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