Merge pull request #11526 from mskvortsov/MulLong
[platform/upstream/coreclr.git] / tests / runtest.sh
1 #!/usr/bin/env bash
2
3 function print_usage {
4     echo ''
5     echo 'CoreCLR test runner script.'
6     echo ''
7     echo 'Typical command line:'
8     echo ''
9     echo 'coreclr/tests/runtest.sh'
10     echo '    --testRootDir="temp/Windows_NT.x64.Debug"'
11     echo '    --testNativeBinDir="coreclr/bin/obj/Linux.x64.Debug/tests"'
12     echo '    --coreClrBinDir="coreclr/bin/Product/Linux.x64.Debug"'
13     echo '    --mscorlibDir="windows/coreclr/bin/Product/Linux.x64.Debug"'
14     echo '    --coreFxBinDir="corefx/bin/runtime/netcoreapp-Linux-Debug-x64'
15     echo ''
16     echo 'Required arguments:'
17     echo '  --testRootDir=<path>             : Root directory of the test build (e.g. coreclr/bin/tests/Windows_NT.x64.Debug).'
18     echo '  --testNativeBinDir=<path>        : Directory of the native CoreCLR test build (e.g. coreclr/bin/obj/Linux.x64.Debug/tests).'
19     echo '  (Also required: Either --coreOverlayDir, or all of the switches --coreOverlayDir overrides)'
20     echo ''
21     echo 'Optional arguments:'
22     echo '  --coreOverlayDir=<path>          : Directory containing core binaries and test dependencies. If not specified, the'
23     echo '                                     default is testRootDir/Tests/coreoverlay. This switch overrides --coreClrBinDir,'
24     echo '                                     --mscorlibDir, and --coreFxBinDir.'
25     echo '  --coreClrBinDir=<path>           : Directory of the CoreCLR build (e.g. coreclr/bin/Product/Linux.x64.Debug).'
26     echo '  --mscorlibDir=<path>             : Directory containing the built mscorlib.dll. If not specified, it is expected to be'
27     echo '                                       in the directory specified by --coreClrBinDir.'
28     echo '  --coreFxBinDir="<path>"          : Directory with CoreFX build outputs'
29     echo '                                     (e.g. "corefx/bin/runtime/netcoreapp-Linux-Debug-x64")'
30     echo '                                     If files with the same name are present in multiple directories, the first one wins.'
31     echo '  --testDir=<path>                 : Run tests only in the specified directory. The path is relative to the directory'
32     echo '                                     specified by --testRootDir. Multiple of this switch may be specified.'
33     echo '  --testDirFile=<path>             : Run tests only in the directories specified by the file at <path>. Paths are listed'
34     echo '                                     one line, relative to the directory specified by --testRootDir.'
35     echo '  --runFailingTestsOnly            : Run only the tests that are disabled on this platform due to unexpected failures.'
36     echo '                                     Failing tests are listed in coreclr/tests/failingTestsOutsideWindows.txt, one per'
37     echo '                                     line, as paths to .sh files relative to the directory specified by --testRootDir.'
38     echo '  --disableEventLogging            : Disable the events logged by both VM and Managed Code'
39     echo '  --sequential                     : Run tests sequentially (default is to run in parallel).'
40     echo '  --playlist=<path>                : Run only the tests that are specified in the file at <path>, in the same format as'
41     echo '                                     runFailingTestsOnly'
42     echo '  -v, --verbose                    : Show output from each test.'
43     echo '  -h|--help                        : Show usage information.'
44     echo '  --useServerGC                    : Enable server GC for this test run'
45     echo '  --test-env                       : Script to set environment variables for tests'
46     echo '  --crossgen                       : Precompiles the framework managed assemblies'
47     echo '  --runcrossgentests               : Runs the ready to run tests' 
48     echo '  --jitstress=<n>                  : Runs the tests with COMPlus_JitStress=n'
49     echo '  --jitstressregs=<n>              : Runs the tests with COMPlus_JitStressRegs=n'
50     echo '  --jitminopts                     : Runs the tests with COMPlus_JITMinOpts=1'
51     echo '  --jitforcerelocs                 : Runs the tests with COMPlus_ForceRelocs=1'
52     echo '  --jitdisasm                      : Runs jit-dasm on the tests'
53     echo '  --gcstresslevel=<n>              : Runs the tests with COMPlus_GCStress=n'
54     echo '  --ilasmroundtrip                 : Runs ilasm round trip on the tests'
55     echo '    0: None                                1: GC on all allocs and '"'easy'"' places'
56     echo '    2: GC on transitions to preemptive GC  4: GC on every allowable JITed instr'
57     echo '    8: GC on every allowable NGEN instr   16: GC only on a unique stack trace'
58     echo '  --long-gc                        : Runs the long GC tests'
59     echo '  --gcsimulator                    : Runs the GCSimulator tests'
60     echo '  --link <ILlink>                  : Runs the tests after linking via ILlink'
61     echo '  --show-time                      : Print execution sequence and running time for each test'
62     echo '  --no-lf-conversion               : Do not execute LF conversion before running test script'
63     echo '  --build-overlay-only             : Exit after overlay directory is populated'
64     echo '  --limitedDumpGeneration          : Enables the generation of a limited number of core dumps if test(s) crash, even if ulimit'
65     echo '                                     is zero when launching this script. This option is intended for use in CI.'
66     echo '  --xunitOutputPath=<path>         : Create xUnit XML report at the specifed path (default: <test root>/coreclrtests.xml)'
67     echo ''
68     echo 'Runtime Code Coverage options:'
69     echo '  --coreclr-coverage               : Optional argument to get coreclr code coverage reports'
70     echo '  --coreclr-objs=<path>            : Location of root of the object directory'
71     echo '                                     containing the linux/mac coreclr build'
72     echo '  --coreclr-src=<path>             : Location of root of the directory'
73     echo '                                     containing the coreclr source files'
74     echo '  --coverage-output-dir=<path>     : Directory where coverage output will be written to'
75     echo ''
76 }
77
78 function print_results {
79     echo ""
80     echo "======================="
81     echo "     Test Results"
82     echo "======================="
83     echo "# CoreCLR Bin Dir  : $coreClrBinDir"
84     echo "# Tests Discovered : $countTotalTests"
85     echo "# Passed           : $countPassedTests"
86     echo "# Failed           : $countFailedTests"
87     echo "# Skipped          : $countSkippedTests"
88     echo "======================="
89 }
90
91 # Initialize counters for bookkeeping.
92 countTotalTests=0
93 countPassedTests=0
94 countFailedTests=0
95 countSkippedTests=0
96
97 # Variables for xUnit-style XML output. XML format: https://xunit.github.io/docs/format-xml-v2.html
98 xunitOutputPath=
99 xunitTestOutputPath=
100
101 # libExtension determines extension for dynamic library files
102 # runtimeName determines where CoreFX Runtime files will be located
103 OSName=$(uname -s)
104 libExtension=
105 case $OSName in
106     Darwin)
107         libExtension="dylib"
108         ;;
109
110     Linux)
111         libExtension="so"
112         ;;
113
114     NetBSD)
115         libExtension="so"
116         ;;
117
118     *)
119         echo "Unsupported OS $OSName detected, configuring as if for Linux"
120         libExtension="so"
121         ;;
122 esac
123
124 function xunit_output_begin {
125     xunitOutputPath=$testRootDir/coreclrtests.xml
126     xunitTestOutputPath=${xunitOutputPath}.test
127     if [ -e "$xunitOutputPath" ]; then
128         rm -f -r "$xunitOutputPath"
129     fi
130     if [ -e "$xunitTestOutputPath" ]; then
131         rm -f -r "$xunitTestOutputPath"
132     fi
133 }
134
135 function xunit_output_add_test {
136     # <assemblies>
137     #   <assembly>
138     #     <collection>
139     #       <test .../> <!-- Write this element here -->
140
141     local scriptFilePath=$1
142     local outputFilePath=$2
143     local testResult=$3 # Pass, Fail, or Skip
144     local testScriptExitCode=$4
145
146     local testPath=${scriptFilePath%.sh} # Remove trailing ".sh"
147     local testDir=$(dirname "$testPath")
148     local testName=$(basename "$testPath")
149
150     # Replace '/' with '.'
151     testPath=$(echo "$testPath" | tr / .)
152     testDir=$(echo "$testDir" | tr / .)
153
154     local line
155
156     line="      "
157     line="${line}<test"
158     line="${line} name=\"${testPath}\""
159     line="${line} type=\"${testDir}\""
160     line="${line} method=\"${testName}\""
161     line="${line} result=\"${testResult}\""
162
163     if [ "$testResult" == "Pass" ]; then
164         line="${line}/>"
165         echo "$line" >>"$xunitTestOutputPath"
166         return
167     fi
168
169     line="${line}>"
170     echo "$line" >>"$xunitTestOutputPath"
171
172     line="        "
173     if [ "$testResult" == "Skip" ]; then
174         line="${line}<reason><![CDATA[$(cat "$outputFilePath")]]></reason>"
175         echo "$line" >>"$xunitTestOutputPath"
176     else
177         line="${line}<failure exception-type=\"Exit code: ${testScriptExitCode}\">"
178         echo "$line" >>"$xunitTestOutputPath"
179
180         line="          "
181         line="${line}<message>"
182         echo "$line" >>"$xunitTestOutputPath"
183         line="            "
184         line="${line}<![CDATA["
185         echo "$line" >>"$xunitTestOutputPath"
186         cat "$outputFilePath" >>"$xunitTestOutputPath"
187         line="            "
188         line="${line}]]>"
189         echo "$line" >>"$xunitTestOutputPath"
190         line="          "
191         line="${line}</message>"
192         echo "$line" >>"$xunitTestOutputPath"
193
194         line="        "
195         line="${line}</failure>"
196         echo "$line" >>"$xunitTestOutputPath"
197     fi
198
199     line="      "
200     line="${line}</test>"
201     echo "$line" >>"$xunitTestOutputPath"
202 }
203
204 function xunit_output_end {
205     local errorSource=$1
206     local errorMessage=$2
207
208     local errorCount
209     if [ -z "$errorSource" ]; then
210         ((errorCount = 0))
211     else
212         ((errorCount = 1))
213     fi
214
215     echo '<?xml version="1.0" encoding="utf-8"?>' >>"$xunitOutputPath"
216     echo '<assemblies>' >>"$xunitOutputPath"
217
218     local line
219
220     # <assembly ...>
221     line="  "
222     line="${line}<assembly"
223     line="${line} name=\"CoreClrTestAssembly\""
224     line="${line} total=\"${countTotalTests}\""
225     line="${line} passed=\"${countPassedTests}\""
226     line="${line} failed=\"${countFailedTests}\""
227     line="${line} skipped=\"${countSkippedTests}\""
228     line="${line} errors=\"${errorCount}\""
229     line="${line}>"
230     echo "$line" >>"$xunitOutputPath"
231
232     # <collection ...>
233     line="    "
234     line="${line}<collection"
235     line="${line} name=\"CoreClrTestCollection\""
236     line="${line} total=\"${countTotalTests}\""
237     line="${line} passed=\"${countPassedTests}\""
238     line="${line} failed=\"${countFailedTests}\""
239     line="${line} skipped=\"${countSkippedTests}\""
240     line="${line}>"
241     echo "$line" >>"$xunitOutputPath"
242
243     # <test .../> <test .../> ...
244     if [ -f "$xunitTestOutputPath" ]; then
245         cat "$xunitTestOutputPath" >>"$xunitOutputPath"
246         rm -f "$xunitTestOutputPath"
247     fi
248
249     # </collection>
250     line="    "
251     line="${line}</collection>"
252     echo "$line" >>"$xunitOutputPath"
253
254     if [ -n "$errorSource" ]; then
255         # <errors>
256         line="    "
257         line="${line}<errors>"
258         echo "$line" >>"$xunitOutputPath"
259
260         # <error ...>
261         line="      "
262         line="${line}<error"
263         line="${line} type=\"TestHarnessError\""
264         line="${line} name=\"${errorSource}\""
265         line="${line}>"
266         echo "$line" >>"$xunitOutputPath"
267
268         # <failure .../>
269         line="        "
270         line="${line}<failure>${errorMessage}</failure>"
271         echo "$line" >>"$xunitOutputPath"
272
273         # </error>
274         line="      "
275         line="${line}</error>"
276         echo "$line" >>"$xunitOutputPath"
277
278         # </errors>
279         line="    "
280         line="${line}</errors>"
281         echo "$line" >>"$xunitOutputPath"
282     fi
283
284     # </assembly>
285     line="  "
286     line="${line}</assembly>"
287     echo "$line" >>"$xunitOutputPath"
288
289     # </assemblies>
290     echo '</assemblies>' >>"$xunitOutputPath"
291 }
292
293 function exit_with_error {
294     local errorSource=$1
295     local errorMessage=$2
296     local printUsage=$3
297
298     if [ -z "$printUsage" ]; then
299         ((printUsage = 0))
300     fi
301
302     echo "$errorMessage"
303     xunit_output_end "$errorSource" "$errorMessage"
304     if ((printUsage != 0)); then
305         print_usage
306     fi
307     exit $EXIT_CODE_EXCEPTION
308 }
309
310 # Handle Ctrl-C. We will stop execution and print the results that
311 # we gathered so far.
312 function handle_ctrl_c {
313     local errorSource='handle_ctrl_c'
314
315     echo ""
316     echo "*** Stopping... ***"
317     print_results
318     exit_with_error "$errorSource" "Test run aborted by Ctrl+C."
319 }
320
321 # Register the Ctrl-C handler
322 trap handle_ctrl_c INT
323
324 function create_core_overlay {
325     local errorSource='create_core_overlay'
326     local printUsage=1
327
328     if [ -n "$coreOverlayDir" ]; then
329         export CORE_ROOT="$coreOverlayDir"
330         return
331     fi
332
333     # Check inputs to make sure we have enough information to create the core layout. $testRootDir/Tests/Core_Root should
334     # already exist and contain test dependencies that are not built.
335     local testDependenciesDir=$testRootDir/Tests/Core_Root
336     if [ ! -d "$testDependenciesDir" ]; then
337         exit_with_error "$errorSource" "Did not find the test dependencies directory: $testDependenciesDir"
338     fi
339     if [ -z "$coreClrBinDir" ]; then
340         exit_with_error "$errorSource" "One of --coreOverlayDir or --coreClrBinDir must be specified." "$printUsage"
341     fi
342     if [ ! -d "$coreClrBinDir" ]; then
343         exit_with_error "$errorSource" "Directory specified by --coreClrBinDir does not exist: $coreClrBinDir"
344     fi
345     if [ -z "$coreFxBinDir" ]; then
346         exit_with_error "$errorSource" "One of --coreOverlayDir or --coreFxBinDir must be specified." "$printUsage"
347     fi
348
349     # Create the overlay
350     coreOverlayDir=$testRootDir/Tests/coreoverlay
351     export CORE_ROOT="$coreOverlayDir"
352     if [ -e "$coreOverlayDir" ]; then
353         rm -f -r "$coreOverlayDir"
354     fi
355     mkdir "$coreOverlayDir"
356
357     cp -f -v "$coreFxBinDir/"* "$coreOverlayDir/" 2>/dev/null
358     cp -f -p -v "$coreClrBinDir/"* "$coreOverlayDir/" 2>/dev/null
359     if [ -d "$mscorlibDir/bin" ]; then
360         cp -f -v "$mscorlibDir/bin/"* "$coreOverlayDir/" 2>/dev/null
361     fi
362     cp -f -v "$testDependenciesDir/"xunit* "$coreOverlayDir/" 2>/dev/null
363     cp -n -v "$testDependenciesDir/"* "$coreOverlayDir/" 2>/dev/null
364     if [ -f "$coreOverlayDir/mscorlib.ni.dll" ]; then
365         # Test dependencies come from a Windows build, and mscorlib.ni.dll would be the one from Windows
366         rm -f "$coreOverlayDir/mscorlib.ni.dll"
367     fi
368     if [ -f "$coreOverlayDir/System.Private.CoreLib.ni.dll" ]; then
369         # Test dependencies come from a Windows build, and System.Private.CoreLib.ni.dll would be the one from Windows
370         rm -f "$coreOverlayDir/System.Private.CoreLib.ni.dll"
371     fi
372     copy_test_native_bin_to_test_root
373 }
374
375 declare -a skipCrossGenFiles
376
377 function is_skip_crossgen_test {
378     for skip in "${skipCrossGenFiles[@]}"; do
379         if [ "$1" == "$skip" ]; then
380             return 0
381         fi
382     done
383     return 1
384 }
385
386 function precompile_overlay_assemblies {
387     skipCrossGenFiles=($(read_array "$(dirname "$0")/skipCrossGenFiles.$ARCH.txt"))
388
389     if [ $doCrossgen == 1 ]; then
390         local overlayDir=$CORE_ROOT
391
392         filesToPrecompile=$(find -L $overlayDir -iname \*.dll -not -iname \*.ni.dll -not -iname \*-ms-win-\* -type f )
393         for fileToPrecompile in ${filesToPrecompile}
394         do
395             local filename=${fileToPrecompile}
396             if [ $jitdisasm == 1 ]; then
397                 $overlayDir/corerun $overlayDir/jit-dasm.dll --crossgen $overlayDir/crossgen --platform $overlayDir --output $testRootDir/dasm $filename
398                 local exitCode=$?
399                 if [ $exitCode != 0 ]; then
400                     echo Unable to generate dasm for $filename
401                 fi
402             else
403                 if is_skip_crossgen_test "$(basename $filename)"; then
404                     continue
405                 fi
406                 echo Precompiling $filename
407                 $overlayDir/crossgen /Platform_Assemblies_Paths $overlayDir $filename 1> $filename.stdout 2>$filename.stderr
408                 local exitCode=$?
409                 if [[ $exitCode != 0 ]]; then
410                     if grep -q -e '0x80131018' $filename.stderr; then
411                         printf "\n\t$filename is not a managed assembly.\n\n"
412                     else
413                         echo Unable to precompile $filename.
414                         cat $filename.stdout
415                         cat $filename.stderr
416                         exit $exitCode
417                     fi
418                 else
419                     rm $filename.{stdout,stderr}
420                 fi
421             fi
422         done
423     else
424         echo Skipping crossgen of FX assemblies.
425     fi
426 }
427
428 function copy_test_native_bin_to_test_root {
429     local errorSource='copy_test_native_bin_to_test_root'
430
431     if [ -z "$testNativeBinDir" ]; then
432         exit_with_error "$errorSource" "--testNativeBinDir is required."
433     fi
434     testNativeBinDir=$testNativeBinDir/src
435     if [ ! -d "$testNativeBinDir" ]; then
436         exit_with_error "$errorSource" "Directory specified by --testNativeBinDir does not exist: $testNativeBinDir"
437     fi
438
439     # Copy native test components from the native test build into the respective test directory in the test root directory
440     find "$testNativeBinDir" -type f -iname '*.$libExtension' |
441         while IFS='' read -r filePath || [ -n "$filePath" ]; do
442             local dirPath=$(dirname "$filePath")
443             local destinationDirPath=${testRootDir}${dirPath:${#testNativeBinDir}}
444             if [ ! -d "$destinationDirPath" ]; then
445                 exit_with_error "$errorSource" "Cannot copy native test bin '$filePath' to '$destinationDirPath/', as the destination directory does not exist."
446             fi
447             cp -f "$filePath" "$destinationDirPath/"
448         done
449 }
450
451 # Variables for unsupported and failing tests
452 declare -a unsupportedTests
453 declare -a failingTests
454 declare -a playlistTests
455 ((runFailingTestsOnly = 0))
456
457 # Get an array of items by reading the specified file line by line.
458 function read_array {
459     local theArray=()
460
461     # bash in Mac OS X doesn't support 'readarray', so using alternate way instead.
462     # readarray -t theArray < "$1"
463     while IFS='' read -r line || [ -n "$line" ]; do
464         theArray[${#theArray[@]}]=$line
465     done < "$1"
466     echo ${theArray[@]}
467 }
468
469 function load_unsupported_tests {
470     # Load the list of tests that are not supported on this platform. These tests are disabled (skipped) permanently.
471     unsupportedTests=($(read_array "$(dirname "$0")/testsUnsupportedOutsideWindows.txt"))
472     if [ "$ARCH" == "arm" ]; then
473         unsupportedTests+=($(read_array "$(dirname "$0")/testsUnsupportedOnARM32.txt"))
474     fi
475 }
476
477 function load_failing_tests {
478     # Load the list of tests that fail on this platform. These tests are disabled (skipped) temporarily, pending investigation.
479     failingTests=($(read_array "$(dirname "$0")/testsFailingOutsideWindows.txt"))
480 }
481
482 function load_playlist_tests {
483     # Load the list of tests that are enabled as a part of this test playlist.
484     playlistTests=($(read_array "${playlistFile}"))
485 }
486
487 function is_unsupported_test {
488     for unsupportedTest in "${unsupportedTests[@]}"; do
489         if [ "$1" == "$unsupportedTest" ]; then
490             return 0
491         fi
492     done
493     return 1
494 }
495
496 function is_failing_test {
497     for failingTest in "${failingTests[@]}"; do
498         if [ "$1" == "$failingTest" ]; then
499             return 0
500         fi
501     done
502     return 1
503 }
504
505 function is_playlist_test {
506     for playlistTest in "${playlistTests[@]}"; do
507         if [ "$1" == "$playlistTest" ]; then
508             return 0
509         fi
510     done
511     return 1
512 }
513
514 function skip_unsupported_test {
515     # This function runs in a background process. It should not echo anything, and should not use global variables. This
516     # function is analogous to run_test, and causes the test to be skipped with the message below.
517
518     local scriptFilePath=$1
519     local outputFilePath=$2
520
521     echo "Not supported on this platform." >"$outputFilePath"
522     return 2 # skip the test
523 }
524
525 function skip_failing_test {
526     # This function runs in a background process. It should not echo anything, and should not use global variables. This
527     # function is analogous to run_test, and causes the test to be skipped with the message below.
528
529     local scriptFilePath=$1
530     local outputFilePath=$2
531
532     echo "Temporarily disabled on this platform due to unexpected failures." >"$outputFilePath"
533     return 2 # skip the test
534 }
535
536 function skip_non_playlist_test {
537     # This function runs in a background process. It should not echo anything, and should not use global variables. This
538     # function is analogous to run_test, and causes the test to be skipped with the message below.
539
540     local scriptFilePath=$1
541     local outputFilePath=$2
542
543     echo "Test is not included in the running playlist." >"$outputFilePath"
544     return 2 # skip the test
545 }
546
547 function set_up_core_dump_generation {
548     # We will only enable dump generation here if we're on Mac or Linux
549     if [[ ! ( "$(uname -s)" == "Darwin" || "$(uname -s)" == "Linux" ) ]]; then
550         return
551     fi
552
553     # We won't enable dump generation on OS X/macOS if the machine hasn't been
554     # configured with the kern.corefile pattern we expect.
555     if [[ ( "$(uname -s)" == "Darwin" && "$(sysctl -n kern.corefile)" != "core.%P" ) ]]; then
556         echo "WARNING: Core dump generation not being enabled due to unexpected kern.corefile value."
557         return
558     fi
559
560     # Allow dump generation
561     ulimit -c unlimited
562
563     if [ "$(uname -s)" == "Linux" ]; then
564         if [ -e /proc/self/coredump_filter ]; then
565             # Include memory in private and shared file-backed mappings in the dump.
566             # This ensures that we can see disassembly from our shared libraries when
567             # inspecting the contents of the dump. See 'man core' for details.
568             echo 0x3F > /proc/self/coredump_filter
569         fi
570     fi
571 }
572
573 function print_info_from_core_file {
574     local core_file_name=$1
575     local executable_name=$2
576
577     if ! [ -e $executable_name ]; then
578         echo "Unable to find executable $executable_name"
579         return
580     elif ! [ -e $core_file_name ]; then
581         echo "Unable to find core file $core_file_name"
582         return
583     fi
584
585     # Use LLDB to inspect the core dump on Mac, and GDB everywhere else.
586     if [[ "$OSName" == "Darwin" ]]; then
587         hash lldb 2>/dev/null || { echo >&2 "LLDB was not found. Unable to print core file."; return; }
588
589         echo "Printing info from core file $core_file_name"
590         lldb -c $core_file_name -b -o 'bt'
591     else
592         # Use GDB to print the backtrace from the core file.
593         hash gdb 2>/dev/null || { echo >&2 "GDB was not found. Unable to print core file."; return; }
594
595         echo "Printing info from core file $core_file_name"
596         gdb --batch -ex "thread apply all bt full" -ex "quit" $executable_name $core_file_name
597     fi
598 }
599
600 function download_dumpling_script {
601     echo "Downloading latest version of dumpling script."
602     wget "https://dumpling.azurewebsites.net/api/client/dumpling.py"
603
604     local dumpling_script="dumpling.py"
605     chmod +x $dumpling_script
606 }
607
608 function upload_core_file_to_dumpling {
609     local core_file_name=$1
610     local dumpling_script="dumpling.py"
611     local dumpling_file="local_dumplings.txt"
612
613     # dumpling requires that the file exist before appending.
614     touch ./$dumpling_file
615
616     if [ ! -x $dumpling_script ]; then
617         download_dumpling_script
618     fi
619
620     if [ ! -x $dumpling_script ]; then
621         echo "Failed to download dumpling script. Dump cannot be uploaded."
622         return
623     fi
624
625     echo "Uploading $core_file_name to dumpling service."
626
627     local paths_to_add=""
628     if [ -d "$coreClrBinDir" ]; then
629         echo "Uploading CoreCLR binaries with dump."
630         paths_to_add=$coreClrBinDir
631     fi
632
633     # Ensure the script has Unix line endings
634     perl -pi -e 's/\r\n|\n|\r/\n/g' "$dumpling_script"
635
636     # The output from this will include a unique ID for this dump.
637     ./$dumpling_script "upload" "--dumppath" "$core_file_name" "--incpaths" $paths_to_add "--properties" "Project=CoreCLR" "--squelch" | tee -a $dumpling_file
638 }
639
640 function preserve_core_file {
641     local core_file_name=$1
642     local storage_location="/tmp/coredumps_coreclr"
643
644     # Create the directory (this shouldn't fail even if it already exists).
645     mkdir -p $storage_location
646
647     # Only preserve the dump if the directory is empty. Otherwise, do nothing.
648     # This is a way to prevent us from storing/uploading too many dumps.
649     if [ ! "$(ls -A $storage_location)" ]; then
650         echo "Copying core file $core_file_name to $storage_location"
651         cp $core_file_name $storage_location
652
653         upload_core_file_to_dumpling $core_file_name
654     fi
655 }
656
657 function inspect_and_delete_core_files {
658     # This function prints some basic information from core files in the current
659     # directory and deletes them immediately. Based on the state of the system, it may
660     # also upload a core file to the dumpling service.
661     # (see preserve_core_file).
662     
663     # Depending on distro/configuration, the core files may either be named "core"
664     # or "core.<PID>" by default. We will read /proc/sys/kernel/core_uses_pid to 
665     # determine which one it is.
666     # On OS X/macOS, we checked the kern.corefile value before enabling core dump
667     # generation, so we know it always includes the PID.
668     local core_name_uses_pid=0
669     if [[ (( -e /proc/sys/kernel/core_uses_pid ) && ( "1" == $(cat /proc/sys/kernel/core_uses_pid) )) 
670           || ( "$(uname -s)" == "Darwin" ) ]]; then
671         core_name_uses_pid=1
672     fi
673
674     if [ $core_name_uses_pid == "1" ]; then
675         # We don't know what the PID of the process was, so let's look at all core
676         # files whose name matches core.NUMBER
677         for f in core.*; do
678             [[ $f =~ core.[0-9]+ ]] && print_info_from_core_file "$f" $CORE_ROOT/"corerun" && preserve_core_file "$f" && rm "$f"
679         done
680     elif [ -f core ]; then
681         print_info_from_core_file "core" $CORE_ROOT/"corerun"
682         preserve_core_file "core"
683         rm "core"
684     fi
685 }
686
687 function run_test {
688     # This function runs in a background process. It should not echo anything, and should not use global variables.
689
690     local scriptFilePath=$1
691     local outputFilePath=$2
692
693     # Switch to directory where the script is
694     cd "$(dirname "$scriptFilePath")"
695
696     local scriptFileName=$(basename "$scriptFilePath")
697     local outputFileName=$(basename "$outputFilePath")
698
699     if [ "$limitedCoreDumps" == "ON" ]; then
700         set_up_core_dump_generation
701     fi
702
703     "./$scriptFileName" >"$outputFileName" 2>&1
704     local testScriptExitCode=$?
705
706     # We will try to print some information from generated core dumps if a debugger
707     # is available, and possibly store a dump in a non-transient location.
708     if [ "$limitedCoreDumps" == "ON" ]; then
709         inspect_and_delete_core_files
710     fi
711
712     return $testScriptExitCode
713 }
714
715 # Variables for running tests in the background
716 if [ `uname` = "NetBSD" ]; then
717     NumProc=$(getconf NPROCESSORS_ONLN)
718 else
719     NumProc=$(getconf _NPROCESSORS_ONLN)
720 fi
721 ((maxProcesses = $NumProc * 3 / 2)) # long tests delay process creation, use a few more processors
722
723 ((nextProcessIndex = 0))
724 ((processCount = 0))
725 declare -a scriptFilePaths
726 declare -a outputFilePaths
727 declare -a processIds
728 declare -a testStartTimes
729
730 function finish_test {
731     wait ${processIds[$nextProcessIndex]}
732     local testScriptExitCode=$?
733     ((--processCount))
734
735     local scriptFilePath=${scriptFilePaths[$nextProcessIndex]}
736     local outputFilePath=${outputFilePaths[$nextProcessIndex]}
737     local scriptFileName=$(basename "$scriptFilePath")
738
739     local testEndTime=
740     local testRunningTime=
741     local header=
742
743     if ((verbose == 1)); then
744         header=$(printf "[%4d]" $countTotalTests)
745     fi
746
747     if [ "$showTime" == "ON" ]; then
748         testEndTime=$(date +%s)
749         testRunningTime=$(( $testEndTime - ${testStartTimes[$nextProcessIndex]} ))
750         header=$header$(printf "[%4ds]" $testRunningTime)
751     fi
752
753     local xunitTestResult
754     case $testScriptExitCode in
755         0)
756             let countPassedTests++
757             xunitTestResult='Pass'
758             if ((verbose == 1 || runFailingTestsOnly == 1)); then
759                 echo "PASSED   - ${header}${scriptFilePath}"
760             else
761                 echo "         - ${header}${scriptFilePath}"
762             fi
763             ;;
764         2)
765             let countSkippedTests++
766             xunitTestResult='Skip'
767             echo "SKIPPED  - ${header}${scriptFilePath}"
768             ;;
769         *)
770             let countFailedTests++
771             xunitTestResult='Fail'
772             echo "FAILED   - ${header}${scriptFilePath}"
773             ;;
774     esac
775     let countTotalTests++
776
777     if ((verbose == 1 || testScriptExitCode != 0)); then
778         while IFS='' read -r line || [ -n "$line" ]; do
779             echo "               $line"
780         done <"$outputFilePath"
781     fi
782
783     xunit_output_add_test "$scriptFilePath" "$outputFilePath" "$xunitTestResult" "$testScriptExitCode"
784 }
785
786 function finish_remaining_tests {
787     # Finish the remaining tests in the order in which they were started
788     if ((nextProcessIndex >= processCount)); then
789         ((nextProcessIndex = 0))
790     fi
791     while ((processCount > 0)); do
792         finish_test
793         ((nextProcessIndex = (nextProcessIndex + 1) % maxProcesses))
794     done
795     ((nextProcessIndex = 0))
796 }
797
798 function prep_test {
799     local scriptFilePath=$1
800     local scriptFileDir=$(dirname "$scriptFilePath")
801
802     test "$verbose" == 1 && echo "Preparing $scriptFilePath"
803
804     if [ ! "$noLFConversion" == "ON" ]; then
805         # Convert DOS line endings to Unix if needed
806         perl -pi -e 's/\r\n|\n|\r/\n/g' "$scriptFilePath"
807     fi
808         
809     # Add executable file mode bit if needed
810     chmod +x "$scriptFilePath"
811
812     #remove any NI and Locks
813     rm -f $scriptFileDir/*.ni.*
814     rm -rf $scriptFileDir/lock
815 }
816
817 function start_test {
818     local scriptFilePath=$1
819     if ((runFailingTestsOnly == 1)) && ! is_failing_test "$scriptFilePath"; then
820         return
821     fi
822
823     # Skip any test that's not in the current playlist, if a playlist was
824     # given to us.
825     if [ -n "$playlistFile" ] && ! is_playlist_test "$scriptFilePath"; then
826         return
827     fi
828
829     if ((nextProcessIndex < processCount)); then
830         finish_test
831     fi
832
833     scriptFilePaths[$nextProcessIndex]=$scriptFilePath
834     local scriptFileName=$(basename "$scriptFilePath")
835     local outputFilePath=$(dirname "$scriptFilePath")/${scriptFileName}.out
836     outputFilePaths[$nextProcessIndex]=$outputFilePath
837
838     if [ "$showTime" == "ON" ]; then
839         testStartTimes[$nextProcessIndex]=$(date +%s)
840     fi
841
842     test "$verbose" == 1 && echo "Starting $scriptFilePath"
843     if is_unsupported_test "$scriptFilePath"; then
844         skip_unsupported_test "$scriptFilePath" "$outputFilePath" &
845     elif ((runFailingTestsOnly == 0)) && is_failing_test "$scriptFilePath"; then
846         skip_failing_test "$scriptFilePath" "$outputFilePath" &
847     else
848         run_test "$scriptFilePath" "$outputFilePath" &
849     fi
850     processIds[$nextProcessIndex]=$!
851
852     ((nextProcessIndex = (nextProcessIndex + 1) % maxProcesses))
853     ((++processCount))
854 }
855
856 # Get a list of directories in which to scan for tests by reading the
857 # specified file line by line.
858 function set_test_directories {
859     local errorSource='set_test_directories'
860
861     local listFileName=$1
862
863     if [ ! -f "$listFileName" ]
864     then
865         exit_with_error "$errorSource" "Test directories file not found at $listFileName"
866     fi
867     testDirectories=($(read_array "$listFileName"))
868 }
869
870 function run_tests_in_directory {
871     local testDir=$1
872
873     # Recursively search through directories for .sh files to prepare them.
874     # Note: This needs to occur before any test runs as some of the .sh files
875     # depend on other .sh files
876     for scriptFilePath in $(find "$testDir" -type f -iname '*.sh' | sort)
877     do
878         prep_test "${scriptFilePath:2}"
879     done
880     echo "The tests have been prepared"
881     # Recursively search through directories for .sh files to run.
882     for scriptFilePath in $(find "$testDir" -type f -iname '*.sh' | sort)
883     do
884         start_test "${scriptFilePath:2}"
885     done
886 }
887
888 function coreclr_code_coverage {
889     local coverageDir="$coverageOutputDir/Coverage"
890     local toolsDir="$coverageOutputDir/Coverage/tools"
891     local reportsDir="$coverageOutputDir/Coverage/reports"
892     local packageName="unix-code-coverage-tools.1.0.0.nupkg"
893
894     rm -rf $coverageDir
895     mkdir -p $coverageDir
896     mkdir -p $toolsDir
897     mkdir -p $reportsDir
898     pushd $toolsDir > /dev/null
899
900     echo "Pulling down code coverage tools"
901     wget -q https://www.myget.org/F/dotnet-buildtools/api/v2/package/unix-code-coverage-tools/1.0.0 -O $packageName
902     echo "Unzipping to $toolsDir"
903     unzip -q -o $packageName
904
905     # Invoke gcovr
906     chmod a+rwx ./gcovr
907     chmod a+rwx ./$OSName/llvm-cov
908
909     echo
910     echo "Generating coreclr code coverage reports at $reportsDir/coreclr.html"
911     echo "./gcovr $coreClrObjs --gcov-executable=$toolsDir/$OS/llvm-cov -r $coreClrSrc --html --html-details -o $reportsDir/coreclr.html"
912     echo
913     ./gcovr $coreClrObjs --gcov-executable=$toolsDir/$OSName/llvm-cov -r $coreClrSrc --html --html-details -o $reportsDir/coreclr.html
914     exitCode=$?
915     popd > /dev/null
916     exit $exitCode
917 }
918
919 function check_cpu_architecture {
920     local CPUName=$(uname -m)
921     local __arch=
922
923     case $CPUName in
924         i686)
925             __arch=x86
926             ;;
927         x86_64)
928             __arch=x64
929             ;;
930         armv7l)
931             __arch=arm
932             ;;
933         aarch64)
934             __arch=arm64
935             ;;
936         *)
937             echo "Unknown CPU $CPUName detected, configuring as if for x64"
938             __arch=x64
939             ;;
940     esac
941
942     echo "$__arch"
943 }
944
945 ARCH=$(check_cpu_architecture)
946 echo "Running on  CPU- $ARCH"
947
948 # Exit code constants
949 readonly EXIT_CODE_SUCCESS=0       # Script ran normally.
950 readonly EXIT_CODE_EXCEPTION=1     # Script exited because something exceptional happened (e.g. bad arguments, Ctrl-C interrupt).
951 readonly EXIT_CODE_TEST_FAILURE=2  # Script completed successfully, but one or more tests failed.
952
953 # Argument variables
954 testRootDir=
955 testNativeBinDir=
956 coreOverlayDir=
957 coreClrBinDir=
958 mscorlibDir=
959 coreFxBinDir=
960 coreClrObjs=
961 coreClrSrc=
962 coverageOutputDir=
963 testEnv=
964 playlistFile=
965 showTime=
966 noLFConversion=
967 buildOverlayOnly=
968 gcsimulator=
969 longgc=
970 limitedCoreDumps=
971 illinker=
972 ((disableEventLogging = 0))
973 ((serverGC = 0))
974
975 # Handle arguments
976 verbose=0
977 doCrossgen=0
978 jitdisasm=0
979 ilasmroundtrip=
980
981 for i in "$@"
982 do
983     case $i in
984         -h|--help)
985             print_usage
986             exit $EXIT_CODE_SUCCESS
987             ;;
988         -v|--verbose)
989             verbose=1
990             ;;
991         --crossgen)
992             doCrossgen=1
993             ;;
994         --jitstress=*)
995             export COMPlus_JitStress=${i#*=}
996             ;;
997         --jitstressregs=*)
998             export COMPlus_JitStressRegs=${i#*=}
999             ;;
1000         --jitminopts)
1001             export COMPlus_JITMinOpts=1
1002             ;;
1003         --jitforcerelocs)
1004             export COMPlus_ForceRelocs=1
1005             ;;
1006         --link=*)
1007             export ILLINK=${i#*=}
1008             export DoLink=true
1009             ;;
1010         --jitdisasm)
1011             jitdisasm=1
1012             ;;
1013         --ilasmroundtrip)
1014             ((ilasmroundtrip = 1))
1015             ;;
1016         --testRootDir=*)
1017             testRootDir=${i#*=}
1018             ;;
1019         --testNativeBinDir=*)
1020             testNativeBinDir=${i#*=}
1021             ;;
1022         --coreOverlayDir=*)
1023             coreOverlayDir=${i#*=}
1024             ;;
1025         --coreClrBinDir=*)
1026             coreClrBinDir=${i#*=}
1027             ;;
1028         --mscorlibDir=*)
1029             mscorlibDir=${i#*=}
1030             ;;
1031         --coreFxBinDir=*)
1032             coreFxBinDir=${i#*=}
1033             ;;
1034         --testDir=*)
1035             testDirectories[${#testDirectories[@]}]=${i#*=}
1036             ;;
1037         --testDirFile=*)
1038             set_test_directories "${i#*=}"
1039             ;;
1040         --runFailingTestsOnly)
1041             ((runFailingTestsOnly = 1))
1042             ;;
1043         --disableEventLogging)
1044             ((disableEventLogging = 1))
1045             ;;
1046         --runcrossgentests)
1047             export RunCrossGen=1
1048             ;;
1049         --sequential)
1050             ((maxProcesses = 1))
1051             ;;
1052         --useServerGC)
1053             ((serverGC = 1))
1054             ;;
1055         --long-gc)
1056             ((longgc = 1))
1057             ;;
1058         --gcsimulator)
1059             ((gcsimulator = 1))
1060             ;;
1061         --playlist=*)
1062             playlistFile=${i#*=}
1063             ;;
1064         --coreclr-coverage)
1065             CoreClrCoverage=ON
1066             ;;
1067         --coreclr-objs=*)
1068             coreClrObjs=${i#*=}
1069             ;;
1070         --coreclr-src=*)
1071             coreClrSrc=${i#*=}
1072             ;;
1073         --coverage-output-dir=*)
1074             coverageOutputDir=${i#*=}
1075             ;;
1076         --test-env=*)
1077             testEnv=${i#*=}
1078             ;;            
1079         --gcstresslevel=*)
1080             export COMPlus_GCStress=${i#*=}
1081             ;;            
1082         --show-time)
1083             showTime=ON
1084             ;;
1085         --no-lf-conversion)
1086             noLFConversion=ON
1087             ;;
1088         --build-overlay-only)
1089             buildOverlayOnly=ON
1090             ;;
1091         --limitedDumpGeneration)
1092             limitedCoreDumps=ON
1093             ;;
1094         --xunitOutputPath=*)
1095             xunitOutputPath=${i#*=}
1096             ;;
1097         *)
1098             echo "Unknown switch: $i"
1099             print_usage
1100             exit $EXIT_CODE_SUCCESS
1101             ;;
1102     esac
1103 done
1104
1105 if [ -n "$coreOverlayDir" ] && [ "$buildOverlayOnly" == "ON" ]; then
1106     echo "Can not use \'--coreOverlayDir=<path>\' and \'--build-overlay-only\' at the same time."
1107     exit $EXIT_CODE_EXCEPTION
1108 fi
1109
1110 if ((disableEventLogging == 0)); then
1111     export COMPlus_EnableEventLog=1
1112 fi
1113
1114 export CORECLR_SERVER_GC="$serverGC"
1115
1116 if [ -z "$testRootDir" ]; then
1117     echo "--testRootDir is required."
1118     print_usage
1119     exit $EXIT_CODE_EXCEPTION
1120 fi
1121 if [ ! -d "$testRootDir" ]; then
1122     echo "Directory specified by --testRootDir does not exist: $testRootDir"
1123     exit $EXIT_CODE_EXCEPTION
1124 fi
1125
1126 # Copy native interop test libraries over to the mscorlib path in
1127 # order for interop tests to run on linux.
1128 if [ -z "$mscorlibDir" ]; then
1129     mscorlibDir=$coreClrBinDir
1130 fi
1131
1132 if [ ! -z "$longgc" ]; then
1133     echo "Running Long GC tests"
1134     export RunningLongGCTests=1
1135 fi
1136
1137 if [ ! -z "$gcsimulator" ]; then
1138     echo "Running GC simulator tests"
1139     export RunningGCSimulatorTests=1
1140 fi
1141
1142 if [[ ! "$jitdisasm" -eq 0 ]]; then
1143     echo "Running jit disasm"
1144     export RunningJitDisasm=1
1145 fi
1146
1147 if [ ! -z "$ilasmroundtrip" ]; then
1148     echo "Running Ilasm round trip"
1149     export RunningIlasmRoundTrip=1
1150 fi
1151
1152 # If this is a coverage run, make sure the appropriate args have been passed
1153 if [ "$CoreClrCoverage" == "ON" ]
1154 then
1155     echo "Code coverage is enabled for this run"
1156     echo ""
1157     if [ ! "$OSName" == "Darwin" ] && [ ! "$OSName" == "Linux" ]
1158     then
1159         echo "Code Coverage not supported on $OS"
1160         exit 1
1161     fi
1162
1163     if [ -z "$coreClrObjs" ]
1164     then
1165         echo "Coreclr obj files are required to generate code coverage reports"
1166         echo "Coreclr obj files root path can be passed using '--coreclr-obj' argument"
1167         exit 1
1168     fi
1169
1170     if [ -z "$coreClrSrc" ]
1171     then
1172         echo "Coreclr src files are required to generate code coverage reports"
1173         echo "Coreclr src files root path can be passed using '--coreclr-src' argument"
1174         exit 1
1175     fi
1176
1177     if [ -z "$coverageOutputDir" ]
1178     then
1179         echo "Output directory for coverage results must be specified"
1180         echo "Output path can be specified '--coverage-output-dir' argument"
1181         exit 1
1182     fi
1183 fi
1184
1185 xunit_output_begin
1186 create_core_overlay
1187 precompile_overlay_assemblies
1188
1189 if [ "$buildOverlayOnly" == "ON" ];
1190 then
1191     echo "Build overlay directory \'$coreOverlayDir\' complete."
1192     exit 0
1193 fi
1194
1195 if [ -n "$playlistFile" ]
1196 then
1197     # Use a playlist file exclusively, if it was provided
1198     echo "Executing playlist $playlistFile"
1199     load_playlist_tests
1200 else
1201     load_unsupported_tests
1202     load_failing_tests
1203 fi
1204
1205 export __TestEnv=$testEnv
1206
1207 cd "$testRootDir"
1208
1209 dumplingsListPath="$testRootDir/dumplings.txt"
1210
1211 # clean up any existing dumpling remnants from previous runs.
1212 rm -f "$dumplingsListPath"
1213 find $testRootDir -type f -name "local_dumplings.txt" -exec rm {} \;
1214
1215 time_start=$(date +"%s")
1216 if [ -z "$testDirectories" ]
1217 then
1218     # No test directories were specified, so run everything in the current
1219     # directory and its subdirectories.
1220     run_tests_in_directory "."
1221 else
1222     # Otherwise, run all the tests in each specified test directory.
1223     for testDir in "${testDirectories[@]}"
1224     do
1225         if [ ! -d "$testDir" ]; then
1226             echo "Test directory does not exist: $testDir"
1227         else
1228             run_tests_in_directory "./$testDir"
1229         fi
1230     done
1231 fi
1232 finish_remaining_tests
1233
1234 print_results
1235
1236 find $testRootDir -type f -name "local_dumplings.txt" -exec cat {} \; > $dumplingsListPath
1237
1238 if [ -s $dumplingsListPath ]; then
1239     cat $dumplingsListPath
1240 else
1241     rm $dumplingsListPath
1242 fi
1243
1244 time_end=$(date +"%s")
1245 time_diff=$(($time_end-$time_start))
1246 echo "$(($time_diff / 60)) minutes and $(($time_diff % 60)) seconds taken to run CoreCLR tests."
1247
1248 xunit_output_end
1249
1250 if [ "$CoreClrCoverage" == "ON" ]
1251 then
1252     coreclr_code_coverage
1253 fi
1254
1255 if ((countFailedTests > 0)); then
1256     exit $EXIT_CODE_TEST_FAILURE
1257 fi
1258
1259 exit $EXIT_CODE_SUCCESS