diff --git a/.config/dotnet-tools.json b/.config/dotnet-tools.json index e39fc127a1123..ef2073ccd06da 100644 --- a/.config/dotnet-tools.json +++ b/.config/dotnet-tools.json @@ -15,7 +15,7 @@ ] }, "microsoft.dotnet.xharness.cli": { - "version": "1.0.0-prerelease.21404.1", + "version": "6.0.0-prerelease.23253.6", "commands": [ "xharness" ] diff --git a/.github/PULL_REQUEST_TEMPLATE/servicing_pull_request_template.md b/.github/PULL_REQUEST_TEMPLATE/servicing_pull_request_template.md index 6fd461e6fc369..9a748a085a20f 100644 --- a/.github/PULL_REQUEST_TEMPLATE/servicing_pull_request_template.md +++ b/.github/PULL_REQUEST_TEMPLATE/servicing_pull_request_template.md @@ -21,3 +21,7 @@ main PR # Risk + +# Package authoring signed off? + +IMPORTANT: If this change touches code that ships in a NuGet package, please make certain that you have added any necessary [package authoring](../../docs/project/library-servicing.md) and gotten it explicitly reviewed. diff --git a/.github/workflows/check-service-labels.yml b/.github/workflows/check-service-labels.yml index efbbcdf9925fd..5261cc165ee12 100644 --- a/.github/workflows/check-service-labels.yml +++ b/.github/workflows/check-service-labels.yml @@ -13,10 +13,12 @@ jobs: check-labels: runs-on: ubuntu-latest steps: - - name: Check servicing labels + - name: Check 'Servicing-approved' label run: | + echo "Merging permission is enabled for servicing PRs when the `Servicing-approved` label is applied." if [ "${{ contains(github.event.pull_request.labels.*.name, 'Servicing-approved') }}" = "true" ]; then exit 0 else + echo "::error:: 'Servicing-approved' label not applied to the PR yet. More information: https://github.com/dotnet/runtime/blob/main/docs/project/library-servicing.md#approval-process" exit 1 fi diff --git a/docs/project/library-servicing.md b/docs/project/library-servicing.md index b3563190c87da..a9431903fc702 100644 --- a/docs/project/library-servicing.md +++ b/docs/project/library-servicing.md @@ -1,6 +1,6 @@ # How to service a library -This document provides the steps necessary after modifying a library in a servicing branch. +This document provides the steps that need to be followed after modifying a library in a servicing branch. Servicing branches represent shipped versions of .NET, and their name is in the format `release/X.0-staging`. Examples: @@ -41,5 +41,15 @@ All the servicing change must go through an approval process. You have two ways For both cases, you must: - Fill out the template of the PR description. -- Add the `servicing-consider` label. -- Bring it to the attention of the engineering lead responsible for the area, so they consider the fix for servicing. \ No newline at end of file +- Bring it to the attention of the [engineering lead responsible for the area](~/docs/area-owners.md). +- If the fix is a product change, the area owner will: + - Add the `Servicing-consider` label. + - Ask the area owner to champion your PR in the .NET Tactics meeting to request merge approval. + - If the change is approved, they will replace the `Servicing-consider` label by `Servicing-approved` and sign-off the PR. +- If the fix is a test-only or infra-only change, the area owner will: + - Review the PR and sign-off if they approve it. + - Add the `Servicing-approved` label. + +The area owner can then merge the PR once the CI looks good (it's either green or the failures are investigated and determined to be unrelated to the PR). + +**Note**: Applying the `Servicing-approved` label ensures the `check-service-labels` CI job passes, which is a mandatory requirement for merging a PR in a servicing branch. diff --git a/eng/Version.Details.xml b/eng/Version.Details.xml index 46b1f09738d3f..133b9956b09f9 100644 --- a/eng/Version.Details.xml +++ b/eng/Version.Details.xml @@ -1,8 +1,8 @@ - + https://github.com/dotnet/icu - f7c5d687a6c09a038fab7572d4b3dfe4a83b5d49 + cff1c9ff20d271c6698d150e484e8327998595a4 https://github.com/dotnet/msquic @@ -26,125 +26,125 @@ - + https://github.com/dotnet/arcade - 7bca7a24dfc0eded1f3e364b4ff7bf1235b6eb26 + 3d9c9a4d3d893e903bb3295fd5b55b8e40699888 - + https://github.com/dotnet/arcade - 7bca7a24dfc0eded1f3e364b4ff7bf1235b6eb26 + 3d9c9a4d3d893e903bb3295fd5b55b8e40699888 - + https://github.com/dotnet/arcade - 7bca7a24dfc0eded1f3e364b4ff7bf1235b6eb26 + 3d9c9a4d3d893e903bb3295fd5b55b8e40699888 - + https://github.com/dotnet/arcade - 7bca7a24dfc0eded1f3e364b4ff7bf1235b6eb26 + 3d9c9a4d3d893e903bb3295fd5b55b8e40699888 - + https://github.com/dotnet/arcade - 7bca7a24dfc0eded1f3e364b4ff7bf1235b6eb26 + 3d9c9a4d3d893e903bb3295fd5b55b8e40699888 - + https://github.com/dotnet/arcade - 7bca7a24dfc0eded1f3e364b4ff7bf1235b6eb26 + 3d9c9a4d3d893e903bb3295fd5b55b8e40699888 - + https://github.com/dotnet/arcade - 7bca7a24dfc0eded1f3e364b4ff7bf1235b6eb26 + 3d9c9a4d3d893e903bb3295fd5b55b8e40699888 - + https://github.com/dotnet/arcade - 7bca7a24dfc0eded1f3e364b4ff7bf1235b6eb26 + 3d9c9a4d3d893e903bb3295fd5b55b8e40699888 - + https://github.com/dotnet/arcade - 7bca7a24dfc0eded1f3e364b4ff7bf1235b6eb26 + 3d9c9a4d3d893e903bb3295fd5b55b8e40699888 - + https://github.com/dotnet/arcade - 7bca7a24dfc0eded1f3e364b4ff7bf1235b6eb26 + 3d9c9a4d3d893e903bb3295fd5b55b8e40699888 - + https://github.com/dotnet/arcade - 7bca7a24dfc0eded1f3e364b4ff7bf1235b6eb26 + 3d9c9a4d3d893e903bb3295fd5b55b8e40699888 - + https://github.com/dotnet/arcade - 7bca7a24dfc0eded1f3e364b4ff7bf1235b6eb26 + 3d9c9a4d3d893e903bb3295fd5b55b8e40699888 - + https://github.com/dotnet/arcade - 7bca7a24dfc0eded1f3e364b4ff7bf1235b6eb26 + 3d9c9a4d3d893e903bb3295fd5b55b8e40699888 - + https://github.com/dotnet/arcade - 7bca7a24dfc0eded1f3e364b4ff7bf1235b6eb26 + 3d9c9a4d3d893e903bb3295fd5b55b8e40699888 - + https://github.com/dotnet/arcade - 7bca7a24dfc0eded1f3e364b4ff7bf1235b6eb26 + 3d9c9a4d3d893e903bb3295fd5b55b8e40699888 - + https://github.com/dotnet/arcade - 7bca7a24dfc0eded1f3e364b4ff7bf1235b6eb26 + 3d9c9a4d3d893e903bb3295fd5b55b8e40699888 - + https://github.com/dotnet/arcade - 7bca7a24dfc0eded1f3e364b4ff7bf1235b6eb26 + 3d9c9a4d3d893e903bb3295fd5b55b8e40699888 - + https://github.com/dotnet/arcade - 7bca7a24dfc0eded1f3e364b4ff7bf1235b6eb26 + 3d9c9a4d3d893e903bb3295fd5b55b8e40699888 https://github.com/microsoft/vstest 140434f7109d357d0158ade9e5164a4861513965 - + https://github.com/dotnet/runtime-assets - 394c6358ffc15856545904f295d7d2d5ce7d0df4 + 27b0291e9fb85b6664e4fc7c6bc10bcd059d8ab7 - + https://github.com/dotnet/runtime-assets - 394c6358ffc15856545904f295d7d2d5ce7d0df4 + 27b0291e9fb85b6664e4fc7c6bc10bcd059d8ab7 - + https://github.com/dotnet/runtime-assets - 394c6358ffc15856545904f295d7d2d5ce7d0df4 + 27b0291e9fb85b6664e4fc7c6bc10bcd059d8ab7 - + https://github.com/dotnet/runtime-assets - 394c6358ffc15856545904f295d7d2d5ce7d0df4 + 27b0291e9fb85b6664e4fc7c6bc10bcd059d8ab7 - + https://github.com/dotnet/runtime-assets - 394c6358ffc15856545904f295d7d2d5ce7d0df4 + 27b0291e9fb85b6664e4fc7c6bc10bcd059d8ab7 - + https://github.com/dotnet/runtime-assets - 394c6358ffc15856545904f295d7d2d5ce7d0df4 + 27b0291e9fb85b6664e4fc7c6bc10bcd059d8ab7 - + https://github.com/dotnet/runtime-assets - 394c6358ffc15856545904f295d7d2d5ce7d0df4 + 27b0291e9fb85b6664e4fc7c6bc10bcd059d8ab7 - + https://github.com/dotnet/runtime-assets - 394c6358ffc15856545904f295d7d2d5ce7d0df4 + 27b0291e9fb85b6664e4fc7c6bc10bcd059d8ab7 - + https://github.com/dotnet/runtime-assets - 394c6358ffc15856545904f295d7d2d5ce7d0df4 + 27b0291e9fb85b6664e4fc7c6bc10bcd059d8ab7 - + https://github.com/dotnet/runtime-assets - 394c6358ffc15856545904f295d7d2d5ce7d0df4 + 27b0291e9fb85b6664e4fc7c6bc10bcd059d8ab7 - + https://github.com/dotnet/runtime-assets - 394c6358ffc15856545904f295d7d2d5ce7d0df4 + 27b0291e9fb85b6664e4fc7c6bc10bcd059d8ab7 https://github.com/dotnet/llvm-project @@ -214,17 +214,17 @@ https://github.com/mono/linker c8499798a2a09639174e2f5c694d6652794cc73d - + https://github.com/dotnet/xharness - e9669dc84ecd668d3bbb748758103e23b394ffef + bc2e9e39a7b424f6e96af8d677d12ac58606753a - + https://github.com/dotnet/xharness - e9669dc84ecd668d3bbb748758103e23b394ffef + bc2e9e39a7b424f6e96af8d677d12ac58606753a - + https://github.com/dotnet/arcade - 7bca7a24dfc0eded1f3e364b4ff7bf1235b6eb26 + 3d9c9a4d3d893e903bb3295fd5b55b8e40699888 https://dev.azure.com/dnceng/internal/_git/dotnet-optimization @@ -242,13 +242,13 @@ https://dev.azure.com/dnceng/internal/_git/dotnet-optimization d50065944d8b41d804448a7056351481d583ad3d - + https://github.com/dotnet/hotreload-utils - 802e79f0cf423249d54bfaafca2da4a272f4ca07 + 83c5bd71b65d9de362ae0ba2f2cdea94c002c8c7 - + https://github.com/dotnet/runtime-assets - 394c6358ffc15856545904f295d7d2d5ce7d0df4 + 27b0291e9fb85b6664e4fc7c6bc10bcd059d8ab7 https://github.com/dotnet/roslyn-analyzers diff --git a/eng/Versions.props b/eng/Versions.props index 91c258882c146..1549f3aebfaff 100644 --- a/eng/Versions.props +++ b/eng/Versions.props @@ -42,21 +42,21 @@ 1.1.0-preview.22164.17 - 6.0.0-beta.23211.7 - 6.0.0-beta.23211.7 - 6.0.0-beta.23211.7 - 6.0.0-beta.23211.7 - 6.0.0-beta.23211.7 - 6.0.0-beta.23211.7 - 2.5.1-beta.23211.7 - 6.0.0-beta.23211.7 - 6.0.0-beta.23211.7 - 6.0.0-beta.23211.7 - 6.0.0-beta.23211.7 - 6.0.0-beta.23211.7 - 6.0.0-beta.23211.7 - 6.0.0-beta.23211.7 - 6.0.0-beta.23211.7 + 6.0.0-beta.23221.7 + 6.0.0-beta.23221.7 + 6.0.0-beta.23221.7 + 6.0.0-beta.23221.7 + 6.0.0-beta.23221.7 + 6.0.0-beta.23221.7 + 2.5.1-beta.23221.7 + 6.0.0-beta.23221.7 + 6.0.0-beta.23221.7 + 6.0.0-beta.23221.7 + 6.0.0-beta.23221.7 + 6.0.0-beta.23221.7 + 6.0.0-beta.23221.7 + 6.0.0-beta.23221.7 + 6.0.0-beta.23221.7 6.0.0-preview.1.102 @@ -108,18 +108,18 @@ 4.5.0 6.0.0-rc.1.21415.6 - 6.0.0-beta.23179.5 - 6.0.0-beta.23179.5 - 6.0.0-beta.23179.5 - 6.0.0-beta.23179.5 - 6.0.0-beta.23179.5 - 6.0.0-beta.23179.5 - 6.0.0-beta.23179.5 - 6.0.0-beta.23179.5 - 6.0.0-beta.23179.5 - 6.0.0-beta.23179.5 - 6.0.0-beta.23179.5 - 6.0.0-beta.23179.5 + 6.0.0-beta.23212.1 + 6.0.0-beta.23212.1 + 6.0.0-beta.23212.1 + 6.0.0-beta.23212.1 + 6.0.0-beta.23212.1 + 6.0.0-beta.23212.1 + 6.0.0-beta.23212.1 + 6.0.0-beta.23212.1 + 6.0.0-beta.23212.1 + 6.0.0-beta.23212.1 + 6.0.0-beta.23212.1 + 6.0.0-beta.23212.1 1.0.0-prerelease.21416.5 1.0.0-prerelease.21416.5 @@ -143,9 +143,9 @@ 1.0.1-prerelease-00006 17.4.0-preview-20220707-01 - 1.0.0-prerelease.21404.1 - 1.0.0-prerelease.21404.1 - 1.0.2-alpha.0.21413.1 + 6.0.0-prerelease.23253.6 + 6.0.0-prerelease.23253.6 + 6.0.0-alpha.0.23226.4 2.4.2-pre.9 2.4.2 1.3.0 @@ -162,7 +162,7 @@ 6.0.100-1.21459.1 $(MicrosoftNETILLinkTasksVersion) - 6.0.0-rtm.23170.3 + 6.0.0-rtm.23218.5 6.0.0-servicing.22205.1 diff --git a/eng/common/templates/job/job.yml b/eng/common/templates/job/job.yml index 547d878da073a..e5784440d0bb2 100644 --- a/eng/common/templates/job/job.yml +++ b/eng/common/templates/job/job.yml @@ -24,7 +24,7 @@ parameters: enablePublishBuildAssets: false enablePublishTestResults: false enablePublishUsingPipelines: false - disableComponentGovernance: false + disableComponentGovernance: '' mergeTestResults: false testRunTitle: '' testResultsFormat: '' @@ -141,9 +141,13 @@ jobs: richNavLogOutputDirectory: $(Build.SourcesDirectory)/artifacts/bin continueOnError: true - - ${{ if and(eq(parameters.runAsPublic, 'false'), ne(variables['System.TeamProject'], 'public'), notin(variables['Build.Reason'], 'PullRequest'), ne(parameters.disableComponentGovernance, 'true')) }}: - - task: ComponentGovernanceComponentDetection@0 - continueOnError: true + - template: /eng/common/templates/steps/component-governance.yml + parameters: + ${{ if eq(parameters.disableComponentGovernance, '') }}: + ${{ if and(ne(variables['System.TeamProject'], 'public'), notin(variables['Build.Reason'], 'PullRequest'), eq(parameters.runAsPublic, 'false'), or(contains(variables['Build.SourceBranch'], 'internal/release'), eq(variables['Build.SourceBranch'], 'main'))) }}: + disableComponentGovernance: false + ${{ else }}: + disableComponentGovernance: true - ${{ if eq(parameters.enableMicrobuild, 'true') }}: - ${{ if and(eq(parameters.runAsPublic, 'false'), ne(variables['System.TeamProject'], 'public'), notin(variables['Build.Reason'], 'PullRequest')) }}: diff --git a/eng/common/templates/steps/component-governance.yml b/eng/common/templates/steps/component-governance.yml new file mode 100644 index 0000000000000..babc2757d8d12 --- /dev/null +++ b/eng/common/templates/steps/component-governance.yml @@ -0,0 +1,10 @@ +parameters: + disableComponentGovernance: false + +steps: +- ${{ if eq(parameters.disableComponentGovernance, 'true') }}: + - script: "echo ##vso[task.setvariable variable=skipComponentGovernanceDetection]true" + displayName: Set skipComponentGovernanceDetection variable +- ${{ if ne(parameters.disableComponentGovernance, 'true') }}: + - task: ComponentGovernanceComponentDetection@0 + continueOnError: true \ No newline at end of file diff --git a/eng/native/configurecompiler.cmake b/eng/native/configurecompiler.cmake index f3526deb19fa0..1a43b710c618b 100644 --- a/eng/native/configurecompiler.cmake +++ b/eng/native/configurecompiler.cmake @@ -367,6 +367,15 @@ if (CLR_CMAKE_HOST_UNIX) add_compile_options(-Wno-incompatible-ms-struct) add_compile_options(-Wno-reserved-identifier) + + # clang 16.0 introduced buffer hardening https://discourse.llvm.org/t/rfc-c-buffer-hardening/65734 + # which we are not conforming to yet. + add_compile_options(-Wno-unsafe-buffer-usage) + + # other clang 16.0 suppressions + add_compile_options(-Wno-single-bit-bitfield-constant-conversion) + add_compile_options(-Wno-cast-function-type-strict) + add_compile_options(-Wno-incompatible-function-pointer-types-strict) else() add_compile_options(-Wno-unknown-pragmas) add_compile_options(-Wno-uninitialized) diff --git a/eng/native/init-compiler.sh b/eng/native/init-compiler.sh index 567d18da4747a..e215bd75ff158 100755 --- a/eng/native/init-compiler.sh +++ b/eng/native/init-compiler.sh @@ -46,8 +46,8 @@ if [[ -z "$CLR_CC" ]]; then # Set default versions if [[ -z "$majorVersion" ]]; then # note: gcc (all versions) and clang versions higher than 6 do not have minor version in file name, if it is zero. - if [[ "$compiler" == "clang" ]]; then versions=( 11 10 9 8 7 6.0 5.0 4.0 3.9 3.8 3.7 3.6 3.5 ) - elif [[ "$compiler" == "gcc" ]]; then versions=( 11 10 9 8 7 6 5 4.9 ); fi + if [[ "$compiler" == "clang" ]]; then versions=( 16 15 14 13 12 11 10 9 8 7 6.0 5.0 4.0 3.9 3.8 3.7 3.6 3.5 ) + elif [[ "$compiler" == "gcc" ]]; then versions=( 12 11 10 9 8 7 6 5 4.9 ); fi for version in "${versions[@]}"; do parts=(${version//./ }) diff --git a/eng/testing/xunit/xunit.targets b/eng/testing/xunit/xunit.targets index 8d4aa64986e4d..5cf2846d40d18 100644 --- a/eng/testing/xunit/xunit.targets +++ b/eng/testing/xunit/xunit.targets @@ -4,6 +4,11 @@ + + true + true + + $(OutDir) diff --git a/global.json b/global.json index 85b8bcde770d4..49180d70c9d09 100644 --- a/global.json +++ b/global.json @@ -12,10 +12,10 @@ "python3": "3.7.1" }, "msbuild-sdks": { - "Microsoft.DotNet.Build.Tasks.TargetFramework.Sdk": "6.0.0-beta.23211.7", - "Microsoft.DotNet.Arcade.Sdk": "6.0.0-beta.23211.7", - "Microsoft.DotNet.Helix.Sdk": "6.0.0-beta.23211.7", - "Microsoft.DotNet.SharedFramework.Sdk": "6.0.0-beta.23211.7", + "Microsoft.DotNet.Build.Tasks.TargetFramework.Sdk": "6.0.0-beta.23221.7", + "Microsoft.DotNet.Arcade.Sdk": "6.0.0-beta.23221.7", + "Microsoft.DotNet.Helix.Sdk": "6.0.0-beta.23221.7", + "Microsoft.DotNet.SharedFramework.Sdk": "6.0.0-beta.23221.7", "Microsoft.Build.NoTargets": "3.1.0", "Microsoft.Build.Traversal": "3.0.23", "Microsoft.NET.Sdk.IL": "6.0.0-rc.1.21415.6" diff --git a/src/coreclr/debug/createdump/createdump.h b/src/coreclr/debug/createdump/createdump.h index 314533a9ed038..930e48b916654 100644 --- a/src/coreclr/debug/createdump/createdump.h +++ b/src/coreclr/debug/createdump/createdump.h @@ -103,7 +103,7 @@ typedef struct int Pid; int CrashThread; int Signal; -#if defined(HOST_UNIX) && !defined(HOST_OSX) +#if defined(HOST_UNIX) int SignalCode; int SignalErrno; void* SignalAddress; diff --git a/src/coreclr/debug/createdump/main.cpp b/src/coreclr/debug/createdump/main.cpp index bddc3f6ea0a22..6dd116a7a3c33 100644 --- a/src/coreclr/debug/createdump/main.cpp +++ b/src/coreclr/debug/createdump/main.cpp @@ -54,7 +54,7 @@ int __cdecl main(const int argc, const char* argv[]) options.Signal = 0; options.CrashThread = 0; options.Pid = 0; -#if defined(HOST_UNIX) && !defined(HOST_OSX) +#if defined(HOST_UNIX) options.SignalCode = 0; options.SignalErrno = 0; options.SignalAddress = nullptr; @@ -140,7 +140,6 @@ int __cdecl main(const int argc, const char* argv[]) { options.Signal = atoi(*++argv); } -#ifndef HOST_OSX else if (strcmp(*argv, "--code") == 0) { options.SignalCode = atoi(*++argv); @@ -153,7 +152,6 @@ int __cdecl main(const int argc, const char* argv[]) { options.SignalAddress = (void*)atoll(*++argv); } -#endif #endif else if ((strcmp(*argv, "-d") == 0) || (strcmp(*argv, "--diag") == 0)) { @@ -264,5 +262,3 @@ trace_verbose_printf(const char* format, ...) va_end(args); } } - - diff --git a/src/coreclr/dlls/mscordbi/CMakeLists.txt b/src/coreclr/dlls/mscordbi/CMakeLists.txt index c7a23c9923fe1..b7618b324c260 100644 --- a/src/coreclr/dlls/mscordbi/CMakeLists.txt +++ b/src/coreclr/dlls/mscordbi/CMakeLists.txt @@ -99,6 +99,17 @@ elseif(CLR_CMAKE_HOST_UNIX) mscordaccore ) + # Before llvm 16, lld was setting `--undefined-version` by default. The default was + # flipped to `--no-undefined-version` in lld 16, so we will explicitly set it to + # `--undefined-version` for our use-case. + include(CheckLinkerFlag OPTIONAL) + if(COMMAND check_linker_flag) + check_linker_flag(CXX -Wl,--undefined-version LINKER_SUPPORTS_UNDEFINED_VERSION) + if (LINKER_SUPPORTS_UNDEFINED_VERSION) + add_linker_flag(-Wl,--undefined-version) + endif(LINKER_SUPPORTS_UNDEFINED_VERSION) + endif(COMMAND check_linker_flag) + # COREDBI_LIBRARIES is mentioned twice because ld is one pass linker and will not find symbols # if they are defined after they are used. Having all libs twice makes sure that ld will actually # find all symbols. diff --git a/src/coreclr/pal/src/config.h.in b/src/coreclr/pal/src/config.h.in index c68421302e115..1de7a61dd6c52 100644 --- a/src/coreclr/pal/src/config.h.in +++ b/src/coreclr/pal/src/config.h.in @@ -68,6 +68,7 @@ #cmakedefine01 HAVE_SCHED_SETAFFINITY #cmakedefine HAVE_UNW_GET_SAVE_LOC #cmakedefine HAVE_UNW_GET_ACCESSORS +#cmakedefine HAVE_UNW_AARCH64_X19 #cmakedefine01 HAVE_XSWDEV #cmakedefine01 HAVE_XSW_USAGE #cmakedefine01 HAVE_PUBLIC_XSTATE_STRUCT diff --git a/src/coreclr/pal/src/configure.cmake b/src/coreclr/pal/src/configure.cmake index ee4a3241196ea..80d257fa349b6 100644 --- a/src/coreclr/pal/src/configure.cmake +++ b/src/coreclr/pal/src/configure.cmake @@ -1047,6 +1047,15 @@ int main(int argc, char **argv) check_symbol_exists(unw_get_save_loc libunwind.h HAVE_UNW_GET_SAVE_LOC) check_symbol_exists(unw_get_accessors libunwind.h HAVE_UNW_GET_ACCESSORS) +check_cxx_source_compiles(" +#include + +int main(int argc, char **argv) +{ + int flag = (int)UNW_AARCH64_X19; + return 0; +}" HAVE_UNW_AARCH64_X19) + if(NOT CLR_CMAKE_USE_SYSTEM_LIBUNWIND) list(REMOVE_AT CMAKE_REQUIRED_INCLUDES 0 1) endif() diff --git a/src/coreclr/pal/src/exception/seh-unwind.cpp b/src/coreclr/pal/src/exception/seh-unwind.cpp index a9ddb179d5f82..d1028feaeadac 100644 --- a/src/coreclr/pal/src/exception/seh-unwind.cpp +++ b/src/coreclr/pal/src/exception/seh-unwind.cpp @@ -54,7 +54,7 @@ Module Name: #endif // HOST_UNIX -#if defined(TARGET_OSX) && defined(TARGET_ARM64) +#if defined(TARGET_OSX) && defined(TARGET_ARM64) && !defined(HAVE_UNW_AARCH64_X19) // MacOS uses ARM64 instead of AARCH64 to describe these registers // Create aliases to reuse more code enum diff --git a/src/coreclr/vm/perfmap.cpp b/src/coreclr/vm/perfmap.cpp index 8eb8925f7e0b7..5eda731ec8bd0 100644 --- a/src/coreclr/vm/perfmap.cpp +++ b/src/coreclr/vm/perfmap.cpp @@ -11,6 +11,7 @@ #include "perfinfo.h" #include "pal.h" + // The code addresses are actually native image offsets during crossgen. Print // them as 32-bit numbers for consistent output when cross-targeting and to // make the output more compact. @@ -24,6 +25,15 @@ Volatile PerfMap::s_enabled = false; PerfMap * PerfMap::s_Current = nullptr; bool PerfMap::s_ShowOptimizationTiers = false; +unsigned PerfMap::s_StubsMapped = 0; + +enum +{ + DISABLED, + ALL, + JITDUMP, + PERFMAP +}; // Initialize the map for the process - called from EEStartupHelper. void PerfMap::Initialize() @@ -31,7 +41,7 @@ void PerfMap::Initialize() LIMITED_METHOD_CONTRACT; // Only enable the map if requested. - if (CLRConfig::GetConfigValue(CLRConfig::EXTERNAL_PerfMapEnabled)) + if (CLRConfig::GetConfigValue(CLRConfig::EXTERNAL_PerfMapEnabled) == ALL || CLRConfig::GetConfigValue(CLRConfig::EXTERNAL_PerfMapEnabled) == PERFMAP) { // Get the current process id. int currentPid = GetCurrentProcessId(); @@ -52,10 +62,12 @@ void PerfMap::Initialize() } s_enabled = true; + } -#ifndef CROSSGEN_COMPILE + if (CLRConfig::GetConfigValue(CLRConfig::EXTERNAL_PerfMapEnabled) == ALL || CLRConfig::GetConfigValue(CLRConfig::EXTERNAL_PerfMapEnabled) == JITDUMP) + { char jitdumpPath[4096]; - + // CLRConfig::GetConfigValue(CLRConfig::EXTERNAL_PerfMapJitDumpPath) returns a LPWSTR // Use GetEnvironmentVariableA because it is simpler. // Keep comment here to make it searchable. @@ -67,7 +79,13 @@ void PerfMap::Initialize() } PAL_PerfJitDump_Start(jitdumpPath); -#endif // CROSSGEN_COMPILE + + if (CLRConfig::GetConfigValue(CLRConfig::EXTERNAL_PerfMapShowOptimizationTiers) != 0) + { + s_ShowOptimizationTiers = true; + } + + s_enabled = true; } } @@ -92,8 +110,6 @@ PerfMap::PerfMap(int pid) // Initialize with no failures. m_ErrorEncountered = false; - m_StubsMapped = 0; - // Build the path to the map file on disk. WCHAR tempPath[MAX_LONGPATH+1]; if(!GetTempPathW(MAX_LONGPATH, tempPath)) @@ -120,8 +136,6 @@ PerfMap::PerfMap() // Initialize with no failures. m_ErrorEncountered = false; - - m_StubsMapped = 0; } // Clean-up resources. @@ -159,6 +173,11 @@ void PerfMap::WriteLine(SString& line) { STANDARD_VM_CONTRACT; + if (m_FileStream == nullptr || m_ErrorEncountered) + { + return; + } + EX_TRY { // Write the line. @@ -180,51 +199,9 @@ void PerfMap::WriteLine(SString& line) EX_CATCH{} EX_END_CATCH(SwallowAllExceptions); } -// Log a method to the map. -void PerfMap::LogMethod(MethodDesc * pMethod, PCODE pCode, size_t codeSize, const char *optimizationTier) -{ - CONTRACTL{ - THROWS; - GC_NOTRIGGER; - MODE_PREEMPTIVE; - PRECONDITION(pMethod != nullptr); - PRECONDITION(pCode != nullptr); - PRECONDITION(codeSize > 0); - } CONTRACTL_END; - - if (m_FileStream == nullptr || m_ErrorEncountered) - { - // A failure occurred, do not log. - return; - } - - // Logging failures should not cause any exceptions to flow upstream. - EX_TRY - { - // Get the full method signature. - SString name; - pMethod->GetFullMethodInfo(name); - - // Build the map file line. - StackScratchBuffer scratch; - if (optimizationTier != nullptr && s_ShowOptimizationTiers) - { - name.AppendPrintf("[%s]", optimizationTier); - } - SString line; - line.Printf(FMT_CODE_ADDR " %x %s\n", pCode, codeSize, name.GetANSI(scratch)); - - // Write the line. - WriteLine(line); - PAL_PerfJitDump_LogMethod((void*)pCode, codeSize, name.GetANSI(scratch), nullptr, nullptr); - } - EX_CATCH{} EX_END_CATCH(SwallowAllExceptions); -} - - -void PerfMap::LogImageLoad(PEFile * pFile) +void PerfMap::LogImageLoad(PEFile *pFile) { - if (s_enabled) + if (s_enabled && s_Current != nullptr) { s_Current->LogImage(pFile); } @@ -263,6 +240,15 @@ void PerfMap::LogJITCompiledMethod(MethodDesc * pMethod, PCODE pCode, size_t cod { LIMITED_METHOD_CONTRACT; + CONTRACTL{ + THROWS; + GC_NOTRIGGER; + MODE_PREEMPTIVE; + PRECONDITION(pMethod != nullptr); + PRECONDITION(pCode != nullptr); + PRECONDITION(codeSize > 0); + } CONTRACTL_END; + if (!s_enabled) { return; @@ -276,7 +262,32 @@ void PerfMap::LogJITCompiledMethod(MethodDesc * pMethod, PCODE pCode, size_t cod } #endif // CROSSGEN_COMPILE - s_Current->LogMethod(pMethod, pCode, codeSize, optimizationTier); + // Logging failures should not cause any exceptions to flow upstream. + EX_TRY + { + // Get the full method signature. + SString name; + pMethod->GetFullMethodInfo(name); + + // Build the map file line. + if (optimizationTier != nullptr && s_ShowOptimizationTiers) + { + name.AppendPrintf("[%s]", optimizationTier); + } + + StackScratchBuffer scratch; + SString line; + line.Printf(FMT_CODE_ADDR " %x %s\n", pCode, codeSize, name.GetANSI(scratch)); + + // Write the line. + if(s_Current != nullptr) + { + s_Current->WriteLine(line); + } + PAL_PerfJitDump_LogMethod((void*)pCode, codeSize, name.GetANSI(scratch), nullptr, nullptr); + } + EX_CATCH{} EX_END_CATCH(SwallowAllExceptions); + } // Log a pre-compiled method to the perfmap. @@ -335,7 +346,7 @@ void PerfMap::LogStubs(const char* stubType, const char* stubOwner, PCODE pCode, { LIMITED_METHOD_CONTRACT; - if (!s_enabled || s_Current->m_FileStream == nullptr) + if (!s_enabled) { return; } @@ -355,12 +366,15 @@ void PerfMap::LogStubs(const char* stubType, const char* stubOwner, PCODE pCode, // Build the map file line. StackScratchBuffer scratch; SString name; - name.Printf("stub<%d> %s<%s>", ++(s_Current->m_StubsMapped), stubType, stubOwner); + name.Printf("stub<%d> %s<%s>", ++(s_StubsMapped), stubType, stubOwner); SString line; line.Printf(FMT_CODE_ADDR " %x %s\n", pCode, codeSize, name.GetANSI(scratch)); // Write the line. - s_Current->WriteLine(line); + if(s_Current != nullptr) + { + s_Current->WriteLine(line); + } PAL_PerfJitDump_LogMethod((void*)pCode, codeSize, name.GetANSI(scratch), nullptr, nullptr); } EX_CATCH{} EX_END_CATCH(SwallowAllExceptions); @@ -417,6 +431,42 @@ NativeImagePerfMap::NativeImagePerfMap(Assembly * pAssembly, BSTR pDestPath) } } +void NativeImagePerfMap::LogMethod(MethodDesc * pMethod, PCODE pCode, size_t codeSize, const char *optimizationTier) +{ + CONTRACTL{ + THROWS; + GC_NOTRIGGER; + MODE_PREEMPTIVE; + PRECONDITION(pMethod != nullptr); + PRECONDITION(pCode != nullptr); + PRECONDITION(codeSize > 0); + } CONTRACTL_END; + + // Logging failures should not cause any exceptions to flow upstream. + EX_TRY + { + // Get the full method signature. + SString name; + pMethod->GetFullMethodInfo(name); + + // Build the map file line. + StackScratchBuffer scratch; + if (optimizationTier != nullptr && s_ShowOptimizationTiers) + { + name.AppendPrintf("[%s]", optimizationTier); + } + SString line; + line.Printf(FMT_CODE_ADDR " %x %s\n", pCode, codeSize, name.GetANSI(scratch)); + + if (s_Current != nullptr) + { + s_Current->WriteLine(line); + } + PAL_PerfJitDump_LogMethod((void*)pCode, codeSize, name.GetANSI(scratch), nullptr, nullptr); + } + EX_CATCH{} EX_END_CATCH(SwallowAllExceptions); +} + // Log data to the perfmap for the specified module. void NativeImagePerfMap::LogDataForModule(Module * pModule) { diff --git a/src/coreclr/vm/perfmap.h b/src/coreclr/vm/perfmap.h index 14595813877d8..636ac81830aa6 100644 --- a/src/coreclr/vm/perfmap.h +++ b/src/coreclr/vm/perfmap.h @@ -18,11 +18,8 @@ class PerfMap private: static Volatile s_enabled; - // The one and only PerfMap for the process. - static PerfMap * s_Current; - - // Indicates whether optimization tiers should be shown for methods in perf maps - static bool s_ShowOptimizationTiers; + // Set to true if an error is encountered when writing to the file. + static unsigned s_StubsMapped; // The file stream to write the map to. CFileStream * m_FileStream; @@ -33,16 +30,16 @@ class PerfMap // Set to true if an error is encountered when writing to the file. bool m_ErrorEncountered; - // Set to true if an error is encountered when writing to the file. - unsigned m_StubsMapped; - // Construct a new map for the specified pid. PerfMap(int pid); - // Write a line to the map file. - void WriteLine(SString & line); - protected: + // Indicates whether optimization tiers should be shown for methods in perf maps + static bool s_ShowOptimizationTiers; + + // The one and only PerfMap for the process. + static PerfMap * s_Current; + // Construct a new map without a specified file name. // Used for offline creation of NGEN map files. PerfMap(); @@ -53,9 +50,6 @@ class PerfMap // Open the perf map file for write. void OpenFile(SString& path); - // Does the actual work to log a method to the map. - void LogMethod(MethodDesc * pMethod, PCODE pCode, size_t codeSize, const char *optimizationTier); - // Does the actual work to log an image void LogImage(PEFile * pFile); @@ -63,6 +57,9 @@ class PerfMap static void GetNativeImageSignature(PEFile * pFile, WCHAR * pwszSig, unsigned int nSigSize); public: + // Write a line to the map file. + void WriteLine(SString & line); + // Initialize the map for the current process. static void Initialize(); @@ -91,6 +88,9 @@ class NativeImagePerfMap : PerfMap // Specify the address format since it's now possible for 'perf script' to output file offsets or RVAs. bool m_EmitRVAs; + // Does the actual work to log a method to the map. + void LogMethod(MethodDesc * pMethod, PCODE pCode, size_t codeSize, const char *optimizationTier); + // Log a pre-compiled method to the map. void LogPreCompiledMethod(MethodDesc * pMethod, PCODE pCode, PEImageLayout *pLoadedLayout, const char *optimizationTier); diff --git a/src/libraries/Common/src/Interop/Windows/Advapi32/Interop.QueryServiceStatusEx.cs b/src/libraries/Common/src/Interop/Windows/Advapi32/Interop.QueryServiceStatusEx.cs new file mode 100644 index 0000000000000..f5793d56db248 --- /dev/null +++ b/src/libraries/Common/src/Interop/Windows/Advapi32/Interop.QueryServiceStatusEx.cs @@ -0,0 +1,34 @@ +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. + +using Microsoft.Win32.SafeHandles; +using System; +using System.Runtime.InteropServices; + +internal static partial class Interop +{ + internal static partial class Advapi32 + { + [StructLayout(LayoutKind.Sequential)] + internal struct SERVICE_STATUS_PROCESS + { + public int dwServiceType; + public int dwCurrentState; + public int dwControlsAccepted; + public int dwWin32ExitCode; + public int dwServiceSpecificExitCode; + public int dwCheckPoint; + public int dwWaitHint; + public int dwProcessId; + public int dwServiceFlags; + } + + private const int SC_STATUS_PROCESS_INFO = 0; + + [DllImport(Libraries.Advapi32, SetLastError = true)] + [return: MarshalAs(UnmanagedType.Bool)] + private static unsafe extern bool QueryServiceStatusEx(SafeServiceHandle serviceHandle, int InfoLevel, SERVICE_STATUS_PROCESS* pStatus, int cbBufSize, out int pcbBytesNeeded); + + internal static unsafe bool QueryServiceStatusEx(SafeServiceHandle serviceHandle, SERVICE_STATUS_PROCESS* pStatus) => QueryServiceStatusEx(serviceHandle, SC_STATUS_PROCESS_INFO, pStatus, sizeof(SERVICE_STATUS_PROCESS), out _); + } +} diff --git a/src/libraries/Common/src/Interop/Windows/Interop.Errors.cs b/src/libraries/Common/src/Interop/Windows/Interop.Errors.cs index d5f6d1637507f..424b57f7a8d7b 100644 --- a/src/libraries/Common/src/Interop/Windows/Interop.Errors.cs +++ b/src/libraries/Common/src/Interop/Windows/Interop.Errors.cs @@ -63,6 +63,8 @@ internal static partial class Errors internal const int ERROR_IO_PENDING = 0x3E5; internal const int ERROR_NO_TOKEN = 0x3f0; internal const int ERROR_SERVICE_DOES_NOT_EXIST = 0x424; + internal const int ERROR_EXCEPTION_IN_SERVICE = 0x428; + internal const int ERROR_PROCESS_ABORTED = 0x42B; internal const int ERROR_NO_UNICODE_TRANSLATION = 0x459; internal const int ERROR_DLL_INIT_FAILED = 0x45A; internal const int ERROR_COUNTER_TIMEOUT = 0x461; diff --git a/src/libraries/Common/src/System/Net/Http/aspnetcore/Http2/Hpack/HPackDecoder.cs b/src/libraries/Common/src/System/Net/Http/aspnetcore/Http2/Hpack/HPackDecoder.cs index 22e2f8bd1987a..329552a2010c2 100644 --- a/src/libraries/Common/src/System/Net/Http/aspnetcore/Http2/Hpack/HPackDecoder.cs +++ b/src/libraries/Common/src/System/Net/Http/aspnetcore/Http2/Hpack/HPackDecoder.cs @@ -187,12 +187,11 @@ private void DecodeInternal(ReadOnlySpan data, IHttpHeadersHandler handler // will no longer be valid. if (_headerNameRange != null) { - EnsureStringCapacity(ref _headerNameOctets); + EnsureStringCapacity(ref _headerNameOctets, _headerNameLength); _headerName = _headerNameOctets; ReadOnlySpan headerBytes = data.Slice(_headerNameRange.GetValueOrDefault().start, _headerNameRange.GetValueOrDefault().length); headerBytes.CopyTo(_headerName); - _headerNameLength = headerBytes.Length; _headerNameRange = null; } } @@ -427,6 +426,7 @@ private void ParseHeaderName(ReadOnlySpan data, ref int currentIndex, IHtt { // Fast path. Store the range rather than copying. _headerNameRange = (start: currentIndex, count); + _headerNameLength = _stringLength; currentIndex += count; _state = State.HeaderValueLength; @@ -616,11 +616,12 @@ int Decode(ref byte[] dst) _state = nextState; } - private void EnsureStringCapacity(ref byte[] dst) + private void EnsureStringCapacity(ref byte[] dst, int stringLength = -1) { - if (dst.Length < _stringLength) + stringLength = stringLength >= 0 ? stringLength : _stringLength; + if (dst.Length < stringLength) { - dst = new byte[Math.Max(_stringLength, dst.Length * 2)]; + dst = new byte[Math.Max(stringLength, dst.Length * 2)]; } } diff --git a/src/libraries/Common/tests/Tests/System/Net/aspnetcore/Http2/HPackDecoderTest.cs b/src/libraries/Common/tests/Tests/System/Net/aspnetcore/Http2/HPackDecoderTest.cs index f73d72d3dd32d..9305334e319e0 100644 --- a/src/libraries/Common/tests/Tests/System/Net/aspnetcore/Http2/HPackDecoderTest.cs +++ b/src/libraries/Common/tests/Tests/System/Net/aspnetcore/Http2/HPackDecoderTest.cs @@ -46,8 +46,13 @@ public class HPackDecoderTests private const string _headerNameString = "new-header"; + // On purpose longer than 4096 (DefaultStringOctetsSize from HPackDecoder) to trigger https://github.com/dotnet/runtime/issues/78516 + private static readonly string _literalHeaderNameString = string.Concat(Enumerable.Range(0, 4100).Select(c => (char)('a' + (c % 26)))); + private static readonly byte[] _headerNameBytes = Encoding.ASCII.GetBytes(_headerNameString); + private static readonly byte[] _literalHeaderNameBytes = Encoding.ASCII.GetBytes(_literalHeaderNameString); + // n e w - h e a d e r * // 10101000 10111110 00010110 10011100 10100011 10010000 10110110 01111111 private static readonly byte[] _headerNameHuffmanBytes = new byte[] { 0xa8, 0xbe, 0x16, 0x9c, 0xa3, 0x90, 0xb6, 0x7f }; @@ -64,6 +69,12 @@ public class HPackDecoderTests .Concat(_headerNameBytes) .ToArray(); + // size = 4096 ==> 0x7f, 0x81, 0x1f (7+) prefixed integer + // size = 4100 ==> 0x7f, 0x85, 0x1f (7+) prefixed integer + private static readonly byte[] _literalHeaderName = new byte[] { 0x7f, 0x85, 0x1f } // 4100 + .Concat(_literalHeaderNameBytes) + .ToArray(); + private static readonly byte[] _headerNameHuffman = new byte[] { (byte)(0x80 | _headerNameHuffmanBytes.Length) } .Concat(_headerNameHuffmanBytes) .ToArray(); @@ -392,6 +403,101 @@ public void DecodesLiteralHeaderFieldNeverIndexed_IndexedName_OutOfRange_Error() Assert.Empty(_handler.DecodedHeaders); } + [Fact] + public void DecodesLiteralHeaderFieldNeverIndexed_NewName_SingleBuffer() + { + byte[] encoded = _literalHeaderFieldWithoutIndexingNewName + .Concat(_literalHeaderName) + .Concat(_headerValue) + .ToArray(); + + _decoder.Decode(encoded, endHeaders: true, handler: _handler); + + Assert.Equal(1, _handler.DecodedHeaders.Count); + Assert.True(_handler.DecodedHeaders.ContainsKey(_literalHeaderNameString)); + Assert.Equal(_headerValueString, _handler.DecodedHeaders[_literalHeaderNameString]); + } + + [Fact] + public void DecodesLiteralHeaderFieldNeverIndexed_NewName_NameLengthBrokenIntoSeparateBuffers() + { + byte[] encoded = _literalHeaderFieldWithoutIndexingNewName + .Concat(_literalHeaderName) + .Concat(_headerValue) + .ToArray(); + + _decoder.Decode(encoded[..1], endHeaders: false, handler: _handler); + _decoder.Decode(encoded[1..], endHeaders: true, handler: _handler); + + Assert.Equal(1, _handler.DecodedHeaders.Count); + Assert.True(_handler.DecodedHeaders.ContainsKey(_literalHeaderNameString)); + Assert.Equal(_headerValueString, _handler.DecodedHeaders[_literalHeaderNameString]); + } + + [Fact] + public void DecodesLiteralHeaderFieldNeverIndexed_NewName_NameBrokenIntoSeparateBuffers() + { + byte[] encoded = _literalHeaderFieldWithoutIndexingNewName + .Concat(_literalHeaderName) + .Concat(_headerValue) + .ToArray(); + + _decoder.Decode(encoded[..(_literalHeaderNameString.Length / 2)], endHeaders: false, handler: _handler); + _decoder.Decode(encoded[(_literalHeaderNameString.Length / 2)..], endHeaders: true, handler: _handler); + + Assert.Equal(1, _handler.DecodedHeaders.Count); + Assert.True(_handler.DecodedHeaders.ContainsKey(_literalHeaderNameString)); + Assert.Equal(_headerValueString, _handler.DecodedHeaders[_literalHeaderNameString]); + } + + [Fact] + public void DecodesLiteralHeaderFieldNeverIndexed_NewName_NameAndValueBrokenIntoSeparateBuffers() + { + byte[] encoded = _literalHeaderFieldWithoutIndexingNewName + .Concat(_literalHeaderName) + .Concat(_headerValue) + .ToArray(); + + _decoder.Decode(encoded[..^_headerValue.Length], endHeaders: false, handler: _handler); + _decoder.Decode(encoded[^_headerValue.Length..], endHeaders: true, handler: _handler); + + Assert.Equal(1, _handler.DecodedHeaders.Count); + Assert.True(_handler.DecodedHeaders.ContainsKey(_literalHeaderNameString)); + Assert.Equal(_headerValueString, _handler.DecodedHeaders[_literalHeaderNameString]); + } + + [Fact] + public void DecodesLiteralHeaderFieldNeverIndexed_NewName_ValueLengthBrokenIntoSeparateBuffers() + { + byte[] encoded = _literalHeaderFieldWithoutIndexingNewName + .Concat(_literalHeaderName) + .Concat(_headerValue) + .ToArray(); + + _decoder.Decode(encoded[..^(_headerValue.Length - 1)], endHeaders: false, handler: _handler); + _decoder.Decode(encoded[^(_headerValue.Length - 1)..], endHeaders: true, handler: _handler); + + Assert.Equal(1, _handler.DecodedHeaders.Count); + Assert.True(_handler.DecodedHeaders.ContainsKey(_literalHeaderNameString)); + Assert.Equal(_headerValueString, _handler.DecodedHeaders[_literalHeaderNameString]); + } + + [Fact] + public void DecodesLiteralHeaderFieldNeverIndexed_NewName_ValueBrokenIntoSeparateBuffers() + { + byte[] encoded = _literalHeaderFieldWithoutIndexingNewName + .Concat(_literalHeaderName) + .Concat(_headerValue) + .ToArray(); + + _decoder.Decode(encoded[..^(_headerValueString.Length / 2)], endHeaders: false, handler: _handler); + _decoder.Decode(encoded[^(_headerValueString.Length / 2)..], endHeaders: true, handler: _handler); + + Assert.Equal(1, _handler.DecodedHeaders.Count); + Assert.True(_handler.DecodedHeaders.ContainsKey(_literalHeaderNameString)); + Assert.Equal(_headerValueString, _handler.DecodedHeaders[_literalHeaderNameString]); + } + [Fact] public void DecodesDynamicTableSizeUpdate() { diff --git a/src/libraries/Microsoft.Extensions.Hosting.WindowsServices/src/Microsoft.Extensions.Hosting.WindowsServices.csproj b/src/libraries/Microsoft.Extensions.Hosting.WindowsServices/src/Microsoft.Extensions.Hosting.WindowsServices.csproj index 8585f19a795d7..9757cd56763cb 100644 --- a/src/libraries/Microsoft.Extensions.Hosting.WindowsServices/src/Microsoft.Extensions.Hosting.WindowsServices.csproj +++ b/src/libraries/Microsoft.Extensions.Hosting.WindowsServices/src/Microsoft.Extensions.Hosting.WindowsServices.csproj @@ -4,7 +4,8 @@ net461;netstandard2.0;netstandard2.1 true .NET hosting infrastructure for Windows Services. - 1 + true + 2 diff --git a/src/libraries/Microsoft.Extensions.Hosting.WindowsServices/src/WindowsServiceLifetime.cs b/src/libraries/Microsoft.Extensions.Hosting.WindowsServices/src/WindowsServiceLifetime.cs index f374e3f0f7132..6f76ab3975bd3 100644 --- a/src/libraries/Microsoft.Extensions.Hosting.WindowsServices/src/WindowsServiceLifetime.cs +++ b/src/libraries/Microsoft.Extensions.Hosting.WindowsServices/src/WindowsServiceLifetime.cs @@ -13,8 +13,10 @@ namespace Microsoft.Extensions.Hosting.WindowsServices public class WindowsServiceLifetime : ServiceBase, IHostLifetime { private readonly TaskCompletionSource _delayStart = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); + private readonly TaskCompletionSource _serviceDispatcherStopped = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); private readonly ManualResetEventSlim _delayStop = new ManualResetEventSlim(); private readonly HostOptions _hostOptions; + private bool _serviceStopRequested; public WindowsServiceLifetime(IHostEnvironment environment, IHostApplicationLifetime applicationLifetime, ILoggerFactory loggerFactory, IOptions optionsAccessor) : this(environment, applicationLifetime, loggerFactory, optionsAccessor, Options.Options.Create(new WindowsServiceLifetimeOptions())) @@ -73,19 +75,30 @@ private void Run() { Run(this); // This blocks until the service is stopped. _delayStart.TrySetException(new InvalidOperationException("Stopped without starting")); + _serviceDispatcherStopped.TrySetResult(null); } catch (Exception ex) { _delayStart.TrySetException(ex); + _serviceDispatcherStopped.TrySetException(ex); } } - public Task StopAsync(CancellationToken cancellationToken) + /// + /// Called from to stop the service if not already stopped, and wait for the service dispatcher to exit. + /// Once this method returns the service is stopped and the process can be terminated at any time. + /// + public async Task StopAsync(CancellationToken cancellationToken) { - // Avoid deadlock where host waits for StopAsync before firing ApplicationStopped, - // and Stop waits for ApplicationStopped. - Task.Run(Stop, CancellationToken.None); - return Task.CompletedTask; + cancellationToken.ThrowIfCancellationRequested(); + + if (!_serviceStopRequested) + { + await Task.Run(Stop, cancellationToken).ConfigureAwait(false); + } + + // When the underlying service is stopped this will cause the ServiceBase.Run method to complete and return, which completes _serviceDispatcherStopped. + await _serviceDispatcherStopped.Task.ConfigureAwait(false); } // Called by base.Run when the service is ready to start. @@ -95,18 +108,28 @@ protected override void OnStart(string[] args) base.OnStart(args); } - // Called by base.Stop. This may be called multiple times by service Stop, ApplicationStopping, and StopAsync. - // That's OK because StopApplication uses a CancellationTokenSource and prevents any recursion. + /// + /// Executes when a Stop command is sent to the service by the Service Control Manager (SCM). + /// Triggers and waits for . + /// Shortly after this method returns, the Service will be marked as stopped in SCM and the process may exit at any point. + /// protected override void OnStop() { + _serviceStopRequested = true; ApplicationLifetime.StopApplication(); // Wait for the host to shutdown before marking service as stopped. _delayStop.Wait(_hostOptions.ShutdownTimeout); base.OnStop(); } + /// + /// Executes when a Shutdown command is sent to the service by the Service Control Manager (SCM). + /// Triggers and waits for . + /// Shortly after this method returns, the Service will be marked as stopped in SCM and the process may exit at any point. + /// protected override void OnShutdown() { + _serviceStopRequested = true; ApplicationLifetime.StopApplication(); // Wait for the host to shutdown before marking service as stopped. _delayStop.Wait(_hostOptions.ShutdownTimeout); diff --git a/src/libraries/Microsoft.Extensions.Hosting.WindowsServices/test/Microsoft.Extensions.Hosting.WindowsServices.Tests.csproj b/src/libraries/Microsoft.Extensions.Hosting.WindowsServices/test/Microsoft.Extensions.Hosting.WindowsServices.Tests.csproj index 67b1cb31ee521..bbbcfb8bee964 100644 --- a/src/libraries/Microsoft.Extensions.Hosting.WindowsServices/test/Microsoft.Extensions.Hosting.WindowsServices.Tests.csproj +++ b/src/libraries/Microsoft.Extensions.Hosting.WindowsServices/test/Microsoft.Extensions.Hosting.WindowsServices.Tests.csproj @@ -1,12 +1,46 @@ - + - $(NetCoreAppCurrent);net461 + + $(NetCoreAppCurrent)-windows;net461 true + true + true + + + + + + + + + + + + + + + + + + + diff --git a/src/libraries/Microsoft.Extensions.Hosting.WindowsServices/test/UseWindowsServiceTests.cs b/src/libraries/Microsoft.Extensions.Hosting.WindowsServices/test/UseWindowsServiceTests.cs index 7e24685466d91..aec72dbdb27fe 100644 --- a/src/libraries/Microsoft.Extensions.Hosting.WindowsServices/test/UseWindowsServiceTests.cs +++ b/src/libraries/Microsoft.Extensions.Hosting.WindowsServices/test/UseWindowsServiceTests.cs @@ -1,14 +1,24 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. +using System; +using System.Reflection; +using System.ServiceProcess; +using Microsoft.DotNet.RemoteExecutor; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Hosting.Internal; +using Microsoft.Extensions.Hosting.WindowsServices; +using Microsoft.Extensions.Logging; +using Microsoft.Extensions.Logging.EventLog; +using Microsoft.Extensions.Options; using Xunit; namespace Microsoft.Extensions.Hosting { public class UseWindowsServiceTests { + private static bool IsRemoteExecutorSupportedAndPrivilegedProcess => RemoteExecutor.IsSupported && AdminHelpers.IsProcessElevated(); + [Fact] public void DefaultsToOffOutsideOfService() { @@ -18,9 +28,29 @@ public void DefaultsToOffOutsideOfService() using (host) { - var lifetime = host.Services.GetRequiredService(); - Assert.IsType(lifetime); - } + var lifetime = host.Services.GetRequiredService(); + Assert.IsType(lifetime); + } + } + + [ConditionalFact(nameof(IsRemoteExecutorSupportedAndPrivilegedProcess))] + public void CanCreateService() + { + using var serviceTester = WindowsServiceTester.Create(() => + { + using IHost host = new HostBuilder() + .UseWindowsService() + .Build(); + host.Run(); + }); + + serviceTester.Start(); + serviceTester.WaitForStatus(ServiceControllerStatus.Running); + serviceTester.Stop(); + serviceTester.WaitForStatus(ServiceControllerStatus.Stopped); + + var status = serviceTester.QueryServiceStatus(); + Assert.Equal(0, status.win32ExitCode); } } } diff --git a/src/libraries/Microsoft.Extensions.Hosting.WindowsServices/test/WindowsServiceLifetimeTests.cs b/src/libraries/Microsoft.Extensions.Hosting.WindowsServices/test/WindowsServiceLifetimeTests.cs new file mode 100644 index 0000000000000..fda639fbc9715 --- /dev/null +++ b/src/libraries/Microsoft.Extensions.Hosting.WindowsServices/test/WindowsServiceLifetimeTests.cs @@ -0,0 +1,348 @@ +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. + +using System; +using System.Diagnostics; +using System.IO; +using System.ServiceProcess; +using System.Threading; +using System.Threading.Tasks; +using Microsoft.DotNet.RemoteExecutor; +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Hosting.Internal; +using Microsoft.Extensions.Hosting.WindowsServices; +using Microsoft.Extensions.Logging; +using Microsoft.Extensions.Logging.Abstractions; +using Microsoft.Extensions.Options; +using Xunit; + +namespace Microsoft.Extensions.Hosting +{ + public class WindowsServiceLifetimeTests + { + private static bool IsRemoteExecutorSupportedAndPrivilegedProcess => RemoteExecutor.IsSupported && AdminHelpers.IsProcessElevated(); + + [ConditionalFact(nameof(IsRemoteExecutorSupportedAndPrivilegedProcess))] + public void ServiceStops() + { + using var serviceTester = WindowsServiceTester.Create(async () => + { + var applicationLifetime = new ApplicationLifetime(NullLogger.Instance); + using var lifetime = new WindowsServiceLifetime( + new HostingEnvironment(), + applicationLifetime, + NullLoggerFactory.Instance, + new OptionsWrapper(new HostOptions())); + + await lifetime.WaitForStartAsync(CancellationToken.None); + + // would normally occur here, but WindowsServiceLifetime does not depend on it. + // applicationLifetime.NotifyStarted(); + + // will be signaled by WindowsServiceLifetime when SCM stops the service. + applicationLifetime.ApplicationStopping.WaitHandle.WaitOne(); + + // required by WindowsServiceLifetime to identify that app has stopped. + applicationLifetime.NotifyStopped(); + + await lifetime.StopAsync(CancellationToken.None); + }); + + serviceTester.Start(); + serviceTester.WaitForStatus(ServiceControllerStatus.Running); + + var statusEx = serviceTester.QueryServiceStatusEx(); + var serviceProcess = Process.GetProcessById(statusEx.dwProcessId); + + serviceTester.Stop(); + serviceTester.WaitForStatus(ServiceControllerStatus.Stopped); + + serviceProcess.WaitForExit(); + + var status = serviceTester.QueryServiceStatus(); + Assert.Equal(0, status.win32ExitCode); + } + + [ConditionalFact(nameof(IsRemoteExecutorSupportedAndPrivilegedProcess))] + [SkipOnTargetFramework(TargetFrameworkMonikers.NetFramework, ".NET Framework is missing the fix from https://github.com/dotnet/corefx/commit/3e68d791066ad0fdc6e0b81828afbd9df00dd7f8")] + public void ExceptionOnStartIsPropagated() + { + using var serviceTester = WindowsServiceTester.Create(async () => + { + using (var lifetime = ThrowingWindowsServiceLifetime.Create(throwOnStart: new Exception("Should be thrown"))) + { + Assert.Equal(lifetime.ThrowOnStart, + await Assert.ThrowsAsync(async () => + await lifetime.WaitForStartAsync(CancellationToken.None))); + } + }); + + serviceTester.Start(); + + serviceTester.WaitForStatus(ServiceControllerStatus.Stopped); + var status = serviceTester.QueryServiceStatus(); + Assert.Equal(Interop.Errors.ERROR_EXCEPTION_IN_SERVICE, status.win32ExitCode); + } + + [ConditionalFact(nameof(IsRemoteExecutorSupportedAndPrivilegedProcess))] + public void ExceptionOnStopIsPropagated() + { + using var serviceTester = WindowsServiceTester.Create(async () => + { + using (var lifetime = ThrowingWindowsServiceLifetime.Create(throwOnStop: new Exception("Should be thrown"))) + { + await lifetime.WaitForStartAsync(CancellationToken.None); + lifetime.ApplicationLifetime.NotifyStopped(); + Assert.Equal(lifetime.ThrowOnStop, + await Assert.ThrowsAsync(async () => + await lifetime.StopAsync(CancellationToken.None))); + } + }); + + serviceTester.Start(); + + serviceTester.WaitForStatus(ServiceControllerStatus.Stopped); + var status = serviceTester.QueryServiceStatus(); + Assert.Equal(Interop.Errors.ERROR_PROCESS_ABORTED, status.win32ExitCode); + } + + [ConditionalFact(nameof(IsRemoteExecutorSupportedAndPrivilegedProcess))] + public void CancelStopAsync() + { + using var serviceTester = WindowsServiceTester.Create(async () => + { + var applicationLifetime = new ApplicationLifetime(NullLogger.Instance); + using var lifetime = new WindowsServiceLifetime( + new HostingEnvironment(), + applicationLifetime, + NullLoggerFactory.Instance, + new OptionsWrapper(new HostOptions())); + await lifetime.WaitForStartAsync(CancellationToken.None); + + await Assert.ThrowsAsync(async () => await lifetime.StopAsync(new CancellationToken(true))); + }); + + serviceTester.Start(); + + serviceTester.WaitForStatus(ServiceControllerStatus.Stopped); + var status = serviceTester.QueryServiceStatus(); + Assert.Equal(Interop.Errors.ERROR_PROCESS_ABORTED, status.win32ExitCode); + } + + [ConditionalFact(nameof(IsRemoteExecutorSupportedAndPrivilegedProcess))] + public void ServiceCanStopItself() + { + using (var serviceTester = WindowsServiceTester.Create(async () => + { + FileLogger.InitializeForTestCase(nameof(ServiceCanStopItself)); + using IHost host = new HostBuilder() + .ConfigureServices(services => + { + services.AddHostedService(); + services.AddSingleton(); + }) + .Build(); + + var applicationLifetime = host.Services.GetRequiredService(); + applicationLifetime.ApplicationStarted.Register(() => FileLogger.Log($"lifetime started")); + applicationLifetime.ApplicationStopping.Register(() => FileLogger.Log($"lifetime stopping")); + applicationLifetime.ApplicationStopped.Register(() => FileLogger.Log($"lifetime stopped")); + + FileLogger.Log("host.Start()"); + host.Start(); + + using (ServiceController selfController = new(nameof(ServiceCanStopItself))) + { + selfController.WaitForStatus(ServiceControllerStatus.Running, WindowsServiceTester.WaitForStatusTimeout); + Assert.Equal(ServiceControllerStatus.Running, selfController.Status); + + FileLogger.Log("host.Stop()"); + await host.StopAsync(); + FileLogger.Log("host.Stop() complete"); + + selfController.WaitForStatus(ServiceControllerStatus.Stopped, WindowsServiceTester.WaitForStatusTimeout); + Assert.Equal(ServiceControllerStatus.Stopped, selfController.Status); + } + })) + { + FileLogger.DeleteLog(nameof(ServiceCanStopItself)); + + // service should start cleanly + serviceTester.Start(); + + // service will proceed to stopped without any error + serviceTester.WaitForStatus(ServiceControllerStatus.Stopped); + + var status = serviceTester.QueryServiceStatus(); + Assert.Equal(0, status.win32ExitCode); + + } + + var logText = FileLogger.ReadLog(nameof(ServiceCanStopItself)); + Assert.Equal( +@"host.Start() +WindowsServiceLifetime.OnStart +BackgroundService.StartAsync +lifetime started +host.Stop() +lifetime stopping +BackgroundService.StopAsync +lifetime stopped +WindowsServiceLifetime.OnStop +host.Stop() complete +", logText); + } + + [ConditionalFact(nameof(IsRemoteExecutorSupportedAndPrivilegedProcess))] + public void ServiceSequenceIsCorrect() + { + using (var serviceTester = WindowsServiceTester.Create(() => + { + FileLogger.InitializeForTestCase(nameof(ServiceSequenceIsCorrect)); + using IHost host = new HostBuilder() + .ConfigureServices(services => + { + services.AddHostedService(); + services.AddSingleton(); + }) + .Build(); + + var applicationLifetime = host.Services.GetRequiredService(); + applicationLifetime.ApplicationStarted.Register(() => FileLogger.Log($"lifetime started")); + applicationLifetime.ApplicationStopping.Register(() => FileLogger.Log($"lifetime stopping")); + applicationLifetime.ApplicationStopped.Register(() => FileLogger.Log($"lifetime stopped")); + + FileLogger.Log("host.Run()"); + host.Run(); + FileLogger.Log("host.Run() complete"); + })) + { + + FileLogger.DeleteLog(nameof(ServiceSequenceIsCorrect)); + + serviceTester.Start(); + serviceTester.WaitForStatus(ServiceControllerStatus.Running); + + var statusEx = serviceTester.QueryServiceStatusEx(); + var serviceProcess = Process.GetProcessById(statusEx.dwProcessId); + + // Give a chance for all asynchronous "started" events to be raised, these happen after the service status changes to started + Thread.Sleep(1000); + + serviceTester.Stop(); + serviceTester.WaitForStatus(ServiceControllerStatus.Stopped); + + var status = serviceTester.QueryServiceStatus(); + Assert.Equal(0, status.win32ExitCode); + + } + + var logText = FileLogger.ReadLog(nameof(ServiceSequenceIsCorrect)); + Assert.Equal( +@"host.Run() +WindowsServiceLifetime.OnStart +BackgroundService.StartAsync +lifetime started +WindowsServiceLifetime.OnStop +lifetime stopping +BackgroundService.StopAsync +lifetime stopped +host.Run() complete +", logText); + + } + + public class LoggingWindowsServiceLifetime : WindowsServiceLifetime + { + public LoggingWindowsServiceLifetime(IHostEnvironment environment, IHostApplicationLifetime applicationLifetime, ILoggerFactory loggerFactory, IOptions optionsAccessor) : + base(environment, applicationLifetime, loggerFactory, optionsAccessor) + { } + + protected override void OnStart(string[] args) + { + FileLogger.Log("WindowsServiceLifetime.OnStart"); + base.OnStart(args); + } + + protected override void OnStop() + { + FileLogger.Log("WindowsServiceLifetime.OnStop"); + base.OnStop(); + } + } + + public class ThrowingWindowsServiceLifetime : WindowsServiceLifetime + { + public static ThrowingWindowsServiceLifetime Create(Exception throwOnStart = null, Exception throwOnStop = null) => + new ThrowingWindowsServiceLifetime( + new HostingEnvironment(), + new ApplicationLifetime(NullLogger.Instance), + NullLoggerFactory.Instance, + new OptionsWrapper(new HostOptions())) + { + ThrowOnStart = throwOnStart, + ThrowOnStop = throwOnStop + }; + + public ThrowingWindowsServiceLifetime(IHostEnvironment environment, ApplicationLifetime applicationLifetime, ILoggerFactory loggerFactory, IOptions optionsAccessor) : + base(environment, applicationLifetime, loggerFactory, optionsAccessor) + { + ApplicationLifetime = applicationLifetime; + } + + public ApplicationLifetime ApplicationLifetime { get; } + + public Exception ThrowOnStart { get; set; } + protected override void OnStart(string[] args) + { + if (ThrowOnStart != null) + { + throw ThrowOnStart; + } + base.OnStart(args); + } + + public Exception ThrowOnStop { get; set; } + protected override void OnStop() + { + if (ThrowOnStop != null) + { + throw ThrowOnStop; + } + base.OnStop(); + } + } + + public class LoggingBackgroundService : BackgroundService + { +#pragma warning disable CS1998 // Async method lacks 'await' operators and will run synchronously + protected override async Task ExecuteAsync(CancellationToken stoppingToken) => FileLogger.Log("BackgroundService.ExecuteAsync"); + public override async Task StartAsync(CancellationToken stoppingToken) => FileLogger.Log("BackgroundService.StartAsync"); + public override async Task StopAsync(CancellationToken stoppingToken) => FileLogger.Log("BackgroundService.StopAsync"); +#pragma warning restore CS1998 // Async method lacks 'await' operators and will run synchronously + } + + static class FileLogger + { + static string _fileName; + + public static void InitializeForTestCase(string testCaseName) + { + Assert.Null(_fileName); + _fileName = GetLogForTestCase(testCaseName); + } + + private static string GetLogForTestCase(string testCaseName) => Path.Combine(AppContext.BaseDirectory, $"{testCaseName}.log"); + public static void DeleteLog(string testCaseName) => File.Delete(GetLogForTestCase(testCaseName)); + public static string ReadLog(string testCaseName) => File.ReadAllText(GetLogForTestCase(testCaseName)); + public static void Log(string message) + { + Assert.NotNull(_fileName); + lock (_fileName) + { + File.AppendAllText(_fileName, message + Environment.NewLine); + } + } + } + } +} diff --git a/src/libraries/Microsoft.Extensions.Hosting.WindowsServices/test/WindowsServiceTester.cs b/src/libraries/Microsoft.Extensions.Hosting.WindowsServices/test/WindowsServiceTester.cs new file mode 100644 index 0000000000000..63103dacd3e6d --- /dev/null +++ b/src/libraries/Microsoft.Extensions.Hosting.WindowsServices/test/WindowsServiceTester.cs @@ -0,0 +1,158 @@ +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. + +using System; +using System.ComponentModel; +using System.Diagnostics; +using System.Runtime.CompilerServices; +using System.ServiceProcess; +using System.Threading.Tasks; +using Microsoft.DotNet.RemoteExecutor; +using Microsoft.Win32.SafeHandles; +using Xunit; + +namespace Microsoft.Extensions.Hosting +{ + public class WindowsServiceTester : ServiceController + { + private WindowsServiceTester(SafeServiceHandle serviceHandle, RemoteInvokeHandle remoteInvokeHandle, string serviceName) : base(serviceName) + { + _serviceHandle = serviceHandle; + _remoteInvokeHandle = remoteInvokeHandle; + } + + private SafeServiceHandle _serviceHandle; + private RemoteInvokeHandle _remoteInvokeHandle; + + public new void Start() + { + Start(Array.Empty()); + } + + public new void Start(string[] args) + { + base.Start(args); + + // get the process + _remoteInvokeHandle.Process.Dispose(); + _remoteInvokeHandle.Process = null; + + var statusEx = QueryServiceStatusEx(); + try + { + _remoteInvokeHandle.Process = Process.GetProcessById(statusEx.dwProcessId); + // fetch the process handle so that we can get the exit code later. + var _ = _remoteInvokeHandle.Process.SafeHandle; + } + catch (ArgumentException) + { } + } + + public static TimeSpan WaitForStatusTimeout { get; set; } = TimeSpan.FromSeconds(30); + + public new void WaitForStatus(ServiceControllerStatus desiredStatus) => + WaitForStatus(desiredStatus, WaitForStatusTimeout); + + public new void WaitForStatus(ServiceControllerStatus desiredStatus, TimeSpan timeout) + { + base.WaitForStatus(desiredStatus, timeout); + + Assert.Equal(Status, desiredStatus); + } + + // the following overloads are necessary to ensure the compiler will produce the correct signature from a lambda. + public static WindowsServiceTester Create(Func serviceMain, [CallerMemberName] string serviceName = null) => Create(RemoteExecutor.Invoke(serviceMain, remoteInvokeOptions), serviceName); + + public static WindowsServiceTester Create(Func> serviceMain, [CallerMemberName] string serviceName = null) => Create(RemoteExecutor.Invoke(serviceMain, remoteInvokeOptions), serviceName); + + public static WindowsServiceTester Create(Func serviceMain, [CallerMemberName] string serviceName = null) => Create(RemoteExecutor.Invoke(serviceMain, remoteInvokeOptions), serviceName); + + public static WindowsServiceTester Create(Action serviceMain, [CallerMemberName] string serviceName = null) => Create(RemoteExecutor.Invoke(serviceMain, remoteInvokeOptions), serviceName); + + private static RemoteInvokeOptions remoteInvokeOptions = new RemoteInvokeOptions() { Start = false }; + + private static WindowsServiceTester Create(RemoteInvokeHandle remoteInvokeHandle, string serviceName) + { + // create remote executor commandline arguments + var startInfo = remoteInvokeHandle.Process.StartInfo; + string commandLine = startInfo.FileName + " " + startInfo.Arguments; + + // install the service + using (var serviceManagerHandle = new SafeServiceHandle(Interop.Advapi32.OpenSCManager(null, null, Interop.Advapi32.ServiceControllerOptions.SC_MANAGER_ALL))) + { + if (serviceManagerHandle.IsInvalid) + { + throw new InvalidOperationException(); + } + + // delete existing service if it exists + using (var existingServiceHandle = new SafeServiceHandle(Interop.Advapi32.OpenService(serviceManagerHandle, serviceName, Interop.Advapi32.ServiceAccessOptions.ACCESS_TYPE_ALL))) + { + if (!existingServiceHandle.IsInvalid) + { + Interop.Advapi32.DeleteService(existingServiceHandle); + } + } + + var serviceHandle = new SafeServiceHandle( + Interop.Advapi32.CreateService(serviceManagerHandle, + serviceName, + $"{nameof(WindowsServiceTester)} {serviceName} test service", + Interop.Advapi32.ServiceAccessOptions.ACCESS_TYPE_ALL, + Interop.Advapi32.ServiceTypeOptions.SERVICE_TYPE_WIN32_OWN_PROCESS, + (int)ServiceStartMode.Manual, + Interop.Advapi32.ServiceStartErrorModes.ERROR_CONTROL_NORMAL, + commandLine, + loadOrderGroup: null, + pTagId: IntPtr.Zero, + dependencies: null, + servicesStartName: null, + password: null)); + + if (serviceHandle.IsInvalid) + { + throw new Win32Exception(); + } + + return new WindowsServiceTester(serviceHandle, remoteInvokeHandle, serviceName); + } + } + + internal unsafe Interop.Advapi32.SERVICE_STATUS QueryServiceStatus() + { + Interop.Advapi32.SERVICE_STATUS status = default; + bool success = Interop.Advapi32.QueryServiceStatus(_serviceHandle, &status); + if (!success) + { + throw new Win32Exception(); + } + return status; + } + + internal unsafe Interop.Advapi32.SERVICE_STATUS_PROCESS QueryServiceStatusEx() + { + Interop.Advapi32.SERVICE_STATUS_PROCESS status = default; + bool success = Interop.Advapi32.QueryServiceStatusEx(_serviceHandle, &status); + if (!success) + { + throw new Win32Exception(); + } + return status; + } + + protected override void Dispose(bool disposing) + { + if (_remoteInvokeHandle != null) + { + _remoteInvokeHandle.Dispose(); + } + + if (!_serviceHandle.IsInvalid) + { + // delete the temporary test service + Interop.Advapi32.DeleteService(_serviceHandle); + _serviceHandle.Close(); + } + } + } +} diff --git a/src/libraries/Microsoft.NETCore.Platforms/src/Microsoft.NETCore.Platforms.csproj b/src/libraries/Microsoft.NETCore.Platforms/src/Microsoft.NETCore.Platforms.csproj index e7365db967190..dde76f41f06cf 100644 --- a/src/libraries/Microsoft.NETCore.Platforms/src/Microsoft.NETCore.Platforms.csproj +++ b/src/libraries/Microsoft.NETCore.Platforms/src/Microsoft.NETCore.Platforms.csproj @@ -19,8 +19,8 @@ $(AdditionalRuntimeIdentifiers);$(OutputRID) - 9 - false + 10 + true diff --git a/src/libraries/Microsoft.NETCore.Platforms/src/RID.cs b/src/libraries/Microsoft.NETCore.Platforms/src/RID.cs index 6f08d1a510e56..42ce8b4e9631a 100644 --- a/src/libraries/Microsoft.NETCore.Platforms/src/RID.cs +++ b/src/libraries/Microsoft.NETCore.Platforms/src/RID.cs @@ -56,7 +56,7 @@ private enum RIDPart : int Max = Qualifier } - public static RID Parse(string runtimeIdentifier) + public static RID Parse(string runtimeIdentifier, bool noQualifier) { string[] parts = new string[(int)RIDPart.Max + 1]; bool omitVersionDelimiter = true; @@ -90,6 +90,15 @@ public static RID Parse(string runtimeIdentifier) // version might be omitted else if (current == ArchitectureDelimiter) { + // The qualifier delimiter and architecture delimiter are the same. + // When there is no qualifier, there will be one delimiter past the base part + // for the architecture. + // So if we see another delimiter later in the string (for the architecture), + // extend the base part instead of starting the architecture part. + if (noQualifier && runtimeIdentifier.IndexOf(ArchitectureDelimiter, i + 1) != -1) + { + break; + } // ensure there's no version later in the string if (runtimeIdentifier.IndexOf(VersionDelimiter, i) != -1) { diff --git a/src/libraries/Microsoft.NETCore.Platforms/src/RuntimeGroupCollection.cs b/src/libraries/Microsoft.NETCore.Platforms/src/RuntimeGroupCollection.cs index 970da5c1f8665..5c2f0c42078f9 100644 --- a/src/libraries/Microsoft.NETCore.Platforms/src/RuntimeGroupCollection.cs +++ b/src/libraries/Microsoft.NETCore.Platforms/src/RuntimeGroupCollection.cs @@ -34,7 +34,8 @@ public RuntimeGroupCollection(ICollection runtimeGroups) /// public void AddRuntimeIdentifier(string runtimeIdentifier, string parent) { - RID rid = RID.Parse(runtimeIdentifier); + // don't parse qualifier since we don't use them and they are ambiguous with `-` in base RID + RID rid = RID.Parse(runtimeIdentifier, noQualifier: true); AddRuntimeIdentifier(rid, parent); } diff --git a/src/libraries/Microsoft.NETCore.Platforms/src/runtime.compatibility.json b/src/libraries/Microsoft.NETCore.Platforms/src/runtime.compatibility.json index d49b40577f0ee..f072bc1d426ac 100644 --- a/src/libraries/Microsoft.NETCore.Platforms/src/runtime.compatibility.json +++ b/src/libraries/Microsoft.NETCore.Platforms/src/runtime.compatibility.json @@ -1359,6 +1359,217 @@ "any", "base" ], + "alpine.3.18": [ + "alpine.3.18", + "alpine.3.17", + "alpine.3.16", + "alpine.3.15", + "alpine.3.14", + "alpine.3.13", + "alpine.3.12", + "alpine.3.11", + "alpine.3.10", + "alpine.3.9", + "alpine.3.8", + "alpine.3.7", + "alpine.3.6", + "alpine", + "linux-musl", + "linux", + "unix", + "any", + "base" + ], + "alpine.3.18-arm": [ + "alpine.3.18-arm", + "alpine.3.18", + "alpine.3.17-arm", + "alpine.3.17", + "alpine.3.16-arm", + "alpine.3.16", + "alpine.3.15-arm", + "alpine.3.15", + "alpine.3.14-arm", + "alpine.3.14", + "alpine.3.13-arm", + "alpine.3.13", + "alpine.3.12-arm", + "alpine.3.12", + "alpine.3.11-arm", + "alpine.3.11", + "alpine.3.10-arm", + "alpine.3.10", + "alpine.3.9-arm", + "alpine.3.9", + "alpine.3.8-arm", + "alpine.3.8", + "alpine.3.7-arm", + "alpine.3.7", + "alpine.3.6-arm", + "alpine.3.6", + "alpine-arm", + "alpine", + "linux-musl-arm", + "linux-musl", + "linux-arm", + "linux", + "unix-arm", + "unix", + "any", + "base" + ], + "alpine.3.18-arm64": [ + "alpine.3.18-arm64", + "alpine.3.18", + "alpine.3.17-arm64", + "alpine.3.17", + "alpine.3.16-arm64", + "alpine.3.16", + "alpine.3.15-arm64", + "alpine.3.15", + "alpine.3.14-arm64", + "alpine.3.14", + "alpine.3.13-arm64", + "alpine.3.13", + "alpine.3.12-arm64", + "alpine.3.12", + "alpine.3.11-arm64", + "alpine.3.11", + "alpine.3.10-arm64", + "alpine.3.10", + "alpine.3.9-arm64", + "alpine.3.9", + "alpine.3.8-arm64", + "alpine.3.8", + "alpine.3.7-arm64", + "alpine.3.7", + "alpine.3.6-arm64", + "alpine.3.6", + "alpine-arm64", + "alpine", + "linux-musl-arm64", + "linux-musl", + "linux-arm64", + "linux", + "unix-arm64", + "unix", + "any", + "base" + ], + "alpine.3.18-s390x": [ + "alpine.3.18-s390x", + "alpine.3.18", + "alpine.3.17-s390x", + "alpine.3.17", + "alpine.3.16-s390x", + "alpine.3.16", + "alpine.3.15-s390x", + "alpine.3.15", + "alpine.3.14-s390x", + "alpine.3.14", + "alpine.3.13-s390x", + "alpine.3.13", + "alpine.3.12-s390x", + "alpine.3.12", + "alpine.3.11-s390x", + "alpine.3.11", + "alpine.3.10-s390x", + "alpine.3.10", + "alpine.3.9-s390x", + "alpine.3.9", + "alpine.3.8-s390x", + "alpine.3.8", + "alpine.3.7-s390x", + "alpine.3.7", + "alpine.3.6-s390x", + "alpine.3.6", + "alpine-s390x", + "alpine", + "linux-musl-s390x", + "linux-musl", + "linux-s390x", + "linux", + "unix-s390x", + "unix", + "any", + "base" + ], + "alpine.3.18-x64": [ + "alpine.3.18-x64", + "alpine.3.18", + "alpine.3.17-x64", + "alpine.3.17", + "alpine.3.16-x64", + "alpine.3.16", + "alpine.3.15-x64", + "alpine.3.15", + "alpine.3.14-x64", + "alpine.3.14", + "alpine.3.13-x64", + "alpine.3.13", + "alpine.3.12-x64", + "alpine.3.12", + "alpine.3.11-x64", + "alpine.3.11", + "alpine.3.10-x64", + "alpine.3.10", + "alpine.3.9-x64", + "alpine.3.9", + "alpine.3.8-x64", + "alpine.3.8", + "alpine.3.7-x64", + "alpine.3.7", + "alpine.3.6-x64", + "alpine.3.6", + "alpine-x64", + "alpine", + "linux-musl-x64", + "linux-musl", + "linux-x64", + "linux", + "unix-x64", + "unix", + "any", + "base" + ], + "alpine.3.18-x86": [ + "alpine.3.18-x86", + "alpine.3.18", + "alpine.3.17-x86", + "alpine.3.17", + "alpine.3.16-x86", + "alpine.3.16", + "alpine.3.15-x86", + "alpine.3.15", + "alpine.3.14-x86", + "alpine.3.14", + "alpine.3.13-x86", + "alpine.3.13", + "alpine.3.12-x86", + "alpine.3.12", + "alpine.3.11-x86", + "alpine.3.11", + "alpine.3.10-x86", + "alpine.3.10", + "alpine.3.9-x86", + "alpine.3.9", + "alpine.3.8-x86", + "alpine.3.8", + "alpine.3.7-x86", + "alpine.3.7", + "alpine.3.6-x86", + "alpine.3.6", + "alpine-x86", + "alpine", + "linux-musl-x86", + "linux-musl", + "linux-x86", + "linux", + "unix-x86", + "unix", + "any", + "base" + ], "alpine.3.6": [ "alpine.3.6", "alpine", @@ -9554,6 +9765,71 @@ "any", "base" ], + "ubuntu.22.10": [ + "ubuntu.22.10", + "ubuntu", + "debian", + "linux", + "unix", + "any", + "base" + ], + "ubuntu.22.10-arm": [ + "ubuntu.22.10-arm", + "ubuntu.22.10", + "ubuntu-arm", + "ubuntu", + "debian-arm", + "debian", + "linux-arm", + "linux", + "unix-arm", + "unix", + "any", + "base" + ], + "ubuntu.22.10-arm64": [ + "ubuntu.22.10-arm64", + "ubuntu.22.10", + "ubuntu-arm64", + "ubuntu", + "debian-arm64", + "debian", + "linux-arm64", + "linux", + "unix-arm64", + "unix", + "any", + "base" + ], + "ubuntu.22.10-x64": [ + "ubuntu.22.10-x64", + "ubuntu.22.10", + "ubuntu-x64", + "ubuntu", + "debian-x64", + "debian", + "linux-x64", + "linux", + "unix-x64", + "unix", + "any", + "base" + ], + "ubuntu.22.10-x86": [ + "ubuntu.22.10-x86", + "ubuntu.22.10", + "ubuntu-x86", + "ubuntu", + "debian-x86", + "debian", + "linux-x86", + "linux", + "unix-x86", + "unix", + "any", + "base" + ], "ubuntu.23.04": [ "ubuntu.23.04", "ubuntu", @@ -9619,6 +9895,71 @@ "any", "base" ], + "ubuntu.23.10": [ + "ubuntu.23.10", + "ubuntu", + "debian", + "linux", + "unix", + "any", + "base" + ], + "ubuntu.23.10-arm": [ + "ubuntu.23.10-arm", + "ubuntu.23.10", + "ubuntu-arm", + "ubuntu", + "debian-arm", + "debian", + "linux-arm", + "linux", + "unix-arm", + "unix", + "any", + "base" + ], + "ubuntu.23.10-arm64": [ + "ubuntu.23.10-arm64", + "ubuntu.23.10", + "ubuntu-arm64", + "ubuntu", + "debian-arm64", + "debian", + "linux-arm64", + "linux", + "unix-arm64", + "unix", + "any", + "base" + ], + "ubuntu.23.10-x64": [ + "ubuntu.23.10-x64", + "ubuntu.23.10", + "ubuntu-x64", + "ubuntu", + "debian-x64", + "debian", + "linux-x64", + "linux", + "unix-x64", + "unix", + "any", + "base" + ], + "ubuntu.23.10-x86": [ + "ubuntu.23.10-x86", + "ubuntu.23.10", + "ubuntu-x86", + "ubuntu", + "debian-x86", + "debian", + "linux-x86", + "linux", + "unix-x86", + "unix", + "any", + "base" + ], "unix": [ "unix", "any", diff --git a/src/libraries/Microsoft.NETCore.Platforms/src/runtime.json b/src/libraries/Microsoft.NETCore.Platforms/src/runtime.json index ddba63053ee85..2f1a877f69808 100644 --- a/src/libraries/Microsoft.NETCore.Platforms/src/runtime.json +++ b/src/libraries/Microsoft.NETCore.Platforms/src/runtime.json @@ -315,6 +315,41 @@ "alpine.3.16-x86" ] }, + "alpine.3.18": { + "#import": [ + "alpine.3.17" + ] + }, + "alpine.3.18-arm": { + "#import": [ + "alpine.3.18", + "alpine.3.17-arm" + ] + }, + "alpine.3.18-arm64": { + "#import": [ + "alpine.3.18", + "alpine.3.17-arm64" + ] + }, + "alpine.3.18-s390x": { + "#import": [ + "alpine.3.18", + "alpine.3.17-s390x" + ] + }, + "alpine.3.18-x64": { + "#import": [ + "alpine.3.18", + "alpine.3.17-x64" + ] + }, + "alpine.3.18-x86": { + "#import": [ + "alpine.3.18", + "alpine.3.17-x86" + ] + }, "alpine.3.6": { "#import": [ "alpine" @@ -3764,6 +3799,35 @@ "ubuntu-x86" ] }, + "ubuntu.22.10": { + "#import": [ + "ubuntu" + ] + }, + "ubuntu.22.10-arm": { + "#import": [ + "ubuntu.22.10", + "ubuntu-arm" + ] + }, + "ubuntu.22.10-arm64": { + "#import": [ + "ubuntu.22.10", + "ubuntu-arm64" + ] + }, + "ubuntu.22.10-x64": { + "#import": [ + "ubuntu.22.10", + "ubuntu-x64" + ] + }, + "ubuntu.22.10-x86": { + "#import": [ + "ubuntu.22.10", + "ubuntu-x86" + ] + }, "ubuntu.23.04": { "#import": [ "ubuntu" @@ -3793,6 +3857,35 @@ "ubuntu-x86" ] }, + "ubuntu.23.10": { + "#import": [ + "ubuntu" + ] + }, + "ubuntu.23.10-arm": { + "#import": [ + "ubuntu.23.10", + "ubuntu-arm" + ] + }, + "ubuntu.23.10-arm64": { + "#import": [ + "ubuntu.23.10", + "ubuntu-arm64" + ] + }, + "ubuntu.23.10-x64": { + "#import": [ + "ubuntu.23.10", + "ubuntu-x64" + ] + }, + "ubuntu.23.10-x86": { + "#import": [ + "ubuntu.23.10", + "ubuntu-x86" + ] + }, "unix": { "#import": [ "any" diff --git a/src/libraries/Microsoft.NETCore.Platforms/src/runtimeGroups.props b/src/libraries/Microsoft.NETCore.Platforms/src/runtimeGroups.props index 6ddb8956684a2..92a1c049d02cf 100644 --- a/src/libraries/Microsoft.NETCore.Platforms/src/runtimeGroups.props +++ b/src/libraries/Microsoft.NETCore.Platforms/src/runtimeGroups.props @@ -16,7 +16,7 @@ linux-musl x64;x86;arm;arm64;s390x - 3.6;3.7;3.8;3.9;3.10;3.11;3.12;3.13;3.14;3.15;3.16;3.17 + 3.6;3.7;3.8;3.9;3.10;3.11;3.12;3.13;3.14;3.15;3.16;3.17;3.18 @@ -244,7 +244,7 @@ debian x64;x86;arm;arm64 - 16.04;16.10;17.04;17.10;18.04;18.10;19.04;19.10;20.04;20.10;21.04;21.10;22.04;23.04 + 16.04;16.10;17.04;17.10;18.04;18.10;19.04;19.10;20.04;20.10;21.04;21.10;22.04;22.10;23.04;23.10 false diff --git a/src/libraries/Microsoft.NETCore.Platforms/tests/RidTests.cs b/src/libraries/Microsoft.NETCore.Platforms/tests/RidTests.cs index 227bcbdd10d4d..8dee0ebeda17a 100644 --- a/src/libraries/Microsoft.NETCore.Platforms/tests/RidTests.cs +++ b/src/libraries/Microsoft.NETCore.Platforms/tests/RidTests.cs @@ -10,35 +10,57 @@ public class RidTests { public static IEnumerable ValidRIDData() { - yield return new object[] { "win10-x64", new RID() { BaseRID = "win", OmitVersionDelimiter = true, Version = new RuntimeVersion("10"), Architecture = "x64" } }; - yield return new object[] { "win10", new RID() { BaseRID = "win", OmitVersionDelimiter = true, Version = new RuntimeVersion("10")} }; - yield return new object[] { "linux", new RID() { BaseRID = "linux" } }; - yield return new object[] { "linux-x64", new RID() { BaseRID = "linux", Architecture = "x64" } }; - yield return new object[] { "linux-x64", new RID() { BaseRID = "linux", Architecture = "x64" } }; - yield return new object[] { "debian.10-x64", new RID() { BaseRID = "debian", Version = new RuntimeVersion("10"), Architecture = "x64" } }; - yield return new object[] { "linuxmint.19.2-x64", new RID() { BaseRID = "linuxmint", Version = new RuntimeVersion("19.2"), Architecture = "x64" } }; - yield return new object[] { "ubuntu.14.04-x64", new RID() { BaseRID = "ubuntu", Version = new RuntimeVersion("14.04"), Architecture = "x64" } }; - yield return new object[] { "foo-bar.42-arm", new RID() { BaseRID = "foo-bar", Version = new RuntimeVersion("42"), Architecture = "arm" } }; - yield return new object[] { "foo-bar-arm", new RID() { BaseRID = "foo", Architecture = "bar", Qualifier = "arm" } }; // demonstrates ambiguity, avoid using `-` in base - yield return new object[] { "linux-musl-x64", new RID() { BaseRID = "linux", Architecture = "musl", Qualifier = "x64" } }; // yes, we already have ambiguous RIDs + yield return new object[] { "win10-x64", new RID() { BaseRID = "win", OmitVersionDelimiter = true, Version = new RuntimeVersion("10"), Architecture = "x64" }, null }; + yield return new object[] { "win10", new RID() { BaseRID = "win", OmitVersionDelimiter = true, Version = new RuntimeVersion("10")}, null }; + yield return new object[] { "linux", new RID() { BaseRID = "linux" }, null }; + yield return new object[] { "linux-x64", new RID() { BaseRID = "linux", Architecture = "x64" }, null }; + yield return new object[] { "linux-x64", new RID() { BaseRID = "linux", Architecture = "x64" }, null }; + yield return new object[] { "debian.10-x64", new RID() { BaseRID = "debian", Version = new RuntimeVersion("10"), Architecture = "x64" }, null }; + yield return new object[] { "linuxmint.19.2-x64", new RID() { BaseRID = "linuxmint", Version = new RuntimeVersion("19.2"), Architecture = "x64" }, null }; + yield return new object[] { "ubuntu.14.04-x64", new RID() { BaseRID = "ubuntu", Version = new RuntimeVersion("14.04"), Architecture = "x64" }, null }; + yield return new object[] { "foo-bar.42-arm", new RID() { BaseRID = "foo-bar", Version = new RuntimeVersion("42"), Architecture = "arm" }, null }; + yield return new object[] { "foo-bar-arm", new RID() { BaseRID = "foo", Architecture = "bar", Qualifier = "arm" }, // demonstrates ambiguity, avoid using `-` in base + new RID() { BaseRID = "foo-bar", Architecture = "arm" } }; + yield return new object[] { "linux-musl-x64", new RID() { BaseRID = "linux", Architecture = "musl", Qualifier = "x64" }, // yes, we already have ambiguous RIDs + new RID() { BaseRID = "linux-musl", Architecture = "x64" } }; } [Theory] [MemberData(nameof(ValidRIDData))] - internal void ParseCorrectly(string input, RID expected) + internal void ParseCorrectly(string input, RID expected, RID? expectedNoQualifier) { - RID actual = RID.Parse(input); + _ = expectedNoQualifier; // unused + + RID actual = RID.Parse(input, noQualifier: false); Assert.Equal(expected, actual); } [Theory] [MemberData(nameof(ValidRIDData))] - internal void ToStringAsExpected(string expected, RID rid) + internal void ParseCorrectlyNoQualifier(string input, RID expected, RID? expectedNoQualifier) + { + expectedNoQualifier ??= expected; + + RID actual = RID.Parse(input, noQualifier: true); + + Assert.Equal(expectedNoQualifier, actual); + } + + [Theory] + [MemberData(nameof(ValidRIDData))] + internal void ToStringAsExpected(string expected, RID rid, RID? expectedNoQualifierRid) { string actual = rid.ToString(); Assert.Equal(expected, actual); + + if (expectedNoQualifierRid is not null) + { + actual = expectedNoQualifierRid.ToString(); + + Assert.Equal(expected, actual); + } } } } diff --git a/src/libraries/Microsoft.Windows.Compatibility/src/Microsoft.Windows.Compatibility.csproj b/src/libraries/Microsoft.Windows.Compatibility/src/Microsoft.Windows.Compatibility.csproj index 96212cd348f63..aff4bb11d3e8c 100644 --- a/src/libraries/Microsoft.Windows.Compatibility/src/Microsoft.Windows.Compatibility.csproj +++ b/src/libraries/Microsoft.Windows.Compatibility/src/Microsoft.Windows.Compatibility.csproj @@ -6,7 +6,7 @@ false true true - 5 + 6 $(NoWarn);NU5128 This Windows Compatibility Pack provides access to APIs that were previously available only for .NET Framework. It can be used from both .NET Core as well as .NET Standard. diff --git a/src/libraries/Native/Unix/CMakeLists.txt b/src/libraries/Native/Unix/CMakeLists.txt index 997849f9ecf92..89c2317d107a8 100644 --- a/src/libraries/Native/Unix/CMakeLists.txt +++ b/src/libraries/Native/Unix/CMakeLists.txt @@ -51,6 +51,15 @@ if(CMAKE_C_COMPILER_ID STREQUAL Clang) add_compile_options(-Wthread-safety) add_compile_options(-Wno-thread-safety-analysis) add_compile_options(-Wno-reserved-identifier) + + # clang 16.0 introduced buffer hardening https://discourse.llvm.org/t/rfc-c-buffer-hardening/65734 + # which we are not conforming to yet. + add_compile_options(-Wno-unsafe-buffer-usage) + + # other clang 16.0 suppressions + add_compile_options(-Wno-single-bit-bitfield-constant-conversion) + add_compile_options(-Wno-cast-function-type-strict) + add_compile_options(-Wno-incompatible-function-pointer-types-strict) elseif(CMAKE_C_COMPILER_ID STREQUAL GNU) add_compile_options(-Wno-stringop-truncation) endif() diff --git a/src/libraries/System.Net.Http.Json/tests/FunctionalTests/HttpClientJsonExtensionsTests.cs b/src/libraries/System.Net.Http.Json/tests/FunctionalTests/HttpClientJsonExtensionsTests.cs index bb2ec7ba2408f..7d8d5602ae54c 100644 --- a/src/libraries/System.Net.Http.Json/tests/FunctionalTests/HttpClientJsonExtensionsTests.cs +++ b/src/libraries/System.Net.Http.Json/tests/FunctionalTests/HttpClientJsonExtensionsTests.cs @@ -266,6 +266,7 @@ public static IEnumerable GetFromJsonAsync_EnforcesMaxResponseContentB [ConditionalTheory(typeof(PlatformDetection), nameof(PlatformDetection.IsNotBrowser))] // No Socket support [MemberData(nameof(GetFromJsonAsync_EnforcesMaxResponseContentBufferSize_MemberData))] + [ActiveIssue("https://github.com/dotnet/runtime/issues/34582", TestPlatforms.Windows, TargetFrameworkMonikers.Netcoreapp, TestRuntimes.Mono)] public async Task GetFromJsonAsync_EnforcesMaxResponseContentBufferSize(int limit, int contentLength, bool chunked) { await LoopbackServer.CreateClientAndServerAsync(async uri => diff --git a/src/libraries/System.Net.Http/src/System/Net/Http/HttpClient.cs b/src/libraries/System.Net.Http/src/System/Net/Http/HttpClient.cs index 3b77aeafc0467..9ef0b3bbf0e26 100644 --- a/src/libraries/System.Net.Http/src/System/Net/Http/HttpClient.cs +++ b/src/libraries/System.Net.Http/src/System/Net/Http/HttpClient.cs @@ -224,7 +224,7 @@ private async Task GetStringAsyncCore(HttpRequestMessage request, Cancel } finally { - FinishSend(cts, disposeCts, telemetryStarted, responseContentTelemetryStarted); + FinishSend(response, cts, disposeCts, telemetryStarted, responseContentTelemetryStarted); } } @@ -303,7 +303,7 @@ private async Task GetByteArrayAsyncCore(HttpRequestMessage request, Can } finally { - FinishSend(cts, disposeCts, telemetryStarted, responseContentTelemetryStarted); + FinishSend(response, cts, disposeCts, telemetryStarted, responseContentTelemetryStarted); } } @@ -349,7 +349,7 @@ private async Task GetStreamAsyncCore(HttpRequestMessage request, Cancel } finally { - FinishSend(cts, disposeCts, telemetryStarted, responseContentTelemetryStarted: false); + FinishSend(response, cts, disposeCts, telemetryStarted, responseContentTelemetryStarted: false); } } @@ -493,7 +493,7 @@ public HttpResponseMessage Send(HttpRequestMessage request, HttpCompletionOption } finally { - FinishSend(cts, disposeCts, telemetryStarted, responseContentTelemetryStarted); + FinishSend(response, cts, disposeCts, telemetryStarted, responseContentTelemetryStarted); } } @@ -548,7 +548,7 @@ async Task Core( } finally { - FinishSend(cts, disposeCts, telemetryStarted, responseContentTelemetryStarted); + FinishSend(response, cts, disposeCts, telemetryStarted, responseContentTelemetryStarted); } } } @@ -583,8 +583,6 @@ private static bool ShouldBufferResponse(HttpCompletionOption completionOption, private void HandleFailure(Exception e, bool telemetryStarted, HttpResponseMessage? response, CancellationTokenSource cts, CancellationToken cancellationToken, CancellationTokenSource pendingRequestsCts) { - LogRequestFailed(telemetryStarted); - response?.Dispose(); Exception? toThrow = null; @@ -616,6 +614,8 @@ private void HandleFailure(Exception e, bool telemetryStarted, HttpResponseMessa e = toThrow = new OperationCanceledException(cancellationToken.IsCancellationRequested ? cancellationToken : cts.Token); } + LogRequestFailed(e, telemetryStarted); + if (NetEventSource.Log.IsEnabled()) NetEventSource.Error(this, e); if (toThrow != null) @@ -635,7 +635,7 @@ private static bool StartSend(HttpRequestMessage request) return false; } - private static void FinishSend(CancellationTokenSource cts, bool disposeCts, bool telemetryStarted, bool responseContentTelemetryStarted) + private static void FinishSend(HttpResponseMessage? response, CancellationTokenSource cts, bool disposeCts, bool telemetryStarted, bool responseContentTelemetryStarted) { // Log completion. if (HttpTelemetry.Log.IsEnabled() && telemetryStarted) @@ -645,7 +645,7 @@ private static void FinishSend(CancellationTokenSource cts, bool disposeCts, boo HttpTelemetry.Log.ResponseContentStop(); } - HttpTelemetry.Log.RequestStop(); + HttpTelemetry.Log.RequestStop(response); } // Dispose of the CancellationTokenSource if it was created specially for this request diff --git a/src/libraries/System.Net.Http/src/System/Net/Http/HttpMessageInvoker.cs b/src/libraries/System.Net.Http/src/System/Net/Http/HttpMessageInvoker.cs index 9b33c75b4b22d..a4a93e08b2bf9 100644 --- a/src/libraries/System.Net.Http/src/System/Net/Http/HttpMessageInvoker.cs +++ b/src/libraries/System.Net.Http/src/System/Net/Http/HttpMessageInvoker.cs @@ -46,18 +46,20 @@ public virtual HttpResponseMessage Send(HttpRequestMessage request, Cancellation { HttpTelemetry.Log.RequestStart(request); + HttpResponseMessage? response = null; try { - return _handler.Send(request, cancellationToken); + response = _handler.Send(request, cancellationToken); + return response; } - catch when (LogRequestFailed(telemetryStarted: true)) + catch (Exception ex) when (LogRequestFailed(ex, telemetryStarted: true)) { // Unreachable as LogRequestFailed will return false throw; } finally { - HttpTelemetry.Log.RequestStop(); + HttpTelemetry.Log.RequestStop(response); } } else @@ -85,18 +87,20 @@ static async Task SendAsyncWithTelemetry(HttpMessageHandler { HttpTelemetry.Log.RequestStart(request); + HttpResponseMessage? response = null; try { - return await handler.SendAsync(request, cancellationToken).ConfigureAwait(false); + response = await handler.SendAsync(request, cancellationToken).ConfigureAwait(false); + return response; } - catch when (LogRequestFailed(telemetryStarted: true)) + catch (Exception ex) when (LogRequestFailed(ex, telemetryStarted: true)) { // Unreachable as LogRequestFailed will return false throw; } finally { - HttpTelemetry.Log.RequestStop(); + HttpTelemetry.Log.RequestStop(response); } } } @@ -107,11 +111,11 @@ private static bool ShouldSendWithTelemetry(HttpRequestMessage request) => request.RequestUri is Uri requestUri && requestUri.IsAbsoluteUri; - internal static bool LogRequestFailed(bool telemetryStarted) + internal static bool LogRequestFailed(Exception exception, bool telemetryStarted) { if (HttpTelemetry.Log.IsEnabled() && telemetryStarted) { - HttpTelemetry.Log.RequestFailed(); + HttpTelemetry.Log.RequestFailed(exception); } return false; } diff --git a/src/libraries/System.Net.Http/src/System/Net/Http/HttpTelemetry.cs b/src/libraries/System.Net.Http/src/System/Net/Http/HttpTelemetry.cs index ae52766e08116..cb5015010db7e 100644 --- a/src/libraries/System.Net.Http/src/System/Net/Http/HttpTelemetry.cs +++ b/src/libraries/System.Net.Http/src/System/Net/Http/HttpTelemetry.cs @@ -48,18 +48,34 @@ public void RequestStart(HttpRequestMessage request) request.VersionPolicy); } - [Event(2, Level = EventLevel.Informational)] - public void RequestStop() + [NonEvent] + public void RequestStop(HttpResponseMessage? response) + { + RequestStop(response is null ? -1 : (int)response.StatusCode); + } + + [Event(2, Level = EventLevel.Informational, Version = 1)] + private void RequestStop(int statusCode) { Interlocked.Increment(ref _stoppedRequests); - WriteEvent(eventId: 2); + WriteEvent(eventId: 2, statusCode); } - [Event(3, Level = EventLevel.Error)] - public void RequestFailed() + [NonEvent] + public void RequestFailed(Exception exception) { Interlocked.Increment(ref _failedRequests); - WriteEvent(eventId: 3); + + if (IsEnabled(EventLevel.Error, EventKeywords.None)) + { + RequestFailed(exceptionMessage: exception.Message); + } + } + + [Event(3, Level = EventLevel.Error, Version = 1)] + private void RequestFailed(string exceptionMessage) + { + WriteEvent(eventId: 3, exceptionMessage); } [Event(4, Level = EventLevel.Informational)] @@ -110,10 +126,10 @@ public void ResponseHeadersStart() WriteEvent(eventId: 11); } - [Event(12, Level = EventLevel.Informational)] - public void ResponseHeadersStop() + [Event(12, Level = EventLevel.Informational, Version = 1)] + public void ResponseHeadersStop(int statusCode) { - WriteEvent(eventId: 12); + WriteEvent(eventId: 12, statusCode); } [Event(13, Level = EventLevel.Informational)] diff --git a/src/libraries/System.Net.Http/src/System/Net/Http/SocketsHttpHandler/Http2Stream.cs b/src/libraries/System.Net.Http/src/System/Net/Http/SocketsHttpHandler/Http2Stream.cs index aa31d88ee8252..5a880f78e30ef 100644 --- a/src/libraries/System.Net.Http/src/System/Net/Http/SocketsHttpHandler/Http2Stream.cs +++ b/src/libraries/System.Net.Http/src/System/Net/Http/SocketsHttpHandler/Http2Stream.cs @@ -998,7 +998,8 @@ public async Task ReadResponseHeadersAsync(CancellationToken cancellationToken) Debug.Assert(!wait); } - if (HttpTelemetry.Log.IsEnabled()) HttpTelemetry.Log.ResponseHeadersStop(); + Debug.Assert(_response is not null); + if (HttpTelemetry.Log.IsEnabled()) HttpTelemetry.Log.ResponseHeadersStop((int)_response.StatusCode); } catch { diff --git a/src/libraries/System.Net.Http/src/System/Net/Http/SocketsHttpHandler/HttpConnection.cs b/src/libraries/System.Net.Http/src/System/Net/Http/SocketsHttpHandler/HttpConnection.cs index 922603b55b143..5efe3736b8410 100644 --- a/src/libraries/System.Net.Http/src/System/Net/Http/SocketsHttpHandler/HttpConnection.cs +++ b/src/libraries/System.Net.Http/src/System/Net/Http/SocketsHttpHandler/HttpConnection.cs @@ -669,7 +669,7 @@ public async Task SendAsyncCore(HttpRequestMessage request, ParseHeaderNameValue(this, line.Span, response, isFromTrailer: false); } - if (HttpTelemetry.Log.IsEnabled()) HttpTelemetry.Log.ResponseHeadersStop(); + if (HttpTelemetry.Log.IsEnabled()) HttpTelemetry.Log.ResponseHeadersStop((int)response.StatusCode); if (allowExpect100ToContinue != null) { diff --git a/src/libraries/System.Net.Http/tests/FunctionalTests/TelemetryTest.cs b/src/libraries/System.Net.Http/tests/FunctionalTests/TelemetryTest.cs index 9cbba2ad0382f..069c9c0e72a67 100644 --- a/src/libraries/System.Net.Http/tests/FunctionalTests/TelemetryTest.cs +++ b/src/libraries/System.Net.Http/tests/FunctionalTests/TelemetryTest.cs @@ -409,14 +409,25 @@ private static void ValidateStartFailedStopEvents(ConcurrentQueue<(EventWrittenE Assert.Equal(count, starts.Length); (EventWrittenEventArgs Event, Guid ActivityId)[] stops = events.Where(e => e.Event.EventName == "RequestStop").ToArray(); - Assert.All(stops, stopEvent => Assert.Empty(stopEvent.Event.Payload)); + foreach (EventWrittenEventArgs stopEvent in stops.Select(e => e.Event)) + { + object payload = Assert.Single(stopEvent.Payload); + int statusCode = Assert.IsType(payload); + Assert.Equal(shouldHaveFailures ? -1 : 200, statusCode); + } ValidateSameActivityIds(starts, stops); (EventWrittenEventArgs Event, Guid ActivityId)[] failures = events.Where(e => e.Event.EventName == "RequestFailed").ToArray(); - Assert.All(failures, failedEvent => Assert.Empty(failedEvent.Event.Payload)); if (shouldHaveFailures) { + foreach (EventWrittenEventArgs failedEvent in failures.Select(e => e.Event)) + { + object payload = Assert.Single(failedEvent.Payload); + string exceptionMessage = Assert.IsType(payload); + Assert.Equal(new OperationCanceledException().Message, exceptionMessage); + } + ValidateSameActivityIds(starts, failures); } else @@ -467,8 +478,8 @@ private static void ValidateRequestResponseStartStopEvents(ConcurrentQueue<(Even foreach (EventWrittenEventArgs requestContentStop in requestContentStops.Select(e => e.Event)) { object payload = Assert.Single(requestContentStop.Payload); - Assert.True(payload is long); - Assert.Equal(requestContentLength.Value, (long)payload); + long contentLength = Assert.IsType(payload); + Assert.Equal(requestContentLength.Value, contentLength); } ValidateSameActivityIds(requestContentStarts, requestContentStops); @@ -479,7 +490,12 @@ private static void ValidateRequestResponseStartStopEvents(ConcurrentQueue<(Even (EventWrittenEventArgs Event, Guid ActivityId)[] responseHeadersStops = events.Where(e => e.Event.EventName == "ResponseHeadersStop").ToArray(); Assert.Equal(count, responseHeadersStops.Length); - Assert.All(responseHeadersStops, r => Assert.Empty(r.Event.Payload)); + foreach (EventWrittenEventArgs responseHeadersStop in responseHeadersStops.Select(e => e.Event)) + { + object payload = Assert.Single(responseHeadersStop.Payload); + int statusCode = Assert.IsType(payload); + Assert.Equal(200, statusCode); + } ValidateSameActivityIds(responseHeadersStarts, responseHeadersStops); diff --git a/src/libraries/System.Net.Http/tests/UnitTests/Fakes/HttpTelemetry.cs b/src/libraries/System.Net.Http/tests/UnitTests/Fakes/HttpTelemetry.cs index 5667687e632e2..26ac057e31bd8 100644 --- a/src/libraries/System.Net.Http/tests/UnitTests/Fakes/HttpTelemetry.cs +++ b/src/libraries/System.Net.Http/tests/UnitTests/Fakes/HttpTelemetry.cs @@ -11,9 +11,9 @@ public class HttpTelemetry public void RequestStart(HttpRequestMessage request) { } - public void RequestStop() { } + public void RequestStop(HttpResponseMessage response) { } - public void RequestFailed() { } + public void RequestFailed(Exception exception) { } public void ResponseContentStart() { } diff --git a/src/libraries/System.Net.Sockets/src/System/Net/Sockets/Socket.Tasks.cs b/src/libraries/System.Net.Sockets/src/System/Net/Sockets/Socket.Tasks.cs index 46fecd795ecd3..d6ce3b64a2cc5 100644 --- a/src/libraries/System.Net.Sockets/src/System/Net/Sockets/Socket.Tasks.cs +++ b/src/libraries/System.Net.Sockets/src/System/Net/Sockets/Socket.Tasks.cs @@ -857,7 +857,7 @@ internal sealed class AwaitableSocketAsyncEventArgs : SocketAsyncEventArgs, IVal /// if it has completed. Another delegate if OnCompleted was called before the operation could complete, /// in which case it's the delegate to invoke when the operation does complete. /// - private Action? _continuation; + private volatile Action? _continuation; private ExecutionContext? _executionContext; private object? _scheduler; /// Current token value given to a ValueTask and then verified against the value it passes back to us. @@ -930,7 +930,7 @@ protected override void OnCompleted(SocketAsyncEventArgs _) /// This instance. public ValueTask AcceptAsync(Socket socket, CancellationToken cancellationToken) { - Debug.Assert(Volatile.Read(ref _continuation) == null, "Expected null continuation to indicate reserved for use"); + Debug.Assert(_continuation == null, "Expected null continuation to indicate reserved for use"); if (socket.AcceptAsync(this, cancellationToken)) { @@ -952,7 +952,7 @@ public ValueTask AcceptAsync(Socket socket, CancellationToken cancellati /// This instance. public ValueTask ReceiveAsync(Socket socket, CancellationToken cancellationToken) { - Debug.Assert(Volatile.Read(ref _continuation) == null, "Expected null continuation to indicate reserved for use"); + Debug.Assert(_continuation == null, "Expected null continuation to indicate reserved for use"); if (socket.ReceiveAsync(this, cancellationToken)) { @@ -972,7 +972,7 @@ public ValueTask ReceiveAsync(Socket socket, CancellationToken cancellation public ValueTask ReceiveFromAsync(Socket socket, CancellationToken cancellationToken) { - Debug.Assert(Volatile.Read(ref _continuation) == null, "Expected null continuation to indicate reserved for use"); + Debug.Assert(_continuation == null, "Expected null continuation to indicate reserved for use"); if (socket.ReceiveFromAsync(this, cancellationToken)) { @@ -993,7 +993,7 @@ public ValueTask ReceiveFromAsync(Socket socket, Cancel public ValueTask ReceiveMessageFromAsync(Socket socket, CancellationToken cancellationToken) { - Debug.Assert(Volatile.Read(ref _continuation) == null, "Expected null continuation to indicate reserved for use"); + Debug.Assert(_continuation == null, "Expected null continuation to indicate reserved for use"); if (socket.ReceiveMessageFromAsync(this, cancellationToken)) { @@ -1018,7 +1018,7 @@ public ValueTask ReceiveMessageFromAsync(Socket /// This instance. public ValueTask SendAsync(Socket socket, CancellationToken cancellationToken) { - Debug.Assert(Volatile.Read(ref _continuation) == null, "Expected null continuation to indicate reserved for use"); + Debug.Assert(_continuation == null, "Expected null continuation to indicate reserved for use"); if (socket.SendAsync(this, cancellationToken)) { @@ -1038,7 +1038,7 @@ public ValueTask SendAsync(Socket socket, CancellationToken cancellationTok public ValueTask SendAsyncForNetworkStream(Socket socket, CancellationToken cancellationToken) { - Debug.Assert(Volatile.Read(ref _continuation) == null, "Expected null continuation to indicate reserved for use"); + Debug.Assert(_continuation == null, "Expected null continuation to indicate reserved for use"); if (socket.SendAsync(this, cancellationToken)) { @@ -1057,7 +1057,7 @@ public ValueTask SendAsyncForNetworkStream(Socket socket, CancellationToken canc public ValueTask SendPacketsAsync(Socket socket, CancellationToken cancellationToken) { - Debug.Assert(Volatile.Read(ref _continuation) == null, "Expected null continuation to indicate reserved for use"); + Debug.Assert(_continuation == null, "Expected null continuation to indicate reserved for use"); if (socket.SendPacketsAsync(this, cancellationToken)) { @@ -1076,7 +1076,7 @@ public ValueTask SendPacketsAsync(Socket socket, CancellationToken cancellationT public ValueTask SendToAsync(Socket socket, CancellationToken cancellationToken) { - Debug.Assert(Volatile.Read(ref _continuation) == null, "Expected null continuation to indicate reserved for use"); + Debug.Assert(_continuation == null, "Expected null continuation to indicate reserved for use"); if (socket.SendToAsync(this, cancellationToken)) { @@ -1096,7 +1096,7 @@ public ValueTask SendToAsync(Socket socket, CancellationToken cancellationT public ValueTask ConnectAsync(Socket socket) { - Debug.Assert(Volatile.Read(ref _continuation) == null, "Expected null continuation to indicate reserved for use"); + Debug.Assert(_continuation == null, "Expected null continuation to indicate reserved for use"); try { @@ -1122,7 +1122,7 @@ public ValueTask ConnectAsync(Socket socket) public ValueTask DisconnectAsync(Socket socket, CancellationToken cancellationToken) { - Debug.Assert(Volatile.Read(ref _continuation) == null, $"Expected null continuation to indicate reserved for use"); + Debug.Assert(_continuation == null, $"Expected null continuation to indicate reserved for use"); if (socket.DisconnectAsync(this, cancellationToken)) { diff --git a/src/libraries/System.Private.CoreLib/src/System/Diagnostics/Tracing/CounterGroup.cs b/src/libraries/System.Private.CoreLib/src/System/Diagnostics/Tracing/CounterGroup.cs index aec84922437a3..77c29cf159801 100644 --- a/src/libraries/System.Private.CoreLib/src/System/Diagnostics/Tracing/CounterGroup.cs +++ b/src/libraries/System.Private.CoreLib/src/System/Diagnostics/Tracing/CounterGroup.cs @@ -52,24 +52,46 @@ private void RegisterCommandCallback() private void OnEventSourceCommand(object? sender, EventCommandEventArgs e) { - if (e.Command == EventCommand.Enable || e.Command == EventCommand.Update) - { - Debug.Assert(e.Arguments != null); + // Should only be enable or disable + Debug.Assert(e.Command == EventCommand.Enable || e.Command == EventCommand.Disable); - if (e.Arguments.TryGetValue("EventCounterIntervalSec", out string? valueStr) && float.TryParse(valueStr, out float value)) + lock (s_counterGroupLock) // Lock the CounterGroup + { + if (e.Command == EventCommand.Enable || e.Command == EventCommand.Update) { - lock (s_counterGroupLock) // Lock the CounterGroup + Debug.Assert(e.Arguments != null); + + if (!e.Arguments.TryGetValue("EventCounterIntervalSec", out string? valueStr) + || !float.TryParse(valueStr, out float intervalValue)) { - EnableTimer(value); + // Command is Enable but no EventCounterIntervalSec arg so ignore + return; } + + EnableTimer(intervalValue); } - } - else if (e.Command == EventCommand.Disable) - { - lock (s_counterGroupLock) + else if (e.Command == EventCommand.Disable) { - DisableTimer(); + // Since we allow sessions to send multiple Enable commands to update the interval, we cannot + // rely on ref counting to determine when to enable and disable counters. You will get an arbitrary + // number of Enables and one Disable per session. + // + // Previously we would turn off counters when we received any Disable command, but that meant that any + // session could turn off counters for all other sessions. To get to a good place we now will only + // turn off counters once the EventSource that provides the counters is disabled. We can then end up + // keeping counters on too long in certain circumstances - if one session enables counters, then a second + // session enables the EventSource but not counters we will stay on until both sessions terminate, even + // if the first session terminates first. + if (!_eventSource.IsEnabled()) + { + DisableTimer(); + } } + + Debug.Assert((s_counterGroupEnabledList == null && !_eventSource.IsEnabled()) + || (_eventSource.IsEnabled() && s_counterGroupEnabledList!.Contains(this)) + || (_pollingIntervalInMilliseconds == 0 && !s_counterGroupEnabledList!.Contains(this)) + || (!_eventSource.IsEnabled() && !s_counterGroupEnabledList!.Contains(this))); } } diff --git a/src/libraries/System.Private.CoreLib/src/System/Diagnostics/Tracing/EventSource.cs b/src/libraries/System.Private.CoreLib/src/System/Diagnostics/Tracing/EventSource.cs index 80c26cc0319b4..f5fe93b02a0ab 100644 --- a/src/libraries/System.Private.CoreLib/src/System/Diagnostics/Tracing/EventSource.cs +++ b/src/libraries/System.Private.CoreLib/src/System/Diagnostics/Tracing/EventSource.cs @@ -2733,9 +2733,6 @@ internal void DoCommand(EventCommandEventArgs commandArgs) m_eventSourceEnabled = true; } - this.OnEventCommand(commandArgs); - this.m_eventCommandExecuted?.Invoke(this, commandArgs); - if (!commandArgs.enable) { // If we are disabling, maybe we can turn on 'quick checks' to filter @@ -2767,6 +2764,9 @@ internal void DoCommand(EventCommandEventArgs commandArgs) m_eventSourceEnabled = false; } } + + this.OnEventCommand(commandArgs); + this.m_eventCommandExecuted?.Invoke(this, commandArgs); } else { diff --git a/src/libraries/System.Security.Cryptography.Xml/tests/SignedXmlTest.cs b/src/libraries/System.Security.Cryptography.Xml/tests/SignedXmlTest.cs index 2eda39d29d86b..89c3c8e907ac2 100644 --- a/src/libraries/System.Security.Cryptography.Xml/tests/SignedXmlTest.cs +++ b/src/libraries/System.Security.Cryptography.Xml/tests/SignedXmlTest.cs @@ -1594,6 +1594,7 @@ public void VerifyHMAC_HMACOutputLength_Invalid() [Theory] [InlineData(false)] [InlineData(true)] + [ActiveIssue("https://github.com/dotnet/runtime/issues/34582", TestPlatforms.Windows, TargetFrameworkMonikers.Netcoreapp, TestRuntimes.Mono)] public void VerifyXmlResolver(bool provideResolver) { HttpListener listener; diff --git a/src/libraries/System.ServiceProcess.ServiceController/src/System.ServiceProcess.ServiceController.csproj b/src/libraries/System.ServiceProcess.ServiceController/src/System.ServiceProcess.ServiceController.csproj index 0484f692b5c80..5ca6ed199bc8a 100644 --- a/src/libraries/System.ServiceProcess.ServiceController/src/System.ServiceProcess.ServiceController.csproj +++ b/src/libraries/System.ServiceProcess.ServiceController/src/System.ServiceProcess.ServiceController.csproj @@ -6,8 +6,8 @@ enable true - false - 0 + true + 1 Provides the System.ServiceProcess.ServiceContainer class, which allows you to connect to a running or stopped service, manipulate it, or get information about it. Commonly Used Types: diff --git a/src/libraries/System.ServiceProcess.ServiceController/src/System/ServiceProcess/ServiceBase.cs b/src/libraries/System.ServiceProcess.ServiceController/src/System/ServiceProcess/ServiceBase.cs index c8dcaa55b8936..782c228a4bb8e 100644 --- a/src/libraries/System.ServiceProcess.ServiceController/src/System/ServiceProcess/ServiceBase.cs +++ b/src/libraries/System.ServiceProcess.ServiceController/src/System/ServiceProcess/ServiceBase.cs @@ -31,6 +31,7 @@ public class ServiceBase : Component private bool _commandPropsFrozen; // set to true once we've use the Can... properties. private bool _disposed; private bool _initialized; + private object _stopLock = new object(); private EventLog? _eventLog; /// @@ -505,27 +506,34 @@ private void DeferredSessionChange(int eventType, int sessionId) // This is a problem when multiple services are hosted in a single process. private unsafe void DeferredStop() { - fixed (SERVICE_STATUS* pStatus = &_status) + lock (_stopLock) { - int previousState = _status.currentState; - - _status.checkPoint = 0; - _status.waitHint = 0; - _status.currentState = ServiceControlStatus.STATE_STOP_PENDING; - SetServiceStatus(_statusHandle, pStatus); - try + // never call SetServiceStatus again after STATE_STOPPED is set. + if (_status.currentState != ServiceControlStatus.STATE_STOPPED) { - OnStop(); - WriteLogEntry(SR.StopSuccessful); - _status.currentState = ServiceControlStatus.STATE_STOPPED; - SetServiceStatus(_statusHandle, pStatus); - } - catch (Exception e) - { - _status.currentState = previousState; - SetServiceStatus(_statusHandle, pStatus); - WriteLogEntry(SR.Format(SR.StopFailed, e), EventLogEntryType.Error); - throw; + fixed (SERVICE_STATUS* pStatus = &_status) + { + int previousState = _status.currentState; + + _status.checkPoint = 0; + _status.waitHint = 0; + _status.currentState = ServiceControlStatus.STATE_STOP_PENDING; + SetServiceStatus(_statusHandle, pStatus); + try + { + OnStop(); + WriteLogEntry(SR.StopSuccessful); + _status.currentState = ServiceControlStatus.STATE_STOPPED; + SetServiceStatus(_statusHandle, pStatus); + } + catch (Exception e) + { + _status.currentState = previousState; + SetServiceStatus(_statusHandle, pStatus); + WriteLogEntry(SR.Format(SR.StopFailed, e), EventLogEntryType.Error); + throw; + } + } } } } @@ -537,14 +545,17 @@ private unsafe void DeferredShutdown() OnShutdown(); WriteLogEntry(SR.ShutdownOK); - if (_status.currentState == ServiceControlStatus.STATE_PAUSED || _status.currentState == ServiceControlStatus.STATE_RUNNING) + lock (_stopLock) { - fixed (SERVICE_STATUS* pStatus = &_status) + if (_status.currentState == ServiceControlStatus.STATE_PAUSED || _status.currentState == ServiceControlStatus.STATE_RUNNING) { - _status.checkPoint = 0; - _status.waitHint = 0; - _status.currentState = ServiceControlStatus.STATE_STOPPED; - SetServiceStatus(_statusHandle, pStatus); + fixed (SERVICE_STATUS* pStatus = &_status) + { + _status.checkPoint = 0; + _status.waitHint = 0; + _status.currentState = ServiceControlStatus.STATE_STOPPED; + SetServiceStatus(_statusHandle, pStatus); + } } } } @@ -672,7 +683,7 @@ private void Initialize(bool multipleServices) { if (!_initialized) { - //Cannot register the service with NT service manatger if the object has been disposed, since finalization has been suppressed. + //Cannot register the service with NT service manager if the object has been disposed, since finalization has been suppressed. if (_disposed) throw new ObjectDisposedException(GetType().Name); @@ -935,8 +946,14 @@ public unsafe void ServiceMainCallback(int argCount, IntPtr argPointer) if (!statusOK) { WriteLogEntry(SR.Format(SR.StartFailed, new Win32Exception().Message), EventLogEntryType.Error); - _status.currentState = ServiceControlStatus.STATE_STOPPED; - SetServiceStatus(_statusHandle, pStatus); + lock (_stopLock) + { + if (_status.currentState != ServiceControlStatus.STATE_STOPPED) + { + _status.currentState = ServiceControlStatus.STATE_STOPPED; + SetServiceStatus(_statusHandle, pStatus); + } + } } } } diff --git a/src/mono/mono/metadata/native-library.c b/src/mono/mono/metadata/native-library.c index f84f2dc8e3061..ab5f643238655 100644 --- a/src/mono/mono/metadata/native-library.c +++ b/src/mono/mono/metadata/native-library.c @@ -518,11 +518,18 @@ netcore_probe_for_module (MonoImage *image, const char *file_name, int flags) // TODO: this algorithm doesn't quite match CoreCLR, so respecting DLLIMPORTSEARCHPATH_LEGACY_BEHAVIOR makes little sense // If the difference becomes a problem, overhaul this algorithm to match theirs exactly + gboolean probe_first_without_prepend = FALSE; + #if defined(HOST_ANDROID) // On Android, try without any path additions first. It is sensitive to probing that will always miss // and lookup for some libraries is required to use a relative path - module = netcore_probe_for_module_variations (NULL, file_name, lflags); + probe_first_without_prepend = TRUE; +#else + if (file_name != NULL && g_path_is_absolute (file_name)) + probe_first_without_prepend = TRUE; #endif + if (module == NULL && probe_first_without_prepend) + module = netcore_probe_for_module_variations (NULL, file_name, lflags); // Check the NATIVE_DLL_SEARCH_DIRECTORIES for (int i = 0; i < pinvoke_search_directories_count && module == NULL; ++i) @@ -537,13 +544,11 @@ netcore_probe_for_module (MonoImage *image, const char *file_name, int flags) g_free (mdirname); } -#if !defined(HOST_ANDROID) - // Try without any path additions - if (module == NULL) + // Try without any path additions, if we didn't try it already + if (module == NULL && !probe_first_without_prepend) { module = netcore_probe_for_module_variations (NULL, file_name, lflags); } -#endif // TODO: Pass remaining flags on to LoadLibraryEx on Windows where appropriate, see https://docs.microsoft.com/en-us/dotnet/api/system.runtime.interopservices.dllimportsearchpath?view=netcore-3.1 diff --git a/src/mono/wasm/debugger/BrowserDebugProxy/DevToolsProxy.cs b/src/mono/wasm/debugger/BrowserDebugProxy/DevToolsProxy.cs index ed40b0f1049a4..7411024a0802c 100644 --- a/src/mono/wasm/debugger/BrowserDebugProxy/DevToolsProxy.cs +++ b/src/mono/wasm/debugger/BrowserDebugProxy/DevToolsProxy.cs @@ -340,9 +340,9 @@ public async Task Run(Uri browserUri, WebSocket ideSocket) } catch (Exception e) { - Log("error", $"DevToolsProxy::Run: Exception {e}"); + if (e.InnerException is null || e.InnerException is not System.Net.WebSockets.WebSocketException) + Log("error", $"DevToolsProxy::Run: Exception {e}"); _channelWriter.Complete(e); - //throw; } finally { diff --git a/src/native/corehost/apphost/static/CMakeLists.txt b/src/native/corehost/apphost/static/CMakeLists.txt index a00c79139863f..6d491c086da98 100644 --- a/src/native/corehost/apphost/static/CMakeLists.txt +++ b/src/native/corehost/apphost/static/CMakeLists.txt @@ -73,8 +73,8 @@ if(CLR_CMAKE_TARGET_WIN32) add_linker_flag("/DEF:${CMAKE_CURRENT_SOURCE_DIR}/singlefilehost.def") else() - if(CLR_CMAKE_TARGET_OSX) - set(DEF_SOURCES ${CMAKE_CURRENT_SOURCE_DIR}/singlefilehost_OSXexports.src) + if(CLR_CMAKE_TARGET_FREEBSD) + set(DEF_SOURCES ${CMAKE_CURRENT_SOURCE_DIR}/singlefilehost_freebsdexports.src) else() set(DEF_SOURCES ${CMAKE_CURRENT_SOURCE_DIR}/singlefilehost_unixexports.src) endif() diff --git a/src/native/corehost/apphost/static/singlefilehost_OSXexports.src b/src/native/corehost/apphost/static/singlefilehost_freebsdexports.src similarity index 81% rename from src/native/corehost/apphost/static/singlefilehost_OSXexports.src rename to src/native/corehost/apphost/static/singlefilehost_freebsdexports.src index 18d5697e84580..767c9546a3b47 100644 --- a/src/native/corehost/apphost/static/singlefilehost_OSXexports.src +++ b/src/native/corehost/apphost/static/singlefilehost_freebsdexports.src @@ -9,3 +9,7 @@ g_dacTable ; Used by profilers MetaDataGetDispenser + +; FreeBSD needs to reexport these +__progname +environ diff --git a/src/native/corehost/apphost/static/singlefilehost_unixexports.src b/src/native/corehost/apphost/static/singlefilehost_unixexports.src index 1f9c517821855..18d5697e84580 100644 --- a/src/native/corehost/apphost/static/singlefilehost_unixexports.src +++ b/src/native/corehost/apphost/static/singlefilehost_unixexports.src @@ -9,7 +9,3 @@ g_dacTable ; Used by profilers MetaDataGetDispenser - -; FreeBSD needs to reexport these -__progname -environ diff --git a/src/tests/issues.targets b/src/tests/issues.targets index 81567b4e08042..3bb40e41b8c21 100644 --- a/src/tests/issues.targets +++ b/src/tests/issues.targets @@ -2409,6 +2409,9 @@ https://github.com/dotnet/runtime/issues/41193 + + Loads an assembly from file + https://github.com/dotnet/runtime/issues/41519