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