forked from dotnet/coreclr
-
Notifications
You must be signed in to change notification settings - Fork 0
/
superpmi.py
executable file
·1634 lines (1239 loc) · 67 KB
/
superpmi.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
#!/usr/bin/env python
#
## Licensed to the .NET Foundation under one or more agreements.
## The .NET Foundation licenses this file to you under the MIT license.
## See the LICENSE file in the project root for more information.
#
##
# Title : superpmi.py
#
# Notes:
#
# Script to handle running SuperPMI Collections, and replays. In addition, this
# script provides support for SuperPMI ASM diffs. Note that some of the options
# provided by this script are also provided in our SuperPMI collect test. The
# test can be found here: https://github.com/dotnet/coreclr/blob/master/tests/src/JIT/superpmi/superpmicollect.cs.
#
################################################################################
################################################################################
import argparse
import datetime
import json
import math
import os
import platform
import shutil
import subprocess
import sys
import tempfile
import time
import re
import string
import zipfile
import xml.etree.ElementTree
from collections import defaultdict
from sys import platform as _platform
# Version specific imports
if sys.version_info.major < 3:
import urllib
else:
import urllib.request
from coreclr_arguments import *
################################################################################
# Argument Parser
################################################################################
description = ("""Script to handle running SuperPMI Collections, and replays. In addition, this
script provides support for SuperPMI ASM diffs. Note that some of the options
provided by this script are also provided in our SuperPMI collect test.""")
superpmi_collect_help = """ Command to run SuperPMI collect over. Note that there
cannot be any dotnet cli command invoked inside this command, as they will fail due
to the shim altjit being set.
"""
superpmi_replay_help = """ Location of the mch file to run a replay over. Note
that this may either be a location to a path on disk or a uri to download the
mch file and replay it.
"""
parser = argparse.ArgumentParser(description=description)
subparsers = parser.add_subparsers(dest='mode')
# subparser for collect
collect_parser = subparsers.add_parser("collect")
# Add required arguments
collect_parser.add_argument("collection_command", nargs=1, help=superpmi_collect_help)
collect_parser.add_argument("collection_args", nargs=1, help="Arguments to pass to the SuperPMI collect command.")
collect_parser.add_argument("--break_on_assert", dest="break_on_assert", default=False, action="store_true")
collect_parser.add_argument("--break_on_error", dest="break_on_error", default=False, action="store_true")
collect_parser.add_argument("-log_file", dest="log_file", default=None)
collect_parser.add_argument("-arch", dest="arch", nargs='?', default="x64")
collect_parser.add_argument("-build_type", dest="build_type", nargs='?', default="Checked")
collect_parser.add_argument("-test_location", dest="test_location", nargs="?", default=None)
collect_parser.add_argument("-core_root", dest="core_root", nargs='?', default=None)
collect_parser.add_argument("-product_location", dest="product_location", nargs='?', default=None)
collect_parser.add_argument("-coreclr_repo_location", dest="coreclr_repo_location", default=os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
collect_parser.add_argument("-test_env", dest="test_env", default=None)
collect_parser.add_argument("-output_mch_path", dest="output_mch_path", default=None)
collect_parser.add_argument("-run_from_coreclr_dir", dest="run_from_coreclr_dir", default=False)
collect_parser.add_argument("--use_zapdisable", dest="use_zapdisable", default=False, action="store_true", help="Allow redundant calls to the systems libraries for more coverage.")
collect_parser.add_argument("--assume_unclean_mch", dest="assume_unclean_mch", default=False, action="store_true", help="Force clean the mch file. This is useful if the dataset is large and there are expected dups.")
# Allow for continuing a collection in progress
collect_parser.add_argument("-existing_temp_dir", dest="existing_temp_dir", default=None, nargs="?")
collect_parser.add_argument("--has_run_collection_command", dest="has_run_collection_command", default=False, action="store_true")
collect_parser.add_argument("--has_merged_mch", dest="has_merged_mch", default=False, action="store_true")
collect_parser.add_argument("--has_verified_clean_mch", dest="has_verified_clean_mch", default=False, action="store_true")
collect_parser.add_argument("--skip_collect_mc_files", dest="skip_collect_mc_files", default=False, action="store_true")
collect_parser.add_argument("--skip_cleanup", dest="skip_cleanup", default=False, action="store_true")
# subparser for replay
replay_parser = subparsers.add_parser("replay")
# Add required arguments
replay_parser.add_argument("jit_path", nargs=1, help="Path to clrjit.")
replay_parser.add_argument("-mch_file", nargs=1, help=superpmi_replay_help)
replay_parser.add_argument("-log_file", dest="log_file", default=None)
replay_parser.add_argument("--break_on_assert", dest="break_on_assert", default=False, action="store_true")
replay_parser.add_argument("--break_on_error", dest="break_on_error", default=False, action="store_true")
replay_parser.add_argument("-arch", dest="arch", nargs='?', default="x64")
replay_parser.add_argument("-build_type", dest="build_type", nargs='?', default="Checked")
replay_parser.add_argument("-test_location", dest="test_location", nargs="?", default=None)
replay_parser.add_argument("-core_root", dest="core_root", nargs='?', default=None)
replay_parser.add_argument("-product_location", dest="product_location", nargs='?', default=None)
replay_parser.add_argument("-coreclr_repo_location", dest="coreclr_repo_location", default=os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
replay_parser.add_argument("-test_env", dest="test_env", default=None)
replay_parser.add_argument("-output_mch_path", dest="output_mch_path", default=None)
replay_parser.add_argument("-run_from_coreclr_dir", dest="run_from_coreclr_dir", default=False)
replay_parser.add_argument("--skip_collect_mc_files", dest="skip_collect_mc_files", default=False, action="store_true")
replay_parser.add_argument("--skip_cleanup", dest="skip_cleanup", default=False, action="store_true")
replay_parser.add_argument("--force_download", dest="force_download", default=False, action="store_true")
# subparser for asmDiffs
asm_diff_parser = subparsers.add_parser("asmdiffs")
# Add required arguments
asm_diff_parser.add_argument("base_jit_path", nargs=1, help="Path to baseline clrjit.")
asm_diff_parser.add_argument("diff_jit_path", nargs=1, help="Path to diff clrjit.")
asm_diff_parser.add_argument("-mch_file", nargs=1, help=superpmi_replay_help)
asm_diff_parser.add_argument("-log_file", dest="log_file", default=None)
asm_diff_parser.add_argument("--break_on_assert", dest="break_on_assert", default=False, action="store_true")
asm_diff_parser.add_argument("--break_on_error", dest="break_on_error", default=False, action="store_true")
asm_diff_parser.add_argument("-arch", dest="arch", nargs='?', default="x64")
asm_diff_parser.add_argument("-build_type", dest="build_type", nargs='?', default="Checked")
asm_diff_parser.add_argument("-test_location", dest="test_location", nargs="?", default=None)
asm_diff_parser.add_argument("-core_root", dest="core_root", nargs='?', default=None)
asm_diff_parser.add_argument("-product_location", dest="product_location", nargs='?', default=None)
asm_diff_parser.add_argument("-coreclr_repo_location", dest="coreclr_repo_location", default=os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
asm_diff_parser.add_argument("-test_env", dest="test_env", default=None)
asm_diff_parser.add_argument("-output_mch_path", dest="output_mch_path", default=None)
asm_diff_parser.add_argument("-run_from_coreclr_dir", dest="run_from_coreclr_dir", default=False)
asm_diff_parser.add_argument("--skip_collect_mc_files", dest="skip_collect_mc_files", default=False, action="store_true")
asm_diff_parser.add_argument("--skip_cleanup", dest="skip_cleanup", default=False, action="store_true")
asm_diff_parser.add_argument("--force_download", dest="force_download", default=False, action="store_true")
asm_diff_parser.add_argument("--diff_with_code", dest="diff_with_code", default=False, action="store_true")
asm_diff_parser.add_argument("--diff_with_code_only", dest="diff_with_code_only", default=False, action="store_true", help="Only run the diff command, do not run SuperPMI to regenerate diffs.")
asm_diff_parser.add_argument("--diff_jit_dump", dest="diff_jit_dump", default=False, action="store_true")
asm_diff_parser.add_argument("--diff_jit_dump_only", dest="diff_jit_dump_only", default=False, action="store_true", help="Only diff jitdumps, not asm.")
################################################################################
# Helper classes
################################################################################
class TempDir:
def __init__(self, path=None):
self.dir = tempfile.mkdtemp() if path is None else path
self.cwd = None
def __enter__(self):
self.cwd = os.getcwd()
os.chdir(self.dir)
return self.dir
def __exit__(self, exc_type, exc_val, exc_tb):
os.chdir(self.cwd)
if not args.skip_cleanup:
shutil.rmtree(self.dir)
class ChangeDir:
def __init__(self, dir):
self.dir = dir
self.cwd = None
def __enter__(self):
self.cwd = os.getcwd()
os.chdir(self.dir)
def __exit__(self, exc_type, exc_val, exc_tb):
os.chdir(self.cwd)
################################################################################
# SuperPMI Collect
################################################################################
class SuperPMICollect:
""" SuperPMI Collect class
Notes:
The object is responsible for setting up a super pmi collection given
the arguments passed into the script.
"""
def __init__(self, args):
""" Constructor
Args:
args (CoreclrArguments): parsed args
"""
if args.host_os == "OSX":
self.standalone_jit_name = "libclrjit.dylib"
self.collection_shim_name = "libsuperpmi-shim-collector.dylib"
self.superpmi_tool_name = "superpmi"
self.mcs_tool_name = "mcs"
elif args.host_os == "Linux":
self.standalone_jit_name = "libclrjit.so"
self.collection_shim_name = "libsuperpmi-shim-collector.so"
self.superpmi_tool_name = "superpmi"
self.mcs_tool_name = "mcs"
elif args.host_os == "Windows_NT":
self.standalone_jit_name = "clrjit.dll"
self.collection_shim_name = "superpmi-shim-collector.dll"
self.superpmi_tool_name = "superpmi.exe"
self.mcs_tool_name = "mcs.exe"
else:
raise RuntimeError("Unsupported OS.")
self.jit_path = os.path.join(args.core_root, self.standalone_jit_name)
self.superpmi_path = os.path.join(args.core_root, self.superpmi_tool_name)
self.mcs_path = os.path.join(args.core_root, self.mcs_tool_name)
self.coreclr_args = args
self.command = self.coreclr_args.collection_command
self.args = self.coreclr_args.collection_args
############################################################################
# Instance Methods
############################################################################
def collect(self):
""" Do the SuperPMI Collection.
"""
# Pathname for a temporary .MCL file used for noticing SuperPMI replay failures against base MCH.
self.base_fail_mcl_file = None
# Pathname for a temporary .MCL file used for noticing SuperPMI replay failures against final MCH.
self.final_fail_mcl_file = None
# The base .MCH file path
self.base_mch_file = None
# Clean .MCH file path
self.clean_mch_file = None
# Final .MCH file path
self.final_mch_file = None
# The .TOC file path for the clean thin unique .MCH file
self.toc_file = None
self.save_the_final_mch_file = False
# Do a basic SuperPMI collect and validation:
# 1. Collect MC files by running a set of sample apps.
# 2. Merge the MC files into a single MCH using "mcs -merge *.mc -recursive".
# 3. Create a clean MCH by running SuperPMI over the MCH, and using "mcs -strip" to filter
# out any failures (if any).
# 4. Create a thin unique MCH by using "mcs -removeDup -thin".
# 5. Create a TOC using "mcs -toc".
# 6. Verify the resulting MCH file is error-free when running SuperPMI against it with the
# same JIT used for collection.
#
# MCH files are big. If we don't need them anymore, clean them up right away to avoid
# running out of disk space in disk constrained situations.
passed = False
try:
with TempDir(self.coreclr_args.existing_temp_dir) as temp_location:
# Setup all of the temp locations
self.base_fail_mcl_file = os.path.join(temp_location, "basefail.mcl")
self.final_fail_mcl_file = os.path.join(temp_location, "finalfail.mcl")
self.base_mch_file = os.path.join(temp_location, "base.mch")
self.clean_mch_file = os.path.join(temp_location, "clean.mch")
self.temp_location = temp_location
if self.coreclr_args.output_mch_path is not None:
self.save_the_final_mch_file = True
self.final_mch_file = os.path.abspath(self.coreclr_args.output_mch_path)
self.toc_file = self.final_mch_file + ".mct"
else:
self.save_the_final_mch_file = True
default_coreclr_bin_mch_location = self.coreclr_args.default_coreclr_bin_mch_location
self.final_mch_file = os.path.join(default_coreclr_bin_mch_location, "{}.{}.{}.mch".format(self.coreclr_args.host_os, self.coreclr_args.arch, self.coreclr_args.build_type))
self.toc_file = "{}.mct".format(self.final_mch_file)
# If we have passed existing_temp_dir, then we have a few flags we need
# to check to see where we are in the collection process. Note that this
# functionality exists to help not lose progress during a SuperPMI collection.
# It is not unreasonable for the SuperPMI collection to take many hours
# therefore allow re-use of a collection in progress
if not self.coreclr_args.has_run_collection_command:
self.__collect_mc_files__(self.command, self.args)
if not self.coreclr_args.has_merged_mch:
self.__merge_mc_files__()
if not self.coreclr_args.has_verified_clean_mch:
self.__create_clean_mch_file__()
self.__create_thin_unique_mch__()
self.__create_toc__()
self.__verify_final_mch__()
passed = True
except Exception as exception:
print(exception)
return passed
############################################################################
# Helper Methods
############################################################################
def __collect_mc_files__(self, command, args):
""" Do the actual SuperPMI collection for a command
Args:
command (str) : script/executable to run
args ([str]) : arguments to pass
Returns:
None
"""
if not self.coreclr_args.skip_collect_mc_files:
assert os.path.isdir(self.temp_location)
# Set environment variables.
env_copy = os.environ.copy()
env_copy["SuperPMIShimLogPath"] = self.temp_location
env_copy["SuperPMIShimPath"] = self.jit_path
env_copy["COMPlus_AltJit"] = "*"
env_copy["COMPlus_AltJitName"] = self.collection_shim_name
if self.coreclr_args.use_zapdisable:
env_copy["COMPlus_ZapDisable"] = "1"
print("Starting collection.")
print("")
print_platform_specific_environment_vars(self.coreclr_args, "SuperPMIShimLogPath", self.temp_location)
print_platform_specific_environment_vars(self.coreclr_args, "SuperPMIShimPath", self.jit_path)
print_platform_specific_environment_vars(self.coreclr_args, "COMPlus_AltJit", "*")
print_platform_specific_environment_vars(self.coreclr_args, "COMPlus_AltJitName", self.collection_shim_name)
print("")
print("%s %s" % (command, " ".join(args)))
assert isinstance(command, str)
assert isinstance(args, list)
return_code = 1
command = [command] + args
proc = subprocess.Popen(command, env=env_copy)
proc.communicate()
return_code = proc.returncode
contents = os.listdir(self.temp_location)
mc_contents = [os.path.join(self.temp_location, item) for item in contents if ".mc" in item]
if len(mc_contents) == 0:
raise RuntimeError("No .mc files generated.")
self.mc_contents = mc_contents
def __merge_mc_files__(self):
""" Merge the mc files that were generated
Notes:
mcs -merge <s_baseMchFile> <s_tempDir>\*.mc -recursive
"""
pattern = os.path.join(self.temp_location, "*.mc")
command = [self.mcs_path, "-merge", self.base_mch_file, pattern, "-recursive"]
print("Invoking: " + " ".join(command))
proc = subprocess.Popen(command)
proc.communicate()
if not os.path.isfile(self.mcs_path):
raise RuntimeError("mch file failed to be generated at: %s" % self.mcs_path)
contents = os.listdir(self.temp_location)
mc_contents = [os.path.join(self.temp_location, item) for item in contents if ".mc" in item and not ".mch" in item]
# All the individual MC files are no longer necessary, now that we have
# merged them into the base.mch. Delete them.
if not self.coreclr_args.skip_cleanup:
for item in mc_contents:
os.remove(item)
def __create_clean_mch_file__(self):
""" Create a clean mch file based on the original
Notes:
<SuperPMIPath> -p -f <s_baseFailMclFile> <s_baseMchFile> <jitPath>
if <s_baseFailMclFile> is non-empty:
<mcl> -strip <s_baseFailMclFile> <s_baseMchFile> <s_cleanMchFile>
else
# no need to copy, just change the names
clean_mch_file = base_mch_file
del <s_baseFailMclFile>
"""
command = [self.superpmi_path, "-p", "-f", self.base_fail_mcl_file, self.base_mch_file, self.jit_path]
print (" ".join(command))
proc = subprocess.Popen(command)
proc.communicate()
if os.path.isfile(self.base_fail_mcl_file) and os.stat(self.base_fail_mcl_file).st_size != 0:
command = [self.mcs_path, "-strip", self.base_fail_mcl_file, self.base_mch_file, self.clean_mch_file]
print (" ".join(command))
proc = subprocess.Popen(command)
proc.communicate()
else:
self.clean_mch_file = self.base_mch_file
self.base_mch_file = None
if not os.path.isfile(self.clean_mch_file):
raise RuntimeError("Clean mch file failed to be generated.")
if not self.coreclr_args.skip_cleanup:
if os.path.isfile(self.base_fail_mcl_file):
os.remove(self.base_fail_mcl_file)
self.base_fail_mcl_file = None
# The base file is no longer used (unless there was no cleaning done, in which case
# self.base_mch_file has been set to None and clean_mch_File is the base file).
if os.path.isfile(self.base_mch_file):
os.remove(self.base_mch_file)
self.base_mch_file = None
def __create_thin_unique_mch__(self):
""" Create a thin unique MCH
Notes:
<mcl> -removeDup -thin <s_cleanMchFile> <s_finalMchFile>
"""
command = [self.mcs_path, "-removeDup", "-thin", self.clean_mch_file, self.final_mch_file]
proc = subprocess.Popen(command)
proc.communicate()
if not os.path.isfile(self.final_mch_file):
raise RuntimeError("Error, final mch file not created correctly.")
if not self.coreclr_args.skip_cleanup:
os.remove(self.clean_mch_file)
self.clean_mch_file = None
def __create_toc__(self):
""" Create a TOC file
Notes:
<mcl> -toc <s_finalMchFile>
"""
command = [self.mcs_path, "-toc", self.final_mch_file]
proc = subprocess.Popen(command)
proc.communicate()
if not os.path.isfile(self.toc_file):
raise RuntimeError("Error, toc file not created correctly.")
def __verify_final_mch__(self):
""" Verify the resulting MCH file is error-free when running SuperPMI against it with the same JIT used for collection.
Notes:
<superPmiPath> -p -f <s_finalFailMclFile> <s_finalMchFile> <jitPath>
"""
spmi_replay = SuperPMIReplay(self.coreclr_args, self.final_mch_file, self.jit_path)
passed = spmi_replay.replay()
if not passed:
raise RuntimeError("Error unclean replay.")
################################################################################
# SuperPMI Replay
################################################################################
class SuperPMIReplay:
""" SuperPMI Replay class
Notes:
The object is responsible for replaying the mch final given to the
instance of the class
"""
def __init__(self, coreclr_args, mch_file, jit_path):
""" Constructor
Args:
args (CoreclrArguments) : parsed args
mch_file (str) : final mch file from the collection
jit_path (str) : path to clrjit/libclrjit
"""
self.jit_path = jit_path
self.mch_file = mch_file
self.superpmi_path = os.path.join(coreclr_args.core_root, "superpmi")
self.coreclr_args = coreclr_args
############################################################################
# Instance Methods
############################################################################
def replay(self):
""" Replay the given SuperPMI collection
Returns:
sucessful_replay (bool)
"""
return_code = False
# Possible return codes from SuperPMI
#
# 0 : success
# -1 : general fatal error (e.g., failed to initialize, failed to read files)
# -2 : JIT failed to initialize
# 1 : there were compilation failures
# 2 : there were assembly diffs
with TempDir() as temp_location:
print("Starting SuperPMI replay.")
print("")
print("Temp Location: {}".format(temp_location))
print("")
self.fail_mcl_file = os.path.join(temp_location, "fail.mcl")
# TODO: add aljit support
#
# Set: -jitoption force AltJit=* -jitoption force AltJitNgen=*
force_altjit_options = [
"-jitoption",
"force",
"AltJit=",
"-jitoption",
"force",
"AltJitNgen="
]
flags = [
"-p", # Parallel
"-f", # Failing mc List
self.fail_mcl_file,
"-r", # Repro name, create .mc repro files
os.path.join(temp_location, "repro")
]
flags += force_altjit_options
if self.coreclr_args.break_on_assert:
flags += [
"-boa" # break on assert
]
if self.coreclr_args.break_on_error:
flags += [
"-boe" # break on error
]
if self.coreclr_args.log_file != None:
flags += [
"-w",
self.coreclr_args.log_file
]
command = [self.superpmi_path] + flags + [self.jit_path, self.mch_file]
print("Invoking: " + " ".join(command))
proc = subprocess.Popen(command)
proc.communicate()
return_code = proc.returncode
if return_code == 0:
print("Clean SuperPMI Replay")
return_code = True
if os.path.isfile(self.fail_mcl_file) and os.stat(self.fail_mcl_file).st_size != 0:
# Unclean replay.
#
# Save the contents of the fail.mcl file to dig into failures.
assert(return_code != 0)
if return_code == -1:
print("General fatal error.")
elif return_code == -2:
print("Jit failed to initialize.")
elif return_code == 1:
print("Complition failures.")
else:
print("Unknown error code.")
self.fail_mcl_contents = None
with open(self.fail_mcl_file) as file_handle:
self.fail_mcl_contents = file_handle.read()
# If there are any .mc files, drop them into bin/repro/<host_os>.<arch>.<build_type>/*.mc
mc_files = [os.path.join(temp_location, item) for item in os.listdir(temp_location) if item.endswith(".mc")]
if len(mc_files) > 0:
repro_location = os.path.join(self.coreclr_args.coreclr_repo_location, "bin", "repro", "{}.{}.{}".format(self.coreclr_args.host_os, self.coreclr_args.arch, self.coreclr_args.build_type))
# Delete existing repro location
if os.path.isdir(repro_location):
shutil.rmtree(repro_location)
assert(not os.path.isdir(repro_location))
os.makedirs(repro_location)
repro_files = []
for item in mc_files:
repro_files.append(os.path.join(repro_location, os.path.basename(item)))
shutil.copy2(item, repro_location)
print("")
print("Repro .mc files:")
print("")
for item in repro_files:
print(item)
print("")
print("To run an specific failure:")
print("")
print("<SuperPMI_path>/SuperPMI <core_root|product_dir>/clrjit.dll|libclrjit.so|libclrjit.dylib <<coreclr_path>/bin/repro/<host_os>.<arch>.<build_type>/1xxxx.mc")
print("")
else:
print(self.fail_mcl_contents)
if not self.coreclr_args.skip_cleanup:
if os.path.isfile(self.fail_mcl_file):
os.remove(self.fail_mcl_file)
self.fail_mcl_file = None
return_code == False
return return_code
################################################################################
# SuperPMI Replay/AsmDiffs
################################################################################
class SuperPMIReplayAsmDiffs:
""" SuperPMI Replay AsmDiffs class
Notes:
The object is responsible for replaying the mch final given to the
instance of the class and doing diffs on the two passed jits.
"""
def __init__(self, coreclr_args, mch_file, base_jit_path, diff_jit_path):
""" Constructor
Args:
args (CoreclrArguments) : parsed args
mch_file (str) : final mch file from the collection
base_jit_path (str) : path to clrjit/libclrjit
diff_jit_path (str) : path to clrjit/libclrjit
"""
self.base_jit_path = base_jit_path
self.diff_jit_path = diff_jit_path
self.mch_file = mch_file
self.superpmi_path = os.path.join(coreclr_args.core_root, "superpmi")
self.coreclr_args = coreclr_args
############################################################################
# Instance Methods
############################################################################
def replay_with_asm_diffs(self):
""" Replay the given SuperPMI collection
Returns:
sucessful_replay (bool)
"""
return_code = False
# Possible return codes from SuperPMI
#
# 0 : success
# -1 : general fatal error (e.g., failed to initialize, failed to read files)
# -2 : JIT failed to initialize
# 1 : there were compilation failures
# 2 : there were assembly diffs
with TempDir() as temp_location:
print("Starting SuperPMI AsmDiffs.")
print("")
print("Temp Location: {}".format(temp_location))
print("")
self.fail_mcl_file = os.path.join(temp_location, "fail.mcl")
self.diff_mcl_file = os.path.join(temp_location, "diff.mcl")
# TODO: add aljit support
#
# Set: -jitoption force AltJit=* -jitoption force AltJitNgen=*
force_altjit_options = [
"-jitoption",
"force",
"AltJit=",
"-jitoption",
"force",
"AltJitNgen=",
"-jit2option",
"force",
"AltJit=",
"-jit2option",
"force",
"AltJitNgen="
]
flags = [
"-a", # Asm diffs
"-p", # Parallel
"-f", # Failing mc List
self.fail_mcl_file,
"-diffMCList", # Create all of the diffs in an mcl file
self.diff_mcl_file,
"-r", # Repro name, create .mc repro files
os.path.join(temp_location, "repro")
]
flags += force_altjit_options
if self.coreclr_args.break_on_assert:
flags += [
"-boa" # break on assert
]
if self.coreclr_args.break_on_error:
flags += [
"-boe" # break on error
]
if self.coreclr_args.log_file != None:
flags += [
"-w",
self.coreclr_args.log_file
]
if not self.coreclr_args.diff_with_code_only:
# Change the working directory to the core root we will call SuperPMI from.
# This is done to allow libcoredistools to be loaded correctly on unix
# as the loadlibrary path will be relative to the current directory.
with ChangeDir(self.coreclr_args.core_root) as dir:
command = [self.superpmi_path] + flags + [self.base_jit_path, self.diff_jit_path, self.mch_file]
print("Invoking: " + " ".join(command))
proc = subprocess.Popen(command)
proc.communicate()
return_code = proc.returncode
if return_code == 0:
print("Clean SuperPMI Replay")
else:
return_code = 2
if os.path.isfile(self.fail_mcl_file) and os.stat(self.fail_mcl_file).st_size != 0:
# Unclean replay.
#
# Save the contents of the fail.mcl file to dig into failures.
assert(return_code != 0)
if return_code == -1:
print("General fatal error.")
elif return_code == -2:
print("Jit failed to initialize.")
elif return_code == 1:
print("Complition failures.")
elif return_code == 139 and self.coreclr_args != "Windows_NT":
print("Fatal error, SuperPMI has returned SIG_SEV (segmentation fault).")
else:
print("Unknown error code.")
self.fail_mcl_contents = None
mcl_lines = []
with open(self.fail_mcl_file) as file_handle:
mcl_lines = file_handle.readlines()
mcl_lines = [item.strip() for item in mcl_lines]
self.fail_mcl_contents = os.linesep.join(mcl_lines)
# If there are any .mc files, drop them into bin/repro/<host_os>.<arch>.<build_type>/*.mc
mc_files = [os.path.join(temp_location, item) for item in os.listdir(temp_location) if item.endswith(".mc")]
if len(mc_files) > 0:
repro_location = os.path.join(self.coreclr_args.coreclr_repo_location, "bin", "repro", "{}.{}.{}".format(self.coreclr_args.host_os, self.coreclr_args.arch, self.coreclr_args.build_type))
# Delete existing repro location
if os.path.isdir(repro_location):
shutil.rmtree(repro_location)
assert(not os.path.isdir(repro_location))
os.makedirs(repro_location)
repro_files = []
for item in mc_files:
repro_files.append(os.path.join(repro_location, os.path.basename(item)))
shutil.copy2(item, repro_location)
print("")
print("Repro .mc files:")
print("")
for item in repro_files:
print(item)
print("")
print("To run an specific failure:")
print("")
print("<SuperPMI_path>/SuperPMI <core_root|product_dir>/clrjit.dll|libclrjit.so|libclrjit.dylib <<coreclr_path>/bin/repro/<host_os>.<arch>.<build_type>/1xxxx.mc")
print("")
print(self.fail_mcl_contents)
# There were diffs. Go through each method that created diffs and
# create a base/diff asm file with diffable asm. In addition, create
# a standalone .mc for easy iteration.
if os.path.isfile(self.diff_mcl_file) and os.stat(self.diff_mcl_file).st_size != 0 or self.coreclr_args.diff_with_code_only:
# AsmDiffs.
#
# Save the contents of the fail.mcl file to dig into failures.
assert(return_code != 0)
if return_code == -1:
print("General fatal error.")
elif return_code == -2:
print("Jit failed to initialize.")
elif return_code == 1:
print("Complition failures.")
elif return_code == 139 and self.coreclr_args != "Windows_NT":
print("Fatal error, SuperPMI has returned SIG_SEV (segmentation fault).")
else:
print("Unknown error code.")
if not self.coreclr_args.diff_with_code_only:
self.diff_mcl_contents = None
with open(self.diff_mcl_file) as file_handle:
mcl_lines = file_handle.readlines()
mcl_lines = [item.strip() for item in mcl_lines]
self.diff_mcl_contents = mcl_lines
base_asm_location = os.path.join(self.coreclr_args.bin_location, "asm", "base")
diff_asm_location = os.path.join(self.coreclr_args.bin_location, "asm", "diff")
base_dump_location = os.path.join(self.coreclr_args.bin_location, "jit_dump", "base")
diff_dump_location = os.path.join(self.coreclr_args.bin_location, "jit_dump", "diff")
if not self.coreclr_args.diff_with_code_only:
# Delete the old asm.
# Create a diff and baseline directory
if os.path.isdir(base_asm_location):
shutil.rmtree(base_asm_location)
if os.path.isdir(diff_asm_location):
shutil.rmtree(diff_asm_location)
os.makedirs(base_asm_location)
os.makedirs(diff_asm_location)
assert(os.path.isdir(base_asm_location))
assert(os.path.isdir(diff_asm_location))
assert(len(os.listdir(base_asm_location)) == 0)
assert(len(os.listdir(diff_asm_location)) == 0)
if self.coreclr_args.diff_jit_dump:
# Create a diff and baseline directory for jit_dumps
if os.path.isdir(base_dump_location):
shutil.rmtree(base_dump_location)
if os.path.isdir(diff_dump_location):
shutil.rmtree(diff_dump_location)
os.makedirs(base_dump_location)
os.makedirs(diff_dump_location)
assert(os.path.isdir(base_dump_location))
assert(os.path.isdir(diff_dump_location))
assert(len(os.listdir(base_dump_location)) == 0)
assert(len(os.listdir(diff_dump_location)) == 0)
text_differences = []
jit_dump_differences = []
if not self.coreclr_args.diff_with_code_only:
for item in self.diff_mcl_contents:
# Setup to call SuperPMI for both the diff jit and the base
# jit
# TODO: add aljit support
#
# Set: -jitoption force AltJit=* -jitoption force AltJitNgen=*
force_altjit_options = [
"-jitoption",
"force",
"AltJit=",
"-jitoption",
"force",
"AltJitNgen="
]
flags = [
"-c",
item,
"-v",
"q" # only log from the jit.
]
flags += force_altjit_options
asm_env = os.environ.copy()
asm_env["COMPlus_JitDisasm"] = "*"
asm_env["COMPlus_JitUnwindDump"] = "*"
asm_env["COMPlus_JitEHDump"] = "*"
asm_env["COMPlus_JitDiffableDasm"] = "1"
asm_env["COMPlus_NgenDisasm"] = "*"
asm_env["COMPlus_NgenDump"] = "*"
asm_env["COMPlus_NgenUnwindDump"] = "*"
asm_env["COMPlus_NgenEHDump"] = "*"
asm_env["COMPlus_JitEnableNoWayAssert"] = "1"
asm_env["COMPlus_JitNoForceFallback"] = "1"
asm_env["COMPlus_JitRequired"] = "1"
jit_dump_env = os.environ.copy()
jit_dump_env["COMPlus_JitEnableNoWayAssert"] = "1"
jit_dump_env["COMPlus_JitNoForceFallback"] = "1"
jit_dump_env["COMPlus_JitRequired"] = "1"
jit_dump_env["COMPlus_JitDump"] = "*"
# Change the working directory to the core root we will call SuperPMI from.
# This is done to allow libcoredistools to be loaded correctly on unix
# as the loadlibrary path will be relative to the current directory.
with ChangeDir(self.coreclr_args.core_root) as dir:
command = [self.superpmi_path] + flags + [self.base_jit_path, self.mch_file]
# Generate diff and base asm
base_txt = None
diff_txt = None
with open(os.path.join(base_asm_location, "{}.asm".format(item)), 'w') as file_handle:
print("Invoking: " + " ".join(command))
proc = subprocess.Popen(command, env=asm_env, stdout=file_handle)
proc.communicate()