-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathopasm.py
More file actions
executable file
·2297 lines (1993 loc) · 94.8 KB
/
opasm.py
File metadata and controls
executable file
·2297 lines (1993 loc) · 94.8 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env python3
"""
Opasm Assembly REPL using Capstone and Unicorn engines
Supports multiple architectures, register manipulation, state management, and more.
"""
import sys
import json
import platform
from typing import Dict, List
from dataclasses import dataclass, asdict
from pathlib import Path
try:
from unicorn import *
from unicorn.x86_const import *
from unicorn.arm_const import *
from unicorn.arm64_const import *
from unicorn.mips_const import *
from unicorn.ppc_const import *
import capstone
from capstone import *
import keystone
from keystone import *
from rich.console import Console
from rich.table import Table
from rich.panel import Panel
from rich.text import Text
from rich.columns import Columns
from rich.syntax import Syntax
from rich import box
from prompt_toolkit import prompt
from prompt_toolkit.completion import WordCompleter
from prompt_toolkit.history import InMemoryHistory
from prompt_toolkit.shortcuts import confirm
except ImportError as e:
print(f"Missing required dependency: {e}")
print("Please install requirements: pip install -r requirements.txt")
sys.exit(1)
ARCH_X86 = 'x86'
ARCH_X64 = 'x64'
ARCH_ARM = 'arm'
ARCH_ARM64 = 'arm64'
ARCH_MIPS32 = 'mips32'
ARCH_MIPS64 = 'mips64'
ARCH_PPC32 = 'ppc32'
ARCH_PPC64 = 'ppc64'
# Initialize rich console
console = Console()
def print_info(message: str):
"""Print informational messages in green"""
console.print(f"[green]{message}[/green]")
def print_error(message: str):
"""Print error messages in red"""
console.print(f"[red]error: {message}[/red]")
def print_warning(message: str):
"""Print warning messages in yellow"""
console.print(f"[yellow]warning: {message}[/yellow]")
@dataclass
class ArchConfig:
"""Configuration for different architectures"""
name: str
uc_arch: int
uc_mode: int
cs_arch: int
cs_mode: int
ks_arch: int
ks_mode: int
is_little_endian: bool
registers: Dict[str, int]
instruction_pointer_register: int
stack_pointer_register: int
stack_base: int
code_base: int
data_base: int
word_size: int
class AssemblyREPL:
"""Main Assembly REPL class"""
# Architecture configurations
ARCHITECTURES = {
ARCH_X86: ArchConfig(
name=ARCH_X86,
uc_arch=UC_ARCH_X86,
uc_mode=UC_MODE_32,
cs_arch=CS_ARCH_X86,
cs_mode=CS_MODE_32,
ks_arch=KS_ARCH_X86,
ks_mode=KS_MODE_32,
is_little_endian=True,
registers={
'eax': UC_X86_REG_EAX, 'ebx': UC_X86_REG_EBX, 'ecx': UC_X86_REG_ECX, 'edx': UC_X86_REG_EDX,
'esi': UC_X86_REG_ESI, 'edi': UC_X86_REG_EDI, 'esp': UC_X86_REG_ESP, 'ebp': UC_X86_REG_EBP,
'eip': UC_X86_REG_EIP, 'eflags': UC_X86_REG_EFLAGS,
'ax': UC_X86_REG_AX, 'bx': UC_X86_REG_BX, 'cx': UC_X86_REG_CX, 'dx': UC_X86_REG_DX,
'al': UC_X86_REG_AL, 'bl': UC_X86_REG_BL, 'cl': UC_X86_REG_CL, 'dl': UC_X86_REG_DL,
'ah': UC_X86_REG_AH, 'bh': UC_X86_REG_BH, 'ch': UC_X86_REG_CH, 'dh': UC_X86_REG_DH,
},
instruction_pointer_register=UC_X86_REG_EIP,
stack_pointer_register=UC_X86_REG_ESP,
stack_base=0x7fff0000,
code_base=0x400000,
data_base=0x10000000,
word_size=4
),
ARCH_X64: ArchConfig(
name=ARCH_X64,
uc_arch=UC_ARCH_X86,
uc_mode=UC_MODE_64,
cs_arch=CS_ARCH_X86,
cs_mode=CS_MODE_64,
ks_arch=KS_ARCH_X86,
ks_mode=KS_MODE_64,
is_little_endian=True,
registers={
'rax': UC_X86_REG_RAX, 'rbx': UC_X86_REG_RBX, 'rcx': UC_X86_REG_RCX, 'rdx': UC_X86_REG_RDX,
'rsi': UC_X86_REG_RSI, 'rdi': UC_X86_REG_RDI, 'rsp': UC_X86_REG_RSP, 'rbp': UC_X86_REG_RBP,
'rip': UC_X86_REG_RIP, 'rflags': UC_X86_REG_EFLAGS,
'r8': UC_X86_REG_R8, 'r9': UC_X86_REG_R9, 'r10': UC_X86_REG_R10, 'r11': UC_X86_REG_R11,
'r12': UC_X86_REG_R12, 'r13': UC_X86_REG_R13, 'r14': UC_X86_REG_R14, 'r15': UC_X86_REG_R15,
'eax': UC_X86_REG_EAX, 'ebx': UC_X86_REG_EBX, 'ecx': UC_X86_REG_ECX, 'edx': UC_X86_REG_EDX,
},
instruction_pointer_register=UC_X86_REG_RIP,
stack_pointer_register=UC_X86_REG_RSP,
stack_base=0x7fff00000000,
code_base=0x400000,
data_base=0x10000000,
word_size=8
),
ARCH_ARM: ArchConfig(
name=ARCH_ARM,
uc_arch=UC_ARCH_ARM,
uc_mode=UC_MODE_ARM,
cs_arch=CS_ARCH_ARM,
cs_mode=CS_MODE_ARM,
ks_arch=KS_ARCH_ARM,
ks_mode=KS_MODE_ARM,
is_little_endian=True,
registers={
'r0': UC_ARM_REG_R0, 'r1': UC_ARM_REG_R1, 'r2': UC_ARM_REG_R2, 'r3': UC_ARM_REG_R3,
'r4': UC_ARM_REG_R4, 'r5': UC_ARM_REG_R5, 'r6': UC_ARM_REG_R6, 'r7': UC_ARM_REG_R7,
'r8': UC_ARM_REG_R8, 'r9': UC_ARM_REG_R9, 'r10': UC_ARM_REG_R10, 'r11': UC_ARM_REG_R11,
'r12': UC_ARM_REG_R12, 'sp': UC_ARM_REG_SP, 'lr': UC_ARM_REG_LR, 'pc': UC_ARM_REG_PC,
'cpsr': UC_ARM_REG_CPSR,
},
instruction_pointer_register=UC_ARM_REG_PC,
stack_pointer_register=UC_ARM_REG_SP,
stack_base=0x7fff0000,
code_base=0x10000,
data_base=0x20000000,
word_size=4
),
ARCH_ARM64: ArchConfig(
name=ARCH_ARM64,
uc_arch=UC_ARCH_ARM64,
uc_mode=UC_MODE_ARM,
cs_arch=CS_ARCH_ARM64,
cs_mode=CS_MODE_ARM,
ks_arch=KS_ARCH_ARM64,
ks_mode=KS_MODE_LITTLE_ENDIAN,
is_little_endian=True,
registers={
'x0': UC_ARM64_REG_X0, 'x1': UC_ARM64_REG_X1, 'x2': UC_ARM64_REG_X2, 'x3': UC_ARM64_REG_X3,
'x4': UC_ARM64_REG_X4, 'x5': UC_ARM64_REG_X5, 'x6': UC_ARM64_REG_X6, 'x7': UC_ARM64_REG_X7,
'x8': UC_ARM64_REG_X8, 'x9': UC_ARM64_REG_X9, 'x10': UC_ARM64_REG_X10, 'x11': UC_ARM64_REG_X11,
'x12': UC_ARM64_REG_X12, 'x13': UC_ARM64_REG_X13, 'x14': UC_ARM64_REG_X14, 'x15': UC_ARM64_REG_X15,
'x16': UC_ARM64_REG_X16, 'x17': UC_ARM64_REG_X17, 'x18': UC_ARM64_REG_X18, 'x19': UC_ARM64_REG_X19,
'x20': UC_ARM64_REG_X20, 'x21': UC_ARM64_REG_X21, 'x22': UC_ARM64_REG_X22, 'x23': UC_ARM64_REG_X23,
'x24': UC_ARM64_REG_X24, 'x25': UC_ARM64_REG_X25, 'x26': UC_ARM64_REG_X26, 'x27': UC_ARM64_REG_X27,
'x28': UC_ARM64_REG_X28, 'x29': UC_ARM64_REG_X29, 'x30': UC_ARM64_REG_X30, 'sp': UC_ARM64_REG_SP,
'pc': UC_ARM64_REG_PC, 'nzcv': UC_ARM64_REG_NZCV,
},
instruction_pointer_register=UC_ARM64_REG_PC,
stack_pointer_register=UC_ARM64_REG_SP,
stack_base=0x7fff00000000,
code_base=0x400000,
data_base=0x10000000,
word_size=8
),
ARCH_MIPS32: ArchConfig(
name=ARCH_MIPS32,
uc_arch=UC_ARCH_MIPS,
uc_mode=UC_MODE_MIPS32,
cs_arch=CS_ARCH_MIPS,
cs_mode=CS_MODE_MIPS32,
ks_arch=KS_ARCH_MIPS,
ks_mode=KS_MODE_MIPS32,
is_little_endian=False,
registers={
'CP0_STATUS': UC_MIPS_REG_CP0_STATUS,
'r0 (zero)': UC_MIPS_REG_ZERO,
'r1 (at)': UC_MIPS_REG_AT,
'r2 (v0)': UC_MIPS_REG_V0,
'r3 (v1)': UC_MIPS_REG_V1,
'r4 (a0)': UC_MIPS_REG_A0,
'r5 (a1)': UC_MIPS_REG_A1,
'r6 (a2)': UC_MIPS_REG_A2,
'r7 (a3)': UC_MIPS_REG_A3,
'r8 (t0)': UC_MIPS_REG_T0,
'r9 (t1)': UC_MIPS_REG_T1,
'r10 (t2)': UC_MIPS_REG_T2,
'r11 (t3)': UC_MIPS_REG_T3,
'r12 (t4)': UC_MIPS_REG_T4,
'r13 (t5)': UC_MIPS_REG_T5,
'r14 (t6)': UC_MIPS_REG_T6,
'r15 (t7)': UC_MIPS_REG_T7,
'r16 (s0)': UC_MIPS_REG_S0,
'r17 (s1)': UC_MIPS_REG_S1,
'r18 (s2)': UC_MIPS_REG_S2,
'r19 (s3)': UC_MIPS_REG_S3,
'r20 (s4)': UC_MIPS_REG_S4,
'r21 (s5)': UC_MIPS_REG_S5,
'r22 (s6)': UC_MIPS_REG_S6,
'r23 (s7)': UC_MIPS_REG_S7,
'r24 (t8)': UC_MIPS_REG_T8,
'r25 (t9)': UC_MIPS_REG_T9,
'r26 (k0)': UC_MIPS_REG_K0,
'r27 (k1)': UC_MIPS_REG_K1,
'r28 (gp)': UC_MIPS_REG_GP,
'r29 (sp)': UC_MIPS_REG_SP,
'r30 (fp)': UC_MIPS_REG_FP,
'r31 (ra)': UC_MIPS_REG_RA,
'pc': UC_MIPS_REG_PC,
'sp': UC_MIPS_REG_SP,
},
instruction_pointer_register=UC_MIPS_REG_PC,
stack_pointer_register=UC_MIPS_REG_SP,
stack_base=0x7fff0000,
code_base=0x400000,
data_base=0x10000000,
word_size=4
),
ARCH_MIPS64: ArchConfig(
name=ARCH_MIPS64,
uc_arch=UC_ARCH_MIPS,
uc_mode=UC_MODE_MIPS64,
cs_arch=CS_ARCH_MIPS,
cs_mode=CS_MODE_MIPS64,
ks_arch=KS_ARCH_MIPS,
ks_mode=KS_MODE_MIPS64,
is_little_endian=False,
registers={
'CP0_STATUS': UC_MIPS_REG_CP0_STATUS,
'r0 (zero)': UC_MIPS_REG_ZERO,
'r1 (at)': UC_MIPS_REG_AT,
'r2 (v0)': UC_MIPS_REG_V0,
'r3 (v1)': UC_MIPS_REG_V1,
'r4 (a0)': UC_MIPS_REG_A0,
'r5 (a1)': UC_MIPS_REG_A1,
'r6 (a2)': UC_MIPS_REG_A2,
'r7 (a3)': UC_MIPS_REG_A3,
'r8 (t0)': UC_MIPS_REG_T0,
'r9 (t1)': UC_MIPS_REG_T1,
'r10 (t2)': UC_MIPS_REG_T2,
'r11 (t3)': UC_MIPS_REG_T3,
'r12 (t4)': UC_MIPS_REG_T4,
'r13 (t5)': UC_MIPS_REG_T5,
'r14 (t6)': UC_MIPS_REG_T6,
'r15 (t7)': UC_MIPS_REG_T7,
'r16 (s0)': UC_MIPS_REG_S0,
'r17 (s1)': UC_MIPS_REG_S1,
'r18 (s2)': UC_MIPS_REG_S2,
'r19 (s3)': UC_MIPS_REG_S3,
'r20 (s4)': UC_MIPS_REG_S4,
'r21 (s5)': UC_MIPS_REG_S5,
'r22 (s6)': UC_MIPS_REG_S6,
'r23 (s7)': UC_MIPS_REG_S7,
'r24 (t8)': UC_MIPS_REG_T8,
'r25 (t9)': UC_MIPS_REG_T9,
'r26 (k0)': UC_MIPS_REG_K0,
'r27 (k1)': UC_MIPS_REG_K1,
'r28 (gp)': UC_MIPS_REG_GP,
'r29 (sp)': UC_MIPS_REG_SP,
'r30 (fp)': UC_MIPS_REG_FP,
'r31 (ra)': UC_MIPS_REG_RA,
'pc': UC_MIPS_REG_PC,
'sp': UC_MIPS_REG_SP,
},
instruction_pointer_register=UC_MIPS_REG_PC,
stack_pointer_register=UC_MIPS_REG_SP,
stack_base=0x7fff00000000,
code_base=0x400000,
data_base=0x10000000,
word_size=8
),
ARCH_PPC32: ArchConfig(
name=ARCH_PPC32,
uc_arch=UC_ARCH_PPC,
uc_mode=UC_MODE_PPC32,
cs_arch=CS_ARCH_PPC,
cs_mode=CS_MODE_32,
ks_arch=KS_ARCH_PPC,
ks_mode=KS_MODE_PPC32,
is_little_endian=False,
registers = {
"r0": UC_PPC_REG_0,
"r1": UC_PPC_REG_1,
"r2": UC_PPC_REG_2,
"r3": UC_PPC_REG_3,
"r4": UC_PPC_REG_4,
"r5": UC_PPC_REG_5,
"r6": UC_PPC_REG_6,
"r7": UC_PPC_REG_7,
"r8": UC_PPC_REG_8,
"r9": UC_PPC_REG_9,
"r10": UC_PPC_REG_10,
"r11": UC_PPC_REG_11,
"r12": UC_PPC_REG_12,
"r13": UC_PPC_REG_13,
"r14": UC_PPC_REG_14,
"r15": UC_PPC_REG_15,
"r16": UC_PPC_REG_16,
"r17": UC_PPC_REG_17,
"r18": UC_PPC_REG_18,
"r19": UC_PPC_REG_19,
"r20": UC_PPC_REG_20,
"r21": UC_PPC_REG_21,
"r22": UC_PPC_REG_22,
"r23": UC_PPC_REG_23,
"r24": UC_PPC_REG_24,
"r25": UC_PPC_REG_25,
"r26": UC_PPC_REG_26,
"r27": UC_PPC_REG_27,
"r28": UC_PPC_REG_28,
"r29": UC_PPC_REG_29,
"r30": UC_PPC_REG_30,
"r31": UC_PPC_REG_31,
"fpr0": UC_PPC_REG_FPR0,
"fpr1": UC_PPC_REG_FPR1,
"fpr2": UC_PPC_REG_FPR2,
"fpr3": UC_PPC_REG_FPR3,
"fpr4": UC_PPC_REG_FPR4,
"fpr5": UC_PPC_REG_FPR5,
"fpr6": UC_PPC_REG_FPR6,
"fpr7": UC_PPC_REG_FPR7,
"fpr8": UC_PPC_REG_FPR8,
"fpr9": UC_PPC_REG_FPR9,
"fpr10": UC_PPC_REG_FPR10,
"fpr11": UC_PPC_REG_FPR11,
"fpr12": UC_PPC_REG_FPR12,
"fpr13": UC_PPC_REG_FPR13,
"fpr14": UC_PPC_REG_FPR14,
"fpr15": UC_PPC_REG_FPR15,
"fpr16": UC_PPC_REG_FPR16,
"fpr17": UC_PPC_REG_FPR17,
"fpr18": UC_PPC_REG_FPR18,
"fpr19": UC_PPC_REG_FPR19,
"fpr20": UC_PPC_REG_FPR20,
"fpr21": UC_PPC_REG_FPR21,
"fpr22": UC_PPC_REG_FPR22,
"fpr23": UC_PPC_REG_FPR23,
"fpr24": UC_PPC_REG_FPR24,
"fpr25": UC_PPC_REG_FPR25,
"fpr26": UC_PPC_REG_FPR26,
"fpr27": UC_PPC_REG_FPR27,
"fpr28": UC_PPC_REG_FPR28,
"fpr29": UC_PPC_REG_FPR29,
"fpr30": UC_PPC_REG_FPR30,
"fpr31": UC_PPC_REG_FPR31,
"pc": UC_PPC_REG_PC,
"lr": UC_PPC_REG_LR,
"ctr": UC_PPC_REG_CTR,
"xer": UC_PPC_REG_XER,
"cr": UC_PPC_REG_CR,
},
instruction_pointer_register=UC_PPC_REG_PC,
stack_pointer_register=UC_PPC_REG_1,
stack_base=0x7fff0000,
code_base=0x10000000,
data_base=0x20000000,
word_size=4
),
ARCH_PPC64: ArchConfig(
name=ARCH_PPC64,
uc_arch=UC_ARCH_PPC,
uc_mode=UC_MODE_PPC64,
cs_arch=CS_ARCH_PPC,
cs_mode=CS_MODE_64,
ks_arch=KS_ARCH_PPC,
ks_mode=KS_MODE_PPC64,
is_little_endian=False,
registers = {
"r0": UC_PPC_REG_0,
"r1": UC_PPC_REG_1,
"r2": UC_PPC_REG_2,
"r3": UC_PPC_REG_3,
"r4": UC_PPC_REG_4,
"r5": UC_PPC_REG_5,
"r6": UC_PPC_REG_6,
"r7": UC_PPC_REG_7,
"r8": UC_PPC_REG_8,
"r9": UC_PPC_REG_9,
"r10": UC_PPC_REG_10,
"r11": UC_PPC_REG_11,
"r12": UC_PPC_REG_12,
"r13": UC_PPC_REG_13,
"r14": UC_PPC_REG_14,
"r15": UC_PPC_REG_15,
"r16": UC_PPC_REG_16,
"r17": UC_PPC_REG_17,
"r18": UC_PPC_REG_18,
"r19": UC_PPC_REG_19,
"r20": UC_PPC_REG_20,
"r21": UC_PPC_REG_21,
"r22": UC_PPC_REG_22,
"r23": UC_PPC_REG_23,
"r24": UC_PPC_REG_24,
"r25": UC_PPC_REG_25,
"r26": UC_PPC_REG_26,
"r27": UC_PPC_REG_27,
"r28": UC_PPC_REG_28,
"r29": UC_PPC_REG_29,
"r30": UC_PPC_REG_30,
"r31": UC_PPC_REG_31,
"fpr0": UC_PPC_REG_FPR0,
"fpr1": UC_PPC_REG_FPR1,
"fpr2": UC_PPC_REG_FPR2,
"fpr3": UC_PPC_REG_FPR3,
"fpr4": UC_PPC_REG_FPR4,
"fpr5": UC_PPC_REG_FPR5,
"fpr6": UC_PPC_REG_FPR6,
"fpr7": UC_PPC_REG_FPR7,
"fpr8": UC_PPC_REG_FPR8,
"fpr9": UC_PPC_REG_FPR9,
"fpr10": UC_PPC_REG_FPR10,
"fpr11": UC_PPC_REG_FPR11,
"fpr12": UC_PPC_REG_FPR12,
"fpr13": UC_PPC_REG_FPR13,
"fpr14": UC_PPC_REG_FPR14,
"fpr15": UC_PPC_REG_FPR15,
"fpr16": UC_PPC_REG_FPR16,
"fpr17": UC_PPC_REG_FPR17,
"fpr18": UC_PPC_REG_FPR18,
"fpr19": UC_PPC_REG_FPR19,
"fpr20": UC_PPC_REG_FPR20,
"fpr21": UC_PPC_REG_FPR21,
"fpr22": UC_PPC_REG_FPR22,
"fpr23": UC_PPC_REG_FPR23,
"fpr24": UC_PPC_REG_FPR24,
"fpr25": UC_PPC_REG_FPR25,
"fpr26": UC_PPC_REG_FPR26,
"fpr27": UC_PPC_REG_FPR27,
"fpr28": UC_PPC_REG_FPR28,
"fpr29": UC_PPC_REG_FPR29,
"fpr30": UC_PPC_REG_FPR30,
"fpr31": UC_PPC_REG_FPR31,
"pc": UC_PPC_REG_PC,
"lr": UC_PPC_REG_LR,
"ctr": UC_PPC_REG_CTR,
"xer": UC_PPC_REG_XER,
"cr": UC_PPC_REG_CR,
},
instruction_pointer_register=UC_PPC_REG_PC,
stack_pointer_register=UC_PPC_REG_1,
stack_base=0x7fff00000000,
code_base=0x10000000,
data_base=0x20000000,
word_size=8
),
}
def __init__(self):
self.current_arch = self._detect_system_arch()
self.arch_config = self.ARCHITECTURES[self.current_arch]
self.uc = None
self.cs = None
self.code_history = []
self.memory_regions = {}
self.breakpoints = set()
self.history = InMemoryHistory()
self.auto_display = True # Enable automatic register/stack display
self.previous_state = {} # Track previous register/memory state
self.direct_execution = False
self.init_engine()
# Command completions
self.commands = [
'help', 'arch', 'registers', 'reg', 'memory', 'mem', 'regions', 'assemble', 'asm',
'disasm', 'step', 'run', 'reset', 'save', 'load', 'load_asm', 'load_bin',
'dump_asm', 'dump_mem', 'set_reg', 'set_mem', 'breakpoint', 'bp', 'clear_bp',
'list_bp', 'quit', 'exit', 'toggle_display', 'toggle_direct', 'endian',
'?', 'calculate'
]
self._update_completer()
def _update_completer(self):
"""Update the completer with commands, registers, and assembly instructions"""
# Create a custom completer that provides context-aware suggestions
self.completer = self._create_context_completer()
def _create_context_completer(self):
"""Create a context-aware completer"""
from prompt_toolkit.completion import Completer, Completion
class ContextAwareCompleter(Completer):
def __init__(self, repl_instance):
self.repl = repl_instance
def get_completions(self, document, complete_event):
# Get the current line and split into words
text = document.text_before_cursor
words = text.split()
if not words:
# No words yet, show all commands
for cmd in self.repl.commands:
yield Completion(cmd, start_position=0)
return
current_word = words[-1] if not text.endswith(' ') else ''
# Context-aware completion based on the first word (command)
if len(words) == 1 and not text.endswith(' '):
# Still typing the first word - show matching commands
for cmd in self.repl.commands:
if cmd.startswith(current_word.lower()):
yield Completion(cmd, start_position=-len(current_word))
elif len(words) >= 1:
command = words[0].lower()
if command == 'arch' and (len(words) == 1 or (len(words) == 2 and not text.endswith(' '))):
# After 'arch' command, show architecture options
arch_options = list(self.repl.ARCHITECTURES.keys())
for arch in arch_options:
if arch.startswith(current_word.lower()):
yield Completion(arch, start_position=-len(current_word))
elif command == 'endian' and (len(words) == 1 or (len(words) == 2 and not text.endswith(' '))):
# After 'endian' command, show endian options
endian_options = ['little', 'big']
for endian in endian_options:
if endian.startswith(current_word.lower()):
yield Completion(endian, start_position=-len(current_word))
elif command in ['set_reg', 'bp', 'memory', 'mem'] and len(words) == 2 and not text.endswith(' '):
# After register-related commands, show registers
for reg in self.repl.arch_config.registers.keys():
if reg.startswith(current_word.lower()):
yield Completion(reg, start_position=-len(current_word))
elif command in ['load_asm', 'load_bin', 'save', 'load', 'dump_asm', 'dump_mem'] and len(words) == 2 and not text.endswith(' '):
# After file commands, we could show file completions
# For now, just don't show anything specific
pass
else:
# For assembly instructions or unknown contexts, show assembly instructions and registers
assembly_instructions = self.repl._get_assembly_instructions()
all_suggestions = assembly_instructions + list(self.repl.arch_config.registers.keys())
for suggestion in all_suggestions:
if suggestion.startswith(current_word.lower()):
yield Completion(suggestion, start_position=-len(current_word))
return ContextAwareCompleter(self)
def _get_keystone_engine(self):
"""Get the keystone-engine instance for assembly"""
mode = self.arch_config.ks_mode
if self.arch_config.is_little_endian:
mode |= KS_MODE_LITTLE_ENDIAN
else:
mode |= KS_MODE_BIG_ENDIAN
ks = Ks(self.arch_config.ks_arch, mode)
return ks
def _get_capstone_engine(self):
"""Get the capstone-engine instance for disassembly"""
mode = self.arch_config.cs_mode
if self.arch_config.is_little_endian:
mode |= CS_MODE_LITTLE_ENDIAN
else:
mode |= CS_MODE_BIG_ENDIAN
cs = Cs(self.arch_config.cs_arch, mode)
return cs
def _get_unicorn_engine(self):
"""Get the unicorn-engine instance for emulation"""
mode = self.arch_config.uc_mode
if self.arch_config.is_little_endian:
mode |= UC_MODE_LITTLE_ENDIAN
else:
mode |= UC_MODE_BIG_ENDIAN
uc = Uc(self.arch_config.uc_arch, mode)
return uc
def _get_assembly_instructions(self) -> List[str]:
"""Get common assembly instructions for the current architecture"""
if self.current_arch in [ARCH_X86, ARCH_X64]:
return [
# Data movement
'mov', 'movsx', 'movzx', 'lea', 'xchg',
# Arithmetic
'add', 'sub', 'mul', 'imul', 'div', 'idiv', 'inc', 'dec', 'neg',
# Logical
'and', 'or', 'xor', 'not', 'shl', 'shr', 'sal', 'sar', 'rol', 'ror',
# Comparison
'cmp', 'test',
# Control flow
'jmp', 'je', 'jne', 'jz', 'jnz', 'jg', 'jge', 'jl', 'jle', 'ja', 'jae', 'jb', 'jbe',
'call', 'ret', 'int', 'iret',
# Stack operations
'push', 'pop', 'pushf', 'popf',
# String operations
'movs', 'stos', 'lods', 'scas', 'cmps',
# Other
'nop', 'hlt', 'cld', 'std', 'cli', 'sti',
]
elif self.current_arch == ARCH_ARM:
return [
# Data movement
'mov', 'mvn', 'ldr', 'str', 'ldm', 'stm',
# Arithmetic
'add', 'sub', 'mul', 'mla', 'rsb', 'adc', 'sbc', 'rsc',
# Logical
'and', 'orr', 'eor', 'bic', 'lsl', 'lsr', 'asr', 'ror', 'rrx',
# Comparison
'cmp', 'cmn', 'tst', 'teq',
# Control flow
'b', 'bl', 'bx', 'blx', 'beq', 'bne', 'bcs', 'bcc', 'bmi', 'bpl',
'bvs', 'bvc', 'bhi', 'bls', 'bge', 'blt', 'bgt', 'ble',
# Other
'nop', 'swi', 'mrs', 'msr',
]
elif self.current_arch == ARCH_ARM64:
return [
# Data movement
'mov', 'mvn', 'ldr', 'str', 'ldp', 'stp',
# Arithmetic
'add', 'sub', 'mul', 'madd', 'msub', 'adc', 'sbc', 'neg',
# Logical
'and', 'orr', 'eor', 'bic', 'lsl', 'lsr', 'asr', 'ror',
# Comparison
'cmp', 'cmn', 'tst',
# Control flow
'b', 'bl', 'br', 'blr', 'ret', 'b.eq', 'b.ne', 'b.cs', 'b.cc',
'b.mi', 'b.pl', 'b.vs', 'b.vc', 'b.hi', 'b.ls', 'b.ge', 'b.lt',
'b.gt', 'b.le',
# Other
'nop', 'svc', 'mrs', 'msr',
]
elif self.current_arch in [ARCH_MIPS32, ARCH_MIPS64]:
return [
# Data movement
'move', 'li', 'la',
# Load/Store
'lw', 'lh', 'lb', 'sw', 'sh', 'sb', 'lui',
# Arithmetic
'add', 'addu', 'addi', 'addiu', 'sub', 'subu',
'mul', 'mult', 'multu', 'div', 'divu',
# Logical
'and', 'andi', 'or', 'ori', 'xor', 'xori', 'nor',
'sll', 'srl', 'sra', 'sllv', 'srlv', 'srav',
# Comparison
'slt', 'slti', 'sltu', 'sltiu',
# Control flow
'j', 'jal', 'jr', 'jalr',
'beq', 'bne', 'bgtz', 'bltz', 'bgez', 'blez',
# Other
'nop', 'syscall', 'break',
]
elif self.current_arch in [ARCH_PPC32, ARCH_PPC64]:
return [
# Data movement
'li', 'lis', 'la', 'mr',
# Load/Store
'lwz', 'lwzu', 'lwzx', 'lhz', 'lha', 'lbz', 'stw', 'stwu', 'stwx', 'sth', 'stb',
'ld', 'ldu', 'ldx', 'std', 'stdu', 'stdx',
# Arithmetic
'add', 'addi', 'addis', 'subf', 'subfic', 'mulld', 'mullw', 'divd', 'divw',
# Logical
'and', 'andi.', 'andis.', 'or', 'ori', 'oris', 'xor', 'xori', 'xoris',
'sld', 'slw', 'srd', 'srw', 'srad', 'sraw',
# Comparison
'cmpd', 'cmpw', 'cmpi', 'cmpl', 'cmpli',
# Control flow
'b', 'bl', 'bctr', 'bctrl', 'blr', 'beq', 'bne', 'blt', 'bgt', 'ble', 'bge',
# Other
'nop', 'sc', 'sync', 'isync',
]
else:
return []
def _detect_system_arch(self) -> str:
"""Detect the system architecture"""
machine = platform.machine().lower()
if machine in ['x86_64', 'amd64']:
return ARCH_X64
elif machine in ['i386', 'i686']:
return ARCH_X86
elif machine.startswith('arm') and '64' in machine:
return ARCH_ARM64
elif machine.startswith('arm'):
return ARCH_ARM
else:
return ARCH_X64 # Default fallback
def init_engine(self):
"""Initialize Unicorn and Capstone engines"""
try:
# Initialize Unicorn engine
self.uc = self._get_unicorn_engine()
# Initialize Capstone engine
self.cs = self._get_capstone_engine()
# Initialize Keystone engine
self.ks = self._get_keystone_engine()
# Map memory regions
self._map_memory_regions()
# Initialize stack and instruction pointers
self._init_registers()
print_info(f"Initialized {self.arch_config.name} architecture")
except Exception as e:
print_error(f"Error initializing engines: {e}")
sys.exit(1)
def _map_memory_regions(self):
"""Map memory regions for code, stack, and data"""
regions = [
('code', self.arch_config.code_base, 0x100000), # 1MB for code
('stack', self.arch_config.stack_base, 0x100000), # 1MB for stack
('data', self.arch_config.data_base, 0x100000), # 1MB for data
]
for name, base, size in regions:
try:
self.uc.mem_map(base, size)
self.memory_regions[name] = (base, size)
except Exception as e:
print_error(f"Error mapping {name} memory: {e}")
def _init_registers(self):
"""Initialize registers with default values"""
try:
# Set stack pointer
self.uc.reg_write(self.arch_config.stack_pointer_register, self.arch_config.stack_base + 0x80000)
# Set instruction pointer
self.uc.reg_write(self.arch_config.instruction_pointer_register, self.arch_config.code_base)
except Exception as e:
print_error(f"Error initializing registers: {e}")
def print_banner(self):
"""Print welcome banner using rich"""
banner_panel = Panel.fit(
"[bold cyan]Opasm Assembly REPL v1.0[/bold cyan]\n"
"[dim]Powered by Capstone & Unicorn[/dim]",
border_style="cyan",
padding=(1, 2)
)
console.print(banner_panel)
console.print(f"\n[yellow]Current Architecture: {self.arch_config.name.upper()}[/yellow]")
console.print("[dim]Type assembly instructions directly or 'help' for commands, 'quit' to exit[/dim]")
def print_help(self):
"""Print help information using rich"""
help_panel = Panel(
"""[bold cyan]Available Commands:[/bold cyan]
[bold green]Architecture & Setup:[/bold green]
arch <name> - Show current arch or switch to: x86, x64, arm, arm64, mips, mips64, ppc32, ppc64
endian <type> - Set endianness to 'little' or 'big' (if supported)
reset - Reset CPU state and clear memory
[bold green]Assembly & Execution:[/bold green]
asm <instruction> - Assemble and execute instruction
step - Execute next instruction
run <count> - Run multiple instructions (default: 10)
toggle_direct - Toggle direct execution mode (bypass memory loading)
[bold green]State Inspection:[/bold green]
registers, reg - Show all registers
memory <addr> <size> - Show memory contents (hex format)
disasm <addr> <count> - Disassemble instructions at address
[bold green]State Modification:[/bold green]
set_reg <reg> <val> - Set register value (hex or decimal)
set_mem <addr> <val> - Set memory value
[bold green]Debugging:[/bold green]
bp <addr> - Set breakpoint at address
clear_bp <addr> - Clear breakpoint
list_bp - List all breakpoints
[bold green]File Operations:[/bold green]
save <file> - Save current state to file
load <file> - Load state from file
load_asm <file> <addr> - Load and assemble assembly file into memory
load_bin <file> <addr> - Load binary file into memory
dump_asm <file> - Dump assembly history to file
dump_mem <file> <addr> <size> - Dump memory region to file
[bold green]Calculator:[/bold green]
? <expression> - WinDbg-style calculator with register dereferencing
calculate <expression> - Alternative to ? command
Supports +, -, *, /, &, |, ^, ~, <<, >>, parentheses
Use $register to reference register values
[bold green]Display & Settings:[/bold green]
toggle_display - Toggle automatic register/stack display
toggle_direct - Toggle direct execution mode
[bold green]General:[/bold green]
help - Show this help
quit, exit - Exit the REPL
[bold yellow]Execution Modes:[/bold yellow]
Normal Mode (default): Instructions are loaded into memory before execution
Direct Mode: Instructions execute without loading into memory first
Use 'toggle_direct' to switch between modes
[bold yellow]Register Dereferencing:[/bold yellow]
Use $ to reference register values:
memory $rip - Show memory at RIP address
set_mem $rsp 0x1234 - Set memory at RSP address
bp $rax - Set breakpoint at RAX value
[bold yellow]Examples:[/bold yellow]
mov eax, 0x1234
set_reg eax 0x5678
memory 0x400000 64
memory $rip - Show memory at current instruction pointer
bp $rax - Set breakpoint at RAX value
toggle_direct - Switch to direct execution mode""",
title="Help",
border_style="blue",
padding=(1, 2)
)
console.print(help_panel)
def show_registers(self, vertical_compact: bool = False, horizontal_compact: bool = False, highlight_changes: set = None):
"""Display current register values using rich table"""
if highlight_changes is None:
highlight_changes = set()
if vertical_compact:
# Compact display for auto-display mode
table = Table(title=f"Registers ({self.arch_config.name.upper()})", box=box.ROUNDED, show_header=False, padding=0)
table.add_column("", style="cyan", min_width=8)
table.add_column("", style="yellow", min_width=12)
table.add_column("", style="cyan", min_width=8)
table.add_column("", style="yellow", min_width=12)
table.add_column("", style="cyan", min_width=8)
table.add_column("", style="yellow", min_width=12)
reg_data = []
for reg_name, reg_id in self.arch_config.registers.items():
try:
value = self.uc.reg_read(reg_id)
hex_val = f"0x{value:0{self.arch_config.word_size*2}x}"
# Apply bold formatting if register changed
if reg_name in highlight_changes:
reg_name_display = f"[bold]{reg_name.upper()}[/bold]"
hex_val_display = f"[bold]{hex_val}[/bold]"
else:
reg_name_display = reg_name.upper()
hex_val_display = hex_val
reg_data.append([reg_name_display, hex_val_display])
except:
reg_data.append([reg_name.upper(), "N/A"])
# Split into 3 columns for compact display
third = len(reg_data) // 3
col1 = reg_data[:third]
col2 = reg_data[third:third*2]
col3 = reg_data[third*2:]
for i in range(max(len(col1), len(col2), len(col3))):
c1 = col1[i] if i < len(col1) else ["", ""]
c2 = col2[i] if i < len(col2) else ["", ""]
c3 = col3[i] if i < len(col3) else ["", ""]
table.add_row(c1[0], c1[1], c2[0], c2[1], c3[0], c3[1])
else:
# Full display for manual register command
table = Table(title=f"Registers ({self.arch_config.name.upper()})", box=box.ROUNDED)
table.add_column("Register", style="cyan", min_width=10)
table.add_column("Hex Value", style="yellow", min_width=18)
table.add_column("Decimal", style="green", min_width=15)
table.add_column("Register", style="cyan", min_width=10)
table.add_column("Hex Value", style="yellow", min_width=18)
table.add_column("Decimal", style="green", min_width=15)
reg_data = []
for reg_name, reg_id in self.arch_config.registers.items():
try:
value = self.uc.reg_read(reg_id)
hex_val = f"0x{value:0{self.arch_config.word_size*2}x}"
# Apply bold formatting if register changed
if reg_name in highlight_changes:
reg_name_display = f"[bold]{reg_name.upper()}[/bold]"
hex_val_display = f"[bold]{hex_val}[/bold]"
decimal_display = f"[bold]{str(value)}[/bold]"
else:
reg_name_display = reg_name.upper()
hex_val_display = hex_val
decimal_display = str(value)
reg_data.append([reg_name_display, hex_val_display, decimal_display])
except:
reg_data.append([reg_name.upper(), "N/A", "N/A"])
# Split into columns for better display
mid = len(reg_data) // 2
left_col = reg_data[:mid]
right_col = reg_data[mid:]
for i in range(max(len(left_col), len(right_col))):
left = left_col[i] if i < len(left_col) else ["", "", ""]
right = right_col[i] if i < len(right_col) else ["", "", ""]
table.add_row(left[0], left[1], left[2], right[0], right[1], right[2])
# Show flags if not in vertical_compact mode
if not vertical_compact:
# Check terminal width to decide layout
width, height = self._check_screen_size()
# If terminal is wide enough (120+ columns), show flags side by side
if width >= 120:
# Get flags table separately and display side by side
flags_table = self._get_flags_table()
if flags_table:
# Use Columns to display registers and flags side by side
console.print(Columns([table, flags_table]))
return # Don't print the registers table again
# Default behavior: show flags below registers
console.print(table)
self.show_flags()
return
# For compact mode, just show the registers table
console.print(table)
def _get_flags_info(self):
"""Get flag register name and flag definitions for the current architecture"""
if self.current_arch in [ARCH_X86, ARCH_X64]:
flag_reg_name = 'eflags' if self.current_arch == ARCH_X86 else 'rflags'
flags = {
'CF': 0,
'PF': 2,
'AF': 4,
'ZF': 6,
'SF': 7,
'TF': 8,
'IF': 9,
'DF': 10,
'OF': 11,
'NT': 14,
'MD': 15,
'RF': 16,
'VM': 17,
'AC': 18,
'VIF': 19,
'VIP': 20,
'ID': 21
}
return flag_reg_name, flags
elif self.current_arch in [ARCH_ARM, ARCH_ARM64]:
flag_reg_name = 'cpsr' if self.current_arch == ARCH_ARM else 'nzcv'
flags = {
'N': 31,
'Z': 30,
'C': 29,
'V': 28
}
return flag_reg_name, flags
elif self.current_arch in [ARCH_MIPS32, ARCH_MIPS64]:
return 'CP0_STATUS', {
'CU0': 28,
'CU1': 29,
'CU2': 30,
'CU3': 31,
'BEV': 22,
'ITS': 21,
'ERL': 2,
'EXL': 1,
'IE': 0
}
elif self.current_arch in [ARCH_PPC32, ARCH_PPC64]:
return 'cr', {
'SO': 31,
'EQ': 30,
'GT': 29,