-
Notifications
You must be signed in to change notification settings - Fork 2
/
arch.html
executable file
·3265 lines (2931 loc) · 142 KB
/
arch.html
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
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, minimum-scale=1" />
<meta name="generator" content="pdoc 0.10.0" />
<title>pandare.arch API documentation</title>
<meta name="description" content="This module contains architecture-specific code …" />
<link rel="preload stylesheet" as="style" href="https://cdnjs.cloudflare.com/ajax/libs/10up-sanitize.css/11.0.1/sanitize.min.css" integrity="sha256-PK9q560IAAa6WVRRh76LtCaI8pjTJ2z11v0miyNNjrs=" crossorigin>
<link rel="preload stylesheet" as="style" href="https://cdnjs.cloudflare.com/ajax/libs/10up-sanitize.css/11.0.1/typography.min.css" integrity="sha256-7l/o7C8jubJiy74VsKTidCy1yBkRtiUGbVkYBylBqUg=" crossorigin>
<link rel="stylesheet preload" as="style" href="https://cdnjs.cloudflare.com/ajax/libs/highlight.js/10.1.1/styles/github.min.css" crossorigin>
<style>:root{--highlight-color:#fe9}.flex{display:flex !important}body{line-height:1.5em}#content{padding:20px}#sidebar{padding:30px;overflow:hidden}#sidebar > *:last-child{margin-bottom:2cm}#lunr-search{width:100%;font-size:1em;padding:6px 9px 5px 9px;border:1px solid silver}.http-server-breadcrumbs{font-size:130%;margin:0 0 15px 0}#footer{font-size:.75em;padding:5px 30px;border-top:1px solid #ddd;text-align:right}#footer p{margin:0 0 0 1em;display:inline-block}#footer p:last-child{margin-right:30px}h1,h2,h3,h4,h5{font-weight:300}h1{font-size:2.5em;line-height:1.1em}h2{font-size:1.75em;margin:1em 0 .50em 0}h3{font-size:1.4em;margin:25px 0 10px 0}h4{margin:0;font-size:105%}h1:target,h2:target,h3:target,h4:target,h5:target,h6:target{background:var(--highlight-color);padding:.2em 0}a{color:#058;text-decoration:none;transition:color .3s ease-in-out}a:hover{color:#e82}.title code{font-weight:bold}h2[id^="header-"]{margin-top:2em}.ident{color:#900}pre code{background:#f8f8f8;font-size:.8em;line-height:1.4em}code{background:#f2f2f1;padding:1px 4px;overflow-wrap:break-word}h1 code{background:transparent}pre{background:#f8f8f8;border:0;border-top:1px solid #ccc;border-bottom:1px solid #ccc;margin:1em 0;padding:1ex}#http-server-module-list{display:flex;flex-flow:column}#http-server-module-list div{display:flex}#http-server-module-list dt{min-width:10%}#http-server-module-list p{margin-top:0}.toc ul,#index{list-style-type:none;margin:0;padding:0}#index code{background:transparent}#index h3{border-bottom:1px solid #ddd}#index ul{padding:0}#index h4{margin-top:.6em;font-weight:bold}@media (min-width:200ex){#index .two-column{column-count:2}}@media (min-width:300ex){#index .two-column{column-count:3}}dl{margin-bottom:2em}dl dl:last-child{margin-bottom:4em}dd{margin:0 0 1em 3em}#header-classes + dl > dd{margin-bottom:3em}dd dd{margin-left:2em}dd p{margin:10px 0}.name{background:#eee;font-weight:bold;font-size:.85em;padding:5px 10px;display:inline-block;min-width:40%}.name:hover{background:#e0e0e0}dt:target .name{background:var(--highlight-color)}.name > span:first-child{white-space:nowrap}.name.class > span:nth-child(2){margin-left:.4em}.inherited{color:#999;border-left:5px solid #eee;padding-left:1em}.inheritance em{font-style:normal;font-weight:bold}.desc h2{font-weight:400;font-size:1.25em}.desc h3{font-size:1em}.desc dt code{background:inherit}.source summary,.git-link-div{color:#666;text-align:right;font-weight:400;font-size:.8em;text-transform:uppercase}.source summary > *{white-space:nowrap;cursor:pointer}.git-link{color:inherit;margin-left:1em}.source pre{max-height:500px;overflow:auto;margin:0}.source pre code{font-size:12px;overflow:visible}.hlist{list-style:none}.hlist li{display:inline}.hlist li:after{content:',\2002'}.hlist li:last-child:after{content:none}.hlist .hlist{display:inline;padding-left:1em}img{max-width:100%}td{padding:0 .5em}.admonition{padding:.1em .5em;margin-bottom:1em}.admonition-title{font-weight:bold}.admonition.note,.admonition.info,.admonition.important{background:#aef}.admonition.todo,.admonition.versionadded,.admonition.tip,.admonition.hint{background:#dfd}.admonition.warning,.admonition.versionchanged,.admonition.deprecated{background:#fd4}.admonition.error,.admonition.danger,.admonition.caution{background:lightpink}</style>
<style media="screen and (min-width: 700px)">@media screen and (min-width:700px){#sidebar{width:30%;height:100vh;overflow:auto;position:sticky;top:0}#content{width:70%;max-width:100ch;padding:3em 4em;border-left:1px solid #ddd}pre code{font-size:1em}.item .name{font-size:1em}main{display:flex;flex-direction:row-reverse;justify-content:flex-end}.toc ul ul,#index ul{padding-left:1.5em}.toc > ul > li{margin-top:.5em}}</style>
<style media="print">@media print{#sidebar h1{page-break-before:always}.source{display:none}}@media print{*{background:transparent !important;color:#000 !important;box-shadow:none !important;text-shadow:none !important}a[href]:after{content:" (" attr(href) ")";font-size:90%}a[href][title]:after{content:none}abbr[title]:after{content:" (" attr(title) ")"}.ir a:after,a[href^="javascript:"]:after,a[href^="#"]:after{content:""}pre,blockquote{border:1px solid #999;page-break-inside:avoid}thead{display:table-header-group}tr,img{page-break-inside:avoid}img{max-width:100% !important}@page{margin:0.5cm}p,h2,h3{orphans:3;widows:3}h1,h2,h3,h4,h5,h6{page-break-after:avoid}}</style>
<script defer src="https://cdnjs.cloudflare.com/ajax/libs/highlight.js/10.1.1/highlight.min.js" integrity="sha256-Uv3H6lx7dJmRfRvH8TH6kJD1TSK1aFcwgx+mdg3epi8=" crossorigin></script>
<script>window.addEventListener('DOMContentLoaded', () => hljs.initHighlighting())</script>
<!-- Bootstrap core CSS -->
<!--
<link href="//maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta/css/bootstrap.min.css" rel="stylesheet">
-->
<!-- hand-crafted bootstrap navbar -->
<style>
.bg-light {
background-color: #f8f9fa!important;
}
.navbar {
position: relative;
display: -ms-flexbox;
display: flex;
-ms-flex-wrap: wrap;
flex-wrap: wrap;
-ms-flex-align: center;
align-items: center;
-ms-flex-pack: justify;
justify-content: space-between;
padding: .5rem 1rem;
}
.navbar-expand-lg {
-ms-flex-direction: row;
flex-direction: row;
-ms-flex-wrap: nowrap;
flex-wrap: nowrap;
-ms-flex-pack: start;
justify-content: flex-start;
}
navbar-light .navbar-brand {
color: rgba(0,0,0,.9);
}
.navbar-brand {
display: inline-block;
padding-top: .3125rem;
padding-bottom: .3125rem;
margin-right: 1rem;
font-size: 1.25rem;
line-height: inherit;
white-space: nowrap;
}
.navbar-nav {
display: -ms-flexbox;
display: flex;
-ms-flex-direction: column;
flex-direction: column;
padding-left: 0;
margin-bottom: 0;
list-style: none;
}
.navbar-expand-lg .navbar-nav {
-ms-flex-direction: row;
flex-direction: row;
}
.mr-auto {
margin-right: auto!important;
}
.navbar-expand-lg .navbar-collapse {
display: -ms-flexbox!important;
display: flex!important;
}
.navbar-collapse {
-ms-flex-preferred-size: 100%;
flex-basis: 100%;
-ms-flex-align: center;
align-items: center;
}
.navbar-light .navbar-brand {
color: rgba(0,0,0,.9);
}
.navbar a {
color: #007bff;
text-decoration: none;
background-color: transparent;
-webkit-text-decoration-skip: objects;
}
.navbar-expand-lg .navbar-nav .nav-link {
padding-right: .5rem;
padding-left: .5rem;
}
.navbar .navbar-nav {
margin: 0;
font-family: -apple-system,BlinkMacSystemFont,"Segoe UI",Roboto,"Helvetica Neue",Arial,sans-serif;
font-size: 1rem;
font-weight: 400;
line-height: 1.5;
color: #212529;
}
.navbar-light .navbar-nav .active>.nav-link, .navbar-light .navbar-nav .nav-link.active, .navbar-light .navbar-nav .nav-link.show, .navbar-light .navbar-nav .show>.nav-link {
color: rgba(0,0,0,.9);
}
.navbar-light .navbar-nav .nav-link {
color: rgba(0,0,0,.5);
}
.nav-link {
display: block;
padding: .5rem 1rem;
}
</style>
<style>.homelink{display:block;font-size:2em;font-weight:bold;color:#555;padding-bottom:.5em;border-bottom:1px solid silver}.homelink:hover{color:inherit}.homelink img{max-width:20%;max-height:5em;margin:auto;margin-bottom:.3em}</style>
</head>
<body>
<nav class="navbar navbar-expand-lg navbar-light bg-light">
<a class="navbar-brand" href="/">PANDA.re</a>
<div class="collapse navbar-collapse" id="navbarSupportedContent">
<ul class="navbar-nav mr-auto">
<li class="nav-item">
<a class="nav-link" href="//panda.re/">Home</a>
</li>
<li class="nav-item">
<a class="nav-link" target="_new" href="https://github.com/panda-re/panda">Github</a>
</li>
<li class="nav-item ">
<a class="nav-link" href="//panda.re/blog/">Blog</a>
</li>
<li class="nav-item ">
<a class="nav-link active" href="//docs.panda.re">Python Docs</a>
</li>
<li class="nav-item ">
<a class="nav-link" href="//panda.re/invite.php">Slack</a>
</li>
<!-- No resources tab here because we don't have real bootstrap -->
</div>
</nav>
<main>
<article id="content">
<header>
<h1 class="title">Module <code>pandare.arch</code></h1>
</header>
<section id="section-intro">
<p>This module contains architecture-specific code.</p>
<p>When the <code><a title="pandare.panda" href="panda.html">pandare.panda</a></code> class is initialized, it will automatically
initialize a PandaArch class for the specified architecture in the variable
<code>panda.arch</code>.</p>
<details class="source">
<summary>
<span>Expand source code</span>
</summary>
<pre><code class="python">'''
This module contains architecture-specific code.
When the `pandare.panda` class is initialized, it will automatically
initialize a PandaArch class for the specified architecture in the variable
`panda.arch`.
'''
import binascii
import struct
from .utils import telescope
class PandaArch():
'''
Base class for architecture-specific implementations for PANDA-supported architectures
'''
def __init__(self, panda):
'''
Initialize a PANDA-supported architecture and hold a handle on the PANDA object
'''
self.panda = panda
self.reg_sp = None # Stack pointer register ID if stored in a register
self.reg_pc = None # PC register ID if stored in a register
self.reg_retaddr = None # Register ID that contains return address
self.reg_retval = None # convention: register name that contains return val
self.call_conventions = None # convention: ['reg_for_arg0', 'reg_for_arg1',...]
self.registers = {}
'''
Mapping of register names to indices into the appropriate CPUState array
'''
def _determine_bits(self):
'''
Determine bits and endianness for the panda object's architecture
'''
bits = None
endianness = None # String 'little' or 'big'
if self.panda.arch_name == "i386":
bits = 32
endianness = "little"
elif self.panda.arch_name == "x86_64":
bits = 64
endianness = "little"
elif self.panda.arch_name == "arm":
endianness = "little" # XXX add support for arm BE?
bits = 32
elif self.panda.arch_name == "aarch64":
bits = 64
endianness = "little" # XXX add support for arm BE?
elif self.panda.arch_name == "ppc":
bits = 32
endianness = "big"
elif self.panda.arch_name == "mips":
bits = 32
endianness = "big"
elif self.panda.arch_name == "mipsel":
bits = 32
endianness = "little"
elif self.panda.arch_name == "mips64":
bits = 64
endianness = "big"
elif self.panda.arch_name == "mips64el":
bits = 64
endianness = "little"
assert (bits is not None), f"Missing num_bits logic for {self.panda.arch_name}"
assert (endianness is not None), f"Missing endianness logic for {self.panda.arch_name}"
register_size = int(bits/8)
return bits, endianness, register_size
def get_reg(self, cpu, reg):
'''
Return value in a `reg` which is either a register name or index (e.g., "R0" or 0)
'''
if isinstance(reg, str):
reg = reg.upper()
if reg == 'PC':
return self.get_pc(cpu)
if reg not in self.registers.keys():
raise ValueError(f"Invalid register name {reg}")
else:
reg = self.registers[reg]
return self._get_reg_val(cpu, reg)
def _get_reg_val(self, cpu, idx):
'''
Virtual method. Must be implemented for each architecture to return contents of register specified by idx.
'''
raise NotImplementedError()
def set_reg(self, cpu, reg, val):
'''
Set register `reg` to a value where `reg` is either a register name or index (e.g., "R0" or 0)
'''
if isinstance(reg, str):
reg = reg.upper()
if reg not in self.registers.keys():
raise ValueError(f"Invalid register name {reg}")
else:
reg = self.registers[reg]
elif not isinstance(reg, int):
raise ValueError(f"Can't set register {reg}")
return self._set_reg_val(cpu, reg, val)
def _set_reg_val(self, cpu, idx, val):
'''
Virtual method. Must be implemented for each architecture to return contents of register specified by idx.
'''
raise NotImplementedError()
def get_pc(self, cpu):
'''
Returns the current program counter. Must be overloaded if self.reg_pc is None
'''
if self.reg_pc:
return self.get_reg(cpu, self.reg_pc)
else:
raise RuntimeError(f"get_pc unsupported for {self.panda.arch_name}")
def _get_arg_loc(self, idx, convention):
'''
return the name of the argument [idx] for the given arch with calling [convention]
'''
if self.call_conventions and convention in self.call_conventions:
if idx < len(self.call_conventions[convention]):
return self.call_conventions[convention][idx]
raise NotImplementedError(f"Unsupported argument number {idx}")
raise NotImplementedError(f"Unsupported convention {convention} for {type(self)}")
def _get_ret_val_reg(self, cpu, convention):
if self.reg_retval and convention in self.reg_retval:
return self.reg_retval[convention]
raise NotImplementedError(f"Unsupported get_retval for architecture {type(self)} {convention}")
def set_arg(self, cpu, idx, val, convention='default'):
'''
Set arg [idx] to [val] for given calling convention.
Note for syscalls we define arg[0] as syscall number and then 1-index the actual args
'''
argloc = self._get_arg_loc(idx, convention)
if self._is_stack_loc(argloc):
return self._write_stack(cpu, argloc, val)
else:
return self.set_reg(cpu, argloc, val)
def get_arg(self, cpu, idx, convention='default'):
'''
Return arg [idx] for given calling convention. This only works right as the guest
is calling or has called a function before register values are clobbered.
If arg[idx] should be stack-based, name it stack_0, stack_1... this allows mixed
conventions where some args are in registers and others are on the stack (i.e.,
mips32 syscalls).
When doing a stack-based read, this function may raise a ValueError if the memory
read fails (i.e., paged out, invalid address).
Note for syscalls we define arg[0] as syscall number and then 1-index the actual args
'''
argloc = self._get_arg_loc(idx, convention)
if self._is_stack_loc(argloc):
return self._read_stack(cpu, argloc)
else:
return self.get_reg(cpu, argloc)
@staticmethod
def _is_stack_loc(argloc):
'''
Given a name returned by self._get_arg_loc
check if it's the name of a stack offset
'''
return argloc.startswith("stack_")
def _write_stack(self, cpu, argloc, val):
'''
Given a name like stack_X, calculate where
the X-th value on the stack is, then write val
to that location
May raise a ValueError if the memory write fails
'''
if isinstance(val, int):
# Encode as word-size with endianness
bits, endianness, reg_sz = self._determine_bits()
val = val.to_bytes(reg_sz, byteorder=endianness)
if not isinstance(val, bytes):
raise ValueError("_write_stack needs an int or bytes")
# Stack based - get stack base, calculate offset, then try to read it
assert(self._is_stack_loc(argloc)), f"Can't get stack offset of {argloc}"
stack_idx = int(argloc.split("stack_")[1])
stack_base = self.get_reg(cpu, self.reg_sp)
offset = reg_sz * (stack_idx+1)
self.panda.virtual_memory_write(cpu, stack_base + offset, val)
def _read_stack(self, cpu, argloc):
'''
Given a name like stack_X, calculate where
the X-th value on the stack is, then read it out of
memory and return it.
May raise a ValueError if the memory read fails
'''
# Stack based - get stack base, calculate offset, then try to read it
assert(self._is_stack_loc(argloc)), f"Can't get stack offset of {argloc}"
stack_idx = int(argloc.split("stack_")[1])
stack_base = self.get_reg(cpu, self.reg_sp)
arg_sz = self.panda.bits // 8
offset = arg_sz * (stack_idx+1)
return self.panda.virtual_memory_read(cpu, stack_base + offset, arg_sz, fmt='int')
def set_retval(self, cpu, val, convention='default', failure=False):
'''
Set return val to [val] for given calling convention. This only works
right after a function call has returned, otherwise the register will contain
a different value.
If the given architecture returns failure/success in a second register (i.e., the A3
register for mips), set that according to the failure flag.
Note the failure argument only used by subclasses that overload this function. It's provided
in the signature here so it can be set by a caller without regard for the guest architecture.
'''
reg = self._get_ret_val_reg(cpu, convention)
return self.set_reg(cpu, reg, val)
def get_retval(self, cpu, convention='default'):
'''
Set return val to [val] for given calling convention. This only works
right after a function call has returned, otherwise the register will contain
a different value.
Return value from syscalls is signed
'''
reg = self._get_ret_val_reg(cpu, convention)
rv = self.get_reg(cpu, reg)
if convention == 'syscall':
rv = self.panda.from_unsigned_guest(rv)
return rv
def set_pc(self, cpu, val):
'''
Set the program counter. Must be overloaded if self.reg_pc is None
'''
if self.reg_pc:
return self.set_reg(cpu, self.reg_pc, val)
else:
raise RuntimeError(f"set_pc unsupported for {self.panda.arch_name}")
def dump_regs(self, cpu):
'''
Print (telescoping) each register and its values
'''
print(f"PC: {self.get_pc(cpu):x}")
for (regname, reg) in self.registers.items():
val = self.get_reg(cpu, reg)
print("{}: 0x{:x}".format(regname, val), end="\t")
telescope(self.panda, cpu, val)
def dump_stack(self, cpu, words=8):
'''
Print (telescoping) most recent `words` words on the stack (from stack pointer to stack pointer + `words`*word_size)
'''
base_reg_s = "SP"
base_reg_val = self.get_reg(cpu, self.reg_sp)
if base_reg_val == 0:
print("[WARNING: no stack pointer]")
return
word_size = int(self.panda.bits/8)
_, endianness, _ = self._determine_bits()
for word_idx in range(words):
try:
val_b = self.panda.virtual_memory_read(cpu, base_reg_val+word_idx*word_size, word_size)
val = int.from_bytes(val_b, byteorder=endianness)
print("[{}+0x{:0>2x}] == 0x{:0<8x}]: 0x{:0<8x}".format(base_reg_s, word_idx*word_size, base_reg_val+word_idx*word_size, val), end="\t")
telescope(self.panda, cpu, val)
except ValueError:
print("[{}+0x{:0>2x}] == [memory read error]".format(base_reg_s, word_idx*word_size))
def dump_state(self, cpu):
"""
Print registers and stack
"""
self.dump_regs(cpu)
self.dump_stack(cpu)
def get_args(self, cpu, num, convention='default'):
return [self.get_arg(cpu,i, convention) for i in range(num)]
class ArmArch(PandaArch):
'''
Register names and accessors for ARM
'''
def __init__(self, panda):
PandaArch.__init__(self, panda)
regnames = ["R0", "R1", "R2", "R3", "R4", "R5", "R6", "R7",
"R8", "R9", "R10", "R11", "R12", "SP", "LR", "IP"]
self.registers = {regnames[idx]: idx for idx in range(len(regnames)) }
"""Register array for ARM"""
self.reg_sp = regnames.index("SP")
self.reg_pc = regnames.index("IP")
self.reg_retaddr = regnames.index("LR")
self.reg_sp = regnames.index("SP")
self.reg_retaddr = regnames.index("LR")
self.call_conventions = {"arm32": ["R0", "R1", "R2", "R3"],
"syscall": ["R7", "R0", "R1", "R2", "R3", "R4", "R5"], # EABI
}
self.call_conventions['default'] = self.call_conventions['arm32']
self.call_conventions['linux_kernel'] = self.call_conventions['arm32']
self.reg_retval = {"default": "R0",
"syscall": "R0",
"linux_kernel": "R0"}
self.reg_pc = regnames.index("IP")
def _get_reg_val(self, cpu, reg):
'''
Return an arm register
'''
return cpu.env_ptr.regs[reg]
def _set_reg_val(self, cpu, reg, val):
'''
Set an arm register
'''
cpu.env_ptr.regs[reg] = val
def get_return_value(self, cpu):
'''
.. Deprecated:: use get_retval
'''
return self.get_retval(cpu)
def get_return_address(self, cpu):
'''
Looks up where ret will go
'''
return self.get_reg(cpu, "LR") & 0xFFFF_FFFE
class Aarch64Arch(PandaArch):
'''
Register names and accessors for ARM64 (Aarch64)
'''
def __init__(self, panda):
PandaArch.__init__(self, panda)
regnames = ["X0", "X1", "X2", "X3", "X4", "X5", "X6", "X7",
"XR", "X9", "X10", "X11", "X12", "X13", "X14",
"X15", "IP0", "IP1", "PR", "X19", "X20", "X21",
"X22", "X23", "X24", "X25", "X26", "X27",
"X28", "FP", "LR", "SP"]
self.reg_sp = regnames.index("SP")
self.registers = {regnames[idx]: idx for idx in range(len(regnames)) }
"""Register array for ARM"""
self.reg_sp = regnames.index("SP")
self.reg_retaddr = regnames.index("LR")
self.call_conventions = {"arm64": ["X0", "X1", "X2", "X3", "X4", "X5", "X6", "X7"],
"syscall": ["XR", "X0", "X1", "X2", "X3", "X4", "X5", "X6", "X7"]}
self.call_conventions['default'] = self.call_conventions['arm64']
self.call_conventions['linux_kernel'] = self.call_conventions['arm64']
self.reg_retval = {"default": "X0",
"syscall": "X0",
"linux_kernel": "X0"}
self.arm32 = ArmArch(panda)
def arm32_dec(f, name):
def wrap(*args, **kwargs):
# first check that we have an arg
if len(args) > 0:
# double check that it's a cpustate
cpu = args[0]
if "_cffi_backend" in str(type(cpu)):
# check if we're in arm32 mode
if cpu.env_ptr.aarch64 == 0:
func = getattr(self.arm32, name)
return func(*args, **kwargs)
return f(*args, **kwargs)
return wrap
for attr in dir(self):
if callable(getattr(self, attr)) and not attr.startswith('_'):
setattr(self, attr, arm32_dec(getattr(self, attr), attr))
def get_pc(self, cpu):
'''
Overloaded function to get aarch64 program counter.
Note the PC is not stored in a general purpose register.
'''
return cpu.env_ptr.pc
def set_pc(self, cpu, val):
'''
Overloaded function set AArch64 program counter
'''
cpu.env_ptr.pc = val
def _get_reg_val(self, cpu, reg):
'''
Return an aarch64 register
'''
if reg == 32:
print("WARNING: unsupported get sp for aarch64")
return 0
else:
return cpu.env_ptr.xregs[reg]
def _set_reg_val(self, cpu, reg, val):
'''
Set an aarch64 register
'''
cpu.env_ptr.xregs[reg] = val
def get_return_value(self, cpu):
'''
.. Deprecated:: use get_retval
'''
return self.get_retval(cpu)
def get_return_address(self, cpu):
'''
Looks up where ret will go
'''
return self.get_reg(cpu, "LR")
class MipsArch(PandaArch):
'''
Register names and accessors for 32-bit MIPS
'''
# Registers are:
'''
Register Number Conventional Name Usage
$0 $zero Hard-wired to 0
$1 $at Reserved for pseudo-instructions
$2 - $3 $v0, $v1 Return values from functions
$4 - $7 $a0 - $a3 Arguments to functions - not preserved by subprograms
$8 - $15 $t0 - $t7 Temporary data, not preserved by subprograms
$16 - $23 $s0 - $s7 Saved registers, preserved by subprograms
$24 - $25 $t8 - $t9 More temporary registers, not preserved by subprograms
$26 - $27 $k0 - $k1 Reserved for kernel. Do not use.
$28 $gp Global Area Pointer (base of global data segment)
$29 $sp Stack Pointer
$30 $fp Frame Pointer
$31 $ra Return Address
'''
def __init__(self, panda):
super().__init__(panda)
regnames = ['ZERO', 'AT', 'V0', 'V1', 'A0', 'A1', 'A2', 'A3',
'T0', 'T1', 'T2', 'T3', 'T4', 'T5', 'T6', 'T7',
'S0', 'S1', 'S2', 'S3', 'S4', 'S5', 'S6', 'S7',
'T8', 'T9', 'K0', 'K1', 'GP', 'SP', 'FP', 'RA']
self.reg_sp = regnames.index('SP')
self.reg_retaddr = regnames.index('RA')
# Default syscall/args are for mips o32
self.call_conventions = {"mips": ["A0", "A1", "A2", "A3"],
"syscall": ["V0", "A0", "A1", "A2", "A3", "stack_3", "stack_4", "stack_5", "stack_6"]} # XXX: Note it's not 0-indexed for stack args, I guess the syscall pushes stuff too
self.call_conventions['default'] = self.call_conventions['mips']
self.call_conventions['linux_kernel'] = self.call_conventions['mips']
self.reg_retval = {"default": "V0",
"syscall": 'V0',
"linux_kernel": 'V0'}
# note names must be stored uppercase for get/set reg to work case-insensitively
self.registers = {regnames[idx].upper(): idx for idx in range(len(regnames)) }
self.registers['R30'] = 30
def get_reg(self, cpu, reg):
'''
Overloaded function for a few mips specific registers
'''
if isinstance(reg, str):
env = cpu.env_ptr
reg = reg.upper()
if reg == 'HI':
return env.CP0_EntryHi
elif reg == 'LO':
return env.CP0_EntryLo0
elif reg.startswith('F') and reg[1:].isnumeric():
num = int(reg[1:])
_, endianness, _ = self._determine_bits()
return int.from_bytes(bytes(env.fpus[0].fpr[num]), byteorder=endianness)
elif reg == 'FCCR':
return env.fpus[0].fcr0
elif reg == 'DSPCONTROL':
return env.active_tc.DSPControl
elif reg == 'CP0_STATUS':
return env.CP0_Status
return super().get_reg(cpu, reg)
def get_pc(self, cpu):
'''
Overloaded function to return the MIPS current program counter
'''
return cpu.env_ptr.active_tc.PC
def set_pc(self, cpu, val):
'''
Overloaded function set the MIPS program counter
'''
cpu.env_ptr.active_tc.PC = val
def get_retval(self, cpu, convention='default'):
'''
Overloaded to incorporate error data from A3 register for syscalls.
If A3 is 1 and convention is syscall, *negate* the return value.
This matches behavior of other architecures (where -ERRNO is returned
on error)
'''
flip = 1
if convention == 'syscall' and self.get_reg(cpu, "A3") == 1:
flip = -1
return flip * super().get_retval(cpu)
def _get_reg_val(self, cpu, reg):
'''
Return a mips register
'''
return cpu.env_ptr.active_tc.gpr[reg]
def _set_reg_val(self, cpu, reg, val):
'''
Set a mips register
'''
cpu.env_ptr.active_tc.gpr[reg] = val
def get_return_value(self, cpu, convention='default'):
'''
.. Deprecated:: use get_retval
'''
return self.get_retval(cpu)
def get_call_return(self, cpu):
'''
.. Deprecated:: use get_return_address
'''
return self.get_return_address(cpu)
def get_return_address(self,cpu):
'''
looks up where ret will go
'''
return self.get_reg(cpu, "RA")
def set_retval(self, cpu, val, convention='default', failure=False):
'''
Overloaded function so when convention is syscall, user can control
the A3 register (which indicates syscall success/failure) in addition
to the syscall return value.
When convention == 'syscall', failure = False means A3 will bet set to 0.
Otherwise, it will be set to 1
'''
if convention == 'syscall':
# Set A3 register to indicate syscall success/failure
self.set_reg(cpu, 'a3', failure)
# If caller is trying to indicate error by setting a negative retval
# for a syscall, just make it positive with A3=1
if failure and self.panda.from_unsigned_guest(val) < 0:
val = -1 * self.panda.from_unsigned_guest(val)
return super().set_retval(cpu, val, convention)
class Mips64Arch(MipsArch):
'''
Register names and accessors for MIPS64. Inherits from MipsArch for everything
except the register name and call conventions.
'''
def __init__(self, panda):
super().__init__(panda)
regnames = ["zero", "at", "v0", "v1", "a0", "a1", "a2", "a3",
"a4", "a5", "a6", "a7", "t0", "t1", "t2", "t3",
"s0", "s1", "s2", "s3", "s4", "s5", "s6", "s7",
"t8", "t9", "k0", "k1", "gp", "sp", "s8", "ra"]
self.reg_sp = regnames.index('sp')
self.reg_retaddr = regnames.index("ra")
# Default syscall/args are for mips 64/n32 - note the registers are different than 32
self.call_conventions = {"mips": ["A0", "A1", "A2", "A3"], # XXX Unsure?
"syscall": ["V0", "A0", "A1", "A2", "A3", "A4", "A5"]}
self.call_conventions['default'] = self.call_conventions['mips']
self.call_conventions['linux_kernel'] = self.call_conventions['mips']
self.reg_retval = {"default": "V0",
"syscall": 'V0'}
# note names must be stored uppercase for get/set reg to work case-insensitively
self.registers = {regnames[idx].upper(): idx for idx in range(len(regnames)) }
class PowerPCArch(PandaArch):
'''
Register names and accessors for ppc
'''
def __init__(self, panda):
super().__init__(panda)
regnames = ["r0", "sp", "r2", "r3", "r4", "r5", "r6", "r7", "r8", "r9", "r10", "r11",
"r12", "r13", "r14", "r15", "r16", "r17", "r18", "r19", "r20", "r21", "r22",
"r23", "r24", "r25", "r26", "r27", "r28", "r29", "r30", "r31"]
self.reg_sp = regnames.index('sp')
self.registers = {regnames[idx].upper(): idx for idx in range(len(regnames)) }
self.registers_crf = ["CR0", "CR1", "CR2", "CR3", "CR4", "CR5", "CR6", "CR7"]
def get_pc(self, cpu):
'''
Overloaded function to return the ppc current program counter
'''
return cpu.env_ptr.nip
def set_pc(self, cpu, val):
'''
Overloaded function to set the ppc program counter
'''
cpu.env_ptr.nip = val
def _get_reg_val(self, cpu, reg):
'''
Return a ppc register
'''
return cpu.env_ptr.gpr[reg]
def _set_reg_val(self, cpu, reg, val):
'''
Set an x86_64 register
'''
cpu.env_ptr.gpr[reg] = val
def get_reg(self, cpu, reg):
reg = reg.upper()
env = cpu.env_ptr
if reg == "LR":
return env.lr
elif reg == "CTR":
return env.ctr
elif reg in self.registers_crf:
return env.crf[self.registers_crf.index(reg)]
else:
return super().get_reg(cpu, reg)
def set_reg(self, cpu, reg, val):
reg = reg.upper()
env = cpu.env_ptr
if reg == "LR":
env.lr = val
elif reg == "CTR":
env.ctr = val
elif reg in self.registers_crf:
env.crf[self.registers_crf.index(reg)] = val
else:
super().set_reg(cpu, reg, val)
class X86_64Arch(PandaArch):
'''
Register names and accessors for x86_64
'''
def __init__(self, panda):
super().__init__(panda)
# The only place I could find the R_ names is in tcg/i386/tcg-target.h:50
regnames = ['RAX', 'RCX', 'RDX', 'RBX', 'RSP', 'RBP', 'RSI', 'RDI',
'R8', 'R9', 'R10', 'R11', 'R12', 'R13', 'R14', 'R15']
# XXX Note order is A C D B, because that's how qemu does it
self.call_conventions = {'sysv': ['RDI', 'RSI', 'RDX', 'RCX', 'R8', 'R9'],
'syscall': ['RAX', 'RDI', 'RSI', 'RDX', 'R10', 'R8', 'R9']}
self.call_conventions['default'] = self.call_conventions['sysv']
self.call_conventions['linux_kernel'] = self.call_conventions['sysv']
self.reg_sp = regnames.index('RSP')
self.reg_retval = {'sysv': 'RAX',
'syscall': 'RAX',
'linux_kernel': 'RAX'}
self.reg_retval['default'] = self.reg_retval['sysv']
self.registers = {regnames[idx]: idx for idx in range(len(regnames)) }
# Internal state to support some of the weird x86-64 registers
self.reg_names_general = ['EAX', 'ECX', 'EDX', 'EBX', 'ESP', 'EBP', 'ESI', 'EDI']
self.reg_names_short = ['AX', 'CX', 'DX', 'BX', 'SP', 'BP', 'SI', 'DI']
self.reg_names_byte = ['AL', 'CL', 'DL', 'BL', 'AH', 'CH', 'DH', 'BH']
self.seg_names = ['ES', 'CS', 'SS', 'DS', 'FS', 'GS']
self.reg_names_mmr = ['LDT', 'TR', 'GDT', 'IDT']
def _get_segment_register(self, env, seg_name):
seg_idx = self.seg_names.index(seg_name)
return env.segs[seg_idx].base
def _get_general_purpose_register(self, env, reg_name, mask):
return env.regs[self.reg_names_general.index(reg_name)] & mask
def _set_segment_register(self, env, seg_name, value):
seg_idx = self.seg_names.index(seg_name)
env.segs[seg_idx].base = value
def _set_general_purpose_register(self, env, reg_name, value, mask):
reg_idx = self.reg_names_general.index(reg_name)
env.regs[reg_idx] = (env.regs[reg_idx] & ~mask) | (value & mask)
def get_pc(self, cpu):
'''
Overloaded function to return the x86_64 current program counter
'''
return cpu.env_ptr.eip
def get_retval(self, cpu, convention='default'):
'''
Overloaded to support FreeBSD syscall ABI
In that ABI, if eflags carry bit is set, an error has occured. To standardize
pandare.arch returns across architectures/ABIs, we indicate a failure by returnning
-ERRNO.
'''
error_flip = False
if convention == 'syscall' and self.panda.get_os_family() == 'OS_FREEBSD' and \
self.panda.libpanda.cpu_cc_compute_all(cpu.env_ptr, 1) & 1 == 1:
error_flip = True
return super().get_retval(cpu, convention) * (-1 if error_flip else 1)
def set_pc(self, cpu, val):
'''
Overloaded function to set the x86_64 program counter
'''
cpu.env_ptr.eip = val
def _get_mmr_val(self, cpu, reg):
reg = reg.lower()
sc = getattr(cpu.env_ptr, reg)
return (sc.selector, sc.base, sc.limit, sc.flags)
def _set_mmr_val(self, cpu, reg, val):
reg = reg.lower()
selector, base, limit, flags = val
sc = getattr(cpu.env_ptr, reg)
sc.selector = selector
sc.base = base
sc.limit = limit
sc.flags = flags
def _get_reg_val(self, cpu, reg):
'''
Return an x86_64 register
'''
return cpu.env_ptr.regs[reg]
def _set_reg_val(self, cpu, reg, val):
'''
Set an x86_64 register
'''
cpu.env_ptr.regs[reg] = val
def get_return_value(self, cpu):
'''
.. Deprecated:: use get_retval
'''
return self.get_retval(cpu)
def get_return_address(self, cpu):
'''
looks up where ret will go
'''
esp = self.get_reg(cpu, "RSP")
return self.panda.virtual_memory_read(cpu, esp, 8, fmt='int')
def get_reg(self, cpu, reg):
'''
X86_64 has a bunch of different ways to access registers. We support
the regular names, the 32 and 16 bit varations (e.g., EAX, AX, AL),
segment registers, and D/W/B style accesses to R8-R15
'''
if isinstance(reg, int):
# If reg is an int, it should be an offset into our register array
return self._get_reg_val(cpu, reg)
reg = reg.upper()
env = cpu.env_ptr
if reg in self.reg_names_mmr:
return self._get_mmr_val(cpu, reg)
if reg in self.seg_names:
return self._get_segment_register(env, reg)
elif reg in ['EFLAGS', 'RFLAGS']:
return env.eflags
elif reg in ['RIP', 'PC', 'EIP']:
pc = self.get_pc(cpu) # changes reg to 'IP' and re-calls this
if reg == 'EIP':
pc &= 0xFFFFFFFF
return pc
elif reg.startswith('XMM'):
raw_arr = env.xmm_regs[int(reg[3:].rstrip('HLQX'))]
_, endianness, _ = self._determine_bits()
if reg.endswith('lq'):
value_bytes = raw_arr[0:8] # Lower 64 bits
elif reg.endswith('hq'):
value_bytes = raw_arr[8:16] # Higher 64 bits
elif reg.endswith('hx'):
value_bytes = raw_arr[4:8] # Higher 32 bits of the lower 64 bits
else: