[Unix|*] Rework and share the logic for determining __DistroRid (#22628)
[platform/upstream/coreclr.git] / build.sh
1 #!/usr/bin/env bash
2
3 # Work around Jenkins CI + msbuild problem: Jenkins sometimes creates very large environment
4 # variables, and msbuild can't handle environment blocks with such large variables. So clear
5 # out the variables that might be too large.
6 export ghprbCommentBody=
7
8 # resolve python-version to use
9 if [ "$PYTHON" == "" ] ; then
10     if ! PYTHON=$(command -v python3 || command -v python2 || command -v python || command -v py)
11     then
12        echo "Unable to locate build-dependency python!" 1>&2
13        exit 1
14     fi
15 fi
16 # validate python-dependency
17 # useful in case of explicitly set option.
18 if ! command -v $PYTHON > /dev/null
19 then
20    echo "Unable to locate build-dependency python ($PYTHON)!" 1>&2
21    exit 1
22 fi
23
24 export PYTHON
25
26 usage()
27 {
28     echo "Usage: $0 [BuildArch] [BuildType] [-verbose] [-coverage] [-cross] [-gccx.y] [-clangx.y] [-ninja] [-configureonly] [-skipconfigure] [-skipnative] [-skipcrossarchnative] [-skipmanaged] [-skipmscorlib] [-skiptests] [-stripsymbols] [-ignorewarnings] [-cmakeargs] [-bindir]"
29     echo "BuildArch can be: -x64, -x86, -arm, -armel, -arm64"
30     echo "BuildType can be: -debug, -checked, -release"
31     echo "-coverage - optional argument to enable code coverage build (currently supported only for Linux and OSX)."
32     echo "-ninja - target ninja instead of GNU make"
33     echo "-gccx.y - optional argument to build using gcc version x.y."
34     echo "-clangx.y - optional argument to build using clang version x.y."
35     echo "-cross - optional argument to signify cross compilation,"
36     echo "       - will use ROOTFS_DIR environment variable if set."
37     echo "-nopgooptimize - do not use profile guided optimizations."
38     echo "-pgoinstrument - generate instrumented code for profile guided optimization enabled binaries."
39     echo "-ibcinstrument - generate IBC-tuning-enabled native images when invoking crossgen."
40     echo "-configureonly - do not perform any builds; just configure the build."
41     echo "-skipconfigure - skip build configuration."
42     echo "-skipnative - do not build native components."
43     echo "-skipcrossarchnative - do not build cross-architecture native components."
44     echo "-skipmanaged - do not build managed components."
45     echo "-skipmscorlib - do not build mscorlib.dll."
46     echo "-skiptests - skip the tests in the 'tests' subdirectory."
47     echo "-skipnuget - skip building nuget packages."
48     echo "-skiprestoreoptdata - skip restoring optimization data used by profile-based optimizations."
49     echo "-skipcrossgen - skip native image generation"
50     echo "-crossgenonly - only run native image generation"
51     echo "-partialngen - build CoreLib as PartialNGen"
52     echo "-verbose - optional argument to enable verbose build output."
53     echo "-skiprestore: skip restoring packages ^(default: packages are restored during build^)."
54     echo "-disableoss: Disable Open Source Signing for System.Private.CoreLib."
55     echo "-officialbuildid=^<ID^>: specify the official build ID to be used by this build."
56     echo "-stripSymbols - Optional argument to strip native symbols during the build."
57     echo "-skipgenerateversion - disable version generation even if MSBuild is supported."
58     echo "-ignorewarnings - do not treat warnings as errors"
59     echo "-cmakeargs - user-settable additional arguments passed to CMake."
60     echo "-bindir - output directory (defaults to $__ProjectRoot/bin)"
61     echo "-msbuildonunsupportedplatform - build managed binaries even if distro is not officially supported."
62     echo "-numproc - set the number of build processes."
63     echo "-portablebuild - pass -portablebuild=false to force a non-portable build."
64     exit 1
65 }
66
67 initTargetDistroRid()
68 {
69     source init-distro-rid.sh
70
71     local passedRootfsDir=""
72
73     # Only pass ROOTFS_DIR if cross is specified.
74     if (( ${__CrossBuild} == 1 )); then
75         passedRootfsDir=${ROOTFS_DIR}
76     elif [ "${__BuildArch}" != "${__HostArch}" ]; then
77         echo "Error, you are building a cross scenario without passing -cross."
78         exit 1
79     fi
80
81     initDistroRidGlobal ${__BuildOS} ${__BuildArch} ${__PortableBuild} ${passedRootfsDir}
82 }
83
84 setup_dirs()
85 {
86     echo Setting up directories for build
87
88     mkdir -p "$__RootBinDir"
89     mkdir -p "$__BinDir"
90     mkdir -p "$__LogsDir"
91     mkdir -p "$__MsbuildDebugLogsDir"
92     mkdir -p "$__IntermediatesDir"
93
94     if [ $__CrossBuild == 1 ]; then
95         mkdir -p "$__CrossComponentBinDir"
96     fi
97 }
98
99 # Check the system to ensure the right prereqs are in place
100
101 check_prereqs()
102 {
103     echo "Checking prerequisites..."
104
105     # Check presence of CMake on the path
106     hash cmake 2>/dev/null || { echo >&2 "Please install cmake before running this script"; exit 1; }
107
108
109     # Minimum required version of clang is version 4.0 for arm/armel cross build
110     if [[ $__CrossBuild == 1 && $__GccBuild == 0 &&  ("$__BuildArch" == "arm" || "$__BuildArch" == "armel") ]]; then
111         if ! [[ "$__ClangMajorVersion" -ge "4" ]]; then
112             echo "Please install clang4.0 or latest for arm/armel cross build"; exit 1;
113         fi
114     fi
115
116     # Check for clang
117     if [[ $__GccBuild == 0 ]]; then
118         __ClangCombinedDottedVersion=$__ClangMajorVersion;
119         if [[ "$__ClangMinorVersion" != "" ]]; then
120             __ClangCombinedDottedVersion=$__ClangCombinedDottedVersion.$__ClangMinorVersion
121         fi
122         hash clang-$__ClangCombinedDottedVersion 2>/dev/null ||  hash clang$__ClangMajorVersion$__ClangMinorVersion 2>/dev/null || hash clang 2>/dev/null || { echo >&2 "Please install clang-$__ClangMajorVersion.$__ClangMinorVersion before running this script"; exit 1; }
123     else
124         __GccCombinedDottedVersion=$__GccMajorVersion;
125         if [[ "$__GccMinorVersion" != "" ]]; then
126             __GccCombinedDottedVersion=$__GccCombinedDottedVersion.$__GccMinorVersion
127         fi
128         hash gcc-$__GccCombinedDottedVersion 2>/dev/null ||  hash gcc$__GccMajorVersion$__GccMinorVersion 2>/dev/null || hash gcc 2>/dev/null || { echo >&2 "Please install gcc-$__GccMajorVersion.$__GccMinorVersion before running this script"; exit 1; }
129     fi
130
131 }
132
133 restore_optdata()
134 {
135     # we only need optdata on a Release build
136     if [[ "$__BuildType" != "Release" ]]; then __SkipRestoreOptData=1; fi
137
138     if [[ ( $__SkipRestoreOptData == 0 ) && ( $__isMSBuildOnNETCoreSupported == 1 ) ]]; then
139         echo "Restoring the OptimizationData package"
140         "$__ProjectRoot/dotnet.sh" msbuild /nologo /verbosity:minimal /clp:Summary \
141                                    /p:RestoreDefaultOptimizationDataPackage=false /p:PortableBuild=true \
142                                    /p:UsePartialNGENOptimization=false /maxcpucount \
143                                    /t:RestoreOptData ./build.proj \
144                                    $__CommonMSBuildArgs $__UnprocessedBuildArgs
145         if [ $? != 0 ]; then
146             echo "Failed to restore the optimization data package."
147             exit 1
148         fi
149     fi
150
151     if [ $__isMSBuildOnNETCoreSupported == 1 ]; then
152         # Parse the optdata package versions out of msbuild so that we can pass them on to CMake
153         local DotNetCli="$__ProjectRoot/Tools/dotnetcli/dotnet"
154         if [ ! -f $DotNetCli ]; then
155             source "$__ProjectRoot/init-tools.sh"
156             if [ $? != 0 ]; then
157                 echo "Failed to restore buildtools."
158                 exit 1
159             fi
160         fi
161         local OptDataProjectFilePath="$__ProjectRoot/src/.nuget/optdata/optdata.csproj"
162         __PgoOptDataVersion=$(DOTNET_SKIP_FIRST_TIME_EXPERIENCE=1 $DotNetCli msbuild $OptDataProjectFilePath /t:DumpPgoDataPackageVersion /nologo | sed 's/^\s*//')
163         __IbcOptDataVersion=$(DOTNET_SKIP_FIRST_TIME_EXPERIENCE=1 $DotNetCli msbuild $OptDataProjectFilePath /t:DumpIbcDataPackageVersion /nologo | sed 's/^[[:blank:]]*//')
164     fi
165 }
166
167 generate_event_logging_sources()
168 {
169     __OutputDir=$1
170     __ConsumingBuildSystem=$2
171
172     __OutputIncDir="$__OutputDir/src/inc"
173     __OutputEventingDir="$__OutputDir/Eventing"
174     __OutputEventProviderDir="$__OutputEventingDir/eventprovider"
175
176     echo "Laying out dynamically generated files consumed by $__ConsumingBuildSystem"
177     echo "Laying out dynamically generated Event test files, etmdummy stub functions, and external linkages"
178
179     __PythonWarningFlags="-Wall"
180     if [[ $__IgnoreWarnings == 0 ]]; then
181         __PythonWarningFlags="$__PythonWarningFlags -Werror"
182     fi
183
184     $PYTHON -B $__PythonWarningFlags "$__ProjectRoot/src/scripts/genEventing.py" --inc $__OutputIncDir --dummy $__OutputIncDir/etmdummy.h --man "$__ProjectRoot/src/vm/ClrEtwAll.man" --testdir "$__OutputEventProviderDir/tests"
185     if [[ $? != 0 ]]; then
186         exit 1
187     fi
188
189     echo "Laying out dynamically generated EventPipe Implementation"
190     $PYTHON -B $__PythonWarningFlags "$__ProjectRoot/src/scripts/genEventPipe.py" --man "$__ProjectRoot/src/vm/ClrEtwAll.man" --intermediate "$__OutputEventingDir/eventpipe"
191
192     echo "Laying out dynamically generated EventSource classes"
193     $PYTHON -B $__PythonWarningFlags "$__ProjectRoot/src/scripts/genRuntimeEventSources.py" --man "$__ProjectRoot/src/vm/ClrEtwAll.man" --intermediate "$__OutputEventingDir"
194
195     # determine the logging system
196     case $__BuildOS in
197         Linux|FreeBSD)
198             echo "Laying out dynamically generated Event Logging Implementation of Lttng"
199             $PYTHON -B $__PythonWarningFlags "$__ProjectRoot/src/scripts/genLttngProvider.py" --man "$__ProjectRoot/src/vm/ClrEtwAll.man" --intermediate "$__OutputEventProviderDir"
200             if [[ $? != 0 ]]; then
201                 exit 1
202             fi
203             ;;
204         *)
205             echo "Laying out dummy event logging provider"
206             $PYTHON -B $__PythonWarningFlags "$__ProjectRoot/src/scripts/genDummyProvider.py" --man "$__ProjectRoot/src/vm/ClrEtwAll.man" --intermediate "$__OutputEventProviderDir"
207             if [[ $? != 0 ]]; then
208                 exit 1
209             fi
210             ;;
211     esac
212 }
213
214 generate_event_logging()
215 {
216     # Event Logging Infrastructure
217     if [[ $__SkipCoreCLR == 0 || $__SkipMSCorLib == 0 || $__ConfigureOnly == 1 ]]; then
218         generate_event_logging_sources "$__IntermediatesDir" "the native build system"
219     fi
220 }
221
222 build_native()
223 {
224     skipCondition=$1
225     platformArch="$2"
226     intermediatesForBuild="$3"
227     extraCmakeArguments="$4"
228     message="$5"
229
230     if [ $skipCondition == 1 ]; then
231         echo "Skipping $message build."
232         return
233     fi
234
235     # All set to commence the build
236     echo "Commencing build of $message for $__BuildOS.$__BuildArch.$__BuildType in $intermediatesForBuild"
237
238     generator=""
239     buildFile="Makefile"
240     buildTool="make"
241     if [ $__UseNinja == 1 ]; then
242         generator="ninja"
243         buildFile="build.ninja"
244         if ! buildTool=$(command -v ninja || command -v ninja-build); then
245            echo "Unable to locate ninja!" 1>&2
246            exit 1
247         fi
248     fi
249
250     if [ $__SkipConfigure == 0 ]; then
251         # if msbuild is not supported, then set __SkipGenerateVersion to 1
252         if [ $__isMSBuildOnNETCoreSupported == 0 ]; then __SkipGenerateVersion=1; fi
253         # Drop version.c file
254         __versionSourceFile="$intermediatesForBuild/version.c"
255         if [ $__SkipGenerateVersion == 0 ]; then
256             pwd
257             "$__ProjectRoot/dotnet.sh" msbuild /nologo /verbosity:minimal /clp:Summary \
258                                        /l:BinClashLogger,Tools/Microsoft.DotNet.Build.Tasks.dll\;LogFile=binclash.log \
259                                        /p:RestoreDefaultOptimizationDataPackage=false /p:PortableBuild=true \
260                                        /p:UsePartialNGENOptimization=false /maxcpucount \
261                                        "$__ProjectDir/build.proj" /p:GenerateVersionSourceFile=true /t:GenerateVersionSourceFile /p:NativeVersionSourceFile=$__versionSourceFile \
262                                        $__CommonMSBuildArgs $__UnprocessedBuildArgs
263         else
264             # Generate the dummy version.c, but only if it didn't exist to make sure we don't trigger unnecessary rebuild
265             __versionSourceLine="static char sccsid[] __attribute__((used)) = \"@(#)No version information produced\";"
266             if [ -e $__versionSourceFile ]; then
267                 read existingVersionSourceLine < $__versionSourceFile
268             fi
269             if [ "$__versionSourceLine" != "$existingVersionSourceLine" ]; then
270                 echo $__versionSourceLine > $__versionSourceFile
271             fi
272         fi
273
274
275         pushd "$intermediatesForBuild"
276         # Regenerate the CMake solution
277
278         if [[ $__GccBuild == 0 ]]; then
279             echo "Invoking \"$__ProjectRoot/src/pal/tools/gen-buildsys-clang.sh\" \"$__ProjectRoot\" $__ClangMajorVersion \"$__ClangMinorVersion\" $platformArch $__BuildType $__CodeCoverage $generator $extraCmakeArguments $__cmakeargs"
280             "$__ProjectRoot/src/pal/tools/gen-buildsys-clang.sh" "$__ProjectRoot" $__ClangMajorVersion "$__ClangMinorVersion" $platformArch $__BuildType $__CodeCoverage $generator "$extraCmakeArguments" "$__cmakeargs"
281         else
282             echo "Invoking \"$__ProjectRoot/src/pal/tools/gen-buildsys-gcc.sh\" \"$__ProjectRoot\" $__GccMajorVersion \"$__GccMinorVersion\" $platformArch $__BuildType $__CodeCoverage $generator $extraCmakeArguments $__cmakeargs"
283             "$__ProjectRoot/src/pal/tools/gen-buildsys-gcc.sh" "$__ProjectRoot" "$__GccMajorVersion" "$__CGccMinorVersion" $platformArch $__BuildType $__CodeCoverage $generator "$extraCmakeArguments" "$__cmakeargs"
284         fi
285         popd
286     fi
287
288     if [ ! -f "$intermediatesForBuild/$buildFile" ]; then
289         echo "Failed to generate $message build project!"
290         exit 1
291     fi
292
293     # Build
294     if [ $__ConfigureOnly == 1 ]; then
295         echo "Finish configuration & skipping $message build."
296         return
297     fi
298
299     # Check that the makefiles were created.
300     pushd "$intermediatesForBuild"
301
302     echo "Executing $buildTool install -j $__NumProc"
303
304     $buildTool install -j $__NumProc
305     if [ $? != 0 ]; then
306         echo "Failed to build $message."
307         exit 1
308     fi
309
310     popd
311 }
312
313 build_cross_architecture_components()
314 {
315     local intermediatesForBuild="$__IntermediatesDir/Host$__CrossArch/crossgen"
316     local crossArchBinDir="$__BinDir/$__CrossArch"
317
318     mkdir -p "$intermediatesForBuild"
319     mkdir -p "$crossArchBinDir"
320
321     generate_event_logging_sources "$intermediatesForBuild" "the crossarch build system"
322
323     __SkipCrossArchBuild=1
324     # check supported cross-architecture components host(__HostArch)/target(__BuildArch) pair
325     if [[ ("$__BuildArch" == "arm" || "$__BuildArch" == "armel") && ("$__CrossArch" == "x86" || "$__CrossArch" == "x64") ]]; then
326         __SkipCrossArchBuild=0
327     elif [[ "$__BuildArch" == "arm64" && "$__CrossArch" == "x64" ]]; then
328         __SkipCrossArchBuild=0
329     else
330         # not supported
331         return
332     fi
333
334     export __CMakeBinDir="$crossArchBinDir"
335     export CROSSCOMPILE=0
336
337     __ExtraCmakeArgs="-DCLR_CMAKE_TARGET_ARCH=$__BuildArch -DCLR_CMAKE_TARGET_OS=$__BuildOS -DCLR_CMAKE_PACKAGES_DIR=$__PackagesDir -DCLR_CMAKE_PGO_INSTRUMENT=$__PgoInstrument -DCLR_CMAKE_OPTDATA_VERSION=$__PgoOptDataVersion -DCLR_CMAKE_PGO_OPTIMIZE=$__PgoOptimize -DCLR_CROSS_COMPONENTS_BUILD=1"
338     build_native $__SkipCrossArchBuild "$__CrossArch" "$intermediatesForBuild" "$__ExtraCmakeArgs" "cross-architecture components"
339
340     export CROSSCOMPILE=1
341 }
342
343 isMSBuildOnNETCoreSupported()
344 {
345     __isMSBuildOnNETCoreSupported=$__msbuildonunsupportedplatform
346
347     if [ $__isMSBuildOnNETCoreSupported == 1 ]; then
348         return
349     fi
350
351     if [ $__SkipManaged == 1 ]; then
352         __isMSBuildOnNETCoreSupported=0
353         return
354     fi
355
356     if [ "$__HostArch" == "x64" ]; then
357         if [ "$__HostOS" == "Linux" ]; then
358             __isMSBuildOnNETCoreSupported=1
359             # note: the RIDs below can use globbing patterns
360             UNSUPPORTED_RIDS=("ubuntu.17.04-x64")
361             for UNSUPPORTED_RID in "${UNSUPPORTED_RIDS[@]}"
362             do
363                 if [[ ${__DistroRid} == $UNSUPPORTED_RID ]]; then
364                     __isMSBuildOnNETCoreSupported=0
365                     break
366                 fi
367             done
368         elif [ "$__HostOS" == "OSX" ]; then
369             __isMSBuildOnNETCoreSupported=1
370         elif [ "$__HostOS" == "FreeBSD" ]; then
371             __isMSBuildOnNETCoreSupported=1
372         fi
373     fi
374 }
375
376
377 build_CoreLib_ni()
378 {
379     local __CrossGenExec=$1
380
381     if [ $__PartialNgen == 1 ]; then
382         export COMPlus_PartialNGen=1
383     fi
384
385     if [ -e $__CrossGenCoreLibLog ]; then
386         rm $__CrossGenCoreLibLog
387     fi
388     echo "Generating native image of System.Private.CoreLib.dll for $__BuildOS.$__BuildArch.$__BuildType. Logging to \"$__CrossGenCoreLibLog\"."
389     echo "$__CrossGenExec /Platform_Assemblies_Paths $__BinDir/IL $__IbcTuning /out $__BinDir/System.Private.CoreLib.dll $__BinDir/IL/System.Private.CoreLib.dll"
390     $__CrossGenExec /Platform_Assemblies_Paths $__BinDir/IL $__IbcTuning /out $__BinDir/System.Private.CoreLib.dll $__BinDir/IL/System.Private.CoreLib.dll >> $__CrossGenCoreLibLog 2>&1
391     if [ $? -ne 0 ]; then
392         echo "Failed to generate native image for System.Private.CoreLib. Refer to $__CrossGenCoreLibLog"
393         exit 1
394     fi
395
396     if [ "$__BuildOS" == "Linux" ]; then
397         echo "Generating symbol file for System.Private.CoreLib.dll"
398         echo "$__CrossGenExec /Platform_Assemblies_Paths $__BinDir /CreatePerfMap $__BinDir $__BinDir/System.Private.CoreLib.dll"
399         $__CrossGenExec /Platform_Assemblies_Paths $__BinDir /CreatePerfMap $__BinDir $__BinDir/System.Private.CoreLib.dll >> $__CrossGenCoreLibLog 2>&1
400         if [ $? -ne 0 ]; then
401             echo "Failed to generate symbol file for System.Private.CoreLib. Refer to $__CrossGenCoreLibLog"
402             exit 1
403         fi
404     fi
405 }
406
407 build_CoreLib()
408 {
409     if [ $__isMSBuildOnNETCoreSupported == 0 ]; then
410         echo "System.Private.CoreLib.dll build unsupported."
411         return
412     fi
413
414     if [ $__SkipMSCorLib == 1 ]; then
415        echo "Skipping building System.Private.CoreLib."
416        return
417     fi
418
419     echo "Commencing build of managed components for $__BuildOS.$__BuildArch.$__BuildType"
420
421     # Invoke MSBuild
422     __ExtraBuildArgs=""
423     if [[ "$__IbcTuning" == "" ]]; then
424         __ExtraBuildArgs="$__ExtraBuildArgs /p:OptimizationDataDir=\"$__PackagesDir/optimization.$__BuildOS-$__BuildArch.IBC.CoreCLR/$__IbcOptDataVersion/data\""
425         __ExtraBuildArgs="$__ExtraBuildArgs /p:EnableProfileGuidedOptimization=true"
426     fi
427
428     if [[ "$__BuildManagedTools" -eq "1" ]]; then
429         __ExtraBuildArgs="$__ExtraBuildArgs /p:BuildManagedTools=true"
430     fi
431
432     $__ProjectRoot/dotnet.sh msbuild /nologo /verbosity:minimal /clp:Summary \
433                              /l:BinClashLogger,Tools/Microsoft.DotNet.Build.Tasks.dll\;LogFile=binclash.log \
434                              /p:RestoreDefaultOptimizationDataPackage=false /p:PortableBuild=true \
435                              /p:UsePartialNGENOptimization=false /maxcpucount \
436                              $__ProjectDir/build.proj \
437                              /flp:Verbosity=normal\;LogFile=$__LogsDir/System.Private.CoreLib_$__BuildOS__$__BuildArch__$__BuildType.log \
438                              /p:__IntermediatesDir=$__IntermediatesDir /p:__RootBinDir=$__RootBinDir /p:BuildNugetPackage=false \
439                              $__CommonMSBuildArgs $__ExtraBuildArgs $__UnprocessedBuildArgs
440
441     if [ $? -ne 0 ]; then
442         echo "Failed to build managed components."
443         exit 1
444     fi
445
446     if [ $__SkipCrossgen == 1 ]; then
447         echo "Skipping generating native image"
448         return
449     fi
450
451     # The cross build generates a crossgen with the target architecture.
452     if [ $__CrossBuild == 0 ]; then
453        if [ $__SkipCoreCLR == 1 ]; then
454            return
455        fi
456
457        # The architecture of host pc must be same architecture with target.
458        if [[ ( "$__HostArch" == "$__BuildArch" ) ]]; then
459            build_CoreLib_ni "$__BinDir/crossgen"
460        elif [[ ( "$__HostArch" == "x64" ) && ( "$__BuildArch" == "x86" ) ]]; then
461            build_CoreLib_ni "$__BinDir/crossgen"
462        elif [[ ( "$__HostArch" == "arm64" ) && ( "$__BuildArch" == "arm" ) ]]; then
463            build_CoreLib_ni "$__BinDir/crossgen"
464        else
465            exit 1
466        fi
467     else
468        if [[ ( "$__CrossArch" == "x86" ) && ( "$__BuildArch" == "arm" ) ]]; then
469            build_CoreLib_ni "$__CrossComponentBinDir/crossgen"
470        elif [[ ( "$__CrossArch" == "x64" ) && ( "$__BuildArch" == "arm" ) ]]; then
471            build_CoreLib_ni "$__CrossComponentBinDir/crossgen"
472        elif [[ ( "$__HostArch" == "x64" ) && ( "$__BuildArch" == "arm64" ) ]]; then
473            build_CoreLib_ni "$__CrossComponentBinDir/crossgen"
474        fi
475     fi
476 }
477
478 generate_NugetPackages()
479 {
480     # We can only generate nuget package if we also support building mscorlib as part of this build.
481     if [ $__isMSBuildOnNETCoreSupported == 0 ]; then
482         echo "Nuget package generation unsupported."
483         return
484     fi
485
486     # Since we can build mscorlib for this OS, did we build the native components as well?
487     if [[ $__SkipCoreCLR == 1 && $__CrossgenOnly == 0 ]]; then
488         echo "Unable to generate nuget packages since native components were not built."
489         return
490     fi
491
492     echo "Generating nuget packages for "$__BuildOS
493     echo "DistroRid is "$__DistroRid
494     echo "ROOTFS_DIR is "$ROOTFS_DIR
495     # Build the packages
496     $__ProjectRoot/dotnet.sh msbuild /nologo /verbosity:minimal /clp:Summary \
497                              /l:BinClashLogger,Tools/Microsoft.DotNet.Build.Tasks.dll\;LogFile=binclash.log \
498                              /p:RestoreDefaultOptimizationDataPackage=false /p:PortableBuild=true \
499                              /p:UsePartialNGENOptimization=false /maxcpucount \
500                              $__SourceDir/.nuget/packages.builds \
501                              /flp:Verbosity=normal\;LogFile=$__LogsDir/Nuget_$__BuildOS__$__BuildArch__$__BuildType.log \
502                              /p:__IntermediatesDir=$__IntermediatesDir /p:__RootBinDir=$__RootBinDir /p:BuildNugetPackages=false /p:__DoCrossArchBuild=$__CrossBuild \
503                              $__CommonMSBuildArgs $__UnprocessedBuildArgs
504
505     if [ $? -ne 0 ]; then
506         echo "Failed to generate Nuget packages."
507         exit 1
508     fi
509 }
510
511 echo "Commencing CoreCLR Repo build"
512
513 # Argument types supported by this script:
514 #
515 # Build architecture - valid values are: x64, ARM.
516 # Build Type         - valid values are: Debug, Checked, Release
517 #
518 # Set the default arguments for build
519
520 # Obtain the location of the bash script to figure out where the root of the repo is.
521 __ProjectRoot="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )"
522
523 # Use uname to determine what the CPU is.
524 CPUName=$(uname -p)
525 # Some Linux platforms report unknown for platform, but the arch for machine.
526 if [ "$CPUName" == "unknown" ]; then
527     CPUName=$(uname -m)
528 fi
529
530 case $CPUName in
531     i686)
532         echo "Unsupported CPU $CPUName detected, build might not succeed!"
533         __BuildArch=x86
534         __HostArch=x86
535         ;;
536
537     x86_64)
538         __BuildArch=x64
539         __HostArch=x64
540         ;;
541
542     armv7l)
543         echo "Unsupported CPU $CPUName detected, build might not succeed!"
544         __BuildArch=arm
545         __HostArch=arm
546         ;;
547
548     aarch64)
549         __BuildArch=arm64
550         __HostArch=arm64
551         ;;
552
553     amd64)
554         __BuildArch=x64
555         __HostArch=x64
556         ;;
557     *)
558         echo "Unknown CPU $CPUName detected, configuring as if for x64"
559         __BuildArch=x64
560         __HostArch=x64
561         ;;
562 esac
563
564 # Use uname to determine what the OS is.
565 OSName=$(uname -s)
566 case $OSName in
567     Linux)
568         __BuildOS=Linux
569         __HostOS=Linux
570         ;;
571
572     Darwin)
573         __BuildOS=OSX
574         __HostOS=OSX
575         ;;
576
577     FreeBSD)
578         __BuildOS=FreeBSD
579         __HostOS=FreeBSD
580         ;;
581
582     OpenBSD)
583         __BuildOS=OpenBSD
584         __HostOS=OpenBSD
585         ;;
586
587     NetBSD)
588         __BuildOS=NetBSD
589         __HostOS=NetBSD
590         ;;
591
592     SunOS)
593         __BuildOS=SunOS
594         __HostOS=SunOS
595         ;;
596
597     *)
598         echo "Unsupported OS $OSName detected, configuring as if for Linux"
599         __BuildOS=Linux
600         __HostOS=Linux
601         ;;
602 esac
603
604 __BuildType=Debug
605 __CodeCoverage=
606 __IgnoreWarnings=0
607
608 # Set the various build properties here so that CMake and MSBuild can pick them up
609 __ProjectDir="$__ProjectRoot"
610 __SourceDir="$__ProjectDir/src"
611 __PackagesDir="${DotNetRestorePackagesPath:-${__ProjectDir}/packages}"
612 __RootBinDir="$__ProjectDir/bin"
613 __UnprocessedBuildArgs=
614 __CommonMSBuildArgs=
615 __MSBCleanBuildArgs=
616 __UseNinja=0
617 __VerboseBuild=0
618 __PgoInstrument=0
619 __PgoOptimize=1
620 __IbcTuning=""
621 __ConfigureOnly=0
622 __SkipConfigure=0
623 __SkipManaged=0
624 __SkipRestore=""
625 __SkipNuget=0
626 __SkipCoreCLR=0
627 __SkipCrossArchNative=0
628 __SkipMSCorLib=0
629 __SkipRestoreOptData=0
630 __SkipCrossgen=0
631 __CrossgenOnly=0
632 __PartialNgen=0
633 __SkipTests=0
634 __CrossBuild=0
635 __ClangMajorVersion=0
636 __ClangMinorVersion=0
637 __GccBuild=0
638 __GccMajorVersion=0
639 __GccMinorVersion=0
640 __NuGetPath="$__PackagesDir/NuGet.exe"
641 __DistroRid=""
642 __cmakeargs=""
643 __SkipGenerateVersion=0
644 __PortableBuild=1
645 __msbuildonunsupportedplatform=0
646 __PgoOptDataVersion=""
647 __IbcOptDataVersion=""
648 __BuildManagedTools=1
649 __SkipRestoreArg=""
650 __SignTypeArg=""
651 __OfficialBuildIdArg=""
652
653 # Get the number of processors available to the scheduler
654 # Other techniques such as `nproc` only get the number of
655 # processors available to a single process.
656 if [ `uname` = "FreeBSD" ]; then
657   __NumProc=`sysctl hw.ncpu | awk '{ print $2+1 }'`
658 elif [ `uname` = "NetBSD" ]; then
659   __NumProc=$(($(getconf NPROCESSORS_ONLN)+1))
660 elif [ `uname` = "Darwin" ]; then
661   __NumProc=$(($(getconf _NPROCESSORS_ONLN)+1))
662 else
663   __NumProc=$(nproc --all)
664 fi
665
666 while :; do
667     if [ $# -le 0 ]; then
668         break
669     fi
670
671     lowerI="$(echo $1 | awk '{print tolower($0)}')"
672     case $lowerI in
673         -\?|-h|--help)
674             usage
675             exit 1
676             ;;
677
678         x86|-x86)
679             __BuildArch=x86
680             ;;
681
682         x64|-x64)
683             __BuildArch=x64
684             ;;
685
686         arm|-arm)
687             __BuildArch=arm
688             ;;
689
690         armel|-armel)
691             __BuildArch=armel
692             ;;
693
694         arm64|-arm64)
695             __BuildArch=arm64
696             ;;
697
698         debug|-debug)
699             __BuildType=Debug
700             ;;
701
702         checked|-checked)
703             __BuildType=Checked
704             ;;
705
706         release|-release)
707             __BuildType=Release
708             ;;
709
710         coverage|-coverage)
711             __CodeCoverage=Coverage
712             ;;
713
714         cross|-cross)
715             __CrossBuild=1
716             ;;
717
718         -portablebuild=false)
719             __PortableBuild=0
720             ;;
721
722         verbose|-verbose)
723             __VerboseBuild=1
724             ;;
725
726         stripsymbols|-stripsymbols)
727             __cmakeargs="$__cmakeargs -DSTRIP_SYMBOLS=true"
728             ;;
729
730         clang3.5|-clang3.5)
731             __ClangMajorVersion=3
732             __ClangMinorVersion=5
733             ;;
734
735         clang3.6|-clang3.6)
736             __ClangMajorVersion=3
737             __ClangMinorVersion=6
738             ;;
739
740         clang3.7|-clang3.7)
741             __ClangMajorVersion=3
742             __ClangMinorVersion=7
743             ;;
744
745         clang3.8|-clang3.8)
746             __ClangMajorVersion=3
747             __ClangMinorVersion=8
748             ;;
749
750         clang3.9|-clang3.9)
751             __ClangMajorVersion=3
752             __ClangMinorVersion=9
753             ;;
754
755         clang4.0|-clang4.0)
756             __ClangMajorVersion=4
757             __ClangMinorVersion=0
758             ;;
759
760         clang5.0|-clang5.0)
761             __ClangMajorVersion=5
762             __ClangMinorVersion=0
763             ;;
764
765         clang6.0|-clang6.0)
766             __ClangMajorVersion=6
767             __ClangMinorVersion=0
768             ;;
769
770         clang7|-clang7)
771             __ClangMajorVersion=7
772             __ClangMinorVersion=
773             ;;
774
775         gcc5|-gcc5)
776             __GccMajorVersion=5
777             __GccMinorVersion=
778             __GccBuild=1
779             ;;
780
781         gcc7|-gcc7)
782             __GccMajorVersion=7
783             __GccMinorVersion=
784             __GccBuild=1
785             ;;
786
787         gcc|-gcc)
788             __GccMajorVersion=
789             __GccMinorVersion=
790             __GccBuild=1
791             ;;
792
793         ninja|-ninja)
794             __UseNinja=1
795             ;;
796
797         pgoinstrument|-pgoinstrument)
798             __PgoInstrument=1
799             ;;
800
801         nopgooptimize|-nopgooptimize)
802             __PgoOptimize=0
803             __SkipRestoreOptData=1
804             ;;
805
806         ibcinstrument|-ibcinstrument)
807             __IbcTuning="/Tuning"
808             ;;
809
810         configureonly|-configureonly)
811             __ConfigureOnly=1
812             __SkipMSCorLib=1
813             __SkipNuget=1
814             ;;
815
816         skipconfigure|-skipconfigure)
817             __SkipConfigure=1
818             ;;
819
820         skipnative|-skipnative)
821             # Use "skipnative" to use the same option name as build.cmd.
822             __SkipCoreCLR=1
823             ;;
824
825         skipcoreclr|-skipcoreclr)
826             # Accept "skipcoreclr" for backwards-compatibility.
827             __SkipCoreCLR=1
828             ;;
829
830         skipcrossarchnative|-skipcrossarchnative)
831             __SkipCrossArchNative=1
832             ;;
833
834         skipmanaged|-skipmanaged)
835             __SkipManaged=1
836             ;;
837
838         skipmscorlib|-skipmscorlib)
839             __SkipMSCorLib=1
840             ;;
841
842         skipgenerateversion|-skipgenerateversion)
843             __SkipGenerateVersion=1
844             ;;
845
846         skiprestoreoptdata|-skiprestoreoptdata)
847             __SkipRestoreOptData=1
848             ;;
849
850         skipcrossgen|-skipcrossgen)
851             __SkipCrossgen=1
852             ;;
853
854         crossgenonly|-crossgenonly)
855             __SkipMSCorLib=1
856             __SkipCoreCLR=1
857             __CrossgenOnly=1
858             ;;
859         partialngen|-partialngen)
860             __PartialNgen=1
861             ;;
862
863         skiptests|-skiptests)
864             __SkipTests=1
865             ;;
866
867         skipnuget|-skipnuget|skipbuildpackages|-skipbuildpackages)
868             __SkipNuget=1
869             ;;
870
871         ignorewarnings|-ignorewarnings)
872             __IgnoreWarnings=1
873             __cmakeargs="$__cmakeargs -DCLR_CMAKE_WARNINGS_ARE_ERRORS=OFF"
874             ;;
875
876         cmakeargs|-cmakeargs)
877             if [ -n "$2" ]; then
878                 __cmakeargs="$__cmakeargs $2"
879                 shift
880             else
881                 echo "ERROR: 'cmakeargs' requires a non-empty option argument"
882                 exit 1
883             fi
884             ;;
885
886         bindir|-bindir)
887             if [ -n "$2" ]; then
888                 __RootBinDir="$2"
889                 if [ ! -d $__RootBinDir ]; then
890                     mkdir $__RootBinDir
891                 fi
892                 __RootBinParent=$(dirname $__RootBinDir)
893                 __RootBinName=${__RootBinDir##*/}
894                 __RootBinDir="$(cd $__RootBinParent &>/dev/null && printf %s/%s $PWD $__RootBinName)"
895                 shift
896             else
897                 echo "ERROR: 'bindir' requires a non-empty option argument"
898                 exit 1
899             fi
900             ;;
901         msbuildonunsupportedplatform|-msbuildonunsupportedplatform)
902             __msbuildonunsupportedplatform=1
903             ;;
904         numproc|-numproc)
905             if [ -n "$2" ]; then
906               __NumProc="$2"
907               shift
908             else
909               echo "ERROR: 'numproc' requires a non-empty option argument"
910               exit 1
911             fi
912             ;;
913         osgroup|-osgroup)
914             if [ -n "$2" ]; then
915               __BuildOS="$2"
916               shift
917             else
918               echo "ERROR: 'osgroup' requires a non-empty option argument"
919               exit 1
920             fi
921             ;;
922         rebuild|-rebuild)
923             echo "ERROR: 'Rebuild' is not supported.  Please remove it."
924             exit 1
925             ;;
926
927         -skiprestore)
928             __SkipRestoreArg="/p:RestoreDuringBuild=false"
929             ;;
930
931         -disableoss)
932             __SignTypeArg="/p:SignType=real"
933             ;;
934
935         -officialbuildid=*)
936             __Id=$(echo $1| cut -d'=' -f 2)
937             __OfficialBuildIdArg="/p:OfficialBuildId=$__Id"
938             ;;
939
940         --)
941             # Skip -Option=Value style argument passing
942             ;;
943
944         *)
945             __UnprocessedBuildArgs="$__UnprocessedBuildArgs $1"
946             ;;
947     esac
948
949     shift
950 done
951
952 __CommonMSBuildArgs="/p:__BuildArch=$__BuildArch /p:__BuildType=$__BuildType /p:__BuildOS=$__BuildOS $__OfficialBuildIdArg $__SignTypeArg $__SkipRestoreArg"
953
954 # Configure environment if we are doing a verbose build
955 if [ $__VerboseBuild == 1 ]; then
956     export VERBOSE=1
957     __CommonMSBuildArgs="$__CommonMSBuildArgs /v:detailed"
958 fi
959
960 # Set default clang version
961 if [[ $__ClangMajorVersion == 0 && $__ClangMinorVersion == 0 ]]; then
962     if [[ "$__BuildArch" == "arm" || "$__BuildArch" == "armel" ]]; then
963         __ClangMajorVersion=5
964         __ClangMinorVersion=0
965     else
966         __ClangMajorVersion=3
967         __ClangMinorVersion=9
968     fi
969 fi
970
971 if [[ "$__BuildArch" == "armel" ]]; then
972     # Armel cross build is Tizen specific and does not support Portable RID build
973     __PortableBuild=0
974 fi
975
976 if [ $__PortableBuild == 0 ]; then
977     __CommonMSBuildArgs="$__CommonMSBuildArgs /p:PortableBuild=false"
978 fi
979
980 # Set dependent variables
981 __LogsDir="$__RootBinDir/Logs"
982 __MsbuildDebugLogsDir="$__LogsDir/MsbuildDebugLogs"
983
984 # Set the remaining variables based upon the determined build configuration
985 __BinDir="$__RootBinDir/Product/$__BuildOS.$__BuildArch.$__BuildType"
986 __PackagesBinDir="$__BinDir/.nuget"
987 __ToolsDir="$__RootBinDir/tools"
988 __TestWorkingDir="$__RootBinDir/tests/$__BuildOS.$__BuildArch.$__BuildType"
989 export __IntermediatesDir="$__RootBinDir/obj/$__BuildOS.$__BuildArch.$__BuildType"
990 __TestIntermediatesDir="$__RootBinDir/tests/obj/$__BuildOS.$__BuildArch.$__BuildType"
991 __isMSBuildOnNETCoreSupported=0
992 __CrossComponentBinDir="$__BinDir"
993
994 __CrossArch="$__HostArch"
995 if [ $__CrossBuild == 1 ]; then
996     __CrossComponentBinDir="$__CrossComponentBinDir/$__CrossArch"
997 fi
998 __CrossGenCoreLibLog="$__LogsDir/CrossgenCoreLib_$__BuildOS.$__BuildArch.$__BuildType.log"
999
1000 # init the target distro name
1001 initTargetDistroRid
1002
1003 # Init if MSBuild for .NET Core is supported for this platform
1004 isMSBuildOnNETCoreSupported
1005
1006 # CI_SPECIFIC - On CI machines, $HOME may not be set. In such a case, create a subfolder and set the variable to set.
1007 # This is needed by CLI to function.
1008 if [ -z "$HOME" ]; then
1009     if [ ! -d "$__ProjectDir/temp_home" ]; then
1010         mkdir temp_home
1011     fi
1012     export HOME=$__ProjectDir/temp_home
1013     echo "HOME not defined; setting it to $HOME"
1014 fi
1015
1016 # Specify path to be set for CMAKE_INSTALL_PREFIX.
1017 # This is where all built CoreClr libraries will copied to.
1018 export __CMakeBinDir="$__BinDir"
1019
1020 # Configure environment if we are doing a cross compile.
1021 if [ $__CrossBuild == 1 ]; then
1022     export CROSSCOMPILE=1
1023     if ! [[ -n "$ROOTFS_DIR" ]]; then
1024         export ROOTFS_DIR="$__ProjectRoot/cross/rootfs/$__BuildArch"
1025     fi
1026 fi
1027
1028 # Make the directories necessary for build if they don't exist
1029 setup_dirs
1030
1031 # Set up the directory for MSBuild debug logs.
1032 export MSBUILDDEBUGPATH="${__MsbuildDebugLogsDir}"
1033
1034 # Check prereqs.
1035 check_prereqs
1036
1037 # Restore the package containing profile counts for profile-guided optimizations
1038 restore_optdata
1039
1040 # Generate event logging infrastructure sources
1041 generate_event_logging
1042
1043 # Build the coreclr (native) components.
1044 __ExtraCmakeArgs="-DCLR_CMAKE_TARGET_OS=$__BuildOS -DCLR_CMAKE_PACKAGES_DIR=$__PackagesDir -DCLR_CMAKE_PGO_INSTRUMENT=$__PgoInstrument -DCLR_CMAKE_OPTDATA_VERSION=$__PgoOptDataVersion -DCLR_CMAKE_PGO_OPTIMIZE=$__PgoOptimize"
1045
1046 # [TODO] Remove this when the `build-test.sh` script properly builds and deploys test assets.
1047 if [ $__SkipTests != 1 ]; then
1048     echo "Adding CMake flags to build native tests for $__BuildOS.$__BuildArch.$__BuildType"
1049     __ExtraCmakeArgs="$__ExtraCmakeArgs -DCLR_CMAKE_BUILD_TESTS=ON"
1050 fi
1051
1052 build_native $__SkipCoreCLR "$__BuildArch" "$__IntermediatesDir" "$__ExtraCmakeArgs" "CoreCLR component"
1053
1054 # Build cross-architecture components
1055 if [ $__SkipCrossArchNative != 1 ]; then
1056     if [[ $__CrossBuild == 1 ]]; then
1057         build_cross_architecture_components
1058     fi
1059 fi
1060
1061 # Build System.Private.CoreLib.
1062
1063 build_CoreLib
1064
1065 if [ $__CrossgenOnly == 1 ]; then
1066     build_CoreLib_ni "$__BinDir/crossgen"
1067 fi
1068
1069 # Generate nuget packages
1070 if [ $__SkipNuget != 1 ]; then
1071     generate_NugetPackages
1072 fi
1073
1074
1075 # Build complete
1076
1077 echo "Repo successfully built."
1078 echo "Product binaries are available at $__BinDir"
1079 exit 0