tools.ps1 30.8 KB
Newer Older
1 2 3 4 5 6 7
# Initialize variables if they aren't already defined.
# These may be defined as parameters of the importing script, or set after importing this script.

# CI mode - set to true on CI server for PR validation build or official build.
[bool]$ci = if (Test-Path variable:ci) { $ci } else { $false }

# Build configuration. Common values include 'Debug' and 'Release', but the repository may use other names.
8
[string]$configuration = if (Test-Path variable:configuration) { $configuration } else { 'Debug' }
9

10 11 12
# Set to true to opt out of outputting binary log while running in CI
[bool]$excludeCIBinarylog = if (Test-Path variable:excludeCIBinarylog) { $excludeCIBinarylog } else { $false }

13
# Set to true to output binary log from msbuild. Note that emitting binary log slows down the build.
14
[bool]$binaryLog = if (Test-Path variable:binaryLog) { $binaryLog } else { $ci -and !$excludeCIBinarylog }
15 16 17 18 19 20 21 22 23 24 25 26 27 28

# Set to true to use the pipelines logger which will enable Azure logging output.
# https://github.com/Microsoft/azure-pipelines-tasks/blob/master/docs/authoring/commands.md
# This flag is meant as a temporary opt-opt for the feature while validate it across
# our consumers. It will be deleted in the future.
[bool]$pipelinesLog = if (Test-Path variable:pipelinesLog) { $pipelinesLog } else { $ci }

# Turns on machine preparation/clean up code that changes the machine state (e.g. kills build processes).
[bool]$prepareMachine = if (Test-Path variable:prepareMachine) { $prepareMachine } else { $false }

# True to restore toolsets and dependencies.
[bool]$restore = if (Test-Path variable:restore) { $restore } else { $true }

# Adjusts msbuild verbosity level.
29
[string]$verbosity = if (Test-Path variable:verbosity) { $verbosity } else { 'minimal' }
30 31 32 33 34 35 36 37 38 39 40 41 42 43

# Set to true to reuse msbuild nodes. Recommended to not reuse on CI.
[bool]$nodeReuse = if (Test-Path variable:nodeReuse) { $nodeReuse } else { !$ci }

# Configures warning treatment in msbuild.
[bool]$warnAsError = if (Test-Path variable:warnAsError) { $warnAsError } else { $true }

# Specifies which msbuild engine to use for build: 'vs', 'dotnet' or unspecified (determined based on presence of tools.vs in global.json).
[string]$msbuildEngine = if (Test-Path variable:msbuildEngine) { $msbuildEngine } else { $null }

# True to attempt using .NET Core already that meets requirements specified in global.json
# installed on the machine instead of downloading one.
[bool]$useInstalledDotNetCli = if (Test-Path variable:useInstalledDotNetCli) { $useInstalledDotNetCli } else { $true }

44 45
# Enable repos to use a particular version of the on-line dotnet-install scripts.
#    default URL: https://dot.net/v1/dotnet-install.ps1
46
[string]$dotnetInstallScriptVersion = if (Test-Path variable:dotnetInstallScriptVersion) { $dotnetInstallScriptVersion } else { 'v1' }
47

48 49 50
# True to use global NuGet cache instead of restoring packages to repository-local directory.
[bool]$useGlobalNuGetCache = if (Test-Path variable:useGlobalNuGetCache) { $useGlobalNuGetCache } else { !$ci }

51 52 53
# True to exclude prerelease versions Visual Studio during build
[bool]$excludePrereleaseVS = if (Test-Path variable:excludePrereleaseVS) { $excludePrereleaseVS } else { $false }

54
# An array of names of processes to stop on script exit if prepareMachine is true.
55
$processesToStopOnExit = if (Test-Path variable:processesToStopOnExit) { $processesToStopOnExit } else { @('msbuild', 'dotnet', 'vbcscompiler') }
56

57 58
$disableConfigureToolsetImport = if (Test-Path variable:disableConfigureToolsetImport) { $disableConfigureToolsetImport } else { $null }

59
set-strictmode -version 2.0
60
$ErrorActionPreference = 'Stop'
61 62
[Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12

63
# If specifies, provides an alternate path for getting .NET Core SDKs and Runtimes. This script will still try public sources first.
64 65 66 67
[string]$runtimeSourceFeed = if (Test-Path variable:runtimeSourceFeed) { $runtimeSourceFeed } else { $null }
# Base-64 encoded SAS token that has permission to storage container described by $runtimeSourceFeed
[string]$runtimeSourceFeedKey = if (Test-Path variable:runtimeSourceFeedKey) { $runtimeSourceFeedKey } else { $null }

68 69
function Create-Directory ([string[]] $path) {
    New-Item -Path $path -Force -ItemType 'Directory' | Out-Null
70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100
}

function Unzip([string]$zipfile, [string]$outpath) {
  Add-Type -AssemblyName System.IO.Compression.FileSystem
  [System.IO.Compression.ZipFile]::ExtractToDirectory($zipfile, $outpath)
}

# This will exec a process using the console and return it's exit code.
# This will not throw when the process fails.
# Returns process exit code.
function Exec-Process([string]$command, [string]$commandArgs) {
  $startInfo = New-Object System.Diagnostics.ProcessStartInfo
  $startInfo.FileName = $command
  $startInfo.Arguments = $commandArgs
  $startInfo.UseShellExecute = $false
  $startInfo.WorkingDirectory = Get-Location

  $process = New-Object System.Diagnostics.Process
  $process.StartInfo = $startInfo
  $process.Start() | Out-Null

  $finished = $false
  try {
    while (-not $process.WaitForExit(100)) {
      # Non-blocking loop done to allow ctr-c interrupts
    }

    $finished = $true
    return $global:LASTEXITCODE = $process.ExitCode
  }
  finally {
101
    # If we didn't finish then an error occurred or the user hit ctrl-c.  Either
102 103 104 105 106 107 108
    # way kill the process
    if (-not $finished) {
      $process.Kill()
    }
  }
}

109 110 111 112
# createSdkLocationFile parameter enables a file being generated under the toolset directory
# which writes the sdk's location into. This is only necessary for cmd --> powershell invocations
# as dot sourcing isn't possible.
function InitializeDotNetCli([bool]$install, [bool]$createSdkLocationFile) {
113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134
  if (Test-Path variable:global:_DotNetInstallDir) {
    return $global:_DotNetInstallDir
  }

  # Don't resolve runtime, shared framework, or SDK from other locations to ensure build determinism
  $env:DOTNET_MULTILEVEL_LOOKUP=0

  # Disable first run since we do not need all ASP.NET packages restored.
  $env:DOTNET_SKIP_FIRST_TIME_EXPERIENCE=1

  # Disable telemetry on CI.
  if ($ci) {
    $env:DOTNET_CLI_TELEMETRY_OPTOUT=1
  }

  # Source Build uses DotNetCoreSdkDir variable
  if ($env:DotNetCoreSdkDir -ne $null) {
    $env:DOTNET_INSTALL_DIR = $env:DotNetCoreSdkDir
  }

  # Find the first path on %PATH% that contains the dotnet.exe
  if ($useInstalledDotNetCli -and (-not $globalJsonHasRuntimes) -and ($env:DOTNET_INSTALL_DIR -eq $null)) {
135 136 137
    $dotnetExecutable = GetExecutableFileName 'dotnet'
    $dotnetCmd = Get-Command $dotnetExecutable -ErrorAction SilentlyContinue

138 139 140 141 142 143 144 145 146
    if ($dotnetCmd -ne $null) {
      $env:DOTNET_INSTALL_DIR = Split-Path $dotnetCmd.Path -Parent
    }
  }

  $dotnetSdkVersion = $GlobalJson.tools.dotnet

  # Use dotnet installation specified in DOTNET_INSTALL_DIR if it contains the required SDK version,
  # otherwise install the dotnet CLI and SDK to repo local .dotnet directory to avoid potential permission issues.
147
  if ((-not $globalJsonHasRuntimes) -and (-not [string]::IsNullOrEmpty($env:DOTNET_INSTALL_DIR)) -and (Test-Path(Join-Path $env:DOTNET_INSTALL_DIR "sdk\$dotnetSdkVersion"))) {
148 149
    $dotnetRoot = $env:DOTNET_INSTALL_DIR
  } else {
150
    $dotnetRoot = Join-Path $RepoRoot '.dotnet'
151 152 153 154 155

    if (-not (Test-Path(Join-Path $dotnetRoot "sdk\$dotnetSdkVersion"))) {
      if ($install) {
        InstallDotNetSdk $dotnetRoot $dotnetSdkVersion
      } else {
156
        Write-PipelineTelemetryError -Category 'InitializeToolset' -Message "Unable to find dotnet with SDK version '$dotnetSdkVersion'"
157 158 159 160 161 162 163
        ExitWithExitCode 1
      }
    }

    $env:DOTNET_INSTALL_DIR = $dotnetRoot
  }

164 165 166 167
  # Creates a temporary file under the toolset dir.
  # The following code block is protecting against concurrent access so that this function can
  # be called in parallel.
  if ($createSdkLocationFile) {
168
    do {
169
      $sdkCacheFileTemp = Join-Path $ToolsetDir $([System.IO.Path]::GetRandomFileName())
170
    }
171 172
    until (!(Test-Path $sdkCacheFileTemp))
    Set-Content -Path $sdkCacheFileTemp -Value $dotnetRoot
173

174
    try {
175
      Move-Item -Force $sdkCacheFileTemp (Join-Path $ToolsetDir 'sdk.txt')
176 177 178 179 180 181
    } catch {
      # Somebody beat us
      Remove-Item -Path $sdkCacheFileTemp
    }
  }

182 183 184 185 186
  # Add dotnet to PATH. This prevents any bare invocation of dotnet in custom
  # build steps from using anything other than what we've downloaded.
  # It also ensures that VS msbuild will use the downloaded sdk targets.
  $env:PATH = "$dotnetRoot;$env:PATH"

187
  # Make Sure that our bootstrapped dotnet cli is available in future steps of the Azure Pipelines build
188
  Write-PipelinePrependPath -Path $dotnetRoot
189

190 191 192 193 194 195
  Write-PipelineSetVariable -Name 'DOTNET_MULTILEVEL_LOOKUP' -Value '0'
  Write-PipelineSetVariable -Name 'DOTNET_SKIP_FIRST_TIME_EXPERIENCE' -Value '1'

  return $global:_DotNetInstallDir = $dotnetRoot
}

196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220
function Retry($downloadBlock, $maxRetries = 5) {
  $retries = 1

  while($true) {
    try {
      & $downloadBlock
      break
    }
    catch {
      Write-PipelineTelemetryError -Category 'InitializeToolset' -Message $_
    }

    if (++$retries -le $maxRetries) {
      $delayInSeconds = [math]::Pow(2, $retries) - 1 # Exponential backoff
      Write-Host "Retrying. Waiting for $delayInSeconds seconds before next attempt ($retries of $maxRetries)."
      Start-Sleep -Seconds $delayInSeconds
    }
    else {
      Write-PipelineTelemetryError -Category 'InitializeToolset' -Message "Unable to download file in $maxRetries attempts."
      break
    }

  }
}

221
function GetDotNetInstallScript([string] $dotnetRoot) {
222
  $installScript = Join-Path $dotnetRoot 'dotnet-install.ps1'
223
  if (!(Test-Path $installScript)) {
224 225 226 227
    Create-Directory $dotnetRoot
    $ProgressPreference = 'SilentlyContinue' # Don't display the console progress UI - it's a huge perf hit
    $uri = "https://dot.net/$dotnetInstallScriptVersion/dotnet-install.ps1"

228 229 230 231
    Retry({
      Write-Host "GET $uri"
      Invoke-WebRequest $uri -OutFile $installScript
    })
232
  }
233

234 235 236
  return $installScript
}

237 238
function InstallDotNetSdk([string] $dotnetRoot, [string] $version, [string] $architecture = '', [switch] $noPath) {
  InstallDotNet $dotnetRoot $version $architecture '' $false $runtimeSourceFeed $runtimeSourceFeedKey -noPath:$noPath
239 240
}

241 242 243 244 245 246
function InstallDotNet([string] $dotnetRoot,
  [string] $version,
  [string] $architecture = '',
  [string] $runtime = '',
  [bool] $skipNonVersionedFiles = $false,
  [string] $runtimeSourceFeed = '',
247 248
  [string] $runtimeSourceFeedKey = '',
  [switch] $noPath) {
249

250 251 252 253 254 255 256 257 258
  $installScript = GetDotNetInstallScript $dotnetRoot
  $installParameters = @{
    Version = $version
    InstallDir = $dotnetRoot
  }

  if ($architecture) { $installParameters.Architecture = $architecture }
  if ($runtime) { $installParameters.Runtime = $runtime }
  if ($skipNonVersionedFiles) { $installParameters.SkipNonVersionedFiles = $skipNonVersionedFiles }
259
  if ($noPath) { $installParameters.NoPath = $True }
260

261 262 263 264
  try {
    & $installScript @installParameters
  }
  catch {
265 266
    if ($runtimeSourceFeed -or $runtimeSourceFeedKey) {
      Write-Host "Failed to install dotnet from public location. Trying from '$runtimeSourceFeed'"
267 268 269 270 271 272 273 274 275 276 277 278
      if ($runtimeSourceFeed) { $installParameters.AzureFeed = $runtimeSourceFeed }

      if ($runtimeSourceFeedKey) {
        $decodedBytes = [System.Convert]::FromBase64String($runtimeSourceFeedKey)
        $decodedString = [System.Text.Encoding]::UTF8.GetString($decodedBytes)
        $installParameters.FeedCredential = $decodedString
      }

      try {
        & $installScript @installParameters
      }
      catch {
279
        Write-PipelineTelemetryError -Category 'InitializeToolset' -Message "Failed to install dotnet from custom location '$runtimeSourceFeed'."
280
        ExitWithExitCode 1
281
      }
282
    } else {
283
      Write-PipelineTelemetryError -Category 'InitializeToolset' -Message "Failed to install dotnet from public location."
284
      ExitWithExitCode 1
285
    }
286 287 288 289 290 291 292 293 294 295 296 297 298 299 300
  }
}

#
# Locates Visual Studio MSBuild installation.
# The preference order for MSBuild to use is as follows:
#
#   1. MSBuild from an active VS command prompt
#   2. MSBuild from a compatible VS installation
#   3. MSBuild from the xcopy tool package
#
# Returns full path to msbuild.exe.
# Throws on failure.
#
function InitializeVisualStudioMSBuild([bool]$install, [object]$vsRequirements = $null) {
301 302 303 304
  if (-not (IsWindowsPlatform)) {
    throw "Cannot initialize Visual Studio on non-Windows"
  }

305 306 307 308
  if (Test-Path variable:global:_MSBuildExe) {
    return $global:_MSBuildExe
  }

309 310
  # Minimum VS version to require.
  $vsMinVersionReqdStr = '16.8'
311 312
  $vsMinVersionReqd = [Version]::new($vsMinVersionReqdStr)

313 314
  # If the version of msbuild is going to be xcopied,
  # use this version. Version matches a package here:
315 316
  # https://dev.azure.com/dnceng/public/_packaging?_a=package&feed=dotnet-eng&package=RoslynTools.MSBuild&protocolType=NuGet&version=16.10.0-preview2&view=overview
  $defaultXCopyMSBuildVersion = '16.10.0-preview2'
317

318
  if (!$vsRequirements) { $vsRequirements = $GlobalJson.tools.vs }
319
  $vsMinVersionStr = if ($vsRequirements.version) { $vsRequirements.version } else { $vsMinVersionReqdStr }
320 321 322 323
  $vsMinVersion = [Version]::new($vsMinVersionStr)

  # Try msbuild command available in the environment.
  if ($env:VSINSTALLDIR -ne $null) {
324
    $msbuildCmd = Get-Command 'msbuild.exe' -ErrorAction SilentlyContinue
325 326 327
    if ($msbuildCmd -ne $null) {
      # Workaround for https://github.com/dotnet/roslyn/issues/35793
      # Due to this issue $msbuildCmd.Version returns 0.0.0.0 for msbuild.exe 16.2+
328
      $msbuildVersion = [Version]::new((Get-Item $msbuildCmd.Path).VersionInfo.ProductVersion.Split([char[]]@('-', '+'))[0])
329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347

      if ($msbuildVersion -ge $vsMinVersion) {
        return $global:_MSBuildExe = $msbuildCmd.Path
      }

      # Report error - the developer environment is initialized with incompatible VS version.
      throw "Developer Command Prompt for VS $($env:VisualStudioVersion) is not recent enough. Please upgrade to $vsMinVersionStr or build from a plain CMD window"
    }
  }

  # Locate Visual Studio installation or download x-copy msbuild.
  $vsInfo = LocateVisualStudio $vsRequirements
  if ($vsInfo -ne $null) {
    $vsInstallDir = $vsInfo.installationPath
    $vsMajorVersion = $vsInfo.installationVersion.Split('.')[0]

    InitializeVisualStudioEnvironmentVariables $vsInstallDir $vsMajorVersion
  } else {

348
    if (Get-Member -InputObject $GlobalJson.tools -Name 'xcopy-msbuild') {
349 350 351
      $xcopyMSBuildVersion = $GlobalJson.tools.'xcopy-msbuild'
      $vsMajorVersion = $xcopyMSBuildVersion.Split('.')[0]
    } else {
352
      #if vs version provided in global.json is incompatible (too low) then use the default version for xcopy msbuild download
353
      if($vsMinVersion -lt $vsMinVersionReqd){
354 355
        Write-Host "Using xcopy-msbuild version of $defaultXCopyMSBuildVersion since VS version $vsMinVersionStr provided in global.json is not compatible"
        $xcopyMSBuildVersion = $defaultXCopyMSBuildVersion
356 357
      }
      else{
358 359 360 361
        # If the VS version IS compatible, look for an xcopy msbuild package
        # with a version matching VS.
        # Note: If this version does not exist, then an explicit version of xcopy msbuild
        # can be specified in global.json. This will be required for pre-release versions of msbuild.
362 363
        $vsMajorVersion = $vsMinVersion.Major
        $vsMinorVersion = $vsMinVersion.Minor
364
        $xcopyMSBuildVersion = "$vsMajorVersion.$vsMinorVersion.0"
365
      }
366
    }
367

368 369 370
    $vsInstallDir = $null
    if ($xcopyMSBuildVersion.Trim() -ine "none") {
        $vsInstallDir = InitializeXCopyMSBuild $xcopyMSBuildVersion $install
371 372 373
        if ($vsInstallDir -eq $null) {
            throw "Could not xcopy msbuild. Please check that package 'RoslynTools.MSBuild @ $xcopyMSBuildVersion' exists on feed 'dotnet-eng'."
        }
374
    }
375
    if ($vsInstallDir -eq $null) {
376
      throw 'Unable to find Visual Studio that has required version and components installed'
377 378 379 380
    }
  }

  $msbuildVersionDir = if ([int]$vsMajorVersion -lt 16) { "$vsMajorVersion.0" } else { "Current" }
381 382 383 384 385 386 387 388 389 390

  $local:BinFolder = Join-Path $vsInstallDir "MSBuild\$msbuildVersionDir\Bin"
  $local:Prefer64bit = if (Get-Member -InputObject $vsRequirements -Name 'Prefer64bit') { $vsRequirements.Prefer64bit } else { $false }
  if ($local:Prefer64bit -and (Test-Path(Join-Path $local:BinFolder "amd64"))) {
    $global:_MSBuildExe = Join-Path $local:BinFolder "amd64\msbuild.exe"
  } else {
    $global:_MSBuildExe = Join-Path $local:BinFolder "msbuild.exe"
  }

  return $global:_MSBuildExe
391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408
}

function InitializeVisualStudioEnvironmentVariables([string] $vsInstallDir, [string] $vsMajorVersion) {
  $env:VSINSTALLDIR = $vsInstallDir
  Set-Item "env:VS$($vsMajorVersion)0COMNTOOLS" (Join-Path $vsInstallDir "Common7\Tools\")

  $vsSdkInstallDir = Join-Path $vsInstallDir "VSSDK\"
  if (Test-Path $vsSdkInstallDir) {
    Set-Item "env:VSSDK$($vsMajorVersion)0Install" $vsSdkInstallDir
    $env:VSSDKInstall = $vsSdkInstallDir
  }
}

function InstallXCopyMSBuild([string]$packageVersion) {
  return InitializeXCopyMSBuild $packageVersion -install $true
}

function InitializeXCopyMSBuild([string]$packageVersion, [bool]$install) {
409
  $packageName = 'RoslynTools.MSBuild'
410 411 412 413 414 415 416 417 418
  $packageDir = Join-Path $ToolsDir "msbuild\$packageVersion"
  $packagePath = Join-Path $packageDir "$packageName.$packageVersion.nupkg"

  if (!(Test-Path $packageDir)) {
    if (!$install) {
      return $null
    }

    Create-Directory $packageDir
419

420
    Write-Host "Downloading $packageName $packageVersion"
421
    $ProgressPreference = 'SilentlyContinue' # Don't display the console progress UI - it's a huge perf hit
422 423 424 425
    Retry({
      Invoke-WebRequest "https://pkgs.dev.azure.com/dnceng/public/_packaging/dotnet-eng/nuget/v3/flat2/$packageName/$packageVersion/$packageName.$packageVersion.nupkg" -OutFile $packagePath
    })

426 427 428
    Unzip $packagePath $packageDir
  }

429
  return Join-Path $packageDir 'tools'
430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445
}

#
# Locates Visual Studio instance that meets the minimal requirements specified by tools.vs object in global.json.
#
# The following properties of tools.vs are recognized:
#   "version": "{major}.{minor}"
#       Two part minimal VS version, e.g. "15.9", "16.0", etc.
#   "components": ["componentId1", "componentId2", ...]
#       Array of ids of workload components that must be available in the VS instance.
#       See e.g. https://docs.microsoft.com/en-us/visualstudio/install/workload-component-id-vs-enterprise?view=vs-2017
#
# Returns JSON describing the located VS instance (same format as returned by vswhere),
# or $null if no instance meeting the requirements is found on the machine.
#
function LocateVisualStudio([object]$vsRequirements = $null){
446 447 448 449
  if (-not (IsWindowsPlatform)) {
    throw "Cannot run vswhere on non-Windows platforms."
  }

450
  if (Get-Member -InputObject $GlobalJson.tools -Name 'vswhere') {
451 452
    $vswhereVersion = $GlobalJson.tools.vswhere
  } else {
453
    $vswhereVersion = '2.5.2'
454 455 456
  }

  $vsWhereDir = Join-Path $ToolsDir "vswhere\$vswhereVersion"
457
  $vsWhereExe = Join-Path $vsWhereDir 'vswhere.exe'
458 459 460

  if (!(Test-Path $vsWhereExe)) {
    Create-Directory $vsWhereDir
461
    Write-Host 'Downloading vswhere'
462 463 464
    Retry({
      Invoke-WebRequest "https://netcorenativeassets.blob.core.windows.net/resource-packages/external/windows/vswhere/$vswhereVersion/vswhere.exe" -OutFile $vswhereExe
    })
465 466 467
  }

  if (!$vsRequirements) { $vsRequirements = $GlobalJson.tools.vs }
468 469 470 471 472
  $args = @('-latest', '-format', 'json', '-requires', 'Microsoft.Component.MSBuild', '-products', '*')

  if (!$excludePrereleaseVS) {
    $args += '-prerelease'
  }
473

474 475
  if (Get-Member -InputObject $vsRequirements -Name 'version') {
    $args += '-version'
476 477 478
    $args += $vsRequirements.version
  }

479
  if (Get-Member -InputObject $vsRequirements -Name 'components') {
480
    foreach ($component in $vsRequirements.components) {
481
      $args += '-requires'
482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497
      $args += $component
    }
  }

  $vsInfo =& $vsWhereExe $args | ConvertFrom-Json

  if ($lastExitCode -ne 0) {
    return $null
  }

  # use first matching instance
  return $vsInfo[0]
}

function InitializeBuildTool() {
  if (Test-Path variable:global:_BuildTool) {
498 499
    # If the requested msbuild parameters do not match, clear the cached variables.
    if($global:_BuildTool.Contains('ExcludePrereleaseVS') -and $global:_BuildTool.ExcludePrereleaseVS -ne $excludePrereleaseVS) {
500
      Remove-Item variable:global:_BuildTool
501 502 503 504
      Remove-Item variable:global:_MSBuildExe
    } else {
      return $global:_BuildTool
    }
505 506 507 508 509 510 511 512
  }

  if (-not $msbuildEngine) {
    $msbuildEngine = GetDefaultMSBuildEngine
  }

  # Initialize dotnet cli if listed in 'tools'
  $dotnetRoot = $null
513
  if (Get-Member -InputObject $GlobalJson.tools -Name 'dotnet') {
514 515 516
    $dotnetRoot = InitializeDotNetCli -install:$restore
  }

517
  if ($msbuildEngine -eq 'dotnet') {
518
    if (!$dotnetRoot) {
519
      Write-PipelineTelemetryError -Category 'InitializeToolset' -Message "/global.json must specify 'tools.dotnet'."
520 521
      ExitWithExitCode 1
    }
522
    $dotnetPath = Join-Path $dotnetRoot (GetExecutableFileName 'dotnet')
523
    $buildTool = @{ Path = $dotnetPath; Command = 'msbuild'; Tool = 'dotnet'; Framework = 'netcoreapp3.1' }
524 525 526 527
  } elseif ($msbuildEngine -eq "vs") {
    try {
      $msbuildPath = InitializeVisualStudioMSBuild -install:$restore
    } catch {
528
      Write-PipelineTelemetryError -Category 'InitializeToolset' -Message $_
529 530 531
      ExitWithExitCode 1
    }

532
    $buildTool = @{ Path = $msbuildPath; Command = ""; Tool = "vs"; Framework = "net472"; ExcludePrereleaseVS = $excludePrereleaseVS }
533
  } else {
534
    Write-PipelineTelemetryError -Category 'InitializeToolset' -Message "Unexpected value of -msbuildEngine: '$msbuildEngine'."
535 536 537 538 539 540 541 542
    ExitWithExitCode 1
  }

  return $global:_BuildTool = $buildTool
}

function GetDefaultMSBuildEngine() {
  # Presence of tools.vs indicates the repo needs to build using VS msbuild on Windows.
543 544
  if (Get-Member -InputObject $GlobalJson.tools -Name 'vs') {
    return 'vs'
545 546
  }

547 548
  if (Get-Member -InputObject $GlobalJson.tools -Name 'dotnet') {
    return 'dotnet'
549 550
  }

551
  Write-PipelineTelemetryError -Category 'InitializeToolset' -Message "-msbuildEngine must be specified, or /global.json must specify 'tools.dotnet' or 'tools.vs'."
552 553 554 555 556
  ExitWithExitCode 1
}

function GetNuGetPackageCachePath() {
  if ($env:NUGET_PACKAGES -eq $null) {
557
    # Use local cache on CI to ensure deterministic build.
558
    # Avoid using the http cache as workaround for https://github.com/NuGet/Home/issues/3116
559
    # use global cache in dev builds to avoid cost of downloading packages.
560
    # For directory normalization, see also: https://github.com/NuGet/Home/issues/7968
561
    if ($useGlobalNuGetCache) {
562
      $env:NUGET_PACKAGES = Join-Path $env:UserProfile '.nuget\packages\'
563
    } else {
564
      $env:NUGET_PACKAGES = Join-Path $RepoRoot '.packages\'
565
      $env:RESTORENOCACHE = $true
566 567 568 569 570 571 572 573 574 575 576 577
    }
  }

  return $env:NUGET_PACKAGES
}

# Returns a full path to an Arcade SDK task project file.
function GetSdkTaskProject([string]$taskName) {
  return Join-Path (Split-Path (InitializeToolset) -Parent) "SdkTasks\$taskName.proj"
}

function InitializeNativeTools() {
578
  if (-Not (Test-Path variable:DisableNativeToolsetInstalls) -And (Get-Member -InputObject $GlobalJson -Name "native-tools")) {
579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606
    $nativeArgs= @{}
    if ($ci) {
      $nativeArgs = @{
        InstallDirectory = "$ToolsDir"
      }
    }
    & "$PSScriptRoot/init-tools-native.ps1" @nativeArgs
  }
}

function InitializeToolset() {
  if (Test-Path variable:global:_ToolsetBuildProj) {
    return $global:_ToolsetBuildProj
  }

  $nugetCache = GetNuGetPackageCachePath

  $toolsetVersion = $GlobalJson.'msbuild-sdks'.'Microsoft.DotNet.Arcade.Sdk'
  $toolsetLocationFile = Join-Path $ToolsetDir "$toolsetVersion.txt"

  if (Test-Path $toolsetLocationFile) {
    $path = Get-Content $toolsetLocationFile -TotalCount 1
    if (Test-Path $path) {
      return $global:_ToolsetBuildProj = $path
    }
  }

  if (-not $restore) {
607
    Write-PipelineTelemetryError -Category 'InitializeToolset' -Message "Toolset version $toolsetVersion has not been restored."
608 609 610 611 612
    ExitWithExitCode 1
  }

  $buildTool = InitializeBuildTool

613 614
  $proj = Join-Path $ToolsetDir 'restore.proj'
  $bl = if ($binaryLog) { '/bl:' + (Join-Path $LogDir 'ToolsetRestore.binlog') } else { '' }
615 616 617 618 619

  '<Project Sdk="Microsoft.DotNet.Arcade.Sdk"/>' | Set-Content $proj

  MSBuild-Core $proj $bl /t:__WriteToolsetLocation /clp:ErrorsOnly`;NoSummary /p:__ToolsetLocationOutputFile=$toolsetLocationFile

620
  $path = Get-Content $toolsetLocationFile -Encoding UTF8 -TotalCount 1
621 622 623 624 625 626 627 628 629 630 631 632 633 634 635
  if (!(Test-Path $path)) {
    throw "Invalid toolset path: $path"
  }

  return $global:_ToolsetBuildProj = $path
}

function ExitWithExitCode([int] $exitCode) {
  if ($ci -and $prepareMachine) {
    Stop-Processes
  }
  exit $exitCode
}

function Stop-Processes() {
636
  Write-Host 'Killing running build processes...'
637 638 639 640 641 642 643 644 645 646 647 648 649
  foreach ($processName in $processesToStopOnExit) {
    Get-Process -Name $processName -ErrorAction SilentlyContinue | Stop-Process
  }
}

#
# Executes msbuild (or 'dotnet msbuild') with arguments passed to the function.
# The arguments are automatically quoted.
# Terminates the script if the build fails.
#
function MSBuild() {
  if ($pipelinesLog) {
    $buildTool = InitializeBuildTool
650

651
    if ($ci -and $buildTool.Tool -eq 'dotnet') {
652 653 654 655 656 657
      $env:NUGET_PLUGIN_HANDSHAKE_TIMEOUT_IN_SECONDS = 20
      $env:NUGET_PLUGIN_REQUEST_TIMEOUT_IN_SECONDS = 20
      Write-PipelineSetVariable -Name 'NUGET_PLUGIN_HANDSHAKE_TIMEOUT_IN_SECONDS' -Value '20'
      Write-PipelineSetVariable -Name 'NUGET_PLUGIN_REQUEST_TIMEOUT_IN_SECONDS' -Value '20'
    }

658
    $toolsetBuildProject = InitializeToolset
659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676
    $basePath = Split-Path -parent $toolsetBuildProject
    $possiblePaths = @(
      # new scripts need to work with old packages, so we need to look for the old names/versions
      (Join-Path $basePath (Join-Path $buildTool.Framework 'Microsoft.DotNet.ArcadeLogging.dll')),
      (Join-Path $basePath (Join-Path $buildTool.Framework 'Microsoft.DotNet.Arcade.Sdk.dll')),
      (Join-Path $basePath (Join-Path netcoreapp2.1 'Microsoft.DotNet.ArcadeLogging.dll')),
      (Join-Path $basePath (Join-Path netcoreapp2.1 'Microsoft.DotNet.Arcade.Sdk.dll'))
    )
    $selectedPath = $null
    foreach ($path in $possiblePaths) {
      if (Test-Path $path -PathType Leaf) {
        $selectedPath = $path
        break
      }
    }
    if (-not $selectedPath) {
      Write-PipelineTelemetryError -Category 'Build' -Message 'Unable to find arcade sdk logger assembly.'
      ExitWithExitCode 1
677
    }
678
    $args += "/logger:$selectedPath"
679 680 681 682 683 684 685 686 687 688 689 690
  }

  MSBuild-Core @args
}

#
# Executes msbuild (or 'dotnet msbuild') with arguments passed to the function.
# The arguments are automatically quoted.
# Terminates the script if the build fails.
#
function MSBuild-Core() {
  if ($ci) {
691 692
    if (!$binaryLog -and !$excludeCIBinarylog) {
      Write-PipelineTelemetryError -Category 'Build' -Message 'Binary log must be enabled in CI build, or explicitly opted-out from with the -excludeCIBinarylog switch.'
693 694 695 696
      ExitWithExitCode 1
    }

    if ($nodeReuse) {
697
      Write-PipelineTelemetryError -Category 'Build' -Message 'Node reuse must be disabled in CI build.'
698 699 700 701 702 703 704 705 706
      ExitWithExitCode 1
    }
  }

  $buildTool = InitializeBuildTool

  $cmdArgs = "$($buildTool.Command) /m /nologo /clp:Summary /v:$verbosity /nr:$nodeReuse /p:ContinuousIntegrationBuild=$ci"

  if ($warnAsError) {
707
    $cmdArgs += ' /warnaserror /p:TreatWarningsAsErrors=true'
708
  }
709
  else {
710
    $cmdArgs += ' /p:TreatWarningsAsErrors=false'
711
  }
712 713

  foreach ($arg in $args) {
714 715 716 717
    if ($null -ne $arg -and $arg.Trim() -ne "") {
      if ($arg.EndsWith('\')) {
        $arg = $arg + "\"
      }
718 719 720 721
      $cmdArgs += " `"$arg`""
    }
  }

722 723
  $env:ARCADE_BUILD_TOOL_COMMAND = "$($buildTool.Path) $cmdArgs"

724 725 726
  $exitCode = Exec-Process $buildTool.Path $cmdArgs

  if ($exitCode -ne 0) {
727 728 729
    # We should not Write-PipelineTaskError here because that message shows up in the build summary
    # The build already logged an error, that's the reason it failed. Producing an error here only adds noise.
    Write-Host "Build failed with exit code $exitCode. Check errors above." -ForegroundColor Red
730 731

    $buildLog = GetMSBuildBinaryLogCommandLineArgument $args
732
    if ($null -ne $buildLog) {
733 734 735
      Write-Host "See log: $buildLog" -ForegroundColor DarkGray
    }

736 737 738 739 740 741 742 743
    if ($ci) {
      Write-PipelineSetResult -Result "Failed" -Message "msbuild execution failed."
      # Exiting with an exit code causes the azure pipelines task to log yet another "noise" error
      # The above Write-PipelineSetResult will cause the task to be marked as failure without adding yet another error
      ExitWithExitCode 0
    } else {
      ExitWithExitCode $exitCode
    }
744 745 746 747 748 749 750
  }
}

function GetMSBuildBinaryLogCommandLineArgument($arguments) {
  foreach ($argument in $arguments) {
    if ($argument -ne $null) {
      $arg = $argument.Trim()
751 752
      if ($arg.StartsWith('/bl:', "OrdinalIgnoreCase")) {
        return $arg.Substring('/bl:'.Length)
753 754
      }

755 756
      if ($arg.StartsWith('/binaryLogger:', 'OrdinalIgnoreCase')) {
        return $arg.Substring('/binaryLogger:'.Length)
757 758 759 760 761 762 763
      }
    }
  }

  return $null
}

764 765 766 767 768 769 770 771 772 773 774 775 776
function GetExecutableFileName($baseName) {
  if (IsWindowsPlatform) {
    return "$baseName.exe"
  }
  else {
    return $baseName
  }
}

function IsWindowsPlatform() {
  return [environment]::OSVersion.Platform -eq [PlatformID]::Win32NT
}

777 778 779 780 781 782 783 784 785 786
function Get-Darc($version) {
  $darcPath  = "$TempDir\darc\$(New-Guid)"
  if ($version -ne $null) {
    & $PSScriptRoot\darc-init.ps1 -toolpath $darcPath -darcVersion $version | Out-Host
  } else {
    & $PSScriptRoot\darc-init.ps1 -toolpath $darcPath | Out-Host
  }
  return "$darcPath\darc.exe"
}

787 788
. $PSScriptRoot\pipeline-logging-functions.ps1

789
$RepoRoot = Resolve-Path (Join-Path $PSScriptRoot '..\..\')
790 791 792 793 794 795 796
$EngRoot = Resolve-Path (Join-Path $PSScriptRoot '..')
$ArtifactsDir = Join-Path $RepoRoot 'artifacts'
$ToolsetDir = Join-Path $ArtifactsDir 'toolset'
$ToolsDir = Join-Path $RepoRoot '.tools'
$LogDir = Join-Path (Join-Path $ArtifactsDir 'log') $configuration
$TempDir = Join-Path (Join-Path $ArtifactsDir 'tmp') $configuration
$GlobalJson = Get-Content -Raw -Path (Join-Path $RepoRoot 'global.json') | ConvertFrom-Json
797 798 799 800 801 802 803 804 805 806 807 808
# true if global.json contains a "runtimes" section
$globalJsonHasRuntimes = if ($GlobalJson.tools.PSObject.Properties.Name -Match 'runtimes') { $true } else { $false }

Create-Directory $ToolsetDir
Create-Directory $TempDir
Create-Directory $LogDir

Write-PipelineSetVariable -Name 'Artifacts' -Value $ArtifactsDir
Write-PipelineSetVariable -Name 'Artifacts.Toolset' -Value $ToolsetDir
Write-PipelineSetVariable -Name 'Artifacts.Log' -Value $LogDir
Write-PipelineSetVariable -Name 'TEMP' -Value $TempDir
Write-PipelineSetVariable -Name 'TMP' -Value $TempDir
809 810 811

# Import custom tools configuration, if present in the repo.
# Note: Import in global scope so that the script set top-level variables without qualification.
812
if (!$disableConfigureToolsetImport) {
813
  $configureToolsetScript = Join-Path $EngRoot 'configure-toolset.ps1'
814
  if (Test-Path $configureToolsetScript) {
815 816 817 818 819 820 821
    . $configureToolsetScript
    if ((Test-Path variable:failOnConfigureToolsetError) -And $failOnConfigureToolsetError) {
      if ((Test-Path variable:LastExitCode) -And ($LastExitCode -ne 0)) {
        Write-PipelineTelemetryError -Category 'Build' -Message 'configure-toolset.ps1 returned a non-zero exit code'
        ExitWithExitCode $LastExitCode
      }
    }
822
  }
823
}