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