This repository has been archived by the owner on Jan 10, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 53
/
Copy pathsea_runtool.py
2877 lines (2443 loc) · 115 KB
/
sea_runtool.py
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
# Intel(R) Single Event API
#
# This file is provided under the BSD 3-Clause license.
# Copyright (c) 2021, Intel Corporation
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:
# Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
# Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
# Neither the name of the Intel Corporation nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
# IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
# HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#
# ********************************************************************************************************************************************************************************************************************************************************************************************
from __future__ import print_function
import os
import imp
import sys
import sea
import copy
import time
import shutil
import struct
import signal
import strings
import fnmatch
import tempfile
import binascii
import platform
import traceback
import threading
import subprocess
from python_compat import *
from glob import glob
from datetime import datetime, timedelta
sys.path.append(os.path.realpath(os.path.join(os.path.dirname(__file__), 'decoders')))
try:
sys.setdefaultencoding("utf-8")
except:
pass
ProgressConst = 20000
TIME_SHIFT_FOR_GT = 1000
# on OSX an Application launched from Launchpad has nothing in PATH
if sys.platform == 'darwin':
if '/usr/bin' not in os.environ['PATH']:
os.environ['PATH'] += os.pathsep + '/usr/bin'
if '/usr/sbin' not in os.environ['PATH']:
os.environ['PATH'] += os.pathsep + '/usr/sbin'
def global_storage(name, default={}):
if isinstance(__builtins__, dict):
seapi = __builtins__.setdefault('SEAPI', {})
else: # pypy
if not hasattr(__builtins__, 'SEAPI'):
setattr(__builtins__, 'SEAPI', {})
seapi = getattr(__builtins__, 'SEAPI', None)
return seapi.setdefault(name, copy.deepcopy(default)) if name else seapi # FIXME put copy.deepcopy under condition
def thread_storage(name, default={}):
tls = global_storage('TLS', {})
lkl = tls.setdefault(threading.current_thread().ident, {})
if name in lkl:
return lkl[name]
else:
return lkl.setdefault(name, copy.deepcopy(default))
def reset_global(name, value):
global_storage(None)[name] = value
def format_time(time):
for coeff, suffix in [(10 ** 3, 'ns'), (10 ** 6, 'us'), (10 ** 9, 'ms')]:
if time < coeff:
return "%.3f%s" % (time * 1000.0 / coeff, suffix)
return "%.3fs" % (float(time) / 10 ** 9)
def format_bytes(num):
for unit in ['', 'K', 'M', 'G']:
if abs(num) < 1024.0:
return "%3.1f %sB" % (num, unit)
num /= 1024.0
return str(num) + 'B'
class DummyWith(): # for conditional with statements
def __enter__(self):
return self
def __exit__(self, type, value, traceback):
return False
class Profiler():
def __enter__(self):
try:
import cProfile as profile
except:
import profile
self.profiler = profile.Profile()
self.profiler.enable()
return self
def __exit__(self, type, value, traceback):
self.profiler.disable()
self.profiler.print_stats('time')
return False
def get_extensions(name, multiple=False):
big_name = (name + 's').upper()
this_module = sys.modules[__name__]
if big_name in dir(this_module):
return getattr(this_module, big_name)
extensions = {}
root = os.path.join(os.path.dirname(os.path.realpath(__file__)), name + 's')
for extension in glob(os.path.join(root, '*.py')):
module_name = name + '.' + os.path.splitext(os.path.basename(extension))[0]
if name not in sys.modules:
sys.modules[name] = imp.new_module(name)
if module_name in sys.modules:
module = sys.modules[module_name]
else:
module = imp.load_source(module_name, extension)
for desc in getattr(module, name.upper() + '_DESCRIPTORS', []):
if desc['available']:
if multiple:
extensions.setdefault(desc['format'], []).append(desc[name])
else:
extensions[desc['format']] = desc[name]
setattr(this_module, big_name, extensions)
return extensions
def get_exporters():
return get_extensions('exporter')
def get_importers():
return get_extensions('importer')
def get_collectors():
return get_extensions('collector')
def get_decoders():
return get_extensions('decoder', multiple=True)
verbose_choices = ['fatal', 'error', 'warning', 'info']
def parse_args(args):
import argparse
parser = argparse.ArgumentParser(epilog="After this command line add ! followed by command line of your program")
format_choices = ["mfc", "mfp"] + list(get_exporters().keys())
if sys.platform == 'win32':
format_choices.append("etw")
elif sys.platform == 'darwin':
format_choices.append("xcode")
elif sys.platform == 'linux':
format_choices.append("kernelshark")
parser.add_argument("-f", "--format", choices=format_choices, nargs='*', default=[], help='One or many output formats.')
parser.add_argument("-o", "--output", help='Output folder pattern -<pid> will be added to it')
parser.add_argument("-b", "--bindir", help='If you run script not from its location')
parser.add_argument("-i", "--input", help='Provide input folder for transformation (<the one you passed to -o>-<pid>)')
parser.add_argument("-t", "--trace", nargs='*', help='Additional trace file in one of supported formats')
parser.add_argument("-d", "--dir", help='Working directory for target (your program)')
parser.add_argument("-v", "--verbose", default="warning", choices=verbose_choices)
parser.add_argument("-c", "--cuts", nargs='*', help='Set "all" to merge all cuts in one trace')
parser.add_argument("-s", "--sync")
parser.add_argument("--single", default=False, action="store_true", help='Narrows capture to one process')
parser.add_argument("-r", "--ring", type=int, const='5', default=None, action='store', nargs='?', help='Makes trace to cycle inside ring buffer of given length in seconds')
parser.add_argument("--time_shift", type=int, default=0)
parser.add_argument("-l", "--limit", help='define')
parser.add_argument("--ssh")
parser.add_argument("-p", "--password")
parser.add_argument("-a", "--ask_to_stop", action="store_true", help='Waits confirmation to stop collection')
parser.add_argument("--target", help='Pid of target')
parser.add_argument("--dry", action="store_true", help='Dry mode, only prints what it would do')
parser.add_argument("--stacks", action="store_true", help='Collect stacks')
parser.add_argument("--min_dur", type=float, default=0, help='Sets minimal task length threshold (in float, microseconds). Helps opening huge traces.')
parser.add_argument("--sampling")
parser.add_argument("--distinct", action="store_true")
parser.add_argument("--memory", choices=["total", "detailed"])
parser.add_argument("--debug", action="store_true", help='Internal: validation')
parser.add_argument("--profile", action="store_true", help='Internal: profile runtool execution')
parser.add_argument("--trace_to", help='Internal: ITT trace runtool execution into given folder') # or: -m trace -t
parser.add_argument("--collector", choices=list(get_collectors().keys()) + ['default'])
parser.add_argument("--strip_aliens", action="store_true", help='Filters out all but target processes')
parser.add_argument("--system_wide", action="store_true", help='Includes all captured data(can kill viewer)')
parser.add_argument("--remove_args", action="store_true", help='Deflates trace by removing arguments')
parser.add_argument("--rem", help="Comment out: Allows to put everything you don't need")
parser.add_argument("--no_left_overs", action="store_true", help='Disables automatic prolongation of unfinished events to the end of the trace')
parser.add_argument("--counter_set", default='OA.RenderBasic', help='gpu counter set, set into none to disable')
parser.add_argument("--memory_limit", type=int, default=0, help='Sets minimal memory counter threshold (in bytes). Helps opening huge memory traces.')
parser.add_argument("--gpu_samples", const='*', default=None, action='store', nargs='?', help='Collect GPU side draw calls and some predefined telemetry counters')
parser.add_argument("--gs_add", nargs='*', default=[], help='Additional telemetry counters to collect, see names in all_metrics.txt')
parser.add_argument("--hotspots", action="store_true")
parser.add_argument("--stats", action="store_true")
parser.add_argument("--no_catapult", action="store_true")
parser.add_argument("--hook", nargs='*', default=[], help='One or many modules to hook in target process')
parser.add_argument("--hook_kmd", nargs='*', default=[], help='One or many modules to hook in KMD')
parser.add_argument("--telemetry", action="store_true", help='Collect all telemetry counters')
parser.add_argument("--filesystem", action="store_true", help='Collect file system events')
parser.add_argument("--args", type=int, help='Collect N function arguments')
parser.add_argument("--greedy", action="store_true", help='Collect all children under hooked functions')
parser.add_argument("--follow", action="store_true", help='Follow child')
parser.add_argument("--sqlite", action="store_true", help='Use DB during transformation - experimental')
parser.add_argument("--mtlshim", action="store_true", help='mtlshim - experimental')
parser.add_argument("--user", action="store_true", default=sys.gettrace(), help="don't elevate") # True under debug
separators = ['!', '?', '%']
separator = None
for sep in separators:
if sep in args:
separator = args.index(sep)
break
# separator = args.index("!") if "!" in args else args.index("?") if "?" in args else None
if separator is not None:
parsed_args = parser.parse_args(args[:separator])
if parsed_args.input:
parser.print_help()
print("Error: Input argument (-i) contradicts launch mode")
sys.exit(-1)
victim = args[separator + 1:]
victim[-1] = victim[-1].strip() # removal of trailing '\r' - when launched from .sh
if not parsed_args.output:
if sys.platform != 'win32':
parsed_args.output = '/tmp/isea_collection'
print('Collection will be written into:' , parsed_args.output)
else:
parser.print_help()
print("Error: No output (-o) given in launch mode")
sys.exit(-1)
handle_args(parsed_args)
return parsed_args, victim
else: # nothing to launch, transformation mode
if args:
args[-1] = args[-1].strip() # removal of trailing '\r' - when launched from .sh
parsed_args = parser.parse_args(args)
handle_args(parsed_args)
if not parsed_args.input:
if sys.platform != 'win32':
parsed_args.input = '/tmp/isea_collection'
if os.path.exists(parsed_args.input):
print('Collection will be read from:', parsed_args.input)
else:
parser.print_help()
sys.exit(-1)
else:
print("--input argument is required for transformation mode.")
parser.print_help()
sys.exit(-1)
if not parsed_args.format:
parsed_args.format = ['gt']
setattr(parsed_args, 'user_input', parsed_args.input)
if not parsed_args.output:
parsed_args.output = parsed_args.input
return parsed_args, None
def handle_args(args):
if args.input:
args.input = subst_env_vars(args.input)
if args.output:
args.output = subst_env_vars(args.output)
if args.dir:
args.dir = subst_env_vars(args.dir)
if not args.bindir:
args.bindir = os.path.join(os.path.dirname(os.path.realpath(__file__)), '../bin')
args.bindir = os.path.abspath(args.bindir)
if args.stacks and not args.system_wide:
args.strip_aliens = True
def get_args():
return global_storage('arguments')
def get_original_env():
return global_storage('environ')
def verbose_level(level=None, statics={}):
if not statics:
args = get_args()
if not args:
return verbose_choices.index(level) if level else 'warning'
statics['level'] = verbose_choices.index(get_args().verbose)
return verbose_choices.index(level) if level else statics['level']
def message(level, txt, statics={}):
assert isinstance(statics, dict)
if level and verbose_level(level) > verbose_level(): # see default in "parse_args"
return False
# in python2 type(parent_frame) is tuple with length == 4
# in python3 type(parent_frame) is FrameSummary
parent_frame = traceback.extract_stack()[-2]
# slice operation returns tuple
history = statics.setdefault(parent_frame[:4], {'count': 0, 'heap': []})
history['count'] += 1
if history['count'] < 5 or not level:
print('\n', (level.upper() + ':') if level else '', '%s' % txt)
print('\tFile "%s", line %d, in %s' % parent_frame[:3])
Collector.log("\n%s:\t%s\n" % (level.upper() if level else 'RUNTIME', txt), stack=(verbose_level(level) <= verbose_level('warning')))
elif history['count'] == 5:
print('\n', level.upper(), 'Stopping pollution from', parent_frame[:3])
return True
def install():
print('Install steps:')
toplevel = os.path.realpath(os.path.join(os.path.dirname(__file__), '..'))
print(toplevel)
def syscall(cmd):
print(cmd)
os.system(cmd)
if sys.platform != 'win32':
syscall('open "%s/README.txt"&' % toplevel)
syscall('chmod +x %s/isea.sh' % toplevel)
syscall('ln -F -s %s/isea.sh /usr/local/bin/isea' % toplevel)
GoogleTrace = get_exporters()['gt']
GoogleTrace.unpack_catapult(os.path.join(toplevel, 'bin'))
if sys.platform == 'darwin':
syscall('launchctl load -w /System/Library/LaunchDaemons/com.apple.locate.plist')
instruments = os.path.expanduser('~/Library/Application Support/Instruments/PlugIns/Instruments')
if not os.path.exists(instruments):
os.makedirs(instruments)
syscall('ln -F -s "%s/dtrace/IntelSEAPI.instrument" "%s/IntelSEAPI.instrument"' % (toplevel, instruments))
def main():
if 'install' in sys.argv:
return install()
reset_global('environ', os.environ.copy())
(args, victim) = parse_args(sys.argv[1:]) # skipping the script name
if not args.user and victim and not sea.as_admin():
return
reset_global('arguments', args)
if args.trace_to:
sea.trace_execution(None, None, args.trace_to)
load_collection(args)
with Profiler() if args.profile else DummyWith():
if victim:
if not args.single:
ensure_dir(args.output, clean=True)
launch(args, victim)
else:
ext = os.path.splitext(args.input)[1] if not os.path.isdir(args.input) else None
if not ext:
transform_all(args)
else:
try:
importer = get_importers()[ext.lstrip('.')]
except KeyError:
print("Error! Format %s is unavailable or unsupported" % ext)
return
output = importer(args)
output = join_gt_output(args, output)
replacement = ('/', '\\') if sys.platform == 'win32' else ('\\', '/')
for path in output:
print(os.path.abspath(path).replace(*replacement))
Collector.log('Started with arguments: %s' % str(sys.argv))
save_domains()
def os_lib_ext():
if sys.platform == 'win32':
return '.dll'
elif sys.platform == 'darwin':
return '.dylib'
elif 'linux' in sys.platform:
return '.so'
assert (not "Unsupported platform")
class Remote:
def __init__(self, args):
self.args = args
if sys.platform == 'win32':
self.execute_prefix = 'plink.exe -ssh %s' % args.ssh
self.copy_prefix = 'pscp.exe'
if args.password:
self.execute_prefix += ' -pw %s' % args.password
self.copy_prefix += ' -pw %s' % args.password
else:
self.execute_prefix = 'ssh %s' % args.ssh
self.copy_prefix = 'scp'
if args.password:
self.execute_prefix = 'sshpass -p %s %s' % (args.password, self.execute_prefix)
self.copy_prefix = 'sshpass -p %s %s' % (args.password, self.copy_prefix)
def execute(self, cmd):
command = '%s "%s"' % (self.execute_prefix, cmd)
message('info', "Command: " + command)
out, err = subprocess.Popen(command, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE).communicate()
if err:
print("Error:", err)
raise Exception(err)
return out
def copy(self, source, target):
message('info', "%s %s %s" % (self.copy_prefix, source, target))
out, err = subprocess.Popen("%s %s %s" % (self.copy_prefix, source, target), shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE).communicate()
if err:
print("Error:", err)
raise Exception(err)
return out
def launch_remote(args, victim):
remote = Remote(args)
print('Getting target uname...', end='')
unix = remote.execute("uname")
print(':', unix)
if 'darwin' in unix.lower():
search = os.path.join(args.bindir, '*IntelSEAPI.dylib')
files = glob(search)
load_lib = 'DYLD_INSERT_LIBRARIES'
else:
file = remote.execute('file %s' % victim[0])
bits = '64' if '64' in file else '32'
search = os.path.join(args.bindir, '*IntelSEAPI' + bits + '.so')
files = glob(search)
load_lib = 'INTEL_LIBITTNOTIFY' + bits
target = '/tmp/' + os.path.basename(files[0])
print('Copying corresponding library...')
print(remote.copy(files[0], '%s:%s' % (args.ssh, target)))
print('Making temp dir...')
trace = remote.execute('mktemp -d' + (' -t SEA_XXX' if 'darwin' in unix.lower() else '')).strip()
print(':', trace)
output = args.output
args.output = trace + '/nop'
print('Starting ftrace...')
ftrace = get_collectors()['ftrace'](args, remote)
print('Executing:', ' '.join(victim), '...')
variables = dict()
variables[load_lib] = target
variables['INTEL_SEA_SAVE_TO'] = trace
if args.verbose not in ['error', 'fatal']:
variables['INTEL_SEA_VERBOSE'] = '1'
if args.ring:
variables['INTEL_SEA_RING'] = str(args.ring)
suffix = ' '.join(['%s=%s' % pair for pair in variables.items()])
print(remote.execute(suffix + ' '.join(victim)))
if ftrace:
args.trace = ftrace.stop()
args.output = output
local_tmp = tempfile.mkdtemp()
print('Copying result:')
print(remote.copy('-r %s:%s' % (args.ssh, trace), local_tmp))
print('Removing temp dir...')
remote.execute('rm -r %s' % trace)
print('Transformation...')
files = glob(os.path.join(local_tmp, '*', 'pid-*'))
if not files:
print("Error: Nothing captured")
sys.exit(-1)
args.input = files[0]
if args.trace:
args.trace = [glob(os.path.join(local_tmp, '*', 'nop*.ftrace'))[0]]
output = transform(args)
output = join_gt_output(args, output)
shutil.rmtree(local_tmp)
print("result:", output)
# FIXME: doesn't belong this file: utils
def get_pids(victim, tracer):
assert len(victim) == 1 # one wildcard is supported yet
assert sys.platform != 'win32' # no Windows support yet
out, err = tracer.execute('ps -o pid,ppid,command -ax', log=False)
if err:
tracer.log(err)
return []
parsed = {}
for line in out.split('\n'):
if not line:
continue
parts = line.split()
if len(parts) < 3:
continue
cmd = ' '.join(parts[2:])
if fnmatch.fnmatch(cmd.lower(), victim[0].lower()) and __file__ not in cmd: # get matching cmd
parsed[parts[0]] = cmd
print("Matching cmd:\t", parts[0], cmd)
return set(parsed.keys())
def launch(args, victim):
if args.ssh:
return launch_remote(args, victim)
sea.prepare_environ(args)
sea_itf = sea.ITT('tools')
global_storage('collection').setdefault('time', {'start': time.time(), 'itt_start': sea_itf.get_timestamp()})
env = {}
paths = []
macosx = sys.platform == 'darwin'
win32 = sys.platform == 'win32'
bits_array = [''] if macosx else ['32', '64']
for bits in bits_array:
search = os.path.sep.join([args.bindir, "*IntelSEAPI" + bits + os_lib_ext()])
files = glob(search)
if not len(files):
message('warning', "didn't find any files for: %s" % search)
continue
paths.append((bits, files[0]))
if not len(paths):
print("Error: didn't find any *IntelSEAPI%s files. Please check that you run from bin directory, or use --bindir." % os_lib_ext())
sys.exit(-1)
if macosx:
env["DYLD_INSERT_LIBRARIES"] = paths[0][1]
else:
paths = dict(paths)
if '32' in paths:
env["INTEL_LIBITTNOTIFY32"] = paths['32']
env["INTEL_JIT_PROFILER32"] = paths['32']
if '64' in paths:
env["INTEL_LIBITTNOTIFY64"] = paths['64']
env["INTEL_JIT_PROFILER64"] = paths['64']
env["INTEL_SEA_FEATURES"] = os.environ['INTEL_SEA_FEATURES'] if 'INTEL_SEA_FEATURES' in os.environ else ""
env["INTEL_SEA_FEATURES"] += (" " + str(args.format)) if args.format else ""
env["INTEL_SEA_FEATURES"] += " stacks" if args.stacks else ""
env["INTEL_SEA_FEATURES"] += " memcount|memstat" if args.memory else ""
if args.verbose == 'info':
env['INTEL_SEA_VERBOSE'] = '1'
if args.ring:
env["INTEL_SEA_RING"] = str(args.ring)
if args.output:
env["INTEL_SEA_SAVE_TO"] = os.path.join(args.output, 'pid') if not args.single else args.output
# vulkan support
os_name = 'WIN' if win32 else 'OSX' if macosx else 'LIN'
var_name = os.pathsep.join(['VK_LAYER_INTEL_SEA_%s%s' % (os_name, bits) for bits in bits_array])
env['VK_INSTANCE_LAYERS'] = (os.environ['VK_INSTANCE_LAYERS'] + os.pathsep + var_name) if 'VK_INSTANCE_LAYERS' in os.environ else var_name
env['VK_LAYER_PATH'] = (os.environ['VK_LAYER_PATH'] + os.pathsep + args.bindir) if 'VK_LAYER_PATH' in os.environ else args.bindir
if args.dry:
for key, val in env.items():
if val:
print(key + "=" + val)
return
message('info', "Running: " + str(victim))
message('info', "Environment: " + str(env))
environ = global_storage('sea_env')
for key, val in env.items():
if key in environ and val != environ[key]:
assert key in ['LD_PRELOAD', 'DYLD_INSERT_LIBRARIES']
environ[key] += ':' + val
else:
environ[key] = val
if 'kernelshark' in args.format:
victim = 'trace-cmd record -e IntelSEAPI/* ' + victim
tracer = None
if args.collector:
tracer = get_collectors()[args.collector]
elif not tracer: # using default collector per system
if 'linux' in sys.platform:
tracer = get_collectors()['ftrace']
elif 'win32' == sys.platform:
tracer = get_collectors()['etw']
elif 'darwin' in sys.platform:
tracer = get_collectors()['dtrace']
run_suspended = False
if args.dir:
full_victim = os.path.join(args.dir, victim[0])
if os.path.exists(full_victim):
victim[0] = full_victim
setattr(args, 'victim', victim[0])
tracer = tracer(args) if tracer else None # turning class into instance
if '!' in sys.argv[1:]:
assert tracer
if hasattr(tracer, 'launch_victim'):
victim[0] = victim[0].replace(' ', r'\ ')
proc = tracer.launch_victim(victim, env=environ)
else:
if run_suspended: # might consider using preload of SEA lib and do the suspend there. Or allow tracers to run it.
suspended = '(cd "%s"; kill -STOP $$; exec %s )' % (args.dir or '.', ' '.join(victim))
proc = subprocess.Popen(suspended, env=environ, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
else:
proc = subprocess.Popen(victim, env=environ, shell=False, cwd=args.dir, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
if sys.platform != 'win32' and not run_suspended: # FIXME: implement suspended start on Windows!
if not args.ring:
proc.send_signal(signal.SIGSTOP)
args.target = proc.pid
tracer.start()
if sys.platform != 'win32': # collector start may be long, so we freeze victim during this time
print("PID:", proc.pid)
if not args.ring:
proc.send_signal(signal.SIGCONT)
print("Waiting application to exit...")
global_storage('collection')['time']['before'] = time.time()
try:
proc.wait()
except KeyboardInterrupt:
print("Stopping all...")
proc.send_signal(signal.SIGABRT)
if args.ask_to_stop:
raw_input('Hit Enter to stop collection:')
out, err = proc.communicate()
if out or err:
print("\n\n -= Target output =- {\n")
print(out.decode().strip())
print("\n", "-" * 50, "\n")
print(err.decode().strip())
print("\n}\n\n")
elif '?' in sys.argv[1:]:
print("Attach to:", victim)
pids = get_pids(victim, tracer)
if not pids:
print("Error: nothing found...")
return
if tracer:
args.target = list(pids)
tracer.start()
print("Waiting for CTRL+C...")
global_storage('collection')['time']['before'] = time.time()
def is_running(pid):
try:
os.kill(int(pid), 0)
return True
except OSError:
return False
try:
while any(is_running(pid) for pid in pids):
time.sleep(0.5)
except KeyboardInterrupt:
pass
else:
message('error', 'unsupported separator')
return -1
global_storage('collection')['time']['after'] = time.time()
print("Stopping collectors...")
if tracer:
args.trace = tracer.stop()
if not args.output:
return []
if args.single:
args.input = "%s-%d" % (args.output, proc.pid)
else:
args.input = args.output
times = global_storage('collection')['time']
times['end'] = time.time()
times['itt_end'] = sea_itf.get_timestamp()
if args.target:
if isinstance(args.target, list):
allowed_pids = args.target
else:
allowed_pids = [args.target]
global_storage('collection').setdefault('targets', allowed_pids)
save_collection(args)
if args.format:
transform_all(args)
def subst_env_vars(path):
return os.path.expandvars(path) if sys.platform == 'win32' else os.path.expanduser(path)
UserProfile = subst_env_vars('%USERPROFILE%' if sys.platform == 'win32' else '~')
PermanentCache = os.path.join(UserProfile, '.isea_cache.dict')
def save_collection(args):
collection = global_storage('collection')
with open(os.path.join(args.output, 'collection.dict'), 'w') as config:
config.write(str(collection))
permanent = global_storage('permanent')
with open(PermanentCache, 'w') as config:
config.write(str(permanent))
def load_collection(args):
collection_config = global_storage('collection')
if not collection_config and args.input:
path = os.path.join(args.input, 'collection.dict')
if os.path.exists(path):
with open(path) as config:
collection_config.update(eval(config.read().replace('L]', ']')))
permanent = global_storage('permanent')
if not permanent:
if os.path.exists(PermanentCache):
with open(PermanentCache) as config:
permanent.update(eval(config.read().replace('L, ', ', ')))
def ensure_dir(path, clean, statics={}):
if path in statics:
assert(statics[path] or not clean)
return
statics[path] = clean
if os.path.exists(path):
if clean:
shutil.rmtree(path)
else:
return
os.makedirs(path)
def transform_all(args):
setattr(args, 'user_input', args.input)
path = os.path.join(args.user_input, 'transform')
ensure_dir(path, True)
traces = set(args.trace if args.trace else [])
importers = get_importers()
for ext in importers.keys():
for file in glob(os.path.join(args.input, '*.' + ext)):
if not any(sub in file for sub in ['.etl.', '.dtrace.', 'merged.']):
traces.add(file)
args.trace = list(traces)
flagman = ['.etl', '.dtrace', '.ftrace', '.perf']
args.trace.sort(key=lambda item: os.path.splitext(item)[1] in flagman, reverse=True)
if not args.single:
multi_out = []
saved_output = args.output
sea_folders = [folder for folder in glob(os.path.join(args.input, 'pid-*')) if os.path.isdir(folder)]
if sea_folders:
for folder in sea_folders:
args.input = folder
args.output = saved_output + '.' + os.path.basename(folder)
multi_out += transform(args)
if args.trace:
traces = args.trace[:]
args.trace = None
for trace in traces:
ext = os.path.splitext(trace)[1]
args.input = trace
args.output = saved_output + '.' + os.path.basename(trace)
multi_out += get_importers()[ext.lstrip('.')](args)
output = join_gt_output(args, multi_out)
args.output = saved_output
else:
output = transform(args)
output = join_gt_output(args, output)
replacement = ('/', '\\') if sys.platform == 'win32' else ('\\', '/')
for path in output:
print('Result:', os.path.abspath(path).replace(*replacement), format_bytes(os.path.getsize(path)))
limits = Callbacks.get_globals()['limits']
arg_limits = Callbacks.parse_limits(getattr(args, 'limit', None))
print("limits:", limits)
if arg_limits[0] and not limits[0] <= arg_limits[0] <= limits[1]:
message('error', 'User argument error --limit: left limit is outside real time range')
if arg_limits[1] and not limits[0] <= arg_limits[1] <= limits[1]:
message('error', 'User argument error --limit: right limit is outside real time range')
return output
def join_gt_output(args, output):
db_traces = [item for item in output if os.path.splitext(item)[1] == '.db']
if db_traces:
results = get_exporters()['db'].join_traces(db_traces, args.output, args)
output = list(set(output) - set(db_traces)) + results
google_traces = [item for item in output if os.path.splitext(item)[1] in ['.json', '.ftrace']]
if google_traces:
res = get_exporters()['gt'].join_traces(google_traces, args.output, args)
output = list(set(output) - set(google_traces)) + [res]
return output
# FIXME: doesn't belong this file
def split_filename(path):
(dir, name) = os.path.split(path)
(name, ext) = os.path.splitext(name)
ring = None
cut = None
if '-' in name:
(name, ring) = name.split("-")
if '!' in name:
(name, cut) = name.split("!")
return {'dir': dir, 'name': name, 'cut': cut, 'ring':ring, 'ext': ext}
def default_tree(args):
tree = {"strings": {}, "domains": {}, "threads": {}, "groups": {}, "modules": {}, "ring_buffer": False, "cuts": set()}
if os.path.isdir(args.input):
process_dct = os.path.join(args.input, 'process.dct')
if not os.path.exists(process_dct):
return tree
with open(process_dct, 'r') as file:
tree["process"] = eval(file.read())
data_jit = os.path.join(args.input, 'data.jit')
if os.path.exists(data_jit):
parse_jit(tree, data_jit)
for filename in glob(os.path.join(args.input, '*.mdl')):
with open(filename, 'r') as file:
parts = file.readline().split()
tree["modules"][int(os.path.basename(filename).replace(".mdl", ""))] = [' '.join(parts[0:-1]), parts[-1]]
return tree
def build_tid_map(args, path):
tid_map = {}
def parse_process(src):
if not os.path.isdir(src):
return
pid = src.rsplit('-', 1)[1]
if not pid.isdigit():
return
pid = int(pid)
for folder in glob(os.path.join(src, '*', '*.sea')):
tid = int(os.path.basename(folder).split('!')[0].split('-')[0].split('.')[0])
tid_map[tid] = pid
if pid not in tid_map:
tid_map[pid] = pid
if not args.single:
for folder in glob(os.path.join(path, '*-*')):
parse_process(folder)
else:
parse_process(path)
return tid_map
def parse_jit(tree, path):
if tree['process']['bits'] == 64:
pointer = {'code': 'Q', 'size': 8}
else:
pointer = {'code': 'I', 'size': 4}
addr_list = []
with open(path, 'rb') as file:
prev_addr = 0
while True:
chunk = file.read(4 + pointer['size'] + 4 + 4)
if not chunk:
break
method_id, load_address, method_size, table_size = struct.unpack('I' + pointer['code'] + 'I' + 'I', chunk)
data = {'id': method_id, 'addr': load_address, 'size': method_size, 'lines': []}
for i in range(table_size):
chunk = file.read(4 + 4)
offset_line = struct.unpack('II', chunk)
if not data['lines'] or offset_line != data['lines'][-1]:
data['lines'].append(offset_line)
names = []
for i in range(3):
chunk = file.read(2) # uint16_t
length = struct.unpack('H', chunk)[0]
names.append(file.read(length))
data['name'], data['class'], data['file'] = names
if load_address > prev_addr:
addr_list.append(data)
prev_addr = load_address
if addr_list:
tree['jit'] = {
'start': addr_list[0]['addr'],
'end': addr_list[-1]['addr'] + addr_list[-1]['size'],
'data': addr_list
}
def sea_reader(args): # reads the structure of .sea format folder into dictionary
folder = args.input
if not os.path.exists(folder):
print("""Error: folder "%s" doesn't exist""" % folder)
tree = default_tree(args)
pos = folder.rfind("-") # pid of the process is encoded right in the name of the folder
tree["pid"] = int(folder[pos + 1:])
folder = folder.replace("\\", "/").rstrip("/")
toplevel = next(os.walk(folder))
for filename in toplevel[2]:
with open("/".join([folder, filename]), "r") as file:
if filename.endswith(".str"): # each string_handle_create writes separate file, name is the handle, content is the value
tree["strings"][int(filename.replace(".str", ""))] = file.readline()
elif filename.endswith(".tid"): # named thread makes record: name is the handle and content is the value
tree["threads"][filename.replace(".tid", "")] = file.readline()
elif filename.endswith(".pid"): # named groups (pseudo pids) makes record: group is the handle and content is the value
tree["groups"][filename.replace(".pid", "")] = file.readline()
for domain in toplevel[1]: # data from every domain gets recorded into separate folder which is named after the domain name
tree["domains"][domain] = {"files": []}
for file in next(os.walk("/".join([folder, domain])))[2]: # each thread of this domain has separate file with data
if not file.endswith(".sea"):
print("Warning: weird file found:", file)
continue
filename = file[:-4]
tree["ring_buffer"] = tree["ring_buffer"] or ('-' in filename)
tid = int(filename.split("!")[0].split("-")[0])
tree["cuts"].add(split_filename(filename)['cut'])
tree["domains"][domain]["files"].append((tid, "/".join([folder, domain, file])))
def time_sort(item):
with open(item[1], "rb") as file:
tuple = read_chunk_header(file)
return tuple[0]
tree["domains"][domain]["files"].sort(key=time_sort)
return tree
g_progress_interceptor = None
verbose_progress = True
# FIXME: doesn't belong this file, move to 'utils'
class Progress:
def __init__(self, total, steps, message=""):
self.total = total
self.steps = steps
self.shown_steps = -1
self.message = message
self.last_tick = None
def __enter__(self):
return self
def time_to_tick(self, interval=1):
return (datetime.now() - self.last_tick).total_seconds() > interval if self.last_tick else True
def tick(self, current):
self.last_tick = datetime.now()
if g_progress_interceptor:
g_progress_interceptor(self.message, current, self.total)
if self.total:
self.show_progress(int(self.steps * current / self.total), float(current) / self.total)
def show_progress(self, show_steps, percentage):
if self.shown_steps < show_steps: