-
Notifications
You must be signed in to change notification settings - Fork 2
/
panda.html
executable file
·12720 lines (11152 loc) · 523 KB
/
panda.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.panda API documentation</title>
<meta name="description" content="This module simply contains the Panda class." />
<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.panda</code></h1>
</header>
<section id="section-intro">
<p>This module simply contains the Panda class.</p>
<details class="source">
<summary>
<span>Expand source code</span>
</summary>
<pre><code class="python">"""
This module simply contains the Panda class.
"""
from sys import version_info, exit
if version_info[0] < 3:
print("Please run with Python 3!")
exit(0)
import socket
import select
import threading
import readline
# XXX: readline is unused but necessary. We need to load python
# readline, to preempt PANDA loading another version. PANDA
# seems to work with python's but not vice-versa. This allows for
# stdio interactions later (e.g., pdb, input()) without segfaults
from os.path import realpath, exists, abspath, isfile, dirname, isdir, join as pjoin
from os import dup, getenv, environ, path
from random import randint
from inspect import signature
from tempfile import NamedTemporaryFile
from time import time
from math import ceil
from inspect import signature
from struct import pack_into
from shlex import quote as shlex_quote, split as shlex_split
from time import sleep
from cffi import FFI
from .utils import progress, warn, make_iso, debug, blocking, GArrayIterator, plugin_list, find_build_dir, rr2_recording, rr2_contains_member
from .taint import TaintQuery
from .panda_expect import Expect
from .asyncthread import AsyncThread
from .qcows_internal import Qcows
from .qemu_logging import QEMU_Log_Manager
from .arch import ArmArch, Aarch64Arch, MipsArch, Mips64Arch, X86Arch, X86_64Arch, PowerPCArch
from .cosi import Cosi
from dataclasses import dataclass
# Might be worth importing and auto-initilizing a PLogReader
# object within Panda for the current architecture?
#from .plog import PLogReader
class Panda():
'''
This is the object used to interact with PANDA. Initializing it creates a virtual machine to interact with.
'''
def __init__(self, arch="i386", mem="128M",
expect_prompt=None, # Regular expression describing the prompt exposed by the guest on a serial console. Used so we know when a running command has finished with its output
serial_kwargs=None,
os_version=None,
qcow=None, # Qcow file to load
os="linux",
generic=None, # Helper: specify a generic qcow to use and set other arguments. Supported values: arm/ppc/x86_64/i386. Will download qcow automatically
raw_monitor=False, # When set, don't specify a -monitor. arg Allows for use of -nographic in args with ctrl-A+C for interactive qemu prompt.
extra_args=None,
catch_exceptions=True, # Should we catch and end_analysis() when python code raises an exception?
libpanda_path=None,
biospath=None,
plugin_path=None):
'''
Construct a new `Panda` object. Note that multiple Panda objects cannot coexist in the same Python instance.
Args:
arch: architecture string (e.g. "i386", "x86_64", "arm", "mips", "mipsel")
generic: specify a generic qcow to use from `pandare.qcows.SUPPORTED_IMAGES` and set all subsequent arguments. Will automatically download qcow if necessary.
mem: size of memory for machine (e.g. "128M", "1G")
expect_prompt: Regular expression describing the prompt exposed by the guest
on a serial console. Used so we know when a running command has finished
with its output.
serial_kwargs: dict of additional arguments to pass to pandare.Expect (see signature of its constructor).
Note that `expect_prompt` is already passed to Expect as "expectation".
If not explicitly given, "unansi" is set to True (simulates a subset of ANSI codes and attempts to
remove command strings repeated by the shell from the shell output).
os_version: analagous to PANDA's -os argument (e.g, linux-32-debian:3.2.0-4-686-pae")
os: type of OS (e.g. "linux")
qcow: path to a qcow file to load
catch_exceptions: Should we catch exceptions raised by python code and end_analysis() and then print a backtrace (Default: True)
raw_monitor: When set, don't specify a -monitor. arg Allows for use of
-nographic in args with ctrl-A+C for interactive qemu prompt. Experts only!
extra_args: extra arguments to pass to PANDA as either a string or an
array. (e.g. "-nographic" or ["-nographic", "-net", "none"])
libpanda_path: path to panda shared object to load
biospath: directory that contains "pc-bios" files
plugin_path: directory that contains panda plugins
Returns:
Panda: the created panda object
'''
self.arch_name = arch
self.mem = mem
self.os = os_version
self.os_type = os
self.qcow = qcow
self.plugins = plugin_list(self)
self.expect_prompt = expect_prompt
self.lambda_cnt = 0
self.__sighandler = None
self.ending = False # True during end_analysis
self.cdrom = None
self.catch_exceptions=catch_exceptions
self.qlog = QEMU_Log_Manager(self)
self.build_dir = None
self.plugin_path = plugin_path
self.serial_unconsumed_data = b''
if isinstance(extra_args, str): # Extra args can be a string or array. Use shlex to preserve quoted substrings
extra_args = shlex_split(extra_args)
elif extra_args is None:
extra_args = []
# If specified, use a generic (x86_64, i386, arm, etc) qcow from MIT and ignore
if generic: # other args. See details in qcows.py
print("using generic " +str(generic))
q = Qcows.get_qcow_info(generic)
self.arch_name = q.arch
self.os = q.os
self.mem = q.default_mem # Might clobber a specified argument, but required if you want snapshots
self.qcow = Qcows.get_qcow(generic)
self.expect_prompt = q.prompt
self.cdrom = q.cdrom
if q.extra_args:
extra_args.extend(shlex_split(q.extra_args))
if self.qcow: # Otherwise we shuld be able to do a replay with no qcow but this is probably broken
if not (exists(self.qcow)):
print("Missing qcow '{}' Please go create that qcow and give it to the PANDA maintainers".format(self.qcow))
# panda.arch is a subclass with architecture-specific functions
self.arch = None # Keep this with the following docstring such that pydoc generats good docs for it; this is a useful variable!
"""
A reference to an auto-instantiated `pandare.arch.PandaArch` subclass (e.g., `pandare.arch.X86Arch`)
"""
if self.arch_name == "i386":
self.arch = X86Arch(self)
elif self.arch_name == "x86_64":
self.arch = X86_64Arch(self)
elif self.arch_name in ["arm"]:
self.arch = ArmArch(self)
elif self.arch_name in ["aarch64"]:
self.arch = Aarch64Arch(self)
elif self.arch_name in ["mips", "mipsel"]:
self.arch = MipsArch(self)
elif self.arch_name in ["mips64", "mips64el"]:
self.arch = Mips64Arch(self)
elif self.arch_name in ["ppc"]:
self.arch = PowerPCArch(self)
else:
raise ValueError(f"Unsupported architecture {self.arch_name}")
self.bits, self.endianness, self.register_size = self.arch._determine_bits()
if libpanda_path:
environ["PANDA_LIB"] = self.libpanda_path = libpanda_path
else:
build_dir = self.get_build_dir()
lib_paths = ["libpanda-{0}.so".format(self.arch_name), "{0}-softmmu/libpanda-{0}.so".format(self.arch_name)]
# Select the first path that exists - we'll have libpanda-{arch}.so for a system install versus arch-softmmu/libpanda-arch.so for a build
for p in lib_paths:
if isfile(pjoin(build_dir, p)):
self.libpanda_path = pjoin(build_dir, p)
break
else:
raise RuntimeError("Couldn't find libpanda-{0}.so in {1} (in either root or {0}-libpanda directory)".format(self.arch_name, build_dir))
self.panda = self.libpanda_path # Necessary for realpath to work inside core-panda, may cause issues?
self.ffi = self._do_types_import()
self.libpanda = self.ffi.dlopen(self.libpanda_path)
self.C = self.ffi.dlopen(None)
# set OS name if we have one
if self.os:
self.set_os_name(self.os)
# Setup argv for panda
self.panda_args = [self.panda]
if biospath is None:
biospath = realpath(pjoin(self.get_build_dir(), "pc-bios")) # XXX: necessary for network drivers for arm/mips, so 'pc-bios' is a misleading name
self.panda_args.append("-L")
self.panda_args.append(biospath)
if self.qcow:
if self.arch_name in ['mips64', 'mips64el']:
# XXX: mips64 needs virtio interface for the qcow
self.panda_args.extend(["-drive", f"file={self.qcow},if=virtio"])
else:
self.panda_args.append(self.qcow)
self.panda_args += extra_args
# Configure memory options
self.panda_args.extend(['-m', self.mem])
# Configure serial - if we have an expect_prompt set. Otherwise how can we know what guest cmds are outputting?
if self.expect_prompt or (serial_kwargs is not None and serial_kwargs.get('expectation')):
self.serial_file = NamedTemporaryFile(prefix="pypanda_s").name
self.serial_socket = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
expect_kwargs = {'expectation': self.expect_prompt, 'consume_first': False, 'unansi': True}
if serial_kwargs:
expect_kwargs.update(serial_kwargs)
self.serial_console = Expect('serial', **expect_kwargs)
self.panda_args.extend(['-serial', 'unix:{},server,nowait'.format(self.serial_file)])
else:
self.serial_file = None
self.serial_socket = None
self.serial_console = None
# Configure monitor - Always enabled for now
self.monitor_file = NamedTemporaryFile(prefix="pypanda_m").name
self.monitor_socket = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
self.raw_monitor = raw_monitor
if not self.raw_monitor:
# XXX don't forget to escape expectation regex parens!
self.monitor_console = Expect('monitor', expectation=rb"\(qemu\) ", consume_first=True)
self.panda_args.extend(['-monitor', 'unix:{},server,nowait'.format(self.monitor_file)])
self.running = threading.Event()
self.started = threading.Event()
self.initializing = threading.Event()
self.athread = AsyncThread(self.started) # athread manages actions that need to occur outside qemu's CPU loop
# Callbacks
self.register_cb_decorators()
self.plugin_register_count = 0
self.registered_callbacks = {} # name -> {procname: "bash", enabled: False, callback: None}
# Register asid_changed CB if and only if a callback requires procname
self._registered_asid_changed_internal_cb = False
self._registered_mmap_cb = False
self._initialized_panda = False
self.disabled_tb_chaining = False
self.named_hooks = {}
self.hook_list = []
self.hook_list2 = {}
self.mem_hooks = {}
self.sr_hooks = []
self.hypercalls = {}
# Asid stuff
self.current_asid_name = None
self.asid_mapping = {}
# Shutdown stuff
self.exception = None # When set to an exn, we'll raise and exit
self._in_replay = False
# cosi
self.cosi = Cosi(self)
# main_loop_wait functions and callbacks
self.main_loop_wait_fnargs = [] # [(fn, args), ...]
progress ("Panda args: [" + (" ".join(self.panda_args)) + "]")
# /__init__
def get_plugin_path(self):
if self.plugin_path is None:
build_dir = self.get_build_dir()
rel_dir = pjoin(*[build_dir, self.arch_name+"-softmmu", "panda", "plugins"])
if build_dir == "/usr/local/bin/":
# Installed - use /usr/local/lib/panda/plugins
self.plugin_path = f"/usr/local/lib/panda/{self.arch_name}"
elif isdir(rel_dir):
self.plugin_path = rel_dir
else:
raise ValueError(f"Could not find plugin path. Build dir={build_dir}")
return self.plugin_path
def get_build_dir(self):
if self.build_dir is None:
self.build_dir = find_build_dir(self.arch_name)
environ["PANDA_DIR"] = self.build_dir
return self.build_dir
def _do_types_import(self):
'''
Import objects from panda_datatypes which are configured by the environment variables(?)
Check the DATATTYPES_VERSION to detect if panda_datatypes.py has gotten stale.
Store these objects in self.callback and self.callback_dictionary
Returns a handle to the FFI object for the libpanda object
'''
required_datatypes_version = 1.1
version_err = "Your panda_datatypes.py is out of date (has version {} but PANDA " \
"requires version {}). Please reinstall pypanda or re-run "\
"create_panda_datatypes.py."
try:
from .autogen.panda_datatypes import DATATYPES_VERSION
except ImportError:
raise RuntimeError(version_err.format(None, required_datatypes_version))
if required_datatypes_version != DATATYPES_VERSION:
raise RuntimeError(version_err.format(DATATYPES_VERSION, required_datatypes_version))
from importlib import import_module
from .autogen.panda_datatypes import get_cbs
panda_arch_support = import_module(f".autogen.panda_{self.arch_name}_{self.bits}",package='pandare')
ffi = panda_arch_support.ffi
self.callback, self.callback_dictionary = get_cbs(ffi)
return ffi
def _initialize_panda(self):
'''
After initializing the class, the user has a chance to do something
(TODO: what? register callbacks? It's something important...) before we finish initializing
'''
self.libpanda._panda_set_library_mode(True)
cenvp = self.ffi.new("char**", self.ffi.new("char[]", b""))
len_cargs = self.ffi.cast("int", len(self.panda_args))
panda_args_ffi = [self.ffi.new("char[]", bytes(str(i),"utf-8")) for i in self.panda_args]
self.libpanda.panda_init(len_cargs, panda_args_ffi, cenvp)
# Now we've run qemu init so we can connect to the sockets for the monitor and serial
if self.serial_console and not self.serial_console.is_connected():
self.serial_socket.connect(self.serial_file)
self.serial_socket.settimeout(None)
self.serial_console.connect(self.serial_socket)
if not self.raw_monitor and not self.monitor_console.is_connected():
self.monitor_socket.connect(self.monitor_file)
self.monitor_console.connect(self.monitor_socket)
# Register __main_loop_wait_callback
self.register_callback(self.callback.main_loop_wait,
self.callback.main_loop_wait(self.__main_loop_wait_cb), '__main_loop_wait')
self._initialized_panda = True
def __main_loop_wait_cb(self):
'''
__main_loop_wait_cb is called at the start of the main cpu loop in qemu.
This is a fairly safe place to call into qemu internals but watch out for deadlocks caused
by your request blocking on the guest's execution. Here any functions in main_loop_wait_fnargs will be called
'''
try:
# Then run any and all requested commands
if len(self.main_loop_wait_fnargs) == 0: return
#progress("Entering main_loop_wait_cb")
for fnargs in self.main_loop_wait_fnargs:
(fn, args) = fnargs
ret = fn(*args)
self.main_loop_wait_fnargs = []
except KeyboardInterrupt:
self.end_analysis()
def queue_main_loop_wait_fn(self, fn, args=[]):
'''
Queue a function to run at the next main loop
fn is a function we want to run, args are arguments to apss to it
'''
self.main_loop_wait_fnargs.append((fn, args))
def exit_cpu_loop(self):
'''
Stop cpu execution at nearest juncture.
'''
self.libpanda.panda_exit_loop = True
def revert_async(self, snapshot_name): # In the next main loop, revert
'''
Request a snapshot revert, eventually. This is fairly dangerous
because you don't know when it finishes. You should be using revert_sync
from a blocking function instead
'''
if not hasattr(self, 'warned_async'):
self.warned_async = True
print("WARNING: panda.revert_async may be deprecated in the near future")
if debug:
progress ("Loading snapshot " + snapshot_name)
# Stop guest, queue up revert, then continue
timer_start = time()
self.vm_stop()
charptr = self.ffi.new("char[]", bytes(snapshot_name, "utf-8"))
self.queue_main_loop_wait_fn(self.libpanda.panda_revert, [charptr])
self.queue_main_loop_wait_fn(self.libpanda.panda_cont)
if debug:
self.queue_main_loop_wait_fn(self._finish_timer, [timer_start, "Loaded snapshot"])
def reset(self):
"""In the next main loop, reset to boot"""
if debug:
progress ("Resetting machine to start state")
# Stop guest, queue up revert, then continue
self.vm_stop()
self.queue_main_loop_wait_fn(self.libpanda.panda_reset)
self.queue_main_loop_wait_fn(self.libpanda.panda_cont)
def cont(self):
''' Continue execution (run after vm_stop) '''
self.libpanda.panda_cont()
self.running.set()
def vm_stop(self, code=4):
''' Stop execution, default code means RUN_STATE_PAUSED '''
self.libpanda.panda_stop(code)
def snap(self, snapshot_name):
'''
Create snapshot with specified name
Args:
snapshot_name (str): name of the snapshot
Returns:
None
'''
if debug:
progress ("Creating snapshot " + snapshot_name)
# Stop guest execution, queue up a snapshot, then continue
timer_start = time()
self.vm_stop()
charptr = self.ffi.new("char[]", bytes(snapshot_name, "utf-8"))
self.queue_main_loop_wait_fn(self.libpanda.panda_snap, [charptr])
self.queue_main_loop_wait_fn(self.libpanda.panda_cont)
if debug:
self.queue_main_loop_wait_fn(self._finish_timer, [timer_start, "Saved snapshot"])
def delvm(self, snapshot_name):
'''
Delete snapshot with specified name
Args:
snapshot_name (str): name of the snapshot
Returns:
None
'''
if debug:
progress ("Deleting snapshot " + snapshot_name)
# Stop guest, queue up delete, then continue
self.vm_stop()
charptr = self.ffi.new("char[]", bytes(snapshot_name, "utf-8"))
self.queue_main_loop_wait_fn(self.libpanda.panda_delvm, [charptr])
def _finish_timer(self, start, msg):
''' Print how long some (main_loop_wait) task took '''
t = time() - start
print("{} in {:.08f} seconds".format(msg, t))
def enable_tb_chaining(self):
'''
This function enables translation block chaining in QEMU
'''
if debug:
progress("Enabling TB chaining")
self.disabled_tb_chaining = False
self.libpanda.panda_enable_tb_chaining()
def disable_tb_chaining(self):
'''
This function disables translation block chaining in QEMU
'''
if not self.disabled_tb_chaining:
if debug:
progress("Disabling TB chaining")
self.disabled_tb_chaining = True
self.libpanda.panda_disable_tb_chaining()
def _setup_internal_signal_handler(self, signal_handler=None):
def SigHandler(SIG,a,b):
from signal import SIGINT, SIGHUP, SIGTERM
if SIG == SIGINT:
self.exit_exception = KeyboardInterrupt
self.end_analysis()
elif SIG == SIGHUP:
self.exit_exception = KeyboardInterrupt
self.end_analysis()
elif SIG == SIGTERM:
self.exit_exception = KeyboardInterrupt
self.end_analysis()
else:
print(f"PyPanda Signal handler received unhandled signal {SIG}")
if signal_handler is not None:
# store custom signal handler if requested1
self.__sighandler = signal_handler
if self._initialized_panda:
# initialize and register signal handler only if panda is initialized
self.__sighandler = (self.ffi.callback("void(int,void*,void*)", SigHandler)
if signal_handler is None and self.__sighandler is None
else self.ffi.callback("void(int,void*,void*)", self.__sighandler))
self.libpanda.panda_setup_signal_handling(self.__sighandler)
def run(self):
'''
This function starts our running PANDA instance from Python. At termination this function returns and the script continues to run after it.
This function starts execution of the guest. It blocks until guest finishes.
It also initializes panda object, clears main_loop_wait fns, and sets up internal callbacks.
Args:
None
Returns:
None: When emulation has finished due to guest termination, replay conclusion or a call to `Panda.end_analysis`
'''
if len(self.main_loop_wait_fnargs):
if debug:
print("Clearing prior main_loop_wait fns:", self.main_loop_wait_fnargs)
self.main_loop_wait_fnargs = [] # [(fn, args), ...]
self.ending = False
if debug:
progress ("Running")
self.initializing.set()
if not self._initialized_panda:
self._initialize_panda()
self.initializing.clear()
if not self.started.is_set():
self.started.set()
self.athread.ending = False
# Ensure our internal CBs are always enabled
self.enable_internal_callbacks()
self._setup_internal_signal_handler()
self.running.set()
self.libpanda.panda_run() # Give control to panda
self.running.clear() # Back from panda's execution (due to shutdown or monitor quit)
self.unload_plugins() # Unload pyplugins and C plugins
self.delete_callbacks() # Unload any registered callbacks
self.plugins = plugin_list(self)
# Write PANDALOG, if any
#self.libpanda.panda_cleanup_record()
if self._in_replay:
self.reset()
if hasattr(self, "exit_exception"):
saved_exception = self.exit_exception
del self.exit_exception
raise saved_exception
def end_analysis(self):
'''
Stop running machine.
Call from any thread to unload all plugins and stop all queued functions.
If called from async thread or a callback, it will also unblock panda.run()
Note here we use the async class's internal thread to process these
without needing to wait for tasks in the main async thread
'''
self.athread.ending = True
self.ending = True
self.unload_plugins()
if self.running.is_set() or self.initializing.is_set():
# If we were running, stop the execution and check if we crashed
self.queue_async(self.stop_run, internal=True)
def record(self, recording_name, snapshot_name=None):
"""Begins active recording with name provided.
Args:
recording_name (string): name of recording to save.
snapshot_name (string, optional): Before recording starts restore to this snapshot name. Defaults to None.
Raises:
Exception: raises exception if there was an error starting recording.
"""
if snapshot_name == None:
snapshot_name_ffi = self.ffi.NULL
else:
snapshot_name_ffi = self.ffi.new("char[]",snapshot_name.encode())
recording_name_ffi = self.ffi.new("char[]", recording_name.encode())
result = self.libpanda.panda_record_begin(recording_name_ffi,snapshot_name_ffi)
res_string_enum = self.ffi.string(self.ffi.cast("RRCTRL_ret",result))
if res_string_enum != "RRCTRL_OK":
raise Exception(f"record method failed with RTCTL_ret {res_string_enum} ({result})")
def end_record(self):
"""Stop active recording.
Raises:
Exception: raises exception if there was an error stopping recording.
"""
result = self.libpanda.panda_record_end()
res_string_enum = self.ffi.string(self.ffi.cast("RRCTRL_ret",result))
if res_string_enum != "RRCTRL_OK":
raise Exception(f"record method failed with RTCTL_ret {res_string_enum} ({result})")
def recording_exists(self, name):
'''
Checks if a recording file exists on disk.
Args:
name (str): name of the recording to check for (e.g., `foo` which uses `foo-rr-snp` and `foo-rr-nondet.log`)
Returns:
boolean: true if file exists, false otherwise
'''
if exists(name + "-rr-snp") or rr2_contains_member(name, "snapshot"):
return True
def run_replay(self, replaypfx):
'''
Load a replay and run it. Starts PANDA execution and returns after end of VM execution.
Args:
replaypfx (str): Replay name/path (e.g., "foo" or "./dir/foo")
Returns:
None
'''
if (not isfile(replaypfx+"-rr-snp") or not isfile(replaypfx+"-rr-nondet.log")) and not rr2_recording(replaypfx):
raise ValueError("Replay files not present to run replay of {}".format(replaypfx))
self.ending = False
if debug:
progress ("Replaying %s" % replaypfx)
charptr = self.ffi.new("char[]",bytes(replaypfx,"utf-8"))
self.libpanda.panda_replay_begin(charptr)
self._in_replay = True
self.run()
self._in_replay = False
def end_replay(self):
'''
Terminates a currently running replay
Returns:
None
Raises:
Exception: raises exception if no replay is active or termination failed.
'''
if self._in_replay is False:
raise Exception("Tried to terminate replay while not in replay mode!")
result = self.libpanda.panda_replay_end()
res_string_enum = self.ffi.string(self.ffi.cast("RRCTRL_ret",result))
if res_string_enum != "RRCTRL_OK":
raise Exception(f"ending record method failed with RTCTL_ret {res_string_enum} ({result})")
def require(self, name):
'''
Load a C plugin with no arguments. Deprecated. Use load_plugin
'''
self.load_plugin(name, args={})
def _plugin_loaded(self, name):
name_c = self.ffi.new("char[]", bytes(name, "utf-8"))
return self.libpanda.panda_get_plugin_by_name(name_c) != self.ffi.NULL
def load_plugin(self, name, args={}):
'''
Load a C plugin, optionally with arguments
Args:
name (str): Name of plugin
args (dict): Arguments matching key to value. e.g. {"key": "value"} sets option `key` to `value`.
Returns:
None.
'''
if debug:
progress ("Loading plugin %s" % name),
argstrs_ffi = []
if isinstance(args, dict):
for k,v in args.items():
this_arg_s = "{}={}".format(k,v)
this_arg = self.ffi.new("char[]", bytes(this_arg_s, "utf-8"))
argstrs_ffi.append(this_arg)
n = len(args.keys())
elif isinstance(args, list):
for arg in args:
this_arg = self.ffi.new("char[]", bytes(arg, "utf-8"))
argstrs_ffi.append(this_arg)
n = len(args)
else:
raise ValueError("Arguments to load plugin must be a list or dict of key/value pairs")
# First set qemu_path so plugins can load (may be unnecessary after the first time)
assert(self.panda), "Unknown location of PANDA"
panda_name_ffi = self.ffi.new("char[]", bytes(self.panda,"utf-8"))
self.libpanda.panda_set_qemu_path(panda_name_ffi)
if len(argstrs_ffi):
plugin_args = argstrs_ffi
else:
plugin_args = self.ffi.NULL
charptr = self.ffi.new("char[]", bytes(name,"utf-8"))
self.libpanda.panda_require_from_library(charptr, plugin_args, len(argstrs_ffi))
self._load_plugin_library(name)
def _procname_changed(self, cpu, name):
for cb_name, cb in self.registered_callbacks.items():
if not cb["procname"]:
continue
if name == cb["procname"] and not cb['enabled']:
self.enable_callback(cb_name)
if name != cb["procname"] and cb['enabled']:
self.disable_callback(cb_name)
def unload_plugin(self, name):
'''
Unload plugin with given name.
Args:
name (str): Name of plug
Returns:
None
'''
if debug:
progress ("Unloading plugin %s" % name),
name_ffi = self.ffi.new("char[]", bytes(name,"utf-8"))
self.libpanda.panda_unload_plugin_by_name(name_ffi)
def _unload_pyplugins(self):
'''
Unload Python plugins first.
We have to be careful to not remove __main_loop_wait because we're executing inside of __main_loop_wait and it more work to do
We achieve this by first popping main loop wait and then re-adding it after unloading all other callbacks
'''
mlw = self.registered_callbacks.pop("__main_loop_wait")
# First unload python plugins, should be safe to do anytime
while self.registered_callbacks:
try:
self.delete_callback(list(self.registered_callbacks.keys())[0])
except IndexError:
continue
self.registered_callbacks["__main_loop_wait"] = mlw
# Next, unload any pyplugins
if hasattr(self, "_pyplugin_manager"):
self.pyplugins.unload_all()
def unload_plugins(self):
'''
Disable all python plugins and request to unload all c plugins
at the next main_loop_wait.
XXX: If called during shutdown/exit, c plugins won't be unloaded
because the next main_loop_wait will never happen. Instead, call
panda.panda_finish directly (which is done at the end of panda.run())
'''
if debug:
progress ("Disabling all python plugins, unloading all C plugins")
# In next main loop wait, unload all python plugin
self.queue_main_loop_wait_fn(self._unload_pyplugins)
# Then unload C plugins. May be unsafe to do except from the top of the main loop (taint segfaults otherwise)
self.queue_main_loop_wait_fn(self.libpanda.panda_unload_plugins)
def memsavep(self, file_out):
'''
Calls QEMU memsavep on your specified python file.
'''
# this part was largely copied from https://cffi.readthedocs.io/en/latest/ref.html#support-for-file
file_out.flush() # make sure the file is flushed
newfd = dup(file_out.fileno()) # make a copy of the file descriptor
fileptr = self.C.fdopen(newfd, b"w")
self.libpanda.panda_memsavep(fileptr)
self.C.fclose(fileptr)
def physical_memory_read(self, addr, length, fmt='bytearray'):
'''
Read guest physical memory. In the specified format. Note that the `ptrlist` format
returns a list of integers, each of the specified architecture's pointer size.
Args:
addr (int): Address
length (int): length of array you would like returned
fmt (str): format for returned array. Options: 'bytearray', 'int', 'str', 'ptrlist'
Returns:
Union[bytearray, int, str, list[int]]: memory data
Raises:
ValueError if memory access fails or fmt is unsupported
'''
return self._memory_read(None, addr, length, physical=True, fmt=fmt)
def virtual_memory_read(self, cpu, addr, length, fmt='bytearray'):
'''
Read guest virtual memory.
Args:
cpu (CPUState): CPUState structure
addr (int): Address
length (int): length of data you would like returned
fmt: format for returned array. See `physical_memory_read`.
Returns:
Union[bytearray, int, str, list[int]]: memory data
Raises:
ValueError if memory access fails or fmt is unsupported
'''
return self._memory_read(cpu, addr, length, physical=False, fmt=fmt)
def _memory_read(self, env, addr, length, physical=False, fmt='bytearray'):
'''
Read but with an autogen'd buffer
Supports physical or virtual addresses
Raises ValueError if read fails
'''
if not isinstance(addr, int):
raise ValueError(f"Unsupported read from address {repr(addr)}")
buf = self.ffi.new("char[]", length)
# Force CFFI to parse addr as an unsigned value. Otherwise we get OverflowErrors