Enable arm64 Linux testing in CI
[platform/upstream/coreclr.git] / build-test.sh
1 #!/usr/bin/env bash
2
3 initHostDistroRid()
4 {
5     __HostDistroRid=""
6
7     # Some OS groups should default to use the portable packages
8     if [ "$__BuildOS" == "OSX" ]; then
9         __PortableBuild=1
10     fi
11
12     if [ "$__HostOS" == "Linux" ]; then
13         if [ -e /etc/redhat-release ]; then
14             local redhatRelease=$(</etc/redhat-release)
15             if [[ $redhatRelease == "CentOS release 6."* || $redhatRelease == "Red Hat Enterprise Linux Server release 6."* ]]; then
16                 __HostDistroRid="rhel.6-$__HostArch"
17             else
18                 __PortableBuild=1
19             fi
20         elif [ -e /etc/os-release ]; then
21             source /etc/os-release
22             if [[ $ID == "alpine" ]]; then
23                 __HostDistroRid="linux-musl-$__HostArch"
24             else
25                 __PortableBuild=1
26                 __HostDistroRid="$ID.$VERSION_ID-$__HostArch"
27             fi
28         fi
29     elif [ "$__HostOS" == "FreeBSD" ]; then
30         __freebsd_version=`sysctl -n kern.osrelease | cut -f1 -d'.'`
31         __HostDistroRid="freebsd.$__freebsd_version-$__HostArch"
32     fi
33
34     # Portable builds target the base RID
35     if [ "$__PortableBuild" == 1 ]; then
36         if [ "$__BuildOS" == "OSX" ]; then
37             export __HostDistroRid="osx-$__BuildArch"
38         elif [ "$__BuildOS" == "Linux" ]; then
39             export __HostDistroRid="linux-$__BuildArch"
40         fi
41     fi
42
43     if [ "$__HostDistroRid" == "" ]; then
44         echo "WARNING: Cannot determine runtime id for current distro."
45     fi
46
47     echo "Setting __HostDistroRid to $__HostDistroRid"
48 }
49
50 initTargetDistroRid()
51 {
52     if [ $__CrossBuild == 1 ]; then
53         if [ "$__BuildOS" == "Linux" ]; then
54             if [ ! -e $ROOTFS_DIR/etc/os-release ]; then
55                 if [ -e $ROOTFS_DIR/android_platform ]; then
56                     source $ROOTFS_DIR/android_platform
57                     export __DistroRid="$RID"
58                 else
59                     echo "WARNING: Cannot determine runtime id for current distro."
60                     export __DistroRid=""
61                 fi
62             else
63                 source $ROOTFS_DIR/etc/os-release
64                 export __DistroRid="$ID.$VERSION_ID-$__BuildArch"
65             fi
66         fi
67     else
68         export __DistroRid="$__HostDistroRid"
69     fi
70
71     if [ "$ID.$VERSION_ID" == "ubuntu.16.04" ]; then
72      export __DistroRid="ubuntu.14.04-$__BuildArch"
73     fi
74
75     # Portable builds target the base RID
76     if [ "$__PortableBuild" == 1 ]; then
77         if [ "$__BuildOS" == "Linux" ]; then
78             export __DistroRid="linux-$__BuildArch"
79             export __RuntimeId="linux-$__BuildArch"
80         elif [ "$__BuildOS" == "OSX" ]; then
81             export __DistroRid="osx-$__BuildArch"
82             export __RuntimeId="osx-$__BuildArch"
83         fi
84     fi
85
86     echo "__DistroRid: " $__DistroRid
87 }
88
89 isMSBuildOnNETCoreSupported()
90 {
91     __isMSBuildOnNETCoreSupported=$__msbuildonunsupportedplatform
92
93     if [ $__isMSBuildOnNETCoreSupported == 1 ]; then
94         return
95     fi
96
97     if [ "$__HostArch" == "x64" ]; then
98         if [ "$__HostOS" == "Linux" ]; then
99             __isMSBuildOnNETCoreSupported=1
100             UNSUPPORTED_RIDS=("debian.9-x64" "ubuntu.17.04-x64")
101             for UNSUPPORTED_RID in "${UNSUPPORTED_RIDS[@]}"
102             do
103                 if [ "$__HostDistroRid" == "$UNSUPPORTED_RID" ]; then
104                     __isMSBuildOnNETCoreSupported=0
105                     break
106                 fi
107             done
108         elif [ "$__HostOS" == "OSX" ]; then
109             __isMSBuildOnNETCoreSupported=1
110         fi
111     fi
112 }
113
114 generate_layout()
115 {
116     __TestDir=$__ProjectDir/tests
117     __ProjectFilesDir=$__TestDir
118     __TestBinDir=$__TestWorkingDir
119
120     if [ $__RebuildTests -ne 0 ]; then
121         if [ -d "${__TestBinDir}" ]; then
122             echo "Removing tests build dir: ${__TestBinDir}"
123             rm -rf $__TestBinDir
124         fi
125     fi
126
127     __CMakeBinDir="${__TestBinDir}"
128
129     if [ -z "$__TestIntermediateDir" ]; then
130         __TestIntermediateDir="tests/obj/${__BuildOS}.${__BuildArch}.${__BuildType}"
131     fi
132
133     echo "__BuildOS: ${__BuildOS}"
134     echo "__BuildArch: ${__BuildArch}"
135     echo "__BuildType: ${__BuildType}"
136     echo "__TestIntermediateDir: ${__TestIntermediateDir}"
137
138     if [ ! -f "$__TestBinDir" ]; then
139         echo "Creating TestBinDir: ${__TestBinDir}"
140         mkdir -p $__TestBinDir
141     fi
142     if [ ! -f "$__LogsDir" ]; then
143         echo "Creating LogsDir: ${__LogsDir}"
144         mkdir -p $__LogsDir
145     fi
146
147     __BuildProperties="-p:OSGroup=${__BuildOS} -p:BuildOS=${__BuildOS} -p:BuildArch=${__BuildArch} -p:BuildType=${__BuildType}"
148
149     # =========================================================================================
150     # ===
151     # === Restore product binaries from packages
152     # ===
153     # =========================================================================================
154
155     build_MSBuild_projects "Restore_Packages" "${__ProjectDir}/tests/build.proj" "Restore product binaries (build tests)" "-BatchRestorePackages"
156
157     if [ -n "$__UpdateInvalidPackagesArg" ]; then
158         __up=-updateinvalidpackageversion
159     fi
160
161     echo "${__MsgPrefix}Creating test overlay..."
162
163     if [ -z "$xUnitTestBinBase" ]; then
164       xUnitTestBinBase=$__TestWorkingDir
165     fi
166
167     export CORE_ROOT=$xUnitTestBinBase/Tests/Core_Root
168
169     if [ -d "${CORE_ROOT}" ]; then
170       rm -rf $CORE_ROOT
171     fi
172
173     mkdir -p $CORE_ROOT
174
175     build_MSBuild_projects "Tests_Overlay_Managed" "${__ProjectDir}/tests/runtest.proj" "Creating test overlay" "-testOverlay"
176
177     chmod +x $__BinDir/corerun
178     chmod +x $__BinDir/crossgen
179
180     # Make sure to copy over the pulled down packages
181     cp -r $__BinDir/* $CORE_ROOT/ > /dev/null
182
183 }
184
185 generate_testhost()
186 {
187     export TEST_HOST=$xUnitTestBinBase/testhost
188
189     if [ -d "${TEST_HOST}" ]; then
190         rm -rf $TEST_HOST
191     fi
192
193     echo "${__MsgPrefix}Creating test overlay..."    
194     mkdir -p $TEST_HOST
195
196     build_MSBuild_projects "Tests_Generate_TestHost" "${__ProjectDir}/tests/runtest.proj" "Creating test host" "-testHost"
197 }
198
199
200 build_Tests()
201 {
202     __TestDir=$__ProjectDir/tests
203     __ProjectFilesDir=$__TestDir
204     __TestBinDir=$__TestWorkingDir
205
206     if [ -f  "${__TestWorkingDir}/build_info.json" ]; then
207         rm  "${__TestWorkingDir}/build_info.json"
208     fi
209
210     if [ $__RebuildTests -ne 0 ]; then
211         if [ -d "${__TestBinDir}" ]; then
212             echo "Removing tests build dir: ${__TestBinDir}"
213             rm -rf $__TestBinDir
214         fi
215     fi
216
217     export __CMakeBinDir="${__TestBinDir}"
218     if [ ! -d "${__TestIntermediatesDir}" ]; then
219         mkdir -p ${__TestIntermediatesDir}
220     fi
221
222     __NativeTestIntermediatesDir="${__TestIntermediatesDir}/Native"
223     if [  ! -d "${__NativeTestIntermediatesDir}" ]; then
224         mkdir -p ${__NativeTestIntermediatesDir}
225     fi
226
227     __ManagedTestIntermediatesDir="${__TestIntermediatesDir}/Managed"
228     if [ ! -d "${__ManagedTestIntermediatesDir}" ]; then
229         mkdir -p ${__ManagedTestIntermediatesDir}
230     fi
231
232     echo "__BuildOS: ${__BuildOS}"
233     echo "__BuildArch: ${__BuildArch}"
234     echo "__BuildType: ${__BuildType}"
235     echo "__TestIntermediatesDir: ${__TestIntermediatesDir}"
236     echo "__NativeTestIntermediatesDir: ${__NativeTestIntermediatesDir}"
237     echo "__ManagedTestIntermediatesDir: ${__ManagedTestIntermediatesDir}"
238
239     if [ ! -f "$__TestBinDir" ]; then
240         echo "Creating TestBinDir: ${__TestBinDir}"
241         mkdir -p $__TestBinDir
242     fi
243     if [ ! -f "$__LogsDir" ]; then
244         echo "Creating LogsDir: ${__LogsDir}"
245         mkdir -p $__LogsDir
246     fi
247
248     __BuildProperties="-p:OSGroup=${__BuildOS} -p:BuildOS=${__BuildOS} -p:BuildArch=${__BuildArch} -p:BuildType=${__BuildType}"
249
250     # =========================================================================================
251     # ===
252     # === Restore product binaries from packages
253     # ===
254     # =========================================================================================
255
256     if [ ${__SkipRestorePackages} != 1 ]; then
257         build_MSBuild_projects "Restore_Product" "${__ProjectDir}/tests/build.proj" "Restore product binaries (build tests)" "-BatchRestorePackages"
258     fi
259
260     if [ $__SkipNative != 1 ]; then
261         build_native_projects "$__BuildArch" "${__NativeTestIntermediatesDir}"
262
263         if [ $? -ne 0 ]; then
264             echo "${__MsgPrefix}Error: build failed. Refer to the build log files for details (above)"
265             exit 1
266         fi
267     fi
268
269     if [ $__SkipManaged != 1 ]; then
270         echo "Starting the Managed Tests Build..."
271
272         build_MSBuild_projects "Tests_Managed" "$__ProjectDir/tests/build.proj" "Managed tests build (build tests)" "$__up"
273
274         if [ $? -ne 0 ]; then
275             echo "${__MsgPrefix}Error: build failed. Refer to the build log files for details (above)"
276             exit 1
277         else
278             echo "Checking the Managed Tests Build..."
279
280             build_MSBuild_projects "Check_Test_Build" "${__ProjectDir}/tests/runtest.proj" "Check Test Build" "-ExtraParameters:/t:CheckTestBuild"
281
282             if [ $? -ne 0 ]; then
283                 echo "${__MsgPrefix}Error: Check Test Build failed."
284                 exit 1
285             fi
286
287             echo "Managed tests build success!"
288         fi
289     fi
290
291     if [ $__BuildTestWrappers -ne -0 ]; then
292         echo "${__MsgPrefix}Creating test wrappers..."
293
294         export __Exclude="${__ProjectDir}/tests/issues.targets"
295         export __BuildLogRootName="Tests_XunitWrapper"
296
297         # Set up directories and file names
298         __BuildLogRootName=$subDirectoryName
299         __BuildLog="$__LogsDir/${__BuildLogRootName}.${__BuildOS}.${__BuildArch}.${__BuildType}.log"
300         __BuildWrn="$__LogsDir/${__BuildLogRootName}.${__BuildOS}.${__BuildArch}.${__BuildType}.wrn"
301         __BuildErr="$__LogsDir/${__BuildLogRootName}.${__BuildOS}.${__BuildArch}.${__BuildType}.err"
302
303         buildVerbosity="Summary"
304
305         if [ $__VerboseBuild == 1 ]; then
306             buildVerbosity="Diag"
307         fi
308
309         echo "${__DotNetCli}" msbuild "${__ProjectDir}/tests/runtest.proj" /p:RestoreAdditionalProjectSources=https://dotnet.myget.org/F/dotnet-core/ /p:BuildWrappers=true /p:TargetsWindows=false /fileloggerparameters:"\"Verbosity=normal;LogFile=${__BuildLog}\"" /fileloggerparameters1:"\"WarningsOnly;LogFile=${__BuildWrn}\"" /fileloggerparameters2:"\"ErrorsOnly;LogFile=${__BuildErr}\"" /consoleloggerparameters:$buildVerbosity /p:__BuildOS=$__BuildOS /p:__BuildType=$__BuildType /p:__BuildArch=$__BuildArch
310         "${__DotNetCli}" msbuild "${__ProjectDir}/tests/runtest.proj" /p:RestoreAdditionalProjectSources=https://dotnet.myget.org/F/dotnet-core/ /p:BuildWrappers=true /p:TargetsWindows=false /fileloggerparameters:"\"Verbosity=normal;LogFile=${__BuildLog}\"" /fileloggerparameters1:"\"WarningsOnly;LogFile=${__BuildWrn}\"" /fileloggerparameters2:"\"ErrorsOnly;LogFile=${__BuildErr}\"" /consoleloggerparameters:$buildVerbosity /p:__BuildOS=$__BuildOS /p:__BuildType=$__BuildType /p:__BuildArch=$__BuildArch
311
312         if [ $? -ne 0 ]; then
313             echo "${__MsgPrefix}Error: build failed. Refer to the build log files for details (above)"
314             exit 1
315         else
316             echo "XUnit Wrappers have been built."
317             echo { "\"build_os\"": "\"${__BuildOS}\"", "\"build_arch\"": "\"${__BuildArch}\"", "\"build_type\"": "\"${__BuildType}\"" } > "${__TestWorkingDir}/build_info.json"
318
319         fi
320     fi
321
322     if [ -n "$__UpdateInvalidPackagesArg" ]; then
323         __up=-updateinvalidpackageversion
324     fi
325
326     echo "${__MsgPrefix}Creating test overlay..."
327
328     generate_layout
329
330     if [ $__ZipTests -ne 0 ]; then
331         echo "${__MsgPrefix}ZIP tests packages..."
332         build_MSBuild_projects "Helix_Prep" "$__ProjectDir/tests/helixprep.proj" "Prep test binaries for Helix publishing" " "
333     fi
334 }
335
336 build_MSBuild_projects()
337 {
338     subDirectoryName=$1
339     shift
340     projectName=$1
341     shift
342     stepName="$1"
343     shift
344     extraBuildParameters=("$@")
345
346     # Set up directories and file names
347     __BuildLogRootName=$subDirectoryName
348     __BuildLog="$__LogsDir/${__BuildLogRootName}.${__BuildOS}.${__BuildArch}.${__BuildType}.log"
349     __BuildWrn="$__LogsDir/${__BuildLogRootName}.${__BuildOS}.${__BuildArch}.${__BuildType}.wrn"
350     __BuildErr="$__LogsDir/${__BuildLogRootName}.${__BuildOS}.${__BuildArch}.${__BuildType}.err"
351
352     # Use binclashlogger by default if no other logger is specified
353     if [[ "${extraBuildParameters[*]}" == *"-MsBuildEventLogging"* ]]; then
354         msbuildEventLogging=""
355     else
356         msbuildEventLogging="-MsBuildEventLogging=\"/l:BinClashLogger,Tools/Microsoft.DotNet.Build.Tasks.dll;LogFile=binclash.log\""
357     fi
358
359     if [[ "$subDirectoryName" == "Tests_Managed" ]]; then
360         # Execute msbuild managed test build in stages - workaround for excessive data retention in MSBuild ConfigCache
361         # See https://github.com/Microsoft/msbuild/issues/2993
362
363         # __SkipPackageRestore and __SkipTargetingPackBuild used  to control build by tests/src/dirs.proj
364         export __SkipPackageRestore=false
365         export __SkipTargetingPackBuild=false
366         export __BuildLoopCount=2
367         export __TestGroupToBuild=1
368         __AppendToLog=false
369
370         if [ -n "$__priority1" ]; then
371             export __BuildLoopCount=16
372             export __TestGroupToBuild=2
373         fi
374
375         for (( slice=1 ; slice <= __BuildLoopCount; slice = slice + 1 ))
376         do
377             __msbuildLog="\"/flp:Verbosity=normal;LogFile=${__BuildLog};Append=${__AppendToLog}\""
378             __msbuildWrn="\"/flp1:WarningsOnly;LogFile=${__BuildWrn};Append=${__AppendToLog}\""
379             __msbuildErr="\"/flp2:ErrorsOnly;LogFile=${__BuildErr};Append=${__AppendToLog}\""
380
381             export TestBuildSlice=$slice
382
383             # Generate build command
384             buildArgs=("-Project=$projectName" "-MsBuildLog=${__msbuildLog}" "-MsBuildWrn=${__msbuildWrn}" "-MsBuildErr=${__msbuildErr}")
385             buildArgs+=("$msbuildEventLogging")
386             buildArgs+=("${extraBuildParameters[@]}")
387             buildArgs+=("${__RunArgs[@]}")
388             buildArgs+=("${__UnprocessedBuildArgs[@]}")
389
390             echo "Building step '$stepName' slice=$slice via $buildCommand"
391
392             # Invoke MSBuild
393             "$__ProjectRoot/run.sh" build "${buildArgs[@]}"
394
395             # Make sure everything is OK
396             if [ $? -ne 0 ]; then
397                 echo "${__MsgPrefix}Failed to build $stepName. See the build logs:"
398                 echo "    $__BuildLog"
399                 echo "    $__BuildWrn"
400                 echo "    $__BuildErr"
401                 exit 1
402             fi
403             export __SkipPackageRestore=true
404             export __SkipTargetingPackBuild=true
405             __AppendToLog=true
406         done
407     else
408         __msbuildLog="\"/flp:Verbosity=normal;LogFile=${__BuildLog}\""
409         __msbuildWrn="\"/flp1:WarningsOnly;LogFile=${__BuildWrn}\""
410         __msbuildErr="\"/flp2:ErrorsOnly;LogFile=${__BuildErr}\""
411
412         # Generate build command
413         buildArgs=("-Project=$projectName" "-MsBuildLog=${__msbuildLog}" "-MsBuildWrn=${__msbuildWrn}" "-MsBuildErr=${__msbuildErr}")
414         buildArgs+=("$msbuildEventLogging")
415         buildArgs+=("${extraBuildParameters[@]}")
416         buildArgs+=("${__RunArgs[@]}")
417         buildArgs+=("${__UnprocessedBuildArgs[@]}")
418
419         echo "Building step '$stepName' via $buildCommand"
420
421         # Invoke MSBuild
422         "$__ProjectRoot/run.sh" build "${buildArgs[@]}"
423
424         # Make sure everything is OK
425         if [ $? -ne 0 ]; then
426             echo "${__MsgPrefix}Failed to build $stepName. See the build logs:"
427             echo "    $__BuildLog"
428             echo "    $__BuildWrn"
429             echo "    $__BuildErr"
430             exit 1
431         fi
432     fi
433 }
434
435 build_native_projects()
436 {
437     platformArch="$1"
438     intermediatesForBuild="$2"
439
440     extraCmakeArguments="-DCLR_CMAKE_TARGET_OS=${__BuildOS} -DCLR_CMAKE_HOST_ARCH=${platformArch}"
441     message="native tests assets"
442
443     # All set to commence the build
444     echo "Commencing build of $message for $__BuildOS.$__BuildArch.$__BuildType in $intermediatesForBuild"
445
446     generator=""
447     buildFile="Makefile"
448     buildTool="make"
449     if [ $__UseNinja == 1 ]; then
450         generator="ninja"
451         buildFile="build.ninja"
452         if ! buildTool=$(command -v ninja || command -v ninja-build); then
453            echo "Unable to locate ninja!" 1>&2
454            exit 1
455         fi
456     fi
457
458     if [ $__SkipConfigure == 0 ]; then
459         # if msbuild is not supported, then set __SkipGenerateVersion to 1
460         if [ $__isMSBuildOnNETCoreSupported == 0 ]; then __SkipGenerateVersion=1; fi
461         # Drop version.cpp file
462         __versionSourceFile="$intermediatesForBuild/version.cpp"
463         if [ $__SkipGenerateVersion == 0 ]; then
464             pwd
465             "$__ProjectRoot/run.sh" build -Project=$__ProjectDir/build.proj -generateHeaderUnix -NativeVersionSourceFile=$__versionSourceFile -MsBuildEventLogging="/l:BinClashLogger,Tools/Microsoft.DotNet.Build.Tasks.dll;LogFile=binclash.log"  $__RunArgs $__UnprocessedBuildArgs
466         else
467             # Generate the dummy version.cpp, but only if it didn't exist to make sure we don't trigger unnecessary rebuild
468             __versionSourceLine="static char sccsid[] __attribute__((used)) = \"@(#)No version information produced\";"
469             if [ -e $__versionSourceFile ]; then
470                 read existingVersionSourceLine < $__versionSourceFile
471             fi
472             if [ "$__versionSourceLine" != "$existingVersionSourceLine" ]; then
473                 echo $__versionSourceLine > $__versionSourceFile
474             fi
475         fi
476
477         pushd "$intermediatesForBuild"
478         # Regenerate the CMake solution
479         # Force cross dir to point to project root cross dir, in case there is a cross build.
480         echo "Invoking CONFIG_DIR=\"$__ProjectRoot/cross\" \"$__ProjectRoot/src/pal/tools/gen-buildsys-clang.sh\" \"$__TestDir\" $__ClangMajorVersion $__ClangMinorVersion $platformArch $__BuildType $__CodeCoverage $generator $extraCmakeArguments $__cmakeargs"
481         CONFIG_DIR="$__ProjectRoot/cross" "$__ProjectRoot/src/pal/tools/gen-buildsys-clang.sh" "$__TestDir" $__ClangMajorVersion $__ClangMinorVersion $platformArch $__BuildType $__CodeCoverage $generator "$extraCmakeArguments" "$__cmakeargs"
482         popd
483     fi
484
485     if [ ! -f "$intermediatesForBuild/$buildFile" ]; then
486         echo "Failed to generate $message build project!"
487         exit 1
488     fi
489
490     # Build
491     if [ $__ConfigureOnly == 1 ]; then
492         echo "Finish configuration & skipping $message build."
493         return
494     fi
495
496     pushd "$intermediatesForBuild"
497
498     echo "Executing $buildTool install -j $__NumProc"
499
500     $buildTool install -j $__NumProc
501     if [ $? != 0 ]; then
502         echo "Failed to build $message."
503         exit 1
504     fi
505
506     popd
507     echo "Native tests build success!"
508 }
509
510 usage()
511 {
512     echo "Usage: $0 [BuildArch] [BuildType] [verbose] [coverage] [cross] [clangx.y] [ninja] [runtests] [bindir]"
513     echo "BuildArch can be: x64, x86, arm, armel, arm64"
514     echo "BuildType can be: debug, checked, release"
515     echo "coverage - optional argument to enable code coverage build (currently supported only for Linux and OSX)."
516     echo "ninja - target ninja instead of GNU make"
517     echo "clangx.y - optional argument to build using clang version x.y - supported version 3.5 - 6.0"
518     echo "cross - optional argument to signify cross compilation,"
519     echo "      - will use ROOTFS_DIR environment variable if set."
520     echo "crosscomponent - optional argument to build cross-architecture component,"
521     echo "               - will use CAC_ROOTFS_DIR environment variable if set."
522     echo "portableLinux - build for Portable Linux Distribution"
523     echo "portablebuild - Use portable build."
524     echo "verbose - optional argument to enable verbose build output."
525     echo "rebuild - if tests have already been built - rebuild them"
526     echo "skipnative: skip the native tests build"
527     echo "skipmanaged: skip the managed section of the test build"
528     echo "generatelayoutonly - only pull down dependencies and build coreroot"
529     echo "generatetesthostonly - only pull down dependencies and build coreroot and the CoreFX testhost"
530     echo "skiprestorepackages - skip package restore"
531     echo "runtests - run tests after building them"
532     echo "ziptests - zips CoreCLR tests & Core_Root for a Helix run"
533     echo "bindir - output directory (defaults to $__ProjectRoot/bin)"
534     echo "msbuildonunsupportedplatform - build managed binaries even if distro is not officially supported."
535     echo "priority1 - include priority=1 tests in the build"
536     exit 1
537 }
538
539
540 # Obtain the location of the bash script to figure out where the root of the repo is.
541 __ProjectRoot="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )"
542
543 # Use uname to determine what the CPU is.
544 CPUName=$(uname -p)
545
546 # Some Linux platforms report unknown for platform, but the arch for machine.
547 if [ "$CPUName" == "unknown" ]; then
548     CPUName=$(uname -m)
549 fi
550
551 case $CPUName in
552     i686)
553         echo "Unsupported CPU $CPUName detected, build might not succeed!"
554         __BuildArch=x86
555         __HostArch=x86
556         ;;
557
558     x86_64)
559         __BuildArch=x64
560         __HostArch=x64
561         ;;
562
563     armv7l)
564         echo "Unsupported CPU $CPUName detected, build might not succeed!"
565         __BuildArch=arm
566         __HostArch=arm
567         ;;
568
569     aarch64)
570         __BuildArch=arm64
571         __HostArch=arm64
572         ;;
573
574     *)
575         echo "Unknown CPU $CPUName detected, configuring as if for x64"
576         __BuildArch=x64
577         __HostArch=x64
578         ;;
579 esac
580
581 # Use uname to determine what the OS is.
582 OSName=$(uname -s)
583 case $OSName in
584     Linux)
585         __BuildOS=Linux
586         __HostOS=Linux
587         ;;
588
589     Darwin)
590         __BuildOS=OSX
591         __HostOS=OSX
592         ;;
593
594     FreeBSD)
595         __BuildOS=FreeBSD
596         __HostOS=FreeBSD
597         ;;
598
599     OpenBSD)
600         __BuildOS=OpenBSD
601         __HostOS=OpenBSD
602         ;;
603
604     NetBSD)
605         __BuildOS=NetBSD
606         __HostOS=NetBSD
607         ;;
608
609     SunOS)
610         __BuildOS=SunOS
611         __HostOS=SunOS
612         ;;
613
614     *)
615         echo "Unsupported OS $OSName detected, configuring as if for Linux"
616         __BuildOS=Linux
617         __HostOS=Linux
618         ;;
619 esac
620
621 __BuildType=Debug
622 __CodeCoverage=
623 __IncludeTests=INCLUDE_TESTS
624
625 # Set the various build properties here so that CMake and MSBuild can pick them up
626 export __ProjectDir="$__ProjectRoot"
627 __SourceDir="$__ProjectDir/src"
628 __PackagesDir="$__ProjectDir/packages"
629 __RootBinDir="$__ProjectDir/bin"
630 __BuildToolsDir="$__ProjectDir/Tools"
631 __DotNetCli="${__BuildToolsDir}/dotnetcli/dotnet"
632 __UnprocessedBuildArgs=
633 __RunArgs=
634 __MSBCleanBuildArgs=
635 __UseNinja=0
636 __VerboseBuild=0
637 __SkipRestore=""
638 __SkipNative=0
639 __SkipManaged=0
640 __SkipConfigure=0
641 __SkipGenerateVersion=0
642 __ConfigureOnly=0
643 __CrossBuild=0
644 __ClangMajorVersion=0
645 __ClangMinorVersion=0
646 __NuGetPath="$__PackagesDir/NuGet.exe"
647 __HostDistroRid=""
648 __SkipRestorePackages=0
649 __DistroRid=""
650 __cmakeargs=""
651 __PortableLinux=0
652 __msbuildonunsupportedplatform=0
653 __ZipTests=0
654 __NativeTestIntermediatesDir=
655 __RunTests=0
656 __RebuildTests=0
657 __BuildTestWrappers=1
658 __GenerateLayoutOnly=
659 __GenerateTestHostOnly=
660 __priority1=
661 CORE_ROOT=
662
663 while :; do
664     if [ $# -le 0 ]; then
665         break
666     fi
667
668     lowerI="$(echo $1 | awk '{print tolower($0)}')"
669     case $lowerI in
670         -\?|-h|--help)
671             usage
672             exit 1
673             ;;
674
675         x86)
676             __BuildArch=x86
677             ;;
678
679         x64)
680             __BuildArch=x64
681             ;;
682
683         arm)
684             __BuildArch=arm
685             ;;
686
687         armel)
688             __BuildArch=armel
689             ;;
690
691         arm64)
692             __BuildArch=arm64
693             ;;
694
695         debug)
696             __BuildType=Debug
697             ;;
698
699         checked)
700             __BuildType=Checked
701             ;;
702
703         release)
704             __BuildType=Release
705             ;;
706
707         coverage)
708             __CodeCoverage=Coverage
709             ;;
710
711         cross)
712             __CrossBuild=1
713             ;;
714
715         portableBuild)
716             __PortableBuild=1
717             ;;
718
719         portablelinux)
720             if [ "$__BuildOS" == "Linux" ]; then
721                 __PortableLinux=1
722             else
723                 echo "ERROR: portableLinux not supported for non-Linux platforms."
724                 exit 1
725             fi
726             ;;
727
728         verbose)
729         __VerboseBuild=1
730         ;;
731
732         clang3.5|-clang3.5)
733             __ClangMajorVersion=3
734             __ClangMinorVersion=5
735             ;;
736
737         clang3.6|-clang3.6)
738             __ClangMajorVersion=3
739             __ClangMinorVersion=6
740             ;;
741
742         clang3.7|-clang3.7)
743             __ClangMajorVersion=3
744             __ClangMinorVersion=7
745             ;;
746
747         clang3.8|-clang3.8)
748             __ClangMajorVersion=3
749             __ClangMinorVersion=8
750             ;;
751
752         clang3.9|-clang3.9)
753             __ClangMajorVersion=3
754             __ClangMinorVersion=9
755             ;;
756
757         clang4.0|-clang4.0)
758             __ClangMajorVersion=4
759             __ClangMinorVersion=0
760             ;;
761
762         clang5.0|-clang5.0)
763             __ClangMajorVersion=5
764             __ClangMinorVersion=0
765             ;;
766
767         clang6.0|-clang6.0)
768             __ClangMajorVersion=6
769             __ClangMinorVersion=0
770             ;;
771
772         ninja)
773             __UseNinja=1
774             ;;
775
776         runtests)
777             __RunTests=1
778             ;;
779
780         rebuild)
781             __RebuildTests=1
782             ;;
783
784         skipnative|-skipnative)
785             __SkipNative=1
786             ;;
787
788         skipmanaged|-skipmanaged)
789             __SkipManaged=1
790             __BuildTestWrappers=0
791             ;;
792
793         ziptests)
794             __ZipTests=1
795             ;;
796
797         generatelayoutonly)
798             __GenerateLayoutOnly=1
799             ;;
800         generatetesthostonly)
801             __GenerateTestHostOnly=1
802             ;;
803         skiprestorepackages)
804             __SkipRestorePackages=1
805             ;;
806
807         bindir)
808             if [ -n "$2" ]; then
809                 __RootBinDir="$2"
810                 if [ ! -d $__RootBinDir ]; then
811                     mkdir $__RootBinDir
812                 fi
813                 __RootBinParent=$(dirname $__RootBinDir)
814                 __RootBinName=${__RootBinDir##*/}
815                 __RootBinDir="$(cd $__RootBinParent &>/dev/null && printf %s/%s $PWD $__RootBinName)"
816                 shift
817             else
818                 echo "ERROR: 'bindir' requires a non-empty option argument"
819                 exit 1
820             fi
821             ;;
822
823         msbuildonunsupportedplatform)
824             __msbuildonunsupportedplatform=1
825             ;;
826         priority1)
827             __priority1=1
828             __UnprocessedBuildArgs+=("-priority=1")
829             ;;
830         *)
831             __UnprocessedBuildArgs+=("$1")
832             ;;
833     esac
834
835     shift
836 done
837
838 # Get the number of processors available to the scheduler
839 # Other techniques such as `nproc` only get the number of
840 # processors available to a single process.
841 if [ `uname` = "FreeBSD" ]; then
842   __NumProc=`sysctl hw.ncpu | awk '{ print $2+1 }'`
843 elif [ `uname` = "NetBSD" ]; then
844   __NumProc=$(($(getconf NPROCESSORS_ONLN)+1))
845 elif [ `uname` = "Darwin" ]; then
846   __NumProc=$(($(getconf _NPROCESSORS_ONLN)+1))
847 else
848   __NumProc=$(nproc --all)
849 fi
850
851 __RunArgs=("-BuildArch=$__BuildArch" "-BuildType=$__BuildType" "-BuildOS=$__BuildOS")
852
853 # Configure environment if we are doing a verbose build
854 if [ $__VerboseBuild == 1 ]; then
855     export VERBOSE=1
856     __RunArgs+=("-verbose")
857 fi
858
859 # Set default clang version
860 if [[ $__ClangMajorVersion == 0 && $__ClangMinorVersion == 0 ]]; then
861     if [[ "$__BuildArch" == "arm" || "$__BuildArch" == "armel" ]]; then
862         __ClangMajorVersion=5
863         __ClangMinorVersion=0
864     else
865         __ClangMajorVersion=3
866         __ClangMinorVersion=9
867     fi
868 fi
869
870 # Set dependent variables
871 __LogsDir="$__RootBinDir/Logs"
872
873 # init the host distro name
874 initHostDistroRid
875
876 # Set the remaining variables based upon the determined build configuration
877 __BinDir="$__RootBinDir/Product/$__BuildOS.$__BuildArch.$__BuildType"
878 __PackagesBinDir="$__BinDir/.nuget"
879 __TestDir="$__ProjectDir/tests"
880 __TestWorkingDir="$__RootBinDir/tests/$__BuildOS.$__BuildArch.$__BuildType"
881 __IntermediatesDir="$__RootBinDir/obj/$__BuildOS.$__BuildArch.$__BuildType"
882 __TestIntermediatesDir="$__RootBinDir/tests/obj/$__BuildOS.$__BuildArch.$__BuildType"
883 __isMSBuildOnNETCoreSupported=0
884 __CrossComponentBinDir="$__BinDir"
885 __CrossCompIntermediatesDir="$__IntermediatesDir/crossgen"
886
887 __CrossArch="$__HostArch"
888 if [[ "$__HostArch" == "x64" && "$__BuildArch" == "arm" ]]; then
889     __CrossArch="x86"
890 fi
891 if [ $__CrossBuild == 1 ]; then
892     __CrossComponentBinDir="$__CrossComponentBinDir/$__CrossArch"
893 fi
894 __CrossgenCoreLibLog="$__LogsDir/CrossgenCoreLib_$__BuildOS.$BuildArch.$__BuildType.log"
895 __CrossgenExe="$__CrossComponentBinDir/crossgen"
896
897 isMSBuildOnNETCoreSupported
898
899 # CI_SPECIFIC - On CI machines, $HOME may not be set. In such a case, create a subfolder and set the variable to it.
900 # This is needed by CLI to function.
901 if [ -z "$HOME" ]; then
902     if [ ! -d "$__ProjectDir/temp_home" ]; then
903         mkdir temp_home
904     fi
905     export HOME=$__ProjectDir/temp_home
906     echo "HOME not defined; setting it to $HOME"
907 fi
908
909 # Configure environment if we are doing a cross compile.
910 if [ $__CrossBuild == 1 ]; then
911     export CROSSCOMPILE=1
912     if ! [[ -n "$ROOTFS_DIR" ]]; then
913         export ROOTFS_DIR="$__ProjectRoot/cross/rootfs/$__BuildArch"
914     fi
915 fi
916
917 # init the target distro name
918 initTargetDistroRid
919
920 # Override tool directory
921
922 __CoreClrVersion=1.1.0
923 __sharedFxDir=$__BuildToolsDir/dotnetcli/shared/Microsoft.NETCore.App/$__CoreClrVersion/
924
925 if [[ (-z "$__GenerateLayoutOnly") && (-z "$__GenerateTestHostOnly") ]]; then
926     echo "Building Tests..."
927     build_Tests
928 else
929     echo "Generating test layout..."
930     generate_layout
931     if [ ! -z "$__GenerateTestHostOnly" ]; then
932         echo "Generating test host..."
933         generate_testhost
934     fi
935 fi
936
937 if [ $? -ne 0 ]; then
938     echo "Failed to build tests"
939     exit 1
940 fi
941
942 echo "${__MsgPrefix}Test build successful."
943 echo "${__MsgPrefix}Test binaries are available at ${__TestBinDir}"
944
945 __testNativeBinDir=$__IntermediatesDir/tests
946
947 if [ $__RunTests -ne 0 ]; then
948
949     echo "Run Tests..."
950
951     echo "${__TestDir}/runtest.sh --testRootDir=$__TestBinDir --coreClrBinDir=$__BinDir --coreFxBinDir=$__sharedFxDir --testNativeBinDir=$__testNativeBinDir"
952
953     $__TestDir/runtest.sh --testRootDir=$__TestBinDir --coreClrBinDir=$__BinDir --coreFxBinDir=$CORE_ROOT --testNativeBinDir=$__testNativeBinDir
954
955     echo "Tests run successful."
956 else
957     echo "To run all tests use 'tests/runtests.sh' where:"
958     echo "    testRootDir      = $__TestBinDir"
959     echo "    coreClrBinDir    = $__BinDir"
960     echo "    coreFxBinDir     = $CORE_ROOT"
961     echo "    testNativeBinDir = $__testNativeBinDir"
962     echo " -------------------------------------------------- "
963     echo " Example runtest.sh command"
964     echo ""
965     echo " ./tests/runtest.sh --coreOverlayDir=$CORE_ROOT --testNativeBinDir=$__testNativeBinDir --testRootDir=$__TestBinDir --copyNativeTestBin"
966     echo " -------------------------------------------------- "
967     echo "To run single test use the following command:"
968     echo "    bash ${__TestBinDir}/__TEST_PATH__/__TEST_NAME__.sh -coreroot=${CORE_ROOT}"
969 fi
970