* JIT: [Just-in-Time](https://github.com/dotnet/coreclr/blob/master/Documentation/botr/ryujit-overview.md) compiler. RyuJIT is the code name for the next generation Just-in-Time(aka "JIT") for the .NET runtime.
* LCG: Lightweight Code Generation. An early name for [dynamic methods](https://github.com/dotnet/coreclr/blob/master/src/mscorlib/src/System/Reflection/Emit/DynamicMethod.cs).
* NGen: Native Image Generator.
+* NYI: Not Yet Implemented
* PAL: [Platform Adaptation Layer](http://archive.oreilly.com/pub/a/dotnet/2002/03/04/rotor.html). Provides an abstraction layer between the runtime and the operating system
* PE: Portable Executable.
* ProjectN: Codename for the first version of [.NET Native for UWP](https://msdn.microsoft.com/en-us/vstudio/dotnetnative.aspx).
* Redhawk: Codename for experimental minimal managed code runtime that evolved into [CoreRT](https://github.com/dotnet/corert/).
* SOS: [Son of Strike](http://blogs.msdn.com/b/jasonz/archive/2003/10/21/53581.aspx). The debugging extension for DbgEng based debuggers. Uses the DAC as an abstraction layer for its operation.
* SVR: The CLR used to be built as two variants, with one called "mscorsvr.dll", to mean the "server" version. In particular, it contained the server GC implementation, which was intended for multi-threaded apps capable of taking advantage of multiple processors. In the .NET Framework 2 release, the two variants were merged into "mscorwks.dll". The WKS version was the default, however the SVR version remained available.
+* TPA: Trusted Platform Assemblies used to be a special set of assemblies that comprised the platform assemblies, when it was originally designed. As of today, it is simply the set of assemblies known to constitute the application.
* URT: Universal Runtime. Ancient name for what ended up being .NET, is used in the WinError facility name FACILITY_URT.
* VSD: [Virtual Stub Dispatch](../botr/virtual-stub-dispatch.md). Technique of using stubs for virtual method invocations instead of the traditional virtual method table.
* VM: Virtual machine.
## What Can you Make from this Repository?
-.NET Core relies heavily on the [Nuget](https://en.wikipedia.org/wiki/NuGet) package manager
-which is system to package, distribute and version software components. See [https://www.nuget.org/](https://www.nuget.org/)
+.NET Core relies heavily on the [Nuget](https://en.wikipedia.org/wiki/NuGet) package manager,
+which is a system to package, distribute and version software components. See [https://www.nuget.org/](https://www.nuget.org/)
for more information on Nuget. For now it is enough to know Nuget is a system that
bundles components into `*.nupkg` files (which are ZIP archives) and these packages can be 'published'
either through a local file system path or by a URL (e.g. https://www.nuget.org/). There are then tools
how to search these publishing locations and pull down consistent set of packages for the
application.
-In a concrete terms, this repository is best thought of as the source code for the following Nuget package
+In concrete terms, this repository is best thought of as the source code for the following Nuget package
* **Microsoft.NETCore.Runtime.CoreCLR** - Represents the object allocator, garbage collector (GC), class
loader, type system, interop and the most fundamental parts of the .NET class library (e.g.
* **Microsoft.NETCore.TestHost** - This contains the corehost.exe program, which is a small wrapper
that uses the .NET Runtime to run IL DLLs passed to it on the command line.
* **Microsoft.TargetingPack.Private.CoreCLR** - A set of assemblies that represent the compile time surface
- area of class library implemented by the runtime itself.
+ area of the class library implemented by the runtime itself.
## Relationship with the [CoreFX](https://github.com/dotnet/corefx) Repository
to the (private) implementation in System.Private.CoreLib.dll defined here.
For example the *System.Runtime* package defined in CoreFX declares the PUBLIC name for types like
System.Object and System.String. Thus from an applications point of view these types live in System.Runtime.dll.
-However System.Runtime.dll (defined in the CoreFX repo) forwards references ultimately to System.Private.CoreLib.dll
+However, System.Runtime.dll (defined in the CoreFX repo) forwards references ultimately to System.Private.CoreLib.dll
which is defined here.
Thus in order to run an application, you need BOTH the Microsoft.NETCore.Runtime.CoreCLR Nuget package
-(defined in this repository) as well as packages for whatever you actually references that were defined
+(defined in this repository) as well as packages for whatever you actually reference that were defined
in the CoreFX repository (which at a minimum includes the System.Runtime package). You also need some
sort of 'host' executable that loads the CoreCLR package as well as the CoreFX packages and starts your code (typically
you use dotnet.exe for this).
These extra pieces are not defined here, however you don't need to build them in order to use the CoreCLR
Nuget package you create here. There are already versions of the CoreFX packages published on
-https://www.nuget.org/ so you can just have your test application's project.json specify the CoreCLR you
-built it will naturally pull anything else it needs from the official location https://www.nuget.org/ to
+https://www.nuget.org/ so you can have your test application's project.json specify the CoreCLR you
+built and it will naturally pull anything else it needs from the official location https://www.nuget.org/ to
make a complete application. More on this in the [Using Your Build](Documentation/workflow/UsingYourBuild.md) page.
--------------------------
can be difficult to debug. Passing 'release' to the build script select this.
In addition, by default the build will not only create the runtime executables, but it will also
-build all the tests. There are quit a few tests so this does take a significant amount of time
-that is not necessary if you are just want to experiment with changes. You can submit the building
+build all the tests. There are quite a few tests so this does take a significant amount of time
+that is not necessary if you want to experiment with changes. You can submit the building
of the tests with the 'skiptests' argument to the build script.
Thus to get a build as quickly as possible type the following (using \ as the directory separator, use / on Unix machines)
* bin\Product\Windows_NT.x64.Release\.nuget\pkg
-directory. These packages are the 'output' of your build.
+These packages are the 'output' of your build.
There are two basic techniques for using your new runtime.
exit 1
}
-initDistroRid()
+initHostDistroRid()
{
- if [ "$__BuildOS" == "Linux" ]; then
+ if [ "$__HostOS" == "Linux" ]; then
if [ ! -e /etc/os-release ]; then
echo "WARNING: Can not determine runtime id for current distro."
- export __DistroRid=""
+ __HostDistroRid=""
else
source /etc/os-release
- export __DistroRid="$ID.$VERSION_ID-$__HostArch"
+ __HostDistroRid="$ID.$VERSION_ID-$__HostArch"
fi
fi
}
+initTargetDistroRid()
+{
+ if [ $__CrossBuild == 1 ]; then
+ if [ "$__BuildOS" == "Linux" ]; then
+ if [ ! -e $ROOTFS_DIR/etc/os-release ]; then
+ echo "WARNING: Can not determine runtime id for current distro."
+ export __DistroRid=""
+ else
+ source $ROOTFS_DIR/etc/os-release
+ export __DistroRid="$ID.$VERSION_ID-$__BuildArch"
+ fi
+ fi
+ else
+ export __DistroRid="$__HostDistroRid"
+ fi
+}
+
setup_dirs()
{
echo Setting up directories for build
if [ $__SkipConfigure == 0 ]; then
# if msbuild is not supported, then set __SkipGenerateVersion to 1
if [ $__isMSBuildOnNETCoreSupported == 0 ]; then __SkipGenerateVersion=1; fi
- # Drop version.c file
+ # Drop version.cpp file
__versionSourceFile=$__IntermediatesDir/version.cpp
if [ $__SkipGenerateVersion == 0 ]; then
"$__ProjectRoot/run.sh" build -Project=$__ProjectDir/build.proj -generateHeaderUnix -NativeVersionSourceFile=$__versionSourceFile $__RunArgs $__UnprocessedBuildArgs
else
+ # Generate the dummy version.cpp, but only if it didn't exist to make sure we don't trigger unnecessary rebuild
__versionSourceLine="static char sccsid[] __attribute__((used)) = \"@(#)No version information produced\";"
- echo $__versionSourceLine > $__versionSourceFile
+ if [ -e $__versionSourceFile ]; then
+ read existingVersionSourceLine < $__versionSourceFile
+ fi
+ if [ "$__versionSourceLine" != "$existingVersionSourceLine" ]; then
+ echo $__versionSourceLine > $__versionSourceFile
+ fi
fi
- pushd "$__IntermediatesDir"
+ pushd "$__IntermediatesDir"
# Regenerate the CMake solution
__ExtraCmakeArgs="-DCLR_CMAKE_TARGET_OS=$__BuildOS -DCLR_CMAKE_PACKAGES_DIR=$__PackagesDir -DCLR_CMAKE_PGO_INSTRUMENT=$__PgoInstrument"
echo "Invoking \"$__ProjectRoot/src/pal/tools/gen-buildsys-clang.sh\" \"$__ProjectRoot\" $__ClangMajorVersion $__ClangMinorVersion $__BuildArch $__BuildType $__CodeCoverage $__IncludeTests $generator $__ExtraCmakeArgs $__cmakeargs"
if [ "$__HostArch" == "x64" ]; then
if [ "$__HostOS" == "Linux" ]; then
- case "$__DistroRid" in
+ case "$__HostDistroRid" in
"centos.7-x64")
__isMSBuildOnNETCoreSupported=1
;;
__ClangMajorVersion=0
__ClangMinorVersion=0
__NuGetPath="$__PackagesDir/NuGet.exe"
+__HostDistroRid=""
__DistroRid=""
__cmakeargs=""
__SkipGenerateVersion=0
# Set dependent variables
__LogsDir="$__RootBinDir/Logs"
-# init the distro name
-initDistroRid
+# init the host distro name
+initHostDistroRid
# Set the remaining variables based upon the determined build configuration
__BinDir="$__RootBinDir/Product/$__BuildOS.$__BuildArch.$__BuildType"
fi
fi
+# init the target distro name
+initTargetDistroRid
+
# Make the directories necessary for build if they don't exist
setup_dirs
endif(NOT CMAKE_SYSTEM_NAME STREQUAL NetBSD)
add_definitions(-DFEATURE_HOST_ASSEMBLY_RESOLVER)
add_definitions(-DFEATURE_ICASTABLE)
+if (WIN32 AND (CLR_CMAKE_TARGET_ARCH_AMD64 OR CLR_CMAKE_TARGET_ARCH_I386))
+add_definitions(-DFEATURE_INTEROP_DEBUGGING)
+endif (WIN32 AND (CLR_CMAKE_TARGET_ARCH_AMD64 OR CLR_CMAKE_TARGET_ARCH_I386))
if (CLR_CMAKE_PLATFORM_UNIX OR CLR_CMAKE_TARGET_ARCH_ARM64)
add_definitions(-DFEATURE_IMPLICIT_TLS)
set(FEATURE_IMPLICIT_TLS 1)
<Project ToolsVersion="12.0" DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<!-- Source of truth for dependency tooling: the commit hash of the dotnet/versions master branch as of the last auto-upgrade. -->
<PropertyGroup>
- <CoreFxCurrentRef>e222c0b56c6f5b852d033473f6c2facf37219331</CoreFxCurrentRef>
- <CoreClrCurrentRef>e222c0b56c6f5b852d033473f6c2facf37219331</CoreClrCurrentRef>
+ <CoreFxCurrentRef>789bedf73cf114afe26a354d6a8e642e9678de80</CoreFxCurrentRef>
+ <CoreClrCurrentRef>789bedf73cf114afe26a354d6a8e642e9678de80</CoreClrCurrentRef>
</PropertyGroup>
<!-- Auto-upgraded properties for each build info dependency. -->
<PropertyGroup>
- <CoreFxExpectedPrerelease>beta-24721-02</CoreFxExpectedPrerelease>
+ <CoreFxExpectedPrerelease>beta-24810-02</CoreFxExpectedPrerelease>
</PropertyGroup>
<!-- Full package version strings that are used in other parts of the build. -->
<PropertyGroup>
- <CoreClrPackageVersion>1.2.0-beta-24801-03</CoreClrPackageVersion>
+ <CoreClrPackageVersion>1.2.0-beta-24810-01</CoreClrPackageVersion>
<XunitPackageVersion>2.2.0-beta2-build3300</XunitPackageVersion>
</PropertyGroup>
[true, false].each { isPR ->
['Windows_NT'].each { os ->
['x64'].each { architecture ->
- def configuration = 'Release'
- def runType = isPR ? 'private' : 'rolling'
- def benchViewName = isPR ? 'coreclr private %ghprbPullTitle%' : 'coreclr rolling %GIT_BRANCH_WITHOUT_ORIGIN% %GIT_COMMIT%'
def newJob = job(Utilities.getFullJobName(project, "perf_perflab_${os}", isPR)) {
// Set the label.
label('windows_clr_perf')
}
}
+ if (isPR)
+ {
+ parameters
+ {
+ stringParam('BenchviewCommitName', '%ghprbPullTitle%', 'The name that you will be used to build the full title of a run in Benchview. The final name will be of the form <branch> private BenchviewCommitName')
+ }
+ }
+ def configuration = 'Release'
+ def runType = isPR ? 'private' : 'rolling'
+ def benchViewName = isPR ? 'coreclr private %BenchviewCommitName%' : 'coreclr rolling %GIT_BRANCH_WITHOUT_ORIGIN% %GIT_COMMIT%'
+
steps {
// Batch
// Create the Linux/OSX/CentOS coreclr test leg for debug and release and each scenario
[true, false].each { isPR ->
['Ubuntu14.04'].each { os ->
- def osGroup = getOSGroup(os)
- def architecture = 'x64'
- def configuration = 'Release'
- def runType = isPR ? 'private' : 'rolling'
- def benchViewName = isPR ? 'coreclr private \$ghprbPullTitle' : 'coreclr rolling \$GIT_BRANCH_WITHOUT_ORIGIN \$GIT_COMMIT'
def newJob = job(Utilities.getFullJobName(project, "perf_${os}", isPR)) {
label('linux_clr_perf')
}
}
+ if (isPR)
+ {
+ parameters
+ {
+ stringParam('BenchviewCommitName', '\$ghprbPullTitle', 'The name that you will be used to build the full title of a run in Benchview. The final name will be of the form <branch> private BenchviewCommitName')
+ }
+ }
+ def osGroup = getOSGroup(os)
+ def architecture = 'x64'
+ def configuration = 'Release'
+ def runType = isPR ? 'private' : 'rolling'
+ def benchViewName = isPR ? 'coreclr private \$BenchviewCommitName' : 'coreclr rolling \$GIT_BRANCH_WITHOUT_ORIGIN \$GIT_COMMIT'
+
steps {
shell("bash ./tests/scripts/perf-prep.sh")
shell("./init-tools.sh")
<OSGroup>Linux</OSGroup>
<Platform>amd64</Platform>
</Project>
+ <Project Condition="'$(TargetsLinux)' == 'true' and '$(DistroRid)' == 'ubuntu.14.04-arm'" Include="ubuntu/14.04/Microsoft.NETCore.ILAsm.pkgproj">
+ <OSGroup>Linux</OSGroup>
+ <Platform>arm</Platform>
+ </Project>
<Project Condition="'$(TargetsLinux)' == 'true' and '$(DistroRid)' == 'ubuntu.16.04-x64'" Include="ubuntu/16.04/Microsoft.NETCore.ILAsm.pkgproj">
<OSGroup>Linux</OSGroup>
<Platform>amd64</Platform>
</Project>
+ <Project Condition="'$(TargetsLinux)' == 'true' and '$(DistroRid)' == 'ubuntu.16.04-arm'" Include="ubuntu/16.04/Microsoft.NETCore.ILAsm.pkgproj">
+ <OSGroup>Linux</OSGroup>
+ <Platform>arm</Platform>
+ </Project>
<Project Condition="'$(TargetsLinux)' == 'true' and '$(DistroRid)' == 'ubuntu.16.10-x64'" Include="ubuntu/16.10/Microsoft.NETCore.ILAsm.pkgproj">
<OSGroup>Linux</OSGroup>
<Platform>amd64</Platform>
<ProjectReference Include="ubuntu\14.04\Microsoft.NETCore.ILAsm.pkgproj">
<Platform>amd64</Platform>
</ProjectReference>
+ <ProjectReference Include="ubuntu\14.04\Microsoft.NETCore.ILAsm.pkgproj">
+ <Platform>arm</Platform>
+ </ProjectReference>
<ProjectReference Include="ubuntu\16.04\Microsoft.NETCore.ILAsm.pkgproj">
<Platform>amd64</Platform>
</ProjectReference>
+ <ProjectReference Include="ubuntu\16.04\Microsoft.NETCore.ILAsm.pkgproj">
+ <Platform>arm</Platform>
+ </ProjectReference>
<ProjectReference Include="ubuntu\16.10\Microsoft.NETCore.ILAsm.pkgproj">
<Platform>amd64</Platform>
</ProjectReference>
</ProjectReference>
</ItemGroup>
<Import Project="$([MSBuild]::GetDirectoryNameOfFileAbove($(MSBuildThisFileDirectory), dir.targets))\dir.targets" />
-</Project>
\ No newline at end of file
+</Project>
<PropertyGroup>
<SkipPackageFileCheck>true</SkipPackageFileCheck>
<PackageTargetRuntime>ubuntu.14.04-$(PackagePlatform)</PackageTargetRuntime>
- <!-- only build for x64 -->
- <PackagePlatforms>x64;</PackagePlatforms>
+ <!-- build for x64, arm -->
+ <PackagePlatforms>x64;arm;</PackagePlatforms>
</PropertyGroup>
<ItemGroup>
<NativeSplittableBinary Include="$(BinDir)ilasm" />
</File>
</ItemGroup>
<Import Project="$([MSBuild]::GetDirectoryNameOfFileAbove($(MSBuildThisFileDirectory), dir.targets))\dir.targets" />
-</Project>
\ No newline at end of file
+</Project>
<PropertyGroup>
<SkipPackageFileCheck>true</SkipPackageFileCheck>
<PackageTargetRuntime>ubuntu.16.04-$(PackagePlatform)</PackageTargetRuntime>
- <!-- only build for x64 -->
- <PackagePlatforms>x64;</PackagePlatforms>
+ <!-- build for x64, arm -->
+ <PackagePlatforms>x64;arm;</PackagePlatforms>
</PropertyGroup>
<ItemGroup>
<NativeSplittableBinary Include="$(BinDir)ilasm" />
</File>
</ItemGroup>
<Import Project="$([MSBuild]::GetDirectoryNameOfFileAbove($(MSBuildThisFileDirectory), dir.targets))\dir.targets" />
-</Project>
\ No newline at end of file
+</Project>
<OSGroup>Linux</OSGroup>
<Platform>amd64</Platform>
</Project>
+ <Project Condition="'$(TargetsLinux)' == 'true' and '$(DistroRid)' == 'ubuntu.14.04-arm'" Include="ubuntu/14.04/Microsoft.NETCore.ILDAsm.pkgproj">
+ <OSGroup>Linux</OSGroup>
+ <Platform>arm</Platform>
+ </Project>
<Project Condition="'$(TargetsLinux)' == 'true' and '$(DistroRid)' == 'ubuntu.16.04-x64'" Include="ubuntu/16.04/Microsoft.NETCore.ILDAsm.pkgproj">
<OSGroup>Linux</OSGroup>
<Platform>amd64</Platform>
</Project>
+ <Project Condition="'$(TargetsLinux)' == 'true' and '$(DistroRid)' == 'ubuntu.16.04-arm'" Include="ubuntu/16.04/Microsoft.NETCore.ILDAsm.pkgproj">
+ <OSGroup>Linux</OSGroup>
+ <Platform>arm</Platform>
+ </Project>
<Project Condition="'$(TargetsLinux)' == 'true' and '$(DistroRid)' == 'ubuntu.16.10-x64'" Include="ubuntu/16.10/Microsoft.NETCore.ILDAsm.pkgproj">
<OSGroup>Linux</OSGroup>
<Platform>amd64</Platform>
<ProjectReference Include="ubuntu\14.04\Microsoft.NETCore.ILDAsm.pkgproj">
<Platform>amd64</Platform>
</ProjectReference>
+ <ProjectReference Include="ubuntu\14.04\Microsoft.NETCore.ILDAsm.pkgproj">
+ <Platform>arm</Platform>
+ </ProjectReference>
<ProjectReference Include="ubuntu\16.04\Microsoft.NETCore.ILDAsm.pkgproj">
<Platform>amd64</Platform>
</ProjectReference>
+ <ProjectReference Include="ubuntu\16.04\Microsoft.NETCore.ILDAsm.pkgproj">
+ <Platform>arm</Platform>
+ </ProjectReference>
<ProjectReference Include="ubuntu\16.10\Microsoft.NETCore.ILDAsm.pkgproj">
<Platform>amd64</Platform>
</ProjectReference>
</ProjectReference>
</ItemGroup>
<Import Project="$([MSBuild]::GetDirectoryNameOfFileAbove($(MSBuildThisFileDirectory), dir.targets))\dir.targets" />
-</Project>
\ No newline at end of file
+</Project>
<PropertyGroup>
<SkipPackageFileCheck>true</SkipPackageFileCheck>
<PackageTargetRuntime>ubuntu.14.04-$(PackagePlatform)</PackageTargetRuntime>
- <!-- only build for x64 -->
- <PackagePlatforms>x64;</PackagePlatforms>
+ <!-- build for x64, arm -->
+ <PackagePlatforms>x64;arm;</PackagePlatforms>
</PropertyGroup>
<ItemGroup>
<NativeSplittableBinary Include="$(BinDir)ildasm" />
</File>
</ItemGroup>
<Import Project="$([MSBuild]::GetDirectoryNameOfFileAbove($(MSBuildThisFileDirectory), dir.targets))\dir.targets" />
-</Project>
\ No newline at end of file
+</Project>
<PropertyGroup>
<SkipPackageFileCheck>true</SkipPackageFileCheck>
<PackageTargetRuntime>ubuntu.16.04-$(PackagePlatform)</PackageTargetRuntime>
- <!-- only build for x64 -->
- <PackagePlatforms>x64;</PackagePlatforms>
+ <!-- build for x64, arm -->
+ <PackagePlatforms>x64;arm;</PackagePlatforms>
</PropertyGroup>
<ItemGroup>
<NativeSplittableBinary Include="$(BinDir)ildasm" />
</File>
</ItemGroup>
<Import Project="$([MSBuild]::GetDirectoryNameOfFileAbove($(MSBuildThisFileDirectory), dir.targets))\dir.targets" />
-</Project>
\ No newline at end of file
+</Project>
<OSGroup>Linux</OSGroup>
<Platform>amd64</Platform>
</Project>
+ <Project Condition="'$(TargetsLinux)' == 'true' and '$(DistroRid)' == 'ubuntu.14.04-arm'" Include="ubuntu/14.04/Microsoft.NETCore.Jit.pkgproj">
+ <OSGroup>Linux</OSGroup>
+ <Platform>arm</Platform>
+ </Project>
<Project Condition="'$(TargetsLinux)' == 'true' and '$(DistroRid)' == 'ubuntu.16.04-x64'" Include="ubuntu/16.04/Microsoft.NETCore.Jit.pkgproj">
<OSGroup>Linux</OSGroup>
<Platform>amd64</Platform>
</Project>
+ <Project Condition="'$(TargetsLinux)' == 'true' and '$(DistroRid)' == 'ubuntu.16.04-arm'" Include="ubuntu/16.04/Microsoft.NETCore.Jit.pkgproj">
+ <OSGroup>Linux</OSGroup>
+ <Platform>arm</Platform>
+ </Project>
<Project Condition="'$(TargetsLinux)' == 'true' and '$(DistroRid)' == 'ubuntu.16.10-x64'" Include="ubuntu/16.10/Microsoft.NETCore.Jit.pkgproj">
<OSGroup>Linux</OSGroup>
<Platform>amd64</Platform>
<ProjectReference Include="ubuntu\14.04\Microsoft.NETCore.Jit.pkgproj">
<Platform>amd64</Platform>
</ProjectReference>
+ <ProjectReference Include="ubuntu\14.04\Microsoft.NETCore.Jit.pkgproj">
+ <Platform>arm</Platform>
+ </ProjectReference>
<ProjectReference Include="ubuntu\16.04\Microsoft.NETCore.Jit.pkgproj">
<Platform>amd64</Platform>
</ProjectReference>
+ <ProjectReference Include="ubuntu\16.04\Microsoft.NETCore.Jit.pkgproj">
+ <Platform>arm</Platform>
+ </ProjectReference>
<ProjectReference Include="ubuntu\16.10\Microsoft.NETCore.Jit.pkgproj">
<Platform>amd64</Platform>
</ProjectReference>
</ProjectReference>
</ItemGroup>
<Import Project="$([MSBuild]::GetDirectoryNameOfFileAbove($(MSBuildThisFileDirectory), dir.targets))\dir.targets" />
-</Project>
\ No newline at end of file
+</Project>
<PropertyGroup>
<SkipPackageFileCheck>true</SkipPackageFileCheck>
<PackageTargetRuntime>ubuntu.14.04-$(PackagePlatform)</PackageTargetRuntime>
- <!-- only build for x64 -->
- <PackagePlatforms>x64;</PackagePlatforms>
+ <!-- build for x64, arm -->
+ <PackagePlatforms>x64;arm;</PackagePlatforms>
</PropertyGroup>
<ItemGroup>
<NativeSplittableBinary Include="$(BinDir)libclrjit.so" />
</File>
</ItemGroup>
<Import Project="$([MSBuild]::GetDirectoryNameOfFileAbove($(MSBuildThisFileDirectory), dir.targets))\dir.targets" />
-</Project>
\ No newline at end of file
+</Project>
<PropertyGroup>
<SkipPackageFileCheck>true</SkipPackageFileCheck>
<PackageTargetRuntime>ubuntu.16.04-$(PackagePlatform)</PackageTargetRuntime>
- <!-- only build for x64 -->
- <PackagePlatforms>x64;</PackagePlatforms>
+ <!-- build for x64, arm -->
+ <PackagePlatforms>x64;arm;</PackagePlatforms>
</PropertyGroup>
<ItemGroup>
<NativeSplittableBinary Include="$(BinDir)libclrjit.so" />
</File>
</ItemGroup>
<Import Project="$([MSBuild]::GetDirectoryNameOfFileAbove($(MSBuildThisFileDirectory), dir.targets))\dir.targets" />
-</Project>
\ No newline at end of file
+</Project>
<!-- This property must be set to the same value as $(PackageOutputPath) for the nuspecs and nupkgs to be binplaced to the intended location. -->
<OutputPath>$(PackageOutputPath)</OutputPath>
</PropertyGroup>
-
<!-- We always build the identity/redirection package. However, the platform specific runtime-*.nupkg is built based upon the target OS we are building the product for. -->
<ItemGroup>
<Project Include="Microsoft.NETCore.Runtime.CoreCLR.pkgproj">
<OSGroup>Linux</OSGroup>
<Platform>amd64</Platform>
</Project>
+ <Project Condition="'$(TargetsLinux)' == 'true' and '$(DistroRid)' == 'ubuntu.14.04-arm'" Include="ubuntu/14.04/Microsoft.NETCore.Runtime.CoreCLR.pkgproj">
+ <OSGroup>Linux</OSGroup>
+ <Platform>arm</Platform>
+ </Project>
<Project Condition="'$(TargetsLinux)' == 'true' and '$(DistroRid)' == 'ubuntu.16.04-x64'" Include="ubuntu/16.04/Microsoft.NETCore.Runtime.CoreCLR.pkgproj">
<OSGroup>Linux</OSGroup>
<Platform>amd64</Platform>
</Project>
+ <Project Condition="'$(TargetsLinux)' == 'true' and '$(DistroRid)' == 'ubuntu.16.04-arm'" Include="ubuntu/16.04/Microsoft.NETCore.Runtime.CoreCLR.pkgproj">
+ <OSGroup>Linux</OSGroup>
+ <Platform>arm</Platform>
+ </Project>
<Project Condition="'$(TargetsLinux)' == 'true' and '$(DistroRid)' == 'ubuntu.16.10-x64'" Include="ubuntu/16.10/Microsoft.NETCore.Runtime.CoreCLR.pkgproj">
<OSGroup>Linux</OSGroup>
<Platform>amd64</Platform>
<ProjectReference Include="ubuntu\14.04\Microsoft.NETCore.Runtime.CoreCLR.pkgproj">
<Platform>amd64</Platform>
</ProjectReference>
+ <ProjectReference Include="ubuntu\14.04\Microsoft.NETCore.Runtime.CoreCLR.pkgproj">
+ <Platform>arm</Platform>
+ </ProjectReference>
<ProjectReference Include="ubuntu\16.04\Microsoft.NETCore.Runtime.CoreCLR.pkgproj">
<Platform>amd64</Platform>
</ProjectReference>
+ <ProjectReference Include="ubuntu\16.04\Microsoft.NETCore.Runtime.CoreCLR.pkgproj">
+ <Platform>arm</Platform>
+ </ProjectReference>
<ProjectReference Include="ubuntu\16.10\Microsoft.NETCore.Runtime.CoreCLR.pkgproj">
<Platform>amd64</Platform>
</ProjectReference>
</ProjectReference>
</ItemGroup>
<Import Project="$([MSBuild]::GetDirectoryNameOfFileAbove($(MSBuildThisFileDirectory), dir.targets))\dir.targets" />
-</Project>
\ No newline at end of file
+</Project>
<PropertyGroup>
<SkipPackageFileCheck>true</SkipPackageFileCheck>
<PackageTargetRuntime>ubuntu.14.04-$(PackagePlatform)</PackageTargetRuntime>
- <!-- only build for x64 -->
- <PackagePlatforms>x64;</PackagePlatforms>
+ <!-- build for x64, arm -->
+ <PackagePlatforms>x64;arm;</PackagePlatforms>
</PropertyGroup>
<ItemGroup>
<NativeSplittableBinary Include="$(BinDir)libcoreclr.so" />
- <NativeSplittableBinary Include="$(BinDir)libcoreclrtraceptprovider.so" />
+ <NativeSplittableBinary Condition="'$(PackagePlatform)' != 'arm'" Include="$(BinDir)libcoreclrtraceptprovider.so" />
<NativeSplittableBinary Include="$(BinDir)libdbgshim.so" />
<NativeSplittableBinary Include="$(BinDir)libmscordaccore.so" />
<NativeSplittableBinary Include="$(BinDir)libmscordbi.so" />
<NativeSplittableBinary Include="$(BinDir)libsosplugin.so" />
<NativeSplittableBinary Include="$(BinDir)System.Globalization.Native.so" />
<ArchitectureSpecificNativeFile Include="$(BinDir)sosdocsunix.txt" />
- <ArchitectureSpecificNativeFile Include="$(BinDir)mscorlib.ni.dll" />
- <ArchitectureSpecificNativeFile Include="$(BinDir)System.Private.CoreLib.ni.dll" />
+ <ArchitectureSpecificNativeFile Condition="'$(PackagePlatform)'!='arm'" Include="$(BinDir)mscorlib.ni.dll" />
+ <ArchitectureSpecificNativeFile Condition="'$(PackagePlatform)'!='arm'" Include="$(BinDir)System.Private.CoreLib.ni.dll" />
<ArchitectureSpecificLibFile Include="$(BinDir)System.Private.CoreLib.dll" />
<ArchitectureSpecificLibFile Include="$(BinDir)mscorlib.dll" />
<ArchitectureSpecificLibFile Include="$(BinDir)SOS.NETCore.dll" />
<PropertyGroup>
<SkipPackageFileCheck>true</SkipPackageFileCheck>
<PackageTargetRuntime>ubuntu.16.04-$(PackagePlatform)</PackageTargetRuntime>
- <!-- only build for x64 -->
- <PackagePlatforms>x64;</PackagePlatforms>
+ <!-- build for x64, arm -->
+ <PackagePlatforms>x64;arm;</PackagePlatforms>
</PropertyGroup>
<ItemGroup>
<NativeSplittableBinary Include="$(BinDir)libcoreclr.so" />
- <NativeSplittableBinary Include="$(BinDir)libcoreclrtraceptprovider.so" />
+ <NativeSplittableBinary Condition="'$(PackagePlatform)' != 'arm'" Include="$(BinDir)libcoreclrtraceptprovider.so" />
<NativeSplittableBinary Include="$(BinDir)libdbgshim.so" />
<NativeSplittableBinary Include="$(BinDir)libmscordaccore.so" />
<NativeSplittableBinary Include="$(BinDir)libmscordbi.so" />
<NativeSplittableBinary Include="$(BinDir)libsosplugin.so" />
<NativeSplittableBinary Include="$(BinDir)System.Globalization.Native.so" />
<ArchitectureSpecificNativeFile Include="$(BinDir)sosdocsunix.txt" />
- <ArchitectureSpecificNativeFile Include="$(BinDir)mscorlib.ni.dll" />
- <ArchitectureSpecificNativeFile Include="$(BinDir)System.Private.CoreLib.ni.dll" />
+ <ArchitectureSpecificNativeFile Condition="'$(PackagePlatform)' != 'arm'" Include="$(BinDir)mscorlib.ni.dll" />
+ <ArchitectureSpecificNativeFile Condition="'$(PackagePlatform)' != 'arm'" Include="$(BinDir)System.Private.CoreLib.ni.dll" />
<ArchitectureSpecificLibFile Include="$(BinDir)System.Private.CoreLib.dll" />
<ArchitectureSpecificLibFile Include="$(BinDir)mscorlib.dll" />
<ArchitectureSpecificLibFile Include="$(BinDir)SOS.NETCore.dll" />
<CrossArchitectureSpecificNativeSymbol Condition="'$(HasCrossTargetComponents)' == 'true'"
Include="@(LongNameFiles -> '$(BinDir)$(CrossTargetComponentFolder)\%(FileName)$(CrossTargetLongNameSuffix)%(Extension)')" />
<AdditionalLibPackageExcludes Condition="'$(HasCrossTargetComponents)' == 'true'"
- Include="@(LongNameFiles -> 'runtimes\$(PackageTargetRuntime)\native\%(FileName)$(CrossTargetLongNameSuffix)%(Extension)')" />
+ Include="@(LongNameFiles -> 'tools\$(CrossTargetComponentFolder)_$(PackagePlatform)\%(FileName)$(CrossTargetLongNameSuffix)%(Extension)')" />
<File Include="@(ArchitectureSpecificNativeSymbol)">
<TargetPath>runtimes\$(PackageTargetRuntime)\native</TargetPath>
<IsSymbolFile>true</IsSymbolFile>
</File>
<File Condition="'$(HasCrossTargetComponents)' == 'true'" Include="@(CrossArchitectureSpecificNativeSymbol)">
- <TargetPath>tools/$(CrossTargetComponentFolder)_$(PackagePlatform)</TargetPath>
+ <TargetPath>tools\$(CrossTargetComponentFolder)_$(PackagePlatform)</TargetPath>
<IsSymbolFile>true</IsSymbolFile>
</File>
</ItemGroup>
<OSGroup>Linux</OSGroup>
<Platform>amd64</Platform>
</Project>
+ <Project Condition="'$(TargetsLinux)' == 'true' and '$(DistroRid)' == 'ubuntu.14.04-arm'" Include="ubuntu/14.04/Microsoft.NETCore.TestHost.pkgproj">
+ <OSGroup>Linux</OSGroup>
+ <Platform>arm</Platform>
+ </Project>
<Project Condition="'$(TargetsLinux)' == 'true' and '$(DistroRid)' == 'ubuntu.16.04-x64'" Include="ubuntu/16.04/Microsoft.NETCore.TestHost.pkgproj">
<OSGroup>Linux</OSGroup>
<Platform>amd64</Platform>
</Project>
+ <Project Condition="'$(TargetsLinux)' == 'true' and '$(DistroRid)' == 'ubuntu.16.04-arm'" Include="ubuntu/16.04/Microsoft.NETCore.TestHost.pkgproj">
+ <OSGroup>Linux</OSGroup>
+ <Platform>arm</Platform>
+ </Project>
<Project Condition="'$(TargetsLinux)' == 'true' and '$(DistroRid)' == 'ubuntu.16.10-x64'" Include="ubuntu/16.10/Microsoft.NETCore.TestHost.pkgproj">
<OSGroup>Linux</OSGroup>
<Platform>amd64</Platform>
<ProjectReference Include="ubuntu\14.04\Microsoft.NETCore.TestHost.pkgproj">
<Platform>amd64</Platform>
</ProjectReference>
+ <ProjectReference Include="ubuntu\14.04\Microsoft.NETCore.TestHost.pkgproj">
+ <Platform>arm</Platform>
+ </ProjectReference>
<ProjectReference Include="ubuntu\16.04\Microsoft.NETCore.TestHost.pkgproj">
<Platform>amd64</Platform>
</ProjectReference>
+ <ProjectReference Include="ubuntu\16.04\Microsoft.NETCore.TestHost.pkgproj">
+ <Platform>arm</Platform>
+ </ProjectReference>
<ProjectReference Include="ubuntu\16.10\Microsoft.NETCore.TestHost.pkgproj">
<Platform>amd64</Platform>
</ProjectReference>
</ProjectReference>
</ItemGroup>
<Import Project="$([MSBuild]::GetDirectoryNameOfFileAbove($(MSBuildThisFileDirectory), dir.targets))\dir.targets" />
-</Project>
\ No newline at end of file
+</Project>
<PropertyGroup>
<SkipPackageFileCheck>true</SkipPackageFileCheck>
<PackageTargetRuntime>ubuntu.14.04-$(PackagePlatform)</PackageTargetRuntime>
- <!-- only build for x64 -->
- <PackagePlatforms>x64;</PackagePlatforms>
+ <!-- build for x64, arm -->
+ <PackagePlatforms>x64;arm;</PackagePlatforms>
</PropertyGroup>
<ItemGroup>
<NativeSplittableBinary Include="$(BinDir)corerun" />
</File>
</ItemGroup>
<Import Project="$([MSBuild]::GetDirectoryNameOfFileAbove($(MSBuildThisFileDirectory), dir.targets))\dir.targets" />
-</Project>
\ No newline at end of file
+</Project>
<PropertyGroup>
<SkipPackageFileCheck>true</SkipPackageFileCheck>
<PackageTargetRuntime>ubuntu.16.04-$(PackagePlatform)</PackageTargetRuntime>
- <!-- only build for x64 -->
- <PackagePlatforms>x64;</PackagePlatforms>
+ <!-- build for x64, arm -->
+ <PackagePlatforms>x64;arm;</PackagePlatforms>
</PropertyGroup>
<ItemGroup>
<NativeSplittableBinary Include="$(BinDir)corerun" />
</File>
</ItemGroup>
<Import Project="$([MSBuild]::GetDirectoryNameOfFileAbove($(MSBuildThisFileDirectory), dir.targets))\dir.targets" />
-</Project>
\ No newline at end of file
+</Project>
/// Read memory callback
/// </summary>
/// <returns>number of bytes read or 0 for error</returns>
- internal unsafe delegate int ReadMemoryDelegate(IntPtr address, byte* buffer, int count);
+ internal unsafe delegate int ReadMemoryDelegate(ulong address, byte* buffer, int count);
private sealed class OpenedReader : IDisposable
{
/// </summary>
private class TargetStream : Stream
{
- readonly IntPtr _address;
+ readonly ulong _address;
readonly ReadMemoryDelegate _readMemory;
public override long Position { get; set; }
public override bool CanRead { get { return true; } }
public override bool CanWrite { get { return false; } }
- public TargetStream(IntPtr address, int size, ReadMemoryDelegate readMemory)
+ public TargetStream(ulong address, int size, ReadMemoryDelegate readMemory)
: base()
{
_address = address;
{
fixed (byte* p = &buffer[offset])
{
- int read = _readMemory(new IntPtr(_address.ToInt64() + Position), p, count);
+ int read = _readMemory(_address + (ulong)Position, p, count);
Position += read;
return read;
}
/// <param name="inMemoryPdbAddress">in memory PDB address or zero</param>
/// <param name="inMemoryPdbSize">in memory PDB size</param>
/// <returns>Symbol reader handle or zero if error</returns>
- internal static IntPtr LoadSymbolsForModule(string assemblyPath, bool isFileLayout, IntPtr loadedPeAddress, int loadedPeSize,
- IntPtr inMemoryPdbAddress, int inMemoryPdbSize, ReadMemoryDelegate readMemory)
+ internal static IntPtr LoadSymbolsForModule(string assemblyPath, bool isFileLayout, ulong loadedPeAddress, int loadedPeSize,
+ ulong inMemoryPdbAddress, int inMemoryPdbSize, ReadMemoryDelegate readMemory)
{
try
{
TargetStream peStream = null;
- if (assemblyPath == null && loadedPeAddress != IntPtr.Zero)
+ if (assemblyPath == null && loadedPeAddress != 0)
{
peStream = new TargetStream(loadedPeAddress, loadedPeSize, readMemory);
}
TargetStream pdbStream = null;
- if (inMemoryPdbAddress != IntPtr.Zero)
+ if (inMemoryPdbAddress != 0)
{
pdbStream = new TargetStream(inMemoryPdbAddress, inMemoryPdbSize, readMemory);
}
// cbString - number of characters available in the string buffer.
//
// The output will be truncated of cbString is not long enough for the full stack trace.
-HRESULT _EFN_GetManagedExcepStack(
+HRESULT CALLBACK _EFN_GetManagedExcepStack(
PDEBUG_CLIENT client,
ULONG64 StackObjAddr,
__out_ecount(cbString) PSTR szStackString,
// _EFN_GetManagedExcepStackW - same as _EFN_GetManagedExcepStack, but returns
// the stack as a wide string.
-HRESULT _EFN_GetManagedExcepStackW(
+HRESULT CALLBACK _EFN_GetManagedExcepStackW(
PDEBUG_CLIENT client,
ULONG64 StackObjAddr,
__out_ecount(cchString) PWSTR wszStackString,
// szName - a buffer to be filled with the full type name
// cbName - the number of characters available in the buffer
//
-HRESULT _EFN_GetManagedObjectName(
+HRESULT CALLBACK _EFN_GetManagedObjectName(
PDEBUG_CLIENT client,
ULONG64 objAddr,
__out_ecount(cbName) PSTR szName,
// pOffset - the offset from objAddr to the field. This parameter can be NULL.
//
// At least one of pValue and pOffset must be non-NULL.
-HRESULT _EFN_GetManagedObjectFieldInfo(
+HRESULT CALLBACK _EFN_GetManagedObjectFieldInfo(
PDEBUG_CLIENT client,
ULONG64 objAddr,
__out_ecount (mdNameLen) PSTR szFieldName,
int ReadMemoryForSymbols(ULONG64 address, char *buffer, int cb)
{
ULONG read;
- if (SafeReadMemory(address, (PVOID)buffer, cb, &read))
+ if (SafeReadMemory(TO_TADDR(address), (PVOID)buffer, cb, &read))
{
return read;
}
static const char *SymbolReaderClassName = "SOS.SymbolReader";
typedef int (*ReadMemoryDelegate)(ULONG64, char *, int);
-typedef ULONG64 (*LoadSymbolsForModuleDelegate)(const char*, BOOL, ULONG64, int, ULONG64, int, ReadMemoryDelegate);
-typedef void (*DisposeDelegate)(ULONG64);
-typedef BOOL (*ResolveSequencePointDelegate)(ULONG64, const char*, unsigned int, unsigned int*, unsigned int*);
-typedef BOOL (*GetLocalVariableName)(ULONG64, int, int, BSTR*);
-typedef BOOL (*GetLineByILOffsetDelegate)(ULONG64, mdMethodDef, ULONG64, ULONG *, BSTR*);
+typedef PVOID (*LoadSymbolsForModuleDelegate)(const char*, BOOL, ULONG64, int, ULONG64, int, ReadMemoryDelegate);
+typedef void (*DisposeDelegate)(PVOID);
+typedef BOOL (*ResolveSequencePointDelegate)(PVOID, const char*, unsigned int, unsigned int*, unsigned int*);
+typedef BOOL (*GetLocalVariableName)(PVOID, int, int, BSTR*);
+typedef BOOL (*GetLineByILOffsetDelegate)(PVOID, mdMethodDef, ULONG64, ULONG *, BSTR*);
class SymbolReader
{
#ifndef FEATURE_PAL
ISymUnmanagedReader* m_pSymReader;
#endif
- ULONG64 m_symbolReaderHandle;
+ PVOID m_symbolReaderHandle;
static LoadSymbolsForModuleDelegate loadSymbolsForModuleDelegate;
static DisposeDelegate disposeDelegate;
DWORD charCount = 0;
DWORD bytesWritten = 0;
- charCount = sprintf(strMethodIndex, "%d\r\n", methodIndex);
+ charCount = sprintf_s(strMethodIndex, sizeof(strMethodIndex), "%d\r\n", methodIndex);
if (!WriteFile(hMCLFile, strMethodIndex, charCount, &bytesWritten, nullptr) || bytesWritten != charCount)
{
if (mc->dumpMethodMD5HashToBuffer(md5Hash, MD5_HASH_BUFFER_SIZE) != MD5_HASH_BUFFER_SIZE)
md5Hash[0] = 0;
- charCount += sprintf(rowData + charCount, "%s,", md5Hash);
+ charCount += sprintf_s(rowData + charCount, _countof(rowData) - charCount, "%s,", md5Hash);
}
if (strchr(statsTypes, '*') != NULL || strchr(statsTypes, 'n') != NULL || strchr(statsTypes, 'N') != NULL)
{
- charCount += sprintf(rowData + charCount, "%d,", methodNumber);
+ charCount += sprintf_s(rowData + charCount, _countof(rowData) - charCount, "%d,", methodNumber);
}
if (strchr(statsTypes, '*') != NULL || strchr(statsTypes, 'i') != NULL || strchr(statsTypes, 'I') != NULL)
{
unsigned flags = 0;
mc->repCompileMethod(&info, &flags);
- charCount += sprintf(rowData + charCount, "%d,", info.ILCodeSize);
+ charCount += sprintf_s(rowData + charCount, _countof(rowData) - charCount, "%d,", info.ILCodeSize);
}
if (strchr(statsTypes, '*') != NULL || strchr(statsTypes, 'a') != NULL || strchr(statsTypes, 'A') != NULL)
{
else
codeSize = 0;//this is likely a thin mc
- charCount += sprintf(rowData + charCount, "%d,", codeSize);
+ charCount += sprintf_s(rowData + charCount, _countof(rowData) - charCount, "%d,", codeSize);
}
if (strchr(statsTypes, '*') != NULL || strchr(statsTypes, 't') != NULL || strchr(statsTypes, 'T') != NULL)
{
- charCount += sprintf(rowData + charCount, "%llu,%llu,", firstTime, secondTime);
+ charCount += sprintf_s(rowData + charCount, _countof(rowData) - charCount, "%llu,%llu,", firstTime, secondTime);
}
//get rid of the final ',' and replace it with a '\n'
DWORD bytesWritten = 0;
if (strchr(statsTypes, '*') != NULL || strchr(statsTypes, 'h') != NULL || strchr(statsTypes, 'H') != NULL)
- charCount += sprintf(rowHeader + charCount, "HASH,");
+ charCount += sprintf_s(rowHeader + charCount, _countof(rowHeader) - charCount, "HASH,");
if (strchr(statsTypes, '*') != NULL || strchr(statsTypes, 'n') != NULL || strchr(statsTypes, 'N') != NULL)
- charCount += sprintf(rowHeader + charCount, "METHOD_NUMBER,");
+ charCount += sprintf_s(rowHeader + charCount, _countof(rowHeader) - charCount, "METHOD_NUMBER,");
if (strchr(statsTypes, '*') != NULL || strchr(statsTypes, 'i') != NULL || strchr(statsTypes, 'I') != NULL)
- charCount += sprintf(rowHeader + charCount, "IL_CODE_SIZE,");
+ charCount += sprintf_s(rowHeader + charCount, _countof(rowHeader) - charCount, "IL_CODE_SIZE,");
if (strchr(statsTypes, '*') != NULL || strchr(statsTypes, 'a') != NULL || strchr(statsTypes, 'A') != NULL)
- charCount += sprintf(rowHeader + charCount, "ASM_CODE_SIZE,");
+ charCount += sprintf_s(rowHeader + charCount, _countof(rowHeader) - charCount, "ASM_CODE_SIZE,");
if (strchr(statsTypes, '*') != NULL || strchr(statsTypes, 't') != NULL || strchr(statsTypes, 'T') != NULL)
- charCount += sprintf(rowHeader + charCount, "Time1,Time2,");
+ charCount += sprintf_s(rowHeader + charCount, _countof(rowHeader) - charCount, "Time1,Time2,");
//get rid of the final ',' and replace it with a '\n'
rowHeader[charCount - 1] = '\n';
LogError("Failed to write row header '%s'. GetLastError()=%u", rowHeader, GetLastError());
}
}
-}
\ No newline at end of file
+}
DWORD charCount = 0;
DWORD bytesWritten = 0;
- charCount = sprintf(strMethodIndex, "%d\r\n", arr[i]);
+ charCount = sprintf_s(strMethodIndex, sizeof(strMethodIndex), "%d\r\n", arr[i]);
if (!WriteFile(hMCLFile, strMethodIndex, charCount, &bytesWritten, nullptr) || (bytesWritten != charCount))
{
if (o.applyDiff)
{
int temp1 = 0, temp2 = 0, temp3 = 0, temp4 = 0;
- int converted = sscanf(buff, g_AsmDiffsSummaryFormatString, &temp1, &temp2, &temp3, &temp4);
+ int converted = sscanf_s(buff, g_AsmDiffsSummaryFormatString, &temp1, &temp2, &temp3, &temp4);
if (converted != 4)
{
LogError("Couldn't parse status message: \"%s\"", buff);
else
{
int temp1 = 0, temp2 = 0, temp3 = 0;
- int converted = sscanf(buff, g_SummaryFormatString, &temp1, &temp2, &temp3);
+ int converted = sscanf_s(buff, g_SummaryFormatString, &temp1, &temp2, &temp3);
if (converted != 3)
{
LogError("Couldn't parse status message: \"%s\"", buff);
if (g_iDbgRuntimeCounter[event & 0x00ff] == count)
{
char tmpStr[256];
- sprintf(tmpStr, "%s == %d, break now!",
- IPCENames::GetName(event), count);
+ _snprintf_s(tmpStr, _countof(tmpStr), _TRUNCATE, "%s == %d, break now!",
+ IPCENames::GetName(event), count);
// fire the assertion
DbgAssertDialog(__FILE__, __LINE__, tmpStr);
if (g_iDbgDebuggerCounter[event & 0x00ff] == count)
{
char tmpStr[256];
- sprintf(tmpStr, "%s == %d, break now!",
- IPCENames::GetName(event), count);
+ _snprintf_s(tmpStr, _countof(tmpStr), _TRUNCATE, "%s == %d, break now!",
+ IPCENames::GetName(event), count);
// fire the assertion
DbgAssertDialog(__FILE__, __LINE__, tmpStr);
_itow_s
_i64tow_s
memcpy_s
+sscanf_s
CoCreateGuid
CopyFileW
static void DiagWalkSurvivors(void* gcContext);
static void DiagWalkLOHSurvivors(void* gcContext);
static void DiagWalkBGCSurvivors(void* gcContext);
+ static void StompWriteBarrier(WriteBarrierParameters* args);
};
#endif // __GCENV_EE_H__
#endif //BACKGROUND_GC
current_hist->fgc_lowest = lowest_address;
current_hist->fgc_highest = highest_address;
- current_hist->g_lowest = g_lowest_address;
- current_hist->g_highest = g_highest_address;
+ current_hist->g_lowest = g_gc_lowest_address;
+ current_hist->g_highest = g_gc_highest_address;
gchist_index_per_heap++;
if (gchist_index_per_heap == max_history_count)
#ifndef MULTIPLE_HEAPS
-#define ephemeral_low g_ephemeral_low
-#define ephemeral_high g_ephemeral_high
+#define ephemeral_low g_gc_ephemeral_low
+#define ephemeral_high g_gc_ephemeral_high
#endif // MULTIPLE_HEAPS
return pos;
}
+#ifndef DACCESS_COMPILE
+
+void stomp_write_barrier_resize(bool is_runtime_suspended, bool requires_upper_bounds_check)
+{
+ WriteBarrierParameters args = {};
+ args.operation = WriteBarrierOp::StompResize;
+ args.is_runtime_suspended = is_runtime_suspended;
+ args.requires_upper_bounds_check = requires_upper_bounds_check;
+ args.card_table = g_gc_card_table;
+ args.lowest_address = g_gc_lowest_address;
+ args.highest_address = g_gc_highest_address;
+ GCToEEInterface::StompWriteBarrier(&args);
+}
+
+void stomp_write_barrier_ephemeral(bool is_runtime_suspended, uint8_t* ephemeral_lo, uint8_t* ephemeral_hi)
+{
+ WriteBarrierParameters args = {};
+ args.operation = WriteBarrierOp::StompEphemeral;
+ args.is_runtime_suspended = is_runtime_suspended;
+ args.ephemeral_lo = g_gc_ephemeral_low;
+ args.ephemeral_hi = g_gc_ephemeral_high;
+#ifdef MULTIPLE_HEAPS
+ // It is not correct to update the EE's g_ephemeral_low and g_ephemeral_high
+ // to anything other than their default values when using Server GC, since
+ // there is no single ephemeral generation across all of the heaps.
+ // Server GC write barriers do not reference these two globals, but ErectWriteBarrier does.
+ //
+ // When MULTIPLE_HEAPS is defined, g_gc_ephemeral_low and g_gc_ephemeral_high should
+ // always have their default values.
+ assert(args.ephemeral_lo == (uint8_t*)1);
+ assert(args.ephemeral_hi == (uint8_t*)~0);
+#endif // MULTIPLE_HEAPS
+ GCToEEInterface::StompWriteBarrier(&args);
+}
+
+void stomp_write_barrier_initialize()
+{
+ WriteBarrierParameters args = {};
+ args.operation = WriteBarrierOp::Initialize;
+ args.is_runtime_suspended = true;
+ args.requires_upper_bounds_check = false;
+ args.card_table = g_gc_card_table;
+ args.lowest_address = g_gc_lowest_address;
+ args.highest_address = g_gc_highest_address;
+ GCToEEInterface::StompWriteBarrier(&args);
+}
+
+#endif // DACCESS_COMPILE
+
//extract the low bits [0,low[ of a uint32_t
#define lowbits(wrd, bits) ((wrd) & ((1 << (bits))-1))
//extract the high bits [high, 32] of a uint32_t
size_t ro_seg_begin_index (heap_segment* seg)
{
size_t begin_index = (size_t)seg / gc_heap::min_segment_size;
- begin_index = max (begin_index, (size_t)g_lowest_address / gc_heap::min_segment_size);
+ begin_index = max (begin_index, (size_t)g_gc_lowest_address / gc_heap::min_segment_size);
return begin_index;
}
size_t ro_seg_end_index (heap_segment* seg)
{
size_t end_index = (size_t)(heap_segment_reserved (seg) - 1) / gc_heap::min_segment_size;
- end_index = min (end_index, (size_t)g_highest_address / gc_heap::min_segment_size);
+ end_index = min (end_index, (size_t)g_gc_highest_address / gc_heap::min_segment_size);
return end_index;
}
void seg_mapping_table_add_ro_segment (heap_segment* seg)
{
#ifdef GROWABLE_SEG_MAPPING_TABLE
- if ((heap_segment_reserved (seg) <= g_lowest_address) || (heap_segment_mem (seg) >= g_highest_address))
+ if ((heap_segment_reserved (seg) <= g_gc_lowest_address) || (heap_segment_mem (seg) >= g_gc_highest_address))
return;
#endif //GROWABLE_SEG_MAPPING_TABLE
gc_heap* seg_mapping_table_heap_of (uint8_t* o)
{
#ifdef GROWABLE_SEG_MAPPING_TABLE
- if ((o < g_lowest_address) || (o >= g_highest_address))
+ if ((o < g_gc_lowest_address) || (o >= g_gc_highest_address))
return 0;
#endif //GROWABLE_SEG_MAPPING_TABLE
gc_heap* seg_mapping_table_heap_of_gc (uint8_t* o)
{
#if defined(FEATURE_BASICFREEZE) && defined(GROWABLE_SEG_MAPPING_TABLE)
- if ((o < g_lowest_address) || (o >= g_highest_address))
+ if ((o < g_gc_lowest_address) || (o >= g_gc_highest_address))
return 0;
#endif //FEATURE_BASICFREEZE || GROWABLE_SEG_MAPPING_TABLE
heap_segment* seg_mapping_table_segment_of (uint8_t* o)
{
#if defined(FEATURE_BASICFREEZE) && defined(GROWABLE_SEG_MAPPING_TABLE)
- if ((o < g_lowest_address) || (o >= g_highest_address))
+ if ((o < g_gc_lowest_address) || (o >= g_gc_highest_address))
#ifdef FEATURE_BASICFREEZE
return ro_segment_lookup (o);
#else
#ifdef FEATURE_BASICFREEZE
// TODO: This was originally written assuming that the seg_mapping_table would always contain entries for ro
- // segments whenever the ro segment falls into the [g_lowest_address,g_highest_address) range. I.e., it had an
+ // segments whenever the ro segment falls into the [g_gc_lowest_address,g_gc_highest_address) range. I.e., it had an
// extra "&& (size_t)(entry->seg1) & ro_in_entry" expression. However, at the moment, grow_brick_card_table does
// not correctly go through the ro segments and add them back to the seg_mapping_table when the [lowest,highest)
// range changes. We should probably go ahead and modify grow_brick_card_table and put back the
memory_details.current_block_normal = 0;
memory_details.current_block_large = 0;
- g_lowest_address = MAX_PTR;
- g_highest_address = 0;
+ g_gc_lowest_address = MAX_PTR;
+ g_gc_highest_address = 0;
if (((size_t)MAX_PTR - large_size) < normal_size)
{
uint8_t* allatonce_block = (uint8_t*)virtual_alloc (requestedMemory);
if (allatonce_block)
{
- g_lowest_address = allatonce_block;
- g_highest_address = allatonce_block + (memory_details.block_count * (large_size + normal_size));
+ g_gc_lowest_address = allatonce_block;
+ g_gc_highest_address = allatonce_block + (memory_details.block_count * (large_size + normal_size));
memory_details.allocation_pattern = initial_memory_details::ALLATONCE;
for(size_t i = 0; i < memory_details.block_count; i++)
if (b2)
{
memory_details.allocation_pattern = initial_memory_details::TWO_STAGE;
- g_lowest_address = min(b1,b2);
- g_highest_address = max(b1 + memory_details.block_count*normal_size,
+ g_gc_lowest_address = min(b1,b2);
+ g_gc_highest_address = max(b1 + memory_details.block_count*normal_size,
b2 + memory_details.block_count*large_size);
for(size_t i = 0; i < memory_details.block_count; i++)
{
}
else
{
- if (current_block->memory_base < g_lowest_address)
- g_lowest_address = current_block->memory_base;
- if (((uint8_t *) current_block->memory_base + block_size) > g_highest_address)
- g_highest_address = (current_block->memory_base + block_size);
+ if (current_block->memory_base < g_gc_lowest_address)
+ g_gc_lowest_address = current_block->memory_base;
+ if (((uint8_t *) current_block->memory_base + block_size) > g_gc_highest_address)
+ g_gc_highest_address = (current_block->memory_base + block_size);
}
reserve_success = TRUE;
}
{
uint8_t* start;
uint8_t* end;
- if (mem < g_lowest_address)
+ if (mem < g_gc_lowest_address)
{
start = (uint8_t*)mem;
}
else
{
- start = (uint8_t*)g_lowest_address;
+ start = (uint8_t*)g_gc_lowest_address;
}
- if (((uint8_t*)mem + size) > g_highest_address)
+ if (((uint8_t*)mem + size) > g_gc_highest_address)
{
end = (uint8_t*)mem + size;
}
else
{
- end = (uint8_t*)g_highest_address;
+ end = (uint8_t*)g_gc_highest_address;
}
if (gc_heap::grow_brick_card_tables (start, end, size, result, __this, loh_p) != 0)
uint8_t* sadd = add;
heap_segment* hs = 0;
heap_segment* hs1 = 0;
- if (!((add >= g_lowest_address) && (add < g_highest_address)))
+ if (!((add >= g_gc_lowest_address) && (add < g_gc_highest_address)))
{
delta = 0;
return 0;
inline
void gset_card (size_t card)
{
- g_card_table [card_word (card)] |= (1 << card_bit (card));
+ g_gc_card_table [card_word (card)] |= (1 << card_bit (card));
}
inline
uint32_t* translate_card_bundle_table (uint32_t* cb)
{
- return (uint32_t*)((uint8_t*)cb - ((((size_t)g_lowest_address) / (card_size*card_word_width*card_bundle_size*card_bundle_word_width)) * sizeof (uint32_t)));
+ return (uint32_t*)((uint8_t*)cb - ((((size_t)g_gc_lowest_address) / (card_size*card_word_width*card_bundle_size*card_bundle_word_width)) * sizeof (uint32_t)));
}
void gc_heap::enable_card_bundles ()
// according to the lowest_address.
uint32_t* translate_mark_array (uint32_t* ma)
{
- return (uint32_t*)((uint8_t*)ma - size_mark_array_of (0, g_lowest_address));
+ return (uint32_t*)((uint8_t*)ma - size_mark_array_of (0, g_gc_lowest_address));
}
// from and end must be page aligned addresses.
{
destroy_card_table (c_table);
// sever the link from the parent
- if (&g_card_table[card_word (gcard_of(g_lowest_address))] == c_table)
+ if (&g_gc_card_table[card_word (gcard_of(g_gc_lowest_address))] == c_table)
{
- g_card_table = 0;
+ g_gc_card_table = 0;
#ifdef FEATURE_USE_SOFTWARE_WRITE_WATCH_FOR_GC_HEAP
SoftwareWriteWatch::StaticClose();
#endif // FEATURE_USE_SOFTWARE_WRITE_WATCH_FOR_GC_HEAP
}
else
{
- uint32_t* p_table = &g_card_table[card_word (gcard_of(g_lowest_address))];
+ uint32_t* p_table = &g_gc_card_table[card_word (gcard_of(g_gc_lowest_address))];
if (p_table)
{
while (p_table && (card_table_next (p_table) != c_table))
uint32_t* gc_heap::make_card_table (uint8_t* start, uint8_t* end)
{
- assert (g_lowest_address == start);
- assert (g_highest_address == end);
+ assert (g_gc_lowest_address == start);
+ assert (g_gc_highest_address == end);
uint32_t virtual_reserve_flags = VirtualReserveFlags::None;
if (can_use_write_watch_for_card_table())
{
virtual_reserve_flags |= VirtualReserveFlags::WriteWatch;
- cb = size_card_bundle_of (g_lowest_address, g_highest_address);
+ cb = size_card_bundle_of (g_gc_lowest_address, g_gc_highest_address);
}
#endif //CARD_BUNDLE
#endif // FEATURE_USE_SOFTWARE_WRITE_WATCH_FOR_GC_HEAP
#ifdef GROWABLE_SEG_MAPPING_TABLE
- size_t st = size_seg_mapping_table_of (g_lowest_address, g_highest_address);
+ size_t st = size_seg_mapping_table_of (g_gc_lowest_address, g_gc_highest_address);
size_t st_table_offset = sizeof(card_table_info) + cs + bs + cb + wws;
size_t st_table_offset_aligned = align_for_seg_mapping_table (st_table_offset);
#ifdef GROWABLE_SEG_MAPPING_TABLE
seg_mapping_table = (seg_mapping*)(mem + st_table_offset_aligned);
seg_mapping_table = (seg_mapping*)((uint8_t*)seg_mapping_table -
- size_seg_mapping_table_of (0, (align_lower_segment (g_lowest_address))));
+ size_seg_mapping_table_of (0, (align_lower_segment (g_gc_lowest_address))));
#endif //GROWABLE_SEG_MAPPING_TABLE
#ifdef MARK_ARRAY
gc_heap* hp,
BOOL loh_p)
{
- uint8_t* la = g_lowest_address;
- uint8_t* ha = g_highest_address;
- uint8_t* saved_g_lowest_address = min (start, g_lowest_address);
- uint8_t* saved_g_highest_address = max (end, g_highest_address);
+ uint8_t* la = g_gc_lowest_address;
+ uint8_t* ha = g_gc_highest_address;
+ uint8_t* saved_g_lowest_address = min (start, g_gc_lowest_address);
+ uint8_t* saved_g_highest_address = max (end, g_gc_highest_address);
#ifdef BACKGROUND_GC
// This value is only for logging purpose - it's not necessarily exactly what we
// would commit for mark array but close enough for diagnostics purpose.
#endif // BIT64
ps *= 2;
- if (saved_g_lowest_address < g_lowest_address)
+ if (saved_g_lowest_address < g_gc_lowest_address)
{
- if (ps > (size_t)g_lowest_address)
+ if (ps > (size_t)g_gc_lowest_address)
saved_g_lowest_address = (uint8_t*)OS_PAGE_SIZE;
else
{
- assert (((size_t)g_lowest_address - ps) >= OS_PAGE_SIZE);
- saved_g_lowest_address = min (saved_g_lowest_address, (g_lowest_address - ps));
+ assert (((size_t)g_gc_lowest_address - ps) >= OS_PAGE_SIZE);
+ saved_g_lowest_address = min (saved_g_lowest_address, (g_gc_lowest_address - ps));
}
}
- if (saved_g_highest_address > g_highest_address)
+ if (saved_g_highest_address > g_gc_highest_address)
{
saved_g_highest_address = max ((saved_g_lowest_address + ps), saved_g_highest_address);
if (saved_g_highest_address > top)
bool write_barrier_updated = false;
uint32_t virtual_reserve_flags = VirtualReserveFlags::None;
- uint32_t* saved_g_card_table = g_card_table;
+ uint32_t* saved_g_card_table = g_gc_card_table;
uint32_t* ct = 0;
uint32_t* translated_ct = 0;
short* bt = 0;
card_table_refcount (ct) = 0;
card_table_lowest_address (ct) = saved_g_lowest_address;
card_table_highest_address (ct) = saved_g_highest_address;
- card_table_next (ct) = &g_card_table[card_word (gcard_of (la))];
+ card_table_next (ct) = &g_gc_card_table[card_word (gcard_of (la))];
//clear the card table
/*
seg_mapping* new_seg_mapping_table = (seg_mapping*)(mem + st_table_offset_aligned);
new_seg_mapping_table = (seg_mapping*)((uint8_t*)new_seg_mapping_table -
size_seg_mapping_table_of (0, (align_lower_segment (saved_g_lowest_address))));
- memcpy(&new_seg_mapping_table[seg_mapping_word_of(g_lowest_address)],
- &seg_mapping_table[seg_mapping_word_of(g_lowest_address)],
- size_seg_mapping_table_of(g_lowest_address, g_highest_address));
+ memcpy(&new_seg_mapping_table[seg_mapping_word_of(g_gc_lowest_address)],
+ &seg_mapping_table[seg_mapping_word_of(g_gc_lowest_address)],
+ size_seg_mapping_table_of(g_gc_lowest_address, g_gc_highest_address));
seg_mapping_table = new_seg_mapping_table;
}
// Note on points where the runtime is suspended anywhere in this function. Upon an attempt to suspend the
// runtime, a different thread may suspend first, causing this thread to block at the point of the suspend call.
// So, at any suspend point, externally visible state needs to be consistent, as code that depends on that state
- // may run while this thread is blocked. This includes updates to g_card_table, g_lowest_address, and
- // g_highest_address.
+ // may run while this thread is blocked. This includes updates to g_gc_card_table, g_gc_lowest_address, and
+ // g_gc_highest_address.
suspend_EE();
}
- g_card_table = translated_ct;
+ g_gc_card_table = translated_ct;
+ g_gc_lowest_address = saved_g_lowest_address;
+ g_gc_highest_address = saved_g_highest_address;
SoftwareWriteWatch::SetResizedUntranslatedTable(
mem + sw_ww_table_offset,
// grow version of the write barrier. This test tells us if the new
// segment was allocated at a lower address than the old, requiring
// that we start doing an upper bounds check in the write barrier.
- StompWriteBarrierResize(true, la != saved_g_lowest_address);
+ stomp_write_barrier_resize(true, la != saved_g_lowest_address);
write_barrier_updated = true;
if (!is_runtime_suspended)
else
#endif // FEATURE_USE_SOFTWARE_WRITE_WATCH_FOR_GC_HEAP
{
- g_card_table = translated_ct;
+ g_gc_card_table = translated_ct;
}
+ g_gc_lowest_address = saved_g_lowest_address;
+ g_gc_highest_address = saved_g_highest_address;
+
if (!write_barrier_updated)
{
// This passes a bool telling whether we need to switch to the post
// to be changed, so we are doing this after all global state has
// been updated. See the comment above suspend_EE() above for more
// info.
- StompWriteBarrierResize(!!IsGCThread(), la != saved_g_lowest_address);
+ stomp_write_barrier_resize(!!IsGCThread(), la != saved_g_lowest_address);
}
- // We need to make sure that other threads executing checked write barriers
- // will see the g_card_table update before g_lowest/highest_address updates.
- // Otherwise, the checked write barrier may AV accessing the old card table
- // with address that it does not cover. Write barriers access card table
- // without memory barriers for performance reasons, so we need to flush
- // the store buffers here.
- GCToOSInterface::FlushProcessWriteBuffers();
-
- g_lowest_address = saved_g_lowest_address;
- VolatileStore(&g_highest_address, saved_g_highest_address);
return 0;
if (mem)
{
- assert(g_card_table == saved_g_card_table);
+ assert(g_gc_card_table == saved_g_card_table);
//delete (uint32_t*)((uint8_t*)ct - sizeof(card_table_info));
if (!GCToOSInterface::VirtualRelease (mem, alloc_size_aligned))
assert (ha == card_table_highest_address (&old_card_table[card_word (card_of (la))]));
/* todo: Need a global lock for this */
- uint32_t* ct = &g_card_table[card_word (gcard_of (g_lowest_address))];
+ uint32_t* ct = &g_gc_card_table[card_word (gcard_of (g_gc_lowest_address))];
own_card_table (ct);
card_table = translate_card_table (ct);
/* End of global lock */
if (gc_can_use_concurrent)
{
mark_array = translate_mark_array (card_table_mark_array (ct));
- assert (mark_word_of (g_highest_address) ==
- mark_word_of (align_on_mark_word (g_highest_address)));
+ assert (mark_word_of (g_gc_highest_address) ==
+ mark_word_of (align_on_mark_word (g_gc_highest_address)));
}
else
mark_array = NULL;
#ifdef CARD_BUNDLE
#if defined(MARK_ARRAY) && defined(_DEBUG)
#ifdef GROWABLE_SEG_MAPPING_TABLE
- size_t st = size_seg_mapping_table_of (g_lowest_address, g_highest_address);
+ size_t st = size_seg_mapping_table_of (g_gc_lowest_address, g_gc_highest_address);
#else //GROWABLE_SEG_MAPPING_TABLE
size_t st = 0;
#endif //GROWABLE_SEG_MAPPING_TABLE
#endif //MARK_ARRAY && _DEBUG
card_bundle_table = translate_card_bundle_table (card_table_card_bundle_table (ct));
- assert (&card_bundle_table [card_bundle_word (cardw_card_bundle (card_word (card_of (g_lowest_address))))] ==
+ assert (&card_bundle_table [card_bundle_word (cardw_card_bundle (card_word (card_of (g_gc_lowest_address))))] ==
card_table_card_bundle_table (ct));
//set the card table if we are in a heap growth scenario
{
size_t bcardw = (uint32_t*)(max(g_addresses[i],base_address)) - &card_table[0];
size_t ecardw = (uint32_t*)(min(g_addresses[i]+OS_PAGE_SIZE, high_address)) - &card_table[0];
- assert (bcardw >= card_word (card_of (g_lowest_address)));
+ assert (bcardw >= card_word (card_of (g_gc_lowest_address)));
card_bundles_set (cardw_card_bundle (bcardw),
cardw_card_bundle (align_cardw_on_bundle (ecardw)));
(size_t)ephemeral_low, (size_t)ephemeral_high))
// This updates the write barrier helpers with the new info.
- StompWriteBarrierEphemeral(is_runtime_suspended);
+ stomp_write_barrier_ephemeral(is_runtime_suspended, ephemeral_low, ephemeral_high);
}
#if defined(TRACE_GC) || defined(GC_CONFIG_DRIVEN)
settings.first_init();
- g_card_table = make_card_table (g_lowest_address, g_highest_address);
+ g_gc_card_table = make_card_table (g_gc_lowest_address, g_gc_highest_address);
- if (!g_card_table)
+ if (!g_gc_card_table)
return E_OUTOFMEMORY;
gc_started = FALSE;
#endif //MULTIPLE_HEAPS
/* todo: Need a global lock for this */
- uint32_t* ct = &g_card_table [card_word (card_of (g_lowest_address))];
+ uint32_t* ct = &g_gc_card_table [card_word (card_of (g_gc_lowest_address))];
own_card_table (ct);
card_table = translate_card_table (ct);
/* End of global lock */
#ifdef CARD_BUNDLE
card_bundle_table = translate_card_bundle_table (card_table_card_bundle_table (ct));
- assert (&card_bundle_table [card_bundle_word (cardw_card_bundle (card_word (card_of (g_lowest_address))))] ==
+ assert (&card_bundle_table [card_bundle_word (cardw_card_bundle (card_word (card_of (g_gc_lowest_address))))] ==
card_table_card_bundle_table (ct));
#endif //CARD_BUNDLE
#ifdef MARK_ARRAY
if (gc_can_use_concurrent)
- mark_array = translate_mark_array (card_table_mark_array (&g_card_table[card_word (card_of (g_lowest_address))]));
+ mark_array = translate_mark_array (card_table_mark_array (&g_gc_card_table[card_word (card_of (g_gc_lowest_address))]));
else
mark_array = NULL;
#endif //MARK_ARRAY
vm_heap->GcCondemnedGeneration = settings.condemned_generation;
- assert (g_card_table == card_table);
+ assert (g_gc_card_table == card_table);
{
if (n == max_generation)
for (int i = 0; i < n_heaps; i++)
{
//copy the card and brick tables
- if (g_card_table != g_heaps[i]->card_table)
+ if (g_gc_card_table != g_heaps[i]->card_table)
{
g_heaps[i]->copy_brick_card_table();
}
}
#endif //BACKGROUND_GC
// check for card table growth
- if (g_card_table != card_table)
+ if (g_gc_card_table != card_table)
copy_brick_card_table();
#endif //MULTIPLE_HEAPS
for (i = 0; i < n_heaps; i++)
{
//copy the card and brick tables
- if (g_card_table!= g_heaps[i]->card_table)
+ if (g_gc_card_table!= g_heaps[i]->card_table)
{
g_heaps[i]->copy_brick_card_table();
}
if (new_card_table == 0)
{
- new_card_table = g_card_table;
+ new_card_table = g_gc_card_table;
}
if (hp->card_table != new_card_table)
{
if (new_lowest_address == 0)
{
- new_lowest_address = g_lowest_address;
+ new_lowest_address = g_gc_lowest_address;
}
uint32_t* ct = &new_card_table[card_word (gcard_of (new_lowest_address))];
return consing_gen;
//copy the card and brick tables
- if (g_card_table!= card_table)
+ if (g_gc_card_table!= card_table)
copy_brick_card_table();
BOOL new_segment_p = (heap_segment_next (new_seg) == 0);
void gc_heap::verify_mark_array_cleared (heap_segment* seg)
{
#if defined (VERIFY_HEAP) && defined (MARK_ARRAY)
- assert (card_table == g_card_table);
+ assert (card_table == g_gc_card_table);
size_t markw = mark_word_of (heap_segment_mem (seg));
size_t markw_end = mark_word_of (heap_segment_reserved (seg));
#endif //BACKGROUND_GC
#ifndef MULTIPLE_HEAPS
- if ((g_ephemeral_low != generation_allocation_start (generation_of (max_generation - 1))) ||
- (g_ephemeral_high != heap_segment_reserved (ephemeral_heap_segment)))
+ if ((g_gc_ephemeral_low != generation_allocation_start (generation_of (max_generation - 1))) ||
+ (g_gc_ephemeral_high != heap_segment_reserved (ephemeral_heap_segment)))
{
FATAL_GC_ERROR();
}
for (int i = 0; i < n_heaps; i++)
{
//copy the card and brick tables
- if (g_card_table != g_heaps[i]->card_table)
+ if (g_gc_card_table != g_heaps[i]->card_table)
{
g_heaps[i]->copy_brick_card_table();
}
current_join->restart();
}
#else
- if (g_card_table != card_table)
+ if (g_gc_card_table != card_table)
copy_brick_card_table();
#endif //MULTIPLE_HEAPS
//CloseHandle (WaitForGCEvent);
//find out if the global card table hasn't been used yet
- uint32_t* ct = &g_card_table[card_word (gcard_of (g_lowest_address))];
+ uint32_t* ct = &g_gc_card_table[card_word (gcard_of (g_gc_lowest_address))];
if (card_table_refcount (ct) == 0)
{
destroy_card_table (ct);
- g_card_table = 0;
+ g_gc_card_table = 0;
#ifdef FEATURE_USE_SOFTWARE_WRITE_WATCH_FOR_GC_HEAP
SoftwareWriteWatch::StaticClose();
#endif // FEATURE_USE_SOFTWARE_WRITE_WATCH_FOR_GC_HEAP
return E_FAIL;
}
- StompWriteBarrierResize(true, false);
+ stomp_write_barrier_initialize();
#ifndef FEATURE_REDHAWK // Redhawk forces relocation a different way
#if defined (STRESS_HEAP) && !defined (MULTIPLE_HEAPS)
uint8_t* o = (uint8_t*)object;
#ifndef FEATURE_BASICFREEZE
- if (!((o < g_highest_address) && (o >= g_lowest_address)))
+ if (!((o < g_gc_highest_address) && (o >= g_gc_lowest_address)))
{
return NULL;
}
uint8_t* object = (uint8_t*) vpObject;
#ifndef FEATURE_BASICFREEZE
- if (!((object < g_highest_address) && (object >= g_lowest_address)))
+ if (!((object < g_gc_highest_address) && (object >= g_gc_lowest_address)))
return FALSE;
#endif //!FEATURE_BASICFREEZE
end = StartPoint + (len/sizeof(Object*));
while (rover < end)
{
- if ( (((uint8_t*)*rover) >= g_ephemeral_low) && (((uint8_t*)*rover) < g_ephemeral_high) )
+ if ( (((uint8_t*)*rover) >= g_gc_ephemeral_low) && (((uint8_t*)*rover) < g_gc_ephemeral_high) )
{
// Set Bit For Card and advance to next card
size_t card = gcard_of ((uint8_t*)rover);
- Interlocked::Or (&g_card_table[card/card_word_width], (1U << (card % card_word_width)));
+ Interlocked::Or (&g_gc_card_table[card/card_word_width], (1U << (card % card_word_width)));
// Skip to next card for the object
rover = (Object**)align_on_card ((uint8_t*)(rover+1));
}
if (!(g_pConfig->GetHeapVerifyLevel() & EEConfig::HEAPVERIFY_BARRIERCHECK))
return;
- size_t len = g_highest_address - g_lowest_address;
+ size_t len = g_gc_highest_address - g_gc_lowest_address;
if (len > (size_t)(g_GCShadowEnd - g_GCShadow))
{
deleteGCShadow();
g_GCShadowEnd += len;
}
- // save the value of g_lowest_address at this time. If this value changes before
+ // save the value of g_gc_lowest_address at this time. If this value changes before
// the next call to checkGCWriteBarrier() it means we extended the heap (with a
// large object segment most probably), and the whole shadow segment is inconsistent.
- g_shadow_lowest_address = g_lowest_address;
+ g_shadow_lowest_address = g_gc_lowest_address;
//****** Copy the whole GC heap ******
//
generation* gen = gc_heap::generation_of (max_generation);
heap_segment* seg = heap_segment_rw (generation_start_segment (gen));
- ptrdiff_t delta = g_GCShadow - g_lowest_address;
+ ptrdiff_t delta = g_GCShadow - g_gc_lowest_address;
BOOL small_object_segments = TRUE;
while(1)
{
// test to see if 'ptr' was only updated via the write barrier.
inline void testGCShadow(Object** ptr)
{
- Object** shadow = (Object**) &g_GCShadow[((uint8_t*) ptr - g_lowest_address)];
+ Object** shadow = (Object**) &g_GCShadow[((uint8_t*) ptr - g_gc_lowest_address)];
if (*ptr != 0 && (uint8_t*) shadow < g_GCShadowEnd && *ptr != *shadow)
{
// Walk the whole heap, looking for pointers that were not updated with the write barrier.
void checkGCWriteBarrier()
{
- // g_shadow_lowest_address != g_lowest_address means the GC heap was extended by a segment
+ // g_shadow_lowest_address != g_gc_lowest_address means the GC heap was extended by a segment
// and the GC shadow segment did not track that change!
- if (g_GCShadowEnd <= g_GCShadow || g_shadow_lowest_address != g_lowest_address)
+ if (g_GCShadowEnd <= g_GCShadow || g_shadow_lowest_address != g_gc_lowest_address)
{
// No shadow stack, nothing to check.
return;
#define MP_LOCKS
+extern "C" uint32_t* g_gc_card_table;
+extern "C" uint8_t* g_gc_lowest_address;
+extern "C" uint8_t* g_gc_highest_address;
+extern "C" uint8_t* g_gc_ephemeral_low;
+extern "C" uint8_t* g_gc_ephemeral_high;
+
namespace WKS {
::IGCHeapInternal* CreateGCHeap();
class GCHeap;
IGCToCLR* g_theGCToCLR;
#endif // FEATURE_STANDALONE_GC
-/* global versions of the card table and brick table */
-GPTR_IMPL(uint32_t,g_card_table);
-
-/* absolute bounds of the GC memory */
-GPTR_IMPL_INIT(uint8_t,g_lowest_address,0);
-GPTR_IMPL_INIT(uint8_t,g_highest_address,0);
-
#ifdef GC_CONFIG_DRIVEN
GARY_IMPL(size_t, gc_global_mechanisms, MAX_GLOBAL_GC_MECHANISMS_COUNT);
#endif //GC_CONFIG_DRIVEN
#ifndef DACCESS_COMPILE
-uint8_t* g_ephemeral_low = (uint8_t*)1;
-uint8_t* g_ephemeral_high = (uint8_t*)~0;
-
#ifdef WRITE_BARRIER_CHECK
uint8_t* g_GCShadow;
uint8_t* g_GCShadowEnd;
uint8_t* g_shadow_lowest_address = NULL;
#endif
+uint32_t* g_gc_card_table;
+uint8_t* g_gc_lowest_address = 0;
+uint8_t* g_gc_highest_address = 0;
+uint8_t* g_gc_ephemeral_low = (uint8_t*)1;
+uint8_t* g_gc_ephemeral_high = (uint8_t*)~0;
+
VOLATILE(int32_t) m_GCLock = -1;
#ifdef GC_CONFIG_DRIVEN
assert(g_theGCToCLR != nullptr);
return g_theGCToCLR->DiagWalkBGCSurvivors(gcContext);
}
+
+inline void GCToEEInterface::StompWriteBarrier(WriteBarrierParameters* args)
+{
+ assert(g_theGCToCLR != nullptr);
+ g_theGCToCLR->StompWriteBarrier(args);
+}
+
#endif // __GCTOENV_EE_STANDALONE_INL__
// At the end of a background GC, gives the diagnostics code a chance to run.
virtual
void DiagWalkBGCSurvivors(void* gcContext) = 0;
+
+ // Informs the EE of changes to the location of the card table, potentially updating the write
+ // barrier if it needs to be updated.
+ virtual
+ void StompWriteBarrier(WriteBarrierParameters* args) = 0;
};
#endif // _GCINTERFACE_EE_H_
walk_for_loh = 3
} walk_surv_type;
+// Different operations that can be done by GCToEEInterface::StompWriteBarrier
+enum class WriteBarrierOp
+{
+ StompResize,
+ StompEphemeral,
+ Initialize
+};
+
+// Arguments to GCToEEInterface::StompWriteBarrier
+struct WriteBarrierParameters
+{
+ // The operation that StompWriteBarrier will perform.
+ WriteBarrierOp operation;
+
+ // Whether or not the runtime is currently suspended. If it is not,
+ // the EE will need to suspend it before bashing the write barrier.
+ // Used for all operations.
+ bool is_runtime_suspended;
+
+ // Whether or not the GC has moved the ephemeral generation to no longer
+ // be at the top of the heap. When the ephemeral generation is at the top
+ // of the heap, and the write barrier observes that a pointer is greater than
+ // g_ephemeral_low, it does not need to check that the pointer is less than
+ // g_ephemeral_high because there is nothing in the GC heap above the ephemeral
+ // generation. When this is not the case, however, the GC must inform the EE
+ // so that the EE can switch to a write barrier that checks that a pointer
+ // is both greater than g_ephemeral_low and less than g_ephemeral_high.
+ // Used for WriteBarrierOp::StompResize.
+ bool requires_upper_bounds_check;
+
+ // The new card table location. May or may not be the same as the previous
+ // card table. Used for WriteBarrierOp::Initialize and WriteBarrierOp::StompResize.
+ uint32_t* card_table;
+
+ // The heap's new low boundary. May or may not be the same as the previous
+ // value. Used for WriteBarrierOp::Initialize and WriteBarrierOp::StompResize.
+ uint8_t* lowest_address;
+
+ // The heap's new high boundary. May or may not be the same as the previous
+ // value. Used for WriteBarrierOp::Initialize and WriteBarrierOp::StompResize.
+ uint8_t* highest_address;
+
+ // The new start of the ephemeral generation.
+ // Used for WriteBarrierOp::StompEphemeral.
+ uint8_t* ephemeral_lo;
+
+ // The new end of the ephemeral generation.
+ // Used for WriteBarrierOp::StompEphemeral.
+ uint8_t* ephemeral_hi;
+};
+
#include "gcinterface.ee.h"
// The allocation context must be known to the VM for use in the allocation
// and the heap is actually recated.
void InitializeHeapType(bool bServerHeap);
-#ifndef DACCESS_COMPILE
-extern "C" {
-#endif // !DACCESS_COMPILE
-GPTR_DECL(uint8_t,g_lowest_address);
-GPTR_DECL(uint8_t,g_highest_address);
-GPTR_DECL(uint32_t,g_card_table);
-#ifndef DACCESS_COMPILE
-}
-#endif // !DACCESS_COMPILE
-
-extern "C" uint8_t* g_ephemeral_low;
-extern "C" uint8_t* g_ephemeral_high;
-
#ifdef WRITE_BARRIER_CHECK
//always defined, but should be 0 in Server GC
extern uint8_t* g_GCShadow;
return &dynamic_data_table [ gen_number ];
}
-extern "C" uint8_t* g_ephemeral_low;
-extern "C" uint8_t* g_ephemeral_high;
-
#define card_word_width ((size_t)32)
//
{
// if the dst is outside of the heap (unboxed value classes) then we
// simply exit
- if (((uint8_t*)dst < g_lowest_address) || ((uint8_t*)dst >= g_highest_address))
+ if (((uint8_t*)dst < g_gc_lowest_address) || ((uint8_t*)dst >= g_gc_highest_address))
return;
- if((uint8_t*)ref >= g_ephemeral_low && (uint8_t*)ref < g_ephemeral_high)
+ if((uint8_t*)ref >= g_gc_ephemeral_low && (uint8_t*)ref < g_gc_ephemeral_high)
{
// volatile is used here to prevent fetch of g_card_table from being reordered
// with g_lowest/highest_address check above. See comment in code:gc_heap::grow_brick_card_tables.
- uint8_t* pCardByte = (uint8_t *)*(volatile uint8_t **)(&g_card_table) + card_byte((uint8_t *)dst);
+ uint8_t* pCardByte = (uint8_t *)*(volatile uint8_t **)(&g_gc_card_table) + card_byte((uint8_t *)dst);
if(*pCardByte != 0xFF)
*pCardByte = 0xFF;
}
{
}
+void GCToEEInterface::StompWriteBarrier(WriteBarrierParameters* args)
+{
+}
+
void FinalizerThread::EnableFinalization()
{
// Signal to finalizer thread that there are objects to finalize
return false;
}
-void StompWriteBarrierEphemeral(bool /* isRuntimeSuspended */)
-{
-}
-
-void StompWriteBarrierResize(bool /* isRuntimeSuspended */, bool /*bReqUpperBoundsCheck*/)
-{
-}
-
bool IsGCThread()
{
return false;
* to the standard code-manager spec.
*/
+#ifndef FEATURE_PAL
#include "utilcode.h" // For _ASSERTE()
+#endif //!FEATURE_PAL
#include "gcdump.h"
/*****************************************************************************/
#ifdef _TARGET_X86_
/*****************************************************************************/
+#ifndef FEATURE_PAL
#include "utilcode.h" // For _ASSERTE()
+#endif //!FEATURE_PAL
#include "gcdump.h"
#define YYAPI_TOKENTYPE int
#define YYAPI_TOKENEME(t) (t)
#define YYAPI_TOKENNONE -1
-#define YYAPI_TOKENSTR(t) (sprintf(yytokbuf, "%d", t), yytokbuf)
+#define YYAPI_TOKENSTR(t) (sprintf_s(yytokbuf, _countof(yytokbuf), "%d", t), yytokbuf)
#define YYAPI_VALUENAME yylval
#define YYAPI_VALUETYPE YYSTYPE
#define YYAPI_VALUEOF(v) (v)
/*
if(ehInfo->GetFlags() & ERR_OUT_OF_CODE)
{
- sprintf(szString,"%s// WARNING: Boundary outside the method code",g_szAsmCodeIndent);
+ _snprintf_s(szString, _countof(szString), _TRUNCATE, "%s// WARNING: Boundary outside the method code",g_szAsmCodeIndent);
printLine(GUICookie,szString);
}
*/
/*
BOOL fHasEmbeddedSource=FALSE;
((ISymUnmanagedDocument*)(pParam->pLCD->FileToken))->HasEmbeddedSource(&fHasEmbeddedSource);
- sprintf(szString,"%s// PDB has %sembedded source",g_szAsmCodeIndent,
- fHasEmbeddedSource ? "" : "no ");
+ _snprintf_s(szString, _countof(szString), _TRUNCATE, "%s// PDB has %sembedded source",g_szAsmCodeIndent,
+ fHasEmbeddedSource ? "" : "no ");
printLine(pParam->GUICookie,szString);
*/
}
void* GUICookie = (void*)wzFileName;
BYTE* pbData;
printLine(GUICookie,"");
- sprintf(szString,"// ========== Win32 Resource Entries (%d) ========",ulNumResNodes);
+ sprintf_s(szString, _countof(szString), "// ========== Win32 Resource Entries (%d) ========",ulNumResNodes);
for(i=0; i < ulNumResNodes; i++)
{
printLine(GUICookie,"");
- sprintf(szString,"// Res.# %d Type=0x%X Name=0x%X Lang=0x%X DataOffset=0x%X DataLength=%d",
+ sprintf_s(szString, _countof(szString), "// Res.# %d Type=0x%X Name=0x%X Lang=0x%X DataOffset=0x%X DataLength=%d",
i+1,
g_prResNodePtr[i]->ResHdr.dwTypeID,
g_prResNodePtr[i]->ResHdr.dwNameID,
if(pos >= 0)
{
//char sz[32];
- //sprintf(sz,"%d:%d",strFind.chrg.cpMin,strFind.chrg.cpMax);
+ //sprintf_s(sz, _countof(sz), "%d:%d",strFind.chrg.cpMin,strFind.chrg.cpMax);
//MessageBox(hwnd,sz,"Find",MB_OK);
SendMessage(hwndLB,EM_SETSEL,(WPARAM)pos,(LPARAM)(pos+wcslen(lpfr->lpstrFindWhat)));
}
{
#ifdef DEBUG
char message[256];
- sprintf(message, "NYI: Unimplemented node type %s\n", GenTree::NodeName(treeNode->OperGet()));
+ _snprintf_s(message, _countof(message), _TRUNCATE, "NYI: Unimplemented node type %s\n",
+ GenTree::NodeName(treeNode->OperGet()));
notYetImplemented(message, __FILE__, __LINE__);
#else
NYI("unimplemented node");
{
#ifdef DEBUG
char message[256];
- sprintf(message, "Unimplemented node type %s\n", GenTree::NodeName(treeNode->OperGet()));
+ _snprintf_s(message, _countof(message), _TRUNCATE, "Unimplemented node type %s\n",
+ GenTree::NodeName(treeNode->OperGet()));
#endif
assert(!"Unknown node in codegen");
}
{
#ifdef DEBUG
char message[256];
- sprintf(message, "Unimplemented node type %s\n", GenTree::NodeName(treeNode->OperGet()));
+ _snprintf_s(message, _countof(message), _TRUNCATE, "Unimplemented node type %s\n",
+ GenTree::NodeName(treeNode->OperGet()));
#endif
assert(!"Unknown node in codegen");
}
{'"', """},
{0, nullptr}
};
-// clang-formt on
+// clang-format on
-const char* Compiler::fgProcessEscapes(const char* nameIn, escapeMapping_t* map)
+const char* Compiler::fgProcessEscapes(const char* nameIn, escapeMapping_t* map)
{
- const char* nameOut = nameIn;
- unsigned lengthOut;
- unsigned index;
- bool match;
- bool subsitutionRequired;
- const char* pChar;
-
- lengthOut = 1;
+ const char* nameOut = nameIn;
+ unsigned lengthOut;
+ unsigned index;
+ bool match;
+ bool subsitutionRequired;
+ const char* pChar;
+
+ lengthOut = 1;
subsitutionRequired = false;
- pChar = nameIn;
+ pChar = nameIn;
while (*pChar != '\0')
{
match = false;
if (subsitutionRequired)
{
- char* newName = (char*) compGetMemA(lengthOut, CMK_DebugOnly);
- char* pDest;
+ char* newName = (char*)compGetMemA(lengthOut, CMK_DebugOnly);
+ char* pDest;
pDest = newName;
pChar = nameIn;
while (*pChar != '\0')
pChar++;
}
*pDest++ = '\0';
- nameOut = (const char*) newName;
+ nameOut = (const char*)newName;
}
return nameOut;
// Opens a file to which a flowgraph can be dumped, whose name is based on the current
// config vales.
-FILE* Compiler::fgOpenFlowGraphFile(bool* wbDontClose, Phases phase, LPCWSTR type)
+FILE* Compiler::fgOpenFlowGraphFile(bool* wbDontClose, Phases phase, LPCWSTR type)
{
- FILE* fgxFile;
- LPCWSTR pattern = nullptr;
- LPCWSTR filename = nullptr;
- LPCWSTR pathname = nullptr;
- const char* escapedString;
- bool createDuplicateFgxFiles = true;
+ FILE* fgxFile;
+ LPCWSTR pattern = nullptr;
+ LPCWSTR filename = nullptr;
+ LPCWSTR pathname = nullptr;
+ const char* escapedString;
+ bool createDuplicateFgxFiles = true;
#ifdef DEBUG
if (opts.jitFlags->IsSet(JitFlags::JIT_FLAG_PREJIT))
{
- pattern = JitConfig.NgenDumpFg();
+ pattern = JitConfig.NgenDumpFg();
filename = JitConfig.NgenDumpFgFile();
pathname = JitConfig.NgenDumpFgDir();
}
else
{
- pattern = JitConfig.JitDumpFg();
+ pattern = JitConfig.JitDumpFg();
filename = JitConfig.JitDumpFgFile();
pathname = JitConfig.JitDumpFgDir();
}
#endif // DEBUG
- if (fgBBcount <= 1) {
+ if (fgBBcount <= 1)
+ {
return nullptr;
-}
+ }
- if (pattern == nullptr) {
+ if (pattern == nullptr)
+ {
return nullptr;
-}
+ }
- if (wcslen(pattern) == 0) {
+ if (wcslen(pattern) == 0)
+ {
return nullptr;
-}
+ }
LPCWSTR phasePattern = JitConfig.JitDumpFgPhase();
- LPCWSTR phaseName = PhaseShortNames[phase];
+ LPCWSTR phaseName = PhaseShortNames[phase];
if (phasePattern == nullptr)
{
if (phase != PHASE_DETERMINE_FIRST_COLD_BLOCK)
{
while ((*pattern != W(':')) && (*pattern != W('*')))
{
- if (*pattern != *className) {
+ if (*pattern != *className)
+ {
return nullptr;
-}
+ }
pattern++;
className++;
}
else
{
- if (*className != 0) {
+ if (*className != 0)
+ {
return nullptr;
-}
- }
+ }
}
- if (*pattern != W(':')) {
+ }
+ if (*pattern != W(':'))
+ {
return nullptr;
}
{
while ((*pattern != 0) && (*pattern != W('*')))
{
- if (*pattern != *methodName) {
+ if (*pattern != *methodName)
+ {
return nullptr;
-}
+ }
pattern++;
methodName++;
}
else
{
- if (*methodName != 0) {
+ if (*methodName != 0)
+ {
return nullptr;
-}
- }
+ }
}
- if (*pattern != 0) {
+ }
+ if (*pattern != 0)
+ {
return nullptr;
}
}
{
createDuplicateFgxFiles = true;
-ONE_FILE_PER_METHOD:;
+ ONE_FILE_PER_METHOD:;
- escapedString = fgProcessEscapes(info.compFullName, s_EscapeFileMapping);
+ escapedString = fgProcessEscapes(info.compFullName, s_EscapeFileMapping);
size_t wCharCount = strlen(escapedString) + wcslen(phaseName) + 1 + strlen("~999") + wcslen(type) + 1;
if (pathname != nullptr)
{
wCharCount += wcslen(pathname) + 1;
}
- filename = (LPCWSTR) alloca(wCharCount * sizeof(WCHAR));
+ filename = (LPCWSTR)alloca(wCharCount * sizeof(WCHAR));
if (pathname != nullptr)
{
swprintf_s((LPWSTR)filename, wCharCount, W("%s\\%S-%s.%s"), pathname, escapedString, phaseName, type);
{
swprintf_s((LPWSTR)filename, wCharCount, W("%S.%s"), escapedString, type);
}
- fgxFile = _wfopen(filename, W("r")); // Check if this file already exists
+ fgxFile = _wfopen(filename, W("r")); // Check if this file already exists
if (fgxFile != nullptr)
{
// For Generic methods we will have both hot and cold versions
{
swprintf_s((LPWSTR)filename, wCharCount, W("%S~%d.%s"), escapedString, i, type);
}
- fgxFile = _wfopen(filename, W("r")); // Check if this file exists
- if (fgxFile == nullptr) {
+ fgxFile = _wfopen(filename, W("r")); // Check if this file exists
+ if (fgxFile == nullptr)
+ {
break;
- }
+ }
}
// If we have already created 1000 files with this name then just fail
if (fgxFile != nullptr)
return nullptr;
}
}
- fgxFile = _wfopen(filename, W("a+"));
+ fgxFile = _wfopen(filename, W("a+"));
*wbDontClose = false;
}
else if (wcscmp(filename, W("stdout")) == 0)
{
- fgxFile = jitstdout;
+ fgxFile = jitstdout;
*wbDontClose = true;
}
else if (wcscmp(filename, W("stderr")) == 0)
{
- fgxFile = stderr;
+ fgxFile = stderr;
*wbDontClose = true;
}
else
{
LPCWSTR origFilename = filename;
- size_t wCharCount = wcslen(origFilename) + wcslen(type) + 2;
+ size_t wCharCount = wcslen(origFilename) + wcslen(type) + 2;
if (pathname != nullptr)
{
wCharCount += wcslen(pathname) + 1;
}
- filename = (LPCWSTR) alloca(wCharCount * sizeof(WCHAR));
+ filename = (LPCWSTR)alloca(wCharCount * sizeof(WCHAR));
if (pathname != nullptr)
{
swprintf_s((LPWSTR)filename, wCharCount, W("%s\\%s.%s"), pathname, origFilename, type);
{
swprintf_s((LPWSTR)filename, wCharCount, W("%s.%s"), origFilename, type);
}
- fgxFile = _wfopen(filename, W("a+"));
+ fgxFile = _wfopen(filename, W("a+"));
*wbDontClose = false;
}
// phases.
// COMPlus_JitDumpFgDot Set to non-zero to emit Dot instead of Xml Flowgraph dump. (Default is xml format.)
-bool Compiler::fgDumpFlowGraph(Phases phase)
+bool Compiler::fgDumpFlowGraph(Phases phase)
{
- bool result = false;
- bool dontClose = false;
- bool createDotFile = false;
+ bool result = false;
+ bool dontClose = false;
+ bool createDotFile = false;
if (JitConfig.JitDumpFgDot())
{
createDotFile = true;
}
- FILE* fgxFile = fgOpenFlowGraphFile(&dontClose, phase, createDotFile ? W("dot") : W("fgx"));
+ FILE* fgxFile = fgOpenFlowGraphFile(&dontClose, phase, createDotFile ? W("dot") : W("fgx"));
if (fgxFile == nullptr)
{
return false;
}
- bool validWeights = fgHaveValidEdgeWeights;
- unsigned calledCount = max(fgCalledWeight, BB_UNITY_WEIGHT) / BB_UNITY_WEIGHT;
- double weightDivisor = (double) (calledCount * BB_UNITY_WEIGHT);
- const char* escapedString;
- const char* regionString = "NONE";
+ bool validWeights = fgHaveValidEdgeWeights;
+ unsigned calledCount = max(fgCalledWeight, BB_UNITY_WEIGHT) / BB_UNITY_WEIGHT;
+ double weightDivisor = (double)(calledCount * BB_UNITY_WEIGHT);
+ const char* escapedString;
+ const char* regionString = "NONE";
- if (info.compMethodInfo->regionKind == CORINFO_REGION_HOT)
+ if (info.compMethodInfo->regionKind == CORINFO_REGION_HOT)
{
- regionString="HOT";
+ regionString = "HOT";
}
else if (info.compMethodInfo->regionKind == CORINFO_REGION_COLD)
{
- regionString="COLD";
+ regionString = "COLD";
}
else if (info.compMethodInfo->regionKind == CORINFO_REGION_JIT)
{
- regionString="JIT";
+ regionString = "JIT";
}
if (createDotFile)
}
else
{
- fprintf(fgxFile, "<method");
+ fprintf(fgxFile, "<method");
escapedString = fgProcessEscapes(info.compFullName, s_EscapeMapping);
fprintf(fgxFile, "\n name=\"%s\"", escapedString);
fprintf(fgxFile, "\n firstColdBlock=\"%d\"", fgFirstColdBlock->bbNum);
}
- fprintf(fgxFile, ">");
+ fprintf(fgxFile, ">");
fprintf(fgxFile, "\n <blocks");
fprintf(fgxFile, "\n blockCount=\"%d\"", fgBBcount);
- fprintf(fgxFile, ">");
+ fprintf(fgxFile, ">");
}
- static const char* kindImage[] = { "EHFINALLYRET", "EHFILTERRET", "EHCATCHRET",
- "THROW", "RETURN", "NONE", "ALWAYS", "LEAVE",
- "CALLFINALLY", "COND", "SWITCH" };
+ static const char* kindImage[] = {"EHFINALLYRET", "EHFILTERRET", "EHCATCHRET", "THROW", "RETURN", "NONE",
+ "ALWAYS", "LEAVE", "CALLFINALLY", "COND", "SWITCH"};
BasicBlock* block;
unsigned blockOrdinal;
- for (block = fgFirstBB , blockOrdinal = 1;
- block != nullptr;
- block = block->bbNext, blockOrdinal++)
+ for (block = fgFirstBB, blockOrdinal = 1; block != nullptr; block = block->bbNext, blockOrdinal++)
{
if (createDotFile)
{
// Add constraint edges to try to keep nodes ordered.
// It seems to work best if these edges are all created first.
- switch(block->bbJumpKind)
+ switch (block->bbJumpKind)
{
- case BBJ_COND:
- case BBJ_NONE:
- assert(block->bbNext != nullptr);
- fprintf(fgxFile, " BB%02u -> BB%02u\n", block->bbNum, block->bbNext->bbNum);
- break;
- default:
- // These may or may not have an edge to the next block.
- // Add a transparent edge to keep nodes ordered.
- if (block->bbNext != nullptr)
- {
- fprintf(fgxFile, " BB%02u -> BB%02u [arrowtail=none,color=transparent]\n", block->bbNum, block->bbNext->bbNum);
- }
+ case BBJ_COND:
+ case BBJ_NONE:
+ assert(block->bbNext != nullptr);
+ fprintf(fgxFile, " BB%02u -> BB%02u\n", block->bbNum, block->bbNext->bbNum);
+ break;
+ default:
+ // These may or may not have an edge to the next block.
+ // Add a transparent edge to keep nodes ordered.
+ if (block->bbNext != nullptr)
+ {
+ fprintf(fgxFile, " BB%02u -> BB%02u [arrowtail=none,color=transparent]\n", block->bbNum,
+ block->bbNext->bbNum);
+ }
}
}
else
{
- fprintf(fgxFile,"\n <block");
- fprintf(fgxFile,"\n id=\"%d\"", block->bbNum);
- fprintf(fgxFile,"\n ordinal=\"%d\"", blockOrdinal);
- fprintf(fgxFile,"\n jumpKind=\"%s\"", kindImage[block->bbJumpKind]);
+ fprintf(fgxFile, "\n <block");
+ fprintf(fgxFile, "\n id=\"%d\"", block->bbNum);
+ fprintf(fgxFile, "\n ordinal=\"%d\"", blockOrdinal);
+ fprintf(fgxFile, "\n jumpKind=\"%s\"", kindImage[block->bbJumpKind]);
if (block->hasTryIndex())
{
- fprintf(fgxFile,"\n inTry=\"%s\"", "true");
+ fprintf(fgxFile, "\n inTry=\"%s\"", "true");
}
if (block->hasHndIndex())
{
- fprintf(fgxFile,"\n inHandler=\"%s\"", "true");
+ fprintf(fgxFile, "\n inHandler=\"%s\"", "true");
}
- if (((fgFirstBB->bbFlags & BBF_PROF_WEIGHT) != 0) &&
- ((block->bbFlags & BBF_COLD) == 0) )
+ if (((fgFirstBB->bbFlags & BBF_PROF_WEIGHT) != 0) && ((block->bbFlags & BBF_COLD) == 0))
{
- fprintf(fgxFile,"\n hot=\"true\"");
+ fprintf(fgxFile, "\n hot=\"true\"");
}
if (block->bbFlags & (BBF_HAS_NEWOBJ | BBF_HAS_NEWARRAY))
{
- fprintf(fgxFile,"\n callsNew=\"true\"");
+ fprintf(fgxFile, "\n callsNew=\"true\"");
}
if (block->bbFlags & BBF_LOOP_HEAD)
{
- fprintf(fgxFile,"\n loopHead=\"true\"");
+ fprintf(fgxFile, "\n loopHead=\"true\"");
}
- fprintf(fgxFile,"\n weight=");
- fprintfDouble(fgxFile, ((double) block->bbWeight) / weightDivisor);
- fprintf(fgxFile,"\n codeEstimate=\"%d\"", fgGetCodeEstimate(block));
- fprintf(fgxFile,"\n startOffset=\"%d\"", block->bbCodeOffs);
- fprintf(fgxFile,"\n endOffset=\"%d\"", block->bbCodeOffsEnd);
- fprintf(fgxFile, ">");
- fprintf(fgxFile,"\n </block>");
+ fprintf(fgxFile, "\n weight=");
+ fprintfDouble(fgxFile, ((double)block->bbWeight) / weightDivisor);
+ fprintf(fgxFile, "\n codeEstimate=\"%d\"", fgGetCodeEstimate(block));
+ fprintf(fgxFile, "\n startOffset=\"%d\"", block->bbCodeOffs);
+ fprintf(fgxFile, "\n endOffset=\"%d\"", block->bbCodeOffsEnd);
+ fprintf(fgxFile, ">");
+ fprintf(fgxFile, "\n </block>");
}
}
fprintf(fgxFile, "\n <edges");
fprintf(fgxFile, "\n edgeCount=\"%d\"", fgEdgeCount);
- fprintf(fgxFile, ">");
+ fprintf(fgxFile, ">");
}
- unsigned edgeNum = 1;
+ unsigned edgeNum = 1;
BasicBlock* bTarget;
for (bTarget = fgFirstBB; bTarget != nullptr; bTarget = bTarget->bbNext)
{
}
else
{
- targetWeightDivisor = (double) bTarget->bbWeight;
+ targetWeightDivisor = (double)bTarget->bbWeight;
}
flowList* edge;
for (edge = bTarget->bbPreds; edge != nullptr; edge = edge->flNext, edgeNum++)
{
- BasicBlock* bSource = edge->flBlock;
- double sourceWeightDivisor;
+ BasicBlock* bSource = edge->flBlock;
+ double sourceWeightDivisor;
if (bSource->bbWeight == BB_ZERO_WEIGHT)
{
sourceWeightDivisor = 1.0;
}
else
{
- sourceWeightDivisor = (double) bSource->bbWeight;
+ sourceWeightDivisor = (double)bSource->bbWeight;
}
if (createDotFile)
{
}
else
{
- fprintf(fgxFile,"\n <edge");
- fprintf(fgxFile,"\n id=\"%d\"", edgeNum);
- fprintf(fgxFile,"\n source=\"%d\"", bSource->bbNum);
- fprintf(fgxFile,"\n target=\"%d\"", bTarget->bbNum);
+ fprintf(fgxFile, "\n <edge");
+ fprintf(fgxFile, "\n id=\"%d\"", edgeNum);
+ fprintf(fgxFile, "\n source=\"%d\"", bSource->bbNum);
+ fprintf(fgxFile, "\n target=\"%d\"", bTarget->bbNum);
if (bSource->bbJumpKind == BBJ_SWITCH)
{
if (edge->flDupCount >= 2)
{
- fprintf(fgxFile,"\n switchCases=\"%d\"", edge->flDupCount);
+ fprintf(fgxFile, "\n switchCases=\"%d\"", edge->flDupCount);
}
if (bSource->bbJumpSwt->getDefault() == bTarget)
{
- fprintf(fgxFile,"\n switchDefault=\"true\"");
+ fprintf(fgxFile, "\n switchDefault=\"true\"");
}
}
if (validWeights)
{
unsigned edgeWeight = (edge->flEdgeWeightMin + edge->flEdgeWeightMax) / 2;
- fprintf(fgxFile,"\n weight=");
- fprintfDouble(fgxFile, ((double) edgeWeight) / weightDivisor);
+ fprintf(fgxFile, "\n weight=");
+ fprintfDouble(fgxFile, ((double)edgeWeight) / weightDivisor);
if (edge->flEdgeWeightMin != edge->flEdgeWeightMax)
{
- fprintf(fgxFile,"\n minWeight=");
- fprintfDouble(fgxFile, ((double) edge->flEdgeWeightMin) / weightDivisor);
- fprintf(fgxFile,"\n maxWeight=");
- fprintfDouble(fgxFile, ((double) edge->flEdgeWeightMax) / weightDivisor);
+ fprintf(fgxFile, "\n minWeight=");
+ fprintfDouble(fgxFile, ((double)edge->flEdgeWeightMin) / weightDivisor);
+ fprintf(fgxFile, "\n maxWeight=");
+ fprintfDouble(fgxFile, ((double)edge->flEdgeWeightMax) / weightDivisor);
}
if (edgeWeight > 0)
{
if (edgeWeight < bSource->bbWeight)
{
- fprintf(fgxFile,"\n out=");
- fprintfDouble(fgxFile, ((double) edgeWeight) / sourceWeightDivisor );
+ fprintf(fgxFile, "\n out=");
+ fprintfDouble(fgxFile, ((double)edgeWeight) / sourceWeightDivisor);
}
if (edgeWeight < bTarget->bbWeight)
{
- fprintf(fgxFile,"\n in=");
- fprintfDouble(fgxFile, ((double) edgeWeight) / targetWeightDivisor);
+ fprintf(fgxFile, "\n in=");
+ fprintfDouble(fgxFile, ((double)edgeWeight) / targetWeightDivisor);
}
}
}
}
if (!createDotFile)
{
- fprintf(fgxFile, ">");
- fprintf(fgxFile,"\n </edge>");
+ fprintf(fgxFile, ">");
+ fprintf(fgxFile, "\n </edge>");
}
}
}
/*****************************************************************************/
#ifdef DEBUG
-void Compiler::fgDispReach()
+void Compiler::fgDispReach()
{
printf("------------------------------------------------\n");
printf("BBnum Reachable by \n");
}
}
-void Compiler::fgDispDoms()
+void Compiler::fgDispDoms()
{
// Don't bother printing this when we have a large number of BasicBlocks in the method
if (fgBBcount > 256)
/*****************************************************************************/
-void Compiler::fgTableDispBasicBlock(BasicBlock* block,
- int ibcColWidth /* = 0 */)
+void Compiler::fgTableDispBasicBlock(BasicBlock* block, int ibcColWidth /* = 0 */)
{
- unsigned flags = block->bbFlags;
+ unsigned flags = block->bbFlags;
- unsigned bbNumMax = compIsForInlining() ? impInlineInfo->InlinerCompiler->fgBBNumMax : fgBBNumMax;
- int maxBlockNumWidth = CountDigits(bbNumMax);
- maxBlockNumWidth = max(maxBlockNumWidth, 2);
- int blockNumWidth = CountDigits(block->bbNum);
- blockNumWidth = max(blockNumWidth, 2);
- int blockNumPadding = maxBlockNumWidth - blockNumWidth;
+ unsigned bbNumMax = compIsForInlining() ? impInlineInfo->InlinerCompiler->fgBBNumMax : fgBBNumMax;
+ int maxBlockNumWidth = CountDigits(bbNumMax);
+ maxBlockNumWidth = max(maxBlockNumWidth, 2);
+ int blockNumWidth = CountDigits(block->bbNum);
+ blockNumWidth = max(blockNumWidth, 2);
+ int blockNumPadding = maxBlockNumWidth - blockNumWidth;
- printf("BB%02u%*s [%08p] %2u",
- block->bbNum,
- blockNumPadding, "",
- dspPtr(block),
- block->bbRefs);
+ printf("BB%02u%*s [%08p] %2u", block->bbNum, blockNumPadding, "", dspPtr(block), block->bbRefs);
//
// Display EH 'try' region index
// Display block branch target
//
- if (flags & BBF_REMOVED)
+ if (flags & BBF_REMOVED)
{
- printf( "[removed] ");
+ printf("[removed] ");
}
else
{
switch (block->bbJumpKind)
{
- case BBJ_COND:
- printf("-> BB%02u%*s ( cond )", block->bbJumpDest->bbNum, maxBlockNumWidth - max(CountDigits(block->bbJumpDest->bbNum), 2), "");
- break;
+ case BBJ_COND:
+ printf("-> BB%02u%*s ( cond )", block->bbJumpDest->bbNum,
+ maxBlockNumWidth - max(CountDigits(block->bbJumpDest->bbNum), 2), "");
+ break;
- case BBJ_CALLFINALLY:
- printf("-> BB%02u%*s (callf )", block->bbJumpDest->bbNum, maxBlockNumWidth - max(CountDigits(block->bbJumpDest->bbNum), 2), "");
- break;
+ case BBJ_CALLFINALLY:
+ printf("-> BB%02u%*s (callf )", block->bbJumpDest->bbNum,
+ maxBlockNumWidth - max(CountDigits(block->bbJumpDest->bbNum), 2), "");
+ break;
- case BBJ_ALWAYS:
- if (flags & BBF_KEEP_BBJ_ALWAYS)
- {
- printf("-> BB%02u%*s (ALWAYS)", block->bbJumpDest->bbNum, maxBlockNumWidth - max(CountDigits(block->bbJumpDest->bbNum), 2), "");
- }
- else
- {
- printf("-> BB%02u%*s (always)", block->bbJumpDest->bbNum, maxBlockNumWidth - max(CountDigits(block->bbJumpDest->bbNum), 2), "");
- }
- break;
+ case BBJ_ALWAYS:
+ if (flags & BBF_KEEP_BBJ_ALWAYS)
+ {
+ printf("-> BB%02u%*s (ALWAYS)", block->bbJumpDest->bbNum,
+ maxBlockNumWidth - max(CountDigits(block->bbJumpDest->bbNum), 2), "");
+ }
+ else
+ {
+ printf("-> BB%02u%*s (always)", block->bbJumpDest->bbNum,
+ maxBlockNumWidth - max(CountDigits(block->bbJumpDest->bbNum), 2), "");
+ }
+ break;
- case BBJ_LEAVE:
- printf("-> BB%02u%*s (leave )", block->bbJumpDest->bbNum, maxBlockNumWidth - max(CountDigits(block->bbJumpDest->bbNum), 2), "");
- break;
+ case BBJ_LEAVE:
+ printf("-> BB%02u%*s (leave )", block->bbJumpDest->bbNum,
+ maxBlockNumWidth - max(CountDigits(block->bbJumpDest->bbNum), 2), "");
+ break;
- case BBJ_EHFINALLYRET:
- printf( "%*s (finret)", maxBlockNumWidth - 2, "");
- break;
+ case BBJ_EHFINALLYRET:
+ printf("%*s (finret)", maxBlockNumWidth - 2, "");
+ break;
- case BBJ_EHFILTERRET:
- printf( "%*s (fltret)", maxBlockNumWidth - 2, "");
- break;
+ case BBJ_EHFILTERRET:
+ printf("%*s (fltret)", maxBlockNumWidth - 2, "");
+ break;
- case BBJ_EHCATCHRET:
- printf("-> BB%02u%*s ( cret )", block->bbJumpDest->bbNum, maxBlockNumWidth - max(CountDigits(block->bbJumpDest->bbNum), 2), "");
- break;
+ case BBJ_EHCATCHRET:
+ printf("-> BB%02u%*s ( cret )", block->bbJumpDest->bbNum,
+ maxBlockNumWidth - max(CountDigits(block->bbJumpDest->bbNum), 2), "");
+ break;
- case BBJ_THROW:
- printf( "%*s (throw )", maxBlockNumWidth - 2, "");
- break;
+ case BBJ_THROW:
+ printf("%*s (throw )", maxBlockNumWidth - 2, "");
+ break;
- case BBJ_RETURN:
- printf( "%*s (return)", maxBlockNumWidth - 2, "");
- break;
+ case BBJ_RETURN:
+ printf("%*s (return)", maxBlockNumWidth - 2, "");
+ break;
- default:
- printf( "%*s ", maxBlockNumWidth - 2, "");
- break;
+ default:
+ printf("%*s ", maxBlockNumWidth - 2, "");
+ break;
- case BBJ_SWITCH:
- printf("->");
-
- unsigned jumpCnt;
- jumpCnt = block->bbJumpSwt->bbsCount;
- BasicBlock** jumpTab;
- jumpTab = block->bbJumpSwt->bbsDstTab;
- int switchWidth;
- switchWidth = 0;
- do
- {
- printf("%cBB%02u",
- (jumpTab == block->bbJumpSwt->bbsDstTab) ? ' ' : ',',
- (*jumpTab)->bbNum);
- switchWidth += 1 /* space/comma */ + 2 /* BB */ + max(CountDigits((*jumpTab)->bbNum), 2);
- }
- while (++jumpTab, --jumpCnt);
+ case BBJ_SWITCH:
+ printf("->");
- if (switchWidth < 7)
- {
- printf("%*s", 8 - switchWidth, "");
- }
+ unsigned jumpCnt;
+ jumpCnt = block->bbJumpSwt->bbsCount;
+ BasicBlock** jumpTab;
+ jumpTab = block->bbJumpSwt->bbsDstTab;
+ int switchWidth;
+ switchWidth = 0;
+ do
+ {
+ printf("%cBB%02u", (jumpTab == block->bbJumpSwt->bbsDstTab) ? ' ' : ',', (*jumpTab)->bbNum);
+ switchWidth += 1 /* space/comma */ + 2 /* BB */ + max(CountDigits((*jumpTab)->bbNum), 2);
+ } while (++jumpTab, --jumpCnt);
- printf(" (switch)");
- break;
+ if (switchWidth < 7)
+ {
+ printf("%*s", 8 - switchWidth, "");
+ }
+
+ printf(" (switch)");
+ break;
}
}
switch (block->bbCatchTyp)
{
- case BBCT_NONE: break;
- case BBCT_FAULT: printf("fault "); cnt += 6; break;
- case BBCT_FINALLY: printf("finally "); cnt += 8; break;
- case BBCT_FILTER: printf("filter "); cnt += 7; break;
- case BBCT_FILTER_HANDLER: printf("filtHnd "); cnt += 8; break;
- default: printf("catch "); cnt += 6; break;
+ case BBCT_NONE:
+ break;
+ case BBCT_FAULT:
+ printf("fault ");
+ cnt += 6;
+ break;
+ case BBCT_FINALLY:
+ printf("finally ");
+ cnt += 8;
+ break;
+ case BBCT_FILTER:
+ printf("filter ");
+ cnt += 7;
+ break;
+ case BBCT_FILTER_HANDLER:
+ printf("filtHnd ");
+ cnt += 8;
+ break;
+ default:
+ printf("catch ");
+ cnt += 6;
+ break;
}
if (block->bbCatchTyp != BBCT_NONE)
EHblkDsc* HBtab;
EHblkDsc* HBtabEnd;
- for (HBtab = compHndBBtab, HBtabEnd = compHndBBtab + compHndBBtabCount;
- HBtab < HBtabEnd;
- HBtab++)
+ for (HBtab = compHndBBtab, HBtabEnd = compHndBBtab + compHndBBtabCount; HBtab < HBtabEnd; HBtab++)
{
if (HBtab->ebdTryBeg == block)
{
EHblkDsc* HBtab;
EHblkDsc* HBtabEnd;
- for (HBtab = compHndBBtab, HBtabEnd = compHndBBtab + compHndBBtabCount;
- HBtab < HBtabEnd;
- HBtab++)
+ for (HBtab = compHndBBtab, HBtabEnd = compHndBBtab + compHndBBtabCount; HBtab < HBtabEnd; HBtab++)
{
if (HBtab->ebdTryLast == block)
{
Dump blocks from firstBlock to lastBlock.
*/
-void Compiler::fgDispBasicBlocks(BasicBlock* firstBlock,
- BasicBlock* lastBlock,
- bool dumpTrees)
+void Compiler::fgDispBasicBlocks(BasicBlock* firstBlock, BasicBlock* lastBlock, bool dumpTrees)
{
BasicBlock* block;
if (block->bbFlags & BBF_PROF_WEIGHT)
{
int thisIbcWidth = CountDigits(block->bbWeight);
- ibcColWidth = max(ibcColWidth, thisIbcWidth);
+ ibcColWidth = max(ibcColWidth, thisIbcWidth);
}
- if (block == lastBlock) {
+ if (block == lastBlock)
+ {
break;
- }
+ }
}
if (ibcColWidth > 0)
{
ibcColWidth = max(ibcColWidth, 3) + 1; // + 1 for the leading space
}
- unsigned bbNumMax = compIsForInlining() ? impInlineInfo->InlinerCompiler->fgBBNumMax : fgBBNumMax;
- int maxBlockNumWidth = CountDigits(bbNumMax);
- maxBlockNumWidth = max(maxBlockNumWidth, 2);
+ unsigned bbNumMax = compIsForInlining() ? impInlineInfo->InlinerCompiler->fgBBNumMax : fgBBNumMax;
+ int maxBlockNumWidth = CountDigits(bbNumMax);
+ maxBlockNumWidth = max(maxBlockNumWidth, 2);
padWidth += maxBlockNumWidth - 2; // Account for functions with a large number of blocks.
+ // clang-format off
+
printf("\n");
printf("------%*s------------------------------------%*s-----------------------%*s----------------------------------------\n",
padWidth, "------------",
ibcColWidth, "------------",
maxBlockNumWidth, "----");
- for (block = firstBlock;
- block;
- block = block->bbNext)
+ // clang-format on
+
+ for (block = firstBlock; block; block = block->bbNext)
{
// First, do some checking on the bbPrev links
if (block->bbPrev)
if (block == fgFirstColdBlock)
{
- printf("~~~~~~%*s~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~%*s~~~~~~~~~~~~~~~~~~~~~~~%*s~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n",
- padWidth, "~~~~~~~~~~~~",
- ibcColWidth, "~~~~~~~~~~~~",
- maxBlockNumWidth, "~~~~");
+ printf("~~~~~~%*s~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~%*s~~~~~~~~~~~~~~~~~~~~~~~%*s~~~~~~~~~~~~~~~~~~~~~~~~~"
+ "~~~~~~~~~~~~~~~\n",
+ padWidth, "~~~~~~~~~~~~", ibcColWidth, "~~~~~~~~~~~~", maxBlockNumWidth, "~~~~");
}
#if FEATURE_EH_FUNCLETS
if (block == fgFirstFuncletBB)
{
- printf("++++++%*s++++++++++++++++++++++++++++++++++++%*s+++++++++++++++++++++++%*s++++++++++++++++++++++++++++++++++++++++ funclets follow\n",
- padWidth, "++++++++++++",
- ibcColWidth, "++++++++++++",
- maxBlockNumWidth, "++++");
+ printf("++++++%*s++++++++++++++++++++++++++++++++++++%*s+++++++++++++++++++++++%*s+++++++++++++++++++++++++"
+ "+++++++++++++++ funclets follow\n",
+ padWidth, "++++++++++++", ibcColWidth, "++++++++++++", maxBlockNumWidth, "++++");
}
#endif // FEATURE_EH_FUNCLETS
fgTableDispBasicBlock(block, ibcColWidth);
- if (block == lastBlock) {
+ if (block == lastBlock)
+ {
break;
- }
+ }
}
- printf("------%*s------------------------------------%*s-----------------------%*s----------------------------------------\n",
- padWidth, "------------",
- ibcColWidth, "------------",
- maxBlockNumWidth, "----");
+ printf("------%*s------------------------------------%*s-----------------------%*s---------------------------------"
+ "-------\n",
+ padWidth, "------------", ibcColWidth, "------------", maxBlockNumWidth, "----");
if (dumpTrees)
{
/*****************************************************************************/
-void Compiler::fgDispBasicBlocks(bool dumpTrees)
+void Compiler::fgDispBasicBlocks(bool dumpTrees)
{
fgDispBasicBlocks(fgFirstBB, nullptr, dumpTrees);
}
/*****************************************************************************/
// Increment the stmtNum and dump the tree using gtDispTree
//
-void Compiler::fgDumpStmtTree(GenTreePtr stmt, unsigned blkNum)
+void Compiler::fgDumpStmtTree(GenTreePtr stmt, unsigned blkNum)
{
- compCurStmtNum++; // Increment the current stmtNum
+ compCurStmtNum++; // Increment the current stmtNum
printf("\n***** BB%02u, stmt %d\n", blkNum, compCurStmtNum);
// Arguments:
// block - The block to dump.
//
-void Compiler::fgDumpBlock(BasicBlock* block)
+void Compiler::fgDumpBlock(BasicBlock* block)
{
printf("\n------------ ");
block->dspBlockHeader(this);
fgDumpStmtTree(stmt, block->bbNum);
if (stmt == block->bbTreeList)
{
- block->bbStmtNum = compCurStmtNum; // Set the block->bbStmtNum
+ block->bbStmtNum = compCurStmtNum; // Set the block->bbStmtNum
}
}
}
/*****************************************************************************/
// Walk the BasicBlock list calling fgDumpTree once per Stmt
//
-void Compiler::fgDumpTrees(BasicBlock* firstBlock,
- BasicBlock* lastBlock)
+void Compiler::fgDumpTrees(BasicBlock* firstBlock, BasicBlock* lastBlock)
{
- compCurStmtNum = 0; // Reset the current stmtNum
+ compCurStmtNum = 0; // Reset the current stmtNum
/* Walk the basic blocks */
{
fgDumpBlock(block);
- if (block == lastBlock) {
+ if (block == lastBlock)
+ {
break;
+ }
}
- }
- printf("\n-------------------------------------------------------------------------------------------------------------------\n");
+ printf("\n---------------------------------------------------------------------------------------------------------"
+ "----------\n");
}
-
/*****************************************************************************
* Try to create as many candidates for GTF_MUL_64RSLT as possible.
* We convert 'intOp1*intOp2' into 'int(long(nop(intOp1))*long(intOp2))'.
*/
/* static */
-Compiler::fgWalkResult Compiler::fgStress64RsltMulCB(GenTreePtr* pTree, fgWalkData* data)
+Compiler::fgWalkResult Compiler::fgStress64RsltMulCB(GenTreePtr* pTree, fgWalkData* data)
{
- GenTreePtr tree = *pTree;
+ GenTreePtr tree = *pTree;
Compiler* pComp = data->compiler;
- if (tree->gtOper != GT_MUL || tree->gtType != TYP_INT || (tree->gtOverflow())) {
+ if (tree->gtOper != GT_MUL || tree->gtType != TYP_INT || (tree->gtOverflow()))
+ {
return WALK_CONTINUE;
}
tree->gtOp.gtOp1 = pComp->gtNewOperNode(GT_NOP, TYP_LONG, tree->gtOp.gtOp1);
tree->gtOp.gtOp1 = pComp->gtNewCastNode(TYP_LONG, tree->gtOp.gtOp1, TYP_LONG);
tree->gtOp.gtOp2 = pComp->gtNewCastNode(TYP_LONG, tree->gtOp.gtOp2, TYP_LONG);
- tree->gtType = TYP_LONG;
- *pTree = pComp->gtNewCastNode(TYP_INT, tree, TYP_INT);
+ tree->gtType = TYP_LONG;
+ *pTree = pComp->gtNewCastNode(TYP_INT, tree, TYP_INT);
#ifdef DEBUG
if (pComp->verbose)
return WALK_SKIP_SUBTREES;
}
-void Compiler::fgStress64RsltMul()
+void Compiler::fgStress64RsltMul()
{
- if (!compStressCompile(STRESS_64RSLT_MUL, 20)) {
+ if (!compStressCompile(STRESS_64RSLT_MUL, 20))
+ {
return;
}
fgWalkAllTreesPre(fgStress64RsltMulCB, (void*)this);
}
-
// This variable is used to generate "traversal labels": one-time constants with which
// we label basic blocks that are members of the basic block list, in order to have a
// fast, high-probability test for membership in that list. Type is "volatile" because
*
*****************************************************************************/
-void Compiler::fgDebugCheckBBlist(bool checkBBNum /* = false */,
- bool checkBBRefs /* = true */)
+void Compiler::fgDebugCheckBBlist(bool checkBBNum /* = false */, bool checkBBRefs /* = true */)
{
#ifdef DEBUG
if (verbose)
unsigned blockRefs;
#if FEATURE_EH_FUNCLETS
- bool reachedFirstFunclet = false;
+ bool reachedFirstFunclet = false;
if (fgFuncletsCreated)
{
//
block->bbTraversalStamp = curTraversalStamp;
}
- for (prevBlock = nullptr, block = fgFirstBB;
- block;
- prevBlock = block, block = block->bbNext)
+ for (prevBlock = nullptr, block = fgFirstBB; block; prevBlock = block, block = block->bbNext)
{
blockRefs = 0;
/* First basic block has countOfInEdges() >= 1 */
- if (block == fgFirstBB)
+ if (block == fgFirstBB)
{
noway_assert(block->countOfInEdges() >= 1);
blockRefs = 1;
{
#ifndef LEGACY_BACKEND
noway_assert(block->lastNode()->gtNext == nullptr &&
- (block->lastNode()->gtOper == GT_SWITCH ||
- block->lastNode()->gtOper == GT_SWITCH_TABLE));
-#else // LEGACY_BACKEND
- noway_assert(block->lastStmt()->gtNext == NULL &&
- block->lastStmt()->gtStmtExpr->gtOper == GT_SWITCH);
+ (block->lastNode()->gtOper == GT_SWITCH || block->lastNode()->gtOper == GT_SWITCH_TABLE));
+#else // LEGACY_BACKEND
+ noway_assert(block->lastStmt()->gtNext == NULL && block->lastStmt()->gtStmtExpr->gtOper == GT_SWITCH);
#endif // LEGACY_BACKEND
}
- else if (!( block->bbJumpKind == BBJ_ALWAYS
- || block->bbJumpKind == BBJ_RETURN))
+ else if (!(block->bbJumpKind == BBJ_ALWAYS || block->bbJumpKind == BBJ_RETURN))
{
- //this block cannot have a poll
+ // this block cannot have a poll
noway_assert(!(block->bbFlags & BBF_NEEDS_GCPOLL));
}
#endif // FEATURE_EH_FUNCLETS
// Don't check cheap preds.
- for (pred = (fgCheapPredsValid ? nullptr : block->bbPreds); pred != nullptr; blockRefs += pred->flDupCount, pred = pred->flNext)
+ for (pred = (fgCheapPredsValid ? nullptr : block->bbPreds); pred != nullptr;
+ blockRefs += pred->flDupCount, pred = pred->flNext)
{
assert(fgComputePredsDone); // If this isn't set, why do we have a preds list?
if (ehTryDsc != nullptr)
{
// You can jump to the start of a try
- if (ehTryDsc->ebdTryBeg == block) {
+ if (ehTryDsc->ebdTryBeg == block)
+ {
goto CHECK_HND;
-}
+ }
// You can jump within the same try region
- if (bbInTryRegions(block->getTryIndex(), blockPred)) {
+ if (bbInTryRegions(block->getTryIndex(), blockPred))
+ {
goto CHECK_HND;
-}
+ }
// The catch block can jump back into the middle of the try
- if (bbInCatchHandlerRegions(block, blockPred)) {
+ if (bbInCatchHandlerRegions(block, blockPred))
+ {
goto CHECK_HND;
-}
+ }
// The end of a finally region is a BBJ_EHFINALLYRET block (during importing, BBJ_LEAVE) which
// is marked as "returning" to the BBJ_ALWAYS block following the BBJ_CALLFINALLY
// block that does a local call to the finally. This BBJ_ALWAYS is within
// the try region protected by the finally (for x86, ARM), but that's ok.
- if (prevBlock->bbJumpKind == BBJ_CALLFINALLY &&
- block->bbJumpKind == BBJ_ALWAYS &&
- blockPred->bbJumpKind == BBJ_EHFINALLYRET) {
+ if (prevBlock->bbJumpKind == BBJ_CALLFINALLY && block->bbJumpKind == BBJ_ALWAYS &&
+ blockPred->bbJumpKind == BBJ_EHFINALLYRET)
+ {
goto CHECK_HND;
-}
+ }
- printf("Jump into the middle of try region: BB%02u branches to BB%02u\n", blockPred->bbNum, block->bbNum);
+ printf("Jump into the middle of try region: BB%02u branches to BB%02u\n", blockPred->bbNum,
+ block->bbNum);
noway_assert(!"Jump into middle of try region");
}
-CHECK_HND:;
+ CHECK_HND:;
EHblkDsc* ehHndDsc = ehGetBlockHndDsc(block);
if (ehHndDsc != nullptr)
{
// You can do a BBJ_EHFINALLYRET or BBJ_EHFILTERRET into a handler region
- if ( (blockPred->bbJumpKind == BBJ_EHFINALLYRET)
- || (blockPred->bbJumpKind == BBJ_EHFILTERRET)) {
+ if ((blockPred->bbJumpKind == BBJ_EHFINALLYRET) || (blockPred->bbJumpKind == BBJ_EHFILTERRET))
+ {
goto CHECK_JUMP;
-}
+ }
// Our try block can call our finally block
- if ((block->bbCatchTyp == BBCT_FINALLY) &&
- (blockPred->bbJumpKind == BBJ_CALLFINALLY) &&
+ if ((block->bbCatchTyp == BBCT_FINALLY) && (blockPred->bbJumpKind == BBJ_CALLFINALLY) &&
ehCallFinallyInCorrectRegion(blockPred, block->getHndIndex()))
{
goto CHECK_JUMP;
}
// You can jump within the same handler region
- if (bbInHandlerRegions(block->getHndIndex(), blockPred)) {
+ if (bbInHandlerRegions(block->getHndIndex(), blockPred))
+ {
goto CHECK_JUMP;
-}
+ }
// A filter can jump to the start of the filter handler
- if (ehHndDsc->HasFilter()) {
+ if (ehHndDsc->HasFilter())
+ {
goto CHECK_JUMP;
-}
+ }
- printf("Jump into the middle of handler region: BB%02u branches to BB%02u\n", blockPred->bbNum, block->bbNum);
+ printf("Jump into the middle of handler region: BB%02u branches to BB%02u\n", blockPred->bbNum,
+ block->bbNum);
noway_assert(!"Jump into the middle of handler region");
}
-CHECK_JUMP:;
+ CHECK_JUMP:;
switch (blockPred->bbJumpKind)
{
- case BBJ_COND:
- noway_assert(blockPred->bbNext == block || blockPred->bbJumpDest == block);
- break;
+ case BBJ_COND:
+ noway_assert(blockPred->bbNext == block || blockPred->bbJumpDest == block);
+ break;
- case BBJ_NONE:
- noway_assert(blockPred->bbNext == block);
- break;
+ case BBJ_NONE:
+ noway_assert(blockPred->bbNext == block);
+ break;
- case BBJ_CALLFINALLY:
- case BBJ_ALWAYS:
- case BBJ_EHCATCHRET:
- case BBJ_EHFILTERRET:
- noway_assert(blockPred->bbJumpDest == block);
- break;
+ case BBJ_CALLFINALLY:
+ case BBJ_ALWAYS:
+ case BBJ_EHCATCHRET:
+ case BBJ_EHFILTERRET:
+ noway_assert(blockPred->bbJumpDest == block);
+ break;
- case BBJ_EHFINALLYRET:
+ case BBJ_EHFINALLYRET:
{
// If the current block is a successor to a BBJ_EHFINALLYRET (return from finally),
// then the lexically previous block should be a call to the same finally.
// Verify all of that.
- unsigned hndIndex = blockPred->getHndIndex();
- EHblkDsc* ehDsc = ehGetDsc(hndIndex);
- BasicBlock* finBeg = ehDsc->ebdHndBeg;
+ unsigned hndIndex = blockPred->getHndIndex();
+ EHblkDsc* ehDsc = ehGetDsc(hndIndex);
+ BasicBlock* finBeg = ehDsc->ebdHndBeg;
// Because there is no bbPrev, we have to search for the lexically previous
// block. We can shorten the search by only looking in places where it is legal
for (BasicBlock* bcall = begBlk; bcall != endBlk; bcall = bcall->bbNext)
{
- if (bcall->bbJumpKind != BBJ_CALLFINALLY || bcall->bbJumpDest != finBeg) {
+ if (bcall->bbJumpKind != BBJ_CALLFINALLY || bcall->bbJumpDest != finBeg)
+ {
continue;
-}
+ }
- if (block == bcall->bbNext) {
+ if (block == bcall->bbNext)
+ {
goto PRED_OK;
- }
+ }
}
#if FEATURE_EH_FUNCLETS
for (BasicBlock* bcall = fgFirstFuncletBB; bcall; bcall = bcall->bbNext)
{
- if (bcall->bbJumpKind != BBJ_CALLFINALLY || bcall->bbJumpDest != finBeg) {
+ if (bcall->bbJumpKind != BBJ_CALLFINALLY || bcall->bbJumpDest != finBeg)
+ {
continue;
-}
+ }
- if (block != bcall->bbNext) {
+ if (block != bcall->bbNext)
+ {
continue;
-}
+ }
- if (ehCallFinallyInCorrectRegion(bcall, hndIndex)) {
+ if (ehCallFinallyInCorrectRegion(bcall, hndIndex))
+ {
goto PRED_OK;
+ }
}
}
- }
#endif // FEATURE_EH_FUNCLETS
}
break;
- case BBJ_THROW:
- case BBJ_RETURN:
- noway_assert(!"THROW and RETURN block cannot be in the predecessor list!");
- break;
+ case BBJ_THROW:
+ case BBJ_RETURN:
+ noway_assert(!"THROW and RETURN block cannot be in the predecessor list!");
+ break;
- case BBJ_SWITCH:
- unsigned jumpCnt; jumpCnt = blockPred->bbJumpSwt->bbsCount;
- BasicBlock** jumpTab; jumpTab = blockPred->bbJumpSwt->bbsDstTab;
+ case BBJ_SWITCH:
+ unsigned jumpCnt;
+ jumpCnt = blockPred->bbJumpSwt->bbsCount;
+ BasicBlock** jumpTab;
+ jumpTab = blockPred->bbJumpSwt->bbsDstTab;
- do
- {
- if (block == *jumpTab)
+ do
{
- goto PRED_OK;
- }
- }
- while (++jumpTab, --jumpCnt);
+ if (block == *jumpTab)
+ {
+ goto PRED_OK;
+ }
+ } while (++jumpTab, --jumpCnt);
- noway_assert(!"SWITCH in the predecessor list with no jump label to BLOCK!");
- break;
+ noway_assert(!"SWITCH in the predecessor list with no jump label to BLOCK!");
+ break;
- default:
- noway_assert(!"Unexpected bbJumpKind");
- break;
+ default:
+ noway_assert(!"Unexpected bbJumpKind");
+ break;
}
-PRED_OK:;
-
+ PRED_OK:;
}
/* Check the bbRefs */
copiedForGenericsCtxt = ((info.compMethodInfo->options & CORINFO_GENERICS_CTXT_FROM_THIS) != 0);
#else // JIT32_GCENCODER
copiedForGenericsCtxt = FALSE;
-#endif // JIT32_GCENCODER
+#endif // JIT32_GCENCODER
// This if only in support of the noway_asserts it contains.
if (info.compIsStatic)
// For instance method:
assert(info.compThisArg != BAD_VAR_NUM);
bool compThisArgAddrExposedOK = !lvaTable[info.compThisArg].lvAddrExposed;
+
#ifndef JIT32_GCENCODER
compThisArgAddrExposedOK = compThisArgAddrExposedOK || copiedForGenericsCtxt;
-#endif // !JIT32_GCENCODER
- noway_assert(compThisArgAddrExposedOK && // should never expose the address of arg 0 or
- !lvaTable[info.compThisArg].lvArgWrite && // write to arg 0.
- ( // In addition,
- lvaArg0Var == info.compThisArg || // lvArg0Var should remain 0 if arg0 is not written to or address-exposed.
- lvaArg0Var != info.compThisArg &&
- (lvaTable[lvaArg0Var].lvAddrExposed || lvaTable[lvaArg0Var].lvArgWrite || copiedForGenericsCtxt)
- ));
+#endif // !JIT32_GCENCODER
+
+ // Should never expose the address of arg 0 or write to arg 0.
+ // In addition, lvArg0Var should remain 0 if arg0 is not
+ // written to or address-exposed.
+ noway_assert(compThisArgAddrExposedOK && !lvaTable[info.compThisArg].lvArgWrite &&
+ (lvaArg0Var == info.compThisArg ||
+ lvaArg0Var != info.compThisArg && (lvaTable[lvaArg0Var].lvAddrExposed ||
+ lvaTable[lvaArg0Var].lvArgWrite || copiedForGenericsCtxt)));
}
}
*
****************************************************************************/
-void Compiler::fgDebugCheckFlags(GenTreePtr tree)
+void Compiler::fgDebugCheckFlags(GenTreePtr tree)
{
noway_assert(tree->gtOper != GT_STMT);
- genTreeOps oper = tree->OperGet();
- unsigned kind = tree->OperKind();
- unsigned treeFlags = tree->gtFlags & GTF_ALL_EFFECT;
- unsigned chkFlags = 0;
+ genTreeOps oper = tree->OperGet();
+ unsigned kind = tree->OperKind();
+ unsigned treeFlags = tree->gtFlags & GTF_ALL_EFFECT;
+ unsigned chkFlags = 0;
/* Is this a leaf node? */
- if (kind & GTK_LEAF)
+ if (kind & GTK_LEAF)
{
switch (oper)
{
- case GT_CLS_VAR:
- chkFlags |= GTF_GLOB_REF;
- break;
+ case GT_CLS_VAR:
+ chkFlags |= GTF_GLOB_REF;
+ break;
- case GT_CATCH_ARG:
- chkFlags |= GTF_ORDER_SIDEEFF;
- break;
+ case GT_CATCH_ARG:
+ chkFlags |= GTF_ORDER_SIDEEFF;
+ break;
- default:
- break;
+ default:
+ break;
}
}
/* Is it a 'simple' unary/binary operator? */
- else if (kind & GTK_SMPOP)
+ else if (kind & GTK_SMPOP)
{
- GenTreePtr op1 = tree->gtOp.gtOp1;
- GenTreePtr op2 = tree->gtGetOp2();
+ GenTreePtr op1 = tree->gtOp.gtOp1;
+ GenTreePtr op2 = tree->gtGetOp2();
// During GS work, we make shadow copies for params.
// In gsParamsToShadows(), we create a shadow var of TYP_INT for every small type param.
// TYP_INT up to the GT_ASG tree is only correct if we don't need to propagate the TYP_INT back up.
// The following checks will ensure this.
- // Is the left child of "tree" a GT_ASG?,
+ // Is the left child of "tree" a GT_ASG?
+ //
+ // If parent is a TYP_VOID, we don't no need to propagate TYP_INT up. We are fine.
+ // (or) If GT_ASG is the left child of a GT_COMMA, the type of the GT_COMMA node will
+ // be determined by its right child. So we don't need to propagate TYP_INT up either. We are fine.
if (op1 && op1->gtOper == GT_ASG)
{
- assert(tree->gtType == TYP_VOID || // If parent is a TYP_VOID, we don't no need to propagate TYP_INT up. We are fine.
- tree->gtOper == GT_COMMA); // (or) If GT_ASG is the left child of a GT_COMMA, the type of the GT_COMMA node will
- } // be determined by its right child. So we don't need to propagate TYP_INT up either. We are fine.
+ assert(tree->gtType == TYP_VOID || tree->gtOper == GT_COMMA);
+ }
- // Is the right child of "tree" a GT_ASG?,
+ // Is the right child of "tree" a GT_ASG?
+ //
+ // If parent is a TYP_VOID, we don't no need to propagate TYP_INT up. We are fine.
if (op2 && op2->gtOper == GT_ASG)
{
- assert(tree->gtType == TYP_VOID); // If parent is a TYP_VOID, we don't no need to propagate TYP_INT up. We are fine.
+ assert(tree->gtType == TYP_VOID);
}
switch (oper)
{
- case GT_QMARK:
- if (op1->OperIsCompare())
- {
- noway_assert(op1->gtFlags & GTF_DONT_CSE);
- }
- else
- {
- noway_assert( (op1->gtOper == GT_CNS_INT) &&
- ((op1->gtIntCon.gtIconVal == 0) || (op1->gtIntCon.gtIconVal == 1)) );
- }
- break;
-
- case GT_LIST:
- case GT_FIELD_LIST:
- if ((op2 != nullptr) && op2->OperIsAnyList())
- {
- ArrayStack<GenTree *> stack(this);
- while ((tree->gtGetOp2() != nullptr) && tree->gtGetOp2()->OperIsAnyList())
+ case GT_QMARK:
+ if (op1->OperIsCompare())
{
- stack.Push(tree);
- tree = tree->gtGetOp2();
+ noway_assert(op1->gtFlags & GTF_DONT_CSE);
}
-
- fgDebugCheckFlags(tree);
-
- while (stack.Height() > 0)
+ else
{
- tree = stack.Pop();
- assert((tree->gtFlags & GTF_REVERSE_OPS) == 0);
- fgDebugCheckFlags(tree->gtOp.gtOp1);
- chkFlags |= (tree->gtOp.gtOp1->gtFlags & GTF_ALL_EFFECT);
- chkFlags |= (tree->gtGetOp2()->gtFlags & GTF_ALL_EFFECT);
- fgDebugCheckFlagsHelper(tree, (tree->gtFlags & GTF_ALL_EFFECT), chkFlags);
+ noway_assert((op1->gtOper == GT_CNS_INT) &&
+ ((op1->gtIntCon.gtIconVal == 0) || (op1->gtIntCon.gtIconVal == 1)));
}
+ break;
- return;
- }
- break;
+ case GT_LIST:
+ case GT_FIELD_LIST:
+ if ((op2 != nullptr) && op2->OperIsAnyList())
+ {
+ ArrayStack<GenTree*> stack(this);
+ while ((tree->gtGetOp2() != nullptr) && tree->gtGetOp2()->OperIsAnyList())
+ {
+ stack.Push(tree);
+ tree = tree->gtGetOp2();
+ }
- default:
- break;
+ fgDebugCheckFlags(tree);
+
+ while (stack.Height() > 0)
+ {
+ tree = stack.Pop();
+ assert((tree->gtFlags & GTF_REVERSE_OPS) == 0);
+ fgDebugCheckFlags(tree->gtOp.gtOp1);
+ chkFlags |= (tree->gtOp.gtOp1->gtFlags & GTF_ALL_EFFECT);
+ chkFlags |= (tree->gtGetOp2()->gtFlags & GTF_ALL_EFFECT);
+ fgDebugCheckFlagsHelper(tree, (tree->gtFlags & GTF_ALL_EFFECT), chkFlags);
+ }
+
+ return;
+ }
+ break;
+
+ default:
+ break;
}
/* Recursively check the subtrees */
if (op1)
{
- chkFlags |= (op1->gtFlags & GTF_ALL_EFFECT);
+ chkFlags |= (op1->gtFlags & GTF_ALL_EFFECT);
}
if (op2)
{
- chkFlags |= (op2->gtFlags & GTF_ALL_EFFECT);
+ chkFlags |= (op2->gtFlags & GTF_ALL_EFFECT);
}
// We reuse the value of GTF_REVERSE_OPS for a GT_IND-specific flag,
was set and thus GTF_ASG cannot be considered here. */
/* For a GT_ASG(GT_IND(x), y) we are interested in the side effects of x */
- GenTreePtr op1p;
+ GenTreePtr op1p;
if ((kind & GTK_ASGOP) && (op1->gtOper == GT_IND))
{
op1p = op1->gtOp.gtOp1;
if (kind & GTK_ASGOP)
{
- chkFlags |= GTF_ASG;
+ chkFlags |= GTF_ASG;
}
/* Note that it is OK for treeFlags not to have a GTF_EXCEPT,
AssertionProp's non-Null may have cleared it */
if (tree->OperMayThrow())
{
- chkFlags |= (treeFlags & GTF_EXCEPT);
+ chkFlags |= (treeFlags & GTF_EXCEPT);
}
- if (oper == GT_ADDR &&
- (op1->OperIsLocal() ||
- op1->gtOper == GT_CLS_VAR ||
- (op1->gtOper == GT_IND && op1->gtOp.gtOp1->gtOper == GT_CLS_VAR_ADDR)))
+ if (oper == GT_ADDR && (op1->OperIsLocal() || op1->gtOper == GT_CLS_VAR ||
+ (op1->gtOper == GT_IND && op1->gtOp.gtOp1->gtOper == GT_CLS_VAR_ADDR)))
{
/* &aliasedVar doesn't need GTF_GLOB_REF, though alisasedVar does.
Similarly for clsVar */
else
{
- switch (tree->OperGet())
+ switch (tree->OperGet())
{
- case GT_CALL:
+ case GT_CALL:
- GenTreePtr args;
- GenTreePtr argx;
- GenTreeCall* call;
+ GenTreePtr args;
+ GenTreePtr argx;
+ GenTreeCall* call;
- call = tree->AsCall();
+ call = tree->AsCall();
- chkFlags |= GTF_CALL;
+ chkFlags |= GTF_CALL;
- if ((treeFlags & GTF_EXCEPT) && !(chkFlags & GTF_EXCEPT))
- {
- switch (eeGetHelperNum(tree->gtCall.gtCallMethHnd))
+ if ((treeFlags & GTF_EXCEPT) && !(chkFlags & GTF_EXCEPT))
{
- // Is this a helper call that can throw an exception ?
- case CORINFO_HELP_LDIV:
- case CORINFO_HELP_LMOD:
- case CORINFO_HELP_METHOD_ACCESS_CHECK:
- case CORINFO_HELP_FIELD_ACCESS_CHECK:
- case CORINFO_HELP_CLASS_ACCESS_CHECK:
- case CORINFO_HELP_DELEGATE_SECURITY_CHECK:
- chkFlags |= GTF_EXCEPT;
- break;
- default:
- break;
+ switch (eeGetHelperNum(tree->gtCall.gtCallMethHnd))
+ {
+ // Is this a helper call that can throw an exception ?
+ case CORINFO_HELP_LDIV:
+ case CORINFO_HELP_LMOD:
+ case CORINFO_HELP_METHOD_ACCESS_CHECK:
+ case CORINFO_HELP_FIELD_ACCESS_CHECK:
+ case CORINFO_HELP_CLASS_ACCESS_CHECK:
+ case CORINFO_HELP_DELEGATE_SECURITY_CHECK:
+ chkFlags |= GTF_EXCEPT;
+ break;
+ default:
+ break;
+ }
}
- }
- if (call->gtCallObjp)
- {
- fgDebugCheckFlags(call->gtCallObjp);
- chkFlags |= (call->gtCallObjp->gtFlags & GTF_SIDE_EFFECT);
-
- if (call->gtCallObjp->gtFlags & GTF_ASG)
+ if (call->gtCallObjp)
{
- treeFlags |= GTF_ASG;
+ fgDebugCheckFlags(call->gtCallObjp);
+ chkFlags |= (call->gtCallObjp->gtFlags & GTF_SIDE_EFFECT);
+
+ if (call->gtCallObjp->gtFlags & GTF_ASG)
+ {
+ treeFlags |= GTF_ASG;
+ }
}
- }
- for (args = call->gtCallArgs; args; args = args->gtOp.gtOp2)
- {
- argx = args->gtOp.gtOp1;
- fgDebugCheckFlags(argx);
+ for (args = call->gtCallArgs; args; args = args->gtOp.gtOp2)
+ {
+ argx = args->gtOp.gtOp1;
+ fgDebugCheckFlags(argx);
- chkFlags |= (argx->gtFlags & GTF_SIDE_EFFECT);
+ chkFlags |= (argx->gtFlags & GTF_SIDE_EFFECT);
- if (argx->gtFlags & GTF_ASG)
- {
- treeFlags |= GTF_ASG;
+ if (argx->gtFlags & GTF_ASG)
+ {
+ treeFlags |= GTF_ASG;
+ }
}
- }
- for (args = call->gtCallLateArgs; args; args = args->gtOp.gtOp2)
- {
- argx = args->gtOp.gtOp1;
- fgDebugCheckFlags(argx);
+ for (args = call->gtCallLateArgs; args; args = args->gtOp.gtOp2)
+ {
+ argx = args->gtOp.gtOp1;
+ fgDebugCheckFlags(argx);
- chkFlags |= (argx->gtFlags & GTF_SIDE_EFFECT);
+ chkFlags |= (argx->gtFlags & GTF_SIDE_EFFECT);
- if (argx->gtFlags & GTF_ASG)
- {
- treeFlags |= GTF_ASG;
+ if (argx->gtFlags & GTF_ASG)
+ {
+ treeFlags |= GTF_ASG;
+ }
}
- }
-
- if ((call->gtCallType == CT_INDIRECT) && (call->gtCallCookie != nullptr))
- {
- fgDebugCheckFlags(call->gtCallCookie);
- chkFlags |= (call->gtCallCookie->gtFlags & GTF_SIDE_EFFECT);
- }
- if (call->gtCallType == CT_INDIRECT)
- {
- fgDebugCheckFlags(call->gtCallAddr);
- chkFlags |= (call->gtCallAddr->gtFlags & GTF_SIDE_EFFECT);
- }
+ if ((call->gtCallType == CT_INDIRECT) && (call->gtCallCookie != nullptr))
+ {
+ fgDebugCheckFlags(call->gtCallCookie);
+ chkFlags |= (call->gtCallCookie->gtFlags & GTF_SIDE_EFFECT);
+ }
- if (call->IsUnmanaged() &&
- (call->gtCallMoreFlags & GTF_CALL_M_UNMGD_THISCALL))
- {
- if (call->gtCallArgs->gtOp.gtOp1->OperGet() == GT_NOP)
+ if (call->gtCallType == CT_INDIRECT)
{
- noway_assert(call->gtCallLateArgs->gtOp.gtOp1->TypeGet() == TYP_I_IMPL ||
- call->gtCallLateArgs->gtOp.gtOp1->TypeGet() == TYP_BYREF);
+ fgDebugCheckFlags(call->gtCallAddr);
+ chkFlags |= (call->gtCallAddr->gtFlags & GTF_SIDE_EFFECT);
}
- else
+
+ if (call->IsUnmanaged() && (call->gtCallMoreFlags & GTF_CALL_M_UNMGD_THISCALL))
{
- noway_assert(call->gtCallArgs->gtOp.gtOp1->TypeGet() == TYP_I_IMPL ||
- call->gtCallArgs->gtOp.gtOp1->TypeGet() == TYP_BYREF);
+ if (call->gtCallArgs->gtOp.gtOp1->OperGet() == GT_NOP)
+ {
+ noway_assert(call->gtCallLateArgs->gtOp.gtOp1->TypeGet() == TYP_I_IMPL ||
+ call->gtCallLateArgs->gtOp.gtOp1->TypeGet() == TYP_BYREF);
+ }
+ else
+ {
+ noway_assert(call->gtCallArgs->gtOp.gtOp1->TypeGet() == TYP_I_IMPL ||
+ call->gtCallArgs->gtOp.gtOp1->TypeGet() == TYP_BYREF);
+ }
}
- }
- break;
+ break;
- case GT_ARR_ELEM:
+ case GT_ARR_ELEM:
- GenTreePtr arrObj;
- unsigned dim;
+ GenTreePtr arrObj;
+ unsigned dim;
- arrObj = tree->gtArrElem.gtArrObj;
- fgDebugCheckFlags(arrObj);
- chkFlags |= (arrObj->gtFlags & GTF_ALL_EFFECT);
+ arrObj = tree->gtArrElem.gtArrObj;
+ fgDebugCheckFlags(arrObj);
+ chkFlags |= (arrObj->gtFlags & GTF_ALL_EFFECT);
- for (dim = 0; dim < tree->gtArrElem.gtArrRank; dim++)
- {
- fgDebugCheckFlags(tree->gtArrElem.gtArrInds[dim]);
- chkFlags |= tree->gtArrElem.gtArrInds[dim]->gtFlags & GTF_ALL_EFFECT;
- }
- break;
+ for (dim = 0; dim < tree->gtArrElem.gtArrRank; dim++)
+ {
+ fgDebugCheckFlags(tree->gtArrElem.gtArrInds[dim]);
+ chkFlags |= tree->gtArrElem.gtArrInds[dim]->gtFlags & GTF_ALL_EFFECT;
+ }
+ break;
- case GT_ARR_OFFSET:
- fgDebugCheckFlags(tree->gtArrOffs.gtOffset);
- chkFlags |= (tree->gtArrOffs.gtOffset->gtFlags & GTF_ALL_EFFECT);
- fgDebugCheckFlags(tree->gtArrOffs.gtIndex);
- chkFlags |= (tree->gtArrOffs.gtIndex->gtFlags & GTF_ALL_EFFECT);
- fgDebugCheckFlags(tree->gtArrOffs.gtArrObj);
- chkFlags |= (tree->gtArrOffs.gtArrObj->gtFlags & GTF_ALL_EFFECT);
- break;
+ case GT_ARR_OFFSET:
+ fgDebugCheckFlags(tree->gtArrOffs.gtOffset);
+ chkFlags |= (tree->gtArrOffs.gtOffset->gtFlags & GTF_ALL_EFFECT);
+ fgDebugCheckFlags(tree->gtArrOffs.gtIndex);
+ chkFlags |= (tree->gtArrOffs.gtIndex->gtFlags & GTF_ALL_EFFECT);
+ fgDebugCheckFlags(tree->gtArrOffs.gtArrObj);
+ chkFlags |= (tree->gtArrOffs.gtArrObj->gtFlags & GTF_ALL_EFFECT);
+ break;
- default:
- break;
+ default:
+ break;
}
}
// Note:
// Checking that all bits that are set in treeFlags are also set in chkFlags is currently disabled.
-void Compiler::fgDebugCheckFlagsHelper(GenTreePtr tree, unsigned treeFlags, unsigned chkFlags)
+void Compiler::fgDebugCheckFlagsHelper(GenTreePtr tree, unsigned treeFlags, unsigned chkFlags)
{
if (chkFlags & ~treeFlags)
{
gtDispTree(tree);
}
#endif // 0
-}
+ }
}
// DEBUG routine to check correctness of the internal gtNext, gtPrev threading of a statement.
noway_assert(stmt->gtStmtList);
// The first node's gtPrev must be nullptr (the gtPrev list is not circular).
- // The last node's gtNext must be nullptr (the gtNext list is not circular). This is tested if the loop below terminates.
+ // The last node's gtNext must be nullptr (the gtNext list is not circular). This is tested if the loop below
+ // terminates.
assert(stmt->gtStmtList->gtPrev == nullptr);
- for (GenTreePtr tree = stmt->gtStmtList;
- tree != nullptr;
- tree = tree->gtNext)
+ for (GenTreePtr tree = stmt->gtStmtList; tree != nullptr; tree = tree->gtNext)
{
- if (tree->gtPrev)
+ if (tree->gtPrev)
{
noway_assert(tree->gtPrev->gtNext == tree);
}
noway_assert(tree == stmt->gtStmtList);
}
- if (tree->gtNext)
+ if (tree->gtNext)
{
noway_assert(tree->gtNext->gtPrev == tree);
}
{
switch (tree->gtOper)
{
- case GT_QMARK:
- expectedPrevTree = tree->gtOp.gtOp2->AsColon()->ThenNode(); // "then" operand of the GT_COLON (generated second).
- break;
+ case GT_QMARK:
+ expectedPrevTree =
+ tree->gtOp.gtOp2->AsColon()->ThenNode(); // "then" operand of the GT_COLON (generated second).
+ break;
- case GT_COLON:
- expectedPrevTree = tree->AsColon()->ElseNode(); // "else" branch result (generated first).
- break;
+ case GT_COLON:
+ expectedPrevTree = tree->AsColon()->ElseNode(); // "else" branch result (generated first).
+ break;
- default:
- if (tree->gtOp.gtOp2)
- {
- if (tree->gtFlags & GTF_REVERSE_OPS)
+ default:
+ if (tree->gtOp.gtOp2)
{
- expectedPrevTree = tree->gtOp.gtOp1;
+ if (tree->gtFlags & GTF_REVERSE_OPS)
+ {
+ expectedPrevTree = tree->gtOp.gtOp1;
+ }
+ else
+ {
+ expectedPrevTree = tree->gtOp.gtOp2;
+ }
}
else
{
- expectedPrevTree = tree->gtOp.gtOp2;
+ expectedPrevTree = tree->gtOp.gtOp1;
}
- }
- else
- {
- expectedPrevTree = tree->gtOp.gtOp1;
- }
- break;
+ break;
}
}
- noway_assert(expectedPrevTree == nullptr || // No expectations about the prev node
- tree->gtPrev == expectedPrevTree); // The "normal" case
+ noway_assert(expectedPrevTree == nullptr || // No expectations about the prev node
+ tree->gtPrev == expectedPrevTree); // The "normal" case
}
}
-
/*****************************************************************************
*
* A DEBUG routine to check the correctness of the links between GT_STMT nodes
*
****************************************************************************/
-void Compiler::fgDebugCheckLinks(bool morphTrees)
+void Compiler::fgDebugCheckLinks(bool morphTrees)
{
// This used to be only on for stress, and there was a comment stating that
// it was "quite an expensive operation" but I did not find that to be true.
// Set DO_SANITY_DEBUG_CHECKS to false to revert to that behavior.
const bool DO_SANITY_DEBUG_CHECKS = true;
- if (!DO_SANITY_DEBUG_CHECKS &&
- !compStressCompile(STRESS_CHK_FLOW_UPDATE, 30))
+ if (!DO_SANITY_DEBUG_CHECKS && !compStressCompile(STRESS_CHK_FLOW_UPDATE, 30))
{
return;
}
/* For each basic block check the bbTreeList links */
for (BasicBlock* block = fgFirstBB; block; block = block->bbNext)
{
-PROCESS_BLOCK_AGAIN:;
+ PROCESS_BLOCK_AGAIN:;
if (block->IsLIR())
{
LIR::AsRange(block).CheckLIR(this);
for (GenTreeStmt* stmt = block->firstStmt(); stmt; stmt = stmt->gtNextStmt)
{
/* Verify that bbTreeList is threaded correctly */
- /* Note that for the GT_STMT list, the gtPrev list is circular. The gtNext list is not: gtNext of the last GT_STMT in a block is nullptr. */
+ /* Note that for the GT_STMT list, the gtPrev list is circular. The gtNext list is not: gtNext of the
+ * last GT_STMT in a block is nullptr. */
noway_assert(stmt->gtPrev);
- if (stmt == block->bbTreeList)
+ if (stmt == block->bbTreeList)
{
noway_assert(stmt->gtPrev->gtNext == nullptr);
}
noway_assert(stmt->gtPrev->gtNext == stmt);
}
- if (stmt->gtNext)
+ if (stmt->gtNext)
{
noway_assert(stmt->gtNext->gtPrev == stmt);
}
// Create a set with all the successors. Don't use BlockSet, so we don't need to worry
// about the BlockSet epoch.
BitVecTraits bitVecTraits(fgBBNumMax + 1, this);
- BitVec BITVEC_INIT_NOCOPY(succBlocks, BitVecOps::MakeEmpty(&bitVecTraits));
+ BitVec BITVEC_INIT_NOCOPY(succBlocks, BitVecOps::MakeEmpty(&bitVecTraits));
BasicBlock** jumpTable = block->bbJumpSwt->bbsDstTab;
- unsigned jumpCount = block->bbJumpSwt->bbsCount;
+ unsigned jumpCount = block->bbJumpSwt->bbsCount;
for (unsigned i = 0; i < jumpCount; i++)
{
BitVecOps::AddElemD(&bitVecTraits, succBlocks, jumpTable[i]->bbNum);
// Likewise the depth limit is a policy consideration, and serves mostly
// as a safeguard to prevent runaway inlining of small methods.
-unsigned Compiler::fgCheckInlineDepthAndRecursion(InlineInfo* inlineInfo)
+unsigned Compiler::fgCheckInlineDepthAndRecursion(InlineInfo* inlineInfo)
{
BYTE* candidateCode = inlineInfo->inlineCandidateInfo->methInfo.ILCode;
InlineContext* inlineContext = inlineInfo->iciStmt->gtInlineContext;
* Inlining phase
*/
-
-void Compiler::fgInline()
+void Compiler::fgInline()
{
- if (!opts.OptEnabled(CLFLG_INLINING)) {
+ if (!opts.OptEnabled(CLFLG_INLINING))
+ {
return;
-}
+ }
#ifdef DEBUG
- if (verbose) {
+ if (verbose)
+ {
printf("*************** In fgInline()\n");
-}
+ }
#endif // DEBUG
BasicBlock* block = fgFirstBB;
for (; block != nullptr; block = block->bbNext)
{
- for (GenTreeStmt* stmt = block->firstStmt();
- stmt;
- stmt = stmt->gtNextStmt)
+ for (GenTreeStmt* stmt = block->firstStmt(); stmt; stmt = stmt->gtNextStmt)
{
stmt->gtInlineContext = rootContext;
}
GenTreeStmt* stmt;
GenTreePtr expr;
- for (stmt = block->firstStmt();
- stmt != nullptr;
- stmt = stmt->gtNextStmt)
+ for (stmt = block->firstStmt(); stmt != nullptr; stmt = stmt->gtNextStmt)
{
expr = stmt->gtStmtExpr;
}
// See if we need to replace the return value place holder.
- fgWalkTreePre(&stmt->gtStmtExpr,
- fgUpdateInlineReturnExpressionPlaceHolder,
- (void *) this);
+ fgWalkTreePre(&stmt->gtStmtExpr, fgUpdateInlineReturnExpressionPlaceHolder, (void*)this);
// See if stmt is of the form GT_COMMA(call, nop)
// If yes, we can get rid of GT_COMMA.
- if (expr->OperGet() == GT_COMMA &&
- expr->gtOp.gtOp1->OperGet() == GT_CALL &&
+ if (expr->OperGet() == GT_COMMA && expr->gtOp.gtOp1->OperGet() == GT_CALL &&
expr->gtOp.gtOp2->OperGet() == GT_NOP)
{
stmt->gtStmtExpr = expr->gtOp.gtOp1;
{
GenTreeStmt* stmt;
- for (stmt = block->firstStmt();
- stmt;
- stmt = stmt->gtNextStmt)
+ for (stmt = block->firstStmt(); stmt; stmt = stmt->gtNextStmt)
{
// Call Compiler::fgDebugCheckInlineCandidates on each node
fgWalkTreePre(&stmt->gtStmtExpr, fgDebugCheckInlineCandidates);
fgVerifyHandlerTab();
- if (verbose)
+ if (verbose)
{
printf("*************** After fgInline()\n");
fgDispBasicBlocks(true);
fgDispHandlerTab();
}
- if (verbose || fgPrintInlinedMethods)
+ if (verbose || fgPrintInlinedMethods)
{
- printf("**************** Inline Tree\n");
- m_inlineStrategy->Dump();
+ printf("**************** Inline Tree\n");
+ m_inlineStrategy->Dump();
}
#endif // DEBUG
// Note:
// Invokes fgNoteNonInlineCandidate on the nodes it finds.
-Compiler::fgWalkResult Compiler::fgFindNonInlineCandidate(GenTreePtr* pTree,
- fgWalkData* data)
+Compiler::fgWalkResult Compiler::fgFindNonInlineCandidate(GenTreePtr* pTree, fgWalkData* data)
{
GenTreePtr tree = *pTree;
if (tree->gtOper == GT_CALL)
{
Compiler* compiler = data->compiler;
- GenTreeStmt* stmt = (GenTreeStmt*) data->pCallbackData;
+ GenTreeStmt* stmt = (GenTreeStmt*)data->pCallbackData;
GenTreeCall* call = tree->AsCall();
compiler->fgNoteNonInlineCandidate(stmt, call);
// Used in debug only to try and place descriptions of inline failures
// into the proper context in the inline tree.
-void Compiler::fgNoteNonInlineCandidate(GenTreeStmt* stmt,
- GenTreeCall* call)
+void Compiler::fgNoteNonInlineCandidate(GenTreeStmt* stmt, GenTreeCall* call)
{
- InlineResult inlineResult(this, call, nullptr, "fgNotInlineCandidate");
+ InlineResult inlineResult(this, call, nullptr, "fgNotInlineCandidate");
InlineObservation currentObservation = InlineObservation::CALLSITE_NOT_CANDIDATE;
// Try and recover the reason left behind when the jit decided
*/
GenTreePtr Compiler::fgGetStructAsStructPtr(GenTreePtr tree)
{
- noway_assert((tree->gtOper == GT_LCL_VAR) ||
- (tree->gtOper == GT_FIELD) ||
- (tree->gtOper == GT_IND) ||
- (tree->gtOper == GT_BLK) ||
- (tree->gtOper == GT_OBJ) ||
- tree->OperIsSIMD() ||
+ noway_assert((tree->gtOper == GT_LCL_VAR) || (tree->gtOper == GT_FIELD) || (tree->gtOper == GT_IND) ||
+ (tree->gtOper == GT_BLK) || (tree->gtOper == GT_OBJ) || tree->OperIsSIMD() ||
// tree->gtOper == GT_CALL || cannot get address of call.
// tree->gtOper == GT_MKREFANY || inlining should've been aborted due to mkrefany opcode.
// tree->gtOper == GT_RET_EXPR || cannot happen after fgUpdateInlineReturnExpressionPlaceHolder
switch (tree->OperGet())
{
- case GT_BLK:
- case GT_OBJ:
- case GT_IND:
- return tree->gtOp.gtOp1;
+ case GT_BLK:
+ case GT_OBJ:
+ case GT_IND:
+ return tree->gtOp.gtOp1;
- case GT_COMMA:
- tree->gtOp.gtOp2 = fgGetStructAsStructPtr(tree->gtOp.gtOp2);
- tree->gtType = TYP_BYREF;
- return tree;
+ case GT_COMMA:
+ tree->gtOp.gtOp2 = fgGetStructAsStructPtr(tree->gtOp.gtOp2);
+ tree->gtType = TYP_BYREF;
+ return tree;
- default:
- return gtNewOperNode(GT_ADDR, TYP_BYREF, tree);
+ default:
+ return gtNewOperNode(GT_ADDR, TYP_BYREF, tree);
}
}
// we have a ", , , call()" -- this is very defensive as we may never get
// an inlinee that is made of commas. If the inlinee is not a call, then
// we use a copy block to do the assignment.
- GenTreePtr src = child;
+ GenTreePtr src = child;
GenTreePtr lastComma = nullptr;
while (src->gtOper == GT_COMMA)
{
lastComma = src;
- src = src->gtOp.gtOp2;
+ src = src->gtOp.gtOp2;
}
GenTreePtr newInlinee = nullptr;
if (child->gtOper == GT_COMMA)
{
lastComma->gtOp.gtOp2 = newInlinee;
- newInlinee = child;
+ newInlinee = child;
}
}
else
{
// Inlinee is not a call, so just create a copy block to the tmp.
- src = child;
+ src = child;
GenTreePtr dstAddr = fgGetStructAsStructPtr(dst);
GenTreePtr srcAddr = fgGetStructAsStructPtr(src);
- newInlinee = gtNewCpObjNode(dstAddr, srcAddr, retClsHnd, false);
+ newInlinee = gtNewCpObjNode(dstAddr, srcAddr, retClsHnd, false);
}
GenTreePtr production = gtNewLclvNode(tmpNum, structType);
}
GenTreePtr dstAddr = fgGetStructAsStructPtr(tree->gtOp.gtOp1);
- GenTreePtr srcAddr = fgGetStructAsStructPtr((child->gtOper == GT_CALL)
- ? fgAssignStructInlineeToVar(child, retClsHnd) // Assign to a variable if it is a call.
- : child); // Just get the address, if not a call.
+ GenTreePtr srcAddr = fgGetStructAsStructPtr(
+ (child->gtOper == GT_CALL)
+ ? fgAssignStructInlineeToVar(child, retClsHnd) // Assign to a variable if it is a call.
+ : child); // Just get the address, if not a call.
tree->CopyFrom(gtNewCpObjNode(dstAddr, srcAddr, retClsHnd, false), this);
}
*/
/* static */
-Compiler::fgWalkResult Compiler::fgUpdateInlineReturnExpressionPlaceHolder(GenTreePtr* pTree,
- fgWalkData* data)
+Compiler::fgWalkResult Compiler::fgUpdateInlineReturnExpressionPlaceHolder(GenTreePtr* pTree, fgWalkData* data)
{
- GenTreePtr tree = *pTree;
- Compiler* comp = data->compiler;
+ GenTreePtr tree = *pTree;
+ Compiler* comp = data->compiler;
CORINFO_CLASS_HANDLE retClsHnd = NO_CLASS_HANDLE;
if (tree->gtOper == GT_RET_EXPR)
printf("\n");
}
#endif // DEBUG
- }
- while (tree->gtOper == GT_RET_EXPR);
+ } while (tree->gtOper == GT_RET_EXPR);
}
#if FEATURE_MULTIREG_RET
if ((tree->gtOper == GT_ASG) && (tree->gtOp.gtOp2->gtOper == GT_COMMA))
{
GenTreePtr comma;
- for (comma = tree->gtOp.gtOp2;
- comma->gtOper == GT_COMMA;
- comma = comma->gtOp.gtOp2)
+ for (comma = tree->gtOp.gtOp2; comma->gtOper == GT_COMMA; comma = comma->gtOp.gtOp2)
{
// empty
}
- noway_assert(!varTypeIsStruct(comma) ||
- comma->gtOper != GT_RET_EXPR ||
+ noway_assert(!varTypeIsStruct(comma) || comma->gtOper != GT_RET_EXPR ||
!comp->IsMultiRegReturnedType(comma->gtRetExpr.gtRetClsHnd));
}
*/
/* static */
-Compiler::fgWalkResult Compiler::fgDebugCheckInlineCandidates(GenTreePtr* pTree,
- fgWalkData* data)
+Compiler::fgWalkResult Compiler::fgDebugCheckInlineCandidates(GenTreePtr* pTree, fgWalkData* data)
{
GenTreePtr tree = *pTree;
if (tree->gtOper == GT_CALL)
#endif // DEBUG
-
-void Compiler::fgInvokeInlineeCompiler(GenTreeCall* call,
- InlineResult* inlineResult)
+void Compiler::fgInvokeInlineeCompiler(GenTreeCall* call, InlineResult* inlineResult)
{
noway_assert(call->gtOper == GT_CALL);
noway_assert((call->gtFlags & GTF_CALL_INLINE_CANDIDATE) != 0);
// Set the trap to catch all errors (including recoverable ones from the EE)
struct Param
{
- Compiler* pThis;
- GenTree* call;
+ Compiler* pThis;
+ GenTree* call;
CORINFO_METHOD_HANDLE fncHandle;
- InlineCandidateInfo* inlineCandidateInfo;
- InlineInfo* inlineInfo;
+ InlineCandidateInfo* inlineCandidateInfo;
+ InlineInfo* inlineInfo;
} param = {nullptr};
- param.pThis = this;
- param.call = call;
- param.fncHandle = fncHandle;
+ param.pThis = this;
+ param.call = call;
+ param.fncHandle = fncHandle;
param.inlineCandidateInfo = inlineCandidateInfo;
- param.inlineInfo = &inlineInfo;
- bool success = eeRunWithErrorTrap<Param>([](Param* pParam)
- {
- // Init the local var info of the inlinee
- pParam->pThis->impInlineInitVars(pParam->inlineInfo);
+ param.inlineInfo = &inlineInfo;
+ bool success = eeRunWithErrorTrap<Param>(
+ [](Param* pParam) {
+ // Init the local var info of the inlinee
+ pParam->pThis->impInlineInitVars(pParam->inlineInfo);
- if (pParam->inlineInfo->inlineResult->IsCandidate())
- {
- /* Clear the temp table */
- memset(pParam->inlineInfo->lclTmpNum, -1, sizeof(pParam->inlineInfo->lclTmpNum));
+ if (pParam->inlineInfo->inlineResult->IsCandidate())
+ {
+ /* Clear the temp table */
+ memset(pParam->inlineInfo->lclTmpNum, -1, sizeof(pParam->inlineInfo->lclTmpNum));
- //
- // Prepare the call to jitNativeCode
- //
+ //
+ // Prepare the call to jitNativeCode
+ //
- pParam->inlineInfo->InlinerCompiler = pParam->pThis;
- if (pParam->pThis->impInlineInfo == nullptr)
- {
- pParam->inlineInfo->InlineRoot = pParam->pThis;
- }
- else
- {
- pParam->inlineInfo->InlineRoot = pParam->pThis->impInlineInfo->InlineRoot;
- }
- pParam->inlineInfo->argCnt = pParam->inlineCandidateInfo->methInfo.args.totalILArgs();
- pParam->inlineInfo->tokenLookupContextHandle = pParam->inlineCandidateInfo->exactContextHnd;
+ pParam->inlineInfo->InlinerCompiler = pParam->pThis;
+ if (pParam->pThis->impInlineInfo == nullptr)
+ {
+ pParam->inlineInfo->InlineRoot = pParam->pThis;
+ }
+ else
+ {
+ pParam->inlineInfo->InlineRoot = pParam->pThis->impInlineInfo->InlineRoot;
+ }
+ pParam->inlineInfo->argCnt = pParam->inlineCandidateInfo->methInfo.args.totalILArgs();
+ pParam->inlineInfo->tokenLookupContextHandle = pParam->inlineCandidateInfo->exactContextHnd;
- JITLOG_THIS(pParam->pThis,
- (LL_INFO100000,
- "INLINER: inlineInfo.tokenLookupContextHandle for %s set to 0x%p:\n",
- pParam->pThis->eeGetMethodFullName(pParam->fncHandle),
- pParam->pThis->dspPtr(pParam->inlineInfo->tokenLookupContextHandle)));
+ JITLOG_THIS(pParam->pThis,
+ (LL_INFO100000, "INLINER: inlineInfo.tokenLookupContextHandle for %s set to 0x%p:\n",
+ pParam->pThis->eeGetMethodFullName(pParam->fncHandle),
+ pParam->pThis->dspPtr(pParam->inlineInfo->tokenLookupContextHandle)));
- JitFlags compileFlagsForInlinee = *pParam->pThis->opts.jitFlags;
+ JitFlags compileFlagsForInlinee = *pParam->pThis->opts.jitFlags;
- // The following flags are lost when inlining.
- // (This is checked in Compiler::compInitOptions().)
- compileFlagsForInlinee.Clear(JitFlags::JIT_FLAG_BBOPT);
- compileFlagsForInlinee.Clear(JitFlags::JIT_FLAG_BBINSTR);
- compileFlagsForInlinee.Clear(JitFlags::JIT_FLAG_PROF_ENTERLEAVE);
- compileFlagsForInlinee.Clear(JitFlags::JIT_FLAG_DEBUG_EnC);
- compileFlagsForInlinee.Clear(JitFlags::JIT_FLAG_DEBUG_INFO);
+ // The following flags are lost when inlining.
+ // (This is checked in Compiler::compInitOptions().)
+ compileFlagsForInlinee.Clear(JitFlags::JIT_FLAG_BBOPT);
+ compileFlagsForInlinee.Clear(JitFlags::JIT_FLAG_BBINSTR);
+ compileFlagsForInlinee.Clear(JitFlags::JIT_FLAG_PROF_ENTERLEAVE);
+ compileFlagsForInlinee.Clear(JitFlags::JIT_FLAG_DEBUG_EnC);
+ compileFlagsForInlinee.Clear(JitFlags::JIT_FLAG_DEBUG_INFO);
- compileFlagsForInlinee.Set(JitFlags::JIT_FLAG_SKIP_VERIFICATION);
+ compileFlagsForInlinee.Set(JitFlags::JIT_FLAG_SKIP_VERIFICATION);
#ifdef DEBUG
- if (pParam->pThis->verbose)
- {
- printf("\nInvoking compiler for the inlinee method %s :\n",
- pParam->pThis->eeGetMethodFullName(pParam->fncHandle));
- }
+ if (pParam->pThis->verbose)
+ {
+ printf("\nInvoking compiler for the inlinee method %s :\n",
+ pParam->pThis->eeGetMethodFullName(pParam->fncHandle));
+ }
#endif // DEBUG
- int result = jitNativeCode(pParam->fncHandle,
- pParam->inlineCandidateInfo->methInfo.scope,
- pParam->pThis->info.compCompHnd,
- &pParam->inlineCandidateInfo->methInfo,
- (void**)pParam->inlineInfo,
- nullptr,
- &compileFlagsForInlinee,
- pParam->inlineInfo);
+ int result =
+ jitNativeCode(pParam->fncHandle, pParam->inlineCandidateInfo->methInfo.scope,
+ pParam->pThis->info.compCompHnd, &pParam->inlineCandidateInfo->methInfo,
+ (void**)pParam->inlineInfo, nullptr, &compileFlagsForInlinee, pParam->inlineInfo);
- if (result != CORJIT_OK)
- {
- // If we haven't yet determined why this inline fails, use
- // a catch-all something bad happened observation.
- InlineResult* innerInlineResult = pParam->inlineInfo->inlineResult;
-
- if (!innerInlineResult->IsFailure())
+ if (result != CORJIT_OK)
{
- innerInlineResult->NoteFatal(InlineObservation::CALLSITE_COMPILATION_FAILURE);
+ // If we haven't yet determined why this inline fails, use
+ // a catch-all something bad happened observation.
+ InlineResult* innerInlineResult = pParam->inlineInfo->inlineResult;
+
+ if (!innerInlineResult->IsFailure())
+ {
+ innerInlineResult->NoteFatal(InlineObservation::CALLSITE_COMPILATION_FAILURE);
+ }
}
}
- }
- }, ¶m);
+ },
+ ¶m);
if (!success)
{
#ifdef DEBUG
if (verbose)
{
- printf("\nInlining failed due to an exception during invoking the compiler for the inlinee method %s.\n",
- eeGetMethodFullName(fncHandle));
+ printf("\nInlining failed due to an exception during invoking the compiler for the inlinee method %s.\n",
+ eeGetMethodFullName(fncHandle));
}
#endif // DEBUG
#ifdef DEBUG
if (0 && verbose)
{
- printf("\nDone invoking compiler for the inlinee method %s\n",
- eeGetMethodFullName(fncHandle));
+ printf("\nDone invoking compiler for the inlinee method %s\n", eeGetMethodFullName(fncHandle));
}
#endif // DEBUG
if (verbose)
{
printf("\nInlining failed because pInlineInfo->retExpr is not set in the inlinee method %s.\n",
- eeGetMethodFullName(fncHandle));
+ eeGetMethodFullName(fncHandle));
}
#endif // DEBUG
inlineResult->NoteFatal(InlineObservation::CALLEE_LACKS_RETURN);
// we defer the call to initClass() until inlining is completed in case it fails. If inlining succeeds,
// we will call initClass().
if (!(info.compCompHnd->initClass(nullptr /* field */, fncHandle /* method */,
- inlineCandidateInfo->exactContextHnd /* context */) & CORINFO_INITCLASS_INITIALIZED))
+ inlineCandidateInfo->exactContextHnd /* context */) &
+ CORINFO_INITCLASS_INITIALIZED))
{
inlineResult->NoteFatal(InlineObservation::CALLEE_CLASS_INIT_FAILURE);
return;
if (verbose || fgPrintInlinedMethods)
{
- printf("Successfully inlined %s (%d IL bytes) (depth %d) [%s]\n",
- eeGetMethodFullName(fncHandle),
- inlineCandidateInfo->methInfo.ILCodeSize,
- inlineDepth,
- inlineResult->ReasonString());
+ printf("Successfully inlined %s (%d IL bytes) (depth %d) [%s]\n", eeGetMethodFullName(fncHandle),
+ inlineCandidateInfo->methInfo.ILCodeSize, inlineDepth, inlineResult->ReasonString());
}
if (verbose)
void Compiler::fgInsertInlineeBlocks(InlineInfo* pInlineInfo)
{
- GenTreeCall* iciCall = pInlineInfo->iciCall;
- GenTreeStmt* iciStmt = pInlineInfo->iciStmt;
- BasicBlock* iciBlock = pInlineInfo->iciBlock;
+ GenTreeCall* iciCall = pInlineInfo->iciCall;
+ GenTreeStmt* iciStmt = pInlineInfo->iciStmt;
+ BasicBlock* iciBlock = pInlineInfo->iciBlock;
BasicBlock* block;
// We can write better assert here. For example, we can check that
// Create a new inline context and mark the inlined statements with it
InlineContext* calleeContext = m_inlineStrategy->NewSuccess(pInlineInfo);
- for (block = InlineeCompiler->fgFirstBB;
- block != nullptr;
- block = block->bbNext)
+ for (block = InlineeCompiler->fgFirstBB; block != nullptr; block = block->bbNext)
{
- for (GenTreeStmt* stmt = block->firstStmt();
- stmt;
- stmt = stmt->gtNextStmt)
+ for (GenTreeStmt* stmt = block->firstStmt(); stmt; stmt = stmt->gtNextStmt)
{
stmt->gtInlineContext = calleeContext;
}
}
#endif // DEBUG
- BasicBlock* topBlock = iciBlock;
+ BasicBlock* topBlock = iciBlock;
BasicBlock* bottomBlock = nullptr;
if (InlineeCompiler->fgBBcount == 1)
// Inlinee contains just one BB. So just insert its statement list to topBlock.
if (InlineeCompiler->fgFirstBB->bbTreeList)
{
- stmtAfter = fgInsertStmtListAfter(iciBlock,
- stmtAfter,
- InlineeCompiler->fgFirstBB->bbTreeList);
+ stmtAfter = fgInsertStmtListAfter(iciBlock, stmtAfter, InlineeCompiler->fgFirstBB->bbTreeList);
// Copy inlinee bbFlags to caller bbFlags.
const unsigned int inlineeBlockFlags = InlineeCompiler->fgFirstBB->bbFlags;
{
noway_assert(currentDumpStmt);
- if (currentDumpStmt != stmtAfter)
+ if (currentDumpStmt != stmtAfter)
{
do
{
gtDispTree(currentDumpStmt);
printf("\n");
- } while (currentDumpStmt != stmtAfter);
+ } while (currentDumpStmt != stmtAfter);
}
}
#endif // DEBUG
// ======= Inserting inlinee's basic blocks ===============
//
- bottomBlock = fgNewBBafter(topBlock->bbJumpKind, topBlock, true);
- bottomBlock->bbRefs = 1;
+ bottomBlock = fgNewBBafter(topBlock->bbJumpKind, topBlock, true);
+ bottomBlock->bbRefs = 1;
bottomBlock->bbJumpDest = topBlock->bbJumpDest;
bottomBlock->inheritWeight(topBlock);
unsigned originalFlags;
originalFlags = topBlock->bbFlags;
noway_assert((originalFlags & BBF_SPLIT_NONEXIST) == 0);
- topBlock->bbFlags &= ~(BBF_SPLIT_LOST);
+ topBlock->bbFlags &= ~(BBF_SPLIT_LOST);
bottomBlock->bbFlags |= originalFlags & BBF_SPLIT_GAINED;
//
GenTreePtr bottomBlock_Begin;
GenTreePtr bottomBlock_End;
- topBlock_Begin = nullptr;
- topBlock_End = nullptr;
+ topBlock_Begin = nullptr;
+ topBlock_End = nullptr;
bottomBlock_Begin = nullptr;
- bottomBlock_End = nullptr;
+ bottomBlock_End = nullptr;
//
// First figure out bottomBlock_Begin
// topBlock is empty before the split.
// In this case, both topBlock and bottomBlock should be empty
noway_assert(bottomBlock_Begin == nullptr);
- topBlock->bbTreeList = nullptr;
+ topBlock->bbTreeList = nullptr;
bottomBlock->bbTreeList = nullptr;
}
else if (topBlock->bbTreeList == bottomBlock_Begin)
// And the split is before the first statement.
// In this case, topBlock should be empty, and everything else should be moved to the bottonBlock.
bottomBlock->bbTreeList = topBlock->bbTreeList;
- topBlock->bbTreeList = nullptr;
+ topBlock->bbTreeList = nullptr;
}
else if (bottomBlock_Begin == nullptr)
{
noway_assert(bottomBlock_Begin);
// This is the normal case where both blocks should contain at least one statement.
- topBlock_Begin = topBlock->bbTreeList;
+ topBlock_Begin = topBlock->bbTreeList;
noway_assert(topBlock_Begin);
- topBlock_End = bottomBlock_Begin->gtPrev;
+ topBlock_End = bottomBlock_Begin->gtPrev;
noway_assert(topBlock_End);
bottomBlock_End = topBlock->lastStmt();
noway_assert(bottomBlock_End);
bool inheritWeight;
inheritWeight = true; // The firstBB does inherit the weight from the iciBlock
- for (block = InlineeCompiler->fgFirstBB;
- block != nullptr;
- block = block->bbNext)
+ for (block = InlineeCompiler->fgFirstBB; block != nullptr; block = block->bbNext)
{
noway_assert(!block->hasTryIndex());
noway_assert(!block->hasHndIndex());
block->copyEHRegion(iciBlock);
- block->bbFlags |= iciBlock->bbFlags & BBF_BACKWARD_JUMP;
+ block->bbFlags |= iciBlock->bbFlags & BBF_BACKWARD_JUMP;
if (iciStmt->gtStmtILoffsx != BAD_IL_OFFSET)
{
block->bbCodeOffs = jitGetILoffs(iciStmt->gtStmtILoffsx);
- block->bbCodeOffsEnd = block->bbCodeOffs + 1; // TODO: is code size of 1 some magic number for inlining?
+ block->bbCodeOffsEnd = block->bbCodeOffs + 1; // TODO: is code size of 1 some magic number for inlining?
}
else
{
- block->bbCodeOffs = 0; // TODO: why not BAD_IL_OFFSET?
- block->bbCodeOffsEnd = 0;
- block->bbFlags |= BBF_INTERNAL;
+ block->bbCodeOffs = 0; // TODO: why not BAD_IL_OFFSET?
+ block->bbCodeOffsEnd = 0;
+ block->bbFlags |= BBF_INTERNAL;
}
if (block->bbJumpKind == BBJ_RETURN)
#ifdef DEBUG
if (verbose)
{
- printf("\nConvert bbJumpKind of BB%02u to BBJ_ALWAYS to bottomBlock BB%02u\n",
- block->bbNum, bottomBlock->bbNum);
+ printf("\nConvert bbJumpKind of BB%02u to BBJ_ALWAYS to bottomBlock BB%02u\n", block->bbNum,
+ bottomBlock->bbNum);
}
#endif // DEBUG
}
//
// Copy out some flags
//
- compLongUsed |= InlineeCompiler->compLongUsed;
- compFloatingPointUsed |= InlineeCompiler->compFloatingPointUsed;
- compLocallocUsed |= InlineeCompiler->compLocallocUsed;
- compQmarkUsed |= InlineeCompiler->compQmarkUsed;
- compUnsafeCastUsed |= InlineeCompiler->compUnsafeCastUsed;
+ compLongUsed |= InlineeCompiler->compLongUsed;
+ compFloatingPointUsed |= InlineeCompiler->compFloatingPointUsed;
+ compLocallocUsed |= InlineeCompiler->compLocallocUsed;
+ compQmarkUsed |= InlineeCompiler->compQmarkUsed;
+ compUnsafeCastUsed |= InlineeCompiler->compUnsafeCastUsed;
compNeedsGSSecurityCookie |= InlineeCompiler->compNeedsGSSecurityCookie;
- compGSReorderStackLayout |= InlineeCompiler->compGSReorderStackLayout;
+ compGSReorderStackLayout |= InlineeCompiler->compGSReorderStackLayout;
// Update unmanaged call count
- info.compCallUnmanaged += InlineeCompiler->info.compCallUnmanaged;
+ info.compCallUnmanaged += InlineeCompiler->info.compCallUnmanaged;
- // Update optMethodFlags
+// Update optMethodFlags
#ifdef DEBUG
unsigned optMethodFlagsBefore = optMethodFlags;
#ifdef DEBUG
if (optMethodFlags != optMethodFlagsBefore)
{
- JITDUMP("INLINER: Updating optMethodFlags -- root:%0x callee:%0x new:%0x\n",
- optMethodFlagsBefore, InlineeCompiler->optMethodFlags, optMethodFlags);
+ JITDUMP("INLINER: Updating optMethodFlags -- root:%0x callee:%0x new:%0x\n", optMethodFlagsBefore,
+ InlineeCompiler->optMethodFlags, optMethodFlags);
}
#endif
GenTreePtr Compiler::fgInlinePrependStatements(InlineInfo* inlineInfo)
{
- BasicBlock* block = inlineInfo->iciBlock;
- GenTreeStmt* callStmt = inlineInfo->iciStmt;
- IL_OFFSETX callILOffset = callStmt->gtStmtILoffsx;
- GenTreeStmt* postStmt = callStmt->gtNextStmt;
- GenTreePtr afterStmt = callStmt; // afterStmt is the place where the new statements should be inserted after.
- GenTreePtr newStmt = nullptr;
- GenTreePtr call = inlineInfo->iciCall;
+ BasicBlock* block = inlineInfo->iciBlock;
+ GenTreeStmt* callStmt = inlineInfo->iciStmt;
+ IL_OFFSETX callILOffset = callStmt->gtStmtILoffsx;
+ GenTreeStmt* postStmt = callStmt->gtNextStmt;
+ GenTreePtr afterStmt = callStmt; // afterStmt is the place where the new statements should be inserted after.
+ GenTreePtr newStmt = nullptr;
+ GenTreePtr call = inlineInfo->iciCall;
noway_assert(call->gtOper == GT_CALL);
// Prepend statements for any initialization / side effects
- InlArgInfo* inlArgInfo = inlineInfo->inlArgInfo;
- InlLclVarInfo* lclVarInfo = inlineInfo->lclVarInfo;
+ InlArgInfo* inlArgInfo = inlineInfo->inlArgInfo;
+ InlLclVarInfo* lclVarInfo = inlineInfo->lclVarInfo;
GenTreePtr tree;
- // Create the null check statement (but not appending it to the statement list yet) for the 'this' pointer if necessary.
+ // Create the null check statement (but not appending it to the statement list yet) for the 'this' pointer if
+ // necessary.
// The NULL check should be done after "argument setup statements".
// The only reason we move it here is for calling "impInlineFetchArg(0,..." to reserve a temp
// for the "this" pointer.
if (call->gtFlags & GTF_CALL_NULLCHECK && !inlineInfo->thisDereferencedFirst)
{
// Call impInlineFetchArg to "reserve" a temp for the "this" pointer.
- nullcheck = gtNewOperNode(GT_IND, TYP_INT,
- impInlineFetchArg(0, inlArgInfo, lclVarInfo));
+ nullcheck = gtNewOperNode(GT_IND, TYP_INT, impInlineFetchArg(0, inlArgInfo, lclVarInfo));
nullcheck->gtFlags |= GTF_EXCEPT;
// The NULL-check statement will be inserted to the statement list after those statements
GenTreePtr argSingleUseNode = inlArgInfo[argNum].argBashTmpNode;
- if (argSingleUseNode &&
- !(argSingleUseNode->gtFlags & GTF_VAR_CLONED) &&
- !inlArgInfo[argNum].argHasLdargaOp &&
- !inlArgInfo[argNum].argHasStargOp)
+ if (argSingleUseNode && !(argSingleUseNode->gtFlags & GTF_VAR_CLONED) &&
+ !inlArgInfo[argNum].argHasLdargaOp && !inlArgInfo[argNum].argHasStargOp)
{
// Change the temp in-place to the actual argument.
// We currently do not support this for struct arguments, so it must not be a GT_OBJ.
noway_assert(structHnd != NO_CLASS_HANDLE);
}
- // Unsafe value cls check is not needed for argTmpNum here since in-linee compiler instance would have
- // iterated over these and marked them accordingly.
- impAssignTempGen(inlArgInfo[argNum].argTmpNum,
- inlArgInfo[argNum].argNode,
- structHnd,
- (unsigned)CHECK_SPILL_NONE,
- & afterStmt,
- callILOffset,
- block);
+ // Unsafe value cls check is not needed for
+ // argTmpNum here since in-linee compiler instance
+ // would have iterated over these and marked them
+ // accordingly.
+ impAssignTempGen(inlArgInfo[argNum].argTmpNum, inlArgInfo[argNum].argNode, structHnd,
+ (unsigned)CHECK_SPILL_NONE, &afterStmt, callILOffset, block);
#ifdef DEBUG
if (verbose)
gtDispTree(afterStmt);
}
#endif // DEBUG
-
}
}
else if (inlArgInfo[argNum].argIsByRefToStructLocal)
{
/* The argument is either not used or a const or lcl var */
- noway_assert(!inlArgInfo[argNum].argIsUsed ||
- inlArgInfo[argNum].argIsInvariant ||
- inlArgInfo[argNum].argIsLclVar );
+ noway_assert(!inlArgInfo[argNum].argIsUsed || inlArgInfo[argNum].argIsInvariant ||
+ inlArgInfo[argNum].argIsLclVar);
/* Make sure we didnt change argNode's along the way, or else
subsequent uses of the arg would have worked with the bashed value */
if (inlArgInfo[argNum].argIsInvariant)
{
- assert(inlArgInfo[argNum].argNode->OperIsConst() ||
- inlArgInfo[argNum].argNode->gtOper == GT_ADDR);
+ assert(inlArgInfo[argNum].argNode->OperIsConst() || inlArgInfo[argNum].argNode->gtOper == GT_ADDR);
}
noway_assert((inlArgInfo[argNum].argIsLclVar == 0) ==
- (inlArgInfo[argNum].argNode->gtOper != GT_LCL_VAR || (inlArgInfo[argNum].argNode->gtFlags & GTF_GLOB_REF)));
+ (inlArgInfo[argNum].argNode->gtOper != GT_LCL_VAR ||
+ (inlArgInfo[argNum].argNode->gtFlags & GTF_GLOB_REF)));
/* If the argument has side effects, append it */
gtDispTree(afterStmt);
}
#endif // DEBUG
-
}
}
}
if (inlineInfo->inlineCandidateInfo->initClassResult & CORINFO_INITCLASS_USE_HELPER)
{
CORINFO_CONTEXT_HANDLE exactContext = inlineInfo->inlineCandidateInfo->exactContextHnd;
- CORINFO_CLASS_HANDLE exactClass;
+ CORINFO_CLASS_HANDLE exactClass;
if (((SIZE_T)exactContext & CORINFO_CONTEXTFLAGS_MASK) == CORINFO_CONTEXTFLAGS_CLASS)
{
}
else
{
- exactClass = info.compCompHnd->getMethodClass(CORINFO_METHOD_HANDLE((SIZE_T)exactContext & ~CORINFO_CONTEXTFLAGS_MASK));
+ exactClass = info.compCompHnd->getMethodClass(
+ CORINFO_METHOD_HANDLE((SIZE_T)exactContext & ~CORINFO_CONTEXTFLAGS_MASK));
}
- tree = fgGetSharedCCtor(exactClass);
- newStmt = gtNewStmt(tree, callILOffset);
+ tree = fgGetSharedCCtor(exactClass);
+ newStmt = gtNewStmt(tree, callILOffset);
afterStmt = fgInsertStmtAfter(block, afterStmt, newStmt);
}
// Insert the nullcheck statement now.
if (nullcheck)
{
- newStmt = gtNewStmt(nullcheck, callILOffset);
+ newStmt = gtNewStmt(nullcheck, callILOffset);
afterStmt = fgInsertStmtAfter(block, afterStmt, newStmt);
}
unsigned lclCnt = InlineeMethodInfo->locals.numArgs;
// Does callee contain any zero-init local?
- if ((lclCnt != 0) &&
- (InlineeMethodInfo->options & CORINFO_OPT_INIT_LOCALS) != 0)
+ if ((lclCnt != 0) && (InlineeMethodInfo->options & CORINFO_OPT_INIT_LOCALS) != 0)
{
#ifdef DEBUG
for (unsigned lclNum = 0; lclNum < lclCnt; lclNum++)
{
- unsigned tmpNum = inlineInfo->lclTmpNum[lclNum];
+ unsigned tmpNum = inlineInfo->lclTmpNum[lclNum];
// Is the local used at all?
if (tmpNum != BAD_VAR_NUM)
{
// Unsafe value cls check is not needed here since in-linee compiler instance would have
// iterated over locals and marked accordingly.
- impAssignTempGen(tmpNum,
- gtNewZeroConNode(genActualType(lclTyp)),
- NO_CLASS_HANDLE,
- (unsigned)CHECK_SPILL_NONE,
- & afterStmt,
- callILOffset,
- block);
+ impAssignTempGen(tmpNum, gtNewZeroConNode(genActualType(lclTyp)), NO_CLASS_HANDLE,
+ (unsigned)CHECK_SPILL_NONE, &afterStmt, callILOffset, block);
}
else
{
- CORINFO_CLASS_HANDLE structType = lclVarInfo[lclNum + inlineInfo->argCnt].lclVerTypeInfo.GetClassHandle();
+ CORINFO_CLASS_HANDLE structType =
+ lclVarInfo[lclNum + inlineInfo->argCnt].lclVerTypeInfo.GetClassHandle();
- tree = gtNewBlkOpNode(gtNewLclvNode(tmpNum, lclTyp), // Dest
- gtNewIconNode(0), // Value
+ tree = gtNewBlkOpNode(gtNewLclvNode(tmpNum, lclTyp), // Dest
+ gtNewIconNode(0), // Value
info.compCompHnd->getClassSize(structType), // Size
- false, // isVolatile
- false); // not copyBlock
+ false, // isVolatile
+ false); // not copyBlock
- newStmt = gtNewStmt(tree, callILOffset);
+ newStmt = gtNewStmt(tree, callILOffset);
afterStmt = fgInsertStmtAfter(block, afterStmt, newStmt);
}
//------------------------------------------------------------------------
// fgInlineAppendStatements: Append statements that are needed
-// after the inlined call.
+// after the inlined call.
//
// Arguments:
// inlineInfo - information about the inline
JITDUMP("Unpin inlinee locals:\n");
- GenTreePtr callStmt = inlineInfo->iciStmt;
- IL_OFFSETX callILOffset = callStmt->gtStmt.gtStmtILoffsx;
+ GenTreePtr callStmt = inlineInfo->iciStmt;
+ IL_OFFSETX callILOffset = callStmt->gtStmt.gtStmtILoffsx;
CORINFO_METHOD_INFO* InlineeMethodInfo = InlineeCompiler->info.compMethodInfo;
- unsigned lclCnt = InlineeMethodInfo->locals.numArgs;
- InlLclVarInfo* lclVarInfo = inlineInfo->lclVarInfo;
+ unsigned lclCnt = InlineeMethodInfo->locals.numArgs;
+ InlLclVarInfo* lclVarInfo = inlineInfo->lclVarInfo;
noway_assert(callStmt->gtOper == GT_STMT);
gtDispTree(unpinStmt);
}
#endif // DEBUG
-
}
}
/*****************************************************************************/
/*static*/
-Compiler::fgWalkResult Compiler::fgChkThrowCB(GenTreePtr* pTree,
- fgWalkData* data)
+Compiler::fgWalkResult Compiler::fgChkThrowCB(GenTreePtr* pTree, fgWalkData* data)
{
GenTreePtr tree = *pTree;
switch (tree->gtOper)
{
- case GT_MUL:
- case GT_ADD:
- case GT_SUB:
- case GT_ASG_ADD:
- case GT_ASG_SUB:
- case GT_CAST:
- if (tree->gtOverflow()) {
- return Compiler::WALK_ABORT;
-}
- break;
+ case GT_MUL:
+ case GT_ADD:
+ case GT_SUB:
+ case GT_ASG_ADD:
+ case GT_ASG_SUB:
+ case GT_CAST:
+ if (tree->gtOverflow())
+ {
+ return Compiler::WALK_ABORT;
+ }
+ break;
- case GT_INDEX:
- if (tree->gtFlags & GTF_INX_RNGCHK) {
- return Compiler::WALK_ABORT;
-}
- break;
+ case GT_INDEX:
+ if (tree->gtFlags & GTF_INX_RNGCHK)
+ {
+ return Compiler::WALK_ABORT;
+ }
+ break;
- case GT_ARR_BOUNDS_CHECK:
- return Compiler::WALK_ABORT;
+ case GT_ARR_BOUNDS_CHECK:
+ return Compiler::WALK_ABORT;
- default:
- break;
+ default:
+ break;
}
return Compiler::WALK_CONTINUE;
/*****************************************************************************/
/*static*/
-Compiler::fgWalkResult Compiler::fgChkLocAllocCB(GenTreePtr* pTree,
- fgWalkData* data)
+Compiler::fgWalkResult Compiler::fgChkLocAllocCB(GenTreePtr* pTree, fgWalkData* data)
{
GenTreePtr tree = *pTree;
- if (tree->gtOper == GT_LCLHEAP) {
+ if (tree->gtOper == GT_LCLHEAP)
+ {
return Compiler::WALK_ABORT;
-}
+ }
return Compiler::WALK_CONTINUE;
}
/*****************************************************************************/
/*static*/
-Compiler::fgWalkResult Compiler::fgChkQmarkCB(GenTreePtr* pTree,
- fgWalkData* data)
+Compiler::fgWalkResult Compiler::fgChkQmarkCB(GenTreePtr* pTree, fgWalkData* data)
{
GenTreePtr tree = *pTree;
- if (tree->gtOper == GT_QMARK) {
+ if (tree->gtOper == GT_QMARK)
+ {
return Compiler::WALK_ABORT;
-}
+ }
return Compiler::WALK_CONTINUE;
}
-
void Compiler::fgLclFldAssign(unsigned lclNum)
{
assert(varTypeIsStruct(lvaTable[lclNum].lvType));
GenTreeDynBlk(GenTreePtr addr, GenTreePtr dynamicSize)
: GenTreeBlk(GT_DYN_BLK, TYP_STRUCT, addr, 0), gtDynamicSize(dynamicSize), gtEvalSizeFirst(false)
{
+ // Conservatively the 'addr' could be null or point into the global heap.
+ gtFlags |= GTF_EXCEPT | GTF_GLOB_REF;
gtFlags |= (dynamicSize->gtFlags & GTF_ALL_EFFECT);
}
// See if token matches
unsigned token = 0;
- int count = sscanf(buffer, " <Token>%u</Token> ", &token);
+ int count = sscanf_s(buffer, " <Token>%u</Token> ", &token);
if ((count != 1) || (token != methodToken))
{
continue;
// See if hash matches
unsigned hash = 0;
- count = sscanf(buffer, " <Hash>%u</Hash> ", &hash);
+ count = sscanf_s(buffer, " <Hash>%u</Hash> ", &hash);
if ((count != 1) || (hash != methodHash))
{
continue;
// Match token
unsigned inlineToken = 0;
- int count = sscanf(buffer, " <Token>%u</Token> ", &inlineToken);
+ int count = sscanf_s(buffer, " <Token>%u</Token> ", &inlineToken);
if ((count != 1) || (inlineToken != token))
{
// Match hash
unsigned inlineHash = 0;
- count = sscanf(buffer, " <Hash>%u</Hash> ", &inlineHash);
+ count = sscanf_s(buffer, " <Hash>%u</Hash> ", &inlineHash);
if ((count != 1) || (inlineHash != hash))
{
// Match offset
unsigned inlineOffset = 0;
- count = sscanf(buffer, " <Offset>%u</Offset> ", &inlineOffset);
+ count = sscanf_s(buffer, " <Offset>%u</Offset> ", &inlineOffset);
if ((count != 1) || (inlineOffset != offset))
{
continue;
if (fgets(buffer, sizeof(buffer), s_ReplayFile) != nullptr)
{
unsigned collectData = 0;
- count = sscanf(buffer, " <CollectData>%u</CollectData> ", &collectData);
+ count = sscanf_s(buffer, " <CollectData>%u</CollectData> ", &collectData);
if (count == 1)
{
#include "lower.h"
#include "lsra.h"
-/* Lowering of GT_CAST nodes */
+//------------------------------------------------------------------------
+// LowerCast: Lower GT_CAST(srcType, DstType) nodes.
+//
+// Arguments:
+// tree - GT_CAST node to be lowered
+//
+// Return Value:
+// None.
+//
+// Notes:
+// Casts from small int type to float/double are transformed as follows:
+// GT_CAST(byte, float/double) = GT_CAST(GT_CAST(byte, int32), float/double)
+// GT_CAST(sbyte, float/double) = GT_CAST(GT_CAST(sbyte, int32), float/double)
+// GT_CAST(int16, float/double) = GT_CAST(GT_CAST(int16, int32), float/double)
+// GT_CAST(uint16, float/double) = GT_CAST(GT_CAST(uint16, int32), float/double)
+//
+// Similarly casts from float/double to a smaller int type are transformed as follows:
+// GT_CAST(float/double, byte) = GT_CAST(GT_CAST(float/double, int32), byte)
+// GT_CAST(float/double, sbyte) = GT_CAST(GT_CAST(float/double, int32), sbyte)
+// GT_CAST(float/double, int16) = GT_CAST(GT_CAST(double/double, int32), int16)
+// GT_CAST(float/double, uint16) = GT_CAST(GT_CAST(double/double, int32), uint16)
+//
+// Note that for the overflow conversions we still depend on helper calls and
+// don't expect to see them here.
+// i) GT_CAST(float/double, int type with overflow detection)
+
void Lowering::LowerCast(GenTree* tree)
{
- NYI_ARM("ARM Lowering for cast");
+ assert(tree->OperGet() == GT_CAST);
+
+ JITDUMP("LowerCast for: ");
+ DISPNODE(tree);
+ JITDUMP("\n");
+
+ GenTreePtr op1 = tree->gtOp.gtOp1;
+ var_types dstType = tree->CastToType();
+ var_types srcType = op1->TypeGet();
+ var_types tmpType = TYP_UNDEF;
+
+ // TODO-ARM-Cleanup: Remove following NYI assertions.
+ if (varTypeIsFloating(srcType))
+ {
+ NYI_ARM("Lowering for cast from float"); // Not tested yet.
+ noway_assert(!tree->gtOverflow());
+ }
+
+ // Case of src is a small type and dst is a floating point type.
+ if (varTypeIsSmall(srcType) && varTypeIsFloating(dstType))
+ {
+ NYI_ARM("Lowering for cast from small type to float"); // Not tested yet.
+ // These conversions can never be overflow detecting ones.
+ noway_assert(!tree->gtOverflow());
+ tmpType = TYP_INT;
+ }
+ // case of src is a floating point type and dst is a small type.
+ else if (varTypeIsFloating(srcType) && varTypeIsSmall(dstType))
+ {
+ NYI_ARM("Lowering for cast from float to small type"); // Not tested yet.
+ tmpType = TYP_INT;
+ }
+
+ if (tmpType != TYP_UNDEF)
+ {
+ GenTreePtr tmp = comp->gtNewCastNode(tmpType, op1, tmpType);
+ tmp->gtFlags |= (tree->gtFlags & (GTF_UNSIGNED | GTF_OVERFLOW | GTF_EXCEPT));
+
+ tree->gtFlags &= ~GTF_UNSIGNED;
+ tree->gtOp.gtOp1 = tmp;
+ BlockRange().InsertAfter(op1, tmp);
+ }
}
void Lowering::LowerRotate(GenTreePtr tree)
//
assert(!castOp1->gtOverflowEx()); // Must not be an overflow checking operation
- GenTreePtr removeTreeNode = op1;
- tree->gtOp.gtOp1 = castOp1;
- op1 = castOp1;
- castOp1->gtType = TYP_UBYTE;
-
- // trim down the value if castOp1 is an int constant since its type changed to UBYTE.
- if (castOp1Oper == GT_CNS_INT)
- {
- castOp1->gtIntCon.gtIconVal = (UINT8)castOp1->gtIntCon.gtIconVal;
- }
-
// TODO-Cleanup: we're within "if (CheckImmedAndMakeContained(tree, op2))", so isn't
// the following condition always true?
if (op2->isContainedIntOrIImmed())
ssize_t val = (ssize_t)op2->AsIntConCommon()->IconValue();
if (val >= 0 && val <= 255)
{
+ GenTreePtr removeTreeNode = op1;
+ tree->gtOp.gtOp1 = castOp1;
+ op1 = castOp1;
+ castOp1->gtType = TYP_UBYTE;
+
+ // trim down the value if castOp1 is an int constant since its type changed to UBYTE.
+ if (castOp1Oper == GT_CNS_INT)
+ {
+ castOp1->gtIntCon.gtIconVal = (UINT8)castOp1->gtIntCon.gtIconVal;
+ }
+
op2->gtType = TYP_UBYTE;
tree->gtFlags |= GTF_UNSIGNED;
MakeSrcContained(tree, op1);
op1IsMadeContained = true;
}
- }
- }
- BlockRange().Remove(removeTreeNode);
+ BlockRange().Remove(removeTreeNode);
- // We've changed the type on op1 to TYP_UBYTE, but we already processed that node. We need to
- // go back and mark it byteable.
- // TODO-Cleanup: it might be better to move this out of the TreeNodeInfoInit pass to the earlier
- // "lower" pass, in which case the byteable check would just fall out. But that is quite
- // complex!
- TreeNodeInfoInitCheckByteable(op1);
+ // We've changed the type on op1 to TYP_UBYTE, but we already processed that node.
+ // We need to go back and mark it byteable.
+ // TODO-Cleanup: it might be better to move this out of the TreeNodeInfoInit pass to
+ // the earlier "lower" pass, in which case the byteable check would just fall out.
+ // But that is quite complex!
+ TreeNodeInfoInitCheckByteable(op1);
#ifdef DEBUG
- if (comp->verbose)
- {
- printf(
- "TreeNodeInfoInitCmp: Removing a GT_CAST to TYP_UBYTE and changing castOp1->gtType to "
- "TYP_UBYTE\n");
- comp->gtDispTreeRange(BlockRange(), tree);
- }
+ if (comp->verbose)
+ {
+ printf("TreeNodeInfoInitCmp: Removing a GT_CAST to TYP_UBYTE and changing "
+ "castOp1->gtType to TYP_UBYTE\n");
+ comp->gtDispTreeRange(BlockRange(), tree);
+ }
#endif
+ }
+ }
}
}
var_types dstType = tree->CastToType();
var_types srcType = op1->TypeGet();
var_types tmpType = TYP_UNDEF;
- bool srcUns = false;
// force the srcType to unsigned if GT_UNSIGNED flag is set
if (tree->gtFlags & GTF_UNSIGNED)
// (i.e. the target is read-modify-write), preference the dst to op1.
bool hasDelayFreeSrc = tree->gtLsraInfo.hasDelayFreeSrc;
- if (tree->OperGet() == GT_PUTARG_REG && isCandidateLocalRef(tree->gtGetOp1()) &&
+
+#if defined(DEBUG) && defined(_TARGET_X86_)
+ // On x86, `LSRA_LIMIT_CALLER` is too restrictive to allow the use of special put args: this stress mode
+ // leaves only three registers allocatable--eax, ecx, and edx--of which the latter two are also used for the
+ // first two integral arguments to a call. This can leave us with too few registers to succesfully allocate in
+ // situations like the following:
+ //
+ // t1026 = lclVar ref V52 tmp35 u:3 REG NA <l:$3a1, c:$98d>
+ //
+ // /--* t1026 ref
+ // t1352 = * putarg_reg ref REG NA
+ //
+ // t342 = lclVar int V14 loc6 u:4 REG NA $50c
+ //
+ // t343 = const int 1 REG NA $41
+ //
+ // /--* t342 int
+ // +--* t343 int
+ // t344 = * + int REG NA $495
+ //
+ // t345 = lclVar int V04 arg4 u:2 REG NA $100
+ //
+ // /--* t344 int
+ // +--* t345 int
+ // t346 = * % int REG NA $496
+ //
+ // /--* t346 int
+ // t1353 = * putarg_reg int REG NA
+ //
+ // t1354 = lclVar ref V52 tmp35 (last use) REG NA
+ //
+ // /--* t1354 ref
+ // t1355 = * lea(b+0) byref REG NA
+ //
+ // Here, the first `putarg_reg` would normally be considered a special put arg, which would remove `ecx` from the
+ // set of allocatable registers, leaving only `eax` and `edx`. The allocator will then fail to allocate a register
+ // for the def of `t345` if arg4 is not a register candidate: the corresponding ref position will be constrained to
+ // { `ecx`, `ebx`, `esi`, `edi` }, which `LSRA_LIMIT_CALLER` will further constrain to `ecx`, which will not be
+ // available due to the special put arg.
+ const bool supportsSpecialPutArg = getStressLimitRegs() != LSRA_LIMIT_CALLER;
+#else
+ const bool supportsSpecialPutArg = true;
+#endif
+
+ if (supportsSpecialPutArg && tree->OperGet() == GT_PUTARG_REG && isCandidateLocalRef(tree->gtGetOp1()) &&
(tree->gtGetOp1()->gtFlags & GTF_VAR_DEATH) == 0)
{
// This is the case for a "pass-through" copy of a lclVar. In the case where it is a non-last-use,
compiler->rpFrameType = frameType;
}
-// Is the copyReg given by this RefPosition still busy at the
+// Is the copyReg/moveReg given by this RefPosition still busy at the
// given location?
-bool copyRegInUse(RefPosition* ref, LsraLocation loc)
+bool copyOrMoveRegInUse(RefPosition* ref, LsraLocation loc)
{
- assert(ref->copyReg);
+ assert(ref->copyReg || ref->moveReg);
if (ref->getRefEndLocation() >= loc)
{
return true;
return false;
}
- // Is this a copyReg? It is if the register assignment doesn't match.
- // (the recentReference may not be a copyReg, because we could have seen another
- // reference since the copyReg)
+ // Is this a copyReg/moveReg? It is if the register assignment doesn't match.
+ // (the recentReference may not be a copyReg/moveReg, because we could have seen another
+ // reference since the copyReg/moveReg)
if (!assignedInterval->isAssignedTo(physRegRecord->regNum))
{
// Don't reassign it if it's still in use
- if (recentReference->copyReg && copyRegInUse(recentReference, currentLoc))
+ if ((recentReference->copyReg || recentReference->moveReg) &&
+ copyOrMoveRegInUse(recentReference, currentLoc))
{
return false;
}
assert(currentInterval != nullptr);
// It's already in a register, but not one we need.
- // If it is a fixed use that is not marked "delayRegFree", there is already a FixedReg to ensure that
- // the needed reg is not otherwise in use, so we can simply ignore it and codegen will do the copy.
- // The reason we need special handling for the "delayRegFree" case is that we need to mark the
- // fixed-reg as in-use and delayed (the FixedReg RefPosition doesn't handle the delay requirement).
- // Otherwise, if this is a pure use localVar or tree temp, we assign a copyReg, but must free both regs
- // if it is a last use.
- if (!currentRefPosition->isFixedRegRef || currentRefPosition->delayRegFree)
- {
- if (!RefTypeIsDef(currentRefPosition->refType))
+ if (!RefTypeIsDef(currentRefPosition->refType))
+ {
+ regNumber copyReg = assignCopyReg(currentRefPosition);
+ assert(copyReg != REG_NA);
+ INDEBUG(dumpLsraAllocationEvent(LSRA_EVENT_COPY_REG, currentInterval, copyReg));
+ lastAllocatedRefPosition = currentRefPosition;
+ if (currentRefPosition->lastUse)
{
- regNumber copyReg = assignCopyReg(currentRefPosition);
- assert(copyReg != REG_NA);
- INDEBUG(dumpLsraAllocationEvent(LSRA_EVENT_COPY_REG, currentInterval, copyReg));
- lastAllocatedRefPosition = currentRefPosition;
- if (currentRefPosition->lastUse)
+ if (currentRefPosition->delayRegFree)
{
- if (currentRefPosition->delayRegFree)
- {
- INDEBUG(dumpLsraAllocationEvent(LSRA_EVENT_LAST_USE_DELAYED, currentInterval,
- assignedRegister));
- delayRegsToFree |=
- (genRegMask(assignedRegister) | currentRefPosition->registerAssignment);
- }
- else
- {
- INDEBUG(
- dumpLsraAllocationEvent(LSRA_EVENT_LAST_USE, currentInterval, assignedRegister));
- regsToFree |= (genRegMask(assignedRegister) | currentRefPosition->registerAssignment);
- }
+ INDEBUG(dumpLsraAllocationEvent(LSRA_EVENT_LAST_USE_DELAYED, currentInterval,
+ assignedRegister));
+ delayRegsToFree |= (genRegMask(assignedRegister) | currentRefPosition->registerAssignment);
}
- // If this is a tree temp (non-localVar) interval, we will need an explicit move.
- if (!currentInterval->isLocalVar)
+ else
{
- currentRefPosition->moveReg = true;
- currentRefPosition->copyReg = false;
+ INDEBUG(dumpLsraAllocationEvent(LSRA_EVENT_LAST_USE, currentInterval, assignedRegister));
+ regsToFree |= (genRegMask(assignedRegister) | currentRefPosition->registerAssignment);
}
- continue;
}
- else
+ // If this is a tree temp (non-localVar) interval, we will need an explicit move.
+ if (!currentInterval->isLocalVar)
{
- INDEBUG(dumpLsraAllocationEvent(LSRA_EVENT_NEEDS_NEW_REG, nullptr, assignedRegister));
- regsToFree |= genRegMask(assignedRegister);
- // We want a new register, but we don't want this to be considered a spill.
- assignedRegister = REG_NA;
- if (physRegRecord->assignedInterval == currentInterval)
- {
- unassignPhysRegNoSpill(physRegRecord);
- }
+ currentRefPosition->moveReg = true;
+ currentRefPosition->copyReg = false;
}
+ continue;
}
else
{
- INDEBUG(dumpLsraAllocationEvent(LSRA_EVENT_KEPT_ALLOCATION, nullptr, assignedRegister));
+ INDEBUG(dumpLsraAllocationEvent(LSRA_EVENT_NEEDS_NEW_REG, nullptr, assignedRegister));
+ regsToFree |= genRegMask(assignedRegister);
+ // We want a new register, but we don't want this to be considered a spill.
+ assignedRegister = REG_NA;
+ if (physRegRecord->assignedInterval == currentInterval)
+ {
+ unassignPhysRegNoSpill(physRegRecord);
+ }
}
}
}
{
if (VERBOSE)
{
+ // If refPos is marked as copyReg, then the reg that is spilled
+ // is the homeReg of the interval not the reg currently assigned
+ // to refPos.
+ regNumber spillReg = regNum;
+ if (currentRefPosition->copyReg)
+ {
+ assert(interval != nullptr);
+ spillReg = interval->physReg;
+ }
dumpRegRecords();
dumpEmptyRefPosition();
- printf("Spill %-4s ", getRegName(regNum));
+ printf("Spill %-4s ", getRegName(spillReg));
}
}
else if (currentRefPosition->copyReg)
interval->physReg = REG_NA;
interval->assignedReg = nullptr;
- // regRegcord could be null if RefPosition is to be allocated a
- // reg only if profitable.
+ // regRegcord could be null if the RefPosition does not require a register.
if (regRecord != nullptr)
{
regRecord->assignedInterval = nullptr;
}
else
{
- assert(currentRefPosition->AllocateIfProfitable());
+ assert(!currentRefPosition->RequiresRegister());
}
}
}
assert(leftInterval->physReg == leftRegNum && rightInterval->physReg == rightRegNum);
leftInterval->physReg = rightRegNum;
rightInterval->physReg = leftRegNum;
+ leftInterval->assignedReg = &physRegs[rightRegNum];
+ rightInterval->assignedReg = &physRegs[leftRegNum];
physRegs[rightRegNum].assignedInterval = leftInterval;
physRegs[leftRegNum].assignedInterval = rightInterval;
if (VERBOSE)
}
#ifdef UNIX_AMD64_ABI
+//------------------------------------------------------------------------
+// Compiler::unwindSetFrameRegCFI: Record a cfi info for a frame register set.
+//
+// Arguments:
+// reg - The register being set as the frame register.
+// offset - The offset from the current stack pointer that the frame pointer will point at.
+//
void Compiler::unwindSetFrameRegCFI(regNumber reg, unsigned offset)
{
assert(compGeneratingProlog);
createCfiCode(func, cbProlog, CFI_DEF_CFA_REGISTER, mapRegNumToDwarfReg(reg));
if (offset != 0)
{
- createCfiCode(func, cbProlog, CFI_ADJUST_CFA_OFFSET, DWARF_REG_ILLEGAL, offset);
+ // before: cfa = rsp + old_cfa_offset;
+ // rbp = rsp + offset;
+ // after: cfa should be based on rbp, but points to the old address:
+ // rsp + old_cfa_offset == rbp + old_cfa_offset + adjust;
+ // adjust = -offset;
+ int adjust = -(int)offset;
+ createCfiCode(func, cbProlog, CFI_ADJUST_CFA_OFFSET, DWARF_REG_ILLEGAL, adjust);
}
}
#endif // UNIX_AMD64_ABI
for (IL_OFFSET offs = 0; offs < codeSize;)
{
char prefix[100];
- sprintf(prefix, "IL_%04x ", offs);
+ sprintf_s(prefix, _countof(prefix), "IL_%04x ", offs);
unsigned codeBytesDumped = dumpSingleInstr(codeAddr, offs, prefix);
offs += codeBytesDumped;
}
#define ENABLE
#define MINBUFFERS
using System;
-#if !FEATURE_CORECLR
-using System.Diagnostics.Tracing;
-#endif
using System.Runtime.InteropServices;
using System.Runtime.ConstrainedExecution;
using System.Collections.Generic;
/// Create a PinnableBufferCache that works on any object (it is intended for OverlappedData)
/// This is only used in mscorlib.
/// </summary>
-#if (ENABLE || MINBUFFERS)
-#pragma warning disable 618
- [EnvironmentPermission(SecurityAction.Assert, Unrestricted = true)]
-#pragma warning restore 618
- [System.Security.SecuritySafeCritical]
-#endif
internal PinnableBufferCache(string cacheName, Func<object> factory)
{
m_NotGen2 = new List<object>(DefaultNumberOfBuffers);
/// <summary>
/// Get a object from the buffer manager. If no buffers exist, allocate a new one.
/// </summary>
- [System.Security.SecuritySafeCritical]
internal object Allocate()
{
#if ENABLE
/// <summary>
/// Return a buffer back to the buffer manager.
/// </summary>
- [System.Security.SecuritySafeCritical]
internal void Free(object buffer)
{
#if ENABLE
/// Called when we don't have any buffers in our free list to give out.
/// </summary>
/// <returns></returns>
- [System.Security.SecuritySafeCritical]
private void Restock(out object returnBuffer)
{
lock (this)
/// <summary>
/// See if we can promote the buffers to the free list. Returns true if sucessful.
/// </summary>
- [System.Security.SecuritySafeCritical]
private bool AgePendingBuffers()
{
if (m_gen1CountAtLastRestock < GC.CollectionCount(GC.MaxGeneration - 1))
/// otherwise, we root the cache to the Gen2GcCallback object, and leak the cache even when
/// the application no longer needs it.
/// </summary>
- [System.Security.SecuritySafeCritical]
private static bool Gen2GcCallbackFunc(object targetObj)
{
return ((PinnableBufferCache)(targetObj)).TrimFreeListIfNeeded();
/// NOTE: DO NOT CALL THIS DIRECTLY FROM THE GEN2GCCALLBACK. INSTEAD CALL IT VIA A STATIC FUNCTION (SEE ABOVE).
/// If you register a non-static function as a callback, then this object will be leaked.
/// </summary>
- [System.Security.SecuritySafeCritical]
private bool TrimFreeListIfNeeded()
{
int curMSec = Environment.TickCount;
/// </summary>
internal sealed class Gen2GcCallback : CriticalFinalizerObject
{
- [System.Security.SecuritySafeCritical]
public Gen2GcCallback()
: base()
{
private Func<object, bool> m_callback;
private GCHandle m_weakTargetObj;
- [System.Security.SecuritySafeCritical]
private void Setup(Func<object, bool> callback, object targetObj)
{
m_callback = callback;
m_weakTargetObj = GCHandle.Alloc(targetObj, GCHandleType.Weak);
}
- [System.Security.SecuritySafeCritical]
~Gen2GcCallback()
{
// Check to see if the target object is still alive.
#endregion
}
-
-#if FEATURE_CORECLR
internal sealed class PinnableBufferCacheEventSource
{
public static readonly PinnableBufferCacheEventSource Log = new PinnableBufferCacheEventSource();
return 0;
}
- [System.Security.SecuritySafeCritical]
static internal unsafe long AddressOfObject(byte[] array)
{
return 0;
}
}
-#else
- /// <summary>
- /// PinnableBufferCacheEventSource is a private eventSource that we are using to
- /// debug and monitor the effectiveness of PinnableBufferCache
- /// </summary>
-#if PINNABLEBUFFERCACHE_MSCORLIB
- [EventSource(Name = "Microsoft-DotNETRuntime-PinnableBufferCache")]
-#else
- [EventSource(Name = "Microsoft-DotNETRuntime-PinnableBufferCache-System")]
-#endif
- internal sealed class PinnableBufferCacheEventSource : EventSource
- {
- public static readonly PinnableBufferCacheEventSource Log = new PinnableBufferCacheEventSource();
-
- [Event(1, Level = EventLevel.Verbose)]
- public void DebugMessage(string message) { if (IsEnabled()) WriteEvent(1, message); }
- [Event(2, Level = EventLevel.Verbose)]
- public void DebugMessage1(string message, long value) { if (IsEnabled()) WriteEvent(2, message, value); }
- [Event(3, Level = EventLevel.Verbose)]
- public void DebugMessage2(string message, long value1, long value2) { if (IsEnabled()) WriteEvent(3, message, value1, value2); }
- [Event(18, Level = EventLevel.Verbose)]
- public void DebugMessage3(string message, long value1, long value2, long value3) { if (IsEnabled()) WriteEvent(18, message, value1, value2, value3); }
-
- [Event(4)]
- public void Create(string cacheName) { if (IsEnabled()) WriteEvent(4, cacheName); }
-
- [Event(5, Level = EventLevel.Verbose)]
- public void AllocateBuffer(string cacheName, ulong objectId, int objectHash, int objectGen, int freeCountAfter) { if (IsEnabled()) WriteEvent(5, cacheName, objectId, objectHash, objectGen, freeCountAfter); }
- [Event(6)]
- public void AllocateBufferFromNotGen2(string cacheName, int notGen2CountAfter) { if (IsEnabled()) WriteEvent(6, cacheName, notGen2CountAfter); }
- [Event(7)]
- public void AllocateBufferCreatingNewBuffers(string cacheName, int totalBuffsBefore, int objectCount) { if (IsEnabled()) WriteEvent(7, cacheName, totalBuffsBefore, objectCount); }
- [Event(8)]
- public void AllocateBufferAged(string cacheName, int agedCount) { if (IsEnabled()) WriteEvent(8, cacheName, agedCount); }
- [Event(9)]
- public void AllocateBufferFreeListEmpty(string cacheName, int notGen2CountBefore) { if (IsEnabled()) WriteEvent(9, cacheName, notGen2CountBefore); }
-
- [Event(10, Level = EventLevel.Verbose)]
- public void FreeBuffer(string cacheName, ulong objectId, int objectHash, int freeCountBefore) { if (IsEnabled()) WriteEvent(10, cacheName, objectId, objectHash, freeCountBefore); }
- [Event(11)]
- public void FreeBufferStillTooYoung(string cacheName, int notGen2CountBefore) { if (IsEnabled()) WriteEvent(11, cacheName, notGen2CountBefore); }
-
- [Event(13)]
- public void TrimCheck(string cacheName, int totalBuffs, bool neededMoreThanFreeList, int deltaMSec) { if (IsEnabled()) WriteEvent(13, cacheName, totalBuffs, neededMoreThanFreeList, deltaMSec); }
- [Event(14)]
- public void TrimFree(string cacheName, int totalBuffs, int freeListCount, int toBeFreed) { if (IsEnabled()) WriteEvent(14, cacheName, totalBuffs, freeListCount, toBeFreed); }
- [Event(15)]
- public void TrimExperiment(string cacheName, int totalBuffs, int freeListCount, int numTrimTrial) { if (IsEnabled()) WriteEvent(15, cacheName, totalBuffs, freeListCount, numTrimTrial); }
- [Event(16)]
- public void TrimFreeSizeOK(string cacheName, int totalBuffs, int freeListCount) { if (IsEnabled()) WriteEvent(16, cacheName, totalBuffs, freeListCount); }
- [Event(17)]
- public void TrimFlush(string cacheName, int totalBuffs, int freeListCount, int notGen2CountBefore) { if (IsEnabled()) WriteEvent(17, cacheName, totalBuffs, freeListCount, notGen2CountBefore); }
- [Event(20)]
- public void AgePendingBuffersResults(string cacheName, int promotedToFreeListCount, int heldBackCount) { if (IsEnabled()) WriteEvent(20, cacheName, promotedToFreeListCount, heldBackCount); }
- [Event(21)]
- public void WalkFreeListResult(string cacheName, int freeListCount, int gen0BuffersInFreeList) { if (IsEnabled()) WriteEvent(21, cacheName, freeListCount, gen0BuffersInFreeList); }
-
-
- static internal ulong AddressOf(object obj)
- {
- var asByteArray = obj as byte[];
- if (asByteArray != null)
- return (ulong)AddressOfByteArray(asByteArray);
- return 0;
- }
-
- [System.Security.SecuritySafeCritical]
- static internal unsafe long AddressOfByteArray(byte[] array)
- {
- if (array == null)
- return 0;
- fixed (byte* ptr = array)
- return (long)(ptr - 2 * sizeof(void*));
- }
- }
-#endif
}
/// "lpt1:", etc. Use this to avoid security problems, like allowing a web client asking a server
/// for "http://server/com1.aspx" and then causing a worker process to hang.
/// </summary>
- [System.Security.SecurityCritical] // auto-generated
internal static SafeFileHandle SafeCreateFile(
String lpFileName,
int dwDesiredAccess,
{
internal partial class mincore
{
- [System.Security.SecurityCritical] // auto-generated
internal static SafeFileHandle UnsafeCreateFile(
string lpFileName,
int dwDesiredAccess,
namespace Microsoft.Win32.SafeHandles
{
- [System.Security.SecurityCritical] // auto-generated_required
public sealed class SafeFileHandle : SafeHandleZeroOrMinusOneIsInvalid
{
private bool? _isAsync;
internal ThreadPoolBoundHandle ThreadPoolBinding { get; set; }
- [System.Security.SecurityCritical]
override protected bool ReleaseHandle()
{
return Interop.mincore.CloseHandle(handle);
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
-using System;
-using System.Runtime.CompilerServices;
-using System.Globalization;
+using System.Diagnostics;
using System.Diagnostics.Contracts;
using System.Runtime.Serialization;
// The following code assumes that the current era value can not be -1.
if (_currentEraValue == -1)
{
- Contract.Assert(BaseCalendarID != CalendarId.UNINITIALIZED_VALUE, "[Calendar.CurrentEraValue] Expected a real calendar ID");
+ Debug.Assert(BaseCalendarID != CalendarId.UNINITIALIZED_VALUE, "[Calendar.CurrentEraValue] Expected a real calendar ID");
_currentEraValue = CalendarData.GetCalendarData(BaseCalendarID).iCurrentEra;
}
return (_currentEraValue);
// this value can be less than 0. It's fine since we are making it positive again in calculating offset.
int dayForJan1 = (int)GetDayOfWeek(time) - (dayOfYear % 7);
int offset = (dayForJan1 - firstDayOfWeek + 14) % 7;
- Contract.Assert(offset >= 0, "Calendar.GetFirstDayWeekOfYear(): offset >= 0");
+ Debug.Assert(offset >= 0, "Calendar.GetFirstDayWeekOfYear(): offset >= 0");
return ((dayOfYear + offset) / 7 + 1);
}
// See the LICENSE file in the project root for more information.
using System.Collections.Generic;
+using System.Diagnostics;
using System.Diagnostics.Contracts;
using System.Runtime.InteropServices;
using System.Security;
break;
default:
const string unsupportedDateFieldSymbols = "YuUrQqwWDFg";
- Contract.Assert(unsupportedDateFieldSymbols.IndexOf(input[index]) == -1,
+ Debug.Assert(unsupportedDateFieldSymbols.IndexOf(input[index]) == -1,
string.Format(CultureInfo.InvariantCulture,
"Encountered an unexpected date field symbol '{0}' from ICU which has no known corresponding .NET equivalent.",
input[index]));
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
-using System;
-using System.Runtime.InteropServices;
-using System.Runtime.CompilerServices;
-using System.Diagnostics.Contracts;
-using System.Collections.Generic;
+using System.Diagnostics;
namespace System.Globalization
{
if (!LoadCalendarDataFromSystem(localeName, calendarId))
{
- Contract.Assert(false, "[CalendarData] LoadCalendarDataFromSystem call isn't expected to fail for calendar " + calendarId + " locale " + localeName);
+ Debug.Assert(false, "[CalendarData] LoadCalendarDataFromSystem call isn't expected to fail for calendar " + calendarId + " locale " + localeName);
// Something failed, try invariant for missing parts
// This is really not good, but we don't want the callers to crash.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
-using System;
-using System.Diagnostics.Contracts;
+using System.Diagnostics;
namespace System.Globalization
{
return longitude;
}
- static public double AsDayFraction(double longitude)
+ public static double AsDayFraction(double longitude)
{
return longitude / FullCircleOfArc;
}
// the following formulas defines a polynomial function which gives us the amount that the earth is slowing down for specific year ranges
private static double DefaultEphemerisCorrection(int gregorianYear)
{
- Contract.Assert(gregorianYear < 1620 || 2020 <= gregorianYear);
+ Debug.Assert(gregorianYear < 1620 || 2020 <= gregorianYear);
long january1stOfYear = GetNumberOfDays(new DateTime(gregorianYear, 1, 1));
double daysSinceStartOf1810 = january1stOfYear - StartOf1810;
double x = TwelveHours + daysSinceStartOf1810;
private static double EphemerisCorrection1988to2019(int gregorianYear)
{
- Contract.Assert(1988 <= gregorianYear && gregorianYear <= 2019);
+ Debug.Assert(1988 <= gregorianYear && gregorianYear <= 2019);
return (double)(gregorianYear - 1933) / SecondsPerDay;
}
private static double EphemerisCorrection1900to1987(int gregorianYear)
{
- Contract.Assert(1900 <= gregorianYear && gregorianYear <= 1987);
+ Debug.Assert(1900 <= gregorianYear && gregorianYear <= 1987);
double centuriesFrom1900 = CenturiesFrom1900(gregorianYear);
return PolynomialSum(s_coefficients1900to1987, centuriesFrom1900);
}
private static double EphemerisCorrection1800to1899(int gregorianYear)
{
- Contract.Assert(1800 <= gregorianYear && gregorianYear <= 1899);
+ Debug.Assert(1800 <= gregorianYear && gregorianYear <= 1899);
double centuriesFrom1900 = CenturiesFrom1900(gregorianYear);
return PolynomialSum(s_coefficients1800to1899, centuriesFrom1900);
}
private static double EphemerisCorrection1700to1799(int gregorianYear)
{
- Contract.Assert(1700 <= gregorianYear && gregorianYear <= 1799);
+ Debug.Assert(1700 <= gregorianYear && gregorianYear <= 1799);
double yearsSince1700 = gregorianYear - 1700;
return PolynomialSum(s_coefficients1700to1799, yearsSince1700) / SecondsPerDay;
}
private static double EphemerisCorrection1620to1699(int gregorianYear)
{
- Contract.Assert(1620 <= gregorianYear && gregorianYear <= 1699);
+ Debug.Assert(1620 <= gregorianYear && gregorianYear <= 1699);
double yearsSince1600 = gregorianYear - 1600;
return PolynomialSum(s_coefficients1620to1699, yearsSince1600) / SecondsPerDay;
}
}
}
- Contract.Assert(false, "Not expected to come here");
+ Debug.Assert(false, "Not expected to come here");
return DefaultEphemerisCorrection(year);
}
- static public double JulianCenturies(double moment)
+ public static double JulianCenturies(double moment)
{
double dynamicalMoment = moment + EphemerisCorrection(moment);
return (dynamicalMoment - Noon2000Jan01) / DaysInUniformLengthCentury;
}
// midday
- static public double Midday(double date, double longitude)
+ public static double Midday(double date, double longitude)
{
return AsLocalTime(date + TwelveHours, longitude) - AsDayFraction(longitude);
}
}
// midday-in-tehran
- static public double MiddayAtPersianObservationSite(double date)
+ public static double MiddayAtPersianObservationSite(double date)
{
return Midday(date, InitLongitude(52.5)); // 52.5 degrees east - longitude of UTC+3:30 which defines Iranian Standard Time
}
return (-0.004778 * SinOfDegree(a)) - (0.0003667 * SinOfDegree(b));
}
- static public double Compute(double time)
+ public static double Compute(double time)
{
double julianCenturies = JulianCenturies(time);
double lambda = 282.7771834
return InitLongitude(longitude);
}
- static public double AsSeason(double longitude)
+ public static double AsSeason(double longitude)
{
return (longitude < 0) ? (longitude + FullCircleOfArc) : longitude;
}
break;
}
}
- Contract.Assert(day != upperBoundNewYearDay);
+ Debug.Assert(day != upperBoundNewYearDay);
return day - 1;
}
//
////////////////////////////////////////////////////////////////////////////
-using System;
-using System.Threading;
-using System.Runtime.InteropServices;
-using System.Runtime.CompilerServices;
-using System.Reflection;
-using System.Security;
+using System.Diagnostics;
using System.Diagnostics.Contracts;
namespace System.Globalization
internal static int InternalConvertToUtf32(String s, int index)
{
- Contract.Assert(s != null, "s != null");
- Contract.Assert(index >= 0 && index < s.Length, "index < s.Length");
+ Debug.Assert(s != null, "s != null");
+ Debug.Assert(index >= 0 && index < s.Length, "index < s.Length");
if (index < s.Length - 1)
{
int temp1 = (int)s[index] - HIGH_SURROGATE_START;
internal static int InternalConvertToUtf32(String s, int index, out int charLength)
{
- Contract.Assert(s != null, "s != null");
- Contract.Assert(s.Length > 0, "s.Length > 0");
- Contract.Assert(index >= 0 && index < s.Length, "index >= 0 && index < s.Length");
+ Debug.Assert(s != null, "s != null");
+ Debug.Assert(s.Length > 0, "s.Length > 0");
+ Debug.Assert(index >= 0 && index < s.Length, "index >= 0 && index < s.Length");
charLength = 1;
if (index < s.Length - 1)
{
internal static bool IsWhiteSpace(String s, int index)
{
- Contract.Assert(s != null, "s!=null");
- Contract.Assert(index >= 0 && index < s.Length, "index >= 0 && index < s.Length");
+ Debug.Assert(s != null, "s!=null");
+ Debug.Assert(index >= 0 && index < s.Length, "index >= 0 && index < s.Length");
UnicodeCategory uc = GetUnicodeCategory(s, index);
// In Unicode 3.0, U+2028 is the only character which is under the category "LineSeparator".
//
// Note that for ch in the range D800-DFFF we just treat it as any other non-numeric character
//
- internal unsafe static double InternalGetNumericValue(int ch)
+ internal static unsafe double InternalGetNumericValue(int ch)
{
- Contract.Assert(ch >= 0 && ch <= 0x10ffff, "ch is not in valid Unicode range.");
+ Debug.Assert(ch >= 0 && ch <= 0x10ffff, "ch is not in valid Unicode range.");
// Get the level 2 item from the highest 12 bit (8 - 19) of ch.
ushort index = s_pNumericLevel1Index[ch >> 8];
// Get the level 2 WORD offset from the 4 - 7 bit of ch. This provides the base offset of the level 3 table.
}
}
- internal unsafe static ushort InternalGetDigitValues(int ch)
+ internal static unsafe ushort InternalGetDigitValues(int ch)
{
- Contract.Assert(ch >= 0 && ch <= 0x10ffff, "ch is not in valid Unicode range.");
+ Debug.Assert(ch >= 0 && ch <= 0x10ffff, "ch is not in valid Unicode range.");
// Get the level 2 item from the highest 12 bit (8 - 19) of ch.
ushort index = s_pNumericLevel1Index[ch >> 8];
// Get the level 2 WORD offset from the 4 - 7 bit of ch. This provides the base offset of the level 3 table.
return InternalGetUnicodeCategory(s, index);
}
- internal unsafe static UnicodeCategory InternalGetUnicodeCategory(int ch)
+ internal static unsafe UnicodeCategory InternalGetUnicodeCategory(int ch)
{
return ((UnicodeCategory)InternalGetCategoryValue(ch, UNICODE_CATEGORY_OFFSET));
}
//
////////////////////////////////////////////////////////////////////////
- internal unsafe static byte InternalGetCategoryValue(int ch, int offset)
+ internal static unsafe byte InternalGetCategoryValue(int ch, int offset)
{
- Contract.Assert(ch >= 0 && ch <= 0x10ffff, "ch is not in valid Unicode range.");
+ Debug.Assert(ch >= 0 && ch <= 0x10ffff, "ch is not in valid Unicode range.");
// Get the level 2 item from the highest 12 bit (8 - 19) of ch.
ushort index = s_pCategoryLevel1Index[ch >> 8];
// Get the level 2 WORD offset from the 4 - 7 bit of ch. This provides the base offset of the level 3 table.
// Make sure that OtherNotAssigned is the last category in UnicodeCategory.
// If that changes, change the following assertion as well.
//
- //Contract.Assert(uc >= 0 && uc <= UnicodeCategory.OtherNotAssigned, "Table returns incorrect Unicode category");
+ //Debug.Assert(uc >= 0 && uc <= UnicodeCategory.OtherNotAssigned, "Table returns incorrect Unicode category");
return (uc);
}
}
internal static UnicodeCategory InternalGetUnicodeCategory(String value, int index)
{
- Contract.Assert(value != null, "value can not be null");
- Contract.Assert(index < value.Length, "index < value.Length");
+ Debug.Assert(value != null, "value can not be null");
+ Debug.Assert(index < value.Length, "index < value.Length");
return (InternalGetUnicodeCategory(InternalConvertToUtf32(value, index)));
}
internal static UnicodeCategory InternalGetUnicodeCategory(String str, int index, out int charLength)
{
- Contract.Assert(str != null, "str can not be null");
- Contract.Assert(str.Length > 0, "str.Length > 0"); ;
- Contract.Assert(index >= 0 && index < str.Length, "index >= 0 && index < str.Length");
+ Debug.Assert(str != null, "str can not be null");
+ Debug.Assert(str.Length > 0, "str.Length > 0"); ;
+ Debug.Assert(index >= 0 && index < str.Length, "index >= 0 && index < str.Length");
return (InternalGetUnicodeCategory(InternalConvertToUtf32(str, index, out charLength)));
}
internal static bool IsCombiningCategory(UnicodeCategory uc)
{
- Contract.Assert(uc >= 0, "uc >= 0");
+ Debug.Assert(uc >= 0, "uc >= 0");
return (
uc == UnicodeCategory.NonSpacingMark ||
uc == UnicodeCategory.SpacingCombiningMark ||
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
+using System.Diagnostics;
using System.Diagnostics.Contracts;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
internal static unsafe int IndexOfOrdinal(string source, string value, int startIndex, int count, bool ignoreCase)
{
- Contract.Assert(source != null);
- Contract.Assert(value != null);
+ Debug.Assert(source != null);
+ Debug.Assert(value != null);
if (value.Length == 0)
{
internal static unsafe int LastIndexOfOrdinal(string source, string value, int startIndex, int count, bool ignoreCase)
{
- Contract.Assert(source != null);
- Contract.Assert(value != null);
+ Debug.Assert(source != null);
+ Debug.Assert(value != null);
if (value.Length == 0)
{
private int GetHashCodeOfStringCore(string source, CompareOptions options)
{
- Contract.Assert(source != null);
- Contract.Assert((options & (CompareOptions.Ordinal | CompareOptions.OrdinalIgnoreCase)) == 0);
+ Debug.Assert(source != null);
+ Debug.Assert((options & (CompareOptions.Ordinal | CompareOptions.OrdinalIgnoreCase)) == 0);
return GetHashCodeOfStringCore(source, options, forceRandomizedHashing: false, additionalEntropy: 0);
}
private unsafe int CompareString(string string1, int offset1, int length1, string string2, int offset2, int length2, CompareOptions options)
{
- Contract.Assert(string1 != null);
- Contract.Assert(string2 != null);
- Contract.Assert((options & (CompareOptions.Ordinal | CompareOptions.OrdinalIgnoreCase)) == 0);
+ Debug.Assert(string1 != null);
+ Debug.Assert(string2 != null);
+ Debug.Assert((options & (CompareOptions.Ordinal | CompareOptions.OrdinalIgnoreCase)) == 0);
fixed (char* pString1 = string1)
{
private unsafe int IndexOfCore(string source, string target, int startIndex, int count, CompareOptions options)
{
- Contract.Assert(!string.IsNullOrEmpty(source));
- Contract.Assert(target != null);
- Contract.Assert((options & CompareOptions.OrdinalIgnoreCase) == 0);
+ Debug.Assert(!string.IsNullOrEmpty(source));
+ Debug.Assert(target != null);
+ Debug.Assert((options & CompareOptions.OrdinalIgnoreCase) == 0);
if (target.Length == 0)
{
private unsafe int LastIndexOfCore(string source, string target, int startIndex, int count, CompareOptions options)
{
- Contract.Assert(!string.IsNullOrEmpty(source));
- Contract.Assert(target != null);
- Contract.Assert((options & CompareOptions.OrdinalIgnoreCase) == 0);
+ Debug.Assert(!string.IsNullOrEmpty(source));
+ Debug.Assert(target != null);
+ Debug.Assert((options & CompareOptions.OrdinalIgnoreCase) == 0);
if (target.Length == 0)
{
private bool StartsWith(string source, string prefix, CompareOptions options)
{
- Contract.Assert(!string.IsNullOrEmpty(source));
- Contract.Assert(!string.IsNullOrEmpty(prefix));
- Contract.Assert((options & (CompareOptions.Ordinal | CompareOptions.OrdinalIgnoreCase)) == 0);
+ Debug.Assert(!string.IsNullOrEmpty(source));
+ Debug.Assert(!string.IsNullOrEmpty(prefix));
+ Debug.Assert((options & (CompareOptions.Ordinal | CompareOptions.OrdinalIgnoreCase)) == 0);
if (_isAsciiEqualityOrdinal && CanUseAsciiOrdinalForOptions(options) && source.IsFastSort() && prefix.IsFastSort())
{
private bool EndsWith(string source, string suffix, CompareOptions options)
{
- Contract.Assert(!string.IsNullOrEmpty(source));
- Contract.Assert(!string.IsNullOrEmpty(suffix));
- Contract.Assert((options & (CompareOptions.Ordinal | CompareOptions.OrdinalIgnoreCase)) == 0);
+ Debug.Assert(!string.IsNullOrEmpty(source));
+ Debug.Assert(!string.IsNullOrEmpty(suffix));
+ Debug.Assert((options & (CompareOptions.Ordinal | CompareOptions.OrdinalIgnoreCase)) == 0);
if (_isAsciiEqualityOrdinal && CanUseAsciiOrdinalForOptions(options) && source.IsFastSort() && suffix.IsFastSort())
{
internal unsafe int GetHashCodeOfStringCore(string source, CompareOptions options, bool forceRandomizedHashing, long additionalEntropy)
{
- Contract.Assert(source != null);
- Contract.Assert((options & (CompareOptions.Ordinal | CompareOptions.OrdinalIgnoreCase)) == 0);
+ Debug.Assert(source != null);
+ Debug.Assert((options & (CompareOptions.Ordinal | CompareOptions.OrdinalIgnoreCase)) == 0);
if (source.Length == 0)
{
int bytesWritten = System.Text.Encoding.UTF8.GetBytes(s, 0, s.Length, buffer, 0);
- Contract.Assert(bytesWritten == byteLen);
+ Debug.Assert(bytesWritten == byteLen);
return buffer;
}
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
+using System.Diagnostics;
using System.Diagnostics.Contracts;
namespace System.Globalization
internal static int IndexOfOrdinal(string source, string value, int startIndex, int count, bool ignoreCase)
{
- Contract.Assert(source != null);
- Contract.Assert(value != null);
+ Debug.Assert(source != null);
+ Debug.Assert(value != null);
return FindStringOrdinal(FIND_FROMSTART, source, startIndex, count, value, value.Length, ignoreCase);
}
internal static int LastIndexOfOrdinal(string source, string value, int startIndex, int count, bool ignoreCase)
{
- Contract.Assert(source != null);
- Contract.Assert(value != null);
+ Debug.Assert(source != null);
+ Debug.Assert(value != null);
return FindStringOrdinal(FIND_FROMEND, source, startIndex - count + 1, count, value, value.Length, ignoreCase);
}
private unsafe int GetHashCodeOfStringCore(string source, CompareOptions options)
{
- Contract.Assert(source != null);
- Contract.Assert((options & (CompareOptions.Ordinal | CompareOptions.OrdinalIgnoreCase)) == 0);
+ Debug.Assert(source != null);
+ Debug.Assert((options & (CompareOptions.Ordinal | CompareOptions.OrdinalIgnoreCase)) == 0);
if (source.Length == 0)
{
private unsafe int CompareString(string string1, int offset1, int length1, string string2, int offset2, int length2, CompareOptions options)
{
- Contract.Assert(string1 != null);
- Contract.Assert(string2 != null);
- Contract.Assert((options & (CompareOptions.Ordinal | CompareOptions.OrdinalIgnoreCase)) == 0);
+ Debug.Assert(string1 != null);
+ Debug.Assert(string2 != null);
+ Debug.Assert((options & (CompareOptions.Ordinal | CompareOptions.OrdinalIgnoreCase)) == 0);
string localeName = _sortHandle != IntPtr.Zero ? null : _sortName;
private int IndexOfCore(string source, string target, int startIndex, int count, CompareOptions options)
{
- Contract.Assert(!string.IsNullOrEmpty(source));
- Contract.Assert(target != null);
- Contract.Assert((options & CompareOptions.OrdinalIgnoreCase) == 0);
+ Debug.Assert(!string.IsNullOrEmpty(source));
+ Debug.Assert(target != null);
+ Debug.Assert((options & CompareOptions.OrdinalIgnoreCase) == 0);
// TODO: Consider moving this up to the relevent APIs we need to ensure this behavior for
// and add a precondition that target is not empty.
private int LastIndexOfCore(string source, string target, int startIndex, int count, CompareOptions options)
{
- Contract.Assert(!string.IsNullOrEmpty(source));
- Contract.Assert(target != null);
- Contract.Assert((options & CompareOptions.OrdinalIgnoreCase) == 0);
+ Debug.Assert(!string.IsNullOrEmpty(source));
+ Debug.Assert(target != null);
+ Debug.Assert((options & CompareOptions.OrdinalIgnoreCase) == 0);
// TODO: Consider moving this up to the relevent APIs we need to ensure this behavior for
// and add a precondition that target is not empty.
private bool StartsWith(string source, string prefix, CompareOptions options)
{
- Contract.Assert(!string.IsNullOrEmpty(source));
- Contract.Assert(!string.IsNullOrEmpty(prefix));
- Contract.Assert((options & (CompareOptions.Ordinal | CompareOptions.OrdinalIgnoreCase)) == 0);
+ Debug.Assert(!string.IsNullOrEmpty(source));
+ Debug.Assert(!string.IsNullOrEmpty(prefix));
+ Debug.Assert((options & (CompareOptions.Ordinal | CompareOptions.OrdinalIgnoreCase)) == 0);
return FindString(FIND_STARTSWITH | (uint)GetNativeCompareFlags(options),
source,
private bool EndsWith(string source, string suffix, CompareOptions options)
{
- Contract.Assert(!string.IsNullOrEmpty(source));
- Contract.Assert(!string.IsNullOrEmpty(suffix));
- Contract.Assert((options & (CompareOptions.Ordinal | CompareOptions.OrdinalIgnoreCase)) == 0);
+ Debug.Assert(!string.IsNullOrEmpty(source));
+ Debug.Assert(!string.IsNullOrEmpty(suffix));
+ Debug.Assert((options & (CompareOptions.Ordinal | CompareOptions.OrdinalIgnoreCase)) == 0);
return FindString(FIND_ENDSWITH | (uint)GetNativeCompareFlags(options),
source,
int sourceStartIndex = findLastIndex ? startIndex - sourceCount + 1 : startIndex;
-#if !TEST_CODEGEN_OPTIMIZATION
fixed (char* pSource = source, spTarget = target)
{
char* spSubSource = pSource + sourceStartIndex;
-#else
- String.StringPointer spSubSource = source.GetStringPointer(sourceStartIndex);
- String.StringPointer spTarget = target.GetStringPointer();
-#endif
+
if (findLastIndex)
{
int startPattern = (sourceCount - 1) - targetCount + 1;
retValue += startIndex;
}
}
-#if !TEST_CODEGEN_OPTIMIZATION
}
return retValue;
-#endif // TEST_CODEGEN_OPTIMIZATION
}
private unsafe SortKey CreateSortKey(String source, CompareOptions options)
if ((options & ValidSortkeyCtorMaskOffFlags) != 0)
{
- throw new ArgumentException(Environment.GetResourceString("Argument_InvalidFlag"), nameof(options));
+ throw new ArgumentException(SR.Argument_InvalidFlag, nameof(options));
}
throw new NotImplementedException();
}
- private unsafe static bool IsSortable(char *text, int length)
+ private static unsafe bool IsSortable(char *text, int length)
{
// CompareInfo c = CultureInfo.InvariantCulture.CompareInfo;
// return (InternalIsSortable(c.m_dataHandle, c.m_handleOrigin, c.m_sortName, text, text.Length));
// Suffix & Prefix shouldn't use this, make sure to turn off the NORM_LINGUISTIC_CASING flag
if (options == CompareOptions.Ordinal) { nativeCompareFlags = COMPARE_OPTIONS_ORDINAL; }
- Contract.Assert(((options & ~(CompareOptions.IgnoreCase |
+ Debug.Assert(((options & ~(CompareOptions.IgnoreCase |
CompareOptions.IgnoreKanaType |
CompareOptions.IgnoreNonSpace |
CompareOptions.IgnoreSymbols |
return nativeCompareFlags;
}
-
+
private SortVersion GetSortVersion()
{
throw new NotImplementedException();
//
////////////////////////////////////////////////////////////////////////////
-using System;
using System.Reflection;
-using System.Collections;
-using System.Collections.Generic;
+using System.Diagnostics;
using System.Diagnostics.Contracts;
-using System.Runtime.CompilerServices;
-using System.Runtime.InteropServices;
using System.Runtime.Serialization;
-using System.Threading;
namespace System.Globalization
{
return CultureInfo.GetCultureInfo(name).CompareInfo;
}
- public unsafe static bool IsSortable(char ch)
+ public static unsafe bool IsSortable(char ch)
{
char *pChar = &ch;
return IsSortable(pChar, 1);
}
- public unsafe static bool IsSortable(string text)
+ public static unsafe bool IsSortable(string text)
{
if (text == null)
{
{
get
{
- Contract.Assert(_name != null, "CompareInfo.Name Expected _name to be set");
+ Debug.Assert(_name != null, "CompareInfo.Name Expected _name to be set");
if (_name == "zh-CHT" || _name == "zh-CHS")
{
return _name;
//
internal static unsafe int CompareOrdinalIgnoreCase(string strA, int indexA, int lengthA, string strB, int indexB, int lengthB)
{
- Contract.Assert(indexA + lengthA <= strA.Length);
- Contract.Assert(indexB + lengthB <= strB.Length);
+ Debug.Assert(indexA + lengthA <= strA.Length);
+ Debug.Assert(indexB + lengthB <= strB.Length);
int length = Math.Min(lengthA, lengthB);
int range = length;
using System;
using System.Collections.Generic;
+using System.Diagnostics;
using System.Diagnostics.Contracts;
using System.Runtime.InteropServices;
using System.Security;
[SecuritySafeCritical]
private unsafe bool InitCultureData()
{
- Contract.Assert(_sRealName != null);
+ Debug.Assert(_sRealName != null);
string alternateSortName = string.Empty;
string realNameBuffer = _sRealName;
private string GetLocaleInfo(LocaleStringData type)
{
- Contract.Assert(_sWindowsName != null, "[CultureData.GetLocaleInfo] Expected _sWindowsName to be populated already");
+ Debug.Assert(_sWindowsName != null, "[CultureData.GetLocaleInfo] Expected _sWindowsName to be populated already");
return GetLocaleInfo(_sWindowsName, type);
}
[SecuritySafeCritical]
private string GetLocaleInfo(string localeName, LocaleStringData type)
{
- Contract.Assert(localeName != null, "[CultureData.GetLocaleInfo] Expected localeName to be not be null");
+ Debug.Assert(localeName != null, "[CultureData.GetLocaleInfo] Expected localeName to be not be null");
switch (type)
{
{
// Failed, just use empty string
StringBuilderCache.Release(sb);
- Contract.Assert(false, "[CultureData.GetLocaleInfo(LocaleStringData)] Failed");
+ Debug.Assert(false, "[CultureData.GetLocaleInfo(LocaleStringData)] Failed");
return String.Empty;
}
return StringBuilderCache.GetStringAndRelease(sb);
[SecuritySafeCritical]
private int GetLocaleInfo(LocaleNumberData type)
{
- Contract.Assert(_sWindowsName != null, "[CultureData.GetLocaleInfo(LocaleNumberData)] Expected _sWindowsName to be populated already");
+ Debug.Assert(_sWindowsName != null, "[CultureData.GetLocaleInfo(LocaleNumberData)] Expected _sWindowsName to be populated already");
switch (type)
{
if (!result)
{
// Failed, just use 0
- Contract.Assert(false, "[CultureData.GetLocaleInfo(LocaleNumberData)] failed");
+ Debug.Assert(false, "[CultureData.GetLocaleInfo(LocaleNumberData)] failed");
}
return value;
[SecuritySafeCritical]
private int[] GetLocaleInfo(LocaleGroupingData type)
{
- Contract.Assert(_sWindowsName != null, "[CultureData.GetLocaleInfo(LocaleGroupingData)] Expected _sWindowsName to be populated already");
+ Debug.Assert(_sWindowsName != null, "[CultureData.GetLocaleInfo(LocaleGroupingData)] Expected _sWindowsName to be populated already");
int primaryGroupingSize = 0;
int secondaryGroupingSize = 0;
bool result = Interop.GlobalizationInterop.GetLocaleInfoGroupingSizes(_sWindowsName, (uint)type, ref primaryGroupingSize, ref secondaryGroupingSize);
if (!result)
{
- Contract.Assert(false, "[CultureData.GetLocaleInfo(LocaleGroupingData type)] failed");
+ Debug.Assert(false, "[CultureData.GetLocaleInfo(LocaleGroupingData type)] failed");
}
if (secondaryGroupingSize == 0)
[SecuritySafeCritical]
private string GetTimeFormatString(bool shortFormat)
{
- Contract.Assert(_sWindowsName != null, "[CultureData.GetTimeFormatString(bool shortFormat)] Expected _sWindowsName to be populated already");
+ Debug.Assert(_sWindowsName != null, "[CultureData.GetTimeFormatString(bool shortFormat)] Expected _sWindowsName to be populated already");
StringBuilder sb = StringBuilderCache.Acquire(ICU_ULOC_KEYWORD_AND_VALUES_CAPACITY);
{
// Failed, just use empty string
StringBuilderCache.Release(sb);
- Contract.Assert(false, "[CultureData.GetTimeFormatString(bool shortFormat)] Failed");
+ Debug.Assert(false, "[CultureData.GetTimeFormatString(bool shortFormat)] Failed");
return String.Empty;
}
// See the LICENSE file in the project root for more information.
using System.Collections.Generic;
-using System.Diagnostics.Contracts;
+using System.Diagnostics;
using System.Runtime.InteropServices;
using System.Text;
+
+#if ENABLE_WINRT
using Internal.Runtime.Augments;
+#endif
namespace System.Globalization
{
private string GetLocaleInfo(LocaleStringData type)
{
- Contract.Assert(_sWindowsName != null, "[CultureData.DoGetLocaleInfo] Expected _sWindowsName to be populated by already");
+ Debug.Assert(_sWindowsName != null, "[CultureData.DoGetLocaleInfo] Expected _sWindowsName to be populated by already");
return GetLocaleInfo(_sWindowsName, type);
}
// Ask OS for data, note that we presume it returns success, so we have to know that
// sWindowsName is valid before calling.
- Contract.Assert(_sWindowsName != null, "[CultureData.DoGetLocaleInfoInt] Expected _sWindowsName to be populated by already");
+ Debug.Assert(_sWindowsName != null, "[CultureData.DoGetLocaleInfoInt] Expected _sWindowsName to be populated by already");
int result = Interop.mincore.GetLocaleInfoExInt(_sWindowsName, lctype);
return result;
private int GetFirstDayOfWeek()
{
- Contract.Assert(_sWindowsName != null, "[CultureData.DoGetLocaleInfoInt] Expected _sWindowsName to be populated by already");
+ Debug.Assert(_sWindowsName != null, "[CultureData.DoGetLocaleInfoInt] Expected _sWindowsName to be populated by already");
const uint LOCALE_IFIRSTDAYOFWEEK = 0x0000100C;
private String[] GetTimeFormats()
{
// Note that this gets overrides for us all the time
- Contract.Assert(_sWindowsName != null, "[CultureData.DoEnumTimeFormats] Expected _sWindowsName to be populated by already");
+ Debug.Assert(_sWindowsName != null, "[CultureData.DoEnumTimeFormats] Expected _sWindowsName to be populated by already");
String[] result = ReescapeWin32Strings(nativeEnumTimeFormats(_sWindowsName, 0, UseUserOverride));
return result;
private String[] GetShortTimeFormats()
{
// Note that this gets overrides for us all the time
- Contract.Assert(_sWindowsName != null, "[CultureData.DoEnumShortTimeFormats] Expected _sWindowsName to be populated by already");
+ Debug.Assert(_sWindowsName != null, "[CultureData.DoEnumShortTimeFormats] Expected _sWindowsName to be populated by already");
String[] result = ReescapeWin32Strings(nativeEnumTimeFormats(_sWindowsName, TIME_NOSECONDS, UseUserOverride));
return result;
// region name match the requested region name
private static CultureData GetCultureDataFromRegionName(String regionName)
{
- Contract.Assert(regionName != null);
+ Debug.Assert(regionName != null);
const uint LOCALE_SUPPLEMENTAL = 0x00000002;
const uint LOCALE_SPECIFICDATA = 0x00000020;
return null;
}
- private static string GetLanguageDisplayName(string cultureName)
+ private string GetLanguageDisplayName(string cultureName)
{
+#if ENABLE_WINRT
return WinRTInterop.Callbacks.GetLanguageDisplayName(cultureName);
+#else
+ // Usually the UI culture shouldn't be different than what we got from WinRT except
+ // if DefaultThreadCurrentUICulture was set
+ CultureInfo ci;
+
+ if (CultureInfo.DefaultThreadCurrentUICulture != null &&
+ ((ci = GetUserDefaultCulture()) != null) &&
+ !CultureInfo.DefaultThreadCurrentUICulture.Name.Equals(ci.Name))
+ {
+ return SNATIVEDISPLAYNAME;
+ }
+ else
+ {
+ return GetLocaleInfo(cultureName, LocaleStringData.LocalizedDisplayName);
+ }
+#endif // ENABLE_WINRT
}
- private static string GetRegionDisplayName(string isoCountryCode)
+ private string GetRegionDisplayName(string isoCountryCode)
{
+#if ENABLE_WINRT
return WinRTInterop.Callbacks.GetRegionDisplayName(isoCountryCode);
+#else
+ // Usually the UI culture shouldn't be different than what we got from WinRT except
+ // if DefaultThreadCurrentUICulture was set
+ CultureInfo ci;
+
+ if (CultureInfo.DefaultThreadCurrentUICulture != null &&
+ ((ci = GetUserDefaultCulture()) != null) &&
+ !CultureInfo.DefaultThreadCurrentUICulture.Name.Equals(ci.Name))
+ {
+ return SNATIVECOUNTRY;
+ }
+ else
+ {
+ return GetLocaleInfo(LocaleStringData.LocalizedCountryName);
+ }
+#endif // ENABLE_WINRT
}
private static CultureInfo GetUserDefaultCulture()
{
+#if ENABLE_WINRT
return (CultureInfo)WinRTInterop.Callbacks.GetUserDefaultCulture();
+#else
+ return CultureInfo.GetUserDefaultCulture();
+#endif // ENABLE_WINRT
}
// PAL methods end here.
private static string GetLocaleInfoFromLCType(string localeName, uint lctype, bool useUserOveride)
{
- Contract.Assert(localeName != null, "[CultureData.GetLocaleInfoFromLCType] Expected localeName to be not be null");
+ Debug.Assert(localeName != null, "[CultureData.GetLocaleInfoFromLCType] Expected localeName to be not be null");
// Fix lctype if we don't want overrides
if (!useUserOveride)
return null;
}
-
- private static int LocaleNameToLCID(string cultureName)
+
+ private int LocaleNameToLCID(string cultureName)
{
- throw new NotImplementedException();
+ return GetLocaleInfo(LocaleNumberData.LanguageId);
}
-
+
private static string LCIDToLocaleName(int culture)
{
throw new NotImplementedException();
}
-
- private static int GetAnsiCodePage(string cultureName)
+
+ private int GetAnsiCodePage(string cultureName)
{
- throw new NotImplementedException();
+ return GetLocaleInfo(LocaleNumberData.AnsiCodePage);
}
- private static int GetOemCodePage(string cultureName)
+ private int GetOemCodePage(string cultureName)
{
- throw new NotImplementedException();
+ return GetLocaleInfo(LocaleNumberData.OemCodePage);
}
- private static int GetMacCodePage(string cultureName)
+ private int GetMacCodePage(string cultureName)
{
- throw new NotImplementedException();
+ return GetLocaleInfo(LocaleNumberData.MacCodePage);
}
- private static int GetEbcdicCodePage(string cultureName)
+ private int GetEbcdicCodePage(string cultureName)
{
- throw new NotImplementedException();
+ return GetLocaleInfo(LocaleNumberData.EbcdicCodePage);
}
- private static int GetGeoId(string cultureName)
+ private int GetGeoId(string cultureName)
{
- throw new NotImplementedException();
+ return GetLocaleInfo(LocaleNumberData.GeoId);
}
-
- private static int GetDigitSubstitution(string cultureName)
+
+ private int GetDigitSubstitution(string cultureName)
{
- throw new NotImplementedException();
+ return GetLocaleInfo(LocaleNumberData.DigitSubstitution);
}
-
- private static string GetThreeLetterWindowsLanguageName(string cultureName)
+
+ private string GetThreeLetterWindowsLanguageName(string cultureName)
{
- throw new NotImplementedException();
+ return GetLocaleInfo(cultureName, LocaleStringData.AbbreviatedWindowsLanguageName);
}
private static CultureInfo[] EnumCultures(CultureTypes types)
throw new NotImplementedException();
}
- private static string GetConsoleFallbackName(string cultureName)
+ private string GetConsoleFallbackName(string cultureName)
{
- throw new NotImplementedException();
+ return GetLocaleInfo(cultureName, LocaleStringData.ConsoleFallbackName);
}
- private bool IsSupplementalCustomCulture
+ internal bool IsFramework
{
get { throw new NotImplementedException(); }
}
-
- private bool IsWin32Installed
+
+ internal bool IsWin32Installed
{
get { throw new NotImplementedException(); }
}
- private bool IsReplacementCulture
+ internal bool IsReplacementCulture
{
get { throw new NotImplementedException(); }
}
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
-using System;
-using System.Collections;
using System.Collections.Generic;
+using System.Diagnostics;
using System.Text;
using System.Threading;
-using System.Runtime.CompilerServices;
-using System.Runtime.InteropServices;
-using System.Diagnostics.Contracts;
namespace System.Globalization
{
// Language
invariant._sISO639Language = "iv"; // ISO 639 Language Name
- invariant._sISO639Language2 = "ivl"; // 3 char ISO 639 lang name 2
+ invariant._sISO639Language2 = "ivl"; // 3 char ISO 639 lang name 2
invariant._sLocalizedLanguage = "Invariant Language"; // Display name for this Language
invariant._sEnglishLanguage = "Invariant Language"; // English name for this language
invariant._sNativeLanguage = "Invariant Language"; // Native name of this language
- invariant._sAbbrevLang = "IVL"; // abbreviated language name (Windows Language Name)
- invariant._sConsoleFallbackName = ""; // The culture name for the console fallback UI culture
- invariant._iInputLanguageHandle = 0x07F; // input language handle
+ invariant._sAbbrevLang = "IVL"; // abbreviated language name (Windows Language Name)
+ invariant._sConsoleFallbackName = ""; // The culture name for the console fallback UI culture
+ invariant._iInputLanguageHandle = 0x07F; // input language handle
// Region
invariant._sRegionName = "IV"; // (RegionInfo)
invariant._sEnglishCountry = "Invariant Country"; // english country name (RegionInfo)
invariant._sNativeCountry = "Invariant Country"; // native country name (Windows Only)
invariant._sISO3166CountryName = "IV"; // (RegionInfo), ie: US
- invariant._sISO3166CountryName2 = "ivc"; // 3 char ISO 3166 country name 2 2(RegionInfo)
- invariant._iGeoId = 244; // GeoId (Windows Only)
+ invariant._sISO3166CountryName2 = "ivc"; // 3 char ISO 3166 country name 2 2(RegionInfo)
+ invariant._iGeoId = 244; // GeoId (Windows Only)
// Numbers
invariant._sPositiveSign = "+"; // positive sign
{
get
{
- Contract.Assert(_sRealName != null, "[CultureData.CultureName] Expected _sRealName to be populated by already");
+ Debug.Assert(_sRealName != null, "[CultureData.CultureName] Expected _sRealName to be populated by already");
// since windows doesn't know about zh-CHS and zh-CHT,
// we leave sRealName == zh-Hanx but we still need to
// pretend that it was zh-CHX.
get
{
// This got populated during the culture initialization
- Contract.Assert(_sSpecificCulture != null, "[CultureData.SSPECIFICCULTURE] Expected this.sSpecificCulture to be populated by culture data initialization already");
+ Debug.Assert(_sSpecificCulture != null, "[CultureData.SSPECIFICCULTURE] Expected this.sSpecificCulture to be populated by culture data initialization already");
return _sSpecificCulture;
}
}
}
}
-
// Localized name for this language (Windows Only) ie: Inglis
// This is only valid for Windows 8 and higher neutrals:
internal String SLOCALIZEDLANGUAGE
// We then have to copy that list to a new array of the right size.
// Default calendar should be first
CalendarId[] calendars = new CalendarId[23];
- Contract.Assert(_sWindowsName != null, "[CultureData.CalendarIds] Expected _sWindowsName to be populated by already");
+ Debug.Assert(_sWindowsName != null, "[CultureData.CalendarIds] Expected _sWindowsName to be populated by already");
int count = CalendarData.GetCalendars(_sWindowsName, _bUseOverrides, calendars);
// See if we had a calendar to add.
internal CalendarData GetCalendar(CalendarId calendarId)
{
- Contract.Assert(calendarId > 0 && calendarId <= CalendarId.LAST_CALENDAR,
+ Debug.Assert(calendarId > 0 && calendarId <= CalendarId.LAST_CALENDAR,
"[CultureData.GetCalendar] Expect calendarId to be in a valid range");
// arrays are 0 based, calendarIds are 1 based
// Make sure that calendar has data
if (calendarData == null)
{
- Contract.Assert(_sWindowsName != null, "[CultureData.GetCalendar] Expected _sWindowsName to be populated by already");
+ Debug.Assert(_sWindowsName != null, "[CultureData.GetCalendar] Expected _sWindowsName to be populated by already");
calendarData = new CalendarData(_sWindowsName, calendarId, this.UseUserOverride);
_calendars[calendarIndex] = calendarData;
}
{
if (_iReadingLayout == undef)
{
- Contract.Assert(_sRealName != null, "[CultureData.IsRightToLeft] Expected _sRealName to be populated by already");
+ Debug.Assert(_sRealName != null, "[CultureData.IsRightToLeft] Expected _sRealName to be populated by already");
_iReadingLayout = GetLocaleInfo(LocaleNumberData.ReadingLayout);
}
{
// Note: Custom cultures might point at another culture's textinfo, however windows knows how
// to redirect it to the desired textinfo culture, so this is OK.
- Contract.Assert(_sRealName != null, "[CultureData.STEXTINFO] Expected _sRealName to be populated by already");
+ Debug.Assert(_sRealName != null, "[CultureData.STEXTINFO] Expected _sRealName to be populated by already");
return (_sRealName);
}
}
{
get
{
- Contract.Assert(_sRealName != null, "[CultureData.SCOMPAREINFO] Expected _sRealName to be populated by already");
+ Debug.Assert(_sRealName != null, "[CultureData.SCOMPAREINFO] Expected _sRealName to be populated by already");
return (_sRealName);
}
}
{
if (_iLanguage == 0)
{
- Contract.Assert(_sRealName != null, "[CultureData.ILANGUAGE] Expected this.sRealName to be populated by COMNlsInfo::nativeInitCultureData already");
+ Debug.Assert(_sRealName != null, "[CultureData.ILANGUAGE] Expected this.sRealName to be populated by COMNlsInfo::nativeInitCultureData already");
_iLanguage = LocaleNameToLCID(_sRealName);
}
return _iLanguage;
// All of our era names
internal String[] EraNames(CalendarId calendarId)
{
- Contract.Assert(calendarId > 0, "[CultureData.saEraNames] Expected Calendar.ID > 0");
+ Debug.Assert(calendarId > 0, "[CultureData.saEraNames] Expected Calendar.ID > 0");
return this.GetCalendar(calendarId).saEraNames;
}
internal String[] AbbrevEraNames(CalendarId calendarId)
{
- Contract.Assert(calendarId > 0, "[CultureData.saAbbrevEraNames] Expected Calendar.ID > 0");
+ Debug.Assert(calendarId > 0, "[CultureData.saAbbrevEraNames] Expected Calendar.ID > 0");
return this.GetCalendar(calendarId).saAbbrevEraNames;
}
internal String[] AbbreviatedEnglishEraNames(CalendarId calendarId)
{
- Contract.Assert(calendarId > 0, "[CultureData.saAbbrevEraNames] Expected Calendar.ID > 0");
+ Debug.Assert(calendarId > 0, "[CultureData.saAbbrevEraNames] Expected Calendar.ID > 0");
return this.GetCalendar(calendarId).saAbbrevEnglishEraNames;
}
////////////////////////////////////////////////////////////////////////////
private static String UnescapeNlsString(String str, int start, int end)
{
- Contract.Requires(str != null);
- Contract.Requires(start >= 0);
- Contract.Requires(end >= 0);
+ Debug.Assert(str != null);
+ Debug.Assert(start >= 0);
+ Debug.Assert(end >= 0);
StringBuilder result = null;
for (int i = start; i < str.Length && i <= end; i++)
private static int IndexOfTimePart(string format, int startIndex, string timeParts)
{
- Contract.Assert(startIndex >= 0, "startIndex cannot be negative");
- Contract.Assert(timeParts.IndexOfAny(new char[] { '\'', '\\' }) == -1, "timeParts cannot include quote characters");
+ Debug.Assert(startIndex >= 0, "startIndex cannot be negative");
+ Debug.Assert(timeParts.IndexOfAny(new char[] { '\'', '\\' }) == -1, "timeParts cannot include quote characters");
bool inQuote = false;
for (int i = startIndex; i < format.Length; ++i)
{
}
else
{
- Contract.Assert(_sWindowsName != null, "[CultureData.GetNFIValues] Expected _sWindowsName to be populated by already");
+ Debug.Assert(_sWindowsName != null, "[CultureData.GetNFIValues] Expected _sWindowsName to be populated by already");
// String values
nfi.positiveSign = GetLocaleInfo(LocaleStringData.PositiveSign);
nfi.negativeSign = GetLocaleInfo(LocaleStringData.NegativeSign);
{
nfi.nativeDigits[i] = new string(digits[i], 1);
}
-
+
nfi.digitSubstitution = GetDigitSubstitution(_sRealName);
}
EnglishLanguageName = 0x00001001,
/// <summary>native name of language, eg "Deutsch" (coresponds to LOCALE_SNATIVELANGUAGENAME)</summary>
NativeLanguageName = 0x00000004,
+ /// <summary>localized name of country, eg "Germany" in UI language (coresponds to LOCALE_SLOCALIZEDCOUNTRYNAME)</summary>
+ LocalizedCountryName = 0x00000006,
/// <summary>English name of country, eg "Germany" (coresponds to LOCALE_SENGLISHCOUNTRYNAME)</summary>
EnglishCountryName = 0x00001002,
/// <summary>native name of country, eg "Deutschland" (coresponds to LOCALE_SNATIVECOUNTRYNAME)</summary>
NativeCountryName = 0x00000008,
+ /// <summary>abbreviated language name (coresponds to LOCALE_SABBREVLANGNAME)</summary>
+ AbbreviatedWindowsLanguageName = 0x00000003,
/// <summary>list item separator (coresponds to LOCALE_SLIST)</summary>
ListSeparator = 0x0000000C,
/// <summary>decimal separator (coresponds to LOCALE_SDECIMAL)</summary>
Iso639LanguageTwoLetterName = 0x00000059,
/// <summary>ISO abbreviated country name (coresponds to LOCALE_SISO639LANGNAME2)</summary>
Iso639LanguageThreeLetterName = 0x00000067,
+ /// <summary>ISO abbreviated language name (coresponds to LOCALE_SISO639LANGNAME)</summary>
+ Iso639LanguageName = 0x00000059,
/// <summary>ISO abbreviated country name (coresponds to LOCALE_SISO3166CTRYNAME)</summary>
Iso3166CountryName = 0x0000005A,
/// <summary>3 letter ISO country code (coresponds to LOCALE_SISO3166CTRYNAME2)</summary>
NegativeInfinitySymbol = 0x0000006b,
/// <summary>Fallback name for resources (coresponds to LOCALE_SPARENT)</summary>
ParentName = 0x0000006d,
+ /// <summary>Fallback name for within the console (coresponds to LOCALE_SCONSOLEFALLBACKNAME)</summary>
+ ConsoleFallbackName = 0x0000006e,
/// <summary>Returns the percent symbol (coresponds to LOCALE_SPERCENT)</summary>
PercentSymbol = 0x00000076,
/// <summary>Returns the permille (U+2030) symbol (coresponds to LOCALE_SPERMILLE)</summary>
{
/// <summary>language id (coresponds to LOCALE_ILANGUAGE)</summary>
LanguageId = 0x00000001,
+ /// <summary>geographical location id, (coresponds to LOCALE_IGEOID)</summary>
+ GeoId = 0x00000008,
+ /// <summary>0 = context, 1 = none, 2 = national (coresponds to LOCALE_IDIGITSUBSTITUTION)</summary>
+ DigitSubstitution = 0x00001014,
/// <summary>0 = metric, 1 = US (coresponds to LOCALE_IMEASURE)</summary>
MeasurementSystem = 0x0000000D,
/// <summary>number of fractional digits (coresponds to LOCALE_IDIGITS)</summary>
/// <summary>Returns 0-11 for the negative percent format (coresponds to LOCALE_INEGATIVEPERCENT)</summary>
NegativePercentFormat = 0x00000074,
/// <summary>Returns 0-3 for the positive percent format (coresponds to LOCALE_IPOSITIVEPERCENT)</summary>
- PositivePercentFormat = 0x00000075
+ PositivePercentFormat = 0x00000075,
+ /// <summary>default ansi code page (coresponds to LOCALE_IDEFAULTCODEPAGE)</summary>
+ OemCodePage = 0x0000000B,
+ /// <summary>default ansi code page (coresponds to LOCALE_IDEFAULTANSICODEPAGE)</summary>
+ AnsiCodePage = 0x00001004,
+ /// <summary>default mac code page (coresponds to LOCALE_IDEFAULTMACCODEPAGE)</summary>
+ MacCodePage = 0x00001011,
+ /// <summary>default ebcdic code page (coresponds to LOCALE_IDEFAULTEBCDICCODEPAGE)</summary>
+ EbcdicCodePage = 0x00001012,
}
}
}
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
+#if ENABLE_WINRT
using Internal.Runtime.Augments;
+#endif
namespace System.Globalization
{
/// </remarks>
private static CultureInfo GetUserDefaultCultureCacheOverride()
{
+#if ENABLE_WINRT
WinRTInteropCallbacks callbacks = WinRTInterop.UnsafeCallbacks;
if (callbacks != null && callbacks.IsAppxModel())
{
return (CultureInfo)callbacks.GetUserDefaultCulture();
}
+#endif
return null;
}
- private static CultureInfo GetUserDefaultCulture()
+ internal static CultureInfo GetUserDefaultCulture()
{
const uint LOCALE_SNAME = 0x0000005c;
const string LOCALE_NAME_USER_DEFAULT = null;
//
////////////////////////////////////////////////////////////////////////////
-using System;
-using System.Collections;
using System.Collections.Generic;
+using System.Diagnostics;
using System.Diagnostics.Contracts;
-using System.Runtime;
-using System.Runtime.CompilerServices;
-using System.Runtime.InteropServices;
using System.Runtime.Serialization;
-using System.Security;
using System.Threading;
namespace System.Globalization
[OnDeserialized]
private void OnDeserialized(StreamingContext ctx)
{
- Contract.Assert(m_name != null, "[CultureInfo.OnDeserialized] m_name != null");
+ Debug.Assert(m_name != null, "[CultureInfo.OnDeserialized] m_name != null");
InitializeFromName(m_name, m_useUserOverride);
}
Init();
}
- Contract.Assert(s_userDefaultCulture != null);
+ Debug.Assert(s_userDefaultCulture != null);
return s_userDefaultCulture;
}
Init();
}
- Contract.Assert(s_userDefaultCulture != null);
+ Debug.Assert(s_userDefaultCulture != null);
return s_userDefaultCulture;
}
{
Init();
}
- Contract.Assert(s_userDefaultCulture != null, "[CultureInfo.InstalledUICulture] s_userDefaultCulture != null");
+ Debug.Assert(s_userDefaultCulture != null, "[CultureInfo.InstalledUICulture] s_userDefaultCulture != null");
return s_userDefaultCulture;
}
}
get
{
Contract.Ensures(Contract.Result<String>() != null);
- Contract.Assert(m_name != null, "[CultureInfo.DisplayName] Always expect m_name to be set");
+ Debug.Assert(m_name != null, "[CultureInfo.DisplayName] Always expect m_name to be set");
return m_cultureData.SLOCALIZEDDISPLAYNAME;
}
//calendars unless they're required.
internal static Calendar GetCalendarInstanceRare(CalendarId calType)
{
- Contract.Assert(calType != CalendarId.GREGORIAN, "calType!=CalendarId.GREGORIAN");
+ Debug.Assert(calType != CalendarId.GREGORIAN, "calType!=CalendarId.GREGORIAN");
switch (calType)
{
{
if (calendar == null)
{
- Contract.Assert(this.m_cultureData.CalendarIds.Length > 0, "this.m_cultureData.CalendarIds.Length > 0");
+ Debug.Assert(this.m_cultureData.CalendarIds.Length > 0, "this.m_cultureData.CalendarIds.Length > 0");
// Get the default calendar for this culture. Note that the value can be
// from registry if this is a user default culture.
Calendar newObj = this.m_cultureData.DefaultCalendar;
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
-using System;
-using System.Collections;
using System.Collections.Generic;
+using System.Diagnostics;
using System.Diagnostics.Contracts;
-using System.Runtime.InteropServices;
using System.Runtime.Serialization;
-using System.Security;
-using System.Text;
-using System.Threading;
namespace System.Globalization
{
[Serializable]
- public sealed partial class DateTimeFormatInfo : IFormatProvider, ICloneable
+ public sealed class DateTimeFormatInfo : IFormatProvider, ICloneable
{
// cache for the invariant culture.
// invariantInfo is constant irrespective of your current culture.
{
// Get the abbreviated day names for our current calendar
this.abbreviatedDayNames = _cultureData.AbbreviatedDayNames(Calendar.ID);
- Contract.Assert(this.abbreviatedDayNames.Length == 7, "[DateTimeFormatInfo.GetAbbreviatedDayOfWeekNames] Expected 7 day names in a week");
+ Debug.Assert(this.abbreviatedDayNames.Length == 7, "[DateTimeFormatInfo.GetAbbreviatedDayOfWeekNames] Expected 7 day names in a week");
}
return (this.abbreviatedDayNames);
}
{
// Get the super short day names for our current calendar
this.m_superShortDayNames = _cultureData.SuperShortDayNames(Calendar.ID);
- Contract.Assert(this.m_superShortDayNames.Length == 7, "[DateTimeFormatInfo.internalGetSuperShortDayNames] Expected 7 day names in a week");
+ Debug.Assert(this.m_superShortDayNames.Length == 7, "[DateTimeFormatInfo.internalGetSuperShortDayNames] Expected 7 day names in a week");
}
return (this.m_superShortDayNames);
}
{
// Get the day names for our current calendar
this.dayNames = _cultureData.DayNames(Calendar.ID);
- Contract.Assert(this.dayNames.Length == 7, "[DateTimeFormatInfo.GetDayOfWeekNames] Expected 7 day names in a week");
+ Debug.Assert(this.dayNames.Length == 7, "[DateTimeFormatInfo.GetDayOfWeekNames] Expected 7 day names in a week");
}
return (this.dayNames);
}
{
// Get the month names for our current calendar
this.abbreviatedMonthNames = _cultureData.AbbreviatedMonthNames(Calendar.ID);
- Contract.Assert(this.abbreviatedMonthNames.Length == 12 || this.abbreviatedMonthNames.Length == 13,
+ Debug.Assert(this.abbreviatedMonthNames.Length == 12 || this.abbreviatedMonthNames.Length == 13,
"[DateTimeFormatInfo.GetAbbreviatedMonthNames] Expected 12 or 13 month names in a year");
}
return (this.abbreviatedMonthNames);
{
// Get the month names for our current calendar
this.monthNames = _cultureData.MonthNames(Calendar.ID);
- Contract.Assert(this.monthNames.Length == 12 || this.monthNames.Length == 13,
+ Debug.Assert(this.monthNames.Length == 12 || this.monthNames.Length == 13,
"[DateTimeFormatInfo.GetMonthNames] Expected 12 or 13 month names in a year");
}
internal DateTimeFormatInfo(CultureData cultureData, Calendar cal)
{
- Contract.Requires(cultureData != null);
- Contract.Requires(cal != null);
+ Debug.Assert(cultureData != null);
+ Debug.Assert(cal != null);
// Remember our culture
_cultureData = cultureData;
private void InitializeOverridableProperties(CultureData cultureData, CalendarId calendarId)
{
- Contract.Requires(cultureData != null);
- Contract.Assert(calendarId != CalendarId.UNINITIALIZED_VALUE, "[DateTimeFormatInfo.Populate] Expected initalized calendarId");
+ Debug.Assert(cultureData != null);
+ Debug.Assert(calendarId != CalendarId.UNINITIALIZED_VALUE, "[DateTimeFormatInfo.Populate] Expected initalized calendarId");
if (this.firstDayOfWeek == -1) { this.firstDayOfWeek = cultureData.IFIRSTDAYOFWEEK; }
if (this.calendarWeekRule == -1) { this.calendarWeekRule = cultureData.IFIRSTWEEKOFYEAR; }
if (this.dateSeparator == null) { this.dateSeparator = cultureData.DateSeparator(calendarId); }
this.allLongTimePatterns = _cultureData.LongTimes;
- Contract.Assert(this.allLongTimePatterns.Length > 0, "[DateTimeFormatInfo.Populate] Expected some long time patterns");
+ Debug.Assert(this.allLongTimePatterns.Length > 0, "[DateTimeFormatInfo.Populate] Expected some long time patterns");
this.allShortTimePatterns = _cultureData.ShortTimes;
- Contract.Assert(this.allShortTimePatterns.Length > 0, "[DateTimeFormatInfo.Populate] Expected some short time patterns");
+ Debug.Assert(this.allShortTimePatterns.Length > 0, "[DateTimeFormatInfo.Populate] Expected some short time patterns");
this.allLongDatePatterns = cultureData.LongDates(calendarId);
- Contract.Assert(this.allLongDatePatterns.Length > 0, "[DateTimeFormatInfo.Populate] Expected some long date patterns");
+ Debug.Assert(this.allLongDatePatterns.Length > 0, "[DateTimeFormatInfo.Populate] Expected some long date patterns");
this.allShortDatePatterns = cultureData.ShortDates(calendarId);
- Contract.Assert(this.allShortDatePatterns.Length > 0, "[DateTimeFormatInfo.Populate] Expected some short date patterns");
+ Debug.Assert(this.allShortDatePatterns.Length > 0, "[DateTimeFormatInfo.Populate] Expected some short date patterns");
this.allYearMonthPatterns = cultureData.YearMonths(calendarId);
- Contract.Assert(this.allYearMonthPatterns.Length > 0, "[DateTimeFormatInfo.Populate] Expected some year month patterns");
+ Debug.Assert(this.allYearMonthPatterns.Length > 0, "[DateTimeFormatInfo.Populate] Expected some year month patterns");
}
[OptionalField(VersionAdded = 1)]
{
this.amDesignator = _cultureData.SAM1159;
}
- Contract.Assert(this.amDesignator != null, "DateTimeFormatInfo.AMDesignator, amDesignator != null");
+ Debug.Assert(this.amDesignator != null, "DateTimeFormatInfo.AMDesignator, amDesignator != null");
return (this.amDesignator);
}
{
Contract.Ensures(Contract.Result<Calendar>() != null);
- Contract.Assert(this.calendar != null, "DateTimeFormatInfo.Calendar: calendar != null");
+ Debug.Assert(this.calendar != null, "DateTimeFormatInfo.Calendar: calendar != null");
return (this.calendar);
}
{
if (this.m_abbrevEnglishEraNames == null)
{
- Contract.Assert(Calendar.ID > 0, "[DateTimeFormatInfo.AbbreviatedEnglishEraNames] Expected Calendar.ID > 0");
+ Debug.Assert(Calendar.ID > 0, "[DateTimeFormatInfo.AbbreviatedEnglishEraNames] Expected Calendar.ID > 0");
this.m_abbrevEnglishEraNames = _cultureData.AbbreviatedEnglishEraNames(Calendar.ID);
}
return (this.m_abbrevEnglishEraNames);
{
dateSeparator = _cultureData.DateSeparator(Calendar.ID);
}
- Contract.Assert(this.dateSeparator != null, "DateTimeFormatInfo.DateSeparator, dateSeparator != null");
+ Debug.Assert(this.dateSeparator != null, "DateTimeFormatInfo.DateSeparator, dateSeparator != null");
return dateSeparator;
}
-
set
{
if (IsReadOnly)
{
this.firstDayOfWeek = _cultureData.IFIRSTDAYOFWEEK;
}
- Contract.Assert(this.firstDayOfWeek != -1, "DateTimeFormatInfo.FirstDayOfWeek, firstDayOfWeek != -1");
+ Debug.Assert(this.firstDayOfWeek != -1, "DateTimeFormatInfo.FirstDayOfWeek, firstDayOfWeek != -1");
return ((DayOfWeek)this.firstDayOfWeek);
}
{
this.calendarWeekRule = _cultureData.IFIRSTWEEKOFYEAR;
}
- Contract.Assert(this.calendarWeekRule != -1, "DateTimeFormatInfo.CalendarWeekRule, calendarWeekRule != -1");
+ Debug.Assert(this.calendarWeekRule != -1, "DateTimeFormatInfo.CalendarWeekRule, calendarWeekRule != -1");
return ((CalendarWeekRule)this.calendarWeekRule);
}
{
if (this.monthDayPattern == null)
{
- Contract.Assert(Calendar.ID > 0, "[DateTimeFormatInfo.MonthDayPattern] Expected calID > 0");
+ Debug.Assert(Calendar.ID > 0, "[DateTimeFormatInfo.MonthDayPattern] Expected calID > 0");
this.monthDayPattern = _cultureData.MonthDay(Calendar.ID);
}
- Contract.Assert(this.monthDayPattern != null, "DateTimeFormatInfo.MonthDayPattern, monthDayPattern != null");
+ Debug.Assert(this.monthDayPattern != null, "DateTimeFormatInfo.MonthDayPattern, monthDayPattern != null");
return (this.monthDayPattern);
}
{
this.pmDesignator = _cultureData.SPM2359;
}
- Contract.Assert(this.pmDesignator != null, "DateTimeFormatInfo.PMDesignator, pmDesignator != null");
+ Debug.Assert(this.pmDesignator != null, "DateTimeFormatInfo.PMDesignator, pmDesignator != null");
return (this.pmDesignator);
}
{
timeSeparator = _cultureData.TimeSeparator;
}
- Contract.Assert(this.timeSeparator != null, "DateTimeFormatInfo.TimeSeparator, timeSeparator != null");
+ Debug.Assert(this.timeSeparator != null, "DateTimeFormatInfo.TimeSeparator, timeSeparator != null");
return (timeSeparator);
}
//
private static void CheckNullValue(String[] values, int length)
{
- Contract.Requires(values != null, "value != null");
- Contract.Requires(values.Length >= length);
+ Debug.Assert(values != null, "value != null");
+ Debug.Assert(values.Length >= length);
for (int i = 0; i < length; i++)
{
if (values[i] == null)
if (this.m_genitiveAbbreviatedMonthNames == null)
{
this.m_genitiveAbbreviatedMonthNames = _cultureData.AbbreviatedGenitiveMonthNames(this.Calendar.ID);
- Contract.Assert(this.m_genitiveAbbreviatedMonthNames.Length == 13,
+ Debug.Assert(this.m_genitiveAbbreviatedMonthNames.Length == 13,
"[DateTimeFormatInfo.GetGenitiveMonthNames] Expected 13 abbreviated genitive month names in a year");
}
return (this.m_genitiveAbbreviatedMonthNames);
if (this.genitiveMonthNames == null)
{
this.genitiveMonthNames = _cultureData.GenitiveMonthNames(this.Calendar.ID);
- Contract.Assert(this.genitiveMonthNames.Length == 13,
+ Debug.Assert(this.genitiveMonthNames.Length == 13,
"[DateTimeFormatInfo.GetGenitiveMonthNames] Expected 13 genitive month names in a year");
}
return (this.genitiveMonthNames);
{
if (this.leapYearMonthNames == null)
{
- Contract.Assert(Calendar.ID > 0, "[DateTimeFormatInfo.internalGetLeapYearMonthNames] Expected Calendar.ID > 0");
+ Debug.Assert(Calendar.ID > 0, "[DateTimeFormatInfo.internalGetLeapYearMonthNames] Expected Calendar.ID > 0");
this.leapYearMonthNames = _cultureData.LeapYearMonthNames(Calendar.ID);
- Contract.Assert(this.leapYearMonthNames.Length == 13,
+ Debug.Assert(this.leapYearMonthNames.Length == 13,
"[DateTimeFormatInfo.internalGetLeapYearMonthNames] Expepcted 13 leap year month names");
}
return (leapYearMonthNames);
// Get all possible combination of inputs
private static String[] GetCombinedPatterns(String[] patterns1, String[] patterns2, String connectString)
{
- Contract.Requires(patterns1 != null);
- Contract.Requires(patterns2 != null);
+ Debug.Assert(patterns1 != null);
+ Debug.Assert(patterns2 != null);
// Get array size
String[] result = new String[patterns1.Length * patterns2.Length];
// The resulting [] can get returned to the calling app, so clone it.
private static string[] GetMergedPatterns(string[] patterns, string defaultPattern)
{
- Contract.Assert(patterns != null && patterns.Length > 0,
+ Debug.Assert(patterns != null && patterns.Length > 0,
"[DateTimeFormatInfo.GetMergedPatterns]Expected array of at least one pattern");
- Contract.Assert(defaultPattern != null,
+ Debug.Assert(defaultPattern != null,
"[DateTimeFormatInfo.GetMergedPatterns]Expected non null default string");
// If the default happens to be the first in the list just return (a cloned) copy
{
if (this.allYearMonthPatterns == null)
{
- Contract.Assert(Calendar.ID > 0, "[DateTimeFormatInfo.UnclonedYearMonthPatterns] Expected Calendar.ID > 0");
+ Debug.Assert(Calendar.ID > 0, "[DateTimeFormatInfo.UnclonedYearMonthPatterns] Expected Calendar.ID > 0");
this.allYearMonthPatterns = _cultureData.YearMonths(this.Calendar.ID);
- Contract.Assert(this.allYearMonthPatterns.Length > 0,
+ Debug.Assert(this.allYearMonthPatterns.Length > 0,
"[DateTimeFormatInfo.UnclonedYearMonthPatterns] Expected some year month patterns");
}
{
if (allShortDatePatterns == null)
{
- Contract.Assert(Calendar.ID > 0, "[DateTimeFormatInfo.UnclonedShortDatePatterns] Expected Calendar.ID > 0");
+ Debug.Assert(Calendar.ID > 0, "[DateTimeFormatInfo.UnclonedShortDatePatterns] Expected Calendar.ID > 0");
this.allShortDatePatterns = _cultureData.ShortDates(this.Calendar.ID);
- Contract.Assert(this.allShortDatePatterns.Length > 0,
+ Debug.Assert(this.allShortDatePatterns.Length > 0,
"[DateTimeFormatInfo.UnclonedShortDatePatterns] Expected some short date patterns");
}
{
if (allLongDatePatterns == null)
{
- Contract.Assert(Calendar.ID > 0, "[DateTimeFormatInfo.UnclonedLongDatePatterns] Expected Calendar.ID > 0");
+ Debug.Assert(Calendar.ID > 0, "[DateTimeFormatInfo.UnclonedLongDatePatterns] Expected Calendar.ID > 0");
this.allLongDatePatterns = _cultureData.LongDates(this.Calendar.ID);
- Contract.Assert(this.allLongDatePatterns.Length > 0,
+ Debug.Assert(this.allLongDatePatterns.Length > 0,
"[DateTimeFormatInfo.UnclonedLongDatePatterns] Expected some long date patterns");
}
if (this.allShortTimePatterns == null)
{
this.allShortTimePatterns = _cultureData.ShortTimes;
- Contract.Assert(this.allShortTimePatterns.Length > 0,
+ Debug.Assert(this.allShortTimePatterns.Length > 0,
"[DateTimeFormatInfo.UnclonedShortTimePatterns] Expected some short time patterns");
}
if (this.allLongTimePatterns == null)
{
this.allLongTimePatterns = _cultureData.LongTimes;
- Contract.Assert(this.allLongTimePatterns.Length > 0,
+ Debug.Assert(this.allLongTimePatterns.Length > 0,
"[DateTimeFormatInfo.UnclonedLongTimePatterns] Expected some long time patterns");
}
} while (i < str.Value.Length && (state != HebrewNumberParsingState.FoundEndOfHebrewNumber));
// When we are here, we are either at the end of the string, or we find a valid Hebrew number.
- Contract.Assert(state == HebrewNumberParsingState.ContinueParsing || state == HebrewNumberParsingState.FoundEndOfHebrewNumber,
+ Debug.Assert(state == HebrewNumberParsingState.ContinueParsing || state == HebrewNumberParsingState.FoundEndOfHebrewNumber,
"Invalid returned state from HebrewNumber.ParseByChar()");
if (state != HebrewNumberParsingState.FoundEndOfHebrewNumber)
tokenValue = 0;
TokenHashValue value;
- Contract.Assert(str.Index < str.Value.Length, "DateTimeFormatInfo.Tokenize(): start < value.Length");
+ Debug.Assert(str.Index < str.Value.Length, "DateTimeFormatInfo.Tokenize(): start < value.Length");
char ch = str.m_current;
bool isLetter = Char.IsLetter(ch);
}
previousNode = temp;
};
- Contract.Assert(false, "The hashtable is full. This should not happen.");
+ Debug.Assert(false, "The hashtable is full. This should not happen.");
}
private void InsertHash(TokenHashValue[] hashTable, String str, TokenType tokenType, int tokenValue)
hashcode += hashProbe;
if (hashcode >= TOKEN_HASH_SIZE) hashcode -= TOKEN_HASH_SIZE;
} while (i < TOKEN_HASH_SIZE);
- Contract.Assert(false, "The hashtable is full. This should not happen.");
+ Debug.Assert(false, "The hashtable is full. This should not happen.");
}
private bool CompareStringIgnoreCaseOptimized(string string1, int offset1, int length1, string string2, int offset2, int length2)
// This class represents a starting/ending time for a period of daylight saving time.
[Serializable]
- public partial class DaylightTime
+ public class DaylightTime
{
- internal DateTime m_start;
- internal DateTime m_end;
- internal TimeSpan m_delta;
+ private readonly DateTime _start;
+ private readonly DateTime _end;
+ private readonly TimeSpan _delta;
private DaylightTime()
{
public DaylightTime(DateTime start, DateTime end, TimeSpan delta)
{
- m_start = start;
- m_end = end;
- m_delta = delta;
+ _start = start;
+ _end = end;
+ _delta = delta;
}
// The start date of a daylight saving period.
- public DateTime Start
- {
- get
- {
- return m_start;
- }
- }
+ public DateTime Start => _start;
// The end date of a daylight saving period.
- public DateTime End
- {
- get
- {
- return m_end;
- }
- }
+ public DateTime End => _end;
// Delta to stardard offset in ticks.
- public TimeSpan Delta
+ public TimeSpan Delta => _delta;
+ }
+
+ // Value type version of DaylightTime
+ internal struct DaylightTimeStruct
+ {
+ public DaylightTimeStruct(DateTime start, DateTime end, TimeSpan delta)
{
- get
- {
- return m_delta;
- }
+ Start = start;
+ End = end;
+ Delta = delta;
}
+
+ public readonly DateTime Start;
+ public readonly DateTime End;
+ public readonly TimeSpan Delta;
}
}
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
-using System;
-using System.Text;
+using System.Diagnostics;
using System.Diagnostics.Contracts;
namespace System.Globalization
[Serializable]
[System.Runtime.InteropServices.ComVisible(true)]
- public partial class HebrewCalendar : Calendar
+ public class HebrewCalendar : Calendar
{
public static readonly int HebrewEra = 1;
// is true.
//
NumDays -= (long)(s_lunarMonthLen[hebrewYearType * MaxMonthPlusOne + lunarDate.month] - lunarDate.day);
- Contract.Assert(NumDays >= 1, "NumDays >= 1");
+ Debug.Assert(NumDays >= 1, "NumDays >= 1");
// If NumDays is 1, then we are done. Otherwise, find the correct Hebrew month
// and day.
int hebrewYearType = GetHebrewYearType(year, era);
CheckHebrewMonthValue(year, month, era);
- Contract.Assert(hebrewYearType >= 1 && hebrewYearType <= 6,
+ Debug.Assert(hebrewYearType >= 1 && hebrewYearType <= 6,
"hebrewYearType should be from 1 to 6, but now hebrewYearType = " + hebrewYearType + " for hebrew year " + year);
int monthDays = s_lunarMonthLen[hebrewYearType * MaxMonthPlusOne + month];
if (monthDays == 0)
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
-using System;
using System.Text;
using System.Diagnostics;
-using System.Diagnostics.Contracts;
namespace System.Globalization
{
-
-#if INSIDE_CLR
- using Debug = BCLDebug;
-#endif
-
////////////////////////////////////////////////////////////////////////////
//
// Used in HebrewNumber.ParseByChar to maintain the context information (
Number -= 5000;
}
- Contract.Assert(Number > 0 && Number <= 999, "Number is out of range."); ;
+ Debug.Assert(Number > 0 && Number <= 999, "Number is out of range."); ;
//
// Get the Hundreds.
//
// The state machine for Hebrew number pasing.
//
- private readonly static HS[] s_numberPasingState =
+ private static readonly HS[] s_numberPasingState =
{
// 400 300/200 100 90~10 8~1 6, 7, 9, ' "
/* 0 */
--- /dev/null
+// Licensed to the .NET Foundation under one or more agreements.
+// The .NET Foundation licenses this file to you under the MIT license.
+// See the LICENSE file in the project root for more information.
+
+using Microsoft.Win32;
+
+namespace System.Globalization
+{
+ public partial class HijriCalendar : Calendar
+ {
+ private static int GetHijriDateAdjustment()
+ {
+ if (_hijriAdvance == Int32.MinValue) {
+ // Never been set before. Use the system value from registry.
+ _hijriAdvance = GetAdvanceHijriDate();
+ }
+ return (_hijriAdvance);
+ }
+
+ private const String InternationalRegKey = "Control Panel\\International";
+ private const String HijriAdvanceRegKeyEntry = "AddHijriDate";
+
+ /*=================================GetAdvanceHijriDate==========================
+ **Action: Gets the AddHijriDate value from the registry.
+ **Returns:
+ **Arguments: None.
+ **Exceptions:
+ **Note:
+ ** The HijriCalendar has a user-overidable calculation. That is, use can set a value from the control
+ ** panel, so that the calculation of the Hijri Calendar can move ahead or backwards from -2 to +2 days.
+ **
+ ** The valid string values in the registry are:
+ ** "AddHijriDate-2" => Add -2 days to the current calculated Hijri date.
+ ** "AddHijriDate" => Add -1 day to the current calculated Hijri date.
+ ** "" => Add 0 day to the current calculated Hijri date.
+ ** "AddHijriDate+1" => Add +1 days to the current calculated Hijri date.
+ ** "AddHijriDate+2" => Add +2 days to the current calculated Hijri date.
+ ============================================================================*/
+ private static int GetAdvanceHijriDate() {
+ int hijriAdvance = 0;
+ Microsoft.Win32.RegistryKey key = null;
+
+ try {
+ // Open in read-only mode.
+ // Use InternalOpenSubKey so that we avoid the security check.
+ key = RegistryKey.GetBaseKey(RegistryKey.HKEY_CURRENT_USER).OpenSubKey(InternationalRegKey, false);
+ }
+ //If this fails for any reason, we'll just return 0.
+ catch (ObjectDisposedException) { return 0; }
+ catch (ArgumentException) { return 0; }
+
+ if (key != null) {
+ try {
+ Object value = key.InternalGetValue(HijriAdvanceRegKeyEntry, null, false, false);
+ if (value == null) {
+ return (0);
+ }
+ String str = value.ToString();
+ if (String.Compare(str, 0, HijriAdvanceRegKeyEntry, 0, HijriAdvanceRegKeyEntry.Length, StringComparison.OrdinalIgnoreCase) == 0) {
+ if (str.Length == HijriAdvanceRegKeyEntry.Length)
+ hijriAdvance = -1;
+ else {
+ str = str.Substring(HijriAdvanceRegKeyEntry.Length);
+ try {
+ int advance = Int32.Parse(str.ToString(), CultureInfo.InvariantCulture);
+ if ((advance >= MinAdvancedHijri) && (advance <= MaxAdvancedHijri)) {
+ hijriAdvance = advance;
+ }
+ }
+ // If we got garbage from registry just ignore it.
+ // hijriAdvance = 0 because of declaraction assignment up above.
+ catch (ArgumentException) { }
+ catch (FormatException) { }
+ catch (OverflowException) { }
+ }
+ }
+ }
+ finally {
+ key.Close();
+ }
+
+ }
+ return (hijriAdvance);
+ }
+ }
+}
{
public partial class HijriCalendar : Calendar
{
- public static int GetHijriDateAdjustment()
+ private static int GetHijriDateAdjustment()
{
return WinRTInterop.Callbacks.GetHijriDateAdjustment();
}
// See the LICENSE file in the project root for more information.
using System.Collections.Generic;
-using System.Security;
namespace System.Globalization
{
public partial class JapaneseCalendar : Calendar
{
- [SecuritySafeCritical]
private static EraInfo[] GetJapaneseEras()
{
string[] eraNames;
return eraNames[eraIndex].Substring(0, 1);
}
- [SecuritySafeCritical]
private static bool GetJapaneseEraStartDate(int era, out DateTime dateTime)
{
dateTime = default(DateTime);
--- /dev/null
+// Licensed to the .NET Foundation under one or more agreements.
+// The .NET Foundation licenses this file to you under the MIT license.
+// See the LICENSE file in the project root for more information.
+
+using System.Diagnostics;
+
+using Microsoft.Win32;
+
+namespace System.Globalization
+{
+ public partial class JapaneseCalendar : Calendar
+ {
+ private const string c_japaneseErasHive = @"System\CurrentControlSet\Control\Nls\Calendars\Japanese\Eras";
+ private const string c_japaneseErasHivePermissionList = @"HKEY_LOCAL_MACHINE\" + c_japaneseErasHive;
+
+ // We know about 4 built-in eras, however users may add additional era(s) from the
+ // registry, by adding values to HKLM\SYSTEM\CurrentControlSet\Control\Nls\Calendars\Japanese\Eras
+ //
+ // Registry values look like:
+ // yyyy.mm.dd=era_abbrev_english_englishabbrev
+ //
+ // Where yyyy.mm.dd is the registry value name, and also the date of the era start.
+ // yyyy, mm, and dd are the year, month & day the era begins (4, 2 & 2 digits long)
+ // era is the Japanese Era name
+ // abbrev is the Abbreviated Japanese Era Name
+ // english is the English name for the Era (unused)
+ // englishabbrev is the Abbreviated English name for the era.
+ // . is a delimiter, but the value of . doesn't matter.
+ // '_' marks the space between the japanese era name, japanese abbreviated era name
+ // english name, and abbreviated english names.
+ private static EraInfo[] GetJapaneseEras()
+ {
+ // Look in the registry key and see if we can find any ranges
+ int iFoundEras = 0;
+ EraInfo[] registryEraRanges = null;
+
+ try
+ {
+ // Need to access registry
+ RegistryKey key = RegistryKey.GetBaseKey(RegistryKey.HKEY_LOCAL_MACHINE).OpenSubKey(c_japaneseErasHive, false);
+
+ // Abort if we didn't find anything
+ if (key == null) return null;
+
+ // Look up the values in our reg key
+ String[] valueNames = key.GetValueNames();
+ if (valueNames != null && valueNames.Length > 0)
+ {
+ registryEraRanges = new EraInfo[valueNames.Length];
+
+ // Loop through the registry and read in all the values
+ for (int i = 0; i < valueNames.Length; i++)
+ {
+ // See if the era is a valid date
+ EraInfo era = GetEraFromValue(valueNames[i], key.GetValue(valueNames[i]).ToString());
+
+ // continue if not valid
+ if (era == null) continue;
+
+ // Remember we found one.
+ registryEraRanges[iFoundEras] = era;
+ iFoundEras++;
+ }
+ }
+ }
+ catch (System.Security.SecurityException)
+ {
+ // If we weren't allowed to read, then just ignore the error
+ return null;
+ }
+ catch (System.IO.IOException)
+ {
+ // If key is being deleted just ignore the error
+ return null;
+ }
+ catch (System.UnauthorizedAccessException)
+ {
+ // Registry access rights permissions, just ignore the error
+ return null;
+ }
+
+ //
+ // If we didn't have valid eras, then fail
+ // should have at least 4 eras
+ //
+ if (iFoundEras < 4) return null;
+
+ //
+ // Now we have eras, clean them up.
+ //
+ // Clean up array length
+ Array.Resize(ref registryEraRanges, iFoundEras);
+
+ // Sort them
+ Array.Sort(registryEraRanges, CompareEraRanges);
+
+ // Clean up era information
+ for (int i = 0; i < registryEraRanges.Length; i++)
+ {
+ // eras count backwards from length to 1 (and are 1 based indexes into string arrays)
+ registryEraRanges[i].era = registryEraRanges.Length - i;
+
+ // update max era year
+ if (i == 0)
+ {
+ // First range is 'til the end of the calendar
+ registryEraRanges[0].maxEraYear = GregorianCalendar.MaxYear - registryEraRanges[0].yearOffset;
+ }
+ else
+ {
+ // Rest are until the next era (remember most recent era is first in array)
+ registryEraRanges[i].maxEraYear = registryEraRanges[i-1].yearOffset + 1 - registryEraRanges[i].yearOffset;
+ }
+ }
+
+ // Return our ranges
+ return registryEraRanges;
+ }
+
+ //
+ // Compare two era ranges, eg just the ticks
+ // Remember the era array is supposed to be in reverse chronological order
+ //
+ private static int CompareEraRanges(EraInfo a, EraInfo b)
+ {
+ return b.ticks.CompareTo(a.ticks);
+ }
+
+ //
+ // GetEraFromValue
+ //
+ // Parse the registry value name/data pair into an era
+ //
+ // Registry values look like:
+ // yyyy.mm.dd=era_abbrev_english_englishabbrev
+ //
+ // Where yyyy.mm.dd is the registry value name, and also the date of the era start.
+ // yyyy, mm, and dd are the year, month & day the era begins (4, 2 & 2 digits long)
+ // era is the Japanese Era name
+ // abbrev is the Abbreviated Japanese Era Name
+ // english is the English name for the Era (unused)
+ // englishabbrev is the Abbreviated English name for the era.
+ // . is a delimiter, but the value of . doesn't matter.
+ // '_' marks the space between the japanese era name, japanese abbreviated era name
+ // english name, and abbreviated english names.
+ private static EraInfo GetEraFromValue(String value, String data)
+ {
+ // Need inputs
+ if (value == null || data == null) return null;
+
+ //
+ // Get Date
+ //
+ // Need exactly 10 characters in name for date
+ // yyyy.mm.dd although the . can be any character
+ if (value.Length != 10) return null;
+
+ int year;
+ int month;
+ int day;
+
+ if (!Int32.TryParse(value.Substring(0,4), NumberStyles.None, NumberFormatInfo.InvariantInfo, out year) ||
+ !Int32.TryParse(value.Substring(5,2), NumberStyles.None, NumberFormatInfo.InvariantInfo, out month) ||
+ !Int32.TryParse(value.Substring(8,2), NumberStyles.None, NumberFormatInfo.InvariantInfo, out day))
+ {
+ // Couldn't convert integer, fail
+ return null;
+ }
+
+ //
+ // Get Strings
+ //
+ // Needs to be a certain length e_a_E_A at least (7 chars, exactly 4 groups)
+ String[] names = data.Split(new char[] {'_'});
+
+ // Should have exactly 4 parts
+ // 0 - Era Name
+ // 1 - Abbreviated Era Name
+ // 2 - English Era Name
+ // 3 - Abbreviated English Era Name
+ if (names.Length != 4) return null;
+
+ // Each part should have data in it
+ if (names[0].Length == 0 ||
+ names[1].Length == 0 ||
+ names[2].Length == 0 ||
+ names[3].Length == 0)
+ return null;
+
+ //
+ // Now we have an era we can build
+ // Note that the era # and max era year need cleaned up after sorting
+ // Don't use the full English Era Name (names[2])
+ //
+ return new EraInfo( 0, year, month, day, year - 1, 1, 0,
+ names[0], names[1], names[3]);
+ }
+
+ // PAL Layer ends here
+
+ private static string[] JapaneseErasEnglishNames = new String[] { "M", "T", "S", "H" };
+
+ private static string GetJapaneseEnglishEraName(int era)
+ {
+ Debug.Assert(era > 0);
+ return era <= JapaneseErasEnglishNames.Length ? JapaneseErasEnglishNames[era - 1] : " ";
+ }
+ }
+}
namespace System.Globalization
{
-
-#if INSIDE_CLR
- using Debug = BCLDebug;
-#endif
-
/*=================================JapaneseCalendar==========================
**
** JapaneseCalendar is based on Gregorian calendar. The month and day values are the same as
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
+using System.Diagnostics;
using System.Diagnostics.Contracts;
// This file contains the handling of Windows OS specific culture features.
int right = s_lcids.Length - 1;
int index;
- Contract.Assert(s_lcids.Length == s_lcidToCultureNameIndices.Length);
+ Debug.Assert(s_lcids.Length == s_lcidToCultureNameIndices.Length);
while (left <= right)
{
if (culture == s_lcids[index])
{
int indexToLocaleNamesIndices = s_lcidToCultureNameIndices[index];
- Contract.Assert(indexToLocaleNamesIndices < s_localeNamesIndices.Length - 1);
+ Debug.Assert(indexToLocaleNamesIndices < s_localeNamesIndices.Length - 1);
return c_localeNames.Substring(s_localeNamesIndices[indexToLocaleNamesIndices],
s_localeNamesIndices[indexToLocaleNamesIndices + 1] -
return -1;
}
- Contract.Assert((s_localeNamesIndices.Length-1 == (s_nameIndexToNumericData.Length/NUMERIC_LOCALE_DATA_COUNT_PER_ROW)) &&
+ Debug.Assert((s_localeNamesIndices.Length-1 == (s_nameIndexToNumericData.Length/NUMERIC_LOCALE_DATA_COUNT_PER_ROW)) &&
index < s_localeNamesIndices.Length);
return s_nameIndexToNumericData[index * NUMERIC_LOCALE_DATA_COUNT_PER_ROW + (int) part];
return null;
}
- Contract.Assert(s_localeNamesIndices.Length-1 == (c_threeLetterWindowsLanguageName.Length / 3));
+ Debug.Assert(s_localeNamesIndices.Length-1 == (c_threeLetterWindowsLanguageName.Length / 3));
return c_threeLetterWindowsLanguageName.Substring(index * 3, 3);
}
return ""; // fallback to invariant
}
- Contract.Assert(indexToIndicesTable < s_localeNamesIndices.Length-1);
+ Debug.Assert(indexToIndicesTable < s_localeNamesIndices.Length-1);
return c_localeNames.Substring(s_localeNamesIndices[indexToIndicesTable],
s_localeNamesIndices[indexToIndicesTable+1] - s_localeNamesIndices[indexToIndicesTable]);
int index;
int result;
- Contract.Assert(s_localeNamesIndices[s_localeNamesIndices.Length - 1] == c_localeNames.Length);
+ Debug.Assert(s_localeNamesIndices[s_localeNamesIndices.Length - 1] == c_localeNames.Length);
name = CultureData.AnsiToLower(name);
{
index = ((right - left) / 2) + left;
- Contract.Assert(index < s_localeNamesIndices.Length - 1);
+ Debug.Assert(index < s_localeNamesIndices.Length - 1);
result = CompareOrdinal(name, c_localeNames, s_localeNamesIndices[index], s_localeNamesIndices[index + 1] - s_localeNamesIndices[index]);
if (result == 0)
{
// Walk the remaining elements (it'll be 3 or fewer).
for (; left <= right; left++)
{
- Contract.Assert(left < s_localeNamesIndices.Length - 1);
+ Debug.Assert(left < s_localeNamesIndices.Length - 1);
if (CompareOrdinal(name, c_localeNames, s_localeNamesIndices[left], s_localeNamesIndices[left + 1] - s_localeNamesIndices[left]) == 0)
{
return (left);
//
[Serializable]
- sealed public partial class NumberFormatInfo : IFormatProvider, ICloneable
+ sealed public class NumberFormatInfo : IFormatProvider, ICloneable
{
// invariantInfo is constant irrespective of your current culture.
private static volatile NumberFormatInfo s_invariantInfo;
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
-using System;
+using System.Diagnostics;
using System.Diagnostics.Contracts;
namespace System.Globalization
private static int MonthFromOrdinalDay(int ordinalDay)
{
- Contract.Assert(ordinalDay <= 366);
+ Debug.Assert(ordinalDay <= 366);
int index = 0;
while (ordinalDay > DaysToMonth[index])
index++;
private static int DaysInPreviousMonths(int month)
{
- Contract.Assert(1 <= month && month <= 12);
+ Debug.Assert(1 <= month && month <= 12);
--month; // months are one based but for calculations use 0 based
return DaysToMonth[month];
}
long yearStart = CalendricalCalculationsHelper.PersianNewYearOnOrBefore(NumDays);
int y = (int)(Math.Floor(((yearStart - PersianEpoch) / CalendricalCalculationsHelper.MeanTropicalYearInDays) + 0.5)) + 1;
- Contract.Assert(y >= 1);
+ Debug.Assert(y >= 1);
if (part == DatePartYear)
{
}
int m = MonthFromOrdinalDay(ordinalDay);
- Contract.Assert(ordinalDay >= 1);
- Contract.Assert(m >= 1 && m <= 12);
+ Debug.Assert(ordinalDay >= 1);
+ Debug.Assert(m >= 1 && m <= 12);
if (part == DatePartMonth)
{
return m;
}
int d = ordinalDay - DaysInPreviousMonths(m);
- Contract.Assert(1 <= d);
- Contract.Assert(d <= 31);
+ Debug.Assert(1 <= d);
+ Debug.Assert(d <= 31);
//
// Calculate the Persian Day.
int daysInMonth = DaysToMonth[month] - DaysToMonth[month - 1];
if ((month == MonthsPerYear) && !IsLeapYear(year))
{
- Contract.Assert(daysInMonth == 30);
+ Debug.Assert(daysInMonth == 30);
--daysInMonth;
}
return daysInMonth;
//
////////////////////////////////////////////////////////////////////////////
-using System;
+using System.Diagnostics;
using System.Diagnostics.Contracts;
using System.Runtime.Serialization;
namespace System.Globalization
{
[Serializable]
- public partial class RegionInfo
+ public class RegionInfo
{
//--------------------------------------------------------------------//
// Internal Information //
{
get
{
- Contract.Assert(_name != null, "Expected RegionInfo._name to be populated already");
+ Debug.Assert(_name != null, "Expected RegionInfo._name to be populated already");
return (_name);
}
}
using System;
using System.Runtime.CompilerServices;
using System.Runtime.Serialization;
+ using System.Diagnostics;
using System.Diagnostics.Contracts;
[System.Runtime.InteropServices.ComVisible(true)]
byte[] key1Data = sortkey1._keyData;
byte[] key2Data = sortkey2._keyData;
- Contract.Assert(key1Data != null, "key1Data != null");
- Contract.Assert(key2Data != null, "key2Data != null");
+ Debug.Assert(key1Data != null, "key1Data != null");
+ Debug.Assert(key2Data != null, "key2Data != null");
if (key1Data.Length == 0)
{
////////////////////////////////////////////////////////////////////////////
using System;
+using System.Diagnostics;
using System.Diagnostics.Contracts;
using System.Runtime.Serialization;
{
[Serializable]
[System.Runtime.InteropServices.ComVisible(true)]
- public partial class StringInfo
+ public class StringInfo
{
[OptionalField(VersionAdded = 2)]
private string _str;
internal static int GetCurrentTextElementLen(string str, int index, int len, ref UnicodeCategory ucCurrent, ref int currentCharCount)
{
- Contract.Assert(index >= 0 && len >= 0, "StringInfo.GetCurrentTextElementLen() : index = " + index + ", len = " + len);
- Contract.Assert(index < len, "StringInfo.GetCurrentTextElementLen() : index = " + index + ", len = " + len);
+ Debug.Assert(index >= 0 && len >= 0, "StringInfo.GetCurrentTextElementLen() : index = " + index + ", len = " + len);
+ Debug.Assert(index < len, "StringInfo.GetCurrentTextElementLen() : index = " + index + ", len = " + len);
if (index + currentCharCount == len)
{
// This is the last character/surrogate in the string.
////////////////////////////////////////////////////////////////////////////
using System.Collections;
-using System.Diagnostics.Contracts;
+using System.Diagnostics;
using System.Runtime.Serialization;
namespace System.Globalization
internal TextElementEnumerator(String str, int startIndex, int strLen)
{
- Contract.Assert(str != null, "TextElementEnumerator(): str != null");
- Contract.Assert(startIndex >= 0 && strLen >= 0, "TextElementEnumerator(): startIndex >= 0 && strLen >= 0");
- Contract.Assert(strLen >= startIndex, "TextElementEnumerator(): strLen >= startIndex");
+ Debug.Assert(str != null, "TextElementEnumerator(): str != null");
+ Debug.Assert(startIndex >= 0 && strLen >= 0, "TextElementEnumerator(): startIndex >= 0 && strLen >= 0");
+ Debug.Assert(strLen >= startIndex, "TextElementEnumerator(): strLen >= startIndex");
_str = str;
_startIndex = startIndex;
_strLen = strLen;
}
//
- // Get the starting _index of the current text element.
+ // Get the starting index of the current text element.
//
public int ElementIndex
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
+using System.Diagnostics;
using System.Diagnostics.Contracts;
using System.Security;
using System.Text;
[SecuritySafeCritical]
private unsafe string ChangeCase(string s, bool toUpper)
{
- Contract.Assert(s != null);
+ Debug.Assert(s != null);
if (s.Length == 0)
{
private bool NeedsTurkishCasing(string localeName)
{
- Contract.Assert(localeName != null);
+ Debug.Assert(localeName != null);
return CultureInfo.GetCultureInfo(localeName).CompareInfo.Compare("\u0131", "I", CompareOptions.IgnoreCase) == 0;
}
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
-using System.Diagnostics.Contracts;
+using System.Diagnostics;
namespace System.Globalization
{
private unsafe string ChangeCase(string s, bool toUpper)
{
- Contract.Assert(s != null);
+ Debug.Assert(s != null);
//
// Get the length of the string.
throw new InvalidOperationException(SR.InvalidOperation_ReadOnly);
}
- Contract.Assert(ret == nLengthInput, "Expected getting the same length of the original string");
+ Debug.Assert(ret == nLengthInput, "Expected getting the same length of the original string");
return result;
}
}
//
////////////////////////////////////////////////////////////////////////////
-using System;
+using System.Diagnostics;
using System.Diagnostics.Contracts;
-using System.Runtime;
-using System.Runtime.CompilerServices;
-using System.Runtime.InteropServices;
using System.Runtime.Serialization;
-using System.Security;
using System.Text;
-using System.Threading;
namespace System.Globalization
{
////
//// Clone
////
- //// Is the implementation of IColnable.
+ //// Is the implementation of ICloneable.
////
//////////////////////////////////////////////////////////////////////////
- public virtual Object Clone()
+ public virtual object Clone()
{
object o = MemberwiseClone();
((TextInfo)o).SetReadOnlyState(false);
return c;
}
- static private bool IsAscii(Char c)
+ private static bool IsAscii(Char c)
{
return c < 0x80;
}
private static int AddNonLetter(ref StringBuilder result, ref String input, int inputIndex, int charLen)
{
- Contract.Assert(charLen == 1 || charLen == 2, "[TextInfo.AddNonLetter] CharUnicodeInfo.InternalGetUnicodeCategory returned an unexpected charLen!");
+ Debug.Assert(charLen == 1 || charLen == 2, "[TextInfo.AddNonLetter] CharUnicodeInfo.InternalGetUnicodeCategory returned an unexpected charLen!");
if (charLen == 2)
{
// Surrogate pair
private int AddTitlecaseLetter(ref StringBuilder result, ref String input, int inputIndex, int charLen)
{
- Contract.Assert(charLen == 1 || charLen == 2, "[TextInfo.AddTitlecaseLetter] CharUnicodeInfo.InternalGetUnicodeCategory returned an unexpected charLen!");
+ Debug.Assert(charLen == 1 || charLen == 2, "[TextInfo.AddTitlecaseLetter] CharUnicodeInfo.InternalGetUnicodeCategory returned an unexpected charLen!");
// for surrogate pairs do a simple ToUpper operation on the substring
if (charLen == 2)
private unsafe int GetCaseInsensitiveHashCodeSlow(String str)
{
- Contract.Assert(str != null);
+ Debug.Assert(str != null);
string upper = ToUpper(str);
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
-using System;
+using System.Diagnostics;
using System.Diagnostics.Contracts;
namespace System.Globalization
=========================ConvertHijriToGregorian============================*/
private static void ConvertHijriToGregorian(int HijriYear, int HijriMonth, int HijriDay, ref int yg, ref int mg, ref int dg)
{
- Contract.Assert((HijriYear >= MinCalendarYear) && (HijriYear <= MaxCalendarYear), "Hijri year is out of range.");
- Contract.Assert(HijriMonth >= 1, "Hijri month is out of range.");
- Contract.Assert(HijriDay >= 1, "Hijri day is out of range.");
+ Debug.Assert((HijriYear >= MinCalendarYear) && (HijriYear <= MaxCalendarYear), "Hijri year is out of range.");
+ Debug.Assert(HijriMonth >= 1, "Hijri month is out of range.");
+ Debug.Assert(HijriDay >= 1, "Hijri day is out of range.");
int index, b, nDays = HijriDay - 1;
DateTime dt;
TimeSpan ts;
int yh1 = 0, mh1 = 0, dh1 = 0;
- Contract.Assert((time.Ticks >= minDate.Ticks) && (time.Ticks <= maxDate.Ticks), "Gregorian date is out of range.");
+ Debug.Assert((time.Ticks >= minDate.Ticks) && (time.Ticks <= maxDate.Ticks), "Gregorian date is out of range.");
// Find the index where we should start our search by quessing the Hijri year that we will be in HijriYearInfo.
// A Hijri year is 354 or 355 days. Use 355 days so that we will search from a lower index.
{
int days = 0, b;
- Contract.Assert((year >= MinCalendarYear) && (year <= MaxCalendarYear), "Hijri year is out of range.");
+ Debug.Assert((year >= MinCalendarYear) && (year <= MaxCalendarYear), "Hijri year is out of range.");
b = s_hijriYearInfo[year - MinCalendarYear].HijriMonthsLengthFlags;
days = days + 29 + (b & 1); /* Add the months lengths before mh */
b = b >> 1;
}
- Contract.Assert((days == 354) || (days == 355), "Hijri year has to be 354 or 355 days.");
+ Debug.Assert((days == 354) || (days == 355), "Hijri year has to be 354 or 355 days.");
return days;
}
internal NativeOverlapped* Overlapped
{
- [SecurityCritical]get { return _overlapped; }
+ get { return _overlapped; }
}
public void SetCompletedSynchronously(int numBytes)
/// <summary>
/// True if the buffer contains the given character.
/// </summary>
- [System.Security.SecurityCritical]
public unsafe bool Contains(char value)
{
char* start = CharPointer;
<Member Name="get_Array" />
<Member Name="get_Count" />
<Member Name="get_Offset" />
+ <Member Name="GetEnumerator" />
<Member Name="GetHashCode" />
<Member Name="op_Equality(System.ArraySegment<T>,System.ArraySegment<T>)" />
<Member Name="op_Inequality(System.ArraySegment<T>,System.ArraySegment<T>)" />
<Member MemberType="Property" Name="Count" />
<Member MemberType="Property" Name="Offset" />
</Type>
+ <Type Name="System.ArraySegment<T>+Enumerator">
+ <Member Name="Dispose" />
+ <Member Name="get_Current" />
+ <Member Name="MoveNext" />
+ <Member MemberType="Property" Name="Current" />
+ <Member Name="System.Collections.IEnumerator.Reset" />
+ </Type>
<Type Name="System.ArrayTypeMismatchException">
<Member Name="#ctor" />
<Member Name="#ctor(System.String)" />
<Type Name="System.Runtime.CompilerServices.ConditionalWeakTable<TKey,TValue>">
<Member Name="#ctor" />
<Member Name="Add(TKey,TValue)" />
+ <Member Name="AddOrUpdate(TKey,TValue)" />
<Member Name="Remove(TKey)" />
<Member Name="TryGetValue(TKey,TValue@)" />
<Member Name="GetValue(TKey,System.Runtime.CompilerServices.ConditionalWeakTable+CreateValueCallback)" />
<Member Name="AppendFormat(System.String,System.Object,System.Object)" />
<Member Name="AppendFormat(System.String,System.Object,System.Object,System.Object)" />
<Member Name="AppendFormat(System.String,System.Object[])" />
+ <Member Name="AppendJoin<T>(System.Char,System.Collections.Generic.IEnumerable<T>)" />
+ <Member Name="AppendJoin<T>(System.Char,T[])" />
+ <Member Name="AppendJoin<T>(System.String,System.Collections.Generic.IEnumerable<T>)" />
+ <Member Name="AppendJoin<T>(System.String,T[])" />
<Member Name="AppendLine" />
<Member Name="AppendLine(System.String)" />
<Member Name="Clear" />
<Member Name="DangerousGetPinnableReference" />
<Member Name="op_Implicit(T[])" ReturnType="System.Span<T>" />
<Member Name="op_Implicit(System.ArraySegment<T>)" ReturnType="System.Span<T>" />
+ <Member Name="op_Equality(System.Span<T>,System.Span<T>)" />
+ <Member Name="op_Inequality(System.Span<T>,System.Span<T>)" />
<Member Name="get_Length" />
<Member Name="get_Empty" />
<Member Name="get_IsEmpty" />
<Member Name="Slice(System.Int32)" />
<Member Name="Slice(System.Int32,System.Int32)" />
<Member Name="Equals(System.Span<T>)" />
+ <Member Name="Equals(System.Object)" />
+ <Member Name="GetHashCode" />
+ <Member Name="CopyTo(System.Span<T>)" />
<Member Name="TryCopyTo(System.Span<T>)" />
- <Member Name="Set(System.ReadOnlySpan<T>)" />
</Type>
<Type Name="System.ReadOnlySpan<T>" Condition="FEATURE_SPAN_OF_T">
<Member Name="#ctor(T[])" />
<InteropSources Include="$(BclSourcesRoot)\System\Runtime\InteropServices\IRegistrationServices.cs" />
<InteropSources Include="$(BclSourcesRoot)\System\Runtime\InteropServices\ITypeLibConverter.cs" />
<InteropSources Include="$(BclSourcesRoot)\System\Runtime\InteropServices\RegistrationServices.cs" />
- <InteropSources Include="$(BclSourcesRoot)\System\Runtime\InteropServices\TypeLibConverter.cs" />
<InteropSources Include="$(BclSourcesRoot)\System\Runtime\InteropServices\UCOMIBindCtx.cs" />
<InteropSources Include="$(BclSourcesRoot)\System\Runtime\InteropServices\UCOMIConnectionPointContainer.cs" />
<InteropSources Include="$(BclSourcesRoot)\System\Runtime\InteropServices\UCOMIConnectionPoint.cs" />
<ItemGroup Condition="'$(TargetsUnix)' == 'true'">
<SafehandleSources Include="$(CoreFxSourcesRoot)\Microsoft\Win32\SafeHandles\SafeFileHandle.Unix.cs" />
<FileStreamSources Include="$(CoreFxSourcesRoot)\System\IO\FileStream.Unix.cs" />
- <SystemSources Include="$(BclSourcesRoot)\System\Environment.Unix.cs" />
</ItemGroup>
<ItemGroup Condition="'$(TargetsUnix)' != 'true'">
<SafehandleSources Include="$(CoreFxSourcesRoot)\Microsoft\Win32\SafeHandles\SafeFileHandle.Windows.cs" />
<FileStreamSources Include="$(CoreFxSourcesRoot)\System\IO\FileStream.Win32.cs" />
<FileStreamSources Include="$(CoreFxSourcesRoot)\System\IO\FileStreamCompletionSource.Win32.cs" />
<FileStreamSources Include="$(CoreFxSourcesRoot)\System\IO\Win32Marshal.cs" />
- <SystemSources Include="$(BclSourcesRoot)\System\Environment.Win32.cs" />
</ItemGroup>
<ItemGroup>
<IoSources Include="$(CoreFxSourcesRoot)\System\IO\Path.cs" />
// See the LICENSE file in the project root for more information.
using System;
+using System.Diagnostics;
using System.Diagnostics.Contracts;
using System.Runtime.CompilerServices;
using System.Runtime.ConstrainedExecution;
private Thread AsThread()
{
- Contract.Assert(this is Thread);
+ Debug.Assert(this is Thread);
return (Thread)this;
}
=========================================================================*/
public extern bool IsAlive
{
- [SecuritySafeCritical] // auto-generated
[MethodImpl(MethodImplOptions.InternalCall)]
get;
}
=========================================================================*/
public bool IsBackground
{
- [SecuritySafeCritical] // auto-generated
get { return IsBackgroundNative(); }
- [SecuritySafeCritical] // auto-generated
- [HostProtection(SelfAffectingThreading = true)]
set { SetBackgroundNative(value); }
}
- [SecurityCritical] // auto-generated
[MethodImpl(MethodImplOptions.InternalCall)]
private extern bool IsBackgroundNative();
- [SecurityCritical] // auto-generated
[MethodImpl(MethodImplOptions.InternalCall)]
private extern void SetBackgroundNative(bool isBackground);
=========================================================================*/
public extern bool IsThreadPoolThread
{
- [SecuritySafeCritical] // auto-generated
[MethodImpl(MethodImplOptions.InternalCall)]
get;
}
=========================================================================*/
public ThreadPriority Priority
{
- [SecuritySafeCritical] // auto-generated
get { return (ThreadPriority)GetPriorityNative(); }
- [SecuritySafeCritical] // auto-generated
- [HostProtection(SelfAffectingThreading = true)]
set { SetPriorityNative((int)value); }
}
- [SecurityCritical] // auto-generated
[MethodImpl(MethodImplOptions.InternalCall)]
private extern int GetPriorityNative();
- [SecurityCritical] // auto-generated
[MethodImpl(MethodImplOptions.InternalCall)]
private extern void SetPriorityNative(int priority);
=========================================================================*/
public ThreadState ThreadState
{
- [SecuritySafeCritical] // auto-generated
get { return (ThreadState)GetThreadStateNative(); }
}
- [SecurityCritical] // auto-generated
[MethodImpl(MethodImplOptions.InternalCall)]
private extern int GetThreadStateNative();
- [SecuritySafeCritical] // auto-generated
public ApartmentState GetApartmentState()
{
#if FEATURE_COMINTEROP_APARTMENT_SUPPORT
return (ApartmentState)GetApartmentStateNative();
#else // !FEATURE_COMINTEROP_APARTMENT_SUPPORT
- Contract.Assert(false); // the Thread class in CoreFX should have handled this case
+ Debug.Assert(false); // the Thread class in CoreFX should have handled this case
return ApartmentState.MTA;
#endif // FEATURE_COMINTEROP_APARTMENT_SUPPORT
}
** An unstarted thread can be marked to indicate that it will host a
** single-threaded or multi-threaded apartment.
=========================================================================*/
- [SecuritySafeCritical] // auto-generated
- [HostProtection(Synchronization = true, SelfAffectingThreading = true)]
public bool TrySetApartmentState(ApartmentState state)
{
#if FEATURE_COMINTEROP_APARTMENT_SUPPORT
return SetApartmentStateHelper(state, false);
#else // !FEATURE_COMINTEROP_APARTMENT_SUPPORT
- Contract.Assert(false); // the Thread class in CoreFX should have handled this case
+ Debug.Assert(false); // the Thread class in CoreFX should have handled this case
return false;
#endif // FEATURE_COMINTEROP_APARTMENT_SUPPORT
}
#if FEATURE_COMINTEROP_APARTMENT_SUPPORT
- [SecurityCritical] // auto-generated
internal bool SetApartmentStateHelper(ApartmentState state, bool fireMDAOnMismatch)
{
ApartmentState retState = (ApartmentState)SetApartmentStateNative((int)state, fireMDAOnMismatch);
return true;
}
- [SecurityCritical] // auto-generated
[MethodImpl(MethodImplOptions.InternalCall)]
internal extern int GetApartmentStateNative();
- [SecurityCritical] // auto-generated
[MethodImpl(MethodImplOptions.InternalCall)]
internal extern int SetApartmentStateNative(int state, bool fireMDAOnMismatch);
#endif // FEATURE_COMINTEROP_APARTMENT_SUPPORT
#if FEATURE_COMINTEROP
- [SecurityCritical] // auto-generated
[ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)]
[MethodImpl(MethodImplOptions.InternalCall)]
public extern void DisableComObjectEagerCleanup();
#else // !FEATURE_COMINTEROP
- [SecurityCritical] // auto-generated
[ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)]
public void DisableComObjectEagerCleanup()
{
- Contract.Assert(false); // the Thread class in CoreFX should have handled this case
+ Debug.Assert(false); // the Thread class in CoreFX should have handled this case
}
#endif // FEATURE_COMINTEROP
** thread is not currently blocked in that manner, it will be interrupted
** when it next begins to block.
=========================================================================*/
-#if FEATURE_CORECLR
- [SecurityCritical] // auto-generated
-#else
- [SecuritySafeCritical] // auto-generated
-#endif
#pragma warning disable 618 // obsolete types: SecurityPermissionAttribute, SecurityAction
- [SecurityPermission(SecurityAction.Demand, ControlThread = true)]
#pragma warning restore 618 // obsolete types: SecurityPermissionAttribute, SecurityAction
public void Interrupt() => InterruptInternal();
// Internal helper (since we can't place security demands on
// ecalls/fcalls).
- [SecurityCritical] // auto-generated
[MethodImpl(MethodImplOptions.InternalCall)]
private extern void InterruptInternal();
** ThreadInterruptedException if the thread is interrupted while waiting.
** ThreadStateException if the thread has not been started yet.
=========================================================================*/
- [SecuritySafeCritical]
- [HostProtection(Synchronization = true, ExternalThreading = true)]
public void Join() => JoinInternal(Timeout.Infinite);
- [SecuritySafeCritical]
- [HostProtection(Synchronization = true, ExternalThreading = true)]
public bool Join(int millisecondsTimeout) => JoinInternal(millisecondsTimeout);
- [SecurityCritical]
[MethodImpl(MethodImplOptions.InternalCall)]
private extern bool JoinInternal(int millisecondsTimeout);
* Variant and the types that CLR supports explicitly in the
* CLR Variant class.
*/
- [System.Security.SecurityCritical] // auto-generated
internal static Variant ChangeType(Variant source, Type targetClass, short options, CultureInfo culture)
{
if (targetClass == null)
#region Private FCalls
- [System.Security.SecurityCritical] // auto-generated
[MethodImplAttribute(MethodImplOptions.InternalCall)]
private static extern void ChangeTypeEx(ref Variant result, ref Variant source, int lcid, IntPtr typeHandle, int cvType, short flags);
//This class contains only static members and does not need to be serializable.
[ComVisible(true)]
public static class Registry {
- [System.Security.SecuritySafeCritical] // auto-generated
static Registry()
{
}
* This is where current configuration information is stored.
*/
public static readonly RegistryKey CurrentConfig = RegistryKey.GetBaseKey(RegistryKey.HKEY_CURRENT_CONFIG);
-
-#if !FEATURE_CORECLR
- /**
- * Dynamic Data Root Key.
- *
- * LEGACY: This is where dynamic performance data is stored on Win9X.
- * This does not exist on NT.
- */
- [Obsolete("The DynData registry key only works on Win9x, which is no longer supported by the CLR. On NT-based operating systems, use the PerformanceData registry key instead.")]
- public static readonly RegistryKey DynData = RegistryKey.GetBaseKey(RegistryKey.HKEY_DYN_DATA);
-#endif
//
// Following function will parse a keyName and returns the basekey for it.
// If the keyName is not valid, we will throw ArgumentException.
// The return value shouldn't be null.
//
- [System.Security.SecurityCritical] // auto-generated
private static RegistryKey GetBaseKeyFromKeyName(string keyName, out string subKeyName) {
if( keyName == null) {
throw new ArgumentNullException(nameof(keyName));
case "HKEY_CURRENT_CONFIG":
basekey = Registry.CurrentConfig;
break;
-#if !FEATURE_CORECLR
- case "HKEY_DYN_DATA":
- basekey = RegistryKey.GetBaseKey(RegistryKey.HKEY_DYN_DATA);
- break;
-#endif
default:
throw new ArgumentException(Environment.GetResourceString("Arg_RegInvalidKeyName", nameof(keyName)));
}
return basekey;
}
- [System.Security.SecuritySafeCritical] // auto-generated
public static object GetValue(string keyName, string valueName, object defaultValue ) {
string subKeyName;
RegistryKey basekey = GetBaseKeyFromKeyName(keyName, out subKeyName);
SetValue(keyName, valueName, value, RegistryValueKind.Unknown);
}
- [System.Security.SecuritySafeCritical] // auto-generated
public static void SetValue(string keyName, string valueName, object value, RegistryValueKind valueKind ) {
string subKeyName;
RegistryKey basekey = GetBaseKeyFromKeyName(keyName, out subKeyName);
*/
-namespace Microsoft.Win32 {
-
+namespace Microsoft.Win32
+{
using System;
using System.Collections;
using System.Collections.Generic;
using System.Security;
-#if FEATURE_MACL
- using System.Security.AccessControl;
-#endif
using System.Security.Permissions;
using System.Text;
using System.Threading;
* Registry hive values. Useful only for GetRemoteBaseKey
*/
[Serializable]
-[System.Runtime.InteropServices.ComVisible(true)]
+ [System.Runtime.InteropServices.ComVisible(true)]
public enum RegistryHive
{
ClassesRoot = unchecked((int)0x80000000),
Users = unchecked((int)0x80000003),
PerformanceData = unchecked((int)0x80000004),
CurrentConfig = unchecked((int)0x80000005),
-#if !FEATURE_CORECLR
- DynData = unchecked((int)0x80000006),
-#endif
}
/**
internal static readonly IntPtr HKEY_USERS = new IntPtr(unchecked((int)0x80000003));
internal static readonly IntPtr HKEY_PERFORMANCE_DATA = new IntPtr(unchecked((int)0x80000004));
internal static readonly IntPtr HKEY_CURRENT_CONFIG = new IntPtr(unchecked((int)0x80000005));
-#if !FEATURE_CORECLR
- internal static readonly IntPtr HKEY_DYN_DATA = new IntPtr(unchecked((int)0x80000006));
-#endif
// Dirty indicates that we have munged data that should be potentially
// written to disk.
"HKEY_USERS",
"HKEY_PERFORMANCE_DATA",
"HKEY_CURRENT_CONFIG",
-#if !FEATURE_CORECLR
- "HKEY_DYN_DATA"
-#endif
};
// MSDN defines the following limits for registry key names & values:
private const int MaxKeyLength = 255;
private const int MaxValueLength = 16383;
- [System.Security.SecurityCritical] // auto-generated
private volatile SafeRegistryHandle hkey = null;
private volatile int state = 0;
private volatile String keyName;
* This key is bound to hkey, if writable is <b>false</b> then no write operations
* will be allowed.
*/
- [System.Security.SecurityCritical] // auto-generated
private RegistryKey(SafeRegistryHandle hkey, bool writable, RegistryView view)
: this(hkey, writable, false, false, false, view) {
}
* The remoteKey flag when set to true indicates that we are dealing with registry entries
* on a remote machine and requires the program making these calls to have full trust.
*/
- [System.Security.SecurityCritical] // auto-generated
private RegistryKey(SafeRegistryHandle hkey, bool writable, bool systemkey, bool remoteKey, bool isPerfData, RegistryView view) {
this.hkey = hkey;
this.keyName = "";
Dispose(true);
}
- [System.Security.SecuritySafeCritical] // auto-generated
private void Dispose(bool disposing) {
if (hkey != null) {
}
}
- [System.Security.SecuritySafeCritical] // auto-generated
public void Flush() {
if (hkey != null) {
if (IsDirty()) {
}
}
-#if FEATURE_CORECLR
void IDisposable.Dispose()
-#else
- public void Dispose()
-#endif
{
Dispose(true);
}
return CreateSubKeyInternal(subkey, writable ? RegistryKeyPermissionCheck.ReadWriteSubTree : RegistryKeyPermissionCheck.ReadSubTree, null, options);
}
-
-#if FEATURE_MACL
- [ComVisible(false)]
- public unsafe RegistryKey CreateSubKey(String subkey, RegistryKeyPermissionCheck permissionCheck, RegistrySecurity registrySecurity)
- {
- return CreateSubKeyInternal(subkey, permissionCheck, registrySecurity, RegistryOptions.None);
- }
-
- [ComVisible(false)]
- public unsafe RegistryKey CreateSubKey(String subkey, RegistryKeyPermissionCheck permissionCheck, RegistryOptions registryOptions, RegistrySecurity registrySecurity)
- {
- return CreateSubKeyInternal(subkey, permissionCheck, registrySecurity, registryOptions);
- }
-#endif
-
- [System.Security.SecuritySafeCritical] // auto-generated
[ComVisible(false)]
private unsafe RegistryKey CreateSubKeyInternal(String subkey, RegistryKeyPermissionCheck permissionCheck, object registrySecurityObj, RegistryOptions registryOptions)
{
}
CheckPermission(RegistryInternalCheck.CheckSubKeyCreatePermission, subkey, false, RegistryKeyPermissionCheck.Default);
-
+
Win32Native.SECURITY_ATTRIBUTES secAttrs = null;
-#if FEATURE_MACL
- RegistrySecurity registrySecurity = (RegistrySecurity)registrySecurityObj;
- // For ACL's, get the security descriptor from the RegistrySecurity.
- if (registrySecurity != null) {
- secAttrs = new Win32Native.SECURITY_ATTRIBUTES();
- secAttrs.nLength = (int)Marshal.SizeOf(secAttrs);
-
- byte[] sd = registrySecurity.GetSecurityDescriptorBinaryForm();
- // We allocate memory on the stack to improve the speed.
- // So this part of code can't be refactored into a method.
- byte* pSecDescriptor = stackalloc byte[sd.Length];
- Buffer.Memcpy(pSecDescriptor, 0, sd, 0, sd.Length);
- secAttrs.pSecurityDescriptor = pSecDescriptor;
- }
-#endif
+
int disposition = 0;
// By default, the new key will be writable.
DeleteSubKey(subkey, true);
}
- [System.Security.SecuritySafeCritical] // auto-generated
public void DeleteSubKey(String subkey, bool throwOnMissingSubKey) {
ValidateKeyName(subkey);
EnsureWriteable();
DeleteSubKeyTree(subkey, true /*throwOnMissingSubKey*/);
}
- [System.Security.SecuritySafeCritical] // auto-generated
[ComVisible(false)]
public void DeleteSubKeyTree(String subkey, Boolean throwOnMissingSubKey) {
ValidateKeyName(subkey);
// An internal version which does no security checks or argument checking. Skipping the
// security checks should give us a slight perf gain on large trees.
- [System.Security.SecurityCritical] // auto-generated
private void DeleteSubKeyTreeInternal(string subkey) {
RegistryKey key = InternalOpenSubKey(subkey, true);
if (key != null) {
if (ret!=0) Win32Error(ret, null);
}
else {
- ThrowHelper.ThrowArgumentException(ExceptionResource.Arg_RegSubKeyAbsent);
+ ThrowHelper.ThrowArgumentException(ExceptionResource.Arg_RegSubKeyAbsent);
}
}
DeleteValue(name, true);
}
- [System.Security.SecuritySafeCritical] // auto-generated
public void DeleteValue(String name, bool throwOnMissingValue) {
EnsureWriteable();
CheckPermission(RegistryInternalCheck.CheckValueWritePermission, name, false, RegistryKeyPermissionCheck.Default);
*
* @return the RegistryKey requested.
*/
- [System.Security.SecurityCritical] // auto-generated
internal static RegistryKey GetBaseKey(IntPtr hKey) {
return GetBaseKey(hKey, RegistryView.Default);
}
- [System.Security.SecurityCritical] // auto-generated
internal static RegistryKey GetBaseKey(IntPtr hKey, RegistryView view) {
int index = ((int)hKey) & 0x0FFFFFFF;
}
- [System.Security.SecuritySafeCritical] // auto-generated
[ComVisible(false)]
public static RegistryKey OpenBaseKey(RegistryHive hKey, RegistryView view) {
ValidateKeyView(view);
return OpenRemoteBaseKey(hKey, machineName, RegistryView.Default);
}
- [System.Security.SecuritySafeCritical] // auto-generated
[ComVisible(false)]
public static RegistryKey OpenRemoteBaseKey(RegistryHive hKey, String machineName, RegistryView view) {
if (machineName==null)
*
* @return the Subkey requested, or <b>null</b> if the operation failed.
*/
- #if FEATURE_CORECLR
- [System.Security.SecurityCritical] // auto-generated
- #else
- [System.Security.SecuritySafeCritical]
- #endif
public RegistryKey OpenSubKey(string name, bool writable ) {
ValidateKeyName(name);
EnsureNotDisposed();
return null;
}
-#if FEATURE_MACL
-
- [System.Security.SecuritySafeCritical] // auto-generated
- [ComVisible(false)]
- public RegistryKey OpenSubKey(String name, RegistryKeyPermissionCheck permissionCheck) {
- ValidateKeyMode(permissionCheck);
- return InternalOpenSubKey(name, permissionCheck, GetRegistryKeyAccess(permissionCheck));
- }
-
- [System.Security.SecuritySafeCritical]
- [ComVisible(false)]
- public RegistryKey OpenSubKey(String name, RegistryRights rights)
- {
- return InternalOpenSubKey(name, this.checkMode, (int)rights);
- }
-
- [System.Security.SecuritySafeCritical] // auto-generated
- [ComVisible(false)]
- public RegistryKey OpenSubKey(String name, RegistryKeyPermissionCheck permissionCheck, RegistryRights rights) {
- return InternalOpenSubKey(name, permissionCheck, (int)rights);
- }
-
- [System.Security.SecurityCritical] // auto-generated
- private RegistryKey InternalOpenSubKey(String name, RegistryKeyPermissionCheck permissionCheck, int rights) {
- ValidateKeyName(name);
- ValidateKeyMode(permissionCheck);
-
- ValidateKeyRights(rights);
-
- EnsureNotDisposed();
- name = FixupName(name); // Fixup multiple slashes to a single slash
-
- CheckPermission(RegistryInternalCheck.CheckOpenSubKeyPermission, name, false, permissionCheck);
- CheckPermission(RegistryInternalCheck.CheckSubTreePermission, name, false, permissionCheck);
- SafeRegistryHandle result = null;
- int ret = Win32Native.RegOpenKeyEx(hkey, name, 0, (rights | (int)regView), out result);
- if (ret == 0 && !result.IsInvalid) {
- RegistryKey key = new RegistryKey(result, (permissionCheck == RegistryKeyPermissionCheck.ReadWriteSubTree), false, remoteKey, false, regView);
- key.keyName = keyName + "\\" + name;
- key.checkMode = permissionCheck;
- return key;
- }
-
- // Return null if we didn't find the key.
- if (ret == Win32Native.ERROR_ACCESS_DENIED || ret == Win32Native.ERROR_BAD_IMPERSONATION_LEVEL) {
- // We need to throw SecurityException here for compatiblity reason,
- // although UnauthorizedAccessException will make more sense.
- ThrowHelper.ThrowSecurityException(ExceptionResource.Security_RegistryPermission);
- }
-
- return null;
- }
-#endif
-
// This required no security checks. This is to get around the Deleting SubKeys which only require
// write permission. They call OpenSubKey which required read. Now instead call this function w/o security checks
- [System.Security.SecurityCritical] // auto-generated
internal RegistryKey InternalOpenSubKey(String name, bool writable) {
ValidateKeyName(name);
EnsureNotDisposed();
*
* @return the Subkey requested, or <b>null</b> if the operation failed.
*/
-#if FEATURE_CORECLR
- [System.Security.SecurityCritical]
-#endif
public RegistryKey OpenSubKey(String name) {
return OpenSubKey(name, false);
}
* @return a count of subkeys.
*/
public int SubKeyCount {
- [System.Security.SecuritySafeCritical] // auto-generated
get {
CheckPermission(RegistryInternalCheck.CheckKeyReadPermission, null, false, RegistryKeyPermissionCheck.Default);
return InternalSubKeyCount();
[ComVisible(false)]
public RegistryView View {
- [System.Security.SecuritySafeCritical]
get {
EnsureNotDisposed();
return regView;
}
}
-#if !FEATURE_CORECLR
- [ComVisible(false)]
- public SafeRegistryHandle Handle {
- [System.Security.SecurityCritical]
- [SecurityPermissionAttribute(SecurityAction.Demand, Flags = SecurityPermissionFlag.UnmanagedCode)]
- get {
- EnsureNotDisposed();
- int ret = Win32Native.ERROR_INVALID_HANDLE;
- if (IsSystemKey()) {
- IntPtr baseKey = (IntPtr)0;
- switch (keyName) {
- case "HKEY_CLASSES_ROOT":
- baseKey = HKEY_CLASSES_ROOT;
- break;
- case "HKEY_CURRENT_USER":
- baseKey = HKEY_CURRENT_USER;
- break;
- case "HKEY_LOCAL_MACHINE":
- baseKey = HKEY_LOCAL_MACHINE;
- break;
- case "HKEY_USERS":
- baseKey = HKEY_USERS;
- break;
- case "HKEY_PERFORMANCE_DATA":
- baseKey = HKEY_PERFORMANCE_DATA;
- break;
- case "HKEY_CURRENT_CONFIG":
- baseKey = HKEY_CURRENT_CONFIG;
- break;
- case "HKEY_DYN_DATA":
- baseKey = HKEY_DYN_DATA;
- break;
- default:
- Win32Error(ret, null);
- break;
- }
- // open the base key so that RegistryKey.Handle will return a valid handle
- SafeRegistryHandle result;
- ret = Win32Native.RegOpenKeyEx(baseKey,
- null,
- 0,
- GetRegistryKeyAccess(IsWritable()) | (int)regView,
- out result);
-
- if (ret == 0 && !result.IsInvalid) {
- return result;
- }
- else {
- Win32Error(ret, null);
- }
- }
- else {
- return hkey;
- }
- throw new IOException(Win32Native.GetMessage(ret), ret);
- }
- }
-
- [System.Security.SecurityCritical]
- [ComVisible(false)]
- [SecurityPermissionAttribute(SecurityAction.Demand, Flags = SecurityPermissionFlag.UnmanagedCode)]
- public static RegistryKey FromHandle(SafeRegistryHandle handle) {
- return FromHandle(handle, RegistryView.Default);
- }
-
- [System.Security.SecurityCritical]
- [ComVisible(false)]
- [SecurityPermissionAttribute(SecurityAction.Demand, Flags = SecurityPermissionFlag.UnmanagedCode)]
- public static RegistryKey FromHandle(SafeRegistryHandle handle, RegistryView view) {
- if (handle == null) throw new ArgumentNullException(nameof(handle));
- ValidateKeyView(view);
-
- return new RegistryKey(handle, true /* isWritable */, view);
- }
-#endif
-
- [System.Security.SecurityCritical] // auto-generated
internal int InternalSubKeyCount() {
EnsureNotDisposed();
*
* @return all subkey names.
*/
- #if FEATURE_CORECLR
- [System.Security.SecurityCritical] // auto-generated
- #else
- [System.Security.SecuritySafeCritical]
- #endif
public String[] GetSubKeyNames() {
CheckPermission(RegistryInternalCheck.CheckKeyReadPermission, null, false, RegistryKeyPermissionCheck.Default);
return InternalGetSubKeyNames();
}
- [System.Security.SecurityCritical] // auto-generated
internal unsafe String[] InternalGetSubKeyNames() {
EnsureNotDisposed();
int subkeys = InternalSubKeyCount();
* @return a count of values.
*/
public int ValueCount {
- [System.Security.SecuritySafeCritical] // auto-generated
get {
CheckPermission(RegistryInternalCheck.CheckKeyReadPermission, null, false, RegistryKeyPermissionCheck.Default);
return InternalValueCount();
}
}
- [System.Security.SecurityCritical] // auto-generated
internal int InternalValueCount() {
EnsureNotDisposed();
int values = 0;
*
* @return all value names.
*/
- [System.Security.SecuritySafeCritical] // auto-generated
public unsafe String[] GetValueNames() {
CheckPermission(RegistryInternalCheck.CheckKeyReadPermission, null, false, RegistryKeyPermissionCheck.Default);
EnsureNotDisposed();
*
* @return the data associated with the value.
*/
- [System.Security.SecuritySafeCritical] // auto-generated
public Object GetValue(String name) {
CheckPermission(RegistryInternalCheck.CheckValueReadPermission, name, false, RegistryKeyPermissionCheck.Default);
return InternalGetValue(name, null, false, true);
*
* @return the data associated with the value.
*/
- #if FEATURE_CORECLR
- [System.Security.SecurityCritical] // auto-generated
- #else
- [System.Security.SecuritySafeCritical]
- #endif
public Object GetValue(String name, Object defaultValue) {
CheckPermission(RegistryInternalCheck.CheckValueReadPermission, name, false, RegistryKeyPermissionCheck.Default);
return InternalGetValue(name, defaultValue, false, true);
}
- #if FEATURE_CORECLR
- [System.Security.SecurityCritical] // auto-generated
- #else
- [System.Security.SecuritySafeCritical]
- #endif
[ComVisible(false)]
public Object GetValue(String name, Object defaultValue, RegistryValueOptions options) {
if( options < RegistryValueOptions.None || options > RegistryValueOptions.DoNotExpandEnvironmentNames) {
return InternalGetValue(name, defaultValue, doNotExpand, true);
}
- [System.Security.SecurityCritical] // auto-generated
internal Object InternalGetValue(String name, Object defaultValue, bool doNotExpand, bool checkSecurity) {
if (checkSecurity) {
// Name can be null! It's the most common use of RegQueryValueEx
}
- [System.Security.SecuritySafeCritical] // auto-generated
[ComVisible(false)]
public RegistryValueKind GetValueKind(string name) {
CheckPermission(RegistryInternalCheck.CheckValueReadPermission, name, false, RegistryKeyPermissionCheck.Default);
}
public String Name {
- [System.Security.SecuritySafeCritical] // auto-generated
get {
EnsureNotDisposed();
return keyName;
SetValue(name, value, RegistryValueKind.Unknown);
}
- [System.Security.SecuritySafeCritical] //auto-generated
[ComVisible(false)]
public unsafe void SetValue(String name, Object value, RegistryValueKind valueKind) {
if (value==null)
*
* @return a string representing the key.
*/
- [System.Security.SecuritySafeCritical] // auto-generated
public override String ToString() {
EnsureNotDisposed();
return keyName;
}
-#if FEATURE_MACL
- public RegistrySecurity GetAccessControl() {
- return GetAccessControl(AccessControlSections.Access | AccessControlSections.Owner | AccessControlSections.Group);
- }
-
- [System.Security.SecuritySafeCritical] // auto-generated
- public RegistrySecurity GetAccessControl(AccessControlSections includeSections) {
- EnsureNotDisposed();
- return new RegistrySecurity(hkey, keyName, includeSections);
- }
-
- [System.Security.SecuritySafeCritical] // auto-generated
- public void SetAccessControl(RegistrySecurity registrySecurity) {
- EnsureWriteable();
- if (registrySecurity == null)
- throw new ArgumentNullException(nameof(registrySecurity));
-
- registrySecurity.Persist(hkey, keyName);
- }
-#endif
-
/**
* After calling GetLastWin32Error(), it clears the last error field,
* so you must save the HResult and pass it to this method. This method
* error, and depending on the error, insert a string into the message
* gotten from the ResourceManager.
*/
- [System.Security.SecuritySafeCritical] // auto-generated
internal void Win32Error(int errorCode, String str) {
switch (errorCode) {
case Win32Native.ERROR_ACCESS_DENIED:
}
}
- [SecuritySafeCritical]
internal static void Win32ErrorStatic(int errorCode, String str) {
switch (errorCode) {
case Win32Native.ERROR_ACCESS_DENIED:
path = keyName + "\\.";
}
- [System.Security.SecurityCritical] // auto-generated
- private void CheckPermission(RegistryInternalCheck check, string item, bool subKeyWritable, RegistryKeyPermissionCheck subKeyCheck) {
+ private void CheckPermission(RegistryInternalCheck check, string item, bool subKeyWritable, RegistryKeyPermissionCheck subKeyCheck)
+ {
bool demand = false;
RegistryPermissionAccess access = RegistryPermissionAccess.NoAccess;
string path = null;
-#if !FEATURE_CORECLR
- if (CodeAccessSecurityEngine.QuickCheckForAllDemands()) {
- return; // full trust fast path
- }
-#endif // !FEATURE_CORECLR
-
switch (check) {
//
// Read/Write/Create SubKey Permission
}
}
- [System.Security.SecurityCritical] // auto-generated
static private void CheckUnmanagedCodePermission() {
#pragma warning disable 618
new SecurityPermission(SecurityPermissionFlag.UnmanagedCode).Demand();
#pragma warning restore 618
}
- [System.Security.SecurityCritical] // auto-generated
private bool ContainsRegistryValue(string name) {
int type = 0;
int datasize = 0;
return retval == 0;
}
- [System.Security.SecurityCritical] // auto-generated
private void EnsureNotDisposed(){
if (hkey == null) {
ThrowHelper.ThrowObjectDisposedException(keyName, ExceptionResource.ObjectDisposed_RegKeyClosed);
}
}
- [System.Security.SecurityCritical] // auto-generated
private void EnsureWriteable() {
EnsureNotDisposed();
if (!IsWritable()) {
}
}
-
-#if FEATURE_MACL
- static private void ValidateKeyRights(int rights) {
- if(0 != (rights & ~((int)RegistryRights.FullControl))) {
- // We need to throw SecurityException here for compatiblity reason,
- // although UnauthorizedAccessException will make more sense.
- ThrowHelper.ThrowSecurityException(ExceptionResource.Security_RegistryPermission);
- }
- }
-#endif
// Win32 constants for error handling
private const int FORMAT_MESSAGE_IGNORE_INSERTS = 0x00000200;
private const int FORMAT_MESSAGE_FROM_SYSTEM = 0x00001000;
namespace Microsoft.Win32.SafeHandles
{
- [System.Security.SecurityCritical] // auto-generated
internal sealed class SafeFileMappingHandle : SafeHandleZeroOrMinusOneIsInvalid
{
- [System.Security.SecurityCritical] // auto-generated_required
internal SafeFileMappingHandle() : base(true) {}
// 0 is an Invalid Handle
- [System.Security.SecurityCritical] // auto-generated_required
internal SafeFileMappingHandle(IntPtr handle, bool ownsHandle) : base (ownsHandle)
{
SetHandle(handle);
}
- [System.Security.SecurityCritical]
override protected bool ReleaseHandle()
{
return Win32Native.CloseHandle(handle);
using Microsoft.Win32;
namespace Microsoft.Win32.SafeHandles {
- [System.Security.SecurityCritical] // auto-generated
internal sealed class SafeFindHandle : SafeHandleZeroOrMinusOneIsInvalid
{
- [System.Security.SecurityCritical] // auto-generated_required
internal SafeFindHandle() : base(true) {}
- [System.Security.SecurityCritical]
override protected bool ReleaseHandle()
{
return Win32Native.FindClose(handle);
// See the LICENSE file in the project root for more information.
namespace Microsoft.Win32 {
- using Microsoft.Win32;
using Microsoft.Win32.SafeHandles;
- using System;
- using System.Runtime.CompilerServices;
- using System.Runtime.ConstrainedExecution;
- using System.Runtime.InteropServices;
- using System.Runtime.Serialization;
- using System.Runtime.Versioning;
- using System.Security;
using System.Security.Permissions;
- using System.Text;
- [System.Security.SecurityCritical] // auto-generated
- [HostProtectionAttribute(MayLeakOnAbort = true)]
sealed internal class SafeLibraryHandle : SafeHandleZeroOrMinusOneIsInvalid {
internal SafeLibraryHandle() : base(true) {}
- [System.Security.SecurityCritical]
override protected bool ReleaseHandle()
{
return UnsafeNativeMethods.FreeLibrary(handle);
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
-namespace Microsoft.Win32.SafeHandles {
+
+namespace Microsoft.Win32.SafeHandles
+{
using System;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Runtime.ConstrainedExecution;
- [System.Security.SecurityCritical] // auto-generated
internal sealed class SafeLocalAllocHandle : SafeBuffer {
private SafeLocalAllocHandle () : base(true) {}
get { return new SafeLocalAllocHandle(IntPtr.Zero); }
}
- [System.Security.SecurityCritical]
override protected bool ReleaseHandle()
{
return Win32Native.LocalFree(handle) == IntPtr.Zero;
using System.Runtime.ConstrainedExecution;
using System.Runtime.Versioning;
- [System.Security.SecurityCritical]
public sealed class SafeRegistryHandle : SafeHandleZeroOrMinusOneIsInvalid {
- [System.Security.SecurityCritical]
internal SafeRegistryHandle() : base(true) {}
- [System.Security.SecurityCritical]
public SafeRegistryHandle(IntPtr preexistingHandle, bool ownsHandle) : base(ownsHandle) {
SetHandle(preexistingHandle);
}
- [System.Security.SecurityCritical]
override protected bool ReleaseHandle() {
return (RegCloseKey(handle) == Win32Native.ERROR_SUCCESS);
}
namespace Microsoft.Win32.SafeHandles
{
- [System.Security.SecurityCritical] // auto-generated
internal sealed class SafeViewOfFileHandle : SafeHandleZeroOrMinusOneIsInvalid
{
- [System.Security.SecurityCritical] // auto-generated_required
internal SafeViewOfFileHandle() : base(true) {}
// 0 is an Invalid Handle
- [System.Security.SecurityCritical] // auto-generated_required
internal SafeViewOfFileHandle(IntPtr handle, bool ownsHandle) : base (ownsHandle) {
SetHandle(handle);
}
- [System.Security.SecurityCritical]
override protected bool ReleaseHandle()
{
if (Win32Native.UnmapViewOfFile(handle))
namespace Microsoft.Win32.SafeHandles {
- [System.Security.SecurityCritical] // auto-generated_required
public sealed class SafeWaitHandle : SafeHandleZeroOrMinusOneIsInvalid
{
// Called by P/Invoke marshaler
SetHandle(existingHandle);
}
- [System.Security.SecurityCritical]
override protected bool ReleaseHandle()
{
return Win32Native.CloseHandle(handle);
using System.Runtime.ConstrainedExecution;
// Class of safe handle which uses 0 or -1 as an invalid handle.
- [System.Security.SecurityCritical] // auto-generated_required
-#if !FEATURE_CORECLR
- [SecurityPermission(SecurityAction.InheritanceDemand, UnmanagedCode=true)]
-#endif
public abstract class SafeHandleZeroOrMinusOneIsInvalid : SafeHandle
{
[ReliabilityContract(Consistency.WillNotCorruptState, Cer.MayFail)]
{
}
-#if FEATURE_CORECLR
// A default constructor is needed to satisfy CoreCLR inheritence rules. It should not be called at runtime
protected SafeHandleZeroOrMinusOneIsInvalid()
{
throw new NotImplementedException();
}
-#endif // FEATURE_CORECLR
public override bool IsInvalid {
- [System.Security.SecurityCritical]
get { return handle.IsNull() || handle == new IntPtr(-1); }
}
}
// Class of safe handle which uses only -1 as an invalid handle.
- [System.Security.SecurityCritical] // auto-generated_required
-#if !FEATURE_CORECLR
- [SecurityPermission(SecurityAction.InheritanceDemand, UnmanagedCode=true)]
-#endif
public abstract class SafeHandleMinusOneIsInvalid : SafeHandle
{
[ReliabilityContract(Consistency.WillNotCorruptState, Cer.MayFail)]
{
}
-#if FEATURE_CORECLR
// A default constructor is needed to satisfy CoreCLR inheritence rules. It should not be called at runtime
protected SafeHandleMinusOneIsInvalid()
{
throw new NotImplementedException();
}
-#endif // FEATURE_CORECLR
public override bool IsInvalid {
- [System.Security.SecurityCritical]
get { return handle == new IntPtr(-1); }
}
}
// Class of critical handle which uses 0 or -1 as an invalid handle.
- [System.Security.SecurityCritical] // auto-generated_required
-#if !FEATURE_CORECLR
- [SecurityPermission(SecurityAction.InheritanceDemand, UnmanagedCode=true)]
-#endif
public abstract class CriticalHandleZeroOrMinusOneIsInvalid : CriticalHandle
{
[ReliabilityContract(Consistency.WillNotCorruptState, Cer.MayFail)]
}
public override bool IsInvalid {
- [System.Security.SecurityCritical]
get { return handle.IsNull() || handle == new IntPtr(-1); }
}
}
// Class of critical handle which uses only -1 as an invalid handle.
- [System.Security.SecurityCritical] // auto-generated_required
-#if !FEATURE_CORECLR
- [SecurityPermission(SecurityAction.InheritanceDemand, UnmanagedCode=true)]
-#endif
public abstract class CriticalHandleMinusOneIsInvalid : CriticalHandle
{
[ReliabilityContract(Consistency.WillNotCorruptState, Cer.MayFail)]
}
public override bool IsInvalid {
- [System.Security.SecurityCritical]
get { return handle == new IntPtr(-1); }
}
}
using System.Text;
using System.Diagnostics.Tracing;
- [System.Security.SecurityCritical] // auto-generated
[SuppressUnmanagedCodeSecurityAttribute()]
internal static class UnsafeNativeMethods {
internal static extern bool FreeLibrary(IntPtr hModule);
- [SecurityCritical]
[SuppressUnmanagedCodeSecurityAttribute()]
internal static unsafe class ManifestEtw
{
//
// Callback
//
- [SecurityCritical]
internal unsafe delegate void EtwEnableCallback(
[In] ref Guid sourceId,
[In] int isEnabled,
//
// Registration APIs
//
- [SecurityCritical]
[DllImport(Win32Native.ADVAPI32, ExactSpelling = true, EntryPoint = "EventRegister", CharSet = System.Runtime.InteropServices.CharSet.Unicode)]
internal static extern unsafe uint EventRegister(
[In] ref Guid providerId,
);
//
- [SecurityCritical]
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Security", "CA2118:ReviewSuppressUnmanagedCodeSecurityUsage")]
[DllImport(Win32Native.ADVAPI32, ExactSpelling = true, EntryPoint = "EventUnregister", CharSet = System.Runtime.InteropServices.CharSet.Unicode)]
internal static extern uint EventUnregister([In] long registrationHandle);
// Writing (Publishing/Logging) APIs
//
//
- [SecurityCritical]
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Security", "CA2118:ReviewSuppressUnmanagedCodeSecurityUsage")]
[DllImport(Win32Native.ADVAPI32, ExactSpelling = true, EntryPoint = "EventWrite", CharSet = System.Runtime.InteropServices.CharSet.Unicode)]
internal static extern unsafe int EventWrite(
[In] EventProvider.EventData* userData
);
- [SecurityCritical]
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Security", "CA2118:ReviewSuppressUnmanagedCodeSecurityUsage")]
[DllImport(Win32Native.ADVAPI32, ExactSpelling = true, EntryPoint = "EventWriteString", CharSet = System.Runtime.InteropServices.CharSet.Unicode)]
internal static extern unsafe int EventWriteString(
}
#if FEATURE_COMINTEROP
- [SecurityCritical]
[DllImport("combase.dll", PreserveSig = true)]
internal static extern int RoGetActivationFactory(
[MarshalAs(UnmanagedType.HString)] string activatableClassId,
// Remove the default demands for all P/Invoke methods with this
// global declaration on the class.
- [System.Security.SecurityCritical]
[SuppressUnmanagedCodeSecurityAttribute()]
internal static class Win32Native {
internal int fileSizeHigh;
internal int fileSizeLow;
- [System.Security.SecurityCritical]
internal void PopulateFrom(WIN32_FIND_DATA findData) {
// Copy the information to data
fileAttributes = findData.dwFileAttributes;
/// strings created with this version of the constructor will be unsafe to use after the buffer
/// has been freed.
/// </remarks>
- [System.Security.SecurityCritical] // auto-generated
internal UNICODE_INTPTR_STRING (int stringBytes, SafeLocalAllocHandle buffer) {
BCLDebug.Assert(buffer == null || (stringBytes >= 0 && (ulong)stringBytes <= buffer.ByteLength),
"buffer == null || (stringBytes >= 0 && stringBytes <= buffer.ByteLength)");
[ReliabilityContract(Consistency.WillNotCorruptState, Cer.MayFail)]
private static extern IntPtr GetModuleHandle(String moduleName);
- [System.Security.SecurityCritical] // auto-generated
internal static bool DoesWin32MethodExist(String moduleName, String methodName)
{
// GetModuleHandle does not increment the module's ref count, so we don't need to call FreeLibrary.
[DllImport(KERNEL32, SetLastError = true, CharSet = CharSet.Unicode, ExactSpelling = true)]
internal static extern uint GetLongPathNameW(string lpszShortPath, SafeHandle lpszLongPath, uint cchBuffer);
-#if !FEATURE_CORECLR
- // Disallow access to all non-file devices from methods that take
- // a String. This disallows DOS devices like "con:", "com1:",
- // "lpt1:", etc. Use this to avoid security problems, like allowing
- // a web client asking a server for "http://server/com1.aspx" and
- // then causing a worker process to hang.
- [System.Security.SecurityCritical] // auto-generated
- internal static SafeFileHandle SafeCreateFile(String lpFileName,
- int dwDesiredAccess, System.IO.FileShare dwShareMode,
- SECURITY_ATTRIBUTES securityAttrs, System.IO.FileMode dwCreationDisposition,
- int dwFlagsAndAttributes, IntPtr hTemplateFile)
- {
- SafeFileHandle handle = CreateFile( lpFileName, dwDesiredAccess, dwShareMode,
- securityAttrs, dwCreationDisposition,
- dwFlagsAndAttributes, hTemplateFile );
-
- if (!handle.IsInvalid)
- {
- int fileType = Win32Native.GetFileType(handle);
- if (fileType != Win32Native.FILE_TYPE_DISK) {
- handle.Dispose();
- throw new NotSupportedException(Environment.GetResourceString("NotSupported_FileStreamOnNonFiles"));
- }
- }
-
- return handle;
- }
-
- [System.Security.SecurityCritical] // auto-generated
- internal static SafeFileHandle UnsafeCreateFile(String lpFileName,
- int dwDesiredAccess, System.IO.FileShare dwShareMode,
- SECURITY_ATTRIBUTES securityAttrs, System.IO.FileMode dwCreationDisposition,
- int dwFlagsAndAttributes, IntPtr hTemplateFile)
- {
- SafeFileHandle handle = CreateFile( lpFileName, dwDesiredAccess, dwShareMode,
- securityAttrs, dwCreationDisposition,
- dwFlagsAndAttributes, hTemplateFile );
-
- return handle;
- }
-
- // Do not use these directly, use the safe or unsafe versions above.
- // The safe version does not support devices (aka if will only open
- // files on disk), while the unsafe version give you the full semantic
- // of the native version.
- [DllImport(KERNEL32, SetLastError=true, CharSet=CharSet.Auto, BestFitMapping=false)]
- private static extern SafeFileHandle CreateFile(String lpFileName,
- int dwDesiredAccess, System.IO.FileShare dwShareMode,
- SECURITY_ATTRIBUTES securityAttrs, System.IO.FileMode dwCreationDisposition,
- int dwFlagsAndAttributes, IntPtr hTemplateFile);
-#endif
-
[DllImport(KERNEL32, SetLastError=true, CharSet=CharSet.Auto, BestFitMapping=false)]
internal static extern SafeFileMappingHandle CreateFileMapping(SafeFileHandle hFile, IntPtr lpAttributes, uint fProtect, uint dwMaximumSizeHigh, uint dwMaximumSizeLow, String lpName);
[DllImport(KERNEL32, SetLastError=true, EntryPoint="SetFilePointer")]
private unsafe static extern int SetFilePointerWin32(SafeFileHandle handle, int lo, int * hi, int origin);
- [System.Security.SecurityCritical] // auto-generated
internal unsafe static long SetFilePointer(SafeFileHandle handle, long offset, System.IO.SeekOrigin origin, out int hr) {
hr = 0;
int lo = (int) offset;
[In] uint dwFlags);
#endif // FEATURE_LEGACYSURFACE
-#if FEATURE_CORECLR
[DllImport(NTDLL, CharSet=CharSet.Unicode, SetLastError=true)]
internal static extern
int RtlNtStatusToDosError (
[In] int status);
-#else
- // identical to RtlNtStatusToDosError, but we are in ask mode for desktop CLR
- [DllImport(ADVAPI32, CharSet = CharSet.Unicode, SetLastError = true)]
- internal static extern
- int LsaNtStatusToWinError (
- [In] int status);
-#endif
+
// Get the current FIPS policy setting on Vista and above
[DllImport("bcrypt.dll")]
internal static extern uint BCryptGetFipsAlgorithmMode(
byte[] dacl,
byte[] sacl );
-#if FEATURE_CORECLR
[DllImport(KERNEL32, CharSet=CharSet.Unicode)]
[SuppressUnmanagedCodeSecurityAttribute()]
internal unsafe static extern int WideCharToMultiByte(
int cchMultiByte,
char* lpWideCharStr,
int cchWideChar);
-#endif // FEATURE_CORECLR
[DllImport(KERNEL32, SetLastError = true)]
[return: MarshalAs(UnmanagedType.Bool)]
internal extern static bool QueryUnbiasedInterruptTime(out ulong UnbiasedTime);
-#if FEATURE_CORECLR
#if FEATURE_PAL
[DllImport(KERNEL32, EntryPoint = "PAL_Random")]
internal extern static bool Random(bool bStrong,
}
}
#endif
-#endif
}
}
NoDebugResources = [{0}]\r\nArguments: {1}\r\nDebugging resource strings are unavailable. Often the key and arguments provide sufficient information to diagnose the problem. See http://go.microsoft.com/fwlink/?linkid=106663&Version={2}&File={3}&Key={4}
#endif // INCLUDE_RUNTIME
-#if !FEATURE_CORECLR
-UnknownError = Unknown error.
-#endif // !FEATURE_CORECLR
-
#if INCLUDE_DEBUG
; For code contracts
InvariantFailed_Cnd = Invariant failed: {0}
MustUseCCRewrite = An assembly (probably "{1}") must be rewritten using the code contracts binary rewriter (CCRewrite) because it is calling Contract.{0} and the CONTRACTS_FULL symbol is defined. Remove any explicit definitions of the CONTRACTS_FULL symbol from your project and rebuild. CCRewrite can be downloaded from http://go.microsoft.com/fwlink/?LinkID=169180. \r\nAfter the rewriter is installed, it can be enabled in Visual Studio from the project's Properties page on the Code Contracts pane. Ensure that "Perform Runtime Contract Checking" is enabled, which will define CONTRACTS_FULL.
-; Access Control
-#if FEATURE_MACL
-AccessControl_MustSpecifyContainerAcl = The named parameter must be a container ACL.
-AccessControl_MustSpecifyLeafObjectAcl = The named parameter must be a non-container ACL.
-AccessControl_AclTooLong = Length of the access control list exceed the allowed maximum.
-AccessControl_MustSpecifyDirectoryObjectAcl = The named parameter must be a directory-object ACL.
-AccessControl_MustSpecifyNonDirectoryObjectAcl = The named parameter must be a non-directory-object ACL.
-AccessControl_InvalidSecurityDescriptorRevision = Security descriptor with revision other than '1' are not legal.
-AccessControl_InvalidSecurityDescriptorSelfRelativeForm = Security descriptor must be in the self-relative form.
-AccessControl_NoAssociatedSecurity = Unable to perform a security operation on an object that has no associated security. This can happen when trying to get an ACL of an anonymous kernel object.
-AccessControl_InvalidHandle = The supplied handle is invalid. This can happen when trying to set an ACL on an anonymous kernel object.
-AccessControl_UnexpectedError = Method failed with unexpected error code {0}.
-AccessControl_InvalidSidInSDDLString = The SDDL string contains an invalid sid or a sid that cannot be translated.
-AccessControl_InvalidOwner = The security identifier is not allowed to be the owner of this object.
-AccessControl_InvalidGroup = The security identifier is not allowed to be the primary group of this object.
-AccessControl_InvalidAccessRuleType = The access rule is not the correct type.
-AccessControl_InvalidAuditRuleType = The audit rule is not the correct type.
-#endif // FEATURE_MACL
-
; Identity Reference Library
#if FEATURE_IDENTITY_REFERENCE
IdentityReference_IdentityNotMapped = Some or all identity references could not be translated.
Arg_TypedReference_Null = The TypedReference must be initialized.
Argument_AddingDuplicate__ = Item has already been added. Key in dictionary: '{0}' Key being added: '{1}'
Argument_AddingDuplicate = An item with the same key has already been added.
-#if FEATURE_CORECLR
Argument_AddingDuplicateWithKey = An item with the same key has already been added. Key: {0}
-#endif // FEATURE_CORECLR
Argument_MethodDeclaringTypeGenericLcg = Method '{0}' has a generic declaring type '{1}'. Explicitly provide the declaring type to GetTokenFor.
Argument_MethodDeclaringTypeGeneric = Cannot resolve method {0} because the declaring type of the method handle {1} is generic. Explicitly provide the declaring type to GetMethodFromHandle.
Argument_FieldDeclaringTypeGeneric = Cannot resolve field {0} because the declaring type of the field handle {1} is generic. Explicitly provide the declaring type to GetFieldFromHandle.
Argument_AlreadyBoundOrSyncHandle = 'handle' has already been bound to the thread pool, or was not opened for asynchronous I/O.
#if FEATURE_SPAN_OF_T
Argument_InvalidTypeWithPointersNotSupported = Cannot use type '{0}'. Only value types without pointers or references are supported.
+Argument_DestinationTooShort = Destination is too short.
#endif // FEATURE_SPAN_OF_T
;
InvalidOperation_EnumNotStarted = Enumeration has not started. Call MoveNext.
InvalidOperation_EnumOpCantHappen = Enumeration has either not started or has already finished.
InvalidOperation_ModifyRONumFmtInfo = Unable to modify a read-only NumberFormatInfo object.
-#if FEATURE_CAS_POLICY
-InvalidOperation_ModifyROPermSet = ReadOnlyPermissionSet objects may not be modified.
-#endif // FEATURE_CAS_POLICY
InvalidOperation_MustBeSameThread = This operation must take place on the same thread on which the object was created.
InvalidOperation_MustRevertPrivilege = Must revert the privilege prior to attempting this operation.
InvalidOperation_ReadOnly = Instance is read-only.
NotSupported_UserDllImport = DllImport cannot be used on user-defined methods.
NotSupported_UserCOM = COM Interop is not supported for user-defined types.
#endif //FEATURE_WINDOWSPHONE
-#if FEATURE_CAS_POLICY
-NotSupported_RequiresCasPolicyExplicit = This method explicitly uses CAS policy, which has been obsoleted by the .NET Framework. In order to enable CAS policy for compatibility reasons, please use the NetFx40_LegacySecurityPolicy configuration switch. Please see http://go.microsoft.com/fwlink/?LinkID=155570 for more information.
-NotSupported_RequiresCasPolicyImplicit = This method implicitly uses CAS policy, which has been obsoleted by the .NET Framework. In order to enable CAS policy for compatibility reasons, please use the NetFx40_LegacySecurityPolicy configuration switch. Please see http://go.microsoft.com/fwlink/?LinkID=155570 for more information.
-NotSupported_CasDeny = The Deny stack modifier has been obsoleted by the .NET Framework. Please see http://go.microsoft.com/fwlink/?LinkId=155571 for more information.
-NotSupported_SecurityContextSourceAppDomainInHeterogenous = SecurityContextSource.CurrentAppDomain is not supported in heterogenous AppDomains.
-#endif // FEATURE_CAS_POLICY
#if FEATURE_APPX
NotSupported_AppX = {0} is not supported in AppX.
LoadOfFxAssemblyNotSupported_AppX = {0} of .NET Framework assemblies is not supported in AppX.
#endif // FEATURE_COMINTEROP
; ReflectionTypeLoadException
ReflectionTypeLoad_LoadFailed = Unable to load one or more of the requested types. Retrieve the LoaderExceptions property for more information.
-#if !FEATURE_CORECLR
-NotSupported_NoTypeInfo = Cannot resolve {0} to a TypeInfo object.
-#endif
#if FEATURE_COMINTEROP
NotSupported_PIAInAppxProcess = A Primary Interop Assembly is not supported in AppX.
#endif
NotSupported_AssemblyLoadCodeBase = Assembly.Load with a Codebase is not supported.
NotSupported_AssemblyLoadFromHash = Assembly.LoadFrom with hashValue is not supported.
#endif
+#if FEATURE_SPAN_OF_T
+NotSupported_CannotCallEqualsOnSpan = Equals() on Span and ReadOnlySpan is not supported. Use operator== instead.
+NotSupported_CannotCallGetHashCodeOnSpan = GetHashCode() on Span and ReadOnlySpan is not supported.
+#endif // FEATURE_SPAN_OF_T
; TypeLoadException
TypeLoad_ResolveType = Could not resolve type '{0}'.
Remoting_NonPublicOrStaticCantBeCalledRemotely = Permission denied: cannot call non-public or static methods remotely.
Remoting_Proxy_ProxyTypeIsNotMBR = classToProxy argument must derive from MarshalByRef type.
Remoting_TP_NonNull = The transparent proxy field of a real proxy must be null.
-#if FEATURE_REMOTING
-Remoting_Activation_BadAttribute = Activation attribute does not implement the IContextAttribute interface.
-Remoting_Activation_BadObject = Proxy Attribute returned an incompatible object when constructing an instance of type {0}.
-Remoting_Activation_MBR_ProxyAttribute = Proxy Attributes are supported on ContextBound types only.
-Remoting_Activation_ConnectFailed = An attempt to connect to the remote activator failed with exception '{0}'.
-Remoting_Activation_Failed = Activation failed due to an unknown reason.
-Remoting_Activation_InconsistentState = Inconsistent state during activation; there may be two proxies for the same object.
-Remoting_Activation_MissingRemoteAppEntry = Cannot find an entry for remote application '{0}'.
-Remoting_Activation_NullReturnValue = Return value of construction call was null.
-Remoting_Activation_NullFromInternalUnmarshal = InternalUnmarshal of returned ObjRef from activation call returned null.
-Remoting_Activation_WellKnownCTOR = Cannot run a non-default constructor when connecting to well-known objects.
-Remoting_Activation_PermissionDenied = Type '{0}' is not registered for activation.
-Remoting_Activation_PropertyUnhappy = A context property did not approve the candidate context for activating the object.
-Remoting_Activation_AsyncUnsupported = Async Activation not supported.
-Remoting_AmbiguousCTOR = Cannot resolve the invocation to the correct constructor.
-Remoting_AmbiguousMethod = Cannot resolve the invocation to the correct method.
-Remoting_AppDomains_NYI = This feature is not yet supported for cross-application domain.
-Remoting_AppDomainsCantBeCalledRemotely = Permission denied: cannot call methods on the AppDomain class remotely.
-Remoting_AssemblyLoadFailed = Cannot load assembly '{0}'.
-Remoting_Attribute_UseAttributeNotsettable = UseAttribute not allowed in SoapTypeAttribute.
-Remoting_BadType = Cannot load type '{0}'.
-Remoting_BadField = Remoting cannot find field '{0}' on type '{1}'.
-Remoting_BadInternalState_ActivationFailure = Invalid internal state: Activation service failed to initialize.
-Remoting_BadInternalState_ProxySameAppDomain = Invalid internal state: A marshal by ref object should not have a proxy in its own AppDomain.
-Remoting_BadInternalState_FailEnvoySink = Invalid internal state: Failed to create an envoy sink for the object.
-Remoting_CantDisconnectClientProxy = Cannot call disconnect on a proxy.
-Remoting_CantInvokeIRemoteDispatch = Cannot invoke methods on IRemoteDispatch.
-Remoting_ChannelNameAlreadyRegistered = The channel '{0}' is already registered.
-Remoting_ChannelNotRegistered = The channel '{0}' is not registered with remoting services.
-Remoting_Channel_PopOnEmptySinkStack = Tried to pop data from an empty channel sink stack.
-Remoting_Channel_PopFromSinkStackWithoutPush = A channel sink tried to pop data from the stack without first pushing data onto the stack.
-Remoting_Channel_StoreOnEmptySinkStack = A channel sink called the Store method when the sink stack was empty.
-Remoting_Channel_StoreOnSinkStackWithoutPush = A channel sink called the Store method on the sink stack without first pushing data onto the stack.
-Remoting_Channel_CantCallAPRWhenStackEmpty = Cannot call the AsyncProcessResponse method on the previous channel sink because the stack is empty.
-Remoting_Channel_CantCallFRSWhenStackEmtpy = Called FlipRememberedStack() when stack was not null.
-Remoting_Channel_CantCallGetResponseStreamWhenStackEmpty = Cannot call the GetResponseStream method on the previous channel sink because the stack is empty.
-Remoting_Channel_DispatchSinkMessageMissing = No message was deserialized prior to calling the DispatchChannelSink.
-Remoting_Channel_DispatchSinkWantsNullRequestStream = The request stream should be null when the DispatchChannelSink is called.
-Remoting_Channel_CannotBeSecured = Channel {0} cannot be secured. Please consider using a channel that implements ISecurableChannel
-Remoting_Config_ChannelMissingCtor = To be used from a .config file, the channel type '{0}' must have a constructor of the form '{1}'
-Remoting_Config_SinkProviderMissingCtor = To be used from a .config file, the sink provider type '{0}' must have a constructor of the form '{1}'
-Remoting_Config_SinkProviderNotFormatter = A sink provider of type '{0}' is incorrectly labeled as a 'formatter'.
-Remoting_Config_ConfigurationFailure = Remoting configuration failed with the exception '{0}'.
-Remoting_Config_InvalidTimeFormat = Invalid time format '{0}'. Examples of valid time formats include 7D, 10H, 5M, 30S, or 20MS.
-Remoting_Config_AppNameSet = The remoting application name, '{0}', had already been set.
-Remoting_Config_ErrorsModeSet = The remoting custom errors mode had already been set.
-Remoting_Config_CantRedirectActivationOfWellKnownService = Attempt to redirect activation for type '{0}, {1}'. This is not allowed since either a well-known service type has already been registered with that type or that type has been registered has a activated service type.
-Remoting_Config_CantUseRedirectedTypeForWellKnownService = Attempt to register a well-known or activated service type of type '{0}, {1}'. This is not allowed since the type has already been redirected to activate elsewhere.
-Remoting_Config_InvalidChannelType = '{0}' does not implement IChannelReceiver or IChannelSender. All channels must implement one of these interfaces.
-Remoting_Config_InvalidSinkProviderType = Unable to use '{0}' as a channel sink provider. It does not implement '{1}'.
-Remoting_Config_MissingWellKnownModeAttribute = Well-known service entries must contain a 'mode' attribute with a value of 'Singleton' or 'SingleCall'.
-Remoting_Config_MissingTypeAttribute = '{0}' entries must contain a '{1}' attribute of the form 'typeName, assemblyName'.
-Remoting_Config_MissingXmlTypeAttribute = '{0}' entries must contain a '{1}' attribute of the form 'xmlTypeName, xmlTypeNamespace'.
-Remoting_Config_NoAppName = Improper remoting configuration: missing ApplicationName property.
-Remoting_Config_NonTemplateIdAttribute = Only '{0}' templates can have an 'id' attribute.
-Remoting_Config_PreloadRequiresTypeOrAssembly = Preload entries require a type or assembly attribute.
-Remoting_Config_ProviderNeedsElementName = Sink providers must have an element name of 'formatter' or 'provider'.
-Remoting_Config_RequiredXmlAttribute = '{0}' entries require a '{1}' attribute.
-Remoting_Config_ReadFailure = .Config file '{0}' cannot be read successfully due to exception '{1}'.
-Remoting_Config_NodeMustBeUnique = There can be only one '{0}' node in the '{1}' section of a config file.
-Remoting_Config_TemplateCannotReferenceTemplate = A '{0}' template cannot reference another '{0}' template.
-Remoting_Config_TypeAlreadyRedirected = Attempt to redirect activation of type '{0}, {1}' which is already redirected.
-Remoting_Config_UnknownValue = Unknown value {1} was found on the {0} node.
-Remoting_Config_UnableToResolveTemplate = Cannot resolve '{0}' template reference: '{1}'.
-Remoting_Config_VersionPresent = Version information is present in the assembly name '{0}' which is not allowed for '{1}' entries.
-Remoting_Contexts_BadProperty = A property that contributed a bad sink to the chain was found.
-Remoting_Contexts_NoProperty = A property with the name '{0}' was not found.
-Remoting_Contexts_ContextNotFrozenForCallBack = Context should be frozen before calling the DoCallBack method.
-Remoting_Default = Unknown remoting error.
-Remoting_HandlerNotRegistered = The tracking handler of type '{0}' is not registered with Remoting Services.
-Remoting_InvalidMsg = Invalid Message Object.
-Remoting_InvalidCallingType = Attempted to call a method declared on type '{0}' on an object which exposes '{1}'.
-Remoting_InvalidRequestedType = The server object type cannot be cast to the requested type '{0}'.
-Remoting_InternalError = Server encountered an internal error. For more information, turn off customErrors in the server's .config file.
-Remoting_Lifetime_ILeaseReturn = Expected a return object of type ILease, but received '{0}'.
-Remoting_Lifetime_InitialStateInitialLeaseTime = InitialLeaseTime property can only be set when the lease is in initial state. The state is '{0}'.
-Remoting_Lifetime_InitialStateRenewOnCall = RenewOnCallTime property can only be set when the lease is in initial state. The state is '{0}'.
-Remoting_Lifetime_InitialStateSponsorshipTimeout = SponsorshipTimeout property can only be set when the lease is in initial state. State is '{0}'.
-Remoting_Lifetime_SetOnce = '{0}' can only be set once within an AppDomain.
-Remoting_Message_ArgMismatch = {2} arguments were passed to '{0}::{1}'. {3} arguments were expected by this method.
-Remoting_Message_BadAsyncResult = The async result object is null or of an unexpected type.
-Remoting_Message_BadType = The method was called with a Message of an unexpected type.
-Remoting_Message_CoercionFailed = The argument type '{0}' cannot be converted into parameter type '{1}'.
-Remoting_Message_MissingArgValue = Expecting an instance of type '{0}' at pos {1} in the args array.
-Remoting_Message_BadSerialization = Invalid or malformed serialization information for the message object.
-Remoting_NoIdentityEntry = No remoting information was found for this object.
-Remoting_NotRemotableByReference = Trying to create a proxy to an unbound type.
-Remoting_NullMessage = The method was called with a null message.
-Remoting_Proxy_BadType = The proxy is of an unsupported type.
-Remoting_ResetURI = Attempt to reset the URI for an object from '{0}' to '{1}'.
-Remoting_ServerObjectNotFound = The server object for URI '{0}' is not registered with the remoting infrastructure (it may have been disconnected).
-Remoting_SetObjectUriForMarshal__ObjectNeedsToBeLocal = SetObjectUriForMarshal method should only be called for MarshalByRefObjects that exist in the current AppDomain.
-Remoting_SetObjectUriForMarshal__UriExists = SetObjectUriForMarshal method has already been called on this object or the object has already been marshaled.
-Remoting_Proxy_BadReturnType = Return argument has an invalid type.
-Remoting_Proxy_ReturnValueTypeCannotBeNull = ByRef value type parameter cannot be null.
-Remoting_Proxy_BadReturnTypeForActivation = Bad return type for activation call via Invoke: must be of type IConstructionReturnMessage.
-Remoting_Proxy_BadTypeForActivation = Type mismatch between proxy type '{0}' and activation type '{1}'.
-Remoting_Proxy_ExpectedOriginalMessage = The message passed to Invoke should be passed to PropagateOutParameters.
-Remoting_Proxy_InvalidCall = Trying to call proxy while constructor call is in progress.
-Remoting_Proxy_InvalidState = Channel sink does not exist. Failed to dispatch async call.
-Remoting_Proxy_NoChannelSink = This remoting proxy has no channel sink which means either the server has no registered server channels that are listening, or this application has no suitable client channel to talk to the server.
-Remoting_Proxy_InvalidCallType = Only the synchronous call type is supported for messages that are not of type Message.
-Remoting_Proxy_WrongContext = ExecuteMessage can be called only from the native context of the object.
-Remoting_SOAPInteropxsdInvalid = Soap Parse error, xsd:type '{0}' invalid {1}
-Remoting_SOAPQNameNamespace = SoapQName missing a Namespace value '{0}'.
-Remoting_ThreadAffinity_InvalidFlag = The specified flag '{0}' does not have one of the valid values.
-Remoting_TrackingHandlerAlreadyRegistered = The handler has already been registered with TrackingServices.
-Remoting_URIClash = Found two different objects associated with the same URI, '{0}'.
-Remoting_URIExists = The remoted object already has an associated URI.
-Remoting_URIToProxy = Trying to associate the URI with a proxy.
-Remoting_WellKnown_MustBeMBR = Attempted to create well-known object of type '{0}'. Well-known objects must derive from the MarshalByRefObject class.
-Remoting_WellKnown_CtorCantMarshal = '{0}': A well-known object cannot marshal itself in its constructor, or perform any action that would cause it to be marshaled (such as passing the 'this' pointer as a parameter to a remote method).
-Remoting_WellKnown_CantDirectlyConnect = Attempt to connect to a server using its object URI: '{0}'. A valid, complete URL must be used.
-Remoting_Connect_CantCreateChannelSink = Cannot create channel sink to connect to URL '{0}'. An appropriate channel has probably not been registered.
-Remoting_UnexpectedNullTP = Failed to create a transparent proxy. If a custom RealProxy is being used ensure it sets the proxy type.
-; The following remoting exception messages appear in native resources too (mscorrc.rc)
-Remoting_Disconnected = Object '{0}' has been disconnected or does not exist at the server.
-Remoting_Message_MethodMissing = The method '{0}' was not found on the interface/type '{1}'.
-#endif // FEATURE_REMOTING
; Resources exceptions
;
Security_NoAPTCA = That assembly does not allow partially trusted callers.
Security_RegistryPermission = Requested registry access is not allowed.
Security_MustRevertOverride = Stack walk modifier must be reverted before another modification of the same type can be performed.
-#if FEATURE_CAS_POLICY
-Security_CannotGenerateHash = Hash for the assembly cannot be generated.
-Security_CannotGetRawData = Assembly bytes could not be retrieved.
-Security_PrincipalPermission = Request for principal permission failed.
-Security_Action = The action that failed was:
-Security_TypeFirstPermThatFailed = The type of the first permission that failed was:
-Security_FirstPermThatFailed = The first permission that failed was:
-Security_Demanded = The demand was for:
-Security_GrantedSet = The granted set of the failing assembly was:
-Security_RefusedSet = The refused set of the failing assembly was:
-Security_Denied = The denied permissions were:
-Security_PermitOnly = The only permitted permissions were:
-Security_Assembly = The assembly or AppDomain that failed was:
-Security_Method = The method that caused the failure was:
-Security_Zone = The Zone of the assembly that failed was:
-Security_Url = The Url of the assembly that failed was:
-Security_AnonymouslyHostedDynamicMethodCheckFailed = The demand failed due to the code access security information captured during the creation of an anonymously hosted dynamic method. In order for this operation to succeed, ensure that the demand would have succeeded at the time the method was created. See http://go.microsoft.com/fwlink/?LinkId=288746 for more information.
-#endif // FEATURE_CAS_POLICY
;
; HostProtection exceptions
; PathTooLongException
IO.PathTooLong = The specified file name or path is too long, or a component of the specified path is too long.
-#if FEATURE_CORECLR
; SecurityException
FileSecurityState_OperationNotPermitted = File operation not permitted. Access to path '{0}' is denied.
-#endif
; PrivilegeNotHeldException
PrivilegeNotHeld_Default = The process does not possess some privilege required for this operation.
XMLSyntax_InvalidSyntaxSatAssemTagBadAttr = Invalid XML in file "{0}" near "{1}" and "{2}". In the <satelliteassemblies> section, the <assembly> tag must have exactly 1 attribute called 'name', whose value is a fully-qualified assembly name.
XMLSyntax_InvalidSyntaxSatAssemTagNoAttr = Invalid XML in file "{0}". In the <satelliteassemblies> section, the <assembly> tag must have exactly 1 attribute called 'name', whose value is a fully-qualified assembly name.
-; CodeGroup
-#if FEATURE_CAS_POLICY
-NetCodeGroup_PermissionSet = Same site Web
-MergeLogic_Union = Union
-MergeLogic_FirstMatch = First Match
-FileCodeGroup_PermissionSet = Same directory FileIO - '{0}'
-#endif // FEATURE_CAS_POLICY
-
; MembershipConditions
StrongName_ToString = StrongName - {0}{1}{2}
StrongName_Name = name = {0}
All_ToString = All code
Url_ToString = Url
GAC_ToString = GAC
-#if FEATURE_CAS_POLICY
-Site_ToStringArg = Site - {0}
-Publisher_ToStringArg = Publisher - {0}
-Url_ToStringArg = Url - {0}
-#endif // FEATURE_CAS_POLICY
-
; Interop non exception strings.
TypeLibConverter_ImportedTypeLibProductName = Assembly imported from type library '{0}'.
; Buffers
ArgumentException_BufferNotFromPool=The buffer is not associated with this pool and may not be returned to it.
-; Globalization resources
-;------------------
-
-#if !FEATURE_CORECLR
-Globalization.LegacyModifier = Legacy
-
-;
-;Total items: 809
-;
-Globalization.ci_ = Invariant Language (Invariant Country)
-Globalization.ci_aa = Afar
-Globalization.ci_aa-DJ = Afar (Djibouti)
-Globalization.ci_aa-ER = Afar (Eritrea)
-Globalization.ci_aa-ET = Afar (Ethiopia)
-Globalization.ci_af = Afrikaans
-Globalization.ci_af-NA = Afrikaans (Namibia)
-Globalization.ci_af-ZA = Afrikaans (South Africa)
-Globalization.ci_agq = Aghem
-Globalization.ci_agq-CM = Aghem (Cameroon)
-Globalization.ci_ak = Akan
-Globalization.ci_ak-GH = Akan (Ghana)
-Globalization.ci_am = Amharic
-Globalization.ci_am-ET = Amharic (Ethiopia)
-Globalization.ci_ar = Arabic
-Globalization.ci_ar-001 = Arabic (World)
-Globalization.ci_ar-AE = Arabic (U.A.E.)
-Globalization.ci_ar-BH = Arabic (Bahrain)
-Globalization.ci_ar-DJ = Arabic (Djibouti)
-Globalization.ci_ar-DZ = Arabic (Algeria)
-Globalization.ci_ar-EG = Arabic (Egypt)
-Globalization.ci_ar-ER = Arabic (Eritrea)
-Globalization.ci_ar-IL = Arabic (Israel)
-Globalization.ci_ar-IQ = Arabic (Iraq)
-Globalization.ci_ar-JO = Arabic (Jordan)
-Globalization.ci_ar-KM = Arabic (Comoros)
-Globalization.ci_ar-KW = Arabic (Kuwait)
-Globalization.ci_ar-LB = Arabic (Lebanon)
-Globalization.ci_ar-LY = Arabic (Libya)
-Globalization.ci_ar-MA = Arabic (Morocco)
-Globalization.ci_ar-MR = Arabic (Mauritania)
-Globalization.ci_ar-OM = Arabic (Oman)
-Globalization.ci_ar-PS = Arabic (Palestinian Authority)
-Globalization.ci_ar-QA = Arabic (Qatar)
-Globalization.ci_ar-SA = Arabic (Saudi Arabia)
-Globalization.ci_ar-SD = Arabic (Sudan)
-Globalization.ci_ar-SO = Arabic (Somalia)
-Globalization.ci_ar-SS = Arabic (South Sudan)
-Globalization.ci_ar-SY = Arabic (Syria)
-Globalization.ci_ar-TD = Arabic (Chad)
-Globalization.ci_ar-TN = Arabic (Tunisia)
-Globalization.ci_ar-YE = Arabic (Yemen)
-Globalization.ci_arn = Mapudungun
-Globalization.ci_arn-CL = Mapudungun (Chile)
-Globalization.ci_as = Assamese
-Globalization.ci_as-IN = Assamese (India)
-Globalization.ci_asa = Asu
-Globalization.ci_asa-TZ = Asu (Tanzania)
-Globalization.ci_ast = Asturian
-Globalization.ci_ast-ES = Asturian (Spain)
-Globalization.ci_az = Azerbaijani
-Globalization.ci_az-Cyrl = Azerbaijani (Cyrillic)
-Globalization.ci_az-Cyrl-AZ = Azerbaijani (Cyrillic, Azerbaijan)
-Globalization.ci_az-Latn = Azerbaijani (Latin)
-Globalization.ci_az-Latn-AZ = Azerbaijani (Latin, Azerbaijan)
-Globalization.ci_ba = Bashkir
-Globalization.ci_ba-RU = Bashkir (Russia)
-Globalization.ci_bas = Basaa
-Globalization.ci_bas-CM = Basaa (Cameroon)
-Globalization.ci_be = Belarusian
-Globalization.ci_be-BY = Belarusian (Belarus)
-Globalization.ci_bem = Bemba
-Globalization.ci_bem-ZM = Bemba (Zambia)
-Globalization.ci_bez = Bena
-Globalization.ci_bez-TZ = Bena (Tanzania)
-Globalization.ci_bg = Bulgarian
-Globalization.ci_bg-BG = Bulgarian (Bulgaria)
-Globalization.ci_bm = Bambara
-Globalization.ci_bm-Latn = Bambara (Latin)
-Globalization.ci_bm-Latn-ML = Bambara (Latin, Mali)
-Globalization.ci_bm-ML = Bamanankan (Latin, Mali)
-Globalization.ci_bn = Bangla
-Globalization.ci_bn-BD = Bangla (Bangladesh)
-Globalization.ci_bn-IN = Bangla (India)
-Globalization.ci_bo = Tibetan
-Globalization.ci_bo-CN = Tibetan (PRC)
-Globalization.ci_bo-IN = Tibetan (India)
-Globalization.ci_br = Breton
-Globalization.ci_br-FR = Breton (France)
-Globalization.ci_brx = Bodo
-Globalization.ci_brx-IN = Bodo (India)
-Globalization.ci_bs = Bosnian
-Globalization.ci_bs-Cyrl = Bosnian (Cyrillic)
-Globalization.ci_bs-Cyrl-BA = Bosnian (Cyrillic, Bosnia and Herzegovina)
-Globalization.ci_bs-Latn = Bosnian (Latin)
-Globalization.ci_bs-Latn-BA = Bosnian (Latin, Bosnia and Herzegovina)
-Globalization.ci_byn = Blin
-Globalization.ci_byn-ER = Blin (Eritrea)
-Globalization.ci_ca = Catalan
-Globalization.ci_ca-AD = Catalan (Andorra)
-Globalization.ci_ca-ES = Catalan (Catalan)
-Globalization.ci_ca-ES-valencia = Valencian (Spain)
-Globalization.ci_ca-FR = Catalan (France)
-Globalization.ci_ca-IT = Catalan (Italy)
-Globalization.ci_cgg = Chiga
-Globalization.ci_cgg-UG = Chiga (Uganda)
-Globalization.ci_chr = Cherokee
-Globalization.ci_chr-Cher = Cherokee (Cherokee)
-Globalization.ci_chr-Cher-US = Cherokee (Cherokee)
-Globalization.ci_co = Corsican
-Globalization.ci_co-FR = Corsican (France)
-Globalization.ci_cs = Czech
-Globalization.ci_cs-CZ = Czech (Czech Republic)
-Globalization.ci_cy = Welsh
-Globalization.ci_cy-GB = Welsh (United Kingdom)
-Globalization.ci_da = Danish
-Globalization.ci_da-DK = Danish (Denmark)
-Globalization.ci_da-GL = Danish (Greenland)
-Globalization.ci_dav = Taita
-Globalization.ci_dav-KE = Taita (Kenya)
-Globalization.ci_de = German
-Globalization.ci_de-AT = German (Austria)
-Globalization.ci_de-BE = German (Belgium)
-Globalization.ci_de-CH = German (Switzerland)
-Globalization.ci_de-DE = German (Germany)
-Globalization.ci_de-DE_phoneb = German (Germany)
-Globalization.ci_de-LI = German (Liechtenstein)
-Globalization.ci_de-LU = German (Luxembourg)
-Globalization.ci_dje = Zarma
-Globalization.ci_dje-NE = Zarma (Niger)
-Globalization.ci_dsb = Lower Sorbian
-Globalization.ci_dsb-DE = Lower Sorbian (Germany)
-Globalization.ci_dua = Duala
-Globalization.ci_dua-CM = Duala (Cameroon)
-Globalization.ci_dv = Divehi
-Globalization.ci_dv-MV = Divehi (Maldives)
-Globalization.ci_dyo = Jola-Fonyi
-Globalization.ci_dyo-SN = Jola-Fonyi (Senegal)
-Globalization.ci_dz = Dzongkha
-Globalization.ci_dz-BT = Dzongkha (Bhutan)
-Globalization.ci_ebu = Embu
-Globalization.ci_ebu-KE = Embu (Kenya)
-Globalization.ci_ee = Ewe
-Globalization.ci_ee-GH = Ewe (Ghana)
-Globalization.ci_ee-TG = Ewe (Togo)
-Globalization.ci_el = Greek
-Globalization.ci_el-CY = Greek (Cyprus)
-Globalization.ci_el-GR = Greek (Greece)
-Globalization.ci_en = English
-Globalization.ci_en-001 = English (World)
-Globalization.ci_en-029 = English (Caribbean)
-Globalization.ci_en-150 = English (Europe)
-Globalization.ci_en-AG = English (Antigua and Barbuda)
-Globalization.ci_en-AI = English (Anguilla)
-Globalization.ci_en-AS = English (American Samoa)
-Globalization.ci_en-AU = English (Australia)
-Globalization.ci_en-BB = English (Barbados)
-Globalization.ci_en-BE = English (Belgium)
-Globalization.ci_en-BM = English (Bermuda)
-Globalization.ci_en-BS = English (Bahamas)
-Globalization.ci_en-BW = English (Botswana)
-Globalization.ci_en-BZ = English (Belize)
-Globalization.ci_en-CA = English (Canada)
-Globalization.ci_en-CC = English (Cocos [Keeling] Islands)
-Globalization.ci_en-CK = English (Cook Islands)
-Globalization.ci_en-CM = English (Cameroon)
-Globalization.ci_en-CX = English (Christmas Island)
-Globalization.ci_en-DM = English (Dominica)
-Globalization.ci_en-ER = English (Eritrea)
-Globalization.ci_en-FJ = English (Fiji)
-Globalization.ci_en-FK = English (Falkland Islands)
-Globalization.ci_en-FM = English (Micronesia)
-Globalization.ci_en-GB = English (United Kingdom)
-Globalization.ci_en-GD = English (Grenada)
-Globalization.ci_en-GG = English (Guernsey)
-Globalization.ci_en-GH = English (Ghana)
-Globalization.ci_en-GI = English (Gibraltar)
-Globalization.ci_en-GM = English (Gambia)
-Globalization.ci_en-GU = English (Guam)
-Globalization.ci_en-GY = English (Guyana)
-Globalization.ci_en-HK = English (Hong Kong SAR)
-Globalization.ci_en-IE = English (Ireland)
-Globalization.ci_en-IM = English (Isle of Man)
-Globalization.ci_en-IN = English (India)
-Globalization.ci_en-IO = English (British Indian Ocean Territory)
-Globalization.ci_en-JE = English (Jersey)
-Globalization.ci_en-JM = English (Jamaica)
-Globalization.ci_en-KE = English (Kenya)
-Globalization.ci_en-KI = English (Kiribati)
-Globalization.ci_en-KN = English (Saint Kitts and Nevis)
-Globalization.ci_en-KY = English (Cayman Islands)
-Globalization.ci_en-LC = English (Saint Lucia)
-Globalization.ci_en-LR = English (Liberia)
-Globalization.ci_en-LS = English (Lesotho)
-Globalization.ci_en-MG = English (Madagascar)
-Globalization.ci_en-MH = English (Marshall Islands)
-Globalization.ci_en-MO = English (Macao SAR)
-Globalization.ci_en-MP = English (Northern Mariana Islands)
-Globalization.ci_en-MS = English (Montserrat)
-Globalization.ci_en-MT = English (Malta)
-Globalization.ci_en-MU = English (Mauritius)
-Globalization.ci_en-MW = English (Malawi)
-Globalization.ci_en-MY = English (Malaysia)
-Globalization.ci_en-NA = English (Namibia)
-Globalization.ci_en-NF = English (Norfolk Island)
-Globalization.ci_en-NG = English (Nigeria)
-Globalization.ci_en-NR = English (Nauru)
-Globalization.ci_en-NU = English (Niue)
-Globalization.ci_en-NZ = English (New Zealand)
-Globalization.ci_en-PG = English (Papua New Guinea)
-Globalization.ci_en-PH = English (Republic of the Philippines)
-Globalization.ci_en-PK = English (Pakistan)
-Globalization.ci_en-PN = English (Pitcairn Islands)
-Globalization.ci_en-PR = English (Puerto Rico)
-Globalization.ci_en-PW = English (Palau)
-Globalization.ci_en-RW = English (Rwanda)
-Globalization.ci_en-SB = English (Solomon Islands)
-Globalization.ci_en-SC = English (Seychelles)
-Globalization.ci_en-SD = English (Sudan)
-Globalization.ci_en-SG = English (Singapore)
-Globalization.ci_en-SH = English (St Helena, Ascension, Tristan da Cunha)
-Globalization.ci_en-SL = English (Sierra Leone)
-Globalization.ci_en-SS = English (South Sudan)
-Globalization.ci_en-SX = English (Sint Maarten)
-Globalization.ci_en-SZ = English (Swaziland)
-Globalization.ci_en-TC = English (Turks and Caicos Islands)
-Globalization.ci_en-TK = English (Tokelau)
-Globalization.ci_en-TO = English (Tonga)
-Globalization.ci_en-TT = English (Trinidad and Tobago)
-Globalization.ci_en-TV = English (Tuvalu)
-Globalization.ci_en-TZ = English (Tanzania)
-Globalization.ci_en-UG = English (Uganda)
-Globalization.ci_en-UM = English (US Minor Outlying Islands)
-Globalization.ci_en-US = English (United States)
-Globalization.ci_en-VC = English (Saint Vincent and the Grenadines)
-Globalization.ci_en-VG = English (British Virgin Islands)
-Globalization.ci_en-VI = English (US Virgin Islands)
-Globalization.ci_en-VU = English (Vanuatu)
-Globalization.ci_en-WS = English (Samoa)
-Globalization.ci_en-ZA = English (South Africa)
-Globalization.ci_en-ZM = English (Zambia)
-Globalization.ci_en-ZW = English (Zimbabwe)
-Globalization.ci_eo = Esperanto
-Globalization.ci_eo-001 = Esperanto (World)
-Globalization.ci_es = Spanish
-Globalization.ci_es-419 = Spanish (Latin America)
-Globalization.ci_es-AR = Spanish (Argentina)
-Globalization.ci_es-BO = Spanish (Bolivia)
-Globalization.ci_es-CL = Spanish (Chile)
-Globalization.ci_es-CO = Spanish (Colombia)
-Globalization.ci_es-CR = Spanish (Costa Rica)
-Globalization.ci_es-CU = Spanish (Cuba)
-Globalization.ci_es-DO = Spanish (Dominican Republic)
-Globalization.ci_es-EC = Spanish (Ecuador)
-Globalization.ci_es-ES = Spanish (Spain)
-Globalization.ci_es-ES_tradnl = Spanish (Spain)
-Globalization.ci_es-GQ = Spanish (Equatorial Guinea)
-Globalization.ci_es-GT = Spanish (Guatemala)
-Globalization.ci_es-HN = Spanish (Honduras)
-Globalization.ci_es-MX = Spanish (Mexico)
-Globalization.ci_es-NI = Spanish (Nicaragua)
-Globalization.ci_es-PA = Spanish (Panama)
-Globalization.ci_es-PE = Spanish (Peru)
-Globalization.ci_es-PH = Spanish (Philippines)
-Globalization.ci_es-PR = Spanish (Puerto Rico)
-Globalization.ci_es-PY = Spanish (Paraguay)
-Globalization.ci_es-SV = Spanish (El Salvador)
-Globalization.ci_es-US = Spanish (United States)
-Globalization.ci_es-UY = Spanish (Uruguay)
-Globalization.ci_es-VE = Spanish (Bolivarian Republic of Venezuela)
-Globalization.ci_et = Estonian
-Globalization.ci_et-EE = Estonian (Estonia)
-Globalization.ci_eu = Basque
-Globalization.ci_eu-ES = Basque (Basque)
-Globalization.ci_ewo = Ewondo
-Globalization.ci_ewo-CM = Ewondo (Cameroon)
-Globalization.ci_fa = Persian
-Globalization.ci_fa-AF = Persian (Afghanistan)
-Globalization.ci_fa-IR = Persian (Iran)
-Globalization.ci_ff = Fulah
-Globalization.ci_ff-CM = Fulah (Cameroon)
-Globalization.ci_ff-GN = Fulah (Guinea)
-Globalization.ci_ff-Latn = Fulah (Latin)
-Globalization.ci_ff-Latn-SN = Fulah (Latin, Senegal)
-Globalization.ci_ff-MR = Fulah (Mauritania)
-Globalization.ci_fi = Finnish
-Globalization.ci_fi-FI = Finnish (Finland)
-Globalization.ci_fil = Filipino
-Globalization.ci_fil-PH = Filipino (Philippines)
-Globalization.ci_fo = Faroese
-Globalization.ci_fo-FO = Faroese (Faroe Islands)
-Globalization.ci_fr = French
-Globalization.ci_fr-BE = French (Belgium)
-Globalization.ci_fr-BF = French (Burkina Faso)
-Globalization.ci_fr-BI = French (Burundi)
-Globalization.ci_fr-BJ = French (Benin)
-Globalization.ci_fr-BL = French (Saint Barthélemy)
-Globalization.ci_fr-CA = French (Canada)
-Globalization.ci_fr-CD = French (Congo DRC)
-Globalization.ci_fr-CF = French (Central African Republic)
-Globalization.ci_fr-CG = French (Congo)
-Globalization.ci_fr-CH = French (Switzerland)
-Globalization.ci_fr-CI = French (Côte d’Ivoire)
-Globalization.ci_fr-CM = French (Cameroon)
-Globalization.ci_fr-DJ = French (Djibouti)
-Globalization.ci_fr-DZ = French (Algeria)
-Globalization.ci_fr-FR = French (France)
-Globalization.ci_fr-GA = French (Gabon)
-Globalization.ci_fr-GF = French (French Guiana)
-Globalization.ci_fr-GN = French (Guinea)
-Globalization.ci_fr-GP = French (Guadeloupe)
-Globalization.ci_fr-GQ = French (Equatorial Guinea)
-Globalization.ci_fr-HT = French (Haiti)
-Globalization.ci_fr-KM = French (Comoros)
-Globalization.ci_fr-LU = French (Luxembourg)
-Globalization.ci_fr-MA = French (Morocco)
-Globalization.ci_fr-MC = French (Monaco)
-Globalization.ci_fr-MF = French (Saint Martin)
-Globalization.ci_fr-MG = French (Madagascar)
-Globalization.ci_fr-ML = French (Mali)
-Globalization.ci_fr-MQ = French (Martinique)
-Globalization.ci_fr-MR = French (Mauritania)
-Globalization.ci_fr-MU = French (Mauritius)
-Globalization.ci_fr-NC = French (New Caledonia)
-Globalization.ci_fr-NE = French (Niger)
-Globalization.ci_fr-PF = French (French Polynesia)
-Globalization.ci_fr-PM = French (Saint Pierre and Miquelon)
-Globalization.ci_fr-RE = French (Reunion)
-Globalization.ci_fr-RW = French (Rwanda)
-Globalization.ci_fr-SC = French (Seychelles)
-Globalization.ci_fr-SN = French (Senegal)
-Globalization.ci_fr-SY = French (Syria)
-Globalization.ci_fr-TD = French (Chad)
-Globalization.ci_fr-TG = French (Togo)
-Globalization.ci_fr-TN = French (Tunisia)
-Globalization.ci_fr-VU = French (Vanuatu)
-Globalization.ci_fr-WF = French (Wallis and Futuna)
-Globalization.ci_fr-YT = French (Mayotte)
-Globalization.ci_fur = Friulian
-Globalization.ci_fur-IT = Friulian (Italy)
-Globalization.ci_fy = Frisian
-Globalization.ci_fy-NL = Frisian (Netherlands)
-Globalization.ci_ga = Irish
-Globalization.ci_ga-IE = Irish (Ireland)
-Globalization.ci_gd = Scottish Gaelic
-Globalization.ci_gd-GB = Scottish Gaelic (United Kingdom)
-Globalization.ci_gl = Galician
-Globalization.ci_gl-ES = Galician (Galician)
-Globalization.ci_gn = Guarani
-Globalization.ci_gn-PY = Guarani (Paraguay)
-Globalization.ci_gsw = Alsatian
-Globalization.ci_gsw-CH = Alsatian (Switzerland)
-Globalization.ci_gsw-FR = Alsatian (France)
-Globalization.ci_gsw-LI = Alsatian (Liechtenstein)
-Globalization.ci_gu = Gujarati
-Globalization.ci_gu-IN = Gujarati (India)
-Globalization.ci_guz = Gusii
-Globalization.ci_guz-KE = Gusii (Kenya)
-Globalization.ci_gv = Manx
-Globalization.ci_gv-IM = Manx (Isle of Man)
-Globalization.ci_ha = Hausa
-Globalization.ci_ha-Latn = Hausa (Latin)
-Globalization.ci_ha-Latn-GH = Hausa (Latin, Ghana)
-Globalization.ci_ha-Latn-NE = Hausa (Latin, Niger)
-Globalization.ci_ha-Latn-NG = Hausa (Latin, Nigeria)
-Globalization.ci_haw = Hawaiian
-Globalization.ci_haw-US = Hawaiian (United States)
-Globalization.ci_he = Hebrew
-Globalization.ci_he-IL = Hebrew (Israel)
-Globalization.ci_hi = Hindi
-Globalization.ci_hi-IN = Hindi (India)
-Globalization.ci_hr = Croatian
-Globalization.ci_hr-BA = Croatian (Latin, Bosnia and Herzegovina)
-Globalization.ci_hr-HR = Croatian (Croatia)
-Globalization.ci_hsb = Upper Sorbian
-Globalization.ci_hsb-DE = Upper Sorbian (Germany)
-Globalization.ci_hu = Hungarian
-Globalization.ci_hu-HU = Hungarian (Hungary)
-Globalization.ci_hu-HU_technl = Hungarian (Hungary)
-Globalization.ci_hy = Armenian
-Globalization.ci_hy-AM = Armenian (Armenia)
-Globalization.ci_ia = Interlingua
-Globalization.ci_ia-001 = Interlingua (World)
-Globalization.ci_ia-FR = Interlingua (France)
-Globalization.ci_id = Indonesian
-Globalization.ci_id-ID = Indonesian (Indonesia)
-Globalization.ci_ig = Igbo
-Globalization.ci_ig-NG = Igbo (Nigeria)
-Globalization.ci_ii = Yi
-Globalization.ci_ii-CN = Yi (PRC)
-Globalization.ci_is = Icelandic
-Globalization.ci_is-IS = Icelandic (Iceland)
-Globalization.ci_it = Italian
-Globalization.ci_it-CH = Italian (Switzerland)
-Globalization.ci_it-IT = Italian (Italy)
-Globalization.ci_it-SM = Italian (San Marino)
-Globalization.ci_iu = Inuktitut
-Globalization.ci_iu-Cans = Inuktitut (Syllabics)
-Globalization.ci_iu-Cans-CA = Inuktitut (Syllabics, Canada)
-Globalization.ci_iu-Latn = Inuktitut (Latin)
-Globalization.ci_iu-Latn-CA = Inuktitut (Latin, Canada)
-Globalization.ci_ja = Japanese
-Globalization.ci_ja-JP = Japanese (Japan)
-Globalization.ci_ja-JP_radstr = Japanese (Japan)
-Globalization.ci_jgo = Ngomba
-Globalization.ci_jgo-CM = Ngomba (Cameroon)
-Globalization.ci_jmc = Machame
-Globalization.ci_jmc-TZ = Machame (Tanzania)
-Globalization.ci_jv = Javanese
-Globalization.ci_jv-Latn = Javanese
-Globalization.ci_jv-Latn-ID = Javanese (Indonesia)
-Globalization.ci_ka = Georgian
-Globalization.ci_ka-GE = Georgian (Georgia)
-Globalization.ci_ka-GE_modern = Georgian (Georgia)
-Globalization.ci_kab = Kabyle
-Globalization.ci_kab-DZ = Kabyle (Algeria)
-Globalization.ci_kam = Kamba
-Globalization.ci_kam-KE = Kamba (Kenya)
-Globalization.ci_kde = Makonde
-Globalization.ci_kde-TZ = Makonde (Tanzania)
-Globalization.ci_kea = Kabuverdianu
-Globalization.ci_kea-CV = Kabuverdianu (Cabo Verde)
-Globalization.ci_khq = Koyra Chiini
-Globalization.ci_khq-ML = Koyra Chiini (Mali)
-Globalization.ci_ki = Kikuyu
-Globalization.ci_ki-KE = Kikuyu (Kenya)
-Globalization.ci_kk = Kazakh
-Globalization.ci_kk-KZ = Kazakh (Kazakhstan)
-Globalization.ci_kkj = Kako
-Globalization.ci_kkj-CM = Kako (Cameroon)
-Globalization.ci_kl = Greenlandic
-Globalization.ci_kl-GL = Greenlandic (Greenland)
-Globalization.ci_kln = Kalenjin
-Globalization.ci_kln-KE = Kalenjin (Kenya)
-Globalization.ci_km = Khmer
-Globalization.ci_km-KH = Khmer (Cambodia)
-Globalization.ci_kn = Kannada
-Globalization.ci_kn-IN = Kannada (India)
-Globalization.ci_ko = Korean
-Globalization.ci_ko-KR = Korean (Korea)
-Globalization.ci_kok = Konkani
-Globalization.ci_kok-IN = Konkani (India)
-Globalization.ci_ks = Kashmiri
-Globalization.ci_ks-Arab = Kashmiri (Perso-Arabic)
-Globalization.ci_ks-Arab-IN = Kashmiri (Perso-Arabic)
-Globalization.ci_ksb = Shambala
-Globalization.ci_ksb-TZ = Shambala (Tanzania)
-Globalization.ci_ksf = Bafia
-Globalization.ci_ksf-CM = Bafia (Cameroon)
-Globalization.ci_ksh = Colognian
-Globalization.ci_ksh-DE = Ripuarian (Germany)
-Globalization.ci_ku = Central Kurdish
-Globalization.ci_ku-Arab = Central Kurdish (Arabic)
-Globalization.ci_ku-Arab-IQ = Central Kurdish (Iraq)
-Globalization.ci_kw = Cornish
-Globalization.ci_kw-GB = Cornish (United Kingdom)
-Globalization.ci_ky = Kyrgyz
-Globalization.ci_ky-KG = Kyrgyz (Kyrgyzstan)
-Globalization.ci_lag = Langi
-Globalization.ci_lag-TZ = Langi (Tanzania)
-Globalization.ci_lb = Luxembourgish
-Globalization.ci_lb-LU = Luxembourgish (Luxembourg)
-Globalization.ci_lg = Ganda
-Globalization.ci_lg-UG = Ganda (Uganda)
-Globalization.ci_lkt = Lakota
-Globalization.ci_lkt-US = Lakota (United States)
-Globalization.ci_ln = Lingala
-Globalization.ci_ln-AO = Lingala (Angola)
-Globalization.ci_ln-CD = Lingala (Congo DRC)
-Globalization.ci_ln-CF = Lingala (Central African Republic)
-Globalization.ci_ln-CG = Lingala (Congo)
-Globalization.ci_lo = Lao
-Globalization.ci_lo-LA = Lao (Lao P.D.R.)
-Globalization.ci_lt = Lithuanian
-Globalization.ci_lt-LT = Lithuanian (Lithuania)
-Globalization.ci_lu = Luba-Katanga
-Globalization.ci_lu-CD = Luba-Katanga (Congo DRC)
-Globalization.ci_luo = Luo
-Globalization.ci_luo-KE = Luo (Kenya)
-Globalization.ci_luy = Luyia
-Globalization.ci_luy-KE = Luyia (Kenya)
-Globalization.ci_lv = Latvian
-Globalization.ci_lv-LV = Latvian (Latvia)
-Globalization.ci_mas = Masai
-Globalization.ci_mas-KE = Masai (Kenya)
-Globalization.ci_mas-TZ = Masai (Tanzania)
-Globalization.ci_mer = Meru
-Globalization.ci_mer-KE = Meru (Kenya)
-Globalization.ci_mfe = Morisyen
-Globalization.ci_mfe-MU = Morisyen (Mauritius)
-Globalization.ci_mg = Malagasy
-Globalization.ci_mg-MG = Malagasy (Madagascar)
-Globalization.ci_mgh = Makhuwa-Meetto
-Globalization.ci_mgh-MZ = Makhuwa-Meetto (Mozambique)
-Globalization.ci_mgo = Meta'
-Globalization.ci_mgo-CM = Meta' (Cameroon)
-Globalization.ci_mi = Maori
-Globalization.ci_mi-NZ = Maori (New Zealand)
-Globalization.ci_mk = Macedonian (FYROM)
-Globalization.ci_mk-MK = Macedonian (Former Yugoslav Republic of Macedonia)
-Globalization.ci_ml = Malayalam
-Globalization.ci_ml-IN = Malayalam (India)
-Globalization.ci_mn = Mongolian
-Globalization.ci_mn-Cyrl = Mongolian (Cyrillic)
-Globalization.ci_mn-MN = Mongolian (Cyrillic, Mongolia)
-Globalization.ci_mn-Mong = Mongolian (Traditional Mongolian)
-Globalization.ci_mn-Mong-CN = Mongolian (Traditional Mongolian, PRC)
-Globalization.ci_mn-Mong-MN = Mongolian (Traditional Mongolian, Mongolia)
-Globalization.ci_moh = Mohawk
-Globalization.ci_moh-CA = Mohawk (Mohawk)
-Globalization.ci_mr = Marathi
-Globalization.ci_mr-IN = Marathi (India)
-Globalization.ci_ms = Malay
-Globalization.ci_ms-BN = Malay (Brunei Darussalam)
-Globalization.ci_ms-MY = Malay (Malaysia)
-Globalization.ci_ms-SG = Malay (Latin, Singapore)
-Globalization.ci_mt = Maltese
-Globalization.ci_mt-MT = Maltese (Malta)
-Globalization.ci_mua = Mundang
-Globalization.ci_mua-CM = Mundang (Cameroon)
-Globalization.ci_my = Burmese
-Globalization.ci_my-MM = Burmese (Myanmar)
-Globalization.ci_naq = Nama
-Globalization.ci_naq-NA = Nama (Namibia)
-Globalization.ci_nb = Norwegian (Bokmål)
-Globalization.ci_nb-NO = Norwegian, Bokmål (Norway)
-Globalization.ci_nb-SJ = Norwegian, Bokmål (Svalbard and Jan Mayen)
-Globalization.ci_nd = North Ndebele
-Globalization.ci_nd-ZW = North Ndebele (Zimbabwe)
-Globalization.ci_ne = Nepali
-Globalization.ci_ne-IN = Nepali (India)
-Globalization.ci_ne-NP = Nepali (Nepal)
-Globalization.ci_nl = Dutch
-Globalization.ci_nl-AW = Dutch (Aruba)
-Globalization.ci_nl-BE = Dutch (Belgium)
-Globalization.ci_nl-BQ = Dutch (Bonaire, Sint Eustatius and Saba)
-Globalization.ci_nl-CW = Dutch (Curaçao)
-Globalization.ci_nl-NL = Dutch (Netherlands)
-Globalization.ci_nl-SR = Dutch (Suriname)
-Globalization.ci_nl-SX = Dutch (Sint Maarten)
-Globalization.ci_nmg = Kwasio
-Globalization.ci_nmg-CM = Kwasio (Cameroon)
-Globalization.ci_nn = Norwegian (Nynorsk)
-Globalization.ci_nn-NO = Norwegian, Nynorsk (Norway)
-Globalization.ci_nnh = Ngiemboon
-Globalization.ci_nnh-CM = Ngiemboon (Cameroon)
-Globalization.ci_no = Norwegian
-Globalization.ci_nqo = N'ko
-Globalization.ci_nqo-GN = N'ko (Guinea)
-Globalization.ci_nr = South Ndebele
-Globalization.ci_nr-ZA = South Ndebele (South Africa)
-Globalization.ci_nso = Sesotho sa Leboa
-Globalization.ci_nso-ZA = Sesotho sa Leboa (South Africa)
-Globalization.ci_nus = Nuer
-Globalization.ci_nus-SD = Nuer (Sudan)
-Globalization.ci_nyn = Nyankole
-Globalization.ci_nyn-UG = Nyankole (Uganda)
-Globalization.ci_oc = Occitan
-Globalization.ci_oc-FR = Occitan (France)
-Globalization.ci_om = Oromo
-Globalization.ci_om-ET = Oromo (Ethiopia)
-Globalization.ci_om-KE = Oromo (Kenya)
-Globalization.ci_or = Odia
-Globalization.ci_or-IN = Odia (India)
-Globalization.ci_os = Ossetic
-Globalization.ci_os-GE = Ossetian (Cyrillic, Georgia)
-Globalization.ci_os-RU = Ossetian (Cyrillic, Russia)
-Globalization.ci_pa = Punjabi
-Globalization.ci_pa-Arab = Punjabi (Arabic)
-Globalization.ci_pa-Arab-PK = Punjabi (Islamic Republic of Pakistan)
-Globalization.ci_pa-IN = Punjabi (India)
-Globalization.ci_pl = Polish
-Globalization.ci_pl-PL = Polish (Poland)
-Globalization.ci_prs = Dari
-Globalization.ci_prs-AF = Dari (Afghanistan)
-Globalization.ci_ps = Pashto
-Globalization.ci_ps-AF = Pashto (Afghanistan)
-Globalization.ci_pt = Portuguese
-Globalization.ci_pt-AO = Portuguese (Angola)
-Globalization.ci_pt-BR = Portuguese (Brazil)
-Globalization.ci_pt-CV = Portuguese (Cabo Verde)
-Globalization.ci_pt-GW = Portuguese (Guinea-Bissau)
-Globalization.ci_pt-MO = Portuguese (Macao SAR)
-Globalization.ci_pt-MZ = Portuguese (Mozambique)
-Globalization.ci_pt-PT = Portuguese (Portugal)
-Globalization.ci_pt-ST = Portuguese (São Tomé and PrÃncipe)
-Globalization.ci_pt-TL = Portuguese (Timor-Leste)
-Globalization.ci_qps-ploc = Pseudo Language (Pseudo)
-Globalization.ci_qps-ploca = Pseudo Language (Pseudo Asia)
-Globalization.ci_qps-plocm = Pseudo Language (Pseudo Mirrored)
-Globalization.ci_qu = Quechua
-Globalization.ci_qu-BO = Quechua (Bolivia)
-Globalization.ci_qu-EC = Quechua (Ecuador)
-Globalization.ci_qu-PE = Quechua (Peru)
-Globalization.ci_quc = K'iche'
-Globalization.ci_quc-Latn = K'iche'
-Globalization.ci_quc-Latn-GT = K'iche' (Guatemala)
-Globalization.ci_qut = K'iche
-Globalization.ci_qut-GT = K'iche (Guatemala)
-Globalization.ci_quz = Quechua
-Globalization.ci_quz-BO = Quechua (Bolivia)
-Globalization.ci_quz-EC = Quechua (Ecuador)
-Globalization.ci_quz-PE = Quechua (Peru)
-Globalization.ci_rm = Romansh
-Globalization.ci_rm-CH = Romansh (Switzerland)
-Globalization.ci_rn = Rundi
-Globalization.ci_rn-BI = Rundi (Burundi)
-Globalization.ci_ro = Romanian
-Globalization.ci_ro-MD = Romanian (Moldova)
-Globalization.ci_ro-RO = Romanian (Romania)
-Globalization.ci_rof = Rombo
-Globalization.ci_rof-TZ = Rombo (Tanzania)
-Globalization.ci_ru = Russian
-Globalization.ci_ru-BY = Russian (Belarus)
-Globalization.ci_ru-KG = Russian (Kyrgyzstan)
-Globalization.ci_ru-KZ = Russian (Kazakhstan)
-Globalization.ci_ru-MD = Russian (Moldova)
-Globalization.ci_ru-RU = Russian (Russia)
-Globalization.ci_ru-UA = Russian (Ukraine)
-Globalization.ci_rw = Kinyarwanda
-Globalization.ci_rw-RW = Kinyarwanda (Rwanda)
-Globalization.ci_rwk = Rwa
-Globalization.ci_rwk-TZ = Rwa (Tanzania)
-Globalization.ci_sa = Sanskrit
-Globalization.ci_sa-IN = Sanskrit (India)
-Globalization.ci_sah = Sakha
-Globalization.ci_sah-RU = Sakha (Russia)
-Globalization.ci_saq = Samburu
-Globalization.ci_saq-KE = Samburu (Kenya)
-Globalization.ci_sbp = Sangu
-Globalization.ci_sbp-TZ = Sangu (Tanzania)
-Globalization.ci_sd = Sindhi
-Globalization.ci_sd-Arab = Sindhi (Arabic)
-Globalization.ci_sd-Arab-PK = Sindhi (Islamic Republic of Pakistan)
-Globalization.ci_se = Sami (Northern)
-Globalization.ci_se-FI = Sami, Northern (Finland)
-Globalization.ci_se-NO = Sami, Northern (Norway)
-Globalization.ci_se-SE = Sami, Northern (Sweden)
-Globalization.ci_seh = Sena
-Globalization.ci_seh-MZ = Sena (Mozambique)
-Globalization.ci_ses = Koyraboro Senni
-Globalization.ci_ses-ML = Koyraboro Senni (Mali)
-Globalization.ci_sg = Sango
-Globalization.ci_sg-CF = Sango (Central African Republic)
-Globalization.ci_shi = Tachelhit
-Globalization.ci_shi-Latn = Tachelhit (Latin)
-Globalization.ci_shi-Latn-MA = Tachelhit (Latin, Morocco)
-Globalization.ci_shi-Tfng = Tachelhit (Tifinagh)
-Globalization.ci_shi-Tfng-MA = Tachelhit (Tifinagh, Morocco)
-Globalization.ci_si = Sinhala
-Globalization.ci_si-LK = Sinhala (Sri Lanka)
-Globalization.ci_sk = Slovak
-Globalization.ci_sk-SK = Slovak (Slovakia)
-Globalization.ci_sl = Slovenian
-Globalization.ci_sl-SI = Slovenian (Slovenia)
-Globalization.ci_sma = Sami (Southern)
-Globalization.ci_sma-NO = Sami, Southern (Norway)
-Globalization.ci_sma-SE = Sami, Southern (Sweden)
-Globalization.ci_smj = Sami (Lule)
-Globalization.ci_smj-NO = Sami, Lule (Norway)
-Globalization.ci_smj-SE = Sami, Lule (Sweden)
-Globalization.ci_smn = Sami (Inari)
-Globalization.ci_smn-FI = Sami, Inari (Finland)
-Globalization.ci_sms = Sami (Skolt)
-Globalization.ci_sms-FI = Sami, Skolt (Finland)
-Globalization.ci_sn = Shona
-Globalization.ci_sn-Latn = Shona (Latin)
-Globalization.ci_sn-Latn-ZW = Shona (Latin, Zimbabwe)
-Globalization.ci_so = Somali
-Globalization.ci_so-DJ = Somali (Djibouti)
-Globalization.ci_so-ET = Somali (Ethiopia)
-Globalization.ci_so-KE = Somali (Kenya)
-Globalization.ci_so-SO = Somali (Somalia)
-Globalization.ci_sq = Albanian
-Globalization.ci_sq-AL = Albanian (Albania)
-Globalization.ci_sq-MK = Albanian (Macedonia, FYRO)
-Globalization.ci_sr = Serbian
-Globalization.ci_sr-Cyrl = Serbian (Cyrillic)
-Globalization.ci_sr-Cyrl-BA = Serbian (Cyrillic, Bosnia and Herzegovina)
-Globalization.ci_sr-Cyrl-CS = Serbian (Cyrillic, Serbia and Montenegro (Former))
-Globalization.ci_sr-Cyrl-ME = Serbian (Cyrillic, Montenegro)
-Globalization.ci_sr-Cyrl-RS = Serbian (Cyrillic, Serbia)
-Globalization.ci_sr-Latn = Serbian (Latin)
-Globalization.ci_sr-Latn-BA = Serbian (Latin, Bosnia and Herzegovina)
-Globalization.ci_sr-Latn-CS = Serbian (Latin, Serbia and Montenegro (Former))
-Globalization.ci_sr-Latn-ME = Serbian (Latin, Montenegro)
-Globalization.ci_sr-Latn-RS = Serbian (Latin, Serbia)
-Globalization.ci_ss = Swati
-Globalization.ci_ss-SZ = Swati (Swaziland)
-Globalization.ci_ss-ZA = Swati (South Africa)
-Globalization.ci_ssy = Saho
-Globalization.ci_ssy-ER = Saho (Eritrea)
-Globalization.ci_st = Southern Sotho
-Globalization.ci_st-LS = Sesotho (Lesotho)
-Globalization.ci_st-ZA = Southern Sotho (South Africa)
-Globalization.ci_sv = Swedish
-Globalization.ci_sv-AX = Swedish (Ã…land Islands)
-Globalization.ci_sv-FI = Swedish (Finland)
-Globalization.ci_sv-SE = Swedish (Sweden)
-Globalization.ci_sw = Kiswahili
-Globalization.ci_sw-KE = Kiswahili (Kenya)
-Globalization.ci_sw-TZ = Kiswahili (Tanzania)
-Globalization.ci_sw-UG = Kiswahili (Uganda)
-Globalization.ci_swc = Congo Swahili
-Globalization.ci_swc-CD = Congo Swahili (Congo DRC)
-Globalization.ci_syr = Syriac
-Globalization.ci_syr-SY = Syriac (Syria)
-Globalization.ci_ta = Tamil
-Globalization.ci_ta-IN = Tamil (India)
-Globalization.ci_ta-LK = Tamil (Sri Lanka)
-Globalization.ci_ta-MY = Tamil (Malaysia)
-Globalization.ci_ta-SG = Tamil (Singapore)
-Globalization.ci_te = Telugu
-Globalization.ci_te-IN = Telugu (India)
-Globalization.ci_teo = Teso
-Globalization.ci_teo-KE = Teso (Kenya)
-Globalization.ci_teo-UG = Teso (Uganda)
-Globalization.ci_tg = Tajik
-Globalization.ci_tg-Cyrl = Tajik (Cyrillic)
-Globalization.ci_tg-Cyrl-TJ = Tajik (Cyrillic, Tajikistan)
-Globalization.ci_th = Thai
-Globalization.ci_th-TH = Thai (Thailand)
-Globalization.ci_ti = Tigrinya
-Globalization.ci_ti-ER = Tigrinya (Eritrea)
-Globalization.ci_ti-ET = Tigrinya (Ethiopia)
-Globalization.ci_tig = Tigre
-Globalization.ci_tig-ER = Tigre (Eritrea)
-Globalization.ci_tk = Turkmen
-Globalization.ci_tk-TM = Turkmen (Turkmenistan)
-Globalization.ci_tn = Setswana
-Globalization.ci_tn-BW = Setswana (Botswana)
-Globalization.ci_tn-ZA = Setswana (South Africa)
-Globalization.ci_to = Tongan
-Globalization.ci_to-TO = Tongan (Tonga)
-Globalization.ci_tr = Turkish
-Globalization.ci_tr-CY = Turkish (Cyprus)
-Globalization.ci_tr-TR = Turkish (Turkey)
-Globalization.ci_ts = Tsonga
-Globalization.ci_ts-ZA = Tsonga (South Africa)
-Globalization.ci_tt = Tatar
-Globalization.ci_tt-RU = Tatar (Russia)
-Globalization.ci_twq = Tasawaq
-Globalization.ci_twq-NE = Tasawaq (Niger)
-Globalization.ci_tzm = Tamazight
-Globalization.ci_tzm-Latn = Tamazight (Latin)
-Globalization.ci_tzm-Latn-DZ = Tamazight (Latin, Algeria)
-Globalization.ci_tzm-Latn-MA = Central Atlas Tamazight (Latin, Morocco)
-Globalization.ci_tzm-Tfng = Tamazight (Tifinagh)
-Globalization.ci_tzm-Tfng-MA = Central Atlas Tamazight (Tifinagh, Morocco)
-Globalization.ci_ug = Uyghur
-Globalization.ci_ug-CN = Uyghur (PRC)
-Globalization.ci_uk = Ukrainian
-Globalization.ci_uk-UA = Ukrainian (Ukraine)
-Globalization.ci_ur = Urdu
-Globalization.ci_ur-IN = Urdu (India)
-Globalization.ci_ur-PK = Urdu (Islamic Republic of Pakistan)
-Globalization.ci_uz = Uzbek
-Globalization.ci_uz-Arab = Uzbek (Perso-Arabic)
-Globalization.ci_uz-Arab-AF = Uzbek (Perso-Arabic, Afghanistan)
-Globalization.ci_uz-Cyrl = Uzbek (Cyrillic)
-Globalization.ci_uz-Cyrl-UZ = Uzbek (Cyrillic, Uzbekistan)
-Globalization.ci_uz-Latn = Uzbek (Latin)
-Globalization.ci_uz-Latn-UZ = Uzbek (Latin, Uzbekistan)
-Globalization.ci_vai = Vai
-Globalization.ci_vai-Latn = Vai (Latin)
-Globalization.ci_vai-Latn-LR = Vai (Latin, Liberia)
-Globalization.ci_vai-Vaii = Vai (Vai)
-Globalization.ci_vai-Vaii-LR = Vai (Vai, Liberia)
-Globalization.ci_ve = Venda
-Globalization.ci_ve-ZA = Venda (South Africa)
-Globalization.ci_vi = Vietnamese
-Globalization.ci_vi-VN = Vietnamese (Vietnam)
-Globalization.ci_vo = Volapük
-Globalization.ci_vo-001 = Volapük (World)
-Globalization.ci_vun = Vunjo
-Globalization.ci_vun-TZ = Vunjo (Tanzania)
-Globalization.ci_wae = Walser
-Globalization.ci_wae-CH = Walser (Switzerland)
-Globalization.ci_wal = Wolaytta
-Globalization.ci_wal-ET = Wolaytta (Ethiopia)
-Globalization.ci_wo = Wolof
-Globalization.ci_wo-SN = Wolof (Senegal)
-Globalization.ci_x-IV = Invariant Language (Invariant Country)
-Globalization.ci_x-IV_mathan = Invariant Language (Invariant Country)
-Globalization.ci_xh = isiXhosa
-Globalization.ci_xh-ZA = isiXhosa (South Africa)
-Globalization.ci_xog = Soga
-Globalization.ci_xog-UG = Soga (Uganda)
-Globalization.ci_yav = Yangben
-Globalization.ci_yav-CM = Yangben (Cameroon)
-Globalization.ci_yi = Yiddish
-Globalization.ci_yi-001 = Yiddish (World)
-Globalization.ci_yo = Yoruba
-Globalization.ci_yo-BJ = Yoruba (Benin)
-Globalization.ci_yo-NG = Yoruba (Nigeria)
-Globalization.ci_zgh = Standard Moroccan Tamazight
-Globalization.ci_zgh-Tfng = Standard Moroccan Tamazight (Tifinagh)
-Globalization.ci_zgh-Tfng-MA = Standard Moroccan Tamazight (Tifinagh, Morocco)
-Globalization.ci_zh = Chinese
-Globalization.ci_zh-CHS = Chinese (Simplified) Legacy
-Globalization.ci_zh-CHT = Chinese (Traditional) Legacy
-Globalization.ci_zh-CN = Chinese (Simplified, PRC)
-Globalization.ci_zh-CN_stroke = Chinese (Simplified, PRC)
-Globalization.ci_zh-Hans = Chinese (Simplified)
-Globalization.ci_zh-Hant = Chinese (Traditional)
-Globalization.ci_zh-HK = Chinese (Traditional, Hong Kong S.A.R.)
-Globalization.ci_zh-HK_radstr = Chinese (Traditional, Hong Kong S.A.R.)
-Globalization.ci_zh-MO = Chinese (Traditional, Macao S.A.R.)
-Globalization.ci_zh-MO_radstr = Chinese (Traditional, Macao S.A.R.)
-Globalization.ci_zh-MO_stroke = Chinese (Traditional, Macao S.A.R.)
-Globalization.ci_zh-SG = Chinese (Simplified, Singapore)
-Globalization.ci_zh-SG_stroke = Chinese (Simplified, Singapore)
-Globalization.ci_zh-TW = Chinese (Traditional, Taiwan)
-Globalization.ci_zh-TW_pronun = Chinese (Traditional, Taiwan)
-Globalization.ci_zh-TW_radstr = Chinese (Traditional, Taiwan)
-Globalization.ci_zu = isiZulu
-Globalization.ci_zu-ZA = isiZulu (South Africa)
-;------------------
-;
-;Total items: 129
-;
-Globalization.ri_029 = Caribbean
-Globalization.ri_AE = U.A.E.
-Globalization.ri_AF = Afghanistan
-Globalization.ri_AL = Albania
-Globalization.ri_AM = Armenia
-Globalization.ri_AR = Argentina
-Globalization.ri_AT = Austria
-Globalization.ri_AU = Australia
-Globalization.ri_AZ = Azerbaijan
-Globalization.ri_BA = Bosnia and Herzegovina
-Globalization.ri_BD = Bangladesh
-Globalization.ri_BE = Belgium
-Globalization.ri_BG = Bulgaria
-Globalization.ri_BH = Bahrain
-Globalization.ri_BN = Brunei Darussalam
-Globalization.ri_BO = Bolivia
-Globalization.ri_BR = Brazil
-Globalization.ri_BY = Belarus
-Globalization.ri_BZ = Belize
-Globalization.ri_CA = Canada
-Globalization.ri_CH = Switzerland
-Globalization.ri_CL = Chile
-Globalization.ri_CN = People's Republic of China
-Globalization.ri_CO = Colombia
-Globalization.ri_CR = Costa Rica
-Globalization.ri_CS = Serbia and Montenegro (Former)
-Globalization.ri_CZ = Czech Republic
-Globalization.ri_DE = Germany
-Globalization.ri_DK = Denmark
-Globalization.ri_DO = Dominican Republic
-Globalization.ri_DZ = Algeria
-Globalization.ri_EC = Ecuador
-Globalization.ri_EE = Estonia
-Globalization.ri_EG = Egypt
-Globalization.ri_ER = Eritrea
-Globalization.ri_ES = Spain
-Globalization.ri_ET = Ethiopia
-Globalization.ri_FI = Finland
-Globalization.ri_FO = Faroe Islands
-Globalization.ri_FR = France
-Globalization.ri_GB = United Kingdom
-Globalization.ri_GE = Georgia
-Globalization.ri_GL = Greenland
-Globalization.ri_GR = Greece
-Globalization.ri_GT = Guatemala
-Globalization.ri_HK = Hong Kong S.A.R.
-Globalization.ri_HN = Honduras
-Globalization.ri_HR = Croatia
-Globalization.ri_HU = Hungary
-Globalization.ri_ID = Indonesia
-Globalization.ri_IE = Ireland
-Globalization.ri_IL = Israel
-Globalization.ri_IN = India
-Globalization.ri_IQ = Iraq
-Globalization.ri_IR = Iran
-Globalization.ri_IS = Iceland
-Globalization.ri_IT = Italy
-Globalization.ri_IV = Invariant Country
-Globalization.ri_JM = Jamaica
-Globalization.ri_JO = Jordan
-Globalization.ri_JP = Japan
-Globalization.ri_KE = Kenya
-Globalization.ri_KG = Kyrgyzstan
-Globalization.ri_KH = Cambodia
-Globalization.ri_KR = Korea
-Globalization.ri_KW = Kuwait
-Globalization.ri_KZ = Kazakhstan
-Globalization.ri_LA = Lao P.D.R.
-Globalization.ri_LB = Lebanon
-Globalization.ri_LI = Liechtenstein
-Globalization.ri_LK = Sri Lanka
-Globalization.ri_LT = Lithuania
-Globalization.ri_LU = Luxembourg
-Globalization.ri_LV = Latvia
-Globalization.ri_LY = Libya
-Globalization.ri_MA = Morocco
-Globalization.ri_MC = Principality of Monaco
-Globalization.ri_ME = Montenegro
-Globalization.ri_MK = Macedonia (FYROM)
-Globalization.ri_MN = Mongolia
-Globalization.ri_MO = Macao S.A.R.
-Globalization.ri_MT = Malta
-Globalization.ri_MV = Maldives
-Globalization.ri_MX = Mexico
-Globalization.ri_MY = Malaysia
-Globalization.ri_NG = Nigeria
-Globalization.ri_NI = Nicaragua
-Globalization.ri_NL = Netherlands
-Globalization.ri_NO = Norway
-Globalization.ri_NP = Nepal
-Globalization.ri_NZ = New Zealand
-Globalization.ri_OM = Oman
-Globalization.ri_PA = Panama
-Globalization.ri_PE = Peru
-Globalization.ri_PH = Philippines
-Globalization.ri_PK = Islamic Republic of Pakistan
-Globalization.ri_PL = Poland
-Globalization.ri_PR = Puerto Rico
-Globalization.ri_PT = Portugal
-Globalization.ri_PY = Paraguay
-Globalization.ri_QA = Qatar
-Globalization.ri_RO = Romania
-Globalization.ri_RS = Serbia
-Globalization.ri_RU = Russia
-Globalization.ri_RW = Rwanda
-Globalization.ri_SA = Saudi Arabia
-Globalization.ri_SE = Sweden
-Globalization.ri_SG = Singapore
-Globalization.ri_SI = Slovenia
-Globalization.ri_SK = Slovakia
-Globalization.ri_SN = Senegal
-Globalization.ri_SV = El Salvador
-Globalization.ri_SY = Syria
-Globalization.ri_TH = Thailand
-Globalization.ri_TJ = Tajikistan
-Globalization.ri_TM = Turkmenistan
-Globalization.ri_TN = Tunisia
-Globalization.ri_TR = Turkey
-Globalization.ri_TT = Trinidad and Tobago
-Globalization.ri_TW = Taiwan
-Globalization.ri_UA = Ukraine
-Globalization.ri_US = United States
-Globalization.ri_UY = Uruguay
-Globalization.ri_UZ = Uzbekistan
-Globalization.ri_VE = Bolivarian Republic of Venezuela
-Globalization.ri_VN = Vietnam
-Globalization.ri_YE = Yemen
-Globalization.ri_ZA = South Africa
-Globalization.ri_ZW = Zimbabwe
-#endif //!FEATURE_CORECLR
-
;------------------
; Encoding names:
;
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
-//
-
-namespace System {
- using System.Runtime.CompilerServices;
-
+namespace System
+{
public delegate void Action<in T>(T obj);
// Action/Func delegates first shipped with .NET Framework 3.5 in System.Core.dll as part of LINQ
// These were type forwarded to mscorlib.dll in .NET Framework 4.0 and in Silverlight 5.0
-
-#if !FEATURE_CORECLR
- [TypeForwardedFrom("System.Core, Version=3.5.0.0, Culture=Neutral, PublicKeyToken=b77a5c561934e089")]
-#endif
public delegate void Action();
-
-#if !FEATURE_CORECLR
- [TypeForwardedFrom("System.Core, Version=3.5.0.0, Culture=Neutral, PublicKeyToken=b77a5c561934e089")]
-#endif
public delegate void Action<in T1,in T2>(T1 arg1, T2 arg2);
-
-#if !FEATURE_CORECLR
- [TypeForwardedFrom("System.Core, Version=3.5.0.0, Culture=Neutral, PublicKeyToken=b77a5c561934e089")]
-#endif
public delegate void Action<in T1,in T2,in T3>(T1 arg1, T2 arg2, T3 arg3);
-
-#if !FEATURE_CORECLR
- [TypeForwardedFrom("System.Core, Version=3.5.0.0, Culture=Neutral, PublicKeyToken=b77a5c561934e089")]
-#endif
public delegate void Action<in T1,in T2,in T3,in T4>(T1 arg1, T2 arg2, T3 arg3, T4 arg4);
-#if !FEATURE_CORECLR
- [TypeForwardedFrom("System.Core, Version=3.5.0.0, Culture=Neutral, PublicKeyToken=b77a5c561934e089")]
-#endif
public delegate TResult Func<out TResult>();
-
-#if !FEATURE_CORECLR
- [TypeForwardedFrom("System.Core, Version=3.5.0.0, Culture=Neutral, PublicKeyToken=b77a5c561934e089")]
-#endif
public delegate TResult Func<in T, out TResult>(T arg);
-
-#if !FEATURE_CORECLR
- [TypeForwardedFrom("System.Core, Version=3.5.0.0, Culture=Neutral, PublicKeyToken=b77a5c561934e089")]
-#endif
public delegate TResult Func<in T1, in T2, out TResult>(T1 arg1, T2 arg2);
-
-#if !FEATURE_CORECLR
- [TypeForwardedFrom("System.Core, Version=3.5.0.0, Culture=Neutral, PublicKeyToken=b77a5c561934e089")]
-#endif
public delegate TResult Func<in T1, in T2, in T3, out TResult>(T1 arg1, T2 arg2, T3 arg3);
-
-#if !FEATURE_CORECLR
- [TypeForwardedFrom("System.Core, Version=3.5.0.0, Culture=Neutral, PublicKeyToken=b77a5c561934e089")]
-#endif
public delegate TResult Func<in T1, in T2, in T3, in T4, out TResult>(T1 arg1, T2 arg2, T3 arg3, T4 arg4);
-
public delegate void Action<in T1,in T2,in T3,in T4,in T5>(T1 arg1, T2 arg2, T3 arg3, T4 arg4, T5 arg5);
public delegate void Action<in T1,in T2,in T3,in T4,in T5,in T6>(T1 arg1, T2 arg2, T3 arg3, T4 arg4, T5 arg5, T6 arg6);
public delegate void Action<in T1,in T2,in T3,in T4,in T5,in T6,in T7>(T1 arg1, T2 arg2, T3 arg3, T4 arg4, T5 arg5, T6 arg6, T7 arg7);
using System;
using System.Reflection;
using System.Runtime.Remoting;
-#if FEATURE_REMOTING
- using System.Runtime.Remoting.Activation;
- using Message = System.Runtime.Remoting.Messaging.Message;
-#endif
using System.Security;
using CultureInfo = System.Globalization.CultureInfo;
using Evidence = System.Security.Policy.Evidence;
// Only statics, does not need to be marked with the serializable attribute
[ClassInterface(ClassInterfaceType.None)]
[ComDefaultInterface(typeof(_Activator))]
-[System.Runtime.InteropServices.ComVisible(true)]
+ [System.Runtime.InteropServices.ComVisible(true)]
public sealed class Activator : _Activator
{
internal const int LookupMask = 0x000000FF;
return CreateInstance(type, bindingAttr, binder, args, culture, null);
}
- [System.Security.SecuritySafeCritical] // auto-generated
[MethodImplAttribute(MethodImplOptions.NoInlining)] // Methods containing StackCrawlMark local var has to be marked non-inlineable
static public Object CreateInstance(Type type,
BindingFlags bindingAttr,
bindingAttr |= Activator.ConstructorDefault;
if (activationAttributes != null && activationAttributes.Length > 0){
- // If type does not derive from MBR
- // throw notsupportedexception
-#if FEATURE_REMOTING
- if(type.IsMarshalByRef){
- // The fix below is preventative.
- //
- if(!(type.IsContextful)){
- if(activationAttributes.Length > 1 || !(activationAttributes[0] is UrlAttribute))
- throw new NotSupportedException(Environment.GetResourceString("NotSupported_NonUrlAttrOnMBR"));
- }
- }
- else
- throw new NotSupportedException(Environment.GetResourceString("NotSupported_ActivAttrOnNonMBR" ));
-#else
- throw new PlatformNotSupportedException(Environment.GetResourceString("NotSupported_ActivAttr" ));
-#endif
+ throw new PlatformNotSupportedException(Environment.GetResourceString("NotSupported_ActivAttr" ));
}
RuntimeType rt = type.UnderlyingSystemType as RuntimeType;
* types to be created remotely without having to load the type locally.
*/
- [System.Security.SecuritySafeCritical] // auto-generated
[MethodImplAttribute(MethodImplOptions.NoInlining)] // Methods containing StackCrawlMark local var has to be marked non-inlineable
static public ObjectHandle CreateInstance(String assemblyName,
String typeName)
ref stackMark);
}
- [System.Security.SecuritySafeCritical] // auto-generated
[MethodImplAttribute(MethodImplOptions.NoInlining)] // Methods containing StackCrawlMark local var has to be marked non-inlineable
static public ObjectHandle CreateInstance(String assemblyName,
String typeName,
activationAttributes);
}
- [System.Security.SecuritySafeCritical] // auto-generated
[MethodImplAttribute(MethodImplOptions.NoInlining)] // Methods containing StackCrawlMark local var has to be marked non-inlineable
[Obsolete("Methods which use evidence to sandbox are obsolete and will be removed in a future release of the .NET Framework. Please use an overload of CreateInstance which does not take an Evidence parameter. See http://go.microsoft.com/fwlink/?LinkID=155570 for more information.")]
static public ObjectHandle CreateInstance(String assemblyName,
ref stackMark);
}
- [SecuritySafeCritical]
[MethodImplAttribute(MethodImplOptions.NoInlining)] // Methods containing StackCrawlMark local var has to be marked non-inlineable
public static ObjectHandle CreateInstance(string assemblyName,
string typeName,
ref stackMark);
}
- [System.Security.SecurityCritical] // auto-generated
static internal ObjectHandle CreateInstance(String assemblyString,
String typeName,
bool ignoreCase,
Evidence securityInfo,
ref StackCrawlMark stackMark)
{
-#if FEATURE_CAS_POLICY
- if (securityInfo != null && !AppDomain.CurrentDomain.IsLegacyCasPolicyEnabled)
- {
- throw new NotSupportedException(Environment.GetResourceString("NotSupported_RequiresCasPolicyImplicit"));
- }
-#endif // FEATURE_CAS_POLICY
-
Type type = null;
Assembly assembly = null;
if (assemblyString == null) {
Evidence securityInfo)
{
-#if FEATURE_CAS_POLICY
- if (securityInfo != null && !AppDomain.CurrentDomain.IsLegacyCasPolicyEnabled)
- {
- throw new NotSupportedException(Environment.GetResourceString("NotSupported_RequiresCasPolicyImplicit"));
- }
-#endif // FEATURE_CAS_POLICY
-
return CreateInstanceFromInternal(assemblyFile,
typeName,
ignoreCase,
Object[] activationAttributes,
Evidence securityInfo)
{
-#if FEATURE_CAS_POLICY
- Contract.Assert(AppDomain.CurrentDomain.IsLegacyCasPolicyEnabled || securityInfo == null);
-#endif // FEATURE_CAS_POLICY
-
#pragma warning disable 618
Assembly assembly = Assembly.LoadFrom(assemblyFile, securityInfo);
#pragma warning restore 618
// to pass the security checks when activating the type.
//
- [System.Security.SecurityCritical] // auto-generated_required
public static ObjectHandle CreateInstance (AppDomain domain, string assemblyName, string typeName) {
if (domain == null)
throw new ArgumentNullException(nameof(domain));
return domain.InternalCreateInstanceWithNoSecurity(assemblyName, typeName);
}
- [System.Security.SecurityCritical] // auto-generated_required
[Obsolete("Methods which use evidence to sandbox are obsolete and will be removed in a future release of the .NET Framework. Please use an overload of CreateInstance which does not take an Evidence parameter. See http://go.microsoft.com/fwlink/?LinkID=155570 for more information.")]
public static ObjectHandle CreateInstance (AppDomain domain,
string assemblyName,
throw new ArgumentNullException(nameof(domain));
Contract.EndContractBlock();
-#if FEATURE_CAS_POLICY
- if (securityAttributes != null && !AppDomain.CurrentDomain.IsLegacyCasPolicyEnabled)
- {
- throw new NotSupportedException(Environment.GetResourceString("NotSupported_RequiresCasPolicyImplicit"));
- }
-#endif // FEATURE_CAS_POLICY
-
return domain.InternalCreateInstanceWithNoSecurity(assemblyName, typeName, ignoreCase, bindingAttr, binder, args, culture, activationAttributes, securityAttributes);
}
- [SecurityCritical]
public static ObjectHandle CreateInstance(AppDomain domain,
string assemblyName,
string typeName,
// to pass the security checks when activating the type.
//
- [System.Security.SecurityCritical] // auto-generated_required
public static ObjectHandle CreateInstanceFrom (AppDomain domain, string assemblyFile, string typeName) {
if (domain == null)
throw new ArgumentNullException(nameof(domain));
return domain.InternalCreateInstanceFromWithNoSecurity(assemblyFile, typeName);
}
- [System.Security.SecurityCritical] // auto-generated_required
[Obsolete("Methods which use Evidence to sandbox are obsolete and will be removed in a future release of the .NET Framework. Please use an overload of CreateInstanceFrom which does not take an Evidence parameter. See http://go.microsoft.com/fwlink/?LinkID=155570 for more information.")]
public static ObjectHandle CreateInstanceFrom (AppDomain domain,
string assemblyFile,
throw new ArgumentNullException(nameof(domain));
Contract.EndContractBlock();
-#if FEATURE_CAS_POLICY
- if (securityAttributes != null && !AppDomain.CurrentDomain.IsLegacyCasPolicyEnabled)
- {
- throw new NotSupportedException(Environment.GetResourceString("NotSupported_RequiresCasPolicyImplicit"));
- }
-#endif // FEATURE_CAS_POLICY
-
return domain.InternalCreateInstanceFromWithNoSecurity(assemblyFile, typeName, ignoreCase, bindingAttr, binder, args, culture, activationAttributes, securityAttributes);
}
- [SecurityCritical]
public static ObjectHandle CreateInstanceFrom(AppDomain domain,
string assemblyFile,
string typeName,
}
}
-#if FEATURE_REMOTING
- // This method is a helper method and delegates to the remoting
- // services to do the actual work.
- [System.Security.SecurityCritical] // auto-generated_required
- static public Object GetObject(Type type, String url)
- {
- return GetObject(type, url, null);
- }
-
- // This method is a helper method and delegates to the remoting
- // services to do the actual work.
- [System.Security.SecurityCritical] // auto-generated_required
- static public Object GetObject(Type type, String url, Object state)
- {
- if (type == null)
- throw new ArgumentNullException(nameof(type));
- Contract.EndContractBlock();
- return RemotingServices.Connect(type, url, state);
- }
-#endif
-
[System.Diagnostics.Conditional("_DEBUG")]
private static void Log(bool test, string title, string success, string failure)
{
-#if FEATURE_REMOTING
- if(test)
- BCLDebug.Trace("REMOTE", "{0}{1}", title, success);
- else
- BCLDebug.Trace("REMOTE", "{0}{1}", title, failure);
-#endif
}
-
+
void _Activator.GetTypeInfoCount(out uint pcTInfo)
{
throw new NotImplementedException();
/// contains contextual information about the source or destination. </param>
/// <exception cref="T:System.ArgumentNullException">The <paramref name="info"/> argument is null.</exception>
/// <exception cref="T:System.Runtime.Serialization.SerializationException">The exception could not be deserialized correctly.</exception>
- [SecurityCritical]
protected AggregateException(SerializationInfo info, StreamingContext context) :
base(info, context)
{
/// <param name="context">The <see cref="T:System.Runtime.Serialization.StreamingContext"/> that
/// contains contextual information about the source or destination. </param>
/// <exception cref="T:System.ArgumentNullException">The <paramref name="info"/> argument is null.</exception>
- [SecurityCritical]
public override void GetObjectData(SerializationInfo info, StreamingContext context)
{
if (info == null)
public static string BaseDirectory
{
-#if FEATURE_CORECLR
- [System.Security.SecuritySafeCritical]
-#endif
get
{
// The value of APP_CONTEXT_BASE_DIRECTORY key has to be a string and it is not allowed to be any other type.
}
}
-#if FEATURE_CORECLR
- [System.Security.SecuritySafeCritical]
-#endif
public static object GetData(string name)
{
return AppDomain.CurrentDomain.GetData(name);
}
- [System.Security.SecuritySafeCritical]
public static void SetData(string name, object data)
{
AppDomain.CurrentDomain.SetData(name, data);
public static event UnhandledExceptionEventHandler UnhandledException
{
- [System.Security.SecurityCritical]
add
{
AppDomain.CurrentDomain.UnhandledException += value;
}
- [System.Security.SecurityCritical]
remove
{
AppDomain.CurrentDomain.UnhandledException -= value;
public static event System.EventHandler<System.Runtime.ExceptionServices.FirstChanceExceptionEventArgs> FirstChanceException
{
- [System.Security.SecurityCritical]
add
{
AppDomain.CurrentDomain.FirstChanceException += value;
}
- [System.Security.SecurityCritical]
remove
{
AppDomain.CurrentDomain.FirstChanceException -= value;
public static event System.EventHandler ProcessExit
{
- [System.Security.SecurityCritical]
add
{
AppDomain.CurrentDomain.ProcessExit += value;
}
- [System.Security.SecurityCritical]
remove
{
AppDomain.CurrentDomain.ProcessExit -= value;
if (!TryParseFrameworkName(targetFrameworkMoniker, out identifier, out version, out profile))
{
-#if FEATURE_CORECLR
// If we can't parse the TFM or we don't have a TFM, default to latest behavior for all
// switches (ie. all of them false).
// If we want to use the latest behavior it is enough to set the value of the switch to string.Empty.
// identifier we are simply saying -- don't turn on any switches, and we are going to get the latest
// behavior for all the switches
identifier = string.Empty;
-#else
- identifier = ".NETFramework";
- version = 40000;
- profile = string.Empty;
-#endif
}
}
using System.Text;
using System.Runtime.ConstrainedExecution;
using System.Runtime.Versioning;
+ using System.Diagnostics;
using System.Diagnostics.Contracts;
#if FEATURE_EXCEPTION_NOTIFICATIONS
using System.Runtime.ExceptionServices;
}
}
- [System.Security.SecurityCritical] // auto-generated
[Serializable]
[ComVisible(true)]
public delegate Assembly ResolveEventHandler(Object sender, ResolveEventArgs args);
Info = itemInfo.ToArray();
}
- [System.Security.SecuritySafeCritical] // auto-generated
internal AppDomainInitializer Unwrap()
{
if (Info==null)
// Domain security information
// These fields initialized from the other side only. (NOTE: order
// of these fields cannot be changed without changing the layout in
- // the EE)
+ // the EE- AppDomainBaseObject in this case)
- [System.Security.SecurityCritical] // auto-generated
private AppDomainManager _domainManager;
private Dictionary<String, Object[]> _LocalStore;
private AppDomainSetup _FusionStore;
[method: System.Security.SecurityCritical]
public event AssemblyLoadEventHandler AssemblyLoad;
- [System.Security.SecurityCritical]
private ResolveEventHandler _TypeResolve;
public event ResolveEventHandler TypeResolve
{
- [System.Security.SecurityCritical]
add
{
lock (this)
}
}
- [System.Security.SecurityCritical]
remove
{
lock (this)
}
}
- [System.Security.SecurityCritical]
private ResolveEventHandler _ResourceResolve;
public event ResolveEventHandler ResourceResolve
{
- [System.Security.SecurityCritical]
add
{
lock (this)
}
}
- [System.Security.SecurityCritical]
remove
{
lock (this)
}
}
- [System.Security.SecurityCritical]
private ResolveEventHandler _AssemblyResolve;
public event ResolveEventHandler AssemblyResolve
{
- [System.Security.SecurityCritical]
add
{
lock (this)
}
}
- [System.Security.SecurityCritical]
remove
{
lock (this)
private ApplicationTrust _applicationTrust;
private EventHandler _processExit;
- [System.Security.SecurityCritical]
private EventHandler _domainUnload;
- [System.Security.SecurityCritical] // auto-generated
private UnhandledExceptionEventHandler _unhandledException;
// The compat flags are set at domain creation time to indicate that the given breaking
private static APPX_FLAGS Flags
{
- [SecuritySafeCritical]
get
{
if (s_flags == 0)
s_flags = nGetAppXFlags();
- Contract.Assert(s_flags != 0);
+ Debug.Assert(s_flags != 0);
return s_flags;
}
}
internal static bool ProfileAPICheck
{
- [SecuritySafeCritical]
get
{
return (Flags & APPX_FLAGS.APPX_FLAGS_API_CHECK) != 0;
internal static bool IsAppXNGen
{
- [SecuritySafeCritical]
get
{
return (Flags & APPX_FLAGS.APPX_FLAGS_APPX_NGEN) != 0;
#endif // FEATURE_APPX
[DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
- [SecurityCritical]
[SuppressUnmanagedCodeSecurity]
[return: MarshalAs(UnmanagedType.Bool)]
private static extern bool DisableFusionUpdatesFromADManager(AppDomainHandle domain);
#if FEATURE_APPX
[DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
- [SecurityCritical]
[SuppressUnmanagedCodeSecurity]
[return: MarshalAs(UnmanagedType.I4)]
private static extern APPX_FLAGS nGetAppXFlags();
#endif
[DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
- [SecurityCritical]
[SuppressUnmanagedCodeSecurity]
private static extern void GetAppDomainManagerType(AppDomainHandle domain,
StringHandleOnStack retAssembly,
StringHandleOnStack retType);
[DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
- [SecurityCritical]
[SuppressUnmanagedCodeSecurity]
private static extern void SetAppDomainManagerType(AppDomainHandle domain,
string assembly,
string type);
- [System.Security.SecurityCritical] // auto-generated
[MethodImplAttribute(MethodImplOptions.InternalCall)]
private static extern void nSetHostSecurityManagerFlags (HostSecurityManagerOptions flags);
- [SecurityCritical]
[SuppressUnmanagedCodeSecurity]
[DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
private static extern void SetSecurityHomogeneousFlag(AppDomainHandle domain,
/// If this AppDomain is configured to have an AppDomain manager then create the instance of it.
/// This method is also called from the VM to create the domain manager in the default domain.
/// </summary>
- [SecuritySafeCritical]
private void CreateAppDomainManager()
{
- Contract.Assert(_domainManager == null, "_domainManager == null");
+ Debug.Assert(_domainManager == null, "_domainManager == null");
AppDomainSetup adSetup = FusionStore;
#if FEATURE_VERSIONING
// for perf, we don't intialize the _compatFlags dictionary when we don't need to. However, we do need to make a
// note that we've run this method, because IsCompatibilityFlagsSet needs to return different values for the
// case where the compat flags have been setup.
- Contract.Assert(!_compatFlagsInitialized);
+ Debug.Assert(!_compatFlagsInitialized);
_compatFlagsInitialized = true;
CompatibilitySwitches.InitializeSwitches();
// either by a host in native, a host in managed using an AppDomainSetup, or by the
// TargetFrameworkAttribute on the executable (VS emits its target framework moniker using this
// attribute starting in version 4).
- [SecuritySafeCritical]
internal String GetTargetFrameworkName()
{
String targetFrameworkName = _FusionStore.TargetFrameworkName;
TargetFrameworkAttribute[] attrs = (TargetFrameworkAttribute[])assembly.GetCustomAttributes(typeof(TargetFrameworkAttribute));
if (attrs != null && attrs.Length > 0)
{
- Contract.Assert(attrs.Length == 1);
+ Debug.Assert(attrs.Length == 1);
targetFrameworkName = attrs[0].FrameworkName;
_FusionStore.TargetFrameworkName = targetFrameworkName;
}
/// <summary>
/// Returns the setting of the corresponding compatibility config switch (see CreateAppDomainManager for the impact).
/// </summary>
- [SecuritySafeCritical]
internal bool DisableFusionUpdatesFromADManager()
{
return DisableFusionUpdatesFromADManager(GetNativeHandle());
/// <summary>
/// Returns whether the current AppDomain follows the AppX rules.
/// </summary>
- [SecuritySafeCritical]
[Pure]
internal static bool IsAppXModel()
{
/// <summary>
/// Returns the setting of the AppXDevMode config switch.
/// </summary>
- [SecuritySafeCritical]
[Pure]
internal static bool IsAppXDesignMode()
{
/// <summary>
/// Checks (and throws on failure) if the domain supports Assembly.LoadFrom.
/// </summary>
- [SecuritySafeCritical]
[Pure]
internal static void CheckLoadFromSupported()
{
/// <summary>
/// Checks (and throws on failure) if the domain supports Assembly.LoadFile.
/// </summary>
- [SecuritySafeCritical]
[Pure]
internal static void CheckLoadFileSupported()
{
/// <summary>
/// Checks (and throws on failure) if the domain supports Assembly.ReflectionOnlyLoad.
/// </summary>
- [SecuritySafeCritical]
[Pure]
internal static void CheckReflectionOnlyLoadSupported()
{
/// <summary>
/// Checks (and throws on failure) if the domain supports Assembly.LoadWithPartialName.
/// </summary>
- [SecuritySafeCritical]
[Pure]
internal static void CheckLoadWithPartialNameSupported(StackCrawlMark stackMark)
{
/// <summary>
/// Checks (and throws on failure) if the domain supports DefinePInvokeMethod.
/// </summary>
- [SecuritySafeCritical]
[Pure]
internal static void CheckDefinePInvokeSupported()
{
/// <summary>
/// Checks (and throws on failure) if the domain supports Assembly.Load(byte[] ...).
/// </summary>
- [SecuritySafeCritical]
[Pure]
internal static void CheckLoadByteArraySupported()
{
/// <summary>
/// Checks (and throws on failure) if the domain supports AppDomain.CreateDomain.
/// </summary>
- [SecuritySafeCritical]
[Pure]
internal static void CheckCreateDomainSupported()
{
/// <summary>
/// Get the name of the assembly and type that act as the AppDomainManager for this domain
/// </summary>
- [SecuritySafeCritical]
internal void GetAppDomainManagerType(out string assembly, out string type)
{
// We can't just use our parameters because we need to ensure that the strings used for hte QCall
/// <summary>
/// Set the assembly and type which act as the AppDomainManager for this domain
/// </summary>
- [SecuritySafeCritical]
private void SetAppDomainManagerType(string assembly, string type)
{
- Contract.Assert(assembly != null, "assembly != null");
- Contract.Assert(type != null, "type != null");
+ Debug.Assert(assembly != null, "assembly != null");
+ Debug.Assert(type != null, "type != null");
SetAppDomainManagerType(GetNativeHandle(), assembly, type);
}
/// <summary>
/// Called for every AppDomain (including the default domain) to initialize the security of the AppDomain)
/// </summary>
- [SecurityCritical]
private void InitializeDomainSecurity(Evidence providedSecurityInfo,
Evidence creatorsSecurityInfo,
bool generateDefaultEvidence,
publishAppDomain);
}
- [System.Security.SecurityCritical] // auto-generated
private void SetupDomainSecurityForHomogeneousDomain(ApplicationTrust appTrust,
bool runtimeSuppliedHomogenousGrantSet)
{
}
public AppDomainManager DomainManager {
- [System.Security.SecurityCritical] // auto-generated_required
get {
return _domainManager;
}
_packageGraphFilePaths = packageGraphFilePaths;
}
- [System.Security.SecurityCritical]
public void ResolveNamespace(
object sender,
System.Runtime.InteropServices.WindowsRuntime.NamespaceResolveEventArgs args)
}
// Called only by native function code:ValidateWorker
- [System.Security.SecuritySafeCritical]
private void EnableResolveAssembliesForIntrospection(string verifiedFileDirectory)
{
CurrentDomain.ReflectionOnlyAssemblyResolve += new ResolveEventHandler(ResolveAssemblyForIntrospection);
* to have a strong name and a hash will be computed when the assembly
* is saved.
**********************************************/
- [System.Security.SecuritySafeCritical] // auto-generated
[MethodImplAttribute(MethodImplOptions.NoInlining)] // Methods containing StackCrawlMark local var has to be marked non-inlineable
public AssemblyBuilder DefineDynamicAssembly(
AssemblyName name,
null, null, null, null, ref stackMark, null, SecurityContextSource.CurrentAssembly);
}
- [System.Security.SecuritySafeCritical] // auto-generated
[MethodImplAttribute(MethodImplOptions.NoInlining)] // Methods containing StackCrawlMark local var has to be marked non-inlineable
public AssemblyBuilder DefineDynamicAssembly(
AssemblyName name,
}
[MethodImplAttribute(MethodImplOptions.NoInlining)] // Due to the stack crawl mark
- [SecuritySafeCritical]
public AssemblyBuilder DefineDynamicAssembly(AssemblyName name,
AssemblyBuilderAccess access,
IEnumerable<CustomAttributeBuilder> assemblyAttributes,
securityContextSource);
}
- [System.Security.SecuritySafeCritical] // auto-generated
[MethodImplAttribute(MethodImplOptions.NoInlining)] // Methods containing StackCrawlMark local var has to be marked non-inlineable
public AssemblyBuilder DefineDynamicAssembly(
AssemblyName name,
SecurityContextSource.CurrentAssembly);
}
- [System.Security.SecuritySafeCritical] // auto-generated
[MethodImplAttribute(MethodImplOptions.NoInlining)] // Methods containing StackCrawlMark local var has to be marked non-inlineable
[Obsolete("Assembly level declarative security is obsolete and is no longer enforced by the CLR by default. See http://go.microsoft.com/fwlink/?LinkID=155570 for more information.")]
public AssemblyBuilder DefineDynamicAssembly(
SecurityContextSource.CurrentAssembly);
}
- [System.Security.SecuritySafeCritical] // auto-generated
[MethodImplAttribute(MethodImplOptions.NoInlining)] // Methods containing StackCrawlMark local var has to be marked non-inlineable
[Obsolete("Assembly level declarative security is obsolete and is no longer enforced by the CLR by default. See http://go.microsoft.com/fwlink/?LinkID=155570 for more information.")]
public AssemblyBuilder DefineDynamicAssembly(
SecurityContextSource.CurrentAssembly);
}
- [System.Security.SecuritySafeCritical] // auto-generated
[MethodImplAttribute(MethodImplOptions.NoInlining)] // Methods containing StackCrawlMark local var has to be marked non-inlineable
[Obsolete("Methods which use evidence to sandbox are obsolete and will be removed in a future release of the .NET Framework. Please use an overload of DefineDynamicAssembly which does not take an Evidence parameter. See http://go.microsoft.com/fwlink/?LinkId=155570 for more information.")]
public AssemblyBuilder DefineDynamicAssembly(
null, null, null, ref stackMark, null, SecurityContextSource.CurrentAssembly);
}
- [System.Security.SecuritySafeCritical] // auto-generated
[MethodImplAttribute(MethodImplOptions.NoInlining)] // Methods containing StackCrawlMark local var has to be marked non-inlineable
[Obsolete("Assembly level declarative security is obsolete and is no longer enforced by the CLR by default. See http://go.microsoft.com/fwlink/?LinkID=155570 for more information.")]
public AssemblyBuilder DefineDynamicAssembly(
SecurityContextSource.CurrentAssembly);
}
- [System.Security.SecuritySafeCritical] // auto-generated
[MethodImplAttribute(MethodImplOptions.NoInlining)] // Methods containing StackCrawlMark local var has to be marked non-inlineable
[Obsolete("Assembly level declarative security is obsolete and is no longer enforced by the CLR by default. See http://go.microsoft.com/fwlink/?LinkID=155570 for more information.")]
public AssemblyBuilder DefineDynamicAssembly(
SecurityContextSource.CurrentAssembly);
}
- [System.Security.SecuritySafeCritical] // auto-generated
[MethodImplAttribute(MethodImplOptions.NoInlining)] // Methods containing StackCrawlMark local var has to be marked non-inlineable
[Obsolete("Assembly level declarative security is obsolete and is no longer enforced by the CLR by default. Please see http://go.microsoft.com/fwlink/?LinkId=155570 for more information.")]
public AssemblyBuilder DefineDynamicAssembly(
SecurityContextSource.CurrentAssembly);
}
- [System.Security.SecuritySafeCritical] // auto-generated
[MethodImplAttribute(MethodImplOptions.NoInlining)] // Methods containing StackCrawlMark local var has to be marked non-inlineable
[Obsolete("Assembly level declarative security is obsolete and is no longer enforced by the CLR by default. See http://go.microsoft.com/fwlink/?LinkID=155570 for more information.")]
public AssemblyBuilder DefineDynamicAssembly(
SecurityContextSource.CurrentAssembly);
}
- [System.Security.SecuritySafeCritical] // auto-generated
[MethodImplAttribute(MethodImplOptions.NoInlining)] // Methods containing StackCrawlMark local var has to be marked non-inlineable
[Obsolete("Assembly level declarative security is obsolete and is no longer enforced by the CLR by default. See http://go.microsoft.com/fwlink/?LinkID=155570 for more information.")]
public AssemblyBuilder DefineDynamicAssembly(
SecurityContextSource.CurrentAssembly);
}
- [System.Security.SecuritySafeCritical] // auto-generated
[MethodImplAttribute(MethodImplOptions.NoInlining)] // Methods containing StackCrawlMark local var has to be marked non-inlineable
public AssemblyBuilder DefineDynamicAssembly(
AssemblyName name,
SecurityContextSource.CurrentAssembly);
}
- [System.Security.SecurityCritical] // auto-generated
[MethodImplAttribute(MethodImplOptions.NoInlining)] // Methods containing StackCrawlMark local var has to be marked non-inlineable
private AssemblyBuilder InternalDefineDynamicAssembly(
AssemblyName name,
securityContextSource);
}
- [System.Security.SecuritySafeCritical] // auto-generated
[MethodImplAttribute(MethodImplOptions.InternalCall)]
private extern String nApplyPolicy(AssemblyName an);
typeName);
}
- [System.Security.SecurityCritical] // auto-generated
internal ObjectHandle InternalCreateInstanceWithNoSecurity (string assemblyName, string typeName) {
PermissionSet.s_fullTrust.Assert();
return CreateInstance(assemblyName, typeName);
typeName);
}
- [System.Security.SecurityCritical] // auto-generated
internal ObjectHandle InternalCreateInstanceFromWithNoSecurity (string assemblyName, string typeName) {
PermissionSet.s_fullTrust.Assert();
return CreateInstanceFrom(assemblyName, typeName);
activationAttributes);
}
- [System.Security.SecurityCritical] // auto-generated
internal ObjectHandle InternalCreateInstanceWithNoSecurity (string assemblyName,
string typeName,
bool ignoreCase,
activationAttributes);
}
- [System.Security.SecurityCritical] // auto-generated
internal ObjectHandle InternalCreateInstanceFromWithNoSecurity (string assemblyName,
string typeName,
bool ignoreCase,
#pragma warning restore 618
}
- [System.Security.SecuritySafeCritical] // auto-generated
[MethodImplAttribute(MethodImplOptions.NoInlining)] // Methods containing StackCrawlMark local var has to be marked non-inlineable
public Assembly Load(AssemblyName assemblyRef)
{
return RuntimeAssembly.InternalLoadAssemblyName(assemblyRef, null, null, ref stackMark, true /*thrownOnFileNotFound*/, false, false);
}
- [System.Security.SecuritySafeCritical] // auto-generated
[MethodImplAttribute(MethodImplOptions.NoInlining)] // Methods containing StackCrawlMark local var has to be marked non-inlineable
public Assembly Load(String assemblyString)
{
return RuntimeAssembly.InternalLoad(assemblyString, null, ref stackMark, false);
}
- [System.Security.SecuritySafeCritical] // auto-generated
[MethodImplAttribute(MethodImplOptions.NoInlining)] // Methods containing StackCrawlMark local var has to be marked non-inlineable
public Assembly Load(byte[] rawAssembly)
{
}
- [System.Security.SecuritySafeCritical] // auto-generated
[MethodImplAttribute(MethodImplOptions.NoInlining)] // Methods containing StackCrawlMark local var has to be marked non-inlineable
public Assembly Load(byte[] rawAssembly,
byte[] rawSymbolStore)
SecurityContextSource.CurrentAssembly);
}
- [System.Security.SecuritySafeCritical] // auto-generated
-#pragma warning disable 618
- [SecurityPermissionAttribute(SecurityAction.Demand, ControlEvidence = true)]
-#pragma warning restore 618
[MethodImplAttribute(MethodImplOptions.NoInlining)] // Methods containing StackCrawlMark local var has to be marked non-inlineable
[Obsolete("Methods which use evidence to sandbox are obsolete and will be removed in a future release of the .NET Framework. Please use an overload of Load which does not take an Evidence parameter. See http://go.microsoft.com/fwlink/?LinkId=155570 for more information.")]
public Assembly Load(byte[] rawAssembly,
SecurityContextSource.CurrentAssembly);
}
- [System.Security.SecuritySafeCritical] // auto-generated
[MethodImplAttribute(MethodImplOptions.NoInlining)] // Methods containing StackCrawlMark local var has to be marked non-inlineable
[Obsolete("Methods which use evidence to sandbox are obsolete and will be removed in a future release of the .NET Framework. Please use an overload of Load which does not take an Evidence parameter. See http://go.microsoft.com/fwlink/?LinkID=155570 for more information.")]
public Assembly Load(AssemblyName assemblyRef,
return RuntimeAssembly.InternalLoadAssemblyName(assemblyRef, assemblySecurity, null, ref stackMark, true /*thrownOnFileNotFound*/, false, false);
}
- [System.Security.SecuritySafeCritical] // auto-generated
[MethodImplAttribute(MethodImplOptions.NoInlining)] // Methods containing StackCrawlMark local var has to be marked non-inlineable
[Obsolete("Methods which use evidence to sandbox are obsolete and will be removed in a future release of the .NET Framework. Please use an overload of Load which does not take an Evidence parameter. See http://go.microsoft.com/fwlink/?LinkID=155570 for more information.")]
public Assembly Load(String assemblyString,
return nExecuteAssembly(assembly, args);
}
- [System.Security.SecurityCritical] // auto-generated
public int ExecuteAssemblyByName(String assemblyName)
{
return ExecuteAssemblyByName(assemblyName, (string[])null);
public String FriendlyName
{
- [System.Security.SecuritySafeCritical] // auto-generated
get { return nGetFriendlyName(); }
}
public String BaseDirectory
{
- [System.Security.SecurityCritical]
get {
return FusionStore.ApplicationBase;
}
}
- [System.Security.SecuritySafeCritical] // auto-generated
public override String ToString()
{
StringBuilder sb = StringBuilderCache.Acquire();
return nGetAssemblies(true /* forIntrospection */);
}
- [System.Security.SecuritySafeCritical] // auto-generated
[MethodImplAttribute(MethodImplOptions.InternalCall)]
private extern Assembly[] nGetAssemblies(bool forIntrospection);
// this is true when we've removed the handles etc so really can't do anything
- [System.Security.SecurityCritical] // auto-generated
[MethodImplAttribute(MethodImplOptions.InternalCall)]
internal extern bool IsUnloadingForcedFinalize();
// this is true when we've just started going through the finalizers and are forcing objects to finalize
// so must be aware that certain infrastructure may have gone away
- [System.Security.SecuritySafeCritical] // auto-generated
[MethodImplAttribute(MethodImplOptions.InternalCall)]
public extern bool IsFinalizingForUnload();
- [System.Security.SecurityCritical] // auto-generated
[MethodImplAttribute(MethodImplOptions.InternalCall)]
internal static extern void PublishAnonymouslyHostedDynamicMethodsAssembly(RuntimeAssembly assemblyHandle);
- [System.Security.SecurityCritical] // auto-generated_required
public void SetData (string name, object data) {
SetDataHelper(name, data, null);
}
- [System.Security.SecurityCritical] // auto-generated_required
public void SetData (string name, object data, IPermission permission)
{
if (!name.Equals("LOCATION_URI"))
SetDataHelper(name, data, permission);
}
- [System.Security.SecurityCritical] // auto-generated
private void SetDataHelper (string name, object data, IPermission permission)
{
if (name == null)
}
[Pure]
- [System.Security.SecurityCritical] // auto-generated
public Object GetData(string name)
{
if(name == null)
case (int) AppDomainSetup.LoaderInformation.ApplicationNameValue:
return FusionStore.ApplicationName;
default:
- Contract.Assert(false, "Need to handle new LoaderInformation value in AppDomain.GetData()");
+ Debug.Assert(false, "Need to handle new LoaderInformation value in AppDomain.GetData()");
return null;
}
}
public String DynamicDirectory
{
- [System.Security.SecuritySafeCritical] // auto-generated
get {
String dyndir = GetDynamicDir();
if (dyndir != null)
}
}
- [System.Security.SecurityCritical] // auto-generated
[MethodImplAttribute(MethodImplOptions.InternalCall)]
extern private String GetDynamicDir();
throw new NotSupportedException(Environment.GetResourceString(ResId.NotSupported_Constructor));
}
- [System.Security.SecuritySafeCritical] // auto-generated
[MethodImplAttribute(MethodImplOptions.InternalCall)]
private extern int _nExecuteAssembly(RuntimeAssembly assembly, String[] args);
internal int nExecuteAssembly(RuntimeAssembly assembly, String[] args)
[MethodImplAttribute(MethodImplOptions.InternalCall)]
internal extern void nCreateContext();
- [System.Security.SecurityCritical]
[DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
[SuppressUnmanagedCodeSecurity]
private static extern void nSetupBindingPaths(String trustedPlatformAssemblies, String platformResourceRoots, String appPath, String appNiPaths, String appLocalWinMD);
- #if FEATURE_CORECLR
- [System.Security.SecurityCritical] // auto-generated
- #endif
internal void SetupBindingPaths(String trustedPlatformAssemblies, String platformResourceRoots, String appPath, String appNiPaths, String appLocalWinMD)
{
nSetupBindingPaths(trustedPlatformAssemblies, platformResourceRoots, appPath, appNiPaths, appLocalWinMD);
}
#endif // FEATURE_VERSIONING
- [System.Security.SecurityCritical] // auto-generated
[MethodImplAttribute(MethodImplOptions.InternalCall)]
private extern String nGetFriendlyName();
- [System.Security.SecurityCritical] // auto-generated
[MethodImplAttribute(MethodImplOptions.InternalCall)]
private extern bool nIsDefaultAppDomainForEvidence();
public event EventHandler ProcessExit
{
- [System.Security.SecuritySafeCritical] // auto-generated_required
add
{
if (value != null)
public event EventHandler DomainUnload
{
- [System.Security.SecuritySafeCritical] // auto-generated_required
add
{
if (value != null)
_domainUnload += value;
}
}
- [System.Security.SecuritySafeCritical]
remove
{
lock(this)
public event UnhandledExceptionEventHandler UnhandledException
{
- [System.Security.SecurityCritical] // auto-generated_required
add
{
if (value != null)
_unhandledException += value;
}
}
- [System.Security.SecurityCritical] // auto-generated_required
remove
{
lock(this)
// To register/unregister the callback, the code must be SecurityCritical.
public event EventHandler<FirstChanceExceptionEventArgs> FirstChanceException
{
- [System.Security.SecurityCritical] // auto-generated_required
add
{
if (value != null)
_firstChanceException += value;
}
}
- [System.Security.SecurityCritical] // auto-generated_required
remove
{
lock(this)
}
// This method is called by the VM.
- [System.Security.SecurityCritical]
private RuntimeAssembly OnResourceResolveEvent(RuntimeAssembly assembly, String resourceName)
{
ResolveEventHandler eventHandler = _ResourceResolve;
}
// This method is called by the VM
- [System.Security.SecurityCritical]
private RuntimeAssembly OnTypeResolveEvent(RuntimeAssembly assembly, String typeName)
{
ResolveEventHandler eventHandler = _TypeResolve;
}
// This method is called by the VM.
- [System.Security.SecurityCritical]
private RuntimeAssembly OnAssemblyResolveEvent(RuntimeAssembly assembly, String assemblyFullName)
{
ResolveEventHandler eventHandler = _AssemblyResolve;
internal AppDomainSetup FusionStore
{
get {
- Contract.Assert(_FusionStore != null,
+ Debug.Assert(_FusionStore != null,
"Fusion store has not been correctly setup in this domain");
return _FusionStore;
}
// Used to determine if server object context is valid in
// x-domain remoting scenarios.
- [System.Security.SecurityCritical] // auto-generated
[MethodImplAttribute(MethodImplOptions.InternalCall)]
[ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)]
internal static extern bool IsDomainIdValid(Int32 id);
- [System.Security.SecurityCritical]
[DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
[SuppressUnmanagedCodeSecurity]
private static extern void nSetNativeDllSearchDirectories(string paths);
- [System.Security.SecurityCritical] // auto-generated
private void SetupFusionStore(AppDomainSetup info, AppDomainSetup oldInfo)
{
Contract.Requires(info != null);
// are any remoting sinks registered, they can add non-mscorlib
// objects to the message (causing an assembly load exception when
// we try to deserialize it on the other side)
- [System.Security.SecurityCritical] // auto-generated
private static object PrepareDataForSetup(String friendlyName,
AppDomainSetup setup,
Evidence providedSecurityInfo,
};
} // PrepareDataForSetup
- [System.Security.SecurityCritical] // auto-generated
[MethodImplAttribute(MethodImplOptions.NoInlining)]
private static Object Setup(Object arg)
{
Evidence providedSecurityInfo = null;
Evidence creatorsSecurityInfo = null;
-
AppDomain ad = AppDomain.CurrentDomain;
AppDomainSetup newSetup=new AppDomainSetup(setup,false);
if(propertyNames!=null && propertyValues != null)
{
- StringBuilder normalisedAppPathList = null;
+ for (int i = 0; i < propertyNames.Length; i++)
+ {
+ // We want to set native dll probing directories before any P/Invokes have a
+ // chance to fire. The Path class, for one, has P/Invokes.
+ if (propertyNames[i] == "NATIVE_DLL_SEARCH_DIRECTORIES")
+ {
+ if (propertyValues[i] == null)
+ throw new ArgumentNullException("NATIVE_DLL_SEARCH_DIRECTORIES");
+
+ string paths = propertyValues[i];
+ if (paths.Length == 0)
+ break;
+
+ nSetNativeDllSearchDirectories(paths);
+ }
+ }
for (int i=0; i<propertyNames.Length; i++)
{
throw new ArgumentException( Environment.GetResourceString( "Argument_AbsolutePathRequired" ) );
newSetup.ApplicationBase = NormalizePath(propertyValues[i], fullCheck: true);
-
}
#if FEATURE_LOADER_OPTIMIZATION
- else
- if(propertyNames[i]=="LOADER_OPTIMIZATION")
+ else if(propertyNames[i]=="LOADER_OPTIMIZATION")
{
if(propertyValues[i]==null)
throw new ArgumentNullException("LOADER_OPTIMIZATION");
}
}
#endif // FEATURE_LOADER_OPTIMIZATION
- else
- if(propertyNames[i]=="NATIVE_DLL_SEARCH_DIRECTORIES")
- {
- if(propertyValues[i]==null)
- throw new ArgumentNullException("NATIVE_DLL_SEARCH_DIRECTORIES");
- ad.SetDataHelper(propertyNames[i],propertyValues[i],null);
- string paths = (string)propertyValues[i];
- if( paths.Length==0 )
- continue;
- nSetNativeDllSearchDirectories(paths);
- }
- else
- if(propertyNames[i]=="TRUSTED_PLATFORM_ASSEMBLIES" ||
+ else if(propertyNames[i]=="TRUSTED_PLATFORM_ASSEMBLIES" ||
propertyNames[i]=="PLATFORM_RESOURCE_ROOTS" ||
propertyNames[i]=="APP_PATHS" ||
propertyNames[i]=="APP_NI_PATHS")
{
string values = propertyValues[i];
- if(values==null)
+ if(values == null)
throw new ArgumentNullException(propertyNames[i]);
- int estimatedLength = values.Length + 1; // +1 for extra separator temporarily added at end
- if (normalisedAppPathList == null) {
- normalisedAppPathList = new StringBuilder(estimatedLength);
- }
- else {
- normalisedAppPathList.Clear();
- if (normalisedAppPathList.Capacity < estimatedLength)
- normalisedAppPathList.Capacity = estimatedLength;
- }
-
- for (int pos = 0; pos < values.Length; pos++)
- {
- string path;
-
- int nextPos = values.IndexOf(Path.PathSeparator, pos);
- if (nextPos == -1)
- {
- path = values.Substring(pos);
- pos = values.Length - 1;
- }
- else
- {
- path = values.Substring(pos, nextPos - pos);
- pos = nextPos;
- }
-
- if( path.Length==0 ) // skip empty dirs
- continue;
-
- if (PathInternal.IsPartiallyQualified(path))
- throw new ArgumentException( Environment.GetResourceString( "Argument_AbsolutePathRequired" ) );
-
- string appPath = NormalizePath(path, fullCheck: true);
- normalisedAppPathList.Append(appPath);
- normalisedAppPathList.Append(Path.PathSeparator);
- }
- // Strip the last separator
- if (normalisedAppPathList.Length > 0)
- {
- normalisedAppPathList.Remove(normalisedAppPathList.Length - 1, 1);
- }
- ad.SetDataHelper(propertyNames[i],normalisedAppPathList.ToString(),null); // not supported by fusion, so set explicitly
+ ad.SetDataHelper(propertyNames[i], NormalizeAppPaths(values), null);
}
- else
- if(propertyNames[i]!= null)
+ else if(propertyNames[i]!= null)
{
ad.SetDataHelper(propertyNames[i],propertyValues[i],null); // just propagate
}
return null;
}
- [SecuritySafeCritical]
+ private static string NormalizeAppPaths(string values)
+ {
+ int estimatedLength = values.Length + 1; // +1 for extra separator temporarily added at end
+ StringBuilder sb = StringBuilderCache.Acquire(estimatedLength);
+
+ for (int pos = 0; pos < values.Length; pos++)
+ {
+ string path;
+
+ int nextPos = values.IndexOf(Path.PathSeparator, pos);
+ if (nextPos == -1)
+ {
+ path = values.Substring(pos);
+ pos = values.Length - 1;
+ }
+ else
+ {
+ path = values.Substring(pos, nextPos - pos);
+ pos = nextPos;
+ }
+
+ // Skip empty directories
+ if (path.Length == 0)
+ continue;
+
+ if (PathInternal.IsPartiallyQualified(path))
+ throw new ArgumentException(Environment.GetResourceString("Argument_AbsolutePathRequired"));
+
+ string appPath = NormalizePath(path, fullCheck: true);
+ sb.Append(appPath);
+ sb.Append(Path.PathSeparator);
+ }
+
+ // Strip the last separator
+ if (sb.Length > 0)
+ {
+ sb.Remove(sb.Length - 1, 1);
+ }
+
+ return StringBuilderCache.GetStringAndRelease(sb);
+ }
+
internal static string NormalizePath(string path, bool fullCheck)
{
return Path.GetFullPath(path);
// This routine is called from unmanaged code to
// set the default fusion context.
- [System.Security.SecurityCritical] // auto-generated
private void SetupDomain(bool allowRedirects, String path, String configFile, String[] propertyNames, String[] propertyValues)
{
// It is possible that we could have multiple threads initializing
}
#if FEATURE_LOADER_OPTIMIZATION
- [System.Security.SecurityCritical] // auto-generated
private void SetupLoaderOptimization(LoaderOptimization policy)
{
if(policy != LoaderOptimization.NotSpecified) {
- Contract.Assert(FusionStore.LoaderOptimization == LoaderOptimization.NotSpecified,
+ Debug.Assert(FusionStore.LoaderOptimization == LoaderOptimization.NotSpecified,
"It is illegal to change the Loader optimization on a domain");
FusionStore.LoaderOptimization = policy;
}
#endif
- [System.Security.SecurityCritical] // auto-generated
[MethodImplAttribute(MethodImplOptions.InternalCall)]
internal extern IntPtr GetSecurityDescriptor();
- [SecurityCritical]
private void SetupDomainSecurity(Evidence appDomainEvidence,
IntPtr creatorsSecurityDescriptor,
bool publishAppDomain)
}
- [SecurityCritical]
[SuppressUnmanagedCodeSecurity]
[DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
private static extern void SetupDomainSecurity(AppDomainHandle appDomain,
IntPtr creatorsSecurityDescriptor,
[MarshalAs(UnmanagedType.Bool)] bool publishAppDomain);
- [System.Security.SecurityCritical] // auto-generated
[MethodImplAttribute(MethodImplOptions.InternalCall)]
private extern void nSetupFriendlyName(string friendlyName);
#endif // FEATURE_COMINTEROP
#if FEATURE_LOADER_OPTIMIZATION
- [System.Security.SecurityCritical] // auto-generated
[MethodImplAttribute(MethodImplOptions.InternalCall)]
internal extern void UpdateLoaderOptimization(LoaderOptimization optimization);
#endif
}
}
- [System.Security.SecurityCritical] // auto-generated
[MethodImplAttribute(MethodImplOptions.InternalCall)]
internal extern String IsStringInterned(String str);
- [System.Security.SecurityCritical] // auto-generated
[MethodImplAttribute(MethodImplOptions.InternalCall)]
internal extern String GetOrInternString(String str);
- [SecurityCritical]
[SuppressUnmanagedCodeSecurity]
[DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
private static extern void GetGrantSet(AppDomainHandle domain, ObjectHandleOnStack retGrantSet);
public PermissionSet PermissionSet
{
// SecurityCritical because permissions can contain sensitive information such as paths
- [SecurityCritical]
get
{
PermissionSet grantSet = null;
public bool IsFullyTrusted
{
- [SecuritySafeCritical]
get
{
PermissionSet grantSet = null;
}
}
- [System.Security.SecurityCritical] // auto-generated
[MethodImplAttribute(MethodImplOptions.InternalCall)]
private extern void nChangeSecurityPolicy();
- [System.Security.SecurityCritical] // auto-generated
[MethodImplAttribute(MethodImplOptions.InternalCall)]
[ReliabilityContract(Consistency.MayCorruptAppDomain, Cer.MayFail)]
internal static extern void nUnload(Int32 domainInternal);
}
}
- [System.Security.SecuritySafeCritical] // auto-generated
[MethodImplAttribute(MethodImplOptions.InternalCall)]
[ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)]
internal extern Int32 GetId();
}
#if FEATURE_APPDOMAIN_RESOURCE_MONITORING
- [System.Security.SecurityCritical] // auto-generated
[MethodImplAttribute(MethodImplOptions.InternalCall)]
private static extern void nEnableMonitoring();
- [System.Security.SecurityCritical] // auto-generated
[MethodImplAttribute(MethodImplOptions.InternalCall)]
private static extern bool nMonitoringIsEnabled();
// return -1 if ARM is not supported.
- [System.Security.SecurityCritical] // auto-generated
[MethodImplAttribute(MethodImplOptions.InternalCall)]
private extern Int64 nGetTotalProcessorTime();
// return -1 if ARM is not supported.
- [System.Security.SecurityCritical] // auto-generated
[MethodImplAttribute(MethodImplOptions.InternalCall)]
private extern Int64 nGetTotalAllocatedMemorySize();
// return -1 if ARM is not supported.
- [System.Security.SecurityCritical] // auto-generated
[MethodImplAttribute(MethodImplOptions.InternalCall)]
private extern Int64 nGetLastSurvivedMemorySize();
// return -1 if ARM is not supported.
- [System.Security.SecurityCritical] // auto-generated
[MethodImplAttribute(MethodImplOptions.InternalCall)]
private static extern Int64 nGetLastSurvivedProcessMemorySize();
public static bool MonitoringIsEnabled
{
- [System.Security.SecurityCritical]
get {
return nMonitoringIsEnabled();
}
- [System.Security.SecurityCritical]
set {
if (value == false)
{
// Throws NotSupportedException if ARM is not enabled.
public TimeSpan MonitoringTotalProcessorTime
{
- [System.Security.SecurityCritical]
get {
Int64 i64ProcessorTime = nGetTotalProcessorTime();
if (i64ProcessorTime == -1)
// Throws NotSupportedException if ARM is not enabled.
public Int64 MonitoringTotalAllocatedMemorySize
{
- [System.Security.SecurityCritical]
get {
Int64 i64AllocatedMemory = nGetTotalAllocatedMemorySize();
if (i64AllocatedMemory == -1)
// Throws NotSupportedException if ARM is not enabled.
public Int64 MonitoringSurvivedMemorySize
{
- [System.Security.SecurityCritical]
get {
Int64 i64LastSurvivedMemory = nGetLastSurvivedMemorySize();
if (i64LastSurvivedMemory == -1)
// Throws NotSupportedException if ARM is not enabled.
public static Int64 MonitoringSurvivedProcessMemorySize
{
- [System.Security.SecurityCritical]
get {
Int64 i64LastSurvivedProcessMemory = nGetLastSurvivedProcessMemorySize();
if (i64LastSurvivedProcessMemory == -1)
using System.Security;
using System.Runtime.InteropServices;
- [System.Security.SecurityCritical] // auto-generated_required
[System.Runtime.InteropServices.ComVisible(true)]
public class AppDomainManager : MarshalByRefObject
{
public AppDomainManager () {}
- [System.Security.SecurityCritical]
public virtual void InitializeNewDomain (AppDomainSetup appDomainInfo)
{
// By default, InitializeNewDomain does nothing. AppDomain.CreateAppDomainManager relies on this fact.
private Assembly m_entryAssembly = null;
public virtual Assembly EntryAssembly {
- [System.Security.SecurityCritical] // auto-generated
get {
// The default AppDomainManager sets the EntryAssembly depending on whether the
// AppDomain is a manifest application domain or not. In the first case, we parse
}
internal static AppDomainManager CurrentAppDomainManager {
- [System.Security.SecurityCritical] // auto-generated
get {
return AppDomain.CurrentDomain.DomainManager;
}
using System.Security;
using System.Security.Policy;
using Path = System.IO.Path;
+ using System.Diagnostics;
using System.Diagnostics.Contracts;
using System.Collections.Generic;
private bool _UseRandomizedStringHashing;
#endif
- [SecuritySafeCritical]
internal AppDomainSetup(AppDomainSetup copy, bool copyDomainBoundData)
{
string[] mine = Value;
_LoaderOptimization = LoaderOptimization.NotSpecified;
}
- [System.Security.SecurityCritical] // auto-generated
internal void SetupDefaults(string imageLocation, bool imageLocationAlreadyNormalized = false) {
char[] sep = {'\\', '/'};
int i = imageLocation.LastIndexOfAny(sep);
public String ApplicationBase
{
- #if FEATURE_CORECLR
- [System.Security.SecurityCritical] // auto-generated
- #else
- [System.Security.SecuritySafeCritical]
- #endif
[Pure]
get {
return VerifyDir(GetUnsecureApplicationBase(), false);
}
- #if FEATURE_CORECLR
- [System.Security.SecurityCritical] // auto-generated
- #endif
set {
Value[(int) LoaderInformation.ApplicationBaseValue] = NormalizePath(value, false);
}
public String ConfigurationFile
{
- [System.Security.SecuritySafeCritical] // auto-generated
get {
return VerifyDir(Value[(int) LoaderInformation.ConfigurationFileValue], true);
}
public String DynamicBase
{
- [System.Security.SecuritySafeCritical] // auto-generated
get {
return VerifyDir(Value[(int) LoaderInformation.DynamicBaseValue], true);
}
- [System.Security.SecuritySafeCritical] // auto-generated
set {
if (value == null)
Value[(int) LoaderInformation.DynamicBaseValue] = null;
}
}
- [System.Security.SecurityCritical] // auto-generated
private String VerifyDir(String dir, bool normalize)
{
if (dir != null) {
return dir;
}
- [System.Security.SecurityCritical] // auto-generated
private void VerifyDirList(String dirs)
{
if (dirs != null) {
internal String DeveloperPath
{
- [System.Security.SecurityCritical] // auto-generated
get {
String dirs = Value[(int) LoaderInformation.DevPathValue];
VerifyDirList(dirs);
public String PrivateBinPath
{
- [System.Security.SecuritySafeCritical] // auto-generated
get {
String dirs = Value[(int) LoaderInformation.PrivateBinPathValue];
VerifyDirList(dirs);
public String ShadowCopyDirectories
{
- [System.Security.SecuritySafeCritical] // auto-generated
get {
String dirs = Value[(int) LoaderInformation.ShadowCopyDirectoriesValue];
VerifyDirList(dirs);
public String CachePath
{
- [System.Security.SecuritySafeCritical] // auto-generated
get {
return VerifyDir(Value[(int) LoaderInformation.CachePathValue], false);
}
public String LicenseFile
{
- [System.Security.SecuritySafeCritical] // auto-generated
get {
return VerifyDir(Value[(int) LoaderInformation.LicenseFileValue], true);
}
if(String.IsNullOrEmpty(s))
return -1;
- Contract.Assert('A' == ACTAG_APP_BASE_URL[0] , "Assumption violated");
+ Debug.Assert('A' == ACTAG_APP_BASE_URL[0] , "Assumption violated");
if (s[0]=='A' && s == ACTAG_APP_BASE_URL)
return (int)LoaderInformation.ApplicationBaseValue;
[StructLayout(LayoutKind.Sequential)]
public struct ArgIterator
{
- [System.Security.SecurityCritical] // auto-generated
[MethodImplAttribute(MethodImplOptions.InternalCall)]
private extern ArgIterator(IntPtr arglist);
// create an arg iterator that points at the first argument that
// is not statically declared (that is the first ... arg)
// 'arglist' is the value returned by the ARGLIST instruction
- [System.Security.SecuritySafeCritical] // auto-generated
public ArgIterator(RuntimeArgumentHandle arglist) : this(arglist.Value)
{
}
- [System.Security.SecurityCritical] // auto-generated
[MethodImplAttribute(MethodImplOptions.InternalCall)]
private unsafe extern ArgIterator(IntPtr arglist, void *ptr);
// 'arglist' is the value returned by the ARGLIST instruction
// This is much like the C va_start macro
- [System.Security.SecurityCritical] // auto-generated
[CLSCompliant(false)]
public unsafe ArgIterator(RuntimeArgumentHandle arglist, void* ptr) : this(arglist.Value, ptr)
// Fetch an argument as a typed referece, advance the iterator.
// Throws an exception if past end of argument list
- [System.Security.SecuritySafeCritical] // auto-generated
[CLSCompliant(false)]
public TypedReference GetNextArg()
{
return result;
}
- [System.Security.SecurityCritical] // auto-generated
[MethodImplAttribute(MethodImplOptions.InternalCall)]
// reference to TypedReference is banned, so have to pass result as void pointer
private unsafe extern void FCallGetNextArg(void * result);
// Alternate version of GetNextArg() intended primarily for IJW code
// generated by VC's "va_arg()" construct.
- [System.Security.SecuritySafeCritical] // auto-generated
[CLSCompliant(false)]
public TypedReference GetNextArg(RuntimeTypeHandle rth)
{
}
- [System.Security.SecurityCritical] // auto-generated
[MethodImplAttribute(MethodImplOptions.InternalCall)]
// reference to TypedReference is banned, so have to pass result as void pointer
private unsafe extern void InternalGetNextArg(void * result, RuntimeType rt);
}
// How many arguments are left in the list
- [System.Security.SecuritySafeCritical] // auto-generated
[MethodImplAttribute(MethodImplOptions.InternalCall)]
public extern int GetRemainingCount();
// Gets the type of the current arg, does NOT advance the iterator
- [System.Security.SecurityCritical] // auto-generated
[MethodImplAttribute(MethodImplOptions.InternalCall)]
private extern unsafe void* _GetNextArgType();
- [System.Security.SecuritySafeCritical] // auto-generated
public unsafe RuntimeTypeHandle GetNextArgType()
{
return new RuntimeTypeHandle(Type.GetTypeFromHandleUnsafe((IntPtr)_GetNextArgType()));
get { return m_paramName; }
}
- [System.Security.SecurityCritical] // auto-generated_required
public override void GetObjectData(SerializationInfo info, StreamingContext context) {
if (info==null) {
throw new ArgumentNullException(nameof(info));
SetErrorCode(__HResults.E_POINTER);
}
- [System.Security.SecurityCritical] // auto-generated_required
protected ArgumentNullException(SerializationInfo info, StreamingContext context) : base(info, context) {
}
}
get { return m_actualValue; }
}
- [System.Security.SecurityCritical] // auto-generated_required
public override void GetObjectData(SerializationInfo info, StreamingContext context) {
if (info==null) {
throw new ArgumentNullException(nameof(info));
using System.Runtime.ConstrainedExecution;
using System.Runtime.Versioning;
using System.Security;
+ using System.Diagnostics;
using System.Security.Permissions;
using System.Diagnostics.Contracts;
}
// Create instance will create an array
- [System.Security.SecuritySafeCritical] // auto-generated
public unsafe static Array CreateInstance(Type elementType, int length)
{
if ((object)elementType == null)
return InternalCreate((void*)t.TypeHandle.Value,1,&length,null);
}
- [System.Security.SecuritySafeCritical] // auto-generated
public unsafe static Array CreateInstance(Type elementType, int length1, int length2)
{
if ((object)elementType == null)
return InternalCreate((void*)t.TypeHandle.Value,2,pLengths,null);
}
- [System.Security.SecuritySafeCritical] // auto-generated
public unsafe static Array CreateInstance(Type elementType, int length1, int length2, int length3)
{
if ((object)elementType == null)
return InternalCreate((void*)t.TypeHandle.Value,3,pLengths,null);
}
- [System.Security.SecuritySafeCritical] // auto-generated
public unsafe static Array CreateInstance(Type elementType, params int[] lengths)
{
if ((object)elementType == null)
}
- [System.Security.SecuritySafeCritical] // auto-generated
public unsafe static Array CreateInstance(Type elementType, int[] lengths,int[] lowerBounds)
{
if (elementType == null)
fixed(int* pLowerBounds = lowerBounds)
return InternalCreate((void*)t.TypeHandle.Value,lengths.Length,pLengths,pLowerBounds);
}
- [System.Security.SecurityCritical] // auto-generated
+
[MethodImplAttribute(MethodImplOptions.InternalCall)]
private unsafe static extern Array InternalCreate(void* elementType,int rank,int *pLengths,int *pLowerBounds);
- [SecurityCritical]
-#if !FEATURE_CORECLR
- [PermissionSet(SecurityAction.Assert, Unrestricted = true)]
-#endif
internal static Array UnsafeCreateInstance(Type elementType, int length)
{
return CreateInstance(elementType, length);
}
- [SecurityCritical]
-#if !FEATURE_CORECLR
- [PermissionSet(SecurityAction.Assert, Unrestricted = true)]
-#endif
internal static Array UnsafeCreateInstance(Type elementType, int length1, int length2)
{
return CreateInstance(elementType, length1, length2);
}
- [SecurityCritical]
-#if !FEATURE_CORECLR
- [PermissionSet(SecurityAction.Assert, Unrestricted = true)]
-#endif
internal static Array UnsafeCreateInstance(Type elementType, params int[] lengths)
{
return CreateInstance(elementType, lengths);
}
- [SecurityCritical]
-#if !FEATURE_CORECLR
- [PermissionSet(SecurityAction.Assert, Unrestricted = true)]
-#endif
internal static Array UnsafeCreateInstance(Type elementType, int[] lengths, int[] lowerBounds)
{
return CreateInstance(elementType, lengths, lowerBounds);
// Copies length elements from sourceArray, starting at index 0, to
// destinationArray, starting at index 0.
//
- [System.Security.SecuritySafeCritical] // auto-generated
[ReliabilityContract(Consistency.MayCorruptInstance, Cer.MayFail)]
public static void Copy(Array sourceArray, Array destinationArray, int length)
{
// Copies length elements from sourceArray, starting at sourceIndex, to
// destinationArray, starting at destinationIndex.
//
- [System.Security.SecuritySafeCritical] // auto-generated
[ReliabilityContract(Consistency.MayCorruptInstance, Cer.MayFail)]
public static void Copy(Array sourceArray, int sourceIndex, Array destinationArray, int destinationIndex, int length)
{
// instance & might fail when called from within a CER, or if the
// reliable flag is true, it will either always succeed or always
// throw an exception with no side effects.
- [System.Security.SecurityCritical] // auto-generated
[ReliabilityContract(Consistency.MayCorruptInstance, Cer.MayFail)]
[MethodImplAttribute(MethodImplOptions.InternalCall)]
internal static extern void Copy(Array sourceArray, int sourceIndex, Array destinationArray, int destinationIndex, int length, bool reliable);
// compatible array types based on the array element type - this
// method does not support casting, boxing, or primitive widening.
// It will up-cast, assuming the array types are correct.
- [System.Security.SecuritySafeCritical] // auto-generated
[ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)]
public static void ConstrainedCopy(Array sourceArray, int sourceIndex, Array destinationArray, int destinationIndex, int length)
{
// Sets length elements in array to 0 (or null for Object arrays), starting
// at index.
//
- [System.Security.SecuritySafeCritical] // auto-generated
[MethodImplAttribute(MethodImplOptions.InternalCall)]
[ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)]
public static extern void Clear(Array array, int index, int length);
// The various Get values...
- [System.Security.SecuritySafeCritical] // auto-generated
public unsafe Object GetValue(params int[] indices)
{
if (indices == null)
return TypedReference.InternalToObject(&elemref);
}
- [System.Security.SecuritySafeCritical] // auto-generated
public unsafe Object GetValue(int index)
{
if (Rank != 1)
return TypedReference.InternalToObject(&elemref);
}
- [System.Security.SecuritySafeCritical] // auto-generated
public unsafe Object GetValue(int index1, int index2)
{
if (Rank != 2)
return TypedReference.InternalToObject(&elemref);
}
- [System.Security.SecuritySafeCritical] // auto-generated
public unsafe Object GetValue(int index1, int index2, int index3)
{
if (Rank != 3)
}
- [System.Security.SecuritySafeCritical] // auto-generated
public unsafe void SetValue(Object value,int index)
{
if (Rank != 1)
InternalSetValue(&elemref,value);
}
- [System.Security.SecuritySafeCritical] // auto-generated
public unsafe void SetValue(Object value,int index1, int index2)
{
if (Rank != 2)
InternalSetValue(&elemref,value);
}
- [System.Security.SecuritySafeCritical] // auto-generated
public unsafe void SetValue(Object value,int index1, int index2, int index3)
{
if (Rank != 3)
InternalSetValue(&elemref,value);
}
- [System.Security.SecuritySafeCritical] // auto-generated
public unsafe void SetValue(Object value,params int[] indices)
{
if (indices == null)
this.SetValue(value, intIndices);
}
- [System.Security.SecurityCritical] // auto-generated
[MethodImplAttribute(MethodImplOptions.InternalCall)]
// reference to TypedReference is banned, so have to pass result as pointer
private unsafe extern void InternalGetReference(void * elemRef, int rank, int * pIndices);
// Ideally, we would like to use TypedReference.SetValue instead. Unfortunately, TypedReference.SetValue
// always throws not-supported exception
- [System.Security.SecurityCritical] // auto-generated
[MethodImplAttribute(MethodImplOptions.InternalCall)]
private unsafe extern static void InternalSetValue(void * target, Object value);
public extern int Length {
[Pure]
- [System.Security.SecuritySafeCritical] // auto-generated
[ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)]
[MethodImpl(MethodImplOptions.InternalCall)]
get;
private static int GetMedian(int low, int hi) {
// Note both may be negative, if we are dealing with arrays w/ negative lower bounds.
Contract.Requires(low <= hi);
- Contract.Assert( hi - low >= 0, "Length overflow!");
+ Debug.Assert( hi - low >= 0, "Length overflow!");
return low + ((hi - low) >> 1);
}
[ComVisible(false)]
public extern long LongLength {
[Pure]
- [System.Security.SecuritySafeCritical] // auto-generated
[ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)]
[MethodImpl(MethodImplOptions.InternalCall)]
get;
}
[Pure]
- [System.Security.SecuritySafeCritical] // auto-generated
[MethodImplAttribute(MethodImplOptions.InternalCall)]
public extern int GetLength(int dimension);
public extern int Rank {
[Pure]
- [System.Security.SecuritySafeCritical] // auto-generated
[ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)]
[MethodImplAttribute(MethodImplOptions.InternalCall)]
get;
}
- [System.Security.SecuritySafeCritical] // auto-generated
[Pure]
[MethodImplAttribute(MethodImplOptions.InternalCall)]
[ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)]
public extern int GetUpperBound(int dimension);
- [System.Security.SecuritySafeCritical] // auto-generated
[Pure]
[ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)]
[MethodImplAttribute(MethodImplOptions.InternalCall)]
public extern int GetLowerBound(int dimension);
- [System.Security.SecurityCritical] // auto-generated
[ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)]
[MethodImplAttribute(MethodImplOptions.InternalCall)]
internal extern int GetDataPtrOffsetInternal();
// is larger than the given search value.
//
[Pure]
- [System.Security.SecuritySafeCritical] // auto-generated
[ReliabilityContract(Consistency.WillNotCorruptState, Cer.MayFail)]
public static int BinarySearch(Array array, int index, int length, Object value, IComparer comparer) {
if (array==null)
return ~lo;
}
- [System.Security.SecurityCritical] // auto-generated
[MethodImplAttribute(MethodImplOptions.InternalCall)]
[ReliabilityContract(Consistency.WillNotCorruptState, Cer.MayFail)]
private static extern bool TrySZBinarySearch(Array sourceArray, int sourceIndex, int count, Object value, out int retVal);
// elements of the array are compared to the given value using the
// Object.Equals method.
//
- [System.Security.SecuritySafeCritical] // auto-generated
[ReliabilityContract(Consistency.WillNotCorruptState, Cer.MayFail)]
public static int IndexOf(Array array, Object value, int startIndex, int count) {
if (array==null)
return EqualityComparer<T>.Default.IndexOf(array, value, startIndex, count);
}
- [System.Security.SecurityCritical] // auto-generated
[MethodImplAttribute(MethodImplOptions.InternalCall)]
[ReliabilityContract(Consistency.WillNotCorruptState, Cer.MayFail)]
private static extern bool TrySZIndexOf(Array sourceArray, int sourceIndex, int count, Object value, out int retVal);
// the array are compared to the given value using the Object.Equals
// method.
//
- [System.Security.SecuritySafeCritical] // auto-generated
[ReliabilityContract(Consistency.WillNotCorruptState, Cer.MayFail)]
public static int LastIndexOf(Array array, Object value, int startIndex, int count) {
if (array==null)
return EqualityComparer<T>.Default.LastIndexOf(array, value, startIndex, count);
}
- [System.Security.SecurityCritical] // auto-generated
[MethodImplAttribute(MethodImplOptions.InternalCall)]
[ReliabilityContract(Consistency.WillNotCorruptState, Cer.MayFail)]
private static extern bool TrySZLastIndexOf(Array sourceArray, int sourceIndex, int count, Object value, out int retVal);
// index index + (index + count - i - 1).
// Reliability note: This may fail because it may have to box objects.
//
- [System.Security.SecuritySafeCritical] // auto-generated
[ReliabilityContract(Consistency.MayCorruptInstance, Cer.MayFail)]
public static void Reverse(Array array, int index, int length) {
if (array==null)
}
}
- [System.Security.SecurityCritical] // auto-generated
[MethodImplAttribute(MethodImplOptions.InternalCall)]
[ReliabilityContract(Consistency.MayCorruptInstance, Cer.MayFail)]
private static extern bool TrySZReverse(Array array, int index, int count);
// the IComparable interface, which in that case must be implemented
// by all elements of the given section of the keys array.
//
- [System.Security.SecuritySafeCritical] // auto-generated
[ReliabilityContract(Consistency.MayCorruptInstance, Cer.MayFail)]
public static void Sort(Array keys, Array items, int index, int length, IComparer comparer) {
if (keys==null)
}
}
- [System.Security.SecurityCritical] // auto-generated
[MethodImplAttribute(MethodImplOptions.InternalCall)]
[ReliabilityContract(Consistency.MayCorruptInstance, Cer.MayFail)]
private static extern bool TrySZSort(Array keys, Array items, int left, int right);
Sort<TKey, TValue>(keys, items, 0, keys.Length, comparer);
}
- [System.Security.SecuritySafeCritical] // auto-generated
[ReliabilityContract(Consistency.MayCorruptInstance, Cer.MayFail)]
public static void Sort<T>(T[] array, int index, int length, System.Collections.Generic.IComparer<T> comparer) {
if (array==null)
}
}
- [System.Security.SecuritySafeCritical] // auto-generated
[ReliabilityContract(Consistency.MayCorruptInstance, Cer.MayFail)]
public static void Sort<TKey, TValue>(TKey[] keys, TValue[] items, int index, int length, System.Collections.Generic.IComparer<TKey> comparer) {
if (keys==null)
private int _endIndex; // cache array length, since it's a little slow.
internal SZArrayEnumerator(Array array) {
- Contract.Assert(array.Rank == 1 && array.GetLowerBound(0) == 0, "SZArrayEnumerator only works on single dimension arrays w/ a lower bound of zero.");
+ Debug.Assert(array.Rank == 1 && array.GetLowerBound(0) == 0, "SZArrayEnumerator only works on single dimension arrays w/ a lower bound of zero.");
_array = array;
_index = -1;
_endIndex = array.Length;
// if this is an array of value classes and that value class has a default constructor
// then this calls this default constructor on every element in the value class array.
// otherwise this is a no-op. Generally this method is called automatically by the compiler
- [System.Security.SecuritySafeCritical] // auto-generated
[MethodImplAttribute(MethodImplOptions.InternalCall)]
public extern void Initialize();
}
sealed class SZArrayHelper {
// It is never legal to instantiate this class.
private SZArrayHelper() {
- Contract.Assert(false, "Hey! How'd I get here?");
+ Debug.Assert(false, "Hey! How'd I get here?");
}
// -----------------------------------------------------------
// ------- Implement IEnumerable<T> interface methods --------
// -----------------------------------------------------------
- [SecuritySafeCritical]
internal IEnumerator<T> GetEnumerator<T>() {
//! Warning: "this" is an array, not an SZArrayHelper. See comments above
//! or you may introduce a security hole!
// -----------------------------------------------------------
// ------- Implement ICollection<T> interface methods --------
// -----------------------------------------------------------
- [SecuritySafeCritical]
void CopyTo<T>(T[] array, int index) {
//! Warning: "this" is an array, not an SZArrayHelper. See comments above
//! or you may introduce a security hole!
Array.Copy(_this, 0, array, index, _this.Length);
}
- [SecuritySafeCritical]
internal int get_Count<T>() {
//! Warning: "this" is an array, not an SZArrayHelper. See comments above
//! or you may introduce a security hole!
// -----------------------------------------------------------
// ---------- Implement IList<T> interface methods -----------
// -----------------------------------------------------------
- [SecuritySafeCritical]
internal T get_Item<T>(int index) {
//! Warning: "this" is an array, not an SZArrayHelper. See comments above
//! or you may introduce a security hole!
return _this[index];
}
- [SecuritySafeCritical]
internal void set_Item<T>(int index, T value) {
//! Warning: "this" is an array, not an SZArrayHelper. See comments above
//! or you may introduce a security hole!
ThrowHelper.ThrowNotSupportedException(ExceptionResource.NotSupported_FixedSizeCollection);
}
- [SecuritySafeCritical]
bool Contains<T>(T value) {
//! Warning: "this" is an array, not an SZArrayHelper. See comments above
//! or you may introduce a security hole!
ThrowHelper.ThrowNotSupportedException(ExceptionResource.NotSupported_ReadOnlyCollection);
}
- [SecuritySafeCritical]
int IndexOf<T>(T value) {
//! Warning: "this" is an array, not an SZArrayHelper. See comments above
//! or you may introduce a security hole!
internal SZGenericArrayEnumerator(T[] array, int endIndex) {
// We allow passing null array in case of empty enumerator.
- Contract.Assert(array != null || endIndex == -1, "endIndex should be -1 in the case of a null array (for the empty enumerator).");
+ Debug.Assert(array != null || endIndex == -1, "endIndex should be -1 in the case of a null array (for the empty enumerator).");
_array = array;
_index = -1;
_endIndex = endIndex;
using System.Collections;
using System.Collections.Generic;
using System.Runtime.InteropServices;
+using System.Diagnostics;
using System.Diagnostics.Contracts;
namespace System
[Serializable]
public struct ArraySegment<T> : IList<T>, IReadOnlyList<T>
{
- private T[] _array;
- private int _offset;
- private int _count;
-
+ private readonly T[] _array;
+ private readonly int _offset;
+ private readonly int _count;
+
public ArraySegment(T[] array)
{
if (array == null)
{
get
{
- Contract.Assert( (null == _array && 0 == _offset && 0 == _count)
+ Debug.Assert( (null == _array && 0 == _offset && 0 == _count)
|| (null != _array && _offset >= 0 && _count >= 0 && _offset + _count <= _array.Length),
"ArraySegment is invalid");
-
+
return _array;
}
}
// after reading each field out of an ArraySegment into their stack.
Contract.Ensures(Contract.Result<int>() >= 0);
- Contract.Assert( (null == _array && 0 == _offset && 0 == _count)
+ Debug.Assert( (null == _array && 0 == _offset && 0 == _count)
|| (null != _array && _offset >= 0 && _count >= 0 && _offset + _count <= _array.Length),
"ArraySegment is invalid");
// after reading each field out of an ArraySegment into their stack.
Contract.Ensures(Contract.Result<int>() >= 0);
- Contract.Assert( (null == _array && 0 == _offset && 0 == _count)
+ Debug.Assert( (null == _array && 0 == _offset && 0 == _count)
|| (null != _array && _offset >= 0 && _count >= 0 && _offset + _count <= _array.Length),
"ArraySegment is invalid");
return _count;
}
}
-
+
+ public Enumerator GetEnumerator()
+ {
+ if (_array == null)
+ ThrowHelper.ThrowInvalidOperationException(ExceptionResource.InvalidOperation_NullArray);
+ Contract.EndContractBlock();
+
+ return new Enumerator(this);
+ }
+
public override int GetHashCode()
{
if (_array == null)
int index = System.Array.IndexOf<T>(_array, item, _offset, _count);
- Contract.Assert(index == -1 ||
+ Debug.Assert(index == -1 ||
(index >= _offset && index < _offset + _count));
return index >= 0 ? index - _offset : -1;
int index = System.Array.IndexOf<T>(_array, item, _offset, _count);
- Contract.Assert(index == -1 ||
+ Debug.Assert(index == -1 ||
(index >= _offset && index < _offset + _count));
return index >= 0;
#endregion
#region IEnumerable<T>
- IEnumerator<T> IEnumerable<T>.GetEnumerator()
- {
- if (_array == null)
- ThrowHelper.ThrowInvalidOperationException(ExceptionResource.InvalidOperation_NullArray);
- Contract.EndContractBlock();
- return new ArraySegmentEnumerator(this);
- }
+ IEnumerator<T> IEnumerable<T>.GetEnumerator() => GetEnumerator();
#endregion
#region IEnumerable
- IEnumerator IEnumerable.GetEnumerator()
- {
- if (_array == null)
- ThrowHelper.ThrowInvalidOperationException(ExceptionResource.InvalidOperation_NullArray);
- Contract.EndContractBlock();
- return new ArraySegmentEnumerator(this);
- }
+ IEnumerator IEnumerable.GetEnumerator() => GetEnumerator();
#endregion
[Serializable]
- private sealed class ArraySegmentEnumerator : IEnumerator<T>
+ public struct Enumerator : IEnumerator<T>
{
- private T[] _array;
- private int _start;
- private int _end;
+ private readonly T[] _array;
+ private readonly int _start;
+ private readonly int _end; // cache Offset + Count, since it's a little slow
private int _current;
- internal ArraySegmentEnumerator(ArraySegment<T> arraySegment)
+ internal Enumerator(ArraySegment<T> arraySegment)
{
Contract.Requires(arraySegment.Array != null);
Contract.Requires(arraySegment.Offset >= 0);
Contract.Requires(arraySegment.Count >= 0);
Contract.Requires(arraySegment.Offset + arraySegment.Count <= arraySegment.Array.Length);
- _array = arraySegment._array;
- _start = arraySegment._offset;
- _end = _start + arraySegment._count;
- _current = _start - 1;
+ _array = arraySegment.Array;
+ _start = arraySegment.Offset;
+ _end = arraySegment.Offset + arraySegment.Count;
+ _current = arraySegment.Offset - 1;
}
public bool MoveNext()
{
get
{
- if (_current < _start) ThrowHelper.ThrowInvalidOperationException_InvalidOperation_EnumNotStarted();
- if (_current >= _end) ThrowHelper.ThrowInvalidOperationException_InvalidOperation_EnumEnded();
+ if (_current < _start)
+ ThrowHelper.ThrowInvalidOperationException_InvalidOperation_EnumNotStarted();
+ if (_current >= _end)
+ ThrowHelper.ThrowInvalidOperationException_InvalidOperation_EnumEnded();
return _array[_current];
}
}
- object IEnumerator.Current
- {
- get
- {
- return Current;
- }
- }
+ object IEnumerator.Current => Current;
void IEnumerator.Reset()
{
using System.Collections.Generic;
using System.Runtime.InteropServices;
using System.Globalization;
+ using System.Diagnostics;
using System.Diagnostics.Contracts;
using System.Security;
using System.Security.Permissions;
Environment.GetResourceString("Format_AttributeUsage", type));
}
- [System.Security.SecuritySafeCritical]
private static Attribute[] CreateAttributeArrayHelper(Type elementType, int elementCount)
{
return (Attribute[])Array.UnsafeCreateInstance(elementType, elementCount);
return element.IsDefined(attributeType, false);
default:
- Contract.Assert(false, "Invalid type for ParameterInfo member in Attribute class");
+ Debug.Assert(false, "Invalid type for ParameterInfo member in Attribute class");
throw new ArgumentException(Environment.GetResourceString("Argument_InvalidParamInfo"));
}
}
#endregion
#region Object Overrides
- [SecuritySafeCritical]
public override bool Equals(Object obj)
{
if (obj == null)
// Attributes can only contain single-dimension arrays, so we don't need to worry about
// multidimensional arrays.
- Contract.Assert(thisValueArray.Rank == 1 && thatValueArray.Rank == 1);
+ Debug.Assert(thisValueArray.Rank == 1 && thatValueArray.Rank == 1);
for (int j = 0; j < thisValueArray.Length; j++)
{
if (!AreFieldValuesEqual(thisValueArray.GetValue(j), thatValueArray.GetValue(j)))
// An object of type Attribute will cause a stack overflow.
// However, this should never happen because custom attributes cannot contain values other than
// constants, single-dimensional arrays and typeof expressions.
- Contract.Assert(!(thisValue is Attribute));
+ Debug.Assert(!(thisValue is Attribute));
if (!thisValue.Equals(thatValue))
return false;
}
return true;
}
- [SecuritySafeCritical]
public override int GetHashCode()
{
Type type = GetType();
#region Public Members
public virtual bool IsDefaultAttribute() { return false; }
#endregion
-
-#if !FEATURE_CORECLR
- void _Attribute.GetTypeInfoCount(out uint pcTInfo)
- {
- throw new NotImplementedException();
- }
-
- void _Attribute.GetTypeInfo(uint iTInfo, uint lcid, IntPtr ppTInfo)
- {
- throw new NotImplementedException();
- }
-
- void _Attribute.GetIDsOfNames([In] ref Guid riid, IntPtr rgszNames, uint cNames, uint lcid, IntPtr rgDispId)
- {
- throw new NotImplementedException();
- }
-
- void _Attribute.Invoke(uint dispIdMember, [In] ref Guid riid, uint lcid, short wFlags, IntPtr pDispParams, IntPtr pVarResult, IntPtr pExcepInfo, IntPtr puArgErr)
- {
- throw new NotImplementedException();
- }
-#endif
}
}
[Pure]
[Conditional("_LOGGING")]
- [SecuritySafeCritical]
static public void Log(String message) {
if (AppDomain.CurrentDomain.IsUnloadingForcedFinalize())
return;
[Pure]
[Conditional("_LOGGING")]
- [SecuritySafeCritical]
static public void Log(String switchName, String message) {
if (AppDomain.CurrentDomain.IsUnloadingForcedFinalize())
return;
[MethodImplAttribute(MethodImplOptions.InternalCall)]
private extern static int GetRegistryLoggingValues(out bool loggingEnabled, out bool logToConsole, out int logLevel, out bool perfWarnings, out bool correctnessWarnings, out bool safeHandleStackTraces);
- [SecuritySafeCritical]
private static void CheckRegistry() {
if (AppDomain.CurrentDomain.IsUnloadingForcedFinalize())
return;
}
}
- [SecuritySafeCritical]
internal static bool CheckEnabled(String switchName) {
if (AppDomain.CurrentDomain.IsUnloadingForcedFinalize())
return false;
return ((int)logSwitch.MinimumLevel<=(int)LogLevel.Trace);
}
- [SecuritySafeCritical]
private static bool CheckEnabled(String switchName, LogLevel level, out LogSwitch logSwitch) {
if (AppDomain.CurrentDomain.IsUnloadingForcedFinalize())
{
[Pure]
[Conditional("_LOGGING")]
- [SecuritySafeCritical]
public static void Log(String switchName, LogLevel level, params Object[]messages) {
if (AppDomain.CurrentDomain.IsUnloadingForcedFinalize())
return;
System.Diagnostics.Log.LogMessage(LoggingLevels.TraceLevel0, logSwitch, trace.ToString());
}
-#if !FEATURE_CORECLR
- // For logging errors related to the console - we often can't expect to
- // write to stdout if it doesn't exist.
- [SecuritySafeCritical]
- [Conditional("_DEBUG")]
- internal static void ConsoleError(String msg)
- {
- if (AppDomain.CurrentDomain.IsUnloadingForcedFinalize())
- return;
-
- if (m_MakeConsoleErrorLoggingWork == null) {
- PermissionSet perms = new PermissionSet();
- perms.AddPermission(new EnvironmentPermission(PermissionState.Unrestricted));
- perms.AddPermission(new FileIOPermission(FileIOPermissionAccess.AllAccess, Path.GetFullPath(".")));
- m_MakeConsoleErrorLoggingWork = perms;
- }
- m_MakeConsoleErrorLoggingWork.Assert();
-
- using (TextWriter err = File.AppendText("ConsoleErrors.log"))
- {
- err.WriteLine(msg);
- }
- }
-#endif // !FEATURE_CORECLR
-
// For perf-related asserts. On a debug build, set the registry key
// BCLPerfWarnings to non-zero.
[Conditional("_DEBUG")]
- [SecuritySafeCritical]
internal static void Perf(bool expr, String msg)
{
if (AppDomain.CurrentDomain.IsUnloadingForcedFinalize())
// BCLCorrectnessWarnings to non-zero.
[Conditional("_DEBUG")]
#if _DEBUG
- [SecuritySafeCritical]
#endif
internal static void Correctness(bool expr, String msg)
{
}
#if !BIT64 // 32
- [SecuritySafeCritical]
#endif
internal static bool CorrectnessEnabled()
{
}
public String FusionLog {
- [System.Security.SecuritySafeCritical] // auto-generated
#pragma warning disable CS0618 // Type or member is obsolete
- [SecurityPermissionAttribute( SecurityAction.Demand, Flags = SecurityPermissionFlag.ControlEvidence | SecurityPermissionFlag.ControlPolicy)]
#pragma warning restore CS0618 // Type or member is obsolete
get { return _fusionLog; }
}
- [System.Security.SecurityCritical] // auto-generated_required
public override void GetObjectData(SerializationInfo info, StreamingContext context) {
// Serialize data for our base classes. base will verify info != null.
base.GetObjectData(info, context);
using System;
using System.Runtime.CompilerServices;
+ using System.Diagnostics;
using System.Diagnostics.Contracts;
using System.Security;
// Converts a short into an array of bytes with length
// two.
- [System.Security.SecuritySafeCritical] // auto-generated
public unsafe static byte[] GetBytes(short value)
{
Contract.Ensures(Contract.Result<byte[]>() != null);
// Converts an int into an array of bytes with length
// four.
- [System.Security.SecuritySafeCritical] // auto-generated
public unsafe static byte[] GetBytes(int value)
{
Contract.Ensures(Contract.Result<byte[]>() != null);
// Converts a long into an array of bytes with length
// eight.
- [System.Security.SecuritySafeCritical] // auto-generated
public unsafe static byte[] GetBytes(long value)
{
Contract.Ensures(Contract.Result<byte[]>() != null);
// Converts a float into an array of bytes with length
// four.
- [System.Security.SecuritySafeCritical] // auto-generated
public unsafe static byte[] GetBytes(float value)
{
Contract.Ensures(Contract.Result<byte[]>() != null);
// Converts a double into an array of bytes with length
// eight.
- [System.Security.SecuritySafeCritical] // auto-generated
public unsafe static byte[] GetBytes(double value)
{
Contract.Ensures(Contract.Result<byte[]>() != null);
}
// Converts an array of bytes into a short.
- [System.Security.SecuritySafeCritical] // auto-generated
public static unsafe short ToInt16(byte[] value, int startIndex) {
if( value == null) {
ThrowHelper.ThrowArgumentNullException(ExceptionArgument.value);
}
// Converts an array of bytes into an int.
- [System.Security.SecuritySafeCritical] // auto-generated
public static unsafe int ToInt32 (byte[] value, int startIndex) {
if( value == null) {
ThrowHelper.ThrowArgumentNullException(ExceptionArgument.value);
}
// Converts an array of bytes into a long.
- [System.Security.SecuritySafeCritical] // auto-generated
public static unsafe long ToInt64 (byte[] value, int startIndex) {
if (value == null) {
ThrowHelper.ThrowArgumentNullException(ExceptionArgument.value);
}
// Converts an array of bytes into a float.
- [System.Security.SecuritySafeCritical] // auto-generated
unsafe public static float ToSingle (byte[] value, int startIndex)
{
if (value == null)
}
// Converts an array of bytes into a double.
- [System.Security.SecuritySafeCritical] // auto-generated
unsafe public static double ToDouble (byte[] value, int startIndex)
{
if (value == null)
}
private static char GetHexValue(int i) {
- Contract.Assert( i >=0 && i <16, "i is out of range.");
+ Debug.Assert( i >=0 && i <16, "i is out of range.");
if (i<10) {
return (char)(i + '0');
}
return (value[startIndex]==0)?false:true;
}
- [SecuritySafeCritical]
public static unsafe long DoubleToInt64Bits(double value) {
return *((long *)&value);
}
- [SecuritySafeCritical]
public static unsafe double Int64BitsToDouble(long value) {
return *((double*)&value);
}
- [SecuritySafeCritical]
public static unsafe int SingleToInt32Bits(float value) {
return *((int*)&value);
}
- [SecuritySafeCritical]
public static unsafe float Int32BitsToSingle(int value) {
return *((float*)&value);
}
using System.Runtime.ConstrainedExecution;
using System.Runtime.InteropServices;
using System.Runtime.Versioning;
+ using System.Diagnostics;
using System.Diagnostics.Contracts;
using System.Security;
using System.Runtime;
// respecting types. This calls memmove internally. The count and
// offset parameters here are in bytes. If you want to use traditional
// array element indices and counts, use Array.Copy.
- [System.Security.SecuritySafeCritical] // auto-generated
[MethodImplAttribute(MethodImplOptions.InternalCall)]
public static extern void BlockCopy(Array src, int srcOffset,
Array dst, int dstOffset, int count);
// parameter validation has already been done. The count and offset
// parameters here are in bytes. If you want to use traditional
// array element indices and counts, use Array.Copy.
- [System.Security.SecuritySafeCritical] // auto-generated
[MethodImplAttribute(MethodImplOptions.InternalCall)]
internal static extern void InternalBlockCopy(Array src, int srcOffsetBytes,
Array dst, int dstOffsetBytes, int byteCount);
// It is however cross platform as the CRT hasn't ported their fast version to 64-bit
// platforms.
//
- [System.Security.SecurityCritical] // auto-generated
internal unsafe static int IndexOfByte(byte* src, byte value, int index, int count)
{
- Contract.Assert(src != null, "src should not be null");
+ Debug.Assert(src != null, "src should not be null");
byte* pByte = src + index;
// Returns a bool to indicate if the array is of primitive data types
// or not.
- [System.Security.SecurityCritical] // auto-generated
[MethodImplAttribute(MethodImplOptions.InternalCall)]
private static extern bool IsPrimitiveTypeArray(Array array);
// This essentially does the following:
// return ((byte*)array) + index.
//
- [System.Security.SecurityCritical] // auto-generated
[MethodImplAttribute(MethodImplOptions.InternalCall)]
private static extern byte _GetByte(Array array, int index);
- [System.Security.SecuritySafeCritical] // auto-generated
public static byte GetByte(Array array, int index)
{
// Is the array present?
// This essentially does the following:
// *(((byte*)array) + index) = value.
//
- [System.Security.SecurityCritical] // auto-generated
[MethodImplAttribute(MethodImplOptions.InternalCall)]
private static extern void _SetByte(Array array, int index, byte value);
- [System.Security.SecuritySafeCritical] // auto-generated
public static void SetByte(Array array, int index, byte value)
{
// Is the array present?
// This essentially does the following:
// return array.length * sizeof(array.UnderlyingElementType).
//
- [System.Security.SecurityCritical] // auto-generated
[MethodImplAttribute(MethodImplOptions.InternalCall)]
private static extern int _ByteLength(Array array);
- [System.Security.SecuritySafeCritical] // auto-generated
public static int ByteLength(Array array)
{
// Is the array present?
return _ByteLength(array);
}
- [System.Security.SecurityCritical] // auto-generated
internal unsafe static void ZeroMemory(byte* src, long len)
{
while(len-- > 0)
*(src + len) = 0;
}
- [System.Security.SecurityCritical] // auto-generated
[ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)]
internal unsafe static void Memcpy(byte[] dest, int destIndex, byte* src, int srcIndex, int len) {
- Contract.Assert( (srcIndex >= 0) && (destIndex >= 0) && (len >= 0), "Index and length must be non-negative!");
- Contract.Assert(dest.Length - destIndex >= len, "not enough bytes in dest");
+ Debug.Assert( (srcIndex >= 0) && (destIndex >= 0) && (len >= 0), "Index and length must be non-negative!");
+ Debug.Assert(dest.Length - destIndex >= len, "not enough bytes in dest");
// If dest has 0 elements, the fixed statement will throw an
// IndexOutOfRangeException. Special-case 0-byte copies.
if (len==0)
}
}
- [SecurityCritical]
[ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)]
internal unsafe static void Memcpy(byte* pDest, int destIndex, byte[] src, int srcIndex, int len)
{
- Contract.Assert( (srcIndex >= 0) && (destIndex >= 0) && (len >= 0), "Index and length must be non-negative!");
- Contract.Assert(src.Length - srcIndex >= len, "not enough bytes in src");
+ Debug.Assert( (srcIndex >= 0) && (destIndex >= 0) && (len >= 0), "Index and length must be non-negative!");
+ Debug.Assert(src.Length - srcIndex >= len, "not enough bytes in src");
// If dest has 0 elements, the fixed statement will throw an
// IndexOutOfRangeException. Special-case 0-byte copies.
if (len==0)
// 1. This method is given access to other internal dlls and this close to release we do not want to change it.
// 2. It is difficult to get this right for arm and again due to release dates we would like to visit it later.
[FriendAccessAllowed]
- [System.Security.SecurityCritical]
[ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)]
#if ARM
[MethodImplAttribute(MethodImplOptions.InternalCall)]
#else // ARM
[MethodImplAttribute(MethodImplOptions.AggressiveInlining)]
internal unsafe static void Memcpy(byte* dest, byte* src, int len) {
- Contract.Assert(len >= 0, "Negative length in memcopy!");
+ Debug.Assert(len >= 0, "Negative length in memcopy!");
Memmove(dest, src, (uint)len);
}
#endif // ARM
// This method has different signature for x64 and other platforms and is done for performance reasons.
- [System.Security.SecurityCritical]
[ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)]
internal unsafe static void Memmove(byte* dest, byte* src, nuint len)
{
// We know due to the above switch-case that this loop will always run 1 iteration; max
// bytes we copy before checking is 23 (7 to align the pointers, 16 for 1 iteration) so
// the switch handles lengths 0-22.
- Contract.Assert(end >= 7 && i <= end);
+ Debug.Assert(end >= 7 && i <= end);
// This is separated out into a different variable, so the i + 16 addition can be
// performed at the start of the pipeline and the loop condition does not have
// Non-inlinable wrapper around the QCall that avoids poluting the fast path
// with P/Invoke prolog/epilog.
- [SecurityCritical]
[ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)]
[MethodImplAttribute(MethodImplOptions.NoInlining)]
private unsafe static void _Memmove(byte* dest, byte* src, nuint len)
[DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
[SuppressUnmanagedCodeSecurity]
- [SecurityCritical]
[ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)]
extern private unsafe static void __Memmove(byte* dest, byte* src, nuint len);
// The attributes on this method are chosen for best JIT performance.
// Please do not edit unless intentional.
- [System.Security.SecurityCritical]
[MethodImplAttribute(MethodImplOptions.AggressiveInlining)]
[CLSCompliant(false)]
public static unsafe void MemoryCopy(void* source, void* destination, long destinationSizeInBytes, long sourceBytesToCopy)
// The attributes on this method are chosen for best JIT performance.
// Please do not edit unless intentional.
- [System.Security.SecurityCritical]
[MethodImplAttribute(MethodImplOptions.AggressiveInlining)]
[CLSCompliant(false)]
public static unsafe void MemoryCopy(void* source, void* destination, ulong destinationSizeInBytes, ulong sourceBytesToCopy)
}
[Pure]
- [System.Security.SecuritySafeCritical] // auto-generated
public override String ToString() {
Contract.Ensures(Contract.Result<String>() != null);
return Number.FormatInt32(m_value, null, NumberFormatInfo.CurrentInfo);
}
[Pure]
- [System.Security.SecuritySafeCritical] // auto-generated
public String ToString(String format) {
Contract.Ensures(Contract.Result<String>() != null);
return Number.FormatInt32(m_value, format, NumberFormatInfo.CurrentInfo);
}
[Pure]
- [System.Security.SecuritySafeCritical] // auto-generated
public String ToString(IFormatProvider provider) {
Contract.Ensures(Contract.Result<String>() != null);
return Number.FormatInt32(m_value, null, NumberFormatInfo.GetInstance(provider));
}
[Pure]
- [System.Security.SecuritySafeCritical] // auto-generated
public String ToString(String format, IFormatProvider provider) {
Contract.Ensures(Contract.Result<String>() != null);
return Number.FormatInt32(m_value, format, NumberFormatInfo.GetInstance(provider));
internal class CLRConfig {
[FriendAccessAllowed]
- [System.Security.SecurityCritical]
[MethodImplAttribute(MethodImplOptions.InternalCall)]
[SuppressUnmanagedCodeSecurity]
internal static extern bool CheckLegacyManagedDeflateStream();
- [System.Security.SecurityCritical]
[MethodImplAttribute(MethodImplOptions.InternalCall)]
[SuppressUnmanagedCodeSecurity]
internal static extern bool CheckThrowUnobservedTaskExceptions();
int textLength,
int prefixLength);
- [System.Security.SecurityCritical] // auto-generated
[MethodImplAttribute(MethodImplOptions.InternalCall)]
internal extern void RunParser(String fileName);
}
return Parse(fileName, configPath, false);
}
- [System.Security.SecuritySafeCritical] // auto-generated
internal ConfigNode Parse(String fileName, String configPath, bool skipSecurityStuff)
{
if (fileName == null)
// Neither Exception nor ApplicationException are the "right" exceptions here.
// Desktop throws ApplicationException for backwards compatibility.
// On Silverlight we don't have ApplicationException, so fall back to Exception.
-#if FEATURE_CORECLR
throw new Exception(message, inner);
-#else
- throw new ApplicationException(message, inner);
-#endif
}
return rootNode;
}
// Neither Exception nor ApplicationException are the "right" exceptions here.
// Desktop throws ApplicationException for backwards compatibility.
// On Silverlight we don't have ApplicationException, so fall back to Exception.
-#if FEATURE_CORECLR
throw new Exception(message);
-#else
- throw new ApplicationException(message);
-#endif
}
}
}
using System.Runtime;
using System.Runtime.InteropServices;
using System.Runtime.CompilerServices;
+ using System.Diagnostics;
using System.Diagnostics.Contracts;
[System.Runtime.InteropServices.ComVisible(true)]
// Return the Unicode category for Unicode character <= 0x00ff.
private static UnicodeCategory GetLatin1UnicodeCategory(char ch) {
- Contract.Assert(IsLatin1(ch), "Char.GetLatin1UnicodeCategory(): ch should be <= 007f");
+ Debug.Assert(IsLatin1(ch), "Char.GetLatin1UnicodeCategory(): ch should be <= 007f");
return (UnicodeCategory)(categoryForLatin1[(int)ch]);
}
** Convert an UTF32 value into a surrogate pair.
==============================================================================*/
- [System.Security.SecuritySafeCritical]
public static String ConvertFromUtf32(int utf32)
{
// For UTF32 values from U+00D800 ~ U+00DFFF, we should throw. They
// of the ArrayList is automatically increased as required by reallocating the
// internal array.
//
-#if FEATURE_CORECLR
[FriendAccessAllowed]
-#endif
[DebuggerTypeProxy(typeof(System.Collections.ArrayList.ArrayListDebugView))]
[DebuggerDisplay("Count = {Count}")]
[Serializable]
// Returns a read-only IList wrapper for the given IList.
//
-#if FEATURE_CORECLR
[FriendAccessAllowed]
-#endif
public static IList ReadOnly(IList list) {
if (list==null)
throw new ArgumentNullException(nameof(list));
// Returns a thread-safe wrapper around an IList.
//
- [HostProtection(Synchronization=true)]
public static IList Synchronized(IList list) {
if (list==null)
throw new ArgumentNullException(nameof(list));
// Returns a thread-safe wrapper around a ArrayList.
//
- [HostProtection(Synchronization=true)]
public static ArrayList Synchronized(ArrayList list) {
if (list==null)
throw new ArgumentNullException(nameof(list));
// downcasting all elements. This copy may fail and is an O(n) operation.
// Internally, this implementation calls Array.Copy.
//
- [SecuritySafeCritical]
public virtual Array ToArray(Type type) {
if (type==null)
throw new ArgumentNullException(nameof(type));
return array;
}
- [SecuritySafeCritical]
public override Array ToArray(Type type)
{
if (type==null)
return array;
}
- [SecuritySafeCritical]
public override Array ToArray(Type type) {
if (type==null)
throw new ArgumentNullException(nameof(type));
throw new ArgumentException(Environment.GetResourceString("Argument_ImplementIComparable"));
}
- [System.Security.SecurityCritical] // auto-generated_required
public void GetObjectData(SerializationInfo info, StreamingContext context) {
if (info==null) {
throw new ArgumentNullException(nameof(info));
namespace System.Collections.Concurrent
{
-
/// <summary>
/// Represents a thread-safe collection of keys and values.
/// </summary>
/// All public and protected members of <see cref="ConcurrentDictionary{TKey,TValue}"/> are thread-safe and may be used
/// concurrently from multiple threads.
/// </remarks>
-#if !FEATURE_CORECLR
- [Serializable]
-#endif
[ComVisible(false)]
[DebuggerTypeProxy(typeof(Mscorlib_DictionaryDebugView<,>))]
[DebuggerDisplay("Count = {Count}")]
- [HostProtection(Synchronization = true, ExternalThreading = true)]
public class ConcurrentDictionary<TKey, TValue> : IDictionary<TKey, TValue>, IDictionary, IReadOnlyDictionary<TKey, TValue>
{
/// <summary>
m_comparer = comparer;
}
}
-#if !FEATURE_CORECLR
- [NonSerialized]
-#endif
+
private volatile Tables m_tables; // Internal tables of the dictionary
// NOTE: this is only used for compat reasons to serialize the comparer.
// This should not be accessed from anywhere else outside of the serialization methods.
internal IEqualityComparer<TKey> m_comparer;
-#if !FEATURE_CORECLR
- [NonSerialized]
-#endif
private readonly bool m_growLockArray; // Whether to dynamically increase the size of the striped lock
// How many times we resized becaused of collisions.
// This is used to make sure we don't resize the dictionary because of multi-threaded Add() calls
// that generate collisions. Whenever a GrowTable() should be the only place that changes this
-#if !FEATURE_CORECLR
- // The field should be have been marked as NonSerialized but because we shipped it without that attribute in 4.5.1.
- // we can't add it back without breaking compat. To maximize compat we are going to keep the OptionalField attribute
- // This will prevent cases where the field was not serialized.
- [OptionalField]
-#endif
private int m_keyRehashCount;
-#if !FEATURE_CORECLR
- [NonSerialized]
-#endif
private int m_budget; // The maximum number of elements per lock before a resize operation is triggered
-#if !FEATURE_CORECLR // These fields are not used in CoreCLR
- private KeyValuePair<TKey, TValue>[] m_serializationArray; // Used for custom serialization
-
- private int m_serializationConcurrencyLevel; // used to save the concurrency level in serialization
-
- private int m_serializationCapacity; // used to save the capacity in serialization
-#endif
// The default concurrency level is DEFAULT_CONCURRENCY_MULTIPLIER * #CPUs. The higher the
// DEFAULT_CONCURRENCY_MULTIPLIER, the more concurrent writes can take place without interference
// and blocking, but also the more expensive operations that require all locks become (e.g. table
bool resizeDesired = false;
bool lockTaken = false;
-#if FEATURE_RANDOMIZED_STRING_HASHING
-#if !FEATURE_CORECLR
- bool resizeDueToCollisions = false;
-#endif // !FEATURE_CORECLR
-#endif
try
{
continue;
}
-#if FEATURE_RANDOMIZED_STRING_HASHING
-#if !FEATURE_CORECLR
- int collisionCount = 0;
-#endif // !FEATURE_CORECLR
-#endif
-
// Try to find this key in the bucket
Node prev = null;
for (Node node = tables.m_buckets[bucketNo]; node != null; node = node.m_next)
return false;
}
prev = node;
-
-#if FEATURE_RANDOMIZED_STRING_HASHING
-#if !FEATURE_CORECLR
- collisionCount++;
-#endif // !FEATURE_CORECLR
-#endif
}
-#if FEATURE_RANDOMIZED_STRING_HASHING
-#if !FEATURE_CORECLR
- if(collisionCount > HashHelpers.HashCollisionThreshold && HashHelpers.IsWellKnownEqualityComparer(comparer))
- {
- resizeDesired = true;
- resizeDueToCollisions = true;
- }
-#endif // !FEATURE_CORECLR
-#endif
-
// The key was not found in the bucket. Insert the key-value pair.
Volatile.Write<Node>(ref tables.m_buckets[bucketNo], new Node(key, value, hashcode, tables.m_buckets[bucketNo]));
checked
if (resizeDesired)
{
#if FEATURE_RANDOMIZED_STRING_HASHING
-#if !FEATURE_CORECLR
- if (resizeDueToCollisions)
- {
- GrowTable(tables, (IEqualityComparer<TKey>)HashHelpers.GetRandomizedEqualityComparer(comparer), true, m_keyRehashCount);
- }
- else
-#endif // !FEATURE_CORECLR
- {
- GrowTable(tables, tables.m_comparer, false, m_keyRehashCount);
- }
+ GrowTable(tables, tables.m_comparer, false, m_keyRehashCount);
#else
GrowTable(tables, tables.m_comparer, false, m_keyRehashCount);
#endif
/// </summary>
private void AcquireAllLocks(ref int locksAcquired)
{
-#if !FEATURE_CORECLR
- if (CDSCollectionETWBCLProvider.Log.IsEnabled())
- {
- CDSCollectionETWBCLProvider.Log.ConcurrentDictionary_AcquiringAllLocks(m_tables.m_buckets.Length);
- }
-#endif //!FEATURE_CORECLR
-
// First, acquire lock 0
AcquireLocks(0, 1, ref locksAcquired);
[Conditional("DEBUG")]
private void Assert(bool condition)
{
- Contract.Assert(condition);
+ Debug.Assert(condition);
}
/// <summary>
m_enumerator.Reset();
}
}
-
-#if !FEATURE_CORECLR
- /// <summary>
- /// Get the data array to be serialized
- /// </summary>
- [OnSerializing]
- private void OnSerializing(StreamingContext context)
- {
- Tables tables = m_tables;
-
- // save the data into the serialization array to be saved
- m_serializationArray = ToArray();
- m_serializationConcurrencyLevel = tables.m_locks.Length;
- m_serializationCapacity = tables.m_buckets.Length;
- m_comparer = (IEqualityComparer<TKey>)HashHelpers.GetEqualityComparerForSerialization(tables.m_comparer);
- }
-
- /// <summary>
- /// Construct the dictionary from a previously serialized one
- /// </summary>
- [OnDeserialized]
- private void OnDeserialized(StreamingContext context)
- {
- KeyValuePair<TKey, TValue>[] array = m_serializationArray;
-
- var buckets = new Node[m_serializationCapacity];
- var countPerLock = new int[m_serializationConcurrencyLevel];
-
- var locks = new object[m_serializationConcurrencyLevel];
- for (int i = 0; i < locks.Length; i++)
- {
- locks[i] = new object();
- }
-
- m_tables = new Tables(buckets, locks, countPerLock, m_comparer);
-
- InitializeFromCollection(array);
- m_serializationArray = null;
-
- }
-#endif
}
}
[ComVisible(false)]
[DebuggerDisplay("Count = {Count}")]
[DebuggerTypeProxy(typeof(SystemCollectionsConcurrent_ProducerConsumerCollectionDebugView<>))]
- [HostProtection(Synchronization = true, ExternalThreading = true)]
[Serializable]
public class ConcurrentQueue<T> : IProducerConsumerCollection<T>, IReadOnlyCollection<T>
{
int index = 0;
foreach (T element in collection)
{
- Contract.Assert(index >= 0 && index < SEGMENT_SIZE);
+ Debug.Assert(index >= 0 && index < SEGMENT_SIZE);
localTail.UnsafeAdd(element);
index++;
[OnDeserialized]
private void OnDeserialized(StreamingContext context)
{
- Contract.Assert(m_serializationArray != null);
+ Debug.Assert(m_serializationArray != null);
InitializeFromCollection(m_serializationArray);
m_serializationArray = null;
}
m_array = new T[SEGMENT_SIZE];
m_state = new VolatileBool[SEGMENT_SIZE]; //all initialized to false
m_high = -1;
- Contract.Assert(index >= 0);
+ Debug.Assert(index >= 0);
m_index = index;
m_source = source;
}
/// <param name="value"></param>
internal void UnsafeAdd(T value)
{
- Contract.Assert(m_high < SEGMENT_SIZE - 1);
+ Debug.Assert(m_high < SEGMENT_SIZE - 1);
m_high++;
m_array[m_high] = value;
m_state[m_high].m_value = true;
/// <returns>the reference to the new Segment</returns>
internal Segment UnsafeGrow()
{
- Contract.Assert(m_high >= SEGMENT_SIZE - 1);
+ Debug.Assert(m_high >= SEGMENT_SIZE - 1);
Segment newSegment = new Segment(m_index + 1, m_source); //m_index is Int64, we don't need to worry about overflow
m_next = newSegment;
return newSegment;
//no CAS is needed, since there is no contention (other threads are blocked, busy waiting)
Segment newSegment = new Segment(m_index + 1, m_source); //m_index is Int64, we don't need to worry about overflow
m_next = newSegment;
- Contract.Assert(m_source.m_tail == this);
+ Debug.Assert(m_source.m_tail == this);
m_source.m_tail = m_next;
}
{
spinLocal.SpinOnce();
}
- Contract.Assert(m_source.m_head == this);
+ Debug.Assert(m_source.m_head == this);
m_source.m_head = m_next;
}
return true;
/// </remarks>
[DebuggerDisplay("Count = {Count}")]
[DebuggerTypeProxy(typeof(SystemCollectionsConcurrent_ProducerConsumerCollectionDebugView<>))]
- [HostProtection(Synchronization = true, ExternalThreading = true)]
-#if !FEATURE_CORECLR
- [Serializable]
-#endif //!FEATURE_CORECLR
public class ConcurrentStack<T> : IProducerConsumerCollection<T>, IReadOnlyCollection<T>
{
/// <summary>
}
}
-#if !FEATURE_CORECLR
- [NonSerialized]
-#endif //!FEATURE_CORECLR
private volatile Node m_head; // The stack is a singly linked list, and only remembers the head.
-#if !FEATURE_CORECLR
- private T[] m_serializationArray; // Used for custom serialization.
-#endif //!FEATURE_CORECLR
-
private const int BACKOFF_MAX_YIELDS = 8; // Arbitrary number to cap backoff.
/// <summary>
m_head = lastNode;
}
-#if !FEATURE_CORECLR
- /// <summary>
- /// Get the data array to be serialized
- /// </summary>
- [OnSerializing]
- private void OnSerializing(StreamingContext context)
- {
- // save the data into the serialization array to be saved
- m_serializationArray = ToArray();
- }
-
- /// <summary>
- /// Construct the stack from a previously seiralized one
- /// </summary>
- [OnDeserialized]
- private void OnDeserialized(StreamingContext context)
- {
- Contract.Assert(m_serializationArray != null);
- // Add the elements to our stack. We need to add them from head-to-tail, to
- // preserve the original ordering of the stack before serialization.
- Node prevNode = null;
- Node head = null;
- for (int i = 0; i < m_serializationArray.Length; i++)
- {
- Node currNode = new Node(m_serializationArray[i]);
-
- if (prevNode == null)
- {
- head = currNode;
- }
- else
- {
- prevNode.m_next = currNode;
- }
-
- prevNode = currNode;
- }
-
- m_head = head;
- m_serializationArray = null;
- }
-#endif //!FEATURE_CORECLR
-
-
/// <summary>
/// Gets a value that indicates whether the <see cref="ConcurrentStack{T}"/> is empty.
/// </summary>
}
}
-
/// <summary>
/// Gets a value indicating whether access to the <see cref="T:System.Collections.ICollection"/> is
/// synchronized with the SyncRoot.
}
while (Interlocked.CompareExchange(
ref m_head, head, tail.m_next) != tail.m_next);
-
-#if !FEATURE_CORECLR
- if (CDSCollectionETWBCLProvider.Log.IsEnabled())
- {
- CDSCollectionETWBCLProvider.Log.ConcurrentStack_FastPushFailed(spin.Count);
- }
-#endif // !FEATURE_CORECLR
}
/// <summary>
// Is the stack empty?
if (head == null)
{
-#if !FEATURE_CORECLR
- if (count == 1 && CDSCollectionETWBCLProvider.Log.IsEnabled())
- {
- CDSCollectionETWBCLProvider.Log.ConcurrentStack_FastPopFailed(spin.Count);
- }
-#endif //!FEATURE_CORECLR
poppedHead = null;
return 0;
}
// Try to swap the new head. If we succeed, break out of the loop.
if (Interlocked.CompareExchange(ref m_head, next.m_next, head) == head)
{
-#if !FEATURE_CORECLR
- if (count == 1 && CDSCollectionETWBCLProvider.Log.IsEnabled())
- {
- CDSCollectionETWBCLProvider.Log.ConcurrentStack_FastPopFailed(spin.Count);
- }
-#endif //!FEATURE_CORECLR
// Return the popped Node.
poppedHead = head;
return nodesCount;
/// </ol>
/// </para>
/// </remarks>
- [HostProtection(Synchronization = true, ExternalThreading = true)]
public abstract class OrderablePartitioner<TSource> : Partitioner<TSource>
{
/// <summary>
/// </ol>
/// </para>
/// </remarks>
- [HostProtection(Synchronization = true, ExternalThreading = true)]
public abstract class Partitioner<TSource>
{
/// <summary>
using System.Collections.Generic;
using System.Security.Permissions;
using System.Threading;
+using System.Diagnostics;
using System.Diagnostics.Contracts;
using System.Runtime.InteropServices;
/// non-blocking. These behaviors can be overridden via this enumeration.
/// </summary>
[Flags]
-#if !FEATURE_CORECLR
- [Serializable]
-#endif
public enum EnumerablePartitionerOptions
{
/// <summary>
/// thread.
/// </para>
/// </remarks>
- [HostProtection(Synchronization = true, ExternalThreading = true)]
public static class Partitioner
{
/// <summary>
//perform deferred allocating of the local variables.
if (m_localOffset == null)
{
- Contract.Assert(m_currentChunkSize == null);
+ Debug.Assert(m_currentChunkSize == null);
m_localOffset = new SharedInt(-1);
m_currentChunkSize = new SharedInt(0);
m_doublingCountdown = CHUNK_DOUBLING_RATE;
{
// The second part of the || condition is necessary to handle the case when MoveNext() is called
// after a previous MoveNext call returned false.
- Contract.Assert(m_localOffset.Value == m_currentChunkSize.Value - 1 || m_currentChunkSize.Value == 0);
+ Debug.Assert(m_localOffset.Value == m_currentChunkSize.Value - 1 || m_currentChunkSize.Value == 0);
//set the requested chunk size to a proper value
int requestedChunkSize;
// Decrement your doubling countdown
m_doublingCountdown--;
- Contract.Assert(requestedChunkSize > 0 && requestedChunkSize <= m_maxChunkSize);
+ Debug.Assert(requestedChunkSize > 0 && requestedChunkSize <= m_maxChunkSize);
//GrabNextChunk will update the value of m_currentChunkSize
if (GrabNextChunk(requestedChunkSize))
{
- Contract.Assert(m_currentChunkSize.Value <= requestedChunkSize && m_currentChunkSize.Value > 0);
+ Debug.Assert(m_currentChunkSize.Value <= requestedChunkSize && m_currentChunkSize.Value > 0);
m_localOffset.Value = 0;
return true;
}
/// </returns>
internal bool GrabChunk_Single(KeyValuePair<long,TSource>[] destArray, int requestedChunkSize, ref int actualNumElementsGrabbed)
{
- Contract.Assert(m_useSingleChunking, "Expected m_useSingleChecking to be true");
- Contract.Assert(requestedChunkSize == 1, "Got requested chunk size of " + requestedChunkSize + " when single-chunking was on");
- Contract.Assert(actualNumElementsGrabbed == 0, "Expected actualNumElementsGrabbed == 0, instead it is " + actualNumElementsGrabbed);
- Contract.Assert(destArray.Length == 1, "Expected destArray to be of length 1, instead its length is " + destArray.Length);
+ Debug.Assert(m_useSingleChunking, "Expected m_useSingleChecking to be true");
+ Debug.Assert(requestedChunkSize == 1, "Got requested chunk size of " + requestedChunkSize + " when single-chunking was on");
+ Debug.Assert(actualNumElementsGrabbed == 0, "Expected actualNumElementsGrabbed == 0, instead it is " + actualNumElementsGrabbed);
+ Debug.Assert(destArray.Length == 1, "Expected destArray to be of length 1, instead its length is " + destArray.Length);
lock (m_sharedLock)
{
/// </returns>
internal bool GrabChunk_Buffered(KeyValuePair<long,TSource>[] destArray, int requestedChunkSize, ref int actualNumElementsGrabbed)
{
- Contract.Assert(requestedChunkSize > 0);
- Contract.Assert(!m_useSingleChunking, "Did not expect to be in single-chunking mode");
+ Debug.Assert(requestedChunkSize > 0);
+ Debug.Assert(!m_useSingleChunking, "Did not expect to be in single-chunking mode");
TryCopyFromFillBuffer(destArray, requestedChunkSize, ref actualNumElementsGrabbed);
while( m_activeCopiers > 0) sw.SpinOnce();
}
- Contract.Assert(m_sharedIndex != null); //already been allocated in MoveNext() before calling GrabNextChunk
+ Debug.Assert(m_sharedIndex != null); //already been allocated in MoveNext() before calling GrabNextChunk
// Now's the time to actually enumerate the source
/// </returns>
override protected bool GrabNextChunk(int requestedChunkSize)
{
- Contract.Assert(requestedChunkSize > 0);
+ Debug.Assert(requestedChunkSize > 0);
if (HasNoElementsLeft)
{
{
//we only set it from false to true once
//we should never set it back in any circumstances
- Contract.Assert(value);
- Contract.Assert(!m_hasNoElementsLeft.Value);
+ Debug.Assert(value);
+ Debug.Assert(!m_hasNoElementsLeft.Value);
m_hasNoElementsLeft.Value = true;
}
}
{
throw new InvalidOperationException(Environment.GetResourceString("PartitionerStatic_CurrentCalledBeforeMoveNext"));
}
- Contract.Assert(m_localList != null);
- Contract.Assert(m_localOffset.Value >= 0 && m_localOffset.Value < m_currentChunkSize.Value);
+ Debug.Assert(m_localList != null);
+ Debug.Assert(m_localOffset.Value >= 0 && m_localOffset.Value < m_currentChunkSize.Value);
return (m_localList[m_localOffset.Value]);
}
}
/// </returns>
override protected bool GrabNextChunk(int requestedChunkSize)
{
- Contract.Assert(requestedChunkSize > 0);
+ Debug.Assert(requestedChunkSize > 0);
while (!HasNoElementsLeft)
{
- Contract.Assert(m_sharedIndex != null);
+ Debug.Assert(m_sharedIndex != null);
// use the new Volatile.Read method because it is cheaper than Interlocked.Read on AMD64 architecture
long oldSharedIndex = Volatile.Read(ref m_sharedIndex.Value);
{
get
{
- Contract.Assert(m_sharedIndex != null);
+ Debug.Assert(m_sharedIndex != null);
// use the new Volatile.Read method because it is cheaper than Interlocked.Read on AMD64 architecture
return Volatile.Read(ref m_sharedIndex.Value) >= SourceCount - 1;
}
set
{
- Contract.Assert(false);
+ Debug.Assert(false);
}
}
throw new InvalidOperationException(Environment.GetResourceString("PartitionerStatic_CurrentCalledBeforeMoveNext"));
}
- Contract.Assert(m_localOffset.Value >= 0 && m_localOffset.Value < m_currentChunkSize.Value);
+ Debug.Assert(m_localOffset.Value >= 0 && m_localOffset.Value < m_currentChunkSize.Value);
return new KeyValuePair<long, TSource>(m_startIndex + m_localOffset.Value,
m_sharedReader[m_startIndex + m_localOffset.Value]);
}
throw new InvalidOperationException(Environment.GetResourceString("PartitionerStatic_CurrentCalledBeforeMoveNext"));
}
- Contract.Assert(m_localOffset.Value >= 0 && m_localOffset.Value < m_currentChunkSize.Value);
+ Debug.Assert(m_localOffset.Value >= 0 && m_localOffset.Value < m_currentChunkSize.Value);
return new KeyValuePair<long, TSource>(m_startIndex + m_localOffset.Value,
m_sharedReader[m_startIndex + m_localOffset.Value]);
}
internal StaticIndexRangePartitionerForIList(IList<TSource> list)
: base()
{
- Contract.Assert(list != null);
+ Debug.Assert(list != null);
m_list = list;
}
override protected int SourceCount
internal StaticIndexRangePartitionForIList(IList<TSource> list, int startIndex, int endIndex)
: base(startIndex, endIndex)
{
- Contract.Assert(startIndex >= 0 && endIndex <= list.Count - 1);
+ Debug.Assert(startIndex >= 0 && endIndex <= list.Count - 1);
m_list = list;
}
throw new InvalidOperationException(Environment.GetResourceString("PartitionerStatic_CurrentCalledBeforeMoveNext"));
}
- Contract.Assert(m_offset >= m_startIndex && m_offset <= m_endIndex);
+ Debug.Assert(m_offset >= m_startIndex && m_offset <= m_endIndex);
return (new KeyValuePair<long, TSource>(m_offset, m_list[m_offset]));
}
}
internal StaticIndexRangePartitionerForArray(TSource[] array)
: base()
{
- Contract.Assert(array != null);
+ Debug.Assert(array != null);
m_array = array;
}
override protected int SourceCount
internal StaticIndexRangePartitionForArray(TSource[] array, int startIndex, int endIndex)
: base(startIndex, endIndex)
{
- Contract.Assert(startIndex >= 0 && endIndex <= array.Length - 1);
+ Debug.Assert(startIndex >= 0 && endIndex <= array.Length - 1);
m_array = array;
}
throw new InvalidOperationException(Environment.GetResourceString("PartitionerStatic_CurrentCalledBeforeMoveNext"));
}
- Contract.Assert(m_offset >= m_startIndex && m_offset <= m_endIndex);
+ Debug.Assert(m_offset >= m_startIndex && m_offset <= m_endIndex);
return (new KeyValuePair<long, TSource>(m_offset, m_array[m_offset]));
}
}
if (typeof(TSource).IsValueType)
{
-#if !FEATURE_CORECLR // Marshal.SizeOf is not supported in CoreCLR
-
- if (typeof(TSource).StructLayoutAttribute.Value == LayoutKind.Explicit)
- {
- chunkSize = Math.Max(1, DEFAULT_BYTES_PER_CHUNK / Marshal.SizeOf(typeof(TSource)));
- }
- else
- {
- // We choose '128' because this ensures, no matter the actual size of the value type,
- // the total bytes used will be a multiple of 128. This ensures it's cache aligned.
- chunkSize = 128;
- }
-#else
chunkSize = 128;
-#endif
}
else
{
- Contract.Assert((DEFAULT_BYTES_PER_CHUNK % IntPtr.Size) == 0, "bytes per chunk should be a multiple of pointer size");
+ Debug.Assert((DEFAULT_BYTES_PER_CHUNK % IntPtr.Size) == 0, "bytes per chunk should be a multiple of pointer size");
chunkSize = (DEFAULT_BYTES_PER_CHUNK / IntPtr.Size);
}
return chunkSize;
}
#endregion
-
}
}
using System;
using System.Globalization;
using System.Runtime.CompilerServices;
+ using System.Diagnostics;
using System.Diagnostics.Contracts;
using System.Runtime.Versioning;
}
}
- [System.Security.SecuritySafeCritical] // auto-generated
private static IArraySortHelper<T> CreateArraySortHelper()
{
if (typeof(IComparable<T>).IsAssignableFrom(typeof(T)))
public void Sort(T[] keys, int index, int length, IComparer<T> comparer)
{
- Contract.Assert(keys != null, "Check the arguments in the caller!");
- Contract.Assert( index >= 0 && length >= 0 && (keys.Length - index >= length), "Check the arguments in the caller!");
+ Debug.Assert(keys != null, "Check the arguments in the caller!");
+ Debug.Assert( index >= 0 && length >= 0 && (keys.Length - index >= length), "Check the arguments in the caller!");
// Add a try block here to detect IComparers (or their
// underlying IComparables, etc) that are bogus.
internal static void Sort(T[] keys, int index, int length, Comparison<T> comparer)
{
- Contract.Assert(keys != null, "Check the arguments in the caller!");
- Contract.Assert(index >= 0 && length >= 0 && (keys.Length - index >= length), "Check the arguments in the caller!");
- Contract.Assert(comparer != null, "Check the arguments in the caller!");
+ Debug.Assert(keys != null, "Check the arguments in the caller!");
+ Debug.Assert(index >= 0 && length >= 0 && (keys.Length - index >= length), "Check the arguments in the caller!");
+ Debug.Assert(comparer != null, "Check the arguments in the caller!");
// Add a try block here to detect bogus comparisons
try
public void Sort(T[] keys, int index, int length, IComparer<T> comparer)
{
- Contract.Assert(keys != null, "Check the arguments in the caller!");
- Contract.Assert(index >= 0 && length >= 0 && (keys.Length - index >= length), "Check the arguments in the caller!");
+ Debug.Assert(keys != null, "Check the arguments in the caller!");
+ Debug.Assert(index >= 0 && length >= 0 && (keys.Length - index >= length), "Check the arguments in the caller!");
try
{
public int BinarySearch(T[] array, int index, int length, T value, IComparer<T> comparer)
{
- Contract.Assert(array != null, "Check the arguments in the caller!");
- Contract.Assert(index >= 0 && length >= 0 && (array.Length - index >= length), "Check the arguments in the caller!");
+ Debug.Assert(array != null, "Check the arguments in the caller!");
+ Debug.Assert(index >= 0 && length >= 0 && (array.Length - index >= length), "Check the arguments in the caller!");
try
{
}
}
- [System.Security.SecuritySafeCritical] // auto-generated
private static IArraySortHelper<TKey, TValue> CreateArraySortHelper()
{
if (typeof(IComparable<TKey>).IsAssignableFrom(typeof(TKey)))
public void Sort(TKey[] keys, TValue[] values, int index, int length, IComparer<TKey> comparer)
{
- Contract.Assert(keys != null, "Check the arguments in the caller!"); // Precondition on interface method
- Contract.Assert(index >= 0 && length >= 0 && (keys.Length - index >= length), "Check the arguments in the caller!");
+ Debug.Assert(keys != null, "Check the arguments in the caller!"); // Precondition on interface method
+ Debug.Assert(index >= 0 && length >= 0 && (keys.Length - index >= length), "Check the arguments in the caller!");
// Add a try block here to detect IComparers (or their
// underlying IComparables, etc) that are bogus.
{
public void Sort(TKey[] keys, TValue[] values, int index, int length, IComparer<TKey> comparer)
{
- Contract.Assert(keys != null, "Check the arguments in the caller!");
- Contract.Assert( index >= 0 && length >= 0 && (keys.Length - index >= length), "Check the arguments in the caller!");
+ Debug.Assert(keys != null, "Check the arguments in the caller!");
+ Debug.Assert( index >= 0 && length >= 0 && (keys.Length - index >= length), "Check the arguments in the caller!");
// Add a try block here to detect IComparers (or their
// underlying IComparables, etc) that are bogus.
using System;
using System.Collections;
using System.Collections.Generic;
+using System.Diagnostics;
using System.Diagnostics.Contracts;
//using System.Globalization;
using System.Runtime.CompilerServices;
// Note that logic in this method is replicated in vm\compile.cpp to ensure that NGen
// saves the right instantiations
//
- [System.Security.SecuritySafeCritical] // auto-generated
private static Comparer<T> CreateComparer()
{
object result = null;
{
public Int32EnumComparer()
{
- Contract.Assert(typeof(T).IsEnum, "This type is only intended to be used to compare enums!");
+ Debug.Assert(typeof(T).IsEnum, "This type is only intended to be used to compare enums!");
}
// Used by the serialization engine.
public override int GetHashCode() =>
GetType().GetHashCode();
- [SecurityCritical]
public void GetObjectData(SerializationInfo info, StreamingContext context)
{
// Previously Comparer<T> was not specialized for enums,
{
public UInt32EnumComparer()
{
- Contract.Assert(typeof(T).IsEnum, "This type is only intended to be used to compare enums!");
+ Debug.Assert(typeof(T).IsEnum, "This type is only intended to be used to compare enums!");
}
// Used by the serialization engine.
public override int GetHashCode() =>
GetType().GetHashCode();
- [SecurityCritical]
public void GetObjectData(SerializationInfo info, StreamingContext context)
{
info.SetType(typeof(ObjectComparer<T>));
{
public Int64EnumComparer()
{
- Contract.Assert(typeof(T).IsEnum, "This type is only intended to be used to compare enums!");
+ Debug.Assert(typeof(T).IsEnum, "This type is only intended to be used to compare enums!");
}
// Used by the serialization engine.
public override int GetHashCode() =>
GetType().GetHashCode();
- [SecurityCritical]
public void GetObjectData(SerializationInfo info, StreamingContext context)
{
info.SetType(typeof(ObjectComparer<T>));
{
public UInt64EnumComparer()
{
- Contract.Assert(typeof(T).IsEnum, "This type is only intended to be used to compare enums!");
+ Debug.Assert(typeof(T).IsEnum, "This type is only intended to be used to compare enums!");
}
// Used by the serialization engine.
public override int GetHashCode() =>
GetType().GetHashCode();
- [SecurityCritical]
public void GetObjectData(SerializationInfo info, StreamingContext context)
{
info.SetType(typeof(ObjectComparer<T>));
if (capacity > 0) Initialize(capacity);
this.comparer = comparer ?? EqualityComparer<TKey>.Default;
-#if FEATURE_RANDOMIZED_STRING_HASHING && FEATURE_CORECLR
+#if FEATURE_RANDOMIZED_STRING_HASHING
if (HashHelpers.s_UseRandomizedStringHashing && comparer == EqualityComparer<string>.Default)
{
this.comparer = (IEqualityComparer<TKey>) NonRandomizedStringEqualityComparer.Default;
}
-#endif // FEATURE_RANDOMIZED_STRING_HASHING && FEATURE_CORECLR
+#endif // FEATURE_RANDOMIZED_STRING_HASHING
}
public Dictionary(IDictionary<TKey,TValue> dictionary): this(dictionary, null) {}
return new Enumerator(this, Enumerator.KeyValuePair);
}
- [System.Security.SecurityCritical] // auto-generated_required
public virtual void GetObjectData(SerializationInfo info, StreamingContext context) {
if (info==null) {
ThrowHelper.ThrowArgumentNullException(ExceptionArgument.info);
for (int i = buckets[targetBucket]; i >= 0; i = entries[i].next) {
if (entries[i].hashCode == hashCode && comparer.Equals(entries[i].key, key)) {
if (add) {
-#if FEATURE_CORECLR
ThrowHelper.ThrowAddingDuplicateWithKeyArgumentException(key);
-#else
- ThrowHelper.ThrowArgumentException(ExceptionResource.Argument_AddingDuplicate);
-#endif
}
entries[i].value = value;
version++;
version++;
#if FEATURE_RANDOMIZED_STRING_HASHING
-
-#if FEATURE_CORECLR
// In case we hit the collision threshold we'll need to switch to the comparer which is using randomized string hashing
// in this case will be EqualityComparer<string>.Default.
// Note, randomized string hashing is turned on by default on coreclr so EqualityComparer<string>.Default will
comparer = (IEqualityComparer<TKey>) EqualityComparer<string>.Default;
Resize(entries.Length, true);
}
-#else
- if(collisionCount > HashHelpers.HashCollisionThreshold && HashHelpers.IsWellKnownEqualityComparer(comparer))
- {
- comparer = (IEqualityComparer<TKey>) HashHelpers.GetRandomizedEqualityComparer(comparer);
- Resize(entries.Length, true);
- }
-#endif // FEATURE_CORECLR
-
#endif
}
}
private void Resize(int newSize, bool forceNewHashCodes) {
- Contract.Assert(newSize >= entries.Length);
+ Debug.Assert(newSize >= entries.Length);
int[] newBuckets = new int[newSize];
for (int i = 0; i < newBuckets.Length; i++) newBuckets[i] = -1;
Entry[] newEntries = new Entry[newSize];
// Note that logic in this method is replicated in vm\compile.cpp to ensure that NGen
// saves the right instantiations
//
- [System.Security.SecuritySafeCritical] // auto-generated
private static EqualityComparer<T> CreateComparer()
{
Contract.Ensures(Contract.Result<EqualityComparer<T>>() != null);
GetType().GetHashCode();
}
-#if FEATURE_CORECLR
// NonRandomizedStringEqualityComparer is the comparer used by default with the Dictionary<string,...>
// As the randomized string hashing is turned on by default on coreclr, we need to keep the performance not affected
// as much as possible in the main stream scenarios like Dictionary<string,>
return obj.GetLegacyNonRandomizedHashCode();
}
}
-#endif // FEATURE_CORECLR
// Performance of IndexOf on byte array is very important for some scenarios.
// We will call the C runtime function memchr, which is optimized.
return b.GetHashCode();
}
- [System.Security.SecuritySafeCritical] // auto-generated
internal unsafe override int IndexOf(byte[] array, byte value, int startIndex, int count) {
if (array==null)
throw new ArgumentNullException(nameof(array));
// This is used by the serialization engine.
protected EnumEqualityComparer(SerializationInfo information, StreamingContext context) { }
- [SecurityCritical]
public void GetObjectData(SerializationInfo info, StreamingContext context) {
// For back-compat we need to serialize the comparers for enums with underlying types other than int as ObjectEqualityComparer
if (Type.GetTypeCode(Enum.GetUnderlyingType(typeof(T))) != TypeCode.Int32) {
// This is used by the serialization engine.
public LongEnumEqualityComparer(SerializationInfo information, StreamingContext context) { }
- [SecurityCritical]
public void GetObjectData(SerializationInfo info, StreamingContext context)
{
// The LongEnumEqualityComparer does not exist on 4.0 so we need to serialize this comparer as ObjectEqualityComparer
}
[Pure]
- [SecuritySafeCritical]
public int GetHashCode(String obj) {
if(obj == null) return 0;
return String.InternalMarvin32HashString(obj, obj.Length, _entropy);
}
[Pure]
- [SecuritySafeCritical]
public int GetHashCode(Object obj) {
if(obj == null) return 0;
}
[Pure]
- [SecuritySafeCritical]
public int GetHashCode(Object obj) {
if(obj == null) return 0;
private void AddEnumerable(IEnumerable<T> enumerable)
{
- Contract.Assert(enumerable != null);
- Contract.Assert(!(enumerable is ICollection<T>), "We should have optimized for this beforehand.");
+ Debug.Assert(enumerable != null);
+ Debug.Assert(!(enumerable is ICollection<T>), "We should have optimized for this beforehand.");
using (IEnumerator<T> en = enumerable.GetEnumerator())
{
using System.Runtime.CompilerServices;
using System.Runtime.ConstrainedExecution;
using System.Diagnostics.Contracts;
-#if !FEATURE_CORECLR
- using System.Security.Cryptography;
-#endif
-
+
// The Hashtable class represents a dictionary of associated keys and values
// with constant lookup time.
//
loadsize = (int)(this.loadFactor * hashsize);
isWriterInProgress = false;
// Based on the current algorithm, loadsize must be less than hashsize.
- Contract.Assert( loadsize < hashsize, "Invalid hashtable loadsize!");
+ Debug.Assert( loadsize < hashsize, "Invalid hashtable loadsize!");
}
// Constructs a new hashtable with the given initial capacity and load
// Removes all entries from this hashtable.
[ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)]
public virtual void Clear() {
- Contract.Assert(!isWriterInProgress, "Race condition detected in usages of Hashtable - multiple threads appear to be writing to a Hashtable instance simultaneously! Don't do that - use Hashtable.Synchronized.");
+ Debug.Assert(!isWriterInProgress, "Race condition detected in usages of Hashtable - multiple threads appear to be writing to a Hashtable instance simultaneously! Don't do that - use Hashtable.Synchronized.");
if (count == 0 && occupancy == 0)
return;
-#if !FEATURE_CORECLR
- Thread.BeginCriticalRegion();
-#endif
isWriterInProgress = true;
for (int i = 0; i < buckets.Length; i++){
buckets[i].hash_coll = 0;
occupancy = 0;
UpdateVersion();
isWriterInProgress = false;
-#if !FEATURE_CORECLR
- Thread.EndCriticalRegion();
-#endif
}
// Clone returns a virtually identical copy of this hash table. This does
} while (b.hash_coll < 0 && ++ntry < lbuckets.Length);
return false;
}
-
-
-
+
// Checks if this hashtable contains an entry with the given value. The
// values of the entries of the hashtable are compared to the given value
// using the Object.Equals method. This method performs a linear
for (nb = 0; nb < buckets.Length; nb++){
bucket oldb = buckets[nb];
if ((oldb.key != null) && (oldb.key != buckets)) {
- int hashcode = ((forceNewHashCode ? GetHash(oldb.key) : oldb.hash_coll) & 0x7FFFFFFF);
+ int hashcode = ((forceNewHashCode ? GetHash(oldb.key) : oldb.hash_coll) & 0x7FFFFFFF);
putEntry(newBuckets, oldb.key, oldb.val, hashcode);
}
}
-
+
// New bucket[] is good to go - replace buckets and other internal state.
-#if !FEATURE_CORECLR
- Thread.BeginCriticalRegion();
-#endif
isWriterInProgress = true;
buckets = newBuckets;
loadsize = (int)(loadFactor * newsize);
UpdateVersion();
isWriterInProgress = false;
-#if !FEATURE_CORECLR
- Thread.EndCriticalRegion();
-#endif
+
// minimun size of hashtable is 3 now and maximum loadFactor is 0.72 now.
- Contract.Assert(loadsize < newsize, "Our current implementaion means this is not possible.");
+ Debug.Assert(loadsize < newsize, "Our current implementaion means this is not possible.");
return;
}
-
+
// Returns an enumerator for this hashtable.
// If modifications made to the hashtable while an enumeration is
// in progress, the MoveNext and Current methods of the
//
protected virtual bool KeyEquals(Object item, Object key)
{
- Contract.Assert(key != null, "key can't be null here!");
+ Debug.Assert(key != null, "key can't be null here!");
if( Object.ReferenceEquals(buckets, item)) {
return false;
}
// We pretty much have to insert in this order. Don't set hash
// code until the value & key are set appropriately.
-#if !FEATURE_CORECLR
- Thread.BeginCriticalRegion();
-#endif
- isWriterInProgress = true;
+ isWriterInProgress = true;
buckets[bucketNumber].val = nvalue;
buckets[bucketNumber].key = key;
buckets[bucketNumber].hash_coll |= (int) hashcode;
count++;
UpdateVersion();
isWriterInProgress = false;
-#if !FEATURE_CORECLR
- Thread.EndCriticalRegion();
-#endif
-#if FEATURE_RANDOMIZED_STRING_HASHING
-#if !FEATURE_CORECLR
- // coreclr has the randomized string hashing on by default so we don't need to resize at this point
-
- if(ntry > HashHelpers.HashCollisionThreshold && HashHelpers.IsWellKnownEqualityComparer(_keycomparer))
- {
- // PERF: We don't want to rehash if _keycomparer is already a RandomizedObjectEqualityComparer since in some
- // cases there may not be any strings in the hashtable and we wouldn't get any mixing.
- if(_keycomparer == null || !(_keycomparer is System.Collections.Generic.RandomizedObjectEqualityComparer))
- {
- _keycomparer = HashHelpers.GetRandomizedEqualityComparer(_keycomparer);
- rehash(buckets.Length, true);
- }
- }
-#endif // !FEATURE_CORECLR
-#endif // FEATURE_RANDOMIZED_STRING_HASHING
return;
}
if (add) {
throw new ArgumentException(Environment.GetResourceString("Argument_AddingDuplicate__", buckets[bucketNumber].key, key));
}
-#if !FEATURE_CORECLR
- Thread.BeginCriticalRegion();
-#endif
- isWriterInProgress = true;
+ isWriterInProgress = true;
buckets[bucketNumber].val = nvalue;
- UpdateVersion();
+ UpdateVersion();
isWriterInProgress = false;
-#if !FEATURE_CORECLR
- Thread.EndCriticalRegion();
-#endif
-
-#if FEATURE_RANDOMIZED_STRING_HASHING
-#if !FEATURE_CORECLR
- if(ntry > HashHelpers.HashCollisionThreshold && HashHelpers.IsWellKnownEqualityComparer(_keycomparer))
- {
- // PERF: We don't want to rehash if _keycomparer is already a RandomizedObjectEqualityComparer since in some
- // cases there may not be any strings in the hashtable and we wouldn't get any mixing.
- if(_keycomparer == null || !(_keycomparer is System.Collections.Generic.RandomizedObjectEqualityComparer))
- {
- _keycomparer = HashHelpers.GetRandomizedEqualityComparer(_keycomparer);
- rehash(buckets.Length, true);
- }
- }
-#endif // !FEATURE_CORECLR
-#endif
return;
}
}
}
- bucketNumber = (int) (((long)bucketNumber + incr)% (uint)buckets.Length);
+ bucketNumber = (int) (((long)bucketNumber + incr)% (uint)buckets.Length);
} while (++ntry < buckets.Length);
// This code is here if and only if there were no buckets without a collision bit set in the entire table
{
// We pretty much have to insert in this order. Don't set hash
// code until the value & key are set appropriately.
-#if !FEATURE_CORECLR
- Thread.BeginCriticalRegion();
-#endif
- isWriterInProgress = true;
+ isWriterInProgress = true;
buckets[emptySlotNumber].val = nvalue;
buckets[emptySlotNumber].key = key;
buckets[emptySlotNumber].hash_coll |= (int) hashcode;
count++;
UpdateVersion();
isWriterInProgress = false;
-#if !FEATURE_CORECLR
- Thread.EndCriticalRegion();
-#endif
-#if FEATURE_RANDOMIZED_STRING_HASHING
-#if !FEATURE_CORECLR
- if(buckets.Length > HashHelpers.HashCollisionThreshold && HashHelpers.IsWellKnownEqualityComparer(_keycomparer))
- {
- // PERF: We don't want to rehash if _keycomparer is already a RandomizedObjectEqualityComparer since in some
- // cases there may not be any strings in the hashtable and we wouldn't get any mixing.
- if(_keycomparer == null || !(_keycomparer is System.Collections.Generic.RandomizedObjectEqualityComparer))
- {
- _keycomparer = HashHelpers.GetRandomizedEqualityComparer(_keycomparer);
- rehash(buckets.Length, true);
- }
- }
-#endif // !FEATURE_CORECLR
-#endif
return;
}
-
+
// If you see this assert, make sure load factor & count are reasonable.
// Then verify that our double hash function (h2, described at top of file)
// meets the requirements described above. You should never see this assert.
- Contract.Assert(false, "hash table insert failed! Load factor too high, or our double hashing function is incorrect.");
+ Debug.Assert(false, "hash table insert failed! Load factor too high, or our double hashing function is incorrect.");
throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_HashInsertFailed"));
}
private void putEntry (bucket[] newBuckets, Object key, Object nvalue, int hashcode)
{
- Contract.Assert(hashcode >= 0, "hashcode >= 0"); // make sure collision bit (sign bit) wasn't set.
+ Debug.Assert(hashcode >= 0, "hashcode >= 0"); // make sure collision bit (sign bit) wasn't set.
uint seed = (uint) hashcode;
uint incr = (uint)(1 + ((seed * HashPrime) % ((uint)newBuckets.Length - 1)));
newBuckets[bucketNumber].hash_coll |= unchecked((int)0x80000000);
occupancy++;
}
- bucketNumber = (int) (((long)bucketNumber + incr)% (uint)newBuckets.Length);
+ bucketNumber = (int) (((long)bucketNumber + incr)% (uint)newBuckets.Length);
} while (true);
}
throw new ArgumentNullException(nameof(key), Environment.GetResourceString("ArgumentNull_Key"));
}
Contract.EndContractBlock();
- Contract.Assert(!isWriterInProgress, "Race condition detected in usages of Hashtable - multiple threads appear to be writing to a Hashtable instance simultaneously! Don't do that - use Hashtable.Synchronized.");
+ Debug.Assert(!isWriterInProgress, "Race condition detected in usages of Hashtable - multiple threads appear to be writing to a Hashtable instance simultaneously! Don't do that - use Hashtable.Synchronized.");
uint seed;
uint incr;
b = buckets[bn];
if (((b.hash_coll & 0x7FFFFFFF) == hashcode) &&
KeyEquals (b.key, key)) {
-#if !FEATURE_CORECLR
- Thread.BeginCriticalRegion();
-#endif
isWriterInProgress = true;
// Clear hash_coll field, then key, then value
buckets[bn].hash_coll &= unchecked((int)0x80000000);
count--;
UpdateVersion();
isWriterInProgress = false;
-#if !FEATURE_CORECLR
- Thread.EndCriticalRegion();
-#endif
return;
}
- bn = (int) (((long)bn + incr)% (uint)buckets.Length);
+ bn = (int) (((long)bn + incr)% (uint)buckets.Length);
} while (b.hash_coll < 0 && ++ntry < buckets.Length);
//throw new ArgumentException(Environment.GetResourceString("Arg_RemoveArgNotFound"));
// Returns a thread-safe wrapper for a Hashtable.
//
- [HostProtection(Synchronization=true)]
public static Hashtable Synchronized(Hashtable table) {
if (table==null)
throw new ArgumentNullException(nameof(table));
// The ISerializable Implementation
//
- [System.Security.SecurityCritical]
public virtual void GetObjectData(SerializationInfo info, StreamingContext context) {
if (info==null) {
throw new ArgumentNullException(nameof(info));
** context -- the StreamingContext for the current serialization (ignored)
**Exceptions: ArgumentNullException if info is null.
==============================================================================*/
- [System.Security.SecurityCritical] // auto-generated
public override void GetObjectData(SerializationInfo info, StreamingContext context) {
if (info==null) {
throw new ArgumentNullException(nameof(info));
// Note that this check works even when _items.Length overflowed thanks to the (uint) cast
if ((uint)newSize > MaxPrimeArrayLength && MaxPrimeArrayLength > oldSize)
{
- Contract.Assert( MaxPrimeArrayLength == GetPrime(MaxPrimeArrayLength), "Invalid MaxPrimeArrayLength");
+ Debug.Assert( MaxPrimeArrayLength == GetPrime(MaxPrimeArrayLength), "Invalid MaxPrimeArrayLength");
return MaxPrimeArrayLength;
}
public static IEqualityComparer GetRandomizedEqualityComparer(object comparer)
{
- Contract.Assert(comparer == null || comparer == System.Collections.Generic.EqualityComparer<string>.Default || comparer is IWellKnownStringEqualityComparer);
+ Debug.Assert(comparer == null || comparer == System.Collections.Generic.EqualityComparer<string>.Default || comparer is IWellKnownStringEqualityComparer);
if(comparer == null) {
return new System.Collections.Generic.RandomizedObjectEqualityComparer();
return cmp.GetRandomizedEqualityComparer();
}
- Contract.Assert(false, "Missing case in GetRandomizedEqualityComparer!");
+ Debug.Assert(false, "Missing case in GetRandomizedEqualityComparer!");
return null;
}
}
private const int bufferSize = 1024;
-#if !FEATURE_CORECLR
- private static RandomNumberGenerator rng;
-#endif
private static byte[] data;
private static int currentIndex = bufferSize;
private static readonly object lockObj = new Object();
if(data == null)
{
data = new byte[bufferSize];
- Contract.Assert(bufferSize % 8 == 0, "We increment our current index by 8, so our buffer size must be a multiple of 8");
-#if !FEATURE_CORECLR
- rng = RandomNumberGenerator.Create();
-#endif
-
+ Debug.Assert(bufferSize % 8 == 0, "We increment our current index by 8, so our buffer size must be a multiple of 8");
}
-#if FEATURE_CORECLR
Microsoft.Win32.Win32Native.Random(true, data, data.Length);
-#else
- rng.GetBytes(data);
-#endif
currentIndex = 0;
}
/// </summary>
new private List<TItem> Items {
get {
- Contract.Assert(base.Items is List<TItem>);
+ Debug.Assert(base.Items is List<TItem>);
return (List<TItem>)base.Items;
}
}
private void RemoveKey(TKey key) {
- Contract.Assert(key != null, "key shouldn't be null!");
+ Debug.Assert(key != null, "key shouldn't be null!");
if (dict != null) {
dict.Remove(key);
}
//
[DebuggerTypeProxy(typeof(System.Collections.SortedList.SortedListDebugView))]
[DebuggerDisplay("Count = {Count}")]
-[System.Runtime.InteropServices.ComVisible(true)]
-#if FEATURE_CORECLR
+ [System.Runtime.InteropServices.ComVisible(true)]
[Obsolete("Non-generic collections have been deprecated. Please use collections in System.Collections.Generic.")]
-#endif
[Serializable]
public class SortedList : IDictionary, ICloneable
{
}
else {
// size can only be zero here.
- Contract.Assert( _size == 0, "Size is not zero");
+ Debug.Assert( _size == 0, "Size is not zero");
keys = emptyArray;
values = emptyArray;
}
// Returns a thread-safe SortedList.
//
- [HostProtection(Synchronization=true)]
public static SortedList Synchronized(SortedList list) {
if (list==null)
throw new ArgumentNullException(nameof(list));
// Returns a synchronized Stack.
//
- [HostProtection(Synchronization=true)]
public static Stack Synchronized(Stack stack) {
if (stack==null)
throw new ArgumentNullException(nameof(stack));
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
-
-using System.Runtime;
using System.Runtime.CompilerServices;
namespace System
internal static class CompatibilitySwitches
{
private static bool s_AreSwitchesSet;
-
-#if FEATURE_CORECLR
private static bool s_useLatestBehaviorWhenTFMNotSpecified; // Which behavior to use when the TFM is not specified.
-#endif //FEATURE_CORECLR
-
-#if !FEATURE_CORECLR
- private static bool s_isNetFx40TimeSpanLegacyFormatMode;
- private static bool s_isNetFx40LegacySecurityPolicy;
- private static bool s_isNetFx45LegacyManagedDeflateStream;
-#endif //!FEATURE_CORECLR
public static bool IsCompatibilityBehaviorDefined
{
internal static void InitializeSwitches()
{
-#if !FEATURE_CORECLR
- s_isNetFx40TimeSpanLegacyFormatMode = IsCompatibilitySwitchSet("NetFx40_TimeSpanLegacyFormatMode");
- s_isNetFx40LegacySecurityPolicy = IsCompatibilitySwitchSet("NetFx40_LegacySecurityPolicy");
- s_isNetFx45LegacyManagedDeflateStream = IsCompatibilitySwitchSet("NetFx45_LegacyManagedDeflateStream");
-#endif //FEATURE_CORECLR
-
s_AreSwitchesSet = true;
}
-#if !FEATURE_CORECLR
- public static bool IsAppEarlierThanSilverlight4
- {
- get
- {
- return false;
- }
- }
-
- public static bool IsAppEarlierThanWindowsPhone8
- {
- get
- {
- return false;
- }
- }
-
- public static bool IsAppEarlierThanWindowsPhoneMango
- {
- get
- {
- return false;
- }
- }
-
-#endif //!FEATURE_CORECLR
-
public static bool IsNetFx40TimeSpanLegacyFormatMode
{
get
{
-#if !FEATURE_CORECLR
- return s_isNetFx40TimeSpanLegacyFormatMode;
-#else
return false;
-#endif //!FEATURE_CORECLR
}
}
{
get
{
-#if !FEATURE_CORECLR
- return s_isNetFx40LegacySecurityPolicy;
-#else
return false;
-#endif //!FEATURE_CORECLR
}
}
{
get
{
-#if !FEATURE_CORECLR
- return s_isNetFx45LegacyManagedDeflateStream;
-#else
return false;
-#endif //!FEATURE_CORECLR
}
}
}
using System.Runtime.InteropServices;
using System.Runtime.Versioning;
using System.Security;
+using System.Diagnostics;
using System.Diagnostics.Contracts;
#if _DEBUG
private static bool TriggerAsserts = DoAsserts();
private static bool DoAsserts() {
- Contract.Assert(ConvertTypes!=null, "[Convert.cctor]ConvertTypes!=null");
- Contract.Assert(ConvertTypes.Length == ((int)TypeCode.String + 1), "[Convert.cctor]ConvertTypes.Length == ((int)TypeCode.String + 1)");
- Contract.Assert(ConvertTypes[(int)TypeCode.Empty]==typeof(System.Empty),
+ Debug.Assert(ConvertTypes!=null, "[Convert.cctor]ConvertTypes!=null");
+ Debug.Assert(ConvertTypes.Length == ((int)TypeCode.String + 1), "[Convert.cctor]ConvertTypes.Length == ((int)TypeCode.String + 1)");
+ Debug.Assert(ConvertTypes[(int)TypeCode.Empty]==typeof(System.Empty),
"[Convert.cctor]ConvertTypes[(int)TypeCode.Empty]==typeof(System.Empty)");
- Contract.Assert(ConvertTypes[(int)TypeCode.String]==typeof(String),
+ Debug.Assert(ConvertTypes[(int)TypeCode.String]==typeof(String),
"[Convert.cctor]ConvertTypes[(int)TypeCode.String]==typeof(System.String)");
- Contract.Assert(ConvertTypes[(int)TypeCode.Int32]==typeof(int),
+ Debug.Assert(ConvertTypes[(int)TypeCode.Int32]==typeof(int),
"[Convert.cctor]ConvertTypes[(int)TypeCode.Int32]==typeof(int)");
return true;
}
throw new OverflowException(Environment.GetResourceString("Overflow_Int32"));
}
- [System.Security.SecuritySafeCritical] // auto-generated
public static int ToInt32(decimal value) {
return Decimal.FCallToInt32(value);
}
}
// Convert the byte value to a string in base fromBase
- [System.Security.SecuritySafeCritical] // auto-generated
public static String ToString (byte value, int toBase) {
if (toBase!=2 && toBase!=8 && toBase!=10 && toBase!=16) {
throw new ArgumentException(Environment.GetResourceString("Arg_InvalidBase"));
}
// Convert the Int16 value to a string in base fromBase
- [System.Security.SecuritySafeCritical] // auto-generated
public static String ToString (short value, int toBase) {
if (toBase!=2 && toBase!=8 && toBase!=10 && toBase!=16) {
throw new ArgumentException(Environment.GetResourceString("Arg_InvalidBase"));
}
// Convert the Int32 value to a string in base toBase
- [System.Security.SecuritySafeCritical] // auto-generated
public static String ToString (int value, int toBase) {
if (toBase!=2 && toBase!=8 && toBase!=10 && toBase!=16) {
throw new ArgumentException(Environment.GetResourceString("Arg_InvalidBase"));
}
// Convert the Int64 value to a string in base toBase
- [System.Security.SecuritySafeCritical] // auto-generated
public static String ToString (long value, int toBase) {
if (toBase!=2 && toBase!=8 && toBase!=10 && toBase!=16) {
throw new ArgumentException(Environment.GetResourceString("Arg_InvalidBase"));
return ToBase64String(inArray, offset, length, Base64FormattingOptions.None);
}
- [System.Security.SecuritySafeCritical] // auto-generated
[System.Runtime.InteropServices.ComVisible(false)]
public static unsafe String ToBase64String(byte[] inArray, int offset, int length, Base64FormattingOptions options) {
//Do data verfication
return ToBase64CharArray(inArray, offsetIn, length, outArray, offsetOut, Base64FormattingOptions.None);
}
- [System.Security.SecuritySafeCritical] // auto-generated
[System.Runtime.InteropServices.ComVisible(false)]
public static unsafe int ToBase64CharArray(byte[] inArray, int offsetIn, int length, char[] outArray, int offsetOut, Base64FormattingOptions options) {
//Do data verfication
return retVal;
}
- [System.Security.SecurityCritical] // auto-generated
private static unsafe int ConvertToBase64Array(char* outChars, byte* inData, int offset, int length, bool insertLineBreaks) {
int lengthmod3 = length%3;
int calcLength = offset + (length - lengthmod3);
/// </summary>
/// <param name="s">The string to convert</param>
/// <returns>The array of bytes represented by the specifed Base64 string.</returns>
- [SecuritySafeCritical]
public static Byte[] FromBase64String(String s) {
// "s" is an unfortunate parameter name, but we need to keep it for backward compat.
/// <param name="offset">A position within the input array.</param>
/// <param name="length">Number of element to convert.</param>
/// <returns>The array of bytes represented by the specified Base64 encoding characters.</returns>
- [SecuritySafeCritical]
public static Byte[] FromBase64CharArray(Char[] inArray, Int32 offset, Int32 length) {
if (inArray == null)
/// <param name="inputPtr">Pointer to the first input char</param>
/// <param name="inputLength">Number of input chars</param>
/// <returns></returns>
- [SecurityCritical]
private static unsafe Byte[] FromBase64CharPtr(Char* inputPtr, Int32 inputLength) {
// The validity of parameters much be checked by callers, thus we are Critical here.
- Contract.Assert(0 <= inputLength);
+ Debug.Assert(0 <= inputLength);
// We need to get rid of any trailing white spaces.
// Otherwise we would be rejecting input such as "abc= ":
// Compute the output length:
Int32 resultLength = FromBase64_ComputeResultLength(inputPtr, inputLength);
- Contract.Assert(0 <= resultLength);
+ Debug.Assert(0 <= resultLength);
// resultLength can be zero. We will still enter FromBase64_Decode and process the input.
// It may either simply write no bytes (e.g. input = " ") or throw (e.g. input = "ab").
/// <param name="destLength">Max length of the preallocated result buffer</param>
/// <returns>If the result buffer was not large enough to write all result bytes, return -1;
/// Otherwise return the number of result bytes actually produced.</returns>
- [SecurityCritical]
private static unsafe Int32 FromBase64_Decode(Char* startInputPtr, Int32 inputLength, Byte* startDestPtr, Int32 destLength) {
// You may find this method weird to look at. It\92s written for performance, not aesthetics.
}} // unchecked while
// 'd be nice to have an assert that we never get here, but CS0162: Unreachable code detected.
- // Contract.Assert(false, "We only leave the above loop by jumping; should never get here.");
+ // Debug.Assert(false, "We only leave the above loop by jumping; should never get here.");
// We jump here out of the loop if we hit an '=':
_EqualityCharEncountered:
- Contract.Assert(currCode == intEq);
+ Debug.Assert(currCode == intEq);
// Recall that inputPtr is now one position past where '=' was read.
// '=' can only be at the last input pos:
/// Walk the entire input counting white spaces and padding chars, then compute result length
/// based on 3 bytes per 4 chars.
/// </summary>
- [SecurityCritical]
private static unsafe Int32 FromBase64_ComputeResultLength(Char* inputPtr, Int32 inputLength) {
const UInt32 intEq = (UInt32) '=';
const UInt32 intSpace = (UInt32) ' ';
- Contract.Assert(0 <= inputLength);
+ Debug.Assert(0 <= inputLength);
Char* inputEndPtr = inputPtr + inputLength;
Int32 usefulInputLength = inputLength;
}
}
- Contract.Assert(0 <= usefulInputLength);
+ Debug.Assert(0 <= usefulInputLength);
// For legal input, we can assume that 0 <= padding < 3. But it may be more for illegal input.
// We will notice it at decode when we see a '=' at the wrong place.
- Contract.Assert(0 <= padding);
+ Debug.Assert(0 <= padding);
// Perf: reuse the variable that stored the number of '=' to store the number of bytes encoded by the
// last group that contains the '=':
// Converts a Currency to a Decimal.
//
- [System.Security.SecuritySafeCritical] // auto-generated
public static Decimal ToDecimal(Currency c)
{
Decimal result = new Decimal ();
return result;
}
- [System.Security.SecurityCritical] // auto-generated
[MethodImplAttribute(MethodImplOptions.InternalCall)]
private static extern void FCallToDecimal(ref Decimal result,Currency c);
}
using System;
using System.Diagnostics.Contracts;
using System.Text;
- using System.Threading;
using System.Collections;
using System.Globalization;
using System.Runtime.CompilerServices;
using System.Runtime.Versioning;
-#if FEATURE_CORECLR
[Obsolete("System.CurrentSystemTimeZone has been deprecated. Please investigate the use of System.TimeZoneInfo.Local instead.")]
-#endif
[Serializable]
internal class CurrentSystemTimeZone : TimeZone
{
// The per-year information is cached in in this instance value. As a result it can
// be cleaned up by CultureInfo.ClearCachedData, which will clear the instance of this object
- private Hashtable m_CachedDaylightChanges = new Hashtable();
+ private readonly Hashtable m_CachedDaylightChanges = new Hashtable();
// Standard offset in ticks to the Universal time if
// no daylight saving is in used.
return new DateTime(tick, DateTimeKind.Local, isAmbiguousLocalDst);
}
- // Private object for locking instead of locking on a public type for SQL reliability work.
- private static Object s_InternalSyncObject;
- private static Object InternalSyncObject
- {
- get
- {
- if (s_InternalSyncObject == null)
- {
- Object o = new Object();
- Interlocked.CompareExchange<Object>(ref s_InternalSyncObject, o, null);
- }
- return s_InternalSyncObject;
- }
- }
-
public override DaylightTime GetDaylightChanges(int year)
{
if (year < 1 || year > 9999)
currentDaylightChanges = new DaylightTime(DateTime.MinValue, DateTime.MinValue, TimeSpan.Zero);
}
- lock (InternalSyncObject)
+ lock (m_CachedDaylightChanges)
{
if (!m_CachedDaylightChanges.Contains(objYear))
{
public static readonly DBNull Value = new DBNull();
- [System.Security.SecurityCritical]
public void GetObjectData(SerializationInfo info, StreamingContext context) {
UnitySerializationHolder.GetUnitySerializationInfo(info, UnitySerializationHolder.NullUnity, null, null);
}
return millis * TicksPerMillisecond;
}
-#if !FEATURE_CORECLR
- [DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
- [SecurityCritical]
- [SuppressUnmanagedCodeSecurity]
- [return: MarshalAs(UnmanagedType.Bool)]
- internal static extern bool LegacyParseMode();
-
- [DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
- [SecurityCritical]
- [SuppressUnmanagedCodeSecurity]
- [return: MarshalAs(UnmanagedType.Bool)]
- internal static extern bool EnableAmPmParseAdjustment();
-#endif
-
// Checks if this DateTime is equal to a given object. Returns
// true if the given object is a boxed DateTime and its value
// is equal to the value of this DateTime. Returns false
}
public static DateTime UtcNow {
- [System.Security.SecuritySafeCritical] // auto-generated
get {
Contract.Ensures(Contract.Result<DateTime>().Kind == DateTimeKind.Utc);
// following code is tuned for speed. Don't change it without running benchmark.
}
- [System.Security.SecurityCritical] // auto-generated
[MethodImplAttribute(MethodImplOptions.InternalCall)]
internal static extern long GetSystemTimeAsFileTime();
using System.Runtime.CompilerServices;
using System.Runtime.Serialization;
using System.Security.Permissions;
+ using System.Diagnostics;
using System.Diagnostics.Contracts;
// DateTimeOffset is a value type that consists of a DateTime and a time zone offset,
}
- [System.Security.SecurityCritical] // auto-generated_required
void ISerializable.GetObjectData(SerializationInfo info, StreamingContext context) {
if (info == null) {
throw new ArgumentNullException(nameof(info));
private static DateTime ValidateDate(DateTime dateTime, TimeSpan offset) {
// The key validation is that both the UTC and clock times fit. The clock time is validated
// by the DateTime constructor.
- Contract.Assert(offset.Ticks >= MinOffset && offset.Ticks <= MaxOffset, "Offset not validated.");
+ Debug.Assert(offset.Ticks >= MinOffset && offset.Ticks <= MaxOffset, "Offset not validated.");
// This operation cannot overflow because offset should have already been validated to be within
// 14 hours and the DateTime instance is more than that distance from the boundaries of Int64.
Int64 utcTicks = dateTime.Ticks - offset.Ticks;
// Constructs a Decimal from a float value.
//
- [System.Security.SecuritySafeCritical] // auto-generated
[MethodImplAttribute(MethodImplOptions.InternalCall)]
public extern Decimal(float value);
// Constructs a Decimal from a double value.
//
- [System.Security.SecuritySafeCritical] // auto-generated
[MethodImplAttribute(MethodImplOptions.InternalCall)]
public extern Decimal(double value);
// Adds two Decimal values.
//
- [System.Security.SecuritySafeCritical] // auto-generated
public static Decimal Add(Decimal d1, Decimal d2)
{
FCallAddSub (ref d1, ref d2, DECIMAL_ADD);
// of the operation. Passing in DECIMAL_ADD or DECIMAL_NEG for bSign indicates
// addition or subtraction, respectively.
//
- [System.Security.SecurityCritical] // auto-generated
[MethodImplAttribute(MethodImplOptions.InternalCall)]
private static extern void FCallAddSub(ref Decimal d1, ref Decimal d2, byte bSign);
- [System.Security.SecurityCritical] // auto-generated
[MethodImplAttribute(MethodImplOptions.InternalCall)]
private static extern void FCallAddSubOverflowed(ref Decimal d1, ref Decimal d2, byte bSign, ref bool overflowed);
// Compares two Decimal values, returning an integer that indicates their
// relationship.
//
- [System.Security.SecuritySafeCritical] // auto-generated
[ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)]
public static int Compare(Decimal d1, Decimal d2) {
return FCallCompare(ref d1, ref d2);
}
- [System.Security.SecurityCritical] // auto-generated
[MethodImplAttribute(MethodImplOptions.InternalCall)]
[ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)]
private static extern int FCallCompare(ref Decimal d1, ref Decimal d2);
// null is considered to be less than any instance.
// If object is not of type Decimal, this method throws an ArgumentException.
//
- [System.Security.SecuritySafeCritical] // auto-generated
public int CompareTo(Object value)
{
if (value == null)
return FCallCompare(ref this, ref other);
}
- [System.Security.SecuritySafeCritical] // auto-generated
public int CompareTo(Decimal value)
{
return FCallCompare(ref this, ref value);
// Divides two Decimal values.
//
- [System.Security.SecuritySafeCritical] // auto-generated
public static Decimal Divide(Decimal d1, Decimal d2)
{
FCallDivide (ref d1, ref d2);
// FCallDivide divides two decimal values. On return, d1 contains the result
// of the operation.
//
- [System.Security.SecurityCritical] // auto-generated
[MethodImplAttribute(MethodImplOptions.InternalCall)]
private static extern void FCallDivide(ref Decimal d1, ref Decimal d2);
- [System.Security.SecurityCritical] // auto-generated
[MethodImplAttribute(MethodImplOptions.InternalCall)]
private static extern void FCallDivideOverflowed(ref Decimal d1, ref Decimal d2, ref bool overflowed);
// if the given object is a boxed Decimal and its value is equal to the
// value of this Decimal. Returns false otherwise.
//
- [System.Security.SecuritySafeCritical] // auto-generated
public override bool Equals(Object value) {
if (value is Decimal) {
Decimal other = (Decimal)value;
return false;
}
- [System.Security.SecuritySafeCritical] // auto-generated
public bool Equals(Decimal value)
{
return FCallCompare(ref this, ref value) == 0;
// Returns the hash code for this Decimal.
//
- [System.Security.SecuritySafeCritical] // auto-generated
[MethodImplAttribute(MethodImplOptions.InternalCall)]
public extern override int GetHashCode();
// Compares two Decimal values for equality. Returns true if the two
// Decimal values are equal, or false if they are not equal.
//
- [System.Security.SecuritySafeCritical] // auto-generated
public static bool Equals(Decimal d1, Decimal d2) {
return FCallCompare(ref d1, ref d2) == 0;
}
// Rounds a Decimal to an integer value. The Decimal argument is rounded
// towards negative infinity.
//
- [System.Security.SecuritySafeCritical] // auto-generated
public static Decimal Floor(Decimal d)
{
FCallFloor (ref d);
return d;
}
- [System.Security.SecurityCritical] // auto-generated
[MethodImplAttribute(MethodImplOptions.InternalCall)]
private static extern void FCallFloor(ref Decimal d);
// optionally followed by a decimal point (".") and another sequence of
// digits.
//
- [System.Security.SecuritySafeCritical] // auto-generated
public override String ToString() {
Contract.Ensures(Contract.Result<String>() != null);
return Number.FormatDecimal(this, null, NumberFormatInfo.CurrentInfo);
}
- [System.Security.SecuritySafeCritical] // auto-generated
public String ToString(String format) {
Contract.Ensures(Contract.Result<String>() != null);
return Number.FormatDecimal(this, format, NumberFormatInfo.CurrentInfo);
}
- [System.Security.SecuritySafeCritical] // auto-generated
public String ToString(IFormatProvider provider) {
Contract.Ensures(Contract.Result<String>() != null);
return Number.FormatDecimal(this, null, NumberFormatInfo.GetInstance(provider));
}
- [System.Security.SecuritySafeCritical] // auto-generated
public String ToString(String format, IFormatProvider provider) {
Contract.Ensures(Contract.Result<String>() != null);
return Number.FormatDecimal(this, format, NumberFormatInfo.GetInstance(provider));
// Returns the larger of two Decimal values.
//
- [System.Security.SecuritySafeCritical] // auto-generated
[ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)]
internal static Decimal Max(Decimal d1, Decimal d2) {
return FCallCompare(ref d1, ref d2) >= 0? d1: d2;
// Returns the smaller of two Decimal values.
//
- [System.Security.SecuritySafeCritical] // auto-generated
[ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)]
internal static Decimal Min(Decimal d1, Decimal d2) {
return FCallCompare(ref d1, ref d2) < 0? d1: d2;
// Multiplies two Decimal values.
//
- [System.Security.SecuritySafeCritical] // auto-generated
public static Decimal Multiply(Decimal d1, Decimal d2)
{
FCallMultiply (ref d1, ref d2);
// FCallMultiply multiples two decimal values. On return, d1 contains the result
// of the operation.
//
- [System.Security.SecurityCritical] // auto-generated
[MethodImplAttribute(MethodImplOptions.InternalCall)]
private static extern void FCallMultiply(ref Decimal d1, ref Decimal d2);
- [System.Security.SecurityCritical] // auto-generated
[MethodImplAttribute(MethodImplOptions.InternalCall)]
private static extern void FCallMultiplyOverflowed(ref Decimal d1, ref Decimal d2, ref bool overflowed);
return Round(d, 0);
}
- [System.Security.SecuritySafeCritical] // auto-generated
public static Decimal Round(Decimal d, int decimals)
{
FCallRound (ref d, decimals);
return Round(d, 0, mode);
}
- [System.Security.SecuritySafeCritical] // auto-generated
public static Decimal Round(Decimal d, int decimals, MidpointRounding mode) {
if ((decimals < 0) || (decimals > 28))
throw new ArgumentOutOfRangeException(nameof(decimals), Environment.GetResourceString("ArgumentOutOfRange_DecimalRound"));
return d;
}
- [System.Security.SecurityCritical] // auto-generated
[MethodImplAttribute(MethodImplOptions.InternalCall)]
private static extern void FCallRound(ref Decimal d, int decimals);
// Subtracts two Decimal values.
//
- [System.Security.SecuritySafeCritical] // auto-generated
public static Decimal Subtract(Decimal d1, Decimal d2)
{
FCallAddSub(ref d1, ref d2, DECIMAL_NEG);
// has fewer significant digits than a Decimal, this operation may
// produce round-off errors.
//
- [System.Security.SecuritySafeCritical] // auto-generated
internal static Currency ToCurrency(Decimal d)
{
Currency result = new Currency ();
return result;
}
- [System.Security.SecurityCritical] // auto-generated
[MethodImplAttribute(MethodImplOptions.InternalCall)]
private static extern void FCallToCurrency(ref Currency result, Decimal d);
// Converts a Decimal to a double. Since a double has fewer significant
// digits than a Decimal, this operation may produce round-off errors.
//
- [System.Security.SecuritySafeCritical] // auto-generated
[MethodImplAttribute(MethodImplOptions.InternalCall)]
public static extern double ToDouble(Decimal d);
- [System.Security.SecurityCritical] // auto-generated
[MethodImplAttribute(MethodImplOptions.InternalCall)]
internal static extern int FCallToInt32(Decimal d);
// zero to the nearest integer value, and the result of this operation is
// returned as an integer.
//
- [System.Security.SecuritySafeCritical] // auto-generated
public static int ToInt32(Decimal d) {
if ((d.flags & ScaleMask) != 0) FCallTruncate (ref d);
if (d.hi == 0 && d.mid == 0) {
// to the nearest integer value, and the result of this operation is
// returned as a long.
//
- [System.Security.SecuritySafeCritical] // auto-generated
public static long ToInt64(Decimal d) {
if ((d.flags & ScaleMask) != 0) FCallTruncate (ref d);
if (d.hi == 0) {
// value is rounded towards zero to the nearest integer value, and the
// result of this operation is returned as an unsigned integer.
//
- [System.Security.SecuritySafeCritical] // auto-generated
[CLSCompliant(false)]
public static uint ToUInt32(Decimal d) {
if ((d.flags & ScaleMask) != 0) FCallTruncate (ref d);
// value is rounded towards zero to the nearest integer value, and the
// result of this operation is returned as a long.
//
- [System.Security.SecuritySafeCritical] // auto-generated
[CLSCompliant(false)]
public static ulong ToUInt64(Decimal d) {
if ((d.flags & ScaleMask) != 0) FCallTruncate (ref d);
// Converts a Decimal to a float. Since a float has fewer significant
// digits than a Decimal, this operation may produce round-off errors.
//
- [System.Security.SecuritySafeCritical] // auto-generated
[MethodImplAttribute(MethodImplOptions.InternalCall)]
public static extern float ToSingle(Decimal d);
// towards zero to the nearest integer value, corresponding to removing all
// digits after the decimal point.
//
- [System.Security.SecuritySafeCritical] // auto-generated
public static Decimal Truncate(Decimal d)
{
FCallTruncate (ref d);
}
- [System.Security.SecurityCritical] // auto-generated
[MethodImplAttribute(MethodImplOptions.InternalCall)]
private static extern void FCallTruncate(ref Decimal d);
return Subtract(d, One);
}
- [System.Security.SecuritySafeCritical] // auto-generated
public static Decimal operator +(Decimal d1, Decimal d2) {
FCallAddSub(ref d1, ref d2, DECIMAL_ADD);
return d1;
}
- [System.Security.SecuritySafeCritical] // auto-generated
public static Decimal operator -(Decimal d1, Decimal d2) {
FCallAddSub(ref d1, ref d2, DECIMAL_NEG);
return d1;
}
- [System.Security.SecuritySafeCritical] // auto-generated
public static Decimal operator *(Decimal d1, Decimal d2) {
FCallMultiply (ref d1, ref d2);
return d1;
}
- [System.Security.SecuritySafeCritical] // auto-generated
public static Decimal operator /(Decimal d1, Decimal d2) {
FCallDivide (ref d1, ref d2);
return d1;
return Remainder(d1, d2);
}
- [System.Security.SecuritySafeCritical] // auto-generated
public static bool operator ==(Decimal d1, Decimal d2) {
return FCallCompare(ref d1, ref d2) == 0;
}
- [System.Security.SecuritySafeCritical] // auto-generated
public static bool operator !=(Decimal d1, Decimal d2) {
return FCallCompare(ref d1, ref d2) != 0;
}
- [System.Security.SecuritySafeCritical] // auto-generated
public static bool operator <(Decimal d1, Decimal d2) {
return FCallCompare(ref d1, ref d2) < 0;
}
- [System.Security.SecuritySafeCritical] // auto-generated
public static bool operator <=(Decimal d1, Decimal d2) {
return FCallCompare(ref d1, ref d2) <= 0;
}
- [System.Security.SecuritySafeCritical] // auto-generated
public static bool operator >(Decimal d1, Decimal d2) {
return FCallCompare(ref d1, ref d2) > 0;
}
- [System.Security.SecuritySafeCritical] // auto-generated
public static bool operator >=(Decimal d1, Decimal d2) {
return FCallCompare(ref d1, ref d2) >= 0;
}
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.Versioning;
+ using System.Diagnostics;
using System.Diagnostics.Contracts;
using CultureInfo = System.Globalization.CultureInfo;
//Marked serializable even though it has no state.
//
// The most specific match will be selected.
//
- [System.Security.SecuritySafeCritical] // auto-generated
public override MethodBase BindToMethod(
BindingFlags bindingAttr, MethodBase[] match, ref Object[] args,
ParameterModifier[] modifiers, CultureInfo cultureInfo, String[] names, out Object state)
// Given a set of fields that match the base criteria, select a field.
// if value is null then we have no way to select a field
- [System.Security.SecuritySafeCritical] // auto-generated
public override FieldInfo BindToField(BindingFlags bindingAttr,FieldInfo[] match, Object value,CultureInfo cultureInfo)
{
if (match == null) {
// Given a set of methods that match the base criteria, select a method based
// upon an array of types. This method should return null if no method matchs
// the criteria.
- [System.Security.SecuritySafeCritical] // auto-generated
public override MethodBase SelectMethod(BindingFlags bindingAttr,MethodBase[] match,Type[] types,ParameterModifier[] modifiers)
{
int i;
}
// Given a set of properties that match the base criteria, select one.
- [System.Security.SecuritySafeCritical] // auto-generated
public override PropertyInfo SelectProperty(BindingFlags bindingAttr,PropertyInfo[] match,Type returnType,
Type[] indexes,ParameterModifier[] modifiers)
{
}
}
- [System.Security.SecuritySafeCritical] // auto-generated
private static int FindMostSpecificType(Type c1, Type c2, Type t)
{
// If the two types are exact move on...
int hierarchyDepth2 = GetHierarchyDepth(cur2.DeclaringType);
if (hierarchyDepth1 == hierarchyDepth2) {
- Contract.Assert(cur1.IsStatic != cur2.IsStatic, "hierarchyDepth1 == hierarchyDepth2");
+ Debug.Assert(cur1.IsStatic != cur2.IsStatic, "hierarchyDepth1 == hierarchyDepth2");
return 0;
}
else if (hierarchyDepth1 < hierarchyDepth2)
// CanConvertPrimitive
// This will determine if the source can be converted to the target type
- [System.Security.SecurityCritical] // auto-generated
[MethodImplAttribute(MethodImplOptions.InternalCall)]
private static extern bool CanConvertPrimitive(RuntimeType source,RuntimeType target);
// CanConvertPrimitiveObjectToType
// This method will determine if the primitive object can be converted
// to a type.
- [System.Security.SecurityCritical] // auto-generated
[MethodImplAttribute(MethodImplOptions.InternalCall)]
static internal extern bool CanConvertPrimitiveObjectToType(Object source,RuntimeType type);
using System.Runtime.InteropServices;
using System.Runtime.CompilerServices;
using System.Runtime.Versioning;
+ using System.Diagnostics;
using System.Diagnostics.Contracts;
[Serializable]
public abstract class Delegate : ICloneable, ISerializable
{
// _target is the object we will invoke on
- [System.Security.SecurityCritical]
internal Object _target;
// MethodBase, either cached after first request or assigned from a DynamicMethod
// For open delegates to collectible types, this may be a LoaderAllocator object
- [System.Security.SecurityCritical]
internal Object _methodBase;
// _methodPtr is a pointer to the method we will invoke
// It could be a small thunk if this is a static or UM call
- [System.Security.SecurityCritical]
internal IntPtr _methodPtr;
// In the case of a static method passed to a delegate, this field stores
// whatever _methodPtr would have stored: and _methodPtr points to a
// small thunk which removes the "this" pointer before going on
// to _methodPtrAux.
- [System.Security.SecurityCritical]
internal IntPtr _methodPtrAux;
// This constructor is called from the class generated by the
// compiler generated code
- [System.Security.SecuritySafeCritical] // auto-generated
protected Delegate(Object target,String method)
{
if (target == null)
// This constructor is called from a class to generate a
// delegate based upon a static method name and the Type object
// for the class defining the method.
- [System.Security.SecuritySafeCritical] // auto-generated
protected unsafe Delegate(Type target,String method)
{
if (target == null)
return DynamicInvokeImpl(args);
}
- [System.Security.SecuritySafeCritical] // auto-generated
protected virtual object DynamicInvokeImpl(object[] args)
{
RuntimeMethodHandleInternal method = new RuntimeMethodHandleInternal(GetInvokeMethod());
}
- [System.Security.SecuritySafeCritical] // auto-generated
public override bool Equals(Object obj)
{
if (obj == null || !InternalEqualTypes(this, obj))
}
}
- [System.Security.SecuritySafeCritical] // auto-generated
protected virtual MethodInfo GetMethodImpl()
{
if ((_methodBase == null) || !(_methodBase is MethodInfo))
}
- [System.Security.SecuritySafeCritical] // auto-generated
public static Delegate Remove(Delegate source, Delegate value)
{
if (source == null)
}
// V1 API.
- [System.Security.SecuritySafeCritical] // auto-generated
public static Delegate CreateDelegate(Type type, Object target, String method, bool ignoreCase, bool throwOnBindFailure)
{
if (type == null)
}
// V1 API.
- [System.Security.SecuritySafeCritical] // auto-generated
public static Delegate CreateDelegate(Type type, Type target, String method, bool ignoreCase, bool throwOnBindFailure)
{
if (type == null)
}
// V1 API.
- [System.Security.SecuritySafeCritical]
[MethodImplAttribute(MethodImplOptions.NoInlining)] // Methods containing StackCrawlMark local var has to be marked non-inlineable
public static Delegate CreateDelegate(Type type, MethodInfo method, bool throwOnBindFailure)
{
}
// V2 API.
- [System.Security.SecuritySafeCritical]
[MethodImplAttribute(MethodImplOptions.NoInlining)] // Methods containing StackCrawlMark local var has to be marked non-inlineable
public static Delegate CreateDelegate(Type type, Object firstArgument, MethodInfo method, bool throwOnBindFailure)
{
// Implementation of ISerializable
//
- [System.Security.SecurityCritical]
public virtual void GetObjectData(SerializationInfo info, StreamingContext context)
{
throw new NotSupportedException();
// V2 internal API.
// This is Critical because it skips the security check when creating the delegate.
- [System.Security.SecurityCritical] // auto-generated
internal unsafe static Delegate CreateDelegateNoSecurityCheck(Type type, Object target, RuntimeMethodHandle method)
{
// Validate the parameters.
}
// Caution: this method is intended for deserialization only, no security checks are performed.
- [System.Security.SecurityCritical] // auto-generated
internal static Delegate CreateDelegateNoSecurityCheck(RuntimeType type, Object firstArgument, MethodInfo method)
{
// Validate the parameters.
return CreateDelegate(type, method, true);
}
- [System.Security.SecuritySafeCritical]
internal static Delegate CreateDelegateInternal(RuntimeType rtType, RuntimeMethodInfo rtMethod, Object firstArgument, DelegateBindingFlags flags, ref StackCrawlMark stackMark)
{
- Contract.Assert((flags & DelegateBindingFlags.SkipSecurityChecks) == 0);
+ Debug.Assert((flags & DelegateBindingFlags.SkipSecurityChecks) == 0);
#if FEATURE_APPX
bool nonW8PMethod = (rtMethod.InvocationFlags & INVOCATION_FLAGS.INVOCATION_FLAGS_NON_W8P_FX_API) != 0;
return UnsafeCreateDelegate(rtType, rtMethod, firstArgument, flags);
}
- [System.Security.SecurityCritical]
internal static Delegate UnsafeCreateDelegate(RuntimeType rtType, RuntimeMethodInfo rtMethod, Object firstArgument, DelegateBindingFlags flags)
{
Delegate d = InternalAlloc(rtType);
// internal implementation details (FCALLS and utilities)
//
- [System.Security.SecurityCritical] // auto-generated
[MethodImplAttribute(MethodImplOptions.InternalCall)]
private extern bool BindToMethodName(Object target, RuntimeType methodType, String method, DelegateBindingFlags flags);
- [System.Security.SecurityCritical] // auto-generated
[MethodImplAttribute(MethodImplOptions.InternalCall)]
private extern bool BindToMethodInfo(Object target, IRuntimeMethodInfo method, RuntimeType methodType, DelegateBindingFlags flags);
- [System.Security.SecurityCritical] // auto-generated
[MethodImplAttribute(MethodImplOptions.InternalCall)]
private extern static MulticastDelegate InternalAlloc(RuntimeType type);
- [System.Security.SecurityCritical] // auto-generated
[MethodImplAttribute(MethodImplOptions.InternalCall)]
internal extern static MulticastDelegate InternalAllocLike(Delegate d);
- [System.Security.SecurityCritical] // auto-generated
[MethodImplAttribute(MethodImplOptions.InternalCall)]
internal extern static bool InternalEqualTypes(object a, object b);
// Used by the ctor. Do not call directly.
// The name of this function will appear in managed stacktraces as delegate constructor.
- [System.Security.SecurityCritical] // auto-generated
[MethodImplAttribute(MethodImplOptions.InternalCall)]
private extern void DelegateConstruct(Object target, IntPtr slot);
- [System.Security.SecurityCritical] // auto-generated
[MethodImplAttribute(MethodImplOptions.InternalCall)]
internal extern IntPtr GetMulticastInvoke();
- [System.Security.SecurityCritical] // auto-generated
[MethodImplAttribute(MethodImplOptions.InternalCall)]
internal extern IntPtr GetInvokeMethod();
[MethodImplAttribute(MethodImplOptions.InternalCall)]
internal extern IRuntimeMethodInfo FindMethodHandle();
- [System.Security.SecurityCritical] // auto-generated
[MethodImplAttribute(MethodImplOptions.InternalCall)]
internal extern static bool InternalEqualMethodHandles(Delegate left, Delegate right);
- [System.Security.SecurityCritical] // auto-generated
[MethodImplAttribute(MethodImplOptions.InternalCall)]
internal extern IntPtr AdjustTarget(Object target, IntPtr methodPtr);
- [System.Security.SecurityCritical] // auto-generated
[MethodImplAttribute(MethodImplOptions.InternalCall)]
internal extern IntPtr GetCallStub(IntPtr methodPtr);
- [System.Security.SecuritySafeCritical]
internal virtual Object GetTarget()
{
return (_methodPtrAux.IsNull()) ? _target : null;
}
- [System.Security.SecurityCritical] // auto-generated
[MethodImplAttribute(MethodImplOptions.InternalCall)]
internal extern static bool CompareUnmanagedFunctionPtrs (Delegate d1, Delegate d2);
}
internal sealed class DelegateSerializationHolder : IObjectReference, ISerializable
{
#region Static Members
- [System.Security.SecurityCritical] // auto-generated
internal static DelegateEntry GetDelegateSerializationInfo(
SerializationInfo info, Type delegateType, Object target, MethodInfo method, int targetIndex)
{
#endregion
#region Constructor
- [System.Security.SecurityCritical] // auto-generated
private DelegateSerializationHolder(SerializationInfo info, StreamingContext context)
{
if (info == null)
return new DelegateEntry(delegateType, delegateAssembly, target, targetTypeAssembly, targetTypeName, methodName);
}
- [System.Security.SecurityCritical]
private Delegate GetDelegate(DelegateEntry de, int index)
{
Delegate d;
// If we received the new style delegate encoding we already have the target MethodInfo in hand.
if (m_methods != null)
{
-#if FEATURE_REMOTING
- Object target = de.target != null ? RemotingServices.CheckCast(de.target, targetType) : null;
-#else
if(de.target != null && !targetType.IsInstanceOfType(de.target))
throw new InvalidCastException();
Object target=de.target;
-#endif
d = Delegate.CreateDelegateNoSecurityCheck(type, target, m_methods[index]);
}
else
{
if (de.target != null)
-#if FEATURE_REMOTING
- d = Delegate.CreateDelegate(type, RemotingServices.CheckCast(de.target, targetType), de.methodName);
-#else
- {
- if(!targetType.IsInstanceOfType(de.target))
- throw new InvalidCastException();
- d = Delegate.CreateDelegate(type, de.target, de.methodName);
- }
-#endif
+ {
+ if(!targetType.IsInstanceOfType(de.target))
+ throw new InvalidCastException();
+ d = Delegate.CreateDelegate(type, de.target, de.methodName);
+ }
else
d = Delegate.CreateDelegate(type, targetType, de.methodName);
}
#endregion
#region IObjectReference
- [System.Security.SecurityCritical] // auto-generated
public Object GetRealObject(StreamingContext context)
{
int count = 0;
#endregion
#region ISerializable
- [System.Security.SecurityCritical] // auto-generated
public void GetObjectData(SerializationInfo info, StreamingContext context)
{
throw new NotSupportedException(Environment.GetResourceString("NotSupported_DelegateSerHolderSerial"));
Fail(conditionString, message, null, exitCode, stackTraceFormat, 0);
}
- [System.Security.SecuritySafeCritical] // auto-generated
internal static void Fail(String conditionString, String message, String windowTitle, int exitCode, StackTrace.TraceFormat stackTraceFormat, int numStackFramesToSkip)
{
// get the stacktrace
}
else if (iResult == AssertFilters.FailTerminate)
{
-#if FEATURE_CORECLR
// We want to exit the Silverlight application, after displaying a message.
// Our best known way to emulate this is to exit the process with a known
// error code. Jolt may not be prepared for an appdomain to be unloaded.
Environment._Exit(exitCode);
-#else
- // This assert dialog will be common for code contract failures. If a code contract failure
- // occurs on an end user machine, we believe the right experience is to do a FailFast, which
- // will report this error via Watson, so someone could theoretically fix the bug.
- // However, in CLR v4, Environment.FailFast when a debugger is attached gives you an MDA
- // saying you've hit a bug in the runtime or unsafe managed code, and this is most likely caused
- // by heap corruption or a stack imbalance from COM Interop or P/Invoke. That extremely
- // misleading error isn't right, and we can temporarily work around this by using Environment.Exit
- // if a debugger is attached. The right fix is to plumb FailFast correctly through our native
- // Watson code, adding in a TypeOfReportedError for fatal managed errors.
- if (Debugger.IsAttached)
- Environment._Exit(exitCode);
- else
- Environment.FailFast(message, unchecked((uint) exitCode));
-#endif
}
}
// Called when an assert happens.
// windowTitle can be null.
- [System.Security.SecurityCritical] // auto-generated
[MethodImplAttribute(MethodImplOptions.InternalCall)]
internal extern static int ShowDefaultAssertDialog(String conditionString, String message, String stackTrace, String windowTitle);
}
{
}
- [System.Security.SecuritySafeCritical] // auto-generated
public override AssertFilters AssertFailure(String condition, String message,
StackTrace location, StackTrace.TraceFormat stackTraceFormat,
String windowTitle)
using System;
using System.Collections.Generic;
+using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Diagnostics.Contracts;
/// </summary>
/// <param name="condition">Expression to assume will always be true.</param>
/// <remarks>
- /// At runtime this is equivalent to an <seealso cref="System.Diagnostics.Contracts.Contract.Assert(bool)"/>.
+ /// At runtime this is equivalent to an <seealso cref="System.Diagnostics.Contracts.Debug.Assert(bool)"/>.
/// </remarks>
[Pure]
[Conditional("DEBUG")]
/// <param name="condition">Expression to assume will always be true.</param>
/// <param name="userMessage">If it is not a constant string literal, then the contract may not be understood by tools.</param>
/// <remarks>
- /// At runtime this is equivalent to an <seealso cref="System.Diagnostics.Contracts.Contract.Assert(bool)"/>.
+ /// At runtime this is equivalent to an <seealso cref="System.Diagnostics.Contracts.Debug.Assert(bool)"/>.
/// </remarks>
[Pure]
[Conditional("DEBUG")]
[CLSCompliant(false)]
[Pure]
[ContractRuntimeIgnored]
- [SecurityCritical]
#if FEATURE_RELIABILITY_CONTRACTS
[ReliabilityContract(Consistency.WillNotCorruptState, Cer.MayFail)]
#endif
[CLSCompliant(false)]
[Pure]
[ContractRuntimeIgnored]
- [SecurityCritical]
#if FEATURE_RELIABILITY_CONTRACTS
[ReliabilityContract(Consistency.WillNotCorruptState, Cer.MayFail)]
#endif
/// This method is used internally to trigger a failure indicating to the "programmer" that he is using the interface incorrectly.
/// It is NEVER used to indicate failure of actual contracts at runtime.
/// </summary>
- [SecuritySafeCritical]
static partial void AssertMustUseRewriter(ContractFailureKind kind, String contractKind)
{
if (_assertingMustUseRewriter)
/// </summary>
public static event EventHandler<ContractFailedEventArgs> ContractFailed {
#if FEATURE_UNTRUSTED_CALLERS
- [SecurityCritical]
#if FEATURE_LINK_DEMAND
- [SecurityPermission(SecurityAction.LinkDemand, Unrestricted = true)]
#endif
#endif
add {
System.Runtime.CompilerServices.ContractHelper.InternalContractFailed += value;
}
#if FEATURE_UNTRUSTED_CALLERS
- [SecurityCritical]
#if FEATURE_LINK_DEMAND
- [SecurityPermission(SecurityAction.LinkDemand, Unrestricted = true)]
#endif
#endif
remove {
}
#if FEATURE_UNTRUSTED_CALLERS
- [SecurityCritical]
#if FEATURE_LINK_DEMAND
- [SecurityPermission(SecurityAction.LinkDemand, Unrestricted = true)]
#endif
#endif
public void SetHandled()
}
#if FEATURE_UNTRUSTED_CALLERS
- [SecurityCritical]
#if FEATURE_LINK_DEMAND
- [SecurityPermission(SecurityAction.LinkDemand, Unrestricted = true)]
#endif
#endif
public void SetUnwind()
}
#if FEATURE_UNTRUSTED_CALLERS && FEATURE_SERIALIZATION
- [SecurityCritical]
#if FEATURE_LINK_DEMAND && FEATURE_SERIALIZATION
- [SecurityPermission(SecurityAction.LinkDemand, Flags = SecurityPermissionFlag.SerializationFormatter)]
#endif // FEATURE_LINK_DEMAND
#endif // FEATURE_UNTRUSTED_CALLERS
public override void GetObjectData(System.Runtime.Serialization.SerializationInfo info, System.Runtime.Serialization.StreamingContext context)
internal static event EventHandler<ContractFailedEventArgs> InternalContractFailed
{
#if FEATURE_UNTRUSTED_CALLERS
- [SecurityCritical]
#endif
add {
// Eagerly prepare each event handler _marked with a reliability contract_, to
}
}
#if FEATURE_UNTRUSTED_CALLERS
- [SecurityCritical]
#endif
remove {
lock (lockObject)
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes")]
[System.Diagnostics.DebuggerNonUserCode]
#if FEATURE_RELIABILITY_CONTRACTS
- [SecuritySafeCritical]
#endif
static partial void RaiseContractFailedEventImplementation(ContractFailureKind failureKind, String userMessage, String conditionText, Exception innerException, ref string resultFailureMessage)
{
}
if (eventArgs.Unwind)
{
-#if !FEATURE_CORECLR
- if (Environment.IsCLRHosted)
- TriggerCodeContractEscalationPolicy(failureKind, displayMessage, conditionText, innerException);
-#endif
// unwind
if (innerException == null) { innerException = eventArgs.thrownDuringHandler; }
throw new ContractException(failureKind, displayMessage, userMessage, conditionText, innerException);
[SuppressMessage("Microsoft.Usage", "CA1801:ReviewUnusedParameters", MessageId = "kind")]
[SuppressMessage("Microsoft.Usage", "CA1801:ReviewUnusedParameters", MessageId = "innerException")]
[System.Diagnostics.DebuggerNonUserCode]
-#if FEATURE_UNTRUSTED_CALLERS && !FEATURE_CORECLR
- [SecuritySafeCritical]
-#endif
static partial void TriggerFailureImplementation(ContractFailureKind kind, String displayMessage, String userMessage, String conditionText, Exception innerException)
{
// If we're here, our intent is to pop up a dialog box (if we can). For developers
// hosted in Internet Explorer, the assert window is great. If we cannot
// pop up a dialog box, throw an exception (consider a library compiled with
// "Assert On Failure" but used in a process that can't pop up asserts, like an
- // NT Service). For the CLR hosted by server apps like SQL or Exchange, we should
- // trigger escalation policy.
-#if !FEATURE_CORECLR
- if (Environment.IsCLRHosted)
- {
- TriggerCodeContractEscalationPolicy(kind, displayMessage, conditionText, innerException);
- // Hosts like SQL may choose to abort the thread, so we will not get here in all cases.
- // But if the host's chosen action was to throw an exception, we should throw an exception
- // here (which is easier to do in managed code with the right parameters).
- throw new ContractException(kind, displayMessage, userMessage, conditionText, innerException);
- }
-#endif // !FEATURE_CORECLR
+ // NT Service).
+
if (!Environment.UserInteractive) {
throw new ContractException(kind, displayMessage, userMessage, conditionText, innerException);
}
+
// May need to rethink Assert.Fail w/ TaskDialogIndirect as a model. Window title. Main instruction. Content. Expanded info.
// Optional info like string for collapsed text vs. expanded text.
String windowTitle = Environment.GetResourceString(GetResourceNameForFailure(kind));
return failureMessage;
}
}
-
-#if !FEATURE_CORECLR
- // Will trigger escalation policy, if hosted and the host requested us to do something (such as
- // abort the thread or exit the process). Starting in Dev11, for hosted apps the default behavior
- // is to throw an exception.
- // Implementation notes:
- // We implement our default behavior of throwing an exception by simply returning from our native
- // method inside the runtime and falling through to throw an exception.
- // We must call through this method before calling the method on the Environment class
- // because our security team does not yet support SecuritySafeCritical on P/Invoke methods.
- // Note this can be called in the context of throwing another exception (EnsuresOnThrow).
- [SecuritySafeCritical]
- [DebuggerNonUserCode]
- [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)]
- private static void TriggerCodeContractEscalationPolicy(ContractFailureKind failureKind, String message, String conditionText, Exception innerException)
- {
- String exceptionAsString = null;
- if (innerException != null)
- exceptionAsString = innerException.ToString();
- Environment.TriggerCodeContractFailure(failureKind, message, conditionText, exceptionAsString);
- }
-#endif // !FEATURE_CORECLR
}
} // namespace System.Runtime.CompilerServices
// Break causes a breakpoint to be signalled to an attached debugger. If no debugger
// is attached, the user is asked if he wants to attach a debugger. If yes, then the
// debugger is launched.
- [System.Security.SecuritySafeCritical] // auto-generated
public static void Break()
{
if (!Debugger.IsAttached)
BreakInternal();
}
- [System.Security.SecuritySafeCritical] // auto-generated
static void BreakCanThrow()
{
if (!Debugger.IsAttached)
BreakInternal();
}
- [System.Security.SecurityCritical] // auto-generated
[MethodImplAttribute(MethodImplOptions.InternalCall)]
private static extern void BreakInternal();
// Launch launches & attaches a debugger to the process. If a debugger is already attached,
// nothing happens.
//
- [System.Security.SecuritySafeCritical] // auto-generated
public static bool Launch()
{
if (Debugger.IsAttached)
}
}
- [System.Security.SecurityCritical] // auto-generated
[MethodImplAttribute(MethodImplOptions.InternalCall)]
private static extern bool LaunchInternal();
//
public static extern bool IsAttached
{
- [System.Security.SecuritySafeCritical] // auto-generated
[MethodImplAttribute(MethodImplOptions.InternalCall)]
get;
}
// Posts a message for the attached debugger. If there is no
// debugger attached, has no effect. The debugger may or may not
// report the message depending on its settings.
- [System.Security.SecuritySafeCritical] // auto-generated
[MethodImplAttribute(MethodImplOptions.InternalCall)]
public static extern void Log(int level, String category, String message);
// Checks to see if an attached debugger has logging enabled
//
- [System.Security.SecuritySafeCritical] // auto-generated
[MethodImplAttribute(MethodImplOptions.InternalCall)]
public static extern bool IsLogging();
// Posts a custom notification for the attached debugger. If there is no
// debugger attached, has no effect. The debugger may or may not
// report the notification depending on its settings.
- [System.Security.SecuritySafeCritical] // auto-generated
[MethodImplAttribute(MethodImplOptions.InternalCall)]
private static extern void CustomNotification(ICustomDebuggerNotification data);
}
- Contract.Assert((options & EventActivityOptions.Disable) == 0);
+ Debug.Assert((options & EventActivityOptions.Disable) == 0);
var currentActivity = m_current.Value;
var fullActivityName = NormalizeActivityName(providerName, activityName, task);
else
{
orphan.m_stopped = 1;
- Contract.Assert(orphan.m_stopped != 0);
+ Debug.Assert(orphan.m_stopped != 0);
}
orphan = orphan.m_creator;
}
/// <summary>
/// Turns on activity tracking. It is sticky, once on it stays on (race issues otherwise)
/// </summary>
- [System.Security.SecuritySafeCritical]
public void Enable()
{
if (m_current == null)
/// byte (since the top nibble can't be zero you can determine if this is true by seeing if
/// this byte is nonZero. This offset is needed to efficiently create the ID for child activities.
/// </summary>
- [System.Security.SecuritySafeCritical]
private unsafe void CreateActivityPathGuid(out Guid idRet, out int activityPathGuidOffset)
{
fixed (Guid* outPtr = &idRet)
/// sufficient space for this ID. By doing this, we preserve the fact that this activity
/// is a child (of unknown depth) from that ancestor.
/// </summary>
- [System.Security.SecurityCritical]
private unsafe void CreateOverflowGuid(Guid* outPtr)
{
// Search backwards for an ancestor that has sufficient space to put the ID.
/// is the maximum number of bytes that fit in a GUID) if the path did not fit.
/// If 'overflow' is true, then the number is encoded as an 'overflow number (which has a
/// special (longer prefix) that indicates that this ID is allocated differently
- [System.Security.SecurityCritical]
private static unsafe int AddIdToGuid(Guid* outPtr, int whereToAddId, uint id, bool overflow = false)
{
byte* ptr = (byte*)outPtr;
/// Thus if it is non-zero it adds to the current byte, otherwise it advances and writes
/// the new byte (in the high bits) of the next byte.
/// </summary>
- [System.Security.SecurityCritical]
private static unsafe void WriteNibble(ref byte* ptr, byte* endPtr, uint value)
{
- Contract.Assert(0 <= value && value < 16);
- Contract.Assert(ptr < endPtr);
+ Debug.Assert(0 <= value && value < 16);
+ Debug.Assert(ptr < endPtr);
if (*ptr != 0)
*ptr++ |= (byte)value;
private static bool m_setInformationMissing;
- [SecurityCritical]
UnsafeNativeMethods.ManifestEtw.EtwEnableCallback m_etwCallback; // Trace Callback function
private long m_regHandle; // Trace Registration Handle
private byte m_level; // Tracing Level
// <SatisfiesLinkDemand Name="Win32Exception..ctor(System.Int32)" />
// <ReferencesCritical Name="Method: EtwEnableCallBack(Guid&, Int32, Byte, Int64, Int64, Void*, Void*):Void" Ring="1" />
// </SecurityKernel>
- [System.Security.SecurityCritical]
internal unsafe void Register(Guid providerGuid)
{
m_providerId = providerGuid;
// <SecurityKernel Critical="True" TreatAsSafe="Does not expose critical resource" Ring="1">
// <ReferencesCritical Name="Method: Deregister():Void" Ring="1" />
// </SecurityKernel>
- [System.Security.SecuritySafeCritical]
protected virtual void Dispose(bool disposing)
{
//
// <UsesUnsafeCode Name="Parameter filterData of type: Void*" />
// <UsesUnsafeCode Name="Parameter callbackContext of type: Void*" />
// </SecurityKernel>
- [System.Security.SecurityCritical]
unsafe void EtwEnableCallBack(
[In] ref System.Guid sourceId,
[In] int controlCode,
/// ETW session that was added or remove, and the bool specifies whether the
/// session was added or whether it was removed from the set.
/// </summary>
- [System.Security.SecuritySafeCritical]
private List<Tuple<SessionInfo, bool>> GetSessions()
{
List<SessionInfo> liveSessionList = null;
/// for the current process ID, calling 'action' for each session, and passing it the
/// ETW session and the 'AllKeywords' the session enabled for the current provider.
/// </summary>
- [System.Security.SecurityCritical]
private unsafe void GetSessionInfo(Action<int, long> action)
{
// We wish the EventSource package to be legal for Windows Store applications.
}
if (providerInstance->NextOffset == 0)
break;
- Contract.Assert(0 <= providerInstance->NextOffset && providerInstance->NextOffset < buffSize);
+ Debug.Assert(0 <= providerInstance->NextOffset && providerInstance->NextOffset < buffSize);
var structBase = (byte*)providerInstance;
providerInstance = (UnsafeNativeMethods.ManifestEtw.TRACE_PROVIDER_INSTANCE_INFO*)&structBase[providerInstance->NextOffset];
}
/// returns an array of bytes representing the data, the index into that byte array where the data
/// starts, and the command being issued associated with that data.
/// </summary>
- [System.Security.SecurityCritical]
private unsafe bool GetDataFromController(int etwSessionId,
UnsafeNativeMethods.ManifestEtw.EVENT_FILTER_DESCRIPTOR* filterData, out ControllerCommand command, out byte[] data, out int dataStart)
{
// <UsesUnsafeCode Name="Parameter dataDescriptor of type: EventData*" />
// <UsesUnsafeCode Name="Parameter dataBuffer of type: Byte*" />
// </SecurityKernel>
- [System.Security.SecurityCritical]
private static unsafe object EncodeObject(ref object data, ref EventData* dataDescriptor, ref byte* dataBuffer, ref uint totalEventSize)
/*++
// </SecurityKernel>
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Maintainability", "CA1502:AvoidExcessiveComplexity", Justification = "Performance-critical code")]
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1045:DoNotPassTypesByReference")]
- [System.Security.SecurityCritical]
internal unsafe bool WriteEvent(ref EventDescriptor eventDescriptor, Guid* activityID, Guid* childActivityID, params object[] eventPayload)
{
int status = 0;
// <CallsSuppressUnmanagedCode Name="UnsafeNativeMethods.ManifestEtw.EventWrite(System.Int64,EventDescriptor&,System.UInt32,System.Void*):System.UInt32" />
// </SecurityKernel>
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1045:DoNotPassTypesByReference")]
- [System.Security.SecurityCritical]
internal unsafe protected bool WriteEvent(ref EventDescriptor eventDescriptor, Guid* activityID, Guid* childActivityID, int dataCount, IntPtr data)
{
if (childActivityID != null)
{
// activity transfers are supported only for events that specify the Send or Receive opcode
- Contract.Assert((EventOpcode)eventDescriptor.Opcode == EventOpcode.Send ||
+ Debug.Assert((EventOpcode)eventDescriptor.Opcode == EventOpcode.Send ||
(EventOpcode)eventDescriptor.Opcode == EventOpcode.Receive ||
(EventOpcode)eventDescriptor.Opcode == EventOpcode.Start ||
(EventOpcode)eventDescriptor.Opcode == EventOpcode.Stop);
}
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1045:DoNotPassTypesByReference")]
- [System.Security.SecurityCritical]
internal unsafe bool WriteEventRaw(
ref EventDescriptor eventDescriptor,
Guid* activityID,
// These are look-alikes to the Manifest based ETW OS APIs that have been shimmed to work
// either with Manifest ETW or Classic ETW (if Manifest based ETW is not available).
- [SecurityCritical]
private unsafe uint EventRegister(ref Guid providerId, UnsafeNativeMethods.ManifestEtw.EtwEnableCallback enableCallback)
{
m_providerId = providerId;
return UnsafeNativeMethods.ManifestEtw.EventRegister(ref providerId, enableCallback, null, ref m_regHandle);
}
- [SecurityCritical]
private uint EventUnregister(long registrationHandle)
{
return UnsafeNativeMethods.ManifestEtw.EventUnregister(registrationHandle);
}
private static int bitindex(uint n)
{
- Contract.Assert(bitcount(n) == 1);
+ Debug.Assert(bitcount(n) == 1);
int idx = 0;
while ((n & (1 << idx)) == 0)
idx++;
/// </summary>
internal static Guid InternalCurrentThreadActivityId
{
- [System.Security.SecurityCritical]
get
{
Guid retval = CurrentThreadActivityId;
internal static Guid FallbackActivityId
{
- [System.Security.SecurityCritical]
get
{
#pragma warning disable 612, 618
#pragma warning disable 1591
// optimized for common signatures (no args)
- [SecuritySafeCritical]
[SuppressMessage("Microsoft.Concurrency", "CA8001", Justification = "This does not need to be correct when racing with other threads")]
protected unsafe void WriteEvent(int eventId)
{
}
// optimized for common signatures (ints)
- [SecuritySafeCritical]
[SuppressMessage("Microsoft.Concurrency", "CA8001", Justification = "This does not need to be correct when racing with other threads")]
protected unsafe void WriteEvent(int eventId, int arg1)
{
}
}
- [SecuritySafeCritical]
[SuppressMessage("Microsoft.Concurrency", "CA8001", Justification = "This does not need to be correct when racing with other threads")]
protected unsafe void WriteEvent(int eventId, int arg1, int arg2)
{
}
}
- [SecuritySafeCritical]
[SuppressMessage("Microsoft.Concurrency", "CA8001", Justification = "This does not need to be correct when racing with other threads")]
protected unsafe void WriteEvent(int eventId, int arg1, int arg2, int arg3)
{
}
// optimized for common signatures (longs)
- [SecuritySafeCritical]
[SuppressMessage("Microsoft.Concurrency", "CA8001", Justification = "This does not need to be correct when racing with other threads")]
protected unsafe void WriteEvent(int eventId, long arg1)
{
}
}
- [SecuritySafeCritical]
[SuppressMessage("Microsoft.Concurrency", "CA8001", Justification = "This does not need to be correct when racing with other threads")]
protected unsafe void WriteEvent(int eventId, long arg1, long arg2)
{
}
}
- [SecuritySafeCritical]
[SuppressMessage("Microsoft.Concurrency", "CA8001", Justification = "This does not need to be correct when racing with other threads")]
protected unsafe void WriteEvent(int eventId, long arg1, long arg2, long arg3)
{
}
// optimized for common signatures (strings)
- [SecuritySafeCritical]
[SuppressMessage("Microsoft.Concurrency", "CA8001", Justification = "This does not need to be correct when racing with other threads")]
protected unsafe void WriteEvent(int eventId, string arg1)
{
}
}
- [SecuritySafeCritical]
[SuppressMessage("Microsoft.Concurrency", "CA8001", Justification = "This does not need to be correct when racing with other threads")]
protected unsafe void WriteEvent(int eventId, string arg1, string arg2)
{
}
}
- [SecuritySafeCritical]
[SuppressMessage("Microsoft.Concurrency", "CA8001", Justification = "This does not need to be correct when racing with other threads")]
protected unsafe void WriteEvent(int eventId, string arg1, string arg2, string arg3)
{
}
// optimized for common signatures (string and ints)
- [SecuritySafeCritical]
[SuppressMessage("Microsoft.Concurrency", "CA8001", Justification = "This does not need to be correct when racing with other threads")]
protected unsafe void WriteEvent(int eventId, string arg1, int arg2)
{
}
}
- [SecuritySafeCritical]
[SuppressMessage("Microsoft.Concurrency", "CA8001", Justification = "This does not need to be correct when racing with other threads")]
protected unsafe void WriteEvent(int eventId, string arg1, int arg2, int arg3)
{
}
// optimized for common signatures (string and longs)
- [SecuritySafeCritical]
[SuppressMessage("Microsoft.Concurrency", "CA8001", Justification = "This does not need to be correct when racing with other threads")]
protected unsafe void WriteEvent(int eventId, string arg1, long arg2)
{
}
// optimized for common signatures (long and string)
- [SecuritySafeCritical]
[SuppressMessage("Microsoft.Concurrency", "CA8001", Justification = "This does not need to be correct when racing with other threads")]
protected unsafe void WriteEvent(int eventId, long arg1, string arg2)
{
}
// optimized for common signatures (int and string)
- [SecuritySafeCritical]
[SuppressMessage("Microsoft.Concurrency", "CA8001", Justification = "This does not need to be correct when racing with other threads")]
protected unsafe void WriteEvent(int eventId, int arg1, string arg2)
{
}
}
- [SecuritySafeCritical]
[SuppressMessage("Microsoft.Concurrency", "CA8001", Justification = "This does not need to be correct when racing with other threads")]
protected unsafe void WriteEvent(int eventId, byte[] arg1)
{
}
}
- [SecuritySafeCritical]
[SuppressMessage("Microsoft.Concurrency", "CA8001", Justification = "This does not need to be correct when racing with other threads")]
protected unsafe void WriteEvent(int eventId, long arg1, byte[] arg2)
{
/// <param name="pointer">Pinned tracelogging-compatible metadata blob.</param>
/// <param name="size">The size of the metadata blob.</param>
/// <param name="reserved">Value for reserved: 2 for per-provider metadata, 1 for per-event metadata</param>
- [SecurityCritical]
internal unsafe void SetMetadata(byte* pointer, int size, int reserved)
{
this.m_Ptr = (long)(ulong)(UIntPtr)pointer;
/// }
/// </code>
/// </remarks>
- [SecurityCritical]
[CLSCompliant(false)]
protected unsafe void WriteEventCore(int eventId, int eventDataCount, EventSource.EventData* data)
{
/// }
/// </code>
/// </remarks>
- [SecurityCritical]
[CLSCompliant(false)]
protected unsafe void WriteEventWithRelatedActivityIdCore(int eventId, Guid* relatedActivityId, int eventDataCount, EventSource.EventData* data)
{
{
try
{
- Contract.Assert(m_eventData != null); // You must have initialized this if you enabled the source.
+ Debug.Assert(m_eventData != null); // You must have initialized this if you enabled the source.
if (relatedActivityId != null)
ValidateEventOpcodeForTransfer(ref m_eventData[eventId], m_eventData[eventId].Name);
/// method signature. Even if you use this for rare events, this call should be guarded by an <see cref="IsEnabled()"/>
/// check so that the varargs call is not made when the EventSource is not active.
/// </summary>
- [SecuritySafeCritical]
[SuppressMessage("Microsoft.Concurrency", "CA8001", Justification = "This does not need to be correct when racing with other threads")]
protected unsafe void WriteEvent(int eventId, params object[] args)
{
/// particular method signature. Even if you use this for rare events, this call should be guarded by an <see cref="IsEnabled()"/>
/// check so that the varargs call is not made when the EventSource is not active.
/// </summary>
- [SecuritySafeCritical]
protected unsafe void WriteEventWithRelatedActivityId(int eventId, Guid relatedActivityId, params object[] args)
{
WriteEventVarargs(eventId, &relatedActivityId, args);
#if FEATURE_ACTIVITYSAMPLING
internal void WriteStringToListener(EventListener listener, string msg, SessionMask m)
{
- Contract.Assert(listener == null || (uint)m == (uint)SessionMask.FromId(0));
+ Debug.Assert(listener == null || (uint)m == (uint)SessionMask.FromId(0));
if (m_eventSourceEnabled)
{
}
#endif
- [SecurityCritical]
private unsafe void WriteEventRaw(
string eventName,
ref EventDescriptor eventDescriptor,
/// member, and any future access to the "Log" would throw the cached exception).
/// </summary>
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1720:IdentifiersShouldNotContainTypeNames", MessageId = "guid")]
- [SecuritySafeCritical]
private unsafe void Initialize(Guid eventSourceGuid, string eventSourceName, string[] traits)
{
try
}
#endif // FEATURE_MANAGED_ETW
- Contract.Assert(!m_eventSourceEnabled); // We can't be enabled until we are completely initted.
+ Debug.Assert(!m_eventSourceEnabled); // We can't be enabled until we are completely initted.
// We are logically completely initialized at this point.
m_completelyInited = true;
}
return new Guid(bytes);
}
- [SecurityCritical]
private unsafe object DecodeObject(int eventId, int parameterId, ref EventSource.EventData* data)
{
// TODO FIX : We use reflection which in turn uses EventSource, right now we carefully avoid
return dispatcher;
}
- [SecurityCritical]
private unsafe void WriteEventVarargs(int eventId, Guid* childActivityID, object[] args)
{
if (m_eventSourceEnabled)
{
try
{
- Contract.Assert(m_eventData != null); // You must have initialized this if you enabled the source.
+ Debug.Assert(m_eventData != null); // You must have initialized this if you enabled the source.
if (childActivityID != null)
{
ValidateEventOpcodeForTransfer(ref m_eventData[eventId], m_eventData[eventId].Name);
}
}
- [SecurityCritical]
unsafe private object[] SerializeEventArgs(int eventId, object[] args)
{
TraceLoggingEventTypes eventTypes = m_eventData[eventId].TraceLoggingEventTypes;
return sum;
}
- [SecurityCritical]
unsafe private void WriteToAllListeners(int eventId, Guid* childActivityID, int eventDataCount, EventSource.EventData* data)
{
// We represent a byte[] as a integer denoting the length and then a blob of bytes in the data pointer. This causes a spurious
}
// helper for writing to all EventListeners attached the current eventSource.
- [SecurityCritical]
unsafe private void WriteToAllListeners(int eventId, Guid* childActivityID, params object[] args)
{
EventWrittenEventArgs eventCallbackArgs = new EventWrittenEventArgs(this);
DispatchToAllListeners(eventId, childActivityID, eventCallbackArgs);
}
- [SecurityCritical]
private unsafe void DispatchToAllListeners(int eventId, Guid* childActivityID, EventWrittenEventArgs eventCallbackArgs)
{
Exception lastThrownException = null;
for (EventDispatcher dispatcher = m_Dispatchers; dispatcher != null; dispatcher = dispatcher.m_Next)
{
- Contract.Assert(dispatcher.m_EventEnabled != null);
+ Debug.Assert(dispatcher.m_EventEnabled != null);
if (eventId == -1 || dispatcher.m_EventEnabled[eventId])
{
#if FEATURE_ACTIVITYSAMPLING
}
}
- [SecuritySafeCritical]
[SuppressMessage("Microsoft.Concurrency", "CA8001", Justification = "This does not need to be correct when racing with other threads")]
private unsafe void WriteEventString(EventLevel level, long keywords, string msgString)
{
}
#if FEATURE_ACTIVITYSAMPLING
- [SecurityCritical]
unsafe private SessionMask GetEtwSessionMask(int eventId, Guid* childActivityID)
{
SessionMask etwSessions = new SessionMask();
{
// PRECONDITION: We should be holding the EventListener.EventListenersLock
// We defer commands until we are completely inited. This allows error messages to be sent.
- Contract.Assert(m_completelyInited);
+ Debug.Assert(m_completelyInited);
#if FEATURE_MANAGED_ETW
if (m_provider == null) // If we failed to construct
try
{
EnsureDescriptorsInitialized();
- Contract.Assert(m_eventData != null);
+ Debug.Assert(m_eventData != null);
// Find the per-EventSource dispatcher corresponding to registered dispatcher
commandArgs.dispatcher = GetDispatcher(commandArgs.listener);
// hasn't changed.
// sesisonId = SessionMask.MAX when one of the legacy ETW sessions changed
// 0 <= perEventSourceSessionId < SessionMask.MAX for activity-tracing aware sessions
- Contract.Assert(commandArgs.perEventSourceSessionId >= -1 && commandArgs.perEventSourceSessionId <= SessionMask.MAX);
+ Debug.Assert(commandArgs.perEventSourceSessionId >= -1 && commandArgs.perEventSourceSessionId <= SessionMask.MAX);
// Send the manifest if we are enabling an ETW session
if (bSessionEnable && commandArgs.dispatcher == null)
// things like log messages, or test if keywords are enabled in the callback.
if (commandArgs.enable)
{
- Contract.Assert(m_eventData != null);
+ Debug.Assert(m_eventData != null);
m_eventSourceEnabled = true;
}
}
// These are not used for non-update commands and thus should always be 'default' values
- // Contract.Assert(enable == true);
- // Contract.Assert(level == EventLevel.LogAlways);
- // Contract.Assert(matchAnyKeyword == EventKeywords.None);
+ // Debug.Assert(enable == true);
+ // Debug.Assert(level == EventLevel.LogAlways);
+ // Debug.Assert(matchAnyKeyword == EventKeywords.None);
this.OnEventCommand(commandArgs);
var eventCommandCallback = m_eventCommandExecuted;
get { return m_eventSourceDisposed; }
}
- [SecuritySafeCritical]
private void EnsureDescriptorsInitialized()
{
#if !ES_BUILD_STANDALONE
- Contract.Assert(Monitor.IsEntered(EventListener.EventListenersLock));
+ Debug.Assert(Monitor.IsEntered(EventListener.EventListenersLock));
#endif
if (m_eventData == null)
{
if (eventSourceGuid.Equals(Guid.Empty) || eventSourceName == null || eventData == null || manifest == null)
{
// GetMetadata failed, so we have to set it via reflection.
- Contract.Assert(m_rawManifest == null);
+ Debug.Assert(m_rawManifest == null);
m_rawManifest = CreateManifestAndDescriptors(this.GetType(), Name, this);
- Contract.Assert(m_eventData != null);
+ Debug.Assert(m_eventData != null);
}
else
// Send out the ETW manifest XML out to ETW
// Today, we only send the manifest to ETW, custom listeners don't get it.
- [SecuritySafeCritical]
private unsafe bool SendManifest(byte[] rawManifest)
{
bool success = true;
if (rawManifest == null)
return false;
- Contract.Assert(!SelfDescribingEvents);
+ Debug.Assert(!SelfDescribingEvents);
#if FEATURE_MANAGED_ETW
fixed (byte* dataPtr = rawManifest)
{
Attribute attr = null;
- Contract.Assert(data.ConstructorArguments.Count <= 1);
+ Debug.Assert(data.ConstructorArguments.Count <= 1);
if (data.ConstructorArguments.Count == 1)
{
int startEventId = eventAttribute.EventId - 1;
if (eventData != null && startEventId < eventData.Length)
{
- Contract.Assert(0 <= startEventId); // Since we reserve id 0, we know that id-1 is <= 0
+ Debug.Assert(0 <= startEventId); // Since we reserve id 0, we know that id-1 is <= 0
EventMetadata startEventMetadata = eventData[startEventId];
// If you remove the Stop and add a Start does that name match the Start Event's Name?
// We give a task to things if they don't have one.
// TODO this is moderately expensive (N*N). We probably should not even bother....
- Contract.Assert(eventAttribute.Task != EventTask.None || eventAttribute.Opcode != EventOpcode.Info);
+ Debug.Assert(eventAttribute.Task != EventTask.None || eventAttribute.Opcode != EventOpcode.Info);
for (int idx = 0; idx < eventData.Length; ++idx)
{
// skip unused Event IDs.
/// </summary>
/// <param name="method">The method to probe.</param>
/// <returns>The literal value or -1 if the value could not be determined. </returns>
- [SecuritySafeCritical]
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Maintainability", "CA1502:AvoidExcessiveComplexity", Justification = "Switch statement is clearer than alternatives")]
static private int GetHelperCallFirstArg(MethodInfo method)
{
goto default;
break;
default:
- /* Contract.Assert(false, "Warning: User validation code sub-optimial: Unsuported opcode " + instrs[idx] +
+ /* Debug.Assert(false, "Warning: User validation code sub-optimial: Unsuported opcode " + instrs[idx] +
" at " + idx + " in method " + method.Name); */
return -1;
}
{
get
{
- Contract.Assert(((m_config & EventSourceSettings.EtwManifestEventFormat) != 0) !=
+ Debug.Assert(((m_config & EventSourceSettings.EtwManifestEventFormat) != 0) !=
((m_config & EventSourceSettings.EtwSelfDescribingEventFormat) != 0));
return (m_config & EventSourceSettings.EtwSelfDescribingEventFormat) != 0;
}
#if FEATURE_ACTIVITYSAMPLING
private void ReportActivitySamplingInfo(EventListener listener, SessionMask sessions)
{
- Contract.Assert(listener == null || (uint)sessions == (uint)SessionMask.FromId(0));
+ Debug.Assert(listener == null || (uint)sessions == (uint)SessionMask.FromId(0));
for (int perEventSourceSessionId = 0; perEventSourceSessionId < SessionMask.MAX; ++perEventSourceSessionId)
{
if (listener == null)
{
EtwSession etwSession = m_etwSessionIdMap[perEventSourceSessionId];
- Contract.Assert(etwSession != null);
+ Debug.Assert(etwSession != null);
af = etwSession.m_activityFilter;
}
else
if (!s_EventSourceShutdownRegistered)
{
s_EventSourceShutdownRegistered = true;
-#if (!ES_BUILD_PCL && !FEATURE_CORECLR && !PROJECTN)
- AppDomain.CurrentDomain.ProcessExit += DisposeOnShutdown;
- AppDomain.CurrentDomain.DomainUnload += DisposeOnShutdown;
-#endif
}
private static void RemoveReferencesToListenerInEventSources(EventListener listenerToRemove)
{
#if !ES_BUILD_STANDALONE
- Contract.Assert(Monitor.IsEntered(EventListener.EventListenersLock));
+ Debug.Assert(Monitor.IsEntered(EventListener.EventListenersLock));
#endif
// Foreach existing EventSource in the appdomain
foreach (WeakReference eventSourceRef in s_EventSources)
EventDispatcher cur = prev.m_Next;
if (cur == null)
{
- Contract.Assert(false, "EventSource did not have a registered EventListener!");
+ Debug.Assert(false, "EventSource did not have a registered EventListener!");
break;
}
if (cur.m_Listener == listenerToRemove)
EventSource eventSource = eventSourceRef.Target as EventSource;
if (eventSource == null)
continue;
- Contract.Assert(eventSource.m_id == id, "Unexpected event source ID.");
+ Debug.Assert(eventSource.m_id == id, "Unexpected event source ID.");
// None listeners on eventSources exist in the dispatcher list.
EventDispatcher dispatcher = eventSource.m_Dispatchers;
while (dispatcher != null)
{
- Contract.Assert(allListeners.ContainsKey(dispatcher.m_Listener), "EventSource has a listener not on the global list.");
+ Debug.Assert(allListeners.ContainsKey(dispatcher.m_Listener), "EventSource has a listener not on the global list.");
dispatcher = dispatcher.m_Next;
}
dispatcher = eventSource.m_Dispatchers;
for (;;)
{
- Contract.Assert(dispatcher != null, "Listener is not on all eventSources.");
+ Debug.Assert(dispatcher != null, "Listener is not on all eventSources.");
if (dispatcher.m_Listener == listener)
break;
dispatcher = dispatcher.m_Next;
/// </summary>
public Guid ActivityId
{
- [System.Security.SecurityCritical]
get { return EventSource.CurrentThreadActivityId; }
}
/// </summary>
public Guid RelatedActivityId
{
- [System.Security.SecurityCritical]
get;
internal set;
}
if (m_payloadNames == null)
{
// Self described events are identified by id -1.
- Contract.Assert(EventId != -1);
+ Debug.Assert(EventId != -1);
var names = new List<string>();
foreach (var parameter in m_eventSource.m_eventData[EventId].Parameters)
public static void DisableFilter(ref ActivityFilter filterList, EventSource source)
{
#if !ES_BUILD_STANDALONE
- Contract.Assert(Monitor.IsEntered(EventListener.EventListenersLock));
+ Debug.Assert(Monitor.IsEntered(EventListener.EventListenersLock));
#endif
if (filterList == null)
string startEvents)
{
#if !ES_BUILD_STANDALONE
- Contract.Assert(Monitor.IsEntered(EventListener.EventListenersLock));
+ Debug.Assert(Monitor.IsEntered(EventListener.EventListenersLock));
#endif
// first remove all filters associated with 'source'
/// If 'childActivityID' is present, it will be added to the active set if the
/// current activity is active.
/// </summary>
- [SecurityCritical]
unsafe public static bool PassesActivityFilter(
ActivityFilter filterList,
Guid* childActivityID,
EventSource source,
int eventId)
{
- Contract.Assert(filterList != null && filterList.m_activeActivities != null);
+ Debug.Assert(filterList != null && filterList.m_activeActivities != null);
bool shouldBeLogged = false;
if (triggeringEvent)
{
return shouldBeLogged;
}
- [System.Security.SecuritySafeCritical]
public static bool IsCurrentActivityActive(ActivityFilter filterList)
{
var activeActivities = GetActiveActivities(filterList);
/// value for 'currentActivityid' is an indication tha caller has already verified
/// that the current activity is active.
/// </summary>
- [SecurityCritical]
unsafe public static void FlowActivityIfNeeded(ActivityFilter filterList, Guid* currentActivityId, Guid* childActivityID)
{
- Contract.Assert(childActivityID != null);
+ Debug.Assert(childActivityID != null);
var activeActivities = GetActiveActivities(filterList);
- Contract.Assert(activeActivities != null);
+ Debug.Assert(activeActivities != null);
// take currentActivityId == null to mean we *know* the current activity is "active"
if (currentActivityId != null && !activeActivities.ContainsKey(*currentActivityId))
public void Dispose()
{
#if !ES_BUILD_STANDALONE
- Contract.Assert(Monitor.IsEntered(EventListener.EventListenersLock));
+ Debug.Assert(Monitor.IsEntered(EventListener.EventListenersLock));
#endif
// m_myActivityDelegate is still alive (held by the static EventSource.s_activityDying).
// Therefore we are ok to take a dependency on m_myActivityDelegate being valid even
m_samplingFreq = samplingFreq;
m_next = existingFilter;
- Contract.Assert(existingFilter == null ||
+ Debug.Assert(existingFilter == null ||
(existingFilter.m_activeActivities == null) == (existingFilter.m_rootActiveActivities == null));
// if this is the first filter we add for this session, we need to create a new
private static bool EnableFilter(ref ActivityFilter filterList, EventSource source, int perEventSourceSessionId, int eventId, int samplingFreq)
{
#if !ES_BUILD_STANDALONE
- Contract.Assert(Monitor.IsEntered(EventListener.EventListenersLock));
+ Debug.Assert(Monitor.IsEntered(EventListener.EventListenersLock));
#endif
- Contract.Assert(samplingFreq > 0);
- Contract.Assert(eventId >= 0);
+ Debug.Assert(samplingFreq > 0);
+ Debug.Assert(eventId >= 0);
filterList = new ActivityFilter(source, perEventSourceSessionId, eventId, samplingFreq, filterList);
public static void RemoveEtwSession(EtwSession etwSession)
{
- Contract.Assert(etwSession != null);
+ Debug.Assert(etwSession != null);
if (s_etwSessions == null || etwSession == null)
return;
public static SessionMask FromId(int perEventSourceSessionId)
{
- Contract.Assert(perEventSourceSessionId < MAX);
+ Debug.Assert(perEventSourceSessionId < MAX);
return new SessionMask((uint)1 << perEventSourceSessionId);
}
{
get
{
- Contract.Assert(perEventSourceSessionId < MAX);
+ Debug.Assert(perEventSourceSessionId < MAX);
return (m_mask & (1 << perEventSourceSessionId)) != 0;
}
set
{
- Contract.Assert(perEventSourceSessionId < MAX);
+ Debug.Assert(perEventSourceSessionId < MAX);
if (value) m_mask |= ((uint)1 << perEventSourceSessionId);
else m_mask &= ~((uint)1 << perEventSourceSessionId);
}
private EventChannelType EventChannelToChannelType(EventChannel channel)
{
#if !ES_BUILD_STANDALONE
- Contract.Assert(channel >= EventChannel.Admin && channel <= EventChannel.Debug);
+ Debug.Assert(channel >= EventChannel.Admin && channel <= EventChannel.Debug);
#endif
return (EventChannelType)((int)channel - (int)EventChannel.Admin + (int)EventChannelType.Admin);
}
#endif
public void StartEvent(string eventName, EventAttribute eventAttribute)
{
- Contract.Assert(numParams == 0);
- Contract.Assert(this.eventName == null);
+ Debug.Assert(numParams == 0);
+ Debug.Assert(this.eventName == null);
this.eventName = eventName;
numParams = 0;
byteArrArgIndices = null;
private static List<CultureInfo> GetSupportedCultures(ResourceManager resources)
{
var cultures = new List<CultureInfo>();
-#if !ES_BUILD_PCL && !FEATURE_CORECLR && !PROJECTN
- foreach (CultureInfo ci in CultureInfo.GetCultures(CultureTypes.SpecificCultures /*| CultureTypes.NeutralCultures*/))
- {
- if (resources.GetResourceSet(ci, true, false) != null)
- cultures.Add(ci);
- }
-#endif // !ES_BUILD_PCL && !FEATURE_CORECLR
+
if (!cultures.Contains(CultureInfo.CurrentUICulture))
cultures.Insert(0, CultureInfo.CurrentUICulture);
return cultures;
/// </summary>
/// <param name="activityId">A Guid that represents the new activity with which to mark
/// the current thread</param>
- [System.Security.SecuritySafeCritical]
public static void SetCurrentThreadActivityId(Guid activityId)
{
if (TplEtwProvider.Log != null)
/// the current thread</param>
/// <param name="oldActivityThatWillContinue">The Guid that represents the current activity
/// which will continue at some point in the future, on the current thread</param>
- [System.Security.SecuritySafeCritical]
public static void SetCurrentThreadActivityId(Guid activityId, out Guid oldActivityThatWillContinue)
{
oldActivityThatWillContinue = activityId;
/// </summary>
public static Guid CurrentThreadActivityId
{
- [System.Security.SecuritySafeCritical]
get
{
// We ignore errors to keep with the convention that EventSources do not throw
internal partial class EventProvider
{
- [System.Security.SecurityCritical]
internal unsafe int SetInformation(
UnsafeNativeMethods.ManifestEtw.EVENT_INFO_CLASS eventInfoClass,
IntPtr data,
/// EventWrite. The instance must be Disabled before the arrays referenced
/// by the pointers are freed or unpinned.
/// </summary>
- [SecurityCritical]
internal unsafe struct DataCollector
{
[ThreadStatic]
using System.Collections.Generic;
using System.Collections;
+using System.Diagnostics;
#if !ES_BUILD_AGAINST_DOTNET_V35
using Contract = System.Diagnostics.Contracts.Contract;
{
internal EventPayload(List<string> payloadNames, List<object> payloadValues)
{
- Contract.Assert(payloadNames.Count == payloadValues.Count);
+ Debug.Assert(payloadNames.Count == payloadValues.Count);
m_names = payloadNames;
m_values = payloadValues;
using System.Reflection;
using System.Runtime.InteropServices;
+using System.Diagnostics;
#if !ES_BUILD_AGAINST_DOTNET_V35
using Contract = System.Diagnostics.Contracts.Contract;
{
get
{
- Contract.Assert(_scalarLength == 0, "This ReflectedValue refers to an unboxed value type, not a reference type or boxed value type.");
+ Debug.Assert(_scalarLength == 0, "This ReflectedValue refers to an unboxed value type, not a reference type or boxed value type.");
return _reference;
}
}
{
get
{
- Contract.Assert(_scalarLength > 0, "This ReflectedValue refers to a reference type or boxed value type, not an unboxed value type");
+ Debug.Assert(_scalarLength > 0, "This ReflectedValue refers to a reference type or boxed value type, not an unboxed value type");
return _scalar;
}
}
{
get
{
- Contract.Assert(_scalarLength > 0, "This ReflectedValue refers to a reference type or boxed value type, not an unboxed value type");
+ Debug.Assert(_scalarLength > 0, "This ReflectedValue refers to a reference type or boxed value type, not an unboxed value type");
return _scalarLength;
}
}
using System;
using System.Collections.Generic;
using System.Reflection;
+using System.Diagnostics;
#if !ES_BUILD_AGAINST_DOTNET_V35
using Contract = System.Diagnostics.Contracts.Contract;
: base(type)
{
var typeArgs = type.GenericTypeArguments;
- Contract.Assert(typeArgs.Length == 1);
+ Debug.Assert(typeArgs.Length == 1);
this.valueInfo = TraceLoggingTypeInfo.GetInstance(typeArgs[0], recursionCheck);
this.hasValueGetter = PropertyValue.GetPropertyGetter(type.GetTypeInfo().GetDeclaredProperty("HasValue"));
this.valueGetter = PropertyValue.GetPropertyGetter(type.GetTypeInfo().GetDeclaredProperty("Value"));
/// full-trust code, this abstraction is unnecessary (though it probably
/// doesn't hurt anything).
/// </summary>
- [SecuritySafeCritical]
internal unsafe class TraceLoggingDataCollector
{
internal static readonly TraceLoggingDataCollector Instance = new TraceLoggingDataCollector();
/// (Native API: EventWriteTransfer)
/// </summary>
/// <param name="eventName">The name of the event. Must not be null.</param>
- [SecuritySafeCritical]
public unsafe void Write(string eventName)
{
if (eventName == null)
/// Options for the event, such as the level, keywords, and opcode. Unset
/// options will be set to default values.
/// </param>
- [SecuritySafeCritical]
public unsafe void Write(string eventName, EventSourceOptions options)
{
if (eventName == null)
/// public instance properties of data will be written recursively to
/// create the fields of the event.
/// </param>
- [SecuritySafeCritical]
public unsafe void Write<T>(
string eventName,
T data)
/// public instance properties of data will be written recursively to
/// create the fields of the event.
/// </param>
- [SecuritySafeCritical]
public unsafe void Write<T>(
string eventName,
EventSourceOptions options,
/// public instance properties of data will be written recursively to
/// create the fields of the event.
/// </param>
- [SecuritySafeCritical]
public unsafe void Write<T>(
string eventName,
ref EventSourceOptions options,
/// public instance properties of data will be written recursively to
/// create the fields of the event.
/// </param>
- [SecuritySafeCritical]
public unsafe void Write<T>(
string eventName,
ref EventSourceOptions options,
/// the values must match the number and types of the fields described by the
/// eventTypes parameter.
/// </param>
- [SecuritySafeCritical]
private unsafe void WriteMultiMerge(
string eventName,
ref EventSourceOptions options,
/// the values must match the number and types of the fields described by the
/// eventTypes parameter.
/// </param>
- [SecuritySafeCritical]
private unsafe void WriteMultiMergeInner(
string eventName,
ref EventSourceOptions options,
/// The number and types of the values must match the number and types of the
/// fields described by the eventTypes parameter.
/// </param>
- [SecuritySafeCritical]
internal unsafe void WriteMultiMerge(
string eventName,
ref EventSourceOptions options,
#endif // FEATURE_MANAGED_ETW
}
- [SecuritySafeCritical]
private unsafe void WriteImpl(
string eventName,
ref EventSourceOptions options,
}
}
- [SecurityCritical]
private unsafe void WriteToAllListeners(string eventName, ref EventDescriptor eventDescriptor, EventTags tags, Guid* pActivityId, EventPayload payload)
{
EventWrittenEventArgs eventCallbackArgs = new EventWrittenEventArgs(this);
System.Runtime.ConstrainedExecution.Consistency.WillNotCorruptState,
System.Runtime.ConstrainedExecution.Cer.Success)]
#endif
- [SecurityCritical]
[NonEvent]
private unsafe void WriteCleanup(GCHandle* pPins, int cPins)
{
//
// All switches (except for the global LogSwitch) have a parent LogSwitch.
//
- [System.Security.SecuritySafeCritical] // auto-generated
public LogSwitch(String name, String description, LogSwitch parent)
{
if (name != null && name.Length == 0)
throw new ArgumentNullException ((name==null ? nameof(name) : nameof(parent)));
}
- [System.Security.SecuritySafeCritical] // auto-generated
internal LogSwitch(String name, String description)
{
strName = name;
public virtual LoggingLevels MinimumLevel
{
get { return iLevel; }
- [System.Security.SecuritySafeCritical] // auto-generated
set
{
iLevel = value;
using System.Security.Permissions;
using System.Diagnostics.Contracts;
- // There is no good reason for the methods of this class to be virtual.
- // In order to ensure trusted code can trust the data it gets from a
- // StackTrace, we use an InheritanceDemand to prevent partially-trusted
- // subclasses.
-#if !FEATURE_CORECLR
- [SecurityPermission(SecurityAction.InheritanceDemand, UnmanagedCode=true)]
-#endif
+ // There is no good reason for the methods of this class to be virtual.
[Serializable]
[System.Runtime.InteropServices.ComVisible(true)]
public class StackFrame
}
// Constructs a StackFrame corresponding to the active stack frame.
-#if FEATURE_CORECLR
- [System.Security.SecuritySafeCritical]
-#endif
public StackFrame()
{
InitMembers();
}
// Constructs a StackFrame corresponding to the active stack frame.
- #if FEATURE_CORECLR
- [System.Security.SecurityCritical] // auto-generated
- #endif
public StackFrame(bool fNeedFileInfo)
{
InitMembers();
// Constructs a StackFrame corresponding to a calling stack frame.
//
- #if FEATURE_CORECLR
- [System.Security.SecurityCritical] // auto-generated
- #endif
public StackFrame(int skipFrames, bool fNeedFileInfo)
{
InitMembers();
// information is normally extracted from the debugging symbols
// for the executable.
//
- #if FEATURE_CORECLR
- [System.Security.SecurityCritical] // auto-generated
- #else
- [System.Security.SecuritySafeCritical]
- #endif
public virtual String GetFileName()
{
if (strFileName != null)
// Builds a readable representation of the stack frame
//
- [System.Security.SecuritySafeCritical] // auto-generated
public override String ToString()
{
StringBuilder sb = new StringBuilder(255);
IntPtr inMemoryPdbAddress, int inMemoryPdbSize, int methodToken, int ilOffset,
out string sourceFile, out int sourceLine, out int sourceColumn);
-#if FEATURE_CORECLR
private static Type s_symbolsType = null;
private static MethodInfo s_symbolsMethodInfo = null;
[ThreadStatic]
private static int t_reentrancy = 0;
-#endif
-
+
public StackFrameHelper(Thread target)
{
targetThread = target;
{
StackTrace.GetStackFramesInternal(this, iSkip, fNeedFileInfo, exception);
-#if FEATURE_CORECLR
if (!fNeedFileInfo)
return;
{
t_reentrancy--;
}
-#endif
}
void IDisposable.Dispose()
{
-#if FEATURE_CORECLR
if (getSourceLineInfo != null)
{
IDisposable disposable = getSourceLineInfo.Target as IDisposable;
disposable.Dispose();
}
}
-#endif
}
- [System.Security.SecuritySafeCritical]
public virtual MethodBase GetMethodBase(int i)
{
// There may be a better way to do this.
// serialization implementation
//
[OnSerializing]
- [SecuritySafeCritical]
void OnSerializing(StreamingContext context)
{
// this is called in the process of serializing this object.
}
[OnDeserialized]
- [SecuritySafeCritical]
void OnDeserialized(StreamingContext context)
{
// after we are done deserializing we need to transform the rgMethodBase in rgMethodHandle
// In order to ensure trusted code can trust the data it gets from a
// StackTrace, we use an InheritanceDemand to prevent partially-trusted
// subclasses.
-#if !FEATURE_CORECLR
- [SecurityPermission(SecurityAction.InheritanceDemand, UnmanagedCode=true)]
-#endif
[Serializable]
[System.Runtime.InteropServices.ComVisible(true)]
public class StackTrace
private int m_iMethodsToSkip;
// Constructs a stack trace from the current location.
-#if FEATURE_CORECLR
- [System.Security.SecuritySafeCritical]
-#endif
public StackTrace()
{
m_iNumOfFrames = 0;
// Constructs a stack trace from the current location.
//
-#if FEATURE_CORECLR
- [System.Security.SecurityCritical] // auto-generated
-#endif
public StackTrace(bool fNeedFileInfo)
{
m_iNumOfFrames = 0;
// Constructs a stack trace from the current location, in a caller's
// frame
//
-#if FEATURE_CORECLR
- [System.Security.SecurityCritical] // auto-generated
-#endif
public StackTrace(int skipFrames)
{
// Constructs a stack trace from the current location, in a caller's
// frame
//
-#if FEATURE_CORECLR
- [System.Security.SecurityCritical] // auto-generated
-#endif
public StackTrace(int skipFrames, bool fNeedFileInfo)
{
// Constructs a stack trace from the current location.
//
-#if FEATURE_CORECLR
- [System.Security.SecurityCritical] // auto-generated
-#endif
public StackTrace(Exception e, bool fNeedFileInfo)
{
if (e == null)
// Constructs a stack trace from the current location, in a caller's
// frame
//
-#if FEATURE_CORECLR
- [System.Security.SecurityCritical] // auto-generated
-#endif
public StackTrace(Exception e, int skipFrames)
{
if (e == null)
// Constructs a stack trace from the current location, in a caller's
// frame
//
-#if FEATURE_CORECLR
- [System.Security.SecurityCritical] // auto-generated
-#endif
public StackTrace(Exception e, int skipFrames, bool fNeedFileInfo)
{
if (e == null)
// Constructs a stack trace for the given thread
//
-#if FEATURE_CORECLR
- [System.Security.SecurityCritical] // auto-generated
-#endif
[Obsolete("This constructor has been deprecated. Please use a constructor that does not require a Thread parameter. http://go.microsoft.com/fwlink/?linkid=14202")]
public StackTrace(Thread targetThread, bool needFileInfo)
{
}
- [System.Security.SecuritySafeCritical]
[MethodImplAttribute(MethodImplOptions.InternalCall)]
internal static extern void GetStackFramesInternal(StackFrameHelper sfh, int iSkip, bool fNeedFileInfo, Exception e);
// Builds a readable representation of the stack trace
//
-#if FEATURE_CORECLR
- [System.Security.SecuritySafeCritical]
-#endif
public override String ToString()
{
// Include a trailing newline for backwards compatibility
// Builds a readable representation of the stack trace, specifying
// the format for backwards compatibility.
-#if FEATURE_CORECLR
- [System.Security.SecurityCritical] // auto-generated
-#endif
internal String ToString(TraceFormat traceFormat)
{
bool displayFilenames = true; // we'll try, but demand may fail
else
fFirstTyParam = false;
- sb.Append(typars[k].Name);
+ sb.Append(typars[k].Name);
k++;
}
sb.Append(']');
}
ParameterInfo[] pi = null;
-#if FEATURE_CORECLR
try
{
-#endif
pi = mb.GetParameters();
-#if FEATURE_CORECLR
}
catch
{
// The parameter info cannot be loaded, so we don't
// append the parameter list.
}
-#endif
if (pi != null)
{
// arguments printing
{
fileName = sf.GetFileName();
}
-#if FEATURE_CAS_POLICY
- catch (NotSupportedException)
- {
- // Having a deprecated stack modifier on the callstack (such as Deny) will cause
- // a NotSupportedException to be thrown. Since we don't know if the app can
- // access the file names, we'll conservatively hide them.
- displayFilenames = false;
- }
-#endif // FEATURE_CAS_POLICY
catch (SecurityException)
{
// If the demand for displaying filenames fails, then it won't
// This helper is called from within the EE to construct a string representation
// of the current stack trace.
-#if FEATURE_CORECLR
- [System.Security.SecurityCritical] // auto-generated
-#endif
private static String GetManagedStackTraceStringHelper(bool fNeedFileInfo)
{
// Note all the frames in System.Diagnostics will be skipped when capturing
// Define a source document. Guid's will be provided for the
// languages, vendors, and document types that we currently know
// about.
- #if FEATURE_CORECLR
- [System.Security.SecurityCritical] // auto-generated
- #endif
ISymbolDocumentWriter DefineDocument(String url,
Guid language,
Guid languageVendor,
// Define the method that the user has defined as their entrypoint
// for this module. This would be, perhaps, the user's main method
// rather than compiler generated stubs before main.
- #if FEATURE_CORECLR
- [System.Security.SecurityCritical] // auto-generated
- #endif
void SetUserEntryPoint(SymbolToken entryMethod);
// Open a method to emit symbol information into. The given method
// defined symbols for that method.
//
// There can be only one open method at a time.
- #if FEATURE_CORECLR
- [System.Security.SecurityCritical] // auto-generated
- #endif
void OpenMethod(SymbolToken method);
// Close the current method. Once a method is closed, no more
// symbols can be defined within it.
- #if FEATURE_CORECLR
- [System.Security.SecurityCritical] // auto-generated
- #endif
void CloseMethod();
// Define a group of sequence points within the current method.
// Each line/column defines the start of a statement within a
// method. The arrays should be sorted by offset. The offset is
// always the offset from the start of the method, in bytes.
- #if FEATURE_CORECLR
- [System.Security.SecurityCritical] // auto-generated
- #endif
void DefineSequencePoints(ISymbolDocumentWriter document,
int[] offsets,
int[] lines,
// Note: scope id's are only valid in the current method.
//
- #if FEATURE_CORECLR
- [System.Security.SecurityCritical] // auto-generated
- #endif
int OpenScope(int startOffset);
// Close the current lexical scope. Once a scope is closed no more
// variables can be defined within it. endOffset points past the
// last instruction in the scope.
- #if FEATURE_CORECLR
- [System.Security.SecurityCritical] // auto-generated
- #endif
void CloseScope(int endOffset);
// Define the offset range for a given lexical scope.
// variable of the same name that has multiple homes throughout a
// scope. (Note: start/end offsets must not overlap in such a
// case.)
- #if FEATURE_CORECLR
- [System.Security.SecurityCritical] // auto-generated
- #endif
void DefineLocalVariable(String name,
FieldAttributes attributes,
byte[] signature,
// Defines a custom attribute based upon its name. Not to be
// confused with Metadata custom attributes, these attributes are
// held in the symbol store.
- #if FEATURE_CORECLR
- [System.Security.SecurityCritical] // auto-generated
- #endif
void SetSymAttribute(SymbolToken parent, String name, byte[] data);
// Opens a new namespace. Call this before defining methods or
// current scope will also stop using the namespace, and the
// namespace will be in use in all scopes that inherit from the
// currently open scope.
- #if FEATURE_CORECLR
- [System.Security.SecurityCritical] // auto-generated
- #endif
void UsingNamespace(String fullName);
// Specifies the true start and end of a method within a source
// programatically, by registry (specifics....) or environment
// variables.
[Serializable]
- [HostProtection(Synchronization=true, ExternalThreading=true)]
internal delegate void LogMessageEventHandler(LoggingLevels level, LogSwitch category,
String message,
StackTrace location);
// Native method to inform the EE about the creation of a new LogSwitch
- [System.Security.SecurityCritical] // auto-generated
[MethodImplAttribute(MethodImplOptions.InternalCall)]
internal static extern void AddLogSwitch(LogSwitch logSwitch);
- [System.Security.SecurityCritical] // auto-generated
[MethodImplAttribute(MethodImplOptions.InternalCall)]
internal static extern void ModifyLogSwitch (int iNewLevel, String strSwitchName, String strParentName);
}
internal static double NegativeZero = BitConverter.Int64BitsToDouble(unchecked((long)0x8000000000000000));
[Pure]
- [System.Security.SecuritySafeCritical] // auto-generated
[System.Runtime.Versioning.NonVersionable]
public unsafe static bool IsInfinity(double d) {
return (*(long*)(&d) & 0x7FFFFFFFFFFFFFFF) == 0x7FF0000000000000;
}
[Pure]
- [System.Security.SecuritySafeCritical] // auto-generated
internal unsafe static bool IsNegative(double d) {
return (*(UInt64*)(&d) & 0x8000000000000000) == 0x8000000000000000;
}
[Pure]
[ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)]
- [System.Security.SecuritySafeCritical]
[System.Runtime.Versioning.NonVersionable]
public unsafe static bool IsNaN(double d)
{
//The hashcode for a double is the absolute value of the integer representation
//of that double.
//
- [System.Security.SecuritySafeCritical]
public unsafe override int GetHashCode() {
double d = m_value;
if (d == 0) {
return unchecked((int)value) ^ ((int)(value >> 32));
}
- [System.Security.SecuritySafeCritical] // auto-generated
public override String ToString() {
Contract.Ensures(Contract.Result<String>() != null);
return Number.FormatDouble(m_value, null, NumberFormatInfo.CurrentInfo);
}
- [System.Security.SecuritySafeCritical] // auto-generated
public String ToString(String format) {
Contract.Ensures(Contract.Result<String>() != null);
return Number.FormatDouble(m_value, format, NumberFormatInfo.CurrentInfo);
}
- [System.Security.SecuritySafeCritical] // auto-generated
public String ToString(IFormatProvider provider) {
Contract.Ensures(Contract.Result<String>() != null);
return Number.FormatDouble(m_value, null, NumberFormatInfo.GetInstance(provider));
}
- [System.Security.SecuritySafeCritical] // auto-generated
public String ToString(String format, IFormatProvider provider) {
Contract.Ensures(Contract.Result<String>() != null);
return Number.FormatDouble(m_value, format, NumberFormatInfo.GetInstance(provider));
return String.Empty;
}
- [System.Security.SecurityCritical] // auto-generated
public void GetObjectData(SerializationInfo info, StreamingContext context) {
if (info==null) {
throw new ArgumentNullException(nameof(info));
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Runtime.Versioning;
+using System.Diagnostics;
using System.Diagnostics.Contracts;
namespace System
#endregion
#region Private Static Methods
- [System.Security.SecuritySafeCritical] // auto-generated
private static TypeValuesAndNames GetCachedValuesAndNames(RuntimeType enumType, bool getNames)
{
TypeValuesAndNames entry = enumType.GenericCache as TypeValuesAndNames;
return entry;
}
- [System.Security.SecuritySafeCritical]
private unsafe String InternalFormattedHexString()
{
fixed (void* pValue = &JitHelpers.GetPinningHelper(this).m_data)
case CorElementType.U8:
return (*(ulong*)pValue).ToString("X16", null);
default:
- Contract.Assert(false, "Invalid Object type in Format");
+ Debug.Assert(false, "Invalid Object type in Format");
throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_UnknownEnumType"));
}
}
return ((UInt64)(Int64)value).ToString("X16", null);
// All unsigned types will be directly cast
default:
- Contract.Assert(false, "Invalid Object type in Format");
+ Debug.Assert(false, "Invalid Object type in Format");
throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_UnknownEnumType"));
}
}
String[] names = entry.Names;
ulong[] values = entry.Values;
- Contract.Assert(names.Length == values.Length);
+ Debug.Assert(names.Length == values.Length);
int index = values.Length - 1;
StringBuilder retval = new StringBuilder();
break;
// All unsigned types will be directly cast
default:
- Contract.Assert(false, "Invalid Object type in ToUInt64");
+ Debug.Assert(false, "Invalid Object type in ToUInt64");
throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_UnknownEnumType"));
}
return result;
}
- [System.Security.SecurityCritical] // auto-generated
[MethodImplAttribute(MethodImplOptions.InternalCall)]
private static extern int InternalCompareTo(Object o1, Object o2);
- [System.Security.SecuritySafeCritical]
[MethodImplAttribute(MethodImplOptions.InternalCall)]
internal static extern RuntimeType InternalGetUnderlyingType(RuntimeType enumType);
- [System.Security.SecurityCritical] // auto-generated
[DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
[System.Security.SuppressUnmanagedCodeSecurity]
private static extern void GetEnumValuesAndNames(RuntimeTypeHandle enumType, ObjectHandleOnStack values, ObjectHandleOnStack names, bool getNames);
- [System.Security.SecurityCritical] // auto-generated
[MethodImplAttribute(MethodImplOptions.InternalCall)]
private static extern Object InternalBoxEnum(RuntimeType enumType, long value);
#endregion
return m_innerException;
default:
- Contract.Assert(false, "Unknown EnumParseFailure: " + m_failure);
+ Debug.Assert(false, "Unknown EnumParseFailure: " + m_failure);
return new ArgumentException(Environment.GetResourceString("Arg_EnumValueNotFound"));
}
}
#endregion
#region Private Methods
- [System.Security.SecuritySafeCritical]
internal unsafe Object GetValue()
{
fixed (void* pValue = &JitHelpers.GetPinningHelper(this).m_data)
case CorElementType.U:
return *(UIntPtr*)pValue;
default:
- Contract.Assert(false, "Invalid primitive type");
+ Debug.Assert(false, "Invalid primitive type");
return null;
}
}
}
- [System.Security.SecuritySafeCritical]
private unsafe ulong ToUInt64()
{
fixed (void* pValue = &JitHelpers.GetPinningHelper(this).m_data)
return *(uint*)pValue;
}
default:
- Contract.Assert(false, "Invalid primitive type");
+ Debug.Assert(false, "Invalid primitive type");
return 0;
}
}
}
- [System.Security.SecurityCritical] // auto-generated
[MethodImplAttribute(MethodImplOptions.InternalCall)]
private extern bool InternalHasFlag(Enum flags);
- [System.Security.SecuritySafeCritical] // auto-generated
[MethodImplAttribute(MethodImplOptions.InternalCall)]
private extern CorElementType InternalGetCorElementType();
#endregion
#region Object Overrides
- [System.Security.SecuritySafeCritical] // auto-generated
[MethodImplAttribute(MethodImplOptions.InternalCall)]
public extern override bool Equals(Object obj);
- [System.Security.SecuritySafeCritical]
public override unsafe int GetHashCode()
{
// CONTRACT with the runtime: GetHashCode of enum types is implemented as GetHashCode of the underlying type.
case CorElementType.U:
return (*(UIntPtr*)pValue).GetHashCode();
default:
- Contract.Assert(false, "Invalid primitive type");
+ Debug.Assert(false, "Invalid primitive type");
return 0;
}
}
#endregion
#region IComparable
- [System.Security.SecuritySafeCritical] // auto-generated
public int CompareTo(Object target)
{
const int retIncompatibleMethodTables = 2; // indicates that the method tables did not match
else
{
// assert valid return code (3)
- Contract.Assert(ret == retInvalidEnumType, "Enum.InternalCompareTo return code was invalid");
+ Debug.Assert(ret == retInvalidEnumType, "Enum.InternalCompareTo return code was invalid");
throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_UnknownEnumType"));
}
return ToString();
}
- [System.Security.SecuritySafeCritical]
public Boolean HasFlag(Enum flag) {
if (flag == null)
throw new ArgumentNullException(nameof(flag));
return TypeCode.Char;
}
- Contract.Assert(false, "Unknown underlying type.");
+ Debug.Assert(false, "Unknown underlying type.");
throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_UnknownEnumType"));
}
#endregion
#region ToObject
- [System.Security.SecuritySafeCritical] // auto-generated
[CLSCompliant(false)]
[System.Runtime.InteropServices.ComVisible(true)]
public static Object ToObject(Type enumType, sbyte value)
return InternalBoxEnum(rtType, value);
}
- [System.Security.SecuritySafeCritical] // auto-generated
[System.Runtime.InteropServices.ComVisible(true)]
public static Object ToObject(Type enumType, short value)
{
return InternalBoxEnum(rtType, value);
}
- [System.Security.SecuritySafeCritical] // auto-generated
[System.Runtime.InteropServices.ComVisible(true)]
public static Object ToObject(Type enumType, int value)
{
return InternalBoxEnum(rtType, value);
}
- [System.Security.SecuritySafeCritical] // auto-generated
[System.Runtime.InteropServices.ComVisible(true)]
public static Object ToObject(Type enumType, byte value)
{
return InternalBoxEnum(rtType, value);
}
- [System.Security.SecuritySafeCritical] // auto-generated
[CLSCompliant(false)]
[System.Runtime.InteropServices.ComVisible(true)]
public static Object ToObject(Type enumType, ushort value)
return InternalBoxEnum(rtType, value);
}
- [System.Security.SecuritySafeCritical] // auto-generated
[CLSCompliant(false)]
[System.Runtime.InteropServices.ComVisible(true)]
public static Object ToObject(Type enumType, uint value)
return InternalBoxEnum(rtType, value);
}
- [System.Security.SecuritySafeCritical] // auto-generated
[System.Runtime.InteropServices.ComVisible(true)]
public static Object ToObject(Type enumType, long value)
{
return InternalBoxEnum(rtType, value);
}
- [System.Security.SecuritySafeCritical] // auto-generated
[CLSCompliant(false)]
[System.Runtime.InteropServices.ComVisible(true)]
public static Object ToObject(Type enumType, ulong value)
return InternalBoxEnum(rtType, unchecked((long)value));
}
- [System.Security.SecuritySafeCritical] // auto-generated
private static Object ToObject(Type enumType, char value)
{
if (enumType == null)
return InternalBoxEnum(rtType, value);
}
- [System.Security.SecuritySafeCritical] // auto-generated
private static Object ToObject(Type enumType, bool value)
{
if (enumType == null)
+++ /dev/null
-// Licensed to the .NET Foundation under one or more agreements.
-// The .NET Foundation licenses this file to you under the MIT license.
-// See the LICENSE file in the project root for more information.
-
-using System.Collections;
-using System.Collections.Generic;
-
-namespace System
-{
- public static partial class Environment
- {
- private static readonly unsafe Lazy<Dictionary<string, string>> s_environ = new Lazy<Dictionary<string, string>>(() =>
- {
- // We cache on Unix as using the block isn't thread safe
- return GetRawEnvironmentVariables();
- });
-
- private static string GetEnvironmentVariableCore(string variable)
- {
- // Ensure variable doesn't include a null char
- int nullEnd = variable.IndexOf('\0');
- if (nullEnd != -1)
- {
- variable = variable.Substring(0, nullEnd);
- }
-
- // Get the value of the variable
- lock (s_environ)
- {
- string value;
- return s_environ.Value.TryGetValue(variable, out value) ? value : null;
- }
- }
-
- private static string GetEnvironmentVariableCore(string variable, EnvironmentVariableTarget target)
- {
- return target == EnvironmentVariableTarget.Process ?
- GetEnvironmentVariableCore(variable) :
- null;
- }
-
- private static IDictionary GetEnvironmentVariablesCore()
- {
- lock (s_environ)
- {
- return new Dictionary<string, string>(s_environ.Value);
- }
- }
-
- private static IDictionary GetEnvironmentVariablesCore(EnvironmentVariableTarget target)
- {
- return target == EnvironmentVariableTarget.Process ?
- GetEnvironmentVariablesCore() :
- new Dictionary<string, string>();
- }
-
- private static void SetEnvironmentVariableCore(string variable, string value)
- {
- int nullEnd;
-
- // Ensure variable doesn't include a null char
- nullEnd = variable.IndexOf('\0');
- if (nullEnd != -1)
- {
- variable = variable.Substring(0, nullEnd);
- }
-
- // Ensure value doesn't include a null char
- if (value != null)
- {
- nullEnd = value.IndexOf('\0');
- if (nullEnd != -1)
- {
- value = value.Substring(0, nullEnd);
- }
- }
-
- lock (s_environ)
- {
- // Remove the entry if the value is null, otherwise add/overwrite it
- if (value == null)
- {
- s_environ.Value.Remove(variable);
- }
- else
- {
- s_environ.Value[variable] = value;
- }
- }
- }
-
- private static void SetEnvironmentVariableCore(string variable, string value, EnvironmentVariableTarget target)
- {
- if (target == EnvironmentVariableTarget.Process)
- {
- SetEnvironmentVariableCore(variable, value);
- }
- // other targets ignored
- }
- }
-}
\ No newline at end of file
+++ /dev/null
-// Licensed to the .NET Foundation under one or more agreements.
-// The .NET Foundation licenses this file to you under the MIT license.
-// See the LICENSE file in the project root for more information.
-
-using Microsoft.Win32;
-using System.Collections;
-using System.Collections.Generic;
-using System.Runtime.InteropServices;
-using System.Text;
-
-namespace System
-{
- public static partial class Environment
- {
- private static string GetEnvironmentVariableCore(string variable)
- {
- if (AppDomain.IsAppXModel() && !AppDomain.IsAppXDesignMode())
- {
- // Environment variable accessors are not approved modern API.
- // Behave as if the variable was not found in this case.
- return null;
- }
-
- StringBuilder sb = StringBuilderCache.Acquire(128); // A somewhat reasonable default size
- int requiredSize = Win32Native.GetEnvironmentVariable(variable, sb, sb.Capacity);
-
- if (requiredSize == 0 && Marshal.GetLastWin32Error() == Win32Native.ERROR_ENVVAR_NOT_FOUND)
- {
- StringBuilderCache.Release(sb);
- return null;
- }
-
- while (requiredSize > sb.Capacity)
- {
- sb.Capacity = requiredSize;
- sb.Length = 0;
- requiredSize = Win32Native.GetEnvironmentVariable(variable, sb, sb.Capacity);
- }
-
- return StringBuilderCache.GetStringAndRelease(sb);
- }
-
- private static string GetEnvironmentVariableCore(string variable, EnvironmentVariableTarget target)
- {
- if (target == EnvironmentVariableTarget.Process)
- return GetEnvironmentVariableCore(variable);
-
-#if FEATURE_WIN32_REGISTRY
- RegistryKey baseKey;
- string keyName;
-
- if (target == EnvironmentVariableTarget.Machine)
- {
- baseKey = Registry.LocalMachine;
- keyName = @"System\CurrentControlSet\Control\Session Manager\Environment";
- }
- else if (target == EnvironmentVariableTarget.User)
- {
- Debug.Assert(target == EnvironmentVariableTarget.User);
- baseKey = Registry.CurrentUser;
- keyName = "Environment";
- }
- else
- {
- throw new ArgumentException(GetResourceString("Arg_EnumIllegalVal", (int)target));
- }
-
- using (RegistryKey environmentKey = baseKey.OpenSubKey(keyName, writable: false))
- {
- return environmentKey?.GetValue(variable) as string;
- }
-#else
- throw new ArgumentException(GetResourceString("Arg_EnumIllegalVal", (int)target));
-#endif
- }
-
- private static IDictionary GetEnvironmentVariablesCore()
- {
- if (AppDomain.IsAppXModel() && !AppDomain.IsAppXDesignMode())
- {
- // Environment variable accessors are not approved modern API.
- // Behave as if no environment variables are defined in this case.
- return new Hashtable(0);
- }
-
- return GetRawEnvironmentVariables();
- }
-
- private static IDictionary GetEnvironmentVariablesCore(EnvironmentVariableTarget target)
- {
- if (target == EnvironmentVariableTarget.Process)
- return GetEnvironmentVariablesCore();
-
-#if FEATURE_WIN32_REGISTRY
- RegistryKey baseKey;
- string keyName;
- if (target == EnvironmentVariableTarget.Machine)
- {
- baseKey = Registry.LocalMachine;
- keyName = @"System\CurrentControlSet\Control\Session Manager\Environment";
- }
- else if (target == EnvironmentVariableTarget.User)
- {
- Debug.Assert(target == EnvironmentVariableTarget.User);
- baseKey = Registry.CurrentUser;
- keyName = @"Environment";
- }
- else
- {
- throw new ArgumentException(GetResourceString("Arg_EnumIllegalVal", (int)target));
- }
-
- using (RegistryKey environmentKey = baseKey.OpenSubKey(keyName, writable: false))
- {
- var table = new Dictionary<string, string>();
- if (environmentKey != null)
- {
- foreach (string name in environmentKey.GetValueNames())
- {
- table.Add(name, environmentKey.GetValue(name, "").ToString());
- }
- }
- return table;
- }
-#endif // FEATURE_WIN32_REGISTRY
-
- throw new ArgumentException(GetResourceString("Arg_EnumIllegalVal", (int)target));
- }
-
- private static void SetEnvironmentVariableCore(string variable, string value)
- {
- // explicitly null out value if is the empty string.
- if (string.IsNullOrEmpty(value) || value[0] == '\0')
- value = null;
-
- if (AppDomain.IsAppXModel() && !AppDomain.IsAppXDesignMode())
- {
- // Environment variable accessors are not approved modern API.
- // so we throw PlatformNotSupportedException.
- throw new PlatformNotSupportedException();
- }
-
- if (!Win32Native.SetEnvironmentVariable(variable, value))
- {
- int errorCode = Marshal.GetLastWin32Error();
-
- switch (errorCode)
- {
- case Win32Native.ERROR_ENVVAR_NOT_FOUND:
- // Allow user to try to clear a environment variable
- return;
- case Win32Native.ERROR_FILENAME_EXCED_RANGE:
- // The error message from Win32 is "The filename or extension is too long",
- // which is not accurate.
- throw new ArgumentException(GetResourceString("Argument_LongEnvVarValue"));
- default:
- throw new ArgumentException(Win32Native.GetMessage(errorCode));
- }
- }
- }
-
- private static void SetEnvironmentVariableCore(string variable, string value, EnvironmentVariableTarget target)
- {
- if (target == EnvironmentVariableTarget.Process)
- {
- SetEnvironmentVariableCore(variable, value);
- return;
- }
-
- // explicitly null out value if is the empty string.
- if (string.IsNullOrEmpty(value) || value[0] == '\0')
- value = null;
-
-#if FEATURE_WIN32_REGISTRY
- RegistryKey baseKey;
- string keyName;
-
- if (target == EnvironmentVariableTarget.Machine)
- {
- baseKey = Registry.LocalMachine;
- keyName = @"System\CurrentControlSet\Control\Session Manager\Environment";
- }
- else if (target == EnvironmentVariableTarget.User)
- {
- Debug.Assert(target == EnvironmentVariableTarget.User);
-
- // User-wide environment variables stored in the registry are limited to 255 chars for the environment variable name.
- const int MaxUserEnvVariableLength = 255;
- if (variable.Length >= MaxUserEnvVariableLength)
- {
- throw new ArgumentException(GetResourceString("Argument_LongEnvVarValue"), nameof(variable));
- }
-
- baseKey = Registry.CurrentUser;
- keyName = "Environment";
- }
- else
- {
- throw new ArgumentException(GetResourceString("Arg_EnumIllegalVal", (int)target));
- }
-
- using (RegistryKey environmentKey = baseKey.OpenSubKey(keyName, writable: true))
- {
- if (environmentKey != null)
- {
- if (value == null)
- {
- environmentKey.DeleteValue(variable, throwOnMissingValue: false);
- }
- else
- {
- environmentKey.SetValue(variable, value);
- }
- }
- }
-
- // send a WM_SETTINGCHANGE message to all windows
- IntPtr r = Win32Native.SendMessageTimeout(new IntPtr(Win32Native.HWND_BROADCAST), Win32Native.WM_SETTINGCHANGE, IntPtr.Zero, "Environment", 0, 1000, IntPtr.Zero);
- if (r == IntPtr.Zero) Debug.Assert(false, "SetEnvironmentVariable failed: " + Marshal.GetLastWin32Error());
-
-#else // FEATURE_WIN32_REGISTRY
- throw new ArgumentException(Environment.GetResourceString("Arg_EnumIllegalVal", (int)target));
-#endif
- }
- }
-}
\ No newline at end of file
}
}
- [System.Security.SecuritySafeCritical] // auto-generated
[ReliabilityContract(Consistency.WillNotCorruptState, Cer.MayFail)]
internal String GetResourceString(String key) {
if (key == null || key.Length == 0) {
- Contract.Assert(false, "Environment::GetResourceString with null or empty key. Bug in caller, or weird recursive loading problem?");
+ Debug.Assert(false, "Environment::GetResourceString with null or empty key. Bug in caller, or weird recursive loading problem?");
return "[Resource lookup failed - null or empty resource name]";
}
return userData.m_retVal;
}
- #if FEATURE_CORECLR
- [System.Security.SecurityCritical] // auto-generated
- #else
- [System.Security.SecuritySafeCritical]
- #endif
private void GetResourceStringCode(Object userDataIn)
{
GetResourceStringUserData userData = (GetResourceStringUserData) userDataIn;
String s = rh.SystemResMgr.GetString(key, null);
rh.currentlyLoading.RemoveAt(rh.currentlyLoading.Count - 1); // Pop
- Contract.Assert(s!=null, "Managed resource string lookup failed. Was your resource name misspelled? Did you rebuild mscorlib after adding a resource to resources.txt? Debug this w/ cordbg and bug whoever owns the code that called Environment.GetResourceString. Resource name was: \""+key+"\"");
+ Debug.Assert(s!=null, "Managed resource string lookup failed. Was your resource name misspelled? Did you rebuild mscorlib after adding a resource to resources.txt? Debug this w/ cordbg and bug whoever owns the code that called Environment.GetResourceString. Resource name was: \""+key+"\"");
userData.m_retVal = s;
}
- #if FEATURE_CORECLR
- [System.Security.SecurityCritical] // auto-generated
- #endif
[PrePrepareMethod]
private void GetResourceStringBackoutCode(Object userDataIn, bool exceptionThrown)
{
**Exceptions: None
==============================================================================*/
public static extern int TickCount {
- [System.Security.SecuritySafeCritical] // auto-generated
[MethodImplAttribute(MethodImplOptions.InternalCall)]
get;
}
// Terminates this process with the given exit code.
- [System.Security.SecurityCritical] // auto-generated
[DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
[SuppressUnmanagedCodeSecurity]
internal static extern void _Exit(int exitCode);
- [System.Security.SecuritySafeCritical] // auto-generated
-#pragma warning disable 618
- [SecurityPermissionAttribute(SecurityAction.Demand, Flags=SecurityPermissionFlag.UnmanagedCode)]
-#pragma warning restore 618
public static void Exit(int exitCode) {
_Exit(exitCode);
}
public static extern int ExitCode {
- [System.Security.SecuritySafeCritical] // auto-generated
[MethodImplAttribute(MethodImplOptions.InternalCall)]
get;
- [System.Security.SecuritySafeCritical] // auto-generated
[MethodImplAttribute(MethodImplOptions.InternalCall)]
set;
}
// Note: The CLR's Watson bucketization code looks at the caller of the FCALL method
// to assign blame for crashes. Don't mess with this, such as by making it call
// another managed helper method, unless you consult with some CLR Watson experts.
- [System.Security.SecurityCritical]
[MethodImplAttribute(MethodImplOptions.InternalCall)]
public static extern void FailFast(String message);
- [System.Security.SecurityCritical]
[MethodImplAttribute(MethodImplOptions.InternalCall)]
internal static extern void FailFast(String message, uint exitCode);
// if the exception object is preallocated, the runtime will use the callsite's
// IP for bucketing. If the exception object is not preallocated, it will use the bucket
// details contained in the object (if any).
- [System.Security.SecurityCritical]
[MethodImplAttribute(MethodImplOptions.InternalCall)]
public static extern void FailFast(String message, Exception exception);
-#if !FEATURE_CORECLR
- [DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
- [SecurityCritical] // Our security team doesn't yet allow safe-critical P/Invoke methods.
- [SuppressUnmanagedCodeSecurity]
- [ReliabilityContract(Consistency.WillNotCorruptState, Cer.MayFail)]
- internal static extern void TriggerCodeContractFailure(ContractFailureKind failureKind, String message, String condition, String exceptionAsString);
-
- [DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
- [SecurityCritical] // Our security team doesn't yet allow safe-critical P/Invoke methods.
- [SuppressUnmanagedCodeSecurity]
- [return: MarshalAs(UnmanagedType.Bool)]
- private static extern bool GetIsCLRHosted();
-
- internal static bool IsCLRHosted {
- [SecuritySafeCritical]
- get { return GetIsCLRHosted(); }
- }
-
- public static String CommandLine {
- [System.Security.SecuritySafeCritical] // auto-generated
- get {
- new EnvironmentPermission(EnvironmentPermissionAccess.Read, "Path").Demand();
-
- String commandLine = null;
- GetCommandLine(JitHelpers.GetStringHandleOnStack(ref commandLine));
- return commandLine;
- }
- }
-
- [System.Security.SecurityCritical] // auto-generated
- [DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode), SuppressUnmanagedCodeSecurity]
- private static extern void GetCommandLine(StringHandleOnStack retString);
-#endif // !FEATURE_CORECLR
-
/*===============================CurrentDirectory===============================
**Action: Provides a getter and setter for the current directory. The original
** current directory is the one from which the process was started.
return Directory.GetCurrentDirectory();
}
- #if FEATURE_CORECLR
- [System.Security.SecurityCritical] // auto-generated
- #endif
set {
Directory.SetCurrentDirectory(value);
}
// Returns the system directory (ie, C:\WinNT\System32).
public static String SystemDirectory {
-#if FEATURE_CORECLR
- [System.Security.SecurityCritical]
-#else
- [System.Security.SecuritySafeCritical] // auto-generated
-#endif
get {
StringBuilder sb = new StringBuilder(Path.MaxPath);
int r = Win32Native.GetSystemDirectory(sb, Path.MaxPath);
- Contract.Assert(r < Path.MaxPath, "r < Path.MaxPath");
+ Debug.Assert(r < Path.MaxPath, "r < Path.MaxPath");
if (r==0) __Error.WinIOError();
String path = sb.ToString();
-
-#if !FEATURE_CORECLR
- // Do security check
- new FileIOPermission(FileIOPermissionAccess.PathDiscovery, path).Demand();
-#endif
return path;
}
// Returns the windows directory (ie, C:\WinNT).
// Used by NLS+ custom culures only at the moment.
internal static String InternalWindowsDirectory {
- [System.Security.SecurityCritical] // auto-generated
get {
StringBuilder sb = new StringBuilder(Path.MaxPath);
int r = Win32Native.GetWindowsDirectory(sb, Path.MaxPath);
- Contract.Assert(r < Path.MaxPath, "r < Path.MaxPath");
+ Debug.Assert(r < Path.MaxPath, "r < Path.MaxPath");
if (r==0) __Error.WinIOError();
String path = sb.ToString();
}
}
- [System.Security.SecuritySafeCritical] // auto-generated
public static String ExpandEnvironmentVariables(String name)
{
if (name == null)
int size;
-#if !FEATURE_CORECLR
- bool isFullTrust = CodeAccessSecurityEngine.QuickCheckForAllDemands();
-
- // Do a security check to guarantee we can read each of the
- // individual environment variables requested here.
- String[] varArray = name.Split(new char[] {'%'});
- StringBuilder vars = isFullTrust ? null : new StringBuilder();
-
- bool fJustExpanded = false; // to accommodate expansion alg.
-
- for(int i=1; i<varArray.Length-1; i++) { // Skip first and last tokens
- // ExpandEnvironmentStrings' greedy algorithm expands every
- // non-boundary %-delimited substring, provided the previous
- // has not been expanded.
- // if "foo" is not expandable, and "PATH" is, then both
- // %foo%PATH% and %foo%foo%PATH% will expand PATH, but
- // %PATH%PATH% will expand only once.
- // Therefore, if we've just expanded, skip this substring.
- if (varArray[i].Length == 0 || fJustExpanded == true)
- {
- fJustExpanded = false;
- continue; // Nothing to expand
- }
- // Guess a somewhat reasonable initial size, call the method, then if
- // it fails (ie, the return value is larger than our buffer size),
- // make a new buffer & try again.
- blob.Length = 0;
- String envVar = "%" + varArray[i] + "%";
- size = Win32Native.ExpandEnvironmentStrings(envVar, blob, currentSize);
- if (size == 0)
- Marshal.ThrowExceptionForHR(Marshal.GetHRForLastWin32Error());
-
- // some environment variable might be changed while this function is called
- while (size > currentSize) {
- currentSize = size;
- blob.Capacity = currentSize;
- blob.Length = 0;
- size = Win32Native.ExpandEnvironmentStrings(envVar, blob, currentSize);
- if (size == 0)
- Marshal.ThrowExceptionForHR(Marshal.GetHRForLastWin32Error());
- }
-
- if (!isFullTrust) {
- String temp = blob.ToString();
- fJustExpanded = (temp != envVar);
- if (fJustExpanded) { // We expanded successfully, we need to do String comparison here
- // since %FOO% can become %FOOD
- vars.Append(varArray[i]);
- vars.Append(';');
- }
- }
- }
-
- if (!isFullTrust)
- new EnvironmentPermission(EnvironmentPermissionAccess.Read, vars.ToString()).Demand();
-#endif // !FEATURE_CORECLR
-
blob.Length = 0;
size = Win32Native.ExpandEnvironmentStrings(name, blob, currentSize);
if (size == 0)
}
public static String MachineName {
- [System.Security.SecuritySafeCritical] // auto-generated
get {
// UWP Debug scenarios
// In future release of operating systems, you might be able to rename a machine without
// rebooting. Therefore, don't cache this machine name.
-#if !FEATURE_CORECLR
- new EnvironmentPermission(EnvironmentPermissionAccess.Read, "COMPUTERNAME").Demand();
-#endif
StringBuilder buf = new StringBuilder(MaxMachineNameLength);
int len = MaxMachineNameLength;
if (Win32Native.GetComputerName(buf, ref len) == 0)
}
}
- [SecurityCritical]
[DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
[SuppressUnmanagedCodeSecurity]
private static extern Int32 GetProcessorCount();
public static int ProcessorCount {
- [System.Security.SecuritySafeCritical] // auto-generated
get {
return GetProcessorCount();
}
}
public static int SystemPageSize {
- [System.Security.SecuritySafeCritical] // auto-generated
get {
(new EnvironmentPermission(PermissionState.Unrestricted)).Demand();
Win32Native.SYSTEM_INFO info = new Win32Native.SYSTEM_INFO();
**Arguments: None
**Exceptions: None.
==============================================================================*/
- [System.Security.SecuritySafeCritical] // auto-generated
public static String[] GetCommandLineArgs()
{
new EnvironmentPermission(EnvironmentPermissionAccess.Read, "Path").Demand();
-#if FEATURE_CORECLR
/*
* There are multiple entry points to a hosted app.
* The host could use ::ExecuteAssembly() or ::CreateDelegate option
*/
if(s_CommandLineArgs != null)
return (string[])s_CommandLineArgs.Clone();
-#endif
+
return GetCommandLineArgsNative();
}
- [System.Security.SecurityCritical] // auto-generated
[MethodImplAttribute(MethodImplOptions.InternalCall)]
private static extern String[] GetCommandLineArgsNative();
-#if !FEATURE_CORECLR
- // We need to keep this Fcall since it is used in AppDomain.cs.
- // If we call GetEnvironmentVariable from AppDomain.cs, we will use StringBuilder class.
- // That has side effect to change the ApartmentState of the calling Thread to MTA.
- // So runtime can't change the ApartmentState of calling thread any more.
- [System.Security.SecurityCritical] // auto-generated
- [MethodImplAttribute(MethodImplOptions.InternalCall)]
- internal static extern String nativeGetEnvironmentVariable(String variable);
-#endif //!FEATURE_CORECLR
-
-#if FEATURE_CORECLR
private static string[] s_CommandLineArgs = null;
private static void SetCommandLineArgs(string[] cmdLineArgs)
{
s_CommandLineArgs = cmdLineArgs;
}
-#endif
private unsafe static char[] GetEnvironmentCharArray()
{
**Exceptions: IOException.
**Permissions: SystemInfo Permission.
==============================================================================*/
- [System.Security.SecuritySafeCritical] // auto-generated
public static String[] GetLogicalDrives() {
new EnvironmentPermission(PermissionState.Unrestricted).Demand();
**Arguments:
**Exceptions:
==============================================================================*/
- [System.Security.SecurityCritical] // auto-generated
[DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode), SuppressUnmanagedCodeSecurity]
private static extern long GetWorkingSet();
public static long WorkingSet {
- [System.Security.SecuritySafeCritical] // auto-generated
get {
new EnvironmentPermission(PermissionState.Unrestricted).Demand();
return GetWorkingSet();
**Exceptions:
==============================================================================*/
public static OperatingSystem OSVersion {
- [System.Security.SecuritySafeCritical] // auto-generated
get {
Contract.Ensures(Contract.Result<OperatingSystem>() != null);
Version v = new Version(osvi.MajorVersion, osvi.MinorVersion, osvi.BuildNumber, (osviEx.ServicePackMajor << 16) |osviEx.ServicePackMinor);
m_os = new OperatingSystem(id, v, osvi.CSDVersion);
}
- Contract.Assert(m_os != null, "m_os != null");
+ Debug.Assert(m_os != null, "m_os != null");
return m_os;
}
}
// Does the current version of Windows have Windows Runtime suppport?
internal static bool IsWinRTSupported {
- [SecuritySafeCritical]
get {
if (!s_CheckedWinRT) {
s_WinRTSupported = WinRTSupported();
}
}
- [SecurityCritical]
[DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
[SuppressUnmanagedCodeSecurity]
[return: MarshalAs(UnmanagedType.Bool)]
#endif // FEATURE_CORESYSTEM
- [System.Security.SecurityCritical] // auto-generated
[MethodImplAttribute(MethodImplOptions.InternalCall)]
internal static extern bool GetVersion(Microsoft.Win32.Win32Native.OSVERSIONINFO osVer);
- [System.Security.SecurityCritical] // auto-generated
[MethodImplAttribute(MethodImplOptions.InternalCall)]
internal static extern bool GetVersionEx(Microsoft.Win32.Win32Native.OSVERSIONINFOEX osVer);
**Exceptions:
==============================================================================*/
public static String StackTrace {
- [System.Security.SecuritySafeCritical] // auto-generated
get {
Contract.Ensures(Contract.Result<String>() != null);
}
}
-#if FEATURE_CORECLR
- [System.Security.SecurityCritical] // auto-generated
-#endif
internal static String GetStackTrace(Exception e, bool needFileInfo)
{
// Note: Setting needFileInfo to true will start up COM and set our
return st.ToString( System.Diagnostics.StackTrace.TraceFormat.Normal );
}
- [System.Security.SecuritySafeCritical] // auto-generated
private static void InitResourceHelper() {
// Only the default AppDomain should have a ResourceHelper. All calls to
// GetResourceString from any AppDomain delegate to GetResourceStringLocal
}
}
-#if !FEATURE_CORECLR
- [System.Security.SecurityCritical] // auto-generated
- [MethodImplAttribute(MethodImplOptions.InternalCall)]
- internal extern static String GetResourceFromDefault(String key);
-#endif
-
// Looks up the resource string value for key.
//
// if you change this method's signature then you must change the code that calls it
// in excep.cpp and probably you will have to visit mscorlib.h to add the new signature
// as well as metasig.h to create the new signature type
-#if FEATURE_CORECLR
- [System.Security.SecurityCritical] // auto-generated
-#endif
// NoInlining causes the caller and callee to not be inlined in mscorlib as it is an assumption of StackCrawlMark use
[MethodImpl(MethodImplOptions.NoInlining)]
internal static String GetResourceStringLocal(String key) {
return m_resHelper.GetResourceString(key);
}
- [System.Security.SecuritySafeCritical] // auto-generated
internal static String GetResourceString(String key) {
-#if FEATURE_CORECLR
return GetResourceStringLocal(key);
-#else
- return GetResourceFromDefault(key);
-#endif //FEATURE_CORECLR
}
// The reason the following overloads exist are to reduce code bloat.
}
public static bool Is64BitOperatingSystem {
- [System.Security.SecuritySafeCritical]
get {
#if BIT64
// 64-bit programs run only on 64-bit
}
public static extern bool HasShutdownStarted {
- [System.Security.SecuritySafeCritical] // auto-generated
[MethodImplAttribute(MethodImplOptions.InternalCall)]
get;
}
-#if !FEATURE_CORECLR
- // This is the temporary Whidbey stub for compatibility flags
- [MethodImplAttribute(MethodImplOptions.InternalCall)]
- [System.Security.SecurityCritical]
- internal static extern bool GetCompatibilityFlag(CompatibilityFlag flag);
-#endif //!FEATURE_CORECLR
-
public static string UserName {
- [System.Security.SecuritySafeCritical] // auto-generated
get {
new EnvironmentPermission(EnvironmentPermissionAccess.Read,"UserName").Demand();
}
}
- // Note that this is a handle to a process window station, but it does
- // not need to be closed. CloseWindowStation would ignore this handle.
- // We also do handle equality checking as well. This isn't a great fit
- // for SafeHandle. We don't gain anything by using SafeHandle here.
-#if !FEATURE_CORECLR
- private static volatile IntPtr processWinStation; // Doesn't need to be initialized as they're zero-init.
- private static volatile bool isUserNonInteractive;
-#endif
-
- public static bool UserInteractive {
- [System.Security.SecuritySafeCritical] // auto-generated
+ public static bool UserInteractive
+ {
get {
-#if !FEATURE_CORECLR
- IntPtr hwinsta = Win32Native.GetProcessWindowStation();
- if (hwinsta != IntPtr.Zero && processWinStation != hwinsta) {
- int lengthNeeded = 0;
- Win32Native.USEROBJECTFLAGS flags = new Win32Native.USEROBJECTFLAGS();
- if (Win32Native.GetUserObjectInformation(hwinsta, Win32Native.UOI_FLAGS, flags, Marshal.SizeOf(flags),ref lengthNeeded)) {
- if ((flags.dwFlags & Win32Native.WSF_VISIBLE) == 0) {
- isUserNonInteractive = true;
- }
- }
- processWinStation = hwinsta;
- }
-
- // The logic is reversed to avoid static initialization to true
- return !isUserNonInteractive;
-#else
return true;
-#endif
}
}
- [System.Security.SecuritySafeCritical] // auto-generated
public static string GetFolderPath(SpecialFolder folder) {
if (!Enum.IsDefined(typeof(SpecialFolder), folder))
throw new ArgumentException(Environment.GetResourceString("Arg_EnumIllegalVal", (int)folder));
return InternalGetFolderPath(folder, SpecialFolderOption.None);
}
- [System.Security.SecuritySafeCritical] // auto-generated
public static string GetFolderPath(SpecialFolder folder, SpecialFolderOption option) {
if (!Enum.IsDefined(typeof(SpecialFolder),folder))
throw new ArgumentException(Environment.GetResourceString("Arg_EnumIllegalVal", (int)folder));
return InternalGetFolderPath(folder, option);
}
- [System.Security.SecurityCritical]
internal static string UnsafeGetFolderPath(SpecialFolder folder)
{
return InternalGetFolderPath(folder, SpecialFolderOption.None, suppressSecurityChecks: true);
}
- [System.Security.SecurityCritical]
private static string InternalGetFolderPath(SpecialFolder folder, SpecialFolderOption option, bool suppressSecurityChecks = false)
{
#if FEATURE_CORESYSTEM
throw new PlatformNotSupportedException();
}
#else // FEATURE_CORESYSTEM
-#if !FEATURE_CORECLR
- if (option == SpecialFolderOption.Create && !suppressSecurityChecks) {
- FileIOPermission createPermission = new FileIOPermission(PermissionState.None);
- createPermission.AllFiles = FileIOPermissionAccess.Write;
- createPermission.Demand();
- }
-#endif
StringBuilder sb = new StringBuilder(Path.MaxPath);
int hresult = Win32Native.SHGetFolderPath(IntPtr.Zero, /* hwndOwner: [in] Reserved */
// On CoreCLR we can check with the host if we're not trying to use any special options.
// Otherwise, we need to do a full demand since hosts aren't expecting to handle requests to
// create special folders.
-#if FEATURE_CORECLR
if (option == SpecialFolderOption.None)
{
FileSecurityState state = new FileSecurityState(FileSecurityStateAccess.PathDiscovery, String.Empty, s);
state.EnsureState();
}
else
-#endif // FEATURE_CORECLR
{
new FileIOPermission(FileIOPermissionAccess.PathDiscovery, s).Demand();
}
public static string UserDomainName
{
- [System.Security.SecuritySafeCritical] // auto-generated
get {
new EnvironmentPermission(EnvironmentPermissionAccess.Read,"UserDomain").Demand();
//
// "MyDocuments" is a better name than "Personal"
//
- MyDocuments = Win32Native.CSIDL_PERSONAL,
+ MyDocuments = Win32Native.CSIDL_PERSONAL,
//
// Represents the program files folder.
//
//
// Represents the folder for components that are shared across applications.
//
- CommonProgramFiles = Win32Native.CSIDL_PROGRAM_FILES_COMMON,
-#if !FEATURE_CORECLR
- //
- // <user name>\Start Menu\Programs\Administrative Tools
- //
- AdminTools = Win32Native.CSIDL_ADMINTOOLS,
- //
- // USERPROFILE\Local Settings\Application Data\Microsoft\CD Burning
- //
- CDBurning = Win32Native.CSIDL_CDBURN_AREA,
- //
- // All Users\Start Menu\Programs\Administrative Tools
- //
- CommonAdminTools = Win32Native.CSIDL_COMMON_ADMINTOOLS,
- //
- // All Users\Documents
- //
- CommonDocuments = Win32Native.CSIDL_COMMON_DOCUMENTS,
- //
- // All Users\My Music
- //
- CommonMusic = Win32Native.CSIDL_COMMON_MUSIC,
- //
- // Links to All Users OEM specific apps
- //
- CommonOemLinks = Win32Native.CSIDL_COMMON_OEM_LINKS,
- //
- // All Users\My Pictures
- //
- CommonPictures = Win32Native.CSIDL_COMMON_PICTURES,
- //
- // All Users\Start Menu
- //
- CommonStartMenu = Win32Native.CSIDL_COMMON_STARTMENU,
- //
- // All Users\Start Menu\Programs
- //
- CommonPrograms = Win32Native.CSIDL_COMMON_PROGRAMS,
- //
- // All Users\Startup
- //
- CommonStartup = Win32Native.CSIDL_COMMON_STARTUP,
- //
- // All Users\Desktop
- //
- CommonDesktopDirectory = Win32Native.CSIDL_COMMON_DESKTOPDIRECTORY,
- //
- // All Users\Templates
- //
- CommonTemplates = Win32Native.CSIDL_COMMON_TEMPLATES,
- //
- // All Users\My Video
- //
- CommonVideos = Win32Native.CSIDL_COMMON_VIDEO,
- //
- // windows\fonts
- //
- Fonts = Win32Native.CSIDL_FONTS,
- //
- // %APPDATA%\Microsoft\Windows\Network Shortcuts
- //
- NetworkShortcuts = Win32Native.CSIDL_NETHOOD,
- //
- // %APPDATA%\Microsoft\Windows\Printer Shortcuts
- //
- PrinterShortcuts = Win32Native.CSIDL_PRINTHOOD,
- //
- // USERPROFILE
- //
- UserProfile = Win32Native.CSIDL_PROFILE,
- //
- // x86 Program Files\Common on RISC
- //
- CommonProgramFilesX86 = Win32Native.CSIDL_PROGRAM_FILES_COMMONX86,
- //
- // x86 C:\Program Files on RISC
- //
- ProgramFilesX86 = Win32Native.CSIDL_PROGRAM_FILESX86,
- //
- // Resource Directory
- //
- Resources = Win32Native.CSIDL_RESOURCES,
- //
- // Localized Resource Directory
- //
- LocalizedResources = Win32Native.CSIDL_RESOURCES_LOCALIZED,
- //
- // %windir%\System32 or %windir%\syswow64
- //
- SystemX86 = Win32Native.CSIDL_SYSTEMX86,
- //
- // GetWindowsDirectory()
- //
- Windows = Win32Native.CSIDL_WINDOWS,
-#endif // !FEATURE_CORECLR
+ CommonProgramFiles = Win32Native.CSIDL_PROGRAM_FILES_COMMON,
}
public static int CurrentManagedThreadId
internal static extern int CurrentProcessorNumber
{
- [System.Security.SecuritySafeCritical]
[MethodImplAttribute(MethodImplOptions.InternalCall)]
get;
}
}
return results;
}
+
+ private static string GetEnvironmentVariableCore(string variable)
+ {
+ if (AppDomain.IsAppXModel() && !AppDomain.IsAppXDesignMode())
+ {
+ // Environment variable accessors are not approved modern API.
+ // Behave as if the variable was not found in this case.
+ return null;
+ }
+
+ StringBuilder sb = StringBuilderCache.Acquire(128); // A somewhat reasonable default size
+ int requiredSize = Win32Native.GetEnvironmentVariable(variable, sb, sb.Capacity);
+
+ if (requiredSize == 0 && Marshal.GetLastWin32Error() == Win32Native.ERROR_ENVVAR_NOT_FOUND)
+ {
+ StringBuilderCache.Release(sb);
+ return null;
+ }
+
+ while (requiredSize > sb.Capacity)
+ {
+ sb.Capacity = requiredSize;
+ sb.Length = 0;
+ requiredSize = Win32Native.GetEnvironmentVariable(variable, sb, sb.Capacity);
+ }
+
+ return StringBuilderCache.GetStringAndRelease(sb);
+ }
+
+ private static string GetEnvironmentVariableCore(string variable, EnvironmentVariableTarget target)
+ {
+ if (target == EnvironmentVariableTarget.Process)
+ return GetEnvironmentVariableCore(variable);
+
+#if !FEATURE_WIN32_REGISTRY
+ return null;
+#else
+ RegistryKey baseKey;
+ string keyName;
+
+ if (target == EnvironmentVariableTarget.Machine)
+ {
+ baseKey = Registry.LocalMachine;
+ keyName = @"System\CurrentControlSet\Control\Session Manager\Environment";
+ }
+ else if (target == EnvironmentVariableTarget.User)
+ {
+ Debug.Assert(target == EnvironmentVariableTarget.User);
+ baseKey = Registry.CurrentUser;
+ keyName = "Environment";
+ }
+ else
+ {
+ throw new ArgumentException(GetResourceString("Arg_EnumIllegalVal", (int)target));
+ }
+
+ using (RegistryKey environmentKey = baseKey.OpenSubKey(keyName, writable: false))
+ {
+ return environmentKey?.GetValue(variable) as string;
+ }
+#endif
+ }
+
+ private static IDictionary GetEnvironmentVariablesCore()
+ {
+ if (AppDomain.IsAppXModel() && !AppDomain.IsAppXDesignMode())
+ {
+ // Environment variable accessors are not approved modern API.
+ // Behave as if no environment variables are defined in this case.
+ return new Dictionary<string, string>(0);
+ }
+
+ return GetRawEnvironmentVariables();
+ }
+
+ private static IDictionary GetEnvironmentVariablesCore(EnvironmentVariableTarget target)
+ {
+ if (target == EnvironmentVariableTarget.Process)
+ return GetEnvironmentVariablesCore();
+
+#if !FEATURE_WIN32_REGISTRY
+ // Without registry support we have nothing to return
+ return new Dictionary<string, string>(0);
+#else
+ RegistryKey baseKey;
+ string keyName;
+ if (target == EnvironmentVariableTarget.Machine)
+ {
+ baseKey = Registry.LocalMachine;
+ keyName = @"System\CurrentControlSet\Control\Session Manager\Environment";
+ }
+ else if (target == EnvironmentVariableTarget.User)
+ {
+ Debug.Assert(target == EnvironmentVariableTarget.User);
+ baseKey = Registry.CurrentUser;
+ keyName = @"Environment";
+ }
+ else
+ {
+ throw new ArgumentException(GetResourceString("Arg_EnumIllegalVal", (int)target));
+ }
+
+ using (RegistryKey environmentKey = baseKey.OpenSubKey(keyName, writable: false))
+ {
+ var table = new Dictionary<string, string>();
+ if (environmentKey != null)
+ {
+ foreach (string name in environmentKey.GetValueNames())
+ {
+ table.Add(name, environmentKey.GetValue(name, "").ToString());
+ }
+ }
+ return table;
+ }
+#endif // FEATURE_WIN32_REGISTRY
+ }
+
+ private static void SetEnvironmentVariableCore(string variable, string value)
+ {
+ // explicitly null out value if is the empty string.
+ if (string.IsNullOrEmpty(value) || value[0] == '\0')
+ value = null;
+
+ if (AppDomain.IsAppXModel() && !AppDomain.IsAppXDesignMode())
+ {
+ // Environment variable accessors are not approved modern API.
+ // so we throw PlatformNotSupportedException.
+ throw new PlatformNotSupportedException();
+ }
+
+ if (!Win32Native.SetEnvironmentVariable(variable, value))
+ {
+ int errorCode = Marshal.GetLastWin32Error();
+
+ switch (errorCode)
+ {
+ case Win32Native.ERROR_ENVVAR_NOT_FOUND:
+ // Allow user to try to clear a environment variable
+ return;
+ case Win32Native.ERROR_FILENAME_EXCED_RANGE:
+ // The error message from Win32 is "The filename or extension is too long",
+ // which is not accurate.
+ throw new ArgumentException(GetResourceString("Argument_LongEnvVarValue"));
+ default:
+ throw new ArgumentException(Win32Native.GetMessage(errorCode));
+ }
+ }
+ }
+
+ private static void SetEnvironmentVariableCore(string variable, string value, EnvironmentVariableTarget target)
+ {
+ if (target == EnvironmentVariableTarget.Process)
+ {
+ SetEnvironmentVariableCore(variable, value);
+ return;
+ }
+
+#if !FEATURE_WIN32_REGISTRY
+ // other targets ignored
+ return;
+#else
+ // explicitly null out value if is the empty string.
+ if (string.IsNullOrEmpty(value) || value[0] == '\0')
+ value = null;
+
+ RegistryKey baseKey;
+ string keyName;
+
+ if (target == EnvironmentVariableTarget.Machine)
+ {
+ baseKey = Registry.LocalMachine;
+ keyName = @"System\CurrentControlSet\Control\Session Manager\Environment";
+ }
+ else if (target == EnvironmentVariableTarget.User)
+ {
+ Debug.Assert(target == EnvironmentVariableTarget.User);
+
+ // User-wide environment variables stored in the registry are limited to 255 chars for the environment variable name.
+ const int MaxUserEnvVariableLength = 255;
+ if (variable.Length >= MaxUserEnvVariableLength)
+ {
+ throw new ArgumentException(GetResourceString("Argument_LongEnvVarValue"), nameof(variable));
+ }
+
+ baseKey = Registry.CurrentUser;
+ keyName = "Environment";
+ }
+ else
+ {
+ throw new ArgumentException(GetResourceString("Arg_EnumIllegalVal", (int)target));
+ }
+
+ using (RegistryKey environmentKey = baseKey.OpenSubKey(keyName, writable: true))
+ {
+ if (environmentKey != null)
+ {
+ if (value == null)
+ {
+ environmentKey.DeleteValue(variable, throwOnMissingValue: false);
+ }
+ else
+ {
+ environmentKey.SetValue(variable, value);
+ }
+ }
+ }
+
+ // send a WM_SETTINGCHANGE message to all windows
+ IntPtr r = Win32Native.SendMessageTimeout(new IntPtr(Win32Native.HWND_BROADCAST),
+ Win32Native.WM_SETTINGCHANGE, IntPtr.Zero, "Environment", 0, 1000, IntPtr.Zero);
+
+ if (r == IntPtr.Zero) Debug.Assert(false, "SetEnvironmentVariable failed: " + Marshal.GetLastWin32Error());
+#endif // FEATURE_WIN32_REGISTRY
+ }
}
}
_innerException = innerException;
}
- [System.Security.SecuritySafeCritical] // auto-generated
protected Exception(SerializationInfo info, StreamingContext context)
{
if (info==null)
}
public virtual IDictionary Data {
- [System.Security.SecuritySafeCritical] // auto-generated
get {
if (_data == null)
if (IsImmutableAgileException(this))
}
}
- [System.Security.SecurityCritical] // auto-generated
[MethodImplAttribute(MethodImplOptions.InternalCall)]
private static extern bool IsImmutableAgileException(Exception e);
}
- [System.Security.SecurityCritical] // auto-generated
[MethodImplAttribute(MethodImplOptions.InternalCall)]
static extern private IRuntimeMethodInfo GetMethodFromStackTrace(Object stackTrace);
- [System.Security.SecuritySafeCritical] // auto-generated
private MethodBase GetExceptionMethodFromStackTrace()
{
IRuntimeMethodInfo method = GetMethodFromStackTrace(_stackTrace);
}
public MethodBase TargetSite {
- [System.Security.SecuritySafeCritical] // auto-generated
get {
return GetTargetSiteInternal();
}
// this function is provided as a private helper to avoid the security demand
- [System.Security.SecurityCritical] // auto-generated
private MethodBase GetTargetSiteInternal() {
if (_exceptionMethod!=null) {
return _exceptionMethod;
// available, null is returned.
public virtual String StackTrace
{
-#if FEATURE_CORECLR
- [System.Security.SecuritySafeCritical]
-#endif
get
{
// By default attempt to include file and line number info
// is true. Note that this requires FileIOPermission(PathDiscovery), and so
// will usually fail in CoreCLR. To avoid the demand and resulting
// SecurityException we can explicitly not even try to get fileinfo.
-#if FEATURE_CORECLR
- [System.Security.SecurityCritical] // auto-generated
-#endif
private string GetStackTrace(bool needFileInfo)
{
string stackTraceString = _stackTraceString;
string remoteStackTraceString = _remoteStackTraceString;
-#if !FEATURE_CORECLR
- if (!needFileInfo)
- {
- // Filter out file names/paths and line numbers from _stackTraceString and _remoteStackTraceString.
- // This is used only when generating stack trace for Watson where the strings must be PII-free.
- stackTraceString = StripFileInfo(stackTraceString, false);
- remoteStackTraceString = StripFileInfo(remoteStackTraceString, true);
- }
-#endif // !FEATURE_CORECLR
-
// if no stack trace, try to get one
if (stackTraceString != null)
{
}
public virtual String Source {
-#if FEATURE_CORECLR
- [System.Security.SecurityCritical] // auto-generated
-#endif
get {
if (_source == null)
{
return _source;
}
-#if FEATURE_CORECLR
- [System.Security.SecurityCritical] // auto-generated
-#endif
set { _source = value; }
}
-#if FEATURE_CORECLR
- [System.Security.SecuritySafeCritical]
-#endif
public override String ToString()
{
return ToString(true, true);
}
-#if FEATURE_CORECLR
- [System.Security.SecurityCritical] // auto-generated
-#endif
private String ToString(bool needFileLineInfo, bool needMessage) {
String message = (needMessage ? Message : null);
String s;
return s;
}
- [System.Security.SecurityCritical] // auto-generated
private String GetExceptionMethodString() {
MethodBase methBase = GetTargetSiteInternal();
if (methBase==null) {
result.Append(separator);
result.Append(rci.ToString());
} else {
- Contract.Assert(methBase is MethodInfo, "[Exception.GetExceptionMethodString]methBase is MethodInfo");
+ Debug.Assert(methBase is MethodInfo, "[Exception.GetExceptionMethodString]methBase is MethodInfo");
RuntimeMethodInfo rmi = (RuntimeMethodInfo)methBase;
Type t = rmi.DeclaringType;
result.Append((int)MemberTypes.Method);
return result.ToString();
}
- [System.Security.SecurityCritical] // auto-generated
private MethodBase GetExceptionMethodFromString() {
- Contract.Assert(_exceptionMethodString != null, "Method string cannot be NULL!");
+ Debug.Assert(_exceptionMethodString != null, "Method string cannot be NULL!");
String[] args = _exceptionMethodString.Split(new char[]{'\0', '\n'});
if (args.Length!=5) {
throw new SerializationException();
}
#endif // FEATURE_SERIALIZATION
- [System.Security.SecurityCritical] // auto-generated_required
public virtual void GetObjectData(SerializationInfo info, StreamingContext context)
{
if (info == null)
// often created in the VM with AllocateObject instead if the managed construtor)
// If you are adding code to use a SafeSerializationManager from an mscorlib exception, update
// this assert to ensure that it fails when that exception's _safeSerializationManager is NULL
- Contract.Assert(((_safeSerializationManager != null) || (this.GetType().Assembly == typeof(object).Assembly)),
+ Debug.Assert(((_safeSerializationManager != null) || (this.GetType().Assembly == typeof(object).Assembly)),
"User defined exceptions must have a valid _safeSerializationManager");
// Handle serializing any transparent or partial trust subclass data
// This is used by the runtime when re-throwing a managed exception. It will
// copy the stack trace to _remoteStackTraceString.
-#if FEATURE_CORECLR
- [System.Security.SecuritySafeCritical]
-#endif
internal void InternalPreserveStackTrace()
{
string tmpStackTraceString;
}
}
- [System.Security.SecurityCritical] // auto-generated
[MethodImplAttribute(MethodImplOptions.InternalCall)]
private static extern void PrepareForForeignExceptionRaise();
- [System.Security.SecurityCritical] // auto-generated
[MethodImplAttribute(MethodImplOptions.InternalCall)]
private static extern void GetStackTracesDeepCopy(Exception exception, out object currentStackTrace, out object dynamicMethodArray);
- [System.Security.SecurityCritical] // auto-generated
[MethodImplAttribute(MethodImplOptions.InternalCall)]
internal static extern void SaveStackTracesFromDeepCopy(Exception exception, object currentStackTrace, object dynamicMethodArray);
- [System.Security.SecurityCritical] // auto-generated
[MethodImplAttribute(MethodImplOptions.InternalCall)]
private static extern object CopyStackTrace(object currentStackTrace);
- [System.Security.SecurityCritical] // auto-generated
[MethodImplAttribute(MethodImplOptions.InternalCall)]
private static extern object CopyDynamicMethods(object currentDynamicMethods);
-#if !FEATURE_CORECLR
- [System.Security.SecuritySafeCritical]
- [MethodImplAttribute(MethodImplOptions.InternalCall)]
- private extern string StripFileInfo(string stackTrace, bool isRemoteStackTrace);
-#endif // !FEATURE_CORECLR
-
- [SecuritySafeCritical]
internal object DeepCopyStackTrace(object currentStackTrace)
{
if (currentStackTrace != null)
}
}
- [SecuritySafeCritical]
internal object DeepCopyDynamicMethods(object currentDynamicMethods)
{
if (currentDynamicMethods != null)
}
}
- [SecuritySafeCritical]
internal void GetStackTracesDeepCopy(out object currentStackTrace, out object dynamicMethodArray)
{
GetStackTracesDeepCopy(this, out currentStackTrace, out dynamicMethodArray);
// This is invoked by ExceptionDispatchInfo.Throw to restore the exception stack trace, corresponding to the original throw of the
// exception, just before the exception is "rethrown".
- [SecuritySafeCritical]
internal void RestoreExceptionDispatchInfo(System.Runtime.ExceptionServices.ExceptionDispatchInfo exceptionDispatchInfo)
{
bool fCanProcessException = !(IsImmutableAgileException(this));
// InternalToString is called by the runtime to get the exception text
// and create a corresponding CrossAppDomainMarshaledException
- [System.Security.SecurityCritical] // auto-generated
internal virtual String InternalToString()
{
try
internal bool IsTransient
{
- [System.Security.SecuritySafeCritical] // auto-generated
get {
return nIsTransient(_HResult);
}
}
- [System.Security.SecurityCritical] // auto-generated
[MethodImplAttribute(MethodImplOptions.InternalCall)]
private extern static bool nIsTransient(int hr);
}
// See comment on ExceptionMessageKind
- [System.Security.SecuritySafeCritical] // auto-generated
internal static String GetMessageFromNativeResources(ExceptionMessageKind kind)
{
string retMesg = null;
return retMesg;
}
- [System.Security.SecurityCritical] // auto-generated
[DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
[SuppressUnmanagedCodeSecurity]
private static extern void GetMessageFromNativeResources(ExceptionMessageKind kind, StringHandleOnStack retMesg);
}
-
-
-#if FEATURE_CORECLR
-
//--------------------------------------------------------------------------
// Telesto: Telesto doesn't support appdomain marshaling of objects so
// managed exceptions that leak across appdomain boundaries are flatted to
// Normally, only Telesto's UEF will see these exceptions.
// This override prints out the original Exception's ToString()
// output and hides the fact that it is wrapped inside another excepton.
-#if FEATURE_CORECLR
- [System.Security.SecurityCritical] // auto-generated
-#endif
internal override String InternalToString()
{
return Message;
}
-
}
-#endif
-
-
}
public static class GC
{
- [System.Security.SecurityCritical] // auto-generated
[MethodImplAttribute(MethodImplOptions.InternalCall)]
internal static extern int GetGCLatencyMode();
- [System.Security.SecurityCritical] // auto-generated
[MethodImplAttribute(MethodImplOptions.InternalCall)]
internal static extern int SetGCLatencyMode(int newLatencyMode);
- [System.Security.SecurityCritical] // auto-generated
[DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
[SuppressUnmanagedCodeSecurity]
internal static extern int _StartNoGCRegion(long totalSize, bool lohSizeKnown, long lohSize, bool disallowFullBlockingGC);
- [System.Security.SecurityCritical] // auto-generated
[DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
[SuppressUnmanagedCodeSecurity]
internal static extern int _EndNoGCRegion();
- [System.Security.SecurityCritical] // auto-generated
[MethodImplAttribute(MethodImplOptions.InternalCall)]
internal static extern int GetLOHCompactionMode();
- [System.Security.SecurityCritical] // auto-generated
[MethodImplAttribute(MethodImplOptions.InternalCall)]
internal static extern void SetLOHCompactionMode(int newLOHCompactionMode);
- [System.Security.SecurityCritical] // auto-generated
[MethodImplAttribute(MethodImplOptions.InternalCall)]
private static extern int GetGenerationWR(IntPtr handle);
- [System.Security.SecurityCritical] // auto-generated
[DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
[SuppressUnmanagedCodeSecurity]
private static extern long GetTotalMemory();
- [System.Security.SecurityCritical] // auto-generated
[DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
[SuppressUnmanagedCodeSecurity]
private static extern void _Collect(int generation, int mode);
- [System.Security.SecurityCritical] // auto-generated
[MethodImplAttribute(MethodImplOptions.InternalCall)]
private static extern int GetMaxGeneration();
- [System.Security.SecurityCritical] // auto-generated
[MethodImplAttribute(MethodImplOptions.InternalCall)]
[ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)]
private static extern int _CollectionCount (int generation, int getSpecialGCCount);
- [System.Security.SecurityCritical] // auto-generated
[MethodImplAttribute(MethodImplOptions.InternalCall)]
internal static extern bool IsServerGC();
- [System.Security.SecurityCritical] // auto-generated
[DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode), SuppressUnmanagedCodeSecurity]
private static extern void _AddMemoryPressure(UInt64 bytesAllocated);
- [System.Security.SecurityCritical] // auto-generated
[DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode), SuppressUnmanagedCodeSecurity]
private static extern void _RemoveMemoryPressure(UInt64 bytesAllocated);
- [System.Security.SecurityCritical] // auto-generated_required
public static void AddMemoryPressure (long bytesAllocated) {
if( bytesAllocated <= 0) {
throw new ArgumentOutOfRangeException(nameof(bytesAllocated),
_AddMemoryPressure((ulong)bytesAllocated);
}
- [System.Security.SecurityCritical] // auto-generated_required
public static void RemoveMemoryPressure (long bytesAllocated) {
if( bytesAllocated <= 0) {
throw new ArgumentOutOfRangeException(nameof(bytesAllocated),
// Returns the generation that obj is currently in.
//
- [System.Security.SecuritySafeCritical] // auto-generated
[MethodImplAttribute(MethodImplOptions.InternalCall)]
public static extern int GetGeneration(Object obj);
// Garbage Collect all generations.
//
- [System.Security.SecuritySafeCritical] // auto-generated
public static void Collect() {
//-1 says to GC all generations.
_Collect(-1, (int)InternalGCCollectionMode.Blocking);
}
- [System.Security.SecuritySafeCritical] // auto-generated
public static void Collect(int generation, GCCollectionMode mode)
{
Collect(generation, mode, true);
}
- [System.Security.SecuritySafeCritical] // auto-generated
public static void Collect(int generation, GCCollectionMode mode, bool blocking)
{
Collect(generation, mode, blocking, false);
}
- [System.Security.SecuritySafeCritical] // auto-generated
public static void Collect(int generation, GCCollectionMode mode, bool blocking, bool compacting)
{
if (generation<0)
_Collect(generation, iInternalModes);
}
- [System.Security.SecuritySafeCritical] // auto-generated
[ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)]
public static int CollectionCount (int generation)
{
}
// pass in true to get the BGC or FGC count.
- [System.Security.SecuritySafeCritical] // auto-generated
[ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)]
internal static int CollectionCount (int generation, bool getSpecialGCCount)
{
// Returns the generation in which wo currently resides.
//
- [System.Security.SecuritySafeCritical] // auto-generated
public static int GetGeneration(WeakReference wo) {
int result = GetGenerationWR(wo.m_handle);
KeepAlive(wo);
// Returns the maximum GC generation. Currently assumes only 1 heap.
//
public static int MaxGeneration {
- [System.Security.SecuritySafeCritical] // auto-generated
get { return GetMaxGeneration(); }
}
- [System.Security.SecurityCritical] // auto-generated
[DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
[SuppressUnmanagedCodeSecurity]
private static extern void _WaitForPendingFinalizers();
- [System.Security.SecuritySafeCritical] // auto-generated
public static void WaitForPendingFinalizers() {
// QCalls can not be exposed from mscorlib directly, need to wrap it.
_WaitForPendingFinalizers();
// Indicates that the system should not call the Finalize() method on
// an object that would normally require this call.
- [System.Security.SecurityCritical] // auto-generated
[MethodImplAttribute(MethodImplOptions.InternalCall)]
[ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)]
private static extern void _SuppressFinalize(Object o);
- [System.Security.SecuritySafeCritical] // auto-generated
[ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)]
public static void SuppressFinalize(Object obj) {
if (obj == null)
// for which SuppressFinalize has already been called. The other situation
// where calling ReRegisterForFinalize is useful is inside a finalizer that
// needs to resurrect itself or an object that it references.
- [System.Security.SecurityCritical] // auto-generated
[MethodImplAttribute(MethodImplOptions.InternalCall)]
private static extern void _ReRegisterForFinalize(Object o);
- [System.Security.SecuritySafeCritical] // auto-generated
public static void ReRegisterForFinalize(Object obj) {
if (obj == null)
throw new ArgumentNullException(nameof(obj));
// the GC heap. This does not return the total size of the GC heap, but
// only the live objects in the GC heap.
//
- [System.Security.SecuritySafeCritical] // auto-generated
public static long GetTotalMemory(bool forceFullCollection) {
long size = GetTotalMemory();
if (!forceFullCollection)
return newSize;
}
- [System.Security.SecurityCritical] // auto-generated
[MethodImplAttribute(MethodImplOptions.InternalCall)]
private static extern long _GetAllocatedBytesForCurrentThread();
- [System.Security.SecuritySafeCritical] // auto-generated
public static long GetAllocatedBytesForCurrentThread() {
return _GetAllocatedBytesForCurrentThread();
}
- [System.Security.SecurityCritical] // auto-generated
[MethodImplAttribute(MethodImplOptions.InternalCall)]
private static extern bool _RegisterForFullGCNotification(int maxGenerationPercentage, int largeObjectHeapPercentage);
[MethodImplAttribute(MethodImplOptions.InternalCall)]
private static extern int _WaitForFullGCComplete(int millisecondsTimeout);
- [SecurityCritical]
public static void RegisterForFullGCNotification(int maxGenerationThreshold, int largeObjectHeapThreshold)
{
if ((maxGenerationThreshold <= 0) || (maxGenerationThreshold >= 100))
}
}
- [SecurityCritical]
public static void CancelFullGCNotification()
{
if (!_CancelFullGCNotification())
}
}
- [SecurityCritical]
public static GCNotificationStatus WaitForFullGCApproach()
{
return (GCNotificationStatus)_WaitForFullGCApproach(-1);
}
- [SecurityCritical]
public static GCNotificationStatus WaitForFullGCApproach(int millisecondsTimeout)
{
if (millisecondsTimeout < -1)
return (GCNotificationStatus)_WaitForFullGCApproach(millisecondsTimeout);
}
- [SecurityCritical]
public static GCNotificationStatus WaitForFullGCComplete()
{
return (GCNotificationStatus)_WaitForFullGCComplete(-1);
}
- [SecurityCritical]
public static GCNotificationStatus WaitForFullGCComplete(int millisecondsTimeout)
{
if (millisecondsTimeout < -1)
AllocationExceeded = 3
}
- [SecurityCritical]
static bool StartNoGCRegionWorker(long totalSize, bool hasLohSize, long lohSize, bool disallowFullBlockingGC)
{
StartNoGCRegionStatus status = (StartNoGCRegionStatus)_StartNoGCRegion(totalSize, hasLohSize, lohSize, disallowFullBlockingGC);
return true;
}
- [SecurityCritical]
public static bool TryStartNoGCRegion(long totalSize)
{
return StartNoGCRegionWorker(totalSize, false, 0, false);
}
- [SecurityCritical]
public static bool TryStartNoGCRegion(long totalSize, long lohSize)
{
return StartNoGCRegionWorker(totalSize, true, lohSize, false);
}
- [SecurityCritical]
public static bool TryStartNoGCRegion(long totalSize, bool disallowFullBlockingGC)
{
return StartNoGCRegionWorker(totalSize, false, 0, disallowFullBlockingGC);
}
- [SecurityCritical]
public static bool TryStartNoGCRegion(long totalSize, long lohSize, bool disallowFullBlockingGC)
{
return StartNoGCRegionWorker(totalSize, true, lohSize, disallowFullBlockingGC);
}
- [SecurityCritical]
static EndNoGCRegionStatus EndNoGCRegionWorker()
{
EndNoGCRegionStatus status = (EndNoGCRegionStatus)_EndNoGCRegion();
return EndNoGCRegionStatus.Succeeded;
}
- [SecurityCritical]
public static void EndNoGCRegion()
{
EndNoGCRegionWorker();
}
}
-
-#if !FEATURE_CORECLR
- internal class SizedReference : IDisposable
- {
- [System.Security.SecurityCritical]
- [MethodImplAttribute(MethodImplOptions.InternalCall)]
- private static extern IntPtr CreateSizedRef(Object o);
-
- [System.Security.SecurityCritical]
- [MethodImplAttribute(MethodImplOptions.InternalCall)]
- private static extern void FreeSizedRef(IntPtr h);
-
- [System.Security.SecurityCritical]
- [MethodImplAttribute(MethodImplOptions.InternalCall)]
- private static extern Object GetTargetOfSizedRef(IntPtr h);
-
- [System.Security.SecurityCritical]
- [MethodImplAttribute(MethodImplOptions.InternalCall)]
- private static extern Int64 GetApproximateSizeOfSizedRef(IntPtr h);
-
- #pragma warning disable 420
- [System.Security.SecuritySafeCritical]
- private void Free()
- {
- IntPtr temp = _handle;
- if (temp != IntPtr.Zero &&
- (Interlocked.CompareExchange(ref _handle, IntPtr.Zero, temp) == temp))
- {
- FreeSizedRef(temp);
- }
- }
-
- internal volatile IntPtr _handle;
-
- [System.Security.SecuritySafeCritical]
- public SizedReference(Object target)
- {
- IntPtr temp = IntPtr.Zero;
- temp = CreateSizedRef(target);
- _handle = temp;
- }
-
- ~SizedReference()
- {
- Free();
- }
-
- public Object Target
- {
- [System.Security.SecuritySafeCritical]
- get
- {
- IntPtr temp = _handle;
- if (temp == IntPtr.Zero)
- {
- return null;
- }
-
- Object o = GetTargetOfSizedRef(temp);
-
- return (_handle == IntPtr.Zero) ? null : o;
- }
- }
-
- public Int64 ApproximateSize
- {
- [System.Security.SecuritySafeCritical]
- get
- {
- IntPtr temp = _handle;
-
- if (temp == IntPtr.Zero)
- {
- throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_HandleIsNotInitialized"));
- }
-
- Int64 size = GetApproximateSizeOfSizedRef(temp);
-
- if (_handle == IntPtr.Zero)
- {
- throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_HandleIsNotInitialized"));
- }
- else
- {
- return size;
- }
- }
- }
-
- public void Dispose()
- {
- Free();
- GC.SuppressFinalize(this);
- }
- }
-#endif
}
using System.Runtime.CompilerServices;
using System.Globalization;
using System.Runtime.Versioning;
+ using System.Diagnostics;
using System.Diagnostics.Contracts;
// This abstract class represents a calendar. A calendar reckons time in
get {
// The following code assumes that the current era value can not be -1.
if (m_currentEraValue == -1) {
- Contract.Assert(BaseCalendarID > 0, "[Calendar.CurrentEraValue] Expected ID > 0");
+ Debug.Assert(BaseCalendarID > 0, "[Calendar.CurrentEraValue] Expected ID > 0");
m_currentEraValue = CalendarData.GetCalendarData(BaseCalendarID).iCurrentEra;
}
return (m_currentEraValue);
// this value can be less than 0. It's fine since we are making it positive again in calculating offset.
int dayForJan1 = (int)GetDayOfWeek(time) - (dayOfYear % 7);
int offset = (dayForJan1 - firstDayOfWeek + 14) % 7;
- Contract.Assert(offset >= 0, "Calendar.GetFirstDayWeekOfYear(): offset >= 0");
+ Debug.Assert(offset >= 0, "Calendar.GetFirstDayWeekOfYear(): offset >= 0");
return ((dayOfYear + offset) / 7 + 1);
}
throw new ArgumentOutOfRangeException(null, Environment.GetResourceString("ArgumentOutOfRange_BadHourMinuteSecond"));
}
- [System.Security.SecuritySafeCritical] // auto-generated
internal static int GetSystemTwoDigitYearSetting(int CalID, int defaultYearValue)
{
// Call nativeGetTwoDigitYearMax
using System.Runtime.InteropServices;
using System.Runtime.CompilerServices;
using System.Runtime.Versioning;
+ using System.Diagnostics;
using System.Diagnostics.Contracts;
//
// List of calendar data
this.bUseUserOverrides = bUseUserOverrides;
if (!nativeGetCalendarData(this, localeName, calendarId))
{
- Contract.Assert(false, "[CalendarData] nativeGetCalendarData call isn't expected to fail for calendar " + calendarId + " locale " +localeName);
+ Debug.Assert(false, "[CalendarData] nativeGetCalendarData call isn't expected to fail for calendar " + calendarId + " locale " +localeName);
// Something failed, try invariant for missing parts
// This is really not good, but we don't want the callers to crash.
// Get native two digit year max
- [System.Security.SecurityCritical] // auto-generated
[MethodImplAttribute(MethodImplOptions.InternalCall)]
internal static extern int nativeGetTwoDigitYearMax(int calID);
// Call native side to load our calendar data
- [System.Security.SecuritySafeCritical] // auto-generated
[MethodImplAttribute(MethodImplOptions.InternalCall)]
private static extern bool nativeGetCalendarData(CalendarData data, String localeName, int calendar);
// Call native side to figure out which calendars are allowed
- [System.Security.SecuritySafeCritical] // auto-generated
[MethodImplAttribute(MethodImplOptions.InternalCall)]
internal static extern int nativeGetCalendars(String localeName, bool useUserOverride, [In, Out] int[] calendars);
namespace System.Globalization
{
using System;
+ using System.Diagnostics;
using System.Diagnostics.Contracts;
internal class CalendricalCalculationsHelper
// the following formulas defines a polynomial function which gives us the amount that the earth is slowing down for specific year ranges
static double DefaultEphemerisCorrection(int gregorianYear)
{
- Contract.Assert(gregorianYear < 1620 || 2020 <= gregorianYear);
+ Debug.Assert(gregorianYear < 1620 || 2020 <= gregorianYear);
long january1stOfYear = GetNumberOfDays(new DateTime(gregorianYear, 1, 1));
double daysSinceStartOf1810 = january1stOfYear - StartOf1810;
double x = TwelveHours + daysSinceStartOf1810;
static double EphemerisCorrection1988to2019(int gregorianYear)
{
- Contract.Assert(1988 <= gregorianYear && gregorianYear <= 2019);
+ Debug.Assert(1988 <= gregorianYear && gregorianYear <= 2019);
return (double)(gregorianYear - 1933) / SecondsPerDay;
}
static double EphemerisCorrection1900to1987(int gregorianYear)
{
- Contract.Assert(1900 <= gregorianYear && gregorianYear <= 1987);
+ Debug.Assert(1900 <= gregorianYear && gregorianYear <= 1987);
double centuriesFrom1900 = CenturiesFrom1900(gregorianYear);
return PolynomialSum(Coefficients1900to1987, centuriesFrom1900);
}
static double EphemerisCorrection1800to1899(int gregorianYear)
{
- Contract.Assert(1800 <= gregorianYear && gregorianYear <= 1899);
+ Debug.Assert(1800 <= gregorianYear && gregorianYear <= 1899);
double centuriesFrom1900 = CenturiesFrom1900(gregorianYear);
return PolynomialSum(Coefficients1800to1899, centuriesFrom1900);
}
static double EphemerisCorrection1700to1799(int gregorianYear)
{
- Contract.Assert(1700 <= gregorianYear && gregorianYear <= 1799);
+ Debug.Assert(1700 <= gregorianYear && gregorianYear <= 1799);
double yearsSince1700 = gregorianYear - 1700;
return PolynomialSum(Coefficients1700to1799, yearsSince1700) / SecondsPerDay;
}
static double EphemerisCorrection1620to1699(int gregorianYear)
{
- Contract.Assert(1620 <= gregorianYear && gregorianYear <= 1699);
+ Debug.Assert(1620 <= gregorianYear && gregorianYear <= 1699);
double yearsSince1600 = gregorianYear - 1600;
return PolynomialSum(Coefficients1620to1699, yearsSince1600) / SecondsPerDay;
}
}
}
- Contract.Assert(false, "Not expected to come here");
+ Debug.Assert(false, "Not expected to come here");
return DefaultEphemerisCorrection(year);
}
break;
}
}
- Contract.Assert(day != upperBoundNewYearDay);
+ Debug.Assert(day != upperBoundNewYearDay);
return day - 1;
}
using System.Runtime.Versioning;
using System.Reflection;
using System.Security;
+ using System.Diagnostics;
using System.Diagnostics.Contracts;
static bool s_initialized = InitTable();
// The native pointer to the 12:4:4 index table of the Unicode cateogry data.
- [SecurityCritical]
unsafe static ushort* s_pCategoryLevel1Index;
- [SecurityCritical]
unsafe static byte* s_pCategoriesValue;
// The native pointer to the 12:4:4 index table of the Unicode numeric data.
// The value of this index table is an index into the real value table stored in s_pNumericValues.
- [SecurityCritical]
unsafe static ushort* s_pNumericLevel1Index;
// The numeric value table, which is indexed by s_pNumericLevel1Index.
// unsafe static double* s_pNumericValues;
// To get around the IA64 alignment issue. Our double data is aligned in 8-byte boundary, but loader loads the embeded table starting
// at 4-byte boundary. This cause a alignment issue since double is 8-byte.
- [SecurityCritical]
unsafe static byte* s_pNumericValues;
// The digit value table, which is indexed by s_pNumericLevel1Index. It shares the same indice as s_pNumericValues.
// Every item contains the value for decimal digit/digit value.
- [SecurityCritical]
unsafe static DigitValues* s_pDigitValues;
internal const String UNICODE_INFO_FILE_NAME = "charinfo.nlp";
//use. We allocate this once in the class initializer and then we don't need to worry
//about it again.
//
- [System.Security.SecuritySafeCritical] // auto-generated
unsafe static bool InitTable() {
// Go to native side and get pointer to the native table
////////////////////////////////////////////////////////////////////////
internal static int InternalConvertToUtf32(String s, int index) {
- Contract.Assert(s != null, "s != null");
- Contract.Assert(index >= 0 && index < s.Length, "index < s.Length");
+ Debug.Assert(s != null, "s != null");
+ Debug.Assert(index >= 0 && index < s.Length, "index < s.Length");
if (index < s.Length - 1) {
int temp1 = (int)s[index] - HIGH_SURROGATE_START;
if (temp1 >= 0 && temp1 <= 0x3ff) {
////////////////////////////////////////////////////////////////////////
internal static int InternalConvertToUtf32(String s, int index, out int charLength) {
- Contract.Assert(s != null, "s != null");
- Contract.Assert(s.Length > 0, "s.Length > 0");
- Contract.Assert(index >= 0 && index < s.Length, "index >= 0 && index < s.Length");
+ Debug.Assert(s != null, "s != null");
+ Debug.Assert(s.Length > 0, "s.Length > 0");
+ Debug.Assert(index >= 0 && index < s.Length, "index >= 0 && index < s.Length");
charLength = 1;
if (index < s.Length - 1) {
int temp1 = (int)s[index] - HIGH_SURROGATE_START;
internal static bool IsWhiteSpace(String s, int index)
{
- Contract.Assert(s != null, "s!=null");
- Contract.Assert(index >= 0 && index < s.Length, "index >= 0 && index < s.Length");
+ Debug.Assert(s != null, "s!=null");
+ Debug.Assert(index >= 0 && index < s.Length, "index >= 0 && index < s.Length");
UnicodeCategory uc = GetUnicodeCategory(s, index);
// In Unicode 3.0, U+2028 is the only character which is under the category "LineSeparator".
//
// Note that for ch in the range D800-DFFF we just treat it as any other non-numeric character
//
- [System.Security.SecuritySafeCritical] // auto-generated
internal unsafe static double InternalGetNumericValue(int ch) {
- Contract.Assert(ch >= 0 && ch <= 0x10ffff, "ch is not in valid Unicode range.");
+ Debug.Assert(ch >= 0 && ch <= 0x10ffff, "ch is not in valid Unicode range.");
// Get the level 2 item from the highest 12 bit (8 - 19) of ch.
ushort index = s_pNumericLevel1Index[ch >> 8];
// Get the level 2 WORD offset from the 4 - 7 bit of ch. This provides the base offset of the level 3 table.
//
// Note that for ch in the range D800-DFFF we just treat it as any other non-numeric character
//
- [System.Security.SecuritySafeCritical] // auto-generated
internal unsafe static DigitValues* InternalGetDigitValues(int ch) {
- Contract.Assert(ch >= 0 && ch <= 0x10ffff, "ch is not in valid Unicode range.");
+ Debug.Assert(ch >= 0 && ch <= 0x10ffff, "ch is not in valid Unicode range.");
// Get the level 2 item from the highest 12 bit (8 - 19) of ch.
ushort index = s_pNumericLevel1Index[ch >> 8];
// Get the level 2 WORD offset from the 4 - 7 bit of ch. This provides the base offset of the level 3 table.
return &(s_pDigitValues[pBytePtr[(ch & 0x000f)]]);
}
- [System.Security.SecuritySafeCritical] // auto-generated
internal unsafe static sbyte InternalGetDecimalDigitValue(int ch) {
return (InternalGetDigitValues(ch)->decimalDigit);
}
- [System.Security.SecuritySafeCritical] // auto-generated
internal unsafe static sbyte InternalGetDigitValue(int ch) {
return (InternalGetDigitValues(ch)->digit);
}
//
////////////////////////////////////////////////////////////////////////
- [System.Security.SecuritySafeCritical] // auto-generated
internal unsafe static byte InternalGetCategoryValue(int ch, int offset) {
- Contract.Assert(ch >= 0 && ch <= 0x10ffff, "ch is not in valid Unicode range.");
+ Debug.Assert(ch >= 0 && ch <= 0x10ffff, "ch is not in valid Unicode range.");
// Get the level 2 item from the highest 12 bit (8 - 19) of ch.
ushort index = s_pCategoryLevel1Index[ch >> 8];
// Get the level 2 WORD offset from the 4 - 7 bit of ch. This provides the base offset of the level 3 table.
// Make sure that OtherNotAssigned is the last category in UnicodeCategory.
// If that changes, change the following assertion as well.
//
- //Contract.Assert(uc >= 0 && uc <= UnicodeCategory.OtherNotAssigned, "Table returns incorrect Unicode category");
+ //Debug.Assert(uc >= 0 && uc <= UnicodeCategory.OtherNotAssigned, "Table returns incorrect Unicode category");
return (uc);
}
////////////////////////////////////////////////////////////////////////
internal static UnicodeCategory InternalGetUnicodeCategory(String value, int index) {
- Contract.Assert(value != null, "value can not be null");
- Contract.Assert(index < value.Length, "index < value.Length");
+ Debug.Assert(value != null, "value can not be null");
+ Debug.Assert(index < value.Length, "index < value.Length");
return (InternalGetUnicodeCategory(InternalConvertToUtf32(value, index)));
}
////////////////////////////////////////////////////////////////////////
internal static UnicodeCategory InternalGetUnicodeCategory(String str, int index, out int charLength) {
- Contract.Assert(str != null, "str can not be null");
- Contract.Assert(str.Length > 0, "str.Length > 0");;
- Contract.Assert(index >= 0 && index < str.Length, "index >= 0 && index < str.Length");
+ Debug.Assert(str != null, "str can not be null");
+ Debug.Assert(str.Length > 0, "str.Length > 0");;
+ Debug.Assert(index >= 0 && index < str.Length, "index >= 0 && index < str.Length");
return (InternalGetUnicodeCategory(InternalConvertToUtf32(str, index, out charLength)));
}
internal static bool IsCombiningCategory(UnicodeCategory uc) {
- Contract.Assert(uc >= 0, "uc >= 0");
+ Debug.Assert(uc >= 0, "uc >= 0");
return (
uc == UnicodeCategory.NonSpacingMark ||
uc == UnicodeCategory.SpacingCombiningMark ||
using System.Security.Permissions;
using Microsoft.Win32;
using System.Security;
+ using System.Diagnostics;
using System.Diagnostics.Contracts;
//
return(IsSortable(ch.ToString()));
}
- [System.Security.SecuritySafeCritical]
[System.Runtime.InteropServices.ComVisible(false)]
public static bool IsSortable(String text) {
if (text == null) {
#if FEATURE_USE_LCID
// This is merely for serialization compatibility with Whidbey/Orcas, it can go away when we don't want that compat any more.
culture = CultureInfo.GetCultureInfo(this.Name).LCID; // This is the lcid of the constructing culture (still have to dereference to get target sort)
- Contract.Assert(m_name != null, "CompareInfo.OnSerializing - expected m_name to be set already");
+ Debug.Assert(m_name != null, "CompareInfo.OnSerializing - expected m_name to be set already");
#endif
}
{
get
{
- Contract.Assert(m_name != null, "CompareInfo.Name Expected m_name to be set");
-#if !FEATURE_CORECLR
- if (m_name == "zh-CHT" || m_name == "zh-CHS")
- {
- return m_name;
- }
-#endif // FEATURE_CORECLR
-
+ Debug.Assert(m_name != null, "CompareInfo.Name Expected m_name to be set");
return (m_sortName);
}
}
// some NLS VM functions can handle COMPARE_OPTIONS_ORDINAL
// in which case options should be simply cast to int instead of using this function
// Does not look like the best approach to me but for now I am going to leave it as it is
- Contract.Assert(options != CompareOptions.OrdinalIgnoreCase, "[CompareInfo.GetNativeCompareFlags]CompareOptions.OrdinalIgnoreCase should be handled separately");
+ Debug.Assert(options != CompareOptions.OrdinalIgnoreCase, "[CompareInfo.GetNativeCompareFlags]CompareOptions.OrdinalIgnoreCase should be handled separately");
// Use "linguistic casing" by default (load the culture's casing exception tables)
int nativeCompareFlags = NORM_LINGUISTIC_CASING;
// Suffix & Prefix shouldn't use this, make sure to turn off the NORM_LINGUISTIC_CASING flag
if (options == CompareOptions.Ordinal) { nativeCompareFlags = COMPARE_OPTIONS_ORDINAL; }
- Contract.Assert(((options & ~(CompareOptions.IgnoreCase |
+ Debug.Assert(((options & ~(CompareOptions.IgnoreCase |
CompareOptions.IgnoreKanaType |
CompareOptions.IgnoreNonSpace |
CompareOptions.IgnoreSymbols |
CompareOptions.StringSort)) == 0) ||
(options == CompareOptions.Ordinal), "[CompareInfo.GetNativeCompareFlags]Expected all flags to be handled");
- Contract.Assert((nativeCompareFlags & RESERVED_FIND_ASCII_STRING) == 0, "[CompareInfo.GetNativeCompareFlags] RESERVED_FIND_ASCII_STRING shouldn't be set here");
+ Debug.Assert((nativeCompareFlags & RESERVED_FIND_ASCII_STRING) == 0, "[CompareInfo.GetNativeCompareFlags] RESERVED_FIND_ASCII_STRING shouldn't be set here");
return nativeCompareFlags;
}
return (Compare(string1, string2, CompareOptions.None));
}
- [System.Security.SecuritySafeCritical] // auto-generated
public unsafe virtual int Compare(String string1, String string2, CompareOptions options){
if (options == CompareOptions.OrdinalIgnoreCase)
}
- [System.Security.SecuritySafeCritical] // auto-generated
public unsafe virtual int Compare(String string1, int offset1, int length1, String string2, int offset2, int length2, CompareOptions options)
{
if (options == CompareOptions.OrdinalIgnoreCase)
////////////////////////////////////////////////////////////////////////
- [System.Security.SecuritySafeCritical] // auto-generated
public unsafe virtual bool IsPrefix(String source, String prefix, CompareOptions options)
{
if (source == null || prefix == null) {
////////////////////////////////////////////////////////////////////////
- [System.Security.SecuritySafeCritical] // auto-generated
public unsafe virtual bool IsSuffix(String source, String suffix, CompareOptions options)
{
if (source == null || suffix == null) {
return IndexOf(source, value, startIndex, count, CompareOptions.None);
}
- [System.Security.SecuritySafeCritical] // auto-generated
public unsafe virtual int IndexOf(String source, char value, int startIndex, int count, CompareOptions options)
{
// Validate inputs
}
- [System.Security.SecuritySafeCritical] // auto-generated
public unsafe virtual int IndexOf(String source, String value, int startIndex, int count, CompareOptions options)
{
// Validate inputs
}
- [System.Security.SecuritySafeCritical] // auto-generated
public unsafe virtual int LastIndexOf(String source, char value, int startIndex, int count, CompareOptions options)
{
// Verify Arguments
}
- [System.Security.SecuritySafeCritical] // auto-generated
public unsafe virtual int LastIndexOf(String source, String value, int startIndex, int count, CompareOptions options)
{
// Verify Arguments
return CreateSortKey(source, CompareOptions.None);
}
- [System.Security.SecuritySafeCritical]
private SortKey CreateSortKey(String source, CompareOptions options)
{
if (source==null) { throw new ArgumentNullException(nameof(source)); }
return GetHashCodeOfString(source, options, false, 0);
}
- [System.Security.SecuritySafeCritical] // auto-generated
internal int GetHashCodeOfString(string source, CompareOptions options, bool forceRandomizedHashing, long additionalEntropy)
{
//
}
#endif
- [System.Security.SecuritySafeCritical]
internal static IntPtr InternalInitSortHandle(String localeName, out IntPtr handleOrigin)
{
return NativeInternalInitSortHandle(localeName, out handleOrigin);
}
-#if !FEATURE_CORECLR
- private const int SORT_VERSION_WHIDBEY = 0x00001000;
- private const int SORT_VERSION_V4 = 0x00060101;
-
- internal static bool IsLegacy20SortingBehaviorRequested
- {
- get
- {
- return InternalSortVersion == SORT_VERSION_WHIDBEY;
- }
- }
-
- private static uint InternalSortVersion
- {
- [System.Security.SecuritySafeCritical]
- get
- {
- return InternalGetSortVersion();
- }
- }
-#endif
-
[OptionalField(VersionAdded = 3)]
private SortVersion m_SortVersion;
public SortVersion Version
{
- [SecuritySafeCritical]
get
{
if(m_SortVersion == null)
}
}
- [System.Security.SecurityCritical]
[DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
[SuppressUnmanagedCodeSecurity]
[return: MarshalAs(UnmanagedType.Bool)]
private static extern bool InternalGetNlsVersionEx(IntPtr handle, IntPtr handleOrigin, String localeName, ref Win32Native.NlsVersionInfoEx lpNlsVersionInformation);
-#if !FEATURE_CORECLR
- [System.Security.SecurityCritical]
- [DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
- [SuppressUnmanagedCodeSecurity]
- private static extern uint InternalGetSortVersion();
-
-#endif
- [System.Security.SecurityCritical]
[DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
[SuppressUnmanagedCodeSecurity]
private static extern IntPtr NativeInternalInitSortHandle(String localeName, out IntPtr handleOrigin);
// Get a locale sensitive sort hash code from native code -- COMNlsInfo::InternalGetGlobalizedHashCode
- [System.Security.SecurityCritical] // auto-generated
[DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
[SuppressUnmanagedCodeSecurity]
private static extern int InternalGetGlobalizedHashCode(IntPtr handle, IntPtr handleOrigin, string localeName, string source, int length, int dwFlags, bool forceRandomizedHashing, long additionalEntropy);
// Use native API calls to see if this string is entirely defined -- COMNlsInfo::InternalIsSortable
- [System.Security.SecurityCritical] // auto-generated
[DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
[SuppressUnmanagedCodeSecurity]
[return: MarshalAs(UnmanagedType.Bool)]
private static extern bool InternalIsSortable(IntPtr handle, IntPtr handleOrigin, String localeName, String source, int length);
// Compare a string using the native API calls -- COMNlsInfo::InternalCompareString
- [System.Security.SecurityCritical] // auto-generated
[DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
[SuppressUnmanagedCodeSecurity]
private static extern int InternalCompareString(IntPtr handle, IntPtr handleOrigin, String localeName, String string1, int offset1, int length1,
// InternalFindNLSStringEx parameters is not exactly matching kernel32::FindNLSStringEx parameters.
// Call through to NewApis::FindNLSStringEx so we can get the right behavior
- [System.Security.SecurityCritical] // auto-generated
[DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
[SuppressUnmanagedCodeSecurity]
private static extern int InternalFindNLSStringEx(IntPtr handle, IntPtr handleOrigin, String localeName, int flags, String source, int sourceCount, int startIndex, string target, int targetCount);
// Call through to NewAPis::LCMapStringEx so we can get appropriate behavior for all platforms
- [System.Security.SecurityCritical] // auto-generated
[DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
[SuppressUnmanagedCodeSecurity]
private static extern int InternalGetSortKey(IntPtr handle, IntPtr handleOrigin, String localeName, int flags, String source, int sourceCount, byte[] target, int targetCount);
using System.Collections.Generic;
using System.Text;
using System.Threading;
-#if !FEATURE_CORECLR
- using System.Reflection;
- using System.Resources;
-#endif
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Runtime.Versioning;
+ using System.Diagnostics;
using System.Diagnostics.Contracts;
using System.Security;
}
private volatile static CultureData s_Invariant;
-
-#if !FEATURE_CORECLR
- internal static volatile ResourceSet MscorlibResourceSet;
-#endif
-
-#if !FEATURE_CORECLR
- [System.Security.SecurityCritical] // auto-generated
- private static bool IsResourcePresent(String resourceKey)
- {
- if (MscorlibResourceSet == null)
- {
- MscorlibResourceSet = new ResourceSet(typeof(Environment).Assembly.GetManifestResourceStream("mscorlib.resources"));
- }
- return MscorlibResourceSet.GetString(resourceKey) != null;
- }
-#endif
-
///////////////
// Constructors //
///////////////
// Ask native code if that one's real
if (culture.InitCultureData() == false)
{
-#if !FEATURE_CORECLR
- if (culture.InitCompatibilityCultureData() == false
- && culture.InitLegacyAlternateSortData() == false)
-#endif
- {
- return null;
- }
+ return null;
}
return culture;
{
return false;
}
-
-#if !FEATURE_CORECLR
- if (CultureInfo.IsTaiwanSku)
- {
- TreatTaiwanParentChainAsHavingTaiwanAsSpecific();
- }
-#endif
- return true;
- }
-
-#if !FEATURE_CORECLR
- [System.Security.SecuritySafeCritical]
- private void TreatTaiwanParentChainAsHavingTaiwanAsSpecific()
- {
- if (IsNeutralInParentChainOfTaiwan() && IsOsPriorToWin7() && !IsReplacementCulture)
- {
- // force population of fields that should have information that is
- // different than zh-TW:
- string s = SNATIVELANGUAGE;
- s = SENGLISHLANGUAGE;
- s = SLOCALIZEDLANGUAGE;
- s = STEXTINFO;
- s = SCOMPAREINFO;
- s = FONTSIGNATURE;
- int i = IDEFAULTANSICODEPAGE;
- i = IDEFAULTOEMCODEPAGE;
- i = IDEFAULTMACCODEPAGE;
-
- this.sSpecificCulture = "zh-TW";
- this.sWindowsName = "zh-TW";
- }
- }
-
- private bool IsNeutralInParentChainOfTaiwan()
- {
- return this.sRealName == "zh" || this.sRealName == "zh-Hant";
- }
-
- static readonly Version s_win7Version = new Version(6, 1);
- static private bool IsOsPriorToWin7()
- {
- return Environment.OSVersion.Platform == PlatformID.Win32NT &&
- Environment.OSVersion.Version < s_win7Version;
- }
- static private bool IsOsWin7OrPrior()
- {
- return Environment.OSVersion.Platform == PlatformID.Win32NT &&
- Environment.OSVersion.Version < new Version(6, 2); // Win7 is 6.1.Build.Revision so we have to check for anything less than 6.2
- }
-
- private bool InitCompatibilityCultureData()
- {
- // for compatibility handle the deprecated ids: zh-chs, zh-cht
- string cultureName = this.sRealName;
-
- string fallbackCultureName;
- string realCultureName;
- switch (AnsiToLower(cultureName))
- {
- case "zh-chs":
- fallbackCultureName = "zh-Hans";
- realCultureName = "zh-CHS";
- break;
- case "zh-cht":
- fallbackCultureName = "zh-Hant";
- realCultureName = "zh-CHT";
- break;
- default:
- return false;
- }
-
- this.sRealName = fallbackCultureName;
- if (InitCultureData() == false)
- {
- return false;
- }
- // fixup our data
- this.sName = realCultureName; // the name that goes back to the user
- this.sParent = fallbackCultureName;
- this.bFramework = true;
-
- return true;
- }
-
- private bool InitLegacyAlternateSortData()
- {
- if (!CompareInfo.IsLegacy20SortingBehaviorRequested)
- {
- return false;
- }
-
- // For V2 compatibility, handle deprecated alternate sorts
- string cultureName = this.sRealName;
-
- switch (AnsiToLower(cultureName))
- {
- case "ko-kr_unicod":
- cultureName = "ko-KR_unicod";
- this.sRealName = "ko-KR";
- this.iLanguage = 0x00010412;
- break;
- case "ja-jp_unicod":
- cultureName = "ja-JP_unicod";
- this.sRealName = "ja-JP";
- this.iLanguage = 0x00010411;
- break;
- case "zh-hk_stroke":
- cultureName = "zh-HK_stroke";
- this.sRealName = "zh-HK";
- this.iLanguage = 0x00020c04;
- break;
- default:
- return false;
- }
-
- if (nativeInitCultureData(this) == false)
- {
- return false;
- }
-
- this.sRealName = cultureName;
- this.sCompareInfo = cultureName;
- this.bFramework = true;
-
return true;
}
-#if FEATURE_WIN32_REGISTRY
- private static String s_RegionKey = @"System\CurrentControlSet\Control\Nls\RegionMapping";
-#endif // FEATURE_WIN32_REGISTRY
-
-#endif // !FEATURE_CORECLR
// Cache of regions we've already looked up
private static volatile Dictionary<String, CultureData> s_cachedRegions;
- [System.Security.SecurityCritical] // auto-generated
internal static CultureData GetCultureDataForRegion(String cultureName, bool useUserOverride)
{
// First do a shortcut for Invariant
//
// Not found in the hash table, look it up the hard way
//
-#if !FEATURE_CORECLR
-#if FEATURE_WIN32_REGISTRY
- // First try the registry in case there are overrides of our table
- try
- {
- // Open in read-only mode.
- // Use InternalOpenSubKey so that we avoid the security check.
- Microsoft.Win32.RegistryKey key = Microsoft.Win32.Registry.LocalMachine.InternalOpenSubKey(s_RegionKey, false);
-
- if (key != null)
- {
- try
- {
- Object value = key.InternalGetValue(cultureName, null, false, false);
-
- if (value != null)
- {
- // Get the name of the locale to try.
- String specificForRegion = value.ToString();
-
- // See if it's real
- retVal = GetCultureData(specificForRegion, useUserOverride);
- }
- }
- finally
- {
- key.Close();
- }
- }
- }
- // If this fails for any reason, we'll just ignore it, likely it just isn't there.
- catch (ObjectDisposedException) { }
- catch (ArgumentException) { }
-#endif // FEATURE_WIN32_REGISTRY
-#endif // !FEATURE_CORECLR
// If not a valid mapping from the registry we'll have to try the hard coded table
if (retVal == null || (retVal.IsNeutralCulture == true))
#if FEATURE_USE_LCID
// Obtain locale name from LCID
// NOTE: This will get neutral names, unlike the OS API
- [System.Security.SecuritySafeCritical] // auto-generated
[MethodImplAttribute(MethodImplOptions.InternalCall)]
internal static extern String LCIDToLocaleName(int lcid);
String localeName = null;
CultureData retVal = null;
-#if !FEATURE_CORECLR
- // If V2 legacy sort is requested, then provide deprecated alternate sorts
- if (CompareInfo.IsLegacy20SortingBehaviorRequested)
- {
- switch (culture)
- {
- case 0x00010412:
- localeName = "ko-KR_unicod";
- break;
- case 0x00010411:
- localeName = "ja-JP_unicod";
- break;
- case 0x00020c04:
- localeName = "zh-HK_stroke";
- break;
- }
- }
-#endif
-
if (localeName == null)
{
// Convert the lcid to a name, then use that
}
else
{
-#if !FEATURE_CORECLR
- switch (localeName)
- {
- // for compatibility with Whidbey, when requesting
- // a locale from LCID, return the old localeName
- case "zh-Hans":
- localeName = "zh-CHS";
- break;
- case "zh-Hant":
- localeName = "zh-CHT";
- break;
- }
-#endif
// Valid name, use it
retVal = GetCultureData(localeName, bUseUserOverride);
}
s_replacementCultureNames = null;
}
- [System.Security.SecuritySafeCritical] // auto-generated
internal static CultureInfo[] GetCultures(CultureTypes types)
{
// Disable warning 618: System.Globalization.CultureTypes.FrameworkCultures' is obsolete
int arrayLength = cultureNames.Length;
-#if !FEATURE_CORECLR
- if ((types & (CultureTypes.NeutralCultures | CultureTypes.FrameworkCultures)) != 0) // add zh-CHT and zh-CHS
- {
- arrayLength += 2;
- }
-#endif // FEATURE_CORECLR
-
CultureInfo[] cultures = new CultureInfo[arrayLength];
for (int i = 0; i < cultureNames.Length; i++)
{
cultures[i] = new CultureInfo(cultureNames[i]);
}
-
-#if !FEATURE_CORECLR
- if ((types & (CultureTypes.NeutralCultures | CultureTypes.FrameworkCultures)) != 0) // add zh-CHT and zh-CHS
- {
- Contract.Assert(arrayLength == cultureNames.Length + 2, "CultureData.nativeEnumCultureNames() Incorrect array size");
- cultures[cultureNames.Length] = new CultureInfo("zh-CHS");
- cultures[cultureNames.Length + 1] = new CultureInfo("zh-CHT");
- }
-#endif // FEATURE_CORECLR
-
#pragma warning restore 618
return cultures;
////////////////////////////////////////////////////////////////////////
- [System.Security.SecuritySafeCritical] // auto-generated
private static bool IsReplacementCultureName(String name)
{
- Contract.Assert(name != null, "IsReplacementCultureName(): name should not be null");
+ Debug.Assert(name != null, "IsReplacementCultureName(): name should not be null");
String[] replacementCultureNames = s_replacementCultureNames;
if (replacementCultureNames == null)
{
}
// Even if we don't have any replacement cultures, the returned replacementCultureNames will still an empty string array, not null.
- Contract.Assert(name != null, "IsReplacementCultureName(): replacementCultureNames should not be null");
+ Debug.Assert(name != null, "IsReplacementCultureName(): replacementCultureNames should not be null");
Array.Sort(replacementCultureNames);
s_replacementCultureNames = replacementCultureNames;
}
{
get
{
- Contract.Assert(this.sRealName != null, "[CultureData.CultureName] Expected this.sRealName to be populated by COMNlsInfo::nativeInitCultureData already");
+ Debug.Assert(this.sRealName != null, "[CultureData.CultureName] Expected this.sRealName to be populated by COMNlsInfo::nativeInitCultureData already");
// since windows doesn't know about zh-CHS and zh-CHT,
// we leave sRealName == zh-Hanx but we still need to
// pretend that it was zh-CHX.
{
get
{
- // Contract.Assert(this.sName != null,
+ // Debug.Assert(this.sName != null,
// "[CultureData.SNAME] Expected this.sName to be populated by COMNlsInfo::nativeInitCultureData already");
if (this.sName == null)
{
// Parent name (which may be a custom locale/culture)
internal String SPARENT
{
- [System.Security.SecurityCritical] // auto-generated
get
{
if (this.sParent == null)
{
// Ask using the real name, so that we get parents of neutrals
this.sParent = DoGetLocaleInfo(this.sRealName, LOCALE_SPARENT);
-
-#if !FEATURE_CORECLR
- // for compatibility, the chain should be:
- // zh-CN -> zh-CHS -> zh-Hans -> zh
- // zh-TW -> zh-CHT -> zh-Hant -> zh
- Contract.Assert(this.sName != "zh-CHS" && this.sName != "zh-CHT",
- "sParent should have been initialized for zh-CHS and zh-CHT when they were constructed, otherwise we get recursion");
- switch (this.sParent)
- {
- case "zh-Hans":
- this.sParent = "zh-CHS";
- break;
- case "zh-Hant":
- this.sParent = "zh-CHT";
- break;
- }
-#endif
-
}
return this.sParent;
}
// Localized pretty name for this locale (ie: Inglis (estados Unitos))
internal String SLOCALIZEDDISPLAYNAME
{
- [System.Security.SecurityCritical] // auto-generated
get
{
if (this.sLocalizedDisplayName == null)
{
-#if !FEATURE_CORECLR
- String resourceKey = "Globalization.ci_" + this.sName;
- if (IsResourcePresent(resourceKey))
- {
- this.sLocalizedDisplayName = Environment.GetResourceString(resourceKey);
- }
-#endif
// If it hasn't been found (Windows 8 and up), fallback to the system
if (String.IsNullOrEmpty(this.sLocalizedDisplayName))
{
// English pretty name for this locale (ie: English (United States))
internal String SENGDISPLAYNAME
{
- [System.Security.SecurityCritical] // auto-generated
get
{
if (this.sEnglishDisplayName == null)
if (this.IsNeutralCulture)
{
this.sEnglishDisplayName = this.SENGLISHLANGUAGE;
-#if !FEATURE_CORECLR
- // differentiate the legacy display names
- switch (this.sName)
- {
- case "zh-CHS":
- case "zh-CHT":
- this.sEnglishDisplayName += " Legacy";
- break;
- }
-#endif
-
}
else
{
// Native pretty name for this locale (ie: Deutsch (Deutschland))
internal String SNATIVEDISPLAYNAME
{
- [System.Security.SecurityCritical] // auto-generated
get
{
if (this.sNativeDisplayName == null)
if (this.IsNeutralCulture)
{
this.sNativeDisplayName = this.SNATIVELANGUAGE;
-#if !FEATURE_CORECLR
- // differentiate the legacy display names
- switch (this.sName)
- {
- case "zh-CHS":
- this.sNativeDisplayName += " \u65E7\u7248";
- break;
- case "zh-CHT":
- this.sNativeDisplayName += " \u820A\u7248";
- break;
- }
-#endif
}
else
{
-#if !FEATURE_CORECLR
- if (IsIncorrectNativeLanguageForSinhala())
- {
- // work around bug in Windows 7 for native name of Sinhala
- this.sNativeDisplayName ="\x0dc3\x0dd2\x0d82\x0dc4\x0dbd (\x0DC1\x0DCA\x200D\x0DBB\x0DD3\x0020\x0DBD\x0D82\x0D9A\x0DCF)";
- }
- else
-#endif
- {
- this.sNativeDisplayName = DoGetLocaleInfo(LOCALE_SNATIVEDISPLAYNAME);
- }
+ this.sNativeDisplayName = DoGetLocaleInfo(LOCALE_SNATIVEDISPLAYNAME);
// if it isn't found build one:
if (String.IsNullOrEmpty(this.sNativeDisplayName))
get
{
// This got populated when ComNlsInfo::nativeInitCultureData told us we had a culture
- Contract.Assert(this.sSpecificCulture != null, "[CultureData.SSPECIFICCULTURE] Expected this.sSpecificCulture to be populated by COMNlsInfo::nativeInitCultureData already");
+ Debug.Assert(this.sSpecificCulture != null, "[CultureData.SSPECIFICCULTURE] Expected this.sSpecificCulture to be populated by COMNlsInfo::nativeInitCultureData already");
return this.sSpecificCulture;
}
}
// iso 639 language name, ie: en
internal String SISO639LANGNAME
{
- [System.Security.SecurityCritical] // auto-generated
get
{
if (this.sISO639Language == null)
// iso 639 language name, ie: eng
internal String SISO639LANGNAME2
{
- [System.Security.SecurityCritical] // auto-generated
get
{
if (this.sISO639Language2 == null)
// abbreviated windows language name (ie: enu) (non-standard, avoid this)
internal String SABBREVLANGNAME
{
- [System.Security.SecurityCritical] // auto-generated
get
{
if (this.sAbbrevLang == null)
// This is only valid for Windows 8 and higher neutrals:
internal String SLOCALIZEDLANGUAGE
{
- [System.Security.SecurityCritical] // auto-generated
get
{
if (this.sLocalizedLanguage == null)
// English name for this language (Windows Only) ie: German
internal String SENGLISHLANGUAGE
{
- [System.Security.SecurityCritical] // auto-generated
get
{
if (this.sEnglishLanguage == null)
// Native name of this language (Windows Only) ie: Deutsch
internal String SNATIVELANGUAGE
{
- [System.Security.SecurityCritical] // auto-generated
get
{
if (this.sNativeLanguage == null)
{
-#if !FEATURE_CORECLR
- if (IsIncorrectNativeLanguageForSinhala())
- {
- this.sNativeLanguage = "\x0dc3\x0dd2\x0d82\x0dc4\x0dbd";
- }
- else
-#endif
{
this.sNativeLanguage = DoGetLocaleInfo(LOCALE_SNATIVELANGUAGENAME);
}
}
}
-#if !FEATURE_CORECLR
- private bool IsIncorrectNativeLanguageForSinhala()
- {
- return IsOsWin7OrPrior()
- && (sName == "si-LK" || sName == "si")
- && !IsReplacementCulture;
- }
-#endif
-
///////////
// Region //
///////////
// region name (eg US)
internal String SREGIONNAME
{
- [System.Security.SecurityCritical] // auto-generated
get
{
if (this.sRegionName == null)
// localized name for the country
internal string SLOCALIZEDCOUNTRY
{
- [System.Security.SecurityCritical] // auto-generated
get
{
if (this.sLocalizedCountry == null)
{
-#if !FEATURE_CORECLR
- String resourceKey = "Globalization.ri_" + this.SREGIONNAME;
- if (IsResourcePresent(resourceKey))
- {
- this.sLocalizedCountry = Environment.GetResourceString(resourceKey);
- }
-#endif
// If it hasn't been found (Windows 8 and up), fallback to the system
if (String.IsNullOrEmpty(this.sLocalizedCountry))
{
// english country name (RegionInfo) ie: Germany
internal String SENGCOUNTRY
{
- [System.Security.SecurityCritical] // auto-generated
get
{
if (this.sEnglishCountry == null)
// native country name (RegionInfo) ie: Deutschland
internal String SNATIVECOUNTRY
{
- [System.Security.SecurityCritical] // auto-generated
get
{
if (this.sNativeCountry == null)
// ISO 3166 Country Name
internal String SISO3166CTRYNAME
{
- [System.Security.SecurityCritical] // auto-generated
get
{
if (this.sISO3166CountryName == null)
// ISO 3166 Country Name
internal String SISO3166CTRYNAME2
{
- [System.Security.SecurityCritical] // auto-generated
get
{
if (this.sISO3166CountryName2 == null)
// abbreviated Country Name (windows version, non-standard, avoid)
internal String SABBREVCTRYNAME
{
- [System.Security.SecurityCritical] // auto-generated
get
{
if (this.sAbbrevCountry == null)
// Console fallback name (ie: locale to use for console apps for unicode-only locales)
internal String SCONSOLEFALLBACKNAME
{
- [System.Security.SecurityCritical] // auto-generated
get
{
if (this.sConsoleFallbackName == null)
// (user can override) grouping of digits
internal int[] WAGROUPING
{
- [System.Security.SecurityCritical] // auto-generated
get
{
if (this.waGrouping == null || UseUserOverride)
// Not a Number
internal String SNAN
{
- [System.Security.SecurityCritical] // auto-generated
get
{
if (this.sNaN == null)
// + Infinity
internal String SPOSINFINITY
{
- [System.Security.SecurityCritical] // auto-generated
get
{
if (this.sPositiveInfinity == null)
// - Infinity
internal String SNEGINFINITY
{
- [System.Security.SecurityCritical] // auto-generated
get
{
if (this.sNegativeInfinity == null)
// Percent (%) symbol
internal String SPERCENT
{
- [System.Security.SecurityCritical] // auto-generated
get
{
if (this.sPercent == null)
// PerMille (‰) symbol
internal String SPERMILLE
{
- [System.Security.SecurityCritical] // auto-generated
get
{
if (this.sPerMille == null)
// (user can override) local monetary symbol, eg: $
internal String SCURRENCY
{
- [System.Security.SecurityCritical] // auto-generated
get
{
if (this.sCurrency == null || UseUserOverride)
// international monetary symbol (RegionInfo), eg: USD
internal String SINTLSYMBOL
{
- [System.Security.SecurityCritical] // auto-generated
get
{
if (this.sIntlMonetarySymbol == null)
// English name for this currency (RegionInfo), eg: US Dollar
internal String SENGLISHCURRENCY
{
- [System.Security.SecurityCritical] // auto-generated
get
{
if (this.sEnglishCurrency == null)
// Native name for this currency (RegionInfo), eg: Schweiz Frank
internal String SNATIVECURRENCY
{
- [System.Security.SecurityCritical] // auto-generated
get
{
if (this.sNativeCurrency == null)
// (user can override) monetary grouping of digits
internal int[] WAMONGROUPING
{
- [System.Security.SecurityCritical] // auto-generated
get
{
if (this.waMonetaryGrouping == null || UseUserOverride)
// (user can override) list Separator
internal String SLIST
{
- [System.Security.SecurityCritical] // auto-generated
get
{
if (this.sListSeparator == null || UseUserOverride)
// (user can override) AM designator
internal String SAM1159
{
- [System.Security.SecurityCritical] // auto-generated
get
{
if (this.sAM1159 == null || UseUserOverride)
// (user can override) PM designator
internal String SPM2359
{
- [System.Security.SecurityCritical] // auto-generated
get
{
if (this.sPM2359 == null || UseUserOverride)
// time duration format
internal String[] SADURATION
{
- [System.Security.SecurityCritical] // auto-generated
get
{
if (this.saDurationFormats == null)
// We then have to copy that list to a new array of the right size.
// Default calendar should be first
int[] calendarInts = new int[23];
- Contract.Assert(this.sWindowsName != null, "[CultureData.CalendarIds] Expected this.sWindowsName to be populated by COMNlsInfo::nativeInitCultureData already");
+ Debug.Assert(this.sWindowsName != null, "[CultureData.CalendarIds] Expected this.sWindowsName to be populated by COMNlsInfo::nativeInitCultureData already");
int count = CalendarData.nativeGetCalendars(this.sWindowsName, this.bUseOverrides, calendarInts);
// See if we had a calendar to add.
// Want 1st calendar to be default
// Prior to Vista the enumeration didn't have default calendar first
// Only a coreclr concern, culture.dll does the right thing.
-#if FEATURE_CORECLR
if (temp.Length > 1)
{
int i = DoGetLocaleInfoInt(LOCALE_ICALENDARTYPE);
temp[0] = i;
}
}
-#endif
this.waCalendars = temp;
}
internal CalendarData GetCalendar(int calendarId)
{
- Contract.Assert(calendarId > 0 && calendarId <= CalendarData.MAX_CALENDARS,
+ Debug.Assert(calendarId > 0 && calendarId <= CalendarData.MAX_CALENDARS,
"[CultureData.GetCalendar] Expect calendarId to be in a valid range");
// arrays are 0 based, calendarIds are 1 based
// Make sure that calendar has data
if (calendarData == null || UseUserOverride)
{
- Contract.Assert(this.sWindowsName != null, "[CultureData.GetCalendar] Expected this.sWindowsName to be populated by COMNlsInfo::nativeInitCultureData already");
+ Debug.Assert(this.sWindowsName != null, "[CultureData.GetCalendar] Expected this.sWindowsName to be populated by COMNlsInfo::nativeInitCultureData already");
calendarData = new CalendarData(this.sWindowsName, calendarId, this.UseUserOverride);
-#if !FEATURE_CORECLR
- //Work around issue where Win7 data for MonthDay contains invalid two sets of data separated by semicolon
- //even though MonthDay is not enumerated
- if (IsOsWin7OrPrior() && !IsSupplementalCustomCulture && !IsReplacementCulture)
- {
- calendarData.FixupWin7MonthDaySemicolonBug();
- }
-#endif
calendars[calendarIndex] = calendarData;
}
{
if (this.iReadingLayout == undef)
{
- Contract.Assert(this.sRealName != null, "[CultureData.IsRightToLeft] Expected this.sRealName to be populated by COMNlsInfo::nativeInitCultureData already");
+ Debug.Assert(this.sRealName != null, "[CultureData.IsRightToLeft] Expected this.sRealName to be populated by COMNlsInfo::nativeInitCultureData already");
this.iReadingLayout = DoGetLocaleInfoInt(LOCALE_IREADINGLAYOUT);
}
// es-ES_tradnl -> es-ES
internal String STEXTINFO // Text info name to use for text information
{
- [System.Security.SecuritySafeCritical]
get
{
if (this.sTextInfo == null)
// Compare info name (including sorting key) to use if custom
internal String SCOMPAREINFO
{
- [System.Security.SecuritySafeCritical]
get
{
if (this.sCompareInfo == null)
private String SSCRIPTS
{
- [System.Security.SecuritySafeCritical] // auto-generated
get
{
if (this.sScripts == null)
private String SOPENTYPELANGUAGETAG
{
- [System.Security.SecuritySafeCritical] // auto-generated
get
{
return DoGetLocaleInfo(LOCALE_SOPENTYPELANGUAGETAG);
private String FONTSIGNATURE
{
- [System.Security.SecuritySafeCritical] // auto-generated
get
{
if (this.fontSignature == null)
private String SKEYBOARDSTOINSTALL
{
- [System.Security.SecuritySafeCritical] // auto-generated
get
{
return DoGetLocaleInfo(LOCALE_SKEYBOARDSTOINSTALL);
// Obtain locale name from LCID
// NOTE: This will get neutral names, unlike the OS API
- [System.Security.SecuritySafeCritical] // auto-generated
[MethodImplAttribute(MethodImplOptions.InternalCall)]
internal static extern int LocaleNameToLCID(String localeName);
{
if (this.iLanguage == 0)
{
- Contract.Assert(this.sRealName != null, "[CultureData.ILANGUAGE] Expected this.sRealName to be populated by COMNlsInfo::nativeInitCultureData already");
+ Debug.Assert(this.sRealName != null, "[CultureData.ILANGUAGE] Expected this.sRealName to be populated by COMNlsInfo::nativeInitCultureData already");
this.iLanguage = LocaleNameToLCID(this.sRealName);
}
return this.iLanguage;
// All of our era names
internal String[] EraNames(int calendarId)
{
- Contract.Assert(calendarId > 0, "[CultureData.saEraNames] Expected Calendar.ID > 0");
+ Debug.Assert(calendarId > 0, "[CultureData.saEraNames] Expected Calendar.ID > 0");
return this.GetCalendar(calendarId).saEraNames;
}
internal String[] AbbrevEraNames(int calendarId)
{
- Contract.Assert(calendarId > 0, "[CultureData.saAbbrevEraNames] Expected Calendar.ID > 0");
+ Debug.Assert(calendarId > 0, "[CultureData.saAbbrevEraNames] Expected Calendar.ID > 0");
return this.GetCalendar(calendarId).saAbbrevEraNames;
}
internal String[] AbbreviatedEnglishEraNames(int calendarId)
{
- Contract.Assert(calendarId > 0, "[CultureData.saAbbrevEraNames] Expected Calendar.ID > 0");
+ Debug.Assert(calendarId > 0, "[CultureData.saAbbrevEraNames] Expected Calendar.ID > 0");
return this.GetCalendar(calendarId).saAbbrevEnglishEraNames;
}
// Time separator (derived from time format)
internal String TimeSeparator
{
- [System.Security.SecuritySafeCritical] // auto-generated
get
{
if (sTimeSeparator == null || UseUserOverride)
private static int IndexOfTimePart(string format, int startIndex, string timeParts)
{
- Contract.Assert(startIndex >= 0, "startIndex cannot be negative");
- Contract.Assert(timeParts.IndexOfAny(new char[] { '\'', '\\' }) == -1, "timeParts cannot include quote characters");
+ Debug.Assert(startIndex >= 0, "startIndex cannot be negative");
+ Debug.Assert(timeParts.IndexOfAny(new char[] { '\'', '\\' }) == -1, "timeParts cannot include quote characters");
bool inQuote = false;
for (int i = startIndex; i < format.Length; ++i)
{
return -1;
}
- [System.Security.SecurityCritical]
string DoGetLocaleInfo(uint lctype)
{
- Contract.Assert(this.sWindowsName != null, "[CultureData.DoGetLocaleInfo] Expected this.sWindowsName to be populated by COMNlsInfo::nativeInitCultureData already");
+ Debug.Assert(this.sWindowsName != null, "[CultureData.DoGetLocaleInfo] Expected this.sWindowsName to be populated by COMNlsInfo::nativeInitCultureData already");
return DoGetLocaleInfo(this.sWindowsName, lctype);
}
// For LOCALE_SPARENT we need the option of using the "real" name (forcing neutral names) instead of the
// "windows" name, which can be specific for downlevel (< windows 7) os's.
- [System.Security.SecurityCritical] // auto-generated
string DoGetLocaleInfo(string localeName, uint lctype)
{
// Fix lctype if we don't want overrides
}
// Ask OS for data
- Contract.Assert(localeName != null, "[CultureData.DoGetLocaleInfo] Expected localeName to be not be null");
+ Debug.Assert(localeName != null, "[CultureData.DoGetLocaleInfo] Expected localeName to be not be null");
string result = CultureInfo.nativeGetLocaleInfoEx(localeName, lctype);
if (result == null)
{
// Ask OS for data, note that we presume it returns success, so we have to know that
// sWindowsName is valid before calling.
- Contract.Assert(this.sWindowsName != null, "[CultureData.DoGetLocaleInfoInt] Expected this.sWindowsName to be populated by COMNlsInfo::nativeInitCultureData already");
+ Debug.Assert(this.sWindowsName != null, "[CultureData.DoGetLocaleInfoInt] Expected this.sWindowsName to be populated by COMNlsInfo::nativeInitCultureData already");
int result = CultureInfo.nativeGetLocaleInfoExInt(this.sWindowsName, lctype);
return result;
String[] DoEnumTimeFormats()
{
// Note that this gets overrides for us all the time
- Contract.Assert(this.sWindowsName != null, "[CultureData.DoEnumTimeFormats] Expected this.sWindowsName to be populated by COMNlsInfo::nativeInitCultureData already");
+ Debug.Assert(this.sWindowsName != null, "[CultureData.DoEnumTimeFormats] Expected this.sWindowsName to be populated by COMNlsInfo::nativeInitCultureData already");
String[] result = ReescapeWin32Strings(nativeEnumTimeFormats(this.sWindowsName, 0, UseUserOverride));
return result;
String[] DoEnumShortTimeFormats()
{
// Note that this gets overrides for us all the time
- Contract.Assert(this.sWindowsName != null, "[CultureData.DoEnumShortTimeFormats] Expected this.sWindowsName to be populated by COMNlsInfo::nativeInitCultureData already");
+ Debug.Assert(this.sWindowsName != null, "[CultureData.DoEnumShortTimeFormats] Expected this.sWindowsName to be populated by COMNlsInfo::nativeInitCultureData already");
String[] result = ReescapeWin32Strings(nativeEnumTimeFormats(this.sWindowsName, TIME_NOSECONDS, UseUserOverride));
return result;
// not affected by the Calendar property in DTFI.
//
////////////////////////////////////////////////////////////////////////////
- [System.Security.SecurityCritical] // auto-generated
internal void GetNFIValues(NumberFormatInfo nfi)
{
if (this.IsInvariantCulture)
//
// Ask native side for our data.
//
- Contract.Assert(this.sWindowsName != null, "[CultureData.GetNFIValues] Expected this.sWindowsName to be populated by COMNlsInfo::nativeInitCultureData already");
+ Debug.Assert(this.sWindowsName != null, "[CultureData.GetNFIValues] Expected this.sWindowsName to be populated by COMNlsInfo::nativeInitCultureData already");
CultureData.nativeGetNumberFormatInfoValues(this.sWindowsName, nfi, UseUserOverride);
}
{
nfi.currencyDecimalSeparator = nfi.numberDecimalSeparator;
}
-
-#if !FEATURE_CORECLR
- if ((932 == this.IDEFAULTANSICODEPAGE) ||
- (949 == this.IDEFAULTANSICODEPAGE))
- {
- // Legacy behavior for cultures that use Japanese/Korean default ANSI code pages
- // Note that this is a code point, not a character. On Japanese/Korean machines this
- // will be rendered as their currency symbol, not rendered as a "\"
- nfi.ansiCurrencySymbol = "\x5c";
- }
-#endif // !FEATURE_CORECLR
}
static private int ConvertFirstDayOfWeekMonToSun(int iTemp)
internal const uint TIME_NOSECONDS = 0x00000002; // Don't use seconds (get short time format for enumtimeformats on win7+)
// Get our initial minimal culture data (name, parent, etc.)
- [System.Security.SecuritySafeCritical] // auto-generated
[MethodImplAttribute(MethodImplOptions.InternalCall)]
internal static extern bool nativeInitCultureData(CultureData cultureData);
// Grab the NumberFormatInfo data
- [System.Security.SecuritySafeCritical] // auto-generated
[MethodImplAttribute(MethodImplOptions.InternalCall)]
internal static extern bool nativeGetNumberFormatInfoValues(String localeName, NumberFormatInfo nfi, bool useUserOverride);
- [System.Security.SecuritySafeCritical] // auto-generated
[MethodImplAttribute(MethodImplOptions.InternalCall)]
private static extern String[] nativeEnumTimeFormats(String localeName, uint dwFlags, bool useUserOverride);
- [System.Security.SecurityCritical] // auto-generated
[SuppressUnmanagedCodeSecurityAttribute()]
[DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
internal static extern int nativeEnumCultureNames(int cultureTypes, ObjectHandleOnStack retStringArray);
using System.Security.Permissions;
using System.Reflection;
using Microsoft.Win32;
+ using System.Diagnostics;
using System.Diagnostics.Contracts;
using System.Resources;
internal bool m_isReadOnly;
internal CompareInfo compareInfo;
internal TextInfo textInfo;
- // Not serialized for now since we only build it privately for use in the CARIB (so rebuilding is OK)
-#if !FEATURE_CORECLR
- [NonSerialized]internal RegionInfo regionInfo;
-#endif
internal NumberFormatInfo numInfo;
internal DateTimeFormatInfo dateTimeInfo;
internal Calendar calendar;
#if FEATURE_LEAK_CULTURE_INFO
[NonSerialized]private bool m_isSafeCrossDomain;
[NonSerialized]private int m_createdDomainID;
-#endif // !FEATURE_CORECLR
+#endif // !FEATURE_LEAK_CULTURE_INFO
[NonSerialized]private CultureInfo m_consoleFallbackCulture;
// Names are confusing. Here are 3 names we have:
#if FEATURE_APPX
// When running under AppX, we use this to get some information about the language list
- [SecurityCritical]
private static volatile WindowsRuntimeResourceManagerBase s_WindowsRuntimeResourceManager;
[ThreadStatic]
return true;
}
- [System.Security.SecuritySafeCritical] // auto-generated
static CultureInfo InitUserDefaultCulture()
{
String strDefault = GetDefaultLocaleName(LOCALE_USER_DEFAULT);
}
#if FEATURE_APPX
- [SecuritySafeCritical]
internal static CultureInfo GetCultureInfoForUserPreferredLanguageInAppX()
{
// If a call to GetCultureInfoForUserPreferredLanguageInAppX() generated a recursive
return toReturn;
}
- [SecuritySafeCritical]
internal static bool SetCultureInfoForUserPreferredLanguageInAppX(CultureInfo ci)
{
// If running within a compilation process (mscorsvw.exe, for example), it is illegal to
// e.g. for es-ES_tradnl: v2 puts es-ES in m_name; v4 puts es-ES_tradnl
if (m_name == null || IsAlternateSortLcid(cultureID))
{
- Contract.Assert(cultureID >=0, "[CultureInfo.OnDeserialized] cultureID >= 0");
+ Debug.Assert(cultureID >=0, "[CultureInfo.OnDeserialized] cultureID >= 0");
InitializeFromCultureId(cultureID, m_useUserOverride);
}
else
{
#endif
- Contract.Assert(m_name != null, "[CultureInfo.OnDeserialized] m_name != null");
+ Debug.Assert(m_name != null, "[CultureInfo.OnDeserialized] m_name != null");
this.m_cultureData = CultureData.GetCultureData(m_name, m_useUserOverride);
if (this.m_cultureData == null)
// For Silverlight, the answer is always no.
internal bool IsSafeCrossDomain {
get {
- Contract.Assert(m_createdDomainID != 0, "[CultureInfo.IsSafeCrossDomain] m_createdDomainID != 0");
+ Debug.Assert(m_createdDomainID != 0, "[CultureInfo.IsSafeCrossDomain] m_createdDomainID != 0");
return m_isSafeCrossDomain;
}
}
internal int CreatedDomainID {
get {
- Contract.Assert(m_createdDomainID != 0, "[CultureInfo.CreatedDomain] m_createdDomainID != 0");
+ Debug.Assert(m_createdDomainID != 0, "[CultureInfo.CreatedDomain] m_createdDomainID != 0");
return m_createdDomainID;
}
}
}
internal static bool VerifyCultureName(CultureInfo culture, bool throwException) {
- Contract.Assert(culture!=null, "[CultureInfo.VerifyCultureName]culture!=null");
+ Debug.Assert(culture!=null, "[CultureInfo.VerifyCultureName]culture!=null");
//If we have an instance of one of our CultureInfos, the user can't have changed the
//name and we know that all names are valid in files.
get {
Contract.Ensures(Contract.Result<CultureInfo>() != null);
-#if !FEATURE_CORECLR
- return Thread.CurrentThread.CurrentCulture;
-#else
// In the case of CoreCLR, Thread.m_CurrentCulture and
// Thread.m_CurrentUICulture are thread static so as not to let
// CultureInfo objects leak across AppDomain boundaries. The
s_DefaultThreadCurrentCulture ??
s_userDefaultCulture ??
UserDefaultCulture;
-#endif
}
set {
get {
Contract.Ensures(Contract.Result<CultureInfo>() != null);
-#if !FEATURE_CORECLR
- return Thread.CurrentThread.CurrentUICulture;
-#else
// In the case of CoreCLR, Thread.m_CurrentCulture and
// Thread.m_CurrentUICulture are thread static so as not to let
// CultureInfo objects leak across AppDomain boundaries. The
s_DefaultThreadCurrentUICulture ??
s_userDefaultUICulture ??
UserDefaultUICulture;
-#endif
}
set {
return s_DefaultThreadCurrentCulture;
}
- [System.Security.SecuritySafeCritical] // auto-generated
-#pragma warning disable 618
- [SecurityPermission(SecurityAction.Demand, ControlThread = true)]
-#pragma warning restore 618
set {
// If you add pre-conditions to this method, check to see if you also need to
return s_DefaultThreadCurrentUICulture;
}
- [System.Security.SecuritySafeCritical] // auto-generated
-#pragma warning disable 618
- [SecurityPermission(SecurityAction.Demand, ControlThread = true)]
-#pragma warning restore 618
set {
//If they're trying to use a Culture with a name that we can't use in resource lookup,
public virtual CultureInfo Parent
{
- [System.Security.SecuritySafeCritical] // auto-generated
get
{
Contract.Ensures(Contract.Result<CultureInfo>() != null);
////////////////////////////////////////////////////////////////////////
public virtual String DisplayName
{
- [System.Security.SecuritySafeCritical] // auto-generated
get
{
Contract.Ensures(Contract.Result<String>() != null);
- Contract.Assert(m_name != null, "[CultureInfo.DisplayName]Always expect m_name to be set");
+ Debug.Assert(m_name != null, "[CultureInfo.DisplayName]Always expect m_name to be set");
return m_cultureData.SLOCALIZEDDISPLAYNAME;
}
//
////////////////////////////////////////////////////////////////////////
public virtual String NativeName {
- [System.Security.SecuritySafeCritical] // auto-generated
get {
Contract.Ensures(Contract.Result<String>() != null);
return (this.m_cultureData.SNATIVEDISPLAYNAME);
//
////////////////////////////////////////////////////////////////////////
public virtual String EnglishName {
- [System.Security.SecuritySafeCritical] // auto-generated
get {
Contract.Ensures(Contract.Result<String>() != null);
return (this.m_cultureData.SENGDISPLAYNAME);
// ie: en
public virtual String TwoLetterISOLanguageName {
- [System.Security.SecuritySafeCritical] // auto-generated
get {
Contract.Ensures(Contract.Result<String>() != null);
return (this.m_cultureData.SISO639LANGNAME);
// ie: eng
public virtual String ThreeLetterISOLanguageName {
- [System.Security.SecuritySafeCritical] // auto-generated
get {
Contract.Ensures(Contract.Result<String>() != null);
return (this.m_cultureData.SISO639LANGNAME2);
//
////////////////////////////////////////////////////////////////////////
public virtual String ThreeLetterWindowsLanguageName {
- [System.Security.SecuritySafeCritical] // auto-generated
get {
Contract.Ensures(Contract.Result<String>() != null);
return (this.m_cultureData.SABBREVLANGNAME);
}
}
-#if !FEATURE_CORECLR
- ////////////////////////////////////////////////////////////////////////
- //
- // RegionInfo
- //
- // Gets the RegionInfo for this culture.
- //
- ////////////////////////////////////////////////////////////////////////
- private RegionInfo Region
- {
- get
- {
- if (regionInfo==null)
- {
- // Make a new regionInfo
- RegionInfo tempRegionInfo = new RegionInfo(this.m_cultureData);
- regionInfo = tempRegionInfo;
- }
- return (regionInfo);
- }
- }
-#endif // FEATURE_CORECLR
-
-
-
////////////////////////////////////////////////////////////////////////
//
// TextInfo
{
Contract.Ensures(Contract.Result<String>() != null);
- Contract.Assert(m_name != null, "[CultureInfo.ToString]Always expect m_name to be set");
+ Debug.Assert(m_name != null, "[CultureInfo.ToString]Always expect m_name to be set");
return m_name;
}
}
}
-
-
public void ClearCachedData() {
s_userDefaultUICulture = null;
s_userDefaultCulture = null;
RegionInfo.s_currentRegionInfo = null;
-#if !FEATURE_CORECLR // System.TimeZone does not exist in CoreCLR
+#pragma warning disable CS0618
TimeZone.ResetTimeZone();
-#endif // FEATURE_CORECLR
+#pragma warning restore CS0618
TimeZoneInfo.ClearCachedData();
+
// Delete the cached cultures.
s_LcidCachedCultures = null;
s_NameCachedCultures = null;
//This function exists as a shortcut to prevent us from loading all of the non-gregorian
//calendars unless they're required.
internal static Calendar GetCalendarInstanceRare(int calType) {
- Contract.Assert(calType!=Calendar.CAL_GREGORIAN, "calType!=Calendar.CAL_GREGORIAN");
+ Debug.Assert(calType!=Calendar.CAL_GREGORIAN, "calType!=Calendar.CAL_GREGORIAN");
switch (calType) {
case Calendar.CAL_GREGORIAN_US: // Gregorian (U.S.) calendar
get {
Contract.Ensures(Contract.Result<Calendar>() != null);
if (calendar == null) {
- Contract.Assert(this.m_cultureData.CalendarIds.Length > 0, "this.m_cultureData.CalendarIds.Length > 0");
+ Debug.Assert(this.m_cultureData.CalendarIds.Length > 0, "this.m_cultureData.CalendarIds.Length > 0");
// Get the default calendar for this culture. Note that the value can be
// from registry if this is a user default culture.
Calendar newObj = this.m_cultureData.DefaultCalendar;
}
}
- [System.Security.SecuritySafeCritical] // auto-generated
[System.Runtime.InteropServices.ComVisible(false)]
public CultureInfo GetConsoleFallbackUICulture()
{
//
// Get Locale Info Ex calls. So we don't have to muck with the different int/string return types we declared two of these:
- [System.Security.SecurityCritical] // auto-generated
[MethodImplAttribute(MethodImplOptions.InternalCall)]
internal static extern String nativeGetLocaleInfoEx(String localeName, uint field);
- [System.Security.SecuritySafeCritical] // auto-generated
[MethodImplAttribute(MethodImplOptions.InternalCall)]
internal static extern int nativeGetLocaleInfoExInt(String localeName, uint field);
- [System.Security.SecurityCritical] // auto-generated
[MethodImplAttribute(MethodImplOptions.InternalCall)]
internal static extern bool nativeSetThreadLocale(String localeName);
- [System.Security.SecurityCritical]
private static String GetDefaultLocaleName(int localeType)
{
- Contract.Assert(localeType == LOCALE_USER_DEFAULT || localeType == LOCALE_SYSTEM_DEFAULT, "[CultureInfo.GetDefaultLocaleName] localeType must be LOCALE_USER_DEFAULT or LOCALE_SYSTEM_DEFAULT");
+ Debug.Assert(localeType == LOCALE_USER_DEFAULT || localeType == LOCALE_SYSTEM_DEFAULT, "[CultureInfo.GetDefaultLocaleName] localeType must be LOCALE_USER_DEFAULT or LOCALE_SYSTEM_DEFAULT");
string localeName = null;
if(InternalGetDefaultLocaleName(localeType, JitHelpers.GetStringHandleOnStack(ref localeName)))
}
// Get the default locale name
- [System.Security.SecurityCritical] // auto-generated
[SuppressUnmanagedCodeSecurity]
[DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
[return: MarshalAs(UnmanagedType.Bool)]
private static extern bool InternalGetDefaultLocaleName(int localetype, StringHandleOnStack localeString);
- [System.Security.SecuritySafeCritical] // auto-generated
private static String GetUserDefaultUILanguage()
{
string userDefaultUiLanguage = null;
}
// Get the user's default UI language, return locale name
- [System.Security.SecurityCritical] // auto-generated
[SuppressUnmanagedCodeSecurity]
[DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
[return: MarshalAs(UnmanagedType.Bool)]
private static extern bool InternalGetUserDefaultUILanguage(StringHandleOnStack userDefaultUiLanguage);
- [System.Security.SecuritySafeCritical] // auto-generated
private static String GetSystemDefaultUILanguage()
{
string systemDefaultUiLanguage = null;
}
- [System.Security.SecurityCritical] // auto-generated
[MethodImplAttribute(MethodImplOptions.InternalCall)]
[SuppressUnmanagedCodeSecurity]
[DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
[return: MarshalAs(UnmanagedType.Bool)]
private static extern bool InternalGetSystemDefaultUILanguage(StringHandleOnStack systemDefaultUiLanguage);
-// Added but disabled from desktop in .NET 4.0, stayed disabled in .NET 4.5
-#if FEATURE_CORECLR
- [System.Security.SecurityCritical] // auto-generated
[MethodImplAttribute(MethodImplOptions.InternalCall)]
internal static extern String[] nativeGetResourceFallbackArray();
-#endif
}
}
m_invalidCultureName = (string) info.GetValue("InvalidCultureName", typeof(string));
}
- [System.Security.SecurityCritical] // auto-generated_required
public override void GetObjectData(SerializationInfo info, StreamingContext context) {
if (info==null) {
throw new ArgumentNullException(nameof(info));
using System.Runtime.InteropServices;
using System.Runtime.Versioning;
using System.Security;
+ using System.Diagnostics;
using System.Diagnostics.Contracts;
/*
//
////////////////////////////////////////////////////////////////////////////
internal static void FormatDigits(StringBuilder outputBuffer, int value, int len) {
- Contract.Assert(value >= 0, "DateTimeFormat.FormatDigits(): value >= 0");
+ Debug.Assert(value >= 0, "DateTimeFormat.FormatDigits(): value >= 0");
FormatDigits(outputBuffer, value, len, false);
}
- [System.Security.SecuritySafeCritical] // auto-generated
internal unsafe static void FormatDigits(StringBuilder outputBuffer, int value, int len, bool overrideLengthLimit) {
- Contract.Assert(value >= 0, "DateTimeFormat.FormatDigits(): value >= 0");
+ Debug.Assert(value >= 0, "DateTimeFormat.FormatDigits(): value >= 0");
// Limit the use of this function to be two-digits, so that we have the same behavior
// as RTM bits.
private static String FormatDayOfWeek(int dayOfWeek, int repeat, DateTimeFormatInfo dtfi)
{
- Contract.Assert(dayOfWeek >= 0 && dayOfWeek <= 6, "dayOfWeek >= 0 && dayOfWeek <= 6");
+ Debug.Assert(dayOfWeek >= 0 && dayOfWeek <= 6, "dayOfWeek >= 0 && dayOfWeek <= 6");
if (repeat == 3)
{
return (dtfi.GetAbbreviatedDayName((DayOfWeek)dayOfWeek));
private static String FormatMonth(int month, int repeatCount, DateTimeFormatInfo dtfi)
{
- Contract.Assert(month >=1 && month <= 12, "month >=1 && month <= 12");
+ Debug.Assert(month >=1 && month <= 12, "month >=1 && month <= 12");
if (repeatCount == 3)
{
return (dtfi.GetAbbreviatedMonthName(month));
*/
private static String FormatHebrewMonthName(DateTime time, int month, int repeatCount, DateTimeFormatInfo dtfi)
{
- Contract.Assert(repeatCount != 3 || repeatCount != 4, "repeateCount should be 3 or 4");
+ Debug.Assert(repeatCount != 3 || repeatCount != 4, "repeateCount should be 3 or 4");
if (dtfi.Calendar.IsLeapYear(dtfi.Calendar.GetYear(time))) {
// This month is in a leap year
return (dtfi.internalGetMonthName(month, MonthNameStyles.LeapYear, (repeatCount == 3)));
// accurate than the system's current offset because of daylight saving time.
offset = TimeZoneInfo.GetLocalUtcOffset(DateTime.Now, TimeZoneInfoOptions.NoThrowOnInvalidTime);
} else if (dateTime.Kind == DateTimeKind.Utc) {
-#if FEATURE_CORECLR
offset = TimeSpan.Zero;
-#else // FEATURE_CORECLR
- // This code path points to a bug in user code. It would make sense to return a 0 offset in this case.
- // However, because it was only possible to detect this in Whidbey, there is user code that takes a
- // dependency on being serialize a UTC DateTime using the 'z' format, and it will work almost all the
- // time if it is offset by an incorrect conversion to local time when parsed. Therefore, we need to
- // explicitly emit the local time offset, which we can do by removing the UTC flag.
- InvalidFormatForUtc(format, dateTime);
- dateTime = DateTime.SpecifyKind(dateTime, DateTimeKind.Local);
- offset = TimeZoneInfo.GetLocalUtcOffset(dateTime, TimeZoneInfoOptions.NoThrowOnInvalidTime);
-#endif // FEATURE_CORECLR
} else {
offset = TimeZoneInfo.GetLocalUtcOffset(dateTime, TimeZoneInfoOptions.NoThrowOnInvalidTime);
}
}
if (offset >= TimeSpan.Zero) {
- result.Append('+');
+ result.Append('+');
}
else {
result.Append('-');
index++;
}
- Contract.Assert(val == 0, "DateTimeFormat.AppendNumber(): digits less than size of val");
+ Debug.Assert(val == 0, "DateTimeFormat.AppendNumber(): digits less than size of val");
}
internal static String[] GetAllDateTimes(DateTime dateTime, char format, DateTimeFormatInfo dtfi)
// This is an MDA for cases when the user is using a local format with
// a Utc DateTime.
- [System.Security.SecuritySafeCritical] // auto-generated
internal static void InvalidFormatForUtc(String format, DateTime dateTime) {
#if MDA_SUPPORTED
Mda.DateTimeInvalidLocalFormat();
using System.Runtime.InteropServices;
using System.Runtime.Versioning;
using System.Text;
+ using System.Diagnostics;
using System.Diagnostics.Contracts;
//
private String LanguageName
{
- [System.Security.SecurityCritical] // auto-generated
get
{
if (m_langName == null)
{
// Get the abbreviated day names for our current calendar
this.abbreviatedDayNames = this.m_cultureData.AbbreviatedDayNames(Calendar.ID);
- Contract.Assert(this.abbreviatedDayNames.Length == 7, "[DateTimeFormatInfo.GetAbbreviatedDayOfWeekNames] Expected 7 day names in a week");
+ Debug.Assert(this.abbreviatedDayNames.Length == 7, "[DateTimeFormatInfo.GetAbbreviatedDayOfWeekNames] Expected 7 day names in a week");
}
return (this.abbreviatedDayNames);
}
{
// Get the super short day names for our current calendar
this.m_superShortDayNames = this.m_cultureData.SuperShortDayNames(Calendar.ID);
- Contract.Assert(this.m_superShortDayNames.Length == 7, "[DateTimeFormatInfo.internalGetSuperShortDayNames] Expected 7 day names in a week");
+ Debug.Assert(this.m_superShortDayNames.Length == 7, "[DateTimeFormatInfo.internalGetSuperShortDayNames] Expected 7 day names in a week");
}
return (this.m_superShortDayNames);
}
{
// Get the day names for our current calendar
this.dayNames = this.m_cultureData.DayNames(Calendar.ID);
- Contract.Assert(this.dayNames.Length == 7, "[DateTimeFormatInfo.GetDayOfWeekNames] Expected 7 day names in a week");
+ Debug.Assert(this.dayNames.Length == 7, "[DateTimeFormatInfo.GetDayOfWeekNames] Expected 7 day names in a week");
}
return (this.dayNames);
}
{
// Get the month names for our current calendar
this.abbreviatedMonthNames = this.m_cultureData.AbbreviatedMonthNames(Calendar.ID);
- Contract.Assert(this.abbreviatedMonthNames.Length == 12 || this.abbreviatedMonthNames.Length == 13,
+ Debug.Assert(this.abbreviatedMonthNames.Length == 12 || this.abbreviatedMonthNames.Length == 13,
"[DateTimeFormatInfo.GetAbbreviatedMonthNames] Expected 12 or 13 month names in a year");
}
return (this.abbreviatedMonthNames);
{
// Get the month names for our current calendar
this.monthNames = this.m_cultureData.MonthNames(Calendar.ID);
- Contract.Assert(this.monthNames.Length == 12 || this.monthNames.Length == 13,
+ Debug.Assert(this.monthNames.Length == 12 || this.monthNames.Length == 13,
"[DateTimeFormatInfo.GetMonthNames] Expected 12 or 13 month names in a year");
}
// m_isDefaultCalendar is set in the setter of Calendar below.
this.Calendar = cal;
}
-
-#if !FEATURE_CORECLR
- [System.Security.SecuritySafeCritical]
-#endif
private void InitializeOverridableProperties(CultureData cultureData, int calendarID)
{
// Silverlight 2.0 never took a snapshot of the user's overridable properties
// This has a substantial performance impact so skip when CoreCLR
Contract.Requires(cultureData != null);
- Contract.Assert(calendarID > 0, "[DateTimeFormatInfo.Populate] Expected Calendar.ID > 0");
+ Debug.Assert(calendarID > 0, "[DateTimeFormatInfo.Populate] Expected Calendar.ID > 0");
if (this.firstDayOfWeek == -1) { this.firstDayOfWeek = cultureData.IFIRSTDAYOFWEEK; }
if (this.calendarWeekRule == -1) { this.calendarWeekRule = cultureData.IFIRSTWEEKOFYEAR; }
if (this.dateSeparator == null) { this.dateSeparator = cultureData.DateSeparator(calendarID); }
this.allLongTimePatterns = this.m_cultureData.LongTimes;
- Contract.Assert(this.allLongTimePatterns.Length > 0, "[DateTimeFormatInfo.Populate] Expected some long time patterns");
+ Debug.Assert(this.allLongTimePatterns.Length > 0, "[DateTimeFormatInfo.Populate] Expected some long time patterns");
this.allShortTimePatterns = this.m_cultureData.ShortTimes;
- Contract.Assert(this.allShortTimePatterns.Length > 0, "[DateTimeFormatInfo.Populate] Expected some short time patterns");
+ Debug.Assert(this.allShortTimePatterns.Length > 0, "[DateTimeFormatInfo.Populate] Expected some short time patterns");
this.allLongDatePatterns = cultureData.LongDates(calendarID);
- Contract.Assert(this.allLongDatePatterns.Length > 0, "[DateTimeFormatInfo.Populate] Expected some long date patterns");
+ Debug.Assert(this.allLongDatePatterns.Length > 0, "[DateTimeFormatInfo.Populate] Expected some long date patterns");
this.allShortDatePatterns = cultureData.ShortDates(calendarID);
- Contract.Assert(this.allShortDatePatterns.Length > 0, "[DateTimeFormatInfo.Populate] Expected some short date patterns");
+ Debug.Assert(this.allShortDatePatterns.Length > 0, "[DateTimeFormatInfo.Populate] Expected some short date patterns");
this.allYearMonthPatterns = cultureData.YearMonths(calendarID);
- Contract.Assert(this.allYearMonthPatterns.Length > 0, "[DateTimeFormatInfo.Populate] Expected some year month patterns");
+ Debug.Assert(this.allYearMonthPatterns.Length > 0, "[DateTimeFormatInfo.Populate] Expected some year month patterns");
}
#region Serialization
// make sure the m_name is initialized.
m_name = this.CultureName;
-#if !FEATURE_CORECLR
- if (s_calendarNativeNames == null)
- s_calendarNativeNames = new Hashtable();
-#endif // FEATURE_CORECLR
-
// Important to initialize these fields otherwise we may run into exception when deserializing on Whidbey
// because Whidbey try to initialize some of these fields using calendar data which could be null values
// and then we get exceptions. So we call the accessors to force the caches to get loaded.
public String AMDesignator
{
-#if FEATURE_CORECLR
- [System.Security.SecuritySafeCritical] // auto-generated
-#endif
get
{
-#if FEATURE_CORECLR
if (this.amDesignator == null)
{
this.amDesignator = this.m_cultureData.SAM1159;
}
-#endif
- Contract.Assert(this.amDesignator != null, "DateTimeFormatInfo.AMDesignator, amDesignator != null");
+
+ Debug.Assert(this.amDesignator != null, "DateTimeFormatInfo.AMDesignator, amDesignator != null");
return (this.amDesignator);
}
get {
Contract.Ensures(Contract.Result<Calendar>() != null);
- Contract.Assert(this.calendar != null, "DateTimeFormatInfo.Calendar: calendar != null");
+ Debug.Assert(this.calendar != null, "DateTimeFormatInfo.Calendar: calendar != null");
return (this.calendar);
}
{
if (this.m_abbrevEnglishEraNames == null)
{
- Contract.Assert(Calendar.ID > 0, "[DateTimeFormatInfo.AbbreviatedEnglishEraNames] Expected Calendar.ID > 0");
+ Debug.Assert(Calendar.ID > 0, "[DateTimeFormatInfo.AbbreviatedEnglishEraNames] Expected Calendar.ID > 0");
this.m_abbrevEnglishEraNames = this.m_cultureData.AbbreviatedEnglishEraNames(Calendar.ID);
}
return (this.m_abbrevEnglishEraNames);
{
get
{
-#if FEATURE_CORECLR
if (this.dateSeparator == null)
{
this.dateSeparator = this.m_cultureData.DateSeparator(Calendar.ID);
}
-#endif
- Contract.Assert(this.dateSeparator != null, "DateTimeFormatInfo.DateSeparator, dateSeparator != null");
+
+ Debug.Assert(this.dateSeparator != null, "DateTimeFormatInfo.DateSeparator, dateSeparator != null");
return (this.dateSeparator);
}
{
get
{
-#if FEATURE_CORECLR
if (this.firstDayOfWeek == -1)
{
this.firstDayOfWeek = this.m_cultureData.IFIRSTDAYOFWEEK;
}
-#endif
- Contract.Assert(this.firstDayOfWeek != -1, "DateTimeFormatInfo.FirstDayOfWeek, firstDayOfWeek != -1");
-
+
+ Debug.Assert(this.firstDayOfWeek != -1, "DateTimeFormatInfo.FirstDayOfWeek, firstDayOfWeek != -1");
return ((DayOfWeek)this.firstDayOfWeek);
}
{
get
{
-#if FEATURE_CORECLR
if (this.calendarWeekRule == -1)
{
this.calendarWeekRule = this.m_cultureData.IFIRSTWEEKOFYEAR;
}
-#endif
- Contract.Assert(this.calendarWeekRule != -1, "DateTimeFormatInfo.CalendarWeekRule, calendarWeekRule != -1");
+
+ Debug.Assert(this.calendarWeekRule != -1, "DateTimeFormatInfo.CalendarWeekRule, calendarWeekRule != -1");
return ((CalendarWeekRule)this.calendarWeekRule);
}
{
if (this.monthDayPattern == null)
{
- Contract.Assert(Calendar.ID > 0, "[DateTimeFormatInfo.MonthDayPattern] Expected calID > 0");
+ Debug.Assert(Calendar.ID > 0, "[DateTimeFormatInfo.MonthDayPattern] Expected calID > 0");
this.monthDayPattern = this.m_cultureData.MonthDay(Calendar.ID);
}
- Contract.Assert(this.monthDayPattern != null, "DateTimeFormatInfo.MonthDayPattern, monthDayPattern != null");
+ Debug.Assert(this.monthDayPattern != null, "DateTimeFormatInfo.MonthDayPattern, monthDayPattern != null");
return (this.monthDayPattern);
}
public String PMDesignator
{
-#if FEATURE_CORECLR
- [System.Security.SecuritySafeCritical] // auto-generated
-#endif
get
{
-#if FEATURE_CORECLR
if (this.pmDesignator == null)
{
this.pmDesignator = this.m_cultureData.SPM2359;
}
-#endif
- Contract.Assert(this.pmDesignator != null, "DateTimeFormatInfo.PMDesignator, pmDesignator != null");
+
+ Debug.Assert(this.pmDesignator != null, "DateTimeFormatInfo.PMDesignator, pmDesignator != null");
return (this.pmDesignator);
}
{
get
{
-#if FEATURE_CORECLR
if (timeSeparator == null)
{
timeSeparator = this.m_cultureData.TimeSeparator;
}
-#endif
- Contract.Assert(this.timeSeparator != null, "DateTimeFormatInfo.TimeSeparator, timeSeparator != null");
+
+ Debug.Assert(this.timeSeparator != null, "DateTimeFormatInfo.TimeSeparator, timeSeparator != null");
return (timeSeparator);
}
if (this.m_genitiveAbbreviatedMonthNames == null)
{
this.m_genitiveAbbreviatedMonthNames = this.m_cultureData.AbbreviatedGenitiveMonthNames(this.Calendar.ID);
- Contract.Assert(this.m_genitiveAbbreviatedMonthNames.Length == 13,
+ Debug.Assert(this.m_genitiveAbbreviatedMonthNames.Length == 13,
"[DateTimeFormatInfo.GetGenitiveMonthNames] Expected 13 abbreviated genitive month names in a year");
}
return (this.m_genitiveAbbreviatedMonthNames);
if (this.genitiveMonthNames == null)
{
this.genitiveMonthNames = this.m_cultureData.GenitiveMonthNames(this.Calendar.ID);
- Contract.Assert(this.genitiveMonthNames.Length == 13,
+ Debug.Assert(this.genitiveMonthNames.Length == 13,
"[DateTimeFormatInfo.GetGenitiveMonthNames] Expected 13 genitive month names in a year");
}
return (this.genitiveMonthNames);
internal String[] internalGetLeapYearMonthNames(/*bool abbreviated*/) {
if (this.leapYearMonthNames == null)
{
- Contract.Assert(Calendar.ID > 0, "[DateTimeFormatInfo.internalGetLeapYearMonthNames] Expected Calendar.ID > 0");
+ Debug.Assert(Calendar.ID > 0, "[DateTimeFormatInfo.internalGetLeapYearMonthNames] Expected Calendar.ID > 0");
this.leapYearMonthNames = this.m_cultureData.LeapYearMonthNames(Calendar.ID);
- Contract.Assert(this.leapYearMonthNames.Length == 13,
+ Debug.Assert(this.leapYearMonthNames.Length == 13,
"[DateTimeFormatInfo.internalGetLeapYearMonthNames] Expepcted 13 leap year month names");
}
return (leapYearMonthNames);
// The resulting [] can get returned to the calling app, so clone it.
private static string[] GetMergedPatterns(string [] patterns, string defaultPattern)
{
- Contract.Assert(patterns != null && patterns.Length > 0,
+ Debug.Assert(patterns != null && patterns.Length > 0,
"[DateTimeFormatInfo.GetMergedPatterns]Expected array of at least one pattern");
- Contract.Assert(defaultPattern != null,
+ Debug.Assert(defaultPattern != null,
"[DateTimeFormatInfo.GetMergedPatterns]Expected non null default string");
// If the default happens to be the first in the list just return (a cloned) copy
{
if (this.allYearMonthPatterns == null)
{
- Contract.Assert(Calendar.ID > 0, "[DateTimeFormatInfo.UnclonedYearMonthPatterns] Expected Calendar.ID > 0");
+ Debug.Assert(Calendar.ID > 0, "[DateTimeFormatInfo.UnclonedYearMonthPatterns] Expected Calendar.ID > 0");
this.allYearMonthPatterns = this.m_cultureData.YearMonths(this.Calendar.ID);
- Contract.Assert(this.allYearMonthPatterns.Length > 0,
+ Debug.Assert(this.allYearMonthPatterns.Length > 0,
"[DateTimeFormatInfo.UnclonedYearMonthPatterns] Expected some year month patterns");
}
{
if (allShortDatePatterns == null)
{
- Contract.Assert(Calendar.ID > 0, "[DateTimeFormatInfo.UnclonedShortDatePatterns] Expected Calendar.ID > 0");
+ Debug.Assert(Calendar.ID > 0, "[DateTimeFormatInfo.UnclonedShortDatePatterns] Expected Calendar.ID > 0");
this.allShortDatePatterns = this.m_cultureData.ShortDates(this.Calendar.ID);
- Contract.Assert(this.allShortDatePatterns.Length > 0,
+ Debug.Assert(this.allShortDatePatterns.Length > 0,
"[DateTimeFormatInfo.UnclonedShortDatePatterns] Expected some short date patterns");
}
{
if (allLongDatePatterns == null)
{
- Contract.Assert(Calendar.ID > 0, "[DateTimeFormatInfo.UnclonedLongDatePatterns] Expected Calendar.ID > 0");
+ Debug.Assert(Calendar.ID > 0, "[DateTimeFormatInfo.UnclonedLongDatePatterns] Expected Calendar.ID > 0");
this.allLongDatePatterns = this.m_cultureData.LongDates(this.Calendar.ID);
- Contract.Assert(this.allLongDatePatterns.Length > 0,
+ Debug.Assert(this.allLongDatePatterns.Length > 0,
"[DateTimeFormatInfo.UnclonedLongDatePatterns] Expected some long date patterns");
}
if (this.allShortTimePatterns == null)
{
this.allShortTimePatterns = this.m_cultureData.ShortTimes;
- Contract.Assert(this.allShortTimePatterns.Length > 0,
+ Debug.Assert(this.allShortTimePatterns.Length > 0,
"[DateTimeFormatInfo.UnclonedShortTimePatterns] Expected some short time patterns");
}
if (this.allLongTimePatterns == null)
{
this.allLongTimePatterns = this.m_cultureData.LongTimes;
- Contract.Assert(this.allLongTimePatterns.Length > 0,
+ Debug.Assert(this.allLongTimePatterns.Length > 0,
"[DateTimeFormatInfo.UnclonedLongTimePatterns] Expected some long time patterns");
}
formatFlags = DateTimeFormatFlags.NotInitialized;
}
- [System.Security.SecurityCritical] // auto-generated
internal TokenHashValue[] CreateTokenHashTable() {
TokenHashValue[] temp = m_dtfiTokenHash;
if (temp == null) {
} while (i < str.Value.Length && (state != HebrewNumberParsingState.FoundEndOfHebrewNumber));
// When we are here, we are either at the end of the string, or we find a valid Hebrew number.
- Contract.Assert(state == HebrewNumberParsingState.ContinueParsing || state == HebrewNumberParsingState.FoundEndOfHebrewNumber,
+ Debug.Assert(state == HebrewNumberParsingState.ContinueParsing || state == HebrewNumberParsingState.FoundEndOfHebrewNumber,
"Invalid returned state from HebrewNumber.ParseByChar()");
if (state != HebrewNumberParsingState.FoundEndOfHebrewNumber) {
return (ch >= '\x0590' && ch <= '\x05ff');
}
- [System.Security.SecurityCritical] // auto-generated
internal bool Tokenize(TokenType TokenMask, out TokenType tokenType, out int tokenValue, ref __DTString str) {
tokenType = TokenType.UnknownToken;
tokenValue = 0;
TokenHashValue value;
- Contract.Assert(str.Index < str.Value.Length, "DateTimeFormatInfo.Tokenize(): start < value.Length");
+ Debug.Assert(str.Index < str.Value.Length, "DateTimeFormatInfo.Tokenize(): start < value.Length");
char ch = str.m_current;
bool isLetter = Char.IsLetter(ch);
}
previousNode = temp;
} ;
- Contract.Assert(false, "The hashtable is full. This should not happen.");
+ Debug.Assert(false, "The hashtable is full. This should not happen.");
}
void InsertHash(TokenHashValue[] hashTable, String str, TokenType tokenType, int tokenValue) {
hashcode += hashProbe;
if (hashcode >= TOKEN_HASH_SIZE) hashcode -= TOKEN_HASH_SIZE;
} while (i < TOKEN_HASH_SIZE);
- Contract.Assert(false, "The hashtable is full. This should not happen.");
+ Debug.Assert(false, "The hashtable is full. This should not happen.");
}
} // class DateTimeFormatInfo
//
////////////////////////////////////////////////////////////////////////////
- #if FEATURE_CORECLR
- [System.Security.SecurityCritical] // auto-generated
- #endif
internal String[] GetDateWordsOfDTFI(DateTimeFormatInfo dtfi) {
// Enumarate all LongDatePatterns, and get the DateWords and scan for month postfix.
String[] datePatterns = dtfi.GetAllDateTimePatterns('D');
internal static MatchNumberDelegate m_hebrewNumberParser = new MatchNumberDelegate(DateTimeParse.MatchHebrewDigits);
-#if !FEATURE_CORECLR
- [SecuritySafeCritical]
- internal static bool GetAmPmParseFlag()
- {
- return DateTime.EnableAmPmParseAdjustment();
- }
-
- internal static bool enableAmPmParseAdjustment = GetAmPmParseFlag();
-#endif
-
internal static DateTime ParseExact(String s, String format, DateTimeFormatInfo dtfi, DateTimeStyles style) {
DateTimeResult result = new DateTimeResult(); // The buffer to store the parsing result.
result.Init();
return false;
}
- Contract.Assert(dtfi != null, "dtfi == null");
+ Debug.Assert(dtfi != null, "dtfi == null");
return DoStrictParse(s, format, style, dtfi, ref result);
}
return false;
}
- Contract.Assert(dtfi != null, "dtfi == null");
+ Debug.Assert(dtfi != null, "dtfi == null");
//
// Do a loop through the provided formats and see if we can parse succesfully in
// Wrong number of digits
return false;
}
- Contract.Assert(hourOffset >= 0 && hourOffset <= 99, "hourOffset >= 0 && hourOffset <= 99");
- Contract.Assert(minuteOffset >= 0 && minuteOffset <= 99, "minuteOffset >= 0 && minuteOffset <= 99");
+ Debug.Assert(hourOffset >= 0 && hourOffset <= 99, "hourOffset >= 0 && hourOffset <= 99");
+ Debug.Assert(minuteOffset >= 0 && minuteOffset <= 99, "minuteOffset >= 0 && minuteOffset <= 99");
if (minuteOffset < 0 || minuteOffset >= 60) {
return false;
}
// This is the lexer. Check the character at the current index, and put the found token in dtok and
// some raw date/time information in raw.
//
- [System.Security.SecuritySafeCritical] // auto-generated
private static Boolean Lex(DS dps, ref __DTString str, ref DateTimeToken dtok, ref DateTimeRawInfo raw, ref DateTimeResult result, ref DateTimeFormatInfo dtfi, DateTimeStyles styles)
{
raw.timeMark = (sep == TokenType.SEP_Am ? TM.AM : TM.PM);
dtok.dtt = DTT.NumAmpm;
// Fix AM/PM parsing case, e.g. "1/10 5 AM"
- if (dps == DS.D_NN
-#if !FEATURE_CORECLR
- && enableAmPmParseAdjustment
-#endif
- )
+ if (dps == DS.D_NN)
{
if (!ProcessTerminaltState(DS.DX_NN, ref result, ref styles, ref raw, dtfi))
{
return (false);
}
-#if !FEATURE_CORECLR
- // If DateTimeParseIgnorePunctuation is defined, we want to have the V1.1 behavior of just
- // ignoring any unrecognized punctuation and moving on to the next character
- if (Environment.GetCompatibilityFlag(CompatibilityFlag.DateTimeParseIgnorePunctuation) && ((result.flags & ParseFlags.CaptureOffset) == 0)) {
- str.GetNext();
- LexTraceExit("0210 (success)", dps);
- return true;
- }
-#endif // FEATURE_CORECLR
-
if ((str.m_current == '-' || str.m_current == '+') && ((result.flags & ParseFlags.TimeZoneUsed) == 0)) {
Int32 originalIndex = str.Index;
if (ParseTimeZone(ref str, ref result.timeZoneOffset)) {
else {
// Time zone parse attempt failed. Fall through to punctuation handling.
str.Index = originalIndex;
- }
+ }
}
// Visual Basic implements string to date conversions on top of DateTime.Parse:
//
if (VerifyValidPunctuation(ref str)) {
LexTraceExit("0230 (success)", dps);
- return true;
+ return true;
}
result.SetFailure(ParseFailureKind.Format, "Format_BadDateTime", null);
private static Boolean GetTimeOfNN(DateTimeFormatInfo dtfi, ref DateTimeResult result, ref DateTimeRawInfo raw)
{
- Contract.Assert(raw.numCount >= 2, "raw.numCount >= 2");
+ Debug.Assert(raw.numCount >= 2, "raw.numCount >= 2");
if ((result.flags & ParseFlags.HaveTime) != 0) {
// Multiple times in the input string
result.SetFailure(ParseFailureKind.Format, "Format_BadDateTime", null);
result.SetFailure(ParseFailureKind.Format, "Format_BadDateTime", null);
return false;
}
- Contract.Assert(raw.numCount >= 3, "raw.numCount >= 3");
+ Debug.Assert(raw.numCount >= 3, "raw.numCount >= 3");
result.Hour = raw.GetNumber(0);
result.Minute = raw.GetNumber(1);
result.Second = raw.GetNumber(2);
//
// This is the real method to do the parsing work.
//
- [System.Security.SecuritySafeCritical] // auto-generated
internal static bool TryParse(String s, DateTimeFormatInfo dtfi, DateTimeStyles styles, ref DateTimeResult result) {
if (s == null) {
result.SetFailure(ParseFailureKind.ArgumentNull, "ArgumentNull_String", null, nameof(s));
return false;
}
- Contract.Assert(dtfi != null, "dtfi == null");
+ Debug.Assert(dtfi != null, "dtfi == null");
#if _LOGGING
DTFITrace(dtfi);
// no adjustment is required in most cases
return DateTimeOffsetTimeZonePostProcessing(ref result, styles);
}
-#if FEATURE_CORECLR // on CoreCLR DateTime is also restricted to +- 14:00, just like DateTimeOffset
else {
Int64 offsetTicks = result.timeZoneOffset.Ticks;
-
+
// the DateTime offset must be within +- 14:00 hours.
if (offsetTicks < DateTimeOffset.MinOffset || offsetTicks > DateTimeOffset.MaxOffset) {
result.SetFailure(ParseFailureKind.Format, "Format_OffsetOutOfRange", null);
return false;
}
}
-#endif // FEATURE_CORECLR
// The flags AssumeUniveral and AssumeLocal only apply when the input does not have a time zone
if ((result.flags & ParseFlags.TimeZoneUsed) == 0) {
}
else {
// No time zone and no Assume flags, so DateTimeKind.Unspecified is fine
- Contract.Assert(result.parsedDate.Kind == DateTimeKind.Unspecified, "result.parsedDate.Kind == DateTimeKind.Unspecified");
+ Debug.Assert(result.parsedDate.Kind == DateTimeKind.Unspecified, "result.parsedDate.Kind == DateTimeKind.Unspecified");
return true;
}
}
}
internal static bool ParseDigits(ref __DTString str, int minDigitLen, int maxDigitLen, out int result) {
- Contract.Assert(minDigitLen > 0, "minDigitLen > 0");
- Contract.Assert(maxDigitLen < 9, "maxDigitLen < 9");
- Contract.Assert(minDigitLen <= maxDigitLen, "minDigitLen <= maxDigitLen");
+ Debug.Assert(minDigitLen > 0, "minDigitLen > 0");
+ Debug.Assert(maxDigitLen < 9, "maxDigitLen < 9");
+ Debug.Assert(minDigitLen <= maxDigitLen, "minDigitLen <= maxDigitLen");
result = 0;
int startingIndex = str.Index;
int tokenLength = 0;
case ParseFailureKind.FormatBadDateTimeCalendar:
return new FormatException(Environment.GetResourceString(result.failureMessageID, result.calendar));
default:
- Contract.Assert(false, "Unkown DateTimeParseFailure: " + result);
+ Debug.Assert(false, "Unkown DateTimeParseFailure: " + result);
return null;
}
}
internal bool Advance(int count) {
- Contract.Assert(Index + count <= len, "__DTString::Advance: Index + count <= len");
+ Debug.Assert(Index + count <= len, "__DTString::Advance: Index + count <= len");
Index += count;
if (Index < len) {
m_current = Value[Index];
// Used by DateTime.Parse() to get the next token.
- [System.Security.SecurityCritical] // auto-generated
internal void GetRegularToken(out TokenType tokenType, out int tokenValue, DateTimeFormatInfo dtfi) {
tokenValue = 0;
if (Index >= len) {
}
}
- [System.Security.SecurityCritical] // auto-generated
internal TokenType GetSeparatorToken(DateTimeFormatInfo dtfi, out int indexBeforeSeparator, out char charBeforeSeparator) {
indexBeforeSeparator = Index;
charBeforeSeparator = m_current;
// Get the current character.
//
internal char GetChar() {
- Contract.Assert(Index >= 0 && Index < len, "Index >= 0 && Index < len");
+ Debug.Assert(Index >= 0 && Index < len, "Index >= 0 && Index < len");
return (Value[Index]);
}
// Convert the current character to a digit, and return it.
//
internal int GetDigit() {
- Contract.Assert(Index >= 0 && Index < len, "Index >= 0 && Index < len");
- Contract.Assert(DateTimeParse.IsDigit(Value[Index]), "IsDigit(Value[Index])");
+ Debug.Assert(Index >= 0 && Index < len, "Index >= 0 && Index < len");
+ Debug.Assert(DateTimeParse.IsDigit(Value[Index]), "IsDigit(Value[Index])");
return (Value[Index] - '0');
}
return sub;
}
int number = ch - '0';
- Contract.Assert(number >= 0 && number <= 9, "number >= 0 && number <= 9");
+ Debug.Assert(number >= 0 && number <= 9, "number >= 0 && number <= 9");
sub.value = sub.value * 10 + number;
}
else {
}
internal void ConsumeSubString(DTSubString sub) {
- Contract.Assert(sub.index == Index, "sub.index == Index");
- Contract.Assert(sub.index + sub.length <= len, "sub.index + sub.length <= len");
+ Debug.Assert(sub.index == Index, "sub.index == Index");
+ Debug.Assert(sub.index + sub.length <= len, "sub.index + sub.length <= len");
Index = sub.index + sub.length;
if (Index < len) {
m_current = Value[Index];
//
internal
unsafe struct DateTimeRawInfo {
- [SecurityCritical]
private int* num;
internal int numCount;
internal int month;
internal bool timeZone;
- [System.Security.SecurityCritical] // auto-generated
internal void Init(int * numberBuffer) {
month = -1;
year = -1;
fraction = -1;
num = numberBuffer;
}
- [System.Security.SecuritySafeCritical] // auto-generated
internal unsafe void AddNumber(int value) {
num[numCount++] = value;
}
- [System.Security.SecuritySafeCritical] // auto-generated
internal unsafe int GetNumber(int index) {
return num[index];
}
internal String m_bodyName;
internal uint m_flags;
- [SecurityCritical]
unsafe internal CodePageDataItem(int dataIndex) {
m_dataIndex = dataIndex;
m_uiFamilyCodePage = EncodingTable.codePageDataPtr[dataIndex].uiFamilyCodePage;
m_flags = EncodingTable.codePageDataPtr[dataIndex].flags;
}
- [System.Security.SecurityCritical]
unsafe internal static String CreateString(sbyte* pStrings, uint index)
{
if (pStrings[0] == '|') // |str1|str2|str3
}
unsafe public String WebName {
- [System.Security.SecuritySafeCritical] // auto-generated
get {
if (m_webName==null) {
m_webName = CreateString(EncodingTable.codePageDataPtr[m_dataIndex].Names, 0);
}
unsafe public String HeaderName {
- [System.Security.SecuritySafeCritical] // auto-generated
get {
if (m_headerName==null) {
m_headerName = CreateString(EncodingTable.codePageDataPtr[m_dataIndex].Names, 1);
}
unsafe public String BodyName {
- [System.Security.SecuritySafeCritical] // auto-generated
get {
if (m_bodyName==null) {
m_bodyName = CreateString(EncodingTable.codePageDataPtr[m_dataIndex].Names, 2);
// See the LICENSE file in the project root for more information.
using System.Collections.Generic;
+using System.Diagnostics;
using System.Diagnostics.Contracts;
using System.Text;
break;
}
- Contract.Assert(item == null || item.CodePage == codepage, "item.CodePage needs to equal the specified codepage");
+ Debug.Assert(item == null || item.CodePage == codepage, "item.CodePage needs to equal the specified codepage");
return item;
}
#if DEBUG
static EncodingTable()
{
- Contract.Assert(
+ Debug.Assert(
s_encodingDataTable.Count == EncodingTableCapacity,
string.Format(CultureInfo.InvariantCulture,
"EncodingTable s_encodingDataTable's initial capacity (EncodingTableCapacity) is incorrect.{0}Expected (s_encodingDataTable.Count): {1}, Actual (EncodingTableCapacity): {2}",
//
// This points to a native data table which maps an encoding name to the correct code page.
//
- [SecurityCritical]
unsafe internal static InternalEncodingDataItem *encodingDataPtr = GetEncodingData();
//
// This points to a native data table which stores the properties for the code page, and
// the table is indexed by code page.
//
- [SecurityCritical]
unsafe internal static InternalCodePageDataItem *codePageDataPtr = GetCodePageData();
//
// This caches the mapping of an encoding name to a code page.
//
private static Hashtable hashByCodePage = Hashtable.Synchronized(new Hashtable());
- [System.Security.SecuritySafeCritical] // static constructors should be safe to call
static EncodingTable()
{
}
// Find the data item by binary searching the table that we have in native.
// nativeCompareOrdinalWC is an internal-only function.
- [System.Security.SecuritySafeCritical] // auto-generated
unsafe private static int internalGetCodePageFromName(String name) {
int left = 0;
int right = lastEncodingItem;
}
// Return a list of all EncodingInfo objects describing all of our encodings
- [System.Security.SecuritySafeCritical] // auto-generated
internal static unsafe EncodingInfo[] GetEncodings()
{
if (lastCodePageItem == 0)
return codePage;
}
- [System.Security.SecuritySafeCritical] // auto-generated
unsafe internal static CodePageDataItem GetCodePageDataItem(int codepage) {
CodePageDataItem dataItem;
return null;
}
- [System.Security.SecurityCritical] // auto-generated
[MethodImplAttribute(MethodImplOptions.InternalCall)]
private unsafe static extern InternalEncodingDataItem *GetEncodingData();
//
// Return the number of encoding data items.
//
- [System.Security.SecurityCritical] // auto-generated
[MethodImplAttribute(MethodImplOptions.InternalCall)]
private static extern int GetNumEncodingItems();
- [System.Security.SecurityCritical] // auto-generated
[MethodImplAttribute(MethodImplOptions.InternalCall)]
private unsafe static extern InternalCodePageDataItem* GetCodePageData();
- [System.Security.SecurityCritical] // auto-generated
[MethodImplAttribute(MethodImplOptions.InternalCall)]
internal unsafe static extern byte* nativeCreateOpenFileMapping(
String inSectionName, int inBytesToAllocate, out IntPtr mappedFileHandle);
[System.Runtime.InteropServices.StructLayout(LayoutKind.Sequential)]
internal unsafe struct InternalEncodingDataItem {
- [SecurityCritical]
internal sbyte * webName;
internal UInt16 codePage;
}
internal UInt16 codePage;
internal UInt16 uiFamilyCodePage;
internal uint flags;
- [SecurityCritical]
internal sbyte * Names;
}
using System.Runtime.ConstrainedExecution;
using System.Runtime.Versioning;
using System.IO;
+ using System.Diagnostics;
using System.Diagnostics.Contracts;
// Instance data members and instance methods.
//
// ----------------------------------------------------------------------------------------------------
- [System.Security.SecurityCritical] // auto-generated
internal unsafe static byte* GetGlobalizationResourceBytePtr(Assembly assembly, String tableName) {
- Contract.Assert(assembly != null, "assembly can not be null. This should be generally the "+System.CoreLib.Name+" assembly.");
- Contract.Assert(tableName != null, "table name can not be null");
+ Debug.Assert(assembly != null, "assembly can not be null. This should be generally the "+System.CoreLib.Name+" assembly.");
+ Debug.Assert(tableName != null, "table name can not be null");
Stream stream = assembly.GetManifestResourceStream(tableName);
UnmanagedMemoryStream bytesStream = stream as UnmanagedMemoryStream;
}
}
- Contract.Assert(
+ Debug.Assert(
false,
String.Format(
CultureInfo.CurrentCulture,
namespace System.Globalization {
using System;
using System.Text;
+ using System.Diagnostics;
using System.Diagnostics.Contracts;
////////////////////////////////////////////////////////////////////////////
// is true.
//
NumDays -= (long)(LunarMonthLen[hebrewYearType, lunarDate.month] - lunarDate.day);
- Contract.Assert(NumDays >= 1, "NumDays >= 1");
+ Debug.Assert(NumDays >= 1, "NumDays >= 1");
// If NumDays is 1, then we are done. Otherwise, find the correct Hebrew month
// and day.
int hebrewYearType = GetHebrewYearType(year, era);
CheckHebrewMonthValue(year, month, era);
- Contract.Assert(hebrewYearType>= 1 && hebrewYearType <= 6,
+ Debug.Assert(hebrewYearType>= 1 && hebrewYearType <= 6,
"hebrewYearType should be from 1 to 6, but now hebrewYearType = " + hebrewYearType + " for hebrew year " + year);
int monthDays = LunarMonthLen[hebrewYearType, month];
if (monthDays == 0) {
namespace System.Globalization {
using System;
using System.Text;
+ using System.Diagnostics;
using System.Diagnostics.Contracts;
////////////////////////////////////////////////////////////////////////////
Number -= 5000;
}
- Contract.Assert(Number > 0 && Number <= 999, "Number is out of range.");;
+ Debug.Assert(Number > 0 && Number <= 999, "Number is out of range.");;
//
// Get the Hundreds.
public int HijriAdjustment {
- [System.Security.SecuritySafeCritical] // auto-generated
get {
if (m_HijriAdvance == Int32.MinValue) {
// Never been set before. Use the system value from registry.
** "AddHijriDate+1" => Add +1 days to the current calculated Hijri date.
** "AddHijriDate+2" => Add +2 days to the current calculated Hijri date.
============================================================================*/
- [System.Security.SecurityCritical] // auto-generated
static int GetAdvanceHijriDate() {
#if FEATURE_WIN32_REGISTRY
using System.Text;
using System.Runtime.Versioning;
using System.Runtime.InteropServices;
+ using System.Diagnostics;
using System.Diagnostics.Contracts;
// IdnMapping class used to map names to Punycode
// Cannot be null terminated (normalization won't help us with this one, and
// may have returned false before checking the whole string above)
- Contract.Assert(unicode.Length >= 1, "[IdnMapping.GetAscii]Expected 0 length strings to fail before now.");
+ Debug.Assert(unicode.Length >= 1, "[IdnMapping.GetAscii]Expected 0 length strings to fail before now.");
if (unicode[unicode.Length - 1] <= 0x1f)
{
throw new ArgumentException(
}
- [System.Security.SecuritySafeCritical]
private String GetAsciiUsingOS(String unicode)
{
if (unicode.Length == 0)
}
- [System.Security.SecuritySafeCritical]
private string GetUnicodeUsingOS(string ascii)
{
uint flags = (uint)((AllowUnassigned ? IDN_ALLOW_UNASSIGNED : 0) | (UseStd3AsciiRules ? IDN_USE_STD3_ASCII_RULES : 0));
static char encode_digit(int d)
{
- Contract.Assert(d >= 0 && d < punycodeBase, "[IdnMapping.encode_digit]Expected 0 <= d < punycodeBase");
+ Debug.Assert(d >= 0 && d < punycodeBase, "[IdnMapping.encode_digit]Expected 0 <= d < punycodeBase");
// 26-35 map to ASCII 0-9
if (d > 25) return (char)(d - 26 + '0');
uint k;
delta = firsttime ? delta / damp : delta / 2;
- Contract.Assert(numpoints != 0, "[IdnMapping.adapt]Expected non-zero numpoints.");
+ Debug.Assert(numpoints != 0, "[IdnMapping.adapt]Expected non-zero numpoints.");
delta += delta / numpoints;
for (k = 0; delta > ((punycodeBase - tmin) * tmax) / 2; k += punycodeBase)
delta /= punycodeBase - tmin;
}
- Contract.Assert(delta + skew != 0, "[IdnMapping.adapt]Expected non-zero delta+skew.");
+ Debug.Assert(delta + skew != 0, "[IdnMapping.adapt]Expected non-zero delta+skew.");
return (int)(k + (punycodeBase - tmin + 1) * delta / (delta + skew));
}
{
// Find end of this segment
iNextDot = unicode.IndexOfAny(M_Dots, iAfterLastDot);
- Contract.Assert(iNextDot <= unicode.Length, "[IdnMapping.punycode_encode]IndexOfAny is broken");
+ Debug.Assert(iNextDot <= unicode.Length, "[IdnMapping.punycode_encode]IndexOfAny is broken");
if (iNextDot < 0)
iNextDot = unicode.Length;
for (basicCount = iAfterLastDot; basicCount < iNextDot; basicCount++)
{
// Can't be lonely surrogate because it would've thrown in normalization
- Contract.Assert(Char.IsLowSurrogate(unicode, basicCount) == false,
+ Debug.Assert(Char.IsLowSurrogate(unicode, basicCount) == false,
"[IdnMapping.punycode_encode]Unexpected low surrogate");
// Double check our bidi rules
/* Increase delta enough to advance the decoder's */
/* <n,i> state to <m,0>, but guard against overflow: */
delta += (int)((m - n) * ((numProcessed - numSurrogatePairs) + 1));
- Contract.Assert(delta > 0, "[IdnMapping.cs]1 punycode_encode - delta overflowed int");
+ Debug.Assert(delta > 0, "[IdnMapping.cs]1 punycode_encode - delta overflowed int");
n = m;
for (j = iAfterLastDot; j < iNextDot; j+= IsSupplementary(test) ? 2 : 1)
if (test < n)
{
delta++;
- Contract.Assert(delta > 0, "[IdnMapping.cs]2 punycode_encode - delta overflowed int");
+ Debug.Assert(delta > 0, "[IdnMapping.cs]2 punycode_encode - delta overflowed int");
}
if (test == n)
int t = k <= bias ? tmin :
k >= bias + tmax ? tmax : k - bias;
if (q < t) break;
- Contract.Assert(punycodeBase != t, "[IdnMapping.punycode_encode]Expected punycodeBase (36) to be != t");
+ Debug.Assert(punycodeBase != t, "[IdnMapping.punycode_encode]Expected punycodeBase (36) to be != t");
int mod;
q = Math.DivRem(q - t, punycodeBase - t, out mod);
}
++delta;
++n;
- Contract.Assert(delta > 0, "[IdnMapping.cs]3 punycode_encode - delta overflowed int");
+ Debug.Assert(delta > 0, "[IdnMapping.cs]3 punycode_encode - delta overflowed int");
}
}
// decode the digit from the next char
int digit = decode_digit(ascii[asciiIndex++]);
- Contract.Assert(w > 0, "[IdnMapping.punycode_decode]Expected w > 0");
+ Debug.Assert(w > 0, "[IdnMapping.punycode_decode]Expected w > 0");
if (digit > (maxint - i) / w)
throw new ArgumentException(Environment.GetResourceString(
"Argument_IdnBadPunycode"), nameof(ascii));
int t = k <= bias ? tmin :
k >= bias + tmax ? tmax : k - bias;
if (digit < t) break;
- Contract.Assert(punycodeBase != t, "[IdnMapping.punycode_decode]Expected t != punycodeBase (36)");
+ Debug.Assert(punycodeBase != t, "[IdnMapping.punycode_decode]Expected t != punycodeBase (36)");
if (w > maxint / (punycodeBase - t))
throw new ArgumentException(Environment.GetResourceString(
"Argument_IdnBadPunycode"), nameof(ascii));
/* i was supposed to wrap around from output.Length to 0, */
/* incrementing n each time, so we'll fix that now: */
- Contract.Assert((output.Length - iOutputAfterLastDot - numSurrogatePairs) + 1 > 0,
+ Debug.Assert((output.Length - iOutputAfterLastDot - numSurrogatePairs) + 1 > 0,
"[IdnMapping.punycode_decode]Expected to have added > 0 characters this segment");
if (i / ((output.Length - iOutputAfterLastDot - numSurrogatePairs) + 1) > maxint - n)
throw new ArgumentException(Environment.GetResourceString(
private const int ERROR_INVALID_NAME = 123;
- [System.Security.SecurityCritical]
[SuppressUnmanagedCodeSecurityAttribute()]
[DllImport("kernel32.dll", CharSet=CharSet.Unicode, SetLastError=true)]
private static extern int IdnToAscii(
char [] lpASCIICharStr,
int cchASCIIChar);
- [System.Security.SecurityCritical]
[SuppressUnmanagedCodeSecurityAttribute()]
[DllImport("kernel32.dll", CharSet=CharSet.Unicode, SetLastError=true)]
private static extern int IdnToUnicode(
// . is a delimiter, but the value of . doesn't matter.
// '_' marks the space between the japanese era name, japanese abbreviated era name
// english name, and abbreviated english names.
- [System.Security.SecuritySafeCritical] // auto-generated
private static EraInfo[] GetErasFromRegistry()
{
// Look in the registry key and see if we can find any ranges
[OnSerializing]
private void OnSerializing(StreamingContext ctx)
{
-#if !FEATURE_CORECLR
- // Update these legacy flags, so that 1.1/2.0 versions of the framework
- // can still throw while parsing; even when using a de-serialized
- // NumberFormatInfo from a 4.0+ version of the framework
- if (numberDecimalSeparator != numberGroupSeparator) {
- validForParseAsNumber = true;
- } else {
- validForParseAsNumber = false;
- }
-
- if ((numberDecimalSeparator != numberGroupSeparator) &&
- (numberDecimalSeparator != currencyGroupSeparator) &&
- (currencyDecimalSeparator != numberGroupSeparator) &&
- (currencyDecimalSeparator != currencyGroupSeparator)) {
- validForParseAsCurrency = true;
- } else {
- validForParseAsCurrency = false;
- }
-#endif // !FEATURE_CORECLR
}
-
[OnDeserializing]
private void OnDeserializing(StreamingContext ctx)
{
}
#endregion Serialization
-
static private void VerifyDecimalSeparator(String decSep, String propertyName) {
if (decSep==null) {
throw new ArgumentNullException(propertyName,
// We aren't persisting dataItem any more (since its useless & we weren't using it),
// Ditto with m_useUserOverride. Don't use them, we use a local copy of everything.
- [System.Security.SecuritySafeCritical] // auto-generated
internal NumberFormatInfo(CultureData cultureData)
{
if (cultureData != null)
namespace System.Globalization {
using System;
+ using System.Diagnostics;
using System.Diagnostics.Contracts;
////////////////////////////////////////////////////////////////////////////
static int MonthFromOrdinalDay(int ordinalDay)
{
- Contract.Assert(ordinalDay <= 366);
+ Debug.Assert(ordinalDay <= 366);
int index = 0;
while (ordinalDay > DaysToMonth[index])
index++;
static int DaysInPreviousMonths(int month)
{
- Contract.Assert(1 <= month && month <= 12);
+ Debug.Assert(1 <= month && month <= 12);
--month; // months are one based but for calculations use 0 based
return DaysToMonth[month];
}
long yearStart = CalendricalCalculationsHelper.PersianNewYearOnOrBefore(NumDays);
int y = (int)(Math.Floor(((yearStart - PersianEpoch) / CalendricalCalculationsHelper.MeanTropicalYearInDays) + 0.5)) + 1;
- Contract.Assert(y >= 1);
+ Debug.Assert(y >= 1);
if (part == DatePartYear)
{
}
int m = MonthFromOrdinalDay(ordinalDay);
- Contract.Assert(ordinalDay >= 1);
- Contract.Assert(m >= 1 && m <= 12);
+ Debug.Assert(ordinalDay >= 1);
+ Debug.Assert(m >= 1 && m <= 12);
if (part == DatePartMonth)
{
return m;
}
int d = ordinalDay - DaysInPreviousMonths(m);
- Contract.Assert(1 <= d);
- Contract.Assert(d <= 31);
+ Debug.Assert(1 <= d);
+ Debug.Assert(d <= 31);
//
// Calculate the Persian Day.
int daysInMonth = DaysToMonth[month] - DaysToMonth[month - 1];
if ((month == MonthsPerYear) && !IsLeapYear(year))
{
- Contract.Assert(daysInMonth == 30);
+ Debug.Assert(daysInMonth == 30);
--daysInMonth;
}
return daysInMonth;
using System;
using System.Runtime.Serialization;
+ using System.Diagnostics;
using System.Diagnostics.Contracts;
[Serializable]
// In Silverlight we enforce that RegionInfos must be created with a full culture name
//
////////////////////////////////////////////////////////////////////////
- [System.Security.SecuritySafeCritical] // auto-generated
public RegionInfo(String name) {
if (name==null)
throw new ArgumentNullException(nameof(name));
#if FEATURE_USE_LCID
// We'd rather people use the named version since this doesn't allow custom locales
- [System.Security.SecuritySafeCritical] // auto-generated
public RegionInfo(int culture)
{
if (culture == CultureInfo.LOCALE_INVARIANT) //The InvariantCulture has no matching region
}
#endif
- [System.Security.SecuritySafeCritical] // auto-generated
internal RegionInfo(CultureData cultureData)
{
this.m_cultureData = cultureData;
this.m_name = this.m_cultureData.SREGIONNAME;
}
- [System.Security.SecurityCritical] // auto-generated
private void SetName(string name)
{
-#if FEATURE_CORECLR
// Use the name of the region we found
this.m_name = this.m_cultureData.SREGIONNAME;
-#else
- // when creating region by culture name, we keep the region name as the culture name so regions
- // created by custom culture names can be differentiated from built in regions.
- this.m_name = name.Equals(this.m_cultureData.SREGIONNAME, StringComparison.OrdinalIgnoreCase) ?
- this.m_cultureData.SREGIONNAME :
- this.m_cultureData.CultureName;
-#endif // FEATURE_CORECLR
}
-
#region Serialization
//
[OptionalField(VersionAdded = 2)]
internal int m_dataItem = 0;
-#if !FEATURE_CORECLR
- static private readonly int[] IdFromEverettRegionInfoDataItem =
- {
- 0x3801, /* 0 */ // AE ar-AE Arabic (U.A.E.)
- 0x041C, /* 1 */ // AL sq-AL Albanian (Albania)
- 0x042B, /* 2 */ // AM hy-AM Armenian (Armenia)
- 0x2C0A, /* 3 */ // AR es-AR Spanish (Argentina)
- 0x0C07, /* 4 */ // AT de-AT German (Austria)
- 0x0C09, /* 5 */ // AU en-AU English (Australia)
- 0x042C, /* 6 */ // AZ az-AZ-Latn Azeri (Latin) (Azerbaijan)
- // 0x082C, 6, // AZ az-AZ-Cyrl Azeri (Cyrillic) (Azerbaijan)
- 0x080C, /* 7 */ // BE fr-BE French (Belgium)
- // 0x0813, 7, // BE nl-BE Dutch (Belgium)
- 0x0402, /* 8 */ // BG bg-BG Bulgarian (Bulgaria)
- 0x3C01, /* 9 */ // BH ar-BH Arabic (Bahrain)
- 0x083E, /* 10 */ // BN ms-BN Malay (Brunei Darussalam)
- 0x400A, /* 11 */ // BO es-BO Spanish (Bolivia)
- 0x0416, /* 12 */ // BR pt-BR Portuguese (Brazil)
- 0x0423, /* 13 */ // BY be-BY Belarusian (Belarus)
- 0x2809, /* 14 */ // BZ en-BZ English (Belize)
- 0x0C0C, /* 15 */ // CA fr-CA French (Canada)
- // 0x1009, 15, // CA en-CA English (Canada)
- 0x2409, /* 16 */ // CB en-CB English (Caribbean)
- 0x0807, /* 17 */ // CH de-CH German (Switzerland)
- // 0x0810, 17, // CH it-CH Italian (Switzerland)
- // 0x100C, 17, // CH fr-CH French (Switzerland)
- 0x340A, /* 18 */ // CL es-CL Spanish (Chile)
- 0x0804, /* 19 */ // CN zh-CN Chinese (People's Republic of China)
- 0x240A, /* 20 */ // CO es-CO Spanish (Colombia)
- 0x140A, /* 21 */ // CR es-CR Spanish (Costa Rica)
- 0x0405, /* 22 */ // CZ cs-CZ Czech (Czech Republic)
- 0x0407, /* 23 */ // DE de-DE German (Germany)
- 0x0406, /* 24 */ // DK da-DK Danish (Denmark)
- 0x1C0A, /* 25 */ // DO es-DO Spanish (Dominican Republic)
- 0x1401, /* 26 */ // DZ ar-DZ Arabic (Algeria)
- 0x300A, /* 27 */ // EC es-EC Spanish (Ecuador)
- 0x0425, /* 28 */ // EE et-EE Estonian (Estonia)
- 0x0C01, /* 29 */ // EG ar-EG Arabic (Egypt)
- 0x0403, /* 30 */ // ES ca-ES Catalan (Catalan)
- // 0x042D, 30, // ES eu-ES Basque (Basque)
- // 0x0456, 30, // ES gl-ES Galician (Galician)
- // 0x0C0A, 30, // ES es-ES Spanish (Spain)
- 0x040B, /* 31 */ // FI fi-FI Finnish (Finland)
- // 0x081D, 31, // FI sv-FI Swedish (Finland)
- 0x0438, /* 32 */ // FO fo-FO Faroese (Faroe Islands)
- 0x040C, /* 33 */ // FR fr-FR French (France)
- 0x0809, /* 34 */ // GB en-GB English (United Kingdom)
- 0x0437, /* 35 */ // GE ka-GE Georgian (Georgia)
- 0x0408, /* 36 */ // GR el-GR Greek (Greece)
- 0x100A, /* 37 */ // GT es-GT Spanish (Guatemala)
- 0x0C04, /* 38 */ // HK zh-HK Chinese (Hong Kong S.A.R.)
- 0x480A, /* 39 */ // HN es-HN Spanish (Honduras)
- 0x041A, /* 40 */ // HR hr-HR Croatian (Croatia)
- 0x040E, /* 41 */ // HU hu-HU Hungarian (Hungary)
- 0x0421, /* 42 */ // ID id-ID Indonesian (Indonesia)
- 0x1809, /* 43 */ // IE en-IE English (Ireland)
- 0x040D, /* 44 */ // IL he-IL Hebrew (Israel)
- 0x0439, /* 45 */ // IN hi-IN Hindi (India)
- // 0x0446, 45, // IN pa-IN Punjabi (India)
- // 0x0447, 45, // IN gu-IN Gujarati (India)
- // 0x0449, 45, // IN ta-IN Tamil (India)
- // 0x044A, 45, // IN te-IN Telugu (India)
- // 0x044B, 45, // IN kn-IN Kannada (India)
- // 0x044E, 45, // IN mr-IN Marathi (India)
- // 0x044F, 45, // IN sa-IN Sanskrit (India)
- // 0x0457, 45, // IN kok-IN Konkani (India)
- 0x0801, /* 46 */ // IQ ar-IQ Arabic (Iraq)
- 0x0429, /* 47 */ // IR fa-IR (Iran)
- 0x040F, /* 48 */ // IS is-IS Icelandic (Iceland)
- 0x0410, /* 49 */ // IT it-IT Italian (Italy)
- 0x2009, /* 50 */ // JM en-JM English (Jamaica)
- 0x2C01, /* 51 */ // JO ar-JO Arabic (Jordan)
- 0x0411, /* 52 */ // JP ja-JP Japanese (Japan)
- 0x0441, /* 53 */ // KE sw-KE Swahili (Kenya)
- 0x0440, /* 54 */ // KG ky-KG Kyrgyz (Kyrgyzstan)
- 0x0412, /* 55 */ // KR ko-KR Korean (Korea)
- 0x3401, /* 56 */ // KW ar-KW Arabic (Kuwait)
- 0x043F, /* 57 */ // KZ kk-KZ Kazakh (Kazakhstan)
- 0x3001, /* 58 */ // LB ar-LB Arabic (Lebanon)
- 0x1407, /* 59 */ // LI de-LI German (Liechtenstein)
- 0x0427, /* 60 */ // LT lt-LT Lithuanian (Lithuania)
- 0x1007, /* 61 */ // LU de-LU German (Luxembourg)
- // 0x140C, 61, // LU fr-LU French (Luxembourg)
- 0x0426, /* 62 */ // LV lv-LV Latvian (Latvia)
- 0x1001, /* 63 */ // LY ar-LY Arabic (Libya)
- 0x1801, /* 64 */ // MA ar-MA Arabic (Morocco)
- 0x180C, /* 65 */ // MC fr-MC French (Principality of Monaco)
- 0x042F, /* 66 */ // MK mk-MK Macedonian (Macedonia, FYRO)
- 0x0450, /* 67 */ // MN mn-MN Mongolian (Mongolia)
- 0x1404, /* 68 */ // MO zh-MO Chinese (Macau S.A.R.)
- 0x0465, /* 69 */ // MV div-MV Divehi (Maldives)
- 0x080A, /* 70 */ // MX es-MX Spanish (Mexico)
- 0x043E, /* 71 */ // MY ms-MY Malay (Malaysia)
- 0x4C0A, /* 72 */ // NI es-NI Spanish (Nicaragua)
- 0x0413, /* 73 */ // NL nl-NL Dutch (Netherlands)
- 0x0414, /* 74 */ // NO nb-NO Norwegian (Bokm?) (Norway)
- // 0x0814, 74, // NO nn-NO Norwegian (Nynorsk) (Norway)
- 0x1409, /* 75 */ // NZ en-NZ English (New Zealand)
- 0x2001, /* 76 */ // OM ar-OM Arabic (Oman)
- 0x180A, /* 77 */ // PA es-PA Spanish (Panama)
- 0x280A, /* 78 */ // PE es-PE Spanish (Peru)
- 0x3409, /* 79 */ // PH en-PH English (Republic of the Philippines)
- 0x0420, /* 80 */ // PK ur-PK Urdu (Islamic Republic of Pakistan)
- 0x0415, /* 81 */ // PL pl-PL Polish (Poland)
- 0x500A, /* 82 */ // PR es-PR Spanish (Puerto Rico)
- 0x0816, /* 83 */ // PT pt-PT Portuguese (Portugal)
- 0x3C0A, /* 84 */ // PY es-PY Spanish (Paraguay)
- 0x4001, /* 85 */ // QA ar-QA Arabic (Qatar)
- 0x0418, /* 86 */ // RO ro-RO Romanian (Romania)
- 0x0419, /* 87 */ // RU ru-RU Russian (Russia)
- // 0x0444, 87, // RU tt-RU Tatar (Russia)
- 0x0401, /* 88 */ // SA ar-SA Arabic (Saudi Arabia)
- 0x041D, /* 89 */ // SE sv-SE Swedish (Sweden)
- 0x1004, /* 90 */ // SG zh-SG Chinese (Singapore)
- 0x0424, /* 91 */ // SI sl-SI Slovenian (Slovenia)
- 0x041B, /* 92 */ // SK sk-SK Slovak (Slovakia)
- 0x081A, /* 93 */ // SP sr-SP-Latn Serbian (Latin) (Serbia)
- // 0x0C1A, 93, // SP sr-SP-Cyrl Serbian (Cyrillic) (Serbia)
- 0x440A, /* 94 */ // SV es-SV Spanish (El Salvador)
- 0x045A, /* 95 */ // SY syr-SY Syriac (Syria)
- // 0x2801, 95, // SY ar-SY Arabic (Syria)
- 0x041E, /* 96 */ // TH th-TH Thai (Thailand)
- 0x1C01, /* 97 */ // TN ar-TN Arabic (Tunisia)
- 0x041F, /* 98 */ // TR tr-TR Turkish (Turkey)
- 0x2C09, /* 99 */ // TT en-TT English (Trinidad and Tobago)
- 0x0404, /*100 */ // TW zh-TW Chinese (Taiwan)
- 0x0422, /*101 */ // UA uk-UA Ukrainian (Ukraine)
- 0x0409, /*102 */ // US en-US English (United States)
- 0x380A, /*103 */ // UY es-UY Spanish (Uruguay)
- 0x0443, /*104 */ // UZ uz-UZ-Latn Uzbek (Latin) (Uzbekistan)
- // 0x0843, 104 // UZ uz-UZ-Cyrl Uzbek (Cyrillic) (Uzbekistan)
- 0x200A, /*105*/ // VE es-VE Spanish (Venezuela)
- 0x042A, /*106*/ // VN vi-VN Vietnamese (Viet Nam)
- 0x2401, /*107*/ // YE ar-YE Arabic (Yemen)
- 0x0436, /*108*/ // ZA af-ZA Afrikaans (South Africa)
- // 0x1C09, 108, // ZA en-ZA English (South Africa)
- 0x3009, /*109*/ // ZW en-ZW English (Zimbabwe)
- };
-#endif
- [System.Security.SecurityCritical] // auto-generated
[OnDeserialized]
private void OnDeserialized(StreamingContext ctx)
{
-#if FEATURE_CORECLR
// This won't happen anyway since CoreCLR doesn't support serialization
this.m_cultureData = CultureData.GetCultureData(m_name, true);
-#else
- if (m_name == null)
- {
- Contract.Assert(m_dataItem >= 0, "[RegionInfo.OnDeserialized] null name and invalid dataItem");
- m_cultureId = IdFromEverettRegionInfoDataItem[m_dataItem];
- }
- if (m_cultureId == 0)
- {
- this.m_cultureData = CultureData.GetCultureDataForRegion(this.m_name, true);
- }
- else
- {
- this.m_cultureData = CultureData.GetCultureData(m_cultureId, true);
- }
-
-#endif
if (this.m_cultureData == null)
throw new ArgumentException(
String.Format(
//
////////////////////////////////////////////////////////////////////////
public static RegionInfo CurrentRegion {
- [System.Security.SecuritySafeCritical] // auto-generated
get {
RegionInfo temp = s_currentRegionInfo;
if (temp == null)
////////////////////////////////////////////////////////////////////////
public virtual String Name {
get {
- Contract.Assert(m_name != null, "Expected RegionInfo.m_name to be populated already");
+ Debug.Assert(m_name != null, "Expected RegionInfo.m_name to be populated already");
return (m_name);
}
}
////////////////////////////////////////////////////////////////////////
public virtual String EnglishName
{
- [System.Security.SecuritySafeCritical] // auto-generated
get
{
return (this.m_cultureData.SENGCOUNTRY);
////////////////////////////////////////////////////////////////////////
public virtual String DisplayName
{
- [System.Security.SecuritySafeCritical] // auto-generated
get
{
return (this.m_cultureData.SLOCALIZEDCOUNTRY);
[System.Runtime.InteropServices.ComVisible(false)]
public virtual String NativeName
{
- [System.Security.SecuritySafeCritical] // auto-generated
get
{
return (this.m_cultureData.SNATIVECOUNTRY);
////////////////////////////////////////////////////////////////////////
public virtual String TwoLetterISORegionName
{
- [System.Security.SecuritySafeCritical] // auto-generated
get
{
return (this.m_cultureData.SISO3166CTRYNAME);
////////////////////////////////////////////////////////////////////////
public virtual String ThreeLetterISORegionName
{
- [System.Security.SecuritySafeCritical] // auto-generated
get
{
return (this.m_cultureData.SISO3166CTRYNAME2);
////////////////////////////////////////////////////////////////////////
public virtual String ThreeLetterWindowsRegionName
{
- [System.Security.SecuritySafeCritical] // auto-generated
get
{
return (this.m_cultureData.SABBREVCTRYNAME);
[System.Runtime.InteropServices.ComVisible(false)]
public virtual String CurrencyEnglishName
{
- [System.Security.SecuritySafeCritical] // auto-generated
get
{
return (this.m_cultureData.SENGLISHCURRENCY);
[System.Runtime.InteropServices.ComVisible(false)]
public virtual String CurrencyNativeName
{
- [System.Security.SecuritySafeCritical] // auto-generated
get
{
return (this.m_cultureData.SNATIVECURRENCY);
//
////////////////////////////////////////////////////////////////////////
public virtual String CurrencySymbol {
- [System.Security.SecuritySafeCritical] // auto-generated
get {
return (this.m_cultureData.SCURRENCY);
}
//
////////////////////////////////////////////////////////////////////////
public virtual String ISOCurrencySymbol {
- [System.Security.SecuritySafeCritical] // auto-generated
get {
return (this.m_cultureData.SINTLSYMBOL);
}
using System;
using System.Runtime.CompilerServices;
using System.Runtime.Serialization;
+ using System.Diagnostics;
using System.Diagnostics.Contracts;
[System.Runtime.InteropServices.ComVisible(true)]
byte[] key1Data = sortkey1.m_KeyData;
byte[] key2Data = sortkey2.m_KeyData;
- Contract.Assert(key1Data!=null, "key1Data!=null");
- Contract.Assert(key2Data!=null, "key2Data!=null");
+ Debug.Assert(key1Data!=null, "key1Data!=null");
+ Debug.Assert(key2Data!=null, "key2Data!=null");
if (key1Data.Length == 0) {
if (key2Data.Length == 0) {
using System;
using System.Runtime.Serialization;
using System.Security.Permissions;
+ using System.Diagnostics;
using System.Diagnostics.Contracts;
[Serializable]
internal static int GetCurrentTextElementLen(String str, int index, int len, ref UnicodeCategory ucCurrent, ref int currentCharCount)
{
- Contract.Assert(index >= 0 && len >= 0, "StringInfo.GetCurrentTextElementLen() : index = " + index + ", len = " + len);
- Contract.Assert(index < len, "StringInfo.GetCurrentTextElementLen() : index = " + index + ", len = " + len);
+ Debug.Assert(index >= 0 && len >= 0, "StringInfo.GetCurrentTextElementLen() : index = " + index + ", len = " + len);
+ Debug.Assert(index < len, "StringInfo.GetCurrentTextElementLen() : index = " + index + ", len = " + len);
if (index + currentCharCount == len)
{
// This is the last character/surrogate in the string.
namespace System.Globalization {
using System.Collections;
+ using System.Diagnostics;
using System.Diagnostics.Contracts;
//
internal TextElementEnumerator(String str, int startIndex, int strLen)
{
- Contract.Assert(str != null, "TextElementEnumerator(): str != null");
- Contract.Assert(startIndex >= 0 && strLen >= 0, "TextElementEnumerator(): startIndex >= 0 && strLen >= 0");
- Contract.Assert(strLen >= startIndex, "TextElementEnumerator(): strLen >= startIndex");
+ Debug.Assert(str != null, "TextElementEnumerator(): str != null");
+ Debug.Assert(startIndex >= 0 && strLen >= 0, "TextElementEnumerator(): startIndex >= 0 && strLen >= 0");
+ Debug.Assert(strLen >= startIndex, "TextElementEnumerator(): strLen >= startIndex");
this.str = str;
this.startIndex = startIndex;
this.strLen = strLen;
using System.Runtime.Serialization;
using System.Runtime.Versioning;
using System.Security.Permissions;
+ using System.Diagnostics;
using System.Diagnostics.Contracts;
this.m_cultureData = cultureData;
this.m_cultureName = this.m_cultureData.CultureName;
this.m_textInfoName = this.m_cultureData.STEXTINFO;
-#if !FEATURE_CORECLR
- IntPtr handleOrigin;
- this.m_dataHandle = CompareInfo.InternalInitSortHandle(m_textInfoName, out handleOrigin);
- this.m_handleOrigin = handleOrigin;
-#endif
}
////////////////////////////////////////////////////////////////////////
// Get the text info name belonging to that culture
this.m_cultureData = CultureInfo.GetCultureInfo(m_cultureName).m_cultureData;
this.m_textInfoName = this.m_cultureData.STEXTINFO;
-#if !FEATURE_CORECLR
- IntPtr handleOrigin;
- this.m_dataHandle = CompareInfo.InternalInitSortHandle(m_textInfoName, out handleOrigin);
- this.m_handleOrigin = handleOrigin;
-#endif
- }
+ }
}
-
[OnDeserialized]
private void OnDeserialized(StreamingContext ctx)
{
OnDeserialized();
- }
-
+ }
+
[OnSerializing]
private void OnSerializing(StreamingContext ctx)
- {
-#if !FEATURE_CORECLR
- // Initialize the fields Whidbey expects:
- // Whidbey expected this, so set it, but the value doesn't matter much
- this.m_useUserOverride = false;
-#endif // FEATURE_CORECLR
-
+ {
// Relabel our name since Whidbey expects it to be called customCultureName
this.customCultureName = this.m_cultureName;
return (Invariant.GetCaseInsensitiveHashCode(s, forceRandomizedHashing, additionalEntropy));
}
- [System.Security.SecuritySafeCritical]
internal static unsafe bool TryFastFindStringOrdinalIgnoreCase(int searchFlags, String source, int startIndex, String value, int count, ref int foundIndex)
{
return InternalTryFindStringOrdinalIgnoreCase(searchFlags, source, count, startIndex, value, value.Length, ref foundIndex);
// This function doesn't check arguments. Please do check in the caller.
// The underlying unmanaged code will assert the sanity of arguments.
- [System.Security.SecuritySafeCritical] // auto-generated
internal static unsafe int CompareOrdinalIgnoreCase(String str1, String str2)
{
// Compare the whole string and ignore case.
// This function doesn't check arguments. Please do check in the caller.
// The underlying unmanaged code will assert the sanity of arguments.
- [System.Security.SecuritySafeCritical] // auto-generated
internal static unsafe int CompareOrdinalIgnoreCaseEx(String strA, int indexA, String strB, int indexB, int lengthA, int lengthB )
{
- Contract.Assert(strA.Length >= indexA + lengthA, "[TextInfo.CompareOrdinalIgnoreCaseEx] Caller should've validated strA.Length >= indexA + lengthA");
- Contract.Assert(strB.Length >= indexB + lengthB, "[TextInfo.CompareOrdinalIgnoreCaseEx] Caller should've validated strB.Length >= indexB + lengthB");
+ Debug.Assert(strA.Length >= indexA + lengthA, "[TextInfo.CompareOrdinalIgnoreCaseEx] Caller should've validated strA.Length >= indexA + lengthA");
+ Debug.Assert(strB.Length >= indexB + lengthB, "[TextInfo.CompareOrdinalIgnoreCaseEx] Caller should've validated strB.Length >= indexB + lengthB");
return InternalCompareStringOrdinalIgnoreCase(strA, indexA, strB, indexB, lengthA, lengthB);
}
internal static int IndexOfStringOrdinalIgnoreCase(String source, String value, int startIndex, int count)
{
- Contract.Assert(source != null, "[TextInfo.IndexOfStringOrdinalIgnoreCase] Caller should've validated source != null");
- Contract.Assert(value != null, "[TextInfo.IndexOfStringOrdinalIgnoreCase] Caller should've validated value != null");
- Contract.Assert(startIndex + count <= source.Length, "[TextInfo.IndexOfStringOrdinalIgnoreCase] Caller should've validated startIndex + count <= source.Length");
+ Debug.Assert(source != null, "[TextInfo.IndexOfStringOrdinalIgnoreCase] Caller should've validated source != null");
+ Debug.Assert(value != null, "[TextInfo.IndexOfStringOrdinalIgnoreCase] Caller should've validated value != null");
+ Debug.Assert(startIndex + count <= source.Length, "[TextInfo.IndexOfStringOrdinalIgnoreCase] Caller should've validated startIndex + count <= source.Length");
// We return 0 if both inputs are empty strings
if (source.Length == 0 && value.Length == 0)
for (; startIndex <= maxStartIndex; startIndex++)
{
// We should always have the same or more characters left to search than our actual pattern
- Contract.Assert(end - startIndex >= value.Length);
+ Debug.Assert(end - startIndex >= value.Length);
// since this is an ordinal comparison, we can assume that the lengths must match
if (CompareOrdinalIgnoreCaseEx(source, startIndex, value, 0, value.Length, value.Length) == 0)
{
internal static int LastIndexOfStringOrdinalIgnoreCase(String source, String value, int startIndex, int count)
{
- Contract.Assert(source != null, "[TextInfo.LastIndexOfStringOrdinalIgnoreCase] Caller should've validated source != null");
- Contract.Assert(value != null, "[TextInfo.LastIndexOfStringOrdinalIgnoreCase] Caller should've validated value != null");
- Contract.Assert(startIndex - count+1 >= 0, "[TextInfo.LastIndexOfStringOrdinalIgnoreCase] Caller should've validated startIndex - count+1 >= 0");
- Contract.Assert(startIndex <= source.Length, "[TextInfo.LastIndexOfStringOrdinalIgnoreCase] Caller should've validated startIndex <= source.Length");
+ Debug.Assert(source != null, "[TextInfo.LastIndexOfStringOrdinalIgnoreCase] Caller should've validated source != null");
+ Debug.Assert(value != null, "[TextInfo.LastIndexOfStringOrdinalIgnoreCase] Caller should've validated value != null");
+ Debug.Assert(startIndex - count+1 >= 0, "[TextInfo.LastIndexOfStringOrdinalIgnoreCase] Caller should've validated startIndex - count+1 >= 0");
+ Debug.Assert(startIndex <= source.Length, "[TextInfo.LastIndexOfStringOrdinalIgnoreCase] Caller should've validated startIndex <= source.Length");
// If value is Empty, the return value is startIndex
if (value.Length == 0)
public virtual String ListSeparator
{
- [System.Security.SecuritySafeCritical] // auto-generated
get
{
if (m_listSeparator == null) {
//
////////////////////////////////////////////////////////////////////////
- [System.Security.SecuritySafeCritical] // auto-generated
public unsafe virtual char ToLower(char c)
{
if(IsAscii(c) && IsAsciiCasingSameAsInvariant)
return (InternalChangeCaseChar(this.m_dataHandle, this.m_handleOrigin, this.m_textInfoName, c, false));
}
- [System.Security.SecuritySafeCritical] // auto-generated
public unsafe virtual String ToLower(String str)
{
if (str == null) { throw new ArgumentNullException(nameof(str)); }
//
////////////////////////////////////////////////////////////////////////
- [System.Security.SecuritySafeCritical] // auto-generated
public unsafe virtual char ToUpper(char c)
{
if (IsAscii(c) && IsAsciiCasingSameAsInvariant)
}
- [System.Security.SecuritySafeCritical] // auto-generated
public unsafe virtual String ToUpper(String str)
{
if (str == null) { throw new ArgumentNullException(nameof(str)); }
private static int AddNonLetter(ref StringBuilder result, ref String input, int inputIndex, int charLen)
{
- Contract.Assert(charLen == 1 || charLen == 2, "[TextInfo.AddNonLetter] CharUnicodeInfo.InternalGetUnicodeCategory returned an unexpected charLen!");
+ Debug.Assert(charLen == 1 || charLen == 2, "[TextInfo.AddNonLetter] CharUnicodeInfo.InternalGetUnicodeCategory returned an unexpected charLen!");
if (charLen == 2)
{
// Surrogate pair
private int AddTitlecaseLetter(ref StringBuilder result, ref String input, int inputIndex, int charLen)
{
- Contract.Assert(charLen == 1 || charLen == 2, "[TextInfo.AddTitlecaseLetter] CharUnicodeInfo.InternalGetUnicodeCategory returned an unexpected charLen!");
+ Debug.Assert(charLen == 1 || charLen == 2, "[TextInfo.AddTitlecaseLetter] CharUnicodeInfo.InternalGetUnicodeCategory returned an unexpected charLen!");
// for surrogate pairs do a simple ToUpper operation on the substring
if (charLen == 2)
// is not null before calling this. Currenlty, CaseInsensitiveHashCodeProvider
// does that.
//
- [System.Security.SecuritySafeCritical] // auto-generated
internal unsafe int GetCaseInsensitiveHashCode(String str)
{
return GetCaseInsensitiveHashCode(str, false, 0);
}
- [System.Security.SecuritySafeCritical] // auto-generated
internal unsafe int GetCaseInsensitiveHashCode(String str, bool forceRandomizedHashing, long additionalEntropy)
{
// Validate inputs
}
// Change case (ToUpper/ToLower) -- COMNlsInfo::InternalChangeCaseChar
- [System.Security.SecurityCritical] // auto-generated
[MethodImplAttribute(MethodImplOptions.InternalCall)]
private static unsafe extern char InternalChangeCaseChar(IntPtr handle, IntPtr handleOrigin, String localeName, char ch, bool isToUpper);
// Change case (ToUpper/ToLower) -- COMNlsInfo::InternalChangeCaseString
- [System.Security.SecurityCritical] // auto-generated
[MethodImplAttribute(MethodImplOptions.InternalCall)]
private static unsafe extern String InternalChangeCaseString(IntPtr handle, IntPtr handleOrigin, String localeName, String str, bool isToUpper);
// Get case insensitive hash -- ComNlsInfo::InternalGetCaseInsHash
- [System.Security.SecurityCritical] // auto-generated
[MethodImplAttribute(MethodImplOptions.InternalCall)]
private static unsafe extern int InternalGetCaseInsHash(IntPtr handle, IntPtr handleOrigin, String localeName, String str, bool forceRandomizedHashing, long additionalEntropy);
// Call ::CompareStringOrdinal -- ComNlsInfo::InternalCompareStringOrdinalIgnoreCase
// Start at indexes and compare for length characters (or remainder of string if length == -1)
- [System.Security.SecurityCritical] // auto-generated
[DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
[SuppressUnmanagedCodeSecurity]
private static unsafe extern int InternalCompareStringOrdinalIgnoreCase(String string1, int index1, String string2, int index2, int length1, int length2);
// ComNlsInfo::InternalTryFindStringOrdinalIgnoreCase attempts a faster IndexOf/LastIndexOf OrdinalIgnoreCase using a kernel function.
// Returns true if FindStringOrdinal was handled, with foundIndex set to the target's index into the source
// Returns false when FindStringOrdinal wasn't handled
- [System.Security.SecurityCritical] // auto-generated
[DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
[SuppressUnmanagedCodeSecurity]
[return: MarshalAs(UnmanagedType.Bool)]
namespace System.Globalization {
using System.Text;
using System;
+ using System.Diagnostics;
using System.Diagnostics.Contracts;
using System.Globalization;
internal static class TimeSpanFormat {
- [System.Security.SecuritySafeCritical] // auto-generated
private static String IntToString(int n, int digits) {
return ParseNumbers.IntToString(n, 10, digits, '0', 0);
}
//
internal static String FormatCustomized(TimeSpan value, String format, DateTimeFormatInfo dtfi) {
- Contract.Assert(dtfi != null, "dtfi == null");
+ Debug.Assert(dtfi != null, "dtfi == null");
int day = (int)(value._ticks / TimeSpan.TicksPerDay);
long time = value._ticks % TimeSpan.TicksPerDay;
case '\"':
if (inQuote && (quote == format[i])) {
/* we were in a quote and found a matching exit quote, so we are outside a quote now */
- Contract.Assert(field >= 0 && field <= 5, "field >= 0 && field <= 5");
+ Debug.Assert(field >= 0 && field <= 5, "field >= 0 && field <= 5");
if (field >= 0 && field <= 5) {
literals[field] = sb.ToString();
sb.Length = 0;
}
break;
case '%':
- Contract.Assert(false, "Unexpected special token '%', Bug in DateTimeFormatInfo.FullTimeSpan[Positive|Negative]Pattern");
+ Debug.Assert(false, "Unexpected special token '%', Bug in DateTimeFormatInfo.FullTimeSpan[Positive|Negative]Pattern");
goto default;
case '\\':
if (!inQuote) {
goto default;
case 'd':
if (!inQuote) {
- Contract.Assert((field == 0 && sb.Length == 0) || field == 1,
+ Debug.Assert((field == 0 && sb.Length == 0) || field == 1,
"field == 0 || field == 1, Bug in DateTimeFormatInfo.FullTimeSpan[Positive|Negative]Pattern");
field = 1; // DayHourSep
dd++;
break;
case 'h':
if (!inQuote) {
- Contract.Assert((field == 1 && sb.Length == 0) || field == 2,
+ Debug.Assert((field == 1 && sb.Length == 0) || field == 2,
"field == 1 || field == 2, Bug in DateTimeFormatInfo.FullTimeSpan[Positive|Negative]Pattern");
field = 2; // HourMinuteSep
hh++;
break;
case 'm':
if (!inQuote) {
- Contract.Assert((field == 2 && sb.Length == 0) || field == 3,
+ Debug.Assert((field == 2 && sb.Length == 0) || field == 3,
"field == 2 || field == 3, Bug in DateTimeFormatInfo.FullTimeSpan[Positive|Negative]Pattern");
field = 3; // MinuteSecondSep
mm++;
break;
case 's':
if (!inQuote) {
- Contract.Assert((field == 3 && sb.Length == 0) || field == 4,
+ Debug.Assert((field == 3 && sb.Length == 0) || field == 4,
"field == 3 || field == 4, Bug in DateTimeFormatInfo.FullTimeSpan[Positive|Negative]Pattern");
field = 4; // SecondFractionSep
ss++;
case 'f':
case 'F':
if (!inQuote) {
- Contract.Assert((field == 4 && sb.Length == 0) || field == 5,
+ Debug.Assert((field == 4 && sb.Length == 0) || field == 5,
"field == 4 || field == 5, Bug in DateTimeFormatInfo.FullTimeSpan[Positive|Negative]Pattern");
field = 5; // End
ff++;
}
}
- Contract.Assert(field == 5);
+ Debug.Assert(field == 5);
AppCompatLiteral = MinuteSecondSep + SecondFractionSep;
- Contract.Assert(0 < dd && dd < 3, "0 < dd && dd < 3, Bug in System.Globalization.DateTimeFormatInfo.FullTimeSpan[Positive|Negative]Pattern");
- Contract.Assert(0 < hh && hh < 3, "0 < hh && hh < 3, Bug in System.Globalization.DateTimeFormatInfo.FullTimeSpan[Positive|Negative]Pattern");
- Contract.Assert(0 < mm && mm < 3, "0 < mm && mm < 3, Bug in System.Globalization.DateTimeFormatInfo.FullTimeSpan[Positive|Negative]Pattern");
- Contract.Assert(0 < ss && ss < 3, "0 < ss && ss < 3, Bug in System.Globalization.DateTimeFormatInfo.FullTimeSpan[Positive|Negative]Pattern");
- Contract.Assert(0 < ff && ff < 8, "0 < ff && ff < 8, Bug in System.Globalization.DateTimeFormatInfo.FullTimeSpan[Positive|Negative]Pattern");
+ Debug.Assert(0 < dd && dd < 3, "0 < dd && dd < 3, Bug in System.Globalization.DateTimeFormatInfo.FullTimeSpan[Positive|Negative]Pattern");
+ Debug.Assert(0 < hh && hh < 3, "0 < hh && hh < 3, Bug in System.Globalization.DateTimeFormatInfo.FullTimeSpan[Positive|Negative]Pattern");
+ Debug.Assert(0 < mm && mm < 3, "0 < mm && mm < 3, Bug in System.Globalization.DateTimeFormatInfo.FullTimeSpan[Positive|Negative]Pattern");
+ Debug.Assert(0 < ss && ss < 3, "0 < ss && ss < 3, Bug in System.Globalization.DateTimeFormatInfo.FullTimeSpan[Positive|Negative]Pattern");
+ Debug.Assert(0 < ff && ff < 8, "0 < ff && ff < 8, Bug in System.Globalization.DateTimeFormatInfo.FullTimeSpan[Positive|Negative]Pattern");
if (useInvariantFieldLengths) {
dd = 2;
namespace System.Globalization {
using System.Text;
using System;
+ using System.Diagnostics;
using System.Diagnostics.Contracts;
using System.Globalization;
}
public bool IsInvalidNumber(int maxValue, int maxPrecision) {
- Contract.Assert(ttt == TTT.Num);
- Contract.Assert(num > -1);
- Contract.Assert(maxValue > 0);
- Contract.Assert(maxPrecision == maxFractionDigits || maxPrecision == unlimitedDigits);
+ Debug.Assert(ttt == TTT.Num);
+ Debug.Assert(num > -1);
+ Debug.Assert(maxValue > 0);
+ Debug.Assert(maxPrecision == maxFractionDigits || maxPrecision == unlimitedDigits);
if (num > maxValue)
return true;
}
// used by the parsing routines that operate on standard-formats
internal TimeSpanToken GetNextToken() {
- Contract.Assert(m_pos > -1);
+ Debug.Assert(m_pos > -1);
TimeSpanToken tok = new TimeSpanToken();
char ch = CurrentChar;
private const int MaxNumericTokens = 5;
internal void Init(DateTimeFormatInfo dtfi) {
- Contract.Assert(dtfi != null);
+ Debug.Assert(dtfi != null);
lastSeenTTT = TTT.None;
tokenCount = 0;
}
lastSeenTTT = tok.ttt;
- Contract.Assert(tokenCount == (SepCount + NumCount), "tokenCount == (SepCount + NumCount)");
+ Debug.Assert(tokenCount == (SepCount + NumCount), "tokenCount == (SepCount + NumCount)");
return true;
}
return new OverflowException(Environment.GetResourceString(m_failureMessageID));
default:
- Contract.Assert(false, "Unknown TimeSpanParseFailure: " + m_failure);
+ Debug.Assert(false, "Unknown TimeSpanParseFailure: " + m_failure);
return new FormatException(Environment.GetResourceString("Format_InvalidString"));
}
}
// Actions: Parse the TimeSpan instance using the specified format. Used by TryParseExactTimeSpan.
//
private static Boolean TryParseByFormat(String input, String format, TimeSpanStyles styles, ref TimeSpanResult result) {
- Contract.Assert(input != null, "input != null");
- Contract.Assert(format != null, "format != null");
+ Debug.Assert(input != null, "input != null");
+ Debug.Assert(format != null, "format != null");
bool seenDD = false; // already processed days?
bool seenHH = false; // already processed hours?
namespace System.Globalization {
using System;
+ using System.Diagnostics;
using System.Diagnostics.Contracts;
=========================ConvertHijriToGregorian============================*/
static void ConvertHijriToGregorian(int HijriYear, int HijriMonth, int HijriDay, ref int yg, ref int mg, ref int dg)
{
- Contract.Assert( (HijriYear >= MinCalendarYear) && (HijriYear <= MaxCalendarYear), "Hijri year is out of range.");
- Contract.Assert( HijriMonth >= 1, "Hijri month is out of range.");
- Contract.Assert( HijriDay >= 1, "Hijri day is out of range.");
+ Debug.Assert( (HijriYear >= MinCalendarYear) && (HijriYear <= MaxCalendarYear), "Hijri year is out of range.");
+ Debug.Assert( HijriMonth >= 1, "Hijri month is out of range.");
+ Debug.Assert( HijriDay >= 1, "Hijri day is out of range.");
int index, b, nDays = HijriDay-1;
DateTime dt;
TimeSpan ts;
int yh1=0, mh1=0, dh1=0;
- Contract.Assert((time.Ticks >= minDate.Ticks) && (time.Ticks <= maxDate.Ticks), "Gregorian date is out of range.");
+ Debug.Assert((time.Ticks >= minDate.Ticks) && (time.Ticks <= maxDate.Ticks), "Gregorian date is out of range.");
// Find the index where we should start our search by quessing the Hijri year that we will be in HijriYearInfo.
// A Hijri year is 354 or 355 days. Use 355 days so that we will search from a lower index.
{
int days = 0, b;
- Contract.Assert( (year >= MinCalendarYear) && (year <= MaxCalendarYear), "Hijri year is out of range.");
+ Debug.Assert( (year >= MinCalendarYear) && (year <= MaxCalendarYear), "Hijri year is out of range.");
b = HijriYearInfo[year-MinCalendarYear].HijriMonthsLengthFlags;
days += 29 + (b & 0x1);
b = b >> 1;
}
- Contract.Assert((days == 354)||(days == 355), "Hijri year has to be 354 or 355 days.");
+ Debug.Assert((days == 354)||(days == 355), "Hijri year has to be 354 or 355 days.");
return days;
}
using Microsoft.Win32;
using System.Runtime.InteropServices;
using System.Runtime.CompilerServices;
+ using System.Diagnostics;
using System.Diagnostics.Contracts;
// Represents a Globally Unique Identifier.
}
internal void SetFailure(ParseFailureKind failure, string failureMessageID, object failureMessageFormatArgument,
string failureArgumentName, Exception innerException) {
- Contract.Assert(failure != ParseFailureKind.NativeException, "ParseFailureKind.NativeException should not be used with this overload");
+ Debug.Assert(failure != ParseFailureKind.NativeException, "ParseFailureKind.NativeException should not be used with this overload");
m_failure = failure;
m_failureMessageID = failureMessageID;
m_failureMessageFormatArgument = failureMessageFormatArgument;
return m_innerException;
default:
- Contract.Assert(false, "Unknown GuidParseFailure: " + m_failure);
+ Debug.Assert(false, "Unknown GuidParseFailure: " + m_failure);
return new FormatException(Environment.GetResourceString("Format_GuidUnrecognized"));
}
}
//
// StringToShort, StringToInt, and StringToLong are wrappers around COMUtilNative integer parsing routines;
- [System.Security.SecuritySafeCritical]
private static unsafe bool StringToShort(String str, int requiredLength, int flags, out short result, ref GuidResult parseResult) {
return StringToShort(str, null, requiredLength, flags, out result, ref parseResult);
}
- [System.Security.SecuritySafeCritical]
private static unsafe bool StringToShort(String str, ref int parsePos, int requiredLength, int flags, out short result, ref GuidResult parseResult) {
fixed(int * ppos = &parsePos) {
return StringToShort(str, ppos, requiredLength, flags, out result, ref parseResult);
}
}
- [System.Security.SecurityCritical]
private static unsafe bool StringToShort(String str, int* parsePos, int requiredLength, int flags, out short result, ref GuidResult parseResult) {
result = 0;
int x;
return retValue;
}
- [System.Security.SecuritySafeCritical]
private static unsafe bool StringToInt(String str, int requiredLength, int flags, out int result, ref GuidResult parseResult) {
return StringToInt(str, null, requiredLength, flags, out result, ref parseResult);
}
- [System.Security.SecuritySafeCritical]
private static unsafe bool StringToInt(String str, ref int parsePos, int requiredLength, int flags, out int result, ref GuidResult parseResult) {
fixed(int * ppos = &parsePos) {
return StringToInt(str, ppos, requiredLength, flags, out result, ref parseResult);
}
}
- [System.Security.SecurityCritical]
private static unsafe bool StringToInt(String str, int* parsePos, int requiredLength, int flags, out int result, ref GuidResult parseResult) {
result = 0;
}
return true;
}
- [System.Security.SecuritySafeCritical]
private static unsafe bool StringToLong(String str, int flags, out long result, ref GuidResult parseResult) {
return StringToLong(str, null, flags, out result, ref parseResult);
}
- [System.Security.SecuritySafeCritical]
private static unsafe bool StringToLong(String str, ref int parsePos, int flags, out long result, ref GuidResult parseResult) {
fixed(int * ppos = &parsePos) {
return StringToLong(str, ppos, flags, out result, ref parseResult);
}
}
- [System.Security.SecuritySafeCritical]
private static unsafe bool StringToLong(String str, int* parsePos, int flags, out long result, ref GuidResult parseResult) {
result = 0;
return ToString("D",null);
}
- [System.Security.SecuritySafeCritical]
public unsafe override int GetHashCode()
{
// Simply XOR all the bits of the GUID 32 bits at a time.
// This will create a new guid. Since we've now decided that constructors should 0-init,
// we need a method that allows users to create a guid.
- [System.Security.SecuritySafeCritical] // auto-generated
public static Guid NewGuid() {
// CoCreateGuid should never return Guid.Empty, since it attempts to maintain some
// uniqueness guarantees. It should also never return a known GUID, but it's unclear
return (char) ((a > 9) ? a - 10 + 0x61 : a + 0x30);
}
- [System.Security.SecurityCritical]
unsafe private static int HexsToChars(char* guidChars, int offset, int a, int b)
{
return HexsToChars(guidChars, offset, a, b, false);
}
- [System.Security.SecurityCritical]
unsafe private static int HexsToChars(char* guidChars, int offset, int a, int b, bool hex)
{
if (hex) {
// IFormattable interface
// We currently ignore provider
- [System.Security.SecuritySafeCritical]
public String ToString(String format, IFormatProvider provider)
{
if (format == null || format.Length == 0)
using System.Runtime.Versioning;
using System.Runtime.CompilerServices;
- [System.Security.SecurityCritical]
internal class AppDomainPauseManager
{
- [System.Security.SecurityCritical]
public AppDomainPauseManager()
{
isPaused = false;
}
- [System.Security.SecurityCritical]
static AppDomainPauseManager()
{
}
static readonly AppDomainPauseManager instance = new AppDomainPauseManager();
internal static AppDomainPauseManager Instance
{
- [System.Security.SecurityCritical]
get { return instance; }
}
// FAS: IAppDomainPauseConsumer interface implementation
// currently there is nothing we do here as the implementation
// of updating pause times have been moved to native CorHost2
- [System.Security.SecurityCritical]
public void Pausing()
{
}
- [System.Security.SecurityCritical]
public void Paused()
{
- Contract.Assert(!isPaused);
+ Debug.Assert(!isPaused);
if(ResumeEvent == null)
ResumeEvent = new ManualResetEvent(false);
isPaused = true;
}
- [System.Security.SecurityCritical]
public void Resuming()
{
- Contract.Assert(isPaused);
+ Debug.Assert(isPaused);
isPaused = false;
ResumeEvent.Set();
}
- [System.Security.SecurityCritical]
public void Resumed()
{
Timer.Resume();
internal static bool IsPaused
{
- [System.Security.SecurityCritical]
get { return isPaused; }
}
internal static ManualResetEvent ResumeEvent
{
- [System.Security.SecurityCritical]
get;
- [System.Security.SecurityCritical]
set;
}
}
using System.Runtime;
using System.Text;
using System.Globalization;
+ using System.Diagnostics;
using System.Diagnostics.Contracts;
using System.Security;
m_isMemoryStream = (m_stream.GetType() == typeof(MemoryStream));
m_leaveOpen = leaveOpen;
- Contract.Assert(m_decoder!=null, "[BinaryReader.ctor]m_decoder!=null");
+ Debug.Assert(m_decoder!=null, "[BinaryReader.ctor]m_decoder!=null");
}
public virtual Stream BaseStream {
if (m_stream==null) __Error.FileNotOpen();
// read directly from MemoryStream buffer
MemoryStream mStream = m_stream as MemoryStream;
- Contract.Assert(mStream != null, "m_stream as MemoryStream != null");
+ Debug.Assert(mStream != null, "m_stream as MemoryStream != null");
return mStream.InternalReadInt32();
}
return ((ulong)hi) << 32 | lo;
}
- [System.Security.SecuritySafeCritical] // auto-generated
public virtual unsafe float ReadSingle() {
FillBuffer(4);
uint tmpBuffer = (uint)(m_buffer[0] | m_buffer[1] << 8 | m_buffer[2] << 16 | m_buffer[3] << 24);
return *((float*)&tmpBuffer);
}
- [System.Security.SecuritySafeCritical] // auto-generated
public virtual unsafe double ReadDouble() {
FillBuffer(8);
uint lo = (uint)(m_buffer[0] | m_buffer[1] << 8 |
return StringBuilderCache.GetStringAndRelease(sb);
}
- [SecuritySafeCritical]
public virtual int Read(char[] buffer, int index, int count) {
if (buffer==null) {
throw new ArgumentNullException(nameof(buffer), Environment.GetResourceString("ArgumentNull_Buffer"));
return InternalReadChars(buffer, index, count);
}
- [SecurityCritical]
private int InternalReadChars(char[] buffer, int index, int count) {
Contract.Requires(buffer != null);
Contract.Requires(index >= 0 && count >= 0);
- Contract.Assert(m_stream != null);
+ Debug.Assert(m_stream != null);
int numBytes = 0;
int charsRemaining = count;
if (m_isMemoryStream)
{
MemoryStream mStream = m_stream as MemoryStream;
- Contract.Assert(mStream != null, "m_stream as MemoryStream != null");
+ Debug.Assert(mStream != null, "m_stream as MemoryStream != null");
position = mStream.InternalGetPosition();
numBytes = mStream.InternalEmulateRead(numBytes);
return (count - charsRemaining);
}
- Contract.Assert(byteBuffer != null, "expected byteBuffer to be non-null");
+ Debug.Assert(byteBuffer != null, "expected byteBuffer to be non-null");
checked
{
}
// this should never fail
- Contract.Assert(charsRemaining >= 0, "We read too many characters.");
+ Debug.Assert(charsRemaining >= 0, "We read too many characters.");
// we may have read fewer than the number of characters requested if end of stream reached
// or if the encoding makes the char count too big for the buffer (e.g. fallback sequence)
return -1;
}
- Contract.Assert(numBytes == 1 || numBytes == 2, "BinaryReader::InternalReadOneChar assumes it's reading one or 2 bytes only.");
+ Debug.Assert(numBytes == 1 || numBytes == 2, "BinaryReader::InternalReadOneChar assumes it's reading one or 2 bytes only.");
try {
throw;
}
- Contract.Assert(charsRead < 2, "InternalReadOneChar - assuming we only got 0 or 1 char, not 2!");
+ Debug.Assert(charsRead < 2, "InternalReadOneChar - assuming we only got 0 or 1 char, not 2!");
// Console.WriteLine("That became: " + charsRead + " characters.");
}
if (charsRead == 0)
return m_singleChar[0];
}
- [SecuritySafeCritical]
public virtual char[] ReadChars(int count) {
if (count<0) {
throw new ArgumentOutOfRangeException(nameof(count), Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
using System.Runtime;
using System.Runtime.Serialization;
using System.Text;
+using System.Diagnostics;
using System.Diagnostics.Contracts;
namespace System.IO {
// give unique encodings.
//
[Serializable]
-[System.Runtime.InteropServices.ComVisible(true)]
+ [System.Runtime.InteropServices.ComVisible(true)]
public class BinaryWriter : IDisposable
{
public static readonly BinaryWriter Null = new BinaryWriter();
[OptionalField] // New in .NET FX 4.5. False is the right default value.
private bool _leaveOpen;
-#if !FEATURE_CORECLR
- // This field should never have been serialized and has not been used since before v2.0.
- // However, this type is serializable, and we need to keep the field name around when deserializing.
- // Also, we'll make .NET FX 4.5 not break if it's missing.
-#pragma warning disable 169
- [OptionalField]
- private char[] _tmpOneCharBuffer;
-#pragma warning restore 169
-#endif
-
// Perf optimization stuff
private byte[] _largeByteBuffer; // temp space for writing chars.
private int _maxChars; // max # of chars we can put in _largeByteBuffer
// advanced by two.
// Note this method cannot handle surrogates properly in UTF-8.
//
- [System.Security.SecuritySafeCritical] // auto-generated
public unsafe virtual void Write(char ch) {
if (Char.IsSurrogate(ch))
throw new ArgumentException(Environment.GetResourceString("Arg_SurrogatesNotAllowedAsSingleChar"));
Contract.EndContractBlock();
- Contract.Assert(_encoding.GetMaxByteCount(1) <= 16, "_encoding.GetMaxByteCount(1) <= 16)");
+ Debug.Assert(_encoding.GetMaxByteCount(1) <= 16, "_encoding.GetMaxByteCount(1) <= 16)");
int numBytes = 0;
fixed(byte * pBytes = _buffer) {
numBytes = _encoder.GetBytes(&ch, 1, pBytes, _buffer.Length, flush: true);
// Writes a double to this stream. The current position of the stream is
// advanced by eight.
//
- [System.Security.SecuritySafeCritical] // auto-generated
public unsafe virtual void Write(double value)
{
ulong TmpValue = *(ulong *)&value;
// Writes a float to this stream. The current position of the stream is
// advanced by four.
//
- [System.Security.SecuritySafeCritical] // auto-generated
public unsafe virtual void Write(float value)
{
uint TmpValue = *(uint *)&value;
// a four-byte unsigned integer, and then writes that many characters
// to the stream.
//
- [System.Security.SecuritySafeCritical] // auto-generated
public unsafe virtual void Write(String value)
{
if (value==null)
if (len <= _largeByteBuffer.Length)
{
- //Contract.Assert(len == _encoding.GetBytes(chars, 0, chars.Length, _largeByteBuffer, 0), "encoding's GetByteCount & GetBytes gave different answers! encoding type: "+_encoding.GetType().Name);
+ //Debug.Assert(len == _encoding.GetBytes(chars, 0, chars.Length, _largeByteBuffer, 0), "encoding's GetByteCount & GetBytes gave different answers! encoding type: "+_encoding.GetType().Name);
_encoding.GetBytes(value, 0, value.Length, _largeByteBuffer, 0);
OutStream.Write(_largeByteBuffer, 0, len);
}
}
#if _DEBUG
totalBytes += byteLen;
- Contract.Assert (totalBytes <= len && byteLen <= _largeByteBuffer.Length, "BinaryWriter::Write(String) - More bytes encoded than expected!");
+ Debug.Assert (totalBytes <= len && byteLen <= _largeByteBuffer.Length, "BinaryWriter::Write(String) - More bytes encoded than expected!");
#endif
OutStream.Write(_largeByteBuffer, 0, byteLen);
charStart += charCount;
numLeft -= charCount;
}
#if _DEBUG
- Contract.Assert(totalBytes == len, "BinaryWriter::Write(String) - Didn't write out all the bytes!");
+ Debug.Assert(totalBytes == len, "BinaryWriter::Write(String) - Didn't write out all the bytes!");
#endif
}
}
**
===========================================================*/
-using System;
-using System.Collections;
using System.Collections.Generic;
using System.Security;
using System.Security.Permissions;
using Microsoft.Win32;
using Microsoft.Win32.SafeHandles;
-using System.Text;
using System.Runtime.InteropServices;
-using System.Globalization;
-using System.Runtime.Versioning;
+using System.Diagnostics;
using System.Diagnostics.Contracts;
-using System.Threading;
-#if FEATURE_MACL
-using System.Security.AccessControl;
-#endif
-
-namespace System.IO {
+namespace System.IO
+{
[ComVisible(true)]
public static class Directory {
public static DirectoryInfo GetParent(String path)
return new DirectoryInfo(s);
}
- [System.Security.SecuritySafeCritical]
public static DirectoryInfo CreateDirectory(String path) {
if (path == null)
throw new ArgumentNullException(nameof(path));
return InternalCreateDirectoryHelper(path, true);
}
- [System.Security.SecurityCritical]
internal static DirectoryInfo UnsafeCreateDirectory(String path)
{
if (path == null)
return InternalCreateDirectoryHelper(path, false);
}
- [System.Security.SecurityCritical]
internal static DirectoryInfo InternalCreateDirectoryHelper(String path, bool checkHost)
{
Contract.Requires(path != null);
// a demand at every level.
String demandDir = GetDemandDir(fullPath, true);
-#if FEATURE_CORECLR
if (checkHost)
{
FileSecurityState state = new FileSecurityState(FileSecurityStateAccess.Read, path, demandDir);
state.EnsureState(); // do the check on the AppDomainManager to make sure this is allowed
}
-#else
- FileIOPermission.QuickDemand(FileIOPermissionAccess.Read, demandDir, false, false);
-#endif
InternalCreateDirectory(fullPath, path, null, checkHost);
return new DirectoryInfo(fullPath, false);
}
-#if FEATURE_MACL
- [System.Security.SecuritySafeCritical] // auto-generated
- public static DirectoryInfo CreateDirectory(String path, DirectorySecurity directorySecurity) {
- if (path==null)
- throw new ArgumentNullException(nameof(path));
- if (path.Length == 0)
- throw new ArgumentException(Environment.GetResourceString("Argument_PathEmpty"));
- Contract.EndContractBlock();
-
- String fullPath = Path.GetFullPathInternal(path);
-
- // You need read access to the directory to be returned back and write access to all the directories
- // that you need to create. If we fail any security checks we will not create any directories at all.
- // We attempt to create directories only after all the security checks have passed. This is avoid doing
- // a demand at every level.
- String demandDir = GetDemandDir(fullPath, true);
- FileIOPermission.QuickDemand(FileIOPermissionAccess.Read, demandDir, false, false );
-
- InternalCreateDirectory(fullPath, path, directorySecurity);
-
- return new DirectoryInfo(fullPath, false);
- }
-#endif // FEATURE_MACL
-
// Input to this method should already be fullpath. This method will ensure that we append
// the trailing slash only when appropriate and when thisDirOnly is specified append a "."
// at the end of the path to indicate that the demand is only for the fullpath and not
}
- [System.Security.SecuritySafeCritical]
internal unsafe static void InternalCreateDirectory(String fullPath, String path, Object dirSecurityObj, bool checkHost)
{
-#if FEATURE_MACL
- DirectorySecurity dirSecurity = (DirectorySecurity)dirSecurityObj;
-#endif // FEATURE_MACL
-
int length = fullPath.Length;
// We need to trim the trailing slash or the code will try to create 2 directories of the same name.
int count = stackDir.Count;
- if (stackDir.Count != 0
-#if FEATURE_CAS_POLICY
- // All demands in full trust domains are no-ops, so skip
- //
- // The full path went through validity checks by being passed through FileIOPermissions already.
- // As a sub string of the full path can't fail the checks if the full path passes.
- && !CodeAccessSecurityEngine.QuickCheckForAllDemands()
-#endif
- )
+ if (stackDir.Count != 0)
{
String[] securityList = new String[stackDir.Count];
stackDir.CopyTo(securityList, 0);
securityList[j] += "\\."; // leaf will never have a slash at the end
// Security check for all directories not present only.
-#if FEATURE_MACL
- AccessControlActions control = (dirSecurity == null) ? AccessControlActions.None : AccessControlActions.Change;
- FileIOPermission.QuickDemand(FileIOPermissionAccess.Write, control, securityList, false, false);
-#else
-#if FEATURE_CORECLR
if (checkHost)
{
foreach (String demandPath in securityList)
state.EnsureState();
}
}
-#else
- FileIOPermission.QuickDemand(FileIOPermissionAccess.Write, securityList, false, false);
-#endif
-#endif //FEATURE_MACL
}
// If we were passed a DirectorySecurity, convert it to a security
// descriptor and set it in he call to CreateDirectory.
Win32Native.SECURITY_ATTRIBUTES secAttrs = null;
-#if FEATURE_MACL
- if (dirSecurity != null) {
- secAttrs = new Win32Native.SECURITY_ATTRIBUTES();
- secAttrs.nLength = (int)Marshal.SizeOf(secAttrs);
-
- // For ACL's, get the security descriptor from the FileSecurity.
- byte[] sd = dirSecurity.GetSecurityDescriptorBinaryForm();
- byte * bytesOnStack = stackalloc byte[sd.Length];
- Buffer.Memcpy(bytesOnStack, 0, sd, 0, sd.Length);
- secAttrs.pSecurityDescriptor = bytesOnStack;
- }
-#endif
bool r = true;
int firstError = 0;
firstError = currentError;
// Give the user a nice error message, but don't leak path information.
try {
-#if FEATURE_CORECLR
if (checkHost)
{
FileSecurityState state = new FileSecurityState(FileSecurityStateAccess.PathDiscovery, String.Empty, GetDemandDir(name, true));
state.EnsureState();
}
-#else
- FileIOPermission.QuickDemand(FileIOPermissionAccess.PathDiscovery, GetDemandDir(name, true));
-#endif // FEATURE_CORECLR
errorString = name;
}
catch(SecurityException) {}
// Your application must have Read permission to the directory's
// contents.
//
- [System.Security.SecuritySafeCritical] // auto-generated
public static bool Exists(String path)
{
return InternalExistsHelper(path, true);
}
- [System.Security.SecurityCritical]
internal static bool UnsafeExists(String path)
{
return InternalExistsHelper(path, false);
}
- [System.Security.SecurityCritical]
internal static bool InternalExistsHelper(String path, bool checkHost) {
try
{
String fullPath = Path.GetFullPath(path);
String demandPath = GetDemandDir(fullPath, true);
-#if FEATURE_CORECLR
if (checkHost)
{
FileSecurityState state = new FileSecurityState(FileSecurityStateAccess.Read, path, demandPath);
state.EnsureState();
}
-#else
- FileIOPermission.QuickDemand(FileIOPermissionAccess.Read, demandPath, false, false);
-#endif
-
return InternalExists(fullPath);
}
catch (IOException) { }
catch (UnauthorizedAccessException)
{
- Contract.Assert(false, "Ignore this assert and send a repro to Microsoft. This assert was tracking purposes only.");
+ Debug.Assert(false, "Ignore this assert and send a repro to Microsoft. This assert was tracking purposes only.");
}
return false;
}
// Determine whether path describes an existing directory
// on disk, avoiding security checks.
- [System.Security.SecurityCritical] // auto-generated
internal static bool InternalExists(String path) {
int lastError = Win32Native.ERROR_SUCCESS;
return InternalExists(path, out lastError);
// Determine whether path describes an existing directory
// on disk, avoiding security checks.
- [System.Security.SecurityCritical] // auto-generated
internal static bool InternalExists(String path, out int lastError) {
Win32Native.WIN32_FILE_ATTRIBUTE_DATA data = new Win32Native.WIN32_FILE_ATTRIBUTE_DATA();
lastError = File.FillAttributeInfo(path, ref data, false, true);
&& ((data.fileAttributes & Win32Native.FILE_ATTRIBUTE_DIRECTORY) != 0);
}
-#if !FEATURE_CORECLR
- public static void SetCreationTime(String path,DateTime creationTime)
- {
- SetCreationTimeUtc(path, creationTime.ToUniversalTime());
- }
-
- [System.Security.SecuritySafeCritical] // auto-generated
- public unsafe static void SetCreationTimeUtc(String path,DateTime creationTimeUtc)
- {
- using (SafeFileHandle handle = Directory.OpenHandle(path)) {
- Win32Native.FILE_TIME fileTime = new Win32Native.FILE_TIME(creationTimeUtc.ToFileTimeUtc());
- bool r = Win32Native.SetFileTime(handle, &fileTime, null, null);
- if (!r)
- {
- int errorCode = Marshal.GetLastWin32Error();
- __Error.WinIOError(errorCode, path);
- }
- }
- }
-#endif // !FEATURE_CORECLR
-
public static DateTime GetCreationTime(String path)
{
return File.GetCreationTime(path);
return File.GetCreationTimeUtc(path);
}
-#if !FEATURE_CORECLR
- public static void SetLastWriteTime(String path,DateTime lastWriteTime)
- {
- SetLastWriteTimeUtc(path, lastWriteTime.ToUniversalTime());
- }
-
- [System.Security.SecuritySafeCritical] // auto-generated
- public unsafe static void SetLastWriteTimeUtc(String path,DateTime lastWriteTimeUtc)
- {
- using (SafeFileHandle handle = Directory.OpenHandle(path)) {
- Win32Native.FILE_TIME fileTime = new Win32Native.FILE_TIME(lastWriteTimeUtc.ToFileTimeUtc());
- bool r = Win32Native.SetFileTime(handle, null, null, &fileTime);
- if (!r)
- {
- int errorCode = Marshal.GetLastWin32Error();
- __Error.WinIOError(errorCode, path);
- }
- }
- }
-#endif // !FEATURE_CORECLR
-
public static DateTime GetLastWriteTime(String path)
{
return File.GetLastWriteTime(path);
return File.GetLastWriteTimeUtc(path);
}
-#if !FEATURE_CORECLR
- public static void SetLastAccessTime(String path,DateTime lastAccessTime)
- {
- SetLastAccessTimeUtc(path, lastAccessTime.ToUniversalTime());
- }
-
- [System.Security.SecuritySafeCritical] // auto-generated
- public unsafe static void SetLastAccessTimeUtc(String path,DateTime lastAccessTimeUtc)
- {
- using (SafeFileHandle handle = Directory.OpenHandle(path)) {
- Win32Native.FILE_TIME fileTime = new Win32Native.FILE_TIME(lastAccessTimeUtc.ToFileTimeUtc());
- bool r = Win32Native.SetFileTime(handle, null, &fileTime, null);
- if (!r)
- {
- int errorCode = Marshal.GetLastWin32Error();
- __Error.WinIOError(errorCode, path);
- }
- }
- }
-#endif // !FEATURE_CORECLR
-
public static DateTime GetLastAccessTime(String path)
{
return File.GetLastAccessTime(path);
public static DateTime GetLastAccessTimeUtc(String path)
{
return File.GetLastAccessTimeUtc(path);
- }
-
-#if FEATURE_MACL
- public static DirectorySecurity GetAccessControl(String path)
- {
- return new DirectorySecurity(path, AccessControlSections.Access | AccessControlSections.Owner | AccessControlSections.Group);
}
- public static DirectorySecurity GetAccessControl(String path, AccessControlSections includeSections)
- {
- return new DirectorySecurity(path, includeSections);
- }
-
- [System.Security.SecuritySafeCritical] // auto-generated
- public static void SetAccessControl(String path, DirectorySecurity directorySecurity)
- {
- if (directorySecurity == null)
- throw new ArgumentNullException(nameof(directorySecurity));
- Contract.EndContractBlock();
-
- String fullPath = Path.GetFullPathInternal(path);
- directorySecurity.Persist(fullPath);
- }
-#endif
-
// Returns an array of filenames in the DirectoryInfo specified by path
public static String[] GetFiles(String path)
{
return InternalGetFileDirectoryNames(path, path, searchPattern, true, false, searchOption, true);
}
- [System.Security.SecurityCritical]
internal static String[] UnsafeGetFiles(String path, String searchPattern, SearchOption searchOption)
{
Contract.Requires(path != null);
return InternalGetFileDirectoryNames(path, path, searchPattern, false, true, searchOption, true);
}
- [System.Security.SecurityCritical]
internal static String[] UnsafeGetDirectories(String path, String searchPattern, SearchOption searchOption)
{
Contract.Requires(path != null);
//
// Your application must have System Info permission.
//
- [System.Security.SecuritySafeCritical] // auto-generated
public static String[] GetLogicalDrives()
{
Contract.Ensures(Contract.Result<String[]>() != null);
return result;
}
- [System.Security.SecuritySafeCritical]
public static String GetDirectoryRoot(String path) {
if (path==null)
throw new ArgumentNullException(nameof(path));
string root = fullPath.Substring(0, PathInternal.GetRootLength(fullPath));
string demandPath = GetDemandDir(root, true);
-#if FEATURE_CORECLR
FileSecurityState state = new FileSecurityState(FileSecurityStateAccess.PathDiscovery, path, demandPath);
state.EnsureState();
-#else
- FileIOPermission.QuickDemand(FileIOPermissionAccess.PathDiscovery, demandPath, false, false);
-#endif
-
+
return root;
}
**Arguments: The current DirectoryInfo to which to switch to the setter.
**Exceptions:
==============================================================================*/
- [System.Security.SecuritySafeCritical]
public static String GetCurrentDirectory()
{
return InternalGetCurrentDirectory(true);
}
- [System.Security.SecurityCritical]
internal static String UnsafeGetCurrentDirectory()
{
return InternalGetCurrentDirectory(false);
}
- [System.Security.SecuritySafeCritical]
private static string InternalGetCurrentDirectory(bool checkHost)
{
string currentDirectory = NewGetCurrentDirectory();
return currentDirectory;
}
- [System.Security.SecurityCritical]
private static string NewGetCurrentDirectory()
{
// Start with a buffer the size of MAX_PATH
}
}
- [System.Security.SecurityCritical] // auto-generated
public static void SetCurrentDirectory(String path)
{
if (path==null)
}
}
- [System.Security.SecuritySafeCritical]
public static void Move(String sourceDirName,String destDirName) {
InternalMove(sourceDirName, destDirName, true);
}
- [System.Security.SecurityCritical]
internal static void UnsafeMove(String sourceDirName,String destDirName) {
InternalMove(sourceDirName, destDirName, false);
}
- [System.Security.SecurityCritical]
private static void InternalMove(String sourceDirName,String destDirName,bool checkHost) {
if (sourceDirName==null)
throw new ArgumentNullException(nameof(sourceDirName));
if (PathInternal.IsDirectoryTooLong(destPath))
throw new PathTooLongException(Environment.GetResourceString("IO.PathTooLong"));
-#if FEATURE_CORECLR
if (checkHost) {
FileSecurityState sourceState = new FileSecurityState(FileSecurityStateAccess.Write | FileSecurityStateAccess.Read, sourceDirName, sourcePath);
FileSecurityState destState = new FileSecurityState(FileSecurityStateAccess.Write, destDirName, destPath);
sourceState.EnsureState();
destState.EnsureState();
}
-#else
- FileIOPermission.QuickDemand(FileIOPermissionAccess.Write | FileIOPermissionAccess.Read, sourcePath, false, false);
- FileIOPermission.QuickDemand(FileIOPermissionAccess.Write, destPath, false, false);
-#endif
if (String.Compare(sourcePath, destPath, StringComparison.OrdinalIgnoreCase) == 0)
throw new IOException(Environment.GetResourceString("IO.IO_SourceDestMustBeDifferent"));
}
}
- [System.Security.SecuritySafeCritical]
public static void Delete(String path)
{
String fullPath = Path.GetFullPath(path);
Delete(fullPath, path, false, true);
}
- [System.Security.SecuritySafeCritical]
public static void Delete(String path, bool recursive)
{
String fullPath = Path.GetFullPath(path);
Delete(fullPath, path, recursive, true);
}
- [System.Security.SecurityCritical]
internal static void UnsafeDelete(String path, bool recursive)
{
String fullPath = Path.GetFullPath(path);
// Called from DirectoryInfo as well. FullPath is fully qualified,
// while the user path is used for feedback in exceptions.
- [System.Security.SecurityCritical] // auto-generated
internal static void Delete(String fullPath, String userPath, bool recursive, bool checkHost)
{
String demandPath;
// If not recursive, do permission check only on this directory
// else check for the whole directory structure rooted below
demandPath = GetDemandDir(fullPath, !recursive);
-
-#if FEATURE_CORECLR
+
if (checkHost)
{
FileSecurityState state = new FileSecurityState(FileSecurityStateAccess.Write, userPath, demandPath);
state.EnsureState();
}
-#else
- // Make sure we have write permission to this directory
- new FileIOPermission(FileIOPermissionAccess.Write, new String[] { demandPath }, false, false ).Demand();
-#endif
// Do not recursively delete through reparse points. Perhaps in a
// future version we will add a new flag to control this behavior,
// Note that fullPath is fully qualified, while userPath may be
// relative. Use userPath for all exception messages to avoid leaking
// fully qualified path information.
- [System.Security.SecurityCritical] // auto-generated
private static void DeleteHelper(String fullPath, String userPath, bool recursive, bool throwOnTopLevelDirectoryNotFound)
{
bool r;
}
}
-#if !FEATURE_CORECLR
- // WinNT only. Win9x this code will not work.
- [System.Security.SecurityCritical] // auto-generated
- private static SafeFileHandle OpenHandle(String path)
- {
- String fullPath = Path.GetFullPathInternal(path);
- String root = Path.GetPathRoot(fullPath);
- if (root == fullPath && root[1] == Path.VolumeSeparatorChar)
- throw new ArgumentException(Environment.GetResourceString("Arg_PathIsVolume"));
-
-#if !FEATURE_CORECLR
- FileIOPermission.QuickDemand(FileIOPermissionAccess.Write, GetDemandDir(fullPath, true), false, false);
-#endif
-
- SafeFileHandle handle = Win32Native.SafeCreateFile (
- fullPath,
- GENERIC_WRITE,
- (FileShare) (FILE_SHARE_WRITE|FILE_SHARE_DELETE),
- null,
- FileMode.Open,
- FILE_FLAG_BACKUP_SEMANTICS,
- IntPtr.Zero
- );
-
- if (handle.IsInvalid) {
- int hr = Marshal.GetLastWin32Error();
- __Error.WinIOError(hr, fullPath);
- }
- return handle;
- }
-#endif // !FEATURE_CORECLR
-
- private const int FILE_ATTRIBUTE_DIRECTORY = 0x00000010;
+ private const int FILE_ATTRIBUTE_DIRECTORY = 0x00000010;
private const int GENERIC_WRITE = unchecked((int)0x40000000);
private const int FILE_SHARE_WRITE = 0x00000002;
private const int FILE_SHARE_DELETE = 0x00000004;
using System.Collections;
using System.Collections.Generic;
using System.Security;
-#if FEATURE_MACL
-using System.Security.AccessControl;
-#endif
using System.Security.Permissions;
using Microsoft.Win32;
using System.Text;
using System.Globalization;
using System.Runtime.Serialization;
using System.Runtime.Versioning;
+using System.Diagnostics;
using System.Diagnostics.Contracts;
-namespace System.IO {
+namespace System.IO
+{
[Serializable]
[ComVisible(true)]
- public sealed class DirectoryInfo : FileSystemInfo {
+ public sealed class DirectoryInfo : FileSystemInfo
+ {
private String[] demandDir;
-#if FEATURE_CORECLR
- // Migrating InheritanceDemands requires this default ctor, so we can annotate it.
+ // Migrating InheritanceDemands requires this default ctor, so we can annotate it.
#if FEATURE_CORESYSTEM
- [System.Security.SecurityCritical]
#else
- [System.Security.SecuritySafeCritical]
#endif //FEATURE_CORESYSTEM
private DirectoryInfo(){}
- [System.Security.SecurityCritical]
public static DirectoryInfo UnsafeCreateDirectoryInfo(String path)
{
if (path == null)
di.Init(path, false);
return di;
}
-#endif
- [System.Security.SecuritySafeCritical]
public DirectoryInfo(String path)
{
if (path==null)
Init(path, true);
}
- [System.Security.SecurityCritical]
private void Init(String path, bool checkHost)
{
// Special case "<DriveLetter>:" to point to "<CurrentDirectory>" instead
String fullPath = Path.GetFullPath(path);
demandDir = new String[] {Directory.GetDemandDir(fullPath, true)};
-#if FEATURE_CORECLR
+
if (checkHost)
{
FileSecurityState state = new FileSecurityState(FileSecurityStateAccess.Read, OriginalPath, fullPath);
state.EnsureState();
}
-#else
- new FileIOPermission(FileIOPermissionAccess.Read, demandDir, false, false ).Demand();
-#endif
FullPath = fullPath;
DisplayPath = GetDisplayName(OriginalPath, FullPath);
}
#if FEATURE_CORESYSTEM
- [System.Security.SecuritySafeCritical]
#endif //FEATURE_CORESYSTEM
internal DirectoryInfo(String fullPath, bool junk)
{
- Contract.Assert(PathInternal.GetRootLength(fullPath) > 0, "fullPath must be fully qualified!");
+ Debug.Assert(PathInternal.GetRootLength(fullPath) > 0, "fullPath must be fully qualified!");
// Fast path when we know a DirectoryInfo exists.
OriginalPath = Path.GetFileName(fullPath);
demandDir = new String[] {Directory.GetDemandDir(fullPath, true)};
}
- [System.Security.SecurityCritical] // auto-generated
private DirectoryInfo(SerializationInfo info, StreamingContext context) : base(info, context)
{
-#if !FEATURE_CORECLR
- demandDir = new String[] {Directory.GetDemandDir(FullPath, true)};
- new FileIOPermission(FileIOPermissionAccess.Read, demandDir, false, false ).Demand();
-#endif
DisplayPath = GetDisplayName(OriginalPath, FullPath);
}
- public override String Name {
+ public override String Name
+ {
get
{
-#if FEATURE_CORECLR
// DisplayPath is dir name for coreclr
return DisplayPath;
-#else
- // Return just dir name
- return GetDirName(FullPath);
-#endif
}
}
public DirectoryInfo Parent {
- [System.Security.SecuritySafeCritical]
get {
String parentName;
// FullPath might be either "c:\bar" or "c:\bar\". Handle
if (parentName==null)
return null;
DirectoryInfo dir = new DirectoryInfo(parentName,false);
-#if FEATURE_CORECLR
+
FileSecurityState state = new FileSecurityState(FileSecurityStateAccess.PathDiscovery | FileSecurityStateAccess.Read, String.Empty, dir.demandDir[0]);
state.EnsureState();
-#else
- new FileIOPermission(FileIOPermissionAccess.PathDiscovery | FileIOPermissionAccess.Read, dir.demandDir, false, false).Demand();
-#endif
+
return dir;
}
}
-
-#if FEATURE_CORECLR
- [System.Security.SecuritySafeCritical]
-#endif
public DirectoryInfo CreateSubdirectory(String path) {
if (path == null)
throw new ArgumentNullException(nameof(path));
return CreateSubdirectory(path, null);
}
-#if FEATURE_MACL
- [System.Security.SecuritySafeCritical] // auto-generated
- public DirectoryInfo CreateSubdirectory(String path, DirectorySecurity directorySecurity)
- {
- return CreateSubdirectoryHelper(path, directorySecurity);
- }
-#else // FEATURE_MACL
- #if FEATURE_CORECLR
- [System.Security.SecurityCritical] // auto-generated
- #endif
public DirectoryInfo CreateSubdirectory(String path, Object directorySecurity)
{
if (path == null)
return CreateSubdirectoryHelper(path, directorySecurity);
}
-#endif // FEATURE_MACL
- [System.Security.SecurityCritical] // auto-generated
private DirectoryInfo CreateSubdirectoryHelper(String path, Object directorySecurity)
{
Contract.Requires(path != null);
// Ensure we have permission to create this subdirectory.
String demandDirForCreation = Directory.GetDemandDir(fullPath, true);
-#if FEATURE_CORECLR
FileSecurityState state = new FileSecurityState(FileSecurityStateAccess.Write, OriginalPath, demandDirForCreation);
state.EnsureState();
-#else
- new FileIOPermission(FileIOPermissionAccess.Write, new String[] { demandDirForCreation }, false, false).Demand();
-#endif
Directory.InternalCreateDirectory(fullPath, path, directorySecurity);
Directory.InternalCreateDirectory(FullPath, OriginalPath, null, true);
}
-#if FEATURE_MACL
- public void Create(DirectorySecurity directorySecurity)
- {
- Directory.InternalCreateDirectory(FullPath, OriginalPath, directorySecurity, true);
- }
-#endif
-
// Tests if the given path refers to an existing DirectoryInfo on disk.
//
// Your application must have Read permission to the directory's
// contents.
//
public override bool Exists {
- [System.Security.SecuritySafeCritical] // auto-generated
get
{
try
}
}
}
-
-#if FEATURE_MACL
- public DirectorySecurity GetAccessControl()
- {
- return Directory.GetAccessControl(FullPath, AccessControlSections.Access | AccessControlSections.Owner | AccessControlSections.Group);
- }
-
- public DirectorySecurity GetAccessControl(AccessControlSections includeSections)
- {
- return Directory.GetAccessControl(FullPath, includeSections);
- }
-
- public void SetAccessControl(DirectorySecurity directorySecurity)
- {
- Directory.SetAccessControl(FullPath, directorySecurity);
- }
-#endif
// Returns an array of Files in the current DirectoryInfo matching the
// given search criteria (ie, "*.txt").
//
public DirectoryInfo Root {
- [System.Security.SecuritySafeCritical]
get
{
String demandPath;
String rootPath = FullPath.Substring(0, rootLength);
demandPath = Directory.GetDemandDir(rootPath, true);
-#if FEATURE_CORECLR
FileSecurityState sourceState = new FileSecurityState(FileSecurityStateAccess.PathDiscovery, String.Empty, demandPath);
sourceState.EnsureState();
-#else
- new FileIOPermission(FileIOPermissionAccess.PathDiscovery, new String[] { demandPath }, false, false).Demand();
-#endif
+
return new DirectoryInfo(rootPath);
}
}
- [System.Security.SecuritySafeCritical]
public void MoveTo(String destDirName) {
if (destDirName==null)
throw new ArgumentNullException(nameof(destDirName));
if (destDirName.Length==0)
throw new ArgumentException(Environment.GetResourceString("Argument_EmptyFileName"), nameof(destDirName));
Contract.EndContractBlock();
-
-#if FEATURE_CORECLR
+
FileSecurityState sourceState = new FileSecurityState(FileSecurityStateAccess.Write | FileSecurityStateAccess.Read, DisplayPath, Directory.GetDemandDir(FullPath, true));
sourceState.EnsureState();
-#else
- new FileIOPermission(FileIOPermissionAccess.Write | FileIOPermissionAccess.Read, demandDir, false, false).Demand();
-#endif
+
String fullDestDirName = Path.GetFullPath(destDirName);
String demandPath;
if (!fullDestDirName.EndsWith(Path.DirectorySeparatorChar))
// had the ability to read the file contents in the old location,
// but you technically also need read permissions to the new
// location as well, and write is not a true superset of read.
-#if FEATURE_CORECLR
FileSecurityState destState = new FileSecurityState(FileSecurityStateAccess.Write, destDirName, demandPath);
destState.EnsureState();
-#else
- new FileIOPermission(FileIOPermissionAccess.Write | FileIOPermissionAccess.Read, demandPath).Demand();
-#endif
-
+
String fullSourcePath;
if (FullPath.EndsWith(Path.DirectorySeparatorChar))
fullSourcePath = FullPath;
_dataInitialised = -1;
}
- [System.Security.SecuritySafeCritical]
public override void Delete()
{
Directory.Delete(FullPath, OriginalPath, false, true);
}
- [System.Security.SecuritySafeCritical]
public void Delete(bool recursive)
{
Directory.Delete(FullPath, OriginalPath, recursive, true);
private static String GetDisplayName(String originalPath, String fullPath)
{
- Contract.Assert(originalPath != null);
- Contract.Assert(fullPath != null);
+ Debug.Assert(originalPath != null);
+ Debug.Assert(fullPath != null);
String displayName = "";
}
else
{
-#if FEATURE_CORECLR
displayName = GetDirName(fullPath);
-#else
- displayName = originalPath;
-#endif
}
return displayName;
}
private static String GetDirName(String fullPath)
{
- Contract.Assert(fullPath != null);
+ Debug.Assert(fullPath != null);
String dirName = null;
if (fullPath.Length > 3)
private const String NameField = "_name"; // For serialization
- [System.Security.SecuritySafeCritical] // auto-generated
public DriveInfo(String driveName)
{
if (driveName == null)
new FileIOPermission(FileIOPermissionAccess.PathDiscovery, demandPath).Demand();
}
- [System.Security.SecurityCritical] // auto-generated
private DriveInfo(SerializationInfo info, StreamingContext context)
{
// Need to add in a security check here once it has been spec'ed.
}
public DriveType DriveType {
- [System.Security.SecuritySafeCritical] // auto-generated
get {
// GetDriveType can't fail
return (DriveType) Win32Native.GetDriveType(Name);
}
public String DriveFormat {
- [System.Security.SecuritySafeCritical] // auto-generated
get {
const int volNameLen = 50;
StringBuilder volumeName = new StringBuilder(volNameLen);
}
public bool IsReady {
- [System.Security.SecuritySafeCritical] // auto-generated
get {
return Directory.InternalExists(Name);
}
}
public long AvailableFreeSpace {
- [System.Security.SecuritySafeCritical] // auto-generated
get {
long userBytes, totalBytes, freeBytes;
int oldMode = Win32Native.SetErrorMode(Win32Native.SEM_FAILCRITICALERRORS);
}
public long TotalFreeSpace {
- [System.Security.SecuritySafeCritical] // auto-generated
get {
long userBytes, totalBytes, freeBytes;
int oldMode = Win32Native.SetErrorMode(Win32Native.SEM_FAILCRITICALERRORS);
}
public long TotalSize {
- [System.Security.SecuritySafeCritical] // auto-generated
get {
// Don't cache this, to handle variable sized floppy drives
// or other various removable media drives.
// Null is a valid volume label.
public String VolumeLabel {
- [System.Security.SecuritySafeCritical] // auto-generated
get {
// NTFS uses a limit of 32 characters for the volume label,
// as of Windows Server 2003.
}
return volumeName.ToString();
}
- [System.Security.SecuritySafeCritical] // auto-generated
set {
String demandPath = _name + '.';
new FileIOPermission(FileIOPermissionAccess.Write, demandPath).Demand();
#if FEATURE_SERIALIZATION
/// <internalonly/>
- [System.Security.SecurityCritical]
void ISerializable.GetObjectData(SerializationInfo info, StreamingContext context)
{
// No need for an additional security check - everything is public.
**
===========================================================*/
-using System;
using System.Security.Permissions;
-using PermissionSet = System.Security.PermissionSet;
using Win32Native = Microsoft.Win32.Win32Native;
using System.Runtime.InteropServices;
using System.Security;
-#if FEATURE_MACL
-using System.Security.AccessControl;
-#endif
using System.Text;
using Microsoft.Win32.SafeHandles;
using System.Collections.Generic;
-using System.Globalization;
-using System.Runtime.Versioning;
+using System.Diagnostics;
using System.Diagnostics.Contracts;
-
-namespace System.IO {
+
+namespace System.IO
+{
// Class for creating FileStream objects, and some basic file management
// routines such as Delete, etc.
[ComVisible(true)]
InternalCopy(sourceFileName, destFileName, overwrite, true);
}
- [System.Security.SecurityCritical]
internal static void UnsafeCopy(String sourceFileName, String destFileName, bool overwrite) {
if (sourceFileName == null)
throw new ArgumentNullException(nameof(sourceFileName), Environment.GetResourceString("ArgumentNull_FileName"));
/// <devdoc>
/// Note: This returns the fully qualified name of the destination file.
/// </devdoc>
- [System.Security.SecuritySafeCritical]
- internal static String InternalCopy(String sourceFileName, String destFileName, bool overwrite, bool checkHost) {
+ internal static String InternalCopy(String sourceFileName, String destFileName, bool overwrite, bool checkHost)
+ {
Contract.Requires(sourceFileName != null);
Contract.Requires(destFileName != null);
Contract.Requires(sourceFileName.Length > 0);
String fullSourceFileName = Path.GetFullPath(sourceFileName);
String fullDestFileName = Path.GetFullPath(destFileName);
-
-#if FEATURE_CORECLR
+
if (checkHost) {
FileSecurityState sourceState = new FileSecurityState(FileSecurityStateAccess.Read, sourceFileName, fullSourceFileName);
FileSecurityState destState = new FileSecurityState(FileSecurityStateAccess.Write, destFileName, fullDestFileName);
sourceState.EnsureState();
destState.EnsureState();
}
-#else
- FileIOPermission.QuickDemand(FileIOPermissionAccess.Read, fullSourceFileName, false, false);
- FileIOPermission.QuickDemand(FileIOPermissionAccess.Write, fullDestFileName, false, false);
-#endif
-
+
bool r = Win32Native.CopyFile(fullSourceFileName, fullDestFileName, !overwrite);
if (!r) {
// Save Win32 error because subsequent checks will overwrite this HRESULT.
String fileName = destFileName;
if (errorCode != Win32Native.ERROR_FILE_EXISTS) {
-#if !FEATURE_CORECLR
- // For a number of error codes (sharing violation, path
- // not found, etc) we don't know if the problem was with
- // the source or dest file. Try reading the source file.
- using(SafeFileHandle handle = Win32Native.UnsafeCreateFile(fullSourceFileName, GENERIC_READ, FileShare.Read, null, FileMode.Open, 0, IntPtr.Zero)) {
- if (handle.IsInvalid)
- fileName = sourceFileName;
- }
-#endif // !FEATURE_CORECLR
-
if (errorCode == Win32Native.ERROR_ACCESS_DENIED) {
if (Directory.InternalExists(fullDestFileName))
throw new IOException(Environment.GetResourceString("Arg_FileIsDirectory_Name", destFileName), Win32Native.ERROR_ACCESS_DENIED, fullDestFileName);
FileShare.None, bufferSize, options);
}
-#if FEATURE_MACL
- public static FileStream Create(String path, int bufferSize, FileOptions options, FileSecurity fileSecurity) {
- return new FileStream(path, FileMode.Create, FileSystemRights.Read | FileSystemRights.Write,
- FileShare.None, bufferSize, options, fileSecurity);
- }
-#endif
-
// Deletes a file. The file specified by the designated path is deleted.
// If the file does not exist, Delete succeeds without throwing
// an exception.
//
// Your application must have Delete permission to the target file.
//
- [System.Security.SecuritySafeCritical]
public static void Delete(String path) {
if (path == null)
throw new ArgumentNullException(nameof(path));
InternalDelete(path, true);
}
- [System.Security.SecurityCritical]
internal static void UnsafeDelete(String path)
{
if (path == null)
InternalDelete(path, false);
}
- [System.Security.SecurityCritical]
internal static void InternalDelete(String path, bool checkHost)
{
String fullPath = Path.GetFullPath(path);
-#if FEATURE_CORECLR
if (checkHost)
{
FileSecurityState state = new FileSecurityState(FileSecurityStateAccess.Write, path, fullPath);
state.EnsureState();
}
-#else
- // For security check, path should be resolved to an absolute path.
- FileIOPermission.QuickDemand(FileIOPermissionAccess.Write, fullPath, false, false);
-#endif
bool r = Win32Native.DeleteFile(fullPath);
if (!r) {
int hr = Marshal.GetLastWin32Error();
}
- [System.Security.SecuritySafeCritical] // auto-generated
public static void Decrypt(String path)
{
if (path == null)
}
}
- [System.Security.SecuritySafeCritical] // auto-generated
public static void Encrypt(String path)
{
if (path == null)
//
// Your application must have Read permission for the target directory.
//
- [System.Security.SecuritySafeCritical]
public static bool Exists(String path)
{
return InternalExistsHelper(path, true);
}
- [System.Security.SecurityCritical]
internal static bool UnsafeExists(String path)
{
return InternalExistsHelper(path, false);
}
- [System.Security.SecurityCritical]
private static bool InternalExistsHelper(String path, bool checkHost)
{
try
// After normalizing, check whether path ends in directory separator.
// Otherwise, FillAttributeInfo removes it and we may return a false positive.
// GetFullPath should never return null
- Contract.Assert(path != null, "File.Exists: GetFullPath returned null");
+ Debug.Assert(path != null, "File.Exists: GetFullPath returned null");
if (path.Length > 0 && PathInternal.IsDirectorySeparator(path[path.Length - 1]))
{
return false;
}
-#if FEATURE_CORECLR
if (checkHost)
{
FileSecurityState state = new FileSecurityState(FileSecurityStateAccess.Read, String.Empty, path);
state.EnsureState();
}
-#else
- FileIOPermission.QuickDemand(FileIOPermissionAccess.Read, path, false, false);
-#endif
return InternalExists(path);
}
return false;
}
- [System.Security.SecurityCritical] // auto-generated
internal static bool InternalExists(String path) {
Win32Native.WIN32_FILE_ATTRIBUTE_DATA data = new Win32Native.WIN32_FILE_ATTRIBUTE_DATA();
int dataInitialised = FillAttributeInfo(path, ref data, false, true);
return new FileStream(path, mode, access, share);
}
-#if !FEATURE_CORECLR
- public static void SetCreationTime(String path, DateTime creationTime)
- {
- SetCreationTimeUtc(path, creationTime.ToUniversalTime());
- }
-
- [System.Security.SecuritySafeCritical] // auto-generated
- public unsafe static void SetCreationTimeUtc(String path, DateTime creationTimeUtc)
- {
- SafeFileHandle handle;
- using(OpenFile(path, FileAccess.Write, out handle)) {
- Win32Native.FILE_TIME fileTime = new Win32Native.FILE_TIME(creationTimeUtc.ToFileTimeUtc());
- bool r = Win32Native.SetFileTime(handle, &fileTime, null, null);
- if (!r)
- {
- int errorCode = Marshal.GetLastWin32Error();
- __Error.WinIOError(errorCode, path);
- }
- }
- }
-#endif // !FEATURE_CORECLR
-
- [System.Security.SecuritySafeCritical]
public static DateTime GetCreationTime(String path)
{
return InternalGetCreationTimeUtc(path, true).ToLocalTime();
}
- [System.Security.SecuritySafeCritical] // auto-generated
public static DateTime GetCreationTimeUtc(String path)
{
return InternalGetCreationTimeUtc(path, false); // this API isn't exposed in Silverlight
}
- [System.Security.SecurityCritical]
private static DateTime InternalGetCreationTimeUtc(String path, bool checkHost)
{
String fullPath = Path.GetFullPath(path);
-#if FEATURE_CORECLR
+
if (checkHost)
{
FileSecurityState state = new FileSecurityState(FileSecurityStateAccess.Read, path, fullPath);
state.EnsureState();
}
-#else
- FileIOPermission.QuickDemand(FileIOPermissionAccess.Read, fullPath, false, false);
-#endif
Win32Native.WIN32_FILE_ATTRIBUTE_DATA data = new Win32Native.WIN32_FILE_ATTRIBUTE_DATA();
int dataInitialised = FillAttributeInfo(fullPath, ref data, false, false);
return DateTime.FromFileTimeUtc(dt);
}
-#if !FEATURE_CORECLR
- public static void SetLastAccessTime(String path, DateTime lastAccessTime)
- {
- SetLastAccessTimeUtc(path, lastAccessTime.ToUniversalTime());
- }
-
- [System.Security.SecuritySafeCritical] // auto-generated
- public unsafe static void SetLastAccessTimeUtc(String path, DateTime lastAccessTimeUtc)
- {
- SafeFileHandle handle;
- using(OpenFile(path, FileAccess.Write, out handle)) {
- Win32Native.FILE_TIME fileTime = new Win32Native.FILE_TIME(lastAccessTimeUtc.ToFileTimeUtc());
- bool r = Win32Native.SetFileTime(handle, null, &fileTime, null);
- if (!r)
- {
- int errorCode = Marshal.GetLastWin32Error();
- __Error.WinIOError(errorCode, path);
- }
- }
- }
-#endif // FEATURE_CORECLR
-
- [System.Security.SecuritySafeCritical]
public static DateTime GetLastAccessTime(String path)
{
return InternalGetLastAccessTimeUtc(path, true).ToLocalTime();
}
- [System.Security.SecuritySafeCritical] // auto-generated
public static DateTime GetLastAccessTimeUtc(String path)
{
return InternalGetLastAccessTimeUtc(path, false); // this API isn't exposed in Silverlight
}
- [System.Security.SecurityCritical]
private static DateTime InternalGetLastAccessTimeUtc(String path, bool checkHost)
- {
+ {
String fullPath = Path.GetFullPath(path);
-#if FEATURE_CORECLR
+
if (checkHost)
{
FileSecurityState state = new FileSecurityState(FileSecurityStateAccess.Read, path, fullPath);
state.EnsureState();
}
-#else
- FileIOPermission.QuickDemand(FileIOPermissionAccess.Read, fullPath, false, false);
-#endif
Win32Native.WIN32_FILE_ATTRIBUTE_DATA data = new Win32Native.WIN32_FILE_ATTRIBUTE_DATA();
int dataInitialised = FillAttributeInfo(fullPath, ref data, false, false);
return DateTime.FromFileTimeUtc(dt);
}
-#if !FEATURE_CORECLR
- public static void SetLastWriteTime(String path, DateTime lastWriteTime)
- {
- SetLastWriteTimeUtc(path, lastWriteTime.ToUniversalTime());
- }
-
- [System.Security.SecuritySafeCritical] // auto-generated
- public unsafe static void SetLastWriteTimeUtc(String path, DateTime lastWriteTimeUtc)
- {
- SafeFileHandle handle;
- using(OpenFile(path, FileAccess.Write, out handle)) {
- Win32Native.FILE_TIME fileTime = new Win32Native.FILE_TIME(lastWriteTimeUtc.ToFileTimeUtc());
- bool r = Win32Native.SetFileTime(handle, null, null, &fileTime);
- if (!r)
- {
- int errorCode = Marshal.GetLastWin32Error();
- __Error.WinIOError(errorCode, path);
- }
- }
- }
-#endif // !FEATURE_CORECLR
-
- [System.Security.SecuritySafeCritical]
public static DateTime GetLastWriteTime(String path)
{
return InternalGetLastWriteTimeUtc(path, true).ToLocalTime();
}
- [System.Security.SecuritySafeCritical] // auto-generated
public static DateTime GetLastWriteTimeUtc(String path)
{
return InternalGetLastWriteTimeUtc(path, false); // this API isn't exposed in Silverlight
}
- [System.Security.SecurityCritical]
private static DateTime InternalGetLastWriteTimeUtc(String path, bool checkHost)
{
String fullPath = Path.GetFullPath(path);
-#if FEATURE_CORECLR
+
if (checkHost)
{
FileSecurityState state = new FileSecurityState(FileSecurityStateAccess.Read, path, fullPath);
state.EnsureState();
}
-#else
- FileIOPermission.QuickDemand(FileIOPermissionAccess.Read, fullPath, false, false);
-#endif
Win32Native.WIN32_FILE_ATTRIBUTE_DATA data = new Win32Native.WIN32_FILE_ATTRIBUTE_DATA();
int dataInitialised = FillAttributeInfo(fullPath, ref data, false, false);
return DateTime.FromFileTimeUtc(dt);
}
- [System.Security.SecuritySafeCritical]
public static FileAttributes GetAttributes(String path)
{
String fullPath = Path.GetFullPath(path);
-#if FEATURE_CORECLR
+
FileSecurityState state = new FileSecurityState(FileSecurityStateAccess.Read, path, fullPath);
state.EnsureState();
-#else
- FileIOPermission.QuickDemand(FileIOPermissionAccess.Read, fullPath, false, false);
-#endif
Win32Native.WIN32_FILE_ATTRIBUTE_DATA data = new Win32Native.WIN32_FILE_ATTRIBUTE_DATA();
int dataInitialised = FillAttributeInfo(fullPath, ref data, false, true);
return (FileAttributes) data.fileAttributes;
}
-#if FEATURE_CORECLR
- [System.Security.SecurityCritical]
-#else
- [System.Security.SecuritySafeCritical]
-#endif
public static void SetAttributes(String path, FileAttributes fileAttributes)
{
String fullPath = Path.GetFullPath(path);
-#if !FEATURE_CORECLR
- FileIOPermission.QuickDemand(FileIOPermissionAccess.Write, fullPath, false, false);
-#endif
bool r = Win32Native.SetFileAttributes(fullPath, (int) fileAttributes);
if (!r) {
int hr = Marshal.GetLastWin32Error();
}
}
-#if FEATURE_MACL
- public static FileSecurity GetAccessControl(String path)
- {
- return GetAccessControl(path, AccessControlSections.Access | AccessControlSections.Owner | AccessControlSections.Group);
- }
-
- public static FileSecurity GetAccessControl(String path, AccessControlSections includeSections)
- {
- // Appropriate security check should be done for us by FileSecurity.
- return new FileSecurity(path, includeSections);
- }
-
- [System.Security.SecuritySafeCritical] // auto-generated
- public static void SetAccessControl(String path, FileSecurity fileSecurity)
- {
- if (fileSecurity == null)
- throw new ArgumentNullException(nameof(fileSecurity));
- Contract.EndContractBlock();
-
- String fullPath = Path.GetFullPath(path);
- // Appropriate security check should be done for us by FileSecurity.
- fileSecurity.Persist(fullPath);
- }
-#endif
-
public static FileStream OpenRead(String path) {
return new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.Read);
}
FileAccess.Write, FileShare.None);
}
- [System.Security.SecuritySafeCritical] // auto-generated
public static String ReadAllText(String path)
{
if (path == null)
return InternalReadAllText(path, Encoding.UTF8, true);
}
- [System.Security.SecuritySafeCritical] // auto-generated
public static String ReadAllText(String path, Encoding encoding)
{
if (path == null)
return InternalReadAllText(path, encoding, true);
}
- [System.Security.SecurityCritical]
internal static String UnsafeReadAllText(String path)
{
if (path == null)
return InternalReadAllText(path, Encoding.UTF8, false);
}
- [System.Security.SecurityCritical]
private static String InternalReadAllText(String path, Encoding encoding, bool checkHost)
{
Contract.Requires(path != null);
return sr.ReadToEnd();
}
- [System.Security.SecuritySafeCritical] // auto-generated
public static void WriteAllText(String path, String contents)
{
if (path == null)
InternalWriteAllText(path, contents, StreamWriter.UTF8NoBOM, true);
}
- [System.Security.SecuritySafeCritical] // auto-generated
public static void WriteAllText(String path, String contents, Encoding encoding)
{
if (path == null)
InternalWriteAllText(path, contents, encoding, true);
}
- [System.Security.SecurityCritical]
internal static void UnsafeWriteAllText(String path, String contents)
{
if (path == null)
InternalWriteAllText(path, contents, StreamWriter.UTF8NoBOM, false);
}
- [System.Security.SecurityCritical]
private static void InternalWriteAllText(String path, String contents, Encoding encoding, bool checkHost)
{
Contract.Requires(path != null);
sw.Write(contents);
}
- [System.Security.SecuritySafeCritical] // auto-generated
public static byte[] ReadAllBytes(String path)
{
return InternalReadAllBytes(path, true);
}
- [System.Security.SecurityCritical]
internal static byte[] UnsafeReadAllBytes(String path)
{
return InternalReadAllBytes(path, false);
}
- [System.Security.SecurityCritical]
private static byte[] InternalReadAllBytes(String path, bool checkHost)
{
byte[] bytes;
return bytes;
}
- [System.Security.SecuritySafeCritical] // auto-generated
public static void WriteAllBytes(String path, byte[] bytes)
{
if (path == null)
InternalWriteAllBytes(path, bytes, true);
}
- [System.Security.SecurityCritical]
internal static void UnsafeWriteAllBytes(String path, byte[] bytes)
{
if (path == null)
InternalWriteAllBytes(path, bytes, false);
}
- [System.Security.SecurityCritical]
private static void InternalWriteAllBytes(String path, byte[] bytes, bool checkHost)
{
Contract.Requires(path != null);
// sourceFileName and Write
// permissions to destFileName.
//
- [System.Security.SecuritySafeCritical]
public static void Move(String sourceFileName, String destFileName) {
InternalMove(sourceFileName, destFileName, true);
}
- [System.Security.SecurityCritical]
internal static void UnsafeMove(String sourceFileName, String destFileName) {
InternalMove(sourceFileName, destFileName, false);
}
- [System.Security.SecurityCritical]
private static void InternalMove(String sourceFileName, String destFileName, bool checkHost) {
if (sourceFileName == null)
throw new ArgumentNullException(nameof(sourceFileName), Environment.GetResourceString("ArgumentNull_FileName"));
String fullSourceFileName = Path.GetFullPath(sourceFileName);
String fullDestFileName = Path.GetFullPath(destFileName);
-#if FEATURE_CORECLR
if (checkHost) {
FileSecurityState sourceState = new FileSecurityState(FileSecurityStateAccess.Write | FileSecurityStateAccess.Read, sourceFileName, fullSourceFileName);
FileSecurityState destState = new FileSecurityState(FileSecurityStateAccess.Write, destFileName, fullDestFileName);
sourceState.EnsureState();
destState.EnsureState();
}
-#else
- FileIOPermission.QuickDemand(FileIOPermissionAccess.Write | FileIOPermissionAccess.Read, fullSourceFileName, false, false);
- FileIOPermission.QuickDemand(FileIOPermissionAccess.Write, fullDestFileName, false, false);
-#endif
if (!InternalExists(fullSourceFileName))
__Error.WinIOError(Win32Native.ERROR_FILE_NOT_FOUND, fullSourceFileName);
InternalReplace(sourceFileName, destinationFileName, destinationBackupFileName, ignoreMetadataErrors);
}
- [System.Security.SecuritySafeCritical]
private static void InternalReplace(String sourceFileName, String destinationFileName, String destinationBackupFileName, bool ignoreMetadataErrors)
{
Contract.Requires(sourceFileName != null);
if (destinationBackupFileName != null)
fullBackupPath = Path.GetFullPath(destinationBackupFileName);
-#if FEATURE_CORECLR
FileSecurityState sourceState = new FileSecurityState(FileSecurityStateAccess.Read | FileSecurityStateAccess.Write, sourceFileName, fullSrcPath);
FileSecurityState destState = new FileSecurityState(FileSecurityStateAccess.Read | FileSecurityStateAccess.Write, destinationFileName, fullDestPath);
FileSecurityState backupState = new FileSecurityState(FileSecurityStateAccess.Read | FileSecurityStateAccess.Write, destinationBackupFileName, fullBackupPath);
sourceState.EnsureState();
destState.EnsureState();
backupState.EnsureState();
-#else
- FileIOPermission perm = new FileIOPermission(FileIOPermissionAccess.Read | FileIOPermissionAccess.Write, new String[] { fullSrcPath, fullDestPath});
- if (destinationBackupFileName != null)
- perm.AddPathList(FileIOPermissionAccess.Write, fullBackupPath);
- perm.Demand();
-#endif
int flags = Win32Native.REPLACEFILE_WRITE_THROUGH;
if (ignoreMetadataErrors)
// Returns 0 on success, otherwise a Win32 error code. Note that
// classes should use -1 as the uninitialized state for dataInitialized.
- [System.Security.SecurityCritical] // auto-generated
internal static int FillAttributeInfo(String path, ref Win32Native.WIN32_FILE_ATTRIBUTE_DATA data, bool tryagain, bool returnErrorOnNotFound)
{
int dataInitialised = 0;
catch {
// if we're already returning an error, don't throw another one.
if (!error) {
- Contract.Assert(false, "File::FillAttributeInfo - FindClose failed!");
+ Debug.Assert(false, "File::FillAttributeInfo - FindClose failed!");
__Error.WinIOError();
}
}
return dataInitialised;
}
-#if !FEATURE_CORECLR
- [System.Security.SecurityCritical] // auto-generated
- private static FileStream OpenFile(String path, FileAccess access, out SafeFileHandle handle)
- {
- FileStream fs = new FileStream(path, FileMode.Open, access, FileShare.ReadWrite, 1);
- handle = fs.SafeFileHandle;
-
- if (handle.IsInvalid) {
- // Return a meaningful error, using the RELATIVE path to
- // the file to avoid returning extra information to the caller.
-
- // NT5 oddity - when trying to open "C:\" as a FileStream,
- // we usually get ERROR_PATH_NOT_FOUND from the OS. We should
- // probably be consistent w/ every other directory.
- int hr = Marshal.GetLastWin32Error();
- String FullPath = Path.GetFullPath(path);
- if (hr==__Error.ERROR_PATH_NOT_FOUND && FullPath.Equals(Directory.GetDirectoryRoot(FullPath)))
- hr = __Error.ERROR_ACCESS_DENIED;
-
-
- __Error.WinIOError(hr, path);
- }
- return fs;
- }
-#endif // !FEATURE_CORECLR
-
-
- // Defined in WinError.h
+ // Defined in WinError.h
private const int ERROR_INVALID_PARAMETER = 87;
- private const int ERROR_ACCESS_DENIED = 0x5;
+ private const int ERROR_ACCESS_DENIED = 0x5;
}
}
===========================================================*/
using System;
-namespace System.IO {
+namespace System.IO
+{
// File attributes for use with the FileEnumerator class.
// These constants correspond to the constants in WinNT.h.
- //
-[Serializable]
+ [Serializable]
[Flags]
-[System.Runtime.InteropServices.ComVisible(true)]
+ [System.Runtime.InteropServices.ComVisible(true)]
public enum FileAttributes
{
// From WinNT.h (FILE_ATTRIBUTE_XXX)
Offline = 0x1000,
NotContentIndexed = 0x2000,
Encrypted = 0x4000,
-
-#if !FEATURE_CORECLR
-#if FEATURE_COMINTEROP
- [System.Runtime.InteropServices.ComVisible(false)]
-#endif // FEATURE_COMINTEROP
- IntegrityStream = 0x8000,
-
-#if FEATURE_COMINTEROP
- [System.Runtime.InteropServices.ComVisible(false)]
-#endif // FEATURE_COMINTEROP
- NoScrubData = 0x20000,
-#endif
}
}
===========================================================*/
using System;
-#if FEATURE_MACL
-using System.Security.AccessControl;
-#endif
using System.Security.Permissions;
using PermissionSet = System.Security.PermissionSet;
using Win32Native = Microsoft.Win32.Win32Native;
using System.Runtime.Serialization;
using System.Globalization;
using System.Runtime.Versioning;
+using System.Diagnostics;
using System.Diagnostics.Contracts;
-namespace System.IO {
+namespace System.IO
+{
// Class for creating FileStream objects, and some basic file management
// routines such as Delete, etc.
[Serializable]
{
private String _name;
-#if FEATURE_CORECLR
// Migrating InheritanceDemands requires this default ctor, so we can annotate it.
#if FEATURE_CORESYSTEM
- [System.Security.SecurityCritical]
#else
- [System.Security.SecuritySafeCritical]
#endif //FEATURE_CORESYSTEM
private FileInfo(){}
- [System.Security.SecurityCritical]
public static FileInfo UnsafeCreateFileInfo(String fileName)
{
if (fileName == null)
fi.Init(fileName, false);
return fi;
}
-#endif
- [System.Security.SecuritySafeCritical]
public FileInfo(String fileName)
{
if (fileName == null)
Init(fileName, true);
}
- [System.Security.SecurityCritical]
private void Init(String fileName, bool checkHost)
{
OriginalPath = fileName;
// Must fully qualify the path for the security check
String fullPath = Path.GetFullPath(fileName);
-#if FEATURE_CORECLR
+
if (checkHost)
{
FileSecurityState state = new FileSecurityState(FileSecurityStateAccess.Read, fileName, fullPath);
state.EnsureState();
}
-#else
- FileIOPermission.QuickDemand(FileIOPermissionAccess.Read, fullPath, false, false);
-#endif
_name = Path.GetFileName(fileName);
FullPath = fullPath;
private String GetDisplayPath(String originalPath)
{
-#if FEATURE_CORECLR
return Path.GetFileName(originalPath);
-#else
- return originalPath;
-#endif
-
}
- [System.Security.SecurityCritical] // auto-generated
private FileInfo(SerializationInfo info, StreamingContext context) : base(info, context)
{
-#if !FEATURE_CORECLR
- new FileIOPermission(FileIOPermissionAccess.Read, new String[] { FullPath }, false, false).Demand();
-#endif
_name = Path.GetFileName(OriginalPath);
DisplayPath = GetDisplayPath(OriginalPath);
}
#if FEATURE_CORESYSTEM
- [System.Security.SecuritySafeCritical]
#endif //FEATURE_CORESYSTEM
internal FileInfo(String fullPath, bool ignoreThis)
{
- Contract.Assert(PathInternal.GetRootLength(fullPath) > 0, "fullPath must be fully qualified!");
+ Debug.Assert(PathInternal.GetRootLength(fullPath) > 0, "fullPath must be fully qualified!");
_name = Path.GetFileName(fullPath);
OriginalPath = _name;
FullPath = fullPath;
public override String Name {
get { return _name; }
}
-
-
+
public long Length {
- [System.Security.SecuritySafeCritical] // auto-generated
get {
if (_dataInitialised == -1)
Refresh();
/* Returns the name of the directory that the file is in */
public String DirectoryName
{
- [System.Security.SecuritySafeCritical]
get
{
String directoryName = Path.GetDirectoryName(FullPath);
if (directoryName != null)
{
-#if FEATURE_CORECLR
FileSecurityState state = new FileSecurityState(FileSecurityStateAccess.Read, DisplayPath, FullPath);
state.EnsureState();
-#else
- new FileIOPermission(FileIOPermissionAccess.PathDiscovery, new String[] { directoryName }, false, false).Demand();
-#endif
}
return directoryName;
}
String dirName = DirectoryName;
if (dirName == null)
return null;
- return new DirectoryInfo(dirName);
+ return new DirectoryInfo(dirName);
}
}
}
}
-#if FEATURE_MACL
- public FileSecurity GetAccessControl()
- {
- return File.GetAccessControl(FullPath, AccessControlSections.Access | AccessControlSections.Owner | AccessControlSections.Group);
- }
-
- public FileSecurity GetAccessControl(AccessControlSections includeSections)
- {
- return File.GetAccessControl(FullPath, includeSections);
- }
-
- public void SetAccessControl(FileSecurity fileSecurity)
- {
- File.SetAccessControl(FullPath, fileSecurity);
- }
-#endif
-
- [System.Security.SecuritySafeCritical] // auto-generated
public StreamReader OpenText()
{
return new StreamReader(FullPath, Encoding.UTF8, true, StreamReader.DefaultBufferSize, false);
//
// Your application must have Delete permission to the target file.
//
- [System.Security.SecuritySafeCritical]
public override void Delete()
{
-#if FEATURE_CORECLR
FileSecurityState state = new FileSecurityState(FileSecurityStateAccess.Write, DisplayPath, FullPath);
state.EnsureState();
-#else
- // For security check, path should be resolved to an absolute path.
- new FileIOPermission(FileIOPermissionAccess.Write, new String[] { FullPath }, false, false).Demand();
-#endif
bool r = Win32Native.DeleteFile(FullPath);
if (!r) {
//
// Your application must have Read permission for the target directory.
public override bool Exists {
- [System.Security.SecuritySafeCritical] // auto-generated
get {
try {
if (_dataInitialised == -1)
}
}
-
-
-
// User must explicitly specify opening a new file or appending to one.
public FileStream Open(FileMode mode) {
return Open(mode, FileAccess.ReadWrite, FileShare.None);
return new FileStream(FullPath, mode, access, share);
}
-
-#if FEATURE_CORECLR
- [System.Security.SecuritySafeCritical] // auto-generated
-#endif
public FileStream OpenRead()
{
return new FileStream(FullPath, FileMode.Open, FileAccess.Read,
FileShare.Read, 4096, false);
}
-
public FileStream OpenWrite() {
return new FileStream(FullPath, FileMode.OpenOrCreate,
FileAccess.Write, FileShare.None);
}
-
-
-
-
-
// Moves a given file to a new location and potentially a new file name.
// This method does work across volumes.
//
// sourceFileName and Write
// permissions to destFileName.
//
- [System.Security.SecuritySafeCritical]
public void MoveTo(String destFileName) {
if (destFileName==null)
throw new ArgumentNullException(nameof(destFileName));
Contract.EndContractBlock();
string fullDestFileName = Path.GetFullPath(destFileName);
-#if FEATURE_CORECLR
+
FileSecurityState sourceState = new FileSecurityState(FileSecurityStateAccess.Write | FileSecurityStateAccess.Read, DisplayPath, FullPath);
FileSecurityState destState = new FileSecurityState(FileSecurityStateAccess.Write, destFileName, fullDestFileName);
sourceState.EnsureState();
destState.EnsureState();
-#else
- new FileIOPermission(FileIOPermissionAccess.Write | FileIOPermissionAccess.Read, new String[] { FullPath }, false, false).Demand();
- FileIOPermission.QuickDemand(FileIOPermissionAccess.Write, fullDestFileName, false, false);
-#endif
-
+
if (!Win32Native.MoveFile(FullPath, fullDestFileName))
__Error.WinIOError();
FullPath = fullDestFileName;
}
public String FusionLog {
- [System.Security.SecuritySafeCritical] // auto-generated
get { return _fusionLog; }
}
- [System.Security.SecurityCritical] // auto-generated_required
public override void GetObjectData(SerializationInfo info, StreamingContext context) {
// Serialize data for our base classes. base will verify info != null.
base.GetObjectData(info, context);
}
}
- [System.Security.SecuritySafeCritical] // auto-generated
internal static String FormatFileLoadExceptionMessage(String fileName,
int hResult)
{
return String.Format(CultureInfo.CurrentCulture, format, fileName, message);
}
- [System.Security.SecurityCritical] // auto-generated
[DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
[SuppressUnmanagedCodeSecurity]
private static extern void GetFileLoadExceptionMessage(int hResult, StringHandleOnStack retString);
- [System.Security.SecurityCritical] // auto-generated
[DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
[SuppressUnmanagedCodeSecurity]
private static extern void GetMessageForHR(int hresult, StringHandleOnStack retString);
}
public String FusionLog {
- [System.Security.SecuritySafeCritical] // auto-generated
get { return _fusionLog; }
}
- [System.Security.SecurityCritical] // auto-generated_required
public override void GetObjectData(SerializationInfo info, StreamingContext context) {
// Serialize data for our base classes. base will verify info != null.
base.GetObjectData(info, context);
namespace System.IO
{
- [SecurityCritical]
[System.Runtime.CompilerServices.FriendAccessAllowed]
internal class FileSecurityState : SecurityState
{
private String m_canonicalizedPath;
// default ctor needed for security rule consistency
- [SecurityCritical]
private FileSecurityState()
{
}
}
}
- #if FEATURE_CORECLR
- [System.Security.SecurityCritical] // auto-generated
- #endif
public override void EnsureState()
{
// this is the case for empty string machine name, etc
using System.Runtime.InteropServices;
using System.Globalization;
using System.Runtime.Versioning;
+using System.Diagnostics;
using System.Diagnostics.Contracts;
using System.Threading;
private List<Directory.SearchData> searchStack;
private Directory.SearchData searchData;
private String searchCriteria;
- [System.Security.SecurityCritical]
SafeFindHandle _hnd = null;
bool needsParentPathDiscoveryDemand;
private int oldMode;
private bool _checkHost;
- [System.Security.SecuritySafeCritical]
internal FileSystemEnumerableIterator(String path, String originalUserPath, String searchPattern, SearchOption searchOption, SearchResultHandler<TSource> resultHandler, bool checkHost)
{
Contract.Requires(path != null);
// Do a demand on the combined path so that we can fail early in case of deny
demandPaths[1] = Directory.GetDemandDir(normalizedSearchPath, true);
_checkHost = checkHost;
-#if FEATURE_CORECLR
+
if (checkHost)
{
FileSecurityState state1 = new FileSecurityState(FileSecurityStateAccess.PathDiscovery, String.Empty, demandPaths[0]);
FileSecurityState state2 = new FileSecurityState(FileSecurityStateAccess.PathDiscovery, String.Empty, demandPaths[1]);
state2.EnsureState();
}
-#else
- new FileIOPermission(FileIOPermissionAccess.PathDiscovery, demandPaths, false, false).Demand();
-#endif
// normalize search criteria
searchCriteria = GetNormalizedSearchCriteria(fullSearchString, normalizedSearchPath);
}
- [System.Security.SecurityCritical]
private void CommonInit()
{
- Contract.Assert(searchCriteria != null && searchData != null, "searchCriteria and searchData should be initialized");
+ Debug.Assert(searchCriteria != null && searchData != null, "searchCriteria and searchData should be initialized");
// Execute searchCriteria against the current directory
String searchPath = Path.Combine(searchData.fullPath, searchCriteria);
}
}
- [System.Security.SecuritySafeCritical]
private FileSystemEnumerableIterator(String fullPath, String normalizedSearchPath, String searchCriteria, String userPath, SearchOption searchOption, SearchResultHandler<TSource> resultHandler, bool checkHost)
{
this.fullPath = fullPath;
// For filters like foo\*.cs we need to verify if the directory foo is not denied access.
// Do a demand on the combined path so that we can fail early in case of deny
demandPaths[1] = Directory.GetDemandDir(normalizedSearchPath, true);
-#if FEATURE_CORECLR
+
if (checkHost)
{
FileSecurityState state1 = new FileSecurityState(FileSecurityStateAccess.PathDiscovery, String.Empty, demandPaths[0]);
FileSecurityState state2 = new FileSecurityState(FileSecurityStateAccess.PathDiscovery, String.Empty, demandPaths[1]);
state2.EnsureState();
}
-#else
- new FileIOPermission(FileIOPermissionAccess.PathDiscovery, demandPaths, false, false).Demand();
-#endif
+
searchData = new Directory.SearchData(normalizedSearchPath, userPath, searchOption);
CommonInit();
}
return new FileSystemEnumerableIterator<TSource>(fullPath, normalizedSearchPath, searchCriteria, userPath, searchOption, _resultHandler, _checkHost);
}
- [System.Security.SecuritySafeCritical]
protected override void Dispose(bool disposing)
{
try
}
}
- [System.Security.SecuritySafeCritical]
public override bool MoveNext()
{
Win32Native.WIN32_FIND_DATA data = new Win32Native.WIN32_FIND_DATA();
}
case STATE_SEARCH_NEXT_DIR:
{
- Contract.Assert(searchData.searchOption != SearchOption.TopDirectoryOnly, "should not reach this code path if searchOption == TopDirectoryOnly");
+ Debug.Assert(searchData.searchOption != SearchOption.TopDirectoryOnly, "should not reach this code path if searchOption == TopDirectoryOnly");
// Traverse directory structure. We need to get '*'
while (searchStack.Count > 0)
{
searchData = searchStack[0];
- Contract.Assert((searchData.fullPath != null), "fullpath can't be null!");
+ Debug.Assert((searchData.fullPath != null), "fullpath can't be null!");
searchStack.RemoveAt(0);
// Traverse the subdirs
return false;
}
- [System.Security.SecurityCritical]
private SearchResult CreateSearchResult(Directory.SearchData localSearchData, Win32Native.WIN32_FIND_DATA findData)
{
String userPathFinal = Path.Combine(localSearchData.userPath, findData.cFileName);
return new SearchResult(fullPathFinal, userPathFinal, findData);
}
- [System.Security.SecurityCritical]
private void HandleError(int hr, String path)
{
Dispose();
__Error.WinIOError(hr, path);
}
- [System.Security.SecurityCritical] // auto-generated
private void AddSearchableDirsToStack(Directory.SearchData localSearchData)
{
Contract.Requires(localSearchData != null);
}
}
- [System.Security.SecurityCritical]
internal void DoDemand(String fullPathToDemand)
{
-#if FEATURE_CORECLR
if(_checkHost) {
String demandDir = Directory.GetDemandDir(fullPathToDemand, true);
FileSecurityState state = new FileSecurityState(FileSecurityStateAccess.PathDiscovery, String.Empty, demandDir);
state.EnsureState();
}
-#else
- String demandDir = Directory.GetDemandDir(fullPathToDemand, true);
- String[] demandPaths = new String[] { demandDir };
- new FileIOPermission(FileIOPermissionAccess.PathDiscovery, demandPaths, false, false).Demand();
-#endif
}
private static String NormalizeSearchPattern(String searchPattern)
}
else
{
- Contract.Assert(fullSearchString.Length > fullPathMod.Length);
+ Debug.Assert(fullSearchString.Length > fullPathMod.Length);
searchCriteria = fullSearchString.Substring(fullPathMod.Length + 1);
}
return searchCriteria;
internal abstract class SearchResultHandler<TSource>
{
- [System.Security.SecurityCritical]
internal abstract bool IsResultIncluded(SearchResult result);
- [System.Security.SecurityCritical]
internal abstract TSource CreateObject(SearchResult result);
}
_includeDirs = includeDirs;
}
- [System.Security.SecurityCritical]
internal override bool IsResultIncluded(SearchResult result)
{
bool includeFile = _includeFiles && FileSystemEnumerableHelpers.IsFile(result.FindData);
bool includeDir = _includeDirs && FileSystemEnumerableHelpers.IsDir(result.FindData);
- Contract.Assert(!(includeFile && includeDir), result.FindData.cFileName + ": current item can't be both file and dir!");
+ Debug.Assert(!(includeFile && includeDir), result.FindData.cFileName + ": current item can't be both file and dir!");
return (includeFile || includeDir);
}
- [System.Security.SecurityCritical]
internal override String CreateObject(SearchResult result)
{
return result.UserPath;
internal class FileInfoResultHandler : SearchResultHandler<FileInfo>
{
- [System.Security.SecurityCritical]
internal override bool IsResultIncluded(SearchResult result)
{
return FileSystemEnumerableHelpers.IsFile(result.FindData);
}
- [System.Security.SecurityCritical]
internal override FileInfo CreateObject(SearchResult result)
{
String name = result.FullPath;
-#if FEATURE_CORECLR
+
FileSecurityState state = new FileSecurityState(FileSecurityStateAccess.Read, String.Empty, name);
state.EnsureState();
-#else
- String[] names = new String[] { name };
- new FileIOPermission(FileIOPermissionAccess.Read, names, false, false).Demand();
-#endif
+
FileInfo fi = new FileInfo(name, false);
fi.InitializeFrom(result.FindData);
return fi;
internal class DirectoryInfoResultHandler : SearchResultHandler<DirectoryInfo>
{
- [System.Security.SecurityCritical]
internal override bool IsResultIncluded(SearchResult result)
{
return FileSystemEnumerableHelpers.IsDir(result.FindData);
}
- [System.Security.SecurityCritical]
internal override DirectoryInfo CreateObject(SearchResult result)
{
String name = result.FullPath;
String permissionName = name + "\\.";
-
-#if FEATURE_CORECLR
+
FileSecurityState state = new FileSecurityState(FileSecurityStateAccess.Read, String.Empty, permissionName);
state.EnsureState();
-#else
- String[] permissionNames = new String[] { permissionName };
- new FileIOPermission(FileIOPermissionAccess.Read, permissionNames, false, false).Demand();
-#endif
+
DirectoryInfo di = new DirectoryInfo(name, false);
di.InitializeFrom(result.FindData);
return di;
internal class FileSystemInfoResultHandler : SearchResultHandler<FileSystemInfo>
{
- [System.Security.SecurityCritical]
internal override bool IsResultIncluded(SearchResult result)
{
bool includeFile = FileSystemEnumerableHelpers.IsFile(result.FindData);
bool includeDir = FileSystemEnumerableHelpers.IsDir(result.FindData);
- Contract.Assert(!(includeFile && includeDir), result.FindData.cFileName + ": current item can't be both file and dir!");
+ Debug.Assert(!(includeFile && includeDir), result.FindData.cFileName + ": current item can't be both file and dir!");
return (includeDir || includeFile);
}
- [System.Security.SecurityCritical]
internal override FileSystemInfo CreateObject(SearchResult result)
{
bool isFile = FileSystemEnumerableHelpers.IsFile(result.FindData);
String name = result.FullPath;
String permissionName = name + "\\.";
-#if FEATURE_CORECLR
FileSecurityState state = new FileSecurityState(FileSecurityStateAccess.Read, String.Empty, permissionName);
state.EnsureState();
-#else
- String[] permissionNames = new String[] { permissionName };
- new FileIOPermission(FileIOPermissionAccess.Read, permissionNames, false, false).Demand();
-#endif
+
DirectoryInfo di = new DirectoryInfo(name, false);
di.InitializeFrom(result.FindData);
return di;
}
else
{
- Contract.Assert(isFile);
+ Debug.Assert(isFile);
String name = result.FullPath;
-#if FEATURE_CORECLR
FileSecurityState state = new FileSecurityState(FileSecurityStateAccess.Read, String.Empty, name);
state.EnsureState();
-#else
- String[] names = new String[] { name };
- new FileIOPermission(FileIOPermissionAccess.Read, names, false, false).Demand();
-#endif
+
FileInfo fi = new FileInfo(name, false);
fi.InitializeFrom(result.FindData);
return fi;
{
private String fullPath; // fully-qualifed path
private String userPath; // user-specified path
- [System.Security.SecurityCritical]
private Win32Native.WIN32_FIND_DATA findData;
- [System.Security.SecurityCritical]
internal SearchResult(String fullPath, String userPath, Win32Native.WIN32_FIND_DATA findData)
{
Contract.Requires(fullPath != null);
internal Win32Native.WIN32_FIND_DATA FindData
{
- [System.Security.SecurityCritical]
get { return findData; }
}
internal static class FileSystemEnumerableHelpers
{
- [System.Security.SecurityCritical] // auto-generated
internal static bool IsDir(Win32Native.WIN32_FIND_DATA data)
{
// Don't add "." nor ".."
&& !data.cFileName.Equals(".") && !data.cFileName.Equals("..");
}
- [System.Security.SecurityCritical] // auto-generated
internal static bool IsFile(Win32Native.WIN32_FIND_DATA data)
{
return 0 == (data.dwFileAttributes & Win32Native.FILE_ATTRIBUTE_DIRECTORY);
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
-/*============================================================
-**
-**
-**
-**
-**
-** Purpose:
-**
-**
-===========================================================*/
-
using System;
using System.Collections;
using System.Security;
using System.Runtime.Versioning;
using System.Diagnostics.Contracts;
-namespace System.IO {
+namespace System.IO
+{
#if FEATURE_SERIALIZATION
[Serializable]
#endif
-#if !FEATURE_CORECLR
- [FileIOPermissionAttribute(SecurityAction.InheritanceDemand,Unrestricted=true)]
-#endif
[ComVisible(true)]
public abstract class FileSystemInfo : MarshalByRefObject, ISerializable {
- [System.Security.SecurityCritical] // auto-generated
internal Win32Native.WIN32_FILE_ATTRIBUTE_DATA _data; // Cache the file information
internal int _dataInitialised = -1; // We use this field in conjunction with the Refresh methods, if we succeed
// we store a zero, on failure we store the HResult in it so that we can
protected String OriginalPath; // path passed in by the user
private String _displayPath = ""; // path that can be displayed to the user
-#if FEATURE_CORECLR
#if FEATURE_CORESYSTEM
- [System.Security.SecurityCritical]
#else
- [System.Security.SecuritySafeCritical]
#endif //FEATURE_CORESYSTEM
-#endif
protected FileSystemInfo()
{
}
_dataInitialised = -1;
}
- [System.Security.SecurityCritical]
internal void InitializeFrom(Win32Native.WIN32_FIND_DATA findData)
{
_data = new Win32Native.WIN32_FILE_ATTRIBUTE_DATA();
// Full path of the direcory/file
public virtual String FullName {
- [System.Security.SecuritySafeCritical]
get
{
String demandDir;
demandDir = Directory.GetDemandDir(FullPath, true);
else
demandDir = FullPath;
-#if FEATURE_CORECLR
+
FileSecurityState sourceState = new FileSecurityState(FileSecurityStateAccess.PathDiscovery, String.Empty, demandDir);
sourceState.EnsureState();
-#else
- new FileIOPermission(FileIOPermissionAccess.PathDiscovery, demandDir).Demand();
-#endif
return FullPath;
}
}
internal virtual String UnsafeGetFullName
{
- [System.Security.SecurityCritical]
get
{
String demandDir;
demandDir = Directory.GetDemandDir(FullPath, true);
else
demandDir = FullPath;
-#if !FEATURE_CORECLR
- new FileIOPermission(FileIOPermissionAccess.PathDiscovery, demandDir).Demand();
-#endif
return FullPath;
}
}
// depends on the security check in get_CreationTimeUtc
return CreationTimeUtc.ToLocalTime();
}
-#if !FEATURE_CORECLR
- set
- {
- CreationTimeUtc = value.ToUniversalTime();
- }
-#endif // !FEATURE_CORECLR
}
[ComVisible(false)]
public DateTime CreationTimeUtc {
- [System.Security.SecuritySafeCritical]
get {
-#if FEATURE_CORECLR
// get_CreationTime also depends on this security check
FileSecurityState sourceState = new FileSecurityState(FileSecurityStateAccess.Read, String.Empty, FullPath);
sourceState.EnsureState();
-#endif
+
if (_dataInitialised == -1) {
_data = new Win32Native.WIN32_FILE_ATTRIBUTE_DATA();
Refresh();
return DateTime.FromFileTimeUtc(fileTime);
}
-#if !FEATURE_CORECLR
- set {
- if (this is DirectoryInfo)
- Directory.SetCreationTimeUtc(FullPath,value);
- else
- File.SetCreationTimeUtc(FullPath,value);
- _dataInitialised = -1;
- }
-#endif // !FEATURE_CORECLR
}
-
public DateTime LastAccessTime
{
get {
[ComVisible(false)]
public DateTime LastAccessTimeUtc {
- [System.Security.SecuritySafeCritical]
get {
-#if FEATURE_CORECLR
// get_LastAccessTime also depends on this security check
FileSecurityState sourceState = new FileSecurityState(FileSecurityStateAccess.Read, String.Empty, FullPath);
sourceState.EnsureState();
-#endif
+
if (_dataInitialised == -1) {
_data = new Win32Native.WIN32_FILE_ATTRIBUTE_DATA();
Refresh();
}
set {
-#if !FEATURE_CORECLR
- if (this is DirectoryInfo)
- Directory.SetLastAccessTimeUtc(FullPath,value);
- else
- File.SetLastAccessTimeUtc(FullPath,value);
- _dataInitialised = -1;
-#endif // !FEATURE_CORECLR
}
}
[ComVisible(false)]
public DateTime LastWriteTimeUtc {
- [System.Security.SecuritySafeCritical]
get {
-#if FEATURE_CORECLR
// get_LastWriteTime also depends on this security check
FileSecurityState sourceState = new FileSecurityState(FileSecurityStateAccess.Read, String.Empty, FullPath);
sourceState.EnsureState();
-#endif
if (_dataInitialised == -1) {
_data = new Win32Native.WIN32_FILE_ATTRIBUTE_DATA();
Refresh();
}
set {
-#if !FEATURE_CORECLR
- if (this is DirectoryInfo)
- Directory.SetLastWriteTimeUtc(FullPath,value);
- else
- File.SetLastWriteTimeUtc(FullPath,value);
- _dataInitialised = -1;
-#endif // !FEATURE_CORECLR
}
}
- [System.Security.SecuritySafeCritical] // auto-generated
public void Refresh()
{
_dataInitialised = File.FillAttributeInfo(FullPath, ref _data, false, false);
}
public FileAttributes Attributes {
- [System.Security.SecuritySafeCritical]
get
{
-#if FEATURE_CORECLR
FileSecurityState sourceState = new FileSecurityState(FileSecurityStateAccess.Read, String.Empty, FullPath);
sourceState.EnsureState();
-#endif
+
if (_dataInitialised == -1) {
_data = new Win32Native.WIN32_FILE_ATTRIBUTE_DATA();
Refresh(); // Call refresh to intialise the data
return (FileAttributes) _data.fileAttributes;
}
-#if FEATURE_CORECLR
- [System.Security.SecurityCritical] // auto-generated
-#else
- [System.Security.SecuritySafeCritical]
-#endif
+
set {
-#if !FEATURE_CORECLR
- new FileIOPermission(FileIOPermissionAccess.Write, FullPath).Demand();
-#endif
bool r = Win32Native.SetFileAttributes(FullPath, (int) value);
if (!r) {
int hr = Marshal.GetLastWin32Error();
}
}
- [System.Security.SecurityCritical] // auto-generated_required
[ComVisible(false)]
public virtual void GetObjectData(SerializationInfo info, StreamingContext context)
{
-#if !FEATURE_CORECLR
- new FileIOPermission(FileIOPermissionAccess.PathDiscovery, FullPath).Demand();
-#endif
-
info.AddValue("OriginalPath", OriginalPath, typeof(String));
info.AddValue("FullPath", FullPath, typeof(String));
}
using System.Runtime;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
+using System.Diagnostics;
using System.Diagnostics.Contracts;
using System.Threading;
using System.Threading.Tasks;
public override void Flush() {
}
- [HostProtection(ExternalThreading=true)]
[ComVisible(false)]
public override Task FlushAsync(CancellationToken cancellationToken) {
if (n > count) n = count;
if (n < 0) n = 0;
- Contract.Assert(_position + n >= 0, "_position + n >= 0"); // len is less than 2^31 -1.
+ Debug.Assert(_position + n >= 0, "_position + n >= 0"); // len is less than 2^31 -1.
_position += n;
return n;
}
if (n <= 0)
return 0;
- Contract.Assert(_position + n >= 0, "_position + n >= 0"); // len is less than 2^31 -1.
+ Debug.Assert(_position + n >= 0, "_position + n >= 0"); // len is less than 2^31 -1.
if (n <= 8)
{
return n;
}
- [HostProtection(ExternalThreading = true)]
[ComVisible(false)]
public override Task<int> ReadAsync(Byte[] buffer, int offset, int count, CancellationToken cancellationToken)
{
{
int n = Read(buffer, offset, count);
var t = _lastReadTask;
- Contract.Assert(t == null || t.Status == TaskStatus.RanToCompletion,
+ Debug.Assert(t == null || t.Status == TaskStatus.RanToCompletion,
"Expected that a stored last task completed successfully");
return (t != null && t.Result == n) ? t : (_lastReadTask = Task.FromResult<int>(n));
}
throw new ArgumentException(Environment.GetResourceString("Argument_InvalidSeekOrigin"));
}
- Contract.Assert(_position >= 0, "_position >= 0");
+ Debug.Assert(_position >= 0, "_position >= 0");
return _position;
}
EnsureWriteable();
// Origin wasn't publicly exposed above.
- Contract.Assert(MemStreamMaxLength == Int32.MaxValue); // Check parameter validation logic in this method if this fails.
+ Debug.Assert(MemStreamMaxLength == Int32.MaxValue); // Check parameter validation logic in this method if this fails.
if (value > (Int32.MaxValue - _origin)) {
throw new ArgumentOutOfRangeException(nameof(value), Environment.GetResourceString("ArgumentOutOfRange_StreamLength"));
}
}
- [HostProtection(ExternalThreading = true)]
[ComVisible(false)]
public override Task WriteAsync(Byte[] buffer, int offset, int count, CancellationToken cancellationToken)
{
===========================================================*/
using System;
using System.Runtime.InteropServices;
+using System.Diagnostics;
using System.Diagnostics.Contracts;
namespace System.IO {
private GCHandle _pinningHandle;
// The new inheritance model requires a Critical default ctor since base (UnmanagedMemoryStream) has one
- [System.Security.SecurityCritical]
private PinnedBufferMemoryStream():base(){}
- [System.Security.SecurityCritical] // auto-generated
internal PinnedBufferMemoryStream(byte[] array)
{
- Contract.Assert(array != null, "Array can't be null");
+ Debug.Assert(array != null, "Array can't be null");
int len = array.Length;
// Handle 0 length byte arrays specially.
Dispose(false);
}
- [System.Security.SecuritySafeCritical] // auto-generated
protected override void Dispose(bool disposing)
{
if (_isOpen) {
**
===========================================================*/
using System;
-#if FEATURE_CORECLR
using System.Buffers;
-#endif
using System.Threading;
using System.Threading.Tasks;
-
using System.Runtime;
using System.Runtime.InteropServices;
using System.Runtime.CompilerServices;
using System.Runtime.ExceptionServices;
using System.Security;
using System.Security.Permissions;
+using System.Diagnostics;
using System.Diagnostics.Contracts;
using System.Reflection;
}
}
- [HostProtection(ExternalThreading = true)]
[ComVisible(false)]
public Task CopyToAsync(Stream destination)
{
int bufferSize = _DefaultCopyBufferSize;
-#if FEATURE_CORECLR
if (CanSeek)
{
long length = Length;
bufferSize = (int)Math.Min(bufferSize, remaining);
}
}
-#endif // FEATURE_CORECLR
-
+
return CopyToAsync(destination, bufferSize);
}
- [HostProtection(ExternalThreading = true)]
[ComVisible(false)]
public Task CopyToAsync(Stream destination, Int32 bufferSize)
{
return CopyToAsync(destination, bufferSize, CancellationToken.None);
}
- [HostProtection(ExternalThreading = true)]
[ComVisible(false)]
public virtual Task CopyToAsync(Stream destination, Int32 bufferSize, CancellationToken cancellationToken)
{
Contract.Requires(CanRead);
Contract.Requires(destination.CanWrite);
-#if FEATURE_CORECLR
byte[] buffer = ArrayPool<byte>.Shared.Rent(bufferSize);
bufferSize = 0; // reuse same field for high water mark to avoid needing another field in the state machine
try
Array.Clear(buffer, 0, bufferSize); // clear only the most we used
ArrayPool<byte>.Shared.Return(buffer, clearArray: false);
}
-#else
- byte[] buffer = new byte[bufferSize];
- while (true)
- {
- int bytesRead = await ReadAsync(buffer, 0, buffer.Length, cancellationToken).ConfigureAwait(false);
- if (bytesRead == 0) break;
- await destination.WriteAsync(buffer, 0, bytesRead, cancellationToken).ConfigureAwait(false);
- }
-#endif
}
// Reads the bytes from the current stream and writes the bytes to
{
int bufferSize = _DefaultCopyBufferSize;
-#if FEATURE_CORECLR
if (CanSeek)
{
long length = Length;
bufferSize = (int)Math.Min(bufferSize, remaining);
}
}
-#endif // FEATURE_CORECLR
-
+
CopyTo(destination, bufferSize);
}
{
StreamHelpers.ValidateCopyToArgs(this, destination, bufferSize);
-#if FEATURE_CORECLR
byte[] buffer = ArrayPool<byte>.Shared.Rent(bufferSize);
int highwaterMark = 0;
try
Array.Clear(buffer, 0, highwaterMark); // clear only the most we used
ArrayPool<byte>.Shared.Return(buffer, clearArray: false);
}
-#else
- byte[] buffer = new byte[bufferSize];
- int read;
- while ((read = Read(buffer, 0, buffer.Length)) != 0)
- {
- destination.Write(buffer, 0, read);
- }
-#endif
}
// Stream used to require that all cleanup logic went into Close(),
public abstract void Flush();
- [HostProtection(ExternalThreading=true)]
[ComVisible(false)]
public Task FlushAsync()
{
return FlushAsync(CancellationToken.None);
}
- [HostProtection(ExternalThreading=true)]
[ComVisible(false)]
public virtual Task FlushAsync(CancellationToken cancellationToken)
{
return new ManualResetEvent(false);
}
- [HostProtection(ExternalThreading=true)]
public virtual IAsyncResult BeginRead(byte[] buffer, int offset, int count, AsyncCallback callback, Object state)
{
Contract.Ensures(Contract.Result<IAsyncResult>() != null);
return BeginReadInternal(buffer, offset, count, callback, state, serializeAsynchronously: false, apm: true);
}
- [HostProtection(ExternalThreading = true)]
internal IAsyncResult BeginReadInternal(
byte[] buffer, int offset, int count, AsyncCallback callback, Object state,
bool serializeAsynchronously, bool apm)
// As we're currently inside of it, we can get the current task
// and grab the parameters from it.
var thisTask = Task.InternalCurrent as ReadWriteTask;
- Contract.Assert(thisTask != null, "Inside ReadWriteTask, InternalCurrent should be the ReadWriteTask");
+ Debug.Assert(thisTask != null, "Inside ReadWriteTask, InternalCurrent should be the ReadWriteTask");
try
{
}
}
- [HostProtection(ExternalThreading = true)]
[ComVisible(false)]
public Task<int> ReadAsync(Byte[] buffer, int offset, int count)
{
return ReadAsync(buffer, offset, count, CancellationToken.None);
}
- [HostProtection(ExternalThreading = true)]
[ComVisible(false)]
public virtual Task<int> ReadAsync(Byte[] buffer, int offset, int count, CancellationToken cancellationToken)
{
: BeginEndReadAsync(buffer, offset, count);
}
- [System.Security.SecuritySafeCritical]
[MethodImplAttribute(MethodImplOptions.InternalCall)]
private extern bool HasOverriddenBeginEndRead();
- [HostProtection(ExternalThreading=true)]
public virtual IAsyncResult BeginWrite(byte[] buffer, int offset, int count, AsyncCallback callback, Object state)
{
Contract.Ensures(Contract.Result<IAsyncResult>() != null);
return BeginWriteInternal(buffer, offset, count, callback, state, serializeAsynchronously: false, apm: true);
}
- [HostProtection(ExternalThreading = true)]
internal IAsyncResult BeginWriteInternal(
byte[] buffer, int offset, int count, AsyncCallback callback, Object state,
bool serializeAsynchronously, bool apm)
// As we're currently inside of it, we can get the current task
// and grab the parameters from it.
var thisTask = Task.InternalCurrent as ReadWriteTask;
- Contract.Assert(thisTask != null, "Inside ReadWriteTask, InternalCurrent should be the ReadWriteTask");
+ Debug.Assert(thisTask != null, "Inside ReadWriteTask, InternalCurrent should be the ReadWriteTask");
try
{
private void RunReadWriteTaskWhenReady(Task asyncWaiter, ReadWriteTask readWriteTask)
{
- Contract.Assert(readWriteTask != null); // Should be Contract.Requires, but CCRewrite is doing a poor job with
+ Debug.Assert(readWriteTask != null); // Should be Contract.Requires, but CCRewrite is doing a poor job with
// preconditions in async methods that await.
- Contract.Assert(asyncWaiter != null); // Ditto
+ Debug.Assert(asyncWaiter != null); // Ditto
// If the wait has already completed, run the task.
if (asyncWaiter.IsCompleted)
{
- Contract.Assert(asyncWaiter.IsRanToCompletion, "The semaphore wait should always complete successfully.");
+ Debug.Assert(asyncWaiter.IsRanToCompletion, "The semaphore wait should always complete successfully.");
RunReadWriteTask(readWriteTask);
}
else // Otherwise, wait for our turn, and then run the task.
{
asyncWaiter.ContinueWith((t, state) => {
- Contract.Assert(t.IsRanToCompletion, "The semaphore wait should always complete successfully.");
+ Debug.Assert(t.IsRanToCompletion, "The semaphore wait should always complete successfully.");
var rwt = (ReadWriteTask)state;
rwt._stream.RunReadWriteTask(rwt); // RunReadWriteTask(readWriteTask);
}, readWriteTask, default(CancellationToken), TaskContinuationOptions.ExecuteSynchronously, TaskScheduler.Default);
private void RunReadWriteTask(ReadWriteTask readWriteTask)
{
Contract.Requires(readWriteTask != null);
- Contract.Assert(_activeReadWriteTask == null, "Expected no other readers or writers");
+ Debug.Assert(_activeReadWriteTask == null, "Expected no other readers or writers");
// Schedule the task. ScheduleAndStart must happen after the write to _activeReadWriteTask to avoid a race.
// Internally, we're able to directly call ScheduleAndStart rather than Start, avoiding
private void FinishTrackingAsyncOperation()
{
_activeReadWriteTask = null;
- Contract.Assert(_asyncActiveSemaphore != null, "Must have been initialized in order to get here.");
+ Debug.Assert(_asyncActiveSemaphore != null, "Must have been initialized in order to get here.");
_asyncActiveSemaphore.Release();
}
try
{
writeTask.GetAwaiter().GetResult(); // block until completion, then propagate any exceptions
- Contract.Assert(writeTask.Status == TaskStatus.RanToCompletion);
+ Debug.Assert(writeTask.Status == TaskStatus.RanToCompletion);
}
finally
{
_buffer = null;
}
- [SecuritySafeCritical] // necessary for EC.Capture
[MethodImpl(MethodImplOptions.NoInlining)]
public ReadWriteTask(
bool isRead,
}
}
- [SecurityCritical] // necessary for CoreCLR
private static void InvokeAsyncCallback(object completedTask)
{
var rwc = (ReadWriteTask)completedTask;
callback(rwc);
}
- [SecurityCritical] // necessary for CoreCLR
private static ContextCallback s_invokeAsyncCallback;
- [SecuritySafeCritical] // necessary for ExecutionContext.Run
void ITaskCompletionAction.Invoke(Task completingTask)
{
// Get the ExecutionContext. If there is none, just run the callback
bool ITaskCompletionAction.InvokeMayRunArbitraryCode { get { return true; } }
}
- [HostProtection(ExternalThreading = true)]
[ComVisible(false)]
public Task WriteAsync(Byte[] buffer, int offset, int count)
{
- [HostProtection(ExternalThreading = true)]
[ComVisible(false)]
public virtual Task WriteAsync(Byte[] buffer, int offset, int count, CancellationToken cancellationToken)
{
: BeginEndWriteAsync(buffer, offset, count);
}
- [System.Security.SecuritySafeCritical]
[MethodImplAttribute(MethodImplOptions.InternalCall)]
private extern bool HasOverriddenBeginEndWrite();
Write(oneByteArray, 0, 1);
}
- [HostProtection(Synchronization=true)]
public static Stream Synchronized(Stream stream)
{
if (stream==null)
Task.CompletedTask;
}
- [HostProtection(ExternalThreading = true)]
public override IAsyncResult BeginRead(byte[] buffer, int offset, int count, AsyncCallback callback, Object state)
{
if (!CanRead) __Error.ReadNotSupported();
return BlockingEndRead(asyncResult);
}
- [HostProtection(ExternalThreading = true)]
public override IAsyncResult BeginWrite(byte[] buffer, int offset, int count, AsyncCallback callback, Object state)
{
if (!CanWrite) __Error.WriteNotSupported();
return _stream.ReadByte();
}
- [HostProtection(ExternalThreading=true)]
public override IAsyncResult BeginRead(byte[] buffer, int offset, int count, AsyncCallback callback, Object state)
{
bool overridesBeginRead = _stream.HasOverriddenBeginEndRead();
_stream.WriteByte(b);
}
- [HostProtection(ExternalThreading=true)]
public override IAsyncResult BeginWrite(byte[] buffer, int offset, int count, AsyncCallback callback, Object state)
{
bool overridesBeginWrite = _stream.HasOverriddenBeginEndWrite();
using System.Text;
using System.Runtime.InteropServices;
using System.Runtime.Versioning;
+using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Diagnostics.Contracts;
using System.Security.Permissions;
: this(path, encoding, detectEncodingFromByteOrderMarks, DefaultBufferSize) {
}
- [System.Security.SecuritySafeCritical]
public StreamReader(String path, Encoding encoding, bool detectEncodingFromByteOrderMarks, int bufferSize)
: this(path, encoding, detectEncodingFromByteOrderMarks, bufferSize, true) {
}
- [System.Security.SecurityCritical]
internal StreamReader(String path, Encoding encoding, bool detectEncodingFromByteOrderMarks, int bufferSize, bool checkHost)
{
// Don't open a Stream before checking for invalid arguments,
// Trims n bytes from the front of the buffer.
private void CompressBuffer(int n)
{
- Contract.Assert(byteLen >= n, "CompressBuffer was called with a number of bytes greater than the current buffer length. Are two threads using this StreamReader at the same time?");
+ Debug.Assert(byteLen >= n, "CompressBuffer was called with a number of bytes greater than the current buffer length. Are two threads using this StreamReader at the same time?");
Buffer.InternalBlockCopy(byteBuffer, n, byteBuffer, 0, byteLen - n);
byteLen -= n;
}
if (!_checkPreamble)
return _checkPreamble;
- Contract.Assert(bytePos <= _preamble.Length, "_compressPreamble was called with the current bytePos greater than the preamble buffer length. Are two threads using this StreamReader at the same time?");
+ Debug.Assert(bytePos <= _preamble.Length, "_compressPreamble was called with the current bytePos greater than the preamble buffer length. Are two threads using this StreamReader at the same time?");
int len = (byteLen >= (_preamble.Length))? (_preamble.Length - bytePos) : (byteLen - bytePos);
for(int i=0; i<len; i++, bytePos++) {
}
}
- Contract.Assert(bytePos <= _preamble.Length, "possible bug in _compressPreamble. Are two threads using this StreamReader at the same time?");
+ Debug.Assert(bytePos <= _preamble.Length, "possible bug in _compressPreamble. Are two threads using this StreamReader at the same time?");
if (_checkPreamble) {
if (bytePos == _preamble.Length) {
byteLen = 0;
do {
if (_checkPreamble) {
- Contract.Assert(bytePos <= _preamble.Length, "possible bug in _compressPreamble. Are two threads using this StreamReader at the same time?");
+ Debug.Assert(bytePos <= _preamble.Length, "possible bug in _compressPreamble. Are two threads using this StreamReader at the same time?");
int len = stream.Read(byteBuffer, bytePos, byteBuffer.Length - bytePos);
- Contract.Assert(len >= 0, "Stream.Read returned a negative number! This is a bug in your stream class.");
+ Debug.Assert(len >= 0, "Stream.Read returned a negative number! This is a bug in your stream class.");
if (len == 0) {
// EOF but we might have buffered bytes from previous
byteLen += len;
}
else {
- Contract.Assert(bytePos == 0, "bytePos can be non zero only when we are trying to _checkPreamble. Are two threads using this StreamReader at the same time?");
+ Debug.Assert(bytePos == 0, "bytePos can be non zero only when we are trying to _checkPreamble. Are two threads using this StreamReader at the same time?");
byteLen = stream.Read(byteBuffer, 0, byteBuffer.Length);
- Contract.Assert(byteLen >= 0, "Stream.Read returned a negative number! This is a bug in your stream class.");
+ Debug.Assert(byteLen >= 0, "Stream.Read returned a negative number! This is a bug in your stream class.");
if (byteLen == 0) // We're at EOF
return charLen;
readToUserBuffer = desiredChars >= _maxCharsPerBuffer;
do {
- Contract.Assert(charsRead == 0);
+ Debug.Assert(charsRead == 0);
if (_checkPreamble) {
- Contract.Assert(bytePos <= _preamble.Length, "possible bug in _compressPreamble. Are two threads using this StreamReader at the same time?");
+ Debug.Assert(bytePos <= _preamble.Length, "possible bug in _compressPreamble. Are two threads using this StreamReader at the same time?");
int len = stream.Read(byteBuffer, bytePos, byteBuffer.Length - bytePos);
- Contract.Assert(len >= 0, "Stream.Read returned a negative number! This is a bug in your stream class.");
+ Debug.Assert(len >= 0, "Stream.Read returned a negative number! This is a bug in your stream class.");
if (len == 0) {
// EOF but we might have buffered bytes from previous
byteLen += len;
}
else {
- Contract.Assert(bytePos == 0, "bytePos can be non zero only when we are trying to _checkPreamble. Are two threads using this StreamReader at the same time?");
+ Debug.Assert(bytePos == 0, "bytePos can be non zero only when we are trying to _checkPreamble. Are two threads using this StreamReader at the same time?");
byteLen = stream.Read(byteBuffer, 0, byteBuffer.Length);
- Contract.Assert(byteLen >= 0, "Stream.Read returned a negative number! This is a bug in your stream class.");
+ Debug.Assert(byteLen >= 0, "Stream.Read returned a negative number! This is a bug in your stream class.");
if (byteLen == 0) // EOF
break;
}
#region Task based Async APIs
- [HostProtection(ExternalThreading=true)]
[ComVisible(false)]
public override Task<String> ReadLineAsync()
{
return GetStringAndReleaseSharedStringBuilder(sb);
}
- [HostProtection(ExternalThreading=true)]
[ComVisible(false)]
public override Task<String> ReadToEndAsync()
{
return GetStringAndReleaseSharedStringBuilder(sb);
}
- [HostProtection(ExternalThreading=true)]
[ComVisible(false)]
public override Task<int> ReadAsync(char[] buffer, int index, int count)
{
// We break out of the loop if the stream is blocked (EOF is reached).
do
{
- Contract.Assert(n == 0);
+ Debug.Assert(n == 0);
if (CheckPreamble_Prop)
{
- Contract.Assert(BytePos_Prop <= Preamble_Prop.Length, "possible bug in _compressPreamble. Are two threads using this StreamReader at the same time?");
+ Debug.Assert(BytePos_Prop <= Preamble_Prop.Length, "possible bug in _compressPreamble. Are two threads using this StreamReader at the same time?");
int tmpBytePos = BytePos_Prop;
int len = await tmpStream.ReadAsync(tmpByteBuffer, tmpBytePos, tmpByteBuffer.Length - tmpBytePos).ConfigureAwait(false);
- Contract.Assert(len >= 0, "Stream.Read returned a negative number! This is a bug in your stream class.");
+ Debug.Assert(len >= 0, "Stream.Read returned a negative number! This is a bug in your stream class.");
if (len == 0)
{
}
// How can part of the preamble yield any chars?
- Contract.Assert(n == 0);
+ Debug.Assert(n == 0);
IsBlocked_Prop = true;
break;
}
else
{
- Contract.Assert(BytePos_Prop == 0, "_bytePos can be non zero only when we are trying to _checkPreamble. Are two threads using this StreamReader at the same time?");
+ Debug.Assert(BytePos_Prop == 0, "_bytePos can be non zero only when we are trying to _checkPreamble. Are two threads using this StreamReader at the same time?");
ByteLen_Prop = await tmpStream.ReadAsync(tmpByteBuffer, 0, tmpByteBuffer.Length).ConfigureAwait(false);
- Contract.Assert(ByteLen_Prop >= 0, "Stream.Read returned a negative number! This is a bug in your stream class.");
+ Debug.Assert(ByteLen_Prop >= 0, "Stream.Read returned a negative number! This is a bug in your stream class.");
if (ByteLen_Prop == 0) // EOF
{
readToUserBuffer = count >= MaxCharsPerBuffer_Prop;
}
- Contract.Assert(n == 0);
+ Debug.Assert(n == 0);
CharPos_Prop = 0;
if (readToUserBuffer)
n += Decoder_Prop.GetChars(tmpByteBuffer, 0, ByteLen_Prop, buffer, index + charsRead);
// Why did the bytes yield no chars?
- Contract.Assert(n > 0);
+ Debug.Assert(n > 0);
CharLen_Prop = 0; // StreamReader's buffer is empty.
}
n = Decoder_Prop.GetChars(tmpByteBuffer, 0, ByteLen_Prop, CharBuffer_Prop, 0);
// Why did the bytes yield no chars?
- Contract.Assert(n > 0);
+ Debug.Assert(n > 0);
CharLen_Prop += n; // Number of chars in StreamReader's buffer.
}
return charsRead;
}
- [HostProtection(ExternalThreading=true)]
[ComVisible(false)]
public override Task<int> ReadBlockAsync(char[] buffer, int index, int count)
{
ByteLen_Prop = 0;
do {
if (CheckPreamble_Prop) {
- Contract.Assert(BytePos_Prop <= Preamble_Prop.Length, "possible bug in _compressPreamble. Are two threads using this StreamReader at the same time?");
+ Debug.Assert(BytePos_Prop <= Preamble_Prop.Length, "possible bug in _compressPreamble. Are two threads using this StreamReader at the same time?");
int tmpBytePos = BytePos_Prop;
int len = await tmpStream.ReadAsync(tmpByteBuffer, tmpBytePos, tmpByteBuffer.Length - tmpBytePos).ConfigureAwait(false);
- Contract.Assert(len >= 0, "Stream.Read returned a negative number! This is a bug in your stream class.");
+ Debug.Assert(len >= 0, "Stream.Read returned a negative number! This is a bug in your stream class.");
if (len == 0) {
// EOF but we might have buffered bytes from previous
ByteLen_Prop += len;
}
else {
- Contract.Assert(BytePos_Prop == 0, "_bytePos can be non zero only when we are trying to _checkPreamble. Are two threads using this StreamReader at the same time?");
+ Debug.Assert(BytePos_Prop == 0, "_bytePos can be non zero only when we are trying to _checkPreamble. Are two threads using this StreamReader at the same time?");
ByteLen_Prop = await tmpStream.ReadAsync(tmpByteBuffer, 0, tmpByteBuffer.Length).ConfigureAwait(false);
- Contract.Assert(ByteLen_Prop >= 0, "Stream.Read returned a negative number! Bug in stream class.");
+ Debug.Assert(ByteLen_Prop >= 0, "Stream.Read returned a negative number! Bug in stream class.");
if (ByteLen_Prop == 0) // We're at EOF
return CharLen_Prop;
using System.Runtime.Versioning;
using System.Security.Permissions;
using System.Runtime.Serialization;
+using System.Diagnostics;
using System.Diagnostics.Contracts;
using System.Runtime.InteropServices;
using System.Threading.Tasks;
: this(path, append, encoding, DefaultBufferSize) {
}
- [System.Security.SecuritySafeCritical]
public StreamWriter(String path, bool append, Encoding encoding, int bufferSize): this(path, append, encoding, bufferSize, true) {
}
- [System.Security.SecurityCritical]
internal StreamWriter(String path, bool append, Encoding encoding, int bufferSize, bool checkHost)
: base(null)
{ // Ask for CurrentCulture all the time
Init(stream, encoding, bufferSize, false);
}
- [System.Security.SecuritySafeCritical]
private void Init(Stream streamArg, Encoding encodingArg, int bufferSize, bool shouldLeaveOpen)
{
this.stream = streamArg;
#endif
}
- [System.Security.SecurityCritical]
private static Stream CreateFile(String path, bool append, bool checkHost) {
FileMode mode = append? FileMode.Append: FileMode.Create;
FileStream f = new FileStream(path, mode, FileAccess.Write, FileShare.Read,
// is generally the right thing to do.
if (stream != null) {
// Note: flush on the underlying stream can throw (ex., low disk space)
-#if FEATURE_CORECLR
if (disposing)
-#else
- if (disposing || (LeaveOpen && stream is __ConsoleStream))
-#endif
{
CheckAsyncTaskInProgress();
if (charPos == charLen) Flush(false, false);
int n = charLen - charPos;
if (n > count) n = count;
- Contract.Assert(n > 0, "StreamWriter::Write(char[]) isn't making progress! This is most likely a race condition in user code.");
+ Debug.Assert(n > 0, "StreamWriter::Write(char[]) isn't making progress! This is most likely a race condition in user code.");
Buffer.InternalBlockCopy(buffer, index * sizeof(char), charBuffer, charPos * sizeof(char), n * sizeof(char));
charPos += n;
index += n;
if (charPos == charLen) Flush(false, false);
int n = charLen - charPos;
if (n > count) n = count;
- Contract.Assert(n > 0, "StreamWriter::Write(char[], int, int) isn't making progress! This is most likely a race condition in user code.");
+ Debug.Assert(n > 0, "StreamWriter::Write(char[], int, int) isn't making progress! This is most likely a race condition in user code.");
Buffer.InternalBlockCopy(buffer, index * sizeof(char), charBuffer, charPos * sizeof(char), n * sizeof(char));
charPos += n;
index += n;
if (charPos == charLen) Flush(false, false);
int n = charLen - charPos;
if (n > count) n = count;
- Contract.Assert(n > 0, "StreamWriter::Write(String) isn't making progress! This is most likely a race condition in user code.");
+ Debug.Assert(n > 0, "StreamWriter::Write(String) isn't making progress! This is most likely a race condition in user code.");
value.CopyTo(index, charBuffer, charPos, n);
charPos += n;
index += n;
}
#region Task based Async APIs
- [HostProtection(ExternalThreading = true)]
[ComVisible(false)]
public override Task WriteAsync(char value)
{
{
if (charPos == charLen) {
await _this.FlushAsyncInternal(false, false, charBuffer, charPos).ConfigureAwait(false);
- Contract.Assert(_this.charPos == 0);
+ Debug.Assert(_this.charPos == 0);
charPos = 0;
}
{
if (charPos == charLen) {
await _this.FlushAsyncInternal(false, false, charBuffer, charPos).ConfigureAwait(false);
- Contract.Assert(_this.charPos == 0);
+ Debug.Assert(_this.charPos == 0);
charPos = 0;
}
if (autoFlush) {
await _this.FlushAsyncInternal(true, false, charBuffer, charPos).ConfigureAwait(false);
- Contract.Assert(_this.charPos == 0);
+ Debug.Assert(_this.charPos == 0);
charPos = 0;
}
_this.CharPos_Prop = charPos;
}
- [HostProtection(ExternalThreading = true)]
[ComVisible(false)]
public override Task WriteAsync(String value)
{
{
if (charPos == charLen) {
await _this.FlushAsyncInternal(false, false, charBuffer, charPos).ConfigureAwait(false);
- Contract.Assert(_this.charPos == 0);
+ Debug.Assert(_this.charPos == 0);
charPos = 0;
}
if (n > count)
n = count;
- Contract.Assert(n > 0, "StreamWriter::Write(String) isn't making progress! This is most likely a race condition in user code.");
+ Debug.Assert(n > 0, "StreamWriter::Write(String) isn't making progress! This is most likely a race condition in user code.");
value.CopyTo(index, charBuffer, charPos, n);
{
if (charPos == charLen) {
await _this.FlushAsyncInternal(false, false, charBuffer, charPos).ConfigureAwait(false);
- Contract.Assert(_this.charPos == 0);
+ Debug.Assert(_this.charPos == 0);
charPos = 0;
}
if (autoFlush) {
await _this.FlushAsyncInternal(true, false, charBuffer, charPos).ConfigureAwait(false);
- Contract.Assert(_this.charPos == 0);
+ Debug.Assert(_this.charPos == 0);
charPos = 0;
}
_this.CharPos_Prop = charPos;
}
- [HostProtection(ExternalThreading = true)]
[ComVisible(false)]
public override Task WriteAsync(char[] buffer, int index, int count)
{
{
if (charPos == charLen) {
await _this.FlushAsyncInternal(false, false, charBuffer, charPos).ConfigureAwait(false);
- Contract.Assert(_this.charPos == 0);
+ Debug.Assert(_this.charPos == 0);
charPos = 0;
}
int n = charLen - charPos;
if (n > count) n = count;
- Contract.Assert(n > 0, "StreamWriter::Write(char[], int, int) isn't making progress! This is most likely a race condition in user code.");
+ Debug.Assert(n > 0, "StreamWriter::Write(char[], int, int) isn't making progress! This is most likely a race condition in user code.");
Buffer.InternalBlockCopy(buffer, index * sizeof(char), charBuffer, charPos * sizeof(char), n * sizeof(char));
{
if (charPos == charLen) {
await _this.FlushAsyncInternal(false, false, charBuffer, charPos).ConfigureAwait(false);
- Contract.Assert(_this.charPos == 0);
+ Debug.Assert(_this.charPos == 0);
charPos = 0;
}
if (autoFlush) {
await _this.FlushAsyncInternal(true, false, charBuffer, charPos).ConfigureAwait(false);
- Contract.Assert(_this.charPos == 0);
+ Debug.Assert(_this.charPos == 0);
charPos = 0;
}
_this.CharPos_Prop = charPos;
}
- [HostProtection(ExternalThreading = true)]
[ComVisible(false)]
public override Task WriteLineAsync()
{
}
- [HostProtection(ExternalThreading = true)]
[ComVisible(false)]
public override Task WriteLineAsync(char value)
{
}
- [HostProtection(ExternalThreading = true)]
[ComVisible(false)]
public override Task WriteLineAsync(String value)
{
}
- [HostProtection(ExternalThreading = true)]
[ComVisible(false)]
public override Task WriteLineAsync(char[] buffer, int index, int count)
{
}
- [HostProtection(ExternalThreading = true)]
[ComVisible(false)]
public override Task FlushAsync()
{
}
#region Task based Async APIs
- [HostProtection(ExternalThreading=true)]
[ComVisible(false)]
public virtual Task<String> ReadLineAsync()
{
this, CancellationToken.None, TaskCreationOptions.DenyChildAttach, TaskScheduler.Default);
}
- [HostProtection(ExternalThreading=true)]
[ComVisible(false)]
public async virtual Task<String> ReadToEndAsync()
{
return sb.ToString();
}
- [HostProtection(ExternalThreading=true)]
[ComVisible(false)]
public virtual Task<int> ReadAsync(char[] buffer, int index, int count)
{
tuple, CancellationToken.None, TaskCreationOptions.DenyChildAttach, TaskScheduler.Default);
}
- [HostProtection(ExternalThreading=true)]
[ComVisible(false)]
public virtual Task<int> ReadBlockAsync(char[] buffer, int index, int count)
{
return ReadBlockAsyncInternal(buffer, index, count);
}
- [HostProtection(ExternalThreading=true)]
private async Task<int> ReadBlockAsyncInternal(char[] buffer, int index, int count)
{
Contract.Requires(buffer != null);
}
#endregion
- [HostProtection(Synchronization=true)]
public static TextReader Synchronized(TextReader reader)
{
if (reader==null)
}
- [HostProtection(Synchronization=true)]
public static TextWriter Synchronized(TextWriter writer) {
if (writer==null)
throw new ArgumentNullException(nameof(writer));
}
#region Task based Async APIs
- [HostProtection(ExternalThreading = true)]
[ComVisible(false)]
public virtual Task WriteAsync(char value)
{
tuple, CancellationToken.None, TaskCreationOptions.DenyChildAttach, TaskScheduler.Default);
}
- [HostProtection(ExternalThreading = true)]
[ComVisible(false)]
public virtual Task WriteAsync(String value)
{
tuple, CancellationToken.None, TaskCreationOptions.DenyChildAttach, TaskScheduler.Default);
}
- [HostProtection(ExternalThreading = true)]
[ComVisible(false)]
public Task WriteAsync(char[] buffer)
{
return WriteAsync(buffer, 0, buffer.Length);
}
- [HostProtection(ExternalThreading = true)]
[ComVisible(false)]
public virtual Task WriteAsync(char[] buffer, int index, int count)
{
tuple, CancellationToken.None, TaskCreationOptions.DenyChildAttach, TaskScheduler.Default);
}
- [HostProtection(ExternalThreading = true)]
[ComVisible(false)]
public virtual Task WriteLineAsync(char value)
{
tuple, CancellationToken.None, TaskCreationOptions.DenyChildAttach, TaskScheduler.Default);
}
- [HostProtection(ExternalThreading = true)]
[ComVisible(false)]
public virtual Task WriteLineAsync(String value)
{
tuple, CancellationToken.None, TaskCreationOptions.DenyChildAttach, TaskScheduler.Default);
}
- [HostProtection(ExternalThreading = true)]
[ComVisible(false)]
public Task WriteLineAsync(char[] buffer)
{
return WriteLineAsync(buffer, 0, buffer.Length);
}
- [HostProtection(ExternalThreading = true)]
[ComVisible(false)]
public virtual Task WriteLineAsync(char[] buffer, int index, int count)
{
tuple, CancellationToken.None, TaskCreationOptions.DenyChildAttach, TaskScheduler.Default);
}
- [HostProtection(ExternalThreading = true)]
[ComVisible(false)]
public virtual Task WriteLineAsync()
{
return WriteAsync(CoreNewLine);
}
- [HostProtection(ExternalThreading = true)]
[ComVisible(false)]
public virtual Task FlushAsync()
{
using System.Runtime.Versioning;
using System.Security.Permissions;
using Microsoft.Win32.SafeHandles;
+using System.Diagnostics;
using System.Diagnostics.Contracts;
namespace System.IO {
/// this gives better throughput; benchmarks showed about 12-15% better.
public class UnmanagedMemoryAccessor : IDisposable {
- [System.Security.SecurityCritical] // auto-generated
private SafeBuffer _buffer;
private Int64 _offset;
[ContractPublicPropertyName("Capacity")]
// <SecurityKernel Critical="True" Ring="1">
// <ReferencesCritical Name="Method: Initialize(SafeBuffer, Int64, Int64, FileAccess):Void" Ring="1" />
// </SecurityKernel>
- [System.Security.SecuritySafeCritical]
public UnmanagedMemoryAccessor(SafeBuffer buffer, Int64 offset, Int64 capacity) {
Initialize(buffer, offset, capacity, FileAccess.Read);
}
- [System.Security.SecuritySafeCritical] // auto-generated
public UnmanagedMemoryAccessor(SafeBuffer buffer, Int64 offset, Int64 capacity, FileAccess access) {
Initialize(buffer, offset, capacity, access);
}
- [System.Security.SecuritySafeCritical] // auto-generated
-#pragma warning disable 618
- [SecurityPermissionAttribute(SecurityAction.Demand, Flags = SecurityPermissionFlag.UnmanagedCode)]
-#pragma warning restore 618
protected void Initialize(SafeBuffer buffer, Int64 offset, Int64 capacity, FileAccess access) {
if (buffer == null) {
throw new ArgumentNullException(nameof(buffer));
return InternalReadByte(position);
}
- [System.Security.SecuritySafeCritical] // auto-generated
public char ReadChar(Int64 position) {
int sizeOfType = sizeof(char);
EnsureSafeToRead(position, sizeOfType);
}
// See comment above.
- [System.Security.SecuritySafeCritical]
public Int16 ReadInt16(Int64 position) {
int sizeOfType = sizeof(Int16);
EnsureSafeToRead(position, sizeOfType);
}
- [System.Security.SecuritySafeCritical] // auto-generated
public Int32 ReadInt32(Int64 position) {
int sizeOfType = sizeof(Int32);
EnsureSafeToRead(position, sizeOfType);
return result;
}
- [System.Security.SecuritySafeCritical] // auto-generated
public Int64 ReadInt64(Int64 position) {
int sizeOfType = sizeof(Int64);
EnsureSafeToRead(position, sizeOfType);
return result;
}
- [System.Security.SecurityCritical]
[MethodImpl(MethodImplOptions.AggressiveInlining)]
private unsafe Int32 UnsafeReadInt32(byte* pointer)
{
return result;
}
- [System.Security.SecuritySafeCritical] // auto-generated
public Decimal ReadDecimal(Int64 position) {
const int ScaleMask = 0x00FF0000;
const int SignMask = unchecked((int)0x80000000);
}
}
- [System.Security.SecuritySafeCritical] // auto-generated
public Single ReadSingle(Int64 position) {
int sizeOfType = sizeof(Single);
EnsureSafeToRead(position, sizeOfType);
return result;
}
- [System.Security.SecuritySafeCritical] // auto-generated
public Double ReadDouble(Int64 position) {
int sizeOfType = sizeof(Double);
EnsureSafeToRead(position, sizeOfType);
return result;
}
- [System.Security.SecuritySafeCritical] // auto-generated
[CLSCompliant(false)]
public SByte ReadSByte(Int64 position) {
int sizeOfType = sizeof(SByte);
return result;
}
- [System.Security.SecuritySafeCritical] // auto-generated
[CLSCompliant(false)]
public UInt16 ReadUInt16(Int64 position) {
int sizeOfType = sizeof(UInt16);
return result;
}
- [System.Security.SecuritySafeCritical] // auto-generated
[CLSCompliant(false)]
public UInt32 ReadUInt32(Int64 position) {
int sizeOfType = sizeof(UInt32);
return result;
}
- [System.Security.SecuritySafeCritical] // auto-generated
[CLSCompliant(false)]
public UInt64 ReadUInt64(Int64 position) {
int sizeOfType = sizeof(UInt64);
// such, it is best to use the ReadXXX methods for small standard types such as ints, longs,
// bools, etc.
- [System.Security.SecurityCritical] // auto-generated_required
public void Read<T>(Int64 position, out T structure) where T : struct {
if (position < 0) {
throw new ArgumentOutOfRangeException(nameof(position), Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
// struct that contains reference members will most likely cause the runtime to AV. This
// is consistent with Marshal.PtrToStructure.
- [System.Security.SecurityCritical] // auto-generated_required
public int ReadArray<T>(Int64 position, T[] array, Int32 offset, Int32 count) where T : struct {
if (array == null) {
throw new ArgumentNullException(nameof(array), "Buffer cannot be null.");
InternalWrite(position, value);
}
- [System.Security.SecuritySafeCritical] // auto-generated
public void Write(Int64 position, char value) {
int sizeOfType = sizeof(char);
EnsureSafeToWrite(position, sizeOfType);
}
- [System.Security.SecuritySafeCritical] // auto-generated
public void Write(Int64 position, Int16 value) {
int sizeOfType = sizeof(Int16);
EnsureSafeToWrite(position, sizeOfType);
}
- [System.Security.SecuritySafeCritical] // auto-generated
public void Write(Int64 position, Int32 value) {
int sizeOfType = sizeof(Int32);
EnsureSafeToWrite(position, sizeOfType);
}
}
- [System.Security.SecuritySafeCritical] // auto-generated
public void Write(Int64 position, Int64 value) {
int sizeOfType = sizeof(Int64);
EnsureSafeToWrite(position, sizeOfType);
}
}
- [System.Security.SecurityCritical]
[MethodImpl(MethodImplOptions.AggressiveInlining)]
private unsafe void UnsafeWriteInt32(byte* pointer, Int32 value)
{
}
}
- [System.Security.SecuritySafeCritical] // auto-generated
public void Write(Int64 position, Decimal value) {
int sizeOfType = sizeof(Decimal);
EnsureSafeToWrite(position, sizeOfType);
}
}
- [System.Security.SecuritySafeCritical] // auto-generated
public void Write(Int64 position, Single value) {
int sizeOfType = sizeof(Single);
EnsureSafeToWrite(position, sizeOfType);
}
}
- [System.Security.SecuritySafeCritical] // auto-generated
public void Write(Int64 position, Double value) {
int sizeOfType = sizeof(Double);
EnsureSafeToWrite(position, sizeOfType);
}
}
- [System.Security.SecuritySafeCritical] // auto-generated
[CLSCompliant(false)]
public void Write(Int64 position, SByte value) {
int sizeOfType = sizeof(SByte);
}
}
- [System.Security.SecuritySafeCritical] // auto-generated
[CLSCompliant(false)]
public void Write(Int64 position, UInt16 value) {
int sizeOfType = sizeof(UInt16);
}
}
- [System.Security.SecuritySafeCritical] // auto-generated
[CLSCompliant(false)]
public void Write(Int64 position, UInt32 value) {
int sizeOfType = sizeof(UInt32);
}
}
- [System.Security.SecuritySafeCritical] // auto-generated
[CLSCompliant(false)]
public void Write(Int64 position, UInt64 value) {
int sizeOfType = sizeof(UInt64);
// though this is number is JIT and architecture dependent). As such, it is best to use
// the WriteX methods for small standard types such as ints, longs, bools, etc.
- [System.Security.SecurityCritical] // auto-generated_required
public void Write<T>(Int64 position, ref T structure) where T : struct {
if (position < 0) {
throw new ArgumentOutOfRangeException(nameof(position), Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
// Writes 'count' structs of type T from 'array' (starting at 'offset') into unmanaged memory.
- [System.Security.SecurityCritical] // auto-generated_required
public void WriteArray<T>(Int64 position, T[] array, Int32 offset, Int32 count) where T : struct {
if (array == null) {
throw new ArgumentNullException(nameof(array), "Buffer cannot be null.");
_buffer.WriteArray<T>((UInt64)(_offset + position), array, offset, count);
}
- [System.Security.SecuritySafeCritical] // auto-generated
private byte InternalReadByte(Int64 position) {
- Contract.Assert(CanRead, "UMA not readable");
- Contract.Assert(position >= 0, "position less than 0");
- Contract.Assert(position <= _capacity - sizeof(byte), "position is greater than capacity - sizeof(byte)");
+ Debug.Assert(CanRead, "UMA not readable");
+ Debug.Assert(position >= 0, "position less than 0");
+ Debug.Assert(position <= _capacity - sizeof(byte), "position is greater than capacity - sizeof(byte)");
byte result;
unsafe {
return result;
}
- [System.Security.SecuritySafeCritical] // auto-generated
private void InternalWrite(Int64 position, byte value) {
- Contract.Assert(CanWrite, "UMA not writable");
- Contract.Assert(position >= 0, "position less than 0");
- Contract.Assert(position <= _capacity - sizeof(byte), "position is greater than capacity - sizeof(byte)");
+ Debug.Assert(CanWrite, "UMA not writable");
+ Debug.Assert(position >= 0, "position less than 0");
+ Debug.Assert(position <= _capacity - sizeof(byte), "position is greater than capacity - sizeof(byte)");
unsafe {
byte* pointer = null;
using System.Security;
using System.Security.Permissions;
using System.Threading;
+using System.Diagnostics;
using System.Diagnostics.Contracts;
using System.Threading.Tasks;
{
private const long UnmanagedMemStreamMaxLength = Int64.MaxValue;
- [System.Security.SecurityCritical] // auto-generated
private SafeBuffer _buffer;
- [SecurityCritical]
private unsafe byte* _mem;
private long _length;
private long _capacity;
// Needed for subclasses that need to map a file, etc.
- [System.Security.SecuritySafeCritical] // auto-generated
protected UnmanagedMemoryStream()
{
unsafe {
_isOpen = false;
}
- [System.Security.SecuritySafeCritical] // auto-generated
public UnmanagedMemoryStream(SafeBuffer buffer, long offset, long length) {
Initialize(buffer, offset, length, FileAccess.Read, false);
}
- [System.Security.SecuritySafeCritical] // auto-generated
public UnmanagedMemoryStream(SafeBuffer buffer, long offset, long length, FileAccess access) {
Initialize(buffer, offset, length, access, false);
}
// We must create one of these without doing a security check. This
// class is created while security is trying to start up. Plus, doing
// a Demand from Assembly.GetManifestResourceStream isn't useful.
- [System.Security.SecurityCritical] // auto-generated
internal UnmanagedMemoryStream(SafeBuffer buffer, long offset, long length, FileAccess access, bool skipSecurityCheck) {
Initialize(buffer, offset, length, access, skipSecurityCheck);
}
- [System.Security.SecuritySafeCritical] // auto-generated
protected void Initialize(SafeBuffer buffer, long offset, long length, FileAccess access) {
Initialize(buffer, offset, length, access, false);
}
- [System.Security.SecurityCritical] // auto-generated
internal void Initialize(SafeBuffer buffer, long offset, long length, FileAccess access, bool skipSecurityCheck) {
if (buffer == null) {
throw new ArgumentNullException(nameof(buffer));
_isOpen = true;
}
- [System.Security.SecurityCritical] // auto-generated
[CLSCompliant(false)]
public unsafe UnmanagedMemoryStream(byte* pointer, long length)
{
Initialize(pointer, length, length, FileAccess.Read, false);
}
- [System.Security.SecurityCritical] // auto-generated
[CLSCompliant(false)]
public unsafe UnmanagedMemoryStream(byte* pointer, long length, long capacity, FileAccess access)
{
// We must create one of these without doing a security check. This
// class is created while security is trying to start up. Plus, doing
// a Demand from Assembly.GetManifestResourceStream isn't useful.
- [System.Security.SecurityCritical] // auto-generated
internal unsafe UnmanagedMemoryStream(byte* pointer, long length, long capacity, FileAccess access, bool skipSecurityCheck)
{
Initialize(pointer, length, capacity, access, skipSecurityCheck);
}
- [System.Security.SecurityCritical] // auto-generated
[CLSCompliant(false)]
protected unsafe void Initialize(byte* pointer, long length, long capacity, FileAccess access)
{
Initialize(pointer, length, capacity, access, false);
}
- [System.Security.SecurityCritical] // auto-generated
internal unsafe void Initialize(byte* pointer, long length, long capacity, FileAccess access, bool skipSecurityCheck)
{
if (pointer == null)
get { return _isOpen && (_access & FileAccess.Write) != 0; }
}
- [System.Security.SecuritySafeCritical] // auto-generated
protected override void Dispose(bool disposing)
{
_isOpen = false;
if (!_isOpen) __Error.StreamIsClosed();
}
- [HostProtection(ExternalThreading=true)]
[ComVisible(false)]
public override Task FlushAsync(CancellationToken cancellationToken) {
Contract.EndContractBlock();
return Interlocked.Read(ref _position);
}
- [System.Security.SecuritySafeCritical] // auto-generated
set {
if (value < 0)
throw new ArgumentOutOfRangeException(nameof(value), Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
[CLSCompliant(false)]
public unsafe byte* PositionPointer {
- [System.Security.SecurityCritical] // auto-generated_required
get {
if (_buffer != null) {
throw new NotSupportedException(Environment.GetResourceString("NotSupported_UmsSafeBuffer"));
if (!_isOpen) __Error.StreamIsClosed();
return ptr;
}
- [System.Security.SecurityCritical] // auto-generated_required
set {
if (_buffer != null)
throw new NotSupportedException(Environment.GetResourceString("NotSupported_UmsSafeBuffer"));
}
internal unsafe byte* Pointer {
- [System.Security.SecurityCritical] // auto-generated
get {
if (_buffer != null)
throw new NotSupportedException(Environment.GetResourceString("NotSupported_UmsSafeBuffer"));
}
}
- [System.Security.SecuritySafeCritical] // auto-generated
public override int Read([In, Out] byte[] buffer, int offset, int count) {
if (buffer==null)
throw new ArgumentNullException(nameof(buffer), Environment.GetResourceString("ArgumentNull_Buffer"));
int nInt = (int) n; // Safe because n <= count, which is an Int32
if (nInt < 0)
return 0; // _position could be beyond EOF
- Contract.Assert(pos + nInt >= 0, "_position + n >= 0"); // len is less than 2^63 -1.
+ Debug.Assert(pos + nInt >= 0, "_position + n >= 0"); // len is less than 2^63 -1.
unsafe
{
return nInt;
}
- [HostProtection(ExternalThreading = true)]
[ComVisible(false)]
public override Task<Int32> ReadAsync(Byte[] buffer, Int32 offset, Int32 count, CancellationToken cancellationToken) {
if (buffer==null)
} catch (Exception ex) {
- Contract.Assert(! (ex is OperationCanceledException));
+ Debug.Assert(! (ex is OperationCanceledException));
return Task.FromException<Int32>(ex);
}
}
- [System.Security.SecuritySafeCritical] // auto-generated
public override int ReadByte() {
if (!_isOpen) __Error.StreamIsClosed();
if (!CanRead) __Error.ReadNotSupported();
}
long finalPos = Interlocked.Read(ref _position);
- Contract.Assert(finalPos >= 0, "_position >= 0");
+ Debug.Assert(finalPos >= 0, "_position >= 0");
return finalPos;
}
- [System.Security.SecuritySafeCritical] // auto-generated
public override void SetLength(long value) {
if (value < 0)
throw new ArgumentOutOfRangeException("length", Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
}
}
- [System.Security.SecuritySafeCritical] // auto-generated
public override void Write(byte[] buffer, int offset, int count) {
if (buffer==null)
throw new ArgumentNullException(nameof(buffer), Environment.GetResourceString("ArgumentNull_Buffer"));
return;
}
- [HostProtection(ExternalThreading = true)]
[ComVisible(false)]
public override Task WriteAsync(Byte[] buffer, Int32 offset, Int32 count, CancellationToken cancellationToken) {
} catch (Exception ex) {
- Contract.Assert(! (ex is OperationCanceledException));
+ Debug.Assert(! (ex is OperationCanceledException));
return Task.FromException<Int32>(ex);
}
}
- [System.Security.SecuritySafeCritical] // auto-generated
public override void WriteByte(byte value) {
if (!_isOpen) __Error.StreamIsClosed();
if (!CanWrite) __Error.WriteNotSupported();
return _unmanagedStream.Seek(offset, loc);
}
- [System.Security.SecuritySafeCritical] // auto-generated
public unsafe override byte[] ToArray() {
if (!_unmanagedStream._isOpen) __Error.StreamIsClosed();
if (!_unmanagedStream.CanRead) __Error.ReadNotSupported();
// discovery permission to that path. If we do not, return just the
// file name. If we know it is a directory, then don't return the
// directory name.
- [System.Security.SecurityCritical] // auto-generated
internal static String GetDisplayablePath(String path, bool isInvalidPath)
{
bool safeToReturn = false;
try {
if (!isInvalidPath) {
-#if !FEATURE_CORECLR
- new FileIOPermission(FileIOPermissionAccess.PathDiscovery, new String[] { path }, false, false).Demand();
-#endif
safeToReturn = true;
}
}
return path;
}
- [System.Security.SecuritySafeCritical] // auto-generated
internal static void WinIOError() {
int errorCode = Marshal.GetLastWin32Error();
WinIOError(errorCode, String.Empty);
// will determine the appropriate exception to throw dependent on your
// error, and depending on the error, insert a string into the message
// gotten from the ResourceManager.
- [System.Security.SecurityCritical] // auto-generated
internal static void WinIOError(int errorCode, String maybeFullPath) {
// This doesn't have to be perfect, but is a perf optimization.
bool isInvalidPath = errorCode == Win32Native.ERROR_INVALID_NAME || errorCode == Win32Native.ERROR_BAD_PATHNAME;
}
// An alternative to WinIOError with friendlier messages for drives
- [System.Security.SecuritySafeCritical] // auto-generated
internal static void WinIODriveError(String driveName) {
int errorCode = Marshal.GetLastWin32Error();
WinIODriveError(driveName, errorCode);
}
- [System.Security.SecurityCritical] // auto-generated
internal static void WinIODriveError(String driveName, int errorCode)
{
switch (errorCode) {
}
- [System.Security.SecuritySafeCritical] // auto-generated
public override String ToString() {
Contract.Ensures(Contract.Result<String>() != null);
return Number.FormatInt32(m_value, null, NumberFormatInfo.CurrentInfo);
}
- [System.Security.SecuritySafeCritical] // auto-generated
public String ToString(IFormatProvider provider) {
Contract.Ensures(Contract.Result<String>() != null);
return Number.FormatInt32(m_value, null, NumberFormatInfo.GetInstance(provider));
return ToString(format, NumberFormatInfo.GetInstance(provider));
}
- [System.Security.SecuritySafeCritical] // auto-generated
private String ToString(String format, NumberFormatInfo info) {
Contract.Ensures(Contract.Result<String>() != null);
return m_value;
}
- [System.Security.SecuritySafeCritical] // auto-generated
[Pure]
public override String ToString() {
Contract.Ensures(Contract.Result<String>() != null);
return Number.FormatInt32(m_value, null, NumberFormatInfo.CurrentInfo);
}
- [System.Security.SecuritySafeCritical] // auto-generated
[Pure]
public String ToString(String format) {
Contract.Ensures(Contract.Result<String>() != null);
return Number.FormatInt32(m_value, format, NumberFormatInfo.CurrentInfo);
}
- [System.Security.SecuritySafeCritical] // auto-generated
[Pure]
public String ToString(IFormatProvider provider) {
Contract.Ensures(Contract.Result<String>() != null);
}
[Pure]
- [System.Security.SecuritySafeCritical] // auto-generated
public String ToString(String format, IFormatProvider provider) {
Contract.Ensures(Contract.Result<String>() != null);
return Number.FormatInt32(m_value, format, NumberFormatInfo.GetInstance(provider));
return (unchecked((int)((long)m_value)) ^ (int)(m_value >> 32));
}
- [System.Security.SecuritySafeCritical] // auto-generated
public override String ToString() {
Contract.Ensures(Contract.Result<String>() != null);
return Number.FormatInt64(m_value, null, NumberFormatInfo.CurrentInfo);
}
- [System.Security.SecuritySafeCritical] // auto-generated
public String ToString(IFormatProvider provider) {
Contract.Ensures(Contract.Result<String>() != null);
return Number.FormatInt64(m_value, null, NumberFormatInfo.GetInstance(provider));
}
- [System.Security.SecuritySafeCritical] // auto-generated
public String ToString(String format) {
Contract.Ensures(Contract.Result<String>() != null);
return Number.FormatInt64(m_value, format, NumberFormatInfo.CurrentInfo);
}
- [System.Security.SecuritySafeCritical] // auto-generated
public String ToString(String format, IFormatProvider provider) {
Contract.Ensures(Contract.Result<String>() != null);
return Number.FormatInt64(m_value, format, NumberFormatInfo.GetInstance(provider));
[System.Runtime.InteropServices.ComVisible(true)]
public struct IntPtr : IEquatable<IntPtr>, ISerializable
{
- [SecurityCritical]
unsafe private void* m_value; // The compiler treats void* closest to uint hence explicit casts are required to preserve int behavior
public static readonly IntPtr Zero;
// fast way to compare IntPtr to (IntPtr)0 while IntPtr.Zero doesn't work due to slow statics access
- [System.Security.SecuritySafeCritical] // auto-generated
[Pure]
[ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)]
internal unsafe bool IsNull()
return (this.m_value == null);
}
- [System.Security.SecuritySafeCritical] // auto-generated
[ReliabilityContract(Consistency.MayCorruptInstance, Cer.MayFail)]
[System.Runtime.Versioning.NonVersionable]
public unsafe IntPtr(int value)
#endif
}
- [System.Security.SecuritySafeCritical] // auto-generated
[ReliabilityContract(Consistency.MayCorruptInstance, Cer.MayFail)]
[System.Runtime.Versioning.NonVersionable]
public unsafe IntPtr(long value)
#endif
}
- [System.Security.SecurityCritical]
[CLSCompliant(false)]
[ReliabilityContract(Consistency.MayCorruptInstance, Cer.MayFail)]
[System.Runtime.Versioning.NonVersionable]
m_value = value;
}
- [System.Security.SecurityCritical] // auto-generated
private unsafe IntPtr(SerializationInfo info, StreamingContext context) {
long l = info.GetInt64("value");
m_value = (void *)l;
}
- [System.Security.SecurityCritical]
unsafe void ISerializable.GetObjectData(SerializationInfo info, StreamingContext context) {
if (info==null) {
throw new ArgumentNullException(nameof(info));
#endif
}
- [System.Security.SecuritySafeCritical] // auto-generated
public unsafe override bool Equals(Object obj) {
if (obj is IntPtr) {
return (m_value == ((IntPtr)obj).m_value);
return false;
}
- [SecuritySafeCritical]
unsafe bool IEquatable<IntPtr>.Equals(IntPtr other)
{
return m_value == other.m_value;
}
- [System.Security.SecuritySafeCritical] // auto-generated
public unsafe override int GetHashCode() {
-#if FEATURE_CORECLR
#if BIT64
long l = (long)m_value;
return (unchecked((int)l) ^ (int)(l >> 32));
#else // !BIT64 (32)
return unchecked((int)m_value);
#endif
-#else
- return unchecked((int)((long)m_value));
-#endif
}
- [System.Security.SecuritySafeCritical] // auto-generated
[ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)]
[System.Runtime.Versioning.NonVersionable]
public unsafe int ToInt32() {
#endif
}
- [System.Security.SecuritySafeCritical] // auto-generated
[ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)]
[System.Runtime.Versioning.NonVersionable]
public unsafe long ToInt64() {
#endif
}
- [System.Security.SecuritySafeCritical] // auto-generated
public unsafe override String ToString() {
#if BIT64
return ((long)m_value).ToString(CultureInfo.InvariantCulture);
#endif
}
- [System.Security.SecuritySafeCritical] // auto-generated
public unsafe String ToString(String format)
{
Contract.Ensures(Contract.Result<String>() != null);
return new IntPtr(value);
}
- [System.Security.SecurityCritical]
[CLSCompliant(false), ReliabilityContract(Consistency.MayCorruptInstance, Cer.MayFail)]
[System.Runtime.Versioning.NonVersionable]
public static unsafe explicit operator IntPtr (void* value)
return new IntPtr(value);
}
- [System.Security.SecuritySafeCritical] // auto-generated
[CLSCompliant(false)]
[System.Runtime.Versioning.NonVersionable]
public static unsafe explicit operator void* (IntPtr value)
return value.m_value;
}
- [System.Security.SecuritySafeCritical] // auto-generated
[System.Runtime.Versioning.NonVersionable]
public unsafe static explicit operator int (IntPtr value)
{
#endif
}
- [System.Security.SecuritySafeCritical] // auto-generated
[System.Runtime.Versioning.NonVersionable]
public unsafe static explicit operator long (IntPtr value)
{
#endif
}
- [System.Security.SecuritySafeCritical] // auto-generated
[ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)]
[System.Runtime.Versioning.NonVersionable]
public unsafe static bool operator == (IntPtr value1, IntPtr value2)
return value1.m_value == value2.m_value;
}
- [System.Security.SecuritySafeCritical] // auto-generated
[ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)]
[System.Runtime.Versioning.NonVersionable]
public unsafe static bool operator != (IntPtr value1, IntPtr value2)
}
- [System.Security.SecuritySafeCritical] // auto-generated
[CLSCompliant(false)]
[ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)]
[System.Runtime.Versioning.NonVersionable]
new Dictionary<Object, UInt32>();
new Dictionary<UInt32, Object>();
new Dictionary<Int64, Object>();
-#if FEATURE_CORECLR
+
// to genereate mdil for Dictionary instantiation when key is user defined value type
new Dictionary<Guid, Int32>();
-#endif
- // Microsoft.Windows.Design
+ // Microsoft.Windows.Design
new Dictionary<System.Reflection.MemberTypes, Object>();
new EnumEqualityComparer<System.Reflection.MemberTypes>();
- // Microsoft.Expression.DesignModel
+ // Microsoft.Expression.DesignModel
new Dictionary<Object, KeyValuePair<Object,Object>>();
new Dictionary<KeyValuePair<Object,Object>, Object>();
SZArrayHelper<CustomAttributeTypedArgument>(null);
SZArrayHelper<CustomAttributeNamedArgument>(null);
-#if FEATURE_CORECLR
#pragma warning disable 4014
// This is necessary to generate MDIL for AsyncVoidMethodBuilder
AsyncHelper<int>();
AsyncHelper2<int>();
AsyncHelper3();
#pragma warning restore 4014
-#endif
}
static T NullableHelper<T>() where T : struct
oSZArrayHelper.GetEnumerator<T>();
}
-#if FEATURE_CORECLR
// System.Runtime.CompilerServices.AsyncVoidMethodBuilder
// System.Runtime.CompilerServices.TaskAwaiter
static async void AsyncHelper<T>()
{
await Task.FromResult<string>("");
}
-#endif
#if FEATURE_COMINTEROP
// typed as matching instantiations of mscorlib copies of WinRT interfaces (IIterable<T>, IVector<T>,
// IMap<K, V>, ...) which is necessary to generate all required IL stubs.
- [SecurityCritical]
static void CommonlyUsedWinRTRedirectedInterfaceStubs()
{
WinRT_IEnumerable<byte>(null, null, null);
WinRT_Nullable<double>();
}
- [SecurityCritical]
static void WinRT_IEnumerable<T>(IterableToEnumerableAdapter iterableToEnumerableAdapter, EnumerableToIterableAdapter enumerableToIterableAdapter, IIterable<T> iterable)
{
// instantiate stubs for the one method on IEnumerable<T> and the one method on IIterable<T>
enumerableToIterableAdapter.First_Stub<T>();
}
- [SecurityCritical]
static void WinRT_IList<T>(VectorToListAdapter vectorToListAdapter, VectorToCollectionAdapter vectorToCollectionAdapter, ListToVectorAdapter listToVectorAdapter, IVector<T> vector)
{
WinRT_IEnumerable<T>(null, null, null);
listToVectorAdapter.Clear<T>();
}
- [SecurityCritical]
static void WinRT_IReadOnlyCollection<T>(VectorViewToReadOnlyCollectionAdapter vectorViewToReadOnlyCollectionAdapter)
{
WinRT_IEnumerable<T>(null, null, null);
vectorViewToReadOnlyCollectionAdapter.Count<T>();
}
- [SecurityCritical]
static void WinRT_IReadOnlyList<T>(IVectorViewToIReadOnlyListAdapter vectorToListAdapter, IReadOnlyListToIVectorViewAdapter listToVectorAdapter, IVectorView<T> vectorView)
{
WinRT_IEnumerable<T>(null, null, null);
listToVectorAdapter.Size<T>();
}
- [SecurityCritical]
static void WinRT_IDictionary<K, V>(MapToDictionaryAdapter mapToDictionaryAdapter, MapToCollectionAdapter mapToCollectionAdapter, DictionaryToMapAdapter dictionaryToMapAdapter, IMap<K, V> map)
{
WinRT_IEnumerable<KeyValuePair<K, V>>(null, null, null);
dictionaryToMapAdapter.Clear<K, V>();
}
- [SecurityCritical]
static void WinRT_IReadOnlyDictionary<K, V>(IMapViewToIReadOnlyDictionaryAdapter mapToDictionaryAdapter, IReadOnlyDictionaryToIMapViewAdapter dictionaryToMapAdapter, IMapView<K, V> mapView, MapViewToReadOnlyCollectionAdapter mapViewToReadOnlyCollectionAdapter)
{
WinRT_IEnumerable<KeyValuePair<K, V>>(null, null, null);
dictionaryToMapAdapter.HasKey<K, V>(default(K));
}
- [SecurityCritical]
static void WinRT_Nullable<T>() where T : struct
{
Nullable<T> nullable = new Nullable<T>();
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
-namespace System {
- using System.Runtime.Serialization;
- using System.Runtime.CompilerServices;
+using System.Runtime.Serialization;
+namespace System
+{
[Serializable]
[System.Security.Permissions.HostProtection(MayLeakOnAbort = true)]
-#if !FEATURE_CORECLR
- [TypeForwardedFrom("System.Core, Version=3.5.0.0, Culture=Neutral, PublicKeyToken=b77a5c561934e089")]
-#endif
- public class InvalidTimeZoneException : Exception {
+ public class InvalidTimeZoneException : Exception
+ {
public InvalidTimeZoneException(String message)
: base(message) { }
/// </remarks>
[Serializable]
[ComVisible(false)]
-#if !FEATURE_CORECLR
- [HostProtection(Synchronization = true, ExternalThreading = true)]
-#endif
[DebuggerTypeProxy(typeof(System_LazyDebugView<>))]
[DebuggerDisplay("ThreadSafetyMode={Mode}, IsValueCreated={IsValueCreated}, IsValueFaulted={IsValueFaulted}, Value={ValueForDebugDisplay}")]
public class Lazy<T>
// 2- Flag to m_threadSafeObj if ExecutionAndPublication mode and the value is known to be initialized
static readonly Func<T> ALREADY_INVOKED_SENTINEL = delegate
{
- Contract.Assert(false, "ALREADY_INVOKED_SENTINEL should never be invoked.");
+ Debug.Assert(false, "ALREADY_INVOKED_SENTINEL should never be invoked.");
return default(T);
};
}
LazyInternalExceptionHolder exc = m_boxed as LazyInternalExceptionHolder;
- Contract.Assert(exc != null);
+ Debug.Assert(exc != null);
exc.m_edi.Throw();
}
// Fall through to the slow path.
-#if !FEATURE_CORECLR
- // We call NOCTD to abort attempts by the debugger to funceval this property (e.g. on mouseover)
- // (the debugger proxy is the correct way to look at state/value of this object)
- Debugger.NotifyOfCrossThreadDependency();
-#endif
return LazyInitValue();
-
}
}
if (threadSafeObj != (object)ALREADY_INVOKED_SENTINEL)
Monitor.Enter(threadSafeObj, ref lockTaken);
else
- Contract.Assert(m_boxed != null);
+ Debug.Assert(m_boxed != null);
if (m_boxed == null)
{
if (boxed == null) // it is not Boxed, so it is a LazyInternalExceptionHolder
{
LazyInternalExceptionHolder exHolder = m_boxed as LazyInternalExceptionHolder;
- Contract.Assert(exHolder != null);
+ Debug.Assert(exHolder != null);
exHolder.m_edi.Throw();
}
}
Monitor.Exit(threadSafeObj);
}
}
- Contract.Assert(boxed != null);
+ Debug.Assert(boxed != null);
return boxed.m_value;
}
public static class Console
{
- [SecurityCritical]
static SafeFileHandle _outputHandle;
- [SecuritySafeCritical]
static Console()
{
_outputHandle = new SafeFileHandle(Win32Native.GetStdHandle(Win32Native.STD_OUTPUT_HANDLE), false);
}
- [SecuritySafeCritical]
public static unsafe void Write(string s)
{
byte[] bytes = Encoding.UTF8.GetBytes(s);
**
**
===========================================================*/
-namespace System {
-
- using System;
- using System.Security;
- using System.Security.Permissions;
- using System.Threading;
- using System.Runtime.Remoting;
-#if FEATURE_REMOTING
- using System.Runtime.Remoting.Lifetime;
- using System.Runtime.Remoting.Services;
-#endif
- using System.Runtime.InteropServices;
- using System.Reflection;
- using System.Runtime.CompilerServices;
- using System.Runtime.Versioning;
- using System.Diagnostics.Contracts;
- using CultureInfo = System.Globalization.CultureInfo;
-
+namespace System
+{
[Serializable]
-[System.Runtime.InteropServices.ComVisible(true)]
+ [System.Runtime.InteropServices.ComVisible(true)]
public abstract class MarshalByRefObject
{
-#if FEATURE_REMOTING
- private Object __identity;
-
- private Object Identity { get { return __identity; } set { __identity = value; } }
-#if FEATURE_COMINTEROP
- [System.Security.SecuritySafeCritical] // auto-generated
- internal IntPtr GetComIUnknown(bool fIsBeingMarshalled)
- {
- IntPtr pUnk;
- if(RemotingServices.IsTransparentProxy(this))
- {
- pUnk = RemotingServices.GetRealProxy(this).GetCOMIUnknown(fIsBeingMarshalled);
- }
- else
- {
- pUnk = Marshal.GetIUnknownForObject(this);
- }
- return pUnk;
- }
-
- [System.Security.SecurityCritical] // auto-generated
- [MethodImplAttribute(MethodImplOptions.InternalCall)]
- internal static extern IntPtr GetComIUnknown(MarshalByRefObject o);
-#endif // FEATURE_COMINTEROP
-
- // (1) for remote COM objects IsInstance of can't be executed on
- // the proxies, so we need this method to be executed on the
- // actual object.
- // (2) for remote objects that do not have the complete type information
- // we intercept calls to check the type and execute it on the actual
- // object
- internal bool IsInstanceOfType(Type T)
- {
- return T.IsInstanceOfType(this);
- }
-
- // for remote COM Objects the late binding methods can't be
- // executed on proxies, so we need this method to execute on
- // the real object
- internal Object InvokeMember(String name,BindingFlags invokeAttr,Binder binder,
- Object[] args,ParameterModifier[] modifiers,CultureInfo culture,String[] namedParameters)
- {
- Type t = GetType();
-
- // Sanity check
- if(!t.IsCOMObject)
- throw new InvalidOperationException(Environment.GetResourceString("Arg_InvokeMember"));
-
- // Call into the runtime to invoke on the COM object.
- return t.InvokeMember(name, invokeAttr, binder, this, args, modifiers, culture, namedParameters);
- }
-
-
- // Returns a new cloned MBR instance that is a memberwise copy of this
- // with the identity nulled out, so there are no identity conflicts
- // when the cloned object is marshalled
- protected MarshalByRefObject MemberwiseClone(bool cloneIdentity)
- {
- MarshalByRefObject mbr = (MarshalByRefObject)base.MemberwiseClone();
- // set the identity on the cloned object to null
- if (!cloneIdentity)
- mbr.Identity = null;
- return mbr;
- }
-
- // A helper routine to extract the identity either from the marshalbyrefobject base
- // class if it is not a proxy, otherwise from the real proxy.
- // A flag is set to indicate whether the object passed in is a server or a proxy
- [System.Security.SecuritySafeCritical] // auto-generated
- internal static Identity GetIdentity(MarshalByRefObject obj, out bool fServer)
- {
- fServer = true;
- Identity id = null;
-
- if(null != obj)
- {
- if(!RemotingServices.IsTransparentProxy(obj))
- {
- id = (Identity)obj.Identity;
- }
- else
- {
- // Toggle flag to indicate that we have a proxy
- fServer = false;
- id = RemotingServices.GetRealProxy(obj).IdentityObject;
- }
- }
-
- return id;
- }
-
- // Another helper that delegates to the helper above
- internal static Identity GetIdentity(MarshalByRefObject obj)
- {
- Contract.Assert(!RemotingServices.IsTransparentProxy(obj), "Use this method for server objects only");
-
- bool fServer;
- return GetIdentity(obj, out fServer);
- }
-
-
- internal ServerIdentity __RaceSetServerIdentity(ServerIdentity id)
- {
- if (__identity == null)
- {
- // For strictly MBR types, the TP field in the identity
- // holds the real server
- if (!id.IsContextBound)
- {
- id.RaceSetTransparentProxy(this);
- }
- Interlocked.CompareExchange(ref __identity, id, null);
- }
- return (ServerIdentity)__identity;
- }
-
-
- internal void __ResetServerIdentity()
- {
- __identity = null;
- }
-
- // This method is used return a lifetime service object which
- // is used to control the lifetime policy to the object.
- // For the default Lifetime service this will be an object of typoe ILease.
- //
- [System.Security.SecurityCritical] // auto-generated_required
- public Object GetLifetimeService()
- {
- return LifetimeServices.GetLease(this);
- }
-
- // This method is used return lifetime service object. This method
- // can be overridden to return a LifetimeService object with properties unique to
- // this object.
- // For the default Lifetime service this will be an object of type ILease.
- //
- [System.Security.SecurityCritical] // auto-generated_required
- public virtual Object InitializeLifetimeService()
- {
- return LifetimeServices.GetLeaseInitial(this);
- }
-
- [System.Security.SecurityCritical] // auto-generated_required
- public virtual ObjRef CreateObjRef(Type requestedType)
- {
- if(__identity == null)
- {
- throw new RemotingException(Environment.GetResourceString(
- "Remoting_NoIdentityEntry"));
- }
- return new ObjRef(this, requestedType);
- }
-
- // This is for casting interop ObjRefLite's.
- // ObjRefLite's have been deprecated. These methods are not exposed
- // through any user APIs and would be removed in the future
- [System.Security.SecuritySafeCritical] // auto-generated
- internal bool CanCastToXmlType(String xmlTypeName, String xmlTypeNamespace)
- {
- Type castType = SoapServices.GetInteropTypeFromXmlType(xmlTypeName, xmlTypeNamespace);
- if (castType == null)
- {
- String typeNamespace;
- String assemblyName;
- if (!SoapServices.DecodeXmlNamespaceForClrTypeNamespace(xmlTypeNamespace,
- out typeNamespace, out assemblyName))
- return false;
-
- String typeName;
- if ((typeNamespace != null) && (typeNamespace.Length > 0))
- typeName = typeNamespace + "." + xmlTypeName;
- else
- typeName = xmlTypeName;
-
- try
- {
- Assembly asm = Assembly.Load(assemblyName);
- castType = asm.GetType(typeName, false, false);
- }
- catch
- {
- return false;
- }
- }
-
- if (castType != null)
- return castType.IsAssignableFrom(this.GetType());
-
- return false;
- } // CanCastToXmlType
-
- // helper method for calling CanCastToXmlType
- // ObjRefLite's have been deprecated. These methods are not exposed
- // through any user APIs and would be removed in the future
- [System.Security.SecuritySafeCritical] // auto-generated
- internal static bool CanCastToXmlTypeHelper(RuntimeType castType, MarshalByRefObject o)
- {
- if (castType == null)
- throw new ArgumentNullException(nameof(castType));
-
- Contract.EndContractBlock();
- // MarshalByRefObject's can only be casted to MarshalByRefObject's or interfaces.
- if (!castType.IsInterface && !castType.IsMarshalByRef)
- return false;
-
- // figure out xml type name
- String xmlTypeName = null;
- String xmlTypeNamespace = null;
- if (!SoapServices.GetXmlTypeForInteropType(castType, out xmlTypeName, out xmlTypeNamespace))
- {
- // There's no registered interop type name, so just use the default.
- xmlTypeName = castType.Name;
- xmlTypeNamespace =
- SoapServices.CodeXmlNamespaceForClrTypeNamespace(
- castType.Namespace, castType.GetRuntimeAssembly().GetSimpleName());
- }
-
- return o.CanCastToXmlType(xmlTypeName, xmlTypeNamespace);
- } // CanCastToXmlType
-#else
protected MarshalByRefObject() { }
public object GetLifetimeService()
{
MarshalByRefObject mbr = (MarshalByRefObject)base.MemberwiseClone();
return mbr;
}
-#endif // FEATURE_REMOTING
-
- }
-} // namespace
+ }
+}
public const double PI = 3.14159265358979323846;
public const double E = 2.7182818284590452354;
- [System.Security.SecuritySafeCritical] // auto-generated
[MethodImplAttribute(MethodImplOptions.InternalCall)]
public static extern double Acos(double d);
- [System.Security.SecuritySafeCritical] // auto-generated
[MethodImplAttribute(MethodImplOptions.InternalCall)]
public static extern double Asin(double d);
- [System.Security.SecuritySafeCritical] // auto-generated
[MethodImplAttribute(MethodImplOptions.InternalCall)]
public static extern double Atan(double d);
- [System.Security.SecuritySafeCritical] // auto-generated
[MethodImplAttribute(MethodImplOptions.InternalCall)]
public static extern double Atan2(double y,double x);
return Decimal.Ceiling(d);
}
- [System.Security.SecuritySafeCritical] // auto-generated
[MethodImplAttribute(MethodImplOptions.InternalCall)]
public static extern double Ceiling(double a);
- [System.Security.SecuritySafeCritical] // auto-generated
[MethodImplAttribute(MethodImplOptions.InternalCall)]
public static extern double Cos (double d);
- [System.Security.SecuritySafeCritical] // auto-generated
[MethodImplAttribute(MethodImplOptions.InternalCall)]
public static extern double Cosh(double value);
return Decimal.Floor(d);
}
- [System.Security.SecuritySafeCritical] // auto-generated
[MethodImplAttribute(MethodImplOptions.InternalCall)]
public static extern double Floor(double d);
- [System.Security.SecuritySafeCritical] // auto-generated
private static unsafe double InternalRound(double value, int digits, MidpointRounding mode) {
if (Abs(value) < doubleRoundLimit) {
Double power10 = roundPower10Double[digits];
return value;
}
- [System.Security.SecuritySafeCritical] // auto-generated
private unsafe static double InternalTruncate(double d) {
SplitFractionDouble(&d);
return d;
}
- [System.Security.SecuritySafeCritical] // auto-generated
[MethodImplAttribute(MethodImplOptions.InternalCall)]
public static extern double Sin(double a);
- [System.Security.SecuritySafeCritical] // auto-generated
[MethodImplAttribute(MethodImplOptions.InternalCall)]
public static extern double Tan(double a);
- [System.Security.SecuritySafeCritical] // auto-generated
[MethodImplAttribute(MethodImplOptions.InternalCall)]
public static extern double Sinh(double value);
- [System.Security.SecuritySafeCritical] // auto-generated
[MethodImplAttribute(MethodImplOptions.InternalCall)]
public static extern double Tanh(double value);
- [System.Security.SecuritySafeCritical] // auto-generated
[MethodImplAttribute(MethodImplOptions.InternalCall)]
public static extern double Round(double a);
return Decimal.Round(d, decimals, mode);
}
- [System.Security.SecurityCritical] // auto-generated
[MethodImplAttribute(MethodImplOptions.InternalCall)]
private static unsafe extern double SplitFractionDouble(double* value);
return InternalTruncate(d);
}
- [System.Security.SecuritySafeCritical] // auto-generated
[ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)]
[MethodImplAttribute(MethodImplOptions.InternalCall)]
public static extern double Sqrt(double d);
- [System.Security.SecuritySafeCritical] // auto-generated
[MethodImplAttribute(MethodImplOptions.InternalCall)]
public static extern double Log (double d);
- [System.Security.SecuritySafeCritical] // auto-generated
[MethodImplAttribute(MethodImplOptions.InternalCall)]
public static extern double Log10(double d);
- [System.Security.SecuritySafeCritical] // auto-generated
[MethodImplAttribute(MethodImplOptions.InternalCall)]
public static extern double Exp(double d);
- [System.Security.SecuritySafeCritical] // auto-generated
[MethodImplAttribute(MethodImplOptions.InternalCall)]
public static extern double Pow(double x, double y);
return -value;
}
- [System.Security.SecuritySafeCritical] // auto-generated
[MethodImplAttribute(MethodImplOptions.InternalCall)]
extern public static float Abs(float value);
// This is special code to handle NaN (We need to make sure NaN's aren't
// it runs the else case, which returns +value instead of negating it.
// return (value < 0) ? -value : value;
- [System.Security.SecuritySafeCritical] // auto-generated
[MethodImplAttribute(MethodImplOptions.InternalCall)]
extern public static double Abs(double value);
// This is special code to handle NaN (We need to make sure NaN's aren't
public static float Abs(float x) => Math.Abs(x);
- [System.Security.SecuritySafeCritical] // auto-generated
[MethodImplAttribute(MethodImplOptions.InternalCall)]
public static extern float Acos(float x);
- [System.Security.SecuritySafeCritical] // auto-generated
[MethodImplAttribute(MethodImplOptions.InternalCall)]
public static extern float Asin(float x);
- [System.Security.SecuritySafeCritical] // auto-generated
[MethodImplAttribute(MethodImplOptions.InternalCall)]
public static extern float Atan(float x);
- [System.Security.SecuritySafeCritical] // auto-generated
[MethodImplAttribute(MethodImplOptions.InternalCall)]
public static extern float Atan2(float y, float x);
- [System.Security.SecuritySafeCritical] // auto-generated
[MethodImplAttribute(MethodImplOptions.InternalCall)]
public static extern float Ceiling(float x);
- [System.Security.SecuritySafeCritical] // auto-generated
[MethodImplAttribute(MethodImplOptions.InternalCall)]
public static extern float Cos(float x);
- [System.Security.SecuritySafeCritical] // auto-generated
[MethodImplAttribute(MethodImplOptions.InternalCall)]
public static extern float Cosh(float x);
- [System.Security.SecuritySafeCritical] // auto-generated
[MethodImplAttribute(MethodImplOptions.InternalCall)]
public static extern float Exp(float x);
- [System.Security.SecuritySafeCritical] // auto-generated
[MethodImplAttribute(MethodImplOptions.InternalCall)]
public static extern float Floor(float x);
}
}
- [System.Security.SecuritySafeCritical] // auto-generated
[MethodImplAttribute(MethodImplOptions.InternalCall)]
public static extern float Log(float x);
return Log(x) / Log(y);
}
- [System.Security.SecuritySafeCritical] // auto-generated
[MethodImplAttribute(MethodImplOptions.InternalCall)]
public static extern float Log10(float x);
[ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)]
public static float Min(float x, float y) => Math.Min(x, y);
- [System.Security.SecuritySafeCritical] // auto-generated
[MethodImplAttribute(MethodImplOptions.InternalCall)]
public static extern float Pow(float x, float y);
- [System.Security.SecuritySafeCritical] // auto-generated
[MethodImplAttribute(MethodImplOptions.InternalCall)]
public static extern float Round(float x);
public static int Sign(float x) => Math.Sign(x);
- [System.Security.SecuritySafeCritical] // auto-generated
[MethodImplAttribute(MethodImplOptions.InternalCall)]
public static extern float Sin(float x);
- [System.Security.SecuritySafeCritical] // auto-generated
[MethodImplAttribute(MethodImplOptions.InternalCall)]
public static extern float Sinh(float x);
- [System.Security.SecuritySafeCritical] // auto-generated
[ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)]
[MethodImplAttribute(MethodImplOptions.InternalCall)]
public static extern float Sqrt(float x);
- [System.Security.SecuritySafeCritical] // auto-generated
[MethodImplAttribute(MethodImplOptions.InternalCall)]
public static extern float Tan(float x);
- [System.Security.SecuritySafeCritical] // auto-generated
[MethodImplAttribute(MethodImplOptions.InternalCall)]
public static extern float Tanh(float x);
public static float Truncate(float x) => InternalTruncate(x);
- [System.Security.SecuritySafeCritical] // auto-generated
private static unsafe float InternalRound(float x, int digits, MidpointRounding mode)
{
if (Abs(x) < singleRoundLimit)
return x;
}
- [System.Security.SecuritySafeCritical] // auto-generated
private unsafe static float InternalTruncate(float x)
{
SplitFractionSingle(&x);
return x;
}
- [System.Security.SecurityCritical] // auto-generated
[MethodImplAttribute(MethodImplOptions.InternalCall)]
private static unsafe extern float SplitFractionSingle(float* x);
}
public override String Message
{
- [System.Security.SecuritySafeCritical] // auto-generated
get {
if (ClassName == null) {
return base.Message;
public override String Message
{
- [System.Security.SecuritySafeCritical] // auto-generated
get {
if (ClassName == null) {
return base.Message;
}
// Called to format signature
- [System.Security.SecurityCritical] // auto-generated
[MethodImplAttribute(MethodImplOptions.InternalCall)]
internal static extern String FormatSignature(byte [] signature);
MemberName = memberName;
}
- [System.Security.SecurityCritical] // auto-generated_required
public override void GetObjectData(SerializationInfo info, StreamingContext context) {
if (info==null) {
throw new ArgumentNullException(nameof(info));
public override String Message
{
- [System.Security.SecuritySafeCritical] // auto-generated
get {
if (ClassName == null) {
return base.Message;
using System.Runtime;
using System.Runtime.CompilerServices;
using System.Runtime.Serialization;
+ using System.Diagnostics;
using System.Diagnostics.Contracts;
using System.Reflection.Emit;
// 1. Multicast delegate
// 2. Secure/Wrapper delegate
// 3. Inner delegate of secure delegate where the secure delegate security context is a collectible method
- [System.Security.SecurityCritical]
private Object _invocationList;
- [System.Security.SecurityCritical]
private IntPtr _invocationCount;
// This constructor is called from the class generated by the
{
}
- [System.Security.SecuritySafeCritical]
internal bool IsUnmanagedFunctionPtr()
{
return (_invocationCount == (IntPtr)(-1));
}
- [System.Security.SecuritySafeCritical]
internal bool InvocationListLogicallyNull()
{
return (_invocationList == null) || (_invocationList is LoaderAllocator) || (_invocationList is DynamicResolver);
}
- [System.Security.SecurityCritical]
public override void GetObjectData(SerializationInfo info, StreamingContext context)
{
int targetIndex = 0;
// equals returns true IIF the delegate is not null and has the
// same target, method and invocation list as this object
- [System.Security.SecuritySafeCritical] // auto-generated
public override sealed bool Equals(Object obj)
{
if (obj == null)
// Since this is a MulticastDelegate and we know
// the types are the same, obj should also be a
// MulticastDelegate
- Contract.Assert(obj is MulticastDelegate, "Shouldn't have failed here since we already checked the types are the same!");
+ Debug.Assert(obj is MulticastDelegate, "Shouldn't have failed here since we already checked the types are the same!");
var d = JitHelpers.UnsafeCast<MulticastDelegate>(obj);
if (_invocationCount != (IntPtr)0)
}
else
{
- Contract.Assert((_invocationList as Object[]) != null, "empty invocation list on multicast delegate");
+ Debug.Assert((_invocationList as Object[]) != null, "empty invocation list on multicast delegate");
return InvocationListEquals(d);
}
}
}
// Recursive function which will check for equality of the invocation list.
- [System.Security.SecuritySafeCritical]
private bool InvocationListEquals(MulticastDelegate d)
{
- Contract.Assert(d != null && (_invocationList as Object[]) != null, "bogus delegate in multicast list comparison");
+ Debug.Assert(d != null && (_invocationList as Object[]) != null, "bogus delegate in multicast list comparison");
Object[] invocationList = _invocationList as Object[];
if (d._invocationCount != _invocationCount)
return false;
return true;
}
- [System.Security.SecurityCritical]
private bool TrySetSlot(Object[] a, int index, Object o)
{
if (a[index] == null && System.Threading.Interlocked.CompareExchange<Object>(ref a[index], o, null) == null)
return false;
}
- [System.Security.SecurityCritical]
private MulticastDelegate NewMulticastDelegate(Object[] invocationList, int invocationCount, bool thisIsMultiCastAlready)
{
// First, allocate a new multicast delegate just like this one, i.e. same type as the this object
return result;
}
- [System.Security.SecurityCritical]
internal MulticastDelegate NewMulticastDelegate(Object[] invocationList, int invocationCount)
{
return NewMulticastDelegate(invocationList, invocationCount, false);
}
- [System.Security.SecurityCritical]
internal void StoreDynamicMethod(MethodInfo dynamicMethod)
{
if (_invocationCount != (IntPtr)0)
{
- Contract.Assert(!IsUnmanagedFunctionPtr(), "dynamic method and unmanaged fntptr delegate combined");
+ Debug.Assert(!IsUnmanagedFunctionPtr(), "dynamic method and unmanaged fntptr delegate combined");
// must be a secure/wrapper one, unwrap and save
MulticastDelegate d = (MulticastDelegate)_invocationList;
d._methodBase = dynamicMethod;
// This method will combine this delegate with the passed delegate
// to form a new delegate.
- [System.Security.SecuritySafeCritical] // auto-generated
protected override sealed Delegate CombineImpl(Delegate follow)
{
if ((Object)follow == null) // cast to object for a more efficient test
}
}
- [System.Security.SecurityCritical]
private Object[] DeleteFromInvocationList(Object[] invocationList, int invocationCount, int deleteIndex, int deleteCount)
{
Object[] thisInvocationList = _invocationList as Object[];
// look at the invocation list.) If this is found we remove it from
// this list and return a new delegate. If its not found a copy of the
// current list is returned.
- [System.Security.SecuritySafeCritical] // auto-generated
protected override sealed Delegate RemoveImpl(Delegate value)
{
// There is a special case were we are removing using a delegate as
}
// This method returns the Invocation list of this multicast delegate.
- [System.Security.SecuritySafeCritical]
public override sealed Delegate[] GetInvocationList()
{
Contract.Ensures(Contract.Result<Delegate[]>() != null);
return !d1.Equals(d2);
}
- [System.Security.SecuritySafeCritical]
public override sealed int GetHashCode()
{
if (IsUnmanagedFunctionPtr())
}
}
- [System.Security.SecuritySafeCritical]
internal override Object GetTarget()
{
if (_invocationCount != (IntPtr)0)
return base.GetTarget();
}
- [System.Security.SecuritySafeCritical]
protected override MethodInfo GetMethodImpl()
{
if (_invocationCount != (IntPtr)0 && _invocationList != null)
throw new ArgumentException(Environment.GetResourceString("Arg_DlgtNullInst"));
}
- [System.Security.SecurityCritical]
[System.Diagnostics.DebuggerNonUserCode]
private void CtorClosed(Object target, IntPtr methodPtr)
{
this._methodPtr = methodPtr;
}
- [System.Security.SecurityCritical]
[System.Diagnostics.DebuggerNonUserCode]
private void CtorClosedStatic(Object target, IntPtr methodPtr)
{
this._methodPtr = methodPtr;
}
- [System.Security.SecurityCritical] // auto-generated
[System.Diagnostics.DebuggerNonUserCode]
private void CtorRTClosed(Object target, IntPtr methodPtr)
{
this._methodPtr = AdjustTarget(target, methodPtr);
}
- [System.Security.SecurityCritical]
[System.Diagnostics.DebuggerNonUserCode]
private void CtorOpened(Object target, IntPtr methodPtr, IntPtr shuffleThunk)
{
this._methodPtrAux = methodPtr;
}
- [System.Security.SecurityCritical] // auto-generated
[System.Diagnostics.DebuggerNonUserCode]
private void CtorSecureClosed(Object target, IntPtr methodPtr, IntPtr callThunk, IntPtr creatorMethod)
{
this._invocationCount = GetInvokeMethod();
}
- [System.Security.SecurityCritical] // auto-generated
[System.Diagnostics.DebuggerNonUserCode]
private void CtorSecureClosedStatic(Object target, IntPtr methodPtr, IntPtr callThunk, IntPtr creatorMethod)
{
this._invocationCount = GetInvokeMethod();
}
- [System.Security.SecurityCritical] // auto-generated
[System.Diagnostics.DebuggerNonUserCode]
private void CtorSecureRTClosed(Object target, IntPtr methodPtr, IntPtr callThunk, IntPtr creatorMethod)
{
this._invocationCount = GetInvokeMethod();
}
- [System.Security.SecurityCritical] // auto-generated
[System.Diagnostics.DebuggerNonUserCode]
private void CtorSecureOpened(Object target, IntPtr methodPtr, IntPtr shuffleThunk, IntPtr callThunk, IntPtr creatorMethod)
{
this._invocationCount = GetInvokeMethod();
}
- [System.Security.SecurityCritical] // auto-generated
[System.Diagnostics.DebuggerNonUserCode]
private void CtorVirtualDispatch(Object target, IntPtr methodPtr, IntPtr shuffleThunk)
{
this._methodPtrAux = GetCallStub(methodPtr);
}
- [System.Security.SecurityCritical] // auto-generated
[System.Diagnostics.DebuggerNonUserCode]
private void CtorSecureVirtualDispatch(Object target, IntPtr methodPtr, IntPtr shuffleThunk, IntPtr callThunk, IntPtr creatorMethod)
{
this._invocationCount = GetInvokeMethod();
}
- [System.Security.SecurityCritical] // auto-generated
[System.Diagnostics.DebuggerNonUserCode]
private void CtorCollectibleClosedStatic(Object target, IntPtr methodPtr, IntPtr gchandle)
{
this._methodBase = System.Runtime.InteropServices.GCHandle.InternalGet(gchandle);
}
- [System.Security.SecurityCritical] // auto-generated
[System.Diagnostics.DebuggerNonUserCode]
private void CtorCollectibleOpened(Object target, IntPtr methodPtr, IntPtr shuffleThunk, IntPtr gchandle)
{
this._methodBase = System.Runtime.InteropServices.GCHandle.InternalGet(gchandle);
}
- [System.Security.SecurityCritical] // auto-generated
[System.Diagnostics.DebuggerNonUserCode]
private void CtorCollectibleVirtualDispatch(Object target, IntPtr methodPtr, IntPtr shuffleThunk, IntPtr gchandle)
{
get { return _offendingNumber; }
}
- [System.Security.SecurityCritical] // auto-generated_required
public override void GetObjectData(SerializationInfo info, StreamingContext context) {
if (info==null) {
throw new ArgumentNullException(nameof(info));
using System.Runtime.Versioning;
using System.Security;
using System.Text;
+ using System.Diagnostics;
using System.Diagnostics.Contracts;
// The Number class implements methods for formatting and parsing
private Number() {
}
- [System.Security.SecurityCritical] // auto-generated
[MethodImplAttribute(MethodImplOptions.InternalCall)]
public static extern String FormatDecimal(Decimal value, String format, NumberFormatInfo info);
- [System.Security.SecurityCritical] // auto-generated
[MethodImplAttribute(MethodImplOptions.InternalCall)]
public static extern String FormatDouble(double value, String format, NumberFormatInfo info);
- [System.Security.SecurityCritical] // auto-generated
[MethodImplAttribute(MethodImplOptions.InternalCall)]
public static extern String FormatInt32(int value, String format, NumberFormatInfo info);
- [System.Security.SecurityCritical] // auto-generated
[MethodImplAttribute(MethodImplOptions.InternalCall)]
public static extern String FormatUInt32(uint value, String format, NumberFormatInfo info);
- [System.Security.SecurityCritical] // auto-generated
[MethodImplAttribute(MethodImplOptions.InternalCall)]
public static extern String FormatInt64(long value, String format, NumberFormatInfo info);
- [System.Security.SecurityCritical] // auto-generated
[MethodImplAttribute(MethodImplOptions.InternalCall)]
public static extern String FormatUInt64(ulong value, String format, NumberFormatInfo info);
- [System.Security.SecurityCritical] // auto-generated
[MethodImplAttribute(MethodImplOptions.InternalCall)]
public static extern String FormatSingle(float value, String format, NumberFormatInfo info);
- [System.Security.SecurityCritical] // auto-generated
[MethodImplAttribute(MethodImplOptions.InternalCall)]
public unsafe static extern Boolean NumberBufferToDecimal(byte* number, ref Decimal value);
- [System.Security.SecurityCritical] // auto-generated
[MethodImplAttribute(MethodImplOptions.InternalCall)]
internal unsafe static extern Boolean NumberBufferToDouble(byte* number, ref Double value);
[MethodImplAttribute(MethodImplOptions.InternalCall)]
[System.Runtime.CompilerServices.FriendAccessAllowed]
- [System.Security.SecurityCritical] // auto-generated
internal static extern unsafe string FormatNumberBuffer(byte* number, string format, NumberFormatInfo info, char* allDigits);
// Constants used by number parsing
// Enough space for NumberMaxDigit characters plus null and 3 32 bit integers and a pointer
public static readonly Int32 NumberBufferBytes = 12 + ((NumberMaxDigits + 1) * 2) + IntPtr.Size;
- [SecurityCritical]
private Byte * baseAddress;
- [SecurityCritical]
public Char * digits;
public Int32 precision;
public Int32 scale;
public Boolean sign;
- [System.Security.SecurityCritical] // auto-generated
public NumberBuffer(Byte* stackBuffer) {
this.baseAddress = stackBuffer;
this.digits = (((Char*) stackBuffer) + 6);
this.sign = false;
}
- [System.Security.SecurityCritical] // auto-generated
public Byte* PackForNative() {
Int32* baseInteger = (Int32*) baseAddress;
baseInteger[0] = precision;
return returnValue;
}
- [System.Security.SecuritySafeCritical] // auto-generated
private unsafe static Boolean HexNumberToUInt32(ref NumberBuffer number, ref UInt32 value) {
Int32 i = number.scale;
return false;
}
Char* p = number.digits;
- Contract.Assert(p != null, "");
+ Debug.Assert(p != null, "");
UInt32 n = 0;
while (--i >= 0) {
newN += (UInt32)((*p - 'A') + 10);
}
else {
- Contract.Assert(*p >= 'a' && *p <= 'f', "");
+ Debug.Assert(*p >= 'a' && *p <= 'f', "");
newN += (UInt32)((*p - 'a') + 10);
}
}
return true;
}
- [System.Security.SecuritySafeCritical] // auto-generated
private unsafe static Boolean HexNumberToUInt64(ref NumberBuffer number, ref UInt64 value) {
Int32 i = number.scale;
return false;
}
Char* p = number.digits;
- Contract.Assert(p != null, "");
+ Debug.Assert(p != null, "");
UInt64 n = 0;
while (--i >= 0) {
newN += (UInt64)((*p - 'A') + 10);
}
else {
- Contract.Assert(*p >= 'a' && *p <= 'f', "");
+ Debug.Assert(*p >= 'a' && *p <= 'f', "");
newN += (UInt64)((*p - 'a') + 10);
}
}
return (((ch) == 0x20) || ((ch) >= 0x09 && (ch) <= 0x0D));
}
- [System.Security.SecuritySafeCritical] // auto-generated
private unsafe static Boolean NumberToInt32(ref NumberBuffer number, ref Int32 value) {
Int32 i = number.scale;
return false;
}
char * p = number.digits;
- Contract.Assert(p != null, "");
+ Debug.Assert(p != null, "");
Int32 n = 0;
while (--i >= 0) {
if ((UInt32)n > (0x7FFFFFFF / 10)) {
return true;
}
- [System.Security.SecuritySafeCritical] // auto-generated
private unsafe static Boolean NumberToInt64(ref NumberBuffer number, ref Int64 value) {
Int32 i = number.scale;
return false;
}
char* p = number.digits;
- Contract.Assert(p != null, "");
+ Debug.Assert(p != null, "");
Int64 n = 0;
while (--i >= 0) {
if ((UInt64)n > (0x7FFFFFFFFFFFFFFF / 10)) {
return true;
}
- [System.Security.SecuritySafeCritical] // auto-generated
private unsafe static Boolean NumberToUInt32(ref NumberBuffer number, ref UInt32 value) {
Int32 i = number.scale;
return false;
}
char* p = number.digits;
- Contract.Assert(p != null, "");
+ Debug.Assert(p != null, "");
UInt32 n = 0;
while (--i >= 0) {
if (n > (0xFFFFFFFF / 10)) {
return true;
}
- [System.Security.SecuritySafeCritical] // auto-generated
private unsafe static Boolean NumberToUInt64(ref NumberBuffer number, ref UInt64 value) {
Int32 i = number.scale;
return false;
}
char * p = number.digits;
- Contract.Assert(p != null, "");
+ Debug.Assert(p != null, "");
UInt64 n = 0;
while (--i >= 0) {
if (n > (0xFFFFFFFFFFFFFFFF / 10)) {
return true;
}
- [System.Security.SecurityCritical] // auto-generated
private unsafe static char * MatchChars(char* p, string str) {
fixed (char* stringPointer = str) {
return MatchChars(p, stringPointer);
}
}
- [System.Security.SecurityCritical] // auto-generated
private unsafe static char * MatchChars(char* p, char* str) {
- Contract.Assert(p != null && str != null, "");
+ Debug.Assert(p != null && str != null, "");
if (*str == '\0') {
return null;
return null;
}
- [System.Security.SecuritySafeCritical] // auto-generated
internal unsafe static Decimal ParseDecimal(String value, NumberStyles options, NumberFormatInfo numfmt) {
Byte * numberBufferBytes = stackalloc Byte[NumberBuffer.NumberBufferBytes];
return result;
}
- [System.Security.SecuritySafeCritical] // auto-generated
internal unsafe static Double ParseDouble(String value, NumberStyles options, NumberFormatInfo numfmt) {
if (value == null) {
throw new ArgumentNullException(nameof(value));
return d;
}
- [System.Security.SecuritySafeCritical] // auto-generated
internal unsafe static Int32 ParseInt32(String s, NumberStyles style, NumberFormatInfo info) {
Byte * numberBufferBytes = stackalloc Byte[NumberBuffer.NumberBufferBytes];
return i;
}
- [System.Security.SecuritySafeCritical] // auto-generated
internal unsafe static Int64 ParseInt64(String value, NumberStyles options, NumberFormatInfo numfmt) {
Byte * numberBufferBytes = stackalloc Byte[NumberBuffer.NumberBufferBytes];
NumberBuffer number = new NumberBuffer(numberBufferBytes);
return i;
}
- [System.Security.SecurityCritical] // auto-generated
private unsafe static Boolean ParseNumber(ref char * str, NumberStyles options, ref NumberBuffer number, StringBuilder sb, NumberFormatInfo numfmt, Boolean parseDecimal) {
const Int32 StateSign = 0x0001;
return false;
}
- [System.Security.SecuritySafeCritical] // auto-generated
internal unsafe static Single ParseSingle(String value, NumberStyles options, NumberFormatInfo numfmt) {
if (value == null) {
throw new ArgumentNullException(nameof(value));
return castSingle;
}
- [System.Security.SecuritySafeCritical] // auto-generated
internal unsafe static UInt32 ParseUInt32(String value, NumberStyles options, NumberFormatInfo numfmt) {
Byte * numberBufferBytes = stackalloc Byte[NumberBuffer.NumberBufferBytes];
return i;
}
- [System.Security.SecuritySafeCritical] // auto-generated
internal unsafe static UInt64 ParseUInt64(String value, NumberStyles options, NumberFormatInfo numfmt) {
Byte * numberBufferBytes = stackalloc Byte[NumberBuffer.NumberBufferBytes];
NumberBuffer number = new NumberBuffer(numberBufferBytes);
return i;
}
- [System.Security.SecuritySafeCritical] // auto-generated
private unsafe static void StringToNumber(String str, NumberStyles options, ref NumberBuffer number, NumberFormatInfo info, Boolean parseDecimal) {
if (str == null) {
throw new ArgumentNullException(nameof(String));
}
Contract.EndContractBlock();
- Contract.Assert(info != null, "");
+ Debug.Assert(info != null, "");
fixed (char* stringPointer = str) {
char * p = stringPointer;
if (!ParseNumber(ref p, options, ref number, null, info , parseDecimal)
return true;
}
- [System.Security.SecuritySafeCritical] // auto-generated
internal unsafe static Boolean TryParseDecimal(String value, NumberStyles options, NumberFormatInfo numfmt, out Decimal result) {
Byte * numberBufferBytes = stackalloc Byte[NumberBuffer.NumberBufferBytes];
return true;
}
- [System.Security.SecuritySafeCritical] // auto-generated
internal unsafe static Boolean TryParseDouble(String value, NumberStyles options, NumberFormatInfo numfmt, out Double result) {
Byte * numberBufferBytes = stackalloc Byte[NumberBuffer.NumberBufferBytes];
NumberBuffer number = new NumberBuffer(numberBufferBytes);
return true;
}
- [System.Security.SecuritySafeCritical] // auto-generated
internal unsafe static Boolean TryParseInt32(String s, NumberStyles style, NumberFormatInfo info, out Int32 result) {
Byte * numberBufferBytes = stackalloc Byte[NumberBuffer.NumberBufferBytes];
return true;
}
- [System.Security.SecuritySafeCritical] // auto-generated
internal unsafe static Boolean TryParseInt64(String s, NumberStyles style, NumberFormatInfo info, out Int64 result) {
Byte * numberBufferBytes = stackalloc Byte[NumberBuffer.NumberBufferBytes];
return true;
}
- [System.Security.SecuritySafeCritical] // auto-generated
internal unsafe static Boolean TryParseSingle(String value, NumberStyles options, NumberFormatInfo numfmt, out Single result) {
Byte * numberBufferBytes = stackalloc Byte[NumberBuffer.NumberBufferBytes];
NumberBuffer number = new NumberBuffer(numberBufferBytes);
return true;
}
- [System.Security.SecuritySafeCritical] // auto-generated
internal unsafe static Boolean TryParseUInt32(String s, NumberStyles style, NumberFormatInfo info, out UInt32 result) {
Byte * numberBufferBytes = stackalloc Byte[NumberBuffer.NumberBufferBytes];
return true;
}
- [System.Security.SecuritySafeCritical] // auto-generated
internal unsafe static Boolean TryParseUInt64(String s, NumberStyles style, NumberFormatInfo info, out UInt64 result) {
Byte * numberBufferBytes = stackalloc Byte[NumberBuffer.NumberBufferBytes];
return TryStringToNumber(str, options, ref number, null, numfmt, parseDecimal);
}
- [System.Security.SecuritySafeCritical] // auto-generated
[System.Runtime.CompilerServices.FriendAccessAllowed]
internal unsafe static Boolean TryStringToNumber(String str, NumberStyles options, ref NumberBuffer number, StringBuilder sb, NumberFormatInfo numfmt, Boolean parseDecimal) {
if (str == null) {
return false;
}
- Contract.Assert(numfmt != null, "");
+ Debug.Assert(numfmt != null, "");
fixed (char* stringPointer = str) {
char * p = stringPointer;
**
===========================================================*/
-namespace System {
+namespace System
+{
using System;
using System.Runtime;
using System.Runtime.InteropServices;
using CultureInfo = System.Globalization.CultureInfo;
using FieldInfo = System.Reflection.FieldInfo;
using BindingFlags = System.Reflection.BindingFlags;
-#if FEATURE_REMOTING
- using RemotingException = System.Runtime.Remoting.RemotingException;
-#endif
+
// The Object is the root class for all object in the CLR System. Object
// is the super class for all other CLR objects and provide a set of methods and low level
// services to subclasses. These services include object synchronization and support for clone
// Returns a Type object which represent this object instance.
//
- [System.Security.SecuritySafeCritical] // auto-generated
[Pure]
[MethodImplAttribute(MethodImplOptions.InternalCall)]
public extern Type GetType();
// so that other object may only call this method on themselves. It is entended to
// support the ICloneable interface.
//
- [System.Security.SecuritySafeCritical] // auto-generated
[MethodImplAttribute(MethodImplOptions.InternalCall)]
protected extern Object MemberwiseClone();
// Sets the value specified in the variant on the field
//
- [System.Security.SecurityCritical] // auto-generated
private void FieldSetter(String typeName, String fieldName, Object val)
{
Contract.Requires(typeName != null);
// Make sure that the value is compatible with the type
// of field
-#if FEATURE_REMOTING
- System.Runtime.Remoting.Messaging.Message.CoerceArg(val, fldInfo.FieldType);
-#else
Type pt=fldInfo.FieldType;
if (pt.IsByRef)
{
pt = pt.GetElementType();
}
-
+
if (!pt.IsInstanceOfType(val))
{
val = Convert.ChangeType(val, pt, CultureInfo.InvariantCulture);
}
-#endif
-
- // Set the value
+ // Set the value
fldInfo.SetValue(this, val);
}
-
+
// Gets the value specified in the variant on the field
//
private void FieldGetter(String typeName, String fieldName, ref Object val)
FieldInfo fldInfo = GetFieldInfo(typeName, fieldName);
// Get the value
- val = fldInfo.GetValue(this);
+ val = fldInfo.GetValue(this);
}
// Gets the field info object given the type name and field name.
if (null == t)
{
-#if FEATURE_REMOTING
- throw new RemotingException(String.Format(
- CultureInfo.CurrentCulture, Environment.GetResourceString("Remoting_BadType"),
- typeName));
-#else
throw new ArgumentException();
-#endif
}
FieldInfo fldInfo = t.GetField(fieldName, BindingFlags.Public |
BindingFlags.IgnoreCase);
if(null == fldInfo)
{
-#if FEATURE_REMOTING
- throw new RemotingException(String.Format(
- CultureInfo.CurrentCulture, Environment.GetResourceString("Remoting_BadField"),
- fieldName, typeName));
-#else
throw new ArgumentException();
-#endif
-
}
-
+
return fldInfo;
}
}
// This class is used to define the name of the base class library
internal class CoreLib
{
-
-#if FEATURE_CORECLR
public const string Name = "System.Private.CoreLib";
-#else
- public const string Name = "mscorlib";
-#endif
public static string FixupCoreLibName(string strToFixup)
{
-#if FEATURE_CORECLR
if (!String.IsNullOrEmpty(strToFixup))
{
strToFixup = strToFixup.Replace("mscorlib", System.CoreLib.Name);
}
-#endif
- return strToFixup;
+
+ return strToFixup;
}
}
objectName = info.GetString("ObjectName");
}
- [System.Security.SecurityCritical] // auto-generated_required
public override void GetObjectData(SerializationInfo info, StreamingContext context) {
base.GetObjectData(info, context);
info.AddValue("ObjectName",ObjectName,typeof(String));
{
// ChangeType
// This binder uses OLEAUT to change the type of the variant.
- [System.Security.SecuritySafeCritical] // overrides transparent member
public override Object ChangeType(Object value, Type type, CultureInfo cultureInfo)
{
Variant myValue = new Variant(value);
return Enum.Parse(type, value.ToString());
}
-#if !FEATURE_CORECLR
- // Special case the convertion from DBNull.
- if (srcType == typeof(DBNull))
- {
- // The requested type is a DBNull so no convertion is required.
- if (type == typeof(DBNull))
- return value;
-
- // Visual J++ supported converting from DBNull to null so customers
- // have requested (via a CDCR) that DBNull be convertible to null.
- // We don't however allow this when converting to a value class, since null
- // doesn't make sense for these, or to object since this would change existing
- // semantics.
- if ((type.IsClass && type != typeof(Object)) || type.IsInterface)
- return null;
- }
-#endif //!FEATURE_CORECLR
-
// Use the OA variant lib to convert primitive types.
try
{
throw new COMException(Environment.GetResourceString("Interop.COM_TypeMismatch"), unchecked((int)0x80020005));
}
}
-
-
}
}
}
}
- [System.Security.SecurityCritical] // auto-generated_required
public void GetObjectData(SerializationInfo info, StreamingContext context) {
if( info == null ) {
throw new ArgumentNullException(nameof(info));
// NATIVE METHODS
// For comments on these methods please see $\src\vm\COMUtilNative.cpp
//
- [System.Security.SecuritySafeCritical] // auto-generated
public unsafe static long StringToLong(System.String s, int radix, int flags) {
return StringToLong(s,radix,flags, null);
}
- [System.Security.SecurityCritical] // auto-generated
[MethodImplAttribute(MethodImplOptions.InternalCall)]
public unsafe extern static long StringToLong(System.String s, int radix, int flags, int* currPos);
- [System.Security.SecuritySafeCritical] // auto-generated
public unsafe static long StringToLong(System.String s, int radix, int flags, ref int currPos) {
fixed(int * ppos = &currPos) {
return StringToLong( s, radix, flags, ppos);
}
}
- [System.Security.SecuritySafeCritical] // auto-generated
public unsafe static int StringToInt(System.String s, int radix, int flags) {
return StringToInt(s,radix,flags, null);
}
- [System.Security.SecurityCritical] // auto-generated
[MethodImplAttribute(MethodImplOptions.InternalCall)]
public unsafe extern static int StringToInt(System.String s, int radix, int flags, int* currPos);
- [System.Security.SecuritySafeCritical] // auto-generated
public unsafe static int StringToInt(System.String s, int radix, int flags, ref int currPos) {
fixed(int * ppos = &currPos) {
return StringToInt( s, radix, flags, ppos);
}
}
- [System.Security.SecurityCritical] // auto-generated
[MethodImplAttribute(MethodImplOptions.InternalCall)]
public extern static String IntToString(int l, int radix, int width, char paddingChar, int flags);
- [System.Security.SecurityCritical] // auto-generated
[MethodImplAttribute(MethodImplOptions.InternalCall)]
public extern static String LongToString(long l, int radix, int width, char paddingChar, int flags);
}
// sync ctx reference identity issues where the sync ctx for one thread could be Current on another.
// If there is no current context, we use a default instance targeting the ThreadPool.
m_synchronizationContext = SynchronizationContext.CurrentNoFlow ?? ProgressStatics.DefaultContext;
- Contract.Assert(m_synchronizationContext != null);
+ Debug.Assert(m_synchronizationContext != null);
m_invokeHandlers = new SendOrPostCallback(InvokeHandlers);
}
[ClassInterface(ClassInterfaceType.None)]
[ComDefaultInterface(typeof(_Assembly))]
[System.Runtime.InteropServices.ComVisible(true)]
-#pragma warning disable 618
- [PermissionSetAttribute(SecurityAction.InheritanceDemand, Unrestricted = true)]
-#pragma warning restore 618
public abstract class Assembly : _Assembly, IEvidenceFactory, ICustomAttributeProvider, ISerializable
{
protected Assembly() {}
return base.GetHashCode();
}
- [System.Security.SecurityCritical]
public static Assembly LoadFrom(String assemblyFile)
{
if(assemblyFile == null)
}
// Locate an assembly for reflection by the name of the file containing the manifest.
- [System.Security.SecuritySafeCritical] // auto-generated
[MethodImplAttribute(MethodImplOptions.NoInlining)] // Methods containing StackCrawlMark local var has to be marked non-inlineable
public static Assembly ReflectionOnlyLoadFrom(String assemblyFile)
{
}
// Evidence is protected in Assembly.Load()
- [System.Security.SecuritySafeCritical] // auto-generated
[Obsolete("This method is obsolete and will be removed in a future release of the .NET Framework. Please use an overload of LoadFrom which does not take an Evidence parameter. See http://go.microsoft.com/fwlink/?LinkID=155570 for more information.")]
[MethodImplAttribute(MethodImplOptions.NoInlining)] // Methods containing StackCrawlMark local var has to be marked non-inlineable
public static Assembly LoadFrom(String assemblyFile,
}
// Evidence is protected in Assembly.Load()
- [System.Security.SecuritySafeCritical] // auto-generated
[Obsolete("This method is obsolete and will be removed in a future release of the .NET Framework. Please use an overload of LoadFrom which does not take an Evidence parameter. See http://go.microsoft.com/fwlink/?LinkID=155570 for more information.")]
[MethodImplAttribute(MethodImplOptions.NoInlining)] // Methods containing StackCrawlMark local var has to be marked non-inlineable
public static Assembly LoadFrom(String assemblyFile,
ref stackMark);
}
- [System.Security.SecuritySafeCritical] // auto-generated
[MethodImplAttribute(MethodImplOptions.NoInlining)] // Methods containing StackCrawlMark local var has to be marked non-inlineable
public static Assembly LoadFrom(String assemblyFile,
byte[] hashValue,
throw new NotSupportedException(Environment.GetResourceString("NotSupported_AssemblyLoadFromHash"));
}
- [SecurityCritical]
public static Assembly UnsafeLoadFrom(string assemblyFile)
{
return LoadFrom(assemblyFile);
// Locate an assembly by the long form of the assembly name.
// eg. "Toolbox.dll, version=1.1.10.1220, locale=en, publickey=1234567890123456789012345678901234567890"
- [System.Security.SecuritySafeCritical] // auto-generated
[MethodImplAttribute(MethodImplOptions.NoInlining)] // Methods containing StackCrawlMark local var has to be marked non-inlineable
public static Assembly Load(String assemblyString)
{
// Calls Type.GetType for WinRT types.
// Note: Type.GetType fails for assembly names that start with weird characters like '['. By calling it for managed types we would
// break AppCompat.
- [System.Security.SecuritySafeCritical] // auto-generated
[MethodImplAttribute(MethodImplOptions.NoInlining)] // Methods containing StackCrawlMark local var has to be marked non-inlineable
internal static Type GetType_Compat(String assemblyString, String typeName)
{
// Locate an assembly for reflection by the long form of the assembly name.
// eg. "Toolbox.dll, version=1.1.10.1220, locale=en, publickey=1234567890123456789012345678901234567890"
//
- [System.Security.SecuritySafeCritical] // auto-generated
[MethodImplAttribute(MethodImplOptions.NoInlining)] // Methods containing StackCrawlMark local var has to be marked non-inlineable
public static Assembly ReflectionOnlyLoad(String assemblyString)
{
return RuntimeAssembly.InternalLoad(assemblyString, null, ref stackMark, true /*forIntrospection*/);
}
- [System.Security.SecuritySafeCritical] // auto-generated
[MethodImplAttribute(MethodImplOptions.NoInlining)] // Methods containing StackCrawlMark local var has to be marked non-inlineable
[Obsolete("This method is obsolete and will be removed in a future release of the .NET Framework. Please use an overload of Load which does not take an Evidence parameter. See http://go.microsoft.com/fwlink/?LinkID=155570 for more information.")]
public static Assembly Load(String assemblyString, Evidence assemblySecurity)
// Locate an assembly by its name. The name can be strong or
// weak. The assembly is loaded into the domain of the caller.
- [System.Security.SecurityCritical] // auto-generated
[MethodImplAttribute(MethodImplOptions.NoInlining)] // Methods containing StackCrawlMark local var has to be marked non-inlineable
public static Assembly Load(AssemblyName assemblyRef)
{
// Locate an assembly by its name. The name can be strong or
// weak. The assembly is loaded into the domain of the caller.
- [System.Security.SecurityCritical] // auto-generated
[MethodImplAttribute(MethodImplOptions.NoInlining)] // Methods containing StackCrawlMark local var has to be marked non-inlineable
internal static Assembly Load(AssemblyName assemblyRef, IntPtr ptrLoadContextBinder)
{
return RuntimeAssembly.InternalLoadAssemblyName(assemblyRef, null, null, ref stackMark, true /*thrownOnFileNotFound*/, false /*forIntrospection*/, false /*suppressSecurityChecks*/, ptrLoadContextBinder);
}
- [System.Security.SecuritySafeCritical] // auto-generated
[MethodImplAttribute(MethodImplOptions.NoInlining)] // Methods containing StackCrawlMark local var has to be marked non-inlineable
[Obsolete("This method is obsolete and will be removed in a future release of the .NET Framework. Please use an overload of Load which does not take an Evidence parameter. See http://go.microsoft.com/fwlink/?LinkID=155570 for more information.")]
public static Assembly Load(AssemblyName assemblyRef, Evidence assemblySecurity)
return RuntimeAssembly.InternalLoadAssemblyName(assemblyRef, assemblySecurity, null, ref stackMark, true /*thrownOnFileNotFound*/, false /*forIntrospection*/, false /*suppressSecurityChecks*/);
}
- [System.Security.SecuritySafeCritical] // auto-generated
[Obsolete("This method has been deprecated. Please use Assembly.Load() instead. http://go.microsoft.com/fwlink/?linkid=14202")]
public static Assembly LoadWithPartialName(String partialName)
{
// Loads the assembly with a COFF based IMAGE containing
// an emitted assembly. The assembly is loaded into the domain
// of the caller.
- [System.Security.SecurityCritical] // auto-generated
[MethodImplAttribute(MethodImplOptions.NoInlining)] // Methods containing StackCrawlMark local var has to be marked non-inlineable
public static Assembly Load(byte[] rawAssembly)
{
// Loads the assembly for reflection with a COFF based IMAGE containing
// an emitted assembly. The assembly is loaded into the domain
// of the caller.
- [System.Security.SecuritySafeCritical] // auto-generated
[MethodImplAttribute(MethodImplOptions.NoInlining)] // Methods containing StackCrawlMark local var has to be marked non-inlineable
public static Assembly ReflectionOnlyLoad(byte[] rawAssembly)
{
// an emitted assembly. The assembly is loaded into the domain
// of the caller. The second parameter is the raw bytes
// representing the symbol store that matches the assembly.
- [System.Security.SecurityCritical] // auto-generated
[MethodImplAttribute(MethodImplOptions.NoInlining)] // Methods containing StackCrawlMark local var has to be marked non-inlineable
public static Assembly Load(byte[] rawAssembly,
byte[] rawSymbolStore)
// Load an assembly from a byte array, controlling where the grant set of this assembly is
// propigated from.
- [SecuritySafeCritical]
[MethodImpl(MethodImplOptions.NoInlining)] // Due to the stack crawl mark
public static Assembly Load(byte[] rawAssembly,
byte[] rawSymbolStore,
private static Dictionary<string, Assembly> s_loadfile = new Dictionary<string, Assembly>();
- [System.Security.SecuritySafeCritical] // auto-generated
public static Assembly LoadFile(String path)
{
Contract.Ensures(Contract.Result<Assembly>() != null);
return result;
}
- [System.Security.SecurityCritical] // auto-generated
[MethodImplAttribute(MethodImplOptions.NoInlining)] // Methods containing StackCrawlMark local var has to be marked non-inlineable
public static Assembly Load(Stream assemblyStream, Stream pdbStream)
{
StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller;
return RuntimeAssembly.InternalLoadFromStream(assemblyStream, pdbStream, ref stackMark);
}
- [System.Security.SecurityCritical] // auto-generated
[MethodImplAttribute(MethodImplOptions.NoInlining)] // Methods containing StackCrawlMark local var has to be marked non-inlineable
public static Assembly Load(Stream assemblyStream)
{
/*
* Get the assembly that the current code is running from.
*/
- [System.Security.SecuritySafeCritical] // auto-generated
[MethodImplAttribute(MethodImplOptions.NoInlining)] // Methods containing StackCrawlMark local var has to be marked non-inlineable
public static Assembly GetExecutingAssembly()
{
return RuntimeAssembly.GetExecutingAssembly(ref stackMark);
}
- [System.Security.SecuritySafeCritical] // auto-generated
[MethodImplAttribute(MethodImplOptions.NoInlining)] // Methods containing StackCrawlMark local var has to be marked non-inlineable
public static Assembly GetCallingAssembly()
{
return RuntimeAssembly.GetExecutingAssembly(ref stackMark);
}
- [System.Security.SecuritySafeCritical] // auto-generated
public static Assembly GetEntryAssembly() {
AppDomainManager domainManager = AppDomain.CurrentDomain.DomainManager;
if (domainManager == null)
#region public methods
public virtual event ModuleResolveEventHandler ModuleResolve
{
- [System.Security.SecurityCritical] // auto-generated_required
add
{
throw new NotImplementedException();
}
- [System.Security.SecurityCritical] // auto-generated_required
remove
{
throw new NotImplementedException();
public virtual String CodeBase
{
- [System.Security.SecurityCritical] // auto-generated
get
{
throw new NotImplementedException();
public virtual String EscapedCodeBase
{
- [System.Security.SecuritySafeCritical] // auto-generated
get
{
return AssemblyName.EscapeCodeBase(CodeBase);
}
}
- [System.Security.SecurityCritical] // auto-generated
public virtual AssemblyName GetName()
{
return GetName(false);
}
- [System.Security.SecurityCritical] // auto-generated
public virtual AssemblyName GetName(bool copiedName)
{
throw new NotImplementedException();
public bool IsFullyTrusted
{
- [SecuritySafeCritical]
get
{
return true;
}
// ISerializable implementation
- [System.Security.SecurityCritical] // auto-generated_required
public virtual void GetObjectData(SerializationInfo info, StreamingContext context)
{
throw new NotImplementedException();
// Returns the file in the File table of the manifest that matches the
// given name. (Name should not include path.)
- [System.Security.SecurityCritical] // auto-generated
public virtual FileStream GetFile(String name)
{
throw new NotImplementedException();
return GetFiles(false);
}
- [System.Security.SecurityCritical] // auto-generated
public virtual FileStream[] GetFiles(bool getResourceModules)
{
throw new NotImplementedException();
public virtual String Location
{
- [System.Security.SecurityCritical] // auto-generated
get
{
throw new NotImplementedException();
private ASSEMBLY_FLAGS Flags
{
- [SecuritySafeCritical]
get
{
if ((m_flags & ASSEMBLY_FLAGS.ASSEMBLY_FLAGS_INITIALIZED) == 0)
public override event ModuleResolveEventHandler ModuleResolve
{
- [System.Security.SecurityCritical] // auto-generated_required
add
{
_ModuleResolve += value;
}
- [System.Security.SecurityCritical] // auto-generated_required
remove
{
_ModuleResolve -= value;
private const String s_localFilePrefix = "file:";
- [System.Security.SecurityCritical] // auto-generated
[DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
[SuppressUnmanagedCodeSecurity]
private static extern void GetCodeBase(RuntimeAssembly assembly,
bool copiedName,
StringHandleOnStack retString);
- [System.Security.SecurityCritical] // auto-generated
internal String GetCodeBase(bool copiedName)
{
String codeBase = null;
public override String CodeBase
{
- [System.Security.SecurityCritical] // auto-generated
get {
String codeBase = GetCodeBase(false);
VerifyCodeBaseDiscovery(codeBase);
// If the assembly is copied before it is loaded, the codebase will be set to the
// actual file loaded if copiedName is true. If it is false, then the original code base
// is returned.
- [System.Security.SecurityCritical] // auto-generated
public override AssemblyName GetName(bool copiedName)
{
AssemblyName an = new AssemblyName();
return an;
}
- [System.Security.SecurityCritical] // auto-generated
[DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
[SuppressUnmanagedCodeSecurity]
private extern static void GetFullName(RuntimeAssembly assembly, StringHandleOnStack retString);
public override String FullName
{
- [System.Security.SecuritySafeCritical] // auto-generated
get {
// If called by Object.ToString(), return val may be NULL.
if (m_fullname == null)
}
}
- [System.Security.SecurityCritical] // auto-generated
[DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
[SuppressUnmanagedCodeSecurity]
private static extern void GetEntryPoint(RuntimeAssembly assembly, ObjectHandleOnStack retMethod);
public override MethodInfo EntryPoint
{
- [System.Security.SecuritySafeCritical] // auto-generated
get {
IRuntimeMethodInfo methodHandle = null;
GetEntryPoint(GetNativeHandle(), JitHelpers.GetObjectHandleOnStack(ref methodHandle));
}
}
- [System.Security.SecurityCritical] // auto-generated
[DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
[SuppressUnmanagedCodeSecurity]
private static extern void GetType(RuntimeAssembly assembly,
ObjectHandleOnStack type,
ObjectHandleOnStack keepAlive);
- [System.Security.SecuritySafeCritical]
public override Type GetType(String name, bool throwOnError, bool ignoreCase)
{
// throw on null strings regardless of the value of "throwOnError"
return type;
}
- [System.Security.SecurityCritical] // auto-generated
[DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
[SuppressUnmanagedCodeSecurity]
internal extern static void GetForwardedTypes(RuntimeAssembly assembly, ObjectHandleOnStack retTypes);
- [System.Security.SecurityCritical] // auto-generated
[DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
[SuppressUnmanagedCodeSecurity]
private extern static void GetExportedTypes(RuntimeAssembly assembly, ObjectHandleOnStack retTypes);
- [System.Security.SecuritySafeCritical] // auto-generated
public override Type[] GetExportedTypes()
{
Type[] types = null;
public override IEnumerable<TypeInfo> DefinedTypes
{
- [System.Security.SecuritySafeCritical]
get
{
List<RuntimeType> rtTypes = new List<RuntimeType>();
}
// Load a resource based on the NameSpace of the type.
- [System.Security.SecuritySafeCritical] // auto-generated
[MethodImplAttribute(MethodImplOptions.NoInlining)] // Methods containing StackCrawlMark local var has to be marked non-inlineable
public override Stream GetManifestResourceStream(Type type, String name)
{
return GetManifestResourceStream(type, name, false, ref stackMark);
}
- [System.Security.SecuritySafeCritical] // auto-generated
[MethodImplAttribute(MethodImplOptions.NoInlining)] // Methods containing StackCrawlMark local var has to be marked non-inlineable
public override Stream GetManifestResourceStream(String name)
{
}
// ISerializable implementation
- [System.Security.SecurityCritical] // auto-generated_required
public override void GetObjectData(SerializationInfo info, StreamingContext context)
{
if (info==null)
return CustomAttributeData.GetCustomAttributesInternal(this);
}
- [System.Security.SecurityCritical] // auto-generated
[MethodImplAttribute(MethodImplOptions.NoInlining)] // Methods containing StackCrawlMark local var has to be marked non-inlineable
internal static RuntimeAssembly InternalLoadFrom(String assemblyFile,
Evidence securityEvidence,
}
// Wrapper function to wrap the typical use of InternalLoad.
- [System.Security.SecurityCritical] // auto-generated
internal static RuntimeAssembly InternalLoad(String assemblyString,
Evidence assemblySecurity,
ref StackCrawlMark stackMark,
return InternalLoad(assemblyString, assemblySecurity, ref stackMark, IntPtr.Zero, forIntrospection);
}
- [System.Security.SecurityCritical] // auto-generated
[MethodImplAttribute(MethodImplOptions.NoInlining)] // Methods containing StackCrawlMark local var has to be marked non-inlineable
internal static RuntimeAssembly InternalLoad(String assemblyString,
Evidence assemblySecurity,
}
// Creates AssemblyName. Fills assembly if AssemblyResolve event has been raised.
- [System.Security.SecurityCritical] // auto-generated
internal static AssemblyName CreateAssemblyName(
String assemblyString,
bool forIntrospection,
}
// Wrapper function to wrap the typical use of InternalLoadAssemblyName.
- [System.Security.SecurityCritical] // auto-generated
internal static RuntimeAssembly InternalLoadAssemblyName(
AssemblyName assemblyRef,
Evidence assemblySecurity,
return InternalLoadAssemblyName(assemblyRef, assemblySecurity, reqAssembly, ref stackMark, IntPtr.Zero, true /*throwOnError*/, forIntrospection, suppressSecurityChecks, ptrLoadContextBinder);
}
- [System.Security.SecurityCritical] // auto-generated
internal static RuntimeAssembly InternalLoadAssemblyName(
AssemblyName assemblyRef,
Evidence assemblySecurity,
};
#if FEATURE_APPX
- [System.Security.SecuritySafeCritical]
internal bool IsFrameworkAssembly()
{
ASSEMBLY_FLAGS flags = Flags;
return (flags & ASSEMBLY_FLAGS.ASSEMBLY_FLAGS_SAFE_REFLECTION) != 0;
}
- [System.Security.SecuritySafeCritical]
private bool IsDesignerBindingContext()
{
return RuntimeAssembly.nIsDesignerBindingContext(this);
}
- [System.Security.SecurityCritical]
[DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
[SuppressUnmanagedCodeSecurity]
private extern static bool nIsDesignerBindingContext(RuntimeAssembly assembly);
#endif
- [System.Security.SecurityCritical] // auto-generated
[MethodImplAttribute(MethodImplOptions.InternalCall)]
private static extern RuntimeAssembly _nLoad(AssemblyName fileName,
String codeBase,
bool suppressSecurityChecks,
IntPtr ptrLoadContextBinder);
- [System.Security.SecurityCritical] // auto-generated
private static RuntimeAssembly nLoad(AssemblyName fileName,
String codeBase,
Evidence assemblySecurity,
throwOnFileNotFound, forIntrospection, suppressSecurityChecks, ptrLoadContextBinder);
}
- [System.Security.SecurityCritical] // auto-generated
[MethodImplAttribute(MethodImplOptions.InternalCall)]
private static extern bool IsReflectionOnly(RuntimeAssembly assembly);
[ComVisible(false)]
public override bool ReflectionOnly
{
- [System.Security.SecuritySafeCritical] // auto-generated
get
{
return IsReflectionOnly(GetNativeHandle());
// an emitted assembly. The assembly is loaded into the domain
// of the caller. Currently is implemented only for UnmanagedMemoryStream
// (no derived classes since we are not calling Read())
- [System.Security.SecurityCritical] // auto-generated
internal static RuntimeAssembly InternalLoadFromStream(Stream assemblyStream, Stream pdbStream, ref StackCrawlMark stackMark)
{
if (assemblyStream == null)
// Returns the module in this assembly with name 'name'
- [System.Security.SecurityCritical] // auto-generated
[DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
[SuppressUnmanagedCodeSecurity]
private static extern void GetModule(RuntimeAssembly assembly, String name, ObjectHandleOnStack retModule);
- [System.Security.SecuritySafeCritical] // auto-generated
public override Module GetModule(String name)
{
Module retModule = null;
// Returns the file in the File table of the manifest that matches the
// given name. (Name should not include path.)
- [System.Security.SecurityCritical] // auto-generated
public override FileStream GetFile(String name)
{
RuntimeModule m = (RuntimeModule)GetModule(name);
FileAccess.Read, FileShare.Read, FileStream.DefaultBufferSize, false);
}
- [System.Security.SecurityCritical] // auto-generated
public override FileStream[] GetFiles(bool getResourceModules)
{
Module[] m = GetModules(getResourceModules);
}
// Returns the names of all the resources
- [System.Security.SecurityCritical] // auto-generated
[MethodImplAttribute(MethodImplOptions.InternalCall)]
private static extern String[] GetManifestResourceNames(RuntimeAssembly assembly);
// Returns the names of all the resources
- [System.Security.SecuritySafeCritical] // auto-generated
public override String[] GetManifestResourceNames()
{
return GetManifestResourceNames(GetNativeHandle());
}
- [System.Security.SecurityCritical] // auto-generated
[DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
[SuppressUnmanagedCodeSecurity]
private extern static void GetExecutingAssembly(StackCrawlMarkHandle stackMark, ObjectHandleOnStack retAssembly);
- [System.Security.SecurityCritical] // auto-generated
internal static RuntimeAssembly GetExecutingAssembly(ref StackCrawlMark stackMark)
{
RuntimeAssembly retAssembly = null;
}
// Returns the names of all the resources
- [System.Security.SecurityCritical] // auto-generated
[MethodImplAttribute(MethodImplOptions.InternalCall)]
private static extern AssemblyName[] GetReferencedAssemblies(RuntimeAssembly assembly);
- [System.Security.SecuritySafeCritical] // auto-generated
public override AssemblyName[] GetReferencedAssemblies()
{
return GetReferencedAssemblies(GetNativeHandle());
}
- [System.Security.SecurityCritical] // auto-generated
[DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
[SuppressUnmanagedCodeSecurity]
private static extern int GetManifestResourceInfo(RuntimeAssembly assembly,
StringHandleOnStack retFileName,
StackCrawlMarkHandle stackMark);
- [System.Security.SecuritySafeCritical] // auto-generated
[MethodImplAttribute(MethodImplOptions.NoInlining)] // Methods containing StackCrawlMark local var has to be marked non-inlineable
public override ManifestResourceInfo GetManifestResourceInfo(String resourceName)
{
(ResourceLocation) location);
}
- [System.Security.SecurityCritical] // auto-generated
[DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
[SuppressUnmanagedCodeSecurity]
private static extern void GetLocation(RuntimeAssembly assembly, StringHandleOnStack retString);
public override String Location
{
- [System.Security.SecurityCritical] // auto-generated
get {
String location = null;
}
}
- [System.Security.SecurityCritical] // auto-generated
[DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
[SuppressUnmanagedCodeSecurity]
private extern static void GetImageRuntimeVersion(RuntimeAssembly assembly, StringHandleOnStack retString);
[ComVisible(false)]
public override String ImageRuntimeVersion
{
- [System.Security.SecuritySafeCritical] // auto-generated
get{
String s = null;
GetImageRuntimeVersion(GetNativeHandle(), JitHelpers.GetStringHandleOnStack(ref s));
}
- [System.Security.SecurityCritical] // auto-generated
[MethodImplAttribute(MethodImplOptions.InternalCall)]
private extern static bool IsGlobalAssemblyCache(RuntimeAssembly assembly);
public override bool GlobalAssemblyCache
{
- [System.Security.SecuritySafeCritical] // auto-generated
get
{
return false;
}
}
- [System.Security.SecurityCritical] // auto-generated
[DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
[SuppressUnmanagedCodeSecurity]
private extern static Int64 GetHostContext(RuntimeAssembly assembly);
public override Int64 HostContext
{
- [System.Security.SecuritySafeCritical] // auto-generated
get
{
return 0;
#endif // !PLATFORM_UNIX
}
- [System.Security.SecurityCritical] // auto-generated
internal Stream GetManifestResourceStream(
Type type,
String name,
}
// GetResource will return a pointer to the resources in memory.
- [System.Security.SecurityCritical] // auto-generated
[DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
[SuppressUnmanagedCodeSecurity]
private static unsafe extern byte* GetResource(RuntimeAssembly assembly,
StackCrawlMarkHandle stackMark,
bool skipSecurityCheck);
- [System.Security.SecurityCritical] // auto-generated
internal unsafe Stream GetManifestResourceStream(String name, ref StackCrawlMark stackMark, bool skipSecurityCheck)
{
ulong length = 0;
return null;
}
- [System.Security.SecurityCritical] // auto-generated
[DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
[SuppressUnmanagedCodeSecurity]
private static extern void GetVersion(RuntimeAssembly assembly,
out int buildNum,
out int revNum);
- [System.Security.SecurityCritical] // auto-generated
internal Version GetVersion()
{
int majorVer, minorVer, build, revision;
return new Version (majorVer, minorVer, build, revision);
}
- [System.Security.SecurityCritical] // auto-generated
[DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
[SuppressUnmanagedCodeSecurity]
private static extern void GetLocale(RuntimeAssembly assembly, StringHandleOnStack retString);
- [System.Security.SecurityCritical] // auto-generated
internal CultureInfo GetLocale()
{
String locale = null;
return new CultureInfo(locale);
}
- [System.Security.SecurityCritical] // auto-generated
[MethodImplAttribute(MethodImplOptions.InternalCall)]
private static extern bool FCallIsDynamic(RuntimeAssembly assembly);
public override bool IsDynamic
{
- [SecuritySafeCritical]
get {
return FCallIsDynamic(GetNativeHandle());
}
}
- [System.Security.SecurityCritical] // auto-generated
private void VerifyCodeBaseDiscovery(String codeBase)
{
if ((codeBase != null) &&
}
}
- [System.Security.SecurityCritical] // auto-generated
[DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
[SuppressUnmanagedCodeSecurity]
private static extern void GetSimpleName(RuntimeAssembly assembly, StringHandleOnStack retSimpleName);
- [SecuritySafeCritical]
internal String GetSimpleName()
{
string name = null;
return name;
}
- [System.Security.SecurityCritical] // auto-generated
[DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
[SuppressUnmanagedCodeSecurity]
private extern static AssemblyHashAlgorithm GetHashAlgorithm(RuntimeAssembly assembly);
- [System.Security.SecurityCritical] // auto-generated
private AssemblyHashAlgorithm GetHashAlgorithm()
{
return GetHashAlgorithm(GetNativeHandle());
}
- [System.Security.SecurityCritical] // auto-generated
[DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
[SuppressUnmanagedCodeSecurity]
private extern static AssemblyNameFlags GetFlags(RuntimeAssembly assembly);
- [System.Security.SecurityCritical] // auto-generated
private AssemblyNameFlags GetFlags()
{
return GetFlags(GetNativeHandle());
}
[DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
- [SecurityCritical]
[SuppressUnmanagedCodeSecurity]
private static extern void GetRawBytes(RuntimeAssembly assembly, ObjectHandleOnStack retRawBytes);
// Get the raw bytes of the assembly
- [SecuritySafeCritical]
internal byte[] GetRawBytes()
{
byte[] rawBytes = null;
return rawBytes;
}
- [System.Security.SecurityCritical] // auto-generated
[DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
[SuppressUnmanagedCodeSecurity]
private static extern void GetPublicKey(RuntimeAssembly assembly, ObjectHandleOnStack retPublicKey);
- [System.Security.SecurityCritical] // auto-generated
internal byte[] GetPublicKey()
{
byte[] publicKey = null;
return publicKey;
}
- [SecurityCritical]
[DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
[SuppressUnmanagedCodeSecurity]
private extern static void GetGrantSet(RuntimeAssembly assembly, ObjectHandleOnStack granted, ObjectHandleOnStack denied);
- [SecurityCritical]
internal void GetGrantSet(out PermissionSet newGrant, out PermissionSet newDenied)
{
PermissionSet granted = null, denied = null;
newGrant = granted; newDenied = denied;
}
- [System.Security.SecurityCritical] // auto-generated
[DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
[SuppressUnmanagedCodeSecurity]
[return: MarshalAs(UnmanagedType.Bool)]
private extern static bool IsAllSecurityCritical(RuntimeAssembly assembly);
// Is everything introduced by this assembly critical
- [System.Security.SecuritySafeCritical] // auto-generated
internal bool IsAllSecurityCritical()
{
return IsAllSecurityCritical(GetNativeHandle());
}
- [System.Security.SecurityCritical] // auto-generated
[DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
[SuppressUnmanagedCodeSecurity]
[return: MarshalAs(UnmanagedType.Bool)]
private extern static bool IsAllSecuritySafeCritical(RuntimeAssembly assembly);
// Is everything introduced by this assembly safe critical
- [System.Security.SecuritySafeCritical] // auto-generated
internal bool IsAllSecuritySafeCritical()
{
return IsAllSecuritySafeCritical(GetNativeHandle());
}
- [System.Security.SecurityCritical] // auto-generated
[DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
[SuppressUnmanagedCodeSecurity]
[return: MarshalAs(UnmanagedType.Bool)]
private extern static bool IsAllPublicAreaSecuritySafeCritical(RuntimeAssembly assembly);
// Is everything introduced by this assembly safe critical
- [System.Security.SecuritySafeCritical] // auto-generated
internal bool IsAllPublicAreaSecuritySafeCritical()
{
return IsAllPublicAreaSecuritySafeCritical(GetNativeHandle());
}
- [System.Security.SecurityCritical] // auto-generated
[DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
[SuppressUnmanagedCodeSecurity]
[return: MarshalAs(UnmanagedType.Bool)]
private extern static bool IsAllSecurityTransparent(RuntimeAssembly assembly);
// Is everything introduced by this assembly transparent
- [System.Security.SecuritySafeCritical] // auto-generated
internal bool IsAllSecurityTransparent()
{
return IsAllSecurityTransparent(GetNativeHandle());
}
// This method is called by the VM.
- [System.Security.SecurityCritical]
private RuntimeModule OnModuleResolveEvent(String moduleName)
{
ModuleResolveEventHandler moduleResolve = _ModuleResolve;
return InternalGetSatelliteAssembly(culture, version, ref stackMark);
}
- [System.Security.SecuritySafeCritical] // auto-generated
[MethodImplAttribute(MethodImplOptions.NoInlining)] // Methods containing StackCrawlMark local var has to be marked non-inlineable
internal Assembly InternalGetSatelliteAssembly(CultureInfo culture,
Version version,
return InternalGetSatelliteAssembly(name, culture, version, true, ref stackMark);
}
- [System.Security.SecurityCritical] // auto-generated
[MethodImplAttribute(MethodImplOptions.NoInlining)] // Methods containing StackCrawlMark local var has to be marked non-inlineable
internal RuntimeAssembly InternalGetSatelliteAssembly(String name,
CultureInfo culture,
}
// Helper method used by InternalGetSatelliteAssembly only. Not abstracted for use elsewhere.
- [System.Security.SecurityCritical] // auto-generated
[MethodImplAttribute(MethodImplOptions.NoInlining)] // Methods containing StackCrawlMark local var has to be marked non-inlineable
private RuntimeAssembly InternalProbeForSatelliteAssemblyNextToParentAssembly(AssemblyName an,
String name,
return retAssembly;
}
- [System.Security.SecurityCritical] // auto-generated
[MethodImplAttribute(MethodImplOptions.InternalCall)]
static internal extern RuntimeAssembly nLoadFile(String path, Evidence evidence);
- [System.Security.SecurityCritical] // auto-generated
[MethodImplAttribute(MethodImplOptions.InternalCall)]
static internal extern RuntimeAssembly nLoadImage(byte[] rawAssembly,
byte[] rawSymbolStore,
bool fIntrospection,
SecurityContextSource securityContextSource);
- [System.Security.SecurityCritical] // auto-generated
[DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
[SuppressUnmanagedCodeSecurity]
static internal extern unsafe void nLoadFromUnmanagedArray(bool fIntrospection,
StackCrawlMarkHandle stackMark,
ObjectHandleOnStack retAssembly);
- [System.Security.SecurityCritical] // auto-generated
[DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
[SuppressUnmanagedCodeSecurity]
private extern static void GetModules(RuntimeAssembly assembly,
bool getResourceModules,
ObjectHandleOnStack retModuleHandles);
- [System.Security.SecuritySafeCritical] // auto-generated
private RuntimeModule[] GetModulesInternal(bool loadIfNotFound,
bool getResourceModules)
{
return GetModulesInternal(false, getResourceModules);
}
- [System.Security.SecuritySafeCritical] // auto-generated
[MethodImplAttribute(MethodImplOptions.InternalCall)]
internal static extern RuntimeModule GetManifestModule(RuntimeAssembly assembly);
- [System.Security.SecurityCritical] // auto-generated
[MethodImplAttribute(MethodImplOptions.InternalCall)]
internal static extern int GetToken(RuntimeAssembly assembly);
}
public String CodeBase
{
-#if FEATURE_CORECLR
- [System.Security.SecurityCritical] // auto-generated
-#endif
get { return _CodeBase; }
-#if FEATURE_CORECLR
- [System.Security.SecurityCritical] // auto-generated
-#endif
set { _CodeBase = value; }
}
public String EscapedCodeBase
{
- [System.Security.SecuritySafeCritical] // auto-generated
get
{
if (_CodeBase == null)
* if the file contains an assembly manifest. This method causes
* the file to be opened and closed.
*/
- [System.Security.SecuritySafeCritical] // auto-generated
static public AssemblyName GetAssemblyName(String assemblyFile)
{
if(assemblyFile == null)
// The compressed version of the public key formed from a truncated hash.
// Will throw a SecurityException if _PublicKey is invalid
- [System.Security.SecuritySafeCritical] // auto-generated
public byte[] GetPublicKeyToken()
{
if (_PublicKeyToken == null)
public String FullName
{
- [System.Security.SecuritySafeCritical] // auto-generated
get {
return nToString();
}
return s;
}
- [System.Security.SecurityCritical] // auto-generated_required
public void GetObjectData(SerializationInfo info, StreamingContext context)
{
if (info == null)
m_siInfo = info;
}
- [System.Security.SecuritySafeCritical] // auto-generated
public AssemblyName(String assemblyName)
{
if (assemblyName == null)
nInit();
}
- [System.Security.SecuritySafeCritical] // auto-generated
static public bool ReferenceMatchesDefinition(AssemblyName reference,
AssemblyName definition)
{
/// "parse" tells us to parse the simple name of the assembly as if it was the full name
/// almost never the right thing to do, but needed for compat
- [System.Security.SecuritySafeCritical] // auto-generated
[MethodImplAttribute(MethodImplOptions.InternalCall)]
static internal extern bool ReferenceMatchesDefinitionInternal(AssemblyName reference,
AssemblyName definition,
- [System.Security.SecurityCritical] // auto-generated
[MethodImplAttribute(MethodImplOptions.InternalCall)]
internal extern void nInit(out RuntimeAssembly assembly, bool forIntrospection, bool raiseResolveEvent);
- [System.Security.SecurityCritical] // auto-generated
internal void nInit()
{
RuntimeAssembly dummy = null;
// This call opens and closes the file, but does not add the
// assembly to the domain.
- [System.Security.SecurityCritical] // auto-generated
[MethodImplAttribute(MethodImplOptions.InternalCall)]
static internal extern AssemblyName nGetFileInformation(String s);
- [System.Security.SecurityCritical] // auto-generated
[MethodImplAttribute(MethodImplOptions.InternalCall)]
private extern String nToString();
- [System.Security.SecurityCritical] // auto-generated
[MethodImplAttribute(MethodImplOptions.InternalCall)]
private extern byte[] nGetPublicKeyToken();
- [System.Security.SecurityCritical] // auto-generated
static internal String EscapeCodeBase(String codebase)
{
if (codebase == null)
{
using System;
using System.Collections.Generic;
+ using System.Diagnostics;
using System.Diagnostics.Contracts;
internal static class Associates
return false;
}
- [System.Security.SecurityCritical] // auto-generated
private static unsafe RuntimeMethodInfo AssignAssociates(
int tkMethod,
RuntimeType declaredType,
if (MetadataToken.IsNullToken(tkMethod))
return null;
- Contract.Assert(declaredType != null);
- Contract.Assert(reflectedType != null);
+ Debug.Assert(declaredType != null);
+ Debug.Assert(reflectedType != null);
bool isInherited = declaredType != reflectedType;
}
RuntimeMethodHandleInternal associateMethodHandle = ModuleHandle.ResolveMethodHandleInternalCore(RuntimeTypeHandle.GetModule(declaredType), tkMethod, genericArgumentHandles, genericArgumentCount, null, 0);
- Contract.Assert(!associateMethodHandle.IsNullHandle(), "Failed to resolve associateRecord methodDef token");
+ Debug.Assert(!associateMethodHandle.IsNullHandle(), "Failed to resolve associateRecord methodDef token");
if (isInherited)
{
return associateMethod;
}
- [System.Security.SecurityCritical] // auto-generated
internal static unsafe void AssignAssociates(
MetadataImport scope,
int mdPropEvent,
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
-using System;
-using System.Globalization;
-using System.IO;
-using System.Reflection;
-using System.Runtime.InteropServices;
-using System.Runtime.Serialization;
-using System.Security.Permissions;
-using System.Security.Policy;
-
namespace System.Runtime.InteropServices
{
[GuidAttribute("BCA8B44D-AAD6-3A86-8AB7-03349F4F2DA2")]
[CLSCompliant(false)]
[InterfaceTypeAttribute(ComInterfaceType.InterfaceIsIUnknown)]
[TypeLibImportClassAttribute(typeof(System.Type))]
-[System.Runtime.InteropServices.ComVisible(true)]
+ [System.Runtime.InteropServices.ComVisible(true)]
public interface _Type
{
-#if !FEATURE_CORECLR
- #region IDispatch Members
- void GetTypeInfoCount(out uint pcTInfo);
- void GetTypeInfo(uint iTInfo, uint lcid, IntPtr ppTInfo);
- void GetIDsOfNames([In] ref Guid riid, IntPtr rgszNames, uint cNames, uint lcid, IntPtr rgDispId);
- void Invoke(uint dispIdMember, [In] ref Guid riid, uint lcid, short wFlags, IntPtr pDispParams, IntPtr pVarResult, IntPtr pExcepInfo, IntPtr puArgErr);
- #endregion
-
- #region Object Members
- String ToString();
- bool Equals(Object other);
- int GetHashCode();
- Type GetType();
- #endregion
-
- #region MemberInfo Members
- MemberTypes MemberType { get; }
- String Name { get; }
- Type DeclaringType { get; }
- Type ReflectedType { get; }
- Object[] GetCustomAttributes(Type attributeType, bool inherit);
- Object[] GetCustomAttributes(bool inherit);
- bool IsDefined(Type attributeType, bool inherit);
- #endregion
-
- #region Type Members
- Guid GUID { get; }
- Module Module { get; }
- Assembly Assembly { get; }
- RuntimeTypeHandle TypeHandle { get; }
- String FullName { get; }
- String Namespace { get; }
- String AssemblyQualifiedName { get; }
- int GetArrayRank();
- Type BaseType { get; }
-
- ConstructorInfo[] GetConstructors(BindingFlags bindingAttr);
- Type GetInterface(String name, bool ignoreCase);
- Type[] GetInterfaces();
- Type[] FindInterfaces(TypeFilter filter,Object filterCriteria);
- EventInfo GetEvent(String name,BindingFlags bindingAttr);
- EventInfo[] GetEvents();
- EventInfo[] GetEvents(BindingFlags bindingAttr);
- Type[] GetNestedTypes(BindingFlags bindingAttr);
- Type GetNestedType(String name, BindingFlags bindingAttr);
- MemberInfo[] GetMember(String name, MemberTypes type, BindingFlags bindingAttr);
- MemberInfo[] GetDefaultMembers();
- MemberInfo[] FindMembers(MemberTypes memberType,BindingFlags bindingAttr,MemberFilter filter,Object filterCriteria);
- Type GetElementType();
- bool IsSubclassOf(Type c);
- bool IsInstanceOfType(Object o);
- bool IsAssignableFrom(Type c);
- InterfaceMapping GetInterfaceMap(Type interfaceType);
- MethodInfo GetMethod(String name, BindingFlags bindingAttr, Binder binder, Type[] types, ParameterModifier[] modifiers);
- MethodInfo GetMethod(String name, BindingFlags bindingAttr);
- MethodInfo[] GetMethods(BindingFlags bindingAttr);
- FieldInfo GetField(String name, BindingFlags bindingAttr);
- FieldInfo[] GetFields(BindingFlags bindingAttr);
- PropertyInfo GetProperty(String name, BindingFlags bindingAttr);
- PropertyInfo GetProperty(String name,BindingFlags bindingAttr,Binder binder, Type returnType, Type[] types, ParameterModifier[] modifiers);
- PropertyInfo[] GetProperties(BindingFlags bindingAttr);
- MemberInfo[] GetMember(String name, BindingFlags bindingAttr);
- MemberInfo[] GetMembers(BindingFlags bindingAttr);
- Object InvokeMember(String name, BindingFlags invokeAttr, Binder binder, Object target, Object[] args, ParameterModifier[] modifiers, CultureInfo culture, String[] namedParameters);
- Type UnderlyingSystemType
- {
- get;
- }
-
- Object InvokeMember(String name,BindingFlags invokeAttr,Binder binder, Object target, Object[] args, CultureInfo culture);
- Object InvokeMember(String name,BindingFlags invokeAttr,Binder binder, Object target, Object[] args);
- ConstructorInfo GetConstructor(BindingFlags bindingAttr, Binder binder, CallingConventions callConvention, Type[] types, ParameterModifier[] modifiers);
- ConstructorInfo GetConstructor(BindingFlags bindingAttr, Binder binder, Type[] types, ParameterModifier[] modifiers);
- ConstructorInfo GetConstructor(Type[] types);
- ConstructorInfo[] GetConstructors();
- ConstructorInfo TypeInitializer
- {
- get;
- }
-
- MethodInfo GetMethod(String name, BindingFlags bindingAttr, Binder binder, CallingConventions callConvention, Type[] types, ParameterModifier[] modifiers);
- MethodInfo GetMethod(String name, Type[] types, ParameterModifier[] modifiers);
- MethodInfo GetMethod(String name, Type[] types);
- MethodInfo GetMethod(String name);
- MethodInfo[] GetMethods();
- FieldInfo GetField(String name);
- FieldInfo[] GetFields();
- Type GetInterface(String name);
- EventInfo GetEvent(String name);
- PropertyInfo GetProperty(String name, Type returnType, Type[] types,ParameterModifier[] modifiers);
- PropertyInfo GetProperty(String name, Type returnType, Type[] types);
- PropertyInfo GetProperty(String name, Type[] types);
- PropertyInfo GetProperty(String name, Type returnType);
- PropertyInfo GetProperty(String name);
- PropertyInfo[] GetProperties();
- Type[] GetNestedTypes();
- Type GetNestedType(String name);
- MemberInfo[] GetMember(String name);
- MemberInfo[] GetMembers();
- TypeAttributes Attributes { get; }
- bool IsNotPublic { get; }
- bool IsPublic { get; }
- bool IsNestedPublic { get; }
- bool IsNestedPrivate { get; }
- bool IsNestedFamily { get; }
- bool IsNestedAssembly { get; }
- bool IsNestedFamANDAssem { get; }
- bool IsNestedFamORAssem { get; }
- bool IsAutoLayout { get; }
- bool IsLayoutSequential { get; }
- bool IsExplicitLayout { get; }
- bool IsClass { get; }
- bool IsInterface { get; }
- bool IsValueType { get; }
- bool IsAbstract { get; }
- bool IsSealed { get; }
- bool IsEnum { get; }
- bool IsSpecialName { get; }
- bool IsImport { get; }
- bool IsSerializable { get; }
- bool IsAnsiClass { get; }
- bool IsUnicodeClass { get; }
- bool IsAutoClass { get; }
- bool IsArray { get; }
- bool IsByRef { get; }
- bool IsPointer { get; }
- bool IsPrimitive { get; }
- bool IsCOMObject { get; }
- bool HasElementType { get; }
- bool IsContextful { get; }
- bool IsMarshalByRef { get; }
- bool Equals(Type o);
- #endregion
-#endif
}
[GuidAttribute("17156360-2f1a-384a-bc52-fde93c215c5b")]
[System.Runtime.InteropServices.ComVisible(true)]
public interface _MemberInfo
{
-#if !FEATURE_CORECLR
- #region IDispatch Members
- void GetTypeInfoCount(out uint pcTInfo);
- void GetTypeInfo(uint iTInfo, uint lcid, IntPtr ppTInfo);
- void GetIDsOfNames([In] ref Guid riid, IntPtr rgszNames, uint cNames, uint lcid, IntPtr rgDispId);
- void Invoke(uint dispIdMember, [In] ref Guid riid, uint lcid, short wFlags, IntPtr pDispParams, IntPtr pVarResult, IntPtr pExcepInfo, IntPtr puArgErr);
- #endregion
-
- #region Object Members
- String ToString();
- bool Equals(Object other);
- int GetHashCode();
- Type GetType();
- #endregion
-
- #region MemberInfo Members
- MemberTypes MemberType { get; }
- String Name { get; }
- Type DeclaringType { get; }
- Type ReflectedType { get; }
- Object[] GetCustomAttributes(Type attributeType, bool inherit);
- Object[] GetCustomAttributes(bool inherit);
- bool IsDefined(Type attributeType, bool inherit);
- #endregion
-#endif
}
-
[GuidAttribute("6240837A-707F-3181-8E98-A36AE086766B")]
[InterfaceTypeAttribute(ComInterfaceType.InterfaceIsIUnknown)]
[CLSCompliant(false)]
[System.Runtime.InteropServices.ComVisible(true)]
public interface _MethodBase
{
-#if !FEATURE_CORECLR
- #region IDispatch Members
- void GetTypeInfoCount(out uint pcTInfo);
- void GetTypeInfo(uint iTInfo, uint lcid, IntPtr ppTInfo);
- void GetIDsOfNames([In] ref Guid riid, IntPtr rgszNames, uint cNames, uint lcid, IntPtr rgDispId);
- void Invoke(uint dispIdMember, [In] ref Guid riid, uint lcid, short wFlags, IntPtr pDispParams, IntPtr pVarResult, IntPtr pExcepInfo, IntPtr puArgErr);
- #endregion
-
- #region Object Members
- String ToString();
- bool Equals(Object other);
- int GetHashCode();
- Type GetType();
- #endregion
-
- #region MemberInfo Members
- MemberTypes MemberType { get; }
- String Name { get; }
- Type DeclaringType { get; }
- Type ReflectedType { get; }
- Object[] GetCustomAttributes(Type attributeType, bool inherit);
- Object[] GetCustomAttributes(bool inherit);
- bool IsDefined(Type attributeType, bool inherit);
- #endregion
-
- #region MethodBase Members
- ParameterInfo[] GetParameters();
- MethodImplAttributes GetMethodImplementationFlags();
- RuntimeMethodHandle MethodHandle { get; }
- MethodAttributes Attributes { get; }
- CallingConventions CallingConvention { get; }
- Object Invoke(Object obj, BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture);
- bool IsPublic { get; }
- bool IsPrivate { get; }
- bool IsFamily { get; }
- bool IsAssembly { get; }
- bool IsFamilyAndAssembly { get; }
- bool IsFamilyOrAssembly { get; }
- bool IsStatic { get; }
- bool IsFinal { get; }
- bool IsVirtual { get; }
- bool IsHideBySig { get; }
- bool IsAbstract { get; }
- bool IsSpecialName { get; }
- bool IsConstructor { get; }
- Object Invoke(Object obj, Object[] parameters);
- #endregion
-#endif
}
-
[GuidAttribute("FFCC1B5D-ECB8-38DD-9B01-3DC8ABC2AA5F")]
[InterfaceTypeAttribute(ComInterfaceType.InterfaceIsIUnknown)]
[CLSCompliant(false)]
[System.Runtime.InteropServices.ComVisible(true)]
public interface _MethodInfo
{
-#if !FEATURE_CORECLR
- #region IDispatch Members
- void GetTypeInfoCount(out uint pcTInfo);
- void GetTypeInfo(uint iTInfo, uint lcid, IntPtr ppTInfo);
- void GetIDsOfNames([In] ref Guid riid, IntPtr rgszNames, uint cNames, uint lcid, IntPtr rgDispId);
- void Invoke(uint dispIdMember, [In] ref Guid riid, uint lcid, short wFlags, IntPtr pDispParams, IntPtr pVarResult, IntPtr pExcepInfo, IntPtr puArgErr);
- #endregion
-
- #region Object Members
- String ToString();
- bool Equals(Object other);
- int GetHashCode();
- Type GetType();
- #endregion
-
- #region MemberInfo Members
- MemberTypes MemberType { get; }
- String Name { get; }
- Type DeclaringType { get; }
- Type ReflectedType { get; }
- Object[] GetCustomAttributes(Type attributeType, bool inherit);
- Object[] GetCustomAttributes(bool inherit);
- bool IsDefined(Type attributeType, bool inherit);
- #endregion
-
- #region MethodBase Members
- ParameterInfo[] GetParameters();
- MethodImplAttributes GetMethodImplementationFlags();
- RuntimeMethodHandle MethodHandle { get; }
- MethodAttributes Attributes { get; }
- CallingConventions CallingConvention { get; }
- Object Invoke(Object obj, BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture);
- bool IsPublic { get; }
- bool IsPrivate { get; }
- bool IsFamily { get; }
- bool IsAssembly { get; }
- bool IsFamilyAndAssembly { get; }
- bool IsFamilyOrAssembly { get; }
- bool IsStatic { get; }
- bool IsFinal { get; }
- bool IsVirtual { get; }
- bool IsHideBySig { get; }
- bool IsAbstract { get; }
- bool IsSpecialName { get; }
- bool IsConstructor { get; }
- Object Invoke(Object obj, Object[] parameters);
- #endregion
-
- #region MethodInfo Members
- Type ReturnType { get; }
- ICustomAttributeProvider ReturnTypeCustomAttributes { get; }
- MethodInfo GetBaseDefinition();
- #endregion
-#endif
}
-
[GuidAttribute("E9A19478-9646-3679-9B10-8411AE1FD57D")]
[InterfaceTypeAttribute(ComInterfaceType.InterfaceIsIUnknown)]
[System.Runtime.InteropServices.ComVisible(true)]
public interface _ConstructorInfo
{
-#if !FEATURE_CORECLR
- #region IDispatch Members
- void GetTypeInfoCount(out uint pcTInfo);
- void GetTypeInfo(uint iTInfo, uint lcid, IntPtr ppTInfo);
- void GetIDsOfNames([In] ref Guid riid, IntPtr rgszNames, uint cNames, uint lcid, IntPtr rgDispId);
- void Invoke(uint dispIdMember, [In] ref Guid riid, uint lcid, short wFlags, IntPtr pDispParams, IntPtr pVarResult, IntPtr pExcepInfo, IntPtr puArgErr);
- #endregion
-
- #region Object Members
- String ToString();
- bool Equals(Object other);
- int GetHashCode();
- Type GetType();
- #endregion
-
- #region MemberInfo Members
- MemberTypes MemberType { get; }
- String Name { get; }
- Type DeclaringType { get; }
- Type ReflectedType { get; }
- Object[] GetCustomAttributes(Type attributeType, bool inherit);
- Object[] GetCustomAttributes(bool inherit);
- bool IsDefined(Type attributeType, bool inherit);
- #endregion
-
- #region MethodBase Members
- ParameterInfo[] GetParameters();
- MethodImplAttributes GetMethodImplementationFlags();
- RuntimeMethodHandle MethodHandle { get; }
- MethodAttributes Attributes { get; }
- CallingConventions CallingConvention { get; }
- Object Invoke_2(Object obj, BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture);
- bool IsPublic { get; }
- bool IsPrivate { get; }
- bool IsFamily { get; }
- bool IsAssembly { get; }
- bool IsFamilyAndAssembly { get; }
- bool IsFamilyOrAssembly { get; }
- bool IsStatic { get; }
- bool IsFinal { get; }
- bool IsVirtual { get; }
- bool IsHideBySig { get; }
- bool IsAbstract { get; }
- bool IsSpecialName { get; }
- bool IsConstructor { get; }
- Object Invoke_3(Object obj, Object[] parameters);
- #endregion
-
- #region ConstructorInfo
- Object Invoke_4(BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture);
- Object Invoke_5(Object[] parameters);
- #endregion
-#endif
}
-
[GuidAttribute("8A7C1442-A9FB-366B-80D8-4939FFA6DBE0")]
[InterfaceTypeAttribute(ComInterfaceType.InterfaceIsIUnknown)]
[CLSCompliant(false)]
[TypeLibImportClassAttribute(typeof(System.Reflection.FieldInfo))]
[System.Runtime.InteropServices.ComVisible(true)]
public interface _FieldInfo
- {
-#if !FEATURE_CORECLR
- #region IDispatch Members
- void GetTypeInfoCount(out uint pcTInfo);
- void GetTypeInfo(uint iTInfo, uint lcid, IntPtr ppTInfo);
- void GetIDsOfNames([In] ref Guid riid, IntPtr rgszNames, uint cNames, uint lcid, IntPtr rgDispId);
- void Invoke(uint dispIdMember, [In] ref Guid riid, uint lcid, short wFlags, IntPtr pDispParams, IntPtr pVarResult, IntPtr pExcepInfo, IntPtr puArgErr);
- #endregion
-
- #region Object Members
- String ToString();
- bool Equals(Object other);
- int GetHashCode();
- Type GetType();
- #endregion
-
- #region MemberInfo Members
- MemberTypes MemberType { get; }
- String Name { get; }
- Type DeclaringType { get; }
- Type ReflectedType { get; }
- Object[] GetCustomAttributes(Type attributeType, bool inherit);
- Object[] GetCustomAttributes(bool inherit);
- bool IsDefined(Type attributeType, bool inherit);
- #endregion
-
- #region FieldInfo Members
- Type FieldType { get; }
- Object GetValue(Object obj);
- Object GetValueDirect(TypedReference obj);
- void SetValue(Object obj, Object value, BindingFlags invokeAttr, Binder binder, CultureInfo culture);
- void SetValueDirect(TypedReference obj,Object value);
- RuntimeFieldHandle FieldHandle { get; }
- FieldAttributes Attributes { get; }
- void SetValue(Object obj, Object value);
- bool IsPublic { get; }
- bool IsPrivate { get; }
- bool IsFamily { get; }
- bool IsAssembly { get; }
- bool IsFamilyAndAssembly { get; }
- bool IsFamilyOrAssembly { get; }
- bool IsStatic { get; }
- bool IsInitOnly { get; }
- bool IsLiteral { get; }
- bool IsNotSerialized { get; }
- bool IsSpecialName { get; }
- bool IsPinvokeImpl { get; }
- #endregion
-#endif
+ {
}
-
[GuidAttribute("F59ED4E4-E68F-3218-BD77-061AA82824BF")]
[InterfaceTypeAttribute(ComInterfaceType.InterfaceIsIUnknown)]
[CLSCompliant(false)]
[TypeLibImportClassAttribute(typeof(System.Reflection.PropertyInfo))]
-[System.Runtime.InteropServices.ComVisible(true)]
+ [System.Runtime.InteropServices.ComVisible(true)]
public interface _PropertyInfo
{
-#if !FEATURE_CORECLR
- #region IDispatch Members
- void GetTypeInfoCount(out uint pcTInfo);
- void GetTypeInfo(uint iTInfo, uint lcid, IntPtr ppTInfo);
- void GetIDsOfNames([In] ref Guid riid, IntPtr rgszNames, uint cNames, uint lcid, IntPtr rgDispId);
- void Invoke(uint dispIdMember, [In] ref Guid riid, uint lcid, short wFlags, IntPtr pDispParams, IntPtr pVarResult, IntPtr pExcepInfo, IntPtr puArgErr);
- #endregion
-
- #region Object Members
- String ToString();
- bool Equals(Object other);
- int GetHashCode();
- Type GetType();
- #endregion
-
- #region MemberInfo Members
- MemberTypes MemberType { get; }
- String Name { get; }
- Type DeclaringType { get; }
- Type ReflectedType { get; }
- Object[] GetCustomAttributes(Type attributeType, bool inherit);
- Object[] GetCustomAttributes(bool inherit);
- bool IsDefined(Type attributeType, bool inherit);
- #endregion
-
- #region Property Members
- Type PropertyType { get; }
- Object GetValue(Object obj,Object[] index);
- Object GetValue(Object obj,BindingFlags invokeAttr,Binder binder, Object[] index, CultureInfo culture);
- void SetValue(Object obj, Object value, Object[] index);
- void SetValue(Object obj, Object value, BindingFlags invokeAttr, Binder binder, Object[] index, CultureInfo culture);
- MethodInfo[] GetAccessors(bool nonPublic);
- MethodInfo GetGetMethod(bool nonPublic);
- MethodInfo GetSetMethod(bool nonPublic);
- ParameterInfo[] GetIndexParameters();
- PropertyAttributes Attributes { get; }
- bool CanRead { get; }
- bool CanWrite { get; }
- MethodInfo[] GetAccessors();
- MethodInfo GetGetMethod();
- MethodInfo GetSetMethod();
- bool IsSpecialName { get; }
- #endregion
-#endif
}
-
[GuidAttribute("9DE59C64-D889-35A1-B897-587D74469E5B")]
[InterfaceTypeAttribute(ComInterfaceType.InterfaceIsIUnknown)]
[CLSCompliant(false)]
[System.Runtime.InteropServices.ComVisible(true)]
public interface _EventInfo
{
-#if !FEATURE_CORECLR
- #region IDispatch Members
- void GetTypeInfoCount(out uint pcTInfo);
- void GetTypeInfo(uint iTInfo, uint lcid, IntPtr ppTInfo);
- void GetIDsOfNames([In] ref Guid riid, IntPtr rgszNames, uint cNames, uint lcid, IntPtr rgDispId);
- void Invoke(uint dispIdMember, [In] ref Guid riid, uint lcid, short wFlags, IntPtr pDispParams, IntPtr pVarResult, IntPtr pExcepInfo, IntPtr puArgErr);
- #endregion
-
- #region Object Members
- String ToString();
- bool Equals(Object other);
- int GetHashCode();
- Type GetType();
- #endregion
-
- #region MemberInfo Members
- MemberTypes MemberType { get; }
- String Name { get; }
- Type DeclaringType { get; }
- Type ReflectedType { get; }
- Object[] GetCustomAttributes(Type attributeType, bool inherit);
- Object[] GetCustomAttributes(bool inherit);
- bool IsDefined(Type attributeType, bool inherit);
- #endregion
-
- #region EventInfo Members
- MethodInfo GetAddMethod(bool nonPublic);
- MethodInfo GetRemoveMethod(bool nonPublic);
- MethodInfo GetRaiseMethod(bool nonPublic);
- EventAttributes Attributes { get; }
- MethodInfo GetAddMethod();
- MethodInfo GetRemoveMethod();
- MethodInfo GetRaiseMethod();
- void AddEventHandler(Object target, Delegate handler);
- void RemoveEventHandler(Object target, Delegate handler);
- Type EventHandlerType { get; }
- bool IsSpecialName { get; }
- bool IsMulticast { get; }
- #endregion
-#endif
}
[GuidAttribute("993634C4-E47A-32CC-BE08-85F567DC27D6")]
[InterfaceTypeAttribute(ComInterfaceType.InterfaceIsIUnknown)]
[CLSCompliant(false)]
[TypeLibImportClassAttribute(typeof(System.Reflection.ParameterInfo))]
-[System.Runtime.InteropServices.ComVisible(true)]
+ [System.Runtime.InteropServices.ComVisible(true)]
public interface _ParameterInfo
{
-#if !FEATURE_CORECLR
- void GetTypeInfoCount(out uint pcTInfo);
- void GetTypeInfo(uint iTInfo, uint lcid, IntPtr ppTInfo);
- void GetIDsOfNames([In] ref Guid riid, IntPtr rgszNames, uint cNames, uint lcid, IntPtr rgDispId);
- void Invoke(uint dispIdMember, [In] ref Guid riid, uint lcid, short wFlags, IntPtr pDispParams, IntPtr pVarResult, IntPtr pExcepInfo, IntPtr puArgErr);
-#endif
}
[GuidAttribute("D002E9BA-D9E3-3749-B1D3-D565A08B13E7")]
[InterfaceTypeAttribute(ComInterfaceType.InterfaceIsIUnknown)]
[CLSCompliant(false)]
[TypeLibImportClassAttribute(typeof(System.Reflection.Module))]
-[System.Runtime.InteropServices.ComVisible(true)]
+ [System.Runtime.InteropServices.ComVisible(true)]
public interface _Module
{
-#if !FEATURE_CORECLR
- void GetTypeInfoCount(out uint pcTInfo);
- void GetTypeInfo(uint iTInfo, uint lcid, IntPtr ppTInfo);
- void GetIDsOfNames([In] ref Guid riid, IntPtr rgszNames, uint cNames, uint lcid, IntPtr rgDispId);
- void Invoke(uint dispIdMember, [In] ref Guid riid, uint lcid, short wFlags, IntPtr pDispParams, IntPtr pVarResult, IntPtr pExcepInfo, IntPtr puArgErr);
-#endif
}
[GuidAttribute("B42B6AAC-317E-34D5-9FA9-093BB4160C50")]
[InterfaceTypeAttribute(ComInterfaceType.InterfaceIsIUnknown)]
[CLSCompliant(false)]
[TypeLibImportClassAttribute(typeof(System.Reflection.AssemblyName))]
-[System.Runtime.InteropServices.ComVisible(true)]
+ [System.Runtime.InteropServices.ComVisible(true)]
public interface _AssemblyName
{
-#if !FEATURE_CORECLR
- void GetTypeInfoCount(out uint pcTInfo);
- void GetTypeInfo(uint iTInfo, uint lcid, IntPtr ppTInfo);
- void GetIDsOfNames([In] ref Guid riid, IntPtr rgszNames, uint cNames, uint lcid, IntPtr rgDispId);
- void Invoke(uint dispIdMember, [In] ref Guid riid, uint lcid, short wFlags, IntPtr pDispParams, IntPtr pVarResult, IntPtr pExcepInfo, IntPtr puArgErr);
-#endif
}
}
using System.Runtime;
using System.Runtime.ConstrainedExecution;
using System.Runtime.InteropServices;
-#if FEATURE_REMOTING
- using System.Runtime.Remoting.Metadata;
-#endif //FEATURE_REMOTING
using System.Runtime.Serialization;
using System.Security;
using System.Security.Permissions;
[Serializable]
[ClassInterface(ClassInterfaceType.None)]
[ComDefaultInterface(typeof(_ConstructorInfo))]
-#pragma warning disable 618
- [PermissionSetAttribute(SecurityAction.InheritanceDemand, Name = "FullTrust")]
-#pragma warning restore 618
[System.Runtime.InteropServices.ComVisible(true)]
public abstract class ConstructorInfo : MethodBase, _ConstructorInfo
{
return Invoke(BindingFlags.Default, null, parameters, null);
}
#endregion
-
-#if !FEATURE_CORECLR
- #region COM Interop Support
- Type _ConstructorInfo.GetType()
- {
- return base.GetType();
- }
-
- Object _ConstructorInfo.Invoke_2(Object obj, BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture)
- {
- return Invoke(obj, invokeAttr, binder, parameters, culture);
- }
-
- Object _ConstructorInfo.Invoke_3(Object obj, Object[] parameters)
- {
- return Invoke(obj, parameters);
- }
-
- Object _ConstructorInfo.Invoke_4(BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture)
- {
- return Invoke(invokeAttr, binder, parameters, culture);
- }
-
- Object _ConstructorInfo.Invoke_5(Object[] parameters)
- {
- return Invoke(parameters);
- }
-
- void _ConstructorInfo.GetTypeInfoCount(out uint pcTInfo)
- {
- throw new NotImplementedException();
- }
-
- void _ConstructorInfo.GetTypeInfo(uint iTInfo, uint lcid, IntPtr ppTInfo)
- {
- throw new NotImplementedException();
- }
-
- void _ConstructorInfo.GetIDsOfNames([In] ref Guid riid, IntPtr rgszNames, uint cNames, uint lcid, IntPtr rgDispId)
- {
- throw new NotImplementedException();
- }
-
- // If you implement this method, make sure to include _ConstructorInfo.Invoke in VM\DangerousAPIs.h and
- // include _ConstructorInfo in SystemDomain::IsReflectionInvocationMethod in AppDomain.cpp.
- void _ConstructorInfo.Invoke(uint dispIdMember, [In] ref Guid riid, uint lcid, short wFlags, IntPtr pDispParams, IntPtr pVarResult, IntPtr pExcepInfo, IntPtr puArgErr)
- {
- throw new NotImplementedException();
- }
- #endregion
-#endif
}
[Serializable]
internal INVOCATION_FLAGS InvocationFlags
{
- [System.Security.SecuritySafeCritical]
get
{
if ((m_invocationFlags & INVOCATION_FLAGS.INVOCATION_FLAGS_INITIALIZED) == 0)
#endregion
#region Constructor
- [System.Security.SecurityCritical] // auto-generated
internal RuntimeConstructorInfo(
RuntimeMethodHandleInternal handle, RuntimeType declaringType, RuntimeTypeCache reflectedTypeCache,
MethodAttributes methodAttributes, BindingFlags bindingFlags)
}
#endregion
-#if FEATURE_REMOTING
- #region Legacy Remoting Cache
- // The size of CachedData is accounted for by BaseObjectWithCachedData in object.h.
- // This member is currently being used by Remoting for caching remoting data. If you
- // need to cache data here, talk to the Remoting team to work out a mechanism, so that
- // both caching systems can happily work together.
- private RemotingMethodCachedData m_cachedData;
-
- internal RemotingMethodCachedData RemotingCache
- {
- get
- {
- // This grabs an internal copy of m_cachedData and uses
- // that instead of looking at m_cachedData directly because
- // the cache may get cleared asynchronously. This prevents
- // us from having to take a lock.
- RemotingMethodCachedData cache = m_cachedData;
- if (cache == null)
- {
- cache = new RemotingMethodCachedData(this);
- RemotingMethodCachedData ret = Interlocked.CompareExchange(ref m_cachedData, cache, null);
- if (ret != null)
- cache = ret;
- }
- return cache;
- }
- }
- #endregion
-#endif //FEATURE_REMOTING
-
#region NonPublic Methods
RuntimeMethodHandleInternal IRuntimeMethodInfo.Value
{
- [System.Security.SecuritySafeCritical]
get
{
return new RuntimeMethodHandleInternal(m_handle);
return CustomAttribute.GetCustomAttributes(this, attributeRuntimeType);
}
- [System.Security.SecuritySafeCritical] // auto-generated
public override bool IsDefined(Type attributeType, bool inherit)
{
if (attributeType == null)
#region MemberInfo Overrides
public override String Name
{
- [System.Security.SecuritySafeCritical] // auto-generated
get { return RuntimeMethodHandle.GetName(this); }
}
[System.Runtime.InteropServices.ComVisible(true)]
public override int MetadataToken
{
- [System.Security.SecuritySafeCritical] // auto-generated
get { return RuntimeMethodHandle.GetMethodDef(this); }
}
public override Module Module
// This seems to always returns System.Void.
internal override Type GetReturnType() { return Signature.ReturnType; }
- [System.Security.SecuritySafeCritical] // auto-generated
internal override ParameterInfo[] GetParametersNoCopy()
{
if (m_parameters == null)
throw new TargetException();
}
- [System.Security.SecuritySafeCritical] // auto-generated
[DebuggerStepThroughAttribute]
[Diagnostics.DebuggerHidden]
[MethodImplAttribute(MethodImplOptions.NoInlining)] // Methods containing StackCrawlMark local var has to be marked non-inlineable
if (obj != null)
{
-
-#if FEATURE_CORECLR
// For unverifiable code, we require the caller to be critical.
// Adding the INVOCATION_FLAGS_NEED_SECURITY flag makes that check happen
invocationFlags |= INVOCATION_FLAGS.INVOCATION_FLAGS_NEED_SECURITY;
-#else // FEATURE_CORECLR
- new SecurityPermission(SecurityPermissionFlag.SkipVerification).Demand();
-#endif // FEATURE_CORECLR
-
}
-#if !FEATURE_CORECLR
- if ((invocationFlags &(INVOCATION_FLAGS.INVOCATION_FLAGS_RISKY_METHOD | INVOCATION_FLAGS.INVOCATION_FLAGS_NEED_SECURITY)) != 0)
- {
- if ((invocationFlags & INVOCATION_FLAGS.INVOCATION_FLAGS_RISKY_METHOD) != 0)
- CodeAccessPermission.Demand(PermissionType.ReflectionMemberAccess);
- if ((invocationFlags & INVOCATION_FLAGS.INVOCATION_FLAGS_NEED_SECURITY) != 0)
- RuntimeMethodHandle.PerformSecurityCheck(obj, this, m_declaringType, (uint)m_invocationFlags);
- }
-#endif // !FEATURE_CORECLR
-
Signature sig = Signature;
// get the signature
}
- [System.Security.SecuritySafeCritical] // overrides SC member
#pragma warning disable 618
[ReflectionPermissionAttribute(SecurityAction.Demand, Flags = ReflectionPermissionFlag.MemberAccess)]
#pragma warning restore 618
public override bool IsSecurityCritical
{
-#if FEATURE_CORECLR
get { return true; }
-#else
- get { return RuntimeMethodHandle.IsSecurityCritical(this); }
-#endif
}
public override bool IsSecuritySafeCritical
{
-#if FEATURE_CORECLR
get { return false; }
-#else
- get { return RuntimeMethodHandle.IsSecuritySafeCritical(this); }
-#endif
}
public override bool IsSecurityTransparent
{
-#if FEATURE_CORECLR
get { return false; }
-#else
- get { return RuntimeMethodHandle.IsSecurityTransparent(this); }
-#endif
}
public override bool ContainsGenericParameters
#endregion
#region ConstructorInfo Overrides
- [System.Security.SecuritySafeCritical] // auto-generated
[DebuggerStepThroughAttribute]
[Diagnostics.DebuggerHidden]
[MethodImplAttribute(MethodImplOptions.NoInlining)] // Methods containing StackCrawlMark local var has to be marked non-inlineable
}
#endif
-#if !FEATURE_CORECLR
- if ((invocationFlags & (INVOCATION_FLAGS.INVOCATION_FLAGS_RISKY_METHOD | INVOCATION_FLAGS.INVOCATION_FLAGS_NEED_SECURITY | INVOCATION_FLAGS.INVOCATION_FLAGS_IS_DELEGATE_CTOR)) != 0)
- {
- if ((invocationFlags & INVOCATION_FLAGS.INVOCATION_FLAGS_RISKY_METHOD) != 0)
- CodeAccessPermission.Demand(PermissionType.ReflectionMemberAccess);
- if ((invocationFlags & INVOCATION_FLAGS.INVOCATION_FLAGS_NEED_SECURITY) != 0)
- RuntimeMethodHandle.PerformSecurityCheck(null, this, m_declaringType, (uint)(m_invocationFlags | INVOCATION_FLAGS.INVOCATION_FLAGS_CONSTRUCTOR_INVOKE));
- if ((invocationFlags & INVOCATION_FLAGS.INVOCATION_FLAGS_IS_DELEGATE_CTOR) != 0)
- new SecurityPermission(SecurityPermissionFlag.UnmanagedCode).Demand();
- }
-#endif // !FEATURE_CORECLR
-
// get the signature
Signature sig = Signature;
#endregion
#region ISerializable Implementation
- [System.Security.SecurityCritical] // auto-generated
public void GetObjectData(SerializationInfo info, StreamingContext context)
{
if (info == null)
}
#endregion
}
-
}
#endregion
#region Internal Static Members
- [System.Security.SecuritySafeCritical] // auto-generated
internal static IList<CustomAttributeData> GetCustomAttributesInternal(RuntimeType target)
{
- Contract.Assert(target != null);
+ Debug.Assert(target != null);
IList<CustomAttributeData> cad = GetCustomAttributes(target.GetRuntimeModule(), target.MetadataToken);
return Array.AsReadOnly(pca);
}
- [System.Security.SecuritySafeCritical] // auto-generated
internal static IList<CustomAttributeData> GetCustomAttributesInternal(RuntimeFieldInfo target)
{
- Contract.Assert(target != null);
+ Debug.Assert(target != null);
IList<CustomAttributeData> cad = GetCustomAttributes(target.GetRuntimeModule(), target.MetadataToken);
return Array.AsReadOnly(pca);
}
- [System.Security.SecuritySafeCritical] // auto-generated
internal static IList<CustomAttributeData> GetCustomAttributesInternal(RuntimeMethodInfo target)
{
- Contract.Assert(target != null);
+ Debug.Assert(target != null);
IList<CustomAttributeData> cad = GetCustomAttributes(target.GetRuntimeModule(), target.MetadataToken);
return Array.AsReadOnly(pca);
}
- [System.Security.SecuritySafeCritical] // auto-generated
internal static IList<CustomAttributeData> GetCustomAttributesInternal(RuntimeConstructorInfo target)
{
- Contract.Assert(target != null);
+ Debug.Assert(target != null);
return GetCustomAttributes(target.GetRuntimeModule(), target.MetadataToken);
}
- [System.Security.SecuritySafeCritical] // auto-generated
internal static IList<CustomAttributeData> GetCustomAttributesInternal(RuntimeEventInfo target)
{
- Contract.Assert(target != null);
+ Debug.Assert(target != null);
return GetCustomAttributes(target.GetRuntimeModule(), target.MetadataToken);
}
- [System.Security.SecuritySafeCritical] // auto-generated
internal static IList<CustomAttributeData> GetCustomAttributesInternal(RuntimePropertyInfo target)
{
- Contract.Assert(target != null);
+ Debug.Assert(target != null);
return GetCustomAttributes(target.GetRuntimeModule(), target.MetadataToken);
}
- [System.Security.SecuritySafeCritical] // auto-generated
internal static IList<CustomAttributeData> GetCustomAttributesInternal(RuntimeModule target)
{
- Contract.Assert(target != null);
+ Debug.Assert(target != null);
if (target.IsResource())
return new List<CustomAttributeData>();
return GetCustomAttributes(target, target.MetadataToken);
}
- [System.Security.SecuritySafeCritical] // auto-generated
internal static IList<CustomAttributeData> GetCustomAttributesInternal(RuntimeAssembly target)
{
- Contract.Assert(target != null);
+ Debug.Assert(target != null);
IList<CustomAttributeData> cad = GetCustomAttributes((RuntimeModule)target.ManifestModule, RuntimeAssembly.GetToken(target.GetNativeHandle()));
return Array.AsReadOnly(pca);
}
- [System.Security.SecuritySafeCritical] // auto-generated
internal static IList<CustomAttributeData> GetCustomAttributesInternal(RuntimeParameterInfo target)
{
- Contract.Assert(target != null);
+ Debug.Assert(target != null);
IList<CustomAttributeData> cad = GetCustomAttributes(target.GetRuntimeModule(), target.MetadataToken);
return new CustomAttributeType(encodedType, encodedArrayType, encodedEnumType, enumName);
}
- [System.Security.SecurityCritical] // auto-generated
private static IList<CustomAttributeData> GetCustomAttributes(RuntimeModule module, int tkTarget)
{
CustomAttributeRecord[] records = GetCustomAttributeRecords(module, tkTarget);
#endregion
#region Internal Static Members
- [System.Security.SecurityCritical] // auto-generated
internal unsafe static CustomAttributeRecord[] GetCustomAttributeRecords(RuntimeModule module, int targetToken)
{
MetadataImport scope = module.MetadataImport;
{
}
- [System.Security.SecuritySafeCritical] // auto-generated
private CustomAttributeData(RuntimeModule scope, CustomAttributeRecord caRecord)
{
m_scope = scope;
}
}
- [SecuritySafeCritical]
private static object EncodedValueToRawValue(long val, CustomAttributeEncoding encodedType)
{
switch (encodedType)
private static object CanonicalizeValue(object value)
{
- Contract.Assert(value != null);
+ Debug.Assert(value != null);
if (value.GetType().IsEnum)
{
internal struct CustomAttributeEncodedArgument
{
#region Parser
- [System.Security.SecurityCritical] // auto-generated
[MethodImplAttribute(MethodImplOptions.InternalCall)]
private static extern void ParseAttributeArguments(
IntPtr pCa,
ref CustomAttributeNamedParameter[] CustomAttributeTypedArgument,
RuntimeAssembly assembly);
- [System.Security.SecurityCritical] // auto-generated
internal static void ParseAttributeArguments(ConstArray attributeBlob,
ref CustomAttributeCtorParameter[] customAttributeCtorParameters,
ref CustomAttributeNamedParameter[] customAttributeNamedParameters,
throw new ArgumentNullException(nameof(customAttributeModule));
Contract.EndContractBlock();
- Contract.Assert(customAttributeCtorParameters != null);
- Contract.Assert(customAttributeNamedParameters != null);
+ Debug.Assert(customAttributeCtorParameters != null);
+ Debug.Assert(customAttributeNamedParameters != null);
if (customAttributeCtorParameters.Length != 0 || customAttributeNamedParameters.Length != 0)
{
IntPtr m_Next;
IntPtr m_Assembly;
- [System.Security.SecurityCritical] // auto-generated
[MethodImplAttribute(MethodImplOptions.InternalCall)]
public extern void Push(RuntimeAssembly assembly);
- [System.Security.SecurityCritical] // auto-generated
[MethodImplAttribute(MethodImplOptions.InternalCall)]
[ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)]
public extern void Pop();
#endregion
#region Internal Static Members
- [System.Security.SecurityCritical] // auto-generated
internal static bool IsDefined(RuntimeType type, RuntimeType caType, bool inherit)
{
Contract.Requires(type != null);
return false;
}
- [System.Security.SecuritySafeCritical] // auto-generated
internal static bool IsDefined(RuntimeMethodInfo method, RuntimeType caType, bool inherit)
{
Contract.Requires(method != null);
return false;
}
- [System.Security.SecurityCritical] // auto-generated
internal static bool IsDefined(RuntimeConstructorInfo ctor, RuntimeType caType)
{
Contract.Requires(ctor != null);
return IsCustomAttributeDefined(ctor.GetRuntimeModule(), ctor.MetadataToken, caType);
}
- [System.Security.SecurityCritical] // auto-generated
internal static bool IsDefined(RuntimePropertyInfo property, RuntimeType caType)
{
Contract.Requires(property != null);
return IsCustomAttributeDefined(property.GetRuntimeModule(), property.MetadataToken, caType);
}
- [System.Security.SecurityCritical] // auto-generated
internal static bool IsDefined(RuntimeEventInfo e, RuntimeType caType)
{
Contract.Requires(e != null);
return IsCustomAttributeDefined(e.GetRuntimeModule(), e.MetadataToken, caType);
}
- [System.Security.SecurityCritical] // auto-generated
internal static bool IsDefined(RuntimeFieldInfo field, RuntimeType caType)
{
Contract.Requires(field != null);
return IsCustomAttributeDefined(field.GetRuntimeModule(), field.MetadataToken, caType);
}
- [System.Security.SecurityCritical] // auto-generated
internal static bool IsDefined(RuntimeParameterInfo parameter, RuntimeType caType)
{
Contract.Requires(parameter != null);
return IsCustomAttributeDefined(parameter.GetRuntimeModule(), parameter.MetadataToken, caType);
}
- [System.Security.SecuritySafeCritical] // auto-generated
internal static bool IsDefined(RuntimeAssembly assembly, RuntimeType caType)
{
Contract.Requires(assembly != null);
return IsCustomAttributeDefined(assembly.ManifestModule as RuntimeModule, RuntimeAssembly.GetToken(assembly.GetNativeHandle()), caType);
}
- [System.Security.SecurityCritical] // auto-generated
internal static bool IsDefined(RuntimeModule module, RuntimeType caType)
{
Contract.Requires(module != null);
return IsCustomAttributeDefined(module, module.MetadataToken, caType);
}
- [System.Security.SecurityCritical] // auto-generated
internal static Object[] GetCustomAttributes(RuntimeType type, RuntimeType caType, bool inherit)
{
Contract.Requires(type != null);
else
{
type = type.DeclaringType as RuntimeType;
- Contract.Assert(type != null);
+ Debug.Assert(type != null);
}
}
private static bool SpecialAllowCriticalAttributes(RuntimeType type)
{
- // Types participating in Type Equivalence are always transparent.
- // See TokenSecurityDescriptor::VerifySemanticDataComputed in securitymeta.cpp.
- // Because of that we allow critical attributes applied to full trust equivalent types.
- // DeclaringType is null for global methods and fields and the global type never participates in type equivalency.
-
-#if FEATURE_CORECLR
return false;
-#else
- return type != null && type.Assembly.IsFullyTrusted && RuntimeTypeHandle.IsEquivalentType(type);
-#endif //!FEATURE_CORECLR
}
private static bool AllowCriticalCustomAttributes(MethodBase method)
return AllowCriticalCustomAttributes(parameter.DefiningMethod);
}
- [System.Security.SecurityCritical] // auto-generated
internal static Object[] GetCustomAttributes(RuntimeMethodInfo method, RuntimeType caType, bool inherit)
{
Contract.Requires(method != null);
return typedResult;
}
- [System.Security.SecuritySafeCritical] // auto-generated
internal static Object[] GetCustomAttributes(RuntimeConstructorInfo ctor, RuntimeType caType)
{
Contract.Requires(ctor != null);
return attributes;
}
- [System.Security.SecuritySafeCritical] // auto-generated
internal static Object[] GetCustomAttributes(RuntimePropertyInfo property, RuntimeType caType)
{
Contract.Requires(property != null);
return attributes;
}
- [System.Security.SecuritySafeCritical] // auto-generated
internal static Object[] GetCustomAttributes(RuntimeEventInfo e, RuntimeType caType)
{
Contract.Requires(e != null);
return attributes;
}
- [System.Security.SecuritySafeCritical] // auto-generated
internal static Object[] GetCustomAttributes(RuntimeFieldInfo field, RuntimeType caType)
{
Contract.Requires(field != null);
return attributes;
}
- [System.Security.SecuritySafeCritical] // auto-generated
internal static Object[] GetCustomAttributes(RuntimeParameterInfo parameter, RuntimeType caType)
{
Contract.Requires(parameter != null);
return attributes;
}
- [System.Security.SecuritySafeCritical] // auto-generated
internal static Object[] GetCustomAttributes(RuntimeAssembly assembly, RuntimeType caType)
{
Contract.Requires(assembly != null);
return attributes;
}
- [System.Security.SecuritySafeCritical] // auto-generated
internal static Object[] GetCustomAttributes(RuntimeModule module, RuntimeType caType)
{
Contract.Requires(module != null);
return attributes;
}
- [System.Security.SecuritySafeCritical]
internal static bool IsAttributeDefined(RuntimeModule decoratedModule, int decoratedMetadataToken, int attributeCtorToken)
{
return IsCustomAttributeDefined(decoratedModule, decoratedMetadataToken, null, attributeCtorToken, false);
}
- [System.Security.SecurityCritical] // auto-generated
private static bool IsCustomAttributeDefined(
RuntimeModule decoratedModule, int decoratedMetadataToken, RuntimeType attributeFilterType)
{
return IsCustomAttributeDefined(decoratedModule, decoratedMetadataToken, attributeFilterType, 0, false);
}
- [System.Security.SecurityCritical] // auto-generated
private static bool IsCustomAttributeDefined(
RuntimeModule decoratedModule, int decoratedMetadataToken, RuntimeType attributeFilterType, int attributeCtorToken, bool mustBeInheritable)
{
if (attributeFilterType != null)
{
- Contract.Assert(attributeCtorToken == 0);
+ Debug.Assert(attributeCtorToken == 0);
MetadataImport scope = decoratedModule.MetadataImport;
RuntimeType attributeType;
}
else
{
- Contract.Assert(attributeFilterType == null);
- Contract.Assert(!MetadataToken.IsNullToken(attributeCtorToken));
+ Debug.Assert(attributeFilterType == null);
+ Debug.Assert(!MetadataToken.IsNullToken(attributeCtorToken));
for (int i = 0; i < car.Length; i++)
{
return false;
}
- [System.Security.SecurityCritical] // auto-generated
private unsafe static object[] GetCustomAttributes(
RuntimeModule decoratedModule, int decoratedMetadataToken, int pcaCount, RuntimeType attributeFilterType, bool isDecoratedTargetSecurityTransparent)
{
return GetCustomAttributes(decoratedModule, decoratedMetadataToken, pcaCount, attributeFilterType, false, null, isDecoratedTargetSecurityTransparent);
}
- [System.Security.SecurityCritical]
private unsafe static object[] GetCustomAttributes(
RuntimeModule decoratedModule, int decoratedMetadataToken, int pcaCount,
RuntimeType attributeFilterType, bool mustBeInheritable, IList derivedAttributes, bool isDecoratedTargetSecurityTransparent)
return result;
}
- [System.Security.SecurityCritical] // auto-generated
private unsafe static bool FilterCustomAttributeRecord(
CustomAttributeRecord caRecord,
MetadataImport scope,
else
{
// We need to relax this when we add support for other types of decorated tokens.
- Contract.Assert(decoratedToken.IsModule || decoratedToken.IsAssembly,
+ Debug.Assert(decoratedToken.IsModule || decoratedToken.IsAssembly,
"The decoratedToken must be either an assembly, a module, a type, or a member.");
}
#endregion
#region Private Static Methods
- [System.Security.SecurityCritical] // auto-generated
private static bool AttributeUsageCheck(
RuntimeType attributeType, bool mustBeInheritable, object[] attributes, IList derivedAttributes)
{
return true;
}
- [System.Security.SecurityCritical] // auto-generated
internal static AttributeUsageAttribute GetAttributeUsage(RuntimeType decoratedAttribute)
{
RuntimeModule decoratedModule = decoratedAttribute.GetRuntimeModule();
#endregion
#region Private Static FCalls
- [System.Security.SecurityCritical] // auto-generated
[MethodImplAttribute(MethodImplOptions.InternalCall)]
private static extern void _ParseAttributeUsageAttribute(
IntPtr pCa, int cCa, out int targets, out bool inherited, out bool allowMultiple);
- [System.Security.SecurityCritical] // auto-generated
private static void ParseAttributeUsageAttribute(
ConstArray ca, out AttributeTargets targets, out bool inherited, out bool allowMultiple)
{
targets = (AttributeTargets)_targets;
}
- [System.Security.SecurityCritical] // auto-generated
[MethodImplAttribute(MethodImplOptions.InternalCall)]
private static unsafe extern Object _CreateCaObject(RuntimeModule pModule, IRuntimeMethodInfo pCtor, byte** ppBlob, byte* pEndBlob, int* pcNamedArgs);
- [System.Security.SecurityCritical] // auto-generated
private static unsafe Object CreateCaObject(RuntimeModule module, IRuntimeMethodInfo ctor, ref IntPtr blob, IntPtr blobEnd, out int namedArgs)
{
byte* pBlob = (byte*)blob;
return ca;
}
- [System.Security.SecurityCritical] // auto-generated
[MethodImplAttribute(MethodImplOptions.InternalCall)]
private unsafe extern static void _GetPropertyOrFieldData(
RuntimeModule pModule, byte** ppBlobStart, byte* pBlobEnd, out string name, out bool bIsProperty, out RuntimeType type, out object value);
- [System.Security.SecurityCritical] // auto-generated
private unsafe static void GetPropertyOrFieldData(
RuntimeModule module, ref IntPtr blobStart, IntPtr blobEnd, out string name, out bool isProperty, out RuntimeType type, out object value)
{
blobStart = (IntPtr)pBlobStart;
}
- [System.Security.SecuritySafeCritical]
private static object[] CreateAttributeArrayHelper(Type elementType, int elementCount)
{
return (object[])Array.UnsafeCreateInstance(elementType, elementCount);
#endregion
#region FCalls
-#if FEATURE_CAS_POLICY
- [System.Security.SecurityCritical] // auto-generated
- [MethodImplAttribute(MethodImplOptions.InternalCall)]
- unsafe private static extern void _GetSecurityAttributes(RuntimeModule module, int token, bool assembly, out object[] securityAttributes);
- [System.Security.SecurityCritical] // auto-generated
- unsafe internal static void GetSecurityAttributes(RuntimeModule module, int token, bool assembly, out object[] securityAttributes)
- {
- _GetSecurityAttributes(module.GetNativeHandle(), token, assembly, out securityAttributes);
- }
-#else
internal static void GetSecurityAttributes(RuntimeModule module, int token, bool assembly, out object[] securityAttributes)
{
securityAttributes = null;
}
-#endif
#endregion
#region Static Constructor
- [System.Security.SecurityCritical] // auto-generated
static PseudoCustomAttribute()
{
RuntimeType[] pcas = new RuntimeType[]
s_pca = temp_pca;
}
- [System.Security.SecurityCritical] // auto-generated
[Conditional("_DEBUG")]
private static void VerifyPseudoCustomAttribute(RuntimeType pca)
{
// If any of these are invariants are no longer true will have to
// re-architect the PCA product logic and test cases -- you've been warned!
- Contract.Assert(pca.BaseType == (RuntimeType)typeof(Attribute), "Pseudo CA Error");
+ Debug.Assert(pca.BaseType == (RuntimeType)typeof(Attribute), "Pseudo CA Error");
AttributeUsageAttribute usage = CustomAttribute.GetAttributeUsage(pca);
- Contract.Assert(usage.Inherited == false, "Pseudo CA Error");
+ Debug.Assert(usage.Inherited == false, "Pseudo CA Error");
//AllowMultiple is true for TypeForwardedToAttribute
- //Contract.Assert(usage.AllowMultiple == false, "Pseudo CA Error");
+ //Debug.Assert(usage.AllowMultiple == false, "Pseudo CA Error");
}
#endregion
#pragma warning restore 618
}
- [System.Security.SecurityCritical] // auto-generated
internal static Attribute[] GetCustomAttributes(RuntimeType type, RuntimeType caType, bool includeSecCa, out int count)
{
Contract.Requires(type != null);
count = pcas.Count;
return pcas.ToArray();
}
- [System.Security.SecurityCritical] // auto-generated
internal static bool IsDefined(RuntimeType type, RuntimeType caType)
{
bool all = caType == (RuntimeType)typeof(object) || caType == (RuntimeType)typeof(Attribute);
return false;
}
- [System.Security.SecurityCritical] // auto-generated
internal static Attribute[] GetCustomAttributes(RuntimeMethodInfo method, RuntimeType caType, bool includeSecCa, out int count)
{
Contract.Requires(method != null);
count = pcas.Count;
return pcas.ToArray();
}
- [System.Security.SecurityCritical] // auto-generated
internal static bool IsDefined(RuntimeMethodInfo method, RuntimeType caType)
{
bool all = caType == (RuntimeType)typeof(object) || caType == (RuntimeType)typeof(Attribute);
return false;
}
- [System.Security.SecurityCritical] // auto-generated
internal static Attribute[] GetCustomAttributes(RuntimeParameterInfo parameter, RuntimeType caType, out int count)
{
Contract.Requires(parameter != null);
}
return pcas;
}
- [System.Security.SecurityCritical] // auto-generated
internal static bool IsDefined(RuntimeParameterInfo parameter, RuntimeType caType)
{
bool all = caType == (RuntimeType)typeof(object) || caType == (RuntimeType)typeof(Attribute);
return false;
}
- [System.Security.SecurityCritical] // auto-generated
internal static Attribute[] GetCustomAttributes(RuntimeAssembly assembly, RuntimeType caType, bool includeSecCa, out int count)
{
count = 0;
count = pcas.Count;
return pcas.ToArray();
}
- [System.Security.SecurityCritical] // auto-generated
internal static bool IsDefined(RuntimeAssembly assembly, RuntimeType caType)
{
int count;
return false;
}
- [System.Security.SecurityCritical] // auto-generated
internal static Attribute[] GetCustomAttributes(RuntimeFieldInfo field, RuntimeType caType, out int count)
{
Contract.Requires(field != null);
}
return pcas;
}
- [System.Security.SecurityCritical] // auto-generated
internal static bool IsDefined(RuntimeFieldInfo field, RuntimeType caType)
{
bool all = caType == (RuntimeType)typeof(object) || caType == (RuntimeType)typeof(Attribute);
return false;
}
- [System.Security.SecurityCritical] // auto-generated
internal static Attribute[] GetCustomAttributes(RuntimeConstructorInfo ctor, RuntimeType caType, bool includeSecCa, out int count)
{
count = 0;
count = pcas.Count;
return pcas.ToArray();
}
- [System.Security.SecurityCritical] // auto-generated
internal static bool IsDefined(RuntimeConstructorInfo ctor, RuntimeType caType)
{
bool all = caType == (RuntimeType)typeof(object) || caType == (RuntimeType)typeof(Attribute);
}
#region QCalls
- [System.Security.SecurityCritical] // auto-generated
[DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
[SuppressUnmanagedCodeSecurity]
private static extern IntPtr CreateTypeNameBuilder();
- [System.Security.SecurityCritical] // auto-generated
[DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
[SuppressUnmanagedCodeSecurity]
private static extern void ReleaseTypeNameBuilder(IntPtr pAQN);
- [System.Security.SecurityCritical] // auto-generated
[DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
[SuppressUnmanagedCodeSecurity]
private static extern void OpenGenericArguments(IntPtr tnb);
- [System.Security.SecurityCritical] // auto-generated
[DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
[SuppressUnmanagedCodeSecurity]
private static extern void CloseGenericArguments(IntPtr tnb);
- [System.Security.SecurityCritical] // auto-generated
[DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
[SuppressUnmanagedCodeSecurity]
private static extern void OpenGenericArgument(IntPtr tnb);
- [System.Security.SecurityCritical] // auto-generated
[DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
[SuppressUnmanagedCodeSecurity]
private static extern void CloseGenericArgument(IntPtr tnb);
- [System.Security.SecurityCritical] // auto-generated
[DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
[SuppressUnmanagedCodeSecurity]
private static extern void AddName(IntPtr tnb, string name);
- [System.Security.SecurityCritical] // auto-generated
[DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
[SuppressUnmanagedCodeSecurity]
private static extern void AddPointer(IntPtr tnb);
- [System.Security.SecurityCritical] // auto-generated
[DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
[SuppressUnmanagedCodeSecurity]
private static extern void AddByRef(IntPtr tnb);
- [System.Security.SecurityCritical] // auto-generated
[DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
[SuppressUnmanagedCodeSecurity]
private static extern void AddSzArray(IntPtr tnb);
- [System.Security.SecurityCritical] // auto-generated
[DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
[SuppressUnmanagedCodeSecurity]
private static extern void AddArray(IntPtr tnb, int rank);
- [System.Security.SecurityCritical] // auto-generated
[DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
[SuppressUnmanagedCodeSecurity]
private static extern void AddAssemblySpec(IntPtr tnb, string assemblySpec);
- [System.Security.SecurityCritical] // auto-generated
[DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
[SuppressUnmanagedCodeSecurity]
private static extern void ToString(IntPtr tnb, StringHandleOnStack retString);
- [System.Security.SecurityCritical] // auto-generated
[DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
[SuppressUnmanagedCodeSecurity]
private static extern void Clear(IntPtr tnb);
#region Static Members
// TypeNameBuilder is NOT thread safe NOR reliable
- [System.Security.SecuritySafeCritical] // auto-generated
internal static string ToString(Type type, Format format)
{
if (format == Format.FullName || format == Format.AssemblyQualifiedName)
#region Constructor
private TypeNameBuilder(IntPtr typeNameBuilder) { m_typeNameBuilder = typeNameBuilder; }
- [System.Security.SecurityCritical] // auto-generated
internal void Dispose() { ReleaseTypeNameBuilder(m_typeNameBuilder); }
#endregion
#region private Members
- [System.Security.SecurityCritical] // auto-generated
private void AddElementType(Type elementType)
{
if (elementType.HasElementType)
AddArray(elementType.GetArrayRank());
}
- [System.Security.SecurityCritical] // auto-generated
private void ConstructAssemblyQualifiedNameWorker(Type type, Format format)
{
Type rootType = type;
AddAssemblySpec(type.Module.Assembly.FullName);
}
- [System.Security.SecurityCritical] // auto-generated
private void OpenGenericArguments() { OpenGenericArguments(m_typeNameBuilder); }
- [System.Security.SecurityCritical] // auto-generated
private void CloseGenericArguments() { CloseGenericArguments(m_typeNameBuilder); }
- [System.Security.SecurityCritical] // auto-generated
private void OpenGenericArgument() { OpenGenericArgument(m_typeNameBuilder); }
- [System.Security.SecurityCritical] // auto-generated
private void CloseGenericArgument() { CloseGenericArgument(m_typeNameBuilder); }
- [System.Security.SecurityCritical] // auto-generated
private void AddName(string name) { AddName(m_typeNameBuilder, name); }
- [System.Security.SecurityCritical] // auto-generated
private void AddPointer() { AddPointer(m_typeNameBuilder); }
- [System.Security.SecurityCritical] // auto-generated
private void AddByRef() { AddByRef(m_typeNameBuilder); }
- [System.Security.SecurityCritical] // auto-generated
private void AddSzArray() { AddSzArray(m_typeNameBuilder); }
- [System.Security.SecurityCritical] // auto-generated
private void AddArray(int rank) { AddArray(m_typeNameBuilder, rank); }
- [System.Security.SecurityCritical] // auto-generated
private void AddAssemblySpec(string assemblySpec) { AddAssemblySpec(m_typeNameBuilder, assemblySpec); }
- [System.Security.SecuritySafeCritical] // auto-generated
public override string ToString() { string ret = null; ToString(m_typeNameBuilder, JitHelpers.GetStringHandleOnStack(ref ret)); return ret; }
- [System.Security.SecurityCritical] // auto-generated
private void Clear() { Clear(m_typeNameBuilder); }
#endregion
}
throw new NotSupportedException(Environment.GetResourceString("NotSupported_DynamicAssembly"));
}
- #if FEATURE_CORECLR
- [System.Security.SecurityCritical] // auto-generated
- #endif
public override FileStream GetFile(String name)
{
throw new NotSupportedException(Environment.GetResourceString("NotSupported_DynamicAssembly"));
}
- #if FEATURE_CORECLR
- [System.Security.SecurityCritical] // auto-generated
- #endif
public override FileStream[] GetFiles(bool getResourceModules)
{
throw new NotSupportedException(Environment.GetResourceString("NotSupported_DynamicAssembly"));
public override String Location
{
-#if FEATURE_CORECLR
- [SecurityCritical]
-#endif // FEATURE_CORECLR
get
{
throw new NotSupportedException(Environment.GetResourceString("NotSupported_DynamicAssembly"));
public override String CodeBase
{
-#if FEATURE_CORECLR
- [SecurityCritical]
-#endif // FEATURE_CORECLR
get
{
throw new NotSupportedException(Environment.GetResourceString("NotSupported_DynamicAssembly"));
// AssemblyBuilder class.
// deliberately not [serializable]
- [HostProtection(MayLeakOnAbort = true)]
[ClassInterface(ClassInterfaceType.None)]
[ComDefaultInterface(typeof(_AssemblyBuilder))]
[ComVisible(true)]
public sealed class AssemblyBuilder : Assembly, _AssemblyBuilder
{
#region FCALL
- [System.Security.SecurityCritical] // auto-generated
[MethodImplAttribute(MethodImplOptions.InternalCall)]
private static extern RuntimeModule GetInMemoryAssemblyModule(RuntimeAssembly assembly);
- [System.Security.SecurityCritical] // auto-generated
private Module nGetInMemoryAssemblyModule()
{
return AssemblyBuilder.GetInMemoryAssemblyModule(GetNativeHandle());
}
-#if !FEATURE_CORECLR
- [System.Security.SecurityCritical] // auto-generated
- [MethodImplAttribute(MethodImplOptions.InternalCall)]
- private static extern RuntimeModule GetOnDiskAssemblyModule(RuntimeAssembly assembly);
-
- [System.Security.SecurityCritical] // auto-generated
- private ModuleBuilder GetOnDiskAssemblyModuleBuilder()
- {
- if (m_onDiskAssemblyModuleBuilder == null)
- {
- Module module = AssemblyBuilder.GetOnDiskAssemblyModule(InternalAssembly.GetNativeHandle());
- ModuleBuilder modBuilder = new ModuleBuilder(this, (InternalModuleBuilder)module);
- modBuilder.Init("RefEmit_OnDiskManifestModule", null, 0);
- m_onDiskAssemblyModuleBuilder = modBuilder;
- }
-
- return m_onDiskAssemblyModuleBuilder;
- }
-#endif // FEATURE_CORECLR
-
#endregion
#region Internal Data Members
// Set to true if the manifest module was returned by code:DefineDynamicModule to the user
private bool m_fManifestModuleUsedAsDefinedModule;
internal const string MANIFEST_MODULE_NAME = "RefEmit_InMemoryManifestModule";
-#if !FEATURE_CORECLR
- private ModuleBuilder m_onDiskAssemblyModuleBuilder;
-#endif // !FEATURE_CORECLR
#if FEATURE_APPX
private bool m_profileAPICheck;
internal ModuleBuilder GetModuleBuilder(InternalModuleBuilder module)
{
Contract.Requires(module != null);
- Contract.Assert(this.InternalAssembly == module.Assembly);
+ Debug.Assert(this.InternalAssembly == module.Assembly);
lock(SyncRoot)
{
-#if !FEATURE_CORECLR
- foreach (ModuleBuilder modBuilder in m_assemblyData.m_moduleBuilderList)
- {
- if (modBuilder.InternalModule == module)
- return modBuilder;
- }
-
- // m_onDiskAssemblyModuleBuilder is null before Save
- if (m_onDiskAssemblyModuleBuilder != null && m_onDiskAssemblyModuleBuilder.InternalModule == module)
- return m_onDiskAssemblyModuleBuilder;
-#endif // !FEATURE_CORECLR
-
// in CoreCLR there is only one module in each dynamic assembly, the manifest module
if (m_manifestModuleBuilder.InternalModule == module)
return m_manifestModuleBuilder;
return InternalAssembly.GetNativeHandle();
}
- [SecurityCritical]
internal Version GetVersion()
{
return InternalAssembly.GetVersion();
#endregion
#region Constructor
- [System.Security.SecurityCritical] // auto-generated
internal AssemblyBuilder(AppDomain domain,
AssemblyName name,
AssemblyBuilderAccess access,
throw new ArgumentNullException(nameof(name));
if (access != AssemblyBuilderAccess.Run
-#if !FEATURE_CORECLR
- && access != AssemblyBuilderAccess.Save
- && access != AssemblyBuilderAccess.RunAndSave
-#endif // !FEATURE_CORECLR
#if FEATURE_REFLECTION_ONLY_LOAD
&& access != AssemblyBuilderAccess.ReflectionOnly
#endif // FEATURE_REFLECTION_ONLY_LOAD
// Clone the name in case the caller modifies it underneath us.
name = (AssemblyName)name.Clone();
-
-#if !FEATURE_CORECLR
- // Set the public key from the key pair if one has been provided.
- // (Overwite any public key in the Assembly name, since it's no
- // longer valid to have a disparity).
- if (name.KeyPair != null)
- name.SetPublicKey(name.KeyPair.PublicKey);
-#endif
// If the caller is trusted they can supply identity
// evidence for the new assembly. Otherwise we copy the
new SecurityPermission(SecurityPermissionFlag.ControlEvidence).Demand();
#pragma warning restore 618
-#if FEATURE_COLLECTIBLE_TYPES && !FEATURE_CORECLR
- // Collectible assemblies require FullTrust. This demand may be removed if we deem the
- // feature robust enough to be used directly by untrusted API consumers.
- if (access == AssemblyBuilderAccess.RunAndCollect)
- new PermissionSet(PermissionState.Unrestricted).Demand();
-#endif // FEATURE_COLLECTIBLE_TYPES && !FEATURE_CORECLR
-
// Scan the assembly level attributes for any attributes which modify how we create the
// assembly. Currently, we look for any attribute which modifies the security transparency
// of the assembly.
}
}
- [System.Security.SecurityCritical] // auto-generated
private void InitManifestModule()
{
InternalModuleBuilder modBuilder = (InternalModuleBuilder)nGetInMemoryAssemblyModule();
* to have a strong name and a hash will be computed when the assembly
* is saved.
**********************************************/
- [System.Security.SecuritySafeCritical] // auto-generated
[MethodImplAttribute(MethodImplOptions.NoInlining)] // Methods containing StackCrawlMark local var has to be marked non-inlineable
public static AssemblyBuilder DefineDynamicAssembly(
AssemblyName name,
null, null, null, null, ref stackMark, null, SecurityContextSource.CurrentAssembly);
}
- [System.Security.SecuritySafeCritical] // auto-generated
[MethodImplAttribute(MethodImplOptions.NoInlining)] // Methods containing StackCrawlMark local var has to be marked non-inlineable
public static AssemblyBuilder DefineDynamicAssembly(
AssemblyName name,
}
- [System.Security.SecurityCritical] // auto-generated
[MethodImplAttribute(MethodImplOptions.InternalCall)]
private static extern Assembly nCreateDynamicAssembly(AppDomain domain,
AssemblyName name,
private class AssemblyBuilderLock { }
- [System.Security.SecurityCritical] // auto-generated
internal static AssemblyBuilder InternalDefineDynamicAssembly(
AssemblyName name,
AssemblyBuilderAccess access,
IEnumerable<CustomAttributeBuilder> unsafeAssemblyAttributes,
SecurityContextSource securityContextSource)
{
-#if FEATURE_CAS_POLICY
- if (evidence != null && !AppDomain.CurrentDomain.IsLegacyCasPolicyEnabled)
- {
- throw new NotSupportedException(Environment.GetResourceString("NotSupported_RequiresCasPolicyExplicit"));
- }
-#endif // FEATURE_CAS_POLICY
-
lock (typeof(AssemblyBuilderLock))
{
// we can only create dynamic assemblies in the current domain
* a transient module.
*
**********************************************/
- [System.Security.SecuritySafeCritical] // auto-generated
[MethodImplAttribute(MethodImplOptions.NoInlining)] // Methods containing StackCrawlMark local var has to be marked non-inlineable
public ModuleBuilder DefineDynamicModule(
String name)
return DefineDynamicModuleInternal(name, false, ref stackMark);
}
- [System.Security.SecuritySafeCritical] // auto-generated
[MethodImplAttribute(MethodImplOptions.NoInlining)] // Methods containing StackCrawlMark local var has to be marked non-inlineable
public ModuleBuilder DefineDynamicModule(
String name,
return DefineDynamicModuleInternal( name, emitSymbolInfo, ref stackMark );
}
- [System.Security.SecurityCritical] // auto-generated
private ModuleBuilder DefineDynamicModuleInternal(
String name,
bool emitSymbolInfo, // specify if emit symbol info or not
}
}
- [System.Security.SecurityCritical] // auto-generated
private ModuleBuilder DefineDynamicModuleInternalNoLock(
String name,
bool emitSymbolInfo, // specify if emit symbol info or not
BCLDebug.Log("DYNIL", "## DYNIL LOGGING: AssemblyBuilder.DefineDynamicModule( " + name + " )");
- Contract.Assert(m_assemblyData != null, "m_assemblyData is null in DefineDynamicModuleInternal");
+ Debug.Assert(m_assemblyData != null, "m_assemblyData is null in DefineDynamicModuleInternal");
ModuleBuilder dynModule;
ISymbolWriter writer = null;
}
}
-#if !FEATURE_CORECLR
- /**********************************************
- *
- * Define stand alone managed resource for Assembly
- *
- **********************************************/
- public IResourceWriter DefineResource(
- String name,
- String description,
- String fileName)
- {
- return DefineResource(name, description, fileName, ResourceAttributes.Public);
- }
-
- /**********************************************
- *
- * Define stand alone managed resource for Assembly
- *
- **********************************************/
- public IResourceWriter DefineResource(
- String name,
- String description,
- String fileName,
- ResourceAttributes attribute)
- {
- lock(SyncRoot)
- {
- return DefineResourceNoLock(name, description, fileName, attribute);
- }
- }
-
- private IResourceWriter DefineResourceNoLock(
- String name,
- String description,
- String fileName,
- ResourceAttributes attribute)
- {
- if (name == null)
- throw new ArgumentNullException(nameof(name));
- if (name.Length == 0)
- throw new ArgumentException(Environment.GetResourceString("Argument_EmptyName"), name);
- if (fileName == null)
- throw new ArgumentNullException(nameof(fileName));
- if (fileName.Length == 0)
- throw new ArgumentException(Environment.GetResourceString("Argument_EmptyFileName"), nameof(fileName));
- if (!String.Equals(fileName, Path.GetFileName(fileName)))
- throw new ArgumentException(Environment.GetResourceString("Argument_NotSimpleFileName"), nameof(fileName));
- Contract.EndContractBlock();
-
- BCLDebug.Log("DYNIL", "## DYNIL LOGGING: AssemblyBuilder.DefineResource( " + name + ", " + fileName + ")");
-
- m_assemblyData.CheckResNameConflict(name);
- m_assemblyData.CheckFileNameConflict(fileName);
-
- ResourceWriter resWriter;
- String fullFileName;
-
- if (m_assemblyData.m_strDir == null)
- {
- // If assembly directory is null, use current directory
- fullFileName = Path.Combine(Directory.GetCurrentDirectory(), fileName);
- resWriter = new ResourceWriter(fullFileName);
- }
- else
- {
- // Form the full path given the directory provided by user
- fullFileName = Path.Combine(m_assemblyData.m_strDir, fileName);
- resWriter = new ResourceWriter(fullFileName);
- }
- // get the full path
- fullFileName = Path.GetFullPath(fullFileName);
-
- // retrieve just the file name
- fileName = Path.GetFileName(fullFileName);
-
- m_assemblyData.AddResWriter( new ResWriterData( resWriter, null, name, fileName, fullFileName, attribute) );
- return resWriter;
- }
-
- /**********************************************
- *
- * Add an existing resource file to the Assembly
- *
- **********************************************/
- public void AddResourceFile(
- String name,
- String fileName)
- {
- AddResourceFile(name, fileName, ResourceAttributes.Public);
- }
-
- /**********************************************
- *
- * Add an existing resource file to the Assembly
- *
- **********************************************/
- public void AddResourceFile(
- String name,
- String fileName,
- ResourceAttributes attribute)
- {
- lock(SyncRoot)
- {
- AddResourceFileNoLock(name, fileName, attribute);
- }
- }
-
- [System.Security.SecuritySafeCritical]
- private void AddResourceFileNoLock(
- String name,
- String fileName,
- ResourceAttributes attribute)
- {
- if (name == null)
- throw new ArgumentNullException(nameof(name));
- if (name.Length == 0)
- throw new ArgumentException(Environment.GetResourceString("Argument_EmptyName"), name);
- if (fileName == null)
- throw new ArgumentNullException(nameof(fileName));
- if (fileName.Length == 0)
- throw new ArgumentException(Environment.GetResourceString("Argument_EmptyFileName"), fileName);
- if (!String.Equals(fileName, Path.GetFileName(fileName)))
- throw new ArgumentException(Environment.GetResourceString("Argument_NotSimpleFileName"), nameof(fileName));
- Contract.EndContractBlock();
-
- BCLDebug.Log("DYNIL", "## DYNIL LOGGING: AssemblyBuilder.AddResourceFile( " + name + ", " + fileName + ")");
-
- m_assemblyData.CheckResNameConflict(name);
- m_assemblyData.CheckFileNameConflict(fileName);
-
- String fullFileName;
-
- if (m_assemblyData.m_strDir == null)
- {
- // If assembly directory is null, use current directory
- fullFileName = Path.Combine(Directory.GetCurrentDirectory(), fileName);
- }
- else
- {
- // Form the full path given the directory provided by user
- fullFileName = Path.Combine(m_assemblyData.m_strDir, fileName);
- }
-
- // get the full path
- fullFileName = Path.UnsafeGetFullPath(fullFileName);
-
- // retrieve just the file name
- fileName = Path.GetFileName(fullFileName);
-
- if (File.UnsafeExists(fullFileName) == false)
- throw new FileNotFoundException(Environment.GetResourceString(
- "IO.FileNotFound_FileName",
- fileName), fileName);
- m_assemblyData.AddResWriter( new ResWriterData( null, null, name, fileName, fullFileName, attribute) );
- }
-#endif // !FEATURE_CORECLR
-
#region object overrides
public override bool Equals(object obj)
{
return InternalAssembly.GetManifestResourceNames();
}
- #if FEATURE_CORECLR
- [System.Security.SecurityCritical] // auto-generated
- #endif
public override FileStream GetFile(String name)
{
return InternalAssembly.GetFile(name);
}
- #if FEATURE_CORECLR
- [System.Security.SecurityCritical] // auto-generated
- #endif
public override FileStream[] GetFiles(bool getResourceModules)
{
return InternalAssembly.GetFiles(getResourceModules);
public override String Location
{
- #if FEATURE_CORECLR
- [System.Security.SecurityCritical] // auto-generated
- #endif
get
{
return InternalAssembly.Location;
public override String CodeBase
{
- #if FEATURE_CORECLR
- [System.Security.SecurityCritical] // auto-generated
- #endif
get
{
return InternalAssembly.CodeBase;
return InternalAssembly.GetExportedTypes();
}
- #if FEATURE_CORECLR
- [System.Security.SecurityCritical] // auto-generated
- #endif
public override AssemblyName GetName(bool copiedName)
{
return InternalAssembly.GetName(copiedName);
return InternalAssembly.GetType(name, throwOnError, ignoreCase);
}
-#if FEATURE_CAS_POLICY
- public override Evidence Evidence
- {
- get
- {
- return InternalAssembly.Evidence;
- }
- }
-
- public override PermissionSet PermissionSet
- {
- [SecurityCritical]
- get
- {
- return InternalAssembly.PermissionSet;
- }
- }
-
- public override SecurityRuleSet SecurityRuleSet
- {
- get
- {
- return InternalAssembly.SecurityRuleSet;
- }
- }
-#endif // FEATURE_CAS_POLICY
-
public override Module ManifestModule
{
get
#endregion
-#if !FEATURE_CORECLR
- /**********************************************
- *
- * Add an unmanaged Version resource to the
- * assembly
- *
- **********************************************/
- public void DefineVersionInfoResource(
- String product,
- String productVersion,
- String company,
- String copyright,
- String trademark)
- {
- lock(SyncRoot)
- {
- DefineVersionInfoResourceNoLock(
- product,
- productVersion,
- company,
- copyright,
- trademark);
- }
- }
-
- private void DefineVersionInfoResourceNoLock(
- String product,
- String productVersion,
- String company,
- String copyright,
- String trademark)
- {
- if (m_assemblyData.m_strResourceFileName != null ||
- m_assemblyData.m_resourceBytes != null ||
- m_assemblyData.m_nativeVersion != null)
- throw new ArgumentException(Environment.GetResourceString("Argument_NativeResourceAlreadyDefined"));
-
- m_assemblyData.m_nativeVersion = new NativeVersionInfo();
-
- m_assemblyData.m_nativeVersion.m_strCopyright = copyright;
- m_assemblyData.m_nativeVersion.m_strTrademark = trademark;
- m_assemblyData.m_nativeVersion.m_strCompany = company;
- m_assemblyData.m_nativeVersion.m_strProduct = product;
- m_assemblyData.m_nativeVersion.m_strProductVersion = productVersion;
- m_assemblyData.m_hasUnmanagedVersionInfo = true;
- m_assemblyData.m_OverrideUnmanagedVersionInfo = true;
-
- }
-
- public void DefineVersionInfoResource()
- {
- lock(SyncRoot)
- {
- DefineVersionInfoResourceNoLock();
- }
- }
-
- private void DefineVersionInfoResourceNoLock()
- {
- if (m_assemblyData.m_strResourceFileName != null ||
- m_assemblyData.m_resourceBytes != null ||
- m_assemblyData.m_nativeVersion != null)
- throw new ArgumentException(Environment.GetResourceString("Argument_NativeResourceAlreadyDefined"));
-
- m_assemblyData.m_hasUnmanagedVersionInfo = true;
- m_assemblyData.m_nativeVersion = new NativeVersionInfo();
- }
-
- public void DefineUnmanagedResource(Byte[] resource)
- {
- if (resource == null)
- throw new ArgumentNullException(nameof(resource));
- Contract.EndContractBlock();
-
- lock(SyncRoot)
- {
- DefineUnmanagedResourceNoLock(resource);
- }
- }
-
- private void DefineUnmanagedResourceNoLock(Byte[] resource)
- {
- if (m_assemblyData.m_strResourceFileName != null ||
- m_assemblyData.m_resourceBytes != null ||
- m_assemblyData.m_nativeVersion != null)
- throw new ArgumentException(Environment.GetResourceString("Argument_NativeResourceAlreadyDefined"));
-
- m_assemblyData.m_resourceBytes = new byte[resource.Length];
- Buffer.BlockCopy(resource, 0, m_assemblyData.m_resourceBytes, 0, resource.Length);
- }
-
- [System.Security.SecuritySafeCritical] // auto-generated
- public void DefineUnmanagedResource(String resourceFileName)
- {
- if (resourceFileName == null)
- throw new ArgumentNullException(nameof(resourceFileName));
- Contract.EndContractBlock();
-
- lock(SyncRoot)
- {
- DefineUnmanagedResourceNoLock(resourceFileName);
- }
- }
-
- [System.Security.SecurityCritical] // auto-generated
- private void DefineUnmanagedResourceNoLock(String resourceFileName)
- {
- if (m_assemblyData.m_strResourceFileName != null ||
- m_assemblyData.m_resourceBytes != null ||
- m_assemblyData.m_nativeVersion != null)
- throw new ArgumentException(Environment.GetResourceString("Argument_NativeResourceAlreadyDefined"));
-
- // Check caller has the right to read the file.
- string strFullFileName;
- if (m_assemblyData.m_strDir == null)
- {
- // If assembly directory is null, use current directory
- strFullFileName = Path.Combine(Directory.GetCurrentDirectory(), resourceFileName);
- }
- else
- {
- // Form the full path given the directory provided by user
- strFullFileName = Path.Combine(m_assemblyData.m_strDir, resourceFileName);
- }
- strFullFileName = Path.GetFullPath(resourceFileName);
- new FileIOPermission(FileIOPermissionAccess.Read, strFullFileName).Demand();
-
- if (File.Exists(strFullFileName) == false)
- throw new FileNotFoundException(Environment.GetResourceString(
- "IO.FileNotFound_FileName",
- resourceFileName), resourceFileName);
- m_assemblyData.m_strResourceFileName = strFullFileName;
- }
-#endif // !FEATURE_CORECLR
-
-
/**********************************************
*
* return a dynamic module with the specified name.
* an exe.
*
**********************************************/
- #if FEATURE_CORECLR
- [System.Security.SecurityCritical] // auto-generated
- #endif
public void SetEntryPoint(
MethodInfo entryMethod)
{
SetEntryPoint(entryMethod, PEFileKinds.ConsoleApplication);
}
- #if FEATURE_CORECLR
- [System.Security.SecurityCritical] // auto-generated
- #endif
public void SetEntryPoint(
MethodInfo entryMethod, // entry method for the assembly. We use this to determine the entry module
PEFileKinds fileKind) // file kind for the assembly.
m_assemblyData.m_entryPointMethod = entryMethod;
m_assemblyData.m_peFileKind = fileKind;
-
-#if !FEATURE_CORECLR
- // Setting the entry point
- ModuleBuilder tmpMB = tmpModule as ModuleBuilder;
- if (tmpMB != null)
- m_assemblyData.m_entryPointModule = tmpMB;
- else
- m_assemblyData.m_entryPointModule = GetModuleBuilder((InternalModuleBuilder)tmpModule);
-
- MethodToken entryMethodToken = m_assemblyData.m_entryPointModule.GetMethodToken(entryMethod);
- m_assemblyData.m_entryPointModule.SetEntryPoint(entryMethodToken);
-#endif //!FEATURE_CORECLR
}
/**********************************************
* Use this function if client decides to form the custom attribute blob themselves
**********************************************/
- #if FEATURE_CORECLR
- [System.Security.SecurityCritical] // auto-generated
- #else
- [System.Security.SecuritySafeCritical]
- #endif
[System.Runtime.InteropServices.ComVisible(true)]
public void SetCustomAttribute(ConstructorInfo con, byte[] binaryAttribute)
{
}
}
- [System.Security.SecurityCritical] // auto-generated
private void SetCustomAttributeNoLock(ConstructorInfo con, byte[] binaryAttribute)
{
TypeBuilder.DefineCustomAttribute(
/**********************************************
* Use this function if client wishes to build CustomAttribute using CustomAttributeBuilder
**********************************************/
- [System.Security.SecuritySafeCritical] // auto-generated
public void SetCustomAttribute(CustomAttributeBuilder customBuilder)
{
if (customBuilder == null)
}
}
- [System.Security.SecurityCritical] // auto-generated
private void SetCustomAttributeNoLock(CustomAttributeBuilder customBuilder)
{
customBuilder.CreateCustomAttribute(
Save(assemblyFileName, System.Reflection.PortableExecutableKinds.ILOnly, System.Reflection.ImageFileMachine.I386);
}
- [System.Security.SecuritySafeCritical] // auto-generated
public void Save(String assemblyFileName,
PortableExecutableKinds portableExecutableKind, ImageFileMachine imageFileMachine)
{
}
}
-#if FEATURE_CORECLR
private void SaveNoLock(String assemblyFileName,
PortableExecutableKinds portableExecutableKind, ImageFileMachine imageFileMachine)
{
- // AssemblyBuilderAccess.Save can never be set with FEATURE_CORECLR
+ // AssemblyBuilderAccess.Save can never be set in CoreCLR
throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_CantSaveTransientAssembly"));
}
-#else // FEATURE_CORECLR
- [System.Security.SecurityCritical] // auto-generated
- private void SaveNoLock(String assemblyFileName,
- PortableExecutableKinds portableExecutableKind, ImageFileMachine imageFileMachine)
- {
- if (assemblyFileName == null)
- throw new ArgumentNullException(nameof(assemblyFileName));
- if (assemblyFileName.Length == 0)
- throw new ArgumentException(Environment.GetResourceString("Argument_EmptyFileName"), nameof(assemblyFileName));
- if (!String.Equals(assemblyFileName, Path.GetFileName(assemblyFileName)))
- throw new ArgumentException(Environment.GetResourceString("Argument_NotSimpleFileName"), nameof(assemblyFileName));
- Contract.EndContractBlock();
-
- int i;
- int size;
- Type type;
- TypeBuilder typeBuilder;
- ModuleBuilder modBuilder;
- String strModFileName;
- ModuleBuilder assemblyModule;
- ResWriterData tempRes;
- int[] tkAttrs = null;
- int[] tkAttrs2 = null;
- ModuleBuilder onDiskAssemblyModule;
- BCLDebug.Log("DYNIL","## DYNIL LOGGING: AssemblyBuilder.Save( " + assemblyFileName + " )");
-
- String tmpVersionFile = null;
-
- try
- {
- if (m_assemblyData.m_iCABuilder != 0)
- tkAttrs = new int[m_assemblyData.m_iCABuilder];
- if ( m_assemblyData.m_iCAs != 0)
- tkAttrs2 = new int[m_assemblyData.m_iCAs];
-
- if (m_assemblyData.m_isSaved == true)
- {
- // assembly has been saved before!
- throw new InvalidOperationException(Environment.GetResourceString(ResId.InvalidOperation_AssemblyHasBeenSaved,
- InternalAssembly.GetSimpleName()));
- }
-
- if ((m_assemblyData.m_access & AssemblyBuilderAccess.Save) != AssemblyBuilderAccess.Save)
- {
- throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_CantSaveTransientAssembly"));
- }
-
- // Check if assembly info is supposed to be stored with one of the module files.
- assemblyModule = m_assemblyData.FindModuleWithFileName(assemblyFileName);
-
- if (assemblyModule != null)
- {
- m_onDiskAssemblyModuleBuilder = assemblyModule;
-
- // In memory this module is not the manifest module and has a valid file token
- // On disk it will be the manifest module so lets clean the file token
- // We should not retrieve FileToken after the assembly has been saved
- // If that is absolutely necessary, we need two separate fields on ModuleBuilderData:
- // the in memory file token and the on disk file token.
- assemblyModule.m_moduleData.FileToken = 0;
- }
- else
- { // If assembly is to be stored alone, then no file name should conflict with it.
- // This check will ensure resource file names are different assembly file name.
- m_assemblyData.CheckFileNameConflict(assemblyFileName);
- }
-
- if (m_assemblyData.m_strDir == null)
- {
- // set it to current directory
- m_assemblyData.m_strDir = Directory.GetCurrentDirectory();
- }
- else if (Directory.Exists(m_assemblyData.m_strDir) == false)
- {
- throw new ArgumentException(Environment.GetResourceString("Argument_InvalidDirectory",
- m_assemblyData.m_strDir));
- }
-
- // after this point, assemblyFileName is the full path name.
- assemblyFileName = Path.Combine(m_assemblyData.m_strDir, assemblyFileName);
- assemblyFileName = Path.GetFullPath(assemblyFileName);
-
- // Check caller has the right to create the assembly file itself.
- new FileIOPermission(FileIOPermissionAccess.Write | FileIOPermissionAccess.Append, assemblyFileName).Demand();
-
- // 1. setup/create the IMetaDataAssemblyEmit for the on disk version
- if (assemblyModule != null)
- {
- // prepare saving CAs on assembly def. We need to introduce the MemberRef for
- // the CA's type first of all. This is for the case the we have embedded manifest.
- // We need to introduce these MRs before we call PreSave where we will snap
- // into a ondisk metadata. If we do it after this, the ondisk metadata will
- // not contain the proper MRs.
- //
- for (i=0; i < m_assemblyData.m_iCABuilder; i++)
- {
- tkAttrs[i] = m_assemblyData.m_CABuilders[i].PrepareCreateCustomAttributeToDisk(
- assemblyModule);
- }
- for (i=0; i < m_assemblyData.m_iCAs; i++)
- {
- tkAttrs2[i] = assemblyModule.InternalGetConstructorToken(m_assemblyData.m_CACons[i], true).Token;
- }
- assemblyModule.PreSave(assemblyFileName, portableExecutableKind, imageFileMachine);
- }
-
- RuntimeModule runtimeAssemblyModule = (assemblyModule != null) ? assemblyModule.ModuleHandle.GetRuntimeModule() : null;
- PrepareForSavingManifestToDisk(GetNativeHandle(), runtimeAssemblyModule);
-
- // This function will return the embedded manifest module, an already exposed ModuleBuilder
- // created by user, or make the stand alone manifest module exposed through managed code.
- //
- onDiskAssemblyModule = GetOnDiskAssemblyModuleBuilder();
-
- // Set any native resources on the OnDiskAssemblyModule.
- if (m_assemblyData.m_strResourceFileName != null)
- onDiskAssemblyModule.DefineUnmanagedResourceFileInternalNoLock(m_assemblyData.m_strResourceFileName);
- else if (m_assemblyData.m_resourceBytes != null)
- onDiskAssemblyModule.DefineUnmanagedResourceInternalNoLock(m_assemblyData.m_resourceBytes);
- else if (m_assemblyData.m_hasUnmanagedVersionInfo == true)
- {
- // calculate unmanaged version info from assembly's custom attributes
- m_assemblyData.FillUnmanagedVersionInfo();
-
- String strFileVersion = m_assemblyData.m_nativeVersion.m_strFileVersion;
- if (strFileVersion == null)
- strFileVersion = GetVersion().ToString();
-
- // Create the file.
- CreateVersionInfoResource(
- assemblyFileName,
- m_assemblyData.m_nativeVersion.m_strTitle, // title
- null, // Icon filename
- m_assemblyData.m_nativeVersion.m_strDescription, // description
- m_assemblyData.m_nativeVersion.m_strCopyright,
- m_assemblyData.m_nativeVersion.m_strTrademark,
- m_assemblyData.m_nativeVersion.m_strCompany,
- m_assemblyData.m_nativeVersion.m_strProduct,
- m_assemblyData.m_nativeVersion.m_strProductVersion,
- strFileVersion,
- m_assemblyData.m_nativeVersion.m_lcid,
- m_assemblyData.m_peFileKind == PEFileKinds.Dll,
- JitHelpers.GetStringHandleOnStack(ref tmpVersionFile));
-
- onDiskAssemblyModule.DefineUnmanagedResourceFileInternalNoLock(tmpVersionFile);
- }
-
- if (assemblyModule == null)
- {
-
- // This is for introducing the MRs for CA's type. This case is for stand alone
- // manifest. We need to wait till PrepareForSavingManifestToDisk is called.
- // That will trigger the creation of the on-disk stand alone manifest module.
- //
- for (i=0; i < m_assemblyData.m_iCABuilder; i++)
- {
- tkAttrs[i] = m_assemblyData.m_CABuilders[i].PrepareCreateCustomAttributeToDisk(
- onDiskAssemblyModule);
- }
- for (i=0; i < m_assemblyData.m_iCAs; i++)
- {
- tkAttrs2[i] = onDiskAssemblyModule.InternalGetConstructorToken(m_assemblyData.m_CACons[i], true).Token;
- }
- }
-
- // 2. save all of the persistable modules contained by this AssemblyBuilder except the module that is going to contain
- // Assembly information
- //
- // 3. create the file list in the manifest and track the file token. If it is embedded assembly,
- // the assembly file should not be on the file list.
- //
- size = m_assemblyData.m_moduleBuilderList.Count;
- for (i = 0; i < size; i++)
- {
- ModuleBuilder mBuilder = (ModuleBuilder) m_assemblyData.m_moduleBuilderList[i];
- if (mBuilder.IsTransient() == false && mBuilder != assemblyModule)
- {
- strModFileName = mBuilder.m_moduleData.m_strFileName;
- if (m_assemblyData.m_strDir != null)
- {
- strModFileName = Path.Combine(m_assemblyData.m_strDir, strModFileName);
- strModFileName = Path.GetFullPath(strModFileName);
- }
-
- // Check caller has the right to create the Module file itself.
- new FileIOPermission(FileIOPermissionAccess.Write | FileIOPermissionAccess.Append, strModFileName).Demand();
-
- mBuilder.m_moduleData.FileToken = AddFile(GetNativeHandle(), mBuilder.m_moduleData.m_strFileName);
- mBuilder.PreSave(strModFileName, portableExecutableKind, imageFileMachine);
- mBuilder.Save(strModFileName, false, portableExecutableKind, imageFileMachine);
-
- // Cannot set the hash value when creating the file since the file token
- // is needed to created the entries for the embedded resources in the
- // module and the resources need to be there before you figure the hash.
- SetFileHashValue(GetNativeHandle(), mBuilder.m_moduleData.FileToken, strModFileName);
- }
- }
-
- // 4. Add the public ComType
- for (i=0; i < m_assemblyData.m_iPublicComTypeCount; i++)
- {
- type = m_assemblyData.m_publicComTypeList[i];
- // If the type that was added as a Public Com Type was obtained via Reflection,
- // it will be a System.RuntimeType, even if it was really, at the same time,
- // a TypeBuilder. Unfortunately, you can't get back to the TypeBuilder, so
- // this code has to deal with either-or.
- if (type is RuntimeType)
- {
- // If type is a runtime type, it must be a baked TypeBuilder,
- // ttype.Module should be an InternalModuleBuilder
-
- InternalModuleBuilder internalMB = (InternalModuleBuilder)type.Module;
- modBuilder = this.GetModuleBuilder(internalMB);
- if (modBuilder != assemblyModule)
- DefineNestedComType(type, modBuilder.m_moduleData.FileToken, type.MetadataToken);
- }
- else
- {
- // Could assert that "type" is a TypeBuilder, but next statement throws if it isn't.
- typeBuilder = (TypeBuilder) type;
- // If type is a TypeBuilder, type.Module must be a ModuleBuilder.
- modBuilder = typeBuilder.GetModuleBuilder();
- if (modBuilder != assemblyModule)
- DefineNestedComType(type, modBuilder.m_moduleData.FileToken, typeBuilder.MetadataTokenInternal);
- }
- }
-
- // 5. write AssemblyDef's CAs (only if we are not saving directly the manifest module itself)
- if (onDiskAssemblyModule != m_manifestModuleBuilder)
- {
- for (i = 0; i < m_assemblyData.m_iCABuilder; i++)
- {
- m_assemblyData.m_CABuilders[i].CreateCustomAttribute(
- onDiskAssemblyModule,
- AssemblyBuilderData.m_tkAssembly, // This is the AssemblyDef token
- tkAttrs[i], true);
- }
-
- for (i = 0; i < m_assemblyData.m_iCAs; i++)
- {
- TypeBuilder.DefineCustomAttribute(
- onDiskAssemblyModule, // pass in the in-memory assembly module
- AssemblyBuilderData.m_tkAssembly, // This is the AssemblyDef token
- tkAttrs2[i],
- m_assemblyData.m_CABytes[i],
- true, false);
- }
- }
-
- // 6. write security permission requests to the manifest.
-#pragma warning disable 618
- if (m_assemblyData.m_RequiredPset != null)
- AddDeclarativeSecurity(m_assemblyData.m_RequiredPset, SecurityAction.RequestMinimum);
-
- if (m_assemblyData.m_RefusedPset != null)
- AddDeclarativeSecurity(m_assemblyData.m_RefusedPset, SecurityAction.RequestRefuse);
-
- if (m_assemblyData.m_OptionalPset != null)
- AddDeclarativeSecurity(m_assemblyData.m_OptionalPset, SecurityAction.RequestOptional);
-#pragma warning restore 618
-
- // 7. Save the stand alone managed resources
- size = m_assemblyData.m_resWriterList.Count;
- for (i = 0; i < size; i++)
- {
- tempRes = null;
-
- try
- {
- tempRes = (ResWriterData)m_assemblyData.m_resWriterList[i];
-
- // If the user added an existing resource to the manifest, the
- // corresponding ResourceWriter will be null.
- if (tempRes.m_resWriter != null)
- // Check caller has the right to create the Resource file itself.
- new FileIOPermission(FileIOPermissionAccess.Write | FileIOPermissionAccess.Append, tempRes.m_strFullFileName).Demand();
- }
- finally
- {
- if (tempRes != null && tempRes.m_resWriter != null)
- tempRes.m_resWriter.Close();
- }
-
- // Add entry to manifest for this stand alone resource
- AddStandAloneResource(GetNativeHandle(), tempRes.m_strName, tempRes.m_strFileName, tempRes.m_strFullFileName, (int)tempRes.m_attribute);
- }
-
- // Save now!!
- if (assemblyModule == null)
- {
- onDiskAssemblyModule.DefineNativeResource(portableExecutableKind, imageFileMachine);
-
- // Stand alone manifest
- int entryPoint = (m_assemblyData.m_entryPointModule != null) ? m_assemblyData.m_entryPointModule.m_moduleData.FileToken : 0;
-
- SaveManifestToDisk(GetNativeHandle(), assemblyFileName, entryPoint, (int)m_assemblyData.m_peFileKind,
- (int)portableExecutableKind, (int)imageFileMachine);
- }
- else
- {
- // embedded manifest
-
- // If the module containing the entry point is not the manifest file, we need to
- // let the manifest file point to the module which contains the entry point.
- //
- //
- //
- //
- if (m_assemblyData.m_entryPointModule != null && m_assemblyData.m_entryPointModule != assemblyModule)
- assemblyModule.SetEntryPoint(new MethodToken(m_assemblyData.m_entryPointModule.m_moduleData.FileToken));
- assemblyModule.Save(assemblyFileName, true, portableExecutableKind, imageFileMachine);
- }
- m_assemblyData.m_isSaved = true;
- }
- finally
- {
- if (tmpVersionFile != null)
- {
- // Delete file.
- System.IO.File.Delete(tmpVersionFile);
- }
- }
- }
-#endif // FEATURE_CORECLR
-
-#if FEATURE_CAS_POLICY
- [System.Security.SecurityCritical] // auto-generated
- private void AddDeclarativeSecurity(PermissionSet pset, SecurityAction action)
- {
- // Translate sets into internal encoding (uses standard binary serialization).
- byte[] blob = pset.EncodeXml();
- AddDeclarativeSecurity(GetNativeHandle(), action, blob, blob.Length);
- }
-#endif // FEATURE_CAS_POLICY
-
internal bool IsPersistable()
{
-#if !FEATURE_CORECLR // AssemblyBuilderAccess.Save is never set in CoreCLR
- if ((m_assemblyData.m_access & AssemblyBuilderAccess.Save) == AssemblyBuilderAccess.Save)
- {
- return true;
- }
- else
-#endif // FEATURE_CORECLR
{
return false;
}
* Internal helper to walk the nested type hierachy
*
**********************************************/
- [System.Security.SecurityCritical] // auto-generated
private int DefineNestedComType(Type type, int tkResolutionScope, int tkTypeDef)
{
Type enclosingType = type.DeclaringType;
return AddExportedTypeOnDisk(GetNativeHandle(), type.Name, tkResolutionScope, tkTypeDef, type.Attributes);
}
- [System.Security.SecurityCritical] // auto-generated
internal int DefineExportedTypeInMemory(Type type, int tkResolutionScope, int tkTypeDef)
{
Type enclosingType = type.DeclaringType;
**********************************************/
private AssemblyBuilder() {}
-#if !FEATURE_CORECLR
- void _AssemblyBuilder.GetTypeInfoCount(out uint pcTInfo)
- {
- throw new NotImplementedException();
- }
-
- void _AssemblyBuilder.GetTypeInfo(uint iTInfo, uint lcid, IntPtr ppTInfo)
- {
- throw new NotImplementedException();
- }
-
- void _AssemblyBuilder.GetIDsOfNames([In] ref Guid riid, IntPtr rgszNames, uint cNames, uint lcid, IntPtr rgDispId)
- {
- throw new NotImplementedException();
- }
-
- // If you implement this method, make sure to include _AssemblyBuilder.Invoke in VM\DangerousAPIs.h and
- // include _AssemblyBuilder in SystemDomain::IsReflectionInvocationMethod in AppDomain.cpp.
- void _AssemblyBuilder.Invoke(uint dispIdMember, [In] ref Guid riid, uint lcid, short wFlags, IntPtr pDispParams, IntPtr pVarResult, IntPtr pExcepInfo, IntPtr puArgErr)
- {
- throw new NotImplementedException();
- }
-#endif
-
// Create a new module in which to emit code. This module will not contain the manifest.
- [System.Security.SecurityCritical] // auto-generated
[DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
[SuppressUnmanagedCodeSecurity]
static private extern void DefineDynamicModule(RuntimeAssembly containingAssembly,
bool fIsTransient,
out int tkFile);
- [System.Security.SecurityCritical] // auto-generated
private static Module DefineDynamicModule(RuntimeAssembly containingAssembly,
bool emitSymbolInfo,
String name,
}
// The following functions are native helpers for creating on-disk manifest
- [System.Security.SecurityCritical] // auto-generated
[DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
[SuppressUnmanagedCodeSecurity]
static private extern void PrepareForSavingManifestToDisk(RuntimeAssembly assembly, RuntimeModule assemblyModule); // module to contain assembly information if assembly is embedded
- [System.Security.SecurityCritical] // auto-generated
[DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
[SuppressUnmanagedCodeSecurity]
static private extern void SaveManifestToDisk(RuntimeAssembly assembly,
int portableExecutableKind,
int ImageFileMachine);
- [System.Security.SecurityCritical] // auto-generated
[DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
[SuppressUnmanagedCodeSecurity]
static private extern int AddFile(RuntimeAssembly assembly, String strFileName);
- [System.Security.SecurityCritical] // auto-generated
[DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
[SuppressUnmanagedCodeSecurity]
static private extern void SetFileHashValue(RuntimeAssembly assembly,
int tkFile,
String strFullFileName);
- [System.Security.SecurityCritical] // auto-generated
[DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
[SuppressUnmanagedCodeSecurity]
static private extern int AddExportedTypeInMemory(RuntimeAssembly assembly,
int tkTypeDef,
TypeAttributes flags);
- [System.Security.SecurityCritical] // auto-generated
[DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
[SuppressUnmanagedCodeSecurity]
static private extern int AddExportedTypeOnDisk(RuntimeAssembly assembly,
TypeAttributes flags);
// Add an entry to assembly's manifestResource table for a stand alone resource.
- [System.Security.SecurityCritical] // auto-generated
[DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
[SuppressUnmanagedCodeSecurity]
static private extern void AddStandAloneResource(RuntimeAssembly assembly,
String strFullFileName,
int attribute);
- [System.Security.SecurityCritical] // auto-generated
[DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
[SuppressUnmanagedCodeSecurity]
#pragma warning disable 618
#pragma warning restore 618
// Functions for defining unmanaged resources.
- [System.Security.SecurityCritical] // auto-generated
[DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
[SuppressUnmanagedCodeSecurity]
static private extern void CreateVersionInfoResource(String filename, String title, String iconFilename, String description,
// EE uses these enum values..look for m_dwDynamicAssemblyAccess in Assembly.hpp
namespace System.Reflection.Emit
-{
+{
[Serializable]
[System.Runtime.InteropServices.ComVisible(true)]
[Flags]
public enum AssemblyBuilderAccess
{
Run = 1,
-#if !FEATURE_CORECLR // these are unsupported
- Save = 2,
- RunAndSave = Run | Save,
-#endif // !FEATURE_CORECLR
#if FEATURE_REFLECTION_ONLY_LOAD
ReflectionOnly = 6, // 4 | Save,
#endif // FEATURE_REFLECTION_ONLY_LOAD
using System.Security;
using System.Diagnostics;
using CultureInfo = System.Globalization.CultureInfo;
-#if !FEATURE_CORECLR
- using ResourceWriter = System.Resources.ResourceWriter;
-#else // FEATURE_CORECLR
using IResourceWriter = System.Resources.IResourceWriter;
-#endif // !FEATURE_CORECLR
using System.IO;
using System.Runtime.Versioning;
using System.Diagnostics.SymbolStore;
// this class cannot be accessed from the EE.
internal class AssemblyBuilderData
{
- [SecurityCritical]
internal AssemblyBuilderData(
InternalAssemblyBuilder assembly,
String strAssemblyName,
// If DefineUnmanagedVersionInfo is called, the parameter provided will override
// the CA's value.
//
- [System.Security.SecurityCritical] // auto-generated
internal void FillUnmanagedVersionInfo()
{
// Get the lcid set on the assembly name as default if available
// hard coding the assembly def token
internal const int m_tkAssembly = 0x20000001;
-
+
// Security permission requests
internal PermissionSet m_RequiredPset;
internal PermissionSet m_OptionalPset;
internal MethodInfo m_entryPointMethod;
internal Assembly m_ISymWrapperAssembly;
-#if !FEATURE_CORECLR
- internal ModuleBuilder m_entryPointModule;
-#endif //!FEATURE_CORECLR
-
// For unmanaged resources
internal String m_strResourceFileName;
internal byte[] m_resourceBytes;
**********************************************/
internal class ResWriterData
{
-#if FEATURE_CORECLR
internal ResWriterData(
IResourceWriter resWriter,
Stream memoryStream,
m_nextResWriter = null;
m_attribute = attribute;
}
-#else
- internal ResWriterData(
- ResourceWriter resWriter,
- Stream memoryStream,
- String strName,
- String strFileName,
- String strFullFileName,
- ResourceAttributes attribute)
- {
- m_resWriter = resWriter;
- m_memoryStream = memoryStream;
- m_strName = strName;
- m_strFileName = strFileName;
- m_strFullFileName = strFullFileName;
- m_nextResWriter = null;
- m_attribute = attribute;
- }
-#endif
-#if !FEATURE_CORECLR
- internal ResourceWriter m_resWriter;
-#else // FEATURE_CORECLR
- internal IResourceWriter m_resWriter;
-#endif // !FEATURE_CORECLR
+
+ internal IResourceWriter m_resWriter;
internal String m_strName;
internal String m_strFileName;
internal String m_strFullFileName;
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
-using System;
-using System.Globalization;
-using System.IO;
-using System.Reflection;
-using System.Runtime.InteropServices;
-using System.Runtime.Serialization;
-using System.Security.Permissions;
-using System.Security.Policy;
-
namespace System.Runtime.InteropServices
{
[GuidAttribute("BEBB2505-8B54-3443-AEAD-142A16DD9CC7")]
[InterfaceTypeAttribute(ComInterfaceType.InterfaceIsIUnknown)]
[CLSCompliant(false)]
[TypeLibImportClassAttribute(typeof(System.Reflection.Emit.AssemblyBuilder))]
-[System.Runtime.InteropServices.ComVisible(true)]
+ [System.Runtime.InteropServices.ComVisible(true)]
public interface _AssemblyBuilder
{
-#if !FEATURE_CORECLR
- void GetTypeInfoCount(out uint pcTInfo);
-
- void GetTypeInfo(uint iTInfo, uint lcid, IntPtr ppTInfo);
-
- void GetIDsOfNames([In] ref Guid riid, IntPtr rgszNames, uint cNames, uint lcid, IntPtr rgDispId);
-
- void Invoke(uint dispIdMember, [In] ref Guid riid, uint lcid, short wFlags, IntPtr pDispParams, IntPtr pVarResult, IntPtr pExcepInfo, IntPtr puArgErr);
-#endif
}
[GuidAttribute("ED3E4384-D7E2-3FA7-8FFD-8940D330519A")]
[System.Runtime.InteropServices.ComVisible(true)]
public interface _ConstructorBuilder
{
-#if !FEATURE_CORECLR
- void GetTypeInfoCount(out uint pcTInfo);
-
- void GetTypeInfo(uint iTInfo, uint lcid, IntPtr ppTInfo);
-
- void GetIDsOfNames([In] ref Guid riid, IntPtr rgszNames, uint cNames, uint lcid, IntPtr rgDispId);
-
- void Invoke(uint dispIdMember, [In] ref Guid riid, uint lcid, short wFlags, IntPtr pDispParams, IntPtr pVarResult, IntPtr pExcepInfo, IntPtr puArgErr);
-#endif
}
[GuidAttribute("BE9ACCE8-AAFF-3B91-81AE-8211663F5CAD")]
[InterfaceTypeAttribute(ComInterfaceType.InterfaceIsIUnknown)]
[CLSCompliant(false)]
[TypeLibImportClassAttribute(typeof(System.Reflection.Emit.CustomAttributeBuilder))]
-[System.Runtime.InteropServices.ComVisible(true)]
+ [System.Runtime.InteropServices.ComVisible(true)]
public interface _CustomAttributeBuilder
{
-#if !FEATURE_CORECLR
- void GetTypeInfoCount(out uint pcTInfo);
-
- void GetTypeInfo(uint iTInfo, uint lcid, IntPtr ppTInfo);
-
- void GetIDsOfNames([In] ref Guid riid, IntPtr rgszNames, uint cNames, uint lcid, IntPtr rgDispId);
-
- void Invoke(uint dispIdMember, [In] ref Guid riid, uint lcid, short wFlags, IntPtr pDispParams, IntPtr pVarResult, IntPtr pExcepInfo, IntPtr puArgErr);
-#endif
}
[GuidAttribute("C7BD73DE-9F85-3290-88EE-090B8BDFE2DF")]
[InterfaceTypeAttribute(ComInterfaceType.InterfaceIsIUnknown)]
[CLSCompliant(false)]
[TypeLibImportClassAttribute(typeof(System.Reflection.Emit.EnumBuilder))]
-[System.Runtime.InteropServices.ComVisible(true)]
+ [System.Runtime.InteropServices.ComVisible(true)]
public interface _EnumBuilder
{
-#if !FEATURE_CORECLR
- void GetTypeInfoCount(out uint pcTInfo);
-
- void GetTypeInfo(uint iTInfo, uint lcid, IntPtr ppTInfo);
-
- void GetIDsOfNames([In] ref Guid riid, IntPtr rgszNames, uint cNames, uint lcid, IntPtr rgDispId);
-
- void Invoke(uint dispIdMember, [In] ref Guid riid, uint lcid, short wFlags, IntPtr pDispParams, IntPtr pVarResult, IntPtr pExcepInfo, IntPtr puArgErr);
-#endif
}
[GuidAttribute("AADABA99-895D-3D65-9760-B1F12621FAE8")]
[InterfaceTypeAttribute(ComInterfaceType.InterfaceIsIUnknown)]
[CLSCompliant(false)]
[TypeLibImportClassAttribute(typeof(System.Reflection.Emit.EventBuilder))]
-[System.Runtime.InteropServices.ComVisible(true)]
+ [System.Runtime.InteropServices.ComVisible(true)]
public interface _EventBuilder
{
-#if !FEATURE_CORECLR
- void GetTypeInfoCount(out uint pcTInfo);
-
- void GetTypeInfo(uint iTInfo, uint lcid, IntPtr ppTInfo);
-
- void GetIDsOfNames([In] ref Guid riid, IntPtr rgszNames, uint cNames, uint lcid, IntPtr rgDispId);
-
- void Invoke(uint dispIdMember, [In] ref Guid riid, uint lcid, short wFlags, IntPtr pDispParams, IntPtr pVarResult, IntPtr pExcepInfo, IntPtr puArgErr);
-#endif
}
[GuidAttribute("CE1A3BF5-975E-30CC-97C9-1EF70F8F3993")]
[InterfaceTypeAttribute(ComInterfaceType.InterfaceIsIUnknown)]
[CLSCompliant(false)]
[TypeLibImportClassAttribute(typeof(System.Reflection.Emit.FieldBuilder))]
-[System.Runtime.InteropServices.ComVisible(true)]
+ [System.Runtime.InteropServices.ComVisible(true)]
public interface _FieldBuilder
{
-#if !FEATURE_CORECLR
- void GetTypeInfoCount(out uint pcTInfo);
-
- void GetTypeInfo(uint iTInfo, uint lcid, IntPtr ppTInfo);
-
- void GetIDsOfNames([In] ref Guid riid, IntPtr rgszNames, uint cNames, uint lcid, IntPtr rgDispId);
-
- void Invoke(uint dispIdMember, [In] ref Guid riid, uint lcid, short wFlags, IntPtr pDispParams, IntPtr pVarResult, IntPtr pExcepInfo, IntPtr puArgErr);
-#endif
}
[GuidAttribute("A4924B27-6E3B-37F7-9B83-A4501955E6A7")]
[InterfaceTypeAttribute(ComInterfaceType.InterfaceIsIUnknown)]
[CLSCompliant(false)]
[TypeLibImportClassAttribute(typeof(System.Reflection.Emit.ILGenerator))]
-[System.Runtime.InteropServices.ComVisible(true)]
+ [System.Runtime.InteropServices.ComVisible(true)]
public interface _ILGenerator
{
-#if !FEATURE_CORECLR
- void GetTypeInfoCount(out uint pcTInfo);
-
- void GetTypeInfo(uint iTInfo, uint lcid, IntPtr ppTInfo);
-
- void GetIDsOfNames([In] ref Guid riid, IntPtr rgszNames, uint cNames, uint lcid, IntPtr rgDispId);
-
- void Invoke(uint dispIdMember, [In] ref Guid riid, uint lcid, short wFlags, IntPtr pDispParams, IntPtr pVarResult, IntPtr pExcepInfo, IntPtr puArgErr);
-#endif
}
[GuidAttribute("4E6350D1-A08B-3DEC-9A3E-C465F9AEEC0C")]
[InterfaceTypeAttribute(ComInterfaceType.InterfaceIsIUnknown)]
[CLSCompliant(false)]
[TypeLibImportClassAttribute(typeof(System.Reflection.Emit.LocalBuilder))]
-[System.Runtime.InteropServices.ComVisible(true)]
+ [System.Runtime.InteropServices.ComVisible(true)]
public interface _LocalBuilder
{
-#if !FEATURE_CORECLR
- void GetTypeInfoCount(out uint pcTInfo);
-
- void GetTypeInfo(uint iTInfo, uint lcid, IntPtr ppTInfo);
-
- void GetIDsOfNames([In] ref Guid riid, IntPtr rgszNames, uint cNames, uint lcid, IntPtr rgDispId);
-
- void Invoke(uint dispIdMember, [In] ref Guid riid, uint lcid, short wFlags, IntPtr pDispParams, IntPtr pVarResult, IntPtr pExcepInfo, IntPtr puArgErr);
-#endif
}
[GuidAttribute("007D8A14-FDF3-363E-9A0B-FEC0618260A2")]
[InterfaceTypeAttribute(ComInterfaceType.InterfaceIsIUnknown)]
[CLSCompliant(false)]
[TypeLibImportClassAttribute(typeof(System.Reflection.Emit.MethodBuilder))]
-[System.Runtime.InteropServices.ComVisible(true)]
+ [System.Runtime.InteropServices.ComVisible(true)]
public interface _MethodBuilder
{
-#if !FEATURE_CORECLR
- void GetTypeInfoCount(out uint pcTInfo);
-
- void GetTypeInfo(uint iTInfo, uint lcid, IntPtr ppTInfo);
-
- void GetIDsOfNames([In] ref Guid riid, IntPtr rgszNames, uint cNames, uint lcid, IntPtr rgDispId);
-
- void Invoke(uint dispIdMember, [In] ref Guid riid, uint lcid, short wFlags, IntPtr pDispParams, IntPtr pVarResult, IntPtr pExcepInfo, IntPtr puArgErr);
-#endif
}
#if FEATURE_METHOD_RENTAL
[InterfaceTypeAttribute(ComInterfaceType.InterfaceIsIUnknown)]
[CLSCompliant(false)]
[TypeLibImportClassAttribute(typeof(System.Reflection.Emit.MethodRental))]
-[System.Runtime.InteropServices.ComVisible(true)]
+ [System.Runtime.InteropServices.ComVisible(true)]
public interface _MethodRental
{
-#if !FEATURE_CORECLR
- void GetTypeInfoCount(out uint pcTInfo);
-
- void GetTypeInfo(uint iTInfo, uint lcid, IntPtr ppTInfo);
-
- void GetIDsOfNames([In] ref Guid riid, IntPtr rgszNames, uint cNames, uint lcid, IntPtr rgDispId);
-
- void Invoke(uint dispIdMember, [In] ref Guid riid, uint lcid, short wFlags, IntPtr pDispParams, IntPtr pVarResult, IntPtr pExcepInfo, IntPtr puArgErr);
-#endif
}
#endif
[InterfaceTypeAttribute(ComInterfaceType.InterfaceIsIUnknown)]
[CLSCompliant(false)]
[TypeLibImportClassAttribute(typeof(System.Reflection.Emit.ModuleBuilder))]
-[System.Runtime.InteropServices.ComVisible(true)]
+ [System.Runtime.InteropServices.ComVisible(true)]
public interface _ModuleBuilder
{
-#if !FEATURE_CORECLR
- void GetTypeInfoCount(out uint pcTInfo);
-
- void GetTypeInfo(uint iTInfo, uint lcid, IntPtr ppTInfo);
-
- void GetIDsOfNames([In] ref Guid riid, IntPtr rgszNames, uint cNames, uint lcid, IntPtr rgDispId);
-
- void Invoke(uint dispIdMember, [In] ref Guid riid, uint lcid, short wFlags, IntPtr pDispParams, IntPtr pVarResult, IntPtr pExcepInfo, IntPtr puArgErr);
-#endif
}
[GuidAttribute("36329EBA-F97A-3565-BC07-0ED5C6EF19FC")]
[InterfaceTypeAttribute(ComInterfaceType.InterfaceIsIUnknown)]
[CLSCompliant(false)]
[TypeLibImportClassAttribute(typeof(System.Reflection.Emit.ParameterBuilder))]
-[System.Runtime.InteropServices.ComVisible(true)]
+ [System.Runtime.InteropServices.ComVisible(true)]
public interface _ParameterBuilder
{
-#if !FEATURE_CORECLR
- void GetTypeInfoCount(out uint pcTInfo);
-
- void GetTypeInfo(uint iTInfo, uint lcid, IntPtr ppTInfo);
-
- void GetIDsOfNames([In] ref Guid riid, IntPtr rgszNames, uint cNames, uint lcid, IntPtr rgDispId);
-
- void Invoke(uint dispIdMember, [In] ref Guid riid, uint lcid, short wFlags, IntPtr pDispParams, IntPtr pVarResult, IntPtr pExcepInfo, IntPtr puArgErr);
-#endif
}
[GuidAttribute("15F9A479-9397-3A63-ACBD-F51977FB0F02")]
[InterfaceTypeAttribute(ComInterfaceType.InterfaceIsIUnknown)]
[CLSCompliant(false)]
[TypeLibImportClassAttribute(typeof(System.Reflection.Emit.PropertyBuilder))]
-[System.Runtime.InteropServices.ComVisible(true)]
+ [System.Runtime.InteropServices.ComVisible(true)]
public interface _PropertyBuilder
{
-#if !FEATURE_CORECLR
- void GetTypeInfoCount(out uint pcTInfo);
-
- void GetTypeInfo(uint iTInfo, uint lcid, IntPtr ppTInfo);
-
- void GetIDsOfNames([In] ref Guid riid, IntPtr rgszNames, uint cNames, uint lcid, IntPtr rgDispId);
-
- void Invoke(uint dispIdMember, [In] ref Guid riid, uint lcid, short wFlags, IntPtr pDispParams, IntPtr pVarResult, IntPtr pExcepInfo, IntPtr puArgErr);
-#endif
}
[GuidAttribute("7D13DD37-5A04-393C-BBCA-A5FEA802893D")]
[InterfaceTypeAttribute(ComInterfaceType.InterfaceIsIUnknown)]
[CLSCompliant(false)]
[TypeLibImportClassAttribute(typeof(System.Reflection.Emit.SignatureHelper))]
-[System.Runtime.InteropServices.ComVisible(true)]
+ [System.Runtime.InteropServices.ComVisible(true)]
public interface _SignatureHelper
{
-#if !FEATURE_CORECLR
- void GetTypeInfoCount(out uint pcTInfo);
-
- void GetTypeInfo(uint iTInfo, uint lcid, IntPtr ppTInfo);
-
- void GetIDsOfNames([In] ref Guid riid, IntPtr rgszNames, uint cNames, uint lcid, IntPtr rgDispId);
-
- void Invoke(uint dispIdMember, [In] ref Guid riid, uint lcid, short wFlags, IntPtr pDispParams, IntPtr pVarResult, IntPtr pExcepInfo, IntPtr puArgErr);
-#endif
}
[GuidAttribute("7E5678EE-48B3-3F83-B076-C58543498A58")]
[InterfaceTypeAttribute(ComInterfaceType.InterfaceIsIUnknown)]
[CLSCompliant(false)]
[TypeLibImportClassAttribute(typeof(System.Reflection.Emit.TypeBuilder))]
-[System.Runtime.InteropServices.ComVisible(true)]
+ [System.Runtime.InteropServices.ComVisible(true)]
public interface _TypeBuilder
{
-#if !FEATURE_CORECLR
- void GetTypeInfoCount(out uint pcTInfo);
-
- void GetTypeInfo(uint iTInfo, uint lcid, IntPtr ppTInfo);
-
- void GetIDsOfNames([In] ref Guid riid, IntPtr rgszNames, uint cNames, uint lcid, IntPtr rgDispId);
-
- void Invoke(uint dispIdMember, [In] ref Guid riid, uint lcid, short wFlags, IntPtr pDispParams, IntPtr pVarResult, IntPtr pExcepInfo, IntPtr puArgErr);
-#endif
}
-
}
using System.Runtime.InteropServices;
using System.Diagnostics.Contracts;
- [HostProtection(MayLeakOnAbort = true)]
[ClassInterface(ClassInterfaceType.None)]
[ComDefaultInterface(typeof(_ConstructorBuilder))]
[System.Runtime.InteropServices.ComVisible(true)]
{
}
- [System.Security.SecurityCritical] // auto-generated
internal ConstructorBuilder(String name, MethodAttributes attributes, CallingConventions callingConvention,
Type[] parameterTypes, Type[][] requiredCustomModifiers, Type[][] optionalCustomModifiers, ModuleBuilder mod, TypeBuilder type)
{
token = m_methodBuilder.GetToken();
}
- [System.Security.SecurityCritical] // auto-generated
internal ConstructorBuilder(String name, MethodAttributes attributes, CallingConventions callingConvention,
Type[] parameterTypes, ModuleBuilder mod, TypeBuilder type) :
this(name, attributes, callingConvention, parameterTypes, null, null, mod, type)
return m_methodBuilder.GetILGenerator(streamSize);
}
- #if FEATURE_CORECLR
- [System.Security.SecurityCritical] // auto-generated
- #endif
public void SetMethodBody(byte[] il, int maxStack, byte[] localSignature, IEnumerable<ExceptionHandler> exceptionHandlers, IEnumerable<int> tokenFixups)
{
if (m_isDefaultConstructor)
m_methodBuilder.SetMethodBody(il, maxStack, localSignature, exceptionHandlers, tokenFixups);
}
-#if FEATURE_CAS_POLICY
- [System.Security.SecuritySafeCritical] // auto-generated
- public void AddDeclarativeSecurity(SecurityAction action, PermissionSet pset)
- {
- if (pset == null)
- throw new ArgumentNullException(nameof(pset));
-
-#pragma warning disable 618
- if (!Enum.IsDefined(typeof(SecurityAction), action) ||
- action == SecurityAction.RequestMinimum ||
- action == SecurityAction.RequestOptional ||
- action == SecurityAction.RequestRefuse)
- {
- throw new ArgumentOutOfRangeException(nameof(action));
- }
-#pragma warning restore 618
- Contract.EndContractBlock();
-
- // Cannot add declarative security after type is created.
- if (m_methodBuilder.IsTypeCreated())
- throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_TypeHasBeenCreated"));
-
- // Translate permission set into serialized format (use standard binary serialization).
- byte[] blob = pset.EncodeXml();
-
- // Write the blob into the metadata.
- TypeBuilder.AddDeclarativeSecurity(GetModuleBuilder().GetNativeHandle(), GetToken().Token, action, blob, blob.Length);
- }
-#endif // FEATURE_CAS_POLICY
-
public override CallingConventions CallingConvention
{
get
get { return m_methodBuilder.Signature; }
}
- #if FEATURE_CORECLR
- [System.Security.SecurityCritical] // auto-generated
- #endif
[System.Runtime.InteropServices.ComVisible(true)]
public void SetCustomAttribute(ConstructorInfo con, byte[] binaryAttribute)
{
}
#endregion
-
-#if !FEATURE_CORECLR
- void _ConstructorBuilder.GetTypeInfoCount(out uint pcTInfo)
- {
- throw new NotImplementedException();
- }
-
- void _ConstructorBuilder.GetTypeInfo(uint iTInfo, uint lcid, IntPtr ppTInfo)
- {
- throw new NotImplementedException();
- }
-
- void _ConstructorBuilder.GetIDsOfNames([In] ref Guid riid, IntPtr rgszNames, uint cNames, uint lcid, IntPtr rgDispId)
- {
- throw new NotImplementedException();
- }
-
- void _ConstructorBuilder.Invoke(uint dispIdMember, [In] ref Guid riid, uint lcid, short wFlags, IntPtr pDispParams, IntPtr pVarResult, IntPtr pExcepInfo, IntPtr puArgErr)
- {
- throw new NotImplementedException();
- }
-#endif
}
}
using System.Security.Permissions;
using System.Runtime.InteropServices;
using System.Globalization;
+ using System.Diagnostics;
using System.Diagnostics.Contracts;
- [HostProtection(MayLeakOnAbort = true)]
[ClassInterface(ClassInterfaceType.None)]
[ComDefaultInterface(typeof(_CustomAttributeBuilder))]
[System.Runtime.InteropServices.ComVisible(true)]
writer.Write((byte)CustomAttributeEncoding.Double);
break;
default:
- Contract.Assert(false, "Invalid primitive type");
+ Debug.Assert(false, "Invalid primitive type");
break;
}
}
writer.Write((ulong)value);
break;
default:
- Contract.Assert(false, "Invalid enum base type");
+ Debug.Assert(false, "Invalid enum base type");
break;
}
}
writer.Write((double)value);
break;
default:
- Contract.Assert(false, "Invalid primitive type");
+ Debug.Assert(false, "Invalid primitive type");
break;
}
}
// return the byte interpretation of the custom attribute
- [System.Security.SecurityCritical] // auto-generated
internal void CreateCustomAttribute(ModuleBuilder mod, int tkOwner)
{
CreateCustomAttribute(mod, tkOwner, mod.GetConstructorToken(m_con).Token, false);
// This function has to be called before we snap the in-memory module for on disk (i.e. Presave on
// ModuleBuilder.
//*************************************************
- [System.Security.SecurityCritical] // auto-generated
internal int PrepareCreateCustomAttributeToDisk(ModuleBuilder mod)
{
return mod.InternalGetConstructorToken(m_con, true).Token;
//*************************************************
// Call this function with toDisk=1, after on disk module has been snapped.
//*************************************************
- [System.Security.SecurityCritical] // auto-generated
internal void CreateCustomAttribute(ModuleBuilder mod, int tkOwner, int tkAttrib, bool toDisk)
{
TypeBuilder.DefineCustomAttribute(mod, tkOwner, tkAttrib, m_blob, toDisk,
typeof(System.Diagnostics.DebuggableAttribute) == m_con.DeclaringType);
}
-#if !FEATURE_CORECLR
- void _CustomAttributeBuilder.GetTypeInfoCount(out uint pcTInfo)
- {
- throw new NotImplementedException();
- }
-
- void _CustomAttributeBuilder.GetTypeInfo(uint iTInfo, uint lcid, IntPtr ppTInfo)
- {
- throw new NotImplementedException();
- }
-
- void _CustomAttributeBuilder.GetIDsOfNames([In] ref Guid riid, IntPtr rgszNames, uint cNames, uint lcid, IntPtr rgDispId)
- {
- throw new NotImplementedException();
- }
-
- void _CustomAttributeBuilder.Invoke(uint dispIdMember, [In] ref Guid riid, uint lcid, short wFlags, IntPtr pDispParams, IntPtr pVarResult, IntPtr pExcepInfo, IntPtr puArgErr)
- {
- throw new NotImplementedException();
- }
-#endif
-
internal ConstructorInfo m_con;
internal Object[] m_constructorArgs;
internal byte[] m_blob;
using System.Collections.Generic;
using System.Security.Permissions;
using System.Threading;
+ using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Diagnostics.Contracts;
using System.Security;
}
- [System.Security.SecurityCritical] // auto-generated
internal void GetCallableMethod(RuntimeModule module, DynamicMethod dm)
{
dm.m_methodHandle = ModuleHandle.GetDynamicMethod(dm,
// Token resolution calls
//
//
- [System.Security.SecuritySafeCritical] // auto-generated
public override void Emit(OpCode opcode, MethodInfo meth)
{
if (meth == null)
// Signature related calls (vararg, calli)
//
//
- [System.Security.SecuritySafeCritical] // overrides SC
public override void EmitCalli(OpCode opcode,
CallingConventions callingConvention,
Type returnType,
PutInteger4(token);
}
- [System.Security.SecuritySafeCritical] // auto-generated
public override void EmitCall(OpCode opcode, MethodInfo methodInfo, Type[] optionalParameterTypes)
{
if (methodInfo == null)
// SignatureHelper.
if (opcode.StackBehaviourPop == StackBehaviour.Varpop)
{
- Contract.Assert(opcode.Equals(OpCodes.Calli),
+ Debug.Assert(opcode.Equals(OpCodes.Calli),
"Unexpected opcode encountered for StackBehaviour VarPop.");
// Pop the arguments..
stackchange -= signature.ArgumentCount;
throw new NotSupportedException(Environment.GetResourceString("InvalidOperation_NotAllowedInDynamicMethod"));
}
- [System.Security.SecurityCritical] // auto-generated
private int GetMemberRefToken(MethodBase methodInfo, Type[] optionalParameterTypes)
{
Type[] parameterTypes;
return GetTokenForVarArgMethod(dm, sig);
}
- [System.Security.SecurityCritical] // auto-generated
internal override SignatureHelper GetMemberRefSignature(
CallingConventions call,
Type returnType,
m_method.m_resolver = this;
}
-#if FEATURE_CORECLR
- [System.Security.SecurityCritical] // auto-generated
-#endif
internal DynamicResolver(DynamicILInfo dynamicILInfo)
{
m_stackSize = dynamicILInfo.MaxStackSize;
{
internal RuntimeMethodHandleInternal m_methodHandle;
- [System.Security.SecuritySafeCritical] // auto-generated
~DestroyScout()
{
if (m_methodHandle.IsNullHandle())
return m_exceptionHeader;
}
- [System.Security.SecurityCritical] // auto-generated
internal override unsafe void GetEHInfo(int excNumber, void* exc)
{
CORINFO_EH_CLAUSE* exception = (CORINFO_EH_CLAUSE*)exc;
}
#endif // FEATURE_COMPRESSEDSTACK
- [System.Security.SecurityCritical]
internal override void ResolveToken(int token, out IntPtr typeHandle, out IntPtr methodHandle, out IntPtr fieldHandle)
{
typeHandle = new IntPtr();
}
-#if FEATURE_CORECLR
-[System.Security.SecurityCritical] // auto-generated
-#endif
[System.Runtime.InteropServices.ComVisible(true)]
public class DynamicILInfo
{
#endregion
#region Internal Methods
- [System.Security.SecurityCritical] // auto-generated
internal void GetCallableMethod(RuntimeModule module, DynamicMethod dm)
{
dm.m_methodHandle = ModuleHandle.GetDynamicMethod(dm,
m_maxStackSize = maxStackSize;
}
- [System.Security.SecurityCritical] // auto-generated
[CLSCompliant(false)]
public unsafe void SetCode(byte* code, int codeSize, int maxStackSize)
{
m_exceptions = (exceptions != null) ? (byte[])exceptions.Clone() : EmptyArray<Byte>.Value;
}
- [System.Security.SecurityCritical] // auto-generated
[CLSCompliant(false)]
public unsafe void SetExceptions(byte* exceptions, int exceptionsSize)
{
m_localSignature = (localSignature != null) ? (byte[])localSignature.Clone() : EmptyArray<Byte>.Value;
}
- [System.Security.SecurityCritical] // auto-generated
[CLSCompliant(false)]
public unsafe void SetLocalSignature(byte* localSignature, int signatureSize)
{
#endregion
#region Public Scope Methods
- [System.Security.SecuritySafeCritical] // auto-generated
public int GetTokenFor(RuntimeMethodHandle method)
{
return DynamicScope.GetTokenFor(method);
#endregion
#region Public Methods
- [System.Security.SecuritySafeCritical] // auto-generated
public int GetTokenFor(RuntimeMethodHandle method)
{
IRuntimeMethodInfo methodReal = method.GetMethodInfo();
using System.Threading;
using System.Runtime.CompilerServices;
using System.Runtime.Versioning;
+ using System.Diagnostics;
using System.Diagnostics.Contracts;
using System.Runtime.InteropServices;
internal IRuntimeMethodInfo m_methodHandle;
private RuntimeType m_returnType;
private DynamicILGenerator m_ilGenerator;
- #if FEATURE_CORECLR
- [System.Security.SecurityCritical] // auto-generated
- #endif
private DynamicILInfo m_DynamicILInfo;
private bool m_fInitLocals;
private RuntimeModule m_module;
private DynamicMethod() { }
- [System.Security.SecuritySafeCritical] // auto-generated
[MethodImplAttribute(MethodImplOptions.NoInlining)] // Methods containing StackCrawlMark local var has to be marked non-inlineable
public DynamicMethod(string name,
Type returnType,
ref stackMark); // transparentMethod
}
- [System.Security.SecuritySafeCritical] // auto-generated
[MethodImplAttribute(MethodImplOptions.NoInlining)] // Methods containing StackCrawlMark local var has to be marked non-inlineable
public DynamicMethod(string name,
Type returnType,
ref stackMark); // transparentMethod
}
- #if FEATURE_CORECLR
- [System.Security.SecurityCritical] // auto-generated
- #else
- [System.Security.SecuritySafeCritical]
- #endif
[MethodImplAttribute(MethodImplOptions.NoInlining)] // Methods containing StackCrawlMark local var has to be marked non-inlineable
public DynamicMethod(string name,
Type returnType,
ref stackMark); // transparentMethod
}
- #if FEATURE_CORECLR
- [System.Security.SecurityCritical] // auto-generated
- #else
- [System.Security.SecuritySafeCritical]
- #endif
[MethodImplAttribute(MethodImplOptions.NoInlining)] // Methods containing StackCrawlMark local var has to be marked non-inlineable
public DynamicMethod(string name,
Type returnType,
ref stackMark); // transparentMethod
}
- #if FEATURE_CORECLR
- [System.Security.SecurityCritical] // auto-generated
- #else
- [System.Security.SecuritySafeCritical]
- #endif
[MethodImplAttribute(MethodImplOptions.NoInlining)] // Methods containing StackCrawlMark local var has to be marked non-inlineable
public DynamicMethod(string name,
MethodAttributes attributes,
ref stackMark); // transparentMethod
}
- #if FEATURE_CORECLR
- [System.Security.SecurityCritical] // auto-generated
- #else
- [System.Security.SecuritySafeCritical]
- #endif
[MethodImplAttribute(MethodImplOptions.NoInlining)] // Methods containing StackCrawlMark local var has to be marked non-inlineable
public DynamicMethod(string name,
Type returnType,
ref stackMark); // transparentMethod
}
- #if FEATURE_CORECLR
- [System.Security.SecurityCritical] // auto-generated
- #else
- [System.Security.SecuritySafeCritical]
- #endif
[MethodImplAttribute(MethodImplOptions.NoInlining)] // Methods containing StackCrawlMark local var has to be marked non-inlineable
public DynamicMethod(string name,
Type returnType,
ref stackMark); // transparentMethod
}
- #if FEATURE_CORECLR
- [System.Security.SecurityCritical] // auto-generated
- #else
- [System.Security.SecuritySafeCritical]
- #endif
[MethodImplAttribute(MethodImplOptions.NoInlining)] // Methods containing StackCrawlMark local var has to be marked non-inlineable
public DynamicMethod(string name,
MethodAttributes attributes,
// We create a transparent assembly to host DynamicMethods. Since the assembly does not have any
// non-public fields (or any fields at all), it is a safe anonymous assembly to host DynamicMethods
- [System.Security.SecurityCritical] // auto-generated
[MethodImplAttribute(MethodImplOptions.NoInlining)] // Methods containing StackCrawlMark local var has to be marked non-inlineable
private static RuntimeModule GetDynamicMethodsModule()
{
CustomAttributeBuilder transparencyAttribute = new CustomAttributeBuilder(transparencyCtor, EmptyArray<Object>.Value);
List<CustomAttributeBuilder> assemblyAttributes = new List<CustomAttributeBuilder>();
assemblyAttributes.Add(transparencyAttribute);
-#if !FEATURE_CORECLR
- // On the desktop, we need to use the security rule set level 1 for anonymously hosted
- // dynamic methods. In level 2, transparency rules are strictly enforced, which leads to
- // errors when a fully trusted application causes a dynamic method to be generated that tries
- // to call a method with a LinkDemand or a SecurityCritical method. To retain compatibility
- // with the v2.0 and v3.x frameworks, these calls should be allowed.
- //
- // If this rule set was not explicitly called out, then the anonymously hosted dynamic methods
- // assembly would inherit the rule set from the creating assembly - which would cause it to
- // be level 2 because mscorlib.dll is using the level 2 rules.
- ConstructorInfo securityRulesCtor = typeof(SecurityRulesAttribute).GetConstructor(new Type[] { typeof(SecurityRuleSet) });
- CustomAttributeBuilder securityRulesAttribute =
- new CustomAttributeBuilder(securityRulesCtor, new object[] { SecurityRuleSet.Level1 });
- assemblyAttributes.Add(securityRulesAttribute);
-#endif // !FEATURE_CORECLR
AssemblyName assemblyName = new AssemblyName("Anonymously Hosted DynamicMethods Assembly");
StackCrawlMark stackMark = StackCrawlMark.LookForMe;
return s_anonymouslyHostedDynamicMethodsModule;
}
- [System.Security.SecurityCritical] // auto-generated
private unsafe void Init(String name,
MethodAttributes attributes,
CallingConventions callingConvention,
if (transparentMethod)
{
- Contract.Assert(owner == null && m == null, "owner and m cannot be set for transparent methods");
+ Debug.Assert(owner == null && m == null, "owner and m cannot be set for transparent methods");
m_module = GetDynamicMethodsModule();
if (skipVisibility)
{
}
else
{
- Contract.Assert(m != null || owner != null, "PerformSecurityCheck should ensure that either m or owner is set");
- Contract.Assert(m == null || !m.Equals(s_anonymouslyHostedDynamicMethodsModule), "The user cannot explicitly use this assembly");
- Contract.Assert(m == null || owner == null, "m and owner cannot both be set");
+ Debug.Assert(m != null || owner != null, "PerformSecurityCheck should ensure that either m or owner is set");
+ Debug.Assert(m == null || !m.Equals(s_anonymouslyHostedDynamicMethodsModule), "The user cannot explicitly use this assembly");
+ Debug.Assert(m == null || owner == null, "m and owner cannot both be set");
if (m != null)
m_module = m.ModuleHandle.GetRuntimeModule(); // this returns the underlying module for all RuntimeModule and ModuleBuilder objects.
m_dynMethod = new RTDynamicMethod(this, name, attributes, callingConvention);
}
- [System.Security.SecurityCritical] // auto-generated
private void PerformSecurityCheck(Module m, ref StackCrawlMark stackMark, bool skipVisibility)
{
if (m == null)
throw new ArgumentNullException(nameof(m));
Contract.EndContractBlock();
-#if !FEATURE_CORECLR
-
- RuntimeModule rtModule;
- ModuleBuilder mb = m as ModuleBuilder;
- if (mb != null)
- rtModule = mb.InternalModule;
- else
- rtModule = m as RuntimeModule;
-
- if (rtModule == null)
- {
- throw new ArgumentException(Environment.GetResourceString("Argument_MustBeRuntimeModule"), nameof(m));
- }
-
- // The user cannot explicitly use this assembly
- if (rtModule == s_anonymouslyHostedDynamicMethodsModule)
- throw new ArgumentException(Environment.GetResourceString("Argument_InvalidValue"), nameof(m));
-
- // ask for member access if skip visibility
- if (skipVisibility)
- new ReflectionPermission(ReflectionPermissionFlag.MemberAccess).Demand();
-
-#if !FEATURE_CORECLR
- // ask for control evidence if outside of the caller assembly
- RuntimeType callingType = RuntimeMethodHandle.GetCallerType(ref stackMark);
- m_creatorAssembly = callingType.GetRuntimeAssembly();
- if (m.Assembly != m_creatorAssembly)
- {
- // Demand the permissions of the assembly where the DynamicMethod will live
- CodeAccessSecurityEngine.ReflectionTargetDemandHelper(PermissionType.SecurityControlEvidence,
- m.Assembly.PermissionSet);
- }
-#else //FEATURE_CORECLR
-#pragma warning disable 618
- new SecurityPermission(SecurityPermissionFlag.ControlEvidence).Demand();
-#pragma warning restore 618
-#endif //FEATURE_CORECLR
-#endif //!FEATURE_CORECLR
}
- [System.Security.SecurityCritical] // auto-generated
private void PerformSecurityCheck(Type owner, ref StackCrawlMark stackMark, bool skipVisibility)
{
if (owner == null)
throw new ArgumentNullException(nameof(owner));
-#if !FEATURE_CORECLR
-
- RuntimeType rtOwner = owner as RuntimeType;
- if (rtOwner == null)
- rtOwner = owner.UnderlyingSystemType as RuntimeType;
-
- if (rtOwner == null)
- throw new ArgumentNullException(nameof(owner), Environment.GetResourceString("Argument_MustBeRuntimeType"));
-
- // get the type the call is coming from
- RuntimeType callingType = RuntimeMethodHandle.GetCallerType(ref stackMark);
-
- // ask for member access if skip visibility
- if (skipVisibility)
- new ReflectionPermission(ReflectionPermissionFlag.MemberAccess).Demand();
- else
- {
- // if the call is not coming from the same class ask for member access
- if (callingType != rtOwner)
- new ReflectionPermission(ReflectionPermissionFlag.MemberAccess).Demand();
- }
-#if !FEATURE_CORECLR
- m_creatorAssembly = callingType.GetRuntimeAssembly();
-
- // ask for control evidence if outside of the caller module
- if (rtOwner.Assembly != m_creatorAssembly)
- {
- // Demand the permissions of the assembly where the DynamicMethod will live
- CodeAccessSecurityEngine.ReflectionTargetDemandHelper(PermissionType.SecurityControlEvidence,
- owner.Assembly.PermissionSet);
- }
-#else //FEATURE_CORECLR
-#pragma warning disable 618
- new SecurityPermission(SecurityPermissionFlag.ControlEvidence).Demand();
-#pragma warning restore 618
-#endif //FEATURE_CORECLR
-#endif //!FEATURE_CORECLR
}
//
// Delegate and method creation
//
- [System.Security.SecuritySafeCritical] // auto-generated
[System.Runtime.InteropServices.ComVisible(true)]
public sealed override Delegate CreateDelegate(Type delegateType) {
if (m_restrictedSkipVisibility)
return d;
}
- [System.Security.SecuritySafeCritical] // auto-generated
[System.Runtime.InteropServices.ComVisible(true)]
public sealed override Delegate CreateDelegate(Type delegateType, Object target) {
if (m_restrictedSkipVisibility)
#endif
// This is guaranteed to return a valid handle
- [System.Security.SecurityCritical] // auto-generated
internal unsafe RuntimeMethodHandle GetMethodDescriptor() {
if (m_methodHandle == null) {
lock (this) {
public override bool IsSecurityCritical
{
-#if FEATURE_CORECLR
get { return true; }
-#else
- [SecuritySafeCritical]
- get
- {
- if (m_methodHandle != null)
- {
- return RuntimeMethodHandle.IsSecurityCritical(m_methodHandle);
- }
- else if (m_typeOwner != null)
- {
- RuntimeAssembly assembly = m_typeOwner.Assembly as RuntimeAssembly;
- Contract.Assert(assembly != null);
-
- return assembly.IsAllSecurityCritical();
- }
- else
- {
- RuntimeAssembly assembly = m_module.Assembly as RuntimeAssembly;
- Contract.Assert(assembly != null);
-
- return assembly.IsAllSecurityCritical();
- }
- }
-#endif
}
public override bool IsSecuritySafeCritical
{
-#if FEATURE_CORECLR
get { return false; }
-#else
- [SecuritySafeCritical]
- get
- {
- if (m_methodHandle != null)
- {
- return RuntimeMethodHandle.IsSecuritySafeCritical(m_methodHandle);
- }
- else if (m_typeOwner != null)
- {
- RuntimeAssembly assembly = m_typeOwner.Assembly as RuntimeAssembly;
- Contract.Assert(assembly != null);
-
- return assembly.IsAllPublicAreaSecuritySafeCritical();
- }
- else
- {
- RuntimeAssembly assembly = m_module.Assembly as RuntimeAssembly;
- Contract.Assert(assembly != null);
-
- return assembly.IsAllSecuritySafeCritical();
- }
- }
-#endif
}
public override bool IsSecurityTransparent
{
-#if FEATURE_CORECLR
get { return false; }
-#else
- [SecuritySafeCritical]
- get
- {
- if (m_methodHandle != null)
- {
- return RuntimeMethodHandle.IsSecurityTransparent(m_methodHandle);
- }
- else if (m_typeOwner != null)
- {
- RuntimeAssembly assembly = m_typeOwner.Assembly as RuntimeAssembly;
- Contract.Assert(assembly != null);
-
- return !assembly.IsAllSecurityCritical();
- }
- else
- {
- RuntimeAssembly assembly = m_module.Assembly as RuntimeAssembly;
- Contract.Assert(assembly != null);
-
- return !assembly.IsAllSecurityCritical();
- }
- }
-#endif
}
- [System.Security.SecuritySafeCritical] // auto-generated
public override Object Invoke(Object obj, BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture) {
if ((CallingConvention & CallingConventions.VarArgs) == CallingConventions.VarArgs)
throw new NotSupportedException(Environment.GetResourceString("NotSupported_CallToVarArg"));
return null;
}
- [System.Security.SecuritySafeCritical] // auto-generated
public DynamicILInfo GetDynamicILInfo()
{
#pragma warning disable 618
return GetDynamicILInfo(new DynamicScope());
}
- [System.Security.SecurityCritical] // auto-generated
internal DynamicILInfo GetDynamicILInfo(DynamicScope scope)
{
if (m_DynamicILInfo == null)
return GetILGenerator(64);
}
- [System.Security.SecuritySafeCritical] // auto-generated
public ILGenerator GetILGenerator(int streamSize)
{
if (m_ilGenerator == null)
using System.Security.Permissions;
- [HostProtection(MayLeakOnAbort = true)]
[ClassInterface(ClassInterfaceType.None)]
[ComDefaultInterface(typeof(_EnumBuilder))]
[System.Runtime.InteropServices.ComVisible(true)]
// Use this function if client decides to form the custom attribute blob themselves
-#if FEATURE_CORECLR
-[System.Security.SecurityCritical] // auto-generated
-#endif
[System.Runtime.InteropServices.ComVisible(true)]
public void SetCustomAttribute(ConstructorInfo con, byte[] binaryAttribute)
{
// Constructs a EnumBuilder.
// EnumBuilder can only be a top-level (not nested) enum type.
- [System.Security.SecurityCritical] // auto-generated
internal EnumBuilder(
String name, // name of type
Type underlyingType, // underlying type for an Enum
m_underlyingField = m_typeBuilder.DefineField("value__", underlyingType, FieldAttributes.Public | FieldAttributes.SpecialName | FieldAttributes.RTSpecialName);
}
-#if !FEATURE_CORECLR
- void _EnumBuilder.GetTypeInfoCount(out uint pcTInfo)
- {
- throw new NotImplementedException();
- }
-
- void _EnumBuilder.GetTypeInfo(uint iTInfo, uint lcid, IntPtr ppTInfo)
- {
- throw new NotImplementedException();
- }
-
- void _EnumBuilder.GetIDsOfNames([In] ref Guid riid, IntPtr rgszNames, uint cNames, uint lcid, IntPtr rgDispId)
- {
- throw new NotImplementedException();
- }
-
- void _EnumBuilder.Invoke(uint dispIdMember, [In] ref Guid riid, uint lcid, short wFlags, IntPtr pDispParams, IntPtr pVarResult, IntPtr pExcepInfo, IntPtr puArgErr)
- {
- throw new NotImplementedException();
- }
-#endif
-
-
/*****************************************************
*
* private data members
// A EventBuilder is always associated with a TypeBuilder. The TypeBuilder.DefineEvent
// method will return a new EventBuilder to a client.
//
- [HostProtection(MayLeakOnAbort = true)]
[ClassInterface(ClassInterfaceType.None)]
[ComDefaultInterface(typeof(_EventBuilder))]
[System.Runtime.InteropServices.ComVisible(true)]
return m_evToken;
}
- [System.Security.SecurityCritical] // auto-generated
private void SetMethodSemantics(MethodBuilder mdBuilder, MethodSemanticsAttributes semantics)
{
if (mdBuilder == null)
mdBuilder.GetToken().Token);
}
- [System.Security.SecuritySafeCritical] // auto-generated
public void SetAddOnMethod(MethodBuilder mdBuilder)
{
SetMethodSemantics(mdBuilder, MethodSemanticsAttributes.AddOn);
}
- [System.Security.SecuritySafeCritical] // auto-generated
public void SetRemoveOnMethod(MethodBuilder mdBuilder)
{
SetMethodSemantics(mdBuilder, MethodSemanticsAttributes.RemoveOn);
}
- [System.Security.SecuritySafeCritical] // auto-generated
public void SetRaiseMethod(MethodBuilder mdBuilder)
{
SetMethodSemantics(mdBuilder, MethodSemanticsAttributes.Fire);
}
- [System.Security.SecuritySafeCritical] // auto-generated
public void AddOtherMethod(MethodBuilder mdBuilder)
{
SetMethodSemantics(mdBuilder, MethodSemanticsAttributes.Other);
// Use this function if client decides to form the custom attribute blob themselves
-#if FEATURE_CORECLR
-[System.Security.SecurityCritical] // auto-generated
-#else
-[System.Security.SecuritySafeCritical]
-#endif
[System.Runtime.InteropServices.ComVisible(true)]
public void SetCustomAttribute(ConstructorInfo con, byte[] binaryAttribute)
{
}
// Use this function if client wishes to build CustomAttribute using CustomAttributeBuilder
- [System.Security.SecuritySafeCritical] // auto-generated
public void SetCustomAttribute(CustomAttributeBuilder customBuilder)
{
if (customBuilder == null)
customBuilder.CreateCustomAttribute(m_module, m_evToken.Token);
}
-#if !FEATURE_CORECLR
- void _EventBuilder.GetTypeInfoCount(out uint pcTInfo)
- {
- throw new NotImplementedException();
- }
-
- void _EventBuilder.GetTypeInfo(uint iTInfo, uint lcid, IntPtr ppTInfo)
- {
- throw new NotImplementedException();
- }
-
- void _EventBuilder.GetIDsOfNames([In] ref Guid riid, IntPtr rgszNames, uint cNames, uint lcid, IntPtr rgDispId)
- {
- throw new NotImplementedException();
- }
-
- void _EventBuilder.Invoke(uint dispIdMember, [In] ref Guid riid, uint lcid, short wFlags, IntPtr pDispParams, IntPtr pVarResult, IntPtr pExcepInfo, IntPtr puArgErr)
- {
- throw new NotImplementedException();
- }
-#endif
-
-
// These are package private so that TypeBuilder can access them.
private String m_name; // The name of the event
private EventToken m_evToken; // The token of this event
private EventAttributes m_attributes;
private TypeBuilder m_type;
}
-
-
-
-
}
using System.Security.Permissions;
using System.Diagnostics.Contracts;
- [HostProtection(MayLeakOnAbort = true)]
[ClassInterface(ClassInterfaceType.None)]
[ComDefaultInterface(typeof(_FieldBuilder))]
[System.Runtime.InteropServices.ComVisible(true)]
#endregion
#region Constructor
- [System.Security.SecurityCritical] // auto-generated
internal FieldBuilder(TypeBuilder typeBuilder, String fieldName, Type type,
Type[] requiredCustomModifiers, Type[] optionalCustomModifiers, FieldAttributes attributes)
{
#endregion
#region Internal Members
- [System.Security.SecurityCritical] // auto-generated
internal void SetData(byte[] data, int size)
{
ModuleBuilder.SetFieldRVAContent(m_typeBuilder.GetModuleBuilder().GetNativeHandle(), m_tkField.Token, data, size);
return m_tkField;
}
- #if FEATURE_CORECLR
- [System.Security.SecurityCritical] // auto-generated
- #else
- [System.Security.SecuritySafeCritical]
- #endif
public void SetOffset(int iOffset)
{
m_typeBuilder.ThrowIfCreated();
TypeBuilder.SetFieldLayoutOffset(m_typeBuilder.GetModuleBuilder().GetNativeHandle(), GetToken().Token, iOffset);
}
- [System.Security.SecuritySafeCritical] // auto-generated
[Obsolete("An alternate API is available: Emit the MarshalAs custom attribute instead. http://go.microsoft.com/fwlink/?linkid=14202")]
public void SetMarshal(UnmanagedMarshal unmanagedMarshal)
{
TypeBuilder.SetFieldMarshal(m_typeBuilder.GetModuleBuilder().GetNativeHandle(), GetToken().Token, ubMarshal, ubMarshal.Length);
}
- [System.Security.SecuritySafeCritical] // auto-generated
public void SetConstant(Object defaultValue)
{
m_typeBuilder.ThrowIfCreated();
}
-#if FEATURE_CORECLR
-[System.Security.SecurityCritical] // auto-generated
-#else
-[System.Security.SecuritySafeCritical]
-#endif
[System.Runtime.InteropServices.ComVisible(true)]
public void SetCustomAttribute(ConstructorInfo con, byte[] binaryAttribute)
{
m_tkField.Token, module.GetConstructorToken(con).Token, binaryAttribute, false, false);
}
- [System.Security.SecuritySafeCritical] // auto-generated
public void SetCustomAttribute(CustomAttributeBuilder customBuilder)
{
if (customBuilder == null)
}
#endregion
-
-#if !FEATURE_CORECLR
- void _FieldBuilder.GetTypeInfoCount(out uint pcTInfo)
- {
- throw new NotImplementedException();
- }
-
- void _FieldBuilder.GetTypeInfo(uint iTInfo, uint lcid, IntPtr ppTInfo)
- {
- throw new NotImplementedException();
- }
-
- void _FieldBuilder.GetIDsOfNames([In] ref Guid riid, IntPtr rgszNames, uint cNames, uint lcid, IntPtr rgDispId)
- {
- throw new NotImplementedException();
- }
-
- void _FieldBuilder.Invoke(uint dispIdMember, [In] ref Guid riid, uint lcid, short wFlags, IntPtr pDispParams, IntPtr pVarResult, IntPtr pExcepInfo, IntPtr puArgErr)
- {
- throw new NotImplementedException();
- }
-#endif
}
}
#endregion
#region Public Members
- #if FEATURE_CORECLR
- [System.Security.SecurityCritical] // auto-generated
- #endif
public void SetCustomAttribute(ConstructorInfo con, byte[] binaryAttribute)
{
m_type.SetGenParamCustomAttribute(con, binaryAttribute);
using System.Reflection;
using System.Security.Permissions;
using System.Globalization;
+ using System.Diagnostics;
using System.Diagnostics.Contracts;
[ClassInterface(ClassInterfaceType.None)]
}
}
- [System.Security.SecurityCritical] // auto-generated
private int GetMethodToken(MethodBase method, Type[] optionalParameterTypes, bool useMethodDef)
{
return ((ModuleBuilder)m_methodBuilder.Module).GetMethodTokenInternal(method, optionalParameterTypes, useMethodDef);
}
- [System.Security.SecurityCritical] // auto-generated
internal virtual SignatureHelper GetMemberRefSignature(CallingConventions call, Type returnType,
Type[] parameterTypes, Type[] optionalParameterTypes)
{
return GetMemberRefSignature(call, returnType, parameterTypes, optionalParameterTypes, 0);
}
- [System.Security.SecurityCritical] // auto-generated
private SignatureHelper GetMemberRefSignature(CallingConventions call, Type returnType,
Type[] parameterTypes, Type[] optionalParameterTypes, int cGenericParameters)
{
{
if (m_RelocFixupCount == 0)
{
- Contract.Assert(m_RelocFixupList == null);
+ Debug.Assert(m_RelocFixupList == null);
return null;
}
PutInteger4(arg);
}
- [System.Security.SecuritySafeCritical] // auto-generated
public virtual void Emit(OpCode opcode, MethodInfo meth)
{
if (meth == null)
}
- [System.Security.SecuritySafeCritical] // auto-generated
public virtual void EmitCalli(OpCode opcode, CallingConventions callingConvention,
Type returnType, Type[] parameterTypes, Type[] optionalParameterTypes)
{
PutInteger4(modBuilder.GetSignatureToken(sig).Token);
}
- [System.Security.SecuritySafeCritical] // auto-generated
public virtual void EmitCall(OpCode opcode, MethodInfo methodInfo, Type[] optionalParameterTypes)
{
if (methodInfo == null)
// SignatureHelper.
if (opcode.StackBehaviourPop == StackBehaviour.Varpop)
{
- Contract.Assert(opcode.Equals(OpCodes.Calli),
+ Debug.Assert(opcode.Equals(OpCodes.Calli),
"Unexpected opcode encountered for StackBehaviour VarPop.");
// Pop the arguments..
stackchange -= signature.ArgumentCount;
PutInteger4(tempVal);
}
- [System.Security.SecuritySafeCritical] // auto-generated
[System.Runtime.InteropServices.ComVisible(true)]
public virtual void Emit(OpCode opcode, ConstructorInfo con)
{
if (opcode.StackBehaviourPush == StackBehaviour.Varpush)
{
// Instruction must be one of call or callvirt.
- Contract.Assert(opcode.Equals(OpCodes.Call) ||
+ Debug.Assert(opcode.Equals(OpCodes.Call) ||
opcode.Equals(OpCodes.Callvirt),
"Unexpected opcode encountered for StackBehaviour of VarPush.");
stackchange++;
if (opcode.StackBehaviourPop == StackBehaviour.Varpop)
{
// Instruction must be one of call, callvirt or newobj.
- Contract.Assert(opcode.Equals(OpCodes.Call) ||
+ Debug.Assert(opcode.Equals(OpCodes.Call) ||
opcode.Equals(OpCodes.Callvirt) ||
opcode.Equals(OpCodes.Newobj),
"Unexpected opcode encountered for StackBehaviour of VarPop.");
PutInteger4(tk);
}
- [System.Security.SecuritySafeCritical] // auto-generated
public virtual void Emit(OpCode opcode, Type cls)
{
// Puts opcode onto the stream and then the metadata token represented
m_ILStream[m_length++] = (byte) (arg>>56);
}
- [System.Security.SecuritySafeCritical] // auto-generated
unsafe public virtual void Emit(OpCode opcode, float arg) {
EnsureCapacity(7);
InternalEmit(opcode);
m_ILStream[m_length++] = (byte) (tempVal>>24);
}
- [System.Security.SecuritySafeCritical] // auto-generated
unsafe public virtual void Emit(OpCode opcode, double arg) {
EnsureCapacity(11);
InternalEmit(opcode);
#endregion
#endregion
-
-#if !FEATURE_CORECLR
- void _ILGenerator.GetTypeInfoCount(out uint pcTInfo)
- {
- throw new NotImplementedException();
- }
-
- void _ILGenerator.GetTypeInfo(uint iTInfo, uint lcid, IntPtr ppTInfo)
- {
- throw new NotImplementedException();
- }
-
- void _ILGenerator.GetIDsOfNames([In] ref Guid riid, IntPtr rgszNames, uint cNames, uint lcid, IntPtr rgDispId)
- {
- throw new NotImplementedException();
- }
-
- void _ILGenerator.Invoke(uint dispIdMember, [In] ref Guid riid, uint lcid, short wFlags, IntPtr pDispParams, IntPtr pVarResult, IntPtr pExcepInfo, IntPtr puArgErr)
- {
- throw new NotImplementedException();
- }
-#endif
}
internal struct __FixupData
m_catchAddr[m_currentCatch] = -1;
if (m_currentCatch > 0)
{
- Contract.Assert(m_catchEndAddr[m_currentCatch-1] == -1,"m_catchEndAddr[m_currentCatch-1] == -1");
+ Debug.Assert(m_catchEndAddr[m_currentCatch-1] == -1,"m_catchEndAddr[m_currentCatch-1] == -1");
m_catchEndAddr[m_currentCatch-1] = catchorfilterAddr;
}
}
{
if (m_type[m_currentCatch] != Filter)
{
- Contract.Assert(m_catchEndAddr[m_currentCatch-1] == -1,"m_catchEndAddr[m_currentCatch-1] == -1");
+ Debug.Assert(m_catchEndAddr[m_currentCatch-1] == -1,"m_catchEndAddr[m_currentCatch-1] == -1");
m_catchEndAddr[m_currentCatch-1] = catchEndAddr;
}
}
}
internal void Done(int endAddr) {
- Contract.Assert(m_currentCatch > 0,"m_currentCatch > 0");
- Contract.Assert(m_catchAddr[m_currentCatch-1] > 0,"m_catchAddr[m_currentCatch-1] > 0");
- Contract.Assert(m_catchEndAddr[m_currentCatch-1] == -1,"m_catchEndAddr[m_currentCatch-1] == -1");
+ Debug.Assert(m_currentCatch > 0,"m_currentCatch > 0");
+ Debug.Assert(m_catchAddr[m_currentCatch-1] > 0,"m_catchAddr[m_currentCatch-1] > 0");
+ Debug.Assert(m_catchEndAddr[m_currentCatch-1] == -1,"m_catchEndAddr[m_currentCatch-1] == -1");
m_catchEndAddr[m_currentCatch-1] = endAddr;
m_currentState = State_Done;
}
// not having a nesting relation.
internal bool IsInner(__ExceptionInfo exc) {
Contract.Requires(exc != null);
- Contract.Assert(m_currentCatch > 0,"m_currentCatch > 0");
- Contract.Assert(exc.m_currentCatch > 0,"exc.m_currentCatch > 0");
+ Debug.Assert(m_currentCatch > 0,"m_currentCatch > 0");
+ Debug.Assert(exc.m_currentCatch > 0,"exc.m_currentCatch > 0");
int exclast = exc.m_currentCatch - 1;
int last = m_currentCatch - 1;
return true;
else if (exc.m_catchEndAddr[exclast] == m_catchEndAddr[last])
{
- Contract.Assert(exc.GetEndAddress() != GetEndAddress(),
+ Debug.Assert(exc.GetEndAddress() != GetEndAddress(),
"exc.GetEndAddress() != GetEndAddress()");
if (exc.GetEndAddress() > GetEndAddress())
return true;
}
}
- #if FEATURE_CORECLR
- [System.Security.SecurityCritical] // auto-generated
- #endif
internal void EmitScopeTree(ISymbolWriter symWriter)
{
int i;
// make sure that arrays are large enough to hold addition info
i = FindDocument(document);
- Contract.Assert(i < m_DocumentCount, "Bad document look up!");
+ Debug.Assert(i < m_DocumentCount, "Bad document look up!");
m_Documents[i].AddLineNumberInfo(document, iOffset, iStartLine, iStartColumn, iEndLine, iEndColumn);
}
}
}
- #if FEATURE_CORECLR
- [System.Security.SecurityCritical] // auto-generated
- #endif
internal void EmitLineNumberInfo(ISymbolWriter symWriter)
{
for (int i = 0; i < m_DocumentCount; i++)
int iEndLine,
int iEndColumn)
{
- Contract.Assert(document == m_document, "Bad document look up!");
+ Debug.Assert(document == m_document, "Bad document look up!");
// make sure that arrays are large enough to hold addition info
EnsureCapacity();
}
}
- #if FEATURE_CORECLR
- [System.Security.SecurityCritical] // auto-generated
- #endif
internal void EmitLineNumberInfo(ISymbolWriter symWriter)
{
int[] iOffsetsTemp;
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
-//
-
-#if FEATURE_CORECLR
-
namespace System.Reflection.Emit
{
using System;
using System.Runtime.CompilerServices;
using System.Diagnostics.SymbolStore;
-
//-----------------------------------------------------------------------------------
// On Telesto, we don't ship the ISymWrapper.dll assembly. However, ReflectionEmit
// relies on that assembly to write out managed PDBs.
//------------------------------------------------------------------------------
// Ctor
//------------------------------------------------------------------------------
- #if FEATURE_CORECLR
- [System.Security.SecurityCritical] // auto-generated
- #endif
internal SymDocumentWriter(PunkSafeHandle pDocumentWriterSafeHandle)
{
m_pDocumentWriterSafeHandle = pDocumentWriterSafeHandle;
//------------------------------------------------------------------------------
// Returns the underlying ISymUnmanagedDocumentWriter* (as a safehandle.)
//------------------------------------------------------------------------------
- #if FEATURE_CORECLR
- [System.Security.SecurityCritical] // auto-generated
- #endif
internal PunkSafeHandle GetUnmanaged()
{
return m_pDocumentWriterSafeHandle;
//------------------------------------------------------------------------------
// SetCheckSum() wrapper
//------------------------------------------------------------------------------
- #if FEATURE_CORECLR
- [System.Security.SecuritySafeCritical]
- #endif
void ISymbolDocumentWriter.SetCheckSum(Guid algorithmId, byte [] checkSum)
{
int hr = m_vtable.SetCheckSum(m_pDocWriter, algorithmId, (uint)checkSum.Length, checkSum);
}
}
- [System.Security.SecurityCritical]
private delegate int DSetCheckSum(ISymUnmanagedDocumentWriter * pThis, Guid algorithmId, uint checkSumSize, [In] byte[] checkSum);
//------------------------------------------------------------------------------
// exactly. If a member is declared as an IntPtr rather than a delegate, it means
// we don't call that particular member.
//------------------------------------------------------------------------------
- [System.Security.SecurityCritical]
[StructLayout(LayoutKind.Sequential)]
private struct ISymUnmanagedDocumentWriterVTable
{
internal IntPtr Release;
internal IntPtr SetSource;
- #if FEATURE_CORECLR
- [System.Security.SecurityCritical]
- #endif
internal DSetCheckSum SetCheckSum;
}
// This layout must match the (start) of the unmanaged ISymUnmanagedDocumentWriter
// COM object.
//------------------------------------------------------------------------------
- [System.Security.SecurityCritical]
[StructLayout(LayoutKind.Sequential)]
private struct ISymUnmanagedDocumentWriter
{
//------------------------------------------------------------------------------
// Stores underlying ISymUnmanagedDocumentWriter* pointer (wrapped in a safehandle.)
//------------------------------------------------------------------------------
- #if FEATURE_CORECLR
- [System.Security.SecurityCritical] // auto-generated
- #endif
private PunkSafeHandle m_pDocumentWriterSafeHandle;
- [SecurityCritical]
private ISymUnmanagedDocumentWriter * m_pDocWriter;
//------------------------------------------------------------------------------
// Stores the "managed vtable" (actually a structure full of delegates that
// P/Invoke to the corresponding unmanaged COM methods.)
//------------------------------------------------------------------------------
- [SecurityCritical]
private ISymUnmanagedDocumentWriterVTable m_vtable;
//------------------------------------------------------------------------------
// DefineDocument() wrapper
//------------------------------------------------------------------------------
- #if FEATURE_CORECLR
- [System.Security.SecurityCritical] // auto-generated
- #endif
ISymbolDocumentWriter ISymbolWriter.DefineDocument(String url,
Guid language,
Guid languageVendor,
//------------------------------------------------------------------------------
// SetUserEntryPoint() wrapper
//------------------------------------------------------------------------------
- #if FEATURE_CORECLR
- [System.Security.SecurityCritical] // auto-generated
- #endif
void ISymbolWriter.SetUserEntryPoint(SymbolToken entryMethod)
{
int hr = m_vtable.SetUserEntryPoint(m_pWriter, entryMethod.GetToken());
//------------------------------------------------------------------------------
// OpenMethod() wrapper
//------------------------------------------------------------------------------
- #if FEATURE_CORECLR
- [System.Security.SecurityCritical] // auto-generated
- #endif
void ISymbolWriter.OpenMethod(SymbolToken method)
{
int hr = m_vtable.OpenMethod(m_pWriter, method.GetToken());
//------------------------------------------------------------------------------
// CloseMethod() wrapper
//------------------------------------------------------------------------------
- #if FEATURE_CORECLR
- [System.Security.SecurityCritical] // auto-generated
- #endif
void ISymbolWriter.CloseMethod()
{
int hr = m_vtable.CloseMethod(m_pWriter);
//------------------------------------------------------------------------------
// DefineSequencePoints() wrapper
//------------------------------------------------------------------------------
- #if FEATURE_CORECLR
- [System.Security.SecurityCritical] // auto-generated
- #endif
void ISymbolWriter.DefineSequencePoints(ISymbolDocumentWriter document,
int[] offsets,
int[] lines,
//------------------------------------------------------------------------------
// OpenScope() wrapper
//------------------------------------------------------------------------------
- #if FEATURE_CORECLR
- [System.Security.SecurityCritical] // auto-generated
- #endif
int ISymbolWriter.OpenScope(int startOffset)
{
int ret;
//------------------------------------------------------------------------------
// CloseScope() wrapper
//------------------------------------------------------------------------------
- #if FEATURE_CORECLR
- [System.Security.SecurityCritical] // auto-generated
- #endif
void ISymbolWriter.CloseScope(int endOffset)
{
int hr = m_vtable.CloseScope(m_pWriter, endOffset);
//------------------------------------------------------------------------------
// DefineLocalVariable() wrapper
//------------------------------------------------------------------------------
- #if FEATURE_CORECLR
- [System.Security.SecurityCritical] // auto-generated
- #endif
void ISymbolWriter.DefineLocalVariable(String name,
FieldAttributes attributes,
byte[] signature,
//------------------------------------------------------------------------------
// SetSymAttribute() wrapper
//------------------------------------------------------------------------------
- #if FEATURE_CORECLR
- [System.Security.SecurityCritical] // auto-generated
- #endif
void ISymbolWriter.SetSymAttribute(SymbolToken parent, String name, byte[] data)
{
int hr = m_vtable.SetSymAttribute(m_pWriter, parent.GetToken(), name, data.Length, data);
//------------------------------------------------------------------------------
// UsingNamespace() wrapper
//------------------------------------------------------------------------------
- #if FEATURE_CORECLR
- [System.Security.SecurityCritical] // auto-generated
- #endif
void ISymbolWriter.UsingNamespace(String name)
{
int hr = m_vtable.UsingNamespace(m_pWriter, name);
// with the real ISymWrapper.dll, ISymWrapper performs *no* Release (or AddRef) on pointers
// furnished through SetUnderlyingWriter. Lifetime management is entirely up to the caller.
//------------------------------------------------------------------------------
- #if FEATURE_CORECLR
- [System.Security.SecurityCritical] // auto-generated
- #endif
internal void InternalSetUnderlyingWriter(IntPtr ppUnderlyingWriter)
{
m_pWriter = *((ISymUnmanagedWriter**)ppUnderlyingWriter);
//------------------------------------------------------------------------------
// Define delegates for the unmanaged COM methods we invoke.
//------------------------------------------------------------------------------
- [System.Security.SecurityCritical]
private delegate int DInitialize(ISymUnmanagedWriter* pthis,
IntPtr emitter, //IUnknown*
[MarshalAs(UnmanagedType.LPWStr)] String filename, //WCHAR*
[MarshalAs(UnmanagedType.Bool)] bool fFullBuild
);
- [System.Security.SecurityCritical]
private delegate int DDefineDocument(ISymUnmanagedWriter* pthis,
[MarshalAs(UnmanagedType.LPWStr)] String url,
[In] ref Guid language,
[Out] out PunkSafeHandle ppsymUnmanagedDocumentWriter
);
- [System.Security.SecurityCritical]
private delegate int DSetUserEntryPoint(ISymUnmanagedWriter* pthis, int entryMethod);
- [System.Security.SecurityCritical]
private delegate int DOpenMethod(ISymUnmanagedWriter* pthis, int entryMethod);
- [System.Security.SecurityCritical]
private delegate int DCloseMethod(ISymUnmanagedWriter* pthis);
- [System.Security.SecurityCritical]
private delegate int DDefineSequencePoints(ISymUnmanagedWriter* pthis,
PunkSafeHandle document,
int spCount,
[In] int[] endLines,
[In] int[] endColumns);
- [System.Security.SecurityCritical]
private delegate int DOpenScope(ISymUnmanagedWriter* pthis, int startOffset, [Out] out int pretval);
- [System.Security.SecurityCritical]
private delegate int DCloseScope(ISymUnmanagedWriter* pthis, int endOffset);
- [System.Security.SecurityCritical]
private delegate int DSetScopeRange(ISymUnmanagedWriter* pthis, int scopeID, int startOffset, int endOffset);
- [System.Security.SecurityCritical]
private delegate int DDefineLocalVariable(ISymUnmanagedWriter* pthis,
[MarshalAs(UnmanagedType.LPWStr)] String name,
int attributes,
int endOffset
);
- [System.Security.SecurityCritical]
private delegate int DClose(ISymUnmanagedWriter* pthis);
- [System.Security.SecurityCritical]
private delegate int DSetSymAttribute(ISymUnmanagedWriter* pthis,
int parent,
[MarshalAs(UnmanagedType.LPWStr)] String name,
);
- [System.Security.SecurityCritical]
private delegate int DOpenNamespace(ISymUnmanagedWriter* pthis, [MarshalAs(UnmanagedType.LPWStr)] String name);
- [System.Security.SecurityCritical]
private delegate int DCloseNamespace(ISymUnmanagedWriter* pthis);
- [System.Security.SecurityCritical]
private delegate int DUsingNamespace(ISymUnmanagedWriter* pthis, [MarshalAs(UnmanagedType.LPWStr)] String name);
internal IntPtr AddRef;
internal IntPtr Release;
- #if FEATURE_CORECLR
- [System.Security.SecurityCritical] // auto-generated
- #endif
internal DDefineDocument DefineDocument;
- #if FEATURE_CORECLR
- [System.Security.SecurityCritical] // auto-generated
- #endif
internal DSetUserEntryPoint SetUserEntryPoint;
- #if FEATURE_CORECLR
- [System.Security.SecurityCritical] // auto-generated
- #endif
internal DOpenMethod OpenMethod;
- #if FEATURE_CORECLR
- [System.Security.SecurityCritical] // auto-generated
- #endif
internal DCloseMethod CloseMethod;
- #if FEATURE_CORECLR
- [System.Security.SecurityCritical] // auto-generated
- #endif
internal DOpenScope OpenScope;
- #if FEATURE_CORECLR
- [System.Security.SecurityCritical] // auto-generated
- #endif
internal DCloseScope CloseScope;
- #if FEATURE_CORECLR
- [System.Security.SecurityCritical] // auto-generated
- #endif
internal DSetScopeRange SetScopeRange;
- #if FEATURE_CORECLR
- [System.Security.SecurityCritical] // auto-generated
- #endif
internal DDefineLocalVariable DefineLocalVariable;
internal IntPtr DefineParameter;
internal IntPtr DefineField;
internal IntPtr DefineGlobalVariable;
- #if FEATURE_CORECLR
- [System.Security.SecurityCritical] // auto-generated
- #endif
internal DClose Close;
- #if FEATURE_CORECLR
- [System.Security.SecurityCritical] // auto-generated
- #endif
internal DSetSymAttribute SetSymAttribute;
- #if FEATURE_CORECLR
- [System.Security.SecurityCritical] // auto-generated
- #endif
internal DOpenNamespace OpenNamespace;
- #if FEATURE_CORECLR
- [System.Security.SecurityCritical] // auto-generated
- #endif
internal DCloseNamespace CloseNamespace;
- #if FEATURE_CORECLR
- [System.Security.SecurityCritical] // auto-generated
- #endif
internal DUsingNamespace UsingNamespace;
internal IntPtr SetMethodSourceRange;
- #if FEATURE_CORECLR
- [System.Security.SecurityCritical] // auto-generated
- #endif
internal DInitialize Initialize;
internal IntPtr GetDebugInfo;
- #if FEATURE_CORECLR
- [System.Security.SecurityCritical] // auto-generated
- #endif
internal DDefineSequencePoints DefineSequencePoints;
}
// As with the real ISymWrapper.dll, ISymWrapper performs *no* Release (or AddRef) on this pointer.
// Managing lifetime is up to the caller (coreclr.dll).
//------------------------------------------------------------------------------
- [SecurityCritical]
private ISymUnmanagedWriter *m_pWriter;
//------------------------------------------------------------------------------
//
// Had to make this a non-nested class since FCall's don't like to bind to nested classes.
//--------------------------------------------------------------------------------------
- #if FEATURE_CORECLR
- [System.Security.SecurityCritical] // auto-generated
- #endif
sealed class PunkSafeHandle : SafeHandle
{
- #if FEATURE_CORECLR
- [System.Security.SecurityCritical] // auto-generated
- #endif
internal PunkSafeHandle()
: base((IntPtr)0, true)
{
}
- [SecurityCritical]
override protected bool ReleaseHandle()
{
m_Release(handle);
public override bool IsInvalid
{
- [SecurityCritical]
get { return handle == ((IntPtr)0); }
}
[MethodImplAttribute(MethodImplOptions.InternalCall)]
private static extern IntPtr nGetDReleaseTarget(); // FCall gets us the native DRelease target (so we don't need named dllexport from coreclr.dll)
- #if FEATURE_CORECLR
- [System.Security.SecurityCritical] // auto-generated
- #endif
static PunkSafeHandle()
{
m_Release = (DRelease)(Marshal.GetDelegateForFunctionPointer(nGetDReleaseTarget(), typeof(DRelease)));
m_Release((IntPtr)0); // make one call to make sure the delegate is fully prepped before we're in the critical finalizer situation.
}
-
} // PunkSafeHandle
-
} //namespace System.Reflection.Emit
-
-
-#endif //FEATURE_CORECLR
-
}
}
#endregion
-
-#if !FEATURE_CORECLR
- void _LocalBuilder.GetTypeInfoCount(out uint pcTInfo)
- {
- throw new NotImplementedException();
- }
-
- void _LocalBuilder.GetTypeInfo(uint iTInfo, uint lcid, IntPtr ppTInfo)
- {
- throw new NotImplementedException();
- }
-
- void _LocalBuilder.GetIDsOfNames([In] ref Guid riid, IntPtr rgszNames, uint cNames, uint lcid, IntPtr rgDispId)
- {
- throw new NotImplementedException();
- }
-
- void _LocalBuilder.Invoke(uint dispIdMember, [In] ref Guid riid, uint lcid, short wFlags, IntPtr pDispParams, IntPtr pVarResult, IntPtr pExcepInfo, IntPtr puArgErr)
- {
- throw new NotImplementedException();
- }
-#endif
}
}
using System.Collections.Generic;
using System.Security.Permissions;
using System.Runtime.InteropServices;
+ using System.Diagnostics;
using System.Diagnostics.Contracts;
- [HostProtection(MayLeakOnAbort = true)]
[ClassInterface(ClassInterfaceType.None)]
[ComDefaultInterface(typeof(_MethodBuilder))]
-[System.Runtime.InteropServices.ComVisible(true)]
+ [System.Runtime.InteropServices.ComVisible(true)]
public sealed class MethodBuilder : MethodInfo, _MethodBuilder
{
#region Private Data Members
m_module.CheckContext(types);
}
- [System.Security.SecurityCritical] // auto-generated
internal void CreateMethodBodyHelper(ILGenerator il)
{
// Sets the IL of the method. An ILGenerator is passed as an argument and the method
}
else
{
- Contract.Assert(false, "We should never get here!");
+ Debug.Assert(false, "We should never get here!");
return null;
}
}
return m_mdMethodFixups;
}
- [System.Security.SecurityCritical] // auto-generated
internal SignatureHelper GetMethodSignature()
{
if (m_parameterTypes == null)
#endregion
#region Object Overrides
- [System.Security.SecuritySafeCritical] // auto-generated
public override bool Equals(Object obj) {
if (!(obj is MethodBuilder)) {
return false;
return this.m_strName.GetHashCode();
}
- [System.Security.SecuritySafeCritical] // auto-generated
public override String ToString()
{
StringBuilder sb = new StringBuilder(1000);
public override bool IsSecurityCritical
{
-#if FEATURE_CORECLR
get { return true; }
-#else
- get { throw new NotSupportedException(Environment.GetResourceString("NotSupported_DynamicModule")); }
-#endif
}
public override bool IsSecuritySafeCritical
{
-#if FEATURE_CORECLR
get { return false; }
-#else
- get { throw new NotSupportedException(Environment.GetResourceString("NotSupported_DynamicModule")); }
-#endif
}
public override bool IsSecurityTransparent
{
-#if FEATURE_CORECLR
get { return false; }
-#else
- get { throw new NotSupportedException(Environment.GetResourceString("NotSupported_DynamicModule")); }
-#endif
}
#endregion
#endregion
#region Public Members
- [System.Security.SecuritySafeCritical] // auto-generated
public MethodToken GetToken()
{
// We used to always "tokenize" a MethodBuilder when it is constructed. After change list 709498
m_containingType.m_lastTokenizedMethod = i;
}
- Contract.Assert(currentMethod == this, "We should have found this method in m_containingType.m_listMethods");
- Contract.Assert(currentToken.Token != 0, "The token should not be 0");
+ Debug.Assert(currentMethod == this, "We should have found this method in m_containingType.m_listMethods");
+ Debug.Assert(currentToken.Token != 0, "The token should not be 0");
return currentToken;
}
- [System.Security.SecurityCritical] // auto-generated
private MethodToken GetTokenNoLock()
{
- Contract.Assert(m_tkMethod.Token == 0, "m_tkMethod should not have been initialized");
+ Debug.Assert(m_tkMethod.Token == 0, "m_tkMethod should not have been initialized");
int sigLength;
byte[] sigBytes = GetMethodSignature().InternalGetSignature(out sigLength);
}
- [System.Security.SecuritySafeCritical] // auto-generated
public ParameterBuilder DefineParameter(int position, ParameterAttributes attributes, String strParamName)
{
if (position < 0)
return new ParameterBuilder(this, position, attributes, strParamName);
}
- [System.Security.SecuritySafeCritical] // auto-generated
[Obsolete("An alternate API is available: Emit the MarshalAs custom attribute instead. http://go.microsoft.com/fwlink/?linkid=14202")]
public void SetMarshal(UnmanagedMarshal unmanagedMarshal)
{
m_symCustomAttrs.Add(new SymCustomAttr(name, data));
}
-#if FEATURE_CAS_POLICY
- [System.Security.SecuritySafeCritical] // auto-generated
- public void AddDeclarativeSecurity(SecurityAction action, PermissionSet pset)
- {
- if (pset == null)
- throw new ArgumentNullException(nameof(pset));
- Contract.EndContractBlock();
-
- ThrowIfGeneric ();
-
-#pragma warning disable 618
- if (!Enum.IsDefined(typeof(SecurityAction), action) ||
- action == SecurityAction.RequestMinimum ||
- action == SecurityAction.RequestOptional ||
- action == SecurityAction.RequestRefuse)
- {
- throw new ArgumentOutOfRangeException(nameof(action));
- }
-#pragma warning restore 618
-
- // cannot declarative security after type is created
- m_containingType.ThrowIfCreated();
-
- // Translate permission set into serialized format (uses standard binary serialization format).
- byte[] blob = null;
- int length = 0;
- if (!pset.IsEmpty())
- {
- blob = pset.EncodeXml();
- length = blob.Length;
- }
-
- // Write the blob into the metadata.
- TypeBuilder.AddDeclarativeSecurity(m_module.GetNativeHandle(), MetadataTokenInternal, action, blob, length);
- }
-#endif // FEATURE_CAS_POLICY
-
- #if FEATURE_CORECLR
- [System.Security.SecurityCritical] // auto-generated
- #endif
public void SetMethodBody(byte[] il, int maxStack, byte[] localSignature, IEnumerable<ExceptionHandler> exceptionHandlers, IEnumerable<int> tokenFixups)
{
if (il == null)
/// <summary>
/// Obsolete.
/// </summary>
- #if FEATURE_CORECLR
- [System.Security.SecurityCritical] // auto-generated
- #endif
public void CreateMethodBody(byte[] il, int count)
{
ThrowIfGeneric();
m_bIsBaked = true;
}
- [System.Security.SecuritySafeCritical] // auto-generated
public void SetImplementationFlags(MethodImplAttributes attributes)
{
ThrowIfGeneric ();
public String Signature
{
- [System.Security.SecuritySafeCritical] // auto-generated
get
{
return GetMethodSignature().ToString();
}
-#if FEATURE_CORECLR
-[System.Security.SecurityCritical] // auto-generated
-#else
-[System.Security.SecuritySafeCritical]
-#endif
[System.Runtime.InteropServices.ComVisible(true)]
public void SetCustomAttribute(ConstructorInfo con, byte[] binaryAttribute)
{
ParseCA(con, binaryAttribute);
}
- [System.Security.SecuritySafeCritical] // auto-generated
public void SetCustomAttribute(CustomAttributeBuilder customBuilder)
{
if (customBuilder == null)
internal bool m_isDllImport = false;
#endregion
-
-#if !FEATURE_CORECLR
- void _MethodBuilder.GetTypeInfoCount(out uint pcTInfo)
- {
- throw new NotImplementedException();
- }
-
- void _MethodBuilder.GetTypeInfo(uint iTInfo, uint lcid, IntPtr ppTInfo)
- {
- throw new NotImplementedException();
- }
-
- void _MethodBuilder.GetIDsOfNames([In] ref Guid riid, IntPtr rgszNames, uint cNames, uint lcid, IntPtr rgDispId)
- {
- throw new NotImplementedException();
- }
-
- void _MethodBuilder.Invoke(uint dispIdMember, [In] ref Guid riid, uint lcid, short wFlags, IntPtr pDispParams, IntPtr pVarResult, IntPtr pExcepInfo, IntPtr puArgErr)
- {
- throw new NotImplementedException();
- }
-#endif
-
}
internal class LocalSymInfo
checked { m_iNameSpaceCount++; }
}
- #if FEATURE_CORECLR
- [System.Security.SecurityCritical] // auto-generated
- #endif
internal virtual void EmitLocalSymInfo(ISymbolWriter symWriter)
{
int i;
internal ExceptionHandler(int tryStartOffset, int tryEndOffset, int filterOffset, int handlerStartOffset, int handlerEndOffset,
int kind, int exceptionTypeToken)
{
- Contract.Assert(tryStartOffset >= 0);
- Contract.Assert(tryEndOffset >= 0);
- Contract.Assert(filterOffset >= 0);
- Contract.Assert(handlerStartOffset >= 0);
- Contract.Assert(handlerEndOffset >= 0);
- Contract.Assert(IsValidKind((ExceptionHandlingClauseOptions)kind));
- Contract.Assert(kind != (int)ExceptionHandlingClauseOptions.Clause || (exceptionTypeToken & 0x00FFFFFF) != 0);
+ Debug.Assert(tryStartOffset >= 0);
+ Debug.Assert(tryEndOffset >= 0);
+ Debug.Assert(filterOffset >= 0);
+ Debug.Assert(handlerStartOffset >= 0);
+ Debug.Assert(handlerEndOffset >= 0);
+ Debug.Assert(IsValidKind((ExceptionHandlingClauseOptions)kind));
+ Debug.Assert(kind != (int)ExceptionHandlingClauseOptions.Clause || (exceptionTypeToken & 0x00FFFFFF) != 0);
m_tryStartOffset = tryStartOffset;
m_tryEndOffset = tryEndOffset;
using System.Diagnostics.SymbolStore;
using System.Globalization;
using System.Reflection;
- using System.Diagnostics;
using System.IO;
using System.Resources;
using System.Security;
using System.Threading;
using System.Runtime.Versioning;
using System.Runtime.CompilerServices;
+ using System.Diagnostics;
using System.Diagnostics.Contracts;
internal sealed class InternalModuleBuilder : RuntimeModule
}
// deliberately not [serializable]
- [HostProtection(MayLeakOnAbort = true)]
[ClassInterface(ClassInterfaceType.None)]
[ComDefaultInterface(typeof(_ModuleBuilder))]
[System.Runtime.InteropServices.ComVisible(true)]
private Dictionary<string, Type> m_TypeBuilderDict;
private ISymbolWriter m_iSymWriter;
internal ModuleBuilderData m_moduleData;
-#if !FEATURE_CORECLR
- private MethodToken m_EntryPoint;
-#endif //!FEATURE_CORECLR
internal InternalModuleBuilder m_internalModuleBuilder;
// This is the "external" AssemblyBuilder
// only the "external" ModuleBuilder has this set
}
- [System.Security.SecurityCritical] // auto-generated
[DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
[SuppressUnmanagedCodeSecurity]
private extern static int GetTypeRef(RuntimeModule module, String strFullName, RuntimeModule refedModule, String strRefedModuleFileName, int tkResolution);
- [System.Security.SecurityCritical] // auto-generated
[DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
[SuppressUnmanagedCodeSecurity]
private extern static int GetMemberRef(RuntimeModule module, RuntimeModule refedModule, int tr, int defToken);
- [System.Security.SecurityCritical] // auto-generated
private int GetMemberRef(Module refedModule, int tr, int defToken)
{
return GetMemberRef(GetNativeHandle(), GetRuntimeModuleFromModule(refedModule).GetNativeHandle(), tr, defToken);
}
- [System.Security.SecurityCritical] // auto-generated
[DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
[SuppressUnmanagedCodeSecurity]
private extern static int GetMemberRefFromSignature(RuntimeModule module, int tr, String methodName, byte[] signature, int length);
- [System.Security.SecurityCritical] // auto-generated
private int GetMemberRefFromSignature(int tr, String methodName, byte[] signature, int length)
{
return GetMemberRefFromSignature(GetNativeHandle(), tr, methodName, signature, length);
}
- [System.Security.SecurityCritical] // auto-generated
[DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
[SuppressUnmanagedCodeSecurity]
private extern static int GetMemberRefOfMethodInfo(RuntimeModule module, int tr, IRuntimeMethodInfo method);
- [System.Security.SecurityCritical] // auto-generated
private int GetMemberRefOfMethodInfo(int tr, RuntimeMethodInfo method)
{
- Contract.Assert(method != null);
+ Debug.Assert(method != null);
#if FEATURE_APPX
if (ContainingAssemblyBuilder.ProfileAPICheck)
return GetMemberRefOfMethodInfo(GetNativeHandle(), tr, method);
}
- [System.Security.SecurityCritical] // auto-generated
private int GetMemberRefOfMethodInfo(int tr, RuntimeConstructorInfo method)
{
- Contract.Assert(method != null);
+ Debug.Assert(method != null);
#if FEATURE_APPX
if (ContainingAssemblyBuilder.ProfileAPICheck)
return GetMemberRefOfMethodInfo(GetNativeHandle(), tr, method);
}
- [System.Security.SecurityCritical] // auto-generated
[DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
[SuppressUnmanagedCodeSecurity]
private extern static int GetMemberRefOfFieldInfo(RuntimeModule module, int tkType, RuntimeTypeHandle declaringType, int tkField);
- [System.Security.SecurityCritical] // auto-generated
private int GetMemberRefOfFieldInfo(int tkType, RuntimeTypeHandle declaringType, RuntimeFieldInfo runtimeField)
{
- Contract.Assert(runtimeField != null);
+ Debug.Assert(runtimeField != null);
#if FEATURE_APPX
if (ContainingAssemblyBuilder.ProfileAPICheck)
return GetMemberRefOfFieldInfo(GetNativeHandle(), tkType, declaringType, runtimeField.MetadataToken);
}
- [System.Security.SecurityCritical] // auto-generated
[DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
[SuppressUnmanagedCodeSecurity]
private extern static int GetTokenFromTypeSpec(RuntimeModule pModule, byte[] signature, int length);
- [System.Security.SecurityCritical] // auto-generated
private int GetTokenFromTypeSpec(byte[] signature, int length)
{
return GetTokenFromTypeSpec(GetNativeHandle(), signature, length);
}
- [System.Security.SecurityCritical] // auto-generated
[DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
[SuppressUnmanagedCodeSecurity]
private extern static int GetArrayMethodToken(RuntimeModule module, int tkTypeSpec, String methodName, byte[] signature, int sigLength);
- [System.Security.SecurityCritical] // auto-generated
[DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
[SuppressUnmanagedCodeSecurity]
private extern static int GetStringConstant(RuntimeModule module, String str, int length);
- [System.Security.SecurityCritical] // auto-generated
[DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
[SuppressUnmanagedCodeSecurity]
private extern static void PreSavePEFile(RuntimeModule module, int portableExecutableKind, int imageFileMachine);
- [System.Security.SecurityCritical] // auto-generated
[DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
[SuppressUnmanagedCodeSecurity]
private extern static void SavePEFile(RuntimeModule module, String fileName, int entryPoint, int isExe, bool isManifestFile);
- [System.Security.SecurityCritical] // auto-generated
[DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
[SuppressUnmanagedCodeSecurity]
private extern static void AddResource(
byte[] resBytes, int resByteCount, int tkFile, int attribute,
int portableExecutableKind, int imageFileMachine);
- [System.Security.SecurityCritical] // auto-generated
[DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
[SuppressUnmanagedCodeSecurity]
private extern static void SetModuleName(RuntimeModule module, String strModuleName);
- [System.Security.SecurityCritical] // auto-generated
[DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
[SuppressUnmanagedCodeSecurity]
internal extern static void SetFieldRVAContent(RuntimeModule module, int fdToken, byte[] data, int length);
- [System.Security.SecurityCritical] // auto-generated
[DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
[SuppressUnmanagedCodeSecurity]
private extern static void DefineNativeResourceFile(RuntimeModule module,
int portableExecutableKind,
int ImageFileMachine);
- [System.Security.SecurityCritical] // auto-generated
[DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
[SuppressUnmanagedCodeSecurity]
private extern static void DefineNativeResourceBytes(RuntimeModule module,
int portableExecutableKind,
int imageFileMachine);
- [System.Security.SecurityCritical] // auto-generated
internal void DefineNativeResource(PortableExecutableKinds portableExecutableKind, ImageFileMachine imageFileMachine)
{
string strResourceFileName = m_moduleData.m_strResourceFileName;
return null;
}
-
-#if !FEATURE_CORECLR
- internal void SetEntryPoint(MethodToken entryPoint)
- {
- // Sets the entry point of the module to be a given method. If no entry point
- // is specified, calling EmitPEFile will generate a dll.
- // AssemblyBuilder.SetEntryPoint has already demanded required permission
- m_EntryPoint = entryPoint;
- }
-#endif //!FEATURE_CORECLR
-
-
-#if !FEATURE_CORECLR
- // This is a helper called by AssemblyBuilder save to presave information for the persistable modules.
- // no need to lock here because we have already taken the lock in AssemblyBuilder.Save
- [System.Security.SecurityCritical] // auto-generated
- internal void PreSave(String fileName,
- PortableExecutableKinds portableExecutableKind, ImageFileMachine imageFileMachine)
- {
- if (m_moduleData.m_isSaved == true)
- {
- // can only save once
- throw new InvalidOperationException(String.Format(CultureInfo.InvariantCulture,
- Environment.GetResourceString("InvalidOperation_ModuleHasBeenSaved"),
- m_moduleData.m_strModuleName));
- }
-
- if (m_moduleData.m_fGlobalBeenCreated == false && m_moduleData.m_fHasGlobal == true)
- throw new NotSupportedException(Environment.GetResourceString("NotSupported_GlobalFunctionNotBaked"));
- TypeBuilder typeBuilder;
- foreach (Type item in m_TypeBuilderDict.Values)
- {
- if (item is TypeBuilder)
- {
- typeBuilder = (TypeBuilder)item;
- }
- else
- {
- EnumBuilder enumBuilder = (EnumBuilder)item;
- typeBuilder = enumBuilder.m_typeBuilder;
- }
-
- if (!typeBuilder.IsCreated())
- {
- // cannot save to PE file without creating all of the types first
- throw new NotSupportedException(String.Format(CultureInfo.InvariantCulture,
- Environment.GetResourceString("NotSupported_NotAllTypesAreBaked"),
- typeBuilder.FullName));
- }
- }
-
- PreSavePEFile(GetNativeHandle(), (int)portableExecutableKind, (int)imageFileMachine);
- }
-
- // no need to lock here because we have already taken the lock in AssemblyBuilder.Save
- [System.Security.SecurityCritical] // auto-generated
- internal void Save(String fileName, bool isAssemblyFile, PortableExecutableKinds portableExecutableKind,
- ImageFileMachine imageFileMachine)
- {
- // This is a helper called by AssemblyBuilder save to save information for the persistable modules.
- if (m_moduleData.m_embeddedRes != null)
- {
- // There are embedded resources for this module
- ResWriterData resWriter;
-
- // Add each resource content into the to be saved PE file
- for (resWriter = m_moduleData.m_embeddedRes; resWriter != null; resWriter = resWriter.m_nextResWriter)
- {
- if (resWriter.m_resWriter != null)
- resWriter.m_resWriter.Generate();
-
- byte[] resBytes = new byte[resWriter.m_memoryStream.Length];
- resWriter.m_memoryStream.Flush();
- resWriter.m_memoryStream.Position = 0;
- resWriter.m_memoryStream.Read(resBytes, 0, resBytes.Length);
-
- AddResource(GetNativeHandle(),
- resWriter.m_strName,
- resBytes,
- resBytes.Length,
- m_moduleData.FileToken,
- (int)resWriter.m_attribute,
- (int)portableExecutableKind,
- (int)imageFileMachine);
- }
- }
-
- DefineNativeResource(portableExecutableKind, imageFileMachine);
-
- PEFileKinds pekind = isAssemblyFile ? ContainingAssemblyBuilder.m_assemblyData.m_peFileKind : PEFileKinds.Dll;
-
- SavePEFile(GetNativeHandle(), fileName, m_EntryPoint.Token, (int)pekind, isAssemblyFile);
-
- m_moduleData.m_isSaved = true;
- }
-#endif // !FEATURE_CORECLR
-
- [System.Security.SecurityCritical] // auto-generated
private int GetTypeRefNested(Type type, Module refedModule, String strRefedModuleFileName)
{
// This function will generate correct TypeRef token for top level type and nested type.
typeName = UnmangleTypeName(typeName);
}
- Contract.Assert(!type.IsByRef, "Must not be ByRef.");
- Contract.Assert(!type.IsGenericType || type.IsGenericTypeDefinition, "Must not have generic arguments.");
+ Debug.Assert(!type.IsByRef, "Must not be ByRef.");
+ Debug.Assert(!type.IsGenericType || type.IsGenericTypeDefinition, "Must not have generic arguments.");
#if FEATURE_APPX
if (ContainingAssemblyBuilder.ProfileAPICheck)
return GetTypeRef(GetNativeHandle(), typeName, GetRuntimeModuleFromModule(refedModule).GetNativeHandle(), strRefedModuleFileName, tkResolution);
}
- [System.Security.SecurityCritical] // auto-generated
internal MethodToken InternalGetConstructorToken(ConstructorInfo con, bool usingRef)
{
// Helper to get constructor token. If usingRef is true, we will never use the def token
return new MethodToken( mr );
}
- [System.Security.SecurityCritical] // auto-generated
internal void Init(String strModuleName, String strFileName, int tkFile)
{
m_moduleData = new ModuleBuilderData(this, strModuleName, strFileName, tkFile);
// This is a method for changing module and file name of the manifest module (created by default for
// each assembly).
- [System.Security.SecurityCritical] // auto-generated
internal void ModifyModuleName(string name)
{
// Reset the names in the managed ModuleBuilderData
return m as RuntimeModule;
}
- [System.Security.SecurityCritical] // auto-generated
private int GetMemberRefToken(MethodBase method, IEnumerable<Type> optionalParameterTypes)
{
Type[] parameterTypes;
}
else
{
- Contract.Assert(method is RuntimeMethodInfo || method is RuntimeConstructorInfo);
+ Debug.Assert(method is RuntimeMethodInfo || method is RuntimeConstructorInfo);
if (method.IsGenericMethod)
{
- Contract.Assert(masmi != null);
+ Debug.Assert(masmi != null);
methDef = masmi.GetGenericMethodDefinition();
methDef = methDef.Module.ResolveMethod(
return GetMemberRefFromSignature(tkParent, method.Name, sigBytes, sigLength);
}
- [System.Security.SecurityCritical] // auto-generated
internal SignatureHelper GetMemberRefSignature(CallingConventions call, Type returnType,
Type[] parameterTypes, IEnumerable<Type> optionalParameterTypes, int cGenericParameters)
{
public override String FullyQualifiedName
{
-#if FEATURE_CORECLR
- [System.Security.SecurityCritical] // auto-generated
-#else
- [System.Security.SecuritySafeCritical]
-#endif
get
{
String fullyQualifiedName = m_moduleData.m_strFileName;
}
}
-#if FEATURE_X509 && FEATURE_CAS_POLICY
- public override System.Security.Cryptography.X509Certificates.X509Certificate GetSignerCertificate()
- {
- return InternalModule.GetSignerCertificate();
- }
-#endif // FEATURE_X509 && FEATURE_CAS_POLICY
#endregion
#region Public Members
#region Define Type
- [System.Security.SecuritySafeCritical] // auto-generated
public TypeBuilder DefineType(String name)
{
Contract.Ensures(Contract.Result<TypeBuilder>() != null);
}
}
- [System.Security.SecuritySafeCritical] // auto-generated
public TypeBuilder DefineType(String name, TypeAttributes attr)
{
Contract.Ensures(Contract.Result<TypeBuilder>() != null);
}
}
- [System.Security.SecuritySafeCritical] // auto-generated
public TypeBuilder DefineType(String name, TypeAttributes attr, Type parent)
{
Contract.Ensures(Contract.Result<TypeBuilder>() != null);
}
}
-#if FEATURE_CORECLR
- [System.Security.SecurityCritical] // auto-generated
-#else
- [System.Security.SecuritySafeCritical]
-#endif
public TypeBuilder DefineType(String name, TypeAttributes attr, Type parent, int typesize)
{
Contract.Ensures(Contract.Result<TypeBuilder>() != null);
}
}
-#if FEATURE_CORECLR
- [System.Security.SecurityCritical] // auto-generated
-#else
- [System.Security.SecuritySafeCritical]
-#endif
public TypeBuilder DefineType(String name, TypeAttributes attr, Type parent, PackingSize packingSize, int typesize)
{
Contract.Ensures(Contract.Result<TypeBuilder>() != null);
}
}
- [System.Security.SecuritySafeCritical] // auto-generated
[System.Runtime.InteropServices.ComVisible(true)]
public TypeBuilder DefineType(String name, TypeAttributes attr, Type parent, Type[] interfaces)
{
}
}
- [System.Security.SecurityCritical] // auto-generated
private TypeBuilder DefineTypeNoLock(String name, TypeAttributes attr, Type parent, Type[] interfaces, PackingSize packingSize, int typesize)
{
Contract.Ensures(Contract.Result<TypeBuilder>() != null);
return new TypeBuilder(name, attr, parent, interfaces, this, packingSize, typesize, null); ;
}
-#if FEATURE_CORECLR
- [System.Security.SecurityCritical] // auto-generated
-#else
- [System.Security.SecuritySafeCritical]
-#endif
public TypeBuilder DefineType(String name, TypeAttributes attr, Type parent, PackingSize packsize)
{
Contract.Ensures(Contract.Result<TypeBuilder>() != null);
}
}
- [System.Security.SecurityCritical] // auto-generated
private TypeBuilder DefineTypeNoLock(String name, TypeAttributes attr, Type parent, PackingSize packsize)
{
Contract.Ensures(Contract.Result<TypeBuilder>() != null);
// This API can only be used to construct a top-level (not nested) enum type.
// Nested enum types can be defined manually using ModuleBuilder.DefineType.
- [System.Security.SecuritySafeCritical] // auto-generated
public EnumBuilder DefineEnum(String name, TypeAttributes visibility, Type underlyingType)
{
Contract.Ensures(Contract.Result<EnumBuilder>() != null);
EnumBuilder enumBuilder = DefineEnumNoLock(name, visibility, underlyingType);
// This enum is not generic, nested, and cannot have any element type.
- Contract.Assert(name == enumBuilder.FullName);
+ Debug.Assert(name == enumBuilder.FullName);
// Replace the TypeBuilder object in m_TypeBuilderDict with this EnumBuilder object.
- Contract.Assert(enumBuilder.m_typeBuilder == m_TypeBuilderDict[name]);
+ Debug.Assert(enumBuilder.m_typeBuilder == m_TypeBuilderDict[name]);
m_TypeBuilderDict[name] = enumBuilder;
return enumBuilder;
}
}
- [System.Security.SecurityCritical] // auto-generated
private EnumBuilder DefineEnumNoLock(String name, TypeAttributes visibility, Type underlyingType)
{
Contract.Ensures(Contract.Result<EnumBuilder>() != null);
#endregion
#region Define Resource
-#if !FEATURE_CORECLR
- public IResourceWriter DefineResource(String name, String description)
- {
- // Define embedded managed resource to be stored in this module
- Contract.Ensures(Contract.Result<IResourceWriter>() != null);
-
- return DefineResource(name, description, ResourceAttributes.Public);
- }
-
- public IResourceWriter DefineResource(String name, String description, ResourceAttributes attribute)
- {
- // Define embedded managed resource to be stored in this module
- Contract.Ensures(Contract.Result<IResourceWriter>() != null);
-
- lock(SyncRoot)
- {
- return DefineResourceNoLock(name, description, attribute);
- }
- }
-
- private IResourceWriter DefineResourceNoLock(String name, String description, ResourceAttributes attribute)
- {
- // Define embedded managed resource to be stored in this module
-
- if (IsTransient())
- throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_BadResourceContainer"));
-
- if (name == null)
- throw new ArgumentNullException(nameof(name));
- if (name.Length == 0)
- throw new ArgumentException(Environment.GetResourceString("Argument_EmptyName"), nameof(name));
- Contract.Ensures(Contract.Result<IResourceWriter>() != null);
- Contract.EndContractBlock();
-
- if (m_assemblyBuilder.IsPersistable())
- {
- m_assemblyBuilder.m_assemblyData.CheckResNameConflict(name);
-
- MemoryStream stream = new MemoryStream();
- ResourceWriter resWriter = new ResourceWriter(stream);
- ResWriterData resWriterData = new ResWriterData( resWriter, stream, name, String.Empty, String.Empty, attribute);
-
- // chain it to the embedded resource list
- resWriterData.m_nextResWriter = m_moduleData.m_embeddedRes;
- m_moduleData.m_embeddedRes = resWriterData;
- return resWriter;
- }
- else
- {
- throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_BadResourceContainer"));
- }
- }
-
- public void DefineManifestResource(String name, Stream stream, ResourceAttributes attribute)
- {
- if (name == null)
- throw new ArgumentNullException(nameof(name));
-
- if (stream == null)
- throw new ArgumentNullException(nameof(stream));
- Contract.EndContractBlock();
-
- // Define embedded managed resource to be stored in this module
- lock(SyncRoot)
- {
- DefineManifestResourceNoLock(name, stream, attribute);
- }
- }
-
- private void DefineManifestResourceNoLock(String name, Stream stream, ResourceAttributes attribute)
- {
- // Define embedded managed resource to be stored in this module
- if (IsTransient())
- throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_BadResourceContainer"));
- Contract.EndContractBlock();
-
- if (name == null)
- throw new ArgumentNullException(nameof(name));
- if (name.Length == 0)
- throw new ArgumentException(Environment.GetResourceString("Argument_EmptyName"), nameof(name));
-
- if (m_assemblyBuilder.IsPersistable())
- {
- m_assemblyBuilder.m_assemblyData.CheckResNameConflict(name);
-
- ResWriterData resWriterData = new ResWriterData( null, stream, name, String.Empty, String.Empty, attribute);
-
- // chain it to the embedded resource list
- resWriterData.m_nextResWriter = m_moduleData.m_embeddedRes;
- m_moduleData.m_embeddedRes = resWriterData;
- }
- else
- {
- throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_BadResourceContainer"));
- }
- }
-
-
- public void DefineUnmanagedResource(Byte[] resource)
- {
- lock(SyncRoot)
- {
- DefineUnmanagedResourceInternalNoLock(resource);
- }
- }
-
- internal void DefineUnmanagedResourceInternalNoLock(Byte[] resource)
- {
- if (resource == null)
- throw new ArgumentNullException(nameof(resource));
- Contract.EndContractBlock();
-
- if (m_moduleData.m_strResourceFileName != null || m_moduleData.m_resourceBytes != null)
- throw new ArgumentException(Environment.GetResourceString("Argument_NativeResourceAlreadyDefined"));
-
- m_moduleData.m_resourceBytes = new byte[resource.Length];
- Buffer.BlockCopy(resource, 0, m_moduleData.m_resourceBytes, 0, resource.Length);
- }
-
- [System.Security.SecuritySafeCritical]
- public void DefineUnmanagedResource(String resourceFileName)
- {
- lock(SyncRoot)
- {
- DefineUnmanagedResourceFileInternalNoLock(resourceFileName);
- }
- }
-
- [System.Security.SecurityCritical] // auto-generated
- internal void DefineUnmanagedResourceFileInternalNoLock(String resourceFileName)
- {
- if (resourceFileName == null)
- throw new ArgumentNullException(nameof(resourceFileName));
- Contract.EndContractBlock();
-
- if (m_moduleData.m_resourceBytes != null || m_moduleData.m_strResourceFileName != null)
- throw new ArgumentException(Environment.GetResourceString("Argument_NativeResourceAlreadyDefined"));
-
- // Check caller has the right to read the file.
- string strFullFileName;
- strFullFileName = Path.UnsafeGetFullPath(resourceFileName);
- new FileIOPermission(FileIOPermissionAccess.Read, strFullFileName).Demand();
-
- new EnvironmentPermission(PermissionState.Unrestricted).Assert();
- try
- {
- if (File.UnsafeExists(resourceFileName) == false)
- throw new FileNotFoundException(Environment.GetResourceString(
- "IO.FileNotFound_FileName",
- resourceFileName), resourceFileName);
- }
- finally
- {
- CodeAccessPermission.RevertAssert();
- }
-
- m_moduleData.m_strResourceFileName = strFullFileName;
- }
-#endif // !FEATURE_CORECLR
#endregion
#region Define Global Method
parameterTypes, requiredParameterTypeCustomModifiers, optionalParameterTypeCustomModifiers);
}
-#if FEATURE_CORECLR
- [System.Security.SecurityCritical] // auto-generated
-#endif
public MethodBuilder DefinePInvokeMethod(String name, String dllName, MethodAttributes attributes,
CallingConventions callingConvention, Type returnType, Type[] parameterTypes,
CallingConvention nativeCallConv, CharSet nativeCharSet)
return DefinePInvokeMethod(name, dllName, name, attributes, callingConvention, returnType, parameterTypes, nativeCallConv, nativeCharSet);
}
-#if FEATURE_CORECLR
- [System.Security.SecurityCritical] // auto-generated
-#endif
public MethodBuilder DefinePInvokeMethod(String name, String dllName, String entryName, MethodAttributes attributes,
CallingConventions callingConvention, Type returnType, Type[] parameterTypes, CallingConvention nativeCallConv,
CharSet nativeCharSet)
}
}
-#if FEATURE_CORECLR
- [System.Security.SecurityCritical] // auto-generated
-#endif
private MethodBuilder DefinePInvokeMethodNoLock(String name, String dllName, String entryName, MethodAttributes attributes,
CallingConventions callingConvention, Type returnType, Type[] parameterTypes, CallingConvention nativeCallConv,
CharSet nativeCharSet)
#region Define Data
-#if FEATURE_CORECLR
- [System.Security.SecurityCritical] // auto-generated
-#endif
public FieldBuilder DefineInitializedData(String name, byte[] data, FieldAttributes attributes)
{
// This method will define an initialized Data in .sdata.
}
}
-#if FEATURE_CORECLR
- [System.Security.SecurityCritical] // auto-generated
-#endif
private FieldBuilder DefineInitializedDataNoLock(String name, byte[] data, FieldAttributes attributes)
{
// This method will define an initialized Data in .sdata.
return m_moduleData.m_globalTypeBuilder.DefineInitializedData(name, data, attributes);
}
-#if FEATURE_CORECLR
- [System.Security.SecurityCritical] // auto-generated
-#endif
public FieldBuilder DefineUninitializedData(String name, int size, FieldAttributes attributes)
{
Contract.Ensures(Contract.Result<FieldBuilder>() != null);
}
}
-#if FEATURE_CORECLR
- [System.Security.SecurityCritical] // auto-generated
-#endif
private FieldBuilder DefineUninitializedDataNoLock(String name, int size, FieldAttributes attributes)
{
// This method will define an uninitialized Data in .sdata.
// 1. GetTypeToken
// 2. ldtoken (see ILGenerator)
// For all other occasions we should return the generic type instantiated on its formal parameters.
- [System.Security.SecurityCritical] // auto-generated
internal TypeToken GetTypeTokenInternal(Type type)
{
return GetTypeTokenInternal(type, false);
}
- [System.Security.SecurityCritical] // auto-generated
private TypeToken GetTypeTokenInternal(Type type, bool getGenericDefinition)
{
lock(SyncRoot)
}
}
- [System.Security.SecuritySafeCritical] // auto-generated
public TypeToken GetTypeToken(Type type)
{
return GetTypeTokenInternal(type, true);
}
- [System.Security.SecurityCritical] // auto-generated
private TypeToken GetTypeTokenWorkerNoLock(Type type, bool getGenericDefinition)
{
if (type == null)
//
ModuleBuilder refedModuleBuilder = refedModule as ModuleBuilder;
-#if !FEATURE_CORECLR
- Contract.Assert(refedModuleBuilder != null || refedModule is RuntimeModule);
- bool isRefedModuleTransient = refedModuleBuilder != null ?
- refedModuleBuilder.IsTransient() :
- ((RuntimeModule)refedModule).IsTransientInternal();
-
- // We cannot have a non-transient module referencing to a transient module.
- if (IsTransient() == false && isRefedModuleTransient)
- {
- throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_BadTransientModuleReference"));
- }
-#endif // !FEATURE_CORECLR
-
String strRefedModuleFileName = String.Empty;
if (refedModule.Assembly.Equals(this.Assembly))
{
return GetTypeToken(InternalModule.GetType(name, false, true));
}
- [System.Security.SecuritySafeCritical] // auto-generated
public MethodToken GetMethodToken(MethodInfo method)
{
lock(SyncRoot)
}
}
- [System.Security.SecurityCritical] // auto-generated
internal MethodToken GetMethodTokenInternal(MethodInfo method)
{
lock(SyncRoot)
// 1. GetMethodToken
// 2. ldtoken (see ILGenerator)
// For all other occasions we should return the method on the generic type instantiated on the formal parameters.
- [System.Security.SecurityCritical] // auto-generated
private MethodToken GetMethodTokenNoLock(MethodInfo method, bool getGenericTypeDefinition)
{
// Return a MemberRef token if MethodInfo is not defined in this module. Or
return new MethodToken(mr);
}
- [System.Security.SecuritySafeCritical] // auto-generated
public MethodToken GetConstructorToken(ConstructorInfo constructor, IEnumerable<Type> optionalParameterTypes)
{
if (constructor == null)
}
}
- [System.Security.SecuritySafeCritical] // auto-generated
public MethodToken GetMethodToken(MethodInfo method, IEnumerable<Type> optionalParameterTypes)
{
if (method == null)
}
}
- [System.Security.SecurityCritical] // auto-generated
internal int GetMethodTokenInternal(MethodBase method, IEnumerable<Type> optionalParameterTypes, bool useMethodDef)
{
int tk = 0;
if (method.IsGenericMethod)
{
// Constructors cannot be generic.
- Contract.Assert(methodInfo != null);
+ Debug.Assert(methodInfo != null);
// Given M<Bar> unbind to M<S>
MethodInfo methodInfoUnbound = methodInfo;
return tk;
}
- [System.Security.SecuritySafeCritical] // auto-generated
public MethodToken GetArrayMethodToken(Type arrayClass, String methodName, CallingConventions callingConvention,
Type returnType, Type[] parameterTypes)
{
}
}
- [System.Security.SecurityCritical] // auto-generated
private MethodToken GetArrayMethodTokenNoLock(Type arrayClass, String methodName, CallingConventions callingConvention,
Type returnType, Type[] parameterTypes)
{
typeSpec.Token, methodName, sigBytes, length));
}
- [System.Security.SecuritySafeCritical] // auto-generated
public MethodInfo GetArrayMethod(Type arrayClass, String methodName, CallingConventions callingConvention,
Type returnType, Type[] parameterTypes)
{
return new SymbolMethod(this, token, arrayClass, methodName, callingConvention, returnType, parameterTypes);
}
- [System.Security.SecuritySafeCritical] // auto-generated
[System.Runtime.InteropServices.ComVisible(true)]
public MethodToken GetConstructorToken(ConstructorInfo con)
{
return InternalGetConstructorToken(con, false);
}
- [System.Security.SecuritySafeCritical] // auto-generated
public FieldToken GetFieldToken(FieldInfo field)
{
lock(SyncRoot)
}
}
- [System.Security.SecurityCritical] // auto-generated
private FieldToken GetFieldTokenNoLock(FieldInfo field)
{
if (field == null) {
return new FieldToken(mr, field.GetType());
}
- [System.Security.SecuritySafeCritical] // auto-generated
public StringToken GetStringConstant(String str)
{
if (str == null)
return new StringToken(GetStringConstant(GetNativeHandle(), str, str.Length));
}
- [System.Security.SecuritySafeCritical] // auto-generated
public SignatureToken GetSignatureToken(SignatureHelper sigHelper)
{
// Define signature token given a signature helper. This will define a metadata
sigBytes = sigHelper.InternalGetSignature(out sigLength);
return new SignatureToken(TypeBuilder.GetTokenFromSig(GetNativeHandle(), sigBytes, sigLength), this);
}
- [System.Security.SecuritySafeCritical] // auto-generated
public SignatureToken GetSignatureToken(byte[] sigBytes, int sigLength)
{
if (sigBytes == null)
#region Other
-#if FEATURE_CORECLR
- [System.Security.SecurityCritical] // auto-generated
-#else
- [System.Security.SecuritySafeCritical]
-#endif
[System.Runtime.InteropServices.ComVisible(true)]
public void SetCustomAttribute(ConstructorInfo con, byte[] binaryAttribute)
{
false, false);
}
- [System.Security.SecuritySafeCritical] // auto-generated
public void SetCustomAttribute(CustomAttributeBuilder customBuilder)
{
if (customBuilder == null)
return m_iSymWriter;
}
-#if FEATURE_CORECLR
- [System.Security.SecuritySafeCritical]
-#endif
public ISymbolDocumentWriter DefineDocument(String url, Guid language, Guid languageVendor, Guid documentType)
{
// url cannot be null but can be an empty string
}
}
-#if FEATURE_CORECLR
- [System.Security.SecurityCritical] // auto-generated
-#endif
private ISymbolDocumentWriter DefineDocumentNoLock(String url, Guid language, Guid languageVendor, Guid documentType)
{
if (m_iSymWriter == null)
return m_iSymWriter.DefineDocument(url, language, languageVendor, documentType);
}
-#if FEATURE_CORECLR
- [System.Security.SecurityCritical] // auto-generated
-#else
- [System.Security.SecuritySafeCritical]
-#endif
public void SetUserEntryPoint(MethodInfo entryPoint)
{
lock(SyncRoot)
}
}
- [System.Security.SecurityCritical] // auto-generated
private void SetUserEntryPointNoLock(MethodInfo entryPoint)
{
// Set the user entry point. Compiler may generate startup stub before calling user main.
#endregion
#endregion
-
-#if !FEATURE_CORECLR
- void _ModuleBuilder.GetTypeInfoCount(out uint pcTInfo)
- {
- throw new NotImplementedException();
- }
-
- void _ModuleBuilder.GetTypeInfo(uint iTInfo, uint lcid, IntPtr ppTInfo)
- {
- throw new NotImplementedException();
- }
-
- void _ModuleBuilder.GetIDsOfNames([In] ref Guid riid, IntPtr rgszNames, uint cNames, uint lcid, IntPtr rgDispId)
- {
- throw new NotImplementedException();
- }
-
- void _ModuleBuilder.Invoke(uint dispIdMember, [In] ref Guid riid, uint lcid, short wFlags, IntPtr pDispParams, IntPtr pVarResult, IntPtr pExcepInfo, IntPtr puArgErr)
- {
- throw new NotImplementedException();
- }
-#endif
}
}
namespace System.Reflection.Emit
{
using System;
+ using System.Diagnostics;
using System.Diagnostics.Contracts;
using System.Globalization;
using System.IO;
[Serializable]
internal class ModuleBuilderData
{
- [System.Security.SecurityCritical] // auto-generated
internal ModuleBuilderData(ModuleBuilder module, String strModuleName, String strFileName, int tkFile)
{
m_globalTypeBuilder = new TypeBuilder(module);
}
// Initialize module and file names.
- [System.Security.SecurityCritical] // auto-generated
private void InitNames(String strModuleName, String strFileName)
{
m_strModuleName = strModuleName;
// This is a method for changing module and file name of the manifest module (created by default for
// each assembly).
- [System.Security.SecurityCritical] // auto-generated
internal virtual void ModifyModuleName(String strModuleName)
{
- Contract.Assert(m_strModuleName == AssemblyBuilder.MANIFEST_MODULE_NAME, "Changing names for non-manifest module");
+ Debug.Assert(m_strModuleName == AssemblyBuilder.MANIFEST_MODULE_NAME, "Changing names for non-manifest module");
InitNames(strModuleName, null /*strFileName*/);
}
internal const int StackChangeShift = 28; // XXXX0000000000000000000000000000
-#if FEATURE_CORECLR
private OpCodeValues m_value;
private int m_flags;
}
}
-
public StackBehaviour StackBehaviourPop
{
get
return (short)m_value;
}
}
-#else // FEATURE_CORECLR
- //
- // The exact layout is part of the legacy COM mscorlib surface, so it is
- // pretty much set in stone for desktop CLR. Ideally, we would use the packed
- // bit field like for CoreCLR, but that would be a breaking change.
- //
-
-// disable csharp compiler warning #0414: field assigned unused value
-#pragma warning disable 0414
- private String m_stringname; // not used - computed lazily
-#pragma warning restore 0414
- private StackBehaviour m_pop;
- private StackBehaviour m_push;
- private OperandType m_operand;
- private OpCodeType m_type;
- private int m_size;
- private byte m_s1;
- private byte m_s2;
- private FlowControl m_ctrl;
-
- // Specifies whether the current instructions causes the control flow to
- // change unconditionally.
- private bool m_endsUncondJmpBlk;
-
-
- // Specifies the stack change that the current instruction causes not
- // taking into account the operand dependant stack changes.
- private int m_stackChange;
-
-
- internal OpCode(OpCodeValues value, int flags)
- {
- m_stringname = null; // computed lazily
- m_pop = (StackBehaviour)((flags >> StackBehaviourPopShift) & StackBehaviourMask);
- m_push = (StackBehaviour)((flags >> StackBehaviourPushShift) & StackBehaviourMask);
- m_operand = (OperandType)(flags & OperandTypeMask);
- m_type = (OpCodeType)((flags >> OpCodeTypeShift) & OpCodeTypeMask);
- m_size = (flags >> SizeShift) & SizeMask;
- m_s1 = (byte)((int)value >> 8);
- m_s2 = (byte)(int)value;
- m_ctrl = (FlowControl)((flags >> FlowControlShift) & FlowControlMask);
- m_endsUncondJmpBlk = (flags & EndsUncondJmpBlkFlag) != 0;
- m_stackChange = (flags >> StackChangeShift);
- }
-
- internal bool EndsUncondJmpBlk()
- {
- return m_endsUncondJmpBlk;
- }
-
- internal int StackChange()
- {
- return m_stackChange;
- }
-
- public OperandType OperandType
- {
- get
- {
- return (m_operand);
- }
- }
-
- public FlowControl FlowControl
- {
- get
- {
- return (m_ctrl);
- }
- }
-
- public OpCodeType OpCodeType
- {
- get
- {
- return (m_type);
- }
- }
-
-
- public StackBehaviour StackBehaviourPop
- {
- get
- {
- return (m_pop);
- }
- }
-
- public StackBehaviour StackBehaviourPush
- {
- get
- {
- return (m_push);
- }
- }
-
- public int Size
- {
- get
- {
- return (m_size);
- }
- }
-
- public short Value
- {
- get
- {
- if (m_size == 2)
- return (short)(m_s1 << 8 | m_s2);
- return (short)m_s2;
- }
- }
-#endif // FEATURE_CORECLR
-
private static volatile string[] g_nameCache;
return Name;
}
}
-
}
public class ParameterBuilder : _ParameterBuilder
{
// set ParamMarshal
- [System.Security.SecuritySafeCritical] // auto-generated
[Obsolete("An alternate API is available: Emit the MarshalAs custom attribute instead. http://go.microsoft.com/fwlink/?linkid=14202")]
public virtual void SetMarshal(UnmanagedMarshal unmanagedMarshal)
{
}
// Set the default value of the parameter
- [System.Security.SecuritySafeCritical] // auto-generated
public virtual void SetConstant(Object defaultValue)
{
TypeBuilder.SetConstantValue(
// Use this function if client decides to form the custom attribute blob themselves
- [System.Security.SecuritySafeCritical]
[System.Runtime.InteropServices.ComVisible(true)]
public void SetCustomAttribute(ConstructorInfo con, byte[] binaryAttribute)
{
}
// Use this function if client wishes to build CustomAttribute using CustomAttributeBuilder
- [System.Security.SecuritySafeCritical] // auto-generated
public void SetCustomAttribute(CustomAttributeBuilder customBuilder)
{
if (customBuilder == null)
private ParameterBuilder() {}
- [System.Security.SecurityCritical] // auto-generated
internal ParameterBuilder(
MethodBuilder methodBuilder,
int sequence,
return m_pdToken;
}
-#if !FEATURE_CORECLR
- void _ParameterBuilder.GetTypeInfoCount(out uint pcTInfo)
- {
- throw new NotImplementedException();
- }
-
- void _ParameterBuilder.GetTypeInfo(uint iTInfo, uint lcid, IntPtr ppTInfo)
- {
- throw new NotImplementedException();
- }
-
- void _ParameterBuilder.GetIDsOfNames([In] ref Guid riid, IntPtr rgszNames, uint cNames, uint lcid, IntPtr rgDispId)
- {
- throw new NotImplementedException();
- }
-
- void _ParameterBuilder.Invoke(uint dispIdMember, [In] ref Guid riid, uint lcid, short wFlags, IntPtr pDispParams, IntPtr pVarResult, IntPtr pExcepInfo, IntPtr puArgErr)
- {
- throw new NotImplementedException();
- }
-#endif
-
internal int MetadataTokenInternal { get { return m_pdToken.Token; } }
public virtual String Name {
// A PropertyBuilder is always associated with a TypeBuilder. The TypeBuilder.DefineProperty
// method will return a new PropertyBuilder to a client.
//
- [HostProtection(MayLeakOnAbort = true)]
[ClassInterface(ClassInterfaceType.None)]
[ComDefaultInterface(typeof(_PropertyBuilder))]
[System.Runtime.InteropServices.ComVisible(true)]
//************************************************
// Set the default value of the Property
//************************************************
- [System.Security.SecuritySafeCritical] // auto-generated
public void SetConstant(Object defaultValue)
{
m_containingType.ThrowIfCreated();
}
}
- [System.Security.SecurityCritical] // auto-generated
private void SetMethodSemantics(MethodBuilder mdBuilder, MethodSemanticsAttributes semantics)
{
if (mdBuilder == null)
mdBuilder.GetToken().Token);
}
- [System.Security.SecuritySafeCritical] // auto-generated
public void SetGetMethod(MethodBuilder mdBuilder)
{
SetMethodSemantics(mdBuilder, MethodSemanticsAttributes.Getter);
m_getMethod = mdBuilder;
}
- [System.Security.SecuritySafeCritical] // auto-generated
public void SetSetMethod(MethodBuilder mdBuilder)
{
SetMethodSemantics(mdBuilder, MethodSemanticsAttributes.Setter);
m_setMethod = mdBuilder;
}
- [System.Security.SecuritySafeCritical] // auto-generated
public void AddOtherMethod(MethodBuilder mdBuilder)
{
SetMethodSemantics(mdBuilder, MethodSemanticsAttributes.Other);
// Use this function if client decides to form the custom attribute blob themselves
-#if FEATURE_CORECLR
-[System.Security.SecurityCritical] // auto-generated
-#else
-[System.Security.SecuritySafeCritical]
-#endif
[System.Runtime.InteropServices.ComVisible(true)]
public void SetCustomAttribute(ConstructorInfo con, byte[] binaryAttribute)
{
}
// Use this function if client wishes to build CustomAttribute using CustomAttributeBuilder
- [System.Security.SecuritySafeCritical] // auto-generated
public void SetCustomAttribute(CustomAttributeBuilder customBuilder)
{
if (customBuilder == null)
throw new NotSupportedException(Environment.GetResourceString("NotSupported_DynamicModule"));
}
-#if !FEATURE_CORECLR
- void _PropertyBuilder.GetTypeInfoCount(out uint pcTInfo)
- {
- throw new NotImplementedException();
- }
-
- void _PropertyBuilder.GetTypeInfo(uint iTInfo, uint lcid, IntPtr ppTInfo)
- {
- throw new NotImplementedException();
- }
-
- void _PropertyBuilder.GetIDsOfNames([In] ref Guid riid, IntPtr rgszNames, uint cNames, uint lcid, IntPtr rgDispId)
- {
- throw new NotImplementedException();
- }
-
- void _PropertyBuilder.Invoke(uint dispIdMember, [In] ref Guid riid, uint lcid, short wFlags, IntPtr pDispParams, IntPtr pVarResult, IntPtr pExcepInfo, IntPtr puArgErr)
- {
- throw new NotImplementedException();
- }
-#endif
-
public override String Name {
get { return m_name; }
}
private MethodInfo m_setMethod;
private TypeBuilder m_containingType;
}
-
}
{
using System.Text;
using System;
+ using System.Diagnostics;
using System.Diagnostics.Contracts;
using System.Reflection;
using System.Runtime.CompilerServices;
#endregion
#region Static Members
- [System.Security.SecuritySafeCritical] // auto-generated
public static SignatureHelper GetMethodSigHelper(Module mod, Type returnType, Type[] parameterTypes)
{
return GetMethodSigHelper(mod, CallingConventions.Standard, returnType, null, null, parameterTypes, null, null);
}
- [System.Security.SecurityCritical] // auto-generated
internal static SignatureHelper GetMethodSigHelper(Module mod, CallingConventions callingConvention, Type returnType, int cGenericParam)
{
return GetMethodSigHelper(mod, callingConvention, cGenericParam, returnType, null, null, null, null, null);
}
- [System.Security.SecuritySafeCritical] // auto-generated
public static SignatureHelper GetMethodSigHelper(Module mod, CallingConventions callingConvention, Type returnType)
{
return GetMethodSigHelper(mod, callingConvention, returnType, null, null, null, null, null);
return sigHelp;
}
- [System.Security.SecurityCritical] // auto-generated
internal static SignatureHelper GetMethodSigHelper(
Module scope, CallingConventions callingConvention,
Type returnType, Type[] requiredReturnTypeCustomModifiers, Type[] optionalReturnTypeCustomModifiers,
optionalReturnTypeCustomModifiers, parameterTypes, requiredParameterTypeCustomModifiers, optionalParameterTypeCustomModifiers);
}
- [System.Security.SecurityCritical] // auto-generated
internal static SignatureHelper GetMethodSigHelper(
Module scope, CallingConventions callingConvention, int cGenericParam,
Type returnType, Type[] requiredReturnTypeCustomModifiers, Type[] optionalReturnTypeCustomModifiers,
return sigHelp;
}
- [System.Security.SecuritySafeCritical] // auto-generated
public static SignatureHelper GetMethodSigHelper(Module mod, CallingConvention unmanagedCallConv, Type returnType)
{
SignatureHelper sigHelp;
return GetPropertySigHelper(mod, (CallingConventions)0, returnType, requiredReturnTypeCustomModifiers, optionalReturnTypeCustomModifiers,
parameterTypes, requiredParameterTypeCustomModifiers, optionalParameterTypeCustomModifiers);
}
- [System.Security.SecuritySafeCritical] // auto-generated
public static SignatureHelper GetPropertySigHelper(Module mod, CallingConventions callingConvention,
Type returnType, Type[] requiredReturnTypeCustomModifiers, Type[] optionalReturnTypeCustomModifiers,
Type[] parameterTypes, Type[][] requiredParameterTypeCustomModifiers, Type[][] optionalParameterTypeCustomModifiers)
return sigHelp;
}
- [System.Security.SecurityCritical] // auto-generated
internal static SignatureHelper GetTypeSigToken(Module mod, Type type)
{
if (mod == null)
Init(mod, callingConvention);
}
- [System.Security.SecurityCritical] // auto-generated
private SignatureHelper(Module mod, MdSigCallingConvention callingConvention, int cGenericParameters,
Type returnType, Type[] requiredCustomModifiers, Type[] optionalCustomModifiers)
{
AddOneArgTypeHelper(returnType, requiredCustomModifiers, optionalCustomModifiers);
}
- [System.Security.SecurityCritical] // auto-generated
private SignatureHelper(Module mod, MdSigCallingConvention callingConvention,
Type returnType, Type[] requiredCustomModifiers, Type[] optionalCustomModifiers)
: this(mod, callingConvention, 0, returnType, requiredCustomModifiers, optionalCustomModifiers)
{
}
- [System.Security.SecurityCritical] // auto-generated
private SignatureHelper(Module mod, Type type)
{
Init(mod);
#endregion
#region Private Members
- [System.Security.SecurityCritical] // auto-generated
private void AddOneArgTypeHelper(Type argument, bool pinned)
{
if (pinned)
AddOneArgTypeHelper(argument);
}
- [System.Security.SecurityCritical] // auto-generated
private void AddOneArgTypeHelper(Type clsArgument, Type[] requiredCustomModifiers, Type[] optionalCustomModifiers)
{
// This function will not increase the argument count. It only fills in bytes
AddElementType(CorElementType.CModOpt);
int token = m_module.GetTypeToken(t).Token;
- Contract.Assert(!MetadataToken.IsNullToken(token));
+ Debug.Assert(!MetadataToken.IsNullToken(token));
AddToken(token);
}
}
AddElementType(CorElementType.CModReqd);
int token = m_module.GetTypeToken(t).Token;
- Contract.Assert(!MetadataToken.IsNullToken(token));
+ Debug.Assert(!MetadataToken.IsNullToken(token));
AddToken(token);
}
}
AddOneArgTypeHelper(clsArgument);
}
- [System.Security.SecurityCritical] // auto-generated
private void AddOneArgTypeHelper(Type clsArgument) { AddOneArgTypeHelperWorker(clsArgument, false); }
- [System.Security.SecurityCritical] // auto-generated
private void AddOneArgTypeHelperWorker(Type clsArgument, bool lastWasGenericInst)
{
if (clsArgument.IsGenericParameter)
AddToken(clsToken.Token);
}
- [System.Security.SecurityCritical] // auto-generated
private unsafe void InternalAddRuntimeType(Type type)
{
// Add a runtime type into the signature.
AddArgument(clsArgument, null, null);
}
- [System.Security.SecuritySafeCritical] // auto-generated
public void AddArgument(Type argument, bool pinned)
{
if (argument == null)
}
}
- [System.Security.SecuritySafeCritical] // auto-generated
public void AddArgument(Type argument, Type[] requiredCustomModifiers, Type[] optionalCustomModifiers)
{
if (m_sigDone)
#endregion
-#if !FEATURE_CORECLR
- void _SignatureHelper.GetTypeInfoCount(out uint pcTInfo)
- {
- throw new NotImplementedException();
- }
-
- void _SignatureHelper.GetTypeInfo(uint iTInfo, uint lcid, IntPtr ppTInfo)
- {
- throw new NotImplementedException();
- }
-
- void _SignatureHelper.GetIDsOfNames([In] ref Guid riid, IntPtr rgszNames, uint cNames, uint lcid, IntPtr rgDispId)
- {
- throw new NotImplementedException();
- }
-
- void _SignatureHelper.Invoke(uint dispIdMember, [In] ref Guid riid, uint lcid, short wFlags, IntPtr pDispParams, IntPtr pVarResult, IntPtr pExcepInfo, IntPtr puArgErr)
- {
- throw new NotImplementedException();
- }
-#endif
-
}
}
#endregion
#region Constructor
- [System.Security.SecurityCritical] // auto-generated
internal SymbolMethod(ModuleBuilder mod, MethodToken token, Type arrayClass, String methodName,
CallingConventions callingConvention, Type returnType, Type[] parameterTypes)
{
using System.Reflection;
using System.Security;
using System.Security.Permissions;
- using System.Diagnostics;
using System.Runtime.InteropServices;
using System.Runtime.CompilerServices;
using System.Collections.Generic;
using CultureInfo = System.Globalization.CultureInfo;
using System.Threading;
using System.Runtime.Versioning;
+ using System.Diagnostics;
using System.Diagnostics.Contracts;
Size128 = 128,
}
- [HostProtection(MayLeakOnAbort = true)]
[ClassInterface(ClassInterfaceType.None)]
[ComDefaultInterface(typeof(_TypeBuilder))]
[System.Runtime.InteropServices.ComVisible(true)]
m_customBuilder = customBuilder;
}
- [System.Security.SecurityCritical] // auto-generated
public void Bake(ModuleBuilder module, int token)
{
if (m_customBuilder == null)
#endregion
#region Private Static FCalls
- [System.Security.SecurityCritical] // auto-generated
[DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
[SuppressUnmanagedCodeSecurity]
private static extern void SetParentType(RuntimeModule module, int tdTypeDef, int tkParent);
- [System.Security.SecurityCritical] // auto-generated
[DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
[SuppressUnmanagedCodeSecurity]
private static extern void AddInterfaceImpl(RuntimeModule module, int tdTypeDef, int tkInterface);
#endregion
#region Internal Static FCalls
- [System.Security.SecurityCritical] // auto-generated
[DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
[SuppressUnmanagedCodeSecurity]
internal static extern int DefineMethod(RuntimeModule module, int tkParent, String name, byte[] signature, int sigLength,
MethodAttributes attributes);
- [System.Security.SecurityCritical] // auto-generated
[DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
[SuppressUnmanagedCodeSecurity]
internal static extern int DefineMethodSpec(RuntimeModule module, int tkParent, byte[] signature, int sigLength);
- [System.Security.SecurityCritical] // auto-generated
[DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
[SuppressUnmanagedCodeSecurity]
internal static extern int DefineField(RuntimeModule module, int tkParent, String name, byte[] signature, int sigLength,
FieldAttributes attributes);
- [System.Security.SecurityCritical] // auto-generated
[DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
[SuppressUnmanagedCodeSecurity]
private static extern void SetMethodIL(RuntimeModule module, int tk, bool isInitLocals,
ExceptionHandler[] exceptions, int numExceptions,
int [] tokenFixups, int numTokenFixups);
- [System.Security.SecurityCritical] // auto-generated
[DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
[SuppressUnmanagedCodeSecurity]
private static extern void DefineCustomAttribute(RuntimeModule module, int tkAssociate, int tkConstructor,
byte[] attr, int attrLength, bool toDisk, bool updateCompilerFlags);
- [System.Security.SecurityCritical] // auto-generated
internal static void DefineCustomAttribute(ModuleBuilder module, int tkAssociate, int tkConstructor,
byte[] attr, bool toDisk, bool updateCompilerFlags)
{
localAttr, (localAttr != null) ? localAttr.Length : 0, toDisk, updateCompilerFlags);
}
- [System.Security.SecurityCritical] // auto-generated
[DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
[SuppressUnmanagedCodeSecurity]
internal static extern void SetPInvokeData(RuntimeModule module, String DllName, String name, int token, int linkFlags);
- [System.Security.SecurityCritical] // auto-generated
[DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
[SuppressUnmanagedCodeSecurity]
internal static extern int DefineProperty(RuntimeModule module, int tkParent, String name, PropertyAttributes attributes,
byte[] signature, int sigLength);
- [System.Security.SecurityCritical] // auto-generated
[DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
[SuppressUnmanagedCodeSecurity]
internal static extern int DefineEvent(RuntimeModule module, int tkParent, String name, EventAttributes attributes, int tkEventType);
- [System.Security.SecurityCritical] // auto-generated
[DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
[SuppressUnmanagedCodeSecurity]
internal static extern void DefineMethodSemantics(RuntimeModule module, int tkAssociation,
MethodSemanticsAttributes semantics, int tkMethod);
- [System.Security.SecurityCritical] // auto-generated
[DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
[SuppressUnmanagedCodeSecurity]
internal static extern void DefineMethodImpl(RuntimeModule module, int tkType, int tkBody, int tkDecl);
- [System.Security.SecurityCritical] // auto-generated
[DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
[SuppressUnmanagedCodeSecurity]
internal static extern void SetMethodImpl(RuntimeModule module, int tkMethod, MethodImplAttributes MethodImplAttributes);
- [System.Security.SecurityCritical] // auto-generated
[DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
[SuppressUnmanagedCodeSecurity]
internal static extern int SetParamInfo(RuntimeModule module, int tkMethod, int iSequence,
ParameterAttributes iParamAttributes, String strParamName);
- [System.Security.SecurityCritical] // auto-generated
[DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
[SuppressUnmanagedCodeSecurity]
internal static extern int GetTokenFromSig(RuntimeModule module, byte[] signature, int sigLength);
- [System.Security.SecurityCritical] // auto-generated
[DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
[SuppressUnmanagedCodeSecurity]
internal static extern void SetFieldLayoutOffset(RuntimeModule module, int fdToken, int iOffset);
- [System.Security.SecurityCritical] // auto-generated
[DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
[SuppressUnmanagedCodeSecurity]
internal static extern void SetClassLayout(RuntimeModule module, int tk, PackingSize iPackingSize, int iTypeSize);
- [System.Security.SecurityCritical] // auto-generated
[DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
[SuppressUnmanagedCodeSecurity]
internal static extern void SetFieldMarshal(RuntimeModule module, int tk, byte[] ubMarshal, int ubSize);
- [System.Security.SecurityCritical] // auto-generated
[DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
[SuppressUnmanagedCodeSecurity]
private static extern unsafe void SetConstantValue(RuntimeModule module, int tk, int corType, void* pValue);
-
-#if FEATURE_CAS_POLICY
- [System.Security.SecurityCritical] // auto-generated
- [DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
- [SuppressUnmanagedCodeSecurity]
- internal static extern void AddDeclarativeSecurity(RuntimeModule module, int parent, SecurityAction action, byte[] blob, int cb);
-#endif
#endregion
#region Internal\Private Static Members
return false;
}
- [System.Security.SecurityCritical] // auto-generated
internal static unsafe void SetConstantValue(ModuleBuilder module, int tk, Type destType, Object value)
{
// This is a helper function that is used by ParameterBuilder, PropertyBuilder,
}
else // must be a runtime Enum Type
{
- Contract.Assert(destType is RuntimeType, "destType is not a runtime type, an EnumBuilder, or a TypeBuilder.");
+ Debug.Assert(destType is RuntimeType, "destType is not a runtime type, an EnumBuilder, or a TypeBuilder.");
underlyingType = Enum.GetUnderlyingType(destType);
m_typeInterfaces = new List<Type>();
}
- [System.Security.SecurityCritical] // auto-generated
internal TypeBuilder(
String name,
TypeAttributes attr,
Init(name, attr, parent, interfaces, module, iPackingSize, iTypeSize, enclosingType);
}
- [System.Security.SecurityCritical] // auto-generated
private void Init(String fullname, TypeAttributes attr, Type parent, Type[] interfaces, ModuleBuilder module,
PackingSize iPackingSize, int iTypeSize, TypeBuilder enclosingType)
{
if ((m_iPackingSize != 0) ||(m_iTypeSize != 0))
SetClassLayout(GetModuleBuilder().GetNativeHandle(), m_tdType.Token, m_iPackingSize, m_iTypeSize);
-#if !FEATURE_CORECLR
- // If the type is public and it is contained in a assemblyBuilder,
- // update the public COMType list.
- if (IsPublicComType(this))
- {
- if (containingAssem.IsPersistable() && m_module.IsTransient() == false)
- {
- // This will throw InvalidOperationException if the assembly has been saved
- // Ideally we should reject all emit operations if the assembly has been saved,
- // but that would be a breaking change for some. Currently you cannot define
- // modules and public types, but you can still define private types and global methods.
- containingAssem.m_assemblyData.AddPublicComType(this);
- }
-
- // Now add the type to the ExportedType table
- if (!m_module.Equals(containingAssem.ManifestModule))
- containingAssem.DefineExportedTypeInMemory(this, m_module.m_moduleData.FileToken, m_tdType.Token);
- }
-#endif
m_module.AddType(FullName, this);
}
#endregion
#region Private Members
- [System.Security.SecurityCritical] // auto-generated
private MethodBuilder DefinePInvokeMethodHelper(
String name, String dllName, String importName, MethodAttributes attributes, CallingConventions callingConvention,
Type returnType, Type[] returnTypeRequiredCustomModifiers, Type[] returnTypeOptionalCustomModifiers,
}
}
- [System.Security.SecurityCritical] // auto-generated
private MethodBuilder DefinePInvokeMethodHelperNoLock(
String name, String dllName, String importName, MethodAttributes attributes, CallingConventions callingConvention,
Type returnType, Type[] returnTypeRequiredCustomModifiers, Type[] returnTypeOptionalCustomModifiers,
return method;
}
- [System.Security.SecurityCritical] // auto-generated
private FieldBuilder DefineDataHelper(String name, byte[] data, int size, FieldAttributes attributes)
{
String strValueClassName;
#endregion
#region FCalls
- [System.Security.SecurityCritical] // auto-generated
[DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
[SuppressUnmanagedCodeSecurity]
private extern static int DefineType(RuntimeModule module,
String fullname, int tkParent, TypeAttributes attributes, int tkEnclosingType, int[] interfaceTokens);
- [System.Security.SecurityCritical] // auto-generated
[DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
[SuppressUnmanagedCodeSecurity]
private extern static int DefineGenericParam(RuntimeModule module,
String name, int tkParent, GenericParameterAttributes attributes, int position, int[] constraints);
- [System.Security.SecurityCritical] // auto-generated
[DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
[SuppressUnmanagedCodeSecurity]
private static extern void TermCreateClass(RuntimeModule module, int tk, ObjectHandleOnStack type);
public override bool IsSecurityCritical
{
-#if FEATURE_CORECLR
get { return true; }
-#else
- get
- {
- if (!IsCreated())
- throw new NotSupportedException(Environment.GetResourceString("NotSupported_TypeNotYetCreated"));
- Contract.EndContractBlock();
-
- return m_bakedRuntimeType.IsSecurityCritical;
- }
-#endif
}
public override bool IsSecuritySafeCritical
{
-#if FEATURE_CORECLR
get { return false; }
-#else
- get
- {
- if (!IsCreated())
- throw new NotSupportedException(Environment.GetResourceString("NotSupported_TypeNotYetCreated"));
- Contract.EndContractBlock();
-
- return m_bakedRuntimeType.IsSecuritySafeCritical;
- }
-#endif
}
public override bool IsSecurityTransparent
{
-#if FEATURE_CORECLR
get { return false; }
-#else
- get
- {
- if (!IsCreated())
- throw new NotSupportedException(Environment.GetResourceString("NotSupported_TypeNotYetCreated"));
- Contract.EndContractBlock();
-
- return m_bakedRuntimeType.IsSecurityTransparent;
- }
-#endif
}
[System.Runtime.InteropServices.ComVisible(true)]
#endregion
#region ICustomAttributeProvider Implementation
- [System.Security.SecuritySafeCritical] // auto-generated
public override Object[] GetCustomAttributes(bool inherit)
{
if (!IsCreated())
return CustomAttribute.GetCustomAttributes(m_bakedRuntimeType, typeof(object) as RuntimeType, inherit);
}
- [System.Security.SecuritySafeCritical] // auto-generated
public override Object[] GetCustomAttributes(Type attributeType, bool inherit)
{
if (!IsCreated())
return CustomAttribute.GetCustomAttributes(m_bakedRuntimeType, attributeRuntimeType, inherit);
}
- [System.Security.SecuritySafeCritical] // auto-generated
public override bool IsDefined(Type attributeType, bool inherit)
{
if (!IsCreated())
#endregion
#region Define Method
- [System.Security.SecuritySafeCritical] // auto-generated
public void DefineMethodOverride(MethodInfo methodInfoBody, MethodInfo methodInfoDeclaration)
{
lock(SyncRoot)
}
}
- [System.Security.SecurityCritical] // auto-generated
private void DefineMethodOverrideNoLock(MethodInfo methodInfoBody, MethodInfo methodInfoDeclaration)
{
if (methodInfoBody == null)
#endregion
#region Define Constructor
- [System.Security.SecuritySafeCritical] // auto-generated
[System.Runtime.InteropServices.ComVisible(true)]
public ConstructorBuilder DefineTypeInitializer()
{
}
}
- [System.Security.SecurityCritical] // auto-generated
private ConstructorBuilder DefineTypeInitializerNoLock()
{
ThrowIfCreated();
return DefineConstructor(attributes, callingConvention, parameterTypes, null, null);
}
- [System.Security.SecuritySafeCritical] // auto-generated
[System.Runtime.InteropServices.ComVisible(true)]
public ConstructorBuilder DefineConstructor(MethodAttributes attributes, CallingConventions callingConvention,
Type[] parameterTypes, Type[][] requiredCustomModifiers, Type[][] optionalCustomModifiers)
}
}
- [System.Security.SecurityCritical] // auto-generated
private ConstructorBuilder DefineConstructorNoLock(MethodAttributes attributes, CallingConventions callingConvention,
Type[] parameterTypes, Type[][] requiredCustomModifiers, Type[][] optionalCustomModifiers)
{
#endregion
#region Define PInvoke
-#if FEATURE_CORECLR
- [System.Security.SecurityCritical] // auto-generated
-#else
- [System.Security.SecuritySafeCritical]
-#endif
public MethodBuilder DefinePInvokeMethod(String name, String dllName, MethodAttributes attributes,
CallingConventions callingConvention, Type returnType, Type[] parameterTypes,
CallingConvention nativeCallConv, CharSet nativeCharSet)
return method;
}
-#if FEATURE_CORECLR
- [System.Security.SecurityCritical] // auto-generated
-#else
- [System.Security.SecuritySafeCritical]
-#endif
public MethodBuilder DefinePInvokeMethod(String name, String dllName, String entryName, MethodAttributes attributes,
CallingConventions callingConvention, Type returnType, Type[] parameterTypes,
CallingConvention nativeCallConv, CharSet nativeCharSet)
return method;
}
-#if FEATURE_CORECLR
- [System.Security.SecurityCritical] // auto-generated
-#else
- [System.Security.SecuritySafeCritical]
-#endif
public MethodBuilder DefinePInvokeMethod(String name, String dllName, String entryName, MethodAttributes attributes,
CallingConventions callingConvention,
Type returnType, Type[] returnTypeRequiredCustomModifiers, Type[] returnTypeOptionalCustomModifiers,
#endregion
#region Define Nested Type
- [System.Security.SecuritySafeCritical] // auto-generated
public TypeBuilder DefineNestedType(String name)
{
lock(SyncRoot)
}
}
- [System.Security.SecuritySafeCritical] // auto-generated
[System.Runtime.InteropServices.ComVisible(true)]
public TypeBuilder DefineNestedType(String name, TypeAttributes attr, Type parent, Type[] interfaces)
{
}
}
- [System.Security.SecuritySafeCritical] // auto-generated
public TypeBuilder DefineNestedType(String name, TypeAttributes attr, Type parent)
{
lock(SyncRoot)
}
}
- [System.Security.SecuritySafeCritical] // auto-generated
public TypeBuilder DefineNestedType(String name, TypeAttributes attr)
{
lock(SyncRoot)
}
}
-#if FEATURE_CORECLR
- [System.Security.SecurityCritical] // auto-generated
-#else
- [System.Security.SecuritySafeCritical]
-#endif
public TypeBuilder DefineNestedType(String name, TypeAttributes attr, Type parent, int typeSize)
{
lock(SyncRoot)
}
}
-#if FEATURE_CORECLR
- [System.Security.SecurityCritical] // auto-generated
-#else
- [System.Security.SecuritySafeCritical]
-#endif
public TypeBuilder DefineNestedType(String name, TypeAttributes attr, Type parent, PackingSize packSize)
{
lock(SyncRoot)
}
}
-#if FEATURE_CORECLR
- [System.Security.SecurityCritical] // auto-generated
-#else
- [System.Security.SecuritySafeCritical]
-#endif
public TypeBuilder DefineNestedType(String name, TypeAttributes attr, Type parent, PackingSize packSize, int typeSize)
{
lock (SyncRoot)
}
}
- [System.Security.SecurityCritical] // auto-generated
private TypeBuilder DefineNestedTypeNoLock(String name, TypeAttributes attr, Type parent, Type[] interfaces, PackingSize packSize, int typeSize)
{
return new TypeBuilder(name, attr, parent, interfaces, m_module, packSize, typeSize, this);
return DefineField(fieldName, type, null, null, attributes);
}
- [System.Security.SecuritySafeCritical] // auto-generated
public FieldBuilder DefineField(String fieldName, Type type, Type[] requiredCustomModifiers,
Type[] optionalCustomModifiers, FieldAttributes attributes)
{
}
}
- [System.Security.SecurityCritical] // auto-generated
private FieldBuilder DefineFieldNoLock(String fieldName, Type type, Type[] requiredCustomModifiers,
Type[] optionalCustomModifiers, FieldAttributes attributes)
{
return new FieldBuilder(this, fieldName, type, requiredCustomModifiers, optionalCustomModifiers, attributes);
}
-#if FEATURE_CORECLR
- [System.Security.SecurityCritical] // auto-generated
-#else
- [System.Security.SecuritySafeCritical]
-#endif
public FieldBuilder DefineInitializedData(String name, byte[] data, FieldAttributes attributes)
{
lock(SyncRoot)
}
}
- [System.Security.SecurityCritical] // auto-generated
private FieldBuilder DefineInitializedDataNoLock(String name, byte[] data, FieldAttributes attributes)
{
if (data == null)
return DefineDataHelper(name, data, data.Length, attributes);
}
-#if FEATURE_CORECLR
- [System.Security.SecurityCritical] // auto-generated
-#else
- [System.Security.SecuritySafeCritical]
-#endif
public FieldBuilder DefineUninitializedData(String name, int size, FieldAttributes attributes)
{
lock(SyncRoot)
}
}
- [System.Security.SecurityCritical] // auto-generated
private FieldBuilder DefineUninitializedDataNoLock(String name, int size, FieldAttributes attributes)
{
// This method will define an uninitialized Data in .sdata.
parameterTypes, parameterTypeRequiredCustomModifiers, parameterTypeOptionalCustomModifiers);
}
- [System.Security.SecuritySafeCritical] // auto-generated
public PropertyBuilder DefineProperty(String name, PropertyAttributes attributes, CallingConventions callingConvention,
Type returnType, Type[] returnTypeRequiredCustomModifiers, Type[] returnTypeOptionalCustomModifiers,
Type[] parameterTypes, Type[][] parameterTypeRequiredCustomModifiers, Type[][] parameterTypeOptionalCustomModifiers)
}
}
- [System.Security.SecurityCritical] // auto-generated
private PropertyBuilder DefinePropertyNoLock(String name, PropertyAttributes attributes, CallingConventions callingConvention,
Type returnType, Type[] returnTypeRequiredCustomModifiers, Type[] returnTypeOptionalCustomModifiers,
Type[] parameterTypes, Type[][] parameterTypeRequiredCustomModifiers, Type[][] parameterTypeOptionalCustomModifiers)
this);
}
- [System.Security.SecuritySafeCritical] // auto-generated
public EventBuilder DefineEvent(String name, EventAttributes attributes, Type eventtype)
{
lock(SyncRoot)
}
}
- [System.Security.SecurityCritical] // auto-generated
private EventBuilder DefineEventNoLock(String name, EventAttributes attributes, Type eventtype)
{
if (name == null)
#region Create Type
- [System.Security.SecuritySafeCritical] // auto-generated
public TypeInfo CreateTypeInfo()
{
lock (SyncRoot)
}
}
- [System.Security.SecuritySafeCritical] // auto-generated
public Type CreateType()
{
lock (SyncRoot)
m_module.CheckContext(types);
}
- [System.Security.SecurityCritical] // auto-generated
private TypeInfo CreateTypeNoLock()
{
if (IsCreated())
}
}
- [System.Security.SecuritySafeCritical] // auto-generated
[System.Runtime.InteropServices.ComVisible(true)]
public void AddInterfaceImplementation(Type interfaceType)
{
m_typeInterfaces.Add(interfaceType);
}
-#if FEATURE_CAS_POLICY
- [System.Security.SecuritySafeCritical] // auto-generated
- public void AddDeclarativeSecurity(SecurityAction action, PermissionSet pset)
- {
- lock(SyncRoot)
- {
- AddDeclarativeSecurityNoLock(action, pset);
- }
- }
-
- [System.Security.SecurityCritical] // auto-generated
- private void AddDeclarativeSecurityNoLock(SecurityAction action, PermissionSet pset)
- {
- if (pset == null)
- throw new ArgumentNullException(nameof(pset));
-
-#pragma warning disable 618
- if (!Enum.IsDefined(typeof(SecurityAction), action) ||
- action == SecurityAction.RequestMinimum ||
- action == SecurityAction.RequestOptional ||
- action == SecurityAction.RequestRefuse)
- {
- throw new ArgumentOutOfRangeException(nameof(action));
- }
-#pragma warning restore 618
-
- Contract.EndContractBlock();
-
- ThrowIfCreated();
-
- // Translate permission set into serialized format(uses standard binary serialization format).
- byte[] blob = null;
- int length = 0;
- if (!pset.IsEmpty())
- {
- blob = pset.EncodeXml();
- length = blob.Length;
- }
-
- // Write the blob into the metadata.
- AddDeclarativeSecurity(m_module.GetNativeHandle(), m_tdType.Token, action, blob, length);
- }
-#endif // FEATURE_CAS_POLICY
-
public TypeToken TypeToken
{
get
}
-#if FEATURE_CORECLR
- [System.Security.SecurityCritical] // auto-generated
-#else
- [System.Security.SecuritySafeCritical]
-#endif
[System.Runtime.InteropServices.ComVisible(true)]
public void SetCustomAttribute(ConstructorInfo con, byte[] binaryAttribute)
{
binaryAttribute, false, false);
}
- [System.Security.SecuritySafeCritical] // auto-generated
public void SetCustomAttribute(CustomAttributeBuilder customBuilder)
{
if (customBuilder == null)
#endregion
#endregion
-
-#if !FEATURE_CORECLR
- void _TypeBuilder.GetTypeInfoCount(out uint pcTInfo)
- {
- throw new NotImplementedException();
- }
-
- void _TypeBuilder.GetTypeInfo(uint iTInfo, uint lcid, IntPtr ppTInfo)
- {
- throw new NotImplementedException();
- }
-
- void _TypeBuilder.GetIDsOfNames([In] ref Guid riid, IntPtr rgszNames, uint cNames, uint lcid, IntPtr rgDispId)
- {
- throw new NotImplementedException();
- }
-
- void _TypeBuilder.Invoke(uint dispIdMember, [In] ref Guid riid, uint lcid, short wFlags, IntPtr pDispParams, IntPtr pVarResult, IntPtr pExcepInfo, IntPtr puArgErr)
- {
- throw new NotImplementedException();
- }
-#endif
}
}
// This class is describing the fieldmarshal.
[Serializable]
- [HostProtection(MayLeakOnAbort = true)]
[System.Runtime.InteropServices.ComVisible(true)]
[Obsolete("An alternate API is available: Emit the MarshalAs custom attribute instead. http://go.microsoft.com/fwlink/?linkid=14202")]
public sealed class UnmanagedMarshal
using System.Collections;
using System.Collections.Generic;
using System.Globalization;
+ using System.Diagnostics;
using System.Diagnostics.Contracts;
internal sealed class MethodOnTypeBuilderInstantiation : MethodInfo
#region Constructor
internal MethodOnTypeBuilderInstantiation(MethodInfo method, TypeBuilderInstantiation type)
{
- Contract.Assert(method is MethodBuilder || method is RuntimeMethodInfo);
+ Debug.Assert(method is MethodBuilder || method is RuntimeMethodInfo);
m_method = method;
m_type = type;
return mb.MetadataTokenInternal;
else
{
- Contract.Assert(m_method is RuntimeMethodInfo);
+ Debug.Assert(m_method is RuntimeMethodInfo);
return m_method.MetadataToken;
}
}
#region Constructor
internal ConstructorOnTypeBuilderInstantiation(ConstructorInfo constructor, TypeBuilderInstantiation type)
{
- Contract.Assert(constructor is ConstructorBuilder || constructor is RuntimeConstructorInfo);
+ Debug.Assert(constructor is ConstructorBuilder || constructor is RuntimeConstructorInfo);
m_ctor = constructor;
m_type = type;
return cb.MetadataTokenInternal;
else
{
- Contract.Assert(m_ctor is RuntimeConstructorInfo);
+ Debug.Assert(m_ctor is RuntimeConstructorInfo);
return m_ctor.MetadataToken;
}
}
#region Constructor
internal FieldOnTypeBuilderInstantiation(FieldInfo field, TypeBuilderInstantiation type)
{
- Contract.Assert(field is FieldBuilder || field is RuntimeFieldInfo);
+ Debug.Assert(field is FieldBuilder || field is RuntimeFieldInfo);
m_field = field;
m_type = type;
return fb.MetadataTokenInternal;
else
{
- Contract.Assert(m_field is RuntimeFieldInfo);
+ Debug.Assert(m_field is RuntimeFieldInfo);
return m_field.MetadataToken;
}
}
[Serializable]
[ClassInterface(ClassInterfaceType.None)]
[ComDefaultInterface(typeof(_EventInfo))]
-#pragma warning disable 618
- [PermissionSetAttribute(SecurityAction.InheritanceDemand, Name = "FullTrust")]
-#pragma warning restore 618
[System.Runtime.InteropServices.ComVisible(true)]
public abstract class EventInfo : MemberInfo, _EventInfo
{
throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_NotSupportedOnWinRTEvent"));
// Must be a normal non-WinRT event
- Contract.Assert(addMethod.ReturnType == typeof(void));
+ Debug.Assert(addMethod.ReturnType == typeof(void));
#endif // FEATURE_COMINTEROP
addMethod.Invoke(target, new object[] { handler });
#if FEATURE_COMINTEROP
ParameterInfo[] parameters = removeMethod.GetParametersNoCopy();
- Contract.Assert(parameters != null && parameters.Length == 1);
+ Debug.Assert(parameters != null && parameters.Length == 1);
if (parameters[0].ParameterType == typeof(System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken))
throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_NotSupportedOnWinRTEvent"));
// Must be a normal non-WinRT event
- Contract.Assert(parameters[0].ParameterType.BaseType == typeof(MulticastDelegate));
+ Debug.Assert(parameters[0].ParameterType.BaseType == typeof(MulticastDelegate));
#endif // FEATURE_COMINTEROP
removeMethod.Invoke(target, new object[] { handler });
}
}
#endregion
-
-#if !FEATURE_CORECLR
- Type _EventInfo.GetType()
- {
- return base.GetType();
- }
-
- void _EventInfo.GetTypeInfoCount(out uint pcTInfo)
- {
- throw new NotImplementedException();
- }
-
- void _EventInfo.GetTypeInfo(uint iTInfo, uint lcid, IntPtr ppTInfo)
- {
- throw new NotImplementedException();
- }
-
- void _EventInfo.GetIDsOfNames([In] ref Guid riid, IntPtr rgszNames, uint cNames, uint lcid, IntPtr rgDispId)
- {
- throw new NotImplementedException();
- }
-
- // If you implement this method, make sure to include _EventInfo.Invoke in VM\DangerousAPIs.h and
- // include _EventInfo in SystemDomain::IsReflectionInvocationMethod in AppDomain.cpp.
- void _EventInfo.Invoke(uint dispIdMember, [In] ref Guid riid, uint lcid, short wFlags, IntPtr pDispParams, IntPtr pVarResult, IntPtr pExcepInfo, IntPtr puArgErr)
- {
- throw new NotImplementedException();
- }
-#endif
}
[Serializable]
private int m_token;
private EventAttributes m_flags;
private string m_name;
- [System.Security.SecurityCritical]
private void* m_utf8name;
private RuntimeTypeCache m_reflectedTypeCache;
private RuntimeMethodInfo m_addMethod;
{
// Used for dummy head node during population
}
- [System.Security.SecurityCritical] // auto-generated
internal RuntimeEventInfo(int tkEvent, RuntimeType declaredType, RuntimeTypeCache reflectedTypeCache, out bool isPrivate)
{
Contract.Requires(declaredType != null);
Contract.Requires(reflectedTypeCache != null);
- Contract.Assert(!reflectedTypeCache.IsGlobal);
+ Debug.Assert(!reflectedTypeCache.IsGlobal);
MetadataImport scope = declaredType.GetRuntimeModule().MetadataImport;
return CustomAttribute.GetCustomAttributes(this, attributeRuntimeType);
}
- [System.Security.SecuritySafeCritical] // auto-generated
public override bool IsDefined(Type attributeType, bool inherit)
{
if (attributeType == null)
public override MemberTypes MemberType { get { return MemberTypes.Event; } }
public override String Name
{
- [System.Security.SecuritySafeCritical] // auto-generated
get
{
if (m_name == null)
#endregion
#region ISerializable
- [System.Security.SecurityCritical] // auto-generated_required
public void GetObjectData(SerializationInfo info, StreamingContext context)
{
if (info == null)
using System.Runtime.CompilerServices;
using System.Runtime.ConstrainedExecution;
using System.Runtime.InteropServices;
-#if FEATURE_REMOTING
- using System.Runtime.Remoting.Metadata;
-#endif //FEATURE_REMOTING
using System.Runtime.Serialization;
using System.Security.Permissions;
using System.Threading;
[Serializable]
[ClassInterface(ClassInterfaceType.None)]
[ComDefaultInterface(typeof(_FieldInfo))]
-#pragma warning disable 618
- [PermissionSetAttribute(SecurityAction.InheritanceDemand, Name = "FullTrust")]
-#pragma warning restore 618
[System.Runtime.InteropServices.ComVisible(true)]
public abstract class FieldInfo : MemberInfo, _FieldInfo
{
}
#endregion
-
-#if !FEATURE_CORECLR
- Type _FieldInfo.GetType()
- {
- return base.GetType();
- }
-
- void _FieldInfo.GetTypeInfoCount(out uint pcTInfo)
- {
- throw new NotImplementedException();
- }
-
- void _FieldInfo.GetTypeInfo(uint iTInfo, uint lcid, IntPtr ppTInfo)
- {
- throw new NotImplementedException();
- }
-
- void _FieldInfo.GetIDsOfNames([In] ref Guid riid, IntPtr rgszNames, uint cNames, uint lcid, IntPtr rgDispId)
- {
- throw new NotImplementedException();
- }
-
- // If you implement this method, make sure to include _FieldInfo.Invoke in VM\DangerousAPIs.h and
- // include _FieldInfo in SystemDomain::IsReflectionInvocationMethod in AppDomain.cpp.
- void _FieldInfo.Invoke(uint dispIdMember, [In] ref Guid riid, uint lcid, short wFlags, IntPtr pDispParams, IntPtr pVarResult, IntPtr pExcepInfo, IntPtr puArgErr)
- {
- throw new NotImplementedException();
- }
-#endif
}
[Serializable]
}
#endregion
-#if FEATURE_REMOTING
- #region Legacy Remoting Cache
- // The size of CachedData is accounted for by BaseObjectWithCachedData in object.h.
- // This member is currently being used by Remoting for caching remoting data. If you
- // need to cache data here, talk to the Remoting team to work out a mechanism, so that
- // both caching systems can happily work together.
- private RemotingFieldCachedData m_cachedData;
-
- internal RemotingFieldCachedData RemotingCache
- {
- get
- {
- // This grabs an internal copy of m_cachedData and uses
- // that instead of looking at m_cachedData directly because
- // the cache may get cleared asynchronously. This prevents
- // us from having to take a lock.
- RemotingFieldCachedData cache = m_cachedData;
- if (cache == null)
- {
- cache = new RemotingFieldCachedData(this);
- RemotingFieldCachedData ret = Interlocked.CompareExchange(ref m_cachedData, cache, null);
- if (ret != null)
- cache = ret;
- }
- return cache;
- }
- }
- #endregion
-#endif //FEATURE_REMOTING
-
#region NonPublic Members
internal BindingFlags BindingFlags { get { return m_bindingFlags; } }
private RuntimeType ReflectedTypeInternal
return CustomAttribute.GetCustomAttributes(this, attributeRuntimeType);
}
- [System.Security.SecuritySafeCritical] // auto-generated
public override bool IsDefined(Type attributeType, bool inherit)
{
if (attributeType == null)
#endregion
#region ISerializable Implementation
- [System.Security.SecurityCritical] // auto-generated
public void GetObjectData(SerializationInfo info, StreamingContext context)
{
if (info == null)
internal unsafe sealed class RtFieldInfo : RuntimeFieldInfo, IRuntimeFieldInfo
{
#region FCalls
- [System.Security.SecurityCritical] // auto-generated
[MethodImplAttribute(MethodImplOptions.InternalCall)]
static private extern void PerformVisibilityCheckOnField(IntPtr field, Object target, RuntimeType declaringType, FieldAttributes attr, uint invocationFlags);
#endregion
private RuntimeAssembly GetRuntimeAssembly() { return m_declaringType.GetRuntimeAssembly(); }
#region Constructor
- [System.Security.SecurityCritical] // auto-generated
internal RtFieldInfo(
RuntimeFieldHandleInternal handle, RuntimeType declaringType, RuntimeTypeCache reflectedTypeCache, BindingFlags bindingFlags)
: base(reflectedTypeCache, declaringType, bindingFlags)
#region Private Members
RuntimeFieldHandleInternal IRuntimeFieldInfo.Value
{
- [System.Security.SecuritySafeCritical]
get
{
return new RuntimeFieldHandleInternal(m_fieldHandle);
return m.m_fieldHandle == m_fieldHandle;
}
- [System.Security.SecurityCritical]
[DebuggerStepThroughAttribute]
[Diagnostics.DebuggerHidden]
internal void InternalSetValue(Object obj, Object value, BindingFlags invokeAttr, Binder binder, CultureInfo culture, ref StackCrawlMark stackMark)
// InternalSetValue() instead. When the caller needs to perform
// consistency checks they should call CheckConsistency() before
// calling this method.
- [System.Security.SecurityCritical] // auto-generated
[DebuggerStepThroughAttribute]
[Diagnostics.DebuggerHidden]
internal void UnsafeSetValue(Object obj, Object value, BindingFlags invokeAttr, Binder binder, CultureInfo culture)
}
}
- [System.Security.SecuritySafeCritical]
[DebuggerStepThroughAttribute]
[Diagnostics.DebuggerHidden]
internal Object InternalGetValue(Object obj, ref StackCrawlMark stackMark)
// InternalGetValue() instead. When the caller needs to perform
// consistency checks they should call CheckConsistency() before
// calling this method.
- [System.Security.SecurityCritical]
[DebuggerStepThroughAttribute]
[Diagnostics.DebuggerHidden]
internal Object UnsafeGetValue(Object obj)
#region MemberInfo Overrides
public override String Name
{
- [System.Security.SecuritySafeCritical] // auto-generated
get
{
if (m_name == null)
public override int MetadataToken
{
- [System.Security.SecuritySafeCritical] // auto-generated
get { return RuntimeFieldHandle.GetToken(this); }
}
- [System.Security.SecuritySafeCritical] // auto-generated
internal override RuntimeModule GetRuntimeModule()
{
return RuntimeTypeHandle.GetModule(RuntimeFieldHandle.GetApproxDeclaringType(this));
public override object GetRawConstantValue() { throw new InvalidOperationException(); }
- [System.Security.SecuritySafeCritical] // auto-generated
[DebuggerStepThroughAttribute]
[Diagnostics.DebuggerHidden]
public override Object GetValueDirect(TypedReference obj)
}
}
- [System.Security.SecuritySafeCritical] // auto-generated
[DebuggerStepThroughAttribute]
[Diagnostics.DebuggerHidden]
public override void SetValue(Object obj, Object value, BindingFlags invokeAttr, Binder binder, CultureInfo culture)
InternalSetValue(obj, value, invokeAttr, binder, culture, ref stackMark);
}
- [System.Security.SecuritySafeCritical] // auto-generated
[DebuggerStepThroughAttribute]
[Diagnostics.DebuggerHidden]
public override void SetValueDirect(TypedReference obj, Object value)
public override Type FieldType
{
- [System.Security.SecuritySafeCritical] // auto-generated
get
{
if (m_fieldType == null)
}
}
- [System.Security.SecuritySafeCritical] // auto-generated
public override Type[] GetRequiredCustomModifiers()
{
return new Signature(this, m_declaringType).GetCustomModifiers(1, true);
}
- [System.Security.SecuritySafeCritical] // auto-generated
public override Type[] GetOptionalCustomModifiers()
{
return new Signature(this, m_declaringType).GetCustomModifiers(1, false);
#region MemberInfo Overrides
public override String Name
{
- [System.Security.SecuritySafeCritical] // auto-generated
get
{
if (m_name == null)
public unsafe override Object GetRawConstantValue() { return GetValue(true); }
- [System.Security.SecuritySafeCritical] // auto-generated
private unsafe Object GetValue(bool raw)
{
// Cannot cache these because they could be user defined non-agile enumerations
public override Type FieldType
{
- [System.Security.SecuritySafeCritical] // auto-generated
get
{
if (m_fieldType == null)
internal IntPtr m_nativeLoaderAllocator;
[SuppressUnmanagedCodeSecurity]
- [SecurityCritical]
[DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
private static extern bool Destroy(IntPtr nativeLoaderAllocator);
- [SecuritySafeCritical]
~LoaderAllocatorScout()
{
if (m_nativeLoaderAllocator.IsNull())
internal static class MdConstant
{
- [System.Security.SecurityCritical] // auto-generated
public static unsafe Object GetValue(MetadataImport scope, int token, RuntimeTypeHandle fieldTypeHandle, bool raw)
{
CorElementType corElementType = 0;
public int Length { get { return m_length; } }
public byte this[int index]
{
- [System.Security.SecuritySafeCritical] // auto-generated
get
{
if (index < 0 || index >= m_length)
public int this[int index]
{
- [System.Security.SecurityCritical]
get
{
Contract.Requires(0 <= index && index < Length);
#endregion
#region Static Members
- [System.Security.SecurityCritical] // auto-generated
[MethodImplAttribute(MethodImplOptions.InternalCall)]
private static extern void _GetMarshalAs(IntPtr pNativeType, int cNativeType, out int unmanagedType, out int safeArraySubType, out string safeArrayUserDefinedSubType,
out int arraySubType, out int sizeParamIndex, out int sizeConst, out string marshalType, out string marshalCookie,
out int iidParamIndex);
- [System.Security.SecurityCritical] // auto-generated
internal static void GetMarshalAs(ConstArray nativeType,
out UnmanagedType unmanagedType, out VarEnum safeArraySubType, out string safeArrayUserDefinedSubType,
out UnmanagedType arraySubType, out int sizeParamIndex, out int sizeConst, out string marshalType, out string marshalCookie,
#endregion
#region FCalls
- [System.Security.SecurityCritical] // auto-generated
[MethodImplAttribute (MethodImplOptions.InternalCall)]
private unsafe static extern void _Enum(IntPtr scope, int type, int parent, out MetadataEnumResult result);
- [System.Security.SecurityCritical] // auto-generated
public unsafe void Enum(MetadataTokenType type, int parent, out MetadataEnumResult result)
{
_Enum(m_metadataImport2, (int)type, parent, out result);
}
- [System.Security.SecurityCritical] // auto-generated
public unsafe void EnumNestedTypes(int mdTypeDef, out MetadataEnumResult result)
{
Enum(MetadataTokenType.TypeDef, mdTypeDef, out result);
}
- [System.Security.SecurityCritical] // auto-generated
public unsafe void EnumCustomAttributes(int mdToken, out MetadataEnumResult result)
{
Enum(MetadataTokenType.CustomAttribute, mdToken, out result);
}
- [System.Security.SecurityCritical] // auto-generated
public unsafe void EnumParams(int mdMethodDef, out MetadataEnumResult result)
{
Enum(MetadataTokenType.ParamDef, mdMethodDef, out result);
}
- [System.Security.SecurityCritical] // auto-generated
public unsafe void EnumFields(int mdTypeDef, out MetadataEnumResult result)
{
Enum(MetadataTokenType.FieldDef, mdTypeDef, out result);
}
- [System.Security.SecurityCritical] // auto-generated
public unsafe void EnumProperties(int mdTypeDef, out MetadataEnumResult result)
{
Enum(MetadataTokenType.Property, mdTypeDef, out result);
}
- [System.Security.SecurityCritical] // auto-generated
public unsafe void EnumEvents(int mdTypeDef, out MetadataEnumResult result)
{
Enum(MetadataTokenType.Event, mdTypeDef, out result);
}
- [System.Security.SecurityCritical] // auto-generated
[MethodImplAttribute (MethodImplOptions.InternalCall)]
private static extern String _GetDefaultValue(IntPtr scope, int mdToken, out long value, out int length, out int corElementType);
- [System.Security.SecurityCritical] // auto-generated
public String GetDefaultValue(int mdToken, out long value, out int length, out CorElementType corElementType)
{
int _corElementType;
return stringVal;
}
- [System.Security.SecurityCritical] // auto-generated
[MethodImplAttribute (MethodImplOptions.InternalCall)]
private static unsafe extern void _GetUserString(IntPtr scope, int mdToken, void** name, out int length);
- [System.Security.SecurityCritical] // auto-generated
public unsafe String GetUserString(int mdToken)
{
void* name;
return new String(c);
}
- [System.Security.SecurityCritical] // auto-generated
[MethodImplAttribute (MethodImplOptions.InternalCall)]
private static unsafe extern void _GetName(IntPtr scope, int mdToken, void** name);
- [System.Security.SecurityCritical] // auto-generated
public unsafe Utf8String GetName(int mdToken)
{
void* name;
return new Utf8String(name);
}
- [System.Security.SecurityCritical] // auto-generated
[MethodImplAttribute (MethodImplOptions.InternalCall)]
private static unsafe extern void _GetNamespace(IntPtr scope, int mdToken, void** namesp);
- [System.Security.SecurityCritical] // auto-generated
public unsafe Utf8String GetNamespace(int mdToken)
{
void* namesp;
return new Utf8String(namesp);
}
- [System.Security.SecurityCritical] // auto-generated
[MethodImplAttribute (MethodImplOptions.InternalCall)]
private unsafe static extern void _GetEventProps(IntPtr scope, int mdToken, void** name, out int eventAttributes);
- [System.Security.SecurityCritical] // auto-generated
public unsafe void GetEventProps(int mdToken, out void* name, out EventAttributes eventAttributes)
{
int _eventAttributes;
eventAttributes = (EventAttributes)_eventAttributes;
}
- [System.Security.SecurityCritical] // auto-generated
[MethodImplAttribute (MethodImplOptions.InternalCall)]
private static extern void _GetFieldDefProps(IntPtr scope, int mdToken, out int fieldAttributes);
- [System.Security.SecurityCritical] // auto-generated
public void GetFieldDefProps(int mdToken, out FieldAttributes fieldAttributes)
{
int _fieldAttributes;
fieldAttributes = (FieldAttributes)_fieldAttributes;
}
- [System.Security.SecurityCritical] // auto-generated
[MethodImplAttribute (MethodImplOptions.InternalCall)]
private unsafe static extern void _GetPropertyProps(IntPtr scope,
int mdToken, void** name, out int propertyAttributes, out ConstArray signature);
- [System.Security.SecurityCritical] // auto-generated
public unsafe void GetPropertyProps(int mdToken, out void* name, out PropertyAttributes propertyAttributes, out ConstArray signature)
{
int _propertyAttributes;
propertyAttributes = (PropertyAttributes)_propertyAttributes;
}
- [System.Security.SecurityCritical] // auto-generated
[MethodImplAttribute (MethodImplOptions.InternalCall)]
private static extern void _GetParentToken(IntPtr scope,
int mdToken, out int tkParent);
- [System.Security.SecurityCritical] // auto-generated
public int GetParentToken(int tkToken)
{
int tkParent;
return tkParent;
}
- [System.Security.SecurityCritical] // auto-generated
[MethodImplAttribute(MethodImplOptions.InternalCall)]
private static extern void _GetParamDefProps(IntPtr scope,
int parameterToken, out int sequence, out int attributes);
- [System.Security.SecurityCritical] // auto-generated
public void GetParamDefProps(int parameterToken, out int sequence, out ParameterAttributes attributes)
{
int _attributes;
attributes = (ParameterAttributes)_attributes;
}
- [System.Security.SecurityCritical] // auto-generated
[MethodImplAttribute(MethodImplOptions.InternalCall)]
private static extern void _GetGenericParamProps(IntPtr scope,
int genericParameter,
out int flags);
- [System.Security.SecurityCritical] // auto-generated
public void GetGenericParamProps(
int genericParameter,
out GenericParameterAttributes attributes)
attributes = (GenericParameterAttributes)_attributes;
}
- [System.Security.SecurityCritical] // auto-generated
[MethodImplAttribute(MethodImplOptions.InternalCall)]
private static extern void _GetScopeProps(IntPtr scope,
out Guid mvid);
- [System.Security.SecurityCritical] // auto-generated
public void GetScopeProps(
out Guid mvid)
{
}
- [System.Security.SecurityCritical] // auto-generated
public ConstArray GetMethodSignature(MetadataToken token)
{
if (token.IsMemberRef)
return GetSigOfMethodDef(token);
}
- [System.Security.SecurityCritical] // auto-generated
[MethodImplAttribute(MethodImplOptions.InternalCall)]
private static extern void _GetSigOfMethodDef(IntPtr scope,
int methodToken,
ref ConstArray signature);
- [System.Security.SecurityCritical] // auto-generated
public ConstArray GetSigOfMethodDef(int methodToken)
{
ConstArray signature = new ConstArray();
return signature;
}
- [System.Security.SecurityCritical] // auto-generated
[MethodImplAttribute(MethodImplOptions.InternalCall)]
private static extern void _GetSignatureFromToken(IntPtr scope,
int methodToken,
ref ConstArray signature);
- [System.Security.SecurityCritical] // auto-generated
public ConstArray GetSignatureFromToken(int token)
{
ConstArray signature = new ConstArray();
return signature;
}
- [System.Security.SecurityCritical] // auto-generated
[MethodImplAttribute(MethodImplOptions.InternalCall)]
private static extern void _GetMemberRefProps(IntPtr scope,
int memberTokenRef,
out ConstArray signature);
- [System.Security.SecurityCritical] // auto-generated
public ConstArray GetMemberRefProps(int memberTokenRef)
{
ConstArray signature = new ConstArray();
return signature;
}
- [System.Security.SecurityCritical] // auto-generated
[MethodImplAttribute(MethodImplOptions.InternalCall)]
private static extern void _GetCustomAttributeProps(IntPtr scope,
int customAttributeToken,
out int constructorToken,
out ConstArray signature);
- [System.Security.SecurityCritical] // auto-generated
public void GetCustomAttributeProps(
int customAttributeToken,
out int constructorToken,
out constructorToken, out signature);
}
- [System.Security.SecurityCritical] // auto-generated
[MethodImplAttribute(MethodImplOptions.InternalCall)]
private static extern void _GetClassLayout(IntPtr scope,
int typeTokenDef, out int packSize, out int classSize);
- [System.Security.SecurityCritical] // auto-generated
public void GetClassLayout(
int typeTokenDef,
out int packSize,
_GetClassLayout(m_metadataImport2, typeTokenDef, out packSize, out classSize);
}
- [System.Security.SecurityCritical] // auto-generated
[MethodImplAttribute(MethodImplOptions.InternalCall)]
private static extern bool _GetFieldOffset(IntPtr scope,
int typeTokenDef, int fieldTokenDef, out int offset);
- [System.Security.SecurityCritical] // auto-generated
public bool GetFieldOffset(
int typeTokenDef,
int fieldTokenDef,
return _GetFieldOffset(m_metadataImport2, typeTokenDef, fieldTokenDef, out offset);
}
- [System.Security.SecurityCritical] // auto-generated
[MethodImplAttribute(MethodImplOptions.InternalCall)]
private static extern void _GetSigOfFieldDef(IntPtr scope,
int fieldToken,
ref ConstArray fieldMarshal);
- [System.Security.SecurityCritical] // auto-generated
public ConstArray GetSigOfFieldDef(int fieldToken)
{
ConstArray fieldMarshal = new ConstArray();
return fieldMarshal;
}
- [System.Security.SecurityCritical] // auto-generated
[MethodImplAttribute(MethodImplOptions.InternalCall)]
private static extern void _GetFieldMarshal(IntPtr scope,
int fieldToken,
ref ConstArray fieldMarshal);
- [System.Security.SecurityCritical] // auto-generated
public ConstArray GetFieldMarshal(int fieldToken)
{
ConstArray fieldMarshal = new ConstArray();
return fieldMarshal;
}
- [System.Security.SecurityCritical] // auto-generated
[MethodImplAttribute(MethodImplOptions.InternalCall)]
private unsafe static extern void _GetPInvokeMap(IntPtr scope,
int token,
void** importName,
void** importDll);
- [System.Security.SecurityCritical] // auto-generated
public unsafe void GetPInvokeMap(
int token,
out PInvokeAttributes attributes,
attributes = (PInvokeAttributes)_attributes;
}
- [System.Security.SecurityCritical] // auto-generated
[MethodImplAttribute(MethodImplOptions.InternalCall)]
private static extern bool _IsValidToken(IntPtr scope, int token);
- [System.Security.SecurityCritical] // auto-generated
public bool IsValidToken(int token)
{
return _IsValidToken(m_metadataImport2, token);
[Serializable]
[ClassInterface(ClassInterfaceType.None)]
[ComDefaultInterface(typeof(_MemberInfo))]
-#pragma warning disable 618
- [PermissionSetAttribute(SecurityAction.InheritanceDemand, Name = "FullTrust")]
-#pragma warning restore 618
[System.Runtime.InteropServices.ComVisible(true)]
public abstract class MemberInfo : ICustomAttributeProvider, _MemberInfo
{
{
return base.GetHashCode();
}
-
-#if !FEATURE_CORECLR
- // this method is required so Object.GetType is not made final virtual by the compiler
- Type _MemberInfo.GetType()
- {
- return base.GetType();
- }
-
- void _MemberInfo.GetTypeInfoCount(out uint pcTInfo)
- {
- throw new NotImplementedException();
- }
-
- void _MemberInfo.GetTypeInfo(uint iTInfo, uint lcid, IntPtr ppTInfo)
- {
- throw new NotImplementedException();
- }
-
- void _MemberInfo.GetIDsOfNames([In] ref Guid riid, IntPtr rgszNames, uint cNames, uint lcid, IntPtr rgDispId)
- {
- throw new NotImplementedException();
- }
-
- void _MemberInfo.Invoke(uint dispIdMember, [In] ref Guid riid, uint lcid, short wFlags, IntPtr pDispParams, IntPtr pVarResult, IntPtr pExcepInfo, IntPtr puArgErr)
- {
- throw new NotImplementedException();
- }
-#endif
}
}
#endregion
#region ISerializable
- [System.Security.SecurityCritical] // auto-generated
public virtual void GetObjectData(SerializationInfo info, StreamingContext context)
{
throw new NotSupportedException(Environment.GetResourceString(ResId.NotSupported_Method));
#endregion
#region IObjectReference
- [System.Security.SecurityCritical] // auto-generated
public virtual Object GetRealObject(StreamingContext context)
{
if (m_memberName == null || m_reflectedType == null || m_memberType == 0)
public static class AssemblyExtensions
{
[DllImport(JitHelpers.QCall)]
- [SecurityCritical] // unsafe method
[SuppressUnmanagedCodeSecurity]
[return: MarshalAs(UnmanagedType.Bool)]
private unsafe static extern bool InternalTryGetRawMetadata(RuntimeAssembly assembly, ref byte* blob, ref int length);
// associated, is alive. The caller is responsible for keeping the assembly object alive while accessing the
// metadata blob.
[CLSCompliant(false)] // out byte* blob
- [SecurityCritical] // unsafe method
public unsafe static bool TryGetRawMetadata(this Assembly assembly, out byte* blob, out int length)
{
if (assembly == null)
[Serializable]
[ClassInterface(ClassInterfaceType.None)]
[ComDefaultInterface(typeof(_MethodBase))]
-#pragma warning disable 618
- [PermissionSetAttribute(SecurityAction.InheritanceDemand, Name = "FullTrust")]
-#pragma warning restore 618
[System.Runtime.InteropServices.ComVisible(true)]
public abstract class MethodBase : MemberInfo, _MethodBase
{
#region Internal Members
// used by EE
- [System.Security.SecurityCritical]
private IntPtr GetMethodDesc() { return MethodHandle.Value; }
#if FEATURE_APPX
}
}
- [System.Security.SecuritySafeCritical]
#pragma warning disable 618
[ReflectionPermissionAttribute(SecurityAction.Demand, Flags=ReflectionPermissionFlag.MemberAccess)]
#pragma warning restore 618
return parameterTypes;
}
- [System.Security.SecuritySafeCritical]
internal Object[] CheckArguments(Object[] parameters, Binder binder,
BindingFlags invokeAttr, CultureInfo culture, Signature sig)
{
return copyOfParameters;
}
#endregion
-
- #region _MethodBase Implementation
-#if !FEATURE_CORECLR
- Type _MethodBase.GetType() { return base.GetType(); }
- bool _MethodBase.IsPublic { get { return IsPublic; } }
- bool _MethodBase.IsPrivate { get { return IsPrivate; } }
- bool _MethodBase.IsFamily { get { return IsFamily; } }
- bool _MethodBase.IsAssembly { get { return IsAssembly; } }
- bool _MethodBase.IsFamilyAndAssembly { get { return IsFamilyAndAssembly; } }
- bool _MethodBase.IsFamilyOrAssembly { get { return IsFamilyOrAssembly; } }
- bool _MethodBase.IsStatic { get { return IsStatic; } }
- bool _MethodBase.IsFinal { get { return IsFinal; } }
- bool _MethodBase.IsVirtual { get { return IsVirtual; } }
- bool _MethodBase.IsHideBySig { get { return IsHideBySig; } }
- bool _MethodBase.IsAbstract { get { return IsAbstract; } }
- bool _MethodBase.IsSpecialName { get { return IsSpecialName; } }
- bool _MethodBase.IsConstructor { get { return IsConstructor; } }
-
- void _MethodBase.GetTypeInfoCount(out uint pcTInfo)
- {
- throw new NotImplementedException();
- }
-
- void _MethodBase.GetTypeInfo(uint iTInfo, uint lcid, IntPtr ppTInfo)
- {
- throw new NotImplementedException();
- }
-
- void _MethodBase.GetIDsOfNames([In] ref Guid riid, IntPtr rgszNames, uint cNames, uint lcid, IntPtr rgDispId)
- {
- throw new NotImplementedException();
- }
-
- // If you implement this method, make sure to include _MethodBase.Invoke in VM\DangerousAPIs.h and
- // include _MethodBase in SystemDomain::IsReflectionInvocationMethod in AppDomain.cpp.
- void _MethodBase.Invoke(uint dispIdMember, [In] ref Guid riid, uint lcid, short wFlags, IntPtr pDispParams, IntPtr pVarResult, IntPtr pExcepInfo, IntPtr puArgErr)
- {
- throw new NotImplementedException();
- }
-#endif
- #endregion
}
-
}
using System;
using System.Globalization;
using System.Collections.Generic;
+using System.Diagnostics;
using System.Diagnostics.Contracts;
namespace System.Reflection
#endregion
#region Public Members
- public virtual Type LocalType { get { Contract.Assert(m_type != null, "type must be set!"); return m_type; } }
+ public virtual Type LocalType { get { Debug.Assert(m_type != null, "type must be set!"); return m_type; } }
public virtual bool IsPinned { get { return m_isPinned != 0; } }
public virtual int LocalIndex { get { return m_localIndex; } }
#endregion
using System.Runtime;
using System.Runtime.InteropServices;
using System.Runtime.ConstrainedExecution;
-#if FEATURE_REMOTING
- using System.Runtime.Remoting.Metadata;
-#endif //FEATURE_REMOTING
using System.Runtime.Serialization;
using System.Security;
using System.Security.Permissions;
[Serializable]
[ClassInterface(ClassInterfaceType.None)]
[ComDefaultInterface(typeof(_MethodInfo))]
-#pragma warning disable 618
- [PermissionSetAttribute(SecurityAction.InheritanceDemand, Name = "FullTrust")]
-#pragma warning restore 618
[System.Runtime.InteropServices.ComVisible(true)]
public abstract class MethodInfo : MethodBase, _MethodInfo
{
public virtual Delegate CreateDelegate(Type delegateType) { throw new NotSupportedException(Environment.GetResourceString("NotSupported_SubclassOverride")); }
public virtual Delegate CreateDelegate(Type delegateType, Object target) { throw new NotSupportedException(Environment.GetResourceString("NotSupported_SubclassOverride")); }
#endregion
-
-#if !FEATURE_CORECLR
- Type _MethodInfo.GetType()
- {
- return base.GetType();
- }
-
- void _MethodInfo.GetTypeInfoCount(out uint pcTInfo)
- {
- throw new NotImplementedException();
- }
-
- void _MethodInfo.GetTypeInfo(uint iTInfo, uint lcid, IntPtr ppTInfo)
- {
- throw new NotImplementedException();
- }
-
- void _MethodInfo.GetIDsOfNames([In] ref Guid riid, IntPtr rgszNames, uint cNames, uint lcid, IntPtr rgDispId)
- {
- throw new NotImplementedException();
- }
-
- // If you implement this method, make sure to include _MethodInfo.Invoke in VM\DangerousAPIs.h and
- // include _MethodInfo in SystemDomain::IsReflectionInvocationMethod in AppDomain.cpp.
- void _MethodInfo.Invoke(uint dispIdMember, [In] ref Guid riid, uint lcid, short wFlags, IntPtr pDispParams, IntPtr pVarResult, IntPtr pExcepInfo, IntPtr puArgErr)
- {
- throw new NotImplementedException();
- }
-#endif
}
[Serializable]
internal INVOCATION_FLAGS InvocationFlags
{
- [System.Security.SecuritySafeCritical]
get
{
if ((m_invocationFlags & INVOCATION_FLAGS.INVOCATION_FLAGS_INITIALIZED) == 0)
#endregion
#region Constructor
- [System.Security.SecurityCritical] // auto-generated
internal RuntimeMethodInfo(
RuntimeMethodHandleInternal handle, RuntimeType declaringType,
RuntimeTypeCache reflectedTypeCache, MethodAttributes methodAttributes, BindingFlags bindingFlags, object keepalive)
{
Contract.Ensures(!m_handle.IsNull());
- Contract.Assert(!handle.IsNullHandle());
- Contract.Assert(methodAttributes == RuntimeMethodHandle.GetAttributes(handle));
+ Debug.Assert(!handle.IsNullHandle());
+ Debug.Assert(methodAttributes == RuntimeMethodHandle.GetAttributes(handle));
m_bindingFlags = bindingFlags;
m_declaringType = declaringType;
}
#endregion
-#if FEATURE_REMOTING
- #region Legacy Remoting Cache
- // The size of CachedData is accounted for by BaseObjectWithCachedData in object.h.
- // This member is currently being used by Remoting for caching remoting data. If you
- // need to cache data here, talk to the Remoting team to work out a mechanism, so that
- // both caching systems can happily work together.
- private RemotingMethodCachedData m_cachedData;
-
- internal RemotingMethodCachedData RemotingCache
- {
- get
- {
- // This grabs an internal copy of m_cachedData and uses
- // that instead of looking at m_cachedData directly because
- // the cache may get cleared asynchronously. This prevents
- // us from having to take a lock.
- RemotingMethodCachedData cache = m_cachedData;
- if (cache == null)
- {
- cache = new RemotingMethodCachedData(this);
- RemotingMethodCachedData ret = Interlocked.CompareExchange(ref m_cachedData, cache, null);
- if (ret != null)
- cache = ret;
- }
- return cache;
- }
- }
- #endregion
-#endif //FEATURE_REMOTING
-
#region Private Methods
RuntimeMethodHandleInternal IRuntimeMethodInfo.Value
{
- [System.Security.SecuritySafeCritical]
get
{
return new RuntimeMethodHandleInternal(m_handle);
}
}
- [System.Security.SecurityCritical] // auto-generated
private ParameterInfo[] FetchNonReturnParameters()
{
if (m_parameters == null)
return m_parameters;
}
- [System.Security.SecurityCritical] // auto-generated
private ParameterInfo FetchReturnParameter()
{
if (m_returnParameter == null)
return new RuntimeMethodHandle(this);
}
- [System.Security.SecuritySafeCritical] // auto-generated
internal RuntimeMethodInfo GetParentDefinition()
{
if (!IsVirtual || m_declaringType.IsInterface)
return base.GetHashCode();
}
- [System.Security.SecuritySafeCritical] // auto-generated
public override bool Equals(object obj)
{
if (!IsGenericMethod)
#endregion
#region ICustomAttributeProvider
- [System.Security.SecuritySafeCritical] // auto-generated
public override Object[] GetCustomAttributes(bool inherit)
{
return CustomAttribute.GetCustomAttributes(this, typeof(object) as RuntimeType as RuntimeType, inherit);
}
- [System.Security.SecuritySafeCritical] // auto-generated
public override Object[] GetCustomAttributes(Type attributeType, bool inherit)
{
if (attributeType == null)
#region MemberInfo Overrides
public override String Name
{
- [System.Security.SecuritySafeCritical] // auto-generated
get
{
if (m_name == null)
public override MemberTypes MemberType { get { return MemberTypes.Method; } }
public override int MetadataToken
{
- [System.Security.SecuritySafeCritical] // auto-generated
get { return RuntimeMethodHandle.GetMethodDef(this); }
}
public override Module Module { get { return GetRuntimeModule(); } }
public override bool IsSecurityCritical
{
-#if FEATURE_CORECLR
get { return true; }
-#else
- get { return RuntimeMethodHandle.IsSecurityCritical(this); }
-#endif
}
public override bool IsSecuritySafeCritical
{
-#if FEATURE_CORECLR
get { return false; }
-#else
- get { return RuntimeMethodHandle.IsSecuritySafeCritical(this); }
-#endif
}
public override bool IsSecurityTransparent
{
-#if FEATURE_CORECLR
get { return false; }
-#else
- get { return RuntimeMethodHandle.IsSecurityTransparent(this); }
-#endif
}
#endregion
#region MethodBase Overrides
- [System.Security.SecuritySafeCritical] // auto-generated
internal override ParameterInfo[] GetParametersNoCopy()
{
FetchNonReturnParameters();
return m_parameters;
}
- [System.Security.SecuritySafeCritical] // auto-generated
[System.Diagnostics.Contracts.Pure]
public override ParameterInfo[] GetParameters()
{
}
}
- [System.Security.SecuritySafeCritical] // overrides SafeCritical member
-#if !FEATURE_CORECLR
-#pragma warning disable 618
- [ReflectionPermissionAttribute(SecurityAction.Demand, Flags = ReflectionPermissionFlag.MemberAccess)]
-#pragma warning restore 618
-#endif
public override MethodBody GetMethodBody()
{
MethodBody mb = RuntimeMethodHandle.GetMethodBody(this, ReflectedTypeInternal);
}
}
- [System.Security.SecuritySafeCritical]
private void ThrowNoInvokeException()
{
// method is ReflectionOnly
throw new TargetException();
}
- [System.Security.SecuritySafeCritical]
[DebuggerStepThroughAttribute]
[Diagnostics.DebuggerHidden]
[MethodImplAttribute(MethodImplOptions.NoInlining)] // Methods containing StackCrawlMark local var has to be marked non-inlineable
throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_APIInvalidForCurrentContext", FullName));
}
#endif
-
-#if !FEATURE_CORECLR
- if ((invocationFlags & (INVOCATION_FLAGS.INVOCATION_FLAGS_RISKY_METHOD | INVOCATION_FLAGS.INVOCATION_FLAGS_NEED_SECURITY)) != 0)
- {
- if ((invocationFlags & INVOCATION_FLAGS.INVOCATION_FLAGS_RISKY_METHOD) != 0)
- CodeAccessPermission.Demand(PermissionType.ReflectionMemberAccess);
-
- if ((invocationFlags & INVOCATION_FLAGS.INVOCATION_FLAGS_NEED_SECURITY) != 0)
- RuntimeMethodHandle.PerformSecurityCheck(obj, this, m_declaringType, (uint)m_invocationFlags);
- }
-#endif // !FEATURE_CORECLR
#endregion
return UnsafeInvokeInternal(obj, parameters, arguments);
}
- [System.Security.SecurityCritical]
[DebuggerStepThroughAttribute]
[Diagnostics.DebuggerHidden]
internal object UnsafeInvoke(Object obj, BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture)
return UnsafeInvokeInternal(obj, parameters, arguments);
}
- [System.Security.SecurityCritical]
[DebuggerStepThroughAttribute]
[Diagnostics.DebuggerHidden]
private object UnsafeInvokeInternal(Object obj, Object[] parameters, Object[] arguments)
public override ParameterInfo ReturnParameter
{
- [System.Security.SecuritySafeCritical] // auto-generated
get
{
Contract.Ensures(m_returnParameter != null);
}
}
- [System.Security.SecuritySafeCritical] // auto-generated
public override MethodInfo GetBaseDefinition()
{
if (!IsVirtual || IsStatic || m_declaringType == null || m_declaringType.IsInterface)
return(MethodInfo)RuntimeType.GetMethodBase(baseDeclaringType, baseMethodHandle);
}
- [System.Security.SecuritySafeCritical]
public override Delegate CreateDelegate(Type delegateType)
{
StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller;
ref stackMark);
}
- [System.Security.SecuritySafeCritical]
public override Delegate CreateDelegate(Type delegateType, Object target)
{
StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller;
ref stackMark);
}
- [System.Security.SecurityCritical]
private Delegate CreateDelegateInternal(Type delegateType, Object firstArgument, DelegateBindingFlags bindingFlags, ref StackCrawlMark stackMark)
{
// Validate the parameters.
#endregion
#region Generics
- [System.Security.SecuritySafeCritical] // auto-generated
public override MethodInfo MakeGenericMethod(params Type[] methodInstantiation)
{
if (methodInstantiation == null)
#endregion
#region ISerializable Implementation
- [System.Security.SecurityCritical] // auto-generated
public void GetObjectData(SerializationInfo info, StreamingContext context)
{
if (info == null)
#endregion
#region ISerializable
- [System.Security.SecurityCritical] // auto-generated_required
void ISerializable.GetObjectData(SerializationInfo info, StreamingContext context)
{
if (info == null)
[ClassInterface(ClassInterfaceType.None)]
[ComDefaultInterface(typeof(_Module))]
[System.Runtime.InteropServices.ComVisible(true)]
-#pragma warning disable 618
- [PermissionSetAttribute(SecurityAction.InheritanceDemand, Unrestricted = true)]
-#pragma warning restore 618
public abstract class Module : _Module, ISerializable, ICustomAttributeProvider
{
#region Static Constructor
}
}
- [System.Security.SecurityCritical] // auto-generated_required
public virtual void GetObjectData(SerializationInfo info, StreamingContext context)
{
throw new NotImplementedException();
public virtual String FullyQualifiedName
{
-#if FEATURE_CORECLR
- [System.Security.SecurityCritical] // auto-generated
-#endif
get
{
throw new NotImplementedException();
{
return ModuleHandle.EmptyHandle;
}
-
-#if FEATURE_X509 && FEATURE_CAS_POLICY
- public virtual System.Security.Cryptography.X509Certificates.X509Certificate GetSignerCertificate()
- {
- throw new NotImplementedException();
- }
-#endif // FEATURE_X509 && FEATURE_CAS_POLICY
#endregion
-
-#if !FEATURE_CORECLR
- void _Module.GetTypeInfoCount(out uint pcTInfo)
- {
- throw new NotImplementedException();
- }
-
- void _Module.GetTypeInfo(uint iTInfo, uint lcid, IntPtr ppTInfo)
- {
- throw new NotImplementedException();
- }
-
- void _Module.GetIDsOfNames([In] ref Guid riid, IntPtr rgszNames, uint cNames, uint lcid, IntPtr rgDispId)
- {
- throw new NotImplementedException();
- }
-
- void _Module.Invoke(uint dispIdMember, [In] ref Guid riid, uint lcid, short wFlags, IntPtr pDispParams, IntPtr pVarResult, IntPtr pExcepInfo, IntPtr puArgErr)
- {
- throw new NotImplementedException();
- }
-#endif
}
[Serializable]
internal RuntimeModule() { throw new NotSupportedException(); }
#region FCalls
- [System.Security.SecurityCritical] // auto-generated
[DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
[SuppressUnmanagedCodeSecurity]
private extern static void GetType(RuntimeModule module, String className, bool ignoreCase, bool throwOnError, ObjectHandleOnStack type, ObjectHandleOnStack keepAlive);
- [System.Security.SecurityCritical]
[DllImport(JitHelpers.QCall)]
[SuppressUnmanagedCodeSecurity]
private static extern bool nIsTransientInternal(RuntimeModule module);
- [System.Security.SecurityCritical] // auto-generated
[DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
[SuppressUnmanagedCodeSecurity]
private extern static void GetScopeName(RuntimeModule module, StringHandleOnStack retString);
- [System.Security.SecurityCritical] // auto-generated
[DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
[SuppressUnmanagedCodeSecurity]
private extern static void GetFullyQualifiedName(RuntimeModule module, StringHandleOnStack retString);
- [System.Security.SecurityCritical] // auto-generated
[MethodImplAttribute(MethodImplOptions.InternalCall)]
private extern static RuntimeType[] GetTypes(RuntimeModule module);
- [System.Security.SecuritySafeCritical] // auto-generated
internal RuntimeType[] GetDefinedTypes()
{
return GetTypes(GetNativeHandle());
}
- [System.Security.SecuritySafeCritical] // auto-generated
[MethodImplAttribute(MethodImplOptions.InternalCall)]
private extern static bool IsResource(RuntimeModule module);
-
-#if FEATURE_X509 && FEATURE_CAS_POLICY
- [System.Security.SecurityCritical] // auto-generated
- [DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
- [SuppressUnmanagedCodeSecurity]
- static private extern void GetSignerCertificate(RuntimeModule module, ObjectHandleOnStack retData);
-#endif // FEATURE_X509 && FEATURE_CAS_POLICY
#endregion
#region Module overrides
return typeHandleArgs;
}
- [System.Security.SecuritySafeCritical] // auto-generated
public override byte[] ResolveSignature(int metadataToken)
{
MetadataToken tk = new MetadataToken(metadataToken);
return sig;
}
- [System.Security.SecuritySafeCritical] // auto-generated
public override MethodBase ResolveMethod(int metadataToken, Type[] genericTypeArguments, Type[] genericMethodArguments)
{
MetadataToken tk = new MetadataToken(metadataToken);
}
}
- [System.Security.SecurityCritical] // auto-generated
private FieldInfo ResolveLiteralField(int metadataToken, Type[] genericTypeArguments, Type[] genericMethodArguments)
{
MetadataToken tk = new MetadataToken(metadataToken);
}
}
- [System.Security.SecuritySafeCritical] // auto-generated
public override FieldInfo ResolveField(int metadataToken, Type[] genericTypeArguments, Type[] genericMethodArguments)
{
MetadataToken tk = new MetadataToken(metadataToken);
}
}
- [System.Security.SecuritySafeCritical] // auto-generated
public override Type ResolveType(int metadataToken, Type[] genericTypeArguments, Type[] genericMethodArguments)
{
MetadataToken tk = new MetadataToken(metadataToken);
}
}
- [System.Security.SecuritySafeCritical] // auto-generated
public override MemberInfo ResolveMember(int metadataToken, Type[] genericTypeArguments, Type[] genericMethodArguments)
{
MetadataToken tk = new MetadataToken(metadataToken);
nameof(metadataToken));
}
- [System.Security.SecuritySafeCritical] // auto-generated
public override string ResolveString(int metadataToken)
{
MetadataToken tk = new MetadataToken(metadataToken);
public override int MDStreamVersion
{
- [System.Security.SecuritySafeCritical] // auto-generated
get
{
return ModuleHandle.GetMDStreamVersion(GetNativeHandle());
}
}
- [System.Security.SecuritySafeCritical]
internal bool IsTransientInternal()
{
return RuntimeModule.nIsTransientInternal(this.GetNativeHandle());
internal MetadataImport MetadataImport
{
- [System.Security.SecurityCritical] // auto-generated
get
{
unsafe
return CustomAttribute.GetCustomAttributes(this, attributeRuntimeType);
}
- [System.Security.SecuritySafeCritical] // auto-generated
public override bool IsDefined(Type attributeType, bool inherit)
{
if (attributeType == null)
#endregion
#region Public Virtuals
- [System.Security.SecurityCritical] // auto-generated_required
public override void GetObjectData(SerializationInfo info, StreamingContext context)
{
if (info == null)
UnitySerializationHolder.GetUnitySerializationInfo(info, UnitySerializationHolder.ModuleUnity, this.ScopeName, this.GetRuntimeAssembly());
}
- [System.Security.SecuritySafeCritical] // auto-generated
[System.Runtime.InteropServices.ComVisible(true)]
public override Type GetType(String className, bool throwOnError, bool ignoreCase)
{
return retType;
}
- [System.Security.SecurityCritical] // auto-generated
internal string GetFullyQualifiedName()
{
String fullyQualifiedName = null;
public override String FullyQualifiedName
{
-#if FEATURE_CORECLR
- [System.Security.SecurityCritical] // auto-generated
-#else
- [System.Security.SecuritySafeCritical]
-#endif
get
{
String fullyQualifiedName = GetFullyQualifiedName();
}
}
- [System.Security.SecuritySafeCritical] // auto-generated
public override Type[] GetTypes()
{
return GetTypes(GetNativeHandle());
public override Guid ModuleVersionId
{
- [System.Security.SecuritySafeCritical] // auto-generated
get
{
unsafe
public override int MetadataToken
{
- [System.Security.SecuritySafeCritical] // auto-generated
get
{
return ModuleHandle.GetToken(GetNativeHandle());
public override String ScopeName
{
- [System.Security.SecuritySafeCritical] // auto-generated
get
{
string scopeName = null;
public override String Name
{
- [System.Security.SecuritySafeCritical] // auto-generated
get
{
String s = GetFullyQualifiedName();
{
return this;
}
-
-#if FEATURE_X509 && FEATURE_CAS_POLICY
- [System.Security.SecuritySafeCritical] // auto-generated
- public override System.Security.Cryptography.X509Certificates.X509Certificate GetSignerCertificate()
- {
- byte[] data = null;
- GetSignerCertificate(GetNativeHandle(), JitHelpers.GetObjectHandleOnStack(ref data));
- return (data != null) ? new System.Security.Cryptography.X509Certificates.X509Certificate(data) : null;
- }
-#endif // FEATURE_X509 && FEATURE_CAS_POLICY
#endregion
}
}
{
using System;
using System.Collections.Generic;
+ using System.Diagnostics;
using System.Diagnostics.Contracts;
using System.Runtime.InteropServices;
using System.Runtime.Serialization;
using System.Runtime.CompilerServices;
-#if FEATURE_REMOTING
- using System.Runtime.Remoting.Metadata;
-#endif //FEATURE_REMOTING
using System.Security.Permissions;
using System.Threading;
using MdToken = System.Reflection.MetadataToken;
#region _ParameterInfo implementation
-#if !FEATURE_CORECLR
- void _ParameterInfo.GetTypeInfoCount(out uint pcTInfo)
- {
- throw new NotImplementedException();
- }
-
- void _ParameterInfo.GetTypeInfo(uint iTInfo, uint lcid, IntPtr ppTInfo)
- {
- throw new NotImplementedException();
- }
-
- void _ParameterInfo.GetIDsOfNames([In] ref Guid riid, IntPtr rgszNames, uint cNames, uint lcid, IntPtr rgDispId)
- {
- throw new NotImplementedException();
- }
-
- void _ParameterInfo.Invoke(uint dispIdMember, [In] ref Guid riid, uint lcid, short wFlags, IntPtr pDispParams, IntPtr pVarResult, IntPtr pExcepInfo, IntPtr puArgErr)
- {
- throw new NotImplementedException();
- }
-#endif
-
#endregion
#region IObjectReference
// In V4 RuntimeParameterInfo is introduced.
// To support deserializing ParameterInfo instances serialized in earlier versions
// we need to implement IObjectReference.
- [System.Security.SecurityCritical]
public object GetRealObject(StreamingContext context)
{
Contract.Ensures(Contract.Result<Object>() != null);
internal unsafe sealed class RuntimeParameterInfo : ParameterInfo, ISerializable
{
#region Static Members
- [System.Security.SecurityCritical] // auto-generated
internal unsafe static ParameterInfo[] GetParameters(IRuntimeMethodInfo method, MemberInfo member, Signature sig)
{
- Contract.Assert(method is RuntimeMethodInfo || method is RuntimeConstructorInfo);
+ Debug.Assert(method is RuntimeMethodInfo || method is RuntimeConstructorInfo);
ParameterInfo dummy;
return GetParameters(method, member, sig, out dummy, false);
}
- [System.Security.SecurityCritical] // auto-generated
internal unsafe static ParameterInfo GetReturnParameter(IRuntimeMethodInfo method, MemberInfo member, Signature sig)
{
- Contract.Assert(method is RuntimeMethodInfo || method is RuntimeConstructorInfo);
+ Debug.Assert(method is RuntimeMethodInfo || method is RuntimeConstructorInfo);
ParameterInfo returnParameter;
GetParameters(method, member, sig, out returnParameter, true);
return returnParameter;
}
- [System.Security.SecurityCritical] // auto-generated
internal unsafe static ParameterInfo[] GetParameters(
IRuntimeMethodInfo methodHandle, MemberInfo member, Signature sig, out ParameterInfo returnParameter, bool fetchReturnParameter)
{
get
{
MethodBase result = m_originalMember != null ? m_originalMember : MemberImpl as MethodBase;
- Contract.Assert(result != null);
+ Debug.Assert(result != null);
return result;
}
}
#endregion
#region VTS magic to serialize/deserialized to/from pre-Whidbey endpoints.
- [System.Security.SecurityCritical]
public void GetObjectData(SerializationInfo info, StreamingContext context)
{
if (info == null)
// The original owner should always be a method, because this method is only used to
// change the owner from a method to a property.
m_originalMember = accessor.MemberImpl as MethodBase;
- Contract.Assert(m_originalMember != null);
+ Debug.Assert(m_originalMember != null);
// Populate all the caches -- we inherit this behavior from RTM
NameImpl = accessor.Name;
int position, ParameterAttributes attributes, MemberInfo member)
{
Contract.Requires(member != null);
- Contract.Assert(MdToken.IsNullToken(tkParamDef) == scope.Equals(MetadataImport.EmptyImport));
- Contract.Assert(MdToken.IsNullToken(tkParamDef) || MdToken.IsTokenOfType(tkParamDef, MetadataTokenType.ParamDef));
+ Debug.Assert(MdToken.IsNullToken(tkParamDef) == scope.Equals(MetadataImport.EmptyImport));
+ Debug.Assert(MdToken.IsNullToken(tkParamDef) || MdToken.IsTokenOfType(tkParamDef, MetadataTokenType.ParamDef));
PositionImpl = position;
MemberImpl = member;
else
parameterType = m_signature.Arguments[PositionImpl];
- Contract.Assert(parameterType != null);
+ Debug.Assert(parameterType != null);
// different thread could only write ClassImpl to the same value, so a race condition is not a problem here
ClassImpl = parameterType;
}
public override String Name
{
- [System.Security.SecuritySafeCritical] // auto-generated
get
{
if (!m_nameIsCached)
}
// returns DBNull.Value if the parameter doesn't have a default value
- [System.Security.SecuritySafeCritical]
private Object GetDefaultValueInternal(bool raw)
{
- Contract.Assert(!m_noMetadata);
+ Debug.Assert(!m_noMetadata);
if (m_noDefaultValue)
return DBNull.Value;
return CustomAttribute.GetCustomAttributes(this, attributeRuntimeType);
}
- [System.Security.SecuritySafeCritical] // auto-generated
public override bool IsDefined(Type attributeType, bool inherit)
{
if (attributeType == null)
return CustomAttributeData.GetCustomAttributesInternal(this);
}
#endregion
-
-#if FEATURE_REMOTING
- #region Remoting Cache
- private RemotingParameterCachedData m_cachedData;
-
- internal RemotingParameterCachedData RemotingCache
- {
- get
- {
- // This grabs an internal copy of m_cachedData and uses
- // that instead of looking at m_cachedData directly because
- // the cache may get cleared asynchronously. This prevents
- // us from having to take a lock.
- RemotingParameterCachedData cache = m_cachedData;
- if (cache == null)
- {
- cache = new RemotingParameterCachedData(this);
- RemotingParameterCachedData ret = Interlocked.CompareExchange(ref m_cachedData, cache, null);
- if (ret != null)
- cache = ret;
- }
- return cache;
- }
- }
- #endregion
-#endif //FEATURE_REMOTING
}
}
[System.Runtime.InteropServices.ComVisible(true)]
public sealed class Pointer : ISerializable
{
- [SecurityCritical]
unsafe private void* _ptr;
private RuntimeType _ptrType;
private Pointer() {}
- [System.Security.SecurityCritical] // auto-generated
private unsafe Pointer(SerializationInfo info, StreamingContext context)
{
_ptr = ((IntPtr)(info.GetValue("_ptr", typeof(IntPtr)))).ToPointer();
// This method will box an pointer. We save both the
// value and the type so we can access it from the native code
// during an Invoke.
- [System.Security.SecurityCritical] // auto-generated
public static unsafe Object Box(void *ptr,Type type) {
if (type == null)
throw new ArgumentNullException(nameof(type));
}
// Returned the stored pointer.
- [System.Security.SecurityCritical] // auto-generated
public static unsafe void* Unbox(Object ptr) {
if (!(ptr is Pointer))
throw new ArgumentException(Environment.GetResourceString("Arg_MustBePointer"),nameof(ptr));
return _ptrType;
}
- [System.Security.SecurityCritical] // auto-generated
internal unsafe Object GetPointerValue() {
return (IntPtr)_ptr;
}
- [System.Security.SecurityCritical]
unsafe void ISerializable.GetObjectData(SerializationInfo info, StreamingContext context) {
info.AddValue("_ptr", new IntPtr(_ptr));
info.AddValue("_ptrType", _ptrType);
[Serializable]
[ClassInterface(ClassInterfaceType.None)]
[ComDefaultInterface(typeof(_PropertyInfo))]
-#pragma warning disable 618
- [PermissionSetAttribute(SecurityAction.InheritanceDemand, Name = "FullTrust")]
-#pragma warning restore 618
[System.Runtime.InteropServices.ComVisible(true)]
public abstract class PropertyInfo : MemberInfo, _PropertyInfo
{
public bool IsSpecialName { get { return(Attributes & PropertyAttributes.SpecialName) != 0; } }
#endregion
-
-#if !FEATURE_CORECLR
- Type _PropertyInfo.GetType()
- {
- return base.GetType();
- }
-
- void _PropertyInfo.GetTypeInfoCount(out uint pcTInfo)
- {
- throw new NotImplementedException();
- }
-
- void _PropertyInfo.GetTypeInfo(uint iTInfo, uint lcid, IntPtr ppTInfo)
- {
- throw new NotImplementedException();
- }
-
- void _PropertyInfo.GetIDsOfNames([In] ref Guid riid, IntPtr rgszNames, uint cNames, uint lcid, IntPtr rgDispId)
- {
- throw new NotImplementedException();
- }
-
- // If you implement this method, make sure to include _PropertyInfo.Invoke in VM\DangerousAPIs.h and
- // include _PropertyInfo in SystemDomain::IsReflectionInvocationMethod in AppDomain.cpp.
- void _PropertyInfo.Invoke(uint dispIdMember, [In] ref Guid riid, uint lcid, short wFlags, IntPtr pDispParams, IntPtr pVarResult, IntPtr pExcepInfo, IntPtr puArgErr)
- {
- throw new NotImplementedException();
- }
-#endif
}
[Serializable]
#region Private Data Members
private int m_token;
private string m_name;
- [System.Security.SecurityCritical]
private void* m_utf8name;
private PropertyAttributes m_flags;
private RuntimeTypeCache m_reflectedTypeCache;
#endregion
#region Constructor
- [System.Security.SecurityCritical] // auto-generated
internal RuntimePropertyInfo(
int tkProperty, RuntimeType declaredType, RuntimeTypeCache reflectedTypeCache, out bool isPrivate)
{
Contract.Requires(declaredType != null);
Contract.Requires(reflectedTypeCache != null);
- Contract.Assert(!reflectedTypeCache.IsGlobal);
+ Debug.Assert(!reflectedTypeCache.IsGlobal);
MetadataImport scope = declaredType.GetRuntimeModule().MetadataImport;
internal Signature Signature
{
- [System.Security.SecuritySafeCritical] // auto-generated
get
{
if (m_signature == null)
return CustomAttribute.GetCustomAttributes(this, attributeRuntimeType);
}
- [System.Security.SecuritySafeCritical] // auto-generated
public override bool IsDefined(Type attributeType, bool inherit)
{
if (attributeType == null)
public override MemberTypes MemberType { get { return MemberTypes.Property; } }
public override String Name
{
- [System.Security.SecuritySafeCritical] // auto-generated
get
{
if (m_name == null)
return Signature.GetCustomModifiers(0, false);
}
- [System.Security.SecuritySafeCritical] // auto-generated
internal object GetConstantValue(bool raw)
{
Object defaultValue = MdConstant.GetValue(GetRuntimeModule().MetadataImport, m_token, PropertyType.GetTypeHandleInternal(), raw);
#endregion
#region ISerializable Implementation
- [System.Security.SecurityCritical] // auto-generated
public void GetObjectData(SerializationInfo info, StreamingContext context)
{
if (info == null)
get {return _exceptions;}
}
- [System.Security.SecurityCritical] // auto-generated_required
public override void GetObjectData(SerializationInfo info, StreamingContext context) {
if (info==null) {
throw new ArgumentNullException(nameof(info));
using System.Runtime.Versioning;
using Microsoft.Win32;
using System.Diagnostics.Contracts;
-#if !FEATURE_CORECLR
- using Microsoft.Runtime.Hosting;
-#endif
[Serializable]
[System.Runtime.InteropServices.ComVisible(true)]
private byte[] _publicKey;
// Build key pair from file.
- [System.Security.SecuritySafeCritical] // auto-generated
-#pragma warning disable 618
- [SecurityPermissionAttribute(SecurityAction.Demand, Flags=SecurityPermissionFlag.UnmanagedCode)]
-#pragma warning restore 618
public StrongNameKeyPair(FileStream keyPairFile)
{
if (keyPairFile == null)
}
// Build key pair from byte array in memory.
- [System.Security.SecuritySafeCritical] // auto-generated
-#pragma warning disable 618
- [SecurityPermissionAttribute(SecurityAction.Demand, Flags=SecurityPermissionFlag.UnmanagedCode)]
-#pragma warning restore 618
public StrongNameKeyPair(byte[] keyPairArray)
{
if (keyPairArray == null)
_keyPairExported = true;
}
- [System.Security.SecuritySafeCritical] // auto-generated
-#pragma warning disable 618
- [SecurityPermissionAttribute(SecurityAction.Demand, Flags=SecurityPermissionFlag.UnmanagedCode)]
-#pragma warning restore 618
protected StrongNameKeyPair (SerializationInfo info, StreamingContext context) {
_keyPairExported = (bool) info.GetValue("_keyPairExported", typeof(bool));
_keyPairArray = (byte[]) info.GetValue("_keyPairArray", typeof(byte[]));
_publicKey = (byte[]) info.GetValue("_publicKey", typeof(byte[]));
}
-#if! FEATURE_CORECLR
- // Reference key pair in named key container.
- [System.Security.SecuritySafeCritical] // auto-generated
-#pragma warning disable 618
- [SecurityPermissionAttribute(SecurityAction.Demand, Flags=SecurityPermissionFlag.UnmanagedCode)]
-#pragma warning restore 618
- public StrongNameKeyPair(String keyPairContainer)
- {
- if (keyPairContainer == null)
- throw new ArgumentNullException(nameof(keyPairContainer));
- Contract.EndContractBlock();
-
- _keyPairContainer = keyPairContainer;
-
- _keyPairExported = false;
- }
-
- // Get the public portion of the key pair.
- public byte[] PublicKey
- {
- [System.Security.SecuritySafeCritical] // auto-generated
- get
- {
- if (_publicKey == null)
- {
- _publicKey = ComputePublicKey();
- }
-
- byte[] publicKey = new byte[_publicKey.Length];
- Array.Copy(_publicKey, publicKey, _publicKey.Length);
-
- return publicKey;
- }
- }
-
- [System.Security.SecurityCritical] // auto-generated
- private unsafe byte[] ComputePublicKey()
- {
- byte[] publicKey = null;
-
- // Make sure pbPublicKey is not leaked with async exceptions
- RuntimeHelpers.PrepareConstrainedRegions();
- try {
- }
- finally
- {
- IntPtr pbPublicKey = IntPtr.Zero;
- int cbPublicKey = 0;
-
- try
- {
- bool result;
- if (_keyPairExported)
- {
- result = StrongNameHelpers.StrongNameGetPublicKey(null, _keyPairArray, _keyPairArray.Length,
- out pbPublicKey, out cbPublicKey);
- }
- else
- {
- result = StrongNameHelpers.StrongNameGetPublicKey(_keyPairContainer, null, 0,
- out pbPublicKey, out cbPublicKey);
- }
- if (!result)
- throw new ArgumentException(Environment.GetResourceString("Argument_StrongNameGetPublicKey"));
-
- publicKey = new byte[cbPublicKey];
- Buffer.Memcpy(publicKey, 0, (byte*)(pbPublicKey.ToPointer()), 0, cbPublicKey);
- }
- finally
- {
- if (pbPublicKey != IntPtr.Zero)
- StrongNameHelpers.StrongNameFreeBuffer(pbPublicKey);
- }
- }
- return publicKey;
- }
- // Internal routine used to retrieve key pair info from unmanaged code.
- private bool GetKeyPair(out Object arrayOrContainer)
- {
- arrayOrContainer = _keyPairExported ? (Object)_keyPairArray : (Object)_keyPairContainer;
- return _keyPairExported;
- }
-#else
public StrongNameKeyPair(String keyPairContainer)
{
throw new PlatformNotSupportedException();
}
}
-#endif// FEATURE_CORECLR
-
/// <internalonly/>
- [System.Security.SecurityCritical]
void ISerializable.GetObjectData (SerializationInfo info, StreamingContext context) {
info.AddValue("_keyPairExported", _keyPairExported);
info.AddValue("_keyPairArray", _keyPairArray);
/// <internalonly/>
void IDeserializationCallback.OnDeserialization (Object sender) {}
-
}
}
protected Type typeImpl;
- #if FEATURE_CORECLR
- [System.Security.SecuritySafeCritical] // auto-generated
- #endif
protected TypeDelegator() {}
public TypeDelegator(Type delegatingType) {
using System.Runtime.Versioning;
using System.Text;
using System.Threading;
+ using System.Diagnostics;
using System.Diagnostics.Contracts;
internal class FileBasedResourceGroveler : IResourceGroveler
public FileBasedResourceGroveler(ResourceManager.ResourceManagerMediator mediator)
{
- Contract.Assert(mediator != null, "mediator shouldn't be null; check caller");
+ Debug.Assert(mediator != null, "mediator shouldn't be null; check caller");
_mediator = mediator;
}
// Consider modifying IResourceGroveler interface (hence this method signature) when we figure out
// serialization compat story for moving ResourceManager members to either file-based or
// manifest-based classes. Want to continue tightening the design to get rid of unused params.
- [System.Security.SecuritySafeCritical] // auto-generated
public ResourceSet GrovelForResourceSet(CultureInfo culture, Dictionary<String, ResourceSet> localResourceSets, bool tryParents, bool createIfNotExists, ref StackCrawlMark stackMark)
{
- Contract.Assert(culture != null, "culture shouldn't be null; check caller");
+ Debug.Assert(culture != null, "culture shouldn't be null; check caller");
String fileName = null;
ResourceSet rs = null;
}
}
-#if !FEATURE_CORECLR // PAL doesn't support eventing, and we don't compile event providers for coreclr
- public bool HasNeutralResources(CultureInfo culture, String defaultResName)
- {
- // Detect missing neutral locale resources.
- String defaultResPath = FindResourceFile(culture, defaultResName);
- if (defaultResPath == null || !File.Exists(defaultResPath))
- {
- String dir = _mediator.ModuleDir;
- if (defaultResPath != null)
- {
- dir = Path.GetDirectoryName(defaultResPath);
- }
- return false;
- }
- return true;
- }
-#endif
-
// Given a CultureInfo, it generates the path &; file name for
// the .resources file for that CultureInfo. This method will grovel
// the disk looking for the correct file name & path. Uses CultureInfo's
private String FindResourceFile(CultureInfo culture, String fileName)
{
- Contract.Assert(culture != null, "culture shouldn't be null; check caller");
- Contract.Assert(fileName != null, "fileName shouldn't be null; check caller");
+ Debug.Assert(culture != null, "culture shouldn't be null; check caller");
+ Debug.Assert(fileName != null, "fileName shouldn't be null; check caller");
// If we have a moduleDir, check there first. Get module fully
// qualified name, append path to that.
// Constructs a new ResourceSet for a given file name. The logic in
// here avoids a ReflectionPermission check for our RuntimeResourceSet
// for perf and working set reasons.
- [System.Security.SecurityCritical]
private ResourceSet CreateResourceSet(String file)
{
- Contract.Assert(file != null, "file shouldn't be null; check caller");
+ Debug.Assert(file != null, "file shouldn't be null; check caller");
if (_mediator.UserResourceSet == null)
{
{
ResourceSet GrovelForResourceSet(CultureInfo culture, Dictionary<String, ResourceSet> localResourceSets, bool tryParents,
bool createIfNotExists, ref StackCrawlMark stackMark);
-
-#if !FEATURE_CORECLR // PAL doesn't support eventing, and we don't compile event providers for coreclr
-
- bool HasNeutralResources(CultureInfo culture, String defaultResName);
-#endif
}
}
using System.Runtime.Versioning;
using System.Text;
using System.Threading;
+ using System.Diagnostics;
using System.Diagnostics.Contracts;
using Microsoft.Win32;
-#if !FEATURE_CORECLR
- using System.Diagnostics.Tracing;
-#endif
-
//
// Note: this type is integral to the construction of exception objects,
// and sometimes this has to be done in low memory situtations (OOM) or
_mediator = mediator;
}
- [System.Security.SecuritySafeCritical]
[MethodImplAttribute(MethodImplOptions.NoInlining)] // Methods containing StackCrawlMark local var have to be marked non-inlineable
public ResourceSet GrovelForResourceSet(CultureInfo culture, Dictionary<String, ResourceSet> localResourceSets, bool tryParents, bool createIfNotExists, ref StackCrawlMark stackMark)
{
- Contract.Assert(culture != null, "culture shouldn't be null; check caller");
- Contract.Assert(localResourceSets != null, "localResourceSets shouldn't be null; check caller");
+ Debug.Assert(culture != null, "culture shouldn't be null; check caller");
+ Debug.Assert(localResourceSets != null, "localResourceSets shouldn't be null; check caller");
ResourceSet rs = null;
Stream stream = null;
// want to add it twice.
lock (localResourceSets)
{
- if (localResourceSets.TryGetValue(culture.Name, out rs))
- {
-#if !FEATURE_CORECLR
- if (FrameworkEventSource.IsInitialized)
- {
- FrameworkEventSource.Log.ResourceManagerFoundResourceSetInCacheUnexpected(_mediator.BaseName, _mediator.MainAssembly, culture.Name);
- }
-#endif
- }
+ localResourceSets.TryGetValue(culture.Name, out rs);
}
stream = GetManifestResourceStream(satellite, fileName, ref stackMark);
}
-#if !FEATURE_CORECLR
- if (FrameworkEventSource.IsInitialized)
- {
- if (stream != null)
- {
- FrameworkEventSource.Log.ResourceManagerStreamFound(_mediator.BaseName, _mediator.MainAssembly, culture.Name, satellite, fileName);
- }
- else
- {
- FrameworkEventSource.Log.ResourceManagerStreamNotFound(_mediator.BaseName, _mediator.MainAssembly, culture.Name, satellite, fileName);
- }
- }
-#endif
-
// 4a. Found a stream; create a ResourceSet if possible
if (createIfNotExists && stream != null && rs == null)
{
-#if !FEATURE_CORECLR
- if (FrameworkEventSource.IsInitialized)
- {
- FrameworkEventSource.Log.ResourceManagerCreatingResourceSet(_mediator.BaseName, _mediator.MainAssembly, culture.Name, fileName);
- }
-#endif
rs = CreateResourceSet(stream, satellite);
}
else if (stream == null && tryParents)
}
}
-#if !FEATURE_CORECLR
- if (!createIfNotExists && stream != null && rs == null)
- {
- if (FrameworkEventSource.IsInitialized)
- {
- FrameworkEventSource.Log.ResourceManagerNotCreatingResourceSet(_mediator.BaseName, _mediator.MainAssembly, culture.Name);
- }
- }
-#endif
-
return rs;
}
-#if !FEATURE_CORECLR
- // Returns whether or not the main assembly contains a particular resource
- // file in it's assembly manifest. Used to verify that the neutral
- // Culture's .resources file is present in the main assembly
- public bool HasNeutralResources(CultureInfo culture, String defaultResName)
- {
- String resName = defaultResName;
- if (_mediator.LocationInfo != null && _mediator.LocationInfo.Namespace != null)
- resName = _mediator.LocationInfo.Namespace + Type.Delimiter + defaultResName;
- String[] resourceFiles = _mediator.MainAssembly.GetManifestResourceNames();
- foreach(String s in resourceFiles)
- if (s.Equals(resName))
- return true;
- return false;
- }
-#endif
-
private CultureInfo UltimateFallbackFixup(CultureInfo lookForCulture)
{
if (lookForCulture.Name == _mediator.NeutralResourcesCulture.Name &&
_mediator.FallbackLoc == UltimateResourceFallbackLocation.MainAssembly)
{
-#if !FEATURE_CORECLR
- if (FrameworkEventSource.IsInitialized)
- {
- FrameworkEventSource.Log.ResourceManagerNeutralResourcesSufficient(_mediator.BaseName, _mediator.MainAssembly, lookForCulture.Name);
- }
-#endif
-
returnCulture = CultureInfo.InvariantCulture;
}
else if (lookForCulture.HasInvariantCultureName && _mediator.FallbackLoc == UltimateResourceFallbackLocation.Satellite)
}
return returnCulture;
-
}
- [System.Security.SecurityCritical]
internal static CultureInfo GetNeutralResourcesLanguage(Assembly a, ref UltimateResourceFallbackLocation fallbackLocation)
{
- Contract.Assert(a != null, "assembly != null");
+ Debug.Assert(a != null, "assembly != null");
string cultureName = null;
short fallback = 0;
if (GetNeutralResourcesLanguageAttribute(((RuntimeAssembly)a).GetNativeHandle(),
fallbackLocation = (UltimateResourceFallbackLocation)fallback;
}
else {
-#if !FEATURE_CORECLR
- if (FrameworkEventSource.IsInitialized) {
- FrameworkEventSource.Log.ResourceManagerNeutralResourceAttributeMissing(a);
- }
-#endif
fallbackLocation = UltimateResourceFallbackLocation.MainAssembly;
return CultureInfo.InvariantCulture;
}
// fires, please fix the build process for the BCL directory.
if (a == typeof(Object).Assembly)
{
- Contract.Assert(false, System.CoreLib.Name+"'s NeutralResourcesLanguageAttribute is a malformed culture name! name: \"" + cultureName + "\" Exception: " + e);
+ Debug.Assert(false, System.CoreLib.Name+"'s NeutralResourcesLanguageAttribute is a malformed culture name! name: \"" + cultureName + "\" Exception: " + e);
return CultureInfo.InvariantCulture;
}
// Use the assembly to resolve assembly manifest resource references.
// Note that is can be null, but probably shouldn't be.
// This method could use some refactoring. One thing at a time.
- [System.Security.SecurityCritical]
internal ResourceSet CreateResourceSet(Stream store, Assembly assembly)
{
- Contract.Assert(store != null, "I need a Stream!");
+ Debug.Assert(store != null, "I need a Stream!");
// Check to see if this is a Stream the ResourceManager understands,
// and check for the correct resource reader type.
if (store.CanSeek && store.Length > 4)
Type resSetType;
if (_mediator.UserResourceSet == null)
{
- Contract.Assert(resSetTypeName != null, "We should have a ResourceSet type name from the custom resource file here.");
+ Debug.Assert(resSetTypeName != null, "We should have a ResourceSet type name from the custom resource file here.");
resSetType = Type.GetType(resSetTypeName, true, false);
}
else
}
}
- [System.Security.SecurityCritical]
private Stream GetManifestResourceStream(RuntimeAssembly satellite, String fileName, ref StackCrawlMark stackMark)
{
Contract.Requires(satellite != null, "satellite shouldn't be null; check caller");
// case-insensitive lookup rules. Yes, this is slow. The metadata
// dev lead refuses to make all assembly manifest resource lookups case-insensitive,
// even optionally case-insensitive.
- [System.Security.SecurityCritical]
[MethodImplAttribute(MethodImplOptions.NoInlining)] // Methods containing StackCrawlMark local var have to be marked non-inlineable
private Stream CaseInsensitiveManifestResourceStreamLookup(RuntimeAssembly satellite, String name)
{
}
}
-#if !FEATURE_CORECLR
- if (FrameworkEventSource.IsInitialized)
- {
- if (canonicalName != null)
- {
- FrameworkEventSource.Log.ResourceManagerCaseInsensitiveResourceStreamLookupSucceeded(_mediator.BaseName, _mediator.MainAssembly, satellite.GetSimpleName(), givenName);
- }
- else
- {
- FrameworkEventSource.Log.ResourceManagerCaseInsensitiveResourceStreamLookupFailed(_mediator.BaseName, _mediator.MainAssembly, satellite.GetSimpleName(), givenName);
- }
- }
-#endif
-
if (canonicalName == null)
{
return null;
}
+
// If we're looking in the main assembly AND if the main
// assembly was the person who created the ResourceManager,
// skip a security check for private manifest resources.
bool canSkipSecurityCheck = _mediator.MainAssembly == satellite && _mediator.CallingAssembly == _mediator.MainAssembly;
StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller;
- Stream s = satellite.GetManifestResourceStream(canonicalName, ref stackMark, canSkipSecurityCheck);
- // GetManifestResourceStream will return null if we don't have
- // permission to read this stream from the assembly. For example,
- // if the stream is private and we're trying to access it from another
- // assembly (ie, ResMgr in mscorlib accessing anything else), we
- // require Reflection TypeInformation permission to be able to read
- // this.
-#if !FEATURE_CORECLR
- if (s!=null) {
- if (FrameworkEventSource.IsInitialized)
- {
- FrameworkEventSource.Log.ResourceManagerManifestResourceAccessDenied(_mediator.BaseName, _mediator.MainAssembly, satellite.GetSimpleName(), canonicalName);
- }
- }
-#endif
- return s;
+ return satellite.GetManifestResourceStream(canonicalName, ref stackMark, canSkipSecurityCheck);
}
- [System.Security.SecurityCritical]
[MethodImplAttribute(MethodImplOptions.NoInlining)] // Methods containing StackCrawlMark local var have to be marked non-inlineable
private RuntimeAssembly GetSatelliteAssembly(CultureInfo lookForCulture, ref StackCrawlMark stackMark)
{
int hr = fle._HResult;
if (hr != Win32Native.MakeHRFromErrorCode(Win32Native.ERROR_ACCESS_DENIED))
{
- Contract.Assert(false, "[This assert catches satellite assembly build/deployment problems - report this message to your build lab & loc engineer]" + Environment.NewLine + "GetSatelliteAssembly failed for culture " + lookForCulture.Name + " and version " + (_mediator.SatelliteContractVersion == null ? _mediator.MainAssembly.GetVersion().ToString() : _mediator.SatelliteContractVersion.ToString()) + " of assembly " + _mediator.MainAssembly.GetSimpleName() + " with error code 0x" + hr.ToString("X", CultureInfo.InvariantCulture) + Environment.NewLine + "Exception: " + fle);
+ Debug.Assert(false, "[This assert catches satellite assembly build/deployment problems - report this message to your build lab & loc engineer]" + Environment.NewLine + "GetSatelliteAssembly failed for culture " + lookForCulture.Name + " and version " + (_mediator.SatelliteContractVersion == null ? _mediator.MainAssembly.GetVersion().ToString() : _mediator.SatelliteContractVersion.ToString()) + " of assembly " + _mediator.MainAssembly.GetSimpleName() + " with error code 0x" + hr.ToString("X", CultureInfo.InvariantCulture) + Environment.NewLine + "Exception: " + fle);
}
}
// Don't throw for zero-length satellite assemblies, for compat with v1
catch (BadImageFormatException bife)
{
- Contract.Assert(false, "[This assert catches satellite assembly build/deployment problems - report this message to your build lab & loc engineer]" + Environment.NewLine + "GetSatelliteAssembly failed for culture " + lookForCulture.Name + " and version " + (_mediator.SatelliteContractVersion == null ? _mediator.MainAssembly.GetVersion().ToString() : _mediator.SatelliteContractVersion.ToString()) + " of assembly " + _mediator.MainAssembly.GetSimpleName() + Environment.NewLine + "Exception: " + bife);
+ Debug.Assert(false, "[This assert catches satellite assembly build/deployment problems - report this message to your build lab & loc engineer]" + Environment.NewLine + "GetSatelliteAssembly failed for culture " + lookForCulture.Name + " and version " + (_mediator.SatelliteContractVersion == null ? _mediator.MainAssembly.GetVersion().ToString() : _mediator.SatelliteContractVersion.ToString()) + " of assembly " + _mediator.MainAssembly.GetSimpleName() + Environment.NewLine + "Exception: " + bife);
}
-#if !FEATURE_CORECLR
- if (FrameworkEventSource.IsInitialized)
- {
- if (satellite != null)
- {
- FrameworkEventSource.Log.ResourceManagerGetSatelliteAssemblySucceeded(_mediator.BaseName, _mediator.MainAssembly, lookForCulture.Name, satAssemblyName);
- }
- else
- {
- FrameworkEventSource.Log.ResourceManagerGetSatelliteAssemblyFailed(_mediator.BaseName, _mediator.MainAssembly, lookForCulture.Name, satAssemblyName);
- }
- }
-#endif
-
return satellite;
}
// and causes partially trusted localized apps to fail.
private bool CanUseDefaultResourceClasses(String readerTypeName, String resSetTypeName)
{
- Contract.Assert(readerTypeName != null, "readerTypeName shouldn't be null; check caller");
- Contract.Assert(resSetTypeName != null, "resSetTypeName shouldn't be null; check caller");
+ Debug.Assert(readerTypeName != null, "readerTypeName shouldn't be null; check caller");
+ Debug.Assert(resSetTypeName != null, "resSetTypeName shouldn't be null; check caller");
if (_mediator.UserResourceSet != null)
return false;
return true;
}
- [System.Security.SecurityCritical]
private String GetSatelliteAssemblyName()
{
String satAssemblyName = _mediator.MainAssembly.GetSimpleName();
return satAssemblyName;
}
- [System.Security.SecurityCritical]
private void HandleSatelliteMissing()
{
String satAssemName = _mediator.MainAssembly.GetSimpleName() + ".resources.dll";
throw new MissingSatelliteAssemblyException(Environment.GetResourceString("MissingSatelliteAssembly_Culture_Name", _mediator.NeutralResourcesCulture, satAssemName), missingCultureName);
}
- [System.Security.SecurityCritical] // auto-generated
private void HandleResourceStreamMissing(String fileName)
{
// Keep people from bothering me about resources problems
if (_mediator.MainAssembly == typeof(Object).Assembly && _mediator.BaseName.Equals(System.CoreLib.Name))
{
// This would break CultureInfo & all our exceptions.
- Contract.Assert(false, "Couldn't get " + System.CoreLib.Name+ResourceManager.ResFileExtension + " from "+System.CoreLib.Name+"'s assembly" + Environment.NewLine + Environment.NewLine + "Are you building the runtime on your machine? Chances are the BCL directory didn't build correctly. Type 'build -c' in the BCL directory. If you get build errors, look at buildd.log. If you then can't figure out what's wrong (and you aren't changing the assembly-related metadata code), ask a BCL dev.\n\nIf you did NOT build the runtime, you shouldn't be seeing this and you've found a bug.");
+ Debug.Assert(false, "Couldn't get " + System.CoreLib.Name+ResourceManager.ResFileExtension + " from "+System.CoreLib.Name+"'s assembly" + Environment.NewLine + Environment.NewLine + "Are you building the runtime on your machine? Chances are the BCL directory didn't build correctly. Type 'build -c' in the BCL directory. If you get build errors, look at buildd.log. If you then can't figure out what's wrong (and you aren't changing the assembly-related metadata code), ask a BCL dev.\n\nIf you did NOT build the runtime, you shouldn't be seeing this and you've found a bug.");
// We cannot continue further - simply FailFast.
string mesgFailFast = System.CoreLib.Name + ResourceManager.ResFileExtension + " couldn't be found! Large parts of the BCL won't work!";
}
[DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
- [System.Security.SecurityCritical] // Our security team doesn't yet allow safe-critical P/Invoke methods.
[System.Security.SuppressUnmanagedCodeSecurity]
[return: MarshalAs(UnmanagedType.Bool)]
internal static extern bool GetNeutralResourcesLanguageAttribute(RuntimeAssembly assemblyHandle, StringHandleOnStack cultureName, out short fallbackLocation);
using System;
using System.Collections;
using System.Collections.Generic;
-#if FEATURE_CORECLR
-using System.Diagnostics.Contracts;
-#endif
using System.Globalization;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
private CultureInfo m_neutralResourcesCulture;
private bool m_useParents;
-// Added but disabled from desktop in .NET 4.0, stayed disabled in .NET 4.5
-#if FEATURE_CORECLR
// This is a cache of the thread, process, user, and OS-preferred fallback cultures.
// However, each thread may have a different value, and these may change during the
// lifetime of the process. So this cache must be verified each time we use it.
// as well to avoid differences across threads.
[ThreadStatic]
private static CultureInfo[] cachedOsFallbackArray;
-#endif // FEATURE_CORECLR
internal ResourceFallbackManager(CultureInfo startingCulture, CultureInfo neutralResourcesCulture, bool useParents)
{
yield break;
}
-// Added but disabled from desktop in .NET 4.0, stayed disabled in .NET 4.5
-#if FEATURE_CORECLR
// 2. user preferred cultures, omitting starting culture if tried already
// Compat note: For console apps, this API will return cultures like Arabic
// or Hebrew that are displayed right-to-left. These don't work with today's
}
}
}
-#endif // FEATURE_CORECLR
// 3. invariant
// Don't return invariant twice though.
yield return CultureInfo.InvariantCulture;
}
-// Added but disabled from desktop in .NET 4.0, stayed disabled in .NET 4.5
-#if FEATURE_CORECLR
private static CultureInfo[] LoadPreferredCultures()
{
// The list of preferred cultures includes thread, process, user, and OS
// Note: May return null.
- [System.Security.SecuritySafeCritical] // auto-generated
private static String[] GetResourceFallbackArray()
{
// AppCompat note: We've added this feature for desktop V4 but we ripped it out
return CultureInfo.nativeGetResourceFallbackArray();
#endif
}
-
-#endif // FEATURE_CORECLR
}
}
using Microsoft.Win32;
using System.Collections.Generic;
using System.Runtime.Versioning;
+ using System.Diagnostics;
using System.Diagnostics.Contracts;
-#if !FEATURE_CORECLR
- using System.Diagnostics.Tracing;
-#endif
#if FEATURE_APPX
//
// Also using interface or abstract class will not play nice with FriendAccessAllowed.
//
[FriendAccessAllowed]
- [SecurityCritical]
internal class WindowsRuntimeResourceManagerBase
{
- [SecurityCritical]
public virtual bool Initialize(string libpath, string reswFilename, out PRIExceptionInfo exceptionInfo){exceptionInfo = null; return false;}
- [SecurityCritical]
public virtual String GetString(String stringName, String startingCulture, String neutralResourcesCulture){return null;}
public virtual CultureInfo GlobalResourceContextBestFitCultureInfo {
- [SecurityCritical]
get { return null; }
}
- [SecurityCritical]
public virtual bool SetGlobalResourceContextDefaultCulture(CultureInfo ci) { return false; }
}
protected ResourceManager()
{
-#if !FEATURE_CORECLR
- // This constructor is not designed to be used under AppX and is not in the Win8 profile.
- // However designers may use them even if they are running under AppX since they are
- // not subject to the restrictions of the Win8 profile.
- Contract.Assert(!AppDomain.IsAppXModel() || AppDomain.IsAppXDesignMode());
-#endif
-
Init();
_lastUsedResourceCache = new CultureNameResourceSetPair();
throw new ArgumentNullException(nameof(resourceDir));
Contract.EndContractBlock();
-#if !FEATURE_CORECLR
- // This constructor is not designed to be used under AppX and is not in the Win8 profile.
- // However designers may use them even if they are running under AppX since they are
- // not subject to the restrictions of the Win8 profile.
- Contract.Assert(!AppDomain.IsAppXModel() || AppDomain.IsAppXDesignMode());
-#endif
-
BaseNameField = baseName;
moduleDir = resourceDir;
ResourceManagerMediator mediator = new ResourceManagerMediator(this);
resourceGroveler = new FileBasedResourceGroveler(mediator);
-
-#if !FEATURE_CORECLR // PAL doesn't support eventing, and we don't compile event providers for coreclr
- if (FrameworkEventSource.IsInitialized && FrameworkEventSource.Log.IsEnabled()) {
- CultureInfo culture = CultureInfo.InvariantCulture;
- String defaultResName = GetResourceFileName(culture);
-
- if (resourceGroveler.HasNeutralResources(culture, defaultResName)) {
- FrameworkEventSource.Log.ResourceManagerNeutralResourcesFound(BaseNameField, MainAssembly, defaultResName);
- }
- else {
- FrameworkEventSource.Log.ResourceManagerNeutralResourcesNotFound(BaseNameField, MainAssembly, defaultResName);
- }
- }
-#endif
}
-
+
[MethodImplAttribute(MethodImplOptions.NoInlining)] // Methods containing StackCrawlMark local var have to be marked non-inlineable
public ResourceManager(String baseName, Assembly assembly)
{
throw new ArgumentNullException(nameof(assembly));
Contract.EndContractBlock();
-#if !FEATURE_CORECLR
- // This constructor is not designed to be used under AppX and is not in the Win8 profile.
- // However designers may use them even if they are running under AppX since they are
- // not subject to the restrictions of the Win8 profile.
- Contract.Assert(!AppDomain.IsAppXModel() || AppDomain.IsAppXDesignMode());
-#endif
-
if (!(assembly is RuntimeAssembly))
throw new ArgumentException(Environment.GetResourceString("Argument_MustBeRuntimeAssembly"));
this._lastUsedResourceCache = null;
}
- [System.Security.SecuritySafeCritical]
[OnDeserialized]
private void OnDeserialized(StreamingContext ctx)
{
// Trying to unify code as much as possible, even though having to do a
// security check in each constructor prevents it.
- [System.Security.SecuritySafeCritical]
private void CommonAssemblyInit()
{
if (_bUsingModernResourceManagement == false)
}
_neutralResourcesCulture = ManifestBasedResourceGroveler.GetNeutralResourcesLanguage(MainAssembly, ref _fallbackLoc);
-
-#if !FEATURE_CORECLR // PAL doesn't support eventing, and we don't compile event providers for coreclr
- if (_bUsingModernResourceManagement == false)
- {
- if (FrameworkEventSource.IsInitialized && FrameworkEventSource.Log.IsEnabled()) {
- CultureInfo culture = CultureInfo.InvariantCulture;
- String defaultResName = GetResourceFileName(culture);
-
- if (resourceGroveler.HasNeutralResources(culture, defaultResName)) {
- FrameworkEventSource.Log.ResourceManagerNeutralResourcesFound(BaseNameField, MainAssembly, defaultResName);
- }
- else {
- String outputResName = defaultResName;
- if (_locationInfo != null && _locationInfo.Namespace != null)
- outputResName = _locationInfo.Namespace + Type.Delimiter + defaultResName;
- FrameworkEventSource.Log.ResourceManagerNeutralResourcesNotFound(BaseNameField, MainAssembly, outputResName);
- }
- }
-
-#pragma warning disable 618
- ResourceSets = new Hashtable(); // for backward compatibility
-#pragma warning restore 618
- }
-#endif
}
// Gets the base name for the ResourceManager.
// creating a new ResourceManager isn't quite the correct behavior.
public virtual void ReleaseAllResources()
{
-#if !FEATURE_CORECLR
- if (FrameworkEventSource.IsInitialized)
- {
- FrameworkEventSource.Log.ResourceManagerReleasingResources(BaseNameField, MainAssembly);
- }
-#endif
Dictionary<String, ResourceSet> localResourceSets = _resourceSets;
// If any calls to Close throw, at least leave ourselves in a
lock(localResourceSets) {
IDictionaryEnumerator setEnum = localResourceSets.GetEnumerator();
-#if !FEATURE_CORECLR
- IDictionaryEnumerator setEnum2 = null;
-#pragma warning disable 618
- if (ResourceSets != null) {
- setEnum2 = ResourceSets.GetEnumerator();
- }
- ResourceSets = new Hashtable(); // for backwards compat
-#pragma warning restore 618
-#endif
-
while (setEnum.MoveNext()) {
((ResourceSet)setEnum.Value).Close();
}
-
-#if !FEATURE_CORECLR
- if (setEnum2 != null) {
- while (setEnum2.MoveNext()) {
- ((ResourceSet)setEnum2.Value).Close();
- }
- }
-#endif
}
}
// if it hasn't yet been loaded and if parent CultureInfos should be
// loaded as well for resource inheritance.
//
- [System.Security.SecuritySafeCritical] // auto-generated
[MethodImplAttribute(MethodImplOptions.NoInlining)] // Methods containing StackCrawlMark local var have to be marked non-inlineable
public virtual ResourceSet GetResourceSet(CultureInfo culture, bool createIfNotExists, bool tryParents) {
if (null==culture)
// for getting a resource set lives. Access to it is controlled by
// threadsafe methods such as GetResourceSet, GetString, & GetObject.
// This will take a minimal number of locks.
- [System.Security.SecuritySafeCritical] // auto-generated
[MethodImplAttribute(MethodImplOptions.NoInlining)] // Methods containing StackCrawlMark local var has to be marked non-inlineable
protected virtual ResourceSet InternalGetResourceSet(CultureInfo culture, bool createIfNotExists, bool tryParents)
{
- Contract.Assert(culture != null, "culture != null");
+ Debug.Assert(culture != null, "culture != null");
StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller;
return InternalGetResourceSet(culture,createIfNotExists,tryParents, ref stackMark);
// for getting a resource set lives. Access to it is controlled by
// threadsafe methods such as GetResourceSet, GetString, & GetObject.
// This will take a minimal number of locks.
- [System.Security.SecurityCritical]
private ResourceSet InternalGetResourceSet(CultureInfo requestedCulture, bool createIfNotExists, bool tryParents, ref StackCrawlMark stackMark)
{
Dictionary<String, ResourceSet> localResourceSets = _resourceSets;
CultureInfo foundCulture = null;
lock (localResourceSets) {
if (localResourceSets.TryGetValue(requestedCulture.Name, out rs)) {
-#if !FEATURE_CORECLR
- if (FrameworkEventSource.IsInitialized) {
- FrameworkEventSource.Log.ResourceManagerFoundResourceSetInCache(BaseNameField, MainAssembly, requestedCulture.Name);
- }
-#endif
return rs;
}
}
foreach (CultureInfo currentCultureInfo in mgr)
{
-#if !FEATURE_CORECLR
- if (FrameworkEventSource.IsInitialized)
- {
- FrameworkEventSource.Log.ResourceManagerLookingForResourceSet(BaseNameField, MainAssembly, currentCultureInfo.Name);
- }
-#endif
lock(localResourceSets) {
if (localResourceSets.TryGetValue(currentCultureInfo.Name, out rs)) {
-#if !FEATURE_CORECLR
- if (FrameworkEventSource.IsInitialized)
- {
- FrameworkEventSource.Log.ResourceManagerFoundResourceSetInCache(BaseNameField, MainAssembly, currentCultureInfo.Name);
- }
-#endif
// we need to update the cache if we fellback
if(requestedCulture != currentCultureInfo) foundCulture = currentCultureInfo;
break;
Object[] attrs = a.GetCustomAttributes(typeof(SatelliteContractVersionAttribute), false);
if (attrs.Length == 0)
return null;
- Contract.Assert(attrs.Length == 1, "Cannot have multiple instances of SatelliteContractVersionAttribute on an assembly!");
+ Debug.Assert(attrs.Length == 1, "Cannot have multiple instances of SatelliteContractVersionAttribute on an assembly!");
v = ((SatelliteContractVersionAttribute)attrs[0]).Version;
}
Version ver;
// If this assert fires, please fix the build process for the
// BCL directory.
if (a == typeof(Object).Assembly) {
- Contract.Assert(false, System.CoreLib.Name+"'s SatelliteContractVersionAttribute is a malformed version string!");
+ Debug.Assert(false, System.CoreLib.Name+"'s SatelliteContractVersionAttribute is a malformed version string!");
return null;
}
#endif
}
- [System.Security.SecuritySafeCritical] // auto-generated
protected static CultureInfo GetNeutralResourcesLanguage(Assembly a)
{
// This method should be obsolete - replace it with the one below.
String typeName2,
AssemblyName asmName2)
{
- Contract.Assert(asmTypeName1 != null, "asmTypeName1 was unexpectedly null");
+ Debug.Assert(asmTypeName1 != null, "asmTypeName1 was unexpectedly null");
// First, compare type names
int comma = asmTypeName1.IndexOf(',');
}
#if FEATURE_APPX
- [SecuritySafeCritical]
- // Throws WinRT hresults
private string GetStringFromPRI(String stringName, String startingCulture, String neutralResourcesCulture) {
- Contract.Assert(_bUsingModernResourceManagement);
- Contract.Assert(_WinRTResourceManager != null);
- Contract.Assert(_PRIonAppXInitialized);
- Contract.Assert(AppDomain.IsAppXModel());
+ Debug.Assert(_bUsingModernResourceManagement);
+ Debug.Assert(_WinRTResourceManager != null);
+ Debug.Assert(_PRIonAppXInitialized);
+ Debug.Assert(AppDomain.IsAppXModel());
if (stringName.Length == 0)
return null;
// Since we can't directly reference System.Runtime.WindowsRuntime from mscorlib, we have to get the type via reflection.
// It would be better if we could just implement WindowsRuntimeResourceManager in mscorlib, but we can't, because
// we can do very little with WinRT in mscorlib.
- [SecurityCritical]
internal static WindowsRuntimeResourceManagerBase GetWinRTResourceManager()
{
Type WinRTResourceManagerType = Type.GetType("System.Resources.WindowsRuntimeResourceManager, " + AssemblyRef.SystemRuntimeWindowsRuntime, true);
#if FEATURE_APPX
[NonSerialized]
- [SecurityCritical]
private WindowsRuntimeResourceManagerBase _WinRTResourceManager; // Written only by SetAppXConfiguration
[NonSerialized]
//
// b) For any other non-FX assembly, we will use the modern resource manager with the premise that app package
// contains the PRI resources.
- [SecuritySafeCritical]
private bool ShouldUseSatelliteAssemblyResourceLookupUnderAppX(RuntimeAssembly resourcesAssembly)
{
bool fUseSatelliteAssemblyResourceLookupUnderAppX = resourcesAssembly.IsFrameworkAssembly();
-
-#if FEATURE_CORECLR
+
if (!fUseSatelliteAssemblyResourceLookupUnderAppX)
{
// Check to see if the assembly is under PLATFORM_RESOURCE_ROOTS. If it is, then we should use satellite assembly lookup for it.
}
}
}
-#endif // FEATURE_CORECLR
+
return fUseSatelliteAssemblyResourceLookupUnderAppX;
-
}
-
- [SecuritySafeCritical]
+
#endif // FEATURE_APPX
// Only call SetAppXConfiguration from ResourceManager constructors, and nowhere else.
// Throws MissingManifestResourceException and WinRT HResults
private void SetAppXConfiguration()
{
- Contract.Assert(_bUsingModernResourceManagement == false); // Only this function writes to this member
+ Debug.Assert(_bUsingModernResourceManagement == false); // Only this function writes to this member
#if FEATURE_APPX
- Contract.Assert(_WinRTResourceManager == null); // Only this function writes to this member
- Contract.Assert(_PRIonAppXInitialized == false); // Only this function writes to this member
- Contract.Assert(_PRIExceptionInfo == null); // Only this function writes to this member
+ Debug.Assert(_WinRTResourceManager == null); // Only this function writes to this member
+ Debug.Assert(_PRIonAppXInitialized == false); // Only this function writes to this member
+ Debug.Assert(_PRIExceptionInfo == null); // Only this function writes to this member
bool bUsingSatelliteAssembliesUnderAppX = false;
// This line behaves the same way as CultureInfo.CurrentUICulture would have in .NET 4
culture = Thread.CurrentThread.GetCurrentUICultureNoAppX();
}
-
-#if !FEATURE_CORECLR
- if (FrameworkEventSource.IsInitialized)
- {
- FrameworkEventSource.Log.ResourceManagerLookupStarted(BaseNameField, MainAssembly, culture.Name);
- }
-#endif
+
ResourceSet last = GetFirstResourceSet(culture);
if (last != null)
last = rs;
}
}
-
-#if !FEATURE_CORECLR
- if (FrameworkEventSource.IsInitialized)
- {
- FrameworkEventSource.Log.ResourceManagerLookupFailed(BaseNameField, MainAssembly, culture.Name);
- }
-#endif
}
return null;
culture = Thread.CurrentThread.GetCurrentUICultureNoAppX();
}
-#if !FEATURE_CORECLR
- if (FrameworkEventSource.IsInitialized)
- {
- FrameworkEventSource.Log.ResourceManagerLookupStarted(BaseNameField, MainAssembly, culture.Name);
- }
-#endif
ResourceSet last = GetFirstResourceSet(culture);
if (last != null)
{
#if RESOURCE_SATELLITE_CONFIG
// Internal helper method - gives an end user the ability to prevent
// satellite assembly probes for certain cultures via a config file.
- [System.Security.SecurityCritical] // auto-generated
private bool TryLookingForSatellite(CultureInfo lookForCulture)
{
if (!_checkedConfigFile) {
// Note: There is one config file per appdomain. This is not
// per-process nor per-assembly.
- [System.Security.SecurityCritical] // auto-generated
private Hashtable GetSatelliteAssembliesFromConfig()
{
return null;
#if RESOURCE_SATELLITE_CONFIG
- [System.Security.SecurityCritical] // auto-generated
internal bool TryLookingForSatellite(CultureInfo lookForCulture)
{
return _rm.TryLookingForSatellite(lookForCulture);
using System.Globalization;
using System.Configuration.Assemblies;
using System.Runtime.Versioning;
+ using System.Diagnostics;
using System.Diagnostics.Contracts;
// Provides the default implementation of IResourceReader, reading
internal static bool CanCache(ResourceTypeCode value)
{
- Contract.Assert(value >= 0, "negative ResourceTypeCode. What?");
+ Debug.Assert(value >= 0, "negative ResourceTypeCode. What?");
return value <= ResourceTypeCode.LastPrimitive;
}
}
// of the assembly. The pointers here are pointers into that block of
// memory controlled by the OS's loader.
private int[] _nameHashes; // hash values for all names.
- [SecurityCritical]
private unsafe int* _nameHashesPtr; // In case we're using UnmanagedMemoryStream
private int[] _namePositions; // relative locations of names
- [SecurityCritical]
private unsafe int* _namePositionsPtr; // If we're using UnmanagedMemoryStream
private RuntimeType[] _typeTable; // Lazy array of Types for resource values.
private int[] _typeNamePositions; // To delay initialize type table
};
#endif // FEATURE_SERIALIZATION
- #if FEATURE_CORECLR
- [System.Security.SecurityCritical] // auto-generated
- #else
- [System.Security.SecuritySafeCritical]
- #endif
public ResourceReader(String fileName)
{
_resCache = new Dictionary<String, ResourceLocator>(FastResourceComparer.Default);
}
}
- [System.Security.SecurityCritical] // auto-generated_required
public ResourceReader(Stream stream)
{
if (stream==null)
// passing in the stream to read from and the RuntimeResourceSet's
// internal hash table (hash table of names with file offsets
// and values, coupled to this ResourceReader).
- [System.Security.SecurityCritical] // auto-generated
internal ResourceReader(Stream stream, Dictionary<String, ResourceLocator> resCache)
{
Contract.Requires(stream != null, "Need a stream!");
Close();
}
- [System.Security.SecuritySafeCritical] // auto-generated
private unsafe void Dispose(bool disposing)
{
if (_store != null) {
}
}
- [System.Security.SecurityCritical] // auto-generated
internal static unsafe int ReadUnalignedI4(int* p)
{
byte* buffer = (byte*)p;
_store.BaseStream.Seek(stringLength, SeekOrigin.Current);
}
- [System.Security.SecuritySafeCritical] // auto-generated
private unsafe int GetNameHash(int index)
{
- Contract.Assert(index >=0 && index < _numResources, "Bad index into hash array. index: "+index);
- Contract.Assert((_ums == null && _nameHashes != null && _nameHashesPtr == null) ||
+ Debug.Assert(index >=0 && index < _numResources, "Bad index into hash array. index: "+index);
+ Debug.Assert((_ums == null && _nameHashes != null && _nameHashesPtr == null) ||
(_ums != null && _nameHashes == null && _nameHashesPtr != null), "Internal state mangled.");
if (_ums == null)
return _nameHashes[index];
return ReadUnalignedI4(&_nameHashesPtr[index]);
}
- [System.Security.SecuritySafeCritical] // auto-generated
private unsafe int GetNamePosition(int index)
{
- Contract.Assert(index >=0 && index < _numResources, "Bad index into name position array. index: "+index);
- Contract.Assert((_ums == null && _namePositions != null && _namePositionsPtr == null) ||
+ Debug.Assert(index >=0 && index < _numResources, "Bad index into name position array. index: "+index);
+ Debug.Assert((_ums == null && _namePositions != null && _namePositionsPtr == null) ||
(_ums != null && _namePositions == null && _namePositionsPtr != null), "Internal state mangled.");
int r;
if (_ums == null)
// This does a binary search through the names.
internal int FindPosForResource(String name)
{
- Contract.Assert(_store != null, "ResourceReader is closed!");
+ Debug.Assert(_store != null, "ResourceReader is closed!");
int hash = FastResourceComparer.HashFunction(name);
BCLDebug.Log("RESMGRFILEFORMAT", "FindPosForResource for "+name+" hash: "+hash.ToString("x", CultureInfo.InvariantCulture));
// Binary search over the hashes. Use the _namePositions array to
// with the string you pass in.
// Whoever calls this method should make sure that they take a lock
// so no one else can cause us to seek in the stream.
- [System.Security.SecuritySafeCritical] // auto-generated
private unsafe bool CompareStringEqualsName(String name)
{
- Contract.Assert(_store != null, "ResourceReader is closed!");
+ Debug.Assert(_store != null, "ResourceReader is closed!");
int byteLen = _store.Read7BitEncodedInt();
if (byteLen < 0) {
throw new BadImageFormatException(Environment.GetResourceString("BadImageFormat_NegativeStringLength"));
// This is used in the enumerator. The enumerator iterates from 0 to n
// of our resources and this returns the resource name for a particular
// index. The parameter is NOT a virtual offset.
- [System.Security.SecurityCritical] // auto-generated
private unsafe String AllocateStringForNameIndex(int index, out int dataOffset)
{
- Contract.Assert(_store != null, "ResourceReader is closed!");
+ Debug.Assert(_store != null, "ResourceReader is closed!");
byte[] bytes;
int byteLen;
long nameVA = GetNamePosition(index);
// index. The parameter is NOT a virtual offset.
private Object GetValueForNameIndex(int index)
{
- Contract.Assert(_store != null, "ResourceReader is closed!");
+ Debug.Assert(_store != null, "ResourceReader is closed!");
long nameVA = GetNamePosition(index);
lock(this) {
_store.BaseStream.Seek(nameVA + _nameSectionOffset, SeekOrigin.Begin);
// no one can cause us to do a seek in here.
internal String LoadString(int pos)
{
- Contract.Assert(_store != null, "ResourceReader is closed!");
+ Debug.Assert(_store != null, "ResourceReader is closed!");
_store.BaseStream.Seek(_dataSectionOffset+pos, SeekOrigin.Begin);
String s = null;
int typeIndex = _store.Read7BitEncodedInt();
// no one can cause us to do a seek in here.
internal Object LoadObjectV1(int pos)
{
- Contract.Assert(_store != null, "ResourceReader is closed!");
- Contract.Assert(_version == 1, ".resources file was not a V1 .resources file!");
+ Debug.Assert(_store != null, "ResourceReader is closed!");
+ Debug.Assert(_version == 1, ".resources file was not a V1 .resources file!");
try {
// mega try-catch performs exceptionally bad on x64; factored out body into
}
#if FEATURE_SERIALIZATION
- [SecuritySafeCritical]
#endif
private Object _LoadObjectV1(int pos) {
_store.BaseStream.Seek(_dataSectionOffset+pos, SeekOrigin.Begin);
internal Object LoadObjectV2(int pos, out ResourceTypeCode typeCode)
{
- Contract.Assert(_store != null, "ResourceReader is closed!");
- Contract.Assert(_version >= 2, ".resources file was not a V2 (or higher) .resources file!");
+ Debug.Assert(_store != null, "ResourceReader is closed!");
+ Debug.Assert(_version >= 2, ".resources file was not a V2 (or higher) .resources file!");
try {
// mega try-catch performs exceptionally bad on x64; factored out body into
}
}
- [System.Security.SecuritySafeCritical] // auto-generated
private Object _LoadObjectV2(int pos, out ResourceTypeCode typeCode) {
_store.BaseStream.Seek(_dataSectionOffset+pos, SeekOrigin.Begin);
typeCode = (ResourceTypeCode) _store.Read7BitEncodedInt();
byte[] bytes = new byte[len];
int r = _ums.Read(bytes, 0, len);
- Contract.Assert(r == len, "ResourceReader needs to use a blocking read here. (Call _store.ReadBytes(len)?)");
+ Debug.Assert(r == len, "ResourceReader needs to use a blocking read here. (Call _store.ReadBytes(len)?)");
return bytes;
}
// deserialization binder to simulate a type-limiting deserializer.
// This method handles types that are safe to deserialize, as well as
// ensuring we only get back what we expect.
- [System.Security.SecurityCritical] // auto-generated
private Object DeserializeObject(int typeIndex)
{
RuntimeType type = FindType(typeIndex);
// Reads in the header information for a .resources file. Verifies some
// of the assumptions about this resource set, and builds the class table
// for the default resource file format.
- [System.Security.SecurityCritical] // auto-generated
private void ReadResources()
{
- Contract.Assert(_store != null, "ResourceReader is closed!");
+ Debug.Assert(_store != null, "ResourceReader is closed!");
#if FEATURE_SERIALIZATION
BinaryFormatter bf = new BinaryFormatter(null, new StreamingContext(StreamingContextStates.File | StreamingContextStates.Persistence));
_typeLimitingBinder = new TypeLimitingDeserializationBinder();
}
}
- [System.Security.SecurityCritical] // auto-generated
private void _ReadResources()
{
// Read ResourceManager header
_store.BaseStream.Position = oldPos;
}
}
- Contract.Assert(_typeTable[typeIndex] != null, "Should have found a type!");
+ Debug.Assert(_typeTable[typeIndex] != null, "Should have found a type!");
return _typeTable[typeIndex];
}
#if FEATURE_SERIALIZATION
- [System.Security.SecurityCritical] // auto-generated
private void InitSafeToDeserializeArray()
{
_safeToDeserialize = new bool[_typeTable.Length];
Array.Sort(sortedDataPositions);
int index = Array.BinarySearch(sortedDataPositions, dataPos);
- Contract.Assert(index >= 0 && index < _numResources, "Couldn't find data position within sorted data positions array!");
+ Debug.Assert(index >= 0 && index < _numResources, "Couldn't find data position within sorted data positions array!");
long nextData = (index < _numResources - 1) ? sortedDataPositions[index + 1] + _dataSectionOffset : _store.BaseStream.Length;
int len = (int) (nextData - (dataPos + _dataSectionOffset));
- Contract.Assert(len >= 0 && len <= (int) _store.BaseStream.Length - dataPos + _dataSectionOffset, "Length was negative or outside the bounds of the file!");
+ Debug.Assert(len >= 0 && len <= (int) _store.BaseStream.Length - dataPos + _dataSectionOffset, "Length was negative or outside the bounds of the file!");
// Read type code then byte[]
_store.BaseStream.Position = _dataSectionOffset + dataPos;
{
Contract.Requires(typeCode >= 0, "can't be negative");
if (typeCode < ResourceTypeCode.StartOfUserTypes) {
- Contract.Assert(!String.Equals(typeCode.ToString(), "LastPrimitive"), "Change ResourceTypeCode metadata order so LastPrimitive isn't what Enum.ToString prefers.");
+ Debug.Assert(!String.Equals(typeCode.ToString(), "LastPrimitive"), "Change ResourceTypeCode metadata order so LastPrimitive isn't what Enum.ToString prefers.");
return "ResourceTypeCode." + typeCode.ToString();
}
else {
int typeIndex = typeCode - ResourceTypeCode.StartOfUserTypes;
- Contract.Assert(typeIndex >= 0 && typeIndex < _typeTable.Length, "TypeCode is broken or corrupted!");
+ Debug.Assert(typeIndex >= 0 && typeIndex < _typeTable.Length, "TypeCode is broken or corrupted!");
long oldPos = _store.BaseStream.Position;
try {
_store.BaseStream.Position = _typeNamePositions[typeIndex];
_typeToDeserialize = type;
}
- [System.Security.SecuritySafeCritical] // overrides transparent public member
public override Type BindToType(string assemblyName, string typeName)
{
// BinaryObjectReader::Bind tries us first, then its own code.
}
public Object Key {
- [System.Security.SecuritySafeCritical] // auto-generated
get {
if (_currentName == ENUM_DONE) throw new InvalidOperationException(Environment.GetResourceString(ResId.InvalidOperation_EnumEnded));
if (!_currentIsValid) throw new InvalidOperationException(Environment.GetResourceString(ResId.InvalidOperation_EnumNotStarted));
}
public DictionaryEntry Entry {
- [System.Security.SecuritySafeCritical] // auto-generated
get {
if (_currentName == ENUM_DONE) throw new InvalidOperationException(Environment.GetResourceString(ResId.InvalidOperation_EnumEnded));
if (!_currentIsValid) throw new InvalidOperationException(Environment.GetResourceString(ResId.InvalidOperation_EnumNotStarted));
// stores them in a hash table. Custom IResourceReaders can be used.
//
[Serializable]
-[System.Runtime.InteropServices.ComVisible(true)]
+ [System.Runtime.InteropServices.ComVisible(true)]
public class ResourceSet : IDisposable, IEnumerable
{
[NonSerialized] protected IResourceReader Reader;
-#if FEATURE_CORECLR
internal Hashtable Table;
-#else
- protected Hashtable Table;
-#endif
private Hashtable _caseInsensitiveTable; // For case-insensitive lookups.
// implementation. Use this constructor to open & read from a file
// on disk.
//
- #if FEATURE_CORECLR
- [System.Security.SecurityCritical] // auto-generated
- #endif
public ResourceSet(String fileName)
{
Reader = new ResourceReader(fileName);
// implementation. Use this constructor to read from an open stream
// of data.
//
- [System.Security.SecurityCritical] // auto-generated_required
public ResourceSet(Stream stream)
{
Reader = new ResourceReader(stream);
}
#if LOOSELY_LINKED_RESOURCE_REFERENCE
- [System.Security.SecurityCritical] // auto_generated_required
public ResourceSet(Stream stream, Assembly assembly)
{
Reader = new ResourceReader(stream);
// GetDefaultReader and GetDefaultWriter.
public virtual Type GetDefaultWriter()
{
-#if FEATURE_CORECLR
return Type.GetType("System.Resources.ResourceWriter, System.Resources.Writer, Version=4.0.1.0, Culture=neutral, PublicKeyToken=" + AssemblyRef.MicrosoftPublicKeyToken, throwOnError: true);
-#else
- return typeof(ResourceWriter);
-#endif
}
[ComVisible(false)]
using System.Globalization;
using System.Reflection;
using System.Runtime.Versioning;
+ using System.Diagnostics;
using System.Diagnostics.Contracts;
// A RuntimeResourceSet stores all the resources defined in one
// the resources once, adding them into the table.
private bool _haveReadFromReader;
- [System.Security.SecurityCritical] // auto-generated
internal RuntimeResourceSet(String fileName) : base(false)
{
BCLDebug.Log("RESMGRFILEFORMAT", "RuntimeResourceSet .ctor(String)");
Assembly = assembly;
}
#else
- [System.Security.SecurityCritical] // auto-generated
internal RuntimeResourceSet(Stream stream) : base(false)
{
BCLDebug.Log("RESMGRFILEFORMAT", "RuntimeResourceSet .ctor(Stream)");
}
if (dataPos != -1 && value == null) {
- Contract.Assert(dataPos >= 0, "data section offset cannot be negative!");
+ Debug.Assert(dataPos >= 0, "data section offset cannot be negative!");
// Normally calling LoadString or LoadObject requires
// taking a lock. Note that in this case, we took a
// lock on the entire RuntimeResourceSet, which is
Reader.Close();
}
else {
- Contract.Assert(ignoreCase, "This should only happen for case-insensitive lookups");
+ Debug.Assert(ignoreCase, "This should only happen for case-insensitive lookups");
ResourceReader.ResourceEnumerator en = _defaultReader.GetEnumeratorInternal();
while (en.MoveNext()) {
// Note: Always ask for the resource key before the data position.
using System;
using System.Collections;
using System.Collections.Generic;
+ using System.Diagnostics;
using System.Diagnostics.Contracts;
internal sealed class FastResourceComparer : IComparer, IEqualityComparer, IComparer<String>, IEqualityComparer<String>
// Input is one string to compare with, and a byte[] containing chars in
// little endian unicode. Pass in the number of valid chars.
- [System.Security.SecurityCritical] // auto-generated
public unsafe static int CompareOrdinal(String a, byte[] bytes, int bCharLength)
{
- Contract.Assert(a != null && bytes != null, "FastResourceComparer::CompareOrdinal must have non-null params");
- Contract.Assert(bCharLength * 2 <= bytes.Length, "FastResourceComparer::CompareOrdinal - numChars is too big!");
+ Debug.Assert(a != null && bytes != null, "FastResourceComparer::CompareOrdinal must have non-null params");
+ Debug.Assert(bCharLength * 2 <= bytes.Length, "FastResourceComparer::CompareOrdinal - numChars is too big!");
// This is a managed version of strcmp, but I can't take advantage
// of a terminating 0, unlike strcmp in C.
int i = 0;
return a.Length - bCharLength;
}
- [System.Security.SecurityCritical] // auto-generated
public static int CompareOrdinal(byte[] bytes, int aCharLength, String b)
{
return -CompareOrdinal(b, bytes, aCharLength);
// This method is to handle potentially misaligned data accesses.
// The byte* must point to little endian Unicode characters.
- [System.Security.SecurityCritical] // auto-generated
internal unsafe static int CompareOrdinal(byte* a, int byteLen, String b)
{
- Contract.Assert((byteLen & 1) == 0, "CompareOrdinal is expecting a UTF-16 string length, which must be even!");
- Contract.Assert(a != null && b != null, "Null args not allowed.");
- Contract.Assert(byteLen >= 0, "byteLen must be non-negative.");
+ Debug.Assert((byteLen & 1) == 0, "CompareOrdinal is expecting a UTF-16 string length, which must be even!");
+ Debug.Assert(a != null && b != null, "Null args not allowed.");
+ Debug.Assert(byteLen >= 0, "byteLen must be non-negative.");
int r = 0;
int i = 0;
using System.Security;
using System.Text;
using System.Runtime.Remoting;
-#if FEATURE_REMOTING
-using System.Runtime.Remoting.Proxies;
-using System.Runtime.Remoting.Messaging;
-using System.Runtime.Remoting.Activation;
-using System.Runtime.Remoting.Metadata;
-#endif
using MdSigCallingConvention = System.Signature.MdSigCallingConvention;
using RuntimeTypeCache = System.RuntimeType.RuntimeTypeCache;
using System.Runtime.InteropServices;
private MemberListType m_listType;
private uint m_nameHash;
- [System.Security.SecurityCritical] // auto-generated
public unsafe Filter(byte* pUtf8Name, int cUtf8Name, MemberListType listType)
{
this.m_name = new Utf8String((void*) pUtf8Name, cUtf8Name);
// Currently the callers of UsesStringComparison assume that if it returns false
// then the match always succeeds and can be skipped. Assert that this is maintained.
- Contract.Assert(retVal || RequiresStringComparison());
+ Debug.Assert(retVal || RequiresStringComparison());
return retVal;
}
public uint GetHashToMatch()
{
- Contract.Assert(RequiresStringComparison());
+ Debug.Assert(RequiresStringComparison());
return m_nameHash;
}
#region Constructor
#if MDA_SUPPORTED
- [System.Security.SecuritySafeCritical] // auto-generated
#endif
internal MemberInfoCache(RuntimeTypeCache runtimeTypeCache)
{
m_runtimeTypeCache = runtimeTypeCache;
}
- [System.Security.SecuritySafeCritical] // auto-generated
internal MethodBase AddMethod(RuntimeType declaringType, RuntimeMethodHandleInternal method, CacheType cacheType)
{
T[] list = null;
return (MethodBase)(object)list[0];
}
- [System.Security.SecuritySafeCritical] // auto-generated
internal FieldInfo AddField(RuntimeFieldHandleInternal field)
{
// create the runtime field info
return (FieldInfo)(object)list[0];
}
- [System.Security.SecuritySafeCritical] // auto-generated
private unsafe T[] Populate(string name, MemberListType listType, CacheType cacheType)
{
T[] list = null;
return list;
}
- [System.Security.SecurityCritical] // auto-generated
private unsafe T[] GetListByName(char* pName, int cNameLen, byte* pUtf8Name, int cUtf8Name, MemberListType listType, CacheType cacheType)
{
if (cNameLen != 0)
// May replace the list with a new one if certain cache
// lookups succeed. Also, may modify the contents of the list
// after merging these new data structures with cached ones.
- [System.Security.SecuritySafeCritical] // auto-generated
[ReliabilityContract(Consistency.WillNotCorruptState, Cer.MayFail)]
internal void Insert(ref T[] list, string name, MemberListType listType)
{
// Grow the list by exactly one element in this case to avoid null entries at the end.
//
- Contract.Assert(false);
+ Debug.Assert(false);
newSize = cachedMembers.Length + 1;
}
cachedMembers = cachedMembers2;
}
- Contract.Assert(cachedMembers[freeSlotIndex] == null);
+ Debug.Assert(cachedMembers[freeSlotIndex] == null);
cachedMembers[freeSlotIndex] = newMemberInfo;
freeSlotIndex++;
}
#region Population Logic
- [System.Security.SecuritySafeCritical] // auto-generated
private unsafe RuntimeMethodInfo[] PopulateMethods(Filter filter)
{
ListBuilder<RuntimeMethodInfo> list = new ListBuilder<RuntimeMethodInfo>();
RuntimeType declaringType = ReflectedType;
- Contract.Assert(declaringType != null);
+ Debug.Assert(declaringType != null);
if (RuntimeTypeHandle.IsInterface(declaringType))
{
{
if (!RuntimeMethodHandle.MatchesNameHash(methodHandle, filter.GetHashToMatch()))
{
- Contract.Assert(!filter.Match(RuntimeMethodHandle.GetUtf8Name(methodHandle)));
+ Debug.Assert(!filter.Match(RuntimeMethodHandle.GetUtf8Name(methodHandle)));
continue;
}
}
#region Loop through all methods on the interface
- Contract.Assert(!methodHandle.IsNullHandle());
+ Debug.Assert(!methodHandle.IsNullHandle());
// Except for .ctor, .cctor, IL_STUB*, and static methods, all interface methods should be abstract, virtual, and non-RTSpecialName.
// Note that this assumption will become invalid when we add support for non-abstract or static methods on interfaces.
- Contract.Assert(
+ Debug.Assert(
(RuntimeMethodHandle.GetAttributes(methodHandle) & (MethodAttributes.RTSpecialName | MethodAttributes.Abstract | MethodAttributes.Virtual)) == (MethodAttributes.Abstract | MethodAttributes.Virtual) ||
(RuntimeMethodHandle.GetAttributes(methodHandle) & MethodAttributes.Static) == MethodAttributes.Static ||
RuntimeMethodHandle.GetName(methodHandle).Equals(".ctor") ||
{
if (!RuntimeMethodHandle.MatchesNameHash(methodHandle, filter.GetHashToMatch()))
{
- Contract.Assert(!filter.Match(RuntimeMethodHandle.GetUtf8Name(methodHandle)));
+ Debug.Assert(!filter.Match(RuntimeMethodHandle.GetUtf8Name(methodHandle)));
continue;
}
}
#region Loop through all methods on the current type
- Contract.Assert(!methodHandle.IsNullHandle());
+ Debug.Assert(!methodHandle.IsNullHandle());
MethodAttributes methodAttributes = RuntimeMethodHandle.GetAttributes(methodHandle);
MethodAttributes methodAccess = methodAttributes & MethodAttributes.MemberAccessMask;
#region Continue if this is a constructor
- Contract.Assert(
+ Debug.Assert(
(RuntimeMethodHandle.GetAttributes(methodHandle) & MethodAttributes.RTSpecialName) == 0 ||
RuntimeMethodHandle.GetName(methodHandle).Equals(".ctor") ||
RuntimeMethodHandle.GetName(methodHandle).Equals(".cctor"));
#region Continue if this is a virtual and is already overridden
if (isVirtual)
{
- Contract.Assert(
+ Debug.Assert(
(methodAttributes & MethodAttributes.Abstract) != 0 ||
(methodAttributes & MethodAttributes.Virtual) != 0 ||
RuntimeMethodHandle.GetDeclaringType(methodHandle) != declaringType);
}
else
{
- Contract.Assert((methodAttributes & (MethodAttributes.Virtual | MethodAttributes.Abstract)) == 0);
+ Debug.Assert((methodAttributes & (MethodAttributes.Virtual | MethodAttributes.Abstract)) == 0);
}
#endregion
return list.ToArray();
}
- [System.Security.SecuritySafeCritical] // auto-generated
private RuntimeConstructorInfo[] PopulateConstructors(Filter filter)
{
if (ReflectedType.IsGenericParameter)
{
if (!RuntimeMethodHandle.MatchesNameHash(methodHandle, filter.GetHashToMatch()))
{
- Contract.Assert(!filter.Match(RuntimeMethodHandle.GetUtf8Name(methodHandle)));
+ Debug.Assert(!filter.Match(RuntimeMethodHandle.GetUtf8Name(methodHandle)));
continue;
}
MethodAttributes methodAttributes = RuntimeMethodHandle.GetAttributes(methodHandle);
- Contract.Assert(!methodHandle.IsNullHandle());
+ Debug.Assert(!methodHandle.IsNullHandle());
if ((methodAttributes & MethodAttributes.RTSpecialName) == 0)
continue;
// Constructors should not be virtual or abstract
- Contract.Assert(
+ Debug.Assert(
(methodAttributes & MethodAttributes.Abstract) == 0 &&
(methodAttributes & MethodAttributes.Virtual) == 0);
return list.ToArray();
}
- [System.Security.SecuritySafeCritical] // auto-generated
private unsafe RuntimeFieldInfo[] PopulateFields(Filter filter)
{
ListBuilder<RuntimeFieldInfo> list = new ListBuilder<RuntimeFieldInfo>();
return list.ToArray();
}
- [System.Security.SecuritySafeCritical] // auto-generated
private unsafe void PopulateRtFields(Filter filter, RuntimeType declaringType, ref ListBuilder<RuntimeFieldInfo> list)
{
IntPtr* pResult = stackalloc IntPtr[64];
}
}
- [System.Security.SecurityCritical] // auto-generated
private unsafe void PopulateRtFields(Filter filter,
IntPtr* ppFieldHandles, int count, RuntimeType declaringType, ref ListBuilder<RuntimeFieldInfo> list)
{
{
if (!RuntimeFieldHandle.MatchesNameHash(runtimeFieldHandle, filter.GetHashToMatch()))
{
- Contract.Assert(!filter.Match(RuntimeFieldHandle.GetUtf8Name(runtimeFieldHandle)));
+ Debug.Assert(!filter.Match(RuntimeFieldHandle.GetUtf8Name(runtimeFieldHandle)));
continue;
}
continue;
}
- Contract.Assert(!runtimeFieldHandle.IsNullHandle());
+ Debug.Assert(!runtimeFieldHandle.IsNullHandle());
FieldAttributes fieldAttributes = RuntimeFieldHandle.GetAttributes(runtimeFieldHandle);
FieldAttributes fieldAccess = fieldAttributes & FieldAttributes.FieldAccessMask;
}
}
- [System.Security.SecuritySafeCritical] // auto-generated
private unsafe void PopulateLiteralFields(Filter filter, RuntimeType declaringType, ref ListBuilder<RuntimeFieldInfo> list)
{
Contract.Requires(declaringType != null);
for (int i = 0; i < tkFields.Length; i++)
{
int tkField = tkFields[i];
- Contract.Assert(MdToken.IsTokenOfType(tkField, MetadataTokenType.FieldDef));
- Contract.Assert(!MdToken.IsNullToken(tkField));
+ Debug.Assert(MdToken.IsTokenOfType(tkField, MetadataTokenType.FieldDef));
+ Debug.Assert(!MdToken.IsNullToken(tkField));
FieldAttributes fieldAttributes;
scope.GetFieldDefProps(tkField, out fieldAttributes);
}
- [System.Security.SecuritySafeCritical] // auto-generated
private RuntimeType[] PopulateInterfaces(Filter filter)
{
ListBuilder<RuntimeType> list = new ListBuilder<RuntimeType>();
continue;
}
- Contract.Assert(interfaceType.IsInterface);
+ Debug.Assert(interfaceType.IsInterface);
list.Add(interfaceType);
}
}
return list.ToArray();
}
- [System.Security.SecuritySafeCritical] // auto-generated
private unsafe RuntimeType[] PopulateNestedClasses(Filter filter)
{
RuntimeType declaringType = ReflectedType;
return list.ToArray();
}
- [System.Security.SecuritySafeCritical] // auto-generated
private unsafe RuntimeEventInfo[] PopulateEvents(Filter filter)
{
Contract.Requires(ReflectedType != null);
return list.ToArray();
}
- [System.Security.SecuritySafeCritical] // auto-generated
private unsafe void PopulateEvents(
Filter filter, RuntimeType declaringType, Dictionary<String, RuntimeEventInfo> csEventInfos, ref ListBuilder<RuntimeEventInfo> list)
{
int tkEvent = tkEvents[i];
bool isPrivate;
- Contract.Assert(!MdToken.IsNullToken(tkEvent));
- Contract.Assert(MdToken.IsTokenOfType(tkEvent, MetadataTokenType.Event));
+ Debug.Assert(!MdToken.IsNullToken(tkEvent));
+ Debug.Assert(MdToken.IsTokenOfType(tkEvent, MetadataTokenType.Event));
if (filter.RequiresStringComparison())
{
}
}
- [System.Security.SecuritySafeCritical] // auto-generated
private unsafe RuntimePropertyInfo[] PopulateProperties(Filter filter)
{
Contract.Requires(ReflectedType != null);
// is called in Populate after this returns.
RuntimeType declaringType = ReflectedType;
- Contract.Assert(declaringType != null);
+ Debug.Assert(declaringType != null);
ListBuilder<RuntimePropertyInfo> list = new ListBuilder<RuntimePropertyInfo>();
return list.ToArray();
}
- [System.Security.SecuritySafeCritical] // auto-generated
private unsafe void PopulateProperties(
Filter filter,
RuntimeType declaringType,
int numVirtuals = RuntimeTypeHandle.GetNumVirtuals(declaringType);
- Contract.Assert((declaringType.IsInterface && usedSlots == null && csPropertyInfos == null) ||
+ Debug.Assert((declaringType.IsInterface && usedSlots == null && csPropertyInfos == null) ||
(!declaringType.IsInterface && usedSlots != null && usedSlots.Length >= numVirtuals));
for (int i = 0; i < tkProperties.Length; i++)
int tkProperty = tkProperties[i];
bool isPrivate;
- Contract.Assert(!MdToken.IsNullToken(tkProperty));
- Contract.Assert(MdToken.IsTokenOfType(tkProperty, MetadataTokenType.Property));
+ Debug.Assert(!MdToken.IsNullToken(tkProperty));
+ Debug.Assert(MdToken.IsTokenOfType(tkProperty, MetadataTokenType.Property));
if (filter.RequiresStringComparison())
{
if (!ModuleHandle.ContainsPropertyMatchingHash(declaringModuleHandle, tkProperty, filter.GetHashToMatch()))
{
- Contract.Assert(!filter.Match(declaringType.GetRuntimeModule().MetadataImport.GetName(tkProperty)));
+ Debug.Assert(!filter.Match(declaringType.GetRuntimeModule().MetadataImport.GetName(tkProperty)));
continue;
}
if (slot < numVirtuals)
{
- Contract.Assert(associateMethod.IsVirtual);
+ Debug.Assert(associateMethod.IsVirtual);
if (usedSlots[slot] == true)
continue;
else
return Populate(name, listType, cacheType);
default:
- Contract.Assert(listType == MemberListType.All);
+ Debug.Assert(listType == MemberListType.All);
if (Volatile.Read(ref m_cacheComplete))
return m_allMembers;
private MemberInfoCache<RuntimeEventInfo> m_eventInfoCache;
private static CerHashtable<RuntimeMethodInfo, RuntimeMethodInfo> s_methodInstantiations;
private static Object s_methodInstantiationsLock;
-#if !FEATURE_CORECLR
- private RuntimeConstructorInfo m_serializationCtor;
-#endif
private string m_defaultMemberName;
private Object m_genericCache; // Generic cache for rare scenario specific data. It is used to cache Enum names and values.
#endregion
}
}
- [System.Security.SecuritySafeCritical]
internal unsafe string GetNameSpace()
{
// @Optimization - Use ConstructName to populate m_namespace
set { m_typeCode = value; }
}
- [System.Security.SecuritySafeCritical] // auto-generated
internal unsafe RuntimeType GetEnclosingType()
{
if (m_enclosingType == null)
{
// Use void as a marker of null enclosing type
RuntimeType enclosingType = RuntimeTypeHandle.GetDeclaringType(GetRuntimeType());
- Contract.Assert(enclosingType != typeof(void));
+ Debug.Assert(enclosingType != typeof(void));
m_enclosingType = enclosingType ?? (RuntimeType)typeof(void);
}
m_nestedClassesCache = null;
}
-#if !FEATURE_CORECLR
- internal RuntimeConstructorInfo GetSerializationCtor()
- {
- if (m_serializationCtor == null)
- {
- if (s_SICtorParamTypes == null)
- s_SICtorParamTypes = new Type[] { typeof(SerializationInfo), typeof(StreamingContext) };
-
- m_serializationCtor = m_runtimeType.GetConstructor(
- BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic,
- null,
- CallingConventions.Any,
- s_SICtorParamTypes,
- null) as RuntimeConstructorInfo;
- }
-
- return m_serializationCtor;
- }
-#endif //!FEATURE_CORECLR
-
internal string GetDefaultMemberName()
{
if (m_defaultMemberName == null)
#endregion
#region Caches Accessors
- [System.Security.SecurityCritical] // auto-generated
internal MethodInfo GetGenericMethodInfo(RuntimeMethodHandleInternal genericMethod)
{
LoaderAllocator la = RuntimeMethodHandle.GetLoaderAllocator(genericMethod);
}
#endregion
-#if FEATURE_REMOTING
- #region Legacy Remoting Cache
- // The size of CachedData is accounted for by BaseObjectWithCachedData in object.h.
- // This member is currently being used by Remoting for caching remoting data. If you
- // need to cache data here, talk to the Remoting team to work out a mechanism, so that
- // both caching systems can happily work together.
- private RemotingTypeCachedData m_cachedData;
-
- internal RemotingTypeCachedData RemotingCache
- {
- get
- {
- // This grabs an internal copy of m_cachedData and uses
- // that instead of looking at m_cachedData directly because
- // the cache may get cleared asynchronously. This prevents
- // us from having to take a lock.
- RemotingTypeCachedData cache = m_cachedData;
- if (cache == null)
- {
- cache = new RemotingTypeCachedData(this);
- RemotingTypeCachedData ret = Interlocked.CompareExchange(ref m_cachedData, cache, null);
- if (ret != null)
- cache = ret;
- }
- return cache;
- }
- }
- #endregion
-#endif //FEATURE_REMOTING
-
#region Static Members
#region Internal
return GetMethodBase(null, methodHandle);
}
- [System.Security.SecuritySafeCritical]
internal static MethodBase GetMethodBase(RuntimeType reflectedType, IRuntimeMethodInfo methodHandle)
{
MethodBase retval = RuntimeType.GetMethodBase(reflectedType, methodHandle.Value);
return retval;
}
- [System.Security.SecurityCritical] // auto-generated
internal unsafe static MethodBase GetMethodBase(RuntimeType reflectedType, RuntimeMethodHandleInternal methodHandle)
{
- Contract.Assert(!methodHandle.IsNullHandle());
+ Debug.Assert(!methodHandle.IsNullHandle());
if (RuntimeMethodHandle.IsDynamicMethod(methodHandle))
{
set { Cache.DomainInitialized = value; }
}
- [System.Security.SecuritySafeCritical] // auto-generated
internal unsafe static FieldInfo GetFieldInfo(IRuntimeFieldInfo fieldHandle)
{
return GetFieldInfo(RuntimeFieldHandle.GetApproxDeclaringType(fieldHandle), fieldHandle);
}
- [System.Security.SecuritySafeCritical] // auto-generated
internal unsafe static FieldInfo GetFieldInfo(RuntimeType reflectedType, IRuntimeFieldInfo field)
{
RuntimeFieldHandleInternal fieldHandle = field.Value;
Environment.GetResourceString("Argument_NotEnoughGenArguments", genericArguments.Length, genericParamters.Length));
}
- [System.Security.SecuritySafeCritical] // auto-generated
internal static void ValidateGenericArguments(MemberInfo definition, RuntimeType[] genericArguments, Exception e)
{
RuntimeType[] typeContext = null;
name = fullname.Substring(nsDelimiter + 1, nameLength);
else
name = "";
- Contract.Assert(fullname.Equals(ns + "." + name));
+ Debug.Assert(fullname.Equals(ns + "." + name));
}
else
{
// Most of the plural GetXXX methods allow prefix lookups while the singular GetXXX methods mostly do not.
private static bool FilterApplyPrefixLookup(MemberInfo memberInfo, string name, bool ignoreCase)
{
- Contract.Assert(name != null);
+ Debug.Assert(name != null);
if (ignoreCase)
{
Type type, BindingFlags bindingFlags, string name, bool prefixLookup, string ns)
{
Contract.Requires((object)type != null);
- Contract.Assert(type is RuntimeType);
+ Debug.Assert(type is RuntimeType);
bool isPublic = type.IsNestedPublic || type.IsPublic;
bool isStatic = false;
{
// If Binding flags did not include varargs we would have filtered this vararg method.
// This Invariant established during callConv check.
- Contract.Assert((callConv & CallingConventions.VarArgs) != 0);
+ Debug.Assert((callConv & CallingConventions.VarArgs) != 0);
}
#endregion
}
private RuntimeTypeCache Cache
{
- [System.Security.SecuritySafeCritical] // auto-generated
get
{
if (m_cache.IsNull())
cache = existingCache;
}
- Contract.Assert(cache != null);
+ Debug.Assert(cache != null);
return cache;
}
}
{
return Cache.GetDefaultMemberName();
}
-
-#if !FEATURE_CORECLR
- internal RuntimeConstructorInfo GetSerializationCtor()
- {
- return Cache.GetSerializationCtor();
- }
-#endif
#endregion
#region Type Overrides
return GetFieldCandidates(null, bindingAttr, false).ToArray();
}
- [System.Security.SecuritySafeCritical] // auto-generated
public override Type[] GetInterfaces()
{
RuntimeType[] candidates = this.Cache.GetInterfaceList(MemberListType.All, null);
events.CopyTo(members, i); i += events.Count;
fields.CopyTo(members, i); i += fields.Count;
nestedTypes.CopyTo(members, i); i += nestedTypes.Count;
- Contract.Assert(i == members.Length);
+ Debug.Assert(i == members.Length);
return members;
}
- [System.Security.SecuritySafeCritical] // auto-generated
public override InterfaceMapping GetInterfaceMap(Type ifaceType)
{
if (IsGenericParameter)
RuntimeTypeHandle ifaceRtTypeHandle = ifaceRtType.GetTypeHandleInternal();
GetTypeHandleInternal().VerifyInterfaceIsImplemented(ifaceRtTypeHandle);
- Contract.Assert(ifaceType.IsInterface); // VerifyInterfaceIsImplemented enforces this invariant
- Contract.Assert(!IsInterface); // VerifyInterfaceIsImplemented enforces this invariant
+ Debug.Assert(ifaceType.IsInterface); // VerifyInterfaceIsImplemented enforces this invariant
+ Debug.Assert(!IsInterface); // VerifyInterfaceIsImplemented enforces this invariant
// SZArrays implement the methods on IList`1, IEnumerable`1, and ICollection`1 with
// SZArrayHelper and some runtime magic. We don't have accurate interface maps for them.
// GetMethodBase will convert this to the instantiating/unboxing stub if necessary
MethodBase ifaceMethodBase = RuntimeType.GetMethodBase(ifaceRtType, ifaceRtMethodHandle);
- Contract.Assert(ifaceMethodBase is RuntimeMethodInfo);
+ Debug.Assert(ifaceMethodBase is RuntimeMethodInfo);
im.InterfaceMethods[i] = (MethodInfo)ifaceMethodBase;
// If the slot is -1, then virtual stub dispatch is active.
// GetMethodBase will convert this to the instantiating/unboxing stub if necessary
MethodBase rtTypeMethodBase = RuntimeType.GetMethodBase(this, classRtMethodHandle);
// a class may not implement all the methods of an interface (abstract class) so null is a valid value
- Contract.Assert(rtTypeMethodBase == null || rtTypeMethodBase is RuntimeMethodInfo);
+ Debug.Assert(rtTypeMethodBase == null || rtTypeMethodBase is RuntimeMethodInfo);
im.TargetMethods[i] = (MethodInfo)rtTypeMethodBase;
}
events.CopyTo(compressMembers, i); i += events.Count;
fields.CopyTo(compressMembers, i); i += fields.Count;
nestedTypes.CopyTo(compressMembers, i); i += nestedTypes.Count;
- Contract.Assert(i == compressMembers.Length);
+ Debug.Assert(i == compressMembers.Length);
return compressMembers;
}
return new RuntimeTypeHandle(this);
}
- [System.Security.SecuritySafeCritical]
internal bool IsCollectible()
{
return RuntimeTypeHandle.IsCollectible(GetTypeHandleInternal());
}
- [System.Security.SecuritySafeCritical] // auto-generated
protected override TypeCode GetTypeCodeImpl()
{
TypeCode typeCode = Cache.TypeCode;
#endregion
#region Hierarchy
- [System.Security.SecuritySafeCritical] // auto-generated
public override bool IsInstanceOfType(Object o)
{
return RuntimeTypeHandle.IsInstanceOfType(this, o);
return false;
}
-#if !FEATURE_CORECLR
- // Reflexive, symmetric, transitive.
- public override bool IsEquivalentTo(Type other)
- {
- RuntimeType otherRtType = other as RuntimeType;
- if ((object)otherRtType == null)
- return false;
-
- if (otherRtType == this)
- return true;
-
- // It's not worth trying to perform further checks in managed
- // as they would lead to FCalls anyway.
- return RuntimeTypeHandle.IsEquivalentTo(this, otherRtType);
- }
-#endif // FEATURE_CORECLR
-
public override Type BaseType
{
get
#endregion
#region Attributes
- [System.Security.SecuritySafeCritical] // auto-generated
protected override TypeAttributes GetAttributeFlagsImpl()
{
return RuntimeTypeHandle.GetAttributes(this);
public override Guid GUID
{
- [System.Security.SecuritySafeCritical] // auto-generated
get
{
Guid result = new Guid ();
}
}
- [System.Security.SecurityCritical] // auto-generated
[MethodImplAttribute(MethodImplOptions.InternalCall)]
private extern void GetGUID(ref Guid result);
- [System.Security.SecuritySafeCritical] // auto-generated
protected override bool IsContextfulImpl()
{
-#if FEATURE_REMOTING
- return RuntimeTypeHandle.IsContextful(this);
-#else
return false;
-#endif
}
- /*
- protected override bool IsMarshalByRefImpl()
- {
- return GetTypeHandleInternal().IsMarshalByRef();
- }
- */
-
protected override bool IsByRefImpl()
{
return RuntimeTypeHandle.IsByRef(this);
return RuntimeTypeHandle.IsPointer(this);
}
- [System.Security.SecuritySafeCritical] // auto-generated
protected override bool IsCOMObjectImpl()
{
return RuntimeTypeHandle.IsComObject(this, false);
}
#if FEATURE_COMINTEROP
- [SecuritySafeCritical]
internal override bool IsWindowsRuntimeObjectImpl()
{
return IsWindowsRuntimeObjectType(this);
}
- [SecuritySafeCritical]
internal override bool IsExportedToWindowsRuntimeImpl()
{
return IsTypeExportedToWindowsRuntime(this);
}
[MethodImplAttribute(MethodImplOptions.InternalCall)]
- [SecurityCritical]
private static extern bool IsWindowsRuntimeObjectType(RuntimeType type);
[MethodImplAttribute(MethodImplOptions.InternalCall)]
- [SecurityCritical]
private static extern bool IsTypeExportedToWindowsRuntime(RuntimeType type);
#endif // FEATURE_COMINTEROP
- [System.Security.SecuritySafeCritical] // auto-generated
internal override bool HasProxyAttributeImpl()
{
return RuntimeTypeHandle.HasProxyAttribute(this);
return IsSubclassOf(typeof(ValueType));
}
-#if !FEATURE_CORECLR
- public override bool IsEnum
- {
- get
- {
- return GetBaseType() == RuntimeType.EnumType;
- }
- }
-#endif
-
protected override bool HasElementTypeImpl()
{
return RuntimeTypeHandle.HasElementType(this);
public override GenericParameterAttributes GenericParameterAttributes
{
- [System.Security.SecuritySafeCritical] // auto-generated
get
{
if (!IsGenericParameter)
return RuntimeTypeHandle.IsArray(this);
}
- [System.Security.SecuritySafeCritical] // auto-generated
public override int GetArrayRank()
{
if (!IsArrayImpl())
return retVal;
}
- [SecuritySafeCritical]
public override Array GetEnumValues()
{
if (!IsEnum)
return types;
}
- [System.Security.SecuritySafeCritical] // auto-generated
public override Type MakeGenericType(Type[] instantiation)
{
if (instantiation == null)
#endregion
#region Misc
- [System.Security.SecuritySafeCritical] // auto-generated
public override Type MakePointerType() { return new RuntimeTypeHandle(this).MakePointer(); }
public override Type MakeByRefType() { return new RuntimeTypeHandle(this).MakeByRef(); }
public override Type MakeArrayType() { return new RuntimeTypeHandle(this).MakeSZArray(); }
}
public override StructLayoutAttribute StructLayoutAttribute
{
- [System.Security.SecuritySafeCritical] // overrides transparent public member
get
{
return (StructLayoutAttribute)StructLayoutAttribute.GetCustomAttribute(this);
BindingFlags.PutDispProperty | BindingFlags.PutRefDispProperty;
private static RuntimeType s_typedRef = (RuntimeType)typeof(TypedReference);
- [System.Security.SecurityCritical] // auto-generated
[MethodImplAttribute(MethodImplOptions.InternalCall)]
static private extern bool CanValueSpecialCast(RuntimeType valueType, RuntimeType targetType);
- [System.Security.SecurityCritical] // auto-generated
[MethodImplAttribute(MethodImplOptions.InternalCall)]
static private extern Object AllocateValueType(RuntimeType type, object value, bool fForceTypeChange);
- [System.Security.SecuritySafeCritical] // auto-generated
internal unsafe Object CheckValue(Object value, Binder binder, CultureInfo culture, BindingFlags invokeAttr)
{
// this method is used by invocation in reflection to check whether a value can be assigned to type.
{
// Since this cannot be a generic parameter, we use RuntimeTypeHandle.IsValueType here
// because it is faster than RuntimeType.IsValueType
- Contract.Assert(!IsGenericParameter);
-
- Type type = null;
-
-#if FEATURE_REMOTING
- // For the remoting objects Object.GetType goes through proxy. Avoid the proxy call and just get
- // the type directly. It is necessary to support proxies that do not handle GetType.
- RealProxy realProxy = System.Runtime.Remoting.RemotingServices.GetRealProxy(value);
+ Debug.Assert(!IsGenericParameter);
- if (realProxy != null)
- {
- type = realProxy.GetProxiedType();
- }
- else
- {
- type = value.GetType();
- }
-#else
- type = value.GetType();
-#endif
+ Type type = value.GetType();
if (!Object.ReferenceEquals(type, this) && RuntimeTypeHandle.IsValueType(this))
{
}
// Factored out of CheckValue to reduce code complexity.
- [System.Security.SecurityCritical]
private Object TryChangeType(Object value, Binder binder, CultureInfo culture, bool needsSpecialCast)
{
if (binder != null && binder != Type.DefaultBinder)
}
#if FEATURE_COMINTEROP
- [System.Security.SecuritySafeCritical] // auto-generated
#endif
[DebuggerStepThroughAttribute]
[Diagnostics.DebuggerHidden]
throw new ArgumentException(Environment.GetResourceString("Arg_COMPropSetPut"), nameof(bindingFlags));
#endregion
-#if FEATURE_REMOTING
- if(!RemotingServices.IsTransparentProxy(target))
-#endif
{
#region Non-TransparentProxy case
if (name == null)
return InvokeDispMethod(name, bindingFlags, target, providedArgs, isByRef, lcid, namedParams);
#endregion
}
-#if FEATURE_REMOTING
- else
- {
- #region TransparentProxy case
- return ((MarshalByRefObject)target).InvokeMember(name, bindingFlags, binder, providedArgs, modifiers, culture, namedParams);
- #endregion
- }
-#endif // FEATURE_REMOTING
}
#endif // FEATURE_COMINTEROP && FEATURE_USE_LCID
#endregion
}
else
{
- Contract.Assert(IsSetField);
+ Debug.Assert(IsSetField);
if (providedArgs == null)
throw new ArgumentNullException(nameof(providedArgs));
FieldInfo selFld = null;
FieldInfo[] flds = GetMember(name, MemberTypes.Field, bindingFlags) as FieldInfo[];
- Contract.Assert(flds != null);
+ Debug.Assert(flds != null);
if (flds.Length == 1)
{
#region Preconditions
if (isGetProperty)
{
- Contract.Assert(!IsSetField);
+ Debug.Assert(!IsSetField);
if (isSetProperty)
throw new ArgumentException(Environment.GetResourceString("Arg_PropSetGet"), nameof(bindingFlags));
}
else
{
- Contract.Assert(isSetProperty);
+ Debug.Assert(isSetProperty);
- Contract.Assert(!IsGetField);
+ Debug.Assert(!IsGetField);
if ((bindingFlags & BindingFlags.InvokeMethod) != 0)
throw new ArgumentException(Environment.GetResourceString("Arg_PropSetInvoke"), nameof(bindingFlags));
for(int i = 0; i < semiFinalists.Length; i ++)
{
MethodInfo semiFinalist = semiFinalists[i];
- Contract.Assert(semiFinalist != null);
+ Debug.Assert(semiFinalist != null);
if (!FilterApplyMethodInfo((RuntimeMethodInfo)semiFinalist, bindingFlags, CallingConventions.Any, new Type[argCnt]))
continue;
if (results != null)
{
- Contract.Assert(results.Count > 1);
+ Debug.Assert(results.Count > 1);
finalists = new MethodInfo[results.Count];
results.CopyTo(finalists);
}
}
#endregion
- Contract.Assert(finalists == null || finalist != null);
+ Debug.Assert(finalists == null || finalist != null);
#region BindingFlags.GetProperty or BindingFlags.SetProperty
if (finalist == null && isGetProperty || isSetProperty)
if (results != null)
{
- Contract.Assert(results.Count > 1);
+ Debug.Assert(results.Count > 1);
finalists = new MethodInfo[results.Count];
results.CopyTo(finalists);
}
return RuntimeHelpers.GetHashCode(this);
}
-#if !FEATURE_CORECLR
- public static bool operator ==(RuntimeType left, RuntimeType right)
- {
- return object.ReferenceEquals(left, right);
- }
-
- public static bool operator !=(RuntimeType left, RuntimeType right)
- {
- return !object.ReferenceEquals(left, right);
- }
-#endif // !FEATURE_CORECLR
-
public override String ToString()
{
return GetCachedName(TypeNameKind.ToString);
#endregion
#region ISerializable
- [System.Security.SecurityCritical] // auto-generated
public void GetObjectData(SerializationInfo info, StreamingContext context)
{
if (info==null)
#endregion
#region ICustomAttributeProvider
- [System.Security.SecuritySafeCritical] // auto-generated
public override Object[] GetCustomAttributes(bool inherit)
{
return CustomAttribute.GetCustomAttributes(this, RuntimeType.ObjectType, inherit);
}
- [System.Security.SecuritySafeCritical] // auto-generated
public override Object[] GetCustomAttributes(Type attributeType, bool inherit)
{
if ((object)attributeType == null)
return CustomAttribute.GetCustomAttributes(this, attributeRuntimeType, inherit);
}
- [System.Security.SecuritySafeCritical] // auto-generated
public override bool IsDefined(Type attributeType, bool inherit)
{
if ((object)attributeType == null)
public override int MetadataToken
{
- [System.Security.SecuritySafeCritical] // auto-generated
get
{
return RuntimeTypeHandle.GetToken(this);
throw new NotSupportedException(Environment.GetResourceString("Acc_CreateVoid"));
}
- [System.Security.SecurityCritical] // auto-generated
internal Object CreateInstanceImpl(
BindingFlags bindingAttr, Binder binder, Object[] args, CultureInfo culture, Object[] activationAttributes, ref StackCrawlMark stackMark)
{
Object server = null;
- try
- {
- try
- {
- // Store the activation attributes in thread local storage.
- // These attributes are later picked up by specialized
- // activation services like remote activation services to
- // influence the activation.
-#if FEATURE_REMOTING
- if(null != activationAttributes)
- {
- ActivationServices.PushActivationAttributes(this, activationAttributes);
- }
-#endif
-
- if (args == null)
- args = EmptyArray<Object>.Value;
+ if (args == null)
+ args = EmptyArray<Object>.Value;
- int argCnt = args.Length;
+ int argCnt = args.Length;
- // Without a binder we need to do use the default binder...
- if (binder == null)
- binder = DefaultBinder;
+ // Without a binder we need to do use the default binder...
+ if (binder == null)
+ binder = DefaultBinder;
+
+ // deal with the __COMObject case first. It is very special because from a reflection point of view it has no ctors
+ // so a call to GetMemberCons would fail
+ if (argCnt == 0 && (bindingAttr & BindingFlags.Public) != 0 && (bindingAttr & BindingFlags.Instance) != 0
+ && (IsGenericCOMObjectImpl() || IsValueType))
+ {
+ server = CreateInstanceDefaultCtor((bindingAttr & BindingFlags.NonPublic) == 0 , false, true, ref stackMark);
+ }
+ else
+ {
+ ConstructorInfo[] candidates = GetConstructors(bindingAttr);
+ List<MethodBase> matches = new List<MethodBase>(candidates.Length);
- // deal with the __COMObject case first. It is very special because from a reflection point of view it has no ctors
- // so a call to GetMemberCons would fail
- if (argCnt == 0 && (bindingAttr & BindingFlags.Public) != 0 && (bindingAttr & BindingFlags.Instance) != 0
- && (IsGenericCOMObjectImpl() || IsValueType))
+ // We cannot use Type.GetTypeArray here because some of the args might be null
+ Type[] argsType = new Type[argCnt];
+ for (int i = 0; i < argCnt; i++)
+ {
+ if (args[i] != null)
{
- server = CreateInstanceDefaultCtor((bindingAttr & BindingFlags.NonPublic) == 0 , false, true, ref stackMark);
+ argsType[i] = args[i].GetType();
}
- else
- {
- ConstructorInfo[] candidates = GetConstructors(bindingAttr);
- List<MethodBase> matches = new List<MethodBase>(candidates.Length);
-
- // We cannot use Type.GetTypeArray here because some of the args might be null
- Type[] argsType = new Type[argCnt];
- for (int i = 0; i < argCnt; i++)
- {
- if (args[i] != null)
- {
- argsType[i] = args[i].GetType();
- }
- }
-
- for(int i = 0; i < candidates.Length; i ++)
- {
- if (FilterApplyConstructorInfo((RuntimeConstructorInfo)candidates[i], bindingAttr, CallingConventions.Any, argsType))
- matches.Add(candidates[i]);
- }
+ }
- MethodBase[] cons = new MethodBase[matches.Count];
- matches.CopyTo(cons);
- if (cons != null && cons.Length == 0)
- cons = null;
+ for(int i = 0; i < candidates.Length; i ++)
+ {
+ if (FilterApplyConstructorInfo((RuntimeConstructorInfo)candidates[i], bindingAttr, CallingConventions.Any, argsType))
+ matches.Add(candidates[i]);
+ }
- if (cons == null)
- {
- // Null out activation attributes before throwing exception
-#if FEATURE_REMOTING
- if(null != activationAttributes)
- {
- ActivationServices.PopActivationAttributes(this);
- activationAttributes = null;
- }
-#endif
- throw new MissingMethodException(Environment.GetResourceString("MissingConstructor_Name", FullName));
- }
+ MethodBase[] cons = new MethodBase[matches.Count];
+ matches.CopyTo(cons);
+ if (cons != null && cons.Length == 0)
+ cons = null;
- MethodBase invokeMethod;
- Object state = null;
+ if (cons == null)
+ {
+ throw new MissingMethodException(Environment.GetResourceString("MissingConstructor_Name", FullName));
+ }
- try
- {
- invokeMethod = binder.BindToMethod(bindingAttr, cons, ref args, null, culture, null, out state);
- }
- catch (MissingMethodException) { invokeMethod = null; }
+ MethodBase invokeMethod;
+ Object state = null;
- if (invokeMethod == null)
- {
-#if FEATURE_REMOTING
- // Null out activation attributes before throwing exception
- if(null != activationAttributes)
- {
- ActivationServices.PopActivationAttributes(this);
- activationAttributes = null;
- }
-#endif
- throw new MissingMethodException(Environment.GetResourceString("MissingConstructor_Name", FullName));
- }
+ try
+ {
+ invokeMethod = binder.BindToMethod(bindingAttr, cons, ref args, null, culture, null, out state);
+ }
+ catch (MissingMethodException) { invokeMethod = null; }
- // If we're creating a delegate, we're about to call a
- // constructor taking an integer to represent a target
- // method. Since this is very difficult (and expensive)
- // to verify, we're just going to demand UnmanagedCode
- // permission before allowing this. Partially trusted
- // clients can instead use Delegate.CreateDelegate,
- // which allows specification of the target method via
- // name or MethodInfo.
- //if (isDelegate)
- if (RuntimeType.DelegateType.IsAssignableFrom(invokeMethod.DeclaringType))
- {
-#if FEATURE_CORECLR
- // In CoreCLR, CAS is not exposed externally. So what we really are looking
- // for is to see if the external caller of this API is transparent or not.
- // We get that information from the fact that a Demand will succeed only if
- // the external caller is not transparent.
- try
- {
+ if (invokeMethod == null)
+ {
+ throw new MissingMethodException(Environment.GetResourceString("MissingConstructor_Name", FullName));
+ }
+
+ // If we're creating a delegate, we're about to call a
+ // constructor taking an integer to represent a target
+ // method. Since this is very difficult (and expensive)
+ // to verify, we're just going to demand UnmanagedCode
+ // permission before allowing this. Partially trusted
+ // clients can instead use Delegate.CreateDelegate,
+ // which allows specification of the target method via
+ // name or MethodInfo.
+ //if (isDelegate)
+ if (RuntimeType.DelegateType.IsAssignableFrom(invokeMethod.DeclaringType))
+ {
+ // In CoreCLR, CAS is not exposed externally. So what we really are looking
+ // for is to see if the external caller of this API is transparent or not.
+ // We get that information from the fact that a Demand will succeed only if
+ // the external caller is not transparent.
+ try
+ {
#pragma warning disable 618
- new SecurityPermission(SecurityPermissionFlag.UnmanagedCode).Demand();
+ new SecurityPermission(SecurityPermissionFlag.UnmanagedCode).Demand();
#pragma warning restore 618
- }
- catch
- {
- throw new NotSupportedException(String.Format(CultureInfo.CurrentCulture, Environment.GetResourceString("NotSupported_DelegateCreationFromPT")));
- }
-#else // FEATURE_CORECLR
- new SecurityPermission(SecurityPermissionFlag.UnmanagedCode).Demand();
-#endif // FEATURE_CORECLR
- }
-
- if (invokeMethod.GetParametersNoCopy().Length == 0)
- {
- if (args.Length != 0)
- {
-
- Contract.Assert((invokeMethod.CallingConvention & CallingConventions.VarArgs) ==
- CallingConventions.VarArgs);
- throw new NotSupportedException(String.Format(CultureInfo.CurrentCulture,
- Environment.GetResourceString("NotSupported_CallToVarArg")));
- }
-
- // fast path??
- server = Activator.CreateInstance(this, true);
- }
- else
- {
- server = ((ConstructorInfo)invokeMethod).Invoke(bindingAttr, binder, args, culture);
- if (state != null)
- binder.ReorderArgumentArray(ref args, state);
- }
}
- }
- finally
+ catch
+ {
+ throw new NotSupportedException(String.Format(CultureInfo.CurrentCulture, Environment.GetResourceString("NotSupported_DelegateCreationFromPT")));
+ }
+ }
+
+ if (invokeMethod.GetParametersNoCopy().Length == 0)
{
-#if FEATURE_REMOTING
- // Reset the TLS to null
- if(null != activationAttributes)
+ if (args.Length != 0)
{
- ActivationServices.PopActivationAttributes(this);
- activationAttributes = null;
+
+ Debug.Assert((invokeMethod.CallingConvention & CallingConventions.VarArgs) ==
+ CallingConventions.VarArgs);
+ throw new NotSupportedException(String.Format(CultureInfo.CurrentCulture,
+ Environment.GetResourceString("NotSupported_CallToVarArg")));
}
-#endif
+
+ // fast path??
+ server = Activator.CreateInstance(this, true);
+ }
+ else
+ {
+ server = ((ConstructorInfo)invokeMethod).Invoke(bindingAttr, binder, args, culture);
+ if (state != null)
+ binder.ReorderArgumentArray(ref args, state);
}
}
- catch (Exception)
- {
- throw;
- }
-
- //Console.WriteLine(server);
- return server;
+
+ return server;
}
// the cache entry
// Lazy initialization was performed
internal volatile bool m_bFullyInitialized;
- [System.Security.SecurityCritical]
internal ActivatorCacheEntry(RuntimeType t, RuntimeMethodHandleInternal rmh, bool bNeedSecurityCheck)
{
m_type = t;
delegateCtorInfo = ctorInfo; // this assignment should be last
}
- [System.Security.SecuritySafeCritical] // auto-generated
private void InitializeCacheEntry(ActivatorCacheEntry ace)
{
if (!ace.m_type.IsValueType)
{
- Contract.Assert(!ace.m_hCtorMethodHandle.IsNullHandle(), "Expected the default ctor method handle for a reference type.");
+ Debug.Assert(!ace.m_hCtorMethodHandle.IsNullHandle(), "Expected the default ctor method handle for a reference type.");
if (delegateCtorInfo == null)
InitializeDelegateCreator();
private static volatile ActivatorCache s_ActivatorCache;
// the slow path of CreateInstanceDefaultCtor
- [System.Security.SecuritySafeCritical] // auto-generated
internal Object CreateInstanceSlow(bool publicOnly, bool skipCheckThis, bool fillCache, ref StackCrawlMark stackMark)
{
RuntimeMethodHandleInternal runtime_ctor = default(RuntimeMethodHandleInternal);
bCanBeCached = false;
}
#endif
-#if FEATURE_CORECLR
bSecurityCheckOff = true; // CoreCLR does not use security at all.
-#endif
Object instance = RuntimeTypeHandle.CreateInstance(this, publicOnly, bSecurityCheckOff, ref bCanBeCached, ref runtime_ctor, ref bNeedSecurityCheck);
// Helper to invoke the default (parameterless) ctor.
// fillCache is set in the SL2/3 compat mode or when called from Marshal.PtrToStructure.
- [System.Security.SecuritySafeCritical] // auto-generated
[DebuggerStepThroughAttribute]
[Diagnostics.DebuggerHidden]
internal Object CreateInstanceDefaultCtor(bool publicOnly, bool skipCheckThis, bool fillCache, ref StackCrawlMark stackMark)
Object instance = RuntimeTypeHandle.Allocate(this);
// if m_ctor is null, this type doesn't have a default ctor
- Contract.Assert(ace.m_ctor != null || this.IsValueType);
+ Debug.Assert(ace.m_ctor != null || this.IsValueType);
if (ace.m_ctor != null)
{
-#if !FEATURE_CORECLR
- // Perform security checks if needed
- if (ace.m_bNeedSecurityCheck)
- RuntimeMethodHandle.PerformSecurityCheck(instance, ace.m_hCtorMethodHandle, this, (uint)INVOCATION_FLAGS.INVOCATION_FLAGS_CONSTRUCTOR_INVOKE);
-#endif
-
// Call ctor (value types wont have any)
try
{
Cache.InvalidateCachedNestedType();
}
- [System.Security.SecuritySafeCritical] // auto-generated
internal bool IsGenericCOMObjectImpl()
{
return RuntimeTypeHandle.IsComObject(this, true);
#endregion
#region Legacy Static Internal
- [System.Security.SecurityCritical]
[MethodImplAttribute(MethodImplOptions.InternalCall)]
private static extern Object _CreateEnum(RuntimeType enumType, long value);
- [System.Security.SecuritySafeCritical] // auto-generated
internal static Object CreateEnum(RuntimeType enumType, long value)
{
return _CreateEnum(enumType, value);
}
- [System.Security.SecurityCritical] // auto-generated
[MethodImplAttribute(MethodImplOptions.InternalCall)]
private extern Object InvokeDispMethod(
String name, BindingFlags invokeAttr, Object target, Object[] args,
bool[] byrefModifiers, int culture, String[] namedParameters);
#if FEATURE_COMINTEROP_UNMANAGED_ACTIVATION
- [System.Security.SecurityCritical] // auto-generated
[MethodImplAttribute(MethodImplOptions.InternalCall)]
internal static extern Type GetTypeFromProgIDImpl(String progID, String server, bool throwOnError);
- [System.Security.SecurityCritical] // auto-generated
[MethodImplAttribute(MethodImplOptions.InternalCall)]
internal static extern Type GetTypeFromCLSIDImpl(Guid clsid, String server, bool throwOnError);
#else // FEATURE_COMINTEROP_UNMANAGED_ACTIVATION
#endregion
#region COM
-#if FEATURE_COMINTEROP && FEATURE_REMOTING
- [System.Security.SecuritySafeCritical] // auto-generated
- private Object ForwardCallToInvokeMember(String memberName, BindingFlags flags, Object target, int[] aWrapperTypes, ref MessageData msgData)
- {
- ParameterModifier[] aParamMod = null;
- Object ret = null;
-
- // Allocate a new message
- Message reqMsg = new Message();
- reqMsg.InitFields(msgData);
-
- // Retrieve the required information from the message object.
- MethodInfo meth = (MethodInfo)reqMsg.GetMethodBase();
- Object[] aArgs = reqMsg.Args;
- int cArgs = aArgs.Length;
-
- // Retrieve information from the method we are invoking on.
- ParameterInfo[] aParams = meth.GetParametersNoCopy();
-
- // If we have arguments, then set the byref flags to true for byref arguments.
- // We also wrap the arguments that require wrapping.
- if (cArgs > 0)
- {
- ParameterModifier paramMod = new ParameterModifier(cArgs);
- for (int i = 0; i < cArgs; i++)
- {
- if (aParams[i].ParameterType.IsByRef)
- paramMod[i] = true;
- }
-
- aParamMod = new ParameterModifier[1];
- aParamMod[0] = paramMod;
-
- if (aWrapperTypes != null)
- WrapArgsForInvokeCall(aArgs, aWrapperTypes);
- }
-
- // If the method has a void return type, then set the IgnoreReturn binding flag.
- if (Object.ReferenceEquals(meth.ReturnType, typeof(void)))
- flags |= BindingFlags.IgnoreReturn;
-
- try
- {
- // Invoke the method using InvokeMember().
- ret = InvokeMember(memberName, flags, null, target, aArgs, aParamMod, null, null);
- }
- catch (TargetInvocationException e)
- {
- // For target invocation exceptions, we need to unwrap the inner exception and
- // re-throw it.
- throw e.InnerException;
- }
-
- // Convert each byref argument that is not of the proper type to
- // the parameter type using the OleAutBinder.
- for (int i = 0; i < cArgs; i++)
- {
- if (aParamMod[0][i] && aArgs[i] != null)
- {
- // The parameter is byref.
- Type paramType = aParams[i].ParameterType.GetElementType();
- if (!Object.ReferenceEquals(paramType, aArgs[i].GetType()))
- aArgs[i] = ForwardCallBinder.ChangeType(aArgs[i], paramType, null);
- }
- }
-
- // If the return type is not of the proper type, then convert it
- // to the proper type using the OleAutBinder.
- if (ret != null)
- {
- Type retType = meth.ReturnType;
- if (!Object.ReferenceEquals(retType, ret.GetType()))
- ret = ForwardCallBinder.ChangeType(ret, retType, null);
- }
-
- // Propagate the out parameters
- RealProxy.PropagateOutParameters(reqMsg, aArgs, ret);
-
- // Return the value returned by the InvokeMember call.
- return ret;
- }
-
- [SecuritySafeCritical]
- private void WrapArgsForInvokeCall(Object[] aArgs, int[] aWrapperTypes)
- {
- int cArgs = aArgs.Length;
- for (int i = 0; i < cArgs; i++)
- {
- if (aWrapperTypes[i] == 0)
- continue;
-
- if (((DispatchWrapperType)aWrapperTypes[i] & DispatchWrapperType.SafeArray) != 0)
- {
- Type wrapperType = null;
- bool isString = false;
-
- // Determine the type of wrapper to use.
- switch ((DispatchWrapperType)aWrapperTypes[i] & ~DispatchWrapperType.SafeArray)
- {
- case DispatchWrapperType.Unknown:
- wrapperType = typeof(UnknownWrapper);
- break;
- case DispatchWrapperType.Dispatch:
- wrapperType = typeof(DispatchWrapper);
- break;
- case DispatchWrapperType.Error:
- wrapperType = typeof(ErrorWrapper);
- break;
- case DispatchWrapperType.Currency:
- wrapperType = typeof(CurrencyWrapper);
- break;
- case DispatchWrapperType.BStr:
- wrapperType = typeof(BStrWrapper);
- isString = true;
- break;
- default:
- Contract.Assert(false, "[RuntimeType.WrapArgsForInvokeCall]Invalid safe array wrapper type specified.");
- break;
- }
-
- // Allocate the new array of wrappers.
- Array oldArray = (Array)aArgs[i];
- int numElems = oldArray.Length;
- Object[] newArray = (Object[])Array.UnsafeCreateInstance(wrapperType, numElems);
-
- // Retrieve the ConstructorInfo for the wrapper type.
- ConstructorInfo wrapperCons;
- if(isString)
- {
- wrapperCons = wrapperType.GetConstructor(new Type[] {typeof(String)});
- }
- else
- {
- wrapperCons = wrapperType.GetConstructor(new Type[] {typeof(Object)});
- }
-
- // Wrap each of the elements of the array.
- for (int currElem = 0; currElem < numElems; currElem++)
- {
- if(isString)
- {
- newArray[currElem] = wrapperCons.Invoke(new Object[] {(String)oldArray.GetValue(currElem)});
- }
- else
- {
- newArray[currElem] = wrapperCons.Invoke(new Object[] {oldArray.GetValue(currElem)});
- }
- }
-
- // Update the argument.
- aArgs[i] = newArray;
- }
- else
- {
- // Determine the wrapper to use and then wrap the argument.
- switch ((DispatchWrapperType)aWrapperTypes[i])
- {
- case DispatchWrapperType.Unknown:
- aArgs[i] = new UnknownWrapper(aArgs[i]);
- break;
- case DispatchWrapperType.Dispatch:
- aArgs[i] = new DispatchWrapper(aArgs[i]);
- break;
- case DispatchWrapperType.Error:
- aArgs[i] = new ErrorWrapper(aArgs[i]);
- break;
- case DispatchWrapperType.Currency:
- aArgs[i] = new CurrencyWrapper(aArgs[i]);
- break;
- case DispatchWrapperType.BStr:
- aArgs[i] = new BStrWrapper((String)aArgs[i]);
- break;
- default:
- Contract.Assert(false, "[RuntimeType.WrapArgsForInvokeCall]Invalid wrapper type specified.");
- break;
- }
- }
- }
- }
-
- private OleAutBinder ForwardCallBinder
- {
- get
- {
- // Synchronization is not required.
- if (s_ForwardCallBinder == null)
- s_ForwardCallBinder = new OleAutBinder();
-
- return s_ForwardCallBinder;
- }
- }
-
- [Flags]
- private enum DispatchWrapperType : int
- {
- // This enum must stay in sync with the DispatchWrapperType enum defined in MLInfo.h
- Unknown = 0x00000001,
- Dispatch = 0x00000002,
- Record = 0x00000004,
- Error = 0x00000008,
- Currency = 0x00000010,
- BStr = 0x00000020,
- SafeArray = 0x00010000
- }
-
- private static volatile OleAutBinder s_ForwardCallBinder;
-#endif // FEATURE_COMINTEROP && FEATURE_REMOTING
#endregion
}
#region Library
internal unsafe struct Utf8String
{
- [System.Security.SecurityCritical] // auto-generated
[MethodImplAttribute(MethodImplOptions.InternalCall)]
private static extern unsafe bool EqualsCaseSensitive(void* szLhs, void* szRhs, int cSz);
- [System.Security.SecurityCritical] // auto-generated
[DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
[SuppressUnmanagedCodeSecurity]
private static extern unsafe bool EqualsCaseInsensitive(void* szLhs, void* szRhs, int cSz);
- [System.Security.SecurityCritical] // auto-generated
[DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
[SuppressUnmanagedCodeSecurity]
private static extern unsafe uint HashCaseInsensitive(void* sz, int cSz);
- [System.Security.SecurityCritical] // auto-generated
private static int GetUtf8StringByteLength(void* pUtf8String)
{
int len = 0;
return len;
}
- [SecurityCritical]
private void* m_pStringHeap; // This is the raw UTF8 string.
private int m_StringHeapByteLength;
- [System.Security.SecurityCritical] // auto-generated
internal Utf8String(void* pStringHeap)
{
m_pStringHeap = pStringHeap;
}
}
- [System.Security.SecurityCritical] // auto-generated
internal unsafe Utf8String(void* pUtf8String, int cUtf8String)
{
m_pStringHeap = pUtf8String;
m_StringHeapByteLength = cUtf8String;
}
- [System.Security.SecuritySafeCritical] // auto-generated
internal unsafe bool Equals(Utf8String s)
{
if (m_pStringHeap == null)
return false;
}
- [System.Security.SecuritySafeCritical] // auto-generated
internal unsafe bool EqualsCaseInsensitive(Utf8String s)
{
if (m_pStringHeap == null)
return false;
}
- [System.Security.SecuritySafeCritical] // auto-generated
internal unsafe uint HashCaseInsensitive()
{
return Utf8String.HashCaseInsensitive(m_pStringHeap, m_StringHeapByteLength);
}
- [System.Security.SecuritySafeCritical] // auto-generated
public override string ToString()
{
unsafe
}
else
{
- Contract.Assert(!hit.Equals(key), "Key was already in CerHashtable! Potential race condition (or bug) in the Reflection cache?");
+ Debug.Assert(!hit.Equals(key), "Key was already in CerHashtable! Potential race condition (or bug) in the Reflection cache?");
index++;
if (index >= keys.Length)
/// Provides a builder for asynchronous methods that return void.
/// This type is intended for compiler use only.
/// </summary>
- [HostProtection(Synchronization = true, ExternalThreading = true)]
public struct AsyncVoidMethodBuilder
{
/// <summary>The synchronization context associated with this operation.</summary>
/// <typeparam name="TStateMachine">Specifies the type of the state machine.</typeparam>
/// <param name="stateMachine">The state machine instance, passed by reference.</param>
/// <exception cref="System.ArgumentNullException">The <paramref name="stateMachine"/> argument was null (Nothing in Visual Basic).</exception>
- [SecuritySafeCritical]
[DebuggerStepThrough]
public void Start<TStateMachine>(ref TStateMachine stateMachine) where TStateMachine : IAsyncStateMachine
{
{
AsyncMethodBuilderCore.MoveNextRunner runnerToInitialize = null;
var continuation = m_coreState.GetCompletionAction(AsyncCausalityTracer.LoggingOn ? this.Task : null, ref runnerToInitialize);
- Contract.Assert(continuation != null, "GetCompletionAction should always return a valid action.");
+ Debug.Assert(continuation != null, "GetCompletionAction should always return a valid action.");
// If this is our first await, such that we've not yet boxed the state machine, do so now.
if (m_coreState.m_stateMachine == null)
/// <typeparam name="TStateMachine">Specifies the type of the state machine.</typeparam>
/// <param name="awaiter">The awaiter.</param>
/// <param name="stateMachine">The state machine.</param>
- [SecuritySafeCritical]
public void AwaitUnsafeOnCompleted<TAwaiter, TStateMachine>(
ref TAwaiter awaiter, ref TStateMachine stateMachine)
where TAwaiter : ICriticalNotifyCompletion
{
AsyncMethodBuilderCore.MoveNextRunner runnerToInitialize = null;
var continuation = m_coreState.GetCompletionAction(AsyncCausalityTracer.LoggingOn ? this.Task : null, ref runnerToInitialize);
- Contract.Assert(continuation != null, "GetCompletionAction should always return a valid action.");
+ Debug.Assert(continuation != null, "GetCompletionAction should always return a valid action.");
// If this is our first await, such that we've not yet boxed the state machine, do so now.
if (m_coreState.m_stateMachine == null)
/// <summary>Notifies the current synchronization context that the operation completed.</summary>
private void NotifySynchronizationContextOfCompletion()
{
- Contract.Assert(m_synchronizationContext != null, "Must only be used with a non-null context.");
+ Debug.Assert(m_synchronizationContext != null, "Must only be used with a non-null context.");
try
{
m_synchronizationContext.OperationCompleted();
/// Prior to being copied, one of its Task, SetResult, or SetException members must be accessed,
/// or else the copies may end up building distinct Task instances.
/// </remarks>
- [HostProtection(Synchronization = true, ExternalThreading = true)]
public struct AsyncTaskMethodBuilder
{
/// <summary>A cached VoidTaskResult task used for builders that complete synchronously.</summary>
/// <summary>Initiates the builder's execution with the associated state machine.</summary>
/// <typeparam name="TStateMachine">Specifies the type of the state machine.</typeparam>
/// <param name="stateMachine">The state machine instance, passed by reference.</param>
- [SecuritySafeCritical]
[DebuggerStepThrough]
public void Start<TStateMachine>(ref TStateMachine stateMachine) where TStateMachine : IAsyncStateMachine
{
/// Prior to being copied, one of its Task, SetResult, or SetException members must be accessed,
/// or else the copies may end up building distinct Task instances.
/// </remarks>
- [HostProtection(Synchronization = true, ExternalThreading = true)]
public struct AsyncTaskMethodBuilder<TResult>
{
/// <summary>A cached task for default(TResult).</summary>
/// <summary>Initiates the builder's execution with the associated state machine.</summary>
/// <typeparam name="TStateMachine">Specifies the type of the state machine.</typeparam>
/// <param name="stateMachine">The state machine instance, passed by reference.</param>
- [SecuritySafeCritical]
[DebuggerStepThrough]
public void Start<TStateMachine>(ref TStateMachine stateMachine) where TStateMachine : IAsyncStateMachine
{
{
AsyncMethodBuilderCore.MoveNextRunner runnerToInitialize = null;
var continuation = m_coreState.GetCompletionAction(AsyncCausalityTracer.LoggingOn ? this.Task : null, ref runnerToInitialize);
- Contract.Assert(continuation != null, "GetCompletionAction should always return a valid action.");
+ Debug.Assert(continuation != null, "GetCompletionAction should always return a valid action.");
// If this is our first await, such that we've not yet boxed the state machine, do so now.
if (m_coreState.m_stateMachine == null)
/// <typeparam name="TStateMachine">Specifies the type of the state machine.</typeparam>
/// <param name="awaiter">The awaiter.</param>
/// <param name="stateMachine">The state machine.</param>
- [SecuritySafeCritical]
public void AwaitUnsafeOnCompleted<TAwaiter, TStateMachine>(
ref TAwaiter awaiter, ref TStateMachine stateMachine)
where TAwaiter : ICriticalNotifyCompletion
{
AsyncMethodBuilderCore.MoveNextRunner runnerToInitialize = null;
var continuation = m_coreState.GetCompletionAction(AsyncCausalityTracer.LoggingOn ? this.Task : null, ref runnerToInitialize);
- Contract.Assert(continuation != null, "GetCompletionAction should always return a valid action.");
+ Debug.Assert(continuation != null, "GetCompletionAction should always return a valid action.");
// If this is our first await, such that we've not yet boxed the state machine, do so now.
if (m_coreState.m_stateMachine == null)
if (task == null)
{
m_task = GetTaskForResult(result);
- Contract.Assert(m_task != null, "GetTaskForResult should never return null");
+ Debug.Assert(m_task != null, "GetTaskForResult should never return null");
}
// Slow path: complete the existing task.
else
/// </summary>
/// <param name="result">The result for which we need a task.</param>
/// <returns>The completed task containing the result.</returns>
- [SecuritySafeCritical] // for JitHelpers.UnsafeCast
private Task<TResult> GetTaskForResult(TResult result)
{
Contract.Ensures(
/// <summary>Creates an array of cached tasks for the values in the range [INCLUSIVE_MIN,EXCLUSIVE_MAX).</summary>
private static Task<Int32>[] CreateInt32Tasks()
{
- Contract.Assert(EXCLUSIVE_INT32_MAX >= INCLUSIVE_INT32_MIN, "Expected max to be at least min");
+ Debug.Assert(EXCLUSIVE_INT32_MAX >= INCLUSIVE_INT32_MIN, "Expected max to be at least min");
var tasks = new Task<Int32>[EXCLUSIVE_INT32_MAX - INCLUSIVE_INT32_MIN];
for (int i = 0; i < tasks.Length; i++)
{
/// <typeparam name="TStateMachine">Specifies the type of the state machine.</typeparam>
/// <param name="stateMachine">The state machine instance, passed by reference.</param>
/// <exception cref="System.ArgumentNullException">The <paramref name="stateMachine"/> argument is null (Nothing in Visual Basic).</exception>
- [SecuritySafeCritical]
[DebuggerStepThrough]
internal static void Start<TStateMachine>(ref TStateMachine stateMachine)
where TStateMachine : IAsyncStateMachine
/// <param name="builder">The builder.</param>
/// <param name="stateMachine">The state machine.</param>
/// <returns>An Action to provide to the awaiter.</returns>
- [SecuritySafeCritical]
internal Action GetCompletionAction(Task taskForTracing, ref MoveNextRunner runnerToInitialize)
{
- Contract.Assert(m_defaultContextAction == null || m_stateMachine != null,
+ Debug.Assert(m_defaultContextAction == null || m_stateMachine != null,
"Expected non-null m_stateMachine on non-null m_defaultContextAction");
// Alert a listening debugger that we can't make forward progress unless it slips threads.
action = m_defaultContextAction;
if (action != null)
{
- Contract.Assert(m_stateMachine != null, "If the delegate was set, the state machine should have been as well.");
+ Debug.Assert(m_stateMachine != null, "If the delegate was set, the state machine should have been as well.");
return action;
}
m_stateMachine = stateMachine;
m_stateMachine.SetStateMachine(m_stateMachine);
- Contract.Assert(runner.m_stateMachine == null, "The runner's state machine should not yet have been populated.");
- Contract.Assert(m_stateMachine != null, "The builder's state machine field should have been initialized.");
+ Debug.Assert(runner.m_stateMachine == null, "The runner's state machine should not yet have been populated.");
+ Debug.Assert(m_stateMachine != null, "The builder's state machine field should have been initialized.");
// Now that we have the state machine, store it into the runner that the action delegate points to.
// And return the action.
/// <summary>Initializes the runner.</summary>
/// <param name="context">The context with which to run MoveNext.</param>
- [SecurityCritical] // Run needs to be SSC to map to Action delegate, so to prevent misuse, we only allow construction through SC
internal MoveNextRunnerWithContext(ExecutionContext context, IAsyncStateMachine stateMachine) : base(stateMachine)
{
m_context = context;
}
/// <summary>Invokes MoveNext under the provided context.</summary>
- [SecuritySafeCritical]
internal void RunWithCapturedContext()
{
- Contract.Assert(m_stateMachine != null, "The state machine must have been set before calling Run.");
+ Debug.Assert(m_stateMachine != null, "The state machine must have been set before calling Run.");
if (m_context != null)
{
internal IAsyncStateMachine m_stateMachine;
/// <summary>Initializes the runner.</summary>
- [SecurityCritical] // Run needs to be SSC to map to Action delegate, so to prevent misuse, we only allow construction through SC
internal MoveNextRunner(IAsyncStateMachine stateMachine)
{
m_stateMachine = stateMachine;
}
/// <summary>Invokes MoveNext under the default context.</summary>
- [SecuritySafeCritical]
internal void RunWithDefaultContext()
{
- Contract.Assert(m_stateMachine != null, "The state machine must have been set before calling Run.");
+ Debug.Assert(m_stateMachine != null, "The state machine must have been set before calling Run.");
ExecutionContext.Run(ExecutionContext.PreAllocatedDefault, InvokeMoveNextCallback, m_stateMachine, preserveSyncCtx: true);
}
/// <summary>Gets a delegate to the InvokeMoveNext method.</summary>
protected static ContextCallback InvokeMoveNextCallback
{
- [SecuritySafeCritical]
get { return s_invokeMoveNext ?? (s_invokeMoveNext = InvokeMoveNext); }
}
/// <summary>Cached delegate used with ExecutionContext.Run.</summary>
- [SecurityCritical]
private static ContextCallback s_invokeMoveNext; // lazily-initialized due to SecurityCritical attribution
/// <summary>Invokes the MoveNext method on the supplied IAsyncStateMachine.</summary>
/// <param name="stateMachine">The IAsyncStateMachine machine instance.</param>
- [SecurityCritical] // necessary for ContextCallback in CoreCLR
private static void InvokeMoveNext(object stateMachine)
{
((IAsyncStateMachine)stateMachine).MoveNext();
** may be delayed until appdomain shutdown.
===========================================================*/
+using System.Collections.Generic;
+using System.Runtime.InteropServices;
+using System.Threading;
+
namespace System.Runtime.CompilerServices
{
- using System;
- using System.Collections.Generic;
- using System.Runtime.Versioning;
- using System.Runtime.InteropServices;
-
-
#region ConditionalWeakTable
- [System.Runtime.InteropServices.ComVisible(false)]
+ [ComVisible(false)]
public sealed class ConditionalWeakTable<TKey, TValue>
where TKey : class
where TValue : class
{
+ #region Fields
+ private const int InitialCapacity = 8; // Initial length of the table. Must be a power of two.
+ private readonly object _lock; // This lock protects all mutation of data in the table. Readers do not take this lock.
+ private volatile Container _container; // The actual storage for the table; swapped out as the table grows.
+ #endregion
#region Constructors
- [System.Security.SecuritySafeCritical]
public ConditionalWeakTable()
{
- _buckets = Array.Empty<int>();
- _entries = Array.Empty<Entry>();
- _freeList = -1;
- _lock = new Object();
-
- Resize(); // Resize at once (so won't need "if initialized" checks all over)
+ _lock = new object();
+ _container = new Container(this);
}
#endregion
// Note: The key may get garbaged collected during the TryGetValue operation. If so, TryGetValue
// may at its discretion, return "false" and set "value" to the default (as if the key was not present.)
//--------------------------------------------------------------------------------------------
- [System.Security.SecuritySafeCritical]
public bool TryGetValue(TKey key, out TValue value)
{
if (key == null)
{
ThrowHelper.ThrowArgumentNullException(ExceptionArgument.key);
}
- lock(_lock)
- {
- VerifyIntegrity();
- return TryGetValueWorker(key, out value);
- }
+
+ return _container.TryGetValueWorker(key, out value);
}
//--------------------------------------------------------------------------------------------
// has the right to consider any prior entries successfully removed and add a new entry without
// throwing an exception.
//--------------------------------------------------------------------------------------------
- [System.Security.SecuritySafeCritical]
public void Add(TKey key, TValue value)
{
if (key == null)
ThrowHelper.ThrowArgumentNullException(ExceptionArgument.key);
}
- lock(_lock)
+ lock (_lock)
{
- VerifyIntegrity();
- _invalid = true;
-
- int entryIndex = FindEntry(key);
+ object otherValue;
+ int entryIndex = _container.FindEntry(key, out otherValue);
if (entryIndex != -1)
{
- _invalid = false;
ThrowHelper.ThrowArgumentException(ExceptionResource.Argument_AddingDuplicate);
}
CreateEntry(key, value);
- _invalid = false;
}
+ }
+
+ //--------------------------------------------------------------------------------------------
+ // key: key to add or update. May not be null.
+ // value: value to associate with key.
+ //
+ // If the key is already entered into the dictionary, this method will update the value associated with key.
+ //--------------------------------------------------------------------------------------------
+ public void AddOrUpdate(TKey key, TValue value)
+ {
+ if (key == null)
+ {
+ ThrowHelper.ThrowArgumentNullException(ExceptionArgument.key);
+ }
+
+ lock (_lock)
+ {
+ object otherValue;
+ int entryIndex = _container.FindEntry(key, out otherValue);
+
+ // if we found a key we should just update, if no we should create a new entry.
+ if (entryIndex != -1)
+ {
+ _container.UpdateValue(entryIndex, value);
+ }
+ else
+ {
+ CreateEntry(key, value);
+ }
+ }
}
//--------------------------------------------------------------------------------------------
//
// Note: The key may get garbage collected during the Remove() operation. If so,
// Remove() will not fail or throw, however, the return value can be either true or false
- // depending on the race condition.
+ // depending on who wins the race.
//--------------------------------------------------------------------------------------------
- [System.Security.SecuritySafeCritical]
public bool Remove(TKey key)
{
if (key == null)
ThrowHelper.ThrowArgumentNullException(ExceptionArgument.key);
}
- lock(_lock)
+ lock (_lock)
{
- VerifyIntegrity();
- _invalid = true;
-
- int hashCode = RuntimeHelpers.GetHashCode(key) & Int32.MaxValue;
- int bucket = hashCode % _buckets.Length;
- int last = -1;
- for (int entriesIndex = _buckets[bucket]; entriesIndex != -1; entriesIndex = _entries[entriesIndex].next)
- {
- if (_entries[entriesIndex].hashCode == hashCode && _entries[entriesIndex].depHnd.GetPrimary() == key)
- {
- if (last == -1)
- {
- _buckets[bucket] = _entries[entriesIndex].next;
- }
- else
- {
- _entries[last].next = _entries[entriesIndex].next;
- }
-
- _entries[entriesIndex].depHnd.Free();
- _entries[entriesIndex].next = _freeList;
-
- _freeList = entriesIndex;
-
- _invalid = false;
- return true;
-
- }
- last = entriesIndex;
- }
- _invalid = false;
- return false;
+ return _container.Remove(key);
}
}
// This rule permits the table to invoke createValueCallback outside the internal table lock
// to prevent deadlocks.
//--------------------------------------------------------------------------------------------
- [System.Security.SecuritySafeCritical]
public TValue GetValue(TKey key, CreateValueCallback createValueCallback)
{
- // Our call to TryGetValue() validates key so no need for us to.
- //
- // if (key == null)
- // {
- // ThrowHelper.ThrowArgumentNullException(ExceptionArgument.key);
- // }
+ // key is validated by TryGetValue
if (createValueCallback == null)
{
}
TValue existingValue;
- if (TryGetValue(key, out existingValue))
- {
- return existingValue;
- }
+ return TryGetValue(key, out existingValue) ?
+ existingValue :
+ GetValueLocked(key, createValueCallback);
+ }
- // If we got here, the key is not currently in table. Invoke the callback (outside the lock)
+ private TValue GetValueLocked(TKey key, CreateValueCallback createValueCallback)
+ {
+ // If we got here, the key was not in the table. Invoke the callback (outside the lock)
// to generate the new value for the key.
TValue newValue = createValueCallback(key);
- lock(_lock)
+ lock (_lock)
{
- VerifyIntegrity();
- _invalid = true;
-
- // Now that we've retaken the lock, must recheck in case there was a race condition to add the key.
- if (TryGetValueWorker(key, out existingValue))
+ // Now that we've taken the lock, must recheck in case we lost a race to add the key.
+ TValue existingValue;
+ if (_container.TryGetValueWorker(key, out existingValue))
{
- _invalid = false;
return existingValue;
}
else
{
+ // Verified in-lock that we won the race to add the key. Add it now.
CreateEntry(key, newValue);
- _invalid = false;
return newValue;
}
}
// to create new instances as needed. If TValue does not have a default constructor, this will
// throw.
//--------------------------------------------------------------------------------------------
- public TValue GetOrCreateValue(TKey key)
- {
- return GetValue(key, k => Activator.CreateInstance<TValue>());
- }
+
+ public TValue GetOrCreateValue(TKey key) => GetValue(key, _ => Activator.CreateInstance<TValue>());
public delegate TValue CreateValueCallback(TKey key);
-
+
#endregion
- #region internal members
-
+ #region Internal members
+
//--------------------------------------------------------------------------------------------
// Find a key that equals (value equality) with the given key - don't use in perf critical path
// Note that it calls out to Object.Equals which may calls the override version of Equals
// if you know for sure that either you won't run into dead locks or you need to live with the
// possiblity
//--------------------------------------------------------------------------------------------
- [System.Security.SecuritySafeCritical]
[FriendAccessAllowed]
internal TKey FindEquivalentKeyUnsafe(TKey key, out TValue value)
{
lock (_lock)
{
- for (int bucket = 0; bucket < _buckets.Length; ++bucket)
- {
- for (int entriesIndex = _buckets[bucket]; entriesIndex != -1; entriesIndex = _entries[entriesIndex].next)
- {
- object thisKey, thisValue;
- _entries[entriesIndex].depHnd.GetPrimaryAndSecondary(out thisKey, out thisValue);
- if (Object.Equals(thisKey, key))
- {
- value = (TValue) thisValue;
- return (TKey) thisKey;
- }
- }
- }
+ return _container.FindEquivalentKeyUnsafe(key, out value);
}
-
- value = default(TValue);
- return null;
}
-
+
//--------------------------------------------------------------------------------------------
// Returns a collection of keys - don't use in perf critical path
//--------------------------------------------------------------------------------------------
internal ICollection<TKey> Keys
{
- [System.Security.SecuritySafeCritical]
get
{
- List<TKey> list = new List<TKey>();
lock (_lock)
{
- for (int bucket = 0; bucket < _buckets.Length; ++bucket)
- {
- for (int entriesIndex = _buckets[bucket]; entriesIndex != -1; entriesIndex = _entries[entriesIndex].next)
- {
- TKey thisKey = (TKey) _entries[entriesIndex].depHnd.GetPrimary();
- if (thisKey != null)
- {
- list.Add(thisKey);
- }
- }
- }
+ return _container.Keys;
}
-
- return list;
}
}
//--------------------------------------------------------------------------------------------
internal ICollection<TValue> Values
{
- [System.Security.SecuritySafeCritical]
get
{
- List<TValue> list = new List<TValue>();
lock (_lock)
{
- for (int bucket = 0; bucket < _buckets.Length; ++bucket)
- {
- for (int entriesIndex = _buckets[bucket]; entriesIndex != -1; entriesIndex = _entries[entriesIndex].next)
- {
- Object primary = null;
- Object secondary = null;
-
- _entries[entriesIndex].depHnd.GetPrimaryAndSecondary(out primary, out secondary);
-
- // Now that we've secured a strong reference to the secondary, must check the primary again
- // to ensure it didn't expire (otherwise, we open a race condition where TryGetValue misreports an
- // expired key as a live key with a null value.)
- if (primary != null)
- {
- list.Add((TValue)secondary);
- }
- }
- }
+ return _container.Values;
}
-
- return list;
}
}
-
+
//--------------------------------------------------------------------------------------------
// Clear all the key/value pairs
//--------------------------------------------------------------------------------------------
- [System.Security.SecuritySafeCritical]
internal void Clear()
{
lock (_lock)
{
- // Clear the buckets
- for (int bucketIndex = 0; bucketIndex < _buckets.Length; bucketIndex++)
- {
- _buckets[bucketIndex] = -1;
- }
-
- // Clear the entries and link them backwards together as part of free list
- int entriesIndex;
- for (entriesIndex = 0; entriesIndex < _entries.Length; entriesIndex++)
- {
- if (_entries[entriesIndex].depHnd.IsAllocated)
- {
- _entries[entriesIndex].depHnd.Free();
- }
-
- // Link back wards as free list
- _entries[entriesIndex].next = entriesIndex - 1;
- }
-
- _freeList = entriesIndex - 1;
- }
+ _container = new Container(this);
+ }
}
#endregion
-
+
#region Private Members
- [System.Security.SecurityCritical]
+
//----------------------------------------------------------------------------------------
- // Worker for finding a key/value pair
+ // Worker for adding a new key/value pair.
+ // Will resize the container if it is full
//
// Preconditions:
// Must hold _lock.
- // Key already validated as non-null
+ // Key already validated as non-null and not already in table.
//----------------------------------------------------------------------------------------
- private bool TryGetValueWorker(TKey key, out TValue value)
+ private void CreateEntry(TKey key, TValue value)
{
- int entryIndex = FindEntry(key);
- if (entryIndex != -1)
+ Debug.Assert(Monitor.IsEntered(_lock));
+
+ Container c = _container;
+ if (!c.HasCapacity)
{
- Object primary = null;
- Object secondary = null;
- _entries[entryIndex].depHnd.GetPrimaryAndSecondary(out primary, out secondary);
- // Now that we've secured a strong reference to the secondary, must check the primary again
- // to ensure it didn't expire (otherwise, we open a race condition where TryGetValue misreports an
- // expired key as a live key with a null value.)
- if (primary != null)
- {
- value = (TValue)secondary;
- return true;
- }
+ _container = c = c.Resize();
}
+ c.CreateEntryNoResize(key, value);
+ }
+
+ private static bool IsPowerOfTwo(int value) => (value > 0) && ((value & (value - 1)) == 0);
- value = default(TValue);
- return false;
+ #endregion
+
+ #region Private Data Members
+ //--------------------------------------------------------------------------------------------
+ // Entry can be in one of four states:
+ //
+ // - Unused (stored with an index _firstFreeEntry and above)
+ // depHnd.IsAllocated == false
+ // hashCode == <dontcare>
+ // next == <dontcare>)
+ //
+ // - Used with live key (linked into a bucket list where _buckets[hashCode & (_buckets.Length - 1)] points to first entry)
+ // depHnd.IsAllocated == true, depHnd.GetPrimary() != null
+ // hashCode == RuntimeHelpers.GetHashCode(depHnd.GetPrimary()) & Int32.MaxValue
+ // next links to next Entry in bucket.
+ //
+ // - Used with dead key (linked into a bucket list where _buckets[hashCode & (_buckets.Length - 1)] points to first entry)
+ // depHnd.IsAllocated == true, depHnd.GetPrimary() == null
+ // hashCode == <notcare>
+ // next links to next Entry in bucket.
+ //
+ // - Has been removed from the table (by a call to Remove)
+ // depHnd.IsAllocated == true, depHnd.GetPrimary() == <notcare>
+ // hashCode == -1
+ // next links to next Entry in bucket.
+ //
+ // The only difference between "used with live key" and "used with dead key" is that
+ // depHnd.GetPrimary() returns null. The transition from "used with live key" to "used with dead key"
+ // happens asynchronously as a result of normal garbage collection. The dictionary itself
+ // receives no notification when this happens.
+ //
+ // When the dictionary grows the _entries table, it scours it for expired keys and does not
+ // add those to the new container.
+ //--------------------------------------------------------------------------------------------
+ private struct Entry
+ {
+ public DependentHandle depHnd; // Holds key and value using a weak reference for the key and a strong reference
+ // for the value that is traversed only if the key is reachable without going through the value.
+ public int HashCode; // Cached copy of key's hashcode
+ public int Next; // Index of next entry, -1 if last
}
- //----------------------------------------------------------------------------------------
- // Worker for adding a new key/value pair.
//
- // Preconditions:
- // Must hold _lock.
- // Key already validated as non-null and not already in table.
- //----------------------------------------------------------------------------------------
- [System.Security.SecurityCritical]
- private void CreateEntry(TKey key, TValue value)
+ // Container holds the actual data for the table. A given instance of Container always has the same capacity. When we need
+ // more capacity, we create a new Container, copy the old one into the new one, and discard the old one. This helps enable lock-free
+ // reads from the table, as readers never need to deal with motion of entries due to rehashing.
+ //
+ private sealed class Container
{
- if (_freeList == -1)
+ private readonly ConditionalWeakTable<TKey, TValue> _parent; // the ConditionalWeakTable with which this container is associated
+ private int[] _buckets; // _buckets[hashcode & (_buckets.Length - 1)] contains index of the first entry in bucket (-1 if empty)
+ private Entry[] _entries; // the table entries containing the stored dependency handles
+ private int _firstFreeEntry; // _firstFreeEntry < _entries.Length => table has capacity, entries grow from the bottom of the table.
+ private bool _invalid; // flag detects if OOM or other background exception threw us out of the lock.
+ private bool _finalized; // set to true when initially finalized
+ private volatile object _oldKeepAlive; // used to ensure the next allocated container isn't finalized until this one is GC'd
+
+ internal Container(ConditionalWeakTable<TKey, TValue> parent)
{
- Resize();
+ Debug.Assert(parent != null);
+ Debug.Assert(IsPowerOfTwo(InitialCapacity));
+
+ int size = InitialCapacity;
+ _buckets = new int[size];
+ for (int i = 0; i < _buckets.Length; i++)
+ {
+ _buckets[i] = -1;
+ }
+ _entries = new Entry[size];
+
+ // Only store the parent after all of the allocations have happened successfully.
+ // Otherwise, as part of growing or clearing the container, we could end up allocating
+ // a new Container that fails (OOMs) part way through construction but that gets finalized
+ // and ends up clearing out some other container present in the associated CWT.
+ _parent = parent;
}
- int hashCode = RuntimeHelpers.GetHashCode(key) & Int32.MaxValue;
- int bucket = hashCode % _buckets.Length;
+ private Container(ConditionalWeakTable<TKey, TValue> parent, int[] buckets, Entry[] entries, int firstFreeEntry)
+ {
+ Debug.Assert(parent != null);
+ Debug.Assert(buckets != null);
+ Debug.Assert(entries != null);
+ Debug.Assert(buckets.Length == entries.Length);
+ Debug.Assert(IsPowerOfTwo(buckets.Length));
+
+ _parent = parent;
+ _buckets = buckets;
+ _entries = entries;
+ _firstFreeEntry = firstFreeEntry;
+ }
- int newEntry = _freeList;
- _freeList = _entries[newEntry].next;
+ internal bool HasCapacity => _firstFreeEntry < _entries.Length;
- _entries[newEntry].hashCode = hashCode;
- _entries[newEntry].depHnd = new DependentHandle(key, value);
- _entries[newEntry].next = _buckets[bucket];
+ //----------------------------------------------------------------------------------------
+ // Worker for adding a new key/value pair.
+ // Preconditions:
+ // Container must NOT be full
+ //----------------------------------------------------------------------------------------
+ internal void CreateEntryNoResize(TKey key, TValue value)
+ {
+ Debug.Assert(HasCapacity);
- _buckets[bucket] = newEntry;
+ VerifyIntegrity();
+ _invalid = true;
- }
+ int hashCode = RuntimeHelpers.GetHashCode(key) & int.MaxValue;
+ int newEntry = _firstFreeEntry++;
- //----------------------------------------------------------------------------------------
- // This does two things: resize and scrub expired keys off bucket lists.
- //
- // Precondition:
- // Must hold _lock.
- //
- // Postcondition:
- // _freeList is non-empty on exit.
- //----------------------------------------------------------------------------------------
- [System.Security.SecurityCritical]
- private void Resize()
- {
- // Start by assuming we won't resize.
- int newSize = _buckets.Length;
+ _entries[newEntry].HashCode = hashCode;
+ _entries[newEntry].depHnd = new DependentHandle(key, value);
+ int bucket = hashCode & (_buckets.Length - 1);
+ _entries[newEntry].Next = _buckets[bucket];
+
+ // This write must be volatile, as we may be racing with concurrent readers. If they see
+ // the new entry, they must also see all of the writes earlier in this method.
+ Volatile.Write(ref _buckets[bucket], newEntry);
+
+ _invalid = false;
+ }
- // If any expired keys exist, we won't resize.
- bool hasExpiredEntries = false;
- int entriesIndex;
- for (entriesIndex = 0; entriesIndex < _entries.Length; entriesIndex++)
+ //----------------------------------------------------------------------------------------
+ // Worker for finding a key/value pair
+ //
+ // Preconditions:
+ // Must hold _lock.
+ // Key already validated as non-null
+ //----------------------------------------------------------------------------------------
+ internal bool TryGetValueWorker(TKey key, out TValue value)
{
- if ( _entries[entriesIndex].depHnd.IsAllocated && _entries[entriesIndex].depHnd.GetPrimary() == null)
+ object secondary;
+ int entryIndex = FindEntry(key, out secondary);
+ value = JitHelpers.UnsafeCast<TValue>(secondary);
+ return entryIndex != -1;
+ }
+
+ //----------------------------------------------------------------------------------------
+ // Returns -1 if not found (if key expires during FindEntry, this can be treated as "not found.")
+ //
+ // Preconditions:
+ // Must hold _lock, or be prepared to retry the search while holding _lock.
+ // Key already validated as non-null.
+ //----------------------------------------------------------------------------------------
+ internal int FindEntry(TKey key, out object value)
+ {
+ int hashCode = RuntimeHelpers.GetHashCode(key) & int.MaxValue;
+ int bucket = hashCode & (_buckets.Length - 1);
+ for (int entriesIndex = Volatile.Read(ref _buckets[bucket]); entriesIndex != -1; entriesIndex = _entries[entriesIndex].Next)
{
- hasExpiredEntries = true;
- break;
+ if (_entries[entriesIndex].HashCode == hashCode)
+ {
+ object primary, secondary;
+ _entries[entriesIndex].depHnd.GetPrimaryAndSecondary(out primary, out secondary);
+ if (primary == key)
+ {
+ GC.KeepAlive(this); // ensure we don't get finalized while accessing DependentHandles.
+ value = secondary;
+ return entriesIndex;
+ }
+ }
}
+
+ GC.KeepAlive(this); // ensure we don't get finalized while accessing DependentHandles.
+ value = null;
+ return -1;
}
- if (!hasExpiredEntries)
+ internal bool Remove(TKey key)
{
- newSize = System.Collections.HashHelpers.GetPrime(_buckets.Length == 0 ? _initialCapacity + 1 : _buckets.Length * 2);
+ VerifyIntegrity();
+
+ object value;
+ int entryIndex = FindEntry(key, out value);
+ if (entryIndex != -1)
+ {
+ ref Entry entry = ref _entries[entryIndex];
+
+ // We do not free the handle here, as we may be racing with readers who already saw the hash code.
+ // Instead, we simply overwrite the entry's hash code, so subsequent reads will ignore it.
+ // The handle will be free'd in Container's finalizer, after the table is resized or discarded.
+ Volatile.Write(ref entry.HashCode, -1);
+
+ // Also, clear the key to allow GC to collect objects pointed to by the entry
+ entry.depHnd.SetPrimary(null);
+
+ return true;
+ }
+
+ return false;
}
- // Reallocate both buckets and entries and rebuild the bucket and freelists from scratch.
- // This serves both to scrub entries with expired keys and to put the new entries in the proper bucket.
- int newFreeList = -1;
- int[] newBuckets = new int[newSize];
- for (int bucketIndex = 0; bucketIndex < newSize; bucketIndex++)
+ internal void UpdateValue(int entryIndex, TValue newValue)
{
- newBuckets[bucketIndex] = -1;
+ Debug.Assert(entryIndex != -1);
+
+ VerifyIntegrity();
+ _invalid = true;
+
+ _entries[entryIndex].depHnd.SetSecondary(newValue);
+
+ _invalid = false;
}
- Entry[] newEntries = new Entry[newSize];
- // Migrate existing entries to the new table.
- for (entriesIndex = 0; entriesIndex < _entries.Length; entriesIndex++)
+ //----------------------------------------------------------------------------------------
+ // This does two things: resize and scrub expired keys off bucket lists.
+ //
+ // Precondition:
+ // Must hold _lock.
+ //
+ // Postcondition:
+ // _firstEntry is less than _entries.Length on exit, that is, the table has at least one free entry.
+ //----------------------------------------------------------------------------------------
+ internal Container Resize()
{
- DependentHandle depHnd = _entries[entriesIndex].depHnd;
- if (depHnd.IsAllocated && depHnd.GetPrimary() != null)
+ // Start by assuming we won't resize.
+ int newSize = _buckets.Length;
+
+ // If any expired or removed keys exist, we won't resize.
+ bool hasExpiredEntries = false;
+ for (int entriesIndex = 0; entriesIndex < _entries.Length; entriesIndex++)
{
- // Entry is used and has not expired. Link it into the appropriate bucket list.
- int bucket = _entries[entriesIndex].hashCode % newSize;
- newEntries[entriesIndex].depHnd = depHnd;
- newEntries[entriesIndex].hashCode = _entries[entriesIndex].hashCode;
- newEntries[entriesIndex].next = newBuckets[bucket];
- newBuckets[bucket] = entriesIndex;
+ if (_entries[entriesIndex].HashCode == -1)
+ {
+ // the entry was removed
+ hasExpiredEntries = true;
+ break;
+ }
+
+ if (_entries[entriesIndex].depHnd.IsAllocated && _entries[entriesIndex].depHnd.GetPrimary() == null)
+ {
+ // the entry has expired
+ hasExpiredEntries = true;
+ break;
+ }
}
- else
+
+ if (!hasExpiredEntries)
{
- // Entry has either expired or was on the freelist to begin with. Either way
- // insert it on the new freelist.
- _entries[entriesIndex].depHnd.Free();
- newEntries[entriesIndex].depHnd = new DependentHandle();
- newEntries[entriesIndex].next = newFreeList;
- newFreeList = entriesIndex;
+ // Not necessary to check for overflow here, the attempt to allocate new arrays will throw
+ newSize = _buckets.Length * 2;
}
+
+ return Resize(newSize);
}
- // Add remaining entries to freelist.
- while (entriesIndex != newEntries.Length)
+ internal Container Resize(int newSize)
{
- newEntries[entriesIndex].depHnd = new DependentHandle();
- newEntries[entriesIndex].next = newFreeList;
- newFreeList = entriesIndex;
- entriesIndex++;
- }
+ Debug.Assert(IsPowerOfTwo(newSize));
- _buckets = newBuckets;
- _entries = newEntries;
- _freeList = newFreeList;
- }
+ // Reallocate both buckets and entries and rebuild the bucket and entries from scratch.
+ // This serves both to scrub entries with expired keys and to put the new entries in the proper bucket.
+ int[] newBuckets = new int[newSize];
+ for (int bucketIndex = 0; bucketIndex < newSize; bucketIndex++)
+ {
+ newBuckets[bucketIndex] = -1;
+ }
+ Entry[] newEntries = new Entry[newSize];
+ int newEntriesIndex = 0;
- //----------------------------------------------------------------------------------------
- // Returns -1 if not found (if key expires during FindEntry, this can be treated as "not found.")
- //
- // Preconditions:
- // Must hold _lock.
- // Key already validated as non-null.
- //----------------------------------------------------------------------------------------
- [System.Security.SecurityCritical]
- private int FindEntry(TKey key)
- {
- int hashCode = RuntimeHelpers.GetHashCode(key) & Int32.MaxValue;
- for (int entriesIndex = _buckets[hashCode % _buckets.Length]; entriesIndex != -1; entriesIndex = _entries[entriesIndex].next)
+ // Migrate existing entries to the new table.
+ for (int entriesIndex = 0; entriesIndex < _entries.Length; entriesIndex++)
+ {
+ int hashCode = _entries[entriesIndex].HashCode;
+ DependentHandle depHnd = _entries[entriesIndex].depHnd;
+ if (hashCode != -1 && depHnd.IsAllocated)
+ {
+ if (depHnd.GetPrimary() != null)
+ {
+ // Entry is used and has not expired. Link it into the appropriate bucket list.
+ newEntries[newEntriesIndex].HashCode = hashCode;
+ newEntries[newEntriesIndex].depHnd = depHnd;
+ int bucket = hashCode & (newBuckets.Length - 1);
+ newEntries[newEntriesIndex].Next = newBuckets[bucket];
+ newBuckets[bucket] = newEntriesIndex;
+ newEntriesIndex++;
+ }
+ else
+ {
+ // Pretend the item was removed, so that this container's finalizer
+ // will clean up this dependent handle.
+ Volatile.Write(ref _entries[entriesIndex].HashCode, -1);
+ }
+ }
+ }
+
+ // Create the new container. We want to transfer the responsibility of freeing the handles from
+ // the old container to the new container, and also ensure that the new container isn't finalized
+ // while the old container may still be in use. As such, we store a reference from the old container
+ // to the new one, which will keep the new container alive as long as the old one is.
+ var newContainer = new Container(_parent, newBuckets, newEntries, newEntriesIndex);
+ _oldKeepAlive = newContainer; // once this is set, the old container's finalizer will not free transferred dependent handles
+
+ GC.KeepAlive(this); // ensure we don't get finalized while accessing DependentHandles.
+
+ return newContainer;
+ }
+
+ internal ICollection<TKey> Keys
{
- if (_entries[entriesIndex].hashCode == hashCode && _entries[entriesIndex].depHnd.GetPrimary() == key)
+ get
{
- return entriesIndex;
+ var list = new List<TKey>();
+
+ for (int bucket = 0; bucket < _buckets.Length; ++bucket)
+ {
+ for (int entriesIndex = _buckets[bucket]; entriesIndex != -1; entriesIndex = _entries[entriesIndex].Next)
+ {
+ TKey thisKey = JitHelpers.UnsafeCast<TKey>(_entries[entriesIndex].depHnd.GetPrimary());
+ if (thisKey != null)
+ {
+ list.Add(thisKey);
+ }
+ }
+ }
+
+ GC.KeepAlive(this); // ensure we don't get finalized while accessing DependentHandles.
+ return list;
}
}
- return -1;
- }
- //----------------------------------------------------------------------------------------
- // Precondition:
- // Must hold _lock.
- //----------------------------------------------------------------------------------------
- private void VerifyIntegrity()
- {
- if (_invalid)
+ internal ICollection<TValue> Values
{
- throw new InvalidOperationException(Environment.GetResourceString("CollectionCorrupted"));
+ get
+ {
+ var list = new List<TValue>();
+
+ for (int bucket = 0; bucket < _buckets.Length; ++bucket)
+ {
+ for (int entriesIndex = _buckets[bucket]; entriesIndex != -1; entriesIndex = _entries[entriesIndex].Next)
+ {
+ object primary = null, secondary = null;
+ _entries[entriesIndex].depHnd.GetPrimaryAndSecondary(out primary, out secondary);
+
+ // Now that we've secured a strong reference to the secondary, must check the primary again
+ // to ensure it didn't expire (otherwise, we open a race where TryGetValue misreports an
+ // expired key as a live key with a null value.)
+ if (primary != null)
+ {
+ list.Add(JitHelpers.UnsafeCast<TValue>(secondary));
+ }
+ }
+ }
+
+ GC.KeepAlive(this); // ensure we don't get finalized while accessing DependentHandles.
+ return list;
+ }
}
- }
- //----------------------------------------------------------------------------------------
- // Finalizer.
- //----------------------------------------------------------------------------------------
- [System.Security.SecuritySafeCritical]
- ~ConditionalWeakTable()
- {
+ internal TKey FindEquivalentKeyUnsafe(TKey key, out TValue value)
+ {
+ for (int bucket = 0; bucket < _buckets.Length; ++bucket)
+ {
+ for (int entriesIndex = _buckets[bucket]; entriesIndex != -1; entriesIndex = _entries[entriesIndex].Next)
+ {
+ if (_entries[entriesIndex].HashCode == -1)
+ {
+ continue; // removed entry whose handle is awaiting condemnation by the finalizer.
+ }
- // We're just freeing per-appdomain unmanaged handles here. If we're already shutting down the AD,
- // don't bother.
- //
- // (Despite its name, Environment.HasShutdownStart also returns true if the current AD is finalizing.)
- if (Environment.HasShutdownStarted)
+ object thisKey, thisValue;
+ _entries[entriesIndex].depHnd.GetPrimaryAndSecondary(out thisKey, out thisValue);
+ if (Equals(thisKey, key))
+ {
+ GC.KeepAlive(this); // ensure we don't get finalized while accessing DependentHandles.
+ value = JitHelpers.UnsafeCast<TValue>(thisValue);
+ return JitHelpers.UnsafeCast<TKey>(thisKey);
+ }
+ }
+ }
+
+ GC.KeepAlive(this); // ensure we don't get finalized while accessing DependentHandles.
+ value = default(TValue);
+ return null;
+ }
+
+ //----------------------------------------------------------------------------------------
+ // Precondition:
+ // Must hold _lock.
+ //----------------------------------------------------------------------------------------
+ private void VerifyIntegrity()
{
- return;
+ if (_invalid)
+ {
+ throw new InvalidOperationException(Environment.GetResourceString("CollectionCorrupted"));
+ }
}
- if (_lock != null)
+ //----------------------------------------------------------------------------------------
+ // Finalizer.
+ //----------------------------------------------------------------------------------------
+ ~Container()
{
- lock(_lock)
+ // We're just freeing per-appdomain unmanaged handles here. If we're already shutting down the AD,
+ // don't bother. (Despite its name, Environment.HasShutdownStart also returns true if the current
+ // AD is finalizing.) We also skip doing anything if the container is invalid, including if someone
+ // the container object was allocated but its associated table never set.
+ if (Environment.HasShutdownStarted || _invalid || _parent == null)
{
- if (_invalid)
+ return;
+ }
+
+ // It's possible that the ConditionalWeakTable could have been resurrected, in which case code could
+ // be accessing this Container as it's being finalized. We don't support usage after finalization,
+ // but we also don't want to potentially corrupt state by allowing dependency handles to be used as
+ // or after they've been freed. To avoid that, if it's at all possible that another thread has a
+ // reference to this container via the CWT, we remove such a reference and then re-register for
+ // finalization: the next time around, we can be sure that no references remain to this and we can
+ // clean up the dependency handles without fear of corruption.
+ if (!_finalized)
+ {
+ _finalized = true;
+ lock (_parent._lock)
{
- return;
+ if (_parent._container == this)
+ {
+ _parent._container = null;
+ }
}
- Entry[] entries = _entries;
+ GC.ReRegisterForFinalize(this); // next time it's finalized, we'll be sure there are no remaining refs
+ return;
+ }
- // Make sure anyone sneaking into the table post-resurrection
- // gets booted before they can damage the native handle table.
- _invalid = true;
- _entries = null;
- _buckets = null;
+ Entry[] entries = _entries;
+ _invalid = true;
+ _entries = null;
+ _buckets = null;
+ if (entries != null)
+ {
for (int entriesIndex = 0; entriesIndex < entries.Length; entriesIndex++)
{
- entries[entriesIndex].depHnd.Free();
+ // We need to free handles in two cases:
+ // - If this container still owns the dependency handle (meaning ownership hasn't been transferred
+ // to another container that replaced this one), then it should be freed.
+ // - If this container had the entry removed, then even if in general ownership was transferred to
+ // another container, removed entries are not, therefore this container must free them.
+ if (_oldKeepAlive == null || entries[entriesIndex].HashCode == -1)
+ {
+ entries[entriesIndex].depHnd.Free();
+ }
}
}
}
}
#endregion
-
- #region Private Data Members
- //--------------------------------------------------------------------------------------------
- // Entry can be in one of three states:
- //
- // - Linked into the freeList (_freeList points to first entry)
- // depHnd.IsAllocated == false
- // hashCode == <dontcare>
- // next links to next Entry on freelist)
- //
- // - Used with live key (linked into a bucket list where _buckets[hashCode % _buckets.Length] points to first entry)
- // depHnd.IsAllocated == true, depHnd.GetPrimary() != null
- // hashCode == RuntimeHelpers.GetHashCode(depHnd.GetPrimary()) & Int32.MaxValue
- // next links to next Entry in bucket.
- //
- // - Used with dead key (linked into a bucket list where _buckets[hashCode % _buckets.Length] points to first entry)
- // depHnd.IsAllocated == true, depHnd.GetPrimary() == null
- // hashCode == <notcare>
- // next links to next Entry in bucket.
- //
- // The only difference between "used with live key" and "used with dead key" is that
- // depHnd.GetPrimary() returns null. The transition from "used with live key" to "used with dead key"
- // happens asynchronously as a result of normal garbage collection. The dictionary itself
- // receives no notification when this happens.
- //
- // When the dictionary grows the _entries table, it scours it for expired keys and puts those
- // entries back on the freelist.
- //--------------------------------------------------------------------------------------------
- private struct Entry
- {
- public DependentHandle depHnd; // Holds key and value using a weak reference for the key and a strong reference
- // for the value that is traversed only if the key is reachable without going through the value.
- public int hashCode; // Cached copy of key's hashcode
- public int next; // Index of next entry, -1 if last
- }
-
- private int[] _buckets; // _buckets[hashcode & _buckets.Length] contains index of first entry in bucket (-1 if empty)
- private Entry[] _entries;
- private int _freeList; // -1 = empty, else index of first unused Entry
- private const int _initialCapacity = 5;
- private readonly Object _lock; // this could be a ReaderWriterLock but CoreCLR does not support RWLocks.
- private bool _invalid; // flag detects if OOM or other background exception threw us out of the lock.
- #endregion
}
#endregion
-
-
-
#region DependentHandle
//=========================================================================================
// This struct collects all operations on native DependentHandles. The DependentHandle
// to use DependentHandles in a thread-safe way.
//=========================================================================================
[ComVisible(false)]
- struct DependentHandle
+ internal struct DependentHandle
{
#region Constructors
- #if FEATURE_CORECLR
- [System.Security.SecuritySafeCritical] // auto-generated
- #else
- [System.Security.SecurityCritical]
- #endif
- public DependentHandle(Object primary, Object secondary)
+ public DependentHandle(object primary, object secondary)
{
IntPtr handle = (IntPtr)0;
nInitialize(primary, secondary, out handle);
#endregion
#region Public Members
- public bool IsAllocated
- {
- get
- {
- return _handle != (IntPtr)0;
- }
- }
+ public bool IsAllocated => _handle != IntPtr.Zero;
// Getting the secondary object is more expensive than getting the first so
// we provide a separate primary-only accessor for those times we only want the
// primary.
- #if FEATURE_CORECLR
- [System.Security.SecuritySafeCritical] // auto-generated
- #else
- [System.Security.SecurityCritical]
- #endif
- public Object GetPrimary()
+ public object GetPrimary()
{
- Object primary;
+ object primary;
nGetPrimary(_handle, out primary);
return primary;
}
- #if FEATURE_CORECLR
- [System.Security.SecuritySafeCritical] // auto-generated
- #else
- [System.Security.SecurityCritical]
- #endif
- public void GetPrimaryAndSecondary(out Object primary, out Object secondary)
+ public void GetPrimaryAndSecondary(out object primary, out object secondary)
{
nGetPrimaryAndSecondary(_handle, out primary, out secondary);
}
+ public void SetPrimary(object primary)
+ {
+ nSetPrimary(_handle, primary);
+ }
+
+ public void SetSecondary(object secondary)
+ {
+ nSetSecondary(_handle, secondary);
+ }
+
//----------------------------------------------------------------------
// Forces dependentHandle back to non-allocated state (if not already there)
// and frees the handle if needed.
//----------------------------------------------------------------------
- [System.Security.SecurityCritical]
public void Free()
{
if (_handle != (IntPtr)0)
#endregion
#region Private Members
- [System.Security.SecurityCritical]
- [MethodImplAttribute(MethodImplOptions.InternalCall)]
- private static extern void nInitialize(Object primary, Object secondary, out IntPtr dependentHandle);
+ [MethodImpl(MethodImplOptions.InternalCall)]
+ private static extern void nInitialize(object primary, object secondary, out IntPtr dependentHandle);
+
+ [MethodImpl(MethodImplOptions.InternalCall)]
+ private static extern void nGetPrimary(IntPtr dependentHandle, out object primary);
- [System.Security.SecurityCritical]
- [MethodImplAttribute(MethodImplOptions.InternalCall)]
- private static extern void nGetPrimary(IntPtr dependentHandle, out Object primary);
+ [MethodImpl(MethodImplOptions.InternalCall)]
+ private static extern void nGetPrimaryAndSecondary(IntPtr dependentHandle, out object primary, out object secondary);
- [System.Security.SecurityCritical]
- [MethodImplAttribute(MethodImplOptions.InternalCall)]
- private static extern void nGetPrimaryAndSecondary(IntPtr dependentHandle, out Object primary, out Object secondary);
+ [MethodImpl(MethodImplOptions.InternalCall)]
+ private static extern void nSetPrimary(IntPtr dependentHandle, object primary);
- [System.Security.SecurityCritical]
- [MethodImplAttribute(MethodImplOptions.InternalCall)]
+ [MethodImpl(MethodImplOptions.InternalCall)]
+ private static extern void nSetSecondary(IntPtr dependentHandle, object secondary);
+
+ [MethodImpl(MethodImplOptions.InternalCall)]
private static extern void nFree(IntPtr dependentHandle);
#endregion
} // struct DependentHandle
#endregion
}
-
// Note: If you add a new ctor overloads you need to update ParameterInfo.RawDefaultValue
using System.Reflection;
+using System.Diagnostics;
using System.Diagnostics.Contracts;
using System.Collections.Generic;
if (namedArgument.MemberInfo.Name.Equals("Value"))
{
// This is not possible because Decimal cannot be represented directly in the metadata.
- Contract.Assert(false, "Decimal cannot be represented directly in the metadata.");
+ Debug.Assert(false, "Decimal cannot be represented directly in the metadata.");
return (Decimal)namedArgument.TypedValue.Value;
}
}
ParameterInfo[] parameters = attr.Constructor.GetParameters();
- Contract.Assert(parameters.Length == 5);
+ Debug.Assert(parameters.Length == 5);
System.Collections.Generic.IList<CustomAttributeTypedArgument> args = attr.ConstructorArguments;
- Contract.Assert(args.Count == 5);
+ Debug.Assert(args.Count == 5);
if (parameters[2].ParameterType == typeof(uint))
{
/// <param name="continuation">The action to invoke when the operation completes.</param>
/// <exception cref="System.ArgumentNullException">The <paramref name="continuation"/> argument is null (Nothing in Visual Basic).</exception>
/// <remarks>Unlike OnCompleted, UnsafeOnCompleted need not propagate ExecutionContext information.</remarks>
- [SecurityCritical]
void UnsafeOnCompleted(Action continuation);
}
}
public static class RuntimeHelpers
{
-#if FEATURE_CORECLR
// Exposed here as a more appropriate place than on FormatterServices itself,
// which is a high level reflection heavy type.
public static Object GetUninitializedObject(Type type)
{
return FormatterServices.GetUninitializedObject(type);
}
-#endif // FEATURE_CORECLR
- [System.Security.SecuritySafeCritical] // auto-generated
[MethodImplAttribute(MethodImplOptions.InternalCall)]
public static extern void InitializeArray(Array array,RuntimeFieldHandle fldHandle);
// cloned when you pass them around, and are always passed by value.
// Of course, reference types are not cloned.
//
- [System.Security.SecuritySafeCritical] // auto-generated
[MethodImplAttribute(MethodImplOptions.InternalCall)]
public static extern Object GetObjectValue(Object obj);
// This call will generate an exception if the specified class constructor threw an
// exception when it ran.
- [System.Security.SecuritySafeCritical]
[MethodImplAttribute(MethodImplOptions.InternalCall)]
private static extern void _RunClassConstructor(RuntimeType type);
// This call will generate an exception if the specified module constructor threw an
// exception when it ran.
- [System.Security.SecuritySafeCritical]
[MethodImplAttribute(MethodImplOptions.InternalCall)]
private static extern void _RunModuleConstructor(System.Reflection.RuntimeModule module);
}
- [System.Security.SecurityCritical] // auto-generated
[DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode), SuppressUnmanagedCodeSecurity]
internal static extern void _CompileMethod(IRuntimeMethodInfo method);
-
- #if FEATURE_CORECLR
public static void PrepareMethod(RuntimeMethodHandle method){}
public static void PrepareMethod(RuntimeMethodHandle method, RuntimeTypeHandle[] instantiation){}
public static void PrepareContractedDelegate(Delegate d){}
}
}
- #else
-
- [System.Security.SecurityCritical] // auto-generated
- [MethodImplAttribute(MethodImplOptions.InternalCall)]
- private static unsafe extern void _PrepareMethod(IRuntimeMethodInfo method, IntPtr* pInstantiation, int cInstantiation);
-
- // Simple (instantiation not required) method.
- [System.Security.SecurityCritical] // auto-generated_required
- public static void PrepareMethod(RuntimeMethodHandle method)
- {
- unsafe
- {
- _PrepareMethod(method.GetMethodInfo(), null, 0);
- }
- }
-
- // Generic method or method with generic class with specific instantiation.
- [System.Security.SecurityCritical] // auto-generated_required
- public static void PrepareMethod(RuntimeMethodHandle method, RuntimeTypeHandle[] instantiation)
- {
- unsafe
- {
- int length;
- IntPtr[] instantiationHandles = RuntimeTypeHandle.CopyRuntimeTypeHandles(instantiation, out length);
- fixed (IntPtr* pInstantiation = instantiationHandles)
- {
- _PrepareMethod(method.GetMethodInfo(), pInstantiation, length);
- GC.KeepAlive(instantiation);
- }
- }
- }
- // This method triggers a given delegate to be prepared. This involves preparing the
- // delegate's Invoke method and preparing the target of that Invoke. In the case of
- // a multi-cast delegate, we rely on the fact that each individual component was prepared
- // prior to the Combine. In other words, this service does not navigate through the
- // entire multicasting list.
- // If our own reliable event sinks perform the Combine (for example AppDomain.DomainUnload),
- // then the result is fully prepared. But if a client calls Combine himself and then
- // then adds that combination to e.g. AppDomain.DomainUnload, then the client is responsible
- // for his own preparation.
- [System.Security.SecurityCritical] // auto-generated_required
- [MethodImplAttribute(MethodImplOptions.InternalCall)]
- public static extern void PrepareDelegate(Delegate d);
-
- // See comment above for PrepareDelegate
- //
- // PrepareContractedDelegate weakens this a bit by only assuring that we prepare
- // delegates which also have a ReliabilityContract. This is useful for services that
- // want to provide opt-in reliability, generally some random event sink providing
- // always reliable semantics to random event handlers that are likely to have not
- // been written with relability in mind is a lost cause anyway.
- //
- // NOTE: that for the NGen case you can sidestep the required ReliabilityContract
- // by using the [PrePrepareMethod] attribute.
- [System.Security.SecurityCritical] // auto-generated_required
- [MethodImplAttribute(MethodImplOptions.InternalCall)]
- public static extern void PrepareContractedDelegate(Delegate d);
- #endif
- [System.Security.SecuritySafeCritical] // auto-generated
[MethodImplAttribute(MethodImplOptions.InternalCall)]
public static extern int GetHashCode(Object o);
- [System.Security.SecuritySafeCritical] // auto-generated
[MethodImplAttribute(MethodImplOptions.InternalCall)]
public new static extern bool Equals(Object o1, Object o2);
// If there is not enough stack, then it throws System.InsufficientExecutionStackException.
// Note: this method is not part of the CER support, and is not to be confused with ProbeForSufficientStack
// below.
- [System.Security.SecuritySafeCritical]
[MethodImplAttribute(MethodImplOptions.InternalCall)]
[ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)]
public static extern void EnsureSufficientExecutionStack();
// If there is not enough stack, then it return false.
// Note: this method is not part of the CER support, and is not to be confused with ProbeForSufficientStack
// below.
- [System.Security.SecuritySafeCritical]
[MethodImplAttribute(MethodImplOptions.InternalCall)]
[ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)]
public static extern bool TryEnsureSufficientExecutionStack();
- #if FEATURE_CORECLR
public static void ProbeForSufficientStack()
{
}
- #else
- [System.Security.SecurityCritical] // auto-generated_required
- [MethodImplAttribute(MethodImplOptions.InternalCall)]
- [ReliabilityContract(Consistency.WillNotCorruptState, Cer.MayFail)]
- public static extern void ProbeForSufficientStack();
- #endif
// This method is a marker placed immediately before a try clause to mark the corresponding catch and finally blocks as
// constrained. There's no code here other than the probe because most of the work is done at JIT time when we spot a call to this routine.
- [System.Security.SecurityCritical] // auto-generated_required
[ReliabilityContract(Consistency.WillNotCorruptState, Cer.MayFail)]
public static void PrepareConstrainedRegions()
{
// When we detect a CER with no calls, we can point the JIT to this non-probing version instead
// as we don't need to probe.
- [System.Security.SecurityCritical] // auto-generated_required
[ReliabilityContract(Consistency.WillNotCorruptState, Cer.MayFail)]
public static void PrepareConstrainedRegionsNoOP()
{
}
- #if FEATURE_CORECLR
- [System.Security.SecurityCritical] // auto-generated
- #endif
public delegate void TryCode(Object userData);
- #if FEATURE_CORECLR
- [System.Security.SecurityCritical] // auto-generated
- #endif
public delegate void CleanupCode(Object userData, bool exceptionThrown);
- [System.Security.SecurityCritical] // auto-generated_required
[MethodImplAttribute(MethodImplOptions.InternalCall)]
public static extern void ExecuteCodeWithGuaranteedCleanup(TryCode code, CleanupCode backoutCode, Object userData);
-#if FEATURE_CORECLR
- [System.Security.SecurityCritical] // auto-generated
-#endif
[PrePrepareMethod]
internal static void ExecuteBackoutCodeHelper(Object backoutCode, Object userData, bool exceptionThrown)
{
private Object m_wrappedException;
- [System.Security.SecurityCritical] // auto-generated_required
public override void GetObjectData(SerializationInfo info, StreamingContext context) {
if (info==null) {
throw new ArgumentNullException(nameof(info));
{
/// <summary>Provides an awaiter for awaiting a <see cref="System.Threading.Tasks.Task"/>.</summary>
/// <remarks>This type is intended for compiler use only.</remarks>
- [HostProtection(Synchronization = true, ExternalThreading = true)]
public struct TaskAwaiter : ICriticalNotifyCompletion
{
/// <summary>The task being awaited.</summary>
/// <exception cref="System.ArgumentNullException">The <paramref name="continuation"/> argument is null (Nothing in Visual Basic).</exception>
/// <exception cref="System.InvalidOperationException">The awaiter was not properly initialized.</exception>
/// <remarks>This method is intended for compiler user rather than use directly in code.</remarks>
- [SecuritySafeCritical]
public void OnCompleted(Action continuation)
{
OnCompletedInternal(m_task, continuation, continueOnCapturedContext:true, flowExecutionContext:true);
/// <exception cref="System.ArgumentNullException">The <paramref name="continuation"/> argument is null (Nothing in Visual Basic).</exception>
/// <exception cref="System.InvalidOperationException">The awaiter was not properly initialized.</exception>
/// <remarks>This method is intended for compiler user rather than use directly in code.</remarks>
- [SecurityCritical]
public void UnsafeOnCompleted(Action continuation)
{
OnCompletedInternal(m_task, continuation, continueOnCapturedContext:true, flowExecutionContext:false);
if (!task.IsCompleted)
{
bool taskCompleted = task.InternalWait(Timeout.Infinite, default(CancellationToken));
- Contract.Assert(taskCompleted, "With an infinite timeout, the task should have always completed.");
+ Debug.Assert(taskCompleted, "With an infinite timeout, the task should have always completed.");
}
// Now that we're done, alert the debugger if so requested
if (oceEdi != null)
{
oceEdi.Throw();
- Contract.Assert(false, "Throw() should have thrown");
+ Debug.Assert(false, "Throw() should have thrown");
}
throw new TaskCanceledException(task);
if (edis.Count > 0)
{
edis[0].Throw();
- Contract.Assert(false, "Throw() should have thrown");
+ Debug.Assert(false, "Throw() should have thrown");
break; // Necessary to compile: non-reachable, but compiler can't determine that
}
else
{
- Contract.Assert(false, "There should be exceptions if we're Faulted.");
+ Debug.Assert(false, "There should be exceptions if we're Faulted.");
throw task.Exception;
}
}
/// <exception cref="System.NullReferenceException">The awaiter was not properly initialized.</exception>
/// <remarks>This method is intended for compiler user rather than use directly in code.</remarks>
[MethodImplAttribute(MethodImplOptions.NoInlining)] // Methods containing StackCrawlMark local var have to be marked non-inlineable
- [SecurityCritical]
internal static void OnCompletedInternal(Task task, Action continuation, bool continueOnCapturedContext, bool flowExecutionContext)
{
if (continuation == null) throw new ArgumentNullException(nameof(continuation));
/// <summary>Provides an awaiter for awaiting a <see cref="System.Threading.Tasks.Task{TResult}"/>.</summary>
/// <remarks>This type is intended for compiler use only.</remarks>
- [HostProtection(Synchronization = true, ExternalThreading = true)]
public struct TaskAwaiter<TResult> : ICriticalNotifyCompletion
{
/// <summary>The task being awaited.</summary>
/// <exception cref="System.ArgumentNullException">The <paramref name="continuation"/> argument is null (Nothing in Visual Basic).</exception>
/// <exception cref="System.NullReferenceException">The awaiter was not properly initialized.</exception>
/// <remarks>This method is intended for compiler user rather than use directly in code.</remarks>
- [SecuritySafeCritical]
public void OnCompleted(Action continuation)
{
TaskAwaiter.OnCompletedInternal(m_task, continuation, continueOnCapturedContext:true, flowExecutionContext:true);
/// <exception cref="System.ArgumentNullException">The <paramref name="continuation"/> argument is null (Nothing in Visual Basic).</exception>
/// <exception cref="System.NullReferenceException">The awaiter was not properly initialized.</exception>
/// <remarks>This method is intended for compiler user rather than use directly in code.</remarks>
- [SecurityCritical]
public void UnsafeOnCompleted(Action continuation)
{
TaskAwaiter.OnCompletedInternal(m_task, continuation, continueOnCapturedContext:true, flowExecutionContext:false);
/// <summary>Provides an awaiter for a <see cref="ConfiguredTaskAwaitable"/>.</summary>
/// <remarks>This type is intended for compiler use only.</remarks>
- [HostProtection(Synchronization = true, ExternalThreading = true)]
public struct ConfiguredTaskAwaiter : ICriticalNotifyCompletion
{
/// <summary>The task being awaited.</summary>
/// <exception cref="System.ArgumentNullException">The <paramref name="continuation"/> argument is null (Nothing in Visual Basic).</exception>
/// <exception cref="System.NullReferenceException">The awaiter was not properly initialized.</exception>
/// <remarks>This method is intended for compiler user rather than use directly in code.</remarks>
- [SecuritySafeCritical]
public void OnCompleted(Action continuation)
{
TaskAwaiter.OnCompletedInternal(m_task, continuation, m_continueOnCapturedContext, flowExecutionContext:true);
/// <exception cref="System.ArgumentNullException">The <paramref name="continuation"/> argument is null (Nothing in Visual Basic).</exception>
/// <exception cref="System.NullReferenceException">The awaiter was not properly initialized.</exception>
/// <remarks>This method is intended for compiler user rather than use directly in code.</remarks>
- [SecurityCritical]
public void UnsafeOnCompleted(Action continuation)
{
TaskAwaiter.OnCompletedInternal(m_task, continuation, m_continueOnCapturedContext, flowExecutionContext:false);
/// <summary>Provides an awaiter for a <see cref="ConfiguredTaskAwaitable{TResult}"/>.</summary>
/// <remarks>This type is intended for compiler use only.</remarks>
- [HostProtection(Synchronization = true, ExternalThreading = true)]
public struct ConfiguredTaskAwaiter : ICriticalNotifyCompletion
{
/// <summary>The task being awaited.</summary>
/// <exception cref="System.ArgumentNullException">The <paramref name="continuation"/> argument is null (Nothing in Visual Basic).</exception>
/// <exception cref="System.NullReferenceException">The awaiter was not properly initialized.</exception>
/// <remarks>This method is intended for compiler user rather than use directly in code.</remarks>
- [SecuritySafeCritical]
public void OnCompleted(Action continuation)
{
TaskAwaiter.OnCompletedInternal(m_task, continuation, m_continueOnCapturedContext, flowExecutionContext:true);
/// <exception cref="System.ArgumentNullException">The <paramref name="continuation"/> argument is null (Nothing in Visual Basic).</exception>
/// <exception cref="System.NullReferenceException">The awaiter was not properly initialized.</exception>
/// <remarks>This method is intended for compiler user rather than use directly in code.</remarks>
- [SecurityCritical]
public void UnsafeOnCompleted(Action continuation)
{
TaskAwaiter.OnCompletedInternal(m_task, continuation, m_continueOnCapturedContext, flowExecutionContext:false);
}
}
- [System.Security.SecurityCritical]
internal static TypeForwardedToAttribute[] GetCustomAttribute(RuntimeAssembly assembly)
{
Type[] types = null;
/// <summary>Provides an awaiter that switches into a target environment.</summary>
/// <remarks>This type is intended for compiler use only.</remarks>
- [HostProtection(Synchronization = true, ExternalThreading = true)]
public struct YieldAwaiter : ICriticalNotifyCompletion
{
/// <summary>Gets whether a yield is not required.</summary>
/// <summary>Posts the <paramref name="continuation"/> back to the current context.</summary>
/// <param name="continuation">The action to invoke asynchronously.</param>
/// <exception cref="System.ArgumentNullException">The <paramref name="continuation"/> argument is null (Nothing in Visual Basic).</exception>
- [SecuritySafeCritical]
public void OnCompleted(Action continuation)
{
QueueContinuation(continuation, flowContext: true);
/// <summary>Posts the <paramref name="continuation"/> back to the current context.</summary>
/// <param name="continuation">The action to invoke asynchronously.</param>
/// <exception cref="System.ArgumentNullException">The <paramref name="continuation"/> argument is null (Nothing in Visual Basic).</exception>
- [SecurityCritical]
public void UnsafeOnCompleted(Action continuation)
{
QueueContinuation(continuation, flowContext: false);
/// <param name="continuation">The action to invoke asynchronously.</param>
/// <param name="flowContext">true to flow ExecutionContext; false if flowing is not required.</param>
/// <exception cref="System.ArgumentNullException">The <paramref name="continuation"/> argument is null (Nothing in Visual Basic).</exception>
- [SecurityCritical]
private static void QueueContinuation(Action continuation, bool flowContext)
{
// Validate arguments
using System.Threading;
using System.Runtime;
using System.Runtime.Versioning;
+using System.Diagnostics;
using System.Diagnostics.Contracts;
using System.Runtime.InteropServices;
using System.Security;
// Wraps object variable into a handle. Used to return managed strings from QCalls.
// s has to be a local variable on the stack.
- [SecurityCritical]
static internal StringHandleOnStack GetStringHandleOnStack(ref string s)
{
return new StringHandleOnStack(UnsafeCastToStackPointer(ref s));
// Wraps object variable into a handle. Used to pass managed object references in and out of QCalls.
// o has to be a local variable on the stack.
- [SecurityCritical]
static internal ObjectHandleOnStack GetObjectHandleOnStack<T>(ref T o) where T : class
{
return new ObjectHandleOnStack(UnsafeCastToStackPointer(ref o));
// Wraps StackCrawlMark into a handle. Used to pass StackCrawlMark to QCalls.
// stackMark has to be a local variable on the stack.
- [SecurityCritical]
static internal StackCrawlMarkHandle GetStackCrawlMarkHandle(ref StackCrawlMark stackMark)
{
return new StackCrawlMarkHandle(UnsafeCastToStackPointer(ref stackMark));
}
#if _DEBUG
- [SecurityCritical]
[FriendAccessAllowed]
static internal T UnsafeCast<T>(Object o) where T : class
{
T ret = UnsafeCastInternal<T>(o);
- Contract.Assert(ret == (o as T), "Invalid use of JitHelpers.UnsafeCast!");
+ Debug.Assert(ret == (o as T), "Invalid use of JitHelpers.UnsafeCast!");
return ret;
}
// The IL body of this method is not critical, but its body will be replaced with unsafe code, so
// this method is effectively critical
- [SecurityCritical]
static private T UnsafeCastInternal<T>(Object o) where T : class
{
// The body of this function will be replaced by the EE with unsafe code that just returns o!!!
static internal int UnsafeEnumCast<T>(T val) where T : struct // Actually T must be 4 byte (or less) enum
{
- Contract.Assert(typeof(T).IsEnum
+ Debug.Assert(typeof(T).IsEnum
&& (Enum.GetUnderlyingType(typeof(T)) == typeof(int)
|| Enum.GetUnderlyingType(typeof(T)) == typeof(uint)
|| Enum.GetUnderlyingType(typeof(T)) == typeof(short)
static internal long UnsafeEnumCastLong<T>(T val) where T : struct // Actually T must be 8 byte enum
{
- Contract.Assert(typeof(T).IsEnum
+ Debug.Assert(typeof(T).IsEnum
&& (Enum.GetUnderlyingType(typeof(T)) == typeof(long)
|| Enum.GetUnderlyingType(typeof(T)) == typeof(ulong)),
"Error, T must be an 8 byte enum JitHelpers.UnsafeEnumCastLong!");
// Internal method for getting a raw pointer for handles in JitHelpers.
// The reference has to point into a local stack variable in order so it can not be moved by the GC.
- [SecurityCritical]
static internal IntPtr UnsafeCastToStackPointer<T>(ref T val)
{
IntPtr p = UnsafeCastToStackPointerInternal<T>(ref val);
- Contract.Assert(IsAddressInStack(p), "Pointer not in the stack!");
+ Debug.Assert(IsAddressInStack(p), "Pointer not in the stack!");
return p;
}
- [SecurityCritical]
static private IntPtr UnsafeCastToStackPointerInternal<T>(ref T val)
{
// The body of this function will be replaced by the EE with unsafe code that just returns val!!!
#else // _DEBUG
// The IL body of this method is not critical, but its body will be replaced with unsafe code, so
// this method is effectively critical
- [SecurityCritical]
[FriendAccessAllowed]
static internal T UnsafeCast<T>(Object o) where T : class
{
throw new InvalidOperationException();
}
- [SecurityCritical]
static internal IntPtr UnsafeCastToStackPointer<T>(ref T val)
{
// The body of this function will be replaced by the EE with unsafe code that just returns o!!!
#endif // _DEBUG
// Set the given element in the array without any type or range checks
- [SecurityCritical]
[MethodImplAttribute(MethodImplOptions.InternalCall)]
extern static internal void UnsafeSetArrayElement(Object[] target, int index, Object element);
// Used for unsafe pinning of arbitrary objects.
- [System.Security.SecurityCritical] // auto-generated
static internal PinningHelper GetPinningHelper(Object o)
{
// This cast is really unsafe - call the private version that does not assert in debug
}
#if _DEBUG
- [SecurityCritical]
[MethodImplAttribute(MethodImplOptions.InternalCall)]
extern static bool IsAddressInStack(IntPtr ptr);
#endif
public static GCLatencyMode LatencyMode
{
- [System.Security.SecuritySafeCritical] // auto-generated
[ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)]
get
{
}
// We don't want to allow this API when hosted.
- [System.Security.SecurityCritical] // auto-generated_required
- [HostProtection(MayLeakOnAbort = true)]
[ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)]
set
{
public static GCLargeObjectHeapCompactionMode LargeObjectHeapCompactionMode
{
- [System.Security.SecuritySafeCritical] // auto-generated
[ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)]
get
{
}
// We don't want to allow this API when hosted.
- [System.Security.SecurityCritical] // auto-generated_required
- [HostProtection(MayLeakOnAbort = true)]
[ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)]
set
{
public static bool IsServerGC
{
- [System.Security.SecuritySafeCritical] // auto-generated
get {
return GC.IsServerGC();
}
// throw new Exception();
//}
- [System.Security.SecuritySafeCritical] // auto-generated
public ArrayWithOffset(Object array, int offset)
{
m_array = array;
return !(a == b);
}
- [System.Security.SecurityCritical] // auto-generated
[MethodImplAttribute(MethodImplOptions.InternalCall)]
private extern int CalculateCount();
using System;
using System.Reflection;
+ using System.Diagnostics;
using System.Diagnostics.Contracts;
[AttributeUsage(AttributeTargets.Delegate, AllowMultiple = false, Inherited = false)]
[System.Runtime.InteropServices.ComVisible(true)]
public unsafe sealed class MarshalAsAttribute : Attribute
{
- [System.Security.SecurityCritical] // auto-generated
internal static Attribute GetCustomAttribute(RuntimeParameterInfo parameter)
{
return GetCustomAttribute(parameter.MetadataToken, parameter.GetRuntimeModule());
}
- [System.Security.SecurityCritical] // auto-generated
internal static bool IsDefined(RuntimeParameterInfo parameter)
{
return GetCustomAttribute(parameter) != null;
}
- [System.Security.SecurityCritical] // auto-generated
internal static Attribute GetCustomAttribute(RuntimeFieldInfo field)
{
return GetCustomAttribute(field.MetadataToken, field.GetRuntimeModule()); ;
}
- [System.Security.SecurityCritical] // auto-generated
internal static bool IsDefined(RuntimeFieldInfo field)
{
return GetCustomAttribute(field) != null;
}
- [System.Security.SecurityCritical] // auto-generated
internal static Attribute GetCustomAttribute(int token, RuntimeModule scope)
{
UnmanagedType unmanagedType, arraySubType;
{
// The user may have supplied a bad type name string causing this TypeLoadException
// Regardless, we return the bad type name
- Contract.Assert(marshalTypeName != null);
+ Debug.Assert(marshalTypeName != null);
}
return new MarshalAsAttribute(
[System.Runtime.InteropServices.ComVisible(true)]
public unsafe sealed class DllImportAttribute : Attribute
{
- [System.Security.SecurityCritical] // auto-generated
internal static Attribute GetCustomAttribute(RuntimeMethodInfo method)
{
if ((method.Attributes & MethodAttributes.PinvokeImpl) == 0)
{
private const int DEFAULT_PACKING_SIZE = 8;
- [System.Security.SecurityCritical] // auto-generated
internal static Attribute GetCustomAttribute(RuntimeType type)
{
if (!IsDefined(type))
[System.Runtime.InteropServices.ComVisible(true)]
public unsafe sealed class FieldOffsetAttribute : Attribute
{
- [System.Security.SecurityCritical] // auto-generated
internal static Attribute GetCustomAttribute(RuntimeFieldInfo field)
{
int fieldOffset;
return null;
}
- [System.Security.SecurityCritical] // auto-generated
internal static bool IsDefined(RuntimeFieldInfo field)
{
return GetCustomAttribute(field) != null;
[System.Runtime.InteropServices.ComVisible(true)]
public sealed class BStrWrapper
{
- [System.Security.SecuritySafeCritical] // auto-generated
-#pragma warning disable 618
- [SecurityPermissionAttribute(SecurityAction.Demand,Flags=SecurityPermissionFlag.UnmanagedCode)]
-#pragma warning restore 618
public BStrWrapper(String value)
{
m_WrappedObject = value;
}
- [System.Security.SecuritySafeCritical] // auto-generated
-#pragma warning disable 618
- [SecurityPermissionAttribute(SecurityAction.Demand, Flags = SecurityPermissionFlag.UnmanagedCode)]
-#pragma warning restore 618
public BStrWrapper(Object value)
{
m_WrappedObject = (String)value;
SetErrorCode(errorCode);
}
- [SecuritySafeCritical]
internal COMException(int hresult)
: base(Win32Native.GetMessage(hresult))
{
/// <param name="iid">identifier of the source interface used by COM object to fire events</param>
/// <param name="dispid">dispatch identifier of the method on the source interface</param>
/// <param name="d">delegate to invoke when specifed COM event is fired</param>
- [System.Security.SecurityCritical]
public static void Combine(object rcw, Guid iid, int dispid, System.Delegate d) {
rcw = UnwrapIfTransparentProxy(rcw);
/// <param name="dispid">dispatch identifier of the method on the source interface</param>
/// <param name="d">delegate to remove from the invocation list</param>
/// <returns></returns>
- [System.Security.SecurityCritical]
public static Delegate Remove(object rcw, Guid iid, int dispid, System.Delegate d) {
rcw = UnwrapIfTransparentProxy(rcw);
}
}
- [System.Security.SecurityCritical]
- internal static object UnwrapIfTransparentProxy(object rcw) {
-#if FEATURE_REMOTING
- if (RemotingServices.IsTransparentProxy(rcw)) {
- IntPtr punk = Marshal.GetIUnknownForObject(rcw);
- try {
- rcw = Marshal.GetObjectForIUnknown(punk);
- } finally {
- Marshal.Release(punk);
- }
- }
-#endif
+ internal static object UnwrapIfTransparentProxy(object rcw)
+ {
return rcw;
}
}
using ComTypes = System.Runtime.InteropServices.ComTypes;
// see code:ComEventsHelper#ComEventsArchitecture
- [System.Security.SecurityCritical]
internal class ComEventsInfo {
_rcw = rcw;
}
- [System.Security.SecuritySafeCritical]
~ComEventsInfo() {
// see code:ComEventsHelper#ComEventsFinalization
_sinks = ComEventsSink.RemoveAll(_sinks);
#region static methods
- [System.Security.SecurityCritical]
internal static ComEventsInfo Find(object rcw) {
return (ComEventsInfo)Marshal.GetComObjectData(rcw, typeof(ComEventsInfo));
}
// it is caller's responsibility to call this method under lock(rcw)
- [System.Security.SecurityCritical]
internal static ComEventsInfo FromObject(object rcw) {
ComEventsInfo eventsInfo = Find(rcw);
if (eventsInfo == null) {
}
// it is caller's responsibility to call this method under lock(rcw)
- [System.Security.SecurityCritical]
internal ComEventsSink RemoveSink(ComEventsSink sink) {
_sinks = ComEventsSink.Remove(_sinks, sink);
return _sinks;
using System.Diagnostics;
// see code:ComEventsHelper#ComEventsArchitecture
- [System.Security.SecurityCritical]
internal class ComEventsSink : NativeMethods.IDispatch, ICustomQueryInterface
{
#region private fields
return sink;
}
- [System.Security.SecurityCritical]
internal static ComEventsSink RemoveAll(ComEventsSink sinks) {
while (sinks != null) {
sinks.Unadvise();
return null;
}
- [System.Security.SecurityCritical]
internal static ComEventsSink Remove(ComEventsSink sinks, ComEventsSink sink) {
BCLDebug.Assert(sinks != null, "removing event sink from empty sinks collection");
BCLDebug.Assert(sink != null, "specify event sink is null");
#region IDispatch Members
- [System.Security.SecurityCritical]
void NativeMethods.IDispatch.GetTypeInfoCount(out uint pctinfo) {
pctinfo = 0;
}
- [System.Security.SecurityCritical]
void NativeMethods.IDispatch.GetTypeInfo(uint iTInfo, int lcid, out IntPtr info) {
throw new NotImplementedException();
}
- [System.Security.SecurityCritical]
void NativeMethods.IDispatch.GetIDsOfNames(ref Guid iid, string[] names, uint cNames, int lcid, int[] rgDispId) {
throw new NotImplementedException();
}
return pSrc;
}
- [System.Security.SecurityCritical]
unsafe void NativeMethods.IDispatch.Invoke(
int dispid,
ref Guid riid,
static Guid IID_IManagedObject = new Guid("{C3FCC19E-A970-11D2-8B5A-00A0C9B7C9C4}");
- [System.Security.SecurityCritical]
CustomQueryInterfaceResult ICustomQueryInterface.GetInterface(ref Guid iid, out IntPtr ppv) {
ppv = IntPtr.Zero;
if (iid == this._iidSourceItf || iid == typeof(NativeMethods.IDispatch).GUID) {
_connectionPoint = cp;
}
- [System.Security.SecurityCritical]
private void Unadvise() {
BCLDebug.Assert(_connectionPoint != null, "can not unadvise from empty connection point");
// we'll do this to ensure we've cut off all attack vectors. Similarly, all
// methods have a link demand to ensure untrusted code cannot directly edit
// or alter a handle.
-[System.Security.SecurityCritical] // auto-generated_required
-#if !FEATURE_CORECLR
-[SecurityPermission(SecurityAction.InheritanceDemand, UnmanagedCode=true)]
-#endif
public abstract class CriticalHandle : CriticalFinalizerObject, IDisposable
{
// ! Do not add or rearrange fields as the EE depends on this layout.
#endif
}
-#if FEATURE_CORECLR
// Adding an empty default constructor for annotation purposes
private CriticalHandle(){}
-#endif
- [System.Security.SecuritySafeCritical] // auto-generated
[ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)]
~CriticalHandle()
{
Dispose(false);
}
- [System.Security.SecurityCritical] // auto-generated
[ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)]
private void Cleanup()
{
get;
}
- [System.Security.SecurityCritical] // auto-generated
[ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)]
public void Close() {
Dispose(true);
}
- [System.Security.SecuritySafeCritical] // auto-generated
[ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)]
public void Dispose()
{
Dispose(true);
}
- [System.Security.SecurityCritical] // auto-generated
[ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)]
protected virtual void Dispose(bool disposing)
{
[System.Runtime.InteropServices.ComVisible(true)]
public sealed class DispatchWrapper
{
- [System.Security.SecuritySafeCritical] // auto-generated
-#pragma warning disable 618
- [SecurityPermissionAttribute(SecurityAction.Demand,Flags=SecurityPermissionFlag.UnmanagedCode)]
-#pragma warning restore 618
public DispatchWrapper(Object obj)
{
if (obj != null)
m_ErrorCode = (int)errorCode;
}
- [System.Security.SecuritySafeCritical] // auto-generated
-#pragma warning disable 618
- [SecurityPermissionAttribute(SecurityAction.Demand, Flags=SecurityPermissionFlag.UnmanagedCode)]
-#pragma warning restore 618
public ErrorWrapper(Exception e)
{
m_ErrorCode = Marshal.GetHRForException(e);
// class for which the callbacks will be made.
// It is not legal to register this callback from a class that has any
// parents that have already registered a callback.
- [System.Security.SecuritySafeCritical] // auto-generated
[MethodImplAttribute(MethodImplOptions.InternalCall)]
public static extern void RegisterObjectCreationCallback(ObjectCreationDelegate callback);
}
private const GCHandleType MaxHandleType = GCHandleType.Pinned;
#if MDA_SUPPORTED
- [System.Security.SecuritySafeCritical] // auto-generated
static GCHandle()
{
s_probeIsActive = Mda.IsInvalidGCHandleCookieProbeEnabled();
#endif
// Allocate a handle storing the object and the type.
- [System.Security.SecurityCritical] // auto-generated
internal GCHandle(Object value, GCHandleType type)
{
// Make sure the type parameter is within the valid range for the enum.
}
// Used in the conversion functions below.
- [System.Security.SecurityCritical] // auto-generated
internal GCHandle(IntPtr handle)
{
InternalCheckDomain(handle);
// type - The type of GC handle to create.
//
// returns a new GC handle that protects the object.
- [System.Security.SecurityCritical] // auto-generated_required
public static GCHandle Alloc(Object value)
{
return new GCHandle(value, GCHandleType.Normal);
}
- [System.Security.SecurityCritical] // auto-generated_required
public static GCHandle Alloc(Object value, GCHandleType type)
{
return new GCHandle(value, type);
// Frees a GC handle.
- [System.Security.SecurityCritical] // auto-generated_required
public void Free()
{
// Copy the handle instance member to a local variable. This is required to prevent
// Target property - allows getting / updating of the handle's referent.
public Object Target
{
- [System.Security.SecurityCritical] // auto-generated_required
get
{
// Check if the handle was never initialized or was freed.
return InternalGet(GetHandleValue());
}
- [System.Security.SecurityCritical] // auto-generated_required
set
{
// Check if the handle was never initialized or was freed.
// Retrieve the address of an object in a Pinned handle. This throws
// an exception if the handle is any type other than Pinned.
- [System.Security.SecurityCritical] // auto-generated_required
public IntPtr AddrOfPinnedObject()
{
// Check if the handle was not a pinned handle.
// Used to create a GCHandle from an int. This is intended to
// be used with the reverse conversion.
- [System.Security.SecurityCritical] // auto-generated_required
public static explicit operator GCHandle(IntPtr value)
{
return FromIntPtr(value);
}
- [System.Security.SecurityCritical] // auto-generated_required
public static GCHandle FromIntPtr(IntPtr value)
{
if (value == IntPtr.Zero)
}
// Internal native calls that this implementation uses.
- [System.Security.SecurityCritical] // auto-generated
[MethodImplAttribute(MethodImplOptions.InternalCall)]
internal static extern IntPtr InternalAlloc(Object value, GCHandleType type);
- [System.Security.SecurityCritical] // auto-generated
[MethodImplAttribute(MethodImplOptions.InternalCall)]
internal static extern void InternalFree(IntPtr handle);
- [System.Security.SecurityCritical] // auto-generated
[MethodImplAttribute(MethodImplOptions.InternalCall)]
internal static extern Object InternalGet(IntPtr handle);
- [System.Security.SecurityCritical] // auto-generated
[MethodImplAttribute(MethodImplOptions.InternalCall)]
internal static extern void InternalSet(IntPtr handle, Object value, bool isPinned);
- [System.Security.SecurityCritical] // auto-generated
[MethodImplAttribute(MethodImplOptions.InternalCall)]
internal static extern Object InternalCompareExchange(IntPtr handle, Object value, Object oldValue, bool isPinned);
- [System.Security.SecurityCritical] // auto-generated
[MethodImplAttribute(MethodImplOptions.InternalCall)]
internal static extern IntPtr InternalAddrOfPinnedObject(IntPtr handle);
- [System.Security.SecurityCritical] // auto-generated
[MethodImplAttribute(MethodImplOptions.InternalCall)]
internal static extern void InternalCheckDomain(IntPtr handle);
- [System.Security.SecurityCritical] // auto-generated
[MethodImplAttribute(MethodImplOptions.InternalCall)]
internal static extern GCHandleType InternalGetHandleType(IntPtr handle);
[System.Runtime.InteropServices.ComVisible(false)]
public interface ICustomQueryInterface
{
- [System.Security.SecurityCritical]
CustomQueryInterfaceResult GetInterface([In]ref Guid iid, out IntPtr ppv);
}
}
[GuidAttribute("b36b5c63-42ef-38bc-a07e-0b34c98f164a")]
[InterfaceTypeAttribute(ComInterfaceType.InterfaceIsDual)]
[CLSCompliant(false)]
-[System.Runtime.InteropServices.ComVisible(true)]
+ [System.Runtime.InteropServices.ComVisible(true)]
public interface _Exception
{
-#if !FEATURE_CORECLR
- // This contains all of our V1 Exception class's members.
-
- // From Object
- String ToString();
- bool Equals (Object obj);
- int GetHashCode ();
- Type GetType ();
-
- // From V1's Exception class
- String Message {
- get;
- }
-
- Exception GetBaseException();
-
- String StackTrace {
- get;
- }
-
- String HelpLink {
- get;
- set;
- }
-
- String Source {
- #if FEATURE_CORECLR
- [System.Security.SecurityCritical] // auto-generated
- #endif
- get;
- #if FEATURE_CORECLR
- [System.Security.SecurityCritical] // auto-generated
- #endif
- set;
- }
- [System.Security.SecurityCritical] // auto-generated_required
- void GetObjectData(SerializationInfo info, StreamingContext context);
-#endif
-
//
// This method is intentionally included in CoreCLR to make Exception.get_InnerException "newslot virtual final".
// Some phone apps include MEF from desktop Silverlight. MEF's ComposablePartException depends on implicit interface
Exception InnerException {
get;
}
-
-#if !FEATURE_CORECLR
- MethodBase TargetSite {
- get;
- }
-#endif
}
-
}
[System.Runtime.InteropServices.ComVisible(true)]
public interface IRegistrationServices
{
- [System.Security.SecurityCritical] // auto-generated_required
bool RegisterAssembly(Assembly assembly, AssemblyRegistrationFlags flags);
- [System.Security.SecurityCritical] // auto-generated_required
bool UnregisterAssembly(Assembly assembly);
- [System.Security.SecurityCritical] // auto-generated_required
Type[] GetRegistrableTypesInAssembly(Assembly assembly);
- [System.Security.SecurityCritical] // auto-generated_required
String GetProgIdForType(Type type);
- [System.Security.SecurityCritical] // auto-generated_required
void RegisterTypeForComClients(Type type, ref Guid g);
Guid GetManagedCategoryGuid();
- [System.Security.SecurityCritical] // auto-generated_required
bool TypeRequiresRegistration(Type type);
bool TypeRepresentsComType(Type type);
using System.Runtime.Versioning;
using Win32Native = Microsoft.Win32.Win32Native;
using Microsoft.Win32.SafeHandles;
+ using System.Diagnostics;
using System.Diagnostics.Contracts;
using System.Runtime.InteropServices.ComTypes;
// declaration on the class.
//========================================================================
- #if FEATURE_CORECLR
- [System.Security.SecurityCritical] // auto-generated
- #endif
public static partial class Marshal
{
//====================================================================
[MethodImplAttribute(MethodImplOptions.InternalCall)]
private static extern int GetSystemMaxDBCSCharSize();
- [System.Security.SecurityCritical] // auto-generated_required
unsafe public static String PtrToStringAnsi(IntPtr ptr)
{
if (IntPtr.Zero == ptr) {
}
}
- [System.Security.SecurityCritical] // auto-generated_required
unsafe public static String PtrToStringAnsi(IntPtr ptr, int len)
{
if (ptr == IntPtr.Zero)
return new String((sbyte *)ptr, 0, len);
}
- [System.Security.SecurityCritical] // auto-generated_required
unsafe public static String PtrToStringUni(IntPtr ptr, int len)
{
if (ptr == IntPtr.Zero)
return new String((char *)ptr, 0, len);
}
- [System.Security.SecurityCritical] // auto-generated_required
public static String PtrToStringAuto(IntPtr ptr, int len)
{
// Ansi platforms are no longer supported
return PtrToStringUni(ptr, len);
}
- [System.Security.SecurityCritical] // auto-generated_required
unsafe public static String PtrToStringUni(IntPtr ptr)
{
if (IntPtr.Zero == ptr) {
}
}
- [System.Security.SecurityCritical] // auto-generated_required
public static String PtrToStringAuto(IntPtr ptr)
{
// Ansi platforms are no longer supported
return PtrToStringUni(ptr);
}
- [System.Security.SecurityCritical] // auto-generated_required
unsafe public static String PtrToStringUTF8(IntPtr ptr)
{
int nbBytes = System.StubHelpers.StubHelpers.strlen((sbyte*)ptr.ToPointer());
return PtrToStringUTF8(ptr, nbBytes);
}
- [System.Security.SecurityCritical] // auto-generated_required
unsafe public static String PtrToStringUTF8(IntPtr ptr,int byteLen)
{
if (byteLen < 0)
[ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)]
private static extern uint AlignedSizeOfType(Type type);
-#if !FEATURE_CORECLR // Marshal is critical in CoreCLR, so SafeCritical members trigger Annotator violations
- [System.Security.SecuritySafeCritical]
-#endif // !FEATURE_CORECLR
[MethodImplAttribute(MethodImplOptions.InternalCall)]
internal static extern int SizeOfHelper(Type t, bool throwIfNotMarshalable);
// an array that is not pinned or in the fixed heap can cause
// unexpected results !
//====================================================================
- [System.Security.SecurityCritical] // auto-generated_required
[MethodImplAttribute(MethodImplOptions.InternalCall)]
public static extern IntPtr UnsafeAddrOfPinnedArrayElement(Array arr, int index);
- [System.Security.SecurityCritical]
public static IntPtr UnsafeAddrOfPinnedArrayElement<T>(T[] arr, int index)
{
return UnsafeAddrOfPinnedArrayElement((Array)arr, index);
//====================================================================
// Copy blocks from CLR arrays to native memory.
//====================================================================
- [System.Security.SecurityCritical] // auto-generated_required
public static void Copy(int[] source, int startIndex, IntPtr destination, int length)
{
CopyToNative(source, startIndex, destination, length);
}
- [System.Security.SecurityCritical] // auto-generated_required
public static void Copy(char[] source, int startIndex, IntPtr destination, int length)
{
CopyToNative(source, startIndex, destination, length);
}
- [System.Security.SecurityCritical] // auto-generated_required
public static void Copy(short[] source, int startIndex, IntPtr destination, int length)
{
CopyToNative(source, startIndex, destination, length);
}
- [System.Security.SecurityCritical] // auto-generated_required
public static void Copy(long[] source, int startIndex, IntPtr destination, int length)
{
CopyToNative(source, startIndex, destination, length);
}
- [System.Security.SecurityCritical] // auto-generated_required
public static void Copy(float[] source, int startIndex, IntPtr destination, int length)
{
CopyToNative(source, startIndex, destination, length);
}
- [System.Security.SecurityCritical] // auto-generated_required
public static void Copy(double[] source, int startIndex, IntPtr destination, int length)
{
CopyToNative(source, startIndex, destination, length);
}
- [System.Security.SecurityCritical] // auto-generated_required
public static void Copy(byte[] source, int startIndex, IntPtr destination, int length)
{
CopyToNative(source, startIndex, destination, length);
}
- [System.Security.SecurityCritical] // auto-generated_required
public static void Copy(IntPtr[] source, int startIndex, IntPtr destination, int length)
{
CopyToNative(source, startIndex, destination, length);
//====================================================================
// Copy blocks from native memory to CLR arrays
//====================================================================
- [System.Security.SecurityCritical] // auto-generated_required
public static void Copy(IntPtr source, int[] destination, int startIndex, int length)
{
CopyToManaged(source, destination, startIndex, length);
}
- [System.Security.SecurityCritical] // auto-generated_required
public static void Copy(IntPtr source, char[] destination, int startIndex, int length)
{
CopyToManaged(source, destination, startIndex, length);
}
- [System.Security.SecurityCritical] // auto-generated_required
public static void Copy(IntPtr source, short[] destination, int startIndex, int length)
{
CopyToManaged(source, destination, startIndex, length);
}
- [System.Security.SecurityCritical] // auto-generated_required
public static void Copy(IntPtr source, long[] destination, int startIndex, int length)
{
CopyToManaged(source, destination, startIndex, length);
}
- [System.Security.SecurityCritical] // auto-generated_required
public static void Copy(IntPtr source, float[] destination, int startIndex, int length)
{
CopyToManaged(source, destination, startIndex, length);
}
- [System.Security.SecurityCritical] // auto-generated_required
public static void Copy(IntPtr source, double[] destination, int startIndex, int length)
{
CopyToManaged(source, destination, startIndex, length);
}
- [System.Security.SecurityCritical] // auto-generated_required
public static void Copy(IntPtr source, byte[] destination, int startIndex, int length)
{
CopyToManaged(source, destination, startIndex, length);
}
- [System.Security.SecurityCritical] // auto-generated_required
public static void Copy(IntPtr source, IntPtr[] destination, int startIndex, int length)
{
CopyToManaged(source, destination, startIndex, length);
//====================================================================
// Read from memory
//====================================================================
- [System.Security.SecurityCritical] // auto-generated
-#if !FEATURE_CORECLR
- [DllImport(Win32Native.SHIM, EntryPoint="ND_RU1")]
- [SuppressUnmanagedCodeSecurity]
- public static extern byte ReadByte([MarshalAs(UnmanagedType.AsAny), In] Object ptr, int ofs);
-#else
public static byte ReadByte([MarshalAs(UnmanagedType.AsAny), In] Object ptr, int ofs)
{
throw new PlatformNotSupportedException();
- }
-#endif // !FEATURE_CORECLR
+ }
- [System.Security.SecurityCritical] // auto-generated_required
public static unsafe byte ReadByte(IntPtr ptr, int ofs)
{
try
}
}
- [System.Security.SecurityCritical] // auto-generated_required
public static byte ReadByte(IntPtr ptr)
{
return ReadByte(ptr,0);
}
-
- [System.Security.SecurityCritical] // auto-generated
-#if !FEATURE_CORECLR
- [DllImport(Win32Native.SHIM, EntryPoint="ND_RI2")]
- [SuppressUnmanagedCodeSecurity]
- public static extern short ReadInt16([MarshalAs(UnmanagedType.AsAny),In] Object ptr, int ofs);
-#else
+
public static short ReadInt16([MarshalAs(UnmanagedType.AsAny),In] Object ptr, int ofs)
{
throw new PlatformNotSupportedException();
- }
-#endif // !FEATURE_CORECLR
+ }
- [System.Security.SecurityCritical] // auto-generated_required
public static unsafe short ReadInt16(IntPtr ptr, int ofs)
{
try
}
}
- [System.Security.SecurityCritical] // auto-generated_required
public static short ReadInt16(IntPtr ptr)
{
return ReadInt16(ptr, 0);
}
-
- [System.Security.SecurityCritical] // auto-generated
-#if !FEATURE_CORECLR
- [DllImport(Win32Native.SHIM, EntryPoint="ND_RI4"), ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)]
- [SuppressUnmanagedCodeSecurity]
- public static extern int ReadInt32([MarshalAs(UnmanagedType.AsAny),In] Object ptr, int ofs);
-#else
+
public static int ReadInt32([MarshalAs(UnmanagedType.AsAny),In] Object ptr, int ofs)
{
throw new PlatformNotSupportedException();
}
-#endif // !FEATURE_CORECLR
- [System.Security.SecurityCritical] // auto-generated_required
[ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)]
public static unsafe int ReadInt32(IntPtr ptr, int ofs)
{
}
}
- [System.Security.SecurityCritical] // auto-generated_required
[ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)]
public static int ReadInt32(IntPtr ptr)
{
return ReadInt32(ptr,0);
}
- [System.Security.SecurityCritical] // auto-generated_required
[ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)]
public static IntPtr ReadIntPtr([MarshalAs(UnmanagedType.AsAny),In] Object ptr, int ofs)
{
#endif
}
- [System.Security.SecurityCritical] // auto-generated_required
[ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)]
public static IntPtr ReadIntPtr(IntPtr ptr, int ofs)
{
#endif
}
- [System.Security.SecurityCritical] // auto-generated_required
[ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)]
public static IntPtr ReadIntPtr(IntPtr ptr)
{
#endif
}
- [System.Security.SecurityCritical] // auto-generated
-#if !FEATURE_CORECLR
- [DllImport(Win32Native.SHIM, EntryPoint="ND_RI8"), ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)]
- [SuppressUnmanagedCodeSecurity]
- public static extern long ReadInt64([MarshalAs(UnmanagedType.AsAny),In] Object ptr, int ofs);
-#else
public static long ReadInt64([MarshalAs(UnmanagedType.AsAny),In] Object ptr, int ofs)
{
throw new PlatformNotSupportedException();
}
-#endif // !FEATURE_CORECLR
- [System.Security.SecurityCritical] // auto-generated_required
public static unsafe long ReadInt64(IntPtr ptr, int ofs)
{
try
}
}
- [System.Security.SecurityCritical] // auto-generated_required
[ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)]
public static long ReadInt64(IntPtr ptr)
{
//====================================================================
// Write to memory
//====================================================================
- [System.Security.SecurityCritical] // auto-generated_required
public static unsafe void WriteByte(IntPtr ptr, int ofs, byte val)
{
try
}
}
- [System.Security.SecurityCritical] // auto-generated
-#if !FEATURE_CORECLR
- [DllImport(Win32Native.SHIM, EntryPoint="ND_WU1")]
- [SuppressUnmanagedCodeSecurity]
- public static extern void WriteByte([MarshalAs(UnmanagedType.AsAny),In,Out] Object ptr, int ofs, byte val);
-#else
public static void WriteByte([MarshalAs(UnmanagedType.AsAny),In,Out] Object ptr, int ofs, byte val)
{
throw new PlatformNotSupportedException();
}
-#endif // !FEATURE_CORECLR
- [System.Security.SecurityCritical] // auto-generated_required
public static void WriteByte(IntPtr ptr, byte val)
{
WriteByte(ptr, 0, val);
}
- [System.Security.SecurityCritical] // auto-generated_required
public static unsafe void WriteInt16(IntPtr ptr, int ofs, short val)
{
try
throw new AccessViolationException();
}
}
-
- [System.Security.SecurityCritical] // auto-generated
-#if !FEATURE_CORECLR
- [DllImport(Win32Native.SHIM, EntryPoint="ND_WI2")]
- [SuppressUnmanagedCodeSecurity]
- public static extern void WriteInt16([MarshalAs(UnmanagedType.AsAny),In,Out] Object ptr, int ofs, short val);
-#else
+
public static void WriteInt16([MarshalAs(UnmanagedType.AsAny),In,Out] Object ptr, int ofs, short val)
{
throw new PlatformNotSupportedException();
}
-#endif // !FEATURE_CORECLR
-
- [System.Security.SecurityCritical] // auto-generated_required
+
public static void WriteInt16(IntPtr ptr, short val)
{
WriteInt16(ptr, 0, val);
}
- [System.Security.SecurityCritical] // auto-generated_required
public static void WriteInt16(IntPtr ptr, int ofs, char val)
{
WriteInt16(ptr, ofs, (short)val);
}
- [System.Security.SecurityCritical] // auto-generated_required
public static void WriteInt16([In,Out]Object ptr, int ofs, char val)
{
WriteInt16(ptr, ofs, (short)val);
}
- [System.Security.SecurityCritical] // auto-generated_required
public static void WriteInt16(IntPtr ptr, char val)
{
WriteInt16(ptr, 0, (short)val);
}
- [System.Security.SecurityCritical] // auto-generated_required
public static unsafe void WriteInt32(IntPtr ptr, int ofs, int val)
{
try
throw new AccessViolationException();
}
}
-
- [System.Security.SecurityCritical] // auto-generated
-#if !FEATURE_CORECLR
- [DllImport(Win32Native.SHIM, EntryPoint="ND_WI4")]
- [SuppressUnmanagedCodeSecurity]
- public static extern void WriteInt32([MarshalAs(UnmanagedType.AsAny),In,Out] Object ptr, int ofs, int val);
-#else
+
public static void WriteInt32([MarshalAs(UnmanagedType.AsAny),In,Out] Object ptr, int ofs, int val)
{
throw new PlatformNotSupportedException();
}
-#endif // !FEATURE_CORECLR
- [System.Security.SecurityCritical] // auto-generated_required
public static void WriteInt32(IntPtr ptr, int val)
{
WriteInt32(ptr,0,val);
}
- [System.Security.SecurityCritical] // auto-generated_required
public static void WriteIntPtr(IntPtr ptr, int ofs, IntPtr val)
{
#if BIT64
#endif
}
- [System.Security.SecurityCritical] // auto-generated_required
public static void WriteIntPtr([MarshalAs(UnmanagedType.AsAny),In,Out] Object ptr, int ofs, IntPtr val)
{
#if BIT64
#endif
}
- [System.Security.SecurityCritical] // auto-generated_required
public static void WriteIntPtr(IntPtr ptr, IntPtr val)
{
#if BIT64
#endif
}
- [System.Security.SecurityCritical] // auto-generated_required
public static unsafe void WriteInt64(IntPtr ptr, int ofs, long val)
{
try
throw new AccessViolationException();
}
}
-
- [System.Security.SecurityCritical] // auto-generated
-#if !FEATURE_CORECLR
- [DllImport(Win32Native.SHIM, EntryPoint="ND_WI8")]
- [SuppressUnmanagedCodeSecurity]
- public static extern void WriteInt64([MarshalAs(UnmanagedType.AsAny),In,Out] Object ptr, int ofs, long val);
-#else
+
public static void WriteInt64([MarshalAs(UnmanagedType.AsAny),In,Out] Object ptr, int ofs, long val)
{
throw new PlatformNotSupportedException();
}
-#endif // !FEATURE_CORECLR
- [System.Security.SecurityCritical] // auto-generated_required
public static void WriteInt64(IntPtr ptr, long val)
{
WriteInt64(ptr, 0, val);
//====================================================================
// GetLastWin32Error
//====================================================================
- [System.Security.SecurityCritical] // auto-generated_required
[MethodImplAttribute(MethodImplOptions.InternalCall)]
[ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)]
public static extern int GetLastWin32Error();
//====================================================================
// GetHRForLastWin32Error
//====================================================================
- [System.Security.SecurityCritical] // auto-generated_required
[ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)]
public static int GetHRForLastWin32Error()
{
//====================================================================
// Prelink
//====================================================================
- [System.Security.SecurityCritical] // auto-generated_required
public static void Prelink(MethodInfo m)
{
if (m == null)
}
[DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode), SuppressUnmanagedCodeSecurity]
- [SecurityCritical]
private static extern void InternalPrelink(IRuntimeMethodInfo m);
- [System.Security.SecurityCritical] // auto-generated_required
public static void PrelinkAll(Type c)
{
if (c == null)
//====================================================================
// NumParamBytes
//====================================================================
- [System.Security.SecurityCritical] // auto-generated_required
public static int NumParamBytes(MethodInfo m)
{
if (m == null)
}
[DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode), SuppressUnmanagedCodeSecurity]
- [SecurityCritical]
private static extern int InternalNumParamBytes(IRuntimeMethodInfo m);
//====================================================================
// These are mostly interesting for Structured exception handling,
// but need to be exposed for all exceptions (not just SEHException).
//====================================================================
- [System.Security.SecurityCritical] // auto-generated_required
[MethodImplAttribute(MethodImplOptions.InternalCall)]
[System.Runtime.InteropServices.ComVisible(true)]
public static extern /* struct _EXCEPTION_POINTERS* */ IntPtr GetExceptionPointers();
- [System.Security.SecurityCritical] // auto-generated_required
[MethodImplAttribute(MethodImplOptions.InternalCall)]
public static extern int GetExceptionCode();
// If the structure contains pointers to allocated blocks and
// "fDeleteOld" is true, this routine will call DestroyStructure() first.
//====================================================================
- [System.Security.SecurityCritical] // auto-generated_required
[MethodImplAttribute(MethodImplOptions.InternalCall), ReliabilityContract(Consistency.WillNotCorruptState, Cer.MayFail)]
[System.Runtime.InteropServices.ComVisible(true)]
public static extern void StructureToPtr(Object structure, IntPtr ptr, bool fDeleteOld);
- [System.Security.SecurityCritical]
public static void StructureToPtr<T>(T structure, IntPtr ptr, bool fDeleteOld)
{
StructureToPtr((object)structure, ptr, fDeleteOld);
//====================================================================
// Marshals data from a native memory block to a preallocated structure class.
//====================================================================
- [System.Security.SecurityCritical] // auto-generated_required
[System.Runtime.InteropServices.ComVisible(true)]
public static void PtrToStructure(IntPtr ptr, Object structure)
{
PtrToStructureHelper(ptr, structure, false);
}
- [System.Security.SecurityCritical]
public static void PtrToStructure<T>(IntPtr ptr, T structure)
{
PtrToStructure(ptr, (object)structure);
// Creates a new instance of "structuretype" and marshals data from a
// native memory block to it.
//====================================================================
- [System.Security.SecurityCritical] // auto-generated_required
[System.Runtime.InteropServices.ComVisible(true)]
[MethodImplAttribute(MethodImplOptions.NoInlining)] // Methods containing StackCrawlMark local var has to be marked non-inlineable
public static Object PtrToStructure(IntPtr ptr, Type structureType)
return structure;
}
- [System.Security.SecurityCritical]
public static T PtrToStructure<T>(IntPtr ptr)
{
return (T)PtrToStructure(ptr, typeof(T));
// Freeds all substructures pointed to by the native memory block.
// "structureclass" is used to provide layout information.
//====================================================================
- [System.Security.SecurityCritical] // auto-generated_required
[MethodImplAttribute(MethodImplOptions.InternalCall)]
[System.Runtime.InteropServices.ComVisible(true)]
public static extern void DestroyStructure(IntPtr ptr, Type structuretype);
- [System.Security.SecurityCritical]
public static void DestroyStructure<T>(IntPtr ptr)
{
DestroyStructure(ptr, typeof(T));
// doesn't have an HInstance. In Memory (Dynamic) Modules won't have
// an HInstance.
//====================================================================
- [System.Security.SecurityCritical] // auto-generated_required
public static IntPtr GetHINSTANCE(Module m)
{
if (m == null)
return GetHINSTANCE(rtModule.GetNativeHandle());
}
- [System.Security.SecurityCritical] // auto-generated_required
[SuppressUnmanagedCodeSecurity]
[DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode), SuppressUnmanagedCodeSecurity]
private extern static IntPtr GetHINSTANCE(RuntimeModule m);
//====================================================================
// Throws a CLR exception based on the HRESULT.
//====================================================================
- [System.Security.SecurityCritical] // auto-generated_required
public static void ThrowExceptionForHR(int errorCode)
{
if (errorCode < 0)
ThrowExceptionForHRInternal(errorCode, IntPtr.Zero);
}
- [System.Security.SecurityCritical] // auto-generated_required
public static void ThrowExceptionForHR(int errorCode, IntPtr errorInfo)
{
if (errorCode < 0)
//====================================================================
// Converts the HRESULT to a CLR exception.
//====================================================================
- [System.Security.SecurityCritical] // auto-generated_required
public static Exception GetExceptionForHR(int errorCode)
{
if (errorCode < 0)
else
return null;
}
- [System.Security.SecurityCritical] // auto-generated_required
public static Exception GetExceptionForHR(int errorCode, IntPtr errorInfo)
{
if (errorCode < 0)
// This method is intended for compiler code generators rather
// than applications.
//====================================================================
- [System.Security.SecurityCritical] // auto-generated_required
[ObsoleteAttribute("The GetUnmanagedThunkForManagedMethodPtr method has been deprecated and will be removed in a future release.", false)]
[MethodImplAttribute(MethodImplOptions.InternalCall)]
public static extern IntPtr GetUnmanagedThunkForManagedMethodPtr(IntPtr pfnMethodToWrap, IntPtr pbSignature, int cbSignature);
// This method is intended for compiler code generators rather
// than applications.
//====================================================================
- [System.Security.SecurityCritical] // auto-generated_required
[ObsoleteAttribute("The GetManagedThunkForUnmanagedMethodPtr method has been deprecated and will be removed in a future release.", false)]
[MethodImplAttribute(MethodImplOptions.InternalCall)]
public static extern IntPtr GetManagedThunkForUnmanagedMethodPtr(IntPtr pfnMethodToWrap, IntPtr pbSignature, int cbSignature);
// activity. A fiber cookie can be redeemed for its managed Thread
// object by calling the following service.
//====================================================================
- [System.Security.SecurityCritical] // auto-generated_required
[ObsoleteAttribute("The GetThreadFromFiberCookie method has been deprecated. Use the hosting API to perform this operation.", false)]
public static Thread GetThreadFromFiberCookie(int cookie)
{
//====================================================================
// Memory allocation and deallocation.
//====================================================================
- [System.Security.SecurityCritical] // auto-generated_required
[ReliabilityContract(Consistency.WillNotCorruptState, Cer.MayFail)]
public static IntPtr AllocHGlobal(IntPtr cb)
{
return pNewMem;
}
- [System.Security.SecurityCritical] // auto-generated_required
[ReliabilityContract(Consistency.WillNotCorruptState, Cer.MayFail)]
public static IntPtr AllocHGlobal(int cb)
{
return AllocHGlobal((IntPtr)cb);
}
- [System.Security.SecurityCritical] // auto-generated_required
[ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)]
public static void FreeHGlobal(IntPtr hglobal)
{
}
}
- [System.Security.SecurityCritical] // auto-generated_required
public static IntPtr ReAllocHGlobal(IntPtr pv, IntPtr cb)
{
IntPtr pNewMem = Win32Native.LocalReAlloc(pv, cb, LMEM_MOVEABLE);
//====================================================================
// String convertions.
//====================================================================
- [System.Security.SecurityCritical] // auto-generated_required
unsafe public static IntPtr StringToHGlobalAnsi(String s)
{
if (s == null)
}
}
- [System.Security.SecurityCritical] // auto-generated_required
unsafe public static IntPtr StringToHGlobalUni(String s)
{
if (s == null)
}
}
- [System.Security.SecurityCritical] // auto-generated_required
public static IntPtr StringToHGlobalAuto(String s)
{
// Ansi platforms are no longer supported
// Converts the CLR exception to an HRESULT. This function also sets
// up an IErrorInfo for the exception.
//====================================================================
- [System.Security.SecurityCritical] // auto-generated_required
[MethodImplAttribute(MethodImplOptions.InternalCall)]
public static extern int GetHRForException(Exception e);
// This function is only used in WinRT and converts ObjectDisposedException
// to RO_E_CLOSED
//====================================================================
- [System.Security.SecurityCritical] // auto-generated_required
[MethodImplAttribute(MethodImplOptions.InternalCall)]
internal static extern int GetHRForException_WinRT(Exception e);
//====================================================================
// Given a managed object that wraps a UCOMITypeLib, return its name
//====================================================================
- [System.Security.SecurityCritical] // auto-generated_required
[Obsolete("Use System.Runtime.InteropServices.Marshal.GetTypeLibName(ITypeLib pTLB) instead. http://go.microsoft.com/fwlink/?linkid=14202&ID=0000011.", false)]
public static String GetTypeLibName(UCOMITypeLib pTLB)
{
//====================================================================
// Given a managed object that wraps an ITypeLib, return its name
//====================================================================
- [System.Security.SecurityCritical] // auto-generated_required
public static String GetTypeLibName(ITypeLib typelib)
{
if (typelib == null)
// Internal version of GetTypeLibName
// Support GUID_ManagedName which aligns with TlbImp
//====================================================================
- [System.Security.SecurityCritical] // auto-generated_required
internal static String GetTypeLibNameInternal(ITypeLib typelib)
{
if (typelib == null)
//====================================================================
// Given an managed object that wraps an UCOMITypeLib, return its guid
//====================================================================
- [System.Security.SecurityCritical] // auto-generated_required
[Obsolete("Use System.Runtime.InteropServices.Marshal.GetTypeLibGuid(ITypeLib pTLB) instead. http://go.microsoft.com/fwlink/?linkid=14202&ID=0000011.", false)]
public static Guid GetTypeLibGuid(UCOMITypeLib pTLB)
{
//====================================================================
// Given an managed object that wraps an ITypeLib, return its guid
//====================================================================
- [System.Security.SecurityCritical] // auto-generated_required
public static Guid GetTypeLibGuid(ITypeLib typelib)
{
Guid result = new Guid ();
//====================================================================
// Given a managed object that wraps a UCOMITypeLib, return its lcid
//====================================================================
- [System.Security.SecurityCritical] // auto-generated_required
[Obsolete("Use System.Runtime.InteropServices.Marshal.GetTypeLibLcid(ITypeLib pTLB) instead. http://go.microsoft.com/fwlink/?linkid=14202&ID=0000011.", false)]
public static int GetTypeLibLcid(UCOMITypeLib pTLB)
{
//====================================================================
// Given a managed object that wraps an ITypeLib, return its lcid
//====================================================================
- [System.Security.SecurityCritical] // auto-generated_required
[MethodImplAttribute(MethodImplOptions.InternalCall)]
public static extern int GetTypeLibLcid(ITypeLib typelib);
//====================================================================
// Given a managed object that wraps an ITypeInfo, return its guid.
//====================================================================
- [System.Security.SecurityCritical] // auto-generated
internal static Guid GetTypeInfoGuid(ITypeInfo typeInfo)
{
Guid result = new Guid ();
// Given a assembly, return the TLBID that will be generated for the
// typelib exported from the assembly.
//====================================================================
- [System.Security.SecurityCritical] // auto-generated_required
public static Guid GetTypeLibGuidForAssembly(Assembly asm)
{
if (asm == null)
[MethodImplAttribute(MethodImplOptions.InternalCall)]
private static extern void _GetTypeLibVersionForAssembly(RuntimeAssembly inputAssembly, out int majorVersion, out int minorVersion);
- [System.Security.SecurityCritical] // auto-generated_required
public static void GetTypeLibVersionForAssembly(Assembly inputAssembly, out int majorVersion, out int minorVersion)
{
if (inputAssembly == null)
//====================================================================
// Given a managed object that wraps an UCOMITypeInfo, return its name
//====================================================================
- [System.Security.SecurityCritical] // auto-generated_required
[Obsolete("Use System.Runtime.InteropServices.Marshal.GetTypeInfoName(ITypeInfo pTLB) instead. http://go.microsoft.com/fwlink/?linkid=14202&ID=0000011.", false)]
public static String GetTypeInfoName(UCOMITypeInfo pTI)
{
//====================================================================
// Given a managed object that wraps an ITypeInfo, return its name
//====================================================================
- [System.Security.SecurityCritical] // auto-generated_required
public static String GetTypeInfoName(ITypeInfo typeInfo)
{
if (typeInfo == null)
// Internal version of GetTypeInfoName
// Support GUID_ManagedName which aligns with TlbImp
//====================================================================
- [System.Security.SecurityCritical] // auto-generated_required
internal static String GetTypeInfoNameInternal(ITypeInfo typeInfo, out bool hasManagedName)
{
if (typeInfo == null)
// Get the corresponding managed name as converted by TlbImp
// Used to get the type using GetType() from imported assemblies
//====================================================================
- [System.Security.SecurityCritical] // auto-generated_required
internal static String GetManagedTypeInfoNameInternal(ITypeLib typeLib, ITypeInfo typeInfo)
{
bool hasManagedName;
[MethodImplAttribute(MethodImplOptions.InternalCall)]
private static extern Type GetLoadedTypeForGUID(ref Guid guid);
-#if !FEATURE_CORECLR // current implementation requires reflection only load
- //====================================================================
- // map ITypeInfo* to Type
- //====================================================================
- [System.Security.SecurityCritical] // auto-generated_required
- public static Type GetTypeForITypeInfo(IntPtr /* ITypeInfo* */ piTypeInfo)
- {
- ITypeInfo pTI = null;
- ITypeLib pTLB = null;
- Type TypeObj = null;
- Assembly AsmBldr = null;
- TypeLibConverter TlbConverter = null;
- int Index = 0;
- Guid clsid;
-
- // If the input ITypeInfo is NULL then return NULL.
- if (piTypeInfo == IntPtr.Zero)
- return null;
-
- // Wrap the ITypeInfo in a CLR object.
- pTI = (ITypeInfo)GetObjectForIUnknown(piTypeInfo);
-
- // Check to see if a class exists with the specified GUID.
-
- clsid = GetTypeInfoGuid(pTI);
- TypeObj = GetLoadedTypeForGUID(ref clsid);
-
- // If we managed to find the type based on the GUID then return it.
- if (TypeObj != null)
- return TypeObj;
-
- // There is no type with the specified GUID in the app domain so lets
- // try and convert the containing typelib.
- try
- {
- pTI.GetContainingTypeLib(out pTLB, out Index);
- }
- catch(COMException)
- {
- pTLB = null;
- }
-
- // Check to see if we managed to get a containing typelib.
- if (pTLB != null)
- {
- // Get the assembly name from the typelib.
- AssemblyName AsmName = TypeLibConverter.GetAssemblyNameFromTypelib(pTLB, null, null, null, null, AssemblyNameFlags.None);
- String AsmNameString = AsmName.FullName;
-
- // Check to see if the assembly that will contain the type already exists.
- Assembly[] aAssemblies = Thread.GetDomain().GetAssemblies();
- int NumAssemblies = aAssemblies.Length;
- for (int i = 0; i < NumAssemblies; i++)
- {
- if (String.Compare(aAssemblies[i].FullName,
- AsmNameString,StringComparison.Ordinal) == 0)
- AsmBldr = aAssemblies[i];
- }
-
- // If we haven't imported the assembly yet then import it.
- if (AsmBldr == null)
- {
- TlbConverter = new TypeLibConverter();
- AsmBldr = TlbConverter.ConvertTypeLibToAssembly(pTLB,
- GetTypeLibName(pTLB) + ".dll", 0, new ImporterCallback(), null, null, null, null);
- }
-
- // Load the type object from the imported typelib.
- // Call GetManagedTypeInfoNameInternal to align with TlbImp behavior
- TypeObj = AsmBldr.GetType(GetManagedTypeInfoNameInternal(pTLB, pTI), true, false);
- if (TypeObj != null && !TypeObj.IsVisible)
- TypeObj = null;
- }
- else
- {
- // If the ITypeInfo does not have a containing typelib then simply
- // return Object as the type.
- TypeObj = typeof(Object);
- }
-
- return TypeObj;
- }
-#endif // #if !FEATURE_CORECLR
-
// This method is identical to Type.GetTypeFromCLSID. Since it's interop specific, we expose it
// on Marshal for more consistent API surface.
-#if !FEATURE_CORECLR
- [System.Security.SecuritySafeCritical]
-#endif //!FEATURE_CORECLR
public static Type GetTypeFromCLSID(Guid clsid)
{
return RuntimeType.GetTypeFromCLSIDImpl(clsid, null, false);
//====================================================================
// map Type to ITypeInfo*
//====================================================================
- [System.Security.SecurityCritical] // auto-generated_required
[MethodImplAttribute(MethodImplOptions.InternalCall)]
public static extern IntPtr /* ITypeInfo* */ GetITypeInfoForType(Type t);
// is the one where the RCW was first seen. Will return null
// otherwise.
//====================================================================
- [System.Security.SecurityCritical] // auto-generated_required
public static IntPtr /* IUnknown* */ GetIUnknownForObject(Object o)
{
return GetIUnknownForObjectNative(o, false);
}
- [System.Security.SecurityCritical] // auto-generated_required
public static IntPtr /* IUnknown* */ GetIUnknownForObjectInContext(Object o)
{
return GetIUnknownForObjectNative(o, true);
//====================================================================
// return the IDispatch* for an Object
//====================================================================
- [System.Security.SecurityCritical] // auto-generated_required
public static IntPtr /* IDispatch */ GetIDispatchForObject(Object o)
{
-#if FEATURE_CORECLR
throw new PlatformNotSupportedException();
-#else
- return GetIDispatchForObjectNative(o, false);
-#endif // FEATURE_CORECLR
}
#if FEATURE_COMINTEROP
// is the one where the RCW was first seen. Will return null
// otherwise.
//====================================================================
- [System.Security.SecurityCritical] // auto-generated_required
public static IntPtr /* IUnknown* */ GetIDispatchForObjectInContext(Object o)
{
return GetIDispatchForObjectNative(o, true);
// return the IUnknown* representing the interface for the Object
// Object o should support Type T
//====================================================================
- [System.Security.SecurityCritical] // auto-generated_required
public static IntPtr /* IUnknown* */ GetComInterfaceForObject(Object o, Type T)
{
return GetComInterfaceForObjectNative(o, T, false, true);
}
- [System.Security.SecurityCritical]
public static IntPtr GetComInterfaceForObject<T, TInterface>(T o)
{
return GetComInterfaceForObject(o, typeof(TInterface));
// Object o should support Type T, it refer the value of mode to
// invoke customized QueryInterface or not
//====================================================================
- [System.Security.SecurityCritical] // auto-generated_required
public static IntPtr /* IUnknown* */ GetComInterfaceForObject(Object o, Type T, CustomQueryInterfaceMode mode)
{
bool bEnableCustomizedQueryInterface = ((mode == CustomQueryInterfaceMode.Allow) ? true : false);
// is the one where the RCW was first seen. Will return null
// otherwise.
//====================================================================
- [System.Security.SecurityCritical] // auto-generated_required
public static IntPtr /* IUnknown* */ GetComInterfaceForObjectInContext(Object o, Type t)
{
return GetComInterfaceForObjectNative(o, t, true, true);
//====================================================================
// return an Object for IUnknown
//====================================================================
- [System.Security.SecurityCritical] // auto-generated_required
[MethodImplAttribute(MethodImplOptions.InternalCall)]
public static extern Object GetObjectForIUnknown(IntPtr /* IUnknown* */ pUnk);
// where you want to be able to call ReleaseComObject on a RCW
// and not worry about other active uses of said RCW.
//====================================================================
- [System.Security.SecurityCritical] // auto-generated_required
[MethodImplAttribute(MethodImplOptions.InternalCall)]
public static extern Object GetUniqueObjectForIUnknown(IntPtr unknown);
// Type T should be either a COM imported Type or a sub-type of COM
// imported Type
//====================================================================
- [System.Security.SecurityCritical] // auto-generated_required
[MethodImplAttribute(MethodImplOptions.InternalCall)]
public static extern Object GetTypedObjectForIUnknown(IntPtr /* IUnknown* */ pUnk, Type t);
- [System.Security.SecurityCritical] // auto-generated_required
[MethodImplAttribute(MethodImplOptions.InternalCall)]
public static extern IntPtr CreateAggregatedObject(IntPtr pOuter, Object o);
- [System.Security.SecurityCritical]
public static IntPtr CreateAggregatedObject<T>(IntPtr pOuter, T o)
{
return CreateAggregatedObject(pOuter, (object)o);
}
- [System.Security.SecurityCritical] // auto-generated_required
[MethodImplAttribute(MethodImplOptions.InternalCall)]
public static extern void CleanupUnusedObjectsInCurrentContext();
- [System.Security.SecurityCritical]
[MethodImplAttribute(MethodImplOptions.InternalCall)]
public static extern bool AreComObjectsAvailableForCleanup();
//====================================================================
// check if the object is classic COM component
//====================================================================
-#if !FEATURE_CORECLR // with FEATURE_CORECLR, the whole type is SecurityCritical
- [System.Security.SecuritySafeCritical]
-#endif
[MethodImplAttribute(MethodImplOptions.InternalCall)]
public static extern bool IsComObject(Object o);
#endif // FEATURE_COMINTEROP
- [System.Security.SecurityCritical] // auto-generated_required
public static IntPtr AllocCoTaskMem(int cb)
{
IntPtr pNewMem = Win32Native.CoTaskMemAlloc(new UIntPtr((uint)cb));
return pNewMem;
}
- [System.Security.SecurityCritical] // auto-generated_required
unsafe public static IntPtr StringToCoTaskMemUni(String s)
{
if (s == null)
}
}
- [System.Security.SecurityCritical] // auto-generated_required
unsafe public static IntPtr StringToCoTaskMemUTF8(String s)
{
const int MAX_UTF8_CHAR_SIZE = 3;
}
}
- [System.Security.SecurityCritical] // auto-generated_required
public static IntPtr StringToCoTaskMemAuto(String s)
{
// Ansi platforms are no longer supported
return StringToCoTaskMemUni(s);
}
- [System.Security.SecurityCritical] // auto-generated_required
unsafe public static IntPtr StringToCoTaskMemAnsi(String s)
{
if (s == null)
}
}
- [System.Security.SecurityCritical] // auto-generated_required
public static void FreeCoTaskMem(IntPtr ptr)
{
if (IsNotWin32Atom(ptr)) {
}
}
- [System.Security.SecurityCritical] // auto-generated_required
public static IntPtr ReAllocCoTaskMem(IntPtr pv, int cb)
{
IntPtr pNewMem = Win32Native.CoTaskMemRealloc(pv, new UIntPtr((uint)cb));
//====================================================================
// BSTR allocation and dealocation.
//====================================================================
- [System.Security.SecurityCritical] // auto-generated_required
public static void FreeBSTR(IntPtr ptr)
{
if (IsNotWin32Atom(ptr))
}
}
- [System.Security.SecurityCritical] // auto-generated_required
public static IntPtr StringToBSTR(String s)
{
if (s == null)
return bstr;
}
- [System.Security.SecurityCritical] // auto-generated_required
public static String PtrToStringBSTR(IntPtr ptr)
{
return PtrToStringUni(ptr, (int)Win32Native.SysStringLen(ptr));
// release the COM component and if the reference hits 0 zombie this object
// further usage of this Object might throw an exception
//====================================================================
- [System.Security.SecurityCritical] // auto-generated_required
public static int ReleaseComObject(Object o)
{
__ComObject co = null;
// release the COM component and zombie this object
// further usage of this Object might throw an exception
//====================================================================
- [System.Security.SecurityCritical] // auto-generated_required
public static Int32 FinalReleaseComObject(Object o)
{
if (o == null)
//====================================================================
// This method retrieves data from the COM object.
//====================================================================
- [System.Security.SecurityCritical] // auto-generated_required
public static Object GetComObjectData(Object obj, Object key)
{
-#if FEATURE_CORECLR
throw new PlatformNotSupportedException();
-#else
- // Validate that the arguments aren't null.
- if (obj == null)
- throw new ArgumentNullException(nameof(obj));
- if (key == null)
- throw new ArgumentNullException(nameof(key));
- Contract.EndContractBlock();
-
- __ComObject comObj = null;
-
- // Make sure the obj is an __ComObject.
- try
- {
- comObj = (__ComObject)obj;
- }
- catch (InvalidCastException)
- {
- throw new ArgumentException(Environment.GetResourceString("Argument_ObjNotComObject"), nameof(obj));
- }
-
- if (obj.GetType().IsWindowsRuntimeObject)
- {
- throw new ArgumentException(Environment.GetResourceString("Argument_ObjIsWinRTObject"), nameof(obj));
- }
-
- // Retrieve the data from the __ComObject.
- return comObj.GetData(key);
-#endif // FEATURE_CORECLR
}
//====================================================================
// true if the data has been added, false if the data could not be
// added because there already was data for the specified key.
//====================================================================
- [System.Security.SecurityCritical] // auto-generated_required
public static bool SetComObjectData(Object obj, Object key, Object data)
{
-#if FEATURE_CORECLR
throw new PlatformNotSupportedException();
-#else
- // Validate that the arguments aren't null. The data can validly be null.
- if (obj == null)
- throw new ArgumentNullException(nameof(obj));
- if (key == null)
- throw new ArgumentNullException(nameof(key));
- Contract.EndContractBlock();
-
- __ComObject comObj = null;
-
- // Make sure the obj is an __ComObject.
- try
- {
- comObj = (__ComObject)obj;
- }
- catch (InvalidCastException)
- {
- throw new ArgumentException(Environment.GetResourceString("Argument_ObjNotComObject"), nameof(obj));
- }
-
- if (obj.GetType().IsWindowsRuntimeObject)
- {
- throw new ArgumentException(Environment.GetResourceString("Argument_ObjIsWinRTObject"), nameof(obj));
- }
-
- // Retrieve the data from the __ComObject.
- return comObj.SetData(key, data);
-#endif // FEATURE_CORECLR
}
#if FEATURE_COMINTEROP
// This method takes the given COM object and wraps it in an object
// of the specified type. The type must be derived from __ComObject.
//====================================================================
- [System.Security.SecurityCritical] // auto-generated_required
public static Object CreateWrapperOfType(Object o, Type t)
{
// Validate the arguments.
return Wrapper;
}
- [System.Security.SecurityCritical]
public static TWrapper CreateWrapperOfType<T, TWrapper>(T o)
{
return (TWrapper)CreateWrapperOfType(o, typeof(TWrapper));
//====================================================================
// Helper method called from CreateWrapperOfType.
//====================================================================
- [System.Security.SecurityCritical] // auto-generated_required
[MethodImplAttribute(MethodImplOptions.InternalCall)]
private static extern Object InternalCreateWrapperOfType(Object o, Type t);
// There may be a thread-based cache of COM components. This service can
// force the aggressive release of the current thread's cache.
//====================================================================
- [System.Security.SecurityCritical] // auto-generated_required
[Obsolete("This API did not perform any operation and will be removed in future versions of the CLR.", false)]
public static void ReleaseThreadCache()
{
//====================================================================
// check if the type is visible from COM.
//====================================================================
- [System.Security.SecuritySafeCritical]
[MethodImplAttribute(MethodImplOptions.InternalCall)]
public static extern bool IsTypeVisibleFromCom(Type t);
//====================================================================
// IUnknown Helpers
//====================================================================
- [System.Security.SecurityCritical] // auto-generated_required
[MethodImplAttribute(MethodImplOptions.InternalCall)]
public static extern int /* HRESULT */ QueryInterface(IntPtr /* IUnknown */ pUnk, ref Guid iid, out IntPtr ppv);
- [System.Security.SecurityCritical] // auto-generated_required
[MethodImplAttribute(MethodImplOptions.InternalCall)]
public static extern int /* ULONG */ AddRef(IntPtr /* IUnknown */ pUnk );
- [System.Security.SecurityCritical] // auto-generated_required
[MethodImplAttribute(MethodImplOptions.InternalCall)]
[ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)]
public static extern int /* ULONG */ Release(IntPtr /* IUnknown */ pUnk );
- [System.Security.SecurityCritical] // auto-generated_required
[MethodImplAttribute(MethodImplOptions.InternalCall)]
public static extern void GetNativeVariantForObject(Object obj, /* VARIANT * */ IntPtr pDstNativeVariant);
- [System.Security.SecurityCritical]
public static void GetNativeVariantForObject<T>(T obj, IntPtr pDstNativeVariant)
{
GetNativeVariantForObject((object)obj, pDstNativeVariant);
}
- [System.Security.SecurityCritical] // auto-generated_required
[MethodImplAttribute(MethodImplOptions.InternalCall)]
public static extern Object GetObjectForNativeVariant(/* VARIANT * */ IntPtr pSrcNativeVariant );
- [System.Security.SecurityCritical]
public static T GetObjectForNativeVariant<T>(IntPtr pSrcNativeVariant)
{
return (T)GetObjectForNativeVariant(pSrcNativeVariant);
}
- [System.Security.SecurityCritical] // auto-generated_required
[MethodImplAttribute(MethodImplOptions.InternalCall)]
public static extern Object[] GetObjectsForNativeVariants(/* VARIANT * */ IntPtr aSrcNativeVariant, int cVars );
- [System.Security.SecurityCritical]
public static T[] GetObjectsForNativeVariants<T>(IntPtr aSrcNativeVariant, int cVars)
{
object[] objects = GetObjectsForNativeVariants(aSrcNativeVariant, cVars);
/// <para>Returns the first valid COM slot that GetMethodInfoForSlot will work on
/// This will be 3 for IUnknown based interfaces and 7 for IDispatch based interfaces. </para>
/// </summary>
- [System.Security.SecurityCritical] // auto-generated_required
[MethodImplAttribute(MethodImplOptions.InternalCall)]
public static extern int GetStartComSlot(Type t);
/// <summary>
/// <para>Returns the last valid COM slot that GetMethodInfoForSlot will work on. </para>
/// </summary>
- [System.Security.SecurityCritical] // auto-generated_required
[MethodImplAttribute(MethodImplOptions.InternalCall)]
public static extern int GetEndComSlot(Type t);
/// For classes, the lookup is done on the default interface that will be
/// exposed for the class. </para>
/// </summary>
- [System.Security.SecurityCritical] // auto-generated_required
[MethodImplAttribute(MethodImplOptions.InternalCall)]
public static extern MemberInfo GetMethodInfoForComSlot(Type t, int slot, ref ComMemberType memberType);
/// <para>Returns the COM slot for a memeber info, taking into account whether
/// the exposed interface is IUnknown based or IDispatch based</para>
/// </summary>
- [System.Security.SecurityCritical] // auto-generated_required
public static int GetComSlotForMethodInfo(MemberInfo m)
{
if (m== null)
// guid GUID is generated based on the fully qualified name of the
// type.
//====================================================================
- [System.Security.SecurityCritical] // auto-generated_required
public static Guid GenerateGuidForType(Type type)
{
-#if FEATURE_CORECLR
return type.GUID;
}
-#else
- Guid result = new Guid ();
- FCallGenerateGuidForType (ref result, type);
- return result;
- }
-
- // The full assembly name is used to compute the GUID, so this should be SxS-safe
- [MethodImplAttribute(MethodImplOptions.InternalCall)]
- private static extern void FCallGenerateGuidForType(ref Guid result, Type type);
-#endif // FEATURE_CORECLR
//====================================================================
// This method generates a PROGID for the specified type. If the type
// PROGID is generated based on the fully qualified name of the
// type.
//====================================================================
- [System.Security.SecurityCritical] // auto-generated_required
public static String GenerateProgIdForType(Type type)
{
if (type == null)
throw new ArgumentException(Environment.GetResourceString("Argument_NeedNonGenericType"), nameof(type));
Contract.EndContractBlock();
-#if !FEATURE_CORECLR
- if (!RegistrationServices.TypeRequiresRegistrationHelper(type))
- throw new ArgumentException(Environment.GetResourceString("Argument_TypeMustBeComCreatable"), nameof(type));
-#endif // FEATURE_CORECLR
-
IList<CustomAttributeData> cas = CustomAttributeData.GetCustomAttributes(type);
for (int i = 0; i < cas.Count; i ++)
{
{
// Retrieve the PROGID string from the ProgIdAttribute.
IList<CustomAttributeTypedArgument> caConstructorArgs = cas[i].ConstructorArguments;
- Contract.Assert(caConstructorArgs.Count == 1, "caConstructorArgs.Count == 1");
+ Debug.Assert(caConstructorArgs.Count == 1, "caConstructorArgs.Count == 1");
CustomAttributeTypedArgument progIdConstructorArg = caConstructorArgs[0];
- Contract.Assert(progIdConstructorArg.ArgumentType == typeof(String), "progIdConstructorArg.ArgumentType == typeof(String)");
+ Debug.Assert(progIdConstructorArg.ArgumentType == typeof(String), "progIdConstructorArg.ArgumentType == typeof(String)");
String strProgId = (String)progIdConstructorArg.Value;
//====================================================================
// This method binds to the specified moniker.
//====================================================================
- [System.Security.SecurityCritical] // auto-generated_required
public static Object BindToMoniker(String monikerName)
{
Object obj = null;
//====================================================================
// This method gets the currently running object.
//====================================================================
- [System.Security.SecurityCritical] // auto-generated_required
public static Object GetActiveObject(String progID)
{
Object obj = null;
[DllImport(Microsoft.Win32.Win32Native.OLE32, PreserveSig = false)]
[SuppressUnmanagedCodeSecurity]
- [System.Security.SecurityCritical] // auto-generated
private static extern void CLSIDFromProgIDEx([MarshalAs(UnmanagedType.LPWStr)] String progId, out Guid clsid);
[DllImport(Microsoft.Win32.Win32Native.OLE32, PreserveSig = false)]
[SuppressUnmanagedCodeSecurity]
- [System.Security.SecurityCritical] // auto-generated
private static extern void CLSIDFromProgID([MarshalAs(UnmanagedType.LPWStr)] String progId, out Guid clsid);
[DllImport(Microsoft.Win32.Win32Native.OLE32, PreserveSig = false)]
[SuppressUnmanagedCodeSecurity]
- [System.Security.SecurityCritical] // auto-generated
private static extern void CreateBindCtx(UInt32 reserved, out IBindCtx ppbc);
[DllImport(Microsoft.Win32.Win32Native.OLE32, PreserveSig = false)]
[SuppressUnmanagedCodeSecurity]
- [System.Security.SecurityCritical] // auto-generated
private static extern void MkParseDisplayName(IBindCtx pbc, [MarshalAs(UnmanagedType.LPWStr)] String szUserName, out UInt32 pchEaten, out IMoniker ppmk);
[DllImport(Microsoft.Win32.Win32Native.OLE32, PreserveSig = false)]
[SuppressUnmanagedCodeSecurity]
- [System.Security.SecurityCritical] // auto-generated
private static extern void BindMoniker(IMoniker pmk, UInt32 grfOpt, ref Guid iidResult, [MarshalAs(UnmanagedType.Interface)] out Object ppvResult);
[DllImport(Microsoft.Win32.Win32Native.OLEAUT32, PreserveSig = false)]
[SuppressUnmanagedCodeSecurity]
- [System.Security.SecurityCritical] // auto-generated
private static extern void GetActiveObject(ref Guid rclsid, IntPtr reserved, [MarshalAs(UnmanagedType.Interface)] out Object ppunk);
//========================================================================
//========================================================================
// Private method called from EE upon use of license/ICF2 marshaling.
//========================================================================
- [SecurityCritical]
private static IntPtr LoadLicenseManager()
{
Assembly sys = Assembly.Load("System, Version="+ ThisAssembly.Version +
return t.TypeHandle.Value;
}
- [System.Security.SecurityCritical] // auto-generated_required
[MethodImplAttribute(MethodImplOptions.InternalCall)]
public static extern void ChangeWrapperHandleStrength(Object otp, bool fIsWeak);
- [System.Security.SecurityCritical]
[MethodImplAttribute(MethodImplOptions.InternalCall)]
internal static extern void InitializeWrapperForWinRT(object o, ref IntPtr pUnk);
#if FEATURE_COMINTEROP_WINRT_MANAGED_ACTIVATION
- [System.Security.SecurityCritical]
[MethodImplAttribute(MethodImplOptions.InternalCall)]
internal static extern void InitializeManagedWinRTFactoryObject(object o, RuntimeType runtimeClassType);
#endif
//========================================================================
// Create activation factory and wraps it with a unique RCW
//========================================================================
- [System.Security.SecurityCritical]
[MethodImplAttribute(MethodImplOptions.InternalCall)]
internal static extern object GetNativeActivationFactory(Type type);
// Methods allowing retrieval of the IIDs exposed by an underlying WinRT
// object, as specified by the object's IInspectable::GetIids()
//========================================================================
- [System.Security.SecurityCritical]
[DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode), SuppressUnmanagedCodeSecurity]
private static extern void _GetInspectableIids(ObjectHandleOnStack obj, ObjectHandleOnStack guids);
- [System.Security.SecurityCritical]
internal static System.Guid[] GetInspectableIids(object obj)
{
System.Guid[] result = null;
// Methods allowing retrieval of the cached WinRT type corresponding to
// the specified GUID
//========================================================================
- [System.Security.SecurityCritical]
[DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode), SuppressUnmanagedCodeSecurity]
private static extern void _GetCachedWinRTTypeByIid(
ObjectHandleOnStack appDomainObj,
System.Guid iid,
out IntPtr rthHandle);
- [System.Security.SecurityCritical]
internal static System.Type GetCachedWinRTTypeByIid(
System.AppDomain ad,
System.Guid iid)
// Methods allowing retrieval of the WinRT types cached in the specified
// app domain
//========================================================================
- [System.Security.SecurityCritical]
[DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode), SuppressUnmanagedCodeSecurity]
private static extern void _GetCachedWinRTTypes(
ObjectHandleOnStack appDomainObj,
ref int epoch,
ObjectHandleOnStack winrtTypes);
- [System.Security.SecurityCritical]
internal static System.Type[] GetCachedWinRTTypes(
System.AppDomain ad,
ref int epoch)
return result;
}
- [System.Security.SecurityCritical]
internal static System.Type[] GetCachedWinRTTypes(
System.AppDomain ad)
{
#endif // FEATURE_COMINTEROP
- [System.Security.SecurityCritical] // auto-generated_required
public static Delegate GetDelegateForFunctionPointer(IntPtr ptr, Type t)
{
// Validate the parameters
return GetDelegateForFunctionPointerInternal(ptr, t);
}
- [System.Security.SecurityCritical]
public static TDelegate GetDelegateForFunctionPointer<TDelegate>(IntPtr ptr)
{
return (TDelegate)(object)GetDelegateForFunctionPointer(ptr, typeof(TDelegate));
[MethodImplAttribute(MethodImplOptions.InternalCall)]
internal static extern Delegate GetDelegateForFunctionPointerInternal(IntPtr ptr, Type t);
- [System.Security.SecurityCritical] // auto-generated_required
public static IntPtr GetFunctionPointerForDelegate(Delegate d)
{
if (d == null)
return GetFunctionPointerForDelegateInternal(d);
}
- [System.Security.SecurityCritical]
public static IntPtr GetFunctionPointerForDelegate<TDelegate>(TDelegate d)
{
return GetFunctionPointerForDelegate((Delegate)(object)d);
[MethodImplAttribute(MethodImplOptions.InternalCall)]
internal static extern IntPtr GetFunctionPointerForDelegateInternal(Delegate d);
- [System.Security.SecurityCritical] // auto-generated_required
public static IntPtr SecureStringToBSTR(SecureString s) {
if( s == null) {
throw new ArgumentNullException(nameof(s));
#endif
}
- [System.Security.SecurityCritical] // auto-generated_required
public static IntPtr SecureStringToCoTaskMemAnsi(SecureString s) {
if( s == null) {
throw new ArgumentNullException(nameof(s));
return s.MarshalToString(globalAlloc: false, unicode: false);
}
- [System.Security.SecurityCritical] // auto-generated_required
public static IntPtr SecureStringToCoTaskMemUnicode(SecureString s)
{
if( s == null) {
}
#if FEATURE_COMINTEROP
- [System.Security.SecurityCritical] // auto-generated_required
public static void ZeroFreeBSTR(IntPtr s)
{
Win32Native.ZeroMemory(s, (UIntPtr)(Win32Native.SysStringLen(s) * 2));
}
#endif
- [System.Security.SecurityCritical] // auto-generated_required
public static void ZeroFreeCoTaskMemAnsi(IntPtr s)
{
Win32Native.ZeroMemory(s, (UIntPtr)(Win32Native.lstrlenA(s)));
FreeCoTaskMem(s);
}
- [System.Security.SecurityCritical] // auto-generated_required
public static void ZeroFreeCoTaskMemUnicode(IntPtr s)
{
Win32Native.ZeroMemory(s, (UIntPtr)(Win32Native.lstrlenW(s) * 2));
FreeCoTaskMem(s);
}
- [System.Security.SecurityCritical] // auto-generated_required
unsafe public static void ZeroFreeCoTaskMemUTF8(IntPtr s)
{
Win32Native.ZeroMemory(s, (UIntPtr)System.StubHelpers.StubHelpers.strlen((sbyte*)s));
FreeCoTaskMem(s);
}
- [System.Security.SecurityCritical] // auto-generated_required
public static IntPtr SecureStringToGlobalAllocAnsi(SecureString s) {
if( s == null) {
throw new ArgumentNullException(nameof(s));
return s.MarshalToString(globalAlloc: true, unicode: false);
}
- [System.Security.SecurityCritical] // auto-generated_required
public static IntPtr SecureStringToGlobalAllocUnicode(SecureString s) {
if( s == null) {
throw new ArgumentNullException(nameof(s));
return s.MarshalToString(globalAlloc: true, unicode: true);;
}
- [System.Security.SecurityCritical] // auto-generated_required
public static void ZeroFreeGlobalAllocAnsi(IntPtr s) {
Win32Native.ZeroMemory(s, (UIntPtr)(Win32Native.lstrlenA(s)));
FreeHGlobal(s);
}
- [System.Security.SecurityCritical] // auto-generated_required
public static void ZeroFreeGlobalAllocUnicode(IntPtr s) {
Win32Native.ZeroMemory(s, (UIntPtr)(Win32Native.lstrlenW(s) * 2));
FreeHGlobal(s);
}
}
-
-#if FEATURE_COMINTEROP && !FEATURE_CORECLR // current implementation requires reflection only load
- //========================================================================
- // Typelib importer callback implementation.
- //========================================================================
- internal class ImporterCallback : ITypeLibImporterNotifySink
- {
- public void ReportEvent(ImporterEventKind EventKind, int EventCode, String EventMsg)
- {
- }
-
- [System.Security.SecuritySafeCritical] // overrides transparent public member
- public Assembly ResolveRef(Object TypeLib)
- {
- try
- {
- // Create the TypeLibConverter.
- ITypeLibConverter TLBConv = new TypeLibConverter();
-
- // Convert the typelib.
- return TLBConv.ConvertTypeLibToAssembly(TypeLib,
- Marshal.GetTypeLibName((ITypeLib)TypeLib) + ".dll",
- 0,
- new ImporterCallback(),
- null,
- null,
- null,
- null);
- }
- catch(Exception)
-// catch
- {
- return null;
- }
- }
- }
-#endif // FEATURE_COMINTEROP && !FEATURE_CORECLR
}
]
internal interface IDispatch {
- [System.Security.SecurityCritical]
void GetTypeInfoCount(out uint pctinfo);
- [System.Security.SecurityCritical]
void GetTypeInfo(uint iTInfo, int lcid, out IntPtr info);
- [System.Security.SecurityCritical]
void GetIDsOfNames(
ref Guid iid,
[MarshalAs(UnmanagedType.LPArray, ArraySubType = UnmanagedType.LPWStr, SizeParamIndex = 2)]
[MarshalAs(UnmanagedType.LPArray, ArraySubType = UnmanagedType.I4, SizeParamIndex = 2)]
int[] rgDispId);
- [System.Security.SecurityCritical]
void Invoke(
int dispIdMember,
ref Guid riid,
using System.Runtime.CompilerServices;
using System.Globalization;
using System.Runtime.Versioning;
+ using System.Diagnostics;
using System.Diagnostics.Contracts;
[Flags]
#region IRegistrationServices
- [System.Security.SecurityCritical] // auto-generated_required
public virtual bool RegisterAssembly(Assembly assembly, AssemblyRegistrationFlags flags)
{
// Validate the arguments.
return false;
}
- [System.Security.SecurityCritical] // auto-generated_required
public virtual bool UnregisterAssembly(Assembly assembly)
{
// Validate the arguments.
return false;
}
- [System.Security.SecurityCritical] // auto-generated_required
public virtual Type[] GetRegistrableTypesInAssembly(Assembly assembly)
{
// Validate the arguments.
return RetArray;
}
- [System.Security.SecurityCritical] // auto-generated_required
public virtual String GetProgIdForType(Type type)
{
return Marshal.GenerateProgIdForType(type);
}
- [System.Security.SecurityCritical] // auto-generated_required
public virtual void RegisterTypeForComClients(Type type, ref Guid g)
{
#if FEATURE_COMINTEROP_MANAGED_ACTIVATION
return s_ManagedCategoryGuid;
}
- [System.Security.SecurityCritical] // auto-generated_required
public virtual bool TypeRequiresRegistration(Type type)
{
return TypeRequiresRegistrationHelper(type);
}
- [System.Security.SecuritySafeCritical] // auto-generated
public virtual bool TypeRepresentsComType(Type type)
{
// If the type is not a COM import, then it does not represent a COM type.
// If the type is derived from a tdImport class and has the same GUID as the
// imported class, then it represents a COM type.
Type baseComImportType = GetBaseComImportType(type);
- Contract.Assert(baseComImportType != null, "baseComImportType != null");
+ Debug.Assert(baseComImportType != null, "baseComImportType != null");
if (Marshal.GenerateGuidForType(type) == Marshal.GenerateGuidForType(baseComImportType))
return true;
#region Public methods not on IRegistrationServices
- [System.Security.SecurityCritical] // auto-generated_required
[ComVisible(false)]
public virtual int RegisterTypeForComClients(Type type, RegistrationClassContext classContext, RegistrationConnectionType flags)
{
#endif // FEATURE_COMINTEROP_MANAGED_ACTIVATION
}
- [System.Security.SecurityCritical] // auto-generated_required
[ComVisible(false)]
public virtual void UnregisterTypeForComClients(int cookie)
{
#region Internal helpers
- [System.Security.SecurityCritical] // auto-generated_required
internal static bool TypeRequiresRegistrationHelper(Type type)
{
// If the type is not a class or a value class, then it does not get registered.
#region Private helpers
- [System.Security.SecurityCritical] // auto-generated
private void RegisterValueType(Type type, String strAsmName, String strAsmVersion, String strAsmCodeBase, String strRuntimeVersion)
{
// Retrieve some information that will be used during the registration process.
}
}
- [System.Security.SecurityCritical] // auto-generated
private void RegisterManagedType(Type type, String strAsmName, String strAsmVersion, String strAsmCodeBase, String strRuntimeVersion)
{
//
EnsureManagedCategoryExists();
}
- [System.Security.SecurityCritical] // auto-generated
private void RegisterComImportedType(Type type, String strAsmName, String strAsmVersion, String strAsmCodeBase, String strRuntimeVersion)
{
// Retrieve some information that will be used during the registration process.
}
}
- [System.Security.SecurityCritical] // auto-generated
private bool UnregisterValueType(Type type, String strAsmVersion)
{
bool bAllVersionsGone = true;
// Return :
// true: All versions are gone.
// false: Some versions are still left in registry
- [System.Security.SecurityCritical] // auto-generated
private bool UnregisterManagedType(Type type,String strAsmVersion)
{
bool bAllVersionsGone = true;
// Return:
// true: All version information are gone.
// false: There are still some version left in registry
- [System.Security.SecurityCritical] // auto-generated
private bool UnregisterComImportedType(Type type, String strAsmVersion)
{
bool bAllVersionsGone = true;
return bAllVersionsGone;
}
- [System.Security.SecurityCritical] // auto-generated
private void RegisterPrimaryInteropAssembly(RuntimeAssembly assembly, String strAsmCodeBase, PrimaryInteropAssemblyAttribute attr)
{
// Validate that the PIA has a strong name.
}
}
- [System.Security.SecurityCritical] // auto-generated
private void UnregisterPrimaryInteropAssembly(Assembly assembly, PrimaryInteropAssemblyAttribute attr)
{
String strTlbId = "{" + Marshal.GetTypeLibGuidForAssembly(assembly).ToString().ToUpper(CultureInfo.InvariantCulture) + "}";
private static bool ManagedCategoryExists()
{
using (RegistryKey componentCategoryKey = Registry.ClassesRoot.OpenSubKey(strComponentCategorySubKey,
-#if FEATURE_MACL
- RegistryKeyPermissionCheck.ReadSubTree))
-#else
false))
-#endif
{
if (componentCategoryKey == null)
return false;
using (RegistryKey managedCategoryKey = componentCategoryKey.OpenSubKey(strManagedCategoryGuid,
-#if FEATURE_MACL
- RegistryKeyPermissionCheck.ReadSubTree))
-#else
false))
-#endif
{
if (managedCategoryKey == null)
return false;
return true;
}
- [System.Security.SecurityCritical] // auto-generated
private void CallUserDefinedRegistrationMethod(Type type, bool bRegister)
{
bool bFunctionCalled = false;
#if FEATURE_COMINTEROP_MANAGED_ACTIVATION
// GUID versioning can be controlled by using the GuidAttribute or
// letting the runtime generate it based on type and assembly strong name.
- [System.Security.SecurityCritical] // auto-generated
[MethodImplAttribute(MethodImplOptions.InternalCall)]
private static extern void RegisterTypeForComClientsNative(Type type,ref Guid g);
// GUID versioning can be controlled by using the GuidAttribute or
// letting the runtime generate it based on type and assembly strong name.
- [System.Security.SecurityCritical] // auto-generated
[MethodImplAttribute(MethodImplOptions.InternalCall)]
private static extern int RegisterTypeForComClientsExNative(Type t, RegistrationClassContext clsContext, RegistrationConnectionType flags);
#endif // FEATURE_COMINTEROP_MANAGED_ACTIVATION
using System.Runtime.Versioning;
using StackCrawlMark = System.Threading.StackCrawlMark;
-namespace System.Runtime.InteropServices {
-[System.Runtime.InteropServices.ComVisible(true)]
-#if FEATURE_CORECLR
- static
-#endif
- public class RuntimeEnvironment {
+namespace System.Runtime.InteropServices
+{
+ [System.Runtime.InteropServices.ComVisible(true)]
+ static public class RuntimeEnvironment {
-#if !FEATURE_CORECLR
- // This should have been a static class, but wasn't as of v3.5. Clearly, this is
- // broken. We'll keep this in V4 for binary compat, but marked obsolete as error
- // so migrated source code gets fixed. On Silverlight, this type exists but is
- // not public.
- [Obsolete("Do not create instances of the RuntimeEnvironment class. Call the static methods directly on this type instead", true)]
- public RuntimeEnvironment()
- {
- // Should not have been instantiable - here for binary compatibility in V4.
- }
-#endif
-
- [System.Security.SecurityCritical] // auto-generated
[MethodImplAttribute(MethodImplOptions.InternalCall)]
internal static extern String GetModuleFileName();
- [System.Security.SecurityCritical] // auto-generated
[MethodImplAttribute(MethodImplOptions.InternalCall)]
internal static extern String GetDeveloperPath();
- [System.Security.SecurityCritical] // auto-generated
[MethodImplAttribute(MethodImplOptions.InternalCall)]
internal static extern String GetHostBindingFile();
-#if !FEATURE_CORECLR
- [System.Security.SecurityCritical] // auto-generated
- [DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
- [SuppressUnmanagedCodeSecurity]
- internal static extern void _GetSystemVersion(StringHandleOnStack retVer);
-#endif //!FEATURE_CORECLR
-
public static bool FromGlobalAccessCache(Assembly a)
{
return a.GlobalAssemblyCache;
}
-
-#if !FEATURE_CORECLR
- [System.Security.SecuritySafeCritical] // public member
-#endif
+
[MethodImpl (MethodImplOptions.NoInlining)]
public static String GetSystemVersion()
{
-#if FEATURE_CORECLR
-
return Assembly.GetExecutingAssembly().ImageRuntimeVersion;
-
-#else // FEATURE_CORECLR
-
- String ver = null;
- _GetSystemVersion(JitHelpers.GetStringHandleOnStack(ref ver));
- return ver;
-
-#endif // FEATURE_CORECLR
-
}
-
- [System.Security.SecuritySafeCritical] // auto-generated
+
public static String GetRuntimeDirectory()
{
String dir = GetRuntimeDirectoryImpl();
return dir;
}
- [System.Security.SecurityCritical] // auto-generated
[MethodImplAttribute(MethodImplOptions.InternalCall)]
internal static extern String GetRuntimeDirectoryImpl();
// Returns the system ConfigurationFile
public static String SystemConfigurationFile {
- [System.Security.SecuritySafeCritical] // auto-generated
get {
StringBuilder sb = new StringBuilder(Path.MaxPath);
sb.Append(GetRuntimeDirectory());
}
#if FEATURE_COMINTEROP
- [System.Security.SecurityCritical]
[DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
[SuppressUnmanagedCodeSecurity]
private static extern IntPtr GetRuntimeInterfaceImpl(
// Returns unmanaged pointer to requested interface on success. Throws
// COMException with failed HR if there is a QI failure.
//
- [System.Security.SecurityCritical] // do not allow partial trust callers
[ComVisible(false)]
public static IntPtr GetRuntimeInterfaceAsIntPtr(Guid clsid, Guid riid)
{
// Returns an RCW to requested interface on success. Throws
// COMException with failed HR if there is a QI failure.
//
- [System.Security.SecurityCritical] // do not allow partial trust callers
[ComVisible(false)]
public static object GetRuntimeInterfaceAsObject(Guid clsid, Guid riid)
{
}
}
}
-
#endif // FEATURE_COMINTEROP
}
}
using System.Runtime.ConstrainedExecution;
using System.Runtime.Versioning;
using Microsoft.Win32.SafeHandles;
+using System.Diagnostics;
using System.Diagnostics.Contracts;
- [System.Security.SecurityCritical]
public abstract unsafe class SafeBuffer : SafeHandleZeroOrMinusOneIsInvalid
{
// Steal UIntPtr.MaxValue as our uninitialized value.
[ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)]
private static InvalidOperationException NotInitialized()
{
- Contract.Assert(false, "Uninitialized SafeBuffer! Someone needs to call Initialize before using this instance!");
+ Debug.Assert(false, "Uninitialized SafeBuffer! Someone needs to call Initialize before using this instance!");
return new InvalidOperationException(Environment.GetResourceString("InvalidOperation_MustCallInitialize"));
}
// we'll do this to ensure we've cut off all attack vectors. Similarly, all
// methods have a link demand to ensure untrusted code cannot directly edit
// or alter a handle.
-[System.Security.SecurityCritical] // auto-generated_required
-#if !FEATURE_CORECLR
-[SecurityPermission(SecurityAction.InheritanceDemand, UnmanagedCode=true)]
-#endif
public abstract class SafeHandle : CriticalFinalizerObject, IDisposable
{
// ! Do not add or rearrange fields as the EE depends on this layout.
_fullyInitialized = true;
}
-#if FEATURE_CORECLR
// Migrating InheritanceDemands requires this default ctor, so we can mark it critical
protected SafeHandle()
{
BCLDebug.Assert(false, "SafeHandle's protected default ctor should never be used!");
throw new NotImplementedException();
}
-#endif
- [System.Security.SecuritySafeCritical] // auto-generated
~SafeHandle()
{
Dispose(false);
get;
}
- [System.Security.SecurityCritical] // auto-generated
[ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)]
public void Close() {
Dispose(true);
}
- [System.Security.SecuritySafeCritical] // auto-generated
[ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)]
public void Dispose() {
Dispose(true);
}
- [System.Security.SecurityCritical] // auto-generated
[ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)]
protected virtual void Dispose(bool disposing)
{
// your handle is invalid and you want to record that information.
// An example is calling a syscall and getting back ERROR_INVALID_HANDLE.
// This method will normally leak handles!
- [System.Security.SecurityCritical] // auto-generated
[ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)]
[MethodImplAttribute(MethodImplOptions.InternalCall)]
public extern void SetHandleAsInvalid();
// when the method is interrupted prior to processing by a thread abort or
// when the handle has already been (or is in the process of being)
// released.
- [System.Security.SecurityCritical] // auto-generated
[ReliabilityContract(Consistency.WillNotCorruptState, Cer.MayFail)]
[MethodImplAttribute(MethodImplOptions.InternalCall)]
public extern void DangerousAddRef(ref bool success);
// constitutes a potential security hole (via handle recycling) as well as a
// correctness problem -- so don't ever expose Dangerous* calls out to
// untrusted code.
- [System.Security.SecurityCritical] // auto-generated
[ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)]
[MethodImplAttribute(MethodImplOptions.InternalCall)]
public extern void DangerousRelease();
using System.Reflection.Emit;
using System.Collections;
using System.Threading;
+ using System.Diagnostics;
using System.Diagnostics.Contracts;
internal class EventProviderWriter
// Find the delegate on the event sink helper.
FieldInfo DelegateField = SinkHelperClass.GetField( "m_" + SrcItfMethod.Name + "Delegate" );
- Contract.Assert(DelegateField != null, "Unable to find the field m_" + SrcItfMethod.Name + "Delegate on the sink helper");
+ Debug.Assert(DelegateField != null, "Unable to find the field m_" + SrcItfMethod.Name + "Delegate on the sink helper");
// Find the cookie on the event sink helper.
FieldInfo CookieField = SinkHelperClass.GetField( "m_dwCookie" );
- Contract.Assert(CookieField != null, "Unable to find the field m_dwCookie on the sink helper");
+ Debug.Assert(CookieField != null, "Unable to find the field m_dwCookie on the sink helper");
// Retrieve the sink helper's constructor.
ConstructorInfo SinkHelperCons = SinkHelperClass.GetConstructor(EventProviderWriter.DefaultLookup | BindingFlags.NonPublic, null, Array.Empty<Type>(), null );
- Contract.Assert(SinkHelperCons != null, "Unable to find the constructor for the sink helper");
+ Debug.Assert(SinkHelperCons != null, "Unable to find the constructor for the sink helper");
// Retrieve the IConnectionPoint.Advise method.
MethodInfo CPAdviseMethod = typeof(IConnectionPoint).GetMethod( "Advise" );
- Contract.Assert(CPAdviseMethod != null, "Unable to find the method ConnectionPoint.Advise");
+ Debug.Assert(CPAdviseMethod != null, "Unable to find the method ConnectionPoint.Advise");
// Retrieve the ArrayList.Add method.
aParamTypes = new Type[1];
aParamTypes[0] = typeof(Object);
MethodInfo ArrayListAddMethod = typeof(ArrayList).GetMethod( "Add", aParamTypes, null );
- Contract.Assert(ArrayListAddMethod != null, "Unable to find the method ArrayList.Add");
+ Debug.Assert(ArrayListAddMethod != null, "Unable to find the method ArrayList.Add");
// Retrieve the Monitor.Enter() method.
MethodInfo MonitorEnterMethod = typeof(Monitor).GetMethod( "Enter", MonitorEnterParamTypes, null );
- Contract.Assert(MonitorEnterMethod != null, "Unable to find the method Monitor.Enter()");
+ Debug.Assert(MonitorEnterMethod != null, "Unable to find the method Monitor.Enter()");
// Retrieve the Monitor.Exit() method.
aParamTypes[0] = typeof(Object);
MethodInfo MonitorExitMethod = typeof(Monitor).GetMethod( "Exit", aParamTypes, null );
- Contract.Assert(MonitorExitMethod != null, "Unable to find the method Monitor.Exit()");
+ Debug.Assert(MonitorExitMethod != null, "Unable to find the method Monitor.Exit()");
// Define the add_XXX method.
Type[] parameterTypes;
// Find the delegate on the event sink helper.
FieldInfo DelegateField = SinkHelperClass.GetField( "m_" + SrcItfMethod.Name + "Delegate" );
- Contract.Assert(DelegateField != null, "Unable to find the field m_" + SrcItfMethod.Name + "Delegate on the sink helper");
+ Debug.Assert(DelegateField != null, "Unable to find the field m_" + SrcItfMethod.Name + "Delegate on the sink helper");
// Find the cookie on the event sink helper.
FieldInfo CookieField = SinkHelperClass.GetField( "m_dwCookie" );
- Contract.Assert(CookieField != null, "Unable to find the field m_dwCookie on the sink helper");
+ Debug.Assert(CookieField != null, "Unable to find the field m_dwCookie on the sink helper");
// Retrieve the ArrayList.RemoveAt method.
aParamTypes = new Type[1];
aParamTypes[0] = typeof(Int32);
MethodInfo ArrayListRemoveMethod = typeof(ArrayList).GetMethod( "RemoveAt", aParamTypes, null );
- Contract.Assert(ArrayListRemoveMethod != null, "Unable to find the method ArrayList.RemoveAt()");
+ Debug.Assert(ArrayListRemoveMethod != null, "Unable to find the method ArrayList.RemoveAt()");
// Retrieve the ArrayList.Item property get method.
PropertyInfo ArrayListItemProperty = typeof(ArrayList).GetProperty( "Item" );
- Contract.Assert(ArrayListItemProperty != null, "Unable to find the property ArrayList.Item");
+ Debug.Assert(ArrayListItemProperty != null, "Unable to find the property ArrayList.Item");
MethodInfo ArrayListItemGetMethod = ArrayListItemProperty.GetGetMethod();
- Contract.Assert(ArrayListItemGetMethod != null, "Unable to find the get method for property ArrayList.Item");
+ Debug.Assert(ArrayListItemGetMethod != null, "Unable to find the get method for property ArrayList.Item");
// Retrieve the ArrayList.Count property get method.
PropertyInfo ArrayListSizeProperty = typeof(ArrayList).GetProperty( "Count" );
- Contract.Assert(ArrayListSizeProperty != null, "Unable to find the property ArrayList.Count");
+ Debug.Assert(ArrayListSizeProperty != null, "Unable to find the property ArrayList.Count");
MethodInfo ArrayListSizeGetMethod = ArrayListSizeProperty.GetGetMethod();
- Contract.Assert(ArrayListSizeGetMethod != null, "Unable to find the get method for property ArrayList.Count");
+ Debug.Assert(ArrayListSizeGetMethod != null, "Unable to find the get method for property ArrayList.Count");
// Retrieve the Delegate.Equals() method.
aParamTypes[0] = typeof(Delegate);
MethodInfo DelegateEqualsMethod = typeof(Delegate).GetMethod( "Equals", aParamTypes, null );
- Contract.Assert(DelegateEqualsMethod != null, "Unable to find the method Delegate.Equlals()");
+ Debug.Assert(DelegateEqualsMethod != null, "Unable to find the method Delegate.Equlals()");
// Retrieve the Monitor.Enter() method.
MethodInfo MonitorEnterMethod = typeof(Monitor).GetMethod("Enter", MonitorEnterParamTypes, null);
- Contract.Assert(MonitorEnterMethod != null, "Unable to find the method Monitor.Enter()");
+ Debug.Assert(MonitorEnterMethod != null, "Unable to find the method Monitor.Enter()");
// Retrieve the Monitor.Exit() method.
aParamTypes[0] = typeof(Object);
MethodInfo MonitorExitMethod = typeof(Monitor).GetMethod( "Exit", aParamTypes, null );
- Contract.Assert(MonitorExitMethod != null, "Unable to find the method Monitor.Exit()");
+ Debug.Assert(MonitorExitMethod != null, "Unable to find the method Monitor.Exit()");
// Retrieve the ConnectionPoint.Unadvise() method.
MethodInfo CPUnadviseMethod = typeof(IConnectionPoint).GetMethod( "Unadvise" );
- Contract.Assert(CPUnadviseMethod != null, "Unable to find the method ConnectionPoint.Unadvise()");
+ Debug.Assert(CPUnadviseMethod != null, "Unable to find the method ConnectionPoint.Unadvise()");
// Retrieve the Marshal.ReleaseComObject() method.
MethodInfo ReleaseComObjectMethod = typeof(Marshal).GetMethod( "ReleaseComObject" );
- Contract.Assert(ReleaseComObjectMethod != null, "Unable to find the method Marshal.ReleaseComObject()");
+ Debug.Assert(ReleaseComObjectMethod != null, "Unable to find the method Marshal.ReleaseComObject()");
// Define the remove_XXX method.
Type[] parameterTypes;
{
// Retrieve the constructor info for the array list's default constructor.
ConstructorInfo DefaultArrayListCons = typeof(ArrayList).GetConstructor(EventProviderWriter.DefaultLookup, null, Array.Empty<Type>(), null );
- Contract.Assert(DefaultArrayListCons != null, "Unable to find the constructor for class ArrayList");
+ Debug.Assert(DefaultArrayListCons != null, "Unable to find the constructor for class ArrayList");
// Temp byte array for Guid
ubyte[] rgByteGuid = new ubyte[16];
Type[] aParamTypes = new Type[1];
aParamTypes[0] = typeof(Byte[]);
ConstructorInfo ByteArrayGUIDCons = typeof(Guid).GetConstructor(EventProviderWriter.DefaultLookup, null, aParamTypes, null );
- Contract.Assert(ByteArrayGUIDCons != null, "Unable to find the constructor for GUID that accepts a string as argument");
+ Debug.Assert(ByteArrayGUIDCons != null, "Unable to find the constructor for GUID that accepts a string as argument");
// Retrieve the IConnectionPointContainer.FindConnectionPoint() method.
MethodInfo CPCFindCPMethod = typeof(IConnectionPointContainer).GetMethod( "FindConnectionPoint" );
- Contract.Assert(CPCFindCPMethod != null, "Unable to find the method ConnectionPointContainer.FindConnectionPoint()");
+ Debug.Assert(CPCFindCPMethod != null, "Unable to find the method ConnectionPointContainer.FindConnectionPoint()");
// Define the Init method itself.
MethodBuilder Meth = OutputTypeBuilder.DefineMethod(
{
// Retrieve the constructor info for the base class's constructor.
ConstructorInfo DefaultBaseClsCons = typeof(Object).GetConstructor(BindingFlags.Instance | BindingFlags.Public, null, Array.Empty<Type>(), null );
- Contract.Assert(DefaultBaseClsCons != null, "Unable to find the object's public default constructor");
+ Debug.Assert(DefaultBaseClsCons != null, "Unable to find the object's public default constructor");
// Define the default constructor.
MethodAttributes ctorAttributes = MethodAttributes.SpecialName | (DefaultBaseClsCons.Attributes & MethodAttributes.MemberAccessMask);
{
// Find the cookie on the event sink helper.
FieldInfo CookieField = SinkHelperClass.GetField( "m_dwCookie" );
- Contract.Assert(CookieField != null, "Unable to find the field m_dwCookie on the sink helper");
+ Debug.Assert(CookieField != null, "Unable to find the field m_dwCookie on the sink helper");
// Retrieve the ArrayList.Item property get method.
PropertyInfo ArrayListItemProperty = typeof(ArrayList).GetProperty( "Item" );
- Contract.Assert(ArrayListItemProperty != null, "Unable to find the property ArrayList.Item");
+ Debug.Assert(ArrayListItemProperty != null, "Unable to find the property ArrayList.Item");
MethodInfo ArrayListItemGetMethod = ArrayListItemProperty.GetGetMethod();
- Contract.Assert(ArrayListItemGetMethod != null, "Unable to find the get method for property ArrayList.Item");
+ Debug.Assert(ArrayListItemGetMethod != null, "Unable to find the get method for property ArrayList.Item");
// Retrieve the ArrayList.Count property get method.
PropertyInfo ArrayListSizeProperty = typeof(ArrayList).GetProperty( "Count" );
- Contract.Assert(ArrayListSizeProperty != null, "Unable to find the property ArrayList.Count");
+ Debug.Assert(ArrayListSizeProperty != null, "Unable to find the property ArrayList.Count");
MethodInfo ArrayListSizeGetMethod = ArrayListSizeProperty.GetGetMethod();
- Contract.Assert(ArrayListSizeGetMethod != null, "Unable to find the get method for property ArrayList.Count");
+ Debug.Assert(ArrayListSizeGetMethod != null, "Unable to find the get method for property ArrayList.Count");
// Retrieve the ConnectionPoint.Unadvise() method.
MethodInfo CPUnadviseMethod = typeof(IConnectionPoint).GetMethod( "Unadvise" );
- Contract.Assert(CPUnadviseMethod != null, "Unable to find the method ConnectionPoint.Unadvise()");
+ Debug.Assert(CPUnadviseMethod != null, "Unable to find the method ConnectionPoint.Unadvise()");
// Retrieve the Marshal.ReleaseComObject() method.
MethodInfo ReleaseComObjectMethod = typeof(Marshal).GetMethod( "ReleaseComObject" );
- Contract.Assert(ReleaseComObjectMethod != null, "Unable to find the method Marshal.ReleaseComObject()");
+ Debug.Assert(ReleaseComObjectMethod != null, "Unable to find the method Marshal.ReleaseComObject()");
// Retrieve the Monitor.Enter() method.
MethodInfo MonitorEnterMethod = typeof(Monitor).GetMethod("Enter", MonitorEnterParamTypes, null);
- Contract.Assert(MonitorEnterMethod != null, "Unable to find the method Monitor.Enter()");
+ Debug.Assert(MonitorEnterMethod != null, "Unable to find the method Monitor.Enter()");
// Retrieve the Monitor.Exit() method.
Type[] aParamTypes = new Type[1];
aParamTypes[0] = typeof(Object);
MethodInfo MonitorExitMethod = typeof(Monitor).GetMethod( "Exit", aParamTypes, null );
- Contract.Assert(MonitorExitMethod != null, "Unable to find the method Monitor.Exit()");
+ Debug.Assert(MonitorExitMethod != null, "Unable to find the method Monitor.Exit()");
// Define the Finalize method itself.
MethodBuilder Meth = OutputTypeBuilder.DefineMethod( "Finalize", MethodAttributes.Public | MethodAttributes.Virtual, null, null );
{
// Retrieve the method info for GC.SuppressFinalize().
MethodInfo SuppressFinalizeMethod = typeof(GC).GetMethod("SuppressFinalize");
- Contract.Assert(SuppressFinalizeMethod != null, "Unable to find the GC.SuppressFinalize");
+ Debug.Assert(SuppressFinalizeMethod != null, "Unable to find the GC.SuppressFinalize");
// Define the Finalize method itself.
MethodBuilder Meth = OutputTypeBuilder.DefineMethod( "Dispose", MethodAttributes.Public | MethodAttributes.Virtual, null, null );
using System.Reflection;
using System.Reflection.Emit;
using System.Collections;
+ using System.Diagnostics;
using System.Diagnostics.Contracts;
internal class EventSinkHelperWriter
{
// Retrieve the delegate type from the add_XXX method.
MethodInfo AddMeth = m_EventItfType.GetMethod( "add_" + aMethods[cMethods].Name );
ParameterInfo[] aParams = AddMeth.GetParameters();
- Contract.Assert(aParams.Length == 1, "All event interface methods must take a single delegate derived type and have a void return type");
+ Debug.Assert(aParams.Length == 1, "All event interface methods must take a single delegate derived type and have a void return type");
Type DelegateCls = aParams[0].ParameterType;
// Define the delegate instance field.
{
// Retrieve the method info for the invoke method on the delegate.
MethodInfo DelegateInvokeMethod = DelegateCls.GetMethod( "Invoke" );
- Contract.Assert(DelegateInvokeMethod != null, "Unable to find method Delegate.Invoke()");
+ Debug.Assert(DelegateInvokeMethod != null, "Unable to find method Delegate.Invoke()");
// Retrieve the return type.
Type ReturnType = Method.ReturnType;
if ( ReturnType == typeof(IntPtr) )
il.Emit( OpCodes.Ldc_I4_0 );
else
- Contract.Assert(false, "Unexpected type for Primitive type.");
+ Debug.Assert(false, "Unexpected type for Primitive type.");
break;
}
}
{
// Retrieve the constructor info for the base classe's constructor.
ConstructorInfo DefaultBaseClsCons = typeof(Object).GetConstructor(BindingFlags.Instance | BindingFlags.Static | BindingFlags.Public, null, Array.Empty<Type>(), null );
- Contract.Assert(DefaultBaseClsCons != null, "Unable to find the constructor for class " + m_InputType.Name);
+ Debug.Assert(DefaultBaseClsCons != null, "Unable to find the constructor for class " + m_InputType.Name);
// Define the default constructor.
MethodBuilder Cons = OutputTypeBuilder.DefineMethod( ".ctor",
+++ /dev/null
-// Licensed to the .NET Foundation under one or more agreements.
-// The .NET Foundation licenses this file to you under the MIT license.
-// See the LICENSE file in the project root for more information.
-
-/*=============================================================================
-**
-**
-**
-** Purpose: Component that implements the ITypeLibConverter interface and
-** does the actual work of converting a typelib to metadata and
-** vice versa.
-**
-**
-=============================================================================*/
-#if !FEATURE_CORECLR // current implementation requires reflection only load
-namespace System.Runtime.InteropServices {
-
- using System;
- using System.Diagnostics.Contracts;
- using System.Collections;
- using System.Collections.Generic;
- using System.Threading;
- using System.Runtime.InteropServices.TCEAdapterGen;
- using System.IO;
- using System.Reflection;
- using System.Reflection.Emit;
- using System.Configuration.Assemblies;
- using Microsoft.Win32;
- using System.Runtime.CompilerServices;
- using System.Globalization;
- using System.Security;
- using System.Security.Permissions;
- using System.Runtime.InteropServices.ComTypes;
- using System.Runtime.Versioning;
- using WORD = System.UInt16;
- using DWORD = System.UInt32;
- using _TYPELIBATTR = System.Runtime.InteropServices.ComTypes.TYPELIBATTR;
-
- [Guid("F1C3BF79-C3E4-11d3-88E7-00902754C43A")]
- [ClassInterface(ClassInterfaceType.None)]
-[System.Runtime.InteropServices.ComVisible(true)]
- public sealed class TypeLibConverter : ITypeLibConverter
- {
- private const String s_strTypeLibAssemblyTitlePrefix = "TypeLib ";
- private const String s_strTypeLibAssemblyDescPrefix = "Assembly generated from typelib ";
- private const int MAX_NAMESPACE_LENGTH = 1024;
-
-
- //
- // ITypeLibConverter interface.
- //
-
- [System.Security.SecuritySafeCritical] // auto-generated
- [SecurityPermissionAttribute(SecurityAction.Demand, Flags=SecurityPermissionFlag.UnmanagedCode)]
- public AssemblyBuilder ConvertTypeLibToAssembly([MarshalAs(UnmanagedType.Interface)] Object typeLib,
- String asmFileName,
- int flags,
- ITypeLibImporterNotifySink notifySink,
- byte[] publicKey,
- StrongNameKeyPair keyPair,
- bool unsafeInterfaces)
- {
- return ConvertTypeLibToAssembly(typeLib,
- asmFileName,
- (unsafeInterfaces
- ? TypeLibImporterFlags.UnsafeInterfaces
- : 0),
- notifySink,
- publicKey,
- keyPair,
- null,
- null);
- }
-
-
-
-
- [System.Security.SecuritySafeCritical] // auto-generated
- [SecurityPermissionAttribute(SecurityAction.Demand, Flags=SecurityPermissionFlag.UnmanagedCode)]
- public AssemblyBuilder ConvertTypeLibToAssembly([MarshalAs(UnmanagedType.Interface)] Object typeLib,
- String asmFileName,
- TypeLibImporterFlags flags,
- ITypeLibImporterNotifySink notifySink,
- byte[] publicKey,
- StrongNameKeyPair keyPair,
- String asmNamespace,
- Version asmVersion)
- {
- // Validate the arguments.
- if (typeLib == null)
- throw new ArgumentNullException(nameof(typeLib));
- if (asmFileName == null)
- throw new ArgumentNullException(nameof(asmFileName));
- if (notifySink == null)
- throw new ArgumentNullException(nameof(notifySink));
- if (String.Empty.Equals(asmFileName))
- throw new ArgumentException(Environment.GetResourceString("Arg_InvalidFileName"), nameof(asmFileName));
- if (asmFileName.Length > Path.MaxPath)
- throw new ArgumentException(Environment.GetResourceString("IO.PathTooLong"), asmFileName);
- if ((flags & TypeLibImporterFlags.PrimaryInteropAssembly) != 0 && publicKey == null && keyPair == null)
- throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_PIAMustBeStrongNamed"));
- Contract.EndContractBlock();
-
- ArrayList eventItfInfoList = null;
-
- // Determine the AssemblyNameFlags
- AssemblyNameFlags asmNameFlags = AssemblyNameFlags.None;
-
- // Retrieve the assembly name from the typelib.
- AssemblyName asmName = GetAssemblyNameFromTypelib(typeLib, asmFileName, publicKey, keyPair, asmVersion, asmNameFlags);
-
- // Create the dynamic assembly that will contain the converted typelib types.
- AssemblyBuilder asmBldr = CreateAssemblyForTypeLib(typeLib, asmFileName, asmName,
- (flags & TypeLibImporterFlags.PrimaryInteropAssembly) != 0,
- (flags & TypeLibImporterFlags.ReflectionOnlyLoading) != 0,
- (flags & TypeLibImporterFlags.NoDefineVersionResource) != 0);
-
- // Define a dynamic module that will contain the contain the imported types.
- String strNonQualifiedAsmFileName = Path.GetFileName(asmFileName);
- ModuleBuilder modBldr = asmBldr.DefineDynamicModule(strNonQualifiedAsmFileName, strNonQualifiedAsmFileName);
-
- // If the namespace hasn't been specified, then use the assembly name.
- if (asmNamespace == null)
- asmNamespace = asmName.Name;
-
- // Create a type resolve handler that will also intercept resolve ref messages
- // on the sink interface to build up a list of referenced assemblies.
- TypeResolveHandler typeResolveHandler = new TypeResolveHandler(modBldr, notifySink);
-
- // Add a listener for the type resolve events.
- AppDomain currentDomain = Thread.GetDomain();
- ResolveEventHandler resolveHandler = new ResolveEventHandler(typeResolveHandler.ResolveEvent);
- ResolveEventHandler asmResolveHandler = new ResolveEventHandler(typeResolveHandler.ResolveAsmEvent);
- ResolveEventHandler ROAsmResolveHandler = new ResolveEventHandler(typeResolveHandler.ResolveROAsmEvent);
- currentDomain.TypeResolve += resolveHandler;
- currentDomain.AssemblyResolve += asmResolveHandler;
- currentDomain.ReflectionOnlyAssemblyResolve += ROAsmResolveHandler;
-
- // Convert the types contained in the typelib into metadata and add them to the assembly.
- nConvertTypeLibToMetadata(typeLib, asmBldr.InternalAssembly, modBldr.InternalModule, asmNamespace, flags, typeResolveHandler, out eventItfInfoList);
-
- // Update the COM types in the assembly.
- UpdateComTypesInAssembly(asmBldr, modBldr);
-
- // If there are any event sources then generate the TCE adapters.
- if (eventItfInfoList.Count > 0)
- new TCEAdapterGenerator().Process(modBldr, eventItfInfoList);
-
- // Remove the listener for the type resolve events.
- currentDomain.TypeResolve -= resolveHandler;
- currentDomain.AssemblyResolve -= asmResolveHandler;
- currentDomain.ReflectionOnlyAssemblyResolve -= ROAsmResolveHandler;
-
- // We have finished converting the typelib and now have a fully formed assembly.
- return asmBldr;
- }
-
- [System.Security.SecuritySafeCritical] // auto-generated
- [SecurityPermissionAttribute(SecurityAction.Demand, Flags=SecurityPermissionFlag.UnmanagedCode)]
- [return : MarshalAs(UnmanagedType.Interface)]
- public Object ConvertAssemblyToTypeLib(Assembly assembly, String strTypeLibName, TypeLibExporterFlags flags, ITypeLibExporterNotifySink notifySink)
- {
- RuntimeAssembly rtAssembly;
- AssemblyBuilder ab = assembly as AssemblyBuilder;
- if (ab != null)
- rtAssembly = ab.InternalAssembly;
- else
- rtAssembly = assembly as RuntimeAssembly;
-
- return nConvertAssemblyToTypeLib(rtAssembly, strTypeLibName, flags, notifySink);
- }
-
- public bool GetPrimaryInteropAssembly(Guid g, Int32 major, Int32 minor, Int32 lcid, out String asmName, out String asmCodeBase)
- {
- String strTlbId = "{" + g.ToString().ToUpper(CultureInfo.InvariantCulture) + "}";
- String strVersion = major.ToString("x", CultureInfo.InvariantCulture) + "." + minor.ToString("x", CultureInfo.InvariantCulture);
-
- // Set the two out values to null before we start.
- asmName = null;
- asmCodeBase = null;
-
- // Try to open the HKEY_CLASS_ROOT\TypeLib key.
- using (RegistryKey TypeLibKey = Registry.ClassesRoot.OpenSubKey("TypeLib", false))
- {
- if (TypeLibKey != null)
- {
- // Try to open the HKEY_CLASS_ROOT\TypeLib\<TLBID> key.
- using (RegistryKey TypeLibSubKey = TypeLibKey.OpenSubKey(strTlbId))
- {
- if (TypeLibSubKey != null)
- {
- // Try to open the HKEY_CLASS_ROOT\TypeLib\<TLBID>\<Major.Minor> key.
- using (RegistryKey VersionKey = TypeLibSubKey.OpenSubKey(strVersion, false))
- {
- if (VersionKey != null)
- {
- // Attempt to retrieve the assembly name and codebase under the version key.
- asmName = (String)VersionKey.GetValue("PrimaryInteropAssemblyName");
- asmCodeBase = (String)VersionKey.GetValue("PrimaryInteropAssemblyCodeBase");
- }
- }
- }
- }
- }
- }
-
- // If the assembly name isn't null, then we found an PIA.
- return asmName != null;
- }
-
-
- //
- // Non native helper methods.
- //
-
- [System.Security.SecurityCritical] // auto-generated
- [MethodImplAttribute(MethodImplOptions.NoInlining)] // Methods containing StackCrawlMark local var has to be marked non-inlineable
- private static AssemblyBuilder CreateAssemblyForTypeLib(Object typeLib, String asmFileName, AssemblyName asmName, bool bPrimaryInteropAssembly, bool bReflectionOnly, bool bNoDefineVersionResource)
- {
- // Retrieve the current app domain.
- AppDomain currentDomain = Thread.GetDomain();
-
- // Retrieve the directory from the assembly file name.
- String dir = null;
- if (asmFileName != null)
- {
- dir = Path.GetDirectoryName(asmFileName);
- if (String.IsNullOrEmpty(dir))
- dir = null;
- }
-
- AssemblyBuilderAccess aba;
- if (bReflectionOnly)
- {
- aba = AssemblyBuilderAccess.ReflectionOnly;
- }
- else
- {
- aba = AssemblyBuilderAccess.RunAndSave;
- }
-
- // Create the dynamic assembly itself.
- AssemblyBuilder asmBldr;
-
- List<CustomAttributeBuilder> assemblyAttributes = new List<CustomAttributeBuilder>();
-#if !FEATURE_CORECLR
- // mscorlib.dll must specify the security rules that assemblies it emits are to use, since by
- // default all assemblies will follow security rule set level 2, and we want to make that an
- // explicit decision.
- ConstructorInfo securityRulesCtor = typeof(SecurityRulesAttribute).GetConstructor(new Type[] { typeof(SecurityRuleSet) });
- CustomAttributeBuilder securityRulesAttribute =
- new CustomAttributeBuilder(securityRulesCtor, new object[] { SecurityRuleSet.Level2 });
- assemblyAttributes.Add(securityRulesAttribute);
-#endif // !FEATURE_CORECLR
-
- asmBldr = currentDomain.DefineDynamicAssembly(asmName, aba, dir, false, assemblyAttributes);
-
- // Set the Guid custom attribute on the assembly.
- SetGuidAttributeOnAssembly(asmBldr, typeLib);
-
- // Set the imported from COM attribute on the assembly and return it.
- SetImportedFromTypeLibAttrOnAssembly(asmBldr, typeLib);
-
- // Set the version information on the typelib.
- if (bNoDefineVersionResource)
- {
- SetTypeLibVersionAttribute(asmBldr, typeLib);
- }
- else
- {
- SetVersionInformation(asmBldr, typeLib, asmName);
- }
-
- // If we are generating a PIA, then set the PIA custom attribute.
- if (bPrimaryInteropAssembly)
- SetPIAAttributeOnAssembly(asmBldr, typeLib);
-
- return asmBldr;
- }
-
- [System.Security.SecurityCritical] // auto-generated
- internal static AssemblyName GetAssemblyNameFromTypelib(Object typeLib, String asmFileName, byte[] publicKey, StrongNameKeyPair keyPair, Version asmVersion, AssemblyNameFlags asmNameFlags)
- {
- // Extract the name of the typelib.
- String strTypeLibName = null;
- String strDocString = null;
- int dwHelpContext = 0;
- String strHelpFile = null;
- ITypeLib pTLB = (ITypeLib)typeLib;
- pTLB.GetDocumentation(-1, out strTypeLibName, out strDocString, out dwHelpContext, out strHelpFile);
-
- // Retrieve the name to use for the assembly.
- if (asmFileName == null)
- {
- asmFileName = strTypeLibName;
- }
- else
- {
- Contract.Assert((asmFileName != null) && (asmFileName.Length > 0), "The assembly file name cannot be an empty string!");
-
- String strFileNameNoPath = Path.GetFileName(asmFileName);
- String strExtension = Path.GetExtension(asmFileName);
-
- // Validate that the extension is valid.
- bool bExtensionValid = ".dll".Equals(strExtension, StringComparison.OrdinalIgnoreCase);
-
- // If the extension is not valid then tell the user and quit.
- if (!bExtensionValid)
- throw new ArgumentException(Environment.GetResourceString("Arg_InvalidFileExtension"));
-
- // The assembly cannot contain the path nor the extension.
- asmFileName = strFileNameNoPath.Substring(0, strFileNameNoPath.Length - ".dll".Length);
- }
-
- // If the version information was not specified, then retrieve it from the typelib.
- if (asmVersion == null)
- {
- int major;
- int minor;
- Marshal.GetTypeLibVersion(pTLB, out major, out minor);
- asmVersion = new Version(major, minor, 0, 0);
- }
-
- // Create the assembly name for the imported typelib's assembly.
- AssemblyName AsmName = new AssemblyName();
- AsmName.Init(
- asmFileName,
- publicKey,
- null,
- asmVersion,
- null,
- AssemblyHashAlgorithm.None,
- AssemblyVersionCompatibility.SameMachine,
- null,
- asmNameFlags,
- keyPair);
-
- return AsmName;
- }
-
- private static void UpdateComTypesInAssembly(AssemblyBuilder asmBldr, ModuleBuilder modBldr)
- {
- // Retrieve the AssemblyBuilderData associated with the assembly builder.
- AssemblyBuilderData AsmBldrData = asmBldr.m_assemblyData;
-
- // Go through the types in the module and add them as public COM types.
- Type[] aTypes = modBldr.GetTypes();
- int NumTypes = aTypes.Length;
- for (int cTypes = 0; cTypes < NumTypes; cTypes++)
- AsmBldrData.AddPublicComType(aTypes[cTypes]);
- }
-
-
- [System.Security.SecurityCritical] // auto-generated
- private static void SetGuidAttributeOnAssembly(AssemblyBuilder asmBldr, Object typeLib)
- {
- // Retrieve the GuidAttribute constructor.
- Type []aConsParams = new Type[1] {typeof(String)};
- ConstructorInfo GuidAttrCons = typeof(GuidAttribute).GetConstructor(aConsParams);
-
- // Create an instance of the custom attribute builder.
- Object[] aArgs = new Object[1] {Marshal.GetTypeLibGuid((ITypeLib)typeLib).ToString()};
- CustomAttributeBuilder GuidCABuilder = new CustomAttributeBuilder(GuidAttrCons, aArgs);
-
- // Set the GuidAttribute on the assembly builder.
- asmBldr.SetCustomAttribute(GuidCABuilder);
- }
-
- [System.Security.SecurityCritical] // auto-generated
- private static void SetImportedFromTypeLibAttrOnAssembly(AssemblyBuilder asmBldr, Object typeLib)
- {
- // Retrieve the ImportedFromTypeLibAttribute constructor.
- Type []aConsParams = new Type[1] {typeof(String)};
- ConstructorInfo ImpFromComAttrCons = typeof(ImportedFromTypeLibAttribute).GetConstructor(aConsParams);
-
- // Retrieve the name of the typelib.
- String strTypeLibName = Marshal.GetTypeLibName((ITypeLib)typeLib);
-
- // Create an instance of the custom attribute builder.
- Object[] aArgs = new Object[1] {strTypeLibName};
- CustomAttributeBuilder ImpFromComCABuilder = new CustomAttributeBuilder(ImpFromComAttrCons, aArgs);
-
- // Set the ImportedFromTypeLibAttribute on the assembly builder.
- asmBldr.SetCustomAttribute(ImpFromComCABuilder);
- }
-
- [System.Security.SecurityCritical] // auto-generated
- private static void SetTypeLibVersionAttribute(AssemblyBuilder asmBldr, Object typeLib)
- {
- Type []aConsParams = new Type[2] {typeof(int), typeof(int)};
- ConstructorInfo TypeLibVerCons = typeof(TypeLibVersionAttribute).GetConstructor(aConsParams);
-
- // Get the typelib version
- int major;
- int minor;
- Marshal.GetTypeLibVersion((ITypeLib)typeLib, out major, out minor);
-
- // Create an instance of the custom attribute builder.
- Object[] aArgs = new Object[2] {major, minor};
- CustomAttributeBuilder TypeLibVerBuilder = new CustomAttributeBuilder(TypeLibVerCons, aArgs);
-
- // Set the attribute on the assembly builder.
- asmBldr.SetCustomAttribute(TypeLibVerBuilder);
- }
-
- [System.Security.SecurityCritical] // auto-generated
- private static void SetVersionInformation(AssemblyBuilder asmBldr, Object typeLib, AssemblyName asmName)
- {
- // Extract the name of the typelib.
- String strTypeLibName = null;
- String strDocString = null;
- int dwHelpContext = 0;
- String strHelpFile = null;
- ITypeLib pTLB = (ITypeLib)typeLib;
- pTLB.GetDocumentation(-1, out strTypeLibName, out strDocString, out dwHelpContext, out strHelpFile);
-
- // Generate the product name string from the named of the typelib.
- String strProductName = String.Format(CultureInfo.InvariantCulture, Environment.GetResourceString("TypeLibConverter_ImportedTypeLibProductName"), strTypeLibName);
-
- // Set the OS version information.
- asmBldr.DefineVersionInfoResource(strProductName, asmName.Version.ToString(), null, null, null);
-
- // Set the TypeLibVersion attribute
- SetTypeLibVersionAttribute(asmBldr, typeLib);
- }
-
- [System.Security.SecurityCritical] // auto-generated
- private static void SetPIAAttributeOnAssembly(AssemblyBuilder asmBldr, Object typeLib)
- {
- IntPtr pAttr = IntPtr.Zero;
- _TYPELIBATTR Attr;
- ITypeLib pTLB = (ITypeLib)typeLib;
- int Major = 0;
- int Minor = 0;
-
- // Retrieve the PrimaryInteropAssemblyAttribute constructor.
- Type []aConsParams = new Type[2] {typeof(int), typeof(int)};
- ConstructorInfo PIAAttrCons = typeof(PrimaryInteropAssemblyAttribute).GetConstructor(aConsParams);
-
- // Retrieve the major and minor version from the typelib.
- try
- {
- pTLB.GetLibAttr(out pAttr);
- Attr = (_TYPELIBATTR)Marshal.PtrToStructure(pAttr, typeof(_TYPELIBATTR));
- Major = Attr.wMajorVerNum;
- Minor = Attr.wMinorVerNum;
- }
- finally
- {
- // Release the typelib attributes.
- if (pAttr != IntPtr.Zero)
- pTLB.ReleaseTLibAttr(pAttr);
- }
-
- // Create an instance of the custom attribute builder.
- Object[] aArgs = new Object[2] {Major, Minor};
- CustomAttributeBuilder PIACABuilder = new CustomAttributeBuilder(PIAAttrCons, aArgs);
-
- // Set the PrimaryInteropAssemblyAttribute on the assembly builder.
- asmBldr.SetCustomAttribute(PIACABuilder);
- }
-
-
- //
- // Native helper methods.
- //
-
- [System.Security.SecurityCritical] // auto-generated
- [MethodImplAttribute(MethodImplOptions.InternalCall)]
- private static extern void nConvertTypeLibToMetadata(Object typeLib, RuntimeAssembly asmBldr, RuntimeModule modBldr, String nameSpace, TypeLibImporterFlags flags, ITypeLibImporterNotifySink notifySink, out ArrayList eventItfInfoList);
-
- // Must use assembly versioning or GuidAttribute to avoid collisions in typelib export or registration.
- [System.Security.SecurityCritical] // auto-generated
- [MethodImplAttribute(MethodImplOptions.InternalCall)]
- private static extern Object nConvertAssemblyToTypeLib(RuntimeAssembly assembly, String strTypeLibName, TypeLibExporterFlags flags, ITypeLibExporterNotifySink notifySink);
-
- [System.Security.SecurityCritical] // auto-generated
- [DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode), SuppressUnmanagedCodeSecurity]
- internal extern static void LoadInMemoryTypeByName(RuntimeModule module, String className);
-
- //
- // Helper class called when a resolve type event is fired.
- //
-
- private class TypeResolveHandler : ITypeLibImporterNotifySink
- {
- public TypeResolveHandler(ModuleBuilder mod, ITypeLibImporterNotifySink userSink)
- {
- m_Module = mod;
- m_UserSink = userSink;
- }
-
- public void ReportEvent(ImporterEventKind eventKind, int eventCode, String eventMsg)
- {
- m_UserSink.ReportEvent(eventKind, eventCode, eventMsg);
- }
-
- public Assembly ResolveRef(Object typeLib)
- {
- Contract.Ensures(Contract.Result<Assembly>() != null && Contract.Result<Assembly>() is RuntimeAssembly);
- Contract.EndContractBlock();
-
- // Call the user sink to resolve the reference.
- Assembly asm = m_UserSink.ResolveRef(typeLib);
-
- if (asm == null)
- throw new ArgumentNullException();
-
- // Return the resolved assembly. We extract the internal assembly because we are called
- // by the VM which accesses fields of the object directly and does not go via those
- // delegating properties (the fields are empty if asm is an (external) AssemblyBuilder).
-
- RuntimeAssembly rtAssembly = asm as RuntimeAssembly;
- if (rtAssembly == null)
- {
- AssemblyBuilder ab = asm as AssemblyBuilder;
- if (ab != null)
- rtAssembly = ab.InternalAssembly;
- }
-
- if (rtAssembly == null)
- throw new ArgumentException(Environment.GetResourceString("Argument_MustBeRuntimeAssembly"));
-
- // Add the assembly to the list of assemblies.
- m_AsmList.Add(rtAssembly);
-
- return rtAssembly;
- }
-
- [System.Security.SecurityCritical] // auto-generated
- public Assembly ResolveEvent(Object sender, ResolveEventArgs args)
- {
- // We need to load the type in the resolve event so that we will deal with
- // cases where we are trying to load the CoClass before the interface has
- // been loaded.
- try
- {
- LoadInMemoryTypeByName(m_Module.GetNativeHandle(), args.Name);
- return m_Module.Assembly;
- }
- catch (TypeLoadException e)
- {
- if (e.ResourceId != System.__HResults.COR_E_TYPELOAD) // type not found
- throw;
- }
-
- foreach (RuntimeAssembly asm in m_AsmList)
- {
- try
- {
- asm.GetType(args.Name, true, false);
- return asm;
- }
- catch (TypeLoadException e)
- {
- if (e._HResult != System.__HResults.COR_E_TYPELOAD) // type not found
- throw;
- }
- }
-
- return null;
- }
-
- public Assembly ResolveAsmEvent(Object sender, ResolveEventArgs args)
- {
- foreach (RuntimeAssembly asm in m_AsmList)
- {
- if (String.Compare(asm.FullName, args.Name, StringComparison.OrdinalIgnoreCase) == 0)
- return asm;
- }
-
- return null;
- }
-
- public Assembly ResolveROAsmEvent(Object sender, ResolveEventArgs args)
- {
- foreach (RuntimeAssembly asm in m_AsmList)
- {
- if (String.Compare(asm.FullName, args.Name, StringComparison.OrdinalIgnoreCase) == 0)
- return asm;
- }
-
- // We failed to find the referenced assembly in our pre-loaded assemblies, so try to load it based on policy.
- string asmName = AppDomain.CurrentDomain.ApplyPolicy(args.Name);
- return Assembly.ReflectionOnlyLoad(asmName);
- }
-
- private ModuleBuilder m_Module;
- private ITypeLibImporterNotifySink m_UserSink;
- private List<RuntimeAssembly> m_AsmList = new List<RuntimeAssembly>();
- }
- }
-}
-#endif // !FEATURE_CORECLR // current implementation requires reflection only load
-
/// to and from COM calls.
/// </summary>
[StructLayout(LayoutKind.Explicit)]
- [System.Security.SecurityCritical]
internal struct Variant {
#if DEBUG
using System.Security;
using System.Collections;
using System.Collections.Generic;
+using System.Diagnostics;
using System.Diagnostics.Contracts;
using System.Runtime.InteropServices;
using System.Runtime.CompilerServices;
{
private BindableVectorToCollectionAdapter()
{
- Contract.Assert(false, "This class is never instantiated");
+ Debug.Assert(false, "This class is never instantiated");
}
// int Count { get }
[Pure]
- [SecurityCritical]
internal int Count()
{
IBindableVector _this = JitHelpers.UnsafeCast<IBindableVector>(this);
// bool IsSynchronized { get }
[Pure]
- [SecurityCritical]
internal bool IsSynchronized()
{
return false;
// object SyncRoot { get }
[Pure]
- [SecurityCritical]
internal object SyncRoot()
{
return this;
// void CopyTo(Array array, int index)
[Pure]
- [SecurityCritical]
internal void CopyTo(Array array, int arrayIndex)
{
if (array == null)
using System.Security;
using System.Collections;
using System.Collections.Generic;
+using System.Diagnostics;
using System.Diagnostics.Contracts;
using System.Runtime.InteropServices;
using System.Runtime.CompilerServices;
{
private BindableVectorToListAdapter()
{
- Contract.Assert(false, "This class is never instantiated");
+ Debug.Assert(false, "This class is never instantiated");
}
// object this[int index] { get }
- [SecurityCritical]
internal object Indexer_Get(int index)
{
if (index < 0)
}
// object this[int index] { set }
- [SecurityCritical]
internal void Indexer_Set(int index, object value)
{
if (index < 0)
}
// int Add(object value)
- [SecurityCritical]
internal int Add(object value)
{
IBindableVector _this = JitHelpers.UnsafeCast<IBindableVector>(this);
}
// bool Contains(object item)
- [SecurityCritical]
internal bool Contains(object item)
{
IBindableVector _this = JitHelpers.UnsafeCast<IBindableVector>(this);
}
// void Clear()
- [SecurityCritical]
internal void Clear()
{
IBindableVector _this = JitHelpers.UnsafeCast<IBindableVector>(this);
// bool IsFixedSize { get }
[Pure]
- [SecurityCritical]
internal bool IsFixedSize()
{
return false;
// bool IsReadOnly { get }
[Pure]
- [SecurityCritical]
internal bool IsReadOnly()
{
return false;
}
// int IndexOf(object item)
- [SecurityCritical]
internal int IndexOf(object item)
{
IBindableVector _this = JitHelpers.UnsafeCast<IBindableVector>(this);
}
// void Insert(int index, object item)
- [SecurityCritical]
internal void Insert(int index, object item)
{
if (index < 0)
}
// bool Remove(object item)
- [SecurityCritical]
internal void Remove(object item)
{
IBindableVector _this = JitHelpers.UnsafeCast<IBindableVector>(this);
}
// void RemoveAt(int index)
- [SecurityCritical]
internal void RemoveAt(int index)
{
if (index < 0)
}
[Pure]
- [SecuritySafeCritical]
public Point GetPoint()
{
if (this.Type != PropertyType.Point)
}
[Pure]
- [SecuritySafeCritical]
public Size GetSize()
{
if (this.Type != PropertyType.Size)
}
[Pure]
- [SecuritySafeCritical]
public Rect GetRect()
{
if (this.Type != PropertyType.Rect)
}
[Pure]
- [SecuritySafeCritical]
public Point[] GetPointArray()
{
if (this.Type != PropertyType.PointArray)
}
[Pure]
- [SecuritySafeCritical]
public Size[] GetSizeArray()
{
if (this.Type != PropertyType.SizeArray)
}
[Pure]
- [SecuritySafeCritical]
public Rect[] GetRectArray()
{
if (this.Type != PropertyType.RectArray)
// Unbox the data stored in the property value to a structurally equivilent type
[Pure]
- [SecurityCritical]
private unsafe T Unbox<T>(Type expectedBoxedType) where T : struct {
Contract.Requires(expectedBoxedType != null);
Contract.Requires(Marshal.SizeOf(expectedBoxedType) == Marshal.SizeOf(typeof(T)));
// Convert the array stored in the property value to a structurally equivilent array type
[Pure]
- [SecurityCritical]
private unsafe T[] UnboxArray<T>(Type expectedArrayElementType) where T : struct {
Contract.Requires(expectedArrayElementType != null);
Contract.Requires(Marshal.SizeOf(expectedArrayElementType) == Marshal.SizeOf(typeof(T)));
using System;
using System.Collections;
+using System.Diagnostics;
using System.Diagnostics.Contracts;
using System.Reflection;
using System.Security;
{
Contract.Requires(wrapper != null);
IReference<T> reference = (IReference<T>) wrapper;
- Contract.Assert(reference != null, "CLRIReferenceImpl::UnboxHelper - QI'ed for IReference<"+typeof(T)+">, but that failed.");
+ Debug.Assert(reference != null, "CLRIReferenceImpl::UnboxHelper - QI'ed for IReference<"+typeof(T)+">, but that failed.");
return reference.Value;
}
}
{
Contract.Requires(wrapper != null);
IReferenceArray<T> reference = (IReferenceArray<T>)wrapper;
- Contract.Assert(reference != null, "CLRIReferenceArrayImpl::UnboxHelper - QI'ed for IReferenceArray<" + typeof(T) + ">, but that failed.");
+ Debug.Assert(reference != null, "CLRIReferenceArrayImpl::UnboxHelper - QI'ed for IReferenceArray<" + typeof(T) + ">, but that failed.");
T[] marshaled = reference.Value;
return marshaled;
}
internal static readonly Type s_rectType = Type.GetType("Windows.Foundation.Rect, " + AssemblyRef.SystemRuntimeWindowsRuntime);
internal static readonly Type s_sizeType = Type.GetType("Windows.Foundation.Size, " + AssemblyRef.SystemRuntimeWindowsRuntime);
- [SecuritySafeCritical]
internal static Object CreateIReference(Object obj)
{
Contract.Requires(obj != null, "Null should not be boxed.");
return Activator.CreateInstance(specificType, new Object[] { propType.Value, obj });
}
- Contract.Assert(false, "We should not see non-WinRT type here");
+ Debug.Assert(false, "We should not see non-WinRT type here");
return null;
}
- [SecuritySafeCritical]
internal static Object CreateIReferenceArray(Array obj)
{
Contract.Requires(obj != null);
Type type = obj.GetType().GetElementType();
- Contract.Assert(obj.Rank == 1 && obj.GetLowerBound(0) == 0 && !type.IsArray);
+ Debug.Assert(obj.Rank == 1 && obj.GetLowerBound(0) == 0 && !type.IsArray);
if (type == typeof(int))
return new CLRIReferenceArrayImpl<int>(PropertyType.Int32Array, (int[])obj);
using System;
using System.Security;
using System.Reflection;
+using System.Diagnostics;
using System.Diagnostics.Contracts;
using System.Runtime.InteropServices;
using System.Runtime.CompilerServices;
InvokeInternal(target, new object[] { indexValue, value }, false);
}
- [SecuritySafeCritical]
private object InvokeInternal(object target, object[] args, bool getValue)
{
// Forward to the right object if we are dealing with a proxy
// We can safely skip access check because this is only used in full trust scenarios.
// And we have already verified that the property accessor is public.
- Contract.Assert(AppDomain.CurrentDomain.PermissionSet.IsUnrestricted());
+ Debug.Assert(AppDomain.CurrentDomain.PermissionSet.IsUnrestricted());
return rtMethod.UnsafeInvoke(target, BindingFlags.Default, null, args, null);
}
using System.Collections;
using System.Collections.Generic;
using System.Collections.ObjectModel;
+using System.Diagnostics;
using System.Diagnostics.Contracts;
using System.Runtime.InteropServices;
using System.Runtime.CompilerServices;
{
private DictionaryToMapAdapter()
{
- Contract.Assert(false, "This class is never instantiated");
+ Debug.Assert(false, "This class is never instantiated");
}
// V Lookup(K key)
- [SecurityCritical]
internal V Lookup<K, V>(K key)
{
IDictionary<K, V> _this = JitHelpers.UnsafeCast<IDictionary<K, V>>(this);
}
// uint Size { get }
- [SecurityCritical]
internal uint Size<K, V>()
{
IDictionary<K, V> _this = JitHelpers.UnsafeCast<IDictionary<K, V>>(this);
}
// bool HasKey(K key)
- [SecurityCritical]
internal bool HasKey<K, V>(K key)
{
IDictionary<K, V> _this = JitHelpers.UnsafeCast<IDictionary<K, V>>(this);
}
// IMapView<K, V> GetView()
- [SecurityCritical]
internal IReadOnlyDictionary<K, V> GetView<K, V>()
{
IDictionary<K, V> _this = JitHelpers.UnsafeCast<IDictionary<K, V>>(this);
- Contract.Assert(_this != null);
+ Debug.Assert(_this != null);
// Note: This dictionary is not really read-only - you could QI for a modifiable
// dictionary. We gain some perf by doing this. We believe this is acceptable.
}
// bool Insert(K key, V value)
- [SecurityCritical]
internal bool Insert<K, V>(K key, V value)
{
IDictionary<K, V> _this = JitHelpers.UnsafeCast<IDictionary<K, V>>(this);
}
// void Remove(K key)
- [SecurityCritical]
internal void Remove<K, V>(K key)
{
IDictionary<K, V> _this = JitHelpers.UnsafeCast<IDictionary<K, V>>(this);
}
// void Clear()
- [SecurityCritical]
internal void Clear<K, V>()
{
IDictionary<K, V> _this = JitHelpers.UnsafeCast<IDictionary<K, V>>(this);
using System;
using System.Collections;
using System.Collections.Generic;
+using System.Diagnostics;
using System.Diagnostics.Contracts;
using System.Runtime.InteropServices;
using System.Runtime.CompilerServices;
{
private EnumerableToIterableAdapter()
{
- Contract.Assert(false, "This class is never instantiated");
+ Debug.Assert(false, "This class is never instantiated");
}
// This method is invoked when First is called on a managed implementation of IIterable<T>.
- [System.Security.SecurityCritical]
internal IIterator<T> First_Stub<T>()
{
IEnumerable<T> _this = JitHelpers.UnsafeCast<IEnumerable<T>>(this);
{
private EnumerableToBindableIterableAdapter()
{
- Contract.Assert(false, "This class is never instantiated");
+ Debug.Assert(false, "This class is never instantiated");
}
internal sealed class NonGenericToGenericEnumerator : IEnumerator<object>
}
// This method is invoked when First is called on a managed implementation of IBindableIterable.
- [System.Security.SecurityCritical]
internal IBindableIterator First_Stub()
{
IEnumerable _this = JitHelpers.UnsafeCast<IEnumerable>(this);
using System;
using System.Security;
using System.Collections;
+using System.Diagnostics;
using System.Diagnostics.Contracts;
using System.Runtime.CompilerServices;
{
private IDisposableToIClosableAdapter()
{
- Contract.Assert(false, "This class is never instantiated");
+ Debug.Assert(false, "This class is never instantiated");
}
- [SecurityCritical]
public void Close()
{
IDisposable _this = JitHelpers.UnsafeCast<IDisposable>(this);
}
// Adapter class which converts IDisposable.Dispose calls into IClosable.Close
- [SecurityCritical]
internal sealed class IClosableToIDisposableAdapter
{
private IClosableToIDisposableAdapter()
{
- Contract.Assert(false, "This class is never instantiated");
+ Debug.Assert(false, "This class is never instantiated");
}
- [SecurityCritical]
private void Dispose()
{
IClosable _this = JitHelpers.UnsafeCast<IClosable>(this);
// Creates a ICustomProperty implementation for Jupiter
// Called from ICustomPropertyProvider_GetIndexedProperty from within runtime
//
- [System.Security.SecurityCritical]
static internal unsafe ICustomProperty CreateIndexedProperty(object target, string propertyName, TypeNameNative *pIndexedParamType)
{
Contract.Requires(target != null);
return new CustomPropertyImpl(propertyInfo);
}
- [System.Security.SecurityCritical]
static internal unsafe void GetType(object target, TypeNameNative *pIndexedParamType)
{
IGetProxyTarget proxy = target as IGetProxyTarget;
//
// ICustomQueryInterface methods
//
- [System.Security.SecurityCritical]
public CustomQueryInterfaceResult GetInterface([In]ref Guid iid, out IntPtr ppv)
{
ppv = IntPtr.Zero;
}
}
- [SecuritySafeCritical]
private IBindableVector GetIBindableVectorNoThrow()
{
if ((_flags & InterfaceForwardingSupport.IBindableVector) != 0)
return null;
}
- [SecuritySafeCritical]
private IVector_Raw<T1> GetVectorOfT()
{
if ((_flags & InterfaceForwardingSupport.IVector) != 0)
public bool MoveNext() { return _iterator.MoveNext(); }
}
- [SecuritySafeCritical]
private IBindableVectorView GetIBindableVectorViewNoThrow()
{
if ((_flags & InterfaceForwardingSupport.IBindableVectorView) != 0)
return null;
}
- [SecuritySafeCritical]
private IVectorView<T2> GetVectorViewOfT()
{
if ((_flags & InterfaceForwardingSupport.IVectorView) != 0)
{
private IMapViewToIReadOnlyDictionaryAdapter()
{
- Contract.Assert(false, "This class is never instantiated");
+ Debug.Assert(false, "This class is never instantiated");
}
// V this[K key] { get }
- [SecurityCritical]
internal V Indexer_Get<K, V>(K key)
{
if (key == null)
}
// IEnumerable<K> Keys { get }
- [SecurityCritical]
internal IEnumerable<K> Keys<K, V>()
{
IMapView<K, V> _this = JitHelpers.UnsafeCast<IMapView<K, V>>(this);
}
// IEnumerable<V> Values { get }
- [SecurityCritical]
internal IEnumerable<V> Values<K, V>()
{
IMapView<K, V> _this = JitHelpers.UnsafeCast<IMapView<K, V>>(this);
// bool ContainsKey(K key)
[Pure]
- [SecurityCritical]
internal bool ContainsKey<K, V>(K key)
{
if (key == null)
}
// bool TryGetValue(TKey key, out TValue value)
- [SecurityCritical]
internal bool TryGetValue<K, V>(K key, out V value)
{
if (key == null)
{
private IReadOnlyDictionaryToIMapViewAdapter()
{
- Contract.Assert(false, "This class is never instantiated");
+ Debug.Assert(false, "This class is never instantiated");
}
// V Lookup(K key)
- [SecurityCritical]
internal V Lookup<K, V>(K key)
{
IReadOnlyDictionary<K, V> _this = JitHelpers.UnsafeCast<IReadOnlyDictionary<K, V>>(this);
}
// uint Size { get }
- [SecurityCritical]
internal uint Size<K, V>()
{
IReadOnlyDictionary<K, V> _this = JitHelpers.UnsafeCast<IReadOnlyDictionary<K, V>>(this);
}
// bool HasKey(K key)
- [SecurityCritical]
internal bool HasKey<K, V>(K key)
{
IReadOnlyDictionary<K, V> _this = JitHelpers.UnsafeCast<IReadOnlyDictionary<K, V>>(this);
}
// void Split(out IMapView<K, V> first, out IMapView<K, V> second)
- [SecurityCritical]
internal void Split<K, V>(out IMapView<K, V> first, out IMapView<K, V> second)
{
IReadOnlyDictionary<K, V> _this = JitHelpers.UnsafeCast<IReadOnlyDictionary<K, V>>(this);
{
private IReadOnlyListToIVectorViewAdapter()
{
- Contract.Assert(false, "This class is never instantiated");
+ Debug.Assert(false, "This class is never instantiated");
}
// T GetAt(uint index)
- [SecurityCritical]
internal T GetAt<T>(uint index)
{
IReadOnlyList<T> _this = JitHelpers.UnsafeCast<IReadOnlyList<T>>(this);
}
// uint Size { get }
- [SecurityCritical]
internal uint Size<T>()
{
IReadOnlyList<T> _this = JitHelpers.UnsafeCast<IReadOnlyList<T>>(this);
}
// bool IndexOf(T value, out uint index)
- [SecurityCritical]
internal bool IndexOf<T>(T value, out uint index)
{
IReadOnlyList<T> _this = JitHelpers.UnsafeCast<IReadOnlyList<T>>(this);
}
// uint GetMany(uint startIndex, T[] items)
- [SecurityCritical]
internal uint GetMany<T>(uint startIndex, T[] items)
{
IReadOnlyList<T> _this = JitHelpers.UnsafeCast<IReadOnlyList<T>>(this);
namespace System.Runtime.InteropServices.WindowsRuntime
{
-#if FEATURE_CORECLR
[System.Runtime.CompilerServices.FriendAccessAllowed]
-#endif
[ComImport]
[Guid("82BA7092-4C88-427D-A7BC-16DD93FEB67E")]
[InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
{
private IVectorViewToIReadOnlyListAdapter()
{
- Contract.Assert(false, "This class is never instantiated");
+ Debug.Assert(false, "This class is never instantiated");
}
// T this[int index] { get }
- [SecurityCritical]
internal T Indexer_Get<T>(int index)
{
if (index < 0)
}
// T this[int index] { get }
- [SecurityCritical]
internal T Indexer_Get_Variance<T>(int index) where T : class
{
bool fUseString;
using System;
using System.Collections;
using System.Collections.Generic;
+using System.Diagnostics;
using System.Diagnostics.Contracts;
using System.Runtime.InteropServices;
using System.Runtime.CompilerServices;
{
private IterableToEnumerableAdapter()
{
- Contract.Assert(false, "This class is never instantiated");
+ Debug.Assert(false, "This class is never instantiated");
}
// This method is invoked when GetEnumerator is called on a WinRT-backed implementation of IEnumerable<T>.
- [SecurityCritical]
internal IEnumerator<T> GetEnumerator_Stub<T>()
{
IIterable<T> _this = JitHelpers.UnsafeCast<IIterable<T>>(this);
// and it is possible that the implementation supports IEnumerable<Type>/IEnumerable<string>/IEnumerable<Exception>/
// IEnumerable<array>/IEnumerable<delegate> rather than IEnumerable<T> because T is assignable from Type/string/
// Exception/array/delegate via co-variance.
- [SecurityCritical]
internal IEnumerator<T> GetEnumerator_Variance_Stub<T>() where T : class
{
bool fUseString;
{
private BindableIterableToEnumerableAdapter()
{
- Contract.Assert(false, "This class is never instantiated");
+ Debug.Assert(false, "This class is never instantiated");
}
private sealed class NonGenericToGenericIterator : IIterator<object>
}
// This method is invoked when GetEnumerator is called on a WinRT-backed implementation of IEnumerable.
- [SecurityCritical]
internal IEnumerator GetEnumerator_Stub()
{
IBindableIterable _this = JitHelpers.UnsafeCast<IBindableIterable>(this);
}
}
- [SecuritySafeCritical]
public bool MoveNext()
{
// If we've passed the end of the iteration, IEnumerable<T> should return false, while
using System.Collections;
using System.Collections.Generic;
using System.Collections.ObjectModel;
+using System.Diagnostics;
using System.Diagnostics.Contracts;
using System.Runtime.InteropServices;
using System.Runtime.CompilerServices;
{
private ListToBindableVectorAdapter()
{
- Contract.Assert(false, "This class is never instantiated");
+ Debug.Assert(false, "This class is never instantiated");
}
// object GetAt(uint index)
- [SecurityCritical]
internal object GetAt(uint index)
{
IList _this = JitHelpers.UnsafeCast<IList>(this);
}
// uint Size { get }
- [SecurityCritical]
internal uint Size()
{
IList _this = JitHelpers.UnsafeCast<IList>(this);
}
// IBindableVectorView GetView()
- [SecurityCritical]
internal IBindableVectorView GetView()
{
IList _this = JitHelpers.UnsafeCast<IList>(this);
}
// bool IndexOf(object value, out uint index)
- [SecurityCritical]
internal bool IndexOf(object value, out uint index)
{
IList _this = JitHelpers.UnsafeCast<IList>(this);
}
// void SetAt(uint index, object value)
- [SecurityCritical]
internal void SetAt(uint index, object value)
{
IList _this = JitHelpers.UnsafeCast<IList>(this);
}
// void InsertAt(uint index, object value)
- [SecurityCritical]
internal void InsertAt(uint index, object value)
{
IList _this = JitHelpers.UnsafeCast<IList>(this);
}
// void RemoveAt(uint index)
- [SecurityCritical]
internal void RemoveAt(uint index)
{
IList _this = JitHelpers.UnsafeCast<IList>(this);
}
// void Append(object value)
- [SecurityCritical]
internal void Append(object value)
{
IList _this = JitHelpers.UnsafeCast<IList>(this);
}
// void RemoveAtEnd()
- [SecurityCritical]
internal void RemoveAtEnd()
{
IList _this = JitHelpers.UnsafeCast<IList>(this);
}
// void Clear()
- [SecurityCritical]
internal void Clear()
{
IList _this = JitHelpers.UnsafeCast<IList>(this);
using System.Collections;
using System.Collections.Generic;
using System.Collections.ObjectModel;
+using System.Diagnostics;
using System.Diagnostics.Contracts;
using System.Runtime.InteropServices;
using System.Runtime.CompilerServices;
{
private ListToVectorAdapter()
{
- Contract.Assert(false, "This class is never instantiated");
+ Debug.Assert(false, "This class is never instantiated");
}
// T GetAt(uint index)
- [SecurityCritical]
internal T GetAt<T>(uint index)
{
IList<T> _this = JitHelpers.UnsafeCast<IList<T>>(this);
}
// uint Size { get }
- [SecurityCritical]
internal uint Size<T>()
{
IList<T> _this = JitHelpers.UnsafeCast<IList<T>>(this);
}
// IVectorView<T> GetView()
- [SecurityCritical]
internal IReadOnlyList<T> GetView<T>()
{
IList<T> _this = JitHelpers.UnsafeCast<IList<T>>(this);
- Contract.Assert(_this != null);
+ Debug.Assert(_this != null);
// Note: This list is not really read-only - you could QI for a modifiable
// list. We gain some perf by doing this. We believe this is acceptable.
}
// bool IndexOf(T value, out uint index)
- [SecurityCritical]
internal bool IndexOf<T>(T value, out uint index)
{
IList<T> _this = JitHelpers.UnsafeCast<IList<T>>(this);
}
// void SetAt(uint index, T value)
- [SecurityCritical]
internal void SetAt<T>(uint index, T value)
{
IList<T> _this = JitHelpers.UnsafeCast<IList<T>>(this);
}
// void InsertAt(uint index, T value)
- [SecurityCritical]
internal void InsertAt<T>(uint index, T value)
{
IList<T> _this = JitHelpers.UnsafeCast<IList<T>>(this);
}
// void RemoveAt(uint index)
- [SecurityCritical]
internal void RemoveAt<T>(uint index)
{
IList<T> _this = JitHelpers.UnsafeCast<IList<T>>(this);
}
// void Append(T value)
- [SecurityCritical]
internal void Append<T>(T value)
{
IList<T> _this = JitHelpers.UnsafeCast<IList<T>>(this);
}
// void RemoveAtEnd()
- [SecurityCritical]
internal void RemoveAtEnd<T>()
{
IList<T> _this = JitHelpers.UnsafeCast<IList<T>>(this);
}
// void Clear()
- [SecurityCritical]
internal void Clear<T>()
{
IList<T> _this = JitHelpers.UnsafeCast<IList<T>>(this);
}
// uint GetMany(uint startIndex, T[] items)
- [SecurityCritical]
internal uint GetMany<T>(uint startIndex, T[] items)
{
IList<T> _this = JitHelpers.UnsafeCast<IList<T>>(this);
}
// void ReplaceAll(T[] items)
- [SecurityCritical]
internal void ReplaceAll<T>(T[] items)
{
IList<T> _this = JitHelpers.UnsafeCast<IList<T>>(this);
{
private Type m_type;
- [SecurityCritical]
internal ManagedActivationFactory(Type type)
{
if (type == null)
using System.Security;
using System.Collections;
using System.Collections.Generic;
+using System.Diagnostics;
using System.Diagnostics.Contracts;
using System.Runtime.InteropServices;
using System.Runtime.CompilerServices;
{
private MapToCollectionAdapter()
{
- Contract.Assert(false, "This class is never instantiated");
+ Debug.Assert(false, "This class is never instantiated");
}
// int Count { get }
[Pure]
- [SecurityCritical]
internal int Count<K, V>()
{
object _this = JitHelpers.UnsafeCast<object>(this);
}
// bool IsReadOnly { get }
- [SecurityCritical]
internal bool IsReadOnly<K, V>()
{
return false;
}
// void Add(T item)
- [SecurityCritical]
internal void Add<K, V>(KeyValuePair<K, V> item)
{
object _this = JitHelpers.UnsafeCast<object>(this);
}
// void Clear()
- [SecurityCritical]
internal void Clear<K, V>()
{
object _this = JitHelpers.UnsafeCast<object>(this);
}
// bool Contains(T item)
- [SecurityCritical]
internal bool Contains<K, V>(KeyValuePair<K, V> item)
{
object _this = JitHelpers.UnsafeCast<object>(this);
}
// void CopyTo(T[] array, int arrayIndex)
- [SecurityCritical]
internal void CopyTo<K, V>(KeyValuePair<K, V>[] array, int arrayIndex)
{
if (array == null)
}
// bool Remove(T item)
- [SecurityCritical]
internal bool Remove<K, V>(KeyValuePair<K, V> item)
{
object _this = JitHelpers.UnsafeCast<object>(this);
using System.Security;
using System.Collections;
using System.Collections.Generic;
+using System.Diagnostics;
using System.Diagnostics.Contracts;
using System.Runtime.InteropServices;
using System.Runtime.CompilerServices;
{
private MapToDictionaryAdapter()
{
- Contract.Assert(false, "This class is never instantiated");
+ Debug.Assert(false, "This class is never instantiated");
}
// V this[K key] { get }
- [SecurityCritical]
internal V Indexer_Get<K, V>(K key)
{
if (key == null)
}
// V this[K key] { set }
- [SecurityCritical]
internal void Indexer_Set<K, V>(K key, V value)
{
if (key == null)
}
// ICollection<K> Keys { get }
- [SecurityCritical]
internal ICollection<K> Keys<K, V>()
{
IMap<K, V> _this = JitHelpers.UnsafeCast<IMap<K, V>>(this);
}
// ICollection<V> Values { get }
- [SecurityCritical]
internal ICollection<V> Values<K, V>()
{
IMap<K, V> _this = JitHelpers.UnsafeCast<IMap<K, V>>(this);
// bool ContainsKey(K key)
[Pure]
- [SecurityCritical]
internal bool ContainsKey<K, V>(K key)
{
if (key == null)
}
// void Add(K key, V value)
- [SecurityCritical]
internal void Add<K, V>(K key, V value)
{
if (key == null)
}
// bool Remove(TKey key)
- [SecurityCritical]
internal bool Remove<K, V>(K key)
{
if (key == null)
}
// bool TryGetValue(TKey key, out TValue value)
- [SecurityCritical]
internal bool TryGetValue<K, V>(K key, out V value)
{
if (key == null)
using System.Security;
using System.Collections;
using System.Collections.Generic;
+using System.Diagnostics;
using System.Diagnostics.Contracts;
using System.Runtime.InteropServices;
using System.Runtime.CompilerServices;
{
private MapViewToReadOnlyCollectionAdapter()
{
- Contract.Assert(false, "This class is never instantiated");
+ Debug.Assert(false, "This class is never instantiated");
}
// int Count { get }
[Pure]
- [SecurityCritical]
internal int Count<K, V>()
{
object _this = JitHelpers.UnsafeCast<object>(this);
internal static class UnsafeNativeMethods
{
[DllImport("api-ms-win-core-winrt-error-l1-1-1.dll", PreserveSig = false)]
- [SecurityCritical]
[SuppressUnmanagedCodeSecurity]
internal static extern IRestrictedErrorInfo GetRestrictedErrorInfo();
[DllImport("api-ms-win-core-winrt-error-l1-1-1.dll")]
- [SecurityCritical]
[SuppressUnmanagedCodeSecurity]
[return: MarshalAs(UnmanagedType.Bool)]
internal static extern bool RoOriginateLanguageException(int error, [MarshalAs(UnmanagedType.HString)]string message, IntPtr languageException);
[DllImport("api-ms-win-core-winrt-error-l1-1-1.dll", PreserveSig = false)]
- [SecurityCritical]
[SuppressUnmanagedCodeSecurity]
internal static extern void RoReportUnhandledError(IRestrictedErrorInfo error);
[DllImport("api-ms-win-core-winrt-string-l1-1-0.dll", CallingConvention = CallingConvention.StdCall)]
- [SecurityCritical]
[SuppressUnmanagedCodeSecurity]
internal static unsafe extern int WindowsCreateString([MarshalAs(UnmanagedType.LPWStr)] string sourceString,
int length,
[Out] IntPtr *hstring);
[DllImport("api-ms-win-core-winrt-string-l1-1-0.dll", CallingConvention = CallingConvention.StdCall)]
- [SecurityCritical]
[SuppressUnmanagedCodeSecurity]
internal static unsafe extern int WindowsCreateStringReference(char *sourceString,
int length,
[Out] IntPtr *hstring);
[DllImport("api-ms-win-core-winrt-string-l1-1-0.dll", CallingConvention = CallingConvention.StdCall)]
- [SecurityCritical]
[SuppressUnmanagedCodeSecurity]
internal static extern int WindowsDeleteString(IntPtr hstring);
[DllImport("api-ms-win-core-winrt-string-l1-1-0.dll", CallingConvention = CallingConvention.StdCall)]
- [SecurityCritical]
[SuppressUnmanagedCodeSecurity]
internal static unsafe extern char* WindowsGetStringRawBuffer(IntPtr hstring, [Out] uint *length);
}
//
// Support for ToString/GetHashCode/Equals override
//
- [System.Security.SecurityCritical]
[MethodImpl(MethodImplOptions.InternalCall)]
internal extern IntPtr GetRedirectedGetHashCodeMD();
- [System.Security.SecurityCritical]
[MethodImpl(MethodImplOptions.InternalCall)]
internal extern int RedirectGetHashCode(IntPtr pMD);
- [System.Security.SecuritySafeCritical]
public override int GetHashCode()
{
IntPtr pMD = GetRedirectedGetHashCodeMD();
return RedirectGetHashCode(pMD);
}
- [System.Security.SecurityCritical]
[MethodImpl(MethodImplOptions.InternalCall)]
internal extern IntPtr GetRedirectedToStringMD();
- [System.Security.SecurityCritical]
[MethodImpl(MethodImplOptions.InternalCall)]
internal extern string RedirectToString(IntPtr pMD);
- [System.Security.SecuritySafeCritical]
public override string ToString()
{
// Check whether the type implements IStringable.
}
}
- [System.Security.SecurityCritical]
[MethodImpl(MethodImplOptions.InternalCall)]
internal extern IntPtr GetRedirectedEqualsMD();
- [System.Security.SecurityCritical]
[MethodImpl(MethodImplOptions.InternalCall)]
internal extern bool RedirectEquals(object obj, IntPtr pMD);
- [System.Security.SecuritySafeCritical]
public override bool Equals(object obj)
{
IntPtr pMD = GetRedirectedEqualsMD();
using System.Security;
using System.Collections;
using System.Collections.Generic;
+using System.Diagnostics;
using System.Diagnostics.Contracts;
using System.Runtime.InteropServices;
using System.Runtime.CompilerServices;
{
private VectorToCollectionAdapter()
{
- Contract.Assert(false, "This class is never instantiated");
+ Debug.Assert(false, "This class is never instantiated");
}
// int Count { get }
[Pure]
- [SecurityCritical]
internal int Count<T>()
{
IVector<T> _this = JitHelpers.UnsafeCast<IVector<T>>(this);
}
// bool IsReadOnly { get }
- [SecurityCritical]
internal bool IsReadOnly<T>()
{
return false;
}
// void Add(T item)
- [SecurityCritical]
internal void Add<T>(T item)
{
IVector<T> _this = JitHelpers.UnsafeCast<IVector<T>>(this);
}
// void Clear()
- [SecurityCritical]
internal void Clear<T>()
{
IVector<T> _this = JitHelpers.UnsafeCast<IVector<T>>(this);
}
// bool Contains(T item)
- [SecurityCritical]
internal bool Contains<T>(T item)
{
IVector<T> _this = JitHelpers.UnsafeCast<IVector<T>>(this);
}
// void CopyTo(T[] array, int arrayIndex)
- [SecurityCritical]
internal void CopyTo<T>(T[] array, int arrayIndex)
{
if (array == null)
}
// bool Remove(T item)
- [SecurityCritical]
internal bool Remove<T>(T item)
{
IVector<T> _this = JitHelpers.UnsafeCast<IVector<T>>(this);
using System.Security;
using System.Collections;
using System.Collections.Generic;
+using System.Diagnostics;
using System.Diagnostics.Contracts;
using System.Runtime.InteropServices;
using System.Runtime.CompilerServices;
{
private VectorToListAdapter()
{
- Contract.Assert(false, "This class is never instantiated");
+ Debug.Assert(false, "This class is never instantiated");
}
// T this[int index] { get }
- [SecurityCritical]
internal T Indexer_Get<T>(int index)
{
if (index < 0)
}
// T this[int index] { set }
- [SecurityCritical]
internal void Indexer_Set<T>(int index, T value)
{
if (index < 0)
}
// int IndexOf(T item)
- [SecurityCritical]
internal int IndexOf<T>(T item)
{
IVector<T> _this = JitHelpers.UnsafeCast<IVector<T>>(this);
}
// void Insert(int index, T item)
- [SecurityCritical]
internal void Insert<T>(int index, T item)
{
if (index < 0)
}
// void RemoveAt(int index)
- [SecurityCritical]
internal void RemoveAt<T>(int index)
{
if (index < 0)
using System.Security;
using System.Collections;
using System.Collections.Generic;
+using System.Diagnostics;
using System.Diagnostics.Contracts;
using System.Runtime.InteropServices;
using System.Runtime.CompilerServices;
{
private VectorViewToReadOnlyCollectionAdapter()
{
- Contract.Assert(false, "This class is never instantiated");
+ Debug.Assert(false, "This class is never instantiated");
}
// int Count { get }
[Pure]
- [SecurityCritical]
internal int Count<T>()
{
IVectorView<T> _this = JitHelpers.UnsafeCast<IVectorView<T>>(this);
internal static class WindowsRuntimeBufferHelper {
- [SecurityCritical]
[DllImport(JitHelpers.QCall)]
[SuppressUnmanagedCodeSecurity]
[ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)]
[FriendAccessAllowed]
- [SecurityCritical]
[ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)]
internal unsafe static void StoreOverlappedInCCW(Object windowsRuntimeBuffer, NativeOverlapped* overlapped) {
using System;
using System.Collections.Generic;
+using System.Diagnostics;
using System.Diagnostics.Contracts;
using System.Reflection;
using System.Runtime.CompilerServices;
// delegate. It then stores the corresponding token in a dictionary for easy access by RemoveEventHandler
// later. Note that the dictionary is indexed by the remove method that will be used for RemoveEventHandler
// so the removeMethod given here must match the remove method supplied there exactly.
- [SecurityCritical]
public static void AddEventHandler<T>(Func<T, EventRegistrationToken> addMethod,
Action<EventRegistrationToken> removeMethod,
T handler)
// Remove the delegate handler from the Windows Runtime style event registration by looking for
// its token, previously stored via AddEventHandler<T>
- [SecurityCritical]
public static void RemoveEventHandler<T>(Action<EventRegistrationToken> removeMethod, T handler)
{
if (removeMethod == null)
ManagedEventRegistrationImpl.RemoveEventHandler<T>(removeMethod, handler);
}
- [SecurityCritical]
public static void RemoveAllEventHandlers(Action<EventRegistrationToken> removeMethod)
{
if (removeMethod == null)
ConditionalWeakTable<object, Dictionary<MethodInfo, Dictionary<object, EventRegistrationTokenList>>> s_eventRegistrations =
new ConditionalWeakTable<object, Dictionary<MethodInfo, Dictionary<object, EventRegistrationTokenList>>>();
- [SecurityCritical]
internal static void AddEventHandler<T>(Func<T, EventRegistrationToken> addMethod,
Action<EventRegistrationToken> removeMethod,
T handler)
}
}
- [SecurityCritical]
internal static void RemoveEventHandler<T>(Action<EventRegistrationToken> removeMethod, T handler)
{
Contract.Requires(removeMethod != null);
BCLDebug.Log("INTEROP", "[WinRT_Eventing] Event unsubscribed for managed instance = " + instance + ", handler = " + handler + ", token = " + token.m_value + "\n");
}
- [SecurityCritical]
internal static void RemoveAllEventHandlers(Action<EventRegistrationToken> removeMethod)
{
Contract.Requires(removeMethod != null);
private volatile static MyReaderWriterLock s_eventCacheRWLock = new MyReaderWriterLock();
// Get InstanceKey to use in the cache
- [SecuritySafeCritical]
private static object GetInstanceKey(Action<EventRegistrationToken> removeMethod)
{
object target = removeMethod.Target;
- Contract.Assert(target == null || Marshal.IsComObject(target), "Must be null or a RCW");
+ Debug.Assert(target == null || Marshal.IsComObject(target), "Must be null or a RCW");
if (target == null)
return removeMethod.Method.DeclaringType;
return (object) Marshal.GetRawIUnknownForComObjectNoAddRef(target);
}
- [SecurityCritical]
internal static void AddEventHandler<T>(Func<T, EventRegistrationToken> addMethod,
Action<EventRegistrationToken> removeMethod,
T handler)
}
}
- [SecurityCritical]
internal static void RemoveEventHandler<T>(Action<EventRegistrationToken> removeMethod, T handler)
{
object instanceKey = GetInstanceKey(removeMethod);
// Note that inside TryGetValueWithValueEquality we assumes that any delegate
// with the same value equality would have the same hash code
object key = registrationTokens.FindEquivalentKeyUnsafe(handler, out tokens);
- Contract.Assert((key != null && tokens != null) || (key == null && tokens == null),
+ Debug.Assert((key != null && tokens != null) || (key == null && tokens == null),
"key and tokens must be both null or non-null");
if (tokens == null)
{
removeMethod(token);
}
- [SecurityCritical]
internal static void RemoveAllEventHandlers(Action<EventRegistrationToken> removeMethod)
{
object instanceKey = GetInstanceKey(removeMethod);
internal void ReleaseReaderLock()
{
EnterMyLock();
- Contract.Assert(owners > 0, "ReleasingReaderLock: releasing lock and no read lock taken");
+ Debug.Assert(owners > 0, "ReleasingReaderLock: releasing lock and no read lock taken");
--owners;
ExitAndWakeUpAppropriateWaiters();
}
internal void ReleaseWriterLock()
{
EnterMyLock();
- Contract.Assert(owners == -1, "Calling ReleaseWriterLock when no write lock is held");
+ Debug.Assert(owners == -1, "Calling ReleaseWriterLock when no write lock is held");
owners++;
ExitAndWakeUpAppropriateWaiters();
}
/// set 'waitEvent'
/// </summary>
private void LazyCreateEvent(ref EventWaitHandle waitEvent, bool makeAutoResetEvent) {
- Contract.Assert(myLock != 0, "Lock must be held");
- Contract.Assert(waitEvent == null, "Wait event must be null");
+ Debug.Assert(myLock != 0, "Lock must be held");
+ Debug.Assert(waitEvent == null, "Wait event must be null");
ExitMyLock();
EventWaitHandle newEvent;
/// </summary>
private void WaitOnEvent(EventWaitHandle waitEvent, ref uint numWaiters, int millisecondsTimeout)
{
- Contract.Assert(myLock != 0, "Lock must be held");
+ Debug.Assert(myLock != 0, "Lock must be held");
waitEvent.Reset();
numWaiters++;
/// </summary>
private void ExitAndWakeUpAppropriateWaiters()
{
- Contract.Assert(myLock != 0, "Lock must be held");
+ Debug.Assert(myLock != 0, "Lock must be held");
if (owners == 0 && numWriteWaiters > 0)
{
}
private void ExitMyLock()
{
- Contract.Assert(myLock != 0, "Exiting spin lock that is not held");
+ Debug.Assert(myLock != 0, "Exiting spin lock that is not held");
myLock = 0;
}
};
throw new AggregateException(exceptions.ToArray());
}
- [SecurityCritical]
internal static unsafe string HStringToString(IntPtr hstring)
{
Contract.Requires(Environment.IsWinRTSupported);
private static bool s_haveBlueErrorApis = true;
- [SecurityCritical]
private static bool RoOriginateLanguageException(int error, string message, IntPtr languageException)
{
if (s_haveBlueErrorApis)
return false;
}
- [SecurityCritical]
private static void RoReportUnhandledError(IRestrictedErrorInfo error)
{
if (s_haveBlueErrorApis)
/// </summary>
/// <returns>true if the error was reported, false if not (ie running on Win8)</returns>
[FriendAccessAllowed]
- [SecuritySafeCritical]
internal static bool ReportUnhandledError(Exception e)
{
// Only report to the WinRT global exception handler in modern apps
#if FEATURE_COMINTEROP_WINRT_MANAGED_ACTIVATION
// Get an IActivationFactory * for a managed type
- [SecurityCritical]
internal static IntPtr GetActivationFactoryForType(Type type)
{
ManagedActivationFactory activationFactory = GetManagedActivationFactory(type);
return Marshal.GetComInterfaceForObject(activationFactory, typeof(IActivationFactory));
}
- [SecurityCritical]
internal static ManagedActivationFactory GetManagedActivationFactory(Type type)
{
ManagedActivationFactory activationFactory = new ManagedActivationFactory(type);
// holds the IWinRTClassActivator* that is used for the process
private static IntPtr s_pClassActivator = IntPtr.Zero;
- [SecurityCritical]
internal static IntPtr GetClassActivatorForApplication(string appBase)
{
if (s_pClassActivator == IntPtr.Zero)
// factories from other apartments and make transiton to those apartments and cause
// deadlocks and create objects in incorrect apartments
//
- [SecurityCritical]
public static IActivationFactory GetActivationFactory(Type type)
{
if (type == null)
// HSTRING marshaling methods:
- [SecurityCritical]
public static IntPtr StringToHString(String s)
{
if (!Environment.IsWinRTSupported)
}
}
- [SecurityCritical]
public static String PtrToStringHString(IntPtr ptr)
{
if (!Environment.IsWinRTSupported)
return HStringToString(ptr);
}
- [SecurityCritical]
public static void FreeHString(IntPtr ptr)
{
if (!Environment.IsWinRTSupported)
public static class WindowsRuntimeMetadata
{
// Wrapper for Win8 API RoResolveNamespace with default Windows SDK path as installed .winmd files in %WINDIR%\system32\WinMetadata.
- [System.Security.SecurityCritical]
public static IEnumerable<string> ResolveNamespace(string namespaceName, IEnumerable<string> packageGraphFilePaths)
{
return ResolveNamespace(namespaceName, null, packageGraphFilePaths);
}
// Wrapper for Win8 API RoResolveNamespace.
- [System.Security.SecurityCritical]
public static IEnumerable<string> ResolveNamespace(string namespaceName, string windowsSdkFilePath, IEnumerable<string> packageGraphFilePaths)
{
if (namespaceName == null)
return retFileNames;
}
- [System.Security.SecurityCritical]
[DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
[SuppressUnmanagedCodeSecurity]
private extern static void nResolveNamespace(
namespace System.Runtime.Loader
{
- [System.Security.SecuritySafeCritical]
public abstract class AssemblyLoadContext
{
[DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
InitializeLoadContext(fRepresentsTPALoadContext);
}
- [System.Security.SecuritySafeCritical]
void InitializeLoadContext(bool fRepresentsTPALoadContext)
{
// Initialize the VM side of AssemblyLoadContext if not already done.
}
}
- [System.Security.SecuritySafeCritical]
class AppPathAssemblyLoadContext : AssemblyLoadContext
{
internal AppPathAssemblyLoadContext() : base(true)
{
}
- [System.Security.SecuritySafeCritical]
protected override Assembly Load(AssemblyName assemblyName)
{
// We were loading an assembly into TPA ALC that was not found on TPA list. As a result we are here.
}
}
- [System.Security.SecuritySafeCritical]
internal class IndividualAssemblyLoadContext : AssemblyLoadContext
{
internal IndividualAssemblyLoadContext() : base(false)
{
}
- [System.Security.SecuritySafeCritical]
protected override Assembly Load(AssemblyName assemblyName)
{
return null;
using System.Runtime.ConstrainedExecution;
using System.Security.Permissions;
using System.Runtime.Versioning;
+using System.Diagnostics;
using System.Diagnostics.Contracts;
/*
private ulong _reservedMemory; // The size of this request (from user)
private bool _mustSubtractReservation; // Did we add data to SharedStatics?
- [System.Security.SecuritySafeCritical] // auto-generated
static MemoryFailPoint()
{
GetMemorySettings(out GCSegmentSize, out TopOfMemory);
// have scenarios for this in partial trust in the future, but
// we're doing this just to restrict this in case the code below
// is somehow incorrect.
- [System.Security.SecurityCritical] // auto-generated_required
public MemoryFailPoint(int sizeInMegabytes)
{
if (sizeInMegabytes <= 0)
break;
default:
- Contract.Assert(false, "Fell through switch statement!");
+ Debug.Assert(false, "Fell through switch statement!");
break;
}
}
#endif
}
- [System.Security.SecurityCritical] // auto-generated
private static void CheckForAvailableMemory(out ulong availPageFile, out ulong totalAddressSpaceFree)
{
bool r;
// returns whether there is enough space. In all cases, we update
// our last known free address space, hopefully avoiding needing to
// probe again.
- [System.Security.SecurityCritical] // auto-generated
private static unsafe bool CheckForFreeAddressSpace(ulong size, bool shouldThrow)
{
// Start walking the address space at 0. VirtualAlloc may wrap
// of pages. If we didn't have enough address space, we still return
// a positive value < size, to help potentially avoid the overhead of
// this check if we use a MemoryFailPoint with a smaller size next.
- [System.Security.SecurityCritical] // auto-generated
private static unsafe ulong MemFreeAfterAddress(void * address, ulong size)
{
if (size >= TopOfMemory)
return largestFreeRegion;
}
- [System.Security.SecurityCritical] // auto-generated
[MethodImpl(MethodImplOptions.InternalCall)]
private static extern void GetMemorySettings(out ulong maxGCSegmentSize, out ulong topOfMemory);
- [System.Security.SecuritySafeCritical] // destructors should be safe to call
~MemoryFailPoint()
{
Dispose(false);
// future create an allocation context and release it in the Dispose
// method. While the finalizer will eventually free this block of
// memory, apps will help their performance greatly by calling Dispose.
- [System.Security.SecuritySafeCritical] // auto-generated
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
- [System.Security.SecurityCritical] // auto-generated
[ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)]
private void Dispose(bool disposing)
{
public static class ProfileOptimization
{
[DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
- [SecurityCritical]
[SuppressUnmanagedCodeSecurity]
internal static extern void InternalSetProfileRoot(string directoryPath);
[DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
- [SecurityCritical]
[SuppressUnmanagedCodeSecurity]
internal static extern void InternalStartProfile(string profile, IntPtr ptrNativeAssemblyLoadContext);
- [SecurityCritical]
public static void SetProfileRoot(string directoryPath)
{
InternalSetProfileRoot(directoryPath);
}
- [SecurityCritical]
public static void StartProfile(string profile)
{
InternalStartProfile(profile, IntPtr.Zero);
namespace System.Runtime.ConstrainedExecution
{
-#if !FEATURE_CORECLR
- [SecurityPermission(SecurityAction.InheritanceDemand, UnmanagedCode=true)]
-#endif
[System.Runtime.InteropServices.ComVisible(true)]
public abstract class CriticalFinalizerObject
{
- #if FEATURE_CORECLR
- [System.Security.SecuritySafeCritical] // auto-generated
- #endif
[ReliabilityContract(Consistency.WillNotCorruptState, Cer.MayFail)]
protected CriticalFinalizerObject()
{
**
===========================================================*/
-namespace System.Runtime.Remoting{
-
+namespace System.Runtime.Remoting
+{
using System;
- using System.Security.Permissions;
using System.Runtime.InteropServices;
- using System.Runtime.Remoting;
-#if FEATURE_REMOTING
- using System.Runtime.Remoting.Activation;
- using System.Runtime.Remoting.Lifetime;
-#endif
[ClassInterface(ClassInterfaceType.AutoDual)]
[System.Runtime.InteropServices.ComVisible(true)]
public class ObjectHandle:
-#if FEATURE_REMOTING
- MarshalByRefObject,
-#endif
IObjectHandle
{
private Object WrappedObject;
{
return WrappedObject;
}
-
- // ObjectHandle has a finite lifetime. For now the default
- // lifetime is being used, this can be changed in this method to
- // specify a custom lifetime.
-#if FEATURE_REMOTING
- [System.Security.SecurityCritical] // auto-generated_required
- public override Object InitializeLifetimeService()
- {
- BCLDebug.Trace("REMOTE", "ObjectHandle.InitializeLifetimeService");
-
- //
- // If the wrapped object has implemented InitializeLifetimeService to return null,
- // we don't want to go to the base class (which will result in a lease being
- // requested from the MarshalByRefObject, which starts up the LeaseManager,
- // which starts up the ThreadPool, adding three threads to the process.
- // We check if the wrapped object is a MarshalByRef object, and call InitializeLifetimeServices on it
- // and if it returns null, we return null. Otherwise we fall back to the old behavior.
- //
-
- MarshalByRefObject mbr = WrappedObject as MarshalByRefObject;
- if (mbr != null) {
- Object o = mbr.InitializeLifetimeService();
- if (o == null)
- return null;
- }
- ILease lease = (ILease)base.InitializeLifetimeService();
- return lease;
- }
-#endif // FEATURE_REMOTING
}
}
using System.IO;
using System.Text;
using System.Globalization;
+ using System.Diagnostics;
using System.Diagnostics.Contracts;
[System.Runtime.InteropServices.ComVisible(true)]
public static class FormatterServices {
#if FEATURE_SERIALIZATION
internal static Dictionary<MemberHolder, MemberInfo[]> m_MemberInfoTable = new Dictionary<MemberHolder, MemberInfo[]>(32);
- [System.Security.SecurityCritical]
private static bool unsafeTypeForwardersIsEnabled = false;
- [System.Security.SecurityCritical]
private static volatile bool unsafeTypeForwardersIsEnabledInitialized = false;
private static Object s_FormatterServicesSyncObject = null;
}
}
- [SecuritySafeCritical]
static FormatterServices()
{
// Static initialization touches security critical types, so we need an
FieldInfo [] typeFields;
RuntimeType parentType;
- Contract.Assert((object)type != null, "[GetAllSerializableMembers]type!=null");
+ Debug.Assert((object)type != null, "[GetAllSerializableMembers]type!=null");
if (type.IsInterface) {
return new MemberInfo[0];
// be included, properties must have both a getter and a setter. N.B.: A class
// which implements ISerializable or has a serialization surrogate may not use all of these members
// (or may have additional members).
- [System.Security.SecurityCritical] // auto-generated_required
public static MemberInfo[] GetSerializableMembers(Type type) {
return GetSerializableMembers(type, new StreamingContext(StreamingContextStates.All));
}
// Get all of the Serializable Members for a particular class. If we're not cloning, this is all
// non-transient, non-static fields. If we are cloning, include the transient fields as well since
// we know that we're going to live inside of the same context.
- [System.Security.SecurityCritical] // auto-generated_required
public static MemberInfo[] GetSerializableMembers(Type type, StreamingContext context) {
MemberInfo[] members;
static readonly Type[] advancedTypes = new Type[]{
typeof(System.DelegateSerializationHolder),
-#if FEATURE_REMOTING
- typeof(System.Runtime.Remoting.ObjRef),
- typeof(System.Runtime.Remoting.IEnvoyInfo),
- typeof(System.Runtime.Remoting.Lifetime.ISponsor),
-#endif
};
-
- public static void CheckTypeSecurity(Type t, TypeFilterLevel securityLevel) {
+
+ public static void CheckTypeSecurity(Type t, TypeFilterLevel securityLevel) {
if (securityLevel == TypeFilterLevel.Low){
for(int i=0;i<advancedTypes.Length;i++){
if (advancedTypes[i].IsAssignableFrom(t))
// will not create an unitialized string because it is non-sensical to create an empty
// instance of an immutable type.
//
- [System.Security.SecurityCritical] // auto-generated_required
public static Object GetUninitializedObject(Type type) {
if ((object)type == null) {
throw new ArgumentNullException(nameof(type));
return nativeGetUninitializedObject((RuntimeType)type);
}
- [System.Security.SecurityCritical] // auto-generated_required
public static Object GetSafeUninitializedObject(Type type) {
if ((object)type == null) {
throw new ArgumentNullException(nameof(type));
}
Contract.EndContractBlock();
-
+
if (!(type is RuntimeType)) {
throw new SerializationException(Environment.GetResourceString("Serialization_InvalidType", type.ToString()));
}
-#if FEATURE_REMOTING
- if (Object.ReferenceEquals(type, typeof(System.Runtime.Remoting.Messaging.ConstructionCall)) ||
- Object.ReferenceEquals(type, typeof(System.Runtime.Remoting.Messaging.LogicalCallContext)) ||
- Object.ReferenceEquals(type, typeof(System.Runtime.Remoting.Contexts.SynchronizationAttribute)))
- return nativeGetUninitializedObject((RuntimeType)type);
-#endif
- try {
- return nativeGetSafeUninitializedObject((RuntimeType)type);
+ try {
+ return nativeGetSafeUninitializedObject((RuntimeType)type);
}
- catch(SecurityException e) {
+ catch(SecurityException e) {
throw new SerializationException(Environment.GetResourceString("Serialization_Security", type.FullName), e);
- }
+ }
}
- [System.Security.SecurityCritical] // auto-generated
[MethodImplAttribute(MethodImplOptions.InternalCall)]
private static extern Object nativeGetSafeUninitializedObject(RuntimeType type);
- [System.Security.SecurityCritical] // auto-generated
[MethodImplAttribute(MethodImplOptions.InternalCall)]
private static extern Object nativeGetUninitializedObject(RuntimeType type);
#if FEATURE_SERIALIZATION
- [System.Security.SecurityCritical]
[MethodImplAttribute(MethodImplOptions.InternalCall)]
private static extern bool GetEnableUnsafeTypeForwarders();
- [SecuritySafeCritical]
internal static bool UnsafeTypeForwardersIsEnabled()
{
if (!unsafeTypeForwardersIsEnabledInitialized)
}
#endif
private static Binder s_binder = Type.DefaultBinder;
- [System.Security.SecurityCritical]
internal static void SerializationSetValue(MemberInfo fi, Object target, Object value)
{
Contract.Requires(fi != null);
// Fill in the members of obj with the data contained in data.
// Returns the number of members populated.
//
- [System.Security.SecurityCritical] // auto-generated_required
public static Object PopulateObjectMembers(Object obj, MemberInfo[] members, Object[] data) {
if (obj==null) {
throw new ArgumentNullException(nameof(obj));
// extract (must be FieldInfos or PropertyInfos). For each supplied member, extract the matching value and
// return it in a Object[] of the same size.
//
- [System.Security.SecurityCritical] // auto-generated_required
public static Object[] GetObjectData(Object obj, MemberInfo[] members) {
if (obj==null) {
}
if (mi.MemberType==MemberTypes.Field) {
- Contract.Assert(mi is RuntimeFieldInfo || mi is SerializationFieldInfo,
+ Debug.Assert(mi is RuntimeFieldInfo || mi is SerializationFieldInfo,
"[FormatterServices.GetObjectData]mi is RuntimeFieldInfo || mi is SerializationFieldInfo.");
RtFieldInfo rfi = mi as RtFieldInfo;
return data;
}
- [System.Security.SecurityCritical] // auto-generated_required
[System.Runtime.InteropServices.ComVisible(false)]
public static ISerializationSurrogate GetSurrogateForCyclicalReference(ISerializationSurrogate innerSurrogate)
{
**Arguments:
**Exceptions:
==============================================================================*/
- [System.Security.SecurityCritical] // auto-generated_required
public static Type GetTypeFromAssembly(Assembly assem, String name) {
if (assem==null)
throw new ArgumentNullException(nameof(assem));
this.innerSurrogate = innerSurrogate;
}
- [System.Security.SecurityCritical] // auto-generated
public void GetObjectData(Object obj, SerializationInfo info, StreamingContext context)
{
innerSurrogate.GetObjectData(obj, info, context);
}
- [System.Security.SecurityCritical] // auto-generated
public Object SetObjectData(Object obj, SerializationInfo info, StreamingContext context, ISurrogateSelector selector)
{
return innerSurrogate.SetObjectData(obj, info, context, selector);
// Interface does not need to be marked with the serializable attribute
[System.Runtime.InteropServices.ComVisible(true)]
public interface IObjectReference {
- [System.Security.SecurityCritical] // auto-generated_required
Object GetRealObject(StreamingContext context);
}
}
[System.Runtime.InteropServices.ComVisible(true)]
public interface ISerializable {
- [System.Security.SecurityCritical] // auto-generated_required
void GetObjectData(SerializationInfo info, StreamingContext context);
}
// Returns a SerializationInfo completely populated with all of the data needed to reinstantiate the
// the object at the other end of serialization.
//
- [System.Security.SecurityCritical] // auto-generated_required
void GetObjectData(Object obj, SerializationInfo info, StreamingContext context);
// Reinflate the object using all of the information in data. The information in
// members is used to find the particular field or property which needs to be set.
//
- [System.Security.SecurityCritical] // auto-generated_required
Object SetObjectData(Object obj, SerializationInfo info, StreamingContext context, ISurrogateSelector selector);
}
}
// Interface does not need to be marked with the serializable attribute
// Specifies the next ISurrogateSelector to be examined for surrogates if the current
// instance doesn't have a surrogate for the given type and assembly in the given context.
- [System.Security.SecurityCritical] // auto-generated_required
void ChainSelector(ISurrogateSelector selector);
// Returns the appropriate surrogate for the given type in the given context.
- [System.Security.SecurityCritical] // auto-generated_required
ISerializationSurrogate GetSurrogate(Type type, StreamingContext context, out ISurrogateSelector selector);
// Return the next surrogate in the chain. Returns null if no more exist.
- [System.Security.SecurityCritical] // auto-generated_required
ISurrogateSelector GetNextSelector();
}
}
//
// 3. Serialize the safe serialization object in GetObjectData, and call its CompleteSerialization method:
//
- // [SecurityCritical]
- // void ISerializable.GetObjectData(SerializationInfo info, StreamingContext context)
// {
// info.AddValue("m_safeSerializationManager", m_safeSerializationManager, typeof(SafeSerializationManager));
// m_safeSerializationManager.CompleteSerialization(this, info, context);
{
}
- [SecurityCritical]
private SafeSerializationManager(SerializationInfo info, StreamingContext context)
{
// We need to determine if we're being called to really deserialize a SafeSerializationManager,
// CompleteSerialization is called by the base ISerializable in its GetObjectData method. It is
// responsible for gathering up the serialized object state of any delegates that wish to add their
// own state to the serialized object.
- [SecurityCritical]
internal void CompleteSerialization(object serializedObject,
SerializationInfo info,
StreamingContext context)
}
}
- [SecurityCritical]
void ISerializable.GetObjectData(SerializationInfo info, StreamingContext context)
{
info.AddValue("m_serializedStates", m_serializedStates, typeof(List<IDeserializationCallback>));
// GetRealObject intercepts the deserialization process in order to allow deserializing part of the
// object's inheritance heirarchy using standard ISerializable constructors, and the remaining
// portion using the saved serialization states.
- [SecurityCritical]
object IObjectReference.GetRealObject(StreamingContext context)
{
// If we've already deserialized the real object, use that rather than deserializing it again
using System;
using System.Reflection;
using System.Globalization;
+ using System.Diagnostics;
using System.Diagnostics.Contracts;
using System.Threading;
-#if FEATURE_REMOTING
- using System.Runtime.Remoting.Metadata;
-#endif //FEATURE_REMOTING
internal sealed class SerializationFieldInfo : FieldInfo {
public override int MetadataToken { get { return m_field.MetadataToken; } }
internal SerializationFieldInfo(RuntimeFieldInfo field, String namePrefix) {
- Contract.Assert(field!=null, "[SerializationFieldInfo.ctor]field!=null");
- Contract.Assert(namePrefix!=null, "[SerializationFieldInfo.ctor]namePrefix!=null");
+ Debug.Assert(field!=null, "[SerializationFieldInfo.ctor]field!=null");
+ Debug.Assert(namePrefix!=null, "[SerializationFieldInfo.ctor]namePrefix!=null");
m_field = field;
m_serializationName = String.Concat(namePrefix, FakeNameSeparatorString, m_field.Name);
return m_field.GetValue(obj);
}
- [System.Security.SecurityCritical]
internal Object InternalGetValue(Object obj) {
RtFieldInfo field = m_field as RtFieldInfo;
if (field != null)
m_field.SetValue(obj, value, invokeAttr, binder, culture);
}
- [System.Security.SecurityCritical]
internal void InternalSetValue(Object obj, Object value, BindingFlags invokeAttr, Binder binder, CultureInfo culture) {
RtFieldInfo field = m_field as RtFieldInfo;
if (field != null)
return m_field.Attributes;
}
}
-
-#if FEATURE_REMOTING
- #region Legacy Remoting Cache
- private RemotingFieldCachedData m_cachedData;
-
- internal RemotingFieldCachedData RemotingCache
- {
- get
- {
- // This grabs an internal copy of m_cachedData and uses
- // that instead of looking at m_cachedData directly because
- // the cache may get cleared asynchronously. This prevents
- // us from having to take a lock.
- RemotingFieldCachedData cache = m_cachedData;
- if (cache == null)
- {
- cache = new RemotingFieldCachedData(this);
- RemotingFieldCachedData ret = Interlocked.CompareExchange(ref m_cachedData, cache, null);
- if (ret != null)
- cache = ret;
- }
- return cache;
- }
- }
- #endregion
-#endif //FEATURE_REMOTING
}
}
using System.Collections.Generic;
using System.Reflection;
using System.Runtime.Remoting;
-#if FEATURE_REMOTING
- using System.Runtime.Remoting.Proxies;
-#endif
using System.Globalization;
+ using System.Diagnostics;
using System.Diagnostics.Contracts;
using System.Security;
-#if FEATURE_CORECLR
using System.Runtime.CompilerServices;
-#endif
[System.Runtime.InteropServices.ComVisible(true)]
public sealed class SerializationInfo
{
return m_assemName;
}
- [SecuritySafeCritical]
set
{
if (null == value)
}
}
- [SecuritySafeCritical]
public void SetType(Type type)
{
if ((object)type == null)
}
}
- [SecuritySafeCritical]
internal static void DemandForUnsafeAssemblyNameAssignments(string originalAssemblyName, string newAssemblyName)
{
-#if !FEATURE_CORECLR
- if (!IsAssemblyNameAssignmentSafe(originalAssemblyName, newAssemblyName))
- {
- CodeAccessPermission.Demand(PermissionType.SecuritySerialization);
- }
-#endif
}
internal static bool IsAssemblyNameAssignmentSafe(string originalAssemblyName, string newAssemblyName)
private void ExpandArrays()
{
int newSize;
- Contract.Assert(m_members.Length == m_currMember, "[SerializationInfo.ExpandArrays]m_members.Length == m_currMember");
+ Debug.Assert(m_members.Length == m_currMember, "[SerializationInfo.ExpandArrays]m_members.Length == m_currMember");
newSize = (m_currMember * 2);
**Exceptions: None. All error checking is done with asserts. Although public in coreclr,
** it's not exposed in a contract and is only meant to be used by corefx.
==============================================================================*/
-#if FEATURE_CORECLR
// This should not be used by clients: exposing out this functionality would allow children
// to overwrite their parent's values. It is public in order to give corefx access to it for
// its ObjectManager implementation, but it should not be exposed out of a contract.
- public
-#else
- internal
-#endif
- void UpdateValue(String name, Object value, Type type)
+ public void UpdateValue(String name, Object value, Type type)
{
- Contract.Assert(null != name, "[SerializationInfo.UpdateValue]name!=null");
- Contract.Assert(null != value, "[SerializationInfo.UpdateValue]value!=null");
- Contract.Assert(null != (object)type, "[SerializationInfo.UpdateValue]type!=null");
+ Debug.Assert(null != name, "[SerializationInfo.UpdateValue]name!=null");
+ Debug.Assert(null != value, "[SerializationInfo.UpdateValue]value!=null");
+ Debug.Assert(null != (object)type, "[SerializationInfo.UpdateValue]type!=null");
int index = FindElement(name);
if (index < 0)
throw new SerializationException(Environment.GetResourceString("Serialization_NotFound", name));
}
- Contract.Assert(index < m_data.Length, "[SerializationInfo.GetElement]index<m_data.Length");
- Contract.Assert(index < m_types.Length, "[SerializationInfo.GetElement]index<m_types.Length");
+ Debug.Assert(index < m_data.Length, "[SerializationInfo.GetElement]index<m_data.Length");
+ Debug.Assert(index < m_types.Length, "[SerializationInfo.GetElement]index<m_types.Length");
foundType = m_types[index];
- Contract.Assert((object)foundType != null, "[SerializationInfo.GetElement]foundType!=null");
+ Debug.Assert((object)foundType != null, "[SerializationInfo.GetElement]foundType!=null");
return m_data[index];
}
return null;
}
- Contract.Assert(index < m_data.Length, "[SerializationInfo.GetElement]index<m_data.Length");
- Contract.Assert(index < m_types.Length, "[SerializationInfo.GetElement]index<m_types.Length");
+ Debug.Assert(index < m_data.Length, "[SerializationInfo.GetElement]index<m_data.Length");
+ Debug.Assert(index < m_types.Length, "[SerializationInfo.GetElement]index<m_types.Length");
foundType = m_types[index];
- Contract.Assert((object)foundType != null, "[SerializationInfo.GetElement]foundType!=null");
+ Debug.Assert((object)foundType != null, "[SerializationInfo.GetElement]foundType!=null");
return m_data[index];
}
// form requested.
//
- [System.Security.SecuritySafeCritical] // auto-generated
public Object GetValue(String name, Type type)
{
Object value;
value = GetElement(name, out foundType);
-#if FEATURE_REMOTING
- if (RemotingServices.IsTransparentProxy(value))
+
+ if (Object.ReferenceEquals(foundType, type) || type.IsAssignableFrom(foundType) || value == null)
{
- RealProxy proxy = RemotingServices.GetRealProxy(value);
- if (RemotingServices.ProxyCheckCast(proxy, rt))
- return value;
+ return value;
}
- else
-#endif
- if (Object.ReferenceEquals(foundType, type) || type.IsAssignableFrom(foundType) || value == null)
- {
- return value;
- }
- Contract.Assert(m_converter != null, "[SerializationInfo.GetValue]m_converter!=null");
+ Debug.Assert(m_converter != null, "[SerializationInfo.GetValue]m_converter!=null");
return m_converter.Convert(value, type);
}
- [System.Security.SecuritySafeCritical] // auto-generated
[System.Runtime.InteropServices.ComVisible(true)]
internal Object GetValueNoThrow(String name, Type type)
{
Type foundType;
Object value;
- Contract.Assert((object)type != null, "[SerializationInfo.GetValue]type ==null");
- Contract.Assert(type is RuntimeType, "[SerializationInfo.GetValue]type is not a runtime type");
+ Debug.Assert((object)type != null, "[SerializationInfo.GetValue]type ==null");
+ Debug.Assert(type is RuntimeType, "[SerializationInfo.GetValue]type is not a runtime type");
value = GetElementNoThrow(name, out foundType);
if (value == null)
return null;
-#if FEATURE_REMOTING
- if (RemotingServices.IsTransparentProxy(value))
+
+ if (Object.ReferenceEquals(foundType, type) || type.IsAssignableFrom(foundType) || value == null)
{
- RealProxy proxy = RemotingServices.GetRealProxy(value);
- if (RemotingServices.ProxyCheckCast(proxy, (RuntimeType)type))
- return value;
+ return value;
}
- else
-#endif
- if (Object.ReferenceEquals(foundType, type) || type.IsAssignableFrom(foundType) || value == null)
- {
- return value;
- }
- Contract.Assert(m_converter != null, "[SerializationInfo.GetValue]m_converter!=null");
+ Debug.Assert(m_converter != null, "[SerializationInfo.GetValue]m_converter!=null");
return m_converter.Convert(value, type);
}
============================================================*/
namespace System.Runtime.Serialization {
using System;
+ using System.Diagnostics;
using System.Collections;
using System.Diagnostics.Contracts;
bool m_current;
internal SerializationInfoEnumerator(String[] members, Object[] info, Type[] types, int numItems) {
- Contract.Assert(members!=null, "[SerializationInfoEnumerator.ctor]members!=null");
- Contract.Assert(info!=null, "[SerializationInfoEnumerator.ctor]info!=null");
- Contract.Assert(types!=null, "[SerializationInfoEnumerator.ctor]types!=null");
- Contract.Assert(numItems>=0, "[SerializationInfoEnumerator.ctor]numItems>=0");
- Contract.Assert(members.Length>=numItems, "[SerializationInfoEnumerator.ctor]members.Length>=numItems");
- Contract.Assert(info.Length>=numItems, "[SerializationInfoEnumerator.ctor]info.Length>=numItems");
- Contract.Assert(types.Length>=numItems, "[SerializationInfoEnumerator.ctor]types.Length>=numItems");
+ Debug.Assert(members!=null, "[SerializationInfoEnumerator.ctor]members!=null");
+ Debug.Assert(info!=null, "[SerializationInfoEnumerator.ctor]info!=null");
+ Debug.Assert(types!=null, "[SerializationInfoEnumerator.ctor]types!=null");
+ Debug.Assert(numItems>=0, "[SerializationInfoEnumerator.ctor]numItems>=0");
+ Debug.Assert(members.Length>=numItems, "[SerializationInfoEnumerator.ctor]members.Length>=numItems");
+ Debug.Assert(info.Length>=numItems, "[SerializationInfoEnumerator.ctor]info.Length>=numItems");
+ Debug.Assert(types.Length>=numItems, "[SerializationInfoEnumerator.ctor]types.Length>=numItems");
m_members = members;
m_data = info;
*
* These apis are for internal use only for FX assmeblies. It has not been decided if they can be used by OOB components due to EULA restrictions
*/
- [System.Security.SecurityCritical]
public static bool IsEnabled(string compatibilitySwitchName)
{
return IsEnabledInternalCall(compatibilitySwitchName, true);
}
- [System.Security.SecurityCritical]
public static string GetValue(string compatibilitySwitchName)
{
// This is used by AppContext.TryGetSwitch to check switch overrides in the Windows Quirk DB
return GetValueInternalCall(compatibilitySwitchName, true);
}
- [System.Security.SecurityCritical]
internal static bool IsEnabledInternal(string compatibilitySwitchName)
{
return IsEnabledInternalCall(compatibilitySwitchName, false);
}
- [System.Security.SecurityCritical]
internal static string GetValueInternal(string compatibilitySwitchName)
{
return GetValueInternalCall(compatibilitySwitchName, false);
}
- [System.Security.SecurityCritical]
[MethodImpl(MethodImplOptions.InternalCall)]
internal static extern string GetAppContextOverridesInternalCall();
return type;
}
- [System.Security.SecurityCritical] // auto-generated
[MethodImplAttribute(MethodImplOptions.InternalCall)]
internal extern static bool IsInstanceOfType(RuntimeType type, Object o);
- [System.Security.SecuritySafeCritical] // auto-generated
internal unsafe static Type GetTypeHelper(Type typeStart, Type[] genericArgs, IntPtr pModifiers, int cModifiers)
{
Type type = typeStart;
public IntPtr Value
{
- [SecurityCritical]
get
{
return m_type != null ? m_type.m_handle : IntPtr.Zero;
}
}
- [System.Security.SecuritySafeCritical] // auto-generated
[MethodImpl(MethodImplOptions.InternalCall)]
internal static extern IntPtr GetValueInternal(RuntimeTypeHandle handle);
return m_type == null;
}
- [System.Security.SecuritySafeCritical] // auto-generated
internal static bool IsPrimitive(RuntimeType type)
{
CorElementType corElemType = GetCorElementType(type);
corElemType == CorElementType.U;
}
- [System.Security.SecuritySafeCritical] // auto-generated
internal static bool IsByRef(RuntimeType type)
{
CorElementType corElemType = GetCorElementType(type);
return (corElemType == CorElementType.ByRef);
}
- [System.Security.SecuritySafeCritical] // auto-generated
internal static bool IsPointer(RuntimeType type)
{
CorElementType corElemType = GetCorElementType(type);
return (corElemType == CorElementType.Ptr);
}
- [System.Security.SecuritySafeCritical] // auto-generated
internal static bool IsArray(RuntimeType type)
{
CorElementType corElemType = GetCorElementType(type);
return (corElemType == CorElementType.Array || corElemType == CorElementType.SzArray);
}
- [System.Security.SecuritySafeCritical] // auto-generated
internal static bool IsSzArray(RuntimeType type)
{
CorElementType corElemType = GetCorElementType(type);
return (corElemType == CorElementType.SzArray);
}
- [System.Security.SecuritySafeCritical] // auto-generated
internal static bool HasElementType(RuntimeType type)
{
CorElementType corElemType = GetCorElementType(type);
|| (corElemType == CorElementType.ByRef)); // IsByRef
}
- [SecurityCritical]
internal static IntPtr[] CopyRuntimeTypeHandles(RuntimeTypeHandle[] inHandles, out int length)
{
if (inHandles == null || inHandles.Length == 0)
return outHandles;
}
- [SecurityCritical]
internal static IntPtr[] CopyRuntimeTypeHandles(Type[] inHandles, out int length)
{
if (inHandles == null || inHandles.Length == 0)
return outHandles;
}
- [System.Security.SecurityCritical] // auto-generated
[MethodImplAttribute(MethodImplOptions.InternalCall)]
internal static extern Object CreateInstance(RuntimeType type, bool publicOnly, bool noCheck, ref bool canBeCached, ref RuntimeMethodHandleInternal ctor, ref bool bNeedSecurityCheck);
- [System.Security.SecurityCritical] // auto-generated
[MethodImplAttribute(MethodImplOptions.InternalCall)]
internal static extern Object CreateCaInstance(RuntimeType type, IRuntimeMethodInfo ctor);
- [System.Security.SecurityCritical] // auto-generated
[MethodImplAttribute(MethodImplOptions.InternalCall)]
internal static extern Object Allocate(RuntimeType type);
- [System.Security.SecurityCritical] // auto-generated
[MethodImplAttribute(MethodImplOptions.InternalCall)]
internal static extern Object CreateInstanceForAnotherGenericParameter(RuntimeType type, RuntimeType genericParameter);
return m_type;
}
- [System.Security.SecurityCritical] // auto-generated
[MethodImplAttribute(MethodImplOptions.InternalCall)]
internal extern static CorElementType GetCorElementType(RuntimeType type);
- [System.Security.SecuritySafeCritical] // auto-generated
[MethodImplAttribute(MethodImplOptions.InternalCall)]
internal extern static RuntimeAssembly GetAssembly(RuntimeType type);
- [System.Security.SecuritySafeCritical] // auto-generated
[MethodImplAttribute(MethodImplOptions.InternalCall)]
[ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)]
internal extern static RuntimeModule GetModule(RuntimeType type);
return new ModuleHandle(RuntimeTypeHandle.GetModule(m_type));
}
- [System.Security.SecuritySafeCritical]
[MethodImplAttribute(MethodImplOptions.InternalCall)]
internal extern static RuntimeType GetBaseType(RuntimeType type);
- [System.Security.SecurityCritical] // auto-generated
[MethodImplAttribute(MethodImplOptions.InternalCall)]
internal extern static TypeAttributes GetAttributes(RuntimeType type);
- [System.Security.SecuritySafeCritical] // auto-generated
[MethodImplAttribute(MethodImplOptions.InternalCall)]
internal extern static RuntimeType GetElementType(RuntimeType type);
- [System.Security.SecurityCritical] // auto-generated
[MethodImplAttribute(MethodImplOptions.InternalCall)]
internal extern static bool CompareCanonicalHandles(RuntimeType left, RuntimeType right);
- [System.Security.SecurityCritical] // auto-generated
[MethodImplAttribute(MethodImplOptions.InternalCall)]
internal extern static int GetArrayRank(RuntimeType type);
- [System.Security.SecurityCritical] // auto-generated
[MethodImplAttribute(MethodImplOptions.InternalCall)]
internal extern static int GetToken(RuntimeType type);
- [System.Security.SecuritySafeCritical] // auto-generated
[MethodImplAttribute(MethodImplOptions.InternalCall)]
internal extern static RuntimeMethodHandleInternal GetMethodAt(RuntimeType type, int slot);
bool _firstCall;
RuntimeMethodHandleInternal _handle;
- [System.Security.SecuritySafeCritical] // auto-generated
internal IntroducedMethodEnumerator(RuntimeType type)
{
_handle = RuntimeTypeHandle.GetFirstIntroducedMethod(type);
_firstCall = true;
}
- [System.Security.SecuritySafeCritical] // auto-generated
public bool MoveNext()
{
if (_firstCall)
return new IntroducedMethodEnumerator(type);
}
- [System.Security.SecurityCritical] // auto-generated
[MethodImplAttribute(MethodImplOptions.InternalCall)]
private static extern RuntimeMethodHandleInternal GetFirstIntroducedMethod(RuntimeType type);
- [System.Security.SecurityCritical] // auto-generated
[MethodImplAttribute(MethodImplOptions.InternalCall)]
private static extern void GetNextIntroducedMethod(ref RuntimeMethodHandleInternal method);
- [System.Security.SecurityCritical] // auto-generated
[MethodImplAttribute(MethodImplOptions.InternalCall)]
internal extern static bool GetFields(RuntimeType type, IntPtr* result, int* count);
- [System.Security.SecurityCritical] // auto-generated
[MethodImplAttribute(MethodImplOptions.InternalCall)]
internal extern static Type[] GetInterfaces(RuntimeType type);
- [System.Security.SecurityCritical] // auto-generated
[DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
[SuppressUnmanagedCodeSecurity]
private extern static void GetConstraints(RuntimeTypeHandle handle, ObjectHandleOnStack types);
- [System.Security.SecuritySafeCritical] // auto-generated
internal Type[] GetConstraints()
{
Type[] types = null;
return types;
}
- [System.Security.SecurityCritical] // auto-generated
[DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
[SuppressUnmanagedCodeSecurity]
private extern static IntPtr GetGCHandle(RuntimeTypeHandle handle, GCHandleType type);
- [System.Security.SecurityCritical] // auto-generated
internal IntPtr GetGCHandle(GCHandleType type)
{
return GetGCHandle(GetNativeHandle(), type);
}
- [System.Security.SecurityCritical] // auto-generated
[MethodImplAttribute(MethodImplOptions.InternalCall)]
internal extern static int GetNumVirtuals(RuntimeType type);
- [System.Security.SecurityCritical] // auto-generated
[DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
[SuppressUnmanagedCodeSecurity]
private extern static void VerifyInterfaceIsImplemented(RuntimeTypeHandle handle, RuntimeTypeHandle interfaceHandle);
- [System.Security.SecuritySafeCritical] // auto-generated
internal void VerifyInterfaceIsImplemented(RuntimeTypeHandle interfaceHandle)
{
VerifyInterfaceIsImplemented(GetNativeHandle(), interfaceHandle.GetNativeHandle());
}
- [System.Security.SecurityCritical] // auto-generated
[DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
[SuppressUnmanagedCodeSecurity]
private extern static int GetInterfaceMethodImplementationSlot(RuntimeTypeHandle handle, RuntimeTypeHandle interfaceHandle, RuntimeMethodHandleInternal interfaceMethodHandle);
- [System.Security.SecuritySafeCritical] // auto-generated
internal int GetInterfaceMethodImplementationSlot(RuntimeTypeHandle interfaceHandle, RuntimeMethodHandleInternal interfaceMethodHandle)
{
return GetInterfaceMethodImplementationSlot(GetNativeHandle(), interfaceHandle.GetNativeHandle(), interfaceMethodHandle);
}
- [System.Security.SecurityCritical] // auto-generated
[MethodImplAttribute(MethodImplOptions.InternalCall)]
internal extern static bool IsComObject(RuntimeType type, bool isGenericCOM);
- [System.Security.SecurityCritical] // auto-generated
[MethodImplAttribute(MethodImplOptions.InternalCall)]
internal extern static bool IsContextful(RuntimeType type);
- [System.Security.SecurityCritical] // auto-generated
[MethodImplAttribute(MethodImplOptions.InternalCall)]
internal extern static bool IsInterface(RuntimeType type);
- [System.Security.SecurityCritical] // auto-generated
[DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
[SuppressUnmanagedCodeSecurity]
[return: MarshalAs(UnmanagedType.Bool)]
private extern static bool _IsVisible(RuntimeTypeHandle typeHandle);
- [System.Security.SecuritySafeCritical] // auto-generated
internal static bool IsVisible(RuntimeType type)
{
return _IsVisible(new RuntimeTypeHandle(type));
}
- [System.Security.SecurityCritical] // auto-generated
[DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
[SuppressUnmanagedCodeSecurity]
[return: MarshalAs(UnmanagedType.Bool)]
private static extern bool IsSecurityCritical(RuntimeTypeHandle typeHandle);
- [System.Security.SecuritySafeCritical] // auto-generated
internal bool IsSecurityCritical()
{
return IsSecurityCritical(GetNativeHandle());
}
- [System.Security.SecurityCritical] // auto-generated
[DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
[SuppressUnmanagedCodeSecurity]
[return: MarshalAs(UnmanagedType.Bool)]
private static extern bool IsSecuritySafeCritical(RuntimeTypeHandle typeHandle);
- [System.Security.SecuritySafeCritical] // auto-generated
internal bool IsSecuritySafeCritical()
{
return IsSecuritySafeCritical(GetNativeHandle());
}
- [System.Security.SecurityCritical] // auto-generated
[DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
[SuppressUnmanagedCodeSecurity]
[return: MarshalAs(UnmanagedType.Bool)]
private static extern bool IsSecurityTransparent(RuntimeTypeHandle typeHandle);
- [System.Security.SecuritySafeCritical] // auto-generated
internal bool IsSecurityTransparent()
{
return IsSecurityTransparent(GetNativeHandle());
}
- [System.Security.SecurityCritical] // auto-generated
[MethodImplAttribute(MethodImplOptions.InternalCall)]
internal extern static bool HasProxyAttribute(RuntimeType type);
- [System.Security.SecuritySafeCritical]
[MethodImplAttribute(MethodImplOptions.InternalCall)]
internal extern static bool IsValueType(RuntimeType type);
- [System.Security.SecurityCritical] // auto-generated
[DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
[SuppressUnmanagedCodeSecurity]
private extern static void ConstructName(RuntimeTypeHandle handle, TypeNameFormatFlags formatFlags, StringHandleOnStack retString);
- [System.Security.SecuritySafeCritical] // auto-generated
internal string ConstructName(TypeNameFormatFlags formatFlags)
{
string name = null;
return name;
}
- [System.Security.SecurityCritical] // auto-generated
[MethodImplAttribute(MethodImplOptions.InternalCall)]
private extern static void* _GetUtf8Name(RuntimeType type);
- [System.Security.SecuritySafeCritical] // auto-generated
internal static Utf8String GetUtf8Name(RuntimeType type)
{
return new Utf8String(_GetUtf8Name(type));
}
- [System.Security.SecuritySafeCritical] // auto-generated
[MethodImplAttribute(MethodImplOptions.InternalCall)]
internal extern static bool CanCastTo(RuntimeType type, RuntimeType target);
- [System.Security.SecurityCritical] // auto-generated
[MethodImplAttribute(MethodImplOptions.InternalCall)]
internal extern static RuntimeType GetDeclaringType(RuntimeType type);
- [System.Security.SecuritySafeCritical] // auto-generated
[MethodImplAttribute(MethodImplOptions.InternalCall)]
internal extern static IRuntimeMethodInfo GetDeclaringMethod(RuntimeType type);
- [System.Security.SecurityCritical] // auto-generated
[DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
[SuppressUnmanagedCodeSecurity]
private extern static void GetDefaultConstructor(RuntimeTypeHandle handle, ObjectHandleOnStack method);
- [System.Security.SecuritySafeCritical] // auto-generated
internal IRuntimeMethodInfo GetDefaultConstructor()
{
IRuntimeMethodInfo ctor = null;
return ctor;
}
- [System.Security.SecurityCritical] // auto-generated
[DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
[SuppressUnmanagedCodeSecurity]
private extern static void GetTypeByName(string name, bool throwOnError, bool ignoreCase, bool reflectionOnly, StackCrawlMarkHandle stackMark,
return GetTypeByName(name, throwOnError, ignoreCase, reflectionOnly, ref stackMark, IntPtr.Zero, loadTypeFromPartialName);
}
- [System.Security.SecuritySafeCritical] // auto-generated
internal static RuntimeType GetTypeByName(string name, bool throwOnError, bool ignoreCase, bool reflectionOnly, ref StackCrawlMark stackMark,
IntPtr pPrivHostBinder,
bool loadTypeFromPartialName)
return GetTypeByName(name, false, false, false, ref stackMark, false);
}
- [System.Security.SecurityCritical] // auto-generated
[DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
[SuppressUnmanagedCodeSecurity]
private extern static void GetTypeByNameUsingCARules(string name, RuntimeModule scope, ObjectHandleOnStack type);
- [System.Security.SecuritySafeCritical] // auto-generated
internal static RuntimeType GetTypeByNameUsingCARules(string name, RuntimeModule scope)
{
if (name == null || name.Length == 0)
return type;
}
- [System.Security.SecurityCritical] // auto-generated
[DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
[SuppressUnmanagedCodeSecurity]
internal extern static void GetInstantiation(RuntimeTypeHandle type, ObjectHandleOnStack types, bool fAsRuntimeTypeArray);
- [System.Security.SecuritySafeCritical] // auto-generated
internal RuntimeType[] GetInstantiationInternal()
{
RuntimeType[] types = null;
return types;
}
- [System.Security.SecuritySafeCritical] // auto-generated
internal Type[] GetInstantiationPublic()
{
Type[] types = null;
return types;
}
- [System.Security.SecurityCritical] // auto-generated
[DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
[SuppressUnmanagedCodeSecurity]
private extern static void Instantiate(RuntimeTypeHandle handle, IntPtr* pInst, int numGenericArgs, ObjectHandleOnStack type);
- [System.Security.SecurityCritical] // auto-generated
internal RuntimeType Instantiate(Type[] inst)
{
// defensive copy to be sure array is not mutated from the outside during processing
}
}
- [System.Security.SecurityCritical] // auto-generated
[DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
[SuppressUnmanagedCodeSecurity]
private extern static void MakeArray(RuntimeTypeHandle handle, int rank, ObjectHandleOnStack type);
- [System.Security.SecuritySafeCritical] // auto-generated
internal RuntimeType MakeArray(int rank)
{
RuntimeType type = null;
return type;
}
- [System.Security.SecurityCritical] // auto-generated
[DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
[SuppressUnmanagedCodeSecurity]
private extern static void MakeSZArray(RuntimeTypeHandle handle, ObjectHandleOnStack type);
- [System.Security.SecuritySafeCritical] // auto-generated
internal RuntimeType MakeSZArray()
{
RuntimeType type = null;
return type;
}
- [System.Security.SecurityCritical] // auto-generated
[DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
[SuppressUnmanagedCodeSecurity]
private extern static void MakeByRef(RuntimeTypeHandle handle, ObjectHandleOnStack type);
- [System.Security.SecuritySafeCritical] // auto-generated
internal RuntimeType MakeByRef()
{
RuntimeType type = null;
return type;
}
- [System.Security.SecurityCritical] // auto-generated
[DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
[SuppressUnmanagedCodeSecurity]
private extern static void MakePointer(RuntimeTypeHandle handle, ObjectHandleOnStack type);
- [System.Security.SecurityCritical] // auto-generated
internal RuntimeType MakePointer()
{
RuntimeType type = null;
return type;
}
- [System.Security.SecurityCritical] // auto-generated
[DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
[SuppressUnmanagedCodeSecurity]
internal extern static bool IsCollectible(RuntimeTypeHandle handle);
-#if FEATURE_CORECLR
- [System.Security.SecuritySafeCritical] // auto-generated
-#endif
[MethodImplAttribute(MethodImplOptions.InternalCall)]
internal extern static bool HasInstantiation(RuntimeType type);
return HasInstantiation(GetTypeChecked());
}
- [System.Security.SecurityCritical] // auto-generated
[DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
[SuppressUnmanagedCodeSecurity]
private extern static void GetGenericTypeDefinition(RuntimeTypeHandle type, ObjectHandleOnStack retType);
- [System.Security.SecuritySafeCritical] // auto-generated
internal static RuntimeType GetGenericTypeDefinition(RuntimeType type)
{
RuntimeType retType = type;
return retType;
}
- [System.Security.SecuritySafeCritical] // auto-generated
[MethodImplAttribute(MethodImplOptions.InternalCall)]
internal extern static bool IsGenericTypeDefinition(RuntimeType type);
- [System.Security.SecuritySafeCritical] // auto-generated
[MethodImplAttribute(MethodImplOptions.InternalCall)]
internal extern static bool IsGenericVariable(RuntimeType type);
return IsGenericVariable(GetTypeChecked());
}
- [System.Security.SecurityCritical] // auto-generated
[MethodImplAttribute(MethodImplOptions.InternalCall)]
private extern static int GetGenericVariableIndex(RuntimeType type);
- [System.Security.SecuritySafeCritical] // auto-generated
internal int GetGenericVariableIndex()
{
RuntimeType type = GetTypeChecked();
return GetGenericVariableIndex(type);
}
- [System.Security.SecurityCritical] // auto-generated
[MethodImplAttribute(MethodImplOptions.InternalCall)]
internal extern static bool ContainsGenericVariables(RuntimeType handle);
- [System.Security.SecuritySafeCritical] // auto-generated
internal bool ContainsGenericVariables()
{
return ContainsGenericVariables(GetTypeChecked());
}
- [System.Security.SecurityCritical] // auto-generated
[MethodImplAttribute(MethodImplOptions.InternalCall)]
private extern static bool SatisfiesConstraints(RuntimeType paramType, IntPtr *pTypeContext, int typeContextLength, IntPtr *pMethodContext, int methodContextLength, RuntimeType toType);
- [System.Security.SecurityCritical]
internal static bool SatisfiesConstraints(RuntimeType paramType, RuntimeType[] typeContext, RuntimeType[] methodContext, RuntimeType toType)
{
int typeContextLength;
}
}
- [System.Security.SecurityCritical] // auto-generated
[MethodImplAttribute(MethodImplOptions.InternalCall)]
private extern static IntPtr _GetMetadataImport(RuntimeType type);
- [System.Security.SecurityCritical] // auto-generated
internal static MetadataImport GetMetadataImport(RuntimeType type)
{
return new MetadataImport(_GetMetadataImport(type), type);
}
- [System.Security.SecurityCritical] // auto-generated
private RuntimeTypeHandle(SerializationInfo info, StreamingContext context)
{
if(info == null)
throw new SerializationException(Environment.GetResourceString("Serialization_InsufficientState"));
}
- [System.Security.SecurityCritical]
public void GetObjectData(SerializationInfo info, StreamingContext context)
{
if(info == null)
info.AddValue("TypeObj", m_type, typeof(RuntimeType));
}
-
-#if !FEATURE_CORECLR
- [System.Security.SecuritySafeCritical]
- [MethodImpl(MethodImplOptions.InternalCall)]
- internal static extern bool IsEquivalentTo(RuntimeType rtType1, RuntimeType rtType2);
-
- [System.Security.SecuritySafeCritical]
- [MethodImpl(MethodImplOptions.InternalCall)]
- internal static extern bool IsEquivalentType(RuntimeType type);
-#endif // FEATURE_CORECLR
}
// This type is used to remove the expense of having a managed reference object that is dynamically
internal IntPtr Value
{
- [SecurityCritical]
get
{
return m_handle;
}
}
- [SecurityCritical]
internal RuntimeMethodHandleInternal(IntPtr value)
{
m_handle = value;
m_value = methodHandleValue;
}
- [SecurityCritical]
public RuntimeMethodInfoStub(IntPtr methodHandleValue, object keepalive)
{
m_keepalive = keepalive;
object m_e;
object m_f;
object m_g;
-#if FEATURE_REMOTING
- object m_h;
-#endif
#pragma warning restore 169
+
public RuntimeMethodHandleInternal m_value;
RuntimeMethodHandleInternal IRuntimeMethodInfo.Value
}
// Used by EE
- [SecurityCritical]
private static IntPtr GetValueInternal(RuntimeMethodHandle rmh)
{
return rmh.Value;
}
// ISerializable interface
- [System.Security.SecurityCritical] // auto-generated
private RuntimeMethodHandle(SerializationInfo info, StreamingContext context)
{
if(info == null)
throw new SerializationException(Environment.GetResourceString("Serialization_InsufficientState"));
}
- [System.Security.SecurityCritical]
public void GetObjectData(SerializationInfo info, StreamingContext context)
{
if (info == null)
public IntPtr Value
{
- [SecurityCritical]
get
{
return m_value != null ? m_value.Value.Value : IntPtr.Zero;
}
}
- [SecuritySafeCritical]
public override int GetHashCode()
{
return ValueType.GetHashCodeOfPtr(Value);
}
[ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)]
- [SecuritySafeCritical]
public override bool Equals(object obj)
{
if (!(obj is RuntimeMethodHandle))
}
[ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)]
- [SecuritySafeCritical]
public bool Equals(RuntimeMethodHandle handle)
{
return handle.Value == Value;
return m_value == null;
}
- [System.Security.SecurityCritical] // auto-generated
[DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
[SuppressUnmanagedCodeSecurity]
internal extern static IntPtr GetFunctionPointer(RuntimeMethodHandleInternal handle);
- [System.Security.SecurityCritical] // auto-generated
public IntPtr GetFunctionPointer()
{
IntPtr ptr = GetFunctionPointer(EnsureNonNullMethodInfo(m_value).Value);
return ptr;
}
- [System.Security.SecurityCritical] // auto-generated
[MethodImplAttribute(MethodImplOptions.InternalCall)]
internal unsafe extern static void CheckLinktimeDemands(IRuntimeMethodInfo method, RuntimeModule module, bool isDecoratedTargetSecurityTransparent);
- [System.Security.SecurityCritical] // auto-generated
[DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
[SuppressUnmanagedCodeSecurity]
internal extern static bool IsCAVisibleFromDecoratedType(
RuntimeTypeHandle sourceTypeHandle,
RuntimeModule sourceModule);
- [System.Security.SecurityCritical] // auto-generated
[MethodImplAttribute(MethodImplOptions.InternalCall)]
private static extern IRuntimeMethodInfo _GetCurrentMethod(ref StackCrawlMark stackMark);
- [System.Security.SecuritySafeCritical] // auto-generated
internal static IRuntimeMethodInfo GetCurrentMethod(ref StackCrawlMark stackMark)
{
return _GetCurrentMethod(ref stackMark);
}
[Pure]
- [System.Security.SecurityCritical] // auto-generated
[MethodImplAttribute(MethodImplOptions.InternalCall)]
internal static extern MethodAttributes GetAttributes(RuntimeMethodHandleInternal method);
- [System.Security.SecurityCritical] // auto-generated
internal static MethodAttributes GetAttributes(IRuntimeMethodInfo method)
{
MethodAttributes retVal = RuntimeMethodHandle.GetAttributes(method.Value);
return retVal;
}
- [System.Security.SecuritySafeCritical] // auto-generated
[MethodImplAttribute(MethodImplOptions.InternalCall)]
internal static extern MethodImplAttributes GetImplAttributes(IRuntimeMethodInfo method);
- [System.Security.SecurityCritical] // auto-generated
[DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
[SuppressUnmanagedCodeSecurity]
private extern static void ConstructInstantiation(IRuntimeMethodInfo method, TypeNameFormatFlags format, StringHandleOnStack retString);
- [System.Security.SecuritySafeCritical] // auto-generated
internal static string ConstructInstantiation(IRuntimeMethodInfo method, TypeNameFormatFlags format)
{
string name = null;
return name;
}
- [System.Security.SecurityCritical] // auto-generated
[MethodImplAttribute(MethodImplOptions.InternalCall)]
internal extern static RuntimeType GetDeclaringType(RuntimeMethodHandleInternal method);
- [System.Security.SecuritySafeCritical] // auto-generated
internal static RuntimeType GetDeclaringType(IRuntimeMethodInfo method)
{
RuntimeType type = RuntimeMethodHandle.GetDeclaringType(method.Value);
return type;
}
- [System.Security.SecurityCritical] // auto-generated
[MethodImplAttribute(MethodImplOptions.InternalCall)]
internal extern static int GetSlot(RuntimeMethodHandleInternal method);
- [System.Security.SecurityCritical] // auto-generated
internal static int GetSlot(IRuntimeMethodInfo method)
{
Contract.Requires(method != null);
return slot;
}
- [System.Security.SecurityCritical] // auto-generated
[MethodImplAttribute(MethodImplOptions.InternalCall)]
internal extern static int GetMethodDef(IRuntimeMethodInfo method);
- [System.Security.SecurityCritical] // auto-generated
[MethodImplAttribute(MethodImplOptions.InternalCall)]
internal extern static string GetName(RuntimeMethodHandleInternal method);
- [System.Security.SecurityCritical] // auto-generated
internal static string GetName(IRuntimeMethodInfo method)
{
string name = RuntimeMethodHandle.GetName(method.Value);
return name;
}
- [System.Security.SecurityCritical] // auto-generated
[MethodImplAttribute(MethodImplOptions.InternalCall)]
private extern static void* _GetUtf8Name(RuntimeMethodHandleInternal method);
- [System.Security.SecurityCritical] // auto-generated
internal static Utf8String GetUtf8Name(RuntimeMethodHandleInternal method)
{
return new Utf8String(_GetUtf8Name(method));
}
- [System.Security.SecurityCritical] // auto-generated
[MethodImplAttribute(MethodImplOptions.InternalCall)]
internal static extern bool MatchesNameHash(RuntimeMethodHandleInternal method, uint hash);
- [System.Security.SecuritySafeCritical] // auto-generated
[DebuggerStepThroughAttribute]
[Diagnostics.DebuggerHidden]
[MethodImplAttribute(MethodImplOptions.InternalCall)]
internal extern static object InvokeMethod(object target, object[] arguments, Signature sig, bool constructor);
#region Private Invocation Helpers
- [System.Security.SecurityCritical] // auto-generated
internal static INVOCATION_FLAGS GetSecurityFlags(IRuntimeMethodInfo handle)
{
return (INVOCATION_FLAGS)RuntimeMethodHandle.GetSpecialSecurityFlags(handle);
}
- [System.Security.SecurityCritical] // auto-generated
[MethodImplAttribute(MethodImplOptions.InternalCall)]
static extern internal uint GetSpecialSecurityFlags(IRuntimeMethodInfo method);
-#if !FEATURE_CORECLR
- [System.Security.SecurityCritical] // auto-generated
- [MethodImplAttribute(MethodImplOptions.InternalCall)]
- static extern internal void PerformSecurityCheck(Object obj, RuntimeMethodHandleInternal method, RuntimeType parent, uint invocationFlags);
-
- [System.Security.SecurityCritical]
- static internal void PerformSecurityCheck(Object obj, IRuntimeMethodInfo method, RuntimeType parent, uint invocationFlags)
- {
- RuntimeMethodHandle.PerformSecurityCheck(obj, method.Value, parent, invocationFlags);
- GC.KeepAlive(method);
- return;
- }
-#endif //!FEATURE_CORECLR
#endregion
- [System.Security.SecuritySafeCritical] // auto-generated
[DebuggerStepThroughAttribute]
[Diagnostics.DebuggerHidden]
[MethodImplAttribute(MethodImplOptions.InternalCall)]
// This returns true if the token is SecurityTransparent:
// just the token - does not consider including module/type etc.
- [System.Security.SecurityCritical] // auto-generated
[MethodImplAttribute(MethodImplOptions.InternalCall)]
internal static extern bool _IsTokenSecurityTransparent(RuntimeModule module, int metaDataToken);
-#if FEATURE_CORECLR
- [System.Security.SecuritySafeCritical] // auto-generated
-#else
- [System.Security.SecurityCritical]
-#endif
internal static bool IsTokenSecurityTransparent(Module module, int metaDataToken)
{
return _IsTokenSecurityTransparent(module.ModuleHandle.GetRuntimeModule(), metaDataToken);
}
- [System.Security.SecurityCritical] // auto-generated
[DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
[SuppressUnmanagedCodeSecurity]
[return: MarshalAs(UnmanagedType.Bool)]
private static extern bool _IsSecurityCritical(IRuntimeMethodInfo method);
- [System.Security.SecuritySafeCritical] // auto-generated
internal static bool IsSecurityCritical(IRuntimeMethodInfo method)
{
return _IsSecurityCritical(method);
}
- [System.Security.SecurityCritical] // auto-generated
[DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
[SuppressUnmanagedCodeSecurity]
[return: MarshalAs(UnmanagedType.Bool)]
private static extern bool _IsSecuritySafeCritical(IRuntimeMethodInfo method);
- [System.Security.SecuritySafeCritical] // auto-generated
internal static bool IsSecuritySafeCritical(IRuntimeMethodInfo method)
{
return _IsSecuritySafeCritical(method);
}
- [System.Security.SecurityCritical] // auto-generated
[DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
[SuppressUnmanagedCodeSecurity]
[return: MarshalAs(UnmanagedType.Bool)]
private static extern bool _IsSecurityTransparent(IRuntimeMethodInfo method);
- [System.Security.SecuritySafeCritical] // auto-generated
internal static bool IsSecurityTransparent(IRuntimeMethodInfo method)
{
return _IsSecurityTransparent(method);
}
- [System.Security.SecurityCritical] // auto-generated
[DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
[SuppressUnmanagedCodeSecurity]
private extern static void GetMethodInstantiation(RuntimeMethodHandleInternal method, ObjectHandleOnStack types, bool fAsRuntimeTypeArray);
- [System.Security.SecuritySafeCritical] // auto-generated
internal static RuntimeType[] GetMethodInstantiationInternal(IRuntimeMethodInfo method)
{
RuntimeType[] types = null;
return types;
}
- [System.Security.SecuritySafeCritical] // auto-generated
internal static RuntimeType[] GetMethodInstantiationInternal(RuntimeMethodHandleInternal method)
{
RuntimeType[] types = null;
return types;
}
- [System.Security.SecuritySafeCritical] // auto-generated
internal static Type[] GetMethodInstantiationPublic(IRuntimeMethodInfo method)
{
RuntimeType[] types = null;
return types;
}
- [System.Security.SecurityCritical] // auto-generated
[MethodImplAttribute(MethodImplOptions.InternalCall)]
internal extern static bool HasMethodInstantiation(RuntimeMethodHandleInternal method);
- [System.Security.SecuritySafeCritical] // auto-generated
internal static bool HasMethodInstantiation(IRuntimeMethodInfo method)
{
bool fRet = RuntimeMethodHandle.HasMethodInstantiation(method.Value);
return fRet;
}
- [System.Security.SecurityCritical] // auto-generated
[MethodImplAttribute(MethodImplOptions.InternalCall)]
internal extern static RuntimeMethodHandleInternal GetStubIfNeeded(RuntimeMethodHandleInternal method, RuntimeType declaringType, RuntimeType[] methodInstantiation);
- [System.Security.SecurityCritical] // auto-generated
[MethodImplAttribute(MethodImplOptions.InternalCall)]
internal extern static RuntimeMethodHandleInternal GetMethodFromCanonical(RuntimeMethodHandleInternal method, RuntimeType declaringType);
- [System.Security.SecurityCritical] // auto-generated
[MethodImplAttribute(MethodImplOptions.InternalCall)]
internal extern static bool IsGenericMethodDefinition(RuntimeMethodHandleInternal method);
- [System.Security.SecuritySafeCritical] // auto-generated
internal static bool IsGenericMethodDefinition(IRuntimeMethodInfo method)
{
bool fRet = RuntimeMethodHandle.IsGenericMethodDefinition(method.Value);
}
- [System.Security.SecuritySafeCritical] // auto-generated
[MethodImplAttribute(MethodImplOptions.InternalCall)]
internal extern static bool IsTypicalMethodDefinition(IRuntimeMethodInfo method);
- [System.Security.SecurityCritical] // auto-generated
[DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
[SuppressUnmanagedCodeSecurity]
private extern static void GetTypicalMethodDefinition(IRuntimeMethodInfo method, ObjectHandleOnStack outMethod);
- [System.Security.SecuritySafeCritical] // auto-generated
internal static IRuntimeMethodInfo GetTypicalMethodDefinition(IRuntimeMethodInfo method)
{
if (!IsTypicalMethodDefinition(method))
return method;
}
- [System.Security.SecurityCritical] // auto-generated
[DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
[SuppressUnmanagedCodeSecurity]
private extern static void StripMethodInstantiation(IRuntimeMethodInfo method, ObjectHandleOnStack outMethod);
- [System.Security.SecuritySafeCritical] // auto-generated
internal static IRuntimeMethodInfo StripMethodInstantiation(IRuntimeMethodInfo method)
{
IRuntimeMethodInfo strippedMethod = method;
return strippedMethod;
}
- [System.Security.SecuritySafeCritical] // auto-generated
[MethodImplAttribute(MethodImplOptions.InternalCall)]
internal extern static bool IsDynamicMethod(RuntimeMethodHandleInternal method);
- [System.Security.SecurityCritical] // auto-generated
[DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
[SuppressUnmanagedCodeSecurity]
internal extern static void Destroy(RuntimeMethodHandleInternal method);
- [System.Security.SecuritySafeCritical] // auto-generated
[MethodImplAttribute(MethodImplOptions.InternalCall)]
internal extern static Resolver GetResolver(RuntimeMethodHandleInternal method);
- [System.Security.SecurityCritical] // auto-generated
[DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
[SuppressUnmanagedCodeSecurity]
private static extern void GetCallerType(StackCrawlMarkHandle stackMark, ObjectHandleOnStack retType);
- [System.Security.SecuritySafeCritical] // auto-generated
internal static RuntimeType GetCallerType(ref StackCrawlMark stackMark)
{
RuntimeType type = null;
}
[MethodImpl(MethodImplOptions.InternalCall)]
- [System.Security.SecuritySafeCritical] // auto-generated
internal extern static MethodBody GetMethodBody(IRuntimeMethodInfo method, RuntimeType declaringType);
- [System.Security.SecurityCritical] // auto-generated
[MethodImpl(MethodImplOptions.InternalCall)]
internal extern static bool IsConstructor(RuntimeMethodHandleInternal method);
- [System.Security.SecurityCritical] // auto-generated
[MethodImpl(MethodImplOptions.InternalCall)]
internal extern static LoaderAllocator GetLoaderAllocator(RuntimeMethodHandleInternal method);
}
internal IntPtr Value
{
- [SecurityCritical]
get
{
return m_handle;
}
}
- [SecurityCritical]
internal RuntimeFieldHandleInternal(IntPtr value)
{
m_handle = value;
[StructLayout(LayoutKind.Sequential)]
internal class RuntimeFieldInfoStub : IRuntimeFieldInfo
{
- [SecuritySafeCritical]
public RuntimeFieldInfoStub(IntPtr methodHandleValue, object keepalive)
{
m_keepalive = keepalive;
object m_d;
int m_b;
object m_e;
-#if FEATURE_REMOTING
- object m_f;
-#endif
RuntimeFieldHandleInternal m_fieldHandle;
#pragma warning restore 169
public IntPtr Value
{
- [SecurityCritical]
get
{
return m_ptr != null ? m_ptr.Value.Value : IntPtr.Zero;
return m_ptr == null;
}
- [SecuritySafeCritical]
public override int GetHashCode()
{
return ValueType.GetHashCodeOfPtr(Value);
}
[ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)]
- [SecuritySafeCritical]
public override bool Equals(object obj)
{
if (!(obj is RuntimeFieldHandle))
}
[ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)]
- [SecuritySafeCritical]
public unsafe bool Equals(RuntimeFieldHandle handle)
{
return handle.Value == Value;
return !left.Equals(right);
}
- [System.Security.SecurityCritical] // auto-generated
[MethodImplAttribute(MethodImplOptions.InternalCall)]
internal static extern String GetName(RtFieldInfo field);
- [System.Security.SecurityCritical] // auto-generated
[MethodImplAttribute(MethodImplOptions.InternalCall)]
private static extern unsafe void* _GetUtf8Name(RuntimeFieldHandleInternal field);
- [System.Security.SecuritySafeCritical] // auto-generated
internal static unsafe Utf8String GetUtf8Name(RuntimeFieldHandleInternal field) { return new Utf8String(_GetUtf8Name(field)); }
- [System.Security.SecurityCritical] // auto-generated
[MethodImplAttribute(MethodImplOptions.InternalCall)]
internal static extern bool MatchesNameHash(RuntimeFieldHandleInternal handle, uint hash);
- [System.Security.SecurityCritical] // auto-generated
[MethodImplAttribute(MethodImplOptions.InternalCall)]
internal static extern FieldAttributes GetAttributes(RuntimeFieldHandleInternal field);
- [System.Security.SecurityCritical] // auto-generated
[MethodImplAttribute(MethodImplOptions.InternalCall)]
internal static extern RuntimeType GetApproxDeclaringType(RuntimeFieldHandleInternal field);
- [System.Security.SecurityCritical] // auto-generated
internal static RuntimeType GetApproxDeclaringType(IRuntimeFieldInfo field)
{
RuntimeType type = GetApproxDeclaringType(field.Value);
return type;
}
- [System.Security.SecurityCritical] // auto-generated
[MethodImplAttribute(MethodImplOptions.InternalCall)]
internal static extern int GetToken(RtFieldInfo field);
- [System.Security.SecurityCritical] // auto-generated
[MethodImplAttribute(MethodImplOptions.InternalCall)]
internal static extern Object GetValue(RtFieldInfo field, Object instance, RuntimeType fieldType, RuntimeType declaringType, ref bool domainInitialized);
- [System.Security.SecurityCritical] // auto-generated
[MethodImplAttribute(MethodImplOptions.InternalCall)]
internal static extern Object GetValueDirect(RtFieldInfo field, RuntimeType fieldType, void *pTypedRef, RuntimeType contextType);
- [System.Security.SecurityCritical] // auto-generated
[MethodImplAttribute(MethodImplOptions.InternalCall)]
internal static extern void SetValue(RtFieldInfo field, Object obj, Object value, RuntimeType fieldType, FieldAttributes fieldAttr, RuntimeType declaringType, ref bool domainInitialized);
- [System.Security.SecurityCritical] // auto-generated
[MethodImplAttribute(MethodImplOptions.InternalCall)]
internal static extern void SetValueDirect(RtFieldInfo field, RuntimeType fieldType, void* pTypedRef, Object value, RuntimeType contextType);
- [System.Security.SecurityCritical] // auto-generated
[MethodImplAttribute(MethodImplOptions.InternalCall)]
internal static extern RuntimeFieldHandleInternal GetStaticFieldForGenericType(RuntimeFieldHandleInternal field, RuntimeType declaringType);
- [System.Security.SecurityCritical] // auto-generated
[MethodImplAttribute(MethodImplOptions.InternalCall)]
internal static extern bool AcquiresContextFromThis(RuntimeFieldHandleInternal field);
- [System.Security.SecurityCritical] // auto-generated
[DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
[SuppressUnmanagedCodeSecurity]
[return: MarshalAs(UnmanagedType.Bool)]
private static extern bool IsSecurityCritical(RuntimeFieldHandle fieldHandle);
- [System.Security.SecuritySafeCritical] // auto-generated
internal bool IsSecurityCritical()
{
return IsSecurityCritical(GetNativeHandle());
}
- [System.Security.SecurityCritical] // auto-generated
[DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
[SuppressUnmanagedCodeSecurity]
[return: MarshalAs(UnmanagedType.Bool)]
private static extern bool IsSecuritySafeCritical(RuntimeFieldHandle fieldHandle);
- [System.Security.SecuritySafeCritical] // auto-generated
internal bool IsSecuritySafeCritical()
{
return IsSecuritySafeCritical(GetNativeHandle());
}
- [System.Security.SecurityCritical] // auto-generated
[DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
[SuppressUnmanagedCodeSecurity]
[return: MarshalAs(UnmanagedType.Bool)]
private static extern bool IsSecurityTransparent(RuntimeFieldHandle fieldHandle);
- [System.Security.SecuritySafeCritical] // auto-generated
internal bool IsSecurityTransparent()
{
return IsSecurityTransparent(GetNativeHandle());
}
- [SecurityCritical]
[DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
[SuppressUnmanagedCodeSecurity]
internal static extern void CheckAttributeAccess(RuntimeFieldHandle fieldHandle, RuntimeModule decoratedTarget);
// ISerializable interface
- [System.Security.SecurityCritical] // auto-generated
private RuntimeFieldHandle(SerializationInfo info, StreamingContext context)
{
if(info==null)
throw new SerializationException(Environment.GetResourceString("Serialization_InsufficientState"));
}
- [System.Security.SecurityCritical]
public void GetObjectData(SerializationInfo info, StreamingContext context)
{
if (info == null)
return !left.Equals(right);
}
- [System.Security.SecurityCritical] // auto-generated
[MethodImplAttribute(MethodImplOptions.InternalCall)]
internal static extern IRuntimeMethodInfo GetDynamicMethod(DynamicMethod method, RuntimeModule module, string name, byte[] sig, Resolver resolver);
- [System.Security.SecurityCritical] // auto-generated
[MethodImplAttribute(MethodImplOptions.InternalCall)]
internal static extern int GetToken(RuntimeModule module);
return new RuntimeTypeHandle(ModuleHandle.ResolveTypeHandleInternal(GetRuntimeModule(), typeToken, typeInstantiationContext, methodInstantiationContext));
}
- [System.Security.SecuritySafeCritical] // auto-generated
internal static RuntimeType ResolveTypeHandleInternal(RuntimeModule module, int typeToken, RuntimeTypeHandle[] typeInstantiationContext, RuntimeTypeHandle[] methodInstantiationContext)
{
ValidateModulePointer(module);
}
}
- [System.Security.SecurityCritical] // auto-generated
[DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
[SuppressUnmanagedCodeSecurity]
private extern static void ResolveType(RuntimeModule module,
return new RuntimeMethodHandle(ResolveMethodHandleInternal(GetRuntimeModule(), methodToken, typeInstantiationContext, methodInstantiationContext));
}
- [System.Security.SecuritySafeCritical] // auto-generated
internal static IRuntimeMethodInfo ResolveMethodHandleInternal(RuntimeModule module, int methodToken, RuntimeTypeHandle[] typeInstantiationContext, RuntimeTypeHandle[] methodInstantiationContext)
{
int typeInstCount, methodInstCount;
return retVal;
}
- [System.Security.SecurityCritical] // auto-generated
internal static RuntimeMethodHandleInternal ResolveMethodHandleInternalCore(RuntimeModule module, int methodToken, IntPtr[] typeInstantiationContext, int typeInstCount, IntPtr[] methodInstantiationContext, int methodInstCount)
{
ValidateModulePointer(module);
}
}
- [System.Security.SecurityCritical] // auto-generated
[DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
[SuppressUnmanagedCodeSecurity]
private extern static RuntimeMethodHandleInternal ResolveMethod(RuntimeModule module,
public RuntimeFieldHandle ResolveFieldHandle(int fieldToken, RuntimeTypeHandle[] typeInstantiationContext, RuntimeTypeHandle[] methodInstantiationContext)
{ return new RuntimeFieldHandle(ResolveFieldHandleInternal(GetRuntimeModule(), fieldToken, typeInstantiationContext, methodInstantiationContext)); }
- [System.Security.SecuritySafeCritical] // auto-generated
internal static IRuntimeFieldInfo ResolveFieldHandleInternal(RuntimeModule module, int fieldToken, RuntimeTypeHandle[] typeInstantiationContext, RuntimeTypeHandle[] methodInstantiationContext)
{
ValidateModulePointer(module);
}
}
- [System.Security.SecurityCritical] // auto-generated
[DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
[SuppressUnmanagedCodeSecurity]
private extern static void ResolveField(RuntimeModule module,
int methodInstCount,
ObjectHandleOnStack retField);
- [System.Security.SecurityCritical] // auto-generated
[DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
[SuppressUnmanagedCodeSecurity]
private extern static bool _ContainsPropertyMatchingHash(RuntimeModule module, int propertyToken, uint hash);
- [System.Security.SecurityCritical] // auto-generated
internal static bool ContainsPropertyMatchingHash(RuntimeModule module, int propertyToken, uint hash)
{
return _ContainsPropertyMatchingHash(module.GetNativeHandle(), propertyToken, hash);
}
- [System.Security.SecurityCritical] // auto-generated
[DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
[SuppressUnmanagedCodeSecurity]
private extern static void GetAssembly(RuntimeModule handle, ObjectHandleOnStack retAssembly);
- [System.Security.SecuritySafeCritical] // auto-generated
internal static RuntimeAssembly GetAssembly(RuntimeModule module)
{
RuntimeAssembly retAssembly = null;
return retAssembly;
}
- [System.Security.SecurityCritical] // auto-generated
[DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
[SuppressUnmanagedCodeSecurity]
internal extern static void GetModuleType(RuntimeModule handle, ObjectHandleOnStack type);
- [System.Security.SecuritySafeCritical] // auto-generated
internal static RuntimeType GetModuleType(RuntimeModule module)
{
RuntimeType type = null;
return type;
}
- [System.Security.SecurityCritical] // auto-generated
[DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
[SuppressUnmanagedCodeSecurity]
private extern static void GetPEKind(RuntimeModule handle, out int peKind, out int machine);
// making this internal, used by Module.GetPEKind
- [System.Security.SecuritySafeCritical] // auto-generated
internal static void GetPEKind(RuntimeModule module, out PortableExecutableKinds peKind, out ImageFileMachine machine)
{
int lKind, lMachine;
machine = (ImageFileMachine)lMachine;
}
- [System.Security.SecurityCritical] // auto-generated
[MethodImplAttribute(MethodImplOptions.InternalCall)]
internal extern static int GetMDStreamVersion(RuntimeModule module);
public int MDStreamVersion
{
- [System.Security.SecuritySafeCritical] // auto-generated
get { return GetMDStreamVersion(GetRuntimeModule().GetNativeHandle()); }
}
- [System.Security.SecurityCritical] // auto-generated
[MethodImplAttribute(MethodImplOptions.InternalCall)]
private extern static IntPtr _GetMetadataImport(RuntimeModule module);
- [System.Security.SecurityCritical] // auto-generated
internal static MetadataImport GetMetadataImport(RuntimeModule module)
{
return new MetadataImport(_GetMetadataImport(module.GetNativeHandle()), module);
#endregion
#region FCalls
- [System.Security.SecurityCritical] // auto-generated
[MethodImplAttribute(MethodImplOptions.InternalCall)]
private extern void GetSignature(
void* pCorSig, int cCorSig,
internal RuntimeType m_declaringType;
internal RuntimeType m_returnTypeORfieldType;
internal object m_keepalive;
- [SecurityCritical]
internal void* m_sig;
internal int m_managedCallingConventionAndArgIteratorFlags; // lowest byte is CallingConvention, upper 3 bytes are ArgIterator flags
internal int m_nSizeOfArgStack;
#endregion
#region Constructors
- [System.Security.SecuritySafeCritical] // auto-generated
public Signature (
IRuntimeMethodInfo method,
RuntimeType[] arguments,
GetSignature(null, 0, new RuntimeFieldHandleInternal(), method, null);
}
- [System.Security.SecuritySafeCritical] // auto-generated
public Signature(IRuntimeMethodInfo methodHandle, RuntimeType declaringType)
{
GetSignature(null, 0, new RuntimeFieldHandleInternal(), methodHandle, declaringType);
}
- [System.Security.SecurityCritical] // auto-generated
public Signature(IRuntimeFieldInfo fieldHandle, RuntimeType declaringType)
{
GetSignature(null, 0, fieldHandle.Value, null, declaringType);
GC.KeepAlive(fieldHandle);
}
- [System.Security.SecurityCritical] // auto-generated
public Signature(void* pCorSig, int cCorSig, RuntimeType declaringType)
{
GetSignature(pCorSig, cCorSig, new RuntimeFieldHandleInternal(), null, declaringType);
internal RuntimeType ReturnType { get { return m_returnTypeORfieldType; } }
internal RuntimeType FieldType { get { return m_returnTypeORfieldType; } }
- [System.Security.SecuritySafeCritical]
[MethodImplAttribute(MethodImplOptions.InternalCall)]
internal static extern bool CompareSig(Signature sig1, Signature sig2);
- [System.Security.SecuritySafeCritical]
[MethodImplAttribute(MethodImplOptions.InternalCall)]
internal extern Type[] GetCustomModifiers(int position, bool required);
#endregion
internal abstract RuntimeType GetJitContext(ref int securityControlFlags);
internal abstract byte[] GetCodeInfo(ref int stackSize, ref int initLocals, ref int EHCount);
internal abstract byte[] GetLocalsSignature();
- [System.Security.SecurityCritical] // takes a pointer parameter
internal abstract unsafe void GetEHInfo(int EHNumber, void* exception);
internal abstract unsafe byte[] GetRawEHInfo();
// token resolution
internal abstract String GetStringLiteral(int token);
- [System.Security.SecurityCritical] // passes a pointer out
internal abstract void ResolveToken(int token, out IntPtr typeHandle, out IntPtr methodHandle, out IntPtr fieldHandle);
internal abstract byte[] ResolveSignature(int token, int fromMethod);
//
// Provides a string representation of a byte.
- [System.Security.SecuritySafeCritical] // auto-generated
public override String ToString() {
Contract.Ensures(Contract.Result<String>() != null);
return Number.FormatInt32(m_value, null, NumberFormatInfo.CurrentInfo);
}
- [System.Security.SecuritySafeCritical] // auto-generated
public String ToString(IFormatProvider provider) {
Contract.Ensures(Contract.Result<String>() != null);
return Number.FormatInt32(m_value, null, NumberFormatInfo.GetInstance(provider));
return ToString(format, NumberFormatInfo.GetInstance(provider));
}
- [System.Security.SecuritySafeCritical] // auto-generated
private String ToString(String format, NumberFormatInfo info) {
Contract.Ensures(Contract.Result<String>() != null);
[Flags]
public enum AccessControlActions {
-#if FEATURE_MACL
- None = 0,
- View = 1,
- Change = 2
-#else
None = 0
-#endif
}
}
//
using System;
+using System.Diagnostics;
using System.Diagnostics.Contracts;
using System.Security.Permissions;
using Microsoft.Win32;
Flags = ""SkipVerification"" />
</PermissionSet>";
-#if FEATURE_CAS_POLICY
- private const string s_wpfExtensionXml =
- @"<PermissionSet class = ""System.Security.PermissionSet""
- version = ""1"">
- <IPermission class = ""System.Security.Permissions.MediaPermission, " + AssemblyRef.WindowsBase + @"""
- version = ""1""
- Audio=""SafeAudio"" Video=""SafeVideo"" Image=""SafeImage"" />
- <IPermission class = ""System.Security.Permissions.WebBrowserPermission, " + AssemblyRef.WindowsBase + @"""
- version = ""1""
- Level=""Safe"" />
- </PermissionSet>";
-
- private const string s_wpfExtensionUnrestrictedXml =
- @"<PermissionSet class = ""System.Security.PermissionSet""
- version = ""1"">
- <IPermission class = ""System.Security.Permissions.MediaPermission, " + AssemblyRef.WindowsBase + @"""
- version = ""1""
- Unrestricted = ""true"" />
- <IPermission class = ""System.Security.Permissions.WebBrowserPermission, " + AssemblyRef.WindowsBase + @"""
- version = ""1""
- Unrestricted = ""true"" />
- </PermissionSet>";
-#endif //FEATURE_CAS_POLICY
-
//
// Built in permission set objects
//
internal static NamedPermissionSet Everything
{
- get { return GetOrDeserializeExtendablePermissionSet(ref s_everything, s_everythingXml
-#if FEATURE_CAS_POLICY
- , s_wpfExtensionUnrestrictedXml
-#endif // FEATURE_CAS_POLICY
- ); }
+ get { return GetOrDeserializeExtendablePermissionSet(ref s_everything, s_everythingXml); }
}
internal static NamedPermissionSet Execution
internal static NamedPermissionSet Internet
{
- get { return GetOrDeserializeExtendablePermissionSet(ref s_internet, s_internetXml
-#if FEATURE_CAS_POLICY
- , s_wpfExtensionXml
-#endif // FEATURE_CAS_POLICY
- ); }
+ get { return GetOrDeserializeExtendablePermissionSet(ref s_internet, s_internetXml); }
}
internal static NamedPermissionSet LocalIntranet
{
- get { return GetOrDeserializeExtendablePermissionSet(ref s_localIntranet, s_localIntranetXml
-#if FEATURE_CAS_POLICY
- , s_wpfExtensionXml
-#endif // FEATURE_CAS_POLICY
- ); }
+ get { return GetOrDeserializeExtendablePermissionSet(ref s_localIntranet, s_localIntranetXml); }
}
internal static NamedPermissionSet Nothing
// set extensions if necessary
//
- private static NamedPermissionSet GetOrDeserializeExtendablePermissionSet(ref NamedPermissionSet permissionSet,
- string permissionSetXml
-#if FEATURE_CAS_POLICY
- ,string extensionXml
-#endif // FEATURE_CAS_POLICY
- )
+ private static NamedPermissionSet GetOrDeserializeExtendablePermissionSet(
+ ref NamedPermissionSet permissionSet,
+ string permissionSetXml)
{
Contract.Requires(!String.IsNullOrEmpty(permissionSetXml));
-#if FEATURE_CAS_POLICY
- Contract.Requires(!String.IsNullOrEmpty(extensionXml));
-#endif // FEATURE_CAS_POLICY
-
- if (permissionSet == null)
- {
-#if FEATURE_CAS_POLICY
- SecurityElement securityElement = SecurityElement.FromString(permissionSetXml);
- NamedPermissionSet deserializedPermissionSet = new NamedPermissionSet(securityElement);
-
- PermissionSet extensions = GetPermissionSetExtensions(extensionXml);
- deserializedPermissionSet.InplaceUnion(extensions);
-
- permissionSet = deserializedPermissionSet;
-#endif // FEATURE_CAS_POLICY
- }
-
return permissionSet.Copy() as NamedPermissionSet;
}
private static NamedPermissionSet GetOrDeserializePermissionSet(ref NamedPermissionSet permissionSet,
string permissionSetXml)
{
- Contract.Assert(!String.IsNullOrEmpty(permissionSetXml));
-
-#if FEATURE_CAS_POLICY
- if (permissionSet == null)
- {
- SecurityElement securityElement = SecurityElement.FromString(permissionSetXml);
- NamedPermissionSet deserializedPermissionSet = new NamedPermissionSet(securityElement);
-
- permissionSet = deserializedPermissionSet;
- }
-#endif // FEATURE_CAS_POLICY
-
+ Debug.Assert(!String.IsNullOrEmpty(permissionSetXml));
return permissionSet.Copy() as NamedPermissionSet;
}
-
-#if FEATURE_CAS_POLICY
- private static PermissionSet GetPermissionSetExtensions(string extensionXml)
- {
- Contract.Requires(!String.IsNullOrEmpty(extensionXml));
-
- SecurityElement se = SecurityElement.FromString(extensionXml);
-
- // Return the permission set extension only if WPF is in the present framework profile.
- // XMLUtil.GetClassFromElement() helps do the quickest check, with no exception thrown and
- // minimal parsing.
- SecurityElement firstPermission = (SecurityElement)se.Children[0];
- if (System.Security.Util.XMLUtil.GetClassFromElement(firstPermission, /*ignoreTypeLoadFailures*/true) != null)
- {
- PermissionSet extensions = new NamedPermissionSet(se);
- return extensions;
- }
-
- return null;
- }
-#endif // FEATURE_CAS_POLICY
}
}
using System.Collections;
using System.Text;
using System;
- using System.Diagnostics;
+ using System.Diagnostics;
using System.Diagnostics.Contracts;
using IUnrestrictedPermission = System.Security.Permissions.IUnrestrictedPermission;
[Serializable]
-#if !FEATURE_CORECLR
- [SecurityPermissionAttribute( SecurityAction.InheritanceDemand, ControlEvidence = true, ControlPolicy = true )]
-#endif
[System.Runtime.InteropServices.ComVisible(true)]
abstract public class CodeAccessPermission
: IPermission, ISecurityEncodable, IStackWalk
{
// Static methods for manipulation of stack
- [System.Security.SecuritySafeCritical] // auto-generated
[MethodImplAttribute(MethodImplOptions.NoInlining)] // Methods containing StackCrawlMark local var has to be marked non-inlineable
public static void RevertAssert()
{
SecurityRuntime.RevertAssert(ref stackMark);
}
- [System.Security.SecuritySafeCritical] // auto-generated
[MethodImplAttribute(MethodImplOptions.NoInlining)] // Methods containing StackCrawlMark local var has to be marked non-inlineable
[Obsolete("Deny is obsolete and will be removed in a future release of the .NET Framework. See http://go.microsoft.com/fwlink/?LinkID=155570 for more information.")]
public static void RevertDeny()
SecurityRuntime.RevertDeny(ref stackMark);
}
- [System.Security.SecuritySafeCritical] // auto-generated
[MethodImplAttribute(MethodImplOptions.NoInlining)] // Methods containing StackCrawlMark local var has to be marked non-inlineable
public static void RevertPermitOnly()
{
SecurityRuntime.RevertPermitOnly(ref stackMark);
}
- [System.Security.SecuritySafeCritical] // auto-generated
[MethodImplAttribute(MethodImplOptions.NoInlining)] // Methods containing StackCrawlMark local var has to be marked non-inlineable
public static void RevertAll()
{
// Mark this method as requiring a security object on the caller's frame
// so the caller won't be inlined (which would mess up stack crawling).
- [System.Security.SecuritySafeCritical] // auto-generated
[DynamicSecurityMethodAttribute()]
[MethodImplAttribute(MethodImplOptions.NoInlining)] // Methods containing StackCrawlMark local var has to be marked non-inlineable
public void Demand()
}
}
- [System.Security.SecuritySafeCritical] // auto-generated
[DynamicSecurityMethodAttribute()]
[MethodImplAttribute(MethodImplOptions.NoInlining)] // Methods containing StackCrawlMark local var has to be marked non-inlineable
internal static void Demand(PermissionType permissionType)
// without having to create objects.
// The security annotation fxcop rule that flags all methods with a Demand() has logic
// which checks for methods named Demand in types that implement IPermission or IStackWalk.
- Contract.Assert(new StackFrame().GetMethod().Name.Equals("Demand"), "This method needs to be named Demand");
+ Debug.Assert(new StackFrame().GetMethod().Name.Equals("Demand"), "This method needs to be named Demand");
StackCrawlMark stackMark = StackCrawlMark.LookForMyCallersCaller;
CodeAccessSecurityEngine.SpecialDemand(permissionType, ref stackMark);
// Metadata for this method should be flaged with REQ_SQ so that
// EE can allocate space on the stack frame for FrameSecurityDescriptor
- [System.Security.SecuritySafeCritical] // auto-generated
[DynamicSecurityMethodAttribute()]
[MethodImplAttribute(MethodImplOptions.NoInlining)] // Methods containing StackCrawlMark local var has to be marked non-inlineable
public void Assert()
}
- [System.Security.SecuritySafeCritical] // auto-generated
[DynamicSecurityMethodAttribute()]
[MethodImplAttribute(MethodImplOptions.NoInlining)] // Methods containing StackCrawlMark local var has to be marked non-inlineable
static internal void Assert(bool allPossible)
// without having to new a PermissionSet.
// The security annotation fxcop rule that flags all methods with an Assert() has logic
// which checks for methods named Assert in types that implement IPermission or IStackWalk.
- Contract.Assert(new StackFrame().GetMethod().Name.Equals("Assert"), "This method needs to be named Assert");
+ Debug.Assert(new StackFrame().GetMethod().Name.Equals("Assert"), "This method needs to be named Assert");
StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller;
SecurityRuntime.AssertAllPossible(ref stackMark);
// Metadata for this method should be flaged with REQ_SQ so that
// EE can allocate space on the stack frame for FrameSecurityDescriptor
- [System.Security.SecuritySafeCritical] // auto-generated
[DynamicSecurityMethodAttribute()]
[MethodImplAttribute(MethodImplOptions.NoInlining)] // Methods containing StackCrawlMark local var has to be marked non-inlineable
[Obsolete("Deny is obsolete and will be removed in a future release of the .NET Framework. See http://go.microsoft.com/fwlink/?LinkID=155570 for more information.")]
// Metadata for this method should be flaged with REQ_SQ so that
// EE can allocate space on the stack frame for FrameSecurityDescriptor
- [System.Security.SecuritySafeCritical] // auto-generated
[DynamicSecurityMethodAttribute()]
[MethodImplAttribute(MethodImplOptions.NoInlining)] // Methods containing StackCrawlMark local var has to be marked non-inlineable
public void PermitOnly()
// otherwise we don't support it.
throw new NotSupportedException(Environment.GetResourceString( "NotSupported_SecurityPermissionUnion" ));
}
-
-#if FEATURE_CAS_POLICY
- static internal SecurityElement CreatePermissionElement( IPermission perm, String permname )
- {
- SecurityElement root = new SecurityElement( "IPermission" );
- XMLUtil.AddClassAttribute( root, perm.GetType(), permname );
- // If you hit this assert then most likely you are trying to change the name of this class.
- // This is ok as long as you change the hard coded string above and change the assert below.
- Contract.Assert( perm.GetType().FullName.Equals( permname ), "Incorrect class name passed in! Was: " + permname + " Should be " + perm.GetType().FullName);
-
- root.AddAttribute( "version", "1" );
- return root;
- }
-
- static internal void ValidateElement( SecurityElement elem, IPermission perm )
- {
- if (elem == null)
- throw new ArgumentNullException( nameof(elem) );
- Contract.EndContractBlock();
-
- if (!XMLUtil.IsPermissionElement( perm, elem ))
- throw new ArgumentException( Environment.GetResourceString( "Argument_NotAPermissionElement"));
-
- String version = elem.Attribute( "version" );
-
- if (version != null && !version.Equals( "1" ))
- throw new ArgumentException( Environment.GetResourceString( "Argument_InvalidXMLBadVersion") );
- }
-
- abstract public SecurityElement ToXml();
- abstract public void FromXml( SecurityElement elem );
-
- //
- // Unimplemented interface methods
- // (as a reminder only)
- //
-
- public override String ToString()
- {
- return ToXml().ToString();
- }
-#endif // FEATURE_CAS_POLICY
//
// HELPERS FOR IMPLEMENTING ABSTRACT METHODS
internal bool CheckDemand(CodeAccessPermission grant)
{
- Contract.Assert( grant == null || grant.GetType().Equals( this.GetType() ), "CheckDemand not defined for permissions of different type" );
+ Debug.Assert( grant == null || grant.GetType().Equals( this.GetType() ), "CheckDemand not defined for permissions of different type" );
return IsSubsetOf( grant );
}
internal bool CheckPermitOnly(CodeAccessPermission permitted)
{
- Contract.Assert( permitted == null || permitted.GetType().Equals( this.GetType() ), "CheckPermitOnly not defined for permissions of different type" );
+ Debug.Assert( permitted == null || permitted.GetType().Equals( this.GetType() ), "CheckPermitOnly not defined for permissions of different type" );
return IsSubsetOf( permitted );
}
internal bool CheckDeny(CodeAccessPermission denied)
{
- Contract.Assert( denied == null || denied.GetType().Equals( this.GetType() ), "CheckDeny not defined for permissions of different type" );
+ Debug.Assert( denied == null || denied.GetType().Equals( this.GetType() ), "CheckDeny not defined for permissions of different type" );
IPermission intersectPerm = Intersect(denied);
return (intersectPerm == null || intersectPerm.IsSubsetOf(null));
}
internal bool CheckAssert(CodeAccessPermission asserted)
{
- Contract.Assert( asserted == null || asserted.GetType().Equals( this.GetType() ), "CheckPermitOnly not defined for permissions of different type" );
+ Debug.Assert( asserted == null || asserted.GetType().Equals( this.GetType() ), "CheckPermitOnly not defined for permissions of different type" );
return IsSubsetOf( asserted );
}
}
using System.Globalization;
using System.Security.Policy;
using System.Runtime.Versioning;
+ using System.Diagnostics;
using System.Diagnostics.Contracts;
// Used in DemandInternal, to remember the result of previous demands
internal static SecurityPermission AssertPermission;
internal static PermissionToken AssertPermissionToken;
- [System.Security.SecurityCritical] // auto-generated
[MethodImplAttribute(MethodImplOptions.InternalCall)]
internal static extern void SpecialDemand(PermissionType whatPermission, ref StackCrawlMark stackMark);
- [System.Security.SecurityCritical] // auto-generated
[System.Diagnostics.Conditional( "_DEBUG" )]
private static void DEBUG_OUT( String str )
{
-#if _DEBUG
+#if _DEBUG
if (debug)
- {
-#if !FEATURE_CORECLR
- if (to_file)
- {
- System.Text.StringBuilder sb = new System.Text.StringBuilder();
- sb.Append( str );
- sb.Append ((char)13) ;
- sb.Append ((char)10) ;
- PolicyManager.DebugOut( file, sb.ToString() );
- }
- else
-#endif
- Console.WriteLine( str );
- }
-#endif
+ Console.WriteLine( str );
+#endif
}
-
-#if _DEBUG
+
+#if _DEBUG
private static bool debug = false;
-#if !FEATURE_CORECLR
- private static readonly bool to_file = false;
-#endif
private const String file = "d:\\foo\\debug.txt";
-#endif
+#endif
// static default constructor. This will be called before any of the static members are accessed.
static CodeAccessSecurityEngine()
AssertPermissionToken = PermissionToken.GetToken(AssertPermission);
}
- [System.Security.SecurityCritical] // auto-generated
#pragma warning disable 618
private static void ThrowSecurityException(RuntimeAssembly asm, PermissionSet granted, PermissionSet refused, RuntimeMethodHandleInternal rmh, SecurityAction action, Object demand, IPermission permThatFailed)
#pragma warning restore 618
// there will be an infinite recursion that overflows the stack.
PermissionSet.s_fullTrust.Assert();
asmName = asm.GetName();
-#if FEATURE_CAS_POLICY
- if(asm != Assembly.GetExecutingAssembly()) // this condition is to avoid having to marshal mscorlib's evidence (which is always in teh default domain) to the current domain
- asmEvidence = asm.Evidence;
-#endif // FEATURE_CAS_POLICY
}
throw SecurityException.MakeSecurityException(asmName, asmEvidence, granted, refused, rmh, action, demand, permThatFailed);
}
- [System.Security.SecurityCritical] // auto-generated
#pragma warning disable 618
private static void ThrowSecurityException(Object assemblyOrString, PermissionSet granted, PermissionSet refused, RuntimeMethodHandleInternal rmh, SecurityAction action, Object demand, IPermission permThatFailed)
#pragma warning restore 618
{
- Contract.Assert((assemblyOrString == null || assemblyOrString is RuntimeAssembly || assemblyOrString is String), "Must pass in an Assembly object or String object here");
+ Debug.Assert((assemblyOrString == null || assemblyOrString is RuntimeAssembly || assemblyOrString is String), "Must pass in an Assembly object or String object here");
if (assemblyOrString == null || assemblyOrString is RuntimeAssembly)
ThrowSecurityException((RuntimeAssembly)assemblyOrString, granted, refused, rmh, action, demand, permThatFailed);
}
#if FEATURE_COMPRESSEDSTACK
- [System.Security.SecurityCritical] // auto-generated
internal static void CheckSetHelper(CompressedStack cs,
PermissionSet grants,
PermissionSet refused,
CheckSetHelper(grants, refused, demands, rmh, (Object)asm, action, true);
}
#else // FEATURE_COMPRESSEDSTACK
- #if FEATURE_CORECLR
- [System.Security.SecurityCritical] // auto-generated
- #endif
#pragma warning disable 618
internal static void CheckSetHelper(Object notUsed,
PermissionSet grants,
// To reduce the amount of ifdef-code-churn, a dummy arg is used for the first parameter - instead of a CompressedStack object,
// we use a System.Object that should always be null. If we tried to change the signature of the function, there will need to be
// corresponding changes in VM (metasig.h, mscorlib.h, securitystackwalk.cpp, number of elements in the arg array, etc.)
- Contract.Assert(notUsed == null, "Should not reach here with a non-null first arg which is the CompressedStack");
+ Debug.Assert(notUsed == null, "Should not reach here with a non-null first arg which is the CompressedStack");
CheckSetHelper(grants, refused, demands, rmh, (Object)asm, action, true);
}
#endif // FEATURE_COMPRESSEDSTACK
- [System.Security.SecurityCritical] // auto-generated
#pragma warning disable 618
internal static bool CheckSetHelper(PermissionSet grants,
PermissionSet refused,
bool throwException)
#pragma warning restore 618
{
-
- Contract.Assert(demands != null, "Should not reach here with a null demand set");
-#if _DEBUG && FEATURE_CAS_POLICY
- if (debug)
- {
- DEBUG_OUT("Granted: ");
- DEBUG_OUT(grants.ToXml().ToString());
- DEBUG_OUT("Refused: ");
- DEBUG_OUT(refused != null ? refused.ToXml().ToString() : "<null>");
- DEBUG_OUT("Demanded: ");
- DEBUG_OUT(demands!=null ? demands.ToXml().ToString() : "<null>");
- }
-#endif // _DEBUG && FEATURE_CAS_POLICY
+ Debug.Assert(demands != null, "Should not reach here with a null demand set");
IPermission permThatFailed = null;
if (grants != null)
return true;
}
#if FEATURE_COMPRESSEDSTACK
- [System.Security.SecurityCritical] // auto-generated
internal static void CheckHelper(CompressedStack cs,
PermissionSet grantedSet,
PermissionSet refusedSet,
CheckHelper(grantedSet, refusedSet, demand, permToken, rmh, (Object)asm, action, true);
}
#else // FEATURE_COMPRESSEDSTACK
- #if FEATURE_CORECLR
- [System.Security.SecurityCritical] // auto-generated
- #endif
#pragma warning disable 618
internal static void CheckHelper(Object notUsed,
PermissionSet grantedSet,
// To reduce the amount of ifdef-code-churn, a dummy arg is used for the first parameter - instead of a CompressedStack object,
// we use a System.Object that should always be null. If we tried to change the signature of the function, there will need to be
// corresponding changes in VM (metasig.h, mscorlib.h, securitystackwalk.cpp, number of elements in the arg array, etc.)
- Contract.Assert(notUsed == null, "Should not reach here with a non-null first arg which is the CompressedStack");
+ Debug.Assert(notUsed == null, "Should not reach here with a non-null first arg which is the CompressedStack");
CheckHelper(grantedSet, refusedSet, demand, permToken, rmh, (Object)asm, action, true);
}
#endif // FEATURE_COMPRESSEDSTACK
- [System.Security.SecurityCritical] // auto-generated
#pragma warning disable 618
internal static bool CheckHelper(PermissionSet grantedSet,
PermissionSet refusedSet,
#pragma warning restore 618
{
// We should never get here with a null demand
- Contract.Assert(demand != null, "Should not reach here with a null demand");
-
-#if _DEBUG && FEATURE_CAS_POLICY
- if (debug)
- {
- DEBUG_OUT("Granted: ");
- DEBUG_OUT(grantedSet.ToXml().ToString());
- DEBUG_OUT("Refused: ");
- DEBUG_OUT(refusedSet != null ? refusedSet.ToXml().ToString() : "<null>");
- DEBUG_OUT("Demanded: ");
- DEBUG_OUT(demand.ToString());
- }
-#endif // _DEBUG && FEATURE_CAS_POLICY
+ Debug.Assert(demand != null, "Should not reach here with a null demand");
if (permToken == null)
permToken = PermissionToken.GetToken(demand);
// If we aren't unrestricted, there is a refused set, or our permission is not of the unrestricted
// variety, we need to do the proper callback.
- Contract.Assert(demand != null,"demand != null");
+ Debug.Assert(demand != null,"demand != null");
// Find the permission of matching type in the permission set.
return true;
}
-#if FEATURE_CAS_POLICY
- /// <summary>
- /// Demand for the grant set of an assembly
- /// </summary>
- /// <remarks>
- /// Managed half of SecurityStackWalk::DemandGrantSet.
- /// </remarks>
- [System.Security.SecurityCritical] // auto-generated
- private static void CheckGrantSetHelper(PermissionSet grantSet)
- {
- Contract.Assert(grantSet != null, "Missing grant set");
- grantSet.CopyWithNoIdentityPermissions().Demand();
- }
-
- /// <summary>
- /// Perform a security demand which succeeds if either a compatibilty permission is granted to the
- /// call stack, or restricted member access and the grant set of the target of the reflection
- /// operation is granted.
- /// </summary>
- /// <param name="permission">compatibility permission to check</param>
- /// <param name="targetGrant">grant set of the reflection target</param>
- [System.Security.SecurityCritical] // auto-generated
- internal static void ReflectionTargetDemandHelper(PermissionType permission, PermissionSet targetGrant)
- {
- ReflectionTargetDemandHelper((int)permission, targetGrant);
- }
-
- /// <summary>
- /// Perform a security demand which succeeds if either a compatibilty permission is granted to the
- /// call stack, or restricted member access and the grant set of the target of the reflection
- /// operation is granted.
- /// </summary>
- /// <remarks>
- /// Managed half of SecurityStackWalk::ReflectionTargetDemand.
- /// </remarks>
- /// <param name="permission">compatibility permission to check (See PermissionType)</param>
- /// <param name="targetGrant">grant set of the reflection target</param>
- [System.Security.SecurityCritical] // auto-generated
- [MethodImplAttribute(MethodImplOptions.NoInlining)] // Methods containing StackCrawlMark local var has to be marked non-inlineable
- private static void ReflectionTargetDemandHelper(int permission, PermissionSet targetGrant)
- {
- // Capture a compressed stack so that we can make both permission checks without walking the stack
- // multiple times.
- StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller;
- CompressedStack cs = CompressedStack.GetCompressedStack(ref stackMark);
-
- ReflectionTargetDemandHelper(permission, targetGrant, cs);
- }
-
- /// <summary>
- /// Perform a reflection target demand against a given access context
- /// </summary>
- /// <remarks>
- /// Managed half of SecurityStackWalk::ReflectionTargetDemand
- /// </remarks>
- /// <param name="permission">compatibility permission to check (See PermissionType)</param>
- /// <param name="targetGrant">grant set of the reflection target</param>
- /// <param name="accessContext">access context to do the demand against</param>
- [System.Security.SecurityCritical] // auto-generated
- private static void ReflectionTargetDemandHelper(int permission,
- PermissionSet targetGrant,
- Resolver accessContext)
- {
- ReflectionTargetDemandHelper(permission, targetGrant, accessContext.GetSecurityContext());
- }
-
- /// <summary>
- /// Perform a reflection target demand against a given compressed stack
- /// </summary>
- /// <remarks>
- /// Managed half of SecurityStackWalk::ReflectionTargetDemand
- /// </remarks>
- /// <param name="permission">compatibility permission to check (See PermissionType)</param>
- /// <param name="targetGrant">grant set of the reflection target</param>
- /// <param name="securityContext">compressed stack to do the demand against</param>
- [System.Security.SecurityCritical] // auto-generated
- private static void ReflectionTargetDemandHelper(int permission,
- PermissionSet targetGrant,
- CompressedStack securityContext)
- {
- Contract.Assert(securityContext != null, "securityContext != null");
-
- // We need to remove all identity permissions from the grant set of the target, otherwise the
- // disjunctive demand will fail unless we're reflecting on the same assembly.
- PermissionSet demandSet = null;
- if (targetGrant == null)
- {
- demandSet = new PermissionSet(PermissionState.Unrestricted);
- }
- else
- {
- demandSet = targetGrant.CopyWithNoIdentityPermissions();
- demandSet.AddPermission(new ReflectionPermission(ReflectionPermissionFlag.RestrictedMemberAccess));
- }
-
- securityContext.DemandFlagsOrGrantSet((1 << (int)permission), demandSet);
- }
-
- [System.Security.SecurityCritical] // auto-generated
- internal static void GetZoneAndOriginHelper( CompressedStack cs, PermissionSet grantSet, PermissionSet refusedSet, ArrayList zoneList, ArrayList originList )
- {
- if (cs != null)
- cs.GetZoneAndOrigin(zoneList, originList, PermissionToken.GetToken(typeof(ZoneIdentityPermission)), PermissionToken.GetToken(typeof(UrlIdentityPermission)));
- else
- {
- ZoneIdentityPermission zone = (ZoneIdentityPermission)grantSet.GetPermission( typeof( ZoneIdentityPermission ) );
- UrlIdentityPermission url = (UrlIdentityPermission)grantSet.GetPermission( typeof( UrlIdentityPermission ) );
-
- if (zone != null)
- zoneList.Add( zone.SecurityZone );
-
- if (url != null)
- originList.Add( url.Url );
- }
- }
-
- [System.Security.SecurityCritical] // auto-generated
- internal static void GetZoneAndOrigin( ref StackCrawlMark mark, out ArrayList zone, out ArrayList origin )
- {
- zone = new ArrayList();
- origin = new ArrayList();
-
- GetZoneAndOriginInternal( zone, origin, ref mark);
- }
-
- [System.Security.SecurityCritical] // auto-generated
- [MethodImplAttribute(MethodImplOptions.InternalCall)]
- private static extern void GetZoneAndOriginInternal(ArrayList zoneList,
- ArrayList originList,
- ref StackCrawlMark stackMark);
-
- [System.Security.SecurityCritical] // auto-generated
- internal static void CheckAssembly(RuntimeAssembly asm, CodeAccessPermission demand )
- {
- Contract.Assert( asm != null, "Must pass in a good assembly" );
- Contract.Assert( demand != null, "Must pass in a good demand" );
-
- PermissionSet granted, refused;
- asm.GetGrantSet( out granted, out refused );
-#pragma warning disable 618
- CheckHelper( granted, refused, demand, PermissionToken.GetToken(demand), RuntimeMethodHandleInternal.EmptyHandle, asm, SecurityAction.Demand, true );
-#pragma warning restore 618
- }
-
- // Check - Used to initiate a code-access security check.
- // This method invokes a stack walk after skipping to the frame
- // referenced by stackMark.
- [System.Security.SecurityCritical] // auto-generated
- [MethodImplAttribute(MethodImplOptions.InternalCall)]
- private static extern void Check (Object demand,
- ref StackCrawlMark stackMark,
- bool isPermSet);
-
-
- [System.Security.SecurityCritical] // auto-generated
- [MethodImplAttribute(MethodImplOptions.InternalCall)]
- internal static extern bool QuickCheckForAllDemands();
- [System.Security.SecurityCritical] // auto-generated
- [MethodImplAttribute(MethodImplOptions.InternalCall)]
- internal static extern bool AllDomainsHomogeneousWithNoStackModifiers();
-#endif // FEATURE_CAS_POLICY
-
- [System.Security.SecurityCritical] // auto-generated
internal static void Check(CodeAccessPermission cap, ref StackCrawlMark stackMark)
{
-#if FEATURE_CAS_POLICY
- Check(cap,
- ref stackMark,
- false);
-#endif // FEATURE_CAS_POLICY
}
- [System.Security.SecurityCritical] // auto-generated
internal static void Check(PermissionSet permSet, ref StackCrawlMark stackMark)
{
-#if FEATURE_CAS_POLICY
- Check(permSet,
- ref stackMark,
- true);
-#endif // FEATURE_CAS_POLICY
}
- [System.Security.SecurityCritical] // auto-generated
[MethodImplAttribute(MethodImplOptions.InternalCall)]
internal static extern FrameSecurityDescriptor CheckNReturnSO(PermissionToken permToken,
CodeAccessPermission demand,
ref StackCrawlMark stackMark,
int create );
- [System.Security.SecurityCritical] // auto-generated
internal static void Assert(CodeAccessPermission cap, ref StackCrawlMark stackMark)
{
-#if FEATURE_CAS_POLICY
- // Make sure the caller of assert has the permission to assert
- //WARNING: The placement of the call here is just right to check
- // the appropriate frame.
-
- // Note: if the "AssertPermission" is not a permission that implements IUnrestrictedPermission
- // you need to change the last parameter to a zero.
- Contract.Assert(AssertPermissionToken != null && AssertPermission != null, "Assert Permission not setup correctly");
- FrameSecurityDescriptor secObj = CheckNReturnSO(AssertPermissionToken,
- AssertPermission,
- ref stackMark,
- 1 );
- if (secObj == null)
- {
- // Security: REQ_SQ flag is missing. Bad compiler ?
- // This can happen when you create delegates over functions that need the REQ_SQ
- System.Environment.FailFast(Environment.GetResourceString("ExecutionEngine_MissingSecurityDescriptor"));
- }
- else
- {
- if (secObj.HasImperativeAsserts())
- throw new SecurityException( Environment.GetResourceString( "Security_MustRevertOverride" ) );
-
- secObj.SetAssert(cap);
- }
-#endif // FEATURE_CAS_POLICY
}
- [System.Security.SecurityCritical] // auto-generated
internal static void Deny(CodeAccessPermission cap, ref StackCrawlMark stackMark)
{
-#if FEATURE_CAS_POLICY
- // Deny is only valid in legacy mode
- if (!AppDomain.CurrentDomain.IsLegacyCasPolicyEnabled)
- {
- throw new NotSupportedException(Environment.GetResourceString("NotSupported_CasDeny"));
- }
-
- FrameSecurityDescriptor secObj =
- SecurityRuntime.GetSecurityObjectForFrame(ref stackMark, true);
- if (secObj == null)
- {
- // Security: REQ_SQ flag is missing. Bad compiler ?
- // This can happen when you create delegates over functions that need the REQ_SQ
- System.Environment.FailFast(Environment.GetResourceString("ExecutionEngine_MissingSecurityDescriptor"));
- }
- else
- {
- if (secObj.HasImperativeDenials())
- throw new SecurityException( Environment.GetResourceString( "Security_MustRevertOverride" ) );
-
- secObj.SetDeny(cap);
- }
-#endif // FEATURE_CAS_POLICY
}
- [System.Security.SecurityCritical] // auto-generated
internal static void PermitOnly(CodeAccessPermission cap, ref StackCrawlMark stackMark)
{
-#if FEATURE_CAS_POLICY
- FrameSecurityDescriptor secObj =
- SecurityRuntime.GetSecurityObjectForFrame(ref stackMark, true);
- if (secObj == null)
- {
- // Security: REQ_SQ flag is missing. Bad compiler ?
- // This can happen when you create delegates over functions that need the REQ_SQ
- System.Environment.FailFast(Environment.GetResourceString("ExecutionEngine_MissingSecurityDescriptor"));
- }
- else
- {
- if (secObj.HasImperativeRestrictions())
- throw new SecurityException( Environment.GetResourceString( "Security_MustRevertOverride" ) );
-
- secObj.SetPermitOnly(cap);
- }
-#endif // FEATURE_CAS_POLICY
- }
-
-#if FEATURE_CAS_POLICY
- // Called from the VM to do a pre-domain initialization check of the security state of the
- // AppDomain. This method looks at the state of the security of an AppDomain before it is
- // completely initialized - so the output of this method does not always match what will be true
- // when the domain is completely initialized. Instead, it is used to read what the input parameters
- // to the domain setup say about the domain.
- private static void PreResolve(out bool isFullyTrusted, out bool isHomogeneous)
- {
- //
- // There are three main cases:
- // 1. The AppDomain has an explict ApplicationTrust - we can use this to read the input state
- // of the AppDomain.
- // 2. The AppDomain is using legacy CAS policy - this means we can't tell much about the
- // domain itself without a full policy resolution.
- // 3. The domain is a standard v4+ AppDomain - these are always full trust and homogenous by
- // default.
- //
-
- // If the AppDomain is setup with an ApplicationTrust then it is always homogenous and we can
- // tell its grant set right from the ApplicaitonTrust
- ApplicationTrust domainTrust = AppDomain.CurrentDomain.SetupInformation.ApplicationTrust;
- if (domainTrust != null)
- {
- isFullyTrusted = domainTrust.DefaultGrantSet.PermissionSet.IsUnrestricted();
- isHomogeneous = true;
- return;
- }
-
- // Otherwise, see if the domain is being configured on input to use legacy CAS policy
- if (CompatibilitySwitches.IsNetFx40LegacySecurityPolicy || AppDomain.CurrentDomain.IsLegacyCasPolicyEnabled)
- {
- isFullyTrusted = false;
- isHomogeneous = false;
- return;
- }
-
- // If none of the above is true, then we must be a standard AppDomain
- isFullyTrusted = true;
- isHomogeneous = true;
- }
-
- // Called from the VM when either a HostSecurityManager or simple sandbox domain can determine the
- // grant set of an assembly
- private static PermissionSet ResolveGrantSet(Evidence evidence, out int specialFlags, bool checkExecutionPermission)
- {
- Contract.Assert(evidence != null);
- Contract.Assert(!AppDomain.CurrentDomain.IsLegacyCasPolicyEnabled); // This API does not do CAS policy resolution
-
- PermissionSet grantSet = null;
- if (!TryResolveGrantSet(evidence, out grantSet))
- {
- // If we couldn't figure out a grant set from the domain or the host, then we treat the
- // assembly as fully trusted.
- grantSet = new PermissionSet(PermissionState.Unrestricted);
- }
-
- // Make sure the grant set includes the ability to execute code if that has been requested.
- if (checkExecutionPermission)
- {
- SecurityPermission executionPermission = new SecurityPermission(SecurityPermissionFlag.Execution);
- if (!grantSet.Contains(executionPermission))
- {
- throw new PolicyException(Environment.GetResourceString("Policy_NoExecutionPermission"),
- System.__HResults.CORSEC_E_NO_EXEC_PERM);
- }
- }
-
- specialFlags = SecurityManager.GetSpecialFlags(grantSet, null);
- return grantSet;
- }
-
- // Consult the host and the current AppDomain if it is homogenous to determine what the grant set
- // of an assembly is. This API returns true if it was able to determine a grant set for the evidence,
- // false if it cannot and other policy needs to be applied.
- [SecuritySafeCritical]
- internal static bool TryResolveGrantSet(Evidence evidence, out PermissionSet grantSet)
- {
- Contract.Assert(evidence != null);
-
- HostSecurityManager securityManager = AppDomain.CurrentDomain.HostSecurityManager;
-
- // GAC assemblies always are fully trusted
- if (evidence.GetHostEvidence<GacInstalled>() != null)
- {
- grantSet = new PermissionSet(PermissionState.Unrestricted);
- return true;
- }
- // If the host wants to participate in policy resolution, then our next option is to ask it for
- // a grant set
- else if ((securityManager.Flags & HostSecurityManagerOptions.HostResolvePolicy) == HostSecurityManagerOptions.HostResolvePolicy)
- {
- PermissionSet hostGrantSet = securityManager.ResolvePolicy(evidence);
-
- if (hostGrantSet == null)
- {
- throw new PolicyException(Environment.GetResourceString("Policy_NullHostGrantSet", securityManager.GetType().FullName));
- }
-
- // If we're in a homogenous domain, we don't want to allow the host to create multiple
- // levels of permissions within the domain. So, if we see the host return something other
- // than full trust or the homogenous grant set, we reject the grant set.
- if (AppDomain.CurrentDomain.IsHomogenous)
- {
- // Some hosts, such as ASP.NET, return Nothing as a way of saying that the assembly should
- // not be allowed to run in the AppDomain. Reject that with a specific
- // no-execution-allowed-here exception message, rather than the return value validation
- // exception message we'd hit below.
- if (hostGrantSet.IsEmpty())
- {
- throw new PolicyException(Environment.GetResourceString("Policy_NoExecutionPermission"));
- }
-
- PermissionSet homogenousGrantSet = AppDomain.CurrentDomain.ApplicationTrust.DefaultGrantSet.PermissionSet;
- bool isValidGrantSet = hostGrantSet.IsUnrestricted() ||
- (hostGrantSet.IsSubsetOf(homogenousGrantSet) && homogenousGrantSet.IsSubsetOf(hostGrantSet));
-
- if (!isValidGrantSet)
- {
- throw new PolicyException(Environment.GetResourceString("Policy_GrantSetDoesNotMatchDomain", securityManager.GetType().FullName));
- }
- }
-
- grantSet = hostGrantSet;
- return true;
- }
- // If we're in a homogenous domain, we can get the grant set directly from the application trust
- else if (AppDomain.CurrentDomain.IsHomogenous)
- {
- grantSet = AppDomain.CurrentDomain.GetHomogenousGrantSet(evidence);
- return true;
- }
- // Otherwise we have no way to figure out what the grant set is
- else
- {
- grantSet = null;
- return false;
- }
}
-#endif // FEATURE_CAS_POLICY
#if FEATURE_PLS
// Update the PLS used for optimization in the AppDomain: called from the VM
- [System.Security.SecurityCritical] // auto-generated
private static PermissionListSet UpdateAppDomainPLS(PermissionListSet adPLS, PermissionSet grantedPerms, PermissionSet refusedPerms) {
if (adPLS == null) {
adPLS = new PermissionListSet();
using System.Globalization;
using System.Runtime.ConstrainedExecution;
using System.Runtime.Versioning;
+ using System.Diagnostics;
using System.Diagnostics.Contracts;
#if !FEATURE_PAL
using Microsoft.Win32.SafeHandles;
// if this frame contains a call to any WindowsIdentity.Impersonate(),
// we save the previous SafeTokenHandles here (in the next two fields)
// Used during exceptionstackwalks to revert impersonation before calling filters
- [System.Security.SecurityCritical] // auto-generated
[NonSerialized]
private SafeAccessTokenHandle m_callerToken;
- [System.Security.SecurityCritical] // auto-generated
[NonSerialized]
private SafeAccessTokenHandle m_impToken;
#endif
- [System.Security.SecurityCritical] // auto-generated
[MethodImplAttribute(MethodImplOptions.InternalCall)]
private static extern void IncrementOverridesCount();
- [System.Security.SecurityCritical] // auto-generated
[MethodImplAttribute(MethodImplOptions.InternalCall)]
private static extern void DecrementOverridesCount();
- [System.Security.SecurityCritical] // auto-generated
[MethodImplAttribute(MethodImplOptions.InternalCall)]
private static extern void IncrementAssertCount();
- [System.Security.SecurityCritical] // auto-generated
[MethodImplAttribute(MethodImplOptions.InternalCall)]
private static extern void DecrementAssertCount();
// we store declarative actions in both fields, so check if they are different
return (m_restriction != null);
}
- [System.Security.SecurityCritical] // auto-generated
internal void SetAssert(IPermission perm)
{
m_assertions = CreateSingletonSet(perm);
IncrementAssertCount();
}
- [System.Security.SecurityCritical] // auto-generated
internal void SetAssert(PermissionSet permSet)
{
m_assertions = permSet.Copy();
return (fDeclarative) ? m_DeclarativeAssertions : m_assertions;
}
- [System.Security.SecurityCritical] // auto-generated
internal void SetAssertAllPossible()
{
m_assertAllPossible = true;
// D E N Y
//-----------------------------------------------------------+
- [System.Security.SecurityCritical] // auto-generated
internal void SetDeny(IPermission perm)
{
-#if FEATURE_CAS_POLICY
- BCLDebug.Assert(AppDomain.CurrentDomain.IsLegacyCasPolicyEnabled, "Deny is only valid in legacy CAS mode");
-#endif // FEATURE_CAS_POLICY
-
m_denials = CreateSingletonSet(perm);
IncrementOverridesCount();
-
}
- [System.Security.SecurityCritical] // auto-generated
internal void SetDeny(PermissionSet permSet)
{
m_denials = permSet.Copy();
// R E S T R I C T
//-----------------------------------------------------------+
- [System.Security.SecurityCritical] // auto-generated
internal void SetPermitOnly(IPermission perm)
{
m_restriction = CreateSingletonSet(perm);
IncrementOverridesCount();
}
- [System.Security.SecurityCritical] // auto-generated
internal void SetPermitOnly(PermissionSet permSet)
{
// permSet must not be null
//-----------------------------------------------------------+
// SafeAccessTokenHandle (Impersonation + EH purposes)
//-----------------------------------------------------------+
- [System.Security.SecurityCritical] // auto-generated
internal void SetTokenHandles (SafeAccessTokenHandle callerToken, SafeAccessTokenHandle impToken)
{
m_callerToken = callerToken;
// R E V E R T
//-----------------------------------------------------------+
- [System.Security.SecurityCritical] // auto-generated
internal void RevertAssert()
{
if (m_assertions != null)
}
}
- [System.Security.SecurityCritical] // auto-generated
internal void RevertAssertAllPossible()
{
if (m_assertAllPossible)
}
}
- [System.Security.SecurityCritical] // auto-generated
internal void RevertDeny()
{
if (HasImperativeDenials())
}
}
- [System.Security.SecurityCritical] // auto-generated
internal void RevertPermitOnly()
{
if (HasImperativeRestrictions())
}
}
- [System.Security.SecurityCritical] // auto-generated
internal void RevertAll()
{
RevertAssert();
// This will get called when we hit a FSD while evaluating a demand on the call stack or compressedstack
- [System.Security.SecurityCritical] // auto-generated
internal bool CheckDemand(CodeAccessPermission demand, PermissionToken permToken, RuntimeMethodHandleInternal rmh)
{
// imperative security
return fContinue;
}
- [System.Security.SecurityCritical] // auto-generated
internal bool CheckDemand2(CodeAccessPermission demand, PermissionToken permToken, RuntimeMethodHandleInternal rmh, bool fDeclarative)
{
PermissionSet permSet;
// If the demand is null, there is no need to continue
- Contract.Assert(demand != null && !demand.CheckDemand(null), "Empty demands should have been filtered out by this point");
+ Debug.Assert(demand != null && !demand.CheckDemand(null), "Empty demands should have been filtered out by this point");
// decode imperative
if (GetPermitOnly(fDeclarative) != null)
return SecurityRuntime.StackContinue;
}
- [System.Security.SecurityCritical] // auto-generated
internal bool CheckSetDemand(PermissionSet demandSet,
out PermissionSet alteredDemandSet,
RuntimeMethodHandleInternal rmh)
return fContinue;
}
- [System.Security.SecurityCritical] // auto-generated
internal bool CheckSetDemand2(PermissionSet demandSet,
out PermissionSet alteredDemandSet,
RuntimeMethodHandleInternal rmh, bool fDeclarative)
}
- [System.Security.SecurityCritical] // auto-generated_required
public override void GetObjectData(SerializationInfo info, StreamingContext context)
{
if (info==null)
AllFlags = 0x001F
}
- [System.Security.SecurityCritical] // auto-generated_required
[Serializable]
-#if !FEATURE_CORECLR
- [SecurityPermissionAttribute(SecurityAction.InheritanceDemand, Flags=SecurityPermissionFlag.Infrastructure)]
-#endif
[System.Runtime.InteropServices.ComVisible(true)]
public class HostSecurityManager {
public HostSecurityManager () {}
}
}
-#if FEATURE_CAS_POLICY
- // provide policy for the AppDomain.
- [Obsolete("AppDomain policy levels are obsolete and will be removed in a future release of the .NET Framework. See http://go.microsoft.com/fwlink/?LinkID=155570 for more information.")]
- public virtual PolicyLevel DomainPolicy {
- get {
- if (!AppDomain.CurrentDomain.IsLegacyCasPolicyEnabled)
- {
- throw new NotSupportedException(Environment.GetResourceString("NotSupported_RequiresCasPolicyExplicit"));
- }
-
- return null;
- }
- }
-#endif
public virtual Evidence ProvideAppDomainEvidence (Evidence inputEvidence) {
// The default implementation does not modify the input evidence.
return inputEvidence;
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
-namespace System.Security {
- using System.Runtime.Remoting;
- using System;
- using System.Security.Policy;
-[System.Runtime.InteropServices.ComVisible(true)]
+namespace System.Security
+{
+ [System.Runtime.InteropServices.ComVisible(true)]
public interface IEvidenceFactory
{
-#if FEATURE_CAS_POLICY
- Evidence Evidence
- {
- get;
- }
-#endif // FEATURE_CAS_POLICY
}
-
}
// implement this interface
//
-namespace System.Security {
-
- using System;
- using System.Security.Util;
-
-
-[System.Runtime.InteropServices.ComVisible(true)]
+namespace System.Security
+{
+ [System.Runtime.InteropServices.ComVisible(true)]
public interface ISecurityEncodable
{
-#if FEATURE_CAS_POLICY
- SecurityElement ToXml();
-
- void FromXml( SecurityElement e );
-#endif // FEATURE_CAS_POLICY
}
-
}
-
-
// implement this interface
//
-namespace System.Security {
-
- using System;
- using System.Security.Util;
- using System.Security.Policy;
-
-
-[System.Runtime.InteropServices.ComVisible(true)]
+namespace System.Security
+{
+ [System.Runtime.InteropServices.ComVisible(true)]
public interface ISecurityPolicyEncodable
{
-#if FEATURE_CAS_POLICY
- SecurityElement ToXml( PolicyLevel level );
-
- void FromXml( SecurityElement e, PolicyLevel level );
-#endif // FEATURE_CAS_POLICY
}
-
}
// Extends PermissionSet to allow an associated name and description
//
-namespace System.Security {
-
+namespace System.Security
+{
using System;
- using System.Security.Util;
using System.Security.Permissions;
- using System.Runtime.Serialization;
- using System.Diagnostics.Contracts;
-#if !FEATURE_CAS_POLICY
- using Microsoft.Win32;
- using System.Collections;
- using System.Globalization;
- using System.IO;
- using System.Reflection;
- using System.Runtime.InteropServices;
- using System.Runtime.Remoting;
- using System.Runtime.Versioning;
- using System.Text;
-
-#else // FEATURE_CAS_POLICY
-
- using System.Threading;
-
-#endif // FEATURE_CAS_POLICY
-
[Serializable]
-[System.Runtime.InteropServices.ComVisible(true)]
+ [System.Runtime.InteropServices.ComVisible(true)]
public sealed class NamedPermissionSet : PermissionSet
{
-#if FEATURE_CAS_POLICY
- // The name of this PermissionSet
- private String m_name;
-
- // The description of this PermissionSet
- private String m_description;
- [OptionalField(VersionAdded = 2)]
- internal String m_descrResource;
-
- internal NamedPermissionSet()
- : base()
- {
- }
-
- public NamedPermissionSet( String name )
- : base()
- {
- CheckName( name );
- m_name = name;
- }
-
- public NamedPermissionSet( String name, PermissionState state)
- : base( state )
- {
- CheckName( name );
- m_name = name;
- }
-
-
- public NamedPermissionSet( String name, PermissionSet permSet )
- : base( permSet )
- {
- CheckName( name );
- m_name = name;
- }
-
- public NamedPermissionSet( NamedPermissionSet permSet )
- : base( permSet )
- {
- m_name = permSet.m_name;
- m_description = permSet.Description;
- }
-
- internal NamedPermissionSet(SecurityElement permissionSetXml)
- : base(PermissionState.None)
- {
- Contract.Assert(permissionSetXml != null);
- FromXml(permissionSetXml);
- }
-
- public String Name {
- get { return m_name; }
- set { CheckName( value ); m_name = value; }
- }
-
- private static void CheckName( String name )
- {
- if (name == null || name.Equals( "" ))
- throw new ArgumentException( Environment.GetResourceString( "Argument_NPMSInvalidName" ));
- Contract.EndContractBlock();
- }
-
- public String Description {
- get
- {
- if(m_descrResource != null)
- {
- m_description = Environment.GetResourceString(m_descrResource);
- m_descrResource = null;
- }
- return m_description;
- }
-
- set
- {
- m_description = value;
- m_descrResource = null;
- }
- }
-
- public override PermissionSet Copy()
- {
- return new NamedPermissionSet( this );
- }
-
- public NamedPermissionSet Copy( String name )
- {
- NamedPermissionSet set = new NamedPermissionSet( this );
- set.Name = name;
- return set;
- }
-
- public override SecurityElement ToXml()
- {
- SecurityElement elem = base.ToXml("System.Security.NamedPermissionSet");
- // If you hit this assert then most likely you are trying to change the name of this class.
- // This is ok as long as you change the hard coded string above and change the assert below.
- Contract.Assert( this.GetType().FullName.Equals( "System.Security.NamedPermissionSet" ), "Class name changed!" );
-
- if (m_name != null && !m_name.Equals( "" ))
- {
- elem.AddAttribute( "Name", SecurityElement.Escape( m_name ) );
- }
-
- if (Description != null && !Description.Equals( "" ))
- {
- elem.AddAttribute( "Description", SecurityElement.Escape( Description ) );
- }
-
- return elem;
- }
-
- public override void FromXml( SecurityElement et )
- {
- FromXml( et, false, false );
- }
-
- internal override void FromXml( SecurityElement et, bool allowInternalOnly, bool ignoreTypeLoadFailures )
- {
- if (et == null)
- throw new ArgumentNullException( nameof(et) );
- Contract.EndContractBlock();
-
- String elem;
-
- elem = et.Attribute( "Name" );
- m_name = elem == null ? null : elem;
-
- elem = et.Attribute( "Description" );
- m_description = (elem == null ? "" : elem);
- m_descrResource = null;
-
- base.FromXml( et, allowInternalOnly, ignoreTypeLoadFailures );
- }
-
- internal void FromXmlNameOnly( SecurityElement et )
+ internal static PermissionSet GetBuiltInSet(string name)
{
- // This function gets only the name for the permission set, ignoring all other info.
-
- String elem;
-
- elem = et.Attribute( "Name" );
- m_name = (elem == null ? null : elem);
- }
-
- // NamedPermissionSet Equals should have the exact semantic as PermissionSet.
- // We explicitly override them here to make sure that no one accidently
- // changes this.
-
- [System.Runtime.InteropServices.ComVisible(false)]
- public override bool Equals( Object obj )
- {
- return base.Equals( obj );
- }
-
- [System.Runtime.InteropServices.ComVisible(false)]
- public override int GetHashCode()
- {
- return base.GetHashCode();
- }
-
- private static Object s_InternalSyncObject;
- private static Object InternalSyncObject {
- get {
- if (s_InternalSyncObject == null) {
- Object o = new Object();
- Interlocked.CompareExchange(ref s_InternalSyncObject, o, null);
- }
- return s_InternalSyncObject;
- }
- }
-#else // FEATURE_CAS_POLICY
-
- internal static PermissionSet GetBuiltInSet(string name) {
// Used by PermissionSetAttribute to create one of the built-in,
// immutable permission sets.
-
if (name == null)
return null;
else if (name.Equals("FullTrust"))
}
-#endif // !FEATURE_CAS_POLICY
}
}
using System.Threading;
using System.Collections;
using System.Collections.Generic;
+ using System.Diagnostics;
using System.Diagnostics.Contracts;
[Serializable]
}
#if FEATURE_PLS
- [System.Security.SecurityCritical] // auto-generated
internal void UpdateDomainPLS (PermissionListSet adPLS) {
if (adPLS != null && adPLS.m_firstPermSetTriple != null)
UpdateDomainPLS(adPLS.m_firstPermSetTriple.GrantSet, adPLS.m_firstPermSetTriple.RefusedSet);
}
- [System.Security.SecurityCritical] // auto-generated
internal void UpdateDomainPLS (PermissionSet grantSet, PermissionSet deniedSet) {
- Contract.Assert(m_permSetTriples == null, "m_permSetTriples != null");
+ Debug.Assert(m_permSetTriples == null, "m_permSetTriples != null");
if (m_firstPermSetTriple == null)
m_firstPermSetTriple = new PermissionSetTriple();
UpdateTripleListAndCreateNewTriple(currentTriple, null);
}
- [System.Security.SecurityCritical] // auto-generated
private void Terminate(PermissionSetTriple currentTriple, PermissionListSet pls)
{
#if FEATURE_COMPRESSEDSTACK
this.UpdateTripleListAndCreateNewTriple(currentTriple, null);
}
- [System.Security.SecurityCritical] // auto-generated
private bool Update(PermissionSetTriple currentTriple, PermissionListSet pls)
{
#if FEATURE_COMPRESSEDSTACK
return this.UpdatePermissions(currentTriple, pls);
}
- [System.Security.SecurityCritical] // auto-generated
private bool Update(PermissionSetTriple currentTriple, FrameSecurityDescriptor fsd)
{
#if FEATURE_COMPRESSEDSTACK
}
#if FEATURE_COMPRESSEDSTACK
- [System.Security.SecurityCritical]
private bool Update2(PermissionSetTriple currentTriple, FrameSecurityDescriptorWithResolver fsdWithResolver)
{
System.Reflection.Emit.DynamicResolver resolver = fsdWithResolver.Resolver;
}
#endif // FEATURE_COMPRESSEDSTACK
- [System.Security.SecurityCritical] // auto-generated
private bool Update2(PermissionSetTriple currentTriple, FrameSecurityDescriptor fsd, bool fDeclarative)
{
// Deny
return false;
}
- [System.Security.SecurityCritical] // auto-generated
private void Update(PermissionSetTriple currentTriple, PermissionSet in_g, PermissionSet in_r)
{
#if FEATURE_COMPRESSEDSTACK
}
// Called from the VM for HG CS construction
- [System.Security.SecurityCritical] // auto-generated
private void Update(PermissionSet in_g)
{
if (m_firstPermSetTriple == null)
}
#endif // FEATURE_COMPRESSEDSTACK
- [System.Security.SecurityCritical] // auto-generated
private bool UpdatePermissions(PermissionSetTriple currentTriple, PermissionListSet pls)
{
if (pls != null)
}
}
-[System.Security.SecurityCritical] // auto-generated
[System.Runtime.InteropServices.ComVisible(true)]
// public(internal) interface begins...
// Creation functions
return pls;
}
- [System.Security.SecurityCritical] // auto-generated
static internal PermissionListSet CreateCompressedState(IntPtr unmanagedDCS, out bool bHaltConstruction)
{
PermissionListSet pls = new PermissionListSet();
return pls;
}
- [System.Security.SecurityCritical] // auto-generated
static internal PermissionListSet CreateCompressedState_HG()
{
PermissionListSet pls = new PermissionListSet();
}
#endif // #if FEATURE_COMPRESSEDSTACK
// Private Demand evaluation functions - only called from the VM
- [System.Security.SecurityCritical] // auto-generated
internal bool CheckDemandNoThrow(CodeAccessPermission demand)
{
// AppDomain permissions - no asserts. So there should only be one triple to work with
- Contract.Assert(m_permSetTriples == null && m_firstPermSetTriple != null, "More than one PermissionSetTriple encountered in AD PermissionListSet");
+ Debug.Assert(m_permSetTriples == null && m_firstPermSetTriple != null, "More than one PermissionSetTriple encountered in AD PermissionListSet");
}
- [System.Security.SecurityCritical] // auto-generated
internal bool CheckSetDemandNoThrow(PermissionSet pSet)
{
// AppDomain permissions - no asserts. So there should only be one triple to work with
- Contract.Assert(m_permSetTriples == null && m_firstPermSetTriple != null, "More than one PermissionSetTriple encountered in AD PermissionListSet");
+ Debug.Assert(m_permSetTriples == null && m_firstPermSetTriple != null, "More than one PermissionSetTriple encountered in AD PermissionListSet");
return m_firstPermSetTriple.CheckSetDemandNoThrow(pSet);
}
// Demand evauation functions
- [System.Security.SecurityCritical] // auto-generated
internal bool CheckDemand(CodeAccessPermission demand, PermissionToken permToken, RuntimeMethodHandleInternal rmh)
{
bool bRet = SecurityRuntime.StackContinue;
return bRet;
}
- [System.Security.SecurityCritical] // auto-generated
internal bool CheckSetDemand(PermissionSet pset , RuntimeMethodHandleInternal rmh)
{
PermissionSet unused;
return SecurityRuntime.StackHalt; // CS demand check always terminates the stackwalk
}
- [System.Security.SecurityCritical]
internal bool CheckSetDemandWithModification(PermissionSet pset, out PermissionSet alteredDemandSet, RuntimeMethodHandleInternal rmh)
{
bool bRet = SecurityRuntime.StackContinue;
/// Check to see if the PLS satisfies a demand for the special permissions encoded in flags
/// </summary>
/// <param name="flags">set of flags to check (See PermissionType)</param>
- [System.Security.SecurityCritical] // auto-generated
private bool CheckFlags(int flags)
{
- Contract.Assert(flags != 0, "Invalid permission flag demand");
+ Debug.Assert(flags != 0, "Invalid permission flag demand");
bool check = true;
/// </summary>
/// <param name="flags">set of flags to check (See PermissionType)</param>
/// <param name="grantSet">alternate permission set to check</param>
- [System.Security.SecurityCritical] // auto-generated
internal void DemandFlagsOrGrantSet(int flags, PermissionSet grantSet)
{
if (CheckFlags(flags))
using System.Text;
using System.Globalization;
using System.Runtime.Versioning;
+ using System.Diagnostics;
using System.Diagnostics.Contracts;
[Serializable]
#if FEATURE_SERIALIZATION
[Serializable]
#endif
-#if !FEATURE_CORECLR
- [StrongNameIdentityPermissionAttribute(SecurityAction.InheritanceDemand, Name = "mscorlib", PublicKey = "0x" + AssemblyRef.EcmaPublicKeyFull)]
-#endif
[System.Runtime.InteropServices.ComVisible(true)]
public class PermissionSet : ISecurityEncodable, ICollection, IStackWalk
#if FEATURE_SERIALIZATION
internal static readonly PermissionSet s_fullTrust = new PermissionSet( true );
-#if FEATURE_REMOTING
- [OnDeserializing]
- private void OnDeserializing(StreamingContext ctx)
- {
- Reset();
- }
-
- [OnDeserialized]
- private void OnDeserialized(StreamingContext ctx)
- {
- if (m_serializedPermissionSet != null)
- {
- // Whidbey non X-AD case
- FromXml(SecurityElement.FromString(m_serializedPermissionSet));
- }
- else if (m_normalPermSet != null)
- {
- // Everett non X-AD case
- m_permSet = m_normalPermSet.SpecialUnion(m_unrestrictedPermSet);
- }
- else if (m_unrestrictedPermSet != null)
- {
- // Everett non X-AD case
- m_permSet = m_unrestrictedPermSet.SpecialUnion(m_normalPermSet);
- }
-
- m_serializedPermissionSet = null;
- m_normalPermSet = null;
- m_unrestrictedPermSet = null;
-
- }
-
- [OnSerializing]
- private void OnSerializing(StreamingContext ctx)
- {
-
- if ((ctx.State & ~(StreamingContextStates.Clone|StreamingContextStates.CrossAppDomain)) != 0)
- {
- m_serializedPermissionSet = ToString(); // For v2.x and beyond
- if (m_permSet != null)
- m_permSet.SpecialSplit(ref m_unrestrictedPermSet, ref m_normalPermSet, m_ignoreTypeLoadFailures);
- m_permSetSaved = m_permSet;
- m_permSet = null;
- }
- }
-#endif // !FEATURE_REMOTING
-
-#if FEATURE_REMOTING || _DEBUG
+#if _DEBUG
[OnSerialized]
private void OnSerialized(StreamingContext context)
{
-#if FEATURE_REMOTING
- if ((context.State & ~(StreamingContextStates.Clone|StreamingContextStates.CrossAppDomain)) != 0)
- {
- m_serializedPermissionSet = null;
- m_permSet = m_permSetSaved;
- m_permSetSaved = null;
- m_unrestrictedPermSet = null;
- m_normalPermSet = null;
- }
-#else // !FEATURE_REMOTING
- Contract.Assert(false, "PermissionSet does not support serialization on CoreCLR");
-#endif // !FEATURE_REMOTING
+ Debug.Assert(false, "PermissionSet does not support serialization on CoreCLR");
}
-#endif // FEATURE_REMOTING || _DEBUG
+#endif // _DEBUG
internal PermissionSet()
{
{
Object obj = m_permSet.GetItem(i);
IPermission perm = obj as IPermission;
-#if FEATURE_CAS_POLICY
- ISecurityElementFactory elem = obj as ISecurityElementFactory;
-#endif // FEATURE_CAS_POLICY
+
if (perm != null)
{
m_permSet.SetItem(i, perm.Copy());
}
-#if FEATURE_CAS_POLICY
- else if (elem != null)
- {
- m_permSet.SetItem(i, elem.Copy());
- }
-#endif // FEATURE_CAS_POLICY
}
}
}
Object obj = m_permSet.GetItem( index );
if (obj == null)
return null;
- IPermission perm = obj as IPermission;
- if (perm != null)
- return perm;
-#if FEATURE_CAS_POLICY
- perm = CreatePermission(obj, index);
-#endif // FEATURE_CAS_POLICY
- if (perm == null)
- return null;
- Contract.Assert( PermissionToken.IsTokenProperlyAssigned( perm, PermissionToken.GetToken( perm ) ),
- "PermissionToken was improperly assigned" );
- Contract.Assert( PermissionToken.GetToken( perm ).m_index == index,
- "Assigning permission to incorrect index in tokenbasedset" );
- return perm;
+ return obj as IPermission;
}
internal IPermission GetPermission(PermissionToken permToken)
return GetPermission(PermissionToken.GetToken( perm ));
}
-#if FEATURE_CAS_POLICY
- public IPermission GetPermission(Type permClass)
- {
- return GetPermissionImpl(permClass);
- }
-
- protected virtual IPermission GetPermissionImpl(Type permClass)
- {
- if (permClass == null)
- return null;
-
- return GetPermission(PermissionToken.FindToken(permClass));
- }
-#endif // FEATURE_CAS_POLICY
-
public IPermission SetPermission(IPermission perm)
{
return SetPermissionImpl(perm);
return (IPermission)m_permSet.RemoveItem( index ); // this cast is safe because the call to GetPermission will guarantee it is an IPermission
}
-#if FEATURE_CAS_POLICY
- public IPermission RemovePermission(Type permClass)
- {
- return RemovePermissionImpl(permClass);
- }
-
- protected virtual IPermission RemovePermissionImpl(Type permClass)
- {
- if (permClass == null)
- {
- return null;
- }
-
- PermissionToken permToken = PermissionToken.FindToken(permClass);
- if (permToken == null)
- {
- return null;
- }
-
- return RemovePermission(permToken.m_index);
- }
-#endif // FEATURE_CAS_POLICY
-
// Make this internal soon.
internal void SetUnrestricted(bool unrestricted)
{
m_permSet = null;
}
}
-
+
public bool IsUnrestricted()
{
return m_Unrestricted;
}
-
+
internal enum IsSubsetOfType
{
Normal,
IPermission targetPerm = target.GetPermission(i);
#if _DEBUG
PermissionToken token = (PermissionToken)PermissionToken.s_tokenSet.GetItem( i );
- Contract.Assert(targetPerm == null || (token.m_type & PermissionTokenType.DontKnow) == 0, "Token not properly initialized");
+ Debug.Assert(targetPerm == null || (token.m_type & PermissionTokenType.DontKnow) == 0, "Token not properly initialized");
#endif
if (target.m_Unrestricted)
internal void CheckDecoded( CodeAccessPermission demandedPerm, PermissionToken tokenDemandedPerm )
{
- Contract.Assert( demandedPerm != null, "Expected non-null value" );
+ Debug.Assert( demandedPerm != null, "Expected non-null value" );
if (this.m_allPermissionsDecoded || this.m_permSet == null)
return;
if (tokenDemandedPerm == null)
tokenDemandedPerm = PermissionToken.GetToken( demandedPerm );
- Contract.Assert( tokenDemandedPerm != null, "Unable to find token for demanded permission" );
+ Debug.Assert( tokenDemandedPerm != null, "Unable to find token for demanded permission" );
CheckDecoded( tokenDemandedPerm.m_index );
}
internal void CheckDecoded(PermissionSet demandedSet)
{
- Contract.Assert(demandedSet != null, "Expected non-null value");
+ Debug.Assert(demandedSet != null, "Expected non-null value");
if (this.m_allPermissionsDecoded || this.m_permSet == null)
return;
}
}
-#if FEATURE_CAS_POLICY
- static internal void SafeChildAdd( SecurityElement parent, ISecurityElementFactory child, bool copy )
- {
- if (child == parent)
- return;
- if (child.GetTag().Equals( "IPermission" ) || child.GetTag().Equals( "Permission" ))
- {
- parent.AddChild( child );
- }
- else if (parent.Tag.Equals( child.GetTag() ))
- {
- Contract.Assert( child is SecurityElement, "SecurityElement expected" );
- SecurityElement elChild = (SecurityElement)child;
- Contract.Assert( elChild.InternalChildren != null,
- "Non-permission elements should have children" );
-
- for (int i = 0; i < elChild.InternalChildren.Count; ++i)
- {
- ISecurityElementFactory current = (ISecurityElementFactory)elChild.InternalChildren[i];
- Contract.Assert( !current.GetTag().Equals( parent.Tag ),
- "Illegal to insert a like-typed element" );
- parent.AddChildNoDuplicates( current );
- }
- }
- else
- {
- parent.AddChild( (ISecurityElementFactory)(copy ? child.Copy() : child) );
- }
- }
-#endif // FEATURE_CAS_POLICY
-
internal void InplaceIntersect( PermissionSet other )
{
Exception savedException = null;
{
Object thisObj = this.m_permSet.GetItem( i );
IPermission thisPerm = thisObj as IPermission;
-#if FEATURE_CAS_POLICY
- ISecurityElementFactory thisElem = thisObj as ISecurityElementFactory;
-#endif // FEATURE_CAS_POLICY
Object otherObj = other.m_permSet.GetItem( i );
IPermission otherPerm = otherObj as IPermission;
-#if FEATURE_CAS_POLICY
- ISecurityElementFactory otherElem = otherObj as ISecurityElementFactory;
-#endif // FEATURE_CAS_POLICY
if (thisObj == null && otherObj == null)
continue;
-#if FEATURE_CAS_POLICY
- if (thisElem != null && otherElem != null)
- {
- // If we already have an intersection node, just add another child
- if (thisElem.GetTag().Equals( s_str_PermissionIntersection ) ||
- thisElem.GetTag().Equals( s_str_PermissionUnrestrictedIntersection ))
- {
- Contract.Assert( thisElem is SecurityElement, "SecurityElement expected" );
- SafeChildAdd( (SecurityElement)thisElem, otherElem, true );
- }
- // If either set is unrestricted, intersect the nodes unrestricted
- else
- {
- bool copyOther = true;
- if (this.IsUnrestricted())
- {
- SecurityElement newElemUU = new SecurityElement( s_str_PermissionUnrestrictedUnion );
- newElemUU.AddAttribute( "class", thisElem.Attribute( "class" ) );
- SafeChildAdd( newElemUU, thisElem, false );
- thisElem = newElemUU;
- }
- if (other.IsUnrestricted())
- {
- SecurityElement newElemUU = new SecurityElement( s_str_PermissionUnrestrictedUnion );
- newElemUU.AddAttribute( "class", otherElem.Attribute( "class" ) );
- SafeChildAdd( newElemUU, otherElem, true );
- otherElem = newElemUU;
- copyOther = false;
- }
-
- SecurityElement newElem = new SecurityElement( s_str_PermissionIntersection );
- newElem.AddAttribute( "class", thisElem.Attribute( "class" ) );
-
- SafeChildAdd( newElem, thisElem, false );
- SafeChildAdd( newElem, otherElem, copyOther );
- this.m_permSet.SetItem( i, newElem );
- }
- }
- else
-#endif // FEATURE_CAS_POLICY
if (thisObj == null)
{
// There is no object in <this>, so intersection is empty except for IUnrestrictedPermissions
if (this.IsUnrestricted())
{
-#if FEATURE_CAS_POLICY
- if (otherElem != null)
- {
- SecurityElement newElem = new SecurityElement( s_str_PermissionUnrestrictedIntersection );
- newElem.AddAttribute( "class", otherElem.Attribute( "class" ) );
- SafeChildAdd( newElem, otherElem, true );
- this.m_permSet.SetItem( i, newElem );
- Contract.Assert( PermissionToken.s_tokenSet.GetItem( i ) != null, "PermissionToken should already be assigned" );
- }
- else
-#endif // FEATURE_CAS_POLICY
{
PermissionToken token = (PermissionToken)PermissionToken.s_tokenSet.GetItem( i );
if ((token.m_type & PermissionTokenType.IUnrestricted) != 0)
{
this.m_permSet.SetItem( i, otherPerm.Copy() );
- Contract.Assert( PermissionToken.s_tokenSet.GetItem( i ) != null, "PermissionToken should already be assigned" );
+ Debug.Assert( PermissionToken.s_tokenSet.GetItem( i ) != null, "PermissionToken should already be assigned" );
}
}
}
{
if (other.IsUnrestricted())
{
-#if FEATURE_CAS_POLICY
- if (thisElem != null)
- {
- SecurityElement newElem = new SecurityElement( s_str_PermissionUnrestrictedIntersection );
- newElem.AddAttribute( "class", thisElem.Attribute( "class" ) );
- SafeChildAdd( newElem, thisElem, false );
- this.m_permSet.SetItem( i, newElem );
- }
- else
-#endif // FEATURE_CAS_POLICY
{
PermissionToken token = (PermissionToken)PermissionToken.s_tokenSet.GetItem( i );
if ((token.m_type & PermissionTokenType.IUnrestricted) == 0)
}
else
{
-#if FEATURE_CAS_POLICY
- if (thisElem != null)
- thisPerm = this.CreatePermission(thisElem, i);
- if (otherElem != null)
- otherPerm = other.CreatePermission(otherElem, i);
-#endif // FEATURE_CAS_POLICY
-
try
{
IPermission intersectPerm;
{
Object thisObj = this.m_permSet.GetItem( i );
IPermission thisPerm = thisObj as IPermission;
-#if FEATURE_CAS_POLICY
- ISecurityElementFactory thisElem = thisObj as ISecurityElementFactory;
-#endif // FEATURE_CAS_POLICY
-
Object otherObj = other.m_permSet.GetItem( i );
IPermission otherPerm = otherObj as IPermission;
-#if FEATURE_CAS_POLICY
- ISecurityElementFactory otherElem = otherObj as ISecurityElementFactory;
-#endif // FEATURE_CAS_POLICY
if (thisObj == null && otherObj == null)
continue;
-#if FEATURE_CAS_POLICY
- if (thisElem != null && otherElem != null)
- {
- bool copyOther = true;
- bool copyThis = true;
- SecurityElement newElem = new SecurityElement( s_str_PermissionIntersection );
- newElem.AddAttribute( "class", otherElem.Attribute( "class" ) );
- if (this.IsUnrestricted())
- {
- SecurityElement newElemUU = new SecurityElement( s_str_PermissionUnrestrictedUnion );
- newElemUU.AddAttribute( "class", thisElem.Attribute( "class" ) );
- SafeChildAdd( newElemUU, thisElem, true );
- copyThis = false;
- thisElem = newElemUU;
- }
- if (other.IsUnrestricted())
- {
- SecurityElement newElemUU = new SecurityElement( s_str_PermissionUnrestrictedUnion );
- newElemUU.AddAttribute( "class", otherElem.Attribute( "class" ) );
- SafeChildAdd( newElemUU, otherElem, true );
- copyOther = false;
- otherElem = newElemUU;
- }
-
- SafeChildAdd( newElem, otherElem, copyOther );
- SafeChildAdd( newElem, thisElem, copyThis );
- pset.m_permSet.SetItem( i, newElem );
- }
- else
-#endif // FEATURE_CAS_POLICY
if (thisObj == null)
{
if (this.m_Unrestricted)
{
-#if FEATURE_CAS_POLICY
- if (otherElem != null)
- {
- SecurityElement newElem = new SecurityElement( s_str_PermissionUnrestrictedIntersection );
- newElem.AddAttribute( "class", otherElem.Attribute( "class" ) );
- SafeChildAdd( newElem, otherElem, true );
- pset.m_permSet.SetItem( i, newElem );
- Contract.Assert( PermissionToken.s_tokenSet.GetItem( i ) != null, "PermissionToken should already be assigned" );
- }
- else
-#endif // FEATURE_CAS_POLICY
if (otherPerm != null)
{
PermissionToken token = (PermissionToken)PermissionToken.s_tokenSet.GetItem( i );
if ((token.m_type & PermissionTokenType.IUnrestricted) != 0)
{
pset.m_permSet.SetItem( i, otherPerm.Copy() );
- Contract.Assert( PermissionToken.s_tokenSet.GetItem( i ) != null, "PermissionToken should already be assigned" );
+ Debug.Assert( PermissionToken.s_tokenSet.GetItem( i ) != null, "PermissionToken should already be assigned" );
}
}
}
{
if (other.m_Unrestricted)
{
-#if FEATURE_CAS_POLICY
- if (thisElem != null)
- {
- SecurityElement newElem = new SecurityElement( s_str_PermissionUnrestrictedIntersection );
- newElem.AddAttribute( "class", thisElem.Attribute( "class" ) );
- SafeChildAdd( newElem, thisElem, true );
- pset.m_permSet.SetItem( i, newElem );
- Contract.Assert( PermissionToken.s_tokenSet.GetItem( i ) != null, "PermissionToken should already be assigned" );
- }
- else
-#endif // FEATURE_CAS_POLICY
if (thisPerm != null)
{
PermissionToken token = (PermissionToken)PermissionToken.s_tokenSet.GetItem( i );
if ((token.m_type & PermissionTokenType.IUnrestricted) != 0)
{
pset.m_permSet.SetItem( i, thisPerm.Copy() );
- Contract.Assert( PermissionToken.s_tokenSet.GetItem( i ) != null, "PermissionToken should already be assigned" );
+ Debug.Assert( PermissionToken.s_tokenSet.GetItem( i ) != null, "PermissionToken should already be assigned" );
}
}
}
}
else
{
-#if FEATURE_CAS_POLICY
- if (thisElem != null)
- thisPerm = this.CreatePermission(thisElem, i);
- if (otherElem != null)
- otherPerm = other.CreatePermission(otherElem, i);
-#endif // FEATURE_CAS_POLICY
-
IPermission intersectPerm;
if (thisPerm == null)
intersectPerm = otherPerm;
else
intersectPerm = thisPerm.Intersect( otherPerm );
pset.m_permSet.SetItem( i, intersectPerm );
- Contract.Assert( intersectPerm == null || PermissionToken.s_tokenSet.GetItem( i ) != null, "PermissionToken should already be assigned" );
+ Debug.Assert( intersectPerm == null || PermissionToken.s_tokenSet.GetItem( i ) != null, "PermissionToken should already be assigned" );
}
}
// Quick out conditions, union doesn't change this PermissionSet
if (other == null || other.FastIsEmpty())
return;
-
-
- m_CheckedForNonCas = false;
-
+ m_CheckedForNonCas = false;
-
this.m_Unrestricted = this.m_Unrestricted || other.m_Unrestricted;
if (this.m_Unrestricted)
int maxMax = -1;
if (other.m_permSet != null)
{
- maxMax = other.m_permSet.GetMaxUsedIndex();
+ maxMax = other.m_permSet.GetMaxUsedIndex();
this.CheckSet();
}
// Save exceptions until the end
{
Object thisObj = this.m_permSet.GetItem( i );
IPermission thisPerm = thisObj as IPermission;
-#if FEATURE_CAS_POLICY
- ISecurityElementFactory thisElem = thisObj as ISecurityElementFactory;
-#endif // FEATURE_CAS_POLICY
Object otherObj = other.m_permSet.GetItem( i );
IPermission otherPerm = otherObj as IPermission;
-#if FEATURE_CAS_POLICY
- ISecurityElementFactory otherElem = otherObj as ISecurityElementFactory;
-#endif // FEATURE_CAS_POLICY
if (thisObj == null && otherObj == null)
continue;
-#if FEATURE_CAS_POLICY
- if (thisElem != null && otherElem != null)
- {
- if (thisElem.GetTag().Equals( s_str_PermissionUnion ) ||
- thisElem.GetTag().Equals( s_str_PermissionUnrestrictedUnion ))
- {
- Contract.Assert( thisElem is SecurityElement, "SecurityElement expected" );
- SafeChildAdd( (SecurityElement)thisElem, otherElem, true );
- }
- else
- {
- SecurityElement newElem;
- if (this.IsUnrestricted() || other.IsUnrestricted())
- newElem = new SecurityElement( s_str_PermissionUnrestrictedUnion );
- else
- newElem = new SecurityElement( s_str_PermissionUnion );
- newElem.AddAttribute( "class", thisElem.Attribute( "class" ) );
- SafeChildAdd( newElem, thisElem, false );
- SafeChildAdd( newElem, otherElem, true );
- this.m_permSet.SetItem( i, newElem );
- }
- }
- else
-#endif // FEATURE_CAS_POLICY
if (thisObj == null)
{
-#if FEATURE_CAS_POLICY
- if (otherElem != null)
- {
- this.m_permSet.SetItem( i, otherElem.Copy() );
- }
- else
-#endif // FEATURE_CAS_POLICY
if (otherPerm != null)
{
PermissionToken token = (PermissionToken)PermissionToken.s_tokenSet.GetItem( i );
}
else
{
-#if FEATURE_CAS_POLICY
- if (thisElem != null)
- thisPerm = this.CreatePermission(thisElem, i);
- if (otherElem != null)
- otherPerm = other.CreatePermission(otherElem, i);
-#endif // FEATURE_CAS_POLICY
-
try
{
IPermission unionPerm;
{
Object thisObj = this.m_permSet.GetItem( i );
IPermission thisPerm = thisObj as IPermission;
-#if FEATURE_CAS_POLICY
- ISecurityElementFactory thisElem = thisObj as ISecurityElementFactory;
-#endif // FEATURE_CAS_POLICY
Object otherObj = other.m_permSet.GetItem( i );
IPermission otherPerm = otherObj as IPermission;
-#if FEATURE_CAS_POLICY
- ISecurityElementFactory otherElem = otherObj as ISecurityElementFactory;
-#endif // FEATURE_CAS_POLICY
if (thisObj == null && otherObj == null)
continue;
-#if FEATURE_CAS_POLICY
- if (thisElem != null && otherElem != null)
- {
- SecurityElement newElem;
- if (this.IsUnrestricted() || other.IsUnrestricted())
- newElem = new SecurityElement( s_str_PermissionUnrestrictedUnion );
- else
- newElem = new SecurityElement( s_str_PermissionUnion );
- newElem.AddAttribute( "class", thisElem.Attribute( "class" ) );
- SafeChildAdd( newElem, thisElem, true );
- SafeChildAdd( newElem, otherElem, true );
- pset.m_permSet.SetItem( i, newElem );
- }
- else
-#endif // FEATURE_CAS_POLICY
if (thisObj == null)
{
-#if FEATURE_CAS_POLICY
- if (otherElem != null)
- {
- pset.m_permSet.SetItem( i, otherElem.Copy() );
- Contract.Assert( PermissionToken.s_tokenSet.GetItem( i ) != null, "PermissionToken should already be assigned" );
- }
- else
-#endif // FEATURE_CAS_POLICY
if (otherPerm != null)
{
PermissionToken token = (PermissionToken)PermissionToken.s_tokenSet.GetItem( i );
if (((token.m_type & PermissionTokenType.IUnrestricted) == 0) || !pset.m_Unrestricted)
{
pset.m_permSet.SetItem( i, otherPerm.Copy() );
- Contract.Assert( PermissionToken.s_tokenSet.GetItem( i ) != null, "PermissionToken should already be assigned" );
+ Debug.Assert( PermissionToken.s_tokenSet.GetItem( i ) != null, "PermissionToken should already be assigned" );
}
}
}
else if (otherObj == null)
{
-#if FEATURE_CAS_POLICY
- if (thisElem != null)
- {
- pset.m_permSet.SetItem( i, thisElem.Copy() );
- }
- else
-#endif // FEATURE_CAS_POLICY
if (thisPerm != null)
{
PermissionToken token = (PermissionToken)PermissionToken.s_tokenSet.GetItem( i );
if (((token.m_type & PermissionTokenType.IUnrestricted) == 0) || !pset.m_Unrestricted)
{
pset.m_permSet.SetItem( i, thisPerm.Copy() );
- Contract.Assert( PermissionToken.s_tokenSet.GetItem( i ) != null, "PermissionToken should already be assigned" );
+ Debug.Assert( PermissionToken.s_tokenSet.GetItem( i ) != null, "PermissionToken should already be assigned" );
}
}
}
else
{
-#if FEATURE_CAS_POLICY
- if (thisElem != null)
- thisPerm = this.CreatePermission(thisElem, i);
- if (otherElem != null)
- otherPerm = other.CreatePermission(otherElem, i);
-#endif // FEATURE_CAS_POLICY
-
IPermission unionPerm;
if(thisPerm == null)
unionPerm = otherPerm;
else
unionPerm = thisPerm.Union( otherPerm );
pset.m_permSet.SetItem( i, unionPerm );
- Contract.Assert( unionPerm == null || PermissionToken.s_tokenSet.GetItem( i ) != null, "PermissionToken should already be assigned" );
+ Debug.Assert( unionPerm == null || PermissionToken.s_tokenSet.GetItem( i ) != null, "PermissionToken should already be assigned" );
}
}
-
+
return pset;
}
// Mark this method as requiring a security object on the caller's frame
// so the caller won't be inlined (which would mess up stack crawling).
- [System.Security.SecuritySafeCritical] // auto-generated
[DynamicSecurityMethodAttribute()]
[MethodImplAttribute(MethodImplOptions.NoInlining)] // Methods containing StackCrawlMark local var has to be marked non-inlineable
public void Demand()
}
}
- [System.Security.SecurityCritical] // auto-generated
internal void DemandNonCAS()
{
ContainsNonCodeAccessPermissions();
// Metadata for this method should be flaged with REQ_SQ so that
// EE can allocate space on the stack frame for FrameSecurityDescriptor
- [System.Security.SecuritySafeCritical] // auto-generated
[DynamicSecurityMethodAttribute()]
[MethodImplAttribute(MethodImplOptions.NoInlining)] // Methods containing StackCrawlMark local var has to be marked non-inlineable
public void Assert()
// Metadata for this method should be flaged with REQ_SQ so that
// EE can allocate space on the stack frame for FrameSecurityDescriptor
- [System.Security.SecuritySafeCritical] // auto-generated
[DynamicSecurityMethodAttribute()]
[MethodImplAttribute(MethodImplOptions.NoInlining)] // Methods containing StackCrawlMark local var has to be marked non-inlineable
[Obsolete("Deny is obsolete and will be removed in a future release of the .NET Framework. See http://go.microsoft.com/fwlink/?LinkID=155570 for more information.")]
// Metadata for this method should be flaged with REQ_SQ so that
// EE can allocate space on the stack frame for FrameSecurityDescriptor
- [System.Security.SecuritySafeCritical] // auto-generated
[DynamicSecurityMethodAttribute()]
[MethodImplAttribute(MethodImplOptions.NoInlining)] // Methods containing StackCrawlMark local var has to be marked non-inlineable
public void PermitOnly()
{
// Explicitly make a new PermissionSet, rather than copying, since we may have a
// ReadOnlyPermissionSet which cannot have identity permissions removed from it in a true copy.
- PermissionSet copy = new PermissionSet(this);
-
- // There's no easy way to distinguish an identity permission from any other CodeAccessPermission,
- // so remove them directly.
-#if FEATURE_CAS_POLICY
- copy.RemovePermission(typeof(GacIdentityPermission));
-#if FEATURE_X509
- copy.RemovePermission(typeof(PublisherIdentityPermission));
-#endif
- copy.RemovePermission(typeof(StrongNameIdentityPermission));
- copy.RemovePermission(typeof(UrlIdentityPermission));
- copy.RemovePermission(typeof(ZoneIdentityPermission));
-#endif // FEATURE_CAS_POLICY
-
- return copy;
+ return new PermissionSet(this);
}
public IEnumerator GetEnumerator()
return new PermissionSetEnumeratorInternal(this);
}
-#if FEATURE_CAS_POLICY
- public override String ToString()
- {
- return ToXml().ToString();
- }
-#endif // FEATURE_CAS_POLICY
-
private void NormalizePermissionSet()
{
// This function guarantees that all the permissions are placed at
{
Object obj = this.m_permSet.GetItem(i);
IPermission perm = obj as IPermission;
-#if FEATURE_CAS_POLICY
- ISecurityElementFactory elem = obj as ISecurityElementFactory;
-
- if (elem != null)
- perm = CreatePerm( elem );
-#endif // FEATURE_CAS_POLICY
if (perm != null)
permSetTemp.SetPermission( perm );
}
this.m_permSet = permSetTemp.m_permSet;
}
-#if FEATURE_CAS_POLICY
- private bool DecodeXml(byte[] data, HostProtectionResource fullTrustOnlyResources, HostProtectionResource inaccessibleResources )
- {
- if (data != null && data.Length > 0)
- {
- FromXml( new Parser( data, Tokenizer.ByteTokenEncoding.UnicodeTokens ).GetTopElement() );
- }
-
- FilterHostProtectionPermissions(fullTrustOnlyResources, inaccessibleResources);
-
- // We call this method from unmanaged to code a set we are going to use declaratively. In
- // this case, all the lazy evaluation for partial policy resolution is wasted since we'll
- // need to decode all of these shortly to make the demand for whatever. Therefore, we
- // pay that price now so that we can calculate whether all the permissions in the set
- // implement the IUnrestrictedPermission interface (the common case) for use in some
- // unmanaged optimizations.
-
- DecodeAllPermissions();
-
- return true;
- }
-#endif // FEATURE_CAS_POLICY
-
private void DecodeAllPermissions()
{
if (m_permSet == null)
HostProtectionPermission newHpp = (HostProtectionPermission)hpp.Intersect(new HostProtectionPermission(fullTrustOnly));
if (newHpp == null)
{
-#if FEATURE_CAS_POLICY
- RemovePermission(typeof(HostProtectionPermission));
-#else // !FEATURE_CAS_POLICY
RemovePermission(HostProtectionPermission.GetTokenIndex());
-#endif // FEATURE_CAS_POLICY
}
else if (newHpp.Resources != hpp.Resources)
{
}
}
-#if FEATURE_CAS_POLICY
- public virtual void FromXml( SecurityElement et )
- {
- FromXml( et, false, false );
- }
-
- internal static bool IsPermissionTag( String tag, bool allowInternalOnly )
- {
- if (tag.Equals( s_str_Permission ) ||
- tag.Equals( s_str_IPermission ))
- {
- return true;
- }
-
- if (allowInternalOnly &&
- (tag.Equals( s_str_PermissionUnion ) ||
- tag.Equals( s_str_PermissionIntersection ) ||
- tag.Equals( s_str_PermissionUnrestrictedIntersection ) ||
- tag.Equals( s_str_PermissionUnrestrictedUnion)))
- {
- return true;
- }
-
- return false;
- }
-
- internal virtual void FromXml( SecurityElement et, bool allowInternalOnly, bool ignoreTypeLoadFailures )
- {
- if (et == null)
- throw new ArgumentNullException(nameof(et));
-
- if (!et.Tag.Equals(s_str_PermissionSet))
- throw new ArgumentException(String.Format( null, Environment.GetResourceString( "Argument_InvalidXMLElement" ), nameof(PermissionSet), this.GetType().FullName) );
- Contract.EndContractBlock();
-
- Reset();
- m_ignoreTypeLoadFailures = ignoreTypeLoadFailures;
- m_allPermissionsDecoded = false;
- m_Unrestricted = XMLUtil.IsUnrestricted( et );
-
- if (et.InternalChildren != null)
- {
- int childCount = et.InternalChildren.Count;
- for (int i = 0; i < childCount; ++i)
- {
- SecurityElement elem = (SecurityElement)et.Children[i];
-
- if (IsPermissionTag( elem.Tag, allowInternalOnly ))
- {
- String className = elem.Attribute( "class" );
-
- PermissionToken token;
- Object objectToInsert;
-
- if (className != null)
- {
- token = PermissionToken.GetToken( className );
- if (token == null)
- {
- objectToInsert = CreatePerm( elem );
-#if _DEBUG
- PermissionToken tokenDebug = PermissionToken.GetToken( (IPermission)objectToInsert );
- Contract.Assert( tokenDebug != null && (tokenDebug.m_type & PermissionTokenType.BuiltIn) != 0, "This should only be called for built-ins" );
-#endif
- if (objectToInsert != null)
- {
- Contract.Assert( objectToInsert.GetType().Module.Assembly == System.Reflection.Assembly.GetExecutingAssembly(),
- "PermissionToken.GetToken returned null for non-mscorlib permission" );
- token = PermissionToken.GetToken( (IPermission)objectToInsert );
- Contract.Assert( (token.m_type & PermissionTokenType.DontKnow) == 0, "We should always know the permission type when getting a token from an instance" );
- }
- }
- else
- {
- objectToInsert = elem;
- }
- }
- else
- {
- IPermission ip = CreatePerm( elem );
- if (ip == null)
- {
- token = null;
- objectToInsert = null;
- }
- else
- {
- token = PermissionToken.GetToken( ip );
- Contract.Assert( PermissionToken.IsTokenProperlyAssigned( ip, token ),
- "PermissionToken was improperly assigned" );
- objectToInsert = ip;
- }
- }
-
- if (token != null && objectToInsert != null)
- {
- if (m_permSet == null)
- m_permSet = new TokenBasedSet();
-
- if (this.m_permSet.GetItem( token.m_index ) != null)
- {
- // If there is already something in that slot, let's union them
- // together.
-
- IPermission permInSlot;
-
- if (this.m_permSet.GetItem( token.m_index ) is IPermission)
- permInSlot = (IPermission)this.m_permSet.GetItem( token.m_index );
- else
- permInSlot = CreatePerm( (SecurityElement)this.m_permSet.GetItem( token.m_index ) );
-
- if (objectToInsert is IPermission)
- objectToInsert = ((IPermission)objectToInsert).Union( permInSlot );
- else
- objectToInsert = CreatePerm( (SecurityElement)objectToInsert ).Union( permInSlot );
- }
-
- if(m_Unrestricted && objectToInsert is IPermission)
- objectToInsert = null;
-
- this.m_permSet.SetItem( token.m_index, objectToInsert );
- }
- }
- }
- }
- }
-
- internal virtual void FromXml( SecurityDocument doc, int position, bool allowInternalOnly )
- {
- if (doc == null)
- throw new ArgumentNullException(nameof(doc));
- Contract.EndContractBlock();
-
- if (!doc.GetTagForElement( position ).Equals(s_str_PermissionSet))
- throw new ArgumentException(String.Format( null, Environment.GetResourceString( "Argument_InvalidXMLElement" ), nameof(PermissionSet), this.GetType().FullName) );
-
- Reset();
- m_allPermissionsDecoded = false;
- Exception savedException = null;
- String strUnrestricted = doc.GetAttributeForElement( position, "Unrestricted" );
- if (strUnrestricted != null)
- m_Unrestricted = strUnrestricted.Equals( "True" ) || strUnrestricted.Equals( "true" ) || strUnrestricted.Equals( "TRUE" );
- else
- m_Unrestricted = false;
-
- ArrayList childrenIndices = doc.GetChildrenPositionForElement( position );
- int childCount = childrenIndices.Count;
- for (int i = 0; i < childCount; ++i)
- {
- int childIndex = (int)childrenIndices[i];
- if (IsPermissionTag( doc.GetTagForElement( childIndex ), allowInternalOnly ))
- {
- try
- {
- String className = doc.GetAttributeForElement( childIndex, "class" );
-
- PermissionToken token;
- Object objectToInsert;
-
- if (className != null)
- {
- token = PermissionToken.GetToken( className );
- if (token == null)
- {
- objectToInsert = CreatePerm( doc.GetElement( childIndex, true ) );
-
- if (objectToInsert != null)
- {
-#if _DEBUG
- PermissionToken tokenDebug = PermissionToken.GetToken( (IPermission)objectToInsert );
- Contract.Assert((tokenDebug != null), "PermissionToken.GetToken returned null ");
- Contract.Assert( (tokenDebug.m_type & PermissionTokenType.BuiltIn) != 0, "This should only be called for built-ins" );
-#endif
- Contract.Assert( objectToInsert.GetType().Module.Assembly == System.Reflection.Assembly.GetExecutingAssembly(),
- "PermissionToken.GetToken returned null for non-mscorlib permission" );
- token = PermissionToken.GetToken( (IPermission)objectToInsert );
- Contract.Assert((token != null), "PermissionToken.GetToken returned null ");
- Contract.Assert( (token.m_type & PermissionTokenType.DontKnow) == 0, "We should always know the permission type when getting a token from an instance" );
- }
- }
- else
- {
- objectToInsert = ((ISecurityElementFactory)new SecurityDocumentElement(doc, childIndex)).CreateSecurityElement();
- }
- }
- else
- {
- IPermission ip = CreatePerm( doc.GetElement( childIndex, true ) );
- if (ip == null)
- {
- token = null;
- objectToInsert = null;
- }
- else
- {
- token = PermissionToken.GetToken( ip );
- Contract.Assert( PermissionToken.IsTokenProperlyAssigned( ip, token ),
- "PermissionToken was improperly assigned" );
- objectToInsert = ip;
- }
- }
-
- if (token != null && objectToInsert != null)
- {
- if (m_permSet == null)
- m_permSet = new TokenBasedSet();
-
- IPermission permInSlot = null;
- if (this.m_permSet.GetItem( token.m_index ) != null)
- {
- // If there is already something in that slot, let's union them
- // together.
-
- if (this.m_permSet.GetItem( token.m_index ) is IPermission)
- permInSlot = (IPermission)this.m_permSet.GetItem( token.m_index );
- else
- permInSlot = CreatePerm( this.m_permSet.GetItem( token.m_index ) );
- }
-
- if (permInSlot != null)
- {
- if (objectToInsert is IPermission)
- objectToInsert = permInSlot.Union((IPermission)objectToInsert);
- else
- objectToInsert = permInSlot.Union(CreatePerm( objectToInsert ));
- }
-
- if(m_Unrestricted && objectToInsert is IPermission)
- objectToInsert = null;
-
- this.m_permSet.SetItem( token.m_index, objectToInsert );
- }
- }
- catch (Exception e)
- {
-#if _DEBUG
- if (debug)
- DEBUG_WRITE( "error while decoding permission set =\n" + e.ToString() );
-#endif
- if (savedException == null)
- savedException = e;
-
- }
- }
- }
-
- if (savedException != null)
- throw savedException;
-
- }
-
- private IPermission CreatePerm(Object obj)
- {
- return CreatePerm(obj, m_ignoreTypeLoadFailures);
- }
-
- internal static IPermission CreatePerm(Object obj, bool ignoreTypeLoadFailures)
- {
- SecurityElement el = obj as SecurityElement;
- ISecurityElementFactory isf = obj as ISecurityElementFactory;
- if (el == null && isf != null)
- {
- el = isf.CreateSecurityElement();
- }
-
- IEnumerator enumerator;
- IPermission finalPerm = null;
-
- switch (el.Tag)
- {
- case s_str_PermissionUnion:
- enumerator = el.Children.GetEnumerator();
- while (enumerator.MoveNext())
- {
- IPermission tempPerm = CreatePerm( (SecurityElement)enumerator.Current, ignoreTypeLoadFailures);
-
- if (finalPerm != null)
- finalPerm = finalPerm.Union( tempPerm );
- else
- finalPerm = tempPerm;
- }
- break;
-
- case s_str_PermissionIntersection:
- enumerator = el.Children.GetEnumerator();
- while (enumerator.MoveNext())
- {
- IPermission tempPerm = CreatePerm( (SecurityElement)enumerator.Current, ignoreTypeLoadFailures);
-
- if (finalPerm != null)
- finalPerm = finalPerm.Intersect( tempPerm );
- else
- finalPerm = tempPerm;
-
- if (finalPerm == null)
- return null;
- }
- break;
-
- case s_str_PermissionUnrestrictedUnion:
- enumerator = el.Children.GetEnumerator();
- bool first = true;
- while (enumerator.MoveNext())
- {
- IPermission tempPerm = CreatePerm( (SecurityElement)enumerator.Current, ignoreTypeLoadFailures );
-
- if (tempPerm == null)
- continue;
-
- PermissionToken token = PermissionToken.GetToken( tempPerm );
-
- Contract.Assert( (token.m_type & PermissionTokenType.DontKnow) == 0, "We should know the permission type already" );
-
- if ((token.m_type & PermissionTokenType.IUnrestricted) != 0)
- {
- finalPerm = XMLUtil.CreatePermission( GetPermissionElement((SecurityElement)enumerator.Current), PermissionState.Unrestricted, ignoreTypeLoadFailures );
- first = false;
- break;
- }
- else
- {
- Contract.Assert( tempPerm != null, "We should only come here if we have a real permission" );
- if (first)
- finalPerm = tempPerm;
- else
- finalPerm = tempPerm.Union( finalPerm );
- first = false;
- }
- }
- break;
-
- case s_str_PermissionUnrestrictedIntersection:
- enumerator = el.Children.GetEnumerator();
- while (enumerator.MoveNext())
- {
- IPermission tempPerm = CreatePerm( (SecurityElement)enumerator.Current, ignoreTypeLoadFailures );
-
- if (tempPerm == null)
- return null;
-
- PermissionToken token = PermissionToken.GetToken( tempPerm );
-
- Contract.Assert( (token.m_type & PermissionTokenType.DontKnow) == 0, "We should know the permission type already" );
-
- if ((token.m_type & PermissionTokenType.IUnrestricted) != 0)
- {
- if (finalPerm != null)
- finalPerm = tempPerm.Intersect( finalPerm );
- else
- finalPerm = tempPerm;
- }
- else
- {
- finalPerm = null;
- }
-
- if (finalPerm == null)
- return null;
- }
- break;
-
- case "IPermission":
- case "Permission":
- finalPerm = el.ToPermission(ignoreTypeLoadFailures);
- break;
-
- default:
- Contract.Assert( false, "Unrecognized case found during permission creation" );
- break;
- }
-
- return finalPerm;
- }
-
- internal IPermission CreatePermission(Object obj, int index)
- {
- IPermission perm = CreatePerm(obj);
- if(perm == null)
- return null;
-
- // See if the PermissionSet.m_Unrestricted flag covers this permission
- if(m_Unrestricted)
- perm = null;
-
- // Store the decoded result
- CheckSet();
- m_permSet.SetItem(index, perm);
-
- // Do some consistency checks
- Contract.Assert(perm == null || PermissionToken.IsTokenProperlyAssigned( perm, PermissionToken.GetToken( perm ) ), "PermissionToken was improperly assigned");
- if (perm != null)
- {
- PermissionToken permToken = PermissionToken.GetToken(perm);
- if (permToken != null && permToken.m_index != index)
- throw new ArgumentException( Environment.GetResourceString( "Argument_UnableToGeneratePermissionSet"));
- }
-
-
- return perm;
- }
-
- private static SecurityElement GetPermissionElement( SecurityElement el )
- {
- switch (el.Tag)
- {
- case "IPermission":
- case "Permission":
- return el;
- }
- IEnumerator enumerator = el.Children.GetEnumerator();
- if (enumerator.MoveNext())
- return GetPermissionElement((SecurityElement)enumerator.Current);
- Contract.Assert( false, "No Permission or IPermission tag found" );
- return null;
- }
-
- internal static SecurityElement CreateEmptyPermissionSetXml()
- {
-
- SecurityElement elTrunk = new SecurityElement("PermissionSet");
- elTrunk.AddAttribute( "class", "System.Security.PermissionSet" );
-
- elTrunk.AddAttribute( "version", "1" );
- return elTrunk;
-
- }
- // internal helper which takes in the hardcoded permission name to avoid lookup at runtime
- // can be called from classes that derive from PermissionSet
- internal SecurityElement ToXml(String permName)
- {
- SecurityElement elTrunk = new SecurityElement("PermissionSet");
- elTrunk.AddAttribute( "class", permName );
-
- elTrunk.AddAttribute( "version", "1" );
-
- PermissionSetEnumeratorInternal enumerator = new PermissionSetEnumeratorInternal(this);
-
- if (m_Unrestricted)
- {
- elTrunk.AddAttribute(s_str_Unrestricted, "true" );
- }
-
- while (enumerator.MoveNext())
- {
- IPermission perm = (IPermission)enumerator.Current;
-
- if (!m_Unrestricted)
- elTrunk.AddChild( perm.ToXml() );
- }
- return elTrunk;
- }
-
- internal SecurityElement InternalToXml()
- {
- SecurityElement elTrunk = new SecurityElement("PermissionSet");
- elTrunk.AddAttribute( "class", this.GetType().FullName);
- elTrunk.AddAttribute( "version", "1" );
-
- if (m_Unrestricted)
- {
- elTrunk.AddAttribute(s_str_Unrestricted, "true" );
- }
-
- if (this.m_permSet != null)
- {
- int maxIndex = this.m_permSet.GetMaxUsedIndex();
-
- for (int i = m_permSet.GetStartingIndex(); i <= maxIndex; ++i)
- {
- Object obj = this.m_permSet.GetItem( i );
- if (obj != null)
- {
- if (obj is IPermission)
- {
- if (!m_Unrestricted)
- elTrunk.AddChild( ((IPermission)obj).ToXml() );
- }
- else
- {
- elTrunk.AddChild( (SecurityElement)obj );
- }
- }
-
- }
- }
- return elTrunk ;
- }
-
- public virtual SecurityElement ToXml()
- {
- // If you hit this assert then most likely you are trying to change the name of this class.
- // This is ok as long as you change the hard coded string above and change the assert below.
- Contract.Assert( this.GetType().FullName.Equals( "System.Security.PermissionSet" ), "Class name changed! Was: System.Security.PermissionSet Should be:" + this.GetType().FullName);
-
- return ToXml("System.Security.PermissionSet");
- }
-#endif // FEATURE_CAS_POLICY
-
-#if FEATURE_CAS_POLICY && FEATURE_SERIALIZATION
- internal
- byte[] EncodeXml()
- {
- MemoryStream ms = new MemoryStream();
- BinaryWriter writer = new BinaryWriter( ms, Encoding.Unicode );
- writer.Write( this.ToXml().ToString() );
- writer.Flush();
-
- // The BinaryWriter is going to place
- // two bytes indicating a Unicode stream.
- // We want to chop those off before returning
- // the bytes out.
-
- ms.Position = 2;
- int countBytes = (int)ms.Length - 2;
- byte[] retval = new byte[countBytes];
- ms.Read( retval, 0, retval.Length );
- return retval;
- }
-
- /// <internalonly/>
- [Obsolete("This method is obsolete and shoud no longer be used.")]
- public static byte[] ConvertPermissionSet(String inFormat, byte[] inData, String outFormat)
- {
- // Since this method has shipped and is public, we cannot remove it without being a breaking change
- throw new NotImplementedException();
- }
-#endif
-
// Determines whether the permission set contains any non-code access
// security permissions.
- #if FEATURE_CORECLR
- [System.Security.SecurityCritical] // auto-generated
- #endif
public bool ContainsNonCodeAccessPermissions()
{
if (m_CheckedForNonCas)
return pset;
}
-#if FEATURE_CAS_POLICY
- private const String s_str_PermissionSet = "PermissionSet";
- private const String s_str_Permission = "Permission";
- private const String s_str_IPermission = "IPermission";
- private const String s_str_Unrestricted = "Unrestricted";
- private const String s_str_PermissionUnion = "PermissionUnion";
- private const String s_str_PermissionIntersection = "PermissionIntersection";
- private const String s_str_PermissionUnrestrictedUnion = "PermissionUnrestrictedUnion";
- private const String s_str_PermissionUnrestrictedIntersection = "PermissionUnrestrictedIntersection";
-
- // This method supports v1.x security attrbutes only - we'll require legacy CAS policy mode
- // to be enabled for that to work.
-#pragma warning disable 618
- // Internal routine used to setup a special security context
- // for creating and manipulated security custom attributes
- // that we use when the Runtime is hosted.
- [System.Security.SecurityCritical] // auto-generated
- private static void SetupSecurity()
- {
- PolicyLevel level = PolicyLevel.CreateAppDomainLevel();
-
- CodeGroup rootGroup = new UnionCodeGroup( new AllMembershipCondition(), level.GetNamedPermissionSet( "Execution" ) );
-
- StrongNamePublicKeyBlob microsoftBlob = new StrongNamePublicKeyBlob( AssemblyRef.MicrosoftPublicKeyFull );
- CodeGroup microsoftGroup = new UnionCodeGroup( new StrongNameMembershipCondition( microsoftBlob, null, null ), level.GetNamedPermissionSet( "FullTrust" ) );
-
- StrongNamePublicKeyBlob ecmaBlob = new StrongNamePublicKeyBlob( AssemblyRef.EcmaPublicKeyFull );
- CodeGroup ecmaGroup = new UnionCodeGroup( new StrongNameMembershipCondition( ecmaBlob, null, null ), level.GetNamedPermissionSet( "FullTrust" ) );
-
- CodeGroup gacGroup = new UnionCodeGroup( new GacMembershipCondition(), level.GetNamedPermissionSet( "FullTrust" ) );
-
- rootGroup.AddChild( microsoftGroup );
- rootGroup.AddChild( ecmaGroup );
- rootGroup.AddChild( gacGroup );
-
- level.RootCodeGroup = rootGroup;
-
- try
- {
- AppDomain.CurrentDomain.SetAppDomainPolicy( level );
- }
- catch (PolicyException)
- {
- }
- }
-#endif
-#pragma warning restore 618
-
// Internal routine used by CreateSerialized to add a permission to the set
private static void MergePermission(IPermission perm, bool separateCasFromNonCas, ref PermissionSet casPset, ref PermissionSet nonCasPset)
{
- Contract.Assert(casPset == null || !casPset.IsReadOnly);
- Contract.Assert(nonCasPset == null || !nonCasPset.IsReadOnly);
+ Debug.Assert(casPset == null || !casPset.IsReadOnly);
+ Debug.Assert(nonCasPset == null || !nonCasPset.IsReadOnly);
if (perm == null)
return;
}
// Converts an array of SecurityAttributes to a PermissionSet
- #if FEATURE_CORECLR
- [System.Security.SecurityCritical] // auto-generated
- #endif
private static byte[] CreateSerialized(Object[] attrs,
bool serialize,
ref byte[] nonCasBlob,
for (int i = 0; i < attrs.Length; i++)
{
#pragma warning disable 618
- Contract.Assert(i == 0 || ((SecurityAttribute)attrs[i]).m_action == ((SecurityAttribute)attrs[i - 1]).m_action, "Mixed SecurityActions");
+ Debug.Assert(i == 0 || ((SecurityAttribute)attrs[i]).m_action == ((SecurityAttribute)attrs[i - 1]).m_action, "Mixed SecurityActions");
#pragma warning restore 618
if (attrs[i] is PermissionSetAttribute)
{
MergePermission(perm, serialize, ref casPset, ref nonCasPset);
}
}
- Contract.Assert(serialize || nonCasPset == null, "We shouldn't separate nonCAS permissions unless fSerialize is true");
+ Debug.Assert(serialize || nonCasPset == null, "We shouldn't separate nonCAS permissions unless fSerialize is true");
//
// Filter HostProtection permission. In the VM, some optimizations are done based upon these
nonCasPset = null;
}
- // Serialize the set(s).
- byte[] casBlob = null;
- nonCasBlob = null;
-#if FEATURE_CAS_POLICY
- if(serialize)
- {
- if(casPset != null)
- casBlob = casPset.EncodeXml();
- if(nonCasPset != null)
- nonCasBlob = nonCasPset.EncodeXml();
- }
-#else // FEATURE_CAS_POLICY
- Contract.Assert(!serialize, "Cannot serialize permission sets on CoreCLR");
-#endif // FEATURE_CAS_POLICY
-
- return casBlob;
+ Debug.Assert(!serialize, "Cannot serialize permission sets on CoreCLR");
+ return null;
}
#if FEATURE_SERIALIZATION
}
#endif
- [System.Security.SecuritySafeCritical] // auto-generated
[MethodImplAttribute(MethodImplOptions.NoInlining)] // Methods containing StackCrawlMark local var has to be marked non-inlineable
public static void RevertAssert()
{
internal static PermissionSet RemoveRefusedPermissionSet(PermissionSet assertSet, PermissionSet refusedSet, out bool bFailedToCompress)
{
- Contract.Assert((assertSet == null || !assertSet.IsUnrestricted()), "Cannot be unrestricted here");
+ Debug.Assert((assertSet == null || !assertSet.IsUnrestricted()), "Cannot be unrestricted here");
PermissionSet retPs = null;
bFailedToCompress = false;
if (assertSet == null)
internal static void RemoveAssertedPermissionSet(PermissionSet demandSet, PermissionSet assertSet, out PermissionSet alteredDemandSet)
{
- Contract.Assert(!assertSet.IsUnrestricted(), "Cannot call this function if assertSet is unrestricted");
+ Debug.Assert(!assertSet.IsUnrestricted(), "Cannot call this function if assertSet is unrestricted");
alteredDemandSet = null;
PermissionSetEnumeratorInternal enumerator = new PermissionSetEnumeratorInternal(demandSet);
enm.Current = perm;
return true;
}
-
-#if FEATURE_CAS_POLICY
- SecurityElement elem = obj as SecurityElement;
-
- if (elem != null)
- {
- perm = m_permSet.CreatePermission(elem, enm.Index);
- if (perm != null)
- {
- enm.Current = perm;
- return true;
- }
- }
-#endif // FEATURE_CAS_POLICY
}
return false;
}
using System.Security;
using System.Security.Permissions;
using System.Runtime.InteropServices;
+ using System.Diagnostics;
using System.Diagnostics.Contracts;
private PermissionToken ZoneToken
{
- [System.Security.SecurityCritical] // auto-generated
get
{
if (s_zoneToken == null)
}
private PermissionToken UrlToken
{
- [System.Security.SecurityCritical] // auto-generated
get
{
if (s_urlToken == null)
return s_urlToken;
}
}
- [System.Security.SecurityCritical] // auto-generated
internal bool Update(PermissionSetTriple psTriple, out PermissionSetTriple retTriple)
{
retTriple = null;
return false;
}
- [System.Security.SecurityCritical] // auto-generated
internal PermissionSetTriple UpdateAssert(PermissionSet in_a)
{
PermissionSetTriple retTriple = null;
if (in_a != null)
{
- Contract.Assert((!in_a.IsUnrestricted() || RefusedSet == null), "Cannot be unrestricted or refused must be null");
+ Debug.Assert((!in_a.IsUnrestricted() || RefusedSet == null), "Cannot be unrestricted or refused must be null");
// if we're already asserting in_a, nothing to do
if (in_a.IsSubsetOf(AssertSet))
return null;
}
return retTriple;
}
- [System.Security.SecurityCritical] // auto-generated
internal void UpdateGrant(PermissionSet in_g, out ZoneIdentityPermission z,out UrlIdentityPermission u)
{
z = null;
}
}
- [System.Security.SecurityCritical] // auto-generated
internal void UpdateGrant(PermissionSet in_g)
{
if (in_g != null)
}
- [System.Security.SecurityCritical] // auto-generated
static bool CheckAssert(PermissionSet pSet, CodeAccessPermission demand, PermissionToken permToken)
{
if (pSet != null)
return SecurityRuntime.StackContinue;
}
- [System.Security.SecurityCritical] // auto-generated
static bool CheckAssert(PermissionSet assertPset, PermissionSet demandSet, out PermissionSet newDemandSet)
{
newDemandSet = null;
}
- [System.Security.SecurityCritical] // auto-generated
internal bool CheckDemand(CodeAccessPermission demand, PermissionToken permToken, RuntimeMethodHandleInternal rmh)
{
if (CheckAssert(AssertSet, demand, permToken) == SecurityRuntime.StackHalt)
return SecurityRuntime.StackContinue;
}
- [System.Security.SecurityCritical] // auto-generated
internal bool CheckSetDemand(PermissionSet demandSet , out PermissionSet alteredDemandset, RuntimeMethodHandleInternal rmh)
{
alteredDemandset = null;
}
- [System.Security.SecurityCritical] // auto-generated
internal bool CheckDemandNoThrow(CodeAccessPermission demand, PermissionToken permToken)
{
- Contract.Assert(AssertSet == null, "AssertSet not null");
+ Debug.Assert(AssertSet == null, "AssertSet not null");
#pragma warning disable 618
return CodeAccessSecurityEngine.CheckHelper(GrantSet, RefusedSet, demand, permToken, RuntimeMethodHandleInternal.EmptyHandle, null, SecurityAction.Demand, false);
#pragma warning restore 618
}
- [System.Security.SecurityCritical] // auto-generated
internal bool CheckSetDemandNoThrow(PermissionSet demandSet)
{
- Contract.Assert(AssertSet == null, "AssertSet not null");
+ Debug.Assert(AssertSet == null, "AssertSet not null");
#pragma warning disable 618
return CodeAccessSecurityEngine.CheckSetHelper(GrantSet, RefusedSet, demandSet, RuntimeMethodHandleInternal.EmptyHandle, null, SecurityAction.Demand, false);
/// If the triple asserts for one of the bits in the flags, it is zeroed out.
/// </remarks>
/// <param name="flags">set of flags to check (See PermissionType)</param>
- [System.Security.SecurityCritical] // auto-generated
internal bool CheckFlags(ref int flags)
{
if (AssertSet != null)
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
-namespace System.Security {
+namespace System.Security
+{
using System;
using System.Security.Util;
using System.Security.Permissions;
using System.Threading;
using System.Globalization;
using System.Runtime.CompilerServices;
+ using System.Diagnostics;
using System.Diagnostics.Contracts;
[Flags]
_info = CultureInfo.InvariantCulture.TextInfo;
}
- [System.Security.SecuritySafeCritical] // auto-generated
public int Compare(Object a, Object b)
{
String strA = a as String;
internal sealed class PermissionToken : ISecurityEncodable
{
private static readonly PermissionTokenFactory s_theTokenFactory;
-#if FEATURE_CAS_POLICY
- private static volatile ReflectionPermission s_reflectPerm = null;
-#endif // FEATURE_CAS_POLICY
-
private const string c_mscorlibName = System.CoreLib.Name;
internal int m_index;
internal volatile PermissionTokenType m_type;
-#if FEATURE_CAS_POLICY
- internal String m_strTypeName;
-#endif // FEATURE_CAS_POLICY
static internal TokenBasedSet s_tokenSet = new TokenBasedSet();
internal static bool IsMscorlibClassName (string className) {
- Contract.Assert( c_mscorlibName == ((RuntimeAssembly)Assembly.GetExecutingAssembly()).GetSimpleName(),
+ Debug.Assert( c_mscorlibName == ((RuntimeAssembly)Assembly.GetExecutingAssembly()).GetSimpleName(),
System.CoreLib.Name+" name mismatch" );
// If the class name does not look like a fully qualified name, we cannot simply determine if it's
// Search for the string 'mscorlib' in the classname. If we find it, we will conservatively assume it's an mscorlib.dll type and load it.
for (int i = index; i < className.Length; i++) {
-#if FEATURE_CORECLR
- if (className[i] == 's' || className[i] == 'S')
-#else
- if (className[i] == 'm' || className[i] == 'M')
-#endif
+ if (className[i] == 's' || className[i] == 'S')
{
if (String.Compare(className, i, c_mscorlibName, 0, c_mscorlibName.Length, StringComparison.OrdinalIgnoreCase) == 0)
return true;
{
m_index = index;
m_type = type;
-#if FEATURE_CAS_POLICY
- m_strTypeName = strTypeName;
-#endif // FEATURE_CAS_POLICY
}
- [System.Security.SecurityCritical] // auto-generated
public static PermissionToken GetToken(Type cls)
{
if (cls == null)
return null;
-
-#if FEATURE_CAS_POLICY
- if (cls.GetInterface( "System.Security.Permissions.IBuiltInPermission" ) != null)
- {
- if (s_reflectPerm == null)
- s_reflectPerm = new ReflectionPermission(PermissionState.Unrestricted);
- s_reflectPerm.Assert();
- MethodInfo method = cls.GetMethod( "GetTokenIndex", BindingFlags.Static | BindingFlags.NonPublic );
- Contract.Assert( method != null, "IBuiltInPermission types should have a static method called 'GetTokenIndex'" );
-
- // GetTokenIndex needs to be invoked without any security checks, since doing a security check
- // will involve a ReflectionTargetDemand which creates a CompressedStack and attempts to get the
- // token.
- RuntimeMethodInfo getTokenIndex = method as RuntimeMethodInfo;
- Contract.Assert(getTokenIndex != null, "method is not a RuntimeMethodInfo");
- int token = (int)getTokenIndex.UnsafeInvoke(null, BindingFlags.Default, null, null, null);
- return s_theTokenFactory.BuiltInGetToken(token, null, cls);
- }
- else
-#endif // FEATURE_CAS_POLICY
- {
- return s_theTokenFactory.GetToken(cls, null);
- }
+
+ return s_theTokenFactory.GetToken(cls, null);
}
public static PermissionToken GetToken(IPermission perm)
return s_theTokenFactory.GetToken(perm.GetType(), perm);
}
-#if FEATURE_CAS_POLICY
- public static PermissionToken GetToken(String typeStr)
- {
- return GetToken( typeStr, false );
- }
-
-#if _DEBUG
- [System.Security.SecuritySafeCritical] // auto-generated
- [MethodImplAttribute(MethodImplOptions.NoInlining)] // Methods containing StackCrawlMark local var has to be marked non-inlineable
- private static void GetTokenHelper(String typeStr)
- {
- new PermissionSet(PermissionState.Unrestricted).Assert();
- StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller;
- Type type = RuntimeTypeHandle.GetTypeByName( typeStr.Trim().Replace( '\'', '\"' ), ref stackMark);
- Contract.Assert( (type == null) || (type.Module.Assembly != System.Reflection.Assembly.GetExecutingAssembly()) || (typeStr.IndexOf("mscorlib", StringComparison.Ordinal) < 0),
- "We should not go through this path for mscorlib based permissions" );
- }
-#endif
-
- public static PermissionToken GetToken(String typeStr, bool bCreateMscorlib)
- {
- if (typeStr == null)
- return null;
-
- if (IsMscorlibClassName( typeStr ))
- {
- if (!bCreateMscorlib)
- {
- return null;
- }
- else
- {
- return FindToken( Type.GetType( typeStr ) );
- }
- }
- else
- {
- PermissionToken token = s_theTokenFactory.GetToken(typeStr);
-#if _DEBUG
- GetTokenHelper(typeStr);
-#endif
- return token;
- }
- }
-
- [SecuritySafeCritical]
- public static PermissionToken FindToken( Type cls )
- {
- if (cls == null)
- return null;
-
-#if FEATURE_CAS_POLICY
- if (cls.GetInterface( "System.Security.Permissions.IBuiltInPermission" ) != null)
- {
- if (s_reflectPerm == null)
- s_reflectPerm = new ReflectionPermission(PermissionState.Unrestricted);
- s_reflectPerm.Assert();
- MethodInfo method = cls.GetMethod( "GetTokenIndex", BindingFlags.Static | BindingFlags.NonPublic );
- Contract.Assert( method != null, "IBuiltInPermission types should have a static method called 'GetTokenIndex'" );
-
- // GetTokenIndex needs to be invoked without any security checks, since doing a security check
- // will involve a ReflectionTargetDemand which creates a CompressedStack and attempts to get the
- // token.
- RuntimeMethodInfo getTokenIndex = method as RuntimeMethodInfo;
- Contract.Assert(getTokenIndex != null, "method is not a RuntimeMethodInfo");
- int token = (int)getTokenIndex.UnsafeInvoke(null, BindingFlags.Default, null, null, null);
- return s_theTokenFactory.BuiltInGetToken(token, null, cls);
- }
- else
-#endif // FEATURE_CAS_POLICY
- {
- return s_theTokenFactory.FindToken( cls );
- }
- }
-#endif // FEATURE_CAS_POLICY
-
public static PermissionToken FindTokenByIndex( int i )
{
return s_theTokenFactory.FindTokenByIndex( i );
return true;
}
-
-#if FEATURE_CAS_POLICY
- public SecurityElement ToXml()
- {
- Contract.Assert( (m_type & PermissionTokenType.DontKnow) == 0, "Should have valid token type when ToXml is called" );
- SecurityElement elRoot = new SecurityElement( "PermissionToken" );
- if ((m_type & PermissionTokenType.BuiltIn) != 0)
- elRoot.AddAttribute( "Index", "" + this.m_index );
- else
- elRoot.AddAttribute( "Name", SecurityElement.Escape( m_strTypeName ) );
- elRoot.AddAttribute("Type", m_type.ToString("F"));
- return elRoot;
- }
-
- public void FromXml(SecurityElement elRoot)
- {
- // For the most part there is no parameter checking here since this is an
- // internal class and the serialization/deserialization path is controlled.
-
- if (!elRoot.Tag.Equals( "PermissionToken" ))
- Contract.Assert( false, "Tried to deserialize non-PermissionToken element here" );
-
- String strName = elRoot.Attribute( "Name" );
- PermissionToken realToken;
- if (strName != null)
- realToken = GetToken( strName, true );
- else
- realToken = FindTokenByIndex( Int32.Parse( elRoot.Attribute( "Index" ), CultureInfo.InvariantCulture ) );
-
- this.m_index = realToken.m_index;
- this.m_type = (PermissionTokenType) Enum.Parse(typeof(PermissionTokenType), elRoot.Attribute("Type"));
- Contract.Assert((this.m_type & PermissionTokenType.DontKnow) == 0, "Should have valid token type when FromXml is called.");
- this.m_strTypeName = realToken.m_strTypeName;
- }
-#endif // FEATURE_CAS_POLICY
}
// Package access only
m_indexTable = new Hashtable(size);
}
-#if FEATURE_CAS_POLICY
- [SecuritySafeCritical]
- internal PermissionToken FindToken( Type cls )
- {
- IntPtr typePtr = cls.TypeHandle.Value;
- PermissionToken tok = (PermissionToken)m_handleTable[typePtr];
-
- if (tok != null)
- return tok;
-
- if (m_tokenTable == null)
- return null;
-
- tok = (PermissionToken)m_tokenTable[cls.AssemblyQualifiedName];
-
- if (tok != null)
- {
- lock (this)
- {
- m_handleTable.Add(typePtr, tok);
- }
- }
-
- return tok;
- }
-#endif // FEATURE_CAS_POLICY
-
internal PermissionToken FindTokenByIndex( int i )
{
PermissionToken token;
return token;
}
- [SecuritySafeCritical]
internal PermissionToken GetToken(Type cls, IPermission perm)
{
- Contract.Assert( cls != null, "Must pass in valid type" );
+ Debug.Assert( cls != null, "Must pass in valid type" );
IntPtr typePtr = cls.TypeHandle.Value;
object tok = m_handleTable[typePtr];
{
if (perm != null)
{
- Contract.Assert( !(perm is IBuiltInPermission), "This should not be called for built-ins" );
+ Debug.Assert( !(perm is IBuiltInPermission), "This should not be called for built-ins" );
((PermissionToken)tok).m_type = PermissionTokenType.IUnrestricted;
-#if FEATURE_CAS_POLICY
- ((PermissionToken)tok).m_strTypeName = perm.GetType().AssemblyQualifiedName;
-#endif // FEATURE_CAS_POLICY
}
else
{
- Contract.Assert( cls.GetInterface( "System.Security.Permissions.IBuiltInPermission" ) == null, "This shoudl not be called for built-ins" );
+ Debug.Assert( cls.GetInterface( "System.Security.Permissions.IBuiltInPermission" ) == null, "This shoudl not be called for built-ins" );
if (cls.GetInterface(s_unrestrictedPermissionInferfaceName) != null)
((PermissionToken)tok).m_type = PermissionTokenType.IUnrestricted;
else
((PermissionToken)tok).m_type = PermissionTokenType.Normal;
-#if FEATURE_CAS_POLICY
- ((PermissionToken)tok).m_strTypeName = cls.AssemblyQualifiedName;
-#endif // FEATURE_CAS_POLICY
}
}
return str;
}
- [SecuritySafeCritical]
public override string ToString()
{
// SafeCritical: we're not storing path information in the strings, so exposing them out is fine ...
AddPathList( flag, pathList );
}
- [System.Security.SecuritySafeCritical] // auto-generated
public void AddPathList( EnvironmentPermissionAccess flag, String pathList )
{
VerifyFlag( flag );
//
//------------------------------------------------------
- [System.Security.SecuritySafeCritical] // auto-generated
public override bool IsSubsetOf(IPermission target)
{
if (target == null)
}
}
- [System.Security.SecuritySafeCritical] // auto-generated
public override IPermission Intersect(IPermission target)
{
if (target == null)
return intersectPermission;
}
- [System.Security.SecuritySafeCritical] // auto-generated
public override IPermission Union(IPermission other)
{
if (other == null)
}
}
- return copy;
+ return copy;
}
-
-#if FEATURE_CAS_POLICY
- public override SecurityElement ToXml()
- {
- SecurityElement esd = CodeAccessPermission.CreatePermissionElement( this, "System.Security.Permissions.EnvironmentPermission" );
- if (!IsUnrestricted())
- {
- if (this.m_read != null && !this.m_read.IsEmpty())
- {
- esd.AddAttribute( "Read", SecurityElement.Escape( m_read.ToString() ) );
- }
- if (this.m_write != null && !this.m_write.IsEmpty())
- {
- esd.AddAttribute( "Write", SecurityElement.Escape( m_write.ToString() ) );
- }
- }
- else
- {
- esd.AddAttribute( "Unrestricted", "true" );
- }
- return esd;
- }
-
- public override void FromXml(SecurityElement esd)
- {
- CodeAccessPermission.ValidateElement( esd, this );
-
- String et;
-
- if (XMLUtil.IsUnrestricted(esd))
- {
- m_unrestricted = true;
- return;
- }
-
- m_unrestricted = false;
- m_read = null;
- m_write = null;
-
- et = esd.Attribute( "Read" );
- if (et != null)
- {
- m_read = new EnvironmentStringExpressionSet( et );
- }
-
- et = esd.Attribute( "Write" );
- if (et != null)
- {
- m_write = new EnvironmentStringExpressionSet( et );
- }
-
- }
-#endif // FEATURE_CAS_POLICY
/// <internalonly/>
int IBuiltInPermission.GetTokenIndex()
return new FileDialogPermission(this.access);
}
-#if FEATURE_CAS_POLICY
- public override void FromXml(SecurityElement esd) {
- CodeAccessPermission.ValidateElement(esd, this);
- if (XMLUtil.IsUnrestricted(esd)) {
- SetUnrestricted(true);
- return;
- }
-
- access = FileDialogPermissionAccess.None;
-
- string accessXml = esd.Attribute("Access");
- if (accessXml != null)
- access = (FileDialogPermissionAccess)Enum.Parse(typeof(FileDialogPermissionAccess), accessXml);
- }
-#endif // FEATURE_CAS_POLICY
-
/// <internalonly/>
int IBuiltInPermission.GetTokenIndex() {
return FileDialogPermission.GetTokenIndex();
}
}
-#if FEATURE_CAS_POLICY
- public override SecurityElement ToXml() {
- SecurityElement esd = CodeAccessPermission.CreatePermissionElement( this, "System.Security.Permissions.FileDialogPermission" );
- if (!IsUnrestricted()) {
- if (access != FileDialogPermissionAccess.None) {
- esd.AddAttribute("Access", Enum.GetName(typeof(FileDialogPermissionAccess), access));
- }
- }
- else {
- esd.AddAttribute("Unrestricted", "true");
- }
- return esd;
- }
-#endif // FEATURE_CAS_POLICY
-
public override IPermission Union(IPermission target) {
if (target == null) {
return this.Copy();
FileDialogPermission operand = (FileDialogPermission)target;
return new FileDialogPermission(access | operand.Access);
- }
+ }
static void VerifyAccess(FileDialogPermissionAccess access) {
if ((access & ~FileDialogPermissionAccess.OpenSave) != 0 ) {
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
-namespace System.Security.Permissions {
+namespace System.Security.Permissions
+{
using System;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
-#if FEATURE_CAS_POLICY
- using SecurityElement = System.Security.SecurityElement;
-#endif // FEATURE_CAS_POLICY
using System.Security.AccessControl;
using System.Security.Util;
using System.IO;
using System.Globalization;
using System.Runtime.Serialization;
using System.Runtime.Versioning;
+ using System.Diagnostics;
using System.Diagnostics.Contracts;
-[Serializable]
+ [Serializable]
[Flags]
-[System.Runtime.InteropServices.ComVisible(true)]
+ [System.Runtime.InteropServices.ComVisible(true)]
public enum FileIOPermissionAccess
{
NoAccess = 0x00,
PathDiscovery = 0x08,
AllAccess = 0x0F,
}
-
-
-[System.Runtime.InteropServices.ComVisible(true)]
+
+ [System.Runtime.InteropServices.ComVisible(true)]
[Serializable]
sealed public class FileIOPermission : CodeAccessPermission, IUnrestrictedPermission, IBuiltInPermission
{
}
}
- [System.Security.SecuritySafeCritical] // auto-generated
public FileIOPermission( FileIOPermissionAccess access, String path )
{
VerifyAccess( access );
AddPathList( access, pathList, false, true, false );
}
- [System.Security.SecuritySafeCritical] // auto-generated
public FileIOPermission( FileIOPermissionAccess access, String[] pathList )
{
VerifyAccess( access );
AddPathList( access, pathList, false, true, false );
}
-#if FEATURE_MACL
- [System.Security.SecuritySafeCritical] // auto-generated
- public FileIOPermission( FileIOPermissionAccess access, AccessControlActions control, String path )
- {
- VerifyAccess( access );
-
- String[] pathList = new String[] { path };
- AddPathList( access, control, pathList, false, true, false );
- }
-
- [System.Security.SecuritySafeCritical] // auto-generated
- public FileIOPermission( FileIOPermissionAccess access, AccessControlActions control, String[] pathList )
- : this( access, control, pathList, true, true )
- {
- }
-#endif
-
- [System.Security.SecurityCritical] // auto-generated
internal FileIOPermission( FileIOPermissionAccess access, String[] pathList, bool checkForDuplicates, bool needFullPath )
{
VerifyAccess( access );
AddPathList( access, pathList, checkForDuplicates, needFullPath, true );
}
-#if FEATURE_MACL
- [System.Security.SecurityCritical] // auto-generated
- internal FileIOPermission( FileIOPermissionAccess access, AccessControlActions control, String[] pathList, bool checkForDuplicates, bool needFullPath )
- {
- VerifyAccess( access );
-
- AddPathList( access, control, pathList, checkForDuplicates, needFullPath, true );
- }
-#endif
-
public void SetPathList( FileIOPermissionAccess access, String path )
{
String[] pathList;
SetPathList( access, AccessControlActions.None, pathList, checkForDuplicates );
}
- [System.Security.SecuritySafeCritical] // auto-generated
internal void SetPathList( FileIOPermissionAccess access, AccessControlActions control, String[] pathList, bool checkForDuplicates )
{
VerifyAccess( access );
if ((access & FileIOPermissionAccess.PathDiscovery) != 0)
m_pathDiscovery = null;
-#if FEATURE_MACL
- if ((control & AccessControlActions.View) != 0)
- m_viewAcl = null;
-
- if ((control & AccessControlActions.Change) != 0)
- m_changeAcl = null;
-#else
m_viewAcl = null;
m_changeAcl = null;
-#endif
-
m_unrestricted = false;
-#if FEATURE_MACL
- AddPathList( access, control, pathList, checkForDuplicates, true, true );
-#else
+
AddPathList( access, pathList, checkForDuplicates, true, true );
-#endif
}
- [System.Security.SecuritySafeCritical] // auto-generated
public void AddPathList( FileIOPermissionAccess access, String path )
{
String[] pathList;
AddPathList( access, pathList, false, true, false );
}
- [System.Security.SecuritySafeCritical] // auto-generated
public void AddPathList( FileIOPermissionAccess access, String[] pathList )
{
AddPathList( access, pathList, true, true, true );
}
- [System.Security.SecurityCritical] // auto-generated
internal void AddPathList( FileIOPermissionAccess access, String[] pathListOrig, bool checkForDuplicates, bool needFullPath, bool copyPathList )
{
AddPathList( access, AccessControlActions.None, pathListOrig, checkForDuplicates, needFullPath, copyPathList );
}
- [System.Security.SecurityCritical] // auto-generated
internal void AddPathList(FileIOPermissionAccess access, AccessControlActions control, String[] pathListOrig, bool checkForDuplicates, bool needFullPath, bool copyPathList)
{
if (pathListOrig == null)
}
m_pathDiscovery.AddExpressions( pathArrayList, checkForDuplicates);
}
-
-#if FEATURE_MACL
- if ((control & AccessControlActions.View) != 0)
- {
- if (m_viewAcl == null)
- {
- m_viewAcl = new FileIOAccess();
- }
- m_viewAcl.AddExpressions( pathArrayList, checkForDuplicates);
- }
-
- if ((control & AccessControlActions.Change) != 0)
- {
- if (m_changeAcl == null)
- {
- m_changeAcl = new FileIOAccess();
- }
- m_changeAcl.AddExpressions( pathArrayList, checkForDuplicates);
- }
-#endif
}
-
- [SecuritySafeCritical]
+
public String[] GetPathList( FileIOPermissionAccess access )
{
VerifyAccess( access );
return null;
}
-
public FileIOPermissionAccess AllLocalFiles
{
}
return copy;
}
-
-#if FEATURE_CAS_POLICY
- public override SecurityElement ToXml()
- {
- SecurityElement esd = CodeAccessPermission.CreatePermissionElement( this, "System.Security.Permissions.FileIOPermission" );
- if (!IsUnrestricted())
- {
- if (this.m_read != null && !this.m_read.IsEmpty())
- {
- esd.AddAttribute( "Read", SecurityElement.Escape( m_read.ToString() ) );
- }
- if (this.m_write != null && !this.m_write.IsEmpty())
- {
- esd.AddAttribute( "Write", SecurityElement.Escape( m_write.ToString() ) );
- }
- if (this.m_append != null && !this.m_append.IsEmpty())
- {
- esd.AddAttribute( "Append", SecurityElement.Escape( m_append.ToString() ) );
- }
- if (this.m_pathDiscovery != null && !this.m_pathDiscovery.IsEmpty())
- {
- esd.AddAttribute( "PathDiscovery", SecurityElement.Escape( m_pathDiscovery.ToString() ) );
- }
- if (this.m_viewAcl != null && !this.m_viewAcl.IsEmpty())
- {
- esd.AddAttribute( "ViewAcl", SecurityElement.Escape( m_viewAcl.ToString() ) );
- }
- if (this.m_changeAcl != null && !this.m_changeAcl.IsEmpty())
- {
- esd.AddAttribute( "ChangeAcl", SecurityElement.Escape( m_changeAcl.ToString() ) );
- }
-
- }
- else
- {
- esd.AddAttribute( "Unrestricted", "true" );
- }
- return esd;
- }
-
- [System.Security.SecuritySafeCritical] // auto-generated
- public override void FromXml(SecurityElement esd)
- {
- CodeAccessPermission.ValidateElement( esd, this );
- String et;
-
- if (XMLUtil.IsUnrestricted(esd))
- {
- m_unrestricted = true;
- return;
- }
-
-
- m_unrestricted = false;
-
- et = esd.Attribute( "Read" );
- if (et != null)
- {
- m_read = new FileIOAccess( et );
- }
- else
- {
- m_read = null;
- }
-
- et = esd.Attribute( "Write" );
- if (et != null)
- {
- m_write = new FileIOAccess( et );
- }
- else
- {
- m_write = null;
- }
-
- et = esd.Attribute( "Append" );
- if (et != null)
- {
- m_append = new FileIOAccess( et );
- }
- else
- {
- m_append = null;
- }
-
- et = esd.Attribute( "PathDiscovery" );
- if (et != null)
- {
- m_pathDiscovery = new FileIOAccess( et );
- m_pathDiscovery.PathDiscovery = true;
- }
- else
- {
- m_pathDiscovery = null;
- }
-
- et = esd.Attribute( "ViewAcl" );
- if (et != null)
- {
- m_viewAcl = new FileIOAccess( et );
- }
- else
- {
- m_viewAcl = null;
- }
-
- et = esd.Attribute( "ChangeAcl" );
- if (et != null)
- {
- m_changeAcl = new FileIOAccess( et );
- }
- else
- {
- m_changeAcl = null;
- }
- }
-#endif // FEATURE_CAS_POLICY
/// <internalonly/>
int IBuiltInPermission.GetTokenIndex()
///
/// IMPORTANT: This method should only be used after calling GetFullPath on the path to verify
/// </summary>
- [System.Security.SecuritySafeCritical]
internal static void QuickDemand(FileIOPermissionAccess access, string fullPath, bool checkForDuplicates = false, bool needFullPath = false)
{
-#if FEATURE_CAS_POLICY
- if (!CodeAccessSecurityEngine.QuickCheckForAllDemands())
- {
- new FileIOPermission(access, new string[] { fullPath }, checkForDuplicates, needFullPath).Demand();
- }
- else
-#endif
- {
- EmulateFileIOPermissionChecks(fullPath);
- }
+ EmulateFileIOPermissionChecks(fullPath);
}
/// <summary>
/// IMPORTANT: This method should only be used after calling GetFullPath on the path to verify
///
/// </summary>
- [System.Security.SecuritySafeCritical]
internal static void QuickDemand(FileIOPermissionAccess access, string[] fullPathList, bool checkForDuplicates = false, bool needFullPath = true)
{
-#if FEATURE_CAS_POLICY
- if (!CodeAccessSecurityEngine.QuickCheckForAllDemands())
+ foreach (string fullPath in fullPathList)
{
- new FileIOPermission(access, fullPathList, checkForDuplicates, needFullPath).Demand();
- }
- else
-#endif
- {
- foreach (string fullPath in fullPathList)
- {
- EmulateFileIOPermissionChecks(fullPath);
- }
+ EmulateFileIOPermissionChecks(fullPath);
}
}
- [System.Security.SecuritySafeCritical]
internal static void QuickDemand(PermissionState state)
{
// Should be a no-op without CAS
-#if FEATURE_CAS_POLICY
- if (!CodeAccessSecurityEngine.QuickCheckForAllDemands())
- {
- new FileIOPermission(state).Demand();
- }
-#endif
}
-#if FEATURE_MACL
- [System.Security.SecuritySafeCritical]
- internal static void QuickDemand(FileIOPermissionAccess access, AccessControlActions control, string fullPath, bool checkForDuplicates = false, bool needFullPath = true)
- {
- if (!CodeAccessSecurityEngine.QuickCheckForAllDemands())
- {
- new FileIOPermission(access, control, new string[] { fullPath }, checkForDuplicates, needFullPath).Demand();
- }
- else
- {
- EmulateFileIOPermissionChecks(fullPath);
- }
- }
-
- [System.Security.SecuritySafeCritical]
- internal static void QuickDemand(FileIOPermissionAccess access, AccessControlActions control, string[] fullPathList, bool checkForDuplicates = true, bool needFullPath = true)
- {
- if (!CodeAccessSecurityEngine.QuickCheckForAllDemands())
- {
- new FileIOPermission(access, control, fullPathList, checkForDuplicates, needFullPath).Demand();
- }
- else
- {
- foreach (string fullPath in fullPathList)
- {
- EmulateFileIOPermissionChecks(fullPath);
- }
- }
- }
-#endif
-
/// <summary>
/// Perform the additional path checks that would normally happen when creating a FileIOPermission object.
/// </summary>
m_pathDiscovery = pathDiscovery;
}
- [System.Security.SecurityCritical] // auto-generated
public FileIOAccess( String value )
{
if (value == null)
m_pathDiscovery = operand.m_pathDiscovery;
}
- [System.Security.SecurityCritical] // auto-generated
public void AddExpressions(ArrayList values, bool checkForDuplicates)
{
m_allFiles = false;
return new FileIOAccess( this );
}
- [System.Security.SecuritySafeCritical] // auto-generated
public FileIOAccess Union( FileIOAccess operand )
{
if (operand == null)
return this.IsEmpty() ? null : this.Copy();
}
- Contract.Assert( this.m_pathDiscovery == operand.m_pathDiscovery, "Path discovery settings must match" );
+ Debug.Assert( this.m_pathDiscovery == operand.m_pathDiscovery, "Path discovery settings must match" );
if (this.m_allFiles || operand.m_allFiles)
{
return new FileIOAccess( this.m_set.Union( operand.m_set ), false, this.m_allLocalFiles || operand.m_allLocalFiles, this.m_pathDiscovery );
}
- [System.Security.SecuritySafeCritical] // auto-generated
public FileIOAccess Intersect( FileIOAccess operand )
{
if (operand == null)
return null;
}
- Contract.Assert( this.m_pathDiscovery == operand.m_pathDiscovery, "Path discovery settings must match" );
+ Debug.Assert( this.m_pathDiscovery == operand.m_pathDiscovery, "Path discovery settings must match" );
if (this.m_allFiles)
{
return new FileIOAccess( intersectionSet, false, this.m_allLocalFiles && operand.m_allLocalFiles, this.m_pathDiscovery );
}
- [System.Security.SecuritySafeCritical] // auto-generated
public bool IsSubsetOf( FileIOAccess operand )
{
if (operand == null)
return true;
}
- Contract.Assert( this.m_pathDiscovery == operand.m_pathDiscovery, "Path discovery settings must match" );
+ Debug.Assert( this.m_pathDiscovery == operand.m_pathDiscovery, "Path discovery settings must match" );
if (!((m_pathDiscovery && this.m_set.IsSubsetOfPathDiscovery( operand.m_set )) || this.m_set.IsSubsetOf( operand.m_set )))
{
}
}
- [SecuritySafeCritical]
public override String ToString()
{
// SafeCritical: all string expression sets are constructed with the throwOnRelative bit set, so
}
}
- [SecuritySafeCritical]
public String[] ToStringArray()
{
// SafeCritical: all string expression sets are constructed with the throwOnRelative bit set, so
return m_set.UnsafeToStringArray();
}
- [System.Security.SecurityCritical] // auto-generated
[DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
[SuppressUnmanagedCodeSecurity]
internal static extern bool IsLocalDrive(String path);
- [System.Security.SecuritySafeCritical] // auto-generated
public override bool Equals(Object obj)
{
FileIOAccess operand = obj as FileIOAccess;
if(operand == null)
return (IsEmpty() && obj == null);
- Contract.Assert( this.m_pathDiscovery == operand.m_pathDiscovery, "Path discovery settings must match" );
+ Debug.Assert( this.m_pathDiscovery == operand.m_pathDiscovery, "Path discovery settings must match" );
if(m_pathDiscovery)
{
if(this.m_allFiles && operand.m_allFiles)
namespace System.Security.Permissions
{
using System;
-#if FEATURE_CAS_POLICY
- using SecurityElement = System.Security.SecurityElement;
-#endif // FEATURE_CAS_POLICY
using System.Globalization;
[AttributeUsage(AttributeTargets.Method | AttributeTargets.Constructor | AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Assembly, AllowMultiple = true, Inherited = false )]
return this.Copy();
}
-#if FEATURE_CAS_POLICY
- public override SecurityElement ToXml()
- {
- SecurityElement securityElement = CodeAccessPermission.CreatePermissionElement( this, "System.Security.Permissions.GacIdentityPermission" );
- return securityElement;
- }
-
- public override void FromXml(SecurityElement securityElement)
- {
- CodeAccessPermission.ValidateElement(securityElement, this);
- }
-#endif // FEATURE_CAS_POLICY
-
/// <internalonly/>
int IBuiltInPermission.GetTokenIndex()
{
[AttributeUsage(AttributeTargets.Method | AttributeTargets.Constructor | AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Assembly | AttributeTargets.Delegate, AllowMultiple = true, Inherited = false )]
[System.Runtime.InteropServices.ComVisible(true)]
[Serializable]
-#if FEATURE_CORECLR
// This needs to be in the asmmeta to enable SecAnnotate to successfully resolve and run the security rules. It gets marked
// as internal by BCLRewriter so we are simply marking it as FriendAccessAllowed so it stays in the asmmeta.
[System.Runtime.CompilerServices.FriendAccessAllowedAttribute]
-#endif // FEATURE_CORECLR
#pragma warning disable 618
sealed public class HostProtectionAttribute : CodeAccessSecurityAttribute
#pragma warning restore 618
return new HostProtectionPermission(m_resources);
}
-#if FEATURE_CAS_POLICY
- //------------------------------------------------------
- //
- // XML
- //
- //------------------------------------------------------
- public override SecurityElement ToXml()
- {
- SecurityElement esd = CodeAccessPermission.CreatePermissionElement( this, this.GetType().FullName );
- if(IsUnrestricted())
- esd.AddAttribute( "Unrestricted", "true" );
- else
- esd.AddAttribute( "Resources", XMLUtil.BitFieldEnumToString( typeof( HostProtectionResource ), Resources ) );
- return esd;
- }
-
- public override void FromXml(SecurityElement esd)
- {
- CodeAccessPermission.ValidateElement( esd, this );
- if (XMLUtil.IsUnrestricted( esd ))
- Resources = HostProtectionResource.All;
- else
- {
- String resources = esd.Attribute( "Resources" );
- if (resources == null)
- Resources = HostProtectionResource.None;
- else
- Resources = (HostProtectionResource)Enum.Parse( typeof( HostProtectionResource ), resources );
- }
- }
-#endif // FEATURE_CAS_POLICY
-
//------------------------------------------------------
//
// OBJECT OVERRIDES
{
return BuiltInPermissionIndex.IsolatedStorageFilePermissionIndex;
}
-
- //------------------------------------------------------
- //
- // IsolatedStoragePermission OVERRIDES
- //
- //------------------------------------------------------
-#if FEATURE_CAS_POLICY
- [System.Runtime.InteropServices.ComVisible(false)]
- public override SecurityElement ToXml()
- {
- return base.ToXml( "System.Security.Permissions.IsolatedStorageFilePermission" );
- }
-#endif // FEATURE_CAS_POLICY
}
}
[Serializable]
-#if !FEATURE_CORECLR
- [SecurityPermissionAttribute( SecurityAction.InheritanceDemand, ControlEvidence = true, ControlPolicy = true )]
-#endif
[System.Runtime.InteropServices.ComVisible(true)]
abstract public class IsolatedStoragePermission
: CodeAccessPermission, IUnrestrictedPermission
//------------------------------------------------------
internal static long min(long x,long y) {return x>y?y:x;}
internal static long max(long x,long y) {return x<y?y:x;}
-
-#if FEATURE_CAS_POLICY
- //------------------------------------------------------
- //
- // PUBLIC ENCODING METHODS
- //
- //------------------------------------------------------
-
- private const String _strUserQuota = "UserQuota";
- private const String _strMachineQuota = "MachineQuota";
- private const String _strExpiry = "Expiry";
- private const String _strPermDat = "Permanent";
-
- public override SecurityElement ToXml()
- {
- return ToXml ( this.GetType().FullName );
- }
-
- internal SecurityElement ToXml(String permName)
- {
- SecurityElement esd = CodeAccessPermission.CreatePermissionElement( this, permName );
- if (!IsUnrestricted())
- {
- esd.AddAttribute( "Allowed", Enum.GetName( typeof( IsolatedStorageContainment ), m_allowed ) );
- if (m_userQuota>0)
- {
- esd.AddAttribute(_strUserQuota, (m_userQuota).ToString(CultureInfo.InvariantCulture)) ;
- }
- if (m_machineQuota>0)
- {
- esd.AddAttribute(_strMachineQuota, (m_machineQuota).ToString(CultureInfo.InvariantCulture)) ;
- }
- if (m_expirationDays>0)
- {
- esd.AddAttribute( _strExpiry, (m_expirationDays).ToString(CultureInfo.InvariantCulture)) ;
- }
- if (m_permanentData)
- {
- esd.AddAttribute(_strPermDat, (m_permanentData).ToString()) ;
- }
- }
- else
- {
- esd.AddAttribute( "Unrestricted", "true" );
- }
- return esd;
- }
-
-
- public override void FromXml(SecurityElement esd)
- {
- CodeAccessPermission.ValidateElement( esd, this );
-
- m_allowed = IsolatedStorageContainment.None; // default if no match
-
- if (XMLUtil.IsUnrestricted(esd))
- {
- m_allowed = IsolatedStorageContainment.UnrestrictedIsolatedStorage;
- }
- else
- {
- String allowed = esd.Attribute( "Allowed" );
-
- if (allowed != null)
- m_allowed = (IsolatedStorageContainment)Enum.Parse( typeof( IsolatedStorageContainment ), allowed );
- }
-
- if (m_allowed == IsolatedStorageContainment.UnrestrictedIsolatedStorage)
- {
- m_userQuota = Int64.MaxValue;
- m_machineQuota = Int64.MaxValue;
- m_expirationDays = Int64.MaxValue ;
- m_permanentData = true;
- }
- else
- {
- String param;
- param = esd.Attribute (_strUserQuota) ;
- m_userQuota = param != null ? Int64.Parse(param, CultureInfo.InvariantCulture) : 0 ;
- param = esd.Attribute (_strMachineQuota) ;
- m_machineQuota = param != null ? Int64.Parse(param, CultureInfo.InvariantCulture) : 0 ;
- param = esd.Attribute (_strExpiry) ;
- m_expirationDays = param != null ? Int64.Parse(param, CultureInfo.InvariantCulture) : 0 ;
- param = esd.Attribute (_strPermDat) ;
- m_permanentData = param != null ? (Boolean.Parse(param)) : false ;
- }
- }
-#endif // FEATURE_CAS_POLICY
}
}
using System.Security.Util;
using System.IO;
using System.Security.Policy;
-#if FEATURE_MACL
- using System.Security.AccessControl;
-#endif
using System.Text;
using System.Threading;
using System.Runtime.InteropServices;
using System.Diagnostics.Contracts;
[Serializable]
-[System.Runtime.InteropServices.ComVisible(true)]
-#if !FEATURE_CAS_POLICY
+ [System.Runtime.InteropServices.ComVisible(true)]
// The csharp compiler requires these types to be public, but they are not used elsewhere.
[Obsolete("SecurityAction is no longer accessible to application code.")]
-#endif
public enum SecurityAction
{
// Demand permission of all caller
RequestRefuse = 10,
}
-
-[Serializable]
-[AttributeUsage(AttributeTargets.Method | AttributeTargets.Constructor | AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Assembly, AllowMultiple = true, Inherited = false )]
-[System.Runtime.InteropServices.ComVisible(true)]
-#if !FEATURE_CAS_POLICY
+ [Serializable]
+ [AttributeUsage(AttributeTargets.Method | AttributeTargets.Constructor | AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Assembly, AllowMultiple = true, Inherited = false )]
+ [System.Runtime.InteropServices.ComVisible(true)]
// The csharp compiler requires these types to be public, but they are not used elsewhere.
[Obsolete("SecurityAttribute is no longer accessible to application code.")]
-#endif
public abstract class SecurityAttribute : System.Attribute
{
/// <internalonly/>
abstract public IPermission CreatePermission();
- [System.Security.SecurityCritical] // auto-generated
internal static unsafe IntPtr FindSecurityAttributeTypeHandle(String typeName)
{
PermissionSet.s_fullTrust.Assert();
}
}
-[Serializable]
-[AttributeUsage(AttributeTargets.Method | AttributeTargets.Constructor | AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Assembly, AllowMultiple = true, Inherited = false )]
-[System.Runtime.InteropServices.ComVisible(true)]
-#if !FEATURE_CAS_POLICY
+ [Serializable]
+ [AttributeUsage(AttributeTargets.Method | AttributeTargets.Constructor | AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Assembly, AllowMultiple = true, Inherited = false )]
+ [System.Runtime.InteropServices.ComVisible(true)]
// The csharp compiler requires these types to be public, but they are not used elsewhere.
[Obsolete("CodeAccessSecurityAttribute is no longer accessible to application code.")]
-#endif
public abstract class CodeAccessSecurityAttribute : SecurityAttribute
{
protected CodeAccessSecurityAttribute( SecurityAction action )
perm.SetPathList( FileIOPermissionAccess.Append, m_append );
if (m_pathDiscovery != null)
perm.SetPathList( FileIOPermissionAccess.PathDiscovery, m_pathDiscovery );
-#if FEATURE_MACL
- if (m_viewAccess != null)
- perm.SetPathList( FileIOPermissionAccess.NoAccess, AccessControlActions.View, new String[] { m_viewAccess }, false );
- if (m_changeAccess != null)
- perm.SetPathList( FileIOPermissionAccess.NoAccess, AccessControlActions.Change, new String[] { m_changeAccess }, false );
-#endif
perm.AllFiles = m_allFiles;
perm.AllLocalFiles = m_allLocalFiles;
}
}
-#if !FEATURE_CORECLR
- // PrincipalPermissionAttribute currently derives from
- // CodeAccessSecurityAttribute, even though it's not related to code access
- // security. This is because compilers are currently looking for
- // CodeAccessSecurityAttribute as a direct parent class rather than
- // SecurityAttribute as the root class.
- [AttributeUsage(AttributeTargets.Method | AttributeTargets.Class, AllowMultiple = true, Inherited = false )]
-[System.Runtime.InteropServices.ComVisible(true)]
- [Serializable]
- sealed public class PrincipalPermissionAttribute : CodeAccessSecurityAttribute
- {
- private String m_name = null;
- private String m_role = null;
- private bool m_authenticated = true;
-
- public PrincipalPermissionAttribute( SecurityAction action )
- : base( action )
- {
- }
-
- public String Name
- {
- get { return m_name; }
- set { m_name = value; }
- }
-
- public String Role
- {
- get { return m_role; }
- set { m_role = value; }
- }
-
- public bool Authenticated
- {
- get { return m_authenticated; }
- set { m_authenticated = value; }
- }
-
-
- public override IPermission CreatePermission()
- {
- if (m_unrestricted)
- {
- return new PrincipalPermission( PermissionState.Unrestricted );
- }
- else
- {
- return new PrincipalPermission( m_name, m_role, m_authenticated );
- }
- }
- }
-#endif // !FEATURE_CORECLR
-
[AttributeUsage(AttributeTargets.Method | AttributeTargets.Constructor | AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Assembly, AllowMultiple = true, Inherited = false )]
[System.Runtime.InteropServices.ComVisible(true)]
[Serializable]
perm.SetPathList( RegistryPermissionAccess.Write, m_write );
if (m_create != null)
perm.SetPathList( RegistryPermissionAccess.Create, m_create );
-#if FEATURE_MACL
- if (m_viewAcl != null)
- perm.SetPathList( AccessControlActions.View, m_viewAcl );
- if (m_changeAcl != null)
- perm.SetPathList( AccessControlActions.Change, m_changeAcl );
-#endif
return perm;
}
}
}
[AttributeUsage(AttributeTargets.Method | AttributeTargets.Constructor | AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Assembly, AllowMultiple = true, Inherited = false )]
-[System.Runtime.InteropServices.ComVisible(true)]
+ [System.Runtime.InteropServices.ComVisible(true)]
[Serializable]
-#if !FEATURE_CAS_POLICY
// The csharp compiler requires these types to be public, but they are not used elsewhere.
[Obsolete("SecurityPermissionAttribute is no longer accessible to application code.")]
-#endif
sealed public class SecurityPermissionAttribute : CodeAccessSecurityAttribute
{
private SecurityPermissionFlag m_flag = SecurityPermissionFlag.NoFlags;
set { m_flag = value ? m_flag | SecurityPermissionFlag.RemotingConfiguration : m_flag & ~SecurityPermissionFlag.RemotingConfiguration; }
}
-[System.Runtime.InteropServices.ComVisible(true)]
+ [System.Runtime.InteropServices.ComVisible(true)]
public bool Infrastructure {
get { return (m_flag & SecurityPermissionFlag.Infrastructure) != 0; }
set { m_flag = value ? m_flag | SecurityPermissionFlag.Infrastructure : m_flag & ~SecurityPermissionFlag.Infrastructure; }
}
}
}
-
-#if FEATURE_X509 && FEATURE_CAS_POLICY
- [AttributeUsage(AttributeTargets.Method | AttributeTargets.Constructor | AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Assembly, AllowMultiple = true, Inherited = false )]
-[System.Runtime.InteropServices.ComVisible(true)]
- [Serializable]
- sealed public class PublisherIdentityPermissionAttribute : CodeAccessSecurityAttribute
- {
- private String m_x509cert = null;
- private String m_certFile = null;
- private String m_signedFile = null;
-
- public PublisherIdentityPermissionAttribute( SecurityAction action )
- : base( action )
- {
- m_x509cert = null;
- m_certFile = null;
- m_signedFile = null;
- }
-
- public String X509Certificate {
- get { return m_x509cert; }
- set { m_x509cert = value; }
- }
-
- public String CertFile {
- get { return m_certFile; }
- set { m_certFile = value; }
- }
-
- public String SignedFile {
- get { return m_signedFile; }
- set { m_signedFile = value; }
- }
-
- public override IPermission CreatePermission()
- {
- if (m_unrestricted)
- {
- return new PublisherIdentityPermission( PermissionState.Unrestricted );
- }
- else
- {
- if (m_x509cert != null)
- {
- return new PublisherIdentityPermission( new X509Certificate( System.Security.Util.Hex.DecodeHexString( m_x509cert ) ) );
- }
- else if (m_certFile != null)
- {
- return new PublisherIdentityPermission( System.Security.Cryptography.X509Certificates.X509Certificate.CreateFromCertFile( m_certFile ) );
- }
- else if (m_signedFile != null)
- {
- return new PublisherIdentityPermission( System.Security.Cryptography.X509Certificates.X509Certificate.CreateFromSignedFile( m_signedFile ) );
- }
- else
- {
- return new PublisherIdentityPermission( PermissionState.None );
- }
- }
- }
- }
-#endif // #if FEATURE_X509 && FEATURE_CAS_POLICY
-
-#if !FEATURE_CORECLR
-[Serializable]
-[AttributeUsage(AttributeTargets.Method | AttributeTargets.Constructor
- | AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Assembly,
- AllowMultiple=true, Inherited=false)]
-[System.Runtime.InteropServices.ComVisible(true)]
- public abstract class IsolatedStoragePermissionAttribute : CodeAccessSecurityAttribute
- {
- /// <internalonly/>
- internal long m_userQuota;
-#if false
- /// <internalonly/>
- internal long m_machineQuota;
- /// <internalonly/>
- internal long m_expirationDays;
- /// <internalonly/>
- internal bool m_permanentData;
-#endif
- /// <internalonly/>
- internal IsolatedStorageContainment m_allowed;
- protected IsolatedStoragePermissionAttribute(SecurityAction action) : base(action)
- {
- }
-
- // properties
- public long UserQuota {
- set{
- m_userQuota = value;
- }
- get{
- return m_userQuota;
- }
- }
-#if false
- internal long MachineQuota {
- set{
- m_machineQuota = value;
- }
- get{
- return m_machineQuota;
- }
- }
- internal long ExpirationDays {
- set{
- m_expirationDays = value;
- }
- get{
- return m_expirationDays;
- }
- }
- internal bool PermanentData {
- set{
- m_permanentData = value;
- }
- get{
- return m_permanentData;
- }
- }
-#endif
- public IsolatedStorageContainment UsageAllowed {
- set{
- m_allowed = value;
- }
- get{
- return m_allowed;
- }
- }
-
- }
-
- [AttributeUsage(AttributeTargets.Method | AttributeTargets.Constructor
- | AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Assembly,
- AllowMultiple=true, Inherited=false)]
-[System.Runtime.InteropServices.ComVisible(true)]
- [Serializable]
- sealed public class IsolatedStorageFilePermissionAttribute : IsolatedStoragePermissionAttribute
- {
- public IsolatedStorageFilePermissionAttribute(SecurityAction action) : base(action)
- {
-
- }
- public override IPermission CreatePermission()
- {
- IsolatedStorageFilePermission p;
- if (m_unrestricted) {
- p = new IsolatedStorageFilePermission
- (PermissionState.Unrestricted);
- } else {
- p = new IsolatedStorageFilePermission(PermissionState.None);
- p.UserQuota = m_userQuota;
- p.UsageAllowed = m_allowed;
-#if false
- p.PermanentData = m_permanentData;
- p.MachineQuota = m_machineQuota;
- p.ExpirationDays = m_expirationDays;
-#endif
- }
- return p;
- }
- }
-#endif // FEATURE_CORECLR
[AttributeUsage(AttributeTargets.Method | AttributeTargets.Constructor | AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Assembly, AllowMultiple = true, Inherited = false )]
[System.Runtime.InteropServices.ComVisible(true)]
return null;
}
-#if FEATURE_CAS_POLICY
- private PermissionSet BruteForceParseStream(Stream stream)
- {
- Encoding[] encodings = new Encoding[] { Encoding.UTF8,
- Encoding.ASCII,
- Encoding.Unicode };
-
- StreamReader reader = null;
- Exception exception = null;
-
- for (int i = 0; reader == null && i < encodings.Length; ++i)
- {
- try
- {
- stream.Position = 0;
- reader = new StreamReader( stream, encodings[i] );
-
- return ParsePermissionSet( new Parser(reader) );
- }
- catch (Exception e1)
- {
- if (exception == null)
- exception = e1;
- }
- }
-
- throw exception;
- }
-
- private PermissionSet ParsePermissionSet(Parser parser)
- {
- SecurityElement e = parser.GetTopElement();
- PermissionSet permSet = new PermissionSet( PermissionState.None );
- permSet.FromXml( e );
-
- return permSet;
- }
-#endif // FEATURE_CAS_POLICY
-
-#if FEATURE_CAS_POLICY
- [System.Security.SecuritySafeCritical] // auto-generated
-#endif
public PermissionSet CreatePermissionSet()
{
if (m_unrestricted)
return new PermissionSet( PermissionState.Unrestricted );
else if (m_name != null)
-#if FEATURE_CAS_POLICY
- return PolicyLevel.GetBuiltInSet( m_name );
-#else
return NamedPermissionSet.GetBuiltInSet( m_name );
-#endif // FEATURE_CAS_POLICY
-#if FEATURE_CAS_POLICY
- else if (m_xml != null)
- return ParsePermissionSet( new Parser(m_xml.ToCharArray()) );
- else if (m_hex != null)
- return BruteForceParseStream( new MemoryStream(Util.Hex.DecodeHexString(m_hex)) );
- else if (m_file != null)
- return BruteForceParseStream( new FileStream( m_file, FileMode.Open, FileAccess.Read) );
-#endif // FEATURE_CAS_POLICY
else
return new PermissionSet( PermissionState.None );
}
throw new ArgumentException(Environment.GetResourceString("Arg_EnumIllegalVal", (int)type));
Contract.EndContractBlock();
}
-
-#if FEATURE_CAS_POLICY
- //------------------------------------------------------
- //
- // PUBLIC ENCODING METHODS
- //
- //------------------------------------------------------
-
- public override SecurityElement ToXml()
- {
- SecurityElement esd = CodeAccessPermission.CreatePermissionElement( this, "System.Security.Permissions.ReflectionPermission" );
- if (!IsUnrestricted())
- {
- esd.AddAttribute( "Flags", XMLUtil.BitFieldEnumToString( typeof( ReflectionPermissionFlag ), m_flags ) );
- }
- else
- {
- esd.AddAttribute( "Unrestricted", "true" );
- }
- return esd;
- }
-
- public override void FromXml(SecurityElement esd)
- {
- CodeAccessPermission.ValidateElement( esd, this );
- if (XMLUtil.IsUnrestricted( esd ))
- {
- m_flags = ReflectionPermission.AllFlagsAndMore;
- return;
- }
-
- Reset () ;
- SetUnrestricted (false) ;
-
- String flags = esd.Attribute( "Flags" );
- if (flags != null)
- m_flags = (ReflectionPermissionFlag)Enum.Parse( typeof( ReflectionPermissionFlag ), flags );
- }
-#endif // FEATURE_CAS_POLICY
/// <internalonly/>
int IBuiltInPermission.GetTokenIndex()
SetPathList( access, pathList );
}
-#if FEATURE_MACL
- public RegistryPermission( RegistryPermissionAccess access, AccessControlActions control, String pathList )
- {
- m_unrestricted = false;
- AddPathList( access, control, pathList );
- }
-#endif
-
public void SetPathList( RegistryPermissionAccess access, String pathList )
{
VerifyAccess( access );
AddPathList( access, pathList );
}
-#if FEATURE_MACL
- internal void SetPathList( AccessControlActions control, String pathList )
- {
- m_unrestricted = false;
-
- if ((control & AccessControlActions.View) != 0)
- m_viewAcl = null;
-
- if ((control & AccessControlActions.Change) != 0)
- m_changeAcl = null;
-
- AddPathList( RegistryPermissionAccess.NoAccess, control, pathList );
- }
-#endif
-
public void AddPathList( RegistryPermissionAccess access, String pathList )
{
AddPathList( access, AccessControlActions.None, pathList );
}
- [System.Security.SecuritySafeCritical] // auto-generated
public void AddPathList( RegistryPermissionAccess access, AccessControlActions control, String pathList )
{
VerifyAccess( access );
m_create = new StringExpressionSet();
m_create.AddExpressions( pathList );
}
-
-#if FEATURE_MACL
- if ((control & AccessControlActions.View) != 0)
- {
- if (m_viewAcl == null)
- m_viewAcl = new StringExpressionSet();
- m_viewAcl.AddExpressions( pathList );
- }
-
- if ((control & AccessControlActions.Change) != 0)
- {
- if (m_changeAcl == null)
- m_changeAcl = new StringExpressionSet();
- m_changeAcl.AddExpressions( pathList );
- }
-#endif
}
- [SecuritySafeCritical]
public String GetPathList( RegistryPermissionAccess access )
{
// SafeCritical: these are registry paths, which means we're not leaking file system information here
//
//------------------------------------------------------
- [System.Security.SecuritySafeCritical] // auto-generated
public override bool IsSubsetOf(IPermission target)
{
if (target == null)
(this.m_changeAcl == null || this.m_changeAcl.IsSubsetOf( operand.m_changeAcl )));
}
- [System.Security.SecuritySafeCritical] // auto-generated
public override IPermission Intersect(IPermission target)
{
if (target == null)
return intersectPermission;
}
- [System.Security.SecuritySafeCritical] // auto-generated
public override IPermission Union(IPermission other)
{
if (other == null)
}
return copy;
}
-
-#if FEATURE_CAS_POLICY
- [SecuritySafeCritical]
- public override SecurityElement ToXml()
- {
- // SafeCritical: our string expression sets don't contain paths, so there's no information that
- // needs to be guarded in them.
- SecurityElement esd = CodeAccessPermission.CreatePermissionElement( this, "System.Security.Permissions.RegistryPermission" );
- if (!IsUnrestricted())
- {
- if (this.m_read != null && !this.m_read.IsEmpty())
- {
- esd.AddAttribute( "Read", SecurityElement.Escape( m_read.UnsafeToString() ) );
- }
- if (this.m_write != null && !this.m_write.IsEmpty())
- {
- esd.AddAttribute( "Write", SecurityElement.Escape( m_write.UnsafeToString() ) );
- }
- if (this.m_create != null && !this.m_create.IsEmpty())
- {
- esd.AddAttribute( "Create", SecurityElement.Escape( m_create.UnsafeToString() ) );
- }
- if (this.m_viewAcl != null && !this.m_viewAcl.IsEmpty())
- {
- esd.AddAttribute( "ViewAccessControl", SecurityElement.Escape( m_viewAcl.UnsafeToString() ) );
- }
- if (this.m_changeAcl != null && !this.m_changeAcl.IsEmpty())
- {
- esd.AddAttribute( "ChangeAccessControl", SecurityElement.Escape( m_changeAcl.UnsafeToString() ) );
- }
- }
- else
- {
- esd.AddAttribute( "Unrestricted", "true" );
- }
- return esd;
- }
-
- public override void FromXml(SecurityElement esd)
- {
- CodeAccessPermission.ValidateElement( esd, this );
- String et;
-
- if (XMLUtil.IsUnrestricted( esd ))
- {
- m_unrestricted = true;
- return;
- }
-
- m_unrestricted = false;
- m_read = null;
- m_write = null;
- m_create = null;
- m_viewAcl = null;
- m_changeAcl = null;
-
- et = esd.Attribute( "Read" );
- if (et != null)
- {
- m_read = new StringExpressionSet( et );
- }
-
- et = esd.Attribute( "Write" );
- if (et != null)
- {
- m_write = new StringExpressionSet( et );
- }
-
- et = esd.Attribute( "Create" );
- if (et != null)
- {
- m_create = new StringExpressionSet( et );
- }
-
- et = esd.Attribute( "ViewAccessControl" );
- if (et != null)
- {
- m_viewAcl = new StringExpressionSet( et );
- }
-
- et = esd.Attribute( "ChangeAccessControl" );
- if (et != null)
- {
- m_changeAcl = new StringExpressionSet( et );
- }
- }
-#endif // FEATURE_CAS_POLICY
/// <internalonly/>
int IBuiltInPermission.GetTokenIndex()
using System.Globalization;
using System.Diagnostics.Contracts;
-[Serializable]
+ [Serializable]
[Flags]
-[System.Runtime.InteropServices.ComVisible(true)]
-#if !FEATURE_CAS_POLICY
+ [System.Runtime.InteropServices.ComVisible(true)]
// The csharp compiler requires these types to be public, but they are not used elsewhere.
[Obsolete("SecurityPermissionFlag is no longer accessible to application code.")]
-#endif
public enum SecurityPermissionFlag
{
NoFlags = 0x00,
Contract.EndContractBlock();
}
-#if FEATURE_CAS_POLICY
- //------------------------------------------------------
- //
- // PUBLIC ENCODING METHODS
- //
- //------------------------------------------------------
-
- private const String _strHeaderAssertion = "Assertion";
- private const String _strHeaderUnmanagedCode = "UnmanagedCode";
- private const String _strHeaderExecution = "Execution";
- private const String _strHeaderSkipVerification = "SkipVerification";
- private const String _strHeaderControlThread = "ControlThread";
- private const String _strHeaderControlEvidence = "ControlEvidence";
- private const String _strHeaderControlPolicy = "ControlPolicy";
- private const String _strHeaderSerializationFormatter = "SerializationFormatter";
- private const String _strHeaderControlDomainPolicy = "ControlDomainPolicy";
- private const String _strHeaderControlPrincipal = "ControlPrincipal";
- private const String _strHeaderControlAppDomain = "ControlAppDomain";
-
- public override SecurityElement ToXml()
- {
- SecurityElement esd = CodeAccessPermission.CreatePermissionElement( this, "System.Security.Permissions.SecurityPermission" );
- if (!IsUnrestricted())
- {
- esd.AddAttribute( "Flags", XMLUtil.BitFieldEnumToString( typeof( SecurityPermissionFlag ), m_flags ) );
- }
- else
- {
- esd.AddAttribute( "Unrestricted", "true" );
- }
- return esd;
- }
-
- public override void FromXml(SecurityElement esd)
- {
- CodeAccessPermission.ValidateElement( esd, this );
- if (XMLUtil.IsUnrestricted( esd ))
- {
- m_flags = SecurityPermissionFlag.AllFlags;
- return;
- }
-
- Reset () ;
- SetUnrestricted (false) ;
-
- String flags = esd.Attribute( "Flags" );
-
- if (flags != null)
- m_flags = (SecurityPermissionFlag)Enum.Parse( typeof( SecurityPermissionFlag ), flags );
- }
-#endif // FEATURE_CAS_POLICY
-
//
// Object Overrides
//
-
- #if ZERO // Do not remove this code, usefull for debugging
- public override String ToString()
- {
- StringBuilder sb = new StringBuilder();
- sb.Append("SecurityPermission(");
- if (IsUnrestricted())
- {
- sb.Append("Unrestricted");
- }
- else
- {
- if (GetFlag(SecurityPermissionFlag.Assertion))
- sb.Append("Assertion; ");
- if (GetFlag(SecurityPermissionFlag.UnmanagedCode))
- sb.Append("UnmangedCode; ");
- if (GetFlag(SecurityPermissionFlag.SkipVerification))
- sb.Append("SkipVerification; ");
- if (GetFlag(SecurityPermissionFlag.Execution))
- sb.Append("Execution; ");
- if (GetFlag(SecurityPermissionFlag.ControlThread))
- sb.Append("ControlThread; ");
- if (GetFlag(SecurityPermissionFlag.ControlEvidence))
- sb.Append("ControlEvidence; ");
- if (GetFlag(SecurityPermissionFlag.ControlPolicy))
- sb.Append("ControlPolicy; ");
- if (GetFlag(SecurityPermissionFlag.SerializationFormatter))
- sb.Append("SerializationFormatter; ");
- if (GetFlag(SecurityPermissionFlag.ControlDomainPolicy))
- sb.Append("ControlDomainPolicy; ");
- if (GetFlag(SecurityPermissionFlag.ControlPrincipal))
- sb.Append("ControlPrincipal; ");
- }
-
- sb.Append(")");
- return sb.ToString();
- }
- #endif
/// <internalonly/>
int IBuiltInPermission.GetTokenIndex()
namespace System.Security.Permissions
{
using System;
-#if FEATURE_CAS_POLICY
- using SecurityElement = System.Security.SecurityElement;
-#endif // FEATURE_CAS_POLICY
using SiteString = System.Security.Util.SiteString;
using System.Text;
using System.Collections;
[OptionalField(VersionAdded = 2)]
private SiteString[] m_sites;
-#if FEATURE_REMOTING
- // This field will be populated only for non X-AD scenarios where we create a XML-ised string of the Permission
- [OptionalField(VersionAdded = 2)]
- private String m_serializedPermission;
-
- // This field is legacy info from v1.x and is never used in v2.0 and beyond: purely for serialization purposes
- private SiteString m_site;
-
- [OnDeserialized]
- private void OnDeserialized(StreamingContext ctx)
- {
- // v2.0 and beyond XML case
- if (m_serializedPermission != null)
- {
- FromXml(SecurityElement.FromString(m_serializedPermission));
- m_serializedPermission = null;
- }
- else if (m_site != null) //v1.x case where we read the m_site value
- {
- m_unrestricted = false;
- m_sites = new SiteString[1];
- m_sites[0] = m_site;
- m_site = null;
- }
- }
-
- [OnSerializing]
- private void OnSerializing(StreamingContext ctx)
- {
-
- if ((ctx.State & ~(StreamingContextStates.Clone|StreamingContextStates.CrossAppDomain)) != 0)
- {
- m_serializedPermission = ToXml().ToString(); //for the v2 and beyond case
- if (m_sites != null && m_sites.Length == 1) // for the v1.x case
- m_site = m_sites[0];
-
- }
- }
- [OnSerialized]
- private void OnSerialized(StreamingContext ctx)
- {
- if ((ctx.State & ~(StreamingContextStates.Clone|StreamingContextStates.CrossAppDomain)) != 0)
- {
- m_serializedPermission = null;
- m_site = null;
- }
- }
-#endif // FEATURE_REMOTING
-
//------------------------------------------------------
//
// PUBLIC CONSTRUCTORS
// IPERMISSION IMPLEMENTATION
//
//------------------------------------------------------
-
-
public override IPermission Copy()
{
SiteIdentityPermission perm = new SiteIdentityPermission( PermissionState.None );
return result;
}
-#if FEATURE_CAS_POLICY
- public override void FromXml(SecurityElement esd)
- {
- m_unrestricted = false;
- m_sites = null;
- CodeAccessPermission.ValidateElement( esd, this );
- String unr = esd.Attribute( "Unrestricted" );
- if(unr != null && String.Compare(unr, "true", StringComparison.OrdinalIgnoreCase) == 0)
- {
- m_unrestricted = true;
- return;
- }
- String elem = esd.Attribute( "Site" );
- List<SiteString> al = new List<SiteString>();
- if(elem != null)
- al.Add(new SiteString( elem ));
- ArrayList alChildren = esd.Children;
- if(alChildren != null)
- {
- foreach(SecurityElement child in alChildren)
- {
- elem = child.Attribute( "Site" );
- if(elem != null)
- al.Add(new SiteString( elem ));
- }
- }
- if(al.Count != 0)
- m_sites = al.ToArray();
- }
-
- public override SecurityElement ToXml()
- {
- SecurityElement esd = CodeAccessPermission.CreatePermissionElement( this, "System.Security.Permissions.SiteIdentityPermission" );
- if (m_unrestricted)
- esd.AddAttribute( "Unrestricted", "true" );
- else if (m_sites != null)
- {
- if (m_sites.Length == 1)
- esd.AddAttribute( "Site", m_sites[0].ToString() );
- else
- {
- int n;
- for(n = 0; n < m_sites.Length; n++)
- {
- SecurityElement child = new SecurityElement("Site");
- child.AddAttribute( "Site", m_sites[n].ToString() );
- esd.AddChild(child);
- }
- }
- }
- return esd;
- }
-#endif // FEATURE_CAS_POLICY
-
/// <internalonly/>
int IBuiltInPermission.GetTokenIndex()
{
namespace System.Security.Permissions
{
using System;
-#if FEATURE_CAS_POLICY
- using SecurityElement = System.Security.SecurityElement;
-#endif // FEATURE_CAS_POLICY
using System.Security.Util;
using System.IO;
using String = System.String;
return result;
}
-#if FEATURE_CAS_POLICY
- public override void FromXml(SecurityElement e)
- {
- m_unrestricted = false;
- m_strongNames = null;
- CodeAccessPermission.ValidateElement( e, this );
- String unr = e.Attribute( "Unrestricted" );
- if(unr != null && String.Compare(unr, "true", StringComparison.OrdinalIgnoreCase) == 0)
- {
- m_unrestricted = true;
- return;
- }
- String elBlob = e.Attribute("PublicKeyBlob");
- String elName = e.Attribute("Name");
- String elVersion = e.Attribute("AssemblyVersion");
- StrongName2 sn;
- List<StrongName2> al = new List<StrongName2>();
- if(elBlob != null || elName != null || elVersion != null)
- {
- sn = new StrongName2(
- (elBlob == null ? null : new StrongNamePublicKeyBlob(elBlob)),
- elName,
- (elVersion == null ? null : new Version(elVersion)));
- al.Add(sn);
- }
- ArrayList alChildren = e.Children;
- if(alChildren != null)
- {
- foreach(SecurityElement child in alChildren)
- {
- elBlob = child.Attribute("PublicKeyBlob");
- elName = child.Attribute("Name");
- elVersion = child.Attribute("AssemblyVersion");
- if(elBlob != null || elName != null || elVersion != null)
- {
- sn = new StrongName2(
- (elBlob == null ? null : new StrongNamePublicKeyBlob(elBlob)),
- elName,
- (elVersion == null ? null : new Version(elVersion)));
- al.Add(sn);
- }
- }
- }
- if(al.Count != 0)
- m_strongNames = al.ToArray();
- }
-
- public override SecurityElement ToXml()
- {
- SecurityElement esd = CodeAccessPermission.CreatePermissionElement( this, "System.Security.Permissions.StrongNameIdentityPermission" );
- if (m_unrestricted)
- esd.AddAttribute( "Unrestricted", "true" );
- else if (m_strongNames != null)
- {
- if (m_strongNames.Length == 1)
- {
- if (m_strongNames[0].m_publicKeyBlob != null)
- esd.AddAttribute("PublicKeyBlob", Hex.EncodeHexString(m_strongNames[0].m_publicKeyBlob.PublicKey));
- if (m_strongNames[0].m_name != null)
- esd.AddAttribute("Name", m_strongNames[0].m_name);
- if ((Object)m_strongNames[0].m_version != null)
- esd.AddAttribute("AssemblyVersion", m_strongNames[0].m_version.ToString());
- }
- else
- {
- int n;
- for(n = 0; n < m_strongNames.Length; n++)
- {
- SecurityElement child = new SecurityElement("StrongName");
- if (m_strongNames[n].m_publicKeyBlob != null)
- child.AddAttribute("PublicKeyBlob", Hex.EncodeHexString(m_strongNames[n].m_publicKeyBlob.PublicKey));
- if (m_strongNames[n].m_name != null)
- child.AddAttribute("Name", m_strongNames[n].m_name);
- if ((Object)m_strongNames[n].m_version != null)
- child.AddAttribute("AssemblyVersion", m_strongNames[n].m_version.ToString());
- esd.AddChild(child);
- }
- }
- }
- return esd;
- }
-#endif // FEATURE_CAS_POLICY
-
/// <internalonly/>
int IBuiltInPermission.GetTokenIndex()
{
{
return new UIPermission(this.m_windowFlag, this.m_clipboardFlag);
}
-
-#if FEATURE_CAS_POLICY
- public override SecurityElement ToXml()
- {
- SecurityElement esd = CodeAccessPermission.CreatePermissionElement( this, "System.Security.Permissions.UIPermission" );
- if (!IsUnrestricted())
- {
- if (m_windowFlag != UIPermissionWindow.NoWindows)
- {
- esd.AddAttribute( "Window", Enum.GetName( typeof( UIPermissionWindow ), m_windowFlag ) );
- }
- if (m_clipboardFlag != UIPermissionClipboard.NoClipboard)
- {
- esd.AddAttribute( "Clipboard", Enum.GetName( typeof( UIPermissionClipboard ), m_clipboardFlag ) );
- }
- }
- else
- {
- esd.AddAttribute( "Unrestricted", "true" );
- }
- return esd;
- }
-
- public override void FromXml(SecurityElement esd)
- {
- CodeAccessPermission.ValidateElement( esd, this );
- if (XMLUtil.IsUnrestricted( esd ))
- {
- SetUnrestricted( true );
- return;
- }
-
- m_windowFlag = UIPermissionWindow.NoWindows;
- m_clipboardFlag = UIPermissionClipboard.NoClipboard;
-
- String window = esd.Attribute( "Window" );
- if (window != null)
- m_windowFlag = (UIPermissionWindow)Enum.Parse( typeof( UIPermissionWindow ), window );
-
- String clipboard = esd.Attribute( "Clipboard" );
- if (clipboard != null)
- m_clipboardFlag = (UIPermissionClipboard)Enum.Parse( typeof( UIPermissionClipboard ), clipboard );
- }
-#endif // FEATURE_CAS_POLICY
/// <internalonly/>
int IBuiltInPermission.GetTokenIndex()
namespace System.Security.Permissions
{
using System;
-#if FEATURE_CAS_POLICY
- using SecurityElement = System.Security.SecurityElement;
-#endif // FEATURE_CAS_POLICY
using System.Security.Util;
using System.IO;
using System.Text;
[OptionalField(VersionAdded = 2)]
private bool m_unrestricted;
- [OptionalField(VersionAdded = 2)]
- private URLString[] m_urls;
-
-#if FEATURE_REMOTING
- // This field will be populated only for non X-AD scenarios where we create a XML-ised string of the Permission
[OptionalField(VersionAdded = 2)]
- private String m_serializedPermission;
-
- // This field is legacy info from v1.x and is never used in v2.0 and beyond: purely for serialization purposes
- private URLString m_url;
-
- [OnDeserialized]
- private void OnDeserialized(StreamingContext ctx)
- {
- // v2.0 and beyond XML case
- if (m_serializedPermission != null)
- {
- FromXml(SecurityElement.FromString(m_serializedPermission));
- m_serializedPermission = null;
- }
- else if (m_url != null) //v1.x case where we read the m_site value
- {
- m_unrestricted = false;
- m_urls = new URLString[1];
- m_urls[0] = m_url;
- m_url = null;
- }
-
- }
-
- [OnSerializing]
- private void OnSerializing(StreamingContext ctx)
- {
-
- if ((ctx.State & ~(StreamingContextStates.Clone|StreamingContextStates.CrossAppDomain)) != 0)
- {
- m_serializedPermission = ToXml().ToString(); //for the v2 and beyond case
- if (m_urls != null && m_urls.Length == 1) // for the v1.x case
- m_url = m_urls[0];
-
- }
- }
- [OnSerialized]
- private void OnSerialized(StreamingContext ctx)
- {
- if ((ctx.State & ~(StreamingContextStates.Clone|StreamingContextStates.CrossAppDomain)) != 0)
- {
- m_serializedPermission = null;
- m_url = null;
- }
- }
-#endif // FEATURE_REMOTING
+ private URLString[] m_urls;
//------------------------------------------------------
//
return result;
}
-#if FEATURE_CAS_POLICY
- public override void FromXml(SecurityElement esd)
- {
- m_unrestricted = false;
- m_urls = null;
- CodeAccessPermission.ValidateElement( esd, this );
- String unr = esd.Attribute( "Unrestricted" );
- if(unr != null && String.Compare(unr, "true", StringComparison.OrdinalIgnoreCase) == 0)
- {
- m_unrestricted = true;
- return;
- }
- String elem = esd.Attribute( "Url" );
- List<URLString> al = new List<URLString>();
- if(elem != null)
- al.Add(new URLString( elem, true ));
- ArrayList alChildren = esd.Children;
- if(alChildren != null)
- {
- foreach(SecurityElement child in alChildren)
- {
- elem = child.Attribute( "Url" );
- if(elem != null)
- al.Add(new URLString( elem, true ));
- }
- }
- if(al.Count != 0)
- m_urls = al.ToArray();
- }
-
- public override SecurityElement ToXml()
- {
- SecurityElement esd = CodeAccessPermission.CreatePermissionElement( this, "System.Security.Permissions.UrlIdentityPermission" );
- if (m_unrestricted)
- esd.AddAttribute( "Unrestricted", "true" );
- else if (m_urls != null)
- {
- if (m_urls.Length == 1)
- esd.AddAttribute( "Url", m_urls[0].ToString() );
- else
- {
- int n;
- for(n = 0; n < m_urls.Length; n++)
- {
- SecurityElement child = new SecurityElement("Url");
- child.AddAttribute( "Url", m_urls[n].ToString() );
- esd.AddChild(child);
- }
- }
- }
- return esd;
- }
-#endif // FEATURE_CAS_POLICY
-
/// <internalonly/>
int IBuiltInPermission.GetTokenIndex()
{
namespace System.Security.Permissions
{
using System;
-#if FEATURE_CAS_POLICY
- using SecurityElement = System.Security.SecurityElement;
-#endif // FEATURE_CAS_POLICY
using System.Globalization;
using System.Runtime.Serialization;
using System.Collections;
[OptionalField(VersionAdded = 2)]
private uint m_zones;
-#if FEATURE_REMOTING
- // This field will be populated only for non X-AD scenarios where we create a XML-ised string of the Permission
- [OptionalField(VersionAdded = 2)]
- private String m_serializedPermission;
-
- // This field is legacy info from v1.x and is never used in v2.0 and beyond: purely for serialization purposes
- private SecurityZone m_zone = SecurityZone.NoZone;
-
- [OnDeserialized]
- private void OnDeserialized(StreamingContext ctx)
- {
- if ((ctx.State & ~(StreamingContextStates.Clone|StreamingContextStates.CrossAppDomain)) != 0)
- {
- // v2.0 and beyond XML case
- if (m_serializedPermission != null)
- {
- FromXml(SecurityElement.FromString(m_serializedPermission));
- m_serializedPermission = null;
- }
- else //v1.x case where we read the m_zone value
- {
- SecurityZone = m_zone;
- m_zone = SecurityZone.NoZone;
- }
- }
-
-
- }
-
- [OnSerializing]
- private void OnSerializing(StreamingContext ctx)
- {
-
- if ((ctx.State & ~(StreamingContextStates.Clone|StreamingContextStates.CrossAppDomain)) != 0)
- {
- m_serializedPermission = ToXml().ToString(); //for the v2 and beyond case
- m_zone = SecurityZone;
-
- }
- }
- [OnSerialized]
- private void OnSerialized(StreamingContext ctx)
- {
- if ((ctx.State & ~(StreamingContextStates.Clone|StreamingContextStates.CrossAppDomain)) != 0)
- {
- m_serializedPermission = null;
- m_zone = SecurityZone.NoZone;
- }
- }
-#endif // FEATURE_REMOTING
-
//------------------------------------------------------
//
// PUBLIC CONSTRUCTORS
return new ZoneIdentityPermission(this.m_zones | that.m_zones);
}
-#if FEATURE_CAS_POLICY
- public override SecurityElement ToXml()
- {
- SecurityElement esd = CodeAccessPermission.CreatePermissionElement( this, "System.Security.Permissions.ZoneIdentityPermission" );
- if (SecurityZone != SecurityZone.NoZone)
- {
- esd.AddAttribute( "Zone", Enum.GetName( typeof( SecurityZone ), this.SecurityZone ) );
- }
- else
- {
- int nEnum = 0;
- uint nFlag;
- for(nFlag = 1; nFlag < AllZones; nFlag <<= 1)
- {
- if((m_zones & nFlag) != 0)
- {
- SecurityElement child = new SecurityElement("Zone");
- child.AddAttribute( "Zone", Enum.GetName( typeof( SecurityZone ), (SecurityZone)nEnum ) );
- esd.AddChild(child);
- }
- nEnum++;
- }
- }
- return esd;
- }
-
- public override void FromXml(SecurityElement esd)
- {
- m_zones = 0;
- CodeAccessPermission.ValidateElement( esd, this );
- String eZone = esd.Attribute( "Zone" );
- if (eZone != null)
- SecurityZone = (SecurityZone)Enum.Parse( typeof( SecurityZone ), eZone );
- if(esd.Children != null)
- {
- foreach(SecurityElement child in esd.Children)
- {
- eZone = child.Attribute( "Zone" );
- int enm = (int)Enum.Parse( typeof( SecurityZone ), eZone );
- if(enm == (int)SecurityZone.NoZone)
- continue;
- m_zones |= ((uint)1 << enm);
- }
- }
- }
-#endif // FEATURE_CAS_POLICY
-
/// <internalonly/>
int IBuiltInPermission.GetTokenIndex()
{
#endif
using System.Security.Util;
using System.Globalization;
+ using System.Diagnostics;
using System.Diagnostics.Contracts;
[Serializable]
return cp;
}
-#if FEATURE_CAS_POLICY
- public override SecurityElement ToXml () {
- SecurityElement securityElement = CodeAccessPermission.CreatePermissionElement(this, "System.Security.Permissions.KeyContainerPermission");
- if (!IsUnrestricted()) {
- securityElement.AddAttribute("Flags", m_flags.ToString());
- if (AccessEntries.Count > 0) {
- SecurityElement al = new SecurityElement("AccessList");
- foreach (KeyContainerPermissionAccessEntry accessEntry in AccessEntries) {
- SecurityElement entryElem = new SecurityElement("AccessEntry");
- entryElem.AddAttribute("KeyStore", accessEntry.KeyStore);
- entryElem.AddAttribute("ProviderName", accessEntry.ProviderName);
- entryElem.AddAttribute("ProviderType", accessEntry.ProviderType.ToString(null, null));
- entryElem.AddAttribute("KeyContainerName", accessEntry.KeyContainerName);
- entryElem.AddAttribute("KeySpec", accessEntry.KeySpec.ToString(null, null));
- entryElem.AddAttribute("Flags", accessEntry.Flags.ToString());
- al.AddChild(entryElem);
- }
- securityElement.AddChild(al);
- }
- } else
- securityElement.AddAttribute("Unrestricted", "true");
-
- return securityElement;
- }
-
- public override void FromXml (SecurityElement securityElement) {
- CodeAccessPermission.ValidateElement(securityElement, this);
- if (XMLUtil.IsUnrestricted(securityElement)) {
- m_flags = KeyContainerPermissionFlags.AllFlags;
- m_accessEntries = new KeyContainerPermissionAccessEntryCollection(m_flags);
- return;
- }
-
- m_flags = KeyContainerPermissionFlags.NoFlags;
- string strFlags = securityElement.Attribute("Flags");
- if (strFlags != null) {
- KeyContainerPermissionFlags flags = (KeyContainerPermissionFlags) Enum.Parse(typeof(KeyContainerPermissionFlags), strFlags);
- VerifyFlags(flags);
- m_flags = flags;
- }
- m_accessEntries = new KeyContainerPermissionAccessEntryCollection(m_flags);
-
- if (securityElement.InternalChildren != null && securityElement.InternalChildren.Count != 0) {
- IEnumerator enumerator = securityElement.Children.GetEnumerator();
- while (enumerator.MoveNext()) {
- SecurityElement current = (SecurityElement) enumerator.Current;
- if (current != null) {
- if (String.Equals(current.Tag, "AccessList"))
- AddAccessEntries(current);
- }
- }
- }
- }
-#endif // FEATURE_CAS_POLICY
-
/// <internalonly/>
int IBuiltInPermission.GetTokenIndex () {
return KeyContainerPermission.GetTokenIndex();
if (current != null) {
if (String.Equals(current.Tag, "AccessEntry")) {
int iMax = current.m_lAttributes.Count;
- Contract.Assert(iMax % 2 == 0, "Odd number of strings means the attr/value pairs were not added correctly");
+ Debug.Assert(iMax % 2 == 0, "Odd number of strings means the attr/value pairs were not added correctly");
string keyStore = null;
string providerName = null;
int providerType = -1;
}
}
-#pragma warning disable 618
- [SecurityPermission(SecurityAction.Demand, SerializationFormatter = true)]
-#pragma warning restore 618
- [SecuritySafeCritical]
public override EvidenceBase Clone()
{
return base.Clone();
using System;
using System.Collections;
using System.Collections.Generic;
+using System.Diagnostics;
using System.Diagnostics.Contracts;
using System.IO;
using System.Runtime.InteropServices;
/// </summary>
[ComVisible(true)]
[Serializable]
-#pragma warning disable 618
- [PermissionSet(SecurityAction.InheritanceDemand, Unrestricted = true)]
-#pragma warning restore 618
public abstract class EvidenceBase
{
protected EvidenceBase()
/// Since legacy evidence objects would be cloned by being serialized, the default implementation
/// of EvidenceBase will do the same.
/// </remarks>
-#pragma warning disable 618
- [SecurityPermission(SecurityAction.Assert, SerializationFormatter = true)]
- [PermissionSet(SecurityAction.InheritanceDemand, Unrestricted = true)]
-#pragma warning restore 618
- [SecuritySafeCritical]
public virtual EvidenceBase Clone()
{
#if FEATURE_SERIALIZATION
internal LegacyEvidenceWrapper(object legacyEvidence)
{
- Contract.Assert(legacyEvidence != null);
- Contract.Assert(legacyEvidence.GetType() != typeof(EvidenceBase), "Attempt to wrap an EvidenceBase in a LegacyEvidenceWrapper");
- Contract.Assert(legacyEvidence.GetType().IsSerializable, "legacyEvidence.GetType().IsSerializable");
+ Debug.Assert(legacyEvidence != null);
+ Debug.Assert(legacyEvidence.GetType() != typeof(EvidenceBase), "Attempt to wrap an EvidenceBase in a LegacyEvidenceWrapper");
+ Debug.Assert(legacyEvidence.GetType().IsSerializable, "legacyEvidence.GetType().IsSerializable");
m_legacyEvidence = legacyEvidence;
}
return m_legacyEvidence.GetHashCode();
}
-#pragma warning disable 618
- [SecurityPermission(SecurityAction.Demand, SerializationFormatter = true)]
-#pragma warning restore 618
- [SecuritySafeCritical]
public override EvidenceBase Clone()
{
return base.Clone();
{
get
{
- Contract.Assert(m_legacyEvidenceList.Count > 0, "No items in LegacyEvidenceList, cannot tell what type they are");
+ Debug.Assert(m_legacyEvidenceList.Count > 0, "No items in LegacyEvidenceList, cannot tell what type they are");
ILegacyEvidenceAdapter adapter = m_legacyEvidenceList[0] as ILegacyEvidenceAdapter;
return adapter == null ? m_legacyEvidenceList[0].GetType() : adapter.EvidenceType;
public void Add(EvidenceBase evidence)
{
- Contract.Assert(evidence != null);
- Contract.Assert(m_legacyEvidenceList.Count == 0 || EvidenceType == evidence.GetType() || (evidence is LegacyEvidenceWrapper && (evidence as LegacyEvidenceWrapper).EvidenceType == EvidenceType),
+ Debug.Assert(evidence != null);
+ Debug.Assert(m_legacyEvidenceList.Count == 0 || EvidenceType == evidence.GetType() || (evidence is LegacyEvidenceWrapper && (evidence as LegacyEvidenceWrapper).EvidenceType == EvidenceType),
"LegacyEvidenceList must be homogeonous");
- Contract.Assert(evidence.GetType() != typeof(LegacyEvidenceList),
+ Debug.Assert(evidence.GetType() != typeof(LegacyEvidenceList),
"Attempt to add a legacy evidence list to another legacy evidence list");
m_legacyEvidenceList.Add(evidence);
return m_legacyEvidenceList.GetEnumerator();
}
-#pragma warning disable 618
- [SecurityPermission(SecurityAction.Demand, SerializationFormatter = true)]
-#pragma warning restore 618
- [SecuritySafeCritical]
public override EvidenceBase Clone()
{
return base.Clone();
/// </summary>
private EvidenceTypeDescriptor(EvidenceTypeDescriptor descriptor)
{
- Contract.Assert(descriptor != null);
+ Debug.Assert(descriptor != null);
m_hostCanGenerate = descriptor.m_hostCanGenerate;
set
{
- Contract.Assert(value != null);
+ Debug.Assert(value != null);
#if _DEBUG
- Contract.Assert(CheckEvidenceType(value), "Incorrect type of AssemblyEvidence set");
+ Debug.Assert(CheckEvidenceType(value), "Incorrect type of AssemblyEvidence set");
#endif
m_assemblyEvidence = value;
}
set
{
- Contract.Assert(value, "Attempt to clear the Generated flag");
+ Debug.Assert(value, "Attempt to clear the Generated flag");
m_generated = value;
}
}
set
{
- Contract.Assert(value, "Attempt to clear HostCanGenerate flag");
+ Debug.Assert(value, "Attempt to clear HostCanGenerate flag");
m_hostCanGenerate = value;
}
}
set
{
- Contract.Assert(value != null);
+ Debug.Assert(value != null);
#if _DEBUG
- Contract.Assert(CheckEvidenceType(value), "Incorrect type of HostEvidence set");
+ Debug.Assert(CheckEvidenceType(value), "Incorrect type of HostEvidence set");
#endif
m_hostEvidence = value;
}
/// </summary>
private bool CheckEvidenceType(EvidenceBase evidence)
{
- Contract.Assert(evidence != null);
+ Debug.Assert(evidence != null);
ILegacyEvidenceAdapter legacyAdapter = evidence as ILegacyEvidenceAdapter;
Type storedType = legacyAdapter == null ? evidence.GetType() : legacyAdapter.EvidenceType;
/// </summary>
internal void SetEvidenceType(Type evidenceType)
{
- Contract.Assert(evidenceType != null);
- Contract.Assert(m_evidenceType == null, "Attempt to reset evidence type");
+ Debug.Assert(evidenceType != null);
+ Debug.Assert(m_evidenceType == null, "Attempt to reset evidence type");
m_evidenceType = evidenceType;
}
/// </summary>
bool IsVerified
{
- [System.Security.SecurityCritical]
get;
}
// The PermissionSet associated with this policy
internal PermissionSet m_permSet;
-#if FEATURE_CAS_POLICY
- // Evidence which was not verified but which was required to generate this policy statement.
- // This is not serialized, since once we serialize we lose the ability to verify the evidence,
- // meaning that restoring this state is meaningless.
- [NonSerialized]
- private List<IDelayEvaluatedEvidence> m_dependentEvidence;
-#endif
-
// The bitfield of inheritance properties associated with this policy
internal PolicyStatementAttribute m_attributes;
}
}
}
-
+
public PolicyStatement Copy()
{
- PolicyStatement copy = new PolicyStatement(m_permSet, Attributes, true); // The PolicyStatement .ctor will copy the permission set
-#if FEATURE_CAS_POLICY
- if (HasDependentEvidence)
- {
- copy.m_dependentEvidence = new List<IDelayEvaluatedEvidence>(m_dependentEvidence);
- }
-#endif
-
- return copy;
+ // The PolicyStatement .ctor will copy the permission set
+ return new PolicyStatement(m_permSet, Attributes, true);
}
-
+
public String AttributeString
{
get
return (flag & (int)m_attributes) != 0;
}
-#if FEATURE_CAS_POLICY
- /// <summary>
- /// Gets all of the delay evaluated evidence which needs to be verified before this policy can
- /// be used.
- /// </summary>
- internal IEnumerable<IDelayEvaluatedEvidence> DependentEvidence
- {
- get
- {
- BCLDebug.Assert(HasDependentEvidence, "HasDependentEvidence");
- return m_dependentEvidence.AsReadOnly();
- }
- }
-
- /// <summary>
- /// Determine if this policy dependent upon the evaluation of any delay evaluated evidence
- /// </summary>
- internal bool HasDependentEvidence
- {
- get { return m_dependentEvidence != null && m_dependentEvidence.Count > 0; }
- }
-
- /// <summary>
- /// Add evidence which this policy statement is depending upon being verified to be valid.
- /// </summary>
- internal void AddDependentEvidence(IDelayEvaluatedEvidence dependentEvidence)
- {
- BCLDebug.Assert(dependentEvidence != null, "dependentEvidence != null");
-
- if (m_dependentEvidence == null)
- {
- m_dependentEvidence = new List<IDelayEvaluatedEvidence>();
- }
-
- m_dependentEvidence.Add(dependentEvidence);
- }
-#endif
-
/// <summary>
/// Union a child policy statement into this policy statement
/// </summary>
throw new PolicyException(Environment.GetResourceString( "Policy_MultipleExclusive" ));
}
-#if FEATURE_CAS_POLICY
- // If our code group generated a grant set based upon unverified evidence, or it generated a grant
- // set strictly less than that of a child group based upon unverified evidence, we need to keep
- // track of any unverified evidence our child group has.
- if (childPolicy.HasDependentEvidence)
- {
- bool childEvidenceNeedsVerification = m_permSet.IsSubsetOf(childPolicy.GetPermissionSetNoCopy()) &&
- !childPolicy.GetPermissionSetNoCopy().IsSubsetOf(m_permSet);
-
- if (HasDependentEvidence || childEvidenceNeedsVerification)
- {
- if (m_dependentEvidence == null)
- {
- m_dependentEvidence = new List<IDelayEvaluatedEvidence>();
- }
-
- m_dependentEvidence.AddRange(childPolicy.DependentEvidence);
- }
- }
-#endif
-
// We need to merge together our grant set and attributes. The result of this merge is
// dependent upon if we're merging a child marked exclusive or not. If the child is not
// exclusive, we need to union in its grant set and or in its attributes. However, if the child
}
}
-#if FEATURE_CAS_POLICY
-
- public SecurityElement ToXml()
- {
- return ToXml( null );
- }
-
- public void FromXml( SecurityElement et )
- {
- FromXml( et, null );
- }
-
- public SecurityElement ToXml( PolicyLevel level )
- {
- return ToXml( level, false );
- }
-
- internal SecurityElement ToXml( PolicyLevel level, bool useInternal )
- {
- SecurityElement e = new SecurityElement( "PolicyStatement" );
- e.AddAttribute( "version", "1" );
- if (m_attributes != PolicyStatementAttribute.Nothing)
- e.AddAttribute( "Attributes", XMLUtil.BitFieldEnumToString( typeof( PolicyStatementAttribute ), m_attributes ) );
-
- lock (this)
- {
- if (m_permSet != null)
- {
- if (m_permSet is NamedPermissionSet)
- {
- // If the named permission set exists in the parent level of this
- // policy struct, then just save the name of the permission set.
- // Otherwise, serialize it like normal.
-
- NamedPermissionSet namedPermSet = (NamedPermissionSet)m_permSet;
- if (level != null && level.GetNamedPermissionSet( namedPermSet.Name ) != null)
- {
- e.AddAttribute( "PermissionSetName", namedPermSet.Name );
- }
- else
- {
- if (useInternal)
- e.AddChild( namedPermSet.InternalToXml() );
- else
- e.AddChild( namedPermSet.ToXml() );
- }
- }
- else
- {
- if (useInternal)
- e.AddChild( m_permSet.InternalToXml() );
- else
- e.AddChild( m_permSet.ToXml() );
- }
- }
- }
-
- return e;
- }
-
- [System.Security.SecuritySafeCritical] // auto-generated
- public void FromXml( SecurityElement et, PolicyLevel level )
- {
- FromXml( et, level, false );
- }
-
- [System.Security.SecurityCritical] // auto-generated
- internal void FromXml( SecurityElement et, PolicyLevel level, bool allowInternalOnly )
- {
- if (et == null)
- throw new ArgumentNullException( nameof(et) );
-
- if (!et.Tag.Equals( "PolicyStatement" ))
- throw new ArgumentException( String.Format( CultureInfo.CurrentCulture, Environment.GetResourceString( "Argument_InvalidXMLElement" ), nameof(PolicyStatement), this.GetType().FullName ) );
- Contract.EndContractBlock();
-
- m_attributes = (PolicyStatementAttribute) 0;
-
- String strAttributes = et.Attribute( "Attributes" );
-
- if (strAttributes != null)
- m_attributes = (PolicyStatementAttribute)Enum.Parse( typeof( PolicyStatementAttribute ), strAttributes );
-
- lock (this)
- {
- m_permSet = null;
-
- if (level != null)
- {
- String permSetName = et.Attribute( "PermissionSetName" );
-
- if (permSetName != null)
- {
- m_permSet = level.GetNamedPermissionSetInternal( permSetName );
-
- if (m_permSet == null)
- m_permSet = new PermissionSet( PermissionState.None );
- }
- }
-
-
- if (m_permSet == null)
- {
- // There is no provided level, it is not a named permission set, or
- // the named permission set doesn't exist in the provided level,
- // so just create the class through reflection and decode normally.
-
- SecurityElement e = et.SearchForChildByTag( "PermissionSet" );
-
- if (e != null)
- {
- String className = e.Attribute( "class" );
-
- if (className != null && (className.Equals( "NamedPermissionSet" ) ||
- className.Equals( "System.Security.NamedPermissionSet" )))
- m_permSet = new NamedPermissionSet( "DefaultName", PermissionState.None );
- else
- m_permSet = new PermissionSet( PermissionState.None );
-
- try
- {
- m_permSet.FromXml( e, allowInternalOnly, true );
- }
- catch
- {
- // ignore any exceptions from the decode process.
- // Note: we go ahead and use the permission set anyway. This should be safe since
- // the decode process should never give permission beyond what a proper decode would have
- // given.
- }
- }
- else
- {
- throw new ArgumentException( Environment.GetResourceString( "Argument_InvalidXML" ) );
- }
- }
-
- if (m_permSet == null)
- m_permSet = new PermissionSet( PermissionState.None );
- }
- }
-
-
- [System.Security.SecurityCritical] // auto-generated
- internal void FromXml( SecurityDocument doc, int position, PolicyLevel level, bool allowInternalOnly )
- {
- if (doc == null)
- throw new ArgumentNullException( nameof(doc) );
- Contract.EndContractBlock();
-
- if (!doc.GetTagForElement( position ).Equals( "PolicyStatement" ))
- throw new ArgumentException( String.Format( CultureInfo.CurrentCulture, Environment.GetResourceString( "Argument_InvalidXMLElement" ), nameof(PolicyStatement), this.GetType().FullName ) );
-
- m_attributes = (PolicyStatementAttribute) 0;
-
- String strAttributes = doc.GetAttributeForElement( position, "Attributes" );
-
- if (strAttributes != null)
- m_attributes = (PolicyStatementAttribute)Enum.Parse( typeof( PolicyStatementAttribute ), strAttributes );
-
- lock (this)
- {
- m_permSet = null;
-
- if (level != null)
- {
- String permSetName = doc.GetAttributeForElement( position, "PermissionSetName" );
-
- if (permSetName != null)
- {
- m_permSet = level.GetNamedPermissionSetInternal( permSetName );
-
- if (m_permSet == null)
- m_permSet = new PermissionSet( PermissionState.None );
- }
- }
-
-
- if (m_permSet == null)
- {
- // There is no provided level, it is not a named permission set, or
- // the named permission set doesn't exist in the provided level,
- // so just create the class through reflection and decode normally.
-
- ArrayList childPositions = doc.GetChildrenPositionForElement( position );
- int positionPermissionSet = -1;
-
- for (int i = 0; i < childPositions.Count; ++i)
- {
- if (doc.GetTagForElement( (int)childPositions[i] ).Equals( "PermissionSet" ))
- {
- positionPermissionSet = (int)childPositions[i];
- }
- }
-
- if (positionPermissionSet != -1)
- {
- String className = doc.GetAttributeForElement( positionPermissionSet, "class" );
-
- if (className != null && (className.Equals( "NamedPermissionSet" ) ||
- className.Equals( "System.Security.NamedPermissionSet" )))
- m_permSet = new NamedPermissionSet( "DefaultName", PermissionState.None );
- else
- m_permSet = new PermissionSet( PermissionState.None );
-
- m_permSet.FromXml( doc, positionPermissionSet, allowInternalOnly );
- }
- else
- {
- throw new ArgumentException( Environment.GetResourceString( "Argument_InvalidXML" ) );
- }
- }
-
- if (m_permSet == null)
- m_permSet = new PermissionSet( PermissionState.None );
- }
- }
-#endif // FEATURE_CAS_POLICY
-
-
[System.Runtime.InteropServices.ComVisible(false)]
public override bool Equals( Object obj )
{
//
using System;
+using System.Diagnostics;
using System.Diagnostics.Contracts;
using System.Globalization;
using System.Security.Permissions;
private Site(SiteString name)
{
- Contract.Assert(name != null);
+ Debug.Assert(name != null);
m_name = name;
}
return Clone();
}
-#if FEATURE_CAS_POLICY
- internal SecurityElement ToXml()
- {
- SecurityElement elem = new SecurityElement( "System.Security.Policy.Site" );
- // If you hit this assert then most likely you are trying to change the name of this class.
- // This is ok as long as you change the hard coded string above and change the assert below.
- Contract.Assert( this.GetType().FullName.Equals( "System.Security.Policy.Site" ), "Class name changed!" );
-
- elem.AddAttribute( "version", "1" );
-
- if(m_name != null)
- elem.AddChild( new SecurityElement( "Name", m_name.ToString() ) );
-
- return elem;
- }
-#endif // FEATURE_CAS_POLICY
-
-#if FEATURE_CAS_POLICY
- public override String ToString()
- {
- return ToXml().ToString();
- }
-#endif // FEATURE_CAS_POLICY
-
// INormalizeForIsolatedStorage is not implemented for startup perf
// equivalent to INormalizeForIsolatedStorage.Normalize()
internal Object Normalize()
bool IDelayEvaluatedEvidence.IsVerified
{
- [System.Security.SecurityCritical] // auto-generated
get
{
-#if FEATURE_CAS_POLICY
- return m_assembly != null ? m_assembly.IsStrongNameVerified : true;
-#else // !FEATURE_CAS_POLICY
return true;
-#endif // FEATURE_CAS_POLICY
}
}
return Clone();
}
-#if FEATURE_CAS_POLICY
- internal SecurityElement ToXml()
- {
- SecurityElement root = new SecurityElement( "StrongName" );
- root.AddAttribute( "version", "1" );
-
- if (m_publicKeyBlob != null)
- root.AddAttribute( "Key", System.Security.Util.Hex.EncodeHexString( m_publicKeyBlob.PublicKey ) );
-
- if (m_name != null)
- root.AddAttribute( "Name", m_name );
-
- if (m_version != null)
- root.AddAttribute( "Version", m_version.ToString() );
-
- return root;
- }
-
- internal void FromXml (SecurityElement element)
- {
- if (element == null)
- throw new ArgumentNullException(nameof(element));
- if (String.Compare(element.Tag, "StrongName", StringComparison.Ordinal) != 0)
- throw new ArgumentException(Environment.GetResourceString("Argument_InvalidXML"));
- Contract.EndContractBlock();
-
- m_publicKeyBlob = null;
- m_version = null;
-
- string key = element.Attribute("Key");
- if (key != null)
- m_publicKeyBlob = new StrongNamePublicKeyBlob(System.Security.Util.Hex.DecodeHexString(key));
-
- m_name = element.Attribute("Name");
-
- string version = element.Attribute("Version");
- if (version != null)
- m_version = new Version(version);
- }
-
- public override String ToString()
- {
- return ToXml().ToString();
- }
-#endif // FEATURE_CAS_POLICY
-
public override bool Equals( Object o )
{
StrongName that = (o as StrongName);
using System.Security.Util;
using UrlIdentityPermission = System.Security.Permissions.UrlIdentityPermission;
using System.Runtime.Serialization;
+ using System.Diagnostics;
using System.Diagnostics.Contracts;
[Serializable]
private Url(Url url)
{
- Contract.Assert(url != null);
+ Debug.Assert(url != null);
m_url = url.m_url;
}
return Clone();
}
-#if FEATURE_CAS_POLICY
- internal SecurityElement ToXml()
- {
- SecurityElement root = new SecurityElement( "System.Security.Policy.Url" );
- // If you hit this assert then most likely you are trying to change the name of this class.
- // This is ok as long as you change the hard coded string above and change the assert below.
- Contract.Assert( this.GetType().FullName.Equals( "System.Security.Policy.Url" ), "Class name changed!" );
-
- root.AddAttribute( "version", "1" );
-
- if (m_url != null)
- root.AddChild( new SecurityElement( "Url", m_url.ToString() ) );
-
- return root;
- }
-
- public override String ToString()
- {
- return ToXml().ToString();
- }
-#endif // FEATURE_CAS_POLICY
-
// INormalizeForIsolatedStorage is not implemented for startup perf
// equivalent to INormalizeForIsolatedStorage.Normalize()
internal Object Normalize()
// Zone is an IIdentity representing Internet/Intranet/MyComputer etc.
//
-namespace System.Security.Policy {
+namespace System.Security.Policy
+{
using System.Security.Util;
using ZoneIdentityPermission = System.Security.Permissions.ZoneIdentityPermission;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Runtime.Versioning;
using System.Runtime.Serialization;
+ using System.Diagnostics;
using System.Diagnostics.Contracts;
[Serializable]
[System.Runtime.InteropServices.ComVisible(true)]
public sealed class Zone : EvidenceBase, IIdentityPermissionFactory
{
-#if FEATURE_CAS_POLICY
- [OptionalField(VersionAdded = 2)]
- private String m_url;
-#endif // FEATURE_CAS_POLICY
private SecurityZone m_zone;
private static readonly String[] s_names =
private Zone(Zone zone)
{
- Contract.Assert(zone != null);
-
-#if FEATURE_CAS_POLICY
- m_url = zone.m_url;
-#endif // FEATURE_CAS_POLICY
+ Debug.Assert(zone != null);
m_zone = zone.m_zone;
}
-#if FEATURE_CAS_POLICY
- private Zone(String url)
- {
- m_url = url;
- m_zone = SecurityZone.NoZone;
- }
-
- public static Zone CreateFromUrl( String url )
- {
- if (url == null)
- throw new ArgumentNullException( nameof(url) );
- Contract.EndContractBlock();
-
- return new Zone( url );
- }
-
- [System.Security.SecurityCritical] // auto-generated
- [DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
- [SuppressUnmanagedCodeSecurity]
- private extern static SecurityZone _CreateFromUrl( String url );
-#endif // FEATURE_CAS_POLICY
-
public IPermission CreateIdentityPermission( Evidence evidence )
{
return new ZoneIdentityPermission( SecurityZone );
public SecurityZone SecurityZone
{
- [System.Security.SecuritySafeCritical] // auto-generated
get
{
-#if FEATURE_CAS_POLICY
- if (m_url != null)
- m_zone = _CreateFromUrl( m_url );
-#endif // FEATURE_CAS_POLICY
-
return m_zone;
}
}
return Clone();
}
-#if FEATURE_CAS_POLICY
- internal SecurityElement ToXml()
- {
- SecurityElement elem = new SecurityElement( "System.Security.Policy.Zone" );
- // If you hit this assert then most likely you are trying to change the name of this class.
- // This is ok as long as you change the hard coded string above and change the assert below.
- Contract.Assert( this.GetType().FullName.Equals( "System.Security.Policy.Zone" ), "Class name changed!" );
-
- elem.AddAttribute( "version", "1" );
- if (SecurityZone != SecurityZone.NoZone)
- elem.AddChild( new SecurityElement( "Zone", s_names[(int)SecurityZone] ) );
- else
- elem.AddChild( new SecurityElement( "Zone", s_names[s_names.Length-1] ) );
- return elem;
- }
-#endif // FEATURE_CAS_POLICY
-
-#if FEATURE_CAS_POLICY
- public override String ToString()
- {
- return ToXml().ToString();
- }
-#endif // FEATURE_CAS_POLICY
-
// INormalizeForIsolatedStorage is not implemented for startup perf
// equivalent to INormalizeForIsolatedStorage.Normalize()
internal Object Normalize()
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
-//
-
namespace System.Security.Principal
{
-#if !FEATURE_CORECLR
- [Serializable]
- [System.Runtime.InteropServices.ComVisible(true)]
-#endif
- public enum TokenImpersonationLevel {
+ public enum TokenImpersonationLevel
+ {
None = 0,
Anonymous = 1,
Identification = 2,
// Introduce this handle to replace internal SafeTokenHandle,
// which is mainly used to hold Windows thread or process access token
- [SecurityCritical]
public sealed class SafeAccessTokenHandle : SafeHandle
{
private SafeAccessTokenHandle()
public static SafeAccessTokenHandle InvalidHandle
{
- [SecurityCritical]
get { return new SafeAccessTokenHandle(IntPtr.Zero); }
}
public override bool IsInvalid
{
- [SecurityCritical]
get { return handle == IntPtr.Zero || handle == new IntPtr(-1); }
}
- [SecurityCritical]
protected override bool ReleaseHandle()
{
return Win32Native.CloseHandle(handle);
}
}
- [System.Security.SecurityCritical] // auto-generated
internal sealed class SafeLsaLogonProcessHandle : SafeHandleZeroOrMinusOneIsInvalid {
private SafeLsaLogonProcessHandle() : base (true) {}
get { return new SafeLsaLogonProcessHandle(IntPtr.Zero); }
}
- [System.Security.SecurityCritical]
override protected bool ReleaseHandle()
{
// LsaDeregisterLogonProcess returns an NTSTATUS
}
}
- [System.Security.SecurityCritical] // auto-generated
internal sealed class SafeLsaMemoryHandle : SafeBuffer {
private SafeLsaMemoryHandle() : base(true) {}
get { return new SafeLsaMemoryHandle( IntPtr.Zero ); }
}
- [System.Security.SecurityCritical]
override protected bool ReleaseHandle()
{
return Win32Native.LsaFreeMemory(handle) == 0;
}
}
- [System.Security.SecurityCritical] // auto-generated
internal sealed class SafeLsaPolicyHandle : SafeHandleZeroOrMinusOneIsInvalid {
private SafeLsaPolicyHandle() : base(true) {}
get { return new SafeLsaPolicyHandle( IntPtr.Zero ); }
}
- [System.Security.SecurityCritical]
override protected bool ReleaseHandle()
{
return Win32Native.LsaClose(handle) == 0;
}
}
- [System.Security.SecurityCritical] // auto-generated
internal sealed class SafeLsaReturnBufferHandle : SafeBuffer {
private SafeLsaReturnBufferHandle() : base (true) {}
get { return new SafeLsaReturnBufferHandle(IntPtr.Zero); }
}
- [System.Security.SecurityCritical]
override protected bool ReleaseHandle()
{
// LsaFreeReturnBuffer returns an NTSTATUS
}
}
- [System.Security.SecurityCritical] // auto-generated
internal sealed class SafeProcessHandle : SafeHandleZeroOrMinusOneIsInvalid {
private SafeProcessHandle() : base (true) {}
get { return new SafeProcessHandle(IntPtr.Zero); }
}
- [System.Security.SecurityCritical]
override protected bool ReleaseHandle()
{
return Win32Native.CloseHandle(handle);
}
}
- [System.Security.SecurityCritical] // auto-generated
internal sealed class SafeThreadHandle : SafeHandleZeroOrMinusOneIsInvalid {
private SafeThreadHandle() : base (true) {}
SetHandle(handle);
}
- [System.Security.SecurityCritical]
override protected bool ReleaseHandle()
{
return Win32Native.CloseHandle(handle);
#endif // FEATURE_CORRUPTING_EXCEPTIONS
using System.Runtime.ConstrainedExecution;
using System.Runtime.Versioning;
+ using System.Diagnostics;
using System.Diagnostics.Contracts;
// This enum must be kept in sync with the SecurityContextSource enum in the VM
internal ExecutionContext currEC; // current ExecutionContext on Thread
internal CompressedStackSwitcher cssw;
- [System.Security.SecuritySafeCritical] // overrides public transparent member
public void Dispose()
{
Undo();
}
- [System.Security.SecurityCritical] // auto-generated
[ReliabilityContract(Consistency.WillNotCorruptState, Cer.MayFail)]
#if FEATURE_CORRUPTING_EXCEPTIONS
[HandleProcessCorruptedStateExceptions]
return true;
}
- [System.Security.SecurityCritical] // auto-generated
[ReliabilityContract(Consistency.WillNotCorruptState, Cer.MayFail)]
#if FEATURE_CORRUPTING_EXCEPTIONS
[HandleProcessCorruptedStateExceptions]
if (currEC != null)
{
- Contract.Assert(currEC == Thread.CurrentThread.GetMutableExecutionContext(), "SecurityContextSwitcher used from another thread");
- Contract.Assert(currSC == currEC.SecurityContext, "SecurityContextSwitcher context mismatch");
+ Debug.Assert(currEC == Thread.CurrentThread.GetMutableExecutionContext(), "SecurityContextSwitcher used from another thread");
+ Debug.Assert(currSC == currEC.SecurityContext, "SecurityContextSwitcher context mismatch");
// restore the saved security context
currEC.SecurityContext = prevSC.DangerousGetRawSecurityContext();
else
{
// caller must have already restored the ExecutionContext
- Contract.Assert(Thread.CurrentThread.GetExecutionContextReader().SecurityContext.IsSame(prevSC));
+ Debug.Assert(Thread.CurrentThread.GetExecutionContextReader().SecurityContext.IsSame(prevSC));
}
currSC = null; // this will prevent the switcher object being used again
static internal SecurityContext FullTrustSecurityContext
{
- [System.Security.SecurityCritical] // auto-generated
get
{
if (_fullTrustSC == null)
{
}
- [System.Security.SecurityCritical] // auto-generated_required
public static AsyncFlowControl SuppressFlow()
{
return SuppressFlow(SecurityContextDisableFlow.All);
}
- [System.Security.SecurityCritical] // auto-generated_required
public static AsyncFlowControl SuppressFlowWindowsIdentity()
{
return SuppressFlow(SecurityContextDisableFlow.WI);
}
- [SecurityCritical]
internal static AsyncFlowControl SuppressFlow(SecurityContextDisableFlow flags)
{
if (IsFlowSuppressed(flags))
return afc;
}
- [SecuritySafeCritical]
public static void RestoreFlow()
{
SecurityContext sc = Thread.CurrentThread.GetMutableExecutionContext().SecurityContext;
return SecurityContext.IsFlowSuppressed(SecurityContextDisableFlow.All);
}
- [SecuritySafeCritical]
internal static bool IsFlowSuppressed(SecurityContextDisableFlow flags)
{
return Thread.CurrentThread.GetExecutionContextReader().SecurityContext.IsFlowSuppressed(flags);
// continue past the call to SecurityContext.Run. If you change the signature to this method, or
// provide an alternate way to do a SecurityContext.Run make sure to update
// SecurityStackWalk::IsSpecialRunFrame in the VM to search for the new method.
- [System.Security.SecurityCritical] // auto-generated_required
[DynamicSecurityMethodAttribute()]
[MethodImplAttribute(MethodImplOptions.NoInlining)] // Methods containing StackCrawlMark local var has to be marked non-inlineable
public static void Run(SecurityContext securityContext, ContextCallback callback, Object state)
// and automatically goes away when the callback returns.
WindowsIdentity.SafeRevertToSelf(ref stackMark);
// Ensure we have reverted to the state we entered in.
- Contract.Assert(GetCurrentWI(Thread.CurrentThread.GetExecutionContextReader()) == null);
+ Debug.Assert(GetCurrentWI(Thread.CurrentThread.GetExecutionContextReader()) == null);
}
}
else
}
}
- [System.Security.SecurityCritical] // auto-generated
internal static void RunInternal(SecurityContext securityContext, ContextCallback callBack, Object state)
{
if (cleanupCode == null)
}
}
- [System.Security.SecurityCritical] // auto-generated
static internal void runTryCode(Object userData)
{
SecurityContextRunData rData = (SecurityContextRunData) userData;
}
- [System.Security.SecurityCritical] // auto-generated
[PrePrepareMethod]
static internal void runFinallyCode(Object userData, bool exceptionThrown)
{
// Internal API that gets called from public SetSecurityContext and from SetExecutionContext
[ReliabilityContract(Consistency.WillNotCorruptState, Cer.MayFail)]
- [System.Security.SecurityCritical] // auto-generated
[DynamicSecurityMethodAttribute()]
[MethodImplAttribute(MethodImplOptions.NoInlining)] // Methods containing StackCrawlMark local var has to be marked non-inlineable
internal static SecurityContextSwitcher SetSecurityContext(SecurityContext sc, SecurityContext.Reader prevSecurityContext, bool modifyCurrentExecutionContext)
return SetSecurityContext(sc, prevSecurityContext, modifyCurrentExecutionContext, ref stackMark);
}
- [System.Security.SecurityCritical] // auto-generated
#if FEATURE_CORRUPTING_EXCEPTIONS
[HandleProcessCorruptedStateExceptions]
#endif // FEATURE_CORRUPTING_EXCEPTIONS
}
/// <internalonly/>
- [System.Security.SecuritySafeCritical] // auto-generated
public SecurityContext CreateCopy()
{
if (!isNewCapture)
}
/// <internalonly/>
- [System.Security.SecuritySafeCritical] // auto-generated
internal SecurityContext CreateMutableCopy()
{
- Contract.Assert(!this.isNewCapture);
+ Debug.Assert(!this.isNewCapture);
SecurityContext sc = new SecurityContext();
sc._disableFlow = this._disableFlow;
return sc;
}
- [System.Security.SecuritySafeCritical] // auto-generated
[MethodImplAttribute(MethodImplOptions.NoInlining)] // Methods containing StackCrawlMark local var has to be marked non-inlineable
public static SecurityContext Capture( )
{
}
// create a clone from a non-existing SecurityContext
- [System.Security.SecurityCritical] // auto-generated
[MethodImpl(MethodImplOptions.AggressiveInlining)]
static internal SecurityContext Capture(ExecutionContext.Reader currThreadEC, ref StackCrawlMark stackMark)
{
return CaptureCore(currThreadEC, ref stackMark);
}
- [System.Security.SecurityCritical] // auto-generated
static private SecurityContext CaptureCore(ExecutionContext.Reader currThreadEC, ref StackCrawlMark stackMark)
{
SecurityContext sc = new SecurityContext();
return sc;
}
- [System.Security.SecurityCritical] // auto-generated
static internal SecurityContext CreateFullTrustSecurityContext()
{
SecurityContext sc = new SecurityContext();
return (IsDefaultThreadSecurityInfo());
}
- [System.Security.SecurityCritical] // auto-generated
[MethodImplAttribute(MethodImplOptions.InternalCall), ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)]
internal extern static bool IsDefaultThreadSecurityInfo();
}
using System.Globalization;
using System.IO;
using System.Security.Permissions;
+ using System.Diagnostics;
using System.Diagnostics.Contracts;
internal enum SecurityElementType
return ((SecurityElement)this).Attribute( attributeName );
}
-//////////////
-
-#if FEATURE_CAS_POLICY
- public static SecurityElement FromString( String xml )
- {
- if (xml == null)
- throw new ArgumentNullException( nameof(xml) );
- Contract.EndContractBlock();
-
- return new Parser( xml ).GetTopElement();
- }
-#endif // FEATURE_CAS_POLICY
-
public SecurityElement( String tag )
{
if (tag == null)
Hashtable hashtable = new Hashtable( m_lAttributes.Count/2 );
int iMax = m_lAttributes.Count;
- Contract.Assert( iMax % 2 == 0, "Odd number of strings means the attr/value pairs were not added correctly" );
+ Debug.Assert( iMax % 2 == 0, "Odd number of strings means the attr/value pairs were not added correctly" );
for (int i = 0; i < iMax; i += 2)
{
else
{
int iMax = m_lAttributes.Count;
- Contract.Assert( iMax % 2 == 0, "Odd number of strings means the attr/value pairs were not added correctly" );
+ Debug.Assert( iMax % 2 == 0, "Odd number of strings means the attr/value pairs were not added correctly" );
for (int i = 0; i < iMax; i += 2)
{
else
{
int iMax = m_lAttributes.Count;
- Contract.Assert( iMax % 2 == 0, "Odd number of strings means the attr/value pairs were not added correctly" );
+ Debug.Assert( iMax % 2 == 0, "Odd number of strings means the attr/value pairs were not added correctly" );
if (iMax != other.m_lAttributes.Count)
return false;
private static String GetEscapeSequence( char c )
{
int iMax = s_escapeStringPairs.Length;
- Contract.Assert( iMax % 2 == 0, "Odd number of strings means the attr/value pairs were not added correctly" );
+ Debug.Assert( iMax % 2 == 0, "Odd number of strings means the attr/value pairs were not added correctly" );
for (int i = 0; i < iMax; i += 2)
{
return strEscValue;
}
- Contract.Assert( false, "Unable to find escape sequence for this character" );
+ Debug.Assert( false, "Unable to find escape sequence for this character" );
return c.ToString();
}
int maxCompareLength = str.Length - index;
int iMax = s_escapeStringPairs.Length;
- Contract.Assert( iMax % 2 == 0, "Odd number of strings means the attr/value pairs were not added correctly" );
+ Debug.Assert( iMax % 2 == 0, "Odd number of strings means the attr/value pairs were not added correctly" );
for (int i = 0; i < iMax; i += 2)
{
while (true);
// C# reports a warning if I leave this in, but I still kinda want to just in case.
- // Contract.Assert( false, "If you got here, the execution engine or compiler is really confused" );
+ // Debug.Assert( false, "If you got here, the execution engine or compiler is really confused" );
// return str;
}
return sb.ToString();
}
-#if !FEATURE_CORECLR
- private static void ToStringHelperStreamWriter(Object obj, String str)
- {
- ((StreamWriter)obj).Write(str);
- }
-
- internal void ToWriter( StreamWriter writer )
- {
- ToString( "", writer, new ToStringHelperFunc( ToStringHelperStreamWriter ) );
- }
-#endif
-
private void ToString( String indent, Object obj, ToStringHelperFunc func )
{
// First add the indent
- // func( obj, indent );
+ // func( obj, indent );
// Add in the opening bracket and the tag.
func( obj, " " );
int iMax = m_lAttributes.Count;
- Contract.Assert( iMax % 2 == 0, "Odd number of strings means the attr/value pairs were not added correctly" );
+ Debug.Assert( iMax % 2 == 0, "Odd number of strings means the attr/value pairs were not added correctly" );
for (int i = 0; i < iMax; i += 2)
{
// the one we are asked for
int iMax = m_lAttributes.Count;
- Contract.Assert( iMax % 2 == 0, "Odd number of strings means the attr/value pairs were not added correctly" );
+ Debug.Assert( iMax % 2 == 0, "Odd number of strings means the attr/value pairs were not added correctly" );
for (int i = 0; i < iMax; i += 2)
{
return null;
}
-#if FEATURE_CAS_POLICY
- internal IPermission ToPermission(bool ignoreTypeLoadFailures)
- {
- IPermission ip = XMLUtil.CreatePermission( this, PermissionState.None, ignoreTypeLoadFailures );
- if (ip == null)
- return null;
- ip.FromXml(this);
-
- // Get the permission token here to ensure that the token
- // type is updated appropriately now that we've loaded the type.
- PermissionToken token = PermissionToken.GetToken( ip );
- Contract.Assert((token.m_type & PermissionTokenType.DontKnow) == 0, "Token type not properly assigned");
-
- return ip;
- }
-
- [System.Security.SecurityCritical] // auto-generated
- internal Object ToSecurityObject()
- {
- switch (m_strTag)
- {
- case "PermissionSet":
- PermissionSet pset = new PermissionSet(PermissionState.None);
- pset.FromXml(this);
- return pset;
-
- default:
- return ToPermission(false);
- }
- }
-#endif // FEATURE_CAS_POLICY
-
internal String SearchForTextOfLocalName(String strLocalName)
{
// Search on each child in order and each
[Serializable]
public class SecurityException : SystemException
{
-#if FEATURE_CAS_POLICY
- private String m_debugString; // NOTE: If you change the name of this field, you'll have to update SOS as well!
- private SecurityAction m_action;
- [NonSerialized] private Type m_typeOfPermissionThatFailed;
- private String m_permissionThatFailed;
- private String m_demanded;
- private String m_granted;
- private String m_refused;
- private String m_denied;
- private String m_permitOnly;
- private AssemblyName m_assemblyName;
- private byte[] m_serializedMethodInfo;
- private String m_strMethodInfo;
- private SecurityZone m_zone;
- private String m_url;
-
- private const String ActionName = "Action";
- private const String FirstPermissionThatFailedName = "FirstPermissionThatFailed";
- private const String DemandedName = "Demanded";
- private const String GrantedSetName = "GrantedSet";
- private const String RefusedSetName = "RefusedSet";
- private const String DeniedName = "Denied";
- private const String PermitOnlyName = "PermitOnly";
- private const String Assembly_Name = "Assembly";
- private const String MethodName_Serialized = "Method";
- private const String MethodName_String = "Method_String";
- private const String ZoneName = "Zone";
- private const String UrlName = "Url";
-#endif // #if FEATURE_CAS_POLICY
-
- [System.Security.SecuritySafeCritical] // auto-generated
internal static string GetResString(string sResourceName)
{
PermissionSet.s_fullTrust.Assert();
return Environment.GetResourceString(sResourceName);
}
- [System.Security.SecurityCritical] // auto-generated
#pragma warning disable 618
internal static Exception MakeSecurityException(AssemblyName asmName, Evidence asmEvidence, PermissionSet granted, PermissionSet refused, RuntimeMethodHandleInternal rmh, SecurityAction action, Object demand, IPermission permThatFailed)
#pragma warning restore 618
{
-#if FEATURE_CAS_POLICY
- // See if we need to throw a HostProtectionException instead
- HostProtectionPermission hostProtectionPerm = permThatFailed as HostProtectionPermission;
- if(hostProtectionPerm != null)
- return new HostProtectionException(GetResString("HostProtection_HostProtection"), HostProtectionPermission.protectedResources, hostProtectionPerm.Resources);
-
- // Produce relevant strings
- String message = "";
- MethodInfo method = null;
- try
- {
- if(granted == null && refused == null && demand == null)
- {
- message = GetResString("Security_NoAPTCA");
- }
- else
- {
- if(demand != null && demand is IPermission)
- message = String.Format(CultureInfo.InvariantCulture, GetResString("Security_Generic"), demand.GetType().AssemblyQualifiedName );
- else if (permThatFailed != null)
- message = String.Format(CultureInfo.InvariantCulture, GetResString("Security_Generic"), permThatFailed.GetType().AssemblyQualifiedName);
- else
- message = GetResString("Security_GenericNoType");
- }
-
- method = SecurityRuntime.GetMethodInfo(rmh);
- }
- catch(Exception e)
- {
- // Environment.GetResourceString will throw if we are ReadyForAbort (thread abort). (We shouldn't do a Contract.Assert in this case or it will lock up the thread.)
- if(e is System.Threading.ThreadAbortException)
- throw;
- }
-
-/* catch(System.Threading.ThreadAbortException)
- {
- // Environment.GetResourceString will throw if we are ReadyForAbort (thread abort). (We shouldn't do a BCLDebug.Assert in this case or it will lock up the thread.)
- throw;
- }
- catch
- {
- }
-*/
- // make the exception object
- return new SecurityException(message, asmName, granted, refused, method, action, demand, permThatFailed, asmEvidence);
-#else
return new SecurityException(GetResString("Arg_SecurityException"));
-#endif
-
}
-#if FEATURE_CAS_POLICY
- private static byte[] ObjectToByteArray(Object obj)
- {
- if(obj == null)
- return null;
- MemoryStream stream = new MemoryStream();
- BinaryFormatter formatter = new BinaryFormatter();
- try {
- formatter.Serialize(stream, obj);
- byte[] array = stream.ToArray();
- return array;
- } catch (NotSupportedException) {
- // Serialization of certain methods is not supported (namely
- // global methods, since they have no representation outside of
- // a module scope).
- return null;
- }
- }
-
- private static Object ByteArrayToObject(byte[] array)
- {
- if(array == null || array.Length == 0)
- return null;
- MemoryStream stream = new MemoryStream(array);
- BinaryFormatter formatter = new BinaryFormatter();
- Object obj = formatter.Deserialize(stream);
- return obj;
- }
-#endif // FEATURE_CAS_POLICY
-
public SecurityException()
: base(GetResString("Arg_SecurityException"))
{
SetErrorCode(System.__HResults.COR_E_SECURITY);
}
-#if FEATURE_CAS_POLICY
- [System.Security.SecuritySafeCritical] // auto-generated
- public SecurityException(String message, Type type )
- : base(message)
- {
- PermissionSet.s_fullTrust.Assert();
- SetErrorCode(System.__HResults.COR_E_SECURITY);
- m_typeOfPermissionThatFailed = type;
- }
-
- // *** Don't use this constructor internally ***
- [System.Security.SecuritySafeCritical] // auto-generated
- public SecurityException(String message, Type type, String state )
- : base(message)
- {
- PermissionSet.s_fullTrust.Assert();
- SetErrorCode(System.__HResults.COR_E_SECURITY);
- m_typeOfPermissionThatFailed = type;
- m_demanded = state;
- }
-#endif //FEATURE_CAS_POLICY
-
public SecurityException(String message, Exception inner)
: base(message, inner)
{
SetErrorCode(System.__HResults.COR_E_SECURITY);
}
-#if FEATURE_CAS_POLICY
- // *** Don't use this constructor internally ***
- [System.Security.SecurityCritical] // auto-generated
- internal SecurityException( PermissionSet grantedSetObj, PermissionSet refusedSetObj )
- : base(GetResString("Arg_SecurityException"))
- {
- PermissionSet.s_fullTrust.Assert();
- SetErrorCode(System.__HResults.COR_E_SECURITY);
- if (grantedSetObj != null)
- m_granted = grantedSetObj.ToXml().ToString();
- if (refusedSetObj != null)
- m_refused = refusedSetObj.ToXml().ToString();
- }
-
- // *** Don't use this constructor internally ***
- [System.Security.SecurityCritical] // auto-generated
- internal SecurityException( String message, PermissionSet grantedSetObj, PermissionSet refusedSetObj )
- : base(message)
- {
- PermissionSet.s_fullTrust.Assert();
- SetErrorCode(System.__HResults.COR_E_SECURITY);
- if (grantedSetObj != null)
- m_granted = grantedSetObj.ToXml().ToString();
- if (refusedSetObj != null)
- m_refused = refusedSetObj.ToXml().ToString();
- }
-
- [System.Security.SecuritySafeCritical] // auto-generated
- protected SecurityException(SerializationInfo info, StreamingContext context) : base (info, context)
- {
- if (info==null)
- throw new ArgumentNullException(nameof(info));
- Contract.EndContractBlock();
-
- try
- {
- m_action = (SecurityAction)info.GetValue(ActionName, typeof(SecurityAction));
- m_permissionThatFailed = (String)info.GetValueNoThrow(FirstPermissionThatFailedName, typeof(String));
- m_demanded = (String)info.GetValueNoThrow(DemandedName, typeof(String));
- m_granted = (String)info.GetValueNoThrow(GrantedSetName, typeof(String));
- m_refused = (String)info.GetValueNoThrow(RefusedSetName, typeof(String));
- m_denied = (String)info.GetValueNoThrow(DeniedName, typeof(String));
- m_permitOnly = (String)info.GetValueNoThrow(PermitOnlyName, typeof(String));
- m_assemblyName = (AssemblyName)info.GetValueNoThrow(Assembly_Name, typeof(AssemblyName));
- m_serializedMethodInfo = (byte[])info.GetValueNoThrow(MethodName_Serialized, typeof(byte[]));
- m_strMethodInfo = (String)info.GetValueNoThrow(MethodName_String, typeof(String));
- m_zone = (SecurityZone)info.GetValue(ZoneName, typeof(SecurityZone));
- m_url = (String)info.GetValueNoThrow(UrlName, typeof(String));
- }
- catch
- {
- m_action = 0;
- m_permissionThatFailed = "";
- m_demanded = "";
- m_granted = "";
- m_refused = "";
- m_denied = "";
- m_permitOnly = "";
- m_assemblyName = null;
- m_serializedMethodInfo = null;
- m_strMethodInfo = null;
- m_zone = SecurityZone.NoZone;
- m_url = "";
- }
- }
-
- // ------------------------------------------
- // | For failures due to insufficient grant |
- // ------------------------------------------
- [System.Security.SecuritySafeCritical] // auto-generated
- public SecurityException(string message, AssemblyName assemblyName, PermissionSet grant, PermissionSet refused, MethodInfo method, SecurityAction action, Object demanded, IPermission permThatFailed, Evidence evidence)
- : base(message)
- {
- PermissionSet.s_fullTrust.Assert();
- SetErrorCode(System.__HResults.COR_E_SECURITY);
- Action = action;
- if(permThatFailed != null)
- m_typeOfPermissionThatFailed = permThatFailed.GetType();
- FirstPermissionThatFailed = permThatFailed;
- Demanded = demanded;
- m_granted = (grant == null ? "" : grant.ToXml().ToString());
- m_refused = (refused == null ? "" : refused.ToXml().ToString());
- m_denied = "";
- m_permitOnly = "";
- m_assemblyName = assemblyName;
- Method = method;
- m_url = "";
- m_zone = SecurityZone.NoZone;
- if(evidence != null)
- {
- Url url = evidence.GetHostEvidence<Url>();
- if(url != null)
- m_url = url.GetURLString().ToString();
- Zone zone = evidence.GetHostEvidence<Zone>();
- if(zone != null)
- m_zone = zone.SecurityZone;
- }
- m_debugString = this.ToString(true, false);
- }
-
- // ------------------------------------------
- // | For failures due to deny or PermitOnly |
- // ------------------------------------------
- [System.Security.SecuritySafeCritical] // auto-generated
- public SecurityException(string message, Object deny, Object permitOnly, MethodInfo method, Object demanded, IPermission permThatFailed)
- : base(message)
- {
- PermissionSet.s_fullTrust.Assert();
- SetErrorCode(System.__HResults.COR_E_SECURITY);
- Action = SecurityAction.Demand;
- if(permThatFailed != null)
- m_typeOfPermissionThatFailed = permThatFailed.GetType();
- FirstPermissionThatFailed = permThatFailed;
- Demanded = demanded;
- m_granted = "";
- m_refused = "";
- DenySetInstance = deny;
- PermitOnlySetInstance = permitOnly;
- m_assemblyName = null;
- Method = method;
- m_zone = SecurityZone.NoZone;
- m_url = "";
- m_debugString = this.ToString(true, false);
- }
-
-
-
-
-
-
-
-
-
-
-
- [System.Runtime.InteropServices.ComVisible(false)]
- public SecurityAction Action
- {
- get
- {
- return m_action;
- }
-
- set
- {
- m_action = value;
- }
- }
-
- public Type PermissionType
- {
- [System.Security.SecuritySafeCritical] // auto-generated
- get
- {
- if(m_typeOfPermissionThatFailed == null)
- {
- Object ob = XMLUtil.XmlStringToSecurityObject(m_permissionThatFailed);
- if(ob == null)
- ob = XMLUtil.XmlStringToSecurityObject(m_demanded);
- if(ob != null)
- m_typeOfPermissionThatFailed = ob.GetType();
- }
- return m_typeOfPermissionThatFailed;
- }
-
- set
- {
- m_typeOfPermissionThatFailed = value;
- }
- }
-
- public IPermission FirstPermissionThatFailed
- {
- [System.Security.SecuritySafeCritical] // auto-generated
- [SecurityPermissionAttribute( SecurityAction.Demand, Flags = SecurityPermissionFlag.ControlEvidence | SecurityPermissionFlag.ControlPolicy)]
- get
- {
- return (IPermission)XMLUtil.XmlStringToSecurityObject(m_permissionThatFailed);
- }
-
- set
- {
- m_permissionThatFailed = XMLUtil.SecurityObjectToXmlString(value);
- }
- }
-
- public String PermissionState
- {
- [System.Security.SecuritySafeCritical] // auto-generated
- [SecurityPermissionAttribute( SecurityAction.Demand, Flags = SecurityPermissionFlag.ControlEvidence | SecurityPermissionFlag.ControlPolicy)]
- get
- {
- return m_demanded;
- }
-
- set
- {
- m_demanded = value;
- }
- }
-
- [System.Runtime.InteropServices.ComVisible(false)]
- public Object Demanded
- {
- [System.Security.SecuritySafeCritical] // auto-generated
- [SecurityPermissionAttribute( SecurityAction.Demand, Flags = SecurityPermissionFlag.ControlEvidence | SecurityPermissionFlag.ControlPolicy)]
- get
- {
- return XMLUtil.XmlStringToSecurityObject(m_demanded);
- }
-
- set
- {
- m_demanded = XMLUtil.SecurityObjectToXmlString(value);
- }
- }
-
- public String GrantedSet
- {
- [System.Security.SecuritySafeCritical] // auto-generated
- [SecurityPermissionAttribute( SecurityAction.Demand, Flags = SecurityPermissionFlag.ControlEvidence | SecurityPermissionFlag.ControlPolicy)]
- get
- {
- return m_granted;
- }
-
- set
- {
- m_granted = value;
- }
- }
-
- public String RefusedSet
- {
- [System.Security.SecuritySafeCritical] // auto-generated
- [SecurityPermissionAttribute( SecurityAction.Demand, Flags = SecurityPermissionFlag.ControlEvidence | SecurityPermissionFlag.ControlPolicy)]
- get
- {
- return m_refused;
- }
-
- set
- {
- m_refused = value;
- }
- }
-
- [System.Runtime.InteropServices.ComVisible(false)]
- public Object DenySetInstance
- {
- [System.Security.SecuritySafeCritical] // auto-generated
- [SecurityPermissionAttribute( SecurityAction.Demand, Flags = SecurityPermissionFlag.ControlEvidence | SecurityPermissionFlag.ControlPolicy)]
- get
- {
- return XMLUtil.XmlStringToSecurityObject(m_denied);
- }
-
- set
- {
- m_denied = XMLUtil.SecurityObjectToXmlString(value);
- }
- }
-
- [System.Runtime.InteropServices.ComVisible(false)]
- public Object PermitOnlySetInstance
- {
- [System.Security.SecuritySafeCritical] // auto-generated
- [SecurityPermissionAttribute( SecurityAction.Demand, Flags = SecurityPermissionFlag.ControlEvidence | SecurityPermissionFlag.ControlPolicy)]
- get
- {
- return XMLUtil.XmlStringToSecurityObject(m_permitOnly);
- }
-
- set
- {
- m_permitOnly = XMLUtil.SecurityObjectToXmlString(value);
- }
- }
-
- [System.Runtime.InteropServices.ComVisible(false)]
- public AssemblyName FailedAssemblyInfo
- {
- [System.Security.SecuritySafeCritical] // auto-generated
- [SecurityPermissionAttribute( SecurityAction.Demand, Flags = SecurityPermissionFlag.ControlEvidence | SecurityPermissionFlag.ControlPolicy)]
- get
- {
- return m_assemblyName;
- }
-
- set
- {
- m_assemblyName = value;
- }
- }
-
- private MethodInfo getMethod()
- {
- return (MethodInfo)ByteArrayToObject(m_serializedMethodInfo);
- }
-
- [System.Runtime.InteropServices.ComVisible(false)]
- public MethodInfo Method
- {
- [System.Security.SecuritySafeCritical] // auto-generated
- [SecurityPermissionAttribute( SecurityAction.Demand, Flags = SecurityPermissionFlag.ControlEvidence | SecurityPermissionFlag.ControlPolicy)]
- get
- {
- return getMethod();
- }
-
- set
- {
- RuntimeMethodInfo m = value as RuntimeMethodInfo;
- m_serializedMethodInfo = ObjectToByteArray(m);
- if (m != null)
- {
- m_strMethodInfo = m.ToString();
- }
- }
- }
-
- public SecurityZone Zone
- {
- get
- {
- return m_zone;
- }
-
- set
- {
- m_zone = value;
- }
- }
-
- public String Url
- {
- [System.Security.SecuritySafeCritical] // auto-generated
- [SecurityPermissionAttribute( SecurityAction.Demand, Flags = SecurityPermissionFlag.ControlEvidence | SecurityPermissionFlag.ControlPolicy)]
- get
- {
- return m_url;
- }
-
- set
- {
- m_url = value;
- }
- }
-
- private void ToStringHelper(StringBuilder sb, String resourceString, Object attr)
- {
- if (attr == null)
- return;
- String attrString = attr as String;
- if (attrString == null)
- attrString = attr.ToString();
- if (attrString.Length == 0)
- return;
- sb.Append(Environment.NewLine);
- sb.Append(GetResString(resourceString));
- sb.Append(Environment.NewLine);
- sb.Append(attrString);
- }
-
- [System.Security.SecurityCritical] // auto-generated
- private String ToString(bool includeSensitiveInfo, bool includeBaseInfo)
- {
- PermissionSet.s_fullTrust.Assert();
- StringBuilder sb = new StringBuilder();
-
- if(includeBaseInfo)
- sb.Append(base.ToString());
- if(Action > 0)
- ToStringHelper(sb, "Security_Action", Action);
- ToStringHelper(sb, "Security_TypeFirstPermThatFailed", PermissionType);
- if(includeSensitiveInfo)
- {
- ToStringHelper(sb, "Security_FirstPermThatFailed", m_permissionThatFailed);
- ToStringHelper(sb, "Security_Demanded", m_demanded);
- ToStringHelper(sb, "Security_GrantedSet", m_granted);
- ToStringHelper(sb, "Security_RefusedSet", m_refused);
- ToStringHelper(sb, "Security_Denied", m_denied);
- ToStringHelper(sb, "Security_PermitOnly", m_permitOnly);
- ToStringHelper(sb, "Security_Assembly", m_assemblyName);
- ToStringHelper(sb, "Security_Method", m_strMethodInfo);
- }
- if(m_zone != SecurityZone.NoZone)
- ToStringHelper(sb, "Security_Zone", m_zone);
- if(includeSensitiveInfo)
- ToStringHelper(sb, "Security_Url", m_url);
- return sb.ToString();
- }
-#else // FEATURE_CAS_POLICY
internal SecurityException(PermissionSet grantedSetObj, PermissionSet refusedSetObj)
: this(){}
#pragma warning disable 618
internal SecurityException(string message, Object deny, Object permitOnly, MethodInfo method, Object demanded, IPermission permThatFailed)
: this(){}
- [System.Security.SecuritySafeCritical] // auto-generated
protected SecurityException(SerializationInfo info, StreamingContext context) : base(info, context)
{
if (info == null)
return base.ToString();
}
-#endif // FEATURE_CAS_POLICY
-
- [System.Security.SecurityCritical] // auto-generated
private bool CanAccessSensitiveInfo()
{
bool retVal = false;
}
return retVal;
}
-#if FEATURE_CAS_POLICY
- [System.Security.SecuritySafeCritical] // auto-generated
- public override String ToString()
- {
- return ToString(CanAccessSensitiveInfo(), true);
- }
-#endif //FEATURE_CAS_POLICY
- [System.Security.SecurityCritical] // auto-generated_required
+
public override void GetObjectData(SerializationInfo info, StreamingContext context)
{
if (info == null)
Contract.EndContractBlock();
base.GetObjectData(info, context);
-#if FEATURE_CAS_POLICY
-
- info.AddValue(ActionName, m_action, typeof(SecurityAction));
- info.AddValue(FirstPermissionThatFailedName, m_permissionThatFailed, typeof(String));
- info.AddValue(DemandedName, m_demanded, typeof(String));
- info.AddValue(GrantedSetName, m_granted, typeof(String));
- info.AddValue(RefusedSetName, m_refused, typeof(String));
- info.AddValue(DeniedName, m_denied, typeof(String));
- info.AddValue(PermitOnlyName, m_permitOnly, typeof(String));
- info.AddValue(Assembly_Name, m_assemblyName, typeof(AssemblyName));
- info.AddValue(MethodName_Serialized, m_serializedMethodInfo, typeof(byte[]));
- info.AddValue(MethodName_String, m_strMethodInfo, typeof(String));
- info.AddValue(ZoneName, m_zone, typeof(SecurityZone));
- info.AddValue(UrlName, m_url, typeof(String));
-#endif // FEATURE_CAS_POLICY
}
-#if !FEATURE_CAS_POLICY
// Stubs for surface area compatibility only
public SecurityException(String message, Type type)
: base(message)
public object PermitOnlySetInstance { get; set; }
public string RefusedSet { get; set; }
public string Url { get; set; }
-#endif // !FEATURE_CAS_POLICY
}
}
}
#pragma warning restore 618
- [System.Security.SecurityCritical] // auto-generated
[DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
[SuppressUnmanagedCodeSecurity]
internal static extern bool IsSameType(String strLeft, String strRight);
- [System.Security.SecurityCritical] // auto-generated
[MethodImplAttribute(MethodImplOptions.InternalCall)]
internal static extern bool _SetThreadSecurity(bool bThreadSecurity);
- [System.Security.SecurityCritical] // auto-generated
[DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
[SuppressUnmanagedCodeSecurity]
internal static extern void GetGrantedPermissions(ObjectHandleOnStack retGranted, ObjectHandleOnStack retDenied, StackCrawlMarkHandle stackMark);
//
-namespace System.Security {
+namespace System.Security
+{
using System;
using System.Globalization;
using System.Threading;
//
// Internal only, do not doc.
//
- [System.Security.SecurityCritical] // auto-generated
[MethodImplAttribute(MethodImplOptions.InternalCall)]
internal static extern
FrameSecurityDescriptor GetSecurityObjectForFrame(ref StackCrawlMark stackMark,
internal const bool StackHalt = false;
// this method is a big perf hit, so don't call unnecessarily
- [System.Security.SecurityCritical] // auto-generated
internal static MethodInfo GetMethodInfo(RuntimeMethodHandleInternal rmh)
{
if (rmh.IsNullHandle())
#endif
}
- [System.Security.SecurityCritical] // auto-generated
private static bool FrameDescSetHelper(FrameSecurityDescriptor secDesc,
PermissionSet demandSet,
out PermissionSet alteredDemandSet,
return secDesc.CheckSetDemand(demandSet, out alteredDemandSet, rmh);
}
- [System.Security.SecurityCritical] // auto-generated
private static bool FrameDescHelper(FrameSecurityDescriptor secDesc,
IPermission demandIn,
PermissionToken permToken,
}
#if FEATURE_COMPRESSEDSTACK
- [System.Security.SecurityCritical]
private static bool CheckDynamicMethodSetHelper(System.Reflection.Emit.DynamicResolver dynamicResolver,
PermissionSet demandSet,
out PermissionSet alteredDemandSet,
return result;
}
- [System.Security.SecurityCritical]
private static bool CheckDynamicMethodHelper(System.Reflection.Emit.DynamicResolver dynamicResolver,
IPermission demandIn,
PermissionToken permToken,
//
// API for PermissionSets
//
-
- [System.Security.SecurityCritical] // auto-generated
+
internal static void Assert(PermissionSet permSet, ref StackCrawlMark stackMark)
{
-#if FEATURE_CAS_POLICY
- // Note: if the "AssertPermission" is not a permission that implements IUnrestrictedPermission
- // you need to change the fourth parameter to a zero.
- FrameSecurityDescriptor secObj = CodeAccessSecurityEngine.CheckNReturnSO(
- CodeAccessSecurityEngine.AssertPermissionToken,
- CodeAccessSecurityEngine.AssertPermission,
- ref stackMark,
- 1 );
-
- Contract.Assert(secObj != null,"Failure in SecurityRuntime.Assert() - secObj != null");
- if (secObj == null)
- {
- // Security: REQ_SQ flag is missing. Bad compiler ?
- System.Environment.FailFast(Environment.GetResourceString("ExecutionEngine_MissingSecurityDescriptor"));
- }
- else
- {
- if (secObj.HasImperativeAsserts())
- throw new SecurityException( Environment.GetResourceString( "Security_MustRevertOverride" ) );
-
- secObj.SetAssert(permSet);
- }
-#endif // FEATURE_CAS_POLICY
}
-
- [System.Security.SecurityCritical] // auto-generated
+
internal static void AssertAllPossible(ref StackCrawlMark stackMark)
{
-#if FEATURE_CAS_POLICY
- FrameSecurityDescriptor secObj =
- SecurityRuntime.GetSecurityObjectForFrame(ref stackMark, true);
-
- Contract.Assert(secObj != null, "Failure in SecurityRuntime.AssertAllPossible() - secObj != null");
- if (secObj == null)
- {
- // Security: REQ_SQ flag is missing. Bad compiler ?
- System.Environment.FailFast(Environment.GetResourceString("ExecutionEngine_MissingSecurityDescriptor"));
- }
- else
- {
- if (secObj.GetAssertAllPossible())
- throw new SecurityException( Environment.GetResourceString( "Security_MustRevertOverride" ) );
-
- secObj.SetAssertAllPossible();
- }
-#endif // FEATURE_CAS_POLICY
}
-
- [System.Security.SecurityCritical] // auto-generated
+
internal static void Deny(PermissionSet permSet, ref StackCrawlMark stackMark)
{
-#if FEATURE_CAS_POLICY
- // Deny is only valid in legacy mode
- if (!AppDomain.CurrentDomain.IsLegacyCasPolicyEnabled)
- {
- throw new NotSupportedException(Environment.GetResourceString("NotSupported_CasDeny"));
- }
-
- FrameSecurityDescriptor secObj =
- SecurityRuntime.GetSecurityObjectForFrame(ref stackMark, true);
-
- Contract.Assert(secObj != null, "Failure in SecurityRuntime.Deny() - secObj != null");
- if (secObj == null)
- {
- // Security: REQ_SQ flag is missing. Bad compiler ?
- System.Environment.FailFast(Environment.GetResourceString("ExecutionEngine_MissingSecurityDescriptor"));
- }
- else
- {
- if (secObj.HasImperativeDenials())
- throw new SecurityException( Environment.GetResourceString( "Security_MustRevertOverride" ) );
-
- secObj.SetDeny(permSet);
- }
-#endif // FEATURE_CAS_POLICY
}
-
- [System.Security.SecurityCritical] // auto-generated
+
internal static void PermitOnly(PermissionSet permSet, ref StackCrawlMark stackMark)
{
-#if FEATURE_CAS_POLICY
- FrameSecurityDescriptor secObj =
- SecurityRuntime.GetSecurityObjectForFrame(ref stackMark, true);
-
- Contract.Assert(secObj != null, "Failure in SecurityRuntime.PermitOnly() - secObj != null");
- if (secObj == null)
- {
- // Security: REQ_SQ flag is missing. Bad compiler ?
- System.Environment.FailFast(Environment.GetResourceString("ExecutionEngine_MissingSecurityDescriptor"));
- }
- else
- {
- if (secObj.HasImperativeRestrictions())
- throw new SecurityException( Environment.GetResourceString( "Security_MustRevertOverride" ) );
-
- secObj.SetPermitOnly(permSet);
- }
-#endif // FEATURE_CAS_POLICY
}
-
+
//
// Revert API
//
-
- [System.Security.SecurityCritical] // auto-generated
+
internal static void RevertAssert(ref StackCrawlMark stackMark)
{
-#if FEATURE_CAS_POLICY
- FrameSecurityDescriptor secObj = GetSecurityObjectForFrame(ref stackMark, false);
- if (secObj != null)
- {
- secObj.RevertAssert();
- }
- else
- {
- throw new InvalidOperationException(Environment.GetResourceString("ExecutionEngine_MissingSecurityDescriptor"));
- }
-#endif // FEATURE_CAS_POLICY
}
- [System.Security.SecurityCritical] // auto-generated
internal static void RevertDeny(ref StackCrawlMark stackMark)
{
-#if FEATURE_CAS_POLICY
- FrameSecurityDescriptor secObj = GetSecurityObjectForFrame(ref stackMark, false);
- if (secObj != null)
- {
- secObj.RevertDeny();
- }
- else
- {
- throw new InvalidOperationException(Environment.GetResourceString("ExecutionEngine_MissingSecurityDescriptor"));
- }
-#endif // FEATURE_CAS_POLICY
}
- [System.Security.SecurityCritical] // auto-generated
internal static void RevertPermitOnly(ref StackCrawlMark stackMark)
{
-#if FEATURE_CAS_POLICY
- FrameSecurityDescriptor secObj = GetSecurityObjectForFrame(ref stackMark, false);
- if (secObj != null)
- {
- secObj.RevertPermitOnly();
- }
- else
- {
- throw new InvalidOperationException(Environment.GetResourceString("ExecutionEngine_MissingSecurityDescriptor"));
- }
-#endif // FEATURE_CAS_POLICY
}
- [System.Security.SecurityCritical] // auto-generated
internal static void RevertAll(ref StackCrawlMark stackMark)
{
-#if FEATURE_CAS_POLICY
- FrameSecurityDescriptor secObj = GetSecurityObjectForFrame(ref stackMark, false);
- if (secObj != null)
- {
- secObj.RevertAll();
- }
- else
- {
- throw new InvalidOperationException(Environment.GetResourceString("ExecutionEngine_MissingSecurityDescriptor"));
- }
-#endif // FEATURE_CAS_POLICY
}
}
}
namespace System.Security
{
- [System.Security.SecurityCritical] // auto-generated_required
-#pragma warning disable 618
- [PermissionSet(SecurityAction.InheritanceDemand, Unrestricted = true)]
-#pragma warning restore 618
public abstract class SecurityState
{
protected SecurityState(){}
- [System.Security.SecurityCritical] // auto-generated
public bool IsStateAvailable()
{
AppDomainManager domainManager = AppDomainManager.CurrentAppDomainManager;
-#if FEATURE_CORECLR
+
// CheckSecuritySettings only when appdomainManager is present. So if there is no
// appDomain Manager return true as by default coreclr runs in fulltrust.
return domainManager != null ? domainManager.CheckSecuritySettings(this) : true;
-#else
- return domainManager != null ? domainManager.CheckSecuritySettings(this) : false;
-#endif
}
// override this function and throw the appropriate
public abstract void EnsureState();
private static volatile string m_machineConfig;
private static volatile string m_userConfig;
- [System.Security.SecurityCritical] // auto-generated
private static void GetFileLocales()
{
if (m_machineConfig == null)
internal static string MachineDirectory
{
- [System.Security.SecurityCritical] // auto-generated
get
{
GetFileLocales();
internal static string UserDirectory
{
- [System.Security.SecurityCritical] // auto-generated
get
{
GetFileLocales();
}
}
-#if FEATURE_CAS_POLICY
- [System.Security.SecurityCritical] // auto-generated
- [DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode), SuppressUnmanagedCodeSecurity]
- internal static extern int SaveDataByte(string path, [In] byte[] data, int length);
-
- [System.Security.SecurityCritical] // auto-generated
- [DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode), SuppressUnmanagedCodeSecurity]
- internal static extern bool RecoverData(ConfigId id);
-
- [System.Security.SecurityCritical] // auto-generated
- [DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode), SuppressUnmanagedCodeSecurity]
- internal static extern void SetQuickCache(ConfigId id, QuickCacheEntryType quickCacheFlags);
-
- [System.Security.SecurityCritical] // auto-generated
- [DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode), SuppressUnmanagedCodeSecurity]
- private static extern bool GetCacheEntry(ConfigId id, int numKey, [In] byte[] key, int keyLength, ObjectHandleOnStack retData);
-
- [System.Security.SecurityCritical] // auto-generated
- internal static bool GetCacheEntry(ConfigId id, int numKey, byte[] key, out byte[] data)
- {
- byte[] retData = null;
- bool ret = GetCacheEntry(id, numKey, key, key.Length, JitHelpers.GetObjectHandleOnStack(ref retData));
-
- data = retData;
- return ret;
- }
-
- [System.Security.SecurityCritical] // auto-generated
- [DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode), SuppressUnmanagedCodeSecurity]
- private static extern void AddCacheEntry(ConfigId id, int numKey, [In] byte[] key, int keyLength, byte[] data, int dataLength);
-
- [System.Security.SecurityCritical] // auto-generated
- internal static void AddCacheEntry(ConfigId id, int numKey, byte[] key, byte[] data)
- {
- AddCacheEntry(id, numKey, key, key.Length, data, data.Length);
- }
-
- [System.Security.SecurityCritical] // auto-generated
- [DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode), SuppressUnmanagedCodeSecurity]
- internal static extern void ResetCacheData(ConfigId id);
-#endif
-
- [System.Security.SecurityCritical] // auto-generated
[DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode), SuppressUnmanagedCodeSecurity]
private static extern void GetMachineDirectory(StringHandleOnStack retDirectory);
- [System.Security.SecurityCritical] // auto-generated
[DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode), SuppressUnmanagedCodeSecurity]
private static extern void GetUserDirectory(StringHandleOnStack retDirectory);
- [System.Security.SecurityCritical] // auto-generated
[DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode), SuppressUnmanagedCodeSecurity]
internal static extern bool WriteToEventLog(string message);
}
using System.Globalization;
using System.Runtime.Versioning;
using System.IO;
+ using System.Diagnostics;
using System.Diagnostics.Contracts;
[Serializable]
// 2. Ensuring that the partial trust code has permission to see full path data
// 3. Not using this set for paths (eg EnvironmentStringExpressionSet)
//
- [SecurityCritical]
protected ArrayList m_list;
protected bool m_ignoreCase;
- [SecurityCritical]
protected String m_expressions;
- [SecurityCritical]
protected String[] m_expressionsArray;
protected bool m_throwOnRelative;
{
}
- [System.Security.SecuritySafeCritical] // auto-generated
public StringExpressionSet( bool ignoreCase, String str, bool throwOnRelative )
{
m_list = null;
return new StringExpressionSet();
}
- [SecuritySafeCritical]
public virtual StringExpressionSet Copy()
{
// SafeCritical: just copying this value around, not leaking it
return StaticProcessSingleString(str);
}
- [System.Security.SecurityCritical] // auto-generated
public void AddExpressions( String str )
{
if (str == null)
Reduce();
}
- [System.Security.SecurityCritical] // auto-generated
public void AddExpressions( String[] str, bool checkForDuplicates, bool needFullPath )
{
AddExpressions(CreateListFromExpressions(str, needFullPath), checkForDuplicates);
}
- [System.Security.SecurityCritical] // auto-generated
public void AddExpressions( ArrayList exprArrayList, bool checkForDuplicates)
{
- Contract.Assert( m_throwOnRelative, "This should only be called when throw on relative is set" );
+ Debug.Assert( m_throwOnRelative, "This should only be called when throw on relative is set" );
m_expressionsArray = null;
m_expressions = null;
}
- [System.Security.SecurityCritical] // auto-generated
internal static ArrayList CreateListFromExpressions(String[] str, bool needFullPath)
{
if (str == null)
return retArrayList;
}
- [System.Security.SecurityCritical] // auto-generated
protected void CheckList()
{
if (m_list == null && m_expressions != null)
}
- [System.Security.SecurityCritical] // auto-generated
protected void CreateList()
{
String[] expressionsArray = Split( m_expressions );
}
}
- [SecuritySafeCritical]
public bool IsEmpty()
{
// SafeCritical: we're just showing that the expressions are empty, the sensitive portion is their
}
}
- [System.Security.SecurityCritical] // auto-generated
public bool IsSubsetOf( StringExpressionSet ses )
{
if (this.IsEmpty())
return true;
}
- [System.Security.SecurityCritical] // auto-generated
public bool IsSubsetOfPathDiscovery( StringExpressionSet ses )
{
if (this.IsEmpty())
}
- [System.Security.SecurityCritical] // auto-generated
public StringExpressionSet Union( StringExpressionSet ses )
{
// If either set is empty, the union represents a copy of the other.
}
- [System.Security.SecurityCritical] // auto-generated
public StringExpressionSet Intersect( StringExpressionSet ses )
{
// If either set is empty, the intersection is empty
return intersectSet;
}
- [SecuritySafeCritical]
protected void GenerateString()
{
// SafeCritical - moves critical data around, but doesn't expose it out
// expressions contain paths that were canonicalized and expanded from the input that would cause
// information disclosure, so we instead only expose this out to trusted code that can ensure they
// either don't leak the information or required full path information.
- [SecurityCritical]
public string UnsafeToString()
{
CheckList();
return m_expressions;
}
- [SecurityCritical]
public String[] UnsafeToStringArray()
{
if (m_expressionsArray == null && m_list != null)
// protected static helper functions
//-------------------------------
- [SecurityCritical]
private bool StringSubsetStringExpression( String left, StringExpressionSet right, bool ignoreCase )
{
for (int index = 0; index < right.m_list.Count; ++index)
return false;
}
- [SecurityCritical]
private static bool StringSubsetStringExpressionPathDiscovery( String left, StringExpressionSet right, bool ignoreCase )
{
for (int index = 0; index < right.m_list.Count; ++index)
// protected helper functions
//-------------------------------
- [SecuritySafeCritical]
protected void AddSingleExpressionNoDuplicates( String expression )
{
// SafeCritical: We're not exposing out the string sets, just allowing modification of them
this.m_list.Add( expression );
}
- [System.Security.SecurityCritical] // auto-generated
protected void Reduce()
{
CheckList();
}
}
- [System.Security.SecurityCritical] // auto-generated
[DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
[SuppressUnmanagedCodeSecurity]
internal static extern void GetLongPathName( String path, StringHandleOnStack retLongPath );
- [System.Security.SecurityCritical] // auto-generated
internal static String CanonicalizePath( String path )
{
return CanonicalizePath( path, true );
}
- [System.Security.SecurityCritical] // auto-generated
internal static string CanonicalizePath(string path, bool needFullPath)
{
if (needFullPath)
using System.Security.Permissions;
using System.Runtime.Serialization;
using System.Threading;
+ using System.Diagnostics;
using System.Diagnostics.Contracts;
using System.Diagnostics.CodeAnalysis;
{
Object thisObj = this.GetItem( i );
IPermission thisPerm = thisObj as IPermission;
-#if FEATURE_CAS_POLICY
- ISecurityElementFactory thisElem = thisObj as ISecurityElementFactory;
-#endif // FEATURE_CAS_POLICY
Object otherObj = (other != null)?other.GetItem( i ):null;
IPermission otherPerm = otherObj as IPermission;
-#if FEATURE_CAS_POLICY
- ISecurityElementFactory otherElem = otherObj as ISecurityElementFactory;
-#endif // FEATURE_CAS_POLICY
if (thisObj == null && otherObj == null)
continue;
-
-
+
if (thisObj == null)
{
-#if FEATURE_CAS_POLICY
- if (otherElem != null)
- {
- otherPerm = PermissionSet.CreatePerm(otherElem, false);
- }
-#endif // FEATURE_CAS_POLICY
-
PermissionToken token = PermissionToken.GetToken(otherPerm);
-
+
if (token == null)
{
throw new SerializationException(Environment.GetResourceString("Serialization_InsufficientState"));
}
else if (otherObj == null)
{
-#if FEATURE_CAS_POLICY
- if (thisElem != null)
- {
- thisPerm = PermissionSet.CreatePerm(thisElem, false);
- }
-#endif // FEATURE_CAS_POLICY
-
PermissionToken token = PermissionToken.GetToken(thisPerm);
if (token == null)
{
}
else
{
- Contract.Assert( (thisObj == null || otherObj == null), "Permission cannot be in both TokenBasedSets" );
+ Debug.Assert( (thisObj == null || otherObj == null), "Permission cannot be in both TokenBasedSets" );
}
}
return unionSet;
if (obj != null)
{
IPermission perm = obj as IPermission;
-#if FEATURE_CAS_POLICY
- if (perm == null)
- perm = PermissionSet.CreatePerm(obj, ignoreTypeLoadFailures);
-#endif // FEATURE_CAS_POLICY
PermissionToken token = PermissionToken.GetToken(perm);
if (perm == null || token == null)
}
#if !PLATFORM_UNIX
- [System.Security.SecuritySafeCritical] // auto-generated
internal URLString SpecialNormalizeUrl()
{
// Under WinXP, file protocol urls can be mapped to
}
}
- [System.Security.SecurityCritical] // auto-generated
[DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
[SuppressUnmanagedCodeSecurity]
private static extern void GetDeviceName( String driveLetter, StringHandleOnStack retDeviceName );
using System.Threading;
using System.Globalization;
using System.Reflection;
+ using System.Diagnostics;
using System.Diagnostics.Contracts;
internal static class XMLUtil
//
private const String BuiltInPermission = "System.Security.Permissions.";
-#if FEATURE_CAS_POLICY
- private const String BuiltInMembershipCondition = "System.Security.Policy.";
- private const String BuiltInCodeGroup = "System.Security.Policy.";
- private const String BuiltInApplicationSecurityManager = "System.Security.Policy.";
- private static readonly char[] sepChar = {',', ' '};
-#endif
+
public static SecurityElement
NewPermissionElement (IPermission ip)
{
if ( typename == null )
typename = type.FullName;
- Contract.Assert( type.FullName.Equals( typename ), "Incorrect class name passed! Was : " + typename + " Shoule be: " + type.FullName);
+ Debug.Assert( type.FullName.Equals( typename ), "Incorrect class name passed! Was : " + typename + " Shoule be: " + type.FullName);
element.AddAttribute( "class", typename + ", " + type.Module.Assembly.FullName.Replace( '\"', '\'' ) );
}
assemblyVersion = an.Version.ToString();
return true;
}
- [System.Security.SecurityCritical] // auto-generated
private static bool
ParseElementForObjectCreation( SecurityElement el,
String requiredNamespace,
return false;
}
-#if FEATURE_CAS_POLICY
- public static String SecurityObjectToXmlString(Object ob)
- {
- if(ob == null)
- return "";
- PermissionSet pset = ob as PermissionSet;
- if(pset != null)
- return pset.ToXml().ToString();
- return ((IPermission)ob).ToXml().ToString();
- }
-
- [System.Security.SecurityCritical] // auto-generated
- public static Object XmlStringToSecurityObject(String s)
- {
- if(s == null)
- return null;
- if(s.Length < 1)
- return null;
- return SecurityElement.FromString(s).ToSecurityObject();
- }
-#endif // FEATURE_CAS_POLICY
-
- [SecuritySafeCritical]
public static IPermission
CreatePermission (SecurityElement el, PermissionState permState, bool ignoreTypeLoadFailures)
{
// UnsafeForHostPermission
// HostProtectionPermission
// StrongNameIdentityPermission
-#if !FEATURE_CORECLR
- // IsolatedStorageFilePermission
-#endif
// RegistryPermission
// PublisherIdentityPermission
else
goto USEREFLECTION;
}
-
-#if !FEATURE_CORECLR
- case 19:
- // PrincipalPermission
- if (String.Compare(className, classNameStart, "PrincipalPermission", 0, classNameLength, StringComparison.Ordinal) == 0)
- return new PrincipalPermission( permState );
- else
- goto USEREFLECTION;
-#endif // !FEATURE_CORECLR
case 20:
// ReflectionPermission
// FileDialogPermission
else
goto USEREFLECTION;
}
-
-
case 22:
// SiteIdentityPermission
// ZoneIdentityPermission
else
goto USEREFLECTION;
}
-
-
case 24:
// HostProtectionPermission
if (String.Compare(className, classNameStart, "HostProtectionPermission", 0, classNameLength, StringComparison.Ordinal) == 0)
return new HostProtectionPermission( permState );
else
goto USEREFLECTION;
-
-#if FEATURE_X509 && FEATURE_CAS_POLICY
- case 27:
- // PublisherIdentityPermission
- if (String.Compare(className, classNameStart, "PublisherIdentityPermission", 0, classNameLength, StringComparison.Ordinal) == 0)
- return new PublisherIdentityPermission( permState );
- else
- goto USEREFLECTION;
-#endif // FEATURE_X509 && FEATURE_CAS_POLICY
-
case 28:
// StrongNameIdentityPermission
if (String.Compare(className, classNameStart, "StrongNameIdentityPermission", 0, classNameLength, StringComparison.Ordinal) == 0)
return new StrongNameIdentityPermission( permState );
else
goto USEREFLECTION;
-#if !FEATURE_CORECLR
- case 29:
- // IsolatedStorageFilePermission
- if (String.Compare(className, classNameStart, "IsolatedStorageFilePermission", 0, classNameLength, StringComparison.Ordinal) == 0)
- return new IsolatedStorageFilePermission( permState );
- else
- goto USEREFLECTION;
-#endif
default:
goto USEREFLECTION;
}
-
+
USEREFLECTION:
Object[] objs = new Object[1];
return perm;
}
-#if FEATURE_CAS_POLICY
-#pragma warning disable 618 // CodeGroups are obsolete
- [System.Security.SecuritySafeCritical] // auto-generated
- public static CodeGroup
- CreateCodeGroup (SecurityElement el)
- {
- if (el == null || !el.Tag.Equals("CodeGroup"))
- throw new ArgumentException( String.Format( CultureInfo.CurrentCulture, Environment.GetResourceString( "Argument_WrongElementType" ), "<CodeGroup>" ) ) ;
- Contract.EndContractBlock();
-
- String className;
- int classNameLength;
- int classNameStart;
-
- if (!ParseElementForObjectCreation( el,
- BuiltInCodeGroup,
- out className,
- out classNameStart,
- out classNameLength ))
- {
- goto USEREFLECTION;
- }
-
- switch (classNameLength)
- {
- case 12:
- // NetCodeGroup
- if (String.Compare(className, classNameStart, "NetCodeGroup", 0, classNameLength, StringComparison.Ordinal) == 0)
- return new NetCodeGroup();
- else
- goto USEREFLECTION;
-
- case 13:
- // FileCodeGroup
- if (String.Compare(className, classNameStart, "FileCodeGroup", 0, classNameLength, StringComparison.Ordinal) == 0)
- return new FileCodeGroup();
- else
- goto USEREFLECTION;
- case 14:
- // UnionCodeGroup
- if (String.Compare(className, classNameStart, "UnionCodeGroup", 0, classNameLength, StringComparison.Ordinal) == 0)
- return new UnionCodeGroup();
- else
- goto USEREFLECTION;
-
- case 19:
- // FirstMatchCodeGroup
- if (String.Compare(className, classNameStart, "FirstMatchCodeGroup", 0, classNameLength, StringComparison.Ordinal) == 0)
- return new FirstMatchCodeGroup();
- else
- goto USEREFLECTION;
-
- default:
- goto USEREFLECTION;
- }
-
-USEREFLECTION:
- Type groupClass = null;
- CodeGroup group = null;
-
- new ReflectionPermission(ReflectionPermissionFlag.MemberAccess).Assert();
- groupClass = GetClassFromElement(el, true);
- if (groupClass == null)
- return null;
- if (!(typeof(CodeGroup).IsAssignableFrom(groupClass)))
- throw new ArgumentException( Environment.GetResourceString("Argument_NotACodeGroupType") );
-
- group = (CodeGroup) Activator.CreateInstance(groupClass, true);
-
- Contract.Assert( groupClass.Module.Assembly != Assembly.GetExecutingAssembly(),
- "This path should not get called for mscorlib based classes" );
-
- return group;
- }
-#pragma warning restore 618
-
- [System.Security.SecurityCritical] // auto-generated
- internal static IMembershipCondition
- CreateMembershipCondition( SecurityElement el )
- {
- if (el == null || !el.Tag.Equals("IMembershipCondition"))
- throw new ArgumentException( String.Format( CultureInfo.CurrentCulture, Environment.GetResourceString( "Argument_WrongElementType" ), "<IMembershipCondition>" ) ) ;
- Contract.EndContractBlock();
-
- String className;
- int classNameStart;
- int classNameLength;
-
- if (!ParseElementForObjectCreation( el,
- BuiltInMembershipCondition,
- out className,
- out classNameStart,
- out classNameLength ))
- {
- goto USEREFLECTION;
- }
-
- // We have a built in membership condition, figure out which it is.
-
- // Here's the list of built in membership conditions as of 9/17/2002
- // System.Security.Policy.AllMembershipCondition
- // System.Security.Policy.URLMembershipCondition
- // System.Security.Policy.SHA1MembershipCondition
- // System.Security.Policy.SiteMembershipCondition
- // System.Security.Policy.ZoneMembershipCondition
- // System.Security.Policy.PublisherMembershipCondition
- // System.Security.Policy.StrongNameMembershipCondition
- // System.Security.Policy.ApplicationMembershipCondition
- // System.Security.Policy.DomainApplicationMembershipCondition
- // System.Security.Policy.ApplicationDirectoryMembershipCondition
-
- switch (classNameLength)
- {
- case 22:
- // AllMembershipCondition
- // URLMembershipCondition
- if (className[classNameStart] == 'A')
- {
- if (String.Compare(className, classNameStart, "AllMembershipCondition", 0, classNameLength, StringComparison.Ordinal) == 0)
- return new AllMembershipCondition();
- else
- goto USEREFLECTION;
- }
- else
- {
- if (String.Compare(className, classNameStart, "UrlMembershipCondition", 0, classNameLength, StringComparison.Ordinal) == 0)
- return new UrlMembershipCondition();
- else
- goto USEREFLECTION;
- }
-
- case 23:
- // HashMembershipCondition
- // SiteMembershipCondition
- // ZoneMembershipCondition
- if (className[classNameStart] == 'H')
- {
- if (String.Compare(className, classNameStart, "HashMembershipCondition", 0, classNameLength, StringComparison.Ordinal) == 0)
- return new HashMembershipCondition();
- else
- goto USEREFLECTION;
- }
- else if (className[classNameStart] == 'S')
- {
- if (String.Compare(className, classNameStart, "SiteMembershipCondition", 0, classNameLength, StringComparison.Ordinal) == 0)
- return new SiteMembershipCondition();
- else
- goto USEREFLECTION;
- }
- else
- {
- if (String.Compare(className, classNameStart, "ZoneMembershipCondition", 0, classNameLength, StringComparison.Ordinal) == 0)
- return new ZoneMembershipCondition();
- else
- goto USEREFLECTION;
- }
-
- case 28:
- // PublisherMembershipCondition
- if (String.Compare(className, classNameStart, "PublisherMembershipCondition", 0, classNameLength, StringComparison.Ordinal) == 0)
- return new PublisherMembershipCondition();
- else
- goto USEREFLECTION;
-
- case 29:
- // StrongNameMembershipCondition
- if (String.Compare(className, classNameStart, "StrongNameMembershipCondition", 0, classNameLength, StringComparison.Ordinal) == 0)
- return new StrongNameMembershipCondition();
- else
- goto USEREFLECTION;
-
- case 39:
- // ApplicationDirectoryMembershipCondition
- if (String.Compare(className, classNameStart, "ApplicationDirectoryMembershipCondition", 0, classNameLength, StringComparison.Ordinal) == 0)
- return new ApplicationDirectoryMembershipCondition();
- else
- goto USEREFLECTION;
-
- default:
- goto USEREFLECTION;
- }
-
-USEREFLECTION:
- Type condClass = null;
- IMembershipCondition cond = null;
-
- new ReflectionPermission(ReflectionPermissionFlag.MemberAccess).Assert();
- condClass = GetClassFromElement(el, true);
- if (condClass == null)
- return null;
- if (!(typeof(IMembershipCondition).IsAssignableFrom(condClass)))
- throw new ArgumentException( Environment.GetResourceString("Argument_NotAMembershipCondition") );
-
- cond = (IMembershipCondition) Activator.CreateInstance(condClass, true);
-
- return cond;
- }
-#endif //#if FEATURE_CAS_POLICY
internal static Type
GetClassFromElement (SecurityElement el, bool ignoreTypeLoadFailures)
{
{
try
{
- return Type.GetType(className, false, false);
+ return Type.GetType(className, false, false);
}
catch (SecurityException)
{
}
}
else
- return Type.GetType(className, true, false);
+ return Type.GetType(className, true, false);
}
public static bool
using System.Runtime.ConstrainedExecution;
using System.Runtime.Versioning;
using Microsoft.Win32.SafeHandles;
+ using System.Diagnostics;
using System.Diagnostics.Contracts;
public sealed class SecureString: IDisposable {
throw new ArgumentOutOfRangeException(nameof(index), Environment.GetResourceString("ArgumentOutOfRange_IndexString"));
}
Contract.EndContractBlock();
- Contract.Assert(index <= Int32.MaxValue / sizeof(char));
+ Debug.Assert(index <= Int32.MaxValue / sizeof(char));
EnsureNotDisposed();
EnsureNotReadOnly();
private int BufferLength {
[System.Security.SecurityCritical] // auto-generated
get {
- Contract.Assert(m_buffer != null, "Buffer is not initialized!");
+ Debug.Assert(m_buffer != null, "Buffer is not initialized!");
return m_buffer.Length;
}
}
[ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)]
private static uint GetAlignedSize( int size) {
- Contract.Assert(size >= 0, "size must be non-negative");
+ Debug.Assert(size >= 0, "size must be non-negative");
uint alignedSize = ((uint)size / BlockSize) * BlockSize;
if( (size % BlockSize != 0) || size == 0) { // if size is 0, set allocated size to blocksize
[System.Security.SecurityCritical] // auto-generated
[ReliabilityContract(Consistency.MayCorruptInstance, Cer.MayFail)]
private void ProtectMemory() {
- Contract.Assert(!m_buffer.IsInvalid && m_buffer.Length != 0, "Invalid buffer!");
- Contract.Assert(m_buffer.Length % BlockSize == 0, "buffer length must be multiple of blocksize!");
+ Debug.Assert(!m_buffer.IsInvalid && m_buffer.Length != 0, "Invalid buffer!");
+ Debug.Assert(m_buffer.Length % BlockSize == 0, "buffer length must be multiple of blocksize!");
if( m_length == 0 || m_encrypted) {
return;
[System.Security.SecurityCritical] // auto-generated
[ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)]
private void UnProtectMemory() {
- Contract.Assert(!m_buffer.IsInvalid && m_buffer.Length != 0, "Invalid buffer!");
- Contract.Assert(m_buffer.Length % BlockSize == 0, "buffer length must be multiple of blocksize!");
+ Debug.Assert(!m_buffer.IsInvalid && m_buffer.Length != 0, "Invalid buffer!");
+ Debug.Assert(m_buffer.Length % BlockSize == 0, "buffer length must be multiple of blocksize!");
if( m_length == 0) {
return;
source.AcquirePointer(ref sourcePtr);
target.AcquirePointer(ref targetPtr);
- Contract.Assert(Win32Native.SysStringLen((IntPtr)targetPtr) >= Win32Native.SysStringLen((IntPtr)sourcePtr), "Target buffer is not large enough!");
+ Debug.Assert(Win32Native.SysStringLen((IntPtr)targetPtr) >= Win32Native.SysStringLen((IntPtr)sourcePtr), "Target buffer is not large enough!");
Buffer.Memcpy(targetPtr, sourcePtr, (int) Win32Native.SysStringLen((IntPtr)sourcePtr) * 2);
}
**
=============================================================================*/
-namespace System {
-
+namespace System
+{
using System.Threading;
using System.Runtime.Remoting;
using System.Security;
using System.Security.Util;
using System.Runtime.CompilerServices;
using System.Runtime.ConstrainedExecution;
+ using System.Diagnostics;
using System.Diagnostics.Contracts;
-#if FEATURE_CAS_POLICY
- using StringMaker = System.Security.Util.Tokenizer.StringMaker;
-#endif // FEATURE_CAS_POLICY
internal sealed class SharedStatics
{
private volatile String _Remoting_Identity_IDGuid;
public static String Remoting_Identity_IDGuid
{
- [System.Security.SecuritySafeCritical] // auto-generated
get
{
if (_sharedStatics._Remoting_Identity_IDGuid == null)
}
}
- Contract.Assert(_sharedStatics._Remoting_Identity_IDGuid != null,
+ Debug.Assert(_sharedStatics._Remoting_Identity_IDGuid != null,
"_sharedStatics._Remoting_Identity_IDGuid != null");
return _sharedStatics._Remoting_Identity_IDGuid;
}
}
-#if FEATURE_CAS_POLICY
- private StringMaker _maker;
- [System.Security.SecuritySafeCritical] // auto-generated
- static public StringMaker GetSharedStringMaker()
- {
- StringMaker maker = null;
-
- bool tookLock = false;
- RuntimeHelpers.PrepareConstrainedRegions();
- try {
- Monitor.Enter(_sharedStatics, ref tookLock);
-
- if (_sharedStatics._maker != null)
- {
- maker = _sharedStatics._maker;
- _sharedStatics._maker = null;
- }
- }
- finally {
- if (tookLock)
- Monitor.Exit(_sharedStatics);
- }
-
- if (maker == null)
- {
- maker = new StringMaker();
- }
-
- return maker;
- }
-
- [System.Security.SecuritySafeCritical] // auto-generated
- static public void ReleaseSharedStringMaker(ref StringMaker maker)
- {
- // save this stringmaker so someone else can use it
- bool tookLock = false;
- RuntimeHelpers.PrepareConstrainedRegions();
- try
- {
- Monitor.Enter(_sharedStatics, ref tookLock);
-
- _sharedStatics._maker = maker;
- maker = null;
- }
- finally {
- if (tookLock)
- Monitor.Exit(_sharedStatics);
- }
- }
-#endif // FEATURE_CAS_POLICY
-
// Note this may not need to be process-wide.
private int _Remoting_Identity_IDSeqNum;
internal static int Remoting_Identity_GetNextSeqNum()
internal static ulong MemoryFailPointReservedMemory {
get {
- Contract.Assert(Volatile.Read(ref _sharedStatics._memFailPointReservedMemory) >= 0, "Process-wide MemoryFailPoint reserved memory was negative!");
+ Debug.Assert(Volatile.Read(ref _sharedStatics._memFailPointReservedMemory) >= 0, "Process-wide MemoryFailPoint reserved memory was negative!");
return (ulong) Volatile.Read(ref _sharedStatics._memFailPointReservedMemory);
}
}
internal static float NegativeZero = BitConverter.Int32BitsToSingle(unchecked((int)0x80000000));
[Pure]
- [System.Security.SecuritySafeCritical] // auto-generated
[System.Runtime.Versioning.NonVersionable]
public unsafe static bool IsInfinity(float f) {
return (*(int*)(&f) & 0x7FFFFFFF) == 0x7F800000;
}
[Pure]
- [System.Security.SecuritySafeCritical] // auto-generated
[System.Runtime.Versioning.NonVersionable]
public unsafe static bool IsPositiveInfinity(float f) {
return *(int*)(&f) == 0x7F800000;
}
[Pure]
- [System.Security.SecuritySafeCritical] // auto-generated
[System.Runtime.Versioning.NonVersionable]
public unsafe static bool IsNegativeInfinity(float f) {
return *(int*)(&f) == unchecked((int)0xFF800000);
[Pure]
[ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)]
- [System.Security.SecuritySafeCritical]
[System.Runtime.Versioning.NonVersionable]
public unsafe static bool IsNaN(float f) {
return (*(int*)(&f) & 0x7FFFFFFF) > 0x7F800000;
}
[Pure]
- [System.Security.SecuritySafeCritical] // auto-generated
internal unsafe static bool IsNegative(float f) {
return (*(uint*)(&f) & 0x80000000) == 0x80000000;
}
return IsNaN(obj) && IsNaN(m_value);
}
- [System.Security.SecuritySafeCritical] // auto-generated
public unsafe override int GetHashCode() {
float f = m_value;
if (f == 0) {
return v;
}
- [System.Security.SecuritySafeCritical] // auto-generated
public override String ToString() {
Contract.Ensures(Contract.Result<String>() != null);
return Number.FormatSingle(m_value, null, NumberFormatInfo.CurrentInfo);
}
- [System.Security.SecuritySafeCritical] // auto-generated
public String ToString(IFormatProvider provider) {
Contract.Ensures(Contract.Result<String>() != null);
return Number.FormatSingle(m_value, null, NumberFormatInfo.GetInstance(provider));
}
- [System.Security.SecuritySafeCritical] // auto-generated
public String ToString(String format) {
Contract.Ensures(Contract.Result<String>() != null);
return Number.FormatSingle(m_value, format, NumberFormatInfo.CurrentInfo);
}
- [System.Security.SecuritySafeCritical] // auto-generated
public String ToString(String format, IFormatProvider provider) {
Contract.Ensures(Contract.Result<String>() != null);
return Number.FormatSingle(m_value, format, NumberFormatInfo.GetInstance(provider));
using System.Diagnostics;
using System.Runtime.CompilerServices;
+#pragma warning disable 0809 //warning CS0809: Obsolete member 'Span<T>.Equals(object)' overrides non-obsolete member 'object.Equals(object)'
+
namespace System
{
/// <summary>
/// <param name="array">The target array.</param>
/// <exception cref="System.ArgumentNullException">Thrown when <paramref name="array"/> is a null
/// reference (Nothing in Visual Basic).</exception>
- /// <exception cref="System.ArrayTypeMismatchException">Thrown when <paramref name="array"/> is covariant.</exception>
+ /// <exception cref="System.ArrayTypeMismatchException">Thrown when <paramref name="array"/> is covariant and array's type is not exactly T[].</exception>
public Span(T[] array)
{
if (array == null)
/// <param name="start">The index at which to begin the span.</param>
/// <exception cref="System.ArgumentNullException">Thrown when <paramref name="array"/> is a null
/// reference (Nothing in Visual Basic).</exception>
- /// <exception cref="System.ArrayTypeMismatchException">Thrown when <paramref name="array"/> is covariant.</exception>
+ /// <exception cref="System.ArrayTypeMismatchException">Thrown when <paramref name="array"/> is covariant and array's type is not exactly T[].</exception>
/// <exception cref="System.ArgumentOutOfRangeException">
/// Thrown when the specified <paramref name="start"/> is not in the range (<0 or >=Length).
/// </exception>
/// <param name="length">The number of items in the span.</param>
/// <exception cref="System.ArgumentNullException">Thrown when <paramref name="array"/> is a null
/// reference (Nothing in Visual Basic).</exception>
- /// <exception cref="System.ArrayTypeMismatchException">Thrown when <paramref name="array"/> is covariant.</exception>
+ /// <exception cref="System.ArrayTypeMismatchException">Thrown when <paramref name="array"/> is covariant and array's type is not exactly T[].</exception>
/// <exception cref="System.ArgumentOutOfRangeException">
/// Thrown when the specified <paramref name="start"/> or end index is not in the range (<0 or >=Length).
/// </exception>
/// out of a void*-typed block of memory. And the length is not checked.
/// But if this creation is correct, then all subsequent uses are correct.
/// </summary>
- /// <param name="ptr">An unmanaged pointer to memory.</param>
+ /// <param name="pointer">An unmanaged pointer to memory.</param>
/// <param name="length">The number of <typeparamref name="T"/> elements the memory contains.</param>
/// <exception cref="System.ArgumentException">
/// Thrown when <typeparamref name="T"/> is reference type or contains pointers and hence cannot be stored in unmanaged memory.
}
/// <summary>
- /// Defines an implicit conversion of an array to a <see cref="Span{T}"/>
- /// </summary>
- public static implicit operator Span<T>(T[] array)
- {
- return new Span<T>(array);
- }
-
- /// <summary>
- /// Defines an implicit conversion of a <see cref="ArraySegment{T}"/> to a <see cref="Span{T}"/>
- /// </summary>
- public static implicit operator Span<T>(ArraySegment<T> arraySegment)
- {
- return new Span<T>(arraySegment.Array, arraySegment.Offset, arraySegment.Count);
- }
-
- /// <summary>
/// Gets the number of elements contained in the <see cref="Span{T}"/>
/// </summary>
- public int Length
- {
- get { return _length; }
- }
-
- /// <summary>
- /// Returns an empty <see cref="Span{T}"/>
- /// </summary>
- public static Span<T> Empty
- {
- get { return default(Span<T>); }
- }
+ public int Length => _length;
/// <summary>
/// Returns whether the <see cref="Span{T}"/> is empty.
/// </summary>
- public bool IsEmpty
- {
- get { return _length == 0; }
- }
+ public bool IsEmpty => _length == 0;
/// <summary>
/// Fetches the element at the specified index.
}
/// <summary>
- /// Copies the contents of this span into a new array. This heap
- /// allocates, so should generally be avoided, however is sometimes
- /// necessary to bridge the gap with APIs written in terms of arrays.
+ /// Copies the contents of this span into destination span. If the source
+ /// and destinations overlap, this method behaves as if the original values in
+ /// a temporary location before the destination is overwritten.
/// </summary>
- public T[] ToArray()
+ /// <param name="destination">The span to copy items into.</param>
+ /// <exception cref="System.ArgumentException">
+ /// Thrown when the destination Span is shorter than the source Span.
+ /// </exception>
+ public void CopyTo(Span<T> destination)
{
- if (_length == 0)
- return Array.Empty<T>();
+ if (!TryCopyTo(destination))
+ ThrowHelper.ThrowArgumentException_DestinationTooShort();
+ }
- var destination = new T[_length];
- SpanHelper.CopyTo<T>(ref JitHelpers.GetArrayData(destination), ref DangerousGetPinnableReference(), _length);
- return destination;
+ /// <summary>
+ /// Copies the contents of this span into destination span. If the source
+ /// and destinations overlap, this method behaves as if the original values in
+ /// a temporary location before the destination is overwritten.
+ /// </summary>
+ /// <param name="destination">The span to copy items into.</param>
+ /// <returns>If the destination span is shorter than the source span, this method
+ /// return false and no data is written to the destination.</returns>
+ public bool TryCopyTo(Span<T> destination)
+ {
+ if ((uint)_length > (uint)destination.Length)
+ return false;
+
+ SpanHelper.CopyTo<T>(ref destination.DangerousGetPinnableReference(), ref DangerousGetPinnableReference(), _length);
+ return true;
}
/// <summary>
+ /// Returns true if left and right point at the same memory and have the same length. Note that
+ /// this does *not* check to see if the *contents* are equal.
+ /// </summary>
+ public static bool operator ==(Span<T> left, Span<T> right) => left.Equals(right);
+
+ /// <summary>
+ /// Returns false if left and right point at the same memory and have the same length. Note that
+ /// this does *not* check to see if the *contents* are equal.
+ /// </summary>
+ public static bool operator !=(Span<T> left, Span<T> right) => !left.Equals(right);
+
+ /// <summary>
+ /// Checks to see if two spans point at the same memory. Note that
+ /// this does *not* check to see if the *contents* are equal.
+ /// </summary>
+ public bool Equals(Span<T> other)
+ {
+ return (_length == other.Length) &&
+ (_length == 0 || Unsafe.AreSame(ref DangerousGetPinnableReference(), ref other.DangerousGetPinnableReference()));
+ }
+
+ /// <summary>
+ /// This method is not supported as spans cannot be boxed. To compare two spans, use operator==.
+ /// <exception cref="System.NotSupportedException">
+ /// Always thrown by this method.
+ /// </exception>
+ /// </summary>
+ [Obsolete("Equals() on Span will always throw an exception. Use == instead.")]
+ public override bool Equals(object obj)
+ {
+ ThrowHelper.ThrowNotSupportedException_CannotCallEqualsOnSpan();
+ // Prevent compiler error CS0161: 'Span<T>.Equals(object)': not all code paths return a value
+ return default(bool);
+ }
+
+ /// <summary>
+ /// This method is not supported as spans cannot be boxed.
+ /// <exception cref="System.NotSupportedException">
+ /// Always thrown by this method.
+ /// </exception>
+ /// </summary>
+ [Obsolete("GetHashCode() on Span will always throw an exception.")]
+ public override int GetHashCode()
+ {
+ ThrowHelper.ThrowNotSupportedException_CannotCallGetHashCodeOnSpan();
+ // Prevent compiler error CS0161: 'Span<T>.GetHashCode()': not all code paths return a value
+ return default(int);
+ }
+
+ /// <summary>
+ /// Defines an implicit conversion of an array to a <see cref="Span{T}"/>
+ /// </summary>
+ public static implicit operator Span<T>(T[] array) => new Span<T>(array);
+
+ /// <summary>
+ /// Defines an implicit conversion of a <see cref="ArraySegment{T}"/> to a <see cref="Span{T}"/>
+ /// </summary>
+ public static implicit operator Span<T>(ArraySegment<T> arraySegment) => new Span<T>(arraySegment.Array, arraySegment.Offset, arraySegment.Count);
+
+ /// <summary>
/// Forms a slice out of the given span, beginning at 'start'.
/// </summary>
/// <param name="start">The index at which to begin this slice.</param>
/// Forms a slice out of the given span, beginning at 'start', of given length
/// </summary>
/// <param name="start">The index at which to begin this slice.</param>
- /// <param name="end">The index at which to end this slice (exclusive).</param>
+ /// <param name="length">The desired length for the slice (exclusive).</param>
/// <exception cref="System.ArgumentOutOfRangeException">
/// Thrown when the specified <paramref name="start"/> or end index is not in range (<0 or >&eq;Length).
/// </exception>
}
/// <summary>
- /// Checks to see if two spans point at the same memory. Note that
- /// this does *not* check to see if the *contents* are equal.
- /// </summary>
- public bool Equals(Span<T> other)
- {
- return (_length == other.Length) &&
- (_length == 0 || Unsafe.AreSame(ref DangerousGetPinnableReference(), ref other.DangerousGetPinnableReference()));
- }
-
- /// <summary>
- /// Copies the contents of this span into destination span. The destination
- /// must be at least as big as the source, and may be bigger.
+ /// Copies the contents of this span into a new array. This heap
+ /// allocates, so should generally be avoided, however it is sometimes
+ /// necessary to bridge the gap with APIs written in terms of arrays.
/// </summary>
- /// <param name="destination">The span to copy items into.</param>
- public bool TryCopyTo(Span<T> destination)
+ public T[] ToArray()
{
- if ((uint)_length > (uint)destination.Length)
- return false;
+ if (_length == 0)
+ return Array.Empty<T>();
- SpanHelper.CopyTo<T>(ref destination.DangerousGetPinnableReference(), ref DangerousGetPinnableReference(), _length);
- return true;
+ var destination = new T[_length];
+ SpanHelper.CopyTo<T>(ref JitHelpers.GetArrayData(destination), ref DangerousGetPinnableReference(), _length);
+ return destination;
}
- /// <exception cref="System.ArgumentOutOfRangeException">
- /// Thrown when the specified <paramref name="values"/>'s Length is longer than source span's Length.
- /// </exception>
- public void Set(ReadOnlySpan<T> values)
- {
- if ((uint)values.Length > (uint)_length)
- ThrowHelper.ThrowArgumentOutOfRangeException();
-
- SpanHelper.CopyTo<T>(ref DangerousGetPinnableReference(), ref values.DangerousGetPinnableReference(), values.Length);
- }
+ // <summary>
+ /// Returns an empty <see cref="Span{T}"/>
+ /// </summary>
+ public static Span<T> Empty => default(Span<T>);
}
public static class SpanExtensions
// See the LICENSE file in the project root for more information.
using System.Collections;
+using System.Diagnostics;
using System.Diagnostics.Contracts;
using System.Globalization;
using System.Runtime.CompilerServices;
//Native Static Methods
//
- [System.Security.SecuritySafeCritical] // auto-generated
private unsafe static int CompareOrdinalIgnoreCaseHelper(String strA, String strB)
{
Contract.Requires(strA != null);
int charA = *a;
int charB = *b;
- Contract.Assert((charA | charB) <= 0x7F, "strings have to be ASCII");
+ Debug.Assert((charA | charB) <= 0x7F, "strings have to be ASCII");
// uppercase both chars - notice that we need just one compare per char
if ((uint)(charA - 'a') <= (uint)('z' - 'a')) charA -= 0x20;
}
// native call to COMString::CompareOrdinalEx
- [System.Security.SecurityCritical] // auto-generated
[MethodImplAttribute(MethodImplOptions.InternalCall)]
internal static extern int CompareOrdinalHelper(String strA, int indexA, int countA, String strB, int indexB, int countB);
//This will not work in case-insensitive mode for any character greater than 0x80.
//We'll throw an ArgumentException.
- [System.Security.SecurityCritical] // auto-generated
[MethodImplAttribute(MethodImplOptions.InternalCall)]
unsafe internal static extern int nativeCompareOrdinalIgnoreCaseWC(String strA, sbyte *strBBytes);
// Search/Query methods
//
- [System.Security.SecuritySafeCritical] // auto-generated
[ReliabilityContract(Consistency.WillNotCorruptState, Cer.MayFail)]
private unsafe static bool EqualsHelper(String strA, String strB)
{
}
}
- [System.Security.SecuritySafeCritical] // auto-generated
[ReliabilityContract(Consistency.WillNotCorruptState, Cer.MayFail)]
private unsafe static bool StartsWithOrdinalHelper(String str, String startsWith)
{
#if BIT64
// Single int read aligns pointers for the following long reads
// No length check needed as this method is called when length >= 2
- Contract.Assert(length >= 2);
+ Debug.Assert(length >= 2);
if (*(int*)a != *(int*)b) goto ReturnFalse;
length -= 2; a += 2; b += 2;
}
}
- [System.Security.SecuritySafeCritical] // auto-generated
private unsafe static int CompareOrdinalHelper(String strA, String strB)
{
Contract.Requires(strA != null);
// NOTE: This may be subject to change if eliminating the check
// in the callers makes them small enough to be inlined by the JIT
- Contract.Assert(strA.m_firstChar == strB.m_firstChar,
+ Debug.Assert(strA.m_firstChar == strB.m_firstChar,
"For performance reasons, callers of this method should " +
"check/short-circuit beforehand if the first char is the same.");
if (*a != *b) return *a - *b;
DiffOffset1:
- Contract.Assert(*(a + 1) != *(b + 1), "This char must be different if we reach here!");
+ Debug.Assert(*(a + 1) != *(b + 1), "This char must be different if we reach here!");
return *(a + 1) - *(b + 1);
}
}
// Provides a more flexible function for string comparision. See StringComparison
// for meaning of different comparisonType.
[Pure]
- [System.Security.SecuritySafeCritical] // auto-generated
public static int Compare(String strA, String strB, StringComparison comparisonType)
{
// Single comparison to check if comparisonType is within [CurrentCulture .. OrdinalIgnoreCase]
}
[Pure]
- [System.Security.SecuritySafeCritical] // auto-generated
public static int Compare(String strA, int indexA, String strB, int indexB, int length, StringComparison comparisonType) {
if (comparisonType < StringComparison.CurrentCulture || comparisonType > StringComparison.OrdinalIgnoreCase) {
throw new ArgumentException(Environment.GetResourceString("NotSupported_StringComparison"), nameof(comparisonType));
// Compares strA and strB using an ordinal (code-point) comparison.
//
[Pure]
- [System.Security.SecuritySafeCritical] // auto-generated
public static int CompareOrdinal(String strA, int indexA, String strB, int indexB, int length)
{
if (strA == null || strB == null)
}
[Pure]
- [System.Security.SecuritySafeCritical] // auto-generated
[ComVisible(false)]
public Boolean EndsWith(String value, StringComparison comparisonType) {
if( (Object)value == null) {
}
[Pure]
- [System.Security.SecuritySafeCritical] // auto-generated
public bool Equals(String value, StringComparison comparisonType) {
if (comparisonType < StringComparison.CurrentCulture || comparisonType > StringComparison.OrdinalIgnoreCase)
throw new ArgumentException(Environment.GetResourceString("NotSupported_StringComparison"), nameof(comparisonType));
}
[Pure]
- [System.Security.SecuritySafeCritical] // auto-generated
public static bool Equals(String a, String b, StringComparison comparisonType) {
if (comparisonType < StringComparison.CurrentCulture || comparisonType > StringComparison.OrdinalIgnoreCase)
throw new ArgumentException(Environment.GetResourceString("NotSupported_StringComparison"), nameof(comparisonType));
#if FEATURE_RANDOMIZED_STRING_HASHING
// Do not remove!
// This method is called by reflection in System.Xml
- [System.Security.SecurityCritical]
[MethodImplAttribute(MethodImplOptions.InternalCall)]
internal static extern int InternalMarvin32HashString(string s, int strLen, long additionalEntropy);
- [System.Security.SecuritySafeCritical]
internal static bool UseRandomizedHashing() {
return InternalUseRandomizedHashing();
}
- [System.Security.SecurityCritical]
[System.Security.SuppressUnmanagedCodeSecurity]
[DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
private static extern bool InternalUseRandomizedHashing();
// Gets a hash code for this string. If strings A and B are such that A.Equals(B), then
// they will return the same hash code.
- [System.Security.SecuritySafeCritical] // auto-generated
[ReliabilityContract(Consistency.WillNotCorruptState, Cer.MayFail)]
public override int GetHashCode()
{
// Use this if and only if you need the hashcode to not change across app domains (e.g. you have an app domain agile
// hash table).
- [System.Security.SecuritySafeCritical] // auto-generated
[ReliabilityContract(Consistency.WillNotCorruptState, Cer.MayFail)]
internal int GetLegacyNonRandomizedHashCode() {
unsafe {
fixed (char* src = &m_firstChar) {
- Contract.Assert(src[this.Length] == '\0', "src[this.Length] == '\\0'");
- Contract.Assert( ((int)src)%4 == 0, "Managed string should start at 4 bytes boundary");
+ Debug.Assert(src[this.Length] == '\0', "src[this.Length] == '\\0'");
+ Debug.Assert( ((int)src)%4 == 0, "Managed string should start at 4 bytes boundary");
#if BIT64
int hash1 = 5381;
#else // !BIT64 (32)
}
[Pure]
- [System.Security.SecuritySafeCritical] // auto-generated
[ComVisible(false)]
public Boolean StartsWith(String value, StringComparison comparisonType) {
if( (Object)value == null) {
// See the LICENSE file in the project root for more information.
using System.Collections.Generic;
+using System.Diagnostics;
using System.Diagnostics.Contracts;
using System.Globalization;
using System.Runtime.CompilerServices;
private const int TrimTail = 1;
private const int TrimBoth = 2;
- [System.Security.SecuritySafeCritical] // auto-generated
unsafe private static void FillStringChecked(String dest, int destPos, String src)
{
Contract.Requires(dest != null);
return Concat(objArgs);
}
- [System.Security.SecuritySafeCritical]
public static string Concat(params object[] args)
{
if (args == null)
{
string s = strings[i];
- Contract.Assert(s != null);
- Contract.Assert(position <= totalLength - s.Length, "We didn't allocate enough space for the result string!");
+ Debug.Assert(s != null);
+ Debug.Assert(position <= totalLength - s.Length, "We didn't allocate enough space for the result string!");
FillStringChecked(result, position, s);
position += s.Length;
}
- [System.Security.SecuritySafeCritical] // auto-generated
public static String Concat(String str0, String str1) {
Contract.Ensures(Contract.Result<String>() != null);
Contract.Ensures(Contract.Result<String>().Length ==
return result;
}
- [System.Security.SecuritySafeCritical] // auto-generated
public static String Concat(String str0, String str1, String str2) {
Contract.Ensures(Contract.Result<String>() != null);
Contract.Ensures(Contract.Result<String>().Length ==
return result;
}
- [System.Security.SecuritySafeCritical] // auto-generated
public static String Concat(String str0, String str1, String str2, String str3) {
Contract.Ensures(Contract.Result<String>() != null);
Contract.Ensures(Contract.Result<String>().Length ==
return result;
}
- [System.Security.SecuritySafeCritical]
public static String Concat(params String[] values) {
if (values == null)
throw new ArgumentNullException(nameof(values));
.AppendFormatHelper(provider, format, args));
}
- [System.Security.SecuritySafeCritical] // auto-generated
public String Insert(int startIndex, String value)
{
if (value == null)
// Joins an array of strings together as one string with a separator between each original string.
//
- [System.Security.SecuritySafeCritical] // auto-generated
public unsafe static string Join(string separator, string[] value, int startIndex, int count)
{
separator = separator ?? string.Empty;
{
// If the separator is null, it is converted to an empty string before entering this function.
// Even for empty strings, fixed should never return null (it should return a pointer to a null char).
- Contract.Assert(separator != null);
- Contract.Assert(separatorLength >= 0);
+ Debug.Assert(separator != null);
+ Debug.Assert(separatorLength >= 0);
if (value == null)
{
}
[Pure]
- [System.Security.SecuritySafeCritical] // auto-generated
public String PadLeft(int totalWidth, char paddingChar) {
if (totalWidth < 0)
throw new ArgumentOutOfRangeException(nameof(totalWidth), Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
}
[Pure]
- [System.Security.SecuritySafeCritical] // auto-generated
public String PadRight(int totalWidth, char paddingChar) {
if (totalWidth < 0)
throw new ArgumentOutOfRangeException(nameof(totalWidth), Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
return result;
}
- [System.Security.SecuritySafeCritical] // auto-generated
public String Remove(int startIndex, int count)
{
if (startIndex < 0)
// Replaces all instances of oldChar with newChar.
//
- [System.Security.SecuritySafeCritical] // auto-generated
public String Replace(char oldChar, char newChar)
{
Contract.Ensures(Contract.Result<String>() != null);
// This method contains the same functionality as StringBuilder Replace. The only difference is that
// a new String has to be allocated since Strings are immutable
- [System.Security.SecuritySafeCritical] // auto-generated
[MethodImplAttribute(MethodImplOptions.InternalCall)]
private extern String ReplaceInternal(String oldValue, String newValue);
return SplitInternal(separator, count, options);
}
- [System.Security.SecuritySafeCritical]
private unsafe String[] SplitInternal(char separator, int count, StringSplitOptions options)
{
return SplitInternal(&separator, 1, count, options);
}
- [System.Security.SecuritySafeCritical]
private unsafe String[] SplitInternal(char[] separator, int count, StringSplitOptions options)
{
fixed (char* pSeparators = separator)
}
}
- [System.Security.SecurityCritical]
private unsafe String[] SplitInternal(char* separators, int separatorsLength, int count, StringSplitOptions options)
{
if (count < 0)
bool omitEmptyEntries = (options == StringSplitOptions.RemoveEmptyEntries);
if ((count == 0) || (omitEmptyEntries && this.Length == 0))
- {
-#if FEATURE_CORECLR
+ {
return EmptyArray<String>.Value;
-#else
- // Keep the old behavior of returning a new empty array
- // to mitigate any potential compat risk.
- return new String[0];
-#endif
}
if (count == 1)
return new String[] { this };
}
- int[] sepList = new int[Length];
+ int[] sepList = new int[Length];
int numReplaces = MakeSeparatorList(separators, separatorsLength, sepList);
// Handle the special case of no replaces.
if (0 == numReplaces) {
return new String[] { this };
- }
+ }
if(omitEmptyEntries)
{
else
{
return SplitKeepEmptyEntries(sepList, null, 1, numReplaces, count);
- }
+ }
}
[ComVisible(false)]
}
if ((count == 0) || (omitEmptyEntries && this.Length ==0)) {
-#if FEATURE_CORECLR
return EmptyArray<String>.Value;
-#else
- // Keep the old behavior of returning a new empty array
- // to mitigate any potential compat risk.
- return new String[0];
-#endif
}
if (count == 1 || (singleSeparator && separator.Length == 0)) {
}
// we must have at least one slot left to fill in the last string.
- Contract.Assert(arrIndex < maxItems);
+ Debug.Assert(arrIndex < maxItems);
//Handle the last string at the end of the array if there is one.
if (currIndex< Length) {
// Args: separator -- A string containing all of the split characters.
// sepList -- an array of ints for split char indicies.
//--------------------------------------------------------------------
- [System.Security.SecurityCritical]
private unsafe int MakeSeparatorList(char* separators, int separatorsLength, int[] sepList) {
- Contract.Assert(separatorsLength >= 0, "separatorsLength >= 0");
+ Debug.Assert(separatorsLength >= 0, "separatorsLength >= 0");
int foundCount=0;
if (separators == null || separatorsLength == 0) {
// Args: separator -- the separator
// sepList -- an array of ints for split string indicies.
//--------------------------------------------------------------------
- [System.Security.SecuritySafeCritical] // auto-generated
private unsafe int MakeSeparatorList(string separator, int[] sepList) {
- Contract.Assert(!string.IsNullOrEmpty(separator), "!string.IsNullOrEmpty(separator)");
+ Debug.Assert(!string.IsNullOrEmpty(separator), "!string.IsNullOrEmpty(separator)");
int foundCount = 0;
int sepListCount = sepList.Length;
// sepList -- an array of ints for split string indicies.
// lengthList -- an array of ints for split string lengths.
//--------------------------------------------------------------------
- [System.Security.SecuritySafeCritical] // auto-generated
private unsafe int MakeSeparatorList(String[] separators, int[] sepList, int[] lengthList) {
- Contract.Assert(separators != null && separators.Length > 0, "separators != null && separators.Length > 0");
+ Debug.Assert(separators != null && separators.Length > 0, "separators != null && separators.Length > 0");
int foundCount = 0;
int sepListCount = sepList.Length;
// Returns a substring of this string.
//
- [System.Security.SecuritySafeCritical] // auto-generated
public String Substring(int startIndex, int length) {
//Bounds Checking.
return InternalSubString(startIndex, length);
}
- [System.Security.SecurityCritical] // auto-generated
unsafe string InternalSubString(int startIndex, int length) {
- Contract.Assert( startIndex >= 0 && startIndex <= this.Length, "StartIndex is out of range!");
- Contract.Assert( length >= 0 && startIndex <= this.Length - length, "length is out of range!");
+ Debug.Assert( startIndex >= 0 && startIndex <= this.Length, "StartIndex is out of range!");
+ Debug.Assert( length >= 0 && startIndex <= this.Length - length, "length is out of range!");
String result = FastAllocateString(length);
}
- [System.Security.SecuritySafeCritical] // auto-generated
private String TrimHelper(int trimType) {
//end will point to the first non-trimmed character on the right
//start will point to the first non-trimmed character on the Left
}
- [System.Security.SecuritySafeCritical] // auto-generated
private String TrimHelper(char[] trimChars, int trimType) {
//end will point to the first non-trimmed character on the right
//start will point to the first non-trimmed character on the Left
}
- [System.Security.SecurityCritical] // auto-generated
private String CreateTrimmedString(int start, int end) {
int len = end -start + 1;
if (len == this.Length) {
}
[Pure]
- [System.Security.SecuritySafeCritical] // auto-generated
public unsafe int IndexOf(char value, int startIndex, int count) {
if (startIndex < 0 || startIndex > Length)
throw new ArgumentOutOfRangeException(nameof(startIndex), Environment.GetResourceString("ArgumentOutOfRange_Index"));
}
[Pure]
- [System.Security.SecuritySafeCritical] // auto-generated
[MethodImplAttribute(MethodImplOptions.InternalCall)]
public extern int IndexOfAny(char [] anyOf, int startIndex, int count);
}
[Pure]
- [System.Security.SecuritySafeCritical]
public int IndexOf(String value, int startIndex, int count, StringComparison comparisonType) {
// Validate inputs
if (value == null)
}
[Pure]
- [System.Security.SecuritySafeCritical] // auto-generated
public unsafe int LastIndexOf(char value, int startIndex, int count) {
if (Length == 0)
return -1;
}
[Pure]
- [System.Security.SecuritySafeCritical] // auto-generated
[MethodImplAttribute(MethodImplOptions.InternalCall)]
public extern int LastIndexOfAny(char [] anyOf, int startIndex, int count);
}
[Pure]
- [System.Security.SecuritySafeCritical]
public int LastIndexOf(String value, int startIndex, int count, StringComparison comparisonType) {
if (value == null)
throw new ArgumentNullException(nameof(value));
using System.Runtime.InteropServices;
using System.Runtime.Versioning;
using Microsoft.Win32;
+ using System.Diagnostics;
using System.Diagnostics.Contracts;
using System.Security;
// than 0x80) before security is fully initialized. Without security initialized, we can't grab resources (the nlp's)
// from the assembly. This provides a workaround for that problem and should NOT be used anywhere else.
//
- [System.Security.SecuritySafeCritical] // auto-generated
internal unsafe static string SmallCharToUpper(string strIn) {
Contract.Requires(strIn != null);
Contract.EndContractBlock();
for(int i = 0; i < length; i++) {
int c = inBuff[i];
- Contract.Assert(c <= 0x7F, "string has to be ASCII");
+ Debug.Assert(c <= 0x7F, "string has to be ASCII");
// uppercase - notice that we need just one compare
if ((uint)(c - 'a') <= (uint)('z' - 'a')) c -= 0x20;
outBuff[i] = (char)c;
}
- Contract.Assert(outBuff[length]=='\0', "outBuff[length]=='\0'");
+ Debug.Assert(outBuff[length]=='\0', "outBuff[length]=='\0'");
}
return strOut;
}
[System.Runtime.CompilerServices.IndexerName("Chars")]
public extern char this[int index] {
[MethodImpl(MethodImplOptions.InternalCall)]
- [System.Security.SecuritySafeCritical] // public member
get;
}
// sourceIndex + count - 1 to the character array buffer, beginning
// at destinationIndex.
//
- [System.Security.SecuritySafeCritical] // auto-generated
unsafe public void CopyTo(int sourceIndex, char[] destination, int destinationIndex, int count)
{
if (destination == null)
}
// Returns the entire string as an array of characters.
- [System.Security.SecuritySafeCritical] // auto-generated
unsafe public char[] ToCharArray() {
int length = Length;
if (length > 0)
}
return chars;
}
-
-#if FEATURE_CORECLR
+
return Array.Empty<char>();
-#else
- return new char[0];
-#endif
}
// Returns a substring of this string as an array of characters.
//
- [System.Security.SecuritySafeCritical] // auto-generated
unsafe public char[] ToCharArray(int startIndex, int length)
{
// Range check everything.
}
return chars;
}
-
-#if FEATURE_CORECLR
+
return Array.Empty<char>();
-#else
- return new char[0];
-#endif
}
[Pure]
//
// Spec#: Add postcondition in a contract assembly. Potential perf problem.
public extern int Length {
- [System.Security.SecuritySafeCritical] // auto-generated
[MethodImplAttribute(MethodImplOptions.InternalCall)]
get;
}
// Creates a new string with the characters copied in from ptr. If
// ptr is null, a 0-length string (like String.Empty) is returned.
//
- [System.Security.SecurityCritical] // auto-generated
[CLSCompliant(false), MethodImplAttribute(MethodImplOptions.InternalCall)]
unsafe public extern String(char *value);
- [System.Security.SecurityCritical] // auto-generated
[CLSCompliant(false), MethodImplAttribute(MethodImplOptions.InternalCall)]
unsafe public extern String(char *value, int startIndex, int length);
- [System.Security.SecurityCritical] // auto-generated
[CLSCompliant(false), MethodImplAttribute(MethodImplOptions.InternalCall)]
unsafe public extern String(sbyte *value);
- [System.Security.SecurityCritical] // auto-generated
[CLSCompliant(false), MethodImplAttribute(MethodImplOptions.InternalCall)]
unsafe public extern String(sbyte *value, int startIndex, int length);
- [System.Security.SecurityCritical] // auto-generated
[CLSCompliant(false), MethodImplAttribute(MethodImplOptions.InternalCall)]
unsafe public extern String(sbyte *value, int startIndex, int length, Encoding enc);
- [System.Security.SecurityCritical] // auto-generated
unsafe static private String CreateString(sbyte *value, int startIndex, int length, Encoding enc) {
if (enc == null)
return new String(value, startIndex, length); // default to ANSI
// Helper for encodings so they can talk to our buffer directly
// stringLength must be the exact size we'll expect
- [System.Security.SecurityCritical] // auto-generated
unsafe static internal String CreateStringFromEncoding(
byte* bytes, int byteLength, Encoding encoding)
{
// Get our string length
int stringLength = encoding.GetCharCount(bytes, byteLength, null);
- Contract.Assert(stringLength >= 0, "stringLength >= 0");
+ Debug.Assert(stringLength >= 0, "stringLength >= 0");
// They gave us an empty string if they needed one
// 0 bytelength might be possible if there's something in an encoder
fixed(char* pTempChars = &s.m_firstChar)
{
int doubleCheck = encoding.GetChars(bytes, byteLength, pTempChars, stringLength, null);
- Contract.Assert(stringLength == doubleCheck,
+ Debug.Assert(stringLength == doubleCheck,
"Expected encoding.GetChars to return same length as encoding.GetCharCount");
}
// This is only intended to be used by char.ToString.
// It is necessary to put the code in this class instead of Char, since m_firstChar is a private member.
// Making m_firstChar internal would be dangerous since it would make it much easier to break String's immutability.
- [SecuritySafeCritical]
internal static string CreateFromChar(char c)
{
string result = FastAllocateString(1);
return result;
}
- [System.Security.SecuritySafeCritical] // auto-generated
unsafe internal int GetBytesFromEncoding(byte* pbNativeBuffer, int cbNativeBuffer,Encoding encoding)
{
// encoding == Encoding.UTF8
}
}
- [System.Security.SecuritySafeCritical] // auto-generated
unsafe internal int ConvertToAnsi(byte *pbNativeBuffer, int cbNativeBuffer, bool fBestFit, bool fThrowOnUnmappableChar)
{
- Contract.Assert(cbNativeBuffer >= (Length + 1) * Marshal.SystemMaxDBCSCharSize, "Insufficient buffer length passed to ConvertToAnsi");
+ Debug.Assert(cbNativeBuffer >= (Length + 1) * Marshal.SystemMaxDBCSCharSize, "Insufficient buffer length passed to ConvertToAnsi");
const uint CP_ACP = 0;
int nb;
#endif
}
- [System.Security.SecuritySafeCritical] // auto-generated
public bool IsNormalized(NormalizationForm normalizationForm)
{
#if !FEATURE_NORM_IDNA_ONLY
#endif
}
- [System.Security.SecuritySafeCritical] // auto-generated
public String Normalize(NormalizationForm normalizationForm)
{
#if !FEATURE_NORM_IDNA_ONLY
return Normalization.Normalize(this, normalizationForm);
}
- [System.Security.SecurityCritical] // auto-generated
[MethodImplAttribute(MethodImplOptions.InternalCall)]
internal extern static String FastAllocateString(int length);
// be created from the characters in value between startIndex and
// startIndex + length - 1.
//
- [System.Security.SecuritySafeCritical] // auto-generated
[MethodImplAttribute(MethodImplOptions.InternalCall)]
public extern String(char [] value, int startIndex, int length);
// created from the characters in value.
//
- [System.Security.SecuritySafeCritical] // auto-generated
[MethodImplAttribute(MethodImplOptions.InternalCall)]
public extern String(char [] value);
- [System.Security.SecurityCritical] // auto-generated
internal static unsafe void wstrcpy(char *dmem, char *smem, int charCount)
{
Buffer.Memcpy((byte*)dmem, (byte*)smem, charCount * 2); // 2 used everywhere instead of sizeof(char)
}
- [System.Security.SecuritySafeCritical] // auto-generated
private String CtorCharArray(char [] value)
{
if (value != null && value.Length != 0) {
return String.Empty;
}
- [System.Security.SecuritySafeCritical] // auto-generated
private String CtorCharArrayStartLength(char [] value, int startIndex, int length)
{
if (value == null)
return String.Empty;
}
- [System.Security.SecuritySafeCritical] // auto-generated
private String CtorCharCount(char c, int count)
{
if (count > 0) {
throw new ArgumentOutOfRangeException(nameof(count), Environment.GetResourceString("ArgumentOutOfRange_MustBeNonNegNum", nameof(count)));
}
- [System.Security.SecurityCritical] // auto-generated
private static unsafe int wcslen(char *ptr)
{
char *end = ptr;
end += 2;
}
- Contract.Assert(end[0] == 0 || end[1] == 0);
+ Debug.Assert(end[0] == 0 || end[1] == 0);
if (end[0] != 0) end++;
#else // !BIT64
// Based on https://graphics.stanford.edu/~seander/bithacks.html#ZeroInWord
#endif // !BIT64
FoundZero:
- Contract.Assert(*end == 0);
+ Debug.Assert(*end == 0);
int count = (int)(end - ptr);
return count;
}
- [System.Security.SecurityCritical] // auto-generated
private unsafe String CtorCharPtr(char *ptr)
{
if (ptr == null)
throw new ArgumentException(Environment.GetResourceString("Arg_MustBeStringPtrNotAtom"));
#endif // FEATURE_PAL
- Contract.Assert(this == null, "this == null"); // this is the string constructor, we allocate it
+ Debug.Assert(this == null, "this == null"); // this is the string constructor, we allocate it
try {
int count = wcslen(ptr);
}
}
- [System.Security.SecurityCritical] // auto-generated
private unsafe String CtorCharPtrStartLength(char *ptr, int startIndex, int length)
{
if (length < 0) {
throw new ArgumentOutOfRangeException(nameof(startIndex), Environment.GetResourceString("ArgumentOutOfRange_StartIndex"));
}
Contract.EndContractBlock();
- Contract.Assert(this == null, "this == null"); // this is the string constructor, we allocate it
+ Debug.Assert(this == null, "this == null"); // this is the string constructor, we allocate it
char *pFrom = ptr + startIndex;
if (pFrom < ptr) {
}
}
- [System.Security.SecuritySafeCritical] // auto-generated
[MethodImplAttribute(MethodImplOptions.InternalCall)]
public extern String(char c, int count);
return this;
}
- [System.Security.SecuritySafeCritical] // auto-generated
unsafe public static String Copy (String str) {
if (str==null) {
throw new ArgumentNullException(nameof(str));
return result;
}
- [System.Security.SecuritySafeCritical] // auto-generated
public static String Intern(String str) {
if (str==null) {
throw new ArgumentNullException(nameof(str));
}
[Pure]
- [System.Security.SecuritySafeCritical] // auto-generated
public static String IsInterned(String str) {
if (str==null) {
throw new ArgumentNullException(nameof(str));
// Is this a string that can be compared quickly (that is it has only characters > 0x80
// and not a - or '
- [System.Security.SecurityCritical] // auto-generated
[MethodImplAttribute(MethodImplOptions.InternalCall)]
internal extern bool IsFastSort();
// Is this a string that only contains characters < 0x80.
- [System.Security.SecurityCritical] // auto-generated
[MethodImplAttribute(MethodImplOptions.InternalCall)]
internal extern bool IsAscii();
// Set extra byte for odd-sized strings that came from interop as BSTR.
- [System.Security.SecurityCritical]
[MethodImplAttribute(MethodImplOptions.InternalCall)]
internal extern void SetTrailByte(byte data);
// Try to retrieve the extra byte - returns false if not present.
- [System.Security.SecurityCritical]
[MethodImplAttribute(MethodImplOptions.InternalCall)]
internal extern bool TryGetTrailByte(out byte data);
}
// Copies the source String (byte buffer) to the destination IntPtr memory allocated with len bytes.
- [System.Security.SecurityCritical] // auto-generated
internal unsafe static void InternalCopy(String src, IntPtr dest,int len)
{
if (len == 0)
return x.Equals(y);
}
- [System.Security.SecuritySafeCritical]
public override int GetHashCode(string obj) {
if( obj == null) {
throw new ArgumentNullException(nameof(obj));
#endif // FEATURE_COMINTEROP
using System.Runtime.CompilerServices;
using System.Runtime.ConstrainedExecution;
+ using System.Diagnostics;
using System.Diagnostics.Contracts;
[ReliabilityContract(Consistency.WillNotCorruptState, Cer.MayFail)]
{
// The length of the returned array is an approximation based on the length of the input string and the system
// character set. It is only guaranteed to be larger or equal to cbLength, don't depend on the exact value.
- [System.Security.SecurityCritical]
unsafe static internal byte[] DoAnsiConversion(string str, bool fBestFit, bool fThrowOnUnmappableChar, out int cbLength)
{
byte[] buffer = new byte[(str.Length + 1) * Marshal.SystemMaxDBCSCharSize];
return buffer;
}
- [System.Security.SecurityCritical]
unsafe static internal byte ConvertToNative(char managedChar, bool fBestFit, bool fThrowOnUnmappableChar)
{
int cbAllocLength = (1 + 1) * Marshal.SystemMaxDBCSCharSize;
[ReliabilityContract(Consistency.WillNotCorruptState, Cer.MayFail)]
internal static class CSTRMarshaler
{
- [System.Security.SecurityCritical] // auto-generated
static internal unsafe IntPtr ConvertToNative(int flags, string strManaged, IntPtr pNativeBuffer)
{
if (null == strManaged)
return (IntPtr)pbNativeBuffer;
}
- [System.Security.SecurityCritical] // auto-generated
static internal unsafe string ConvertToManaged(IntPtr cstr)
{
if (IntPtr.Zero == cstr)
return new String((sbyte*)cstr);
}
- [System.Security.SecurityCritical] // auto-generated
static internal void ClearNative(IntPtr pNative)
{
Win32Native.CoTaskMemFree(pNative);
internal static class UTF8Marshaler
{
const int MAX_UTF8_CHAR_SIZE = 3;
- [System.Security.SecurityCritical]
static internal unsafe IntPtr ConvertToNative(int flags, string strManaged, IntPtr pNativeBuffer)
{
if (null == strManaged)
return (IntPtr)pbNativeBuffer;
}
- [System.Security.SecurityCritical]
static internal unsafe string ConvertToManaged(IntPtr cstr)
{
if (IntPtr.Zero == cstr)
return String.CreateStringFromEncoding((byte*)cstr, nbBytes, Encoding.UTF8);
}
- [System.Security.SecurityCritical]
static internal void ClearNative(IntPtr pNative)
{
if (pNative != IntPtr.Zero)
[ReliabilityContract(Consistency.WillNotCorruptState, Cer.MayFail)]
internal static class UTF8BufferMarshaler
{
- [System.Security.SecurityCritical]
static internal unsafe IntPtr ConvertToNative(StringBuilder sb, IntPtr pNativeBuffer, int flags)
{
if (null == sb)
return (IntPtr)pbNativeBuffer;
}
- [System.Security.SecurityCritical]
static internal unsafe void ConvertToManaged(StringBuilder sb, IntPtr pNative)
{
if (pNative == null)
[ReliabilityContract(Consistency.WillNotCorruptState, Cer.MayFail)]
internal static class BSTRMarshaler
{
- [System.Security.SecurityCritical] // auto-generated
static internal unsafe IntPtr ConvertToNative(string strManaged, IntPtr pNativeBuffer)
{
if (null == strManaged)
}
}
- [System.Security.SecurityCritical] // auto-generated
static internal unsafe string ConvertToManaged(IntPtr bstr)
{
if (IntPtr.Zero == bstr)
}
}
- [System.Security.SecurityCritical] // auto-generated
static internal void ClearNative(IntPtr pNative)
{
if (IntPtr.Zero != pNative)
[ReliabilityContract(Consistency.WillNotCorruptState, Cer.MayFail)]
internal static class VBByValStrMarshaler
{
- [System.Security.SecurityCritical] // auto-generated
static internal unsafe IntPtr ConvertToNative(string strManaged, bool fBestFit, bool fThrowOnUnmappableChar, ref int cch)
{
if (null == strManaged)
return new IntPtr(pNative);
}
- [System.Security.SecurityCritical] // auto-generated
static internal unsafe string ConvertToManaged(IntPtr pNative, int cch)
{
if (IntPtr.Zero == pNative)
return new String((sbyte*)pNative, 0, cch);
}
- [System.Security.SecurityCritical] // auto-generated
static internal unsafe void ClearNative(IntPtr pNative)
{
if (IntPtr.Zero != pNative)
[ReliabilityContract(Consistency.WillNotCorruptState, Cer.MayFail)]
internal static class AnsiBSTRMarshaler
{
- [System.Security.SecurityCritical] // auto-generated
static internal unsafe IntPtr ConvertToNative(int flags, string strManaged)
{
if (null == strManaged)
return Win32Native.SysAllocStringByteLen(bytes, (uint)nb);
}
- [System.Security.SecurityCritical] // auto-generated
static internal unsafe string ConvertToManaged(IntPtr bstr)
{
if (IntPtr.Zero == bstr)
}
}
- [System.Security.SecurityCritical] // auto-generated
static internal unsafe void ClearNative(IntPtr pNative)
{
if (IntPtr.Zero != pNative)
{
static internal IntPtr ConvertToNative(string strManaged)
{
- Contract.Assert(false, "NYI");
+ Debug.Assert(false, "NYI");
return IntPtr.Zero;
}
static internal unsafe string ConvertToManaged(IntPtr bstr)
{
- Contract.Assert(false, "NYI");
+ Debug.Assert(false, "NYI");
return null;
}
static internal void ClearNative(IntPtr pNative)
{
- Contract.Assert(false, "NYI");
+ Debug.Assert(false, "NYI");
}
} // class WSTRBufferMarshaler
// You can get this through: (new DateTimeOffset(1601, 1, 1, 0, 0, 1, TimeSpan.Zero)).Ticks;
private const Int64 ManagedUtcTicksAtNativeZero = 504911232000000000;
- [SecurityCritical]
internal static void ConvertToNative(ref DateTimeOffset managedDTO, out DateTimeNative dateTime) {
Int64 managedUtcTicks = managedDTO.UtcTicks;
dateTime.UniversalTime = managedUtcTicks - ManagedUtcTicksAtNativeZero;
}
- [SecurityCritical]
internal static void ConvertToManaged(out DateTimeOffset managedLocalDTO, ref DateTimeNative nativeTicks) {
Int64 managedUtcTicks = ManagedUtcTicksAtNativeZero + nativeTicks.UniversalTime;
internal static class HStringMarshaler
{
// Slow-path, which requires making a copy of the managed string into the resulting HSTRING
- [SecurityCritical]
internal static unsafe IntPtr ConvertToNative(string managed)
{
if (!Environment.IsWinRTSupported)
// Note that the managed string input to this method MUST be pinned, and stay pinned for the lifetime of
// the returned HSTRING object. If the string is not pinned, or becomes unpinned before the HSTRING's
// lifetime ends, the HSTRING instance will be corrupted.
- [SecurityCritical]
internal static unsafe IntPtr ConvertToNativeReference(string managed,
[Out] HSTRING_HEADER *hstringHeader)
{
}
}
- [SecurityCritical]
internal static string ConvertToManaged(IntPtr hstring)
{
if (!Environment.IsWinRTSupported)
return WindowsRuntimeMarshal.HStringToString(hstring);
}
- [SecurityCritical]
internal static void ClearNative(IntPtr hstring)
{
- Contract.Assert(Environment.IsWinRTSupported);
+ Debug.Assert(Environment.IsWinRTSupported);
if (hstring != IntPtr.Zero)
{
[ReliabilityContract(Consistency.WillNotCorruptState, Cer.MayFail)]
internal static class ValueClassMarshaler
{
- [SecurityCritical]
[MethodImplAttribute(MethodImplOptions.InternalCall)]
static internal extern void ConvertToNative(IntPtr dst, IntPtr src, IntPtr pMT, ref CleanupWorkList pCleanupWorkList);
[MethodImplAttribute(MethodImplOptions.InternalCall)]
static internal extern object ConvertToManaged(IntPtr pUnk, IntPtr itfMT, IntPtr classMT, int flags);
- [SecurityCritical]
[DllImport(JitHelpers.QCall), SuppressUnmanagedCodeSecurity]
static internal extern void ClearNative(IntPtr pUnk);
static internal extern string GetRawUriFromNative(IntPtr pUri);
[MethodImplAttribute(MethodImplOptions.InternalCall)]
- [System.Security.SecurityCritical]
static unsafe internal extern IntPtr CreateNativeUriInstanceHelper(char* rawUri, int strLen);
- [System.Security.SecurityCritical]
static unsafe internal IntPtr CreateNativeUriInstance(string rawUri)
{
fixed(char* pManaged = rawUri)
[FriendAccessAllowed]
internal static class EventArgsMarshaler
{
- [SecurityCritical]
[FriendAccessAllowed]
static internal IntPtr CreateNativeNCCEventArgsInstance(int action, object newItems, object oldItems, int newIndex, int oldIndex)
{
}
}
- [SecurityCritical]
[FriendAccessAllowed]
[DllImport(JitHelpers.QCall), SuppressUnmanagedCodeSecurity]
static extern internal IntPtr CreateNativePCEventArgsInstance([MarshalAs(UnmanagedType.HString)]string name);
- [SecurityCritical]
[DllImport(JitHelpers.QCall), SuppressUnmanagedCodeSecurity]
static extern internal IntPtr CreateNativeNCCEventArgsInstanceHelper(int action, IntPtr newItem, IntPtr oldItem, int newIndex, int oldIndex);
}
[ReliabilityContract(Consistency.WillNotCorruptState, Cer.MayFail)]
internal static class MngdHiddenLengthArrayMarshaler
{
- [SecurityCritical]
[MethodImplAttribute(MethodImplOptions.InternalCall)]
static internal extern void CreateMarshaler(IntPtr pMarshalState, IntPtr pMT, IntPtr cbElementSize, ushort vt);
- [SecurityCritical]
[MethodImplAttribute(MethodImplOptions.InternalCall)]
internal static extern void ConvertSpaceToNative(IntPtr pMarshalState, ref object pManagedHome, IntPtr pNativeHome);
- [SecurityCritical]
[MethodImplAttribute(MethodImplOptions.InternalCall)]
internal static extern void ConvertContentsToNative(IntPtr pMarshalState, ref object pManagedHome, IntPtr pNativeHome);
- [SecurityCritical]
internal static unsafe void ConvertContentsToNative_DateTime(ref DateTimeOffset[] managedArray, IntPtr pNativeHome)
{
if (managedArray != null)
}
}
- [SecurityCritical]
internal static unsafe void ConvertContentsToNative_Type(ref System.Type[] managedArray, IntPtr pNativeHome)
{
if (managedArray != null)
}
}
- [SecurityCritical]
internal static unsafe void ConvertContentsToNative_Exception(ref Exception[] managedArray, IntPtr pNativeHome)
{
if (managedArray != null)
}
}
- [SecurityCritical]
internal static unsafe void ConvertContentsToNative_Nullable<T>(ref Nullable<T>[] managedArray, IntPtr pNativeHome)
where T : struct
{
}
}
- [SecurityCritical]
internal static unsafe void ConvertContentsToNative_KeyValuePair<K, V>(ref KeyValuePair<K, V>[] managedArray, IntPtr pNativeHome)
{
if (managedArray != null)
}
}
- [SecurityCritical]
[MethodImplAttribute(MethodImplOptions.InternalCall)]
internal static extern void ConvertSpaceToManaged(IntPtr pMarshalState, ref object pManagedHome, IntPtr pNativeHome, int elementCount);
- [SecurityCritical]
[MethodImplAttribute(MethodImplOptions.InternalCall)]
internal static extern void ConvertContentsToManaged(IntPtr pMarshalState, ref object pManagedHome, IntPtr pNativeHome);
- [SecurityCritical]
internal static unsafe void ConvertContentsToManaged_DateTime(ref DateTimeOffset[] managedArray, IntPtr pNativeHome)
{
if (managedArray != null)
}
}
- [SecurityCritical]
internal static unsafe void ConvertContentsToManaged_Type(ref System.Type[] managedArray, IntPtr pNativeHome)
{
if (managedArray != null)
}
}
- [SecurityCritical]
internal static unsafe void ConvertContentsToManaged_Exception(ref Exception[] managedArray, IntPtr pNativeHome)
{
if (managedArray != null)
}
}
- [SecurityCritical]
internal static unsafe void ConvertContentsToManaged_Nullable<T>(ref Nullable<T>[] managedArray, IntPtr pNativeHome)
where T : struct
{
}
}
- [SecurityCritical]
internal static unsafe void ConvertContentsToManaged_KeyValuePair<K, V>(ref KeyValuePair<K, V>[] managedArray, IntPtr pNativeHome)
{
if (managedArray != null)
}
}
- [SecurityCritical]
[MethodImplAttribute(MethodImplOptions.InternalCall)]
internal static extern void ClearNativeContents(IntPtr pMarshalState, IntPtr pNativeHome, int cElements);
- [SecurityCritical]
internal static unsafe void ClearNativeContents_Type(IntPtr pNativeHome, int cElements)
{
- Contract.Assert(Environment.IsWinRTSupported);
+ Debug.Assert(Environment.IsWinRTSupported);
TypeNameNative *pNativeTypeArray = *(TypeNameNative **)pNativeHome;
if (pNativeTypeArray != null)
} // class MngdRefCustomMarshaler
[ReliabilityContract(Consistency.WillNotCorruptState, Cer.MayFail)]
- [System.Security.SecurityCritical]
internal struct AsAnyMarshaler
{
private const ushort VTHACK_ANSICHAR = 253;
#region ConvertToNative helpers
- [System.Security.SecurityCritical]
private unsafe IntPtr ConvertArrayToNative(object pManagedHome, int dwFlags)
{
Type elementType = pManagedHome.GetType().GetElementType();
return pNativeHome;
}
- [System.Security.SecurityCritical]
private static IntPtr ConvertStringToNative(string pManagedHome, int dwFlags)
{
IntPtr pNativeHome;
return pNativeHome;
}
- [System.Security.SecurityCritical]
private unsafe IntPtr ConvertStringBuilderToNative(StringBuilder pManagedHome, int dwFlags)
{
IntPtr pNativeHome;
ptr, allocSize,
IsBestFit(dwFlags),
IsThrowOn(dwFlags));
- Contract.Assert(length < allocSize, "Expected a length less than the allocated size");
+ Debug.Assert(length < allocSize, "Expected a length less than the allocated size");
}
if (IsOut(dwFlags))
{
return pNativeHome;
}
- [System.Security.SecurityCritical]
private unsafe IntPtr ConvertLayoutToNative(object pManagedHome, int dwFlags)
{
// Note that the following call will not throw exception if the type
#endregion
- [System.Security.SecurityCritical]
internal IntPtr ConvertToNative(object pManagedHome, int dwFlags)
{
if (pManagedHome == null)
return pNativeHome;
}
- [System.Security.SecurityCritical]
internal unsafe void ConvertToManaged(object pManagedHome, IntPtr pNativeHome)
{
switch (backPropAction)
}
}
- [System.Security.SecurityCritical]
internal void ClearNative(IntPtr pNativeHome)
{
if (pNativeHome != IntPtr.Zero)
[ReliabilityContract(Consistency.WillNotCorruptState, Cer.MayFail)]
internal static class NullableMarshaler
{
- [SecurityCritical]
static internal IntPtr ConvertToNative<T>(ref Nullable<T> pManaged) where T : struct
{
if (pManaged.HasValue)
}
}
- [SecurityCritical]
static internal void ConvertToManagedRetVoid<T>(IntPtr pNative, ref Nullable<T> retObj) where T : struct
{
retObj = ConvertToManaged<T>(pNative);
}
- [SecurityCritical]
static internal Nullable<T> ConvertToManaged<T>(IntPtr pNative) where T : struct
{
if (pNative != IntPtr.Zero)
[ReliabilityContract(Consistency.WillNotCorruptState, Cer.MayFail)]
internal static class SystemTypeMarshaler
{
- [SecurityCritical]
internal static unsafe void ConvertToNative(System.Type managedType, TypeNameNative *pNativeType)
{
if (!Environment.IsWinRTSupported)
Marshal.ThrowExceptionForHR(hrCreate, new IntPtr(-1));
}
- [SecurityCritical]
internal static unsafe void ConvertToManaged(TypeNameNative *pNativeType, ref System.Type managedType)
{
if (!Environment.IsWinRTSupported)
}
}
- [SecurityCritical]
internal static unsafe void ClearNative(TypeNameNative *pNativeType)
{
- Contract.Assert(Environment.IsWinRTSupported);
+ Debug.Assert(Environment.IsWinRTSupported);
if (pNativeType->typeName != IntPtr.Zero)
{
return ex._HResult;
}
- [SecuritySafeCritical]
static internal unsafe Exception ConvertToManaged(int hr)
{
Contract.Ensures(Contract.Result<Exception>() != null || hr >= 0);
// S_OK should be marshaled as null. WinRT API's should not return S_FALSE by convention.
// We've chosen to treat S_FALSE as success and return null.
- Contract.Assert(e != null || hr == 0 || hr == 1, "Unexpected HRESULT - it is a success HRESULT (without the high bit set) other than S_OK & S_FALSE.");
+ Debug.Assert(e != null || hr == 0 || hr == 1, "Unexpected HRESULT - it is a success HRESULT (without the high bit set) other than S_OK & S_FALSE.");
return e;
}
} // class HResultExceptionMarshaler
[ReliabilityContract(Consistency.WillNotCorruptState, Cer.MayFail)]
internal static class KeyValuePairMarshaler
{
- [SecurityCritical]
internal static IntPtr ConvertToNative<K, V>([In] ref KeyValuePair<K, V> pair)
{
IKeyValuePair<K, V> impl = new CLRIKeyValuePairImpl<K, V>(ref pair);
return Marshal.GetComInterfaceForObject(impl, typeof(IKeyValuePair<K, V>));
}
- [SecurityCritical]
internal static KeyValuePair<K, V> ConvertToManaged<K, V>(IntPtr pInsp)
{
object obj = InterfaceMarshaler.ConvertToManagedWithoutUnboxing(pInsp);
}
// Called from COMInterfaceMarshaler
- [SecurityCritical]
internal static object ConvertToManagedBox<K, V>(IntPtr pInsp)
{
return (object)ConvertToManaged<K, V>(pInsp);
#endif
} // struct NativeVariant
-#if !BIT64 && !FEATURE_CORECLR
- // Structure filled by IL stubs if copy constructor(s) and destructor(s) need to be called
- // on value types pushed on the stack. The structure is stored in s_copyCtorStubDesc by
- // SetCopyCtorCookieChain and fetched by CopyCtorCallStubWorker. Must be stack-allocated.
- [StructLayout(LayoutKind.Sequential)]
- unsafe internal struct CopyCtorStubCookie
- {
- public void SetData(IntPtr srcInstancePtr, uint dstStackOffset, IntPtr ctorPtr, IntPtr dtorPtr)
- {
- m_srcInstancePtr = srcInstancePtr;
- m_dstStackOffset = dstStackOffset;
- m_ctorPtr = ctorPtr;
- m_dtorPtr = dtorPtr;
- }
-
- public void SetNext(IntPtr pNext)
- {
- m_pNext = pNext;
- }
-
- public IntPtr m_srcInstancePtr; // pointer to the source instance
- public uint m_dstStackOffset; // offset from the start of stack arguments of the pushed 'this' instance
-
- public IntPtr m_ctorPtr; // fnptr to the managed copy constructor, result of ldftn
- public IntPtr m_dtorPtr; // fnptr to the managed destructor, result of ldftn
-
- public IntPtr m_pNext; // pointer to next cookie in the chain or IntPtr.Zero
- } // struct CopyCtorStubCookie
-
- // Aggregates pointer to CopyCtorStubCookie and the target of the interop call.
- [StructLayout(LayoutKind.Sequential)]
- unsafe internal struct CopyCtorStubDesc
- {
- public IntPtr m_pCookie;
- public IntPtr m_pTarget;
- } // struct CopyCtorStubDes
-#endif // !BIT64 && !FEATURE_CORECLR
-
// Aggregates SafeHandle and the "owned" bit which indicates whether the SafeHandle
// has been successfully AddRef'ed. This allows us to do realiable cleanup (Release)
// if and only if it is needed.
- [System.Security.SecurityCritical]
internal sealed class CleanupWorkListElement
{
public CleanupWorkListElement(SafeHandle handle)
} // class CleanupWorkListElement
[ReliabilityContract(Consistency.WillNotCorruptState, Cer.MayFail)]
- [System.Security.SecurityCritical]
internal sealed class CleanupWorkList
{
private List<CleanupWorkListElement> m_list = new List<CleanupWorkListElement>();
}
} // class CleanupWorkList
- [System.Security.SecurityCritical] // auto-generated
[ReliabilityContract(Consistency.WillNotCorruptState, Cer.MayFail)]
[SuppressUnmanagedCodeSecurityAttribute()]
internal static class StubHelpers
[MethodImplAttribute(MethodImplOptions.InternalCall)]
static internal extern IntPtr GetDelegateTarget(Delegate pThis, ref IntPtr pStubArg);
-#if !BIT64 && !FEATURE_CORECLR
- // Written to by a managed stub helper, read by CopyCtorCallStubWorker in VM.
- [ThreadStatic]
- static CopyCtorStubDesc s_copyCtorStubDesc;
-
- static internal void SetCopyCtorCookieChain(IntPtr pStubArg, IntPtr pUnmngThis, int dwStubFlags, IntPtr pCookie)
- {
- // we store both the cookie chain head and the target of the copy ctor stub to a thread
- // static field to be accessed by the copy ctor (see code:CopyCtorCallStubWorker)
- s_copyCtorStubDesc.m_pCookie = pCookie;
- s_copyCtorStubDesc.m_pTarget = GetFinalStubTarget(pStubArg, pUnmngThis, dwStubFlags);
- }
-
- // Returns the final unmanaged stub target, ignores interceptors.
- [MethodImplAttribute(MethodImplOptions.InternalCall)]
- static internal extern IntPtr GetFinalStubTarget(IntPtr pStubArg, IntPtr pUnmngThis, int dwStubFlags);
-#endif // !FEATURE_CORECLR && !BIT64
-
-#if !FEATURE_CORECLR
- [MethodImplAttribute(MethodImplOptions.InternalCall)]
- static internal extern void DemandPermission(IntPtr pNMD);
-#endif // !FEATURE_CORECLR
-
-#if FEATURE_CORECLR
[MethodImplAttribute(MethodImplOptions.InternalCall)]
static internal extern void ClearLastError();
-#endif
[MethodImplAttribute(MethodImplOptions.InternalCall)]
static internal extern void SetLastError();
[MethodImplAttribute(MethodImplOptions.InternalCall)]
static internal extern void ThrowInteropParamException(int resID, int paramIdx);
- [System.Security.SecurityCritical]
static internal IntPtr AddToCleanupList(ref CleanupWorkList pCleanupWorkList, SafeHandle handle)
{
if (pCleanupWorkList == null)
return SafeHandleAddRef(handle, ref element.m_owned);
}
- [System.Security.SecurityCritical]
[ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)]
static internal void DestroyCleanupList(ref CleanupWorkList pCleanupWorkList)
{
//-------------------------------------------------------
// AddRefs the SH and returns the underlying unmanaged handle.
- [System.Security.SecurityCritical] // auto-generated
static internal IntPtr SafeHandleAddRef(SafeHandle pHandle, ref bool success)
{
if (pHandle == null)
}
// Releases the SH (to be called from finally block).
- [System.Security.SecurityCritical] // auto-generated
[ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)]
static internal void SafeHandleRelease(SafeHandle pHandle)
{
static internal extern IntPtr GetDelegateInvokeMethod(Delegate pThis);
[MethodImplAttribute(MethodImplOptions.InternalCall)]
- [System.Security.SecurityCritical]
static internal extern object GetWinRTFactoryObject(IntPtr pCPCMD);
[MethodImplAttribute(MethodImplOptions.InternalCall)]
- [System.Security.SecurityCritical]
static internal extern IntPtr GetWinRTFactoryReturnValue(object pThis, IntPtr pCtorEntry);
[MethodImplAttribute(MethodImplOptions.InternalCall)]
- [System.Security.SecurityCritical]
static internal extern IntPtr GetOuterInspectable(object pThis, IntPtr pCtorMD);
#if MDA_SUPPORTED
using System;
using System.Runtime.Serialization;
using System.Security.Permissions;
+ using System.Diagnostics;
using System.Diagnostics.Contracts;
// ASCIIEncoding
return EncodingForwarder.GetByteCount(this, chars);
}
- [System.Security.SecurityCritical] // auto-generated
[CLSCompliant(false)]
[System.Runtime.InteropServices.ComVisible(false)]
public override unsafe int GetByteCount(char* chars, int count)
return EncodingForwarder.GetBytes(this, chars, charIndex, charCount, bytes, byteIndex);
}
- [System.Security.SecurityCritical] // auto-generated
[CLSCompliant(false)]
[System.Runtime.InteropServices.ComVisible(false)]
public override unsafe int GetBytes(char* chars, int charCount, byte* bytes, int byteCount)
return EncodingForwarder.GetCharCount(this, bytes, index, count);
}
- [System.Security.SecurityCritical] // auto-generated
[CLSCompliant(false)]
[System.Runtime.InteropServices.ComVisible(false)]
public override unsafe int GetCharCount(byte* bytes, int count)
return EncodingForwarder.GetChars(this, bytes, byteIndex, byteCount, chars, charIndex);
}
- [System.Security.SecurityCritical] // auto-generated
[CLSCompliant(false)]
[System.Runtime.InteropServices.ComVisible(false)]
public unsafe override int GetChars(byte* bytes, int byteCount, char* chars, int charCount)
// GetByteCount
// Note: We start by assuming that the output will be the same as count. Having
// an encoder or fallback may change that assumption
- [System.Security.SecurityCritical] // auto-generated
internal override unsafe int GetByteCount(char* chars, int charCount, EncoderNLS encoder)
{
// Just need to ASSERT, this is called by something else internal that checked parameters already
- Contract.Assert(charCount >= 0, "[ASCIIEncoding.GetByteCount]count is negative");
- Contract.Assert(chars != null, "[ASCIIEncoding.GetByteCount]chars is null");
+ Debug.Assert(charCount >= 0, "[ASCIIEncoding.GetByteCount]count is negative");
+ Debug.Assert(chars != null, "[ASCIIEncoding.GetByteCount]chars is null");
// Assert because we shouldn't be able to have a null encoder.
- Contract.Assert(encoderFallback != null, "[ASCIIEncoding.GetByteCount]Attempting to use null fallback encoder");
+ Debug.Assert(encoderFallback != null, "[ASCIIEncoding.GetByteCount]Attempting to use null fallback encoder");
char charLeftOver = (char)0;
EncoderReplacementFallback fallback = null;
if (encoder != null)
{
charLeftOver = encoder.charLeftOver;
- Contract.Assert(charLeftOver == 0 || Char.IsHighSurrogate(charLeftOver),
+ Debug.Assert(charLeftOver == 0 || Char.IsHighSurrogate(charLeftOver),
"[ASCIIEncoding.GetByteCount]leftover character should be high surrogate");
fallback = encoder.Fallback as EncoderReplacementFallback;
}
// Verify that we have no fallbackbuffer, for ASCII its always empty, so just assert
- Contract.Assert(!encoder.m_throwOnOverflow || !encoder.InternalHasFallbackBuffer ||
+ Debug.Assert(!encoder.m_throwOnOverflow || !encoder.InternalHasFallbackBuffer ||
encoder.FallbackBuffer.Remaining == 0,
"[ASCIICodePageEncoding.GetByteCount]Expected empty fallback buffer");
// if (encoder.InternalHasFallbackBuffer && encoder.FallbackBuffer.Remaining > 0)
// We may have a left over character from last time, try and process it.
if (charLeftOver > 0)
{
- Contract.Assert(Char.IsHighSurrogate(charLeftOver), "[ASCIIEncoding.GetByteCount]leftover character should be high surrogate");
- Contract.Assert(encoder != null, "[ASCIIEncoding.GetByteCount]Expected encoder");
+ Debug.Assert(Char.IsHighSurrogate(charLeftOver), "[ASCIIEncoding.GetByteCount]leftover character should be high surrogate");
+ Debug.Assert(encoder != null, "[ASCIIEncoding.GetByteCount]Expected encoder");
// Since left over char was a surrogate, it'll have to be fallen back.
// Get Fallback
byteCount++;
}
- Contract.Assert(fallbackBuffer == null || fallbackBuffer.Remaining == 0,
+ Debug.Assert(fallbackBuffer == null || fallbackBuffer.Remaining == 0,
"[ASCIIEncoding.GetByteCount]Expected Empty fallback buffer");
return byteCount;
}
- [System.Security.SecurityCritical] // auto-generated
internal override unsafe int GetBytes(char* chars, int charCount,
byte* bytes, int byteCount, EncoderNLS encoder)
{
// Just need to ASSERT, this is called by something else internal that checked parameters already
- Contract.Assert(bytes != null, "[ASCIIEncoding.GetBytes]bytes is null");
- Contract.Assert(byteCount >= 0, "[ASCIIEncoding.GetBytes]byteCount is negative");
- Contract.Assert(chars != null, "[ASCIIEncoding.GetBytes]chars is null");
- Contract.Assert(charCount >= 0, "[ASCIIEncoding.GetBytes]charCount is negative");
+ Debug.Assert(bytes != null, "[ASCIIEncoding.GetBytes]bytes is null");
+ Debug.Assert(byteCount >= 0, "[ASCIIEncoding.GetBytes]byteCount is negative");
+ Debug.Assert(chars != null, "[ASCIIEncoding.GetBytes]chars is null");
+ Debug.Assert(charCount >= 0, "[ASCIIEncoding.GetBytes]charCount is negative");
// Assert because we shouldn't be able to have a null encoder.
- Contract.Assert(encoderFallback != null, "[ASCIIEncoding.GetBytes]Attempting to use null encoder fallback");
+ Debug.Assert(encoderFallback != null, "[ASCIIEncoding.GetBytes]Attempting to use null encoder fallback");
// Get any left over characters
char charLeftOver = (char)0;
fallbackBuffer.InternalInitialize(charStart, charEnd, encoder, true);
}
- Contract.Assert(charLeftOver == 0 || Char.IsHighSurrogate(charLeftOver),
+ Debug.Assert(charLeftOver == 0 || Char.IsHighSurrogate(charLeftOver),
"[ASCIIEncoding.GetBytes]leftover character should be high surrogate");
// Verify that we have no fallbackbuffer, for ASCII its always empty, so just assert
- Contract.Assert(!encoder.m_throwOnOverflow || !encoder.InternalHasFallbackBuffer ||
+ Debug.Assert(!encoder.m_throwOnOverflow || !encoder.InternalHasFallbackBuffer ||
encoder.FallbackBuffer.Remaining == 0,
"[ASCIICodePageEncoding.GetBytes]Expected empty fallback buffer");
// if (encoder.m_throwOnOverflow && encoder.InternalHasFallbackBuffer &&
if (charLeftOver > 0)
{
// Initialize the buffer
- Contract.Assert(encoder != null,
+ Debug.Assert(encoder != null,
"[ASCIIEncoding.GetBytes]Expected non null encoder if we have surrogate left over");
fallbackBuffer = encoder.FallbackBuffer;
fallbackBuffer.InternalInitialize(chars, charEnd, encoder, true);
// didn't use this char, we'll throw or use buffer
if (fallbackBuffer == null || fallbackBuffer.bFallingBack == false)
{
- Contract.Assert(chars > charStart || bytes == byteStart,
+ Debug.Assert(chars > charStart || bytes == byteStart,
"[ASCIIEncoding.GetBytes]Expected chars to have advanced already.");
chars--; // don't use last char
}
encoder.m_charsUsed = (int)(chars - charStart);
}
- Contract.Assert(fallbackBuffer == null || fallbackBuffer.Remaining == 0 ||
+ Debug.Assert(fallbackBuffer == null || fallbackBuffer.Remaining == 0 ||
(encoder != null && !encoder.m_throwOnOverflow ),
"[ASCIIEncoding.GetBytes]Expected Empty fallback buffer at end");
}
// This is internal and called by something else,
- [System.Security.SecurityCritical] // auto-generated
internal override unsafe int GetCharCount(byte* bytes, int count, DecoderNLS decoder)
{
// Just assert, we're called internally so these should be safe, checked already
- Contract.Assert(bytes != null, "[ASCIIEncoding.GetCharCount]bytes is null");
- Contract.Assert(count >= 0, "[ASCIIEncoding.GetCharCount]byteCount is negative");
+ Debug.Assert(bytes != null, "[ASCIIEncoding.GetCharCount]bytes is null");
+ Debug.Assert(count >= 0, "[ASCIIEncoding.GetCharCount]byteCount is negative");
// ASCII doesn't do best fit, so don't have to check for it, find out which decoder fallback we're using
DecoderReplacementFallback fallback = null;
else
{
fallback = decoder.Fallback as DecoderReplacementFallback;
- Contract.Assert(!decoder.m_throwOnOverflow || !decoder.InternalHasFallbackBuffer ||
+ Debug.Assert(!decoder.m_throwOnOverflow || !decoder.InternalHasFallbackBuffer ||
decoder.FallbackBuffer.Remaining == 0,
"[ASCIICodePageEncoding.GetCharCount]Expected empty fallback buffer");
}
}
// Fallback buffer must be empty
- Contract.Assert(fallbackBuffer == null || fallbackBuffer.Remaining == 0,
+ Debug.Assert(fallbackBuffer == null || fallbackBuffer.Remaining == 0,
"[ASCIIEncoding.GetCharCount]Expected Empty fallback buffer");
// Converted sequence is same length as input
return charCount;
}
- [System.Security.SecurityCritical] // auto-generated
internal override unsafe int GetChars(byte* bytes, int byteCount,
char* chars, int charCount, DecoderNLS decoder)
{
// Just need to ASSERT, this is called by something else internal that checked parameters already
- Contract.Assert(bytes != null, "[ASCIIEncoding.GetChars]bytes is null");
- Contract.Assert(byteCount >= 0, "[ASCIIEncoding.GetChars]byteCount is negative");
- Contract.Assert(chars != null, "[ASCIIEncoding.GetChars]chars is null");
- Contract.Assert(charCount >= 0, "[ASCIIEncoding.GetChars]charCount is negative");
+ Debug.Assert(bytes != null, "[ASCIIEncoding.GetChars]bytes is null");
+ Debug.Assert(byteCount >= 0, "[ASCIIEncoding.GetChars]byteCount is negative");
+ Debug.Assert(chars != null, "[ASCIIEncoding.GetChars]chars is null");
+ Debug.Assert(charCount >= 0, "[ASCIIEncoding.GetChars]charCount is negative");
// Do it fast way if using ? replacement fallback
byte* byteEnd = bytes + byteCount;
else
{
fallback = decoder.Fallback as DecoderReplacementFallback;
- Contract.Assert(!decoder.m_throwOnOverflow || !decoder.InternalHasFallbackBuffer ||
+ Debug.Assert(!decoder.m_throwOnOverflow || !decoder.InternalHasFallbackBuffer ||
decoder.FallbackBuffer.Remaining == 0,
"[ASCIICodePageEncoding.GetChars]Expected empty fallback buffer");
}
if (!fallbackBuffer.InternalFallback(byteBuffer, bytes, ref chars))
{
// May or may not throw, but we didn't get this byte
- Contract.Assert(bytes > byteStart || chars == charStart,
+ Debug.Assert(bytes > byteStart || chars == charStart,
"[ASCIIEncoding.GetChars]Expected bytes to have advanced already (fallback case)");
bytes--; // unused byte
fallbackBuffer.InternalReset(); // Didn't fall this back
// Make sure we have buffer space
if (chars >= charEnd)
{
- Contract.Assert(bytes > byteStart || chars == charStart,
+ Debug.Assert(bytes > byteStart || chars == charStart,
"[ASCIIEncoding.GetChars]Expected bytes to have advanced already (normal case)");
bytes--; // unused byte
ThrowCharsOverflow(decoder, chars == charStart); // throw?
decoder.m_bytesUsed = (int)(bytes - byteStart);
// Expect Empty fallback buffer for GetChars
- Contract.Assert(fallbackBuffer == null || fallbackBuffer.Remaining == 0,
+ Debug.Assert(fallbackBuffer == null || fallbackBuffer.Remaining == 0,
"[ASCIIEncoding.GetChars]Expected Empty fallback buffer");
return (int)(chars - charStart);
namespace System.Text
{
using System;
+ using System.Diagnostics;
using System.Diagnostics.Contracts;
using System.Globalization;
using System.Runtime.InteropServices;
[NonSerialized]
protected bool m_bUseMlangTypeForSerialization = false;
- [System.Security.SecuritySafeCritical] // static constructors should be safe to call
static BaseCodePageEncoding()
{
}
}
// Initialize our global stuff
- [SecurityCritical]
unsafe static CodePageDataFileHeader* m_pCodePageFileHeader =
(CodePageDataFileHeader*)GlobalizationAssembly.GetGlobalizationResourceBytePtr(
typeof(CharUnicodeInfo).Assembly, CODE_PAGE_DATA_FILE_NAME);
// Real variables
[NonSerialized]
- [SecurityCritical]
unsafe protected CodePageHeader* pCodePage = null;
// Safe handle wrapper around section map view
- [System.Security.SecurityCritical] // auto-generated
[NonSerialized]
protected SafeViewOfFileHandle safeMemorySectionHandle = null;
// Safe handle wrapper around mapped file handle
- [System.Security.SecurityCritical] // auto-generated
[NonSerialized]
protected SafeFileMappingHandle safeFileMappingHandle = null;
- [System.Security.SecurityCritical] // auto-generated
internal BaseCodePageEncoding(int codepage) : this(codepage, codepage)
{
}
- [System.Security.SecurityCritical] // auto-generated
internal BaseCodePageEncoding(int codepage, int dataCodePage) :
base(codepage == 0? Microsoft.Win32.Win32Native.GetACP(): codepage)
{
}
// Constructor called by serialization.
- [System.Security.SecurityCritical] // auto-generated
internal BaseCodePageEncoding(SerializationInfo info, StreamingContext context) : base(0)
{
// We cannot ever call this, we've proxied ourselved to CodePageEncoding
}
// ISerializable implementation
- [System.Security.SecurityCritical] // auto-generated_required
void ISerializable.GetObjectData(SerializationInfo info, StreamingContext context)
{
// Make sure to get the base stuff too This throws if info is null
SerializeEncoding(info, context);
- Contract.Assert(info!=null, "[BaseCodePageEncoding.GetObjectData] Expected null info to throw");
+ Debug.Assert(info!=null, "[BaseCodePageEncoding.GetObjectData] Expected null info to throw");
// Just need Everett maxCharSize (BaseCodePageEncoding) or m_maxByteSize (MLangBaseCodePageEncoding)
info.AddValue(m_bUseMlangTypeForSerialization ? "m_maxByteSize" : "maxCharSize",
}
// We need to load tables for our code page
- [System.Security.SecurityCritical] // auto-generated
private unsafe void LoadCodePageTables()
{
CodePageHeader* pCodePage = FindCodePage(dataTableCodePage);
}
// Look up the code page pointer
- [System.Security.SecurityCritical] // auto-generated
private static unsafe CodePageHeader* FindCodePage(int codePage)
{
// We'll have to loop through all of the m_pCodePageIndex[] items to find our code page, this isn't
}
// Get our code page byte count
- [System.Security.SecurityCritical] // auto-generated
internal static unsafe int GetCodePageByteSize(int codePage)
{
// Get our code page info
if (pCodePage == null)
return 0;
- Contract.Assert(pCodePage->ByteCount == 1 || pCodePage->ByteCount == 2,
+ Debug.Assert(pCodePage->ByteCount == 1 || pCodePage->ByteCount == 2,
"[BaseCodePageEncoding] Code page (" + codePage + ") has invalid byte size (" + pCodePage->ByteCount + ") in table");
// Return what it says for byte count
return pCodePage->ByteCount;
}
// We have a managed code page entry, so load our tables
- [System.Security.SecurityCritical]
protected abstract unsafe void LoadManagedCodePage();
// Allocate memory to load our code page
- [System.Security.SecurityCritical] // auto-generated
protected unsafe byte* GetSharedMemory(int iSize)
{
// Build our name
// This gets shared memory for our map. If its can't, it gives us clean memory.
Byte *pMemorySection = EncodingTable.nativeCreateOpenFileMapping(strName, iSize, out mappedFileHandle);
- Contract.Assert(pMemorySection != null,
+ Debug.Assert(pMemorySection != null,
"[BaseCodePageEncoding.GetSharedMemory] Expected non-null memory section to be opened");
// If that failed, we have to die.
return pMemorySection;
}
- [System.Security.SecurityCritical] // auto-generated
protected unsafe virtual String GetMemorySectionName()
{
int iUseCodePage = this.bFlagDataTable ? dataTableCodePage : CodePage;
return strName;
}
- [System.Security.SecurityCritical]
protected abstract unsafe void ReadBestFitTable();
- [System.Security.SecuritySafeCritical]
internal override char[] GetBestFitUnicodeToBytesData()
{
// Read in our best fit table if necessary
if (arrayUnicodeBestFit == null) ReadBestFitTable();
- Contract.Assert(arrayUnicodeBestFit != null,
+ Debug.Assert(arrayUnicodeBestFit != null,
"[BaseCodePageEncoding.GetBestFitUnicodeToBytesData]Expected non-null arrayUnicodeBestFit");
// Normally we don't have any best fit data.
return arrayUnicodeBestFit;
}
- [System.Security.SecuritySafeCritical]
internal override char[] GetBestFitBytesToUnicodeData()
{
// Read in our best fit table if necessary
if (arrayBytesBestFit == null) ReadBestFitTable();
- Contract.Assert(arrayBytesBestFit != null,
+ Debug.Assert(arrayBytesBestFit != null,
"[BaseCodePageEncoding.GetBestFitBytesToUnicodeData]Expected non-null arrayBytesBestFit");
// Normally we don't have any best fit data.
// is invalid. so we detect that by validating the memory section handle then re-initialize the memory
// section by calling LoadManagedCodePage() method and eventually the mapped file handle and
// the memory section pointer will get finalized one more time.
- [System.Security.SecurityCritical] // auto-generated
internal unsafe void CheckMemorySection()
{
if (safeMemorySectionHandle != null && safeMemorySectionHandle.DangerousGetHandle() == IntPtr.Zero)
using System;
using System.Runtime.Serialization;
using System.Security.Permissions;
+ using System.Diagnostics;
using System.Diagnostics.Contracts;
/*=================================CodePageEncoding==================================
}
// Just get it from GetEncoding
- [System.Security.SecurityCritical] // auto-generated
public Object GetRealObject(StreamingContext context)
{
// Get our encoding (Note: This has default fallbacks for readonly and everett cases)
}
// ISerializable implementation
- [System.Security.SecurityCritical] // auto-generated_required
void ISerializable.GetObjectData(SerializationInfo info, StreamingContext context)
{
// We cannot ever call this.
- Contract.Assert(false, "Didn't expect to make it to CodePageEncoding ISerializable.GetObjectData");
+ Debug.Assert(false, "Didn't expect to make it to CodePageEncoding ISerializable.GetObjectData");
throw new ArgumentException(Environment.GetResourceString("Arg_ExecutionEngineException"));
}
}
// Just get it from GetDecider
- [System.Security.SecurityCritical] // auto-generated
public Object GetRealObject(StreamingContext context)
{
return this.realEncoding.GetDecoder();
}
// ISerializable implementation, get data for this object
- [System.Security.SecurityCritical] // auto-generated_required
void ISerializable.GetObjectData(SerializationInfo info, StreamingContext context)
{
// We cannot ever call this.
- Contract.Assert(false, "Didn't expect to make it to CodePageEncoding.Decoder.GetObjectData");
+ Debug.Assert(false, "Didn't expect to make it to CodePageEncoding.Decoder.GetObjectData");
throw new ArgumentException(Environment.GetResourceString("Arg_ExecutionEngineException"));
}
}
namespace System.Text
{
using System;
+ using System.Diagnostics;
using System.Diagnostics.Contracts;
using System.Text;
using System.Threading;
{
// Pointers to our memory section parts
[NonSerialized]
- [SecurityCritical]
protected unsafe char* mapBytesToUnicode = null; // char 65536
[NonSerialized]
- [SecurityCritical]
protected unsafe ushort* mapUnicodeToBytes = null; // byte 65536
[NonSerialized]
- [SecurityCritical]
protected unsafe int* mapCodePageCached = null; // to remember which CP is cached
[NonSerialized]
[NonSerialized]
protected char charUnknown = (char)0;
- [System.Security.SecurityCritical] // auto-generated
public DBCSCodePageEncoding(int codePage) : this(codePage, codePage)
{
}
- [System.Security.SecurityCritical] // auto-generated
internal DBCSCodePageEncoding(int codePage, int dataCodePage) : base(codePage, dataCodePage)
{
}
// Constructor called by serialization.
// Note: We use the base GetObjectData however
- [System.Security.SecurityCritical] // auto-generated
internal DBCSCodePageEncoding(SerializationInfo info, StreamingContext context) : base(0)
{
// Actually this can't ever get called, CodePageEncoding is our proxy
- Contract.Assert(false, "Didn't expect to make it to DBCSCodePageEncoding serialization constructor");
+ Debug.Assert(false, "Didn't expect to make it to DBCSCodePageEncoding serialization constructor");
throw new ArgumentNullException("this");
}
// corrospond to those unicode code points.
// We have a managed code page entry, so load our tables
//
- [System.Security.SecurityCritical] // auto-generated
protected override unsafe void LoadManagedCodePage()
{
// Should be loading OUR code page
- Contract.Assert(pCodePage->CodePage == this.dataTableCodePage,
+ Debug.Assert(pCodePage->CodePage == this.dataTableCodePage,
"[DBCSCodePageEncoding.LoadManagedCodePage]Expected to load data table code page");
// Make sure we're really a 1 byte code page
byteCountUnknown++;
// We use fallback encoder, which uses ?, which so far all of our tables do as well
- Contract.Assert(bytesUnknown == 0x3f,
+ Debug.Assert(bytesUnknown == 0x3f,
"[DBCSCodePageEncoding.LoadManagedCodePage]Expected 0x3f (?) as unknown byte character");
// Get our mapped section (bytes to allocate = 2 bytes per 65536 Unicode chars + 2 bytes per 65536 DBCS chars)
// If its cached (& filled in) we don't have to do anything else
if (*mapCodePageCached != 0)
{
- Contract.Assert(((*mapCodePageCached == this.dataTableCodePage && this.bFlagDataTable) ||
+ Debug.Assert(((*mapCodePageCached == this.dataTableCodePage && this.bFlagDataTable) ||
(*mapCodePageCached == this.CodePage && !this.bFlagDataTable)),
"[DBCSCodePageEncoding.LoadManagedCodePage]Expected mapped section cached page flag to be set to data table or regular code page.");
else if (input == LEAD_BYTE_CHAR) // 0xfffe
{
// Lead byte mark
- Contract.Assert(bytePosition < 0x100, "[DBCSCodePageEncoding.LoadManagedCodePage]expected lead byte to be < 0x100");
+ Debug.Assert(bytePosition < 0x100, "[DBCSCodePageEncoding.LoadManagedCodePage]expected lead byte to be < 0x100");
useBytes = bytePosition;
// input stays 0xFFFE
}
}
// Any special processing for this code page
- [System.Security.SecurityCritical] // auto-generated
protected virtual unsafe void CleanUpEndBytes(char* chars)
{
}
}
// Read in our best fit table
- [System.Security.SecurityCritical] // auto-generated
protected unsafe override void ReadBestFitTable()
{
// Lock so we don't confuse ourselves.
// If they're out of order we need to sort them.
if (bOutOfOrder)
{
- Contract.Assert((arrayTemp.Length / 2) < 20,
+ Debug.Assert((arrayTemp.Length / 2) < 20,
"[DBCSCodePageEncoding.ReadBestFitTable]Expected small best fit table < 20 for code page " + CodePage + ", not " + arrayTemp.Length / 2);
for (int i = 0; i < arrayTemp.Length - 2; i+=2)
// We can't do this assert for CP 51932 & 50220 because they aren't
// calling CleanUpBytes() for best fit. All the string stuff here
// also makes this assert slow.
- // Contract.Assert(arrayTemp[iBestFitCount-1] != (char)0xFFFD, String.Format(
+ // Debug.Assert(arrayTemp[iBestFitCount-1] != (char)0xFFFD, String.Format(
// "[DBCSCodePageEncoding.ReadBestFitTable] No valid Unicode value {0:X4} for round trip bytes {1:X4}, encoding {2}",
// (int)mapBytesToUnicode[input], (int)input, CodePage));
}
// GetByteCount
// Note: We start by assuming that the output will be the same as count. Having
// an encoder or fallback may change that assumption
- [System.Security.SecurityCritical] // auto-generated
internal override unsafe int GetByteCount(char* chars, int count, EncoderNLS encoder)
{
// Just need to ASSERT, this is called by something else internal that checked parameters already
- Contract.Assert(count >= 0, "[DBCSCodePageEncoding.GetByteCount]count is negative");
- Contract.Assert(chars != null, "[DBCSCodePageEncoding.GetByteCount]chars is null");
+ Debug.Assert(count >= 0, "[DBCSCodePageEncoding.GetByteCount]count is negative");
+ Debug.Assert(chars != null, "[DBCSCodePageEncoding.GetByteCount]chars is null");
// Assert because we shouldn't be able to have a null encoder.
- Contract.Assert(encoderFallback != null, "[DBCSCodePageEncoding.GetByteCount]Attempting to use null fallback");
+ Debug.Assert(encoderFallback != null, "[DBCSCodePageEncoding.GetByteCount]Attempting to use null fallback");
CheckMemorySection();
// We may have a left over character from last time, try and process it.
if (charLeftOver > 0)
{
- Contract.Assert(Char.IsHighSurrogate(charLeftOver), "[DBCSCodePageEncoding.GetByteCount]leftover character should be high surrogate");
- Contract.Assert(encoder != null,
+ Debug.Assert(Char.IsHighSurrogate(charLeftOver), "[DBCSCodePageEncoding.GetByteCount]leftover character should be high surrogate");
+ Debug.Assert(encoder != null,
"[DBCSCodePageEncoding.GetByteCount]Expect to have encoder if we have a charLeftOver");
// Since left over char was a surrogate, it'll have to be fallen back.
return (int)byteCount;
}
- [System.Security.SecurityCritical] // auto-generated
internal override unsafe int GetBytes(char* chars, int charCount,
byte* bytes, int byteCount, EncoderNLS encoder)
{
// Just need to ASSERT, this is called by something else internal that checked parameters already
- Contract.Assert(bytes != null, "[DBCSCodePageEncoding.GetBytes]bytes is null");
- Contract.Assert(byteCount >= 0, "[DBCSCodePageEncoding.GetBytes]byteCount is negative");
- Contract.Assert(chars != null, "[DBCSCodePageEncoding.GetBytes]chars is null");
- Contract.Assert(charCount >= 0, "[DBCSCodePageEncoding.GetBytes]charCount is negative");
+ Debug.Assert(bytes != null, "[DBCSCodePageEncoding.GetBytes]bytes is null");
+ Debug.Assert(byteCount >= 0, "[DBCSCodePageEncoding.GetBytes]byteCount is negative");
+ Debug.Assert(chars != null, "[DBCSCodePageEncoding.GetBytes]chars is null");
+ Debug.Assert(charCount >= 0, "[DBCSCodePageEncoding.GetBytes]charCount is negative");
// Assert because we shouldn't be able to have a null encoder.
- Contract.Assert(encoderFallback != null, "[DBCSCodePageEncoding.GetBytes]Attempting to use null encoder fallback");
+ Debug.Assert(encoderFallback != null, "[DBCSCodePageEncoding.GetBytes]Attempting to use null encoder fallback");
CheckMemorySection();
if (encoder != null)
{
charLeftOver = encoder.charLeftOver;
- Contract.Assert(charLeftOver == 0 || Char.IsHighSurrogate(charLeftOver),
+ Debug.Assert(charLeftOver == 0 || Char.IsHighSurrogate(charLeftOver),
"[DBCSCodePageEncoding.GetBytes]leftover character should be high surrogate");
// Go ahead and get the fallback buffer (need leftover fallback if converting)
// We may have a left over character from last time, try and process it.
if (charLeftOver > 0)
{
- Contract.Assert(encoder != null,
+ Debug.Assert(encoder != null,
"[DBCSCodePageEncoding.GetBytes]Expect to have encoder if we have a charLeftOver");
// Since left over char was a surrogate, it'll have to be fallen back.
if (fallbackBuffer == null)
{
// Initialize the buffer
- Contract.Assert(encoder == null,
+ Debug.Assert(encoder == null,
"[DBCSCodePageEncoding.GetBytes]Expected delayed create fallback only if no encoder.");
fallbackBuffer = this.encoderFallback.CreateFallbackBuffer();
fallbackBuffer.InternalInitialize(charEnd - charCount, charEnd, encoder, true);
// didn't use this char, we'll throw or use buffer
if (fallbackBuffer == null || fallbackBuffer.bFallingBack == false)
{
- Contract.Assert(chars > charStart,
+ Debug.Assert(chars > charStart,
"[DBCSCodePageEncoding.GetBytes]Expected chars to have advanced (double byte case)");
chars--; // don't use last char
}
// didn't use this char, we'll throw or use buffer
if (fallbackBuffer == null || fallbackBuffer.bFallingBack == false)
{
- Contract.Assert(chars > charStart,
+ Debug.Assert(chars > charStart,
"[DBCSCodePageEncoding.GetBytes]Expected chars to have advanced (single byte case)");
chars--; // don't use last char
}
// If we're not converting we must not have a fallback buffer
// (We don't really have a way to clear none-encoder using fallbacks however)
-// Contract.Assert((encoder == null || encoder.m_throwOnOverflow) &&
+// Debug.Assert((encoder == null || encoder.m_throwOnOverflow) &&
// (fallbackBuffer == null || fallbackBuffer.Remaining == 0),
// "[DBCSEncoding.GetBytes]Expected empty fallback buffer at end if not converting");
}
// This is internal and called by something else,
- [System.Security.SecurityCritical] // auto-generated
internal override unsafe int GetCharCount(byte* bytes, int count, DecoderNLS baseDecoder)
{
// Just assert, we're called internally so these should be safe, checked already
- Contract.Assert(bytes != null, "[DBCSCodePageEncoding.GetCharCount]bytes is null");
- Contract.Assert(count >= 0, "[DBCSCodePageEncoding.GetCharCount]byteCount is negative");
+ Debug.Assert(bytes != null, "[DBCSCodePageEncoding.GetCharCount]bytes is null");
+ Debug.Assert(count >= 0, "[DBCSCodePageEncoding.GetCharCount]byteCount is negative");
CheckMemorySection();
// Shouldn't have anything in fallback buffer for GetCharCount
// (don't have to check m_throwOnOverflow for count)
- Contract.Assert(decoder == null ||
+ Debug.Assert(decoder == null ||
!decoder.InternalHasFallbackBuffer || decoder.FallbackBuffer.Remaining == 0,
"[DBCSCodePageEncoding.GetCharCount]Expected empty fallback buffer at start");
}
- Contract.Assert(fallbackBuffer == null,
+ Debug.Assert(fallbackBuffer == null,
"[DBCSCodePageEncoding.GetCharCount]Expected empty fallback buffer");
fallbackBuffer = decoder.FallbackBuffer;
fallbackBuffer.InternalInitialize(bytes, null);
charCount--;
// We'll need a fallback
- Contract.Assert(fallbackBuffer == null,
+ Debug.Assert(fallbackBuffer == null,
"[DBCSCodePageEncoding.GetCharCount]Expected empty fallback buffer for unknown pair");
fallbackBuffer = decoder.FallbackBuffer;
fallbackBuffer.InternalInitialize(byteEnd - count, null);
}
// Shouldn't have anything in fallback buffer for GetChars
- Contract.Assert(decoder == null || !decoder.m_throwOnOverflow ||
+ Debug.Assert(decoder == null || !decoder.m_throwOnOverflow ||
!decoder.InternalHasFallbackBuffer || decoder.FallbackBuffer.Remaining == 0,
"[DBCSCodePageEncoding.GetCharCount]Expected empty fallback buffer at end");
return charCount;
}
- [System.Security.SecurityCritical] // auto-generated
internal override unsafe int GetChars(byte* bytes, int byteCount,
char* chars, int charCount, DecoderNLS baseDecoder)
{
// Just need to ASSERT, this is called by something else internal that checked parameters already
- Contract.Assert(bytes != null, "[DBCSCodePageEncoding.GetChars]bytes is null");
- Contract.Assert(byteCount >= 0, "[DBCSCodePageEncoding.GetChars]byteCount is negative");
- Contract.Assert(chars != null, "[DBCSCodePageEncoding.GetChars]chars is null");
- Contract.Assert(charCount >= 0, "[DBCSCodePageEncoding.GetChars]charCount is negative");
+ Debug.Assert(bytes != null, "[DBCSCodePageEncoding.GetChars]bytes is null");
+ Debug.Assert(byteCount >= 0, "[DBCSCodePageEncoding.GetChars]byteCount is negative");
+ Debug.Assert(chars != null, "[DBCSCodePageEncoding.GetChars]chars is null");
+ Debug.Assert(charCount >= 0, "[DBCSCodePageEncoding.GetChars]charCount is negative");
CheckMemorySection();
DecoderFallbackBuffer fallbackBuffer = null;
// Shouldn't have anything in fallback buffer for GetChars
- Contract.Assert(decoder == null || !decoder.m_throwOnOverflow ||
+ Debug.Assert(decoder == null || !decoder.m_throwOnOverflow ||
!decoder.InternalHasFallbackBuffer || decoder.FallbackBuffer.Remaining == 0,
"[DBCSCodePageEncoding.GetChars]Expected empty fallback buffer at start");
// Well, we're flushing, so use '?' or fallback
// fallback leftover byte
- Contract.Assert(fallbackBuffer == null,
+ Debug.Assert(fallbackBuffer == null,
"[DBCSCodePageEncoding.GetChars]Expected empty fallback");
fallbackBuffer = decoder.FallbackBuffer;
fallbackBuffer.InternalInitialize(bytes, charEnd);
char cDecoder = mapBytesToUnicode[iBytes];
if (cDecoder == UNKNOWN_CHAR_FLAG && iBytes != 0)
{
- Contract.Assert(fallbackBuffer == null,
+ Debug.Assert(fallbackBuffer == null,
"[DBCSCodePageEncoding.GetChars]Expected empty fallback for two bytes");
fallbackBuffer = decoder.FallbackBuffer;
fallbackBuffer.InternalInitialize(byteEnd - byteCount, charEnd);
if (!fallbackBuffer.InternalFallback(byteBuffer, bytes, ref chars))
{
// May or may not throw, but we didn't get these byte(s)
- Contract.Assert(bytes >= byteStart + byteBuffer.Length,
+ Debug.Assert(bytes >= byteStart + byteBuffer.Length,
"[DBCSCodePageEncoding.GetChars]Expected bytes to have advanced for fallback");
bytes-=byteBuffer.Length; // didn't use these byte(s)
fallbackBuffer.InternalReset(); // Didn't fall this back
if (chars >= charEnd)
{
// May or may not throw, but we didn't get these byte(s)
- Contract.Assert(bytes > byteStart,
+ Debug.Assert(bytes > byteStart,
"[DBCSCodePageEncoding.GetChars]Expected bytes to have advanced for lead byte");
bytes--; // unused byte
if (iBytes >= 0x100)
{
- Contract.Assert(bytes > byteStart,
+ Debug.Assert(bytes > byteStart,
"[DBCSCodePageEncoding.GetChars]Expected bytes to have advanced for trail byte");
bytes--; // 2nd unused byte
}
}
// Shouldn't have anything in fallback buffer for GetChars
- Contract.Assert(decoder == null || !decoder.m_throwOnOverflow ||
+ Debug.Assert(decoder == null || !decoder.m_throwOnOverflow ||
!decoder.InternalHasFallbackBuffer || decoder.FallbackBuffer.Remaining == 0,
"[DBCSCodePageEncoding.GetChars]Expected empty fallback buffer at end");
using System.Runtime.Serialization;
using System.Text;
using System;
+ using System.Diagnostics;
using System.Diagnostics.Contracts;
// A Decoder is used to decode a sequence of blocks of bytes into a
// sequence of blocks of characters. Following instantiation of a decoder,
// We expect this to be the workhorse for NLS Encodings, but for existing
// ones we need a working (if slow) default implimentation)
- [System.Security.SecurityCritical] // auto-generated
[CLSCompliant(false)]
[System.Runtime.InteropServices.ComVisible(false)]
public virtual unsafe int GetCharCount(byte* bytes, int count, bool flush)
// the char[] to our char* output buffer. If the result count was wrong, we
// could easily overflow our output buffer. Therefore we do an extra test
// when we copy the buffer so that we don't overflow charCount either.
- [System.Security.SecurityCritical] // auto-generated
[CLSCompliant(false)]
[System.Runtime.InteropServices.ComVisible(false)]
public virtual unsafe int GetChars(byte* bytes, int byteCount,
// Do the work
int result = GetChars(arrByte, 0, byteCount, arrChar, 0, flush);
- Contract.Assert(result <= charCount, "Returned more chars than we have space for");
+ Debug.Assert(result <= charCount, "Returned more chars than we have space for");
// Copy the char array
// WARNING: We MUST make sure that we don't copy too many chars. We can't
// Note that if all of the input bytes are not consumed, then we'll do a /2, which means
// that its likely that we didn't consume as many bytes as we could have. For some
// applications this could be slow. (Like trying to exactly fill an output buffer from a bigger stream)
- [System.Security.SecurityCritical] // auto-generated
[CLSCompliant(false)]
[System.Runtime.InteropServices.ComVisible(false)]
public virtual unsafe void Convert(byte* bytes, int byteCount,
using System;
using System.Text;
using System.Threading;
+ using System.Diagnostics;
using System.Diagnostics.Contracts;
[Serializable]
public override bool Fallback(byte[] bytesUnknown, int index)
{
// We expect no previous fallback in our buffer
- Contract.Assert(iCount < 1, "[DecoderReplacementFallbackBuffer.Fallback] Calling fallback without a previously empty buffer");
+ Debug.Assert(iCount < 1, "[DecoderReplacementFallbackBuffer.Fallback] Calling fallback without a previously empty buffer");
cBestFit = TryBestFit(bytesUnknown);
if (cBestFit == '\0')
}
// Clear the buffer
- [System.Security.SecuritySafeCritical] // overrides public transparent member
public override unsafe void Reset()
{
iCount = -1;
}
// This version just counts the fallback and doesn't actually copy anything.
- [System.Security.SecurityCritical] // auto-generated
internal unsafe override int InternalFallback(byte[] bytes, byte* pBytes)
// Right now this has both bytes and bytes[], since we might have extra bytes, hence the
// array, and we might need the index, hence the byte*
if (cTest == cCheck)
{
// We found it
- Contract.Assert(index + 1 < oFallback.arrayBestFit.Length,
+ Debug.Assert(index + 1 < oFallback.arrayBestFit.Length,
"[InternalDecoderBestFitFallbackBuffer.TryBestFit]Expected replacement character at end of array");
return oFallback.arrayBestFit[index + 1];
}
if (oFallback.arrayBestFit[index] == cCheck)
{
// We found it
- Contract.Assert(index + 1 < oFallback.arrayBestFit.Length,
+ Debug.Assert(index + 1 < oFallback.arrayBestFit.Length,
"[InternalDecoderBestFitFallbackBuffer.TryBestFit]Expected replacement character at end of array");
return oFallback.arrayBestFit[index + 1];
}
using System.Security;
using System.Threading;
using System.Globalization;
+using System.Diagnostics;
using System.Diagnostics.Contracts;
namespace System.Text
// Internal items to help us figure out what we're doing as far as error messages, etc.
// These help us with our performance and messages internally
- [SecurityCritical]
internal unsafe byte* byteStart;
- [SecurityCritical]
internal unsafe char* charEnd;
// Internal Reset
- [System.Security.SecurityCritical] // auto-generated
internal unsafe void InternalReset()
{
byteStart = null;
// Set the above values
// This can't be part of the constructor because DecoderFallbacks would have to know how to impliment these.
- [System.Security.SecurityCritical] // auto-generated
internal unsafe void InternalInitialize(byte* byteStart, char* charEnd)
{
this.byteStart = byteStart;
// Right now this has both bytes and bytes[], since we might have extra bytes, hence the
// array, and we might need the index, hence the byte*
// Don't touch ref chars unless we succeed
- [System.Security.SecurityCritical] // auto-generated
internal unsafe virtual bool InternalFallback(byte[] bytes, byte* pBytes, ref char* chars)
{
// Copy bytes to array (slow, but right now that's what we get to do.
// for (int i = 0; i < count; i++)
// bytesUnknown[i] = *(bytes++);
- Contract.Assert(byteStart != null, "[DecoderFallback.InternalFallback]Used InternalFallback without calling InternalInitialize");
+ Debug.Assert(byteStart != null, "[DecoderFallback.InternalFallback]Used InternalFallback without calling InternalInitialize");
// See if there's a fallback character and we have an output buffer then copy our string.
if (this.Fallback(bytes, (int)(pBytes - byteStart - bytes.Length)))
}
// This version just counts the fallback and doesn't actually copy anything.
- [System.Security.SecurityCritical] // auto-generated
internal unsafe virtual int InternalFallback(byte[] bytes, byte* pBytes)
// Right now this has both bytes and bytes[], since we might have extra bytes, hence the
// array, and we might need the index, hence the byte*
// for (int i = 0; i < count; i++)
// bytesUnknown[i] = *(bytes++);
- Contract.Assert(byteStart != null, "[DecoderFallback.InternalFallback]Used InternalFallback without calling InternalInitialize");
+ Debug.Assert(byteStart != null, "[DecoderFallback.InternalFallback]Used InternalFallback without calling InternalInitialize");
// See if there's a fallback character and we have an output buffer then copy our string.
if (this.Fallback(bytes, (int)(pBytes - byteStart - bytes.Length)))
}
// ISerializable implementation. called during serialization.
- [System.Security.SecurityCritical] // auto-generated_required
void ISerializable.GetObjectData(SerializationInfo info, StreamingContext context)
{
SerializeDecoder(info);
return GetCharCount(bytes, index, count, false);
}
- [System.Security.SecuritySafeCritical] // auto-generated
public override unsafe int GetCharCount(byte[] bytes, int index, int count, bool flush)
{
// Validate Parameters
return GetCharCount(pBytes + index, count, flush);
}
- [System.Security.SecurityCritical] // auto-generated
public unsafe override int GetCharCount(byte* bytes, int count, bool flush)
{
// Validate parameters
return GetChars(bytes, byteIndex, byteCount, chars, charIndex, false);
}
- [System.Security.SecuritySafeCritical] // auto-generated
public override unsafe int GetChars(byte[] bytes, int byteIndex, int byteCount,
char[] chars, int charIndex, bool flush)
{
pChars + charIndex, charCount, flush);
}
- [System.Security.SecurityCritical] // auto-generated
public unsafe override int GetChars(byte* bytes, int byteCount,
char* chars, int charCount, bool flush)
{
// This method is used when the output buffer might not be big enough.
// Just call the pointer version. (This gets chars)
- [System.Security.SecuritySafeCritical] // auto-generated
public override unsafe void Convert(byte[] bytes, int byteIndex, int byteCount,
char[] chars, int charIndex, int charCount, bool flush,
out int bytesUsed, out int charsUsed, out bool completed)
// This is the version that used pointers. We call the base encoding worker function
// after setting our appropriate internal variables. This is getting chars
- [System.Security.SecurityCritical] // auto-generated
public unsafe override void Convert(byte* bytes, int byteCount,
char* chars, int charCount, bool flush,
out int bytesUsed, out int charsUsed, out bool completed)
namespace System.Text
{
using System;
+ using System.Diagnostics;
using System.Diagnostics.Contracts;
[Serializable]
}
// Now make sure its in the expected range
- Contract.Assert(fallbackIndex < strDefault.Length && fallbackIndex >= 0,
+ Debug.Assert(fallbackIndex < strDefault.Length && fallbackIndex >= 0,
"Index exceeds buffer range");
return strDefault[fallbackIndex];
}
// Clear the buffer
- [System.Security.SecuritySafeCritical] // auto-generated
public override unsafe void Reset()
{
fallbackCount = -1;
}
// This version just counts the fallback and doesn't actually copy anything.
- [System.Security.SecurityCritical] // auto-generated
internal unsafe override int InternalFallback(byte[] bytes, byte* pBytes)
// Right now this has both bytes and bytes[], since we might have extra bytes, hence the
// array, and we might need the index, hence the byte*
internal class EUCJPEncoding : DBCSCodePageEncoding
{
// This pretends to be CP 932 as far as memory tables are concerned.
- [System.Security.SecurityCritical] // auto-generated
public EUCJPEncoding() : base(51932, 932)
{
this.m_bUseMlangTypeForSerialization = true;
}
- [System.Security.SecurityCritical] // auto-generated
protected unsafe override String GetMemorySectionName()
{
int iUseCodePage = this.bFlagDataTable ? dataTableCodePage : CodePage;
return true;
}
- [System.Security.SecurityCritical] // auto-generated
protected override unsafe void CleanUpEndBytes(char* chars)
{
// Need to special case CP 51932
using System.Runtime.Serialization;
using System.Text;
using System;
+ using System.Diagnostics;
using System.Diagnostics.Contracts;
// An Encoder is used to encode a sequence of blocks of characters into
// a sequence of blocks of bytes. Following instantiation of an encoder,
// We expect this to be the workhorse for NLS encodings
// unfortunately for existing overrides, it has to call the [] version,
// which is really slow, so avoid this method if you might be calling external encodings.
- [System.Security.SecurityCritical] // auto-generated
[CLSCompliant(false)]
[System.Runtime.InteropServices.ComVisible(false)]
public virtual unsafe int GetByteCount(char* chars, int count, bool flush)
// the byte[] to our byte* output buffer. If the result count was wrong, we
// could easily overflow our output buffer. Therefore we do an extra test
// when we copy the buffer so that we don't overflow byteCount either.
- [System.Security.SecurityCritical] // auto-generated
[CLSCompliant(false)]
[System.Runtime.InteropServices.ComVisible(false)]
public virtual unsafe int GetBytes(char* chars, int charCount,
// Do the work
int result = GetBytes(arrChar, 0, charCount, arrByte, 0, flush);
- Contract.Assert(result <= byteCount, "Returned more bytes than we have space for");
+ Debug.Assert(result <= byteCount, "Returned more bytes than we have space for");
// Copy the byte array
// WARNING: We MUST make sure that we don't copy too many bytes. We can't
// Note that if all of the input chars are not consumed, then we'll do a /2, which means
// that its likely that we didn't consume as many chars as we could have. For some
// applications this could be slow. (Like trying to exactly fill an output buffer from a bigger stream)
- [System.Security.SecurityCritical] // auto-generated
[CLSCompliant(false)]
[System.Runtime.InteropServices.ComVisible(false)]
public virtual unsafe void Convert(char* chars, int charCount,
using System.Globalization;
using System.Text;
using System.Threading;
+ using System.Diagnostics;
using System.Diagnostics.Contracts;
[Serializable]
// If we had a buffer already we're being recursive, throw, it's probably at the suspect
// character in our array.
// Shouldn't be able to get here for all of our code pages, table would have to be messed up.
- Contract.Assert(iCount < 1, "[InternalEncoderBestFitFallbackBuffer.Fallback(non surrogate)] Fallback char " + ((int)cBestFit).ToString("X4", CultureInfo.InvariantCulture) + " caused recursive fallback");
+ Debug.Assert(iCount < 1, "[InternalEncoderBestFitFallbackBuffer.Fallback(non surrogate)] Fallback char " + ((int)cBestFit).ToString("X4", CultureInfo.InvariantCulture) + " caused recursive fallback");
iCount = iSize = 1;
cBestFit = TryBestFit(charUnknown);
// If we had a buffer already we're being recursive, throw, it's probably at the suspect
// character in our array. 0 is processing last character, < 0 is not falling back
// Shouldn't be able to get here, table would have to be messed up.
- Contract.Assert(iCount < 1, "[InternalEncoderBestFitFallbackBuffer.Fallback(surrogate)] Fallback char " + ((int)cBestFit).ToString("X4", CultureInfo.InvariantCulture) + " caused recursive fallback");
+ Debug.Assert(iCount < 1, "[InternalEncoderBestFitFallbackBuffer.Fallback(surrogate)] Fallback char " + ((int)cBestFit).ToString("X4", CultureInfo.InvariantCulture) + " caused recursive fallback");
// Go ahead and get our fallback, surrogates don't have best fit
cBestFit = '?';
}
// Clear the buffer
- [System.Security.SecuritySafeCritical] // overrides public transparent member
public override unsafe void Reset()
{
iCount = -1;
if (cTest == cUnknown)
{
// We found it
- Contract.Assert(index + 1 < oFallback.arrayBestFit.Length,
+ Debug.Assert(index + 1 < oFallback.arrayBestFit.Length,
"[InternalEncoderBestFitFallbackBuffer.TryBestFit]Expected replacement character at end of array");
return oFallback.arrayBestFit[index + 1];
}
if (oFallback.arrayBestFit[index] == cUnknown)
{
// We found it
- Contract.Assert(index + 1 < oFallback.arrayBestFit.Length,
+ Debug.Assert(index + 1 < oFallback.arrayBestFit.Length,
"[InternalEncoderBestFitFallbackBuffer.TryBestFit]Expected replacement character at end of array");
return oFallback.arrayBestFit[index + 1];
}
using System;
using System.Security;
using System.Threading;
+using System.Diagnostics;
using System.Diagnostics.Contracts;
namespace System.Text
// Internal items to help us figure out what we're doing as far as error messages, etc.
// These help us with our performance and messages internally
- [SecurityCritical]
internal unsafe char* charStart;
- [SecurityCritical]
internal unsafe char* charEnd;
internal EncoderNLS encoder;
internal bool setEncoder;
// Internal Reset
// For example, what if someone fails a conversion and wants to reset one of our fallback buffers?
- [System.Security.SecurityCritical] // auto-generated
internal unsafe void InternalReset()
{
charStart = null;
// Set the above values
// This can't be part of the constructor because EncoderFallbacks would have to know how to impliment these.
- [System.Security.SecurityCritical] // auto-generated
internal unsafe void InternalInitialize(char* charStart, char* charEnd, EncoderNLS encoder, bool setEncoder)
{
this.charStart = charStart;
// Note that this could also change the contents of this.encoder, which is the same
// object that the caller is using, so the caller could mess up the encoder for us
// if they aren't careful.
- [System.Security.SecurityCritical] // auto-generated
internal unsafe virtual bool InternalFallback(char ch, ref char* chars)
{
// Shouldn't have null charStart
- Contract.Assert(charStart != null,
+ Debug.Assert(charStart != null,
"[EncoderFallback.InternalFallbackBuffer]Fallback buffer is not initialized");
// Get our index, remember chars was preincremented to point at next char, so have to -1
}
// ISerializable implementation. called during serialization.
- [System.Security.SecurityCritical] // auto-generated_required
void ISerializable.GetObjectData(SerializationInfo info, StreamingContext context)
{
SerializeEncoder(info);
m_fallbackBuffer.Reset();
}
- [System.Security.SecuritySafeCritical] // auto-generated
public override unsafe int GetByteCount(char[] chars, int index, int count, bool flush)
{
// Validate input parameters
return result;
}
- [System.Security.SecurityCritical] // auto-generated
public unsafe override int GetByteCount(char* chars, int count, bool flush)
{
// Validate input parameters
return m_encoding.GetByteCount(chars, count, this);
}
- [System.Security.SecuritySafeCritical] // auto-generated
public override unsafe int GetBytes(char[] chars, int charIndex, int charCount,
byte[] bytes, int byteIndex, bool flush)
{
pBytes + byteIndex, byteCount, flush);
}
- [System.Security.SecurityCritical] // auto-generated
public unsafe override int GetBytes(char* chars, int charCount, byte* bytes, int byteCount, bool flush)
{
// Validate parameters
// This method is used when your output buffer might not be large enough for the entire result.
// Just call the pointer version. (This gets bytes)
- [System.Security.SecuritySafeCritical] // auto-generated
public override unsafe void Convert(char[] chars, int charIndex, int charCount,
byte[] bytes, int byteIndex, int byteCount, bool flush,
out int charsUsed, out int bytesUsed, out bool completed)
// This is the version that uses pointers. We call the base encoding worker function
// after setting our appropriate internal variables. This is getting bytes
- [System.Security.SecurityCritical] // auto-generated
public override unsafe void Convert(char* chars, int charCount,
byte* bytes, int byteCount, bool flush,
out int charsUsed, out int bytesUsed, out bool completed)
{
using System;
using System.Runtime;
+ using System.Diagnostics;
using System.Diagnostics.Contracts;
[Serializable]
}
// Now make sure its in the expected range
- Contract.Assert(fallbackIndex < strDefault.Length && fallbackIndex >= 0,
+ Debug.Assert(fallbackIndex < strDefault.Length && fallbackIndex >= 0,
"Index exceeds buffer range");
return strDefault[fallbackIndex];
}
// Clear the buffer
- [System.Security.SecuritySafeCritical] // auto-generated
public override unsafe void Reset()
{
fallbackCount = -1;
using System.Security.Permissions;
using System.Threading;
using System.Text;
+ using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Diagnostics.Contracts;
using Win32Native = Microsoft.Win32.Win32Native;
private static volatile Hashtable encodings;
#endif
-#if !FEATURE_CORECLR
- [System.Security.SecurityCritical]
-#endif
public static void RegisterProvider(EncodingProvider provider)
{
// Parameters validated inside EncodingProvider
}
[Pure]
-#if !FEATURE_CORECLR
- [System.Security.SecuritySafeCritical] // auto-generated
-#endif
public static Encoding GetEncoding(int codepage)
{
Encoding result = EncodingProvider.GetEncodingFromProvider(codepage);
result = GetEncodingCodePage(codepage) ?? GetEncodingRare(codepage);
}
- Contract.Assert(result != null, "result != null");
+ Debug.Assert(result != null, "result != null");
encodings.Add(key, result);
}
return fallbackEncoding;
}
#if FEATURE_CODEPAGES_FILE
- [System.Security.SecurityCritical] // auto-generated
private static Encoding GetEncodingRare(int codepage)
{
- Contract.Assert(codepage != 0 && codepage != 1200 && codepage != 1201 && codepage != 65001,
+ Debug.Assert(codepage != 0 && codepage != 1200 && codepage != 1201 && codepage != 65001,
"[Encoding.GetEncodingRare]This code page (" + codepage + ") isn't supported by GetEncodingRare!");
Encoding result;
switch (codepage)
return result;
}
- [System.Security.SecurityCritical] // auto-generated
private static Encoding GetEncodingCodePage(int CodePage)
{
// Single Byte or Double Byte Code Page? (0 if not found)
// which is really slow, so this method should be avoided if you're calling
// a 3rd party encoding.
[Pure]
- [System.Security.SecurityCritical] // auto-generated
[CLSCompliant(false)]
[System.Runtime.InteropServices.ComVisible(false)]
public virtual unsafe int GetByteCount(char* chars, int count)
// For NLS Encodings, workhorse takes an encoder (may be null)
// Always validate parameters before calling internal version, which will only assert.
- [System.Security.SecurityCritical] // auto-generated
internal virtual unsafe int GetByteCount(char* chars, int count, EncoderNLS encoder)
{
Contract.Requires(chars != null);
int byteCount = GetByteCount(s);
byte[] bytes = new byte[byteCount];
int bytesReceived = GetBytes(s, 0, s.Length, bytes, 0);
- Contract.Assert(byteCount == bytesReceived);
+ Debug.Assert(byteCount == bytesReceived);
return bytes;
}
// This is our internal workhorse
// Always validate parameters before calling internal version, which will only assert.
- [System.Security.SecurityCritical] // auto-generated
internal virtual unsafe int GetBytes(char* chars, int charCount,
byte* bytes, int byteCount, EncoderNLS encoder)
{
// could easily overflow our output buffer. Therefore we do an extra test
// when we copy the buffer so that we don't overflow byteCount either.
- [System.Security.SecurityCritical] // auto-generated
[CLSCompliant(false)]
[System.Runtime.InteropServices.ComVisible(false)]
public virtual unsafe int GetBytes(char* chars, int charCount,
// Do the work
int result = GetBytes(arrChar, 0, charCount, arrByte, 0);
- Contract.Assert(result <= byteCount, "[Encoding.GetBytes]Returned more bytes than we have space for");
+ Debug.Assert(result <= byteCount, "[Encoding.GetBytes]Returned more bytes than we have space for");
// Copy the byte array
// WARNING: We MUST make sure that we don't copy too many bytes. We can't
// We expect this to be the workhorse for NLS Encodings, but for existing
// ones we need a working (if slow) default implimentation)
[Pure]
- [System.Security.SecurityCritical] // auto-generated
[CLSCompliant(false)]
[System.Runtime.InteropServices.ComVisible(false)]
public virtual unsafe int GetCharCount(byte* bytes, int count)
// This is our internal workhorse
// Always validate parameters before calling internal version, which will only assert.
- [System.Security.SecurityCritical] // auto-generated
internal virtual unsafe int GetCharCount(byte* bytes, int count, DecoderNLS decoder)
{
return GetCharCount(bytes, count);
// could easily overflow our output buffer. Therefore we do an extra test
// when we copy the buffer so that we don't overflow charCount either.
- [System.Security.SecurityCritical] // auto-generated
[CLSCompliant(false)]
[System.Runtime.InteropServices.ComVisible(false)]
public virtual unsafe int GetChars(byte* bytes, int byteCount,
// Do the work
int result = GetChars(arrByte, 0, byteCount, arrChar, 0);
- Contract.Assert(result <= charCount, "[Encoding.GetChars]Returned more chars than we have space for");
+ Debug.Assert(result <= charCount, "[Encoding.GetChars]Returned more chars than we have space for");
// Copy the char array
// WARNING: We MUST make sure that we don't copy too many chars. We can't
// This is our internal workhorse
// Always validate parameters before calling internal version, which will only assert.
- [System.Security.SecurityCritical] // auto-generated
internal virtual unsafe int GetChars(byte* bytes, int byteCount,
char* chars, int charCount, DecoderNLS decoder)
{
}
- [System.Security.SecurityCritical] // auto-generated
[CLSCompliant(false)]
[System.Runtime.InteropServices.ComVisible(false)]
public unsafe string GetString(byte* bytes, int byteCount)
return new DefaultDecoder(this);
}
- [System.Security.SecuritySafeCritical]
private static Encoding CreateDefaultEncoding()
{
// defaultEncoding should be null if we get here, but we can't
EncodingName, EncoderFallback.GetType()), "bytes");
}
- [System.Security.SecurityCritical] // auto-generated
internal void ThrowBytesOverflow(EncoderNLS encoder, bool nothingEncoded)
{
if (encoder == null || encoder.m_throwOnOverflow || nothingEncoded)
EncodingName, DecoderFallback.GetType()), "chars");
}
- [System.Security.SecurityCritical] // auto-generated
internal void ThrowCharsOverflow(DecoderNLS decoder, bool nothingDecoded)
{
if (decoder == null || decoder.m_throwOnOverflow || nothingDecoded)
}
// Just get it from GetEncoding
- [System.Security.SecurityCritical] // auto-generated
public Object GetRealObject(StreamingContext context)
{
// upon deserialization since the DefaultEncoder implement IObjectReference the
}
// ISerializable implementation, get data for this object
- [System.Security.SecurityCritical] // auto-generated_required
void ISerializable.GetObjectData(SerializationInfo info, StreamingContext context)
{
// Any info?
return m_encoding.GetByteCount(chars, index, count);
}
- [System.Security.SecurityCritical] // auto-generated
[SuppressMessage("Microsoft.Contracts", "CC1055")] // Skip extra error checking to avoid *potential* AppCompat problems.
public unsafe override int GetByteCount(char* chars, int count, bool flush)
{
return m_encoding.GetBytes(chars, charIndex, charCount, bytes, byteIndex);
}
- [System.Security.SecurityCritical] // auto-generated
[SuppressMessage("Microsoft.Contracts", "CC1055")] // Skip extra error checking to avoid *potential* AppCompat problems.
public unsafe override int GetBytes(char* chars, int charCount,
byte* bytes, int byteCount, bool flush)
}
// Just get it from GetEncoding
- [System.Security.SecurityCritical] // auto-generated
public Object GetRealObject(StreamingContext context)
{
// upon deserialization since the DefaultEncoder implement IObjectReference the
}
// ISerializable implementation, get data for this object
- [System.Security.SecurityCritical] // auto-generated_required
void ISerializable.GetObjectData(SerializationInfo info, StreamingContext context)
{
// Any info?
return m_encoding.GetCharCount(bytes, index, count);
}
- [System.Security.SecurityCritical] // auto-generated
[SuppressMessage("Microsoft.Contracts", "CC1055")] // Skip extra error checking to avoid *potential* AppCompat problems.
public unsafe override int GetCharCount(byte* bytes, int count, bool flush)
{
return m_encoding.GetChars(bytes, byteIndex, byteCount, chars, charIndex);
}
- [System.Security.SecurityCritical] // auto-generated
[SuppressMessage("Microsoft.Contracts", "CC1055")] // Skip extra error checking to avoid *potential* AppCompat problems.
public unsafe override int GetChars(byte* bytes, int byteCount,
char* chars, int charCount, bool flush)
internal class EncodingCharBuffer
{
- [SecurityCritical]
unsafe char* chars;
- [SecurityCritical]
unsafe char* charStart;
- [SecurityCritical]
unsafe char* charEnd;
int charCountResult = 0;
Encoding enc;
DecoderNLS decoder;
- [SecurityCritical]
unsafe byte* byteStart;
- [SecurityCritical]
unsafe byte* byteEnd;
- [SecurityCritical]
unsafe byte* bytes;
DecoderFallbackBuffer fallbackBuffer;
- [System.Security.SecurityCritical] // auto-generated
internal unsafe EncodingCharBuffer(Encoding enc, DecoderNLS decoder, char* charStart, int charCount,
byte* byteStart, int byteCount)
{
// If we're getting chars or getting char count we don't expect to have
// to remember fallbacks between calls (so it should be empty)
- Contract.Assert(fallbackBuffer.Remaining == 0,
+ Debug.Assert(fallbackBuffer.Remaining == 0,
"[Encoding.EncodingCharBuffer.EncodingCharBuffer]Expected empty fallback buffer for getchars/charcount");
fallbackBuffer.InternalInitialize(bytes, charEnd);
}
- [System.Security.SecurityCritical] // auto-generated
internal unsafe bool AddChar(char ch, int numBytes)
{
if (chars != null)
return true;
}
- [System.Security.SecurityCritical] // auto-generated
internal unsafe bool AddChar(char ch)
{
return AddChar(ch,1);
}
- [System.Security.SecurityCritical] // auto-generated
internal unsafe bool AddChar(char ch1, char ch2, int numBytes)
{
// Need room for 2 chars
return AddChar(ch1, numBytes) && AddChar(ch2, numBytes);
}
- [System.Security.SecurityCritical] // auto-generated
internal unsafe void AdjustBytes(int count)
{
bytes += count;
internal unsafe bool MoreData
{
- [System.Security.SecurityCritical] // auto-generated
get
{
return bytes < byteEnd;
}
// Do we have count more bytes?
- [System.Security.SecurityCritical] // auto-generated
internal unsafe bool EvenMoreData(int count)
{
return (bytes <= byteEnd - count);
// GetNextByte shouldn't be called unless the caller's already checked more data or even more data,
// but we'll double check just to make sure.
- [System.Security.SecurityCritical] // auto-generated
internal unsafe byte GetNextByte()
{
- Contract.Assert(bytes < byteEnd, "[EncodingCharBuffer.GetNextByte]Expected more date");
+ Debug.Assert(bytes < byteEnd, "[EncodingCharBuffer.GetNextByte]Expected more date");
if (bytes >= byteEnd)
return 0;
return *(bytes++);
internal unsafe int BytesUsed
{
- [System.Security.SecurityCritical] // auto-generated
get
{
return (int)(bytes - byteStart);
}
}
- [System.Security.SecurityCritical] // auto-generated
internal unsafe bool Fallback(byte fallbackByte)
{
// Build our buffer
return Fallback(byteBuffer);
}
- [System.Security.SecurityCritical] // auto-generated
internal unsafe bool Fallback(byte byte1, byte byte2)
{
// Build our buffer
return Fallback(byteBuffer);
}
- [System.Security.SecurityCritical] // auto-generated
internal unsafe bool Fallback(byte byte1, byte byte2, byte byte3, byte byte4)
{
// Build our buffer
return Fallback(byteBuffer);
}
- [System.Security.SecurityCritical] // auto-generated
internal unsafe bool Fallback(byte[] byteBuffer)
{
// Do the fallback and add the data.
internal class EncodingByteBuffer
{
- [SecurityCritical]
unsafe byte* bytes;
- [SecurityCritical]
unsafe byte* byteStart;
- [SecurityCritical]
unsafe byte* byteEnd;
- [SecurityCritical]
unsafe char* chars;
- [SecurityCritical]
unsafe char* charStart;
- [SecurityCritical]
unsafe char* charEnd;
int byteCountResult = 0;
Encoding enc;
EncoderNLS encoder;
internal EncoderFallbackBuffer fallbackBuffer;
- [System.Security.SecurityCritical] // auto-generated
internal unsafe EncodingByteBuffer(Encoding inEncoding, EncoderNLS inEncoder,
byte* inByteStart, int inByteCount, char* inCharStart, int inCharCount)
{
fallbackBuffer.InternalInitialize(chars, charEnd, encoder, bytes != null);
}
- [System.Security.SecurityCritical] // auto-generated
internal unsafe bool AddByte(byte b, int moreBytesExpected)
{
- Contract.Assert(moreBytesExpected >= 0, "[EncodingByteBuffer.AddByte]expected non-negative moreBytesExpected");
+ Debug.Assert(moreBytesExpected >= 0, "[EncodingByteBuffer.AddByte]expected non-negative moreBytesExpected");
if (bytes != null)
{
if (bytes >= byteEnd - moreBytesExpected)
return true;
}
- [System.Security.SecurityCritical] // auto-generated
internal unsafe bool AddByte(byte b1)
{
return (AddByte(b1, 0));
}
- [System.Security.SecurityCritical] // auto-generated
internal unsafe bool AddByte(byte b1, byte b2)
{
return (AddByte(b1, b2, 0));
}
- [System.Security.SecurityCritical] // auto-generated
internal unsafe bool AddByte(byte b1, byte b2, int moreBytesExpected)
{
return (AddByte(b1, 1 + moreBytesExpected) && AddByte(b2, moreBytesExpected));
}
- [System.Security.SecurityCritical] // auto-generated
internal unsafe bool AddByte(byte b1, byte b2, byte b3)
{
return AddByte(b1, b2, b3, (int)0);
}
- [System.Security.SecurityCritical] // auto-generated
internal unsafe bool AddByte(byte b1, byte b2, byte b3, int moreBytesExpected)
{
return (AddByte(b1, 2 + moreBytesExpected) &&
AddByte(b3, moreBytesExpected));
}
- [System.Security.SecurityCritical] // auto-generated
internal unsafe bool AddByte(byte b1, byte b2, byte b3, byte b4)
{
return (AddByte(b1, 3) &&
AddByte(b4, 0));
}
- [System.Security.SecurityCritical] // auto-generated
internal unsafe void MovePrevious(bool bThrow)
{
if (fallbackBuffer.bFallingBack)
fallbackBuffer.MovePrevious(); // don't use last fallback
else
{
- Contract.Assert(chars > charStart ||
+ Debug.Assert(chars > charStart ||
((bThrow == true) && (bytes == byteStart)),
"[EncodingByteBuffer.MovePrevious]expected previous data or throw");
if (chars > charStart)
enc.ThrowBytesOverflow(encoder, bytes == byteStart); // Throw? (and reset fallback if not converting)
}
- [System.Security.SecurityCritical] // auto-generated
internal unsafe bool Fallback(char charFallback)
{
// Do the fallback
internal unsafe bool MoreData
{
- [System.Security.SecurityCritical] // auto-generated
get
{
// See if fallbackBuffer is not empty or if there's data left in chars buffer.
}
}
- [System.Security.SecurityCritical] // auto-generated
internal unsafe char GetNextChar()
{
// See if there's something in our fallback buffer
internal unsafe int CharsUsed
{
- [System.Security.SecurityCritical] // auto-generated
get
{
return (int)(chars - charStart);
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
+using System.Diagnostics;
using System.Diagnostics.Contracts;
using System.Security;
// the parameter, it will call the same method again, which will eventually
// lead to a StackOverflowException.
- [SecuritySafeCritical]
public unsafe static int GetByteCount(Encoding encoding, char[] chars, int index, int count)
{
// Validate parameters
- Contract.Assert(encoding != null); // this parameter should only be affected internally, so just do a debug check here
+ Debug.Assert(encoding != null); // this parameter should only be affected internally, so just do a debug check here
if (chars == null)
{
throw new ArgumentNullException(nameof(chars), Environment.GetResourceString("ArgumentNull_Array"));
return encoding.GetByteCount(pChars + index, count, encoder: null);
}
- [SecuritySafeCritical]
public unsafe static int GetByteCount(Encoding encoding, string s)
{
- Contract.Assert(encoding != null);
+ Debug.Assert(encoding != null);
if (s == null)
{
string paramName = encoding is ASCIIEncoding ? "chars" : nameof(s); // ASCIIEncoding calls the string chars
return encoding.GetByteCount(pChars, s.Length, encoder: null);
}
- [SecurityCritical]
public unsafe static int GetByteCount(Encoding encoding, char* chars, int count)
{
- Contract.Assert(encoding != null);
+ Debug.Assert(encoding != null);
if (chars == null)
{
throw new ArgumentNullException(nameof(chars), Environment.GetResourceString("ArgumentNull_Array"));
return encoding.GetByteCount(chars, count, encoder: null);
}
- [SecuritySafeCritical]
public unsafe static int GetBytes(Encoding encoding, string s, int charIndex, int charCount, byte[] bytes, int byteIndex)
{
- Contract.Assert(encoding != null);
+ Debug.Assert(encoding != null);
if (s == null || bytes == null)
{
string stringName = encoding is ASCIIEncoding ? "chars" : nameof(s); // ASCIIEncoding calls the first parameter chars
}
}
- [SecuritySafeCritical]
public unsafe static int GetBytes(Encoding encoding, char[] chars, int charIndex, int charCount, byte[] bytes, int byteIndex)
{
- Contract.Assert(encoding != null);
+ Debug.Assert(encoding != null);
if (chars == null || bytes == null)
{
throw new ArgumentNullException(chars == null ? nameof(chars) : nameof(bytes), Environment.GetResourceString("ArgumentNull_Array"));
}
}
- [SecurityCritical]
public unsafe static int GetBytes(Encoding encoding, char* chars, int charCount, byte* bytes, int byteCount)
{
- Contract.Assert(encoding != null);
+ Debug.Assert(encoding != null);
if (bytes == null || chars == null)
{
throw new ArgumentNullException(bytes == null ? nameof(bytes) : nameof(chars), Environment.GetResourceString("ArgumentNull_Array"));
return encoding.GetBytes(chars, charCount, bytes, byteCount, encoder: null);
}
- [SecuritySafeCritical]
public unsafe static int GetCharCount(Encoding encoding, byte[] bytes, int index, int count)
{
- Contract.Assert(encoding != null);
+ Debug.Assert(encoding != null);
if (bytes == null)
{
throw new ArgumentNullException(nameof(bytes), Environment.GetResourceString("ArgumentNull_Array"));
return encoding.GetCharCount(pBytes + index, count, decoder: null);
}
- [SecurityCritical]
public unsafe static int GetCharCount(Encoding encoding, byte* bytes, int count)
{
- Contract.Assert(encoding != null);
+ Debug.Assert(encoding != null);
if (bytes == null)
{
throw new ArgumentNullException(nameof(bytes), Environment.GetResourceString("ArgumentNull_Array"));
return encoding.GetCharCount(bytes, count, decoder: null);
}
- [SecuritySafeCritical]
public unsafe static int GetChars(Encoding encoding, byte[] bytes, int byteIndex, int byteCount, char[] chars, int charIndex)
{
- Contract.Assert(encoding != null);
+ Debug.Assert(encoding != null);
if (bytes == null || chars == null)
{
throw new ArgumentNullException(bytes == null ? nameof(bytes) : nameof(chars), Environment.GetResourceString("ArgumentNull_Array"));
}
}
- [SecurityCritical]
public unsafe static int GetChars(Encoding encoding, byte* bytes, int byteCount, char* chars, int charCount)
{
- Contract.Assert(encoding != null);
+ Debug.Assert(encoding != null);
if (bytes == null || chars == null)
{
throw new ArgumentNullException(bytes == null ? nameof(bytes) : nameof(chars), Environment.GetResourceString("ArgumentNull_Array"));
return encoding.GetChars(bytes, byteCount, chars, charCount, decoder: null);
}
- [SecuritySafeCritical]
public unsafe static string GetString(Encoding encoding, byte[] bytes, int index, int count)
{
- Contract.Assert(encoding != null);
+ Debug.Assert(encoding != null);
if (bytes == null)
{
throw new ArgumentNullException(nameof(bytes), Environment.GetResourceString("ArgumentNull_Array"));
return EncodingForwarder.GetByteCount(this, s);
}
- [System.Security.SecurityCritical] // auto-generated
public override unsafe int GetByteCount(char* chars, int count)
{
return EncodingForwarder.GetByteCount(this, chars, count);
return EncodingForwarder.GetBytes(this, chars, charIndex, charCount, bytes, byteIndex);
}
- [System.Security.SecurityCritical] // auto-generated
public override unsafe int GetBytes(char* chars, int charCount, byte* bytes, int byteCount)
{
return EncodingForwarder.GetBytes(this, chars, charCount, bytes, byteCount);
return EncodingForwarder.GetCharCount(this, bytes, index, count);
}
- [System.Security.SecurityCritical] // auto-generated
public override unsafe int GetCharCount(byte* bytes, int count)
{
return EncodingForwarder.GetCharCount(this, bytes, count);
return EncodingForwarder.GetChars(this, bytes, byteIndex, byteCount, chars, charIndex);
}
- [System.Security.SecurityCritical] // auto-generated
public unsafe override int GetChars(byte* bytes, int byteCount, char* chars, int charCount)
{
return EncodingForwarder.GetChars(this, bytes, byteCount, chars, charCount);
namespace System.Text
{
using System;
+ using System.Diagnostics;
using System.Diagnostics.Contracts;
using System.Text;
using System.Runtime.InteropServices;
// This is the table of 4 byte conversions.
private const int GBLast4ByteCode = 0x99FB;
[NonSerialized]
- [SecurityCritical]
unsafe internal char* map4BytesToUnicode = null; // new char[GBLast4ByteCode + 1]; // Need to map all 4 byte sequences to Unicode
[NonSerialized]
- [SecurityCritical]
unsafe internal byte* mapUnicodeTo4BytesFlags = null; // new byte[0x10000 / 8]; // Need 1 bit for each code point to say if its 4 byte or not
private const int GB18030 = 54936;
private const int GBLastSurrogateOffset = 0x12E247; // GBE3329A35
// We have to load the 936 code page tables, so impersonate 936 as our base
- [System.Security.SecurityCritical] // auto-generated
internal GB18030Encoding() : base(GB18030, 936)
{
}
// Constructor called by serialization.
- [System.Security.SecurityCritical] // auto-generated
internal GB18030Encoding(SerializationInfo info, StreamingContext context) :
base(GB18030, 936)
{
// Set up our base, also throws if info was empty
DeserializeEncoding(info, context);
- Contract.Assert(info!=null, "[GB18030Encoding(Serialization...)] Expected null info to throw");
+ Debug.Assert(info!=null, "[GB18030Encoding(Serialization...)] Expected null info to throw");
// Already build our code page, fallbacks & read only, so we're good to go!
}
// ISerializable implementation
- [System.Security.SecurityCritical] // auto-generated_required
void ISerializable.GetObjectData(SerializationInfo info, StreamingContext context)
{
// Make sure to get the base stuff too This throws if info is null
SerializeEncoding(info, context);
- Contract.Assert(info!=null, "[GB18030.GetObjectData] Expected null info to throw");
+ Debug.Assert(info!=null, "[GB18030.GetObjectData] Expected null info to throw");
// Everett doesn't need more than the basics
}
// This loads our base 936 code page and then applys the changes from the tableUnicodeToGBDiffs table.
// See table comments for table format.
- [System.Security.SecurityCritical] // auto-generated
protected override unsafe void LoadManagedCodePage()
{
// Use base code page loading algorithm.
// It was GB 18030 4 byte data, next <data> characters are 4 byte sequences.
while (data > 0)
{
- Contract.Assert(count4Byte <= GBLast4ByteCode,
+ Debug.Assert(count4Byte <= GBLast4ByteCode,
"[GB18030Encoding.LoadManagedCodePage] Found too many 4 byte codes in data table.");
// Set the 4 byte -> Unicode value
}
// unicodeCount should've wrapped back to 0
- Contract.Assert(unicodeCount == 0,
+ Debug.Assert(unicodeCount == 0,
"[GB18030Encoding.LoadManagedCodePage] Expected unicodeCount to wrap around to 0 as all chars were processed");
// We should've read in GBLast4ByteCode 4 byte sequences
- Contract.Assert(count4Byte == GBLast4ByteCode + 1,
+ Debug.Assert(count4Byte == GBLast4ByteCode + 1,
"[GB18030Encoding.LoadManagedCodePage] Expected 0x99FB to be last 4 byte offset, found 0x" + count4Byte.ToString("X4", CultureInfo.InvariantCulture));
// Need to flag ourselves saying we've built this CP.
// Is4Byte
// Checks the 4 byte table and returns true if this is a 4 byte code.
// Its a 4 byte code if the flag is set in mapUnicodeTo4BytesFlags
- [System.Security.SecurityCritical] // auto-generated
internal unsafe bool Is4Byte(char charTest)
{
// See what kind it is
}
// GetByteCount
- [System.Security.SecurityCritical] // auto-generated
internal override unsafe int GetByteCount(char* chars, int count, EncoderNLS encoder)
{
// Just call GetBytes() with null bytes
return GetBytes(chars, count, null, 0, encoder);
}
- [System.Security.SecurityCritical] // auto-generated
internal override unsafe int GetBytes(char* chars, int charCount,
byte* bytes, int byteCount, EncoderNLS encoder)
{
// Just need to ASSERT, this is called by something else internal that checked parameters already
// We'll allow null bytes as a count
-// Contract.Assert(bytes != null, "[GB18030Encoding.GetBytes]bytes is null");
- Contract.Assert(byteCount >= 0, "[GB18030Encoding.GetBytes]byteCount is negative");
- Contract.Assert(chars != null, "[GB18030Encoding.GetBytes]chars is null");
- Contract.Assert(charCount >= 0, "[GB18030Encoding.GetBytes]charCount is negative");
+// Debug.Assert(bytes != null, "[GB18030Encoding.GetBytes]bytes is null");
+ Debug.Assert(byteCount >= 0, "[GB18030Encoding.GetBytes]byteCount is negative");
+ Debug.Assert(chars != null, "[GB18030Encoding.GetBytes]chars is null");
+ Debug.Assert(charCount >= 0, "[GB18030Encoding.GetBytes]charCount is negative");
// Assert because we shouldn't be able to have a null encoder.
- Contract.Assert(encoderFallback != null, "[GB18030Encoding.GetBytes]Attempting to use null encoder fallback");
+ Debug.Assert(encoderFallback != null, "[GB18030Encoding.GetBytes]Attempting to use null encoder fallback");
// Get any left over characters
char charLeftOver = (char)0;
// Have to check for charLeftOver
if (charLeftOver != 0)
{
- Contract.Assert(Char.IsHighSurrogate(charLeftOver),
+ Debug.Assert(Char.IsHighSurrogate(charLeftOver),
"[GB18030Encoding.GetBytes] leftover character should be high surrogate, not 0x" + ((int)charLeftOver).ToString("X4", CultureInfo.InvariantCulture));
// If our next char isn't a low surrogate, then we need to do fallback.
offset /= 0x7e;
byte byte2 = (byte)((offset % 0x0a) + 0x30);
offset /= 0x0a;
- Contract.Assert(offset < 0x6f,
+ Debug.Assert(offset < 0x6f,
"[GB18030Encoding.GetBytes](1) Expected offset < 0x6f, not 0x" + offset.ToString("X2", CultureInfo.InvariantCulture));
charLeftOver = (char)0;
iBytes /= 0x7e;
byte byte2 = (byte)((iBytes % 0x0a) + 0x30);
iBytes /= 0x0a;
- Contract.Assert(iBytes < 0x7e,
+ Debug.Assert(iBytes < 0x7e,
"[GB18030Encoding.GetBytes]Expected iBytes < 0x7e, not 0x" + iBytes.ToString("X2", CultureInfo.InvariantCulture));
if (!buffer.AddByte((byte)(iBytes + 0x81), byte2, byte3, byte4))
break;
}
// This is internal and called by something else,
- [System.Security.SecurityCritical] // auto-generated
internal override unsafe int GetCharCount(byte* bytes, int count, DecoderNLS baseDecoder)
{
// Just call GetChars() with null chars to count
return GetChars(bytes, count, null, 0, baseDecoder);
}
- [System.Security.SecurityCritical] // auto-generated
internal override unsafe int GetChars(byte* bytes, int byteCount,
char* chars, int charCount, DecoderNLS baseDecoder)
{
// Just need to ASSERT, this is called by something else internal that checked parameters already
// We'll allow null chars as a count
- Contract.Assert(bytes != null, "[GB18030Encoding.GetChars]bytes is null");
- Contract.Assert(byteCount >= 0, "[GB18030Encoding.GetChars]byteCount is negative");
-// Contract.Assert(chars != null, "[GB18030Encoding.GetChars]chars is null");
- Contract.Assert(charCount >= 0, "[GB18030Encoding.GetChars]charCount is negative");
+ Debug.Assert(bytes != null, "[GB18030Encoding.GetChars]bytes is null");
+ Debug.Assert(byteCount >= 0, "[GB18030Encoding.GetChars]byteCount is negative");
+// Debug.Assert(chars != null, "[GB18030Encoding.GetChars]chars is null");
+ Debug.Assert(charCount >= 0, "[GB18030Encoding.GetChars]charCount is negative");
// Fix our decoder
GB18030Decoder decoder = (GB18030Decoder)baseDecoder;
}
// Constructor called by serialization, have to handle deserializing from Everett
- [System.Security.SecurityCritical] // auto-generated
internal GB18030Decoder(SerializationInfo info, StreamingContext context)
{
// Any info?
}
// ISerializable implementation, get data for this object
- [System.Security.SecurityCritical] // auto-generated_required
void ISerializable.GetObjectData(SerializationInfo info, StreamingContext context)
{
// Any info?
namespace System.Text
{
using System;
+ using System.Diagnostics;
using System.Diagnostics.Contracts;
using System.Globalization;
using System.Runtime.Serialization;
defaultCodePage = codePage - 57000;
// Legal windows code pages are between Devanagari and Punjabi
- Contract.Assert(defaultCodePage >= CodeDevanagari && defaultCodePage <= CodePunjabi,
+ Debug.Assert(defaultCodePage >= CodeDevanagari && defaultCodePage <= CodePunjabi,
"[ISCIIEncoding] Code page (" + codePage + " isn't supported by ISCIIEncoding!");
// This shouldn't really be possible
{
// Actually this can't ever get called, MLangCodePageEncoding is our proxy
// (In Everett this was done by MLang)
- Contract.Assert(false, "Didn't expect to make it to ISCIIEncoding serialization constructor");
+ Debug.Assert(false, "Didn't expect to make it to ISCIIEncoding serialization constructor");
throw new ArgumentException(Environment.GetResourceString("Arg_ExecutionEngineException"));
}
// ISerializable implementation
- [System.Security.SecurityCritical] // auto-generated_required
void ISerializable.GetObjectData(SerializationInfo info, StreamingContext context)
{
// Make sure to get the base stuff too This throws if info is null
SerializeEncoding(info, context);
- Contract.Assert(info!=null, "[ISCIIEncoding.GetObjectData] Expected null info to throw");
+ Debug.Assert(info!=null, "[ISCIIEncoding.GetObjectData] Expected null info to throw");
// Just need Everett MLangCodePageEncoding maxCharSize
info.AddValue("m_maxByteSize", 2);
}
// Our workhorse version
- [System.Security.SecurityCritical] // auto-generated
internal override unsafe int GetByteCount(char* chars, int count, EncoderNLS baseEncoder)
{
// Use null pointer to ask GetBytes for count
}
// Workhorse
- [System.Security.SecurityCritical] // auto-generated
internal override unsafe int GetBytes(char *chars, int charCount,
byte* bytes, int byteCount, EncoderNLS baseEncoder)
{
// Allow null bytes for counting
- Contract.Assert(chars != null, "[ISCIIEncoding.GetBytes]chars!=null");
-// Contract.Assert(bytes != null, "[ISCIIEncoding.GetBytes]bytes!=null");
- Contract.Assert(charCount >=0, "[ISCIIEncoding.GetBytes]charCount >=0");
- Contract.Assert(byteCount >=0, "[ISCIIEncoding.GetBytes]byteCount >=0");
+ Debug.Assert(chars != null, "[ISCIIEncoding.GetBytes]chars!=null");
+// Debug.Assert(bytes != null, "[ISCIIEncoding.GetBytes]bytes!=null");
+ Debug.Assert(charCount >=0, "[ISCIIEncoding.GetBytes]charCount >=0");
+ Debug.Assert(byteCount >=0, "[ISCIIEncoding.GetBytes]byteCount >=0");
// Need the ISCII Encoder
ISCIIEncoder encoder = (ISCIIEncoder) baseEncoder;
// See if our code page ("font" in ISCII spec) has to change
// (This if doesn't add character, just changes character set)
- Contract.Assert(indicScript!=0, "[ISCIIEncoding.GetBytes]expected an indic script value");
+ Debug.Assert(indicScript!=0, "[ISCIIEncoding.GetBytes]expected an indic script value");
if (indicScript != currentCodePage)
{
// It changed, spit out the ATR
currentCodePage = indicScript;
// We only know how to map from Unicode to pages from Devanagari to Punjabi (2 to 11)
- Contract.Assert(currentCodePage >= CodeDevanagari && currentCodePage <= CodePunjabi,
+ Debug.Assert(currentCodePage >= CodeDevanagari && currentCodePage <= CodePunjabi,
"[ISCIIEncoding.GetBytes]Code page (" + currentCodePage + " shouldn't appear in ISCII from Unicode table!");
}
if (indicTwoBytes != 0)
{
// This one needs another byte
- Contract.Assert((indicTwoBytes >> 12) > 0 && (indicTwoBytes >> 12) <= 3,
+ Debug.Assert((indicTwoBytes >> 12) > 0 && (indicTwoBytes >> 12) <= 3,
"[ISCIIEncoding.GetBytes]Expected indicTwoBytes from 1-3, not " + (indicTwoBytes >> 12));
// Already did buffer checking, but...
}
// Workhorse
- [System.Security.SecurityCritical] // auto-generated
internal override unsafe int GetCharCount(byte* bytes, int count, DecoderNLS baseDecoder)
{
// Just call GetChars with null chars saying we want count
// Devenagari F0, B8 -> \u0952
// Devenagari F0, BF -> \u0970
// Some characters followed by E9 become a different character instead.
- [System.Security.SecurityCritical] // auto-generated
internal override unsafe int GetChars(byte* bytes, int byteCount,
char* chars, int charCount, DecoderNLS baseDecoder)
{
// Just need to ASSERT, this is called by something else internal that checked parameters already
// Allow null chars for counting
- Contract.Assert(bytes != null, "[ISCIIEncoding.GetChars]bytes is null");
- Contract.Assert(byteCount >= 0, "[ISCIIEncoding.GetChars]byteCount is negative");
-// Contract.Assert(chars != null, "[ISCIIEncoding.GetChars]chars is null");
- Contract.Assert(charCount >= 0, "[ISCIIEncoding.GetChars]charCount is negative");
+ Debug.Assert(bytes != null, "[ISCIIEncoding.GetChars]bytes is null");
+ Debug.Assert(byteCount >= 0, "[ISCIIEncoding.GetChars]byteCount is negative");
+// Debug.Assert(chars != null, "[ISCIIEncoding.GetChars]chars is null");
+ Debug.Assert(charCount >= 0, "[ISCIIEncoding.GetChars]charCount is negative");
// Need the ISCII Decoder
ISCIIDecoder decoder = (ISCIIDecoder) baseDecoder;
// Get our current code page index (some code pages are dups)
int currentCodePageIndex = -1;
- Contract.Assert(currentCodePage >= CodeDevanagari && currentCodePage <= CodePunjabi,
+ Debug.Assert(currentCodePage >= CodeDevanagari && currentCodePage <= CodePunjabi,
"[ISCIIEncoding.GetChars]Decoder code page must be >= Devanagari and <= Punjabi, not " + currentCodePage);
if (currentCodePage >= CodeDevanagari && currentCodePage <= CodePunjabi)
bLastSpecial = false;
// One and only one of our flags should be set
- Contract.Assert(((bLastVirama ? 1 : 0) + (bLastATR ? 1 : 0) +
+ Debug.Assert(((bLastVirama ? 1 : 0) + (bLastATR ? 1 : 0) +
(bLastDevenagariStressAbbr ? 1 : 0) +
((cLastCharForNextNukta > 0) ? 1 : 0)) == 1,
String.Format(CultureInfo.InvariantCulture,
bLastATR = false;
// we know we can't have any of these other modes
- Contract.Assert(bLastVirama == false, "[ISCIIEncoding.GetChars] Expected no bLastVirama in bLastATR mode");
- Contract.Assert(bLastDevenagariStressAbbr == false, "[ISCIIEncoding.GetChars] Expected no bLastDevenagariStressAbbr in bLastATR mode");
- Contract.Assert(cLastCharForNextNukta == (char)0, "[ISCIIEncoding.GetChars] Expected no cLastCharForNextNukta in bLastATR mode");
- Contract.Assert(cLastCharForNoNextNukta == (char)0, "[ISCIIEncoding.GetChars] Expected no cLastCharForNoNextNukta in bLastATR mode");
+ Debug.Assert(bLastVirama == false, "[ISCIIEncoding.GetChars] Expected no bLastVirama in bLastATR mode");
+ Debug.Assert(bLastDevenagariStressAbbr == false, "[ISCIIEncoding.GetChars] Expected no bLastDevenagariStressAbbr in bLastATR mode");
+ Debug.Assert(cLastCharForNextNukta == (char)0, "[ISCIIEncoding.GetChars] Expected no cLastCharForNextNukta in bLastATR mode");
+ Debug.Assert(cLastCharForNoNextNukta == (char)0, "[ISCIIEncoding.GetChars] Expected no cLastCharForNoNextNukta in bLastATR mode");
// Keep processing this byte
}
bLastVirama = false;
// We know we can't have any of these other modes
- Contract.Assert(bLastATR == false, "[ISCIIEncoding.GetChars] Expected no bLastATR in bLastVirama mode");
- Contract.Assert(bLastDevenagariStressAbbr == false, "[ISCIIEncoding.GetChars] Expected no bLastDevenagariStressAbbr in bLastVirama mode");
- Contract.Assert(cLastCharForNextNukta == (char)0, "[ISCIIEncoding.GetChars] Expected no cLastCharForNextNukta in bLastVirama mode");
- Contract.Assert(cLastCharForNoNextNukta == (char)0, "[ISCIIEncoding.GetChars] Expected no cLastCharForNoNextNukta in bLastVirama mode");
+ Debug.Assert(bLastATR == false, "[ISCIIEncoding.GetChars] Expected no bLastATR in bLastVirama mode");
+ Debug.Assert(bLastDevenagariStressAbbr == false, "[ISCIIEncoding.GetChars] Expected no bLastDevenagariStressAbbr in bLastVirama mode");
+ Debug.Assert(cLastCharForNextNukta == (char)0, "[ISCIIEncoding.GetChars] Expected no cLastCharForNextNukta in bLastVirama mode");
+ Debug.Assert(cLastCharForNoNextNukta == (char)0, "[ISCIIEncoding.GetChars] Expected no cLastCharForNoNextNukta in bLastVirama mode");
}
else if (bLastDevenagariStressAbbr)
{
// (last character was added when mode was set)
bLastDevenagariStressAbbr = false;
- Contract.Assert(bLastATR == false, "[ISCIIEncoding.GetChars] Expected no bLastATR in bLastDevenagariStressAbbr mode");
- Contract.Assert(bLastVirama == false, "[ISCIIEncoding.GetChars] Expected no bLastVirama in bLastDevenagariStressAbbr mode");
- Contract.Assert(cLastCharForNextNukta == (char)0, "[ISCIIEncoding.GetChars] Expected no cLastCharForNextNukta in bLastDevenagariStressAbbr mode");
- Contract.Assert(cLastCharForNoNextNukta == (char)0, "[ISCIIEncoding.GetChars] Expected no cLastCharForNoNextNukta in bLastDevenagariStressAbbr mode");
+ Debug.Assert(bLastATR == false, "[ISCIIEncoding.GetChars] Expected no bLastATR in bLastDevenagariStressAbbr mode");
+ Debug.Assert(bLastVirama == false, "[ISCIIEncoding.GetChars] Expected no bLastVirama in bLastDevenagariStressAbbr mode");
+ Debug.Assert(cLastCharForNextNukta == (char)0, "[ISCIIEncoding.GetChars] Expected no cLastCharForNextNukta in bLastDevenagariStressAbbr mode");
+ Debug.Assert(cLastCharForNoNextNukta == (char)0, "[ISCIIEncoding.GetChars] Expected no cLastCharForNoNextNukta in bLastDevenagariStressAbbr mode");
}
else
{
// We were checking for next char being a nukta
- Contract.Assert(cLastCharForNextNukta > 0 && cLastCharForNoNextNukta > 0,
+ Debug.Assert(cLastCharForNextNukta > 0 && cLastCharForNoNextNukta > 0,
"[ISCIIEncoding.GetChars]No other special case found, but cLastCharFor(No)NextNukta variable(s) aren't set.");
// We'll either add combined char or last char
// Keep processing this byte, turn off mode.
cLastCharForNextNukta = cLastCharForNoNextNukta = '\0';
- Contract.Assert(bLastATR == false, "[ISCIIEncoding.GetChars] Expected no bLastATR in cLastCharForNextNukta mode");
- Contract.Assert(bLastVirama == false, "[ISCIIEncoding.GetChars] Expected no bLastVirama in cLastCharForNextNukta mode");
- Contract.Assert(bLastDevenagariStressAbbr == false, "[ISCIIEncoding.GetChars] Expected no bLastDevenagariStressAbbr in cLastCharForNextNukta mode");
+ Debug.Assert(bLastATR == false, "[ISCIIEncoding.GetChars] Expected no bLastATR in cLastCharForNextNukta mode");
+ Debug.Assert(bLastVirama == false, "[ISCIIEncoding.GetChars] Expected no bLastVirama in cLastCharForNextNukta mode");
+ Debug.Assert(bLastDevenagariStressAbbr == false, "[ISCIIEncoding.GetChars] Expected no bLastDevenagariStressAbbr in cLastCharForNextNukta mode");
}
}
// Now bLastSpecial should be false and all flags false.
- Contract.Assert (!bLastSpecial && !bLastDevenagariStressAbbr && !bLastVirama && !bLastATR &&
+ Debug.Assert (!bLastSpecial && !bLastDevenagariStressAbbr && !bLastVirama && !bLastATR &&
cLastCharForNextNukta == '\0',
"[ISCIIEncoding.GetChars]No special state for last code point should exist at this point.");
continue;
}
- Contract.Assert (currentCodePageIndex != -1, "[ISCIIEncoding.GetChars]Expected valid currentCodePageIndex != -1");
+ Debug.Assert (currentCodePageIndex != -1, "[ISCIIEncoding.GetChars]Expected valid currentCodePageIndex != -1");
char ch = IndicMapping[currentCodePageIndex, 0, b - MultiByteBegin];
char cAlt = IndicMapping[currentCodePageIndex, 1, b - MultiByteBegin];
}
// We must be the Devenagari special case for F0, B8 & F0, BF
- Contract.Assert(currentCodePage == CodeDevanagari && b == DevenagariExt,
+ Debug.Assert(currentCodePage == CodeDevanagari && b == DevenagariExt,
String.Format(CultureInfo.InvariantCulture,
"[ISCIIEncoding.GetChars] Devenagari special case must {0} not {1} or in Devanagari code page {2} not {3}.",
DevenagariExt, b, CodeDevanagari, currentCodePage));
cLastCharForNoNextNukta != '\0' || bLastATR || bLastDevenagariStressAbbr)
{
// Either not flushing or had state (from convert)
- Contract.Assert(!decoder.MustFlush || !decoder.m_throwOnOverflow,
+ Debug.Assert(!decoder.MustFlush || !decoder.m_throwOnOverflow,
"[ISCIIEncoding.GetChars]Expected no state or not converting or not flushing");
decoder.currentCodePage = currentCodePage;
decoder.bLastVirama = bLastVirama;
namespace System.Text
{
using System.Globalization;
+ using System.Diagnostics;
using System.Diagnostics.Contracts;
using System.Text;
using System.Runtime.InteropServices;
// We have to load the 936 code page tables, so impersonate 936 as our base
// This pretends to be other code pages as far as memory sections are concerned.
- [System.Security.SecurityCritical] // auto-generated
internal ISO2022Encoding(int codePage) : base(codePage, tableBaseCodePages[codePage % 10])
{
this.m_bUseMlangTypeForSerialization = true;
// Constructor called by serialization.
// Note: We use the base GetObjectData however
- [System.Security.SecurityCritical] // auto-generated
internal ISO2022Encoding(SerializationInfo info, StreamingContext context) : base(info, context)
{
// Actually this can't ever get called, CodePageEncoding is our proxy
- Contract.Assert(false, "Didn't expect to make it to DBCSCodePageEncoding serialization constructor");
+ Debug.Assert(false, "Didn't expect to make it to DBCSCodePageEncoding serialization constructor");
throw new ArgumentException(Environment.GetResourceString("Arg_ExecutionEngineException"));
}
ModeNOOP = -3
}
- [System.Security.SecurityCritical] // auto-generated
protected unsafe override String GetMemorySectionName()
{
int iUseCodePage = this.bFlagDataTable ? dataTableCodePage : CodePage;
strFormat = "CodePage_{0}_{1}_{2}_{3}_{4}_HZ";
break;
default:
- Contract.Assert(false, "[ISO2022Encoding.GetMemorySectionName] Don't expect to get here for code page " + this.CodePage);
+ Debug.Assert(false, "[ISO2022Encoding.GetMemorySectionName] Don't expect to get here for code page " + this.CodePage);
strFormat = "CodePage_{0}_{1}_{2}_{3}_{4}";
break;
}
}
// GetByteCount
- [System.Security.SecurityCritical] // auto-generated
internal override unsafe int GetByteCount(char* chars, int count, EncoderNLS baseEncoder)
{
// Just need to ASSERT, this is called by something else internal that checked parameters already
- Contract.Assert(count >= 0, "[ISO2022Encoding.GetByteCount]count is negative");
- Contract.Assert(chars != null, "[ISO2022Encoding.GetByteCount]chars is null");
+ Debug.Assert(count >= 0, "[ISO2022Encoding.GetByteCount]count is negative");
+ Debug.Assert(chars != null, "[ISO2022Encoding.GetByteCount]chars is null");
// Just call GetBytes with null byte* to get count
return GetBytes(chars, count, null, 0, baseEncoder);
}
- [System.Security.SecurityCritical] // auto-generated
internal override unsafe int GetBytes(char* chars, int charCount,
byte* bytes, int byteCount, EncoderNLS baseEncoder)
{
// Just need to ASSERT, this is called by something else internal that checked parameters already
- Contract.Assert(chars != null, "[ISO2022Encoding.GetBytes]chars is null");
- Contract.Assert(byteCount >= 0, "[ISO2022Encoding.GetBytes]byteCount is negative");
- Contract.Assert(charCount >= 0, "[ISO2022Encoding.GetBytes]charCount is negative");
+ Debug.Assert(chars != null, "[ISO2022Encoding.GetBytes]chars is null");
+ Debug.Assert(byteCount >= 0, "[ISO2022Encoding.GetBytes]byteCount is negative");
+ Debug.Assert(charCount >= 0, "[ISO2022Encoding.GetBytes]charCount is negative");
// Assert because we shouldn't be able to have a null encoder.
- Contract.Assert(encoderFallback != null, "[ISO2022Encoding.GetBytes]Attempting to use null encoder fallback");
+ Debug.Assert(encoderFallback != null, "[ISO2022Encoding.GetBytes]Attempting to use null encoder fallback");
// Fix our encoder
ISO2022Encoder encoder = (ISO2022Encoder)baseEncoder;
}
// This is internal and called by something else,
- [System.Security.SecurityCritical] // auto-generated
internal override unsafe int GetCharCount(byte* bytes, int count, DecoderNLS baseDecoder)
{
// Just assert, we're called internally so these should be safe, checked already
- Contract.Assert(bytes != null, "[ISO2022Encoding.GetCharCount]bytes is null");
- Contract.Assert(count >= 0, "[ISO2022Encoding.GetCharCount]byteCount is negative");
+ Debug.Assert(bytes != null, "[ISO2022Encoding.GetCharCount]bytes is null");
+ Debug.Assert(count >= 0, "[ISO2022Encoding.GetCharCount]byteCount is negative");
// Just call getChars with null char* to get count
return GetChars(bytes, count, null, 0, baseDecoder);
}
- [System.Security.SecurityCritical] // auto-generated
internal override unsafe int GetChars(byte* bytes, int byteCount,
char* chars, int charCount, DecoderNLS baseDecoder)
{
// Just need to ASSERT, this is called by something else internal that checked parameters already
- Contract.Assert(bytes != null, "[ISO2022Encoding.GetChars]bytes is null");
- Contract.Assert(byteCount >= 0, "[ISO2022Encoding.GetChars]byteCount is negative");
- Contract.Assert(charCount >= 0, "[ISO2022Encoding.GetChars]charCount is negative");
+ Debug.Assert(bytes != null, "[ISO2022Encoding.GetChars]bytes is null");
+ Debug.Assert(byteCount >= 0, "[ISO2022Encoding.GetChars]byteCount is negative");
+ Debug.Assert(charCount >= 0, "[ISO2022Encoding.GetChars]charCount is negative");
// Fix our decoder
ISO2022Decoder decoder = (ISO2022Decoder)baseDecoder;
iCount = GetCharsCP52936( bytes, byteCount, chars, charCount, decoder);
break;
default:
- Contract.Assert(false, "[ISO2022Encoding.GetChars] had unexpected code page");
+ Debug.Assert(false, "[ISO2022Encoding.GetChars] had unexpected code page");
break;
}
// undefined, so we maintain that behavior when decoding. We will never generate characters using
// that technique, but the decoder will process them.
//
- [System.Security.SecurityCritical] // auto-generated
private unsafe int GetBytesCP5022xJP(char* chars, int charCount,
byte* bytes, int byteCount, ISO2022Encoder encoder)
{
// We may have a left over character from last time, try and process it.
if (charLeftOver > 0)
{
- Contract.Assert(Char.IsHighSurrogate(charLeftOver), "[ISO2022Encoding.GetBytesCP5022xJP]leftover character should be high surrogate");
+ Debug.Assert(Char.IsHighSurrogate(charLeftOver), "[ISO2022Encoding.GetBytesCP5022xJP]leftover character should be high surrogate");
// It has to be a high surrogate, which we don't support, so it has to be a fallback
buffer.Fallback(charLeftOver);
else
{
// 50221 does halfwidth katakana by escape sequence
- Contract.Assert(CodePage == 50221, "[ISO2022Encoding.GetBytesCP5022xJP]Expected Code Page 50221");
+ Debug.Assert(CodePage == 50221, "[ISO2022Encoding.GetBytesCP5022xJP]Expected Code Page 50221");
// Add our escape sequence
if (!buffer.AddByte(ESCAPE, unchecked((byte)'('), unchecked((byte)'I')))
// Also Mlang always assumed KR mode, even if the designator wasn't found yet, so we do that as
// well. So basically we just ignore <ESC>$)C when decoding.
//
- [System.Security.SecurityCritical] // auto-generated
private unsafe int GetBytesCP50225KR(char* chars, int charCount,
byte* bytes, int byteCount, ISO2022Encoder encoder)
{
// We may have a l left over character from last time, try and process it.
if (charLeftOver > 0)
{
- Contract.Assert(Char.IsHighSurrogate(charLeftOver), "[ISO2022Encoding.GetBytesCP50225KR]leftover character should be high surrogate");
+ Debug.Assert(Char.IsHighSurrogate(charLeftOver), "[ISO2022Encoding.GetBytesCP50225KR]leftover character should be high surrogate");
// It has to be a high surrogate, which we don't support, so it has to be a fallback
buffer.Fallback(charLeftOver);
if (!encoder.MustFlush || encoder.charLeftOver != (char)0)
{
// We should be not flushing or converting
- Contract.Assert(!encoder.MustFlush || !encoder.m_throwOnOverflow,
+ Debug.Assert(!encoder.MustFlush || !encoder.m_throwOnOverflow,
"[ISO2022Encoding.GetBytesCP50225KR]Expected no left over data or not flushing or not converting");
encoder.shiftInOutMode = shiftOutMode;
}
//
// This encoding is designed for transmission by e-mail and news. No bytes should have high bit set.
// (all bytes <= 0x7f)
- [System.Security.SecurityCritical] // auto-generated
private unsafe int GetBytesCP52936(char* chars, int charCount,
byte* bytes, int byteCount, ISO2022Encoder encoder)
{
// We may have a left over character from last time, try and process it.
if (charLeftOver > 0)
{
- Contract.Assert(Char.IsHighSurrogate(charLeftOver), "[ISO2022Encoding.GetBytesCP52936]leftover character should be high surrogate");
+ Debug.Assert(Char.IsHighSurrogate(charLeftOver), "[ISO2022Encoding.GetBytesCP52936]leftover character should be high surrogate");
// It has to be a high surrogate, which we don't support, so it has to be a fallback
buffer.Fallback(charLeftOver);
return buffer.Count;
}
- [System.Security.SecurityCritical] // auto-generated
private unsafe int GetCharsCP5022xJP(byte* bytes, int byteCount,
char* chars, int charCount, ISO2022Decoder decoder)
{
if (!decoder.MustFlush || escapeCount != 0)
{
// Either not flushing or had state (from convert)
- Contract.Assert(!decoder.MustFlush || !decoder.m_throwOnOverflow,
+ Debug.Assert(!decoder.MustFlush || !decoder.m_throwOnOverflow,
"[ISO2022Encoding.GetCharsCP5022xJP]Expected no state or not converting or not flushing");
decoder.currentMode = currentMode;
private byte DecrementEscapeBytes(ref byte[] bytes, ref int count)
{
- Contract.Assert(count > 0, "[ISO2022Encoding.DecrementEscapeBytes]count > 0");
+ Debug.Assert(count > 0, "[ISO2022Encoding.DecrementEscapeBytes]count > 0");
// Decrement our count
count--;
// Note that in DBCS mode mlang passed through ' ', '\t' and '\n' as SBCS characters
// probably to allow mailer formatting without too much extra work.
- [System.Security.SecurityCritical] // auto-generated
private unsafe int GetCharsCP50225KR(byte* bytes, int byteCount,
char* chars, int charCount, ISO2022Decoder decoder)
{
if (!decoder.MustFlush || escapeCount != 0)
{
// Either not flushing or had state (from convert)
- Contract.Assert(!decoder.MustFlush || !decoder.m_throwOnOverflow,
+ Debug.Assert(!decoder.MustFlush || !decoder.m_throwOnOverflow,
"[ISO2022Encoding.GetCharsCP50225KR]Expected no state or not converting or not flushing");
decoder.currentMode = currentMode;
//
// This encoding is designed for transmission by e-mail and news. No bytes should have high bit set.
// (all bytes <= 0x7f)
- [System.Security.SecurityCritical] // auto-generated
private unsafe int GetCharsCP52936(byte* bytes, int byteCount,
char* chars, int charCount, ISO2022Decoder decoder)
{
- Contract.Assert(byteCount >=0, "[ISO2022Encoding.GetCharsCP52936]count >=0");
- Contract.Assert(bytes!=null, "[ISO2022Encoding.GetCharsCP52936]bytes!=null");
+ Debug.Assert(byteCount >=0, "[ISO2022Encoding.GetCharsCP52936]count >=0");
+ Debug.Assert(bytes!=null, "[ISO2022Encoding.GetCharsCP52936]bytes!=null");
// Get our info.
Encoding.EncodingCharBuffer buffer = new Encoding.EncodingCharBuffer(
if (currentMode != ISO2022Modes.ModeASCII)
{
// Should be ModeHZ
- Contract.Assert(currentMode == ISO2022Modes.ModeHZ, "[ISO2022Encoding.GetCharsCP52936]Expected ModeHZ");
+ Debug.Assert(currentMode == ISO2022Modes.ModeHZ, "[ISO2022Encoding.GetCharsCP52936]Expected ModeHZ");
char cm;
// Everett allowed characters < 0x20 to be passed as if they were ASCII
else
{
// Either not flushing or had state (from convert)
- Contract.Assert(!decoder.MustFlush || !decoder.m_throwOnOverflow,
+ Debug.Assert(!decoder.MustFlush || !decoder.m_throwOnOverflow,
"[ISO2022Encoding.GetCharsCP52936]Expected no state or not converting or not flushing");
decoder.currentMode = currentMode;
namespace System.Text
{
using System;
+ using System.Diagnostics;
using System.Diagnostics.Contracts;
using System.Globalization;
using System.Runtime.InteropServices;
}
// ISerializable implementation, serialize it as a CodePageEncoding
- [System.Security.SecurityCritical] // auto-generated_required
void ISerializable.GetObjectData(SerializationInfo info, StreamingContext context)
{
// Make sure to get the base stuff too This throws if info is null
SerializeEncoding(info, context);
- Contract.Assert(info!=null, "[Latin1Encoding.GetObjectData] Expected null info to throw");
+ Debug.Assert(info!=null, "[Latin1Encoding.GetObjectData] Expected null info to throw");
// In Everett this is a CodePageEncoding, so it needs maxCharSize
info.AddValue("CodePageEncoding+maxCharSize", 1);
// GetByteCount
// Note: We start by assuming that the output will be the same as count. Having
// an encoder or fallback may change that assumption
- [System.Security.SecurityCritical] // auto-generated
internal override unsafe int GetByteCount(char* chars, int charCount, EncoderNLS encoder)
{
// Just need to ASSERT, this is called by something else internal that checked parameters already
- Contract.Assert(charCount >= 0, "[Latin1Encoding.GetByteCount]count is negative");
- Contract.Assert(chars != null, "[Latin1Encoding.GetByteCount]chars is null");
+ Debug.Assert(charCount >= 0, "[Latin1Encoding.GetByteCount]count is negative");
+ Debug.Assert(chars != null, "[Latin1Encoding.GetByteCount]chars is null");
// Assert because we shouldn't be able to have a null encoder.
- Contract.Assert(encoderFallback != null, "[Latin1Encoding.GetByteCount]Attempting to use null fallback encoder");
+ Debug.Assert(encoderFallback != null, "[Latin1Encoding.GetByteCount]Attempting to use null fallback encoder");
char charLeftOver = (char)0;
if (encoder != null)
{
charLeftOver = encoder.charLeftOver;
- Contract.Assert(charLeftOver == 0 || Char.IsHighSurrogate(charLeftOver),
+ Debug.Assert(charLeftOver == 0 || Char.IsHighSurrogate(charLeftOver),
"[Latin1Encoding.GetByteCount]leftover character should be high surrogate");
fallback = encoder.Fallback as EncoderReplacementFallback;
// Verify that we have no fallbackbuffer, for Latin1 its always empty, so just assert
- Contract.Assert(!encoder.m_throwOnOverflow || !encoder.InternalHasFallbackBuffer ||
+ Debug.Assert(!encoder.m_throwOnOverflow || !encoder.InternalHasFallbackBuffer ||
encoder.FallbackBuffer.Remaining == 0,
"[Latin1CodePageEncoding.GetByteCount]Expected empty fallback buffer");
}
if (charLeftOver > 0)
{
// Initialize the buffer
- Contract.Assert(encoder != null,
+ Debug.Assert(encoder != null,
"[Latin1Encoding.GetByteCount]Expected encoder if we have charLeftOver");
fallbackBuffer = encoder.FallbackBuffer;
fallbackBuffer.InternalInitialize(chars, charEnd, encoder, false);
byteCount++;
}
- Contract.Assert(fallbackBuffer == null || fallbackBuffer.Remaining == 0,
+ Debug.Assert(fallbackBuffer == null || fallbackBuffer.Remaining == 0,
"[Latin1Encoding.GetByteCount]Expected Empty fallback buffer");
return byteCount;
}
- [System.Security.SecurityCritical] // auto-generated
internal override unsafe int GetBytes(char* chars, int charCount,
byte* bytes, int byteCount, EncoderNLS encoder)
{
// Just need to ASSERT, this is called by something else internal that checked parameters already
- Contract.Assert(bytes != null, "[Latin1Encoding.GetBytes]bytes is null");
- Contract.Assert(byteCount >= 0, "[Latin1Encoding.GetBytes]byteCount is negative");
- Contract.Assert(chars != null, "[Latin1Encoding.GetBytes]chars is null");
- Contract.Assert(charCount >= 0, "[Latin1Encoding.GetBytes]charCount is negative");
+ Debug.Assert(bytes != null, "[Latin1Encoding.GetBytes]bytes is null");
+ Debug.Assert(byteCount >= 0, "[Latin1Encoding.GetBytes]byteCount is negative");
+ Debug.Assert(chars != null, "[Latin1Encoding.GetBytes]chars is null");
+ Debug.Assert(charCount >= 0, "[Latin1Encoding.GetBytes]charCount is negative");
// Assert because we shouldn't be able to have a null encoder.
- Contract.Assert(encoderFallback != null, "[Latin1Encoding.GetBytes]Attempting to use null encoder fallback");
+ Debug.Assert(encoderFallback != null, "[Latin1Encoding.GetBytes]Attempting to use null encoder fallback");
// Get any left over characters & check fast or slower fallback type
char charLeftOver = (char)0;
{
charLeftOver = encoder.charLeftOver;
fallback = encoder.Fallback as EncoderReplacementFallback;
- Contract.Assert(charLeftOver == 0 || Char.IsHighSurrogate(charLeftOver),
+ Debug.Assert(charLeftOver == 0 || Char.IsHighSurrogate(charLeftOver),
"[Latin1Encoding.GetBytes]leftover character should be high surrogate");
// Verify that we have no fallbackbuffer, for ASCII its always empty, so just assert
- Contract.Assert(!encoder.m_throwOnOverflow || !encoder.InternalHasFallbackBuffer ||
+ Debug.Assert(!encoder.m_throwOnOverflow || !encoder.InternalHasFallbackBuffer ||
encoder.FallbackBuffer.Remaining == 0,
"[Latin1CodePageEncoding.GetBytes]Expected empty fallback buffer");
}
{
// Since left over char was a surrogate, it'll have to be fallen back.
// Get Fallback
- Contract.Assert(encoder != null,
+ Debug.Assert(encoder != null,
"[Latin1Encoding.GetBytes]Expected encoder if we have charLeftOver");
fallbackBuffer = encoder.FallbackBuffer;
fallbackBuffer.InternalInitialize(chars, charEnd, encoder, true);
{
// Didn't use this char, throw it. Chars should've advanced by now
// If we had encoder fallback data it would've thrown before the loop
- Contract.Assert(chars > charStart,
+ Debug.Assert(chars > charStart,
"[Latin1Encoding.GetBytes]Expected chars to have advanced (fallback case)");
chars--;
fallbackBuffer.InternalReset();
if (bytes >= byteEnd)
{
// didn't use this char, we'll throw or use buffer
- Contract.Assert(fallbackBuffer == null || fallbackBuffer.bFallingBack == false,
+ Debug.Assert(fallbackBuffer == null || fallbackBuffer.bFallingBack == false,
"[Latin1Encoding.GetBytes]Expected fallback to have throw initially if insufficient space");
if (fallbackBuffer == null || fallbackBuffer.bFallingBack == false)
{
- Contract.Assert(chars > charStart,
+ Debug.Assert(chars > charStart,
"[Latin1Encoding.GetBytes]Expected chars to have advanced (fallback case)");
chars--; // don't use last char
}
encoder.m_charsUsed = (int)(chars - charStart);
}
- Contract.Assert(fallbackBuffer == null || fallbackBuffer.Remaining == 0,
+ Debug.Assert(fallbackBuffer == null || fallbackBuffer.Remaining == 0,
"[Latin1Encoding.GetBytes]Expected Empty fallback buffer");
return (int)(bytes - byteStart);
}
// This is internal and called by something else,
- [System.Security.SecurityCritical] // auto-generated
internal override unsafe int GetCharCount(byte* bytes, int count, DecoderNLS decoder)
{
// Just assert, we're called internally so these should be safe, checked already
- Contract.Assert(bytes != null, "[Latin1Encoding.GetCharCount]bytes is null");
- Contract.Assert(count >= 0, "[Latin1Encoding.GetCharCount]byteCount is negative");
+ Debug.Assert(bytes != null, "[Latin1Encoding.GetCharCount]bytes is null");
+ Debug.Assert(count >= 0, "[Latin1Encoding.GetCharCount]byteCount is negative");
// Just return length, SBCS stay the same length because they don't map to surrogate
// pairs and we don't have to fallback because all latin1Encoding code points are unicode
return count;
}
- [System.Security.SecurityCritical] // auto-generated
internal override unsafe int GetChars(byte* bytes, int byteCount,
char* chars, int charCount, DecoderNLS decoder)
{
// Just need to ASSERT, this is called by something else internal that checked parameters already
- Contract.Assert(bytes != null, "[Latin1Encoding.GetChars]bytes is null");
- Contract.Assert(byteCount >= 0, "[Latin1Encoding.GetChars]byteCount is negative");
- Contract.Assert(chars != null, "[Latin1Encoding.GetChars]chars is null");
- Contract.Assert(charCount >= 0, "[Latin1Encoding.GetChars]charCount is negative");
+ Debug.Assert(bytes != null, "[Latin1Encoding.GetChars]bytes is null");
+ Debug.Assert(byteCount >= 0, "[Latin1Encoding.GetChars]byteCount is negative");
+ Debug.Assert(chars != null, "[Latin1Encoding.GetChars]chars is null");
+ Debug.Assert(charCount >= 0, "[Latin1Encoding.GetChars]charCount is negative");
// Need byteCount chars, otherwise too small buffer
if (charCount < byteCount)
using System;
using System.Runtime.Serialization;
using System.Security.Permissions;
+ using System.Diagnostics;
using System.Diagnostics.Contracts;
/*=================================MLangCodePageEncoding==================================
}
// Just get it from GetEncoding
- [System.Security.SecurityCritical] // auto-generated
public Object GetRealObject(StreamingContext context)
{
// Get our encoding (Note: This has default fallbacks for readonly and everett cases)
}
// ISerializable implementation
- [System.Security.SecurityCritical] // auto-generated_required
void ISerializable.GetObjectData(SerializationInfo info, StreamingContext context)
{
// We cannot ever call this.
- Contract.Assert(false, "Didn't expect to make it to MLangCodePageEncoding ISerializable.GetObjectData");
+ Debug.Assert(false, "Didn't expect to make it to MLangCodePageEncoding ISerializable.GetObjectData");
throw new ArgumentException(Environment.GetResourceString("Arg_ExecutionEngineException"));
}
}
// Just get it from GetEncoder
- [System.Security.SecurityCritical] // auto-generated
public Object GetRealObject(StreamingContext context)
{
return this.realEncoding.GetEncoder();
}
// ISerializable implementation, get data for this object
- [System.Security.SecurityCritical] // auto-generated_required
void ISerializable.GetObjectData(SerializationInfo info, StreamingContext context)
{
// We cannot ever call this.
- Contract.Assert(false, "Didn't expect to make it to MLangCodePageEncoding.MLangEncoder.GetObjectData");
+ Debug.Assert(false, "Didn't expect to make it to MLangCodePageEncoding.MLangEncoder.GetObjectData");
throw new ArgumentException(Environment.GetResourceString("Arg_ExecutionEngineException"));
}
}
}
// Just get it from GetDecoder
- [System.Security.SecurityCritical] // auto-generated
public Object GetRealObject(StreamingContext context)
{
return this.realEncoding.GetDecoder();
}
// ISerializable implementation, get data for this object
- [System.Security.SecurityCritical] // auto-generated_required
void ISerializable.GetObjectData(SerializationInfo info, StreamingContext context)
{
// We cannot ever call this.
- Contract.Assert(false, "Didn't expect to make it to MLangCodePageEncoding.MLangDecoder.GetObjectData");
+ Debug.Assert(false, "Didn't expect to make it to MLangCodePageEncoding.MLangDecoder.GetObjectData");
throw new ArgumentException(Environment.GetResourceString("Arg_ExecutionEngineException"));
}
}
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Runtime.Versioning;
+ using System.Diagnostics;
using System.Diagnostics.Contracts;
// This internal class wraps up our normalization behavior
private const int ERROR_INSUFFICIENT_BUFFER = 122;
private const int ERROR_NO_UNICODE_TRANSLATION = 1113;
- [System.Security.SecurityCritical] // auto-generated
static private unsafe void InitializeForm(NormalizationForm form, String strDataFile)
{
byte* pTables = null;
nativeNormalizationInitNormalization(form, pTables);
}
- [System.Security.SecurityCritical] // auto-generated
static private void EnsureInitialized(NormalizationForm form)
{
switch ((ExtendedNormalizationForms)form)
}
}
- [System.Security.SecurityCritical]
internal static bool IsNormalized(String strInput, NormalizationForm normForm)
{
Contract.Requires(strInput != null);
return result;
}
- [System.Security.SecurityCritical]
internal static String Normalize(String strInput, NormalizationForm normForm)
{
Contract.Requires(strInput != null);
{
// Do appropriate stuff for the individual errors:
case ERROR_INSUFFICIENT_BUFFER:
- Contract.Assert(iLength > cBuffer.Length, "Buffer overflow should have iLength > cBuffer.Length");
+ Debug.Assert(iLength > cBuffer.Length, "Buffer overflow should have iLength > cBuffer.Length");
continue;
case ERROR_INVALID_PARAMETER:
return new String(cBuffer, 0, iLength);
}
- [System.Security.SecurityCritical] // auto-generated
[MethodImplAttribute(MethodImplOptions.InternalCall)]
unsafe private static extern int nativeNormalizationNormalizeString(
NormalizationForm normForm, ref int iError,
String lpSrcString, int cwSrcLength,
char[] lpDstString, int cwDstLength);
- [System.Security.SecurityCritical] // auto-generated
[MethodImplAttribute(MethodImplOptions.InternalCall)]
unsafe private static extern bool nativeNormalizationIsNormalizedString(
NormalizationForm normForm, ref int iError,
String lpString, int cwLength);
- [System.Security.SecurityCritical] // auto-generated
[SuppressUnmanagedCodeSecurity]
[DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
unsafe private static extern void nativeNormalizationInitNormalization(
namespace System.Text
{
using System;
+ using System.Diagnostics;
using System.Diagnostics.Contracts;
using System.Text;
using System.Threading;
{
// Pointers to our memory section parts
[NonSerialized]
- [SecurityCritical]
unsafe char* mapBytesToUnicode = null; // char 256
[NonSerialized]
- [SecurityCritical]
unsafe byte* mapUnicodeToBytes = null; // byte 65536
[NonSerialized]
- [SecurityCritical]
unsafe int* mapCodePageCached = null; // to remember which CP is cached
const char UNKNOWN_CHAR=(char)0xFFFD;
[NonSerialized]
char charUnknown;
- [System.Security.SecurityCritical] // auto-generated
public SBCSCodePageEncoding(int codePage) : this(codePage, codePage)
{
}
- [System.Security.SecurityCritical] // auto-generated
internal SBCSCodePageEncoding(int codePage, int dataCodePage) : base(codePage, dataCodePage)
{
}
// Constructor called by serialization.
// Note: We use the base GetObjectData however
- [System.Security.SecurityCritical] // auto-generated
internal SBCSCodePageEncoding(SerializationInfo info, StreamingContext context) : base(0)
{
// Actually this can't ever get called, CodePageEncoding is our proxy
- Contract.Assert(false, "Didn't expect to make it to SBCSCodePageEncoding serialization constructor");
+ Debug.Assert(false, "Didn't expect to make it to SBCSCodePageEncoding serialization constructor");
throw new ArgumentNullException("this");
}
// byte < 0x20 means skip the next n positions. (Where n is the byte #)
// byte == 1 means that next word is another unicode code point #
// byte == 0 is unknown. (doesn't override initial WCHAR[256] table!
- [System.Security.SecurityCritical] // auto-generated
protected override unsafe void LoadManagedCodePage()
{
// Should be loading OUR code page
- Contract.Assert(pCodePage->CodePage == this.dataTableCodePage,
+ Debug.Assert(pCodePage->CodePage == this.dataTableCodePage,
"[SBCSCodePageEncoding.LoadManagedCodePage]Expected to load data table code page");
// Make sure we're really a 1 byte code page
// If its cached (& filled in) we don't have to do anything else
if (*mapCodePageCached != 0)
{
- Contract.Assert(*mapCodePageCached == this.dataTableCodePage,
+ Debug.Assert(*mapCodePageCached == this.dataTableCodePage,
"[DBCSCodePageEncoding.LoadManagedCodePage]Expected mapped section cached page to be same as data table code page. Cached : " +
*mapCodePageCached + " Expected:" + this.dataTableCodePage);
}
// Read in our best fit table
- [System.Security.SecurityCritical] // auto-generated
protected unsafe override void ReadBestFitTable()
{
// Lock so we don't confuse ourselves.
while ((byteTemp = *((ushort*)pData)) != 0)
{
- Contract.Assert(arrayTemp[byteTemp] == UNKNOWN_CHAR, String.Format(CultureInfo.InvariantCulture,
+ Debug.Assert(arrayTemp[byteTemp] == UNKNOWN_CHAR, String.Format(CultureInfo.InvariantCulture,
"[SBCSCodePageEncoding::ReadBestFitTable] Expected unallocated byte (not 0x{2:X2}) for best fit byte at 0x{0:X2} for code page {1}",
byteTemp, CodePage, (int)arrayTemp[byteTemp]));
pData += 2;
arrayTemp[iBestFitCount++] = mapBytesToUnicode[input];
// This won't work if it won't round trip.
- Contract.Assert(arrayTemp[iBestFitCount-1] != (char)0,
+ Debug.Assert(arrayTemp[iBestFitCount-1] != (char)0,
String.Format(CultureInfo.InvariantCulture,
"[SBCSCodePageEncoding.ReadBestFitTable] No valid Unicode value {0:X4} for round trip bytes {1:X4}, encoding {2}",
(int)mapBytesToUnicode[input], (int)input, CodePage));
// GetByteCount
// Note: We start by assuming that the output will be the same as count. Having
// an encoder or fallback may change that assumption
- [System.Security.SecurityCritical] // auto-generated
internal override unsafe int GetByteCount(char* chars, int count, EncoderNLS encoder)
{
// Just need to ASSERT, this is called by something else internal that checked parameters already
- Contract.Assert(count >= 0, "[SBCSCodePageEncoding.GetByteCount]count is negative");
- Contract.Assert(chars != null, "[SBCSCodePageEncoding.GetByteCount]chars is null");
+ Debug.Assert(count >= 0, "[SBCSCodePageEncoding.GetByteCount]count is negative");
+ Debug.Assert(chars != null, "[SBCSCodePageEncoding.GetByteCount]chars is null");
// Assert because we shouldn't be able to have a null encoder.
- Contract.Assert(encoderFallback != null, "[SBCSCodePageEncoding.GetByteCount]Attempting to use null fallback");
+ Debug.Assert(encoderFallback != null, "[SBCSCodePageEncoding.GetByteCount]Attempting to use null fallback");
CheckMemorySection();
if (encoder != null)
{
charLeftOver = encoder.charLeftOver;
- Contract.Assert(charLeftOver == 0 || Char.IsHighSurrogate(charLeftOver),
+ Debug.Assert(charLeftOver == 0 || Char.IsHighSurrogate(charLeftOver),
"[SBCSCodePageEncoding.GetByteCount]leftover character should be high surrogate");
fallback = encoder.Fallback as EncoderReplacementFallback;
// Verify that we have no fallbackbuffer, actually for SBCS this is always empty, so just assert
- Contract.Assert(!encoder.m_throwOnOverflow || !encoder.InternalHasFallbackBuffer ||
+ Debug.Assert(!encoder.m_throwOnOverflow || !encoder.InternalHasFallbackBuffer ||
encoder.FallbackBuffer.Remaining == 0,
"[SBCSCodePageEncoding.GetByteCount]Expected empty fallback buffer at start");
}
{
// Since left over char was a surrogate, it'll have to be fallen back.
// Get Fallback
- Contract.Assert(encoder != null, "[SBCSCodePageEncoding.GetByteCount]Expect to have encoder if we have a charLeftOver");
+ Debug.Assert(encoder != null, "[SBCSCodePageEncoding.GetByteCount]Expect to have encoder if we have a charLeftOver");
fallbackBuffer = encoder.FallbackBuffer;
fallbackBuffer.InternalInitialize(chars, charEnd, encoder, false);
byteCount++;
}
- Contract.Assert(fallbackBuffer == null || fallbackBuffer.Remaining == 0,
+ Debug.Assert(fallbackBuffer == null || fallbackBuffer.Remaining == 0,
"[SBCSEncoding.GetByteCount]Expected Empty fallback buffer at end");
return (int)byteCount;
}
- [System.Security.SecurityCritical] // auto-generated
internal override unsafe int GetBytes(char* chars, int charCount,
byte* bytes, int byteCount, EncoderNLS encoder)
{
// Just need to ASSERT, this is called by something else internal that checked parameters already
- Contract.Assert(bytes != null, "[SBCSCodePageEncoding.GetBytes]bytes is null");
- Contract.Assert(byteCount >= 0, "[SBCSCodePageEncoding.GetBytes]byteCount is negative");
- Contract.Assert(chars != null, "[SBCSCodePageEncoding.GetBytes]chars is null");
- Contract.Assert(charCount >= 0, "[SBCSCodePageEncoding.GetBytes]charCount is negative");
+ Debug.Assert(bytes != null, "[SBCSCodePageEncoding.GetBytes]bytes is null");
+ Debug.Assert(byteCount >= 0, "[SBCSCodePageEncoding.GetBytes]byteCount is negative");
+ Debug.Assert(chars != null, "[SBCSCodePageEncoding.GetBytes]chars is null");
+ Debug.Assert(charCount >= 0, "[SBCSCodePageEncoding.GetBytes]charCount is negative");
// Assert because we shouldn't be able to have a null encoder.
- Contract.Assert(encoderFallback != null, "[SBCSCodePageEncoding.GetBytes]Attempting to use null encoder fallback");
+ Debug.Assert(encoderFallback != null, "[SBCSCodePageEncoding.GetBytes]Attempting to use null encoder fallback");
CheckMemorySection();
if (encoder != null)
{
charLeftOver = encoder.charLeftOver;
- Contract.Assert(charLeftOver == 0 || Char.IsHighSurrogate(charLeftOver),
+ Debug.Assert(charLeftOver == 0 || Char.IsHighSurrogate(charLeftOver),
"[SBCSCodePageEncoding.GetBytes]leftover character should be high surrogate");
fallback = encoder.Fallback as EncoderReplacementFallback;
// Verify that we have no fallbackbuffer, for SBCS its always empty, so just assert
- Contract.Assert(!encoder.m_throwOnOverflow || !encoder.InternalHasFallbackBuffer ||
+ Debug.Assert(!encoder.m_throwOnOverflow || !encoder.InternalHasFallbackBuffer ||
encoder.FallbackBuffer.Remaining == 0,
"[SBCSCodePageEncoding.GetBytes]Expected empty fallback buffer at start");
// if (encoder.m_throwOnOverflow && encoder.InternalHasFallbackBuffer &&
{
// Since left over char was a surrogate, it'll have to be fallen back.
// Get Fallback
- Contract.Assert(encoder != null, "[SBCSCodePageEncoding.GetBytes]Expect to have encoder if we have a charLeftOver");
+ Debug.Assert(encoder != null, "[SBCSCodePageEncoding.GetBytes]Expect to have encoder if we have a charLeftOver");
fallbackBuffer = encoder.FallbackBuffer;
fallbackBuffer.InternalInitialize(chars, charEnd, encoder, true);
if (fallbackBuffer.Remaining > byteEnd - bytes)
{
// Didn't use this char, reset it
- Contract.Assert(chars > charStart,
+ Debug.Assert(chars > charStart,
"[SBCSCodePageEncoding.GetBytes]Expected chars to have advanced (fallback)");
chars--;
fallbackBuffer.InternalReset();
if (bytes >= byteEnd)
{
// didn't use this char, we'll throw or use buffer
- Contract.Assert(fallbackBuffer == null || fallbackBuffer.bFallingBack == false,
+ Debug.Assert(fallbackBuffer == null || fallbackBuffer.bFallingBack == false,
"[SBCSCodePageEncoding.GetBytes]Expected to NOT be falling back");
if (fallbackBuffer == null || fallbackBuffer.bFallingBack == false)
{
- Contract.Assert(chars > charStart,
+ Debug.Assert(chars > charStart,
"[SBCSCodePageEncoding.GetBytes]Expected chars to have advanced (normal)");
chars--; // don't use last char
}
}
// Expect Empty fallback buffer for SBCS
- Contract.Assert(fallbackBuffer == null || fallbackBuffer.Remaining == 0,
+ Debug.Assert(fallbackBuffer == null || fallbackBuffer.Remaining == 0,
"[SBCSEncoding.GetBytes]Expected Empty fallback buffer at end");
return (int)(bytes - byteStart);
}
// This is internal and called by something else,
- [System.Security.SecurityCritical] // auto-generated
internal override unsafe int GetCharCount(byte* bytes, int count, DecoderNLS decoder)
{
// Just assert, we're called internally so these should be safe, checked already
- Contract.Assert(bytes != null, "[SBCSCodePageEncoding.GetCharCount]bytes is null");
- Contract.Assert(count >= 0, "[SBCSCodePageEncoding.GetCharCount]byteCount is negative");
+ Debug.Assert(bytes != null, "[SBCSCodePageEncoding.GetCharCount]bytes is null");
+ Debug.Assert(count >= 0, "[SBCSCodePageEncoding.GetCharCount]byteCount is negative");
CheckMemorySection();
{
fallback = decoder.Fallback as DecoderReplacementFallback;
bUseBestFit = decoder.Fallback.IsMicrosoftBestFitFallback;
- Contract.Assert(!decoder.m_throwOnOverflow || !decoder.InternalHasFallbackBuffer ||
+ Debug.Assert(!decoder.m_throwOnOverflow || !decoder.InternalHasFallbackBuffer ||
decoder.FallbackBuffer.Remaining == 0,
"[SBCSCodePageEncoding.GetChars]Expected empty fallback buffer at start");
}
}
// Fallback buffer must be empty
- Contract.Assert(fallbackBuffer == null || fallbackBuffer.Remaining == 0,
+ Debug.Assert(fallbackBuffer == null || fallbackBuffer.Remaining == 0,
"[SBCSEncoding.GetCharCount]Expected Empty fallback buffer at end");
// Converted sequence is same length as input
return charCount;
}
- [System.Security.SecurityCritical] // auto-generated
internal override unsafe int GetChars(byte* bytes, int byteCount,
char* chars, int charCount, DecoderNLS decoder)
{
// Just need to ASSERT, this is called by something else internal that checked parameters already
- Contract.Assert(bytes != null, "[SBCSCodePageEncoding.GetChars]bytes is null");
- Contract.Assert(byteCount >= 0, "[SBCSCodePageEncoding.GetChars]byteCount is negative");
- Contract.Assert(chars != null, "[SBCSCodePageEncoding.GetChars]chars is null");
- Contract.Assert(charCount >= 0, "[SBCSCodePageEncoding.GetChars]charCount is negative");
+ Debug.Assert(bytes != null, "[SBCSCodePageEncoding.GetChars]bytes is null");
+ Debug.Assert(byteCount >= 0, "[SBCSCodePageEncoding.GetChars]byteCount is negative");
+ Debug.Assert(chars != null, "[SBCSCodePageEncoding.GetChars]chars is null");
+ Debug.Assert(charCount >= 0, "[SBCSCodePageEncoding.GetChars]charCount is negative");
CheckMemorySection();
{
fallback = decoder.Fallback as DecoderReplacementFallback;
bUseBestFit = decoder.Fallback.IsMicrosoftBestFitFallback;
- Contract.Assert(!decoder.m_throwOnOverflow || !decoder.InternalHasFallbackBuffer ||
+ Debug.Assert(!decoder.m_throwOnOverflow || !decoder.InternalHasFallbackBuffer ||
decoder.FallbackBuffer.Remaining == 0,
"[SBCSCodePageEncoding.GetChars]Expected empty fallback buffer at start");
}
}
// Use fallback buffer
- Contract.Assert(bytes > byteStart,
+ Debug.Assert(bytes > byteStart,
"[SBCSCodePageEncoding.GetChars]Expected bytes to have advanced already (unknown byte)");
byteBuffer[0] = *(bytes - 1);
// Fallback adds fallback to chars, but doesn't increment chars unless the whole thing fits.
// Make sure we have buffer space
if (chars >= charEnd)
{
- Contract.Assert(bytes > byteStart,
+ Debug.Assert(bytes > byteStart,
"[SBCSCodePageEncoding.GetChars]Expected bytes to have advanced already (known byte)");
bytes--; // unused byte
ThrowCharsOverflow(decoder, bytes == byteStart); // throw?
decoder.m_bytesUsed = (int)(bytes - byteStart);
// Expect Empty fallback buffer for GetChars
- Contract.Assert(fallbackBuffer == null || fallbackBuffer.Remaining == 0,
+ Debug.Assert(fallbackBuffer == null || fallbackBuffer.Remaining == 0,
"[SBCSEncoding.GetChars]Expected Empty fallback buffer at end");
return (int)(chars - charStart);
using System.Security;
using System.Threading;
using System.Globalization;
+ using System.Diagnostics;
using System.Diagnostics.Contracts;
+ using System.Collections.Generic;
// This class represents a mutable string. It is convenient for situations in
// which it is desirable to modify a string, perhaps by removing, replacing, or
// Creates a new string builder from the specifed substring with the specified
// capacity. The maximum number of characters is set by capacity.
//
- [System.Security.SecuritySafeCritical] // auto-generated
public StringBuilder(String value, int startIndex, int length, int capacity) {
if (capacity<0) {
throw new ArgumentOutOfRangeException(nameof(capacity),
m_ChunkChars = new char[capacity];
}
- [System.Security.SecurityCritical] // auto-generated
private StringBuilder(SerializationInfo info, StreamingContext context) {
if (info == null)
throw new ArgumentNullException(nameof(info));
VerifyClassInvariant();
}
- [System.Security.SecurityCritical] // auto-generated
void ISerializable.GetObjectData(SerializationInfo info, StreamingContext context)
{
if (info==null) {
for (; ; )
{
// All blocks have copy of the maxCapacity.
- Contract.Assert(currentBlock.m_MaxCapacity == maxCapacity, "Bad maxCapacity");
- Contract.Assert(currentBlock.m_ChunkChars != null, "Empty Buffer");
+ Debug.Assert(currentBlock.m_MaxCapacity == maxCapacity, "Bad maxCapacity");
+ Debug.Assert(currentBlock.m_ChunkChars != null, "Empty Buffer");
- Contract.Assert(currentBlock.m_ChunkLength <= currentBlock.m_ChunkChars.Length, "Out of range length");
- Contract.Assert(currentBlock.m_ChunkLength >= 0, "Negative length");
- Contract.Assert(currentBlock.m_ChunkOffset >= 0, "Negative offset");
+ Debug.Assert(currentBlock.m_ChunkLength <= currentBlock.m_ChunkChars.Length, "Out of range length");
+ Debug.Assert(currentBlock.m_ChunkLength >= 0, "Negative length");
+ Debug.Assert(currentBlock.m_ChunkOffset >= 0, "Negative offset");
StringBuilder prevBlock = currentBlock.m_ChunkPrevious;
if (prevBlock == null)
{
- Contract.Assert(currentBlock.m_ChunkOffset == 0, "First chunk's offset is not 0");
+ Debug.Assert(currentBlock.m_ChunkOffset == 0, "First chunk's offset is not 0");
break;
}
// There are no gaps in the blocks.
- Contract.Assert(currentBlock.m_ChunkOffset == prevBlock.m_ChunkOffset + prevBlock.m_ChunkLength, "There is a gap between chunks!");
+ Debug.Assert(currentBlock.m_ChunkOffset == prevBlock.m_ChunkOffset + prevBlock.m_ChunkLength, "There is a gap between chunks!");
currentBlock = prevBlock;
}
}
return Capacity;
}
- [System.Security.SecuritySafeCritical] // auto-generated
public override String ToString() {
Contract.Ensures(Contract.Result<String>() != null);
// Converts a substring of this string builder to a String.
- [System.Security.SecuritySafeCritical] // auto-generated
public String ToString(int startIndex, int length) {
Contract.Ensures(Contract.Result<String>() != null);
{
m_ChunkLength = 0;
m_ChunkOffset = 0;
- Contract.Assert(Capacity >= originalCapacity, "setting the Length should never decrease the Capacity");
+ Debug.Assert(Capacity >= originalCapacity, "setting the Length should never decrease the Capacity");
return;
}
int newLen = originalCapacity - chunk.m_ChunkOffset;
char[] newArray = new char[newLen];
- Contract.Assert(newLen > chunk.m_ChunkChars.Length, "the new chunk should be larger than the one it is replacing");
+ Debug.Assert(newLen > chunk.m_ChunkChars.Length, "the new chunk should be larger than the one it is replacing");
Array.Copy(chunk.m_ChunkChars, newArray, chunk.m_ChunkLength);
m_ChunkChars = newArray;
m_ChunkLength = value - chunk.m_ChunkOffset;
VerifyClassInvariant();
}
- Contract.Assert(Capacity >= originalCapacity, "setting the Length should never decrease the Capacity");
+ Debug.Assert(Capacity >= originalCapacity, "setting the Length should never decrease the Capacity");
}
}
{
m_ChunkLength = idx;
ExpandByABlock(repeatCount);
- Contract.Assert(m_ChunkLength == 0, "Expand should create a new block");
+ Debug.Assert(m_ChunkLength == 0, "Expand should create a new block");
idx = 0;
}
}
}
// Appends an array of characters at the end of this string builder. The capacity is adjusted as needed.
- [System.Security.SecuritySafeCritical] // auto-generated
public StringBuilder Append(char[] value, int startIndex, int charCount) {
if (startIndex < 0) {
throw new ArgumentOutOfRangeException(nameof(startIndex), Environment.GetResourceString("ArgumentOutOfRange_GenericPositive"));
// Appends a copy of this string at the end of this string builder.
- [System.Security.SecuritySafeCritical] // auto-generated
public StringBuilder Append(String value) {
Contract.Ensures(Contract.Result<StringBuilder>() != null);
// We put this fixed in its own helper to avoid the cost zero initing valueChars in the
// case we don't actually use it.
- [System.Security.SecuritySafeCritical] // auto-generated
private void AppendHelper(string value) {
unsafe {
fixed (char* valueChars = value)
}
[MethodImplAttribute(MethodImplOptions.InternalCall)]
- [SecurityCritical]
internal unsafe extern void ReplaceBufferInternal(char* newBuffer, int newLength);
[MethodImplAttribute(MethodImplOptions.InternalCall)]
- [SecurityCritical]
internal unsafe extern void ReplaceBufferAnsiInternal(sbyte* newBuffer, int newLength);
// Appends a copy of the characters in value from startIndex to startIndex +
// count at the end of this string builder.
- [System.Security.SecuritySafeCritical] // auto-generated
public StringBuilder Append(String value, int startIndex, int count) {
if (startIndex < 0) {
throw new ArgumentOutOfRangeException(nameof(startIndex), Environment.GetResourceString("ArgumentOutOfRange_Index"));
}
[System.Runtime.InteropServices.ComVisible(false)]
- [SecuritySafeCritical]
public void CopyTo(int sourceIndex, char[] destination, int destinationIndex, int count) {
if (destination == null) {
throw new ArgumentNullException(nameof(destination));
// The capacity is adjusted as needed. If value equals String.Empty, this
// string builder is not changed.
//
- [System.Security.SecuritySafeCritical] // auto-generated
public StringBuilder Insert(int index, String value, int count) {
if (count < 0) {
throw new ArgumentOutOfRangeException(nameof(count), Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
if (insertingChars > MaxCapacity - this.Length) {
throw new OutOfMemoryException();
}
- Contract.Assert(insertingChars + this.Length < Int32.MaxValue);
+ Debug.Assert(insertingChars + this.Length < Int32.MaxValue);
StringBuilder chunk;
int indexInChunk;
}
// Appends all of the characters in value to the current instance.
- [System.Security.SecuritySafeCritical] // auto-generated
public StringBuilder Append(char[] value) {
Contract.Ensures(Contract.Result<StringBuilder>() != null);
return this;
}
+ // Append joined values with a separator between each value.
+ public unsafe StringBuilder AppendJoin<T>(char separator, params T[] values)
+ {
+ // Defer argument validation to the internal function
+ return AppendJoinCore(&separator, 1, values);
+ }
+
+ public unsafe StringBuilder AppendJoin<T>(string separator, params T[] values)
+ {
+ separator = separator ?? string.Empty;
+ fixed (char* pSeparator = separator)
+ {
+ // Defer argument validation to the internal function
+ return AppendJoinCore(pSeparator, separator.Length, values);
+ }
+ }
+
+ public unsafe StringBuilder AppendJoin<T>(char separator, IEnumerable<T> values)
+ {
+ // Defer argument validation to the internal function
+ return AppendJoinCore(&separator, 1, values);
+ }
+
+ public unsafe StringBuilder AppendJoin<T>(string separator, IEnumerable<T> values)
+ {
+ separator = separator ?? string.Empty;
+ fixed (char* pSeparator = separator)
+ {
+ // Defer argument validation to the internal function
+ return AppendJoinCore(pSeparator, separator.Length, values);
+ }
+ }
+
+ private unsafe StringBuilder AppendJoinCore<T>(char* separator, int separatorLength, params T[] values)
+ {
+ if (values == null)
+ throw new ArgumentNullException(nameof(values));
+ Contract.Ensures(Contract.Result<StringBuilder>() != null);
+
+ if (values.Length == 0)
+ return this;
+
+ var value = values[0];
+ if (value != null)
+ Append(value.ToString());
+
+ for (var i = 1; i < values.Length; i++)
+ {
+ Append(separator, separatorLength);
+ value = values[i];
+ if (value != null)
+ Append(value.ToString());
+ }
+ return this;
+ }
+
+ private unsafe StringBuilder AppendJoinCore<T>(char* separator, int separatorLength, IEnumerable<T> values)
+ {
+ if (values == null)
+ throw new ArgumentNullException(nameof(values));
+ Contract.Ensures(Contract.Result<StringBuilder>() != null);
+
+ using (var en = values.GetEnumerator())
+ {
+ if (!en.MoveNext())
+ return this;
+
+ var value = en.Current;
+ if (value != null)
+ Append(value.ToString());
+
+ while (en.MoveNext())
+ {
+ Append(separator, separatorLength);
+ value = en.Current;
+ if (value != null)
+ Append(value.ToString());
+ }
+ }
+ return this;
+ }
+
/*====================================Insert====================================
**
==============================================================================*/
// The capacity is adjusted as needed. If value equals String.Empty, the
// StringBuilder is not changed.
//
- [System.Security.SecuritySafeCritical] // auto-generated
public StringBuilder Insert(int index, String value) {
if ((uint)index > (uint)Length) {
throw new ArgumentOutOfRangeException(nameof(index), Environment.GetResourceString("ArgumentOutOfRange_Index"));
// the buffer at index. Existing characters are shifted to make room for the new text.
// The capacity is adjusted as needed. If value equals String.Empty, the
// StringBuilder is not changed.
- [SecuritySafeCritical]
public StringBuilder Insert(int index, char value) {
Contract.Ensures(Contract.Result<StringBuilder>() != null);
// value inserted into the buffer at index. Existing characters are shifted
// to make room for the new text and capacity is adjusted as required. If value is null, the StringBuilder
// is unchanged. Characters are taken from value starting at position startIndex.
- [System.Security.SecuritySafeCritical] // auto-generated
public StringBuilder Insert(int index, char[] value, int startIndex, int charCount) {
Contract.Ensures(Contract.Result<StringBuilder>() != null);
chunk = FindChunkForIndex(index);
indexInChunk = index - chunk.m_ChunkOffset;
- Contract.Assert(chunk != null || count == 0, "Chunks ended prematurely");
+ Debug.Assert(chunk != null || count == 0, "Chunks ended prematurely");
}
}
VerifyClassInvariant();
/// <summary>
/// Appends 'value' of length 'count' to the stringBuilder.
/// </summary>
- [SecurityCritical]
[System.CLSCompliantAttribute(false)]
public unsafe StringBuilder Append(char* value, int valueCount)
{
// Expand the builder to add another chunk.
int restLength = valueCount - firstLength;
ExpandByABlock(restLength);
- Contract.Assert(m_ChunkLength == 0, "Expand did not make a new block");
+ Debug.Assert(m_ChunkLength == 0, "Expand did not make a new block");
// Copy the second chunk
ThreadSafeCopy(value + firstLength, m_ChunkChars, 0, restLength);
/// <summary>
/// Inserts 'value' of length 'cou
/// </summary>
- [SecurityCritical]
unsafe private void Insert(int index, char* value, int valueCount)
{
if ((uint)index > (uint)Length)
/// replacements in bulk (and therefore very efficiently.
/// with the string 'value'.
/// </summary>
- [System.Security.SecuritySafeCritical] // auto-generated
private void ReplaceAllInChunk(int[] replacements, int replacementsCount, StringBuilder sourceChunk, int removeCount, string value)
{
if (replacementsCount <= 0)
break;
int gapEnd = replacements[i];
- Contract.Assert(gapStart < sourceChunk.m_ChunkChars.Length, "gap starts at end of buffer. Should not happen");
- Contract.Assert(gapStart <= gapEnd, "negative gap size");
- Contract.Assert(gapEnd <= sourceChunk.m_ChunkLength, "gap too big");
+ Debug.Assert(gapStart < sourceChunk.m_ChunkChars.Length, "gap starts at end of buffer. Should not happen");
+ Debug.Assert(gapStart <= gapEnd, "negative gap size");
+ Debug.Assert(gapEnd <= sourceChunk.m_ChunkLength, "gap too big");
if (delta != 0) // can skip the sliding of gaps if source an target string are the same size.
{
// Copy the gap data between the current replacement and the the next replacement
else
{
targetIndexInChunk += gapEnd - gapStart;
- Contract.Assert(targetIndexInChunk <= targetChunk.m_ChunkLength, "gap not in chunk");
+ Debug.Assert(targetIndexInChunk <= targetChunk.m_ChunkLength, "gap not in chunk");
}
}
/// point at the end of the characters just copyied (thus you can splice in strings from multiple
/// places by calling this mulitple times.
/// </summary>
- [SecurityCritical]
unsafe private void ReplaceInPlaceAtChunk(ref StringBuilder chunk, ref int indexInChunk, char* value, int count)
{
if (count != 0)
for (; ; )
{
int lengthInChunk = chunk.m_ChunkLength - indexInChunk;
- Contract.Assert(lengthInChunk >= 0, "index not in chunk");
+ Debug.Assert(lengthInChunk >= 0, "index not in chunk");
int lengthToCopy = Math.Min(lengthInChunk, count);
ThreadSafeCopy(value, chunk.m_ChunkChars, indexInChunk, lengthToCopy);
/// The only way to do this is to copy all interesting variables out of the heap and then do the
/// bounds check. This is what we do here.
/// </summary>
- [SecurityCritical]
unsafe private static void ThreadSafeCopy(char* sourcePtr, char[] destination, int destinationIndex, int count)
{
if (count > 0)
}
}
}
- [SecurityCritical]
private static void ThreadSafeCopy(char[] source, int sourceIndex, char[] destination, int destinationIndex, int count)
{
if (count > 0)
}
// Copies the source StringBuilder to the destination IntPtr memory allocated with len bytes.
- [System.Security.SecurityCritical] // auto-generated
internal unsafe void InternalCopy(IntPtr dest, int len) {
if(len ==0)
return;
/// <returns></returns>
private StringBuilder FindChunkForIndex(int index)
{
- Contract.Assert(0 <= index && index <= Length, "index not in string");
+ Debug.Assert(0 <= index && index <= Length, "index not in string");
StringBuilder ret = this;
while (ret.m_ChunkOffset > index)
ret = ret.m_ChunkPrevious;
- Contract.Assert(ret != null, "index not in string");
+ Debug.Assert(ret != null, "index not in string");
return ret;
}
/// <returns></returns>
private StringBuilder FindChunkForByte(int byteIndex)
{
- Contract.Assert(0 <= byteIndex && byteIndex <= Length*sizeof(char), "Byte Index not in string");
+ Debug.Assert(0 <= byteIndex && byteIndex <= Length*sizeof(char), "Byte Index not in string");
StringBuilder ret = this;
while (ret.m_ChunkOffset*sizeof(char) > byteIndex)
ret = ret.m_ChunkPrevious;
- Contract.Assert(ret != null, "Byte Index not in string");
+ Debug.Assert(ret != null, "Byte Index not in string");
return ret;
}
/// If dontMoveFollowingChars is true, then the room must be made by inserting a chunk BEFORE the
/// current chunk (this is what it does most of the time anyway)
/// </summary>
- [System.Security.SecuritySafeCritical] // auto-generated
private void MakeRoom(int index, int count, out StringBuilder chunk, out int indexInChunk, bool doneMoveFollowingChars)
{
VerifyClassInvariant();
- Contract.Assert(count > 0, "Count must be strictly positive");
- Contract.Assert(index >= 0, "Index can't be negative");
+ Debug.Assert(count > 0, "Count must be strictly positive");
+ Debug.Assert(index >= 0, "Index can't be negative");
if (count + Length > m_MaxCapacity || count + Length < count)
throw new ArgumentOutOfRangeException("requiredLength", Environment.GetResourceString("ArgumentOutOfRange_SmallCapacity"));
/// </summary>
private StringBuilder(int size, int maxCapacity, StringBuilder previousBlock)
{
- Contract.Assert(size > 0, "size not positive");
- Contract.Assert(maxCapacity > 0, "maxCapacity not positive");
+ Debug.Assert(size > 0, "size not positive");
+ Debug.Assert(maxCapacity > 0, "maxCapacity not positive");
m_ChunkChars = new char[size];
m_MaxCapacity = maxCapacity;
m_ChunkPrevious = previousBlock;
/// Removes 'count' characters from the logical index 'startIndex' and returns the chunk and
/// index in the chunk of that logical index in the out parameters.
/// </summary>
- [SecuritySafeCritical]
private void Remove(int startIndex, int count, out StringBuilder chunk, out int indexInChunk)
{
VerifyClassInvariant();
- Contract.Assert(startIndex >= 0 && startIndex < Length, "startIndex not in string");
+ Debug.Assert(startIndex >= 0 && startIndex < Length, "startIndex not in string");
int endIndex = startIndex + count;
}
chunk = chunk.m_ChunkPrevious;
}
- Contract.Assert(chunk != null, "fell off beginning of string!");
+ Debug.Assert(chunk != null, "fell off beginning of string!");
int copyTargetIndexInChunk = indexInChunk;
int copyCount = endChunk.m_ChunkLength - endIndexInChunk;
if (copyTargetIndexInChunk != endIndexInChunk) // Sometimes no move is necessary
ThreadSafeCopy(endChunk.m_ChunkChars, endIndexInChunk, endChunk.m_ChunkChars, copyTargetIndexInChunk, copyCount);
- Contract.Assert(chunk != null, "fell off beginning of string!");
+ Debug.Assert(chunk != null, "fell off beginning of string!");
VerifyClassInvariant();
}
}
using System;
using System.Runtime.Serialization;
using System.Security.Permissions;
+ using System.Diagnostics;
using System.Diagnostics.Contracts;
/*=================================SurrogateEncoder==================================
}
// Just get it from GetEncoding
- [System.Security.SecurityCritical] // auto-generated
public Object GetRealObject(StreamingContext context)
{
// Need to get our Encoding's Encoder
}
// ISerializable implementation
- [System.Security.SecurityCritical] // auto-generated_required
void ISerializable.GetObjectData(SerializationInfo info, StreamingContext context)
{
// We cannot ever call this.
- Contract.Assert(false, "Didn't expect to make it to SurrogateEncoder.GetObjectData");
+ Debug.Assert(false, "Didn't expect to make it to SurrogateEncoder.GetObjectData");
throw new ArgumentException(Environment.GetResourceString("Arg_ExecutionEngineException"));
}
}
{
using System;
+ using System.Diagnostics;
using System.Diagnostics.Contracts;
using System.Globalization;
// Encodes text into and out of UTF-32. UTF-32 is a way of writing
return EncodingForwarder.GetByteCount(this, s);
}
- [System.Security.SecurityCritical] // auto-generated
[CLSCompliant(false)]
public override unsafe int GetByteCount(char* chars, int count)
{
return EncodingForwarder.GetBytes(this, chars, charIndex, charCount, bytes, byteIndex);
}
- [System.Security.SecurityCritical] // auto-generated
[CLSCompliant(false)]
public override unsafe int GetBytes(char* chars, int charCount, byte* bytes, int byteCount)
{
return EncodingForwarder.GetCharCount(this, bytes, index, count);
}
- [System.Security.SecurityCritical] // auto-generated
[CLSCompliant(false)]
public override unsafe int GetCharCount(byte* bytes, int count)
{
return EncodingForwarder.GetChars(this, bytes, byteIndex, byteCount, chars, charIndex);
}
- [System.Security.SecurityCritical] // auto-generated
[CLSCompliant(false)]
public unsafe override int GetChars(byte* bytes, int byteCount, char* chars, int charCount)
{
// End of overridden methods which use EncodingForwarder
- [System.Security.SecurityCritical] // auto-generated
internal override unsafe int GetByteCount(char *chars, int count, EncoderNLS encoder)
{
- Contract.Assert(chars!=null, "[UTF32Encoding.GetByteCount]chars!=null");
- Contract.Assert(count >=0, "[UTF32Encoding.GetByteCount]count >=0");
+ Debug.Assert(chars!=null, "[UTF32Encoding.GetByteCount]chars!=null");
+ Debug.Assert(count >=0, "[UTF32Encoding.GetByteCount]count >=0");
char* end = chars + count;
char* charStart = chars;
// We are missing our low surrogate, decrement chars and fallback the high surrogate
// The high surrogate may have come from the encoder, but nothing else did.
- Contract.Assert(chars > charStart,
+ Debug.Assert(chars > charStart,
"[UTF32Encoding.GetByteCount]Expected chars to have advanced if no low surrogate");
chars--;
// Shouldn't have anything in fallback buffer for GetByteCount
// (don't have to check m_throwOnOverflow for count)
- Contract.Assert(fallbackBuffer.Remaining == 0,
+ Debug.Assert(fallbackBuffer.Remaining == 0,
"[UTF32Encoding.GetByteCount]Expected empty fallback buffer at end");
// Return our count
return byteCount;
}
- [System.Security.SecurityCritical] // auto-generated
internal override unsafe int GetBytes(char *chars, int charCount,
byte* bytes, int byteCount, EncoderNLS encoder)
{
- Contract.Assert(chars!=null, "[UTF32Encoding.GetBytes]chars!=null");
- Contract.Assert(bytes!=null, "[UTF32Encoding.GetBytes]bytes!=null");
- Contract.Assert(byteCount >=0, "[UTF32Encoding.GetBytes]byteCount >=0");
- Contract.Assert(charCount >=0, "[UTF32Encoding.GetBytes]charCount >=0");
+ Debug.Assert(chars!=null, "[UTF32Encoding.GetBytes]chars!=null");
+ Debug.Assert(bytes!=null, "[UTF32Encoding.GetBytes]bytes!=null");
+ Debug.Assert(byteCount >=0, "[UTF32Encoding.GetBytes]byteCount >=0");
+ Debug.Assert(charCount >=0, "[UTF32Encoding.GetBytes]charCount >=0");
char* charStart = chars;
char* charEnd = chars + charCount;
{
// If we don't have enough room, then either we should've advanced a while
// or we should have bytes==byteStart and throw below
- Contract.Assert(chars > charStart + 1 || bytes == byteStart,
+ Debug.Assert(chars > charStart + 1 || bytes == byteStart,
"[UnicodeEncoding.GetBytes]Expected chars to have when no room to add surrogate pair");
chars-=2; // Aren't using those 2 chars
}
// We are missing our low surrogate, decrement chars and fallback the high surrogate
// The high surrogate may have come from the encoder, but nothing else did.
- Contract.Assert(chars > charStart,
+ Debug.Assert(chars > charStart,
"[UTF32Encoding.GetBytes]Expected chars to have advanced if no low surrogate");
chars--;
else
{
// Must've advanced already
- Contract.Assert(chars > charStart,
+ Debug.Assert(chars > charStart,
"[UTF32Encoding.GetBytes]Expected chars to have advanced if normal character");
chars--; // Aren't using this char
}
}
// Fix our encoder if we have one
- Contract.Assert(highSurrogate == 0 || (encoder != null && !encoder.MustFlush),
+ Debug.Assert(highSurrogate == 0 || (encoder != null && !encoder.MustFlush),
"[UTF32Encoding.GetBytes]Expected encoder to be flushed.");
if (encoder != null)
return (int)(bytes - byteStart);
}
- [System.Security.SecurityCritical] // auto-generated
internal override unsafe int GetCharCount(byte* bytes, int count, DecoderNLS baseDecoder)
{
- Contract.Assert(bytes!=null, "[UTF32Encoding.GetCharCount]bytes!=null");
- Contract.Assert(count >=0, "[UTF32Encoding.GetCharCount]count >=0");
+ Debug.Assert(bytes!=null, "[UTF32Encoding.GetCharCount]bytes!=null");
+ Debug.Assert(count >=0, "[UTF32Encoding.GetCharCount]count >=0");
UTF32Decoder decoder = (UTF32Decoder)baseDecoder;
// Shouldn't have anything in fallback buffer for GetCharCount
// (don't have to check m_throwOnOverflow for chars or count)
- Contract.Assert(fallbackBuffer.Remaining == 0,
+ Debug.Assert(fallbackBuffer.Remaining == 0,
"[UTF32Encoding.GetCharCount]Expected empty fallback buffer at start");
}
else
// Shouldn't have anything in fallback buffer for GetCharCount
// (don't have to check m_throwOnOverflow for chars or count)
- Contract.Assert(fallbackBuffer.Remaining == 0,
+ Debug.Assert(fallbackBuffer.Remaining == 0,
"[UTF32Encoding.GetCharCount]Expected empty fallback buffer at end");
// Return our count
return charCount;
}
- [System.Security.SecurityCritical] // auto-generated
internal override unsafe int GetChars(byte* bytes, int byteCount,
char* chars, int charCount, DecoderNLS baseDecoder)
{
- Contract.Assert(chars!=null, "[UTF32Encoding.GetChars]chars!=null");
- Contract.Assert(bytes!=null, "[UTF32Encoding.GetChars]bytes!=null");
- Contract.Assert(byteCount >=0, "[UTF32Encoding.GetChars]byteCount >=0");
- Contract.Assert(charCount >=0, "[UTF32Encoding.GetChars]charCount >=0");
+ Debug.Assert(chars!=null, "[UTF32Encoding.GetChars]chars!=null");
+ Debug.Assert(bytes!=null, "[UTF32Encoding.GetChars]bytes!=null");
+ Debug.Assert(byteCount >=0, "[UTF32Encoding.GetChars]byteCount >=0");
+ Debug.Assert(charCount >=0, "[UTF32Encoding.GetChars]charCount >=0");
UTF32Decoder decoder = (UTF32Decoder)baseDecoder;
// Shouldn't have anything in fallback buffer for GetChars
// (don't have to check m_throwOnOverflow for chars)
- Contract.Assert(fallbackBuffer.Remaining == 0,
+ Debug.Assert(fallbackBuffer.Remaining == 0,
"[UTF32Encoding.GetChars]Expected empty fallback buffer at start");
}
else
// Couldn't fallback, throw or wait til next time
// We either read enough bytes for bytes-=4 to work, or we're
// going to throw in ThrowCharsOverflow because chars == charStart
- Contract.Assert(bytes >= byteStart + 4 || chars == charStart,
+ Debug.Assert(bytes >= byteStart + 4 || chars == charStart,
"[UTF32Encoding.GetChars]Expected to have consumed bytes or throw (bad surrogate)");
bytes-=4; // get back to where we were
iChar=0; // Remembering nothing
// Throwing or stopping
// We either read enough bytes for bytes-=4 to work, or we're
// going to throw in ThrowCharsOverflow because chars == charStart
- Contract.Assert(bytes >= byteStart + 4 || chars == charStart,
+ Debug.Assert(bytes >= byteStart + 4 || chars == charStart,
"[UTF32Encoding.GetChars]Expected to have consumed bytes or throw (surrogate)");
bytes-=4; // get back to where we were
iChar=0; // Remembering nothing
// Throwing or stopping
// We either read enough bytes for bytes-=4 to work, or we're
// going to throw in ThrowCharsOverflow because chars == charStart
- Contract.Assert(bytes >= byteStart + 4 || chars == charStart,
+ Debug.Assert(bytes >= byteStart + 4 || chars == charStart,
"[UTF32Encoding.GetChars]Expected to have consumed bytes or throw (normal char)");
bytes-=4; // get back to where we were
iChar=0; // Remembering nothing
// Shouldn't have anything in fallback buffer for GetChars
// (don't have to check m_throwOnOverflow for chars)
- Contract.Assert(fallbackBuffer.Remaining == 0,
+ Debug.Assert(fallbackBuffer.Remaining == 0,
"[UTF32Encoding.GetChars]Expected empty fallback buffer at end");
// Return our count
using System;
using System.Runtime.Serialization;
using System.Security.Permissions;
+ using System.Diagnostics;
using System.Diagnostics.Contracts;
return EncodingForwarder.GetByteCount(this, s);
}
- [System.Security.SecurityCritical] // auto-generated
[CLSCompliant(false)]
[System.Runtime.InteropServices.ComVisible(false)]
public override unsafe int GetByteCount(char* chars, int count)
return EncodingForwarder.GetBytes(this, chars, charIndex, charCount, bytes, byteIndex);
}
- [System.Security.SecurityCritical] // auto-generated
[CLSCompliant(false)]
[System.Runtime.InteropServices.ComVisible(false)]
public override unsafe int GetBytes(char* chars, int charCount, byte* bytes, int byteCount)
return EncodingForwarder.GetCharCount(this, bytes, index, count);
}
- [System.Security.SecurityCritical] // auto-generated
[CLSCompliant(false)]
[System.Runtime.InteropServices.ComVisible(false)]
public override unsafe int GetCharCount(byte* bytes, int count)
return EncodingForwarder.GetChars(this, bytes, byteIndex, byteCount, chars, charIndex);
}
- [System.Security.SecurityCritical] // auto-generated
[CLSCompliant(false)]
[System.Runtime.InteropServices.ComVisible(false)]
public unsafe override int GetChars(byte* bytes, int byteCount, char* chars, int charCount)
// End of overridden methods which use EncodingForwarder
- [System.Security.SecurityCritical] // auto-generated
internal override unsafe int GetByteCount(char* chars, int count, EncoderNLS baseEncoder)
{
- Contract.Assert(chars!=null, "[UTF7Encoding.GetByteCount]chars!=null");
- Contract.Assert(count >=0, "[UTF7Encoding.GetByteCount]count >=0");
+ Debug.Assert(chars!=null, "[UTF7Encoding.GetByteCount]chars!=null");
+ Debug.Assert(count >=0, "[UTF7Encoding.GetByteCount]count >=0");
// Just call GetBytes with bytes == null
return GetBytes(chars, count, null, 0, baseEncoder);
}
- [System.Security.SecurityCritical] // auto-generated
internal override unsafe int GetBytes(char* chars, int charCount,
byte* bytes, int byteCount, EncoderNLS baseEncoder)
{
- Contract.Assert(byteCount >=0, "[UTF7Encoding.GetBytes]byteCount >=0");
- Contract.Assert(chars!=null, "[UTF7Encoding.GetBytes]chars!=null");
- Contract.Assert(charCount >=0, "[UTF7Encoding.GetBytes]charCount >=0");
+ Debug.Assert(byteCount >=0, "[UTF7Encoding.GetBytes]byteCount >=0");
+ Debug.Assert(chars!=null, "[UTF7Encoding.GetBytes]chars!=null");
+ Debug.Assert(charCount >=0, "[UTF7Encoding.GetBytes]charCount >=0");
// Get encoder info
UTF7Encoding.Encoder encoder = (UTF7Encoding.Encoder)baseEncoder;
return buffer.Count;
}
- [System.Security.SecurityCritical] // auto-generated
internal override unsafe int GetCharCount(byte* bytes, int count, DecoderNLS baseDecoder)
{
- Contract.Assert(count >=0, "[UTF7Encoding.GetCharCount]count >=0");
- Contract.Assert(bytes!=null, "[UTF7Encoding.GetCharCount]bytes!=null");
+ Debug.Assert(count >=0, "[UTF7Encoding.GetCharCount]count >=0");
+ Debug.Assert(bytes!=null, "[UTF7Encoding.GetCharCount]bytes!=null");
// Just call GetChars with null char* to do counting
return GetChars(bytes, count, null, 0, baseDecoder);
}
- [System.Security.SecurityCritical] // auto-generated
internal override unsafe int GetChars(byte* bytes, int byteCount,
char* chars, int charCount, DecoderNLS baseDecoder)
{
- Contract.Assert(byteCount >=0, "[UTF7Encoding.GetChars]byteCount >=0");
- Contract.Assert(bytes!=null, "[UTF7Encoding.GetChars]bytes!=null");
- Contract.Assert(charCount >=0, "[UTF7Encoding.GetChars]charCount >=0");
+ Debug.Assert(byteCount >=0, "[UTF7Encoding.GetChars]byteCount >=0");
+ Debug.Assert(bytes!=null, "[UTF7Encoding.GetChars]bytes!=null");
+ Debug.Assert(charCount >=0, "[UTF7Encoding.GetChars]charCount >=0");
// Might use a decoder
UTF7Encoding.Decoder decoder = (UTF7Encoding.Decoder) baseDecoder;
bitCount = decoder.bitCount;
firstByte = decoder.firstByte;
- Contract.Assert(firstByte == false || decoder.bitCount <= 0,
+ Debug.Assert(firstByte == false || decoder.bitCount <= 0,
"[UTF7Encoding.GetChars]If remembered bits, then first byte flag shouldn't be set");
}
}
// ISerializable implementation, get data for this object
- [System.Security.SecurityCritical] // auto-generated_required
void ISerializable.GetObjectData(SerializationInfo info, StreamingContext context)
{
// Any info?
}
// ISerializable implementation, get data for this object
- [System.Security.SecurityCritical] // auto-generated_required
void ISerializable.GetObjectData(SerializationInfo info, StreamingContext context)
{
// Any info?
public override bool Fallback(byte[] bytesUnknown, int index)
{
// We expect no previous fallback in our buffer
- Contract.Assert(iCount < 0, "[DecoderUTF7FallbackBuffer.Fallback] Can't have recursive fallbacks");
- Contract.Assert(bytesUnknown.Length == 1, "[DecoderUTF7FallbackBuffer.Fallback] Only possible fallback case should be 1 unknown byte");
+ Debug.Assert(iCount < 0, "[DecoderUTF7FallbackBuffer.Fallback] Can't have recursive fallbacks");
+ Debug.Assert(bytesUnknown.Length == 1, "[DecoderUTF7FallbackBuffer.Fallback] Only possible fallback case should be 1 unknown byte");
// Go ahead and get our fallback
cFallback = (char)bytesUnknown[0];
}
// Clear the buffer
- [System.Security.SecuritySafeCritical] // overrides public transparent member
public override unsafe void Reset()
{
iCount = -1;
}
// This version just counts the fallback and doesn't actually copy anything.
- [System.Security.SecurityCritical] // auto-generated
internal unsafe override int InternalFallback(byte[] bytes, byte* pBytes)
// Right now this has both bytes and bytes[], since we might have extra bytes, hence the
// array, and we might need the index, hence the byte*
{
// We expect no previous fallback in our buffer
- Contract.Assert(iCount < 0, "[DecoderUTF7FallbackBuffer.InternalFallback] Can't have recursive fallbacks");
+ Debug.Assert(iCount < 0, "[DecoderUTF7FallbackBuffer.InternalFallback] Can't have recursive fallbacks");
if (bytes.Length != 1)
{
throw new ArgumentException(Environment.GetResourceString("Argument_InvalidCharSequenceNoIndex"));
using System.Globalization;
using System.Runtime.Serialization;
using System.Security.Permissions;
+ using System.Diagnostics;
using System.Diagnostics.Contracts;
// Encodes text into and out of UTF-8. UTF-8 is a way of writing
return EncodingForwarder.GetByteCount(this, chars);
}
- [System.Security.SecurityCritical] // auto-generated
[CLSCompliant(false)]
[System.Runtime.InteropServices.ComVisible(false)]
public override unsafe int GetByteCount(char* chars, int count)
return EncodingForwarder.GetBytes(this, chars, charIndex, charCount, bytes, byteIndex);
}
- [System.Security.SecurityCritical] // auto-generated
[CLSCompliant(false)]
[System.Runtime.InteropServices.ComVisible(false)]
public override unsafe int GetBytes(char* chars, int charCount, byte* bytes, int byteCount)
return EncodingForwarder.GetCharCount(this, bytes, index, count);
}
- [System.Security.SecurityCritical] // auto-generated
[CLSCompliant(false)]
[System.Runtime.InteropServices.ComVisible(false)]
public override unsafe int GetCharCount(byte* bytes, int count)
return EncodingForwarder.GetChars(this, bytes, byteIndex, byteCount, chars, charIndex);
}
- [System.Security.SecurityCritical] // auto-generated
[CLSCompliant(false)]
[System.Runtime.InteropServices.ComVisible(false)]
public unsafe override int GetChars(byte* bytes, int byteCount, char* chars, int charCount)
// To simplify maintenance, the structure of GetByteCount and GetBytes should be
// kept the same as much as possible
- [System.Security.SecurityCritical] // auto-generated
internal override unsafe int GetByteCount(char *chars, int count, EncoderNLS baseEncoder)
{
// For fallback we may need a fallback buffer.
} else {
// Case of surrogates in the fallback.
if (fallbackBuffer != null && fallbackBuffer.bFallingBack) {
- Contract.Assert(ch >= 0xD800 && ch <= 0xDBFF,
+ Debug.Assert(ch >= 0xD800 && ch <= 0xDBFF,
"[UTF8Encoding.GetBytes]expected high surrogate, not 0x" + ((int)ch).ToString("X4", CultureInfo.InvariantCulture));
ch = fallbackBuffer.InternalGetNextChar();
}
if (ch > 0) {
- Contract.Assert(ch >= 0xD800 && ch <= 0xDBFF,
+ Debug.Assert(ch >= 0xD800 && ch <= 0xDBFF,
"[UTF8Encoding.GetBytes]expected high surrogate, not 0x" + ((int)ch).ToString("X4", CultureInfo.InvariantCulture));
// use separate helper variables for local contexts so that the jit optimizations
}
#endif
- Contract.Assert(fallbackBuffer == null || fallbackBuffer.Remaining == 0,
+ Debug.Assert(fallbackBuffer == null || fallbackBuffer.Remaining == 0,
"[UTF8Encoding.GetByteCount]Expected Empty fallback buffer");
return byteCount;
// diffs two char pointers using unsigned arithmetic. The unsigned arithmetic
// is good enough for us, and it tends to generate better code than the signed
// arithmetic generated by default
- [System.Security.SecurityCritical] // auto-generated
unsafe private static int PtrDiff(char *a, char* b)
{
return (int)(((uint)((byte*)a - (byte*)b)) >> 1);
}
// byte* flavor just for parity
- [System.Security.SecurityCritical] // auto-generated
unsafe private static int PtrDiff(byte* a, byte* b)
{
return (int)(a - b);
// Our workhorse
// Note: We ignore mismatched surrogates, unless the exception flag is set in which case we throw
- [System.Security.SecurityCritical] // auto-generated
internal override unsafe int GetBytes(char* chars, int charCount,
byte* bytes, int byteCount, EncoderNLS baseEncoder)
{
- Contract.Assert(chars!=null, "[UTF8Encoding.GetBytes]chars!=null");
- Contract.Assert(byteCount >=0, "[UTF8Encoding.GetBytes]byteCount >=0");
- Contract.Assert(charCount >=0, "[UTF8Encoding.GetBytes]charCount >=0");
- Contract.Assert(bytes!=null, "[UTF8Encoding.GetBytes]bytes!=null");
+ Debug.Assert(chars!=null, "[UTF8Encoding.GetBytes]chars!=null");
+ Debug.Assert(byteCount >=0, "[UTF8Encoding.GetBytes]byteCount >=0");
+ Debug.Assert(charCount >=0, "[UTF8Encoding.GetBytes]charCount >=0");
+ Debug.Assert(bytes!=null, "[UTF8Encoding.GetBytes]bytes!=null");
UTF8Encoder encoder = null;
} else {
// Case of leftover surrogates in the fallback buffer
if (fallbackBuffer != null && fallbackBuffer.bFallingBack) {
- Contract.Assert(ch >= 0xD800 && ch <= 0xDBFF,
+ Debug.Assert(ch >= 0xD800 && ch <= 0xDBFF,
"[UTF8Encoding.GetBytes]expected high surrogate, not 0x" + ((int)ch).ToString("X4", CultureInfo.InvariantCulture));
int cha = ch;
if (ch > 0) {
// We have a high surrogate left over from a previous loop.
- Contract.Assert(ch >= 0xD800 && ch <= 0xDBFF,
+ Debug.Assert(ch >= 0xD800 && ch <= 0xDBFF,
"[UTF8Encoding.GetBytes]expected high surrogate, not 0x" + ((int)ch).ToString("X4", CultureInfo.InvariantCulture));
// use separate helper variables for local contexts so that the jit optimizations
if (ch > 0xFFFF)
pSrc--; // Was surrogate, didn't use 2nd part either
}
- Contract.Assert(pSrc >= chars || pTarget == bytes,
+ Debug.Assert(pSrc >= chars || pTarget == bytes,
"[UTF8Encoding.GetBytes]Expected pSrc to be within buffer or to throw with insufficient room.");
ThrowBytesOverflow(encoder, pTarget == bytes); // Throw if we must
ch = 0; // Nothing left over (we backed up to start of pair if supplimentary)
pTarget++;
}
- Contract.Assert(pTarget <= pAllocatedBufferEnd, "[UTF8Encoding.GetBytes]pTarget <= pAllocatedBufferEnd");
+ Debug.Assert(pTarget <= pAllocatedBufferEnd, "[UTF8Encoding.GetBytes]pTarget <= pAllocatedBufferEnd");
#endif // FASTLOOP
// Do we have to set the encoder bytes?
if (encoder != null)
{
- Contract.Assert(!encoder.MustFlush || ch == 0,
+ Debug.Assert(!encoder.MustFlush || ch == 0,
"[UTF8Encoding.GetBytes] Expected no mustflush or 0 leftover ch " + ch.ToString("X2", CultureInfo.InvariantCulture));
encoder.surrogateChar = ch;
encoder.m_charsUsed = (int)(pSrc - chars);
}
- Contract.Assert(fallbackBuffer == null || fallbackBuffer.Remaining == 0 ||
+ Debug.Assert(fallbackBuffer == null || fallbackBuffer.Remaining == 0 ||
baseEncoder == null || !baseEncoder.m_throwOnOverflow,
"[UTF8Encoding.GetBytes]Expected empty fallback buffer if not converting");
//
// To simplify maintenance, the structure of GetCharCount and GetChars should be
// kept the same as much as possible
- [System.Security.SecurityCritical] // auto-generated
internal override unsafe int GetCharCount(byte* bytes, int count, DecoderNLS baseDecoder)
{
- Contract.Assert(count >=0, "[UTF8Encoding.GetCharCount]count >=0");
- Contract.Assert(bytes!=null, "[UTF8Encoding.GetCharCount]bytes!=null");
+ Debug.Assert(count >=0, "[UTF8Encoding.GetCharCount]count >=0");
+ Debug.Assert(bytes!=null, "[UTF8Encoding.GetCharCount]bytes!=null");
// Initialize stuff
byte *pSrc = bytes;
// Shouldn't have anything in fallback buffer for GetCharCount
// (don't have to check m_throwOnOverflow for count)
- Contract.Assert(!decoder.InternalHasFallbackBuffer || decoder.FallbackBuffer.Remaining == 0,
+ Debug.Assert(!decoder.InternalHasFallbackBuffer || decoder.FallbackBuffer.Remaining == 0,
"[UTF8Encoding.GetCharCount]Expected empty fallback buffer at start");
}
ch = (ch << 6) | (cha & 0x3F);
if ((ch & FinalByte) == 0) {
- Contract.Assert( (ch & (SupplimentarySeq | ThreeByteSeq)) != 0,
+ Debug.Assert( (ch & (SupplimentarySeq | ThreeByteSeq)) != 0,
"[UTF8Encoding.GetChars]Invariant volation");
if ((ch & SupplimentarySeq) != 0) {
// Shouldn't have anything in fallback buffer for GetCharCount
// (don't have to check m_throwOnOverflow for count)
- Contract.Assert(fallback == null || fallback.Remaining == 0,
+ Debug.Assert(fallback == null || fallback.Remaining == 0,
"[UTF8Encoding.GetCharCount]Expected empty fallback buffer at end");
return charCount;
//
// To simplify maintenance, the structure of GetCharCount and GetChars should be
// kept the same as much as possible
- [System.Security.SecurityCritical] // auto-generated
internal override unsafe int GetChars(byte* bytes, int byteCount,
char* chars, int charCount, DecoderNLS baseDecoder)
{
- Contract.Assert(chars!=null, "[UTF8Encoding.GetChars]chars!=null");
- Contract.Assert(byteCount >=0, "[UTF8Encoding.GetChars]count >=0");
- Contract.Assert(charCount >=0, "[UTF8Encoding.GetChars]charCount >=0");
- Contract.Assert(bytes!=null, "[UTF8Encoding.GetChars]bytes!=null");
+ Debug.Assert(chars!=null, "[UTF8Encoding.GetChars]chars!=null");
+ Debug.Assert(byteCount >=0, "[UTF8Encoding.GetChars]count >=0");
+ Debug.Assert(charCount >=0, "[UTF8Encoding.GetChars]charCount >=0");
+ Debug.Assert(bytes!=null, "[UTF8Encoding.GetChars]bytes!=null");
byte *pSrc = bytes;
char *pTarget = chars;
// Shouldn't have anything in fallback buffer for GetChars
// (don't have to check m_throwOnOverflow for chars, we always use all or none so always should be empty)
- Contract.Assert(!decoder.InternalHasFallbackBuffer || decoder.FallbackBuffer.Remaining == 0,
+ Debug.Assert(!decoder.InternalHasFallbackBuffer || decoder.FallbackBuffer.Remaining == 0,
"[UTF8Encoding.GetChars]Expected empty fallback buffer at start");
}
if ((ch & FinalByte) == 0) {
// Not at last byte yet
- Contract.Assert( (ch & (SupplimentarySeq | ThreeByteSeq)) != 0,
+ Debug.Assert( (ch & (SupplimentarySeq | ThreeByteSeq)) != 0,
"[UTF8Encoding.GetChars]Invariant volation");
if ((ch & SupplimentarySeq) != 0) {
{
// Ran out of buffer space
// Need to throw an exception?
- Contract.Assert(pSrc >= bytes || pTarget == chars,
+ Debug.Assert(pSrc >= bytes || pTarget == chars,
"[UTF8Encoding.GetChars]Expected to throw or remain in byte buffer after fallback");
fallback.InternalReset();
ThrowCharsOverflow(baseDecoder, pTarget == chars);
ch = 0;
break;
}
- Contract.Assert(pSrc >= bytes,
+ Debug.Assert(pSrc >= bytes,
"[UTF8Encoding.GetChars]Expected invalid byte sequence to have remained within the byte array");
ch = 0;
continue;
// Throw that we don't have enough room (pSrc could be < chars if we had started to process
// a 4 byte sequence alredy)
- Contract.Assert(pSrc >= bytes || pTarget == chars,
+ Debug.Assert(pSrc >= bytes || pTarget == chars,
"[UTF8Encoding.GetChars]Expected pSrc to be within input buffer or throw due to no output]");
ThrowCharsOverflow(baseDecoder, pTarget == chars);
}
#endif // FASTLOOP
- Contract.Assert(pTarget <= pAllocatedBufferEnd, "[UTF8Encoding.GetChars]pTarget <= pAllocatedBufferEnd");
+ Debug.Assert(pTarget <= pAllocatedBufferEnd, "[UTF8Encoding.GetChars]pTarget <= pAllocatedBufferEnd");
// no pending bits at this point
ch = 0;
// This'll back us up the appropriate # of bytes if we didn't get anywhere
if (!FallbackInvalidByteSequence(ref pSrc, ch, fallback, ref pTarget))
{
- Contract.Assert(pSrc >= bytes || pTarget == chars,
+ Debug.Assert(pSrc >= bytes || pTarget == chars,
"[UTF8Encoding.GetChars]Expected to throw or remain in byte buffer while flushing");
// Ran out of buffer space
fallback.InternalReset();
ThrowCharsOverflow(baseDecoder, pTarget == chars);
}
- Contract.Assert(pSrc >= bytes,
+ Debug.Assert(pSrc >= bytes,
"[UTF8Encoding.GetChars]Expected flushing invalid byte sequence to have remained within the byte array");
ch = 0;
}
// If we're storing flush data we expect all bits to be used or else
// we're stuck in the middle of a conversion
- Contract.Assert(!baseDecoder.MustFlush || ch == 0 || !baseDecoder.m_throwOnOverflow,
+ Debug.Assert(!baseDecoder.MustFlush || ch == 0 || !baseDecoder.m_throwOnOverflow,
"[UTF8Encoding.GetChars]Expected no must flush or no left over bits or no throw on overflow.");
// Remember our leftover bits.
// Shouldn't have anything in fallback buffer for GetChars
// (don't have to check m_throwOnOverflow for chars)
- Contract.Assert(fallback == null || fallback.Remaining == 0,
+ Debug.Assert(fallback == null || fallback.Remaining == 0,
"[UTF8Encoding.GetChars]Expected empty fallback buffer at end");
return PtrDiff(pTarget, chars);
// During GetChars we had an invalid byte sequence
// pSrc is backed up to the start of the bad sequence if we didn't have room to
// fall it back. Otherwise pSrc remains wher it is.
- [System.Security.SecurityCritical] // auto-generated
private unsafe bool FallbackInvalidByteSequence(
ref byte* pSrc, int ch, DecoderFallbackBuffer fallback, ref char* pTarget)
{
// During GetCharCount we had an invalid byte sequence
// pSrc is used to find the index that points to the invalid bytes,
// however the byte[] contains the fallback bytes (in case the index is -1)
- [System.Security.SecurityCritical] // auto-generated
private unsafe int FallbackInvalidByteSequence(
byte* pSrc, int ch, DecoderFallbackBuffer fallback)
{
// Note that some of these bytes may have come from a previous fallback, so we cannot
// just decrement the pointer and use the values we read. In those cases we have
// to regenerate the original values.
- [System.Security.SecurityCritical] // auto-generated
private unsafe byte[] GetBytesUnknown(ref byte* pSrc, int ch)
{
// Get our byte[]
}
// ISerializable implementation, get data for this object
- [System.Security.SecurityCritical] // auto-generated_required
void ISerializable.GetObjectData(SerializationInfo info, StreamingContext context)
{
// Any info?
}
// ISerializable implementation, get data for this object
- [System.Security.SecurityCritical] // auto-generated_required
void ISerializable.GetObjectData(SerializationInfo info, StreamingContext context)
{
// Any info?
using System.Globalization;
using System.Runtime.Serialization;
using System.Security.Permissions;
+ using System.Diagnostics;
using System.Diagnostics.Contracts;
return EncodingForwarder.GetByteCount(this, s);
}
- [System.Security.SecurityCritical] // auto-generated
[CLSCompliant(false)]
[System.Runtime.InteropServices.ComVisible(false)]
public override unsafe int GetByteCount(char* chars, int count)
return EncodingForwarder.GetBytes(this, chars, charIndex, charCount, bytes, byteIndex);
}
- [System.Security.SecurityCritical] // auto-generated
[CLSCompliant(false)]
[System.Runtime.InteropServices.ComVisible(false)]
public override unsafe int GetBytes(char* chars, int charCount, byte* bytes, int byteCount)
return EncodingForwarder.GetCharCount(this, bytes, index, count);
}
- [System.Security.SecurityCritical] // auto-generated
[CLSCompliant(false)]
[System.Runtime.InteropServices.ComVisible(false)]
public override unsafe int GetCharCount(byte* bytes, int count)
return EncodingForwarder.GetChars(this, bytes, byteIndex, byteCount, chars, charIndex);
}
- [System.Security.SecurityCritical] // auto-generated
[CLSCompliant(false)]
[System.Runtime.InteropServices.ComVisible(false)]
public unsafe override int GetChars(byte* bytes, int byteCount, char* chars, int charCount)
// End of overridden methods which use EncodingForwarder
- [System.Security.SecurityCritical] // auto-generated
internal override unsafe int GetByteCount(char* chars, int count, EncoderNLS encoder)
{
- Contract.Assert(chars!=null, "[UnicodeEncoding.GetByteCount]chars!=null");
- Contract.Assert(count >= 0, "[UnicodeEncoding.GetByteCount]count >=0");
+ Debug.Assert(chars!=null, "[UnicodeEncoding.GetByteCount]chars!=null");
+ Debug.Assert(count >= 0, "[UnicodeEncoding.GetByteCount]count >=0");
// Start by assuming each char gets 2 bytes
int byteCount = count << 1;
// Unwind the current character, this should be safe because we
// don't have leftover data in the fallback, so chars must have
// advanced already.
- Contract.Assert(chars > charStart,
+ Debug.Assert(chars > charStart,
"[UnicodeEncoding.GetByteCount]Expected chars to have advanced in unexpected high surrogate");
chars--;
// Rewind the current character, fallback previous character.
// this should be safe because we don't have leftover data in the
// fallback, so chars must have advanced already.
- Contract.Assert(chars > charStart,
+ Debug.Assert(chars > charStart,
"[UnicodeEncoding.GetByteCount]Expected chars to have advanced when expected low surrogate");
chars--;
// Shouldn't have anything in fallback buffer for GetByteCount
// (don't have to check m_throwOnOverflow for count)
- Contract.Assert(fallbackBuffer == null || fallbackBuffer.Remaining == 0,
+ Debug.Assert(fallbackBuffer == null || fallbackBuffer.Remaining == 0,
"[UnicodeEncoding.GetByteCount]Expected empty fallback buffer at end");
// Don't remember fallbackBuffer.encoder for counting
return byteCount;
}
- [System.Security.SecurityCritical] // auto-generated
internal override unsafe int GetBytes(char* chars, int charCount,
byte* bytes, int byteCount, EncoderNLS encoder)
{
- Contract.Assert(chars!=null, "[UnicodeEncoding.GetBytes]chars!=null");
- Contract.Assert(byteCount >=0, "[UnicodeEncoding.GetBytes]byteCount >=0");
- Contract.Assert(charCount >=0, "[UnicodeEncoding.GetBytes]charCount >=0");
- Contract.Assert(bytes!=null, "[UnicodeEncoding.GetBytes]bytes!=null");
+ Debug.Assert(chars!=null, "[UnicodeEncoding.GetBytes]chars!=null");
+ Debug.Assert(byteCount >=0, "[UnicodeEncoding.GetBytes]byteCount >=0");
+ Debug.Assert(charCount >=0, "[UnicodeEncoding.GetBytes]charCount >=0");
+ Debug.Assert(bytes!=null, "[UnicodeEncoding.GetBytes]bytes!=null");
char charLeftOver = (char)0;
char ch;
// Unwind the current character, this should be safe because we
// don't have leftover data in the fallback, so chars must have
// advanced already.
- Contract.Assert(chars > charStart,
+ Debug.Assert(chars > charStart,
"[UnicodeEncoding.GetBytes]Expected chars to have advanced in unexpected high surrogate");
chars--;
{
// If we don't have enough room, then either we should've advanced a while
// or we should have bytes==byteStart and throw below
- Contract.Assert(chars > charStart + 1 || bytes == byteStart,
+ Debug.Assert(chars > charStart + 1 || bytes == byteStart,
"[UnicodeEncoding.GetBytes]Expected chars to have when no room to add surrogate pair");
chars-=2; // Didn't use either surrogate
}
// Rewind the current character, fallback previous character.
// this should be safe because we don't have leftover data in the
// fallback, so chars must have advanced already.
- Contract.Assert(chars > charStart,
+ Debug.Assert(chars > charStart,
"[UnicodeEncoding.GetBytes]Expected chars to have advanced after expecting low surrogate");
chars--;
{
// Lonely charLeftOver (from previous call) would've been caught up above,
// so this must be a case where we've already read an input char.
- Contract.Assert(chars > charStart,
+ Debug.Assert(chars > charStart,
"[UnicodeEncoding.GetBytes]Expected chars to have advanced for failed fallback");
chars--; // Not using this char
}
// Remember charLeftOver if we must, or clear it if we're flushing
// (charLeftOver should be 0 if we're flushing)
- Contract.Assert((encoder != null && !encoder.MustFlush) || charLeftOver == (char)0,
+ Debug.Assert((encoder != null && !encoder.MustFlush) || charLeftOver == (char)0,
"[UnicodeEncoding.GetBytes] Expected no left over characters if flushing");
- Contract.Assert(fallbackBuffer == null || fallbackBuffer.Remaining == 0 ||
+ Debug.Assert(fallbackBuffer == null || fallbackBuffer.Remaining == 0 ||
encoder == null || !encoder.m_throwOnOverflow,
"[UnicodeEncoding.GetBytes]Expected empty fallback buffer if not converting");
return (int)(bytes - byteStart);
}
- [System.Security.SecurityCritical] // auto-generated
internal override unsafe int GetCharCount(byte* bytes, int count, DecoderNLS baseDecoder)
{
- Contract.Assert(bytes!=null, "[UnicodeEncoding.GetCharCount]bytes!=null");
- Contract.Assert(count >= 0, "[UnicodeEncoding.GetCharCount]count >=0");
+ Debug.Assert(bytes!=null, "[UnicodeEncoding.GetCharCount]bytes!=null");
+ Debug.Assert(count >= 0, "[UnicodeEncoding.GetCharCount]count >=0");
UnicodeEncoding.Decoder decoder = (UnicodeEncoding.Decoder)baseDecoder;
// Shouldn't have anything in fallback buffer for GetCharCount
// (don't have to check m_throwOnOverflow for count)
- Contract.Assert(!decoder.InternalHasFallbackBuffer || decoder.FallbackBuffer.Remaining == 0,
+ Debug.Assert(!decoder.InternalHasFallbackBuffer || decoder.FallbackBuffer.Remaining == 0,
"[UnicodeEncoding.GetCharCount]Expected empty fallback buffer at start");
}
// Shouldn't have anything in fallback buffer for GetCharCount
// (don't have to check m_throwOnOverflow for count)
- Contract.Assert(fallbackBuffer == null || fallbackBuffer.Remaining == 0,
+ Debug.Assert(fallbackBuffer == null || fallbackBuffer.Remaining == 0,
"[UnicodeEncoding.GetCharCount]Expected empty fallback buffer at end");
return charCount;
}
- [System.Security.SecurityCritical] // auto-generated
internal override unsafe int GetChars(byte* bytes, int byteCount,
char* chars, int charCount, DecoderNLS baseDecoder )
{
- Contract.Assert(chars!=null, "[UnicodeEncoding.GetChars]chars!=null");
- Contract.Assert(byteCount >=0, "[UnicodeEncoding.GetChars]byteCount >=0");
- Contract.Assert(charCount >=0, "[UnicodeEncoding.GetChars]charCount >=0");
- Contract.Assert(bytes!=null, "[UnicodeEncoding.GetChars]bytes!=null");
+ Debug.Assert(chars!=null, "[UnicodeEncoding.GetChars]chars!=null");
+ Debug.Assert(byteCount >=0, "[UnicodeEncoding.GetChars]byteCount >=0");
+ Debug.Assert(charCount >=0, "[UnicodeEncoding.GetChars]charCount >=0");
+ Debug.Assert(bytes!=null, "[UnicodeEncoding.GetChars]bytes!=null");
UnicodeEncoding.Decoder decoder = (UnicodeEncoding.Decoder)baseDecoder;
// Shouldn't have anything in fallback buffer for GetChars
// (don't have to check m_throwOnOverflow for chars)
- Contract.Assert(!decoder.InternalHasFallbackBuffer || decoder.FallbackBuffer.Remaining == 0,
+ Debug.Assert(!decoder.InternalHasFallbackBuffer || decoder.FallbackBuffer.Remaining == 0,
"[UnicodeEncoding.GetChars]Expected empty fallback buffer at start");
}
{
// couldn't fall back lonely surrogate
// We either advanced bytes or chars should == charStart and throw below
- Contract.Assert(bytes >= byteStart + 2 || chars == charStart,
+ Debug.Assert(bytes >= byteStart + 2 || chars == charStart,
"[UnicodeEncoding.GetChars]Expected bytes to have advanced or no output (bad surrogate)");
bytes-=2; // didn't use these 2 bytes
fallbackBuffer.InternalReset();
{
// couldn't fall back lonely surrogate
// We either advanced bytes or chars should == charStart and throw below
- Contract.Assert(bytes >= byteStart + 2 || chars == charStart,
+ Debug.Assert(bytes >= byteStart + 2 || chars == charStart,
"[UnicodeEncoding.GetChars]Expected bytes to have advanced or no output (lonely surrogate)");
bytes-=2; // didn't use these 2 bytes
fallbackBuffer.InternalReset();
{
// couldn't find room for this surrogate pair
// We either advanced bytes or chars should == charStart and throw below
- Contract.Assert(bytes >= byteStart + 2 || chars == charStart,
+ Debug.Assert(bytes >= byteStart + 2 || chars == charStart,
"[UnicodeEncoding.GetChars]Expected bytes to have advanced or no output (surrogate pair)");
bytes-=2; // didn't use these 2 bytes
ThrowCharsOverflow(decoder, chars == charStart);// Might throw, if no chars output
{
// couldn't fall back high surrogate, or char that would be next
// We either advanced bytes or chars should == charStart and throw below
- Contract.Assert(bytes >= byteStart + 2 || chars == charStart,
+ Debug.Assert(bytes >= byteStart + 2 || chars == charStart,
"[UnicodeEncoding.GetChars]Expected bytes to have advanced or no output (no low surrogate)");
bytes-=2; // didn't use these 2 bytes
fallbackBuffer.InternalReset();
{
// 2 bytes couldn't fall back
// We either advanced bytes or chars should == charStart and throw below
- Contract.Assert(bytes >= byteStart + 2 || chars == charStart,
+ Debug.Assert(bytes >= byteStart + 2 || chars == charStart,
"[UnicodeEncoding.GetChars]Expected bytes to have advanced or no output (normal)");
bytes-=2; // didn't use these bytes
ThrowCharsOverflow(decoder, chars == charStart);// Might throw, if no chars output
{
// 2 bytes couldn't fall back
// We either advanced bytes or chars should == charStart and throw below
- Contract.Assert(bytes >= byteStart + 2 || chars == charStart,
+ Debug.Assert(bytes >= byteStart + 2 || chars == charStart,
"[UnicodeEncoding.GetChars]Expected bytes to have advanced or no output (decoder)");
bytes-=2; // didn't use these bytes
if (lastByte >= 0)
// Remember our decoder if we must
if (decoder != null)
{
- Contract.Assert((decoder.MustFlush == false) || ((lastChar == (char)0) && (lastByte == -1)),
+ Debug.Assert((decoder.MustFlush == false) || ((lastChar == (char)0) && (lastByte == -1)),
"[UnicodeEncoding.GetChars] Expected no left over chars or bytes if flushing"
// + " " + ((int)lastChar).ToString("X4") + " " + lastByte.ToString("X2")
);
// Shouldn't have anything in fallback buffer for GetChars
// (don't have to check m_throwOnOverflow for count or chars)
- Contract.Assert(fallbackBuffer == null || fallbackBuffer.Remaining == 0,
+ Debug.Assert(fallbackBuffer == null || fallbackBuffer.Remaining == 0,
"[UnicodeEncoding.GetChars]Expected empty fallback buffer at end");
return (int)(chars - charStart);
}
// ISerializable implementation, get data for this object
- [System.Security.SecurityCritical] // auto-generated_required
void ISerializable.GetObjectData(SerializationInfo info, StreamingContext context)
{
// Any info?
using System;
using System.Collections.Generic;
+using System.Diagnostics;
using System.Diagnostics.Contracts;
using System.Security;
//
public sealed class AsyncLocal<T> : IAsyncLocal
{
- [SecurityCritical] // critical because this action will terminate the process if it throws.
private readonly Action<AsyncLocalValueChangedArgs<T>> m_valueChangedHandler;
//
// Constructs an AsyncLocal<T> with a delegate that is called whenever the current value changes
// on any thread.
//
- [SecurityCritical]
public AsyncLocal(Action<AsyncLocalValueChangedArgs<T>> valueChangedHandler)
{
m_valueChangedHandler = valueChangedHandler;
public T Value
{
- [SecuritySafeCritical]
get
{
object obj = ExecutionContext.GetLocalValue(this);
return (obj == null) ? default(T) : (T)obj;
}
- [SecuritySafeCritical]
set
{
ExecutionContext.SetLocalValue(this, value, m_valueChangedHandler != null);
}
}
- [SecurityCritical]
void IAsyncLocal.OnValueChanged(object previousValueObj, object currentValueObj, bool contextChanged)
{
- Contract.Assert(m_valueChangedHandler != null);
+ Debug.Assert(m_valueChangedHandler != null);
T previousValue = previousValueObj == null ? default(T) : (T)previousValueObj;
T currentValue = currentValueObj == null ? default(T) : (T)currentValueObj;
m_valueChangedHandler(new AsyncLocalValueChangedArgs<T>(previousValue, currentValue, contextChanged));
//
internal interface IAsyncLocal
{
- [SecurityCritical]
void OnValueChanged(object previousValue, object currentValue, bool contextChanged);
}
multi.UnsafeStore(index++, pair.Key, pair.Value);
}
}
- Contract.Assert(index == MultiElementAsyncLocalValueMap.MaxMultiElements);
+ Debug.Assert(index == MultiElementAsyncLocalValueMap.MaxMultiElements);
return multi;
}
else
map[pair.Key] = pair.Value;
}
}
- Contract.Assert(map.Count == count - 1);
+ Debug.Assert(map.Count == count - 1);
return map;
}
}
using System.Security.Permissions;
using System.Runtime.InteropServices;
- [HostProtection(Synchronization=true, ExternalThreading=true)]
[System.Runtime.InteropServices.ComVisible(true)]
public sealed class AutoResetEvent : EventWaitHandle
{
#pragma warning disable 0420 // turn off 'a reference to a volatile field will not be treated as volatile' during CAS.
using System;
-using System.Diagnostics;
using System.Runtime.InteropServices;
using System.Security.Permissions;
+using System.Diagnostics;
using System.Diagnostics.Contracts;
using System.Runtime;
using System.Runtime.CompilerServices;
/// </para>
/// </remarks>
[ComVisible(false)]
- [HostProtection(Synchronization = true, ExternalThreading = true)]
[DebuggerDisplay("IsCancellationRequested = {IsCancellationRequested}")]
public struct CancellationToken
{
private static void ActionToActionObjShunt(object obj)
{
Action action = obj as Action;
- Contract.Assert(action != null, "Expected an Action here");
+ Debug.Assert(action != null, "Expected an Action here");
action();
}
}
// the real work..
- [SecuritySafeCritical]
[MethodImpl(MethodImplOptions.NoInlining)]
private CancellationTokenRegistration Register(Action<Object> callback, Object state, bool useSynchronizationContext, bool useExecutionContext)
{
/// <remarks>
/// To unregister a callback, dispose the corresponding Registration instance.
/// </remarks>
- [HostProtection(Synchronization = true, ExternalThreading = true)]
public struct CancellationTokenRegistration : IEquatable<CancellationTokenRegistration>, IDisposable
{
private readonly CancellationCallbackInfo m_callbackInfo;
using System.Collections.Generic;
using System.Runtime.InteropServices;
using System.Security.Permissions;
+using System.Diagnostics;
using System.Diagnostics.Contracts;
using System.Runtime;
/// </para>
/// </remarks>
[ComVisible(false)]
- [HostProtection(Synchronization = true, ExternalThreading = true)]
public class CancellationTokenSource : IDisposable
{
}
// the CancellationToken has already checked that the token is cancelable before calling this method.
- Contract.Assert(CanBeCanceled, "Cannot register for uncancelable token src");
+ Debug.Assert(CanBeCanceled, "Cannot register for uncancelable token src");
// if not canceled, register the event handlers
// if canceled already, run the callback synchronously
// - After transition, no more delegates will be added to the
// - list of handlers, and hence it can be consumed and cleared at leisure by ExecuteCallbackHandlers.
ExecuteCallbackHandlers(throwOnFirstException);
- Contract.Assert(IsCancellationCompleted, "Expected cancellation to have finished");
+ Debug.Assert(IsCancellationCompleted, "Expected cancellation to have finished");
}
}
/// </remarks>
private void ExecuteCallbackHandlers(bool throwOnFirstException)
{
- Contract.Assert(IsCancellationRequested, "ExecuteCallbackHandlers should only be called after setting IsCancellationRequested->true");
- Contract.Assert(ThreadIDExecutingCallbacks != -1, "ThreadIDExecutingCallbacks should have been set.");
+ Debug.Assert(IsCancellationRequested, "ExecuteCallbackHandlers should only be called after setting IsCancellationRequested->true");
+ Debug.Assert(ThreadIDExecutingCallbacks != -1, "ThreadIDExecutingCallbacks should have been set.");
// Design decision: call the delegates in LIFO order so that callbacks fire 'deepest first'.
// This is intended to help with nesting scenarios so that child enlisters cancel before their parents.
var wsc = m_executingCallback as CancellationCallbackInfo.WithSyncContext;
if (wsc != null)
{
- Contract.Assert(wsc.TargetSyncContext != null, "Should only have derived CCI if non-null SyncCtx");
+ Debug.Assert(wsc.TargetSyncContext != null, "Should only have derived CCI if non-null SyncCtx");
wsc.TargetSyncContext.Send(CancellationCallbackCoreWork_OnSyncContext, args);
// CancellationCallbackCoreWork_OnSyncContext may have altered ThreadIDExecutingCallbacks, so reset it.
ThreadIDExecutingCallbacks = Thread.CurrentThread.ManagedThreadId;
if (exceptionList != null)
{
- Contract.Assert(exceptionList.Count > 0, "Expected exception count > 0");
+ Debug.Assert(exceptionList.Count > 0, "Expected exception count > 0");
throw new AggregateException(exceptionList);
}
}
}
// Cached callback delegate that's lazily initialized due to ContextCallback being SecurityCritical
- [SecurityCritical]
private static ContextCallback s_executionContextCallback;
/// <summary>
/// InternalExecuteCallbackSynchronously_GeneralPath
/// This will be called on the target synchronization context, however, we still need to restore the required execution context
/// </summary>
- [SecuritySafeCritical]
internal void ExecuteCallback()
{
if (TargetExecutionContext != null)
// the worker method to actually run the callback
// The signature is such that it can be used as a 'ContextCallback'
- [SecurityCritical]
private static void ExecutionContextCallback(object obj)
{
CancellationCallbackInfo callbackInfo = obj as CancellationCallbackInfo;
- Contract.Assert(callbackInfo != null);
+ Debug.Assert(callbackInfo != null);
callbackInfo.Callback(callbackInfo.StateForCallback);
}
}
start = 0;
curr.m_freeCount--; // Too many free elements; fix up.
}
- Contract.Assert(start >= 0 && start < c, "start is outside of bounds");
+ Debug.Assert(start >= 0 && start < c, "start is outside of bounds");
// Now walk the array until we find a free slot (or reach the end).
for (int i = 0; i < c; i++)
{
// If the slot is null, try to CAS our element into it.
int tryIndex = (start + i) % c;
- Contract.Assert(tryIndex >= 0 && tryIndex < curr.m_elements.Length, "tryIndex is outside of bounds");
+ Debug.Assert(tryIndex >= 0 && tryIndex < curr.m_elements.Length, "tryIndex is outside of bounds");
if (curr.m_elements[tryIndex] == null && Interlocked.CompareExchange(ref curr.m_elements[tryIndex], element, null) == null)
{
internal SparselyPopulatedArrayAddInfo(SparselyPopulatedArrayFragment<T> source, int index)
{
- Contract.Assert(source != null);
- Contract.Assert(index >= 0 && index < source.Length);
+ Debug.Assert(source != null);
+ Debug.Assert(index >= 0 && index < source.Length);
m_source = source;
m_index = index;
}
// =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-
using System;
-using System.Diagnostics;
using System.Security.Permissions;
using System.Runtime.InteropServices;
using System.Threading;
+using System.Diagnostics;
using System.Diagnostics.Contracts;
namespace System.Threading
/// </remarks>
[ComVisible(false)]
[DebuggerDisplay("Initial Count={InitialCount}, Current Count={CurrentCount}")]
- [HostProtection(Synchronization = true, ExternalThreading = true)]
public class CountdownEvent : IDisposable
{
// CountdownEvent is a simple synchronization primitive used for fork/join parallelism. We create a
public bool Signal()
{
ThrowIfDisposed();
- Contract.Assert(m_event != null);
+ Debug.Assert(m_event != null);
if (m_currentCount <= 0)
{
}
ThrowIfDisposed();
- Contract.Assert(m_event != null);
+ Debug.Assert(m_event != null);
int observedCount;
SpinWait spin = new SpinWait();
return true;
}
- Contract.Assert(m_currentCount >= 0, "latch was decremented below zero");
+ Debug.Assert(m_currentCount >= 0, "latch was decremented below zero");
return false;
}
=============================================================================*/
-#if !FEATURE_MACL
namespace System.Security.AccessControl
{
public class EventWaitHandleSecurity
{
}
}
-#endif
namespace System.Threading
{
using System.Security.AccessControl;
using System.Diagnostics.Contracts;
- [HostProtection(Synchronization=true, ExternalThreading=true)]
[ComVisibleAttribute(true)]
public class EventWaitHandle : WaitHandle
{
- [System.Security.SecuritySafeCritical] // auto-generated
public EventWaitHandle(bool initialState, EventResetMode mode) : this(initialState,mode,null) { }
- [System.Security.SecurityCritical] // auto-generated_required
public EventWaitHandle(bool initialState, EventResetMode mode, string name)
{
if(name != null)
SetHandleInternal(_handle);
}
- [System.Security.SecurityCritical] // auto-generated_required
public EventWaitHandle(bool initialState, EventResetMode mode, string name, out bool createdNew)
: this(initialState, mode, name, out createdNew, null)
{
}
- [System.Security.SecurityCritical] // auto-generated_required
public unsafe EventWaitHandle(bool initialState, EventResetMode mode, string name, out bool createdNew, EventWaitHandleSecurity eventSecurity)
{
if(name != null)
}
Contract.EndContractBlock();
Win32Native.SECURITY_ATTRIBUTES secAttrs = null;
-#if FEATURE_MACL
- // For ACL's, get the security descriptor from the EventWaitHandleSecurity.
- if (eventSecurity != null) {
- secAttrs = new Win32Native.SECURITY_ATTRIBUTES();
- secAttrs.nLength = (int)Marshal.SizeOf(secAttrs);
-
- byte[] sd = eventSecurity.GetSecurityDescriptorBinaryForm();
- byte* pSecDescriptor = stackalloc byte[sd.Length];
- Buffer.Memcpy(pSecDescriptor, 0, sd, 0, sd.Length);
- secAttrs.pSecurityDescriptor = pSecDescriptor;
- }
-#endif
SafeWaitHandle _handle = null;
Boolean isManualReset;
SetHandleInternal(_handle);
}
- [System.Security.SecurityCritical] // auto-generated
private EventWaitHandle(SafeWaitHandle handle)
{
SetHandleInternal(handle);
}
- [System.Security.SecurityCritical] // auto-generated_required
public static EventWaitHandle OpenExisting(string name)
{
-#if !FEATURE_MACL
return OpenExisting(name, (EventWaitHandleRights)0);
-#else
- return OpenExisting(name, EventWaitHandleRights.Modify | EventWaitHandleRights.Synchronize);
-#endif
}
- [System.Security.SecurityCritical] // auto-generated_required
public static EventWaitHandle OpenExisting(string name, EventWaitHandleRights rights)
{
EventWaitHandle result;
}
}
- [System.Security.SecurityCritical] // auto-generated_required
public static bool TryOpenExisting(string name, out EventWaitHandle result)
{
-#if !FEATURE_MACL
return OpenExistingWorker(name, (EventWaitHandleRights)0, out result) == OpenExistingResult.Success;
-#else
- return OpenExistingWorker(name, EventWaitHandleRights.Modify | EventWaitHandleRights.Synchronize, out result) == OpenExistingResult.Success;
-#endif
}
- [System.Security.SecurityCritical] // auto-generated_required
public static bool TryOpenExisting(string name, EventWaitHandleRights rights, out EventWaitHandle result)
{
return OpenExistingWorker(name, rights, out result) == OpenExistingResult.Success;
}
- [System.Security.SecurityCritical] // auto-generated_required
private static OpenExistingResult OpenExistingWorker(string name, EventWaitHandleRights rights, out EventWaitHandle result)
{
#if PLATFORM_UNIX
result = null;
-#if FEATURE_MACL
- SafeWaitHandle myHandle = Win32Native.OpenEvent((int) rights, false, name);
-#else
SafeWaitHandle myHandle = Win32Native.OpenEvent(Win32Native.EVENT_MODIFY_STATE | Win32Native.SYNCHRONIZE, false, name);
-#endif
-
+
if (myHandle.IsInvalid)
{
int errorCode = Marshal.GetLastWin32Error();
return OpenExistingResult.Success;
#endif
}
- [System.Security.SecuritySafeCritical] // auto-generated
public bool Reset()
{
bool res = Win32Native.ResetEvent(safeWaitHandle);
__Error.WinIOError();
return res;
}
- [System.Security.SecuritySafeCritical] // auto-generated
public bool Set()
{
bool res = Win32Native.SetEvent(safeWaitHandle);
return res;
}
-
-#if FEATURE_MACL
- [System.Security.SecuritySafeCritical] // auto-generated
- public EventWaitHandleSecurity GetAccessControl()
- {
- return new EventWaitHandleSecurity(safeWaitHandle, AccessControlSections.Access | AccessControlSections.Owner | AccessControlSections.Group);
- }
-
- [System.Security.SecuritySafeCritical] // auto-generated
- public void SetAccessControl(EventWaitHandleSecurity eventSecurity)
- {
- if (eventSecurity == null)
- throw new ArgumentNullException(nameof(eventSecurity));
- Contract.EndContractBlock();
-
- eventSecurity.Persist(safeWaitHandle);
- }
-#endif
}
}
using System.Runtime.InteropServices;
using System.Runtime.CompilerServices;
using System.Runtime.ConstrainedExecution;
+ using System.Diagnostics;
using System.Diagnostics.Contracts;
using System.Diagnostics.CodeAnalysis;
- [System.Security.SecurityCritical] // auto-generated
[System.Runtime.InteropServices.ComVisible(true)]
public delegate void ContextCallback(Object state);
- [SecurityCritical]
internal struct ExecutionContextSwitcher
{
internal ExecutionContext m_ec;
internal void Undo(Thread currentThread)
{
- Contract.Assert(currentThread == Thread.CurrentThread);
+ Debug.Assert(currentThread == Thread.CurrentThread);
// The common case is that these have not changed, so avoid the cost of a write if not needed.
if (currentThread.SynchronizationContext != m_sc)
{
}
- [SecuritySafeCritical]
public static ExecutionContext Capture()
{
ExecutionContext executionContext = Thread.CurrentThread.ExecutionContext;
private ExecutionContext ShallowClone(bool isFlowSuppressed)
{
- Contract.Assert(isFlowSuppressed != m_isFlowSuppressed);
+ Debug.Assert(isFlowSuppressed != m_isFlowSuppressed);
if (!isFlowSuppressed &&
m_localValues == Default.m_localValues &&
return executionContext != null && executionContext.m_isFlowSuppressed;
}
- [SecurityCritical]
[HandleProcessCorruptedStateExceptions]
public static void Run(ExecutionContext executionContext, ContextCallback callback, Object state)
{
ecsw.Undo(currentThread);
}
- [SecurityCritical]
internal static void Restore(Thread currentThread, ExecutionContext executionContext)
{
- Contract.Assert(currentThread == Thread.CurrentThread);
+ Debug.Assert(currentThread == Thread.CurrentThread);
ExecutionContext previous = currentThread.ExecutionContext ?? Default;
currentThread.ExecutionContext = executionContext;
}
}
- [SecurityCritical]
static internal void EstablishCopyOnWriteScope(Thread currentThread, ref ExecutionContextSwitcher ecsw)
{
- Contract.Assert(currentThread == Thread.CurrentThread);
+ Debug.Assert(currentThread == Thread.CurrentThread);
ecsw.m_ec = currentThread.ExecutionContext;
ecsw.m_sc = currentThread.SynchronizationContext;
}
- [SecurityCritical]
[HandleProcessCorruptedStateExceptions]
private static void OnContextChanged(ExecutionContext previous, ExecutionContext current)
{
- Contract.Assert(previous != null);
- Contract.Assert(current != null);
- Contract.Assert(previous != current);
+ Debug.Assert(previous != null);
+ Debug.Assert(current != null);
+ Debug.Assert(previous != current);
foreach (IAsyncLocal local in previous.m_localChangeNotifications)
{
}
}
- [SecurityCritical]
internal static object GetLocalValue(IAsyncLocal local)
{
ExecutionContext current = Thread.CurrentThread.ExecutionContext;
return value;
}
- [SecurityCritical]
internal static void SetLocalValue(IAsyncLocal local, object newValue, bool needChangeNotifications)
{
ExecutionContext current = Thread.CurrentThread.ExecutionContext ?? ExecutionContext.Default;
{
if (hadPreviousValue)
{
- Contract.Assert(Array.IndexOf(newChangeNotifications, local) >= 0);
+ Debug.Assert(Array.IndexOf(newChangeNotifications, local) >= 0);
}
else
{
OptimizeDefaultCase = 0x02,
}
- [SecurityCritical]
internal static ExecutionContext Capture(ref StackCrawlMark stackMark, CaptureOptions captureOptions)
{
return Capture();
}
- [SecuritySafeCritical]
[FriendAccessAllowed]
internal static ExecutionContext FastCapture()
{
return Capture();
}
- [SecurityCritical]
[FriendAccessAllowed]
internal static void Run(ExecutionContext executionContext, ContextCallback callback, Object state, bool preserveSyncCtx)
{
Run(executionContext, callback, state);
}
- [SecurityCritical]
internal bool IsDefaultFTContext(bool ignoreSyncCtx)
{
return this == Default;
}
- [SecuritySafeCritical]
public ExecutionContext CreateCopy()
{
return this; // since CoreCLR's ExecutionContext is immutable, we don't need to create copies.
internal static ExecutionContext PreAllocatedDefault
{
- [SecuritySafeCritical]
get { return ExecutionContext.Default; }
}
internal void Initialize(Thread currentThread)
{
- Contract.Assert(currentThread == Thread.CurrentThread);
+ Debug.Assert(currentThread == Thread.CurrentThread);
_thread = currentThread;
}
[MethodImplAttribute(MethodImplOptions.InternalCall)]
[ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)]
- [System.Security.SecuritySafeCritical]
public static extern int Exchange(ref int location1, int value);
[MethodImplAttribute(MethodImplOptions.InternalCall)]
- [System.Security.SecuritySafeCritical]
public static extern long Exchange(ref long location1, long value);
[MethodImplAttribute(MethodImplOptions.InternalCall)]
- [System.Security.SecuritySafeCritical]
public static extern float Exchange(ref float location1, float value);
[MethodImplAttribute(MethodImplOptions.InternalCall)]
- [System.Security.SecuritySafeCritical]
public static extern double Exchange(ref double location1, double value);
[MethodImplAttribute(MethodImplOptions.InternalCall)]
[ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)]
- [System.Security.SecuritySafeCritical]
public static extern Object Exchange(ref Object location1, Object value);
[MethodImplAttribute(MethodImplOptions.InternalCall)]
[ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)]
- [System.Security.SecuritySafeCritical]
public static extern IntPtr Exchange(ref IntPtr location1, IntPtr value);
[ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)]
[System.Runtime.InteropServices.ComVisible(false)]
- [System.Security.SecuritySafeCritical]
public static T Exchange<T>(ref T location1, T value) where T : class
{
_Exchange(__makeref(location1), __makeref(value));
[MethodImplAttribute(MethodImplOptions.InternalCall)]
[ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)]
- [System.Security.SecuritySafeCritical]
private static extern void _Exchange(TypedReference location1, TypedReference value);
/******************************
[MethodImplAttribute(MethodImplOptions.InternalCall)]
[ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)]
- [System.Security.SecuritySafeCritical]
public static extern int CompareExchange(ref int location1, int value, int comparand);
[MethodImplAttribute(MethodImplOptions.InternalCall)]
- [System.Security.SecuritySafeCritical]
public static extern long CompareExchange(ref long location1, long value, long comparand);
[MethodImplAttribute(MethodImplOptions.InternalCall)]
- [System.Security.SecuritySafeCritical]
public static extern float CompareExchange(ref float location1, float value, float comparand);
[MethodImplAttribute(MethodImplOptions.InternalCall)]
- [System.Security.SecuritySafeCritical]
public static extern double CompareExchange(ref double location1, double value, double comparand);
[MethodImplAttribute(MethodImplOptions.InternalCall)]
[ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)]
- [System.Security.SecuritySafeCritical]
public static extern Object CompareExchange(ref Object location1, Object value, Object comparand);
[MethodImplAttribute(MethodImplOptions.InternalCall)]
[ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)]
- [System.Security.SecuritySafeCritical]
public static extern IntPtr CompareExchange(ref IntPtr location1, IntPtr value, IntPtr comparand);
/*****************************************************************
[ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)]
[System.Runtime.InteropServices.ComVisible(false)]
- [System.Security.SecuritySafeCritical]
public static T CompareExchange<T>(ref T location1, T value, T comparand) where T : class
{
// _CompareExchange() passes back the value read from location1 via local named 'value'
[MethodImplAttribute(MethodImplOptions.InternalCall)]
[ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)]
- [System.Security.SecuritySafeCritical]
private static extern void _CompareExchange(TypedReference location1, TypedReference value, Object comparand);
// BCL-internal overload that returns success via a ref bool param, useful for reliable spin locks.
[MethodImplAttribute(MethodImplOptions.InternalCall)]
[ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)]
- [System.Security.SecuritySafeCritical]
internal static extern int CompareExchange(ref int location1, int value, int comparand, ref bool succeeded);
/******************************
using System.Security.Permissions;
+using System.Diagnostics;
using System.Diagnostics.Contracts;
namespace System.Threading
{
/// These routines avoid needing to allocate a dedicated, lazy-initialization instance, instead using
/// references to ensure targets have been initialized as they are accessed.
/// </remarks>
- [HostProtection(Synchronization = true, ExternalThreading = true)]
public static class LazyInitializer
{
/// <summary>
}
Interlocked.CompareExchange(ref target, value, null);
- Contract.Assert(target != null);
+ Debug.Assert(target != null);
return target;
}
[Serializable]
[System.Security.Permissions.HostProtection(MayLeakOnAbort = true)]
-#if !FEATURE_CORECLR
- [TypeForwardedFrom("System.Core, Version=3.5.0.0, Culture=Neutral, PublicKeyToken=b77a5c561934e089")]
-#endif
public class LockRecursionException : System.Exception
{
public LockRecursionException() { }
using System.Security.Permissions;
using System.Runtime.InteropServices;
- [HostProtection(Synchronization=true, ExternalThreading=true)]
[System.Runtime.InteropServices.ComVisible(true)]
public sealed class ManualResetEvent : EventWaitHandle
{
// =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-
using System;
-using System.Diagnostics;
using System.Security.Permissions;
using System.Threading;
using System.Runtime.InteropServices;
+using System.Diagnostics;
using System.Diagnostics.Contracts;
namespace System.Threading
/// </remarks>
[ComVisible(false)]
[DebuggerDisplay("Set = {IsSet}")]
- [HostProtection(Synchronization = true, ExternalThreading = true)]
public class ManualResetEventSlim : IDisposable
{
// These are the default spin counts we use on single-proc and MP machines.
private set
{
- Contract.Assert(value >= 0, "SpinCount is a restricted-width integer. The value supplied is outside the legal range.");
- Contract.Assert(value <= SpinCountState_MaxValue, "SpinCount is a restricted-width integer. The value supplied is outside the legal range.");
+ Debug.Assert(value >= 0, "SpinCount is a restricted-width integer. The value supplied is outside the legal range.");
+ Debug.Assert(value <= SpinCountState_MaxValue, "SpinCount is a restricted-width integer. The value supplied is outside the legal range.");
// Don't worry about thread safety because it's set one time from the constructor
m_combinedState = (m_combinedState & ~SpinCountState_BitMask) | (value << SpinCountState_ShiftCount);
}
set
{
//setting to <0 would indicate an internal flaw, hence Assert is appropriate.
- Contract.Assert(value >= 0, "NumWaiters should never be less than zero. This indicates an internal error.");
+ Debug.Assert(value >= 0, "NumWaiters should never be less than zero. This indicates an internal error.");
// it is possible for the max number of waiters to be exceeded via user-code, hence we use a real exception here.
if (value >= NumWaitersState_MaxValue)
this.m_combinedState = initialState ? (1 << SignalledState_ShiftCount) : 0;
//the spinCount argument has been validated by the ctors.
//but we now sanity check our predefined constants.
- Contract.Assert(DEFAULT_SPIN_SP >= 0, "Internal error - DEFAULT_SPIN_SP is outside the legal range.");
- Contract.Assert(DEFAULT_SPIN_SP <= SpinCountState_MaxValue, "Internal error - DEFAULT_SPIN_SP is outside the legal range.");
+ Debug.Assert(DEFAULT_SPIN_SP >= 0, "Internal error - DEFAULT_SPIN_SP is outside the legal range.");
+ Debug.Assert(DEFAULT_SPIN_SP <= SpinCountState_MaxValue, "Internal error - DEFAULT_SPIN_SP is outside the legal range.");
SpinCount = PlatformHelper.IsSingleProcessor ? DEFAULT_SPIN_SP : spinCount;
bool currentIsSet = IsSet;
if (currentIsSet != preInitializeIsSet)
{
- Contract.Assert(currentIsSet,
+ Debug.Assert(currentIsSet,
"The only safe concurrent transition is from unset->set: detected set->unset.");
// We saw it as unsignaled, but it has since become set.
// If there are waiting threads, we need to pulse them.
if (Waiters > 0)
{
- Contract.Assert(m_lock != null); //if waiters>0, then m_lock has already been created.
+ Debug.Assert(m_lock != null); //if waiters>0, then m_lock has already been created.
lock (m_lock)
{
private static void CancellationTokenCallback(object obj)
{
ManualResetEventSlim mre = obj as ManualResetEventSlim;
- Contract.Assert(mre != null, "Expected a ManualResetEventSlim");
- Contract.Assert(mre.m_lock != null); //the lock should have been created before this callback is registered for use.
+ Debug.Assert(mre != null, "Expected a ManualResetEventSlim");
+ Debug.Assert(mre.m_lock != null); //the lock should have been created before this callback is registered for use.
lock (mre.m_lock)
{
Monitor.PulseAll(mre.m_lock); // awaken all waiters
{
SpinWait sw = new SpinWait();
- Contract.Assert((newBits | updateBitsMask) == updateBitsMask, "newBits do not fall within the updateBitsMask.");
+ Debug.Assert((newBits | updateBitsMask) == updateBitsMask, "newBits do not fall within the updateBitsMask.");
do
{
using System.Runtime.CompilerServices;
using System.Runtime.ConstrainedExecution;
using System.Runtime.Versioning;
+ using System.Diagnostics;
using System.Diagnostics.Contracts;
- [HostProtection(Synchronization=true, ExternalThreading=true)]
[System.Runtime.InteropServices.ComVisible(true)]
public static class Monitor
{
**
** Exceptions: ArgumentNullException if object is null.
=========================================================================*/
- [System.Security.SecuritySafeCritical]
[MethodImplAttribute(MethodImplOptions.InternalCall)]
public static extern void Enter(Object obj);
ThrowLockTakenException();
ReliableEnter(obj, ref lockTaken);
- Contract.Assert(lockTaken);
+ Debug.Assert(lockTaken);
}
private static void ThrowLockTakenException()
throw new ArgumentException(Environment.GetResourceString("Argument_MustBeFalse"), "lockTaken");
}
- [System.Security.SecuritySafeCritical]
[MethodImplAttribute(MethodImplOptions.InternalCall)]
private static extern void ReliableEnter(Object obj, ref bool lockTaken);
** SynchronizationLockException if the current thread does not
** own the lock.
=========================================================================*/
- [System.Security.SecuritySafeCritical]
[MethodImplAttribute(MethodImplOptions.InternalCall)]
[ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)]
public static extern void Exit(Object obj);
ReliableEnterTimeout(obj, MillisecondsTimeoutFromTimeSpan(timeout), ref lockTaken);
}
- [System.Security.SecuritySafeCritical]
[MethodImplAttribute(MethodImplOptions.InternalCall)]
private static extern void ReliableEnterTimeout(Object obj, int timeout, ref bool lockTaken);
- [System.Security.SecuritySafeCritical]
public static bool IsEntered(object obj)
{
if (obj == null)
return IsEnteredNative(obj);
}
- [System.Security.SecurityCritical]
[MethodImplAttribute(MethodImplOptions.InternalCall)]
private static extern bool IsEnteredNative(Object obj);
**
** Exceptions: ArgumentNullException if object is null.
========================================================================*/
- [System.Security.SecurityCritical] // auto-generated
[MethodImplAttribute(MethodImplOptions.InternalCall)]
private static extern bool ObjWait(bool exitContext, int millisecondsTimeout, Object obj);
- [System.Security.SecuritySafeCritical] // auto-generated
public static bool Wait(Object obj, int millisecondsTimeout, bool exitContext)
{
if (obj == null)
* Exceptions: SynchronizationLockException if this method is not called inside
* a synchronized block of code.
========================================================================*/
- [System.Security.SecurityCritical] // auto-generated
[MethodImplAttribute(MethodImplOptions.InternalCall)]
private static extern void ObjPulse(Object obj);
- [System.Security.SecuritySafeCritical] // auto-generated
public static void Pulse(Object obj)
{
if (obj == null)
/*========================================================================
** Sends a notification to all waiting objects.
========================================================================*/
- [System.Security.SecurityCritical] // auto-generated
[MethodImplAttribute(MethodImplOptions.InternalCall)]
private static extern void ObjPulseAll(Object obj);
- [System.Security.SecuritySafeCritical] // auto-generated
public static void PulseAll(Object obj)
{
if (obj == null)
using System.Runtime.ConstrainedExecution;
using System.Runtime.Versioning;
using System.Security;
+ using System.Diagnostics;
using System.Diagnostics.Contracts;
-
-#if FEATURE_MACL
- using System.Security.AccessControl;
-#endif
- [HostProtection(Synchronization=true, ExternalThreading=true)]
[ComVisible(true)]
public sealed class Mutex : WaitHandle
{
static bool dummyBool;
-#if !FEATURE_MACL
- public class MutexSecurity {
+ public class MutexSecurity
+ {
}
-#endif
- [System.Security.SecurityCritical] // auto-generated_required
[ReliabilityContract(Consistency.WillNotCorruptState, Cer.MayFail)]
public Mutex(bool initiallyOwned, String name, out bool createdNew)
: this(initiallyOwned, name, out createdNew, (MutexSecurity)null)
{
}
- [System.Security.SecurityCritical] // auto-generated_required
[ReliabilityContract(Consistency.WillNotCorruptState, Cer.MayFail)]
public unsafe Mutex(bool initiallyOwned, String name, out bool createdNew, MutexSecurity mutexSecurity)
{
#endif
Contract.EndContractBlock();
Win32Native.SECURITY_ATTRIBUTES secAttrs = null;
-#if FEATURE_MACL
- // For ACL's, get the security descriptor from the MutexSecurity.
- if (mutexSecurity != null) {
-
- secAttrs = new Win32Native.SECURITY_ATTRIBUTES();
- secAttrs.nLength = (int)Marshal.SizeOf(secAttrs);
-
- byte[] sd = mutexSecurity.GetSecurityDescriptorBinaryForm();
- byte* pSecDescriptor = stackalloc byte[sd.Length];
- Buffer.Memcpy(pSecDescriptor, 0, sd, 0, sd.Length);
- secAttrs.pSecurityDescriptor = pSecDescriptor;
- }
-#endif
CreateMutexWithGuaranteedCleanup(initiallyOwned, name, out createdNew, secAttrs);
}
- [System.Security.SecurityCritical] // auto-generated_required
[ReliabilityContract(Consistency.WillNotCorruptState, Cer.MayFail)]
internal Mutex(bool initiallyOwned, String name, out bool createdNew, Win32Native.SECURITY_ATTRIBUTES secAttrs)
{
CreateMutexWithGuaranteedCleanup(initiallyOwned, name, out createdNew, secAttrs);
}
- [System.Security.SecurityCritical] // auto-generated_required
[ReliabilityContract(Consistency.WillNotCorruptState, Cer.MayFail)]
internal void CreateMutexWithGuaranteedCleanup(bool initiallyOwned, String name, out bool createdNew, Win32Native.SECURITY_ATTRIBUTES secAttrs)
{
MutexCleanupInfo m_cleanupInfo;
internal bool m_newMutex;
String m_name;
- [System.Security.SecurityCritical] // auto-generated
Win32Native.SECURITY_ATTRIBUTES m_secAttrs;
Mutex m_mutex;
- [System.Security.SecurityCritical] // auto-generated
[PrePrepareMethod]
internal MutexTryCodeHelper(bool initiallyOwned,MutexCleanupInfo cleanupInfo, String name, Win32Native.SECURITY_ATTRIBUTES secAttrs, Mutex mutex)
{
- Contract.Assert(name == null || name.Length != 0);
+ Debug.Assert(name == null || name.Length != 0);
m_initiallyOwned = initiallyOwned;
m_cleanupInfo = cleanupInfo;
m_mutex = mutex;
}
- [System.Security.SecurityCritical] // auto-generated
[PrePrepareMethod]
internal void MutexTryCode(object userData)
{
if (m_initiallyOwned)
{
m_cleanupInfo.inCriticalRegion = true;
-#if !FEATURE_CORECLR
- Thread.BeginThreadAffinity();
- Thread.BeginCriticalRegion();
-#endif //!FEATURE_CORECLR
}
}
- int errorCode = 0;
+ int errorCode = 0;
RuntimeHelpers.PrepareConstrainedRegions();
try
{
}
}
- [System.Security.SecurityCritical] // auto-generated
[PrePrepareMethod]
private void MutexCleanupCode(Object userData, bool exceptionThrown)
{
MutexCleanupInfo cleanupInfo = (MutexCleanupInfo) userData;
// If hasThreadAffinity isn't true, we've thrown an exception in the above try, and we must free the mutex
- // on this OS thread before ending our thread affninity.
+ // on this OS thread before ending our thread affninity.
if(!hasThreadAffinity) {
if (cleanupInfo.mutexHandle != null && !cleanupInfo.mutexHandle.IsInvalid) {
if( cleanupInfo.inCriticalRegion) {
- Win32Native.ReleaseMutex(cleanupInfo.mutexHandle);
+ Win32Native.ReleaseMutex(cleanupInfo.mutexHandle);
}
- cleanupInfo.mutexHandle.Dispose();
-
+ cleanupInfo.mutexHandle.Dispose();
}
-
- if( cleanupInfo.inCriticalRegion) {
-#if !FEATURE_CORECLR
- Thread.EndCriticalRegion();
- Thread.EndThreadAffinity();
-#endif
- }
}
}
internal class MutexCleanupInfo
{
- [System.Security.SecurityCritical] // auto-generated
internal SafeWaitHandle mutexHandle;
internal bool inCriticalRegion;
- [System.Security.SecurityCritical] // auto-generated
internal MutexCleanupInfo(SafeWaitHandle mutexHandle, bool inCriticalRegion)
{
this.mutexHandle = mutexHandle;
}
}
- [System.Security.SecurityCritical] // auto-generated_required
[ReliabilityContract(Consistency.WillNotCorruptState, Cer.MayFail)]
public Mutex(bool initiallyOwned, String name) : this(initiallyOwned, name, out dummyBool) {
}
- [System.Security.SecuritySafeCritical] // auto-generated
[ReliabilityContract(Consistency.WillNotCorruptState, Cer.MayFail)]
public Mutex(bool initiallyOwned) : this(initiallyOwned, null, out dummyBool)
{
}
- [System.Security.SecuritySafeCritical] // auto-generated
[ReliabilityContract(Consistency.WillNotCorruptState, Cer.MayFail)]
public Mutex() : this(false, null, out dummyBool)
{
}
- [System.Security.SecurityCritical] // auto-generated
[ReliabilityContract(Consistency.WillNotCorruptState, Cer.MayFail)]
private Mutex(SafeWaitHandle handle)
{
hasThreadAffinity = true;
}
- [System.Security.SecurityCritical] // auto-generated_required
public static Mutex OpenExisting(string name)
{
-#if !FEATURE_MACL
return OpenExisting(name, (MutexRights) 0);
-#else // FEATURE_MACL
- return OpenExisting(name, MutexRights.Modify | MutexRights.Synchronize);
-#endif // FEATURE_MACL
}
-#if !FEATURE_MACL
public enum MutexRights
{
}
-#endif
- [System.Security.SecurityCritical] // auto-generated_required
public static Mutex OpenExisting(string name, MutexRights rights)
{
Mutex result;
}
}
- [System.Security.SecurityCritical] // auto-generated_required
public static bool TryOpenExisting(string name, out Mutex result)
{
-#if !FEATURE_MACL
return OpenExistingWorker(name, (MutexRights)0, out result) == OpenExistingResult.Success;
-#else // FEATURE_MACL
- return OpenExistingWorker(name, MutexRights.Modify | MutexRights.Synchronize, out result) == OpenExistingResult.Success;
-#endif // FEATURE_MACL
}
- [System.Security.SecurityCritical] // auto-generated_required
public static bool TryOpenExisting(string name, MutexRights rights, out Mutex result)
{
return OpenExistingWorker(name, rights, out result) == OpenExistingResult.Success;
}
- [System.Security.SecurityCritical]
private static OpenExistingResult OpenExistingWorker(string name, MutexRights rights, out Mutex result)
{
if (name == null)
// with parameters to allow us to view & edit the ACL. This will
// fail if we don't have permission to view or edit the ACL's.
// If that happens, ask for less permissions.
-#if FEATURE_MACL
- SafeWaitHandle myHandle = Win32Native.OpenMutex((int) rights, false, name);
-#else
SafeWaitHandle myHandle = Win32Native.OpenMutex(Win32Native.MUTEX_MODIFY_STATE | Win32Native.SYNCHRONIZE, false, name);
-#endif
int errorCode = 0;
if (myHandle.IsInvalid)
// Note: To call ReleaseMutex, you must have an ACL granting you
// MUTEX_MODIFY_STATE rights (0x0001). The other interesting value
// in a Mutex's ACL is MUTEX_ALL_ACCESS (0x1F0001).
- [System.Security.SecuritySafeCritical] // auto-generated
- [ReliabilityContract(Consistency.WillNotCorruptState, Cer.MayFail)]
+ [ReliabilityContract(Consistency.WillNotCorruptState, Cer.MayFail)]
public void ReleaseMutex()
{
if (Win32Native.ReleaseMutex(safeWaitHandle))
{
-#if !FEATURE_CORECLR
- Thread.EndCriticalRegion();
- Thread.EndThreadAffinity();
-#endif
}
else
{
-#if FEATURE_CORECLR
throw new Exception(Environment.GetResourceString("Arg_SynchronizationLockException"));
-#else
- throw new ApplicationException(Environment.GetResourceString("Arg_SynchronizationLockException"));
-#endif // FEATURE_CORECLR
- }
+ }
}
- [System.Security.SecurityCritical] // auto-generated
[ReliabilityContract(Consistency.WillNotCorruptState, Cer.MayFail)]
- static int CreateMutexHandle(bool initiallyOwned, String name, Win32Native.SECURITY_ATTRIBUTES securityAttribute, out SafeWaitHandle mutexHandle) {
- int errorCode;
- bool fAffinity = false;
-
- while(true) {
+ static int CreateMutexHandle(bool initiallyOwned, String name, Win32Native.SECURITY_ATTRIBUTES securityAttribute, out SafeWaitHandle mutexHandle)
+ {
+ int errorCode;
+
+ while (true)
+ {
mutexHandle = Win32Native.CreateMutex(securityAttribute, initiallyOwned, name);
- errorCode = Marshal.GetLastWin32Error();
- if( !mutexHandle.IsInvalid) {
- break;
- }
+ errorCode = Marshal.GetLastWin32Error();
+ if (!mutexHandle.IsInvalid) break;
- if( errorCode == Win32Native.ERROR_ACCESS_DENIED) {
- // If a mutex with the name already exists, OS will try to open it with FullAccess.
- // It might fail if we don't have enough access. In that case, we try to open the mutex will modify and synchronize access.
- //
-
- RuntimeHelpers.PrepareConstrainedRegions();
- try
- {
- try
- {
- }
- finally
- {
-#if !FEATURE_CORECLR
- Thread.BeginThreadAffinity();
-#endif
- fAffinity = true;
- }
- mutexHandle = Win32Native.OpenMutex(Win32Native.MUTEX_MODIFY_STATE | Win32Native.SYNCHRONIZE, false, name);
- if(!mutexHandle.IsInvalid)
- {
- errorCode = Win32Native.ERROR_ALREADY_EXISTS;
- }
- else
- {
- errorCode = Marshal.GetLastWin32Error();
- }
- }
- finally
- {
- if (fAffinity) {
-#if !FEATURE_CORECLR
- Thread.EndThreadAffinity();
-#endif
- }
- }
+ if (errorCode != Win32Native.ERROR_ACCESS_DENIED) break;
- // There could be a race condition here, the other owner of the mutex can free the mutex,
- // We need to retry creation in that case.
- if( errorCode != Win32Native.ERROR_FILE_NOT_FOUND) {
- if( errorCode == Win32Native.ERROR_SUCCESS) {
- errorCode = Win32Native.ERROR_ALREADY_EXISTS;
- }
- break;
- }
- }
- else {
+ // If a mutex with the name already exists, OS will try to open it with FullAccess.
+ // It might fail if we don't have enough access. In that case, we try to open the mutex will modify and synchronize access.
+ RuntimeHelpers.PrepareConstrainedRegions();
+
+ mutexHandle = Win32Native.OpenMutex(
+ Win32Native.MUTEX_MODIFY_STATE | Win32Native.SYNCHRONIZE,
+ false,
+ name);
+
+ errorCode = !mutexHandle.IsInvalid ? Win32Native.ERROR_ALREADY_EXISTS : Marshal.GetLastWin32Error();
+
+ // There could be a race condition here, the other owner of the mutex can free the mutex,
+ // We need to retry creation in that case.
+ if (errorCode != Win32Native.ERROR_FILE_NOT_FOUND)
+ {
+ if (errorCode == Win32Native.ERROR_SUCCESS) errorCode = Win32Native.ERROR_ALREADY_EXISTS;
break;
}
- }
+ }
return errorCode;
}
-
-#if FEATURE_MACL
- [System.Security.SecuritySafeCritical] // auto-generated
- public MutexSecurity GetAccessControl()
- {
- return new MutexSecurity(safeWaitHandle, AccessControlSections.Access | AccessControlSections.Owner | AccessControlSections.Group);
- }
-
- [System.Security.SecuritySafeCritical] // auto-generated
- public void SetAccessControl(MutexSecurity mutexSecurity)
- {
- if (mutexSecurity == null)
- throw new ArgumentNullException(nameof(mutexSecurity));
- Contract.EndContractBlock();
-
- mutexSecurity.Persist(safeWaitHandle);
- }
-#endif
-
}
}
using System.Security;
using System.Security.Permissions;
using System.Runtime.ConstrainedExecution;
+ using System.Diagnostics;
using System.Diagnostics.Contracts;
using System.Collections.Concurrent;
unsafe internal class _IOCompletionCallback
{
- [System.Security.SecurityCritical] // auto-generated
IOCompletionCallback _ioCompletionCallback;
ExecutionContext _executionContext;
uint _errorCode; // Error code
uint _numBytes; // No. of bytes transferred
- [SecurityCritical]
NativeOverlapped* _pOVERLAP;
- [System.Security.SecuritySafeCritical] // auto-generated
static _IOCompletionCallback()
{
}
- [System.Security.SecurityCritical] // auto-generated
internal _IOCompletionCallback(IOCompletionCallback ioCompletionCallback, ref StackCrawlMark stackMark)
{
_ioCompletionCallback = ioCompletionCallback;
ExecutionContext.CaptureOptions.IgnoreSyncCtx | ExecutionContext.CaptureOptions.OptimizeDefaultCase);
}
// Context callback: same sig for SendOrPostCallback and ContextCallback
- #if FEATURE_CORECLR
- [System.Security.SecurityCritical] // auto-generated
- #endif
static internal ContextCallback _ccb = new ContextCallback(IOCompletionCallback_Context);
- [System.Security.SecurityCritical]
static internal void IOCompletionCallback_Context(Object state)
{
_IOCompletionCallback helper = (_IOCompletionCallback)state;
- Contract.Assert(helper != null,"_IOCompletionCallback cannot be null");
+ Debug.Assert(helper != null,"_IOCompletionCallback cannot be null");
helper._ioCompletionCallback(helper._errorCode, helper._numBytes, helper._pOVERLAP);
}
// call back helper
- [System.Security.SecurityCritical] // auto-generated
static unsafe internal void PerformIOCompletionCallback(uint errorCode, // Error code
uint numBytes, // No. of bytes transferred
NativeOverlapped* pOVERLAP // ptr to OVERLAP structure
// ! If you make any change to the layout here, you need to make matching change
// ! to OverlappedObject in vm\nativeoverlapped.h
internal IAsyncResult m_asyncResult;
- [System.Security.SecurityCritical] // auto-generated
internal IOCompletionCallback m_iocb;
internal _IOCompletionCallback m_iocbHelper;
internal Overlapped m_overlapped;
#pragma warning restore 169
internal NativeOverlapped m_nativeOverlapped;
-#if FEATURE_CORECLR
// Adding an empty default ctor for annotation purposes
- [System.Security.SecuritySafeCritical] // auto-generated
internal OverlappedData(){}
-#endif // FEATURE_CORECLR
-
- [System.Security.SecurityCritical]
internal void ReInitialize()
{
m_asyncResult = null;
m_iocbHelper = null;
m_overlapped = null;
m_userObject = null;
- Contract.Assert(m_pinSelf.IsNull(), "OverlappedData has not been freed: m_pinSelf");
+ Debug.Assert(m_pinSelf.IsNull(), "OverlappedData has not been freed: m_pinSelf");
m_pinSelf = (IntPtr)0;
m_userObjectInternal = (IntPtr)0;
- Contract.Assert(m_AppDomainId == 0 || m_AppDomainId == AppDomain.CurrentDomain.Id, "OverlappedData is not in the current domain");
+ Debug.Assert(m_AppDomainId == 0 || m_AppDomainId == AppDomain.CurrentDomain.Id, "OverlappedData is not in the current domain");
m_AppDomainId = 0;
m_nativeOverlapped.EventHandle = (IntPtr)0;
m_isArray = 0;
m_nativeOverlapped.InternalHigh = (IntPtr)0;
}
- [System.Security.SecurityCritical] // auto-generated
[MethodImplAttribute(MethodImplOptions.NoInlining)] // Methods containing StackCrawlMark local var has to be marked non-inlineable
unsafe internal NativeOverlapped* Pack(IOCompletionCallback iocb, Object userData)
{
return AllocateNativeOverlapped();
}
- [System.Security.SecurityCritical] // auto-generated_required
unsafe internal NativeOverlapped* UnsafePack(IOCompletionCallback iocb, Object userData)
{
if (!m_pinSelf.IsNull()) {
set { m_nativeOverlapped.EventHandle = value; }
}
- [System.Security.SecurityCritical] // auto-generated
[MethodImplAttribute(MethodImplOptions.InternalCall)]
unsafe private extern NativeOverlapped* AllocateNativeOverlapped();
- [System.Security.SecurityCritical] // auto-generated
[MethodImplAttribute(MethodImplOptions.InternalCall)]
unsafe internal static extern void FreeNativeOverlapped(NativeOverlapped* nativeOverlappedPtr);
- [System.Security.SecurityCritical] // auto-generated
[MethodImplAttribute(MethodImplOptions.InternalCall)]
unsafe internal static extern OverlappedData GetOverlappedFromNative(NativeOverlapped* nativeOverlappedPtr);
- [System.Security.SecurityCritical] // auto-generated
[MethodImplAttribute(MethodImplOptions.InternalCall)]
unsafe internal static extern void CheckVMForIOPacket(out NativeOverlapped* pOVERLAP, out uint errorCode, out uint numBytes);
}
private OverlappedData m_overlappedData;
private static PinnableBufferCache s_overlappedDataCache = new PinnableBufferCache("System.Threading.OverlappedData", ()=> new OverlappedData());
-#if FEATURE_CORECLR
- [System.Security.SecuritySafeCritical] // auto-generated
-#endif
public Overlapped()
{
m_overlappedData = (OverlappedData) s_overlappedDataCache.Allocate();
internal IOCompletionCallback UserCallback
{
- [System.Security.SecurityCritical]
get { return m_overlappedData.m_iocb; }
}
* Roots the iocb and stores it in the ReservedCOR field of native Overlapped
* Pins the native Overlapped struct and returns the pinned index.
====================================================================*/
- [System.Security.SecurityCritical] // auto-generated
[Obsolete("This method is not safe. Use Pack (iocb, userData) instead. http://go.microsoft.com/fwlink/?linkid=14202")]
[CLSCompliant(false)]
unsafe public NativeOverlapped* Pack(IOCompletionCallback iocb)
return Pack (iocb, null);
}
- [System.Security.SecurityCritical] // auto-generated
[CLSCompliant(false),ComVisible(false)]
unsafe public NativeOverlapped* Pack(IOCompletionCallback iocb, Object userData)
{
return m_overlappedData.Pack(iocb, userData);
}
- [System.Security.SecurityCritical] // auto-generated_required
[Obsolete("This method is not safe. Use UnsafePack (iocb, userData) instead. http://go.microsoft.com/fwlink/?linkid=14202")]
[CLSCompliant(false)]
unsafe public NativeOverlapped* UnsafePack(IOCompletionCallback iocb)
return UnsafePack (iocb, null);
}
- [System.Security.SecurityCritical] // auto-generated_required
[CLSCompliant(false), ComVisible(false)]
unsafe public NativeOverlapped* UnsafePack(IOCompletionCallback iocb, Object userData)
{
* Unpacks an unmanaged native Overlapped struct.
* Unpins the native Overlapped struct
====================================================================*/
- [System.Security.SecurityCritical] // auto-generated
[CLSCompliant(false)]
unsafe public static Overlapped Unpack(NativeOverlapped* nativeOverlappedPtr)
{
return overlapped;
}
- [System.Security.SecurityCritical] // auto-generated
[CLSCompliant(false)]
unsafe public static void Free(NativeOverlapped* nativeOverlappedPtr)
{
using System.Runtime.Versioning;
using System.Diagnostics.Contracts;
- [HostProtection(Synchronization=true, ExternalThreading=true)]
[ComVisible(true)]
public sealed class ReaderWriterLock: CriticalFinalizerObject
{
/*
* Constructor
*/
- [System.Security.SecuritySafeCritical] // auto-generated
public ReaderWriterLock()
{
PrivateInitialize();
/*
* Destructor
*/
- [System.Security.SecuritySafeCritical] // auto-generated
~ReaderWriterLock()
{
PrivateDestruct();
* by the current thread
*/
public bool IsReaderLockHeld {
- [System.Security.SecuritySafeCritical] // auto-generated
[ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)]
get {
return(PrivateGetIsReaderLockHeld());
* by the current thread
*/
public bool IsWriterLockHeld {
- [System.Security.SecuritySafeCritical] // auto-generated
[ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)]
get {
return(PrivateGetIsWriterLockHeld());
* meaningful results
*/
public int WriterSeqNum {
- [System.Security.SecuritySafeCritical] // auto-generated
get {
return(PrivateGetWriterSeqNum());
}
* Acquires reader lock. The thread will block if a different
* thread has writer lock.
*/
- [System.Security.SecurityCritical] // auto-generated
[MethodImplAttribute(MethodImplOptions.InternalCall)]
private extern void AcquireReaderLockInternal(int millisecondsTimeout);
- [System.Security.SecuritySafeCritical] // auto-generated
public void AcquireReaderLock(int millisecondsTimeout)
{
AcquireReaderLockInternal(millisecondsTimeout);
}
- [System.Security.SecuritySafeCritical] // auto-generated
public void AcquireReaderLock(TimeSpan timeout)
{
long tm = (long)timeout.TotalMilliseconds;
* has reader lock. Use UpgardeToWriterLock when you are not
* sure if the thread has reader lock
*/
- [System.Security.SecurityCritical] // auto-generated
[MethodImplAttribute(MethodImplOptions.InternalCall)]
private extern void AcquireWriterLockInternal(int millisecondsTimeout);
- [System.Security.SecuritySafeCritical] // auto-generated
public void AcquireWriterLock(int millisecondsTimeout)
{
AcquireWriterLockInternal(millisecondsTimeout);
}
- [System.Security.SecuritySafeCritical] // auto-generated
public void AcquireWriterLock(TimeSpan timeout)
{
long tm = (long)timeout.TotalMilliseconds;
/*
* Releases reader lock.
*/
- [System.Security.SecurityCritical] // auto-generated
[MethodImplAttribute(MethodImplOptions.InternalCall)]
[ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)]
private extern void ReleaseReaderLockInternal();
- [System.Security.SecuritySafeCritical] // auto-generated
[ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)]
public void ReleaseReaderLock()
{
/*
* Releases writer lock.
*/
- [System.Security.SecurityCritical] // auto-generated
[MethodImplAttribute(MethodImplOptions.InternalCall)]
[ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)]
private extern void ReleaseWriterLockInternal();
- [System.Security.SecuritySafeCritical] // auto-generated
[ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)]
public void ReleaseWriterLock()
{
* reader, it is possible that the reader lock was
* released before writer lock was acquired.
*/
- [System.Security.SecuritySafeCritical] // auto-generated
public LockCookie UpgradeToWriterLock(int millisecondsTimeout)
{
LockCookie result = new LockCookie ();
return result;
}
- [System.Security.SecurityCritical] // auto-generated
[MethodImplAttribute(MethodImplOptions.InternalCall)]
private extern void FCallUpgradeToWriterLock(ref LockCookie result, int millisecondsTimeout);
* Restores the lock status of the thread to the one it was
* in when it called UpgradeToWriterLock.
*/
- [System.Security.SecurityCritical] // auto-generated
[MethodImplAttribute(MethodImplOptions.InternalCall)]
private extern void DowngradeFromWriterLockInternal(ref LockCookie lockCookie);
- [System.Security.SecuritySafeCritical] // auto-generated
public void DowngradeFromWriterLock(ref LockCookie lockCookie)
{
DowngradeFromWriterLockInternal(ref lockCookie);
* Releases the lock irrespective of the number of times the thread
* acquired the lock
*/
- [System.Security.SecuritySafeCritical] // auto-generated
public LockCookie ReleaseLock()
{
LockCookie result = new LockCookie ();
return result;
}
- [System.Security.SecurityCritical] // auto-generated
[MethodImplAttribute(MethodImplOptions.InternalCall)]
private extern void FCallReleaseLock(ref LockCookie result);
* Restores the lock status of the thread to the one it was
* in when it called ReleaseLock.
*/
- [System.Security.SecurityCritical] // auto-generated
[MethodImplAttribute(MethodImplOptions.InternalCall)]
private extern void RestoreLockInternal(ref LockCookie lockCookie);
- [System.Security.SecuritySafeCritical] // auto-generated
public void RestoreLock(ref LockCookie lockCookie)
{
RestoreLockInternal(ref lockCookie);
* Internal helper that returns TRUE if the reader lock is held
* by the current thread
*/
- [System.Security.SecurityCritical] // auto-generated
[MethodImplAttribute(MethodImplOptions.InternalCall)]
[ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)]
private extern bool PrivateGetIsReaderLockHeld();
* Internal helper that returns TRUE if the writer lock is held
* by the current thread
*/
- [System.Security.SecurityCritical] // auto-generated
[MethodImplAttribute(MethodImplOptions.InternalCall)]
[ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)]
private extern bool PrivateGetIsWriterLockHeld();
* number. The caller should be a reader or writer for getting
* meaningful results
*/
- [System.Security.SecurityCritical] // auto-generated
[MethodImplAttribute(MethodImplOptions.InternalCall)]
private extern int PrivateGetWriterSeqNum();
* sequence number was obtained. The caller should be
* a reader or writer for getting meaningful results
*/
- [System.Security.SecuritySafeCritical] // auto-generated
[MethodImplAttribute(MethodImplOptions.InternalCall)]
public extern bool AnyWritersSince(int seqNum);
// Initialize state kept inside the lock
- [System.Security.SecurityCritical] // auto-generated
[MethodImplAttribute(MethodImplOptions.InternalCall)]
private extern void PrivateInitialize();
// Destruct resource associated with the lock
- [System.Security.SecurityCritical] // auto-generated
[MethodImplAttribute(MethodImplOptions.InternalCall)]
private extern void PrivateDestruct();
using Microsoft.Win32;
using Microsoft.Win32.SafeHandles;
+using System.Diagnostics;
using System.Diagnostics.Contracts;
using System.IO;
using System.Runtime.InteropServices;
{
public sealed partial class Semaphore : WaitHandle
{
- [SecuritySafeCritical]
public Semaphore(int initialCount, int maximumCount) : this(initialCount, maximumCount, null) { }
- [SecurityCritical]
public Semaphore(int initialCount, int maximumCount, string name)
{
if (initialCount < 0)
this.SafeWaitHandle = myHandle;
}
- [SecurityCritical]
public Semaphore(int initialCount, int maximumCount, string name, out bool createdNew)
{
if (initialCount < 0)
this.SafeWaitHandle = myHandle;
}
- [SecurityCritical]
private Semaphore(SafeWaitHandle handle)
{
this.SafeWaitHandle = handle;
}
- [SecurityCritical]
private static SafeWaitHandle CreateSemaphone(int initialCount, int maximumCount, string name)
{
if (name != null)
#endif
}
- Contract.Assert(initialCount >= 0);
- Contract.Assert(maximumCount >= 1);
- Contract.Assert(initialCount <= maximumCount);
+ Debug.Assert(initialCount >= 0);
+ Debug.Assert(maximumCount >= 1);
+ Debug.Assert(initialCount <= maximumCount);
return Win32Native.CreateSemaphore(null, initialCount, maximumCount, name);
}
- [SecurityCritical]
-
public static Semaphore OpenExisting(string name)
{
Semaphore result;
}
}
- [SecurityCritical]
public static bool TryOpenExisting(string name, out Semaphore result)
{
return OpenExistingWorker(name, out result) == OpenExistingResult.Success;
}
- [SecurityCritical]
private static OpenExistingResult OpenExistingWorker(string name, out Semaphore result)
{
#if PLATFORM_UNIX
}
// increase the count on a semaphore, returns previous count
- [SecuritySafeCritical]
public int Release(int releaseCount)
{
if (releaseCount < 1)
[Serializable]
[ComVisibleAttribute(false)]
-#if !FEATURE_CORECLR
- [System.Runtime.CompilerServices.TypeForwardedFrom("System, Version=2.0.0.0, Culture=Neutral, PublicKeyToken=b77a5c561934e089")]
-#endif
public class SemaphoreFullException : SystemException {
public SemaphoreFullException() : base(Environment.GetResourceString("Threading_SemaphoreFullException")){
/// </para>
/// </remarks>
[ComVisible(false)]
- [HostProtection(Synchronization = true, ExternalThreading = true)]
[DebuggerDisplay("Current Count = {m_currentCount}")]
public class SemaphoreSlim : IDisposable
{
internal TaskNode Prev, Next;
internal TaskNode() : base() {}
- [SecurityCritical]
void IThreadPoolWorkItem.ExecuteWorkItem()
{
bool setSuccessfully = TrySetResult(true);
- Contract.Assert(setSuccessfully, "Should have been able to complete task");
+ Debug.Assert(setSuccessfully, "Should have been able to complete task");
}
- [SecurityCritical]
void IThreadPoolWorkItem.MarkAborted(ThreadAbortException tae) { /* nop */ }
}
#endregion
// then block on (once we've released the lock).
if (m_asyncHead != null)
{
- Contract.Assert(m_asyncTail != null, "tail should not be null if head isn't");
+ Debug.Assert(m_asyncTail != null, "tail should not be null if head isn't");
asyncWaitTask = WaitAsync(millisecondsTimeout, cancellationToken);
}
// There are no async waiters, so we can proceed with normal synchronous waiting.
// defer to synchronous waiters in priority, which means that if it's possible an asynchronous
// waiter didn't get released because a synchronous waiter was present, we need to ensure
// that synchronous waiter succeeds so that they have a chance to release.
- Contract.Assert(!waitSuccessful || m_currentCount > 0,
+ Debug.Assert(!waitSuccessful || m_currentCount > 0,
"If the wait was successful, there should be count available.");
if (m_currentCount > 0)
{
// the semaphore or when the timeout expired or cancellation was requested.
else
{
- Contract.Assert(m_currentCount == 0, "m_currentCount should never be negative");
+ Debug.Assert(m_currentCount == 0, "m_currentCount should never be negative");
var asyncWaiter = CreateAndAddAsyncWaiter();
return (millisecondsTimeout == Timeout.Infinite && !cancellationToken.CanBeCanceled) ?
asyncWaiter :
/// <returns>The created task.</returns>
private TaskNode CreateAndAddAsyncWaiter()
{
- Contract.Assert(Monitor.IsEntered(m_lockObj), "Requires the lock be held");
+ Debug.Assert(Monitor.IsEntered(m_lockObj), "Requires the lock be held");
// Create the task
var task = new TaskNode();
// Add it to the linked list
if (m_asyncHead == null)
{
- Contract.Assert(m_asyncTail == null, "If head is null, so too should be tail");
+ Debug.Assert(m_asyncTail == null, "If head is null, so too should be tail");
m_asyncHead = task;
m_asyncTail = task;
}
else
{
- Contract.Assert(m_asyncTail != null, "If head is not null, neither should be tail");
+ Debug.Assert(m_asyncTail != null, "If head is not null, neither should be tail");
m_asyncTail.Next = task;
task.Prev = m_asyncTail;
m_asyncTail = task;
private bool RemoveAsyncWaiter(TaskNode task)
{
Contract.Requires(task != null, "Expected non-null task");
- Contract.Assert(Monitor.IsEntered(m_lockObj), "Requires the lock be held");
+ Debug.Assert(Monitor.IsEntered(m_lockObj), "Requires the lock be held");
// Is the task in the list? To be in the list, either it's the head or it has a predecessor that's in the list.
bool wasInList = m_asyncHead == task || task.Prev != null;
if (task.Prev != null) task.Prev.Next = task.Next;
if (m_asyncHead == task) m_asyncHead = task.Next;
if (m_asyncTail == task) m_asyncTail = task.Prev;
- Contract.Assert((m_asyncHead == null) == (m_asyncTail == null), "Head is null iff tail is null");
+ Debug.Assert((m_asyncHead == null) == (m_asyncTail == null), "Head is null iff tail is null");
// Make sure not to leak
task.Next = task.Prev = null;
/// <returns>The task to return to the caller.</returns>
private async Task<bool> WaitUntilCountOrTimeoutAsync(TaskNode asyncWaiter, int millisecondsTimeout, CancellationToken cancellationToken)
{
- Contract.Assert(asyncWaiter != null, "Waiter should have been constructed");
- Contract.Assert(Monitor.IsEntered(m_lockObj), "Requires the lock be held");
+ Debug.Assert(asyncWaiter != null, "Waiter should have been constructed");
+ Debug.Assert(Monitor.IsEntered(m_lockObj), "Requires the lock be held");
// Wait until either the task is completed, timeout occurs, or cancellation is requested.
// We need to ensure that the Task.Delay task is appropriately cleaned up if the await
// waits are canceled, but the wait code path will handle that.
if (m_asyncHead != null)
{
- Contract.Assert(m_asyncTail != null, "tail should not be null if head isn't null");
+ Debug.Assert(m_asyncTail != null, "tail should not be null if head isn't null");
int maxAsyncToRelease = currentCount - waitCount;
while (maxAsyncToRelease > 0 && m_asyncHead != null)
{
/// Queues a waiter task to the ThreadPool. We use this small helper method so that
/// the larger Release(count) method does not need to be SecuritySafeCritical.
/// </summary>
- [SecuritySafeCritical] // for ThreadPool.UnsafeQueueCustomWorkItem
private static void QueueWaiterTask(TaskNode waiterTask)
{
ThreadPool.UnsafeQueueCustomWorkItem(waiterTask, forceGlobal: false);
private static void CancellationTokenCanceledEventHandler(object obj)
{
SemaphoreSlim semaphore = obj as SemaphoreSlim;
- Contract.Assert(semaphore != null, "Expected a SemaphoreSlim");
+ Debug.Assert(semaphore != null, "Expected a SemaphoreSlim");
lock (semaphore.m_lockObj)
{
Monitor.PulseAll(semaphore.m_lockObj); //wake up all waiters.
//
// =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-
using System;
-using System.Diagnostics;
using System.Security.Permissions;
using System.Runtime.InteropServices;
using System.Runtime.CompilerServices;
using System.Runtime.ConstrainedExecution;
+using System.Diagnostics;
using System.Diagnostics.Contracts;
namespace System.Threading
/// </para>
/// </remarks>
[ComVisible(false)]
- [HostProtection(Synchronization = true, ExternalThreading = true)]
[DebuggerTypeProxy(typeof(SystemThreading_SpinLockDebugView))]
[DebuggerDisplay("IsHeld = {IsHeld}")]
public struct SpinLock
// The waiters count is calculated by m_owner & WAITERS_MASK 01111....110
private static int MAXIMUM_WAITERS = WAITERS_MASK;
-
/// <summary>
/// Initializes a new instance of the <see cref="T:System.Threading.SpinLock"/>
/// structure with the option to track thread IDs to improve debugging.
if (!enableThreadOwnerTracking)
{
m_owner |= LOCK_ID_DISABLE_MASK;
- Contract.Assert(!IsThreadOwnerTrackingEnabled, "property should be false by now");
+ Debug.Assert(!IsThreadOwnerTrackingEnabled, "property should be false by now");
}
}
-
/// <summary>
/// Initializes a new instance of the <see cref="T:System.Threading.SpinLock"/>
/// structure with the option to track thread IDs to improve debugging.
/// </exception>
public void Enter(ref bool lockTaken)
{
-#if !FEATURE_CORECLR
- Thread.BeginCriticalRegion();
-#endif
//Try to keep the code and branching in this method as small as possible in order to inline the method
int observedOwner = m_owner;
if (lockTaken || //invalid parameter
/// a negative number other than -1, which represents an infinite time-out.</exception>
public void TryEnter(int millisecondsTimeout, ref bool lockTaken)
{
-#if !FEATURE_CORECLR
- Thread.BeginCriticalRegion();
-#endif
-
int observedOwner = m_owner;
if (millisecondsTimeout < -1 || //invalid parameter
lockTaken || //invalid parameter
/// <param name="lockTaken">The lockTaken param</param>
private void ContinueTryEnter(int millisecondsTimeout, ref bool lockTaken)
{
- //Leave the critical region which is entered by the fast path
-#if !FEATURE_CORECLR
- Thread.EndCriticalRegion();
-#endif
// The fast path doesn't throw any exception, so we have to validate the parameters here
if (lockTaken)
{
nameof(millisecondsTimeout), millisecondsTimeout, Environment.GetResourceString("SpinLock_TryEnter_ArgumentOutOfRange"));
}
-
uint startTime = 0;
if (millisecondsTimeout != Timeout.Infinite && millisecondsTimeout != 0)
{
startTime = TimeoutHelper.GetTime();
}
-#if !FEATURE_CORECLR
- if (CdsSyncEtwBCLProvider.Log.IsEnabled())
- {
- CdsSyncEtwBCLProvider.Log.SpinLock_FastPathFailed(m_owner);
- }
-#endif
-
if (IsThreadOwnerTrackingEnabled)
{
// Slow path for enabled thread tracking mode
observedOwner = m_owner;
if ((observedOwner & LOCK_ANONYMOUS_OWNED) == LOCK_UNOWNED)
{
-#if !FEATURE_CORECLR
- Thread.BeginCriticalRegion();
-#endif
-
if (Interlocked.CompareExchange(ref m_owner, observedOwner | 1, observedOwner, ref lockTaken) == observedOwner)
{
// Aquired lock
return;
}
-#if !FEATURE_CORECLR
- Thread.EndCriticalRegion();
-#endif
if (millisecondsTimeout == 0)
{
// Did not aquire lock in CompareExchange and timeout is 0 so fail fast
observedOwner = m_owner;
if ((observedOwner & LOCK_ANONYMOUS_OWNED) == LOCK_UNOWNED)
{
-#if !FEATURE_CORECLR
- Thread.BeginCriticalRegion();
-#endif
-
int newOwner = (observedOwner & WAITERS_MASK) == 0 ? // Gets the number of waiters, if zero
observedOwner | 1 // don't decrement it. just set the lock bit, it is zzero because a previous call of Exit(false) ehich corrupted the waiters
: (observedOwner - 2) | 1; // otherwise decrement the waiters and set the lock bit
- Contract.Assert((newOwner & WAITERS_MASK) >= 0);
+ Debug.Assert((newOwner & WAITERS_MASK) >= 0);
if (Interlocked.CompareExchange(ref m_owner, newOwner, observedOwner, ref lockTaken) == observedOwner)
{
return;
}
-
-#if !FEATURE_CORECLR
- Thread.EndCriticalRegion();
-#endif
}
}
}
}
-
//*** Step 3, Yielding
//Sleep(1) every 50 yields
int yieldsoFar = 0;
observedOwner = m_owner;
if ((observedOwner & LOCK_ANONYMOUS_OWNED) == LOCK_UNOWNED)
{
-#if !FEATURE_CORECLR
- Thread.BeginCriticalRegion();
-#endif
int newOwner = (observedOwner & WAITERS_MASK) == 0 ? // Gets the number of waiters, if zero
observedOwner | 1 // don't decrement it. just set the lock bit, it is zzero because a previous call of Exit(false) ehich corrupted the waiters
: (observedOwner - 2) | 1; // otherwise decrement the waiters and set the lock bit
- Contract.Assert((newOwner & WAITERS_MASK) >= 0);
+ Debug.Assert((newOwner & WAITERS_MASK) >= 0);
if (Interlocked.CompareExchange(ref m_owner, newOwner, observedOwner, ref lockTaken) == observedOwner)
{
return;
}
-
-#if !FEATURE_CORECLR
- Thread.EndCriticalRegion();
-#endif
}
if (yieldsoFar % SLEEP_ONE_FREQUENCY == 0)
if ((observedOwner & WAITERS_MASK) == 0) return; // don't decrement the waiters if it's corrupted by previous call of Exit(false)
if (Interlocked.CompareExchange(ref m_owner, observedOwner - 2, observedOwner) == observedOwner)
{
- Contract.Assert(!IsThreadOwnerTrackingEnabled); // Make sure the waiters never be negative which will cause the thread tracking bit to be flipped
+ Debug.Assert(!IsThreadOwnerTrackingEnabled); // Make sure the waiters never be negative which will cause the thread tracking bit to be flipped
break;
}
spinner.SpinOnce();
/// </summary>
private void ContinueTryEnterWithThreadTracking(int millisecondsTimeout, uint startTime, ref bool lockTaken)
{
- Contract.Assert(IsThreadOwnerTrackingEnabled);
+ Debug.Assert(IsThreadOwnerTrackingEnabled);
int lockUnowned = 0;
// We are using thread IDs to mark ownership. Snap the thread ID and check for recursion.
if (m_owner == lockUnowned)
{
-#if !FEATURE_CORECLR
- Thread.BeginCriticalRegion();
-#endif
if (Interlocked.CompareExchange(ref m_owner, m_newOwner, lockUnowned, ref lockTaken) == lockUnowned)
{
return;
}
-#if !FEATURE_CORECLR
- // The thread failed to get the lock, so we don't need to remain in a critical region.
- Thread.EndCriticalRegion();
-#endif
}
// Check the timeout. We only RDTSC if the next spin will yield, to amortize the cost.
if (millisecondsTimeout == 0 ||
ExitSlowPath(true);
else
Interlocked.Decrement(ref m_owner);
-
-#if !FEATURE_CORECLR
- Thread.EndCriticalRegion();
-#endif
-
}
/// <summary>
}
else
ExitSlowPath(useMemoryBarrier);
-
-#if !FEATURE_CORECLR
- Thread.EndCriticalRegion();
-#endif
}
/// <summary>
using System.Runtime.ConstrainedExecution;
using System.Security.Permissions;
using System.Threading;
+using System.Diagnostics;
using System.Diagnostics.Contracts;
using System.Diagnostics.CodeAnalysis;
/// threads must spin, each should use its own instance of SpinWait.
/// </para>
/// </remarks>
- [HostProtection(Synchronization = true, ExternalThreading = true)]
public struct SpinWait
{
// remove the thread from the scheduler's queue for 10+ms, if the system is
// configured to use the (default) coarse-grained system timer.
//
-
-#if !FEATURE_CORECLR
- CdsSyncEtwBCLProvider.Log.SpinWait_NextSpinWillYield();
-#endif
int yieldsSoFar = (m_count >= YIELD_THRESHOLD ? m_count - YIELD_THRESHOLD : m_count);
if ((yieldsSoFar % SLEEP_1_EVERY_HOW_MANY_TIMES) == (SLEEP_1_EVERY_HOW_MANY_TIMES - 1))
#endif
SpinUntil(condition, Timeout.Infinite);
#if DEBUG
- Contract.Assert(result);
+ Debug.Assert(result);
#endif
}
s_lastProcessorCountRefreshTicks = now;
}
- Contract.Assert(procCount > 0 && procCount <= 64,
+ Debug.Assert(procCount > 0 && procCount <= 64,
"Processor count not within the expected range (1 - 64).");
return procCount;
public static int UpdateTimeOut(uint startTime, int originalWaitMillisecondsTimeout)
{
// The function must be called in case the time out is not infinite
- Contract.Assert(originalWaitMillisecondsTimeout != Timeout.Infinite);
+ Debug.Assert(originalWaitMillisecondsTimeout != Timeout.Infinite);
uint elapsedMilliseconds = (GetTime() - startTime);
using System.Runtime.ConstrainedExecution;
using System.Reflection;
using System.Security;
+ using System.Diagnostics;
using System.Diagnostics.Contracts;
using System.Diagnostics.CodeAnalysis;
// I'd like this to be an interface, or at least an abstract class - but neither seems to play nice with FriendAccessAllowed.
//
[FriendAccessAllowed]
- [SecurityCritical]
internal class WinRTSynchronizationContextFactoryBase
{
- [SecurityCritical]
public virtual SynchronizationContext Create(object coreDispatcher) {return null;}
}
#endif //FEATURE_COMINTEROP
-#if !FEATURE_CORECLR
- [SecurityPermissionAttribute(SecurityAction.InheritanceDemand, Flags =SecurityPermissionFlag.ControlPolicy|SecurityPermissionFlag.ControlEvidence)]
-#endif
public class SynchronizationContext
{
#if FEATURE_SYNCHRONIZATIONCONTEXT_WAIT
static Type s_cachedPreparedType5;
// protected so that only the derived sync context class can enable these flags
- [System.Security.SecuritySafeCritical] // auto-generated
[SuppressMessage("Microsoft.Concurrency", "CA8001", Justification = "We never dereference s_cachedPreparedType*, so ordering is unimportant")]
protected void SetWaitNotificationRequired()
{
#if FEATURE_SYNCHRONIZATIONCONTEXT_WAIT
// Method called when the CLR does a wait operation
- [System.Security.SecurityCritical] // auto-generated_required
[CLSCompliant(false)]
[PrePrepareMethod]
public virtual int Wait(IntPtr[] waitHandles, bool waitAll, int millisecondsTimeout)
}
// Method that can be called by Wait overrides
- [System.Security.SecurityCritical] // auto-generated_required
[CLSCompliant(false)]
[PrePrepareMethod]
[ReliabilityContract(Consistency.WillNotCorruptState, Cer.MayFail)]
// Static helper to which the above method can delegate to in order to get the default
// COM behavior.
- [System.Security.SecurityCritical] // auto-generated_required
[CLSCompliant(false)]
[PrePrepareMethod]
[MethodImplAttribute(MethodImplOptions.InternalCall)]
private static extern int WaitHelperNative(IntPtr[] waitHandles, bool waitAll, int millisecondsTimeout);
#endif
-#if FEATURE_CORECLR
-
- [System.Security.SecurityCritical]
public static void SetSynchronizationContext(SynchronizationContext syncContext)
{
Thread.CurrentThread.SynchronizationContext = syncContext;
}
- [System.Security.SecurityCritical]
public static void SetThreadStaticContext(SynchronizationContext syncContext)
{
Thread.CurrentThread.SynchronizationContext = syncContext;
}
}
-#else //FEATURE_CORECLR
-
- // set SynchronizationContext on the current thread
- [System.Security.SecurityCritical] // auto-generated_required
- public static void SetSynchronizationContext(SynchronizationContext syncContext)
- {
- ExecutionContext ec = Thread.CurrentThread.GetMutableExecutionContext();
- ec.SynchronizationContext = syncContext;
- ec.SynchronizationContextNoFlow = syncContext;
- }
-
- // Get the current SynchronizationContext on the current thread
- public static SynchronizationContext Current
- {
- get
- {
- return Thread.CurrentThread.GetExecutionContextReader().SynchronizationContext ?? GetThreadLocalContext();
- }
- }
-
- // Get the last SynchronizationContext that was set explicitly (not flowed via ExecutionContext.Capture/Run)
- internal static SynchronizationContext CurrentNoFlow
- {
- [FriendAccessAllowed]
- get
- {
- return Thread.CurrentThread.GetExecutionContextReader().SynchronizationContextNoFlow ?? GetThreadLocalContext();
- }
- }
-
- private static SynchronizationContext GetThreadLocalContext()
- {
- SynchronizationContext context = null;
-
-#if FEATURE_APPX
- if (context == null && AppDomain.IsAppXModel())
- context = GetWinRTContext();
-#endif
-
- return context;
- }
-
-#endif //FEATURE_CORECLR
-
#if FEATURE_APPX
- [SecuritySafeCritical]
private static SynchronizationContext GetWinRTContext()
{
- Contract.Assert(Environment.IsWinRTSupported);
- Contract.Assert(AppDomain.IsAppXModel());
+ Debug.Assert(Environment.IsWinRTSupported);
+ Debug.Assert(AppDomain.IsAppXModel());
//
// We call into the VM to get the dispatcher. This is because:
return null;
}
- [SecurityCritical]
static WinRTSynchronizationContextFactoryBase s_winRTContextFactory;
- [SecurityCritical]
private static WinRTSynchronizationContextFactoryBase GetWinRTSynchronizationContextFactory()
{
//
}
[DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
- [SecurityCritical]
[SuppressUnmanagedCodeSecurity]
[return: MarshalAs(UnmanagedType.Interface)]
private static extern object GetWinRTDispatcherForCurrentThread();
}
#if FEATURE_SYNCHRONIZATIONCONTEXT_WAIT
- [System.Security.SecurityCritical] // auto-generated
private static int InvokeWaitMethodHelper(SynchronizationContext syncContext, IntPtr[] waitHandles, bool waitAll, int millisecondsTimeout)
{
return syncContext.Wait(waitHandles, waitAll, millisecondsTimeout);
private static Loggers f_LoggingOn; //assumes false by default
// The precise static constructor will run first time somebody attempts to access this class
- [SecuritySafeCritical]
static AsyncCausalityTracer()
{
if (!Environment.IsWinRTSupported) return;
s_TracerFactory = (WFD.IAsyncCausalityTracerStatics)factory;
EventRegistrationToken token = s_TracerFactory.add_TracingStatusChanged(new EventHandler<WFD.TracingStatusChangedEventArgs>(TracingStatusChangedHandler));
- Contract.Assert(token != default(EventRegistrationToken), "EventRegistrationToken is null");
+ Debug.Assert(token != default(EventRegistrationToken), "EventRegistrationToken is null");
}
catch (Exception ex)
{
}
- [SecuritySafeCritical]
private static void TracingStatusChangedHandler(Object sender, WFD.TracingStatusChangedEventArgs args)
{
if (args.Enabled)
// See the LICENSE file in the project root for more information.
using System;
+using System.Diagnostics;
using System.Diagnostics.Contracts;
using System.IO;
using System.Runtime.CompilerServices;
/// It expects that an BeginEndAwaitableAdapter instance was supplied to the APM Begin method as the object state.</summary>
public readonly static AsyncCallback Callback = (asyncResult) => {
- Contract.Assert(asyncResult != null);
- Contract.Assert(asyncResult.IsCompleted);
- Contract.Assert(asyncResult.AsyncState is BeginEndAwaitableAdapter);
+ Debug.Assert(asyncResult != null);
+ Debug.Assert(asyncResult.IsCompleted);
+ Debug.Assert(asyncResult.AsyncState is BeginEndAwaitableAdapter);
// Get the adapter object supplied as the "object state" to the Begin method
BeginEndAwaitableAdapter adapter = (BeginEndAwaitableAdapter) asyncResult.AsyncState;
Action continuation = Interlocked.Exchange(ref adapter._continuation, CALLBACK_RAN);
if (continuation != null) {
- Contract.Assert(continuation != CALLBACK_RAN);
+ Debug.Assert(continuation != CALLBACK_RAN);
continuation();
}
};
/// <summary>Schedules the continuation to run when the operation completes.</summary>
/// <param name="continuation">The continuation.</param>
- [SecurityCritical]
public void UnsafeOnCompleted(Action continuation) {
- Contract.Assert(continuation != null);
+ Debug.Assert(continuation != null);
OnCompleted(continuation);
}
/// <param name="continuation">The continuation.</param>
public void OnCompleted(Action continuation) {
- Contract.Assert(continuation != null);
+ Debug.Assert(continuation != null);
// If the continuation field is null, then set it to be the target continuation
// so that when the operation completes, it'll invoke the continuation. If it's non-null,
/// <returns>The IAsyncResult for the operation.</returns>
public IAsyncResult GetResult() {
- Contract.Assert(_asyncResult != null && _asyncResult.IsCompleted);
+ Debug.Assert(_asyncResult != null && _asyncResult.IsCompleted);
// Get the IAsyncResult
IAsyncResult result = _asyncResult;
/// Provides concurrent and exclusive task schedulers that coordinate to execute
/// tasks while ensuring that concurrent tasks may run concurrently and exclusive tasks never do.
/// </summary>
- [HostProtection(Synchronization = true, ExternalThreading = true)]
[DebuggerDisplay("Concurrent={ConcurrentTaskCountForDebugger}, Exclusive={ExclusiveTaskCountForDebugger}, Mode={ModeForDebugger}")]
[DebuggerTypeProxy(typeof(ConcurrentExclusiveSchedulerPair.DebugView))]
public class ConcurrentExclusiveSchedulerPair
ThreadPool.QueueUserWorkItem(state =>
{
var localCs = (CompletionState)state; // don't use 'cs', as it'll force a closure
- Contract.Assert(!localCs.Task.IsCompleted, "Completion should only happen once.");
+ Debug.Assert(!localCs.Task.IsCompleted, "Completion should only happen once.");
var exceptions = localCs.m_exceptions;
bool success = (exceptions != null && exceptions.Count > 0) ?
localCs.TrySetException(exceptions) :
localCs.TrySetResult(default(VoidTaskResult));
- Contract.Assert(success, "Expected to complete completion task.");
+ Debug.Assert(success, "Expected to complete completion task.");
}, cs);
}
}
// Check to see if all tasks have completed and if completion has been requested.
CleanupStateIfCompletingAndQuiesced();
}
- else Contract.Assert(m_processingCount == EXCLUSIVE_PROCESSING_SENTINEL, "The processing count must be the sentinel if it's not >= 0.");
+ else Debug.Assert(m_processingCount == EXCLUSIVE_PROCESSING_SENTINEL, "The processing count must be the sentinel if it's not >= 0.");
}
/// <summary>
try
{
// Note that we're processing exclusive tasks on the current thread
- Contract.Assert(!m_threadProcessingMapping.ContainsKey(Thread.CurrentThread.ManagedThreadId),
+ Debug.Assert(!m_threadProcessingMapping.ContainsKey(Thread.CurrentThread.ManagedThreadId),
"This thread should not yet be involved in this pair's processing.");
m_threadProcessingMapping[Thread.CurrentThread.ManagedThreadId] = ProcessingMode.ProcessingExclusiveTask;
// We're no longer processing exclusive tasks on the current thread
ProcessingMode currentMode;
m_threadProcessingMapping.TryRemove(Thread.CurrentThread.ManagedThreadId, out currentMode);
- Contract.Assert(currentMode == ProcessingMode.ProcessingExclusiveTask,
+ Debug.Assert(currentMode == ProcessingMode.ProcessingExclusiveTask,
"Somehow we ended up escaping exclusive mode.");
lock (ValueLock)
// There might be more concurrent tasks available, for example, if concurrent tasks arrived
// after we exited the loop, or if we exited the loop while concurrent tasks were still
// available but we hit our maxItemsPerTask limit.
- Contract.Assert(m_processingCount == EXCLUSIVE_PROCESSING_SENTINEL, "The processing mode should not have deviated from exclusive.");
+ Debug.Assert(m_processingCount == EXCLUSIVE_PROCESSING_SENTINEL, "The processing mode should not have deviated from exclusive.");
m_processingCount = 0;
ProcessAsyncIfNecessary(true);
}
try
{
// Note that we're processing concurrent tasks on the current thread
- Contract.Assert(!m_threadProcessingMapping.ContainsKey(Thread.CurrentThread.ManagedThreadId),
+ Debug.Assert(!m_threadProcessingMapping.ContainsKey(Thread.CurrentThread.ManagedThreadId),
"This thread should not yet be involved in this pair's processing.");
m_threadProcessingMapping[Thread.CurrentThread.ManagedThreadId] = ProcessingMode.ProcessingConcurrentTasks;
// We're no longer processing concurrent tasks on the current thread
ProcessingMode currentMode;
m_threadProcessingMapping.TryRemove(Thread.CurrentThread.ManagedThreadId, out currentMode);
- Contract.Assert(currentMode == ProcessingMode.ProcessingConcurrentTasks,
+ Debug.Assert(currentMode == ProcessingMode.ProcessingConcurrentTasks,
"Somehow we ended up escaping concurrent mode.");
lock (ValueLock)
// There might be more concurrent tasks available, for example, if concurrent tasks arrived
// after we exited the loop, or if we exited the loop while concurrent tasks were still
// available but we hit our maxItemsPerTask limit.
- Contract.Assert(m_processingCount > 0, "The procesing mode should not have deviated from concurrent.");
+ Debug.Assert(m_processingCount > 0, "The procesing mode should not have deviated from concurrent.");
if (m_processingCount > 0) --m_processingCount;
ProcessAsyncIfNecessary(true);
}
/// <summary>Queues a task to the scheduler.</summary>
/// <param name="task">The task to be queued.</param>
- [SecurityCritical]
protected internal override void QueueTask(Task task)
{
- Contract.Assert(task != null, "Infrastructure should have provided a non-null task.");
+ Debug.Assert(task != null, "Infrastructure should have provided a non-null task.");
lock (m_pair.ValueLock)
{
// If the scheduler has already had completion requested, no new work is allowed to be scheduled
/// <summary>Executes a task on this scheduler.</summary>
/// <param name="task">The task to be executed.</param>
- [SecuritySafeCritical]
internal void ExecuteTask(Task task)
{
- Contract.Assert(task != null, "Infrastructure should have provided a non-null task.");
+ Debug.Assert(task != null, "Infrastructure should have provided a non-null task.");
base.TryExecuteTask(task);
}
/// <param name="task">The task to execute.</param>
/// <param name="taskWasPreviouslyQueued">Whether the task was previously queued to the scheduler.</param>
/// <returns>true if the task could be executed; otherwise, false.</returns>
- [SecurityCritical]
protected override bool TryExecuteTaskInline(Task task, bool taskWasPreviouslyQueued)
{
- Contract.Assert(task != null, "Infrastructure should have provided a non-null task.");
+ Debug.Assert(task != null, "Infrastructure should have provided a non-null task.");
// If the scheduler has had completion requested, no new work is allowed to be scheduled.
// A non-locked read on m_completionRequested (in CompletionRequested) is acceptable here because:
}
catch
{
- Contract.Assert(t.IsFaulted, "Task should be faulted due to the scheduler faulting it and throwing the exception.");
+ Debug.Assert(t.IsFaulted, "Task should be faulted due to the scheduler faulting it and throwing the exception.");
var ignored = t.Exception;
throw;
}
/// This method is separated out not because of performance reasons but so that
/// the SecuritySafeCritical attribute may be employed.
/// </remarks>
- [SecuritySafeCritical]
private static bool TryExecuteTaskShim(object state)
{
var tuple = (Tuple<ConcurrentExclusiveTaskScheduler, Task>)state;
/// <summary>Gets for debugging purposes the tasks scheduled to this scheduler.</summary>
/// <returns>An enumerable of the tasks queued.</returns>
- [SecurityCritical]
protected override IEnumerable<Task> GetScheduledTasks() { return m_tasks; }
/// <summary>Gets the number of tasks queued to this scheduler.</summary>
exceptionThrown = false;
}
catch (SynchronizationLockException) { exceptionThrown = true; }
- Contract.Assert(held == !exceptionThrown, "The locking scheme was not correctly followed.");
+ Debug.Assert(held == !exceptionThrown, "The locking scheme was not correctly followed.");
}
#endif
#else
- Contract.Assert(Monitor.IsEntered(syncObj) == held, "The locking scheme was not correctly followed.");
+ Debug.Assert(Monitor.IsEntered(syncObj) == held, "The locking scheme was not correctly followed.");
#endif
}
using System.Security.Permissions;
using System.Runtime.CompilerServices;
using System.Threading;
+using System.Diagnostics;
using System.Diagnostics.Contracts;
using System.Runtime.Versioning;
/// <see cref="System.Threading.Tasks.Task{TResult}.Factory">Task{TResult}.Factory</see> property.
/// </para>
/// </remarks>
- [HostProtection(Synchronization = true, ExternalThreading = true)]
public class TaskFactory<TResult>
{
// Member variables, DefaultScheduler, other properties and ctors
}, state);
if (asyncResult.CompletedSynchronously)
{
- Contract.Assert(asyncResult.IsCompleted, "If the operation completed synchronously, it must be completed.");
+ Debug.Assert(asyncResult.IsCompleted, "If the operation completed synchronously, it must be completed.");
FromAsyncCoreLogic(asyncResult, endFunction, endAction, promise, requiresSynchronization: false);
}
}
}, state);
if (asyncResult.CompletedSynchronously)
{
- Contract.Assert(asyncResult.IsCompleted, "If the operation completed synchronously, it must be completed.");
+ Debug.Assert(asyncResult.IsCompleted, "If the operation completed synchronously, it must be completed.");
FromAsyncCoreLogic(asyncResult, endFunction, endAction, promise, requiresSynchronization: false);
}
}
}, state);
if (asyncResult.CompletedSynchronously)
{
- Contract.Assert(asyncResult.IsCompleted, "If the operation completed synchronously, it must be completed.");
+ Debug.Assert(asyncResult.IsCompleted, "If the operation completed synchronously, it must be completed.");
FromAsyncCoreLogic(asyncResult, endFunction, endAction, promise, requiresSynchronization: false);
}
}
}, state);
if (asyncResult.CompletedSynchronously)
{
- Contract.Assert(asyncResult.IsCompleted, "If the operation completed synchronously, it must be completed.");
+ Debug.Assert(asyncResult.IsCompleted, "If the operation completed synchronously, it must be completed.");
FromAsyncCoreLogic(asyncResult, endFunction, endAction, promise, requiresSynchronization: false);
}
}
where TInstance : class
{
// Validate arguments, but only with asserts, as this is an internal only implementation.
- Contract.Assert(thisRef != null, "Expected a non-null thisRef");
- Contract.Assert(beginMethod != null, "Expected a non-null beginMethod");
- Contract.Assert(endMethod != null, "Expected a non-null endMethod");
+ Debug.Assert(thisRef != null, "Expected a non-null thisRef");
+ Debug.Assert(beginMethod != null, "Expected a non-null beginMethod");
+ Debug.Assert(endMethod != null, "Expected a non-null endMethod");
// Create the promise and start the operation.
// No try/catch is necessary here as we want exceptions to bubble out, and because
// If it completed synchronously, we'll handle that here.
if (asyncResult.CompletedSynchronously)
{
- Contract.Assert(asyncResult.IsCompleted, "If the operation completed synchronously, it must be completed.");
+ Debug.Assert(asyncResult.IsCompleted, "If the operation completed synchronously, it must be completed.");
promise.Complete(thisRef, endMethod, asyncResult, requiresSynchronization: false);
}
TInstance thisRef, Func<TInstance, IAsyncResult, TResult> endMethod, IAsyncResult asyncResult,
bool requiresSynchronization)
{
- Contract.Assert(!IsCompleted, "The task should not have been completed yet.");
+ Debug.Assert(!IsCompleted, "The task should not have been completed yet.");
// Run the end method and complete the task
bool successfullySet = false;
{
successfullySet = TrySetException(exc);
}
- Contract.Assert(successfullySet, "Expected the task to not yet be completed");
+ Debug.Assert(successfullySet, "Expected the task to not yet be completed");
}
}
}
else
{
- Contract.Assert(continuationAction != null);
+ Debug.Assert(continuationAction != null);
return starter.ContinueWith<TResult>(
// use a cached delegate
}
else
{
- Contract.Assert(continuationAction != null);
+ Debug.Assert(continuationAction != null);
return starter.ContinueWith<TResult>(
//the following delegate avoids closure capture as much as possible
//completedTasks.Result == tasksCopy;
}
else
{
- Contract.Assert(continuationAction != null);
+ Debug.Assert(continuationAction != null);
return starter.ContinueWith<TResult>(
//the following delegate avoids closure capture as much as possible
//completedTask.Result is the winning task; state == continuationAction
}
else
{
- Contract.Assert(continuationAction != null);
+ Debug.Assert(continuationAction != null);
return starter.ContinueWith<TResult>(
// Use a cached delegate
GenericDelegateCache<TAntecedentResult,TResult>.CWAnyActionDelegate,
/// The <see cref="T:System.Threading.Tasks.Parallel"/> class provides library-based data parallel replacements
/// for common operations such as for loops, for each loops, and execution of a set of statements.
/// </remarks>
- [HostProtection(Synchronization = true, ExternalThreading = true)]
public static class Parallel
{
// static counter for generating unique Fork/Join Context IDs to be used in ETW events
Func<int, ParallelLoopState, TLocal, TLocal> bodyWithLocal,
Func<TLocal> localInit, Action<TLocal> localFinally)
{
- Contract.Assert(((body == null ? 0 : 1) + (bodyWithState == null ? 0 : 1) + (bodyWithLocal == null ? 0 : 1)) == 1,
+ Debug.Assert(((body == null ? 0 : 1) + (bodyWithState == null ? 0 : 1) + (bodyWithLocal == null ? 0 : 1)) == 1,
"expected exactly one body function to be supplied");
- Contract.Assert(bodyWithLocal != null || (localInit == null && localFinally == null),
+ Debug.Assert(bodyWithLocal != null || (localInit == null && localFinally == null),
"thread local functions should only be supplied for loops w/ thread local bodies");
// Instantiate our result. Specifics will be filled in later.
if (bodyWithState != null)
{
- Contract.Assert(sharedPStateFlags != null);
+ Debug.Assert(sharedPStateFlags != null);
state = new ParallelLoopState32(sharedPStateFlags);
}
else if (bodyWithLocal != null)
{
- Contract.Assert(sharedPStateFlags != null);
+ Debug.Assert(sharedPStateFlags != null);
state = new ParallelLoopState32(sharedPStateFlags);
if (localInit != null)
{
Func<long, ParallelLoopState, TLocal, TLocal> bodyWithLocal,
Func<TLocal> localInit, Action<TLocal> localFinally)
{
- Contract.Assert(((body == null ? 0 : 1) + (bodyWithState == null ? 0 : 1) + (bodyWithLocal == null ? 0 : 1)) == 1,
+ Debug.Assert(((body == null ? 0 : 1) + (bodyWithState == null ? 0 : 1) + (bodyWithLocal == null ? 0 : 1)) == 1,
"expected exactly one body function to be supplied");
- Contract.Assert(bodyWithLocal != null || (localInit == null && localFinally == null),
+ Debug.Assert(bodyWithLocal != null || (localInit == null && localFinally == null),
"thread local functions should only be supplied for loops w/ thread local bodies");
// Instantiate our result. Specifics will be filled in later.
if (bodyWithState != null)
{
- Contract.Assert(sharedPStateFlags != null);
+ Debug.Assert(sharedPStateFlags != null);
state = new ParallelLoopState64(sharedPStateFlags);
}
else if (bodyWithLocal != null)
{
- Contract.Assert(sharedPStateFlags != null);
+ Debug.Assert(sharedPStateFlags != null);
state = new ParallelLoopState64(sharedPStateFlags);
// If a thread-local selector was supplied, invoke it. Otherwise, use the default.
Func<TSource, ParallelLoopState, long, TLocal, TLocal> bodyWithEverything,
Func<TLocal> localInit, Action<TLocal> localFinally)
{
- Contract.Assert(((body == null ? 0 : 1) + (bodyWithState == null ? 0 : 1) +
+ Debug.Assert(((body == null ? 0 : 1) + (bodyWithState == null ? 0 : 1) +
(bodyWithStateAndIndex == null ? 0 : 1) + (bodyWithStateAndLocal == null ? 0 : 1) + (bodyWithEverything == null ? 0 : 1)) == 1,
"expected exactly one body function to be supplied");
- Contract.Assert((bodyWithStateAndLocal != null) || (bodyWithEverything != null) || (localInit == null && localFinally == null),
+ Debug.Assert((bodyWithStateAndLocal != null) || (bodyWithEverything != null) || (localInit == null && localFinally == null),
"thread local functions should only be supplied for loops w/ thread local bodies");
// Before getting started, do a quick peek to see if we have been canceled already
Func<TSource, ParallelLoopState, long, TLocal, TLocal> bodyWithEverything,
Func<TLocal> localInit, Action<TLocal> localFinally)
{
- Contract.Assert(array != null);
- Contract.Assert(parallelOptions != null, "ForEachWorker(array): parallelOptions is null");
+ Debug.Assert(array != null);
+ Debug.Assert(parallelOptions != null, "ForEachWorker(array): parallelOptions is null");
int from = array.GetLowerBound(0);
int to = array.GetUpperBound(0) + 1;
Func<TSource, ParallelLoopState, long, TLocal, TLocal> bodyWithEverything,
Func<TLocal> localInit, Action<TLocal> localFinally)
{
- Contract.Assert(list != null);
- Contract.Assert(parallelOptions != null, "ForEachWorker(list): parallelOptions is null");
+ Debug.Assert(list != null);
+ Debug.Assert(parallelOptions != null, "ForEachWorker(list): parallelOptions is null");
if (body != null)
{
Func<TLocal> localInit,
Action<TLocal> localFinally)
{
- Contract.Assert(((simpleBody == null ? 0 : 1) + (bodyWithState == null ? 0 : 1) +
+ Debug.Assert(((simpleBody == null ? 0 : 1) + (bodyWithState == null ? 0 : 1) +
(bodyWithStateAndIndex == null ? 0 : 1) + (bodyWithStateAndLocal == null ? 0 : 1) + (bodyWithEverything == null ? 0 : 1)) == 1,
"PartitionForEach: expected exactly one body function to be supplied");
- Contract.Assert((bodyWithStateAndLocal != null) || (bodyWithEverything != null) || (localInit == null && localFinally == null),
+ Debug.Assert((bodyWithStateAndLocal != null) || (bodyWithEverything != null) || (localInit == null && localFinally == null),
"PartitionForEach: thread local functions should only be supplied for loops w/ thread local bodies");
OrderablePartitioner<TSource> orderedSource = source as OrderablePartitioner<TSource>;
- Contract.Assert((orderedSource != null) || (bodyWithStateAndIndex == null && bodyWithEverything == null),
+ Debug.Assert((orderedSource != null) || (bodyWithStateAndIndex == null && bodyWithEverything == null),
"PartitionForEach: bodies with indices are only allowable for OrderablePartitioner");
if (!source.SupportsDynamicPartitions)
else if (bodyWithStateAndLocal != null)
localValue = bodyWithStateAndLocal(t, state, localValue);
else
- Contract.Assert(false, "PartitionerForEach: illegal body type in Partitioner handler");
+ Debug.Assert(false, "PartitionerForEach: illegal body type in Partitioner handler");
// Any break, stop or exception causes us to halt
public bool LimitExceeded()
{
- Contract.Assert(m_timeLimit != 0, "Probably the default initializer for LoopTimer was used somewhere");
+ Debug.Assert(m_timeLimit != 0, "Probably the default initializer for LoopTimer was used somewhere");
// comparing against the next expected time saves an addition operation here
// Also we omit the comparison for wrap around here. The only side effect is one extra early yield every 38 days.
/// Enables iterations of <see cref="T:System.Threading.Tasks.Parallel"/> loops to interact with
/// other iterations.
/// </summary>
- [HostProtection(Synchronization = true, ExternalThreading = true)]
[DebuggerDisplay("ShouldExitCurrentIteration = {ShouldExitCurrentIteration}")]
public class ParallelLoopState
{
{
get
{
- Contract.Assert(false);
+ Debug.Assert(false);
throw new NotSupportedException(
Environment.GetResourceString("ParallelState_NotSupportedException_UnsupportedMethod"));
}
{
get
{
- Contract.Assert(false);
+ Debug.Assert(false);
throw new NotSupportedException(
Environment.GetResourceString("ParallelState_NotSupportedException_UnsupportedMethod"));
}
// Internal/virtual support for Break().
internal virtual void InternalBreak()
{
- Contract.Assert(false);
+ Debug.Assert(false);
throw new NotSupportedException(
Environment.GetResourceString("ParallelState_NotSupportedException_UnsupportedMethod"));
}
using System;
using System.Threading;
+using System.Diagnostics;
using System.Diagnostics.Contracts;
#pragma warning disable 0420
bool bRetVal = FindNewWork(out nFromInclusiveLocal, out nToExclusiveLocal);
- Contract.Assert((nFromInclusiveLocal <= Int32.MaxValue) && (nFromInclusiveLocal >= Int32.MinValue) &&
+ Debug.Assert((nFromInclusiveLocal <= Int32.MaxValue) && (nFromInclusiveLocal >= Int32.MinValue) &&
(nToExclusiveLocal <= Int32.MaxValue) && (nToExclusiveLocal >= Int32.MinValue));
// convert to 32 bit before returning
//
// find the actual number of index ranges we will need
//
- Contract.Assert((uSpan / uRangeSize) < Int32.MaxValue);
+ Debug.Assert((uSpan / uRangeSize) < Int32.MaxValue);
int nNumRanges = (int)(uSpan / uRangeSize);
nCurrentIndex > nToExclusive)
{
// this should only happen at the last index
- Contract.Assert(i == nNumRanges - 1);
+ Debug.Assert(i == nNumRanges - 1);
nCurrentIndex = nToExclusive;
}
/// </summary>
internal RangeWorker RegisterNewWorker()
{
- Contract.Assert(m_indexRanges != null && m_indexRanges.Length != 0);
+ Debug.Assert(m_indexRanges != null && m_indexRanges.Length != 0);
int nInitialRange = (Interlocked.Increment(ref m_nCurrentIndexRangeToAssign) - 1) % m_indexRanges.Length;
internal SingleProducerSingleConsumerQueue()
{
// Validate constants in ctor rather than in an explicit cctor that would cause perf degradation
- Contract.Assert(INIT_SEGMENT_SIZE > 0, "Initial segment size must be > 0.");
- Contract.Assert((INIT_SEGMENT_SIZE & (INIT_SEGMENT_SIZE - 1)) == 0, "Initial segment size must be a power of 2");
- Contract.Assert(INIT_SEGMENT_SIZE <= MAX_SEGMENT_SIZE, "Initial segment size should be <= maximum.");
- Contract.Assert(MAX_SEGMENT_SIZE < Int32.MaxValue / 2, "Max segment size * 2 must be < Int32.MaxValue, or else overflow could occur.");
+ Debug.Assert(INIT_SEGMENT_SIZE > 0, "Initial segment size must be > 0.");
+ Debug.Assert((INIT_SEGMENT_SIZE & (INIT_SEGMENT_SIZE - 1)) == 0, "Initial segment size must be a power of 2");
+ Debug.Assert(INIT_SEGMENT_SIZE <= MAX_SEGMENT_SIZE, "Initial segment size should be <= maximum.");
+ Debug.Assert(MAX_SEGMENT_SIZE < Int32.MaxValue / 2, "Max segment size * 2 must be < Int32.MaxValue, or else overflow could occur.");
// Initialize the queue
m_head = m_tail = new Segment(INIT_SEGMENT_SIZE);
}
int newSegmentSize = m_tail.m_array.Length << 1; // double size
- Contract.Assert(newSegmentSize > 0, "The max size should always be small enough that we don't overflow.");
+ Debug.Assert(newSegmentSize > 0, "The max size should always be small enough that we don't overflow.");
if (newSegmentSize > MAX_SEGMENT_SIZE) newSegmentSize = MAX_SEGMENT_SIZE;
var newSegment = new Segment(newSegmentSize);
/// <remarks>The Count is not thread safe, so we need to acquire the lock.</remarks>
int IProducerConsumerQueue<T>.GetCountSafe(object syncObj)
{
- Contract.Assert(syncObj != null, "The syncObj parameter is null.");
+ Debug.Assert(syncObj != null, "The syncObj parameter is null.");
lock (syncObj)
{
return Count;
/// <param name="OperationType">The kind of fork/join operation.</param>
/// <param name="InclusiveFrom">The lower bound of the loop.</param>
/// <param name="ExclusiveTo">The upper bound of the loop.</param>
- [SecuritySafeCritical]
[Event(PARALLELLOOPBEGIN_ID, Level = EventLevel.Informational, ActivityOptions=EventActivityOptions.Recursive,
Task = TplEtwProvider.Tasks.Loop, Opcode = EventOpcode.Start)]
public void ParallelLoopBegin(
/// <param name="OriginatingTaskID">The task ID.</param>
/// <param name="ForkJoinContextID">The loop ID.</param>
/// <param name="TotalIterations">the total number of iterations processed.</param>
- [SecuritySafeCritical]
[Event(PARALLELLOOPEND_ID, Level = EventLevel.Informational, Task = TplEtwProvider.Tasks.Loop, Opcode = EventOpcode.Stop)]
public void ParallelLoopEnd(
int OriginatingTaskSchedulerID, int OriginatingTaskID, // PFX_COMMON_EVENT_HEADER
/// <param name="ForkJoinContextID">The invoke ID.</param>
/// <param name="OperationType">The kind of fork/join operation.</param>
/// <param name="ActionCount">The number of actions being invoked.</param>
- [SecuritySafeCritical]
[Event(PARALLELINVOKEBEGIN_ID, Level = EventLevel.Informational, ActivityOptions=EventActivityOptions.Recursive,
Task = TplEtwProvider.Tasks.Invoke, Opcode = EventOpcode.Start)]
public void ParallelInvokeBegin(
/// <param name="TaskID">The task ID.</param>
/// <param name="CreatingTaskID">The task ID</param>
/// <param name="TaskCreationOptions">The options used to create the task.</param>
- [SecuritySafeCritical]
[Event(TASKSCHEDULED_ID, Task = Tasks.TaskScheduled, Version=1, Opcode = EventOpcode.Send,
Level = EventLevel.Informational, Keywords = Keywords.TaskTransfer|Keywords.Tasks)]
public void TaskScheduled(
/// <param name="OriginatingTaskID">The task ID.</param>
/// <param name="TaskID">The task ID.</param>
/// <param name="IsExceptional">Whether the task completed due to an error.</param>
- [SecuritySafeCritical]
[Event(TASKCOMPLETED_ID, Version=1,
Level = EventLevel.Informational, Keywords = Keywords.TaskStops)]
public void TaskCompleted(
/// <param name="ContinueWithTaskID">If known, if 'TaskID' has a 'continueWith' task, mention give its ID here.
/// 0 means unknown. This allows better visualization of the common sequential chaining case.</param>
/// </summary>
- [SecuritySafeCritical]
[Event(TASKWAITBEGIN_ID, Version=3, Task = TplEtwProvider.Tasks.TaskWait, Opcode = EventOpcode.Send,
Level = EventLevel.Informational, Keywords = Keywords.TaskTransfer|Keywords.Tasks)]
public void TaskWaitBegin(
/// <param name="OriginatingTaskSchedulerID">The scheduler ID.</param>
/// <param name="OriginatingTaskID">The task ID.</param>
/// <param name="TaskID">The activityId for the continuation.</param>
- [SecuritySafeCritical]
[Event(AWAITTASKCONTINUATIONSCHEDULED_ID, Task = Tasks.AwaitTaskContinuationScheduled, Opcode = EventOpcode.Send,
Level = EventLevel.Informational, Keywords = Keywords.TaskTransfer|Keywords.Tasks)]
public void AwaitTaskContinuationScheduled(
}
}
- [SecuritySafeCritical]
[Event(TRACEOPERATIONSTART_ID, Version=1,
Level = EventLevel.Informational, Keywords = Keywords.AsyncCausalityOperation)]
public void TraceOperationBegin(int TaskID, string OperationName, long RelatedContext)
}
}
- [SecuritySafeCritical]
[Event(TRACEOPERATIONRELATION_ID, Version=1,
Level = EventLevel.Informational, Keywords = Keywords.AsyncCausalityRelation)]
public void TraceOperationRelation(int TaskID, CausalityRelation Relation)
WriteEvent(TRACEOPERATIONRELATION_ID, TaskID,(int) Relation); // optmized overload for this exists
}
- [SecuritySafeCritical]
[Event(TRACEOPERATIONSTOP_ID, Version=1,
Level = EventLevel.Informational, Keywords = Keywords.AsyncCausalityOperation)]
public void TraceOperationEnd(int TaskID, AsyncCausalityStatus Status)
WriteEvent(TRACEOPERATIONSTOP_ID, TaskID,(int) Status); // optmized overload for this exists
}
- [SecuritySafeCritical]
[Event(TRACESYNCHRONOUSWORKSTART_ID, Version=1,
Level = EventLevel.Informational, Keywords = Keywords.AsyncCausalitySynchronousWork)]
public void TraceSynchronousWorkBegin(int TaskID, CausalitySynchronousWork Work)
WriteEvent(TRACESYNCHRONOUSWORKSTART_ID, TaskID,(int) Work); // optmized overload for this exists
}
- [SecuritySafeCritical]
[Event(TRACESYNCHRONOUSWORKSTOP_ID, Version=1,
Level = EventLevel.Informational, Keywords = Keywords.AsyncCausalitySynchronousWork)]
public void TraceSynchronousWorkEnd(CausalitySynchronousWork Work)
/// InternalWait method serves a potential marker for when a Task is entering a wait operation.
/// </para>
/// </remarks>
- [HostProtection(Synchronization = true, ExternalThreading = true)]
[DebuggerTypeProxy(typeof(SystemThreadingTasks_TaskDebugView))]
[DebuggerDisplay("Id = {Id}, Status = {Status}, Method = {DebuggerDisplayMethodDescription}")]
public class Task : IThreadPoolWorkItem, IAsyncResult, IDisposable
// (action,TCO). It should always be true.
internal Task(object state, TaskCreationOptions creationOptions, bool promiseStyle)
{
- Contract.Assert(promiseStyle, "Promise CTOR: promiseStyle was false");
+ Debug.Assert(promiseStyle, "Promise CTOR: promiseStyle was false");
// Check the creationOptions. We allow the AttachedToParent option to be specified for promise tasks.
// Also allow RunContinuationsAsynchronously because this is the constructor called by TCS
InternalTaskOptions.ContinuationTask |
InternalTaskOptions.LazyCancellation |
InternalTaskOptions.QueuedByRuntime));
- Contract.Assert(illegalInternalOptions == 0, "TaskConstructorCore: Illegal internal options");
+ Debug.Assert(illegalInternalOptions == 0, "TaskConstructorCore: Illegal internal options");
#endif
// Throw exception if the user specifies both LongRunning and SelfReplicating
}
// Assign options to m_stateAndOptionsFlag.
- Contract.Assert(m_stateFlags == 0, "TaskConstructorCore: non-zero m_stateFlags");
- Contract.Assert((((int)creationOptions) | OptionsMask) == OptionsMask, "TaskConstructorCore: options take too many bits");
+ Debug.Assert(m_stateFlags == 0, "TaskConstructorCore: non-zero m_stateFlags");
+ Debug.Assert((((int)creationOptions) | OptionsMask) == OptionsMask, "TaskConstructorCore: options take too many bits");
var tmpFlags = (int)creationOptions | (int)internalOptions;
if ((m_action == null) || ((internalOptions & InternalTaskOptions.ContinuationTask) != 0))
{
// we need to do this as the very last thing in the construction path, because the CT registration could modify m_stateFlags
if (cancellationToken.CanBeCanceled)
{
- Contract.Assert((internalOptions &
+ Debug.Assert((internalOptions &
(InternalTaskOptions.ChildReplica | InternalTaskOptions.SelfReplicating | InternalTaskOptions.ContinuationTask)) == 0,
"TaskConstructorCore: Did not expect to see cancelable token for replica/replicating or continuation task.");
antecedentTask.RemoveContinuation(continuation);
}
}
- Contract.Assert(targetTask != null,
+ Debug.Assert(targetTask != null,
"targetTask should have been non-null, with the supplied argument being a task or a tuple containing one");
targetTask.InternalCancel(false);
}
/// </summary>
/// <param name="stackMark">A stack crawl mark pointing to the frame of the caller.</param>
- [SecuritySafeCritical]
internal void PossiblyCaptureContext(ref StackCrawlMark stackMark)
{
- Contract.Assert(m_contingentProperties == null || m_contingentProperties.m_capturedContext == null,
+ Debug.Assert(m_contingentProperties == null || m_contingentProperties.m_capturedContext == null,
"Captured an ExecutionContext when one was already captured.");
// In the legacy .NET 3.5 build, we don't have the optimized overload of Capture()
// a read of the volatile m_stateFlags field.
internal static TaskCreationOptions OptionsMethod(int flags)
{
- Contract.Assert((OptionsMask & 1) == 1, "OptionsMask needs a shift in Options.get");
+ Debug.Assert((OptionsMask & 1) == 1, "OptionsMask needs a shift in Options.get");
return (TaskCreationOptions)(flags & OptionsMask);
}
/// <param name="enabled">true to set the bit; false to unset the bit.</param>
internal void SetNotificationForWaitCompletion(bool enabled)
{
- Contract.Assert((Options & (TaskCreationOptions)InternalTaskOptions.PromiseTask) != 0,
+ Debug.Assert((Options & (TaskCreationOptions)InternalTaskOptions.PromiseTask) != 0,
"Should only be used for promise-style tasks"); // hasn't been vetted on other kinds as there hasn't been a need
if (enabled)
// Atomically set the END_AWAIT_NOTIFICATION bit
bool success = AtomicStateUpdate(TASK_STATE_WAIT_COMPLETION_NOTIFICATION,
TASK_STATE_COMPLETED_MASK | TASK_STATE_COMPLETION_RESERVED);
- Contract.Assert(success, "Tried to set enabled on completed Task");
+ Debug.Assert(success, "Tried to set enabled on completed Task");
}
else
{
/// <returns>true if any of the tasks require notification; otherwise, false.</returns>
internal static bool AnyTaskRequiresNotifyDebuggerOfWaitCompletion(Task[] tasks)
{
- Contract.Assert(tasks != null, "Expected non-null array of tasks");
+ Debug.Assert(tasks != null, "Expected non-null array of tasks");
foreach (var task in tasks)
{
if (task != null &&
// bit was unset between the time that it was checked and this method was called.
// It's so remote a chance that it's worth having the assert to protect against misuse.
bool isWaitNotificationEnabled = IsWaitNotificationEnabled;
- Contract.Assert(isWaitNotificationEnabled, "Should only be called if the wait completion bit is set.");
+ Debug.Assert(isWaitNotificationEnabled, "Should only be called if the wait completion bit is set.");
return isWaitNotificationEnabled;
}
}
// It's theoretically possible but extremely rare that this assert could fire because the
// bit was unset between the time that it was checked and this method was called.
// It's so remote a chance that it's worth having the assert to protect against misuse.
- Contract.Assert(IsWaitNotificationEnabled, "Should only be called if the wait completion bit is set.");
+ Debug.Assert(IsWaitNotificationEnabled, "Should only be called if the wait completion bit is set.");
// Now that we're notifying the debugger, clear the bit. The debugger should do this anyway,
// but this adds a bit of protection in case it fails to, and given that the debugger is involved,
/// </summary>
internal void AddNewChild()
{
- Contract.Assert(Task.InternalCurrent == this || this.IsSelfReplicatingRoot, "Task.AddNewChild(): Called from an external context");
+ Debug.Assert(Task.InternalCurrent == this || this.IsSelfReplicatingRoot, "Task.AddNewChild(): Called from an external context");
var props = EnsureContingentPropertiesInitialized();
// We need to subtract that child from m_completionCountdown, or the parent will never complete.
internal void DisregardChild()
{
- Contract.Assert(Task.InternalCurrent == this, "Task.DisregardChild(): Called from an external context");
+ Debug.Assert(Task.InternalCurrent == this, "Task.DisregardChild(): Called from an external context");
var props = EnsureContingentPropertiesInitialized();
- Contract.Assert(props.m_completionCountdown >= 2, "Task.DisregardChild(): Expected parent count to be >= 2");
+ Debug.Assert(props.m_completionCountdown >= 2, "Task.DisregardChild(): Expected parent count to be >= 2");
Interlocked.Decrement(ref props.m_completionCountdown);
}
//
// Internal version of RunSynchronously that allows not waiting for completion.
//
- [SecuritySafeCritical] // Needed for QueueTask
internal void InternalRunSynchronously(TaskScheduler scheduler, bool waitForCompletion)
{
Contract.Requires(scheduler != null, "Task.InternalRunSynchronously(): null TaskScheduler");
// Mark ourselves as "handled" to avoid crashing the finalizer thread if the caller neglects to
// call Wait() on this task.
// m_contingentProperties.m_exceptionsHolder *should* already exist after AddException()
- Contract.Assert(
+ Debug.Assert(
(m_contingentProperties != null) &&
(m_contingentProperties.m_exceptionsHolder != null) &&
(m_contingentProperties.m_exceptionsHolder.ContainsFaultList),
}
else
{
- Contract.Assert((m_stateFlags & TASK_STATE_CANCELED) != 0, "Task.RunSynchronously: expected TASK_STATE_CANCELED to be set");
+ Debug.Assert((m_stateFlags & TASK_STATE_CANCELED) != 0, "Task.RunSynchronously: expected TASK_STATE_CANCELED to be set");
// Can't call this method on canceled task.
ThrowHelper.ThrowInvalidOperationException(ExceptionResource.Task_RunSynchronously_TaskCompleted);
}
// Only return an exception in faulted state (skip manufactured exceptions)
// A "benevolent" race condition makes it possible to return null when IsFaulted is
// true (i.e., if IsFaulted is set just after the check to IsFaulted above).
- Contract.Assert((e == null) || IsFaulted, "Task.Exception_get(): returning non-null value when not Faulted");
+ Debug.Assert((e == null) || IsFaulted, "Task.Exception_get(): returning non-null value when not Faulted");
return e;
}
/// underneath us. If false, TASK_STATE_STARTED bit is OR-ed right in. This
/// allows us to streamline things a bit for StartNew(), where competing cancellations
/// are not a problem.</param>
- [SecuritySafeCritical] // Needed for QueueTask
internal void ScheduleAndStart(bool needsProtection)
{
- Contract.Assert(m_taskScheduler != null, "expected a task scheduler to have been selected");
- Contract.Assert((m_stateFlags & TASK_STATE_STARTED) == 0, "task has already started");
+ Debug.Assert(m_taskScheduler != null, "expected a task scheduler to have been selected");
+ Debug.Assert((m_stateFlags & TASK_STATE_STARTED) == 0, "task has already started");
// Set the TASK_STATE_STARTED bit
if (needsProtection)
if ((Options & (TaskCreationOptions)InternalTaskOptions.ContinuationTask) == 0)
{
// m_contingentProperties.m_exceptionsHolder *should* already exist after AddException()
- Contract.Assert(
+ Debug.Assert(
(m_contingentProperties != null) &&
(m_contingentProperties.m_exceptionsHolder != null) &&
(m_contingentProperties.m_exceptionsHolder.ContainsFaultList),
var eoAsEdi = exceptionObject as ExceptionDispatchInfo;
var eoAsEnumerableEdi = exceptionObject as IEnumerable<ExceptionDispatchInfo>;
- Contract.Assert(
+ Debug.Assert(
eoAsException != null || eoAsEnumerableException != null || eoAsEdi != null || eoAsEnumerableEdi != null,
"Task.AddException: Expected an Exception, ExceptionDispatchInfo, or an IEnumerable<> of one of those");
var eoAsOce = exceptionObject as OperationCanceledException;
- Contract.Assert(
+ Debug.Assert(
!representsCancellation ||
eoAsOce != null ||
(eoAsEdi != null && eoAsEdi.SourceException is OperationCanceledException),
{
// There are exceptions; get the aggregate and optionally add the canceled
// exception to the aggregate (if applicable).
- Contract.Assert(m_contingentProperties != null); // ExceptionRecorded ==> m_contingentProperties != null
+ Debug.Assert(m_contingentProperties != null); // ExceptionRecorded ==> m_contingentProperties != null
// No need to lock around this, as other logic prevents the consumption of exceptions
// before they have been completely processed.
internal ReadOnlyCollection<ExceptionDispatchInfo> GetExceptionDispatchInfos()
{
bool exceptionsAvailable = IsFaulted && ExceptionRecorded;
- Contract.Assert(exceptionsAvailable, "Must only be used when the task has faulted with exceptions.");
+ Debug.Assert(exceptionsAvailable, "Must only be used when the task has faulted with exceptions.");
return exceptionsAvailable ?
m_contingentProperties.m_exceptionsHolder.GetExceptionDispatchInfos() :
new ReadOnlyCollection<ExceptionDispatchInfo>(new ExceptionDispatchInfo[0]);
/// <returns>The ExceptionDispatchInfo. May be null if no OCE was stored for the task.</returns>
internal ExceptionDispatchInfo GetCancellationExceptionDispatchInfo()
{
- Contract.Assert(IsCanceled, "Must only be used when the task has canceled.");
+ Debug.Assert(IsCanceled, "Must only be used when the task has canceled.");
return Volatile.Read(ref m_contingentProperties)?.m_exceptionsHolder?.GetCancellationExceptionDispatchInfo(); // may be null
}
Contract.Requires(childTask != null);
Contract.Requires(childTask.IsCompleted, "ProcessChildCompletion was called for an uncompleted task");
- Contract.Assert(childTask.m_contingentProperties?.m_parent == this, "ProcessChildCompletion should only be called for a child of this task");
+ Debug.Assert(childTask.m_contingentProperties?.m_parent == this, "ProcessChildCompletion should only be called for a child of this task");
var props = Volatile.Read(ref m_contingentProperties);
{
// Ensure any exceptions thrown by children are added to the parent.
// In doing this, we are implicitly marking children as being "handled".
- Contract.Assert(task.IsCompleted, "Expected all tasks in list to be completed");
+ Debug.Assert(task.IsCompleted, "Expected all tasks in list to be completed");
if (task.IsFaulted && !task.IsExceptionObservedByParent)
{
TaskExceptionHolder exceptionHolder = Volatile.Read(ref task.m_contingentProperties).m_exceptionsHolder;
- Contract.Assert(exceptionHolder != null);
+ Debug.Assert(exceptionHolder != null);
// No locking necessary since child task is finished adding exceptions
// and concurrent CreateExceptionObject() calls do not constitute
/// <param name="delegateRan">Whether the delegate was executed.</param>
internal void FinishThreadAbortedTask(bool bTAEAddedToExceptionHolder, bool delegateRan)
{
- Contract.Assert(!bTAEAddedToExceptionHolder || m_contingentProperties?.m_exceptionsHolder != null,
+ Debug.Assert(!bTAEAddedToExceptionHolder || m_contingentProperties?.m_exceptionsHolder != null,
"FinishThreadAbortedTask() called on a task whose exception holder wasn't initialized");
// this will only be false for non-root self replicating task copies, because all of their exceptions go to the root task.
/// IThreadPoolWorkItem override, which is the entry function for this task when the TP scheduler decides to run it.
///
/// </summary>
- [SecurityCritical]
void IThreadPoolWorkItem.ExecuteWorkItem()
{
ExecuteEntry(false);
/// The ThreadPool calls this if a ThreadAbortException is thrown while trying to execute this workitem. This may occur
/// before Task would otherwise be able to observe it.
/// </summary>
- [SecurityCritical]
void IThreadPoolWorkItem.MarkAborted(ThreadAbortException tae)
{
// If the task has marked itself as Completed, then it either a) already observed this exception (so we shouldn't handle it here)
/// </summary>
/// <param name="bPreventDoubleExecution"> Performs atomic updates to prevent double execution. Should only be set to true
/// in codepaths servicing user provided TaskSchedulers. The ConcRT or ThreadPool schedulers don't need this. </param>
- [SecuritySafeCritical]
internal bool ExecuteEntry(bool bPreventDoubleExecution)
{
if (bPreventDoubleExecution || ((Options & (TaskCreationOptions)InternalTaskOptions.SelfReplicating) != 0))
}
// A trick so we can refer to the TLS slot with a byref.
- [SecurityCritical]
private void ExecuteWithThreadLocal(ref Task currentTaskSlot)
{
// Remember the current task so we can restore it after running, and then
}
// Cached callback delegate that's lazily initialized due to ContextCallback being SecurityCritical
- [SecurityCritical]
private static ContextCallback s_ecCallback;
- [SecurityCritical]
private static void ExecutionContextCallback(object obj)
{
Task task = obj as Task;
- Contract.Assert(task != null, "expected a task object");
+ Debug.Assert(task != null, "expected a task object");
task.Execute();
}
internal virtual void InnerInvoke()
{
// Invoke the delegate
- Contract.Assert(m_action != null, "Null action in InnerInvoke()");
+ Debug.Assert(m_action != null, "Null action in InnerInvoke()");
var action = m_action as Action;
if (action != null)
{
actionWithState(m_stateObject);
return;
}
- Contract.Assert(false, "Invalid m_action in Task");
+ Debug.Assert(false, "Invalid m_action in Task");
}
/// <summary>
/// <param name="flowExecutionContext">Whether to flow ExecutionContext across the await.</param>
/// <param name="stackMark">A stack crawl mark tied to execution context.</param>
/// <exception cref="System.InvalidOperationException">The awaiter was not properly initialized.</exception>
- [SecurityCritical]
internal void SetContinuationForAwait(
Action continuationAction, bool continueOnCapturedContext, bool flowExecutionContext, ref StackCrawlMark stackMark)
{
}
else
{
- Contract.Assert(!flowExecutionContext, "We already determined we're not required to flow context.");
+ Debug.Assert(!flowExecutionContext, "We already determined we're not required to flow context.");
if (!AddTaskContinuation(continuationAction, addBeforeOthers: false))
AwaitTaskContinuation.UnsafeScheduleAction(continuationAction, this);
}
Wait(Timeout.Infinite, default(CancellationToken));
#if DEBUG
- Contract.Assert(waitResult, "expected wait to succeed");
+ Debug.Assert(waitResult, "expected wait to succeed");
#endif
}
ThrowIfExceptional(true);
}
- Contract.Assert((m_stateFlags & TASK_STATE_FAULTED) == 0, "Task.Wait() completing when in Faulted state.");
+ Debug.Assert((m_stateFlags & TASK_STATE_FAULTED) == 0, "Task.Wait() completing when in Faulted state.");
return true;
}
}
}
- Contract.Assert(IsCompleted || millisecondsTimeout != Timeout.Infinite);
+ Debug.Assert(IsCompleted || millisecondsTimeout != Timeout.Infinite);
// ETW event for Task Wait End
if (etwIsEnabled)
/// For custom schedulers we also attempt an atomic state transition.
/// </param>
/// <returns>true if the task was successfully canceled; otherwise, false.</returns>
- [SecuritySafeCritical]
internal bool InternalCancel(bool bCancelNonExecutingOnly)
{
Contract.Requires((Options & (TaskCreationOptions)InternalTaskOptions.PromiseTask) == 0, "Task.InternalCancel() did not expect promise-style task");
if (bPopSucceeded)
{
// hitting this would mean something wrong with the AtomicStateUpdate above
- Contract.Assert(!mustCleanup, "Possibly an invalid state transition call was made in InternalCancel()");
+ Debug.Assert(!mustCleanup, "Possibly an invalid state transition call was made in InternalCancel()");
// Include TASK_STATE_DELEGATE_INVOKED in "illegal" bits to protect against the situation where
// TS.TryDequeue() returns true but the task is still left on the queue.
{
RecordInternalCancellationRequest();
- Contract.Assert((Options & (TaskCreationOptions)InternalTaskOptions.PromiseTask) != 0, "Task.RecordInternalCancellationRequest(CancellationToken) only valid for promise-style task");
- Contract.Assert(m_contingentProperties.m_cancellationToken == default(CancellationToken));
+ Debug.Assert((Options & (TaskCreationOptions)InternalTaskOptions.PromiseTask) != 0, "Task.RecordInternalCancellationRequest(CancellationToken) only valid for promise-style task");
+ Debug.Assert(m_contingentProperties.m_cancellationToken == default(CancellationToken));
// Store the supplied cancellation token as this task's token.
// Waiting on this task will then result in an OperationCanceledException containing this token.
if (oce == null)
{
var edi = cancellationException as ExceptionDispatchInfo;
- Contract.Assert(edi != null, "Expected either an OCE or an EDI");
+ Debug.Assert(edi != null, "Expected either an OCE or an EDI");
oce = edi.SourceException as OperationCanceledException;
- Contract.Assert(oce != null, "Expected EDI to contain an OCE");
+ Debug.Assert(oce != null, "Expected EDI to contain an OCE");
}
- Contract.Assert(oce.CancellationToken == tokenToRecord,
+ Debug.Assert(oce.CancellationToken == tokenToRecord,
"Expected OCE's token to match the provided token.");
#endif
AddException(cancellationException, representsCancellation: true);
// And this method should be called at most once per task.
internal void CancellationCleanupLogic()
{
- Contract.Assert((m_stateFlags & (TASK_STATE_CANCELED | TASK_STATE_COMPLETION_RESERVED)) != 0, "Task.CancellationCleanupLogic(): Task not canceled or reserved.");
+ Debug.Assert((m_stateFlags & (TASK_STATE_CANCELED | TASK_STATE_COMPLETION_RESERVED)) != 0, "Task.CancellationCleanupLogic(): Task not canceled or reserved.");
// I'd like to do this, but there is a small window for a race condition. If someone calls Wait() between InternalCancel() and
// here, that will set m_completionEvent, leading to a meaningless/harmless assertion.
- //Contract.Assert((m_completionEvent == null) || !m_completionEvent.IsSet, "Task.CancellationCleanupLogic(): Completion event already set.");
+ //Debug.Assert((m_completionEvent == null) || !m_completionEvent.IsSet, "Task.CancellationCleanupLogic(): Completion event already set.");
// This may have been set already, but we need to make sure.
Interlocked.Exchange(ref m_stateFlags, m_stateFlags | TASK_STATE_CANCELED);
/// </summary>
private void SetCancellationAcknowledged()
{
- Contract.Assert(this == Task.InternalCurrent, "SetCancellationAcknowledged() should only be called while this is still the current task");
- Contract.Assert(IsCancellationRequested, "SetCancellationAcknowledged() should not be called if the task's CT wasn't signaled");
+ Debug.Assert(this == Task.InternalCurrent, "SetCancellationAcknowledged() should only be called while this is still the current task");
+ Debug.Assert(IsCancellationRequested, "SetCancellationAcknowledged() should not be called if the task's CT wasn't signaled");
m_stateFlags |= TASK_STATE_CANCELLATIONACKNOWLEDGED;
}
/// <summary>
/// Runs all of the continuations, as appropriate.
/// </summary>
- [SecuritySafeCritical] // for AwaitTaskContinuation.RunOrScheduleAction
internal void FinishContinuations()
{
// Atomically store the fact that this task is completing. From this point on, the adding of continuations will
// Otherwise, it must be an ITaskCompletionAction, so invoke it.
else
{
- Contract.Assert(currentContinuation is ITaskCompletionAction, "Expected continuation element to be Action, TaskContinuation, or ITaskContinuationAction");
+ Debug.Assert(currentContinuation is ITaskCompletionAction, "Expected continuation element to be Action, TaskContinuation, or ITaskContinuationAction");
var action = (ITaskCompletionAction)currentContinuation;
if (bCanInlineContinuations || !action.InvokeMayRunArbitraryCode)
// m_continuationObject is guaranteed at this point to be either a List or
// s_taskCompletionSentinel.
List<object> list = m_continuationObject as List<object>;
- Contract.Assert((list != null) || (m_continuationObject == s_taskCompletionSentinel),
+ Debug.Assert((list != null) || (m_continuationObject == s_taskCompletionSentinel),
"Expected m_continuationObject to be list or sentinel");
// If list is null, it can only mean that s_taskCompletionSentinel has been exchanged
WaitAll(tasks, Timeout.Infinite);
#if DEBUG
- Contract.Assert(waitResult, "expected wait to succeed");
+ Debug.Assert(waitResult, "expected wait to succeed");
#endif
}
// Now gather up and throw all of the exceptions.
foreach (var task in tasks) AddExceptionsForCompletedTask(ref exceptions, task);
- Contract.Assert(exceptions != null, "Should have seen at least one exception");
+ Debug.Assert(exceptions != null, "Should have seen at least one exception");
ThrowHelper.ThrowAggregateException(exceptions);
}
/// <returns>true if all of the tasks completed; otherwise, false.</returns>
private static bool WaitAllBlockingCore(List<Task> tasks, int millisecondsTimeout, CancellationToken cancellationToken)
{
- Contract.Assert(tasks != null, "Expected a non-null list of tasks");
- Contract.Assert(tasks.Count > 0, "Expected at least one task");
+ Debug.Assert(tasks != null, "Expected a non-null list of tasks");
+ Debug.Assert(tasks.Count > 0, "Expected at least one task");
bool waitCompleted = false;
var mres = new SetOnCountdownMres(tasks.Count);
internal SetOnCountdownMres(int count)
{
- Contract.Assert(count > 0, "Expected count > 0");
+ Debug.Assert(count > 0, "Expected count > 0");
_count = count;
}
public void Invoke(Task completingTask)
{
if (Interlocked.Decrement(ref _count) == 0) Set();
- Contract.Assert(_count >= 0, "Count should never go below 0");
+ Debug.Assert(_count >= 0, "Count should never go below 0");
}
public bool InvokeMayRunArbitraryCode { get { return false; } }
public static int WaitAny(params Task[] tasks)
{
int waitResult = WaitAny(tasks, Timeout.Infinite);
- Contract.Assert(tasks.Length == 0 || waitResult != -1, "expected wait to succeed");
+ Debug.Assert(tasks.Length == 0 || waitResult != -1, "expected wait to succeed");
return waitResult;
}
bool waitCompleted = firstCompleted.Wait(millisecondsTimeout, cancellationToken);
if (waitCompleted)
{
- Contract.Assert(firstCompleted.Status == TaskStatus.RanToCompletion);
+ Debug.Assert(firstCompleted.Status == TaskStatus.RanToCompletion);
signaledTaskIndex = Array.IndexOf(tasks, firstCompleted.Result);
- Contract.Assert(signaledTaskIndex >= 0);
+ Debug.Assert(signaledTaskIndex >= 0);
}
}
var task = new Task<TResult>();
bool succeeded = task.TrySetException(exception);
- Contract.Assert(succeeded, "This should always succeed on a new task.");
+ Debug.Assert(succeeded, "This should always succeed on a new task.");
return task;
}
var task = new Task<TResult>();
bool succeeded = task.TrySetCanceled(exception.CancellationToken, exception);
- Contract.Assert(succeeded, "This should always succeed on a new task.");
+ Debug.Assert(succeeded, "This should always succeed on a new task.");
return task;
}
for (int i = 0; i < m_tasks.Length; i++)
{
var task = m_tasks[i];
- Contract.Assert(task != null, "Constituent task in WhenAll should never be null");
+ Debug.Assert(task != null, "Constituent task in WhenAll should never be null");
if (task.IsFaulted)
{
if (observedExceptions != null)
{
- Contract.Assert(observedExceptions.Count > 0, "Expected at least one exception");
+ Debug.Assert(observedExceptions.Count > 0, "Expected at least one exception");
//We don't need to TraceOperationCompleted here because TrySetException will call Finish and we'll log it there
TrySetResult(default(VoidTaskResult));
}
}
- Contract.Assert(m_count >= 0, "Count should never go below 0");
+ Debug.Assert(m_count >= 0, "Count should never go below 0");
}
public bool InvokeMayRunArbitraryCode { get { return true; } }
for (int i = 0; i < m_tasks.Length; i++)
{
Task<T> task = m_tasks[i];
- Contract.Assert(task != null, "Constituent task in WhenAll should never be null");
+ Debug.Assert(task != null, "Constituent task in WhenAll should never be null");
if (task.IsFaulted)
{
}
else
{
- Contract.Assert(task.Status == TaskStatus.RanToCompletion);
+ Debug.Assert(task.Status == TaskStatus.RanToCompletion);
results[i] = task.GetResultCore(waitCompletionNotification: false); // avoid Result, which would triggering debug notification
}
if (observedExceptions != null)
{
- Contract.Assert(observedExceptions.Count > 0, "Expected at least one exception");
+ Debug.Assert(observedExceptions.Count > 0, "Expected at least one exception");
//We don't need to TraceOperationCompleted here because TrySetException will call Finish and we'll log it there
TrySetResult(results);
}
}
- Contract.Assert(m_count >= 0, "Count should never go below 0");
+ Debug.Assert(m_count >= 0, "Count should never go below 0");
}
public bool InvokeMayRunArbitraryCode { get { return true; } }
Task continuationTask = continuationObject as Task;
if (continuationTask != null)
{
- Contract.Assert(continuationTask.m_action == null);
+ Debug.Assert(continuationTask.m_action == null);
Delegate[] delegates = continuationTask.GetDelegateContinuationsForDebugger();
if (delegates != null)
return delegates;
m_completingTask = completingTask;
}
- [SecurityCritical]
void IThreadPoolWorkItem.ExecuteWorkItem()
{
m_action.Invoke(m_completingTask);
}
- [SecurityCritical]
void IThreadPoolWorkItem.MarkAborted(ThreadAbortException tae)
{
/* NOP */
// that can SO in 20 inlines on a typical 1MB stack size probably needs to be revisited anyway.
private const int MAX_UNCHECKED_INLINING_DEPTH = 20;
-#if !FEATURE_CORECLR
-
- private UInt64 m_lastKnownWatermark;
- private static int s_pageSize;
-
- // We are conservative here. We assume that the platform needs a whole 64KB to
- // respond to stack overflow. This means that for very small stacks (e.g. 128KB)
- // we'll fail a lot of stack checks incorrectly.
- private const long STACK_RESERVED_SPACE = 4096 * 16;
-
-#endif // !FEATURE_CORECLR
-
/// <summary>
/// This method needs to be called before attempting inline execution on the current thread.
/// If false is returned, it means we are too close to the end of the stack and should give up inlining.
/// Each call to TryBeginInliningScope() that returns true must be matched with a
/// call to EndInliningScope() regardless of whether inlining actually took place.
/// </summary>
- [SecuritySafeCritical]
internal bool TryBeginInliningScope()
{
// If we're still under the 'safe' limit we'll just skip the stack probe to save p/invoke calls
internal void EndInliningScope()
{
m_inliningDepth--;
- Contract.Assert(m_inliningDepth >= 0, "Inlining depth count should never go negative.");
+ Debug.Assert(m_inliningDepth >= 0, "Inlining depth count should never go negative.");
// do the right thing just in case...
if (m_inliningDepth < 0) m_inliningDepth = 0;
}
- [SecurityCritical]
private unsafe bool CheckForSufficientStack()
{
-#if FEATURE_CORECLR
return RuntimeHelpers.TryEnsureSufficientExecutionStack();
-#else
- // see if we already have the system page size info recorded
- int pageSize = s_pageSize;
- if (pageSize == 0)
- {
- // If not we need to query it from GetSystemInfo()
- // Note that this happens only once for the process lifetime
- Win32Native.SYSTEM_INFO sysInfo = new Win32Native.SYSTEM_INFO();
- Win32Native.GetSystemInfo(ref sysInfo);
-
- s_pageSize = pageSize = sysInfo.dwPageSize;
- }
-
- Win32Native.MEMORY_BASIC_INFORMATION stackInfo = new Win32Native.MEMORY_BASIC_INFORMATION();
-
- // We subtract one page for our request. VirtualQuery rounds UP to the next page.
- // Unfortunately, the stack grows down. If we're on the first page (last page in the
- // VirtualAlloc), we'll be moved to the next page, which is off the stack!
-
- UIntPtr currentAddr = new UIntPtr(&stackInfo - pageSize);
- UInt64 current64 = currentAddr.ToUInt64();
-
- // Check whether we previously recorded a deeper stack than where we currently are,
- // If so we don't need to do the P/Invoke to VirtualQuery
- if (m_lastKnownWatermark != 0 && current64 > m_lastKnownWatermark)
- return true;
-
- // Actual stack probe. P/Invoke to query for the current stack allocation information.
- Win32Native.VirtualQuery(currentAddr.ToPointer(), ref stackInfo, (UIntPtr)(sizeof(Win32Native.MEMORY_BASIC_INFORMATION)));
-
- // If the current address minus the base (remember: the stack grows downward in the
- // address space) is greater than the number of bytes requested plus the reserved
- // space at the end, the request has succeeded.
-
- if ((current64 - ((UIntPtr)stackInfo.AllocationBase).ToUInt64()) > STACK_RESERVED_SPACE)
- {
- m_lastKnownWatermark = current64;
- return true;
- }
-
- return false;
-#endif
}
}
case STATE_WAITING_ON_INNER_TASK:
bool result = TrySetFromTask(completingTask, lookForOce: false);
_state = STATE_DONE; // bump the state
- Contract.Assert(result, "Expected TrySetFromTask from inner task to succeed");
+ Debug.Assert(result, "Expected TrySetFromTask from inner task to succeed");
break;
default:
- Contract.Assert(false, "UnwrapPromise in illegal state");
+ Debug.Assert(false, "UnwrapPromise in illegal state");
break;
}
}
// Calls InvokeCore asynchronously.
- [SecuritySafeCritical]
private void InvokeCoreAsync(Task completingTask)
{
// Queue a call to Invoke. If we're so deep on the stack that we're at risk of overflowing,
private void ProcessCompletedOuterTask(Task task)
{
Contract.Requires(task != null && task.IsCompleted, "Expected non-null, completed outer task");
- Contract.Assert(_state == STATE_WAITING_ON_OUTER_TASK, "We're in the wrong state!");
+ Debug.Assert(_state == STATE_WAITING_ON_OUTER_TASK, "We're in the wrong state!");
// Bump our state before proceeding any further
_state = STATE_WAITING_ON_INNER_TASK;
case TaskStatus.Canceled:
case TaskStatus.Faulted:
bool result = TrySetFromTask(task, _lookForOce);
- Contract.Assert(result, "Expected TrySetFromTask from outer task to succeed");
+ Debug.Assert(result, "Expected TrySetFromTask from outer task to succeed");
break;
// Otherwise, process the inner task it returned.
// =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-
using System;
+using System.Diagnostics;
using System.Diagnostics.Contracts;
using System.Collections.Generic;
using System.Runtime.CompilerServices;
/// </remarks>
/// <typeparam name="TResult">The type of the result value assocatied with this <see
/// cref="TaskCompletionSource{TResult}"/>.</typeparam>
- [HostProtection(Synchronization = true, ExternalThreading = true)]
public class TaskCompletionSource<TResult>
{
private readonly Task<TResult> m_task;
/// <remarks>Unlike the public methods, this method doesn't currently validate that its arguments are correct.</remarks>
internal bool TrySetException(IEnumerable<ExceptionDispatchInfo> exceptions)
{
- Contract.Assert(exceptions != null);
+ Debug.Assert(exceptions != null);
#if DEBUG
- foreach(var edi in exceptions) Contract.Assert(edi != null, "Contents must be non-null");
+ foreach(var edi in exceptions) Debug.Assert(edi != null, "Contents must be non-null");
#endif
bool rval = m_task.TrySetException(exceptions);
// =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-
using System.Security;
+using System.Diagnostics;
using System.Diagnostics.Contracts;
using System.Runtime.ExceptionServices;
using System.Runtime.CompilerServices;
// Get and null out the antecedent. This is crucial to avoid a memory
// leak with long chains of continuations.
var antecedent = m_antecedent;
- Contract.Assert(antecedent != null,
+ Debug.Assert(antecedent != null,
"No antecedent was set for the ContinuationTaskFromTask.");
m_antecedent = null;
antecedent.NotifyDebuggerOfWaitCompletionIfNecessary();
// Invoke the delegate
- Contract.Assert(m_action != null);
+ Debug.Assert(m_action != null);
var action = m_action as Action<Task>;
if (action != null)
{
actionWithState(antecedent, m_stateObject);
return;
}
- Contract.Assert(false, "Invalid m_action in ContinuationTaskFromTask");
+ Debug.Assert(false, "Invalid m_action in ContinuationTaskFromTask");
}
}
// Get and null out the antecedent. This is crucial to avoid a memory
// leak with long chains of continuations.
var antecedent = m_antecedent;
- Contract.Assert(antecedent != null,
+ Debug.Assert(antecedent != null,
"No antecedent was set for the ContinuationResultTaskFromTask.");
m_antecedent = null;
antecedent.NotifyDebuggerOfWaitCompletionIfNecessary();
// Invoke the delegate
- Contract.Assert(m_action != null);
+ Debug.Assert(m_action != null);
var func = m_action as Func<Task, TResult>;
if (func != null)
{
m_result = funcWithState(antecedent, m_stateObject);
return;
}
- Contract.Assert(false, "Invalid m_action in ContinuationResultTaskFromTask");
+ Debug.Assert(false, "Invalid m_action in ContinuationResultTaskFromTask");
}
}
// Get and null out the antecedent. This is crucial to avoid a memory
// leak with long chains of continuations.
var antecedent = m_antecedent;
- Contract.Assert(antecedent != null,
+ Debug.Assert(antecedent != null,
"No antecedent was set for the ContinuationTaskFromResultTask.");
m_antecedent = null;
antecedent.NotifyDebuggerOfWaitCompletionIfNecessary();
// Invoke the delegate
- Contract.Assert(m_action != null);
+ Debug.Assert(m_action != null);
var action = m_action as Action<Task<TAntecedentResult>>;
if (action != null)
{
actionWithState(antecedent, m_stateObject);
return;
}
- Contract.Assert(false, "Invalid m_action in ContinuationTaskFromResultTask");
+ Debug.Assert(false, "Invalid m_action in ContinuationTaskFromResultTask");
}
}
// Get and null out the antecedent. This is crucial to avoid a memory
// leak with long chains of continuations.
var antecedent = m_antecedent;
- Contract.Assert(antecedent != null,
+ Debug.Assert(antecedent != null,
"No antecedent was set for the ContinuationResultTaskFromResultTask.");
m_antecedent = null;
antecedent.NotifyDebuggerOfWaitCompletionIfNecessary();
// Invoke the delegate
- Contract.Assert(m_action != null);
+ Debug.Assert(m_action != null);
var func = m_action as Func<Task<TAntecedentResult>, TResult>;
if (func != null)
{
m_result = funcWithState(antecedent, m_stateObject);
return;
}
- Contract.Assert(false, "Invalid m_action in ContinuationResultTaskFromResultTask");
+ Debug.Assert(false, "Invalid m_action in ContinuationResultTaskFromResultTask");
}
}
/// <param name="needsProtection">
/// true if we need to protect against multiple threads racing to start/cancel the task; otherwise, false.
/// </param>
- [SecuritySafeCritical]
protected static void InlineIfPossibleOrElseQueue(Task task, bool needsProtection)
{
Contract.Requires(task != null);
- Contract.Assert(task.m_taskScheduler != null);
+ Debug.Assert(task.m_taskScheduler != null);
// Set the TASK_STATE_STARTED flag. This only needs to be done
// if the task may be canceled or if someone else has a reference to it
/// <param name="bCanInlineContinuationTask">Whether the continuation can be inlined.</param>
internal override void Run(Task completedTask, bool bCanInlineContinuationTask)
{
- Contract.Assert(completedTask != null);
- Contract.Assert(completedTask.IsCompleted, "ContinuationTask.Run(): completedTask not completed");
+ Debug.Assert(completedTask != null);
+ Debug.Assert(completedTask.IsCompleted, "ContinuationTask.Run(): completedTask not completed");
// Check if the completion status of the task works with the desired
// activation criteria of the TaskContinuationOptions.
/// <summary>SendOrPostCallback delegate to invoke the action.</summary>
private readonly static SendOrPostCallback s_postCallback = state => ((Action)state)(); // can't use InvokeAction as it's SecurityCritical
/// <summary>Cached delegate for PostAction</summary>
- [SecurityCritical]
private static ContextCallback s_postActionCallback;
/// <summary>The context with which to run the action.</summary>
private readonly SynchronizationContext m_syncContext;
/// <param name="action">The action to invoke. Must not be null.</param>
/// <param name="flowExecutionContext">Whether to capture and restore ExecutionContext.</param>
/// <param name="stackMark">The captured stack mark.</param>
- [SecurityCritical]
internal SynchronizationContextAwaitTaskContinuation(
SynchronizationContext context, Action action, bool flowExecutionContext, ref StackCrawlMark stackMark) :
base(action, flowExecutionContext, ref stackMark)
{
- Contract.Assert(context != null);
+ Debug.Assert(context != null);
m_syncContext = context;
}
/// <summary>Inlines or schedules the continuation.</summary>
/// <param name="ignored">The antecedent task, which is ignored.</param>
/// <param name="canInlineContinuationTask">true if inlining is permitted; otherwise, false.</param>
- [SecuritySafeCritical]
internal sealed override void Run(Task task, bool canInlineContinuationTask)
{
// If we're allowed to inline, run the action on this thread.
/// <summary>Calls InvokeOrPostAction(false) on the supplied SynchronizationContextAwaitTaskContinuation.</summary>
/// <param name="state">The SynchronizationContextAwaitTaskContinuation.</param>
- [SecurityCritical]
private static void PostAction(object state)
{
var c = (SynchronizationContextAwaitTaskContinuation)state;
/// to be passed as state.
/// </returns>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
- [SecurityCritical]
private static ContextCallback GetPostActionCallback()
{
ContextCallback callback = s_postActionCallback;
/// <param name="action">The action to invoke. Must not be null.</param>
/// <param name="flowExecutionContext">Whether to capture and restore ExecutionContext.</param>
/// <param name="stackMark">The captured stack mark.</param>
- [SecurityCritical]
internal TaskSchedulerAwaitTaskContinuation(
TaskScheduler scheduler, Action action, bool flowExecutionContext, ref StackCrawlMark stackMark) :
base(action, flowExecutionContext, ref stackMark)
{
- Contract.Assert(scheduler != null);
+ Debug.Assert(scheduler != null);
m_scheduler = scheduler;
}
/// <param name="action">The action to invoke. Must not be null.</param>
/// <param name="flowExecutionContext">Whether to capture and restore ExecutionContext.</param>
/// <param name="stackMark">The captured stack mark with which to construct an ExecutionContext.</param>
- [SecurityCritical]
internal AwaitTaskContinuation(Action action, bool flowExecutionContext, ref StackCrawlMark stackMark)
{
Contract.Requires(action != null);
/// <summary>Initializes the continuation.</summary>
/// <param name="action">The action to invoke. Must not be null.</param>
/// <param name="flowExecutionContext">Whether to capture and restore ExecutionContext.</param>
- [SecurityCritical]
internal AwaitTaskContinuation(Action action, bool flowExecutionContext)
{
Contract.Requires(action != null);
/// <summary>Inlines or schedules the continuation onto the default scheduler.</summary>
/// <param name="ignored">The antecedent task, which is ignored.</param>
/// <param name="canInlineContinuationTask">true if inlining is permitted; otherwise, false.</param>
- [SecuritySafeCritical]
internal override void Run(Task task, bool canInlineContinuationTask)
{
// For the base AwaitTaskContinuation, we allow inlining if our caller allows it
}
/// <summary>IThreadPoolWorkItem override, which is the entry function for this when the ThreadPool scheduler decides to run it.</summary>
- [SecurityCritical]
void ExecuteWorkItemHelper()
{
var etwLog = TplEtwProvider.Log;
}
}
- [SecurityCritical]
void IThreadPoolWorkItem.ExecuteWorkItem()
{
// inline the fast path
/// <summary>
/// The ThreadPool calls this if a ThreadAbortException is thrown while trying to execute this workitem.
/// </summary>
- [SecurityCritical]
void IThreadPoolWorkItem.MarkAborted(ThreadAbortException tae) { /* nop */ }
/// <summary>Cached delegate that invokes an Action passed as an object parameter.</summary>
- [SecurityCritical]
private static ContextCallback s_invokeActionCallback;
/// <summary>Runs an action provided as an object parameter.</summary>
/// <param name="state">The Action to invoke.</param>
- [SecurityCritical]
private static void InvokeAction(object state) { ((Action)state)(); }
[MethodImpl(MethodImplOptions.AggressiveInlining)]
- [SecurityCritical]
protected static ContextCallback GetInvokeActionCallback()
{
ContextCallback callback = s_invokeActionCallback;
/// <param name="callback">The callback to run.</param>
/// <param name="state">The state to pass to the callback.</param>
/// <param name="currentTask">A reference to Task.t_currentTask.</param>
- [SecurityCritical]
protected void RunCallback(ContextCallback callback, object state, ref Task currentTask)
{
Contract.Requires(callback != null);
- Contract.Assert(currentTask == Task.t_currentTask);
+ Debug.Assert(currentTask == Task.t_currentTask);
// Pretend there's no current task, so that no task is seen as a parent
// and TaskScheduler.Current does not reflect false information
/// only happens in Task.SetContinuationForAwait if execution context flow was disabled
/// via using TaskAwaiter.UnsafeOnCompleted or a similar path.
/// </remarks>
- [SecurityCritical]
internal static void RunOrScheduleAction(Action action, bool allowInlining, ref Task currentTask)
{
- Contract.Assert(currentTask == Task.t_currentTask);
+ Debug.Assert(currentTask == Task.t_currentTask);
// If we're not allowed to run here, schedule the action
if (!allowInlining || !IsValidLocationForInlining)
/// <summary>Schedules the action to be executed. No ExecutionContext work is performed used.</summary>
/// <param name="action">The action to invoke or queue.</param>
- [SecurityCritical]
internal static void UnsafeScheduleAction(Action action, Task task)
{
AwaitTaskContinuation atc = new AwaitTaskContinuation(action, flowExecutionContext: false);
internal override Delegate[] GetDelegateContinuationsForDebugger()
{
- Contract.Assert(m_action != null);
+ Debug.Assert(m_action != null);
return new Delegate[] { AsyncMethodBuilderCore.TryGetStateMachineForDebugger(m_action) };
}
}
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
+ using System.Diagnostics;
using System.Diagnostics.Contracts;
using System.Runtime.ExceptionServices;
using System.Security;
EnsureADUnloadCallbackRegistered();
}
- [SecuritySafeCritical]
private static bool ShouldFailFastOnUnobservedException()
{
- bool shouldFailFast = false;
- #if !FEATURE_CORECLR
- shouldFailFast = System.CLRConfig.CheckThrowUnobservedTaskExceptions();
- #endif
- return shouldFailFast;
+ return false;
}
private static void EnsureADUnloadCallbackRegistered()
{
Contract.Requires(exceptionObject != null, "Expected exceptionObject to be non-null.");
- Contract.Assert(m_cancellationException == null,
+ Debug.Assert(m_cancellationException == null,
"Expected SetCancellationException to be called only once.");
// Breaking this assumption will overwrite a previously OCE,
// and implies something may be wrong elsewhere, since there should only ever be one.
- Contract.Assert(m_faultExceptions == null,
+ Debug.Assert(m_faultExceptions == null,
"Expected SetCancellationException to be called before any faults were added.");
// Breaking this assumption shouldn't hurt anything here, but it implies something may be wrong elsewhere.
// If this changes, make sure to only conditionally mark as handled below.
else
{
var edi = exceptionObject as ExceptionDispatchInfo;
- Contract.Assert(edi != null && edi.SourceException is OperationCanceledException,
+ Debug.Assert(edi != null && edi.SourceException is OperationCanceledException,
"Expected an OCE or an EDI that contained an OCE");
m_cancellationException = edi;
}
// Initialize the exceptions list if necessary. The list should be non-null iff it contains exceptions.
var exceptions = m_faultExceptions;
if (exceptions == null) m_faultExceptions = exceptions = new List<ExceptionDispatchInfo>(1);
- else Contract.Assert(exceptions.Count > 0, "Expected existing exceptions list to have > 0 exceptions.");
+ else Debug.Assert(exceptions.Count > 0, "Expected existing exceptions list to have > 0 exceptions.");
// Handle Exception by capturing it into an ExceptionDispatchInfo and storing that
var exception = exceptionObject as Exception;
foreach (var exc in exColl)
{
#if DEBUG
- Contract.Assert(exc != null, "No exceptions should be null");
+ Debug.Assert(exc != null, "No exceptions should be null");
numExceptions++;
#endif
exceptions.Add(ExceptionDispatchInfo.Capture(exc));
}
#if DEBUG
- Contract.Assert(numExceptions > 0, "Collection should contain at least one exception.");
+ Debug.Assert(numExceptions > 0, "Collection should contain at least one exception.");
#endif
}
else
{
exceptions.AddRange(ediColl);
#if DEBUG
- Contract.Assert(exceptions.Count > 0, "There should be at least one dispatch info.");
+ Debug.Assert(exceptions.Count > 0, "There should be at least one dispatch info.");
foreach(var tmp in exceptions)
{
- Contract.Assert(tmp != null, "No dispatch infos should be null");
+ Debug.Assert(tmp != null, "No dispatch infos should be null");
}
#endif
}
internal AggregateException CreateExceptionObject(bool calledFromFinalizer, Exception includeThisException)
{
var exceptions = m_faultExceptions;
- Contract.Assert(exceptions != null, "Expected an initialized list.");
- Contract.Assert(exceptions.Count > 0, "Expected at least one exception.");
+ Debug.Assert(exceptions != null, "Expected an initialized list.");
+ Debug.Assert(exceptions.Count > 0, "Expected at least one exception.");
// Mark as handled and aggregate the exceptions.
MarkAsHandled(calledFromFinalizer);
internal ReadOnlyCollection<ExceptionDispatchInfo> GetExceptionDispatchInfos()
{
var exceptions = m_faultExceptions;
- Contract.Assert(exceptions != null, "Expected an initialized list.");
- Contract.Assert(exceptions.Count > 0, "Expected at least one exception.");
+ Debug.Assert(exceptions != null, "Expected an initialized list.");
+ Debug.Assert(exceptions.Count > 0, "Expected at least one exception.");
MarkAsHandled(false);
return new ReadOnlyCollection<ExceptionDispatchInfo>(exceptions);
}
internal ExceptionDispatchInfo GetCancellationExceptionDispatchInfo()
{
var edi = m_cancellationException;
- Contract.Assert(edi == null || edi.SourceException is OperationCanceledException,
+ Debug.Assert(edi == null || edi.SourceException is OperationCanceledException,
"Expected the EDI to be for an OperationCanceledException");
return edi;
}
using System.Security.Permissions;
using System.Runtime.CompilerServices;
using System.Threading;
+using System.Diagnostics;
using System.Diagnostics.Contracts;
namespace System.Threading.Tasks
/// <see cref="System.Threading.Tasks.Task.Factory">Task.Factory</see> property.
/// </para>
/// </remarks>
- [HostProtection(Synchronization = true, ExternalThreading = true)]
public class TaskFactory
{
// member variables
TrySetResult(_tasks);
}
- Contract.Assert(_count >= 0, "Count should never go below 0");
+ Debug.Assert(_count >= 0, "Count should never go below 0");
}
public bool InvokeMayRunArbitraryCode { get { return true; } }
TrySetResult(_tasks);
}
- Contract.Assert(_count >= 0, "Count should never go below 0");
+ Debug.Assert(_count >= 0, "Count should never go below 0");
}
public bool InvokeMayRunArbitraryCode { get { return true; } }
}
bool success = TrySetResult(completingTask);
- Contract.Assert(success, "Only one task should have gotten to this point, and thus this must be successful.");
+ Debug.Assert(success, "Only one task should have gotten to this point, and thus this must be successful.");
// We need to remove continuations that may be left straggling on other tasks.
// Otherwise, repeated calls to WhenAny using the same task could leak actions.
/// </remarks>
[DebuggerDisplay("Id={Id}")]
[DebuggerTypeProxy(typeof(SystemThreadingTasks_TaskSchedulerDebugView))]
- [HostProtection(Synchronization = true, ExternalThreading = true)]
-#pragma warning disable 618
- [PermissionSet(SecurityAction.InheritanceDemand, Unrestricted = true)]
-#pragma warning restore 618
public abstract class TaskScheduler
{
////////////////////////////////////////////////////////////
/// </remarks>
/// <param name="task">The <see cref="T:System.Threading.Tasks.Task">Task</see> to be queued.</param>
/// <exception cref="T:System.ArgumentNullException">The <paramref name="task"/> argument is null.</exception>
- [SecurityCritical]
protected internal abstract void QueueTask(Task task);
/// <summary>
/// null.</exception>
/// <exception cref="T:System.InvalidOperationException">The <paramref name="task"/> was already
/// executed.</exception>
- [SecurityCritical]
protected abstract bool TryExecuteTaskInline(Task task, bool taskWasPreviouslyQueued);
/// <summary>
/// <exception cref="T:System.NotSupportedException">
/// This scheduler is unable to generate a list of queued tasks at this time.
/// </exception>
- [SecurityCritical]
protected abstract IEnumerable<Task> GetScheduledTasks();
/// <summary>
/// <param name="taskWasPreviouslyQueued">True if the task may have been previously queued,
/// false if the task was absolutely not previously queued.</param>
/// <returns>True if it ran, false otherwise.</returns>
- [SecuritySafeCritical]
internal bool TryRunInline(Task task, bool taskWasPreviouslyQueued)
{
// Do not inline unstarted tasks (i.e., task.ExecutingTaskScheduler == null).
/// <param name="task">The <see cref="T:System.Threading.Tasks.Task">Task</see> to be dequeued.</param>
/// <returns>A Boolean denoting whether the <paramref name="task"/> argument was successfully dequeued.</returns>
/// <exception cref="T:System.ArgumentNullException">The <paramref name="task"/> argument is null.</exception>
- [SecurityCritical]
protected internal virtual bool TryDequeue(Task task)
{
return false;
/// <summary>
/// Calls QueueTask() after performing any needed firing of events
/// </summary>
- [SecurityCritical]
internal void InternalQueueTask(Task task)
{
Contract.Requires(task != null);
/// <returns>A Boolean that is true if <paramref name="task"/> was successfully executed, false if it
/// was not. A common reason for execution failure is that the task had previously been executed or
/// is in the process of being executed by another thread.</returns>
- [SecurityCritical]
protected bool TryExecuteTask(Task task)
{
if (task.ExecutingTaskScheduler != this)
/// </remarks>
public static event EventHandler<UnobservedTaskExceptionEventArgs> UnobservedTaskException
{
- [System.Security.SecurityCritical]
add
{
if (value != null)
}
}
- [System.Security.SecurityCritical]
remove
{
lock (_unobservedTaskExceptionLockObject) _unobservedTaskException -= value;
/// <exception cref="T:System.NotSupportedException">
/// This scheduler is unable to generate a list of queued tasks at this time.
/// </exception>
- [SecurityCritical]
internal Task[] GetScheduledTasksForDebugger()
{
// this can throw InvalidOperationException indicating that they are unable to provide the info
/// It should not be called by any other codepaths.
/// </remarks>
/// <returns>An array of <see cref="System.Threading.Tasks.TaskScheduler">TaskScheduler</see> instances.</returns>
- [SecurityCritical]
internal static TaskScheduler[] GetTaskSchedulersForDebugger()
{
if (s_activeTaskSchedulers == null)
schedulers.CopyTo(arr, 0);
foreach (var scheduler in arr)
{
- Contract.Assert(scheduler != null, "Table returned an incorrect Count or CopyTo failed");
+ Debug.Assert(scheduler != null, "Table returned an incorrect Count or CopyTo failed");
int tmp = scheduler.Id; // force Ids for debugger
}
return arr;
// returns the scheduler\92s GetScheduledTasks
public IEnumerable<Task> ScheduledTasks
{
- [SecurityCritical]
get { return m_taskScheduler.GetScheduledTasks(); }
}
}
/// Simply posts the tasks to be executed on the associated <see cref="T:System.Threading.SynchronizationContext"/>.
/// </summary>
/// <param name="task"></param>
- [SecurityCritical]
protected internal override void QueueTask(Task task)
{
m_synchronizationContext.Post(s_postCallback, (object)task);
/// </summary>
/// <param name="task"></param>
/// <param name="taskWasPreviouslyQueued"></param>
- [SecurityCritical]
protected override bool TryExecuteTaskInline(Task task, bool taskWasPreviouslyQueued)
{
if (SynchronizationContext.Current == m_synchronizationContext)
}
// not implemented
- [SecurityCritical]
protected override IEnumerable<Task> GetScheduledTasks()
{
return null;
// =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-
using System.IO;
+using System.Diagnostics;
using System.Diagnostics.Contracts;
namespace System.Threading.Tasks
if (twar != null)
{
task = twar.Task;
- Contract.Assert(task != null, "TaskWrapperAsyncResult should never wrap a null Task.");
+ Debug.Assert(task != null, "TaskWrapperAsyncResult should never wrap a null Task.");
}
// Otherwise, the IAsyncResult should be a Task.
else
if (twar != null)
{
task = twar.Task as Task<TResult>;
- Contract.Assert(twar.Task != null, "TaskWrapperAsyncResult should never wrap a null Task.");
+ Debug.Assert(twar.Task != null, "TaskWrapperAsyncResult should never wrap a null Task.");
}
// Otherwise, the IAsyncResult should be a Task<TResult>.
else
using System;
using System.Security;
+using System.Diagnostics;
using System.Diagnostics.Contracts;
using System.Collections.Generic;
using System.Text;
{
Contract.Requires(obj != null, "TaskScheduler.LongRunningThreadWork: obj is null");
Task t = obj as Task;
- Contract.Assert(t != null, "TaskScheduler.LongRunningThreadWork: t is null");
+ Debug.Assert(t != null, "TaskScheduler.LongRunningThreadWork: t is null");
t.ExecuteEntry(false);
}
/// Schedules a task to the ThreadPool.
/// </summary>
/// <param name="task">The task to schedule.</param>
- [SecurityCritical]
protected internal override void QueueTask(Task task)
{
if ((task.Options & TaskCreationOptions.LongRunning) != 0)
/// IMPORTANT NOTE: TryExecuteTaskInline will NOT throw task exceptions itself. Any wait code path using this function needs
/// to account for exceptions that need to be propagated, and throw themselves accordingly.
/// </summary>
- [SecurityCritical]
protected override bool TryExecuteTaskInline(Task task, bool taskWasPreviouslyQueued)
{
// If the task was previously scheduled, and we can't pop it, then return false.
return rval;
}
- [SecurityCritical]
protected internal override bool TryDequeue(Task task)
{
// just delegate to TP
return ThreadPool.TryPopCustomWorkItem(task);
}
- [SecurityCritical]
protected override IEnumerable<Task> GetScheduledTasks()
{
return FilterTasksFromWorkItems(ThreadPool.GetQueuedWorkItems());
/// and may be used from multiple threads concurrently.
/// </para>
/// </remarks>
- [HostProtection(Synchronization = true, ExternalThreading = true)]
[DebuggerTypeProxy(typeof(SystemThreadingTasks_FutureDebugView<>))]
[DebuggerDisplay("Id = {Id}, Status = {Status}, Method = {DebuggerDisplayMethodDescription}, Result = {DebuggerDisplayResultDescription}")]
public class Task<TResult> : Task
internal bool TrySetResult(TResult result)
{
if (IsCompleted) return false;
- Contract.Assert(m_action == null, "Task<T>.TrySetResult(): non-null m_action");
+ Debug.Assert(m_action == null, "Task<T>.TrySetResult(): non-null m_action");
// "Reserve" the completion for this task, while making sure that: (1) No prior reservation
// has been made, (2) The result has not already been set, (3) An exception has not previously
// the task, avoiding expensive completion paths, before the task is actually given to anyone.
internal void DangerousSetResult(TResult result)
{
- Contract.Assert(!IsCompleted, "The promise must not yet be completed.");
+ Debug.Assert(!IsCompleted, "The promise must not yet be completed.");
// If we have a parent, we need to notify it of the completion. Take the slow path to handle that.
if (m_contingentProperties?.m_parent != null)
bool success = TrySetResult(result);
// Nobody else has had a chance to complete this Task yet, so we should succeed.
- Contract.Assert(success);
+ Debug.Assert(success);
}
else
{
{
get
{
- Contract.Assert(!IsWaitNotificationEnabledOrNotRanToCompletion,
+ Debug.Assert(!IsWaitNotificationEnabledOrNotRanToCompletion,
"Should only be used when the task completed successfully and there's no wait notification enabled");
return m_result;
}
if (!IsRanToCompletion) ThrowIfExceptional(includeTaskCanceledExceptions: true);
// We shouldn't be here if the result has not been set.
- Contract.Assert(IsRanToCompletion, "Task<T>.Result getter: Expected result to have been set.");
+ Debug.Assert(IsRanToCompletion, "Task<T>.Result getter: Expected result to have been set.");
return m_result;
}
// Called from TaskCompletionSource<T>.SetException(IEnumerable<Exception>).
internal bool TrySetException(object exceptionObject)
{
- Contract.Assert(m_action == null, "Task<T>.TrySetException(): non-null m_action");
+ Debug.Assert(m_action == null, "Task<T>.TrySetException(): non-null m_action");
// TCS.{Try}SetException() should have checked for this
- Contract.Assert(exceptionObject != null, "Expected non-null exceptionObject argument");
+ Debug.Assert(exceptionObject != null, "Expected non-null exceptionObject argument");
// Only accept these types.
- Contract.Assert(
+ Debug.Assert(
(exceptionObject is Exception) || (exceptionObject is IEnumerable<Exception>) ||
(exceptionObject is ExceptionDispatchInfo) || (exceptionObject is IEnumerable<ExceptionDispatchInfo>),
"Expected exceptionObject to be either Exception, ExceptionDispatchInfo, or IEnumerable<> of one of those");
// This method is only valid for promise tasks.
internal bool TrySetCanceled(CancellationToken tokenToRecord, object cancellationException)
{
- Contract.Assert(m_action == null, "Task<T>.TrySetCanceled(): non-null m_action");
+ Debug.Assert(m_action == null, "Task<T>.TrySetCanceled(): non-null m_action");
#if DEBUG
var ceAsEdi = cancellationException as ExceptionDispatchInfo;
- Contract.Assert(
+ Debug.Assert(
cancellationException == null ||
cancellationException is OperationCanceledException ||
(ceAsEdi != null && ceAsEdi.SourceException is OperationCanceledException),
internal override void InnerInvoke()
{
// Invoke the delegate
- Contract.Assert(m_action != null);
+ Debug.Assert(m_action != null);
var func = m_action as Func<TResult>;
if (func != null)
{
m_result = funcWithState(m_stateObject);
return;
}
- Contract.Assert(false, "Invalid m_action in Task<TResult>");
+ Debug.Assert(false, "Invalid m_action in Task<TResult>");
}
#region Await Support
using System.Threading;
using System.Runtime;
using System.Runtime.InteropServices;
-#if FEATURE_REMOTING
- using System.Runtime.Remoting.Contexts;
- using System.Runtime.Remoting.Messaging;
-#endif
using System;
- using System.Diagnostics;
using System.Security.Permissions;
using System.Security.Principal;
using System.Globalization;
using System.Runtime.ConstrainedExecution;
using System.Security;
using System.Runtime.Versioning;
+ using System.Diagnostics;
using System.Diagnostics.Contracts;
internal delegate Object InternalCrossContextDelegate(Object[] args);
internal class ThreadHelper
{
- [System.Security.SecuritySafeCritical]
static ThreadHelper() {}
Delegate _start;
_executionContext = ec;
}
- [System.Security.SecurityCritical]
static internal ContextCallback _ccb = new ContextCallback(ThreadStart_Context);
- [System.Security.SecurityCritical]
static private void ThreadStart_Context(Object state)
{
ThreadHelper t = (ThreadHelper)state;
}
// call back helper
- #if FEATURE_CORECLR
- [System.Security.SecuritySafeCritical] // auto-generated
- #else
- [System.Security.SecurityCritical]
- #endif
internal void ThreadStart(object obj)
{
_startArg = obj;
}
// call back helper
- #if FEATURE_CORECLR
- [System.Security.SecuritySafeCritical] // auto-generated
- #else
- [System.Security.SecurityCritical]
- #endif
internal void ThreadStart()
{
if (_executionContext != null)
** ThreadBaseObject to maintain alignment between the two classes.
** DON'T CHANGE THESE UNLESS YOU MODIFY ThreadBaseObject in vm\object.h
=========================================================================*/
-#if FEATURE_REMOTING
- private Context m_Context;
-#endif
private ExecutionContext m_ExecutionContext; // this call context follows the logical thread
-#if FEATURE_CORECLR
private SynchronizationContext m_SynchronizationContext; // On CoreCLR, this is maintained separately from ExecutionContext
-#endif
private String m_Name;
private Delegate m_Delegate; // Delegate
-
+
#if FEATURE_LEAK_CULTURE_INFO
private CultureInfo m_CurrentCulture;
private CultureInfo m_CurrentUICulture;
#endif // FEATURE_LEAK_CULTURE_INFO
}
-#if FEATURE_CORECLR
// Adding an empty default ctor for annotation purposes
- [System.Security.SecuritySafeCritical] // auto-generated
internal Thread(){}
-#endif // FEATURE_CORECLR
/*=========================================================================
** Creates a new Thread object which will begin execution at
**
** Exceptions: ArgumentNullException if start == null.
=========================================================================*/
- [System.Security.SecuritySafeCritical] // auto-generated
public Thread(ThreadStart start) {
if (start == null) {
throw new ArgumentNullException(nameof(start));
SetStartHelper((Delegate)start,0); //0 will setup Thread with default stackSize
}
- [System.Security.SecuritySafeCritical] // auto-generated
public Thread(ThreadStart start, int maxStackSize) {
if (start == null) {
throw new ArgumentNullException(nameof(start));
Contract.EndContractBlock();
SetStartHelper((Delegate)start, maxStackSize);
}
- [System.Security.SecuritySafeCritical] // auto-generated
public Thread(ParameterizedThreadStart start) {
if (start == null) {
throw new ArgumentNullException(nameof(start));
SetStartHelper((Delegate)start, 0);
}
- [System.Security.SecuritySafeCritical] // auto-generated
public Thread(ParameterizedThreadStart start, int maxStackSize) {
if (start == null) {
throw new ArgumentNullException(nameof(start));
{
[ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)]
[MethodImplAttribute(MethodImplOptions.InternalCall)]
- [System.Security.SecuritySafeCritical] // auto-generated
get;
}
**
** Exceptions: ThreadStateException if the thread has already been started.
=========================================================================*/
- [HostProtection(Synchronization=true,ExternalThreading=true)]
[MethodImplAttribute(MethodImplOptions.NoInlining)] // Methods containing StackCrawlMark local var has to be marked non-inlineable
public new void Start()
{
Start(ref stackMark);
}
- [HostProtection(Synchronization=true,ExternalThreading=true)]
[MethodImplAttribute(MethodImplOptions.NoInlining)] // Methods containing StackCrawlMark local var has to be marked non-inlineable
public new void Start(object parameter)
{
Start(ref stackMark);
}
- [System.Security.SecuritySafeCritical]
private void Start(ref StackCrawlMark stackMark)
{
#if FEATURE_COMINTEROP_APARTMENT_SUPPORT
StartInternal(principal, ref stackMark);
}
-#if FEATURE_CORECLR
internal ExecutionContext ExecutionContext
{
get { return m_ExecutionContext; }
{
get { return m_SynchronizationContext; }
set { m_SynchronizationContext = value; }
- }
-#else // !FEATURE_CORECLR
- [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)]
- internal ExecutionContext.Reader GetExecutionContextReader()
- {
- return new ExecutionContext.Reader(m_ExecutionContext);
- }
-
- internal bool ExecutionContextBelongsToCurrentScope
- {
- get { return !m_ExecutionContextBelongsToOuterScope; }
- set { m_ExecutionContextBelongsToOuterScope = !value; }
- }
-
-#if DEBUG
- internal bool ForbidExecutionContextMutation
- {
- set { m_ForbidExecutionContextMutation = value; }
- }
-#endif
-
- // note: please don't access this directly from mscorlib. Use GetMutableExecutionContext or GetExecutionContextReader instead.
- public ExecutionContext ExecutionContext
- {
- [SecuritySafeCritical]
- [ReliabilityContract(Consistency.WillNotCorruptState, Cer.MayFail)]
- get
- {
- ExecutionContext result;
- if (this == Thread.CurrentThread)
- result = GetMutableExecutionContext();
- else
- result = m_ExecutionContext;
-
- return result;
- }
- }
-
- [SecurityCritical]
- [ReliabilityContract(Consistency.WillNotCorruptState, Cer.MayFail)]
- internal ExecutionContext GetMutableExecutionContext()
- {
- Contract.Assert(Thread.CurrentThread == this);
-#if DEBUG
- Contract.Assert(!m_ForbidExecutionContextMutation);
-#endif
- if (m_ExecutionContext == null)
- {
- m_ExecutionContext = new ExecutionContext();
- }
- else if (!ExecutionContextBelongsToCurrentScope)
- {
- ExecutionContext copy = m_ExecutionContext.CreateMutableCopy();
- m_ExecutionContext = copy;
- }
-
- ExecutionContextBelongsToCurrentScope = true;
- return m_ExecutionContext;
- }
-
- [SecurityCritical]
- [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)]
- internal void SetExecutionContext(ExecutionContext value, bool belongsToCurrentScope)
- {
- m_ExecutionContext = value;
- ExecutionContextBelongsToCurrentScope = belongsToCurrentScope;
- }
-
- [SecurityCritical]
- [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)]
- internal void SetExecutionContext(ExecutionContext.Reader value, bool belongsToCurrentScope)
- {
- m_ExecutionContext = value.DangerousGetRawExecutionContext();
- ExecutionContextBelongsToCurrentScope = belongsToCurrentScope;
}
-#endif //!FEATURE_CORECLR
- [System.Security.SecurityCritical] // auto-generated
[MethodImplAttribute(MethodImplOptions.InternalCall)]
private extern void StartInternal(IPrincipal principal, ref StackCrawlMark stackMark);
#if FEATURE_COMPRESSEDSTACK
/// <internalonly/>
- [System.Security.SecurityCritical] // auto-generated_required
[DynamicSecurityMethodAttribute()]
[Obsolete("Thread.SetCompressedStack is no longer supported. Please use the System.Threading.CompressedStack class")]
public void SetCompressedStack( CompressedStack stack )
throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_ThreadAPIsNotSupported"));
}
- [System.Security.SecurityCritical] // auto-generated
[MethodImplAttribute(MethodImplOptions.InternalCall), ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)]
internal extern IntPtr SetAppDomainStack( SafeCompressedStackHandle csHandle);
- [System.Security.SecurityCritical] // auto-generated
[MethodImplAttribute(MethodImplOptions.InternalCall), ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)]
internal extern void RestoreAppDomainStack( IntPtr appDomainStack);
/// <internalonly/>
- [System.Security.SecurityCritical] // auto-generated_required
[Obsolete("Thread.GetCompressedStack is no longer supported. Please use the System.Threading.CompressedStack class")]
public CompressedStack GetCompressedStack()
{
// Helper method to get a logical thread ID for StringBuilder (for
// correctness) and for FileStream's async code path (for perf, to
// avoid creating a Thread instance).
- [System.Security.SecurityCritical] // auto-generated
[MethodImplAttribute(MethodImplOptions.InternalCall)]
internal extern static IntPtr InternalGetCurrentThread();
** If Abort is called twice on the same thread, a DuplicateThreadAbort
** exception is thrown.
=========================================================================*/
-
-#if !FEATURE_CORECLR
- [System.Security.SecuritySafeCritical] // auto-generated
- [SecurityPermissionAttribute(SecurityAction.Demand, ControlThread=true)]
- public void Abort(Object stateInfo)
- {
- // If two aborts come at the same time, it is possible that the state info
- // gets set by one, and the actual abort gets delivered by another. But this
- // is not distinguishable by an application.
- // The accessor helper will only set the value if it isn't already set,
- // and that particular bit of native code can test much faster than this
- // code could, because testing might cause a cross-appdomain marshalling.
- AbortReason = stateInfo;
-
- // Note: we demand ControlThread permission, then call AbortInternal directly
- // rather than delegating to the Abort() function below. We do this to ensure
- // that only callers with ControlThread are allowed to change the AbortReason
- // of the thread. We call AbortInternal directly to avoid demanding the same
- // permission twice.
- AbortInternal();
- }
-#endif
-
- #if FEATURE_CORECLR
- [System.Security.SecurityCritical] // auto-generated
- #else
- [System.Security.SecuritySafeCritical]
- #endif
#pragma warning disable 618
[SecurityPermissionAttribute(SecurityAction.Demand, ControlThread = true)]
#pragma warning restore 618
// Internal helper (since we can't place security demands on
// ecalls/fcalls).
- [System.Security.SecurityCritical] // auto-generated
[MethodImplAttribute(MethodImplOptions.InternalCall)]
private extern void AbortInternal();
-#if !FEATURE_CORECLR
- /*=========================================================================
- ** Resets a thread abort.
- ** Should be called by trusted code only
- =========================================================================*/
- [System.Security.SecuritySafeCritical] // auto-generated
- [SecurityPermissionAttribute(SecurityAction.Demand, ControlThread=true)]
- public static void ResetAbort()
- {
- Thread thread = Thread.CurrentThread;
- if ((thread.ThreadState & ThreadState.AbortRequested) == 0)
- throw new ThreadStateException(Environment.GetResourceString("ThreadState_NoAbortRequested"));
- thread.ResetAbortNative();
- thread.ClearAbortReason();
- }
-
- [System.Security.SecurityCritical] // auto-generated
- [MethodImplAttribute(MethodImplOptions.InternalCall)]
- private extern void ResetAbortNative();
-
- /*=========================================================================
- ** Suspends the thread. If the thread is already suspended, this call has
- ** no effect.
- **
- ** Exceptions: ThreadStateException if the thread has not been started or
- ** it is dead.
- =========================================================================*/
- [System.Security.SecuritySafeCritical] // auto-generated
- [Obsolete("Thread.Suspend has been deprecated. Please use other classes in System.Threading, such as Monitor, Mutex, Event, and Semaphore, to synchronize Threads or protect resources. http://go.microsoft.com/fwlink/?linkid=14202", false)][SecurityPermission(SecurityAction.Demand, ControlThread=true)]
- [SecurityPermission(SecurityAction.Demand, ControlThread=true)]
- public void Suspend() { SuspendInternal(); }
-
- // Internal helper (since we can't place security demands on
- // ecalls/fcalls).
- [System.Security.SecurityCritical] // auto-generated
- [MethodImplAttribute(MethodImplOptions.InternalCall)]
- private extern void SuspendInternal();
-
- /*=========================================================================
- ** Resumes a thread that has been suspended.
- **
- ** Exceptions: ThreadStateException if the thread has not been started or
- ** it is dead or it isn't in the suspended state.
- =========================================================================*/
- [System.Security.SecuritySafeCritical] // auto-generated
- [Obsolete("Thread.Resume has been deprecated. Please use other classes in System.Threading, such as Monitor, Mutex, Event, and Semaphore, to synchronize Threads or protect resources. http://go.microsoft.com/fwlink/?linkid=14202", false)]
- [SecurityPermission(SecurityAction.Demand, ControlThread=true)]
- public void Resume() { ResumeInternal(); }
-
- // Internal helper (since we can't place security demands on
- // ecalls/fcalls).
- [System.Security.SecurityCritical] // auto-generated
- [MethodImplAttribute(MethodImplOptions.InternalCall)]
- private extern void ResumeInternal();
-
- /*=========================================================================
- ** Interrupts a thread that is inside a Wait(), Sleep() or Join(). If that
- ** thread is not currently blocked in that manner, it will be interrupted
- ** when it next begins to block.
- =========================================================================*/
- [System.Security.SecuritySafeCritical] // auto-generated
- [SecurityPermission(SecurityAction.Demand, ControlThread = true)]
- public new void Interrupt() => base.Interrupt();
-
- /*=========================================================================
- ** Returns the priority of the thread.
- **
- ** Exceptions: ThreadStateException if the thread is dead.
- =========================================================================*/
-
- public new ThreadPriority Priority
- {
- [System.Security.SecuritySafeCritical] // auto-generated
- get
- {
- return base.Priority;
- }
- [System.Security.SecuritySafeCritical] // auto-generated
- [HostProtection(SelfAffectingThreading = true)]
- set
- {
- base.Priority = value;
- }
- }
-
- /*=========================================================================
- ** Returns true if the thread has been started and is not dead.
- =========================================================================*/
- public new bool IsAlive
- {
- [System.Security.SecuritySafeCritical] // auto-generated
- get
- {
- return base.IsAlive;
- }
- }
-
- /*=========================================================================
- ** Returns true if the thread is a threadpool thread.
- =========================================================================*/
- public new bool IsThreadPoolThread
- {
- [System.Security.SecuritySafeCritical] // auto-generated
- get
- {
- return base.IsThreadPoolThread;
- }
- }
-
- /*=========================================================================
- ** Waits for the thread to die or for timeout milliseconds to elapse.
- ** Returns true if the thread died, or false if the wait timed out. If
- ** Timeout.Infinite is given as the parameter, no timeout will occur.
- **
- ** Exceptions: ArgumentException if timeout < 0.
- ** ThreadInterruptedException if the thread is interrupted while waiting.
- ** ThreadStateException if the thread has not been started yet.
- =========================================================================*/
- [System.Security.SecuritySafeCritical]
- [HostProtection(Synchronization = true, ExternalThreading = true)]
- public new void Join() => base.Join();
-
- [System.Security.SecuritySafeCritical]
- [HostProtection(Synchronization = true, ExternalThreading = true)]
- public new bool Join(int millisecondsTimeout) => base.Join(millisecondsTimeout);
-#endif // !FEATURE_CORECLR
-
- [HostProtection(Synchronization=true, ExternalThreading=true)]
public bool Join(TimeSpan timeout)
{
long tm = (long)timeout.TotalMilliseconds;
** Exceptions: ArgumentException if timeout < 0.
** ThreadInterruptedException if the thread is interrupted while sleeping.
=========================================================================*/
- [System.Security.SecurityCritical] // auto-generated
[MethodImplAttribute(MethodImplOptions.InternalCall)]
private static extern void SleepInternal(int millisecondsTimeout);
- [System.Security.SecuritySafeCritical] // auto-generated
public static new void Sleep(int millisecondsTimeout)
{
SleepInternal(millisecondsTimeout);
only take a few machine instructions. Calling this API is preferable to coding
a explict busy loop because the hardware can be informed that it is busy waiting. */
- [System.Security.SecurityCritical] // auto-generated
[MethodImplAttribute(MethodImplOptions.InternalCall)]
- [HostProtection(Synchronization=true,ExternalThreading=true)]
[ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)]
private static extern void SpinWaitInternal(int iterations);
- [System.Security.SecuritySafeCritical] // auto-generated
- [HostProtection(Synchronization=true,ExternalThreading=true)]
[ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)]
public static new void SpinWait(int iterations)
{
SpinWaitInternal(iterations);
}
- [System.Security.SecurityCritical] // auto-generated
[DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
[SuppressUnmanagedCodeSecurity]
- [HostProtection(Synchronization = true, ExternalThreading = true)]
[ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)]
private static extern bool YieldInternal();
- [System.Security.SecuritySafeCritical] // auto-generated
- [HostProtection(Synchronization = true, ExternalThreading = true)]
[ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)]
public static new bool Yield()
{
}
public static new Thread CurrentThread {
- [System.Security.SecuritySafeCritical] // auto-generated
[ReliabilityContract(Consistency.WillNotCorruptState, Cer.MayFail)]
get {
Contract.Ensures(Contract.Result<Thread>() != null);
return GetCurrentThreadNative();
}
}
- [System.Security.SecurityCritical] // auto-generated
[MethodImplAttribute(MethodImplOptions.InternalCall), ReliabilityContract(Consistency.WillNotCorruptState, Cer.MayFail)]
private static extern Thread GetCurrentThreadNative();
- [System.Security.SecurityCritical] // auto-generated
private void SetStartHelper(Delegate start, int maxStackSize)
{
-#if FEATURE_CORECLR
// We only support default stacks in CoreCLR
- Contract.Assert(maxStackSize == 0);
-#else
- // Only fully-trusted code is allowed to create "large" stacks. Partial-trust falls back to
- // the default stack size.
- ulong defaultStackSize = GetProcessDefaultStackSize();
- if ((ulong)(uint)maxStackSize > defaultStackSize)
- {
- try
- {
- SecurityPermission.Demand(PermissionType.FullTrust);
- }
- catch (SecurityException)
- {
- maxStackSize = (int)Math.Min(defaultStackSize, (ulong)(uint)int.MaxValue);
- }
- }
-#endif
+ Debug.Assert(maxStackSize == 0);
ThreadHelper threadStartCallBack = new ThreadHelper(start);
if(start is ThreadStart)
}
}
- [SecurityCritical]
[DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
[SuppressUnmanagedCodeSecurity]
private static extern ulong GetProcessDefaultStackSize();
** PRIVATE Sets the IThreadable interface for the thread. Assumes that
** start != null.
=========================================================================*/
- [System.Security.SecurityCritical] // auto-generated
[MethodImplAttribute(MethodImplOptions.InternalCall)]
private extern void SetStart(Delegate start, int maxStackSize);
/*=========================================================================
** Clean up the thread when it goes away.
=========================================================================*/
- [System.Security.SecuritySafeCritical] // auto-generated
[ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)]
~Thread()
{
InternalFinalize();
}
- [System.Security.SecurityCritical] // auto-generated
[ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)]
[MethodImplAttribute(MethodImplOptions.InternalCall)]
private extern void InternalFinalize();
-#if !FEATURE_CORECLR
-#if FEATURE_COMINTEROP
- [System.Security.SecurityCritical] // auto-generated
- [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)]
- public new void DisableComObjectEagerCleanup()
- {
- base.DisableComObjectEagerCleanup();
- }
-#endif // FEATURE_COMINTEROP
-
- /*=========================================================================
- ** Return whether or not this thread is a background thread. Background
- ** threads do not affect when the Execution Engine shuts down.
- **
- ** Exceptions: ThreadStateException if the thread is dead.
- =========================================================================*/
- public new bool IsBackground
- {
- [System.Security.SecuritySafeCritical] // auto-generated
- get
- {
- return base.IsBackground;
- }
- [System.Security.SecuritySafeCritical] // auto-generated
- [HostProtection(SelfAffectingThreading = true)]
- set
- {
- base.IsBackground = value;
- }
- }
-
- /*=========================================================================
- ** Return the thread state as a consistent set of bits. This is more
- ** general then IsAlive or IsBackground.
- =========================================================================*/
- public new ThreadState ThreadState
- {
- [System.Security.SecuritySafeCritical] // auto-generated
- get
- {
- return base.ThreadState;
- }
- }
-#endif // !FEATURE_CORECLR
-
#if FEATURE_COMINTEROP_APARTMENT_SUPPORT
/*=========================================================================
** An unstarted thread can be marked to indicate that it will host a
[Obsolete("The ApartmentState property has been deprecated. Use GetApartmentState, SetApartmentState or TrySetApartmentState instead.", false)]
public ApartmentState ApartmentState
{
- [System.Security.SecuritySafeCritical] // auto-generated
get
{
return (ApartmentState)GetApartmentStateNative();
}
- [System.Security.SecuritySafeCritical] // auto-generated
- [HostProtection(Synchronization=true, SelfAffectingThreading=true)]
set
{
SetApartmentStateNative((int)value, true);
}
}
-#if !FEATURE_CORECLR
- [System.Security.SecuritySafeCritical] // auto-generated
- public new ApartmentState GetApartmentState() => base.GetApartmentState();
-
- [System.Security.SecuritySafeCritical] // auto-generated
- [HostProtection(Synchronization=true, SelfAffectingThreading=true)]
- public new bool TrySetApartmentState(ApartmentState state) => base.TrySetApartmentState(state);
-#endif // !FEATURE_CORECLR
-
- [System.Security.SecuritySafeCritical] // auto-generated
- [HostProtection(Synchronization=true, SelfAffectingThreading=true)]
public void SetApartmentState(ApartmentState state)
{
bool result = SetApartmentStateHelper(state, true);
throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_ApartmentStateSwitchFailed"));
}
- [System.Security.SecurityCritical] // auto-generated
[MethodImplAttribute(MethodImplOptions.InternalCall)]
private extern void StartupSetApartmentStateInternal();
#endif // FEATURE_COMINTEROP_APARTMENT_SUPPORT
** Allocates an un-named data slot. The slot is allocated on ALL the
** threads.
=========================================================================*/
- [HostProtection(SharedState=true, ExternalThreading=true)]
public static LocalDataStoreSlot AllocateDataSlot()
{
return LocalDataStoreManager.AllocateDataSlot();
** threads. Named data slots are "public" and can be manipulated by
** anyone.
=========================================================================*/
- [HostProtection(SharedState=true, ExternalThreading=true)]
public static LocalDataStoreSlot AllocateNamedDataSlot(String name)
{
return LocalDataStoreManager.AllocateNamedDataSlot(name);
** allocated. Named data slots are "public" and can be manipulated by
** anyone.
=========================================================================*/
- [HostProtection(SharedState=true, ExternalThreading=true)]
public static LocalDataStoreSlot GetNamedDataSlot(String name)
{
return LocalDataStoreManager.GetNamedDataSlot(name);
** threads. Named data slots are "public" and can be manipulated by
** anyone.
=========================================================================*/
- [HostProtection(SharedState=true, ExternalThreading=true)]
public static void FreeNamedDataSlot(String name)
{
LocalDataStoreManager.FreeNamedDataSlot(name);
/*=========================================================================
** Retrieves the value from the specified slot on the current thread, for that thread's current domain.
=========================================================================*/
- [HostProtection(SharedState=true, ExternalThreading=true)]
public static Object GetData(LocalDataStoreSlot slot)
{
LocalDataStoreHolder dls = s_LocalDataStore;
/*=========================================================================
** Sets the data in the specified slot on the currently running thread, for that thread's current domain.
=========================================================================*/
- [HostProtection(SharedState=true, ExternalThreading=true)]
public static void SetData(LocalDataStoreSlot slot, Object data)
{
LocalDataStoreHolder dls = s_LocalDataStore;
// default domain to lookup resources. See Environment.cs for more details.
//
#if FEATURE_LEAK_CULTURE_INFO
- [System.Security.SecurityCritical] // auto-generated
[MethodImplAttribute(MethodImplOptions.InternalCall)]
static extern private bool nativeGetSafeCulture(Thread t, int appDomainId, bool isUI, ref CultureInfo safeCulture);
#endif // FEATURE_LEAK_CULTURE_INFO
}
}
- [System.Security.SecuritySafeCritical] // auto-generated
- [HostProtection(ExternalThreading=true)]
set {
if (value == null) {
throw new ArgumentNullException(nameof(value));
}
#if FEATURE_LEAK_CULTURE_INFO
- [System.Security.SecuritySafeCritical] // auto-generated
#endif
internal CultureInfo GetCurrentUICultureNoAppX() {
// This returns the exposed context for a given context ID.
#if FEATURE_LEAK_CULTURE_INFO
- [System.Security.SecurityCritical] // auto-generated
[MethodImplAttribute(MethodImplOptions.InternalCall)]
static extern private bool nativeSetThreadUILocale(String locale);
#endif
}
}
- [System.Security.SecuritySafeCritical] // auto-generated
#if FEATURE_LEAK_CULTURE_INFO
- [SecurityPermission(SecurityAction.Demand, ControlThread = true)]
#endif
set {
if (null==value) {
}
#if FEATURE_LEAK_CULTURE_INFO
- [System.Security.SecuritySafeCritical] // auto-generated
#endif
private CultureInfo GetCurrentCultureNoAppX() {
}
#if !FEATURE_LEAK_CULTURE_INFO
- [System.Security.SecurityCritical] // auto-generated
[DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
[SuppressUnmanagedCodeSecurity]
private static extern void nativeInitCultureAccessors();
** Returns the current domain in which current thread is running.
======================================================================*/
- [System.Security.SecurityCritical] // auto-generated
[MethodImplAttribute(MethodImplOptions.InternalCall)]
private static extern AppDomain GetDomainInternal();
- [System.Security.SecurityCritical] // auto-generated
[MethodImplAttribute(MethodImplOptions.InternalCall)]
private static extern AppDomain GetFastDomainInternal();
- [System.Security.SecuritySafeCritical] // auto-generated
public static AppDomain GetDomain()
{
Contract.Ensures(Contract.Result<AppDomain>() != null);
get {
return m_Name;
}
- [System.Security.SecuritySafeCritical] // auto-generated
- [HostProtection(ExternalThreading=true)]
set {
lock(this) {
if (m_Name != null)
}
}
- [System.Security.SecurityCritical] // auto-generated
[DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
[SuppressUnmanagedCodeSecurity]
private static extern void InformThreadNameChange(ThreadHandle t, String name, int len);
internal Object AbortReason {
- [System.Security.SecurityCritical] // auto-generated
get {
object result = null;
try
}
return result;
}
- [System.Security.SecurityCritical] // auto-generated
set { SetAbortReason(value); }
}
-#if !FEATURE_CORECLR
- /*
- * This marks the beginning of a critical code region.
- */
- [System.Security.SecuritySafeCritical] // auto-generated
- [HostProtection(Synchronization=true, ExternalThreading=true)]
- [MethodImplAttribute(MethodImplOptions.InternalCall)]
- [ReliabilityContract(Consistency.WillNotCorruptState, Cer.MayFail)]
- public static extern void BeginCriticalRegion();
-
- /*
- * This marks the end of a critical code region.
- */
- [System.Security.SecuritySafeCritical] // auto-generated
- [HostProtection(Synchronization=true, ExternalThreading=true)]
- [MethodImplAttribute(MethodImplOptions.InternalCall)]
- [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)]
- public static extern void EndCriticalRegion();
-
- /*
- * This marks the beginning of a code region that requires thread affinity.
- */
- [System.Security.SecurityCritical] // auto-generated_required
- [MethodImplAttribute(MethodImplOptions.InternalCall)]
- [ReliabilityContract(Consistency.WillNotCorruptState, Cer.MayFail)]
- public static extern void BeginThreadAffinity();
-
- /*
- * This marks the end of a code region that requires thread affinity.
- */
- [System.Security.SecurityCritical] // auto-generated_required
- [MethodImplAttribute(MethodImplOptions.InternalCall)]
- [ReliabilityContract(Consistency.WillNotCorruptState, Cer.MayFail)]
- public static extern void EndThreadAffinity();
-#endif // !FEATURE_CORECLR
-
/*=========================================================================
** Volatile Read & Write and MemoryBarrier methods.
** Provides the ability to read and write values ensuring that the values
address = value;
}
- [System.Security.SecuritySafeCritical] // auto-generated
[MethodImplAttribute(MethodImplOptions.InternalCall)]
public static extern void MemoryBarrier();
}
}
-#if !FEATURE_CORECLR
- void _Thread.GetTypeInfoCount(out uint pcTInfo)
- {
- throw new NotImplementedException();
- }
-
- void _Thread.GetTypeInfo(uint iTInfo, uint lcid, IntPtr ppTInfo)
- {
- throw new NotImplementedException();
- }
-
- void _Thread.GetIDsOfNames([In] ref Guid riid, IntPtr rgszNames, uint cNames, uint lcid, IntPtr rgDispId)
- {
- throw new NotImplementedException();
- }
-
- void _Thread.Invoke(uint dispIdMember, [In] ref Guid riid, uint lcid, short wFlags, IntPtr pDispParams, IntPtr pVarResult, IntPtr pExcepInfo, IntPtr puArgErr)
- {
- throw new NotImplementedException();
- }
-#endif
-
// Helper function to set the AbortReason for a thread abort.
// Checks that they're not alredy set, and then atomically updates
// the reason info (object + ADID).
- [System.Security.SecurityCritical] // auto-generated
[MethodImplAttribute(MethodImplOptions.InternalCall)]
internal extern void SetAbortReason(Object o);
// Helper function to retrieve the AbortReason from a thread
// abort. Will perform cross-AppDomain marshalling if the object
// lives in a different AppDomain from the requester.
- [System.Security.SecurityCritical] // auto-generated
[MethodImplAttribute(MethodImplOptions.InternalCall)]
internal extern Object GetAbortReason();
// Helper function to clear the AbortReason. Takes care of
// AppDomain related cleanup if required.
- [System.Security.SecurityCritical] // auto-generated
[MethodImplAttribute(MethodImplOptions.InternalCall)]
internal extern void ClearAbortReason();
public Object ExceptionState
{
- [System.Security.SecuritySafeCritical] // auto-generated
get {return Thread.CurrentThread.AbortReason;}
}
}
//
// =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-
-using System.Diagnostics;
using System.Collections.Generic;
using System.Security.Permissions;
+using System.Diagnostics;
using System.Diagnostics.Contracts;
namespace System.Threading
/// </remarks>
[DebuggerTypeProxy(typeof(SystemThreading_ThreadLocalDebugView<>))]
[DebuggerDisplay("IsValueCreated={IsValueCreated}, Value={ValueForDebugDisplay}, Count={ValuesCountForDebugDisplay}")]
- [HostProtection(Synchronization = true, ExternalThreading = true)]
public class ThreadLocal<T> : IDisposable
{
if (id < 0 || !m_initialized)
{
- Contract.Assert(id >= 0 || !m_initialized, "expected id >= 0 if initialized");
+ Debug.Assert(id >= 0 || !m_initialized, "expected id >= 0 if initialized");
// Handle double Dispose calls or disposal of an instance whose constructor threw an exception.
return;
/// </summary>
private void GrowTable(ref LinkedSlotVolatile[] table, int minLength)
{
- Contract.Assert(table.Length < minLength);
+ Debug.Assert(table.Length < minLength);
// Determine the size of the new table and allocate it.
int newLen = GetNewTableSize(minLength);
// Intentionally return a value that will result in an OutOfMemoryException
return int.MaxValue;
}
- Contract.Assert(minSize > 0);
+ Debug.Assert(minSize > 0);
//
// Round up the size to the next power of 2
~FinalizationHelper()
{
LinkedSlotVolatile[] slotArray = SlotArray;
- Contract.Assert(slotArray != null);
+ Debug.Assert(slotArray != null);
for (int i = 0; i < slotArray.Length; i++)
{
}
// Since the list uses a dummy head node, the Previous reference should never be null.
- Contract.Assert(linkedSlot.Previous != null);
+ Debug.Assert(linkedSlot.Previous != null);
linkedSlot.Previous.Next = linkedSlot.Next;
}
}
namespace System.Threading
{
using System.Security;
-#if FEATURE_REMOTING
- using System.Runtime.Remoting;
-#endif
using System.Security.Permissions;
using System;
using Microsoft.Win32;
using System.Runtime.ConstrainedExecution;
using System.Runtime.InteropServices;
using System.Collections.Generic;
+ using System.Diagnostics;
using System.Diagnostics.Contracts;
using System.Diagnostics.CodeAnalysis;
using System.Diagnostics.Tracing;
public static volatile bool vmTpInitialized;
public static bool enableWorkerTracking;
- [SecurityCritical]
public static readonly ThreadPoolWorkQueue workQueue = new ThreadPoolWorkQueue();
- [System.Security.SecuritySafeCritical] // static constructors should be safe to call
static ThreadPoolGlobals()
{
}
//
m_headIndex = m_headIndex & m_mask;
m_tailIndex = tail = m_tailIndex & m_mask;
- Contract.Assert(m_headIndex <= m_tailIndex);
+ Debug.Assert(m_headIndex <= m_tailIndex);
}
}
finally
IThreadPoolWorkItem unused;
if (LocalPop(out unused))
{
- Contract.Assert(unused == obj);
+ Debug.Assert(unused == obj);
return true;
}
return false;
upper = (i >> 16) & SixteenBits;
lower = i & SixteenBits;
- Contract.Assert(upper >= lower);
- Contract.Assert(upper <= nodes.Length);
- Contract.Assert(lower <= nodes.Length);
- Contract.Assert(upper >= 0);
- Contract.Assert(lower >= 0);
+ Debug.Assert(upper >= lower);
+ Debug.Assert(upper <= nodes.Length);
+ Debug.Assert(lower <= nodes.Length);
+ Debug.Assert(upper >= 0);
+ Debug.Assert(lower >= 0);
}
bool CompareExchangeIndexes(ref int prevUpper, int newUpper, ref int prevLower, int newLower)
{
- Contract.Assert(newUpper >= newLower);
- Contract.Assert(newUpper <= nodes.Length);
- Contract.Assert(newLower <= nodes.Length);
- Contract.Assert(newUpper >= 0);
- Contract.Assert(newLower >= 0);
- Contract.Assert(newUpper >= prevUpper);
- Contract.Assert(newLower >= prevLower);
- Contract.Assert(newUpper == prevUpper ^ newLower == prevLower);
+ Debug.Assert(newUpper >= newLower);
+ Debug.Assert(newUpper <= nodes.Length);
+ Debug.Assert(newLower <= nodes.Length);
+ Debug.Assert(newUpper >= 0);
+ Debug.Assert(newLower >= 0);
+ Debug.Assert(newUpper >= prevUpper);
+ Debug.Assert(newLower >= prevLower);
+ Debug.Assert(newUpper == prevUpper ^ newLower == prevLower);
int oldIndexes = (prevUpper << 16) | (prevLower & SixteenBits);
int newIndexes = (newUpper << 16) | (newLower & SixteenBits);
[ReliabilityContract(Consistency.WillNotCorruptState, Cer.MayFail)]
public QueueSegment()
{
- Contract.Assert(QueueSegmentLength <= SixteenBits);
+ Debug.Assert(QueueSegmentLength <= SixteenBits);
nodes = new IThreadPoolWorkItem[QueueSegmentLength];
}
// with a busy-wait loop, waiting for the element to become non-null. This implies
// that we can never store null nodes in this data structure.
//
- Contract.Assert(null != node);
+ Debug.Assert(null != node);
int upper, lower;
GetIndexes(out upper, out lower);
if (CompareExchangeIndexes(ref upper, upper + 1, ref lower, lower))
{
- Contract.Assert(Volatile.Read(ref nodes[upper]) == null);
+ Debug.Assert(Volatile.Read(ref nodes[upper]) == null);
Volatile.Write(ref nodes[upper], node);
return true;
}
loggingEnabled = FrameworkEventSource.Log.IsEnabled(EventLevel.Verbose, FrameworkEventSource.Keywords.ThreadPool|FrameworkEventSource.Keywords.ThreadTransfer);
}
- [SecurityCritical]
public ThreadPoolWorkQueueThreadLocals EnsureCurrentThreadHasQueue()
{
if (null == ThreadPoolWorkQueueThreadLocals.threadLocals)
return ThreadPoolWorkQueueThreadLocals.threadLocals;
}
- [SecurityCritical]
internal void EnsureThreadRequested()
{
//
}
}
- [SecurityCritical]
internal void MarkThreadRequestSatisfied()
{
//
}
}
- [SecurityCritical]
public void Enqueue(IThreadPoolWorkItem callback, bool forceGlobal)
{
ThreadPoolWorkQueueThreadLocals tl = null;
EnsureThreadRequested();
}
- [SecurityCritical]
internal bool LocalFindAndPop(IThreadPoolWorkItem callback)
{
ThreadPoolWorkQueueThreadLocals tl = ThreadPoolWorkQueueThreadLocals.threadLocals;
return tl.workStealingQueue.LocalFindAndPop(callback);
}
- [SecurityCritical]
public void Dequeue(ThreadPoolWorkQueueThreadLocals tl, out IThreadPoolWorkItem callback, out bool missedSteal)
{
callback = null;
WorkStealingQueue wsq = tl.workStealingQueue;
if (wsq.LocalPop(out callback))
- Contract.Assert(null != callback);
+ Debug.Assert(null != callback);
if (null == callback)
{
{
if (tail.TryDequeue(out callback))
{
- Contract.Assert(null != callback);
+ Debug.Assert(null != callback);
break;
}
otherQueue != wsq &&
otherQueue.TrySteal(out callback, ref missedSteal))
{
- Contract.Assert(null != callback);
+ Debug.Assert(null != callback);
break;
}
c--;
}
}
- [SecurityCritical]
static internal bool Dispatch()
{
var workQueue = ThreadPoolGlobals.workQueue;
}
// we can never reach this point, but the C# compiler doesn't know that, because it doesn't know the ThreadAbortException will be reraised above.
- Contract.Assert(false);
+ Debug.Assert(false);
return true;
}
}
internal sealed class ThreadPoolWorkQueueThreadLocals
{
[ThreadStatic]
- [SecurityCritical]
public static ThreadPoolWorkQueueThreadLocals threadLocals;
public readonly ThreadPoolWorkQueue workQueue;
ThreadPoolWorkQueue.allThreadQueues.Add(workStealingQueue);
}
- [SecurityCritical]
private void CleanUp()
{
if (null != workStealingQueue)
IThreadPoolWorkItem cb = null;
if (workStealingQueue.LocalPop(out cb))
{
- Contract.Assert(null != cb);
+ Debug.Assert(null != cb);
workQueue.Enqueue(cb, true);
}
else
}
}
- [SecuritySafeCritical]
~ThreadPoolWorkQueueThreadLocals()
{
// Since the purpose of calling CleanUp is to transfer any pending workitems into the global
{
private static IntPtr InvalidHandle
{
- [System.Security.SecuritySafeCritical] // auto-generated
get
{
return Win32Native.INVALID_HANDLE_VALUE;
private bool bReleaseNeeded = false;
private volatile int m_lock = 0;
- #if FEATURE_CORECLR
- [System.Security.SecuritySafeCritical] // auto-generated
- #endif
internal RegisteredWaitHandleSafe()
{
registeredWaitHandle = InvalidHandle;
registeredWaitHandle = handle;
}
- [System.Security.SecurityCritical] // auto-generated
[ReliabilityContract(Consistency.WillNotCorruptState, Cer.MayFail)]
internal void SetWaitObject(WaitHandle waitObject)
{
}
}
- [System.Security.SecurityCritical] // auto-generated
[ReliabilityContract(Consistency.WillNotCorruptState, Cer.MayFail)]
internal bool Unregister(
WaitHandle waitObject // object to be notified when all callbacks to delegates have completed
return (registeredWaitHandle != InvalidHandle && registeredWaitHandle != IntPtr.Zero);
}
- [System.Security.SecuritySafeCritical] // auto-generated
~RegisteredWaitHandleSafe()
{
// if the app has already unregistered the wait, there is nothing to cleanup
}
}
- [System.Security.SecurityCritical] // auto-generated
[MethodImplAttribute(MethodImplOptions.InternalCall)]
private static extern void WaitHandleCleanupNative(IntPtr handle);
- [System.Security.SecurityCritical] // auto-generated
[MethodImplAttribute(MethodImplOptions.InternalCall)]
private static extern bool UnregisterWaitNative(IntPtr handle, SafeHandle waitObject);
}
internalRegisteredWait.SetHandle(handle);
}
- [System.Security.SecurityCritical] // auto-generated
internal void SetWaitObject(WaitHandle waitObject)
{
internalRegisteredWait.SetWaitObject(waitObject);
}
-[System.Security.SecuritySafeCritical] // auto-generated
[System.Runtime.InteropServices.ComVisible(true)]
// This is the only public method on this class
public bool Unregister(
//
internal static class _ThreadPoolWaitCallback
{
- [System.Security.SecurityCritical]
static internal bool PerformWaitCallback()
{
return ThreadPoolWorkQueue.Dispatch();
//
internal interface IThreadPoolWorkItem
{
- [SecurityCritical]
void ExecuteWorkItem();
- [SecurityCritical]
void MarkAborted(ThreadAbortException tae);
}
internal sealed class QueueUserWorkItemCallback : IThreadPoolWorkItem
{
- [System.Security.SecuritySafeCritical]
static QueueUserWorkItemCallback() {}
private WaitCallback callback;
~QueueUserWorkItemCallback()
{
- Contract.Assert(
+ Debug.Assert(
executed != 0 || Environment.HasShutdownStarted || AppDomain.CurrentDomain.IsFinalizingForUnload(),
"A QueueUserWorkItemCallback was never called!");
}
void MarkExecuted(bool aborted)
{
GC.SuppressFinalize(this);
- Contract.Assert(
+ Debug.Assert(
0 == Interlocked.Exchange(ref executed, 1) || aborted,
"A QueueUserWorkItemCallback was called twice!");
}
#endif
- [SecurityCritical]
internal QueueUserWorkItemCallback(WaitCallback waitCallback, Object stateObj, ExecutionContext ec)
{
callback = waitCallback;
context = ec;
}
- [SecurityCritical]
void IThreadPoolWorkItem.ExecuteWorkItem()
{
#if DEBUG
}
}
- [SecurityCritical]
void IThreadPoolWorkItem.MarkAborted(ThreadAbortException tae)
{
#if DEBUG
#endif
}
- [System.Security.SecurityCritical]
static internal ContextCallback ccb = new ContextCallback(WaitCallback_Context);
- [System.Security.SecurityCritical]
static private void WaitCallback_Context(Object state)
{
QueueUserWorkItemCallback obj = (QueueUserWorkItemCallback)state;
WaitCallback wc = obj.callback as WaitCallback;
- Contract.Assert(null != wc);
+ Debug.Assert(null != wc);
wc(obj.state);
}
}
internal sealed class QueueUserWorkItemCallbackDefaultContext : IThreadPoolWorkItem
{
- [System.Security.SecuritySafeCritical]
static QueueUserWorkItemCallbackDefaultContext() { }
private WaitCallback callback;
~QueueUserWorkItemCallbackDefaultContext()
{
- Contract.Assert(
+ Debug.Assert(
executed != 0 || Environment.HasShutdownStarted || AppDomain.CurrentDomain.IsFinalizingForUnload(),
"A QueueUserWorkItemCallbackDefaultContext was never called!");
}
void MarkExecuted(bool aborted)
{
GC.SuppressFinalize(this);
- Contract.Assert(
+ Debug.Assert(
0 == Interlocked.Exchange(ref executed, 1) || aborted,
"A QueueUserWorkItemCallbackDefaultContext was called twice!");
}
#endif
- [SecurityCritical]
internal QueueUserWorkItemCallbackDefaultContext(WaitCallback waitCallback, Object stateObj)
{
callback = waitCallback;
state = stateObj;
}
- [SecurityCritical]
void IThreadPoolWorkItem.ExecuteWorkItem()
{
#if DEBUG
ExecutionContext.Run(ExecutionContext.PreAllocatedDefault, ccb, this, true);
}
- [SecurityCritical]
void IThreadPoolWorkItem.MarkAborted(ThreadAbortException tae)
{
#if DEBUG
#endif
}
- [System.Security.SecurityCritical]
static internal ContextCallback ccb = new ContextCallback(WaitCallback_Context);
- [System.Security.SecurityCritical]
static private void WaitCallback_Context(Object state)
{
QueueUserWorkItemCallbackDefaultContext obj = (QueueUserWorkItemCallbackDefaultContext)state;
WaitCallback wc = obj.callback as WaitCallback;
- Contract.Assert(null != wc);
+ Debug.Assert(null != wc);
obj.callback = null;
wc(obj.state);
}
internal class _ThreadPoolWaitOrTimerCallback
{
- [System.Security.SecuritySafeCritical]
static _ThreadPoolWaitOrTimerCallback() {}
WaitOrTimerCallback _waitOrTimerCallback;
ExecutionContext _executionContext;
Object _state;
- [System.Security.SecurityCritical]
static private ContextCallback _ccbt = new ContextCallback(WaitOrTimerCallback_Context_t);
- [System.Security.SecurityCritical]
static private ContextCallback _ccbf = new ContextCallback(WaitOrTimerCallback_Context_f);
- [System.Security.SecurityCritical] // auto-generated
internal _ThreadPoolWaitOrTimerCallback(WaitOrTimerCallback waitOrTimerCallback, Object state, bool compressStack, ref StackCrawlMark stackMark)
{
_waitOrTimerCallback = waitOrTimerCallback;
}
}
- [System.Security.SecurityCritical]
static private void WaitOrTimerCallback_Context_t(Object state)
{
WaitOrTimerCallback_Context(state, true);
}
- [System.Security.SecurityCritical]
static private void WaitOrTimerCallback_Context_f(Object state)
{
WaitOrTimerCallback_Context(state, false);
}
// call back helper
- [System.Security.SecurityCritical] // auto-generated
static internal void PerformWaitOrTimerCallback(Object state, bool timedOut)
{
_ThreadPoolWaitOrTimerCallback helper = (_ThreadPoolWaitOrTimerCallback)state;
- Contract.Assert(helper != null, "Null state passed to PerformWaitOrTimerCallback!");
+ Debug.Assert(helper != null, "Null state passed to PerformWaitOrTimerCallback!");
// call directly if it is an unsafe call OR EC flow is suppressed
if (helper._executionContext == null)
{
}
- [System.Security.SecurityCritical]
[CLSCompliant(false)]
[System.Runtime.InteropServices.ComVisible(true)]
unsafe public delegate void IOCompletionCallback(uint errorCode, // Error code
NativeOverlapped* pOVERLAP // ptr to OVERLAP structure
);
- [HostProtection(Synchronization=true, ExternalThreading=true)]
public static class ThreadPool
{
- #if FEATURE_CORECLR
- [System.Security.SecurityCritical] // auto-generated
- #else
- [System.Security.SecuritySafeCritical]
- #endif
-#pragma warning disable 618
- [SecurityPermissionAttribute(SecurityAction.Demand, ControlThread = true)]
-#pragma warning restore 618
public static bool SetMaxThreads(int workerThreads, int completionPortThreads)
{
return SetMaxThreadsNative(workerThreads, completionPortThreads);
}
- [System.Security.SecuritySafeCritical] // auto-generated
public static void GetMaxThreads(out int workerThreads, out int completionPortThreads)
{
GetMaxThreadsNative(out workerThreads, out completionPortThreads);
}
- #if FEATURE_CORECLR
- [System.Security.SecurityCritical] // auto-generated
- #else
- [System.Security.SecuritySafeCritical]
- #endif
-#pragma warning disable 618
- [SecurityPermissionAttribute(SecurityAction.Demand, ControlThread = true)]
-#pragma warning restore 618
public static bool SetMinThreads(int workerThreads, int completionPortThreads)
{
return SetMinThreadsNative(workerThreads, completionPortThreads);
}
- [System.Security.SecuritySafeCritical] // auto-generated
public static void GetMinThreads(out int workerThreads, out int completionPortThreads)
{
GetMinThreadsNative(out workerThreads, out completionPortThreads);
}
- [System.Security.SecuritySafeCritical] // auto-generated
public static void GetAvailableThreads(out int workerThreads, out int completionPortThreads)
{
GetAvailableThreadsNative(out workerThreads, out completionPortThreads);
}
- [System.Security.SecuritySafeCritical] // auto-generated
[CLSCompliant(false)]
[MethodImplAttribute(MethodImplOptions.NoInlining)] // Methods containing StackCrawlMark local var has to be marked non-inlineable
public static RegisteredWaitHandle RegisterWaitForSingleObject( // throws RegisterWaitException
return RegisterWaitForSingleObject(waitObject,callBack,state,millisecondsTimeOutInterval,executeOnlyOnce,ref stackMark,true);
}
- [System.Security.SecurityCritical] // auto-generated_required
[CLSCompliant(false)]
[MethodImplAttribute(MethodImplOptions.NoInlining)] // Methods containing StackCrawlMark local var has to be marked non-inlineable
public static RegisteredWaitHandle UnsafeRegisterWaitForSingleObject( // throws RegisterWaitException
}
- [System.Security.SecurityCritical] // auto-generated
private static RegisteredWaitHandle RegisterWaitForSingleObject( // throws RegisterWaitException
WaitHandle waitObject,
WaitOrTimerCallback callBack,
bool compressStack
)
{
-#if FEATURE_REMOTING
- if (RemotingServices.IsTransparentProxy(waitObject))
- throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_WaitOnTransparentProxy"));
- Contract.EndContractBlock();
-#endif
-
RegisteredWaitHandle registeredWaitHandle = new RegisteredWaitHandle();
if (callBack != null)
}
- [System.Security.SecuritySafeCritical] // auto-generated
[MethodImplAttribute(MethodImplOptions.NoInlining)] // Methods containing StackCrawlMark local var has to be marked non-inlineable
public static RegisteredWaitHandle RegisterWaitForSingleObject( // throws RegisterWaitException
WaitHandle waitObject,
return RegisterWaitForSingleObject(waitObject,callBack,state,(UInt32)millisecondsTimeOutInterval,executeOnlyOnce,ref stackMark,true);
}
- [System.Security.SecurityCritical] // auto-generated_required
[MethodImplAttribute(MethodImplOptions.NoInlining)] // Methods containing StackCrawlMark local var has to be marked non-inlineable
public static RegisteredWaitHandle UnsafeRegisterWaitForSingleObject( // throws RegisterWaitException
WaitHandle waitObject,
return RegisterWaitForSingleObject(waitObject,callBack,state,(UInt32)millisecondsTimeOutInterval,executeOnlyOnce,ref stackMark,false);
}
- [System.Security.SecuritySafeCritical] // auto-generated
[MethodImplAttribute(MethodImplOptions.NoInlining)] // Methods containing StackCrawlMark local var has to be marked non-inlineable
public static RegisteredWaitHandle RegisterWaitForSingleObject( // throws RegisterWaitException
WaitHandle waitObject,
return RegisterWaitForSingleObject(waitObject,callBack,state,(UInt32)millisecondsTimeOutInterval,executeOnlyOnce,ref stackMark,true);
}
- [System.Security.SecurityCritical] // auto-generated_required
[MethodImplAttribute(MethodImplOptions.NoInlining)] // Methods containing StackCrawlMark local var has to be marked non-inlineable
public static RegisteredWaitHandle UnsafeRegisterWaitForSingleObject( // throws RegisterWaitException
WaitHandle waitObject,
return RegisterWaitForSingleObject(waitObject,callBack,state,(UInt32)millisecondsTimeOutInterval,executeOnlyOnce,ref stackMark,false);
}
- [System.Security.SecuritySafeCritical] // auto-generated
[MethodImplAttribute(MethodImplOptions.NoInlining)] // Methods containing StackCrawlMark local var has to be marked non-inlineable
public static RegisteredWaitHandle RegisterWaitForSingleObject(
WaitHandle waitObject,
return RegisterWaitForSingleObject(waitObject,callBack,state,(UInt32)tm,executeOnlyOnce,ref stackMark,true);
}
- [System.Security.SecurityCritical] // auto-generated_required
[MethodImplAttribute(MethodImplOptions.NoInlining)] // Methods containing StackCrawlMark local var has to be marked non-inlineable
public static RegisteredWaitHandle UnsafeRegisterWaitForSingleObject(
WaitHandle waitObject,
return RegisterWaitForSingleObject(waitObject,callBack,state,(UInt32)tm,executeOnlyOnce,ref stackMark,false);
}
- [System.Security.SecuritySafeCritical] // auto-generated
[MethodImplAttribute(MethodImplOptions.NoInlining)] // Methods containing StackCrawlMark local var has to be marked non-inlineable
public static bool QueueUserWorkItem(
WaitCallback callBack, // NOTE: we do not expose options that allow the callback to be queued as an APC
return QueueUserWorkItemHelper(callBack,state,ref stackMark,true);
}
- [System.Security.SecuritySafeCritical] // auto-generated
[MethodImplAttribute(MethodImplOptions.NoInlining)] // Methods containing StackCrawlMark local var has to be marked non-inlineable
public static bool QueueUserWorkItem(
WaitCallback callBack // NOTE: we do not expose options that allow the callback to be queued as an APC
return QueueUserWorkItemHelper(callBack,null,ref stackMark,true);
}
- [System.Security.SecurityCritical] // auto-generated_required
[MethodImplAttribute(MethodImplOptions.NoInlining)] // Methods containing StackCrawlMark local var has to be marked non-inlineable
public static bool UnsafeQueueUserWorkItem(
WaitCallback callBack, // NOTE: we do not expose options that allow the callback to be queued as an APC
//ThreadPool has per-appdomain managed queue of work-items. The VM is
//responsible for just scheduling threads into appdomains. After that
//work-items are dispatched from the managed queue.
- [System.Security.SecurityCritical] // auto-generated
private static bool QueueUserWorkItemHelper(WaitCallback callBack, Object state, ref StackCrawlMark stackMark, bool compressStack )
{
bool success = true;
return success;
}
- [SecurityCritical]
internal static void UnsafeQueueCustomWorkItem(IThreadPoolWorkItem workItem, bool forceGlobal)
{
- Contract.Assert(null != workItem);
+ Debug.Assert(null != workItem);
EnsureVMInitialized();
//
}
// This method tries to take the target callback out of the current thread's queue.
- [SecurityCritical]
internal static bool TryPopCustomWorkItem(IThreadPoolWorkItem workItem)
{
- Contract.Assert(null != workItem);
+ Debug.Assert(null != workItem);
if (!ThreadPoolGlobals.vmTpInitialized)
return false; //Not initialized, so there's no way this workitem was ever queued.
return ThreadPoolGlobals.workQueue.LocalFindAndPop(workItem);
}
// Get all workitems. Called by TaskScheduler in its debugger hooks.
- [SecurityCritical]
internal static IEnumerable<IThreadPoolWorkItem> GetQueuedWorkItems()
{
return EnumerateQueuedWorkItems(ThreadPoolWorkQueue.allThreadQueues.Current, ThreadPoolGlobals.workQueue.queueTail);
}
}
- [SecurityCritical]
internal static IEnumerable<IThreadPoolWorkItem> GetLocallyQueuedWorkItems()
{
return EnumerateQueuedWorkItems(new ThreadPoolWorkQueue.WorkStealingQueue[] { ThreadPoolWorkQueueThreadLocals.threadLocals.workStealingQueue }, null);
}
- [SecurityCritical]
internal static IEnumerable<IThreadPoolWorkItem> GetGloballyQueuedWorkItems()
{
return EnumerateQueuedWorkItems(null, ThreadPoolGlobals.workQueue.queueTail);
// This is the method the debugger will actually call, if it ends up calling
// into ThreadPool directly. Tests can use this to simulate a debugger, as well.
- [SecurityCritical]
internal static object[] GetQueuedWorkItemsForDebugger()
{
return ToObjectArray(GetQueuedWorkItems());
}
- [SecurityCritical]
internal static object[] GetGloballyQueuedWorkItemsForDebugger()
{
return ToObjectArray(GetGloballyQueuedWorkItems());
}
- [SecurityCritical]
internal static object[] GetLocallyQueuedWorkItemsForDebugger()
{
return ToObjectArray(GetLocallyQueuedWorkItems());
}
- [System.Security.SecurityCritical] // auto-generated
[DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
[SuppressUnmanagedCodeSecurity]
internal static extern bool RequestWorkerThread();
- [System.Security.SecurityCritical] // auto-generated
[MethodImplAttribute(MethodImplOptions.InternalCall)]
unsafe private static extern bool PostQueuedCompletionStatus(NativeOverlapped* overlapped);
- [System.Security.SecurityCritical] // auto-generated_required
[CLSCompliant(false)]
unsafe public static bool UnsafeQueueNativeOverlapped(NativeOverlapped* overlapped)
{
return PostQueuedCompletionStatus(overlapped);
}
- [SecurityCritical]
private static void EnsureVMInitialized()
{
if (!ThreadPoolGlobals.vmTpInitialized)
// Native methods:
- [System.Security.SecurityCritical] // auto-generated
[MethodImplAttribute(MethodImplOptions.InternalCall)]
private static extern bool SetMinThreadsNative(int workerThreads, int completionPortThreads);
- [System.Security.SecurityCritical] // auto-generated
[MethodImplAttribute(MethodImplOptions.InternalCall)]
private static extern bool SetMaxThreadsNative(int workerThreads, int completionPortThreads);
- [System.Security.SecurityCritical] // auto-generated
[MethodImplAttribute(MethodImplOptions.InternalCall)]
private static extern void GetMinThreadsNative(out int workerThreads, out int completionPortThreads);
- [System.Security.SecurityCritical] // auto-generated
[MethodImplAttribute(MethodImplOptions.InternalCall)]
private static extern void GetMaxThreadsNative(out int workerThreads, out int completionPortThreads);
- [System.Security.SecurityCritical] // auto-generated
[MethodImplAttribute(MethodImplOptions.InternalCall)]
private static extern void GetAvailableThreadsNative(out int workerThreads, out int completionPortThreads);
- [System.Security.SecurityCritical] // auto-generated
[MethodImplAttribute(MethodImplOptions.InternalCall)]
internal static extern bool NotifyWorkItemComplete();
- [System.Security.SecurityCritical]
[MethodImplAttribute(MethodImplOptions.InternalCall)]
internal static extern void ReportThreadStatus(bool isWorking);
- [System.Security.SecuritySafeCritical]
internal static void NotifyWorkItemProgress()
{
if (!ThreadPoolGlobals.vmTpInitialized)
NotifyWorkItemProgressNative();
}
- [System.Security.SecurityCritical] // auto-generated
[MethodImplAttribute(MethodImplOptions.InternalCall)]
internal static extern void NotifyWorkItemProgressNative();
- [System.Security.SecurityCritical] // auto-generated
[MethodImplAttribute(MethodImplOptions.InternalCall)]
internal static extern bool IsThreadPoolHosted();
- [System.Security.SecurityCritical] // auto-generated
[DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
[SuppressUnmanagedCodeSecurity]
private static extern void InitializeVMTp(ref bool enableWorkerTracking);
- [System.Security.SecurityCritical] // auto-generated
[MethodImplAttribute(MethodImplOptions.InternalCall)]
private static extern IntPtr RegisterWaitForSingleObjectNative(
WaitHandle waitHandle,
);
- [System.Security.SecuritySafeCritical] // auto-generated
[Obsolete("ThreadPool.BindHandle(IntPtr) has been deprecated. Please use ThreadPool.BindHandle(SafeHandle) instead.", false)]
-#pragma warning disable 618
- [SecurityPermissionAttribute( SecurityAction.Demand, Flags = SecurityPermissionFlag.UnmanagedCode)]
-#pragma warning restore 618
public static bool BindHandle(
IntPtr osHandle
)
return BindIOCompletionCallbackNative(osHandle);
}
- #if FEATURE_CORECLR
- [System.Security.SecurityCritical] // auto-generated
- #else
- [System.Security.SecuritySafeCritical]
- #endif
-#pragma warning disable 618
- [SecurityPermissionAttribute(SecurityAction.Demand, Flags = SecurityPermissionFlag.UnmanagedCode)]
-#pragma warning restore 618
public static bool BindHandle(SafeHandle osHandle)
{
if (osHandle == null)
return ret;
}
- [System.Security.SecurityCritical] // auto-generated
[MethodImplAttribute(MethodImplOptions.InternalCall)]
[ReliabilityContract(Consistency.WillNotCorruptState, Cer.MayFail)]
private static extern bool BindIOCompletionCallbackNative(IntPtr fileHandle);
using System.Runtime.InteropServices;
using System.Runtime.ConstrainedExecution;
using System.Runtime.Versioning;
+ using System.Diagnostics;
using System.Diagnostics.Contracts;
using System.Diagnostics.Tracing;
using Microsoft.Win32.SafeHandles;
//
private static int TickCount
{
- [SecuritySafeCritical]
get
{
#if !FEATURE_PAL
//
// We use a SafeHandle to ensure that the native timer is destroyed when the AppDomain is unloaded.
//
- [SecurityCritical]
class AppDomainTimerSafeHandle : SafeHandleZeroOrMinusOneIsInvalid
{
public AppDomainTimerSafeHandle()
{
}
- [SecurityCritical]
[ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)]
protected override bool ReleaseHandle()
{
}
}
- [SecurityCritical]
AppDomainTimerSafeHandle m_appDomainTimer;
bool m_isAppDomainTimerScheduled;
int m_currentAppDomainTimerStartTicks;
uint m_currentAppDomainTimerDuration;
- [SecuritySafeCritical]
private bool EnsureAppDomainTimerFiresBy(uint requestedDuration)
{
//
// A later update during resume will re-schedule
if(m_pauseTicks != 0)
{
- Contract.Assert(!m_isAppDomainTimerScheduled);
- Contract.Assert(m_appDomainTimer == null);
+ Debug.Assert(!m_isAppDomainTimerScheduled);
+ Debug.Assert(m_appDomainTimer == null);
return true;
}
if (m_appDomainTimer == null || m_appDomainTimer.IsInvalid)
{
- Contract.Assert(!m_isAppDomainTimerScheduled);
+ Debug.Assert(!m_isAppDomainTimerScheduled);
m_appDomainTimer = CreateAppDomainTimer(actualDuration);
if (!m_appDomainTimer.IsInvalid)
//
// The VM calls this when the native timer fires.
//
- [SecuritySafeCritical]
internal static void AppDomainTimerCallback()
{
Instance.FireNextTimers();
}
- [System.Security.SecurityCritical]
[DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
[SuppressUnmanagedCodeSecurity]
static extern AppDomainTimerSafeHandle CreateAppDomainTimer(uint dueTime);
- [System.Security.SecurityCritical]
[DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
[SuppressUnmanagedCodeSecurity]
static extern bool ChangeAppDomainTimer(AppDomainTimerSafeHandle handle, uint dueTime);
- [System.Security.SecurityCritical]
[DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
[SuppressUnmanagedCodeSecurity]
[ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)]
volatile int m_pauseTicks = 0; // Time when Pause was called
- [SecurityCritical]
internal void Pause()
{
lock(this)
}
}
- [SecurityCritical]
internal void Resume()
{
//
TimerQueueTimer timer = m_timers;
while (timer != null)
{
- Contract.Assert(timer.m_dueTime != Timeout.UnsignedInfinite);
- Contract.Assert(resumedTicks >= timer.m_startTicks);
+ Debug.Assert(timer.m_dueTime != Timeout.UnsignedInfinite);
+ Debug.Assert(resumedTicks >= timer.m_startTicks);
uint elapsed; // How much of the timer dueTime has already elapsed
TimerQueueTimer timer = m_timers;
while (timer != null)
{
- Contract.Assert(timer.m_dueTime != Timeout.UnsignedInfinite);
+ Debug.Assert(timer.m_dueTime != Timeout.UnsignedInfinite);
uint elapsed = (uint)(nowTicks - timer.m_startTicks);
if (elapsed >= timer.m_dueTime)
timerToFireOnThisThread.Fire();
}
- [SecuritySafeCritical]
private static void QueueTimerCompletion(TimerQueueTimer timer)
{
WaitCallback callback = s_fireQueuedTimerCompletion;
volatile WaitHandle m_notifyWhenNoCallbacksRunning;
- [SecurityCritical]
internal TimerQueueTimer(TimerCallback timerCallback, object state, uint dueTime, uint period, ref StackCrawlMark stackMark)
{
m_timerCallback = timerCallback;
SignalNoCallbacksRunning();
}
- [SecuritySafeCritical]
internal void SignalNoCallbacksRunning()
{
Win32Native.SetEvent(m_notifyWhenNoCallbacksRunning.SafeWaitHandle);
}
- [SecuritySafeCritical]
internal void CallCallback()
{
if (FrameworkEventSource.IsInitialized && FrameworkEventSource.Log.IsEnabled(EventLevel.Informational, FrameworkEventSource.Keywords.ThreadTransfer))
}
}
- [SecurityCritical]
private static ContextCallback s_callCallbackInContext;
- [SecurityCritical]
private static void CallCallbackInContext(object state)
{
TimerQueueTimer t = (TimerQueueTimer)state;
}
- [HostProtection(Synchronization=true, ExternalThreading=true)]
[System.Runtime.InteropServices.ComVisible(true)]
public sealed class Timer : MarshalByRefObject, IDisposable
{
private TimerHolder m_timer;
- [SecuritySafeCritical]
[MethodImplAttribute(MethodImplOptions.NoInlining)] // Methods containing StackCrawlMark local var has to be marked non-inlineable
public Timer(TimerCallback callback,
Object state,
TimerSetup(callback,state,(UInt32)dueTime,(UInt32)period,ref stackMark);
}
- [SecuritySafeCritical]
[MethodImplAttribute(MethodImplOptions.NoInlining)] // Methods containing StackCrawlMark local var has to be marked non-inlineable
public Timer(TimerCallback callback,
Object state,
}
[CLSCompliant(false)]
- [SecuritySafeCritical]
[MethodImplAttribute(MethodImplOptions.NoInlining)] // Methods containing StackCrawlMark local var has to be marked non-inlineable
public Timer(TimerCallback callback,
Object state,
TimerSetup(callback,state,dueTime,period,ref stackMark);
}
- [SecuritySafeCritical]
[MethodImplAttribute(MethodImplOptions.NoInlining)] // Methods containing StackCrawlMark local var has to be marked non-inlineable
public Timer(TimerCallback callback,
Object state,
TimerSetup(callback,state,(UInt32) dueTime, (UInt32) period,ref stackMark);
}
- [SecuritySafeCritical]
[MethodImplAttribute(MethodImplOptions.NoInlining)] // Methods containing StackCrawlMark local var has to be marked non-inlineable
public Timer(TimerCallback callback)
{
TimerSetup(callback, this, (UInt32)dueTime, (UInt32)period, ref stackMark);
}
- [SecurityCritical]
private void TimerSetup(TimerCallback callback,
Object state,
UInt32 dueTime,
m_timer = new TimerHolder(new TimerQueueTimer(callback, state, dueTime, period, ref stackMark));
}
- [SecurityCritical]
internal static void Pause()
{
TimerQueue.Instance.Pause();
}
- [SecurityCritical]
internal static void Resume()
{
TimerQueue.Instance.Resume();
[ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)]
[CLSCompliant(false)]
[System.Runtime.Versioning.NonVersionable]
- [SecuritySafeCritical] // to match 32-bit version
public static ulong Read(ref ulong location)
{
//
[ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)]
[CLSCompliant(false)]
- [SecuritySafeCritical] // contains unsafe code
public static ulong Read(ref ulong location)
{
unsafe
}
[ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)]
- [SecuritySafeCritical] //the intrinsic implementation of this method contains unverifiable code
[System.Runtime.Versioning.NonVersionable]
public static T Read<T>(ref T location) where T : class
{
[ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)]
[CLSCompliant(false)]
[System.Runtime.Versioning.NonVersionable]
- [SecuritySafeCritical] // to match 32-bit version
public static void Write(ref ulong location, ulong value)
{
//
[ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)]
[CLSCompliant(false)]
- [SecuritySafeCritical] // contains unsafe code
public static void Write(ref ulong location, ulong value)
{
//
}
[ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)]
- [SecuritySafeCritical] //the intrinsic implementation of this method contains unverifiable code
[System.Runtime.Versioning.NonVersionable]
public static void Write<T>(ref T location, T value) where T : class
{
using System.Diagnostics.CodeAnalysis;
using Win32Native = Microsoft.Win32.Win32Native;
-[System.Runtime.InteropServices.ComVisible(true)]
+ [System.Runtime.InteropServices.ComVisible(true)]
public abstract class WaitHandle : MarshalByRefObject, IDisposable {
public const int WaitTimeout = 0x102;
private IntPtr waitHandle; // !!! DO NOT MOVE THIS FIELD. (See defn of WAITHANDLEREF in object.h - has hardcoded access to this field.)
#pragma warning restore 414
- [System.Security.SecurityCritical] // auto-generated
internal volatile SafeWaitHandle safeWaitHandle;
internal bool hasThreadAffinity;
- [System.Security.SecuritySafeCritical] // auto-generated
private static IntPtr GetInvalidHandle()
{
return Win32Native.INVALID_HANDLE_VALUE;
Init();
}
- [System.Security.SecuritySafeCritical] // auto-generated
private void Init()
{
safeWaitHandle = null;
[Obsolete("Use the SafeWaitHandle property instead.")]
public virtual IntPtr Handle
{
- [System.Security.SecuritySafeCritical] // auto-generated
get { return safeWaitHandle == null ? InvalidHandle : safeWaitHandle.DangerousGetHandle();}
-
- [System.Security.SecurityCritical] // auto-generated_required
-#if !FEATURE_CORECLR
- [SecurityPermissionAttribute(SecurityAction.InheritanceDemand, Flags=SecurityPermissionFlag.UnmanagedCode)]
-#endif
set
{
if (value == InvalidHandle)
}
}
-
public SafeWaitHandle SafeWaitHandle
{
- [System.Security.SecurityCritical] // auto-generated_required
-#if !FEATURE_CORECLR
- [SecurityPermissionAttribute(SecurityAction.InheritanceDemand, Flags=SecurityPermissionFlag.UnmanagedCode)]
-#endif
[ReliabilityContract(Consistency.WillNotCorruptState, Cer.MayFail)]
get
{
}
return safeWaitHandle;
}
-
- [System.Security.SecurityCritical] // auto-generated_required
-#if !FEATURE_CORECLR
- [SecurityPermissionAttribute(SecurityAction.InheritanceDemand, Flags=SecurityPermissionFlag.UnmanagedCode)]
-#endif
+
[ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)]
set
{
// FileStream, which will then call Sethandle, which requires a link time
// security check.). While security has fixed that problem, we still
// don't need to do a linktime check here.
- [System.Security.SecurityCritical] // auto-generated
internal void SetHandleInternal(SafeWaitHandle handle)
{
safeWaitHandle = handle;
return WaitOne(timeout, false);
}
- [System.Security.SecuritySafeCritical] // auto-generated
[SuppressMessage("Microsoft.Concurrency", "CA8001", Justification = "Reviewed for thread-safety.")]
private bool WaitOne(long timeout, bool exitContext)
{
return InternalWaitOne(safeWaitHandle, timeout, hasThreadAffinity, exitContext);
}
- [System.Security.SecurityCritical] // auto-generated
internal static bool InternalWaitOne(SafeHandle waitableSafeHandle, long millisecondsTimeout, bool hasThreadAffinity, bool exitContext)
{
if (waitableSafeHandle == null)
return (ret != WaitTimeout);
}
- [System.Security.SecurityCritical]
internal bool WaitOneWithoutFAS()
{
// version of waitone without fast application switch (FAS) support
return (ret != WaitTimeout);
}
- [System.Security.SecurityCritical] // auto-generated
[MethodImplAttribute(MethodImplOptions.InternalCall)]
private static extern int WaitOneNative(SafeHandle waitableSafeHandle, uint millisecondsTimeout, bool hasThreadAffinity, bool exitContext);
** (if in a synchronized context) is exited before the wait and reacquired
========================================================================*/
- [System.Security.SecurityCritical] // auto-generated
[MethodImplAttribute(MethodImplOptions.InternalCall)]
[ReliabilityContract(Consistency.WillNotCorruptState, Cer.MayFail)]
private static extern int WaitMultiple(WaitHandle[] waitHandles, int millisecondsTimeout, bool exitContext, bool WaitAll);
- [System.Security.SecuritySafeCritical] // auto-generated
public static bool WaitAll(WaitHandle[] waitHandles, int millisecondsTimeout, bool exitContext)
{
if (waitHandles == null)
// in CoreCLR, and ArgumentNullException in the desktop CLR. This is ugly, but so is breaking
// user code.
//
-#if FEATURE_CORECLR
throw new ArgumentException(Environment.GetResourceString("Argument_EmptyWaithandleArray"));
-#else
- throw new ArgumentNullException(nameof(waitHandles), Environment.GetResourceString("Argument_EmptyWaithandleArray"));
-#endif
}
if (waitHandles.Length > MAX_WAITHANDLES)
{
if (waitHandle == null)
throw new ArgumentNullException("waitHandles[" + i + "]", Environment.GetResourceString("ArgumentNull_ArrayElement"));
-#if FEATURE_REMOTING
- if (RemotingServices.IsTransparentProxy(waitHandle))
- throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_WaitOnTransparentProxy"));
-#endif
-
internalWaitHandles[i] = waitHandle;
}
#if _DEBUG
** (if in a synchronized context) is exited before the wait and reacquired
========================================================================*/
- [System.Security.SecuritySafeCritical] // auto-generated
[ReliabilityContract(Consistency.WillNotCorruptState, Cer.MayFail)]
public static int WaitAny(WaitHandle[] waitHandles, int millisecondsTimeout, bool exitContext)
{
if (waitHandle == null)
throw new ArgumentNullException("waitHandles[" + i + "]", Environment.GetResourceString("ArgumentNull_ArrayElement"));
-#if FEATURE_REMOTING
- if (RemotingServices.IsTransparentProxy(waitHandle))
- throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_WaitOnTransparentProxy"));
-#endif
-
internalWaitHandles[i] = waitHandle;
}
#if _DEBUG
==
==================================================*/
- [System.Security.SecurityCritical] // auto-generated
[MethodImplAttribute(MethodImplOptions.InternalCall)]
private static extern int SignalAndWaitOne(SafeWaitHandle waitHandleToSignal,SafeWaitHandle waitHandleToWaitOn, int millisecondsTimeout,
bool hasThreadAffinity, bool exitContext);
#endif
}
- [System.Security.SecuritySafeCritical] // auto-generated
[SuppressMessage("Microsoft.Concurrency", "CA8001", Justification = "Reviewed for thread-safety.")]
public static bool SignalAndWait(
WaitHandle toSignal,
int ret = SignalAndWaitOne(toSignal.safeWaitHandle,toWaitOn.safeWaitHandle,millisecondsTimeout,
toWaitOn.hasThreadAffinity,exitContext);
-#if !FEATURE_CORECLR
- if(WAIT_FAILED != ret && toSignal.hasThreadAffinity)
- {
- Thread.EndCriticalRegion();
- Thread.EndThreadAffinity();
- }
-#endif
-
if(WAIT_ABANDONED == ret)
{
ThrowAbandonedMutexException();
GC.SuppressFinalize(this);
}
- [System.Security.SecuritySafeCritical] // auto-generated
protected virtual void Dispose(bool explicitDisposing)
{
if (safeWaitHandle != null)
using Collections.Generic;
using System.Runtime.CompilerServices;
using System.Runtime.Serialization;
+ using System.Diagnostics;
using System.Diagnostics.Contracts;
[Pure]
internal static void ThrowArgumentOutOfRangeException() {
throw new ArgumentOutOfRangeException();
}
+
+ internal static void ThrowArgumentException_DestinationTooShort() {
+ throw new ArgumentException(Environment.GetResourceString("Argument_DestinationTooShort"));
+ }
+
+ internal static void ThrowNotSupportedException_CannotCallEqualsOnSpan() {
+ throw new NotSupportedException(Environment.GetResourceString("NotSupported_CannotCallEqualsOnSpan"));
+ }
+
+ internal static void ThrowNotSupportedException_CannotCallGetHashCodeOnSpan() {
+ throw new NotSupportedException(Environment.GetResourceString("NotSupported_CannotCallGetHashCodeOnSpan"));
+ }
#endif
internal static void ThrowArgumentOutOfRange_IndexException() {
throw GetWrongValueTypeArgumentException(value, targetType);
}
-
-#if FEATURE_CORECLR
private static ArgumentException GetAddingDuplicateWithKeyArgumentException(object key) {
return new ArgumentException(Environment.GetResourceString("Argument_AddingDuplicateWithKey", key));
}
internal static void ThrowAddingDuplicateWithKeyArgumentException(object key) {
throw GetAddingDuplicateWithKeyArgumentException(key);
}
-#endif
internal static void ThrowKeyNotFoundException() {
throw new System.Collections.Generic.KeyNotFoundException();
// Second function in chain so as to not propergate the non-inlining to outside caller
[MethodImpl(MethodImplOptions.NoInlining)]
private static string GetArgumentNameInner(ExceptionArgument argument) {
- Contract.Assert(Enum.IsDefined(typeof(ExceptionArgument), argument),
+ Debug.Assert(Enum.IsDefined(typeof(ExceptionArgument), argument),
"The enum value is not defined, please check the ExceptionArgument Enum.");
return argument.ToString();
// Second function in chain so as to not propergate the non-inlining to outside caller
[MethodImpl(MethodImplOptions.NoInlining)]
private static string GetResourceStringInner(ExceptionResource resource) {
- Contract.Assert(Enum.IsDefined(typeof(ExceptionResource), resource),
+ Debug.Assert(Enum.IsDefined(typeof(ExceptionResource), resource),
"The enum value is not defined, please check the ExceptionResource Enum.");
return Environment.GetResourceString(resource.ToString());
// details of this type should change, or new fields added, we need to remember to add
// an appropriate custom ILMarshaler to keep WInRT interop scenarios enabled.
//
-[System.Runtime.InteropServices.ComVisible(true)]
+ [System.Runtime.InteropServices.ComVisible(true)]
[Serializable] public struct TimeSpan : IComparable
, IComparable<TimeSpan>, IEquatable<TimeSpan>, IFormattable
{
// [HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\.NETFramework]
// "TimeSpan_LegacyFormatMode"=dword:00000001
//
-#if !FEATURE_CORECLR
- [System.Security.SecurityCritical]
- [MethodImplAttribute(MethodImplOptions.InternalCall)]
- private static extern bool LegacyFormatMode();
-#endif // !FEATURE_CORECLR
- //
- // In Silverlight v4, specifying the APP_EARLIER_THAN_SL4.0 quirks mode allows applications to
- // run in v2 - v3 legacy behavior.
- //
-#if !FEATURE_CORECLR
- [System.Security.SecuritySafeCritical]
-#endif
private static bool GetLegacyFormatMode() {
-#if !FEATURE_CORECLR
- if (LegacyFormatMode()) // FCALL to check COMPlus_TimeSpan_LegacyFormatMode
- return true;
- return CompatibilitySwitches.IsNetFx40TimeSpanLegacyFormatMode;
-#else
return false;
-#endif // !FEATURE_CORECLR
}
private static volatile bool _legacyConfigChecked;
using System.Globalization;
[Serializable]
-[System.Runtime.InteropServices.ComVisible(true)]
-#if FEATURE_CORECLR
+ [System.Runtime.InteropServices.ComVisible(true)]
[Obsolete("System.TimeZone has been deprecated. Please investigate the use of System.TimeZoneInfo instead.")]
-#endif
public abstract class TimeZone {
private static volatile TimeZone currentTimeZone = null;
NoThrowOnInvalidTime = 2
};
-
[Serializable]
[System.Security.Permissions.HostProtection(MayLeakOnAbort = true)]
-#if !FEATURE_CORECLR
- [TypeForwardedFrom("System.Core, Version=3.5.0.0, Culture=Neutral, PublicKeyToken=b77a5c561934e089")]
-#endif
sealed public class TimeZoneInfo : IEquatable<TimeZoneInfo>, ISerializable, IDeserializationCallback
{
// ---- SECTION: members supporting exposed properties -------------*
- private String m_id;
- private String m_displayName;
- private String m_standardDisplayName;
- private String m_daylightDisplayName;
- private TimeSpan m_baseUtcOffset;
- private Boolean m_supportsDaylightSavingTime;
- private AdjustmentRule[] m_adjustmentRules;
+ private readonly String m_id;
+ private readonly String m_displayName;
+ private readonly String m_standardDisplayName;
+ private readonly String m_daylightDisplayName;
+ private readonly TimeSpan m_baseUtcOffset;
+ private readonly Boolean m_supportsDaylightSavingTime;
+ private readonly AdjustmentRule[] m_adjustmentRules;
// ---- SECTION: members for internal support ---------*
private enum TimeZoneInfoResult {
private const long c_ticksPerDay = c_ticksPerHour * 24;
private const long c_ticksPerDayRange = c_ticksPerDay - c_ticksPerMillisecond;
+ private static readonly TimeZoneInfo s_utcTimeZone = CreateCustomTimeZone(c_utcId, TimeSpan.Zero, c_utcId, c_utcId);
+
//
// All cached data are encapsulated in a helper class to allow consistent view even when the data are refreshed using ClearCachedData()
//
class CachedData
{
private volatile TimeZoneInfo m_localTimeZone;
- private volatile TimeZoneInfo m_utcTimeZone;
private TimeZoneInfo CreateLocal()
{
}
}
- private TimeZoneInfo CreateUtc()
- {
- lock (this)
- {
- TimeZoneInfo timeZone = m_utcTimeZone;
- if (timeZone == null) {
- timeZone = CreateCustomTimeZone(c_utcId, TimeSpan.Zero, c_utcId, c_utcId);
- m_utcTimeZone = timeZone;
- }
- return timeZone;
- }
- }
-
- public TimeZoneInfo Utc {
- get {
- Contract.Ensures(Contract.Result<TimeZoneInfo>() != null);
-
- TimeZoneInfo timeZone = m_utcTimeZone;
- if (timeZone == null) {
- timeZone = CreateUtc();
- }
- return timeZone;
- }
- }
-
//
// GetCorrespondingKind-
//
// in this example. Only when the user passes in TimeZoneInfo.Local or
// TimeZoneInfo.Utc to the ConvertTime(...) methods will this check succeed.
//
- if ((object)timeZone == (object)m_utcTimeZone) {
+ if ((object)timeZone == (object)s_utcTimeZone) {
kind = DateTimeKind.Utc;
}
else if ((object)timeZone == (object)m_localTimeZone) {
public bool m_allSystemTimeZonesRead;
#if FEATURE_WIN32_REGISTRY
- [System.Security.SecuritySafeCritical]
private static TimeZoneInfo GetCurrentOneYearLocal() {
// load the data from the OS
TimeZoneInfo match;
private AdjustmentRule[] GetFilledRules()
{
- Contract.Assert(m_adjustmentRules != null, "m_adjustmentRules expected to be not null");
+ Debug.Assert(m_adjustmentRules != null, "m_adjustmentRules expected to be not null");
AdjustmentRule[] rules = new AdjustmentRule[m_adjustmentRules.Length];
for (int i = 0; i < m_adjustmentRules.Length; i++)
}
else if (dateTime.Kind == DateTimeKind.Utc) {
CachedData cachedData = s_cachedData;
- adjustedTime = TimeZoneInfo.ConvertTime(dateTime, cachedData.Utc, this, TimeZoneInfoOptions.None, cachedData);
+ adjustedTime = TimeZoneInfo.ConvertTime(dateTime, s_utcTimeZone, this, TimeZoneInfoOptions.None, cachedData);
}
else {
adjustedTime = dateTime;
//
// normal case of converting from Local to Utc and then getting the offset from the UTC DateTime
//
- DateTime adjustedTime = TimeZoneInfo.ConvertTime(dateTime, cachedData.Local, cachedData.Utc, flags);
+ DateTime adjustedTime = TimeZoneInfo.ConvertTime(dateTime, cachedData.Local, s_utcTimeZone, flags);
return GetUtcOffsetFromUtc(adjustedTime, this);
}
}
else if (dateTime.Kind == DateTimeKind.Utc) {
CachedData cachedData = s_cachedData;
- adjustedTime = TimeZoneInfo.ConvertTime(dateTime, cachedData.Utc, this, flags, cachedData);
+ adjustedTime = TimeZoneInfo.ConvertTime(dateTime, s_utcTimeZone, this, flags, cachedData);
}
else {
adjustedTime = dateTime;
// be reference equal to the new TimeZoneInfo.Utc
//
CachedData cachedData = s_cachedData;
- return ConvertTime(dateTime, cachedData.Utc, FindSystemTimeZoneById(destinationTimeZoneId), TimeZoneInfoOptions.None, cachedData);
+ return ConvertTime(dateTime, s_utcTimeZone, FindSystemTimeZoneById(destinationTimeZoneId), TimeZoneInfoOptions.None, cachedData);
}
else
{
}
CachedData cachedData = s_cachedData;
if (dateTime.Kind == DateTimeKind.Utc) {
- return ConvertTime(dateTime, cachedData.Utc, destinationTimeZone, TimeZoneInfoOptions.None, cachedData);
+ return ConvertTime(dateTime, s_utcTimeZone, destinationTimeZone, TimeZoneInfoOptions.None, cachedData);
}
else {
return ConvertTime(dateTime, cachedData.Local, destinationTimeZone, TimeZoneInfoOptions.None, cachedData);
//
static public DateTime ConvertTimeFromUtc(DateTime dateTime, TimeZoneInfo destinationTimeZone) {
CachedData cachedData = s_cachedData;
- return ConvertTime(dateTime, cachedData.Utc, destinationTimeZone, TimeZoneInfoOptions.None, cachedData);
+ return ConvertTime(dateTime, s_utcTimeZone, destinationTimeZone, TimeZoneInfoOptions.None, cachedData);
}
return dateTime;
}
CachedData cachedData = s_cachedData;
- return ConvertTime(dateTime, cachedData.Local, cachedData.Utc, TimeZoneInfoOptions.None, cachedData);
+ return ConvertTime(dateTime, cachedData.Local, s_utcTimeZone, TimeZoneInfoOptions.None, cachedData);
}
return dateTime;
}
CachedData cachedData = s_cachedData;
- return ConvertTime(dateTime, cachedData.Local, cachedData.Utc, flags, cachedData);
+ return ConvertTime(dateTime, cachedData.Local, s_utcTimeZone, flags, cachedData);
}
static public DateTime ConvertTimeToUtc(DateTime dateTime, TimeZoneInfo sourceTimeZone) {
CachedData cachedData = s_cachedData;
- return ConvertTime(dateTime, sourceTimeZone, cachedData.Utc, TimeZoneInfoOptions.None, cachedData);
+ return ConvertTime(dateTime, sourceTimeZone, s_utcTimeZone, TimeZoneInfoOptions.None, cachedData);
}
}
public override bool Equals(object obj) {
- TimeZoneInfo tzi = obj as TimeZoneInfo;
- if (null == tzi) {
- return false;
- }
- return Equals(tzi);
+ return Equals(obj as TimeZoneInfo);
}
//
// GetHashCode -
//
public override int GetHashCode() {
- return m_id.ToUpper(CultureInfo.InvariantCulture).GetHashCode();
+ return StringComparer.OrdinalIgnoreCase.GetHashCode(m_id);
}
//
// <SecurityKernel Critical="True" Ring="0">
// <Asserts Name="Imperative: System.Security.PermissionSet" />
// </SecurityKernel>
- [System.Security.SecuritySafeCritical] // auto-generated
static public ReadOnlyCollection<TimeZoneInfo> GetSystemTimeZones() {
CachedData cachedData = s_cachedData;
}
// sort and copy the TimeZoneInfo's into a ReadOnlyCollection for the user
- list.Sort(new TimeZoneInfoComparer());
+ list.Sort((x, y) =>
+ {
+ // sort by BaseUtcOffset first and by DisplayName second - this is similar to the Windows Date/Time control panel
+ int comparison = x.BaseUtcOffset.CompareTo(y.BaseUtcOffset);
+ return comparison == 0 ? string.CompareOrdinal(x.DisplayName, y.DisplayName) : comparison;
+ });
cachedData.m_readOnlySystemTimeZones = new ReadOnlyCollection<TimeZoneInfo>(list);
}
return cachedData.m_readOnlySystemTimeZones;
}
- [SecuritySafeCritical]
private static void PopulateAllSystemTimeZones(CachedData cachedData)
{
#if FEATURE_WIN32_REGISTRY
PermissionSet permSet = new PermissionSet(PermissionState.None);
permSet.AddPermission(new RegistryPermission(RegistryPermissionAccess.Read, c_timeZonesRegistryHivePermissionList));
permSet.Assert();
-
- using (RegistryKey reg = Registry.LocalMachine.OpenSubKey(
- c_timeZonesRegistryHive,
-#if FEATURE_MACL
- RegistryKeyPermissionCheck.Default,
- System.Security.AccessControl.RegistryRights.ReadKey
-#else
- false
-#endif
- )) {
- if (reg != null) {
- foreach (string keyName in reg.GetSubKeyNames()) {
+ using (RegistryKey reg = Registry.LocalMachine.OpenSubKey(c_timeZonesRegistryHive, false))
+ {
+ if (reg != null)
+ {
+ foreach (string keyName in reg.GetSubKeyNames())
+ {
TimeZoneInfo value;
Exception ex;
TryGetTimeZone(keyName, false, out value, out ex, cachedData); // populate the cache
static public TimeZoneInfo Utc {
get {
Contract.Ensures(Contract.Result<TimeZoneInfo>() != null);
- return s_cachedData.Utc;
+ return s_utcTimeZone;
}
}
// private ctor
//
#if FEATURE_WIN32_REGISTRY
- [System.Security.SecurityCritical] // auto-generated
private TimeZoneInfo(Win32Native.TimeZoneInformation zone, Boolean dstDisabled) {
if (String.IsNullOrEmpty(zone.StandardName)) {
Boolean adjustmentRulesSupportDst;
ValidateTimeZoneInfo(id, baseUtcOffset, adjustmentRules, out adjustmentRulesSupportDst);
- if (!disableDaylightSavingTime && adjustmentRules != null && adjustmentRules.Length > 0) {
- m_adjustmentRules = (AdjustmentRule[])adjustmentRules.Clone();
- }
-
m_id = id;
m_baseUtcOffset = baseUtcOffset;
m_displayName = displayName;
m_standardDisplayName = standardDisplayName;
m_daylightDisplayName = (disableDaylightSavingTime ? null : daylightDisplayName);
m_supportsDaylightSavingTime = adjustmentRulesSupportDst && !disableDaylightSavingTime;
+ m_adjustmentRules = adjustmentRules;
}
// -------- SECTION: factory methods -----------------*
String daylightDisplayName,
AdjustmentRule [] adjustmentRules) {
- return new TimeZoneInfo(
+ return CreateCustomTimeZone(
id,
baseUtcOffset,
displayName,
AdjustmentRule [] adjustmentRules,
Boolean disableDaylightSavingTime) {
- return new TimeZoneInfo(
+ if (!disableDaylightSavingTime && adjustmentRules?.Length > 0) {
+ adjustmentRules = (AdjustmentRule[])adjustmentRules.Clone();
+ }
+
+ return new TimeZoneInfo(
id,
baseUtcOffset,
displayName,
}
- [System.Security.SecurityCritical] // auto-generated_required
void ISerializable.GetObjectData(SerializationInfo info, StreamingContext context) {
if (info == null) {
throw new ArgumentNullException(nameof(info));
//
// This check is only meant to be used for "Local".
//
- [System.Security.SecurityCritical] // auto-generated
static private Boolean CheckDaylightSavingTimeNotSupported(Win32Native.TimeZoneInformation timeZone) {
return ( timeZone.DaylightDate.Year == timeZone.StandardDate.Year
&& timeZone.DaylightDate.Month == timeZone.StandardDate.Month
//
// Converts a Win32Native.RegistryTimeZoneInformation (REG_TZI_FORMAT struct) to an AdjustmentRule
//
- [System.Security.SecurityCritical] // auto-generated
static private AdjustmentRule CreateAdjustmentRuleFromTimeZoneInformation(Win32Native.RegistryTimeZoneInformation timeZoneInformation, DateTime startDate, DateTime endDate, int defaultBaseUtcOffset) {
AdjustmentRule rule;
bool supportsDst = (timeZoneInformation.StandardDate.Month != 0);
// Helper function that searches the registry for a time zone entry
// that matches the TimeZoneInformation struct
//
- [System.Security.SecuritySafeCritical] // auto-generated
static private String FindIdFromTimeZoneInformation(Win32Native.TimeZoneInformation timeZone, out Boolean dstDisabled) {
dstDisabled = false;
permSet.AddPermission(new RegistryPermission(RegistryPermissionAccess.Read, c_timeZonesRegistryHivePermissionList));
permSet.Assert();
- using (RegistryKey key = Registry.LocalMachine.OpenSubKey(
- c_timeZonesRegistryHive,
-#if FEATURE_MACL
- RegistryKeyPermissionCheck.Default,
- System.Security.AccessControl.RegistryRights.ReadKey
-#else
- false
-#endif
- )) {
-
- if (key == null) {
+ using (RegistryKey key = Registry.LocalMachine.OpenSubKey(c_timeZonesRegistryHive, false))
+ {
+ if (key == null)
+ {
return null;
}
- foreach (string keyName in key.GetSubKeyNames()) {
- if (TryCompareTimeZoneInformationToRegistry(timeZone, keyName, out dstDisabled)) {
+ foreach (string keyName in key.GetSubKeyNames())
+ {
+ if (TryCompareTimeZoneInformationToRegistry(timeZone, keyName, out dstDisabled))
+ {
return keyName;
}
}
// assumes cachedData lock is taken
//
- [System.Security.SecuritySafeCritical] // auto-generated
static private TimeZoneInfo GetLocalTimeZone(CachedData cachedData) {
/// 3. Look for the data in GetTimeZoneDirectory()/localtime.
/// 4. Use UTC if all else fails.
/// </summary>
- [SecurityCritical]
private static bool TryGetLocalTzFile(out byte[] rawData, out string id)
{
rawData = null;
/// Finds the time zone id by using 'readlink' on the path to see if tzFilePath is
/// a symlink to a file
/// </summary>
- [SecuritySafeCritical]
private static string FindTimeZoneIdUsingReadLink(string tzFilePath)
{
string id = null;
//
// The TryGetLocalTzFile() call returns a Byte[] containing the compiled tzfile.
//
- [System.Security.SecurityCritical]
static private TimeZoneInfo GetLocalTimeZoneFromTzFile()
{
byte[] rawData;
// try/catch logic for handling the TimeZoneInfo private constructor that takes
// a Win32Native.TimeZoneInformation structure.
//
- [System.Security.SecurityCritical] // auto-generated
static private TimeZoneInfo GetLocalTimeZoneFromWin32Data(Win32Native.TimeZoneInformation timeZoneInformation, Boolean dstDisabled) {
// first try to create the TimeZoneInfo with the original 'dstDisabled' flag
try {
#if FEATURE_WIN32_REGISTRY
throw new InvalidTimeZoneException(Environment.GetResourceString("InvalidTimeZone_InvalidRegistryData", id), e);
#elif PLATFORM_UNIX
- Contract.Assert(e is InvalidTimeZoneException,
+ Debug.Assert(e is InvalidTimeZoneException,
"TryGetTimeZone must create an InvalidTimeZoneException when it returns TimeZoneInfoResult.InvalidTimeZoneException");
throw e;
#endif
// * when the argument 'readStart' is true the corresponding daylightTransitionTimeStart field is read
// * when the argument 'readStart' is false the corresponding dayightTransitionTimeEnd field is read
//
- [System.Security.SecurityCritical] // auto-generated
static private bool TransitionTimeFromTimeZoneInformation(Win32Native.RegistryTimeZoneInformation timeZoneInformation, out TransitionTime transitionTime, bool readStartDate) {
//
// SYSTEMTIME -
//
// This method expects that its caller has already Asserted RegistryPermission.Read
//
- [System.Security.SecurityCritical] // auto-generated
static private bool TryCreateAdjustmentRules(string id, Win32Native.RegistryTimeZoneInformation defaultTimeZoneInformation, out AdjustmentRule[] rules, out Exception e, int defaultBaseUtcOffset) {
e = null;
try {
using (RegistryKey dynamicKey = Registry.LocalMachine.OpenSubKey(
- String.Format(CultureInfo.InvariantCulture, "{0}\\{1}\\Dynamic DST",
- c_timeZonesRegistryHive, id),
-#if FEATURE_MACL
- RegistryKeyPermissionCheck.Default,
- System.Security.AccessControl.RegistryRights.ReadKey
-#else
- false
-#endif
- )) {
+ c_timeZonesRegistryHive + "\\" + id + "\\Dynamic DST",
+ false)) {
if (dynamicKey == null) {
AdjustmentRule rule = CreateAdjustmentRuleFromTimeZoneInformation(
defaultTimeZoneInformation, DateTime.MinValue.Date, DateTime.MaxValue.Date, defaultBaseUtcOffset);
- if (rule == null) {
+ if (rule == null)
+ {
rules = null;
}
- else {
+ else
+ {
rules = new AdjustmentRule[1];
rules[0] = rule;
}
-
+
return true;
}
Int32 first = (Int32)dynamicKey.GetValue(c_firstEntryValue, -1, RegistryValueOptions.None);
Int32 last = (Int32)dynamicKey.GetValue(c_lastEntryValue, -1, RegistryValueOptions.None);
- if (first == -1 || last == -1 || first > last) {
+ if (first == -1 || last == -1 || first > last)
+ {
rules = null;
return false;
}
// read the first year entry
Win32Native.RegistryTimeZoneInformation dtzi;
Byte[] regValue = dynamicKey.GetValue(first.ToString(CultureInfo.InvariantCulture), null, RegistryValueOptions.None) as Byte[];
- if (regValue == null || regValue.Length != c_regByteLength) {
+ if (regValue == null || regValue.Length != c_regByteLength)
+ {
rules = null;
return false;
}
dtzi = new Win32Native.RegistryTimeZoneInformation(regValue);
- if (first == last) {
+ if (first == last)
+ {
// there is just 1 dynamic rule for this time zone.
- AdjustmentRule rule = CreateAdjustmentRuleFromTimeZoneInformation(dtzi, DateTime.MinValue.Date, DateTime.MaxValue.Date, defaultBaseUtcOffset);
+ AdjustmentRule rule = CreateAdjustmentRuleFromTimeZoneInformation(dtzi, DateTime.MinValue.Date, DateTime.MaxValue.Date, defaultBaseUtcOffset);
- if (rule == null) {
+ if (rule == null)
+ {
rules = null;
}
- else {
+ else
+ {
rules = new AdjustmentRule[1];
rules[0] = rule;
}
List<AdjustmentRule> rulesList = new List<AdjustmentRule>(1);
- // there are more than 1 dynamic rules for this time zone.
+ // there are more than 1 dynamic rules for this time zone.
AdjustmentRule firstRule = CreateAdjustmentRuleFromTimeZoneInformation(
dtzi,
DateTime.MinValue.Date, // MinValue
new DateTime(first, 12, 31), // December 31, <FirstYear>
- defaultBaseUtcOffset);
- if (firstRule != null) {
+ defaultBaseUtcOffset);
+ if (firstRule != null)
+ {
rulesList.Add(firstRule);
}
// read the middle year entries
- for (Int32 i = first + 1; i < last; i++) {
+ for (Int32 i = first + 1; i < last; i++)
+ {
regValue = dynamicKey.GetValue(i.ToString(CultureInfo.InvariantCulture), null, RegistryValueOptions.None) as Byte[];
- if (regValue == null || regValue.Length != c_regByteLength) {
+ if (regValue == null || regValue.Length != c_regByteLength)
+ {
rules = null;
return false;
}
new DateTime(i, 1, 1), // January 01, <Year>
new DateTime(i, 12, 31), // December 31, <Year>
defaultBaseUtcOffset);
- if (middleRule != null) {
+ if (middleRule != null)
+ {
rulesList.Add(middleRule);
}
}
// read the last year entry
regValue = dynamicKey.GetValue(last.ToString(CultureInfo.InvariantCulture), null, RegistryValueOptions.None) as Byte[];
dtzi = new Win32Native.RegistryTimeZoneInformation(regValue);
- if (regValue == null || regValue.Length != c_regByteLength) {
+ if (regValue == null || regValue.Length != c_regByteLength)
+ {
rules = null;
return false;
}
new DateTime(last, 1, 1), // January 01, <LastYear>
DateTime.MaxValue.Date, // MaxValue
defaultBaseUtcOffset);
- if (lastRule != null) {
+ if (lastRule != null)
+ {
rulesList.Add(lastRule);
}
// convert the ArrayList to an AdjustmentRule array
rules = rulesList.ToArray();
- if (rules != null && rules.Length == 0) {
+ if (rules != null && rules.Length == 0)
+ {
rules = null;
}
} // end of: using (RegistryKey dynamicKey...
// Helper function that compares the StandardBias and StandardDate portion a
// TimeZoneInformation struct to a time zone registry entry
//
- [System.Security.SecurityCritical] // auto-generated
static private Boolean TryCompareStandardDate(Win32Native.TimeZoneInformation timeZone, Win32Native.RegistryTimeZoneInformation registryTimeZoneInfo) {
return timeZone.Bias == registryTimeZoneInfo.Bias
&& timeZone.StandardBias == registryTimeZoneInfo.StandardBias
//
// Helper function that compares a TimeZoneInformation struct to a time zone registry entry
//
- [System.Security.SecuritySafeCritical] // auto-generated
- static private Boolean TryCompareTimeZoneInformationToRegistry(Win32Native.TimeZoneInformation timeZone, string id, out Boolean dstDisabled) {
-
+ static private Boolean TryCompareTimeZoneInformationToRegistry(Win32Native.TimeZoneInformation timeZone, string id, out Boolean dstDisabled)
+ {
dstDisabled = false;
try {
PermissionSet permSet = new PermissionSet(PermissionState.None);
permSet.Assert();
using (RegistryKey key = Registry.LocalMachine.OpenSubKey(
- String.Format(CultureInfo.InvariantCulture, "{0}\\{1}",
- c_timeZonesRegistryHive, id),
-#if FEATURE_MACL
- RegistryKeyPermissionCheck.Default,
- System.Security.AccessControl.RegistryRights.ReadKey
-#else
- false
-#endif
- )) {
+ c_timeZonesRegistryHive + "\\" + id,
+ false))
+ {
if (key == null) {
return false;
//
Boolean result = TryCompareStandardDate(timeZone, registryTimeZoneInfo);
- if (!result) {
+ if (!result)
+ {
return false;
}
// since Daylight Saving Time is not "disabled", do a straight comparision between
// the Win32 API data and the registry data ...
//
- ||( timeZone.DaylightBias == registryTimeZoneInfo.DaylightBias
- && timeZone.DaylightDate.Year == registryTimeZoneInfo.DaylightDate.Year
- && timeZone.DaylightDate.Month == registryTimeZoneInfo.DaylightDate.Month
- && timeZone.DaylightDate.DayOfWeek == registryTimeZoneInfo.DaylightDate.DayOfWeek
- && timeZone.DaylightDate.Day == registryTimeZoneInfo.DaylightDate.Day
- && timeZone.DaylightDate.Hour == registryTimeZoneInfo.DaylightDate.Hour
- && timeZone.DaylightDate.Minute == registryTimeZoneInfo.DaylightDate.Minute
- && timeZone.DaylightDate.Second == registryTimeZoneInfo.DaylightDate.Second
+ || (timeZone.DaylightBias == registryTimeZoneInfo.DaylightBias
+ && timeZone.DaylightDate.Year == registryTimeZoneInfo.DaylightDate.Year
+ && timeZone.DaylightDate.Month == registryTimeZoneInfo.DaylightDate.Month
+ && timeZone.DaylightDate.DayOfWeek == registryTimeZoneInfo.DaylightDate.DayOfWeek
+ && timeZone.DaylightDate.Day == registryTimeZoneInfo.DaylightDate.Day
+ && timeZone.DaylightDate.Hour == registryTimeZoneInfo.DaylightDate.Hour
+ && timeZone.DaylightDate.Minute == registryTimeZoneInfo.DaylightDate.Minute
+ && timeZone.DaylightDate.Second == registryTimeZoneInfo.DaylightDate.Second
&& timeZone.DaylightDate.Milliseconds == registryTimeZoneInfo.DaylightDate.Milliseconds);
// Finally compare the "StandardName" string value...
// we do not compare "DaylightName" as this TimeZoneInformation field may contain
// either "StandardName" or "DaylightName" depending on the time of year and current machine settings
//
- if (result) {
+ if (result)
+ {
String registryStandardName = key.GetValue(c_standardValue, String.Empty, RegistryValueOptions.None) as String;
result = String.Compare(registryStandardName, timeZone.StandardName, StringComparison.Ordinal) == 0;
}
- return result;
+ return result;
}
}
finally {
// <CallsSuppressUnmanagedCode Name="UnsafeNativeMethods.GetFileMUIPath(System.Int32,System.String,System.Text.StringBuilder,System.Int32&,System.Text.StringBuilder,System.Int32&,System.Int64&):System.Boolean" />
// <ReferencesCritical Name="Method: TryGetLocalizedNameByNativeResource(String, Int32):String" Ring="1" />
// </SecurityKernel>
- [System.Security.SecuritySafeCritical] // auto-generated
-#if !FEATURE_CORECLR
- [FileIOPermissionAttribute(SecurityAction.Assert, AllLocalFiles = FileIOPermissionAccess.PathDiscovery)]
-#endif
static private string TryGetLocalizedNameByMuiNativeResource(string resource) {
if (String.IsNullOrEmpty(resource)) {
return String.Empty;
// "resource.dll" is a language-specific resource DLL.
// If the localized resource DLL exists, LoadString(resource) is returned.
//
- [SecurityCritical]
static private string TryGetLocalizedNameByNativeResource(string filePath, int resource) {
using (SafeLibraryHandle handle =
UnsafeNativeMethods.LoadLibraryEx(filePath, IntPtr.Zero, Win32Native.LOAD_LIBRARY_AS_DATAFILE)) {
//
// This method expects that its caller has already Asserted RegistryPermission.Read
//
-#if FEATURE_CORECLR
- [System.Security.SecurityCritical] // auto-generated
-#endif
static private Boolean TryGetLocalizedNamesByRegistryKey(RegistryKey key, out String displayName, out String standardName, out String daylightName) {
displayName = String.Empty;
standardName = String.Empty;
// * TZI, REG_BINARY REG_TZI_FORMAT
// See Win32Native.RegistryTimeZoneInformation
//
- [System.Security.SecuritySafeCritical] // auto-generated
static private TimeZoneInfoResult TryGetTimeZoneByRegistryKey(string id, out TimeZoneInfo value, out Exception e) {
e = null;
permSet.Assert();
using (RegistryKey key = Registry.LocalMachine.OpenSubKey(
- String.Format(CultureInfo.InvariantCulture, "{0}\\{1}",
- c_timeZonesRegistryHive, id),
-#if FEATURE_MACL
- RegistryKeyPermissionCheck.Default,
- System.Security.AccessControl.RegistryRights.ReadKey
-#else
- false
-#endif
- )) {
+ c_timeZonesRegistryHive + "\\" + id,
+ false)) {
if (key == null) {
value = null;
// Converts an array of bytes into an int - always using standard byte order (Big Endian)
// per TZif file standard
- [System.Security.SecuritySafeCritical] // auto-generated
static private unsafe int TZif_ToInt32 (byte[]value, int startIndex) {
fixed( byte * pbyte = &value[startIndex]) {
return (*pbyte << 24) | (*(pbyte + 1) << 16) | (*(pbyte + 2) << 8) | (*(pbyte + 3));
// Converts an array of bytes into a long - always using standard byte order (Big Endian)
// per TZif file standard
- [System.Security.SecuritySafeCritical] // auto-generated
static private unsafe long TZif_ToInt64(byte[] value, int startIndex)
{
fixed (byte* pbyte = &value[startIndex])
============================================================*/
[Serializable]
[System.Security.Permissions.HostProtection(MayLeakOnAbort = true)]
-#if !FEATURE_CORECLR
- [TypeForwardedFrom("System.Core, Version=3.5.0.0, Culture=Neutral, PublicKeyToken=b77a5c561934e089")]
-#endif
sealed public class AdjustmentRule : IEquatable<AdjustmentRule>, ISerializable, IDeserializationCallback
{
// ---- SECTION: members supporting exposed properties -------------*
- private DateTime m_dateStart;
- private DateTime m_dateEnd;
- private TimeSpan m_daylightDelta;
- private TransitionTime m_daylightTransitionStart;
- private TransitionTime m_daylightTransitionEnd;
- private TimeSpan m_baseUtcOffsetDelta; // delta from the default Utc offset (utcOffset = defaultUtcOffset + m_baseUtcOffsetDelta)
- private bool m_noDaylightTransitions;
+ private readonly DateTime m_dateStart;
+ private readonly DateTime m_dateEnd;
+ private readonly TimeSpan m_daylightDelta;
+ private readonly TransitionTime m_daylightTransitionStart;
+ private readonly TransitionTime m_daylightTransitionEnd;
+ private readonly TimeSpan m_baseUtcOffsetDelta; // delta from the default Utc offset (utcOffset = defaultUtcOffset + m_baseUtcOffsetDelta)
+ private readonly bool m_noDaylightTransitions;
// ---- SECTION: public properties --------------*
public DateTime DateStart {
// IEquatable<AdjustmentRule>
public bool Equals(AdjustmentRule other) {
- bool equals = (other != null
- && this.m_dateStart == other.m_dateStart
- && this.m_dateEnd == other.m_dateEnd
- && this.m_daylightDelta == other.m_daylightDelta
- && this.m_baseUtcOffsetDelta == other.m_baseUtcOffsetDelta);
-
- equals = equals && this.m_daylightTransitionEnd.Equals(other.m_daylightTransitionEnd)
- && this.m_daylightTransitionStart.Equals(other.m_daylightTransitionStart);
-
- return equals;
+ return other != null
+ && m_dateStart == other.m_dateStart
+ && m_dateEnd == other.m_dateEnd
+ && m_daylightDelta == other.m_daylightDelta
+ && m_baseUtcOffsetDelta == other.m_baseUtcOffsetDelta
+ && m_daylightTransitionEnd.Equals(other.m_daylightTransitionEnd)
+ && m_daylightTransitionStart.Equals(other.m_daylightTransitionStart);
}
// -------- SECTION: constructors -----------------*
- private AdjustmentRule() { }
-
-
- // -------- SECTION: factory methods -----------------*
-
- static internal AdjustmentRule CreateAdjustmentRule(
- DateTime dateStart,
- DateTime dateEnd,
- TimeSpan daylightDelta,
- TransitionTime daylightTransitionStart,
- TransitionTime daylightTransitionEnd,
- bool noDaylightTransitions) {
+ private AdjustmentRule(
+ DateTime dateStart,
+ DateTime dateEnd,
+ TimeSpan daylightDelta,
+ TransitionTime daylightTransitionStart,
+ TransitionTime daylightTransitionEnd,
+ TimeSpan baseUtcOffsetDelta,
+ bool noDaylightTransitions)
+ {
ValidateAdjustmentRule(dateStart, dateEnd, daylightDelta,
daylightTransitionStart, daylightTransitionEnd, noDaylightTransitions);
- AdjustmentRule rule = new AdjustmentRule();
+ m_dateStart = dateStart;
+ m_dateEnd = dateEnd;
+ m_daylightDelta = daylightDelta;
+ m_daylightTransitionStart = daylightTransitionStart;
+ m_daylightTransitionEnd = daylightTransitionEnd;
+ m_baseUtcOffsetDelta = baseUtcOffsetDelta;
+ m_noDaylightTransitions = noDaylightTransitions;
+ }
- rule.m_dateStart = dateStart;
- rule.m_dateEnd = dateEnd;
- rule.m_daylightDelta = daylightDelta;
- rule.m_daylightTransitionStart = daylightTransitionStart;
- rule.m_daylightTransitionEnd = daylightTransitionEnd;
- rule.m_baseUtcOffsetDelta = TimeSpan.Zero;
- rule.m_noDaylightTransitions = noDaylightTransitions;
- return rule;
- }
+ // -------- SECTION: factory methods -----------------*
static public AdjustmentRule CreateAdjustmentRule(
DateTime dateStart,
TransitionTime daylightTransitionStart,
TransitionTime daylightTransitionEnd)
{
- return CreateAdjustmentRule(dateStart, dateEnd, daylightDelta,
- daylightTransitionStart, daylightTransitionEnd, noDaylightTransitions: false);
+ return new AdjustmentRule(
+ dateStart,
+ dateEnd,
+ daylightDelta,
+ daylightTransitionStart,
+ daylightTransitionEnd,
+ baseUtcOffsetDelta: TimeSpan.Zero,
+ noDaylightTransitions: false);
}
static internal AdjustmentRule CreateAdjustmentRule(
TransitionTime daylightTransitionStart,
TransitionTime daylightTransitionEnd,
TimeSpan baseUtcOffsetDelta,
- bool noDaylightTransitions) {
- AdjustmentRule rule = CreateAdjustmentRule(dateStart, dateEnd, daylightDelta,
- daylightTransitionStart, daylightTransitionEnd, noDaylightTransitions);
-
- rule.m_baseUtcOffsetDelta = baseUtcOffsetDelta;
- return rule;
+ bool noDaylightTransitions)
+ {
+ return new AdjustmentRule(
+ dateStart,
+ dateEnd,
+ daylightDelta,
+ daylightTransitionStart,
+ daylightTransitionEnd,
+ baseUtcOffsetDelta,
+ noDaylightTransitions);
}
// ----- SECTION: internal utility methods ----------------*
}
}
- [System.Security.SecurityCritical] // auto-generated_required
void ISerializable.GetObjectData(SerializationInfo info, StreamingContext context) {
if (info == null) {
throw new ArgumentNullException(nameof(info));
============================================================*/
[Serializable]
[System.Security.Permissions.HostProtection(MayLeakOnAbort = true)]
-#if !FEATURE_CORECLR
- [TypeForwardedFrom("System.Core, Version=3.5.0.0, Culture=Neutral, PublicKeyToken=b77a5c561934e089")]
-#endif
public struct TransitionTime : IEquatable<TransitionTime>, ISerializable, IDeserializationCallback
{
// ---- SECTION: members supporting exposed properties -------------*
- private DateTime m_timeOfDay;
- private byte m_month;
- private byte m_week;
- private byte m_day;
- private DayOfWeek m_dayOfWeek;
- private Boolean m_isFixedDateRule;
+ private readonly DateTime m_timeOfDay;
+ private readonly byte m_month;
+ private readonly byte m_week;
+ private readonly byte m_day;
+ private readonly DayOfWeek m_dayOfWeek;
+ private readonly Boolean m_isFixedDateRule;
// ---- SECTION: public properties --------------*
// -------- SECTION: constructors -----------------*
-/*
- private TransitionTime() {
- m_timeOfDay = new DateTime();
- m_month = 0;
- m_week = 0;
- m_day = 0;
- m_dayOfWeek = DayOfWeek.Sunday;
- m_isFixedDateRule = false;
+
+ private TransitionTime(
+ DateTime timeOfDay,
+ Int32 month,
+ Int32 week,
+ Int32 day,
+ DayOfWeek dayOfWeek,
+ Boolean isFixedDateRule)
+ {
+ ValidateTransitionTime(timeOfDay, month, week, day, dayOfWeek);
+
+ m_timeOfDay = timeOfDay;
+ m_month = (byte)month;
+ m_week = (byte)week;
+ m_day = (byte)day;
+ m_dayOfWeek = dayOfWeek;
+ m_isFixedDateRule = isFixedDateRule;
}
-*/
// -------- SECTION: factory methods -----------------*
Int32 month,
Int32 day) {
- return CreateTransitionTime(timeOfDay, month, 1, day, DayOfWeek.Sunday, true);
+ return new TransitionTime(timeOfDay, month, 1, day, DayOfWeek.Sunday, isFixedDateRule: true);
}
Int32 week,
DayOfWeek dayOfWeek) {
- return CreateTransitionTime(timeOfDay, month, week, 1, dayOfWeek, false);
- }
-
-
- static private TransitionTime CreateTransitionTime(
- DateTime timeOfDay,
- Int32 month,
- Int32 week,
- Int32 day,
- DayOfWeek dayOfWeek,
- Boolean isFixedDateRule) {
-
- ValidateTransitionTime(timeOfDay, month, week, day, dayOfWeek);
-
- TransitionTime t = new TransitionTime();
- t.m_isFixedDateRule = isFixedDateRule;
- t.m_timeOfDay = timeOfDay;
- t.m_dayOfWeek = dayOfWeek;
- t.m_day = (byte)day;
- t.m_week = (byte)week;
- t.m_month = (byte)month;
-
- return t;
+ return new TransitionTime(timeOfDay, month, week, 1, dayOfWeek, isFixedDateRule: false);
}
}
- [System.Security.SecurityCritical] // auto-generated_required
void ISerializable.GetObjectData(SerializationInfo info, StreamingContext context) {
if (info == null) {
throw new ArgumentNullException(nameof(info));
AdjustmentRule[] rules = s.GetNextAdjustmentRuleArrayValue(false);
try {
- return TimeZoneInfo.CreateCustomTimeZone(id, baseUtcOffset, displayName, standardName, daylightName, rules);
+ return new TimeZoneInfo(id, baseUtcOffset, displayName, standardName, daylightName, rules, disableDaylightSavingTime: false);
}
catch (ArgumentException ex) {
throw new SerializationException(Environment.GetResourceString("Serialization_InvalidData"), ex);
}
}
- private class TimeZoneInfoComparer : System.Collections.Generic.IComparer<TimeZoneInfo> {
- int System.Collections.Generic.IComparer<TimeZoneInfo>.Compare(TimeZoneInfo x, TimeZoneInfo y) {
- // sort by BaseUtcOffset first and by DisplayName second - this is similar to the Windows Date/Time control panel
- int comparison = x.BaseUtcOffset.CompareTo(y.BaseUtcOffset);
- return comparison == 0 ? String.Compare(x.DisplayName, y.DisplayName, StringComparison.Ordinal) : comparison;
- }
- }
-
#if PLATFORM_UNIX
private struct TZifType
{
using System.Runtime.CompilerServices;
[Serializable]
-#if !FEATURE_CORECLR
- [TypeForwardedFrom("System.Core, Version=3.5.0.0, Culture=Neutral, PublicKeyToken=b77a5c561934e089")]
-#endif
[System.Security.Permissions.HostProtection(MayLeakOnAbort = true)]
public class TimeZoneNotFoundException : Exception {
public TimeZoneNotFoundException(String message)
using System.Text;
using System.Collections;
using System.Collections.Generic;
+using System.Diagnostics;
using System.Diagnostics.Contracts;
//
case 7:
return Tuple.CombineHashCodes(comparer.GetHashCode(m_Item1), comparer.GetHashCode(m_Item2), comparer.GetHashCode(m_Item3), comparer.GetHashCode(m_Item4), comparer.GetHashCode(m_Item5), comparer.GetHashCode(m_Item6), comparer.GetHashCode(m_Item7), t.GetHashCode(comparer));
}
- Contract.Assert(false, "Missed all cases for computing Tuple hash code");
+ Debug.Assert(false, "Missed all cases for computing Tuple hash code");
return -1;
}
//
// ======================================================================================
-namespace System {
-
+namespace System
+{
using System;
using System.Reflection;
using System.Threading;
// param progID: the progID of the class to retrieve
// returns: the class object associated to the progID
////
- [System.Security.SecurityCritical] // auto-generated_required
public static Type GetTypeFromProgID(String progID)
{
return RuntimeType.GetTypeFromProgIDImpl(progID, null, false);
// param progID: the progID of the class to retrieve
// returns: the class object associated to the progID
////
- [System.Security.SecurityCritical] // auto-generated_required
public static Type GetTypeFromProgID(String progID, bool throwOnError)
{
return RuntimeType.GetTypeFromProgIDImpl(progID, null, throwOnError);
}
- [System.Security.SecurityCritical] // auto-generated_required
public static Type GetTypeFromProgID(String progID, String server)
{
return RuntimeType.GetTypeFromProgIDImpl(progID, server, false);
}
- [System.Security.SecurityCritical] // auto-generated_required
public static Type GetTypeFromProgID(String progID, String server, bool throwOnError)
{
return RuntimeType.GetTypeFromProgIDImpl(progID, server, throwOnError);
// param CLSID: the CLSID of the class to retrieve
// returns: the class object associated to the CLSID
////
- [System.Security.SecuritySafeCritical] // auto-generated
public static Type GetTypeFromCLSID(Guid clsid)
{
return RuntimeType.GetTypeFromCLSIDImpl(clsid, null, false);
}
- [System.Security.SecuritySafeCritical] // auto-generated
public static Type GetTypeFromCLSID(Guid clsid, bool throwOnError)
{
return RuntimeType.GetTypeFromCLSIDImpl(clsid, null, throwOnError);
}
- [System.Security.SecuritySafeCritical] // auto-generated
public static Type GetTypeFromCLSID(Guid clsid, String server)
{
return RuntimeType.GetTypeFromCLSIDImpl(clsid, server, false);
}
- [System.Security.SecuritySafeCritical] // auto-generated
public static Type GetTypeFromCLSID(Guid clsid, String server, bool throwOnError)
{
return RuntimeType.GetTypeFromCLSIDImpl(clsid, server, throwOnError);
}
// Given a class handle, this will return the class for that handle.
- [System.Security.SecurityCritical]
[MethodImpl(MethodImplOptions.InternalCall)]
internal static extern RuntimeType GetTypeFromHandleUnsafe(IntPtr handle);
[Pure]
- [System.Security.SecuritySafeCritical] // auto-generated
[MethodImpl(MethodImplOptions.InternalCall)]
public static extern Type GetTypeFromHandle(RuntimeTypeHandle handle);
{
return GetProperties(Type.DefaultLookup);
}
-#if !FEATURE_CORECLR
-#endif
+
// GetNestedTypes()
// This set of method will return any nested types that are found inside
// of the type.
abstract public Type[] GetNestedTypes(BindingFlags bindingAttr);
-#if !FEATURE_CORECLR
- // GetNestedType()
-#endif
public Type GetNestedType(String name)
{
return GetNestedType(name,Type.DefaultLookup);
public bool IsInterface {
[Pure]
- [System.Security.SecuritySafeCritical] // auto-generated
get
{
RuntimeType rt = this as RuntimeType;
// Protected routine to determine if this class is contextful
- protected virtual bool IsContextfulImpl(){
-#if FEATURE_REMOTING
- return typeof(ContextBoundObject).IsAssignableFrom(this);
-#else
+ protected virtual bool IsContextfulImpl()
+ {
return false;
-#endif
}
// Protected routine to determine if this class is marshaled by ref
- protected virtual bool IsMarshalByRefImpl(){
-#if FEATURE_REMOTING
- return typeof(MarshalByRefObject).IsAssignableFrom(this);
-#else
+ protected virtual bool IsMarshalByRefImpl()
+ {
return false;
-#endif
}
internal virtual bool HasProxyAttributeImpl()
return (Object.ReferenceEquals(this.UnderlyingSystemType, o.UnderlyingSystemType));
}
- [System.Security.SecuritySafeCritical]
[Pure]
[MethodImplAttribute(MethodImplOptions.InternalCall)]
public static extern bool operator ==(Type left, Type right);
- [System.Security.SecuritySafeCritical]
[Pure]
[MethodImplAttribute(MethodImplOptions.InternalCall)]
public static extern bool operator !=(Type left, Type right);
return base.GetType();
}
-#if !FEATURE_CORECLR
- void _Type.GetTypeInfoCount(out uint pcTInfo)
- {
- throw new NotImplementedException();
- }
-
- void _Type.GetTypeInfo(uint iTInfo, uint lcid, IntPtr ppTInfo)
- {
- throw new NotImplementedException();
- }
-
- void _Type.GetIDsOfNames([In] ref Guid riid, IntPtr rgszNames, uint cNames, uint lcid, IntPtr rgDispId)
- {
- throw new NotImplementedException();
- }
-
- // If you implement this method, make sure to include _Type.Invoke in VM\DangerousAPIs.h and
- // include _Type in SystemDomain::IsReflectionInvocationMethod in AppDomain.cpp.
- void _Type.Invoke(uint dispIdMember, [In] ref Guid riid, uint lcid, short wFlags, IntPtr pDispParams, IntPtr pVarResult, IntPtr pExcepInfo, IntPtr puArgErr)
- {
- throw new NotImplementedException();
- }
-#endif
-
// private convenience data
private const BindingFlags DefaultLookup = BindingFlags.Instance | BindingFlags.Static | BindingFlags.Public;
internal const BindingFlags DeclaredOnlyLookup = BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.Static | BindingFlags.DeclaredOnly;
}
}
- [System.Security.SecurityCritical] // auto-generated_required
public override void GetObjectData(SerializationInfo info, StreamingContext context) {
base.GetObjectData(info, context);
info.AddValue("TypeName",TypeName,typeof(String));
public override String Message
{
- [System.Security.SecuritySafeCritical] // auto-generated
get {
SetMessageField();
return _message;
}
}
- [System.Security.SecurityCritical] // auto-generated
private void SetMessageField()
{
if (_message == null) {
}
// This is called from inside the EE.
- [System.Security.SecurityCritical] // auto-generated
private TypeLoadException(String className,
String assemblyName,
String messageArg,
ResourceId = info.GetInt32("TypeLoadResourceID");
}
- [System.Security.SecurityCritical] // auto-generated
[DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
[SuppressUnmanagedCodeSecurity]
private static extern void GetTypeLoadExceptionMessage(int resourceId, StringHandleOnStack retString);
//We can rely on the serialization mechanism on Exception to handle most of our needs, but
//we need to add a few fields of our own.
- [System.Security.SecurityCritical] // auto-generated_required
public override void GetObjectData(SerializationInfo info, StreamingContext context) {
if (info == null)
throw new ArgumentNullException(nameof(info));
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
+using System.Diagnostics;
using System.Diagnostics.Contracts;
using System.IO;
using System.Reflection;
namespace System
{
- [SecurityCritical]
internal class SafeTypeNameParserHandle : SafeHandleZeroOrMinusOneIsInvalid
{
#region QCalls
- [SecurityCritical]
[DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
[SuppressUnmanagedCodeSecurity]
private static extern void _ReleaseTypeNameParser(IntPtr pTypeNameParser);
{
}
- [SecurityCritical]
protected override bool ReleaseHandle()
{
_ReleaseTypeNameParser(handle);
internal sealed class TypeNameParser : IDisposable
{
#region QCalls
- [SecurityCritical]
[DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
[SuppressUnmanagedCodeSecurity]
private static extern void _CreateTypeNameParser(string typeName, ObjectHandleOnStack retHandle, bool throwOnError);
- [SecurityCritical]
[DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
[SuppressUnmanagedCodeSecurity]
private static extern void _GetNames(SafeTypeNameParserHandle pTypeNameParser, ObjectHandleOnStack retArray);
- [SecurityCritical]
[DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
[SuppressUnmanagedCodeSecurity]
private static extern void _GetTypeArguments(SafeTypeNameParserHandle pTypeNameParser, ObjectHandleOnStack retArray);
- [SecurityCritical]
[DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
[SuppressUnmanagedCodeSecurity]
private static extern void _GetModifiers(SafeTypeNameParserHandle pTypeNameParser, ObjectHandleOnStack retArray);
- [SecurityCritical]
[DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
[SuppressUnmanagedCodeSecurity]
private static extern void _GetAssemblyName(SafeTypeNameParserHandle pTypeNameParser, StringHandleOnStack retString);
#endregion
#region Static Members
- [SecuritySafeCritical]
internal static Type GetType(
string typeName,
Func<AssemblyName, Assembly> assemblyResolver,
#endregion
#region Private Data Members
- [SecurityCritical]
private SafeTypeNameParserHandle m_NativeParser;
private static readonly char[] SPECIAL_CHARS = {',', '[', ']', '&', '*', '+', '\\'}; /* see typeparse.h */
#endregion
#region Constructor and Disposer
- [SecuritySafeCritical]
private TypeNameParser(SafeTypeNameParserHandle handle)
{
m_NativeParser = handle;
}
- [SecuritySafeCritical]
public void Dispose()
{
m_NativeParser.Dispose();
#endregion
#region private Members
- [SecuritySafeCritical]
private unsafe Type ConstructType(
Func<AssemblyName, Assembly> assemblyResolver,
Func<Assembly, string, bool, Type> typeResolver,
string asmName = GetAssemblyName();
// GetAssemblyName never returns null
- Contract.Assert(asmName != null);
+ Debug.Assert(asmName != null);
if (asmName.Length > 0)
{
if (baseType == null)
{
// Cannot resolve the type. If throwOnError is true we should have already thrown.
- Contract.Assert(throwOnError == false);
+ Debug.Assert(throwOnError == false);
return null;
}
types = new Type[typeArguments.Length];
for (int i = 0; i < typeArguments.Length; i++)
{
- Contract.Assert(typeArguments[i] != null);
+ Debug.Assert(typeArguments[i] != null);
using (TypeNameParser argParser = new TypeNameParser(typeArguments[i]))
{
if (types[i] == null)
{
// If throwOnError is true argParser.ConstructType should have already thrown.
- Contract.Assert(throwOnError == false);
+ Debug.Assert(throwOnError == false);
return null;
}
}
}
}
- [SecuritySafeCritical]
private static Assembly ResolveAssembly(string asmName, Func<AssemblyName, Assembly> assemblyResolver, bool throwOnError, ref StackCrawlMark stackMark)
{
Contract.Requires(asmName != null && asmName.Length > 0);
return StringBuilderCache.GetStringAndRelease(sb);
}
- [SecuritySafeCritical]
private static SafeTypeNameParserHandle CreateTypeNameParser(string typeName, bool throwOnError)
{
SafeTypeNameParserHandle retHandle = null;
return retHandle;
}
- [SecuritySafeCritical]
private string[] GetNames()
{
string[] names = null;
return names;
}
- [SecuritySafeCritical]
private SafeTypeNameParserHandle[] GetTypeArguments()
{
SafeTypeNameParserHandle[] arguments = null;
return arguments;
}
- [SecuritySafeCritical]
private int[] GetModifiers()
{
int[] modifiers = null;
return modifiers;
}
- [SecuritySafeCritical]
private string GetAssemblyName()
{
string assemblyName = null;
private IntPtr Value;
private IntPtr Type;
- [System.Security.SecurityCritical] // auto-generated_required
[CLSCompliant(false)]
public static TypedReference MakeTypedReference(Object target, FieldInfo[] flds) {
if (target == null)
return result;
}
- [System.Security.SecurityCritical] // auto-generated
[MethodImplAttribute(MethodImplOptions.InternalCall)]
// reference to TypedReference is banned, so have to pass result as pointer
private unsafe static extern void InternalMakeTypedReference(void* result, Object target, IntPtr[] flds, RuntimeType lastFieldType);
throw new NotSupportedException(Environment.GetResourceString("NotSupported_NYI"));
}
- [System.Security.SecuritySafeCritical] // auto-generated
public unsafe static Object ToObject(TypedReference value)
{
return InternalToObject(&value);
}
- [System.Security.SecurityCritical] // auto-generated
[MethodImplAttribute(MethodImplOptions.InternalCall)]
internal unsafe extern static Object InternalToObject(void * value);
}
// This may cause the type to be changed.
- [System.Security.SecuritySafeCritical] // auto-generated
[CLSCompliant(false)]
public unsafe static void SetTypedReference(TypedReference target, Object value)
{
InternalSetTypedReference(&target, value);
}
- [System.Security.SecurityCritical] // auto-generated
[MethodImplAttribute(MethodImplOptions.InternalCall)]
internal unsafe extern static void InternalSetTypedReference(void * target, Object value);
}
}
// Converts the current value to a String in base-10 with no extra padding.
- [System.Security.SecuritySafeCritical] // auto-generated
public override String ToString() {
Contract.Ensures(Contract.Result<String>() != null);
return Number.FormatUInt32(m_value, null, NumberFormatInfo.CurrentInfo);
}
- [System.Security.SecuritySafeCritical] // auto-generated
public String ToString(IFormatProvider provider) {
Contract.Ensures(Contract.Result<String>() != null);
return Number.FormatUInt32(m_value, null, NumberFormatInfo.GetInstance(provider));
}
- [System.Security.SecuritySafeCritical] // auto-generated
public String ToString(String format) {
Contract.Ensures(Contract.Result<String>() != null);
return Number.FormatUInt32(m_value, format, NumberFormatInfo.CurrentInfo);
}
- [System.Security.SecuritySafeCritical] // auto-generated
public String ToString(String format, IFormatProvider provider) {
Contract.Ensures(Contract.Result<String>() != null);
return Number.FormatUInt32(m_value, format, NumberFormatInfo.GetInstance(provider));
}
// The base 10 representation of the number with no extra padding.
- [System.Security.SecuritySafeCritical] // auto-generated
public override String ToString() {
Contract.Ensures(Contract.Result<String>() != null);
return Number.FormatUInt32(m_value, null, NumberFormatInfo.CurrentInfo);
}
- [System.Security.SecuritySafeCritical] // auto-generated
public String ToString(IFormatProvider provider) {
Contract.Ensures(Contract.Result<String>() != null);
return Number.FormatUInt32(m_value, null, NumberFormatInfo.GetInstance(provider));
}
- [System.Security.SecuritySafeCritical] // auto-generated
public String ToString(String format) {
Contract.Ensures(Contract.Result<String>() != null);
return Number.FormatUInt32(m_value, format, NumberFormatInfo.CurrentInfo);
}
- [System.Security.SecuritySafeCritical] // auto-generated
public String ToString(String format, IFormatProvider provider) {
Contract.Ensures(Contract.Result<String>() != null);
return Number.FormatUInt32(m_value, format, NumberFormatInfo.GetInstance(provider));
return ((int)m_value) ^ (int)(m_value >> 32);
}
- [System.Security.SecuritySafeCritical] // auto-generated
public override String ToString() {
Contract.Ensures(Contract.Result<String>() != null);
return Number.FormatUInt64(m_value, null, NumberFormatInfo.CurrentInfo);
}
- [System.Security.SecuritySafeCritical] // auto-generated
public String ToString(IFormatProvider provider) {
Contract.Ensures(Contract.Result<String>() != null);
return Number.FormatUInt64(m_value, null, NumberFormatInfo.GetInstance(provider));
}
- [System.Security.SecuritySafeCritical] // auto-generated
public String ToString(String format) {
Contract.Ensures(Contract.Result<String>() != null);
return Number.FormatUInt64(m_value, format, NumberFormatInfo.CurrentInfo);
}
- [System.Security.SecuritySafeCritical] // auto-generated
public String ToString(String format, IFormatProvider provider) {
Contract.Ensures(Contract.Result<String>() != null);
return Number.FormatUInt64(m_value, format, NumberFormatInfo.GetInstance(provider));
[System.Runtime.InteropServices.ComVisible(true)]
public struct UIntPtr : IEquatable<UIntPtr>, ISerializable
{
- [SecurityCritical]
unsafe private void* m_value;
public static readonly UIntPtr Zero;
- [System.Security.SecuritySafeCritical] // auto-generated
[System.Runtime.Versioning.NonVersionable]
public unsafe UIntPtr(uint value)
{
m_value = (void *)value;
}
- [System.Security.SecuritySafeCritical] // auto-generated
[System.Runtime.Versioning.NonVersionable]
public unsafe UIntPtr(ulong value)
{
#endif
}
- [System.Security.SecurityCritical]
[CLSCompliant(false)]
[System.Runtime.Versioning.NonVersionable]
public unsafe UIntPtr(void* value)
m_value = value;
}
- [System.Security.SecurityCritical] // auto-generated
private unsafe UIntPtr(SerializationInfo info, StreamingContext context) {
ulong l = info.GetUInt64("value");
m_value = (void *)l;
}
- [System.Security.SecurityCritical]
unsafe void ISerializable.GetObjectData(SerializationInfo info, StreamingContext context)
{
if (info==null) {
info.AddValue("value", (ulong)m_value);
}
- [System.Security.SecuritySafeCritical] // auto-generated
public unsafe override bool Equals(Object obj) {
if (obj is UIntPtr) {
return (m_value == ((UIntPtr)obj).m_value);
return false;
}
- [SecuritySafeCritical]
unsafe bool IEquatable<UIntPtr>.Equals(UIntPtr other)
{
return m_value == other.m_value;
}
- [System.Security.SecuritySafeCritical] // auto-generated
public unsafe override int GetHashCode() {
-#if FEATURE_CORECLR
#if BIT64
ulong l = (ulong)m_value;
return (unchecked((int)l) ^ (int)(l >> 32));
#else // 32
return unchecked((int)m_value);
#endif
-#else
- return unchecked((int)((long)m_value)) & 0x7fffffff;
-#endif
}
- [System.Security.SecuritySafeCritical] // auto-generated
[System.Runtime.Versioning.NonVersionable]
public unsafe uint ToUInt32() {
#if BIT64
#endif
}
- [System.Security.SecuritySafeCritical] // auto-generated
[System.Runtime.Versioning.NonVersionable]
public unsafe ulong ToUInt64() {
return (ulong)m_value;
}
- [System.Security.SecuritySafeCritical] // auto-generated
public unsafe override String ToString() {
Contract.Ensures(Contract.Result<String>() != null);
return new UIntPtr(value);
}
- [System.Security.SecuritySafeCritical] // auto-generated
[System.Runtime.Versioning.NonVersionable]
public unsafe static explicit operator uint(UIntPtr value)
{
#endif
}
- [System.Security.SecuritySafeCritical] // auto-generated
[System.Runtime.Versioning.NonVersionable]
public unsafe static explicit operator ulong (UIntPtr value)
{
return (ulong)value.m_value;
}
- [System.Security.SecurityCritical]
[CLSCompliant(false)]
[System.Runtime.Versioning.NonVersionable]
public static unsafe explicit operator UIntPtr (void* value)
return new UIntPtr(value);
}
- [System.Security.SecurityCritical]
[CLSCompliant(false)]
[System.Runtime.Versioning.NonVersionable]
public static unsafe explicit operator void* (UIntPtr value)
}
- [System.Security.SecuritySafeCritical] // auto-generated
[System.Runtime.Versioning.NonVersionable]
public unsafe static bool operator == (UIntPtr value1, UIntPtr value2)
{
}
- [System.Security.SecuritySafeCritical] // auto-generated
[System.Runtime.Versioning.NonVersionable]
public unsafe static bool operator != (UIntPtr value1, UIntPtr value2)
{
}
}
- [System.Security.SecuritySafeCritical] // auto-generated
[CLSCompliant(false)]
[System.Runtime.Versioning.NonVersionable]
public unsafe void* ToPointer()
namespace System {
using System;
-#if FEATURE_CORECLR
- [System.Security.SecurityCritical] // auto-generated
-#endif
[Serializable]
[System.Runtime.InteropServices.ComVisible(true)]
public delegate void UnhandledExceptionEventHandler(Object sender, UnhandledExceptionEventArgs e);
#endregion
#region ISerializable
- [System.Security.SecurityCritical] // auto-generated
public virtual void GetObjectData(SerializationInfo info, StreamingContext context)
{
throw new NotSupportedException(Environment.GetResourceString("NotSupported_UnitySerHolder"));
#endregion
#region IObjectReference
- [System.Security.SecurityCritical] // auto-generated
public virtual Object GetRealObject(StreamingContext context)
{
// GetRealObject uses the data we have in m_data and m_unityType to do a lookup on the correct
[System.Runtime.InteropServices.ComVisible(true)]
public abstract class ValueType {
- [System.Security.SecuritySafeCritical]
public override bool Equals (Object obj) {
BCLDebug.Perf(false, "ValueType::Equals is not fast. "+this.GetType().FullName+" should override Equals(Object)");
if (null==obj) {
return true;
}
- [System.Security.SecuritySafeCritical] // auto-generated
[MethodImplAttribute(MethodImplOptions.InternalCall)]
private static extern bool CanCompareBits(Object obj);
- [System.Security.SecuritySafeCritical] // auto-generated
[MethodImplAttribute(MethodImplOptions.InternalCall)]
private static extern bool FastEqualsCheck(Object a, Object b);
**Arguments: None.
**Exceptions: None.
==============================================================================*/
- [System.Security.SecuritySafeCritical] // auto-generated
[MethodImplAttribute(MethodImplOptions.InternalCall)]
public extern override int GetHashCode();
using System.Globalization;
using System.Runtime.CompilerServices;
using System.Runtime.Versioning;
+ using System.Diagnostics;
using System.Diagnostics.Contracts;
[Serializable]
//
// Native Methods
//
- [System.Security.SecurityCritical] // auto-generated
[MethodImplAttribute(MethodImplOptions.InternalCall)]
internal extern double GetR8FromVar();
- [System.Security.SecurityCritical] // auto-generated
[MethodImplAttribute(MethodImplOptions.InternalCall)]
internal extern float GetR4FromVar();
- [System.Security.SecurityCritical] // auto-generated
[MethodImplAttribute(MethodImplOptions.InternalCall)]
internal extern void SetFieldsR4(float val);
- [System.Security.SecurityCritical] // auto-generated
[MethodImplAttribute(MethodImplOptions.InternalCall)]
internal extern void SetFieldsR8(double val);
- [System.Security.SecurityCritical] // auto-generated
[MethodImplAttribute(MethodImplOptions.InternalCall)]
internal extern void SetFieldsObject(Object val);
m_data2 = (int)(val >> 32);
}
- [System.Security.SecuritySafeCritical] // auto-generated
public Variant(float val) {
m_objref=null;
m_flags=CV_R4;
SetFieldsR4(val);
}
- [System.Security.SecurityCritical] // auto-generated
public Variant(double val) {
m_objref=null;
m_flags=CV_R8;
m_data2=0;
}
- [System.Security.SecuritySafeCritical] // auto-generated
public Variant(Object obj) {
m_data1=0;
m_data2=0;
{
vt = VarEnum.VT_ERROR;
obj = (Object)(((ErrorWrapper)obj).ErrorCode);
- Contract.Assert(obj != null, "obj != null");
+ Debug.Assert(obj != null, "obj != null");
}
else if (obj is CurrencyWrapper)
{
vt = VarEnum.VT_CY;
obj = (Object)(((CurrencyWrapper)obj).WrappedObject);
- Contract.Assert(obj != null, "obj != null");
+ Debug.Assert(obj != null, "obj != null");
}
else if (obj is BStrWrapper)
{
}
- [System.Security.SecurityCritical] // auto-generated
unsafe public Variant(void* voidPointer,Type pointerType) {
if (pointerType == null)
throw new ArgumentNullException(nameof(pointerType));
}
}
- [System.Security.SecuritySafeCritical] // auto-generated
public Object ToObject() {
switch (CVType) {
case CV_EMPTY:
}
// This routine will return an boxed enum.
- [System.Security.SecurityCritical] // auto-generated
[MethodImplAttribute(MethodImplOptions.InternalCall)]
private extern Object BoxEnum();
// Helper code for marshaling managed objects to VARIANT's (we use
// managed variants as an intermediate type.
- [System.Security.SecuritySafeCritical] // auto-generated
internal static void MarshalHelperConvertObjectToVariant(Object o, ref Variant v)
{
-#if FEATURE_REMOTING
- IConvertible ic = System.Runtime.Remoting.RemotingServices.IsTransparentProxy(o) ? null : o as IConvertible;
-#else
IConvertible ic = o as IConvertible;
-#endif
+
if (o == null)
{
v = Empty;
// Helper code: on the back propagation path where a VT_BYREF VARIANT*
// is marshaled to a "ref Object", we use this helper to force the
// updated object back to the original type.
- [System.Security.SecurityCritical] // auto-generated
internal static void MarshalHelperCastVariant(Object pValue, int vt, ref Variant v)
{
IConvertible iv = pValue as IConvertible;
===========================================================*/
namespace System {
+ using System.Diagnostics;
using System.Diagnostics.Contracts;
using System.Text;
using CultureInfo = System.Globalization.CultureInfo;
private Version(Version version)
{
- Contract.Assert(version != null);
+ Debug.Assert(version != null);
_Major = version._Major;
_Minor = version._Minor;
private const int ZERO_CHAR_VALUE = (int) '0';
private static void AppendPositiveNumber(int num, StringBuilder sb)
{
- Contract.Assert(num >= 0, "AppendPositiveNumber expect positive numbers");
+ Debug.Assert(num >= 0, "AppendPositiveNumber expect positive numbers");
int index = sb.Length;
int reminder;
} catch (OverflowException e) {
return e;
}
- Contract.Assert(false, "Int32.Parse() did not throw exception but TryParse failed: " + m_exceptionArgument);
+ Debug.Assert(false, "Int32.Parse() did not throw exception but TryParse failed: " + m_exceptionArgument);
return new FormatException(Environment.GetResourceString("Format_InvalidString"));
default:
- Contract.Assert(false, "Unmatched case in Version.GetVersionParseException() for value: " + m_failure);
+ Debug.Assert(false, "Unmatched case in Version.GetVersionParseException() for value: " + m_failure);
return new ArgumentException(Environment.GetResourceString("Arg_VersionString"));
}
}
using System.Security.Permissions;
using System.Runtime.CompilerServices;
using System.Runtime.Versioning;
+ using System.Diagnostics;
using System.Diagnostics.Contracts;
+
[System.Runtime.InteropServices.ComVisible(true)]
-#if !FEATURE_CORECLR
- [SecurityPermissionAttribute(SecurityAction.InheritanceDemand, Flags=SecurityPermissionFlag.UnmanagedCode)] // Don't call Object::MemberwiseClone.
-#endif
[Serializable]
public class WeakReference : ISerializable
{
// This field is not a regular GC handle. It can have a special values that are used to prevent a race condition between setting the target and finalization.
internal IntPtr m_handle;
-
-#if FEATURE_CORECLR
+
// Migrating InheritanceDemands requires this default ctor, so we can mark it SafeCritical
- [SecuritySafeCritical]
protected WeakReference() {
- Contract.Assert(false, "WeakReference's protected default ctor should never be used!");
+ Debug.Assert(false, "WeakReference's protected default ctor should never be used!");
throw new NotImplementedException();
}
-#endif
// Creates a new WeakReference that keeps track of target.
// Assumes a Short Weak Reference (ie TrackResurrection is false.)
//
public extern virtual bool IsAlive {
[MethodImplAttribute(MethodImplOptions.InternalCall)]
- [SecuritySafeCritical]
get;
}
//
public extern virtual Object Target {
[MethodImplAttribute(MethodImplOptions.InternalCall)]
- [SecuritySafeCritical]
get;
[MethodImplAttribute(MethodImplOptions.InternalCall)]
- [SecuritySafeCritical]
set;
}
// This is needed for subclasses deriving from WeakReference, however.
// Additionally, there may be some cases during shutdown when we run this finalizer.
[MethodImplAttribute(MethodImplOptions.InternalCall)]
- [SecuritySafeCritical]
extern ~WeakReference();
- [SecurityCritical]
public virtual void GetObjectData(SerializationInfo info, StreamingContext context)
{
if (info==null) {
}
[MethodImplAttribute(MethodImplOptions.InternalCall)]
- [SecuritySafeCritical]
private extern void Create(Object target, bool trackResurrection);
[MethodImplAttribute(MethodImplOptions.InternalCall)]
- [SecuritySafeCritical]
private extern bool IsTrackResurrection();
}
private extern T Target
{
[MethodImplAttribute(MethodImplOptions.InternalCall)]
- [SecuritySafeCritical]
get;
[MethodImplAttribute(MethodImplOptions.InternalCall)]
- [SecuritySafeCritical]
set;
}
// This is needed for subclasses deriving from WeakReference<T>, however.
// Additionally, there may be some cases during shutdown when we run this finalizer.
[MethodImplAttribute(MethodImplOptions.InternalCall)]
- [SecuritySafeCritical]
extern ~WeakReference();
- [SecurityCritical]
public void GetObjectData(SerializationInfo info, StreamingContext context)
{
if (info == null) {
}
[MethodImplAttribute(MethodImplOptions.InternalCall)]
- [SecuritySafeCritical]
private extern void Create(T target, bool trackResurrection);
[MethodImplAttribute(MethodImplOptions.InternalCall)]
- [SecuritySafeCritical]
private extern bool IsTrackResurrection();
}
}
using System;
using System.Threading;
using System.Runtime.CompilerServices;
+ using System.Diagnostics;
using System.Diagnostics.Contracts;
// Helper class to aid removal of LocalDataStore from the LocalDataStoreMgr
/*=========================================================================
** Method used to expand the capacity of the local data store.
=========================================================================*/
- [System.Security.SecuritySafeCritical] // auto-generated
private LocalDataStoreElement PopulateElement(LocalDataStoreSlot slot)
{
bool tookLock = false;
int capacity = m_Manager.GetSlotTableLength();
// Validate that the specified capacity is larger than the current one.
- Contract.Assert(capacity >= m_DataTable.Length, "LocalDataStore corrupted: capacity >= m_DataTable.Length");
+ Debug.Assert(capacity >= m_DataTable.Length, "LocalDataStore corrupted: capacity >= m_DataTable.Length");
// Allocate the new data table.
LocalDataStoreElement[] NewDataTable = new LocalDataStoreElement[capacity];
}
// Validate that there is enough space in the local data store now
- Contract.Assert(slotIdx < m_DataTable.Length, "LocalDataStore corrupted: slotIdx < m_DataTable.Length");
+ Debug.Assert(slotIdx < m_DataTable.Length, "LocalDataStore corrupted: slotIdx < m_DataTable.Length");
if (m_DataTable[slotIdx] == null)
m_DataTable[slotIdx] = new LocalDataStoreElement(slot.Cookie);
** list. The initial size of the new store matches the number of slots
** allocated in this manager.
=========================================================================*/
- [System.Security.SecuritySafeCritical] // auto-generated
public LocalDataStoreHolder CreateLocalDataStore()
{
// Create a new local data store.
/*=========================================================================
* Remove the specified store from the list of managed stores..
=========================================================================*/
- [System.Security.SecuritySafeCritical] // auto-generated
public void DeleteLocalDataStore(LocalDataStore store)
{
bool tookLock = false;
** an object to prevent clients from manipulating it directly, allowing us
** to make assumptions its integrity.
=========================================================================*/
- [System.Security.SecuritySafeCritical] // auto-generated
public LocalDataStoreSlot AllocateDataSlot()
{
bool tookLock = false;
/*=========================================================================
** Allocate a slot and associate a name with it.
=========================================================================*/
- [System.Security.SecuritySafeCritical] // auto-generated
public LocalDataStoreSlot AllocateNamedDataSlot(String name)
{
bool tookLock = false;
** Retrieve the slot associated with a name, allocating it if no such
** association has been defined.
=========================================================================*/
- [System.Security.SecuritySafeCritical] // auto-generated
public LocalDataStoreSlot GetNamedDataSlot(String name)
{
bool tookLock = false;
** Eliminate the association of a name with a slot. The actual slot will
** be reclaimed when the finalizer for the slot object runs.
=========================================================================*/
- [System.Security.SecuritySafeCritical] // auto-generated
public void FreeNamedDataSlot(String name)
{
bool tookLock = false;
/*=========================================================================
** Free's a previously allocated data slot on ALL the managed data stores.
=========================================================================*/
- [System.Security.SecuritySafeCritical] // auto-generated
internal void FreeDataSlot(int slot, long cookie)
{
bool tookLock = false;
**
**
===========================================================*/
-namespace System {
-
+namespace System
+{
using System;
using System.Collections;
using System.Threading;
return base.ToString();
}
- [System.Security.SecurityCritical] // auto-generated
internal IntPtr GetIUnknown(out bool fIsURTAggregated)
{
fIsURTAggregated = !GetType().IsDefined(typeof(ComImportAttribute), false);
// This method is called from within the EE and releases all the
// cached data for the __ComObject.
//====================================================================
- [System.Security.SecurityCritical] // auto-generated
internal void ReleaseAllData()
{
// Synchronize access to the map.
// This method is called from within the EE and is used to handle
// calls on methods of event interfaces.
//====================================================================
- [System.Security.SecurityCritical] // auto-generated
internal Object GetEventProvider(RuntimeType t)
{
// Check to see if we already have a cached event provider for this type.
return EvProvider;
}
- [System.Security.SecurityCritical] // auto-generated
internal int ReleaseSelf()
{
return Marshal.InternalReleaseComObject(this);
}
- [System.Security.SecurityCritical] // auto-generated
internal void FinalReleaseSelf()
{
Marshal.InternalFinalReleaseComObject(this);
}
- [System.Security.SecurityCritical] // auto-generated
-#if !FEATURE_CORECLR
- [ReflectionPermissionAttribute(SecurityAction.Assert, MemberAccess=true)]
-#endif
private Object CreateEventProvider(RuntimeType t)
{
// Create the event provider for the specified type.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
-
-using System;
-using System.Globalization;
-using System.IO;
-using System.Reflection;
-using System.Runtime.InteropServices;
-using System.Runtime.Serialization;
-using System.Security.Permissions;
-using System.Security.Policy;
-
namespace System.Runtime.InteropServices
{
[GuidAttribute("03973551-57A1-3900-A2B5-9083E3FF2943")]
[InterfaceTypeAttribute(ComInterfaceType.InterfaceIsIUnknown)]
[CLSCompliant(false)]
[TypeLibImportClassAttribute(typeof(System.Activator))]
-[System.Runtime.InteropServices.ComVisible(true)]
+ [System.Runtime.InteropServices.ComVisible(true)]
public interface _Activator
{
void GetTypeInfoCount(out uint pcTInfo);
[InterfaceTypeAttribute(ComInterfaceType.InterfaceIsIUnknown)]
[CLSCompliant(false)]
[TypeLibImportClassAttribute(typeof(System.Attribute))]
-[System.Runtime.InteropServices.ComVisible(true)]
+ [System.Runtime.InteropServices.ComVisible(true)]
public interface _Attribute
{
-#if !FEATURE_CORECLR
- void GetTypeInfoCount(out uint pcTInfo);
-
- void GetTypeInfo(uint iTInfo, uint lcid, IntPtr ppTInfo);
-
- void GetIDsOfNames([In] ref Guid riid, IntPtr rgszNames, uint cNames, uint lcid, IntPtr rgDispId);
-
- void Invoke(uint dispIdMember, [In] ref Guid riid, uint lcid, short wFlags, IntPtr pDispParams, IntPtr pVarResult, IntPtr pExcepInfo, IntPtr puArgErr);
-#endif
}
[GuidAttribute("C281C7F1-4AA9-3517-961A-463CFED57E75")]
[InterfaceTypeAttribute(ComInterfaceType.InterfaceIsIUnknown)]
[CLSCompliant(false)]
[TypeLibImportClassAttribute(typeof(System.Threading.Thread))]
-[System.Runtime.InteropServices.ComVisible(true)]
+ [System.Runtime.InteropServices.ComVisible(true)]
public interface _Thread
{
-#if !FEATURE_CORECLR
- void GetTypeInfoCount(out uint pcTInfo);
-
- void GetTypeInfo(uint iTInfo, uint lcid, IntPtr ppTInfo);
-
- void GetIDsOfNames([In] ref Guid riid, IntPtr rgszNames, uint cNames, uint lcid, IntPtr rgDispId);
-
- void Invoke(uint dispIdMember, [In] ref Guid riid, uint lcid, short wFlags, IntPtr pDispParams, IntPtr pVarResult, IntPtr pExcepInfo, IntPtr puArgErr);
-#endif
}
}
private static volatile int _captureAllocatedCallStackState;
internal static bool Enabled {
- [System.Security.SecuritySafeCritical] // auto-generated
get {
if (_enabledState == 0) {
if (Mda.IsStreamWriterBufferedDataLostEnabled())
}
internal static bool CaptureAllocatedCallStack {
- [System.Security.SecuritySafeCritical] // auto-generated
get {
if (_captureAllocatedCallStackState == 0) {
if (Mda.IsStreamWriterBufferedDataLostCaptureAllocatedCallStack())
}
}
- [System.Security.SecuritySafeCritical] // auto-generated
internal static void ReportError(String text) {
Mda.ReportStreamWriterBufferedDataLost(text);
}
}
- [System.Security.SecurityCritical] // auto-generated
[MethodImplAttribute(MethodImplOptions.InternalCall)]
internal static extern void ReportStreamWriterBufferedDataLost(String text);
- [System.Security.SecurityCritical] // auto-generated
[MethodImplAttribute(MethodImplOptions.InternalCall)]
internal static extern bool IsStreamWriterBufferedDataLostEnabled();
- [System.Security.SecurityCritical] // auto-generated
[MethodImplAttribute(MethodImplOptions.InternalCall)]
internal static extern bool IsStreamWriterBufferedDataLostCaptureAllocatedCallStack();
- [System.Security.SecurityCritical] // auto-generated
[MethodImplAttribute(MethodImplOptions.InternalCall)]
internal static extern void MemberInfoCacheCreation();
- [System.Security.SecurityCritical] // auto-generated
[MethodImplAttribute(MethodImplOptions.InternalCall)]
internal static extern void DateTimeInvalidLocalFormat();
- [System.Security.SecurityCritical] // auto-generated
[MethodImplAttribute(MethodImplOptions.InternalCall)]
internal static extern bool IsInvalidGCHandleCookieProbeEnabled();
- [System.Security.SecurityCritical] // auto-generated
[MethodImplAttribute(MethodImplOptions.InternalCall)]
internal static extern void FireInvalidGCHandleCookieProbe(IntPtr cookie);
- [System.Security.SecurityCritical]
[MethodImplAttribute(MethodImplOptions.InternalCall)]
internal static extern void ReportErrorSafeHandleRelease(Exception ex);
}
// See the LICENSE file in the project root for more information.
using System.Runtime.CompilerServices;
-#if FEATURE_CORECLR
// We need this to be able to typeforward to internal types
[assembly: InternalsVisibleTo("mscorlib, PublicKey=00240000048000009400000006020000002400005253413100040000010001008d56c76f9e8649383049f383c44be0ec204181822a6c31cf5eb7ef486944d032188ea1d3920763712ccb12d75fb77e9811149e6148e5d32fbaab37611c1878ddc19e20ef135d0cb2cff2bfec3d115810c3d9069638fe4be215dbf795861920e5ab6f7db2e2ceef136ac23d5dd2bf031700aec232f6c6b1c785b4305c123b37ab", AllInternalsVisible=false)]
-#endif
// For now we are only moving to using this file over AssemblyAttributes.cspp in CoreSys, ideally we would move away from the centralized
// AssemblyAttributes.cspp model for the other build types at a future point in time.
#define printf PAL_printf
#define vprintf PAL_vprintf
#define wprintf PAL_wprintf
-#define sprintf PAL_sprintf
#define swprintf PAL_swprintf
-#define sscanf PAL_sscanf
#define wcsspn PAL_wcsspn
#define wcstod PAL_wcstod
#define wcstol PAL_wcstol
PALIMPORT char * __cdecl strtok(char *, const char *);
PALIMPORT size_t __cdecl strspn(const char *, const char *);
PALIMPORT size_t __cdecl strcspn(const char *, const char *);
-PALIMPORT int __cdecl sprintf(char *, const char *, ...);
PALIMPORT int __cdecl vsprintf(char *, const char *, va_list);
-PALIMPORT int __cdecl sscanf(const char *, const char *, ...);
PALIMPORT int __cdecl atoi(const char *);
PALIMPORT LONG __cdecl atol(const char *);
PALIMPORT ULONG __cdecl strtoul(const char *, char **, int);
PALIMPORT int __cdecl swprintf_s(WCHAR *, size_t, const WCHAR *, ... );
PALIMPORT int __cdecl _snwprintf_s(WCHAR *, size_t, size_t, const WCHAR *, ...);
PALIMPORT int __cdecl vswprintf_s( WCHAR *, size_t, const WCHAR *, va_list);
+PALIMPORT int __cdecl sscanf_s(const char *, const char *, ...);
PALIMPORT errno_t __cdecl _itow_s(int, WCHAR *, size_t, int);
PALIMPORT size_t __cdecl PAL_wcslen(const WCHAR *);
#define _wcslwr_s _wcslwr_unsafe
#define _snprintf_s _snprintf_unsafe
#define swscanf_s swscanf
-#define sscanf_s sscanf
#define _wfopen_s _wfopen_unsafe
#define fopen_s _fopen_unsafe
.global C_FUNC(\Name\()_End)
LEAF_END \Name, \Section
.endm
+
+.macro PROLOG_BEG
+ push ebp
+ .cfi_def_cfa_offset 8
+ .cfi_offset ebp, -8
+ mov ebp, esp
+.endm
+
+.macro PROLOG_PUSH Reg
+ push \Reg
+ .cfi_adjust_cfa_offset 4
+ .cfi_rel_offset \Reg, 0
+.endm
+
+.macro PROLOG_END
+ .cfi_def_cfa_register ebp
+ .cfi_def_cfa_offset 8
+.endm
+
+.macro EPILOG_BEG
+.endm
+
+.macro EPILOG_POP Reg
+ pop \Reg
+ .cfi_restore \Reg
+.endm
+
+.macro EPILOG_END
+ pop ebp
+.endm
safecrt/safecrt_winput_s.cpp
safecrt/safecrt_woutput_s.cpp
safecrt/splitpath_s.cpp
- safecrt/sprintf.cpp
- safecrt/sscanf.cpp
+ safecrt/sprintf_s.cpp
+ safecrt/sscanf_s.cpp
safecrt/strcat_s.cpp
safecrt/strcpy_s.cpp
safecrt/strlen_s.cpp
// Restore
pop ebx
pop eax
- ret
+ ret 4
LEAF_END CONTEXT_CaptureContext, _TEXT
LEAF_ENTRY RtlCaptureContext, _TEXT
mov DWORD PTR [eax + CONTEXT_ContextFlags], (CONTEXT_FLOATING_POINT)
pop eax
jmp C_FUNC(CONTEXT_CaptureContext)
- ret
LEAF_END RtlCaptureContext, _TEXT
LEAF_ENTRY RtlRestoreContext, _TEXT
pop esi
pop edi
- ret
+ ret 8
LEAF_END RtlRestoreContext, _TEXT
/*++
Function:
- PAL_sscanf
-
-See MSDN doc.
---*/
-int
-__cdecl
-PAL_sscanf(
- const char *buffer,
- const char *format,
- ...)
-{
- int Length;
- va_list ap;
-
- PERF_ENTRY(sscanf);
- ENTRY("PAL_sscanf (buffer=%p (%s), format=%p (%s))\n", buffer, buffer, format, format);
-
- va_start(ap, format);
- Length = PAL_vsscanf(buffer, format, ap);
- va_end(ap);
-
- LOGEXIT("PAL_sscanf returns int %d\n", Length);
- PERF_EXIT(sscanf);
- return Length;
-}
-
-/*++
-Function:
- PAL_sprintf
-
-See MSDN doc.
---*/
-int
-__cdecl
-PAL_sprintf(
- char *buffer,
- const char *format,
- ...)
-{
- LONG Length;
- va_list ap;
-
- PERF_ENTRY(sprintf);
- ENTRY("PAL_sprintf (buffer=%p, format=%p (%s))\n", buffer, format, format);
-
- va_start(ap, format);
- Length = InternalVsnprintf(CorUnix::InternalGetCurrentThread(), buffer, 0x7fffffff, format, ap);
- va_end(ap);
-
- LOGEXIT("PAL_sprintf returns int %d\n", Length);
- PERF_EXIT(sprintf);
- return Length;
-}
-
-
-/*++
-Function:
PAL_swprintf
See MSDN doc.
if (nbAttachLeft == 0)
{
#if HAVE_PROCFS_CTL
- sprintf(ctlPath, sizeof(ctlPath), "/proc/%d/ctl", processId);
+ snprintf(ctlPath, sizeof(ctlPath), "/proc/%d/ctl", processId);
fd = InternalOpen(pThread, ctlPath, O_WRONLY);
if (fd == -1)
{
if (machret != KERN_SUCCESS) \
{ \
char _szError[1024]; \
- sprintf(_szError, "%s: %u: %s", __FUNCTION__, __LINE__, _msg); \
+ snprintf(_szError, _countof(_szError), "%s: %u: %s", __FUNCTION__, __LINE__, _msg); \
mach_error(_szError, machret); \
abort(); \
} \
--*/
void
+PALAPI
CONTEXT_CaptureContext(
LPCONTEXT lpContext
);
#undef vfwprintf
#undef vprintf
#undef wprintf
-#undef sprintf
#undef swprintf
-#undef sscanf
#undef wcstod
#undef wcstol
#undef wcstoul
#endif /* _SECURE_SCANF */
#ifndef _UNICODE
if (fl_wchar_arg) {
- wctemp = L'?';
+ wctemp = W('?');
char temp[2];
temp[0] = (char) ch;
#if 0 // we are not supporting multibyte input strings
#endif /* 0 */
_MBTOWC(&wctemp, temp, MB_CUR_MAX);
*(wchar_t UNALIGNED *)pointer = wctemp;
- /* just copy L'?' if mbtowc fails, errno is set by mbtowc */
+ /* just copy W('?') if mbtowc fails, errno is set by mbtowc */
pointer = (wchar_t *)pointer + 1;
#ifdef _SECURE_SCANF
--array_width;
/***
* _safecrt_cfltcvt - convert a float to an ascii string.
-* Uses sprintf - this usage is OK.
****/
/* routine used for floating-point output */
{
if ( flag != 0 ) // double
{
- double dblValue = 0.0;
- (void)sscanf( number, "%lf", &dblValue );
+ double dblValue = strtod(number, NULL);
*( ( double* )argument ) = dblValue;
}
else // float
{
- float fltValue = 0.0;
- (void)sscanf( number, "%f", &fltValue );
+ float fltValue = strtof(number, NULL);
*( ( float* )argument ) = fltValue;
}
}
// See the LICENSE file in the project root for more information.
/***
-*sprintf.c - print formatted to string
+*sprintf_s.c - print formatted to string
*
*
// See the LICENSE file in the project root for more information.
/***
-*sscanf.c - read formatted data from string
+*sscanf_s.c - read formatted data from string
*
*
extern PGET_GCMARKER_EXCEPTION_CODE g_getGcMarkerExceptionCode;
-// in context2.S
-extern void CONTEXT_CaptureContext(LPCONTEXT lpContext);
-
#define CONTEXT_AREA_MASK 0xffff
#ifdef _X86_
#define CONTEXT_ALL_FLOATING (CONTEXT_FLOATING_POINT | CONTEXT_EXTENDED_REGISTERS)
// According to `man proc`, the second field in the stat file is the filename of the executable,
// in parentheses. Tokenizing the stat file using spaces as separators breaks when that name
- // has spaces in it, so we start using sscanf after skipping everything up to and including the
+ // has spaces in it, so we start using sscanf_s after skipping everything up to and including the
// last closing paren and the space after it.
char *scanStartPosition = strrchr(line, ')') + 2;
// All the format specifiers for the fields in the stat file are provided by 'man proc'.
- int sscanfRet = sscanf(scanStartPosition,
+ int sscanfRet = sscanf_s(scanStartPosition,
"%*c %*d %*d %*d %*d %*d %*u %*lu %*lu %*lu %*lu %*lu %*lu %*ld %*ld %*ld %*ld %*ld %*ld %llu \n",
&starttime);
if (sscanfRet != 1)
{
- _ASSERTE(!"Failed to parse stat file contents with sscanf.");
+ _ASSERTE(!"Failed to parse stat file contents with sscanf_s.");
return FALSE;
}
char moduleName[PATH_MAX];
int size;
- if (sscanf(line, "__TEXT %p-%p [ %dK] %*[-/rwxsp] SM=%*[A-Z] %s\n", &startAddress, &endAddress, &size, moduleName) == 4)
+ if (sscanf_s(line, "__TEXT %p-%p [ %dK] %*[-/rwxsp] SM=%*[A-Z] %s\n", &startAddress, &endAddress, &size, moduleName, _countof(moduleName)) == 4)
{
bool dup = false;
for (ProcessModules *entry = listHead; entry != NULL; entry = entry->Next)
int devHi, devLo, inode;
char moduleName[PATH_MAX];
- if (sscanf(line, "%p-%p %*[-rwxsp] %p %x:%x %d %s\n", &startAddress, &endAddress, &offset, &devHi, &devLo, &inode, moduleName) == 7)
+ if (sscanf_s(line, "%p-%p %*[-rwxsp] %p %x:%x %d %s\n", &startAddress, &endAddress, &offset, &devHi, &devLo, &inode, moduleName, _countof(moduleName)) == 7)
{
if (inode != 0)
{
add_subdirectory(sinf)
add_subdirectory(sinh)
add_subdirectory(sinhf)
-add_subdirectory(sprintf)
+add_subdirectory(sprintf_s)
add_subdirectory(sqrt)
add_subdirectory(sqrtf)
-add_subdirectory(sscanf)
+add_subdirectory(sscanf_s)
add_subdirectory(strcat)
add_subdirectory(strchr)
add_subdirectory(strcmp)
+++ /dev/null
-cmake_minimum_required(VERSION 2.8.12.2)
-
-set(CMAKE_INCLUDE_CURRENT_DIR ON)
-
-set(SOURCES
- test5.cpp
-)
-
-add_executable(paltest_sprintf_test5
- ${SOURCES}
-)
-
-add_dependencies(paltest_sprintf_test5 coreclrpal)
-
-target_link_libraries(paltest_sprintf_test5
- pthread
- m
- coreclrpal
-)
+++ /dev/null
-// Licensed to the .NET Foundation under one or more agreements.
-// The .NET Foundation licenses this file to you under the MIT license.
-// See the LICENSE file in the project root for more information.
-
-/*============================================================================
-**
-** Source: test5.c
-**
-** Purpose: Test #5 for the sprintf function. Tests the count specifier (%n).
-**
-**
-**==========================================================================*/
-
-
-
-#include <palsuite.h>
-#include "../sprintf.h"
-
-/*
- * Depends on memcmp and strlen
- */
-
-
-int __cdecl main(int argc, char *argv[])
-{
- char *longStr =
- "really-long-string-that-just-keeps-going-on-and-on-and-on.."
- "..................useless-filler.................................."
- "..................useless-filler.................................."
- "..................useless-filler.................................."
- "%n bar";
- char *longResult =
- "really-long-string-that-just-keeps-going-on-and-on-and-on.."
- "..................useless-filler.................................."
- "..................useless-filler.................................."
- "..................useless-filler.................................."
- " bar";
-
- if (PAL_Initialize(argc, argv)!= 0)
- {
- return FAIL;
- }
-
- DoCountTest("foo %n bar", 4, "foo bar");
- DoCountTest(longStr, 257, longResult);
- DoCountTest("fo%n bar", 2, "fo bar");
- DoCountTest("%n", 0, "");
- DoCountTest("foo %#n bar", 4, "foo bar");
- DoCountTest("foo % n bar", 4, "foo bar");
- DoCountTest("foo %+n bar", 4, "foo bar");
- DoCountTest("foo %-n bar", 4, "foo bar");
- DoCountTest("foo %0n bar", 4, "foo bar");
- DoShortCountTest("foo %hn bar", 4, "foo bar");
- DoCountTest("foo %ln bar", 4, "foo bar");
- DoCountTest("foo %Ln bar", 4, "foo bar");
- DoCountTest("foo %I64n bar", 4, "foo bar");
- DoCountTest("foo %20.3n bar", 4, "foo bar");
-
- PAL_Terminate();
-
- return PASS;
-}
+++ /dev/null
-# Licensed to the .NET Foundation under one or more agreements.
-# The .NET Foundation licenses this file to you under the MIT license.
-# See the LICENSE file in the project root for more information.
-
-Version = 1.0
-Section = C Runtime
-Function = sprintf
-Name = Positive Test for sprintf
-TYPE = DEFAULT
-EXE1 = test5
-Description
-= Tests sprintf with the count specifier
add_subdirectory(test2)
add_subdirectory(test3)
add_subdirectory(test4)
-add_subdirectory(test5)
add_subdirectory(test6)
add_subdirectory(test7)
add_subdirectory(test8)
/*============================================================================
**
-** Source: sprintf.h
+** Source: sprintf_s.h
**
-** Purpose: Containts common testing functions for sprintf
+** Purpose: Containts common testing functions for sprintf_s
**
**
**==========================================================================*/
-#ifndef __SPRINTF_H__
-#define __SPRINTF_H__
+#ifndef __SPRINTF_S_H__
+#define __SPRINTF_S_H__
void DoStrTest(const char *formatstr, char* param, const char *checkstr)
{
char buf[256] = { 0 };
- sprintf(buf, formatstr, param);
+ sprintf_s(buf, _countof(buf), formatstr, param);
if (memcmp(buf, checkstr, strlen(checkstr) + 1) != 0)
{
Fail("ERROR: failed to insert string \"%s\" into \"%s\"\n"
{
char buf[256] = { 0 };
- sprintf(buf, formatstr, param);
+ sprintf_s(buf, _countof(buf), formatstr, param);
if (memcmp(buf, checkstr, strlen(checkstr) + 1) != 0)
{
Fail("ERROR: failed to insert wide string \"%s\" into \"%s\"\n"
{
char buf[256] = { 0 };
- sprintf(buf, formatstr, param);
+ sprintf_s(buf, _countof(buf), formatstr, param);
if (memcmp(buf, checkstr1, strlen(checkstr1) + 1) != 0)
{
Fail("ERROR: failed to insert %s into \"%s\"\n"
char buf[512] = { 0 };
int n = -1;
- sprintf(buf, formatstr, &n);
+ sprintf_s(buf, _countof(buf), formatstr, &n);
if (n != param)
{
char buf[256] = { 0 };
short int n = -1;
- sprintf(buf, formatstr, &n);
+ sprintf_s(buf, _countof(buf), formatstr, &n);
if (n != param)
{
{
char buf[256] = { 0 };
- sprintf(buf, formatstr, param);
+ sprintf_s(buf, _countof(buf), formatstr, param);
if (memcmp(buf, checkstr, strlen(checkstr) + 1) != 0)
{
Fail("ERROR: failed to insert char \'%c\' (%d) into \"%s\"\n"
{
char buf[256] = { 0 };
- sprintf(buf, formatstr, param);
+ sprintf_s(buf, _countof(buf), formatstr, param);
if (memcmp(buf, checkstr, strlen(checkstr) + 1) != 0)
{
Fail("ERROR: failed to insert wide char \'%c\' (%d) into \"%s\"\n"
{
char buf[256] = { 0 };
- sprintf(buf, formatstr, value);
+ sprintf_s(buf, _countof(buf), formatstr, value);
if (memcmp(buf, checkstr, strlen(checkstr) + 1) != 0)
{
Fail("ERROR: failed to insert %#x into \"%s\"\n"
{
char buf[256] = { 0 };
- sprintf(buf, formatstr, value);
+ sprintf_s(buf, _countof(buf), formatstr, value);
if (memcmp(buf, checkstr1, strlen(checkstr1) + 1) != 0)
{
Fail("ERROR: failed to insert %s into \"%s\"\n"
{
char buf[256] = { 0 };
- sprintf(buf, formatstr, value);
+ sprintf_s(buf, _countof(buf), formatstr, value);
if (memcmp(buf, checkstr1, strlen(checkstr1) + 1) != 0 &&
memcmp(buf, checkstr2, strlen(checkstr2) + 1) != 0)
{
{
char buf[256];
- sprintf(buf, formatstr, precision, param);
+ sprintf_s(buf, _countof(buf), formatstr, precision, param);
if (memcmp(buf, checkstr1, strlen(checkstr1) + 1) != 0 &&
memcmp(buf, checkstr2, strlen(checkstr2) + 1) != 0)
{
{
char buf[256];
- sprintf(buf, formatstr, precision, param);
+ sprintf_s(buf, _countof(buf), formatstr, precision, param);
if (memcmp(buf, checkstr1, strlen(checkstr1) + 1) != 0 &&
memcmp(buf, checkstr2, strlen(checkstr2) + 1) != 0)
{
**
** Source: test1.c
**
-** Purpose: Test #1 for the sprintf function. A single, basic, test
+** Purpose: Test #1 for the sprintf_s function. A single, basic, test
** case with no formatting.
**
**
#include <palsuite.h>
-#include "../sprintf.h"
+#include "../sprintf_s.h"
/*
* Depends on memcmp and strlen
}
- sprintf(buf, "hello world");
+ sprintf_s(buf, _countof(buf), "hello world");
if (memcmp(checkstr, buf, strlen(checkstr)+1) != 0)
{
Version = 1.0
Section = C Runtime
-Function = sprintf
-Name = Positive Test for sprintf
+Function = sprintf_s
+Name = Positive Test for sprintf_s
TYPE = DEFAULT
EXE1 = test1
Description
-= General test to see if sprintf works correctly
+= General test to see if sprintf_s works correctly
**
** Source: test10.c
**
-** Purpose: Test #10 for the sprintf function. Tests the octal specifier
+** Purpose: Test #10 for the sprintf_s function. Tests the octal specifier
** (%o).
**
**
#include <palsuite.h>
-#include "../sprintf.h"
+#include "../sprintf_s.h"
/*
* Depends on memcmp and strlen
Version = 1.0
Section = C Runtime
-Function = sscanf
-Name = Positive Test for sscanf
+Function = sprintf_s
+Name = Positive Test for sprintf_s
TYPE = DEFAULT
EXE1 = test10
Description
-= Tests sscanf with wide characters
+= Tests sprintf_s with octal numbers
**
** Source: test11.c
**
-** Purpose: Test #11 for the sprintf function. Test the unsigned int
+** Purpose: Test #11 for the sprintf_s function. Test the unsigned int
** specifier (%u).
**
**
#include <palsuite.h>
-#include "../sprintf.h"
+#include "../sprintf_s.h"
/*
* Depends on memcmp and strlen
Version = 1.0
Section = C Runtime
-Function = sprintf
-Name = Positive Test for sprintf
+Function = sprintf_s
+Name = Positive Test for sprintf_s
TYPE = DEFAULT
EXE1 = test11
Description
-= Tests sprintf with unsigned numbers
+= Tests sprintf_s with unsigned numbers
**
** Source: test12.c
**
-** Purpose: Test #12 for the sprintf function. Tests the (lowercase)
+** Purpose: Test #12 for the sprintf_s function. Tests the (lowercase)
** hexadecimal specifier (%x)
**
**
#include <palsuite.h>
-#include "../sprintf.h"
+#include "../sprintf_s.h"
/*
* Depends on memcmp and strlen
Version = 1.0
Section = C Runtime
-Function = sprintf
-Name = Positive Test for sprintf
+Function = sprintf_s
+Name = Positive Test for sprintf_s
TYPE = DEFAULT
EXE1 = test12
Description
-= Tests sprintf with hex numbers (lowercase)
+= Tests sprintf_s with hex numbers (lowercase)
**
** Source: test13.c
**
-** Purpose: Test #13 for the sprintf function. Tests the (uppercase)
+** Purpose: Test #13 for the sprintf_s function. Tests the (uppercase)
** hexadecimal specifier (%X)
**
**
#include <palsuite.h>
-#include "../sprintf.h"
+#include "../sprintf_s.h"
/*
* Depends on memcmp and strlen
Version = 1.0
Section = C Runtime
-Function = sscanf
-Name = Positive Test for sscanf
+Function = sprintf_s
+Name = Positive Test for sprintf_s
TYPE = DEFAULT
EXE1 = test13
Description
-= Tests sscanf with floats (decimal notation)
+= Tests sprintf_s with hex numbers (uppercase)
**
** Source: test14.c
**
-** Purpose: Test #14 for the sprintf function. Tests the lowercase
+** Purpose: Test #14 for the sprintf_s function. Tests the lowercase
** exponential notation double specifier (%e)
**
**
#include <palsuite.h>
-#include "../sprintf.h"
+#include "../sprintf_s.h"
/*
* Depends on memcmp and strlen
Version = 1.0
Section = C Runtime
-Function = sscanf
-Name = Positive Test for sscanf
+Function = sprintf_s
+Name = Positive Test for sprintf_s
TYPE = DEFAULT
EXE1 = test14
Description
-= Tests sscanf with floats (exponential notation, lowercase)
+= Tests sprintf_s with exponential format doubles (lowercase)
**
** Source: test15.c
**
-** Purpose: Test #15 for the sprintf function. Tests the uppercase
+** Purpose: Test #15 for the sprintf_s function. Tests the uppercase
** exponential notation double specifier (%E)
**
**
#include <palsuite.h>
-#include "../sprintf.h"
+#include "../sprintf_s.h"
/*
* Depends on memcmp and strlen
Version = 1.0
Section = C Runtime
-Function = sscanf
-Name = Positive Test for sscanf
+Function = sprintf_s
+Name = Positive Test for sprintf_s
TYPE = DEFAULT
EXE1 = test15
Description
-= Tests sscanf with floats (exponential notation, uppercase)
+= Tests sprintf_s with exponential format doubles (uppercase)
**
** Source: test16.c
**
-** Purpose: Test #16 for the sprintf function. Tests the decimal notation
+** Purpose: Test #16 for the sprintf_s function. Tests the decimal notation
** double specifier (%f)
**
**
#include <palsuite.h>
-#include "../sprintf.h"
+#include "../sprintf_s.h"
/*
* Depends on memcmp and strlen
Version = 1.0
Section = C Runtime
-Function = sprintf
-Name = Positive Test for sprintf
+Function = sprintf_s
+Name = Positive Test for sprintf_s
TYPE = DEFAULT
EXE1 = test16
Description
-= Tests sprintf with decimal point format doubles
+= Tests sprintf_s with decimal point format doubles
**
** Source: test17.c
**
-** Purpose: Test #17 for the sprintf function. Tests the lowercase
+** Purpose: Test #17 for the sprintf_s function. Tests the lowercase
** shorthand notation double specifier (%g)
**
**
#include <palsuite.h>
-#include "../sprintf.h"
+#include "../sprintf_s.h"
/*
* Depends on memcmp and strlen
Version = 1.0
Section = C Runtime
-Function = sscanf
-Name = Positive Test for sscanf
+Function = sprintf_s
+Name = Positive Test for sprintf_s
TYPE = DEFAULT
EXE1 = test17
Description
-= Tests sscanf with floats (compact notation, uppercase)
+= Tests sprintf_s with compact format doubles (lowercase)
**
** Source: test18.c
**
-** Purpose: Test #18 for the sprintf function. Tests the uppercase
+** Purpose: Test #18 for the sprintf_s function. Tests the uppercase
** shorthand notation double specifier (%G)
**
**
#include <palsuite.h>
-#include "../sprintf.h"
+#include "../sprintf_s.h"
/*
* Depends on memcmp and strlen
Version = 1.0
Section = C Runtime
-Function = sprintf
-Name = Positive Test for sprintf
+Function = sprintf_s
+Name = Positive Test for sprintf_s
TYPE = DEFAULT
EXE1 = test18
Description
-= Tests sprintf with compact format doubles (uppercase)
+= Tests sprintf_s with compact format doubles (uppercase)
**
** Source: test19.c
**
-** Purpose: Test #19 for the sprintf function. Tests the variable length
+** Purpose: Test #19 for the sprintf_s function. Tests the variable length
** precision argument.
**
**
#include <palsuite.h>
-#include "../sprintf.h"
+#include "../sprintf_s.h"
/*
* Depends on memcmp and strlen
DoArgumentPrecTest("%.*s", 2, (void*)"bar", "bar", "ba", "ba");
DoArgumentPrecTest("%.*S", 2, (void*)convert("bar"), "bar", "ba", "ba");
- DoArgumentPrecTest("%.*n", 3, (void*)&n, "pointer to int", "", "");
- if (n != 0)
- {
- Fail("ERROR: Expected count parameter to resolve to %d, got %X\n",
- 0, n);
- }
-
DoArgumentPrecTest("%.*c", 0, (void*)'a', "a", "a", "a");
DoArgumentPrecTest("%.*c", 4, (void*)'a', "a", "a", "a");
DoArgumentPrecTest("%.*C", 0, (void*)'a', "a", "a", "a");
Version = 1.0
Section = C Runtime
-Function = sprintf
-Name = Positive Test for sprintf
+Function = sprintf_s
+Name = Positive Test for sprintf_s
TYPE = DEFAULT
EXE1 = test19
Description
-= Tests sprintf with argument specified precision
+= Tests sprintf_s with argument specified precision
**
** Source: test2.c
**
-** Purpose: Test #2 for the sprintf function. Tests the string specifier
+** Purpose: Test #2 for the sprintf_s function. Tests the string specifier
** (%s).
**
**
#include <palsuite.h>
-#include "../sprintf.h"
+#include "../sprintf_s.h"
/*
* Depends on memcmp and strlen
Version = 1.0
Section = C Runtime
-Function = sprintf
-Name = Positive Test for sprintf
+Function = sprintf_s
+Name = Positive Test for sprintf_s
TYPE = DEFAULT
EXE1 = test2
Description
-= Tests sprintf with strings
+= Tests sprintf_s with strings
**
** Source: test3.c
**
-** Purpose: Test #3 for the sprintf function. Tests the wide string
+** Purpose: Test #3 for the sprintf_s function. Tests the wide string
** specifier (%S).
**
**
#include <palsuite.h>
-#include "../sprintf.h"
+#include "../sprintf_s.h"
/*
* Depends on memcmp and strlen
Version = 1.0
Section = C Runtime
-Function = sscanf
-Name = Positive Test for sscanf
+Function = sprintf_s
+Name = Positive Test for sprintf_s
TYPE = DEFAULT
EXE1 = test3
Description
-= Tests sscanf with bracketed set strings
+= Tests sprintf_s with wide strings
**
** Source: test4.c
**
-** Purpose: Test #4 for the sprintf function. Tests the pointer
+** Purpose: Test #4 for the sprintf_s function. Tests the pointer
** specifier (%p).
**
**
#include <palsuite.h>
-#include "../sprintf.h"
+#include "../sprintf_s.h"
/*
* Depends on memcmp and strlen
*/
Version = 1.0
Section = C Runtime
-Function = sscanf
-Name = Positive Test for sscanf
+Function = sprintf_s
+Name = Positive Test for sprintf_s
TYPE = DEFAULT
EXE1 = test4
Description
-= Tests sscanf with decimal numbers
+= Tests sprintf_s with pointers
**
** Source: test6.c
**
-** Purpose: Test #6 for the sprintf function. Tests the char specifier (%c).
+** Purpose: Test #6 for the sprintf_s function. Tests the char specifier (%c).
**
**
**==========================================================================*/
#include <palsuite.h>
-#include "../sprintf.h"
+#include "../sprintf_s.h"
/*
* Depends on memcmp and strlen
Version = 1.0
Section = C Runtime
-Function = sprintf
-Name = Positive Test for sprintf
+Function = sprintf_s
+Name = Positive Test for sprintf_s
TYPE = DEFAULT
EXE1 = test6
Description
-= Tests sprintf with characters
+= Tests sprintf_s with characters
**
** Source: test7.c
**
-** Purpose: Test #7 for the sprintf function. Tests the wide char
+** Purpose: Test #7 for the sprintf_s function. Tests the wide char
** specifier (%C).
**
**
#include <palsuite.h>
-#include "../sprintf.h"
+#include "../sprintf_s.h"
/*
* Depends on memcmp and strlen
Version = 1.0
Section = C Runtime
-Function = sprintf
-Name = Positive Test for sprintf
+Function = sprintf_s
+Name = Positive Test for sprintf_s
TYPE = DEFAULT
EXE1 = test7
Description
-= Tests sprintf with wide characters
+= Tests sprintf_s with wide characters
**
** Source: test8.c
**
-** Purpose: Test #8 for the sprintf function. Tests the decimal
+** Purpose: Test #8 for the sprintf_s function. Tests the decimal
** specifier (%d).
**
**
#include <palsuite.h>
-#include "../sprintf.h"
+#include "../sprintf_s.h"
/*
* Depends on memcmp and strlen
Version = 1.0
Section = C Runtime
-Function = sscanf
-Name = Positive Test for sscanf
+Function = sprintf_s
+Name = Positive Test for sprintf_s
TYPE = DEFAULT
EXE1 = test8
Description
-= Tests sscanf with unsigned numbers
+= Tests sprintf_s with decimal numbers
**
** Source: test9.c
**
-** Purpose: Test #9 for the sprintf function. Tests the integer
+** Purpose: Test #9 for the sprintf_s function. Tests the integer
** specifier (%i).
**
**
#include <palsuite.h>
-#include "../sprintf.h"
+#include "../sprintf_s.h"
/*
* Depends on memcmp and strlen
Version = 1.0
Section = C Runtime
-Function = sprintf
-Name = Positive Test for sprintf
+Function = sprintf_s
+Name = Positive Test for sprintf_s
TYPE = DEFAULT
EXE1 = test9
Description
-= Tests sprintf with integer numbers
+= Tests sprintf_s with integer numbers
/*============================================================================
**
-** Source: sscanf.h
+** Source: sscanf_s.h
**
-** Purpose: Contains common testing functions for sscanf.h
+** Purpose: Contains common testing functions for sscanf_s
**
**
**==========================================================================*/
-#ifndef __SSCANF_H__
-#define __SSCANF_H__
+#ifndef __SSCANF_S_H__
+#define __SSCANF_S_H__
void DoVoidTest(char *inputstr, const char *formatstr)
{
int i;
int ret;
- ret = sscanf(inputstr, formatstr, buf);
+ ret = sscanf_s(inputstr, formatstr, buf);
if (ret != 0)
{
- Fail("ERROR: Expected sscanf to return 0, got %d.\n"
+ Fail("ERROR: Expected sscanf_s to return 0, got %d.\n"
"Using \"%s\" in \"%s\".\n", ret, inputstr, formatstr);
}
char buf[256] = { 0 };
int ret;
- ret = sscanf(inputstr, formatstr, buf);
+ ret = sscanf_s(inputstr, formatstr, buf, _countof(buf));
if (ret != 1)
{
- Fail("ERROR: Expected sscanf to return 1, got %d.\n"
+ Fail("ERROR: Expected sscanf_s to return 1, got %d.\n"
"Using \"%s\" in \"%s\".\n", ret, inputstr, formatstr);
}
WCHAR buf[256] = { 0 };
int ret;
- ret = sscanf(inputstr, formatstr, buf);
+ ret = sscanf_s(inputstr, formatstr, buf, _countof(buf));
if (ret != 1)
{
- Fail("ERROR: Expected sscanf to return 1, got %d.\n"
+ Fail("ERROR: Expected sscanf_s to return 1, got %d.\n"
"Using \"%s\" in \"%s\".\n", ret, inputstr, formatstr);
}
int num;
int ret;
- ret = sscanf(inputstr, formatstr, &num);
+ ret = sscanf_s(inputstr, formatstr, &num);
if (ret != 1)
{
- Fail("ERROR: Expected sscanf to return 1, got %d.\n"
+ Fail("ERROR: Expected sscanf_s to return 1, got %d.\n"
"Using \"%s\" in \"%s\".\n", ret, inputstr, formatstr);
}
short num;
int ret;
- ret = sscanf(inputstr, formatstr, &num);
+ ret = sscanf_s(inputstr, formatstr, &num);
if (ret != 1)
{
- Fail("ERROR: Expected sscanf to return 1, got %d.\n"
+ Fail("ERROR: Expected sscanf_s to return 1, got %d.\n"
"Using \"%s\" in \"%s\".\n", ret, inputstr, formatstr);
}
INT64 num;
int ret;
- ret = sscanf(inputstr, formatstr, &num);
+ ret = sscanf_s(inputstr, formatstr, &num);
if (ret != 1)
{
- Fail("ERROR: Expected sscanf to return 1, got %d.\n"
+ Fail("ERROR: Expected sscanf_s to return 1, got %d.\n"
"Using \"%s\" in \"%s\".\n", ret, inputstr, formatstr);
}
if (checknum != num)
{
- sprintf(buf, "%I64d", num);
- sprintf(check, "%I64d", checknum);
+ sprintf_s(buf, _countof(buf), "%I64d", num);
+ sprintf_s(check, _countof(check), "%I64d", checknum);
Fail("ERROR: scanned I64 number incorrectly from \"%s\" using \"%s\".\n"
"Expected %s, got %s.\n", inputstr, formatstr, check, buf);
}
for (i=0; i<256; i++)
buf[i] = (char)-1;
- ret = sscanf(inputstr, formatstr, buf);
+ ret = sscanf_s(inputstr, formatstr, buf, _countof(buf));
if (ret != 1)
{
- Fail("ERROR: Expected sscanf to return 1, got %d.\n"
+ Fail("ERROR: Expected sscanf_s to return 1, got %d.\n"
"Using \"%s\" in \"%s\".\n", ret, inputstr, formatstr);
}
for (i=0; i<256; i++)
buf[i] = (WCHAR)-1;
- ret = sscanf(inputstr, formatstr, buf);
+ ret = sscanf_s(inputstr, formatstr, buf, _countof(buf));
if (ret != 1)
{
- Fail("ERROR: Expected sscanf to return 1, got %d.\n"
+ Fail("ERROR: Expected sscanf_s to return 1, got %d.\n"
"Using \"%s\" in \"%s\".\n", ret, inputstr, formatstr);
}
for (i=0; i<256; i++)
buf[i] = (char)-1;
- ret = sscanf(inputstr, formatstr, buf);
+ ret = sscanf_s(inputstr, formatstr, buf);
val = *(float*)buf;
if (ret != 1)
{
- Fail("ERROR: Expected sscanf to return 1, got %d.\n"
+ Fail("ERROR: Expected sscanf_s to return 1, got %d.\n"
"Using \"%s\" in \"%s\".\n", ret, inputstr, formatstr);
}
**
** Source: test1.c
**
-** Purpose: General test of sscanf
+** Purpose: General test of sscanf_s
**
**
**==========================================================================*/
#include <palsuite.h>
-#include "../sscanf.h"
+#include "../sscanf_s.h"
int __cdecl main(int argc, char *argv[])
DoVoidTest("foo bar baz", "foo % bar %s");
DoVoidTest("foo baz bar", "foo% baz %s");
- ret = sscanf("foo bar baz", "foo bar %n", &num);
+ ret = sscanf_s("foo bar baz", "foo bar %n", &num);
if (ret != 0 || num != 8)
{
Fail("ERROR: Got incorrect values in scanning \"%s\" using \"%s\".\n"
Version = 1.0
Section = C Runtime
-Function = sscanf
-Name = Positive Test for sscanf
+Function = sscanf_s
+Name = Positive Test for sscanf_s
TYPE = DEFAULT
EXE1 = test1
Description
-= General test of sscanf
+= General test of sscanf_s
**
** Source: test10.c
**
-** Purpose: Tests sscanf with wide charactersn
+** Purpose: Tests sscanf_s with wide characters
**
**
**==========================================================================*/
#include <palsuite.h>
-#include "../sscanf.h"
+#include "../sscanf_s.h"
int __cdecl main(int argc, char *argv[])
{
Version = 1.0
Section = C Runtime
-Function = sprintf
-Name = Positive Test for sprintf
+Function = sscanf_s
+Name = Positive Test for sscanf_s
TYPE = DEFAULT
EXE1 = test10
Description
-= Tests sprintf with octal numbers
+= Tests sscanf_s with wide characters
**
** Source: test11.c
**
-** Purpose: Tests sscanf with strings
+** Purpose: Tests sscanf_s with strings
**
**
**==========================================================================*/
#include <palsuite.h>
-#include "../sscanf.h"
+#include "../sscanf_s.h"
int __cdecl main(int argc, char *argv[])
{
Version = 1.0
Section = C Runtime
-Function = sscanf
-Name = Positive Test for sscanf
+Function = sscanf_s
+Name = Positive Test for sscanf_s
TYPE = DEFAULT
EXE1 = test11
Description
-= Tests sscanf with strings
+= Tests sscanf_s with strings
**
** Source: test12.c
**
-** Purpose: Tests sscanf with wide strings
+** Purpose: Tests sscanf_s with wide strings
**
**
**==========================================================================*/
#include <palsuite.h>
-#include "../sscanf.h"
+#include "../sscanf_s.h"
int __cdecl main(int argc, char *argv[])
{
Version = 1.0
Section = C Runtime
-Function = sscanf
-Name = Positive Test for sscanf
+Function = sscanf_s
+Name = Positive Test for sscanf_s
TYPE = DEFAULT
EXE1 = test12
Description
-= Tests sscanf with wide strings
+= Tests sscanf_s with wide strings
**
** Source: test13.c
**
-** Purpose: Tests sscanf with floats (decimal notation)
+** Purpose: Tests sscanf_s with floats (decimal notation)
**
**
**==========================================================================*/
#include <palsuite.h>
-#include "../sscanf.h"
+#include "../sscanf_s.h"
int __cdecl main(int argc, char *argv[])
{
Version = 1.0
Section = C Runtime
-Function = sprintf
-Name = Positive Test for sprintf
+Function = sscanf_s
+Name = Positive Test for sscanf_s
TYPE = DEFAULT
EXE1 = test13
Description
-= Tests sprintf with hex numbers (uppercase)
+= Tests sscanf_s with floats (decimal notation)
**
** Source: test14.c
**
-** Purpose: Tests sscanf with floats (exponential notation, lowercase)
+** Purpose: Tests sscanf_s with floats (exponential notation, lowercase)
**
**
**==========================================================================*/
#include <palsuite.h>
-#include "../sscanf.h"
+#include "../sscanf_s.h"
int __cdecl main(int argc, char *argv[])
{
Version = 1.0
Section = C Runtime
-Function = sprintf
-Name = Positive Test for sprintf
+Function = sscanf_s
+Name = Positive Test for sscanf_s
TYPE = DEFAULT
EXE1 = test14
Description
-= Tests sprintf with exponential format doubles (lowercase)
+= Tests sscanf_s with floats (exponential notation, lowercase)
**
** Source: test15.c
**
-** Purpose: Tests sscanf with floats (exponential notation, uppercase
+** Purpose: Tests sscanf_s with floats (exponential notation, uppercase
**
**
**==========================================================================*/
#include <palsuite.h>
-#include "../sscanf.h"
+#include "../sscanf_s.h"
int __cdecl main(int argc, char *argv[])
{
Version = 1.0
Section = C Runtime
-Function = sprintf
-Name = Positive Test for sprintf
+Function = sscanf_s
+Name = Positive Test for sscanf_s
TYPE = DEFAULT
EXE1 = test15
Description
-= Tests sprintf with exponential format doubles (uppercase)
+= Tests sscanf_s with floats (exponential notation, uppercase)
**
** Source: test16.c
**
-** Purpose:Tests sscanf with floats (compact notation, lowercase)
+** Purpose:Tests sscanf_s with floats (compact notation, lowercase)
**
**
**==========================================================================*/
#include <palsuite.h>
-#include "../sscanf.h"
+#include "../sscanf_s.h"
int __cdecl main(int argc, char *argv[])
{
Version = 1.0
Section = C Runtime
-Function = sscanf
-Name = Positive Test for sscanf
+Function = sscanf_s
+Name = Positive Test for sscanf_s
TYPE = DEFAULT
EXE1 = test16
Description
-= Tests sscanf with floats (compact notation, lowercase)
+= Tests sscanf_s with floats (compact notation, lowercase)
**
** Source: test17.c
**
-** Purpose: Tests sscanf with floats (compact notation, uppercase)
+** Purpose: Tests sscanf_s with floats (compact notation, uppercase)
**
**
**==========================================================================*/
#include <palsuite.h>
-#include "../sscanf.h"
+#include "../sscanf_s.h"
int __cdecl main(int argc, char *argv[])
{
Version = 1.0
Section = C Runtime
-Function = sprintf
-Name = Positive Test for sprintf
+Function = sscanf_s
+Name = Positive Test for sscanf_s
TYPE = DEFAULT
EXE1 = test17
Description
-= Tests sprintf with compact format doubles (lowercase)
+= Tests sscanf_s with floats (compact notation, uppercase)
**
** Source: test2.c
**
-** Purpose: Test to see if sscanf handles whitespace correctly
+** Purpose: Test to see if sscanf_s handles whitespace correctly
**
**
**==========================================================================*/
#include <palsuite.h>
-#include "../sscanf.h"
+#include "../sscanf_s.h"
/*
Version = 1.0
Section = C Runtime
-Function = sscanf
-Name = Positive Test for sscanf
+Function = sscanf_s
+Name = Positive Test for sscanf_s
TYPE = DEFAULT
EXE1 = test2
Description
-= Test to see if sscanf handles whitespace correctly
+= Test to see if sscanf_s handles whitespace correctly
**
** Source: test3.c
**
-** Purpose: Tests sscanf with bracketed set strings
+** Purpose: Tests sscanf_s with bracketed set strings
**
**
**==========================================================================*/
#include <palsuite.h>
-#include "../sscanf.h"
+#include "../sscanf_s.h"
int __cdecl main(int argc, char *argv[])
{
Version = 1.0
Section = C Runtime
-Function = sprintf
-Name = Positive Test for sprintf
+Function = sscanf_s
+Name = Positive Test for sscanf_s
TYPE = DEFAULT
EXE1 = test3
Description
-= Tests sprintf with wide strings
+= Tests sscanf_s with bracketed set strings
**
** Source: test4.c
**
-** Purpose: Tests sscanf with decimal numbers
+** Purpose: Tests sscanf_s with decimal numbers
**
**
**==========================================================================*/
#include <palsuite.h>
-#include "../sscanf.h"
+#include "../sscanf_s.h"
int __cdecl main(int argc, char *argv[])
Version = 1.0
Section = C Runtime
-Function = sprintf
-Name = Positive Test for sprintf
+Function = sscanf_s
+Name = Positive Test for sscanf_s
TYPE = DEFAULT
EXE1 = test4
Description
-= Tests sprintf with pointers
+= Tests sscanf_s with decimal numbers
**
** Source: test5.c
**
-** Purpose: Tests sscanf with integer numbers
+** Purpose: Tests sscanf_s with integer numbers
**
**
**==========================================================================*/
#include <palsuite.h>
-#include "../sscanf.h"
+#include "../sscanf_s.h"
int __cdecl main(int argc, char *argv[])
{
Version = 1.0
Section = C Runtime
-Function = sscanf
-Name = Positive Test for sscanf
+Function = sscanf_s
+Name = Positive Test for sscanf_s
TYPE = DEFAULT
EXE1 = test5
Description
-= Tests sscanf with integer numbers
+= Tests sscanf_s with integer numbers
**
** Source: test6.c
**
-** Purpose: Tests sscanf with octal numbers
+** Purpose: Tests sscanf_s with octal numbers
**
**
**==========================================================================*/
#include <palsuite.h>
-#include "../sscanf.h"
+#include "../sscanf_s.h"
int __cdecl main(int argc, char *argv[])
{
Version = 1.0
Section = C Runtime
-Function = sscanf
-Name = Positive Test for sscanf
+Function = sscanf_s
+Name = Positive Test for sscanf_s
TYPE = DEFAULT
EXE1 = test6
Description
-= Tests sscanf with octal numbers
+= Tests sscanf_s with octal numbers
**
** Source: test7.c
**
-** Purpose: Tests sscanf with hex numbers (lowercase)
+** Purpose: Tests sscanf_s with hex numbers (lowercase)
**
**
**==========================================================================*/
#include <palsuite.h>
-#include "../sscanf.h"
+#include "../sscanf_s.h"
int __cdecl main(int argc, char *argv[])
{
Version = 1.0
Section = C Runtime
-Function = sscanf
-Name = Positive Test for sscanf
+Function = sscanf_s
+Name = Positive Test for sscanf_s
TYPE = DEFAULT
EXE1 = test7
Description
-= Tests sscanf with hex numbers (lowercase)
+= Tests sscanf_s with hex numbers (lowercase)
**
** Source: test8.c
**
-** Purpose:Tests sscanf with unsigned number
+** Purpose:Tests sscanf_s with unsigned number
**
**
**==========================================================================*/
#include <palsuite.h>
-#include "../sscanf.h"
+#include "../sscanf_s.h"
int __cdecl main(int argc, char *argv[])
{
Version = 1.0
Section = C Runtime
-Function = sprintf
-Name = Positive Test for sprintf
+Function = sscanf_s
+Name = Positive Test for sscanf_s
TYPE = DEFAULT
EXE1 = test8
Description
-= Tests sprintf with decimal numbers
+= Tests sscanf_s with unsigned numbers
**
** Source: test9.c
**
-** Purpose: Tests sscanf with characters
+** Purpose: Tests sscanf_s with characters
**
**
**==========================================================================*/
#include <palsuite.h>
-#include "../sscanf.h"
+#include "../sscanf_s.h"
int __cdecl main(int argc, char *argv[])
Version = 1.0
Section =C Runtime
-Function = sscanf
-Name = Positive Test for sscanf
+Function = sscanf_s
+Name = Positive Test for sscanf_s
TYPE = DEFAULT
EXE1 = test9
Description
-= Tests sscanf with characters
+= Tests sscanf_s with characters
if (checknum != num)
{
- sprintf(buf, "%I64d", num);
- sprintf(check, "%I64d", checknum);
+ sprintf_s(buf, _countof(buf), "%I64d", num);
+ sprintf_s(check, _countof(check), "%I64d", checknum);
Fail("ERROR: scanned I64 number incorrectly from \"%s\" using \"%s\".\n"
"Expected %s, got %s.\n", convertC(inputstr),
convertC(formatstr), check, buf);
#include <palsuite.h>
/*
- * Notes: uses memcmp and the (pal) sprintf
+ * Notes: uses memcmp and the (pal) sprintf_s
*/
int __cdecl main(int argc, char *argv[])
if (memcmp(dest, test, sizeof(test)) != 0)
{
- sprintf(buffer, "%S", dest);
+ sprintf_s(buffer, _countof(buffer), "%S", dest);
Fail("ERROR: Expected wcscat to give \"%s\", got \"%s\"\n",
"foo bar baz", buffer);
}
#include <palsuite.h>
/*
- * Notes: uses memcmp and sprintf.
+ * Notes: uses memcmp and sprintf_s.
*/
int __cdecl main(int argc, char *argv[])
if (ret != dest || memcmp(dest, result, sizeof(result)) != 0)
{
- sprintf(buffer, "%S", dest);
+ sprintf_s(buffer, _countof(buffer), "%S", dest);
Fail("Expected wcscpy to give \"%s\" with a return value of %p, got \"%s\" "
"with a return value of %p.\n", "foo", dest, buffer, ret);
}
#define th_htons(w) (((w) >> 8) | ((w) << 8))
#endif // BIGENDIAN
-
+#define _countof(_array) (sizeof(_array)/sizeof(_array[0]))
WCHAR* convert(const char * aString)
{
ResetEvent(hEvFromHelper);
ResetEvent(hEvToHelper);
- if (!sprintf(cmdComposeBuf, "helper %s", commsFileName))
+ if (!sprintf_s(cmdComposeBuf, _countof(cmdComposeBuf), "helper %s", commsFileName))
{
Fail("Could not convert command line\n");
}
"(already exists!)\n", szcFromHelperEvName);
}
- if (!sprintf(cmdComposeBuf, "helper %s", commsFileName))
+ if (!sprintf_s(cmdComposeBuf, _countof(cmdComposeBuf), "helper %s", commsFileName))
{
Fail("Could not convert command line\n");
}
/* directories with dots */
memset(szDirName, 0, buf_size);
- sprintf(szDirName, szDotDir);
+ sprintf_s(szDirName, _countof(szDirName), szDotDir);
bRc = CreateDirectoryA(szDirName, NULL);
if (bRc == FALSE)
{
/* directories with dots */
memset(szDirName, 0, 252);
- sprintf(szDirName, ".dotDirectory");
+ sprintf_s(szDirName, _countof(szDirName), ".dotDirectory");
pTemp = convert(szDirName);
bRc = CreateDirectoryW(pTemp, NULL);
if (bRc == FALSE)
// loop through all accesses, modes, dispositions and flags
for (i=0; i<4*8*4*5; ++i) {
- sprintf(FileName, "test%03d.txt", i);
+ sprintf_s(FileName, _countof(FileName), "test%03d.txt", i);
if (DeleteFileA(FileName) == FALSE) {
if (GetLastError() != ERROR_FILE_NOT_FOUND) {
bRet = FALSE;
// creation disp loop
for (l = 0; l < 5; l++)
{
- sprintf(lpFileName, "test%03d.txt", nCounter);
+ sprintf_s(lpFileName, _countof(lpFileName), "test%03d.txt", nCounter);
hFile = CreateFile(lpFileName,
dwDesiredAccess[i],
dwShareMode[j],
// loop through all accesses, modes, dispositions and flags
for (i=0; i<4*8*4*5; ++i) {
- sprintf(FileName, "test%03d.txt", i);
+ sprintf_s(FileName, _countof(FileName), "test%03d.txt", i);
if (DeleteFileA(FileName) == FALSE) {
if (GetLastError() != ERROR_FILE_NOT_FOUND) {
bRet = FALSE;
// creation disp loop
for (l = 0; l < 5; l++)
{
- sprintf(string, "test%03d.txt", nCounter);
+ sprintf_s(string, _countof(string), "test%03d.txt", nCounter);
lpFileName = convert(string);
hFile = CreateFileW(lpFileName,
dwDesiredAccess[i],
}
/* now verify that it only used the first 3 characters of the prefix */
- sprintf(szTempString, "%s\\%s", szDot, szLongValidPrefix);
+ sprintf_s(szTempString, _countof(szTempString), "%s\\%s", szDot, szLongValidPrefix);
if (strncmp(szTempString, szReturnedName, 6) == 0)
{
Fail("GetTempFileNameA: ERROR -> It appears that an improper prefix "
}
memset(szBuffer, 0, 100);
- sprintf(szBuffer, "%s/test01.txt", lpSource[2]);
+ sprintf_s(szBuffer, _countof(szBuffer), "%s/test01.txt", lpSource[2]);
tempFile = fopen(szBuffer, "w");
if (tempFile != NULL)
{
}
memset(szBuffer, 0, 100);
- sprintf(szBuffer, "%s/test02.txt", lpSource[2]);
+ sprintf_s(szBuffer, _countof(szBuffer), "%s/test02.txt", lpSource[2]);
tempFile = fopen(szBuffer, "w");
if (tempFile != NULL)
{
dwAtt = GetFileAttributesA(lpSource[2]);
if (( dwAtt != INVALID_FILE_ATTRIBUTES ) && ( dwAtt & FILE_ATTRIBUTE_DIRECTORY) )
{
- sprintf(szTemp, "%s/test01.txt", lpSource[2]);
+ sprintf_s(szTemp, _countof(szTemp), "%s/test01.txt", lpSource[2]);
removeFileHelper(szTemp, 18);
- sprintf(szTemp, "%s/test02.txt", lpSource[2]);
+ sprintf_s(szTemp, _countof(szTemp), "%s/test02.txt", lpSource[2]);
removeFileHelper(szTemp, 19);
removeDirectoryHelper(lpSource[2], 103);
}
dwAtt = GetFileAttributesA(lpSource[3]);
if (( dwAtt != INVALID_FILE_ATTRIBUTES ) && ( dwAtt & FILE_ATTRIBUTE_DIRECTORY) )
{
- sprintf(szTemp, "%s/test01.txt", lpSource[3]);
+ sprintf_s(szTemp, _countof(szTemp), "%s/test01.txt", lpSource[3]);
removeFileHelper(szTemp, 18);
- sprintf(szTemp, "%s/test02.txt", lpSource[3]);
+ sprintf_s(szTemp, _countof(szTemp), "%s/test02.txt", lpSource[3]);
removeFileHelper(szTemp, 19);
removeDirectoryHelper(lpSource[3], 103);
}
dwAtt = GetFileAttributesA(lpDestination[0]);
if (( dwAtt != INVALID_FILE_ATTRIBUTES ) && ( dwAtt & FILE_ATTRIBUTE_DIRECTORY) )
{
- sprintf(szTemp, "%s/test01.txt", lpDestination[0]);
+ sprintf_s(szTemp, _countof(szTemp), "%s/test01.txt", lpDestination[0]);
removeFileHelper(szTemp, 18);
- sprintf(szTemp, "%s/test02.txt", lpDestination[0]);
+ sprintf_s(szTemp, _countof(szTemp), "%s/test02.txt", lpDestination[0]);
removeFileHelper(szTemp, 19);
removeDirectoryHelper(lpDestination[0], 103);
}
dwAtt = GetFileAttributesA(lpDestination[1]);
if (( dwAtt != INVALID_FILE_ATTRIBUTES ) && ( dwAtt & FILE_ATTRIBUTE_DIRECTORY) )
{
- sprintf(szTemp, "%s/test01.txt", lpDestination[1]);
+ sprintf_s(szTemp, _countof(szTemp), "%s/test01.txt", lpDestination[1]);
removeFileHelper(szTemp, 18);
- sprintf(szTemp, "%s/test02.txt", lpDestination[1]);
+ sprintf_s(szTemp, _countof(szTemp), "%s/test02.txt", lpDestination[1]);
removeFileHelper(szTemp, 19);
removeDirectoryHelper(lpDestination[1], 103);
}
dwAtt = GetFileAttributesA(lpDestination[2]);
if (( dwAtt != INVALID_FILE_ATTRIBUTES ) && ( dwAtt & FILE_ATTRIBUTE_DIRECTORY) )
{
- sprintf(szTemp, "%s/test01.txt", lpDestination[2]);
+ sprintf_s(szTemp, _countof(szTemp), "%s/test01.txt", lpDestination[2]);
removeFileHelper(szTemp, 18);
- sprintf(szTemp, "%s/test02.txt", lpDestination[2]);
+ sprintf_s(szTemp, _countof(szTemp), "%s/test02.txt", lpDestination[2]);
removeFileHelper(szTemp, 19);
removeDirectoryHelper(lpDestination[2], 103);
}
dwAtt = GetFileAttributesA(lpDestination[3]);
if (( dwAtt != INVALID_FILE_ATTRIBUTES ) && ( dwAtt & FILE_ATTRIBUTE_DIRECTORY) )
{
- sprintf(szTemp, "%s/test01.txt", lpDestination[3]);
+ sprintf_s(szTemp, _countof(szTemp), "%s/test01.txt", lpDestination[3]);
removeFileHelper(szTemp, 18);
- sprintf(szTemp, "%s/test02.txt", lpDestination[3]);
+ sprintf_s(szTemp, _countof(szTemp), "%s/test02.txt", lpDestination[3]);
removeFileHelper(szTemp, 19);
removeDirectoryHelper(lpDestination[3], 103);
}
}
memset(szBuffer, 0, 100);
- sprintf(szBuffer, "%s/test01.txt", lpSource[2]);
+ sprintf_s(szBuffer, _countof(szBuffer), "%s/test01.txt", lpSource[2]);
tempFile = fopen(szBuffer, "w");
if (tempFile != NULL)
{
}
memset(szBuffer, 0, 100);
- sprintf(szBuffer, "%s/test02.txt", lpSource[2]);
+ sprintf_s(szBuffer, _countof(szBuffer), "%s/test02.txt", lpSource[2]);
tempFile = fopen(szBuffer, "w");
if (tempFile != NULL)
{
dwAtt = GetFileAttributesA(lpSource[2]);
if (( dwAtt != INVALID_FILE_ATTRIBUTES ) && ( dwAtt & FILE_ATTRIBUTE_DIRECTORY) )
{
- sprintf(szTemp, "%s/test01.txt", lpSource[2]);
+ sprintf_s(szTemp, _countof(szTemp), "%s/test01.txt", lpSource[2]);
removeFileHelper(szTemp, 18);
- sprintf(szTemp, "%s/test02.txt", lpSource[2]);
+ sprintf_s(szTemp, _countof(szTemp), "%s/test02.txt", lpSource[2]);
removeFileHelper(szTemp, 19);
removeDirectoryHelper(lpSource[2], 103);
}
dwAtt = GetFileAttributesA(lpSource[3]);
if (( dwAtt != INVALID_FILE_ATTRIBUTES ) && ( dwAtt & FILE_ATTRIBUTE_DIRECTORY) )
{
- sprintf(szTemp, "%s/test01.txt", lpSource[3]);
+ sprintf_s(szTemp, _countof(szTemp), "%s/test01.txt", lpSource[3]);
removeFileHelper(szTemp, 18);
- sprintf(szTemp, "%s/test02.txt", lpSource[3]);
+ sprintf_s(szTemp, _countof(szTemp), "%s/test02.txt", lpSource[3]);
removeFileHelper(szTemp, 19);
removeDirectoryHelper(lpSource[3], 103);
}
dwAtt = GetFileAttributesA(lpDestination[0]);
if (( dwAtt != INVALID_FILE_ATTRIBUTES ) && ( dwAtt & FILE_ATTRIBUTE_DIRECTORY) )
{
- sprintf(szTemp, "%s/test01.txt", lpDestination[0]);
+ sprintf_s(szTemp, _countof(szTemp), "%s/test01.txt", lpDestination[0]);
removeFileHelper(szTemp, 18);
- sprintf(szTemp, "%s/test02.txt", lpDestination[0]);
+ sprintf_s(szTemp, _countof(szTemp), "%s/test02.txt", lpDestination[0]);
removeFileHelper(szTemp, 19);
removeDirectoryHelper(lpDestination[0], 103);
}
dwAtt = GetFileAttributesA(lpDestination[1]);
if (( dwAtt != INVALID_FILE_ATTRIBUTES ) && ( dwAtt & FILE_ATTRIBUTE_DIRECTORY) )
{
- sprintf(szTemp, "%s/test01.txt", lpDestination[1]);
+ sprintf_s(szTemp, _countof(szTemp), "%s/test01.txt", lpDestination[1]);
removeFileHelper(szTemp, 18);
- sprintf(szTemp, "%s/test02.txt", lpDestination[1]);
+ sprintf_s(szTemp, _countof(szTemp), "%s/test02.txt", lpDestination[1]);
removeFileHelper(szTemp, 19);
removeDirectoryHelper(lpDestination[1], 103);
}
dwAtt = GetFileAttributesA(lpDestination[2]);
if (( dwAtt != INVALID_FILE_ATTRIBUTES ) && ( dwAtt & FILE_ATTRIBUTE_DIRECTORY) )
{
- sprintf(szTemp, "%s/test01.txt", lpDestination[2]);
+ sprintf_s(szTemp, _countof(szTemp), "%s/test01.txt", lpDestination[2]);
removeFileHelper(szTemp, 18);
- sprintf(szTemp, "%s/test02.txt", lpDestination[2]);
+ sprintf_s(szTemp, _countof(szTemp), "%s/test02.txt", lpDestination[2]);
removeFileHelper(szTemp, 19);
removeDirectoryHelper(lpDestination[2], 103);
}
dwAtt = GetFileAttributesA(lpDestination[3]);
if (( dwAtt != INVALID_FILE_ATTRIBUTES ) && ( dwAtt & FILE_ATTRIBUTE_DIRECTORY) )
{
- sprintf(szTemp, "%s/test01.txt", lpDestination[3]);
+ sprintf_s(szTemp, _countof(szTemp), "%s/test01.txt", lpDestination[3]);
removeFileHelper(szTemp, 18);
- sprintf(szTemp, "%s/test02.txt", lpDestination[3]);
+ sprintf_s(szTemp, _countof(szTemp), "%s/test02.txt", lpDestination[3]);
removeFileHelper(szTemp, 19);
removeDirectoryHelper(lpDestination[3], 103);
}
* remove a directory that does not exist
*/
szTemp = (char *) malloc (sizeof("test_directory"));
- sprintf(szTemp, "test_directory");
+ sprintf_s(szTemp, sizeof("test_directory"), "test_directory");
bRc = RemoveDirectoryA(szTemp);
if (bRc != FALSE)
{
}
char *szSymlinkName = (char *) malloc (sizeof("test_directory_symlink"));
- sprintf(szSymlinkName, "test_directory_symlink");
+ sprintf_s(szSymlinkName, sizeof("test_directory_symlink"), "test_directory_symlink");
if (symlink(szTemp, szSymlinkName) != 0)
{
Fail("Error:RemoveDirectoryA: Failed to create a symlink to the directory \"test_directory\".\n");
* directories with dots
*/
memset(szDirName, 0, 252);
- sprintf(szDirName, ".dotDirectory");
+ sprintf_s(szDirName, _countof(szDirName), ".dotDirectory");
szTemp = (char *) malloc (sizeof(szDirName));
szTemp = strncpy(szTemp, szDirName, strlen(szDirName) + 1);
* Try calling RemoveDirectory with a file name
*/
memset(szDirName, 0, 252);
- sprintf(szDirName, "removedirectoryw.c");
+ sprintf_s(szDirName, _countof(szDirName), "removedirectoryw.c");
szTemp = (char *) malloc (sizeof(szDirName));
szTemp = strncpy(szTemp, szDirName, strlen(szDirName) + 1);
}
/* Create non_empty_dir */
- sprintf( szDirName, "non_empty_dir");
+ sprintf_s(szDirName, _countof(szDirName), "non_empty_dir");
szTemp = (char *) malloc (sizeof(szDirName));
szTemp = strncpy(szTemp, szDirName, strlen(szDirName) + 1);
bRc = CreateDirectoryA(szTemp, NULL);
}
/* Create sub_dir */
- sprintf (szDirName, "sub_dir");
+ sprintf_s(szDirName, _countof(szDirName), "sub_dir");
szTemp2 = (char *) malloc (sizeof(szDirName));
szTemp2 = strncpy(szTemp2, szDirName, strlen(szDirName) + 1);
bRc = CreateDirectoryA(szTemp2, NULL);
* directories with dots
*/
memset(szDirName, 0, 252);
- sprintf(szDirName, ".dotDirectory");
+ sprintf_s(szDirName, _countof(szDirName), ".dotDirectory");
szwTemp = convert(szDirName);
bRc = CreateDirectoryW(szwTemp, NULL);
if (bRc == FALSE)
* Try calling RemoveDirectory with a file name
*/
memset(szDirName, 0, 252);
- sprintf(szDirName, "removedirectoryw.c");
+ sprintf_s(szDirName, _countof(szDirName), "removedirectoryw.c");
szwTemp = convert(szDirName);
bRc = RemoveDirectoryW(szwTemp);
}
memset(fileloc, 0, _MAX_PATH);
- sprintf(fileloc, "%s%s", fullPath, szFileNameExistsWithExt);
+ sprintf_s(fileloc, _countof(fileloc), "%s%s", fullPath, szFileNameExistsWithExt);
RemoveAll();
}
memset(fileloc, 0, _MAX_PATH);
- sprintf(fileloc, "%s%s", fullPath, szFileNameExistsWithExt);
+ sprintf_s(fileloc, _countof(fileloc), "%s%s", fullPath, szFileNameExistsWithExt);
RemoveAll();
/* append the temp name to the "home" directory */
memset(szBuiltDir, 0, (_MAX_DIR+1));
#if WIN32
- sprintf(szBuiltDir,"%s%s\\", szHomeDir, szDirName);
+ sprintf_s(szBuiltDir, _countof(szBuiltDir),"%s%s\\", szHomeDir, szDirName);
#else
- sprintf(szBuiltDir,"%s%s/", szHomeDir, szDirName);
+ sprintf_s(szBuiltDir, _countof(szBuiltDir),"%s%s/", szHomeDir, szDirName);
#endif
/* get the new current directory */
/* append the temp name to the "home" directory */
memset(szBuiltDir, 0, (_MAX_DIR+1));
#if WIN32
- sprintf(szBuiltDir,"%s\\..\\", szDirName);
+ sprintf_s(szBuiltDir, _countof(szBuiltDir),"%s\\..\\", szDirName);
#else
- sprintf(szBuiltDir,"%s/../", szDirName);
+ sprintf_s(szBuiltDir, _countof(szBuiltDir),"%s/../", szDirName);
#endif
/* append the temp name to the "home" directory */
memset(szBuiltDir, 0, MAX_PATH);
#if WIN32
- sprintf(szBuiltDir,"%s\\..\\", szDirName);
+ sprintf_s(szBuiltDir, _countof(szBuiltDir),"%s\\..\\", szDirName);
#else
- sprintf(szBuiltDir,"%s/../", szDirName);
+ sprintf_s(szBuiltDir, _countof(szBuiltDir),"%s/../", szDirName);
#endif
szwBuiltDir = convert(szBuiltDir);
}
#if WIN32
- sprintf(executableFileName,"%s","executable.exe");
+ sprintf_s(executableFileName, _countof(executableFileName),"%s","executable.exe");
#else
- sprintf(executableFileName,"%s","executable");
+ sprintf_s(executableFileName, _countof(executableFileName),"%s","executable");
#endif
//conver string to a unicode one
ResetEvent(hEvFromHelper);
ResetEvent(hEvToHelper);
- if (!sprintf(cmdComposeBuf, "helper %s", commsFileName))
+ if (!sprintf_s(cmdComposeBuf, _countof(cmdComposeBuf), "helper %s", commsFileName))
{
Fail("Could not convert command line\n");
}
errno, GetLastError());
}
PEDANTIC1(fclose,(commsFile));
- sscanf(incomingCMDBuffer, LLFORMAT " " LLFORMAT, &pDestMemory, &Count);
+ sscanf_s(incomingCMDBuffer, LLFORMAT " " LLFORMAT, &pDestMemory, &Count);
if (argc > 1)
{
Trace("Preparing to write to " LLFORMAT " bytes @ " LLFORMAT "('%s')\n",
/*Module name without extension but with a trailing dot*/
#if WIN32
- sprintf(ModuleName, "%s", "rotor_pal.");
+ sprintf_s(ModuleName, _countof(ModuleName), "%s", "rotor_pal.");
#else
/* Under FreeBSD */
- sprintf(ModuleName, "%s", "librotor_pal.");
+ sprintf_s(ModuleName, _countof(ModuleName), "%s", "librotor_pal.");
#endif
/* load a module which does not have the file extension,
/*Module name without extension but with a trailing dot*/
#if WIN32
- sprintf(ModuleName,"%s","rotor_pal.");
+ sprintf_s(ModuleName, _countof(ModuleName),"%s","rotor_pal.");
#else
- sprintf(ModuleName,"%s","librotor_pal.");
+ sprintf_s(ModuleName, _countof(ModuleName),"%s","librotor_pal.");
#endif
/* convert a normal string to a wide one */
/*zero the buffer*/
memset(ModuleName,0,64);
- sprintf(ModuleName, "%s", "rotor_pal");
+ sprintf_s(ModuleName, _countof(ModuleName), "%s", "rotor_pal");
/*convert a normal string to a wide one*/
wpModuleName = convert(ModuleName);
}
memset(ModuleName, 0, 64);
- sprintf(ModuleName, "%s", "not_exist_module_name");
+ sprintf_s(ModuleName, _countof(ModuleName), "%s", "not_exist_module_name");
/*convert a normal string to a wide one*/
wpModuleName = convert(ModuleName);
c_runtime/sinf/test1/paltest_sinf_test1
c_runtime/sinh/test1/paltest_sinh_test1
c_runtime/sinhf/test1/paltest_sinhf_test1
-c_runtime/sprintf/test1/paltest_sprintf_test1
-c_runtime/sprintf/test10/paltest_sprintf_test10
-c_runtime/sprintf/test11/paltest_sprintf_test11
-c_runtime/sprintf/test12/paltest_sprintf_test12
-c_runtime/sprintf/test13/paltest_sprintf_test13
-c_runtime/sprintf/test14/paltest_sprintf_test14
-c_runtime/sprintf/test15/paltest_sprintf_test15
-c_runtime/sprintf/test16/paltest_sprintf_test16
-c_runtime/sprintf/test17/paltest_sprintf_test17
-c_runtime/sprintf/test18/paltest_sprintf_test18
-c_runtime/sprintf/test19/paltest_sprintf_test19
-c_runtime/sprintf/test2/paltest_sprintf_test2
-c_runtime/sprintf/test3/paltest_sprintf_test3
-c_runtime/sprintf/test4/paltest_sprintf_test4
-c_runtime/sprintf/test5/paltest_sprintf_test5
-c_runtime/sprintf/test6/paltest_sprintf_test6
-c_runtime/sprintf/test7/paltest_sprintf_test7
-c_runtime/sprintf/test8/paltest_sprintf_test8
-c_runtime/sprintf/test9/paltest_sprintf_test9
+c_runtime/sprintf_s/test1/paltest_sprintf_test1
+c_runtime/sprintf_s/test10/paltest_sprintf_test10
+c_runtime/sprintf_s/test11/paltest_sprintf_test11
+c_runtime/sprintf_s/test12/paltest_sprintf_test12
+c_runtime/sprintf_s/test13/paltest_sprintf_test13
+c_runtime/sprintf_s/test14/paltest_sprintf_test14
+c_runtime/sprintf_s/test15/paltest_sprintf_test15
+c_runtime/sprintf_s/test16/paltest_sprintf_test16
+c_runtime/sprintf_s/test17/paltest_sprintf_test17
+c_runtime/sprintf_s/test18/paltest_sprintf_test18
+c_runtime/sprintf_s/test19/paltest_sprintf_test19
+c_runtime/sprintf_s/test2/paltest_sprintf_test2
+c_runtime/sprintf_s/test3/paltest_sprintf_test3
+c_runtime/sprintf_s/test4/paltest_sprintf_test4
+c_runtime/sprintf_s/test6/paltest_sprintf_test6
+c_runtime/sprintf_s/test7/paltest_sprintf_test7
+c_runtime/sprintf_s/test8/paltest_sprintf_test8
+c_runtime/sprintf_s/test9/paltest_sprintf_test9
c_runtime/sqrt/test1/paltest_sqrt_test1
c_runtime/sqrtf/test1/paltest_sqrtf_test1
-c_runtime/sscanf/test1/paltest_sscanf_test1
-c_runtime/sscanf/test10/paltest_sscanf_test10
-c_runtime/sscanf/test11/paltest_sscanf_test11
-c_runtime/sscanf/test12/paltest_sscanf_test12
-c_runtime/sscanf/test13/paltest_sscanf_test13
-c_runtime/sscanf/test14/paltest_sscanf_test14
-c_runtime/sscanf/test15/paltest_sscanf_test15
-c_runtime/sscanf/test16/paltest_sscanf_test16
-c_runtime/sscanf/test17/paltest_sscanf_test17
-c_runtime/sscanf/test2/paltest_sscanf_test2
-c_runtime/sscanf/test3/paltest_sscanf_test3
-c_runtime/sscanf/test4/paltest_sscanf_test4
-c_runtime/sscanf/test5/paltest_sscanf_test5
-c_runtime/sscanf/test6/paltest_sscanf_test6
-c_runtime/sscanf/test7/paltest_sscanf_test7
-c_runtime/sscanf/test8/paltest_sscanf_test8
-c_runtime/sscanf/test9/paltest_sscanf_test9
+c_runtime/sscanf_s/test1/paltest_sscanf_test1
+c_runtime/sscanf_s/test10/paltest_sscanf_test10
+c_runtime/sscanf_s/test11/paltest_sscanf_test11
+c_runtime/sscanf_s/test12/paltest_sscanf_test12
+c_runtime/sscanf_s/test13/paltest_sscanf_test13
+c_runtime/sscanf_s/test14/paltest_sscanf_test14
+c_runtime/sscanf_s/test15/paltest_sscanf_test15
+c_runtime/sscanf_s/test16/paltest_sscanf_test16
+c_runtime/sscanf_s/test17/paltest_sscanf_test17
+c_runtime/sscanf_s/test2/paltest_sscanf_test2
+c_runtime/sscanf_s/test3/paltest_sscanf_test3
+c_runtime/sscanf_s/test4/paltest_sscanf_test4
+c_runtime/sscanf_s/test5/paltest_sscanf_test5
+c_runtime/sscanf_s/test6/paltest_sscanf_test6
+c_runtime/sscanf_s/test7/paltest_sscanf_test7
+c_runtime/sscanf_s/test8/paltest_sscanf_test8
+c_runtime/sscanf_s/test9/paltest_sscanf_test9
c_runtime/strcat/test1/paltest_strcat_test1
c_runtime/strchr/test1/paltest_strchr_test1
c_runtime/strcmp/test1/paltest_strcmp_test1
c_runtime/sinf/test1,1
c_runtime/sinh/test1,1
c_runtime/sinhf/test1,1
-c_runtime/sprintf/test1,1
-c_runtime/sprintf/test2,1
-c_runtime/sprintf/test3,1
-c_runtime/sprintf/test4,1
-c_runtime/sprintf/test5,1
-c_runtime/sprintf/test6,1
-c_runtime/sprintf/test7,1
-c_runtime/sprintf/test8,1
-c_runtime/sprintf/test9,1
-c_runtime/sprintf/test10,1
-c_runtime/sprintf/test11,1
-c_runtime/sprintf/test12,1
-c_runtime/sprintf/test13,1
-c_runtime/sprintf/test14,1
-c_runtime/sprintf/test15,1
-c_runtime/sprintf/test16,1
-c_runtime/sprintf/test17,1
-c_runtime/sprintf/test18,1
-c_runtime/sprintf/test19,1
+c_runtime/sprintf_s/test1,1
+c_runtime/sprintf_s/test2,1
+c_runtime/sprintf_s/test3,1
+c_runtime/sprintf_s/test4,1
+c_runtime/sprintf_s/test6,1
+c_runtime/sprintf_s/test7,1
+c_runtime/sprintf_s/test8,1
+c_runtime/sprintf_s/test9,1
+c_runtime/sprintf_s/test10,1
+c_runtime/sprintf_s/test11,1
+c_runtime/sprintf_s/test12,1
+c_runtime/sprintf_s/test13,1
+c_runtime/sprintf_s/test14,1
+c_runtime/sprintf_s/test15,1
+c_runtime/sprintf_s/test16,1
+c_runtime/sprintf_s/test17,1
+c_runtime/sprintf_s/test18,1
+c_runtime/sprintf_s/test19,1
c_runtime/sqrt/test1,1
c_runtime/sqrtf/test1,1
-c_runtime/sscanf/test1,1
-c_runtime/sscanf/test2,1
-c_runtime/sscanf/test3,1
-c_runtime/sscanf/test4,1
-c_runtime/sscanf/test5,1
-c_runtime/sscanf/test6,1
-c_runtime/sscanf/test7,1
-c_runtime/sscanf/test8,1
-c_runtime/sscanf/test9,1
-c_runtime/sscanf/test10,1
-c_runtime/sscanf/test11,1
-c_runtime/sscanf/test12,1
-c_runtime/sscanf/test13,1
-c_runtime/sscanf/test14,1
-c_runtime/sscanf/test15,1
-c_runtime/sscanf/test16,1
-c_runtime/sscanf/test17,1
+c_runtime/sscanf_s/test1,1
+c_runtime/sscanf_s/test2,1
+c_runtime/sscanf_s/test3,1
+c_runtime/sscanf_s/test4,1
+c_runtime/sscanf_s/test5,1
+c_runtime/sscanf_s/test6,1
+c_runtime/sscanf_s/test7,1
+c_runtime/sscanf_s/test8,1
+c_runtime/sscanf_s/test9,1
+c_runtime/sscanf_s/test10,1
+c_runtime/sscanf_s/test11,1
+c_runtime/sscanf_s/test12,1
+c_runtime/sscanf_s/test13,1
+c_runtime/sscanf_s/test14,1
+c_runtime/sscanf_s/test15,1
+c_runtime/sscanf_s/test16,1
+c_runtime/sscanf_s/test17,1
c_runtime/strcat/test1,1
c_runtime/strchr/test1,1
c_runtime/strcmp/test1,1
W(" /in <file> - Specifies input filename (optional)\n")
W(" /out <file> - Specifies output filename (optional)\n")
#ifdef FEATURE_CORECLR
- W(" /Trusted_Platform_Assemblies <path[;path]>\n")
+ W(" /Trusted_Platform_Assemblies <path[") PATH_SEPARATOR_STR_W W("path]>\n")
W(" - List of assemblies treated as trusted platform\n")
W(" - Cannot be used with Platform_Assemblies_Paths\n")
- W(" /Platform_Resource_Roots <path[;path]>\n")
+ W(" /Platform_Resource_Roots <path[") PATH_SEPARATOR_STR_W W("path]>\n")
W(" - List of paths containing localized assembly directories\n")
- W(" /App_Paths <path> - List of paths containing user-application assemblies and resources\n")
+ W(" /App_Paths <path[") PATH_SEPARATOR_STR_W W("path]>\n")
+ W(" - List of paths containing user-application assemblies and resources\n")
#ifndef NO_NGENPDB
- W(" /App_Ni_Paths <path[;path]>\n")
+ W(" /App_Ni_Paths <path[") PATH_SEPARATOR_STR_W W("path]>\n")
W(" - List of paths containing user-application native images\n")
W(" - Must be used with /CreatePDB switch\n")
#endif // NO_NGENPDB
#endif // FEATURE_CORECLR
- W(" /Platform_Assemblies_Paths\n")
+ W(" /Platform_Assemblies_Paths <path[") PATH_SEPARATOR_STR_W W("path]>\n")
W(" - List of paths containing target platform assemblies\n")
#ifdef FEATURE_CORECLR
// If Platform_Assemblies_Paths, we will use it to build the TPA list and thus,
#endif // FEATURE_CORECLR
#ifdef FEATURE_COMINTEROP
- W(" /Platform_Winmd_Paths\n")
+ W(" /Platform_Winmd_Paths <path[") PATH_SEPARATOR_STR_W W("path]>\n")
W(" - List of paths containing target platform WinMDs used\n")
W(" for emulating RoResolveNamespace\n")
#endif
W(" scenario traces, which can be used with ibcmerge.exe\n")
#endif
#if defined(FEATURE_CORECLR) && !defined(FEATURE_MERGE_JIT_AND_ENGINE)
- W(" /JITPath\n")
+ W(" /JITPath <path>\n")
W(" - Specifies the absolute file path to JIT compiler to be used.\n")
#endif // defined(FEATURE_CORECLR) && !defined(FEATURE_MERGE_JIT_AND_ENGINE)
#ifdef FEATURE_READYTORUN_COMPILER
set(VM_SOURCES_WKS_ARCH_ASM
${ARCH_SOURCES_DIR}/asmhelpers.S
${ARCH_SOURCES_DIR}/gmsasm.S
+ ${ARCH_SOURCES_DIR}/umthunkstub.S
)
elseif(CLR_CMAKE_TARGET_ARCH_ARM)
set(VM_SOURCES_WKS_ARCH_ASM
if (takeSnapShot)
{
char buffer[1024];
- sprintf(buffer, "vadump -p %d -o > vadump.%d", GetCurrentProcessId(), unloadCount);
+ sprintf_s(buffer, _countof(buffer), "vadump -p %d -o > vadump.%d", GetCurrentProcessId(), unloadCount);
system(buffer);
- sprintf(buffer, "umdh -p:%d -d -i:1 -f:umdh.%d", GetCurrentProcessId(), unloadCount);
+ sprintf_s(buffer, _countof(buffer), "umdh -p:%d -d -i:1 -f:umdh.%d", GetCurrentProcessId(), unloadCount);
system(buffer);
int takeDHSnapShot = CLRConfig::GetConfigValue(CLRConfig::INTERNAL_ADTakeDHSnapShot);
if (takeDHSnapShot)
{
- sprintf(buffer, "dh -p %d -s -g -h -b -f dh.%d", GetCurrentProcessId(), unloadCount);
+ sprintf_s(buffer, _countof(buffer), "dh -p %d -s -g -h -b -f dh.%d", GetCurrentProcessId(), unloadCount);
system(buffer);
}
}
#if (defined(_TARGET_X86_) || defined(_TARGET_AMD64_)) && !defined(CROSSGEN_COMPILE)
extern "C" DWORD __stdcall getcpuid(DWORD arg, unsigned char result[16]);
+extern "C" DWORD __stdcall xmmYmmStateSupport();
#endif
inline bool TargetHasAVXSupport()
}
#if defined(_TARGET_X86_) || defined(_TARGET_AMD64_)
-extern "C" DWORD __stdcall getcpuid(DWORD arg, unsigned char result[16]);
-extern "C" DWORD __stdcall xmmYmmStateSupport();
bool DoesOSSupportAVX()
{
// Get UMEntryThunk from appdomain thunkcache cache.
UMEntryThunk *pUMEntryThunk = GetAppDomain()->GetUMEntryThunkCache()->GetUMEntryThunk(pMD);
-#ifdef _TARGET_X86_
+#if defined(_TARGET_X86_) && !defined(FEATURE_STUBS_AS_IL)
// System.Runtime.InteropServices.NativeCallableAttribute
BYTE* pData = NULL;
pUMThunkMarshalInfo->SetCallingConvention(callConv);
}
}
-#endif //_TARGET_X86_
+#endif //_TARGET_X86_ && !FEATURE_STUBS_AS_IL
pCode = (PCODE)pUMEntryThunk->GetCode();
_ASSERTE(pCode != NULL);
}
FCIMPLEND
+FCIMPL2(VOID, DependentHandle::nSetPrimary, OBJECTHANDLE handle, Object *_primary)
+{
+ FCALL_CONTRACT;
+
+ _ASSERTE(handle != NULL);
+
+ OBJECTREF primary(_primary);
+ StoreObjectInHandle(handle, primary);
+}
+FCIMPLEND
+
+FCIMPL2(VOID, DependentHandle::nSetSecondary, OBJECTHANDLE handle, Object *_secondary)
+{
+ FCALL_CONTRACT;
+
+ _ASSERTE(handle != NULL);
+
+ OBJECTREF secondary(_secondary);
+ SetDependentHandleSecondary(handle, secondary);
+}
+FCIMPLEND
static FCDECL2(VOID, nGetPrimary, OBJECTHANDLE handle, Object **outPrimary);
static FCDECL3(VOID, nGetPrimaryAndSecondary, OBJECTHANDLE handle, Object **outPrimary, Object **outSecondary);
static FCDECL1(VOID, nFree, OBJECTHANDLE handle);
+ static FCDECL2(VOID, nSetPrimary, OBJECTHANDLE handle, Object *primary);
+ static FCDECL2(VOID, nSetSecondary, OBJECTHANDLE handle, Object *secondary);
};
#endif
StackScratchBuffer buffer;
thArg.GetName(candidateInstName);
char output[1024];
- sprintf(output, "Generics TypeDependencyAttribute processing: Couldn't satisfy a constraint. Class with Attribute: %s Bad candidate instantiated type: %s\r\n", pMT->GetDebugClassName(), candidateInstName.GetANSI(buffer));
+ _snprintf_s(output, _countof(output), _TRUNCATE, "Generics TypeDependencyAttribute processing: Couldn't satisfy a constraint. Class with Attribute: %s Bad candidate instantiated type: %s\r\n", pMT->GetDebugClassName(), candidateInstName.GetANSI(buffer));
OutputDebugStringA(output);
*/
#endif
}
FCIMPLEND
-#ifdef _TARGET_X86_
+#if defined(_TARGET_X86_) && defined(_MSC_VER)
__declspec(naked) LPVOID __fastcall ThreadNative::FastGetDomain()
{
STATIC_CONTRACT_MODE_COOPERATIVE;
ret
}
}
-#else // _TARGET_X86_
+#else // _TARGET_X86_ && _MSC_VER
LPVOID F_CALL_CONV ThreadNative::FastGetDomain()
{
CONTRACTL
}
return NULL;
}
-#endif // _TARGET_X86_
+#endif // _TARGET_X86_ && _MSC_VER
#ifdef FEATURE_REMOTING
// This is just a helper method that lets BCL get to the managed context
UNINSTALL_MANAGED_EXCEPTION_DISPATCHER;
}
-#ifdef _TARGET_X86_
+#if defined(_TARGET_X86_) && !defined(FEATURE_STUBS_AS_IL)
EXTERN_C VOID __cdecl UMThunkStubRareDisable();
EXTERN_C Thread* __stdcall CreateThreadBlockThrow();
return pcpusl->Link(pLoaderHeap);
}
-#else // _TARGET_X86_
+#else // _TARGET_X86_ && !FEATURE_STUBS_AS_IL
PCODE UMThunkMarshInfo::GetExecStubEntryPoint()
{
return GetEEFuncEntryPoint(UMThunkStub);
}
-#endif // _TARGET_X86_
+#endif // _TARGET_X86_ && !FEATURE_STUBS_AS_IL
UMEntryThunkCache::UMEntryThunkCache(AppDomain *pDomain) :
m_crst(CrstUMEntryThunkCache),
}
CONTRACTL_END;
-#ifdef _TARGET_X86_
+#if defined(_TARGET_X86_) && !defined(FEATURE_STUBS_AS_IL)
if (m_pExecStub)
m_pExecStub->DecRef();
#endif
m_pModule = pModule;
m_sig = sig;
-#ifdef _TARGET_X86_
+#if defined(_TARGET_X86_) && !defined(FEATURE_STUBS_AS_IL)
INDEBUG(m_cbRetPop = 0xcccc;)
#endif
}
pFinalILStub = GetStubForInteropMethod(pMD, dwStubFlags, &pStubMD);
}
-#ifdef _TARGET_X86_
+#if defined(_TARGET_X86_) && !defined(FEATURE_STUBS_AS_IL)
PInvokeStaticSigInfo sigInfo;
if (pMD != NULL)
pFinalExecStub->DecRef();
}
-#else // _TARGET_X86_
+#else // _TARGET_X86_ && !FEATURE_STUBS_AS_IL
if (pFinalILStub == NULL)
{
//
m_cbActualArgSize = (pStubMD != NULL) ? pStubMD->AsDynamicMethodDesc()->GetNativeStackArgSize() : pMD->SizeOfArgStack();
-#endif // _TARGET_X86_
+#endif // _TARGET_X86_ && !FEATURE_STUBS_AS_IL
// Must be the last thing we set!
InterlockedCompareExchangeT<PCODE>(&m_pILStub, pFinalILStub, (PCODE)1);
return m_pMD;
}
-#ifdef _TARGET_X86_
+#if defined(_TARGET_X86_) && !defined(FEATURE_STUBS_AS_IL)
PCODE GetExecStubEntryPoint()
{
WRAPPER_NO_CONTRACT;
return (UINT32)offsetof(UMThunkMarshInfo, m_pILStub);
}
-#ifdef _TARGET_X86_
+#if defined(_TARGET_X86_) && !defined(FEATURE_STUBS_AS_IL)
// Compiles an unmanaged to managed thunk for the given signature. The thunk
// will call the stub or, if fNoStub == TRUE, directly the managed target.
Stub *CompileNExportThunk(LoaderHeap *pLoaderHeap, PInvokeStaticSigInfo* pSigInfo, MetaSig *pMetaSig, BOOL fNoStub);
-#endif // _TARGET_X86_
+#endif // _TARGET_X86_ && !FEATURE_STUBS_AS_IL
private:
PCODE m_pILStub; // IL stub for marshaling
// On x86, NULL for no-marshal signatures
// On non-x86, the managed entrypoint for no-delegate no-marshal signatures
UINT32 m_cbActualArgSize; // caches m_pSig.SizeOfFrameArgumentArray()
-#ifdef _TARGET_X86_
+#if defined(_TARGET_X86_) && !defined(FEATURE_STUBS_AS_IL)
Stub* m_pExecStub; // UMEntryThunk jumps directly here
UINT16 m_cbRetPop; // stack bytes popped by callee (for UpdateRegDisplay)
UINT16 m_callConv; // unmanaged calling convention and flags (CorPinvokeMap)
static UMEntryThunk* CreateUMEntryThunk();
static VOID FreeUMEntryThunk(UMEntryThunk* p);
-#ifdef _TARGET_X86_
+#if defined(_TARGET_X86_) && !defined(FEATURE_STUBS_AS_IL)
// Compiles an unmanaged to managed thunk with the given calling convention adaptation.
// - psrcofsregs are stack offsets that should be loaded to argument registers (ECX, EDX)
// - psrcofs are stack offsets that should be repushed for the managed target
UINT *psrcofsregs,
UINT *psrcofs,
UINT retbufofs);
-#endif // _TARGET_X86_
+#endif // _TARGET_X86_ && !FEATURE_STUBS_AS_IL
#ifndef DACCESS_COMPILE
VOID LoadTimeInit(PCODE pManagedTarget,
AppDomain *m_pDomain;
};
-#ifdef _TARGET_X86_
+#if defined(_TARGET_X86_) && !defined(FEATURE_STUBS_AS_IL)
//-------------------------------------------------------------------------
// One-time creation of special prestub to initialize UMEntryThunks.
//-------------------------------------------------------------------------
Stub *GenerateUMThunkPrestub();
-#endif // _TARGET_X86_
+#endif // _TARGET_X86_ && !FEATURE_STUBS_AS_IL
//-------------------------------------------------------------------------
// NExport stub
FCFuncElement("nGetPrimary", DependentHandle::nGetPrimary)
FCFuncElement("nGetPrimaryAndSecondary", DependentHandle::nGetPrimaryAndSecondary)
FCFuncElement("nFree", DependentHandle::nFree)
+ FCFuncElement("nSetPrimary", DependentHandle::nSetPrimary)
+ FCFuncElement("nSetSecondary", DependentHandle::nSetSecondary)
FCFuncEnd()
#ifndef FEATURE_CORECLR
#endif //GC_PROFILING || FEATURE_EVENT_TRACE
}
+void GCToEEInterface::StompWriteBarrier(WriteBarrierParameters* args)
+{
+ assert(args != nullptr);
+ switch (args->operation)
+ {
+ case WriteBarrierOp::StompResize:
+ // StompResize requires a new card table, a new lowest address, and
+ // a new highest address
+ assert(args->card_table != nullptr);
+ assert(args->lowest_address != nullptr);
+ assert(args->highest_address != nullptr);
+ g_card_table = args->card_table;
+ ::StompWriteBarrierResize(args->is_runtime_suspended, args->requires_upper_bounds_check);
+
+ // We need to make sure that other threads executing checked write barriers
+ // will see the g_card_table update before g_lowest/highest_address updates.
+ // Otherwise, the checked write barrier may AV accessing the old card table
+ // with address that it does not cover. Write barriers access card table
+ // without memory barriers for performance reasons, so we need to flush
+ // the store buffers here.
+ FlushProcessWriteBuffers();
+
+ g_lowest_address = args->lowest_address;
+ VolatileStore(&g_highest_address, args->highest_address);
+ return;
+ case WriteBarrierOp::StompEphemeral:
+ // StompEphemeral requires a new ephemeral low and a new ephemeral high
+ assert(args->ephemeral_lo != nullptr);
+ assert(args->ephemeral_hi != nullptr);
+ g_ephemeral_low = args->ephemeral_lo;
+ g_ephemeral_high = args->ephemeral_hi;
+ ::StompWriteBarrierEphemeral(args->is_runtime_suspended);
+ return;
+ case WriteBarrierOp::Initialize:
+ // This operation should only be invoked once, upon initialization.
+ assert(g_card_table == nullptr);
+ assert(g_lowest_address == nullptr);
+ assert(g_highest_address == nullptr);
+ assert(args->card_table != nullptr);
+ assert(args->lowest_address != nullptr);
+ assert(args->highest_address != nullptr);
+ assert(args->is_runtime_suspended && "the runtime must be suspended here!");
+ assert(!args->requires_upper_bounds_check && "the ephemeral generation must be at the top of the heap!");
+
+ g_card_table = args->card_table;
+ FlushProcessWriteBuffers();
+ g_lowest_address = args->lowest_address;
+ VolatileStore(&g_highest_address, args->highest_address);
+ ::StompWriteBarrierResize(true, false);
+ return;
+ default:
+ assert(!"unknown WriteBarrierOp enum");
+ }
+}
void DiagWalkSurvivors(void* gcContext);
void DiagWalkLOHSurvivors(void* gcContext);
void DiagWalkBGCSurvivors(void* gcContext);
+ void StompWriteBarrier(WriteBarrierParameters* args);
};
#endif // FEATURE_STANDALONE_GC
#include "common.h"
#include "gcheaputilities.h"
+// These globals are variables used within the GC and maintained
+// by the EE for use in write barriers. It is the responsibility
+// of the GC to communicate updates to these globals to the EE through
+// GCToEEInterface::StompWriteBarrierResize and GCToEEInterface::StompWriteBarrierEphemeral.
+GPTR_IMPL_INIT(uint32_t, g_card_table, nullptr);
+GPTR_IMPL_INIT(uint8_t, g_lowest_address, nullptr);
+GPTR_IMPL_INIT(uint8_t, g_highest_address, nullptr);
+uint8_t* g_ephemeral_low = (uint8_t*)1;
+uint8_t* g_ephemeral_high = (uint8_t*)~0;
+
// This is the global GC heap, maintained by the VM.
GPTR_IMPL(IGCHeap, g_pGCHeap);
\ No newline at end of file
GCHeapUtilities() = delete;
};
+#ifndef DACCESS_COMPILE
+extern "C" {
+#endif // !DACCESS_COMPILE
+GPTR_DECL(uint8_t,g_lowest_address);
+GPTR_DECL(uint8_t,g_highest_address);
+GPTR_DECL(uint32_t,g_card_table);
+#ifndef DACCESS_COMPILE
+}
+#endif // !DACCESS_COMPILE
+
+extern "C" uint8_t* g_ephemeral_low;
+extern "C" uint8_t* g_ephemeral_high;
+
#endif // _GCHEAPUTILITIES_H_
\ No newline at end of file
method[method_index]->GetLocalsDebugInfo(pTypeMap, locals, symInfo[firstLineIndex].nativeOffset);
method[method_index]->m_sub_low_pc = pCode + method_start;
method[method_index]->m_sub_high_pc = method_size;
- method[method_index]->m_member_name = new char[strlen(methodName) + 10];
+ size_t methodNameSize = strlen(methodName) + 10;
+ method[method_index]->m_member_name = new char[methodNameSize];
if (method_index == 0)
- sprintf(method[method_index]->m_member_name, "%s", methodName);
+ sprintf_s(method[method_index]->m_member_name, methodNameSize, "%s", methodName);
else
- sprintf(method[method_index]->m_member_name, "%s_%i", methodName, method_index);
+ sprintf_s(method[method_index]->m_member_name, methodNameSize, "%s_%i", methodName, method_index);
// method's class
GetTypeInfoFromTypeHandle(TypeHandle(method[method_index]->md->GetMethodTable()), pTypeMap);
int symbolNameLength = strlen(methodName) + sizeof("__thunk_");
SymbolNames[i].m_name = new char[symbolNameLength];
SymbolNames[i].m_releaseName = true;
- sprintf((char*)SymbolNames[i].m_name, "__thunk_%s", methodName);
+ sprintf_s((char*)SymbolNames[i].m_name, symbolNameLength, "__thunk_%s", methodName);
SymbolNames[i].m_value = callAddr;
++i;
codeAddrs.Add(callAddr);
bool isThunkSection = i >= SectionNamesCount;
if (isThunkSection)
{
- sprintf(thunkSectNameBuf, ".thunk_%i", i);
+ sprintf_s(thunkSectNameBuf, _countof(thunkSectNameBuf), ".thunk_%i", i);
sectName = thunkSectNameBuf;
}
else
//
.macro STUB_PROLOG
// push ebp-frame
- push ebp
- mov ebp, esp
+ PROLOG_BEG
// save CalleeSavedRegisters
- push ebx
- push esi
- push edi
+ PROLOG_PUSH ebx
+ PROLOG_PUSH esi
+ PROLOG_PUSH edi
// push ArgumentRegisters
- push ecx
- push edx
+ PROLOG_PUSH ecx
+ PROLOG_PUSH edx
+
+ // set frame pointer
+ PROLOG_END
.endm
//
// FramedMethodFrame epilog
//
.macro STUB_EPILOG
+ // restore stack pointer
+ EPILOG_BEG
+
// pop ArgumentRegisters
- pop edx
- pop ecx
+ EPILOG_POP edx
+ EPILOG_POP ecx
// pop CalleeSavedRegisters
- pop edi
- pop esi
- pop ebx
- pop ebp
+ EPILOG_POP edi
+ EPILOG_POP esi
+ EPILOG_POP ebx
+
+ // pop ebp-frame
+ EPILOG_END
.endm
//
// ------------------------------------------------------------------------------
// void STDCALL CallDescrWorkerInternal(CallDescrWorkerParams * pParams)
NESTED_ENTRY CallDescrWorkerInternal, _TEXT, NoHandler
+ PROLOG_BEG
+ PROLOG_PUSH ebx
+ PROLOG_END
- mov ebx, [esp + 4] // pParams = esp + 4
+ mov ebx, [esp + ((2 + 1) * 4)]
// copy the stack
mov ecx, [ebx +CallDescrData__numStackSlots]
mov [ebx + CallDescrData__returnValue + 4], edx
LOCAL_LABEL(Epilog):
+ EPILOG_BEG
+ EPILOG_POP ebx
+ EPILOG_END
ret 4
LOCAL_LABEL(ReturnsFloat):
sub eax, 5
// Push ebp frame to get good callstack under debugger
- push ebp
- mov ebp, esp
+ PROLOG_BEG
// Preserve argument registers
- push ecx
- push edx
+ PROLOG_PUSH ecx
+ PROLOG_PUSH edx
+
+ // Set frame pointer
+ PROLOG_END
push eax // address of the thunk
push ecx // this ptr
call C_FUNC(VirtualMethodFixupWorker)
+ // Restore stack pointer
+ EPILOG_BEG
+
// Restore argument registers
- pop edx
- pop ecx
+ EPILOG_POP edx
+ EPILOG_POP ecx
// Pop ebp frame
- pop ebp
+ EPILOG_END
PATCH_LABEL VirtualMethodFixupPatchLabel
// Proceed to execute the actual method.
DYNAMICHELPER (DynamicHelperFrameFlags_ObjectArg | DynamicHelperFrameFlags_ObjectArg2), _ObjObj
#endif // FEATURE_READYTORUN
+
+NESTED_ENTRY ResolveWorkerAsmStub, _TEXT, NoHandler
+ //
+ // The stub arguments are where we want to setup the TransitionBlock. We will
+ // setup the TransitionBlock later once we can trash them
+ //
+ // push ebp-frame
+ // push ebp
+ // mov ebp,esp
+
+ // save CalleeSavedRegisters
+ // push ebx
+
+ push esi
+ push edi
+
+ // push ArgumentRegisters
+ push ecx
+ push edx
+
+ mov esi, esp
+
+ push [esi + 4*4] // dispatch token
+ push [esi + 5*4] // siteAddrForRegisterIndirect
+ push esi // pTransitionBlock
+
+ // Setup up proper EBP frame now that the stub arguments can be trashed
+ mov [esi + 4*4],ebx
+ mov [esi + 5*4],ebp
+ lea ebp, [esi + 5*4]
+
+ // Make the call
+ call C_FUNC(VSD_ResolveWorker)
+
+ // From here on, mustn't trash eax
+
+ // pop ArgumentRegisters
+ pop edx
+ pop ecx
+
+ // pop CalleeSavedRegisters
+ pop edi
+ pop esi
+ pop ebx
+ pop ebp
+
+ // Now jump to the target
+ jmp eax // continue on into the method
+NESTED_END ResolveWorkerAsmStub, _TEXT
#ifndef DACCESS_COMPILE
+#if defined(_TARGET_X86_) && !defined(FEATURE_STUBS_AS_IL)
//-------------------------------------------------------------------------
// One-time creation of special prestub to initialize UMEntryThunks.
//-------------------------------------------------------------------------
}
CONTRACT_END;
-#ifndef FEATURE_STUBS_AS_IL
CPUSTUBLINKER sl;
CPUSTUBLINKER *psl = &sl;
psl->EmitComMethodStubEpilog(UMThkCallFrame::GetMethodFrameVPtr(), rgRareLabels, rgRejoinLabels, FALSE /*Don't profile*/);
RETURN psl->Link(SystemDomain::GetGlobalLoaderAllocator()->GetExecutableHeap());
-#else // FEATURE_STUBS_AS_IL
- PORTABILITY_ASSERT("GenerateUMThunkPrestub");
- return NULL;
-#endif // FEATURE_STUBS_AS_IL
}
+#endif // _TARGET_X86_ && !FEATURE_STUBS_AS_IL
Stub *GenerateInitPInvokeFrameHelper()
{
#pragma warning(pop)
-#endif
+#else // !FEATURE_PAL
+
+extern "C" DWORD __stdcall getcpuid(DWORD arg, unsigned char result[16])
+{
+ DWORD eax;
+ __asm(" xor %%ecx, %%ecx\n" \
+ " cpuid\n" \
+ " mov %%eax, 0(%[result])\n" \
+ " mov %%ebx, 4(%[result])\n" \
+ " mov %%ecx, 8(%[result])\n" \
+ " mov %%edx, 12(%[result])\n" \
+ : "=a"(eax) /*output in eax*/\
+ : "a"(arg), [result]"r"(result) /*inputs - arg in eax, result in any register*/\
+ : "eax", "rbx", "ecx", "edx", "memory" /* registers that are clobbered, *result is clobbered */
+ );
+ return eax;
+}
+
+extern "C" DWORD __stdcall getextcpuid(DWORD arg1, DWORD arg2, unsigned char result[16])
+{
+ DWORD eax;
+ __asm(" cpuid\n" \
+ " mov %%eax, 0(%[result])\n" \
+ " mov %%ebx, 4(%[result])\n" \
+ " mov %%ecx, 8(%[result])\n" \
+ " mov %%edx, 12(%[result])\n" \
+ : "=a"(eax) /*output in eax*/\
+ : "c"(arg1), "a"(arg2), [result]"r"(result) /*inputs - arg1 in ecx, arg2 in eax, result in any register*/\
+ : "eax", "rbx", "ecx", "edx", "memory" /* registers that are clobbered, *result is clobbered */
+ );
+ return eax;
+}
+
+extern "C" DWORD __stdcall xmmYmmStateSupport()
+{
+ DWORD eax;
+ __asm(" xgetbv\n" \
+ : "=a"(eax) /*output in eax*/\
+ : "c"(0) /*inputs - 0 in ecx*/\
+ : "eax", "edx" /* registers that are clobbered*/
+ );
+ // check OS has enabled both XMM and YMM state support
+ return ((eax & 0x06) == 0x06) ? 1 : 0;
+}
+
+#endif // !FEATURE_PAL
// This function returns the number of logical processors on a given physical chip. If it cannot
// determine the number of logical cpus, or the machine is not populated uniformly with the same
--- /dev/null
+// Licensed to the .NET Foundation under one or more agreements.
+// The .NET Foundation licenses this file to you under the MIT license.
+// See the LICENSE file in the project root for more information.
+
+.intel_syntax noprefix
+#include "unixasmmacros.inc"
+#include "asmconstants.h"
+
+//
+// eax = UMEntryThunk*
+//
+NESTED_ENTRY TheUMEntryPrestub, _TEXT, UnhandledExceptionHandlerUnix
+ // Preserve argument registers
+ push ecx
+ push edx
+
+ push eax
+ call C_FUNC(TheUMEntryPrestubWorker)
+ pop edx
+
+ // Restore argument registers
+ pop edx
+ pop ecx
+
+ jmp eax // Tail Jmp
+NESTED_END TheUMEntryPrestub, _TEXT
+
+
+NESTED_ENTRY UMThunkStub, _TEXT, UnhandledExceptionHandlerUnix
+ int 3 // implement here
+ ret
+NESTED_END UMThunkStub, _TEXT
PORTABILITY_ASSERT("Implement for PAL");
}
- DWORD getcpuid(DWORD arg, unsigned char result[16])
- {
- DWORD eax;
- __asm(" xor %%ecx, %%ecx\n" \
- " cpuid\n" \
- " mov %%eax, 0(%[result])\n" \
- " mov %%ebx, 4(%[result])\n" \
- " mov %%ecx, 8(%[result])\n" \
- " mov %%edx, 12(%[result])\n" \
- : "=a"(eax) /*output in eax*/\
- : "a"(arg), [result]"r"(result) /*inputs - arg in eax, result in any register*/\
- : "eax", "rbx", "ecx", "edx", "memory" /* registers that are clobbered, *result is clobbered */
- );
- return eax;
- }
-
- DWORD getextcpuid(DWORD arg1, DWORD arg2, unsigned char result[16])
- {
- DWORD eax;
- __asm(" cpuid\n" \
- " mov %%eax, 0(%[result])\n" \
- " mov %%ebx, 4(%[result])\n" \
- " mov %%ecx, 8(%[result])\n" \
- " mov %%edx, 12(%[result])\n" \
- : "=a"(eax) /*output in eax*/\
- : "c"(arg1), "a"(arg2), [result]"r"(result) /*inputs - arg1 in ecx, arg2 in eax, result in any register*/\
- : "eax", "rbx", "ecx", "edx", "memory" /* registers that are clobbered, *result is clobbered */
- );
- return eax;
- }
-
- DWORD xmmYmmStateSupport()
- {
- DWORD eax;
- __asm(" xgetbv\n" \
- : "=a"(eax) /*output in eax*/\
- : "c"(0) /*inputs - 0 in ecx*/\
- : "eax", "edx" /* registers that are clobbered*/
- );
- // check OS has enabled both XMM and YMM state support
- return ((eax & 0x06) == 0x06) ? 1 : 0;
- }
-
void STDCALL JIT_ProfilerEnterLeaveTailcallStub(UINT_PTR ProfilerHandle)
{
}
{
PORTABILITY_ASSERT("Implement for PAL");
}
+
+EXTERN_C VOID SinglecastDelegateInvokeStub()
+{
+ PORTABILITY_ASSERT("SinglecastDelegateInvokeStub");
+}
+
+EXTERN_C VOID ResolveWorkerChainLookupAsmStub()
+{
+ PORTABILITY_ASSERT("ResolveWorkerChainLookupAsmStub");
+}
+
+EXTERN_C VOID BackPatchWorkerAsmStub()
+{
+ PORTABILITY_ASSERT("BackPatchWorkerAsmStub");
+}
// use the prestub.
//==========================================================================
-#ifdef _TARGET_X86_
+#if defined(_TARGET_X86_) && !defined(FEATURE_STUBS_AS_IL)
static PCODE g_UMThunkPreStub;
-#endif // _TARGET_X86_
+#endif // _TARGET_X86_ && !FEATURE_STUBS_AS_IL
#ifndef DACCESS_COMPILE
return;
}
-#ifdef _TARGET_X86_
+#if defined(_TARGET_X86_) && !defined(FEATURE_STUBS_AS_IL)
g_UMThunkPreStub = GenerateUMThunkPrestub()->GetEntryPoint();
-#endif // _TARGET_X86_
+#endif // _TARGET_X86_ && !FEATURE_STUBS_AS_IL
ThePreStubManager::Init();
}
{
LIMITED_METHOD_CONTRACT;
-#ifdef _TARGET_X86_
+#if defined(_TARGET_X86_) && !defined(FEATURE_STUBS_AS_IL)
return g_UMThunkPreStub;
-#else // _TARGET_X86_
+#else // _TARGET_X86_ && !FEATURE_STUBS_AS_IL
return GetEEFuncEntryPoint(TheUMEntryPrestub);
-#endif // _TARGET_X86_
+#endif // _TARGET_X86_ && !FEATURE_STUBS_AS_IL
}
PCODE TheVarargNDirectStub(BOOL hasRetBuffArg)
{
"dependencies": {
- "Microsoft.NETCore.ILAsm": "1.2.0-beta-24801-03",
- "Microsoft.NETCore.ILDAsm": "1.2.0-beta-24801-03",
- "Microsoft.NETCore.Jit": "1.2.0-beta-24801-03",
- "Microsoft.NETCore.Runtime.CoreCLR": "1.2.0-beta-24801-03",
- "Microsoft.NETCore.TestHost": "1.2.0-beta-24801-03"
+ "Microsoft.NETCore.ILAsm": "1.2.0-beta-24810-01",
+ "Microsoft.NETCore.ILDAsm": "1.2.0-beta-24810-01",
+ "Microsoft.NETCore.Jit": "1.2.0-beta-24810-01",
+ "Microsoft.NETCore.Runtime.CoreCLR": "1.2.0-beta-24810-01",
+ "Microsoft.NETCore.TestHost": "1.2.0-beta-24810-01"
},
"frameworks": {
"netcoreapp1.1": {
"emitEntryPoint": true
},
"dependencies": {
- "Microsoft.NETCore.Platforms": "1.2.0-beta-24721-02",
- "Microsoft.NETCore.Targets": "1.2.0-beta-24721-02",
- "System.Threading.Thread": "4.4.0-beta-24721-02",
- "System.Collections": "4.4.0-beta-24721-02",
- "System.Xml.XmlSerializer": "4.4.0-beta-24721-02",
- "System.Collections.Concurrent": "4.4.0-beta-24721-02",
- "System.ObjectModel": "4.4.0-beta-24721-02",
- "System.Runtime.Numerics": "4.4.0-beta-24721-02",
- "System.Collections.NonGeneric": "4.4.0-beta-24721-02",
- "System.Collections.Specialized": "4.4.0-beta-24721-02",
- "System.ComponentModel": "4.4.0-beta-24721-02",
- "System.Reflection.Emit.Lightweight": "4.4.0-beta-24721-02",
- "System.Reflection.TypeExtensions": "4.4.0-beta-24721-02",
- "System.Console": "4.4.0-beta-24721-02",
- "System.Diagnostics.Contracts": "4.4.0-beta-24721-02",
- "System.Diagnostics.Debug": "4.4.0-beta-24721-02",
- "System.Diagnostics.Process": "4.4.0-beta-24721-02",
- "System.Diagnostics.Tools": "4.4.0-beta-24721-02",
- "System.Diagnostics.Tracing": "4.4.0-beta-24721-02",
- "System.Dynamic.Runtime": "4.4.0-beta-24721-02",
- "System.Globalization": "4.4.0-beta-24721-02",
- "System.Globalization.Calendars": "4.4.0-beta-24721-02",
- "System.IO": "4.4.0-beta-24721-02",
- "System.IO.FileSystem": "4.4.0-beta-24721-02",
- "System.IO.FileSystem.Primitives": "4.4.0-beta-24721-02",
- "System.Linq": "4.4.0-beta-24721-02",
- "System.Linq.Queryable": "4.4.0-beta-24721-02",
- "System.Linq.Expressions": "4.4.0-beta-24721-02",
- "System.Reflection": "4.4.0-beta-24721-02",
- "System.Reflection.Extensions": "4.4.0-beta-24721-02",
- "System.Resources.ResourceManager": "4.4.0-beta-24721-02",
- "System.Runtime": "4.4.0-beta-24721-02",
- "System.Runtime.CompilerServices.Unsafe": "4.4.0-beta-24721-02",
- "System.Runtime.Extensions": "4.4.0-beta-24721-02",
- "System.Runtime.Handles": "4.4.0-beta-24721-02",
- "System.Runtime.InteropServices": "4.4.0-beta-24721-02",
- "System.Runtime.InteropServices.RuntimeInformation": "4.4.0-beta-24721-02",
- "System.Runtime.Loader": "4.4.0-beta-24721-02",
- "System.Security.Cryptography.Algorithms": "4.4.0-beta-24721-02",
- "System.Text.Encoding": "4.4.0-beta-24721-02",
- "System.Text.Encoding.Extensions": "4.4.0-beta-24721-02",
- "System.Text.RegularExpressions": "4.4.0-beta-24721-02",
- "System.Threading": "4.4.0-beta-24721-02",
- "System.Threading.AccessControl": "4.4.0-beta-24721-02",
- "System.Threading.Overlapped": "4.4.0-beta-24721-02",
- "System.Threading.Tasks": "4.4.0-beta-24721-02",
- "System.Threading.Tasks.Parallel": "4.4.0-beta-24721-02",
- "System.Threading.ThreadPool": "4.4.0-beta-24721-02",
- "System.Threading.Timer": "4.4.0-beta-24721-02",
- "System.Xml.ReaderWriter": "4.4.0-beta-24721-02",
- "System.Xml.XDocument": "4.4.0-beta-24721-02",
- "System.Xml.XmlDocument": "4.4.0-beta-24721-02",
- "System.Xml.XPath": "4.4.0-beta-24721-02",
- "System.Xml.XPath.XmlDocument": "4.4.0-beta-24721-02",
- "System.Numerics.Vectors": "4.4.0-beta-24721-02"
+ "Microsoft.NETCore.Platforms": "1.2.0-beta-24810-02",
+ "Microsoft.NETCore.Targets": "1.2.0-beta-24810-02",
+ "System.Threading.Thread": "4.4.0-beta-24810-02",
+ "System.Collections": "4.4.0-beta-24810-02",
+ "System.Xml.XmlSerializer": "4.4.0-beta-24810-02",
+ "System.Collections.Concurrent": "4.4.0-beta-24810-02",
+ "System.ObjectModel": "4.4.0-beta-24810-02",
+ "System.Runtime.Numerics": "4.4.0-beta-24810-02",
+ "System.Collections.NonGeneric": "4.4.0-beta-24810-02",
+ "System.Collections.Specialized": "4.4.0-beta-24810-02",
+ "System.ComponentModel": "4.4.0-beta-24810-02",
+ "System.Reflection.Emit.Lightweight": "4.4.0-beta-24810-02",
+ "System.Reflection.TypeExtensions": "4.4.0-beta-24810-02",
+ "System.Console": "4.4.0-beta-24810-02",
+ "System.Diagnostics.Contracts": "4.4.0-beta-24810-02",
+ "System.Diagnostics.Debug": "4.4.0-beta-24810-02",
+ "System.Diagnostics.Process": "4.4.0-beta-24810-02",
+ "System.Diagnostics.Tools": "4.4.0-beta-24810-02",
+ "System.Diagnostics.Tracing": "4.4.0-beta-24810-02",
+ "System.Dynamic.Runtime": "4.4.0-beta-24810-02",
+ "System.Globalization": "4.4.0-beta-24810-02",
+ "System.Globalization.Calendars": "4.4.0-beta-24810-02",
+ "System.IO": "4.4.0-beta-24810-02",
+ "System.IO.FileSystem": "4.4.0-beta-24810-02",
+ "System.IO.FileSystem.Primitives": "4.4.0-beta-24810-02",
+ "System.Linq": "4.4.0-beta-24810-02",
+ "System.Linq.Queryable": "4.4.0-beta-24810-02",
+ "System.Linq.Expressions": "4.4.0-beta-24810-02",
+ "System.Reflection": "4.4.0-beta-24810-02",
+ "System.Reflection.Extensions": "4.4.0-beta-24810-02",
+ "System.Resources.ResourceManager": "4.4.0-beta-24810-02",
+ "System.Runtime": "4.4.0-beta-24810-02",
+ "System.Runtime.CompilerServices.Unsafe": "4.4.0-beta-24810-02",
+ "System.Runtime.Extensions": "4.4.0-beta-24810-02",
+ "System.Runtime.Handles": "4.4.0-beta-24810-02",
+ "System.Runtime.InteropServices": "4.4.0-beta-24810-02",
+ "System.Runtime.InteropServices.RuntimeInformation": "4.4.0-beta-24810-02",
+ "System.Runtime.Loader": "4.4.0-beta-24810-02",
+ "System.Security.Cryptography.Algorithms": "4.4.0-beta-24810-02",
+ "System.Text.Encoding": "4.4.0-beta-24810-02",
+ "System.Text.Encoding.Extensions": "4.4.0-beta-24810-02",
+ "System.Text.RegularExpressions": "4.4.0-beta-24810-02",
+ "System.Threading": "4.4.0-beta-24810-02",
+ "System.Threading.AccessControl": "4.4.0-beta-24810-02",
+ "System.Threading.Overlapped": "4.4.0-beta-24810-02",
+ "System.Threading.Tasks": "4.4.0-beta-24810-02",
+ "System.Threading.Tasks.Parallel": "4.4.0-beta-24810-02",
+ "System.Threading.ThreadPool": "4.4.0-beta-24810-02",
+ "System.Threading.Timer": "4.4.0-beta-24810-02",
+ "System.Xml.ReaderWriter": "4.4.0-beta-24810-02",
+ "System.Xml.XDocument": "4.4.0-beta-24810-02",
+ "System.Xml.XmlDocument": "4.4.0-beta-24810-02",
+ "System.Xml.XPath": "4.4.0-beta-24810-02",
+ "System.Xml.XPath.XmlDocument": "4.4.0-beta-24810-02",
+ "System.Numerics.Vectors": "4.4.0-beta-24810-02"
},
"frameworks": {
"netcoreapp1.1": {
"dependencies": {
- "Microsoft.NETCore.Runtime.CoreCLR": "1.2.0-beta-24801-03"
+ "Microsoft.NETCore.Runtime.CoreCLR": "1.2.0-beta-24810-01"
}
}
},
{
"dependencies": {
- "Microsoft.TargetingPack.Private.CoreCLR": "1.2.0-beta-24801-03"
+ "Microsoft.TargetingPack.Private.CoreCLR": "1.2.0-beta-24810-01"
},
"frameworks": {
"netcoreapp1.1": {
"Microsoft.DotNet.xunit.performance": "1.0.0-alpha-build0040",
"Microsoft.DotNet.xunit.performance.analysis": "1.0.0-alpha-build0040",
"Microsoft.DotNet.xunit.performance.runner.Windows": "1.0.0-alpha-build0040",
- "Microsoft.Win32.Primitives": "4.4.0-beta-24721-02",
+ "Microsoft.Win32.Primitives": "4.4.0-beta-24810-02",
"Newtonsoft.Json": "8.0.3",
- "Microsoft.NETCore.Platforms": "1.2.0-beta-24721-02",
- "Microsoft.NETCore.Targets": "1.2.0-beta-24721-02",
- "System.Collections.Immutable": "1.4.0-beta-24721-02",
- "System.Threading.Thread": "4.4.0-beta-24721-02",
- "System.Collections": "4.4.0-beta-24721-02",
- "System.Xml.XmlSerializer": "4.4.0-beta-24721-02",
- "System.Collections.Concurrent": "4.4.0-beta-24721-02",
- "System.ObjectModel": "4.4.0-beta-24721-02",
- "System.Runtime.Numerics": "4.4.0-beta-24721-02",
- "System.Collections.NonGeneric": "4.4.0-beta-24721-02",
- "System.Collections.Specialized": "4.4.0-beta-24721-02",
- "System.ComponentModel": "4.4.0-beta-24721-02",
- "System.Reflection.Emit.Lightweight": "4.4.0-beta-24721-02",
- "System.Reflection.TypeExtensions": "4.4.0-beta-24721-02",
- "System.Console": "4.4.0-beta-24721-02",
- "System.Diagnostics.Contracts": "4.4.0-beta-24721-02",
- "System.Diagnostics.Debug": "4.4.0-beta-24721-02",
- "System.Diagnostics.Process": "4.4.0-beta-24721-02",
- "System.Diagnostics.Tools": "4.4.0-beta-24721-02",
- "System.Diagnostics.Tracing": "4.4.0-beta-24721-02",
- "System.Dynamic.Runtime": "4.4.0-beta-24721-02",
- "System.Globalization": "4.4.0-beta-24721-02",
- "System.Globalization.Calendars": "4.4.0-beta-24721-02",
- "System.IO": "4.4.0-beta-24721-02",
- "System.IO.FileSystem": "4.4.0-beta-24721-02",
- "System.IO.FileSystem.Primitives": "4.4.0-beta-24721-02",
- "System.Linq": "4.4.0-beta-24721-02",
- "System.Linq.Queryable": "4.4.0-beta-24721-02",
- "System.Linq.Expressions": "4.4.0-beta-24721-02",
- "System.Reflection": "4.4.0-beta-24721-02",
- "System.Reflection.Extensions": "4.4.0-beta-24721-02",
- "System.Resources.ResourceManager": "4.4.0-beta-24721-02",
- "System.Runtime": "4.4.0-beta-24721-02",
- "System.Runtime.CompilerServices.Unsafe": "4.4.0-beta-24721-02",
- "System.Runtime.Extensions": "4.4.0-beta-24721-02",
- "System.Runtime.Handles": "4.4.0-beta-24721-02",
- "System.Runtime.InteropServices": "4.4.0-beta-24721-02",
- "System.Runtime.InteropServices.RuntimeInformation": "4.4.0-beta-24721-02",
- "System.Runtime.Loader": "4.4.0-beta-24721-02",
- "System.Runtime.Serialization.Json": "4.4.0-beta-24721-02",
- "System.Runtime.Serialization.Primitives": "4.4.0-beta-24721-02",
- "System.Runtime.Serialization.Xml": "4.4.0-beta-24721-02",
- "System.Security.Cryptography.Algorithms": "4.4.0-beta-24721-02",
- "System.Text.Encoding": "4.4.0-beta-24721-02",
- "System.Text.Encoding.Extensions": "4.4.0-beta-24721-02",
- "System.Text.RegularExpressions": "4.4.0-beta-24721-02",
- "System.Threading": "4.4.0-beta-24721-02",
- "System.Threading.AccessControl": "4.4.0-beta-24721-02",
- "System.Threading.Overlapped": "4.4.0-beta-24721-02",
- "System.Threading.Tasks": "4.4.0-beta-24721-02",
- "System.Threading.Tasks.Parallel": "4.4.0-beta-24721-02",
- "System.Threading.ThreadPool": "4.4.0-beta-24721-02",
- "System.Threading.Timer": "4.4.0-beta-24721-02",
- "System.Xml.ReaderWriter": "4.4.0-beta-24721-02",
- "System.Xml.XDocument": "4.4.0-beta-24721-02",
- "System.Xml.XmlDocument": "4.4.0-beta-24721-02",
- "System.Xml.XPath": "4.4.0-beta-24721-02",
- "System.Xml.XPath.XmlDocument": "4.4.0-beta-24721-02",
- "System.Numerics.Vectors": "4.4.0-beta-24721-02"
+ "Microsoft.NETCore.Platforms": "1.2.0-beta-24810-02",
+ "Microsoft.NETCore.Targets": "1.2.0-beta-24810-02",
+ "System.Collections.Immutable": "1.4.0-beta-24810-02",
+ "System.Threading.Thread": "4.4.0-beta-24810-02",
+ "System.Collections": "4.4.0-beta-24810-02",
+ "System.Xml.XmlSerializer": "4.4.0-beta-24810-02",
+ "System.Collections.Concurrent": "4.4.0-beta-24810-02",
+ "System.ObjectModel": "4.4.0-beta-24810-02",
+ "System.Runtime.Numerics": "4.4.0-beta-24810-02",
+ "System.Collections.NonGeneric": "4.4.0-beta-24810-02",
+ "System.Collections.Specialized": "4.4.0-beta-24810-02",
+ "System.ComponentModel": "4.4.0-beta-24810-02",
+ "System.Reflection.Emit.Lightweight": "4.4.0-beta-24810-02",
+ "System.Reflection.TypeExtensions": "4.4.0-beta-24810-02",
+ "System.Console": "4.4.0-beta-24810-02",
+ "System.Diagnostics.Contracts": "4.4.0-beta-24810-02",
+ "System.Diagnostics.Debug": "4.4.0-beta-24810-02",
+ "System.Diagnostics.Process": "4.4.0-beta-24810-02",
+ "System.Diagnostics.Tools": "4.4.0-beta-24810-02",
+ "System.Diagnostics.Tracing": "4.4.0-beta-24810-02",
+ "System.Dynamic.Runtime": "4.4.0-beta-24810-02",
+ "System.Globalization": "4.4.0-beta-24810-02",
+ "System.Globalization.Calendars": "4.4.0-beta-24810-02",
+ "System.IO": "4.4.0-beta-24810-02",
+ "System.IO.FileSystem": "4.4.0-beta-24810-02",
+ "System.IO.FileSystem.Primitives": "4.4.0-beta-24810-02",
+ "System.Linq": "4.4.0-beta-24810-02",
+ "System.Linq.Queryable": "4.4.0-beta-24810-02",
+ "System.Linq.Expressions": "4.4.0-beta-24810-02",
+ "System.Reflection": "4.4.0-beta-24810-02",
+ "System.Reflection.Extensions": "4.4.0-beta-24810-02",
+ "System.Resources.ResourceManager": "4.4.0-beta-24810-02",
+ "System.Runtime": "4.4.0-beta-24810-02",
+ "System.Runtime.CompilerServices.Unsafe": "4.4.0-beta-24810-02",
+ "System.Runtime.Extensions": "4.4.0-beta-24810-02",
+ "System.Runtime.Handles": "4.4.0-beta-24810-02",
+ "System.Runtime.InteropServices": "4.4.0-beta-24810-02",
+ "System.Runtime.InteropServices.RuntimeInformation": "4.4.0-beta-24810-02",
+ "System.Runtime.Loader": "4.4.0-beta-24810-02",
+ "System.Runtime.Serialization.Json": "4.4.0-beta-24810-02",
+ "System.Runtime.Serialization.Primitives": "4.4.0-beta-24810-02",
+ "System.Runtime.Serialization.Xml": "4.4.0-beta-24810-02",
+ "System.Security.Cryptography.Algorithms": "4.4.0-beta-24810-02",
+ "System.Text.Encoding": "4.4.0-beta-24810-02",
+ "System.Text.Encoding.Extensions": "4.4.0-beta-24810-02",
+ "System.Text.RegularExpressions": "4.4.0-beta-24810-02",
+ "System.Threading": "4.4.0-beta-24810-02",
+ "System.Threading.AccessControl": "4.4.0-beta-24810-02",
+ "System.Threading.Overlapped": "4.4.0-beta-24810-02",
+ "System.Threading.Tasks": "4.4.0-beta-24810-02",
+ "System.Threading.Tasks.Parallel": "4.4.0-beta-24810-02",
+ "System.Threading.ThreadPool": "4.4.0-beta-24810-02",
+ "System.Threading.Timer": "4.4.0-beta-24810-02",
+ "System.Xml.ReaderWriter": "4.4.0-beta-24810-02",
+ "System.Xml.XDocument": "4.4.0-beta-24810-02",
+ "System.Xml.XmlDocument": "4.4.0-beta-24810-02",
+ "System.Xml.XPath": "4.4.0-beta-24810-02",
+ "System.Xml.XPath.XmlDocument": "4.4.0-beta-24810-02",
+ "System.Numerics.Vectors": "4.4.0-beta-24810-02"
},
"frameworks": {
"netcoreapp1.1": {
<ProjectTypeGuids>{786C830F-07A1-408B-BD7F-6EE04809D6DB};{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}</ProjectTypeGuids>
<ReferencePath>$(ProgramFiles)\Common Files\microsoft shared\VSTT\11.0\UITestExtensionPackages</ReferencePath>
<SolutionDir Condition="$(SolutionDir) == '' Or $(SolutionDir) == '*Undefined*'">..\..\</SolutionDir>
+ <GCStressIncompatible Condition="'$(Platform)' == 'x86'">true</GCStressIncompatible>
<NuGetPackageImportStamp>7a9bfb7d</NuGetPackageImportStamp>
<CLRTestExecutionArguments></CLRTestExecutionArguments>
--- /dev/null
+// Licensed to the .NET Foundation under one or more agreements.
+// The .NET Foundation licenses this file to you under the MIT license.
+// See the LICENSE file in the project root for more information.
+
+using System;
+using System.Runtime.CompilerServices;
+
+// TreeNodeInfoInitCmp attempts to eliminate the cast from cmp(cast<ubyte>(x), icon)
+// by narrowing the compare to ubyte. This should only happen if the constant fits in
+// a byte so it can be narrowed too, otherwise codegen produces an int sized compare.
+
+class Program
+{
+ [MethodImpl(MethodImplOptions.NoInlining)]
+ static int GetValue() => 301;
+
+ static void Escape(ref int x)
+ {
+ }
+
+ static int Main()
+ {
+ if ((byte)GetValue() > 300)
+ {
+ return -1;
+ }
+
+ int x = GetValue();
+ Escape(ref x);
+ if ((byte)x > 300)
+ {
+ return -2;
+ }
+
+ if ((byte)(GetValue() | 2) > 300)
+ {
+ return -3;
+ }
+
+ return 100;
+ }
+}
--- /dev/null
+<?xml version="1.0" encoding="utf-8"?>
+<Project ToolsVersion="12.0" DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
+ <Import Project="$([MSBuild]::GetDirectoryNameOfFileAbove($(MSBuildThisFileDirectory), dir.props))\dir.props" />
+ <PropertyGroup>
+ <Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>
+ <Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform>
+ <AssemblyName>$(MSBuildProjectName)</AssemblyName>
+ <SchemaVersion>2.0</SchemaVersion>
+ <ProjectGuid>{95DFC527-4DC1-495E-97D7-E94EE1F7140D}</ProjectGuid>
+ <OutputType>Exe</OutputType>
+ <AppDesignerFolder>Properties</AppDesignerFolder>
+ <FileAlignment>512</FileAlignment>
+ <ProjectTypeGuids>{786C830F-07A1-408B-BD7F-6EE04809D6DB};{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}</ProjectTypeGuids>
+ <ReferencePath>$(ProgramFiles)\Common Files\microsoft shared\VSTT\11.0\UITestExtensionPackages</ReferencePath>
+ <SolutionDir Condition="$(SolutionDir) == '' Or $(SolutionDir) == '*Undefined*'">..\..\</SolutionDir>
+
+ <NuGetPackageImportStamp>7a9bfb7d</NuGetPackageImportStamp>
+ </PropertyGroup>
+ <!-- Default configurations to help VS understand the configurations -->
+ <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' ">
+ </PropertyGroup>
+ <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' ">
+ </PropertyGroup>
+ <ItemGroup>
+ <CodeAnalysisDependentAssemblyPaths Condition=" '$(VS100COMNTOOLS)' != '' " Include="$(VS100COMNTOOLS)..\IDE\PrivateAssemblies">
+ <Visible>False</Visible>
+ </CodeAnalysisDependentAssemblyPaths>
+ </ItemGroup>
+ <PropertyGroup>
+ <DebugType></DebugType>
+ <Optimize>True</Optimize>
+ </PropertyGroup>
+ <ItemGroup>
+ <Compile Include="$(MSBuildProjectName).cs" />
+ </ItemGroup>
+ <ItemGroup>
+ <Service Include="{82A7F48D-3B50-4B1E-B82E-3ADA8210C358}" />
+ </ItemGroup>
+ <PropertyGroup>
+ <ProjectJson>$(JitPackagesConfigFileDirectory)minimal\project.json</ProjectJson>
+ <ProjectLockJson>$(JitPackagesConfigFileDirectory)minimal\project.lock.json</ProjectLockJson>
+ </PropertyGroup>
+ <Import Project="$([MSBuild]::GetDirectoryNameOfFileAbove($(MSBuildThisFileDirectory), dir.targets))\dir.targets" />
+ <PropertyGroup Condition=" '$(MsBuildProjectDirOverride)' != '' ">
+ </PropertyGroup>
+</Project>
"Microsoft.DotNet.xunit.performance": "1.0.0-alpha-build0040",
"Microsoft.DotNet.xunit.performance.analysis": "1.0.0-alpha-build0040",
"Microsoft.DotNet.xunit.performance.runner.Windows": "1.0.0-alpha-build0040",
- "Microsoft.NETCore.Platforms": "1.2.0-beta-24721-02",
- "System.Console": "4.4.0-beta-24721-02",
- "System.Dynamic.Runtime": "4.4.0-beta-24721-02",
- "System.Linq": "4.4.0-beta-24721-02",
- "System.IO.FileSystem": "4.4.0-beta-24721-02",
- "System.Numerics.Vectors": "4.4.0-beta-24721-02",
- "System.Reflection": "4.4.0-beta-24721-02",
- "System.Reflection.Extensions": "4.4.0-beta-24721-02",
- "System.Reflection.TypeExtensions": "4.4.0-beta-24721-02",
- "System.Runtime": "4.4.0-beta-24721-02",
- "System.Runtime.Extensions": "4.4.0-beta-24721-02",
- "System.Runtime.Numerics": "4.4.0-beta-24721-02",
- "System.Text.RegularExpressions": "4.4.0-beta-24721-02",
- "System.Threading": "4.4.0-beta-24721-02",
- "System.Threading.Tasks": "4.4.0-beta-24721-02",
- "System.Threading.Tasks.Parallel": "4.4.0-beta-24721-02",
- "System.Security.Cryptography.Algorithms": "4.4.0-beta-24721-02",
+ "Microsoft.NETCore.Platforms": "1.2.0-beta-24810-02",
+ "System.Console": "4.4.0-beta-24810-02",
+ "System.Dynamic.Runtime": "4.4.0-beta-24810-02",
+ "System.Linq": "4.4.0-beta-24810-02",
+ "System.IO.FileSystem": "4.4.0-beta-24810-02",
+ "System.Numerics.Vectors": "4.4.0-beta-24810-02",
+ "System.Reflection": "4.4.0-beta-24810-02",
+ "System.Reflection.Extensions": "4.4.0-beta-24810-02",
+ "System.Reflection.TypeExtensions": "4.4.0-beta-24810-02",
+ "System.Runtime": "4.4.0-beta-24810-02",
+ "System.Runtime.Extensions": "4.4.0-beta-24810-02",
+ "System.Runtime.Numerics": "4.4.0-beta-24810-02",
+ "System.Text.RegularExpressions": "4.4.0-beta-24810-02",
+ "System.Threading": "4.4.0-beta-24810-02",
+ "System.Threading.Tasks": "4.4.0-beta-24810-02",
+ "System.Threading.Tasks.Parallel": "4.4.0-beta-24810-02",
+ "System.Security.Cryptography.Algorithms": "4.4.0-beta-24810-02",
"xunit": "2.2.0-beta2-build3300",
"xunit.console.netcore": "1.0.2-prerelease-00177",
"xunit.runner.utility": "2.2.0-beta2-build3300"
"Microsoft.DotNet.xunit.performance": "1.0.0-alpha-build0040",
"Microsoft.DotNet.xunit.performance.analysis": "1.0.0-alpha-build0040",
"Microsoft.DotNet.xunit.performance.runner.Windows": "1.0.0-alpha-build0040",
- "Microsoft.NETCore.Platforms": "1.2.0-beta-24721-02",
+ "Microsoft.NETCore.Platforms": "1.2.0-beta-24810-02",
"Newtonsoft.Json": "7.0.1",
- "System.Console": "4.4.0-beta-24721-02",
- "System.IO": "4.4.0-beta-24721-02",
- "System.IO.FileSystem": "4.4.0-beta-24721-02",
- "System.Linq": "4.4.0-beta-24721-02",
- "System.ObjectModel": "4.4.0-beta-24721-02",
- "System.Dynamic.Runtime": "4.4.0-beta-24721-02",
- "System.Reflection": "4.4.0-beta-24721-02",
- "System.Reflection.Extensions": "4.4.0-beta-24721-02",
- "System.Reflection.TypeExtensions": "4.4.0-beta-24721-02",
- "System.Runtime": "4.4.0-beta-24721-02",
- "System.Runtime.Serialization.Json": "4.4.0-beta-24721-02",
- "System.Runtime.Serialization.Primitives": "4.4.0-beta-24721-02",
- "System.Runtime.Serialization.Xml": "4.4.0-beta-24721-02",
- "System.Text.RegularExpressions": "4.4.0-beta-24721-02",
- "System.Xml.XmlDocument": "4.4.0-beta-24721-02",
- "System.Xml.XmlSerializer": "4.4.0-beta-24721-02",
+ "System.Console": "4.4.0-beta-24810-02",
+ "System.IO": "4.4.0-beta-24810-02",
+ "System.IO.FileSystem": "4.4.0-beta-24810-02",
+ "System.Linq": "4.4.0-beta-24810-02",
+ "System.ObjectModel": "4.4.0-beta-24810-02",
+ "System.Dynamic.Runtime": "4.4.0-beta-24810-02",
+ "System.Reflection": "4.4.0-beta-24810-02",
+ "System.Reflection.Extensions": "4.4.0-beta-24810-02",
+ "System.Reflection.TypeExtensions": "4.4.0-beta-24810-02",
+ "System.Runtime": "4.4.0-beta-24810-02",
+ "System.Runtime.Serialization.Json": "4.4.0-beta-24810-02",
+ "System.Runtime.Serialization.Primitives": "4.4.0-beta-24810-02",
+ "System.Runtime.Serialization.Xml": "4.4.0-beta-24810-02",
+ "System.Text.RegularExpressions": "4.4.0-beta-24810-02",
+ "System.Xml.XmlDocument": "4.4.0-beta-24810-02",
+ "System.Xml.XmlSerializer": "4.4.0-beta-24810-02",
"xunit": "2.2.0-beta2-build3300",
"xunit.console.netcore": "1.0.2-prerelease-00177",
"xunit.runner.utility": "2.2.0-beta2-build3300"
"Microsoft.DotNet.xunit.performance": "1.0.0-alpha-build0040",
"Microsoft.DotNet.xunit.performance.analysis": "1.0.0-alpha-build0040",
"Microsoft.DotNet.xunit.performance.runner.Windows": "1.0.0-alpha-build0040",
- "Microsoft.NETCore.Platforms": "1.2.0-beta-24721-02",
- "System.Collections.NonGeneric": "4.4.0-beta-24721-02",
- "System.Console": "4.4.0-beta-24721-02",
- "System.IO.FileSystem": "4.4.0-beta-24721-02",
- "System.Linq": "4.4.0-beta-24721-02",
- "System.Linq.Expressions": "4.4.0-beta-24721-02",
- "System.Numerics.Vectors": "4.4.0-beta-24721-02",
- "System.Reflection": "4.4.0-beta-24721-02",
- "System.Reflection.Extensions": "4.4.0-beta-24721-02",
- "System.Reflection.TypeExtensions": "4.4.0-beta-24721-02",
- "System.Runtime": "4.4.0-beta-24721-02",
- "System.Runtime.Extensions": "4.4.0-beta-24721-02",
- "System.Runtime.Numerics": "4.4.0-beta-24721-02",
- "System.Text.RegularExpressions": "4.4.0-beta-24721-02",
- "System.Threading": "4.4.0-beta-24721-02",
- "System.Threading.Tasks": "4.4.0-beta-24721-02",
- "System.Threading.Tasks.Parallel": "4.4.0-beta-24721-02",
- "System.Diagnostics.Process": "4.4.0-beta-24721-02",
- "System.Xml.XmlDocument": "4.4.0-beta-24721-02",
- "System.Xml.XPath": "4.4.0-beta-24721-02",
- "System.Xml.XPath.XmlDocument": "4.4.0-beta-24721-02",
+ "Microsoft.NETCore.Platforms": "1.2.0-beta-24810-02",
+ "System.Collections.NonGeneric": "4.4.0-beta-24810-02",
+ "System.Console": "4.4.0-beta-24810-02",
+ "System.IO.FileSystem": "4.4.0-beta-24810-02",
+ "System.Linq": "4.4.0-beta-24810-02",
+ "System.Linq.Expressions": "4.4.0-beta-24810-02",
+ "System.Numerics.Vectors": "4.4.0-beta-24810-02",
+ "System.Reflection": "4.4.0-beta-24810-02",
+ "System.Reflection.Extensions": "4.4.0-beta-24810-02",
+ "System.Reflection.TypeExtensions": "4.4.0-beta-24810-02",
+ "System.Runtime": "4.4.0-beta-24810-02",
+ "System.Runtime.Extensions": "4.4.0-beta-24810-02",
+ "System.Runtime.Numerics": "4.4.0-beta-24810-02",
+ "System.Text.RegularExpressions": "4.4.0-beta-24810-02",
+ "System.Threading": "4.4.0-beta-24810-02",
+ "System.Threading.Tasks": "4.4.0-beta-24810-02",
+ "System.Threading.Tasks.Parallel": "4.4.0-beta-24810-02",
+ "System.Diagnostics.Process": "4.4.0-beta-24810-02",
+ "System.Xml.XmlDocument": "4.4.0-beta-24810-02",
+ "System.Xml.XPath": "4.4.0-beta-24810-02",
+ "System.Xml.XPath.XmlDocument": "4.4.0-beta-24810-02",
"xunit": "2.2.0-beta2-build3300",
"xunit.console.netcore": "1.0.2-prerelease-00177",
"xunit.runner.utility": "2.2.0-beta2-build3300"
{
"dependencies": {
- "Microsoft.NETCore.Platforms": "1.2.0-beta-24721-02",
- "System.Collections": "4.4.0-beta-24721-02",
- "System.Console": "4.4.0-beta-24721-02",
- "System.Diagnostics.Debug": "4.4.0-beta-24721-02",
- "System.Runtime.InteropServices.RuntimeInformation": "4.4.0-beta-24721-02",
- "System.Diagnostics.Process": "4.4.0-beta-24721-02",
- "System.Globalization": "4.4.0-beta-24721-02",
- "System.IO": "4.4.0-beta-24721-02",
- "System.IO.FileSystem": "4.4.0-beta-24721-02",
- "System.Reflection": "4.4.0-beta-24721-02",
- "System.Reflection.Extensions": "4.4.0-beta-24721-02",
- "System.Reflection.TypeExtensions": "4.4.0-beta-24721-02",
- "System.Runtime": "4.4.0-beta-24721-02",
- "System.Runtime.Extensions": "4.4.0-beta-24721-02",
- "System.Runtime.CompilerServices.Unsafe": "4.4.0-beta-24721-02",
- "System.Runtime.InteropServices": "4.4.0-beta-24721-02"
+ "Microsoft.NETCore.Platforms": "1.2.0-beta-24810-02",
+ "System.Collections": "4.4.0-beta-24810-02",
+ "System.Console": "4.4.0-beta-24810-02",
+ "System.Diagnostics.Debug": "4.4.0-beta-24810-02",
+ "System.Runtime.InteropServices.RuntimeInformation": "4.4.0-beta-24810-02",
+ "System.Diagnostics.Process": "4.4.0-beta-24810-02",
+ "System.Globalization": "4.4.0-beta-24810-02",
+ "System.IO": "4.4.0-beta-24810-02",
+ "System.IO.FileSystem": "4.4.0-beta-24810-02",
+ "System.Reflection": "4.4.0-beta-24810-02",
+ "System.Reflection.Extensions": "4.4.0-beta-24810-02",
+ "System.Reflection.TypeExtensions": "4.4.0-beta-24810-02",
+ "System.Runtime": "4.4.0-beta-24810-02",
+ "System.Runtime.Extensions": "4.4.0-beta-24810-02",
+ "System.Runtime.CompilerServices.Unsafe": "4.4.0-beta-24810-02",
+ "System.Runtime.InteropServices": "4.4.0-beta-24810-02"
},
"frameworks": {
"netcoreapp1.1": {}
{
"dependencies": {
- "Microsoft.NETCore.Platforms": "1.2.0-beta-24721-02",
- "System.Console": "4.4.0-beta-24721-02",
- "System.Runtime": "4.4.0-beta-24721-02",
- "System.Runtime.Extensions": "4.4.0-beta-24721-02",
- "System.Runtime.InteropServices": "4.4.0-beta-24721-02"
+ "Microsoft.NETCore.Platforms": "1.2.0-beta-24810-02",
+ "System.Console": "4.4.0-beta-24810-02",
+ "System.Runtime": "4.4.0-beta-24810-02",
+ "System.Runtime.Extensions": "4.4.0-beta-24810-02",
+ "System.Runtime.InteropServices": "4.4.0-beta-24810-02"
},
"frameworks": {
"netcoreapp1.1": {}
{
"dependencies": {
- "Microsoft.NETCore.Platforms": "1.2.0-beta-24721-02",
- "System.Console": "4.4.0-beta-24721-02",
- "System.Numerics.Vectors": "4.4.0-beta-24721-02",
- "System.Runtime": "4.4.0-beta-24721-02",
- "System.Runtime.Extensions": "4.4.0-beta-24721-02",
- "System.Threading": "4.4.0-beta-24721-02",
- "System.Threading.Thread": "4.4.0-beta-24721-02"
+ "Microsoft.NETCore.Platforms": "1.2.0-beta-24810-02",
+ "System.Console": "4.4.0-beta-24810-02",
+ "System.Numerics.Vectors": "4.4.0-beta-24810-02",
+ "System.Runtime": "4.4.0-beta-24810-02",
+ "System.Runtime.Extensions": "4.4.0-beta-24810-02",
+ "System.Threading": "4.4.0-beta-24810-02",
+ "System.Threading.Thread": "4.4.0-beta-24810-02"
},
"frameworks": {
"netcoreapp1.1": {}
{
"dependencies": {
- "Microsoft.NETCore.Platforms": "1.2.0-beta-24721-02",
- "System.Console": "4.4.0-beta-24721-02",
- "System.Runtime": "4.4.0-beta-24721-02",
- "System.Runtime.Extensions": "4.4.0-beta-24721-02",
- "System.Threading": "4.4.0-beta-24721-02"
+ "Microsoft.NETCore.Platforms": "1.2.0-beta-24810-02",
+ "System.Console": "4.4.0-beta-24810-02",
+ "System.Runtime": "4.4.0-beta-24810-02",
+ "System.Runtime.Extensions": "4.4.0-beta-24810-02",
+ "System.Threading": "4.4.0-beta-24810-02"
},
"frameworks": {
"netcoreapp1.1": {}
"Microsoft.DotNet.xunit.performance": "1.0.0-alpha-build0040",
"Microsoft.DotNet.xunit.performance.analysis": "1.0.0-alpha-build0040",
"Microsoft.DotNet.xunit.performance.runner.Windows": "1.0.0-alpha-build0040",
- "Microsoft.NETCore.Platforms": "1.2.0-beta-24721-02",
- "System.Collections.NonGeneric": "4.4.0-beta-24721-02",
- "System.Console": "4.4.0-beta-24721-02",
- "System.IO.FileSystem": "4.4.0-beta-24721-02",
- "System.Linq": "4.4.0-beta-24721-02",
- "System.Linq.Expressions": "4.4.0-beta-24721-02",
- "System.Numerics.Vectors": "4.4.0-beta-24721-02",
- "System.Reflection": "4.4.0-beta-24721-02",
- "System.Reflection.Extensions": "4.4.0-beta-24721-02",
- "System.Reflection.TypeExtensions": "4.4.0-beta-24721-02",
- "System.Runtime": "4.4.0-beta-24721-02",
- "System.Runtime.Extensions": "4.4.0-beta-24721-02",
- "System.Runtime.Numerics": "4.4.0-beta-24721-02",
- "System.Text.RegularExpressions": "4.4.0-beta-24721-02",
- "System.Threading": "4.4.0-beta-24721-02",
- "System.Threading.Tasks": "4.4.0-beta-24721-02",
- "System.Threading.Tasks.Parallel": "4.4.0-beta-24721-02",
- "System.Diagnostics.Process": "4.4.0-beta-24721-02",
- "System.Xml.XmlDocument": "4.4.0-beta-24721-02",
- "System.Xml.XPath": "4.4.0-beta-24721-02",
- "System.Xml.XPath.XmlDocument": "4.4.0-beta-24721-02",
+ "Microsoft.NETCore.Platforms": "1.2.0-beta-24810-02",
+ "System.Collections.NonGeneric": "4.4.0-beta-24810-02",
+ "System.Console": "4.4.0-beta-24810-02",
+ "System.IO.FileSystem": "4.4.0-beta-24810-02",
+ "System.Linq": "4.4.0-beta-24810-02",
+ "System.Linq.Expressions": "4.4.0-beta-24810-02",
+ "System.Numerics.Vectors": "4.4.0-beta-24810-02",
+ "System.Reflection": "4.4.0-beta-24810-02",
+ "System.Reflection.Extensions": "4.4.0-beta-24810-02",
+ "System.Reflection.TypeExtensions": "4.4.0-beta-24810-02",
+ "System.Runtime": "4.4.0-beta-24810-02",
+ "System.Runtime.Extensions": "4.4.0-beta-24810-02",
+ "System.Runtime.Numerics": "4.4.0-beta-24810-02",
+ "System.Text.RegularExpressions": "4.4.0-beta-24810-02",
+ "System.Threading": "4.4.0-beta-24810-02",
+ "System.Threading.Tasks": "4.4.0-beta-24810-02",
+ "System.Threading.Tasks.Parallel": "4.4.0-beta-24810-02",
+ "System.Diagnostics.Process": "4.4.0-beta-24810-02",
+ "System.Xml.XmlDocument": "4.4.0-beta-24810-02",
+ "System.Xml.XPath": "4.4.0-beta-24810-02",
+ "System.Xml.XPath.XmlDocument": "4.4.0-beta-24810-02",
"xunit": "2.2.0-beta2-build3300",
"xunit.console.netcore": "1.0.2-prerelease-00177",
"xunit.runner.utility": "2.2.0-beta2-build3300"