From f62e93416a1799aecc6b0947adad55a0d9870732 Mon Sep 17 00:00:00 2001 From: Jeremy Koritzinsky Date: Fri, 29 May 2020 17:37:12 -0700 Subject: [PATCH] Remove built-in WinRT support from the runtime (#36715) --- docs/coding-guidelines/project-guidelines.md | 5 +- docs/design/features/WinRT-activation.md | 53 - docs/design/features/host-components.md | 5 +- docs/design/features/localization-options.md | 8 +- docs/design/features/native-hosting.md | 2 +- eng/Signing.props | 1 - eng/Versions.props | 2 - src/coreclr/clr.featuredefines.props | 2 - src/coreclr/clrdefinitions.cmake | 2 - src/coreclr/src/CMakeLists.txt | 1 - .../src/System.Private.CoreLib/ILLinkTrim.xml | 3 - .../System.Private.CoreLib.csproj | 54 - .../WindowsRuntime/ActivationFactoryLoader.cs | 71 - .../WindowsRuntime/ExceptionSupport.cs | 76 - .../src/Microsoft/Win32/UnsafeNativeMethods.cs | 20 - .../src/System/Environment.CoreCLR.cs | 15 - .../src/System/Exception.CoreCLR.cs | 67 - .../Runtime/InteropServices/Marshal.CoreCLR.cs | 16 - .../BindableVectorToCollectionAdapter.cs | 92 - .../WindowsRuntime/BindableVectorToListAdapter.cs | 217 -- .../WindowsRuntime/CLRIKeyValuePairImpl.cs | 54 - .../WindowsRuntime/CLRIPropertyValueImpl.cs | 517 ---- .../WindowsRuntime/CLRIReferenceImpl.cs | 353 --- .../WindowsRuntime/ConstantSplittableMap.cs | 194 -- .../WindowsRuntime/CustomPropertyImpl.cs | 102 - .../WindowsRuntime/DictionaryKeyCollection.cs | 113 - .../WindowsRuntime/DictionaryToMapAdapter.cs | 102 - .../WindowsRuntime/DictionaryValueCollection.cs | 117 - .../WindowsRuntime/EnumeratorToIteratorAdapter.cs | 156 -- .../WindowsRuntime/EventRegistrationTokenTable.cs | 246 -- .../InteropServices/WindowsRuntime/IClosable.cs | 48 - .../WindowsRuntime/ICustomProperty.cs | 40 - .../WindowsRuntime/ICustomPropertyProvider.cs | 519 ---- .../InteropServices/WindowsRuntime/IIterable.cs | 27 - .../InteropServices/WindowsRuntime/IIterator.cs | 44 - .../Runtime/InteropServices/WindowsRuntime/IMap.cs | 46 - .../IMapViewToIReadOnlyDictionaryAdapter.cs | 299 --- .../WindowsRuntime/IPropertyValue.cs | 125 - .../IReadOnlyDictionaryToIMapViewAdapter.cs | 74 - .../IReadOnlyListToIVectorViewAdapter.cs | 130 - .../InteropServices/WindowsRuntime/IReference.cs | 25 - .../WindowsRuntime/IRestrictedErrorInfo.cs | 19 - .../InteropServices/WindowsRuntime/IVector.cs | 87 - .../IVectorViewToIReadOnlyListAdapter.cs | 74 - .../WindowsRuntime/IteratorToEnumeratorAdapter.cs | 199 -- .../WindowsRuntime/ListToBindableVectorAdapter.cs | 170 -- .../ListToBindableVectorViewAdapter.cs | 76 - .../WindowsRuntime/ListToVectorAdapter.cs | 235 -- .../WindowsRuntime/ManagedActivationFactory.cs | 69 - .../WindowsRuntime/MapToCollectionAdapter.cs | 169 -- .../WindowsRuntime/MapToDictionaryAdapter.cs | 161 -- .../MapViewToReadOnlyCollectionAdapter.cs | 59 - .../WindowsRuntime/NativeMethods.cs | 45 - .../WindowsRuntime/PropertyValue.cs | 55 - .../InteropServices/WindowsRuntime/RuntimeClass.cs | 106 - .../WindowsRuntime/VectorToCollectionAdapter.cs | 109 - .../WindowsRuntime/VectorToListAdapter.cs | 157 -- .../VectorViewToReadOnlyCollectionAdapter.cs | 38 - .../WindowsFoundationEventHandler.cs | 11 - .../WindowsRuntime/WindowsRuntimeMarshal.cs | 1298 ---------- .../WindowsRuntime/WindowsRuntimeMetadata.cs | 62 - .../Runtime/Loader/AssemblyLoadContext.CoreCLR.cs | 20 - .../src/System/RuntimeHandles.cs | 11 +- .../src/System/RuntimeType.CoreCLR.cs | 16 +- .../src/System/StubHelpers.cs | 523 +--- .../System/Threading/SynchronizationContext.Uap.cs | 81 - .../System/Threading/Tasks/AsyncCausalityTracer.cs | 192 -- .../Tasks/IAsyncCausalityTracerStatics.cs | 98 - .../src/System/Type.CoreCLR.cs | 24 - .../src/System/__ComObject.cs | 22 - src/coreclr/src/binder/applicationcontext.cpp | 11 - src/coreclr/src/binder/assemblybinder.cpp | 23 +- src/coreclr/src/binder/assemblyname.cpp | 4 - src/coreclr/src/binder/bindertracing.cpp | 6 +- src/coreclr/src/debug/daccess/daccess.cpp | 129 +- src/coreclr/src/debug/daccess/dacdbiimpl.cpp | 94 +- src/coreclr/src/debug/daccess/nidump.cpp | 15 +- src/coreclr/src/debug/daccess/request.cpp | 7 - src/coreclr/src/debug/di/module.cpp | 42 - src/coreclr/src/debug/di/process.cpp | 7 - src/coreclr/src/debug/di/rsappdomain.cpp | 117 - src/coreclr/src/debug/di/rspriv.h | 10 - src/coreclr/src/debug/ee/dactable.cpp | 3 +- src/coreclr/src/dlls/mscordac/CMakeLists.txt | 6 - src/coreclr/src/dlls/mscordbi/CMakeLists.txt | 4 - .../src/dlls/mscoree/coreclr/CMakeLists.txt | 4 - src/coreclr/src/dlls/mscorrc/mscorrc.rc | 41 +- src/coreclr/src/dlls/mscorrc/resource.h | 35 +- src/coreclr/src/hosts/corerun/corerun.cpp | 22 +- src/coreclr/src/ilasm/CMakeLists.txt | 1 - src/coreclr/src/ildasm/exe/CMakeLists.txt | 1 - src/coreclr/src/inc/CrstTypes.def | 7 - src/coreclr/src/inc/clrconfigvalues.h | 6 - src/coreclr/src/inc/clrprivbinderutil.h | 176 -- src/coreclr/src/inc/clrprivbinding.idl | 12 - src/coreclr/src/inc/cor.h | 21 - src/coreclr/src/inc/corcompile.h | 22 - src/coreclr/src/inc/coregen.h | 2 - src/coreclr/src/inc/corhost.h | 10 - src/coreclr/src/inc/corpriv.h | 2 +- src/coreclr/src/inc/crsttypes.h | 264 +- src/coreclr/src/inc/dacvars.h | 2 - src/coreclr/src/inc/winrt/paraminstanceapi.h | 1756 ------------- src/coreclr/src/inc/winrt/windowsruntime.h | 52 - src/coreclr/src/inc/winrt/windowsstring.h | 774 ------ src/coreclr/src/inc/winrtprojectedtypes.h | 271 -- src/coreclr/src/inc/zapper.h | 4 - src/coreclr/src/md/CMakeLists.txt | 3 - src/coreclr/src/md/compiler/disp.cpp | 15 +- src/coreclr/src/md/compiler/importhelper.cpp | 2 +- src/coreclr/src/md/compiler/regmeta.cpp | 3 - src/coreclr/src/md/compiler/regmeta.h | 2 - src/coreclr/src/md/enc/mdinternalrw.cpp | 4 - src/coreclr/src/md/inc/metamodel.h | 24 +- src/coreclr/src/md/inc/verifylayouts.h | 1 - src/coreclr/src/md/inc/winmdinterfaces.h | 112 - src/coreclr/src/md/runtime/CMakeLists.txt | 1 - src/coreclr/src/md/runtime/mdinternaldisp.cpp | 15 +- src/coreclr/src/md/runtime/mdinternalro.h | 2 +- src/coreclr/src/md/winmd/CMakeLists.txt | 44 - src/coreclr/src/md/winmd/adapter.cpp | 2740 -------------------- src/coreclr/src/md/winmd/inc/adapter.h | 942 ------- src/coreclr/src/md/winmd/inc/memotable.h | 205 -- src/coreclr/src/md/winmd/stdafx.cpp | 12 - src/coreclr/src/md/winmd/stdafx.h | 29 - src/coreclr/src/md/winmd/winmdimport.cpp | 2138 --------------- src/coreclr/src/md/winmd/winmdinternalimportro.cpp | 1721 ------------ .../src/pal/prebuilt/idl/clrprivbinding_i.cpp | 3 - src/coreclr/src/pal/prebuilt/inc/clrprivbinding.h | 77 - src/coreclr/src/tools/crossgen/CMakeLists.txt | 1 - src/coreclr/src/tools/crossgen/compare.bat | 22 +- src/coreclr/src/tools/crossgen/crossgen.cpp | 136 +- .../ReadyToRun/AttributePresenceFilterNode.cs | 17 +- src/coreclr/src/tools/r2rtest/CompilerRunner.cs | 1 - src/coreclr/src/utilcode/pedecoder.cpp | 10 +- src/coreclr/src/vm/.vscode/c_cpp_properties.json | 1 - src/coreclr/src/vm/CMakeLists.txt | 21 - src/coreclr/src/vm/appdomain.cpp | 679 ----- src/coreclr/src/vm/appdomain.hpp | 186 -- src/coreclr/src/vm/assembly.cpp | 122 +- src/coreclr/src/vm/assembly.hpp | 36 +- src/coreclr/src/vm/assemblynative.cpp | 22 +- src/coreclr/src/vm/assemblynative.hpp | 3 - src/coreclr/src/vm/assemblyspec.cpp | 151 +- src/coreclr/src/vm/assemblyspec.hpp | 25 +- src/coreclr/src/vm/baseassemblyspec.cpp | 56 +- src/coreclr/src/vm/baseassemblyspec.h | 38 +- src/coreclr/src/vm/baseassemblyspec.inl | 63 - src/coreclr/src/vm/callhelpers.cpp | 3 +- src/coreclr/src/vm/ceeload.cpp | 467 +--- src/coreclr/src/vm/ceeload.h | 36 +- src/coreclr/src/vm/class.cpp | 105 +- src/coreclr/src/vm/class.h | 55 +- src/coreclr/src/vm/class.inl | 1 - src/coreclr/src/vm/classcompat.cpp | 2 +- src/coreclr/src/vm/classlayoutinfo.cpp | 21 +- src/coreclr/src/vm/classnames.h | 29 - src/coreclr/src/vm/clrex.cpp | 228 +- src/coreclr/src/vm/clrex.h | 27 +- src/coreclr/src/vm/clrprivbinderutil.cpp | 26 - src/coreclr/src/vm/clrprivbinderwinrt.cpp | 1113 -------- src/coreclr/src/vm/clrprivbinderwinrt.h | 326 --- src/coreclr/src/vm/clrprivtypecachewinrt.cpp | 238 -- src/coreclr/src/vm/clrprivtypecachewinrt.h | 70 - src/coreclr/src/vm/clrtocomcall.cpp | 229 +- src/coreclr/src/vm/clrtocomcall.h | 2 - src/coreclr/src/vm/clsload.cpp | 113 +- src/coreclr/src/vm/clsload.hpp | 5 +- src/coreclr/src/vm/comcallablewrapper.cpp | 1003 +------ src/coreclr/src/vm/comcallablewrapper.h | 372 +-- src/coreclr/src/vm/comdelegate.cpp | 101 +- src/coreclr/src/vm/comdelegate.h | 3 - src/coreclr/src/vm/cominterfacemarshaler.cpp | 505 +--- src/coreclr/src/vm/cominterfacemarshaler.h | 13 - src/coreclr/src/vm/commodule.cpp | 2 +- src/coreclr/src/vm/common.h | 8 - src/coreclr/src/vm/commtmemberinfomap.cpp | 18 +- src/coreclr/src/vm/compile.cpp | 499 +--- src/coreclr/src/vm/compile.h | 11 - src/coreclr/src/vm/comtoclrcall.cpp | 106 +- src/coreclr/src/vm/comtoclrcall.h | 34 +- src/coreclr/src/vm/corhost.cpp | 110 +- src/coreclr/src/vm/crossgen/CMakeLists.txt | 12 - src/coreclr/src/vm/crossgenroparsetypename.cpp | 494 ---- src/coreclr/src/vm/crossgenroresolvenamespace.cpp | 194 -- src/coreclr/src/vm/crossgenroresolvenamespace.h | 27 - src/coreclr/src/vm/dllimport.cpp | 724 +----- src/coreclr/src/vm/dllimport.h | 27 +- src/coreclr/src/vm/domainfile.cpp | 40 - src/coreclr/src/vm/ecall.cpp | 7 +- src/coreclr/src/vm/ecalllist.h | 79 - src/coreclr/src/vm/eedbginterfaceimpl.cpp | 3 +- src/coreclr/src/vm/eventtrace.cpp | 23 +- src/coreclr/src/vm/excep.cpp | 97 +- src/coreclr/src/vm/excep.h | 4 - src/coreclr/src/vm/fieldmarshaler.cpp | 46 +- src/coreclr/src/vm/fieldmarshaler.h | 3 +- src/coreclr/src/vm/frameworkexceptionloader.cpp | 97 - src/coreclr/src/vm/frameworkexceptionloader.h | 26 - src/coreclr/src/vm/gcenv.h | 4 - src/coreclr/src/vm/gchelpers.cpp | 4 +- src/coreclr/src/vm/generics.cpp | 7 - src/coreclr/src/vm/generics.inl | 98 - src/coreclr/src/vm/genmeth.cpp | 14 +- src/coreclr/src/vm/ilmarshalers.cpp | 1783 +------------ src/coreclr/src/vm/ilmarshalers.h | 417 +-- src/coreclr/src/vm/ilstubcache.cpp | 9 +- src/coreclr/src/vm/ilstubresolver.cpp | 2 - src/coreclr/src/vm/ilstubresolver.h | 2 - src/coreclr/src/vm/interopconverter.cpp | 234 +- src/coreclr/src/vm/interopconverter.h | 32 +- src/coreclr/src/vm/interoplibinterface.cpp | 31 +- src/coreclr/src/vm/interoputil.cpp | 2435 ++--------------- src/coreclr/src/vm/interoputil.h | 67 +- src/coreclr/src/vm/interoputil.inl | 5 +- src/coreclr/src/vm/jitinterface.cpp | 16 +- src/coreclr/src/vm/jupiterobject.h | 91 - src/coreclr/src/vm/marshalnative.cpp | 198 +- src/coreclr/src/vm/marshalnative.h | 6 - src/coreclr/src/vm/metasig.h | 17 - src/coreclr/src/vm/method.hpp | 5 +- src/coreclr/src/vm/methodtable.cpp | 397 +-- src/coreclr/src/vm/methodtable.h | 69 +- src/coreclr/src/vm/methodtable.inl | 78 +- src/coreclr/src/vm/methodtablebuilder.cpp | 304 +-- src/coreclr/src/vm/methodtablebuilder.h | 1 - src/coreclr/src/vm/mlinfo.cpp | 959 +------ src/coreclr/src/vm/mlinfo.h | 221 +- src/coreclr/src/vm/mngstdinterfaces.cpp | 73 +- src/coreclr/src/vm/mscorlib.cpp | 3 - src/coreclr/src/vm/mscorlib.h | 290 +-- src/coreclr/src/vm/mtypes.h | 129 +- src/coreclr/src/vm/multicorejitimpl.h | 2 - src/coreclr/src/vm/multicorejitplayer.cpp | 16 +- src/coreclr/src/vm/namespace.h | 13 - src/coreclr/src/vm/object.h | 15 - src/coreclr/src/vm/olevariant.h | 1 - src/coreclr/src/vm/pefile.cpp | 14 +- src/coreclr/src/vm/pefile.h | 16 +- src/coreclr/src/vm/pefile.inl | 45 +- src/coreclr/src/vm/prestub.cpp | 23 +- src/coreclr/src/vm/proftoeeinterfaceimpl.cpp | 10 +- src/coreclr/src/vm/rcwrefcache.cpp | 22 - src/coreclr/src/vm/rcwrefcache.h | 50 +- src/coreclr/src/vm/rcwwalker.cpp | 952 ------- src/coreclr/src/vm/rcwwalker.h | 152 -- src/coreclr/src/vm/rexcep.h | 50 +- src/coreclr/src/vm/runtimecallablewrapper.cpp | 2090 +-------------- src/coreclr/src/vm/runtimecallablewrapper.h | 460 +--- src/coreclr/src/vm/runtimeexceptionkind.h | 2 - src/coreclr/src/vm/runtimehandles.cpp | 47 +- src/coreclr/src/vm/runtimehandles.h | 10 +- src/coreclr/src/vm/stdinterfaces.cpp | 670 +---- src/coreclr/src/vm/stdinterfaces.h | 92 +- src/coreclr/src/vm/stdinterfaces_internal.h | 50 - src/coreclr/src/vm/stdinterfaces_wrapper.cpp | 585 ----- src/coreclr/src/vm/stubhelpers.cpp | 544 +--- src/coreclr/src/vm/stubhelpers.h | 24 +- src/coreclr/src/vm/stubmgr.cpp | 79 +- src/coreclr/src/vm/stubmgr.h | 1 - .../src/vm/synchronizationcontextnative.cpp | 152 -- src/coreclr/src/vm/synchronizationcontextnative.h | 27 - src/coreclr/src/vm/threads.cpp | 4 +- src/coreclr/src/vm/typehandle.cpp | 18 +- src/coreclr/src/vm/typehandle.h | 17 +- src/coreclr/src/vm/typehandle.inl | 6 - src/coreclr/src/vm/typeparse.cpp | 61 +- src/coreclr/src/vm/typeparse.h | 11 +- src/coreclr/src/vm/typestring.h | 2 +- src/coreclr/src/vm/vars.cpp | 1 - src/coreclr/src/vm/vars.hpp | 1 - src/coreclr/src/vm/virtualcallstub.cpp | 23 +- src/coreclr/src/vm/winrtdispatcherqueue.h | 101 - src/coreclr/src/vm/winrthelpers.cpp | 163 -- src/coreclr/src/vm/winrthelpers.h | 30 - src/coreclr/src/vm/winrtredirector.h | 143 - src/coreclr/src/vm/winrtredirector.inl | 70 - src/coreclr/src/vm/winrttypenameconverter.cpp | 1050 -------- src/coreclr/src/vm/winrttypenameconverter.h | 126 - src/coreclr/src/vm/wrappers.h | 37 - src/coreclr/src/vm/zapsig.cpp | 43 - src/coreclr/src/zap/zapimage.cpp | 7 +- src/coreclr/src/zap/zapmetadata.cpp | 2 +- src/coreclr/src/zap/zapper.cpp | 32 +- .../src/Common/CoreCLRTestLibrary/Utilities.cs | 9 +- src/coreclr/tests/src/Interop/CMakeLists.txt | 1 - .../ComWrappers/GlobalInstance/GlobalInstance.cs | 9 - .../ReferenceTrackerRuntime.cpp | 8 - .../Interop/WinRT/Contracts/Component.Contracts.cs | 118 - .../WinRT/Contracts/Component.Contracts.idl | 104 - .../src/Interop/WinRT/Contracts/NativeComponent.cs | 16 - .../WinRT/NETClients/Bindings/BindingTests.cs | 58 - .../NETClients/Bindings/NETClientBindings.csproj | 22 - .../WinRT/NETClients/Primitives/ArrayTests.cs | 34 - .../WinRT/NETClients/Primitives/BooleanTests.cs | 17 - .../WinRT/NETClients/Primitives/EnumTests.cs | 17 - .../WinRT/NETClients/Primitives/ExceptionTests.cs | 22 - .../NETClients/Primitives/KeyValuePairTests.cs | 34 - .../Primitives/NETClientPrimitives.csproj | 29 - .../WinRT/NETClients/Primitives/NullableTests.cs | 18 - .../Interop/WinRT/NETClients/Primitives/Program.cs | 38 - .../WinRT/NETClients/Primitives/StringTests.cs | 18 - .../WinRT/NETClients/Primitives/TypeTests.cs | 25 - .../WinRT/NETClients/Primitives/UriTests.cs | 19 - .../Interop/WinRT/NativeComponent/CMakeLists.txt | 114 - .../Component.Contracts.ArrayTesting.cpp | 19 - .../Component.Contracts.ArrayTesting.h | 24 - ...mponent.Contracts.BindingProjectionsTesting.cpp | 20 - ...Component.Contracts.BindingProjectionsTesting.h | 25 - .../Component.Contracts.BindingViewModel.cpp | 40 - .../Component.Contracts.BindingViewModel.h | 163 -- .../Component.Contracts.BooleanTesting.cpp | 13 - .../Component.Contracts.BooleanTesting.h | 23 - .../Component.Contracts.EnumTesting.cpp | 15 - .../Component.Contracts.EnumTesting.h | 21 - .../Component.Contracts.ExceptionTesting.cpp | 18 - .../Component.Contracts.ExceptionTesting.h | 24 - .../Component.Contracts.KeyValuePairTesting.cpp | 49 - .../Component.Contracts.KeyValuePairTesting.h | 25 - .../Component.Contracts.NullableTesting.cpp | 20 - .../Component.Contracts.NullableTesting.h | 24 - .../Component.Contracts.StringTesting.cpp | 13 - .../Component.Contracts.StringTesting.h | 23 - .../Component.Contracts.TypeTesting.cpp | 13 - .../Component.Contracts.TypeTesting.h | 23 - .../Component.Contracts.UriTesting.cpp | 19 - .../Component.Contracts.UriTesting.h | 24 - .../src/Interop/WinRT/NativeComponent/Exports.def | 3 - .../tests/src/Interop/WinRT/NativeComponent/pch.h | 10 - .../WinRT/{NETClients/Bindings => }/Program.cs | 24 +- src/coreclr/tests/src/Interop/WinRT/WinRT.csproj | 13 + .../WindowsRuntimeImportAttribute.cs | 0 src/installer/corehost/build.proj | 3 - src/installer/corehost/cli/CMakeLists.txt | 1 - .../corehost/cli/hostpolicy/hostpolicy.cpp | 6 +- .../corehost/cli/winrthost/CMakeLists.txt | 35 - src/installer/corehost/cli/winrthost/Exports.def | 3 - src/installer/corehost/cli/winrthost/winrthost.cpp | 84 - src/installer/pkg/projects/Directory.Build.targets | 6 +- .../src/localnetcoreapp.override.targets | 18 - .../System/PlatformDetection.Windows.cs | 5 +- .../Microsoft/CSharp/RuntimeBinder/BinderHelper.cs | 30 +- .../CSharp/RuntimeBinder/CSharpConvertBinder.cs | 2 +- .../CSharp/RuntimeBinder/CSharpGetIndexBinder.cs | 2 +- .../CSharp/RuntimeBinder/CSharpGetMemberBinder.cs | 2 +- .../CSharp/RuntimeBinder/CSharpInvokeBinder.cs | 2 +- .../RuntimeBinder/CSharpInvokeMemberBinder.cs | 2 +- .../CSharp/RuntimeBinder/CSharpSetIndexBinder.cs | 2 +- .../CSharp/RuntimeBinder/CSharpSetMemberBinder.cs | 2 +- .../CSharp/RuntimeBinder/RuntimeBinder.cs | 74 - .../RuntimeBinder/Semantics/ExpressionBinder.cs | 49 - .../CSharp/RuntimeBinder/Semantics/MemberLookup.cs | 2 +- .../RuntimeBinder/Semantics/Symbols/EventSymbol.cs | 2 - .../CSharp/RuntimeBinder/Semantics/Types/Type.cs | 2 - .../Microsoft/CSharp/RuntimeBinder/SymbolTable.cs | 76 - .../src/Internal/Resources/PRIExceptionInfo.cs | 12 - .../Resources/WindowsRuntimeResourceManagerBase.cs | 33 - .../Threading/Tasks/AsyncCausalitySupport.cs | 45 - .../src/System.Private.CoreLib.Shared.projitems | 13 - .../src/System/Reflection/EventInfo.cs | 15 - .../src/System/Resources/ResourceManager.Uap.cs | 203 -- .../src/System/Resources/ResourceManager.cs | 13 - .../InteropServices/WindowsRuntime/Attributes.cs | 94 - .../WindowsRuntime/EventRegistrationToken.cs | 34 - .../WindowsRuntime/IActivationFactory.cs | 14 - .../src/System/Threading/SynchronizationContext.cs | 2 - .../src/System/Threading/Tasks/Task.cs | 7 - .../Directory.Build.props | 7 - ...stem.Runtime.InteropServices.WindowsRuntime.sln | 60 - ...ystem.Runtime.InteropServices.WindowsRuntime.cs | 73 - ...m.Runtime.InteropServices.WindowsRuntime.csproj | 12 - .../src/MatchingRefApiCompatBaseline.txt | 8 - .../src/Resources/Strings.resx | 63 - ...m.Runtime.InteropServices.WindowsRuntime.csproj | 26 - ...ime.InteropServices.WindowsRuntime.Tests.csproj | 18 - .../DefaultInterfaceAttributeTests.cs | 20 - .../WindowsRuntime/EmptyAttributeTests.cs | 18 - .../EventRegistrationTokenTableTests.cs | 179 -- .../WindowsRuntime/EventRegistrationTokenTests.cs | 44 - .../InterfaceImplementedInVersionAttributeTests.cs | 25 - .../ReturnValueNameAttributeTests.cs | 20 - .../InteropServices/WindowsRuntime/UnixTests.cs | 89 - .../WindowsRuntime/WindowsRuntimeMarshalTests.cs | 324 --- .../ChangeWrapperHandleStrengthTests.Windows.cs | 1 - .../Marshal/Common/CommonTypes.Windows.cs | 2 + .../Marshal/GetIDispatchForObjectTests.Windows.cs | 6 + .../GetNativeVariantForObjectTests.Windows.cs | 2 - .../Marshal/GetStartComSlotTests.Windows.cs | 9 +- .../Marshal/QueryInterfaceTests.Windows.cs | 4 +- .../InteropServices/Marshal/QueryInterfaceTests.cs | 16 - .../Directory.Build.props | 9 - .../System.Runtime.WindowsRuntime.UI.Xaml.sln | 60 - .../System.Runtime.WindowsRuntime.UI.Xaml.pkgproj | 58 - .../System.Runtime.WindowsRuntime.UI.Xaml.targets | 31 - .../System.Runtime.WindowsRuntime.UI.Xaml.targets | 31 - .../ref/System.Runtime.WindowsRuntime.UI.Xaml.cs | 252 -- .../System.Runtime.WindowsRuntime.UI.Xaml.csproj | 17 - .../src/Resources/Strings.resx | 81 - .../System.Runtime.WindowsRuntime.UI.Xaml.rd.xml | 10 - .../System.Runtime.WindowsRuntime.UI.Xaml.csproj | 45 - .../src/System/Runtime/InteropServices/HResults.cs | 23 - .../Automation/ElementNotAvailableException.cs | 46 - .../Automation/ElementNotEnabledException.cs | 39 - .../Controls/Primitives/GeneratorPosition.cs | 70 - .../src/System/Windows/CornerRadius.cs | 163 -- .../src/System/Windows/Duration.cs | 317 --- .../src/System/Windows/GridLength.cs | 137 - .../src/System/Windows/LayoutCycleException.cs | 46 - .../System/Windows/Markup/XamlParseException.cs | 40 - .../src/System/Windows/Media/Animation/KeyTime.cs | 89 - .../Windows/Media/Animation/RepeatBehavior.cs | 212 -- .../src/System/Windows/Media/Matrix.cs | 262 -- .../src/System/Windows/Media/Media3D/Matrix3D.cs | 708 ----- .../src/System/Windows/Thickness.cs | 129 - .../src/System/Windows/TokenizerHelper.cs | 44 - ...tem.Runtime.WindowsRuntime.UI.Xaml.Tests.csproj | 23 - .../ElementNotAvailableExceptionTests.cs | 43 - .../Automation/ElementNotEnabledExceptionTests.cs | 43 - .../Controls/Primitives/GeneratorPositionTests.cs | 85 - .../tests/Windows/UI/Xaml/CornerRadiusTests.cs | 220 -- .../tests/Windows/UI/Xaml/DurationTests.cs | 174 -- .../tests/Windows/UI/Xaml/GridLengthTests.cs | 125 - .../Windows/UI/Xaml/LayoutCycleExceptionTests.cs | 43 - .../UI/Xaml/Markup/XamlParseExceptionTests.cs | 43 - .../UI/Xaml/Media/Animation/KeyTimeTests.cs | 86 - .../UI/Xaml/Media/Animation/RepeatBehaviorTests.cs | 216 -- .../tests/Windows/UI/Xaml/Media/MatrixTests.cs | 369 --- .../tests/Windows/UI/Xaml/Media3D/Matrix3DTests.cs | 212 -- .../tests/Windows/UI/Xaml/ThicknessTests.cs | 163 -- .../Directory.Build.props | 9 - .../System.Runtime.WindowsRuntime.sln | 88 - .../pkg/System.Runtime.WindowsRuntime.pkgproj | 65 - .../net45/System.Runtime.WindowsRuntime.targets | 32 - .../net451/System.Runtime.WindowsRuntime.targets | 31 - .../net461/System.Runtime.WindowsRuntime.targets | 31 - .../ref/System.Runtime.WindowsRuntime.Manual.cs | 34 - .../ref/System.Runtime.WindowsRuntime.cs | 210 -- .../ref/System.Runtime.WindowsRuntime.csproj | 31 - .../src/MatchingRefApiCompatBaseline.txt | 5 - .../src/PinvokeAnalyzerExceptionList.analyzerdata | 1 - .../src/Resources/Strings.resx | 344 --- .../src/System.Runtime.WindowsRuntime.csproj | 98 - .../src/System/IO/HANDLE_ACCESS_OPTIONS.cs | 33 - .../src/System/IO/HANDLE_CREATION_OPTIONS.cs | 15 - .../src/System/IO/HANDLE_OPTIONS.cs | 19 - .../src/System/IO/HANDLE_SHARING_OPTION.cs | 15 - .../src/System/IO/IStorageFolderHandleAccess.cs | 26 - .../src/System/IO/IStorageItemHandleAccess.cs | 24 - .../src/System/IO/NetFxToWinRtStreamAdapter.cs | 451 ---- .../src/System/IO/StreamOperationAsyncResult.cs | 392 --- .../System/IO/StreamOperationsImplementation.cs | 245 -- .../src/System/IO/WinRtIOHelper.cs | 55 - .../src/System/IO/WinRtToNetFxStreamAdapter.cs | 800 ------ .../System/IO/WindowsRuntimeStorageExtensions.cs | 312 --- .../System/IO/WindowsRuntimeStreamExtensions.cs | 347 --- .../Resources/WindowsRuntimeResourceManager.cs | 652 ----- .../src/System/Runtime/InteropServices/HResults.cs | 26 - .../System/Runtime/InteropServices/IAgileObject.cs | 22 - .../src/System/Runtime/InteropServices/IMarshal.cs | 31 - .../InteropServices/WindowsRuntime/AsyncInfo.cs | 206 -- .../WindowsRuntime/IBufferByteAccess.cs | 23 - .../WindowsRuntime/MarshalingHelpers.cs | 527 ---- .../WindowsRuntime/WindowsRuntimeBuffer.cs | 308 --- .../WindowsRuntimeBufferExtensions.cs | 515 ---- .../System/Threading/Tasks/AsyncInfoIdGenerator.cs | 80 - .../Threading/Tasks/AsyncInfoToTaskBridge.cs | 245 -- .../Threading/Tasks/ExceptionDispatchHelper.cs | 56 - .../Threading/Tasks/TaskToAsyncActionAdapter.cs | 54 - .../Tasks/TaskToAsyncActionWithProgressAdapter.cs | 67 - .../Threading/Tasks/TaskToAsyncInfoAdapter.cs | 1009 ------- .../Threading/Tasks/TaskToAsyncOperationAdapter.cs | 52 - .../TaskToAsyncOperationWithProgressAdapter.cs | 65 - .../WindowsRuntimeSynchronizationContext.cs | 222 -- .../src/System/VoidTypeParameter.cs | 14 - .../src/System/Windows/Point.cs | 118 - .../src/System/Windows/Rect.cs | 350 --- .../src/System/Windows/Size.cs | 157 -- .../src/System/Windows/TokenizerHelper.cs | 55 - .../src/System/Windows/UI/Color.cs | 153 -- .../src/System/WindowsRuntimeSystemExtensions.cs | 461 ---- .../System.Runtime.WindowsRuntime.Tests.rd.xml | 6 - .../System.Runtime.WindowsRuntime.Tests.csproj | 23 - .../tests/System/IO/AsWinRTStreamTests.cs | 397 --- .../tests/System/IO/CreateSafeFileHandleTests.cs | 235 -- .../tests/System/IO/StorageFileMock.cs | 116 - .../tests/System/IO/StorageFolderMock.cs | 102 - .../tests/System/IO/TestStreamProvider.cs | 112 - .../tests/System/IO/WriteOnlyStream.cs | 16 - .../WindowsRuntimeBufferExtensionsTests.cs | 465 ---- .../InteropServices/WindowsRuntimeBufferTests.cs | 99 - .../tests/Windows/Foundation/PointTests.cs | 120 - .../tests/Windows/Foundation/RectTests.cs | 328 --- .../tests/Windows/Foundation/SizeTests.cs | 146 -- .../tests/Windows/UI/ColorTests.cs | 94 - .../System.Runtime/tests/System/ActivatorTests.cs | 16 - src/libraries/pkg/descriptions.json | 28 - .../shims/ApiCompatBaseline.PreviousNetCoreApp.txt | 21 +- 497 files changed, 1407 insertions(+), 64025 deletions(-) delete mode 100644 docs/design/features/WinRT-activation.md delete mode 100644 src/coreclr/src/System.Private.CoreLib/src/Internal/Runtime/InteropServices/WindowsRuntime/ActivationFactoryLoader.cs delete mode 100644 src/coreclr/src/System.Private.CoreLib/src/Internal/Runtime/InteropServices/WindowsRuntime/ExceptionSupport.cs delete mode 100644 src/coreclr/src/System.Private.CoreLib/src/Microsoft/Win32/UnsafeNativeMethods.cs delete mode 100644 src/coreclr/src/System.Private.CoreLib/src/System/Runtime/InteropServices/WindowsRuntime/BindableVectorToCollectionAdapter.cs delete mode 100644 src/coreclr/src/System.Private.CoreLib/src/System/Runtime/InteropServices/WindowsRuntime/BindableVectorToListAdapter.cs delete mode 100644 src/coreclr/src/System.Private.CoreLib/src/System/Runtime/InteropServices/WindowsRuntime/CLRIKeyValuePairImpl.cs delete mode 100644 src/coreclr/src/System.Private.CoreLib/src/System/Runtime/InteropServices/WindowsRuntime/CLRIPropertyValueImpl.cs delete mode 100644 src/coreclr/src/System.Private.CoreLib/src/System/Runtime/InteropServices/WindowsRuntime/CLRIReferenceImpl.cs delete mode 100644 src/coreclr/src/System.Private.CoreLib/src/System/Runtime/InteropServices/WindowsRuntime/ConstantSplittableMap.cs delete mode 100644 src/coreclr/src/System.Private.CoreLib/src/System/Runtime/InteropServices/WindowsRuntime/CustomPropertyImpl.cs delete mode 100644 src/coreclr/src/System.Private.CoreLib/src/System/Runtime/InteropServices/WindowsRuntime/DictionaryKeyCollection.cs delete mode 100644 src/coreclr/src/System.Private.CoreLib/src/System/Runtime/InteropServices/WindowsRuntime/DictionaryToMapAdapter.cs delete mode 100644 src/coreclr/src/System.Private.CoreLib/src/System/Runtime/InteropServices/WindowsRuntime/DictionaryValueCollection.cs delete mode 100644 src/coreclr/src/System.Private.CoreLib/src/System/Runtime/InteropServices/WindowsRuntime/EnumeratorToIteratorAdapter.cs delete mode 100644 src/coreclr/src/System.Private.CoreLib/src/System/Runtime/InteropServices/WindowsRuntime/EventRegistrationTokenTable.cs delete mode 100644 src/coreclr/src/System.Private.CoreLib/src/System/Runtime/InteropServices/WindowsRuntime/IClosable.cs delete mode 100644 src/coreclr/src/System.Private.CoreLib/src/System/Runtime/InteropServices/WindowsRuntime/ICustomProperty.cs delete mode 100644 src/coreclr/src/System.Private.CoreLib/src/System/Runtime/InteropServices/WindowsRuntime/ICustomPropertyProvider.cs delete mode 100644 src/coreclr/src/System.Private.CoreLib/src/System/Runtime/InteropServices/WindowsRuntime/IIterable.cs delete mode 100644 src/coreclr/src/System.Private.CoreLib/src/System/Runtime/InteropServices/WindowsRuntime/IIterator.cs delete mode 100644 src/coreclr/src/System.Private.CoreLib/src/System/Runtime/InteropServices/WindowsRuntime/IMap.cs delete mode 100644 src/coreclr/src/System.Private.CoreLib/src/System/Runtime/InteropServices/WindowsRuntime/IMapViewToIReadOnlyDictionaryAdapter.cs delete mode 100644 src/coreclr/src/System.Private.CoreLib/src/System/Runtime/InteropServices/WindowsRuntime/IPropertyValue.cs delete mode 100644 src/coreclr/src/System.Private.CoreLib/src/System/Runtime/InteropServices/WindowsRuntime/IReadOnlyDictionaryToIMapViewAdapter.cs delete mode 100644 src/coreclr/src/System.Private.CoreLib/src/System/Runtime/InteropServices/WindowsRuntime/IReadOnlyListToIVectorViewAdapter.cs delete mode 100644 src/coreclr/src/System.Private.CoreLib/src/System/Runtime/InteropServices/WindowsRuntime/IReference.cs delete mode 100644 src/coreclr/src/System.Private.CoreLib/src/System/Runtime/InteropServices/WindowsRuntime/IRestrictedErrorInfo.cs delete mode 100644 src/coreclr/src/System.Private.CoreLib/src/System/Runtime/InteropServices/WindowsRuntime/IVector.cs delete mode 100644 src/coreclr/src/System.Private.CoreLib/src/System/Runtime/InteropServices/WindowsRuntime/IVectorViewToIReadOnlyListAdapter.cs delete mode 100644 src/coreclr/src/System.Private.CoreLib/src/System/Runtime/InteropServices/WindowsRuntime/IteratorToEnumeratorAdapter.cs delete mode 100644 src/coreclr/src/System.Private.CoreLib/src/System/Runtime/InteropServices/WindowsRuntime/ListToBindableVectorAdapter.cs delete mode 100644 src/coreclr/src/System.Private.CoreLib/src/System/Runtime/InteropServices/WindowsRuntime/ListToBindableVectorViewAdapter.cs delete mode 100644 src/coreclr/src/System.Private.CoreLib/src/System/Runtime/InteropServices/WindowsRuntime/ListToVectorAdapter.cs delete mode 100644 src/coreclr/src/System.Private.CoreLib/src/System/Runtime/InteropServices/WindowsRuntime/ManagedActivationFactory.cs delete mode 100644 src/coreclr/src/System.Private.CoreLib/src/System/Runtime/InteropServices/WindowsRuntime/MapToCollectionAdapter.cs delete mode 100644 src/coreclr/src/System.Private.CoreLib/src/System/Runtime/InteropServices/WindowsRuntime/MapToDictionaryAdapter.cs delete mode 100644 src/coreclr/src/System.Private.CoreLib/src/System/Runtime/InteropServices/WindowsRuntime/MapViewToReadOnlyCollectionAdapter.cs delete mode 100644 src/coreclr/src/System.Private.CoreLib/src/System/Runtime/InteropServices/WindowsRuntime/NativeMethods.cs delete mode 100644 src/coreclr/src/System.Private.CoreLib/src/System/Runtime/InteropServices/WindowsRuntime/PropertyValue.cs delete mode 100644 src/coreclr/src/System.Private.CoreLib/src/System/Runtime/InteropServices/WindowsRuntime/RuntimeClass.cs delete mode 100644 src/coreclr/src/System.Private.CoreLib/src/System/Runtime/InteropServices/WindowsRuntime/VectorToCollectionAdapter.cs delete mode 100644 src/coreclr/src/System.Private.CoreLib/src/System/Runtime/InteropServices/WindowsRuntime/VectorToListAdapter.cs delete mode 100644 src/coreclr/src/System.Private.CoreLib/src/System/Runtime/InteropServices/WindowsRuntime/VectorViewToReadOnlyCollectionAdapter.cs delete mode 100644 src/coreclr/src/System.Private.CoreLib/src/System/Runtime/InteropServices/WindowsRuntime/WindowsFoundationEventHandler.cs delete mode 100644 src/coreclr/src/System.Private.CoreLib/src/System/Runtime/InteropServices/WindowsRuntime/WindowsRuntimeMarshal.cs delete mode 100644 src/coreclr/src/System.Private.CoreLib/src/System/Runtime/InteropServices/WindowsRuntime/WindowsRuntimeMetadata.cs delete mode 100644 src/coreclr/src/System.Private.CoreLib/src/System/Threading/SynchronizationContext.Uap.cs delete mode 100644 src/coreclr/src/System.Private.CoreLib/src/System/Threading/Tasks/AsyncCausalityTracer.cs delete mode 100644 src/coreclr/src/System.Private.CoreLib/src/System/Threading/Tasks/IAsyncCausalityTracerStatics.cs delete mode 100644 src/coreclr/src/inc/winrt/paraminstanceapi.h delete mode 100644 src/coreclr/src/inc/winrt/windowsruntime.h delete mode 100644 src/coreclr/src/inc/winrt/windowsstring.h delete mode 100644 src/coreclr/src/inc/winrtprojectedtypes.h delete mode 100644 src/coreclr/src/md/inc/winmdinterfaces.h delete mode 100644 src/coreclr/src/md/winmd/CMakeLists.txt delete mode 100644 src/coreclr/src/md/winmd/adapter.cpp delete mode 100644 src/coreclr/src/md/winmd/inc/adapter.h delete mode 100644 src/coreclr/src/md/winmd/inc/memotable.h delete mode 100644 src/coreclr/src/md/winmd/stdafx.cpp delete mode 100644 src/coreclr/src/md/winmd/stdafx.h delete mode 100644 src/coreclr/src/md/winmd/winmdimport.cpp delete mode 100644 src/coreclr/src/md/winmd/winmdinternalimportro.cpp delete mode 100644 src/coreclr/src/vm/clrprivbinderwinrt.cpp delete mode 100644 src/coreclr/src/vm/clrprivbinderwinrt.h delete mode 100644 src/coreclr/src/vm/clrprivtypecachewinrt.cpp delete mode 100644 src/coreclr/src/vm/clrprivtypecachewinrt.h delete mode 100644 src/coreclr/src/vm/crossgenroparsetypename.cpp delete mode 100644 src/coreclr/src/vm/crossgenroresolvenamespace.cpp delete mode 100644 src/coreclr/src/vm/crossgenroresolvenamespace.h delete mode 100644 src/coreclr/src/vm/frameworkexceptionloader.cpp delete mode 100644 src/coreclr/src/vm/frameworkexceptionloader.h delete mode 100644 src/coreclr/src/vm/generics.inl delete mode 100644 src/coreclr/src/vm/jupiterobject.h delete mode 100644 src/coreclr/src/vm/rcwwalker.cpp delete mode 100644 src/coreclr/src/vm/rcwwalker.h delete mode 100644 src/coreclr/src/vm/synchronizationcontextnative.cpp delete mode 100644 src/coreclr/src/vm/synchronizationcontextnative.h delete mode 100644 src/coreclr/src/vm/winrtdispatcherqueue.h delete mode 100644 src/coreclr/src/vm/winrthelpers.cpp delete mode 100644 src/coreclr/src/vm/winrthelpers.h delete mode 100644 src/coreclr/src/vm/winrtredirector.h delete mode 100644 src/coreclr/src/vm/winrtredirector.inl delete mode 100644 src/coreclr/src/vm/winrttypenameconverter.cpp delete mode 100644 src/coreclr/src/vm/winrttypenameconverter.h delete mode 100644 src/coreclr/tests/src/Interop/WinRT/Contracts/Component.Contracts.cs delete mode 100644 src/coreclr/tests/src/Interop/WinRT/Contracts/Component.Contracts.idl delete mode 100644 src/coreclr/tests/src/Interop/WinRT/Contracts/NativeComponent.cs delete mode 100644 src/coreclr/tests/src/Interop/WinRT/NETClients/Bindings/BindingTests.cs delete mode 100644 src/coreclr/tests/src/Interop/WinRT/NETClients/Bindings/NETClientBindings.csproj delete mode 100644 src/coreclr/tests/src/Interop/WinRT/NETClients/Primitives/ArrayTests.cs delete mode 100644 src/coreclr/tests/src/Interop/WinRT/NETClients/Primitives/BooleanTests.cs delete mode 100644 src/coreclr/tests/src/Interop/WinRT/NETClients/Primitives/EnumTests.cs delete mode 100644 src/coreclr/tests/src/Interop/WinRT/NETClients/Primitives/ExceptionTests.cs delete mode 100644 src/coreclr/tests/src/Interop/WinRT/NETClients/Primitives/KeyValuePairTests.cs delete mode 100644 src/coreclr/tests/src/Interop/WinRT/NETClients/Primitives/NETClientPrimitives.csproj delete mode 100644 src/coreclr/tests/src/Interop/WinRT/NETClients/Primitives/NullableTests.cs delete mode 100644 src/coreclr/tests/src/Interop/WinRT/NETClients/Primitives/Program.cs delete mode 100644 src/coreclr/tests/src/Interop/WinRT/NETClients/Primitives/StringTests.cs delete mode 100644 src/coreclr/tests/src/Interop/WinRT/NETClients/Primitives/TypeTests.cs delete mode 100644 src/coreclr/tests/src/Interop/WinRT/NETClients/Primitives/UriTests.cs delete mode 100644 src/coreclr/tests/src/Interop/WinRT/NativeComponent/CMakeLists.txt delete mode 100644 src/coreclr/tests/src/Interop/WinRT/NativeComponent/Component.Contracts.ArrayTesting.cpp delete mode 100644 src/coreclr/tests/src/Interop/WinRT/NativeComponent/Component.Contracts.ArrayTesting.h delete mode 100644 src/coreclr/tests/src/Interop/WinRT/NativeComponent/Component.Contracts.BindingProjectionsTesting.cpp delete mode 100644 src/coreclr/tests/src/Interop/WinRT/NativeComponent/Component.Contracts.BindingProjectionsTesting.h delete mode 100644 src/coreclr/tests/src/Interop/WinRT/NativeComponent/Component.Contracts.BindingViewModel.cpp delete mode 100644 src/coreclr/tests/src/Interop/WinRT/NativeComponent/Component.Contracts.BindingViewModel.h delete mode 100644 src/coreclr/tests/src/Interop/WinRT/NativeComponent/Component.Contracts.BooleanTesting.cpp delete mode 100644 src/coreclr/tests/src/Interop/WinRT/NativeComponent/Component.Contracts.BooleanTesting.h delete mode 100644 src/coreclr/tests/src/Interop/WinRT/NativeComponent/Component.Contracts.EnumTesting.cpp delete mode 100644 src/coreclr/tests/src/Interop/WinRT/NativeComponent/Component.Contracts.EnumTesting.h delete mode 100644 src/coreclr/tests/src/Interop/WinRT/NativeComponent/Component.Contracts.ExceptionTesting.cpp delete mode 100644 src/coreclr/tests/src/Interop/WinRT/NativeComponent/Component.Contracts.ExceptionTesting.h delete mode 100644 src/coreclr/tests/src/Interop/WinRT/NativeComponent/Component.Contracts.KeyValuePairTesting.cpp delete mode 100644 src/coreclr/tests/src/Interop/WinRT/NativeComponent/Component.Contracts.KeyValuePairTesting.h delete mode 100644 src/coreclr/tests/src/Interop/WinRT/NativeComponent/Component.Contracts.NullableTesting.cpp delete mode 100644 src/coreclr/tests/src/Interop/WinRT/NativeComponent/Component.Contracts.NullableTesting.h delete mode 100644 src/coreclr/tests/src/Interop/WinRT/NativeComponent/Component.Contracts.StringTesting.cpp delete mode 100644 src/coreclr/tests/src/Interop/WinRT/NativeComponent/Component.Contracts.StringTesting.h delete mode 100644 src/coreclr/tests/src/Interop/WinRT/NativeComponent/Component.Contracts.TypeTesting.cpp delete mode 100644 src/coreclr/tests/src/Interop/WinRT/NativeComponent/Component.Contracts.TypeTesting.h delete mode 100644 src/coreclr/tests/src/Interop/WinRT/NativeComponent/Component.Contracts.UriTesting.cpp delete mode 100644 src/coreclr/tests/src/Interop/WinRT/NativeComponent/Component.Contracts.UriTesting.h delete mode 100644 src/coreclr/tests/src/Interop/WinRT/NativeComponent/Exports.def delete mode 100644 src/coreclr/tests/src/Interop/WinRT/NativeComponent/pch.h rename src/coreclr/tests/src/Interop/WinRT/{NETClients/Bindings => }/Program.cs (52%) create mode 100644 src/coreclr/tests/src/Interop/WinRT/WinRT.csproj rename src/coreclr/tests/src/Interop/WinRT/{Contracts => }/WindowsRuntimeImportAttribute.cs (100%) delete mode 100644 src/installer/corehost/cli/winrthost/CMakeLists.txt delete mode 100644 src/installer/corehost/cli/winrthost/Exports.def delete mode 100644 src/installer/corehost/cli/winrthost/winrthost.cpp delete mode 100644 src/libraries/System.Private.CoreLib/src/Internal/Resources/PRIExceptionInfo.cs delete mode 100644 src/libraries/System.Private.CoreLib/src/Internal/Resources/WindowsRuntimeResourceManagerBase.cs delete mode 100644 src/libraries/System.Private.CoreLib/src/Internal/Threading/Tasks/AsyncCausalitySupport.cs delete mode 100644 src/libraries/System.Private.CoreLib/src/System/Resources/ResourceManager.Uap.cs delete mode 100644 src/libraries/System.Private.CoreLib/src/System/Runtime/InteropServices/WindowsRuntime/Attributes.cs delete mode 100644 src/libraries/System.Private.CoreLib/src/System/Runtime/InteropServices/WindowsRuntime/EventRegistrationToken.cs delete mode 100644 src/libraries/System.Private.CoreLib/src/System/Runtime/InteropServices/WindowsRuntime/IActivationFactory.cs delete mode 100644 src/libraries/System.Runtime.InteropServices.WindowsRuntime/Directory.Build.props delete mode 100644 src/libraries/System.Runtime.InteropServices.WindowsRuntime/System.Runtime.InteropServices.WindowsRuntime.sln delete mode 100644 src/libraries/System.Runtime.InteropServices.WindowsRuntime/ref/System.Runtime.InteropServices.WindowsRuntime.cs delete mode 100644 src/libraries/System.Runtime.InteropServices.WindowsRuntime/ref/System.Runtime.InteropServices.WindowsRuntime.csproj delete mode 100644 src/libraries/System.Runtime.InteropServices.WindowsRuntime/src/MatchingRefApiCompatBaseline.txt delete mode 100644 src/libraries/System.Runtime.InteropServices.WindowsRuntime/src/Resources/Strings.resx delete mode 100644 src/libraries/System.Runtime.InteropServices.WindowsRuntime/src/System.Runtime.InteropServices.WindowsRuntime.csproj delete mode 100644 src/libraries/System.Runtime.InteropServices.WindowsRuntime/tests/System.Runtime.InteropServices.WindowsRuntime.Tests.csproj delete mode 100644 src/libraries/System.Runtime.InteropServices.WindowsRuntime/tests/System/Runtime/InteropServices/WindowsRuntime/DefaultInterfaceAttributeTests.cs delete mode 100644 src/libraries/System.Runtime.InteropServices.WindowsRuntime/tests/System/Runtime/InteropServices/WindowsRuntime/EmptyAttributeTests.cs delete mode 100644 src/libraries/System.Runtime.InteropServices.WindowsRuntime/tests/System/Runtime/InteropServices/WindowsRuntime/EventRegistrationTokenTableTests.cs delete mode 100644 src/libraries/System.Runtime.InteropServices.WindowsRuntime/tests/System/Runtime/InteropServices/WindowsRuntime/EventRegistrationTokenTests.cs delete mode 100644 src/libraries/System.Runtime.InteropServices.WindowsRuntime/tests/System/Runtime/InteropServices/WindowsRuntime/InterfaceImplementedInVersionAttributeTests.cs delete mode 100644 src/libraries/System.Runtime.InteropServices.WindowsRuntime/tests/System/Runtime/InteropServices/WindowsRuntime/ReturnValueNameAttributeTests.cs delete mode 100644 src/libraries/System.Runtime.InteropServices.WindowsRuntime/tests/System/Runtime/InteropServices/WindowsRuntime/UnixTests.cs delete mode 100644 src/libraries/System.Runtime.InteropServices.WindowsRuntime/tests/System/Runtime/InteropServices/WindowsRuntime/WindowsRuntimeMarshalTests.cs delete mode 100644 src/libraries/System.Runtime.WindowsRuntime.UI.Xaml/Directory.Build.props delete mode 100644 src/libraries/System.Runtime.WindowsRuntime.UI.Xaml/System.Runtime.WindowsRuntime.UI.Xaml.sln delete mode 100644 src/libraries/System.Runtime.WindowsRuntime.UI.Xaml/pkg/System.Runtime.WindowsRuntime.UI.Xaml.pkgproj delete mode 100644 src/libraries/System.Runtime.WindowsRuntime.UI.Xaml/pkg/build/net45/System.Runtime.WindowsRuntime.UI.Xaml.targets delete mode 100644 src/libraries/System.Runtime.WindowsRuntime.UI.Xaml/pkg/build/net461/System.Runtime.WindowsRuntime.UI.Xaml.targets delete mode 100644 src/libraries/System.Runtime.WindowsRuntime.UI.Xaml/ref/System.Runtime.WindowsRuntime.UI.Xaml.cs delete mode 100644 src/libraries/System.Runtime.WindowsRuntime.UI.Xaml/ref/System.Runtime.WindowsRuntime.UI.Xaml.csproj delete mode 100644 src/libraries/System.Runtime.WindowsRuntime.UI.Xaml/src/Resources/Strings.resx delete mode 100644 src/libraries/System.Runtime.WindowsRuntime.UI.Xaml/src/Resources/System.Runtime.WindowsRuntime.UI.Xaml.rd.xml delete mode 100644 src/libraries/System.Runtime.WindowsRuntime.UI.Xaml/src/System.Runtime.WindowsRuntime.UI.Xaml.csproj delete mode 100644 src/libraries/System.Runtime.WindowsRuntime.UI.Xaml/src/System/Runtime/InteropServices/HResults.cs delete mode 100644 src/libraries/System.Runtime.WindowsRuntime.UI.Xaml/src/System/Windows/Automation/ElementNotAvailableException.cs delete mode 100644 src/libraries/System.Runtime.WindowsRuntime.UI.Xaml/src/System/Windows/Automation/ElementNotEnabledException.cs delete mode 100644 src/libraries/System.Runtime.WindowsRuntime.UI.Xaml/src/System/Windows/Controls/Primitives/GeneratorPosition.cs delete mode 100644 src/libraries/System.Runtime.WindowsRuntime.UI.Xaml/src/System/Windows/CornerRadius.cs delete mode 100644 src/libraries/System.Runtime.WindowsRuntime.UI.Xaml/src/System/Windows/Duration.cs delete mode 100644 src/libraries/System.Runtime.WindowsRuntime.UI.Xaml/src/System/Windows/GridLength.cs delete mode 100644 src/libraries/System.Runtime.WindowsRuntime.UI.Xaml/src/System/Windows/LayoutCycleException.cs delete mode 100644 src/libraries/System.Runtime.WindowsRuntime.UI.Xaml/src/System/Windows/Markup/XamlParseException.cs delete mode 100644 src/libraries/System.Runtime.WindowsRuntime.UI.Xaml/src/System/Windows/Media/Animation/KeyTime.cs delete mode 100644 src/libraries/System.Runtime.WindowsRuntime.UI.Xaml/src/System/Windows/Media/Animation/RepeatBehavior.cs delete mode 100644 src/libraries/System.Runtime.WindowsRuntime.UI.Xaml/src/System/Windows/Media/Matrix.cs delete mode 100644 src/libraries/System.Runtime.WindowsRuntime.UI.Xaml/src/System/Windows/Media/Media3D/Matrix3D.cs delete mode 100644 src/libraries/System.Runtime.WindowsRuntime.UI.Xaml/src/System/Windows/Thickness.cs delete mode 100644 src/libraries/System.Runtime.WindowsRuntime.UI.Xaml/src/System/Windows/TokenizerHelper.cs delete mode 100644 src/libraries/System.Runtime.WindowsRuntime.UI.Xaml/tests/System.Runtime.WindowsRuntime.UI.Xaml.Tests.csproj delete mode 100644 src/libraries/System.Runtime.WindowsRuntime.UI.Xaml/tests/Windows/UI/Xaml/Automation/ElementNotAvailableExceptionTests.cs delete mode 100644 src/libraries/System.Runtime.WindowsRuntime.UI.Xaml/tests/Windows/UI/Xaml/Automation/ElementNotEnabledExceptionTests.cs delete mode 100644 src/libraries/System.Runtime.WindowsRuntime.UI.Xaml/tests/Windows/UI/Xaml/Controls/Primitives/GeneratorPositionTests.cs delete mode 100644 src/libraries/System.Runtime.WindowsRuntime.UI.Xaml/tests/Windows/UI/Xaml/CornerRadiusTests.cs delete mode 100644 src/libraries/System.Runtime.WindowsRuntime.UI.Xaml/tests/Windows/UI/Xaml/DurationTests.cs delete mode 100644 src/libraries/System.Runtime.WindowsRuntime.UI.Xaml/tests/Windows/UI/Xaml/GridLengthTests.cs delete mode 100644 src/libraries/System.Runtime.WindowsRuntime.UI.Xaml/tests/Windows/UI/Xaml/LayoutCycleExceptionTests.cs delete mode 100644 src/libraries/System.Runtime.WindowsRuntime.UI.Xaml/tests/Windows/UI/Xaml/Markup/XamlParseExceptionTests.cs delete mode 100644 src/libraries/System.Runtime.WindowsRuntime.UI.Xaml/tests/Windows/UI/Xaml/Media/Animation/KeyTimeTests.cs delete mode 100644 src/libraries/System.Runtime.WindowsRuntime.UI.Xaml/tests/Windows/UI/Xaml/Media/Animation/RepeatBehaviorTests.cs delete mode 100644 src/libraries/System.Runtime.WindowsRuntime.UI.Xaml/tests/Windows/UI/Xaml/Media/MatrixTests.cs delete mode 100644 src/libraries/System.Runtime.WindowsRuntime.UI.Xaml/tests/Windows/UI/Xaml/Media3D/Matrix3DTests.cs delete mode 100644 src/libraries/System.Runtime.WindowsRuntime.UI.Xaml/tests/Windows/UI/Xaml/ThicknessTests.cs delete mode 100644 src/libraries/System.Runtime.WindowsRuntime/Directory.Build.props delete mode 100644 src/libraries/System.Runtime.WindowsRuntime/System.Runtime.WindowsRuntime.sln delete mode 100644 src/libraries/System.Runtime.WindowsRuntime/pkg/System.Runtime.WindowsRuntime.pkgproj delete mode 100644 src/libraries/System.Runtime.WindowsRuntime/pkg/build/net45/System.Runtime.WindowsRuntime.targets delete mode 100644 src/libraries/System.Runtime.WindowsRuntime/pkg/build/net451/System.Runtime.WindowsRuntime.targets delete mode 100644 src/libraries/System.Runtime.WindowsRuntime/pkg/build/net461/System.Runtime.WindowsRuntime.targets delete mode 100644 src/libraries/System.Runtime.WindowsRuntime/ref/System.Runtime.WindowsRuntime.Manual.cs delete mode 100644 src/libraries/System.Runtime.WindowsRuntime/ref/System.Runtime.WindowsRuntime.cs delete mode 100644 src/libraries/System.Runtime.WindowsRuntime/ref/System.Runtime.WindowsRuntime.csproj delete mode 100644 src/libraries/System.Runtime.WindowsRuntime/src/MatchingRefApiCompatBaseline.txt delete mode 100644 src/libraries/System.Runtime.WindowsRuntime/src/PinvokeAnalyzerExceptionList.analyzerdata delete mode 100644 src/libraries/System.Runtime.WindowsRuntime/src/Resources/Strings.resx delete mode 100644 src/libraries/System.Runtime.WindowsRuntime/src/System.Runtime.WindowsRuntime.csproj delete mode 100644 src/libraries/System.Runtime.WindowsRuntime/src/System/IO/HANDLE_ACCESS_OPTIONS.cs delete mode 100644 src/libraries/System.Runtime.WindowsRuntime/src/System/IO/HANDLE_CREATION_OPTIONS.cs delete mode 100644 src/libraries/System.Runtime.WindowsRuntime/src/System/IO/HANDLE_OPTIONS.cs delete mode 100644 src/libraries/System.Runtime.WindowsRuntime/src/System/IO/HANDLE_SHARING_OPTION.cs delete mode 100644 src/libraries/System.Runtime.WindowsRuntime/src/System/IO/IStorageFolderHandleAccess.cs delete mode 100644 src/libraries/System.Runtime.WindowsRuntime/src/System/IO/IStorageItemHandleAccess.cs delete mode 100644 src/libraries/System.Runtime.WindowsRuntime/src/System/IO/NetFxToWinRtStreamAdapter.cs delete mode 100644 src/libraries/System.Runtime.WindowsRuntime/src/System/IO/StreamOperationAsyncResult.cs delete mode 100644 src/libraries/System.Runtime.WindowsRuntime/src/System/IO/StreamOperationsImplementation.cs delete mode 100644 src/libraries/System.Runtime.WindowsRuntime/src/System/IO/WinRtIOHelper.cs delete mode 100644 src/libraries/System.Runtime.WindowsRuntime/src/System/IO/WinRtToNetFxStreamAdapter.cs delete mode 100644 src/libraries/System.Runtime.WindowsRuntime/src/System/IO/WindowsRuntimeStorageExtensions.cs delete mode 100644 src/libraries/System.Runtime.WindowsRuntime/src/System/IO/WindowsRuntimeStreamExtensions.cs delete mode 100644 src/libraries/System.Runtime.WindowsRuntime/src/System/Resources/WindowsRuntimeResourceManager.cs delete mode 100644 src/libraries/System.Runtime.WindowsRuntime/src/System/Runtime/InteropServices/HResults.cs delete mode 100644 src/libraries/System.Runtime.WindowsRuntime/src/System/Runtime/InteropServices/IAgileObject.cs delete mode 100644 src/libraries/System.Runtime.WindowsRuntime/src/System/Runtime/InteropServices/IMarshal.cs delete mode 100644 src/libraries/System.Runtime.WindowsRuntime/src/System/Runtime/InteropServices/WindowsRuntime/AsyncInfo.cs delete mode 100644 src/libraries/System.Runtime.WindowsRuntime/src/System/Runtime/InteropServices/WindowsRuntime/IBufferByteAccess.cs delete mode 100644 src/libraries/System.Runtime.WindowsRuntime/src/System/Runtime/InteropServices/WindowsRuntime/MarshalingHelpers.cs delete mode 100644 src/libraries/System.Runtime.WindowsRuntime/src/System/Runtime/InteropServices/WindowsRuntime/WindowsRuntimeBuffer.cs delete mode 100644 src/libraries/System.Runtime.WindowsRuntime/src/System/Runtime/InteropServices/WindowsRuntime/WindowsRuntimeBufferExtensions.cs delete mode 100644 src/libraries/System.Runtime.WindowsRuntime/src/System/Threading/Tasks/AsyncInfoIdGenerator.cs delete mode 100644 src/libraries/System.Runtime.WindowsRuntime/src/System/Threading/Tasks/AsyncInfoToTaskBridge.cs delete mode 100644 src/libraries/System.Runtime.WindowsRuntime/src/System/Threading/Tasks/ExceptionDispatchHelper.cs delete mode 100644 src/libraries/System.Runtime.WindowsRuntime/src/System/Threading/Tasks/TaskToAsyncActionAdapter.cs delete mode 100644 src/libraries/System.Runtime.WindowsRuntime/src/System/Threading/Tasks/TaskToAsyncActionWithProgressAdapter.cs delete mode 100644 src/libraries/System.Runtime.WindowsRuntime/src/System/Threading/Tasks/TaskToAsyncInfoAdapter.cs delete mode 100644 src/libraries/System.Runtime.WindowsRuntime/src/System/Threading/Tasks/TaskToAsyncOperationAdapter.cs delete mode 100644 src/libraries/System.Runtime.WindowsRuntime/src/System/Threading/Tasks/TaskToAsyncOperationWithProgressAdapter.cs delete mode 100644 src/libraries/System.Runtime.WindowsRuntime/src/System/Threading/WindowsRuntimeSynchronizationContext.cs delete mode 100644 src/libraries/System.Runtime.WindowsRuntime/src/System/VoidTypeParameter.cs delete mode 100644 src/libraries/System.Runtime.WindowsRuntime/src/System/Windows/Point.cs delete mode 100644 src/libraries/System.Runtime.WindowsRuntime/src/System/Windows/Rect.cs delete mode 100644 src/libraries/System.Runtime.WindowsRuntime/src/System/Windows/Size.cs delete mode 100644 src/libraries/System.Runtime.WindowsRuntime/src/System/Windows/TokenizerHelper.cs delete mode 100644 src/libraries/System.Runtime.WindowsRuntime/src/System/Windows/UI/Color.cs delete mode 100644 src/libraries/System.Runtime.WindowsRuntime/src/System/WindowsRuntimeSystemExtensions.cs delete mode 100644 src/libraries/System.Runtime.WindowsRuntime/tests/Resources/System.Runtime.WindowsRuntime.Tests.rd.xml delete mode 100644 src/libraries/System.Runtime.WindowsRuntime/tests/System.Runtime.WindowsRuntime.Tests.csproj delete mode 100644 src/libraries/System.Runtime.WindowsRuntime/tests/System/IO/AsWinRTStreamTests.cs delete mode 100644 src/libraries/System.Runtime.WindowsRuntime/tests/System/IO/CreateSafeFileHandleTests.cs delete mode 100644 src/libraries/System.Runtime.WindowsRuntime/tests/System/IO/StorageFileMock.cs delete mode 100644 src/libraries/System.Runtime.WindowsRuntime/tests/System/IO/StorageFolderMock.cs delete mode 100644 src/libraries/System.Runtime.WindowsRuntime/tests/System/IO/TestStreamProvider.cs delete mode 100644 src/libraries/System.Runtime.WindowsRuntime/tests/System/IO/WriteOnlyStream.cs delete mode 100644 src/libraries/System.Runtime.WindowsRuntime/tests/System/Runtime/InteropServices/WindowsRuntimeBufferExtensionsTests.cs delete mode 100644 src/libraries/System.Runtime.WindowsRuntime/tests/System/Runtime/InteropServices/WindowsRuntimeBufferTests.cs delete mode 100644 src/libraries/System.Runtime.WindowsRuntime/tests/Windows/Foundation/PointTests.cs delete mode 100644 src/libraries/System.Runtime.WindowsRuntime/tests/Windows/Foundation/RectTests.cs delete mode 100644 src/libraries/System.Runtime.WindowsRuntime/tests/Windows/Foundation/SizeTests.cs delete mode 100644 src/libraries/System.Runtime.WindowsRuntime/tests/Windows/UI/ColorTests.cs diff --git a/docs/coding-guidelines/project-guidelines.md b/docs/coding-guidelines/project-guidelines.md index f0050a5..6a8f0ba 100644 --- a/docs/coding-guidelines/project-guidelines.md +++ b/docs/coding-guidelines/project-guidelines.md @@ -169,8 +169,8 @@ The output for the src product build will be a flat runtime folder into the foll `bin\runtime\$(BuildSettings)` -Note: The `BuildSettings` is a global property and not the project setting because we need all projects to output to the same runtime directory no matter which compatible target framework we select and build the project with. -```$(BuildTargetFramework)-$(TargetOS)-(Configuration)-(TargetArchitecture)``` +Note: The `BuildSettings` is a global property and not the project setting because we need all projects to output to the same runtime directory no matter which compatible target framework we select and build the project with. +```$(BuildTargetFramework)-$(TargetOS)-(Configuration)-(TargetArchitecture)``` ## pkg In the pkg directory for the library there should be only **one** `.pkgproj` for the primary package for the library. If the library has platform-specific implementations those should be split into platform specific projects in a subfolder for each platform. (see [Package projects](./package-projects.md)) @@ -216,7 +216,6 @@ Each source file should use the following guidelines - Where `` is the name of something that causes a fork in code that isn't a single configuration. Examples: - `.CoreCLR.cs` - implementation specific to CoreCLR runtime - `.Win32.cs` - implementation based on [Win32](https://en.wikipedia.org/wiki/Windows_API) - - `.WinRT.cs` - implementation based on [WinRT](https://en.wikipedia.org/wiki/Windows_Runtime) ## Define naming convention diff --git a/docs/design/features/WinRT-activation.md b/docs/design/features/WinRT-activation.md deleted file mode 100644 index e8a72d5..0000000 --- a/docs/design/features/WinRT-activation.md +++ /dev/null @@ -1,53 +0,0 @@ -# Managed WinRT Activation of .NET Core components - -As part of supporting a complete story for XAML Islands on .NET Core, we should provide a mechanism of activating .NET Core WinRT components. To do so, we will follow the path of the COM and IJW activations and provide a new host for activating these components in a manner similar to native WinRT components, which we will call the `winrthost`. We are creating a separate host instead of combining with the COM host because the COM and WinRT hosts (although generally similar in design in Windows) have very different activation and resolution paths. As a result, we would not be able to reuse much code at all. Additionally, the WinRT host does not require a `clsidmap` or similar functionality to function. If we were to combine the two hosts, we would have to emit an empty clsidmap when creating the host and modify it even though the WinRT portion has no dependencies on any embedded resources. - -## Requirements - -* Discover all installed versions of .NET Core. -* Load the appropriate version of .NET Core for the class if a .NET Core instance is not running, or validate the currently existing .NET Core instance can satisfy the class requirement. -* Return an [`IActivationFactory`](https://docs.microsoft.com/windows/desktop/api/activation/nn-activation-iactivationfactory) implementation that will construct an instance of the .NET WinRT class. - -## Native WinRT Activation - -In the native (C++/CX, C++/WRL, or C++/WinRT) world, building a WinRT Component named `MyComponent` produces files named `MyComponent.dll`, `MyComponent.winmd`. In this world, the `winmd` contains the metadata describing the types provided by the component, and the code implementing said types is compiled into the `dll`. When an application wants to activate a component, it will call [`RoGetActivationFactory`](https://docs.microsoft.com/windows/desktop/api/roapi/nf-roapi-rogetactivationfactory). The operating system will then search through various areas in the filesystem to find the correct component for the class name. Starting in Windows 10 19H1, there is now support for declaring that specific classes come from components that live side-by-side with the application, similar to Reg-Free COM. After finding the correct component, the OS will load the component via `CoLoadLibrary` and then call the `DllGetActivationFactory` entrypoint, which gets an activation factory for the class by name. - -## Proposed Managed WinRT Activation - -In the managed (.NET) world, we put all of the code that implements the component into the `winmd`. So, when running in an AppContainer/`.appx`, a .NET component only needs one file. However, when outside of an AppContainer, there needs to be some sort of host to activate runtime. We will supply a host that implements the [`DllGetActivationFactory`](https://docs.microsoft.com/previous-versions//br205771(v=vs.85)) entrypoint. When `DllGetActivationFactory` is called, the following will occur: - -1) If a [`.runtimeconfig.json`](https://github.com/dotnet/cli/blob/master/Documentation/specs/runtime-configuration-file.md) file exists adjacent to the shim assembly (`.runtimeconfig.json`), that file will be used to describe CLR configuration details. The documentation for the `.runtimeconfig.json` format defines under what circumstances this file may be optional. -2) Using the existing `hostfxr` library, attempt to discover the desired CLR and target [framework](https://docs.microsoft.com/en-us/dotnet/core/packages#frameworks). - * If a CLR is active with the process, the requested CLR version will be validated against that CLR. If version satisfiability fails, activation will fail. - * If a CLR is **not** active with the process, an attempt will be made to create a satisfying CLR instance. - * Failure to create an instance will result in activation failure. -3) A request to the CLR will be made to load the corresponding WinRT type for the given type name into the runtime. - * This request will use the runtime's current support for resolving WinRT types to correctly resolve them. - * The ability to load an assembly from memory will require exposing a new function that can be called from `hostfxr`, as well as a new API in `System.Private.CoreLib` on a new class in `Internal.Runtime.InteropServices`: - -```csharp -namespace Internal.Runtime.InteropServices.WindowsRuntime -{ - public static class ActivationFactoryLoader - { - public unsafe static int GetActivationFactory( - char* componentPath, - [MarshalAs(UnmanagedType.HString)] string typeName, - [MarshalAs(UnmanagedType.Interface)] out IActivationFactory activationFactory); - } -} -``` - -Note this API would not be exposed outside of `System.Private.CoreLib` unless we decide to do so. The runtime loads WinRT components via a different binder than .NET assemblies, so the WinRT component assemblies themselves will be loaded by the WinRT binder, but all assemblies that the WinRT component depends on will be loaded into an isolated `AssemblyLoadContext`. - -To match the user-visible architecture of native WinRT Activation, when building a Windows Metadata component (`winmdobj`), we will copy the `winrthost` to the user's output directory and rename it to be the same name as the `.winmd` but with a `.dll` extension. For example, if the user creates a project `MyComponent` and is building a Windows Metadata component, we will copy the `winrthost` to the output directory for `MyComponent` and rename it to be `MyComponent.dll`. From a user's perspective, they will activate WinRT objects via `MyComponent.dll`, the same as if the component was a native WinRT component. - -## Error reporting - -If the runtime activation fails, we want to ensure that the user can diagnose the failure. However, we don't want to write directly to the `stderr` of a process that we don't own. So, we will redirect the trace stream to point to a local stream. In the case of failure to activate the runtime, we will report the error code via [`RoOriginateErrorW`](https://docs.microsoft.com/windows/desktop/api/roerrorapi/nf-roerrorapi-rooriginateerrorw), which will present the user with the error according to the error reporting flags they have set via [`RoSetErrorReportingFlags`](https://docs.microsoft.com/windows/desktop/api/roerrorapi/nf-roerrorapi-roseterrorreportingflags). - -## Open issues - -* The tool that converts the `.winmdobj` to a `.winmd`, WinMDExp, is only available in Desktop MSBuild and is not available in the .NET Core MSBuild distribution. Additionally, WinMDExp only supports full PDBs and will fail if given portable PDBs. -* To build a `.winmdobj`, the user will need to reference a contract assembly that includes the `Windows.Foundation` namespace. There are new packages that expose these contract assemblies, but we should ensure that these contract assemblies will be released by the time that we finalize our Managed WinRT Component support. -* Writing unit tests for the WinRT host without modifying system-global state requires the new Reg-Free WinRT support, which is Windows 10 19H1 only. diff --git a/docs/design/features/host-components.md b/docs/design/features/host-components.md index ca351fb..59669d6 100644 --- a/docs/design/features/host-components.md +++ b/docs/design/features/host-components.md @@ -8,15 +8,14 @@ The .NET Core default hosting setup consists of several components which are des * `apphost` (executable) - which is used to give app an actual executable which can be run directly. The executable will be named using the application name. The advantage of having an app-local executable is that it can be customized for each app (not just the name, but icon, OS behavior and so on). * `comhost` (library) - which is used to enable COM server hosting. Component which wants to expose COM server objects will be built with this dynamic library in its output. The `comhost` then acts as the main entry point for the OS. * `ijwhost` (library) - which is used to enable loading of IJW assemblies. The library exposes functionality needed by the C++ compiler to generate mixed mode assemblies. -* `winrthost` (library) - which is used to enable WinRT component hosting. Any component which wants to be a WinRT component will be built with this library in its output. The `winrthost` then acts as the main entry point for the OS (very similar to `comhost`). * `nethost` (library) - which is used by native apps (any app which is not .NET Core) to load .NET Core code dynamically. The entry-point typically does just one thing: it finds the `hostfxr` library and passes control to it. It also exposes the right entry points for its purpose (so the "main" for `dotnet` and `apphost`, the COM exports for `comhost` and so on). * `dotnet` host - `hostfxr` is obtained from the `./host/fxr/` folder (relative to the location of the `dotnet` host). * `apphost`, `comhost` and the others - `hostfxr` is located using this process: 1. The app's folder is searched first. This is either the folder where the entry-point host lives or in case of `apphost` it is the path it has embedded in it as the app path. - 1. If the `DOTNET_ROOT` environment variable is defined, that path is searched - 1. The default shared locations are searched + 2. If the `DOTNET_ROOT` environment variable is defined, that path is searched + 3. The default shared locations are searched ## Host FXR This library finds and resolves the runtime and all the frameworks the app needs. Then it loads the `hostpolicy` library and transfers control to it. diff --git a/docs/design/features/localization-options.md b/docs/design/features/localization-options.md index f2a1b5b..a32be0f 100644 --- a/docs/design/features/localization-options.md +++ b/docs/design/features/localization-options.md @@ -67,7 +67,7 @@ Each host component will include English resource strings by default. If the res `apphost` will have a single localized message. All languages will be included in the executable itself. The message will direct the user to a URL that will contain localized content. -`ijwhost`, `winrthost`, and `nethost` intentionally do not show messages by default. They will not be localized. +`ijwhost`, and `nethost` intentionally do not show messages by default. They will not be localized. `comhost` also intentionally does not show messages, but it does populate an `IErrorInfo` with an error string, allowing consumers to access any error messages. This can take the same approach as `apphost`, but would be a lower priority for localization. @@ -75,7 +75,7 @@ Each host component will include English resource strings by default. If the res `dotnet`, `hostfxr`, and `hostpolicy` are all included as part of a .NET Core install. They can each carry their own separate resources in a known path relative next to their current install locations. -The other entry-point hosts (`apphost`, `comhost`, `ijwhost`, `winrthost`, `nethost`) add some complication as they represent and ship as part of the developer's application or component. They are also the most impactful in terms of file size, as they are not shared across applications the way that other components can be. +The other entry-point hosts (`apphost`, `comhost`, `ijwhost`, `nethost`) add some complication as they represent and ship as part of the developer's application or component. They are also the most impactful in terms of file size, as they are not shared across applications the way that other components can be. The messaging coming from the hosts themselves is a small portion of the host messaging. They are mostly around: - Failure to find `hostfxr` (all hosts) @@ -119,9 +119,9 @@ Possible options for hosts: 2. Option: Shared resource for all hosts (except `dotnet`) - Compatibility requirement for resource shared between hosts -`comhost`, `ijwhost`, `winrthost`, and `nethost` are designed to be consumed by a component that .NET Core does not own and intentionally do not show messages to the user. As such, they sit at a low priority for localization support. +`comhost`, `ijwhost`, and `nethost` are designed to be consumed by a component that .NET Core does not own and intentionally do not show messages to the user. As such, they sit at a low priority for localization support. -`apphost` is the end-user-facing host. The amount of logic and messaging in `apphost` is intentionally limited. The most important message it contains for an end-user is for the missing .NET runtime scenario, so it should not rely on resources installed via the .NET runtime. +`apphost` is the end-user-facing host. The amount of logic and messaging in `apphost` is intentionally limited. The most important message it contains for an end-user is for the missing .NET runtime scenario, so it should not rely on resources installed via the .NET runtime. Embedding resources in the `apphost` would make for the most stream-lined user experience (particularly around deployment). Since the `apphost` is sensitive to size, the number of messages will be pared down to one generic localized message which directs the user to a URL. diff --git a/docs/design/features/native-hosting.md b/docs/design/features/native-hosting.md index fabe5a1..b5a3ea4 100644 --- a/docs/design/features/native-hosting.md +++ b/docs/design/features/native-hosting.md @@ -300,7 +300,7 @@ Starts the runtime and returns a function pointer to specified functionality of * `hdt_load_assembly_and_get_function_pointer` - entry point which loads an assembly (with dependencies) and returns function pointer for a specified static method. See below for details (Loading managed components) * `hdt_com_activation`, `hdt_com_register`, `hdt_com_unregister` - COM activation entry-points - see [COM activation](https://github.com/dotnet/runtime/tree/master/docs/design/features/COM-activation.md) for more details. * `hdt_load_in_memory_assembly` - IJW entry-point - see [IJW activation](https://github.com/dotnet/runtime/tree/master/docs/design/features/IJW-activation.md) for more details. - * `hdt_winrt_activation` - WinRT activation entry-point - see [WinRT activation](https://github.com/dotnet/runtime/tree/master/docs/design/features/WinRT-activation.md) for more details. + * `hdt_winrt_activation` - removed WinRT activation entry-point. This delegate is not supported for .NET 5 or newer. * `delegate` - when successful, the native function pointer to the requested runtime functionality. Initially the function will only work if `hostfxr_initialize_for_runtime_config` was used to initialize the host context. Later on this could be relaxed to allow being used in combination with `hostfxr_initialize_for_dotnet_command_line`. diff --git a/eng/Signing.props b/eng/Signing.props index 463c360..d2bd5b8 100644 --- a/eng/Signing.props +++ b/eng/Signing.props @@ -67,7 +67,6 @@ - diff --git a/eng/Versions.props b/eng/Versions.props index d90c25c..b4838ec 100644 --- a/eng/Versions.props +++ b/eng/Versions.props @@ -90,7 +90,6 @@ 99.99.99-master-20200228.3 99.99.99-master-20200228.3 - 1.0.5 1.7.0 2.0.0-beta1.20253.1 diff --git a/src/coreclr/clr.featuredefines.props b/src/coreclr/clr.featuredefines.props index b407467..151f7b2 100644 --- a/src/coreclr/clr.featuredefines.props +++ b/src/coreclr/clr.featuredefines.props @@ -32,7 +32,6 @@ true true true - true true true true @@ -59,7 +58,6 @@ $(DefineConstants);FEATURE_COMINTEROP $(DefineConstants);FEATURE_COMINTEROP_APARTMENT_SUPPORT $(DefineConstants);FEATURE_COMINTEROP_UNMANAGED_ACTIVATION - $(DefineConstants);FEATURE_COMINTEROP_WINRT_MANAGED_ACTIVATION $(DefineConstants);FEATURE_MANAGED_ETW $(DefineConstants);FEATURE_MANAGED_ETW_CHANNELS $(DefineConstants);FEATURE_PERFTRACING diff --git a/src/coreclr/clrdefinitions.cmake b/src/coreclr/clrdefinitions.cmake index 469e009..c77feb6 100644 --- a/src/coreclr/clrdefinitions.cmake +++ b/src/coreclr/clrdefinitions.cmake @@ -99,7 +99,6 @@ if(CLR_CMAKE_TARGET_WIN32) add_definitions(-DFEATURE_COMINTEROP) add_definitions(-DFEATURE_COMINTEROP_APARTMENT_SUPPORT) add_definitions(-DFEATURE_COMINTEROP_UNMANAGED_ACTIVATION) - add_definitions(-DFEATURE_COMINTEROP_WINRT_MANAGED_ACTIVATION) endif(CLR_CMAKE_TARGET_WIN32) add_definitions(-DFEATURE_BASICFREEZE) @@ -220,7 +219,6 @@ endif(CLR_CMAKE_TARGET_ARCH_AMD64 OR CLR_CMAKE_TARGET_ARCH_ARM64) if(NOT CLR_CMAKE_TARGET_UNIX) add_definitions(-DFEATURE_WIN32_REGISTRY) endif(NOT CLR_CMAKE_TARGET_UNIX) -add_definitions(-DFEATURE_WINMD_RESILIENT) add_definitions(-D_SECURE_SCL=0) add_definitions(-DUNICODE) add_definitions(-D_UNICODE) diff --git a/src/coreclr/src/CMakeLists.txt b/src/coreclr/src/CMakeLists.txt index 262e6b7..68e7221 100644 --- a/src/coreclr/src/CMakeLists.txt +++ b/src/coreclr/src/CMakeLists.txt @@ -1,5 +1,4 @@ include_directories("inc") -include_directories("inc/winrt") include_directories("debug/inc") include_directories("debug/inc/${ARCH_SOURCES_DIR}") include_directories("debug/inc/dump") diff --git a/src/coreclr/src/System.Private.CoreLib/ILLinkTrim.xml b/src/coreclr/src/System.Private.CoreLib/ILLinkTrim.xml index 77dc30f..048818c 100644 --- a/src/coreclr/src/System.Private.CoreLib/ILLinkTrim.xml +++ b/src/coreclr/src/System.Private.CoreLib/ILLinkTrim.xml @@ -62,12 +62,9 @@ - - - @@ -382,9 +331,6 @@ Windows_NT - - true - diff --git a/src/coreclr/src/System.Private.CoreLib/src/Internal/Runtime/InteropServices/WindowsRuntime/ActivationFactoryLoader.cs b/src/coreclr/src/System.Private.CoreLib/src/Internal/Runtime/InteropServices/WindowsRuntime/ActivationFactoryLoader.cs deleted file mode 100644 index a6ddce7..0000000 --- a/src/coreclr/src/System.Private.CoreLib/src/Internal/Runtime/InteropServices/WindowsRuntime/ActivationFactoryLoader.cs +++ /dev/null @@ -1,71 +0,0 @@ -// 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.Collections.Generic; -using System.Runtime.InteropServices; -using System.Runtime.InteropServices.WindowsRuntime; -using System.Runtime.Loader; - -namespace Internal.Runtime.InteropServices.WindowsRuntime -{ - internal static class ActivationFactoryLoader - { - // Collection of all ALCs used for WinRT activation. - // Since each of the assemblies that act as the "key" here are WinRT assemblies - // we don't need to share this dictionary with the COM activation dictionary - // since there will be no overlap. - private static readonly Dictionary s_assemblyLoadContexts = new Dictionary(StringComparer.InvariantCultureIgnoreCase); - - private static AssemblyLoadContext GetALC(string assemblyPath) - { - AssemblyLoadContext? alc; - - lock (s_assemblyLoadContexts) - { - if (!s_assemblyLoadContexts.TryGetValue(assemblyPath, out alc)) - { - alc = new IsolatedComponentLoadContext(assemblyPath); - s_assemblyLoadContexts.Add(assemblyPath, alc); - } - } - - return alc; - } - - /// Get a WinRT activation factory for a given type name. - /// The path to the WinRT component that the type is expected to be defined in. - /// The name of the component type to activate - /// The activation factory - public static unsafe int GetActivationFactory( - char* componentPath, - [MarshalAs(UnmanagedType.HString)] string typeName, - [MarshalAs(UnmanagedType.Interface)] out IActivationFactory? activationFactory) - { - activationFactory = null; - try - { - if (typeName is null) - { - throw new ArgumentNullException(nameof(typeName)); - } - - AssemblyLoadContext context = GetALC(Marshal.PtrToStringUni((IntPtr)componentPath)!); - - Type winRTType = context.LoadTypeForWinRTTypeNameInContext(typeName); - - if (winRTType is null || !winRTType.IsExportedToWindowsRuntime) - { - throw new TypeLoadException(typeName); - } - activationFactory = WindowsRuntimeMarshal.GetManagedActivationFactory(winRTType); - } - catch (Exception ex) - { - return ex.HResult; - } - return 0; - } - } -} diff --git a/src/coreclr/src/System.Private.CoreLib/src/Internal/Runtime/InteropServices/WindowsRuntime/ExceptionSupport.cs b/src/coreclr/src/System.Private.CoreLib/src/Internal/Runtime/InteropServices/WindowsRuntime/ExceptionSupport.cs deleted file mode 100644 index c7feb47..0000000 --- a/src/coreclr/src/System.Private.CoreLib/src/Internal/Runtime/InteropServices/WindowsRuntime/ExceptionSupport.cs +++ /dev/null @@ -1,76 +0,0 @@ -// 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.Diagnostics.CodeAnalysis; -using System.Runtime.InteropServices.WindowsRuntime; - -namespace Internal.Runtime.InteropServices.WindowsRuntime -{ - public static class ExceptionSupport - { - /// - /// Attach restricted error information to the exception if it may apply to that exception, returning - /// back the input value - /// - [return: NotNullIfNotNull("e")] - public static Exception? AttachRestrictedErrorInfo(Exception? e) - { - // If there is no exception, then the restricted error info doesn't apply to it - if (e != null) - { - try - { - // Get the restricted error info for this thread and see if it may correlate to the current - // exception object. Note that in general the thread's IRestrictedErrorInfo is not meant for - // exceptions that are marshaled Windows.Foundation.HResults and instead are intended for - // HRESULT ABI return values. However, in many cases async APIs will set the thread's restricted - // error info as a convention in order to provide extended debugging information for the ErrorCode - // property. - IRestrictedErrorInfo restrictedErrorInfo = UnsafeNativeMethods.GetRestrictedErrorInfo(); - if (restrictedErrorInfo != null) - { - restrictedErrorInfo.GetErrorDetails(out string description, - out int restrictedErrorInfoHResult, - out string restrictedDescription, - out string capabilitySid); - - // Since this is a special case where by convention there may be a correlation, there is not a - // guarantee that the restricted error info does belong to the async error code. In order to - // reduce the risk that we associate incorrect information with the exception object, we need - // to apply a heuristic where we attempt to match the current exception's HRESULT with the - // HRESULT the IRestrictedErrorInfo belongs to. If it is a match we will assume association - // for the IAsyncInfo case. - if (e.HResult == restrictedErrorInfoHResult) - { - restrictedErrorInfo.GetReference(out string errorReference); - - e.AddExceptionDataForRestrictedErrorInfo(restrictedDescription, - errorReference, - capabilitySid, - restrictedErrorInfo); - } - } - } - catch - { - // If we can't get the restricted error info, then proceed as if it isn't associated with this - // error. - } - } - - return e; - } - - /// - /// Report that an exception has occurred which went user unhandled. This allows the global error handler - /// for the application to be invoked to process the error. - /// - /// true if the error was reported, false if not (ie running on Win8) - public static bool ReportUnhandledError(Exception? ex) - { - return WindowsRuntimeMarshal.ReportUnhandledError(ex); - } - } -} diff --git a/src/coreclr/src/System.Private.CoreLib/src/Microsoft/Win32/UnsafeNativeMethods.cs b/src/coreclr/src/System.Private.CoreLib/src/Microsoft/Win32/UnsafeNativeMethods.cs deleted file mode 100644 index 423af0a..0000000 --- a/src/coreclr/src/System.Private.CoreLib/src/Microsoft/Win32/UnsafeNativeMethods.cs +++ /dev/null @@ -1,20 +0,0 @@ -// 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.InteropServices; - -namespace Microsoft.Win32 -{ - internal static class UnsafeNativeMethods - { -#if FEATURE_COMINTEROP - [DllImport("api-ms-win-core-winrt-l1-1-0.dll", PreserveSig = true)] - internal static extern int RoGetActivationFactory( - [MarshalAs(UnmanagedType.HString)] string activatableClassId, - [In] ref Guid iid, - [Out, MarshalAs(UnmanagedType.IInspectable)] out object factory); -#endif - } -} diff --git a/src/coreclr/src/System.Private.CoreLib/src/System/Environment.CoreCLR.cs b/src/coreclr/src/System.Private.CoreLib/src/System/Environment.CoreCLR.cs index f141b1e..8e2a9dc 100644 --- a/src/coreclr/src/System.Private.CoreLib/src/System/Environment.CoreCLR.cs +++ b/src/coreclr/src/System.Private.CoreLib/src/System/Environment.CoreCLR.cs @@ -110,20 +110,5 @@ namespace System [MethodImpl(MethodImplOptions.InternalCall)] get; } - -#if FEATURE_COMINTEROP - // Separate type so a .cctor is not created for Enviroment which then would be triggered during startup - private static class WinRT - { - // Cache the value in readonly static that can be optimized out by the JIT - public static readonly bool IsSupported = WinRTSupported() != Interop.BOOL.FALSE; - } - - // Does the current version of Windows have Windows Runtime suppport? - internal static bool IsWinRTSupported => WinRT.IsSupported; - - [DllImport(RuntimeHelpers.QCall, CharSet = CharSet.Unicode)] - private static extern Interop.BOOL WinRTSupported(); -#endif // FEATURE_COMINTEROP } } diff --git a/src/coreclr/src/System.Private.CoreLib/src/System/Exception.CoreCLR.cs b/src/coreclr/src/System.Private.CoreLib/src/System/Exception.CoreCLR.cs index 903760a..165811f 100644 --- a/src/coreclr/src/System.Private.CoreLib/src/System/Exception.CoreCLR.cs +++ b/src/coreclr/src/System.Private.CoreLib/src/System/Exception.CoreCLR.cs @@ -56,73 +56,6 @@ namespace System [MethodImpl(MethodImplOptions.InternalCall)] private static extern bool IsImmutableAgileException(Exception e); -#if FEATURE_COMINTEROP - // - // Exception requires anything to be added into Data dictionary is serializable - // This wrapper is made serializable to satisfy this requirement but does NOT serialize - // the object and simply ignores it during serialization, because we only need - // the exception instance in the app to hold the error object alive. - // Once the exception is serialized to debugger, debugger only needs the error reference string - // - [Serializable] - internal class __RestrictedErrorObject - { - // Hold the error object instance but don't serialize/deserialize it - [NonSerialized] - private readonly object _realErrorObject; - - internal __RestrictedErrorObject(object errorObject) - { - _realErrorObject = errorObject; - } - - public object RealErrorObject - { - get - { - return _realErrorObject; - } - } - } - - internal void AddExceptionDataForRestrictedErrorInfo( - string restrictedError, - string restrictedErrorReference, - string restrictedCapabilitySid, - object? restrictedErrorObject, - bool hasrestrictedLanguageErrorObject = false) - { - IDictionary dict = Data; - if (dict != null) - { - dict.Add("RestrictedDescription", restrictedError); - dict.Add("RestrictedErrorReference", restrictedErrorReference); - dict.Add("RestrictedCapabilitySid", restrictedCapabilitySid); - - // Keep the error object alive so that user could retrieve error information - // using Data["RestrictedErrorReference"] - dict.Add("__RestrictedErrorObject", restrictedErrorObject == null ? null : new __RestrictedErrorObject(restrictedErrorObject)); - dict.Add("__HasRestrictedLanguageErrorObject", hasrestrictedLanguageErrorObject); - } - } - - internal bool TryGetRestrictedLanguageErrorObject(out object? restrictedErrorObject) - { - restrictedErrorObject = null; - if (Data != null && Data.Contains("__HasRestrictedLanguageErrorObject")) - { - if (Data.Contains("__RestrictedErrorObject")) - { - if (Data["__RestrictedErrorObject"] is __RestrictedErrorObject restrictedObject) - restrictedErrorObject = restrictedObject.RealErrorObject; - } - return (bool)Data["__HasRestrictedLanguageErrorObject"]!; - } - - return false; - } -#endif // FEATURE_COMINTEROP - [MethodImpl(MethodImplOptions.InternalCall)] private static extern IRuntimeMethodInfo GetMethodFromStackTrace(object stackTrace); diff --git a/src/coreclr/src/System.Private.CoreLib/src/System/Runtime/InteropServices/Marshal.CoreCLR.cs b/src/coreclr/src/System.Private.CoreLib/src/System/Runtime/InteropServices/Marshal.CoreCLR.cs index e9b8b3d..f3454c3 100644 --- a/src/coreclr/src/System.Private.CoreLib/src/System/Runtime/InteropServices/Marshal.CoreCLR.cs +++ b/src/coreclr/src/System.Private.CoreLib/src/System/Runtime/InteropServices/Marshal.CoreCLR.cs @@ -602,10 +602,6 @@ namespace System.Runtime.InteropServices { throw new ArgumentException(SR.Argument_ObjNotComObject, nameof(obj)); } - if (obj.GetType().IsWindowsRuntimeObject) - { - throw new ArgumentException(SR.Argument_ObjIsWinRTObject, nameof(obj)); - } // Retrieve the data from the __ComObject. return co.GetData(key); @@ -631,10 +627,6 @@ namespace System.Runtime.InteropServices { throw new ArgumentException(SR.Argument_ObjNotComObject, nameof(obj)); } - if (obj.GetType().IsWindowsRuntimeObject) - { - throw new ArgumentException(SR.Argument_ObjIsWinRTObject, nameof(obj)); - } // Retrieve the data from the __ComObject. return co.SetData(key, data); @@ -659,10 +651,6 @@ namespace System.Runtime.InteropServices { throw new ArgumentException(SR.Argument_NeedNonGenericType, nameof(t)); } - if (t.IsWindowsRuntimeObject) - { - throw new ArgumentException(SR.Argument_TypeIsWinRTType, nameof(t)); - } if (o is null) { @@ -673,10 +661,6 @@ namespace System.Runtime.InteropServices { throw new ArgumentException(SR.Argument_ObjNotComObject, nameof(o)); } - if (o.GetType().IsWindowsRuntimeObject) - { - throw new ArgumentException(SR.Argument_ObjIsWinRTObject, nameof(o)); - } // Check to see if we have nothing to do. if (o.GetType() == t) diff --git a/src/coreclr/src/System.Private.CoreLib/src/System/Runtime/InteropServices/WindowsRuntime/BindableVectorToCollectionAdapter.cs b/src/coreclr/src/System.Private.CoreLib/src/System/Runtime/InteropServices/WindowsRuntime/BindableVectorToCollectionAdapter.cs deleted file mode 100644 index f21bd53..0000000 --- a/src/coreclr/src/System.Private.CoreLib/src/System/Runtime/InteropServices/WindowsRuntime/BindableVectorToCollectionAdapter.cs +++ /dev/null @@ -1,92 +0,0 @@ -// 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 Internal.Runtime.CompilerServices; - -namespace System.Runtime.InteropServices.WindowsRuntime -{ - // This is a set of stub methods implementing the support for the ICollection interface on WinRT - // objects that support IBindableVector. Used by the interop mashaling infrastructure. - // - // The methods on this class must be written VERY carefully to avoid introducing security holes. - // That's because they are invoked with special "this"! The "this" object - // for all of these methods are not BindableVectorToCollectionAdapter objects. Rather, they are - // of type IBindableVector. No actual BindableVectorToCollectionAdapter object is ever instantiated. - // Thus, you will see a lot of expressions that cast "this" to "IBindableVector". - internal sealed class BindableVectorToCollectionAdapter - { - private BindableVectorToCollectionAdapter() - { - Debug.Fail("This class is never instantiated"); - } - - // int Count { get } - internal int Count() - { - IBindableVector _this = Unsafe.As(this); - uint size = _this.Size; - if (((uint)int.MaxValue) < size) - { - throw new InvalidOperationException(SR.InvalidOperation_CollectionBackingListTooLarge); - } - - return (int)size; - } - - // bool IsSynchronized { get } - internal bool IsSynchronized() - { - return false; - } - - // object SyncRoot { get } - internal object SyncRoot() - { - return this; - } - - // void CopyTo(Array array, int index) - internal void CopyTo(Array array, int arrayIndex) - { - if (array == null) - throw new ArgumentNullException(nameof(array)); - - // ICollection expects the destination array to be single-dimensional. - if (array.Rank != 1) - throw new ArgumentException(SR.Arg_RankMultiDimNotSupported); - - int destLB = array.GetLowerBound(0); - - int srcLen = Count(); - int destLen = array.GetLength(0); - - if (arrayIndex < destLB) - throw new ArgumentOutOfRangeException(nameof(arrayIndex)); - - // Does the dimension in question have sufficient space to copy the expected number of entries? - // We perform this check before valid index check to ensure the exception message is in sync with - // the following snippet that uses regular framework code: - // - // ArrayList list = new ArrayList(); - // list.Add(1); - // Array items = Array.CreateInstance(typeof(object), new int[] { 1 }, new int[] { -1 }); - // list.CopyTo(items, 0); - - if (srcLen > (destLen - (arrayIndex - destLB))) - throw new ArgumentException(SR.Argument_InsufficientSpaceToCopyCollection); - - if (arrayIndex - destLB > destLen) - throw new ArgumentException(SR.Argument_IndexOutOfArrayBounds); - - // We need to verify the index as we; - IBindableVector _this = Unsafe.As(this); - - for (uint i = 0; i < srcLen; i++) - { - array.SetValue(_this.GetAt(i), i + arrayIndex); - } - } - } -} diff --git a/src/coreclr/src/System.Private.CoreLib/src/System/Runtime/InteropServices/WindowsRuntime/BindableVectorToListAdapter.cs b/src/coreclr/src/System.Private.CoreLib/src/System/Runtime/InteropServices/WindowsRuntime/BindableVectorToListAdapter.cs deleted file mode 100644 index 737dd90..0000000 --- a/src/coreclr/src/System.Private.CoreLib/src/System/Runtime/InteropServices/WindowsRuntime/BindableVectorToListAdapter.cs +++ /dev/null @@ -1,217 +0,0 @@ -// 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 Internal.Runtime.CompilerServices; - -namespace System.Runtime.InteropServices.WindowsRuntime -{ - // This is a set of stub methods implementing the support for the IList interface on WinRT - // objects that support IBindableVector. Used by the interop mashaling infrastructure. - // - // The methods on this class must be written VERY carefully to avoid introducing security holes. - // That's because they are invoked with special "this"! The "this" object - // for all of these methods are not BindableVectorToListAdapter objects. Rather, they are - // of type IBindableVector. No actual BindableVectorToListAdapter object is ever instantiated. - // Thus, you will see a lot of expressions that cast "this" to "IBindableVector". - internal sealed class BindableVectorToListAdapter - { - private BindableVectorToListAdapter() - { - Debug.Fail("This class is never instantiated"); - } - - // object this[int index] { get } - internal object? Indexer_Get(int index) - { - if (index < 0) - throw new ArgumentOutOfRangeException(nameof(index)); - - IBindableVector _this = Unsafe.As(this); - return GetAt(_this, (uint)index); - } - - // object this[int index] { set } - internal void Indexer_Set(int index, object value) - { - if (index < 0) - throw new ArgumentOutOfRangeException(nameof(index)); - - IBindableVector _this = Unsafe.As(this); - SetAt(_this, (uint)index, value); - } - - // int Add(object value) - internal int Add(object value) - { - IBindableVector _this = Unsafe.As(this); - _this.Append(value); - - uint size = _this.Size; - if (((uint)int.MaxValue) < size) - { - throw new InvalidOperationException(SR.InvalidOperation_CollectionBackingListTooLarge); - } - - return (int)(size - 1); - } - - // bool Contains(object item) - internal bool Contains(object item) - { - IBindableVector _this = Unsafe.As(this); - - return _this.IndexOf(item, out _); - } - - // void Clear() - internal void Clear() - { - IBindableVector _this = Unsafe.As(this); - _this.Clear(); - } - - // bool IsFixedSize { get } - internal bool IsFixedSize() - { - return false; - } - - // bool IsReadOnly { get } - internal bool IsReadOnly() - { - return false; - } - - // int IndexOf(object item) - internal int IndexOf(object item) - { - IBindableVector _this = Unsafe.As(this); - - bool exists = _this.IndexOf(item, out uint index); - - if (!exists) - return -1; - - if (((uint)int.MaxValue) < index) - { - throw new InvalidOperationException(SR.InvalidOperation_CollectionBackingListTooLarge); - } - - return (int)index; - } - - // void Insert(int index, object item) - internal void Insert(int index, object item) - { - if (index < 0) - throw new ArgumentOutOfRangeException(nameof(index)); - - IBindableVector _this = Unsafe.As(this); - InsertAtHelper(_this, (uint)index, item); - } - - // bool Remove(object item) - internal void Remove(object item) - { - IBindableVector _this = Unsafe.As(this); - - bool exists = _this.IndexOf(item, out uint index); - - if (exists) - { - if (((uint)int.MaxValue) < index) - { - throw new InvalidOperationException(SR.InvalidOperation_CollectionBackingListTooLarge); - } - - RemoveAtHelper(_this, index); - } - } - - // void RemoveAt(int index) - internal void RemoveAt(int index) - { - if (index < 0) - throw new ArgumentOutOfRangeException(nameof(index)); - - IBindableVector _this = Unsafe.As(this); - RemoveAtHelper(_this, (uint)index); - } - - // Helpers: - - private static object? GetAt(IBindableVector _this, uint index) - { - try - { - return _this.GetAt(index); - - // We delegate bounds checking to the underlying collection and if it detected a fault, - // we translate it to the right exception: - } - catch (Exception ex) - { - if (HResults.E_BOUNDS == ex.HResult) - throw new ArgumentOutOfRangeException(nameof(index)); - - throw; - } - } - - private static void SetAt(IBindableVector _this, uint index, object value) - { - try - { - _this.SetAt(index, value); - - // We delegate bounds checking to the underlying collection and if it detected a fault, - // we translate it to the right exception: - } - catch (Exception ex) - { - if (HResults.E_BOUNDS == ex.HResult) - throw new ArgumentOutOfRangeException(nameof(index)); - - throw; - } - } - - private static void InsertAtHelper(IBindableVector _this, uint index, object item) - { - try - { - _this.InsertAt(index, item); - - // We delegate bounds checking to the underlying collection and if it detected a fault, - // we translate it to the right exception: - } - catch (Exception ex) - { - if (HResults.E_BOUNDS == ex.HResult) - throw new ArgumentOutOfRangeException(nameof(index)); - - throw; - } - } - - private static void RemoveAtHelper(IBindableVector _this, uint index) - { - try - { - _this.RemoveAt(index); - - // We delegate bounds checking to the underlying collection and if it detected a fault, - // we translate it to the right exception: - } - catch (Exception ex) - { - if (HResults.E_BOUNDS == ex.HResult) - throw new ArgumentOutOfRangeException(nameof(index)); - - throw; - } - } - } -} diff --git a/src/coreclr/src/System.Private.CoreLib/src/System/Runtime/InteropServices/WindowsRuntime/CLRIKeyValuePairImpl.cs b/src/coreclr/src/System.Private.CoreLib/src/System/Runtime/InteropServices/WindowsRuntime/CLRIKeyValuePairImpl.cs deleted file mode 100644 index dee3657..0000000 --- a/src/coreclr/src/System.Private.CoreLib/src/System/Runtime/InteropServices/WindowsRuntime/CLRIKeyValuePairImpl.cs +++ /dev/null @@ -1,54 +0,0 @@ -// 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.Generic; -using System.Diagnostics; - -namespace System.Runtime.InteropServices.WindowsRuntime -{ - // Provides access to a System.Collections.Generic.KeyValuePair via the IKeyValuePair WinRT interface. - internal sealed class CLRIKeyValuePairImpl : IKeyValuePair, - IGetProxyTarget - { - private readonly KeyValuePair _pair; - - public CLRIKeyValuePairImpl([In] ref KeyValuePair pair) - { - _pair = pair; - } - - // IKeyValuePair implementation - public K Key => _pair.Key; - - public V Value => _pair.Value; - - // Called from the VM to wrap a boxed KeyValuePair with a CLRIKeyValuePairImpl. - internal static object BoxHelper(object pair) - { - Debug.Assert(pair != null); - - KeyValuePair unboxedPair = (KeyValuePair)pair; - return new CLRIKeyValuePairImpl(ref unboxedPair); - } - - // Called from the VM to get a boxed KeyValuePair out of a CLRIKeyValuePairImpl. - internal static object UnboxHelper(object wrapper) - { - Debug.Assert(wrapper != null); - - CLRIKeyValuePairImpl reference = (CLRIKeyValuePairImpl)wrapper; - return reference._pair; - } - - public override string ToString() - { - return _pair.ToString(); - } - - object IGetProxyTarget.GetTarget() - { - return _pair; - } - } -} diff --git a/src/coreclr/src/System.Private.CoreLib/src/System/Runtime/InteropServices/WindowsRuntime/CLRIPropertyValueImpl.cs b/src/coreclr/src/System.Private.CoreLib/src/System/Runtime/InteropServices/WindowsRuntime/CLRIPropertyValueImpl.cs deleted file mode 100644 index bec5ac7..0000000 --- a/src/coreclr/src/System.Private.CoreLib/src/System/Runtime/InteropServices/WindowsRuntime/CLRIPropertyValueImpl.cs +++ /dev/null @@ -1,517 +0,0 @@ -// 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 System.Runtime.CompilerServices; - -using Internal.Runtime.CompilerServices; - -namespace System.Runtime.InteropServices.WindowsRuntime -{ - internal class CLRIPropertyValueImpl : IPropertyValue - { - private readonly PropertyType _type; - private readonly object _data; - - // Numeric scalar types which participate in coersion - private static volatile Tuple[]? s_numericScalarTypes; - - internal CLRIPropertyValueImpl(PropertyType type, object data) - { - _type = type; - _data = data; - } - - private static Tuple[] NumericScalarTypes - { - get - { - if (s_numericScalarTypes == null) - { - Tuple[] numericScalarTypes = new Tuple[] { - new Tuple(typeof(byte), PropertyType.UInt8), - new Tuple(typeof(short), PropertyType.Int16), - new Tuple(typeof(ushort), PropertyType.UInt16), - new Tuple(typeof(int), PropertyType.Int32), - new Tuple(typeof(uint), PropertyType.UInt32), - new Tuple(typeof(long), PropertyType.Int64), - new Tuple(typeof(ulong), PropertyType.UInt64), - new Tuple(typeof(float), PropertyType.Single), - new Tuple(typeof(double), PropertyType.Double) - }; - - s_numericScalarTypes = numericScalarTypes; - } - - return s_numericScalarTypes; - } - } - - public PropertyType Type => _type; - - public bool IsNumericScalar => IsNumericScalarImpl(_type, _data); - - public override string? ToString() - { - if (_data != null) - { - return _data.ToString(); - } - else - { - return base.ToString(); - } - } - - public byte GetUInt8() - { - return CoerceScalarValue(PropertyType.UInt8); - } - - public short GetInt16() - { - return CoerceScalarValue(PropertyType.Int16); - } - - public ushort GetUInt16() - { - return CoerceScalarValue(PropertyType.UInt16); - } - - public int GetInt32() - { - return CoerceScalarValue(PropertyType.Int32); - } - - public uint GetUInt32() - { - return CoerceScalarValue(PropertyType.UInt32); - } - - public long GetInt64() - { - return CoerceScalarValue(PropertyType.Int64); - } - - public ulong GetUInt64() - { - return CoerceScalarValue(PropertyType.UInt64); - } - - public float GetSingle() - { - return CoerceScalarValue(PropertyType.Single); - } - - public double GetDouble() - { - return CoerceScalarValue(PropertyType.Double); - } - - public char GetChar16() - { - if (this.Type != PropertyType.Char16) - throw new InvalidCastException(SR.Format(SR.InvalidCast_WinRTIPropertyValueElement, this.Type, "Char16"), HResults.TYPE_E_TYPEMISMATCH); - return (char)_data; - } - - public bool GetBoolean() - { - if (this.Type != PropertyType.Boolean) - throw new InvalidCastException(SR.Format(SR.InvalidCast_WinRTIPropertyValueElement, this.Type, "Boolean"), HResults.TYPE_E_TYPEMISMATCH); - return (bool)_data; - } - - public string GetString() - { - return CoerceScalarValue(PropertyType.String); - } - - - public Guid GetGuid() - { - return CoerceScalarValue(PropertyType.Guid); - } - - - public DateTimeOffset GetDateTime() - { - if (this.Type != PropertyType.DateTime) - throw new InvalidCastException(SR.Format(SR.InvalidCast_WinRTIPropertyValueElement, this.Type, "DateTime"), HResults.TYPE_E_TYPEMISMATCH); - return (DateTimeOffset)_data; - } - - public TimeSpan GetTimeSpan() - { - if (this.Type != PropertyType.TimeSpan) - throw new InvalidCastException(SR.Format(SR.InvalidCast_WinRTIPropertyValueElement, this.Type, "TimeSpan"), HResults.TYPE_E_TYPEMISMATCH); - return (TimeSpan)_data; - } - - public Point GetPoint() - { - if (this.Type != PropertyType.Point) - throw new InvalidCastException(SR.Format(SR.InvalidCast_WinRTIPropertyValueElement, this.Type, "Point"), HResults.TYPE_E_TYPEMISMATCH); - - return Unbox(IReferenceFactory.s_pointType); - } - - public Size GetSize() - { - if (this.Type != PropertyType.Size) - throw new InvalidCastException(SR.Format(SR.InvalidCast_WinRTIPropertyValueElement, this.Type, "Size"), HResults.TYPE_E_TYPEMISMATCH); - - return Unbox(IReferenceFactory.s_sizeType); - } - - public Rect GetRect() - { - if (this.Type != PropertyType.Rect) - throw new InvalidCastException(SR.Format(SR.InvalidCast_WinRTIPropertyValueElement, this.Type, "Rect"), HResults.TYPE_E_TYPEMISMATCH); - - return Unbox(IReferenceFactory.s_rectType); - } - - public byte[] GetUInt8Array() - { - return CoerceArrayValue(PropertyType.UInt8Array); - } - - public short[] GetInt16Array() - { - return CoerceArrayValue(PropertyType.Int16Array); - } - - public ushort[] GetUInt16Array() - { - return CoerceArrayValue(PropertyType.UInt16Array); - } - - public int[] GetInt32Array() - { - return CoerceArrayValue(PropertyType.Int32Array); - } - - public uint[] GetUInt32Array() - { - return CoerceArrayValue(PropertyType.UInt32Array); - } - - public long[] GetInt64Array() - { - return CoerceArrayValue(PropertyType.Int64Array); - } - - public ulong[] GetUInt64Array() - { - return CoerceArrayValue(PropertyType.UInt64Array); - } - - public float[] GetSingleArray() - { - return CoerceArrayValue(PropertyType.SingleArray); - } - - public double[] GetDoubleArray() - { - return CoerceArrayValue(PropertyType.DoubleArray); - } - - public char[] GetChar16Array() - { - if (this.Type != PropertyType.Char16Array) - throw new InvalidCastException(SR.Format(SR.InvalidCast_WinRTIPropertyValueElement, this.Type, "Char16[]"), HResults.TYPE_E_TYPEMISMATCH); - return (char[])_data; - } - - public bool[] GetBooleanArray() - { - if (this.Type != PropertyType.BooleanArray) - throw new InvalidCastException(SR.Format(SR.InvalidCast_WinRTIPropertyValueElement, this.Type, "Boolean[]"), HResults.TYPE_E_TYPEMISMATCH); - return (bool[])_data; - } - - public string[] GetStringArray() - { - return CoerceArrayValue(PropertyType.StringArray); - } - - public object[] GetInspectableArray() - { - if (this.Type != PropertyType.InspectableArray) - throw new InvalidCastException(SR.Format(SR.InvalidCast_WinRTIPropertyValueElement, this.Type, "Inspectable[]"), HResults.TYPE_E_TYPEMISMATCH); - return (object[])_data; - } - - public Guid[] GetGuidArray() - { - return CoerceArrayValue(PropertyType.GuidArray); - } - - public DateTimeOffset[] GetDateTimeArray() - { - if (this.Type != PropertyType.DateTimeArray) - throw new InvalidCastException(SR.Format(SR.InvalidCast_WinRTIPropertyValueElement, this.Type, "DateTimeOffset[]"), HResults.TYPE_E_TYPEMISMATCH); - return (DateTimeOffset[])_data; - } - - public TimeSpan[] GetTimeSpanArray() - { - if (this.Type != PropertyType.TimeSpanArray) - throw new InvalidCastException(SR.Format(SR.InvalidCast_WinRTIPropertyValueElement, this.Type, "TimeSpan[]"), HResults.TYPE_E_TYPEMISMATCH); - return (TimeSpan[])_data; - } - - public Point[] GetPointArray() - { - if (this.Type != PropertyType.PointArray) - throw new InvalidCastException(SR.Format(SR.InvalidCast_WinRTIPropertyValueElement, this.Type, "Point[]"), HResults.TYPE_E_TYPEMISMATCH); - - return UnboxArray(IReferenceFactory.s_pointType); - } - - public Size[] GetSizeArray() - { - if (this.Type != PropertyType.SizeArray) - throw new InvalidCastException(SR.Format(SR.InvalidCast_WinRTIPropertyValueElement, this.Type, "Size[]"), HResults.TYPE_E_TYPEMISMATCH); - - - return UnboxArray(IReferenceFactory.s_sizeType); - } - - public Rect[] GetRectArray() - { - if (this.Type != PropertyType.RectArray) - throw new InvalidCastException(SR.Format(SR.InvalidCast_WinRTIPropertyValueElement, this.Type, "Rect[]"), HResults.TYPE_E_TYPEMISMATCH); - - return UnboxArray(IReferenceFactory.s_rectType); - } - - private T[] CoerceArrayValue(PropertyType unboxType) - { - // If we contain the type being looked for directly, then take the fast-path - if (Type == unboxType) - { - return (T[])_data; - } - - // Make sure we have an array to begin with - if (!(_data is Array dataArray)) - { - throw new InvalidCastException(SR.Format(SR.InvalidCast_WinRTIPropertyValueElement, this.Type, typeof(T).MakeArrayType().Name), HResults.TYPE_E_TYPEMISMATCH); - } - - // Array types are 1024 larger than their equivilent scalar counterpart - Debug.Assert((int)Type > 1024, "Unexpected array PropertyType value"); - PropertyType scalarType = Type - 1024; - - // If we do not have the correct array type, then we need to convert the array element-by-element - // to a new array of the requested type - T[] coercedArray = new T[dataArray.Length]; - for (int i = 0; i < dataArray.Length; ++i) - { - try - { - coercedArray[i] = CoerceScalarValue(scalarType, dataArray.GetValue(i)!); - } - catch (InvalidCastException elementCastException) - { - Exception e = new InvalidCastException(SR.Format(SR.InvalidCast_WinRTIPropertyValueArrayCoersion, this.Type, typeof(T).MakeArrayType().Name, i, elementCastException.Message), elementCastException); - e.HResult = elementCastException.HResult; - throw e; - } - } - - return coercedArray; - } - - private T CoerceScalarValue(PropertyType unboxType) - { - // If we are just a boxed version of the requested type, then take the fast path out - if (Type == unboxType) - { - return (T)_data; - } - - return CoerceScalarValue(Type, _data); - } - - private static T CoerceScalarValue(PropertyType type, object value) - { - // If the property type is neither one of the coercable numeric types nor IInspectable, we - // should not attempt coersion, even if the underlying value is technically convertable - if (!IsCoercable(type, value) && type != PropertyType.Inspectable) - { - throw new InvalidCastException(SR.Format(SR.InvalidCast_WinRTIPropertyValueElement, type, typeof(T).Name), HResults.TYPE_E_TYPEMISMATCH); - } - - try - { - // Try to coerce: - // * String <--> Guid - // * Numeric scalars - if (type == PropertyType.String && typeof(T) == typeof(Guid)) - { - return (T)(object)Guid.Parse((string)value); - } - else if (type == PropertyType.Guid && typeof(T) == typeof(string)) - { - return (T)(object)((Guid)value).ToString("D", System.Globalization.CultureInfo.InvariantCulture); - } - else - { - // Iterate over the numeric scalars, to see if we have a match for one of the known conversions - foreach (Tuple numericScalar in NumericScalarTypes) - { - if (numericScalar.Item1 == typeof(T)) - { - return (T)Convert.ChangeType(value, typeof(T), System.Globalization.CultureInfo.InvariantCulture)!; - } - } - } - } - catch (FormatException) - { - throw new InvalidCastException(SR.Format(SR.InvalidCast_WinRTIPropertyValueElement, type, typeof(T).Name), HResults.TYPE_E_TYPEMISMATCH); - } - catch (InvalidCastException) - { - throw new InvalidCastException(SR.Format(SR.InvalidCast_WinRTIPropertyValueElement, type, typeof(T).Name), HResults.TYPE_E_TYPEMISMATCH); - } - catch (OverflowException) - { - throw new InvalidCastException(SR.Format(SR.InvalidCast_WinRTIPropertyValueCoersion, type, value, typeof(T).Name), HResults.DISP_E_OVERFLOW); - } - - // If the property type is IInspectable, and we have a nested IPropertyValue, then we need - // to pass along the request to coerce the value. - if (type == PropertyType.Inspectable && value is IPropertyValue ipv) - { - if (typeof(T) == typeof(byte)) - { - return (T)(object)ipv.GetUInt8(); - } - else if (typeof(T) == typeof(short)) - { - return (T)(object)ipv.GetInt16(); - } - else if (typeof(T) == typeof(ushort)) - { - return (T)(object)ipv.GetUInt16(); - } - else if (typeof(T) == typeof(int)) - { - return (T)(object)ipv.GetUInt32(); - } - else if (typeof(T) == typeof(uint)) - { - return (T)(object)ipv.GetUInt32(); - } - else if (typeof(T) == typeof(long)) - { - return (T)(object)ipv.GetInt64(); - } - else if (typeof(T) == typeof(ulong)) - { - return (T)(object)ipv.GetUInt64(); - } - else if (typeof(T) == typeof(float)) - { - return (T)(object)ipv.GetSingle(); - } - else if (typeof(T) == typeof(double)) - { - return (T)(object)ipv.GetDouble(); - } - else - { - Debug.Fail("T in coersion function wasn't understood as a type that can be coerced - make sure that CoerceScalarValue and NumericScalarTypes are in sync"); - } - } - - // Otherwise, this is an invalid coersion - throw new InvalidCastException(SR.Format(SR.InvalidCast_WinRTIPropertyValueElement, type, typeof(T).Name), HResults.TYPE_E_TYPEMISMATCH); - } - - private static bool IsCoercable(PropertyType type, object data) - { - // String <--> Guid is allowed - if (type == PropertyType.Guid || type == PropertyType.String) - { - return true; - } - - // All numeric scalars can also be coerced - return IsNumericScalarImpl(type, data); - } - - private static bool IsNumericScalarImpl(PropertyType type, object data) - { - if (data.GetType().IsEnum) - { - return true; - } - - foreach (Tuple numericScalar in NumericScalarTypes) - { - if (numericScalar.Item2 == type) - { - return true; - } - } - - return false; - } - - // Unbox the data stored in the property value to a structurally equivalent type - private unsafe T Unbox(Type expectedBoxedType) where T : struct - { - Debug.Assert(expectedBoxedType != null); - Debug.Assert(Marshal.SizeOf(expectedBoxedType) == Marshal.SizeOf(typeof(T))); - - if (_data.GetType() != expectedBoxedType) - { - throw new InvalidCastException(SR.Format(SR.InvalidCast_WinRTIPropertyValueElement, _data.GetType(), expectedBoxedType.Name), HResults.TYPE_E_TYPEMISMATCH); - } - - T unboxed = default; - - fixed (byte* pData = &_data.GetRawData()) - { - byte* pUnboxed = (byte*)Unsafe.AsPointer(ref unboxed); - Buffer.Memcpy(pUnboxed, pData, Marshal.SizeOf(unboxed)); - } - - return unboxed; - } - - // Convert the array stored in the property value to a structurally equivilent array type - private unsafe T[] UnboxArray(Type expectedArrayElementType) where T : struct - { - Debug.Assert(expectedArrayElementType != null); - Debug.Assert(Marshal.SizeOf(expectedArrayElementType) == Marshal.SizeOf(typeof(T))); - - if (!(_data is Array dataArray) || _data.GetType().GetElementType() != expectedArrayElementType) - { - throw new InvalidCastException(SR.Format(SR.InvalidCast_WinRTIPropertyValueElement, _data.GetType(), expectedArrayElementType.MakeArrayType().Name), HResults.TYPE_E_TYPEMISMATCH); - } - - T[] converted = new T[dataArray.Length]; - - if (converted.Length > 0) - { - fixed (byte* dataPin = &dataArray.GetRawData()) - fixed (byte* convertedPin = &converted.GetRawData()) - { - byte* pData = (byte*)Marshal.UnsafeAddrOfPinnedArrayElement(dataArray, 0); - byte* pConverted = (byte*)Marshal.UnsafeAddrOfPinnedArrayElement(converted, 0); - - Buffer.Memcpy(pConverted, pData, checked(Marshal.SizeOf(typeof(T)) * converted.Length)); - } - } - - return converted; - } - } -} diff --git a/src/coreclr/src/System.Private.CoreLib/src/System/Runtime/InteropServices/WindowsRuntime/CLRIReferenceImpl.cs b/src/coreclr/src/System.Private.CoreLib/src/System/Runtime/InteropServices/WindowsRuntime/CLRIReferenceImpl.cs deleted file mode 100644 index 3a3741c..0000000 --- a/src/coreclr/src/System.Private.CoreLib/src/System/Runtime/InteropServices/WindowsRuntime/CLRIReferenceImpl.cs +++ /dev/null @@ -1,353 +0,0 @@ -// 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.Diagnostics; - -namespace System.Runtime.InteropServices.WindowsRuntime -{ - internal sealed class CLRIReferenceImpl : CLRIPropertyValueImpl, IReference, IGetProxyTarget - { - private readonly T _value; - - public CLRIReferenceImpl(PropertyType type, T obj) - : base(type, obj!) - { - Debug.Assert(obj != null, "Must not be null"); - _value = obj; - } - - public T Value => _value; - - public override string? ToString() - { - if (_value != null) - { - return _value.ToString(); - } - else - { - return base.ToString(); - } - } - - object IGetProxyTarget.GetTarget() - { - return _value!; - } - - // We have T in an IReference. Need to QI for IReference with the appropriate GUID, call - // the get_Value property, allocate an appropriately-sized managed object, marshal the native object - // to the managed object, and free the native method. Also we want the return value boxed (aka normal value type boxing). - // - // This method is called by VM. - internal static object UnboxHelper(object wrapper) - { - Debug.Assert(wrapper != null); - IReference reference = (IReference)wrapper; - Debug.Assert(reference != null, "CLRIReferenceImpl::UnboxHelper - QI'ed for IReference<" + typeof(T) + ">, but that failed."); - return reference.Value!; - } - } - - // T can be any WinRT-compatible type - internal sealed class CLRIReferenceArrayImpl : CLRIPropertyValueImpl, - IGetProxyTarget, - IReferenceArray, - IList // Jupiter data binding needs IList/IEnumerable - { - private readonly T[] _value; - private readonly IList _list; - - public CLRIReferenceArrayImpl(PropertyType type, T[] obj) - : base(type, obj) - { - Debug.Assert(obj != null, "Must not be null"); - - _value = obj; - - _list = (IList)_value; - } - - public T[] Value => _value; - - public override string? ToString() - { - if (_value != null) - { - return _value.ToString(); - } - else - { - return base.ToString(); - } - } - - // - // IEnumerable methods. Used by data-binding in Jupiter when you try to data bind - // against a managed array - // - IEnumerator IEnumerable.GetEnumerator() - { - return ((IEnumerable)_value).GetEnumerator(); - } - - // - // IList & ICollection methods. - // This enables two-way data binding and index access in Jupiter - // - object? IList.this[int index] - { - get => _list[index]; - set => _list[index] = value; - } - - int IList.Add(object? value) - { - return _list.Add(value); - } - - bool IList.Contains(object? value) - { - return _list.Contains(value); - } - - void IList.Clear() - { - _list.Clear(); - } - - bool IList.IsReadOnly => _list.IsReadOnly; - - bool IList.IsFixedSize => _list.IsFixedSize; - - int IList.IndexOf(object? value) - { - return _list.IndexOf(value); - } - - void IList.Insert(int index, object? value) - { - _list.Insert(index, value); - } - - void IList.Remove(object? value) - { - _list.Remove(value); - } - - void IList.RemoveAt(int index) - { - _list.RemoveAt(index); - } - - void ICollection.CopyTo(Array array, int index) - { - _list.CopyTo(array, index); - } - - int ICollection.Count => _list.Count; - - object ICollection.SyncRoot => _list.SyncRoot; - - bool ICollection.IsSynchronized => _list.IsSynchronized; - - object IGetProxyTarget.GetTarget() - { - return (object)_value; - } - - // We have T in an IReferenceArray. Need to QI for IReferenceArray with the appropriate GUID, call - // the get_Value property, allocate an appropriately-sized managed object, marshal the native object - // to the managed object, and free the native method. - // - // This method is called by VM. - internal static object UnboxHelper(object wrapper) - { - Debug.Assert(wrapper != null); - IReferenceArray reference = (IReferenceArray)wrapper; - Debug.Assert(reference != null, "CLRIReferenceArrayImpl::UnboxHelper - QI'ed for IReferenceArray<" + typeof(T) + ">, but that failed."); - T[] marshaled = reference.Value; - return marshaled; - } - } - - // For creating instances of Windows Runtime's IReference and IReferenceArray. - internal static class IReferenceFactory - { - internal static readonly Type s_pointType = Type.GetType("Windows.Foundation.Point, System.Runtime.WindowsRuntime")!; - internal static readonly Type s_rectType = Type.GetType("Windows.Foundation.Rect, System.Runtime.WindowsRuntime")!; - internal static readonly Type s_sizeType = Type.GetType("Windows.Foundation.Size, System.Runtime.WindowsRuntime")!; - - internal static object CreateIReference(object obj) - { - Debug.Assert(obj != null, "Null should not be boxed."); - - Type type = obj.GetType(); - - if (type.IsArray) - return CreateIReferenceArray((Array)obj); - - if (type == typeof(int)) - return new CLRIReferenceImpl(PropertyType.Int32, (int)obj); - if (type == typeof(string)) - return new CLRIReferenceImpl(PropertyType.String, (string)obj); - if (type == typeof(byte)) - return new CLRIReferenceImpl(PropertyType.UInt8, (byte)obj); - if (type == typeof(short)) - return new CLRIReferenceImpl(PropertyType.Int16, (short)obj); - if (type == typeof(ushort)) - return new CLRIReferenceImpl(PropertyType.UInt16, (ushort)obj); - if (type == typeof(uint)) - return new CLRIReferenceImpl(PropertyType.UInt32, (uint)obj); - if (type == typeof(long)) - return new CLRIReferenceImpl(PropertyType.Int64, (long)obj); - if (type == typeof(ulong)) - return new CLRIReferenceImpl(PropertyType.UInt64, (ulong)obj); - if (type == typeof(float)) - return new CLRIReferenceImpl(PropertyType.Single, (float)obj); - if (type == typeof(double)) - return new CLRIReferenceImpl(PropertyType.Double, (double)obj); - if (type == typeof(char)) - return new CLRIReferenceImpl(PropertyType.Char16, (char)obj); - if (type == typeof(bool)) - return new CLRIReferenceImpl(PropertyType.Boolean, (bool)obj); - if (type == typeof(Guid)) - return new CLRIReferenceImpl(PropertyType.Guid, (Guid)obj); - if (type == typeof(DateTimeOffset)) - return new CLRIReferenceImpl(PropertyType.DateTime, (DateTimeOffset)obj); - if (type == typeof(TimeSpan)) - return new CLRIReferenceImpl(PropertyType.TimeSpan, (TimeSpan)obj); - if (type == typeof(object)) - return new CLRIReferenceImpl(PropertyType.Inspectable, (object)obj); - if (type == typeof(RuntimeType)) - { // If the type is System.RuntimeType, we want to use System.Type marshaler (it's parent of the type) - return new CLRIReferenceImpl(PropertyType.Other, (Type)obj); - } - - // Handle arbitrary WinRT-compatible value types, and recognize a few special types. - PropertyType? propType = null; - if (type == s_pointType) - { - propType = PropertyType.Point; - } - else if (type == s_rectType) - { - propType = PropertyType.Rect; - } - else if (type == s_sizeType) - { - propType = PropertyType.Size; - } - else if (type.IsValueType || obj is Delegate) - { - propType = PropertyType.Other; - } - - if (propType.HasValue) - { - Type specificType = typeof(CLRIReferenceImpl<>).MakeGenericType(type); - return Activator.CreateInstance(specificType, new object[] { propType.GetValueOrDefault(), obj })!; - } - - Debug.Fail("We should not see non-WinRT type here"); - return null!; - } - - internal static object CreateIReferenceArray(Array obj) - { - Debug.Assert(obj != null); - Debug.Assert(obj.GetType().IsArray); - - Type type = obj.GetType().GetElementType()!; - - Debug.Assert(obj.Rank == 1 && obj.GetLowerBound(0) == 0 && !type.IsArray); - - if (type == typeof(int)) - return new CLRIReferenceArrayImpl(PropertyType.Int32Array, (int[])obj); - if (type == typeof(string)) - return new CLRIReferenceArrayImpl(PropertyType.StringArray, (string[])obj); - if (type == typeof(byte)) - return new CLRIReferenceArrayImpl(PropertyType.UInt8Array, (byte[])obj); - if (type == typeof(short)) - return new CLRIReferenceArrayImpl(PropertyType.Int16Array, (short[])obj); - if (type == typeof(ushort)) - return new CLRIReferenceArrayImpl(PropertyType.UInt16Array, (ushort[])obj); - if (type == typeof(uint)) - return new CLRIReferenceArrayImpl(PropertyType.UInt32Array, (uint[])obj); - if (type == typeof(long)) - return new CLRIReferenceArrayImpl(PropertyType.Int64Array, (long[])obj); - if (type == typeof(ulong)) - return new CLRIReferenceArrayImpl(PropertyType.UInt64Array, (ulong[])obj); - if (type == typeof(float)) - return new CLRIReferenceArrayImpl(PropertyType.SingleArray, (float[])obj); - if (type == typeof(double)) - return new CLRIReferenceArrayImpl(PropertyType.DoubleArray, (double[])obj); - if (type == typeof(char)) - return new CLRIReferenceArrayImpl(PropertyType.Char16Array, (char[])obj); - if (type == typeof(bool)) - return new CLRIReferenceArrayImpl(PropertyType.BooleanArray, (bool[])obj); - if (type == typeof(Guid)) - return new CLRIReferenceArrayImpl(PropertyType.GuidArray, (Guid[])obj); - if (type == typeof(DateTimeOffset)) - return new CLRIReferenceArrayImpl(PropertyType.DateTimeArray, (DateTimeOffset[])obj); - if (type == typeof(TimeSpan)) - return new CLRIReferenceArrayImpl(PropertyType.TimeSpanArray, (TimeSpan[])obj); - if (type == typeof(Type)) - { // Note: The array type will be System.Type, not System.RuntimeType - return new CLRIReferenceArrayImpl(PropertyType.OtherArray, (Type[])obj); - } - - PropertyType? propType = null; - if (type == s_pointType) - { - propType = PropertyType.PointArray; - } - else if (type == s_rectType) - { - propType = PropertyType.RectArray; - } - else if (type == s_sizeType) - { - propType = PropertyType.SizeArray; - } - else if (type.IsValueType) - { - // note that KeyValuePair`2 is a reference type on the WinRT side so the array - // must be wrapped with CLRIReferenceArrayImpl - if (type.IsGenericType && - type.GetGenericTypeDefinition() == typeof(System.Collections.Generic.KeyValuePair<,>)) - { - object?[] objArray = new object?[obj.Length]; - for (int i = 0; i < objArray.Length; i++) - { - objArray[i] = obj.GetValue(i); - } - obj = objArray; - } - else - { - propType = PropertyType.OtherArray; - } - } - else if (typeof(Delegate).IsAssignableFrom(type)) - { - propType = PropertyType.OtherArray; - } - - - if (propType.HasValue) - { - // All WinRT value type will be Property.Other - Type specificType = typeof(CLRIReferenceArrayImpl<>).MakeGenericType(type); - return Activator.CreateInstance(specificType, new object[] { propType.GetValueOrDefault(), obj })!; - } - else - { - // All WinRT reference type (including arbitrary managed type) will be PropertyType.ObjectArray - return new CLRIReferenceArrayImpl(PropertyType.InspectableArray, (object[])obj); - } - } - } -} diff --git a/src/coreclr/src/System.Private.CoreLib/src/System/Runtime/InteropServices/WindowsRuntime/ConstantSplittableMap.cs b/src/coreclr/src/System.Private.CoreLib/src/System/Runtime/InteropServices/WindowsRuntime/ConstantSplittableMap.cs deleted file mode 100644 index d7cd618..0000000 --- a/src/coreclr/src/System.Private.CoreLib/src/System/Runtime/InteropServices/WindowsRuntime/ConstantSplittableMap.cs +++ /dev/null @@ -1,194 +0,0 @@ -// 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 System.Collections; -using System.Collections.Generic; -using System.Diagnostics.CodeAnalysis; - -namespace System.Runtime.InteropServices.WindowsRuntime -{ - /// - /// This is a constant map aimed to efficiently support a Split operation (map decomposition). - /// A Split operation returns two non-overlapping, non-empty views of the existing map (or both - /// values are set to NULL). The two views returned should contain roughly the same number of elements. - /// This map is backed by a sorted array. Thus, split operations are O(1) and enumerations are fast; - /// however, look-up in the map are O(log n). - /// - /// Type of objects that act as keys. - /// Type of objects that act as entries / values. - [DebuggerDisplay("Count = {Count}")] - internal sealed class ConstantSplittableMap : IMapView where TKey : notnull - { - private class KeyValuePairComparator : IComparer> - { - private static readonly IComparer keyComparator = Comparer.Default; - - public int Compare(KeyValuePair x, KeyValuePair y) - { - return keyComparator.Compare(x.Key, y.Key); - } - } // private class KeyValuePairComparator - - - private static readonly KeyValuePairComparator keyValuePairComparator = new KeyValuePairComparator(); - - private readonly KeyValuePair[] items; - private readonly int firstItemIndex; - private readonly int lastItemIndex; - - internal ConstantSplittableMap(IReadOnlyDictionary data) - { - if (data == null) - throw new ArgumentNullException(nameof(data)); - - firstItemIndex = 0; - lastItemIndex = data.Count - 1; - items = CreateKeyValueArray(data.Count, data.GetEnumerator()); - } - - - private ConstantSplittableMap(KeyValuePair[] items, int firstItemIndex, int lastItemIndex) - { - this.items = items; - this.firstItemIndex = firstItemIndex; - this.lastItemIndex = lastItemIndex; - } - - - private KeyValuePair[] CreateKeyValueArray(int count, IEnumerator> data) - { - KeyValuePair[] kvArray = new KeyValuePair[count]; - - int i = 0; - while (data.MoveNext()) - kvArray[i++] = data.Current; - - Array.Sort(kvArray, keyValuePairComparator); - - return kvArray; - } - - - public int Count => lastItemIndex - firstItemIndex + 1; - - // [CLSCompliant(false)] - public uint Size => (uint)(lastItemIndex - firstItemIndex + 1); - - public TValue Lookup(TKey key) - { - if (!TryGetValue(key, out TValue value)) - { - Debug.Assert(key != null); - Exception e = new KeyNotFoundException(SR.Format(SR.Arg_KeyNotFoundWithKey, key.ToString())); - e.HResult = HResults.E_BOUNDS; - throw e; - } - - return value; - } - - - public bool HasKey(TKey key) => - TryGetValue(key, out _); - - IEnumerator IEnumerable.GetEnumerator() => - ((IEnumerable>)this).GetEnumerator(); - - public IIterator> First() => - new EnumeratorToIteratorAdapter>(GetEnumerator()); - - public IEnumerator> GetEnumerator() => - new IKeyValuePairEnumerator(items, firstItemIndex, lastItemIndex); - - public void Split(out IMapView? firstPartition, out IMapView? secondPartition) - { - if (Count < 2) - { - firstPartition = null; - secondPartition = null; - return; - } - - int pivot = (int)(((long)firstItemIndex + (long)lastItemIndex) / (long)2); - - firstPartition = new ConstantSplittableMap(items, firstItemIndex, pivot); - secondPartition = new ConstantSplittableMap(items, pivot + 1, lastItemIndex); - } - - #region IReadOnlyDictionary members - - public bool TryGetValue(TKey key, [MaybeNullWhen(false)] out TValue value) - { - KeyValuePair searchKey = new KeyValuePair(key, default!); - int index = Array.BinarySearch(items, firstItemIndex, Count, searchKey, keyValuePairComparator); - - if (index < 0) - { - value = default!; - return false; - } - - value = items[index].Value; - return true; - } - - #endregion IReadOnlyDictionary members - - #region IKeyValuePair Enumerator - - internal struct IKeyValuePairEnumerator : IEnumerator> - { - private readonly KeyValuePair[] _array; - private readonly int _start; - private readonly int _end; - private int _current; - - internal IKeyValuePairEnumerator(KeyValuePair[] items, int first, int end) - { - Debug.Assert(items != null); - Debug.Assert(first >= 0); - Debug.Assert(end >= 0); - Debug.Assert(first < items.Length); - Debug.Assert(end < items.Length); - - _array = items; - _start = first; - _end = end; - _current = _start - 1; - } - - public bool MoveNext() - { - if (_current < _end) - { - _current++; - return true; - } - return false; - } - - public IKeyValuePair Current - { - get - { - if (_current < _start) throw new InvalidOperationException(SR.InvalidOperation_EnumNotStarted); - if (_current > _end) throw new InvalidOperationException(SR.InvalidOperation_EnumEnded); - return new CLRIKeyValuePairImpl(ref _array[_current]); - } - } - - object? IEnumerator.Current => Current; - - void IEnumerator.Reset() => - _current = _start - 1; - - public void Dispose() - { - } - } - - #endregion IKeyValuePair Enumerator - } // internal ConstantSplittableMap -} // namespace System.Runtime.InteropServices.WindowsRuntime diff --git a/src/coreclr/src/System.Private.CoreLib/src/System/Runtime/InteropServices/WindowsRuntime/CustomPropertyImpl.cs b/src/coreclr/src/System.Private.CoreLib/src/System/Runtime/InteropServices/WindowsRuntime/CustomPropertyImpl.cs deleted file mode 100644 index f36e4be..0000000 --- a/src/coreclr/src/System.Private.CoreLib/src/System/Runtime/InteropServices/WindowsRuntime/CustomPropertyImpl.cs +++ /dev/null @@ -1,102 +0,0 @@ -// 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.Reflection; - -namespace System.Runtime.InteropServices.WindowsRuntime -{ - // - // ICustomProperty implementation - basically a wrapper of PropertyInfo - // - internal sealed class CustomPropertyImpl : ICustomProperty - { - private readonly PropertyInfo m_property; - - // - // Constructor - // - public CustomPropertyImpl(PropertyInfo propertyInfo) - { - if (propertyInfo == null) - throw new ArgumentNullException(nameof(propertyInfo)); - - m_property = propertyInfo; - } - - // - // ICustomProperty interface implementation - // - - public string Name => m_property.Name; - - public bool CanRead => - // Return false if the getter is not public - m_property.GetGetMethod() != null; - - public bool CanWrite => - // Return false if the setter is not public - m_property.GetSetMethod() != null; - - public object? GetValue(object target) - { - return InvokeInternal(target, null, true); - } - - // Unlike normal .Net, Jupiter properties can have at most one indexer parameter. A null - // indexValue here means that the property has an indexer argument and its value is null. - public object? GetValue(object target, object indexValue) - { - return InvokeInternal(target, new object[] { indexValue }, true); - } - - public void SetValue(object target, object value) - { - InvokeInternal(target, new object[] { value }, false); - } - - // Unlike normal .Net, Jupiter properties can have at most one indexer parameter. A null - // indexValue here means that the property has an indexer argument and its value is null. - public void SetValue(object target, object value, object indexValue) - { - InvokeInternal(target, new object[] { indexValue, value }, false); - } - - private object? InvokeInternal(object target, object[]? args, bool getValue) - { - // Forward to the right object if we are dealing with a proxy - if (target is IGetProxyTarget proxy) - { - target = proxy.GetTarget(); - } - - // You can get PropertyInfo for properties with a private getter/public setter (or vice versa) - // even if you pass BindingFlags.Public only. And in this case, passing binding flags to - // GetValue/SetValue won't work as the default binder ignores those values - // Use GetGetMethod/GetSetMethod instead - - // We get non-public accessors just so that we can throw the correct exception. - MethodInfo? accessor = getValue ? m_property.GetGetMethod(true) : m_property.GetSetMethod(true); - - if (accessor == null) - throw new ArgumentException(getValue ? SR.Arg_GetMethNotFnd : SR.Arg_SetMethNotFnd); - - if (!accessor.IsPublic) - throw new MethodAccessException( - SR.Format( - SR.Arg_MethodAccessException_WithMethodName, - accessor, - accessor.DeclaringType!.FullName)); - - RuntimeMethodInfo? rtMethod = accessor as RuntimeMethodInfo; - if (rtMethod == null) - throw new ArgumentException(SR.Argument_MustBeRuntimeMethodInfo); - - // 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. - return rtMethod.Invoke(target, BindingFlags.Default, null, args, null); - } - - public Type Type => m_property.PropertyType; - } -} diff --git a/src/coreclr/src/System.Private.CoreLib/src/System/Runtime/InteropServices/WindowsRuntime/DictionaryKeyCollection.cs b/src/coreclr/src/System.Private.CoreLib/src/System/Runtime/InteropServices/WindowsRuntime/DictionaryKeyCollection.cs deleted file mode 100644 index d11f950..0000000 --- a/src/coreclr/src/System.Private.CoreLib/src/System/Runtime/InteropServices/WindowsRuntime/DictionaryKeyCollection.cs +++ /dev/null @@ -1,113 +0,0 @@ -// 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; -using System.Diagnostics; - -namespace System.Runtime.InteropServices.WindowsRuntime -{ - [DebuggerDisplay("Count = {Count}")] - internal sealed class DictionaryKeyCollection : ICollection where TKey : notnull - { - private readonly IDictionary dictionary; - - public DictionaryKeyCollection(IDictionary dictionary) - { - if (dictionary == null) - throw new ArgumentNullException(nameof(dictionary)); - - this.dictionary = dictionary; - } - - public void CopyTo(TKey[] array, int index) - { - if (array == null) - throw new ArgumentNullException(nameof(array)); - if (index < 0) - throw new ArgumentOutOfRangeException(nameof(index)); - if (array.Length <= index && this.Count > 0) - throw new ArgumentException(SR.Arg_IndexOutOfRangeException); - if (array.Length - index < dictionary.Count) - throw new ArgumentException(SR.Argument_InsufficientSpaceToCopyCollection); - - int i = index; - foreach (KeyValuePair mapping in dictionary) - { - array[i++] = mapping.Key; - } - } - - public int Count => dictionary.Count; - - bool ICollection.IsReadOnly => true; - - void ICollection.Add(TKey item) - { - throw new NotSupportedException(SR.NotSupported_KeyCollectionSet); - } - - void ICollection.Clear() - { - throw new NotSupportedException(SR.NotSupported_KeyCollectionSet); - } - - public bool Contains(TKey item) - { - return dictionary.ContainsKey(item); - } - - bool ICollection.Remove(TKey item) - { - throw new NotSupportedException(SR.NotSupported_KeyCollectionSet); - } - - IEnumerator IEnumerable.GetEnumerator() - { - return ((IEnumerable)this).GetEnumerator(); - } - - public IEnumerator GetEnumerator() - { - return new DictionaryKeyEnumerator(dictionary); - } - } // public class DictionaryKeyCollection - - - internal sealed class DictionaryKeyEnumerator : IEnumerator where TKey : notnull - { - private readonly IDictionary dictionary; - private IEnumerator> enumeration; - - public DictionaryKeyEnumerator(IDictionary dictionary) - { - if (dictionary == null) - throw new ArgumentNullException(nameof(dictionary)); - - this.dictionary = dictionary; - enumeration = dictionary.GetEnumerator(); - } - - void IDisposable.Dispose() - { - enumeration.Dispose(); - } - - public bool MoveNext() - { - return enumeration.MoveNext(); - } - - object? IEnumerator.Current => ((IEnumerator)this).Current; - - public TKey Current => enumeration.Current.Key; - - public void Reset() - { - enumeration = dictionary.GetEnumerator(); - } - } // class DictionaryKeyEnumerator -} - -// DictionaryKeyCollection.cs diff --git a/src/coreclr/src/System.Private.CoreLib/src/System/Runtime/InteropServices/WindowsRuntime/DictionaryToMapAdapter.cs b/src/coreclr/src/System.Private.CoreLib/src/System/Runtime/InteropServices/WindowsRuntime/DictionaryToMapAdapter.cs deleted file mode 100644 index bdacad0..0000000 --- a/src/coreclr/src/System.Private.CoreLib/src/System/Runtime/InteropServices/WindowsRuntime/DictionaryToMapAdapter.cs +++ /dev/null @@ -1,102 +0,0 @@ -// 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.Generic; -using System.Collections.ObjectModel; -using System.Diagnostics; -using Internal.Runtime.CompilerServices; - -namespace System.Runtime.InteropServices.WindowsRuntime -{ - // This is a set of stub methods implementing the support for the IMap`2 interface on managed - // objects that implement IDictionary`2. Used by the interop mashaling infrastructure. - // - // The methods on this class must be written VERY carefully to avoid introducing security holes. - // That's because they are invoked with special "this"! The "this" object - // for all of these methods are not DictionaryToMapAdapter objects. Rather, they are of type - // IDictionary. No actual DictionaryToMapAdapter object is ever instantiated. Thus, you will - // see a lot of expressions that cast "this" to "IDictionary". - internal sealed class DictionaryToMapAdapter - { - private DictionaryToMapAdapter() - { - Debug.Fail("This class is never instantiated"); - } - - // V Lookup(K key) - internal V Lookup(K key) where K : notnull - { - IDictionary _this = Unsafe.As>(this); - if (!_this.TryGetValue(key, out V value)) - { - Debug.Assert(key != null); - Exception e = new KeyNotFoundException(SR.Format(SR.Arg_KeyNotFoundWithKey, key.ToString())); - e.HResult = HResults.E_BOUNDS; - throw e; - } - - return value; - } - - // uint Size { get } - internal uint Size() where K : notnull - { - IDictionary _this = Unsafe.As>(this); - return (uint)_this.Count; - } - - // bool HasKey(K key) - internal bool HasKey(K key) where K : notnull - { - IDictionary _this = Unsafe.As>(this); - return _this.ContainsKey(key); - } - - // IMapView GetView() - internal IReadOnlyDictionary GetView() where K : notnull - { - IDictionary _this = Unsafe.As>(this); - 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. - if (!(_this is IReadOnlyDictionary roDictionary)) - { - roDictionary = new ReadOnlyDictionary(_this); - } - return roDictionary; - } - - // bool Insert(K key, V value) - internal bool Insert(K key, V value) where K : notnull - { - IDictionary _this = Unsafe.As>(this); - bool replacing = _this.ContainsKey(key); - _this[key] = value; - return replacing; - } - - // void Remove(K key) - internal void Remove(K key) where K : notnull - { - IDictionary _this = Unsafe.As>(this); - bool removed = _this.Remove(key); - - if (!removed) - { - Debug.Assert(key != null); - Exception e = new KeyNotFoundException(SR.Format(SR.Arg_KeyNotFoundWithKey, key.ToString())); - e.HResult = HResults.E_BOUNDS; - throw e; - } - } - - // void Clear() - internal void Clear() where K : notnull - { - IDictionary _this = Unsafe.As>(this); - _this.Clear(); - } - } -} diff --git a/src/coreclr/src/System.Private.CoreLib/src/System/Runtime/InteropServices/WindowsRuntime/DictionaryValueCollection.cs b/src/coreclr/src/System.Private.CoreLib/src/System/Runtime/InteropServices/WindowsRuntime/DictionaryValueCollection.cs deleted file mode 100644 index 6272c09..0000000 --- a/src/coreclr/src/System.Private.CoreLib/src/System/Runtime/InteropServices/WindowsRuntime/DictionaryValueCollection.cs +++ /dev/null @@ -1,117 +0,0 @@ -// 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; -using System.Diagnostics; - -namespace System.Runtime.InteropServices.WindowsRuntime -{ - [DebuggerDisplay("Count = {Count}")] - internal sealed class DictionaryValueCollection : ICollection where TKey : notnull - { - private readonly IDictionary dictionary; - - public DictionaryValueCollection(IDictionary dictionary) - { - if (dictionary == null) - throw new ArgumentNullException(nameof(dictionary)); - - this.dictionary = dictionary; - } - - public void CopyTo(TValue[] array, int index) - { - if (array == null) - throw new ArgumentNullException(nameof(array)); - if (index < 0) - throw new ArgumentOutOfRangeException(nameof(index)); - if (array.Length <= index && this.Count > 0) - throw new ArgumentException(SR.Arg_IndexOutOfRangeException); - if (array.Length - index < dictionary.Count) - throw new ArgumentException(SR.Argument_InsufficientSpaceToCopyCollection); - - int i = index; - foreach (KeyValuePair mapping in dictionary) - { - array[i++] = mapping.Value; - } - } - - public int Count => dictionary.Count; - - bool ICollection.IsReadOnly => true; - - void ICollection.Add(TValue item) - { - throw new NotSupportedException(SR.NotSupported_ValueCollectionSet); - } - - void ICollection.Clear() - { - throw new NotSupportedException(SR.NotSupported_ValueCollectionSet); - } - - public bool Contains(TValue item) - { - EqualityComparer comparer = EqualityComparer.Default; - foreach (TValue value in this) - if (comparer.Equals(item, value)) - return true; - return false; - } - - bool ICollection.Remove(TValue item) - { - throw new NotSupportedException(SR.NotSupported_ValueCollectionSet); - } - - IEnumerator IEnumerable.GetEnumerator() - { - return ((IEnumerable)this).GetEnumerator(); - } - - public IEnumerator GetEnumerator() - { - return new DictionaryValueEnumerator(dictionary); - } - } // public class DictionaryValueCollection - - - internal sealed class DictionaryValueEnumerator : IEnumerator where TKey : notnull - { - private readonly IDictionary dictionary; - private IEnumerator> enumeration; - - public DictionaryValueEnumerator(IDictionary dictionary) - { - if (dictionary == null) - throw new ArgumentNullException(nameof(dictionary)); - - this.dictionary = dictionary; - enumeration = dictionary.GetEnumerator(); - } - - void IDisposable.Dispose() - { - enumeration.Dispose(); - } - - public bool MoveNext() - { - return enumeration.MoveNext(); - } - - object? IEnumerator.Current => ((IEnumerator)this).Current; - - public TValue Current => enumeration.Current.Value; - - public void Reset() - { - enumeration = dictionary.GetEnumerator(); - } - } // class DictionaryValueEnumerator -} - -// DictionaryValueCollection.cs diff --git a/src/coreclr/src/System.Private.CoreLib/src/System/Runtime/InteropServices/WindowsRuntime/EnumeratorToIteratorAdapter.cs b/src/coreclr/src/System.Private.CoreLib/src/System/Runtime/InteropServices/WindowsRuntime/EnumeratorToIteratorAdapter.cs deleted file mode 100644 index 8f5cb04..0000000 --- a/src/coreclr/src/System.Private.CoreLib/src/System/Runtime/InteropServices/WindowsRuntime/EnumeratorToIteratorAdapter.cs +++ /dev/null @@ -1,156 +0,0 @@ -// 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; -using System.Diagnostics; -using Internal.Runtime.CompilerServices; - -namespace System.Runtime.InteropServices.WindowsRuntime -{ - // This is a set of stub methods implementing the support for the IIterable`1 interface on managed - // objects that implement IEnumerable`1. Used by the interop mashaling infrastructure. - // - // The methods on this class must be written VERY carefully to avoid introducing security holes. - // That's because they are invoked with special "this"! The "this" object - // for all of these methods are not EnumerableToIterableAdapter objects. Rather, they are of type - // IEnumerable. No actual EnumerableToIterableAdapter object is ever instantiated. Thus, you will - // see a lot of expressions that cast "this" to "IEnumerable". - internal sealed class EnumerableToIterableAdapter - { - private EnumerableToIterableAdapter() - { - Debug.Fail("This class is never instantiated"); - } - - // This method is invoked when First is called on a managed implementation of IIterable. - internal IIterator First_Stub() - { - IEnumerable _this = Unsafe.As>(this); - return new EnumeratorToIteratorAdapter(_this.GetEnumerator()); - } - } - - internal sealed class EnumerableToBindableIterableAdapter - { - private EnumerableToBindableIterableAdapter() - { - Debug.Fail("This class is never instantiated"); - } - - internal sealed class NonGenericToGenericEnumerator : IEnumerator - { - private readonly IEnumerator enumerator; - - public NonGenericToGenericEnumerator(IEnumerator enumerator) - { this.enumerator = enumerator; } - - public object? Current => enumerator.Current; - public bool MoveNext() { return enumerator.MoveNext(); } - public void Reset() { enumerator.Reset(); } - public void Dispose() { } - } - - // This method is invoked when First is called on a managed implementation of IBindableIterable. - internal IBindableIterator First_Stub() - { - IEnumerable _this = Unsafe.As(this); - return new EnumeratorToIteratorAdapter(new NonGenericToGenericEnumerator(_this.GetEnumerator())); - } - } - - // Adapter class which holds a managed IEnumerator, exposing it as a Windows Runtime IIterator - internal sealed class EnumeratorToIteratorAdapter : IIterator, IBindableIterator - { - private readonly IEnumerator m_enumerator; - private bool m_firstItem = true; - private bool m_hasCurrent; - - internal EnumeratorToIteratorAdapter(IEnumerator enumerator) - { - Debug.Assert(enumerator != null); - m_enumerator = enumerator; - } - - public T Current - { - get - { - // IEnumerator starts at item -1, while IIterators start at item 0. Therefore, if this is the - // first access to the iterator we need to advance to the first item. - if (m_firstItem) - { - m_firstItem = false; - MoveNext(); - } - - if (!m_hasCurrent) - { - throw WindowsRuntimeMarshal.GetExceptionForHR(HResults.E_BOUNDS, null); - } - - return m_enumerator.Current; - } - } - - object? IBindableIterator.Current => ((IIterator)this).Current; - - public bool HasCurrent - { - get - { - // IEnumerator starts at item -1, while IIterators start at item 0. Therefore, if this is the - // first access to the iterator we need to advance to the first item. - if (m_firstItem) - { - m_firstItem = false; - MoveNext(); - } - - return m_hasCurrent; - } - } - - public bool MoveNext() - { - try - { - m_hasCurrent = m_enumerator.MoveNext(); - } - catch (InvalidOperationException e) - { - throw WindowsRuntimeMarshal.GetExceptionForHR(HResults.E_CHANGED_STATE, e); - } - - return m_hasCurrent; - } - - public int GetMany(T[] items) - { - if (items == null) - { - return 0; - } - - int index = 0; - while (index < items.Length && HasCurrent) - { - items[index] = Current; - MoveNext(); - ++index; - } - - if (typeof(T) == typeof(string)) - { - string[] stringItems = (items as string[])!; - - // Fill the rest of the array with string.Empty to avoid marshaling failure - for (int i = index; i < items.Length; ++i) - stringItems[i] = string.Empty; - } - - return index; - } - } -} diff --git a/src/coreclr/src/System.Private.CoreLib/src/System/Runtime/InteropServices/WindowsRuntime/EventRegistrationTokenTable.cs b/src/coreclr/src/System.Private.CoreLib/src/System/Runtime/InteropServices/WindowsRuntime/EventRegistrationTokenTable.cs deleted file mode 100644 index ce52f02..0000000 --- a/src/coreclr/src/System.Private.CoreLib/src/System/Runtime/InteropServices/WindowsRuntime/EventRegistrationTokenTable.cs +++ /dev/null @@ -1,246 +0,0 @@ -// 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.Generic; -using System.Diagnostics; -using System.Diagnostics.CodeAnalysis; -using System.Threading; - -namespace System.Runtime.InteropServices.WindowsRuntime -{ - // An event registration token table stores mappings from delegates to event tokens, in order to support - // sourcing WinRT style events from managed code. - public sealed class EventRegistrationTokenTable where T : class - { - // Note this dictionary is also used as the synchronization object for this table - private readonly Dictionary m_tokens = new Dictionary(); - - // Cached multicast delegate which will invoke all of the currently registered delegates. This - // will be accessed frequently in common coding paterns, so we don't want to calculate it repeatedly. - private volatile T? m_invokeList = null; - - public EventRegistrationTokenTable() - { - // T must be a delegate type, but we cannot constrain on being a delegate. Therefore, we'll do a - // static check at construction time - if (!typeof(Delegate).IsAssignableFrom(typeof(T))) - { - throw new InvalidOperationException(SR.Format(SR.InvalidOperation_EventTokenTableRequiresDelegate, typeof(T))); - } - } - - // The InvocationList property provides access to a delegate which will invoke every registered event handler - // in this table. If the property is set, the new value will replace any existing token registrations. - public T? InvocationList - { - get => m_invokeList; - set - { - lock (m_tokens) - { - // The value being set replaces any of the existing values - m_tokens.Clear(); - m_invokeList = null; - - if (value != null) - { - AddEventHandlerNoLock(value); - } - } - } - } - - public EventRegistrationToken AddEventHandler(T? handler) - { - // Windows Runtime allows null handlers. Assign those a token value of 0 for easy identity - if (handler == null) - { - return new EventRegistrationToken(0); - } - - lock (m_tokens) - { - return AddEventHandlerNoLock(handler); - } - } - - private EventRegistrationToken AddEventHandlerNoLock(T handler) - { - Debug.Assert(handler != null); - - // Get a registration token, making sure that we haven't already used the value. This should be quite - // rare, but in the case it does happen, just keep trying until we find one that's unused. - EventRegistrationToken token = GetPreferredToken(handler); - while (m_tokens.ContainsKey(token)) - { - token = new EventRegistrationToken(token.Value + 1); - } - m_tokens[token] = handler; - - // Update the current invocation list to include the newly added delegate - Delegate? invokeList = (Delegate?)(object?)m_invokeList; - invokeList = MulticastDelegate.Combine(invokeList, (Delegate)(object)handler); - m_invokeList = (T?)(object?)invokeList; - - return token; - } - - // Generate a token that may be used for a particular event handler. We will frequently be called - // upon to look up a token value given only a delegate to start from. Therefore, we want to make - // an initial token value that is easily determined using only the delegate instance itself. Although - // in the common case this token value will be used to uniquely identify the handler, it is not - // the only possible token that can represent the handler. - // - // This means that both: - // * if there is a handler assigned to the generated initial token value, it is not necessarily - // this handler. - // * if there is no handler assigned to the generated initial token value, the handler may still - // be registered under a different token - // - // Effectively the only reasonable thing to do with this value is either to: - // 1. Use it as a good starting point for generating a token for handler - // 2. Use it as a guess to quickly see if the handler was really assigned this token value - private static EventRegistrationToken GetPreferredToken(T handler) - { - Debug.Assert(handler != null); - - // We want to generate a token value that has the following properties: - // 1. is quickly obtained from the handler instance - // 2. uses bits in the upper 32 bits of the 64 bit value, in order to avoid bugs where code - // may assume the value is realy just 32 bits - // 3. uses bits in the bottom 32 bits of the 64 bit value, in order to ensure that code doesn't - // take a dependency on them always being 0. - // - // The simple algorithm chosen here is to simply assign the upper 32 bits the metadata token of the - // event handler type, and the lower 32 bits the hash code of the handler instance itself. Using the - // metadata token for the upper 32 bits gives us at least a small chance of being able to identify a - // totally corrupted token if we ever come across one in a minidump or other scenario. - // - // The hash code of a unicast delegate is not tied to the method being invoked, so in the case - // of a unicast delegate, the hash code of the target method is used instead of the full delegate - // hash code. - // - // While calculating this initial value will be somewhat more expensive than just using a counter - // for events that have few registrations, it will also gives us a shot at preventing unregistration - // from becoming an O(N) operation. - // - // We should feel free to change this algorithm as other requirements / optimizations become - // available. This implementation is sufficiently random that code cannot simply guess the value to - // take a dependency upon it. (Simply applying the hash-value algorithm directly won't work in the - // case of collisions, where we'll use a different token value). - - uint handlerHashCode; - Delegate[] invocationList = ((Delegate)(object)handler).GetInvocationList(); - if (invocationList.Length == 1) - { - handlerHashCode = (uint)invocationList[0].Method.GetHashCode(); - } - else - { - handlerHashCode = (uint)handler.GetHashCode(); - } - - ulong tokenValue = ((ulong)(uint)typeof(T).MetadataToken << 32) | handlerHashCode; - return new EventRegistrationToken(tokenValue); - } - - // Remove the event handler from the table and - // Get the delegate associated with an event registration token if it exists - // If the event registration token is not registered, returns false - public bool RemoveEventHandler(EventRegistrationToken token, [NotNullWhen(true)] out T? handler) - { - lock (m_tokens) - { - if (m_tokens.TryGetValue(token, out handler)) - { - RemoveEventHandlerNoLock(token); - return true; - } - } - - return false; - } - - public void RemoveEventHandler(EventRegistrationToken token) - { - // The 0 token is assigned to null handlers, so there's nothing to do - if (token.Value == 0) - { - return; - } - - lock (m_tokens) - { - RemoveEventHandlerNoLock(token); - } - } - - public void RemoveEventHandler(T? handler) - { - // To match the Windows Runtime behaivor when adding a null handler, removing one is a no-op - if (handler == null) - { - return; - } - - lock (m_tokens) - { - // Fast path - if the delegate is stored with its preferred token, then there's no need to do - // a full search of the table for it. Note that even if we find something stored using the - // preferred token value, it's possible we have a collision and another delegate was using that - // value. Therefore we need to make sure we really have the handler we want before taking the - // fast path. - EventRegistrationToken preferredToken = GetPreferredToken(handler); - if (m_tokens.TryGetValue(preferredToken, out T? registeredHandler)) - { - if (registeredHandler == handler) - { - RemoveEventHandlerNoLock(preferredToken); - return; - } - } - - // Slow path - we didn't find the delegate with its preferred token, so we need to fall - // back to a search of the table - foreach (KeyValuePair registration in m_tokens) - { - if (registration.Value == (T)(object)handler) - { - RemoveEventHandlerNoLock(registration.Key); - - // If a delegate has been added multiple times to handle an event, then it - // needs to be removed the same number of times to stop handling the event. - // Stop after the first one we find. - return; - } - } - - // Note that falling off the end of the loop is not an error, as removing a registration - // for a handler that is not currently registered is simply a no-op - } - } - - private void RemoveEventHandlerNoLock(EventRegistrationToken token) - { - if (m_tokens.TryGetValue(token, out T? handler)) - { - m_tokens.Remove(token); - - // Update the current invocation list to remove the delegate - Delegate? invokeList = (Delegate?)(object?)m_invokeList; - invokeList = MulticastDelegate.Remove(invokeList, (Delegate?)(object?)handler); - m_invokeList = (T?)(object?)invokeList; - } - } - - public static EventRegistrationTokenTable GetOrCreateEventRegistrationTokenTable(ref EventRegistrationTokenTable? refEventTable) - { - if (refEventTable == null) - { - Interlocked.CompareExchange(ref refEventTable, new EventRegistrationTokenTable(), null); - } - return refEventTable; - } - } -} diff --git a/src/coreclr/src/System.Private.CoreLib/src/System/Runtime/InteropServices/WindowsRuntime/IClosable.cs b/src/coreclr/src/System.Private.CoreLib/src/System/Runtime/InteropServices/WindowsRuntime/IClosable.cs deleted file mode 100644 index e5df5f4..0000000 --- a/src/coreclr/src/System.Private.CoreLib/src/System/Runtime/InteropServices/WindowsRuntime/IClosable.cs +++ /dev/null @@ -1,48 +0,0 @@ -// 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 Internal.Runtime.CompilerServices; - -namespace System.Runtime.InteropServices.WindowsRuntime -{ - // Local definition of Windows.Foundation.IClosable - [ComImport] - [Guid("30d5a829-7fa4-4026-83bb-d75bae4ea99e")] - [WindowsRuntimeImport] - internal interface IClosable - { - void Close(); - } - - // Adapter class - converts IClosable.Close calls to Disposable.Dispose - internal sealed class IDisposableToIClosableAdapter - { - private IDisposableToIClosableAdapter() - { - Debug.Fail("This class is never instantiated"); - } - - public void Close() - { - IDisposable _this = Unsafe.As(this); - _this.Dispose(); - } - } - - // Adapter class which converts IDisposable.Dispose calls into IClosable.Close - internal sealed class IClosableToIDisposableAdapter - { - private IClosableToIDisposableAdapter() - { - Debug.Fail("This class is never instantiated"); - } - - private void Dispose() - { - IClosable _this = Unsafe.As(this); - _this.Close(); - } - } -} diff --git a/src/coreclr/src/System.Private.CoreLib/src/System/Runtime/InteropServices/WindowsRuntime/ICustomProperty.cs b/src/coreclr/src/System.Private.CoreLib/src/System/Runtime/InteropServices/WindowsRuntime/ICustomProperty.cs deleted file mode 100644 index 1b95ef6..0000000 --- a/src/coreclr/src/System.Private.CoreLib/src/System/Runtime/InteropServices/WindowsRuntime/ICustomProperty.cs +++ /dev/null @@ -1,40 +0,0 @@ -// 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 System.Runtime.InteropServices.WindowsRuntime -{ - [ComImport] - [Guid("30DA92C0-23E8-42A0-AE7C-734A0E5D2782")] - [WindowsRuntimeImport] - internal interface ICustomProperty - { - Type Type - { - get; - } - - string Name - { - get; - } - - object? GetValue(object target); - - void SetValue(object target, object value); - - object? GetValue(object target, object indexValue); - - void SetValue(object target, object value, object indexValue); - - bool CanWrite - { - get; - } - - bool CanRead - { - get; - } - } -} diff --git a/src/coreclr/src/System.Private.CoreLib/src/System/Runtime/InteropServices/WindowsRuntime/ICustomPropertyProvider.cs b/src/coreclr/src/System.Private.CoreLib/src/System/Runtime/InteropServices/WindowsRuntime/ICustomPropertyProvider.cs deleted file mode 100644 index 819d570..0000000 --- a/src/coreclr/src/System.Private.CoreLib/src/System/Runtime/InteropServices/WindowsRuntime/ICustomPropertyProvider.cs +++ /dev/null @@ -1,519 +0,0 @@ -// 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.StubHelpers; -using System.Reflection; -using System.Diagnostics; -using System.Collections; -using System.Collections.Generic; -using Internal.Runtime.CompilerServices; - -namespace System.Runtime.InteropServices.WindowsRuntime -{ - // - // ICustomProperty Implementation helpers - // - internal static class ICustomPropertyProviderImpl - { - // - // Creates a ICustomProperty implementation for Jupiter - // Called from ICustomPropertyProvider_GetProperty from within runtime - // - internal static ICustomProperty? CreateProperty(object target, string propertyName) - { - Debug.Assert(target != null); - Debug.Assert(propertyName != null); - - if (target is IGetProxyTarget proxy) - target = proxy.GetTarget(); - - // Only return public instance/static properties - PropertyInfo? propertyInfo = target.GetType().GetProperty( - propertyName, - BindingFlags.Instance | BindingFlags.Static | BindingFlags.Public); - - if (propertyInfo == null) - return null; - else - return new CustomPropertyImpl(propertyInfo); - } - - // - // Creates a ICustomProperty implementation for Jupiter - // Called from ICustomPropertyProvider_GetIndexedProperty from within runtime - // - internal static unsafe ICustomProperty? CreateIndexedProperty(object target, string propertyName, TypeNameNative* pIndexedParamType) - { - Debug.Assert(target != null); - Debug.Assert(propertyName != null); - - Type? indexedParamType = null; - SystemTypeMarshaler.ConvertToManaged(pIndexedParamType, ref indexedParamType); - - return CreateIndexedProperty(target, propertyName, indexedParamType!); - } - - internal static ICustomProperty? CreateIndexedProperty(object target, string propertyName, Type indexedParamType) - { - Debug.Assert(target != null); - Debug.Assert(propertyName != null); - - if (target is IGetProxyTarget proxy) - target = proxy.GetTarget(); - - // Only return public instance/static properties - PropertyInfo? propertyInfo = target.GetType().GetProperty( - propertyName, - BindingFlags.Instance | BindingFlags.Static | BindingFlags.Public, - null, // default binder - null, // ignore return type - new Type[] { indexedParamType }, // indexed parameter type - null // ignore type modifier - ); - - if (propertyInfo == null) - return null; - else - return new CustomPropertyImpl(propertyInfo); - } - - internal static unsafe void GetType(object target, TypeNameNative* pIndexedParamType) - { - if (target is IGetProxyTarget proxy) - target = proxy.GetTarget(); - - SystemTypeMarshaler.ConvertToNative(target.GetType(), pIndexedParamType); - } - } - - [Flags] - internal enum InterfaceForwardingSupport - { - None = 0, - IBindableVector = 0x1, // IBindableVector -> IBindableVector - IVector = 0x2, // IBindableVector -> IVector - IBindableVectorView = 0x4, // IBindableVectorView -> IBindableVectorView - IVectorView = 0x8, // IBindableVectorView -> IVectorView - IBindableIterableOrIIterable = 0x10 // IBindableIterable -> IBindableIterable/IIterable - } - - // - // Interface for data binding code (CustomPropertyImpl) to retrieve the target object - // See CustomPropertyImpl.InvokeInternal for details - // - internal interface IGetProxyTarget - { - object GetTarget(); - } - - // - // Proxy that supports data binding on another object - // - // This serves two purposes: - // - // 1. Delegate data binding interfaces to another object - // Note that this proxy implements the native interfaces directly to avoid unnecessary overhead - // (such as the adapter code that addresses behavior differences between IBindableVector & List - // as well as simplify forwarding code (except for IEnumerable) - // - // 2. ICLRServices.GetTrackerTarget will hand out ICCW* of a new instance of this object - // and will hold the other object alive - // - // - internal class ICustomPropertyProviderProxy : IGetProxyTarget, - ICustomQueryInterface, - IEnumerable, // IBindableIterable -> IBindableIterable/IIterable - IBindableVector, // IBindableVector -> IBindableVector/IVector - IBindableVectorView // IBindableVectorView -> IBindableVectorView/IVectorView - { - private readonly object _target; - private readonly InterfaceForwardingSupport _flags; - - internal ICustomPropertyProviderProxy(object target, InterfaceForwardingSupport flags) - { - _target = target; - _flags = flags; - } - - // - // Creates a new instance of ICustomPropertyProviderProxy and assign appropriate - // flags - // - internal static object CreateInstance(object target) - { - InterfaceForwardingSupport supportFlags = InterfaceForwardingSupport.None; - - // - // QI and figure out the right flags - // - if (target is IList) - supportFlags |= InterfaceForwardingSupport.IBindableVector; - - // NOTE: We need to use the directed type here - // If we use IVector_Raw here, it derives from a different IIterable which the runtime - // doesn't recognize, and therefore IEnumerable cast won't be able to take advantage of this QI - if (target is IList) - supportFlags |= InterfaceForwardingSupport.IVector; - - if (target is IBindableVectorView) - supportFlags |= InterfaceForwardingSupport.IBindableVectorView; - - // NOTE: We need to use the redirected type here - // If we use IVector_Raw here, it derives from a different IIterable which the runtime - // doesn't recognize, and therefore IEnumerable cast won't be able to take advantage of this QI - if (target is IReadOnlyList) - supportFlags |= InterfaceForwardingSupport.IVectorView; - - // Verify IEnumerable last because the first few QIs might succeed and we need - // IEnumerable cast to use that cache (instead of having ICustomPropertyProvider to - // forward it manually) - // For example, if we try to shoot in the dark by trying IVector and it - // succeeded, IEnumerable needs to know that - if (target is IEnumerable) - supportFlags |= InterfaceForwardingSupport.IBindableIterableOrIIterable; - - return new ICustomPropertyProviderProxy(target, supportFlags); - } - - - // - // override ToString() to make sure callers get correct IStringable.ToString() behavior in native code - // - public override string? ToString() - { - return WindowsRuntime.IStringableHelper.ToString(_target); - } - - // - // IGetProxyTarget - unwraps the target object and use it for data binding - // - object IGetProxyTarget.GetTarget() - { - return _target; - } - - // - // ICustomQueryInterface methods - // - public CustomQueryInterfaceResult GetInterface([In]ref Guid iid, out IntPtr ppv) - { - ppv = IntPtr.Zero; - - if (iid == typeof(IBindableIterable).GUID) - { - // Reject the QI if target doesn't implement IEnumerable - if ((_flags & (InterfaceForwardingSupport.IBindableIterableOrIIterable)) == 0) - return CustomQueryInterfaceResult.Failed; - } - - if (iid == typeof(IBindableVector).GUID) - { - // Reject the QI if target doesn't implement IBindableVector/IVector - if ((_flags & (InterfaceForwardingSupport.IBindableVector | InterfaceForwardingSupport.IVector)) == 0) - return CustomQueryInterfaceResult.Failed; - } - - if (iid == typeof(IBindableVectorView).GUID) - { - // Reject the QI if target doesn't implement IBindableVectorView/IVectorView - if ((_flags & (InterfaceForwardingSupport.IBindableVectorView | InterfaceForwardingSupport.IVectorView)) == 0) - return CustomQueryInterfaceResult.Failed; - } - - return CustomQueryInterfaceResult.NotHandled; - } - - // - // IEnumerable methods - // - public IEnumerator GetEnumerator() - { - return ((IEnumerable)_target).GetEnumerator(); - } - - // - // IBindableVector implementation (forwards to IBindableVector / IVector) - // - object? IBindableVector.GetAt(uint index) - { - IBindableVector? bindableVector = GetIBindableVectorNoThrow(); - if (bindableVector != null) - { - // IBindableVector -> IBindableVector - return bindableVector.GetAt(index); - } - else - { - // IBindableVector -> IVector - return GetVectorOfT().GetAt(index); - } - } - - uint IBindableVector.Size - { - get - { - IBindableVector? bindableVector = GetIBindableVectorNoThrow(); - if (bindableVector != null) - { - // IBindableVector -> IBindableVector - return bindableVector.Size; - } - else - { - // IBindableVector -> IVector - return GetVectorOfT().Size; - } - } - } - - IBindableVectorView IBindableVector.GetView() - { - IBindableVector? bindableVector = GetIBindableVectorNoThrow(); - if (bindableVector != null) - { - // IBindableVector -> IBindableVector - return bindableVector.GetView(); - } - else - { - // IBindableVector -> IVector - return new IVectorViewToIBindableVectorViewAdapter(GetVectorOfT().GetView()); - } - } - - private sealed class IVectorViewToIBindableVectorViewAdapter : IBindableVectorView - { - private readonly IVectorView _vectorView; - - public IVectorViewToIBindableVectorViewAdapter(IVectorView vectorView) - { - _vectorView = vectorView; - } - - object? IBindableVectorView.GetAt(uint index) - { - return _vectorView.GetAt(index); - } - - uint IBindableVectorView.Size => _vectorView.Size; - - bool IBindableVectorView.IndexOf(object value, out uint index) - { - return _vectorView.IndexOf(ConvertTo(value), out index); - } - - IBindableIterator IBindableIterable.First() - { - return new IteratorOfTToIteratorAdapter(_vectorView.First()); - } - } - - bool IBindableVector.IndexOf(object value, out uint index) - { - IBindableVector? bindableVector = GetIBindableVectorNoThrow(); - if (bindableVector != null) - { - // IBindableVector -> IBindableVector - return bindableVector.IndexOf(value, out index); - } - else - { - // IBindableVector -> IVector - return GetVectorOfT().IndexOf(ConvertTo(value), out index); - } - } - - void IBindableVector.SetAt(uint index, object value) - { - IBindableVector? bindableVector = GetIBindableVectorNoThrow(); - if (bindableVector != null) - { - // IBindableVector -> IBindableVector - bindableVector.SetAt(index, value); - } - else - { - // IBindableVector -> IVector - GetVectorOfT().SetAt(index, ConvertTo(value)); - } - } - - void IBindableVector.InsertAt(uint index, object value) - { - IBindableVector? bindableVector = GetIBindableVectorNoThrow(); - if (bindableVector != null) - { - // IBindableVector -> IBindableVector - bindableVector.InsertAt(index, value); - } - else - { - // IBindableVector -> IVector - GetVectorOfT().InsertAt(index, ConvertTo(value)); - } - } - - void IBindableVector.RemoveAt(uint index) - { - IBindableVector? bindableVector = GetIBindableVectorNoThrow(); - if (bindableVector != null) - { - // IBindableVector -> IBindableVector - bindableVector.RemoveAt(index); - } - else - { - // IBindableVector -> IVector - GetVectorOfT().RemoveAt(index); - } - } - - void IBindableVector.Append(object value) - { - IBindableVector? bindableVector = GetIBindableVectorNoThrow(); - if (bindableVector != null) - { - // IBindableVector -> IBindableVector - bindableVector.Append(value); - } - else - { - // IBindableVector -> IVector - GetVectorOfT().Append(ConvertTo(value)); - } - } - - void IBindableVector.RemoveAtEnd() - { - IBindableVector? bindableVector = GetIBindableVectorNoThrow(); - if (bindableVector != null) - { - // IBindableVector -> IBindableVector - bindableVector.RemoveAtEnd(); - } - else - { - // IBindableVector -> IVector - GetVectorOfT().RemoveAtEnd(); - } - } - - void IBindableVector.Clear() - { - IBindableVector? bindableVector = GetIBindableVectorNoThrow(); - if (bindableVector != null) - { - // IBindableVector -> IBindableVector - bindableVector.Clear(); - } - else - { - // IBindableVector -> IVector - GetVectorOfT().Clear(); - } - } - - private IBindableVector? GetIBindableVectorNoThrow() - { - if ((_flags & InterfaceForwardingSupport.IBindableVector) != 0) - return Unsafe.As(_target); - else - return null; - } - - private IVector_Raw GetVectorOfT() - { - if ((_flags & InterfaceForwardingSupport.IVector) != 0) - return Unsafe.As>(_target); - else - throw new InvalidOperationException(); // We should not go down this path, unless Jupiter pass this out to managed code - // and managed code use reflection to do the cast - } - - // - // IBindableVectorView implementation (forwarding to IBindableVectorView or IVectorView) - // - object? IBindableVectorView.GetAt(uint index) - { - IBindableVectorView? bindableVectorView = GetIBindableVectorViewNoThrow(); - if (bindableVectorView != null) - return bindableVectorView.GetAt(index); - else - return GetVectorViewOfT().GetAt(index); - } - - uint IBindableVectorView.Size - { - get - { - IBindableVectorView? bindableVectorView = GetIBindableVectorViewNoThrow(); - if (bindableVectorView != null) - return bindableVectorView.Size; - else - return GetVectorViewOfT().Size; - } - } - - bool IBindableVectorView.IndexOf(object value, out uint index) - { - IBindableVectorView? bindableVectorView = GetIBindableVectorViewNoThrow(); - if (bindableVectorView != null) - return bindableVectorView.IndexOf(value, out index); - else - return GetVectorViewOfT().IndexOf(ConvertTo(value), out index); - } - - IBindableIterator IBindableIterable.First() - { - IBindableVectorView? bindableVectorView = GetIBindableVectorViewNoThrow(); - if (bindableVectorView != null) - return bindableVectorView.First(); - else - return new IteratorOfTToIteratorAdapter(GetVectorViewOfT().First()); - } - - private sealed class IteratorOfTToIteratorAdapter : IBindableIterator - { - private readonly IIterator _iterator; - - public IteratorOfTToIteratorAdapter(IIterator iterator) - { _iterator = iterator; } - - public bool HasCurrent => _iterator.HasCurrent; - public object? Current => _iterator.Current; - public bool MoveNext() { return _iterator.MoveNext(); } - } - - private IBindableVectorView? GetIBindableVectorViewNoThrow() - { - if ((_flags & InterfaceForwardingSupport.IBindableVectorView) != 0) - return Unsafe.As(_target); - else - return null; - } - - private IVectorView GetVectorViewOfT() - { - if ((_flags & InterfaceForwardingSupport.IVectorView) != 0) - return Unsafe.As>(_target); - else - throw new InvalidOperationException(); // We should not go down this path, unless Jupiter pass this out to managed code - // and managed code use reflection to do the cast - } - - // - // Convert to type T - // - private static T ConvertTo(object value) - { - // Throw ArgumentNullException if value is null (otherwise we'll throw NullReferenceException - // when casting value to T) - ThrowHelper.IfNullAndNullsAreIllegalThenThrow(value, ExceptionArgument.value); - - // No coersion support needed. If we need coersion later, this is the place - return (T)value; - } - } -} diff --git a/src/coreclr/src/System.Private.CoreLib/src/System/Runtime/InteropServices/WindowsRuntime/IIterable.cs b/src/coreclr/src/System.Private.CoreLib/src/System/Runtime/InteropServices/WindowsRuntime/IIterable.cs deleted file mode 100644 index 39f0f96..0000000 --- a/src/coreclr/src/System.Private.CoreLib/src/System/Runtime/InteropServices/WindowsRuntime/IIterable.cs +++ /dev/null @@ -1,27 +0,0 @@ -// 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.Generic; - -// Windows.Foundation.Collections.IIterable`1 cannot be referenced from managed code because it's hidden -// by the metadata adapter. We redeclare the interface manually to be able to talk to native WinRT objects. - -namespace System.Runtime.InteropServices.WindowsRuntime -{ - [ComImport] - [Guid("faa585ea-6214-4217-afda-7f46de5869b3")] - [WindowsRuntimeImport] - internal interface IIterable : IEnumerable - { - IIterator First(); - } - - [ComImport] - [Guid("036d2c08-df29-41af-8aa2-d774be62ba6f")] - [WindowsRuntimeImport] - internal interface IBindableIterable - { - IBindableIterator First(); - } -} diff --git a/src/coreclr/src/System.Private.CoreLib/src/System/Runtime/InteropServices/WindowsRuntime/IIterator.cs b/src/coreclr/src/System.Private.CoreLib/src/System/Runtime/InteropServices/WindowsRuntime/IIterator.cs deleted file mode 100644 index 2ce2e1d..0000000 --- a/src/coreclr/src/System.Private.CoreLib/src/System/Runtime/InteropServices/WindowsRuntime/IIterator.cs +++ /dev/null @@ -1,44 +0,0 @@ -// 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 System.Runtime.InteropServices.WindowsRuntime -{ - [ComImport] - [WindowsRuntimeImport] - [Guid("6a79e863-4300-459a-9966-cbb660963ee1")] - internal interface IIterator - { - T Current - { - get; - } - - bool HasCurrent - { - get; - } - - bool MoveNext(); - - int GetMany([Out] T[] items); - } - - [ComImport] - [WindowsRuntimeImport] - [Guid("6a1d6c07-076d-49f2-8314-f52c9c9a8331")] - internal interface IBindableIterator - { - object? Current - { - get; - } - - bool HasCurrent - { - get; - } - - bool MoveNext(); - } -} diff --git a/src/coreclr/src/System.Private.CoreLib/src/System/Runtime/InteropServices/WindowsRuntime/IMap.cs b/src/coreclr/src/System.Private.CoreLib/src/System/Runtime/InteropServices/WindowsRuntime/IMap.cs deleted file mode 100644 index 164350a..0000000 --- a/src/coreclr/src/System.Private.CoreLib/src/System/Runtime/InteropServices/WindowsRuntime/IMap.cs +++ /dev/null @@ -1,46 +0,0 @@ -// 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.Generic; - -// Windows.Foundation.Collections.IMap`2, IMapView`2, and IKeyValuePair`2 cannot be referenced from -// managed code because they're hidden by the metadata adapter. We redeclare the interfaces manually -// to be able to talk to native WinRT objects. - -namespace System.Runtime.InteropServices.WindowsRuntime -{ - [ComImport] - [Guid("3c2925fe-8519-45c1-aa79-197b6718c1c1")] - [WindowsRuntimeImport] - internal interface IMap : IIterable> where K : notnull - { - V Lookup(K key); - uint Size { get; } - bool HasKey(K key); - IReadOnlyDictionary GetView(); // Really an IMapView - bool Insert(K key, V value); - void Remove(K key); - void Clear(); - } - - [ComImport] - [Guid("e480ce40-a338-4ada-adcf-272272e48cb9")] - [WindowsRuntimeImport] - internal interface IMapView : IIterable> - { - V Lookup(K key); - uint Size { get; } - bool HasKey(K key); - void Split(out IMapView? first, out IMapView? second); - } - - [ComImport] - [Guid("02b51929-c1c4-4a7e-8940-0312b5c18500")] - [WindowsRuntimeImport] - internal interface IKeyValuePair - { - K Key { get; } - V Value { get; } - } -} diff --git a/src/coreclr/src/System.Private.CoreLib/src/System/Runtime/InteropServices/WindowsRuntime/IMapViewToIReadOnlyDictionaryAdapter.cs b/src/coreclr/src/System.Private.CoreLib/src/System/Runtime/InteropServices/WindowsRuntime/IMapViewToIReadOnlyDictionaryAdapter.cs deleted file mode 100644 index 567de57..0000000 --- a/src/coreclr/src/System.Private.CoreLib/src/System/Runtime/InteropServices/WindowsRuntime/IMapViewToIReadOnlyDictionaryAdapter.cs +++ /dev/null @@ -1,299 +0,0 @@ -// 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; -using System.Diagnostics; -using System.Diagnostics.CodeAnalysis; -using Internal.Runtime.CompilerServices; - -namespace System.Runtime.InteropServices.WindowsRuntime -{ - // This is a set of stub methods implementing the support for the IReadOnlyDictionary`2 interface on WinRT - // objects that support IMapView`2. Used by the interop mashaling infrastructure. - // - // The methods on this class must be written VERY carefully to avoid introducing security holes. - // That's because they are invoked with special "this"! The "this" object - // for all of these methods are not IMapViewToIReadOnlyDictionaryAdapter objects. Rather, they are of type - // IMapView. No actual IMapViewToIReadOnlyDictionaryAdapter object is ever instantiated. Thus, you will see - // a lot of expressions that cast "this" to "IMapView". - [DebuggerDisplay("Count = {Count}")] - internal sealed class IMapViewToIReadOnlyDictionaryAdapter - { - private IMapViewToIReadOnlyDictionaryAdapter() - { - Debug.Fail("This class is never instantiated"); - } - - // V this[K key] { get } - internal V Indexer_Get(K key) - { - if (key == null) - throw new ArgumentNullException(nameof(key)); - - IMapView _this = Unsafe.As>(this); - return Lookup(_this, key); - } - - // IEnumerable Keys { get } - internal IEnumerable Keys() where K : notnull - { - IMapView _this = Unsafe.As>(this); - IReadOnlyDictionary roDictionary = (IReadOnlyDictionary)_this; - return new ReadOnlyDictionaryKeyCollection(roDictionary); - } - - // IEnumerable Values { get } - internal IEnumerable Values() where K : notnull - { - IMapView _this = Unsafe.As>(this); - IReadOnlyDictionary roDictionary = (IReadOnlyDictionary)_this; - return new ReadOnlyDictionaryValueCollection(roDictionary); - } - - // bool ContainsKey(K key) - internal bool ContainsKey(K key) where K : notnull - { - if (key == null) - throw new ArgumentNullException(nameof(key)); - - IMapView _this = Unsafe.As>(this); - return _this.HasKey(key); - } - - // bool TryGetValue(TKey key, out TValue value) - internal bool TryGetValue(K key, [MaybeNullWhen(false)] out V value) where K : notnull - { - if (key == null) - throw new ArgumentNullException(nameof(key)); - - IMapView _this = Unsafe.As>(this); - - // It may be faster to call HasKey then Lookup. On failure, we would otherwise - // throw an exception from Lookup. - if (!_this.HasKey(key)) - { - value = default!; - return false; - } - - try - { - value = _this.Lookup(key); - return true; - } - catch (Exception ex) // Still may hit this case due to a race condition - { - if (HResults.E_BOUNDS == ex.HResult) - { - value = default!; - return false; - } - throw; - } - } - - #region Helpers - - private static V Lookup(IMapView _this, K key) - { - Debug.Assert(null != key); - - try - { - return _this.Lookup(key); - } - catch (Exception ex) - { - if (HResults.E_BOUNDS == ex.HResult) - throw new KeyNotFoundException(SR.Format(SR.Arg_KeyNotFoundWithKey, key.ToString())); - throw; - } - } - - #endregion Helpers - } - - // Note: One day we may make these return IReadOnlyCollection - [DebuggerDisplay("Count = {Count}")] - internal sealed class ReadOnlyDictionaryKeyCollection : IEnumerable where TKey : notnull - { - private readonly IReadOnlyDictionary dictionary; - - public ReadOnlyDictionaryKeyCollection(IReadOnlyDictionary dictionary) - { - if (dictionary == null) - throw new ArgumentNullException(nameof(dictionary)); - - this.dictionary = dictionary; - } - - /* - public void CopyTo(TKey[] array, int index) - { - if (array == null) - throw new ArgumentNullException(nameof(array)); - if (index < 0) - throw new ArgumentOutOfRangeException(nameof(index)); - if (array.Length <= index && this.Count > 0) - throw new ArgumentException(SR.Arg_IndexOutOfRangeException); - if (array.Length - index < dictionary.Count) - throw new ArgumentException(SR.Argument_InsufficientSpaceToCopyCollection); - - int i = index; - foreach (KeyValuePair mapping in dictionary) - { - array[i++] = mapping.Key; - } - } - - public int Count { - get { return dictionary.Count; } - } - - public bool Contains(TKey item) - { - return dictionary.ContainsKey(item); - } - */ - - IEnumerator IEnumerable.GetEnumerator() - { - return ((IEnumerable)this).GetEnumerator(); - } - - public IEnumerator GetEnumerator() - { - return new ReadOnlyDictionaryKeyEnumerator(dictionary); - } - } // public class ReadOnlyDictionaryKeyCollection - - - internal sealed class ReadOnlyDictionaryKeyEnumerator : IEnumerator where TKey : notnull - { - private readonly IReadOnlyDictionary dictionary; - private IEnumerator> enumeration; - - public ReadOnlyDictionaryKeyEnumerator(IReadOnlyDictionary dictionary) - { - if (dictionary == null) - throw new ArgumentNullException(nameof(dictionary)); - - this.dictionary = dictionary; - enumeration = dictionary.GetEnumerator(); - } - - void IDisposable.Dispose() - { - enumeration.Dispose(); - } - - public bool MoveNext() - { - return enumeration.MoveNext(); - } - - object? IEnumerator.Current => ((IEnumerator)this).Current; - - public TKey Current => enumeration.Current.Key; - - public void Reset() - { - enumeration = dictionary.GetEnumerator(); - } - } // class ReadOnlyDictionaryKeyEnumerator - - - [DebuggerDisplay("Count = {Count}")] - internal sealed class ReadOnlyDictionaryValueCollection : IEnumerable where TKey : notnull - { - private readonly IReadOnlyDictionary dictionary; - - public ReadOnlyDictionaryValueCollection(IReadOnlyDictionary dictionary) - { - if (dictionary == null) - throw new ArgumentNullException(nameof(dictionary)); - - this.dictionary = dictionary; - } - - /* - public void CopyTo(TValue[] array, int index) - { - if (array == null) - throw new ArgumentNullException(nameof(array)); - if (index < 0) - throw new ArgumentOutOfRangeException(nameof(index)); - if (array.Length <= index && this.Count > 0) - throw new ArgumentException(SR.Arg_IndexOutOfRangeException); - if (array.Length - index < dictionary.Count) - throw new ArgumentException(SR.Argument_InsufficientSpaceToCopyCollection); - - int i = index; - foreach (KeyValuePair mapping in dictionary) - { - array[i++] = mapping.Value; - } - } - - public int Count { - get { return dictionary.Count; } - } - - public bool Contains(TValue item) - { - EqualityComparer comparer = EqualityComparer.Default; - foreach (TValue value in this) - if (comparer.Equals(item, value)) - return true; - return false; - } - */ - - IEnumerator IEnumerable.GetEnumerator() - { - return ((IEnumerable)this).GetEnumerator(); - } - - public IEnumerator GetEnumerator() - { - return new ReadOnlyDictionaryValueEnumerator(dictionary); - } - } // public class ReadOnlyDictionaryValueCollection - - - internal sealed class ReadOnlyDictionaryValueEnumerator : IEnumerator where TKey : notnull - { - private readonly IReadOnlyDictionary dictionary; - private IEnumerator> enumeration; - - public ReadOnlyDictionaryValueEnumerator(IReadOnlyDictionary dictionary) - { - if (dictionary == null) - throw new ArgumentNullException(nameof(dictionary)); - - this.dictionary = dictionary; - enumeration = dictionary.GetEnumerator(); - } - - void IDisposable.Dispose() - { - enumeration.Dispose(); - } - - public bool MoveNext() - { - return enumeration.MoveNext(); - } - - object? IEnumerator.Current => ((IEnumerator)this).Current; - - public TValue Current => enumeration.Current.Value; - - public void Reset() - { - enumeration = dictionary.GetEnumerator(); - } - } // class ReadOnlyDictionaryValueEnumerator -} diff --git a/src/coreclr/src/System.Private.CoreLib/src/System/Runtime/InteropServices/WindowsRuntime/IPropertyValue.cs b/src/coreclr/src/System.Private.CoreLib/src/System/Runtime/InteropServices/WindowsRuntime/IPropertyValue.cs deleted file mode 100644 index ab59a6c..0000000 --- a/src/coreclr/src/System.Private.CoreLib/src/System/Runtime/InteropServices/WindowsRuntime/IPropertyValue.cs +++ /dev/null @@ -1,125 +0,0 @@ -// 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 System.Runtime.InteropServices.WindowsRuntime -{ - [ComImport] - [Guid("4bd682dd-7554-40e9-9a9b-82654ede7e62")] - [WindowsRuntimeImport] - internal interface IPropertyValue - { - PropertyType Type - { - get; - } - - bool IsNumericScalar - { - get; - } - - byte GetUInt8(); - - short GetInt16(); - - ushort GetUInt16(); - - int GetInt32(); - - uint GetUInt32(); - - long GetInt64(); - - ulong GetUInt64(); - - float GetSingle(); - - double GetDouble(); - - char GetChar16(); - - bool GetBoolean(); - - string GetString(); - - Guid GetGuid(); - - DateTimeOffset GetDateTime(); - - TimeSpan GetTimeSpan(); - - Point GetPoint(); - - Size GetSize(); - - Rect GetRect(); - - byte[] GetUInt8Array(); - - short[] GetInt16Array(); - - ushort[] GetUInt16Array(); - - int[] GetInt32Array(); - - uint[] GetUInt32Array(); - - long[] GetInt64Array(); - - ulong[] GetUInt64Array(); - - float[] GetSingleArray(); - - double[] GetDoubleArray(); - - char[] GetChar16Array(); - - bool[] GetBooleanArray(); - - string[] GetStringArray(); - - object[] GetInspectableArray(); - - Guid[] GetGuidArray(); - - DateTimeOffset[] GetDateTimeArray(); - - TimeSpan[] GetTimeSpanArray(); - - Point[] GetPointArray(); - - Size[] GetSizeArray(); - - Rect[] GetRectArray(); - } - - // Specify size directly instead of fields to avoid warnings - [StructLayout(LayoutKind.Sequential, Size = 8)] - [WindowsRuntimeImport] - internal struct Point - { - // float X; - // float Y; - } - - // Specify size directly instead of fields to avoid warnings - [StructLayout(LayoutKind.Sequential, Size = 8)] - [WindowsRuntimeImport] - internal struct Size - { - // float Width; - // float Height; - } - - // Specify size directly instead of fields to avoid warnings - [StructLayout(LayoutKind.Sequential, Size = 16)] - [WindowsRuntimeImport] - internal struct Rect - { - // float X; - // float Y; - // float Width; - // float Height; - } -} diff --git a/src/coreclr/src/System.Private.CoreLib/src/System/Runtime/InteropServices/WindowsRuntime/IReadOnlyDictionaryToIMapViewAdapter.cs b/src/coreclr/src/System.Private.CoreLib/src/System/Runtime/InteropServices/WindowsRuntime/IReadOnlyDictionaryToIMapViewAdapter.cs deleted file mode 100644 index 81c3a45..0000000 --- a/src/coreclr/src/System.Private.CoreLib/src/System/Runtime/InteropServices/WindowsRuntime/IReadOnlyDictionaryToIMapViewAdapter.cs +++ /dev/null @@ -1,74 +0,0 @@ -// 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.Generic; -using System.Diagnostics; -using Internal.Runtime.CompilerServices; - -namespace System.Runtime.InteropServices.WindowsRuntime -{ - // This is a set of stub methods implementing the support for the IMapView`2 interface on managed - // objects that implement IReadOnlyDictionary`2. Used by the interop mashaling infrastructure. - // - // The methods on this class must be written VERY carefully to avoid introducing security holes. - // That's because they are invoked with special "this"! The "this" object - // for all of these methods are not IReadOnlyDictionaryToIMapViewAdapter objects. Rather, they are of type - // IReadOnlyDictionary. No actual IReadOnlyDictionaryToIMapViewAdapter object is ever instantiated. Thus, you will - // see a lot of expressions that cast "this" to "IReadOnlyDictionary". - [DebuggerDisplay("Size = {Size}")] - internal sealed class IReadOnlyDictionaryToIMapViewAdapter - { - private IReadOnlyDictionaryToIMapViewAdapter() - { - Debug.Fail("This class is never instantiated"); - } - - // V Lookup(K key) - internal V Lookup(K key) where K : notnull - { - IReadOnlyDictionary _this = Unsafe.As>(this); - if (!_this.TryGetValue(key, out V value)) - { - Debug.Assert(key != null); - Exception e = new KeyNotFoundException(SR.Format(SR.Arg_KeyNotFoundWithKey, key.ToString())); - e.HResult = HResults.E_BOUNDS; - throw e; - } - - return value; - } - - // uint Size { get } - internal uint Size() where K : notnull - { - IReadOnlyDictionary _this = Unsafe.As>(this); - return (uint)_this.Count; - } - - // bool HasKey(K key) - internal bool HasKey(K key) where K : notnull - { - IReadOnlyDictionary _this = Unsafe.As>(this); - return _this.ContainsKey(key); - } - - // void Split(out IMapView first, out IMapView second) - internal void Split(out IMapView? first, out IMapView? second) where K : notnull - { - IReadOnlyDictionary _this = Unsafe.As>(this); - - if (_this.Count < 2) - { - first = null; - second = null; - return; - } - - if (!(_this is ConstantSplittableMap splittableMap)) - splittableMap = new ConstantSplittableMap(_this); - - splittableMap.Split(out first, out second); - } - } -} diff --git a/src/coreclr/src/System.Private.CoreLib/src/System/Runtime/InteropServices/WindowsRuntime/IReadOnlyListToIVectorViewAdapter.cs b/src/coreclr/src/System.Private.CoreLib/src/System/Runtime/InteropServices/WindowsRuntime/IReadOnlyListToIVectorViewAdapter.cs deleted file mode 100644 index 50147f0..0000000 --- a/src/coreclr/src/System.Private.CoreLib/src/System/Runtime/InteropServices/WindowsRuntime/IReadOnlyListToIVectorViewAdapter.cs +++ /dev/null @@ -1,130 +0,0 @@ -// 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.Generic; -using System.Diagnostics; -using Internal.Runtime.CompilerServices; - -namespace System.Runtime.InteropServices.WindowsRuntime -{ - // This is a set of stub methods implementing the support for the IVectorView`1 interface on managed - // objects that implement IReadOnlyList`1. Used by the interop mashaling infrastructure. - // - // The methods on this class must be written VERY carefully to avoid introducing security holes. - // That's because they are invoked with special "this"! The "this" object - // for all of these methods are not IReadOnlyListToIVectorViewAdapter objects. Rather, they are of type - // IReadOnlyList. No actual IReadOnlyListToIVectorViewAdapter object is ever instantiated. Thus, you will - // see a lot of expressions that cast "this" to "IReadOnlyList". - [DebuggerDisplay("Size = {Size}")] - internal sealed class IReadOnlyListToIVectorViewAdapter - { - private IReadOnlyListToIVectorViewAdapter() - { - Debug.Fail("This class is never instantiated"); - } - - // T GetAt(uint index) - internal T GetAt(uint index) - { - IReadOnlyList _this = Unsafe.As>(this); - EnsureIndexInt32(index, _this.Count); - - try - { - return _this[(int)index]; - } - catch (ArgumentOutOfRangeException ex) - { - ex.HResult = HResults.E_BOUNDS; - throw; - } - } - - // uint Size { get } - internal uint Size() - { - IReadOnlyList _this = Unsafe.As>(this); - return (uint)_this.Count; - } - - // bool IndexOf(T value, out uint index) - internal bool IndexOf(T value, out uint index) - { - IReadOnlyList _this = Unsafe.As>(this); - - int ind = -1; - int max = _this.Count; - for (int i = 0; i < max; i++) - { - if (EqualityComparer.Default.Equals(value, _this[i])) - { - ind = i; - break; - } - } - - if (-1 == ind) - { - index = 0; - return false; - } - - index = (uint)ind; - return true; - } - - // uint GetMany(uint startIndex, T[] items) - internal uint GetMany(uint startIndex, T[] items) - { - IReadOnlyList _this = Unsafe.As>(this); - - // REX spec says "calling GetMany with startIndex equal to the length of the vector - // (last valid index + 1) and any specified capacity will succeed and return zero actual - // elements". - if (startIndex == _this.Count) - return 0; - - EnsureIndexInt32(startIndex, _this.Count); - - if (items == null) - { - return 0; - } - - uint itemCount = Math.Min((uint)items.Length, (uint)_this.Count - startIndex); - - for (uint i = 0; i < itemCount; ++i) - { - items[i] = _this[(int)(i + startIndex)]; - } - - if (typeof(T) == typeof(string)) - { - string[] stringItems = (items as string[])!; - - // Fill in the rest of the array with string.Empty to avoid marshaling failure - for (uint i = itemCount; i < items.Length; ++i) - stringItems[i] = string.Empty; - } - - return itemCount; - } - - #region Helpers - - private static void EnsureIndexInt32(uint index, int listCapacity) - { - // We use '<=' and not '<' because int.MaxValue == index would imply - // that Size > int.MaxValue: - if (((uint)int.MaxValue) <= index || index >= (uint)listCapacity) - { - Exception e = new ArgumentOutOfRangeException(nameof(index), SR.ArgumentOutOfRange_IndexLargerThanMaxValue); - e.HResult = HResults.E_BOUNDS; - throw e; - } - } - - #endregion Helpers - } -} diff --git a/src/coreclr/src/System.Private.CoreLib/src/System/Runtime/InteropServices/WindowsRuntime/IReference.cs b/src/coreclr/src/System.Private.CoreLib/src/System/Runtime/InteropServices/WindowsRuntime/IReference.cs deleted file mode 100644 index 6b35e3c..0000000 --- a/src/coreclr/src/System.Private.CoreLib/src/System/Runtime/InteropServices/WindowsRuntime/IReference.cs +++ /dev/null @@ -1,25 +0,0 @@ -// 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 System.Runtime.InteropServices.WindowsRuntime -{ - [ComImport] - [Guid("61c17706-2d65-11e0-9ae8-d48564015472")] - [WindowsRuntimeImport] - // Note that ideally, T should be constrained to be a value type. However, Windows uses IReference - // and the projection may not be exactly pretty. - internal interface IReference : IPropertyValue - { - T Value { get; } - } - - [ComImport] - [Guid("61c17707-2d65-11e0-9ae8-d48564015472")] - [WindowsRuntimeImport] - // T can be any WinRT-compatible type, including reference types. - internal interface IReferenceArray : IPropertyValue - { - T[] Value { get; } - } -} diff --git a/src/coreclr/src/System.Private.CoreLib/src/System/Runtime/InteropServices/WindowsRuntime/IRestrictedErrorInfo.cs b/src/coreclr/src/System.Private.CoreLib/src/System/Runtime/InteropServices/WindowsRuntime/IRestrictedErrorInfo.cs deleted file mode 100644 index a48b779..0000000 --- a/src/coreclr/src/System.Private.CoreLib/src/System/Runtime/InteropServices/WindowsRuntime/IRestrictedErrorInfo.cs +++ /dev/null @@ -1,19 +0,0 @@ -// 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 System.Runtime.InteropServices.WindowsRuntime -{ - [ComImport] - [Guid("82BA7092-4C88-427D-A7BC-16DD93FEB67E")] - [InterfaceType(ComInterfaceType.InterfaceIsIUnknown)] - internal interface IRestrictedErrorInfo - { - void GetErrorDetails([MarshalAs(UnmanagedType.BStr)] out string description, - out int error, - [MarshalAs(UnmanagedType.BStr)] out string restrictedDescription, - [MarshalAs(UnmanagedType.BStr)] out string capabilitySid); - - void GetReference([MarshalAs(UnmanagedType.BStr)] out string reference); - } -} diff --git a/src/coreclr/src/System.Private.CoreLib/src/System/Runtime/InteropServices/WindowsRuntime/IVector.cs b/src/coreclr/src/System.Private.CoreLib/src/System/Runtime/InteropServices/WindowsRuntime/IVector.cs deleted file mode 100644 index ac5e875..0000000 --- a/src/coreclr/src/System.Private.CoreLib/src/System/Runtime/InteropServices/WindowsRuntime/IVector.cs +++ /dev/null @@ -1,87 +0,0 @@ -// 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.Generic; - -// Windows.Foundation.Collections.IVector`1 and IVectorView`1 cannot be referenced from managed -// code because they're hidden by the metadata adapter. We redeclare the interfaces manually -// to be able to talk to native WinRT objects. - -namespace System.Runtime.InteropServices.WindowsRuntime -{ - [ComImport] - [Guid("913337e9-11a1-4345-a3a2-4e7f956e222d")] - [WindowsRuntimeImport] - internal interface IVector : IIterable - { - T GetAt(uint index); - uint Size { get; } - IReadOnlyList GetView(); // Really an IVectorView. - bool IndexOf(T value, out uint index); - void SetAt(uint index, T value); - void InsertAt(uint index, T value); - void RemoveAt(uint index); - void Append(T value); - void RemoveAtEnd(); - void Clear(); - uint GetMany(uint startIndex, [Out] T[] items); - void ReplaceAll(T[] items); - } - - // Same as IVector - the only difference is that GetView returns IVectorView - [ComImport] - [Guid("913337e9-11a1-4345-a3a2-4e7f956e222d")] - [WindowsRuntimeImport] - internal interface IVector_Raw : IIterable - { - T GetAt(uint index); - uint Size { get; } - IVectorView GetView(); - bool IndexOf(T value, out uint index); - void SetAt(uint index, T value); - void InsertAt(uint index, T value); - void RemoveAt(uint index); - void Append(T value); - void RemoveAtEnd(); - void Clear(); - } - - [ComImport] - [Guid("bbe1fa4c-b0e3-4583-baef-1f1b2e483e56")] - [WindowsRuntimeImport] - internal interface IVectorView : IIterable - { - T GetAt(uint index); - uint Size { get; } - bool IndexOf(T value, out uint index); - uint GetMany(uint startIndex, [Out] T[] items); - } - - [ComImport] - [Guid("393de7de-6fd0-4c0d-bb71-47244a113e93")] - [WindowsRuntimeImport] - internal interface IBindableVector : IBindableIterable - { - object? GetAt(uint index); - uint Size { get; } - IBindableVectorView GetView(); - bool IndexOf(object value, out uint index); - void SetAt(uint index, object value); - void InsertAt(uint index, object value); - void RemoveAt(uint index); - void Append(object value); - void RemoveAtEnd(); - void Clear(); - } - - [ComImport] - [Guid("346dd6e7-976e-4bc3-815d-ece243bc0f33")] - [WindowsRuntimeImport] - internal interface IBindableVectorView : IBindableIterable - { - object? GetAt(uint index); - uint Size { get; } - bool IndexOf(object value, out uint index); - } -} diff --git a/src/coreclr/src/System.Private.CoreLib/src/System/Runtime/InteropServices/WindowsRuntime/IVectorViewToIReadOnlyListAdapter.cs b/src/coreclr/src/System.Private.CoreLib/src/System/Runtime/InteropServices/WindowsRuntime/IVectorViewToIReadOnlyListAdapter.cs deleted file mode 100644 index 75aded1..0000000 --- a/src/coreclr/src/System.Private.CoreLib/src/System/Runtime/InteropServices/WindowsRuntime/IVectorViewToIReadOnlyListAdapter.cs +++ /dev/null @@ -1,74 +0,0 @@ -// 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.Generic; -using System.Diagnostics; -using Internal.Runtime.CompilerServices; - -namespace System.Runtime.InteropServices.WindowsRuntime -{ - internal delegate T Indexer_Get_Delegate(int index); - - // This is a set of stub methods implementing the support for the IReadOnlyList`1 interface on WinRT - // objects that support IVectorView`1. Used by the interop mashaling infrastructure. - // - // The methods on this class must be written VERY carefully to avoid introducing security holes. - // That's because they are invoked with special "this"! The "this" object - // for all of these methods are not IVectorViewToIReadOnlyListAdapter objects. Rather, they are of type - // IVectorView. No actual IVectorViewToIReadOnlyListAdapter object is ever instantiated. Thus, you will see - // a lot of expressions that cast "this" to "IVectorView". - [DebuggerDisplay("Count = {Count}")] - internal sealed class IVectorViewToIReadOnlyListAdapter - { - private IVectorViewToIReadOnlyListAdapter() - { - Debug.Fail("This class is never instantiated"); - } - - // T this[int index] { get } - internal T Indexer_Get(int index) - { - if (index < 0) - throw new ArgumentOutOfRangeException(nameof(index)); - - IVectorView _this = Unsafe.As>(this); - - try - { - return _this.GetAt((uint)index); - - // We delegate bounds checking to the underlying collection and if it detected a fault, - // we translate it to the right exception: - } - catch (Exception ex) - { - if (HResults.E_BOUNDS == ex.HResult) - throw new ArgumentOutOfRangeException(nameof(index)); - - throw; - } - } - - // T this[int index] { get } - internal T Indexer_Get_Variance(int index) where T : class - { - Delegate target = System.StubHelpers.StubHelpers.GetTargetForAmbiguousVariantCall( - this, - typeof(IReadOnlyList).TypeHandle.Value, - out bool fUseString); - - if (target != null) - { - return (Unsafe.As>(target))(index); - } - - if (fUseString) - { - return Unsafe.As(Indexer_Get(index)); - } - - return Indexer_Get(index); - } - } -} diff --git a/src/coreclr/src/System.Private.CoreLib/src/System/Runtime/InteropServices/WindowsRuntime/IteratorToEnumeratorAdapter.cs b/src/coreclr/src/System.Private.CoreLib/src/System/Runtime/InteropServices/WindowsRuntime/IteratorToEnumeratorAdapter.cs deleted file mode 100644 index f6d3cfa..0000000 --- a/src/coreclr/src/System.Private.CoreLib/src/System/Runtime/InteropServices/WindowsRuntime/IteratorToEnumeratorAdapter.cs +++ /dev/null @@ -1,199 +0,0 @@ -// 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; -using System.Diagnostics; -using Internal.Runtime.CompilerServices; - -namespace System.Runtime.InteropServices.WindowsRuntime -{ - internal delegate IEnumerator GetEnumerator_Delegate(); - - // This is a set of stub methods implementing the support for the IEnumerable`1 interface on WinRT - // objects that implement IIterable`1. Used by the interop mashaling infrastructure. - // - // The methods on this class must be written VERY carefully to avoid introducing security holes. - // That's because they are invoked with special "this"! The "this" object - // for all of these methods are not IterableToEnumerableAdapter objects. Rather, they are of type - // IIterable. No actual IterableToEnumerableAdapter object is ever instantiated. Thus, you will - // see a lot of expressions that cast "this" to "IIterable". - internal sealed class IterableToEnumerableAdapter - { - private IterableToEnumerableAdapter() - { - Debug.Fail("This class is never instantiated"); - } - - // This method is invoked when GetEnumerator is called on a WinRT-backed implementation of IEnumerable. - internal IEnumerator GetEnumerator_Stub() - { - IIterable _this = Unsafe.As>(this); - return new IteratorToEnumeratorAdapter(_this.First()); - } - - // This method is invoked when GetEnumerator is called on a WinRT-backed implementation of IEnumerable - // and it is possible that the implementation supports IEnumerable/IEnumerable/IEnumerable/ - // IEnumerable/IEnumerable rather than IEnumerable because T is assignable from Type/string/ - // Exception/array/delegate via co-variance. - internal IEnumerator GetEnumerator_Variance_Stub() where T : class - { - Delegate target = System.StubHelpers.StubHelpers.GetTargetForAmbiguousVariantCall( - this, - typeof(IEnumerable).TypeHandle.Value, - out bool fUseString); - - if (target != null) - { - return (Unsafe.As>(target))(); - } - - if (fUseString) - { - return Unsafe.As>(GetEnumerator_Stub()); - } - - return GetEnumerator_Stub(); - } - } - - internal sealed class BindableIterableToEnumerableAdapter - { - private BindableIterableToEnumerableAdapter() - { - Debug.Fail("This class is never instantiated"); - } - - private sealed class NonGenericToGenericIterator : IIterator - { - private readonly IBindableIterator iterator; - - public NonGenericToGenericIterator(IBindableIterator iterator) - { this.iterator = iterator; } - - public object? Current => iterator.Current; - public bool HasCurrent => iterator.HasCurrent; - public bool MoveNext() { return iterator.MoveNext(); } - public int GetMany(object?[] items) { throw new NotSupportedException(); } - } - - // This method is invoked when GetEnumerator is called on a WinRT-backed implementation of IEnumerable. - internal IEnumerator GetEnumerator_Stub() - { - IBindableIterable _this = Unsafe.As(this); - return new IteratorToEnumeratorAdapter(new NonGenericToGenericIterator(_this.First())); - } - } - - // Adapter class which holds a Windows Runtime IIterator, exposing it as a managed IEnumerator - - // There are a few implementation differences between the Iterator and IEnumerator which need to be - // addressed. Iterator starts at index 0 while IEnumerator starts at index -1 as a result of which - // the first call to IEnumerator.Current is correct only after calling MoveNext(). - // Also IEnumerator throws an exception when we call Current after reaching the end of collection. - internal sealed class IteratorToEnumeratorAdapter : IEnumerator - { - private readonly IIterator m_iterator; - private bool m_hadCurrent; - private T m_current = default!; - private bool m_isInitialized; - - internal IteratorToEnumeratorAdapter(IIterator iterator) - { - Debug.Assert(iterator != null); - m_iterator = iterator; - m_hadCurrent = true; - m_isInitialized = false; - } - - public T Current - { - get - { - // The enumerator has not been advanced to the first element yet. - if (!m_isInitialized) - ThrowHelper.ThrowInvalidOperationException_InvalidOperation_EnumNotStarted(); - // The enumerator has reached the end of the collection - if (!m_hadCurrent) - ThrowHelper.ThrowInvalidOperationException_InvalidOperation_EnumEnded(); - return m_current; - } - } - - object? IEnumerator.Current - { - get - { - // The enumerator has not been advanced to the first element yet. - if (!m_isInitialized) - ThrowHelper.ThrowInvalidOperationException_InvalidOperation_EnumNotStarted(); - // The enumerator has reached the end of the collection - if (!m_hadCurrent) - ThrowHelper.ThrowInvalidOperationException_InvalidOperation_EnumEnded(); - return m_current; - } - } - - public bool MoveNext() - { - // If we've passed the end of the iteration, IEnumerable should return false, while - // IIterable will fail the interface call - if (!m_hadCurrent) - { - return false; - } - - // IIterators start at index 0, rather than -1. If this is the first call, we need to just - // check HasCurrent rather than actually moving to the next element - try - { - if (!m_isInitialized) - { - m_hadCurrent = m_iterator.HasCurrent; - m_isInitialized = true; - } - else - { - m_hadCurrent = m_iterator.MoveNext(); - } - - // We want to save away the current value for two reasons: - // 1. Accessing .Current is cheap on other iterators, so having it be a property which is a - // simple field access preserves the expected performance characteristics (as opposed to - // triggering a COM call every time the property is accessed) - // - // 2. This allows us to preserve the same semantics as generic collection iteration when iterating - // beyond the end of the collection - namely that Current continues to return the last value - // of the collection - if (m_hadCurrent) - { - m_current = m_iterator.Current; - } - } - catch (Exception e) - { - // Translate E_CHANGED_STATE into an InvalidOperationException for an updated enumeration - if (Marshal.GetHRForException(e) == HResults.E_CHANGED_STATE) - { - ThrowHelper.ThrowInvalidOperationException_InvalidOperation_EnumFailedVersion(); - } - else - { - throw; - } - } - - return m_hadCurrent; - } - - public void Reset() - { - throw new NotSupportedException(); - } - - public void Dispose() - { - } - } -} diff --git a/src/coreclr/src/System.Private.CoreLib/src/System/Runtime/InteropServices/WindowsRuntime/ListToBindableVectorAdapter.cs b/src/coreclr/src/System.Private.CoreLib/src/System/Runtime/InteropServices/WindowsRuntime/ListToBindableVectorAdapter.cs deleted file mode 100644 index cdb4d09..0000000 --- a/src/coreclr/src/System.Private.CoreLib/src/System/Runtime/InteropServices/WindowsRuntime/ListToBindableVectorAdapter.cs +++ /dev/null @@ -1,170 +0,0 @@ -// 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.Diagnostics; -using Internal.Runtime.CompilerServices; - -namespace System.Runtime.InteropServices.WindowsRuntime -{ - // This is a set of stub methods implementing the support for the IBindableVector interface on managed - // objects that implement IList. Used by the interop mashaling infrastructure. - // - // The methods on this class must be written VERY carefully to avoid introducing security holes. - // That's because they are invoked with special "this"! The "this" object - // for all of these methods are not ListToBindableVectorAdapter objects. Rather, they are of type - // IList. No actual ListToVectorBindableAdapter object is ever instantiated. Thus, you will - // see a lot of expressions that cast "this" to "IList". - internal sealed class ListToBindableVectorAdapter - { - private ListToBindableVectorAdapter() - { - Debug.Fail("This class is never instantiated"); - } - - // object GetAt(uint index) - internal object? GetAt(uint index) - { - IList _this = Unsafe.As(this); - EnsureIndexInt32(index, _this.Count); - - try - { - return _this[(int)index]; - } - catch (ArgumentOutOfRangeException ex) - { - throw WindowsRuntimeMarshal.GetExceptionForHR(HResults.E_BOUNDS, ex, "ArgumentOutOfRange_IndexOutOfRange"); - } - } - - // uint Size { get } - internal uint Size() - { - IList _this = Unsafe.As(this); - return (uint)_this.Count; - } - - // IBindableVectorView GetView() - internal IBindableVectorView GetView() - { - IList _this = Unsafe.As(this); - return new ListToBindableVectorViewAdapter(_this); - } - - // bool IndexOf(object value, out uint index) - internal bool IndexOf(object? value, out uint index) - { - IList _this = Unsafe.As(this); - int ind = _this.IndexOf(value); - - if (-1 == ind) - { - index = 0; - return false; - } - - index = (uint)ind; - return true; - } - - // void SetAt(uint index, object value) - internal void SetAt(uint index, object? value) - { - IList _this = Unsafe.As(this); - EnsureIndexInt32(index, _this.Count); - - try - { - _this[(int)index] = value; - } - catch (ArgumentOutOfRangeException ex) - { - throw WindowsRuntimeMarshal.GetExceptionForHR(HResults.E_BOUNDS, ex, "ArgumentOutOfRange_IndexOutOfRange"); - } - } - - // void InsertAt(uint index, object value) - internal void InsertAt(uint index, object? value) - { - IList _this = Unsafe.As(this); - - // Inserting at an index one past the end of the list is equivalent to appending - // so we need to ensure that we're within (0, count + 1). - EnsureIndexInt32(index, _this.Count + 1); - - try - { - _this.Insert((int)index, value); - } - catch (ArgumentOutOfRangeException ex) - { - // Change error code to match what WinRT expects - ex.HResult = HResults.E_BOUNDS; - throw; - } - } - - // void RemoveAt(uint index) - internal void RemoveAt(uint index) - { - IList _this = Unsafe.As(this); - EnsureIndexInt32(index, _this.Count); - - try - { - _this.RemoveAt((int)index); - } - catch (ArgumentOutOfRangeException ex) - { - // Change error code to match what WinRT expects - ex.HResult = HResults.E_BOUNDS; - throw; - } - } - - // void Append(object value) - internal void Append(object? value) - { - IList _this = Unsafe.As(this); - _this.Add(value); - } - - // void RemoveAtEnd() - internal void RemoveAtEnd() - { - IList _this = Unsafe.As(this); - if (_this.Count == 0) - { - Exception e = new InvalidOperationException(SR.InvalidOperation_CannotRemoveLastFromEmptyCollection); - e.HResult = HResults.E_BOUNDS; - throw e; - } - - uint size = (uint)_this.Count; - RemoveAt(size - 1); - } - - // void Clear() - internal void Clear() - { - IList _this = Unsafe.As(this); - _this.Clear(); - } - - // Helpers: - - private static void EnsureIndexInt32(uint index, int listCapacity) - { - // We use '<=' and not '<' becasue int.MaxValue == index would imply - // that Size > int.MaxValue: - if (((uint)int.MaxValue) <= index || index >= (uint)listCapacity) - { - Exception e = new ArgumentOutOfRangeException(nameof(index), SR.ArgumentOutOfRange_IndexLargerThanMaxValue); - e.HResult = HResults.E_BOUNDS; - throw e; - } - } - } -} diff --git a/src/coreclr/src/System.Private.CoreLib/src/System/Runtime/InteropServices/WindowsRuntime/ListToBindableVectorViewAdapter.cs b/src/coreclr/src/System.Private.CoreLib/src/System/Runtime/InteropServices/WindowsRuntime/ListToBindableVectorViewAdapter.cs deleted file mode 100644 index 7f9b8af..0000000 --- a/src/coreclr/src/System.Private.CoreLib/src/System/Runtime/InteropServices/WindowsRuntime/ListToBindableVectorViewAdapter.cs +++ /dev/null @@ -1,76 +0,0 @@ -// 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; - -namespace System.Runtime.InteropServices.WindowsRuntime -{ - /// A Windows Runtime IBindableVectorView implementation that wraps around a managed IList exposing - /// it to Windows runtime interop. - internal sealed class ListToBindableVectorViewAdapter : IBindableVectorView - { - private readonly IList list; - - internal ListToBindableVectorViewAdapter(IList list) - { - if (list == null) - throw new ArgumentNullException(nameof(list)); - - - this.list = list; - } - - private static void EnsureIndexInt32(uint index, int listCapacity) - { - // We use '<=' and not '<' becasue int.MaxValue == index would imply - // that Size > int.MaxValue: - if (((uint)int.MaxValue) <= index || index >= (uint)listCapacity) - { - Exception e = new ArgumentOutOfRangeException(nameof(index), SR.ArgumentOutOfRange_IndexLargerThanMaxValue); - e.HResult = HResults.E_BOUNDS; - throw e; - } - } - - // IBindableIterable implementation: - - public IBindableIterator First() - { - IEnumerator enumerator = list.GetEnumerator(); - return new EnumeratorToIteratorAdapter(new EnumerableToBindableIterableAdapter.NonGenericToGenericEnumerator(enumerator)); - } - - // IBindableVectorView implementation: - - public object? GetAt(uint index) - { - EnsureIndexInt32(index, list.Count); - - try - { - return list[(int)index]; - } - catch (ArgumentOutOfRangeException ex) - { - throw WindowsRuntimeMarshal.GetExceptionForHR(HResults.E_BOUNDS, ex, "ArgumentOutOfRange_IndexOutOfRange"); - } - } - - public uint Size => (uint)list.Count; - - public bool IndexOf(object value, out uint index) - { - int ind = list.IndexOf(value); - - if (-1 == ind) - { - index = 0; - return false; - } - - index = (uint)ind; - return true; - } - } -} diff --git a/src/coreclr/src/System.Private.CoreLib/src/System/Runtime/InteropServices/WindowsRuntime/ListToVectorAdapter.cs b/src/coreclr/src/System.Private.CoreLib/src/System/Runtime/InteropServices/WindowsRuntime/ListToVectorAdapter.cs deleted file mode 100644 index 8745245..0000000 --- a/src/coreclr/src/System.Private.CoreLib/src/System/Runtime/InteropServices/WindowsRuntime/ListToVectorAdapter.cs +++ /dev/null @@ -1,235 +0,0 @@ -// 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.Generic; -using System.Collections.ObjectModel; -using System.Diagnostics; -using Internal.Runtime.CompilerServices; - -namespace System.Runtime.InteropServices.WindowsRuntime -{ - // This is a set of stub methods implementing the support for the IVector`1 interface on managed - // objects that implement IList`1. Used by the interop mashaling infrastructure. - // - // The methods on this class must be written VERY carefully to avoid introducing security holes. - // That's because they are invoked with special "this"! The "this" object - // for all of these methods are not ListToVectorAdapter objects. Rather, they are of type - // IList. No actual ListToVectorAdapter object is ever instantiated. Thus, you will - // see a lot of expressions that cast "this" to "IList". - internal sealed class ListToVectorAdapter - { - private ListToVectorAdapter() - { - Debug.Fail("This class is never instantiated"); - } - - // T GetAt(uint index) - internal T GetAt(uint index) - { - IList _this = Unsafe.As>(this); - EnsureIndexInt32(index, _this.Count); - - try - { - return _this[(int)index]; - } - catch (ArgumentOutOfRangeException ex) - { - throw WindowsRuntimeMarshal.GetExceptionForHR(HResults.E_BOUNDS, ex, "ArgumentOutOfRange_IndexOutOfRange"); - } - } - - // uint Size { get } - internal uint Size() - { - IList _this = Unsafe.As>(this); - return (uint)_this.Count; - } - - // IVectorView GetView() - internal IReadOnlyList GetView() - { - IList _this = Unsafe.As>(this); - 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. - if (!(_this is IReadOnlyList roList)) - { - roList = new ReadOnlyCollection(_this); - } - return roList; - } - - // bool IndexOf(T value, out uint index) - internal bool IndexOf(T value, out uint index) - { - IList _this = Unsafe.As>(this); - int ind = _this.IndexOf(value); - - if (-1 == ind) - { - index = 0; - return false; - } - - index = (uint)ind; - return true; - } - - // void SetAt(uint index, T value) - internal void SetAt(uint index, T value) - { - IList _this = Unsafe.As>(this); - EnsureIndexInt32(index, _this.Count); - - try - { - _this[(int)index] = value; - } - catch (ArgumentOutOfRangeException ex) - { - throw WindowsRuntimeMarshal.GetExceptionForHR(HResults.E_BOUNDS, ex, "ArgumentOutOfRange_IndexOutOfRange"); - } - } - - // void InsertAt(uint index, T value) - internal void InsertAt(uint index, T value) - { - IList _this = Unsafe.As>(this); - - // Inserting at an index one past the end of the list is equivalent to appending - // so we need to ensure that we're within (0, count + 1). - EnsureIndexInt32(index, _this.Count + 1); - - try - { - _this.Insert((int)index, value); - } - catch (ArgumentOutOfRangeException ex) - { - // Change error code to match what WinRT expects - ex.HResult = HResults.E_BOUNDS; - throw; - } - } - - // void RemoveAt(uint index) - internal void RemoveAt(uint index) - { - IList _this = Unsafe.As>(this); - EnsureIndexInt32(index, _this.Count); - - try - { - _this.RemoveAt((int)index); - } - catch (ArgumentOutOfRangeException ex) - { - // Change error code to match what WinRT expects - ex.HResult = HResults.E_BOUNDS; - throw; - } - } - - // void Append(T value) - internal void Append(T value) - { - IList _this = Unsafe.As>(this); - _this.Add(value); - } - - // void RemoveAtEnd() - internal void RemoveAtEnd() - { - IList _this = Unsafe.As>(this); - if (_this.Count == 0) - { - Exception e = new InvalidOperationException(SR.InvalidOperation_CannotRemoveLastFromEmptyCollection); - e.HResult = HResults.E_BOUNDS; - throw e; - } - - uint size = (uint)_this.Count; - RemoveAt(size - 1); - } - - // void Clear() - internal void Clear() - { - IList _this = Unsafe.As>(this); - _this.Clear(); - } - - // uint GetMany(uint startIndex, T[] items) - internal uint GetMany(uint startIndex, T[] items) - { - IList _this = Unsafe.As>(this); - return GetManyHelper(_this, startIndex, items); - } - - // void ReplaceAll(T[] items) - internal void ReplaceAll(T[] items) - { - IList _this = Unsafe.As>(this); - _this.Clear(); - - if (items != null) - { - foreach (T item in items) - { - _this.Add(item); - } - } - } - - // Helpers: - - private static void EnsureIndexInt32(uint index, int listCapacity) - { - // We use '<=' and not '<' becasue int.MaxValue == index would imply - // that Size > int.MaxValue: - if (((uint)int.MaxValue) <= index || index >= (uint)listCapacity) - { - Exception e = new ArgumentOutOfRangeException(nameof(index), SR.ArgumentOutOfRange_IndexLargerThanMaxValue); - e.HResult = HResults.E_BOUNDS; - throw e; - } - } - - private static uint GetManyHelper(IList sourceList, uint startIndex, T[] items) - { - // Calling GetMany with a start index equal to the size of the list should always - // return 0 elements, regardless of the input item size - if (startIndex == sourceList.Count) - { - return 0; - } - - EnsureIndexInt32(startIndex, sourceList.Count); - - if (items == null) - { - return 0; - } - - uint itemCount = Math.Min((uint)items.Length, (uint)sourceList.Count - startIndex); - for (uint i = 0; i < itemCount; ++i) - { - items[i] = sourceList[(int)(i + startIndex)]; - } - - if (typeof(T) == typeof(string)) - { - string[] stringItems = (items as string[])!; - - // Fill in rest of the array with string.Empty to avoid marshaling failure - for (uint i = itemCount; i < items.Length; ++i) - stringItems[i] = string.Empty; - } - - return itemCount; - } - } -} diff --git a/src/coreclr/src/System.Private.CoreLib/src/System/Runtime/InteropServices/WindowsRuntime/ManagedActivationFactory.cs b/src/coreclr/src/System.Private.CoreLib/src/System/Runtime/InteropServices/WindowsRuntime/ManagedActivationFactory.cs deleted file mode 100644 index bf3392b..0000000 --- a/src/coreclr/src/System.Private.CoreLib/src/System/Runtime/InteropServices/WindowsRuntime/ManagedActivationFactory.cs +++ /dev/null @@ -1,69 +0,0 @@ -// 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.Reflection; -using System.Runtime.CompilerServices; - -namespace System.Runtime.InteropServices.WindowsRuntime -{ - [ComImport] - [Guid("60D27C8D-5F61-4CCE-B751-690FAE66AA53")] - [WindowsRuntimeImport] - internal interface IManagedActivationFactory - { - void RunClassConstructor(); - } - - // A ManangedActivationFactory provides the IActivationFactory implementation for managed types which are - // constructable via Windows Runtime. Implementation of specialized factory and static WinRT interfaces is - // provided using VM functionality (see Marshal.InitializeWinRTFactoryObject for details). - // - // In order to be activatable via the ManagedActivationFactory type, the type must be decorated with either - // ActivatableAttribute, or StaticAttribute. - [ComVisible(true)] - [ClassInterface(ClassInterfaceType.None)] - internal sealed class ManagedActivationFactory : IActivationFactory, IManagedActivationFactory - { - private readonly Type m_type; - - internal ManagedActivationFactory(Type type) - { - if (type == null) - throw new ArgumentNullException(nameof(type)); - - // Check whether the type is "exported to WinRT", i.e. it is declared in a managed .winmd and is decorated - // with at least one ActivatableAttribute or StaticAttribute. - if (!(type is RuntimeType) || !type.IsExportedToWindowsRuntime) - throw new ArgumentException(SR.Format(SR.Argument_TypeNotActivatableViaWindowsRuntime, type), nameof(type)); - - m_type = type; - } - - // Activate an instance of the managed type by using its default constructor. - public object ActivateInstance() - { - try - { - return Activator.CreateInstance(m_type)!; - } - catch (MissingMethodException) - { - // If the type doesn't expose a default constructor, then we fail with E_NOTIMPL - throw new NotImplementedException(); - } - catch (TargetInvocationException e) - { - throw e.InnerException!; - } - } - - // Runs the class constructor - // Currently only Jupiter use this to run class constructor in order to - // initialize DependencyProperty objects and do necessary work - void IManagedActivationFactory.RunClassConstructor() - { - RuntimeHelpers.RunClassConstructor(m_type.TypeHandle); - } - } -} diff --git a/src/coreclr/src/System.Private.CoreLib/src/System/Runtime/InteropServices/WindowsRuntime/MapToCollectionAdapter.cs b/src/coreclr/src/System.Private.CoreLib/src/System/Runtime/InteropServices/WindowsRuntime/MapToCollectionAdapter.cs deleted file mode 100644 index bc2df08..0000000 --- a/src/coreclr/src/System.Private.CoreLib/src/System/Runtime/InteropServices/WindowsRuntime/MapToCollectionAdapter.cs +++ /dev/null @@ -1,169 +0,0 @@ -// 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.Generic; -using System.Diagnostics; -using Internal.Runtime.CompilerServices; - -namespace System.Runtime.InteropServices.WindowsRuntime -{ - // These stubs will be used when a call via ICollection> is made in managed code. - // This can mean two things - either the underlying unmanaged object implements IMap or it - // implements IVector> and we cannot determine this statically in the general - // case so we have to cast at run-time. Used by the interop mashaling infrastructure. - // - // The methods on this class must be written VERY carefully to avoid introducing security holes. - // That's because they are invoked with special "this"! The "this" object - // for all of these methods are not MapToCollectionAdapter objects. Rather, they are of type - // IVector> or IMap. No actual MapToCollectionAdapter object is ever - // instantiated. Thus, you will see a lot of expressions that cast "this" to "IVector>" - // or "IMap". - internal sealed class MapToCollectionAdapter - { - private MapToCollectionAdapter() - { - Debug.Fail("This class is never instantiated"); - } - - // int Count { get } - internal int Count() where K : notnull - { - object _this = Unsafe.As(this); - - if (_this is IMap _this_map) - { - uint size = _this_map.Size; - - if (((uint)int.MaxValue) < size) - { - throw new InvalidOperationException(SR.InvalidOperation_CollectionBackingDictionaryTooLarge); - } - - return (int)size; - } - else - { - IVector> _this_vector = Unsafe.As>>(this); - uint size = _this_vector.Size; - - if (((uint)int.MaxValue) < size) - { - throw new InvalidOperationException(SR.InvalidOperation_CollectionBackingListTooLarge); - } - - return (int)size; - } - } - - // bool IsReadOnly { get } - internal bool IsReadOnly() where K : notnull - { - return false; - } - - // void Add(T item) - internal void Add(KeyValuePair item) where K : notnull - { - object _this = Unsafe.As(this); - - if (_this is IDictionary _this_dictionary) - { - _this_dictionary.Add(item.Key, item.Value); - } - else - { - IVector> _this_vector = Unsafe.As>>(this); - _this_vector.Append(item); - } - } - - // void Clear() - internal void Clear() where K : notnull - { - object _this = Unsafe.As(this); - - if (_this is IMap _this_map) - { - _this_map.Clear(); - } - else - { - IVector> _this_vector = Unsafe.As>>(this); - _this_vector.Clear(); - } - } - - // bool Contains(T item) - internal bool Contains(KeyValuePair item) where K : notnull - { - object _this = Unsafe.As(this); - - if (_this is IDictionary _this_dictionary) - { - bool hasKey = _this_dictionary.TryGetValue(item.Key, out V value); - - if (!hasKey) - return false; - - return EqualityComparer.Default.Equals(value, item.Value); - } - else - { - IVector> _this_vector = Unsafe.As>>(this); - - return _this_vector.IndexOf(item, out _); - } - } - - // void CopyTo(T[] array, int arrayIndex) - internal void CopyTo(KeyValuePair[] array, int arrayIndex) where K : notnull - { - if (array == null) - throw new ArgumentNullException(nameof(array)); - - if (arrayIndex < 0) - throw new ArgumentOutOfRangeException(nameof(arrayIndex)); - - if (array.Length <= arrayIndex && Count() > 0) - throw new ArgumentException(SR.Argument_IndexOutOfArrayBounds); - - if (array.Length - arrayIndex < Count()) - throw new ArgumentException(SR.Argument_InsufficientSpaceToCopyCollection); - - - IIterable> _this = Unsafe.As>>(this); - foreach (KeyValuePair mapping in _this) - { - array[arrayIndex++] = mapping; - } - } - - // bool Remove(T item) - internal bool Remove(KeyValuePair item) where K : notnull - { - object _this = Unsafe.As(this); - - if (_this is IDictionary _this_dictionary) - { - return _this_dictionary.Remove(item.Key); - } - else - { - IVector> _this_vector = Unsafe.As>>(this); - bool exists = _this_vector.IndexOf(item, out uint index); - - if (!exists) - return false; - - if (((uint)int.MaxValue) < index) - { - throw new InvalidOperationException(SR.InvalidOperation_CollectionBackingListTooLarge); - } - - VectorToListAdapter.RemoveAtHelper>(_this_vector, index); - return true; - } - } - } -} diff --git a/src/coreclr/src/System.Private.CoreLib/src/System/Runtime/InteropServices/WindowsRuntime/MapToDictionaryAdapter.cs b/src/coreclr/src/System.Private.CoreLib/src/System/Runtime/InteropServices/WindowsRuntime/MapToDictionaryAdapter.cs deleted file mode 100644 index 64b9eb4..0000000 --- a/src/coreclr/src/System.Private.CoreLib/src/System/Runtime/InteropServices/WindowsRuntime/MapToDictionaryAdapter.cs +++ /dev/null @@ -1,161 +0,0 @@ -// 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.Generic; -using System.Diagnostics; -using System.Diagnostics.CodeAnalysis; -using Internal.Runtime.CompilerServices; - -namespace System.Runtime.InteropServices.WindowsRuntime -{ - // This is a set of stub methods implementing the support for the IDictionary`2 interface on WinRT - // objects that support IMap`2. Used by the interop mashaling infrastructure. - // - // The methods on this class must be written VERY carefully to avoid introducing security holes. - // That's because they are invoked with special "this"! The "this" object - // for all of these methods are not MapToDictionaryAdapter objects. Rather, they are of type - // IMap. No actual MapToDictionaryAdapter object is ever instantiated. Thus, you will see - // a lot of expressions that cast "this" to "IMap". - internal sealed class MapToDictionaryAdapter - { - private MapToDictionaryAdapter() - { - Debug.Fail("This class is never instantiated"); - } - - // V this[K key] { get } - internal V Indexer_Get(K key) where K : notnull - { - if (key == null) - throw new ArgumentNullException(nameof(key)); - - IMap _this = Unsafe.As>(this); - return Lookup(_this, key); - } - - // V this[K key] { set } - internal void Indexer_Set(K key, V value) where K : notnull - { - if (key == null) - throw new ArgumentNullException(nameof(key)); - - IMap _this = Unsafe.As>(this); - Insert(_this, key, value); - } - - // ICollection Keys { get } - internal ICollection Keys() where K : notnull - { - IMap _this = Unsafe.As>(this); - IDictionary dictionary = (IDictionary)_this; - return new DictionaryKeyCollection(dictionary); - } - - // ICollection Values { get } - internal ICollection Values() where K : notnull - { - IMap _this = Unsafe.As>(this); - IDictionary dictionary = (IDictionary)_this; - return new DictionaryValueCollection(dictionary); - } - - // bool ContainsKey(K key) - internal bool ContainsKey(K key) where K : notnull - { - if (key == null) - throw new ArgumentNullException(nameof(key)); - - IMap _this = Unsafe.As>(this); - return _this.HasKey(key); - } - - // void Add(K key, V value) - internal void Add(K key, V value) where K : notnull - { - if (key == null) - throw new ArgumentNullException(nameof(key)); - - if (ContainsKey(key)) - throw new ArgumentException(SR.Argument_AddingDuplicate); - - IMap _this = Unsafe.As>(this); - Insert(_this, key, value); - } - - // bool Remove(TKey key) - internal bool Remove(K key) where K : notnull - { - if (key == null) - throw new ArgumentNullException(nameof(key)); - - IMap _this = Unsafe.As>(this); - if (!_this.HasKey(key)) - return false; - - try - { - _this.Remove(key); - return true; - } - catch (Exception ex) - { - if (HResults.E_BOUNDS == ex.HResult) - return false; - - throw; - } - } - - // bool TryGetValue(TKey key, out TValue value) - internal bool TryGetValue(K key, [MaybeNullWhen(false)] out V value) where K : notnull - { - if (key == null) - throw new ArgumentNullException(nameof(key)); - - IMap _this = Unsafe.As>(this); - if (!_this.HasKey(key)) - { - value = default!; - return false; - } - - try - { - value = Lookup(_this, key); - return true; - } - catch (KeyNotFoundException) - { - value = default!; - return false; - } - } - - // Helpers: - - private static V Lookup(IMap _this, K key) where K : notnull - { - Debug.Assert(null != key); - - try - { - return _this.Lookup(key); - } - catch (Exception ex) - { - if (HResults.E_BOUNDS == ex.HResult) - throw new KeyNotFoundException(SR.Arg_KeyNotFound); - throw; - } - } - - private static bool Insert(IMap _this, K key, V value) where K : notnull - { - Debug.Assert(null != key); - - bool replaced = _this.Insert(key, value); - return replaced; - } - } -} diff --git a/src/coreclr/src/System.Private.CoreLib/src/System/Runtime/InteropServices/WindowsRuntime/MapViewToReadOnlyCollectionAdapter.cs b/src/coreclr/src/System.Private.CoreLib/src/System/Runtime/InteropServices/WindowsRuntime/MapViewToReadOnlyCollectionAdapter.cs deleted file mode 100644 index 09e0f3b..0000000 --- a/src/coreclr/src/System.Private.CoreLib/src/System/Runtime/InteropServices/WindowsRuntime/MapViewToReadOnlyCollectionAdapter.cs +++ /dev/null @@ -1,59 +0,0 @@ -// 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.Generic; -using System.Diagnostics; -using Internal.Runtime.CompilerServices; - -namespace System.Runtime.InteropServices.WindowsRuntime -{ - // These stubs will be used when a call via IReadOnlyCollection> is made in managed code. - // This can mean two things - either the underlying unmanaged object implements IMapView or it - // implements IVectorView> and we cannot determine this statically in the general - // case so we have to cast at run-time. Used by the interop mashaling infrastructure. - // - // The methods on this class must be written VERY carefully to avoid introducing security holes. - // That's because they are invoked with special "this"! The "this" object - // for all of these methods are not MapViewToReadOnlyCollectionAdapter objects. Rather, they are of type - // IVectorView> or IMapView. No actual MapViewToReadOnlyCollectionAdapter object is ever - // instantiated. Thus, you will see a lot of expressions that cast "this" to "IVectorView>" - // or "IMapView". - internal sealed class MapViewToReadOnlyCollectionAdapter - { - private MapViewToReadOnlyCollectionAdapter() - { - Debug.Fail("This class is never instantiated"); - } - - // int Count { get } - internal int Count() - { - object _this = Unsafe.As(this); - - if (_this is IMapView _this_map) - { - uint size = _this_map.Size; - - if (((uint)int.MaxValue) < size) - { - throw new InvalidOperationException(SR.InvalidOperation_CollectionBackingDictionaryTooLarge); - } - - return (int)size; - } - else - { - IVectorView> _this_vector = Unsafe.As>>(this); - uint size = _this_vector.Size; - - if (((uint)int.MaxValue) < size) - { - throw new InvalidOperationException(SR.InvalidOperation_CollectionBackingListTooLarge); - } - - return (int)size; - } - } - } -} diff --git a/src/coreclr/src/System.Private.CoreLib/src/System/Runtime/InteropServices/WindowsRuntime/NativeMethods.cs b/src/coreclr/src/System.Private.CoreLib/src/System/Runtime/InteropServices/WindowsRuntime/NativeMethods.cs deleted file mode 100644 index a499d6d..0000000 --- a/src/coreclr/src/System.Private.CoreLib/src/System/Runtime/InteropServices/WindowsRuntime/NativeMethods.cs +++ /dev/null @@ -1,45 +0,0 @@ -// 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 System.Runtime.InteropServices.WindowsRuntime -{ -#if TARGET_64BIT - [StructLayout(LayoutKind.Explicit, Size = 24)] -#else - [StructLayout(LayoutKind.Explicit, Size = 20)] -#endif - internal unsafe struct HSTRING_HEADER - { - } - - internal static class UnsafeNativeMethods - { - [DllImport("api-ms-win-core-winrt-error-l1-1-0.dll", PreserveSig = false)] - internal static extern IRestrictedErrorInfo GetRestrictedErrorInfo(); - - [DllImport("api-ms-win-core-winrt-error-l1-1-1.dll")] - [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)] - internal static extern void RoReportUnhandledError(IRestrictedErrorInfo error); - - [DllImport("api-ms-win-core-winrt-string-l1-1-0.dll", CallingConvention = CallingConvention.StdCall)] - internal static extern unsafe 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)] - internal static extern unsafe int WindowsCreateStringReference(char* sourceString, - int length, - [Out] HSTRING_HEADER* hstringHeader, - [Out] IntPtr* hstring); - - [DllImport("api-ms-win-core-winrt-string-l1-1-0.dll", CallingConvention = CallingConvention.StdCall)] - internal static extern int WindowsDeleteString(IntPtr hstring); - - [DllImport("api-ms-win-core-winrt-string-l1-1-0.dll", CallingConvention = CallingConvention.StdCall)] - internal static extern unsafe char* WindowsGetStringRawBuffer(IntPtr hstring, [Out] uint* length); - } -} diff --git a/src/coreclr/src/System.Private.CoreLib/src/System/Runtime/InteropServices/WindowsRuntime/PropertyValue.cs b/src/coreclr/src/System.Private.CoreLib/src/System/Runtime/InteropServices/WindowsRuntime/PropertyValue.cs deleted file mode 100644 index dec24e8..0000000 --- a/src/coreclr/src/System.Private.CoreLib/src/System/Runtime/InteropServices/WindowsRuntime/PropertyValue.cs +++ /dev/null @@ -1,55 +0,0 @@ -// 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 System.Runtime.InteropServices.WindowsRuntime -{ - // Note this is a copy of the PropertyType enumeration from Windows.Foundation.winmd - internal enum PropertyType - { - // WARNING: These values have to match enum Windows.Foundation.PropertyType !!! - Empty = 0, - UInt8 = 1, - Int16 = 2, - UInt16 = 3, - Int32 = 4, - UInt32 = 5, - Int64 = 6, - UInt64 = 7, - Single = 8, - Double = 9, - Char16 = 10, - Boolean = 11, - String = 12, - Inspectable = 13, - DateTime = 14, - TimeSpan = 15, - Guid = 16, - Point = 17, - Size = 18, - Rect = 19, - - Other = 20, - - UInt8Array = UInt8 + 1024, - Int16Array = Int16 + 1024, - UInt16Array = UInt16 + 1024, - Int32Array = Int32 + 1024, - UInt32Array = UInt32 + 1024, - Int64Array = Int64 + 1024, - UInt64Array = UInt64 + 1024, - SingleArray = Single + 1024, - DoubleArray = Double + 1024, - Char16Array = Char16 + 1024, - BooleanArray = Boolean + 1024, - StringArray = String + 1024, - InspectableArray = Inspectable + 1024, - DateTimeArray = DateTime + 1024, - TimeSpanArray = TimeSpan + 1024, - GuidArray = Guid + 1024, - PointArray = Point + 1024, - SizeArray = Size + 1024, - RectArray = Rect + 1024, - OtherArray = Other + 1024, - } -} diff --git a/src/coreclr/src/System.Private.CoreLib/src/System/Runtime/InteropServices/WindowsRuntime/RuntimeClass.cs b/src/coreclr/src/System.Private.CoreLib/src/System/Runtime/InteropServices/WindowsRuntime/RuntimeClass.cs deleted file mode 100644 index 9dd7a63..0000000 --- a/src/coreclr/src/System.Private.CoreLib/src/System/Runtime/InteropServices/WindowsRuntime/RuntimeClass.cs +++ /dev/null @@ -1,106 +0,0 @@ -// 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. - -/*============================================================ -** -** -** -** RuntimeClass is the base class of all WinRT types -** -** -===========================================================*/ - -using System.Runtime.CompilerServices; - -namespace System.Runtime.InteropServices.WindowsRuntime -{ - // Local definition of Windows.Foundation.IStringable - [ComImport] - [Guid("96369f54-8eb6-48f0-abce-c1b211e627c3")] - [WindowsRuntimeImport] - internal interface IStringable - { - string ToString(); - } - - internal static class IStringableHelper - { - internal static string? ToString(object obj) - { - if (obj is IGetProxyTarget proxy) - obj = proxy.GetTarget(); - - // Check whether the type implements IStringable. - if (obj is IStringable stringableType) - { - return stringableType.ToString(); - } - - return obj.ToString(); - } - } - - // - // Base class for every WinRT class - // We'll make it a ComImport and WindowsRuntimeImport in the type loader - // as C# compiler won't allow putting code in ComImport type - // - internal abstract class RuntimeClass : __ComObject - { - // - // Support for ToString/GetHashCode/Equals override - // - [MethodImpl(MethodImplOptions.InternalCall)] - internal extern IntPtr GetRedirectedGetHashCodeMD(); - - [MethodImpl(MethodImplOptions.InternalCall)] - internal extern int RedirectGetHashCode(IntPtr pMD); - - public override int GetHashCode() - { - IntPtr pMD = GetRedirectedGetHashCodeMD(); - if (pMD == IntPtr.Zero) - return base.GetHashCode(); - return RedirectGetHashCode(pMD); - } - - [MethodImpl(MethodImplOptions.InternalCall)] - internal extern IntPtr GetRedirectedToStringMD(); - - [MethodImpl(MethodImplOptions.InternalCall)] - internal extern string RedirectToString(IntPtr pMD); - - public override string ToString() - { - // Check whether the type implements IStringable. - if (this is IStringable stringableType) - { - return stringableType.ToString(); - } - else - { - IntPtr pMD = GetRedirectedToStringMD(); - - if (pMD == IntPtr.Zero) - return base.ToString(); - - return RedirectToString(pMD); - } - } - - [MethodImpl(MethodImplOptions.InternalCall)] - internal extern IntPtr GetRedirectedEqualsMD(); - - [MethodImpl(MethodImplOptions.InternalCall)] - internal extern bool RedirectEquals(object? obj, IntPtr pMD); - - public override bool Equals(object? obj) - { - IntPtr pMD = GetRedirectedEqualsMD(); - if (pMD == IntPtr.Zero) - return base.Equals(obj); - return RedirectEquals(obj, pMD); - } - } -} diff --git a/src/coreclr/src/System.Private.CoreLib/src/System/Runtime/InteropServices/WindowsRuntime/VectorToCollectionAdapter.cs b/src/coreclr/src/System.Private.CoreLib/src/System/Runtime/InteropServices/WindowsRuntime/VectorToCollectionAdapter.cs deleted file mode 100644 index 1b67ceb..0000000 --- a/src/coreclr/src/System.Private.CoreLib/src/System/Runtime/InteropServices/WindowsRuntime/VectorToCollectionAdapter.cs +++ /dev/null @@ -1,109 +0,0 @@ -// 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 Internal.Runtime.CompilerServices; - -namespace System.Runtime.InteropServices.WindowsRuntime -{ - // This is a set of stub methods implementing the support for the ICollection`1 interface on WinRT - // objects that support IVector`1. Used by the interop mashaling infrastructure. - // - // The methods on this class must be written VERY carefully to avoid introducing security holes. - // That's because they are invoked with special "this"! The "this" object - // for all of these methods are not VectorToCollectionAdapter objects. Rather, they are of type - // IVector. No actual VectorToCollectionAdapter object is ever instantiated. Thus, you will see - // a lot of expressions that cast "this" to "IVector". - internal sealed class VectorToCollectionAdapter - { - private VectorToCollectionAdapter() - { - Debug.Fail("This class is never instantiated"); - } - - // int Count { get } - internal int Count() - { - IVector _this = Unsafe.As>(this); - uint size = _this.Size; - if (((uint)int.MaxValue) < size) - { - throw new InvalidOperationException(SR.InvalidOperation_CollectionBackingListTooLarge); - } - - return (int)size; - } - - // bool IsReadOnly { get } - internal bool IsReadOnly() - { - return false; - } - - // void Add(T item) - internal void Add(T item) - { - IVector _this = Unsafe.As>(this); - _this.Append(item); - } - - // void Clear() - internal void Clear() - { - IVector _this = Unsafe.As>(this); - _this.Clear(); - } - - // bool Contains(T item) - internal bool Contains(T item) - { - IVector _this = Unsafe.As>(this); - - return _this.IndexOf(item, out _); - } - - // void CopyTo(T[] array, int arrayIndex) - internal void CopyTo(T[] array, int arrayIndex) - { - if (array == null) - throw new ArgumentNullException(nameof(array)); - - if (arrayIndex < 0) - throw new ArgumentOutOfRangeException(nameof(arrayIndex)); - - if (array.Length <= arrayIndex && Count() > 0) - throw new ArgumentException(SR.Argument_IndexOutOfArrayBounds); - - if (array.Length - arrayIndex < Count()) - throw new ArgumentException(SR.Argument_InsufficientSpaceToCopyCollection); - - - IVector _this = Unsafe.As>(this); - int count = Count(); - for (int i = 0; i < count; i++) - { - array[i + arrayIndex] = VectorToListAdapter.GetAt(_this, (uint)i); - } - } - - // bool Remove(T item) - internal bool Remove(T item) - { - IVector _this = Unsafe.As>(this); - - bool exists = _this.IndexOf(item, out uint index); - - if (!exists) - return false; - - if (((uint)int.MaxValue) < index) - { - throw new InvalidOperationException(SR.InvalidOperation_CollectionBackingListTooLarge); - } - - VectorToListAdapter.RemoveAtHelper(_this, index); - return true; - } - } -} diff --git a/src/coreclr/src/System.Private.CoreLib/src/System/Runtime/InteropServices/WindowsRuntime/VectorToListAdapter.cs b/src/coreclr/src/System.Private.CoreLib/src/System/Runtime/InteropServices/WindowsRuntime/VectorToListAdapter.cs deleted file mode 100644 index 5dffcce..0000000 --- a/src/coreclr/src/System.Private.CoreLib/src/System/Runtime/InteropServices/WindowsRuntime/VectorToListAdapter.cs +++ /dev/null @@ -1,157 +0,0 @@ -// 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 Internal.Runtime.CompilerServices; - -namespace System.Runtime.InteropServices.WindowsRuntime -{ - // This is a set of stub methods implementing the support for the IList`1 interface on WinRT - // objects that support IVector`1. Used by the interop mashaling infrastructure. - // - // The methods on this class must be written VERY carefully to avoid introducing security holes. - // That's because they are invoked with special "this"! The "this" object - // for all of these methods are not VectorToListAdapter objects. Rather, they are of type - // IVector. No actual VectorToListAdapter object is ever instantiated. Thus, you will see - // a lot of expressions that cast "this" to "IVector". - internal sealed class VectorToListAdapter - { - private VectorToListAdapter() - { - Debug.Fail("This class is never instantiated"); - } - - // T this[int index] { get } - internal T Indexer_Get(int index) - { - if (index < 0) - throw new ArgumentOutOfRangeException(nameof(index)); - - IVector _this = Unsafe.As>(this); - return GetAt(_this, (uint)index); - } - - // T this[int index] { set } - internal void Indexer_Set(int index, T value) - { - if (index < 0) - throw new ArgumentOutOfRangeException(nameof(index)); - - IVector _this = Unsafe.As>(this); - SetAt(_this, (uint)index, value); - } - - // int IndexOf(T item) - internal int IndexOf(T item) - { - IVector _this = Unsafe.As>(this); - - bool exists = _this.IndexOf(item, out uint index); - - if (!exists) - return -1; - - if (((uint)int.MaxValue) < index) - { - throw new InvalidOperationException(SR.InvalidOperation_CollectionBackingListTooLarge); - } - - return (int)index; - } - - // void Insert(int index, T item) - internal void Insert(int index, T item) - { - if (index < 0) - throw new ArgumentOutOfRangeException(nameof(index)); - - IVector _this = Unsafe.As>(this); - InsertAtHelper(_this, (uint)index, item); - } - - // void RemoveAt(int index) - internal void RemoveAt(int index) - { - if (index < 0) - throw new ArgumentOutOfRangeException(nameof(index)); - - IVector _this = Unsafe.As>(this); - RemoveAtHelper(_this, (uint)index); - } - - // Helpers: - - internal static T GetAt(IVector _this, uint index) - { - try - { - return _this.GetAt(index); - - // We delegate bounds checking to the underlying collection and if it detected a fault, - // we translate it to the right exception: - } - catch (Exception ex) - { - if (HResults.E_BOUNDS == ex.HResult) - throw new ArgumentOutOfRangeException(nameof(index)); - - throw; - } - } - - private static void SetAt(IVector _this, uint index, T value) - { - try - { - _this.SetAt(index, value); - - // We deligate bounds checking to the underlying collection and if it detected a fault, - // we translate it to the right exception: - } - catch (Exception ex) - { - if (HResults.E_BOUNDS == ex.HResult) - throw new ArgumentOutOfRangeException(nameof(index)); - - throw; - } - } - - private static void InsertAtHelper(IVector _this, uint index, T item) - { - try - { - _this.InsertAt(index, item); - - // We delegate bounds checking to the underlying collection and if it detected a fault, - // we translate it to the right exception: - } - catch (Exception ex) - { - if (HResults.E_BOUNDS == ex.HResult) - throw new ArgumentOutOfRangeException(nameof(index)); - - throw; - } - } - - internal static void RemoveAtHelper(IVector _this, uint index) - { - try - { - _this.RemoveAt(index); - - // We delegate bounds checking to the underlying collection and if it detected a fault, - // we translate it to the right exception: - } - catch (Exception ex) - { - if (HResults.E_BOUNDS == ex.HResult) - throw new ArgumentOutOfRangeException(nameof(index)); - - throw; - } - } - } -} diff --git a/src/coreclr/src/System.Private.CoreLib/src/System/Runtime/InteropServices/WindowsRuntime/VectorViewToReadOnlyCollectionAdapter.cs b/src/coreclr/src/System.Private.CoreLib/src/System/Runtime/InteropServices/WindowsRuntime/VectorViewToReadOnlyCollectionAdapter.cs deleted file mode 100644 index f782e11..0000000 --- a/src/coreclr/src/System.Private.CoreLib/src/System/Runtime/InteropServices/WindowsRuntime/VectorViewToReadOnlyCollectionAdapter.cs +++ /dev/null @@ -1,38 +0,0 @@ -// 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 Internal.Runtime.CompilerServices; - -namespace System.Runtime.InteropServices.WindowsRuntime -{ - // This is a set of stub methods implementing the support for the IReadOnlyCollection interface on WinRT - // objects that support IVectorView. Used by the interop mashaling infrastructure. - // - // The methods on this class must be written VERY carefully to avoid introducing security holes. - // That's because they are invoked with special "this"! The "this" object - // for all of these methods are not VectorViewToReadOnlyCollectionAdapter objects. Rather, they are of type - // IVectorView. No actual VectorViewToReadOnlyCollectionAdapter object is ever instantiated. Thus, you will see - // a lot of expressions that cast "this" to "IVectorView". - internal sealed class VectorViewToReadOnlyCollectionAdapter - { - private VectorViewToReadOnlyCollectionAdapter() - { - Debug.Fail("This class is never instantiated"); - } - - // int Count { get } - internal int Count() - { - IVectorView _this = Unsafe.As>(this); - uint size = _this.Size; - if (((uint)int.MaxValue) < size) - { - throw new InvalidOperationException(SR.InvalidOperation_CollectionBackingListTooLarge); - } - - return (int)size; - } - } -} diff --git a/src/coreclr/src/System.Private.CoreLib/src/System/Runtime/InteropServices/WindowsRuntime/WindowsFoundationEventHandler.cs b/src/coreclr/src/System.Private.CoreLib/src/System/Runtime/InteropServices/WindowsRuntime/WindowsFoundationEventHandler.cs deleted file mode 100644 index 216b48b..0000000 --- a/src/coreclr/src/System.Private.CoreLib/src/System/Runtime/InteropServices/WindowsRuntime/WindowsFoundationEventHandler.cs +++ /dev/null @@ -1,11 +0,0 @@ -// 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 System.Runtime.InteropServices.WindowsRuntime -{ - // WindowsFoundationEventHandler a copy of the definition for the Windows.Foundation.EventHandler delegate - [Guid("9de1c535-6ae1-11e0-84e1-18a905bcc53f")] - [WindowsRuntimeImport] - internal delegate void WindowsFoundationEventHandler(object sender, T args); -} diff --git a/src/coreclr/src/System.Private.CoreLib/src/System/Runtime/InteropServices/WindowsRuntime/WindowsRuntimeMarshal.cs b/src/coreclr/src/System.Private.CoreLib/src/System/Runtime/InteropServices/WindowsRuntime/WindowsRuntimeMarshal.cs deleted file mode 100644 index 23d62ab..0000000 --- a/src/coreclr/src/System.Private.CoreLib/src/System/Runtime/InteropServices/WindowsRuntime/WindowsRuntimeMarshal.cs +++ /dev/null @@ -1,1298 +0,0 @@ -// 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.Generic; -using System.Diagnostics; -using System.Reflection; -using System.Runtime.CompilerServices; -using System.Threading; - -namespace System.Runtime.InteropServices.WindowsRuntime -{ - // Helper functions to manually marshal data between .NET and WinRT - public static class WindowsRuntimeMarshal - { - // Add an event handler to a Windows Runtime style event, such that it can be removed via a delegate - // lookup at a later time. This method adds the handler to the add method using the supplied - // 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. - public static void AddEventHandler(Func addMethod, - Action removeMethod, - T handler) - { - if (addMethod == null) - throw new ArgumentNullException(nameof(addMethod)); - if (removeMethod == null) - throw new ArgumentNullException(nameof(removeMethod)); - - // Managed code allows adding a null event handler, the effect is a no-op. To match this behavior - // for WinRT events, we simply ignore attempts to add null. - if (handler == null) - { - return; - } - - // Delegate to managed event registration implementation or native event registration implementation - // They have completely different implementation because native side has its own unique problem to solve - - // there could be more than one RCW for the same COM object - // it would be more confusing and less-performant if we were to merge them together - object? target = removeMethod.Target; - if (target == null || Marshal.IsComObject(target)) - NativeOrStaticEventRegistrationImpl.AddEventHandler(addMethod, removeMethod, handler); - else - ManagedEventRegistrationImpl.AddEventHandler(addMethod, removeMethod, handler); - } - - // Remove the delegate handler from the Windows Runtime style event registration by looking for - // its token, previously stored via AddEventHandler - public static void RemoveEventHandler(Action removeMethod, T handler) - { - if (removeMethod == null) - throw new ArgumentNullException(nameof(removeMethod)); - - // Managed code allows removing a null event handler, the effect is a no-op. To match this behavior - // for WinRT events, we simply ignore attempts to remove null. - if (handler == null) - { - return; - } - - // Delegate to managed event registration implementation or native event registration implementation - // They have completely different implementation because native side has its own unique problem to solve - - // there could be more than one RCW for the same COM object - // it would be more confusing and less-performant if we were to merge them together - object? target = removeMethod.Target; - if (target == null || Marshal.IsComObject(target)) - NativeOrStaticEventRegistrationImpl.RemoveEventHandler(removeMethod, handler); - else - ManagedEventRegistrationImpl.RemoveEventHandler(removeMethod, handler); - } - - public static void RemoveAllEventHandlers(Action removeMethod) - { - if (removeMethod == null) - throw new ArgumentNullException(nameof(removeMethod)); - - // Delegate to managed event registration implementation or native event registration implementation - // They have completely different implementation because native side has its own unique problem to solve - - // there could be more than one RCW for the same COM object - // it would be more confusing and less-performant if we were to merge them together - object? target = removeMethod.Target; - if (target == null || Marshal.IsComObject(target)) - NativeOrStaticEventRegistrationImpl.RemoveAllEventHandlers(removeMethod); - else - ManagedEventRegistrationImpl.RemoveAllEventHandlers(removeMethod); - } - - // Returns the total cache size - // Used by test only to verify we don't leak event cache - internal static int GetRegistrationTokenCacheSize() - { - int count = 0; - - if (ManagedEventRegistrationImpl.s_eventRegistrations != null) - { - lock (ManagedEventRegistrationImpl.s_eventRegistrations) - { - foreach (var item in ManagedEventRegistrationImpl.s_eventRegistrations) - count++; - } - } - - if (NativeOrStaticEventRegistrationImpl.s_eventRegistrations != null) - { - lock (NativeOrStaticEventRegistrationImpl.s_eventRegistrations) - { - count += NativeOrStaticEventRegistrationImpl.s_eventRegistrations.Count; - } - } - - return count; - } - - // - // Optimized version of List of EventRegistrationToken - // It is made a struct to reduce overhead - // - internal struct EventRegistrationTokenList - { - private readonly EventRegistrationToken firstToken; // Optimization for common case where there is only one token - private List? restTokens; // Rest of the tokens - - internal EventRegistrationTokenList(EventRegistrationToken token) - { - firstToken = token; - restTokens = null; - } - - // Push a new token into this list - // Returns true if you need to copy back this list into the dictionary (so that you - // don't lose change outside the dictionary). false otherwise. - public bool Push(EventRegistrationToken token) - { - bool needCopy = false; - - if (restTokens == null) - { - restTokens = new List(); - needCopy = true; - } - - restTokens.Add(token); - - return needCopy; - } - - // Pops the last token - // Returns false if no more tokens left, true otherwise - public bool Pop(out EventRegistrationToken token) - { - // Only 1 token in this list and we just removed the last token - if (restTokens == null || restTokens.Count == 0) - { - token = firstToken; - return false; - } - - int last = restTokens.Count - 1; - token = restTokens[last]; - restTokens.RemoveAt(last); - - return true; - } - - public void CopyTo(List tokens) - { - tokens.Add(firstToken); - if (restTokens != null) - tokens.AddRange(restTokens); - } - } - - // - // Event registration support for managed objects events & static events - // - internal static class ManagedEventRegistrationImpl - { - // Mappings of delegates registered for events -> their registration tokens. - // These mappings are stored indexed by the remove method which can be used to undo the registrations. - // - // The full structure of this table is: - // object the event is being registered on -> - // Table [RemoveMethod] -> - // Table [Handler] -> Token - // - // Note: There are a couple of optimizations I didn't do here because they don't make sense for managed events: - // 1. Flatten the event cache (see EventCacheKey in native WinRT event implementation below) - // - // This is because managed events use ConditionalWeakTable to hold Objects->(Event->(Handler->Tokens)), - // and when object goes away everything else will be nicely cleaned up. If I flatten it like native WinRT events, - // I'll have to use Dictionary (as ConditionalWeakTable won't work - nobody will hold the new key alive anymore) - // instead, and that means I'll have to add more code from native WinRT events into managed WinRT event to support - // self-cleanup in the finalization, as well as reader/writer lock to protect against race conditions in the finalization, - // which adds a lot more complexity and doesn't really worth it. - // - // 2. Use conditionalWeakTable to hold Handler->Tokens. - // - // The reason is very simple - managed object use dictionary (see EventRegistrationTokenTable) to hold delegates alive. - // If the delegates aren't alive, it means either they have been unsubscribed, or the object itself is gone, - // and in either case, they've been already taken care of. - // - internal static volatile - ConditionalWeakTable>> s_eventRegistrations = - new ConditionalWeakTable>>(); - - internal static void AddEventHandler(Func addMethod, - Action removeMethod, - T handler) - { - Debug.Assert(addMethod != null); - Debug.Assert(removeMethod != null); - Debug.Assert(removeMethod.Target != null); - Debug.Assert(handler != null); - - // Add the method, and make a note of the token -> delegate mapping. - object instance = removeMethod.Target; - Dictionary registrationTokens = GetEventRegistrationTokenTable(instance, removeMethod); - EventRegistrationToken token = addMethod(handler); - lock (registrationTokens) - { - if (!registrationTokens.TryGetValue(handler, out EventRegistrationTokenList tokens)) - { - tokens = new EventRegistrationTokenList(token); - registrationTokens[handler] = tokens; - } - else - { - bool needCopy = tokens.Push(token); - - // You need to copy back this list into the dictionary (so that you don't lose change outside dictionary) - if (needCopy) - registrationTokens[handler] = tokens; - } - - Log("[WinRT_Eventing] Event subscribed for managed instance = " + instance + ", handler = " + handler + "\n"); - } - } - - // Get the event registration token table for an event. These are indexed by the remove method of the event. - private static Dictionary GetEventRegistrationTokenTable(object instance, Action removeMethod) - { - Debug.Assert(instance != null); - Debug.Assert(removeMethod != null); - Debug.Assert(s_eventRegistrations != null); - - lock (s_eventRegistrations) - { - if (!s_eventRegistrations.TryGetValue(instance, out Dictionary>? instanceMap)) - { - instanceMap = new Dictionary>(); - s_eventRegistrations.Add(instance, instanceMap); - } - - if (!instanceMap.TryGetValue(removeMethod.Method, out Dictionary? tokens)) - { - tokens = new Dictionary(); - instanceMap.Add(removeMethod.Method, tokens); - } - - return tokens; - } - } - - internal static void RemoveEventHandler(Action removeMethod, T handler) - { - Debug.Assert(removeMethod != null); - Debug.Assert(removeMethod.Target != null); - Debug.Assert(handler != null); - - object instance = removeMethod.Target; - Dictionary registrationTokens = GetEventRegistrationTokenTable(instance, removeMethod); - EventRegistrationToken token; - - lock (registrationTokens) - { - - // Failure to find a registration for a token is not an error - it's simply a no-op. - if (!registrationTokens.TryGetValue(handler, out EventRegistrationTokenList tokens)) - { - Log("[WinRT_Eventing] no registrationTokens found for instance=" + instance + ", handler= " + handler + "\n"); - - return; - } - - // Select a registration token to unregister - // We don't care which one but I'm returning the last registered token to be consistent - // with native event registration implementation - bool moreItems = tokens.Pop(out token); - if (!moreItems) - { - // Remove it from cache if this list become empty - // This must be done because EventRegistrationTokenList now becomes invalid - // (mostly because there is no safe default value for EventRegistrationToken to express 'no token') - // NOTE: We should try to remove registrationTokens itself from cache if it is empty, otherwise - // we could run into a race condition where one thread removes it from cache and another thread adds - // into the empty registrationToken table - registrationTokens.Remove(handler); - } - } - - removeMethod(token); - - Log("[WinRT_Eventing] Event unsubscribed for managed instance = " + instance + ", handler = " + handler + ", token = " + token.Value + "\n"); - } - - internal static void RemoveAllEventHandlers(Action removeMethod) - { - Debug.Assert(removeMethod != null); - Debug.Assert(removeMethod.Target != null); - - object instance = removeMethod.Target; - Dictionary registrationTokens = GetEventRegistrationTokenTable(instance, removeMethod); - - List tokensToRemove = new List(); - - lock (registrationTokens) - { - // Copy all tokens to tokensToRemove array which later we'll call removeMethod on - // outside this lock - foreach (EventRegistrationTokenList tokens in registrationTokens.Values) - { - tokens.CopyTo(tokensToRemove); - } - - // Clear the dictionary - at this point all event handlers are no longer in the cache - // but they are not removed yet - registrationTokens.Clear(); - Log("[WinRT_Eventing] Cache cleared for managed instance = " + instance + "\n"); - } - - // - // Remove all handlers outside the lock - // - Log("[WinRT_Eventing] Start removing all events for instance = " + instance + "\n"); - CallRemoveMethods(removeMethod, tokensToRemove); - Log("[WinRT_Eventing] Finished removing all events for instance = " + instance + "\n"); - } - } - - // - // WinRT event registration implementation code - // - internal static class NativeOrStaticEventRegistrationImpl - { - // - // Key = (target object, event) - // We use a key of object+event to save an extra dictionary - // - internal struct EventCacheKey : IEquatable - { - internal object target; - internal MethodInfo method; - - public override string ToString() - { - return "(" + target + ", " + method + ")"; - } - - public bool Equals(EventCacheKey other) - { - return object.Equals(target, other.target) && object.Equals(method, other.method); - } - - public int GetHashCode(EventCacheKey key) - { - return key.target.GetHashCode() ^ key.method.GetHashCode(); - } - } - - // - // EventRegistrationTokenListWithCount - // - // A list of EventRegistrationTokens that maintains a count - // - // The reason this needs to be a separate class is that we need a finalizer for this class - // If the delegate is collected, it will take this list away with it (due to dependent handles), - // and we need to remove the PerInstancEntry from cache - // See ~EventRegistrationTokenListWithCount for more details - // - internal class EventRegistrationTokenListWithCount - { - private readonly TokenListCount _tokenListCount; - private EventRegistrationTokenList _tokenList; - - internal EventRegistrationTokenListWithCount(TokenListCount tokenListCount, EventRegistrationToken token) - { - _tokenListCount = tokenListCount; - _tokenListCount.Inc(); - - _tokenList = new EventRegistrationTokenList(token); - } - - ~EventRegistrationTokenListWithCount() - { - // Decrement token list count - // This is need to correctly keep trace of number of tokens for EventCacheKey - // and remove it from cache when the token count drop to 0 - // we don't need to take locks for decrement the count - we only need to take a global - // lock when we decide to destroy cache for the IUnknown */type instance - Log("[WinRT_Eventing] Finalizing EventRegistrationTokenList for " + _tokenListCount.Key + "\n"); - _tokenListCount.Dec(); - } - - public void Push(EventRegistrationToken token) - { - // Since EventRegistrationTokenListWithCount is a reference type, there is no need - // to copy back. Ignore the return value - _tokenList.Push(token); - } - - public bool Pop(out EventRegistrationToken token) - { - return _tokenList.Pop(out token); - } - - public void CopyTo(List tokens) - { - _tokenList.CopyTo(tokens); - } - } - - // - // Maintains the number of tokens for a particular EventCacheKey - // TokenListCount is a class for two reasons: - // 1. Efficient update in the Dictionary to avoid lookup twice to update the value - // 2. Update token count without taking a global lock. Only takes a global lock when drop to 0 - // - internal class TokenListCount - { - private int _count; - private EventCacheKey _key; - - internal TokenListCount(EventCacheKey key) - { - _key = key; - } - - internal EventCacheKey Key => _key; - - internal void Inc() - { - int newCount = Interlocked.Increment(ref _count); - Log("[WinRT_Eventing] Incremented TokenListCount for " + _key + ", Value = " + newCount + "\n"); - } - - internal void Dec() - { - // Avoid racing with Add/Remove event entries into the cache - // You don't want this removing the key in the middle of a Add/Remove - s_eventCacheRWLock.AcquireWriterLock(Timeout.Infinite); - try - { - int newCount = Interlocked.Decrement(ref _count); - Log("[WinRT_Eventing] Decremented TokenListCount for " + _key + ", Value = " + newCount + "\n"); - if (newCount == 0) - CleanupCache(); - } - finally - { - s_eventCacheRWLock.ReleaseWriterLock(); - } - } - - private void CleanupCache() - { - // Time to destroy cache for this IUnknown */type instance - // because the total token list count has dropped to 0 and we don't have any events subscribed - Debug.Assert(s_eventRegistrations != null); - - Log("[WinRT_Eventing] Removing " + _key + " from cache\n"); - s_eventRegistrations.Remove(_key); - Log("[WinRT_Eventing] s_eventRegistrations size = " + s_eventRegistrations.Count + "\n"); - } - } - - internal struct EventCacheEntry - { - // [Handler] -> Token - internal ConditionalWeakTable registrationTable; - - // Maintains current total count for the EventRegistrationTokenListWithCount for this event cache key - internal TokenListCount tokenListCount; - } - - // Mappings of delegates registered for events -> their registration tokens. - // These mappings are stored indexed by the remove method which can be used to undo the registrations. - // - // The full structure of this table is: - // EventCacheKey (instanceKey, eventMethod) -> EventCacheEntry (Handler->tokens) - // - // A InstanceKey is the IUnknown * or static type instance - // - // Couple of things to note: - // 1. We need to use IUnknown* because we want to be able to unscribe to the event for another RCW - // based on the same COM object. For example: - // m_canvas.GetAt(0).Event += Func; - // m_canvas.GetAt(0).Event -= Func; // GetAt(0) might create a new RCW - // - // 2. Handler->Token is a ConditionalWeakTable because we don't want to keep the delegate alive - // and we want EventRegistrationTokenListWithCount to be finalized after the delegate is no longer alive - // 3. It is possible another COM object is created at the same address - // before the entry in cache is destroyed. More specifically, - // a. The same delegate is being unsubscribed. In this case we'll give them a - // stale token - unlikely to be a problem - // b. The same delegate is subscribed then unsubscribed. We need to make sure give - // them the latest token in this case. This is guaranteed by always giving the last token and always use equality to - // add/remove event handlers - internal static volatile Dictionary s_eventRegistrations = - new Dictionary(); - - // Prevent add/remove handler code to run at the same with with cache cleanup code - private static readonly MyReaderWriterLock s_eventCacheRWLock = new MyReaderWriterLock(); - - // Get InstanceKey to use in the cache - private static object GetInstanceKey(Action removeMethod) - { - object? target = removeMethod.Target; - Debug.Assert(target == null || Marshal.IsComObject(target), "Must be null or a RCW"); - if (target == null) - return removeMethod.Method.DeclaringType!; - - // Need the "Raw" IUnknown pointer for the RCW that is not bound to the current context - return (object)Marshal.GetRawIUnknownForComObjectNoAddRef(target); - } - - private static object? FindEquivalentKeyUnsafe(ConditionalWeakTable registrationTable, object handler, out EventRegistrationTokenListWithCount? tokens) - { - foreach (KeyValuePair item in registrationTable) - { - if (object.Equals(item.Key, handler)) - { - tokens = item.Value; - return item.Key; - } - } - tokens = null; - return null; - } - - internal static void AddEventHandler(Func addMethod, - Action removeMethod, - T handler) - { - Debug.Assert(handler != null); - - // The instanceKey will be IUnknown * of the target object - object instanceKey = GetInstanceKey(removeMethod); - - // Call addMethod outside of RW lock - // At this point we don't need to worry about race conditions and we can avoid deadlocks - // if addMethod waits on finalizer thread - // If we later throw we need to remove the method - EventRegistrationToken token = addMethod(handler); - - bool tokenAdded = false; - - try - { - - // - // The whole add/remove code has to be protected by a reader/writer lock - // Add/Remove cannot run at the same time with cache cleanup but Add/Remove can run at the same time - // - s_eventCacheRWLock.AcquireReaderLock(Timeout.Infinite); - try - { - // Add the method, and make a note of the delegate -> token mapping. - ConditionalWeakTable registrationTokens = GetOrCreateEventRegistrationTokenTable(instanceKey, removeMethod, out TokenListCount tokenListCount); - lock (registrationTokens) - { - // - // We need to find the key that equals to this handler - // Suppose we have 3 handlers A, B, C that are equal (refer to the same object and method), - // the first handler (let's say A) will be used as the key and holds all the tokens. - // We don't need to hold onto B and C, because the COM object itself will keep them alive, - // and they won't die anyway unless the COM object dies or they get unsubscribed. - // It may appear that it is fine to hold A, B, C, and add them and their corresponding tokens - // into registrationTokens table. However, this is very dangerous, because this COM object - // may die, but A, B, C might not get collected yet, and another COM object comes into life - // with the same IUnknown address, and we subscribe event B. In this case, the right token - // will be added into B's token list, but once we unsubscribe B, we might end up removing - // the last token in C, and that may lead to crash. - // - object? key = FindEquivalentKeyUnsafe(registrationTokens, handler, out EventRegistrationTokenListWithCount? tokens); - if (key == null) - { - tokens = new EventRegistrationTokenListWithCount(tokenListCount, token); - registrationTokens.Add(handler, tokens); - } - else - { - tokens!.Push(token); - } - - tokenAdded = true; - } - } - finally - { - s_eventCacheRWLock.ReleaseReaderLock(); - } - - Log("[WinRT_Eventing] Event subscribed for instance = " + instanceKey + ", handler = " + handler + "\n"); - } - catch (Exception) - { - // If we've already added the token and go there, we don't need to "UNDO" anything - if (!tokenAdded) - { - // Otherwise, "Undo" addMethod if any exception occurs - // There is no need to cleanup our data structure as we haven't added the token yet - removeMethod(token); - } - - throw; - } - } - - private static ConditionalWeakTable? GetEventRegistrationTokenTableNoCreate(object instance, Action removeMethod, out TokenListCount? tokenListCount) - { - Debug.Assert(instance != null); - Debug.Assert(removeMethod != null); - - return GetEventRegistrationTokenTableInternal(instance, removeMethod, out tokenListCount, /* createIfNotFound = */ false); - } - - private static ConditionalWeakTable GetOrCreateEventRegistrationTokenTable(object instance, Action removeMethod, out TokenListCount tokenListCount) - { - Debug.Assert(instance != null); - Debug.Assert(removeMethod != null); - - return GetEventRegistrationTokenTableInternal(instance, removeMethod, out tokenListCount!, /* createIfNotFound = */ true)!; - } - - // Get the event registration token table for an event. These are indexed by the remove method of the event. - private static ConditionalWeakTable? GetEventRegistrationTokenTableInternal(object instance, Action removeMethod, out TokenListCount? tokenListCount, bool createIfNotFound) - { - Debug.Assert(instance != null); - Debug.Assert(removeMethod != null); - Debug.Assert(s_eventRegistrations != null); - - EventCacheKey eventCacheKey; - eventCacheKey.target = instance; - eventCacheKey.method = removeMethod.Method; - - lock (s_eventRegistrations) - { - if (!s_eventRegistrations.TryGetValue(eventCacheKey, out EventCacheEntry eventCacheEntry)) - { - if (!createIfNotFound) - { - // No need to create an entry in this case - tokenListCount = null; - return null; - } - - Log("[WinRT_Eventing] Adding (" + instance + "," + removeMethod.Method + ") into cache\n"); - - eventCacheEntry = default; - eventCacheEntry.registrationTable = new ConditionalWeakTable(); - eventCacheEntry.tokenListCount = new TokenListCount(eventCacheKey); - - s_eventRegistrations.Add(eventCacheKey, eventCacheEntry); - } - - tokenListCount = eventCacheEntry.tokenListCount; - - return eventCacheEntry.registrationTable; - } - } - - internal static void RemoveEventHandler(Action removeMethod, T handler) - { - Debug.Assert(handler != null); - - object instanceKey = GetInstanceKey(removeMethod); - - EventRegistrationToken token; - - // - // The whole add/remove code has to be protected by a reader/writer lock - // Add/Remove cannot run at the same time with cache cleanup but Add/Remove can run at the same time - // - s_eventCacheRWLock.AcquireReaderLock(Timeout.Infinite); - try - { - ConditionalWeakTable? registrationTokens = GetEventRegistrationTokenTableNoCreate(instanceKey, removeMethod, out TokenListCount? tokenListCount); - if (registrationTokens == null) - { - // We have no information regarding this particular instance (IUnknown*/type) - just return - // This is necessary to avoid leaking empty dictionary/conditionalWeakTables for this instance - Log("[WinRT_Eventing] no registrationTokens found for instance=" + instanceKey + ", handler= " + handler + "\n"); - return; - } - - lock (registrationTokens) - { - - // Note: - // When unsubscribing events, we allow subscribing the event using a different delegate - // (but with the same object/method), so we need to find the first delegate that matches - // and unsubscribe it - // It actually doesn't matter which delegate - as long as it matches - // Note that inside TryGetValueWithValueEquality we assumes that any delegate - // with the same value equality would have the same hash code - object? key = FindEquivalentKeyUnsafe(registrationTokens, handler, out EventRegistrationTokenListWithCount? tokens); - Debug.Assert((key != null && tokens != null) || (key == null && tokens == null), - "key and tokens must be both null or non-null"); - if (tokens == null) - { - // Failure to find a registration for a token is not an error - it's simply a no-op. - Log("[WinRT_Eventing] no token list found for instance=" + instanceKey + ", handler= " + handler + "\n"); - return; - } - - // Select a registration token to unregister - // Note that we need to always get the last token just in case another COM object - // is created at the same address before the entry for the old one goes away. - // See comments above s_eventRegistrations for more details - bool moreItems = tokens.Pop(out token); - - // If the last token is removed from token list, we need to remove it from the cache - // otherwise FindEquivalentKeyUnsafe may found this empty token list even though there could be other - // equivalent keys in there with non-0 token list - if (!moreItems) - { - // Remove it from (handler)->(tokens) - // NOTE: We should not check whether registrationTokens has 0 entries and remove it from the cache - // (just like managed event implementation), because this might have raced with the finalizer of - // EventRegistrationTokenList - registrationTokens.Remove(key!); - } - - Log("[WinRT_Eventing] Event unsubscribed for managed instance = " + instanceKey + ", handler = " + handler + ", token = " + token.Value + "\n"); - } - } - finally - { - s_eventCacheRWLock.ReleaseReaderLock(); - } - - // Call removeMethod outside of RW lock - // At this point we don't need to worry about race conditions and we can avoid deadlocks - // if removeMethod waits on finalizer thread - removeMethod(token); - } - - internal static void RemoveAllEventHandlers(Action removeMethod) - { - object instanceKey = GetInstanceKey(removeMethod); - - List tokensToRemove = new List(); - - // - // The whole add/remove code has to be protected by a reader/writer lock - // Add/Remove cannot run at the same time with cache cleanup but Add/Remove can run at the same time - // - s_eventCacheRWLock.AcquireReaderLock(Timeout.Infinite); - try - { - ConditionalWeakTable? registrationTokens = GetEventRegistrationTokenTableNoCreate(instanceKey, removeMethod, out _); - if (registrationTokens == null) - { - // We have no information regarding this particular instance (IUnknown*/type) - just return - // This is necessary to avoid leaking empty dictionary/conditionalWeakTables for this instance - return; - } - - lock (registrationTokens) - { - // Copy all tokens to tokensToRemove array which later we'll call removeMethod on - // outside this lock - foreach (KeyValuePair item in registrationTokens) - { - item.Value.CopyTo(tokensToRemove); - } - - // Clear the table - at this point all event handlers are no longer in the cache - // but they are not removed yet - registrationTokens.Clear(); - Log("[WinRT_Eventing] Cache cleared for managed instance = " + instanceKey + "\n"); - } - } - finally - { - s_eventCacheRWLock.ReleaseReaderLock(); - } - - // - // Remove all handlers outside the lock - // - Log("[WinRT_Eventing] Start removing all events for instance = " + instanceKey + "\n"); - CallRemoveMethods(removeMethod, tokensToRemove); - Log("[WinRT_Eventing] Finished removing all events for instance = " + instanceKey + "\n"); - } - - internal class ReaderWriterLockTimedOutException : ApplicationException - { - } - - /// Discussed @ https://blogs.msdn.microsoft.com/vancem/2006/03/29/analysis-of-reader-writer-lock/ - /// - /// - /// A reader-writer lock implementation that is intended to be simple, yet very - /// efficient. In particular only 1 interlocked operation is taken for any lock - /// operation (we use spin locks to achieve this). The spin lock is never held - /// for more than a few instructions (in particular, we never call event APIs - /// or in fact any non-trivial API while holding the spin lock). - /// - /// Currently this ReaderWriterLock does not support recursion, however it is - /// not hard to add - /// - internal class MyReaderWriterLock - { - // Lock specifiation for myLock: This lock protects exactly the local fields associted - // instance of MyReaderWriterLock. It does NOT protect the memory associted with the - // the events that hang off this lock (eg writeEvent, readEvent upgradeEvent). - private int myLock; - - // Who owns the lock owners > 0 => readers - // owners = -1 means there is one writer. Owners must be >= -1. - private int owners; - - // These variables allow use to avoid Setting events (which is expensive) if we don't have to. - private uint numWriteWaiters; // maximum number of threads that can be doing a WaitOne on the writeEvent - private uint numReadWaiters; // maximum number of threads that can be doing a WaitOne on the readEvent - - // conditions we wait on. - private EventWaitHandle? writeEvent; // threads waiting to acquire a write lock go here. - private EventWaitHandle? readEvent; // threads waiting to acquire a read lock go here (will be released in bulk) - - internal MyReaderWriterLock() - { - // All state can start out zeroed. - } - - internal void AcquireReaderLock(int millisecondsTimeout) - { - EnterMyLock(); - while (true) - { - // We can enter a read lock if there are only read-locks have been given out - // and a writer is not trying to get in. - if (owners >= 0 && numWriteWaiters == 0) - { - // Good case, there is no contention, we are basically done - owners++; // Indicate we have another reader - break; - } - - // Drat, we need to wait. Mark that we have waiters and wait. - if (readEvent == null) // Create the needed event - { - LazyCreateEvent(ref readEvent, false); - continue; // since we left the lock, start over. - } - - WaitOnEvent(readEvent, ref numReadWaiters, millisecondsTimeout); - } - ExitMyLock(); - } - - internal void AcquireWriterLock(int millisecondsTimeout) - { - EnterMyLock(); - while (true) - { - if (owners == 0) - { - // Good case, there is no contention, we are basically done - owners = -1; // indicate we have a writer. - break; - } - - // Drat, we need to wait. Mark that we have waiters and wait. - if (writeEvent == null) // create the needed event. - { - LazyCreateEvent(ref writeEvent, true); - continue; // since we left the lock, start over. - } - - WaitOnEvent(writeEvent, ref numWriteWaiters, millisecondsTimeout); - } - ExitMyLock(); - } - - internal void ReleaseReaderLock() - { - EnterMyLock(); - Debug.Assert(owners > 0, "ReleasingReaderLock: releasing lock and no read lock taken"); - --owners; - ExitAndWakeUpAppropriateWaiters(); - } - - internal void ReleaseWriterLock() - { - EnterMyLock(); - Debug.Assert(owners == -1, "Calling ReleaseWriterLock when no write lock is held"); - owners++; - ExitAndWakeUpAppropriateWaiters(); - } - - /// - /// A routine for lazily creating a event outside the lock (so if errors - /// happen they are outside the lock and that we don't do much work - /// while holding a spin lock). If all goes well, reenter the lock and - /// set 'waitEvent' - /// - private void LazyCreateEvent(ref EventWaitHandle? waitEvent, bool makeAutoResetEvent) - { - Debug.Assert(myLock != 0, "Lock must be held"); - Debug.Assert(waitEvent == null, "Wait event must be null"); - - ExitMyLock(); - EventWaitHandle newEvent; - if (makeAutoResetEvent) - newEvent = new AutoResetEvent(false); - else - newEvent = new ManualResetEvent(false); - EnterMyLock(); - if (waitEvent == null) // maybe someone snuck in. - waitEvent = newEvent; - } - - /// - /// Waits on 'waitEvent' with a timeout of 'millisceondsTimeout. - /// Before the wait 'numWaiters' is incremented and is restored before leaving this routine. - /// - private void WaitOnEvent(EventWaitHandle waitEvent, ref uint numWaiters, int millisecondsTimeout) - { - Debug.Assert(myLock != 0, "Lock must be held"); - - waitEvent.Reset(); - numWaiters++; - - bool waitSuccessful = false; - ExitMyLock(); // Do the wait outside of any lock - try - { - if (!waitEvent.WaitOne(millisecondsTimeout, false)) - throw new ReaderWriterLockTimedOutException(); - - waitSuccessful = true; - } - finally - { - EnterMyLock(); - --numWaiters; - if (!waitSuccessful) // We are going to throw for some reason. Exit myLock. - ExitMyLock(); - } - } - - /// - /// Determines the appropriate events to set, leaves the locks, and sets the events. - /// - private void ExitAndWakeUpAppropriateWaiters() - { - Debug.Assert(myLock != 0, "Lock must be held"); - - if (owners == 0 && numWriteWaiters > 0) - { - ExitMyLock(); // Exit before signaling to improve efficiency (wakee will need the lock) - writeEvent!.Set(); // release one writer. Must be non-null if there were waiters. - } - else if (owners >= 0 && numReadWaiters != 0) - { - ExitMyLock(); // Exit before signaling to improve efficiency (wakee will need the lock) - readEvent!.Set(); // release all readers. Must be non-null if there were waiters. - } - else - { - ExitMyLock(); - } - } - - private void EnterMyLock() - { - if (Interlocked.CompareExchange(ref myLock, 1, 0) != 0) - EnterMyLockSpin(); - } - - private void EnterMyLockSpin() - { - for (int i = 0; ; i++) - { - if (i < 3 && Environment.ProcessorCount > 1) - Thread.SpinWait(20); // Wait a few dozen instructions to let another processor release lock. - else - Thread.Sleep(0); // Give up my quantum. - - if (Interlocked.CompareExchange(ref myLock, 1, 0) == 0) - return; - } - } - private void ExitMyLock() - { - Debug.Assert(myLock != 0, "Exiting spin lock that is not held"); - myLock = 0; - } - } - } - - // - // Call removeMethod on each token and aggregate all exceptions thrown from removeMethod into one in case of failure - // - internal static void CallRemoveMethods(Action removeMethod, List tokensToRemove) - { - List exceptions = new List(); - - foreach (EventRegistrationToken token in tokensToRemove) - { - try - { - removeMethod(token); - } - catch (Exception ex) - { - exceptions.Add(ex); - } - - Log("[WinRT_Eventing] Event unsubscribed for token = " + token.Value + "\n"); - } - - if (exceptions.Count > 0) - throw new AggregateException(exceptions.ToArray()); - } - - internal static unsafe string HStringToString(IntPtr hstring) - { - Debug.Assert(Environment.IsWinRTSupported); - - // There is no difference between a null and empty HSTRING - if (hstring == IntPtr.Zero) - { - return string.Empty; - } - - uint length; - char* rawBuffer = UnsafeNativeMethods.WindowsGetStringRawBuffer(hstring, &length); - return new string(rawBuffer, 0, checked((int)length)); - } - - internal static Exception GetExceptionForHR(int hresult, Exception? innerException, string? messageResource) - { - Exception? e; - if (innerException != null) - { - string? message = innerException.Message; - if (message == null && messageResource != null) - { - message = SR.GetResourceString(messageResource); - } - e = new Exception(message, innerException); - } - else - { - string? message = messageResource != null ? SR.GetResourceString(messageResource) : null; - e = new Exception(message); - } - - e.HResult = hresult; - return e; - } - - internal static Exception GetExceptionForHR(int hresult, Exception? innerException) - { - return GetExceptionForHR(hresult, innerException, null); - } - - private static bool s_haveBlueErrorApis = true; - - private static bool RoOriginateLanguageException(int error, string message, IntPtr languageException) - { - if (s_haveBlueErrorApis) - { - try - { - return UnsafeNativeMethods.RoOriginateLanguageException(error, message, languageException); - } - catch (EntryPointNotFoundException) - { - s_haveBlueErrorApis = false; - } - } - - return false; - } - - private static void RoReportUnhandledError(IRestrictedErrorInfo error) - { - if (s_haveBlueErrorApis) - { - try - { - UnsafeNativeMethods.RoReportUnhandledError(error); - } - catch (EntryPointNotFoundException) - { - s_haveBlueErrorApis = false; - } - } - } - - private static Guid s_iidIErrorInfo = new Guid(0x1CF2B120, 0x547D, 0x101B, 0x8E, 0x65, 0x08, 0x00, 0x2B, 0x2B, 0xD1, 0x19); - - /// - /// Report that an exception has occurred which went user unhandled. This allows the global error handler - /// for the application to be invoked to process the error. - /// - /// true if the error was reported, false if not (ie running on Win8) - internal static bool ReportUnhandledError(Exception? e) - { - // Only report to the WinRT global exception handler in modern apps - if (!ApplicationModel.IsUap) - { - return false; - } - - // If we don't have the capability to report to the global error handler, early out - if (!s_haveBlueErrorApis) - { - return false; - } - - if (e != null) - { - IntPtr exceptionIUnknown = IntPtr.Zero; - IntPtr exceptionIErrorInfo = IntPtr.Zero; - try - { - // Get an IErrorInfo for the current exception and originate it as a langauge error in order to have - // Windows generate an IRestrictedErrorInfo corresponding to the exception object. We can then - // notify the global error handler that this IRestrictedErrorInfo instance represents an exception that - // went unhandled in managed code. - // - // Note that we need to get an IUnknown for the exception object and then QI for IErrorInfo since Exception - // doesn't implement IErrorInfo in managed code - only its CCW does. - exceptionIUnknown = Marshal.GetIUnknownForObject(e); - if (exceptionIUnknown != IntPtr.Zero) - { - Marshal.QueryInterface(exceptionIUnknown, ref s_iidIErrorInfo, out exceptionIErrorInfo); - if (exceptionIErrorInfo != IntPtr.Zero) - { - if (RoOriginateLanguageException(Marshal.GetHRForException(e), e.Message, exceptionIErrorInfo)) - { - IRestrictedErrorInfo restrictedError = UnsafeNativeMethods.GetRestrictedErrorInfo(); - if (restrictedError != null) - { - RoReportUnhandledError(restrictedError); - return true; - } - } - } - } - } - finally - { - if (exceptionIErrorInfo != IntPtr.Zero) - { - Marshal.Release(exceptionIErrorInfo); - } - - if (exceptionIUnknown != IntPtr.Zero) - { - Marshal.Release(exceptionIUnknown); - } - } - } - - // If we got here, then some step of the marshaling failed, which means the GEH was not invoked - return false; - } - -#if FEATURE_COMINTEROP_WINRT_MANAGED_ACTIVATION - // Get an IActivationFactory * for a managed type - internal static IntPtr GetActivationFactoryForType(Type type) - { - ManagedActivationFactory activationFactory = GetManagedActivationFactory(type); - return Marshal.GetComInterfaceForObject(activationFactory, typeof(IActivationFactory)); - } - - internal static ManagedActivationFactory GetManagedActivationFactory(Type type) - { - ManagedActivationFactory activationFactory = new ManagedActivationFactory(type); - - // If the type has any associated factory interfaces (i.e. supports non-default activation - // or has statics), the CCW for this instance of ManagedActivationFactory must support them. - InitializeManagedWinRTFactoryObject(activationFactory, (RuntimeType)type); - return activationFactory; - } - -#endif // FEATURE_COMINTEROP_WINRT_MANAGED_ACTIVATION - - // - // Get activation factory object for a specified WinRT type - // If the WinRT type is a native type, we'll always create a unique RCW for it, - // This is necessary because WinRT factories are often implemented as a singleton, - // and getting back a RCW for such WinRT factory would usually get back a RCW from - // another apartment, even if the interface pointe returned from GetActivationFactory - // is a raw pointer. As a result, user would randomly get back RCWs for activation - // factories from other apartments and make transiton to those apartments and cause - // deadlocks and create objects in incorrect apartments - // - public static IActivationFactory GetActivationFactory(Type type) - { - if (type == null) - throw new ArgumentNullException(nameof(type)); - - if (type.IsWindowsRuntimeObject && type.IsImport) - { - return (IActivationFactory)GetNativeActivationFactory(type); - } - else - { -#if FEATURE_COMINTEROP_WINRT_MANAGED_ACTIVATION - return GetManagedActivationFactory(type); -#else - // Managed factories are not supported so as to minimize public surface (and test effort) - throw new NotSupportedException(); -#endif - } - } - - // HSTRING marshaling methods: - - public static IntPtr StringToHString(string s) - { - if (!Environment.IsWinRTSupported) - throw new PlatformNotSupportedException(SR.PlatformNotSupported_WinRT); - - if (s == null) - throw new ArgumentNullException(nameof(s)); - - unsafe - { - IntPtr hstring; - int hrCreate = UnsafeNativeMethods.WindowsCreateString(s, s.Length, &hstring); - Marshal.ThrowExceptionForHR(hrCreate, new IntPtr(-1)); - return hstring; - } - } - - public static string PtrToStringHString(IntPtr ptr) - { - if (!Environment.IsWinRTSupported) - { - throw new PlatformNotSupportedException(SR.PlatformNotSupported_WinRT); - } - - return HStringToString(ptr); - } - - public static void FreeHString(IntPtr ptr) - { - if (!Environment.IsWinRTSupported) - throw new PlatformNotSupportedException(SR.PlatformNotSupported_WinRT); - - if (ptr != IntPtr.Zero) - { - UnsafeNativeMethods.WindowsDeleteString(ptr); - } - } - - [MethodImpl(MethodImplOptions.InternalCall)] - public static extern object GetUniqueObjectForIUnknownWithoutUnboxing(IntPtr unknown); - - [MethodImpl(MethodImplOptions.InternalCall)] - internal static extern void InitializeWrapper(object o, ref IntPtr pUnk); - - /// - /// Converts the CLR exception to an HRESULT. This function also sets - /// up an IErrorInfo for the exception. - /// This function is only used in WinRT and converts ObjectDisposedException - /// to RO_E_CLOSED - /// - [MethodImpl(MethodImplOptions.InternalCall)] - internal static extern int GetHRForException(Exception e); - -#if FEATURE_COMINTEROP_WINRT_MANAGED_ACTIVATION - [MethodImpl(MethodImplOptions.InternalCall)] - internal static extern void InitializeManagedWinRTFactoryObject(object o, RuntimeType runtimeClassType); -#endif - - /// - /// Create activation factory and wraps it with a unique RCW. - /// - [MethodImpl(MethodImplOptions.InternalCall)] - internal static extern object GetNativeActivationFactory(Type type); - - [Conditional("_LOGGING")] - private static void Log(string s) - { - // Internal.Console.WriteLine(s); - } - } -} diff --git a/src/coreclr/src/System.Private.CoreLib/src/System/Runtime/InteropServices/WindowsRuntime/WindowsRuntimeMetadata.cs b/src/coreclr/src/System.Private.CoreLib/src/System/Runtime/InteropServices/WindowsRuntime/WindowsRuntimeMetadata.cs deleted file mode 100644 index 01ba97d..0000000 --- a/src/coreclr/src/System.Private.CoreLib/src/System/Runtime/InteropServices/WindowsRuntime/WindowsRuntimeMetadata.cs +++ /dev/null @@ -1,62 +0,0 @@ -// 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.ObjectModel; - -namespace System.Runtime.InteropServices.WindowsRuntime -{ - internal static class WindowsRuntimeMetadata - { - private static readonly EventHandler? DesignerNamespaceResolve; - - internal static string[]? OnDesignerNamespaceResolve(string namespaceName) - { - EventHandler? eventHandler = DesignerNamespaceResolve; - if (eventHandler != null) - { - foreach (EventHandler handler in eventHandler.GetInvocationList()) - { - DesignerNamespaceResolveEventArgs eventArgs = new DesignerNamespaceResolveEventArgs(namespaceName); - - handler(AppDomain.CurrentDomain, eventArgs); - - Collection assemblyFilesCollection = eventArgs.ResolvedAssemblyFiles; - if (assemblyFilesCollection.Count > 0) - { - string[] retAssemblyFiles = new string[assemblyFilesCollection.Count]; - int retIndex = 0; - foreach (string assemblyFile in assemblyFilesCollection) - { - if (string.IsNullOrEmpty(assemblyFile)) - { // DesignerNamespaceResolve event returned null or empty file name - that is not allowed - throw new ArgumentException(SR.Arg_EmptyOrNullString, "DesignerNamespaceResolveEventArgs.ResolvedAssemblyFiles"); - } - retAssemblyFiles[retIndex] = assemblyFile; - retIndex++; - } - - return retAssemblyFiles; - } - } - } - - return null; - } - } - - - internal class DesignerNamespaceResolveEventArgs : EventArgs - { - private readonly string _NamespaceName; - private readonly Collection _ResolvedAssemblyFiles; - - public Collection ResolvedAssemblyFiles => _ResolvedAssemblyFiles; - - public DesignerNamespaceResolveEventArgs(string namespaceName) - { - _NamespaceName = namespaceName; - _ResolvedAssemblyFiles = new Collection(); - } - } -} diff --git a/src/coreclr/src/System.Private.CoreLib/src/System/Runtime/Loader/AssemblyLoadContext.CoreCLR.cs b/src/coreclr/src/System.Private.CoreLib/src/System/Runtime/Loader/AssemblyLoadContext.CoreCLR.cs index 997fa49..5bd31a8 100644 --- a/src/coreclr/src/System.Private.CoreLib/src/System/Runtime/Loader/AssemblyLoadContext.CoreCLR.cs +++ b/src/coreclr/src/System.Private.CoreLib/src/System/Runtime/Loader/AssemblyLoadContext.CoreCLR.cs @@ -131,26 +131,6 @@ namespace System.Runtime.Loader } [DllImport(RuntimeHelpers.QCall, CharSet = CharSet.Unicode)] - private static extern void LoadTypeForWinRTTypeNameInContextInternal(IntPtr ptrNativeAssemblyLoadContext, string typeName, ObjectHandleOnStack loadedType); - - internal Type LoadTypeForWinRTTypeNameInContext(string typeName) - { - if (typeName is null) - { - throw new ArgumentNullException(nameof(typeName)); - } - - lock (_unloadLock) - { - VerifyIsAlive(); - - Type? type = null; - LoadTypeForWinRTTypeNameInContextInternal(_nativeAssemblyLoadContext, typeName, ObjectHandleOnStack.Create(ref type)); - return type!; - } - } - - [DllImport(RuntimeHelpers.QCall, CharSet = CharSet.Unicode)] private static extern IntPtr GetLoadContextForAssembly(QCallAssembly assembly); // Returns the load context in which the specified assembly has been loaded diff --git a/src/coreclr/src/System.Private.CoreLib/src/System/RuntimeHandles.cs b/src/coreclr/src/System.Private.CoreLib/src/System/RuntimeHandles.cs index c95afb2..65d3975 100644 --- a/src/coreclr/src/System.Private.CoreLib/src/System/RuntimeHandles.cs +++ b/src/coreclr/src/System.Private.CoreLib/src/System/RuntimeHandles.cs @@ -406,17 +406,16 @@ namespace System [DllImport(RuntimeHelpers.QCall, CharSet = CharSet.Unicode)] private static extern void GetTypeByName(string name, bool throwOnError, bool ignoreCase, StackCrawlMarkHandle stackMark, ObjectHandleOnStack assemblyLoadContext, - bool loadTypeFromPartialName, ObjectHandleOnStack type, ObjectHandleOnStack keepalive); + ObjectHandleOnStack type, ObjectHandleOnStack keepalive); // Wrapper function to reduce the need for ifdefs. - internal static RuntimeType? GetTypeByName(string name, bool throwOnError, bool ignoreCase, ref StackCrawlMark stackMark, bool loadTypeFromPartialName) + internal static RuntimeType? GetTypeByName(string name, bool throwOnError, bool ignoreCase, ref StackCrawlMark stackMark) { - return GetTypeByName(name, throwOnError, ignoreCase, ref stackMark, AssemblyLoadContext.CurrentContextualReflectionContext!, loadTypeFromPartialName); + return GetTypeByName(name, throwOnError, ignoreCase, ref stackMark, AssemblyLoadContext.CurrentContextualReflectionContext!); } internal static RuntimeType? GetTypeByName(string name, bool throwOnError, bool ignoreCase, ref StackCrawlMark stackMark, - AssemblyLoadContext assemblyLoadContext, - bool loadTypeFromPartialName) + AssemblyLoadContext assemblyLoadContext) { if (string.IsNullOrEmpty(name)) { @@ -432,7 +431,7 @@ namespace System GetTypeByName(name, throwOnError, ignoreCase, new StackCrawlMarkHandle(ref stackMark), ObjectHandleOnStack.Create(ref assemblyLoadContextStack), - loadTypeFromPartialName, ObjectHandleOnStack.Create(ref type), ObjectHandleOnStack.Create(ref keepAlive)); + ObjectHandleOnStack.Create(ref type), ObjectHandleOnStack.Create(ref keepAlive)); GC.KeepAlive(keepAlive); return type; diff --git a/src/coreclr/src/System.Private.CoreLib/src/System/RuntimeType.CoreCLR.cs b/src/coreclr/src/System.Private.CoreLib/src/System/RuntimeType.CoreCLR.cs index 3851127..ddcf030 100644 --- a/src/coreclr/src/System.Private.CoreLib/src/System/RuntimeType.CoreCLR.cs +++ b/src/coreclr/src/System.Private.CoreLib/src/System/RuntimeType.CoreCLR.cs @@ -1675,7 +1675,7 @@ namespace System throw new ArgumentNullException(nameof(typeName)); return RuntimeTypeHandle.GetTypeByName( - typeName, throwOnError, ignoreCase, ref stackMark, false); + typeName, throwOnError, ignoreCase, ref stackMark); } internal static MethodBase? GetMethodBase(RuntimeModule scope, int typeMetadataToken) @@ -3123,20 +3123,6 @@ namespace System [MethodImpl(MethodImplOptions.InternalCall)] private extern void GetGUID(ref Guid result); -#if FEATURE_COMINTEROP - internal override bool IsWindowsRuntimeObjectImpl() => IsWindowsRuntimeObjectType(this); - - [MethodImpl(MethodImplOptions.InternalCall)] - private static extern bool IsWindowsRuntimeObjectType(RuntimeType type); - -#if FEATURE_COMINTEROP_WINRT_MANAGED_ACTIVATION - internal override bool IsExportedToWindowsRuntimeImpl() => IsTypeExportedToWindowsRuntime(this); - - [MethodImpl(MethodImplOptions.InternalCall)] - private static extern bool IsTypeExportedToWindowsRuntime(RuntimeType type); -#endif // FEATURE_COMINTEROP_WINRT_MANAGED_ACTIVATION -#endif // FEATURE_COMINTEROP - internal bool IsDelegate() => GetBaseType() == typeof(MulticastDelegate); public override GenericParameterAttributes GenericParameterAttributes diff --git a/src/coreclr/src/System.Private.CoreLib/src/System/StubHelpers.cs b/src/coreclr/src/System.Private.CoreLib/src/System/StubHelpers.cs index 51d0138..f6861b7 100644 --- a/src/coreclr/src/System.Private.CoreLib/src/System/StubHelpers.cs +++ b/src/coreclr/src/System.Private.CoreLib/src/System/StubHelpers.cs @@ -5,9 +5,6 @@ using System.Text; using System.Collections.Generic; using System.Runtime.InteropServices; -#if FEATURE_COMINTEROP -using System.Runtime.InteropServices.WindowsRuntime; -#endif // FEATURE_COMINTEROP using System.Runtime.CompilerServices; using System.Diagnostics; using Internal.Runtime.CompilerServices; @@ -542,102 +539,7 @@ namespace System.StubHelpers native[numChars] = '\0'; } } // class WSTRBufferMarshaler - -#if FEATURE_COMINTEROP - - [StructLayout(LayoutKind.Sequential)] - internal struct DateTimeNative - { - public long UniversalTime; - } - - internal static class DateTimeOffsetMarshaler - { - // Numer of ticks counted between 0001-01-01, 00:00:00 and 1601-01-01, 00:00:00. - // You can get this through: (new DateTimeOffset(1601, 1, 1, 0, 0, 1, TimeSpan.Zero)).Ticks; - private const long ManagedUtcTicksAtNativeZero = 504911232000000000; - - internal static void ConvertToNative(ref DateTimeOffset managedDTO, out DateTimeNative dateTime) - { - long managedUtcTicks = managedDTO.UtcTicks; - dateTime.UniversalTime = managedUtcTicks - ManagedUtcTicksAtNativeZero; - } - - internal static void ConvertToManaged(out DateTimeOffset managedLocalDTO, ref DateTimeNative nativeTicks) - { - long managedUtcTicks = ManagedUtcTicksAtNativeZero + nativeTicks.UniversalTime; - DateTimeOffset managedUtcDTO = new DateTimeOffset(managedUtcTicks, TimeSpan.Zero); - - // Some Utc times cannot be represented in local time in certain timezones. E.g. 0001-01-01 12:00:00 AM cannot - // be represented in any timezones with a negative offset from Utc. We throw an ArgumentException in that case. - managedLocalDTO = managedUtcDTO.ToLocalTime(true); - } - } // class DateTimeOffsetMarshaler - -#endif // FEATURE_COMINTEROP - #if FEATURE_COMINTEROP - internal static class HStringMarshaler - { - // Slow-path, which requires making a copy of the managed string into the resulting HSTRING - internal static unsafe IntPtr ConvertToNative(string managed) - { - if (!Environment.IsWinRTSupported) - throw new PlatformNotSupportedException(SR.PlatformNotSupported_WinRT); - if (managed == null) - throw new ArgumentNullException(); // We don't have enough information to get the argument name - - IntPtr hstring; - int hrCreate = System.Runtime.InteropServices.WindowsRuntime.UnsafeNativeMethods.WindowsCreateString(managed, managed.Length, &hstring); - Marshal.ThrowExceptionForHR(hrCreate, new IntPtr(-1)); - return hstring; - } - - // Fast-path, which creates a reference over a pinned managed string. This may only be used if the - // pinned string and HSTRING_HEADER will outlive the HSTRING produced (for instance, as an in parameter). - // - // 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. - internal static unsafe IntPtr ConvertToNativeReference(string managed, - [Out] HSTRING_HEADER* hstringHeader) - { - if (!Environment.IsWinRTSupported) - throw new PlatformNotSupportedException(SR.PlatformNotSupported_WinRT); - if (managed == null) - throw new ArgumentNullException(); // We don't have enough information to get the argument name - - // The string must also be pinned by the caller to ConvertToNativeReference, which also owns - // the HSTRING_HEADER. - fixed (char* pManaged = managed) - { - IntPtr hstring; - int hrCreate = System.Runtime.InteropServices.WindowsRuntime.UnsafeNativeMethods.WindowsCreateStringReference(pManaged, managed.Length, hstringHeader, &hstring); - Marshal.ThrowExceptionForHR(hrCreate, new IntPtr(-1)); - return hstring; - } - } - - internal static string ConvertToManaged(IntPtr hstring) - { - if (!Environment.IsWinRTSupported) - { - throw new PlatformNotSupportedException(SR.PlatformNotSupported_WinRT); - } - - return WindowsRuntimeMarshal.HStringToString(hstring); - } - - internal static void ClearNative(IntPtr hstring) - { - Debug.Assert(Environment.IsWinRTSupported); - - if (hstring != IntPtr.Zero) - { - System.Runtime.InteropServices.WindowsRuntime.UnsafeNativeMethods.WindowsDeleteString(hstring); - } - } - } // class HStringMarshaler internal static class ObjectMarshaler { @@ -705,32 +607,9 @@ namespace System.StubHelpers [DllImport(RuntimeHelpers.QCall)] internal static extern void ClearNative(IntPtr pUnk); - - [MethodImpl(MethodImplOptions.InternalCall)] - internal static extern object ConvertToManagedWithoutUnboxing(IntPtr pNative); } // class InterfaceMarshaler #endif // FEATURE_COMINTEROP -#if FEATURE_COMINTEROP - internal static class UriMarshaler - { - [MethodImpl(MethodImplOptions.InternalCall)] - internal static extern string GetRawUriFromNative(IntPtr pUri); - - [MethodImpl(MethodImplOptions.InternalCall)] - internal static extern unsafe IntPtr CreateNativeUriInstanceHelper(char* rawUri, int strLen); - - internal static unsafe IntPtr CreateNativeUriInstance(string rawUri) - { - fixed (char* pManaged = rawUri) - { - return CreateNativeUriInstanceHelper(pManaged, rawUri.Length); - } - } - } // class InterfaceMarshaler - -#endif // FEATURE_COMINTEROP - internal static class MngdNativeArrayMarshaler { // Needs to match exactly with MngdNativeArrayMarshaler in ilmarshalers.h @@ -812,165 +691,6 @@ namespace System.StubHelpers [MethodImpl(MethodImplOptions.InternalCall)] internal static extern void ClearNative(IntPtr pMarshalState, ref object pManagedHome, IntPtr pNativeHome); } // class MngdSafeArrayMarshaler - - internal static class MngdHiddenLengthArrayMarshaler - { - [MethodImpl(MethodImplOptions.InternalCall)] - internal static extern void CreateMarshaler(IntPtr pMarshalState, IntPtr pMT, IntPtr cbElementSize, ushort vt, IntPtr pManagedMarshaler); - - [MethodImpl(MethodImplOptions.InternalCall)] - internal static extern void ConvertSpaceToNative(IntPtr pMarshalState, ref object pManagedHome, IntPtr pNativeHome); - - [MethodImpl(MethodImplOptions.InternalCall)] - internal static extern void ConvertContentsToNative(IntPtr pMarshalState, ref object pManagedHome, IntPtr pNativeHome); - - internal static unsafe void ConvertContentsToNative_DateTime(ref DateTimeOffset[]? managedArray, IntPtr pNativeHome) - { - if (managedArray != null) - { - DateTimeNative* nativeBuffer = *(DateTimeNative**)pNativeHome; - for (int i = 0; i < managedArray.Length; i++) - { - DateTimeOffsetMarshaler.ConvertToNative(ref managedArray[i], out nativeBuffer[i]); - } - } - } - - internal static unsafe void ConvertContentsToNative_Type(ref System.Type[]? managedArray, IntPtr pNativeHome) - { - if (managedArray != null) - { - TypeNameNative* nativeBuffer = *(TypeNameNative**)pNativeHome; - for (int i = 0; i < managedArray.Length; i++) - { - SystemTypeMarshaler.ConvertToNative(managedArray[i], &nativeBuffer[i]); - } - } - } - - internal static unsafe void ConvertContentsToNative_Exception(ref Exception[]? managedArray, IntPtr pNativeHome) - { - if (managedArray != null) - { - int* nativeBuffer = *(int**)pNativeHome; - for (int i = 0; i < managedArray.Length; i++) - { - nativeBuffer[i] = HResultExceptionMarshaler.ConvertToNative(managedArray[i]); - } - } - } - - internal static unsafe void ConvertContentsToNative_Nullable(ref T?[]? managedArray, IntPtr pNativeHome) - where T : struct - { - if (managedArray != null) - { - IntPtr* nativeBuffer = *(IntPtr**)pNativeHome; - for (int i = 0; i < managedArray.Length; i++) - { - nativeBuffer[i] = NullableMarshaler.ConvertToNative(ref managedArray[i]); - } - } - } - - internal static unsafe void ConvertContentsToNative_KeyValuePair(ref KeyValuePair[]? managedArray, IntPtr pNativeHome) - { - if (managedArray != null) - { - IntPtr* nativeBuffer = *(IntPtr**)pNativeHome; - for (int i = 0; i < managedArray.Length; i++) - { - nativeBuffer[i] = KeyValuePairMarshaler.ConvertToNative(ref managedArray[i]); - } - } - } - - [MethodImpl(MethodImplOptions.InternalCall)] - internal static extern void ConvertSpaceToManaged(IntPtr pMarshalState, ref object pManagedHome, IntPtr pNativeHome, int elementCount); - - [MethodImpl(MethodImplOptions.InternalCall)] - internal static extern void ConvertContentsToManaged(IntPtr pMarshalState, ref object pManagedHome, IntPtr pNativeHome); - - internal static unsafe void ConvertContentsToManaged_DateTime(ref DateTimeOffset[]? managedArray, IntPtr pNativeHome) - { - if (managedArray != null) - { - DateTimeNative* nativeBuffer = *(DateTimeNative**)pNativeHome; - for (int i = 0; i < managedArray.Length; i++) - { - DateTimeOffsetMarshaler.ConvertToManaged(out managedArray[i], ref nativeBuffer[i]); - } - } - } - - internal static unsafe void ConvertContentsToManaged_Type(ref System.Type?[]? managedArray, IntPtr pNativeHome) - { - if (managedArray != null) - { - TypeNameNative* nativeBuffer = *(TypeNameNative**)pNativeHome; - for (int i = 0; i < managedArray.Length; i++) - { - SystemTypeMarshaler.ConvertToManaged(&nativeBuffer[i], ref managedArray[i]); - } - } - } - - internal static unsafe void ConvertContentsToManaged_Exception(ref Exception?[]? managedArray, IntPtr pNativeHome) - { - if (managedArray != null) - { - int* nativeBuffer = *(int**)pNativeHome; - for (int i = 0; i < managedArray.Length; i++) - { - managedArray[i] = HResultExceptionMarshaler.ConvertToManaged(nativeBuffer[i]); - } - } - } - - internal static unsafe void ConvertContentsToManaged_Nullable(ref T?[]? managedArray, IntPtr pNativeHome) - where T : struct - { - if (managedArray != null) - { - IntPtr* nativeBuffer = *(IntPtr**)pNativeHome; - for (int i = 0; i < managedArray.Length; i++) - { - managedArray[i] = NullableMarshaler.ConvertToManaged(nativeBuffer[i]); - } - } - } - - internal static unsafe void ConvertContentsToManaged_KeyValuePair(ref KeyValuePair[]? managedArray, IntPtr pNativeHome) - { - if (managedArray != null) - { - IntPtr* nativeBuffer = *(IntPtr**)pNativeHome; - for (int i = 0; i < managedArray.Length; i++) - { - managedArray[i] = KeyValuePairMarshaler.ConvertToManaged(nativeBuffer[i]); - } - } - } - - [MethodImpl(MethodImplOptions.InternalCall)] - internal static extern void ClearNativeContents(IntPtr pMarshalState, IntPtr pNativeHome, int cElements); - - internal static unsafe void ClearNativeContents_Type(IntPtr pNativeHome, int cElements) - { - Debug.Assert(Environment.IsWinRTSupported); - - TypeNameNative* pNativeTypeArray = *(TypeNameNative**)pNativeHome; - if (pNativeTypeArray != null) - { - for (int i = 0; i < cElements; ++i) - { - SystemTypeMarshaler.ClearNative(pNativeTypeArray); - pNativeTypeArray++; - } - } - } - } // class MngdHiddenLengthArrayMarshaler - #endif // FEATURE_COMINTEROP internal static class MngdRefCustomMarshaler @@ -1354,210 +1074,6 @@ namespace System.StubHelpers } } // struct AsAnyMarshaler -#if FEATURE_COMINTEROP - internal static class NullableMarshaler - { - internal static IntPtr ConvertToNative(ref T? pManaged) where T : struct - { - if (pManaged.HasValue) - { - object impl = IReferenceFactory.CreateIReference(pManaged); - return Marshal.GetComInterfaceForObject(impl, typeof(IReference)); - } - else - { - return IntPtr.Zero; - } - } - - internal static void ConvertToManagedRetVoid(IntPtr pNative, ref T? retObj) where T : struct - { - retObj = ConvertToManaged(pNative); - } - - internal static T? ConvertToManaged(IntPtr pNative) where T : struct - { - if (pNative != IntPtr.Zero) - { - object wrapper = InterfaceMarshaler.ConvertToManagedWithoutUnboxing(pNative); - return (T?)CLRIReferenceImpl.UnboxHelper(wrapper); - } - else - { - return default; - } - } - } // class NullableMarshaler - - // Corresponds to Windows.UI.Xaml.Interop.TypeName - [StructLayout(LayoutKind.Sequential)] - internal struct TypeNameNative - { - internal IntPtr typeName; // HSTRING - internal TypeKind typeKind; // TypeKind enum - } - - // Corresponds to Windows.UI.Xaml.TypeSource - internal enum TypeKind - { - Primitive, - Metadata, - Projection - } - - internal static class WinRTTypeNameConverter - { - [MethodImpl(MethodImplOptions.InternalCall)] - internal static extern string ConvertToWinRTTypeName(System.Type managedType, out bool isPrimitive); - - [MethodImpl(MethodImplOptions.InternalCall)] - internal static extern System.Type GetTypeFromWinRTTypeName(string typeName, out bool isPrimitive); - } - - internal static class SystemTypeMarshaler - { - internal static unsafe void ConvertToNative(System.Type managedType, TypeNameNative* pNativeType) - { - if (!Environment.IsWinRTSupported) - { - throw new PlatformNotSupportedException(SR.PlatformNotSupported_WinRT); - } - - string typeName; - if (managedType != null) - { - if (managedType.GetType() != typeof(System.RuntimeType)) - { // The type should be exactly System.RuntimeType (and not its child System.ReflectionOnlyType, or other System.Type children) - throw new ArgumentException(SR.Format(SR.Argument_WinRTSystemRuntimeType, managedType.GetType())); - } - - string winrtTypeName = WinRTTypeNameConverter.ConvertToWinRTTypeName(managedType, out bool isPrimitive); - if (winrtTypeName != null) - { - // Must be a WinRT type, either in a WinMD or a Primitive - typeName = winrtTypeName; - if (isPrimitive) - pNativeType->typeKind = TypeKind.Primitive; - else - pNativeType->typeKind = TypeKind.Metadata; - } - else - { - // Custom .NET type - typeName = managedType.AssemblyQualifiedName!; - pNativeType->typeKind = TypeKind.Projection; - } - } - else - { // Marshal null as empty string + Projection - typeName = ""; - pNativeType->typeKind = TypeKind.Projection; - } - - int hrCreate = System.Runtime.InteropServices.WindowsRuntime.UnsafeNativeMethods.WindowsCreateString(typeName, typeName.Length, &pNativeType->typeName); - Marshal.ThrowExceptionForHR(hrCreate, new IntPtr(-1)); - } - - internal static unsafe void ConvertToManaged(TypeNameNative* pNativeType, ref System.Type? managedType) - { - if (!Environment.IsWinRTSupported) - { - throw new PlatformNotSupportedException(SR.PlatformNotSupported_WinRT); - } - - string typeName = WindowsRuntimeMarshal.HStringToString(pNativeType->typeName); - if (string.IsNullOrEmpty(typeName)) - { - managedType = null; - return; - } - - if (pNativeType->typeKind == TypeKind.Projection) - { - managedType = Type.GetType(typeName, /* throwOnError = */ true); - } - else - { - managedType = WinRTTypeNameConverter.GetTypeFromWinRTTypeName(typeName, out bool isPrimitive); - - // TypeSource must match - if (isPrimitive != (pNativeType->typeKind == TypeKind.Primitive)) - throw new ArgumentException(SR.Argument_Unexpected_TypeSource); - } - } - - internal static unsafe void ClearNative(TypeNameNative* pNativeType) - { - Debug.Assert(Environment.IsWinRTSupported); - - if (pNativeType->typeName != IntPtr.Zero) - { - System.Runtime.InteropServices.WindowsRuntime.UnsafeNativeMethods.WindowsDeleteString(pNativeType->typeName); - } - } - } // class SystemTypeMarshaler - - // For converting WinRT's Windows.Foundation.HResult into System.Exception and vice versa. - internal static class HResultExceptionMarshaler - { - internal static int ConvertToNative(Exception ex) - { - if (!Environment.IsWinRTSupported) - { - throw new PlatformNotSupportedException(SR.PlatformNotSupported_WinRT); - } - - if (ex == null) - return 0; // S_OK; - - return ex.HResult; - } - - internal static Exception? ConvertToManaged(int hr) - { - if (!Environment.IsWinRTSupported) - { - throw new PlatformNotSupportedException(SR.PlatformNotSupported_WinRT); - } - - Exception? e = null; - if (hr < 0) - { - e = StubHelpers.InternalGetCOMHRExceptionObject(hr, IntPtr.Zero, null, /* fForWinRT */ true); - } - - // 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. - 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 - - internal static class KeyValuePairMarshaler - { - internal static IntPtr ConvertToNative([In] ref KeyValuePair pair) - { - IKeyValuePair impl = new CLRIKeyValuePairImpl(ref pair); - return Marshal.GetComInterfaceForObject(impl, typeof(IKeyValuePair)); - } - - internal static KeyValuePair ConvertToManaged(IntPtr pInsp) - { - object obj = InterfaceMarshaler.ConvertToManagedWithoutUnboxing(pInsp); - - IKeyValuePair pair = (IKeyValuePair)obj; - return new KeyValuePair(pair.Key, pair.Value); - } - - // Called from COMInterfaceMarshaler - internal static object ConvertToManagedBox(IntPtr pInsp) - { - return (object)ConvertToManaged(pInsp); - } - } // class KeyValuePairMarshaler - -#endif // FEATURE_COMINTEROP - [StructLayout(LayoutKind.Sequential)] internal struct NativeVariant { @@ -1726,20 +1242,13 @@ namespace System.StubHelpers #if FEATURE_COMINTEROP internal static Exception GetCOMHRExceptionObject(int hr, IntPtr pCPCMD, object pThis) { - Exception ex = InternalGetCOMHRExceptionObject(hr, pCPCMD, pThis, false); - ex.InternalPreserveStackTrace(); - return ex; - } - - internal static Exception GetCOMHRExceptionObject_WinRT(int hr, IntPtr pCPCMD, object pThis) - { - Exception ex = InternalGetCOMHRExceptionObject(hr, pCPCMD, pThis, true); + Exception ex = InternalGetCOMHRExceptionObject(hr, pCPCMD, pThis); ex.InternalPreserveStackTrace(); return ex; } [MethodImpl(MethodImplOptions.InternalCall)] - internal static extern Exception InternalGetCOMHRExceptionObject(int hr, IntPtr pCPCMD, object? pThis, bool fForWinRT); + internal static extern Exception InternalGetCOMHRExceptionObject(int hr, IntPtr pCPCMD, object? pThis); #endif // FEATURE_COMINTEROP @@ -1776,34 +1285,6 @@ namespace System.StubHelpers #if FEATURE_COMINTEROP [MethodImpl(MethodImplOptions.InternalCall)] internal static extern IntPtr GetCOMIPFromRCW(object objSrc, IntPtr pCPCMD, out IntPtr ppTarget, out bool pfNeedsRelease); - - [MethodImpl(MethodImplOptions.InternalCall)] - internal static extern IntPtr GetCOMIPFromRCW_WinRT(object objSrc, IntPtr pCPCMD, out IntPtr ppTarget); - - [MethodImpl(MethodImplOptions.InternalCall)] - internal static extern IntPtr GetCOMIPFromRCW_WinRTSharedGeneric(object objSrc, IntPtr pCPCMD, out IntPtr ppTarget); - - [MethodImpl(MethodImplOptions.InternalCall)] - internal static extern IntPtr GetCOMIPFromRCW_WinRTDelegate(object objSrc, IntPtr pCPCMD, out IntPtr ppTarget); - - [MethodImpl(MethodImplOptions.InternalCall)] - internal static extern bool ShouldCallWinRTInterface(object objSrc, IntPtr pCPCMD); - - [MethodImpl(MethodImplOptions.InternalCall)] - internal static extern Delegate GetTargetForAmbiguousVariantCall(object objSrc, IntPtr pMT, out bool fUseString); - - [MethodImpl(MethodImplOptions.InternalCall)] - internal static extern IntPtr GetDelegateInvokeMethod(Delegate pThis); - - [MethodImpl(MethodImplOptions.InternalCall)] - internal static extern object GetWinRTFactoryObject(IntPtr pCPCMD); - - [MethodImpl(MethodImplOptions.InternalCall)] - internal static extern IntPtr GetWinRTFactoryReturnValue(object pThis, IntPtr pCtorEntry); - - [MethodImpl(MethodImplOptions.InternalCall)] - internal static extern IntPtr GetOuterInspectable(object pThis, IntPtr pCtorMD); - #endif // FEATURE_COMINTEROP //------------------------------------------------------- diff --git a/src/coreclr/src/System.Private.CoreLib/src/System/Threading/SynchronizationContext.Uap.cs b/src/coreclr/src/System.Private.CoreLib/src/System/Threading/SynchronizationContext.Uap.cs deleted file mode 100644 index 67c6af8..0000000 --- a/src/coreclr/src/System.Private.CoreLib/src/System/Threading/SynchronizationContext.Uap.cs +++ /dev/null @@ -1,81 +0,0 @@ -// 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.Runtime.InteropServices; -using System.Runtime.CompilerServices; -using System.Reflection; -using System.Diagnostics; - -namespace System.Threading -{ - public partial class SynchronizationContext - { - public static SynchronizationContext? Current - { - get - { - SynchronizationContext? context = Thread.CurrentThread._synchronizationContext; - - if (context == null && ApplicationModel.IsUap) - context = GetWinRTContext(); - - return context; - } - } - - private static SynchronizationContext? GetWinRTContext() - { - Debug.Assert(Environment.IsWinRTSupported); - Debug.Assert(ApplicationModel.IsUap); - - // - // We call into the VM to get the dispatcher. This is because: - // - // a) We cannot call the WinRT APIs directly from mscorlib, because we don't have the fancy projections here. - // b) We cannot call into System.Runtime.WindowsRuntime here, because we don't want to load that assembly - // into processes that don't need it (for performance reasons). - // - // So, we check the VM to see if the current thread has a dispatcher; if it does, we pass that along to - // System.Runtime.WindowsRuntime to get a corresponding SynchronizationContext. - // - object? dispatcher = GetWinRTDispatcherForCurrentThread(); - if (dispatcher != null) - return GetWinRTSynchronizationContext(dispatcher); - - return null; - } - - private static Func? s_createSynchronizationContextDelegate; - - // This is necessary because linker can't add new assemblies to the closure when recognizing Type.GetType - // so even though the GetType call below is analyzable, the PreserveDependency is still necessary to actually include - // the assembly in the trimmed closure. - [PreserveDependency("Create", "System.Threading.WinRTSynchronizationContextFactory", "System.Runtime.WindowsRuntime")] - private static SynchronizationContext GetWinRTSynchronizationContext(object dispatcher) - { - // - // Since we can't directly reference System.Runtime.WindowsRuntime from mscorlib, we have to get the factory via reflection. - // It would be better if we could just implement WinRTSynchronizationContextFactory in mscorlib, but we can't, because - // we can do very little with WinRT stuff in mscorlib. - // - Func? createSynchronizationContextDelegate = s_createSynchronizationContextDelegate; - if (createSynchronizationContextDelegate == null) - { - Type factoryType = Type.GetType("System.Threading.WinRTSynchronizationContextFactory, System.Runtime.WindowsRuntime", throwOnError: true)!; - - // Create an instance delegate for the Create static method - MethodInfo createMethodInfo = factoryType.GetMethod("Create", BindingFlags.Static | BindingFlags.NonPublic | BindingFlags.Public)!; - createSynchronizationContextDelegate = (Func)Delegate.CreateDelegate(typeof(Func), createMethodInfo); - - s_createSynchronizationContextDelegate = createSynchronizationContextDelegate; - } - - return createSynchronizationContextDelegate(dispatcher); - } - - [DllImport(RuntimeHelpers.QCall, CharSet = CharSet.Unicode)] - [return: MarshalAs(UnmanagedType.Interface)] - private static extern object? GetWinRTDispatcherForCurrentThread(); - } -} diff --git a/src/coreclr/src/System.Private.CoreLib/src/System/Threading/Tasks/AsyncCausalityTracer.cs b/src/coreclr/src/System.Private.CoreLib/src/System/Threading/Tasks/AsyncCausalityTracer.cs deleted file mode 100644 index 80e2e7c..0000000 --- a/src/coreclr/src/System.Private.CoreLib/src/System/Threading/Tasks/AsyncCausalityTracer.cs +++ /dev/null @@ -1,192 +0,0 @@ -// 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 System.Runtime.CompilerServices; -using System.Runtime.InteropServices.WindowsRuntime; -using WFD = Windows.Foundation.Diagnostics; - -namespace System.Threading.Tasks -{ - internal static class AsyncCausalityTracer - { - internal static void EnableToETW(bool enabled) - { - if (enabled) - f_LoggingOn |= Loggers.ETW; - else - f_LoggingOn &= ~Loggers.ETW; - } - - internal static bool LoggingOn => f_LoggingOn != 0; - - // s_PlatformId = {4B0171A6-F3D0-41A0-9B33-02550652B995} - private static readonly Guid s_PlatformId = new Guid(0x4B0171A6, 0xF3D0, 0x41A0, 0x9B, 0x33, 0x02, 0x55, 0x06, 0x52, 0xB9, 0x95); - - // Indicates this information comes from the BCL Library - private const WFD.CausalitySource s_CausalitySource = WFD.CausalitySource.Library; - - private static readonly WFD.IAsyncCausalityTracerStatics s_TracerFactory = null!; - - // The loggers that this Tracer knows about. - [Flags] - private enum Loggers : byte - { - CausalityTracer = 1, - ETW = 2 - } - - - // We receive the actual value for these as a callback - private static Loggers f_LoggingOn; // assumes false by default - - // The precise static constructor will run first time somebody attempts to access this class -#pragma warning disable CA1810 - static AsyncCausalityTracer() -#pragma warning restore CA1810 - { - if (!Environment.IsWinRTSupported) return; - - // COM Class Id - const string ClassId = "Windows.Foundation.Diagnostics.AsyncCausalityTracer"; - - // COM Interface GUID {50850B26-267E-451B-A890-AB6A370245EE} - Guid guid = new Guid(0x50850B26, 0x267E, 0x451B, 0xA8, 0x90, 0XAB, 0x6A, 0x37, 0x02, 0x45, 0xEE); - - object? factory = null; - - try - { - int hresult = Microsoft.Win32.UnsafeNativeMethods.RoGetActivationFactory(ClassId, ref guid, out factory); - - if (hresult < 0 || factory == null) return; // This prevents having an exception thrown in case IAsyncCausalityTracerStatics isn't registered. - - s_TracerFactory = (WFD.IAsyncCausalityTracerStatics)factory; - - EventRegistrationToken token = s_TracerFactory.add_TracingStatusChanged(new EventHandler(TracingStatusChangedHandler)); - Debug.Assert(token != default, "EventRegistrationToken is null"); - } - catch (Exception ex) - { - // Although catching generic Exception is not recommended, this file is one exception - // since we don't want to propagate any kind of exception to the user since all we are - // doing here depends on internal state. - LogAndDisable(ex); - } - } - - private static void TracingStatusChangedHandler(object? sender, WFD.TracingStatusChangedEventArgs args) - { - if (args.Enabled) - f_LoggingOn |= Loggers.CausalityTracer; - else - f_LoggingOn &= ~Loggers.CausalityTracer; - } - - // - // The TraceXXX methods should be called only if LoggingOn property returned true - // - [MethodImpl(MethodImplOptions.NoInlining)] // Tracking is slow path. Disable inlining for it. - internal static void TraceOperationCreation(Task task, string operationName) - { - try - { - int taskId = task.Id; - if ((f_LoggingOn & Loggers.ETW) != 0) - TplEventSource.Log.TraceOperationBegin(taskId, operationName, RelatedContext: 0); - if ((f_LoggingOn & Loggers.CausalityTracer) != 0) - s_TracerFactory.TraceOperationCreation(WFD.CausalityTraceLevel.Required, s_CausalitySource, s_PlatformId, GetOperationId((uint)taskId), operationName, relatedContext: 0); - } - catch (Exception ex) - { - // view function comment - LogAndDisable(ex); - } - } - - [MethodImpl(MethodImplOptions.NoInlining)] - internal static void TraceOperationCompletion(Task task, AsyncCausalityStatus status) - { - try - { - int taskId = task.Id; - if ((f_LoggingOn & Loggers.ETW) != 0) - TplEventSource.Log.TraceOperationEnd(taskId, status); - if ((f_LoggingOn & Loggers.CausalityTracer) != 0) - s_TracerFactory.TraceOperationCompletion(WFD.CausalityTraceLevel.Required, s_CausalitySource, s_PlatformId, GetOperationId((uint)taskId), (WFD.AsyncCausalityStatus)status); - } - catch (Exception ex) - { - // view function comment - LogAndDisable(ex); - } - } - - [MethodImpl(MethodImplOptions.NoInlining)] - internal static void TraceOperationRelation(Task task, CausalityRelation relation) - { - try - { - int taskId = task.Id; - if ((f_LoggingOn & Loggers.ETW) != 0) - TplEventSource.Log.TraceOperationRelation(taskId, relation); - if ((f_LoggingOn & Loggers.CausalityTracer) != 0) - s_TracerFactory.TraceOperationRelation(WFD.CausalityTraceLevel.Important, s_CausalitySource, s_PlatformId, GetOperationId((uint)taskId), (WFD.CausalityRelation)relation); - } - catch (Exception ex) - { - // view function comment - LogAndDisable(ex); - } - } - - [MethodImpl(MethodImplOptions.NoInlining)] - internal static void TraceSynchronousWorkStart(Task task, CausalitySynchronousWork work) - { - try - { - int taskId = task.Id; - if ((f_LoggingOn & Loggers.ETW) != 0) - TplEventSource.Log.TraceSynchronousWorkBegin(taskId, work); - if ((f_LoggingOn & Loggers.CausalityTracer) != 0) - s_TracerFactory.TraceSynchronousWorkStart(WFD.CausalityTraceLevel.Required, s_CausalitySource, s_PlatformId, GetOperationId((uint)taskId), (WFD.CausalitySynchronousWork)work); - } - catch (Exception ex) - { - // view function comment - LogAndDisable(ex); - } - } - - [MethodImpl(MethodImplOptions.NoInlining)] - internal static void TraceSynchronousWorkCompletion(CausalitySynchronousWork work) - { - try - { - if ((f_LoggingOn & Loggers.ETW) != 0) - TplEventSource.Log.TraceSynchronousWorkEnd(work); - if ((f_LoggingOn & Loggers.CausalityTracer) != 0) - s_TracerFactory.TraceSynchronousWorkCompletion(WFD.CausalityTraceLevel.Required, s_CausalitySource, (WFD.CausalitySynchronousWork)work); - } - catch (Exception ex) - { - // view function comment - LogAndDisable(ex); - } - } - - // fix for 796185: leaking internal exceptions to customers, - // we should catch and log exceptions but never propagate them. - private static void LogAndDisable(Exception ex) - { - f_LoggingOn = 0; - Debugger.Log(0, "AsyncCausalityTracer", ex.ToString()); - } - - private static ulong GetOperationId(uint taskId) - { - return (((ulong)Thread.GetDomainID()) << 32) + taskId; - } - } -} diff --git a/src/coreclr/src/System.Private.CoreLib/src/System/Threading/Tasks/IAsyncCausalityTracerStatics.cs b/src/coreclr/src/System.Private.CoreLib/src/System/Threading/Tasks/IAsyncCausalityTracerStatics.cs deleted file mode 100644 index ab859a0..0000000 --- a/src/coreclr/src/System.Private.CoreLib/src/System/Threading/Tasks/IAsyncCausalityTracerStatics.cs +++ /dev/null @@ -1,98 +0,0 @@ -// 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; -using System.Runtime.InteropServices; -using System.Runtime.InteropServices.WindowsRuntime; - -// Windows.Foundation.Diagnostics cannot be referenced from managed code because -// they're hidden by the metadata adapter. We redeclare the interfaces manually -// to be able to talk to native WinRT objects. - -namespace Windows.Foundation.Diagnostics -{ - [ComImport] - [Guid("50850B26-267E-451B-A890-AB6A370245EE")] - [WindowsRuntimeImport] - internal interface IAsyncCausalityTracerStatics - { - void TraceOperationCreation(CausalityTraceLevel traceLevel, CausalitySource source, Guid platformId, ulong operationId, string operationName, ulong relatedContext); - void TraceOperationCompletion(CausalityTraceLevel traceLevel, CausalitySource source, Guid platformId, ulong operationId, AsyncCausalityStatus status); - void TraceOperationRelation(CausalityTraceLevel traceLevel, CausalitySource source, Guid platformId, ulong operationId, CausalityRelation relation); - void TraceSynchronousWorkStart(CausalityTraceLevel traceLevel, CausalitySource source, Guid platformId, ulong operationId, CausalitySynchronousWork work); - void TraceSynchronousWorkCompletion(CausalityTraceLevel traceLevel, CausalitySource source, CausalitySynchronousWork work); - // These next 2 functions could've been represented as an event except that the EventRegistrationToken wasn't being propagated to WinRT - EventRegistrationToken add_TracingStatusChanged(System.EventHandler eventHandler); - void remove_TracingStatusChanged(EventRegistrationToken token); - } - - [ComImport] - [Guid("410B7711-FF3B-477F-9C9A-D2EFDA302DC3")] - [WindowsRuntimeImport] - internal interface ITracingStatusChangedEventArgs - { - bool Enabled { get; } - CausalityTraceLevel TraceLevel { get; } - } - - // We need this dummy class to satisfy a QI when the TracingStatusChangedHandler - // after being stored in a GIT cookie and then called by the WinRT API. This usually - // happens when calling a Managed WinMD which access this feature. - [ComImport] - [Guid("410B7711-FF3B-477F-9C9A-D2EFDA302DC3")] - [WindowsRuntimeImport] - internal sealed class TracingStatusChangedEventArgs : ITracingStatusChangedEventArgs - { - public extern bool Enabled - { - [MethodImpl(MethodImplOptions.InternalCall)] - get; - } - - public extern CausalityTraceLevel TraceLevel - { - [MethodImpl(MethodImplOptions.InternalCall)] - get; - } - } - - internal enum CausalityRelation - { - AssignDelegate, - Join, - Choice, - Cancel, - Error - } - - internal enum CausalitySource - { - Application, - Library, - System - } - - internal enum CausalitySynchronousWork - { - CompletionNotification, - ProgressNotification, - Execution - } - - internal enum CausalityTraceLevel - { - Required, - Important, - Verbose - } - - internal enum AsyncCausalityStatus - { - Canceled = 2, - Completed = 1, - Error = 3, - Started = 0 - } -} diff --git a/src/coreclr/src/System.Private.CoreLib/src/System/Type.CoreCLR.cs b/src/coreclr/src/System.Private.CoreLib/src/System/Type.CoreCLR.cs index 79a6710..22325c2 100644 --- a/src/coreclr/src/System.Private.CoreLib/src/System/Type.CoreCLR.cs +++ b/src/coreclr/src/System.Private.CoreLib/src/System/Type.CoreCLR.cs @@ -113,30 +113,6 @@ namespace System [MethodImpl(MethodImplOptions.InternalCall)] public static extern Type GetTypeFromHandle(RuntimeTypeHandle handle); -#if FEATURE_COMINTEROP - internal bool IsWindowsRuntimeObject - { - get { return IsWindowsRuntimeObjectImpl(); } - } - - internal bool IsExportedToWindowsRuntime - { - get { return IsExportedToWindowsRuntimeImpl(); } - } - - // Protected routine to determine if this class represents a Windows Runtime object - internal virtual bool IsWindowsRuntimeObjectImpl() - { - throw new NotImplementedException(); - } - - // Determines if this type is exported to WinRT (i.e. is an activatable class in a managed .winmd) - internal virtual bool IsExportedToWindowsRuntimeImpl() - { - throw new NotImplementedException(); - } -#endif // FEATURE_COMINTEROP - [Intrinsic] [MethodImpl(MethodImplOptions.InternalCall)] public static extern bool operator ==(Type? left, Type? right); diff --git a/src/coreclr/src/System.Private.CoreLib/src/System/__ComObject.cs b/src/coreclr/src/System.Private.CoreLib/src/System/__ComObject.cs index d49e228..38b88b6 100644 --- a/src/coreclr/src/System.Private.CoreLib/src/System/__ComObject.cs +++ b/src/coreclr/src/System.Private.CoreLib/src/System/__ComObject.cs @@ -4,7 +4,6 @@ using System.Collections; using System.Runtime.InteropServices; -using System.Runtime.InteropServices.WindowsRuntime; using System.Reflection; namespace System @@ -25,27 +24,6 @@ namespace System } /// - /// Overrides ToString() to make sure we call to IStringable if the COM - /// object implements it in the case of weakly typed RCWs - /// - public override string ToString() - { - // Only do the IStringable cast when running under AppX for better compat - // Otherwise we could do a IStringable cast in classic apps which could introduce - // a thread transition which would lead to deadlock. - if (ApplicationModel.IsUap) - { - // Check whether the type implements IStringable. - if (this is IStringable stringableType) - { - return stringableType.ToString(); - } - } - - return base.ToString()!; - } - - /// /// Retrieves the data associated with the specified if such data exists. /// internal object? GetData(object key) diff --git a/src/coreclr/src/binder/applicationcontext.cpp b/src/coreclr/src/binder/applicationcontext.cpp index eba617b..e91ceb6 100644 --- a/src/coreclr/src/binder/applicationcontext.cpp +++ b/src/coreclr/src/binder/applicationcontext.cpp @@ -260,10 +260,8 @@ namespace BINDER_SPACE // GCC complains if we create SStrings inline as part of a function call SString sNiDll(W(".ni.dll")); SString sNiExe(W(".ni.exe")); - SString sNiWinmd(W(".ni.winmd")); SString sDll(W(".dll")); SString sExe(W(".exe")); - SString sWinmd(W(".winmd")); if (fileName.EndsWithCaseInsensitive(sNiDll) || fileName.EndsWithCaseInsensitive(sNiExe)) @@ -271,20 +269,11 @@ namespace BINDER_SPACE simpleName.Set(fileName, iSimpleNameStart, fileName.End() - 7); isNativeImage = true; } - else if (fileName.EndsWithCaseInsensitive(sNiWinmd)) - { - simpleName.Set(fileName, iSimpleNameStart, fileName.End() - 9); - isNativeImage = true; - } else if (fileName.EndsWithCaseInsensitive(sDll) || fileName.EndsWithCaseInsensitive(sExe)) { simpleName.Set(fileName, iSimpleNameStart, fileName.End() - 4); } - else if (fileName.EndsWithCaseInsensitive(sWinmd)) - { - simpleName.Set(fileName, iSimpleNameStart, fileName.End() - 6); - } else { // Invalid filename diff --git a/src/coreclr/src/binder/assemblybinder.cpp b/src/coreclr/src/binder/assemblybinder.cpp index 362c2b8..0a68dae 100644 --- a/src/coreclr/src/binder/assemblybinder.cpp +++ b/src/coreclr/src/binder/assemblybinder.cpp @@ -1016,7 +1016,7 @@ namespace BINDER_SPACE // Single-file bundle contents take precedence over TPA. // The list of bundled assemblies is contained in the bundle manifest, and NOT in the TPA. // Therefore the bundle is first probed using the assembly's simple name. - // If found, the assembly is loaded from the bundle. + // If found, the assembly is loaded from the bundle. if (Bundle::AppIsBundle()) { // Search Assembly.ni.dll, then Assembly.dll @@ -1051,7 +1051,7 @@ namespace BINDER_SPACE if (TestCandidateRefMatchesDef(pRequestedAssemblyName, pTPAAssembly->GetAssemblyName(), true /*tpaListAssembly*/)) { - // We have found the requested assembly match in the bundle with validation of the full-qualified name. + // We have found the requested assembly match in the bundle with validation of the full-qualified name. // Bind to it. pBindResult->SetResult(pTPAAssembly); GO_WITH_HRESULT(S_OK); @@ -1239,24 +1239,7 @@ namespace BINDER_SPACE if (pIMetaDataAssemblyImport == NULL && pNativePEImage != NULL) { - // The native image doesn't contain metadata. Currently this is only supported for Windows.ni.winmd. - // While loading Windows.winmd, CLRPrivBinderWinRT::GetAssemblyAndTryFindNativeImage should have passed - // in a non-NULL szMDAssemblyPath, where we can load metadata from. If szMDAssemblyPath is NULL, - // it indicates that the app is trying to load a non-WinMD assembly named Windows (it's possible - // that the app happens to contain an assembly Windows.dll). To handle this case properly, we - // return a file-not-found error, so the caller can continues it's search. - if (szMDAssemblyPath == NULL) - { - IF_FAIL_GO(HRESULT_FROM_WIN32(ERROR_FILE_NOT_FOUND)); - } - else - { - hr = BinderAcquirePEImage(szMDAssemblyPath, &pPEImage, NULL, FALSE, bundleFileLocation); - IF_FAIL_GO(hr); - - hr = BinderAcquireImport(pPEImage, &pIMetaDataAssemblyImport, dwPAFlags, FALSE); - IF_FAIL_GO(hr); - } + IF_FAIL_GO(HRESULT_FROM_WIN32(ERROR_FILE_NOT_FOUND)); } IF_FAIL_GO(TranslatePEToArchitectureType(dwPAFlags, &PeKind)); diff --git a/src/coreclr/src/binder/assemblyname.cpp b/src/coreclr/src/binder/assemblyname.cpp index 53a5683..5cb9d79 100644 --- a/src/coreclr/src/binder/assemblyname.cpp +++ b/src/coreclr/src/binder/assemblyname.cpp @@ -127,10 +127,6 @@ namespace BINDER_SPACE { SetContentType(AssemblyContentType_Default); } - else if (IsAfContentType_WindowsRuntime(dwRefOrDefFlags)) - { - SetContentType(AssemblyContentType_WindowsRuntime); - } else { IF_FAIL_GO(FUSION_E_INVALID_NAME); diff --git a/src/coreclr/src/binder/bindertracing.cpp b/src/coreclr/src/binder/bindertracing.cpp index a971f5b..5e94359 100644 --- a/src/coreclr/src/binder/bindertracing.cpp +++ b/src/coreclr/src/binder/bindertracing.cpp @@ -115,11 +115,7 @@ namespace void GetAssemblyLoadContextNameFromBinderID(UINT_PTR binderID, AppDomain *domain, /*out*/ SString &alcName) { ICLRPrivBinder *binder = reinterpret_cast(binderID); -#ifdef FEATURE_COMINTEROP - if (AreSameBinderInstance(binder, domain->GetTPABinderContext()) || AreSameBinderInstance(binder, domain->GetWinRtBinder())) -#else if (AreSameBinderInstance(binder, domain->GetTPABinderContext())) -#endif // FEATURE_COMINTEROP { alcName.Set(W("Default")); } @@ -463,4 +459,4 @@ namespace BinderTracing void BinderTracing::PathProbed(const WCHAR *path, BinderTracing::PathSource source, HRESULT hr) { FireEtwKnownPathProbed(GetClrInstanceId(), path, source, hr); -} \ No newline at end of file +} diff --git a/src/coreclr/src/debug/daccess/daccess.cpp b/src/coreclr/src/debug/daccess/daccess.cpp index 4441145..cd848b1 100644 --- a/src/coreclr/src/debug/daccess/daccess.cpp +++ b/src/coreclr/src/debug/daccess/daccess.cpp @@ -6604,7 +6604,7 @@ bool ClrDataAccess::GetILImageInfoFromNgenPEFile(PEFile *peFile, #if defined(FEATURE_CORESYSTEM) /* static */ -// We extract "ni.dll or .ni.winmd" from the NGEM image name to obtain the IL image name. +// We extract "ni.dll from the NGEN image name to obtain the IL image name. // In the end we add given ilExtension. // This dependecy is based on Apollo installer behavior. bool ClrDataAccess::GetILImageNameFromNgenImage( LPCWSTR ilExtension, @@ -6617,20 +6617,14 @@ bool ClrDataAccess::GetILImageNameFromNgenImage( LPCWSTR ilExtension, } _wcslwr_s(wszFilePath, cchFilePath); - // Find the "ni.dll" or "ni.winmd" extension (check for PEFile isWinRT something to know when is winmd or not. + // Find the "ni.dll" extension. // If none exists use NGEN image name. // - const WCHAR* ngenExtension[] = {W("ni.dll"), W("ni.winmd")}; + const WCHAR* ngenExtension = W("ni.dll"); - for (unsigned i = 0; i < COUNTOF(ngenExtension); ++i) + if (wcslen(ilExtension) <= wcslen(ngenExtension)) { - if (wcslen(ilExtension) > wcslen(ngenExtension[i])) - { - // We should not have IL image name bigger than NGEN image. - // It will not fit inside wszFilePath. - continue; - } - LPWSTR wszFileExtension = wcsstr(wszFilePath, ngenExtension[i]); + LPWSTR wszFileExtension = wcsstr(wszFilePath, ngenExtension); if (wszFileExtension != 0) { LPWSTR wszNextFileExtension = wszFileExtension; @@ -6638,14 +6632,14 @@ bool ClrDataAccess::GetILImageNameFromNgenImage( LPCWSTR ilExtension, do { wszFileExtension = wszNextFileExtension; - wszNextFileExtension = wcsstr(wszFileExtension + 1, ngenExtension[i]); + wszNextFileExtension = wcsstr(wszFileExtension + 1, ngenExtension); } while (wszNextFileExtension != 0); - // Overwrite ni.dll or ni.winmd with ilExtension(.dll, .winmd) + // Overwrite ni.dll with ilExtension if (!memcpy_s(wszFileExtension, - wcslen(ngenExtension[i])*sizeof(WCHAR), - ilExtension, - wcslen(ilExtension)*sizeof(WCHAR))) + wcslen(ngenExtension)*sizeof(WCHAR), + ilExtension, + wcslen(ilExtension)*sizeof(WCHAR))) { wszFileExtension[wcslen(ilExtension)] = '\0'; return true; @@ -6772,63 +6766,54 @@ ClrDataAccess::GetMetaDataFromHost(PEFile* peFile, } #if defined(FEATURE_CORESYSTEM) - const WCHAR* ilExtension[] = {W("dll"), W("winmd")}; + const WCHAR* ilExtension = W("dll"); WCHAR ngenImageName[MAX_LONGPATH] = {0}; if (wcscpy_s(ngenImageName, NumItems(ngenImageName), uniPath) != 0) { goto ErrExit; } - for (unsigned i = 0; i < COUNTOF(ilExtension); i++) + if (wcscpy_s(uniPath, NumItems(uniPath), ngenImageName) != 0) { - if (wcscpy_s(uniPath, NumItems(uniPath), ngenImageName) != 0) - { - goto ErrExit; - } - // Transform NGEN image name into IL Image name - if (!GetILImageNameFromNgenImage(ilExtension[i], uniPath, NumItems(uniPath))) - { - goto ErrExit; - } + goto ErrExit; + } + // Transform NGEN image name into IL Image name + if (!GetILImageNameFromNgenImage(ilExtension, uniPath, NumItems(uniPath))) + { + goto ErrExit; + } #endif//FEATURE_CORESYSTEM - // RVA size in ngen image and IL image is the same. Because the only - // different is in RVA. That is 4 bytes column fixed. - // + // RVA size in ngen image and IL image is the same. Because the only + // different is in RVA. That is 4 bytes column fixed. + // - // try again - if (m_legacyMetaDataLocator) - { - hr = m_legacyMetaDataLocator->GetMetadata( - uniPath, - imageTimestamp, - imageSize, - NULL, // MVID - not used yet - 0, // pass zero hint here... important - 0, // flags - reserved for future. - dataSize, - (BYTE*)buffer, - NULL); - } - else - { - hr = m_target3->GetMetaData( - uniPath, - imageTimestamp, - imageSize, - NULL, // MVID - not used yet - 0, // pass zero hint here... important - 0, // flags - reserved for future. - dataSize, - (BYTE*)buffer, - NULL); - } -#if defined(FEATURE_CORESYSTEM) - if (SUCCEEDED(hr)) - { - break; - } + // try again + if (m_legacyMetaDataLocator) + { + hr = m_legacyMetaDataLocator->GetMetadata( + uniPath, + imageTimestamp, + imageSize, + NULL, // MVID - not used yet + 0, // pass zero hint here... important + 0, // flags - reserved for future. + dataSize, + (BYTE*)buffer, + NULL); + } + else + { + hr = m_target3->GetMetaData( + uniPath, + imageTimestamp, + imageSize, + NULL, // MVID - not used yet + 0, // pass zero hint here... important + 0, // flags - reserved for future. + dataSize, + (BYTE*)buffer, + NULL); } -#endif // FEATURE_CORESYSTEM } if (FAILED(hr)) @@ -8174,6 +8159,12 @@ void DacHandleWalker::GetRefCountedHandleInfo( { SUPPORTS_DAC; + if (pJupiterRefCount) + *pJupiterRefCount = 0; + + if (pIsPegged) + *pIsPegged = FALSE; + #ifdef FEATURE_COMINTEROP if (uType == HNDTYPE_REFCOUNTED) { @@ -8184,12 +8175,6 @@ void DacHandleWalker::GetRefCountedHandleInfo( if (pRefCount) *pRefCount = (unsigned int)pWrap->GetRefCount(); - if (pJupiterRefCount) - *pJupiterRefCount = (unsigned int)pWrap->GetJupiterRefCount(); - - if (pIsPegged) - *pIsPegged = pWrap->IsConsideredPegged(); - if (pIsStrong) *pIsStrong = pWrap->IsWrapperActive(); @@ -8201,12 +8186,6 @@ void DacHandleWalker::GetRefCountedHandleInfo( if (pRefCount) *pRefCount = 0; - if (pJupiterRefCount) - *pJupiterRefCount = 0; - - if (pIsPegged) - *pIsPegged = FALSE; - if (pIsStrong) *pIsStrong = FALSE; } diff --git a/src/coreclr/src/debug/daccess/dacdbiimpl.cpp b/src/coreclr/src/debug/daccess/dacdbiimpl.cpp index e315265..b37312b 100644 --- a/src/coreclr/src/debug/daccess/dacdbiimpl.cpp +++ b/src/coreclr/src/debug/daccess/dacdbiimpl.cpp @@ -3753,45 +3753,7 @@ void DacDbiInterfaceImpl::GetCachedWinRTTypesForIIDs( DacDbiArrayList & iids, OUT DacDbiArrayList * pTypes) { -#ifdef FEATURE_COMINTEROP - - DD_ENTER_MAY_THROW; - - AppDomain * pAppDomain = vmAppDomain.GetDacPtr(); - - { - pTypes->Alloc(iids.Count()); - - for (unsigned int i = 0; i < iids.Count(); ++i) - { - // There is the possiblity that we'll get this far with a dump and not fail, but still - // not be able to get full info for a particular param. - EX_TRY_ALLOW_DATATARGET_MISSING_MEMORY_WITH_HANDLER - { - PTR_MethodTable pMT = pAppDomain->LookupTypeByGuid(iids[i]); - - // Fill in the struct using the current TypeHandle - VMPTR_TypeHandle vmTypeHandle = VMPTR_TypeHandle::NullPtr(); - TypeHandle th = TypeHandle::FromTAddr(dac_cast(pMT)); - vmTypeHandle.SetDacTargetPtr(th.AsTAddr()); - TypeHandleToExpandedTypeInfo(NoValueTypeBoxing, - vmAppDomain, - vmTypeHandle, - &((*pTypes)[i])); - } - EX_CATCH_ALLOW_DATATARGET_MISSING_MEMORY_WITH_HANDLER - { - // On failure for a particular type, default it to NULL. - (*pTypes)[i].elementType = ELEMENT_TYPE_END; - } - EX_END_CATCH_ALLOW_DATATARGET_MISSING_MEMORY_WITH_HANDLER - } - } -#else // FEATURE_COMINTEROP - { - pTypes->Alloc(0); - } -#endif // FEATURE_COMINTEROP + pTypes->Alloc(0); } void DacDbiInterfaceImpl::GetCachedWinRTTypes( @@ -3799,52 +3761,7 @@ void DacDbiInterfaceImpl::GetCachedWinRTTypes( OUT DacDbiArrayList * pGuids, OUT DacDbiArrayList * pTypes) { -#ifdef FEATURE_COMINTEROP - - DD_ENTER_MAY_THROW; - - AppDomain * pAppDomain = vmAppDomain.GetDacPtr(); - - InlineSArray rgMT; - InlineSArray rgGuid; - - { - pAppDomain->GetCachedWinRTTypes(&rgMT, &rgGuid, 0, NULL); - - pTypes->Alloc(rgMT.GetCount()); - pGuids->Alloc(rgGuid.GetCount()); - - for (COUNT_T i = 0; i < rgMT.GetCount(); ++i) - { - // There is the possiblity that we'll get this far with a dump and not fail, but still - // not be able to get full info for a particular param. - EX_TRY_ALLOW_DATATARGET_MISSING_MEMORY_WITH_HANDLER - { - // Fill in the struct using the current TypeHandle - VMPTR_TypeHandle vmTypeHandle = VMPTR_TypeHandle::NullPtr(); - TypeHandle th = TypeHandle::FromTAddr(dac_cast(rgMT[i])); - vmTypeHandle.SetDacTargetPtr(th.AsTAddr()); - TypeHandleToExpandedTypeInfo(NoValueTypeBoxing, - vmAppDomain, - vmTypeHandle, - &((*pTypes)[i])); - } - EX_CATCH_ALLOW_DATATARGET_MISSING_MEMORY_WITH_HANDLER - { - // On failure for a particular type, default it to NULL. - (*pTypes)[i].elementType = ELEMENT_TYPE_END; - } - EX_END_CATCH_ALLOW_DATATARGET_MISSING_MEMORY_WITH_HANDLER - (*pGuids)[i] = rgGuid[i]; - - } - - } -#else // FEATURE_COMINTEROP - { - pTypes->Alloc(0); - } -#endif // FEATURE_COMINTEROP + pTypes->Alloc(0); } //----------------------------------------------------------------------------- @@ -5863,13 +5780,6 @@ HRESULT DacDbiInterfaceImpl::IsWinRTModule(VMPTR_Module vmModule, BOOL& isWinRT) HRESULT hr = S_OK; isWinRT = FALSE; - EX_TRY - { - Module* pModule = vmModule.GetDacPtr(); - isWinRT = pModule->GetFile()->GetAssembly()->IsWindowsRuntime(); - } - EX_CATCH_HRESULT(hr); - return hr; } diff --git a/src/coreclr/src/debug/daccess/nidump.cpp b/src/coreclr/src/debug/daccess/nidump.cpp index f69bd30..ef4b1ff 100644 --- a/src/coreclr/src/debug/daccess/nidump.cpp +++ b/src/coreclr/src/debug/daccess/nidump.cpp @@ -887,8 +887,6 @@ NativeImageDumper::DumpNativeImage() NULL, &dwAssemblyFlags)); if ((afContentType_WindowsRuntime & dwAssemblyFlags) == afContentType_WindowsRuntime) { - // The WinMD adapter doesn't implement the IID_IMetaDataTables interface so we can't dump - // the raw metadata. DisplayWriteElementString ("Metadata", "Not supported by WinRT", COR_INFO); } else @@ -3869,15 +3867,6 @@ void NativeImageDumper::DumpModule( PTR_Module module ) false ); } -#ifdef FEATURE_COMINTEROP - TraverseGuidToMethodTableHash( module->m_pGuidToTypeHash, - "m_pGuidToTypeHash", - offsetof(Module, m_pGuidToTypeHash), - fieldsize(Module, m_pGuidToTypeHash), - true); - -#endif // FEATURE_COMINTEROP - _ASSERTE(module->m_pProfilingBlobTable == NULL); DisplayWriteFieldFlag( m_nativeImageProfiling, @@ -5708,8 +5697,6 @@ static NativeImageDumper::EnumMnemonics s_VMFlags[] = VMF_ENTRY(SPARSE_FOR_COMINTEROP), VMF_ENTRY(HASCOCLASSATTRIB), VMF_ENTRY(COMEVENTITFMASK), - VMF_ENTRY(PROJECTED_FROM_WINRT), - VMF_ENTRY(EXPORTED_TO_WINRT), #endif // FEATURE_COMINTEROP VMF_ENTRY(NOT_TIGHTLY_PACKED), @@ -7983,7 +7970,7 @@ void NativeImageDumper::DumpMethodDesc( PTR_MethodDesc md, PTR_Module module ) { PTR_DictionaryLayout layout(wrapped->IsSharedByGenericMethodInstantiations() ? dac_cast(wrapped->GetDictLayoutRaw()) : NULL ); - dictSize = DictionaryLayout::GetDictionarySizeFromLayout(imd->GetNumGenericMethodArgs(), + dictSize = DictionaryLayout::GetDictionarySizeFromLayout(imd->GetNumGenericMethodArgs(), layout); } } diff --git a/src/coreclr/src/debug/daccess/request.cpp b/src/coreclr/src/debug/daccess/request.cpp index 8fc4896..a0f7523 100644 --- a/src/coreclr/src/debug/daccess/request.cpp +++ b/src/coreclr/src/debug/daccess/request.cpp @@ -3904,12 +3904,8 @@ HRESULT ClrDataAccess::GetRCWData(CLRDATA_ADDRESS addr, struct DacpRCWData *rcwD rcwData->creatorThread = TO_CDADDR(pRCW->m_pCreatorThread); rcwData->ctxCookie = TO_CDADDR(pRCW->GetWrapperCtxCookie()); rcwData->refCount = pRCW->m_cbRefCount; - - rcwData->isJupiterObject = pRCW->IsJupiterObject(); - rcwData->supportsIInspectable = pRCW->SupportsIInspectable(); rcwData->isAggregated = pRCW->IsURTAggregated(); rcwData->isContained = pRCW->IsURTContained(); - rcwData->jupiterObject = TO_CDADDR(pRCW->GetJupiterObject()); rcwData->isFreeThreaded = pRCW->IsFreeThreaded(); rcwData->isDisconnected = pRCW->IsDisconnected(); @@ -4155,9 +4151,6 @@ HRESULT ClrDataAccess::GetCCWData(CLRDATA_ADDRESS ccw, struct DacpCCWData *ccwDa ccwData->isNeutered = pSimpleCCW->IsNeutered(); ccwData->ccwAddress = TO_CDADDR(dac_cast(pCCW)); - ccwData->jupiterRefCount = pSimpleCCW->GetJupiterRefCount(); - ccwData->isPegged = pSimpleCCW->IsPegged(); - ccwData->isGlobalPegged = RCWWalker::IsGlobalPeggingOn(); ccwData->hasStrongRef = pCCW->IsWrapperActive(); ccwData->handle = pCCW->GetObjectHandle(); ccwData->isExtendsCOMObject = pCCW->GetSimpleWrapper()->IsExtendsCOMObject(); diff --git a/src/coreclr/src/debug/di/module.cpp b/src/coreclr/src/debug/di/module.cpp index 24911ba..4bf2b09 100644 --- a/src/coreclr/src/debug/di/module.cpp +++ b/src/coreclr/src/debug/di/module.cpp @@ -63,7 +63,6 @@ CordbModule::CordbModule( m_vmDomainFile(vmDomainFile), m_vmModule(vmModule), m_EnCCount(0), - m_isIlWinMD(Uninitialized), m_fForceMetaDataSerialize(FALSE), m_nativeCodeTable(101) { @@ -372,14 +371,6 @@ void CordbModule::UpdateMetaDataCacheIfNeeded(mdToken token) return; } - // the metadata in WinMD is currently static since there's no - // support for profilers or EnC so we can simply exit early. - if (IsWinMD()) - { - LOG((LF_CORDB,LL_INFO10000, "CM::UMCIN token is in WinMD, exiting\n")); - return; - } - // // 1) Check if in-range? Compare against tables, etc. // @@ -411,8 +402,6 @@ BOOL CordbModule::CheckIfTokenInMetaData(mdToken token) CONTRACTL_END; LOG((LF_CORDB,LL_INFO10000, "CM::CITIM token=0x%x\n", token)); _ASSERTE(TypeFromToken(token) == mdtSignature); - // we shouldn't be doing this on WinMD modules since they don't implement IID_IMetaDataTables - _ASSERTE(!IsWinMD()); RSExtSmartPtr pTable; HRESULT hr = GetMetaDataImporter()->QueryInterface(IID_IMetaDataTables, (void**) &pTable); @@ -2764,37 +2753,6 @@ HRESULT CordbModule::GetJITCompilerFlags(DWORD *pdwFlags ) return hr; } -BOOL CordbModule::IsWinMD() -{ - CONTRACTL - { - THROWS; - } - CONTRACTL_END; - - if (m_isIlWinMD == Uninitialized) - { - BOOL isWinRT; - HRESULT hr = E_FAIL; - - { - RSLockHolder processLockHolder(GetProcess()->GetProcessLock()); - hr = GetProcess()->GetDAC()->IsWinRTModule(m_vmModule, isWinRT); - } - - _ASSERTE(SUCCEEDED(hr)); - if (FAILED(hr)) - ThrowHR(hr); - - if (isWinRT) - m_isIlWinMD = True; - else - m_isIlWinMD = False; - } - - return m_isIlWinMD == True; -} - /* ------------------------------------------------------------------------- * * CordbCode class * ------------------------------------------------------------------------- */ diff --git a/src/coreclr/src/debug/di/process.cpp b/src/coreclr/src/debug/di/process.cpp index f13e7b9..a965652 100644 --- a/src/coreclr/src/debug/di/process.cpp +++ b/src/coreclr/src/debug/di/process.cpp @@ -422,9 +422,6 @@ IMDInternalImport * CordbProcess::LookupMetaDataFromDebugger( const WCHAR *niexe = W(".ni.exe"); const size_t dllLen = wcslen(nidll); // used for ni.exe as well - const WCHAR *niwinmd = W(".ni.winmd"); - const size_t winmdLen = wcslen(niwinmd); - if (pathLen > dllLen && _wcsicmp(mutableFilePath+pathLen-dllLen, nidll) == 0) { wcscpy_s(mutableFilePath+pathLen-dllLen, dllLen, W(".dll")); @@ -433,10 +430,6 @@ IMDInternalImport * CordbProcess::LookupMetaDataFromDebugger( { wcscpy_s(mutableFilePath+pathLen-dllLen, dllLen, W(".exe")); } - else if (pathLen > winmdLen && _wcsicmp(mutableFilePath+pathLen-winmdLen, niwinmd) == 0) - { - wcscpy_s(mutableFilePath+pathLen-winmdLen, winmdLen, W(".winmd")); - } #endif//FEATURE_CORESYSTEM ALLOW_DATATARGET_MISSING_MEMORY( diff --git a/src/coreclr/src/debug/di/rsappdomain.cpp b/src/coreclr/src/debug/di/rsappdomain.cpp index 727b488..b944456 100644 --- a/src/coreclr/src/debug/di/rsappdomain.cpp +++ b/src/coreclr/src/debug/di/rsappdomain.cpp @@ -1067,130 +1067,13 @@ HRESULT CordbAppDomain::GetCachedWinRTTypesForIIDs( GUID * iids, ICorDebugTypeEnum * * ppTypesEnum) { -#if !defined(FEATURE_COMINTEROP) - return E_NOTIMPL; - -#else - - HRESULT hr = S_OK; - PUBLIC_API_ENTRY(this); - FAIL_IF_NEUTERED(this); - ATT_REQUIRE_STOPPED_MAY_FAIL(GetProcess()); - - _ASSERTE(!m_vmAppDomain.IsNull()); - - - EX_TRY - { - *ppTypesEnum = NULL; - - DacDbiArrayList dacTypes; - DacDbiArrayList dacGuids; - - IDacDbiInterface* pDAC = GetProcess()->GetDAC(); - - dacGuids.Init(iids, cGuids); - - // retrieve type info from LS - pDAC->GetCachedWinRTTypesForIIDs(m_vmAppDomain, dacGuids, &dacTypes); - - // synthesize CordbType instances - int cItfs = dacTypes.Count(); - NewArrayHolder pTypes(NULL); - - if (cItfs > 0) - { - pTypes = new CordbType*[cItfs]; - for (int n = 0; n < cItfs; ++n) - { - hr = CordbType::TypeDataToType(this, - &(dacTypes[n]), - &pTypes[n]); - } - } - - // build a type enumerator - CordbTypeEnum* pTypeEnum = CordbTypeEnum::Build(this, GetProcess()->GetContinueNeuterList(), cItfs, pTypes); - if ( pTypeEnum == NULL ) - { - IfFailThrow(E_OUTOFMEMORY); - } - - (*ppTypesEnum) = static_cast (pTypeEnum); - pTypeEnum->ExternalAddRef(); - - } - EX_CATCH_HRESULT(hr); - - return hr; - -#endif // !defined(FEATURE_COMINTEROP) } HRESULT CordbAppDomain::GetCachedWinRTTypes( ICorDebugGuidToTypeEnum * * ppTypesEnum) { -#if !defined(FEATURE_COMINTEROP) - return E_NOTIMPL; - -#else - - HRESULT hr = S_OK; - PUBLIC_API_ENTRY(this); - FAIL_IF_NEUTERED(this); - ATT_REQUIRE_STOPPED_MAY_FAIL(GetProcess()); - - EX_TRY - { - *ppTypesEnum = NULL; - - DacDbiArrayList guids; - DacDbiArrayList types; - - IDacDbiInterface* pDAC = GetProcess()->GetDAC(); - - // retrieve type info from LS - pDAC->GetCachedWinRTTypes(m_vmAppDomain, &guids, &types); - - _ASSERTE(guids.Count() == types.Count()); - if (guids.Count() != types.Count()) - IfFailThrow(E_FAIL); - - int cnt = types.Count(); - - RsGuidToTypeMapping* pMap = new RsGuidToTypeMapping[cnt]; - - for (int i = 0; i < cnt; ++i) - { - pMap[i].iid = guids[i]; - CordbType* pType; - hr = CordbType::TypeDataToType(this, &(types[i]), &pType); - if (SUCCEEDED(hr)) - { - pMap[i].spType.Assign(pType); - } - else - { - // spType stays NULL - } - } - - CordbGuidToTypeEnumerator * enumerator = new CordbGuidToTypeEnumerator(GetProcess(), &pMap, cnt); - _ASSERTE(pMap == NULL); - GetProcess()->GetContinueNeuterList()->Add(GetProcess(), enumerator); - - hr = enumerator->QueryInterface(IID_ICorDebugGuidToTypeEnum, reinterpret_cast(ppTypesEnum)); - _ASSERTE(SUCCEEDED(hr)); - IfFailThrow(hr); - - } - EX_CATCH_HRESULT(hr); - - return hr; - -#endif // !defined(FEATURE_COMINTEROP) } //----------------------------------------------------------- diff --git a/src/coreclr/src/debug/di/rspriv.h b/src/coreclr/src/debug/di/rspriv.h index 5c5f98a..9386c3a 100644 --- a/src/coreclr/src/debug/di/rspriv.h +++ b/src/coreclr/src/debug/di/rspriv.h @@ -4319,8 +4319,6 @@ private: CordbAssembly * ResolveAssemblyInternal(mdToken tkAssemblyRef); - BOOL IsWinMD(); - //----------------------------------------------------------- // Convenience routines //----------------------------------------------------------- @@ -4383,19 +4381,11 @@ public: private: - enum ILWinMDState - { - Uninitialized, - False, - True - }; - // Base Address and size of this module in debuggee's process. Maybe null if unknown. TargetBuffer m_PEBuffer; BOOL m_fDynamic; // Dynamic modules can grow (like Reflection Emit) BOOL m_fInMemory; // In memory modules don't have file-backing. - ILWinMDState m_isIlWinMD; // WinMD modules don't support all metadata interfaces // Indicates that the module must serialize its metadata in process as part of metadata // refresh. This is required for modules updated on the fly by the profiler diff --git a/src/coreclr/src/debug/ee/dactable.cpp b/src/coreclr/src/debug/ee/dactable.cpp index 967ac69..5313761 100644 --- a/src/coreclr/src/debug/ee/dactable.cpp +++ b/src/coreclr/src/debug/ee/dactable.cpp @@ -21,7 +21,6 @@ #include "../../vm/common.h" #include "../../vm/gcenv.h" #include "../../vm/ecall.h" -#include "../../vm/rcwwalker.h" // This header include will need to be rmeoved as part of GitHub#12170. // The only reason it's here now is that this file references the GC-private // variable g_HandleTableMap. @@ -40,7 +39,7 @@ extern DWORD gAppDomainTLSIndex; extern BOOL g_fAppX; #endif // FEATURE_APPX -DLLEXPORT +DLLEXPORT DacGlobals g_dacTable; // DAC global pointer table initialization diff --git a/src/coreclr/src/dlls/mscordac/CMakeLists.txt b/src/coreclr/src/dlls/mscordac/CMakeLists.txt index ddf66b4..692a803 100644 --- a/src/coreclr/src/dlls/mscordac/CMakeLists.txt +++ b/src/coreclr/src/dlls/mscordac/CMakeLists.txt @@ -139,12 +139,6 @@ set(COREDAC_LIBRARIES ${END_LIBRARY_GROUP} # End group of libraries that have circular references ) -if(CLR_CMAKE_TARGET_WIN32) - list(APPEND COREDAC_LIBRARIES - mdwinmd_dac - ) -endif(CLR_CMAKE_TARGET_WIN32) - if(CLR_CMAKE_HOST_WIN32) # mscordac.def should be generated before mscordaccore.dll is built add_dependencies(mscordaccore mscordaccore_def) diff --git a/src/coreclr/src/dlls/mscordbi/CMakeLists.txt b/src/coreclr/src/dlls/mscordbi/CMakeLists.txt index ffd48ee..39561e1 100644 --- a/src/coreclr/src/dlls/mscordbi/CMakeLists.txt +++ b/src/coreclr/src/dlls/mscordbi/CMakeLists.txt @@ -83,13 +83,9 @@ set(COREDBI_LIBRARIES ) if(CLR_CMAKE_HOST_WIN32) - if(CLR_CMAKE_TARGET_WIN32) - set(COREDBI_TARGET_WIN32_LIBRARIES mdwinmd_dbi) - endif(CLR_CMAKE_TARGET_WIN32) list(APPEND COREDBI_LIBRARIES mdhotdata-staticcrt - ${COREDBI_TARGET_WIN32_LIBRARIES} kernel32.lib advapi32.lib ole32.lib diff --git a/src/coreclr/src/dlls/mscoree/coreclr/CMakeLists.txt b/src/coreclr/src/dlls/mscoree/coreclr/CMakeLists.txt index 918fbf2..32fb9e2 100644 --- a/src/coreclr/src/dlls/mscoree/coreclr/CMakeLists.txt +++ b/src/coreclr/src/dlls/mscoree/coreclr/CMakeLists.txt @@ -16,10 +16,7 @@ if (CLR_CMAKE_HOST_WIN32) add_link_options(/INCREMENTAL:NO) # Delay load libraries required for WinRT as that is not supported on all platforms - add_link_options("/DELAYLOAD:api-ms-win-core-winrt-string-l1-1-0.dll") add_link_options("/DELAYLOAD:api-ms-win-core-winrt-l1-1-0.dll") - add_link_options("/DELAYLOAD:api-ms-win-core-winrt-roparameterizediid-l1-1-0.dll") - add_link_options("/DELAYLOAD:api-ms-win-ro-typeresolution-l1-1-0.dll") # Delay load version.dll so that we can specify how to search when loading it as it is not part of Windows' known DLLs add_link_options("/DELAYLOAD:version.dll") @@ -122,7 +119,6 @@ if(CLR_CMAKE_TARGET_WIN32) list(APPEND CORECLR_LIBRARIES ${STATIC_MT_CRT_LIB} ${STATIC_MT_VCRT_LIB} - mdwinmd_wks kernel32.lib advapi32.lib ole32.lib diff --git a/src/coreclr/src/dlls/mscorrc/mscorrc.rc b/src/coreclr/src/dlls/mscorrc/mscorrc.rc index 4573e20..6353a14 100644 --- a/src/coreclr/src/dlls/mscorrc/mscorrc.rc +++ b/src/coreclr/src/dlls/mscorrc/mscorrc.rc @@ -237,15 +237,6 @@ BEGIN IDS_EE_BADMARSHALFIELD_DECIMAL "Invalid managed/unmanaged type combination (Decimal fields must be paired with Struct or Currency)." IDS_EE_BADMARSHAL_STRINGARRAY "Invalid managed/unmanaged type combination (String[] must be paired with an ArraySubType of LPStr, LPWStr, BStr, or LPTStr)." IDS_EE_BADMARSHAL_DECIMALARRAY "Invalid managed/unmanaged type combination (Decimal[] must be paired with an ArraySubType of Struct or Currency)." - IDS_EE_BADMARSHAL_WINRT_MARSHAL_AS "Invalid managed/unmanaged type combination (Windows Runtime parameters and fields must not have a MarshalAs attribute set)." - IDS_EE_BADMARSHAL_WINRT_MISSING_GUID "Invalid managed/unmanaged type combination (Windows Runtime interfaces, classes and delegates must have a Guid or a default interface)." - IDS_EE_BADMARSHAL_WINRT_COPYCTOR "Windows Runtime marshaler does not support types with copy constructor." - IDS_EE_BADMARSHAL_WINRT_DELEGATE "Invalid managed/unmanaged type combination (Delegates must be Windows Runtime delegates)." - IDS_EE_BADMARSHAL_DEFAULTIFACE_NOT_WINRT_IFACE "The default interface must refer to a Windows Runtime interface with a GUID." - IDS_EE_BADMARSHAL_DEFAULTIFACE_NOT_SUBTYPE "The default interface must refer to an interface that is implemented by the type." - IDS_EE_BADMARSHAL_DATETIMEOFFSET "Invalid managed/unmanaged type combination (the DateTimeOffset structure must be paired with Struct)." - IDS_EE_INVALIDARG_WINRT_INVALIDURI "The given System.Uri cannot be converted into a Windows.Foundation.Uri. Please see http://go.microsoft.com/fwlink/?LinkID=215849 for details." - IDS_EE_BADMARSHAL_WINRT_ILLEGAL_TYPE "Windows Runtime marshaler does not support the type." #else // FEATURE_COMINTEROP IDS_EE_BADMARSHAL_BOOLEAN "Invalid managed/unmanaged type combination (booleans must be paired with I1, U1, or Bool)." IDS_EE_BADMARSHAL_I4 "Invalid managed/unmanaged type combination (Int32/UInt32 must be paired with I4 or U4)." @@ -317,10 +308,6 @@ BEGIN IDS_EE_BADMARSHALFIELD_NOSTRINGBUILDER "Struct or class fields cannot be of type StringBuilder. The same effect can usually be achieved by using a String field and preinitializing it to a string with length matching the length of the appropriate buffer." IDS_EE_BADMARSHALFIELD_ZEROLENGTHFIXEDSTRING "The length for ByValTStr strings cannot be zero." -#ifdef FEATURE_COMINTEROP - IDS_EE_BADMARSHALARRAY_NULL_HSTRING "Null strings may not be marshaled in Windows Runtime arrays. Null string was encountered at index %1." -#endif // FEATURE_COMINTEROP - // For ManagedToNativeComInteropStubAttribute #ifdef FEATURE_COMINTEROP IDS_EE_INTEROP_STUB_CA_MUST_BE_WITHIN_SAME_ASSEMBLY "The stub class '%1' specified in ManagedToNativeComInteropStubAttribute and interface '%2' must be from the same assembly." @@ -331,20 +318,7 @@ BEGIN #endif // FEATURE_COMINTEROP #ifdef FEATURE_COMINTEROP - IDS_EE_STRUCTLAYOUT_WINRT "Windows Runtime value types must have sequential layout." - IDS_EE_PRESERVESIG_WINRT "The PreserveSigAttribute may not be used on Windows Runtime methods." - IDS_EE_DELEGATEPINVOKE_WINRT "Windows Runtime delegates may not be used for PInvoke interop." - IDS_EE_WINRT_IENUMERABLE_BAD_CALL "There is not enough information to call IEnumerable.GetEnumerator on a Windows Runtime object, please cast the object to IEnumerable first." - IDS_EE_WINRT_IENUMERABLE_BAD_CAST "There is not enough information to cast a Windows Runtime object to IEnumerable, please cast the object to IEnumerable first." - IDS_EE_WINRT_INTERFACE_WITHOUT_GUID "Windows Runtime interface '%1' in assembly '%2' must have a valid GUID." - IDS_EE_WINRT_IID_ILLEGALTYPE "Unable to compute GUID for type '%1' because the instantiation contains types that are not supported by Windows Runtime." - IDS_EE_WINRT_IID_NODEFAULTINTERFACE "Unable to compute GUID because type '%1' does not have a default Windows Runtime interface." - IDS_EE_WINRT_ATTRIBUTES_NOT_INVOKABLE "Cannot construct type '%1'. Windows Runtime attribute types are not constructable." - IDS_EE_WINRT_TYPE_NOT_REGISTERED "Requested Windows Runtime type '%1' is not registered." - IDS_EE_WINRT_NOT_FACTORY_FOR_TYPE "Windows Runtime factory '%1' is not a factory for Windows Runtime type '%2'." - IDS_EE_WINRT_INVALID_FACTORY_FOR_TYPE "Windows Runtime type '%1' has a invalid Windows Runtime factory" - IDS_EE_CANNOTCAST_NOMARSHAL "The Windows Runtime Object can only be used in the threading context where it was created, because it implements INoMarshal or has MarshalingBehaviorAttribute(MarshalingType.None) set." - IDS_EE_NATIVE_COM_WEAKREF_BAD_TYPE "The object resolved by a native IWeakReference has an incompatible type for its managed WeakReference instance.\r\nExpected WeakReference target type: '%1'\r\nNative IWeakReference returned type: '%2'" + IDS_EE_NATIVE_COM_WEAKREF_BAD_TYPE "The object resolved by a native IWeakReference has an incompatible type for its managed WeakReference instance.\r\nExpected WeakReference target type: '%1'\r\nNative IWeakReference returned type: '%2'" #endif // FEATURE_COMINTEROP IDS_EE_INTEROP_CODE_SIZE_COMMENT "Code size" @@ -361,6 +335,10 @@ BEGIN IDS_CLASSLOAD_GENERICTYPE_RECURSIVE "Could not load type '%1' from assembly '%2' because it has recursive generic definition." IDS_CLASSLOAD_TOOMANYGENERICARGS "Could not load type '%1' from assembly '%2'. Internal limitation: Too many generic arguments." +#if FEATURE_COMINTEROP + IDS_EE_CANNOTCAST_NOMARSHAL "The Windows Runtime Object can only be used in the threading context where it was created, because it implements INoMarshal or has MarshalingBehaviorAttribute(MarshalingType.None) set." +#endif + IDS_CLASSLOAD_GENERAL "Could not load type '%1' from assembly '%2'." IDS_CLASSLOAD_TYPESPEC "Could not load TypeSpec from assembly '%2'." IDS_CLASSLOAD_SEALEDPARENT "Could not load type '%1' from assembly '%2' because the parent type is sealed." @@ -470,9 +448,6 @@ BEGIN IDS_EE_SIZECONTROLBADTYPE "Array size control parameter type not supported." IDS_EE_SAFEARRAYSZARRAYMISMATCH "SafeArray cannot be marshaled to this array type because it has either nonzero lower bounds or more than one dimension." - IDS_EE_WINRT_LOADFAILURE "Could not find Windows Runtime type '%1'." - IDS_EE_WINRT_THIRDPARTY_NOTSUPPORTED "Types from custom Windows Runtime components are not supported in desktop applications." - IDS_EE_ASSEMBLY_GETTYPE_CANNONT_HAVE_ASSEMBLY_SPEC "Type names passed to Assembly.GetType() must not specify an assembly." IDS_EE_CANNOT_HAVE_ASSEMBLY_SPEC "Unexpected assembly-qualifier in a typename." IDS_EE_NEEDS_ASSEMBLY_SPEC "Typename needs an assembly qualifier." @@ -500,6 +475,7 @@ BEGIN IDS_EE_MISSING_METHOD "Method not found: '%1'." IDS_EE_NO_IDISPATCH "This object cannot be marshaled as an IDispatch." + IDS_EE_NO_IINSPECTABLE "Marshalling as IInspectable is not supported in the .NET runtime." IDS_EE_NO_BACKING_CLASS_FACTORY "An instance of the __ComObject type cannot be created unless the type has been obtained using GetTypeFromProgID or GetTypeFromCLSID." IDS_EE_SIGTOOCOMPLEX "Internal limitation: method signature is too complex or too large." @@ -743,11 +719,6 @@ BEGIN BFA_TYPEDBYREFCANNOTHAVEBYREF "An ELEMENT_TYPE_TYPEDBYREF cannot have a ELEMENT_TYPE_BYREF modifier." BFA_REFERENCE_ASSEMBLY "Cannot load a reference assembly for execution." BFA_IJW_IN_COLLECTIBLE_ALC "Cannot load a mixed assembly into a collectible AssemblyLoadContext." - -#ifdef FEATURE_COMINTEROP - BFA_WINRT_INVALID_NAMESPACE_FOR_TYPE "Windows Runtime type '%1' has invalid namespace that does not begin with the file name in assembly '%2'." -#endif - END diff --git a/src/coreclr/src/dlls/mscorrc/resource.h b/src/coreclr/src/dlls/mscorrc/resource.h index 4011efb..d60986b 100644 --- a/src/coreclr/src/dlls/mscorrc/resource.h +++ b/src/coreclr/src/dlls/mscorrc/resource.h @@ -376,8 +376,6 @@ #define IDS_EE_CODEEXECUTION_CONTAINSGENERICVAR 0x1abb #define IDS_CLASSLOAD_WRONGCPU 0x1abc #define IDS_EE_CREATEINSTANCEFROMAPP_FAILED 0x1abd -#define IDS_EE_WINRT_LOADFAILURE 0x1abf -#define IDS_EE_WINRT_THIRDPARTY_NOTSUPPORTED 0x1ac2 #define IDS_EE_SIMD_NGEN_DISALLOWED 0x1ac3 #define IDS_IBC_MISSING_EXTERNAL_TYPE 0x1ac5 @@ -567,38 +565,7 @@ #define IDS_E_PROF_TIMEOUT_WAITING_FOR_CONCURRENT_GC 0x251D -#ifdef FEATURE_COMINTEROP -#define IDS_EE_BADMARSHAL_WINRT_MARSHAL_AS 0x2606 -#define IDS_EE_BADMARSHALARRAY_NULL_HSTRING 0x2607 -#define IDS_EE_BADMARSHAL_WINRT_ILLEGAL_TYPE 0x2608 -#define IDS_EE_STRUCTLAYOUT_WINRT 0x260a -#define IDS_EE_PRESERVESIG_WINRT 0x260b -#define IDS_EE_DELEGATEPINVOKE_WINRT 0x260c -#define IDS_EE_BADMARSHAL_WINRT_MISSING_GUID 0x260d -#define IDS_EE_BADMARSHAL_DEFAULTIFACE_NOT_WINRT_IFACE 0x260f - -#define IDS_EE_BADMARSHAL_DEFAULTIFACE_NOT_SUBTYPE 0x2610 -#define IDS_EE_BADMARSHAL_WINRT_DELEGATE 0x2611 -#define IDS_EE_BADMARSHAL_DATETIMEOFFSET 0x2614 -#define IDS_EE_WINRT_IENUMERABLE_BAD_CALL 0x2615 -#define IDS_EE_WINRT_IENUMERABLE_BAD_CAST 0x2616 -#define IDS_EE_WINRT_INTERFACE_WITHOUT_GUID 0x2617 -#define IDS_EE_WINRT_IID_ILLEGALTYPE 0x2619 -#define IDS_EE_WINRT_IID_NODEFAULTINTERFACE 0x261A -#define IDS_EE_WINRT_ATTRIBUTES_NOT_INVOKABLE 0x261B - -#define IDS_EE_WINRT_TYPE_NOT_REGISTERED 0x261F -#define IDS_EE_WINRT_NOT_FACTORY_FOR_TYPE 0x2620 -#define IDS_EE_INVALIDARG_WINRT_INVALIDURI 0x2624 - -#define IDS_EE_WINRT_INVALID_FACTORY_FOR_TYPE 0x2628 #define IDS_EE_CANNOTCAST_NOMARSHAL 0x2629 - -#define BFA_WINRT_INVALID_NAMESPACE_FOR_TYPE 0x262a -#define IDS_EE_BADMARSHAL_NULLABLE_RESTRICTION 0x262d -#endif // FEATURE_COMINTEROP - - #ifdef FEATURE_COMINTEROP #define IDS_EE_NATIVE_COM_WEAKREF_BAD_TYPE 0x262e #endif // FEATURE_COMINTEROP @@ -632,6 +599,6 @@ #define IDS_EE_NDIRECT_GETPROCADDR_UNIX_SO 0x2645 #define IDS_EE_BADMARSHAL_STRING_OUT 0x2646 #define IDS_EE_BADMARSHAL_COPYCTORRESTRICTION 0x2647 -#define IDS_EE_BADMARSHAL_WINRT_COPYCTOR 0x2648 #define IDS_EE_BADMARSHAL_DELEGATE_TLB_INTERFACE 0x2649 #define IDS_EE_THREAD_APARTMENT_NOT_SUPPORTED 0x264A +#define IDS_EE_NO_IINSPECTABLE 0x264B diff --git a/src/coreclr/src/hosts/corerun/corerun.cpp b/src/coreclr/src/hosts/corerun/corerun.cpp index 1643922..5095d74 100644 --- a/src/coreclr/src/hosts/corerun/corerun.cpp +++ b/src/coreclr/src/hosts/corerun/corerun.cpp @@ -283,9 +283,7 @@ public: W("*.ni.dll"), // Probe for .ni.dll first so that it's preferred if ni and il coexist in the same dir W("*.dll"), W("*.ni.exe"), - W("*.exe"), - W("*.ni.winmd"), - W("*.winmd") + W("*.exe") }; // Add files from %CORE_LIBRARIES% if specified @@ -524,7 +522,6 @@ HRESULT InitializeHost( const SString& appPath, const SString& appNiPath, const SString& nativeDllSearchDirs, - const SString& appLocalWinmetadata, void **hostHandle, unsigned int *domainId) { @@ -533,7 +530,6 @@ HRESULT InitializeHost( StackScratchBuffer appPathUTF8; StackScratchBuffer appNiPathUTF8; StackScratchBuffer nativeDllSearchDirsUTF8; - StackScratchBuffer appLocalWinmetadataUTF8; STARTUP_FLAGS flags = CreateStartupFlags(); @@ -562,7 +558,6 @@ HRESULT InitializeHost( "APP_PATHS", "APP_NI_PATHS", "NATIVE_DLL_SEARCH_DIRECTORIES", - "APP_LOCAL_WINMETADATA", "System.GC.Server", "System.GC.Concurrent" }; @@ -576,8 +571,6 @@ HRESULT InitializeHost( appNiPath.GetUTF8(appNiPathUTF8), // NATIVE_DLL_SEARCH_DIRECTORIES nativeDllSearchDirs.GetUTF8(nativeDllSearchDirsUTF8), - // APP_LOCAL_WINMETADATA - appLocalWinmetadata.GetUTF8(appLocalWinmetadataUTF8), // System.GC.Server flags & STARTUP_SERVER_GC ? "true" : "false", // System.GC.Concurrent @@ -690,7 +683,6 @@ bool TryRun(const int argc, const wchar_t* argv[], Logger &log, const bool verbo StackSString appPath; StackSString appNiPath; StackSString managedAssemblyFullName; - StackSString appLocalWinmetadata; wchar_t* filePart = NULL; @@ -718,16 +710,6 @@ bool TryRun(const int argc, const wchar_t* argv[], Logger &log, const bool verbo log << W("Loading: ") << managedAssemblyFullName.GetUnicode() << Logger::endl; - appLocalWinmetadata.Set(appPath); - appLocalWinmetadata.Append(W("\\WinMetadata")); - - DWORD dwAttrib = WszGetFileAttributes(appLocalWinmetadata); - bool appLocalWinMDexists = dwAttrib != INVALID_FILE_ATTRIBUTES && (dwAttrib & FILE_ATTRIBUTE_DIRECTORY); - - if (!appLocalWinMDexists) - { - appLocalWinmetadata.Clear(); - } appNiPath.Set(appPath); appNiPath.Append(W("NI")); appNiPath.Append(W(";")); @@ -764,7 +746,7 @@ bool TryRun(const int argc, const wchar_t* argv[], Logger &log, const bool verbo void* hostHandle = nullptr; DWORD domainId = 0; - hr = InitializeHost(log, hostEnvironment, appPath, appNiPath, nativeDllSearchDirs, appLocalWinmetadata, &hostHandle, (unsigned int*)&domainId); + hr = InitializeHost(log, hostEnvironment, appPath, appNiPath, nativeDllSearchDirs, &hostHandle, (unsigned int*)&domainId); if (FAILED(hr)) { exitCode = hr; diff --git a/src/coreclr/src/ilasm/CMakeLists.txt b/src/coreclr/src/ilasm/CMakeLists.txt index 94fe6b8..0036ed4 100644 --- a/src/coreclr/src/ilasm/CMakeLists.txt +++ b/src/coreclr/src/ilasm/CMakeLists.txt @@ -86,7 +86,6 @@ if(CLR_CMAKE_TARGET_WIN32) list(APPEND ILASM_LINK_LIBRARIES ${STATIC_MT_CRT_LIB} ${STATIC_MT_VCRT_LIB} - mdwinmd_wks kernel32.lib advapi32.lib ole32.lib diff --git a/src/coreclr/src/ildasm/exe/CMakeLists.txt b/src/coreclr/src/ildasm/exe/CMakeLists.txt index 87a0fa0..47531eb 100644 --- a/src/coreclr/src/ildasm/exe/CMakeLists.txt +++ b/src/coreclr/src/ildasm/exe/CMakeLists.txt @@ -79,7 +79,6 @@ if(CLR_CMAKE_HOST_WIN32) list(APPEND ILDASM_LINK_LIBRARIES ${STATIC_MT_CRT_LIB} ${STATIC_MT_VCRT_LIB} - mdwinmd_wks kernel32.lib advapi32.lib ole32.lib diff --git a/src/coreclr/src/inc/CrstTypes.def b/src/coreclr/src/inc/CrstTypes.def index 0bbd24b9..7946d58 100644 --- a/src/coreclr/src/inc/CrstTypes.def +++ b/src/coreclr/src/inc/CrstTypes.def @@ -133,9 +133,6 @@ Crst ClrNotification Unordered End -Crst CrstCLRPrivBinderLocalWinMDPath -End - Crst CLRPrivBinderMaps End @@ -669,10 +666,6 @@ Crst MulticoreJitManager AcquiredBefore MulticoreJitHash ThreadStore End -Crst WinRTFactoryCache - AcquiredBefore HandleTable -End - Crst SqmManager End diff --git a/src/coreclr/src/inc/clrconfigvalues.h b/src/coreclr/src/inc/clrconfigvalues.h index 109c3c8..141af86 100644 --- a/src/coreclr/src/inc/clrconfigvalues.h +++ b/src/coreclr/src/inc/clrconfigvalues.h @@ -123,7 +123,6 @@ RETAIL_CONFIG_DWORD_INFO(INTERNAL_JitPitchMaxVal, W("JitPitchMaxVal"), (DWORD)0x /// /// Assembly Loader /// -RETAIL_CONFIG_DWORD_INFO_EX(EXTERNAL_DesignerNamespaceResolutionEnabled, W("designerNamespaceResolution"), FALSE, "Set it to 1 to enable DesignerNamespaceResolve event for WinRT types", CLRConfig::IgnoreEnv | CLRConfig::IgnoreHKLM | CLRConfig::IgnoreHKCU) CONFIG_DWORD_INFO_EX(INTERNAL_GetAssemblyIfLoadedIgnoreRidMap, W("GetAssemblyIfLoadedIgnoreRidMap"), 0, "Used to force loader to ignore assemblies cached in the rid-map", CLRConfig::EEConfig_default) /// @@ -403,7 +402,6 @@ RETAIL_CONFIG_DWORD_INFO(INTERNAL_InterpreterFallback, W("InterpreterFallback"), /// /// Loader /// -RETAIL_CONFIG_STRING_INFO(INTERNAL_WinMDPath, W("WinMDPath"), "Path for Windows WinMD files") /// /// Loader heap @@ -442,9 +440,6 @@ CONFIG_DWORD_INFO_EX(INTERNAL_MD_MiniMDBreak, W("MD_MiniMDBreak"), 0, "ASSERT wh CONFIG_DWORD_INFO_EX(INTERNAL_MD_PreSaveBreak, W("MD_PreSaveBreak"), 0, "ASSERT when calling CMiniMdRw::PreSave", CLRConfig::EEConfig_default) CONFIG_DWORD_INFO_EX(INTERNAL_MD_RegMetaBreak, W("MD_RegMetaBreak"), 0, "ASSERT when creating RegMeta class", CLRConfig::EEConfig_default) CONFIG_DWORD_INFO_EX(INTERNAL_MD_RegMetaDump, W("MD_RegMetaDump"), 0, "Dump MD in 4 functions (?)", CLRConfig::EEConfig_default) -// MetaData - Desktop-only -CONFIG_DWORD_INFO_EX(INTERNAL_MD_WinMD_Disable, W("MD_WinMD_Disable"), 0, "Never activate the WinMD import adapter", CLRConfig::EEConfig_default) -CONFIG_DWORD_INFO_EX(INTERNAL_MD_WinMD_AssertOnIllegalUsage, W("MD_WinMD_AssertOnIllegalUsage"), 0, "ASSERT if a WinMD import adapter detects a tool incompatibility", CLRConfig::EEConfig_default) // Metadata - mscordbi only - this flag is only intended to mitigate potential issues in bug fix 458597. RETAIL_CONFIG_DWORD_INFO_EX(EXTERNAL_MD_PreserveDebuggerMetadataMemory, W("MD_PreserveDebuggerMetadataMemory"), 0, "Save all versions of metadata memory in the debugger when debuggee metadata is updated", CLRConfig::EEConfig_default) @@ -698,7 +693,6 @@ RETAIL_CONFIG_DWORD_INFO(UNSUPPORTED_InteropValidatePinnedObjects, W("InteropVal RETAIL_CONFIG_DWORD_INFO(EXTERNAL_InteropLogArguments, W("InteropLogArguments"), 0, "Log all pinned arguments passed to an interop call") RETAIL_CONFIG_STRING_INFO(UNSUPPORTED_LogCCWRefCountChange, W("LogCCWRefCountChange"), "Outputs debug information and calls LogCCWRefCountChange_BREAKPOINT when AddRef or Release is called on a CCW.") RETAIL_CONFIG_DWORD_INFO(INTERNAL_EnableRCWCleanupOnSTAShutdown, W("EnableRCWCleanupOnSTAShutdown"), 0, "Performs RCW cleanup when STA shutdown is detected using IInitializeSpy in classic processes.") -RETAIL_CONFIG_STRING_INFO(INTERNAL_LocalWinMDPath, W("LocalWinMDPath"), "Additional path to probe for WinMD files in if a WinRT type is not resolved using the standard paths.") RETAIL_CONFIG_DWORD_INFO(EXTERNAL_AllowDComReflection, W("AllowDComReflection"), 0, "Allows out of process DCOM clients to marshal blocked reflection types.") // diff --git a/src/coreclr/src/inc/clrprivbinderutil.h b/src/coreclr/src/inc/clrprivbinderutil.h index cdc24a5..6f65ea6 100644 --- a/src/coreclr/src/inc/clrprivbinderutil.h +++ b/src/coreclr/src/inc/clrprivbinderutil.h @@ -13,9 +13,6 @@ #include "internalunknownimpl.h" #include "clrprivbinding.h" #include "slist.h" -#ifdef FEATURE_COMINTEROP -#include "windowsstring.h" -#endif // FEATURE_COMINTEROP #include "strongnameholders.h" //===================================================================================================================== @@ -81,179 +78,6 @@ namespace CLRPrivBinderUtil //--------------------------------------------------------------------------------------------- NewArrayHolder m_wzPath; }; - - //================================================================================================================= - // Types for WStringList (used in WinRT binders) - - typedef SListElem< PTR_WSTR > WStringListElem; - typedef DPTR(WStringListElem) PTR_WStringListElem; - typedef SList< WStringListElem, false /* = fHead default value */, PTR_WStringListElem > WStringList; - typedef DPTR(WStringList) PTR_WStringList; - - // Destroys list of strings (code:WStringList). - void WStringList_Delete(WStringList * pList); - -#ifndef DACCESS_COMPILE - //===================================================================================================================== - // Holder of allocated code:WStringList (helper class for WinRT binders - e.g. code:CLRPrivBinderWinRT::GetFileNameListForNamespace). - class WStringListHolder - { - public: - WStringListHolder(WStringList * pList = nullptr) - { - LIMITED_METHOD_CONTRACT; - m_pList = pList; - } - ~WStringListHolder() - { - LIMITED_METHOD_CONTRACT; - Destroy(); - } - - void InsertTail(LPCWSTR wszValue) - { - CONTRACTL - { - THROWS; - GC_NOTRIGGER; - MODE_ANY; - } - CONTRACTL_END; - - NewArrayHolder wszElemValue = DuplicateStringThrowing(wszValue); - NewHolder pElem = new WStringListElem(wszElemValue); - - if (m_pList == nullptr) - { - m_pList = new WStringList(); - } - - m_pList->InsertTail(pElem.Extract()); - // The string is now owned by the list - wszElemValue.SuppressRelease(); - } - - WStringList * GetValue() - { - LIMITED_METHOD_CONTRACT; - return m_pList; - } - - WStringList * Extract() - { - LIMITED_METHOD_CONTRACT; - - WStringList * pList = m_pList; - m_pList = nullptr; - return pList; - } - - private: - void Destroy() - { - LIMITED_METHOD_CONTRACT; - - if (m_pList != nullptr) - { - WStringList_Delete(m_pList); - m_pList = nullptr; - } - } - - private: - WStringList * m_pList; - }; // class WStringListHolder -#endif //!DACCESS_COMPILE - -#ifdef FEATURE_COMINTEROP - //===================================================================================================================== - // Holder of allocated array of HSTRINGs (helper class for WinRT binders - e.g. code:CLRPrivBinderWinRT::m_rgAltPaths). - class HSTRINGArrayHolder - { - public: - HSTRINGArrayHolder() - { - LIMITED_METHOD_CONTRACT; - - m_cValues = 0; - m_rgValues = nullptr; - } -#ifndef DACCESS_COMPILE - ~HSTRINGArrayHolder() - { - LIMITED_METHOD_CONTRACT; - Destroy(); - } - - // Destroys current array and allocates a new one with cValues elements. - void Allocate(DWORD cValues) - { - STANDARD_VM_CONTRACT; - - Destroy(); - _ASSERTE(m_cValues == 0); - - if (cValues > 0) - { - m_rgValues = new HSTRING[cValues]; - m_cValues = cValues; - - // Initialize the array values - for (DWORD i = 0; i < cValues; i++) - { - m_rgValues[i] = nullptr; - } - } - } -#endif //!DACCESS_COMPILE - - HSTRING GetAt(DWORD index) const - { - LIMITED_METHOD_CONTRACT; - return m_rgValues[index]; - } - - HSTRING * GetRawArray() - { - LIMITED_METHOD_CONTRACT; - return m_rgValues; - } - - DWORD GetCount() - { - LIMITED_METHOD_CONTRACT; - return m_cValues; - } - - private: -#ifndef DACCESS_COMPILE - void Destroy() - { - LIMITED_METHOD_CONTRACT; - - for (DWORD i = 0; i < m_cValues; i++) - { - if (m_rgValues[i] != nullptr) - { - WindowsDeleteString(m_rgValues[i]); - } - } - m_cValues = 0; - - if (m_rgValues != nullptr) - { - delete [] m_rgValues; - m_rgValues = nullptr; - } - } -#endif //!DACCESS_COMPILE - - private: - DWORD m_cValues; - HSTRING * m_rgValues; - }; // class HSTRINGArrayHolder - -#endif // FEATURE_COMINTEROP } // namespace CLRPrivBinderUtil #endif // __CLRPRIVBINDERUTIL_H__ diff --git a/src/coreclr/src/inc/clrprivbinding.idl b/src/coreclr/src/inc/clrprivbinding.idl index 7c812b6..d0df1e4 100644 --- a/src/coreclr/src/inc/clrprivbinding.idl +++ b/src/coreclr/src/inc/clrprivbinding.idl @@ -203,15 +203,3 @@ interface ICLRPrivAssemblyInfo : IUnknown [out] LPDWORD pcbBuffer, [out, size_is(cbBuffer), length_is(*pcbBuffer), optional] BYTE *pbBuffer); }; - -/************************************************************************************** - ** ICLRPrivAssemblyID_WinRT - Provides identification for WinRT assembly - allows dynamic casting inside code:CLRPrivAssemblyWinRT. - **************************************************************************************/ -[ - uuid(4372D277-9906-4FED-BF53-30C0B4010896), - version(1.0), - local -] -interface ICLRPrivAssemblyID_WinRT : IUnknown -{ -}; diff --git a/src/coreclr/src/inc/cor.h b/src/coreclr/src/inc/cor.h index 2ed0cc5..ba0c9c3 100644 --- a/src/coreclr/src/inc/cor.h +++ b/src/coreclr/src/inc/cor.h @@ -1825,27 +1825,6 @@ DECLARE_INTERFACE_(IMetaDataInfo, IUnknown) DWORD * pdwMappingType) PURE; // [out] Type of file mapping (code:CorFileMapping). }; // class IMetaDataInfo - -//------------------------------------- -//--- IMetaDataWinMDImport -//------------------------------------- -// {969EA0C5-964E-411B-A807-B0F3C2DFCBD4} -EXTERN_GUID(IID_IMetaDataWinMDImport, 0x969ea0c5, 0x964e, 0x411b, 0xa8, 0x7, 0xb0, 0xf3, 0xc2, 0xdf, 0xcb, 0xd4); - -//--- -#undef INTERFACE -#define INTERFACE IMetaDataWinMDImport -DECLARE_INTERFACE_(IMetaDataWinMDImport, IUnknown) -{ - STDMETHOD(GetUntransformedTypeRefProps)( // S_OK or error. - mdTypeRef tr, // [IN] TypeRef token. - mdToken *ptkResolutionScope, // [OUT] Resolution scope, ModuleRef or AssemblyRef. - _Out_writes_to_opt_(cchName, *pchName) - LPWSTR szName, // [OUT] Name of the TypeRef. - ULONG cchName, // [IN] Size of buffer. - ULONG *pchName) PURE; // [OUT] Size of Name. -}; // class IMetaDataWinMDImport - //********************************************************************** // // Predefined CustomAttribute and structures for these custom value diff --git a/src/coreclr/src/inc/corcompile.h b/src/coreclr/src/inc/corcompile.h index 2973b7a..2410a0a 100644 --- a/src/coreclr/src/inc/corcompile.h +++ b/src/coreclr/src/inc/corcompile.h @@ -1387,13 +1387,6 @@ class ICorCompilationDomain CORCOMPILE_DEPENDENCY **ppDependencies, DWORD *cDependencies ) = 0; - - -#ifdef CROSSGEN_COMPILE - virtual HRESULT SetPlatformWinmdPaths( - LPCWSTR pwzPlatformWinmdPaths - ) = 0; -#endif }; /********************************************************************************* @@ -1456,19 +1449,6 @@ class ICorCompileInfo CORINFO_ASSEMBLY_HANDLE *pHandle ) = 0; - -#ifdef FEATURE_COMINTEROP - // Loads a WinRT typeref into the EE and returns - // a handle to it. We have to load all typerefs - // during dependency computation since assemblyrefs - // are meaningless to WinRT. - virtual HRESULT LoadTypeRefWinRT( - IMDInternalImport *pAssemblyImport, - mdTypeRef ref, - CORINFO_ASSEMBLY_HANDLE *pHandle - ) = 0; -#endif - virtual BOOL IsInCurrentVersionBubble(CORINFO_MODULE_HANDLE hModule) = 0; // Loads a module from an assembly into the EE @@ -1776,8 +1756,6 @@ extern "C" HRESULT __stdcall CreatePdb(CORINFO_ASSEMBLY_HANDLE hAssembly, BSTR p extern bool g_fNGenMissingDependenciesOk; -extern bool g_fNGenWinMDResilient; - #ifdef FEATURE_READYTORUN_COMPILER extern bool g_fReadyToRunCompilation; extern bool g_fLargeVersionBubble; diff --git a/src/coreclr/src/inc/coregen.h b/src/coreclr/src/inc/coregen.h index a286c27..0ab034a 100644 --- a/src/coreclr/src/inc/coregen.h +++ b/src/coreclr/src/inc/coregen.h @@ -15,9 +15,7 @@ #define NGENWORKER_FLAGS_MISSINGDEPENDENCIESOK 0x0004 #define NGENWORKER_FLAGS_LARGEVERSIONBUBBLE 0x0008 -#define NGENWORKER_FLAGS_WINMD_RESILIENT 0x1000 #define NGENWORKER_FLAGS_READYTORUN 0x2000 -#define NGENWORKER_FLAGS_NO_METADATA 0x4000 #define NGENWORKER_FLAGS_SILENT 0x8000 #define NGENWORKER_FLAGS_VERBOSE 0x10000 #define NGENWORKER_FLAGS_SUPPRESS_WARNINGS 0x20000 diff --git a/src/coreclr/src/inc/corhost.h b/src/coreclr/src/inc/corhost.h index 81b000e..4c920ca 100644 --- a/src/coreclr/src/inc/corhost.h +++ b/src/coreclr/src/inc/corhost.h @@ -156,14 +156,4 @@ private: SVAL_DECL(STARTUP_FLAGS, m_dwStartupFlags); }; -#ifdef FEATURE_COMINTEROP -extern "C" -HRESULT STDMETHODCALLTYPE DllGetActivationFactoryImpl( - LPCWSTR wszAssemblyName, - LPCWSTR wszTypeName, - LPCWSTR wszCodeBase, - IActivationFactory ** factory); - -#endif // defined(FEATURE_COMINTEROP) - #endif // __CorHost__h__ diff --git a/src/coreclr/src/inc/corpriv.h b/src/coreclr/src/inc/corpriv.h index 6b92458..6172285 100644 --- a/src/coreclr/src/inc/corpriv.h +++ b/src/coreclr/src/inc/corpriv.h @@ -314,7 +314,7 @@ DECLARE_INTERFACE_(ICeeGenInternal, IUnknown) // Private interface exposed by // AssemblyMDInternalImport - gives us access to the internally stored IMDInternalImport*. // -// RegMeta, WinMDImport - supports the internal GetMetaDataInternalInterfaceFromPublic() "api". +// RegMeta - supports the internal GetMetaDataInternalInterfaceFromPublic() "api". // // {92B2FEF9-F7F5-420d-AD42-AECEEE10A1EF} EXTERN_GUID(IID_IGetIMDInternalImport, 0x92b2fef9, 0xf7f5, 0x420d, 0xad, 0x42, 0xae, 0xce, 0xee, 0x10, 0xa1, 0xef); diff --git a/src/coreclr/src/inc/crsttypes.h b/src/coreclr/src/inc/crsttypes.h index 904babb..9986855 100644 --- a/src/coreclr/src/inc/crsttypes.h +++ b/src/coreclr/src/inc/crsttypes.h @@ -40,137 +40,135 @@ enum CrstType CrstCOMWrapperCache = 21, CrstConnectionNameTable = 22, CrstContexts = 23, - CrstCrstCLRPrivBinderLocalWinMDPath = 24, - CrstCSPCache = 25, - CrstDataTest1 = 26, - CrstDataTest2 = 27, - CrstDbgTransport = 28, - CrstDeadlockDetection = 29, - CrstDebuggerController = 30, - CrstDebuggerFavorLock = 31, - CrstDebuggerHeapExecMemLock = 32, - CrstDebuggerHeapLock = 33, - CrstDebuggerJitInfo = 34, - CrstDebuggerMutex = 35, - CrstDelegateToFPtrHash = 36, - CrstDomainLocalBlock = 37, - CrstDynamicIL = 38, - CrstDynamicMT = 39, - CrstDynLinkZapItems = 40, - CrstEtwTypeLogHash = 41, - CrstEventPipe = 42, - CrstEventStore = 43, - CrstException = 44, - CrstExecuteManLock = 45, - CrstExecuteManRangeLock = 46, - CrstExternalObjectContextCache = 47, - CrstFCall = 48, - CrstFriendAccessCache = 49, - CrstFuncPtrStubs = 50, - CrstFusionAppCtx = 51, - CrstGCCover = 52, - CrstGlobalStrLiteralMap = 53, - CrstHandleTable = 54, - CrstHostAssemblyMap = 55, - CrstHostAssemblyMapAdd = 56, - CrstIbcProfile = 57, - CrstIJWFixupData = 58, - CrstIJWHash = 59, - CrstILStubGen = 60, - CrstInlineTrackingMap = 61, - CrstInstMethodHashTable = 62, - CrstInterfaceVTableMap = 63, - CrstInterop = 64, - CrstInteropData = 65, - CrstIOThreadpoolWorker = 66, - CrstIsJMCMethod = 67, - CrstISymUnmanagedReader = 68, - CrstJit = 69, - CrstJitGenericHandleCache = 70, - CrstJitInlineTrackingMap = 71, - CrstJitPatchpoint = 72, - CrstJitPerf = 73, - CrstJumpStubCache = 74, - CrstLeafLock = 75, - CrstListLock = 76, - CrstLoaderAllocator = 77, - CrstLoaderAllocatorReferences = 78, - CrstLoaderHeap = 79, - CrstMda = 80, - CrstMetadataTracker = 81, - CrstMethodDescBackpatchInfoTracker = 82, - CrstModIntPairList = 83, - CrstModule = 84, - CrstModuleFixup = 85, - CrstModuleLookupTable = 86, - CrstMulticoreJitHash = 87, - CrstMulticoreJitManager = 88, - CrstMUThunkHash = 89, - CrstNativeBinderInit = 90, - CrstNativeImageCache = 91, - CrstNativeImageEagerFixups = 92, - CrstNls = 93, - CrstNotifyGdb = 94, - CrstObjectList = 95, - CrstOnEventManager = 96, - CrstPatchEntryPoint = 97, - CrstPEImage = 98, - CrstPEImagePDBStream = 99, - CrstPendingTypeLoadEntry = 100, - CrstPinHandle = 101, - CrstPinnedByrefValidation = 102, - CrstProfilerGCRefDataFreeList = 103, - CrstProfilingAPIStatus = 104, - CrstPublisherCertificate = 105, - CrstRCWCache = 106, - CrstRCWCleanupList = 107, - CrstRCWRefCache = 108, - CrstReadyToRunEntryPointToMethodDescMap = 109, - CrstReDacl = 110, - CrstReflection = 111, - CrstReJITGlobalRequest = 112, - CrstRemoting = 113, - CrstRetThunkCache = 114, - CrstRWLock = 115, - CrstSavedExceptionInfo = 116, - CrstSaveModuleProfileData = 117, - CrstSecurityStackwalkCache = 118, - CrstSharedAssemblyCreate = 119, - CrstSigConvert = 120, - CrstSingleUseLock = 121, - CrstSpecialStatics = 122, - CrstSqmManager = 123, - CrstStackSampler = 124, - CrstStressLog = 125, - CrstStrongName = 126, - CrstStubCache = 127, - CrstStubDispatchCache = 128, - CrstStubUnwindInfoHeapSegments = 129, - CrstSyncBlockCache = 130, - CrstSyncHashLock = 131, - CrstSystemBaseDomain = 132, - CrstSystemDomain = 133, - CrstSystemDomainDelayedUnloadList = 134, - CrstThreadIdDispenser = 135, - CrstThreadpoolEventCache = 136, - CrstThreadpoolTimerQueue = 137, - CrstThreadpoolWaitThreads = 138, - CrstThreadpoolWorker = 139, - CrstThreadStaticDataHashTable = 140, - CrstThreadStore = 141, - CrstTieredCompilation = 142, - CrstTPMethodTable = 143, - CrstTypeEquivalenceMap = 144, - CrstTypeIDMap = 145, - CrstUMEntryThunkCache = 146, - CrstUMThunkHash = 147, - CrstUniqueStack = 148, - CrstUnresolvedClassLock = 149, - CrstUnwindInfoTableLock = 150, - CrstVSDIndirectionCellLock = 151, - CrstWinRTFactoryCache = 152, - CrstWrapperTemplate = 153, - kNumberOfCrstTypes = 154 + CrstCSPCache = 24, + CrstDataTest1 = 25, + CrstDataTest2 = 26, + CrstDbgTransport = 27, + CrstDeadlockDetection = 28, + CrstDebuggerController = 29, + CrstDebuggerFavorLock = 30, + CrstDebuggerHeapExecMemLock = 31, + CrstDebuggerHeapLock = 32, + CrstDebuggerJitInfo = 33, + CrstDebuggerMutex = 34, + CrstDelegateToFPtrHash = 35, + CrstDomainLocalBlock = 36, + CrstDynamicIL = 37, + CrstDynamicMT = 38, + CrstDynLinkZapItems = 39, + CrstEtwTypeLogHash = 40, + CrstEventPipe = 41, + CrstEventStore = 42, + CrstException = 43, + CrstExecuteManLock = 44, + CrstExecuteManRangeLock = 45, + CrstExternalObjectContextCache = 46, + CrstFCall = 47, + CrstFriendAccessCache = 48, + CrstFuncPtrStubs = 49, + CrstFusionAppCtx = 50, + CrstGCCover = 51, + CrstGlobalStrLiteralMap = 52, + CrstHandleTable = 53, + CrstHostAssemblyMap = 54, + CrstHostAssemblyMapAdd = 55, + CrstIbcProfile = 56, + CrstIJWFixupData = 57, + CrstIJWHash = 58, + CrstILStubGen = 59, + CrstInlineTrackingMap = 60, + CrstInstMethodHashTable = 61, + CrstInterfaceVTableMap = 62, + CrstInterop = 63, + CrstInteropData = 64, + CrstIOThreadpoolWorker = 65, + CrstIsJMCMethod = 66, + CrstISymUnmanagedReader = 67, + CrstJit = 68, + CrstJitGenericHandleCache = 69, + CrstJitInlineTrackingMap = 70, + CrstJitPatchpoint = 71, + CrstJitPerf = 72, + CrstJumpStubCache = 73, + CrstLeafLock = 74, + CrstListLock = 75, + CrstLoaderAllocator = 76, + CrstLoaderAllocatorReferences = 77, + CrstLoaderHeap = 78, + CrstMda = 79, + CrstMetadataTracker = 80, + CrstMethodDescBackpatchInfoTracker = 81, + CrstModIntPairList = 82, + CrstModule = 83, + CrstModuleFixup = 84, + CrstModuleLookupTable = 85, + CrstMulticoreJitHash = 86, + CrstMulticoreJitManager = 87, + CrstMUThunkHash = 88, + CrstNativeBinderInit = 89, + CrstNativeImageCache = 90, + CrstNativeImageEagerFixups = 91, + CrstNls = 92, + CrstNotifyGdb = 93, + CrstObjectList = 94, + CrstOnEventManager = 95, + CrstPatchEntryPoint = 96, + CrstPEImage = 97, + CrstPEImagePDBStream = 98, + CrstPendingTypeLoadEntry = 99, + CrstPinHandle = 100, + CrstPinnedByrefValidation = 101, + CrstProfilerGCRefDataFreeList = 102, + CrstProfilingAPIStatus = 103, + CrstPublisherCertificate = 104, + CrstRCWCache = 105, + CrstRCWCleanupList = 106, + CrstRCWRefCache = 107, + CrstReadyToRunEntryPointToMethodDescMap = 108, + CrstReDacl = 109, + CrstReflection = 110, + CrstReJITGlobalRequest = 111, + CrstRemoting = 112, + CrstRetThunkCache = 113, + CrstRWLock = 114, + CrstSavedExceptionInfo = 115, + CrstSaveModuleProfileData = 116, + CrstSecurityStackwalkCache = 117, + CrstSharedAssemblyCreate = 118, + CrstSigConvert = 119, + CrstSingleUseLock = 120, + CrstSpecialStatics = 121, + CrstSqmManager = 122, + CrstStackSampler = 123, + CrstStressLog = 124, + CrstStrongName = 125, + CrstStubCache = 126, + CrstStubDispatchCache = 127, + CrstStubUnwindInfoHeapSegments = 128, + CrstSyncBlockCache = 129, + CrstSyncHashLock = 130, + CrstSystemBaseDomain = 131, + CrstSystemDomain = 132, + CrstSystemDomainDelayedUnloadList = 133, + CrstThreadIdDispenser = 134, + CrstThreadpoolEventCache = 135, + CrstThreadpoolTimerQueue = 136, + CrstThreadpoolWaitThreads = 137, + CrstThreadpoolWorker = 138, + CrstThreadStaticDataHashTable = 139, + CrstThreadStore = 140, + CrstTieredCompilation = 141, + CrstTPMethodTable = 142, + CrstTypeEquivalenceMap = 143, + CrstTypeIDMap = 144, + CrstUMEntryThunkCache = 145, + CrstUMThunkHash = 146, + CrstUniqueStack = 147, + CrstUnresolvedClassLock = 148, + CrstUnwindInfoTableLock = 149, + CrstVSDIndirectionCellLock = 150, + CrstWrapperTemplate = 151, + kNumberOfCrstTypes = 152 }; #endif // __CRST_TYPES_INCLUDED @@ -205,7 +203,6 @@ int g_rgCrstLevelMap[] = 4, // CrstCOMWrapperCache 0, // CrstConnectionNameTable 17, // CrstContexts - 0, // CrstCrstCLRPrivBinderLocalWinMDPath 7, // CrstCSPCache 3, // CrstDataTest1 0, // CrstDataTest2 @@ -333,7 +330,6 @@ int g_rgCrstLevelMap[] = 7, // CrstUnresolvedClassLock 3, // CrstUnwindInfoTableLock 3, // CrstVSDIndirectionCellLock - 3, // CrstWinRTFactoryCache 3, // CrstWrapperTemplate }; @@ -364,7 +360,6 @@ LPCSTR g_rgCrstNameMap[] = "CrstCOMWrapperCache", "CrstConnectionNameTable", "CrstContexts", - "CrstCrstCLRPrivBinderLocalWinMDPath", "CrstCSPCache", "CrstDataTest1", "CrstDataTest2", @@ -492,7 +487,6 @@ LPCSTR g_rgCrstNameMap[] = "CrstUnresolvedClassLock", "CrstUnwindInfoTableLock", "CrstVSDIndirectionCellLock", - "CrstWinRTFactoryCache", "CrstWrapperTemplate", }; diff --git a/src/coreclr/src/inc/dacvars.h b/src/coreclr/src/inc/dacvars.h index dea6fa6..9f08082 100644 --- a/src/coreclr/src/inc/dacvars.h +++ b/src/coreclr/src/inc/dacvars.h @@ -191,7 +191,6 @@ DEFINE_DACVAR(ULONG, UNKNOWN_POINTER_TYPE, dac__g_TypedReferenceMT, ::g_TypedRef #ifdef FEATURE_COMINTEROP DEFINE_DACVAR(ULONG, UNKNOWN_POINTER_TYPE, dac__g_pBaseCOMObject, ::g_pBaseCOMObject) -DEFINE_DACVAR(ULONG, UNKNOWN_POINTER_TYPE, dac__g_pBaseRuntimeClass, ::g_pBaseRuntimeClass) #endif #ifdef FEATURE_ICASTABLE @@ -222,7 +221,6 @@ DEFINE_DACVAR(ULONG, SIZE_T, dac__gFCallMethods, ::gFCallMethods) DEFINE_DACVAR(ULONG, PTR_SyncTableEntry, dac__g_pSyncTable, ::g_pSyncTable) #ifdef FEATURE_COMINTEROP DEFINE_DACVAR(ULONG, UNKNOWN_POINTER_TYPE, dac__g_pRCWCleanupList, ::g_pRCWCleanupList) -DEFINE_DACVAR(ULONG, BOOL, RCWWalker__s_bIsGlobalPeggingOn, RCWWalker::s_bIsGlobalPeggingOn) #endif // FEATURE_COMINTEROP #ifndef TARGET_UNIX diff --git a/src/coreclr/src/inc/winrt/paraminstanceapi.h b/src/coreclr/src/inc/winrt/paraminstanceapi.h deleted file mode 100644 index 9f65aff..0000000 --- a/src/coreclr/src/inc/winrt/paraminstanceapi.h +++ /dev/null @@ -1,1756 +0,0 @@ -// 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. - -/*************************************************************** - -* -* Portions of this header fall under the following -* copyrights and/or licenses: -* -* rfc4122 and supporting functions -* * Algorithm from RFC 4122 - A Universally Unique IDentifier (UUID) URN Namespace -* * By Paul J. Leach, Michael Mealling and Rich Sals, July 2005. -* * -* * This function is adapted from the routines in the document -* * uuid_create_sha1_from_name and format_uuid_v3or5 -* * -* * -* * Copyright (c) 1990- 1993, 1996 Open Software Foundation, Inc. -* * Copyright (c) 1989 by Hewlett-Packard Company, Palo Alto, Ca. & -* * Digital Equipment Corporation, Maynard, Mass. -* * Copyright (c) 1998 Microsoft. -* * To anyone who acknowledges that this file is provided "AS IS" -* * without any express or implied warranty: permission to use, copy, -* * modify, and distribute this file for any purpose is hereby -* * granted without fee, provided that the above copyright notices and -* * this notice appears in all source code copies, and that none of -* * the names of Open Software Foundation, Inc., Hewlett-Packard -* * Company, Microsoft, or Digital Equipment Corporation be used in -* * advertising or publicity pertaining to distribution of the software -* * without specific, written prior permission. Neither Open Software -* * Foundation, Inc., Hewlett-Packard Company, Microsoft, nor Digital -* * Equipment Corporation makes any representations about the -* * suitability of this software for any purpose. -* * -*/ - -#ifdef _MSC_VER -#pragma once -#endif /* _MSC_VER */ - -#ifndef WINRT_PARAMINSTANCEAPI_H -#define WINRT_PARAMINSTANCEAPI_H - -#ifdef __cplusplus - -#ifdef _MSC_VER -#pragma warning( push ) -#pragma warning( disable : 4180 ) // qualifier applied to function type has no meaning; ignored -#endif - -#include -#include -#include -#include -#include -#include -#include - -//#ifdef _MSC_VER -//#include -//#else -//#include -//#endif - -#ifndef WINRT_PARAMINSTANCE_NOCRYPT_SHA1 -#include -#endif - -#ifdef _MSC_VER -#pragma push_macro("CHKHR") -#pragma push_macro("CHKNT") -#endif - -namespace Ro { namespace detail { - - // - // Debugging aide. Set breakpoint on _FailedHR - // to see HRESULT propagation. - // - #ifdef DEBUG - inline HRESULT NOINLINE _FailedHR(HRESULT hr) { static HRESULT _hr = hr; return hr; } - #else - inline HRESULT _FailedHR(HRESULT hr) { return hr; } - #endif -}} - -#undef CHKHR -// -// Call HRESULT returning code and propagate any errors. -// Note: only use in code that is exception-safe / uses RAII. -// -#define CHKHR(expr) \ - { HRESULT _zzhr; \ - _zzhr = expr; \ - if (FAILED(_zzhr)) return Ro::detail::_FailedHR(_zzhr); } - -#undef CHKNT -// -// Call NTSTATUS returning code and propagate any errors, as HRESULTs. -// Note: -// - only use in code that is exception-safe / uses RAII / RRID. -// - HRESULT_FROM_NT does safely convert STATUS_SUCCESS into -// a SUCCEEDED hr. -// -#define CHKNT(expr) \ - CHKHR( HRESULT_FROM_NT( expr ) ) - -namespace Ro { namespace detail { - - // - // Runtime check for an invariant. This check executes in release builds. - // - - inline HRESULT Verify(bool invariant, HRESULT defaultHr = E_UNEXPECTED) - { - if (!invariant) - { - CHKHR(defaultHr); - } - return S_OK; - } -}} - - -extern "C" { - - -// sha1 adaptor -// create hash instance - -HRESULT _RoSha1Create( - __out void** handle); - - -// sha1 adaptor -// append more data to the input stream - -HRESULT _RoSha1AppendData( - __in void* handle, - __in size_t numBytes, - __in_bcount(numBytes) const void* data); - - -// sha1 adaptor -// return the first 16 bytes of SHA1 hash - -HRESULT _RoSha1Finish( - __in void* handle, - __out BYTE (*hashValue)[20]); - - -// sha1 adaptor -// free this instance - -void _RoSha1Release(__in void* handle); - -} - -struct IRoSimpleMetaDataBuilder; -struct IRoMetaDataLocator; - -// The 'detail' namespace includes implementation details that -// are subject to change without notice. -namespace Ro { namespace detail -{ - struct SimpleMetaDataBuffer; -}} - - -// -// Purpose: -// Given a parameterized type instance name and metadata, -// computes the IID for that instance. -// -// Parameters: -// -// nameElementCount -// number of elements in nameElements -// nameElements -// a parsed WinRt type name, as would be returned by RoParseTypeName. -// Eg: ["W.F.C.IVector`1", "N1.N2.IFoo"] -// metaDataLocator -// A callback to use for resolving metadata. -// -// An implementation could, for example, forward all calls -// to RoGetMetaData, then passing the results to -// RoWriteImporterToPushSimpleMetaData. As RoGetMetadata does -// not cache results, such an implementation would be inefficient. -// A better implementation will cache the results to RoGetMetaData, -// as appropriate. -// -// The Locator helper function can be used to wrap a lambda -// expression, or function pointer. eg: -// RoGetParameterizedTypeInstanceIID( -// ..., -// Locate([&](PCWSTR* name, IRoSimpleMetaDataBuilder& push){...}), -// ...); -// iid -// out param. Returns the iid for the parameterized type specified -// by nameElements -// extra -// out param. returns a handle that holds extra information about the -// IID result, for diagnostic purposes. If this handle is not desired, -// provide nullptr instead. -// -// Notes: -// - This function is stateless. IRoMetaDataLocator will not be preserved -// between calls. -// - This function does not perform deep semantic analysis. For instance, -// if IRoSimpleMetaDataBuilder specifies that a struct contains an interface pointer, -// this API will return success, even though such metadata is semantically -// invalid. The value of the IID returned is unspecified in such cases. -// - This function does introduce reentrancy. Its implementation -// of IRoSimpleMetaDataBuilder may make reentrant calls to IRoMetaDataLocator. -// - If a call to IRoSimpleMetaDataBuilder fails, this function will return that -// failure code. -// - - -DECLARE_HANDLE(ROPARAMIIDHANDLE); - -inline HRESULT RoGetParameterizedTypeInstanceIID( - UINT32 nameElementCount, - __in_ecount(nameElementCount) PCWSTR* nameElements, - __in const IRoMetaDataLocator& metaDataLocator, - __out GUID* iid, - __deref_opt_out ROPARAMIIDHANDLE* pExtra = nullptr); - -// Frees the 'extra' handle allocated -// by RoGetParameterizedTypeInstanceIID -inline void RoFreeParameterizedTypeExtra(__in ROPARAMIIDHANDLE extra); - -// Fetches the TypeSignature used to compute the IID by the last -// call to RoGetParameterizedTypeInstanceIID on this extra handle. -// The string contains ASCII code only, and the string is valid -// until RoFreeParameterizedTypeExtra is called on the extra pointer. -inline PCSTR RoParameterizedTypeExtraGetTypeSignature(__in ROPARAMIIDHANDLE extra); - -namespace Ro { namespace detail -{ - - // private type used in helper function - - template - struct _Locator; -}} // namespace Ro::detail - -namespace Ro -{ - - // helper function to create IRoMetaDataLocator from lambda expression - - template - Ro::detail::_Locator Locator(const Fn& fn); -} // namespace Ro - - -// -// Purpose: -// Destination for IRoMetaDataLocator::Locate to write parsed metadata to. -// 'Locate' should set the appropriate Windows Runtime metadata information gleaned -// from Windows Runtime metadata file, or other appropriate source. -// -// Notes: -// - Methods for base types and COM interfaces (eg, Int32 and IInspectable -// respectively) are not needed -- RoGetParameterizedTypeInstanceIID already -// knows the WinRT base type names, so will not invoke IMetDataLocator -// to discover them. -// - This is not a COM interface. It does not derive from IUnknown. -// - -struct IRoSimpleMetaDataBuilder -{ - - // Notes: - // IInspectable and other non-WinRT interfaces are not permissible. - // Not for use with parameterized type instances. See SetParameterizedInterface - - STDMETHOD(SetWinRtInterface)( - GUID iid) = 0; - - - // Notes: - // Not for use with parameterized type instances. See SetParameterizedDelegate - - STDMETHOD(SetDelegate)( - GUID iid) = 0; - - - // Notes: - // Call this method when an interface group has a default interface - // that is a non-parametric type. - - STDMETHOD(SetInterfaceGroupSimpleDefault)( - PCWSTR name, - PCWSTR defaultInterfaceName, - __in_opt const GUID* defaultInterfaceIID) = 0; - - - // Notes: - // Call this method when an interface group has a parameterized - // interface as its default interface. - - STDMETHOD(SetInterfaceGroupParameterizedDefault)( - PCWSTR name, - UINT32 elementCount, - __in_ecount(elementCount) PCWSTR* defaultInterfaceNameElements) = 0; - - STDMETHOD(SetRuntimeClassSimpleDefault)( - PCWSTR name, - PCWSTR defaultInterfaceName, - __in_opt const GUID* defaultInterfaceIID) = 0; - - STDMETHOD(SetRuntimeClassParameterizedDefault)( - PCWSTR name, - UINT32 elementCount, - __in_ecount(elementCount) PCWSTR* defaultInterfaceNameElements) = 0; - - STDMETHOD(SetStruct)( - PCWSTR name, - UINT32 numFields, - __in_ecount(numFields) PCWSTR* fieldTypeNames) = 0; - - STDMETHOD(SetEnum)( - PCWSTR name, - PCWSTR baseType) = 0; - - - // Notes: - // This is only for the 'non-instantiated' parameterized interface itself - - // instances are handled by RoGetParameterizedTypeInstanceIID, and the - // caller need not parse them. - - STDMETHOD(SetParameterizedInterface)( - GUID piid, - UINT32 numArgs) = 0; - - STDMETHOD(SetParameterizedDelegate)( - GUID piid, - UINT32 numArgs) = 0; -}; - - -// -// Purpose: -// Callback for resolving metadata. -// - -struct IRoMetaDataLocator -{ - - // - // Parameters: - // nameElement - // a metadata typeref name to resolve. - // Eg: "N1.N2.IFoo", or "W.F.C.IVector`1". - // pushMetaData - // data sink for providing information about the - // type information for nameElement - // - - STDMETHOD(Locate)( - PCWSTR nameElement, - __in IRoSimpleMetaDataBuilder& metaDataDestination - ) const = 0; -}; - -namespace Ro { namespace detail { - - - // - // helper function, moves range of elements - // - - template - void _VecMoveRange( - __in_ecount(size) T* dst, - __in_ecount(size) T* src, - size_t size) - { - for (size_t i = 0; i != size; ++i) - { - dst[i] = static_cast(src[i]); - } - } - - // - // specializations to move strings more efficiently - // - - inline void _VecMoveRange( - __in_ecount(size) char* dst, - __in_ecount(size) char* src, - size_t size) - { - errno_t err = memcpy_s(dst, size*sizeof(*dst), src, size*sizeof(*dst)); - NT_ASSERT(!err); - (void)err; - } - inline void _VecMoveRange( - __in_ecount(size) wchar_t* dst, - __in_ecount(size) wchar_t* src, - size_t size) - { - errno_t err = memcpy_s(dst, size*sizeof(*dst), src, size*sizeof(*dst)); - NT_ASSERT(!err); - (void)err; - } - - - // - // helper function, moves range of elements - // - - template - void _VecCopyRange( - __in_ecount(size) T* dst, - __in_ecount(size) const T* src, - size_t size) - { - for (size_t i = 0; i != size; ++i) - { - dst[i] = src[i]; - } - } - - // - // specializations to move strings more efficiently - // - - inline void _VecCopyRange( - __in_ecount(size) char* dst, - __in_ecount(size) const char* src, - size_t size) - { - errno_t err = memcpy_s(dst, size*sizeof(*dst), const_cast(src), size*sizeof(*dst)); - NT_ASSERT(!err); - (void)err; - } - inline void _VecCopyRange( - __in_ecount(size) wchar_t* dst, - __in_ecount(size) const wchar_t* src, - size_t size) - { - errno_t err = memcpy_s(dst, size*sizeof(*dst), const_cast(src), size*sizeof(*dst)); - NT_ASSERT(!err); - (void)err; - } - - // - // Single-owner smart pointer for arrays - // - - template - struct ArrayHolder - { - ArrayHolder() : _value(NULL) - { - } - T* Value() const - { - return _value; - } - T*& Value() - { - return _value; - } - T* Detach() - { - T* tmp = _value; - _value = NULL; - return tmp; - } - ~ArrayHolder() - { - delete[] _value; - } - - private: - T* _value; - }; - - // - // Single-owner smart pointer for object pointer - // - - template - struct ElementHolder - { - ElementHolder() : _value(NULL) - { - } - T* operator->() const - { - return _value; - } - T* Value() const - { - return _value; - } - T*& Value() - { - return _value; - } - T* Detach() - { - T* tmp = _value; - _value = NULL; - return tmp; - } - ~ElementHolder() - { - delete _value; - } - - private: - T* _value; - }; - - - - // - // simple vector, with small vector optimization - // T - must be default constructable and movable. - // const input overload of AppendN requires copyable. - // FixedBufSize - number of bytes to use for small array - // optimization, to avoid heap allocation in case of - // small vectors. Defaults to at least one element, - // otherwise the largest value such that <= 64 bytes - // are used. - // - - template < - typename T, - size_t FixedBufSize = 0 - > - class Vec - { - private: - static const size_t _fixedBufSize = - FixedBufSize/sizeof(T) - ? FixedBufSize/sizeof(T) - : (((64/sizeof(T)) > 0) ? (64/sizeof(T)) - : 1); - public: - Vec() : - _size(0), - _cap(_countof(_fixedBuf)), - _buf(_fixedBuf) - { - } - - - // Appends an element, or a default value if one - // it not specified. If called with an rvalue, - // it uses move assignment instead of copy. - - HRESULT Append(T value = T()) - { - if (_cap - _size < 1) - { - CHKHR(_Grow()); - } - _buf[_size] = static_cast(value); - ++_size; - - return S_OK; - } - - // Moves elements (move assignment) into array. - - HRESULT MoveN(__in_ecount(n) T* values, size_t n) - { - if (_cap - _size < n) - { - CHKHR(_Grow(n - (_cap - _size))); - } - _VecMoveRange(_buf + _size, values, n); - _size += n; - - return S_OK; - } - - - // Appends elements. Does not invoke move assignment. - - HRESULT AppendN(__in_ecount(n) const T* values, size_t n) - { - if (_cap - _size < n) - { - CHKHR(_Grow(n - (_cap - _size))); - } - _VecCopyRange(_buf + _size, values, n); - _size += n; - - return S_OK; - } - - HRESULT Pop() - { - CHKHR(Verify( _size > 0 )); - --_size; - return S_OK; - } - - HRESULT Resize(size_t newSize) - { - if (_cap < newSize) - { - CHKHR(_Grow(newSize - _cap)); - } - _size = newSize; - return S_OK; - } - - size_t Size() const - { - return _size; - } - - T& operator[](size_t index) - { - NT_ASSERT(index < _size); - return _buf[index]; - } - - T& Last() - { - return (*this)[_size-1]; - } - - ~Vec() - { - if (_buf != _fixedBuf) - { - delete[] _buf; - } - } - - private: - - // - // growth factor (does not check for overflow) -- returns amount to grow by - // - - static size_t _GrowthIncrement(size_t n) - { - return n / 2; - } - - HRESULT _Grow(size_t byAtLeast = 4) - { - size_t increase = _GrowthIncrement(_cap); - if (increase < byAtLeast) - { - increase = byAtLeast; - } - size_t newCap = _cap + increase; - if (newCap <= _cap) - { - CHKHR(E_OUTOFMEMORY); - } - ArrayHolder newBuf; - - void* p = (newBuf.Value() = new (std::nothrow) T[newCap]); - if (!p) - { - CHKHR(E_OUTOFMEMORY); - } - - _VecMoveRange( newBuf.Value(), _buf, _size ); - - if (_buf != _fixedBuf) - { - delete _buf; - } - _buf = newBuf.Detach(); - _cap = newCap; - - return S_OK; - } - - size_t _size; - size_t _cap; - T* _buf; - T _fixedBuf[_fixedBufSize]; - }; - - struct SimpleMetaDataBuilder : IRoSimpleMetaDataBuilder - { - public: - SimpleMetaDataBuilder(SimpleMetaDataBuffer& buffer, const IRoMetaDataLocator& locator) - : _buffer(&buffer), _locator(&locator), _invoked(false) - { - } - IFACEMETHOD(SetWinRtInterface)(GUID iid); - IFACEMETHOD(SetDelegate)(GUID iid); - IFACEMETHOD(SetInterfaceGroupSimpleDefault)(PCWSTR name, PCWSTR defaultInterfaceName, __in_opt const GUID *defaultInterfaceIID); - IFACEMETHOD(SetInterfaceGroupParameterizedDefault)(PCWSTR name, UINT32 elementCount, __in_ecount(elementCount) PCWSTR *defaultInterfaceNameElements); - IFACEMETHOD(SetRuntimeClassSimpleDefault)(PCWSTR name, PCWSTR defaultInterfaceName, __in_opt const GUID *defaultInterfaceIID); - IFACEMETHOD(SetRuntimeClassParameterizedDefault)(PCWSTR name, UINT32 elementCount, __in_ecount(elementCount) PCWSTR *defaultInterfaceNameElements); - IFACEMETHOD(SetStruct)(PCWSTR name, UINT32 numFields, __in_ecount(numFields) PCWSTR *fieldTypeNames); - IFACEMETHOD(SetEnum)(PCWSTR name, PCWSTR baseType); - IFACEMETHOD(SetParameterizedInterface)(GUID piid, UINT32 numArgs); - IFACEMETHOD(SetParameterizedDelegate)(GUID piid, UINT32 numArgs); - - - // Runs the locating process for a parameterized type. - // Notes: - // _buffer->_nestingLevel is used to determine the number of - // arguments left to consume for nested parameterized types. - - HRESULT SendArguments(UINT32 nameElementCount, __in_ecount(nameElementCount) PCWSTR *nameElements); - - private: - - - // Writes the type signature for the type 'name' - // Notes: - // - If a builtin type, writes the type directly. - // - Otherwise, uses the IRoMetaDataLocator to - // write the type signature into _buffer - // - As the sole function to call - // IRoMetaDataLocator, it also performs the check - // on recursion depth bounds. - - HRESULT _WriteType(PCWSTR name); - - - // The tail portion of IG and RC formats is the same. This - // function implements the shared portion of that format. - - HRESULT _CommonInterfaceGroupSimple(PCWSTR name, PCWSTR defaultInterfaceName, __in_opt const GUID *defaultInterfaceIID); - - - // Called at the beginning of every 'Set' method. Set must only be called once. - - HRESULT _OnSet(); - - - // Called at the end of every 'Set' method, only if successful. - - void _Completed(); - - static char _AsciiLower(char ch) - { - if ('A' <= ch && ch <= 'Z') - { - return ch + ('a' - 'A'); - } - else - { - return ch; - } - } - - - // Writes a guid into the type signature being built, in lower case. - - HRESULT _WriteGuid(const GUID& iid); - HRESULT _WriteString(PCSTR str); - HRESULT _WriteChar(char c); - HRESULT _WriteWideString(PCWSTR str); - - SimpleMetaDataBuilder(); - SimpleMetaDataBuilder(const SimpleMetaDataBuilder&); - void operator=(const SimpleMetaDataBuilder&); - - SimpleMetaDataBuffer* _buffer; - const IRoMetaDataLocator* _locator; - bool _invoked; - }; - - - // If the type string describes a built-in type, modifies - // this instance to use builtin type table entry instead of name. - - inline bool _IsBuiltin(__in PCWSTR name, __out PCSTR * typeSignature) - { - *typeSignature = nullptr; - - struct BuiltinEntry { PCWSTR name; PCSTR typeSignature; }; - static const BuiltinEntry entries[] = { - - { L"UInt8", "u1" }, - { L"Int16", "i2" }, - { L"UInt16", "u2" }, - { L"Int32", "i4" }, - { L"UInt32", "u4" }, - { L"Int64", "i8" }, - { L"UInt64", "u8" }, - { L"Single", "f4" }, - { L"Double", "f8" }, - { L"Boolean", "b1" }, - { L"Char16", "c2" }, - { L"String", "string" }, - { L"Guid", "g16" }, - { L"Object", "cinterface(IInspectable)" }, - }; - for (const BuiltinEntry* tip = entries; - tip != &entries[_countof(entries)]; - ++tip) - { - if (wcscmp(tip->name, name) == 0) - { - *typeSignature = tip->typeSignature; - return true; - } - } - - // if not found, assume is a normal type name - - return false; - } - - - // Linked list (stack allocated) of type resolution calls, - // used to detect if an InterfaceGroup/RuntimeClass type - // signature depends on itself. In that case, we use "*" - // in the type signature instead of recurring further. - - struct ResolutionPathEntry - { - ResolutionPathEntry* _next; - PCWSTR _typeName; - - ResolutionPathEntry(PCWSTR typeName) - : _next(nullptr) - , _typeName(typeName) - { - } - }; - - inline void Push(ResolutionPathEntry*& top, ResolutionPathEntry* item) - { - item->_next = top; - top = item; - } - inline HRESULT Pop(ResolutionPathEntry*& top) - { - if (!top) - { - return E_UNEXPECTED; - } - top = top->_next; - return S_OK; - } - - - // Holds metadata state that is shared between RoGetParamInstanceIID and SimpleMetaDataBuilder - - struct SimpleMetaDataBuffer - { - SimpleMetaDataBuffer() - { - Clear(); - } - - // reset all tables - void Clear() - { - _recursionDepth = 0; - _topLevelTypes = 0; - _resolutionPath = nullptr; - _outputStream.Resize(0); - } - - static const size_t _maxTypeName = 256; - - - // Estimate of 'reasonable' level of Interface Group / Runtime - // Class / Parameterized Type nesting. - - static const size_t _maxRecursionDepth = 64; - - Vec _outputStream; - ResolutionPathEntry* _resolutionPath; - - - // RAII object, places an item on the resolution path, and pops it on destruction - - class ResolutionPathGuard - { - private: - ResolutionPathEntry _entry; - SimpleMetaDataBuffer* _buffer; - - public: - ResolutionPathGuard(PCWSTR typeName, SimpleMetaDataBuffer* buffer) - : _buffer(buffer) - , _entry(typeName) - { - Push(buffer->_resolutionPath, &_entry); - } - ~ResolutionPathGuard() - { - HRESULT hr = Pop(_buffer->_resolutionPath); - NT_ASSERT(SUCCEEDED(hr)); - (void)hr; - } - }; - - - // Searches the resolution path for 'name' returning true if exists - - bool ExistsCycle(PCWSTR typeName) - { - for (auto pTip = _resolutionPath; pTip; pTip = pTip->_next) - { - if (wcscmp(typeName, pTip->_typeName) == 0) - { - return true; - } - } - return false; - } - - - // Indicates the nesting level of compound types, used - // to properly balance parenthesis on parameterized types, - // and used to bound recursion depth. - // - // - Pinterfaces - // : push 'numArgs' on to _nestingLevel - // - A compound type that doesn't know number of arguments - // eg, RoGetParameterizedInstanceIID arguments, or - // SetIG..Parameterized - // : will 0) note nesting level - // 1) iterate calling Locate on the compound arguments. - // 2) the above should cause exactly one push of _nestingLevel - // 3) reduce nesting level back to original nesting level, - // inserting the difference in closing parens - // - Compound types that do know number of arguments (eg SetStruct) - // : will 1) increase nesting level by 1 - // 2) iterate calling Locate on arguments - // 3) decrease nesting level again - // - // - - Vec _nestedArgs; - - // topLevelTypes should be incremented once, by the initial - // parameterized type, then never again. - - size_t _topLevelTypes; - size_t _recursionDepth; - }; -}} // namespace Ro::detail - -namespace Ro { namespace detail -{ - template - struct _Locator : IRoMetaDataLocator - { - Fn _fn; - - _Locator(const Fn& fn) - : _fn(fn) - { - } - - IFACEMETHOD(Locate)( - PCWSTR name, - IRoSimpleMetaDataBuilder& pushMetaData) const - { - return _fn(name, pushMetaData); - } - }; -}} // namespace Ro::detail - -namespace Ro -{ - template - Ro::detail::_Locator Locator(const Fn& fn) - { - return Ro::detail::_Locator(fn); - } -} - -namespace Ro { namespace detail -{ - - // Figure out if we're compiling for a big- or little-endian machine. - - inline bool BigEndian() - { - unsigned long n = 0xff000000L; - - return 0 != *reinterpret_cast(&n); - } - - - // HostToNetworkLong converts a 32-bit long to network byte order - - inline ULONG HostToNetworkLong(ULONG hostlong) - { - if (BigEndian()) - return hostlong; - else - return ( (hostlong >> 24) & 0x000000FFL) | - ( (hostlong >> 8) & 0x0000FF00L) | - ( (hostlong << 8) & 0x00FF0000L) | - ( (hostlong << 24) & 0xFF000000L); - } - - - // HostToNetworkLong converts a 16-bit short to network byte order - - inline USHORT HostToNetworkShort(USHORT hostshort) - { - if (BigEndian()) - return hostshort; - else - return ((hostshort >> 8) & 0x00FF) | ((hostshort << 8) & 0xFF00); - } - - - // NetworkToHostLong converts a 32-bit long to local host byte order - - inline ULONG NetworkToHostLong(ULONG netlong) - { - if (BigEndian()) - return netlong; - else - return ( (netlong >> 24) & 0x000000FFL) | - ( (netlong >> 8) & 0x0000FF00L) | - ( (netlong << 8) & 0x00FF0000L) | - ( (netlong << 24) & 0xFF000000L); - } - - - // NetworkToHostShort converts a 16-bit short to local host byte order - - inline USHORT NetworkToHostShort(USHORT netshort) - { - if (BigEndian()) - return netshort; - else - return ((netshort >> 8) & 0x00FF) | ((netshort << 8) & 0xFF00); - } - - - // smart pointer for Sha1 handle - - struct Sha1Holder - { - Sha1Holder() : _handle(nullptr) - { - } - void*& Value() - { - return _handle; - } - ~Sha1Holder() - { - if (_handle) - { - _RoSha1Release(_handle); - } - } - private: - void* _handle; - }; - - - - // - // Computes the rfc4122 v5 UUID from GUID,name pair. - // - // Notes: - // - see copyright at beginning of file. - // - - inline HRESULT - GuidFromName( - __in const GUID& guidNamespace, - __in_bcount(dwcbSize) const void* pbName, - __in DWORD dwcbSize, - __out GUID* pGuid) - { - Sha1Holder sha1; - - CHKHR( _RoSha1Create(&sha1.Value()) ); - { - GUID networkOrderGuidNamespace = guidNamespace; - - // Put name space ID in network byte order so it hashes the same - // no matter what endian machine we're on - - if (!BigEndian()) - { - networkOrderGuidNamespace.Data1 = HostToNetworkLong (networkOrderGuidNamespace.Data1); - networkOrderGuidNamespace.Data2 = HostToNetworkShort(networkOrderGuidNamespace.Data2); - networkOrderGuidNamespace.Data3 = HostToNetworkShort(networkOrderGuidNamespace.Data3); - } - CHKHR( _RoSha1AppendData(sha1.Value(), sizeof(networkOrderGuidNamespace), reinterpret_cast(&networkOrderGuidNamespace)) ); - } - CHKHR( _RoSha1AppendData(sha1.Value(), dwcbSize, pbName) ); - - { - BYTE sha1Result[20]; - CHKHR( _RoSha1Finish(sha1.Value(), &sha1Result) ); - - errno_t err = memcpy_s(pGuid, sizeof(GUID), &sha1Result[0], sizeof(GUID)); - CHKHR(Verify( 0 == err )); - - - // Restore the byte order - - if (!BigEndian()) - { - pGuid->Data1 = NetworkToHostLong (pGuid->Data1); - pGuid->Data2 = NetworkToHostShort(pGuid->Data2); - pGuid->Data3 = NetworkToHostShort(pGuid->Data3); - } - - - // set version number - // 1: clear version number nibble - // 2: set version 5 = name-based SHA1 - - pGuid->Data3 &= 0x0FFF; - pGuid->Data3 |= (5 << 12); - - - // set variant field by clearing variant bits. - - pGuid->Data4[0] &= 0x3F; - pGuid->Data4[0] |= 0x80; - } - return S_OK; - } -}} // namespace Ro::detail - -inline HRESULT RoGetParameterizedTypeInstanceIID( - UINT32 nameElementCount, - __in_ecount(nameElementCount) PCWSTR* nameElements, - __in const IRoMetaDataLocator& metaDataLocator, - __out GUID* iid, - __deref_opt_out ROPARAMIIDHANDLE* pExtra) -{ - using namespace Ro::detail; - memset(iid, 0, sizeof(*iid)); - - SimpleMetaDataBuffer reserveBuffer; - SimpleMetaDataBuffer *pBuffer = &reserveBuffer; - - // if user wishes to hold on to the result value, - // dynamically allocate this buffer. - if (pExtra) - { - pBuffer = new (std::nothrow) SimpleMetaDataBuffer; - *pExtra = static_cast(static_cast(pBuffer)); - } - SimpleMetaDataBuffer& buffer = *pBuffer; - SimpleMetaDataBuilder builder(*pBuffer, metaDataLocator); - - // send initial arguments - CHKHR(builder.SendArguments(nameElementCount, nameElements)); - - // verify that precisely one type was resolved, to completion. - CHKHR(Verify(buffer._topLevelTypes == 1 - && buffer._nestedArgs.Size() == 0, - E_INVALIDARG)); - - // compute type signature hash - static const GUID guidPinterfaceNamespace - = { 0x11f47ad5, 0x7b73, 0x42c0, { 0xab, 0xae, 0x87, 0x8b, 0x1e, 0x16, 0xad, 0xee }}; - - CHKHR(Ro::detail::Verify( buffer._outputStream.Size() <= DWORD(-1) )); - - // null terminate - CHKHR( buffer._outputStream.Append('\0') ); - - - // - // Unit test logging, to verify proper signatures - // - #ifdef UNITTEST_TRACE - { - CHKHR( UNITTEST_TRACE("type signature", &buffer._outputStream[0]) ); - } - #endif - - - CHKHR( GuidFromName(guidPinterfaceNamespace, - &buffer._outputStream[0], - DWORD(buffer._outputStream.Size() - 1), // does not include terminator - iid) ); - return S_OK; -} - -inline void RoFreeParameterizedTypeExtra(__in ROPARAMIIDHANDLE extra) -{ - using namespace Ro::detail; - delete static_cast(static_cast(extra)); -} -inline PCSTR RoParameterizedTypeExtraGetTypeSignature(__in ROPARAMIIDHANDLE extra) -{ - using namespace Ro::detail; - SimpleMetaDataBuffer* pBuffer = static_cast(static_cast(extra)); - - return &pBuffer->_outputStream[0]; -} - -namespace Ro { namespace detail -{ - - inline HRESULT SimpleMetaDataBuilder::_WriteType(PCWSTR name) - { - PCSTR builtInName = nullptr; - SimpleMetaDataBuilder builder(*_buffer, *_locator); - - if (_IsBuiltin(name, &builtInName)) - { - CHKHR(builder._OnSet()); - CHKHR(builder._WriteString(builtInName)); - builder._Completed(); - } - else - { - size_t newDepth = ++_buffer->_recursionDepth; - size_t pinterfaceNesting = _buffer->_nestedArgs.Size(); - if (newDepth + pinterfaceNesting > _buffer->_maxRecursionDepth) - { - - // Terminate recursion; bounds call stack consumption - - CHKHR(E_UNEXPECTED); - } - CHKHR(_locator->Locate(name, builder)); - - // Note, buffers aren't reusable, so it's fine that we don't - // unwind this value on return. Also note, we do not unwind - // this value if the user provides inconsistent data either - // (eg, if they provide only 1 argument to a 2 parameter - // parameterized type). - - --_buffer->_recursionDepth; - } - return S_OK; - } - - inline HRESULT SimpleMetaDataBuilder::_OnSet() - { - if (_invoked) - { - CHKHR(E_INVALIDARG); - } - _invoked = true; - - - // Reduce the number of arguments left for this compound type. - - if(_buffer->_nestedArgs.Size() > 0) - { - --(_buffer->_nestedArgs.Last()); - } - else - { - - // Increase number of top level types in signature - // string. (should never exceed one) - - ++_buffer->_topLevelTypes; - } - - return S_OK; - } - - inline void SimpleMetaDataBuilder::_Completed() - { - } - inline HRESULT SimpleMetaDataBuilder::SendArguments(UINT32 nameElementCount, __in_ecount(nameElementCount) PCWSTR *nameElements) - { - CHKHR(Verify(nameElementCount > 0)); - - CHKHR(Verify(_buffer->_nestedArgs.Size() <= UINT32(-1))); - UINT32 previousLevel = UINT32(_buffer->_nestedArgs.Size()); - - for (UINT32 i = 0; i < nameElementCount; ++i) - { - CHKHR(_WriteType(nameElements[i])); - - - // Close any nested parameterized types that are complete - - while (_buffer->_nestedArgs.Size() > previousLevel - && _buffer->_nestedArgs.Last() == 0) - { - CHKHR(_buffer->_nestedArgs.Pop()); - CHKHR(_WriteChar(')')); - } - - // insert separator between parameterized type arguments - - CHKHR(_WriteChar(';')); - } - - // remove final separator - - CHKHR(_buffer->_outputStream.Pop()); - - - // Verify that all the arguments were consumed. - - CHKHR(Verify(_buffer->_nestedArgs.Size() == previousLevel, - E_INVALIDARG)); - return S_OK; - } - - inline HRESULT SimpleMetaDataBuilder::_WriteGuid(const GUID& iid) - { - static const size_t guidStringLength = _countof("{11223344-1122-1122-1122-334455667788}") - 1; - WCHAR tmpString[guidStringLength+1]; - - int numWritten = StringFromGUID2(iid, tmpString, guidStringLength + 1); - CHKHR(Verify( numWritten == guidStringLength + 1 )); - NT_ASSERT( numWritten == guidStringLength + 1 ); - - size_t offset = _buffer->_outputStream.Size(); - CHKHR(Verify( offset + guidStringLength > offset )) - CHKHR( _buffer->_outputStream.Resize(offset + guidStringLength) ); - char* writePtr = &_buffer->_outputStream[offset]; - - - // All characters are ascii. Just truncate. - - for(size_t i = 0; i < guidStringLength; ++i) - { - writePtr[i] = _AsciiLower(char(tmpString[i])); - } - return S_OK; - } - inline HRESULT SimpleMetaDataBuilder::_WriteString(PCSTR str) - { - CHKHR( _buffer->_outputStream.AppendN(str, strlen(str)) ); - return S_OK; - } - inline HRESULT SimpleMetaDataBuilder::_WriteChar(char c) - { - CHKHR( _buffer->_outputStream.Append(c) ); - return S_OK; - } - inline HRESULT SimpleMetaDataBuilder::_WriteWideString(PCWSTR str) - { - size_t len = wcslen(str); - size_t offset = _buffer->_outputStream.Size(); - int written; - - - // provision enough space for conversion to take place - - size_t provision = len + 1; - for(;;) - { - CHKHR( _buffer->_outputStream.Resize(offset+provision)); - char* writePtr = &_buffer->_outputStream[offset]; - - CHKHR(Verify(len <= INT_MAX)); - CHKHR(Verify(provision <= INT_MAX)); - - written = WideCharToMultiByte( - CP_UTF8, - 0, - str, - int(len), - writePtr, - int(provision), - nullptr, - nullptr - ); - - if (written > 0) - { - break; - } - else if (GetLastError() != ERROR_INSUFFICIENT_BUFFER) - { - CHKHR(HRESULT_FROM_WIN32(GetLastError())); - } - else - { - provision *= 2; - CHKHR(Verify( offset + provision > offset )); - } - } - - // reduce size to reflect number of characters actually written. - // Note that since we specified string length, no null terminator - // was injected, so we don't have to remove it. - - CHKHR( _buffer->_outputStream.Resize(offset+written) ); - - return S_OK; - } - - inline __override HRESULT STDMETHODCALLTYPE SimpleMetaDataBuilder::SetWinRtInterface( - GUID iid) - { - CHKHR(_OnSet()); - - CHKHR(_WriteGuid(iid)); - - _Completed(); - return S_OK; - } - - inline __override HRESULT STDMETHODCALLTYPE SimpleMetaDataBuilder::SetDelegate( - GUID iid) - { - CHKHR(_OnSet()); - - CHKHR(_WriteString("delegate(")); - CHKHR(_WriteGuid(iid)); - CHKHR(_WriteChar(')')); - - _Completed(); - return S_OK; - } - - inline HRESULT SimpleMetaDataBuilder::_CommonInterfaceGroupSimple( - PCWSTR name, - PCWSTR defaultInterfaceName, - __in_opt const GUID * defaultInterfaceIID) - { - CHKHR(_WriteWideString(name)); - CHKHR(_WriteChar(';')); - - - // InterfaceGroups and RuntimeClasses take one nested argument - - CHKHR(_buffer->_nestedArgs.Append(1)); - if (!defaultInterfaceIID) - { - CHKHR(_WriteType(defaultInterfaceName)); - } - else - { - - // complete the type signature immediately; no nested - // call needed to resolve the interface. - - SimpleMetaDataBuilder builder(*_buffer, *_locator); - CHKHR(builder.SetWinRtInterface(*defaultInterfaceIID)) - } - CHKHR(_WriteChar(')')); - CHKHR(_buffer->_nestedArgs.Pop()); - return S_OK; - } - - inline __override HRESULT STDMETHODCALLTYPE SimpleMetaDataBuilder::SetInterfaceGroupSimpleDefault( - PCWSTR name, - PCWSTR defaultInterfaceName, - __in_opt const GUID* defaultInterfaceIID) - { - CHKHR(_OnSet()); - - CHKHR(_WriteString("ig(")); - CHKHR(_CommonInterfaceGroupSimple(name, defaultInterfaceName, defaultInterfaceIID)); - - _Completed(); - return S_OK; - } - - - inline __override HRESULT STDMETHODCALLTYPE SimpleMetaDataBuilder::SetInterfaceGroupParameterizedDefault( - PCWSTR name, - UINT32 elementCount, - __in_ecount(elementCount) PCWSTR* defaultInterfaceNameElements) - { - CHKHR(_OnSet()); - - - // If an interface group or runtime class has a compound type as its default, and that - // type directly or indirectly refers to itself, the second occurrence instead used '*' - // to signal that the default interface has already been specified earlier up the call - // stack. This prevents unbounded recursion. - - if (_buffer->ExistsCycle(name)) - { - CHKHR( _WriteString("ig(") ); - CHKHR( _WriteWideString(name) ); - CHKHR( _WriteString(";*)") ); - } - else - { - SimpleMetaDataBuffer::ResolutionPathGuard guard(name, _buffer); - - CHKHR( _WriteString("ig(") ); - CHKHR( _WriteWideString(name) ); - CHKHR( _WriteChar(';') ); - - - // InterfaceGroups and RuntimeClasses take one nested argument - - CHKHR( _buffer->_nestedArgs.Append(1) ); - CHKHR( SendArguments(elementCount, defaultInterfaceNameElements) ); - CHKHR( _buffer->_nestedArgs.Pop() ); - CHKHR( _WriteChar(')') );; - - } - _Completed(); - return S_OK; - } - - inline __override HRESULT STDMETHODCALLTYPE SimpleMetaDataBuilder::SetRuntimeClassSimpleDefault( - PCWSTR name, - PCWSTR defaultInterfaceName, - __in_opt const GUID* defaultInterfaceIID) - { - CHKHR(_OnSet()); - - CHKHR(_WriteString("rc(")); - CHKHR(_CommonInterfaceGroupSimple(name, defaultInterfaceName, defaultInterfaceIID)); - - _Completed(); - return S_OK; - } - - - inline __override HRESULT STDMETHODCALLTYPE SimpleMetaDataBuilder::SetRuntimeClassParameterizedDefault( - PCWSTR name, - UINT32 elementCount, - __in_ecount(elementCount) PCWSTR* defaultInterfaceNameElements) - { - CHKHR(_OnSet()); - - if (_buffer->ExistsCycle(name)) - { - CHKHR(_WriteString("rc(")); - CHKHR(_WriteWideString(name)); - CHKHR(_WriteString(";*)")); - } - else - { - SimpleMetaDataBuffer::ResolutionPathGuard guard(name, _buffer); - - CHKHR(_WriteString("rc(")); - CHKHR(_WriteWideString(name)); - CHKHR(_WriteChar(';')); - - - // InterfaceGroups and RuntimeClasses take one nested argument - - CHKHR(_buffer->_nestedArgs.Append(1)); - CHKHR(SendArguments(elementCount, defaultInterfaceNameElements)); - CHKHR(_buffer->_nestedArgs.Pop()); - - CHKHR(_WriteChar(')')); - } - _Completed(); - return S_OK; - } - - inline __override HRESULT STDMETHODCALLTYPE SimpleMetaDataBuilder::SetStruct( - PCWSTR name, - UINT32 numFields, - __in_ecount(numFields) PCWSTR* fieldTypeNames) - { - CHKHR(_OnSet()); - CHKHR(_WriteString("struct(")); - CHKHR(_WriteWideString(name)); - CHKHR(_WriteChar(';')); - - CHKHR(_buffer->_nestedArgs.Append(1)); - CHKHR(SendArguments(numFields, fieldTypeNames)); - CHKHR(_buffer->_nestedArgs.Pop()); - - CHKHR(_WriteChar(')')); - - _Completed(); - return S_OK; - } - - inline __override HRESULT STDMETHODCALLTYPE SimpleMetaDataBuilder::SetEnum( - PCWSTR name, - PCWSTR baseType) - { - CHKHR(_OnSet()); - - CHKHR(_WriteString("enum(")); - CHKHR(_WriteWideString(name)); - CHKHR(_WriteChar(';')); - CHKHR(_buffer->_nestedArgs.Append(1)); - CHKHR(_WriteType(baseType)); - CHKHR(_buffer->_nestedArgs.Pop()); - CHKHR(_WriteChar(')')); - - _Completed(); - return S_OK; - } - - inline __override HRESULT STDMETHODCALLTYPE SimpleMetaDataBuilder::SetParameterizedInterface( - GUID piid, - UINT32 numArgs) - { - CHKHR(_OnSet()); - - CHKHR(_WriteString("pinterface(")); - CHKHR(_WriteGuid(piid)); - - - // Note the number of arguments. The SendArguments - // function will append the ')' after that number of - // arguments are consumed. - - CHKHR(_buffer->_nestedArgs.Append(numArgs)); - - _Completed(); - return S_OK; - } - - inline __override HRESULT STDMETHODCALLTYPE SimpleMetaDataBuilder::SetParameterizedDelegate( - GUID piid, - UINT32 numArgs) - { - - // Parameterized interfaces and parameterized delegates use the same signature scheme. - - return SetParameterizedInterface(piid, numArgs); - } - -}} // namespace Ro::detail - -#ifndef WINRT_PARAMINSTANCE_NOCRYPT_SHA1 - -namespace Ro { namespace detail { - - class Sha1 - { - public: - Sha1() - : _hAlg(nullptr) - , _hHash(nullptr) - { - } - - HRESULT Initialize() - { - DWORD dwcb; - DWORD dwcbResult; - -#ifdef _PREFAST_ -#pragma warning(push) -#pragma warning(disable: 33098) // "Banned hash algorithm is used" - SHA-1 is required for compatibility -#endif // _PREFAST_ - CHKNT(BCryptOpenAlgorithmProvider(&_hAlg, BCRYPT_SHA1_ALGORITHM, MS_PRIMITIVE_PROVIDER, 0)); -#ifdef _PREFAST_ -#pragma warning(pop) -#endif // _PREFAST_ - - CHKNT(BCryptGetProperty(_hAlg, BCRYPT_OBJECT_LENGTH, reinterpret_cast(&dwcb), sizeof(dwcb), &dwcbResult, 0)); - - _ahBuf.Value() = new (std::nothrow) BYTE[dwcb]; - if (nullptr == _ahBuf.Value()) - { - CHKHR( E_OUTOFMEMORY ); - } - - CHKNT(BCryptCreateHash(_hAlg, &_hHash, _ahBuf.Value(), dwcb, NULL, 0, 0)); - return S_OK; - } - HRESULT AppendData(size_t numBytes, __in_bcount(numBytes) const void* bytes) - { - CHKHR(Verify(numBytes <= DWORD(-1))); - CHKNT(BCryptHashData(_hHash, reinterpret_cast(const_cast(bytes)), DWORD(numBytes), 0)); - return S_OK;; - } - HRESULT GetResult(__out BYTE (*hashValue)[20]) - { - - // Sha1 hash result is fixed size, at 20 bytes. - - CHKNT(BCryptFinishHash(_hHash, reinterpret_cast(&hashValue[0]), _countof(*hashValue), 0)); - return S_OK; - } - ~Sha1() - { - if (_hHash) - { - BCryptDestroyHash(_hHash); - } - if (_hAlg) - { - BCryptCloseAlgorithmProvider(_hAlg, 0); - } - } - private: - - ArrayHolder _ahBuf; - BCRYPT_ALG_HANDLE _hAlg; - BCRYPT_HASH_HANDLE _hHash; - }; -}} // namespace Ro::detail - -extern "C" -{ - -inline HRESULT _RoSha1Create( - __out void** handle) -{ - *handle = nullptr; - - Ro::detail::ElementHolder sha1Instance; - sha1Instance.Value() = new (std::nothrow) Ro::detail::Sha1; - if (!sha1Instance.Value()) - { - CHKHR(E_OUTOFMEMORY); - } - CHKHR(sha1Instance->Initialize()); - - *handle = sha1Instance.Detach(); - return S_OK; -} - - -inline HRESULT _RoSha1AppendData( - __in void* handle, - __in size_t numBytes, - __in_bcount(numBytes) const void* data) -{ - Ro::detail::Sha1* sha1Instance = static_cast(handle); - CHKHR(sha1Instance->AppendData(numBytes, data)); - return S_OK; -} - - -inline HRESULT _RoSha1Finish( - __in void* handle, - __out BYTE (*hashValue)[20]) -{ - Ro::detail::Sha1* sha1Instance = static_cast(handle); - CHKHR(sha1Instance->GetResult(hashValue)); - return S_OK; -} - -inline void _RoSha1Release(__in void* handle) -{ - Ro::detail::Sha1* sha1Instance = static_cast(handle); - delete sha1Instance; -} - -} - -#endif /* ifdef WINRT_PARAMINSTANCE_NOCRYPT_SHA1 */ - -#ifdef _MSC_VER -#pragma pop_macro("CHKNT") -#pragma pop_macro("CHKHR") -#pragma warning( pop ) -#endif - -#endif /* ifdef __cplusplus */ -#endif /* ifndef WINRT_PARAMINSTANCEAPI_H */ diff --git a/src/coreclr/src/inc/winrt/windowsruntime.h b/src/coreclr/src/inc/winrt/windowsruntime.h deleted file mode 100644 index 2ac4391..0000000 --- a/src/coreclr/src/inc/winrt/windowsruntime.h +++ /dev/null @@ -1,52 +0,0 @@ -// 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. - -#ifndef WindowsRuntime_h -#define WindowsRuntime_h - -#include -#include -#include "holder.h" - -#ifndef IID_INS_ARGS - #define IID_INS_ARGS(ppType) __uuidof(**(ppType)), IID_INS_ARGS_Helper(ppType) -#endif - -HRESULT StringCchLength( - __in LPCWSTR wz, - __out UINT32 *pcch); - -#ifndef CROSSGEN_COMPILE -namespace clr -{ - namespace winrt - { - using ABI::Windows::Foundation::GetActivationFactory; - - template inline - HRESULT GetActivationFactory( - __in WinRtStringRef const & wzActivatableClassId, - __deref_out ItfT** ppItf) - { - LIMITED_METHOD_CONTRACT; - GCX_PREEMP(); - return GetActivationFactory(wzActivatableClassId.Get(), ppItf); - } - - template - HRESULT GetActivationFactory( - __in WinRtStringRef const & wzActivatableClassId, - __in typename ReleaseHolder& hItf) - { - LIMITED_METHOD_CONTRACT; - GCX_PREEMP(); - return GetActivationFactory(wzActivatableClassId.Get(), (ItfT**)&hItf); - } - } // namespace winrt -} // namespace clr -#endif //CROSSGEN_COMPILE - -#endif // WindowsRuntime_h - - diff --git a/src/coreclr/src/inc/winrt/windowsstring.h b/src/coreclr/src/inc/winrt/windowsstring.h deleted file mode 100644 index f63fcdd..0000000 --- a/src/coreclr/src/inc/winrt/windowsstring.h +++ /dev/null @@ -1,774 +0,0 @@ -// 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. -// -// - -#pragma once - -#ifndef WindowsString_h -#define WindowsString_h - -#include // Required by strsafe.h -#include // For SizeTToUInt32 -#include // For StringCchLengthW. -#include // The Windows SDK header file for HSTRING and HSTRING_HEADER. - -//--------------------------------------------------------------------------------------------------------------------------- -// Forward declarations -void DECLSPEC_NORETURN ThrowHR(HRESULT hr); - -//--------------------------------------------------------------------------------------------------------------------------- -namespace clr -{ - namespace winrt - { - //------------------------------------------------------------------------------------------------------------------- - // The internal Windows Runtime String wrapper class which doesn't throw exception when a failure occurs - // Note String class doesn't provide copy constructor and copy assigment. This is because the *fast* string duplicate - // can fail, which makes the copy constructor unusable in contexts where exceptions are not expected because it would - // need to throw on failure. However, a move constructor and move assignment are provided. These require a String && - // argument, which prevents a *fast* string from being moved (StringReference can be cast to const String&, but not - // String&&). - class String - { - public: - String() throw() : _hstring(nullptr) - { - STATIC_CONTRACT_LIMITED_METHOD; - } - - // Move Constructor - String(__inout String&& other) throw() - : _hstring(other._hstring) - { - STATIC_CONTRACT_LIMITED_METHOD; - other._hstring = nullptr; - } - - // Move assignment - String & operator = (__inout String&& other) throw() - { - STATIC_CONTRACT_LIMITED_METHOD; - Release(); - _hstring = other._hstring; - other._hstring = nullptr; - return *this; - } - - // Initialize this string from a source string. A copy is made in this call. - // The str parameter doesn't need to be null terminated, and it may have embedded NUL characters. - HRESULT Initialize(_In_reads_opt_(length) const wchar_t *str, UINT32 length) throw() - { - STATIC_CONTRACT_LIMITED_METHOD; - HSTRING local; - HRESULT hr = WindowsCreateString(str, length, &local); - return FreeAndAssignOnSuccess(hr, local, &_hstring); - } - - // Initialize this string from a source string. A copy is made in this call. The input string must have a terminating NULL. - HRESULT Initialize(__in PCWSTR str) throw() - { - STATIC_CONTRACT_LIMITED_METHOD; - HRESULT hr = S_OK; - - if (nullptr == str) - { // HSTRING functions promote null string pointers to the empty string, so we should too. - str = L""; - } - - size_t length = 0; - if (SUCCEEDED(hr)) - { - hr = StringCchLengthW(str, STRSAFE_MAX_CCH, &length); - } - - HSTRING local = nullptr; - if (SUCCEEDED(hr)) - { - hr = WindowsCreateString(str, static_cast(length), &local); - } - - return FreeAndAssignOnSuccess(hr, local, &_hstring); - } - - // Initialize this string from an HSTRING. A copy is made in this call. - HRESULT Initialize(const HSTRING& other) throw() - { - STATIC_CONTRACT_LIMITED_METHOD; - HSTRING local; - HRESULT hr = WindowsDuplicateString(other, &local); - return FreeAndAssignOnSuccess(hr, local, &_hstring); - } - - ~String() throw() - { - STATIC_CONTRACT_LIMITED_METHOD; - if (_hstring) - { - WindowsDeleteString(_hstring); - } - } - - // Release the current HSTRING object and reset the member variable to empty - void Release() throw() - { - STATIC_CONTRACT_LIMITED_METHOD; - if (_hstring) - { - WindowsDeleteString(_hstring); - _hstring = nullptr; - } - } - - // Detach the current HSTRING - void Detach(__out HSTRING *phstring) throw() - { - STATIC_CONTRACT_LIMITED_METHOD; - *phstring = _hstring; - _hstring = nullptr; - } - - // Duplicate from another String. - HRESULT Duplicate(__in const String& other) throw() - { - STATIC_CONTRACT_LIMITED_METHOD; - HSTRING local; - HRESULT hr = WindowsDuplicateString(other, &local); - return FreeAndAssignOnSuccess(hr, local, &_hstring); - } - - // Copy/duplicate into a bare HSTRING - HRESULT CopyTo(__out HSTRING *phstring) const throw() - { - STATIC_CONTRACT_LIMITED_METHOD; - return WindowsDuplicateString(this->_hstring, phstring); - } - - // HSTRING operator - operator const HSTRING&() const throw() - { - STATIC_CONTRACT_LIMITED_METHOD; - return _hstring; - } - - // Explicit conversion to HSTRING - HSTRING Get() const throw() - { - STATIC_CONTRACT_LIMITED_METHOD; - return _hstring; - } - - // Retrieve the address of the held hstring - HSTRING* Address() - { - STATIC_CONTRACT_LIMITED_METHOD; - return &_hstring; - } - - // Return the address of the internal HSTRING so that the caller can overwrite it, - // trusting that the caller will not leak the previously held value - HSTRING* GetAddressOf() - { - STATIC_CONTRACT_LIMITED_METHOD; - return &_hstring; - } - - // Return the address of the internal HSTRING so that the caller can overwrite it, - // but release the previous HSTRING to prevent a leak - HSTRING* ReleaseAndGetAddressOf() - { - STATIC_CONTRACT_LIMITED_METHOD; - if (_hstring != nullptr) - { - WindowsDeleteString(_hstring); - _hstring = nullptr; - } - return &_hstring; - } - - // Allow the wrapper to assign a new HSTRING to this wrapper, releasing the old HSTRING - void Attach(__in_opt HSTRING string) - { - STATIC_CONTRACT_LIMITED_METHOD; - WindowsDeleteString(_hstring); - _hstring = string; - } - - // Data Access - UINT32 length() const throw() - { - STATIC_CONTRACT_LIMITED_METHOD; - return WindowsGetStringLen(_hstring); - } - - // The size() function is an alias for length(), included to parallel stl conventions. - // The length() function is preferred. - UINT32 size() const throw() - { - STATIC_CONTRACT_LIMITED_METHOD; - return length(); - } - - BOOL IsEmpty() const throw() - { - STATIC_CONTRACT_LIMITED_METHOD; - return WindowsIsStringEmpty(_hstring); - } - - BOOL HasEmbeddedNull() const throw() - { - STATIC_CONTRACT_LIMITED_METHOD; - BOOL answer; - // Not capturing HRESULT - WindowsStringHasEmbeddedNull(_hstring, &answer); - return answer; - } - - LPCWSTR GetRawBuffer(__out_opt UINT32 *length = nullptr) const throw() - { - STATIC_CONTRACT_LIMITED_METHOD; - return WindowsGetStringRawBuffer(_hstring, length); - } - - HRESULT GetLpcwstr(__deref_out LPCWSTR *ppsz) const throw() - { - STATIC_CONTRACT_LIMITED_METHOD; - if (HasEmbeddedNull()) - { - *ppsz = nullptr; - return E_INVALIDARG; - } - *ppsz = WindowsGetStringRawBuffer(_hstring, nullptr); - return S_OK; - } - - // CompareOrdinal - INT32 CompareOrdinal(const String& other) const throw() - { - STATIC_CONTRACT_LIMITED_METHOD; - INT32 result = 0; - - // Ignore the HRESULT from the following call. - WindowsCompareStringOrdinal(_hstring, other, &result); - - return result; - } - - // Concatenation - HRESULT Concat(const String& string, __out String& newString) const throw() - { - STATIC_CONTRACT_LIMITED_METHOD; - HSTRING local; - HRESULT hr = WindowsConcatString(_hstring, string, &local); - return FreeAndAssignOnSuccess(hr, local, &newString._hstring); - } - - // Trim - HRESULT TrimStart(const String& trimString, __out String& newString) const throw() - { - STATIC_CONTRACT_LIMITED_METHOD; - HSTRING local; - HRESULT hr = WindowsTrimStringStart(_hstring, trimString, &local); - return FreeAndAssignOnSuccess(hr, local, &newString._hstring); - } - - HRESULT TrimEnd(const String& trimString, __out String& newString) const throw() - { - STATIC_CONTRACT_LIMITED_METHOD; - HSTRING local; - HRESULT hr = WindowsTrimStringEnd(_hstring, trimString, &local); - return FreeAndAssignOnSuccess(hr, local, &newString._hstring); - } - - // Substring - HRESULT Substring(UINT32 startIndex, __out String& newString) const throw() - { - STATIC_CONTRACT_LIMITED_METHOD; - HSTRING local; - HRESULT hr = WindowsSubstring(_hstring, startIndex, &local); - return FreeAndAssignOnSuccess(hr, local, &newString._hstring); - } - - HRESULT Substring(UINT32 startIndex, UINT32 length, __out String& newString) const throw() - { - STATIC_CONTRACT_LIMITED_METHOD; - HSTRING local; - HRESULT hr = WindowsSubstringWithSpecifiedLength(_hstring, startIndex, length, &local); - return FreeAndAssignOnSuccess(hr, local, &newString._hstring); - } - - // Replace - HRESULT Replace(const String& stringReplaced, const String& stringReplaceWith, __out String& newString) const throw() - { - STATIC_CONTRACT_LIMITED_METHOD; - HSTRING local; - HRESULT hr = WindowsReplaceString(_hstring, stringReplaced, stringReplaceWith, &local); - return FreeAndAssignOnSuccess(hr, local, &newString._hstring); - } - - private: - - // No Copy Constructor - String(const String& other); - - // No Copy assignment because if it can fail - String & operator = (const String& other); - - // - // helper function, always returns the passed in HRESULT - // - // if the HRESULT indicates success, frees any previous *target string, - // and over-writes it with newValue - // - // if the HRESULT indicates failure, does nothing - // - static HRESULT FreeAndAssignOnSuccess(HRESULT hr, HSTRING newValue, __inout HSTRING *target) - { - STATIC_CONTRACT_LIMITED_METHOD; - if (SUCCEEDED(hr)) - { - // InterlockedExchangePointer wouldn't have much value, unless we also modified - // all readers of *target to insert a ReadBarrier. - HSTRING oldValue = *target; - *target = newValue; - WindowsDeleteString(oldValue); - } - return hr; - } - - HSTRING _hstring; - }; - - static_assert(sizeof(String[2]) == sizeof(HSTRING[2]), "clr::winrt::String must be same size as HSTRING!"); - - //------------------------------------------------------------------------------------------------------------------- - // String Comparison Operators - inline - bool operator == (const String& left, const String& right) throw() - { - STATIC_CONTRACT_LIMITED_METHOD; - INT32 result = 0; - // Ignore the HRESULT from the following call. - WindowsCompareStringOrdinal(left, right, &result); - - return 0 == result; - } - - inline - bool operator != (const String& left, const String& right) throw() - { - STATIC_CONTRACT_LIMITED_METHOD; - INT32 result = 0; - // Ignore the HRESULT from the following call. - WindowsCompareStringOrdinal(left, right, &result); - - return 0 != result; - } - - inline - bool operator < (const String& left, const String& right) throw() - { - STATIC_CONTRACT_LIMITED_METHOD; - INT32 result = 0; - // Ignore the HRESULT from the following call. - WindowsCompareStringOrdinal(left, right, &result); - - return -1 == result; - } - - inline - bool operator <= (const String& left, const String& right) throw() - { - STATIC_CONTRACT_LIMITED_METHOD; - INT32 result = 0; - // Ignore the HRESULT from the following call. - WindowsCompareStringOrdinal(left, right, &result); - - return -1 == result || 0 == result; - } - - inline - bool operator > (const String& left, const String& right) throw() - { - STATIC_CONTRACT_LIMITED_METHOD; - INT32 result = 0; - // Ignore the HRESULT from the following call. - WindowsCompareStringOrdinal(left, right, &result); - - return 1 == result; - } - - inline - bool operator >= (const String& left, const String& right) throw() - { - STATIC_CONTRACT_LIMITED_METHOD; - INT32 result = 0; - // Ignore the HRESULT from the following call. - WindowsCompareStringOrdinal(left, right, &result); - - return 1 == result || 0 == result; - } - - - //------------------------------------------------------------------------------------------------------------------- - // The internal Windows Runtime String wrapper class for passing a reference of an existing string buffer. - // This class is allocated on stack. - class StringReference - { - public: - - // Constructor which takes an existing string buffer and its length as the parameters. - // It fills an HSTRING_HEADER struct with the parameter. - // - // Warning: The caller must ensure the lifetime of the buffer outlives this - // object as it does not make a copy of the wide string memory. - StringReference(__in_opt PCWSTR stringRef, UINT32 length) throw() - { - STATIC_CONTRACT_LIMITED_METHOD; - HRESULT hr = WindowsCreateStringReference(stringRef, length, &_header, &_hstring); - - // Failfast if internal developers try to create a reference to a non-NUL terminated string - if (FAILED(hr)) - { - RaiseException(static_cast(STATUS_INVALID_PARAMETER), EXCEPTION_NONCONTINUABLE, 0, nullptr); - } - } - - // Constructor for use with string literals. - // It fills an HSTRING_HEADER struct with the parameter. - template - StringReference(__in WCHAR const (&stringRef)[N]) throw() - { - STATIC_CONTRACT_LIMITED_METHOD; - - HRESULT hr = WindowsCreateStringReference(stringRef, N - 1 /* remove terminating NUL from length */, &_header, &_hstring); - - // Failfast if internal developers try to create a reference to a non-NUL terminated string. This constructor - // should only be used with string literals, but someone could mistakenly use this with a local WCHAR array and - // forget to NUL-terminate it. - if (FAILED(hr)) - { - RaiseException(static_cast(STATUS_INVALID_PARAMETER), EXCEPTION_NONCONTINUABLE, 0, nullptr); - } - } - - // Contructor which takes an HSTRING as the parameter. The new StringReference will not create a new copy of the original HSTRING. - // - // Warning: The caller must ensure the lifetime of the hstring argument outlives this - // object as it does not make a copy. - explicit StringReference(const HSTRING& hstring) throw() - { - STATIC_CONTRACT_LIMITED_METHOD; - // Create the StringReference without using the _header member, but instead with whatever header is used in hstring so that we - // prevent copying when Duplicate() is called on this object. There is no addref, nor decrement in the destructor, since we - // don't know or care if it's refcounted or truly a stack allocated reference. - _hstring = hstring; - } - - // const String& operator - operator const String&() const throw() - { - STATIC_CONTRACT_LIMITED_METHOD; - return _AsString(); - } - - // const HSTRING& operator - operator const HSTRING&() const throw() - { - STATIC_CONTRACT_LIMITED_METHOD; - return _hstring; - } - - // Explicit conversion to HSTRING - HSTRING Get() const throw() - { - STATIC_CONTRACT_LIMITED_METHOD; - return _hstring; - } - - // CompareOrdinal - INT32 CompareOrdinal(const String& other) const throw() - { - STATIC_CONTRACT_LIMITED_METHOD; - return _AsString().CompareOrdinal(other); - } - - // Data Access - UINT32 length() const throw() - { - STATIC_CONTRACT_LIMITED_METHOD; - return _AsString().length(); - } - - UINT32 size() const throw() - { - STATIC_CONTRACT_LIMITED_METHOD; - return _AsString().size(); - } - - BOOL IsEmpty() const throw() - { - STATIC_CONTRACT_LIMITED_METHOD; - return _AsString().IsEmpty(); - } - - BOOL HasEmbeddedNull() const throw() - { - STATIC_CONTRACT_LIMITED_METHOD; - return _AsString().HasEmbeddedNull(); - } - - LPCWSTR GetRawBuffer(__out_opt UINT32 *length) const throw() - { - STATIC_CONTRACT_LIMITED_METHOD; - return _AsString().GetRawBuffer(length); - } - - HRESULT GetLpcwstr(__deref_out LPCWSTR *ppsz) const throw() - { - STATIC_CONTRACT_LIMITED_METHOD; - return _AsString().GetLpcwstr(ppsz); - } - - HRESULT CopyTo(__out HSTRING *phstring) const throw() - { - STATIC_CONTRACT_LIMITED_METHOD; - return WindowsDuplicateString(this->_hstring, phstring); - } - - // Concatenation - HRESULT Concat(const String& otherString, __out String& newString) const throw() - { - STATIC_CONTRACT_LIMITED_METHOD; - return _AsString().Concat(otherString, newString); - } - - // Trim - HRESULT TrimStart(const String& trimString, __out String& newString) const throw() - { - STATIC_CONTRACT_LIMITED_METHOD; - return _AsString().TrimStart(trimString, newString); - } - - HRESULT TrimEnd(const String& trimString, __out String& newString) const throw() - { - STATIC_CONTRACT_LIMITED_METHOD; - return _AsString().TrimEnd(trimString, newString); - } - - // Substring - HRESULT Substring(UINT32 startIndex, __out String& newString) const throw() - { - STATIC_CONTRACT_LIMITED_METHOD; - return _AsString().Substring(startIndex, newString); - } - - HRESULT Substring(UINT32 startIndex, UINT32 length, __out String& newString) const throw() - { - STATIC_CONTRACT_LIMITED_METHOD; - return _AsString().Substring(startIndex, length, newString); - } - - // Replace - HRESULT Replace(const String& stringReplaced, const String& stringReplaceWith, __out String& newString) const throw() - { - STATIC_CONTRACT_LIMITED_METHOD; - return _AsString().Replace(stringReplaced, stringReplaceWith, newString); - } - - private: - // No Copy Constructor - StringReference(const String& other); - - // No non-const WCHAR array constructor - template - StringReference(__in WCHAR (&stringRef)[N]); - - // No Copy assigment - const StringReference & operator = (const String& other); - - // No new operator - static void * operator new(size_t size); - - // No delete operator - static void operator delete(void *p, size_t size); - - // const String& operator - const String& _AsString() const throw() - { - STATIC_CONTRACT_LIMITED_METHOD; - return reinterpret_cast(_hstring); - } - - HSTRING _hstring; - HSTRING_HEADER _header; - }; - } // namespace winrt -} // namespace clr - -typedef clr::winrt::String WinRtString; -typedef clr::winrt::StringReference WinRtStringRef; - -// ========================================================== -// WinRT-specific DuplicateString variations. - -LPWSTR DuplicateString( - LPCWSTR wszString, - size_t cchString); - -LPWSTR DuplicateStringThrowing( - LPCWSTR wszString, - size_t cchString); - -inline -LPWSTR DuplicateString(WinRtString const & str) -{ - STATIC_CONTRACT_NOTHROW; - UINT32 cchStr; - LPCWSTR wzStr = str.GetRawBuffer(&cchStr); - return DuplicateString(wzStr, cchStr); -} - -inline -LPWSTR DuplicateStringThrowing(WinRtString const & str) -{ - STATIC_CONTRACT_THROWS; - UINT32 cchStr; - LPCWSTR wzStr = str.GetRawBuffer(&cchStr); - return DuplicateStringThrowing(wzStr, cchStr); -} - -inline -LPWSTR DuplicateString(HSTRING const & hStr) -{ - STATIC_CONTRACT_NOTHROW; - WinRtStringRef str(hStr); - UINT32 cchStr; - LPCWSTR wzStr = str.GetRawBuffer(&cchStr); - return DuplicateString(wzStr, cchStr); -} - -inline -LPWSTR DuplicateStringThrowing(HSTRING const & hStr) -{ - STATIC_CONTRACT_THROWS; - WinRtStringRef str(hStr); - UINT32 cchStr; - LPCWSTR wzStr = str.GetRawBuffer(&cchStr); - return DuplicateStringThrowing(wzStr, cchStr); -} - -// ========================================================== -// Convenience overloads of StringCchLength - -// A convenience overload that assumes cchMax is STRSAFE_MAX_CCH. -inline -HRESULT StringCchLength( - __in LPCWSTR wz, - __out size_t *pcch) -{ - // To align with HSTRING functionality (which always promotes null - // string pointers to the empty string), this wrapper also promotes - // null string pointers to empty string before forwarding to Windows' - // implementation. Don't skip the call to StringCchLength for null - // pointers because we want to continue to align with the return value - // when passed a null length out parameter. - return StringCchLengthW(wz == nullptr ? L"" : wz, size_t(STRSAFE_MAX_CCH), pcch); -} - -#ifdef HOST_64BIT - // A UINT32-specific overload with built-in overflow check. - inline - HRESULT StringCchLength( - __in LPCWSTR wz, - __out UINT32 *pcch) - { - if (pcch == nullptr) - return E_INVALIDARG; - - size_t cch; - HRESULT hr = StringCchLength(wz, &cch); - if (FAILED(hr)) - return hr; - - return SizeTToUInt32(cch, pcch); - } -#endif // HOST_64BIT - -#ifndef DACCESS_COMPILE - //===================================================================================================================== - // Holder of CoTaskMem-allocated array of HSTRING (helper class for WinRT binders - e.g. code:CLRPrivBinderWinRT::GetFileNameListForNamespace). - class CoTaskMemHSTRINGArrayHolder - { - public: - CoTaskMemHSTRINGArrayHolder() - { - LIMITED_METHOD_CONTRACT; - - m_cValues = 0; - m_rgValues = nullptr; - } - ~CoTaskMemHSTRINGArrayHolder() - { - LIMITED_METHOD_CONTRACT; - Destroy(); - } - - // Destroys current array and holds new array rgValues of size cValues. - void Init(HSTRING * rgValues, DWORD cValues) - { - LIMITED_METHOD_CONTRACT; - - Destroy(); - _ASSERTE(m_cValues == 0); - - _ASSERTE(((cValues == 0) && (rgValues == nullptr)) || - ((cValues > 0) && (rgValues != nullptr))); - - m_rgValues = rgValues; - m_cValues = cValues; - } - - HSTRING GetAt(DWORD index) const - { - LIMITED_METHOD_CONTRACT; - return m_rgValues[index]; - } - - DWORD GetCount() - { - LIMITED_METHOD_CONTRACT; - return m_cValues; - } - - private: - void Destroy() - { - LIMITED_METHOD_CONTRACT; - - for (DWORD i = 0; i < m_cValues; i++) - { - if (m_rgValues[i] != nullptr) - { - WindowsDeleteString(m_rgValues[i]); - } - } - m_cValues = 0; - - if (m_rgValues != nullptr) - { - CoTaskMemFree(m_rgValues); - m_rgValues = nullptr; - } - } - - private: - DWORD m_cValues; - HSTRING * m_rgValues; - }; // class CoTaskMemHSTRINGArrayHolder -#endif //!DACCESS_COMPILE - - -#endif // WindowsString_h - diff --git a/src/coreclr/src/inc/winrtprojectedtypes.h b/src/coreclr/src/inc/winrtprojectedtypes.h deleted file mode 100644 index 226aa44..0000000 --- a/src/coreclr/src/inc/winrtprojectedtypes.h +++ /dev/null @@ -1,271 +0,0 @@ -// 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. - -// -// This header defines the list of types that are redirected in the CLR projection of WinRT. -// - -// -// The DEFINE_PROJECTED_TYPE macro takes the following parameters: -// * An ASCII string representing the namespace in winmd which contains the type being projected from -// * An ASCII string representing the name in winmd of the type being projected from -// * An ASCII string representing the namespace in .NET which contains the type being projected to -// * An ASCII string representing the name in .NET of the type being projected to -// * A symbol which is used to represent the assembly the .NET type is defined in -// * A symbol which is used to represent the contract assembly the .NET type is defined in -// * A symbol which is used to represent the WinRT type -// * A symbol which is used to represent the .NET type -// * A symbol which indicates what kind of type this is (struct, runtimeclassclass, etc) - -// -// Optionally, the DEFINE_PROJECTED_RUNTIMECLASS, DEFINE_PROJECTED_STRUCT, DEFINE_PROJECTED_ENUM, DEFINE_PROJECTED_PINTERFACE, -// DEFINE_PROJECTED_INTERFACE, and DEFINE_PROJECTED_ATTRIBUTE macros can be defined by the consumer of this header file, in -// order to get extra information about the projected types. -// -// Note that the input to these macros is in terms of the original winmd - so HResult is a DEFINE_PROJECTED_STRUCT even though it -// projects to the class Exception. If you are adding a projection where the WinRT and CLR views differ upon if the type is a -// value type or not, you'll need to update the signature rewriting code in md\winmd\adapter.cpp as well as the export code in -// toolbox\winmdexp\projectedtypes.cspp. -// -// If these extra macros are not defined, then the DEFINE_PROJECTED_TYPE macro is used to register the type -// -// Additionally, the DEFINE_HIDDEN_WINRT_TYPE macro can be defined by the consumer of this file to get information about WinRT -// types that are not projected but should be hidden from the developer, for instance because they are not intended to be used -// by 3rd party components. -// -// - -// DEFINE_PROJECTED_RUNTIMECLASS adds the following parameters: -// * A ASCII string representing the namespace qualified default interface name -// * The IID of the default interface -#ifndef DEFINE_PROJECTED_RUNTIMECLASS -#define DEFINE_PROJECTED_RUNTIMECLASS(szWinRTNamespace, szWinRTName, szClrNamespace, szClrName, nClrAssemblyIndex, nContractAsmIdx, WinRTRedirectedTypeIndex, ClrRedirectedTypeIndex, szDefaultInterfaceName, DefaultInterfaceIID) \ - DEFINE_PROJECTED_TYPE(szWinRTNamespace, szWinRTName, szClrNamespace, szClrName, nClrAssemblyIndex, nContractAsmIdx, WinRTRedirectedTypeIndex, ClrRedirectedTypeIndex, Runtimeclass) -#define __LOCAL_DEFINE_PROJECTED_RUNTIMECLASS -#endif // !DEFINE_PROJECTED_RUNTIMECLASS - -// DEFINE_PROJECTED_STRUCT adds the following parameters: -// * An array of Unicode strings representing the types of those fields -// -// Note that if a field is of a non-primitive type, it must be represented in WinRTGuidGenerator::MetaDataLocator::Locate -#ifndef DEFINE_PROJECTED_STRUCT -#define DEFINE_PROJECTED_STRUCT(szWinRTNamespace, szWinRTName, szClrNamespace, szClrName, nClrAssemblyIndex, nContractAsmIdx, WinRTRedirectedTypeIndex, ClrRedirectedTypeIndex, fieldSizes) \ - DEFINE_PROJECTED_TYPE(szWinRTNamespace, szWinRTName, szClrNamespace, szClrName, nClrAssemblyIndex, nContractAsmIdx, WinRTRedirectedTypeIndex, ClrRedirectedTypeIndex, Struct) -#define __LOCAL_DEFINE_PROJECTED_STRUCT -#endif // !DEFINE_PROJECTED_STRUCT - -#ifndef DEFINE_PROJECTED_JUPITER_STRUCT -#define DEFINE_PROJECTED_JUPITER_STRUCT(szWinRTNamespace, szWinRTName, szClrNamespace, szClrName, nClrAssemblyIndex, nContractAsmIdx, WinRTRedirectedTypeIndex, ClrRedirectedTypeIndex, fieldSizes) \ - DEFINE_PROJECTED_TYPE(szWinRTNamespace, szWinRTName, szClrNamespace, szClrName, nClrAssemblyIndex, nContractAsmIdx, WinRTRedirectedTypeIndex, ClrRedirectedTypeIndex, Struct) -#define __LOCAL_DEFINE_PROJECTED_JUPITER_STRUCT -#endif // !DEFINE_PROJECTED_JUPITER_STRUCT - -#ifndef STRUCT_FIELDS -#define STRUCT_FIELDS(...) __VA_ARGS__ -#endif // !STRUCT_FIELDS - -// DEFINE_PROJECTED_ENUM adds the following parameters: -// * An ASCII string defining the size of the backing field of the enumeration -#ifndef DEFINE_PROJECTED_ENUM -#define DEFINE_PROJECTED_ENUM(szWinRTNamespace, szWinRTName, szClrNamespace, szClrName, nClrAssemblyIndex, nContractAsmIdx, WinRTRedirectedTypeIndex, ClrRedirectedTypeIndex, szBackingFieldSize) \ - DEFINE_PROJECTED_TYPE(szWinRTNamespace, szWinRTName, szClrNamespace, szClrName, nClrAssemblyIndex, nContractAsmIdx, WinRTRedirectedTypeIndex, ClrRedirectedTypeIndex, Enum) -#define __LOCAL_DEFINE_PROJECTED_ENUM -#endif // !DEFINE_PROJECTED_ENUM - -// DEFINE_PROJECTED_INTERFACE adds the following extra parameters: -// * The IID of the interface -#ifndef DEFINE_PROJECTED_INTERFACE -#define DEFINE_PROJECTED_INTERFACE(szWinRTNamespace, szWinRTName, szClrNamespace, szClrName, nClrAssemblyIndex, nContractAsmIdx, WinRTRedirectedTypeIndex, ClrRedirectedTypeIndex, PIID) \ - DEFINE_PROJECTED_TYPE(szWinRTNamespace, szWinRTName, szClrNamespace, szClrName, nClrAssemblyIndex, nContractAsmIdx, WinRTRedirectedTypeIndex, ClrRedirectedTypeIndex, Interface) -#define __LOCAL_DEFINE_PROJECTED_INTERFACE -#endif // !DEFINE_PROJECTED_INTERFACE - -// DEFINE_PROJECTED_PINTERFACE adds the following extra parameters: -// * The number of generic type parameters on the interface -// * The PIID of the interface -#ifndef DEFINE_PROJECTED_PINTERFACE -#define DEFINE_PROJECTED_PINTERFACE(szWinRTNamespace, szWinRTName, szClrNamespace, szClrName, nClrAssemblyIndex, nContractAsmIdx, WinRTRedirectedTypeIndex, ClrRedirectedTypeIndex, GenericTypeParameterCount, PIID) \ - DEFINE_PROJECTED_TYPE(szWinRTNamespace, szWinRTName, szClrNamespace, szClrName, nClrAssemblyIndex, nContractAsmIdx, WinRTRedirectedTypeIndex, ClrRedirectedTypeIndex, PInterface) -#define __LOCAL_DEFINE_PROJECTED_PINTERFACE -#endif // !DEFINE_PROJECTED_PINTERFACE - -// DEFINE_PROJECTED_DELEGATE adds the following extra parameters: -// * The IID of the delegate -#ifndef DEFINE_PROJECTED_DELEGATE -#define DEFINE_PROJECTED_DELEGATE(szWinRTNamespace, szWinRTName, szClrNamespace, szClrName, nClrAssemblyIndex, nContractAsmIdx, WinRTRedirectedTypeIndex, ClrRedirectedTypeIndex, PIID) \ - DEFINE_PROJECTED_TYPE(szWinRTNamespace, szWinRTName, szClrNamespace, szClrName, nClrAssemblyIndex, nContractAsmIdx, WinRTRedirectedTypeIndex, ClrRedirectedTypeIndex, Delegate) -#define __LOCAL_DEFINE_PROJECTED_DELEGATE -#endif // !DEFINE_PROJECTED_DELEGATE - -// DEFINE_PROJECTED_PDELEGATE adds the following extra parameters: -// * The number of generic type parameters on the interface -// * The PIID of the delegate -#ifndef DEFINE_PROJECTED_PDELEGATE -#define DEFINE_PROJECTED_PDELEGATE(szWinRTNamespace, szWinRTName, szClrNamespace, szClrName, nClrAssemblyIndex, nContractAsmIdx, WinRTRedirectedTypeIndex, ClrRedirectedTypeIndex, GenericTypeParameterCount, PIID) \ - DEFINE_PROJECTED_TYPE(szWinRTNamespace, szWinRTName, szClrNamespace, szClrName, nClrAssemblyIndex, nContractAsmIdx, WinRTRedirectedTypeIndex, ClrRedirectedTypeIndex, PDelegate) -#define __LOCAL_DEFINE_PROJECTED_PDELEGATE -#endif // !DEFINE_PROJECTED_PDELEGATE - -#ifndef PIID -#define PIID(...) { __VA_ARGS__ } -#endif // !PIID - -// DEFINE_PROJECTED_ATTRIBUTE adds no additional parameters -#ifndef DEFINE_PROJECTED_ATTRIBUTE -#define DEFINE_PROJECTED_ATTRIBUTE(szWinRTNamespace, szWinRTName, szClrNamespace, szClrName, nClrAssemblyIndex, nContractAsmIdx, WinRTRedirectedTypeIndex, ClrRedirectedTypeIndex) \ - DEFINE_PROJECTED_TYPE(szWinRTNamespace, szWinRTName, szClrNamespace, szClrName, nClrAssemblyIndex, nContractAsmIdx, WinRTRedirectedTypeIndex, ClrRedirectedTypeIndex, Attribute) -#define __LOCAL_DEFINE_PROJECTED_ATTRIBUTE -#endif // !DEFINE_PROJECTED_ATTRIBUTE - -#ifndef DEFINE_HIDDEN_WINRT_TYPE -#define DEFINE_HIDDEN_WINRT_TYPE(szWinRTNamespace, szWinRTName) -#define __LOCAL_DEFINE_HIDDEN_WINRT_TYPE -#endif // !DEFINE_HIDDEN_WINRT_TYPE - -// szWinRTNamespace szWinRTName szClrNamespace szClrName nClrAssemblyIndex nContractAsmIdx WinRTRedirectedTypeIndex ClrRedirectedTypeIndex Extra parameters -// ---------------- ----------- -------------- --------- ----------------- --------------- --------------------- ---------------------- ---------------- -DEFINE_PROJECTED_ATTRIBUTE ("Windows.Foundation.Metadata", "AttributeUsageAttribute", "System", "AttributeUsageAttribute", Mscorlib, SystemRuntime, Windows_Foundation_Metadata_AttributeUsageAttribute, System_AttributeUsage) -DEFINE_PROJECTED_ENUM ("Windows.Foundation.Metadata", "AttributeTargets", "System", "AttributeTargets", Mscorlib, SystemRuntime, Windows_Foundation_Metadata_AttributeTargets, System_AttributeTargets, "Int32") - -DEFINE_PROJECTED_STRUCT ("Windows.UI", "Color", "Windows.UI", "Color", SystemRuntimeWindowsRuntime, SystemRuntimeWindowsRuntime, Windows_UI_Color, System_Windows_Color, STRUCT_FIELDS(W("UInt8"), W("UInt8"), W("UInt8"), W("UInt8"))) - -DEFINE_PROJECTED_STRUCT ("Windows.Foundation", "DateTime", "System", "DateTimeOffset", Mscorlib, SystemRuntime, Windows_Foundation_DateTime, System_DateTimeOffset, STRUCT_FIELDS(W("Int64"))) -DEFINE_PROJECTED_PDELEGATE ("Windows.Foundation", "EventHandler`1", "System", "EventHandler`1", Mscorlib, SystemRuntime, Windows_Foundation_EventHandlerGeneric, System_EventHandlerGeneric, 1, PIID(0x9de1c535, 0x6ae1, 0x11e0, {0x84, 0xe1, 0x18, 0xa9, 0x05, 0xbc, 0xc5, 0x3f})) -DEFINE_PROJECTED_STRUCT ("Windows.Foundation", "EventRegistrationToken", "System.Runtime.InteropServices.WindowsRuntime", "EventRegistrationToken", Mscorlib, SystemRuntimeInteropServicesWindowsRuntime, Windows_Foundation_EventRegistrationToken, System_Runtime_InteropServices_WindowsRuntime_EventRegistrationToken, STRUCT_FIELDS(W("Int64"))) -DEFINE_PROJECTED_STRUCT ("Windows.Foundation", "HResult", "System", "Exception", Mscorlib, SystemRuntime, Windows_Foundation_HResult, System_Exception, STRUCT_FIELDS(W("Int32"))) -DEFINE_PROJECTED_PINTERFACE ("Windows.Foundation", "IReference`1", "System", "Nullable`1", Mscorlib, SystemRuntime, Windows_Foundation_IReference, System_Nullable, 1, PIID(0x61c17706, 0x2d65, 0x11e0, {0x9a, 0xe8, 0xd4, 0x85, 0x64, 0x01, 0x54, 0x72})) -DEFINE_PROJECTED_STRUCT ("Windows.Foundation", "Point", "Windows.Foundation", "Point", SystemRuntimeWindowsRuntime, SystemRuntimeWindowsRuntime, Windows_Foundation_Point, Windows_Foundation_Point_clr, STRUCT_FIELDS(W("Single"), W("Single"))) -DEFINE_PROJECTED_STRUCT ("Windows.Foundation", "Rect", "Windows.Foundation", "Rect", SystemRuntimeWindowsRuntime, SystemRuntimeWindowsRuntime, Windows_Foundation_Rect, Windows_Foundation_Rect_clr, STRUCT_FIELDS(W("Single"), W("Single"), W("Single"), W("Single"))) -DEFINE_PROJECTED_STRUCT ("Windows.Foundation", "Size", "Windows.Foundation", "Size", SystemRuntimeWindowsRuntime, SystemRuntimeWindowsRuntime, Windows_Foundation_Size, Windows_Foundation_Size_clr, STRUCT_FIELDS(W("Single"), W("Single"))) -DEFINE_PROJECTED_STRUCT ("Windows.Foundation", "TimeSpan", "System", "TimeSpan", Mscorlib, SystemRuntime, Windows_Foundation_TimeSpan, System_TimeSpan, STRUCT_FIELDS(W("Int64"))) -DEFINE_PROJECTED_RUNTIMECLASS("Windows.Foundation", "Uri", "System", "Uri", SystemRuntime, SystemRuntime, Windows_Foundation_Uri, System_Uri, "Windows.Foundation.IUriRuntimeClass", __uuidof(ABI::Windows::Foundation::IUriRuntimeClass)) - -DEFINE_PROJECTED_INTERFACE ("Windows.Foundation", "IClosable", "System", "IDisposable", Mscorlib, SystemRuntime, Windows_Foundation_IClosable, System_IDisposable, PIID(0x30d5a829, 0x7fa4, 0x4026, {0x83, 0xbb, 0xd7, 0x5b, 0xae, 0x4e, 0xa9, 0x9e})) - -DEFINE_PROJECTED_PINTERFACE ("Windows.Foundation.Collections", "IIterable`1", "System.Collections.Generic", "IEnumerable`1", Mscorlib, SystemRuntime, Windows_Foundation_Collections_IIterable, System_Collections_Generic_IEnumerable, 1, PIID(0xfaa585ea, 0x6214, 0x4217, {0xaf, 0xda, 0x7f, 0x46, 0xde, 0x58, 0x69, 0xb3})) -DEFINE_PROJECTED_PINTERFACE ("Windows.Foundation.Collections", "IVector`1", "System.Collections.Generic", "IList`1", Mscorlib, SystemRuntime, Windows_Foundation_Collections_IVector, System_Collections_Generic_IList, 1, PIID(0x913337e9, 0x11a1, 0x4345, {0xa3, 0xa2, 0x4e, 0x7f, 0x95, 0x6e, 0x22, 0x2d})) -DEFINE_PROJECTED_PINTERFACE ("Windows.Foundation.Collections", "IVectorView`1", "System.Collections.Generic", "IReadOnlyList`1", Mscorlib, SystemRuntime, Windows_Foundation_Collections_IVectorView, System_Collections_Generic_IReadOnlyList, 1, PIID(0xbbe1fa4c, 0xb0e3, 0x4583, {0xba, 0xef, 0x1f, 0x1b, 0x2e, 0x48, 0x3e, 0x56})) -DEFINE_PROJECTED_PINTERFACE ("Windows.Foundation.Collections", "IMap`2", "System.Collections.Generic", "IDictionary`2", Mscorlib, SystemRuntime, Windows_Foundation_Collections_IMap, System_Collections_Generic_IDictionary, 2, PIID(0x3c2925fe, 0x8519, 0x45c1, {0xaa, 0x79, 0x19, 0x7b, 0x67, 0x18, 0xc1, 0xc1})) -DEFINE_PROJECTED_PINTERFACE ("Windows.Foundation.Collections", "IMapView`2", "System.Collections.Generic", "IReadOnlyDictionary`2", Mscorlib, SystemRuntime, Windows_Foundation_Collections_IMapView, System_Collections_Generic_IReadOnlyDictionary, 2, PIID(0xe480ce40, 0xa338, 0x4ada, {0xad, 0xcf, 0x27, 0x22, 0x72, 0xe4, 0x8c, 0xb9})) -DEFINE_PROJECTED_PINTERFACE ("Windows.Foundation.Collections", "IKeyValuePair`2", "System.Collections.Generic", "KeyValuePair`2", Mscorlib, SystemRuntime, Windows_Foundation_Collections_IKeyValuePair, System_Collections_Generic_KeyValuePair, 2, PIID(0x02b51929, 0xc1c4, 0x4a7e, {0x89, 0x40, 0x03, 0x12, 0xb5, 0xc1, 0x85, 0x00})) - -DEFINE_PROJECTED_INTERFACE ("Windows.UI.Xaml.Input", "ICommand", "System.Windows.Input", "ICommand", SystemObjectModel, SystemObjectModel, Windows_UI_Xaml_Input_ICommand, System_Windows_Input_ICommand, PIID(0xE5AF3542, 0xCA67, 0x4081, {0x99, 0x5B, 0x70, 0x9D, 0xD1, 0x37, 0x92, 0xDF})) - -DEFINE_PROJECTED_INTERFACE ("Windows.UI.Xaml.Interop", "IBindableIterable", "System.Collections", "IEnumerable", Mscorlib, SystemRuntime, Windows_UI_Xaml_Interop_IBindableIterable, System_Collections_IEnumerable, PIID(0x036d2c08, 0xdf29, 0x41af, {0x8a, 0xa2, 0xd7, 0x74, 0xbe, 0x62, 0xba, 0x6f})) -DEFINE_PROJECTED_INTERFACE ("Windows.UI.Xaml.Interop", "IBindableVector", "System.Collections", "IList", Mscorlib, SystemRuntime, Windows_UI_Xaml_Interop_IBindableVector, System_Collections_IList, PIID(0x393de7de, 0x6fd0, 0x4c0d, {0xbb, 0x71, 0x47, 0x24, 0x4a, 0x11, 0x3e, 0x93})) - -DEFINE_PROJECTED_INTERFACE ("Windows.UI.Xaml.Interop", "INotifyCollectionChanged", "System.Collections.Specialized", "INotifyCollectionChanged", SystemObjectModel, SystemObjectModel, Windows_UI_Xaml_Interop_INotifyCollectionChanged, System_Collections_Specialized_INotifyCollectionChanged, PIID(0x28b167d5, 0x1a31, 0x465b, {0x9b, 0x25, 0xd5, 0xc3, 0xae, 0x68, 0x6c, 0x40})) -DEFINE_PROJECTED_DELEGATE ("Windows.UI.Xaml.Interop", "NotifyCollectionChangedEventHandler", "System.Collections.Specialized", "NotifyCollectionChangedEventHandler", SystemObjectModel, SystemObjectModel, Windows_UI_Xaml_Interop_NotifyCollectionChangedEventHandler, System_Collections_Specialized_NotifyCollectionChangedEventHandler, PIID(0xca10b37c, 0xf382, 0x4591, {0x85, 0x57, 0x5e, 0x24, 0x96, 0x52, 0x79, 0xb0})) -DEFINE_PROJECTED_RUNTIMECLASS("Windows.UI.Xaml.Interop", "NotifyCollectionChangedEventArgs", "System.Collections.Specialized", "NotifyCollectionChangedEventArgs", SystemObjectModel, SystemObjectModel, Windows_UI_Xaml_Interop_NotifyCollectionChangedEventArgs, System_Collections_Specialized_NotifyCollectionChangedEventArgs, "Windows.UI.Xaml.Interop.INotifyCollectionChangedEventArgs", PIID(0x4cf68d33, 0xe3f2, 0x4964, {0xb8, 0x5e, 0x94, 0x5b, 0x4f, 0x7e, 0x2f, 0x21})) -DEFINE_PROJECTED_ENUM ("Windows.UI.Xaml.Interop", "NotifyCollectionChangedAction", "System.Collections.Specialized", "NotifyCollectionChangedAction", SystemObjectModel, SystemObjectModel, Windows_UI_Xaml_Interop_NotifyCollectionChangedAction, System_Collections_Specialized_NotifyCollectionChangedAction, "Int32") - -DEFINE_PROJECTED_INTERFACE ("Windows.UI.Xaml.Data", "INotifyPropertyChanged", "System.ComponentModel", "INotifyPropertyChanged", SystemObjectModel, SystemObjectModel, Windows_UI_Xaml_Data_INotifyPropertyChanged, System_ComponentModel_INotifyPropertyChanged, PIID(0xcf75d69c, 0xf2f4, 0x486b, {0xb3, 0x02, 0xbb, 0x4c, 0x09, 0xba, 0xeb, 0xfa})) -DEFINE_PROJECTED_DELEGATE ("Windows.UI.Xaml.Data", "PropertyChangedEventHandler", "System.ComponentModel", "PropertyChangedEventHandler", SystemObjectModel, SystemObjectModel, Windows_UI_Xaml_Data_PropertyChangedEventHandler, System_ComponentModel_PropertyChangedEventHandler, PIID(0x50f19c16, 0x0a22, 0x4d8e, {0xa0, 0x89, 0x1e, 0xa9, 0x95, 0x16, 0x57, 0xd2})) -DEFINE_PROJECTED_RUNTIMECLASS("Windows.UI.Xaml.Data", "PropertyChangedEventArgs", "System.ComponentModel", "PropertyChangedEventArgs", SystemObjectModel, SystemObjectModel, Windows_UI_Xaml_Data_PropertyChangedEventArgs, System_ComponentModel_PropertyChangedEventArgs, "Windows.UI.Xaml.Data.IPropertyChangedEventArgs", PIID(0x4f33a9a0, 0x5cf4, 0x47a4, {0xb1, 0x6f, 0xd7, 0xfa, 0xaf, 0x17, 0x45, 0x7e})) - -DEFINE_PROJECTED_JUPITER_STRUCT("Windows.UI.Xaml", "CornerRadius", "Windows.UI.Xaml", "CornerRadius", SystemRuntimeWindowsRuntimeUIXaml, SystemRuntimeWindowsRuntimeUIXaml, Windows_UI_Xaml_CornerRadius, Windows_UI_Xaml_CornerRadius_clr, STRUCT_FIELDS(W("Double"), W("Double"), W("Double"), W("Double"))) -DEFINE_PROJECTED_JUPITER_STRUCT("Windows.UI.Xaml", "Duration", "Windows.UI.Xaml", "Duration", SystemRuntimeWindowsRuntimeUIXaml, SystemRuntimeWindowsRuntimeUIXaml, Windows_UI_Xaml_Duration, Windows_UI_Xaml_Duration_clr, STRUCT_FIELDS(W("Windows.Foundation.TimeSpan"), W("Windows.UI.Xaml.DurationType"))) -DEFINE_PROJECTED_ENUM ("Windows.UI.Xaml", "DurationType", "Windows.UI.Xaml", "DurationType", SystemRuntimeWindowsRuntimeUIXaml, SystemRuntimeWindowsRuntimeUIXaml, Windows_UI_Xaml_DurationType, Windows_UI_Xaml_DurationType_clr, "Int32") -DEFINE_PROJECTED_JUPITER_STRUCT("Windows.UI.Xaml", "GridLength", "Windows.UI.Xaml", "GridLength", SystemRuntimeWindowsRuntimeUIXaml, SystemRuntimeWindowsRuntimeUIXaml, Windows_UI_Xaml_GridLength, Windows_UI_Xaml_GridLength_clr, STRUCT_FIELDS(W("Double"), W("Windows.UI.Xaml.GridUnitType"))) -DEFINE_PROJECTED_ENUM ("Windows.UI.Xaml", "GridUnitType", "Windows.UI.Xaml", "GridUnitType", SystemRuntimeWindowsRuntimeUIXaml, SystemRuntimeWindowsRuntimeUIXaml, Windows_UI_Xaml_GridUnitType, Windows_UI_Xaml_GridUnitType_clr, "Int32") -DEFINE_PROJECTED_JUPITER_STRUCT("Windows.UI.Xaml", "Thickness", "Windows.UI.Xaml", "Thickness", SystemRuntimeWindowsRuntimeUIXaml, SystemRuntimeWindowsRuntimeUIXaml, Windows_UI_Xaml_Thickness, Windows_UI_Xaml_Thickness_clr, STRUCT_FIELDS(W("Double"), W("Double"), W("Double"), W("Double"))) - -DEFINE_PROJECTED_JUPITER_STRUCT("Windows.UI.Xaml.Interop", "TypeName", "System", "Type", Mscorlib, SystemRuntime, Windows_UI_Xaml_Interop_TypeName, System_Type, STRUCT_FIELDS(W("String"), W("Windows.UI.Xaml.Interop.TypeKind"))) - -DEFINE_PROJECTED_JUPITER_STRUCT("Windows.UI.Xaml.Controls.Primitives", "GeneratorPosition", "Windows.UI.Xaml.Controls.Primitives", "GeneratorPosition", SystemRuntimeWindowsRuntimeUIXaml, SystemRuntimeWindowsRuntimeUIXaml, Windows_UI_Xaml_Controls_Primitives_GeneratorPosition, Windows_UI_Xaml_Controls_Primitives_GeneratorPosition_clr, STRUCT_FIELDS(W("Int32"), W("Int32"))) - -DEFINE_PROJECTED_JUPITER_STRUCT("Windows.UI.Xaml.Media", "Matrix", "Windows.UI.Xaml.Media", "Matrix", SystemRuntimeWindowsRuntimeUIXaml, SystemRuntimeWindowsRuntimeUIXaml, Windows_UI_Xaml_Media_Matrix, Windows_UI_Xaml_Media_Matrix_clr, STRUCT_FIELDS(W("Double"), W("Double"), W("Double"), W("Double"), W("Double"), W("Double"))) - -DEFINE_PROJECTED_JUPITER_STRUCT("Windows.UI.Xaml.Media.Animation", "KeyTime", "Windows.UI.Xaml.Media.Animation", "KeyTime", SystemRuntimeWindowsRuntimeUIXaml, SystemRuntimeWindowsRuntimeUIXaml, Windows_UI_Xaml_Media_Animation_KeyTime, Windows_UI_Xaml_Media_Animation_KeyTime_clr, STRUCT_FIELDS(W("Windows.Foundation.TimeSpan"))) -DEFINE_PROJECTED_JUPITER_STRUCT("Windows.UI.Xaml.Media.Animation", "RepeatBehavior", "Windows.UI.Xaml.Media.Animation", "RepeatBehavior", SystemRuntimeWindowsRuntimeUIXaml, SystemRuntimeWindowsRuntimeUIXaml, Windows_UI_Xaml_Media_Animation_RepeatBehavior, Windows_UI_Xaml_Media_Animation_RepeatBehavior_clr, STRUCT_FIELDS(W("Double"), W("Windows.Foundation.TimeSpan"), W("Windows.UI.Xaml.Media.Animation.RepeatBehaviorType"))) -DEFINE_PROJECTED_ENUM ("Windows.UI.Xaml.Media.Animation", "RepeatBehaviorType", "Windows.UI.Xaml.Media.Animation", "RepeatBehaviorType", SystemRuntimeWindowsRuntimeUIXaml, SystemRuntimeWindowsRuntimeUIXaml, Windows_UI_Xaml_Media_Animation_RepeatBehaviorType, Windows_UI_Xaml_Media_Animation_RepeatBehaviorType_clr, "Int32") - -DEFINE_PROJECTED_JUPITER_STRUCT("Windows.UI.Xaml.Media.Media3D", "Matrix3D", "Windows.UI.Xaml.Media.Media3D", "Matrix3D", SystemRuntimeWindowsRuntimeUIXaml, SystemRuntimeWindowsRuntimeUIXaml, Windows_UI_Xaml_Media_Media3D_Matrix3D, Windows_UI_Xaml_Media_Media3D_Matrix3D_clr, STRUCT_FIELDS(W("Double"), W("Double"), W("Double"), W("Double"), W("Double"), W("Double"), W("Double"), W("Double"), W("Double"), W("Double"), W("Double"), W("Double"), W("Double"), W("Double"), W("Double"), W("Double"))) - -DEFINE_PROJECTED_STRUCT ("Windows.Foundation.Numerics", "Vector2", "System.Numerics", "Vector2", SystemNumericsVectors, SystemNumericsVectors, Windows_Foundation_Numerics_Vector2, System_Numerics_Vector2, STRUCT_FIELDS(L"Single", L"Single")) -DEFINE_PROJECTED_STRUCT ("Windows.Foundation.Numerics", "Vector3", "System.Numerics", "Vector3", SystemNumericsVectors, SystemNumericsVectors, Windows_Foundation_Numerics_Vector3, System_Numerics_Vector3, STRUCT_FIELDS(L"Single", L"Single", L"Single")) -DEFINE_PROJECTED_STRUCT ("Windows.Foundation.Numerics", "Vector4", "System.Numerics", "Vector4", SystemNumericsVectors, SystemNumericsVectors, Windows_Foundation_Numerics_Vector4, System_Numerics_Vector4, STRUCT_FIELDS(L"Single", L"Single", L"Single", L"Single")) -DEFINE_PROJECTED_STRUCT ("Windows.Foundation.Numerics", "Matrix3x2", "System.Numerics", "Matrix3x2", SystemNumericsVectors, SystemNumericsVectors, Windows_Foundation_Numerics_Matrix3x2, System_Numerics_Matrix3x2, STRUCT_FIELDS(L"Single", L"Single", L"Single", L"Single", L"Single", L"Single")) -DEFINE_PROJECTED_STRUCT ("Windows.Foundation.Numerics", "Matrix4x4", "System.Numerics", "Matrix4x4", SystemNumericsVectors, SystemNumericsVectors, Windows_Foundation_Numerics_Matrix4x4, System_Numerics_Matrix4x4, STRUCT_FIELDS(L"Single", L"Single", L"Single", L"Single", L"Single", L"Single", L"Single", L"Single", L"Single", L"Single", L"Single", L"Single", L"Single", L"Single", L"Single", L"Single")) -DEFINE_PROJECTED_STRUCT ("Windows.Foundation.Numerics", "Plane", "System.Numerics", "Plane", SystemNumericsVectors, SystemNumericsVectors, Windows_Foundation_Numerics_Plane, System_Numerics_Plane, STRUCT_FIELDS(L"Windows.Foundation.Numerics.Vector3", L"Single")) -DEFINE_PROJECTED_STRUCT ("Windows.Foundation.Numerics", "Quaternion", "System.Numerics", "Quaternion", SystemNumericsVectors, SystemNumericsVectors, Windows_Foundation_Numerics_Quaternion, System_Numerics_Quaternion, STRUCT_FIELDS(L"Single", L"Single", L"Single", L"Single")) - -#ifdef DEFINE_PROJECTED_ATTRIBUTETARGETS_VALUE - -// Windows.Foundation.Metadata.AttributeTarget and System.AttributeTarget enum -// define different bits for everything (@todo: Be nice to change that before we ship.) -// -// This table encapsulates the correspondence. NOTE: Some rows in the CLR column store a 0 -// to indicate that the CLR has no corresponding bit for the WinRT value. -// -// WinRT CLR -DEFINE_PROJECTED_ATTRIBUTETARGETS_VALUE(0x00000001, 0x00001000) // AttributeTargets.Delegate -DEFINE_PROJECTED_ATTRIBUTETARGETS_VALUE(0x00000002, 0x00000010) // AttributeTargets.Enum -DEFINE_PROJECTED_ATTRIBUTETARGETS_VALUE(0x00000004, 0x00000200) // AttributeTargets.Event -DEFINE_PROJECTED_ATTRIBUTETARGETS_VALUE(0x00000008, 0x00000100) // AttributeTargets.Field -DEFINE_PROJECTED_ATTRIBUTETARGETS_VALUE(0x00000010, 0x00000400) // AttributeTargets.Interface -DEFINE_PROJECTED_ATTRIBUTETARGETS_VALUE(0x00000020, 0x00000000) // AttributeTargets.InterfaceGroup (no equivalent in CLR) -DEFINE_PROJECTED_ATTRIBUTETARGETS_VALUE(0x00000040, 0x00000040) // AttributeTargets.Method -DEFINE_PROJECTED_ATTRIBUTETARGETS_VALUE(0x00000080, 0x00000800) // AttributeTargets.Parameter -DEFINE_PROJECTED_ATTRIBUTETARGETS_VALUE(0x00000100, 0x00000080) // AttributeTargets.Property -DEFINE_PROJECTED_ATTRIBUTETARGETS_VALUE(0x00000200, 0x00000004) // AttributeTargets.RuntimeClass <--> Class -DEFINE_PROJECTED_ATTRIBUTETARGETS_VALUE(0x00000400, 0x00000008) // AttributeTargets.Struct -DEFINE_PROJECTED_ATTRIBUTETARGETS_VALUE(0x00000800, 0x00000000) // AttributeTargets.InterfaceImpl (no equivalent in CLR) - -#endif // #ifdef DEFINE_PROJECTED_ATTRIBUTETARGETS_VALUES - - -DEFINE_HIDDEN_WINRT_TYPE("Windows.Foundation.Metadata", "GCPressureAttribute") -DEFINE_HIDDEN_WINRT_TYPE("Windows.Foundation.Metadata", "GCPressureAmount") - -DEFINE_HIDDEN_WINRT_TYPE("Windows.Foundation", "IPropertyValue") -DEFINE_HIDDEN_WINRT_TYPE("Windows.Foundation", "IReferenceArray`1") - - -#ifdef __LOCAL_DEFINE_PROJECTED_RUNTIMECLASS -#undef DEFINE_PROJECTED_RUNTIMECLASS -#endif // __LOCAL_DEFINE_PROJECTED_RUNTIMECLASS - -#ifdef __LOCAL_DEFINE_PROJECTED_STRUCT -#undef DEFINE_PROJECTED_STRUCT -#endif // __LOCAL_DEFINE_PROJECTED_STRUCT - -#ifdef __LOCAL_DEFINE_PROJECTED_JUPITER_STRUCT -#undef DEFINE_PROJECTED_JUPITER_STRUCT -#endif // __LOCAL_DEFINE_PROJECTED_JUPITER_STRUCT - -#ifdef __LOCAL_DEFINE_PROJECTED_ENUM -#undef DEFINE_PROJECTED_ENUM -#endif // __LOCAL_DEFINE_PROJECTED_ENUM - -#ifdef __LOCAL_DEFINE_PROJECTED_INTERFACE -#undef DEFINE_PROJECTED_INTERFACE -#endif // __LOCAL_DEFINE_PROJECTED_INTERFACE - -#ifdef __LOCAL_DEFINE_PROJECTED_PINTERFACE -#undef DEFINE_PROJECTED_PINTERFACE -#endif // __LOCAL_DEFINE_PROJECTED_PINTERFACE - -#ifdef __LOCAL_DEFINE_PROJECTED_DELEGATE -#undef DEFINE_PROJECTED_DELEGATE -#endif // __LOCAL_DEFINE_PROJECTED_DELEGATE - -#ifdef __LOCAL_DEFINE_PROJECTED_PDELEGATE -#undef DEFINE_PROJECTED_PDELEGATE -#endif // __LOCAL_DEFINE_PROJECTED_PDELEGATE - -#ifdef __LOCAL_DEFINE_PROJECTED_ATTRIBUTE -#undef DEFINE_PROJECTED_ATTRIBUTE -#endif // __LOCAL_DEFINE_PROJECTED_ATTRIBUTE - -#ifdef __LOCAL_DEFINE_HIDDEN_WINRT_TYPE -#undef DEFINE_HIDDEN_WINRT_TYPE -#endif // __LOCAL_DEFINE_HIDDEN_WINRT_TYPE - -#undef JUPITER_PROJECTION_NS -#undef JUPITER_PROJECTION_CONTROLS_PRIMITIVES_NS -#undef JUPITER_PROJECTION_MEDIA_NS -#undef JUPITER_PROJECTION_MEDIA_ANIMATION_NS -#undef JUPITER_PROJECTION_MEDIA_3D_NS -#undef JUPITER_FOUNDATION_PROJECTION_NS diff --git a/src/coreclr/src/inc/zapper.h b/src/coreclr/src/inc/zapper.h index 159f5fe..74b9892 100644 --- a/src/coreclr/src/inc/zapper.h +++ b/src/coreclr/src/inc/zapper.h @@ -117,7 +117,6 @@ class Zapper SString m_platformResourceRoots; SString m_appPaths; SString m_appNiPaths; - SString m_platformWinmdPaths; #if !defined(FEATURE_MERGE_JIT_AND_ENGINE) SString m_CLRJITPath; @@ -350,7 +349,6 @@ class Zapper void SetPlatformResourceRoots(LPCWSTR pwzPlatformResourceRoots); void SetAppPaths(LPCWSTR pwzAppPaths); void SetAppNiPaths(LPCWSTR pwzAppNiPaths); - void SetPlatformWinmdPaths(LPCWSTR pwzPlatformWinmdPaths); #if !defined(FEATURE_MERGE_JIT_AND_ENGINE) void SetCLRJITPath(LPCWSTR pwszCLRJITPath); @@ -440,8 +438,6 @@ class ZapperOptions CORJIT_FLAGS m_compilerFlags; - bool m_fNoMetaData; // Do not copy metadata and IL to native image - void SetCompilerFlags(void); ZapperOptions(); diff --git a/src/coreclr/src/md/CMakeLists.txt b/src/coreclr/src/md/CMakeLists.txt index bfc4efa..910d7fd 100644 --- a/src/coreclr/src/md/CMakeLists.txt +++ b/src/coreclr/src/md/CMakeLists.txt @@ -20,6 +20,3 @@ add_subdirectory(hotdata) add_subdirectory(ceefilegen) add_subdirectory(datasource) add_subdirectory(staticmd) -if(CLR_CMAKE_TARGET_WIN32) - add_subdirectory(winmd) -endif(CLR_CMAKE_TARGET_WIN32) diff --git a/src/coreclr/src/md/compiler/disp.cpp b/src/coreclr/src/md/compiler/disp.cpp index deeec8f..fc9d773 100644 --- a/src/coreclr/src/md/compiler/disp.cpp +++ b/src/coreclr/src/md/compiler/disp.cpp @@ -178,25 +178,14 @@ ErrExit: //***************************************************************************** -// Deliver scope to caller of OpenScope or OpenScopeOnMemory (this may -// involve wrapping a WinMD adapter.) +// Deliver scope to caller of OpenScope or OpenScopeOnMemory //***************************************************************************** static HRESULT DeliverScope(IMDCommon *pMDCommon, REFIID riid, DWORD dwOpenFlags, IUnknown **ppIUnk) { HRESULT hr; BEGIN_ENTRYPOINT_NOTHROW; -#if defined(FEATURE_COMINTEROP) - IfFailGo((dwOpenFlags & ofNoTransform) ? S_FALSE : CheckIfWinMDAdapterNeeded(pMDCommon)); - if (hr == S_OK) - { - IfFailGo(CreateWinMDImport(pMDCommon, riid, (void**)ppIUnk)); - } - else -#endif - { - IfFailGo(pMDCommon->QueryInterface(riid, (void**)ppIUnk)); - } + IfFailGo(pMDCommon->QueryInterface(riid, (void**)ppIUnk)); ErrExit: END_ENTRYPOINT_NOTHROW; diff --git a/src/coreclr/src/md/compiler/importhelper.cpp b/src/coreclr/src/md/compiler/importhelper.cpp index 3a8a0a2..068206a 100644 --- a/src/coreclr/src/md/compiler/importhelper.cpp +++ b/src/coreclr/src/md/compiler/importhelper.cpp @@ -857,7 +857,7 @@ ImportHelper::FindTypeDefByName( szTypeDefNamespace = ""; if (tkEnclosingClass == TokenFromRid(1, mdtModule)) - { // Module scope is the same as no scope (used in .winmd files as TypeRef scope for self-references) + { // Module scope is the same as no scope tkEnclosingClass = mdTokenNil; } diff --git a/src/coreclr/src/md/compiler/regmeta.cpp b/src/coreclr/src/md/compiler/regmeta.cpp index 5d22c27..e79778b 100644 --- a/src/coreclr/src/md/compiler/regmeta.cpp +++ b/src/coreclr/src/md/compiler/regmeta.cpp @@ -1473,9 +1473,6 @@ HRESULT RegMeta::GetVersionString( // S_OK or error. else { //This emptry string matches the fallback behavior we have in other places that query the version string. - //From what I can tell the only caller to this method is the code that tests if we need to apply the WinMD adapter - //and it checks if pVer == "WindowsRuntime". We don't support the debugger custom metadata source scenario with WinMDs (yet?) - //so we intend for that check to return FALSE. *pVer = ""; } #endif diff --git a/src/coreclr/src/md/compiler/regmeta.h b/src/coreclr/src/md/compiler/regmeta.h index eb5c97e..56e6f43 100644 --- a/src/coreclr/src/md/compiler/regmeta.h +++ b/src/coreclr/src/md/compiler/regmeta.h @@ -24,8 +24,6 @@ #include "sigparser.h" -#include "winmdinterfaces.h" - class FilterManager; // Support for symbol binding meta data. This is a custom value hung off of diff --git a/src/coreclr/src/md/enc/mdinternalrw.cpp b/src/coreclr/src/md/enc/mdinternalrw.cpp index daa66d8..c18b842 100644 --- a/src/coreclr/src/md/enc/mdinternalrw.cpp +++ b/src/coreclr/src/md/enc/mdinternalrw.cpp @@ -98,8 +98,6 @@ STDAPI ConvertRO2RW( // Avoid confusion. *ppIUnk = 0; - IfFailGo(VerifyNotWinMD(pRO, "ConvertRO2RW() not supported on .winmd files.")); - // If the interface is already RW, done, just return. if (pRO->QueryInterface(IID_IMDInternalImportENC, (void**)&pRW) == S_OK) { @@ -226,8 +224,6 @@ STDAPI GetMDPublicInterfaceFromInternal( _ASSERTE(pIUnkInternal && ppIUnkPublic); *ppIUnkPublic = 0; - IfFailGo(VerifyNotWinMD((IUnknown*)pIUnkInternal, "GetMDPublicInterfaceFromInternal() not supported on .winmd files.")); - IfFailGo(ConvertRO2RW((IUnknown*)pIUnkInternal, IID_IMDInternalImport, (void **)&pInternalImport)); pIUnkPublic = pInternalImport->GetCachedPublicInterface(TRUE); diff --git a/src/coreclr/src/md/inc/metamodel.h b/src/coreclr/src/md/inc/metamodel.h index 70402a0..db8f914 100644 --- a/src/coreclr/src/md/inc/metamodel.h +++ b/src/coreclr/src/md/inc/metamodel.h @@ -173,11 +173,10 @@ public: // An extension of IMetaModelCommon, exposed by read-only importers only. -// (The primary user for this is the WinMD import adapter which needs -// a unified view of RegMeta and MDInternalRO.) // -// These methods were separated from IMetaModelCommon as they are only used by -// the WinMDAdapter and we don't want the maintainence and code-coverage cost +// These methods were separated from IMetaModelCommon as +// Enc-aware versions of these methods haven't been needed +// and we don't want the maintainence and code-coverage cost // of providing Enc-aware versions of these methods. class IMetaModelCommonRO : public IMetaModelCommon { @@ -2125,6 +2124,23 @@ public: }; //class CMiniMdTemplate +//----------------------------------------------------------------------------------------------------- +// A common interface unifying RegMeta and MDInternalRO, giving the adapter a common interface to +// access the raw metadata. +//----------------------------------------------------------------------------------------------------- + +// {4F8EE8A3-24F8-4241-BC75-C8CAEC0255B5} +EXTERN_GUID(IID_IMDCommon, 0x4f8ee8a3, 0x24f8, 0x4241, 0xbc, 0x75, 0xc8, 0xca, 0xec, 0x2, 0x55, 0xb5); + +#undef INTERFACE +#define INTERFACE IID_IMDCommon +DECLARE_INTERFACE_(IMDCommon, IUnknown) +{ + STDMETHOD_(IMetaModelCommon*, GetMetaModelCommon)() PURE; + STDMETHOD_(IMetaModelCommonRO*, GetMetaModelCommonRO)() PURE; + STDMETHOD(GetVersionString)(LPCSTR *pszVersionString) PURE; +}; + #undef SETP #undef _GETCDTKN diff --git a/src/coreclr/src/md/inc/verifylayouts.h b/src/coreclr/src/md/inc/verifylayouts.h index 6779e56..aa3201fb 100644 --- a/src/coreclr/src/md/inc/verifylayouts.h +++ b/src/coreclr/src/md/inc/verifylayouts.h @@ -102,7 +102,6 @@ #include // offsetof #include "static_assert.h" #include "metamodel.h" -#include "WinMDInterfaces.h" #include "MDInternalRW.h" // other types provide friend access to this type so that the diff --git a/src/coreclr/src/md/inc/winmdinterfaces.h b/src/coreclr/src/md/inc/winmdinterfaces.h deleted file mode 100644 index d01cd9d..0000000 --- a/src/coreclr/src/md/inc/winmdinterfaces.h +++ /dev/null @@ -1,112 +0,0 @@ -// 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. - -// -// ======================================================================================================= -// Defines the surface area between md\WinMD and md\everything-else. -// -// md\WinMD contains adapter importers that wrap RegMeta and MDInternalRO to make .winmd files look like -// regular .NET assemblies. -// ======================================================================================================= - -#ifndef __WINMDINTERFACES_H__ -#define __WINMDINTERFACES_H__ - -#include "metamodel.h" - - -//----------------------------------------------------------------------------------------------------- -// A common interface unifying RegMeta and MDInternalRO, giving the adapter a common interface to -// access the raw metadata. -//----------------------------------------------------------------------------------------------------- - -// {4F8EE8A3-24F8-4241-BC75-C8CAEC0255B5} -EXTERN_GUID(IID_IMDCommon, 0x4f8ee8a3, 0x24f8, 0x4241, 0xbc, 0x75, 0xc8, 0xca, 0xec, 0x2, 0x55, 0xb5); - -#undef INTERFACE -#define INTERFACE IID_IMDCommon -DECLARE_INTERFACE_(IMDCommon, IUnknown) -{ - STDMETHOD_(IMetaModelCommon*, GetMetaModelCommon)() PURE; - STDMETHOD_(IMetaModelCommonRO*, GetMetaModelCommonRO)() PURE; - STDMETHOD(GetVersionString)(LPCSTR *pszVersionString) PURE; -}; - - -//----------------------------------------------------------------------------------------------------- -// Returns: -// S_OK: if WinMD adapter should be used. -// S_FALSE: if not -//----------------------------------------------------------------------------------------------------- -HRESULT CheckIfWinMDAdapterNeeded(IMDCommon *pRawMDCommon); - - - -//----------------------------------------------------------------------------------------------------- -// Factory method that creates an WinMD adapter that implements: -// -// IMetaDataImport2 -// IMetaDataAssemblyImport -// IMetaDataValidate -// IMarshal -// IMDCommon (subset) -// -// IMDCommon is included as a concession to the fact that certain IMetaDataEmit apis have -// an (apparently undocumented) dependency on their importer arguments supporting this. -// -// You must provide a regular MD importer that implements: -// -// IMDCommon -// IMetaDataImport2 -// IMetaDataAssemblyImport -// IMetaDataValidate -// -// The underlying metadata file must follow these restrictions: -// -// - Have an existing assemblyRef to "mscorlib" -// -//----------------------------------------------------------------------------------------------------- -HRESULT CreateWinMDImport(IMDCommon * pRawMDCommon, REFIID riid, /*[out]*/ void **ppWinMDImport); - - -//----------------------------------------------------------------------------------------------------- -// Factory method that creates an WinMD adapter that implements IMDInternalImport. -// You must provide a regular MD importer that implements: -// -// IMDCommon -// IMDInternalImport -// -// The underlying metadata file must follow these restrictions: -// -// - Have an existing assemblyRef to "mscorlib" -// -//----------------------------------------------------------------------------------------------------- -#ifdef FEATURE_METADATA_INTERNAL_APIS -HRESULT CreateWinMDInternalImportRO(IMDCommon * pRawMDCommon, REFIID riid, /*[out]*/ void **ppWinMDInternalImport); - -#endif // FEATURE_METADATA_INTERNAL_APIS -//----------------------------------------------------------------------------------------------------- -// S_OK if pUnknown is really a WinMD wrapper. This is just a polite way of asking "is it bad to -// to static cast pUnknown to RegMeta/MDInternalRO." -//----------------------------------------------------------------------------------------------------- -HRESULT CheckIfImportingWinMD(IUnknown *pUnknown); - - -//----------------------------------------------------------------------------------------------------- -// E_NOTIMPL if pUnknown is really a WinMD wrapper. -//----------------------------------------------------------------------------------------------------- -HRESULT VerifyNotWinMDHelper(IUnknown *pUnknown -#ifdef _DEBUG - ,LPCSTR assertMsg - ,LPCSTR file - ,int line -#endif //_DEBUG - ); -#define VerifyNotWinMD(pUnknown, assertMsg) S_OK - - -#endif //__WINMDINTERFACES_H__ - - - diff --git a/src/coreclr/src/md/runtime/CMakeLists.txt b/src/coreclr/src/md/runtime/CMakeLists.txt index 109b9f1..9b5e3f2 100644 --- a/src/coreclr/src/md/runtime/CMakeLists.txt +++ b/src/coreclr/src/md/runtime/CMakeLists.txt @@ -30,7 +30,6 @@ set(MDRUNTIME_HEADERS ../inc/metamodel.h ../inc/metamodelro.h ../inc/recordpool.h - ../inc/winmdinterfaces.h metamodelcolumndefs.h mdinternaldisp.h mdinternalro.h diff --git a/src/coreclr/src/md/runtime/mdinternaldisp.cpp b/src/coreclr/src/md/runtime/mdinternaldisp.cpp index e489737..c11a492 100644 --- a/src/coreclr/src/md/runtime/mdinternaldisp.cpp +++ b/src/coreclr/src/md/runtime/mdinternaldisp.cpp @@ -16,7 +16,7 @@ #include "corpriv.h" #include "assemblymdinternaldisp.h" #include "pedecoder.h" -#include "winmdinterfaces.h" +#include "metamodel.h" #ifdef FEATURE_METADATA_INTERNAL_APIS @@ -184,18 +184,7 @@ STDAPI GetMDInternalInterface( IfFailGo( pInternalRO->Init(const_cast(pData), cbData) ); -#ifdef FEATURE_COMINTEROP - IfFailGo(pInternalRO->QueryInterface(IID_IMDCommon, (void**)&pInternalROMDCommon)); - IfFailGo( (flags & ofNoTransform) ? S_FALSE : CheckIfWinMDAdapterNeeded(pInternalROMDCommon)); - if (hr == S_OK) - { - IfFailGo(CreateWinMDInternalImportRO(pInternalROMDCommon, riid, (void**)ppIUnk)); - } - else -#endif // FEATURE_COMINTEROP - { - IfFailGo(pInternalRO->QueryInterface(riid, ppIUnk)); - } + IfFailGo(pInternalRO->QueryInterface(riid, ppIUnk)); } else diff --git a/src/coreclr/src/md/runtime/mdinternalro.h b/src/coreclr/src/md/runtime/mdinternalro.h index f215fb1..0094231 100644 --- a/src/coreclr/src/md/runtime/mdinternalro.h +++ b/src/coreclr/src/md/runtime/mdinternalro.h @@ -12,7 +12,7 @@ #ifndef __MDInternalRO__h__ #define __MDInternalRO__h__ -#include "winmdinterfaces.h" +#include "metamodel.h" #ifdef FEATURE_METADATA_INTERNAL_APIS diff --git a/src/coreclr/src/md/winmd/CMakeLists.txt b/src/coreclr/src/md/winmd/CMakeLists.txt deleted file mode 100644 index 3b52f31..0000000 --- a/src/coreclr/src/md/winmd/CMakeLists.txt +++ /dev/null @@ -1,44 +0,0 @@ -set(MDWINMD_SOURCES - adapter.cpp - winmdimport.cpp - winmdinternalimportro.cpp -) - -set(MDWINMD_HEADERS - ../../inc/cor.h - ../../inc/corpriv.h - ../../inc/metadataexports.h - ../../inc/nsutilpriv.h - ../../inc/sigbuilder.h - ../../inc/sigparser.h - ../../inc/utsem.h - ../inc/winmdinterfaces.h - inc/adapter.h - inc/memotable.h -) - -convert_to_absolute_path(MDWINMD_HEADERS ${MDWINMD_HEADERS}) -convert_to_absolute_path(MDWINMD_SOURCES ${MDWINMD_SOURCES}) - -if (CLR_CMAKE_TARGET_WIN32) - list(APPEND MDWINMD_SOURCES ${MDWINMD_HEADERS}) -endif (CLR_CMAKE_TARGET_WIN32) - - -add_library_clr(mdwinmd_dac ${MDWINMD_SOURCES}) -set_target_properties(mdwinmd_dac PROPERTIES DAC_COMPONENT TRUE) -target_precompile_header(TARGET mdwinmd_dac HEADER stdafx.h) - -add_library_clr(mdwinmd_wks ${MDWINMD_SOURCES}) -target_compile_definitions(mdwinmd_wks PRIVATE FEATURE_METADATA_EMIT_ALL) -target_precompile_header(TARGET mdwinmd_wks HEADER stdafx.h) - -if(CLR_CMAKE_TARGET_WIN32) - add_library_clr(mdwinmd_dbi ${MDWINMD_SOURCES}) - set_target_properties(mdwinmd_dbi PROPERTIES DBI_COMPONENT TRUE) - target_precompile_header(TARGET mdwinmd_dbi HEADER stdafx.h) - - add_library_clr(mdwinmd_crossgen ${MDWINMD_SOURCES}) - set_target_properties(mdwinmd_crossgen PROPERTIES CROSSGEN_COMPONENT TRUE) - target_precompile_header(TARGET mdwinmd_crossgen HEADER stdafx.h) -endif(CLR_CMAKE_TARGET_WIN32) diff --git a/src/coreclr/src/md/winmd/adapter.cpp b/src/coreclr/src/md/winmd/adapter.cpp deleted file mode 100644 index 61ae4f9..0000000 --- a/src/coreclr/src/md/winmd/adapter.cpp +++ /dev/null @@ -1,2740 +0,0 @@ -// 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. -#include "stdafx.h" -#include "sigparser.h" -#include "sigbuilder.h" -#include "inc/adapter.h" -#include "clrversion.h" - -//---------------------------------------------------------------------------------------------------- -// The name prefixes used by WinMD to hide/unhide WinRT and CLR versions of RuntimeClasses. -//---------------------------------------------------------------------------------------------------- - -static const char s_szWinRTPrefix[] = ""; -//static const size_t s_ncWinRTPrefix = sizeof(s_szWinRTPrefix) - 1; - -static const char s_szCLRPrefix[] = ""; -static const size_t s_ncCLRPrefix = sizeof(s_szCLRPrefix) - 1; - -// the public key token of the ecma key used by some framework assemblies (mscorlib, system, etc). -// note that some framework assemblies use a different key: b03f5f7f11d50a3a -static const BYTE s_pbFrameworkPublicKeyToken[] = {0xB7,0x7A,0x5C,0x56,0x19,0x34,0xE0,0x89}; - - -//----------------------------------------------------------------------------------------------------- -// Returns: -// S_OK: if WinMD adapter should be used. -// S_FALSE: if not -//----------------------------------------------------------------------------------------------------- -HRESULT CheckIfWinMDAdapterNeeded(IMDCommon *pRawMDCommon) -{ - HRESULT hr; - _ASSERTE(pRawMDCommon != NULL); - - LPCSTR szMetadataVersionString = NULL; - -#ifndef DACCESS_COMPILE -#ifdef _DEBUG - //--------------------------------------------------------------------------------------------------------- - // set COMPLUS_INTERNAL_MD_WinMD_AssertOnIllegalUsage=1 - // - // to turn the WinMD adapter off universally. - //--------------------------------------------------------------------------------------------------------- - if (CLRConfig::GetConfigValue(CLRConfig::INTERNAL_MD_WinMD_Disable)) - { - hr = S_FALSE; - goto ErrExit; - } -#endif //_DEBUG -#endif - - //--------------------------------------------------------------------------------------------------------- - // This is the real check: activate WinMD based on metadata version string. - //--------------------------------------------------------------------------------------------------------- - static const LPCSTR g_szWindowsRuntimeVersion = "WindowsRuntime "; - IfFailGo(pRawMDCommon->GetVersionString(&szMetadataVersionString)); - if (0 == strncmp(szMetadataVersionString, g_szWindowsRuntimeVersion, strlen(g_szWindowsRuntimeVersion))) - { - hr = S_OK; - goto ErrExit; - } - else - { - hr = S_FALSE; - goto ErrExit; - } - - ErrExit: - return hr; -} - - -//------------------------------------------------------------------------------ - -// -// Factory for WinMDAdapters. Caller must use "delete" to destroy adapter when done. -// -/*static*/ HRESULT WinMDAdapter::Create(IMDCommon *pRawMDCommon, /*[out]*/ WinMDAdapter **ppAdapter) -{ - HRESULT hr; - LPWSTR wszCorVersion = NULL; - WinMDAdapter* pNewAdapter = NULL; - ULONG numAssemblyRefs = 0; - const char *szClrPortion = NULL; - - *ppAdapter = NULL; - - pNewAdapter = new (nothrow) WinMDAdapter(pRawMDCommon); - if (!pNewAdapter) - { - IfFailGo(E_OUTOFMEMORY); - } - - //------------------------------------------------------------------------------------------------ - // Create a stored string to hold our phantom metadata version string. - //------------------------------------------------------------------------------------------------ - LPCSTR szVersion; - IfFailGo(pRawMDCommon->GetVersionString(&szVersion)); - szClrPortion = strchr(szVersion, ';'); - if (szClrPortion) - { - pNewAdapter->m_scenario = kWinMDExp; - szClrPortion++; - - // skip the "CLR" prefix if present - if ((szClrPortion[0] == 'c' || szClrPortion[0] == 'C') && - (szClrPortion[1] == 'l' || szClrPortion[1] == 'L') && - (szClrPortion[2] == 'r' || szClrPortion[2] == 'R')) - { - szClrPortion += 3; - } - while (szClrPortion[0] == ' ') - { - szClrPortion++; - } - - size_t ncClrPortion = strlen(szClrPortion); - pNewAdapter->m_pRedirectedVersionString = new (nothrow) char[ncClrPortion + 1]; - IfNullGo(pNewAdapter->m_pRedirectedVersionString); - memcpy(pNewAdapter->m_pRedirectedVersionString, szClrPortion, ncClrPortion + 1); - } - else - { - pNewAdapter->m_scenario = kWinMDNormal; -#ifndef DACCESS_COMPILE - LPCSTR szCorVersion = CLR_METADATA_VERSION; - size_t nch = strlen(szCorVersion) + 1; - pNewAdapter->m_pRedirectedVersionString = new (nothrow) char[nch]; - IfNullGo(pNewAdapter->m_pRedirectedVersionString); - memcpy(pNewAdapter->m_pRedirectedVersionString, szCorVersion, nch); -#else - pNewAdapter->m_pRedirectedVersionString = new (nothrow) char[1]; - pNewAdapter->m_pRedirectedVersionString[0] = 0; -#endif - } - - - //------------------------------------------------------------------------------------------------ - // Find an assemblyRef to mscorlib (required to exist in .winmd files precisely to make the adapter's job easier. - //------------------------------------------------------------------------------------------------ - numAssemblyRefs = pNewAdapter->m_pRawMetaModelCommonRO->CommonGetRowCount(mdtAssemblyRef); - pNewAdapter->m_assemblyRefMscorlib = 0; - pNewAdapter->m_fReferencesMscorlibV4 = FALSE; - for (ULONG rid = 1; rid <= numAssemblyRefs; rid++) - { - mdAssemblyRef mdar = mdtAssemblyRef|rid; - LPCSTR arefName; - USHORT usMajorVersion; - IfFailGo(pNewAdapter->m_pRawMetaModelCommonRO->CommonGetAssemblyRefProps(mdar, &usMajorVersion, NULL, NULL, NULL, NULL, NULL, NULL, &arefName, NULL, NULL, NULL)); - - // We check for legacy Core library name since Windows.winmd references mscorlib and not System.Private.CoreLib - if (0 == strcmp(arefName, LegacyCoreLibName_A)) - { - pNewAdapter->m_assemblyRefMscorlib = mdar; - - if (usMajorVersion == 4) - { - // Older WinMDExp used to incorrectly generate an assemblyRef to 4.0.0.0 mscorlib. - // We use this flag to implement back-compat quirks. - pNewAdapter->m_fReferencesMscorlibV4 = TRUE; - } - - break; - } - } - if (pNewAdapter->m_assemblyRefMscorlib == 0) - { - // .winmd files are required to have an assemblyRef to mscorlib. - IfFailGo(COR_E_BADIMAGEFORMAT); - } - - - //------------------------------------------------------------------------------------------------ - // All initialization tasks done. - //------------------------------------------------------------------------------------------------ - *ppAdapter = pNewAdapter; - hr = S_OK; - - ErrExit: - delete wszCorVersion; - if (FAILED(hr)) - delete pNewAdapter; - return hr; -} - - -//------------------------------------------------------------------------------ - -WinMDAdapter::WinMDAdapter(IMDCommon *pRawMDCommon) - : m_typeRefTreatmentMemoTable(pRawMDCommon->GetMetaModelCommonRO()->CommonGetRowCount(mdtTypeRef), kTrNotYetInitialized) - , m_typeDefTreatmentMemoTable(pRawMDCommon->GetMetaModelCommonRO()->CommonGetRowCount(mdtTypeDef), kTdNotYetInitialized) - , m_methodDefTreatmentMemoTable(pRawMDCommon->GetMetaModelCommonRO()->CommonGetRowCount(mdtMethodDef), kMdNotYetInitialized) - , m_redirectedCABlobsMemoTable(pRawMDCommon->GetMetaModelCommonRO()->CommonGetRowCount(mdtCustomAttribute), NULL) - , m_redirectedMethodDefSigMemoTable(pRawMDCommon->GetMetaModelCommonRO()->CommonGetRowCount(mdtMethodDef), NULL) - , m_redirectedFieldDefSigMemoTable(pRawMDCommon->GetMetaModelCommonRO()->CommonGetRowCount(mdtFieldDef), NULL) - , m_redirectedMemberRefSigMemoTable(pRawMDCommon->GetMetaModelCommonRO()->CommonGetRowCount(mdtMemberRef), NULL) - , m_redirectedPropertySigMemoTable(pRawMDCommon->GetMetaModelCommonRO()->CommonGetRowCount(mdtProperty), NULL) - , m_redirectedTypeSpecSigMemoTable(pRawMDCommon->GetMetaModelCommonRO()->CommonGetRowCount(mdtTypeSpec), NULL) - , m_redirectedMethodSpecSigMemoTable(pRawMDCommon->GetMetaModelCommonRO()->CommonGetRowCount(mdtMethodSpec), NULL) - , m_mangledTypeNameTable(pRawMDCommon->GetMetaModelCommonRO()->CommonGetRowCount(mdtTypeDef), NULL) - , m_extraAssemblyRefCount(-1) -{ - m_rawAssemblyRefCount = pRawMDCommon->GetMetaModelCommonRO()->CommonGetRowCount(mdtAssemblyRef); - m_pRedirectedVersionString = NULL; - m_pRawMetaModelCommonRO = pRawMDCommon->GetMetaModelCommonRO(); -} - -//------------------------------------------------------------------------------ - -WinMDAdapter::~WinMDAdapter() -{ - delete m_pRedirectedVersionString; -} - - -//------------------------------------------------------------------------------ -// Hides projected jupiter struct helper class & interfaces - -struct HiddenWinRTTypeInfo -{ - LPCSTR szWinRTNamespace; - LPCSTR szWinRTName; -}; - -#define DEFINE_PROJECTED_JUPITER_STRUCT(szWinRTNamespace, szWinRTName, szClrNamespace, szClrName, nClrAssemblyIndex, nContractAssemblyIndex, WinRTRedirectedTypeIndex, ClrRedirectedTypeIndex, fieldSizes) \ - { \ - szWinRTNamespace, \ - szWinRTName "Helper" \ - }, - -#define DEFINE_HIDDEN_WINRT_TYPE(szWinRTNamespace, szWinRTName) \ - { \ - szWinRTNamespace, \ - szWinRTName \ - }, - -#define DEFINE_PROJECTED_TYPE(szWinRTNS, szWinRTName, szClrNS, szClrName, nClrAsmIdx, nContractAsmIdx, nWinRTIndex, nClrIndex, nWinMDTypeKind) - -static const HiddenWinRTTypeInfo g_rgHiddenWinRTTypes[] = -{ - #include "WinRTProjectedTypes.h" -}; - -#undef DEFINE_PROJECTED_JUPITER_STRUCT -#undef DEFINE_HIDDEN_WINRT_TYPE -#undef DEFINE_PROJECTED_TYPE - -// Whether the WinRT type should be hidden from managed code -// Example: helper class for projected jupiter structs -// (helper class interfaces are already private by default) -BOOL WinMDAdapter::IsHiddenWinRTType(LPCSTR szWinRTNamespace, LPCSTR szWinRTName) -{ - _ASSERTE(szWinRTNamespace && szWinRTName); - - for (UINT i = 0; i < _countof(g_rgHiddenWinRTTypes); i++) - { - if (0 == strcmp(szWinRTNamespace, g_rgHiddenWinRTTypes[i].szWinRTNamespace)) - { - if (0 == strcmp(szWinRTName, g_rgHiddenWinRTTypes[i].szWinRTName)) - { - return TRUE; - } - } - } - - return FALSE; -} - -//------------------------------------------------------------------------------ - -struct RedirectedTypeInfo -{ - LPCSTR szWinRTNamespace; - LPCSTR szWinRTName; - LPCSTR szWinRTFullName; - LPCWSTR wszWinRTFullName; - LPCSTR szClrNamespace; - LPCSTR szClrName; - LPCSTR szClrFullName; - LPCWSTR wszClrFullName; - const WinMDAdapter::FrameworkAssemblyIndex nClrAssemblyIndex; - const WinMDAdapter::ContractAssemblyIndex nContractAssemblyIndex; - const WinMDAdapter::WinMDTypeKind nTypeKind; -#ifdef _DEBUG - // Indexes for verification of constants RedirectedTypeIndex_* - const UINT dbg_nIndex1; - const UINT dbg_nIndex2; -#endif -}; - -#define DEFINE_PROJECTED_TYPE(szWinRTNS, szWinRTName, szClrNS, szClrName, nClrAsmIdx, nContractAsmIdx, nWinRTIndex, nClrIndex, nWinMDTypeKind) \ - { \ - szWinRTNS, \ - szWinRTName, \ - szWinRTNS "." szWinRTName, \ - L##szWinRTNS W(".") L##szWinRTName, \ - szClrNS, \ - szClrName, \ - szClrNS "." szClrName, \ - L##szClrNS W(".") L##szClrName, \ - WinMDAdapter::FrameworkAssembly_ ## nClrAsmIdx, \ - WinMDAdapter::ContractAssembly_ ## nContractAsmIdx, \ - WinMDAdapter::WinMDTypeKind_ ## nWinMDTypeKind \ - COMMA_INDEBUG(WinMDAdapter::RedirectedTypeIndex_ ## nWinRTIndex) \ - COMMA_INDEBUG(WinMDAdapter::RedirectedTypeIndex_ ## nClrIndex) \ - }, - -static const RedirectedTypeInfo -g_rgRedirectedTypes[WinMDAdapter::RedirectedTypeIndex_Count] = -{ -#include "WinRTProjectedTypes.h" - - -}; -#undef SCAT -#undef DEFINE_PROJECTED_TYPE - -//------------------------------------------------------------------------------ - -/*static*/ BOOL WinMDAdapter::ConvertWellKnownTypeNameFromWinRTToClr(LPCSTR *pszNamespace, LPCSTR *pszName) -{ - return ConvertWellKnownTypeNameFromWinRTToClr(pszNamespace, pszName, NULL); -} - - -// Maps well-known WinRT typenames to CLR typename. If the incoming name is not a well-known WinRT typename, -// this function leaves *pszNamespace and *pszName alone and returns FALSE. Otherwise, it overwrites -// them with pointers to const strings, returns the index into the rewrite table in *pIndex and returns TRUE. -// -// (Note: munged names from WinMDExp are not "well-known" names. Since the idea of munging them is to hide them, -// this function will not transform such names. Not to mention, it would be hard to return such strings -// in a function that no error return mechanism.) -// -/*static*/ BOOL WinMDAdapter::ConvertWellKnownTypeNameFromWinRTToClr(LPCSTR *pszNamespace, LPCSTR *pszName, UINT *pIndex) -{ - _ASSERTE(pszNamespace && pszName); - for (UINT i = 0; i < RedirectedTypeIndex_Count; i++) - { - _ASSERTE(g_rgRedirectedTypes[i].dbg_nIndex1 == i); - _ASSERTE(g_rgRedirectedTypes[i].dbg_nIndex2 == i); - - if (0 == strcmp(*pszNamespace, g_rgRedirectedTypes[i].szWinRTNamespace)) - { - if (0 == strcmp(*pszName, g_rgRedirectedTypes[i].szWinRTName)) - { - *pszNamespace = g_rgRedirectedTypes[i].szClrNamespace; - *pszName = g_rgRedirectedTypes[i].szClrName; - if (pIndex) - *pIndex = i; - return TRUE; - } - } - } - return FALSE; -} - -/*static*/ BOOL WinMDAdapter::ConvertWellKnownFullTypeNameFromWinRTToClr(LPCWSTR *pwszFullName, RedirectedTypeIndex *pIndex) -{ - _ASSERTE(pwszFullName); - for (UINT i = 0; i < RedirectedTypeIndex_Count; i++) - { - _ASSERTE(g_rgRedirectedTypes[i].dbg_nIndex1 == i); - _ASSERTE(g_rgRedirectedTypes[i].dbg_nIndex2 == i); - - if (0 == wcscmp(*pwszFullName, g_rgRedirectedTypes[i].wszWinRTFullName)) - { - *pwszFullName = g_rgRedirectedTypes[i].wszClrFullName; - if (pIndex) - *pIndex = static_cast(i); - return TRUE; - } - } - return FALSE; -} - -//------------------------------------------------------------------------------ - -// Maps well-known CLR typenames to WinRT typename. If the incoming name is not a well-known CLR typename, -// this function leaves *pszNamespace and *pszName alone and returns FALSE. Otherwise, it overwrites -// them with pointers to const strings and returns TRUE. -// -// (Note: munged names from WinMDExp are not "well-known" names. Since the idea of munging them is to hide them, -// this function will not transform such names. Not to mention, it would be hard to return such strings -// in a function that no error return mechanism.) -// -/*static*/ BOOL WinMDAdapter::ConvertWellKnownTypeNameFromClrToWinRT(LPCSTR *pszFullName) -{ - _ASSERTE(pszFullName); - - for (UINT i = 0; i < RedirectedTypeIndex_Count; i++) - { - if (0 == strcmp(g_rgRedirectedTypes[i].szClrFullName, *pszFullName)) - { - *pszFullName = g_rgRedirectedTypes[i].szWinRTFullName; - return TRUE; - } - } - return FALSE; -} - -/*static*/ BOOL WinMDAdapter::ConvertWellKnownTypeNameFromClrToWinRT(LPCSTR *pszNamespace, LPCSTR *pszName) -{ - _ASSERTE(pszNamespace); - _ASSERTE(pszName); - - for (UINT i = 0; i < RedirectedTypeIndex_Count; i++) - { - if (0 == strcmp(g_rgRedirectedTypes[i].szClrNamespace, *pszNamespace) && - 0 == strcmp(g_rgRedirectedTypes[i].szClrName, *pszName)) - { - *pszNamespace = g_rgRedirectedTypes[i].szWinRTNamespace; - *pszName = g_rgRedirectedTypes[i].szWinRTName; - - return TRUE; - } - } - return FALSE; -} - -//--------------------------------------------------------------------------------------- -// -// Returns names of redirected type 'index'. -// -//static -void -WinMDAdapter::GetRedirectedTypeInfo( - RedirectedTypeIndex index, - LPCSTR * pszClrNamespace, - LPCSTR * pszClrName, - LPCSTR * pszFullWinRTName, - FrameworkAssemblyIndex * pFrameworkAssemblyIdx, - ContractAssemblyIndex * pContractAssemblyIdx, - WinMDTypeKind * pWinMDTypeKind) -{ - _ASSERTE(index < RedirectedTypeIndex_Count); - - if (pszClrName != nullptr) - { - *pszClrName = g_rgRedirectedTypes[index].szClrName; - } - if (pszClrNamespace != nullptr) - { - *pszClrNamespace = g_rgRedirectedTypes[index].szClrNamespace; - } - if (pszFullWinRTName != nullptr) - { - *pszFullWinRTName = g_rgRedirectedTypes[index].szWinRTFullName; - } - if (pFrameworkAssemblyIdx != nullptr) - { - *pFrameworkAssemblyIdx = g_rgRedirectedTypes[index].nClrAssemblyIndex; - } - if (pContractAssemblyIdx != nullptr) - { - *pContractAssemblyIdx = g_rgRedirectedTypes[index].nContractAssemblyIndex; - } - if (pWinMDTypeKind != nullptr) - { - *pWinMDTypeKind = g_rgRedirectedTypes[index].nTypeKind; - } -} - -//--------------------------------------------------------------------------------------- -// -// Returns WinRT name of redirected type 'index'. -// -//static -LPCWSTR -WinMDAdapter::GetRedirectedTypeFullWinRTName( - RedirectedTypeIndex index) -{ - _ASSERTE(index < RedirectedTypeIndex_Count); - - return g_rgRedirectedTypes[index].wszWinRTFullName; -} - -//--------------------------------------------------------------------------------------- -// -// Returns CLR name of redirected type 'index'. -// -//static -LPCSTR -WinMDAdapter::GetRedirectedTypeFullCLRName( - RedirectedTypeIndex index) -{ - _ASSERTE(index < RedirectedTypeIndex_Count); - - return g_rgRedirectedTypes[index].szClrFullName; -} - -//------------------------------------------------------------------------------ -// -// Get TypeRefTreatment value for a TypeRef -// -HRESULT - WinMDAdapter::GetTypeDefTreatment( - mdTypeDef tkTypeDef, - ULONG * pTypeDefTreatment) -{ - HRESULT hr; - - _ASSERTE(pTypeDefTreatment != NULL); - _ASSERTE(TypeFromToken(tkTypeDef) == mdtTypeDef); - - ULONG typeDefIndex = RidFromToken(tkTypeDef) - 1; - ULONG treatment; - IfFailGo(m_typeDefTreatmentMemoTable.GetEntry(typeDefIndex, &treatment)); - if (hr == S_FALSE) - { - LPCSTR szNamespace; - LPCSTR szName; - ULONG dwFlags; - mdToken extends; - IfFailGo(m_pRawMetaModelCommonRO->CommonGetTypeDefProps(tkTypeDef, &szNamespace, &szName, &dwFlags, &extends, NULL)); - treatment = kTdOther; - ULONG baseTypeRefTreatment = kTrNotYetInitialized; - - // We only want to treat this type special if it has metadata that was encoded as WinRT metadata - if (IsTdWindowsRuntime(dwFlags)) - { - // We need to know whether the typeDef is an Enum/Struct/Delegate/Attribute - if (TypeFromToken(extends) == mdtTypeRef) - { - IfFailGo(GetTypeRefTreatment(extends, &baseTypeRefTreatment)); - } - // Force tdWindowsRuntime flag on (@todo: WinMDExp already does this on its own - if AppModel could do so, we could get rid of this code) - if (m_scenario == kWinMDNormal) - { - BOOL isAttribute = FALSE; - if (TypeFromToken(extends) == mdtTypeRef) - { - ULONG treatment; - IfFailGo(GetTypeRefTreatment(extends, &treatment)); - if (treatment == kTrSystemAttribute) - { - isAttribute = TRUE; - } - } - - if (!isAttribute) - { - treatment = kTdNormalNonAttribute; - } - else - { - treatment = kTdNormalAttribute; - } - } - - // Windows.Foundation.WinMD: Hide any type defs that define well-known types that we'd redirect to mscorlib equivalents. - LPCSTR szTempNamespace = szNamespace; - LPCSTR szTempName = szName; - if ((treatment != kTdOther) && ConvertWellKnownTypeNameFromWinRTToClr(&szTempNamespace, &szTempName)) - { - if (treatment == kTdNormalNonAttribute) - treatment = kTdRedirectedToCLRType; - else - treatment = kTdRedirectedToCLRAttribute; - } - else - { - // WinMDExp emits two versions of RuntimeClasses and Enums: - // - // public class Foo {} // the WinRT reference class - // internal class Foo {} // the implementation class that we want WinRT consumers to ignore - // - // The adapter's job is to undo WinMDExp's transformations. I.e. turn the above into: - // - // internal class Foo {} // the WinRT reference class that we want CLR consumers to ignore - // public class Foo {} // the implementation class - // - // We only add the prefix here since the WinRT view is the only view that is marked tdWindowsRuntime - // De-mangling the CLR name is done below. - if (m_scenario == kWinMDExp && !IsTdNested(dwFlags) && IsTdPublic(dwFlags) && !IsTdInterface(dwFlags)) - { - switch (baseTypeRefTreatment) - { - case kTrSystemDelegate: - case kTrSystemAttribute: - case kTrSystemValueType: - { - // Delegates, Attributes, and Structs have only one version - break; - } - - case kTrSystemEnum: - { - if (m_fReferencesMscorlibV4 && !IsTdSpecialName(dwFlags)) - { - // This is a back-compat quirk. Enums exported with an older WinMDExp have only one version - // not marked with tdSpecialName. These enums should *not* be mangled and flipped to private. - break; - } - // fall-thru - } - default: - { - // Prepend "" and flip the visibility to private - treatment = kTdPrefixWinRTName; - } - } - } - } - - // Scan through Custom Attributes on type, looking for interesting bits. We only need to do this for RuntimeClasses. (The if check below is conservative.) - if (!IsTdInterface(dwFlags) && ((treatment == kTdPrefixWinRTName) || (treatment == kTdNormalNonAttribute))) - { - HRESULT hrCA; - hrCA = m_pRawMetaModelCommonRO->CommonGetCustomAttributeByNameEx(tkTypeDef, "Windows.UI.Xaml.TreatAsAbstractComposableClassAttribute", NULL, NULL, NULL); - if (hrCA == S_OK) - { - treatment |= kTdMarkAbstractFlag; - } - } - - if ((treatment == kTdNormalNonAttribute || treatment == kTdNormalAttribute) && // native WinMD, not redirected - IsHiddenWinRTType(szTempNamespace, szTempName) // hidden type - ) - { - // Hide those WinRT types. Examples of those WinRT types that we need to hide are Jupiter struct helpers - treatment |= kTdMarkInternalFlag; - } - } - else if (m_scenario == kWinMDExp && !IsTdNested(dwFlags)) - { - // implementation classes are not marked tdWindowsRuntime, but still need to be modified - // by the adapter. See if we have one of those here. - LPCSTR szUnmangledName; - IfFailGo(CheckIfClrImplementationType(szName, dwFlags, &szUnmangledName)); - if (hr == S_OK) - { - treatment = kTdUnmangleWinRTName; - } - } - - if (baseTypeRefTreatment == kTrSystemEnum) - { - // The typeDef is an Enum. We need to store the treatment. - treatment |= kTdEnum; - } - - IfFailGo(m_typeDefTreatmentMemoTable.InitEntry(typeDefIndex, &treatment)); - } - _ASSERTE(treatment != kTdNotYetInitialized); - - *pTypeDefTreatment = treatment; - hr = S_OK; - -ErrExit: - return hr; -} // WinMDAdapter::GetTypeDefTreatment - -//------------------------------------------------------------------------------ -// Returns renamed typedefs -HRESULT WinMDAdapter::GetTypeDefProps(mdTypeDef tkTypeDef, // [IN] given typedef - LPCUTF8 *pszNamespace, // [OUT] return typedef namespace - LPCUTF8 *pszName, // [OUT] return typedef name - DWORD *pdwFlags, // [OUT] return typedef flags - mdToken *ptkExtends // [OUT] Put base class TypeDef/TypeRef here. - ) -{ - HRESULT hr; - - _ASSERTE(TypeFromToken(tkTypeDef) == mdtTypeDef); - - LPCSTR szNamespace; - LPCSTR szName; - ULONG dwFlags; - mdToken extends; - ULONG treatment; - IfFailGo(m_pRawMetaModelCommonRO->CommonGetTypeDefProps(tkTypeDef, &szNamespace, &szName, &dwFlags, &extends, NULL)); - IfFailGo(GetTypeDefTreatment(tkTypeDef, &treatment)); - - switch (treatment & kTdTreatmentMask) - { - case kTdOther: - break; - - case kTdNormalNonAttribute: - // Force tdWindowsRuntime flag on (@todo: WinMDExp already does this on its own - if AppModel could do so, we could get rid of this code) - dwFlags |= tdWindowsRuntime | tdImport; - break; - - case kTdNormalAttribute: - // Attribute types don't really exist, so we don't want to allow derivation from them either - dwFlags |= tdWindowsRuntime | tdSealed; - break; - - case kTdUnmangleWinRTName: - szName = szName + s_ncCLRPrefix; - dwFlags |= tdPublic; - dwFlags &= ~tdSpecialName; - break; - - case kTdPrefixWinRTName: - { - // Prepend "" and flip the visibility to private - LPCSTR szPrefixedName; - ULONG index = RidFromToken(tkTypeDef) - 1; - IfFailGo(m_mangledTypeNameTable.GetEntry(index, &szPrefixedName)); - if (hr == S_FALSE) - { - IfFailGo(CreatePrefixedName(s_szWinRTPrefix, szName, &szPrefixedName)); - IfFailGo(m_mangledTypeNameTable.InitEntry(index, &szPrefixedName)); - } - szName = szPrefixedName; - dwFlags &= ~tdPublic; - dwFlags |= tdImport; - break; - } - - case kTdRedirectedToCLRType: - dwFlags &= ~tdPublic; - dwFlags |= tdImport; - break; - - case kTdRedirectedToCLRAttribute: - dwFlags &= ~tdPublic; - break; - - default: - UNREACHABLE(); - } - - if ((treatment & kTdMarkAbstractFlag) == kTdMarkAbstractFlag) - { - dwFlags |= tdAbstract; - } - if ((treatment & kTdMarkInternalFlag) == kTdMarkInternalFlag) - { - dwFlags &= ~tdPublic; - } - - if (pszNamespace) - *pszNamespace = szNamespace; - if (pszName) - *pszName = szName; - if (pdwFlags) - *pdwFlags = dwFlags; - if (ptkExtends) - *ptkExtends = extends; - - hr = S_OK; - - ErrExit: - return hr; -} - -//------------------------------------------------------------------------------ - -// Find TypeDef by name -HRESULT WinMDAdapter::FindTypeDef( - LPCSTR szTypeDefNamespace, // [IN] Namespace for the TypeDef. - LPCSTR szTypeDefName, // [IN] Name of the TypeDef. - mdToken tkEnclosingClass, // [IN] TypeDef/TypeRef of enclosing class. - mdTypeDef * ptkTypeDef // [OUT] return typedef -) -{ - HRESULT hr = S_OK; - - _ASSERTE((szTypeDefName != NULL) && (ptkTypeDef != NULL)); - _ASSERTE((TypeFromToken(tkEnclosingClass) == mdtTypeRef) || - (TypeFromToken(tkEnclosingClass) == mdtTypeDef) || - IsNilToken(tkEnclosingClass)); - - // initialize the output parameter - *ptkTypeDef = mdTypeDefNil; - - // Treat no namespace as empty string. - if (szTypeDefNamespace == NULL) - szTypeDefNamespace = ""; - - // Do a linear search - ULONG cTypeDefRecs = m_pRawMetaModelCommonRO->CommonGetRowCount(mdtTypeDef); - - // Get TypeDef of the tkEnclosingClass passed in - if (TypeFromToken(tkEnclosingClass) == mdtTypeRef) - { - LPCUTF8 szNamespace; - LPCUTF8 szName; - mdToken tkResolutionScope; - - IfFailRet(this->GetTypeRefProps(tkEnclosingClass, &szNamespace, &szName, &tkResolutionScope)); - // Update tkEnclosingClass to TypeDef - IfFailRet(this->FindTypeDef( - szNamespace, - szName, - (TypeFromToken(tkResolutionScope) == mdtTypeRef) ? tkResolutionScope : mdTokenNil, - &tkEnclosingClass)); - _ASSERTE(TypeFromToken(tkEnclosingClass) == mdtTypeDef); - } - - // Search for the TypeDef - for (ULONG i = 1; i <= cTypeDefRecs; i++) - { - LPCUTF8 szNamespace; - LPCUTF8 szName; - ULONG dwFlags; - - mdTypeDef tkTypeDefCandidate = TokenFromRid(i, mdtTypeDef); - - IfFailRet(this->GetTypeDefProps(tkTypeDefCandidate, &szNamespace, &szName, &dwFlags, NULL)); - if (!IsTdNested(dwFlags) && !IsNilToken(tkEnclosingClass)) - { - // If the class is not Nested and EnclosingClass passed in is not nil - continue; - } - else if (IsTdNested(dwFlags) && IsNilToken(tkEnclosingClass)) - { - // If the class is nested and EnclosingClass passed is nil - continue; - } - else if (!IsNilToken(tkEnclosingClass)) - { - _ASSERTE(TypeFromToken(tkEnclosingClass) == mdtTypeDef); - - mdTypeDef enclosingTypeDef; - IfFailRet(m_pRawMetaModelCommonRO->CommonGetEnclosingClassOfTypeDef(tkTypeDefCandidate, &enclosingTypeDef)); - if (enclosingTypeDef != tkEnclosingClass) - { - // Type was not nested by tkEnclosingClass - continue; - } - } - - if (strcmp(szTypeDefName, szName) == 0) - { - if (strcmp(szTypeDefNamespace, szNamespace) == 0) - { - *ptkTypeDef = TokenFromRid(i, mdtTypeDef); - return S_OK; - } - } - } - // Cannot find the TypeDef by name - return CLDB_E_RECORD_NOTFOUND; -} - -//------------------------------------------------------------------------------ -// -// Modifies TypeRef names and resolution scope. -// -HRESULT -WinMDAdapter::GetTypeRefProps( - mdTypeRef tkTypeRef, - LPCSTR * pszNamespace, - LPCSTR * pszName, - mdToken * ptkResolutionScope) -{ - - HRESULT hr; - ULONG treatment; - ULONG treatmentClass; - IfFailGo(GetTypeRefTreatment(tkTypeRef, &treatment)); - _ASSERTE(treatment != kTrNotYetInitialized); - - treatmentClass = treatment & kTrClassMask; - if (treatmentClass == kTrClassWellKnownRedirected) - { - ULONG nRewritePairIndex = treatment & ~kTrClassMask; - if (pszNamespace != NULL) - *pszNamespace = g_rgRedirectedTypes[nRewritePairIndex].szClrNamespace; - if (pszName != NULL) - *pszName = g_rgRedirectedTypes[nRewritePairIndex].szClrName; - if (ptkResolutionScope != NULL) - { - ContractAssemblyIndex assemblyIndex = g_rgRedirectedTypes[nRewritePairIndex].nContractAssemblyIndex; - _ASSERTE(assemblyIndex < ContractAssembly_Count); - *ptkResolutionScope = mdtAssemblyRef | (m_rawAssemblyRefCount + assemblyIndex + 1); - } - } - else - { - _ASSERTE(treatmentClass == kTrClassMisc); - switch (treatment) - { - case kTrNoRewriteNeeded: - case kTrSystemValueType: - case kTrSystemEnum: - IfFailGo(m_pRawMetaModelCommonRO->CommonGetTypeRefProps(tkTypeRef, pszNamespace, pszName, ptkResolutionScope)); - break; - - case kTrSystemDelegate: - if (pszNamespace != NULL) *pszNamespace = "System"; - if (pszName != NULL) *pszName = "MulticastDelegate"; - if (ptkResolutionScope) *ptkResolutionScope = mdtAssemblyRef | (m_rawAssemblyRefCount + ContractAssembly_SystemRuntime + 1); - break; - - case kTrSystemAttribute: - if (pszNamespace != NULL) *pszNamespace = "System"; - if (pszName != NULL) *pszName = "Attribute"; - if (ptkResolutionScope != NULL) *ptkResolutionScope = mdtAssemblyRef | (m_rawAssemblyRefCount + ContractAssembly_SystemRuntime + 1); - break; - - default: - _ASSERTE(!"Unknown treatment value."); - break; - - } - } - hr = S_OK; - -ErrExit: - return hr; -} // WinMDAdapter::GetTypeRefProps - -//------------------------------------------------------------------------------ -// -// Get TypeRefTreatment value for a TypeRef -// -HRESULT -WinMDAdapter::GetTypeRefTreatment( - mdTypeRef tkTypeRef, - ULONG * pTypeRefTreatment) -{ - HRESULT hr; - - _ASSERTE(pTypeRefTreatment != NULL); - _ASSERTE(TypeFromToken(tkTypeRef) == mdtTypeRef); - - ULONG typeRefIndex = RidFromToken(tkTypeRef) - 1; - ULONG treatment; - IfFailGo(m_typeRefTreatmentMemoTable.GetEntry(typeRefIndex, &treatment)); - if (hr == S_FALSE) - { - LPCSTR szFromNamespace; - LPCSTR szFromName; - mdToken tkResolutionScope; - IfFailGo(m_pRawMetaModelCommonRO->CommonGetTypeRefProps(tkTypeRef, &szFromNamespace, &szFromName, &tkResolutionScope)); - treatment = kTrNoRewriteNeeded; - UINT redirIndex; - if (ConvertWellKnownTypeNameFromWinRTToClr(&szFromNamespace, &szFromName, &redirIndex)) - { - treatment = kTrClassWellKnownRedirected | redirIndex; - } - else - { - if (0 == strcmp(szFromNamespace, "System")) - { - if (0 == strcmp(szFromName, "MulticastDelegate")) - { - treatment = kTrSystemDelegate; - } - else if (0 == strcmp(szFromName, "Attribute")) - { - treatment = kTrSystemAttribute; - } - else if (0 == strcmp(szFromName, "Enum")) - { - treatment = kTrSystemEnum; - } - else if (0 == strcmp(szFromName, "ValueType")) - { - treatment = kTrSystemValueType; - } - } - } - - // Note that we intentionally do not mangle names of TypeRef's pointing to mangled TypeDef's - // in the same module. This allows WinMDExp to generate "conditional TypeRef's", i.e. references - // to the WinMD view or CLR view, depending on whether the adapter is on. - - IfFailGo(m_typeRefTreatmentMemoTable.InitEntry(typeRefIndex, &treatment)); - } - _ASSERTE(treatment != kTrNotYetInitialized); - - *pTypeRefTreatment = treatment; - hr = S_OK; - -ErrExit: - return hr; -} // WinMDAdapter::GetTypeRefTreatment - - -//------------------------------------------------------------------------------ -// -// Get TypeRef's index in array code:g_rgRedirectedTypes. -// Returns S_OK if TypeRef is redirected and fills its index (*pIndex). -// Returns S_FALSE if type is not well known redirected type (*pIndex is not initialized). - -// -HRESULT -WinMDAdapter::GetTypeRefRedirectedInfo( - mdTypeRef tkTypeRef, - RedirectedTypeIndex * pIndex) -{ - _ASSERTE(TypeFromToken(tkTypeRef) == mdtTypeRef); - _ASSERTE(pIndex != NULL); - - HRESULT hr; - ULONG treatment; - ULONG treatmentClass; - IfFailGo(GetTypeRefTreatment(tkTypeRef, &treatment)); - - treatmentClass = treatment & kTrClassMask; - if (treatmentClass == kTrClassWellKnownRedirected) - { - *pIndex = (RedirectedTypeIndex)(treatment & ~kTrClassMask); - _ASSERTE(*pIndex < RedirectedTypeIndex_Count); - hr = S_OK; - } - else - { - // Do not initialize *pIndex - hr = S_FALSE; - } - -ErrExit: - return hr; -} - -//------------------------------------------------------------------------------ -// -// Finds a typeref by its (transformed) name -// -HRESULT WinMDAdapter::FindTypeRef( // S_OK or error. - LPCSTR szNamespace, // [IN] Namespace for the TypeRef. - LPCSTR szName, // [IN] Name of the TypeRef. - mdToken tkResolutionScope, // [IN] Resolution Scope fo the TypeRef. - mdTypeRef *ptk) // [OUT] TypeRef token returned. -{ - HRESULT hr; - - _ASSERTE(szName); // Crash on NULL pszName (just like the real metadata importer) - _ASSERTE(ptk); // Crash on NULL ptk (just like the real metadata importer) - - - // initialize the output parameter - *ptk = mdTypeRefNil; - - // Treat no namespace as empty string. - if (!szNamespace) - szNamespace = ""; - - ULONG cTypeRefRecs = m_pRawMetaModelCommonRO->CommonGetRowCount(mdtTypeRef); - - for (ULONG i = 1; i <= cTypeRefRecs; i++) - { - LPCUTF8 szNamespaceTmp; - LPCUTF8 szNameTmp; - mdToken tkRes; - - mdTypeRef tr = TokenFromRid(i, mdtTypeRef); - IfFailGo(GetTypeRefProps(tr, &szNamespaceTmp, &szNameTmp, &tkRes)); - if (IsNilToken(tkRes)) - { - if (!IsNilToken(tkResolutionScope)) - continue; - } - else if (tkRes != tkResolutionScope) - continue; - - if (strcmp(szNamespace, szNamespaceTmp)) - continue; - - if (!strcmp(szNameTmp, szName)) - { - *ptk = tr; - hr = S_OK; - goto ErrExit; - } - } - - // cannot find the typedef - hr = CLDB_E_RECORD_NOTFOUND; -ErrExit: - return hr; -} - -//------------------------------------------------------------------------------ - -HRESULT WinMDAdapter::ModifyExportedTypeName( - mdExportedType tkExportedType, // [IN] exportedType token - LPCSTR *pszNamespace, // [IN,OUT,OPTIONAL] namespace to modify - LPCSTR *pszName // [IN,OUT,OPTIONAL] name to modify -) -{ - _ASSERTE(TypeFromToken(tkExportedType) == mdtExportedType); - - if (m_scenario == kWinMDExp) - { - if (pszName && 0 == strncmp(*pszName, s_szCLRPrefix, s_ncCLRPrefix)) - { - (*pszName) += s_ncCLRPrefix; - } - } - return S_OK; -} - -//------------------------------------------------------------------------------ - -// We must optionally add an assembly ref for System.Numerics.Vectors.dll since this assembly is not available -// on downlevel platforms. -// -// This function assumes that System.Numerics.Vectors.dll is the last assembly that -// we add so if we find a reference then we return ContractAssembly_Count otherwise we return -// ContractAssembly_Count - 1. -int WinMDAdapter::GetExtraAssemblyRefCount() -{ - HRESULT hr; - - if (m_extraAssemblyRefCount == -1) - { - mdAssemblyRef tkSystemNumericsVectors = TokenFromRid(m_rawAssemblyRefCount + ContractAssembly_SystemNumericsVectors + 1, mdtAssemblyRef); - ULONG cTypeRefRecs = m_pRawMetaModelCommonRO->CommonGetRowCount(mdtTypeRef); - BOOL systemNumericsVectorsTypeFound = FALSE; - - for (ULONG i = 1; i <= cTypeRefRecs; i++) - { - mdToken tkResolutionScope; - mdTypeRef tkTypeRef = TokenFromRid(i, mdtTypeRef); - - // Get the resolution scope(AssemblyRef) token for the type. GetTypeRefProps does the type redirection. - IfFailGo(GetTypeRefProps(tkTypeRef, nullptr, nullptr, &tkResolutionScope)); - - if (tkResolutionScope == tkSystemNumericsVectors) - { - systemNumericsVectorsTypeFound = TRUE; - break; - } - } - - if (systemNumericsVectorsTypeFound) - { - m_extraAssemblyRefCount = ContractAssembly_Count; - } - else - { - m_extraAssemblyRefCount = ContractAssembly_Count - 1; - } - } - -ErrExit: - if (m_extraAssemblyRefCount == -1) - { - // Setting m_extraAssemblyRefCount to ContractAssembly_Count so that this function returns a stable value and - // that if there is a System.Numerics type ref that it does not have a dangling assembly ref - m_extraAssemblyRefCount = ContractAssembly_Count; - } - - return m_extraAssemblyRefCount; -} - -//------------------------------------------------------------------------------ - -/*static*/ -void WinMDAdapter::GetExtraAssemblyRefProps(FrameworkAssemblyIndex index, - LPCSTR* ppName, - AssemblyMetaDataInternal* pContext, - PCBYTE * ppPublicKeytoken, - DWORD* pTokenLength, - DWORD* pdwFlags) -{ - _ASSERTE(index >= 0 && index < FrameworkAssembly_Count); - _ASSERTE(index != FrameworkAssembly_Mscorlib); - - if (ppName) - { - *ppName = GetExtraAssemblyRefNameFromIndex((FrameworkAssemblyIndex)index); - } - - if (pContext) - { - ::memset(pContext, 0, sizeof(AssemblyMetaDataInternal)); - - pContext->usMajorVersion = 4; - pContext->usMinorVersion = 0; - pContext->usBuildNumber = 0; - pContext->usRevisionNumber = 0; - - pContext->szLocale = ""; - } - - if (ppPublicKeytoken) - { - if (index == FrameworkAssembly_Mscorlib) - { - *ppPublicKeytoken = g_rbTheSilverlightPlatformKeyToken; - *pTokenLength = sizeof(g_rbTheSilverlightPlatformKeyToken); - } - else - { - if (index == FrameworkAssembly_SystemNumericsVectors || index == FrameworkAssembly_SystemRuntime || index == FrameworkAssembly_SystemObjectModel) - { - *ppPublicKeytoken = s_pbContractPublicKeyToken; - *pTokenLength = sizeof(s_pbContractPublicKeyToken); - } - else - { - *ppPublicKeytoken = s_pbFrameworkPublicKeyToken; - *pTokenLength = sizeof(s_pbFrameworkPublicKeyToken); - } - } - } - - if (pdwFlags) - { - // ppPublicKeytoken contains the public key token, not the whole key. - *pdwFlags = 0; - } -} - -//-------------------------------------------------------------------------------- - -HRESULT WinMDAdapter::FindExportedType( - LPCUTF8 szNamespace, // [IN] expected namespace - LPCUTF8 szName, // [IN] expected name - mdToken tkEnclosingType, // [IN] expected tkEnclosingType - mdExportedType *ptkExportedType // [OUT] ExportedType token returned. -) -{ - HRESULT hr; - - _ASSERTE(szName && ptkExportedType); - - // Set NULL namespace to empty string. - if (!szNamespace) - szNamespace = ""; - - // Set output to Nil. - *ptkExportedType = mdTokenNil; - - ULONG ulCount = m_pRawMetaModelCommonRO->CommonGetRowCount(mdtExportedType); - while (ulCount) - { - mdExportedType tkCandidateExportedType = TokenFromRid(ulCount--, mdtExportedType); - - LPCSTR szCandidateNamespace; - LPCSTR szCandidateName; - mdToken tkCandidateImpl; - - IfFailRet(m_pRawMetaModelCommonRO->CommonGetExportedTypeProps(tkCandidateExportedType, &szCandidateNamespace, &szCandidateName, &tkCandidateImpl)); - IfFailRet(this->ModifyExportedTypeName(tkCandidateExportedType, &szCandidateNamespace, &szCandidateName)); - // Handle the case of nested vs. non-nested classes. - if (TypeFromToken(tkCandidateImpl) == mdtExportedType && !IsNilToken(tkCandidateImpl)) - { - // Current ExportedType being looked at is a nested type, so - // comparing the implementation token. - if (tkCandidateImpl != tkEnclosingType) - continue; - } - else if (TypeFromToken(tkEnclosingType) == mdtExportedType && - !IsNilToken(tkEnclosingType)) - { - // ExportedType passed in is nested but the current ExportedType is not. - continue; - } - - if (0 != strcmp(szName, szCandidateName)) - continue; - - if (0 != strcmp(szNamespace, szCandidateNamespace)) - continue; - - *ptkExportedType = tkCandidateExportedType; - return S_OK; - } - return CLDB_E_RECORD_NOTFOUND; -} - - -//------------------------------------------------------------------------------ - -// Modifies methodDef flags and RVA -HRESULT WinMDAdapter::ModifyMethodProps(mdMethodDef tkMethodDef, /*[in, out]*/ DWORD *pdwAttr, /* [in,out] */ DWORD *pdwImplFlags, /* [in,out] */ ULONG *pulRVA, /* [in, out] */ LPCSTR *pszName) -{ - HRESULT hr; - _ASSERTE(TypeFromToken(tkMethodDef) == mdtMethodDef); - - ULONG mdTreatment; - DWORD dwAttr; - DWORD dwImplFlags; - ULONG ulRVA; - IfFailGo(GetMethodDefTreatment(tkMethodDef, &mdTreatment)); - - dwAttr = pdwAttr ? *pdwAttr: 0; - dwImplFlags = pdwImplFlags ? *pdwImplFlags : 0; - ulRVA = pulRVA ? *pulRVA : 0; - - switch (mdTreatment & kMdTreatmentMask) - { - case kMdInterface: - // Method is declared on an interface - dwImplFlags |= miRuntime|miInternalCall; - break; - - case kMdDelegate: - // Method is declared on a delegate - dwAttr &= ~mdMemberAccessMask; - dwAttr |= mdPublic; - ulRVA = 0; - dwImplFlags |= miRuntime; - break; - - case kMdAttribute: - // Method is declared on an attribute - ulRVA = 0; - dwImplFlags |= miRuntime|miInternalCall; - break; - - case kMdImplementation: - // CLR implementation class. Needs no adjustment. - break; - - case kMdHiddenImpl: - dwAttr &= ~mdMemberAccessMask; - dwAttr |= mdPrivate; - // fall-through - - case kMdOther: - - // All other cases - ulRVA = 0; - dwImplFlags |= miRuntime|miInternalCall; - - if (mdTreatment & kMdMarkAbstractFlag) - { - dwAttr |= mdAbstract; - } - - if (mdTreatment & kMdMarkPublicFlag) - { - dwAttr &= ~mdMemberAccessMask; - dwAttr |= mdPublic; - } - - break; - - case kMdRenameToDisposeMethod: - ulRVA = 0; - dwImplFlags |= miRuntime|miInternalCall; - if(pszName) - { - *pszName = "Dispose"; - } - break; - - default: - UNREACHABLE(); - - } - - dwAttr |= mdHideBySig; - - if (pdwAttr) - (*pdwAttr) = dwAttr; - if (pdwImplFlags) - (*pdwImplFlags) = dwImplFlags; - if (pulRVA) - *pulRVA = ulRVA; - hr = S_OK; - - ErrExit: - return hr; -} - -HRESULT WinMDAdapter::ModifyFieldProps (mdToken tkField, mdToken tkParent, LPCSTR szFieldName, DWORD *pdwFlags) -{ - _ASSERTE(szFieldName != NULL); - - HRESULT hr; - if (pdwFlags && IsFdPrivate(*pdwFlags) && (0 == strcmp(szFieldName, "value__"))) - { - ULONG treatment; - BOOL isEnum = FALSE; - if(TypeFromToken(tkParent) == mdtTypeDef) - { - IfFailGo(GetTypeDefTreatment(tkParent, &treatment)); - - if ((treatment & kTdEnum) == kTdEnum) - { - isEnum = TRUE; - } - } - - if (isEnum) - { - // We have found the value__ field of the enum. - // We need to change its flags from private to public - *pdwFlags = (*pdwFlags & ~fdPrivate) | fdPublic; - } - } - - hr = S_OK; - -ErrExit: - return hr; -} - - -HRESULT WinMDAdapter::ModifyFieldDefProps (mdFieldDef tkFielddDef, DWORD *pdwFlags) -{ - HRESULT hr; - - if (pdwFlags) - { - mdTypeDef tkParent; - LPCSTR szName; - IfFailGo(m_pRawMetaModelCommonRO->CommonGetFieldDefProps(tkFielddDef, &tkParent, &szName, pdwFlags)); - IfFailGo(ModifyFieldProps(tkFielddDef, tkParent, szName, pdwFlags)); - } - - hr = S_OK; -ErrExit: - return hr; -} - -//------------------------------------------------------------------------------ - -HRESULT WinMDAdapter::ModifyMemberProps(mdToken tkMember, /*[in, out]*/ DWORD *pdwAttr, /* [in,out] */ DWORD *pdwImplFlags, /* [in,out] */ ULONG *pulRVA, LPCSTR *pszNewName) -{ - HRESULT hr; - switch(TypeFromToken(tkMember)) - { - case mdtMethodDef: IfFailGo(ModifyMethodProps(tkMember, pdwAttr, pdwImplFlags, pulRVA, pszNewName)); - break; - - case mdtMemberRef: - { - // - // We need to rename the MemberRef for IClosable.Close as well - // so that the MethodImpl for Dispose method can correctly be shown as IDisposable.Dispose - // instead of IDisposable.Close - // - UINT nIndex = WinMDAdapter::RedirectedTypeIndex_Invalid; - if (pszNewName && - CheckIfMethodImplImplementsARedirectedInterface(tkMember, &nIndex) == S_OK && - nIndex == WinMDAdapter::RedirectedTypeIndex_Windows_Foundation_IClosable) - { - *pszNewName = "Dispose"; - } - } - break; - - case mdtFieldDef: - IfFailGo(ModifyFieldDefProps(tkMember, pdwAttr)); - break; - } - - hr = S_OK; -ErrExit: - return hr; -} - -//------------------------------------------------------------------------------ - -// Get MethodTreatment value for a methodDef -HRESULT WinMDAdapter::GetMethodDefTreatment(mdMethodDef tkMethodDef, ULONG *ppMethodDefTreatment) -{ - HRESULT hr; - - _ASSERTE(TypeFromToken(tkMethodDef) == mdtMethodDef); - ULONG index = RidFromToken(tkMethodDef) - 1; - - // Thread-safety: No lock is needed to update this table as we're monotonically advancing a kMdNotYetInitialized to - // some other fixed byte. The work to decide this value is idempotent and side-effect free so - // there's no harm if two threads do it concurrently. - ULONG mdTreatment; - IfFailGo(m_methodDefTreatmentMemoTable.GetEntry(index, &mdTreatment)); - if (hr == S_FALSE) - { - mdTypeDef declaringTypeDef; - IfFailGo(m_pRawMetaModelCommonRO->FindParentOfMethodHelper(tkMethodDef, &declaringTypeDef)); - ULONG firstMethodRid; - IfFailGo(m_pRawMetaModelCommonRO->CommonGetTypeDefProps(declaringTypeDef, NULL, NULL, NULL, NULL, &firstMethodRid)); - IfFailGo(ComputeMethodDefTreatment(tkMethodDef, declaringTypeDef, &mdTreatment)); - _ASSERTE(mdTreatment != kMdNotYetInitialized); - IfFailGo(m_methodDefTreatmentMemoTable.InitEntry(index, &mdTreatment)); - - // Since the mdTreatment is only a function of the declaring type in most cases, cache it for all the declared method since - // we took the time to look up the declaring type. Do enough validity checks to avoid corrupting the heap - // or table but otherwise, swallow validity errors as this is just an optimization. - // Methods on RuntimeClasses need to get treatment data per method. - if (((mdTreatment & kMdTreatmentMask) != kMdOther) && - ((mdTreatment & kMdTreatmentMask) != kMdHiddenImpl) && - ((mdTreatment & kMdTreatmentMask) != kMdRenameToDisposeMethod)) - { - const ULONG methodDefCount = m_pRawMetaModelCommonRO->CommonGetRowCount(mdtMethodDef); - const ULONG startIndex = RidFromToken(firstMethodRid) - 1; - if (startIndex < methodDefCount) - { - const ULONG typeDefCount = m_pRawMetaModelCommonRO->CommonGetRowCount(mdtTypeDef); - if (RidFromToken(declaringTypeDef) < typeDefCount) - { - ULONG stopMethodRid; - if (S_OK == m_pRawMetaModelCommonRO->CommonGetTypeDefProps(declaringTypeDef + 1, NULL, NULL, NULL, NULL, &stopMethodRid)) - { - ULONG stopIndex = RidFromToken(stopMethodRid) - 1; - if (startIndex < methodDefCount && stopIndex <= methodDefCount) - { - ULONG walkIndex = startIndex; - while (walkIndex < stopIndex) - { - IfFailGo(m_methodDefTreatmentMemoTable.InitEntry(walkIndex++, &mdTreatment)); - } - } - } - } - else - { - // This was final typeDef - blast the mdTreatment into the rest of the table. - for (ULONG i = startIndex; i < methodDefCount; i++) - { - IfFailGo(m_methodDefTreatmentMemoTable.InitEntry(i, &mdTreatment)); - } - } - } - } - } - - *ppMethodDefTreatment = mdTreatment; - hr = S_OK; - - ErrExit: - return hr; -} - -//------------------------------------------------------------------------------ - -// Compute MethodTreatment value for a methodDef (unlike GetMethodDefTreatment, this -// does not cache.) -// -HRESULT WinMDAdapter::ComputeMethodDefTreatment(mdMethodDef tkMethodDef, mdTypeDef tkDeclaringTypeDef, ULONG *ppMethodDefTreatment) -{ - HRESULT hr; - - BYTE mdTreatment = kMdImplementation; - - LPCSTR szDeclaringTypeName; - DWORD parentTdAttr; - mdToken extends; - IfFailGo(m_pRawMetaModelCommonRO->CommonGetTypeDefProps(tkDeclaringTypeDef, NULL, &szDeclaringTypeName, &parentTdAttr, &extends, NULL)); - - // We only want to treat this method special if it has metadata exposed to WinRT - if (IsTdWindowsRuntime(parentTdAttr)) - { - LPCSTR szUnmangledName; - IfFailGo(CheckIfClrImplementationType(szDeclaringTypeName, parentTdAttr, &szUnmangledName)); - if (hr == S_OK) - { - mdTreatment = kMdImplementation; - } - else if (IsTdNested(parentTdAttr)) - { - // nested types are implementation - mdTreatment = kMdImplementation; - } - else if (parentTdAttr & tdInterface) - { - // Method is declared on an interface. - mdTreatment = kMdInterface; - } - else if (m_scenario == kWinMDExp && (parentTdAttr & tdPublic) == 0) - { - // internal classes generated by WinMDExp are implementation - mdTreatment = kMdImplementation; - } - else - { - mdTreatment = kMdOther; - - if (TypeFromToken(extends) == mdtTypeRef) - { - ULONG trTreatment; - IfFailGo(GetTypeRefTreatment(extends, &trTreatment)); - if (trTreatment == kTrSystemDelegate) - { - // Method is declared on a delegate - mdTreatment = kMdDelegate; - } - else if (trTreatment == kTrSystemAttribute) - { - // Method is declared on a attribute - mdTreatment = kMdAttribute; - } - } - } - } - if (mdTreatment == kMdOther) - { - // we want to hide the method if it implements only redirected interfaces - // Also we want to check if the methodImpl is IClosable.Close then we will change the name. - bool fSeenRedirectedInterfaces = false; - bool fSeenNonRedirectedInterfaces = false; - - bool isIClosableCloseMethod = false; - - mdToken tkMethodImplFirst; - ULONG count; - IfFailGo(m_pRawMetaModelCommonRO->CommonGetMethodImpls(tkDeclaringTypeDef, &tkMethodImplFirst, &count)); - for (ULONG i = 0; i < count; i++) - { - mdToken tkMethodImpl = tkMethodImplFirst + i; - mdToken tkBody, tkDecl; - IfFailGo(m_pRawMetaModelCommonRO->CommonGetMethodImplProps(tkMethodImpl, &tkBody, &tkDecl)); - - if (tkBody == tkMethodDef) - { - // See if this MethodImpl implements a redirected interface - UINT nIndex; - IfFailGo(CheckIfMethodImplImplementsARedirectedInterface(tkDecl, &nIndex)); - if (hr == S_FALSE) - { - // Now we know this implements a non-redirected interface - // But we need to keep looking, just in case we got a MethodImpl that implements - // the IClosable.Close method and needs to be renamed - fSeenNonRedirectedInterfaces = true; - } - else if (SUCCEEDED(hr)) - { - fSeenRedirectedInterfaces = true; - if (nIndex == WinMDAdapter::RedirectedTypeIndex_Windows_Foundation_IClosable) - { - // This method implements IClosable.Close - // Let's rename it to Dispose later - // Once we know this implements IClosable.Close, we are done looking as we know - // we won't hide it - isIClosableCloseMethod = true; - break; - } - } - } - } - - if (isIClosableCloseMethod) - { - // Rename IClosable.Close to Dispose - mdTreatment = kMdRenameToDisposeMethod; - } - else if (fSeenRedirectedInterfaces && !fSeenNonRedirectedInterfaces) - { - // Only hide if all the interfaces implemented are redirected - mdTreatment = kMdHiddenImpl; - } - } - - // If treatment is other, then this is a non-managed WinRT runtime class definition. Find out about various bits that we apply via attrubtes and name parsing. - if (mdTreatment == kMdOther) - { - // Scan through Custom Attributes on type, looking for interesting bits. - HRESULT hrCA; - hrCA = m_pRawMetaModelCommonRO->CommonGetCustomAttributeByNameEx(tkMethodDef, "Windows.UI.Xaml.TreatAsPublicMethodAttribute", NULL, NULL, NULL); - if (hrCA == S_OK) - { - mdTreatment |= kMdMarkPublicFlag; - } - - - hrCA = m_pRawMetaModelCommonRO->CommonGetCustomAttributeByNameEx(tkMethodDef, "Windows.UI.Xaml.TreatAsAbstractMethodAttribute", NULL, NULL, NULL); - if (hrCA == S_OK) - { - mdTreatment |= kMdMarkAbstractFlag; - } - - LPCSTR szName; - DWORD dwFlags; - IfFailRet(m_pRawMetaModelCommonRO->CommonGetMethodDefProps(tkMethodDef, &szName, &dwFlags, NULL, NULL)); - } - *ppMethodDefTreatment = mdTreatment; - hr = S_OK; - -ErrExit: - return hr; -} - -//------------------------------------------------------------------------------ - -// -// Finds a CA by its (transformed) name -// -HRESULT WinMDAdapter::GetCustomAttributeByName( // S_OK or error. - mdToken tkObj, // [IN] Object with Custom Attribute. - LPCUTF8 szName, // [IN] Name of desired Custom Attribute. - mdCustomAttribute *ptkCA, // [OUT] Put custom attribute token here - const void **ppData, // [OUT] Put pointer to data here. - ULONG *pcbData) // [OUT] Put size of data here. -{ - HRESULT hr; - _ASSERTE(szName); - - if (ConvertWellKnownTypeNameFromClrToWinRT(&szName)) - { - mdCustomAttribute tkCA; - IfFailGo(m_pRawMetaModelCommonRO->CommonGetCustomAttributeByNameEx(tkObj, szName, &tkCA, NULL, NULL)); - if (hr == S_FALSE) - goto ErrExit; - if (ptkCA) - *ptkCA = tkCA; - IfFailGo(GetCustomAttributeBlob(tkCA, ppData, pcbData)); - } - else - { - IfFailGo(m_pRawMetaModelCommonRO->CommonGetCustomAttributeByNameEx(tkObj, szName, ptkCA, ppData, pcbData)); - } - ErrExit: - return hr; -} - -//------------------------------------------------------------------------------ - -// -// Modify CA blobs -// -HRESULT WinMDAdapter::GetCustomAttributeBlob( - mdCustomAttribute tkCA, - const void **ppData, // [OUT] Put pointer to data here. - ULONG *pcbData) // [OUT] Put size of data here. -{ - HRESULT hr; - - _ASSERTE(TypeFromToken(tkCA) == mdtCustomAttribute); - ULONG index = RidFromToken(tkCA) - 1; - - // If someone already queried this CA, use the previous result. - CABlob * pCABlob; - IfFailGo(m_redirectedCABlobsMemoTable.GetEntry(index, &pCABlob)); - if (hr == S_FALSE) - { - // No, we're the first. Initialize the entry (keeping in mind we may be racing with other threads.) - pCABlob = CABlob::NOREDIRECT; - mdToken tkOwner; - mdToken tkCtor; - IfFailGo(m_pRawMetaModelCommonRO->CommonGetCustomAttributeProps(tkCA, &tkOwner, &tkCtor, NULL, NULL)); - if (TypeFromToken(tkOwner) == mdtTypeDef) // AttributeUsageAttribute only goes on a typeDef, so if the owner isn't a typeDef, no point in going further. - { - if (TypeFromToken(tkCtor) == mdtMemberRef) // REX has promised to use a memberRef (not Def) here. - { - mdToken tkCtorType; - IfFailGo(m_pRawMetaModelCommonRO->CommonGetMemberRefProps(tkCtor, &tkCtorType)); - if (TypeFromToken(tkCtorType) == mdtTypeRef) // REX has promised to use a typeRef (not a Def, or heavens forbid, a Spec) here - { - RedirectedTypeIndex redirectedTypeIndex; - IfFailGo(GetTypeRefRedirectedInfo(tkCtorType, &redirectedTypeIndex)); - _ASSERTE((hr == S_OK) || (hr == S_FALSE)); - - if ((hr == S_OK) && (redirectedTypeIndex == RedirectedTypeIndex_Windows_Foundation_Metadata_AttributeUsageAttribute)) - { - // We found a Windows.Foundation.Metadata.AttributeUsageAttribute. The TypeRef redirection already makes this - // look like a System.AttributeUsageAttribute. Must munge the blob so that it matches the CLR expections. - BOOL allowMultiple; - DWORD clrTargetValue; - IfFailGo(TranslateWinMDAttributeUsageAttribute(tkOwner, &clrTargetValue, &allowMultiple)); - if (hr == S_OK) - { - CABlob *pNewCABlob = NULL; - IfFailGo(CreateClrAttributeUsageAttributeCABlob(clrTargetValue, allowMultiple, &pNewCABlob)); - pCABlob = pNewCABlob; - } - } - } - } - } - - IfFailGo(m_redirectedCABlobsMemoTable.InitEntry(index, &pCABlob)); - } - - _ASSERTE(pCABlob != NULL); - const void *pData; - ULONG cbData; - if (pCABlob == CABlob::NOREDIRECT) - { - // The normal case: don't rewrite the blob. - IfFailGo(m_pRawMetaModelCommonRO->CommonGetCustomAttributeProps(tkCA, NULL, NULL, &pData, &cbData)); - } - else - { - // The special cases: Blob was rewritten, return the rewritten blob. - pData = pCABlob->data; - cbData = pCABlob->cbBlob; - } - if (ppData) - *ppData = pData; - if (pcbData) - *pcbData = cbData; - - hr = S_OK; - ErrExit: - return hr; -} - -//------------------------------------------------------------------------------ - -// Note: This method will look in a cache for the reinterpreted signature, but does not add any values to -// the cache or do any work on failure. If we can't find it then it returns S_FALSE. -HRESULT WinMDAdapter::GetCachedSigForToken( - mdToken token, // [IN] given token - MemoTable &memoTable, // [IN] the MemoTable to use - ULONG *pcbSigBlob, // [OUT] count of bytes in the signature blob - PCCOR_SIGNATURE *ppSig, // [OUT] new signature - BOOL *pfPassThrough // [OUT] did the cache say we don't need to reinterpret this sig? -) -{ - _ASSERTE(pfPassThrough != NULL); - - HRESULT hr; - - ULONG index = RidFromToken(token) - 1; - - // If someone already queried this method signature, use the previous result. - SigData *pSigData = NULL; - IfFailGo(memoTable.GetEntry(index, &pSigData)); - if (hr == S_FALSE) - { - *pfPassThrough = FALSE; - return S_FALSE; - } - - _ASSERTE(pSigData != NULL); - - if (pSigData == SigData::NOREDIRECT) - { - // The normal case: don't rewrite the signature. - *pfPassThrough = TRUE; - return S_FALSE; - } - else - { - *pfPassThrough = FALSE; - // The signature was rewritten, return the rewritten sig. - if (ppSig) - *ppSig = (PCCOR_SIGNATURE) pSigData->data; - if (pcbSigBlob) - *pcbSigBlob = pSigData->cbSig; - } - - hr = S_OK; - - ErrExit: - return hr; -} - -//------------------------------------------------------------------------------ -// static -HRESULT WinMDAdapter::InsertCachedSigForToken( - mdToken token, // [IN] given token - MemoTable &memoTable, // [IN] the MemoTable to use - SigData **ppSigData // [IN, OUT] new signature or SigData::NOREDIRECT if the signature didn't need to be reparsed, -) // will be updated with another (but identical) SigData* if this thread lost the race -{ - _ASSERTE(ppSigData != NULL && *ppSigData != NULL); - - HRESULT hr; - ULONG index = RidFromToken(token) - 1; - - IfFailGo(memoTable.InitEntry(index, ppSigData)); - hr = S_OK; - - ErrExit: - return hr; -} - -//------------------------------------------------------------------------------ -static HRESULT FinalizeSignatureRewrite( - SigBuilder & newSig, - BOOL fChangedSig, - WinMDAdapter::SigData **ppSigData - DEBUG_ARG(ULONG cbOrigSigBlob) - ) -{ - // Make sure we didn't lose anything, since we wrote out the full signature. - ULONG cbNewSigLen; - BYTE * pNewSigBytes = (BYTE *) newSig.GetSignature(&cbNewSigLen); - _ASSERTE(cbNewSigLen == cbOrigSigBlob); // Didn't lose any data nor add anything - - // Set the output SigData appropriately. - if (fChangedSig) - { - *ppSigData = WinMDAdapter::SigData::Create(cbNewSigLen, pNewSigBytes); - - if (*ppSigData == NULL) - { - return E_OUTOFMEMORY; - } - } - else - { - *ppSigData = WinMDAdapter::SigData::NOREDIRECT; - } - return S_OK; -} - -//------------------------------------------------------------------------------ - -// Purpose: Translate method signatures containing classes that we're projecting as value types, and vice versa. -// Example: ELEMENT_TYPE_CLASS [IReference] to ELEMENT_TYPE_VALUETYPE [Nullable] -// Example: ELEMENT_TYPE_VALUETYPE [Windows.Foundation.HResult] to ELEMENT_TYPE_CLASS [Exception] -HRESULT WinMDAdapter::ReinterpretMethodSignature( - ULONG cbOrigSigBlob, // [IN] count of bytes in the original signature blob - PCCOR_SIGNATURE pOrigSig, // [IN] original signature - SigData **ppSigData // [OUT] new signature or SigData::NOREDIRECT -) -{ - _ASSERTE(pOrigSig != NULL); - _ASSERTE(ppSigData != NULL); - - HRESULT hr; - - // @REVISIT_TODO: Need to allocate memory here. We cannot take a lock though (such as any lock needed by 'new'), or we can get - // into deadlocks from profilers that need to inspect metadata to walk the stack. Needs some help from some loader/ngen experts. - - BOOL fChangedSig = FALSE; - - // The following implements MethodDef signature parsing, per ECMA CLI spec, section 23.2.1. - SigParser sigParser(pOrigSig, cbOrigSigBlob); - SigBuilder newSig(cbOrigSigBlob); // We will not change the signature size, just modify it a bit (E_T_CLASS <-> E_T_VALUETYPE) - - // Read calling convention info - Note: Calling convention is always one byte - ULONG callingConvention; - IfFailGo(sigParser.GetCallingConvInfo(&callingConvention)); - _ASSERTE((callingConvention & 0xff) == callingConvention); - newSig.AppendByte((BYTE)callingConvention); - - // If it is generic, read the generic parameter count - if ((callingConvention & CORINFO_CALLCONV_GENERIC) != 0) - { - ULONG genericArgsCount; - IfFailGo(sigParser.GetData(&genericArgsCount)); - newSig.AppendData(genericArgsCount); - } - - // Read number of locals / method parameters - ULONG cParameters; - IfFailGo(sigParser.GetData(&cParameters)); - newSig.AppendData(cParameters); - - if (callingConvention != CORINFO_CALLCONV_LOCAL_SIG) - { - // Read return type - IfFailGo(RewriteTypeInSignature(&sigParser, &newSig, &fChangedSig)); - } - - // Visit each local / parameter - for (ULONG i = 0; i < cParameters; i++) - { - IfFailGo(RewriteTypeInSignature(&sigParser, &newSig, &fChangedSig)); - } - - IfFailGo(FinalizeSignatureRewrite(newSig, fChangedSig, ppSigData DEBUG_ARG(cbOrigSigBlob))); - return S_OK; - -ErrExit: - Debug_ReportError("Couldn't parse a signature in WinMDAdapter::ReinterpretMethodSignature!"); - return hr; -} // WinMDAdapter::ReinterpretMethodSignature - - -//------------------------------------------------------------------------------ - -// Purpose: Translate FieldDef signatures containing classes that we're projecting as value types, and vice versa. -// Example: ELEMENT_TYPE_VALUETYPE [Windows.Foundation.HResult] to ELEMENT_TYPE_CLASS [Exception] -HRESULT WinMDAdapter::ReinterpretFieldSignature( - ULONG cbOrigSigBlob, // [IN] count of bytes in the original signature blob - PCCOR_SIGNATURE pOrigSig, // [IN] original signature - SigData **ppSigData // [OUT] new signature or SigData::NOREDIRECT -) -{ - _ASSERTE(pOrigSig != NULL); - _ASSERTE(ppSigData != NULL); - - HRESULT hr = S_OK; - BOOL fChangedSig = FALSE; - - // The following implements FieldDef signature parsing, per ECMA CLI spec, section 23.2.4. - // Format is FIELD [custom modifiers]* Type - SigParser sigParser(pOrigSig, cbOrigSigBlob); - SigBuilder newSig(cbOrigSigBlob); // We will not change the signature size, just modify it a bit (E_T_CLASS <-> E_T_VALUETYPE) - - // Read calling convention info - this should be IMAGE_CEE_CS_CALLCONV_FIELD. - ULONG callingConvention; - IfFailGo(sigParser.GetCallingConvInfo(&callingConvention)); - _ASSERTE((callingConvention & 0xff) == callingConvention); - _ASSERTE(callingConvention == IMAGE_CEE_CS_CALLCONV_FIELD); - newSig.AppendByte((BYTE)callingConvention); - - // Rewrite field type - IfFailGo(RewriteTypeInSignature(&sigParser, &newSig, &fChangedSig)); - - IfFailGo(FinalizeSignatureRewrite(newSig, fChangedSig, ppSigData DEBUG_ARG(cbOrigSigBlob))); - return S_OK; - -ErrExit: - Debug_ReportError("Couldn't parse a signature in WinMDAdapter::ReinterpretFieldSignature!"); - return hr; -} // WinMDAdapter::ReinterpretFieldSignature - - -//------------------------------------------------------------------------------ - -// Purpose: Translate TypeSpec signatures containing classes that we're projecting as value types, and vice versa. -HRESULT WinMDAdapter::ReinterpretTypeSpecSignature( - ULONG cbOrigSigBlob, // [IN] count of bytes in the original signature blob - PCCOR_SIGNATURE pOrigSig, // [IN] original signature - SigData **ppSigData // [OUT] new signature or SigData::NOREDIRECT -) -{ - _ASSERTE(pOrigSig != NULL); - _ASSERTE(ppSigData != NULL); - - HRESULT hr = S_OK; - BOOL fChangedSig = FALSE; - - // The following implements TypeSpec signature parsing, per ECMA CLI spec, section 23.2.14. - // Format is [custom modifiers]* Type - SigParser sigParser(pOrigSig, cbOrigSigBlob); - SigBuilder newSig(cbOrigSigBlob); // We will not change the signature size, just modify it a bit (E_T_CLASS <-> E_T_VALUETYPE) - - // Rewrite the type - IfFailGo(RewriteTypeInSignature(&sigParser, &newSig, &fChangedSig)); - - IfFailGo(FinalizeSignatureRewrite(newSig, fChangedSig, ppSigData DEBUG_ARG(cbOrigSigBlob))); - return S_OK; - -ErrExit: - Debug_ReportError("Couldn't parse a signature in WinMDAdapter::ReinterpretTypeSpecSignature!"); - return hr; -} // WinMDAdapter::ReinterpretTypeSpecSignature - - -//------------------------------------------------------------------------------ - -// Purpose: Translate MethodSpec signatures containing classes that we're projecting as value types, and vice versa. -HRESULT WinMDAdapter::ReinterpretMethodSpecSignature( - ULONG cbOrigSigBlob, // [IN] count of bytes in the original signature blob - PCCOR_SIGNATURE pOrigSig, // [IN] original signature - SigData **ppSigData // [OUT] new signature or SigData::NOREDIRECT -) -{ - _ASSERTE(pOrigSig != NULL); - _ASSERTE(ppSigData != NULL); - - HRESULT hr = S_OK; - BOOL fChangedSig = FALSE; - - // The following implements MethodSpec signature parsing, per ECMA CLI spec, section 23.2.15. - // Format is GENERICINST GenArgCount Type+ - SigParser sigParser(pOrigSig, cbOrigSigBlob); - SigBuilder newSig(cbOrigSigBlob); // We will not change the signature size, just modify it a bit (E_T_CLASS <-> E_T_VALUETYPE) - - // Read calling convention info - this should be IMAGE_CEE_CS_CALLCONV_GENERICINST. - ULONG callingConvention; - IfFailGo(sigParser.GetCallingConvInfo(&callingConvention)); - _ASSERTE((callingConvention & 0xff) == callingConvention); - _ASSERTE(callingConvention == IMAGE_CEE_CS_CALLCONV_GENERICINST); - newSig.AppendByte((BYTE)callingConvention); - - // Read number of generic arguments - ULONG cArguments; - IfFailGo(sigParser.GetData(&cArguments)); - newSig.AppendData(cArguments); - - // Rewrite each argument - for (ULONG i = 0; i < cArguments; i++) - { - IfFailGo(RewriteTypeInSignature(&sigParser, &newSig, &fChangedSig)); - } - - IfFailGo(FinalizeSignatureRewrite(newSig, fChangedSig, ppSigData DEBUG_ARG(cbOrigSigBlob))); - return S_OK; - -ErrExit: - Debug_ReportError("Couldn't parse a signature in WinMDAdapter::ReinterpretMethodSpecSignature!"); - return hr; -} // WinMDAdapter::ReinterpretMethodSpecSignature - - -//------------------------------------------------------------------------------ -// -// We expose some WinRT types to managed as CLR types, while changing reference type <-> value type: -// E_T_CLASS Windows.Foundation.IReference ---> E_T_VALUETYPE System.Nullable -// E_T_CLASS Windows.Foundation.Collections.IKeyValuePair ---> E_T_VALUETYPE System.Collections.Generic.KeyValuePair -// E_T_VALUETYPE Windows.UI.Xaml.Interop.TypeName ---> E_T_CLASS System.Type -// E_T_VALUETYPE Windows.Foundation.HResult ---> E_T_CLASS System.Exception -HRESULT WinMDAdapter::RewriteTypeInSignature( - SigParser * pSigParser, - SigBuilder * pSigBuilder, - BOOL * pfChangedSig) -{ - HRESULT hr; - - BYTE elementType; - IfFailGo(pSigParser->GetByte(&elementType)); - - switch (elementType) - { - // Simple types with no additional data in the signature - case ELEMENT_TYPE_VOID: - case ELEMENT_TYPE_BOOLEAN: - case ELEMENT_TYPE_CHAR: - case ELEMENT_TYPE_I1: - case ELEMENT_TYPE_U1: - case ELEMENT_TYPE_I2: - case ELEMENT_TYPE_U2: - case ELEMENT_TYPE_I4: - case ELEMENT_TYPE_U4: - case ELEMENT_TYPE_I8: - case ELEMENT_TYPE_U8: - case ELEMENT_TYPE_R4: - case ELEMENT_TYPE_R8: - case ELEMENT_TYPE_STRING: - case ELEMENT_TYPE_I: - case ELEMENT_TYPE_U: - case ELEMENT_TYPE_OBJECT: - case ELEMENT_TYPE_TYPEDBYREF: // TYPEDREF (it takes no args) a typed reference to some other type - { - pSigBuilder->AppendByte(elementType); - break; - } - - // Read a token - case ELEMENT_TYPE_CLASS: - { - mdToken token; - IfFailGo(pSigParser->GetToken(&token)); - - if (TypeFromToken(token) == mdtTypeRef) - { - RedirectedTypeIndex nRedirectedTypeIndex; - IfFailGo(this->GetTypeRefRedirectedInfo(token, &nRedirectedTypeIndex)); - _ASSERTE((hr == S_OK) || (hr == S_FALSE)); - - if (hr == S_OK) - { // TypeRef is well known redirectetd type (with index in array code:g_rgRedirectedTypes) - if (nRedirectedTypeIndex == RedirectedTypeIndex_Windows_Foundation_IReference || - nRedirectedTypeIndex == RedirectedTypeIndex_Windows_Foundation_Collections_IKeyValuePair) - { // The TypeRef name was changed to System.Nullable or System.Collections.Generic.KeyValuePair`2 (value type, not class) - elementType = ELEMENT_TYPE_VALUETYPE; - *pfChangedSig = TRUE; - } - } - // We do not want to return S_FALSE - hr = S_OK; - } - - pSigBuilder->AppendByte(elementType); - pSigBuilder->AppendToken(token); - - break; - } - case ELEMENT_TYPE_VALUETYPE: - { - mdToken token; - IfFailGo(pSigParser->GetToken(&token)); - - if (TypeFromToken(token) == mdtTypeRef) - { - RedirectedTypeIndex nRedirectedTypeIndex; - IfFailGo(this->GetTypeRefRedirectedInfo(token, &nRedirectedTypeIndex)); - _ASSERTE((hr == S_OK) || (hr == S_FALSE)); - - if (hr == S_OK) - { // TypeRef is well known redirectetd type (with index in array code:g_rgRedirectedTypes) - if (nRedirectedTypeIndex == RedirectedTypeIndex_Windows_UI_Xaml_Interop_TypeName || - nRedirectedTypeIndex == RedirectedTypeIndex_Windows_Foundation_HResult) - { - // TypeIdentifier and HResult are all value types in winmd and are mapped to reference - // types in CLR: Type, and Exception. - elementType = ELEMENT_TYPE_CLASS; - *pfChangedSig = TRUE; - } - } - // We do not want to return S_FALSE - hr = S_OK; - } - - pSigBuilder->AppendByte(elementType); - pSigBuilder->AppendToken(token); - - break; - } - - // Read a type - case ELEMENT_TYPE_SZARRAY: // SZARRAY - case ELEMENT_TYPE_PTR: // PTR - case ELEMENT_TYPE_BYREF: // BYREF - case ELEMENT_TYPE_SENTINEL: // sentinel for VARARGS ("..." in the parameter list), it behaves as prefix to next arg - { - pSigBuilder->AppendByte(elementType); - - IfFailGo(RewriteTypeInSignature(pSigParser, pSigBuilder, pfChangedSig)); - break; - } - - // Read a token then a type. That type could be another custom modifier. - case ELEMENT_TYPE_CMOD_REQD: // required C modifier : E_T_CMOD_REQD [followed by a type, or another custom modifier] - case ELEMENT_TYPE_CMOD_OPT: // optional C modifier : E_T_CMOD_OPT - { - pSigBuilder->AppendByte(elementType); - - mdToken token; - IfFailGo(pSigParser->GetToken(&token)); - pSigBuilder->AppendToken(token); - - // Process next type or custom modifier - IfFailGo(RewriteTypeInSignature(pSigParser, pSigBuilder, pfChangedSig)); - break; - } - - // Read a number - case ELEMENT_TYPE_VAR: // a class type variable VAR - case ELEMENT_TYPE_MVAR: // a method type variable MVAR - { - pSigBuilder->AppendByte(elementType); - - ULONG number; - IfFailGo(pSigParser->GetData(&number)); - pSigBuilder->AppendData(number); - break; - } - - case ELEMENT_TYPE_ARRAY: // MDARRAY ... ... - { - pSigBuilder->AppendByte(elementType); - - // Read array type - IfFailGo(RewriteTypeInSignature(pSigParser, pSigBuilder, pfChangedSig)); - - // Read rank - ULONG rank; - IfFailGo(pSigParser->GetData(&rank)); - pSigBuilder->AppendData(rank); - - // If rank is 0, then there's nothing else in the array signature - if (rank != 0) - { - // Read number of dimension sizes - ULONG cDimensionSizes; - IfFailGo(pSigParser->GetData(&cDimensionSizes)); - pSigBuilder->AppendData(cDimensionSizes); - - // Read all dimension sizes - for (ULONG i = 0; i < cDimensionSizes; i++) - { - ULONG dimensionSize; - IfFailGo(pSigParser->GetData(&dimensionSize)); - pSigBuilder->AppendData(dimensionSize); - } - - // Read number of lower bounds - ULONG cLowerBounds; - IfFailGo(pSigParser->GetData(&cLowerBounds)); - pSigBuilder->AppendData(cLowerBounds); - - // Read all lower bounds - for (ULONG i = 0; i < cLowerBounds; i++) - { - ULONG lowerBound; - IfFailGo(pSigParser->GetData(&lowerBound)); - pSigBuilder->AppendData(lowerBound); - } - } - break; - } - - case ELEMENT_TYPE_GENERICINST: // GENERICINST ... - { - pSigBuilder->AppendByte(elementType); - - // Read the generic type - IfFailGo(RewriteTypeInSignature(pSigParser, pSigBuilder, pfChangedSig)); - - // Read arg count - ULONG cGenericTypeArguments; - IfFailGo(pSigParser->GetData(&cGenericTypeArguments)); - pSigBuilder->AppendData(cGenericTypeArguments); - - // Read each type argument - for (ULONG i = 0; i < cGenericTypeArguments; i++) - { - IfFailGo(RewriteTypeInSignature(pSigParser, pSigBuilder, pfChangedSig)); - } - break; - } - - case ELEMENT_TYPE_FNPTR: // FNPTR - /* - // FNPTR is not supported in C#/VB, thefore this is not a main scenario. - // This implementation was late during .NET 4.5, but may be useful in future releases when we decide to support more languages for managed WinMD implementation. - { - pSigBuilder->AppendByte(elementType); - - // Read calling convention - DWORD callingConvention; - IfFailGo(pSigParser->GetData(&callingConvention)); - pSigBuilder->AppendData(callingConvention); - - // Read arg count - ULONG cArgs; - IfFailGo(pSigParser->GetData(&cArgs)); - pSigBuilder->AppendData(cArgs); - - // Read return argument - IfFailGo(RewriteTypeInSignature(pSigParser, pSigBuilder, pfChangedSig)); - - // Read each argument - for (ULONG i = 0; i < cArgs; i++) - { - IfFailGo(RewriteTypeInSignature(pSigParser, pSigBuilder, pfChangedSig)); - } - break; - } - */ - Debug_ReportError("ELEMENT_TYPE_FNPTR signature parsing in WinMD Adapter is NYI."); - IfFailGo(E_FAIL); - - case ELEMENT_TYPE_END: - case ELEMENT_TYPE_INTERNAL: // INTERNAL (Only in ngen images, but not reachable from MetaData - no sig rewriting) - case ELEMENT_TYPE_PINNED: // PINNED , used only in LocalSig (no sig rewriting) - Debug_ReportError("Unexpected CorElementType in a signature. Sig parsing failing."); - IfFailGo(E_FAIL); - - default: - Debug_ReportError("Unknown CorElementType."); - IfFailGo(E_FAIL); - } - _ASSERTE(hr == S_OK); - return hr; - -ErrExit: - Debug_ReportError("Sig parsing failed."); - return hr; -} // WinMDAdapter::RewriteTypeInSignature - -//------------------------------------------------------------------------------ - - - -//--------------------------------------------------------------------------------- -// Windows.Foundation.Metadata.AttributeTarget and System.AttributeTarget enum -// define different bits for everything (@todo: Be nice to change that before we ship.) -// Do the conversion here. -//--------------------------------------------------------------------------------- -static DWORD ConvertToClrAttributeTarget(DWORD winRTTarget) -{ - struct AttributeTargetsPair - { - DWORD WinRTValue; - DWORD ClrValue; - }; - - static const AttributeTargetsPair s_attributeTargetPairs[] = - { -#define DEFINE_PROJECTED_TYPE(a,b,c,d,e,f,g,h,i) -#define DEFINE_PROJECTED_ATTRIBUTETARGETS_VALUE(winrt, clr) { winrt, clr }, -#include "WinRTProjectedTypes.h" -#undef DEFINE_PROJECTED_ATTRIBUTETARGETS_VALUES -#undef DEFINE_PROJECTED_TYPE - }; - - if (winRTTarget == 0xffffffff /* Windows.Foundation.Metadata.AttributeTargets.All */) - return 0x00007fff; /* System.AttributeTargets.All */ - DWORD clrTarget = 0; - for (UINT i = 0; i < sizeof(s_attributeTargetPairs)/sizeof(*s_attributeTargetPairs); i++) - { - if (winRTTarget & s_attributeTargetPairs[i].WinRTValue) - { - clrTarget |= s_attributeTargetPairs[i].ClrValue; - } - } - return clrTarget; -} - - -//------------------------------------------------------------------------------ - - -// Search a typeDef for WF.AttributeUsageAttribute and WF.AllowMultipleAttribute, and compute -// -// *pClrTargetValue - the equivalent System.AttributeTargets enum value -// *pAllowMultiple - where multiple instances of the CA are allowed. -// -// Returns: -// S_OK: a WF.AttributeUsageAttribute CA exists (this is the one that we will rewrite) -// S_FALSE: no WF.AttributeUsageAttribute CA exists -// -HRESULT WinMDAdapter::TranslateWinMDAttributeUsageAttribute(mdTypeDef tkTypeDefOfCA, /*[out]*/ DWORD *pClrTargetValue, /*[out]*/ BOOL *pAllowMultiple) -{ - HRESULT hr; - _ASSERTE(TypeFromToken(tkTypeDefOfCA) == mdtTypeDef); - _ASSERTE(pClrTargetValue != NULL); - _ASSERTE(pAllowMultiple != NULL); - - const BYTE *pbWFUsageBlob; - ULONG cbWFUsageBlob; - IfFailGo(m_pRawMetaModelCommonRO->CommonGetCustomAttributeByName(tkTypeDefOfCA, "Windows.Foundation.Metadata.AttributeUsageAttribute", (const void **)&pbWFUsageBlob, &cbWFUsageBlob)); - if (hr == S_FALSE) - goto ErrExit; - // Expected blob format: - // 01 00 - Fixed prolog for CA's - // xx xx xx xx - The Windows.Foundation.Metadata.AttributeTarget value - // 00 00 - Indicates 0 name/value pairs following. - if (cbWFUsageBlob != 2 + sizeof(DWORD) + 2) - { - IfFailGo(COR_E_BADIMAGEFORMAT); - } - - { - DWORD wfTargetValue = *(DWORD*)(pbWFUsageBlob + 2); - *pClrTargetValue = ConvertToClrAttributeTarget(wfTargetValue); - } - - // add AttributeTargets.Method, AttributeTargets.Constructor , AttributeTargets.Property, and AttributeTargets.Event if this is the VersionAttribute - LPCSTR szNamespace; - LPCSTR szName; - IfFailGo(m_pRawMetaModelCommonRO->CommonGetTypeDefProps(tkTypeDefOfCA, &szNamespace, &szName, NULL, NULL, NULL)); - - if ((strcmp(szName, "VersionAttribute") == 0 || strcmp(szName, "DeprecatedAttribute") == 0) && strcmp(szNamespace, "Windows.Foundation.Metadata") == 0) - { - *pClrTargetValue |= 0x2E0; - } - - const BYTE *pbWFAllowMultipleBlob; - ULONG cbWFAllowMultipleBlob; - IfFailGo(m_pRawMetaModelCommonRO->CommonGetCustomAttributeByName(tkTypeDefOfCA, "Windows.Foundation.Metadata.AllowMultipleAttribute", (const void **)&pbWFAllowMultipleBlob, &cbWFAllowMultipleBlob)); - *pAllowMultiple = (hr == S_OK); - hr = S_OK; - - ErrExit: - return hr; -} - -//------------------------------------------------------------------------------ - -/*static*/ HRESULT WinMDAdapter::CreateClrAttributeUsageAttributeCABlob(DWORD clrTargetValue, BOOL allowMultiple, CABlob **ppCABlob) -{ - // Emit the blob format corresponding to: - // [System.AttributeUsage(System.AttributeTargets.xx, AllowMultiple=yy)] - // - // 01 00 - Fixed prolog for CA's - // xx xx xx xx - The System.AttributeTarget value - // 01 00 - Indicates 1 name/value pair following. - // 54 - SERIALIZATION_TYPE_PROPERTY - // 02 - ELEMENT_TYPE_BOOLEAN - // 0d - strlen("AllowMultiple") - 1 - // 41 6c ... 65 - "A" "l" "l" "o" "w" "M" "u" "l" "t" "i" "p" "l" "e" - // yy - The boolean selection for "AllowMultiple" - - BYTE blob[] = { 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x00, 0x54, 0x02, 0x0D, 0x41, 0x6C, 0x6C, 0x6F, 0x77, 0x4D, 0x75, 0x6C, 0x74, 0x69, 0x70, 0x6C, 0x65, 0x00 }; - blob[sizeof(blob) - 1] = allowMultiple ? 1 : 0; - *((DWORD*)(blob+2)) = clrTargetValue; - CABlob *pCABlob; - IfNullRet(pCABlob = CABlob::Create(blob, sizeof(blob))); - *ppCABlob = pCABlob; - return S_OK; -} - - -//------------------------------------------------------------------------------ - -// Gets Guid from Windows.Foundation.Metadata.Guid -HRESULT WinMDAdapter::GetItemGuid(mdToken tkObj, CLSID *pGuid) -{ - HRESULT hr; - _ASSERTE(pGuid); - *pGuid = GUID_NULL; - const BYTE *pBlob; - ULONG cbBlob; - IfFailGo(m_pRawMetaModelCommonRO->CommonGetCustomAttributeByName(tkObj, "Windows.Foundation.Metadata.GuidAttribute", (const void**)&pBlob, &cbBlob)); - if (hr == S_OK) - { - if (cbBlob == 2 + sizeof(GUID) + 2) - { - memcpy(pGuid, pBlob + 2, sizeof(GUID)); - hr = S_OK; - goto ErrExit; - } - } - hr = S_FALSE; - ErrExit: - return hr; - -} - - -//------------------------------------------------------------------------------ - -//---------------------------------------------------------------------------- -// Gets filtered methodImpl list and adds it to an existing DynamicArray enum. -// -// This is used to hide implementations of methods on redirected interfaces after -// we've replaced them with their CLR counterparts in the interface implementation list. -// -// Each filtered methodImpl adds two elements to the enum: the body and decl values -// in that order. -//---------------------------------------------------------------------------- -HRESULT WinMDAdapter::AddMethodImplsToEnum(mdTypeDef tkTypeDef, HENUMInternal *henum) -{ - _ASSERTE(henum != NULL); - _ASSERTE(henum->m_EnumType == MDDynamicArrayEnum); - _ASSERTE(TypeFromToken(tkTypeDef) == mdtTypeDef); - - HRESULT hr; - - mdToken tkMethodImplFirst; - ULONG count; - IfFailGo(m_pRawMetaModelCommonRO->CommonGetMethodImpls(tkTypeDef, &tkMethodImplFirst, &count)); - for (ULONG i = 0; i < count; i++) - { - mdToken tkMethodImpl = tkMethodImplFirst + i; - mdToken tkBody, tkDecl; - IfFailGo(m_pRawMetaModelCommonRO->CommonGetMethodImplProps(tkMethodImpl, &tkBody, &tkDecl)); - UINT nIndex; - IfFailGo(CheckIfMethodImplImplementsARedirectedInterface(tkDecl, &nIndex)); - if (hr == S_FALSE || - (SUCCEEDED(hr) && nIndex == WinMDAdapter::RedirectedTypeIndex_Windows_Foundation_IClosable)) - { - // Keep MethodImpl for IClosable methods and non-redirected interfaces - IfFailGo(HENUMInternal::AddElementToEnum(henum, tkBody)); - IfFailGo(HENUMInternal::AddElementToEnum(henum, tkDecl)); - } - } - - hr = S_OK; - ErrExit: - return hr; -} - -//------------------------------------------------------------------------------ - -// S_OK if this is a CLR implementation type that was mangled and hidden by WinMDExp -// -// Logically, this function takes a mdTypeDef, but since the caller has already extracted the -// row data for other purposes, we'll take the row data. -HRESULT WinMDAdapter::CheckIfClrImplementationType(LPCSTR szName, DWORD dwAttr, LPCSTR *pszUnmangledName) -{ - if (m_scenario != kWinMDExp) - return S_FALSE; // Input file not produced by WinMDExp - if (IsTdNested(dwAttr)) - return S_FALSE; // Type is nested in another type - if ((dwAttr & (tdPublic|tdSpecialName)) != tdSpecialName) - return S_FALSE; // Type public or not SpecialName - if (0 != strncmp(szName, s_szCLRPrefix, s_ncCLRPrefix)) - return S_FALSE; // Name does not begin with "" - - // Ran out of reasons. - *pszUnmangledName = szName + s_ncCLRPrefix; - return S_OK; -} - - -//------------------------------------------------------------------------------ - -//------------------------------------------------------------------------------------- -// Returns: S_OK if tkDecl of a methodImpl is a reference to a method on a redirected interface. -//------------------------------------------------------------------------------------- -HRESULT WinMDAdapter::CheckIfMethodImplImplementsARedirectedInterface(mdToken tkDecl, UINT *pIndex) -{ - - HRESULT hr; - if (TypeFromToken(tkDecl) != mdtMemberRef) - return S_FALSE; // REX will always use memberRef and typeRefs to refer to redirected interfaces, even if in same module. - - mdToken tkParent; - IfFailRet(m_pRawMetaModelCommonRO->CommonGetMemberRefProps(tkDecl, &tkParent)); - - mdTypeRef tkTypeRef; - if (TypeFromToken(tkParent) == mdtTypeRef) - { - tkTypeRef = tkParent; - } - else if (TypeFromToken(tkParent) == mdtTypeSpec) - { - PCCOR_SIGNATURE pvSig; - ULONG cbSig; - IfFailRet(m_pRawMetaModelCommonRO->CommonGetTypeSpecProps(tkParent, &pvSig, &cbSig)); - static const BYTE expectedSigStart[] = {ELEMENT_TYPE_GENERICINST, ELEMENT_TYPE_CLASS}; - if (cbSig < sizeof(expectedSigStart) + 1) - return S_FALSE; - if (0 != memcmp(pvSig, expectedSigStart, sizeof(expectedSigStart))) - return S_FALSE; - const BYTE *pCodedToken = pvSig + sizeof(expectedSigStart); - if (cbSig < sizeof(expectedSigStart) + CorSigUncompressedDataSize(pCodedToken)) - return S_FALSE; - mdToken genericType = CorSigUncompressToken(/*modifies*/pCodedToken); - if (TypeFromToken(genericType) != mdtTypeRef) - return S_FALSE; - tkTypeRef = genericType; - } - else - { - return S_FALSE; - } - - ULONG treatment; - IfFailRet(GetTypeRefTreatment(tkTypeRef, &treatment)); - if ((treatment & kTrClassMask) != kTrClassWellKnownRedirected) - return S_FALSE; - - if (pIndex) - *pIndex = (treatment & ~kTrClassMask); - - return S_OK; -} - -//----------------------------------------------------------------------------------------------------- - -/*static*/ HRESULT WinMDAdapter::CreatePrefixedName(LPCSTR szPrefix, LPCSTR szName, LPCSTR *ppOut) -{ - // This can cause allocations (thus entering the host) during a profiler stackwalk. - // But we're ok since we're not supporting SQL/F1 profiling with WinMDs. FUTURE: - // Would be nice to eliminate allocations on stack walks regardless. - PERMANENT_CONTRACT_VIOLATION(HostViolation, ReasonUnsupportedForSQLF1Profiling); - - size_t ncPrefix = strlen(szPrefix); - size_t ncName = strlen(szName); - if (ncPrefix + ncName < ncPrefix || ncPrefix + ncName + 1 < ncPrefix + ncName) - return E_OUTOFMEMORY; - LPSTR szResult = new (nothrow) char[ncPrefix + ncName + 1]; - IfNullRet(szResult); - memcpy(szResult, szPrefix, ncPrefix); - memcpy(szResult + ncPrefix, szName, ncName); - szResult[ncPrefix + ncName] = '\0'; - *ppOut = szResult; - return S_OK; -} - -//----------------------------------------------------------------------------------------------------- - -// Sentinel value in m_redirectedCABlobsMemoTable table. Means "do no blob rewriting. Return the one from the underlying importer." -/*static*/ WinMDAdapter::CABlob * const WinMDAdapter::CABlob::NOREDIRECT = ((WinMDAdapter::CABlob *)(0x1)); - -//----------------------------------------------------------------------------------------------------- - -/*static*/ WinMDAdapter::CABlob* WinMDAdapter::CABlob::Create(const BYTE *pBlob, ULONG cbBlob) -{ - // This can cause allocations (thus entering the host) during a profiler stackwalk. - // But we're ok since we're not supporting SQL/F1 profiling with WinMDs. FUTURE: - // Would be nice to eliminate allocations on stack walks regardless. - PERMANENT_CONTRACT_VIOLATION(HostViolation, ReasonUnsupportedForSQLF1Profiling); - - size_t cbAlloc = sizeof(CABlob) + cbBlob; // This overestimates the needed size a bit - no biggie - if (cbAlloc < sizeof(CABlob)) - return NULL; - - CABlob *pNewCABlob = (CABlob*)(new (nothrow) BYTE[cbAlloc]); - if (!pNewCABlob) - return NULL; - - pNewCABlob->cbBlob = cbBlob; - memcpy(pNewCABlob->data, pBlob, cbBlob); - return pNewCABlob; -} - -//----------------------------------------------------------------------------------------------------- - -/*static*/ void WinMDAdapter::CABlob::Destroy(WinMDAdapter::CABlob *pCABlob) -{ - if (pCABlob != CABlob::NOREDIRECT) - delete [] (BYTE*)pCABlob; -} - -//----------------------------------------------------------------------------------------------------- - -// Sentinel value in m_redirectedMethodSigMemoTable or m_redirectedFieldMemoTable. -// Means "do no signature rewriting. Return the one from the underlying importer." -/*static*/ WinMDAdapter::SigData * const WinMDAdapter::SigData::NOREDIRECT = ((WinMDAdapter::SigData *)(0x1)); - -//----------------------------------------------------------------------------------------------------- - -/*static*/ WinMDAdapter::SigData* WinMDAdapter::SigData::Create(ULONG cbSig, PCCOR_SIGNATURE pSig) -{ - // This can cause allocations (thus entering the host) during a profiler stackwalk. - // But we're ok since we're not supporting SQL/F1 profiling with WinMDs. FUTURE: - // Would be nice to eliminate allocations on stack walks regardless. - PERMANENT_CONTRACT_VIOLATION(HostViolation, ReasonUnsupportedForSQLF1Profiling); - - _ASSERTE(pSig != NULL); - size_t cbAlloc = sizeof(SigData) + cbSig; // This overestimates the needed size a bit - no biggie - if (cbAlloc < sizeof(SigData)) - return NULL; - - SigData *pNewSigData = (SigData*)(new (nothrow) BYTE[cbAlloc]); - if (!pNewSigData) - return NULL; - - pNewSigData->cbSig = cbSig; - memcpy(pNewSigData->data, pSig, cbSig); - return pNewSigData; -} - -//----------------------------------------------------------------------------------------------------- - -/*static*/ void WinMDAdapter::SigData::Destroy(WinMDAdapter::SigData *pSigData) -{ - if (pSigData != SigData::NOREDIRECT) - delete [] (BYTE*)pSigData; -} - -//----------------------------------------------------------------------------------------------------- - -//----------------------------------------------------------------------------------------------------- -// S_OK if pUnknown is really a WinMD wrapper. This is just a polite way of asking "is it bad to -// to static cast pUnknown to RegMeta/MDInternalRO." -//----------------------------------------------------------------------------------------------------- -HRESULT CheckIfImportingWinMD(IUnknown *pUnknown) -{ - IUnknown *pIgnore = NULL; - HRESULT hr = pUnknown->QueryInterface(IID_IWinMDImport, (void**)&pIgnore); - if (hr == S_OK) - { - pIgnore->Release(); - } - if (hr == E_NOINTERFACE) - { - hr = S_FALSE; - } - return hr; -} - - -//----------------------------------------------------------------------------------------------------- -// E_NOTIMPL if pUnknown is really a WinMD wrapper. -//----------------------------------------------------------------------------------------------------- -HRESULT VerifyNotWinMDHelper(IUnknown *pUnknown -#ifdef _DEBUG - ,LPCSTR assertMsg - ,LPCSTR file - ,int line -#endif //_DEBUG - ) -{ - HRESULT hr = CheckIfImportingWinMD(pUnknown); - if (FAILED(hr)) - return hr; - if (hr == S_FALSE) - { - return S_OK; - } -#ifdef _DEBUG -#ifndef DACCESS_COMPILE - if (CLRConfig::GetConfigValue(CLRConfig::INTERNAL_MD_WinMD_AssertOnIllegalUsage)) - { - DbgAssertDialog(file, line, assertMsg); - } -#endif -#endif - return E_NOTIMPL; -} - - - diff --git a/src/coreclr/src/md/winmd/inc/adapter.h b/src/coreclr/src/md/winmd/inc/adapter.h deleted file mode 100644 index ef6306f..0000000 --- a/src/coreclr/src/md/winmd/inc/adapter.h +++ /dev/null @@ -1,942 +0,0 @@ -// 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. -#ifndef __MDWinMDAdapter__h__ -#define __MDWinMDAdapter__h__ - -#include "memotable.h" -#include "../../inc/winmdinterfaces.h" -#include "thekey.h" -#include "ecmakey.h" - -// Instantiation of template in holder.h -template void DoNothing(ULONG); - -class SigBuilder; -class SigParser; - -typedef const BYTE * PCBYTE; -static const BYTE s_pbContractPublicKeyToken[] = {0xB0,0x3F,0x5F,0x7F,0x11,0xD5,0x0A,0x3A}; -static const BYTE s_pbContractPublicKey[] = {0x00, 0x24, 0x00, 0x00, 0x04, 0x80, 0x00, 0x00, 0x94, 0x00, 0x00, 0x00, 0x06, 0x02, 0x00, 0x00, 0x00, 0x24, 0x00, 0x00, 0x52, 0x53, 0x41, 0x31, 0x00, 0x04, 0x00, 0x00, 0x01, 0x00, 0x01, 0x00, 0x07, 0xD1, 0xFA, 0x57, 0xC4, 0xAE, 0xD9, 0xF0, 0xA3, 0x2E, 0x84, 0xAA, 0x0F, 0xAE, 0xFD, 0x0D, 0xE9, 0xE8, 0xFD, 0x6A, 0xEC, 0x8F, 0x87, 0xFB, 0x03, 0x76, 0x6C, 0x83, 0x4C, 0x99, 0x92, 0x1E, 0xB2, 0x3B, 0xE7, 0x9A, 0xD9, 0xD5, 0xDC, 0xC1, 0xDD, 0x9A, 0xD2, 0x36, 0x13, 0x21, 0x02, 0x90, 0x0B, 0x72, 0x3C, 0xF9, 0x80, 0x95, 0x7F, 0xC4, 0xE1, 0x77, 0x10, 0x8F, 0xC6, 0x07, 0x77, 0x4F, 0x29, 0xE8, 0x32, 0x0E, 0x92, 0xEA, 0x05, 0xEC, 0xE4, 0xE8, 0x21, 0xC0, 0xA5, 0xEF, 0xE8, 0xF1, 0x64, 0x5C, 0x4C, 0x0C, 0x93, 0xC1, 0xAB, 0x99, 0x28, 0x5D, 0x62, 0x2C, 0xAA, 0x65, 0x2C, 0x1D, 0xFA, 0xD6, 0x3D, 0x74, 0x5D, 0x6F, 0x2D, 0xE5, 0xF1, 0x7E, 0x5E, 0xAF, 0x0F, 0xC4, 0x96, 0x3D, 0x26, 0x1C, 0x8A, 0x12, 0x43, 0x65, 0x18, 0x20, 0x6D, 0xC0, 0x93, 0x34, 0x4D, 0x5A, 0xD2, 0x93}; - -class DECLSPEC_UUID("996AA908-5606-476d-9985-48607B2DA076") IWinMDImport : public IUnknown -{ -public : - STDMETHOD(IsScenarioWinMDExp)(BOOL *pbResult) = 0; - STDMETHOD(IsRuntimeClassImplementation)(mdTypeDef tkTypeDef, BOOL *pbResult) = 0; -}; - -//======================================================================================== -// Only IWinMDImport and IWinMDImportInternalRO QI successfully for this guid - for cases where we need to -// tell the difference between the classic MD importers and the WinMD wrappers. -//======================================================================================== -// {996AA908-5606-476d-9985-48607B2DA076} -extern const IID DECLSPEC_SELECTANY IID_IWinMDImport = __uuidof(IWinMDImport); - -//======================================================================================== -// Popup an assert box if COMPLUS_MD_WinMD_AssertOnIllegalUsage=1 -//======================================================================================== -#if defined(_DEBUG) && !defined(DACCESS_COMPILE) -#define WINMD_COMPAT_ASSERT(assertMsg) if (CLRConfig::GetConfigValue(CLRConfig::INTERNAL_MD_WinMD_AssertOnIllegalUsage)) DbgAssertDialog(__FILE__, __LINE__, assertMsg) -#else -#define WINMD_COMPAT_ASSERT(assertMsg) -#endif - - -//======================================================================================== -// class WinMDAdapter -// -// This object performs typeref redirection and any other chores involved in -// masquerading WinMD files as .NET assemblies. -// -// WinMDAdapters act as internal helper objects to WinMDImport and WinMDInternalImportRO -// and factor out as much common code as is practical given that these two importers -// expose wildly different interfaces. -// -// The main input to this object is a standard .NET metadata importer (the "raw" importer.) Since -// the two importers have no common public interface, we use the internal (non-COM) IMetaModelCommon -// interface that both imports have internally and expose through the private IMDCommon -// interface. -// -// Methods on this class follow the IMDInternalImport philosophy (i.e. validation? what validation?, -// return strings as direct UTF8 pointers to internal strings allocated for the lifetime -// of WinMDAdapter.) When used by the public IMetaDataImport adapter, it's important that the caller -// validate parameters before invoking WinMDAdapter. -//======================================================================================== -class WinMDAdapter -{ -public: -#define DEFINE_PROJECTED_TYPE(szWinRTNS, szWinRTName, szClrNS, szClrName, ClrAsmIdx, nContractAsmIdx, WinRTIndex, ClrIndex, TypeKind) \ - RedirectedTypeIndex_ ## WinRTIndex, \ - RedirectedTypeIndex_ ## ClrIndex = RedirectedTypeIndex_ ## WinRTIndex, \ - - // Indexes of well-known redirected types into array code:g_rgRedirectedTypes - enum RedirectedTypeIndex - { -#include "WinRTProjectedTypes.h" - RedirectedTypeIndex_Count, - RedirectedTypeIndex_Invalid = -1, - }; -#undef DEFINE_PROJECTED_TYPE - - enum FrameworkAssemblyIndex - { - FrameworkAssembly_Mscorlib, - FrameworkAssembly_SystemObjectModel, - FrameworkAssembly_SystemRuntime, - FrameworkAssembly_SystemRuntimeWindowsRuntime, - FrameworkAssembly_SystemRuntimeWindowsRuntimeUIXaml, - FrameworkAssembly_SystemNumericsVectors, - - FrameworkAssembly_Count, - }; - - // If new contract assemblies need to be added, they must be appended to the end of the following list. - // Also, don't remove or change any existing assemblies in this list. - // Not following these rules will break existing MDIL images generated in the Store. - enum ContractAssemblyIndex - { - ContractAssembly_SystemRuntime, - ContractAssembly_SystemRuntimeInteropServicesWindowsRuntime, - ContractAssembly_SystemObjectModel, - ContractAssembly_SystemRuntimeWindowsRuntime, - ContractAssembly_SystemRuntimeWindowsRuntimeUIXaml, - ContractAssembly_SystemNumericsVectors, // GetExtraAssemblyRefCount assumes SystemNumericsVectors is the last assembly. - // If you add an assembly you must update GetActualExtraAssemblyRefCount. - - ContractAssembly_Count, - }; - - - enum WinMDTypeKind - { - WinMDTypeKind_Attribute, - WinMDTypeKind_Enum, - WinMDTypeKind_Delegate, - WinMDTypeKind_Interface, - WinMDTypeKind_PDelegate, - WinMDTypeKind_PInterface, - WinMDTypeKind_Struct, - WinMDTypeKind_Runtimeclass, - }; - - int GetExtraAssemblyRefCount(); - - // Factory and destructor - static HRESULT Create(IMDCommon *pRawMDCommon, /*[out]*/ WinMDAdapter **ppAdapter); - ~WinMDAdapter(); - - // Map a well-known WinRT typename to CLR typename - static BOOL ConvertWellKnownTypeNameFromWinRTToClr(LPCSTR *pszNamespace, LPCSTR *pszName); - - // Map a well-known WinRT full typename to CLR full typename - static BOOL ConvertWellKnownFullTypeNameFromWinRTToClr(LPCWSTR *pszFullName, RedirectedTypeIndex *pIndex); - - // Map a well-known CLR typename to WinRT typename - static BOOL ConvertWellKnownTypeNameFromClrToWinRT(LPCSTR *pszFullName); - - // Map a well-known CLR typename to WinRT typename - static BOOL ConvertWellKnownTypeNameFromClrToWinRT(LPCSTR *pszNamespace, LPCSTR *pszName); - - // Returns names of redirected type 'index'. - static void GetRedirectedTypeInfo( - RedirectedTypeIndex index, - LPCSTR * pszClrNamespace, - LPCSTR * pszClrName, - LPCSTR * pszFullWinRTName, - FrameworkAssemblyIndex * pFrameworkAssemblyIdx, - ContractAssemblyIndex * pContractAssemblyIdx, - WinMDTypeKind * pWinMDTypeKind); - - // Returns name of redirected type 'index'. - static LPCWSTR GetRedirectedTypeFullWinRTName(RedirectedTypeIndex index); - static LPCSTR GetRedirectedTypeFullCLRName(RedirectedTypeIndex index); - - // Returns renamed typedefs - HRESULT GetTypeDefProps( - mdTypeDef typeDef, // [IN] given typedef - LPCUTF8 *pszNameSpace, // [OUT] return typedef namespace - LPCUTF8 *pszName, // [OUT] return typedef name - DWORD *pdwFlags, // [OUT] return typedef flags - mdToken *ptkExtends // [OUT] Put base class TypeDef/TypeRef here. - ); - - // Find TypeDef by name - HRESULT FindTypeDef( - LPCSTR szTypeDefNamespace, // [IN] Namespace for the TypeDef. - LPCSTR szTypeDefName, // [IN] Name of the TypeDef. - mdToken tkEnclosingClass, // [IN] TypeDef/TypeRef of enclosing class. - mdTypeDef * ptkTypeDef // [OUT] return typedef - ); - - // Returns redirected typerefs - HRESULT GetTypeRefProps( - mdTypeRef typeref, // [IN] given typeref - LPCSTR *psznamespace, // [OUT] return typeref namespace - LPCSTR *pszname, // [OUT] return typeref name - mdToken *ptkResolutionScope // [OUT] return typeref resolutionscope - ); - - // Find TypeRef by name - HRESULT FindTypeRef( - LPCSTR szNamespace, // [IN] Namespace for the TypeRef (NULL for standalone names) - LPCSTR szName, // [IN] Name of the TypeRef. - mdToken tkResolutionScope, // [IN] Resolution Scope fo the TypeRef. - mdTypeRef *ptk // [OUT] TypeRef token returned. - ); - - // Modify an ExportedType name - HRESULT ModifyExportedTypeName( - mdExportedType tkExportedType, // [IN] exportedType token - LPCSTR *pszNamespace, // [IN,OUT,OPTIONAL] namespace to modify - LPCSTR *pszName // [IN,OUT,OPTIONAL] name to modify - ); - - // Find ExportedType by name - HRESULT FindExportedType( - LPCUTF8 szNamespace, // [IN] expected namespace - LPCUTF8 szName, // [IN] expected name - mdToken tkEnclosingType, // [IN] expected tkEnclosingType - mdExportedType *ptkExportedType // [OUT] ExportedType token returned. - ); - - // Returns rewritten metadata version string - HRESULT GetVersionString( - LPCSTR *pszVersion // [OUT] return metadata version string - ) - { - _ASSERTE(pszVersion != NULL); - *pszVersion = m_pRedirectedVersionString; - return S_OK; - } - - void ModifyAssemblyRefProps( - mdAssemblyRef mdar, - const void **ppbPublicKeyOrToken, - ULONG *pcbPublicKeyOrToken, - LPCSTR *pszName, - USHORT *pusMajorVersion, - USHORT *pusMinorVersion, - USHORT *pusBuildNumber, - USHORT *pusRevisionNumber, - const void **ppbHashValue, - ULONG *pcbHashValue) - { - _ASSERTE(TypeFromToken(mdar) == mdtAssemblyRef); - - if (m_assemblyRefMscorlib == mdar) - { - if (pusMajorVersion != nullptr) - *pusMajorVersion = 4; - if (pusMinorVersion != nullptr) - *pusMinorVersion = 0; - if (pusBuildNumber != nullptr) - *pusBuildNumber = 0; - if (pusRevisionNumber != nullptr) - *pusRevisionNumber = 0; - - // Under CoreCLR, we replace the ECMA key in the mscorlib assembly ref with the CoreCLR platform public key token - if (ppbPublicKeyOrToken != nullptr) - { - *ppbPublicKeyOrToken = g_rbTheSilverlightPlatformKeyToken; - *pcbPublicKeyOrToken = _countof(g_rbTheSilverlightPlatformKeyToken); - } - } - else if (RidFromToken(mdar) > m_rawAssemblyRefCount) - { - // This is one of the assemblies that we inject - UINT index = RidFromToken(mdar) - m_rawAssemblyRefCount - 1; - - if (ppbPublicKeyOrToken != nullptr) - { - if (index != ContractAssemblyIndex::ContractAssembly_SystemRuntimeWindowsRuntime && - index != ContractAssemblyIndex::ContractAssembly_SystemRuntimeWindowsRuntimeUIXaml) - { - // The assembly ref is a contract/facade assembly. System.Runtime.WindowsRuntime and - // System.Runtime.WindowsRuntime.UI.Xaml are special cased because the contract and the implementation - // assembly share the same identity and use mscorlib's public key/token that ppbPublicKeyOrToken - // alredy contains since the raw GetAssemblyRefProps was called with mscorlib's token before this - // function was called. - if (*pcbPublicKeyOrToken == sizeof(s_pbContractPublicKeyToken)) - *ppbPublicKeyOrToken = s_pbContractPublicKeyToken; - else if (*pcbPublicKeyOrToken == sizeof(s_pbContractPublicKey)) - *ppbPublicKeyOrToken = s_pbContractPublicKey; - } - else - { - // System.Runtime.WindowsRuntime uses the ECMA key. - // The WinRT adapter's policy of using mscorlib's assembly references for all the additional - // assembly references doesn't work here since mscorlib uses the Silverlight Platform key. - if (*pcbPublicKeyOrToken == sizeof(g_rbNeutralPublicKeyToken)) - *ppbPublicKeyOrToken = g_rbNeutralPublicKeyToken; - else if (*pcbPublicKeyOrToken == sizeof(g_rbNeutralPublicKey)) - *ppbPublicKeyOrToken = g_rbNeutralPublicKey; - } - } - - if (pszName != nullptr) - *pszName = GetExtraAssemblyRefName(mdar); - - if (pusMajorVersion != nullptr) - *pusMajorVersion = 4; - if (pusMinorVersion != nullptr) - *pusMinorVersion = 0; - if (pusBuildNumber != nullptr) - *pusBuildNumber = 0; - if (pusRevisionNumber != nullptr) - *pusRevisionNumber = 0; - - if (ppbHashValue) - *ppbHashValue = NULL; - - if (pcbHashValue) - *pcbHashValue = 0; - } - } - - // Modifes the FieldDefProps. - HRESULT ModifyFieldDefProps (mdFieldDef tkFielddDef, DWORD *pdwFlags); - - // Modifies FieldProps - HRESULT ModifyFieldProps (mdToken tkField, mdToken tkParent, LPCSTR szFieldName, DWORD *pdwFlags); - - // Modifies methodDef flags and RVA - HRESULT ModifyMethodProps(mdMethodDef tkMethodDef, /*[in, out]*/ DWORD *pdwAttr, /* [in,out] */ DWORD *pdwImplFlags, /* [in,out] */ ULONG *pulRVA, LPCSTR *pszName); - - // Modifies member flags and RVA - HRESULT ModifyMemberProps(mdToken tkMember, /*[in, out]*/ DWORD *pdwAttr, /* [in,out] */ DWORD *pdwImplFlags, /* [in,out] */ ULONG *pulRVA, LPCSTR *pszNewName); - - // Modifies CA's - HRESULT GetCustomAttributeByName( // S_OK or error. - mdToken tkObj, // [IN] Object with Custom Attribute. - LPCUTF8 szName, // [IN] Name of desired Custom Attribute. - mdCustomAttribute *ptkCA, // [OUT] Put custom attribute token here - const void **ppData, // [OUT] Put pointer to data here. - ULONG *pcbData); // [OUT] Put size of data here. - - // Modify CA blobs - HRESULT GetCustomAttributeBlob( - mdCustomAttribute tkCA, - const void **ppData, // [OUT] Put pointer to data here. - ULONG *pcbData); // [OUT] Put size of data here. - - // Gets the GUID used for COM interop purposes. - HRESULT GetItemGuid(mdToken tkObj, CLSID *pGuid); - - // Gets filtered methodImpl list - HRESULT AddMethodImplsToEnum(mdTypeDef tkTypeDef, HENUMInternal *henum); - - //----------------------------------------------------------------------------------- - // For each token, we cache the signature that the adapter reports to callers. - //----------------------------------------------------------------------------------- - struct SigData - { - ULONG cbSig; // Length of sig in bytes - BYTE data[1]; // Signature - - static SigData* Create(ULONG cbSig, PCCOR_SIGNATURE pSig); - static void Destroy(SigData *pSigData); - - // Sentinel value meaning we did not need to rewrite the signature; use the underlying importer's signature - static SigData* const NOREDIRECT; - }; - - // Gets a method/field/TypeSpec/MethodSpec signature, with appropriate WinMD changes. - HRESULT ReinterpretMethodSignature (ULONG cbOrigSigBlob, PCCOR_SIGNATURE pOrigSig, SigData **ppSigData); - HRESULT ReinterpretFieldSignature (ULONG cbOrigSigBlob, PCCOR_SIGNATURE pOrigSig, SigData **ppSigData); - HRESULT ReinterpretTypeSpecSignature (ULONG cbOrigSigBlob, PCCOR_SIGNATURE pOrigSig, SigData **ppSigData); - HRESULT ReinterpretMethodSpecSignature (ULONG cbOrigSigBlob, PCCOR_SIGNATURE pOrigSig, SigData **ppSigData); - - template - HRESULT ReinterpretSignature( - ULONG cbOrigSigBlob, // [IN] count of bytes in original signature blob - PCCOR_SIGNATURE pOrigSig, // [IN] original signature - SigData **ppSigData // [OUT] new signature or SigData::NOREDIRECT - ) - { - UNREACHABLE_MSG("You should create a specialized version of ReinterpretSignature for this token type"); - } - - // Explicit specializations of ReinterpretSignature for all supported token types - template<> // mdMethodDef - HRESULT ReinterpretSignature(ULONG cbOrigSigBlob, PCCOR_SIGNATURE pOrigSig, SigData **ppSigData) - { - return ReinterpretMethodSignature(cbOrigSigBlob, pOrigSig, ppSigData); - } - - template<> // mdFieldDef - HRESULT ReinterpretSignature(ULONG cbOrigSigBlob, PCCOR_SIGNATURE pOrigSig, SigData **ppSigData) - { - return ReinterpretFieldSignature(cbOrigSigBlob, pOrigSig, ppSigData); - } - - template<> // mdMemberRef - HRESULT ReinterpretSignature(ULONG cbOrigSigBlob, PCCOR_SIGNATURE pOrigSig, SigData **ppSigData) - { - if (cbOrigSigBlob == 0) - { - *ppSigData = SigData::NOREDIRECT; - - return META_E_BAD_SIGNATURE; - } - - // MemberRef references either a field or a method - return (*pOrigSig == IMAGE_CEE_CS_CALLCONV_FIELD) ? - ReinterpretFieldSignature(cbOrigSigBlob, pOrigSig, ppSigData) : - ReinterpretMethodSignature(cbOrigSigBlob, pOrigSig, ppSigData); - } - - template<> // mdProperty - HRESULT ReinterpretSignature(ULONG cbOrigSigBlob, PCCOR_SIGNATURE pOrigSig, SigData **ppSigData) - { - // Per ECMA CLI spec, section 23.2.5 PropertySig is just an ordinary method (getter) signature - return ReinterpretMethodSignature(cbOrigSigBlob, pOrigSig, ppSigData); - } - - template<> // mdTypeSpec - HRESULT ReinterpretSignature(ULONG cbOrigSigBlob, PCCOR_SIGNATURE pOrigSig, SigData **ppSigData) - { - return ReinterpretTypeSpecSignature(cbOrigSigBlob, pOrigSig, ppSigData); - } - - template<> // mdMethodSpec - HRESULT ReinterpretSignature(ULONG cbOrigSigBlob, PCCOR_SIGNATURE pOrigSig, SigData **ppSigData) - { - return ReinterpretMethodSpecSignature(cbOrigSigBlob, pOrigSig, ppSigData); - } - - // Note: This method will look in a cache for the reinterpreted signature, but does not add any values to - // the cache or do any work on failure. If we can't find it then it returns S_FALSE. - static HRESULT GetCachedSigForToken( - mdToken token, // [IN] given token - MemoTable &memoTable, // [IN] the MemoTable to use - ULONG *pcbSigBlob, // [OUT] count of bytes in the signature blob - PCCOR_SIGNATURE *ppSig, // [OUT] new signature - BOOL *pfPassThrough // [OUT] did the cache say we don't need to reinterpret this sig? - ); - - static HRESULT InsertCachedSigForToken( - mdToken token, // [IN] given token - MemoTable &memoTable, // [IN] the MemoTable to use - SigData **ppSigData // [IN, OUT] new signature or SigData::NOREDIRECT if the signature didn't need to be reparsed, - ); // will be updated with another (but identical) SigData* if this thread lost the race - - template - HRESULT GetOriginalSigForToken( - T *pImport, - mdToken token, // [IN] Token. - PCCOR_SIGNATURE *ppvSig, // [OUT] return pointer to signature. - ULONG *pcbSig // [OUT] return size of signature. - ) - { - UNREACHABLE_MSG("You should create a specialized version of GetOriginalSigForToken for this interface/token type"); - } - - template - MemoTable &GetSignatureMemoTable() - { - UNREACHABLE_MSG("You should create a specialized version of GetSignatureMemoTable for this token type"); - } - - // Explicit specializations of GetOriginalSigForToken for all supported token types (IMetaDataImport2) - template<> // mdMethodDef - HRESULT GetOriginalSigForToken(IMetaDataImport2 *pImport, mdMethodDef tk, PCCOR_SIGNATURE *ppvSig, ULONG *pcbSig) - { - return pImport->GetMethodProps(tk, NULL, NULL, 0, NULL, NULL, ppvSig, pcbSig, NULL, NULL); - } - - template<> // mdFieldDef - HRESULT GetOriginalSigForToken(IMetaDataImport2 *pImport, mdFieldDef tk, PCCOR_SIGNATURE *ppvSig, ULONG *pcbSig) - { - return pImport->GetFieldProps(tk, NULL, NULL, 0, NULL, NULL, ppvSig, pcbSig, NULL, NULL, NULL); - } - - template<> // mdMemberRef - HRESULT GetOriginalSigForToken(IMetaDataImport2 *pImport, mdMemberRef tk, PCCOR_SIGNATURE *ppvSig, ULONG *pcbSig) - { - return pImport->GetMemberRefProps(tk, NULL, NULL, 0, NULL, ppvSig, pcbSig); - } - - template<> // mdProperty - HRESULT GetOriginalSigForToken(IMetaDataImport2 *pImport, mdProperty tk, PCCOR_SIGNATURE *ppvSig, ULONG *pcbSig) - { - return pImport->GetPropertyProps(tk, NULL, NULL, 0, NULL, NULL, ppvSig, pcbSig, NULL, NULL, NULL, NULL, NULL, NULL, 0, NULL); - } - - template<> // mdTypeSpec - HRESULT GetOriginalSigForToken(IMetaDataImport2 *pImport, mdTypeSpec tk, PCCOR_SIGNATURE *ppvSig, ULONG *pcbSig) - { - return pImport->GetTypeSpecFromToken(tk, ppvSig, pcbSig); - } - - template<> // mdMethodSpec - HRESULT GetOriginalSigForToken(IMetaDataImport2 *pImport, mdMethodSpec tk, PCCOR_SIGNATURE *ppvSig, ULONG *pcbSig) - { - return pImport->GetMethodSpecProps(tk, NULL, ppvSig, pcbSig); - } - - // Explicit specializations of GetOriginalSigForToken for all supported token types (IMDInternalImport) - template<> // mdMethodDef - HRESULT GetOriginalSigForToken(IMDInternalImport *pImport, mdMethodDef tk, PCCOR_SIGNATURE *ppvSig, ULONG *pcbSig) - { - return pImport->GetSigOfMethodDef(tk, pcbSig, ppvSig); - } - - template<> // mdFieldDef - HRESULT GetOriginalSigForToken(IMDInternalImport *pImport, mdFieldDef tk, PCCOR_SIGNATURE *ppvSig, ULONG *pcbSig) - { - return pImport->GetSigOfFieldDef(tk, pcbSig, ppvSig); - } - - template<> // mdMemberRef - HRESULT GetOriginalSigForToken(IMDInternalImport *pImport, mdMemberRef tk, PCCOR_SIGNATURE *ppvSig, ULONG *pcbSig) - { - LPCSTR szMemberRefName; - return pImport->GetNameAndSigOfMemberRef(tk, ppvSig, pcbSig, &szMemberRefName); - } - - template<> // mdProperty - HRESULT GetOriginalSigForToken(IMDInternalImport *pImport, mdProperty tk, PCCOR_SIGNATURE *ppvSig, ULONG *pcbSig) - { - return pImport->GetPropertyProps(tk, NULL, NULL, ppvSig, pcbSig); - } - - template<> // mdTypeSpec - HRESULT GetOriginalSigForToken(IMDInternalImport *pImport, mdTypeSpec tk, PCCOR_SIGNATURE *ppvSig, ULONG *pcbSig) - { - return pImport->GetSigFromToken(tk, pcbSig, ppvSig); - } - - template<> // mdMethodSpec - HRESULT GetOriginalSigForToken(IMDInternalImport *pImport, mdMethodSpec tk, PCCOR_SIGNATURE *ppvSig, ULONG *pcbSig) - { - return pImport->GetMethodSpecProps(tk, NULL, ppvSig, pcbSig); - } - - - // Returns signature for the given MethodDef, FieldDef, MemberRef, standalone Signature, Property, TypeSpec, or MethodSpec token. - // Performs cache lookup, computes the new reinterpreted signature if needed, and inserts it into the cache. Be sure to instantiate - // the method with right template arguments. T is the underlying metadata interface that should be used to retrieve the original - // signature if not passed in ppOrigSig/pcbOrigSigBlob. TOKENTYPE an mdt* constants corresponding to the type of the token. - template - HRESULT GetSignatureForToken( - mdToken token, - PCCOR_SIGNATURE *ppOrigSig, // [IN] pointer to count of bytes in the original signature blob, NULL if we need to retrieve from GetOriginalSigForToken - ULONG *pcbOrigSigBlob, // [IN] pointer to original signature, NULL if we need to retrieve from GetOriginalSigForToken - PCCOR_SIGNATURE *ppSig, // [OUT] new signature - ULONG *pcbSigBlob, // [OUT] count of bytes in the signature blob - T *pImport) - { - _ASSERTE(TypeFromToken(token) == TOKENTYPE); - if ((ppSig == NULL) && (pcbSigBlob == NULL)) - { - return S_OK; - } - - // When loading NGen images we go through code paths that expect no faults and no - // throws. We will need to take a look at how we use the winmd metadata with ngen, - // potentially storing the post-mangled metadata in the NI because as the adapter grows - // we'll see more of these. - CONTRACT_VIOLATION(ThrowsViolation | FaultViolation); - - HRESULT hr = S_OK; - ULONG cbOrigSigBlob = (ULONG)(-1); - PCCOR_SIGNATURE pOrigSig = NULL; - BOOL fPassThrough = FALSE; - - MemoTable &memoTable = GetSignatureMemoTable(); - - // Get from cache - IfFailRet(GetCachedSigForToken(token, memoTable, pcbSigBlob, ppSig, &fPassThrough)); - if (hr == S_FALSE) - { - // We do not want to leak S_FALSE from this function - hr = S_OK; - - // Original signature has already been provided? - if ((pcbOrigSigBlob == NULL) || (ppOrigSig == NULL)) - { - // Not provided, we need to get one by ourselves - IfFailRet((GetOriginalSigForToken(pImport, token, &pOrigSig, &cbOrigSigBlob))); - } - else - { - // Provided, use that - pOrigSig = *ppOrigSig; - cbOrigSigBlob = *pcbOrigSigBlob; - } - - if (fPassThrough) // We cached that we don't need to reinterpret anything. - { - if (ppSig != NULL) - *ppSig = pOrigSig; - if (pcbSigBlob != NULL) - *pcbSigBlob = cbOrigSigBlob; - } - else - { - SigData *pSigData; - IfFailRet(ReinterpretSignature(cbOrigSigBlob, pOrigSig, &pSigData)); - IfFailRet(InsertCachedSigForToken(token, memoTable, &pSigData)); - - fPassThrough = (pSigData == SigData::NOREDIRECT); - - if (ppSig != NULL) - *ppSig = (fPassThrough ? pOrigSig : (PCCOR_SIGNATURE)pSigData->data); - if (pcbSigBlob != NULL) - *pcbSigBlob = (fPassThrough ? cbOrigSigBlob : pSigData->cbSig); - } - } - else - { - _ASSERTE(!fPassThrough); - // Already wrote to our output parameters. - } - // We should return error (via IfFailRet macro) or S_OK here - _ASSERTE(hr == S_OK); - - return hr; - } - - // - // Support for extra assembly refs inserted into this assembly - // - ULONG GetRawAssemblyRefCount() { return m_rawAssemblyRefCount; } - - mdAssemblyRef GetAssemblyRefMscorlib() { return m_assemblyRefMscorlib; } - - LPCSTR GetExtraAssemblyRefName(mdAssemblyRef mda) - { - UINT index = RidFromToken(mda) - m_rawAssemblyRefCount - 1; - return WinMDAdapter::GetExtraAssemblyRefNameFromIndex((ContractAssemblyIndex)index); - } - - - static LPCSTR GetExtraAssemblyRefNameFromIndex(FrameworkAssemblyIndex index) - { - _ASSERTE(index >= 0 && index < FrameworkAssembly_Count); - _ASSERTE(index != FrameworkAssembly_Mscorlib); - switch(index) - { - case FrameworkAssembly_SystemObjectModel: - return "System.ObjectModel"; - case FrameworkAssembly_SystemRuntime: - return "System.Runtime"; - case FrameworkAssembly_SystemRuntimeWindowsRuntime: - return "System.Runtime.WindowsRuntime"; - case FrameworkAssembly_SystemRuntimeWindowsRuntimeUIXaml: - return "System.Runtime.WindowsRuntime.UI.Xaml"; - case FrameworkAssembly_SystemNumericsVectors: - return "System.Numerics.Vectors"; - default: - _ASSERTE(!"Invalid AssemblyRef token!"); - return NULL; - } - } - - static LPCSTR GetExtraAssemblyRefNameFromIndex(ContractAssemblyIndex index) - { - _ASSERTE(index >= 0 && index < ContractAssembly_Count); - switch(index) - { - case ContractAssembly_SystemRuntime: - return "System.Runtime"; - case ContractAssembly_SystemRuntimeInteropServicesWindowsRuntime: - return "System.Runtime.InteropServices.WindowsRuntime"; - case ContractAssembly_SystemObjectModel: - return "System.ObjectModel"; - case ContractAssembly_SystemRuntimeWindowsRuntime: - return "System.Runtime.WindowsRuntime"; - case ContractAssembly_SystemRuntimeWindowsRuntimeUIXaml: - return "System.Runtime.WindowsRuntime.UI.Xaml"; - case ContractAssembly_SystemNumericsVectors: - return "System.Numerics.Vectors"; - default: - _ASSERTE(!"Invalid AssemblyRef token!"); - return NULL; - } - } - - LPCWSTR GetExtraAssemblyRefNameW(mdAssemblyRef mda) - { - UINT index = RidFromToken(mda) - m_rawAssemblyRefCount - 1; - return WinMDAdapter::GetExtraAssemblyRefNameFromIndexW((ContractAssemblyIndex)index); - } - - static LPCWSTR GetExtraAssemblyRefNameFromIndexW(ContractAssemblyIndex index) - { - _ASSERTE(index >= 0 && index < ContractAssembly_Count); - switch(index) - { - case ContractAssembly_SystemRuntime: - return W("System.Runtime"); - case ContractAssembly_SystemRuntimeInteropServicesWindowsRuntime: - return W("System.Runtime.InteropServices.WindowsRuntime"); - case ContractAssembly_SystemObjectModel: - return W("System.ObjectModel"); - case ContractAssembly_SystemRuntimeWindowsRuntime: - return W("System.Runtime.WindowsRuntime"); - case ContractAssembly_SystemRuntimeWindowsRuntimeUIXaml: - return W("System.Runtime.WindowsRuntime.UI.Xaml"); - case ContractAssembly_SystemNumericsVectors: - return W("System.Numerics.Vectors"); - default: - _ASSERTE(!"Invalid AssemblyRef token!"); - return NULL; - } - } - - BOOL IsValidAssemblyRefToken(mdAssemblyRef tk) - { - _ASSERTE(TypeFromToken(tk) == mdtAssemblyRef); - - RID rid = RidFromToken(tk); - if (rid > 0 && - rid <= m_rawAssemblyRefCount + GetExtraAssemblyRefCount()) - { - return TRUE; - } - - return FALSE; - } - - static void GetExtraAssemblyRefProps(FrameworkAssemblyIndex index, - LPCSTR* ppName, - AssemblyMetaDataInternal* pContext, - PCBYTE * ppPublicKeytoken, - DWORD* pTokenLength, - DWORD* pdwFlags); - - BOOL IsScenarioWinMDExp() - { - return (m_scenario == kWinMDExp); - } - - HRESULT IsRuntimeClassImplementation(mdTypeDef tkTypeDef, BOOL *pbResult) - { - _ASSERTE(pbResult != NULL); - - ULONG typeDefTreatment; - HRESULT hr = GetTypeDefTreatment(tkTypeDef, &typeDefTreatment); - - if (SUCCEEDED(hr)) - { - // kTdUnmangleWinRTName treatment means it is a implementation class - *pbResult = (typeDefTreatment == kTdUnmangleWinRTName); - } - - return hr; - } - -private: - struct CABlob; - -private: - - WinMDAdapter(IMDCommon * pRawMDCommon); - - // S_OK if this is a CLR implementation type that was mangled and hidden by WinMDExp - HRESULT CheckIfClrImplementationType(LPCSTR szName, DWORD dwAttr, LPCSTR *pszUnmangledName); - - // Get TypeRefTreatment value for a typeRef - HRESULT GetTypeRefTreatment(mdTypeRef typeRef, ULONG *ppTypeRefTreatment); - - // Get TypeRef's index in array code:g_rgRedirectedTypes or return S_FALSE. - HRESULT GetTypeRefRedirectedInfo( - mdTypeRef tkTypeRef, - RedirectedTypeIndex * pIndex); - - // Get TypeDefTreatment value for a typeDef - HRESULT GetTypeDefTreatment(mdTypeDef typeDef, ULONG *ppTypeRefTreatment); - - // Get MethodTreatment value for a methodDef - HRESULT GetMethodDefTreatment(mdMethodDef methodDef, ULONG *ppMethodDefTreatment); - - // Compute MethodTreatment value for a methodDef (unlike GetMethodDefTreatment, this - // does not cache.) - HRESULT ComputeMethodDefTreatment(mdMethodDef tkMethodDef, mdTypeDef tkDeclaringTypeDef, ULONG *ppMethodDefTreatment); - - HRESULT CheckIfMethodImplImplementsARedirectedInterface(mdToken tkDecl, UINT *pIndex); - - HRESULT TranslateWinMDAttributeUsageAttribute(mdTypeDef tkTypeDefOfCA, DWORD *pClrTargetValue, BOOL *pAllowMultiple); - - static HRESULT CreateClrAttributeUsageAttributeCABlob(DWORD clrTargetValue, BOOL allowMultiple, CABlob **ppCABlob); - - // Whether the WinRT type should be hidden from managed code - // Example: helper class/interface for projected jupiter structs - static BOOL IsHiddenWinRTType(LPCSTR szWinRTNamespace, LPCSTR szWinRTName); - - // Map a WinRT typename to CLR typename - static BOOL ConvertWellKnownTypeNameFromWinRTToClr(LPCSTR *pszNamespace, LPCSTR *pszName, UINT *pIndex); - - static HRESULT CreatePrefixedName(LPCSTR szPrefix, LPCSTR szName, LPCSTR *ppOut); - - template static void Delete(T* ptr) - { - delete [] ptr; - } - - HRESULT RewriteTypeInSignature(SigParser * pSigParser, SigBuilder * pSigBuilder, BOOL * pfChangedSig); - - private: - //----------------------------------------------------------------------------------- - // Pointer to the raw view of the metadata. - //----------------------------------------------------------------------------------- - IMetaModelCommonRO *m_pRawMetaModelCommonRO; - - - private: - //----------------------------------------------------------------------------------- - // Stores whether the file is a pure .winmd file or one that combines WinRT and CLR code. - //----------------------------------------------------------------------------------- - enum WinMDScenario - { - kWinMDNormal = 1, // File is normal Windows .winmd file (Version string = "Windows Runtime nnn") - kWinMDExp = 2, // File is output of winmdexp (Version string = "Windows Runtime nnn;") - }; - - WinMDScenario m_scenario; - - - private: - - //----------------------------------------------------------------------------------- - // Every WinMD file is required to have an assemblyRef to mscorlib - this field caches that assemblyRef - //----------------------------------------------------------------------------------- - mdAssemblyRef m_assemblyRefMscorlib; - BOOL m_fReferencesMscorlibV4; // m_assemblyRefMscorlib is a version=4.0.0.0 AssemblyRef - ULONG m_rawAssemblyRefCount; // the raw assembly ref count not including the extra ones. - LONG m_extraAssemblyRefCount; // the assembly ref count to return from IMetaDataAssemblyImport::EnumAssemblyRefs - - - private: - //----------------------------------------------------------------------------------- - // For each typeref token, we cache an enum that determines how the adapter treats it. - //----------------------------------------------------------------------------------- - enum TypeRefTreatment - { - // The upper 8 bits determine how to interpret the lower 24-bits: - kTrClassMask = 0xff000000, - - // Lower 24-bits represent fixed values (defined in rest of enum) - kTrClassMisc = 0x00000000, - - // TypeRef is one of a small # of hard-coded Windows.Foundation types that we redirect to mscorlib counterparts. - // Lower 24-bits is index into typeref redirection table. - kTrClassWellKnownRedirected = 0x01000000, - - kTrNotYetInitialized = kTrClassMisc|0x000000, // Entry has not yet been initialized. - kTrNoRewriteNeeded = kTrClassMisc|0x000001, // Do not mangle the name. - kTrSystemDelegate = kTrClassMisc|0x000002, // Fast-recognition code for System.Delegate - kTrSystemAttribute = kTrClassMisc|0x000003, // Fast-recognition code for System.Attribute - kTrSystemEnum = kTrClassMisc|0x000004, // Fast-recognition code for System.Enum - kTrSystemValueType = kTrClassMisc|0x000005, // Fast-recognition code for System.ValueType - }; - MemoTable > m_typeRefTreatmentMemoTable; // Holds index into typeRef rename array or member of TypeRefTreatment enum - - private: - //----------------------------------------------------------------------------------- - // For each typedef token, we cache an enum that determines how the adapter treats it. - //----------------------------------------------------------------------------------- - enum TypeDefTreatment - { - kTdNotYetInitialized = 0x00, - - kTdTreatmentMask = 0x0f, - kTdOther = 0x01, // Anything not covered below, and not affected by the treatment flags - kTdNormalNonAttribute = 0x02, // non-attribute TypeDef from non-managed winmd assembly - kTdNormalAttribute = 0x03, // Attribute TypeDef from non-managed winmd assembly - kTdUnmangleWinRTName = 0x04, // Type in managed winmd that should be renamed from Foo to Foo - kTdPrefixWinRTName = 0x05, // Type in managed winmd that should be renamed from Foo to Foo - kTdRedirectedToCLRType = 0x06, // Type is redirected to a CLR type implementation. - kTdRedirectedToCLRAttribute = 0x07, // Type is redirected to a CLR type implementation that is an attribute. - - kTdMarkAbstractFlag = 0x10, // Type should be marked as abstract - kTdMarkInternalFlag = 0x20, // Type should be hidden from managed code - examples are struct helpers - // for redirected Jupiter structs - kTdEnum = 0x40, // Type is an enum from managed\non-managed winmd assembly. - }; - MemoTable > m_typeDefTreatmentMemoTable; // Holds member of TypeDefTreatment enum - - private: - //----------------------------------------------------------------------------------- - // For each methoddef token, we cache an enum that determines how the adapter treats it. - //----------------------------------------------------------------------------------- - enum MethodDefTreatment - { - kMdNotYetInitialized = 0x00, - kMdTreatmentMask = 0x0f, // Mask of various options - kMdOther = 0x01, // Anything not covered below - kMdDelegate = 0x02, // Declared by delegate - kMdAttribute = 0x03, // Declared by an attribute - kMdInterface = 0x04, // Is member of interface - kMdImplementation = 0x05, // CLR implementation of RuntimeClass - kMdHiddenImpl = 0x06, // Implements a redirected (hidden) interface - kMdtUnusedFlag = 0x07, // UnUnsed flag. - kMdRenameToDisposeMethod = 0x08, // Rename IClosable.Close to Dispose - - kMdMarkAbstractFlag = 0x10, // Method should be marked as abstract - kMdMarkPublicFlag = 0x20, // Method visibility should be marked as public - }; - MemoTable > m_methodDefTreatmentMemoTable; // Holds member of MethodDefTreatment enum - - private: - //----------------------------------------------------------------------------------- - // The version string we report to callers. - //----------------------------------------------------------------------------------- - LPSTR m_pRedirectedVersionString; - - private: - //----------------------------------------------------------------------------------- - // For each customattribute token, we cache the blob that the adapter reports to callers. - // The special pointer value CABlob::NOREDIRECT indicates that the raw blob is to be - // passed unchanged. - //----------------------------------------------------------------------------------- - - // Represents a custom attribute blob - struct CABlob - { - ULONG cbBlob; // Length of blob in bytes. - BYTE data[1]; // Start of variable-length blob (cbBlob indicates length in bytes.) - - static CABlob* Create(const BYTE *pBlob, ULONG cbBlob); - static void Destroy(CABlob *pCABlob); - - // Sentinel value in m_redirectedCABlobsMemoTable table. Means "do no blob rewriting. Return the one from the underlying importer." - static CABlob* const NOREDIRECT; - }; - - MemoTable m_redirectedCABlobsMemoTable; // Array of rewritten CA blobs - - private: - //----------------------------------------------------------------------------------- - // For each token, we cache the signature that the adapter reports to callers. - //----------------------------------------------------------------------------------- - MemoTable m_redirectedMethodDefSigMemoTable; // Array of rewritten MethodDef signatures - MemoTable m_redirectedFieldDefSigMemoTable; // Array of rewritten FieldDef signatures - MemoTable m_redirectedMemberRefSigMemoTable; // Array of rewritten MemberRef signatures - MemoTable m_redirectedPropertySigMemoTable; // Array of rewritten Property signatures - MemoTable m_redirectedTypeSpecSigMemoTable; // Array of rewritten TypeSpec signatures - MemoTable m_redirectedMethodSpecSigMemoTable; // Array of rewritten MethodSpec signatures - - // Explicit specializations of GetSignatureMemoTable for all supported token types - template<> MemoTable &GetSignatureMemoTable() { return m_redirectedMethodDefSigMemoTable; } - template<> MemoTable &GetSignatureMemoTable() { return m_redirectedFieldDefSigMemoTable; } - template<> MemoTable &GetSignatureMemoTable() { return m_redirectedMemberRefSigMemoTable; } - template<> MemoTable &GetSignatureMemoTable() { return m_redirectedPropertySigMemoTable; } - template<> MemoTable &GetSignatureMemoTable() { return m_redirectedTypeSpecSigMemoTable; } - template<> MemoTable &GetSignatureMemoTable() { return m_redirectedMethodSpecSigMemoTable; } - - private: - //----------------------------------------------------------------------------------- - // For each typedef whose name we mangle, we cache the mangled name that we report to callers. (The "name" - // is the "name" half of the namespace/name pair. We don't mangle namespaces.) - // - // Currently, the adapter used the tdAttr value to determine whether a typedef name needs - // be mangled at all - thus, we don't have a sentinel for "don't mangle." - //----------------------------------------------------------------------------------- - MemoTable > m_mangledTypeNameTable; // Array of mangled typedef names -}; - - -#endif // __MDWinMDAdapter__h__ diff --git a/src/coreclr/src/md/winmd/inc/memotable.h b/src/coreclr/src/md/winmd/inc/memotable.h deleted file mode 100644 index d2435b5..0000000 --- a/src/coreclr/src/md/winmd/inc/memotable.h +++ /dev/null @@ -1,205 +0,0 @@ -// 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. -#ifndef __MDMemoTable__h__ -#define __MDMemoTable__h__ - - -//======================================================================================== -// A MemoTable is a 0-based N element array designed for safe multithreaded access -// and single-initialization rules (e.g. multiple threads can race to initialize an entry -// but only the first one actually modifies the table.) -// -// Template parameters: -// -// ELEMTYPE - Type of the data stored in the array. This type must be small enough -// to be supported by InterlockedCompareExchange. -// -// INITVALUE - Sentinel that indicates that InitEntry() has not been called for that entry yet. -// This is the "initial value" for all elements of the array. -// -// ELEMDELETER - (set to NULL if ELEMTYPE does not represent allocated storage.) -// A function that deallocates the memory referenced by a pointer-typed ELEMTYPE. -// MemoTable will never pass INITVALUE to this function. -// -// Restriction: if ELEMDELETER != NULL, ELEMTYPE must be a C++ pointer type -// (annoying template weirdness with InterlockedCompareExchangeT that -// life is too short to disentangle.) -//======================================================================================== -template -class MemoTable -{ -public: - MemoTable(ULONG numElems, ELEMTYPE initValue); - ~MemoTable(); - HRESULT GetEntry(ULONG index, /* [out] */ ELEMTYPE *pElem); - HRESULT InitEntry(ULONG index, /* [in,out] */ ELEMTYPE *pElem); - -private: - MemoTable(const MemoTable &other); - MemoTable& operator=(const MemoTable &other); - - const ULONG m_numElems; - const ELEMTYPE m_initValue; - ELEMTYPE *m_pTable; // Lazily allocated 0-based array with m_numElems elements. -}; - - - - -//============================================================================== -// MemoTable::MemoTable() -//============================================================================== -template -MemoTable::MemoTable(ULONG numElems, ELEMTYPE initValue) : - m_numElems(numElems), - m_initValue(initValue) -{ - m_pTable = NULL; -} - - - -//============================================================================== -// MemoTable::~MemoTable() -//============================================================================== -template -MemoTable::~MemoTable() -{ - if (m_pTable != NULL) - { - if (ELEMDELETER != NULL) - { - for (ULONG index = 0; index < m_numElems; index++) - { - if (m_pTable[index] != m_initValue) - { - ELEMDELETER(m_pTable[index]); - } - } - } - delete [] m_pTable; - } -} - -//============================================================================== -// HRESULT MemoTable::GetEntry(ULONG index, [out] ELEMTYPE *pElem) -// -// Retrieves the element at the specified index. -// -// Returns: -// S_OK if returned element is not INITVALUE -// S_FALSE if returned element is INITVALUE -// CDLB_E_INDEX_NOT_FOUND if index is out of range. -//============================================================================== -template -HRESULT MemoTable::GetEntry(ULONG index, /* [out] */ ELEMTYPE *pElem) -{ - _ASSERTE(pElem); - if (index >= m_numElems) - { - return CLDB_E_INDEX_NOTFOUND; - } - if (m_pTable == NULL) - { - *pElem = m_initValue; - return S_FALSE; - } - ELEMTYPE elem = m_pTable[index]; - *pElem = elem; - return (elem == m_initValue) ? S_FALSE : S_OK; -} - -//============================================================================== -// HRESULT MemoTable::InitEntry(ULONG index, [in, out] ELEMTYPE *pElem) -// -// Initalizes the elment at the specified index. It is illegal to attempt -// to initialize to INITVALUE. For scalar tables, it is illegal to attempt -// to overwrite a previously initialized entry with a different value. -// For pointer tables, the entry will be initialized using InterlockedCompareExchangeT -// and your new value thrown away via ELEMDELETER if you lose the race to initialize. -// -// Returns: -// *pElem overwritten with the actual value written into the table -// (for pointer tables, this may not be the original pointer you passed -// due to races.) -// -// S_OK is the only success value. -//============================================================================== -template -HRESULT MemoTable::InitEntry(ULONG index, /* [in,out] */ ELEMTYPE *pElem) -{ - // This can cause allocations (thus entering the host) during a profiler stackwalk. - // But we're ok since we're not supporting SQL/F1 profiling with WinMDs. FUTURE: - // Would be nice to eliminate allocations on stack walks regardless. - PERMANENT_CONTRACT_VIOLATION(HostViolation, ReasonUnsupportedForSQLF1Profiling); - - HRESULT hr = S_OK; - _ASSERTE(pElem); - ELEMTYPE incomingElem = *pElem; - - if (index >= m_numElems) - { - IfFailGo(CLDB_E_INDEX_NOTFOUND); - } - _ASSERTE(incomingElem != m_initValue); - - // If this is first call to InitEntry(), must initialize the table itself. - if (m_pTable == NULL) - { - NewHolder pNewTable = NULL; - - if ((((size_t)(-1)) / sizeof(ELEMTYPE)) < m_numElems) - { - IfFailGo(E_OUTOFMEMORY); - } - - // When loading NGen images we go through code paths that expect no faults and no - // throws. We will need to take a look at how we use the winmd metadata with ngen, - // potentially storing the post-mangled metadata in the NI because as the adapter grows - // we'll see more of these. - CONTRACT_VIOLATION(FaultViolation); - pNewTable = new (nothrow) ELEMTYPE[m_numElems]; - IfNullGo(pNewTable); - - for (ULONG walk = 0; walk < m_numElems; walk++) - { - pNewTable[walk] = m_initValue; - } - if (InterlockedCompareExchangeT(&m_pTable, pNewTable, NULL) == NULL) - { // We won the initialization race - pNewTable.SuppressRelease(); - } - } - - - //------------------------------------------------------------------------- - // Cannot fail after this point, or we may delete *pElem after entering it into table. - //------------------------------------------------------------------------- - hr = S_OK; - if (ELEMDELETER == NULL) - { - _ASSERTE(m_pTable[index] == m_initValue || m_pTable[index] == incomingElem); - m_pTable[index] = incomingElem; - } - else - { - ELEMTYPE winner = InterlockedCompareExchangeT((ELEMTYPE volatile *)&m_pTable[index], incomingElem, m_initValue); - if (winner != m_initValue) - { - ELEMDELETER(incomingElem); // Lost the race - *pElem = winner; - } - } - _ASSERTE(*pElem != m_initValue); - -ErrExit: - if (ELEMDELETER != NULL && FAILED(hr)) - { - ELEMDELETER(*pElem); - *pElem = m_initValue; - } - return hr; -} - -#endif // __MDMemoTable__h__ diff --git a/src/coreclr/src/md/winmd/stdafx.cpp b/src/coreclr/src/md/winmd/stdafx.cpp deleted file mode 100644 index 625e1a1..0000000 --- a/src/coreclr/src/md/winmd/stdafx.cpp +++ /dev/null @@ -1,12 +0,0 @@ -// 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. -//***************************************************************************** -// stdafx.cpp -// - -// -// Precompiled headers. -// -//***************************************************************************** -#include "stdafx.h" diff --git a/src/coreclr/src/md/winmd/stdafx.h b/src/coreclr/src/md/winmd/stdafx.h deleted file mode 100644 index 32494ed..0000000 --- a/src/coreclr/src/md/winmd/stdafx.h +++ /dev/null @@ -1,29 +0,0 @@ -// 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. -//***************************************************************************** -// stdafx.h -// - -// -// Precompiled headers. -// -//***************************************************************************** -#ifndef __STDAFX_H_ -#define __STDAFX_H_ - -#include -#include -#include - -#include -#include - -#include "nsutilpriv.h" - -#include "utsem.h" - -#include -#include - -#endif // __STDAFX_H_ diff --git a/src/coreclr/src/md/winmd/winmdimport.cpp b/src/coreclr/src/md/winmd/winmdimport.cpp deleted file mode 100644 index c629895..0000000 --- a/src/coreclr/src/md/winmd/winmdimport.cpp +++ /dev/null @@ -1,2138 +0,0 @@ -// 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. - - - -#include "stdafx.h" -#include "winmdinterfaces.h" -#include "metadataexports.h" -#include "inc/adapter.h" -#include "strsafe.h" - -//======================================================================================== -// This metadata importer is exposed publically via CoCreateInstance(CLSID_CorMetaDataDispenser...). -// when the target is a .winmd file. It applies a small number of on-the-fly -// conversions to make the .winmd file look like a regular .NET assembly. -// -// Despite what the MSDN docs say, this importer only supports the reader interfaces and -// a subset of them at that. Supporting the whole set would not be practical with an -// on-the-fly translation strategy. -//======================================================================================== -class WinMDImport : public IMetaDataImport2 - , IMetaDataAssemblyImport - , IMetaDataWinMDImport - , IMetaDataValidate - , IMDCommon - , IMetaModelCommon - , IWinMDImport -#ifdef FEATURE_METADATA_INTERNAL_APIS - , IGetIMDInternalImport -#endif //FEATURE_METADATA_INTERNAL_APIS -{ - public: - //========================================================= - // Factory - //========================================================= - static HRESULT Create(IMDCommon *pRawMDCommon, WinMDImport **ppWinMDImport) - { - HRESULT hr; - *ppWinMDImport = NULL; - - WinMDImport *pNewWinMDImport = new (nothrow) WinMDImport(pRawMDCommon); - - IfFailGo(pNewWinMDImport->m_pRawMDCommon->QueryInterface(IID_IMetaDataImport2, (void**)&pNewWinMDImport->m_pRawImport)); - IfFailGo(pNewWinMDImport->m_pRawImport->QueryInterface(IID_IMetaDataAssemblyImport, (void**)&pNewWinMDImport->m_pRawAssemblyImport)); - - if (FAILED(pNewWinMDImport->m_pRawImport->QueryInterface(IID_IMetaDataValidate, (void**)&pNewWinMDImport->m_pRawValidate))) - { - pNewWinMDImport->m_pRawValidate = nullptr; - } - - pNewWinMDImport->m_pRawMetaModelCommonRO = pRawMDCommon->GetMetaModelCommonRO(); - - IfFailGo(WinMDAdapter::Create(pRawMDCommon, &pNewWinMDImport->m_pWinMDAdapter)); - - (*ppWinMDImport = pNewWinMDImport)->AddRef(); - hr = S_OK; - - ErrExit: - if (pNewWinMDImport) - pNewWinMDImport->Release(); - return hr; - } - - - private: - //========================================================= - // Ctors, Dtors - //========================================================= - WinMDImport(IMDCommon * pRawMDCommon) - { - m_cRef = 1; - m_pRawImport = NULL; - m_pWinMDAdapter = NULL; - m_pRawAssemblyImport = NULL; - m_pFreeThreadedMarshaler = NULL; - (m_pRawMDCommon = pRawMDCommon)->AddRef(); - } - - //--------------------------------------------------------- - ~WinMDImport() - { - if (m_pRawMDCommon) - m_pRawMDCommon->Release(); - if (m_pRawImport) - m_pRawImport->Release(); - if (m_pRawAssemblyImport) - m_pRawAssemblyImport->Release(); - if (m_pRawValidate) - m_pRawValidate->Release(); - if (m_pFreeThreadedMarshaler) - m_pFreeThreadedMarshaler->Release(); - delete m_pWinMDAdapter; - } - - //--------------------------------------------------------- - BOOL IsValidNonNilToken(mdToken token, DWORD tkKind) - { - DWORD tkKindActual = TypeFromToken(token); - DWORD rid = RidFromToken(token); - - if (tkKindActual != tkKind) - return FALSE; - - if (rid == 0) - return FALSE; - - ULONG ulRowCount = m_pRawMetaModelCommonRO->CommonGetRowCount(tkKind); - if (tkKind == mdtAssemblyRef) - return rid <= ulRowCount + m_pWinMDAdapter->GetExtraAssemblyRefCount(); - else - return rid <= ulRowCount; - } - - public: - //========================================================= - // IUnknown methods - //========================================================= - STDMETHODIMP QueryInterface(REFIID riid, void** ppUnk) - { - HRESULT hr; - - *ppUnk = 0; - if (riid == IID_IUnknown || riid == IID_IWinMDImport) - *ppUnk = (IWinMDImport*)this; - else if (riid == IID_IMetaDataImport || riid == IID_IMetaDataImport2) - *ppUnk = (IMetaDataImport*)this; - else if (riid == IID_IMetaDataWinMDImport) - *ppUnk = (IMetaDataWinMDImport*)this; - else if (riid == IID_IMetaDataAssemblyImport) - *ppUnk = (IMetaDataAssemblyImport*)this; - else if (riid == IID_IMDCommon) - *ppUnk = (IMDCommon*)this; - else if (riid == IID_IMetaDataValidate) - { - if (m_pRawValidate == NULL) - { - return E_NOINTERFACE; - } - - *ppUnk = (IMetaDataValidate*)this; - } -#ifdef FEATURE_METADATA_INTERNAL_APIS - else if (riid == IID_IGetIMDInternalImport) - *ppUnk = (IGetIMDInternalImport*)this; -#endif // FEATURE_METADATA_INTERNAL_APIS - else if (riid == IID_IMarshal) - { - if (m_pFreeThreadedMarshaler == NULL) - { - ReleaseHolder pFreeThreadedMarshaler = NULL; - IfFailRet(CoCreateFreeThreadedMarshaler((IUnknown *)(IMetaDataImport *)this, &pFreeThreadedMarshaler)); - if (InterlockedCompareExchangeT(&m_pFreeThreadedMarshaler, pFreeThreadedMarshaler, NULL) == NULL) - { // We won the initialization race - pFreeThreadedMarshaler.SuppressRelease(); - } - } - return m_pFreeThreadedMarshaler->QueryInterface(riid, ppUnk); - } - else - { -#ifndef DACCESS_COMPILE -#ifdef _DEBUG - if (CLRConfig::GetConfigValue(CLRConfig::INTERNAL_MD_WinMD_AssertOnIllegalUsage)) - { - if (riid == IID_IMetaDataTables) - _ASSERTE(!"WinMDImport::QueryInterface(IID_IMetaDataTables) returning E_NOINTERFACE"); - else if (riid == IID_IMetaDataTables2) - _ASSERTE(!"WinMDImport::QueryInterface(IID_IMetaDataTables2) returning E_NOINTERFACE"); - else if (riid == IID_IMetaDataInfo) - _ASSERTE(!"WinMDImport::QueryInterface(IID_IMetaDataInfo) returning E_NOINTERFACE"); - else if (riid == IID_IMetaDataEmit) - _ASSERTE(!"WinMDImport::QueryInterface(IID_IMetaDataEmit) returning E_NOINTERFACE"); - else if (riid == IID_IMetaDataEmit2) - _ASSERTE(!"WinMDImport::QueryInterface(IID_IMetaDataEmit2) returning E_NOINTERFACE"); - else if (riid == IID_IMetaDataAssemblyEmit) - _ASSERTE(!"WinMDImport::QueryInterface(IID_IMetaDataAssemblyEmit) returning E_NOINTERFACE"); - else if (riid == IID_IMetaDataValidate) - _ASSERTE(!"WinMDImport::QueryInterface(IID_IMetaDataValidate) returning E_NOINTERFACE"); - else if (riid == IID_IMetaDataFilter) - _ASSERTE(!"WinMDImport::QueryInterface(IID_IMetaDataFilter) returning E_NOINTERFACE"); - else if (riid == IID_IMetaDataHelper) - _ASSERTE(!"WinMDImport::QueryInterface(IID_IMetaDataHelper) returning E_NOINTERFACE"); - else if (riid == IID_IMDInternalEmit) - _ASSERTE(!"WinMDImport::QueryInterface(IID_IMDInternalEmit) returning E_NOINTERFACE"); - else if (riid == IID_IMetaDataEmitHelper) - _ASSERTE(!"WinMDImport::QueryInterface(IID_IMetaDataEmitHelper) returning E_NOINTERFACE"); -#ifdef FEATURE_PREJIT - else if (riid == IID_IMetaDataCorProfileData) - _ASSERTE(!"WinMDImport::QueryInterface(IID_IMetaDataCorProfileData) returning E_NOINTERFACE"); - else if (riid == IID_IMDInternalMetadataReorderingOptions) - _ASSERTE(!"WinMDImport::QueryInterface(IID_IMDInternalMetadataReorderingOptions) returning E_NOINTERFACE"); -#endif - else - _ASSERTE(!"WinMDImport::QueryInterface() returning E_NOINTERFACE"); - } -#endif //_DEBUG -#endif - return E_NOINTERFACE; - } - AddRef(); - return S_OK; - } - //--------------------------------------------------------- - STDMETHODIMP_(ULONG) AddRef(void) - { - return InterlockedIncrement(&m_cRef); - } - //--------------------------------------------------------- - STDMETHODIMP_(ULONG) Release(void) - { - ULONG cRef = InterlockedDecrement(&m_cRef); - if (!cRef) - delete this; - return cRef; - } - - public: - //========================================================= - // IWinMDImport methods - //========================================================= - STDMETHODIMP IsScenarioWinMDExp(BOOL *pbResult) - { - if (pbResult == NULL) - return E_POINTER; - - *pbResult = m_pWinMDAdapter->IsScenarioWinMDExp(); - return S_OK; - } - - STDMETHODIMP IsRuntimeClassImplementation(mdTypeDef tkTypeDef, BOOL *pbResult) - { - if (pbResult == NULL) - return E_POINTER; - - return m_pWinMDAdapter->IsRuntimeClassImplementation(tkTypeDef, pbResult); - } - - //========================================================= - // IMetaDataImport methods - //========================================================= - STDMETHODIMP_(void) CloseEnum(HCORENUM hEnum) - { - m_pRawImport->CloseEnum(hEnum); - } - - STDMETHODIMP CountEnum(HCORENUM hEnum, ULONG *pulCount) - { - _ASSERTE(pulCount != NULL); // Crash on NULL pulCount (just like real RegMeta) - if (hEnum != NULL) - { - HENUMInternal *henuminternal = static_cast(hEnum); - // Special case: We hijack MethodImpl enum's - if (henuminternal->m_tkKind == (TBL_MethodImpl << 24)) - { - *pulCount = henuminternal->m_ulCount / 2; // MethodImpl enum's are weird - their entries are body/decl pairs so the internal count is twice the number the caller wants to see. - return S_OK; - } - } - - return m_pRawImport->CountEnum(hEnum, pulCount); - } - - STDMETHODIMP ResetEnum(HCORENUM hEnum, ULONG ulPos) - { - return m_pRawImport->ResetEnum(hEnum, ulPos); - } - - STDMETHODIMP EnumTypeDefs(HCORENUM *phEnum, mdTypeDef rTypeDefs[], - ULONG cMax, ULONG *pcTypeDefs) - { - return m_pRawImport->EnumTypeDefs(phEnum, rTypeDefs, cMax, pcTypeDefs); - } - - STDMETHODIMP EnumInterfaceImpls(HCORENUM *phEnum, mdTypeDef td, - mdInterfaceImpl rImpls[], ULONG cMax, - ULONG* pcImpls) - { - return m_pRawImport->EnumInterfaceImpls(phEnum, td, rImpls, cMax, pcImpls); - } - - STDMETHODIMP EnumTypeRefs(HCORENUM *phEnum, mdTypeRef rTypeRefs[], - ULONG cMax, ULONG* pcTypeRefs) - { - // No trick needed: a previous call to EnumTypeRefs must have already taken care of the - // extra type refs. - return m_pRawImport->EnumTypeRefs(phEnum, rTypeRefs, cMax, pcTypeRefs); - } - - STDMETHODIMP FindTypeDefByName( // S_OK or error. - LPCWSTR wszTypeDef, // [IN] Name of the Type. - mdToken tkEnclosingClass, // [IN] TypeDef/TypeRef for Enclosing class. - mdTypeDef *ptd) // [OUT] Put the TypeDef token here. - { - if (wszTypeDef == NULL) // E_INVALIDARG on NULL szTypeDef (just like real RegMeta) - return E_INVALIDARG; - _ASSERTE(ptd != NULL); // AV on NULL ptd (just like real RegMeta) - *ptd = mdTypeDefNil; - - LPUTF8 szFullName; - LPCUTF8 szNamespace; - LPCUTF8 szName; - // Convert the name to UTF8. - UTF8STR(wszTypeDef, szFullName); - ns::SplitInline(szFullName, szNamespace, szName); - - return m_pWinMDAdapter->FindTypeDef(szNamespace, szName, tkEnclosingClass, ptd); - } - - - STDMETHODIMP GetScopeProps( // S_OK or error. - __out_ecount_part_opt(cchName, *pchName) - LPWSTR szName, // [OUT] Put the name here. - ULONG cchName, // [IN] Size of name buffer in wide chars. - ULONG *pchName, // [OUT] Put size of name (wide chars) here. - GUID *pmvid) // [OUT, OPTIONAL] Put MVID here. - { - // Returns error code from name filling (may be CLDB_S_TRUNCTATION) - return m_pRawImport->GetScopeProps(szName, cchName, pchName, pmvid); - } - - - STDMETHODIMP GetModuleFromScope( // S_OK. - mdModule *pmd) // [OUT] Put mdModule token here. - { - return m_pRawImport->GetModuleFromScope(pmd); - } - - - STDMETHODIMP GetTypeDefProps( // S_OK or error. - mdTypeDef td, // [IN] TypeDef token for inquiry. - __out_ecount_part_opt(cchTypeDef, *pchTypeDef) - LPWSTR szTypeDef, // [OUT] Put name here. - ULONG cchTypeDef, // [IN] size of name buffer in wide chars. - ULONG *pchTypeDef, // [OUT] put size of name (wide chars) here. - DWORD *pdwTypeDefFlags, // [OUT] Put flags here. - mdToken *ptkExtends) // [OUT] Put base class TypeDef/TypeRef here. - { - HRESULT hr; - LPCSTR szNamespace; - LPCSTR szName; - if (!IsValidNonNilToken(td, mdtTypeDef)) - { - // Idiosyncractic edge cases - delegate straight through to inherit the correct idiosyncractic edge results - return m_pRawImport->GetTypeDefProps(td, szTypeDef, cchTypeDef, pchTypeDef, pdwTypeDefFlags, ptkExtends); - } - IfFailRet(m_pWinMDAdapter->GetTypeDefProps(td, &szNamespace, &szName, pdwTypeDefFlags, ptkExtends)); - // Returns error code from name filling (may be CLDB_S_TRUNCTATION) - return DeliverUtf8NamespaceAndName(szNamespace, szName, szTypeDef, cchTypeDef, pchTypeDef); - } - - - STDMETHODIMP GetInterfaceImplProps( // S_OK or error. - mdInterfaceImpl iiImpl, // [IN] InterfaceImpl token. - mdTypeDef *pClass, // [OUT] Put implementing class token here. - mdToken *ptkIface) // [OUT] Put implemented interface token here. - { - return m_pRawImport->GetInterfaceImplProps(iiImpl, pClass, ptkIface); - } - - - STDMETHODIMP GetTypeRefProps( // S_OK or error. - mdTypeRef tr, // [IN] TypeRef token. - mdToken *ptkResolutionScope, // [OUT] Resolution scope, ModuleRef or AssemblyRef. - __out_ecount_part_opt(cchName, *pchName) - LPWSTR szName, // [OUT] Name of the TypeRef. - ULONG cchName, // [IN] Size of buffer. - ULONG *pchName) // [OUT] Size of Name. - { - HRESULT hr; - if (!IsValidNonNilToken(tr, mdtTypeRef)) - { - // Idiosyncratic edge cases - delegate straight through to inherit the correct idiosyncratic edge result - return m_pRawImport->GetTypeRefProps(tr, ptkResolutionScope, szName, cchName, pchName); - } - - LPCUTF8 szUtf8Namespace; - LPCUTF8 szUtf8Name; - mdToken tkResolutionScope; - IfFailRet(CommonGetTypeRefProps(tr, &szUtf8Namespace, &szUtf8Name, &tkResolutionScope)); - if (ptkResolutionScope != NULL) - { - *ptkResolutionScope = tkResolutionScope; - } - // Returns error code from name filling (may be CLDB_S_TRUNCTATION) - return DeliverUtf8NamespaceAndName(szUtf8Namespace, szUtf8Name, szName, cchName, pchName); - } - - - STDMETHODIMP ResolveTypeRef(mdTypeRef tr, REFIID riid, IUnknown **ppIScope, mdTypeDef *ptd) - { - WINMD_COMPAT_ASSERT("IMetaDataImport::ResolveTypeRef() not supported on .winmd files."); - return E_NOTIMPL; - } - - - STDMETHODIMP EnumMembers( // S_OK, S_FALSE, or error. - HCORENUM *phEnum, // [IN|OUT] Pointer to the enum. - mdTypeDef cl, // [IN] TypeDef to scope the enumeration. - mdToken rMembers[], // [OUT] Put MemberDefs here. - ULONG cMax, // [IN] Max MemberDefs to put. - ULONG *pcTokens) // [OUT] Put # put here. - { - return m_pRawImport->EnumMembers(phEnum, cl, rMembers, cMax, pcTokens); - } - - - STDMETHODIMP EnumMembersWithName( // S_OK, S_FALSE, or error. - HCORENUM *phEnum, // [IN|OUT] Pointer to the enum. - mdTypeDef cl, // [IN] TypeDef to scope the enumeration. - LPCWSTR szName, // [IN] Limit results to those with this name. - mdToken rMembers[], // [OUT] Put MemberDefs here. - ULONG cMax, // [IN] Max MemberDefs to put. - ULONG *pcTokens) // [OUT] Put # put here. - { - return m_pRawImport->EnumMembersWithName(phEnum, cl, szName, rMembers, cMax, pcTokens); - } - - - STDMETHODIMP EnumMethods( // S_OK, S_FALSE, or error. - HCORENUM *phEnum, // [IN|OUT] Pointer to the enum. - mdTypeDef cl, // [IN] TypeDef to scope the enumeration. - mdMethodDef rMethods[], // [OUT] Put MethodDefs here. - ULONG cMax, // [IN] Max MethodDefs to put. - ULONG *pcTokens) // [OUT] Put # put here. - { - return m_pRawImport->EnumMethods(phEnum, cl, rMethods, cMax, pcTokens); - } - - - STDMETHODIMP EnumMethodsWithName( // S_OK, S_FALSE, or error. - HCORENUM *phEnum, // [IN|OUT] Pointer to the enum. - mdTypeDef cl, // [IN] TypeDef to scope the enumeration. - LPCWSTR szName, // [IN] Limit results to those with this name. - mdMethodDef rMethods[], // [OU] Put MethodDefs here. - ULONG cMax, // [IN] Max MethodDefs to put. - ULONG *pcTokens) // [OUT] Put # put here. - { - return m_pRawImport->EnumMethodsWithName(phEnum, cl, szName, rMethods, cMax, pcTokens); - } - - - STDMETHODIMP EnumFields( // S_OK, S_FALSE, or error. - HCORENUM *phEnum, // [IN|OUT] Pointer to the enum. - mdTypeDef cl, // [IN] TypeDef to scope the enumeration. - mdFieldDef rFields[], // [OUT] Put FieldDefs here. - ULONG cMax, // [IN] Max FieldDefs to put. - ULONG *pcTokens) // [OUT] Put # put here. - { - return m_pRawImport->EnumFields(phEnum, cl, rFields, cMax, pcTokens); - } - - - STDMETHODIMP EnumFieldsWithName( // S_OK, S_FALSE, or error. - HCORENUM *phEnum, // [IN|OUT] Pointer to the enum. - mdTypeDef cl, // [IN] TypeDef to scope the enumeration. - LPCWSTR szName, // [IN] Limit results to those with this name. - mdFieldDef rFields[], // [OUT] Put MemberDefs here. - ULONG cMax, // [IN] Max MemberDefs to put. - ULONG *pcTokens) // [OUT] Put # put here. - { - return m_pRawImport->EnumFieldsWithName(phEnum, cl, szName, rFields, cMax, pcTokens); - } - - - - STDMETHODIMP EnumParams( // S_OK, S_FALSE, or error. - HCORENUM *phEnum, // [IN|OUT] Pointer to the enum. - mdMethodDef mb, // [IN] MethodDef to scope the enumeration. - mdParamDef rParams[], // [OUT] Put ParamDefs here. - ULONG cMax, // [IN] Max ParamDefs to put. - ULONG *pcTokens) // [OUT] Put # put here. - { - return m_pRawImport->EnumParams(phEnum, mb, rParams, cMax, pcTokens); - } - - - STDMETHODIMP EnumMemberRefs( // S_OK, S_FALSE, or error. - HCORENUM *phEnum, // [IN|OUT] Pointer to the enum. - mdToken tkParent, // [IN] Parent token to scope the enumeration. - mdMemberRef rMemberRefs[], // [OUT] Put MemberRefs here. - ULONG cMax, // [IN] Max MemberRefs to put. - ULONG *pcTokens) // [OUT] Put # put here. - { - return m_pRawImport->EnumMemberRefs(phEnum, tkParent, rMemberRefs, cMax, pcTokens); - } - - - STDMETHODIMP EnumMethodImpls( // S_OK, S_FALSE, or error - HCORENUM *phEnum, // [IN|OUT] Pointer to the enum. - mdTypeDef td, // [IN] TypeDef to scope the enumeration. - mdToken rMethodBody[], // [OUT] Put Method Body tokens here. - mdToken rMethodDecl[], // [OUT] Put Method Declaration tokens here. - ULONG cMax, // [IN] Max tokens to put. - ULONG *pcTokens) // [OUT] Put # put here. - { - // Note: This wrapper emulates the underlying RegMeta's parameter validation semantics: - // Pass a bad phEnum: Instant AV - // Pass out of range typedef: returns S_FALSE (i.e. generates empty list) - // Pass non-typedef: returns S_FALSE with assert - // Pass bad output ptr for bodies or decls, AV - // Pass bad output ptr for pcTokens, AV (but NULL is allowed.) - - HRESULT hr; - HENUMInternal **ppmdEnum = reinterpret_cast (phEnum); - HENUMInternal *pEnum = *ppmdEnum; - - if ( pEnum == 0 ) - { - // Create the enumerator, DynamicArrayEnum does not use the token type. - IfFailGo( HENUMInternal::CreateDynamicArrayEnum( (TBL_MethodImpl << 24), &pEnum) ); - IfFailGo( m_pWinMDAdapter->AddMethodImplsToEnum(td, pEnum)); - // set the output parameter - *ppmdEnum = pEnum; - } - - // fill the output token buffer - hr = HENUMInternal::EnumWithCount(pEnum, cMax, rMethodBody, rMethodDecl, pcTokens); - - ErrExit: - HENUMInternal::DestroyEnumIfEmpty(ppmdEnum); - return hr; - } - - - STDMETHODIMP EnumPermissionSets( // S_OK, S_FALSE, or error. - HCORENUM *phEnum, // [IN|OUT] Pointer to the enum. - mdToken tk, // [IN] if !NIL, token to scope the enumeration. - DWORD dwActions, // [IN] if !0, return only these actions. - mdPermission rPermission[], // [OUT] Put Permissions here. - ULONG cMax, // [IN] Max Permissions to put. - ULONG *pcTokens) // [OUT] Put # put here. - { - return m_pRawImport->EnumPermissionSets(phEnum, tk, dwActions, rPermission, cMax, pcTokens); - } - - - STDMETHODIMP FindMember( - mdTypeDef td, // [IN] given typedef - LPCWSTR szName, // [IN] member name - PCCOR_SIGNATURE pvSigBlob, // [IN] point to a blob value of CLR signature - ULONG cbSigBlob, // [IN] count of bytes in the signature blob - mdToken *pmb) // [OUT] matching memberdef - { - HRESULT hr = FindMethod( - td, - szName, - pvSigBlob, - cbSigBlob, - pmb); - - if (hr == CLDB_E_RECORD_NOTFOUND) - { - // now try field table - hr = FindField( - td, - szName, - pvSigBlob, - cbSigBlob, - pmb); - } - - return hr; - } - - - STDMETHODIMP FindMethod( - mdTypeDef td, // [IN] given typedef - LPCWSTR szName, // [IN] member name - PCCOR_SIGNATURE pvSigBlob, // [IN] point to a blob value of CLR signature - ULONG cbSigBlob, // [IN] count of bytes in the signature blob - mdMethodDef *pmb) // [OUT] matching memberdef - { - if (pvSigBlob == NULL || cbSigBlob == 0) - { - // if signature matching is not needed, we can delegate to the underlying implementation - return m_pRawImport->FindMethod(td, szName, pvSigBlob, cbSigBlob, pmb); - } - - // The following code emulates RegMeta::FindMethod. We cannot call the underlying - // implementation because we need to compare pvSigBlob to reinterpreted signatures. - HRESULT hr = S_OK; - HCORENUM hEnum = NULL; - - CQuickBytes qbSig; // holds non-varargs signature - CQuickArray rName; - - if (szName == NULL || pmb == NULL) - IfFailGo(E_INVALIDARG); - - *pmb = mdMethodDefNil; - - { - // check to see if this is a vararg signature - PCCOR_SIGNATURE pvSigTemp = pvSigBlob; - if (isCallConv(CorSigUncompressCallingConv(pvSigTemp), IMAGE_CEE_CS_CALLCONV_VARARG)) - { - // Get the fixed part of VARARG signature - IfFailGo(_GetFixedSigOfVarArg(pvSigBlob, cbSigBlob, &qbSig, &cbSigBlob)); - pvSigBlob = (PCCOR_SIGNATURE) qbSig.Ptr(); - } - } - - // now iterate all methods in td and compare name and signature - IfNullGo(rName.AllocNoThrow(wcslen(szName) + 1)); - - mdMethodDef md; - ULONG count; - while ((hr = EnumMethods(&hEnum, td, &md, 1, &count)) == S_OK) - { - PCCOR_SIGNATURE pvMethodSigBlob; - ULONG cbMethodSigBlob; - ULONG chMethodName; - DWORD dwMethodAttr; - - IfFailGo(GetMethodProps(md, NULL, rName.Ptr(), (ULONG)rName.Size(), &chMethodName, &dwMethodAttr, &pvMethodSigBlob, &cbMethodSigBlob, NULL, NULL)); - - if (chMethodName == rName.Size() && wcscmp(szName, rName.Ptr()) == 0) - { - // we have a name match, check signature - if (cbSigBlob != cbMethodSigBlob || memcmp(pvSigBlob, pvMethodSigBlob, cbSigBlob) != 0) - continue; - - // ignore PrivateScope methods - if (IsMdPrivateScope(dwMethodAttr)) - continue; - - // we found the method - *pmb = md; - goto ErrExit; - } - } - IfFailGo(hr); - hr = CLDB_E_RECORD_NOTFOUND; - - ErrExit: - if (hEnum != NULL) - CloseEnum(hEnum); - - return hr; - } - - - STDMETHODIMP FindField( - mdTypeDef td, // [IN] given typedef - LPCWSTR szName, // [IN] member name - PCCOR_SIGNATURE pvSigBlob, // [IN] point to a blob value of CLR signature - ULONG cbSigBlob, // [IN] count of bytes in the signature blob - mdFieldDef *pmb) // [OUT] matching memberdef - { - if (pvSigBlob == NULL || cbSigBlob == 0) - { - // if signature matching is not needed, we can delegate to the underlying implementation - return m_pRawImport->FindField(td, szName, pvSigBlob, cbSigBlob, pmb); - } - - // The following code emulates RegMeta::FindField. We cannot call the underlying - // implementation because we need to compare pvSigBlob to reinterpreted signatures. - HRESULT hr = S_OK; - HCORENUM hEnum = NULL; - - CQuickArray rName; - - if (szName == NULL || pmb == NULL) - IfFailGo(E_INVALIDARG); - - *pmb = mdFieldDefNil; - - // now iterate all fields in td and compare name and signature - IfNullGo(rName.AllocNoThrow(wcslen(szName) + 1)); - - mdFieldDef fd; - ULONG count; - while ((hr = EnumFields(&hEnum, td, &fd, 1, &count)) == S_OK) - { - PCCOR_SIGNATURE pvFieldSigBlob; - ULONG cbFieldSigBlob; - ULONG chFieldName; - DWORD dwFieldAttr; - - IfFailGo(GetFieldProps(fd, NULL, rName.Ptr(), (ULONG)rName.Size(), &chFieldName, &dwFieldAttr, &pvFieldSigBlob, &cbFieldSigBlob, NULL, NULL, NULL)); - - if (chFieldName == rName.Size() && wcscmp(szName, rName.Ptr()) == 0) - { - // we have a name match, check signature - if (cbSigBlob != cbFieldSigBlob || memcmp(pvSigBlob, pvFieldSigBlob, cbSigBlob) != 0) - continue; - - // ignore PrivateScope fields - if (IsFdPrivateScope(dwFieldAttr)) - continue; - - // we found the field - *pmb = fd; - goto ErrExit; - } - } - IfFailGo(hr); - hr = CLDB_E_RECORD_NOTFOUND; - - ErrExit: - if (hEnum != NULL) - CloseEnum(hEnum); - - return hr; - } - - - STDMETHODIMP FindMemberRef( - mdTypeRef td, // [IN] given typeRef - LPCWSTR szName, // [IN] member name - PCCOR_SIGNATURE pvSigBlob, // [IN] point to a blob value of CLR signature - ULONG cbSigBlob, // [IN] count of bytes in the signature blob - mdMemberRef *pmr) // [OUT] matching memberref - { - if (pvSigBlob == NULL || cbSigBlob == 0) - { - // if signature matching is not needed, we can delegate to the underlying implementation - return m_pRawImport->FindMemberRef(td, szName, pvSigBlob, cbSigBlob, pmr); - } - - // The following code emulates RegMeta::FindMemberRef. We cannot call the underlying - // implementation because we need to compare pvSigBlob to reinterpreted signatures. - HRESULT hr = S_OK; - HCORENUM hEnum = NULL; - - CQuickArray rName; - - if (szName == NULL || pmr == NULL) - IfFailGo(CLDB_E_RECORD_NOTFOUND); - - *pmr = mdMemberRefNil; - - // now iterate all members in td and compare name and signature - IfNullGo(rName.AllocNoThrow(wcslen(szName) + 1)); - - mdMemberRef rd; - ULONG count; - while ((hr = EnumMemberRefs(&hEnum, td, &rd, 1, &count)) == S_OK) - { - PCCOR_SIGNATURE pvMemberSigBlob; - ULONG cbMemberSigBlob; - ULONG chMemberName; - - IfFailGo(GetMemberRefProps(rd, NULL, rName.Ptr(), (ULONG)rName.Size(), &chMemberName, &pvMemberSigBlob, &cbMemberSigBlob)); - - if (chMemberName == rName.Size() && wcscmp(szName, rName.Ptr()) == 0) - { - // we have a name match, check signature - if (cbSigBlob != cbMemberSigBlob || memcmp(pvSigBlob, pvMemberSigBlob, cbSigBlob) != 0) - continue; - - // we found the member - *pmr = rd; - goto ErrExit; - } - } - IfFailGo(hr); - hr = CLDB_E_RECORD_NOTFOUND; - - ErrExit: - if (hEnum != NULL) - CloseEnum(hEnum); - - return hr; - } - - - STDMETHODIMP GetMethodProps( - mdMethodDef mb, // The method for which to get props. - mdTypeDef *pClass, // Put method's class here. - __out_ecount_part_opt(cchMethod, *pchMethod) - LPWSTR szMethod, // Put method's name here. - ULONG cchMethod, // Size of szMethod buffer in wide chars. - ULONG *pchMethod, // Put actual size here - DWORD *pdwAttr, // Put flags here. - PCCOR_SIGNATURE *ppvSigBlob, // [OUT] point to the blob value of meta data - ULONG *pcbSigBlob, // [OUT] actual size of signature blob - ULONG *pulCodeRVA, // [OUT] codeRVA - DWORD *pdwImplFlags) // [OUT] Impl. Flags - { - HRESULT hr; - HRESULT hrNameTruncation; - if (!IsValidNonNilToken(mb, mdtMethodDef)) - { - // Idiosyncratic edge cases - delegate straight through to inherit the correct idiosyncratic edge result - return m_pRawImport->GetMethodProps(mb, pClass, szMethod, cchMethod, pchMethod, pdwAttr, ppvSigBlob, pcbSigBlob, pulCodeRVA, pdwImplFlags); - } - - ULONG cbOrigSigBlob = (ULONG)(-1); - PCCOR_SIGNATURE pOrigSig = NULL; - IfFailRet(hrNameTruncation = m_pRawImport->GetMethodProps(mb, pClass, szMethod, cchMethod, pchMethod, pdwAttr, &pOrigSig, &cbOrigSigBlob, pulCodeRVA, pdwImplFlags)); - - IfFailRet((m_pWinMDAdapter->GetSignatureForToken( - mb, - &pOrigSig, // ppOrigSig - &cbOrigSigBlob, // pcbOrigSig - ppvSigBlob, - pcbSigBlob, - m_pRawImport))); - - LPCSTR szNewName = NULL; - IfFailRet(m_pWinMDAdapter->ModifyMethodProps(mb, pdwAttr, pdwImplFlags, pulCodeRVA, &szNewName)); - if (szNewName != NULL) - { - // We want to return name truncation status from the method that really fills the output buffer, rewrite the previous value - IfFailRet(hrNameTruncation = DeliverUtf8String(szNewName, szMethod, cchMethod, pchMethod)); - } - - // Return the success code from name filling (S_OK or CLDB_S_TRUNCATION) - return hrNameTruncation; - } - - - STDMETHODIMP GetMemberRefProps( // S_OK or error. - mdMemberRef mr, // [IN] given memberref - mdToken *ptk, // [OUT] Put classref or classdef here. - __out_ecount_part_opt(cchMember, *pchMember) - LPWSTR szMember, // [OUT] buffer to fill for member's name - ULONG cchMember, // [IN] the count of char of szMember - ULONG *pchMember, // [OUT] actual count of char in member name - PCCOR_SIGNATURE *ppvSigBlob, // [OUT] point to meta data blob value - ULONG *pbSig) // [OUT] actual size of signature blob - { - HRESULT hr = S_OK; - HRESULT hrNameTruncation; - - ULONG cbOrigSigBlob = (ULONG)(-1); - PCCOR_SIGNATURE pOrigSig = NULL; - IfFailRet(hrNameTruncation = m_pRawImport->GetMemberRefProps(mr, ptk, szMember, cchMember, pchMember, &pOrigSig, &cbOrigSigBlob)); - LPCSTR szNewName = NULL; - IfFailRet(m_pWinMDAdapter->ModifyMemberProps(mr, NULL, NULL, NULL, &szNewName)); - IfFailRet((m_pWinMDAdapter->GetSignatureForToken( - mr, - &pOrigSig, // ppOrigSig - &cbOrigSigBlob, // pcbOrigSig - ppvSigBlob, - pbSig, - m_pRawImport))); - if (szNewName != NULL) - { - // We want to return name truncation status from the method that really fills the output buffer, rewrite the previous value - IfFailRet(hrNameTruncation = DeliverUtf8String(szNewName, szMember, cchMember, pchMember)); - } - // Return the success code from name filling (S_OK or CLDB_S_TRUNCATION) - return hrNameTruncation; - } - - - STDMETHODIMP EnumProperties( // S_OK, S_FALSE, or error. - HCORENUM *phEnum, // [IN|OUT] Pointer to the enum. - mdTypeDef td, // [IN] TypeDef to scope the enumeration. - mdProperty rProperties[], // [OUT] Put Properties here. - ULONG cMax, // [IN] Max properties to put. - ULONG *pcProperties) // [OUT] Put # put here. - { - return m_pRawImport->EnumProperties(phEnum, td, rProperties, cMax, pcProperties); - } - - - STDMETHODIMP EnumEvents( // S_OK, S_FALSE, or error. - HCORENUM *phEnum, // [IN|OUT] Pointer to the enum. - mdTypeDef td, // [IN] TypeDef to scope the enumeration. - mdEvent rEvents[], // [OUT] Put events here. - ULONG cMax, // [IN] Max events to put. - ULONG *pcEvents) // [OUT] Put # put here. - { - return m_pRawImport->EnumEvents(phEnum, td, rEvents, cMax, pcEvents); - } - - - STDMETHODIMP GetEventProps( // S_OK, S_FALSE, or error. - mdEvent ev, // [IN] event token - mdTypeDef *pClass, // [OUT] typedef containing the event declarion. - LPCWSTR szEvent, // [OUT] Event name - ULONG cchEvent, // [IN] the count of wchar of szEvent - ULONG *pchEvent, // [OUT] actual count of wchar for event's name - DWORD *pdwEventFlags, // [OUT] Event flags. - mdToken *ptkEventType, // [OUT] EventType class - mdMethodDef *pmdAddOn, // [OUT] AddOn method of the event - mdMethodDef *pmdRemoveOn, // [OUT] RemoveOn method of the event - mdMethodDef *pmdFire, // [OUT] Fire method of the event - mdMethodDef rmdOtherMethod[], // [OUT] other method of the event - ULONG cMax, // [IN] size of rmdOtherMethod - ULONG *pcOtherMethod) // [OUT] total number of other method of this event - { - // Returns error code from name filling (may be CLDB_S_TRUNCTATION) - return m_pRawImport->GetEventProps(ev, pClass, szEvent, cchEvent, pchEvent, pdwEventFlags, ptkEventType, pmdAddOn, pmdRemoveOn, pmdFire, rmdOtherMethod, cMax, pcOtherMethod); - } - - - STDMETHODIMP EnumMethodSemantics( // S_OK, S_FALSE, or error. - HCORENUM *phEnum, // [IN|OUT] Pointer to the enum. - mdMethodDef mb, // [IN] MethodDef to scope the enumeration. - mdToken rEventProp[], // [OUT] Put Event/Property here. - ULONG cMax, // [IN] Max properties to put. - ULONG *pcEventProp) // [OUT] Put # put here. - { - return m_pRawImport->EnumMethodSemantics(phEnum, mb, rEventProp, cMax, pcEventProp); - } - - STDMETHODIMP GetMethodSemantics( // S_OK, S_FALSE, or error. - mdMethodDef mb, // [IN] method token - mdToken tkEventProp, // [IN] event/property token. - DWORD *pdwSemanticsFlags) // [OUT] the role flags for the method/propevent pair - { - return m_pRawImport->GetMethodSemantics(mb, tkEventProp, pdwSemanticsFlags); - } - - - STDMETHODIMP GetClassLayout( - mdTypeDef td, // [IN] give typedef - DWORD *pdwPackSize, // [OUT] 1, 2, 4, 8, or 16 - COR_FIELD_OFFSET rFieldOffset[], // [OUT] field offset array - ULONG cMax, // [IN] size of the array - ULONG *pcFieldOffset, // [OUT] needed array size - ULONG *pulClassSize) // [OUT] the size of the class - { - return m_pRawImport->GetClassLayout(td, pdwPackSize, rFieldOffset, cMax, pcFieldOffset, pulClassSize); - } - - - STDMETHODIMP GetFieldMarshal( - mdToken tk, // [IN] given a field's memberdef - PCCOR_SIGNATURE *ppvNativeType, // [OUT] native type of this field - ULONG *pcbNativeType) // [OUT] the count of bytes of *ppvNativeType - { - return m_pRawImport->GetFieldMarshal(tk, ppvNativeType, pcbNativeType); - } - - - STDMETHODIMP GetRVA( // S_OK or error. - mdToken tk, // Member for which to set offset - ULONG *pulCodeRVA, // The offset - DWORD *pdwImplFlags) // the implementation flags - { - HRESULT hr; - if (!IsValidNonNilToken(tk, mdtMethodDef)) - { - // Idiosyncratic edge cases - delegate straight through to inherit the correct idiosyncratic edge result - return m_pRawImport->GetRVA(tk, pulCodeRVA, pdwImplFlags); - } - - IfFailRet(m_pRawImport->GetRVA(tk, pulCodeRVA, pdwImplFlags)); - IfFailRet(m_pWinMDAdapter->ModifyMethodProps(tk, NULL, pdwImplFlags, pulCodeRVA, NULL)); - return hr; - } - - - STDMETHODIMP GetPermissionSetProps( - mdPermission pm, // [IN] the permission token. - DWORD *pdwAction, // [OUT] CorDeclSecurity. - void const **ppvPermission, // [OUT] permission blob. - ULONG *pcbPermission) // [OUT] count of bytes of pvPermission. - { - return m_pRawImport->GetPermissionSetProps(pm, pdwAction, ppvPermission, pcbPermission); - } - - - STDMETHODIMP GetSigFromToken( // S_OK or error. - mdSignature mdSig, // [IN] Signature token. - PCCOR_SIGNATURE *ppvSig, // [OUT] return pointer to token. - ULONG *pcbSig) // [OUT] return size of signature. - { - // mdSignature is not part of public WinMD surface, so it does not need signature rewriting - return m_pRawImport->GetSigFromToken(mdSig, ppvSig, pcbSig); - } - - STDMETHODIMP GetModuleRefProps( // S_OK or error. - mdModuleRef mur, // [IN] moduleref token. - __out_ecount_part_opt(cchName, *pchName) - LPWSTR szName, // [OUT] buffer to fill with the moduleref name. - ULONG cchName, // [IN] size of szName in wide characters. - ULONG *pchName) // [OUT] actual count of characters in the name. - { - // Returns error code from name filling (may be CLDB_S_TRUNCTATION) - return m_pRawImport->GetModuleRefProps(mur, szName, cchName, pchName); - } - - - STDMETHODIMP EnumModuleRefs( // S_OK or error. - HCORENUM *phEnum, // [IN|OUT] pointer to the enum. - mdModuleRef rModuleRefs[], // [OUT] put modulerefs here. - ULONG cmax, // [IN] max memberrefs to put. - ULONG *pcModuleRefs) // [OUT] put # put here. - { - return m_pRawImport->EnumModuleRefs(phEnum, rModuleRefs, cmax, pcModuleRefs); - } - - - STDMETHODIMP GetTypeSpecFromToken( // S_OK or error. - mdTypeSpec typespec, // [IN] TypeSpec token. - PCCOR_SIGNATURE *ppvSig, // [OUT] return pointer to TypeSpec signature - ULONG *pcbSig) // [OUT] return size of signature. - { - return m_pWinMDAdapter->GetSignatureForToken( - typespec, - NULL, // ppOrigSig - NULL, // pcbOrigSig - ppvSig, - pcbSig, - m_pRawImport); - } - - - STDMETHODIMP GetNameFromToken( // Not Recommended! May be removed! - mdToken tk, // [IN] Token to get name from. Must have a name. - MDUTF8CSTR *pszUtf8NamePtr) // [OUT] Return pointer to UTF8 name in heap. - { - HRESULT hr; - - if (!IsValidNonNilToken(tk, mdtTypeRef)) - { - // Handle corner error case - IfFailGo(m_pRawImport->GetNameFromToken(tk, pszUtf8NamePtr)); - } - else - { - IfFailGo(m_pWinMDAdapter->GetTypeRefProps(tk, NULL, pszUtf8NamePtr, NULL)); - } - - ErrExit: - return hr; - } - - - STDMETHODIMP EnumUnresolvedMethods( // S_OK, S_FALSE, or error. - HCORENUM *phEnum, // [IN|OUT] Pointer to the enum. - mdToken rMethods[], // [OUT] Put MemberDefs here. - ULONG cMax, // [IN] Max MemberDefs to put. - ULONG *pcTokens) // [OUT] Put # put here. - { - return m_pRawImport->EnumUnresolvedMethods(phEnum, rMethods, cMax, pcTokens); - } - - - STDMETHODIMP GetUserString( // S_OK or error. - mdString stk, // [IN] String token. - __out_ecount_part_opt(cchString, *pchString) - LPWSTR szString, // [OUT] Copy of string. - ULONG cchString, // [IN] Max chars of room in szString. - ULONG *pchString) // [OUT] How many chars in actual string. - { - // Returns error code from name filling (may be CLDB_S_TRUNCTATION) - return m_pRawImport->GetUserString(stk, szString, cchString, pchString); - } - - - STDMETHODIMP GetPinvokeMap( // S_OK or error. - mdToken tk, // [IN] FieldDef or MethodDef. - DWORD *pdwMappingFlags, // [OUT] Flags used for mapping. - __out_ecount_part_opt(cchImportName, *pchImportName) - LPWSTR szImportName, // [OUT] Import name. - ULONG cchImportName, // [IN] Size of the name buffer. - ULONG *pchImportName, // [OUT] Actual number of characters stored. - mdModuleRef *pmrImportDLL) // [OUT] ModuleRef token for the target DLL. - { - // Returns error code from name filling (may be CLDB_S_TRUNCTATION) - return m_pRawImport->GetPinvokeMap(tk, pdwMappingFlags, szImportName, cchImportName, pchImportName, pmrImportDLL); - } - - - STDMETHODIMP EnumSignatures( // S_OK or error. - HCORENUM *phEnum, // [IN|OUT] pointer to the enum. - mdSignature rSignatures[], // [OUT] put signatures here. - ULONG cmax, // [IN] max signatures to put. - ULONG *pcSignatures) // [OUT] put # put here. - { - return m_pRawImport->EnumSignatures(phEnum, rSignatures, cmax, pcSignatures); - } - - - STDMETHODIMP EnumTypeSpecs( // S_OK or error. - HCORENUM *phEnum, // [IN|OUT] pointer to the enum. - mdTypeSpec rTypeSpecs[], // [OUT] put TypeSpecs here. - ULONG cmax, // [IN] max TypeSpecs to put. - ULONG *pcTypeSpecs) // [OUT] put # put here. - { - return m_pRawImport->EnumTypeSpecs(phEnum, rTypeSpecs, cmax, pcTypeSpecs); - } - - - STDMETHODIMP EnumUserStrings( // S_OK or error. - HCORENUM *phEnum, // [IN/OUT] pointer to the enum. - mdString rStrings[], // [OUT] put Strings here. - ULONG cmax, // [IN] max Strings to put. - ULONG *pcStrings) // [OUT] put # put here. - { - return m_pRawImport->EnumUserStrings(phEnum, rStrings, cmax, pcStrings); - } - - - STDMETHODIMP GetParamForMethodIndex( // S_OK or error. - mdMethodDef md, // [IN] Method token. - ULONG ulParamSeq, // [IN] Parameter sequence. - mdParamDef *ppd) // [IN] Put Param token here. - { - return m_pRawImport->GetParamForMethodIndex(md, ulParamSeq, ppd); - } - - - STDMETHODIMP EnumCustomAttributes( // S_OK or error. - HCORENUM *phEnum, // [IN, OUT] COR enumerator. - mdToken tk, // [IN] Token to scope the enumeration, 0 for all. - mdToken tkType, // [IN] Type of interest, 0 for all. - mdCustomAttribute rCustomAttributes[], // [OUT] Put custom attribute tokens here. - ULONG cMax, // [IN] Size of rCustomAttributes. - ULONG *pcCustomAttributes) // [OUT, OPTIONAL] Put count of token values here. - { - return m_pRawImport->EnumCustomAttributes(phEnum, tk, tkType, rCustomAttributes, cMax, pcCustomAttributes); - } - - - STDMETHODIMP GetCustomAttributeProps( // S_OK or error. - mdCustomAttribute cv, // [IN] CustomAttribute token. - mdToken *ptkObj, // [OUT, OPTIONAL] Put object token here. - mdToken *ptkType, // [OUT, OPTIONAL] Put AttrType token here. - void const **ppBlob, // [OUT, OPTIONAL] Put pointer to data here. - ULONG *pcbSize) // [OUT, OPTIONAL] Put size of date here. - { - HRESULT hr; - if (!IsValidNonNilToken(cv, mdtCustomAttribute)) - { - // Idiosyncratic edge cases - delegate straight through to inherit the correct idiosyncratic edge result - return m_pRawImport->GetCustomAttributeProps(cv, ptkObj, ptkType, ppBlob, pcbSize); - } - IfFailRet(m_pRawImport->GetCustomAttributeProps(cv, ptkObj, ptkType, NULL, NULL)); - IfFailRet(m_pWinMDAdapter->GetCustomAttributeBlob(cv, ppBlob, pcbSize)); - return hr; - } - - - STDMETHODIMP FindTypeRef( - mdToken tkResolutionScope, // [IN] ModuleRef, AssemblyRef or TypeRef. - LPCWSTR wzTypeName, // [IN] TypeRef Name. - mdTypeRef *ptr) // [OUT] matching TypeRef. - { - - HRESULT hr; - LPUTF8 szFullName; - LPCUTF8 szNamespace; - LPCUTF8 szName; - - _ASSERTE(wzTypeName && ptr); - *ptr = mdTypeRefNil; // AV if caller passes NULL: just like the real RegMeta. - - // Convert the name to UTF8. - PREFIX_ASSUME(wzTypeName != NULL); // caller might pass NULL, but they'll AV (just like the real RegMeta) - UTF8STR(wzTypeName, szFullName); - ns::SplitInline(szFullName, szNamespace, szName); - hr = m_pWinMDAdapter->FindTypeRef(szNamespace, szName, tkResolutionScope, ptr); - - return hr; - } - - - STDMETHODIMP GetMemberProps( - mdToken mb, // The member for which to get props. - mdTypeDef *pClass, // Put member's class here. - __out_ecount_part_opt(cchMember, *pchMember) - LPWSTR szMember, // Put member's name here. - ULONG cchMember, // Size of szMember buffer in wide chars. - ULONG *pchMember, // Put actual size here - DWORD *pdwAttr, // Put flags here. - PCCOR_SIGNATURE *ppvSigBlob, // [OUT] point to the blob value of meta data - ULONG *pcbSigBlob, // [OUT] actual size of signature blob - ULONG *pulCodeRVA, // [OUT] codeRVA - DWORD *pdwImplFlags, // [OUT] Impl. Flags - DWORD *pdwCPlusTypeFlag, // [OUT] flag for value type. selected ELEMENT_TYPE_* - UVCP_CONSTANT *ppValue, // [OUT] constant value - ULONG *pcchValue) // [OUT] size of constant string in chars, 0 for non-strings. - { - HRESULT hr; - HRESULT hrNameTruncation; - if (!IsValidNonNilToken(mb, mdtMethodDef) && !IsValidNonNilToken(mb, mdtFieldDef)) - { - // Idiosyncratic edge cases - delegate straight through to inherit the correct idiosyncratic edge result - return m_pRawImport->GetMemberProps(mb, pClass, szMember, cchMember, pchMember, pdwAttr, ppvSigBlob, pcbSigBlob, pulCodeRVA, pdwImplFlags, pdwCPlusTypeFlag, ppValue, pcchValue); - } - - PCCOR_SIGNATURE pOrigSig; - ULONG cbOrigSig; - - IfFailRet(hrNameTruncation = m_pRawImport->GetMemberProps(mb, pClass, szMember, cchMember, pchMember, pdwAttr, &pOrigSig, &cbOrigSig, pulCodeRVA, pdwImplFlags, pdwCPlusTypeFlag, ppValue, pcchValue)); - - LPCSTR szNewName = NULL; - IfFailRet(m_pWinMDAdapter->ModifyMemberProps(mb, pdwAttr, pdwImplFlags, pulCodeRVA, &szNewName)); - - if (IsValidNonNilToken(mb, mdtMethodDef)) - { - IfFailRet((m_pWinMDAdapter->GetSignatureForToken( - mb, - &pOrigSig, // ppOrigSig - &cbOrigSig, // pcbOrigSig - ppvSigBlob, - pcbSigBlob, - m_pRawImport))); - } - else if (IsValidNonNilToken(mb, mdtFieldDef)) - { - IfFailRet((m_pWinMDAdapter->GetSignatureForToken( - mb, - &pOrigSig, // ppOrigSig - &cbOrigSig, // pcbOrigSig - ppvSigBlob, - pcbSigBlob, - m_pRawImport))); - } - else - { - if (ppvSigBlob != NULL) - *ppvSigBlob = pOrigSig; - - if (pcbSigBlob != NULL) - *pcbSigBlob = cbOrigSig; - } - - if (szNewName != NULL) - { - // We want to return name truncation status from the method that really fills the output buffer, rewrite the previous value - IfFailRet(hrNameTruncation = DeliverUtf8String(szNewName, szMember, cchMember, pchMember)); - } - - // Return the success code from name filling (S_OK or CLDB_S_TRUNCATION) - return hrNameTruncation; - } - - - STDMETHODIMP GetFieldProps( - mdFieldDef mb, // The field for which to get props. - mdTypeDef *pClass, // Put field's class here. - __out_ecount_part_opt(cchField, *pchField) - LPWSTR szField, // Put field's name here. - ULONG cchField, // Size of szField buffer in wide chars. - ULONG *pchField, // Put actual size here - DWORD *pdwAttr, // Put flags here. - PCCOR_SIGNATURE *ppvSigBlob, // [OUT] point to the blob value of meta data - ULONG *pcbSigBlob, // [OUT] actual size of signature blob - DWORD *pdwCPlusTypeFlag, // [OUT] flag for value type. selected ELEMENT_TYPE_* - UVCP_CONSTANT *ppValue, // [OUT] constant value - ULONG *pcchValue) // [OUT] size of constant string in chars, 0 for non-strings. - { - HRESULT hr; - HRESULT hrNameTruncation; - - PCCOR_SIGNATURE pOrigSig; - ULONG cbOrigSig; - IfFailRet(hrNameTruncation = m_pRawImport->GetFieldProps(mb, pClass, szField, cchField, pchField, pdwAttr, &pOrigSig, &cbOrigSig, pdwCPlusTypeFlag, ppValue, pcchValue)); - - IfFailRet(m_pWinMDAdapter->ModifyFieldDefProps(mb, pdwAttr)); - IfFailRet((m_pWinMDAdapter->GetSignatureForToken( - mb, - &pOrigSig, - &cbOrigSig, - ppvSigBlob, - pcbSigBlob, - m_pRawImport))); - - // Return the success code from name filling (S_OK or CLDB_S_TRUNCATION) - return hrNameTruncation; - } - - - STDMETHODIMP GetPropertyProps( // S_OK, S_FALSE, or error. - mdProperty prop, // [IN] property token - mdTypeDef *pClass, // [OUT] typedef containing the property declarion. - LPCWSTR szProperty, // [OUT] Property name - ULONG cchProperty, // [IN] the count of wchar of szProperty - ULONG *pchProperty, // [OUT] actual count of wchar for property name - DWORD *pdwPropFlags, // [OUT] property flags. - PCCOR_SIGNATURE *ppvSig, // [OUT] property type. pointing to meta data internal blob - ULONG *pbSig, // [OUT] count of bytes in *ppvSig - DWORD *pdwCPlusTypeFlag, // [OUT] flag for value type. selected ELEMENT_TYPE_* - UVCP_CONSTANT *ppDefaultValue, // [OUT] constant value - ULONG *pcchDefaultValue, // [OUT] size of constant string in chars, 0 for non-strings. - mdMethodDef *pmdSetter, // [OUT] setter method of the property - mdMethodDef *pmdGetter, // [OUT] getter method of the property - mdMethodDef rmdOtherMethod[], // [OUT] other method of the property - ULONG cMax, // [IN] size of rmdOtherMethod - ULONG *pcOtherMethod) // [OUT] total number of other method of this property - { - HRESULT hr = S_OK; - HRESULT hrNameTruncation; - - ULONG cbOrigSigBlob = (ULONG)(-1); - PCCOR_SIGNATURE pOrigSig = NULL; - IfFailRet(hrNameTruncation = m_pRawImport->GetPropertyProps(prop, pClass, szProperty, cchProperty, pchProperty, pdwPropFlags, &pOrigSig, &cbOrigSigBlob, pdwCPlusTypeFlag, ppDefaultValue, pcchDefaultValue, pmdSetter, pmdGetter, rmdOtherMethod, cMax, pcOtherMethod)); - - IfFailRet((m_pWinMDAdapter->GetSignatureForToken( - prop, - &pOrigSig, // ppOrigSig - &cbOrigSigBlob, // pcbOrigSig - ppvSig, - pbSig, - m_pRawImport))); - // Return the success code from name filling (S_OK or CLDB_S_TRUNCATION) - return hrNameTruncation; - } - - - STDMETHODIMP GetParamProps( // S_OK or error. - mdParamDef tk, // [IN]The Parameter. - mdMethodDef *pmd, // [OUT] Parent Method token. - ULONG *pulSequence, // [OUT] Parameter sequence. - __out_ecount_part_opt(cchName, *pchName) - LPWSTR szName, // [OUT] Put name here. - ULONG cchName, // [OUT] Size of name buffer. - ULONG *pchName, // [OUT] Put actual size of name here. - DWORD *pdwAttr, // [OUT] Put flags here. - DWORD *pdwCPlusTypeFlag, // [OUT] Flag for value type. selected ELEMENT_TYPE_*. - UVCP_CONSTANT *ppValue, // [OUT] Constant value. - ULONG *pcchValue) // [OUT] size of constant string in chars, 0 for non-strings. - { - // Returns error code from name filling (may be CLDB_S_TRUNCTATION) - return m_pRawImport->GetParamProps(tk, pmd, pulSequence, szName, cchName, pchName, pdwAttr, pdwCPlusTypeFlag, ppValue, pcchValue); - } - - - STDMETHODIMP GetCustomAttributeByName( // S_OK or error. - mdToken tkObj, // [IN] Object with Custom Attribute. - LPCWSTR wszName, // [IN] Name of desired Custom Attribute. - const void **ppData, // [OUT] Put pointer to data here. - ULONG *pcbData) // [OUT] Put size of data here. - { - HRESULT hr; - if (wszName == NULL) - { - hr = S_FALSE; // Questionable response but maintains compatibility with RegMeta - } - else - { - MAKE_UTF8PTR_FROMWIDE_NOTHROW(szName, wszName); - IfNullGo(szName); - IfFailGo(CommonGetCustomAttributeByName(tkObj, szName, ppData, pcbData)); - } - ErrExit: - return hr; - } - - - STDMETHODIMP_(BOOL) IsValidToken( // True or False. - mdToken tk) // [IN] Given token. - { - mdToken tokenType = TypeFromToken(tk); - if (tokenType == mdtAssemblyRef) - return m_pWinMDAdapter->IsValidAssemblyRefToken(tk); - - return m_pRawImport->IsValidToken(tk); - } - - - STDMETHODIMP GetNestedClassProps( // S_OK or error. - mdTypeDef tdNestedClass, // [IN] NestedClass token. - mdTypeDef *ptdEnclosingClass) // [OUT] EnclosingClass token. - { - return m_pRawImport->GetNestedClassProps(tdNestedClass, ptdEnclosingClass); - } - - - STDMETHODIMP GetNativeCallConvFromSig( // S_OK or error. - void const *pvSig, // [IN] Pointer to signature. - ULONG cbSig, // [IN] Count of signature bytes. - ULONG *pCallConv) // [OUT] Put calling conv here (see CorPinvokemap). - { - return m_pRawImport->GetNativeCallConvFromSig(pvSig, cbSig, pCallConv); - } - - - STDMETHODIMP IsGlobal( // S_OK or error. - mdToken pd, // [IN] Type, Field, or Method token. - int *pbGlobal) // [OUT] Put 1 if global, 0 otherwise. - { - return m_pRawImport->IsGlobal(pd, pbGlobal); - } - - public: - - // ======================================================== - // IMetaDataWinMDImport methods - // ======================================================== - - // This method returns the RAW view of the metadata. Essentially removing the Adapter's projection support for the typeRef. - STDMETHODIMP GetUntransformedTypeRefProps( - mdTypeRef tr, // [IN] TypeRef token. - mdToken *ptkResolutionScope, // [OUT] Resolution scope, ModuleRef or AssemblyRef. - __out_ecount_part_opt(cchName, *pchName) - LPWSTR szName, // [OUT] Unprojected name of the TypeRef. - ULONG cchName, // [IN] Size of buffer. - ULONG *pchName) // [OUT] Size of Name. - { - // By-pass the call to the raw importer, removing the adapter layer. - return m_pRawImport->GetTypeRefProps(tr, ptkResolutionScope, szName, cchName, pchName); - } - - //========================================================= - // IMetaDataImport2 methods - //========================================================= - STDMETHODIMP EnumGenericParams( - HCORENUM *phEnum, // [IN|OUT] Pointer to the enum. - mdToken tk, // [IN] TypeDef or MethodDef whose generic parameters are requested - mdGenericParam rGenericParams[], // [OUT] Put GenericParams here. - ULONG cMax, // [IN] Max GenericParams to put. - ULONG *pcGenericParams) // [OUT] Put # put here. - { - return m_pRawImport->EnumGenericParams(phEnum, tk, rGenericParams, cMax, pcGenericParams); - } - - - STDMETHODIMP GetGenericParamProps( // S_OK or error. - mdGenericParam gp, // [IN] GenericParam - ULONG *pulParamSeq, // [OUT] Index of the type parameter - DWORD *pdwParamFlags, // [OUT] Flags, for future use (e.g. variance) - mdToken *ptOwner, // [OUT] Owner (TypeDef or MethodDef) - DWORD *reserved, // [OUT] For future use (e.g. non-type parameters) - __out_ecount_part_opt(cchName, *pchName) - LPWSTR wzname, // [OUT] Put name here - ULONG cchName, // [IN] Size of buffer - ULONG *pchName) // [OUT] Put size of name (wide chars) here. - { - // Returns error code from name filling (may be CLDB_S_TRUNCTATION) - return m_pRawImport->GetGenericParamProps(gp, pulParamSeq, pdwParamFlags, ptOwner, reserved, wzname, cchName, pchName); - } - - - STDMETHODIMP GetMethodSpecProps( - mdMethodSpec mi, // [IN] The method instantiation - mdToken *tkParent, // [OUT] MethodDef or MemberRef - PCCOR_SIGNATURE *ppvSigBlob, // [OUT] point to the blob value of meta data - ULONG *pcbSigBlob) // [OUT] actual size of signature blob - { - HRESULT hr = S_OK; - - ULONG cbOrigSigBlob = (ULONG)(-1); - PCCOR_SIGNATURE pOrigSig = NULL; - IfFailRet(m_pRawImport->GetMethodSpecProps(mi, tkParent, &pOrigSig, &cbOrigSigBlob)); - - return m_pWinMDAdapter->GetSignatureForToken( - mi, - &pOrigSig, // ppOrigSig - &cbOrigSigBlob, // pcbOrigSig - ppvSigBlob, - pcbSigBlob, - m_pRawImport); - } - - - STDMETHODIMP EnumGenericParamConstraints( - HCORENUM *phEnum, // [IN|OUT] Pointer to the enum. - mdGenericParam tk, // [IN] GenericParam whose constraints are requested - mdGenericParamConstraint rGenericParamConstraints[], // [OUT] Put GenericParamConstraints here. - ULONG cMax, // [IN] Max GenericParamConstraints to put. - ULONG *pcGenericParamConstraints) // [OUT] Put # put here. - { - return m_pRawImport->EnumGenericParamConstraints(phEnum, tk, rGenericParamConstraints, cMax, pcGenericParamConstraints); - } - - - STDMETHODIMP GetGenericParamConstraintProps( // S_OK or error. - mdGenericParamConstraint gpc, // [IN] GenericParamConstraint - mdGenericParam *ptGenericParam, // [OUT] GenericParam that is constrained - mdToken *ptkConstraintType) // [OUT] TypeDef/Ref/Spec constraint - { - return m_pRawImport->GetGenericParamConstraintProps(gpc, ptGenericParam, ptkConstraintType); - } - - - STDMETHODIMP GetPEKind( // S_OK or error. - DWORD* pdwPEKind, // [OUT] The kind of PE (0 - not a PE) - DWORD* pdwMachine) // [OUT] Machine as defined in NT header - { - return m_pRawImport->GetPEKind(pdwPEKind, pdwMachine); - } - - - STDMETHODIMP GetVersionString( // S_OK or error. - __out_ecount_part_opt(ccBufSize, *pccBufSize) - LPWSTR pwzBuf, // [OUT] Put version string here. - DWORD ccBufSize, // [IN] size of the buffer, in wide chars - DWORD *pccBufSize) // [OUT] Size of the version string, wide chars, including terminating nul. - { - HRESULT hr; - LPCSTR szVersion; - IfFailRet(GetVersionString(&szVersion)); - // Returns error code from name filling (may be CLDB_S_TRUNCTATION) - return DeliverUtf8String(szVersion, pwzBuf, ccBufSize, pccBufSize); - } - - - STDMETHODIMP EnumMethodSpecs( - HCORENUM *phEnum, // [IN|OUT] Pointer to the enum. - mdToken tk, // [IN] MethodDef or MemberRef whose MethodSpecs are requested - mdMethodSpec rMethodSpecs[], // [OUT] Put MethodSpecs here. - ULONG cMax, // [IN] Max tokens to put. - ULONG *pcMethodSpecs) // [OUT] Put actual count here. - { - return m_pRawImport->EnumMethodSpecs(phEnum, tk, rMethodSpecs, cMax, pcMethodSpecs); - } - - - public: - //========================================================= - // IMetaDataAssemblyImport methods - //========================================================= - - STDMETHODIMP GetAssemblyProps( // S_OK or error. - mdAssembly mda, // [IN] The Assembly for which to get the properties. - const void **ppbPublicKey, // [OUT] Pointer to the public key. - ULONG *pcbPublicKey, // [OUT] Count of bytes in the public key. - ULONG *pulHashAlgId, // [OUT] Hash Algorithm. - __out_ecount_part_opt(cchName, *pchName) LPWSTR szName, // [OUT] Buffer to fill with assembly's simply name. - ULONG cchName, // [IN] Size of buffer in wide chars. - ULONG *pchName, // [OUT] Actual # of wide chars in name. - ASSEMBLYMETADATA *pMetaData, // [OUT] Assembly MetaData. - DWORD *pdwAssemblyFlags) // [OUT] Flags. - { - return m_pRawAssemblyImport->GetAssemblyProps(mda, ppbPublicKey, pcbPublicKey, pulHashAlgId, szName, cchName, pchName, pMetaData, pdwAssemblyFlags); - } - - - STDMETHODIMP GetAssemblyRefProps( // S_OK or error. - mdAssemblyRef mdar, // [IN] The AssemblyRef for which to get the properties. - const void **ppbPublicKeyOrToken, // [OUT] Pointer to the public key or token. - ULONG *pcbPublicKeyOrToken, // [OUT] Count of bytes in the public key or token. - __out_ecount_part_opt(cchName, *pchName)LPWSTR szName, // [OUT] Buffer to fill with name. - ULONG cchName, // [IN] Size of buffer in wide chars. - ULONG *pchName, // [OUT] Actual # of wide chars in name. - ASSEMBLYMETADATA *pMetaData, // [OUT] Assembly MetaData. - const void **ppbHashValue, // [OUT] Hash blob. - ULONG *pcbHashValue, // [OUT] Count of bytes in the hash blob. - DWORD *pdwAssemblyRefFlags) // [OUT] Flags. - { - HRESULT hr; - HRESULT hrNameTruncation; - - if (!IsValidNonNilToken(mdar, mdtAssemblyRef)) - { - // Idiosyncratic edge cases - delegate straight through to inherit the correct idiosyncratic edge result - return m_pRawAssemblyImport->GetAssemblyRefProps(mdar, ppbPublicKeyOrToken, pcbPublicKeyOrToken, szName, cchName, pchName, pMetaData, ppbHashValue, pcbHashValue, pdwAssemblyRefFlags); - } - - mdAssemblyRef md = mdar; - if (RidFromToken(md) > m_pWinMDAdapter->GetRawAssemblyRefCount()) - { - // The extra framework assemblies we add references to should all have the - // same verion, key, culture, etc as those of mscorlib. - // So we retrieve the mscorlib properties and change the name. - md = m_pWinMDAdapter->GetAssemblyRefMscorlib(); - } - - IfFailRet(hrNameTruncation = m_pRawAssemblyImport->GetAssemblyRefProps(md, ppbPublicKeyOrToken, pcbPublicKeyOrToken, szName, cchName, pchName, pMetaData, ppbHashValue, pcbHashValue, pdwAssemblyRefFlags)); - - LPCSTR szNewName = nullptr; - USHORT *pusMajorVersion = nullptr; - USHORT *pusMinorVersion = nullptr; - USHORT *pusBuildNumber = nullptr; - USHORT *pusRevisionNumber = nullptr; - - if (pMetaData != nullptr) - { - pusMajorVersion = &pMetaData->usMajorVersion; - pusMinorVersion = &pMetaData->usMinorVersion; - pusBuildNumber = &pMetaData->usBuildNumber; - pusRevisionNumber = &pMetaData->usRevisionNumber; - } - - m_pWinMDAdapter->ModifyAssemblyRefProps( - mdar, - ppbPublicKeyOrToken, - pcbPublicKeyOrToken, - &szNewName, - pusMajorVersion, - pusMinorVersion, - pusBuildNumber, - pusRevisionNumber, - ppbHashValue, - pcbHashValue); - - if (szNewName != nullptr) - { - IfFailRet(hrNameTruncation = DeliverUtf8String(szNewName, szName, cchName, pchName)); - } - - // Return the success code from name filling (S_OK or CLDB_S_TRUNCATION) - return hrNameTruncation; - } - - - STDMETHODIMP GetFileProps( // S_OK or error. - mdFile mdf, // [IN] The File for which to get the properties. - __out_ecount_part_opt(cchName, *pchName) LPWSTR szName, // [OUT] Buffer to fill with name. - ULONG cchName, // [IN] Size of buffer in wide chars. - ULONG *pchName, // [OUT] Actual # of wide chars in name. - const void **ppbHashValue, // [OUT] Pointer to the Hash Value Blob. - ULONG *pcbHashValue, // [OUT] Count of bytes in the Hash Value Blob. - DWORD *pdwFileFlags) // [OUT] Flags. - { - // Returns error code from name filling (may be CLDB_S_TRUNCTATION) - return m_pRawAssemblyImport->GetFileProps(mdf, szName, cchName, pchName, ppbHashValue, pcbHashValue, pdwFileFlags); - } - - - STDMETHODIMP GetExportedTypeProps( // S_OK or error. - mdExportedType mdct, // [IN] The ExportedType for which to get the properties. - __out_ecount_part_opt(cchName, *pchName) LPWSTR szName, // [OUT] Buffer to fill with name. - ULONG cchName, // [IN] Size of buffer in wide chars. - ULONG *pchName, // [OUT] Actual # of wide chars in name. - mdToken *ptkImplementation, // [OUT] mdFile or mdAssemblyRef or mdExportedType. - mdTypeDef *ptkTypeDef, // [OUT] TypeDef token within the file. - DWORD *pdwExportedTypeFlags) // [OUT] Flags. - { - HRESULT hr; - LPCSTR szUtf8Namespace; - LPCSTR szUtf8Name; - if (!IsValidNonNilToken(mdct, mdtExportedType)) - { - // Idiosyncractic edge cases - delegate straight through to inherit the correct idiosyncractic edge results - return m_pRawAssemblyImport->GetExportedTypeProps(mdct, szName, cchName, pchName, ptkImplementation, ptkTypeDef, pdwExportedTypeFlags); - } - IfFailRet(m_pRawAssemblyImport->GetExportedTypeProps(mdct, NULL, 0, NULL, NULL, ptkTypeDef, pdwExportedTypeFlags)); - IfFailRet(this->CommonGetExportedTypeProps(mdct, &szUtf8Namespace, &szUtf8Name, ptkImplementation)); - // Returns error code from name filling (may be CLDB_S_TRUNCTATION) - return DeliverUtf8NamespaceAndName(szUtf8Namespace, szUtf8Name, szName, cchName, pchName); - } - - - STDMETHODIMP GetManifestResourceProps( // S_OK or error. - mdManifestResource mdmr, // [IN] The ManifestResource for which to get the properties. - __out_ecount_part_opt(cchName, *pchName)LPWSTR szName, // [OUT] Buffer to fill with name. - ULONG cchName, // [IN] Size of buffer in wide chars. - ULONG *pchName, // [OUT] Actual # of wide chars in name. - mdToken *ptkImplementation, // [OUT] mdFile or mdAssemblyRef that provides the ManifestResource. - DWORD *pdwOffset, // [OUT] Offset to the beginning of the resource within the file. - DWORD *pdwResourceFlags) // [OUT] Flags. - { - // Returns error code from name filling (may be CLDB_S_TRUNCTATION) - return m_pRawAssemblyImport->GetManifestResourceProps(mdmr, szName, cchName, pchName, ptkImplementation, pdwOffset, pdwResourceFlags); - } - - - STDMETHODIMP EnumAssemblyRefs( // S_OK or error - HCORENUM *phEnum, // [IN|OUT] Pointer to the enum. - mdAssemblyRef rAssemblyRefs[], // [OUT] Put AssemblyRefs here. - ULONG cMax, // [IN] Max AssemblyRefs to put. - ULONG *pcTokens) // [OUT] Put # put here. - { - if (*phEnum != NULL) - { - // No trick needed: a previous call to EnumAssemblyRefs must have already taken care of the - // extra assembly refs. - return m_pRawAssemblyImport->EnumAssemblyRefs(phEnum, rAssemblyRefs, cMax, pcTokens); - } - else - { - // if *phEnum is NULL, we need create the HENUMInternal, adjust the assembly ref count, - // and enumerate the number of assembly refs requested. This is done in three steps: - HRESULT hr; - - // Step 1: Call EnumAssemblyRefs with an empty buffer to create the HENUMInternal - IfFailGo(m_pRawAssemblyImport->EnumAssemblyRefs(phEnum, NULL, 0, NULL)); - - { - // Step 2: Increment the count to include the extra assembly refs - HENUMInternal *phInternalEnum = static_cast(*phEnum); - - _ASSERTE(phInternalEnum->m_EnumType == MDSimpleEnum); - - _ASSERTE( phInternalEnum->m_ulCount == m_pWinMDAdapter->GetRawAssemblyRefCount()); - int n = m_pWinMDAdapter->GetExtraAssemblyRefCount(); - phInternalEnum->m_ulCount += n; - phInternalEnum->u.m_ulEnd += n; - } - - // Step 3: Call EnumAssemblyRefs again and pass in the modifed HENUMInternal and the real buffer - IfFailGo(m_pRawAssemblyImport->EnumAssemblyRefs(phEnum, rAssemblyRefs, cMax, pcTokens)); - -ErrExit: - return hr; - } - } - - - STDMETHODIMP EnumFiles( // S_OK or error - HCORENUM *phEnum, // [IN|OUT] Pointer to the enum. - mdFile rFiles[], // [OUT] Put Files here. - ULONG cMax, // [IN] Max Files to put. - ULONG *pcTokens) // [OUT] Put # put here. - { - return m_pRawAssemblyImport->EnumFiles(phEnum, rFiles, cMax, pcTokens); - } - - - STDMETHODIMP EnumExportedTypes( // S_OK or error - HCORENUM *phEnum, // [IN|OUT] Pointer to the enum. - mdExportedType rExportedTypes[], // [OUT] Put ExportedTypes here. - ULONG cMax, // [IN] Max ExportedTypes to put. - ULONG *pcTokens) // [OUT] Put # put here. - { - return m_pRawAssemblyImport->EnumExportedTypes(phEnum, rExportedTypes, cMax, pcTokens); - } - - - STDMETHODIMP EnumManifestResources( // S_OK or error - HCORENUM *phEnum, // [IN|OUT] Pointer to the enum. - mdManifestResource rManifestResources[], // [OUT] Put ManifestResources here. - ULONG cMax, // [IN] Max Resources to put. - ULONG *pcTokens) // [OUT] Put # put here. - { - return m_pRawAssemblyImport->EnumManifestResources(phEnum, rManifestResources, cMax, pcTokens); - } - - - STDMETHODIMP GetAssemblyFromScope( // S_OK or error - mdAssembly *ptkAssembly) // [OUT] Put token here. - { - return m_pRawAssemblyImport->GetAssemblyFromScope(ptkAssembly); - } - - - STDMETHODIMP FindExportedTypeByName( // S_OK or error - LPCWSTR wszName, // [IN] Name of the ExportedType. - mdToken mdtExportedType, // [IN] ExportedType for the enclosing class. - mdExportedType *ptkExportedType) // [OUT] Put the ExportedType token here. - { - if (wszName == NULL) - return E_INVALIDARG; - - LPUTF8 szFullName; - LPCUTF8 szNamespace; - LPCUTF8 szName; - // Convert the name to UTF8. - UTF8STR(wszName, szFullName); - ns::SplitInline(szFullName, szNamespace, szName); - return this->CommonFindExportedType(szNamespace, szName, mdtExportedType, ptkExportedType); - } - - - STDMETHODIMP FindManifestResourceByName( // S_OK or error - LPCWSTR szName, // [IN] Name of the ManifestResource. - mdManifestResource *ptkManifestResource) // [OUT] Put the ManifestResource token here. - { - return m_pRawAssemblyImport->FindManifestResourceByName(szName, ptkManifestResource); - } - - - - STDMETHODIMP FindAssembliesByName( // S_OK or error - LPCWSTR szAppBase, // [IN] optional - can be NULL - LPCWSTR szPrivateBin, // [IN] optional - can be NULL - LPCWSTR szAssemblyName, // [IN] required - this is the assembly you are requesting - IUnknown *ppIUnk[], // [OUT] put IMetaDataAssemblyImport pointers here - ULONG cMax, // [IN] The max number to put - ULONG *pcAssemblies) // [OUT] The number of assemblies returned. - { - return m_pRawAssemblyImport->FindAssembliesByName(szAppBase, szPrivateBin, szAssemblyName, ppIUnk, cMax, pcAssemblies); - } - - //========================================================= - // IMetaDataValidate - //========================================================= - STDMETHODIMP ValidatorInit( // S_OK or error. - DWORD dwModuleType, // [IN] Specifies the type of the module. - IUnknown *pUnk) // [IN] Validation error handler. - { - if (m_pRawValidate == nullptr) - return E_NOTIMPL; - - return m_pRawValidate->ValidatorInit(dwModuleType, pUnk); - } - - STDMETHODIMP ValidateMetaData() // S_OK or error. - { - if (m_pRawValidate == nullptr) - return E_NOTIMPL; - - return m_pRawValidate->ValidateMetaData(); - } - - //========================================================= - // IMDCommon methods - //========================================================= - STDMETHODIMP_(IMetaModelCommon*) GetMetaModelCommon() - { - return this; - } - - STDMETHODIMP_(IMetaModelCommonRO*) GetMetaModelCommonRO() - { - _ASSERTE(!"WinMDImport does not support GetMetaModelCommonRO(). The most likely cause of this assert is that you're trying to wrap a WinMD adapter around another WinMD adapter."); - return NULL; - } - - STDMETHODIMP GetVersionString(LPCSTR *pszVersionString) - { - return m_pWinMDAdapter->GetVersionString(pszVersionString); - } - - - //========================================================= - // IMetaModelCommon methods - //========================================================= - __checkReturn - virtual HRESULT CommonGetScopeProps( - LPCUTF8 *pszName, - GUID *pMvid) - { - return m_pRawMetaModelCommonRO->CommonGetScopeProps(pszName, pMvid); - } - - __checkReturn - virtual HRESULT CommonGetTypeRefProps( - mdTypeRef tr, - LPCUTF8 *pszNamespace, - LPCUTF8 *pszName, - mdToken *ptkResolution) - { - return m_pWinMDAdapter->GetTypeRefProps(tr, pszNamespace, pszName, ptkResolution); - } - - - __checkReturn - virtual HRESULT CommonGetTypeDefProps( - mdTypeDef td, - LPCUTF8 *pszNameSpace, - LPCUTF8 *pszName, - DWORD *pdwFlags, - mdToken *pdwExtends, - ULONG *pMethodList) - { - HRESULT hr; - IfFailGo(m_pRawMetaModelCommonRO->CommonGetTypeDefProps(td, NULL, NULL, NULL, NULL, pMethodList)); - IfFailGo(m_pWinMDAdapter->GetTypeDefProps(td, pszNameSpace, pszName, pdwFlags, pdwExtends)); - ErrExit: - return hr; - } - - - __checkReturn - virtual HRESULT CommonGetTypeSpecProps( - mdTypeSpec ts, - PCCOR_SIGNATURE *ppvSig, - ULONG *pcbSig) - { - return m_pWinMDAdapter->GetSignatureForToken( - ts, - NULL, // ppOrigSig - NULL, // pcbOrigSig - ppvSig, - pcbSig, - m_pRawImport); - } - - - __checkReturn - virtual HRESULT CommonGetEnclosingClassOfTypeDef( - mdTypeDef td, - mdTypeDef *ptkEnclosingTypeDef) - { - return m_pRawMetaModelCommonRO->CommonGetEnclosingClassOfTypeDef(td, ptkEnclosingTypeDef); - } - - - __checkReturn - virtual HRESULT CommonGetAssemblyProps( - USHORT *pusMajorVersion, - USHORT *pusMinorVersion, - USHORT *pusBuildNumber, - USHORT *pusRevisionNumber, - DWORD *pdwFlags, - const void **ppbPublicKey, - ULONG *pcbPublicKey, - LPCUTF8 *pszName, - LPCUTF8 *pszLocale) - { - return m_pRawMetaModelCommonRO->CommonGetAssemblyProps(pusMajorVersion, pusMinorVersion, pusBuildNumber, pusRevisionNumber, pdwFlags, ppbPublicKey, pcbPublicKey, pszName, pszLocale); - } - - - __checkReturn - virtual HRESULT CommonGetAssemblyRefProps( - mdAssemblyRef tkAssemRef, - USHORT *pusMajorVersion, - USHORT *pusMinorVersion, - USHORT *pusBuildNumber, - USHORT *pusRevisionNumber, - DWORD *pdwFlags, - const void **ppbPublicKeyOrToken, - ULONG *pcbPublicKeyOrToken, - LPCUTF8 *pszName, - LPCUTF8 *pszLocale, - const void **ppbHashValue, - ULONG *pcbHashValue) - { - HRESULT hr; - - mdAssemblyRef md = tkAssemRef; - if (RidFromToken(md) > m_pWinMDAdapter->GetRawAssemblyRefCount()) - { - // The extra framework assemblies we add references to should all have the - // same verion, key, culture, etc as those of mscorlib. - // So we retrieve the mscorlib properties and change the name. - md = m_pWinMDAdapter->GetAssemblyRefMscorlib(); - } - - IfFailRet(m_pRawMetaModelCommonRO->CommonGetAssemblyRefProps( - md, - pusMajorVersion, - pusMinorVersion, - pusBuildNumber, - pusRevisionNumber, - pdwFlags, - ppbPublicKeyOrToken, - pcbPublicKeyOrToken, - pszName, - pszLocale, - ppbHashValue, - pcbHashValue)); - - m_pWinMDAdapter->ModifyAssemblyRefProps( - tkAssemRef, - ppbPublicKeyOrToken, - pcbPublicKeyOrToken, - pszName, - pusMajorVersion, - pusMinorVersion, - pusBuildNumber, - pusRevisionNumber, - ppbHashValue, - pcbHashValue); - - return hr; - } - - - __checkReturn - virtual HRESULT CommonGetModuleRefProps( - mdModuleRef tkModuleRef, - LPCUTF8 *pszName) - { - return m_pRawMetaModelCommonRO->CommonGetModuleRefProps(tkModuleRef, pszName); - } - - - __checkReturn - virtual HRESULT CommonFindExportedType( - LPCUTF8 szNamespace, - LPCUTF8 szName, - mdToken tkEnclosingType, - mdExportedType *ptkExportedType) - { - return m_pWinMDAdapter->FindExportedType(szNamespace, szName, tkEnclosingType, ptkExportedType); - } - - - __checkReturn - virtual HRESULT CommonGetExportedTypeProps( - mdToken tkExportedType, - LPCUTF8 *pszNamespace, - LPCUTF8 *pszName, - mdToken *ptkImpl) - { - HRESULT hr; - IfFailRet(m_pRawMetaModelCommonRO->CommonGetExportedTypeProps(tkExportedType, pszNamespace, pszName, ptkImpl)); - IfFailRet(m_pWinMDAdapter->ModifyExportedTypeName(tkExportedType, pszNamespace, pszName)); - return hr; - } - - - virtual int CommonIsRo() - { - return m_pRawMetaModelCommonRO->CommonIsRo(); - } - - - __checkReturn - virtual HRESULT CommonGetCustomAttributeByNameEx( // S_OK or error. - mdToken tkObj, // [IN] Object with Custom Attribute. - LPCUTF8 szName, // [IN] Name of desired Custom Attribute. - mdCustomAttribute *ptkCA, // [OUT] put custom attribute token here - const void **ppData, // [OUT] Put pointer to data here. - ULONG *pcbData) // [OUT] Put size of data here. - { - return m_pWinMDAdapter->GetCustomAttributeByName(tkObj, szName, ptkCA, ppData, pcbData); - } - - - __checkReturn - virtual HRESULT FindParentOfMethodHelper(mdMethodDef md, mdTypeDef *ptd) - { - return m_pRawMetaModelCommonRO->FindParentOfMethodHelper(md, ptd); - } - - - - public: - //========================================================= - // IGetIMDInternalImport methods - //========================================================= - STDMETHODIMP GetIMDInternalImport(IMDInternalImport ** ppIMDInternalImport) - { - HRESULT hr = S_OK; - ReleaseHolder pMDCommon; - ReleaseHolder pRawMDInternalImport; - - *ppIMDInternalImport = NULL; - // Get the raw IMDInternalImport - IfFailGo(GetMDInternalInterfaceFromPublic(m_pRawImport, IID_IMDInternalImport, (LPVOID*)(&pRawMDInternalImport))); - - // Create an adapter around the internal raw interface - IfFailGo(pRawMDInternalImport->QueryInterface(IID_IMDCommon, (LPVOID*)(&pMDCommon))); - IfFailGo(CreateWinMDInternalImportRO(pMDCommon, IID_IMDInternalImport, (void**)ppIMDInternalImport)); - - ErrExit: - return hr; - } - - - //========================================================= - // Private methods - //========================================================= - - //------------------------------------------------------------------------------------------------------ - // Deliver a result string (Unicode) to a caller's sized output buffer using the standard convention - // followed by all metadata api. - //------------------------------------------------------------------------------------------------------ - static HRESULT DeliverUnicodeString(LPCWSTR wszResult, __out_ecount_part(cchCallerBuffer, *pchSizeNeeded) LPWSTR wszCallerBuffer, ULONG cchCallerBuffer, ULONG *pchSizeNeeded) - { - ULONG cchActual = (ULONG)(wcslen(wszResult) + 1); - if (pchSizeNeeded) - { - *pchSizeNeeded = cchActual; - } - if (wszCallerBuffer == NULL || cchCallerBuffer < cchActual) - { - if (wszCallerBuffer != NULL) - { - memcpy(wszCallerBuffer, wszResult, cchCallerBuffer * sizeof(WCHAR)); // If buffer too small, return truncated result to be compatible with metadata api conventions - if (cchCallerBuffer > 0) - { // null-terminate the truncated output string - wszCallerBuffer[cchCallerBuffer - 1] = W('\0'); - } - } - return CLDB_S_TRUNCATION; - } - else - { - memcpy(wszCallerBuffer, wszResult, cchActual * sizeof(WCHAR)); - return S_OK; - } - } - - //------------------------------------------------------------------------------------------------------ - // Deliver a result string (Utf8) to a caller's sized output buffer using the standard convention - // followed by all metadata api. - //------------------------------------------------------------------------------------------------------ - static HRESULT DeliverUtf8String(LPCSTR szUtf8Result, __out_ecount_part(cchCallerBuffer, *pchSizeNeeded) LPWSTR wszCallerBuffer, ULONG cchCallerBuffer, ULONG *pchSizeNeeded) - { - MAKE_WIDEPTR_FROMUTF8_NOTHROW(wzResult, szUtf8Result); - if (wzResult == NULL) - return E_OUTOFMEMORY; - return DeliverUnicodeString(wzResult, wszCallerBuffer, cchCallerBuffer, pchSizeNeeded); - } - - //------------------------------------------------------------------------------------------------------ - // Combine a result namespace/name string pair (Utf8) to a Unicode fullname and deliver to a caller's - // sized output buffer using the standard convention followed by all metadata api. - //------------------------------------------------------------------------------------------------------ - static HRESULT DeliverUtf8NamespaceAndName(LPCSTR szUtf8Namespace, LPCSTR szUtf8Name, __out_ecount_part(cchCallerBuffer, *pchSizeNeeded) LPWSTR wszCallerBuffer, ULONG cchCallerBuffer, ULONG *pchSizeNeeded) - { - HRESULT hr; - if (wszCallerBuffer != NULL || pchSizeNeeded != NULL) - { - MAKE_WIDEPTR_FROMUTF8_NOTHROW(wzNamespace, szUtf8Namespace); - IfNullRet(wzNamespace); - MAKE_WIDEPTR_FROMUTF8_NOTHROW(wzName, szUtf8Name); - IfNullRet(wzName); - - BOOL fTruncation = FALSE; - if (wszCallerBuffer != NULL) - { - fTruncation = !(ns::MakePath(wszCallerBuffer, cchCallerBuffer, wzNamespace, wzName)); - if (fTruncation && (cchCallerBuffer > 0)) - { // null-terminate the truncated output string - wszCallerBuffer[cchCallerBuffer - 1] = W('\0'); - } - } - if (pchSizeNeeded != NULL) - { - if (fTruncation || (wszCallerBuffer == NULL)) - { - *pchSizeNeeded = ns::GetFullLength(wzNamespace, wzName); - } - else - { - *pchSizeNeeded = (ULONG)(wcslen(wszCallerBuffer) + 1); - } - } - hr = fTruncation ? CLDB_S_TRUNCATION : S_OK; - } - else - { - hr = S_OK; // Caller did not request name back. - } - return hr; - } - - private: - //========================================================= - // Private instance data - //========================================================= - IMDCommon *m_pRawMDCommon; - IMetaDataImport2 *m_pRawImport; - IMetaDataAssemblyImport *m_pRawAssemblyImport; - IMetaDataValidate *m_pRawValidate; - IMetaModelCommonRO *m_pRawMetaModelCommonRO; - IUnknown *m_pFreeThreadedMarshaler; - WinMDAdapter *m_pWinMDAdapter; - LONG m_cRef; - -}; // class WinMDImport - - - -//======================================================================================== -// Entrypoint called by IMetaDataDispenser::OpenScope() -//======================================================================================== -HRESULT CreateWinMDImport(IMDCommon * pRawMDCommon, REFIID riid, /*[out]*/ void **ppWinMDImport) -{ - HRESULT hr; - *ppWinMDImport = NULL; - WinMDImport *pWinMDImport = NULL; - IfFailGo(WinMDImport::Create(pRawMDCommon, &pWinMDImport)); - IfFailGo(pWinMDImport->QueryInterface(riid, ppWinMDImport)); - hr = S_OK; - ErrExit: - if (pWinMDImport) - pWinMDImport->Release(); - return hr; -} diff --git a/src/coreclr/src/md/winmd/winmdinternalimportro.cpp b/src/coreclr/src/md/winmd/winmdinternalimportro.cpp deleted file mode 100644 index 0027437..0000000 --- a/src/coreclr/src/md/winmd/winmdinternalimportro.cpp +++ /dev/null @@ -1,1721 +0,0 @@ -// 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. - - - -#include "stdafx.h" -#include "winmdinterfaces.h" -#include "inc/adapter.h" - - -#ifdef FEATURE_METADATA_INTERNAL_APIS - - -__checkReturn -HRESULT TranslateSigHelper( // S_OK or error. - IMDInternalImport *pImport, // [IN] import scope. - IMDInternalImport *pAssemImport, // [IN] import assembly scope. - const void *pbHashValue, // [IN] hash value for the import assembly. - ULONG cbHashValue, // [IN] count of bytes in the hash value. - PCCOR_SIGNATURE pbSigBlob, // [IN] signature in the importing scope - ULONG cbSigBlob, // [IN] count of bytes of signature - IMetaDataAssemblyEmit *pAssemEmit, // [IN] assembly emit scope. - IMetaDataEmit *emit, // [IN] emit interface - CQuickBytes *pqkSigEmit, // [OUT] buffer to hold translated signature - ULONG *pcbSig); // [OUT] count of bytes in the translated signature - - -//======================================================================================== -// This metadata importer is used internally by the runtime and exposes an -// IMDInternalImport* on .winmd files. It applies a small number of on-the-fly -// conversions to make the .winmd file look like a regular .NET assembly. -// -// All those places in src\vm where the runtime calls an IMDInternalImport* -// pointer, it may now be talking to a WinMDInternalImportRO. Ideally, the -// runtime will never know the difference (but this being an internal interface, -// we may tolerate the occasional leakiness in the name of expediency.) -//======================================================================================== -class WinMDInternalImportRO : public IMDInternalImport, IWinMDImport, IMetaModelCommon -{ - public: - //========================================================= - // Factory - //========================================================= - static HRESULT Create(IMDCommon *pRawMDCommon, WinMDInternalImportRO **ppWinMDInternalImportRO) - { - HRESULT hr; - *ppWinMDInternalImportRO = NULL; - WinMDInternalImportRO *pNewWinMDInternalImport = new (nothrow) WinMDInternalImportRO(pRawMDCommon); - IfFailGo(pRawMDCommon->QueryInterface(IID_IMDInternalImport, (void**)&(pNewWinMDInternalImport->m_pRawInternalImport))); - IfFailGo(WinMDAdapter::Create(pNewWinMDInternalImport->m_pRawMDCommon, &(pNewWinMDInternalImport->m_pWinMDAdapter))); - (*ppWinMDInternalImportRO = pNewWinMDInternalImport)->AddRef(); - hr = S_OK; - - ErrExit: - if (pNewWinMDInternalImport) - pNewWinMDInternalImport->Release(); - return hr; - } - - private: - //========================================================= - // Ctors, Dtors - //========================================================= - WinMDInternalImportRO(IMDCommon * pRawMDCommon) - : m_cRef(1) - , m_pWinMDAdapter(NULL) - , m_pRawInternalImport(NULL) - , m_pRawMDCommon(pRawMDCommon) - , m_pRawMetaModelCommon(pRawMDCommon->GetMetaModelCommon()) - { - m_pRawMDCommon->AddRef(); - } - - //--------------------------------------------------------- - ~WinMDInternalImportRO() - { - m_pRawMDCommon->Release(); - m_pRawInternalImport->Release(); - delete m_pWinMDAdapter; - } - - public: - //========================================================= - // IUnknown methods - //========================================================= - STDMETHODIMP QueryInterface(REFIID riid, void** ppUnk) - { - *ppUnk = 0; - if (riid == IID_IUnknown || riid == IID_IWinMDImport) - *ppUnk = (IWinMDImport *) this; - else if (riid == IID_IMDInternalImport) - *ppUnk = (IMDInternalImport *) this; - else - { -#ifndef DACCESS_COMPILE -#ifdef _DEBUG - if (CLRConfig::GetConfigValue(CLRConfig::INTERNAL_MD_WinMD_AssertOnIllegalUsage)) - { - if (riid == IID_IMDInternalImportENC) - _ASSERTE(!"WinMDInternalImportRO::QueryInterface(IID_IMDInternalImportENC) returning E_NOINTERFACE"); - else if (riid == IID_IMarshal) - _ASSERTE(!"WinMDInternalImportRO::QueryInterface(IID_IMarshal) returning E_NOINTERFACE"); - else - _ASSERTE(!"WinMDInternalImportRO::QueryInterface() returning E_NOINTERFACE"); - } -#endif //_DEBUG -#endif - return E_NOINTERFACE; - } - AddRef(); - return S_OK; - } - //--------------------------------------------------------- - STDMETHODIMP_(ULONG) AddRef(void) - { - return InterlockedIncrement(&m_cRef); - } - //--------------------------------------------------------- - STDMETHODIMP_(ULONG) Release(void) - { - ULONG cRef = InterlockedDecrement(&m_cRef); - if (!cRef) - delete this; - return cRef; - } - - public: - //========================================================= - // IWinMDImport methods - //========================================================= - STDMETHODIMP IsScenarioWinMDExp(BOOL *pbResult) - { - if (pbResult == NULL) - return E_POINTER; - - *pbResult = m_pWinMDAdapter->IsScenarioWinMDExp(); - return S_OK; - } - - STDMETHODIMP IsRuntimeClassImplementation(mdTypeDef tkTypeDef, BOOL *pbResult) - { - if (pbResult == NULL) - return E_POINTER; - - return m_pWinMDAdapter->IsRuntimeClassImplementation(tkTypeDef, pbResult); - } - - //========================================================= - // IMDInternalImport methods - //========================================================= - //***************************************************************************** - // return the count of entries of a given kind in a scope - // For example, pass in mdtMethodDef will tell you how many MethodDef - // contained in a scope - //***************************************************************************** - STDMETHODIMP_(ULONG) GetCountWithTokenKind(// return hresult - DWORD tkKind) // [IN] pass in the kind of token. - { - if (tkKind == mdtAssemblyRef) - { - return m_pRawInternalImport->GetCountWithTokenKind(tkKind) + m_pWinMDAdapter->GetExtraAssemblyRefCount(); - } - else - { - return m_pRawInternalImport->GetCountWithTokenKind(tkKind); - } - } - - //***************************************************************************** - // enumerator for typedef - //***************************************************************************** - __checkReturn - STDMETHODIMP EnumTypeDefInit( // return hresult - HENUMInternal *phEnum) // [OUT] buffer to fill for enumerator data - { - return m_pRawInternalImport->EnumTypeDefInit(phEnum); - } - - //***************************************************************************** - // enumerator for MethodImpl - //***************************************************************************** - __checkReturn - STDMETHODIMP EnumMethodImplInit( // return hresult - mdTypeDef td, // [IN] TypeDef over which to scope the enumeration. - HENUMInternal *phEnumBody, // [OUT] buffer to fill for enumerator data for MethodBody tokens. - HENUMInternal *) // [OUT] used only on RW imports - { - HRESULT hr; - HENUMInternal::InitDynamicArrayEnum(phEnumBody); - phEnumBody->m_tkKind = TBL_MethodImpl << 24; - IfFailGo(m_pWinMDAdapter->AddMethodImplsToEnum(td, phEnumBody)); - hr = S_OK; - - ErrExit: - if (FAILED(hr)) - { - HENUMInternal::ClearEnum(phEnumBody); - INDEBUG(HENUMInternal::ZeroEnum(phEnumBody)); - } - return hr; - } - - STDMETHODIMP_(ULONG) EnumMethodImplGetCount( - HENUMInternal *phEnumBody, // [IN] MethodBody enumerator. - HENUMInternal *) // [IN] used only on RW imports - - { - return phEnumBody->m_ulCount / 2; - } - - STDMETHODIMP_(void) EnumMethodImplReset( - HENUMInternal *phEnumBody, // [IN] MethodBody enumerator. - HENUMInternal *) // [IN] used only on RW imports - { - phEnumBody->u.m_ulCur = phEnumBody->u.m_ulStart; - return; - } - - __checkReturn - STDMETHODIMP EnumMethodImplNext( // return hresult (S_OK = TRUE, S_FALSE = FALSE or error code) - HENUMInternal *phEnumBody, // [IN] input enum for MethodBody - HENUMInternal *, // [IN] used only on RW imports - mdToken *ptkBody, // [OUT] return token for MethodBody - mdToken *ptkDecl) // [OUT] return token for MethodDecl - { - _ASSERTE(ptkBody && ptkDecl); - return HENUMInternal::EnumWithCount(phEnumBody, 1, ptkBody, ptkDecl, NULL); - } - - STDMETHODIMP_(void) EnumMethodImplClose( - HENUMInternal *phEnumBody, // [IN] MethodBody enumerator. - HENUMInternal *) // [IN] used only on RW imports - { - HENUMInternal::ClearEnum(phEnumBody); - } - - //***************************************** - // Enumerator helpers for memberdef, memberref, interfaceimp, - // event, property, exception, param - //***************************************** - - __checkReturn - STDMETHODIMP EnumGlobalFunctionsInit( // return hresult - HENUMInternal *phEnum) // [OUT] buffer to fill for enumerator data - { - return m_pRawInternalImport->EnumGlobalFunctionsInit(phEnum); - } - - __checkReturn - STDMETHODIMP EnumGlobalFieldsInit( // return hresult - HENUMInternal *phEnum) // [OUT] buffer to fill for enumerator data - { - return m_pRawInternalImport->EnumGlobalFieldsInit(phEnum); - } - - __checkReturn - STDMETHODIMP EnumInit( // return S_FALSE if record not found - DWORD tkKind, // [IN] which table to work on - mdToken tkParent, // [IN] token to scope the search - HENUMInternal *phEnum) // [OUT] the enumerator to fill - { - if (tkKind == (TBL_MethodImpl << 24)) - return EnumMethodImplInit(tkParent, phEnum, NULL); - - HRESULT hr; - IfFailGo(m_pRawInternalImport->EnumInit(tkKind, tkParent, phEnum)); - - _ASSERTE(phEnum->m_EnumType == MDSimpleEnum); - - if (tkKind == mdtAssemblyRef) - { - _ASSERTE( phEnum->m_ulCount == m_pWinMDAdapter->GetRawAssemblyRefCount()); - int n = m_pWinMDAdapter->GetExtraAssemblyRefCount(); - phEnum->m_ulCount += n; - phEnum->u.m_ulEnd += n; - } - - -ErrExit: - return hr; - } - - __checkReturn - STDMETHODIMP EnumAllInit( // return S_FALSE if record not found - DWORD tkKind, // [IN] which table to work on - HENUMInternal *phEnum) // [OUT] the enumerator to fill - { - HRESULT hr; - IfFailGo(m_pRawInternalImport->EnumAllInit(tkKind, phEnum)); - - _ASSERTE(phEnum->m_EnumType == MDSimpleEnum); - - if (tkKind == mdtAssemblyRef) - { - _ASSERTE( phEnum->m_ulCount == m_pWinMDAdapter->GetRawAssemblyRefCount()); - int n = m_pWinMDAdapter->GetExtraAssemblyRefCount(); - phEnum->m_ulCount += n; - phEnum->u.m_ulEnd += n; - } - -ErrExit: - return hr; - } - - //***************************************** - // Enumerator helpers for CustomAttribute - //***************************************** - __checkReturn - STDMETHODIMP EnumCustomAttributeByNameInit(// return S_FALSE if record not found - mdToken tkParent, // [IN] token to scope the search - LPCSTR szName, // [IN] CustomAttribute's name to scope the search - HENUMInternal *phEnum) // [OUT] the enumerator to fill - { - WinMDAdapter::ConvertWellKnownTypeNameFromClrToWinRT(&szName); - return m_pRawInternalImport->EnumCustomAttributeByNameInit(tkParent, szName, phEnum); - } - - //***************************************** - // Nagivator helper to navigate back to the parent token given a token. - // For example, given a memberdef token, it will return the containing typedef. - // - // the mapping is as following: - // ---given child type---------parent type - // mdMethodDef mdTypeDef - // mdFieldDef mdTypeDef - // mdInterfaceImpl mdTypeDef - // mdParam mdMethodDef - // mdProperty mdTypeDef - // mdEvent mdTypeDef - // - //***************************************** - __checkReturn - STDMETHODIMP GetParentToken( - mdToken tkChild, // [IN] given child token - mdToken *ptkParent) // [OUT] returning parent - { - return m_pRawInternalImport->GetParentToken(tkChild, ptkParent); - } - - //***************************************** - // Custom value helpers - //***************************************** - __checkReturn - STDMETHODIMP GetCustomAttributeProps( // S_OK or error. - mdCustomAttribute at, // [IN] The attribute. - mdToken *ptkType) // [OUT] Put attribute type here. - { - return m_pRawInternalImport->GetCustomAttributeProps(at, ptkType); - } - - __checkReturn - STDMETHODIMP GetCustomAttributeAsBlob( - mdCustomAttribute cv, // [IN] given custom value token - void const **ppBlob, // [OUT] return the pointer to internal blob - ULONG *pcbSize) // [OUT] return the size of the blob - { - return m_pWinMDAdapter->GetCustomAttributeBlob(cv, ppBlob, pcbSize); - } - - // returned void in v1.0/v1.1 - __checkReturn - STDMETHODIMP GetScopeProps( - LPCSTR *pszName, // [OUT] scope name - GUID *pmvid) // [OUT] version id - { - return m_pRawInternalImport->GetScopeProps(pszName, pmvid); - } - - // The default signature comparison function. - static BOOL CompareSignatures(PCCOR_SIGNATURE pvFirstSigBlob, // First signature - DWORD cbFirstSigBlob, // - PCCOR_SIGNATURE pvSecondSigBlob, // Second signature - DWORD cbSecondSigBlob, // - void * SigArguments) // No additional arguments required - { - if (cbFirstSigBlob != cbSecondSigBlob || memcmp(pvFirstSigBlob, pvSecondSigBlob, cbSecondSigBlob)) - return FALSE; - else - return TRUE; - } - - // finding a particular method - __checkReturn - STDMETHODIMP FindMethodDef( - mdTypeDef classdef, // [IN] given typedef - LPCSTR szName, // [IN] member name - PCCOR_SIGNATURE pvSigBlob, // [IN] point to a blob value of CLR signature - ULONG cbSigBlob, // [IN] count of bytes in the signature blob - mdMethodDef *pmd) // [OUT] matching memberdef - { - return FindMethodDefUsingCompare(classdef, - szName, - pvSigBlob, - cbSigBlob, - CompareSignatures, - NULL, - pmd); - } - - // return a iSeq's param given a MethodDef - __checkReturn - STDMETHODIMP FindParamOfMethod( // S_OK or error. - mdMethodDef md, // [IN] The owning method of the param. - ULONG iSeq, // [IN] The sequence # of the param. - mdParamDef *pparamdef) // [OUT] Put ParamDef token here. - { - return m_pRawInternalImport->FindParamOfMethod(md, iSeq, pparamdef); - } - - //***************************************** - // - // GetName* functions - // - //***************************************** - - // return the name and namespace of typedef - __checkReturn - STDMETHODIMP GetNameOfTypeDef( - mdTypeDef classdef, // given classdef - LPCSTR *pszname, // return class name(unqualified) - LPCSTR *psznamespace) // return the name space name - { - if (TypeFromToken(classdef) != mdtTypeDef) - return CLDB_E_INTERNALERROR; - - HRESULT hr; - IfFailRet(m_pWinMDAdapter->GetTypeDefProps(classdef, psznamespace, pszname, NULL, NULL)); - return hr; - } - - __checkReturn - STDMETHODIMP GetIsDualOfTypeDef( - mdTypeDef classdef, // [IN] given classdef. - ULONG *pDual) // [OUT] return dual flag here. - { - return m_pRawInternalImport->GetIsDualOfTypeDef(classdef, pDual); - } - - __checkReturn - STDMETHODIMP GetIfaceTypeOfTypeDef( - mdTypeDef classdef, // [IN] given classdef. - ULONG *pIface) // [OUT] 0=dual, 1=vtable, 2=dispinterface - { - return m_pRawInternalImport->GetIfaceTypeOfTypeDef(classdef, pIface); - } - - // get the name of either methoddef - __checkReturn - STDMETHODIMP GetNameOfMethodDef( // return the name of the memberdef in UTF8 - mdMethodDef md, // given memberdef - LPCSTR *pszName) - { - HRESULT hr = S_OK; - IfFailRet(m_pRawInternalImport->GetNameOfMethodDef(md, pszName)); - return m_pWinMDAdapter->ModifyMethodProps(md, NULL, NULL, NULL, pszName); - } - - __checkReturn - STDMETHODIMP GetNameAndSigOfMethodDef( - mdMethodDef methoddef, // [IN] given memberdef - PCCOR_SIGNATURE *ppvSigBlob, // [OUT] point to a blob value of CLR signature - ULONG *pcbSigBlob, // [OUT] count of bytes in the signature blob - LPCSTR *pszName) - { - PCCOR_SIGNATURE pOrigSig; - ULONG cbOrigSig; - HRESULT hr = S_OK; - IfFailRet(m_pRawInternalImport->GetNameAndSigOfMethodDef(methoddef, &pOrigSig, &cbOrigSig, pszName)); - IfFailRet(m_pWinMDAdapter->ModifyMethodProps(methoddef, NULL, NULL, NULL, pszName)); - - return m_pWinMDAdapter->GetSignatureForToken( - methoddef, - &pOrigSig, // ppOrigSig - &cbOrigSig, // pcbOrigSig - ppvSigBlob, - pcbSigBlob, - m_pRawInternalImport); - } - - // return the name of a FieldDef - __checkReturn - STDMETHODIMP GetNameOfFieldDef( - mdFieldDef fd, // given memberdef - LPCSTR *pszName) - { - return m_pRawInternalImport->GetNameOfFieldDef(fd, pszName); - } - - // return the name of typeref - __checkReturn - STDMETHODIMP GetNameOfTypeRef( - mdTypeRef classref, // [IN] given typeref - LPCSTR *psznamespace, // [OUT] return typeref name - LPCSTR *pszname) // [OUT] return typeref namespace - { - mdToken resolutionScope; - return m_pWinMDAdapter->GetTypeRefProps(classref, psznamespace, pszname, &resolutionScope); - } - - // return the resolutionscope of typeref - __checkReturn - STDMETHODIMP GetResolutionScopeOfTypeRef( - mdTypeRef classref, // given classref - mdToken *ptkResolutionScope) - { - LPCSTR sznamespace; - LPCSTR szname; - return m_pWinMDAdapter->GetTypeRefProps(classref, &sznamespace, &szname, ptkResolutionScope); - } - - // Find the type token given the name. - __checkReturn - STDMETHODIMP FindTypeRefByName( - LPCSTR szNamespace, // [IN] Namespace for the TypeRef. - LPCSTR szName, // [IN] Name of the TypeRef. - mdToken tkResolutionScope, // [IN] Resolution Scope fo the TypeRef. - mdTypeRef *ptk) // [OUT] TypeRef token returned. - { - return m_pWinMDAdapter->FindTypeRef(szNamespace, szName, tkResolutionScope, ptk); - } - - // return the TypeDef properties - // returned void in v1.0/v1.1 - __checkReturn - STDMETHODIMP GetTypeDefProps( - mdTypeDef classdef, // given classdef - DWORD *pdwAttr, // return flags on class, tdPublic, tdAbstract - mdToken *ptkExtends) // [OUT] Put base class TypeDef/TypeRef here - { - HRESULT hr; - IfFailGo(m_pWinMDAdapter->GetTypeDefProps(classdef, NULL, NULL, pdwAttr, ptkExtends)); - ErrExit: - return hr; - } - - // return the item's guid - __checkReturn - STDMETHODIMP GetItemGuid( - mdToken tkObj, // [IN] given item. - CLSID *pGuid) // [out[ put guid here. - { - HRESULT hr; - IfFailGo(m_pWinMDAdapter->GetItemGuid(tkObj, pGuid)); - - if (hr == S_FALSE) - { - // if this is not a WinRT type, also look for System.Guid by falling back to the raw internal MD import - if (TypeFromToken(tkObj) == mdtTypeDef) - { - DWORD dwAttr; - IfFailGo(m_pWinMDAdapter->GetTypeDefProps(tkObj, NULL, NULL, &dwAttr, NULL)); - - if (!IsTdWindowsRuntime(dwAttr)) - { - IfFailGo(m_pRawInternalImport->GetItemGuid(tkObj, pGuid)); - } - else - { - // reset the return value to S_FALSE if the type is WinRT - hr = S_FALSE; - } - } - } - - ErrExit: - return hr; - } - - // Get enclosing class of the NestedClass. - __checkReturn - STDMETHODIMP GetNestedClassProps( // S_OK or error - mdTypeDef tkNestedClass, // [IN] NestedClass token. - mdTypeDef *ptkEnclosingClass) // [OUT] EnclosingClass token. - { - return m_pRawInternalImport->GetNestedClassProps(tkNestedClass, ptkEnclosingClass); - } - - // Get count of Nested classes given the enclosing class. - __checkReturn - STDMETHODIMP GetCountNestedClasses( // return count of Nested classes. - mdTypeDef tkEnclosingClass, // Enclosing class. - ULONG *pcNestedClassesCount) - { - return m_pRawInternalImport->GetCountNestedClasses(tkEnclosingClass, pcNestedClassesCount); - } - - // Return array of Nested classes given the enclosing class. - __checkReturn - STDMETHODIMP GetNestedClasses( // Return actual count. - mdTypeDef tkEnclosingClass, // [IN] Enclosing class. - mdTypeDef *rNestedClasses, // [OUT] Array of nested class tokens. - ULONG ulNestedClasses, // [IN] Size of array. - ULONG *pcNestedClasses) - { - return m_pRawInternalImport->GetNestedClasses(tkEnclosingClass, rNestedClasses, ulNestedClasses, pcNestedClasses); - } - - // return the ModuleRef properties - // returned void in v1.0/v1.1 - __checkReturn - STDMETHODIMP GetModuleRefProps( - mdModuleRef mur, // [IN] moduleref token - LPCSTR *pszName) // [OUT] buffer to fill with the moduleref name - { - return m_pRawInternalImport->GetModuleRefProps(mur, pszName); - } - - //***************************************** - // - // GetSig* functions - // - //***************************************** - __checkReturn - STDMETHODIMP GetSigOfMethodDef( - mdMethodDef methoddef, // [IN] given memberdef - ULONG *pcbSigBlob, // [OUT] count of bytes in the signature blob - PCCOR_SIGNATURE *ppSig) - { - return m_pWinMDAdapter->GetSignatureForToken( - methoddef, - NULL, - NULL, - ppSig, - pcbSigBlob, - m_pRawInternalImport); - } - - __checkReturn - STDMETHODIMP GetSigOfFieldDef( - mdFieldDef fielddef, // [IN] given fielddef - ULONG *pcbSigBlob, // [OUT] count of bytes in the signature blob - PCCOR_SIGNATURE *ppSig) - { - return m_pWinMDAdapter->GetSignatureForToken( - fielddef, - NULL, - NULL, - ppSig, - pcbSigBlob, - m_pRawInternalImport); - } - - __checkReturn - STDMETHODIMP GetSigFromToken( - mdToken tk, // FieldDef, MethodDef, Signature or TypeSpec token - ULONG * pcbSig, - PCCOR_SIGNATURE * ppSig) - { - if (TypeFromToken(tk) == mdtMethodDef) - { - return GetSigOfMethodDef(tk, pcbSig, ppSig); - } - else if (TypeFromToken(tk) == mdtFieldDef) - { - return GetSigOfFieldDef(tk, pcbSig, ppSig); - } - else if (TypeFromToken(tk) == mdtTypeSpec) - { - return GetTypeSpecFromToken(tk, ppSig, pcbSig); - } - // Note: mdtSignature is not part of public WinMD surface, so it does not need signature rewriting - just call the underlying "raw" implementation - return m_pRawInternalImport->GetSigFromToken(tk, pcbSig, ppSig); - } - - - - //***************************************** - // get method property - //***************************************** - __checkReturn - STDMETHODIMP GetMethodDefProps( - mdMethodDef md, // The method for which to get props. - DWORD *pdwFlags) - { - HRESULT hr; - IfFailGo(m_pRawInternalImport->GetMethodDefProps(md, pdwFlags)); - IfFailGo(m_pWinMDAdapter->ModifyMethodProps(md, pdwFlags, NULL, NULL, NULL)); - ErrExit: - return hr; - } - - //***************************************** - // return method implementation informaiton, like RVA and implflags - //***************************************** - // returned void in v1.0/v1.1 - __checkReturn - STDMETHODIMP GetMethodImplProps( - mdToken tk, // [IN] MethodDef - ULONG *pulCodeRVA, // [OUT] CodeRVA - DWORD *pdwImplFlags) // [OUT] Impl. Flags - { - HRESULT hr; - IfFailGo(m_pRawInternalImport->GetMethodImplProps(tk, pulCodeRVA, pdwImplFlags)); - IfFailGo(m_pWinMDAdapter->ModifyMethodProps(tk, NULL, pdwImplFlags, pulCodeRVA, NULL)); - ErrExit: - return hr; - } - - //***************************************** - // return method implementation informaiton, like RVA and implflags - //***************************************** - __checkReturn - STDMETHODIMP GetFieldRVA( - mdFieldDef fd, // [IN] fielddef - ULONG *pulCodeRVA) // [OUT] CodeRVA - { - return m_pRawInternalImport->GetFieldRVA(fd, pulCodeRVA); - } - - //***************************************** - // get field property - //***************************************** - __checkReturn - STDMETHODIMP GetFieldDefProps( - mdFieldDef fd, // [IN] given fielddef - DWORD *pdwFlags) // [OUT] return fdPublic, fdPrive, etc flags - { - HRESULT hr; - IfFailGo(m_pRawInternalImport->GetFieldDefProps(fd, pdwFlags)); - IfFailGo(m_pWinMDAdapter->ModifyFieldDefProps(fd, pdwFlags)); -ErrExit: - return hr; - } - - //***************************************************************************** - // return default value of a token(could be paramdef, fielddef, or property - //***************************************************************************** - __checkReturn - STDMETHODIMP GetDefaultValue( - mdToken tk, // [IN] given FieldDef, ParamDef, or Property - MDDefaultValue *pDefaultValue) // [OUT] default value to fill - { - return m_pRawInternalImport->GetDefaultValue(tk, pDefaultValue); - } - - - //***************************************** - // get dispid of a MethodDef or a FieldDef - //***************************************** - __checkReturn - STDMETHODIMP GetDispIdOfMemberDef( // return hresult - mdToken tk, // [IN] given methoddef or fielddef - ULONG *pDispid) // [OUT] Put the dispid here. - { - return m_pRawInternalImport->GetDispIdOfMemberDef(tk, pDispid); - } - - //***************************************** - // return TypeRef/TypeDef given an InterfaceImpl token - //***************************************** - __checkReturn - STDMETHODIMP GetTypeOfInterfaceImpl( // return the TypeRef/typedef token for the interfaceimpl - mdInterfaceImpl iiImpl, // given a interfaceimpl - mdToken *ptkType) - { - return m_pRawInternalImport->GetTypeOfInterfaceImpl(iiImpl, ptkType); - } - - //***************************************** - // look up function for TypeDef - //***************************************** - __checkReturn - STDMETHODIMP FindTypeDef( - LPCSTR szNamespace, // [IN] Namespace for the TypeDef. - LPCSTR szName, // [IN] Name of the TypeDef. - mdToken tkEnclosingClass, // [IN] TypeRef/TypeDef Token for the enclosing class. - mdTypeDef *ptypedef) // [IN] return typedef - { - return m_pWinMDAdapter->FindTypeDef(szNamespace, szName, tkEnclosingClass, ptypedef); - } - - //***************************************** - // return name and sig of a memberref - //***************************************** - __checkReturn - STDMETHODIMP GetNameAndSigOfMemberRef( // return name here - mdMemberRef memberref, // given memberref - PCCOR_SIGNATURE *ppvSigBlob, // [OUT] point to a blob value of CLR signature - ULONG *pcbSigBlob, // [OUT] count of bytes in the signature blob - LPCSTR *pszName) - { - HRESULT hr = S_OK; - PCCOR_SIGNATURE pOrigSig; - ULONG cbOrigSig; - - IfFailRet(m_pRawInternalImport->GetNameAndSigOfMemberRef(memberref, &pOrigSig, &cbOrigSig, pszName)); - IfFailRet(m_pWinMDAdapter->ModifyMemberProps(memberref, NULL, NULL, NULL, pszName)); - - return m_pWinMDAdapter->GetSignatureForToken( - memberref, - &pOrigSig, // ppOrigSig - &cbOrigSig, // pcbOrigSig - ppvSigBlob, - pcbSigBlob, - m_pRawInternalImport); - } - - //***************************************************************************** - // Given memberref, return the parent. It can be TypeRef, ModuleRef, MethodDef - //***************************************************************************** - __checkReturn - STDMETHODIMP GetParentOfMemberRef( - mdMemberRef memberref, // given memberref - mdToken *ptkParent) // return the parent token - { - return m_pRawInternalImport->GetParentOfMemberRef(memberref, ptkParent); - } - - __checkReturn - STDMETHODIMP GetParamDefProps( - mdParamDef paramdef, // given a paramdef - USHORT *pusSequence, // [OUT] slot number for this parameter - DWORD *pdwAttr, // [OUT] flags - LPCSTR *pszName) // [OUT] return the name of the parameter - { - return m_pRawInternalImport->GetParamDefProps(paramdef, pusSequence, pdwAttr, pszName); - } - - __checkReturn - STDMETHODIMP GetPropertyInfoForMethodDef( // Result. - mdMethodDef md, // [IN] memberdef - mdProperty *ppd, // [OUT] put property token here - LPCSTR *pName, // [OUT] put pointer to name here - ULONG *pSemantic) // [OUT] put semantic here - { - return m_pRawInternalImport->GetPropertyInfoForMethodDef(md, ppd, pName, pSemantic); - } - - //***************************************** - // class layout/sequence information - //***************************************** - __checkReturn - STDMETHODIMP GetClassPackSize( // return error if class doesn't have packsize - mdTypeDef td, // [IN] give typedef - ULONG *pdwPackSize) // [OUT] 1, 2, 4, 8, or 16 - { - return m_pRawInternalImport->GetClassPackSize(td, pdwPackSize); - } - - __checkReturn - STDMETHODIMP GetClassTotalSize( // return error if class doesn't have total size info - mdTypeDef td, // [IN] give typedef - ULONG *pdwClassSize) // [OUT] return the total size of the class - { - return m_pRawInternalImport->GetClassTotalSize(td, pdwClassSize); - } - - __checkReturn - STDMETHODIMP GetClassLayoutInit( - mdTypeDef td, // [IN] give typedef - MD_CLASS_LAYOUT *pLayout) // [OUT] set up the status of query here - { - return m_pRawInternalImport->GetClassLayoutInit(td, pLayout); - } - - __checkReturn - STDMETHODIMP GetClassLayoutNext( - MD_CLASS_LAYOUT *pLayout, // [IN|OUT] set up the status of query here - mdFieldDef *pfd, // [OUT] return the fielddef - ULONG *pulOffset) // [OUT] return the offset/ulSequence associate with it - { - return m_pRawInternalImport->GetClassLayoutNext(pLayout, pfd, pulOffset); - } - - //***************************************** - // marshal information of a field - //***************************************** - __checkReturn - STDMETHODIMP GetFieldMarshal( // return error if no native type associate with the token - mdFieldDef fd, // [IN] given fielddef - PCCOR_SIGNATURE *pSigNativeType, // [OUT] the native type signature - ULONG *pcbNativeType) // [OUT] the count of bytes of *ppvNativeType - { - return m_pRawInternalImport->GetFieldMarshal(fd, pSigNativeType, pcbNativeType); - } - - - //***************************************** - // property APIs - //***************************************** - // find a property by name - __checkReturn - STDMETHODIMP FindProperty( - mdTypeDef td, // [IN] given a typdef - LPCSTR szPropName, // [IN] property name - mdProperty *pProp) // [OUT] return property token - { - return m_pRawInternalImport->FindProperty(td, szPropName, pProp); - } - - // returned void in v1.0/v1.1 - __checkReturn - STDMETHODIMP GetPropertyProps( - mdProperty prop, // [IN] property token - LPCSTR *szProperty, // [OUT] property name - DWORD *pdwPropFlags, // [OUT] property flags. - PCCOR_SIGNATURE *ppvSig, // [OUT] property type. pointing to meta data internal blob - ULONG *pcbSig) // [OUT] count of bytes in *ppvSig - { - HRESULT hr = S_OK; - PCCOR_SIGNATURE pOrigSig; - ULONG cbOrigSig; - - IfFailRet(m_pRawInternalImport->GetPropertyProps(prop, szProperty, pdwPropFlags, &pOrigSig, &cbOrigSig)); - - return m_pWinMDAdapter->GetSignatureForToken( - prop, - &pOrigSig, // ppOrigSig - &cbOrigSig, // pcbOrigSig - ppvSig, - pcbSig, - m_pRawInternalImport); - } - - //********************************** - // Event APIs - //********************************** - __checkReturn - STDMETHODIMP FindEvent( - mdTypeDef td, // [IN] given a typdef - LPCSTR szEventName, // [IN] event name - mdEvent *pEvent) // [OUT] return event token - { - return m_pRawInternalImport->FindEvent(td, szEventName, pEvent); - } - - // returned void in v1.0/v1.1 - __checkReturn - STDMETHODIMP GetEventProps( - mdEvent ev, // [IN] event token - LPCSTR *pszEvent, // [OUT] Event name - DWORD *pdwEventFlags, // [OUT] Event flags. - mdToken *ptkEventType) // [OUT] EventType class - { - return m_pRawInternalImport->GetEventProps(ev, pszEvent, pdwEventFlags, ptkEventType); - } - - - //********************************** - // find a particular associate of a property or an event - //********************************** - __checkReturn - STDMETHODIMP FindAssociate( - mdToken evprop, // [IN] given a property or event token - DWORD associate, // [IN] given a associate semantics(setter, getter, testdefault, reset, AddOn, RemoveOn, Fire) - mdMethodDef *pmd) // [OUT] return method def token - { - return m_pRawInternalImport->FindAssociate(evprop, associate, pmd); - } - - // Note, void function in v1.0/v1.1 - __checkReturn - STDMETHODIMP EnumAssociateInit( - mdToken evprop, // [IN] given a property or an event token - HENUMInternal *phEnum) // [OUT] cursor to hold the query result - { - return m_pRawInternalImport->EnumAssociateInit(evprop, phEnum); - } - - // returned void in v1.0/v1.1 - __checkReturn - STDMETHODIMP GetAllAssociates( - HENUMInternal *phEnum, // [IN] query result form GetPropertyAssociateCounts - ASSOCIATE_RECORD *pAssociateRec, // [OUT] struct to fill for output - ULONG cAssociateRec) // [IN] size of the buffer - { - return m_pRawInternalImport->GetAllAssociates(phEnum, pAssociateRec, cAssociateRec); - } - - - //********************************** - // Get info about a PermissionSet. - //********************************** - // returned void in v1.0/v1.1 - __checkReturn - STDMETHODIMP GetPermissionSetProps( - mdPermission pm, // [IN] the permission token. - DWORD *pdwAction, // [OUT] CorDeclSecurity. - void const **ppvPermission, // [OUT] permission blob. - ULONG *pcbPermission) // [OUT] count of bytes of pvPermission. - { - return m_pRawInternalImport->GetPermissionSetProps(pm, pdwAction, ppvPermission, pcbPermission); - } - - //**************************************** - // Get the String given the String token. - // Returns a pointer to the string, or NULL in case of error. - //**************************************** - __checkReturn - STDMETHODIMP GetUserString( - mdString stk, // [IN] the string token. - ULONG *pchString, // [OUT] count of characters in the string. - BOOL *pbIs80Plus, // [OUT] specifies where there are extended characters >= 0x80. - LPCWSTR *pwszUserString) - { - return m_pRawInternalImport->GetUserString(stk, pchString, pbIs80Plus, pwszUserString); - } - - //***************************************************************************** - // p-invoke APIs. - //***************************************************************************** - __checkReturn - STDMETHODIMP GetPinvokeMap( - mdToken tk, // [IN] FieldDef, MethodDef. - DWORD *pdwMappingFlags, // [OUT] Flags used for mapping. - LPCSTR *pszImportName, // [OUT] Import name. - mdModuleRef *pmrImportDLL) // [OUT] ModuleRef token for the target DLL. - { - return m_pRawInternalImport->GetPinvokeMap(tk, pdwMappingFlags, pszImportName, pmrImportDLL); - } - - //***************************************************************************** - // helpers to convert a text signature to a com format - //***************************************************************************** - __checkReturn - STDMETHODIMP ConvertTextSigToComSig( // Return hresult. - BOOL fCreateTrIfNotFound, // [IN] create typeref if not found - LPCSTR pSignature, // [IN] class file format signature - CQuickBytes *pqbNewSig, // [OUT] place holder for CLR signature - ULONG *pcbCount) // [OUT] the result size of signature - { - return m_pRawInternalImport->ConvertTextSigToComSig(fCreateTrIfNotFound, pSignature, pqbNewSig, pcbCount); - } - - //***************************************************************************** - // Assembly MetaData APIs. - //***************************************************************************** - // returned void in v1.0/v1.1 - __checkReturn - STDMETHODIMP GetAssemblyProps( - mdAssembly mda, // [IN] The Assembly for which to get the properties. - const void **ppbPublicKey, // [OUT] Pointer to the public key. - ULONG *pcbPublicKey, // [OUT] Count of bytes in the public key. - ULONG *pulHashAlgId, // [OUT] Hash Algorithm. - LPCSTR *pszName, // [OUT] Buffer to fill with name. - AssemblyMetaDataInternal *pMetaData,// [OUT] Assembly MetaData. - DWORD *pdwAssemblyFlags) // [OUT] Flags. - { - return m_pRawInternalImport->GetAssemblyProps(mda, ppbPublicKey, pcbPublicKey, pulHashAlgId, pszName, pMetaData, pdwAssemblyFlags); - } - - // returned void in v1.0/v1.1 - __checkReturn - STDMETHODIMP GetAssemblyRefProps( - mdAssemblyRef mdar, // [IN] The AssemblyRef for which to get the properties. - const void **ppbPublicKeyOrToken, // [OUT] Pointer to the public key or token. - ULONG *pcbPublicKeyOrToken, // [OUT] Count of bytes in the public key or token. - LPCSTR *pszName, // [OUT] Buffer to fill with name. - AssemblyMetaDataInternal *pMetaData,// [OUT] Assembly MetaData. - const void **ppbHashValue, // [OUT] Hash blob. - ULONG *pcbHashValue, // [OUT] Count of bytes in the hash blob. - DWORD *pdwAssemblyRefFlags) // [OUT] Flags. - { - HRESULT hr; - mdAssemblyRef md = mdar; - if (RidFromToken(md) > m_pWinMDAdapter->GetRawAssemblyRefCount()) - { - // The extra framework assemblies we add references to should all have the - // same verion, key, culture, etc as those of mscorlib. - // So we retrieve the mscorlib properties and change the name. - md = m_pWinMDAdapter->GetAssemblyRefMscorlib(); - } - - IfFailRet(m_pRawInternalImport->GetAssemblyRefProps(md, ppbPublicKeyOrToken, pcbPublicKeyOrToken, pszName, pMetaData, ppbHashValue, pcbHashValue, pdwAssemblyRefFlags)); - - USHORT *pusMajorVersion = nullptr; - USHORT *pusMinorVersion = nullptr; - USHORT *pusBuildNumber = nullptr; - USHORT *pusRevisionNumber = nullptr; - - if (pMetaData != nullptr) - { - pusMajorVersion = &pMetaData->usMajorVersion; - pusMinorVersion = &pMetaData->usMinorVersion; - pusBuildNumber = &pMetaData->usBuildNumber; - pusRevisionNumber = &pMetaData->usRevisionNumber; - } - - m_pWinMDAdapter->ModifyAssemblyRefProps( - mdar, - ppbPublicKeyOrToken, - pcbPublicKeyOrToken, - pszName, - pusMajorVersion, - pusMinorVersion, - pusBuildNumber, - pusRevisionNumber, - ppbHashValue, - pcbHashValue); - - return hr; - } - - // returned void in v1.0/v1.1 - __checkReturn - STDMETHODIMP GetFileProps( - mdFile mdf, // [IN] The File for which to get the properties. - LPCSTR *pszName, // [OUT] Buffer to fill with name. - const void **ppbHashValue, // [OUT] Pointer to the Hash Value Blob. - ULONG *pcbHashValue, // [OUT] Count of bytes in the Hash Value Blob. - DWORD *pdwFileFlags) // [OUT] Flags. - { - return m_pRawInternalImport->GetFileProps(mdf, pszName, ppbHashValue, pcbHashValue, pdwFileFlags); - } - - // returned void in v1.0/v1.1 - __checkReturn - STDMETHODIMP GetExportedTypeProps( - mdExportedType mdct, // [IN] The ExportedType for which to get the properties. - LPCSTR *pszNamespace, // [OUT] Namespace. - LPCSTR *pszName, // [OUT] Name. - mdToken *ptkImplementation, // [OUT] mdFile or mdAssemblyRef that provides the ExportedType. - mdTypeDef *ptkTypeDef, // [OUT] TypeDef token within the file. - DWORD *pdwExportedTypeFlags) // [OUT] Flags. - { - HRESULT hr; - IfFailRet(m_pRawInternalImport->GetExportedTypeProps(mdct, pszNamespace, pszName, ptkImplementation, ptkTypeDef, pdwExportedTypeFlags)); - IfFailRet(m_pWinMDAdapter->ModifyExportedTypeName(mdct, pszNamespace, pszName)); - return hr; - } - - // returned void in v1.0/v1.1 - __checkReturn - STDMETHODIMP GetManifestResourceProps( - mdManifestResource mdmr, // [IN] The ManifestResource for which to get the properties. - LPCSTR *pszName, // [OUT] Buffer to fill with name. - mdToken *ptkImplementation, // [OUT] mdFile or mdAssemblyRef that provides the ExportedType. - DWORD *pdwOffset, // [OUT] Offset to the beginning of the resource within the file. - DWORD *pdwResourceFlags) // [OUT] Flags. - { - return m_pRawInternalImport->GetManifestResourceProps(mdmr, pszName, ptkImplementation, pdwOffset, pdwResourceFlags); - } - - __checkReturn - STDMETHODIMP FindExportedTypeByName( // S_OK or error - LPCSTR szNamespace, // [IN] Namespace of the ExportedType. - LPCSTR szName, // [IN] Name of the ExportedType. - mdExportedType tkEnclosingType, // [IN] ExportedType for the enclosing class. - mdExportedType *pmct) // [OUT] Put ExportedType token here. - { - return m_pWinMDAdapter->FindExportedType(szNamespace, szName, tkEnclosingType, pmct); - } - - __checkReturn - STDMETHODIMP FindManifestResourceByName( // S_OK or error - LPCSTR szName, // [IN] Name of the ManifestResource. - mdManifestResource *pmmr) // [OUT] Put ManifestResource token here. - { - return m_pRawInternalImport->FindManifestResourceByName(szName, pmmr); - } - - __checkReturn - STDMETHODIMP GetAssemblyFromScope( // S_OK or error - mdAssembly *ptkAssembly) // [OUT] Put token here. - { - return m_pRawInternalImport->GetAssemblyFromScope(ptkAssembly); - } - - __checkReturn - STDMETHODIMP GetCustomAttributeByName( // S_OK or error - mdToken tkObj, // [IN] Object with Custom Attribute. - LPCUTF8 szName, // [IN] Name of desired Custom Attribute. - const void **ppData, // [OUT] Put pointer to data here. - ULONG *pcbData) // [OUT] Put size of data here. - { - return m_pWinMDAdapter->GetCustomAttributeByName(tkObj, szName, NULL, ppData, pcbData); - } - - // Note: The return type of this method was void in v1 - __checkReturn - STDMETHODIMP GetTypeSpecFromToken( // S_OK or error. - mdTypeSpec typespec, // [IN] Signature token. - PCCOR_SIGNATURE *ppvSig, // [OUT] return pointer to token. - ULONG *pcbSig) // [OUT] return size of signature. - { - return m_pWinMDAdapter->GetSignatureForToken( - typespec, - NULL, // ppOrigSig - NULL, // pcbOrigSig - ppvSig, - pcbSig, - m_pRawInternalImport); - } - - __checkReturn - STDMETHODIMP SetUserContextData( // S_OK or E_NOTIMPL - IUnknown *pIUnk) // The user context. - { - return m_pRawInternalImport->SetUserContextData(pIUnk); - } - - __checkReturn - STDMETHODIMP_(BOOL) IsValidToken( // True or False. - mdToken tk) // [IN] Given token. - { - if (TypeFromToken(tk) == mdtAssemblyRef) - return m_pWinMDAdapter->IsValidAssemblyRefToken(tk); - - return m_pRawInternalImport->IsValidToken(tk); - } - - - __checkReturn - STDMETHODIMP TranslateSigWithScope( - IMDInternalImport* pAssemImport, // [IN] import assembly scope. - const void* pbHashValue, // [IN] hash value for the import assembly. - ULONG cbHashValue, // [IN] count of bytes in the hash value. - PCCOR_SIGNATURE pbSigBlob, // [IN] signature in the importing scope - ULONG cbSigBlob, // [IN] count of bytes of signature - IMetaDataAssemblyEmit* pAssemEmit, // [IN] assembly emit scope. - IMetaDataEmit* emit, // [IN] emit interface - CQuickBytes* pqkSigEmit, // [OUT] buffer to hold translated signature - ULONG* pcbSig) // [OUT] count of bytes in the translated signature - { - return TranslateSigHelper( - this, - pAssemImport, - pbHashValue, - cbHashValue, - pbSigBlob, - cbSigBlob, - pAssemEmit, - emit, - pqkSigEmit, - pcbSig); - } - - - STDMETHODIMP_(IMetaModelCommon*) GetMetaModelCommon() // Return MetaModelCommon interface. - { - return static_cast(this); - } - - STDMETHODIMP_(IUnknown *) GetCachedPublicInterface(BOOL fWithLock) // return the cached public interface - { - return m_pRawInternalImport->GetCachedPublicInterface(fWithLock); - } - __checkReturn - - STDMETHODIMP SetCachedPublicInterface(IUnknown *pUnk) // no return value - { - return m_pRawInternalImport->SetCachedPublicInterface(pUnk); - } - - STDMETHODIMP_(UTSemReadWrite*) GetReaderWriterLock() // return the reader writer lock - { - return m_pRawInternalImport->GetReaderWriterLock(); - } - - __checkReturn - STDMETHODIMP SetReaderWriterLock(UTSemReadWrite * pSem) - { - return m_pRawInternalImport->SetReaderWriterLock(pSem); - } - - STDMETHODIMP_(mdModule) GetModuleFromScope() // [OUT] Put mdModule token here. - { - return m_pRawInternalImport->GetModuleFromScope(); - } - - - //----------------------------------------------------------------- - // Additional custom methods - - // finding a particular method - __checkReturn - STDMETHODIMP FindMethodDefUsingCompare( - mdTypeDef classdef, // [IN] given typedef - LPCSTR szName, // [IN] member name - PCCOR_SIGNATURE pvSigBlob, // [IN] point to a blob value of CLR signature - ULONG cbSigBlob, // [IN] count of bytes in the signature blob - PSIGCOMPARE pSignatureCompare, // [IN] Routine to compare signatures - void* pSignatureArgs, // [IN] Additional info to supply the compare function - mdMethodDef *pmd) // [OUT] matching memberdef - { - if (pvSigBlob == NULL || cbSigBlob == 0 || pSignatureCompare == NULL) - { - // if signature matching is not needed, we can delegate to the underlying implementation - return m_pRawInternalImport->FindMethodDefUsingCompare(classdef, szName, pvSigBlob, cbSigBlob, pSignatureCompare, pSignatureArgs, pmd); - } - - // The following code emulates MDInternalRO::FindMethodDefUsingCompare. We cannot call the underlying - // implementation because we need to compare pvSigBlob to reinterpreted signatures. - _ASSERTE(szName && pmd); - - HRESULT hr = S_OK; - HENUMInternal hEnum; - - CQuickBytes qbSig; // holds non-varargs signature - - *pmd = mdMethodDefNil; - - // check to see if this is a vararg signature - PCCOR_SIGNATURE pvSigTemp = pvSigBlob; - if (isCallConv(CorSigUncompressCallingConv(pvSigTemp), IMAGE_CEE_CS_CALLCONV_VARARG)) - { - // Get the fixed part of VARARG signature - IfFailGo(_GetFixedSigOfVarArg(pvSigBlob, cbSigBlob, &qbSig, &cbSigBlob)); - pvSigBlob = (PCCOR_SIGNATURE) qbSig.Ptr(); - } - - // now iterate all methods in td and compare name and signature - IfFailGo(EnumInit(mdtMethodDef, classdef, &hEnum)); - - mdMethodDef md; - while(EnumNext(&hEnum, &md)) - { - PCCOR_SIGNATURE pvMethodSigBlob; - ULONG cbMethodSigBlob; - LPCSTR szMethodName; - - IfFailGo(GetNameAndSigOfMethodDef(md, &pvMethodSigBlob, &cbMethodSigBlob, &szMethodName)); - - if (strcmp(szName, szMethodName) == 0) - { - // we have a name match, check signature - if (pSignatureCompare(pvMethodSigBlob, cbMethodSigBlob, pvSigBlob, cbSigBlob, pSignatureArgs) == FALSE) - continue; - - // ignore PrivateScope methods - DWORD dwMethodAttr; - IfFailGo(GetMethodDefProps(md, &dwMethodAttr)); - - if (IsMdPrivateScope(dwMethodAttr)) - continue; - - // we found the method - *pmd = md; - goto ErrExit; - } - } - hr = CLDB_E_RECORD_NOTFOUND; - - ErrExit: - EnumClose(&hEnum); - return hr; - } - - // Additional v2 methods. - - //***************************************** - // return a field offset for a given field - //***************************************** - __checkReturn - STDMETHODIMP GetFieldOffset( - mdFieldDef fd, // [IN] fielddef - ULONG *pulOffset) // [OUT] FieldOffset - { - return m_pRawInternalImport->GetFieldOffset(fd, pulOffset); - } - - __checkReturn - STDMETHODIMP GetMethodSpecProps( - mdMethodSpec ms, // [IN] The method instantiation - mdToken *tkParent, // [OUT] MethodDef or MemberRef - PCCOR_SIGNATURE *ppvSigBlob, // [OUT] point to the blob value of meta data - ULONG *pcbSigBlob) // [OUT] actual size of signature blob - { - HRESULT hr = S_OK; - PCCOR_SIGNATURE pOrigSig; - ULONG cbOrigSig; - - IfFailRet(m_pRawInternalImport->GetMethodSpecProps(ms, tkParent, &pOrigSig, &cbOrigSig)); - - return m_pWinMDAdapter->GetSignatureForToken( - ms, - &pOrigSig, // ppOrigSig - &cbOrigSig, // pcbOrigSig - ppvSigBlob, - pcbSigBlob, - m_pRawInternalImport); - } - - __checkReturn - STDMETHODIMP GetTableInfoWithIndex( - ULONG index, // [IN] pass in the table index - void **pTable, // [OUT] pointer to table at index - void **pTableSize) // [OUT] size of table at index - { - // This abstraction breaker is apparently used only by SOS... at this time of writing. - return m_pRawInternalImport->GetTableInfoWithIndex(index, pTable, pTableSize); - } - - __checkReturn - STDMETHODIMP ApplyEditAndContinue( - void *pDeltaMD, // [IN] the delta metadata - ULONG cbDeltaMD, // [IN] length of pData - IMDInternalImport **ppv) // [OUT] the resulting metadata interface - { - WINMD_COMPAT_ASSERT("IMDInternalImport::ApplyEditAndContinue() not supported on .winmd files."); - return E_NOTIMPL; - } - - //********************************** - // Generics APIs - //********************************** - __checkReturn - STDMETHODIMP GetGenericParamProps( // S_OK or error. - mdGenericParam rd, // [IN] The type parameter - ULONG* pulSequence, // [OUT] Parameter sequence number - DWORD* pdwAttr, // [OUT] Type parameter flags (for future use) - mdToken *ptOwner, // [OUT] The owner (TypeDef or MethodDef) - DWORD *reserved, // [OUT] The kind (TypeDef/Ref/Spec, for future use) - LPCSTR *szName) // [OUT] The name - { - return m_pRawInternalImport->GetGenericParamProps(rd, pulSequence, pdwAttr, ptOwner, reserved, szName); - } - - __checkReturn - STDMETHODIMP GetGenericParamConstraintProps( // S_OK or error. - mdGenericParamConstraint rd, // [IN] The constraint token - mdGenericParam *ptGenericParam, // [OUT] GenericParam that is constrained - mdToken *ptkConstraintType) // [OUT] TypeDef/Ref/Spec constraint - { - return m_pRawInternalImport->GetGenericParamConstraintProps(rd, ptGenericParam, ptkConstraintType); - } - - //***************************************************************************** - // This function gets the "built for" version of a metadata scope. - // NOTE: if the scope has never been saved, it will not have a built-for - // version, and an empty string will be returned. - //***************************************************************************** - __checkReturn - STDMETHODIMP GetVersionString( // S_OK or error. - LPCSTR *pVer) // [OUT] Put version string here. - { - return m_pWinMDAdapter->GetVersionString(pVer); - } - - __checkReturn - STDMETHODIMP GetTypeDefRefTokenInTypeSpec(// return S_FALSE if enclosing type does not have a token - mdTypeSpec tkTypeSpec, // [IN] TypeSpec token to look at - mdToken *tkEnclosedToken) // [OUT] The enclosed type token - { - return m_pRawInternalImport->GetTypeDefRefTokenInTypeSpec(tkTypeSpec, tkEnclosedToken); - } - - STDMETHODIMP_(DWORD) GetMetadataStreamVersion() //returns DWORD with major version of - // MD stream in senior word and minor version--in junior word - { - return m_pRawInternalImport->GetMetadataStreamVersion(); - } - - __checkReturn - STDMETHODIMP GetNameOfCustomAttribute(// S_OK or error - mdCustomAttribute mdAttribute, // [IN] The Custom Attribute - LPCUTF8 *pszNamespace, // [OUT] Namespace of Custom Attribute. - LPCUTF8 *pszName) // [OUT] Name of Custom Attribute. - { - HRESULT hr; - IfFailRet(m_pRawInternalImport->GetNameOfCustomAttribute(mdAttribute, pszNamespace, pszName)); - WinMDAdapter::ConvertWellKnownTypeNameFromWinRTToClr(pszNamespace, pszName); - return hr; - } - - STDMETHODIMP SetOptimizeAccessForSpeed(// S_OK or error - BOOL fOptSpeed) - { - return m_pRawInternalImport->SetOptimizeAccessForSpeed(fOptSpeed); - } - - STDMETHODIMP SetVerifiedByTrustedSource(// S_OK or error - BOOL fVerified) - { - return m_pRawInternalImport->SetVerifiedByTrustedSource(fVerified); - } - - STDMETHODIMP GetRvaOffsetData(// S_OK or error - DWORD *pFirstMethodRvaOffset, // [OUT] Offset (from start of metadata) to the first RVA field in MethodDef table. - DWORD *pMethodDefRecordSize, // [OUT] Size of each record in MethodDef table. - DWORD *pMethodDefCount, // [OUT] Number of records in MethodDef table. - DWORD *pFirstFieldRvaOffset, // [OUT] Offset (from start of metadata) to the first RVA field in FieldRVA table. - DWORD *pFieldRvaRecordSize, // [OUT] Size of each record in FieldRVA table. - DWORD *pFieldRvaCount) // [OUT] Number of records in FieldRVA table. - { - return m_pRawInternalImport->GetRvaOffsetData( - pFirstMethodRvaOffset, - pMethodDefRecordSize, - pMethodDefCount, - pFirstFieldRvaOffset, - pFieldRvaRecordSize, - pFieldRvaCount); - } - - - // ******************************************************************************** - // **************** Implementation of IMetaModelCommon methods ******************** - // ******************************************************************************** - - __checkReturn - HRESULT CommonGetScopeProps( - LPCUTF8 *pszName, - GUID *pMvid) - { - return m_pRawMetaModelCommon->CommonGetScopeProps(pszName, pMvid); - } - - __checkReturn - HRESULT CommonGetTypeRefProps( - mdTypeRef tr, - LPCUTF8 *pszNamespace, - LPCUTF8 *pszName, - mdToken *ptkResolution) - { - return m_pWinMDAdapter->GetTypeRefProps(tr, pszNamespace, pszName, ptkResolution); - } - - __checkReturn - HRESULT CommonGetTypeDefProps( - mdTypeDef td, - LPCUTF8 *pszNameSpace, - LPCUTF8 *pszName, - DWORD *pdwFlags, - mdToken *pdwExtends, - ULONG *pMethodList) - { - // We currently don't support retrieving the method list. - if (pMethodList) - return E_NOTIMPL; - - return m_pWinMDAdapter->GetTypeDefProps(td, pszNameSpace, pszName, pdwFlags, pdwExtends); - } - - __checkReturn - HRESULT CommonGetTypeSpecProps( - mdTypeSpec ts, - PCCOR_SIGNATURE *ppvSig, - ULONG *pcbSig) - { - return m_pWinMDAdapter->GetSignatureForToken( - ts, - NULL, // ppOrigSig - NULL, // pcbOrigSig - ppvSig, - pcbSig, - m_pRawInternalImport); - } - - __checkReturn - HRESULT CommonGetEnclosingClassOfTypeDef( - mdTypeDef td, - mdTypeDef *ptkEnclosingTypeDef) - { - return m_pRawMetaModelCommon->CommonGetEnclosingClassOfTypeDef(td, ptkEnclosingTypeDef); - } - - __checkReturn - HRESULT CommonGetAssemblyProps( - USHORT *pusMajorVersion, - USHORT *pusMinorVersion, - USHORT *pusBuildNumber, - USHORT *pusRevisionNumber, - DWORD *pdwFlags, - const void **ppbPublicKey, - ULONG *pcbPublicKey, - LPCUTF8 *pszName, - LPCUTF8 *pszLocale) - { - HRESULT hr; - AssemblyMetaDataInternal MetaData; - mdToken tkAssembly = TokenFromRid(1, mdtAssembly); - - IfFailRet(GetAssemblyProps( - tkAssembly, - ppbPublicKey, - pcbPublicKey, - NULL, - pszName, - &MetaData, - pdwFlags)); - - if (pusMajorVersion) - *pusMajorVersion = MetaData.usMajorVersion; - if (pusMinorVersion) - *pusMinorVersion = MetaData.usMinorVersion; - if (pusBuildNumber) - *pusBuildNumber = MetaData.usBuildNumber; - if (pusRevisionNumber) - *pusRevisionNumber = MetaData.usRevisionNumber; - if (pszLocale) - *pszLocale = MetaData.szLocale; - - return S_OK; - } - - __checkReturn - HRESULT CommonGetAssemblyRefProps( - mdAssemblyRef tkAssemRef, - USHORT *pusMajorVersion, - USHORT *pusMinorVersion, - USHORT *pusBuildNumber, - USHORT *pusRevisionNumber, - DWORD *pdwFlags, - const void **ppbPublicKeyOrToken, - ULONG *pcbPublicKeyOrToken, - LPCUTF8 *pszName, - LPCUTF8 *pszLocale, - const void **ppbHashValue, - ULONG *pcbHashValue) - { - HRESULT hr; - - AssemblyMetaDataInternal MetaData; - IfFailRet(GetAssemblyRefProps( - tkAssemRef, - ppbPublicKeyOrToken, - pcbPublicKeyOrToken, - pszName, - &MetaData, - ppbHashValue, - pcbHashValue, - pdwFlags)); - - if (pusMajorVersion) - *pusMajorVersion = MetaData.usMajorVersion; - if (pusMinorVersion) - *pusMinorVersion = MetaData.usMinorVersion; - if (pusBuildNumber) - *pusBuildNumber = MetaData.usBuildNumber; - if (pusRevisionNumber) - *pusRevisionNumber = MetaData.usRevisionNumber; - if (pszLocale) - *pszLocale = MetaData.szLocale; - - return S_OK; - } - - __checkReturn - HRESULT CommonGetModuleRefProps( - mdModuleRef tkModuleRef, - LPCUTF8 *pszName) - { - return m_pRawMetaModelCommon->CommonGetModuleRefProps(tkModuleRef, pszName); - } - - __checkReturn - HRESULT CommonFindExportedType( - LPCUTF8 szNamespace, - LPCUTF8 szName, - mdToken tkEnclosingType, - mdExportedType *ptkExportedType) - { - return m_pWinMDAdapter->FindExportedType(szNamespace, szName, tkEnclosingType, ptkExportedType); - } - - __checkReturn - HRESULT CommonGetExportedTypeProps( - mdToken tkExportedType, - LPCUTF8 *pszNamespace, - LPCUTF8 *pszName, - mdToken *ptkImpl) - { - return GetExportedTypeProps( - tkExportedType, - pszNamespace, - pszName, - ptkImpl, - NULL, - NULL); - } - - __checkReturn - HRESULT CommonGetCustomAttributeByNameEx( // S_OK or error. - mdToken tkObj, // [IN] Object with Custom Attribute. - LPCUTF8 szName, // [IN] Name of desired Custom Attribute. - mdCustomAttribute *ptkCA, // [OUT] put custom attribute token here - const void **ppData, // [OUT] Put pointer to data here. - ULONG *pcbData) // [OUT] Put size of data here. - { - return m_pWinMDAdapter->GetCustomAttributeByName(tkObj, szName, ptkCA, ppData, pcbData); - } - - __checkReturn - HRESULT FindParentOfMethodHelper(mdMethodDef md, mdTypeDef *ptd) - { - return m_pRawMetaModelCommon->FindParentOfMethodHelper(md, ptd); - } - - int CommonIsRo() - { - return m_pRawMetaModelCommon->CommonIsRo(); - } - - private: - //========================================================= - // Private instance data - //========================================================= - IMDCommon *m_pRawMDCommon; - IMetaModelCommon *m_pRawMetaModelCommon; - IMDInternalImport *m_pRawInternalImport; - WinMDAdapter *m_pWinMDAdapter; - LONG m_cRef; -}; // class WinMDInternalImportRO - - - - -//======================================================================================== -// Entrypoint called by GetMDInternalInterface() -//======================================================================================== -HRESULT CreateWinMDInternalImportRO(IMDCommon * pRawMDCommon, REFIID riid, /*[out]*/ void **ppWinMDInternalImport) -{ - HRESULT hr; - *ppWinMDInternalImport = NULL; - WinMDInternalImportRO *pNewImport = NULL; - IfFailGo(WinMDInternalImportRO::Create(pRawMDCommon, &pNewImport)); - IfFailGo(pNewImport->QueryInterface(riid, ppWinMDInternalImport)); - hr = S_OK; - - ErrExit: - if (pNewImport) - pNewImport->Release(); - return hr; - -} - -#endif // FEATURE_METADATA_INTERNAL_APIS - - - diff --git a/src/coreclr/src/pal/prebuilt/idl/clrprivbinding_i.cpp b/src/coreclr/src/pal/prebuilt/idl/clrprivbinding_i.cpp index 3aead62..5584a55 100644 --- a/src/coreclr/src/pal/prebuilt/idl/clrprivbinding_i.cpp +++ b/src/coreclr/src/pal/prebuilt/idl/clrprivbinding_i.cpp @@ -78,9 +78,6 @@ MIDL_DEFINE_GUID(IID, IID_ICLRPrivResourceAssembly,0x8d2d3cc9,0x1249,0x4ad4,0x97 MIDL_DEFINE_GUID(IID, IID_ICLRPrivAssemblyInfo,0x5653946E,0x800B,0x48B7,0x8B,0x09,0xB1,0xB8,0x79,0xB5,0x4F,0x68); - -MIDL_DEFINE_GUID(IID, IID_ICLRPrivAssemblyID_WinRT,0x4372D277,0x9906,0x4FED,0xBF,0x53,0x30,0xC0,0xB4,0x01,0x08,0x96); - #undef MIDL_DEFINE_GUID #ifdef __cplusplus diff --git a/src/coreclr/src/pal/prebuilt/inc/clrprivbinding.h b/src/coreclr/src/pal/prebuilt/inc/clrprivbinding.h index 61094d1..543d277 100644 --- a/src/coreclr/src/pal/prebuilt/inc/clrprivbinding.h +++ b/src/coreclr/src/pal/prebuilt/inc/clrprivbinding.h @@ -81,13 +81,6 @@ typedef interface ICLRPrivAssemblyInfo ICLRPrivAssemblyInfo; #endif /* __ICLRPrivAssemblyInfo_FWD_DEFINED__ */ -#ifndef __ICLRPrivAssemblyID_WinRT_FWD_DEFINED__ -#define __ICLRPrivAssemblyID_WinRT_FWD_DEFINED__ -typedef interface ICLRPrivAssemblyID_WinRT ICLRPrivAssemblyID_WinRT; - -#endif /* __ICLRPrivAssemblyID_WinRT_FWD_DEFINED__ */ - - /* header files for imported files */ #include "unknwn.h" #include "objidl.h" @@ -706,76 +699,6 @@ EXTERN_C const IID IID_ICLRPrivAssemblyInfo; #endif /* __ICLRPrivAssemblyInfo_INTERFACE_DEFINED__ */ -#ifndef __ICLRPrivAssemblyID_WinRT_INTERFACE_DEFINED__ -#define __ICLRPrivAssemblyID_WinRT_INTERFACE_DEFINED__ - -/* interface ICLRPrivAssemblyID_WinRT */ -/* [object][local][version][uuid] */ - - -EXTERN_C const IID IID_ICLRPrivAssemblyID_WinRT; - -#if defined(__cplusplus) && !defined(CINTERFACE) - - MIDL_INTERFACE("4372D277-9906-4FED-BF53-30C0B4010896") - ICLRPrivAssemblyID_WinRT : public IUnknown - { - public: - }; - - -#else /* C style interface */ - - typedef struct ICLRPrivAssemblyID_WinRTVtbl - { - BEGIN_INTERFACE - - HRESULT ( STDMETHODCALLTYPE *QueryInterface )( - ICLRPrivAssemblyID_WinRT * This, - /* [in] */ REFIID riid, - /* [annotation][iid_is][out] */ - _COM_Outptr_ void **ppvObject); - - ULONG ( STDMETHODCALLTYPE *AddRef )( - ICLRPrivAssemblyID_WinRT * This); - - ULONG ( STDMETHODCALLTYPE *Release )( - ICLRPrivAssemblyID_WinRT * This); - - END_INTERFACE - } ICLRPrivAssemblyID_WinRTVtbl; - - interface ICLRPrivAssemblyID_WinRT - { - CONST_VTBL struct ICLRPrivAssemblyID_WinRTVtbl *lpVtbl; - }; - - - -#ifdef COBJMACROS - - -#define ICLRPrivAssemblyID_WinRT_QueryInterface(This,riid,ppvObject) \ - ( (This)->lpVtbl -> QueryInterface(This,riid,ppvObject) ) - -#define ICLRPrivAssemblyID_WinRT_AddRef(This) \ - ( (This)->lpVtbl -> AddRef(This) ) - -#define ICLRPrivAssemblyID_WinRT_Release(This) \ - ( (This)->lpVtbl -> Release(This) ) - - -#endif /* COBJMACROS */ - - -#endif /* C style interface */ - - - - -#endif /* __ICLRPrivAssemblyID_WinRT_INTERFACE_DEFINED__ */ - - /* Additional Prototypes for ALL interfaces */ /* end of Additional Prototypes */ diff --git a/src/coreclr/src/tools/crossgen/CMakeLists.txt b/src/coreclr/src/tools/crossgen/CMakeLists.txt index 685ba73..bf37a9c 100644 --- a/src/coreclr/src/tools/crossgen/CMakeLists.txt +++ b/src/coreclr/src/tools/crossgen/CMakeLists.txt @@ -70,7 +70,6 @@ else() version shlwapi bcrypt - mdwinmd_crossgen ${STATIC_MT_CRT_LIB} ${STATIC_MT_VCRT_LIB} ) diff --git a/src/coreclr/src/tools/crossgen/compare.bat b/src/coreclr/src/tools/crossgen/compare.bat index 290cc06..436876a 100644 --- a/src/coreclr/src/tools/crossgen/compare.bat +++ b/src/coreclr/src/tools/crossgen/compare.bat @@ -79,21 +79,6 @@ ::System.Xml.ReaderWriter ::System.Xml.XDocument ::System.Xml.XmlSerializer -::Windows.ApplicationModel -::Windows.Data -::Windows.Devices -::Windows.Foundation -::Windows.Globalization -::Windows.Graphics -::Windows.Management -::Windows.Media -::Windows.Networking -::Windows.Security -::Windows.Storage -::Windows.System -::Windows.UI -::Windows.UI.Xaml -::Windows.Web ::END_OF_LIST @echo off @@ -134,8 +119,6 @@ set CROSSGENIMAGEPATH=%_NTTREE%\ni rmdir /S /Q %CROSSGENIMAGEPATH% if not exist %CROSSGENIMAGEPATH% mkdir %CROSSGENIMAGEPATH% -set WINMDPATH=%WINDIR%\System32\WinMetadata - set SELF=%~fd0 set FAILED= @@ -157,7 +140,6 @@ exit /B 1 set FILEPATH= call :ProbeFile %ILIMAGEPATH%\%1.dll -call :ProbeFile %WINMDPATH%\%1.winmd if "%FILEPATH%" == "" ( echo File not found: %1 & goto LError ) @@ -166,8 +148,8 @@ echo ========= COMPILE and COMPARE %1 ========== echo ngen install /nodependencies %FILEPATH% ngen install /nodependencies %FILEPATH% echo. -echo %_NTTREE%\crossgen /platform_assemblies_paths %ILIMAGEPATH%;%CROSSGENIMAGEPATH% /Platform_Winmd_Paths %WINMDPATH% /in %FILEPATH% /out %CROSSGENIMAGEPATH%\%1.ni.dll -%_NTTREE%\crossgen /platform_assemblies_paths %ILIMAGEPATH%;%CROSSGENIMAGEPATH% /Platform_Winmd_Paths %WINMDPATH% /in %FILEPATH% /out %CROSSGENIMAGEPATH%\%1.ni.dll +echo %_NTTREE%\crossgen /platform_assemblies_paths %ILIMAGEPATH%;%CROSSGENIMAGEPATH% /in %FILEPATH% /out %CROSSGENIMAGEPATH%\%1.ni.dll +%_NTTREE%\crossgen /platform_assemblies_paths %ILIMAGEPATH%;%CROSSGENIMAGEPATH% /in %FILEPATH% /out %CROSSGENIMAGEPATH%\%1.ni.dll IF NOT "%ERRORLEVEL%"=="0" set FAILED=1 echo. forfiles /P %NATIVEIMAGEPATH% /M %1.ni.dll /S /C "cmd /c echo Compare: @path & fc /B @path %CROSSGENIMAGEPATH%\%1.ni.dll > %CROSSGENIMAGEPATH%\diff.txt & IF NOT ERRORLEVEL 1 del %CROSSGENIMAGEPATH%\diff.txt" diff --git a/src/coreclr/src/tools/crossgen/crossgen.cpp b/src/coreclr/src/tools/crossgen/crossgen.cpp index fafad63..622a1e5 100644 --- a/src/coreclr/src/tools/crossgen/crossgen.cpp +++ b/src/coreclr/src/tools/crossgen/crossgen.cpp @@ -33,12 +33,12 @@ enum ReturnValues #define NumItems(s) (sizeof(s) / sizeof(s[0])) -STDAPI CreatePDBWorker(LPCWSTR pwzAssemblyPath, LPCWSTR pwzPlatformAssembliesPaths, LPCWSTR pwzTrustedPlatformAssemblies, LPCWSTR pwzPlatformResourceRoots, LPCWSTR pwzAppPaths, LPCWSTR pwzAppNiPaths, LPCWSTR pwzPdbPath, BOOL fGeneratePDBLinesInfo, LPCWSTR pwzManagedPdbSearchPath, LPCWSTR pwzPlatformWinmdPaths, LPCWSTR pwzDiasymreaderPath); -STDAPI NGenWorker(LPCWSTR pwzFilename, DWORD dwFlags, LPCWSTR pwzPlatformAssembliesPaths, LPCWSTR pwzTrustedPlatformAssemblies, LPCWSTR pwzPlatformResourceRoots, LPCWSTR pwzAppPaths, LPCWSTR pwzOutputFilename=NULL, SIZE_T customBaseAddress=0, LPCWSTR pwzPlatformWinmdPaths=NULL, ICorSvcLogger *pLogger = NULL, LPCWSTR pwszCLRJITPath = nullptr); +STDAPI CreatePDBWorker(LPCWSTR pwzAssemblyPath, LPCWSTR pwzPlatformAssembliesPaths, LPCWSTR pwzTrustedPlatformAssemblies, LPCWSTR pwzPlatformResourceRoots, LPCWSTR pwzAppPaths, LPCWSTR pwzAppNiPaths, LPCWSTR pwzPdbPath, BOOL fGeneratePDBLinesInfo, LPCWSTR pwzManagedPdbSearchPath, LPCWSTR pwzDiasymreaderPath); +STDAPI NGenWorker(LPCWSTR pwzFilename, DWORD dwFlags, LPCWSTR pwzPlatformAssembliesPaths, LPCWSTR pwzTrustedPlatformAssemblies, LPCWSTR pwzPlatformResourceRoots, LPCWSTR pwzAppPaths, LPCWSTR pwzOutputFilename=NULL, SIZE_T customBaseAddress=0, ICorSvcLogger *pLogger = NULL, LPCWSTR pwszCLRJITPath = nullptr); void SetSvcLogger(ICorSvcLogger *pCorSvcLogger); void SetMscorlibPath(LPCWSTR wzSystemDirectory); -/* --------------------------------------------------------------------------- * +/* --------------------------------------------------------------------------- * * Console stuff * --------------------------------------------------------------------------- */ @@ -131,12 +131,6 @@ void PrintUsageHelper() W(" - List of paths containing user-application native images\n") W(" - Must be used with /CreatePDB switch\n") #endif // NO_NGENPDB - -#ifdef FEATURE_COMINTEROP - W(" /Platform_Winmd_Paths \n") - W(" - List of paths containing target platform WinMDs used\n") - W(" for emulating RoResolveNamespace\n") -#endif W(" /MissingDependenciesOK\n") W(" - Specifies that crossgen should attempt not to fail\n") W(" if a dependency is missing.\n") @@ -158,12 +152,6 @@ void PrintUsageHelper() #ifdef FEATURE_ENABLE_NO_ADDRESS_SPACE_RANDOMIZATION W(" /BaseAddress - Specifies base address to use for compilation.\n") #endif -#ifdef FEATURE_WINMD_RESILIENT - W(" WinMD Parameters\n") - W(" /WinMDResilient - Generate images resilient to WinMD dependency changes.\n") -#endif - W(" Size on Disk Parameters\n") - W(" /NoMetaData - Do not copy metadata and IL into native image.\n") #ifndef NO_NGENPDB W(" Debugging Parameters\n") W(" /CreatePDB [/lines [] ]\n") @@ -187,11 +175,11 @@ public: STDMETHODIMP_(ULONG) Release() {return E_NOTIMPL;} STDMETHODIMP QueryInterface(REFIID riid,void ** ppv) { - if (ppv==0) + if (ppv==0) return E_POINTER; - + *ppv = NULL; - + if (IsEqualIID(riid, IID_ICorSvcLogger) || IsEqualIID(riid, IID_IUnknown)) { *ppv = this; @@ -203,7 +191,7 @@ public: } } - HRESULT STDMETHODCALLTYPE Log( + HRESULT STDMETHODCALLTYPE Log( /*[in] */CorSvcLogLevel logLevel, /*[in] */BSTR message ) @@ -276,7 +264,7 @@ bool ComputeMscorlibPathFromTrustedPlatformAssemblies(SString& pwzMscorlibPath, wcscpy_s(wszTrustedPathCopy, wcslen(pwzTrustedPlatformAssemblies) + 1, pwzTrustedPlatformAssemblies); WCHAR *context; LPWSTR wszSingleTrustedPath = wcstok_s(wszTrustedPathCopy, PATH_SEPARATOR_STR_W, &context); - + while (wszSingleTrustedPath != NULL) { size_t pathLength = wcslen(wszSingleTrustedPath); @@ -293,7 +281,7 @@ bool ComputeMscorlibPathFromTrustedPlatformAssemblies(SString& pwzMscorlibPath, pwzMscorlibPath.Set(wszSingleTrustedPath); SString::Iterator pwzSeparator = pwzMscorlibPath.End(); bool retval = true; - + if (!SUCCEEDED(CopySystemDirectory(pwzMscorlibPath, pwzMscorlibPath))) { retval = false; @@ -302,7 +290,7 @@ bool ComputeMscorlibPathFromTrustedPlatformAssemblies(SString& pwzMscorlibPath, delete [] wszTrustedPathCopy; return retval; } - + wszSingleTrustedPath = wcstok_s(NULL, PATH_SEPARATOR_STR_W, &context); } delete [] wszTrustedPathCopy; @@ -317,7 +305,7 @@ void PopulateTPAList(SString path, LPCWSTR pwszMask, SString &refTPAList, bool f { _ASSERTE(path.GetCount() > 0); ClrDirectoryEnumerator folderEnumerator(path.GetUnicode(), pwszMask); - + while (folderEnumerator.Next()) { // Got a valid enumeration handle and the data about the first file. @@ -327,7 +315,7 @@ void PopulateTPAList(SString path, LPCWSTR pwszMask, SString &refTPAList, bool f bool fAddDelimiter = (refTPAList.GetCount() > 0)?true:false; bool fAddFileToTPAList = true; LPCWSTR pwszFilename = folderEnumerator.GetFileName(); - + // No NIs are supported when creating NI images (other than NI of System.Private.CoreLib.dll). if (!fCreatePDB) { @@ -337,7 +325,7 @@ void PopulateTPAList(SString path, LPCWSTR pwszMask, SString &refTPAList, bool f fAddFileToTPAList = false; } } - + if (fAddFileToTPAList) { if (fAddDelimiter) @@ -348,7 +336,7 @@ void PopulateTPAList(SString path, LPCWSTR pwszMask, SString &refTPAList, bool f // Add the path to the TPAList refTPAList.Append(path); refTPAList.Append(pwszFilename); - } + } } } } @@ -359,9 +347,9 @@ void ComputeTPAListFromPlatformAssembliesPath(LPCWSTR pwzPlatformAssembliesPaths { // We should have a valid pointer to the paths _ASSERTE(pwzPlatformAssembliesPaths != NULL); - + SString ssPlatformAssembliesPath(pwzPlatformAssembliesPaths); - + // Platform Assemblies Path List is semi-colon delimited if(ssPlatformAssembliesPath.GetCount() > 0) { @@ -431,7 +419,6 @@ int _cdecl wmain(int argc, __in_ecount(argc) WCHAR **argv) LPCWSTR pwzAppPaths = nullptr; LPCWSTR pwzAppNiPaths = nullptr; LPCWSTR pwzPlatformAssembliesPaths = nullptr; - LPCWSTR pwzPlatformWinmdPaths = nullptr; StackSString wzDirectoryToStorePDB; bool fCreatePDB = false; bool fGeneratePDBLinesInfo = false; @@ -469,7 +456,7 @@ int _cdecl wmain(int argc, __in_ecount(argc) WCHAR **argv) PrintUsageHelper(); exit(INVALID_ARGUMENTS); } - + if (!consoleArgs.ExpandResponseFiles(argc, argv, &argc2, &argv2)) { if (consoleArgs.ErrorMessage() != nullptr) @@ -478,7 +465,7 @@ int _cdecl wmain(int argc, __in_ecount(argc) WCHAR **argv) exit(FAILURE_RESULT); } } - + argc = argc2; argv = argv2; @@ -521,18 +508,12 @@ int _cdecl wmain(int argc, __in_ecount(argc) WCHAR **argv) else if (MatchParameter(*argv, W("JITPath")) && (argc > 1)) { pwszCLRJITPath = argv[1]; - + // skip JIT Path argv++; argc--; } #endif // !defined(FEATURE_MERGE_JIT_AND_ENGINE) -#ifdef FEATURE_WINMD_RESILIENT - else if (MatchParameter(*argv, W("WinMDResilient"))) - { - dwFlags |= NGENWORKER_FLAGS_WINMD_RESILIENT; - } -#endif #ifdef FEATURE_READYTORUN_COMPILER else if (MatchParameter(*argv, W("ReadyToRun"))) { @@ -561,10 +542,6 @@ int _cdecl wmain(int argc, __in_ecount(argc) WCHAR **argv) argc--; } #endif - else if (MatchParameter(*argv, W("NoMetaData"))) - { - dwFlags |= NGENWORKER_FLAGS_NO_METADATA; - } else if (MatchParameter(*argv, W("out"))) { if (pwzOutputFilename != NULL) @@ -630,26 +607,16 @@ int _cdecl wmain(int argc, __in_ecount(argc) WCHAR **argv) else if ((MatchParameter(*argv, W("Platform_Assemblies_Paths")) || MatchParameter(*argv, W("p"))) && (argc > 1)) { pwzPlatformAssembliesPaths = argv[1]; - - // skip path list - argv++; - argc--; - } -#ifdef FEATURE_COMINTEROP - else if (MatchParameter(*argv, W("Platform_Winmd_Paths")) && (argc > 1)) - { - pwzPlatformWinmdPaths = argv[1]; - // skip User app path + // skip path list argv++; argc--; } -#endif // FEATURE_COMINTEROP #ifndef NO_NGENPDB else if (MatchParameter(*argv, W("CreatePDB")) && (argc > 1)) { // syntax: /CreatePDB [/lines [] ] - + // Parse: /CreatePDB fCreatePDB = true; argv++; @@ -773,7 +740,7 @@ int _cdecl wmain(int argc, __in_ecount(argc) WCHAR **argv) OutputErr(W("Cannot use /In and specify an input file as the last argument.\n")); exit(INVALID_ARGUMENTS); } - + pwzFilename = *argv; break; } @@ -833,31 +800,6 @@ int _cdecl wmain(int argc, __in_ecount(argc) WCHAR **argv) exit(FAILURE_RESULT); } - if ((dwFlags & NGENWORKER_FLAGS_NO_METADATA) != 0) - { - const size_t windowsDotWinmdLength = 13; // Length of string "Windows.winmd" - size_t filenameLength = wcslen(pwzFilename); - bool isWindowsDotWinmd = true; - if (filenameLength < windowsDotWinmdLength || - _wcsicmp(pwzFilename + filenameLength - windowsDotWinmdLength, W("windows.winmd")) != 0) - { - isWindowsDotWinmd = false; - } - else if (filenameLength > windowsDotWinmdLength) - { - WCHAR pathSeparator = pwzFilename[filenameLength - windowsDotWinmdLength - 1]; - if (pathSeparator != W('\\') && pathSeparator != W('/') && pathSeparator != W(':')) - { - isWindowsDotWinmd = false; - } - } - if (!isWindowsDotWinmd) - { - OutputErr(W("The /NoMetaData switch can only be used with Windows.winmd.\n")); - exit(FAILURE_RESULT); - } - } - // All argument processing has happened by now. The only messages that should appear before here are errors // related to argument parsing, such as the Usage message. Afterwards, other messages can appear. @@ -873,7 +815,7 @@ int _cdecl wmain(int argc, __in_ecount(argc) WCHAR **argv) PathString wzTrustedPathRoot; - SString ssTPAList; + SString ssTPAList; if (fCreatePDB) { @@ -887,7 +829,7 @@ int _cdecl wmain(int argc, __in_ecount(argc) WCHAR **argv) { // /p command line switch has been specified. _ASSERTE(pwzTrustedPlatformAssemblies == nullptr); - + // Formulate the TPAList from /p ComputeTPAListFromPlatformAssembliesPath(pwzPlatformAssembliesPaths, ssTPAList, fCreatePDB); pwzTrustedPlatformAssemblies = (WCHAR *)ssTPAList.GetUnicode(); @@ -910,7 +852,7 @@ int _cdecl wmain(int argc, __in_ecount(argc) WCHAR **argv) ERROR_WIN32(W("Error: GetModuleFileName failed (%d)\n"), GetLastError()); exit(CLR_INIT_ERROR); } - + if (SUCCEEDED(CopySystemDirectory(wzTrustedPathRoot, wzTrustedPathRoot))) { pwzPlatformAssembliesPaths = wzTrustedPathRoot.GetUnicode(); @@ -920,8 +862,8 @@ int _cdecl wmain(int argc, __in_ecount(argc) WCHAR **argv) ERROR_HR(W("Error: wcsrchr returned NULL; GetModuleFileName must have given us something bad\n"), E_UNEXPECTED); exit(CLR_INIT_ERROR); } - - + + } // Verbose mode will always print warnings @@ -938,18 +880,17 @@ int _cdecl wmain(int argc, __in_ecount(argc) WCHAR **argv) if (fCreatePDB) { hr = CreatePDBWorker( - pwzFilename, - pwzPlatformAssembliesPaths, - pwzTrustedPlatformAssemblies, - pwzPlatformResourceRoots, - pwzAppPaths, + pwzFilename, + pwzPlatformAssembliesPaths, + pwzTrustedPlatformAssemblies, + pwzPlatformResourceRoots, + pwzAppPaths, pwzAppNiPaths, - wzDirectoryToStorePDB, - fGeneratePDBLinesInfo, + wzDirectoryToStorePDB, + fGeneratePDBLinesInfo, pwzSearchPathForManagedPDB, - pwzPlatformWinmdPaths, pwzDiasymreaderPath); - + } else { @@ -959,16 +900,15 @@ int _cdecl wmain(int argc, __in_ecount(argc) WCHAR **argv) pwzPlatformResourceRoots, pwzAppPaths, pwzOutputFilename, - baseAddress, - pwzPlatformWinmdPaths + baseAddress #if !defined(FEATURE_MERGE_JIT_AND_ENGINE) , NULL, // ICorSvcLogger - pwszCLRJITPath + pwszCLRJITPath #endif // !defined(FEATURE_MERGE_JIT_AND_ENGINE) ); } - + if (FAILED(hr)) { diff --git a/src/coreclr/src/tools/crossgen2/ILCompiler.ReadyToRun/Compiler/DependencyAnalysis/ReadyToRun/AttributePresenceFilterNode.cs b/src/coreclr/src/tools/crossgen2/ILCompiler.ReadyToRun/Compiler/DependencyAnalysis/ReadyToRun/AttributePresenceFilterNode.cs index eef7490..134aa65 100644 --- a/src/coreclr/src/tools/crossgen2/ILCompiler.ReadyToRun/Compiler/DependencyAnalysis/ReadyToRun/AttributePresenceFilterNode.cs +++ b/src/coreclr/src/tools/crossgen2/ILCompiler.ReadyToRun/Compiler/DependencyAnalysis/ReadyToRun/AttributePresenceFilterNode.cs @@ -60,11 +60,6 @@ namespace ILCompiler.DependencyAnalysis.ReadyToRun { addToTable = true; } - else if (customAttributeTypeNamespace == "Windows.Foundation.Metadata") - { - // Windows.Foundation.Metadata attributes are a similar construct to compilerservices attributes. Add them to the table - addToTable = true; - } else if (customAttributeTypeNamespace == "System") { // Some historical well known attributes were placed in the System namespace. Special case them @@ -101,12 +96,12 @@ namespace ILCompiler.DependencyAnalysis.ReadyToRun /** * This class is used to extract the first type handle in a signature. - * + * * In the case that a custom attribute's constructor is a MemberReference, - * and its parent is a TypeSpec, we have to parse the signature, but we do - * not want to actually resolve the types. So we used this dummy signature + * and its parent is a TypeSpec, we have to parse the signature, but we do + * not want to actually resolve the types. So we used this dummy signature * type provider to extract the first type handle. - */ + */ private class FirstTypeHandleExtractor : ISignatureTypeProvider { private EntityHandle _firstTypeHandle; @@ -251,7 +246,7 @@ namespace ILCompiler.DependencyAnalysis.ReadyToRun { TypeDefinitionHandle customAttributeConstructorTypeDefinitionHandle = (TypeDefinitionHandle)firstTypeHandle; GetTypeNameFromTypeDefinitionHandle(customAttributeConstructorTypeDefinitionHandle, out customAttributeTypeNamespace, out customAttributeTypeName); - } + } else { Debug.Assert(firstTypeHandle.Kind == HandleKind.TypeReference); @@ -462,7 +457,7 @@ namespace ILCompiler.DependencyAnalysis.ReadyToRun builder.RequireInitialAlignment(16); builder.AddSymbol(this); builder.EmitBytes(result); - + return builder.ToObjectData(); ; } } diff --git a/src/coreclr/src/tools/r2rtest/CompilerRunner.cs b/src/coreclr/src/tools/r2rtest/CompilerRunner.cs index 1c91757..ae36492 100644 --- a/src/coreclr/src/tools/r2rtest/CompilerRunner.cs +++ b/src/coreclr/src/tools/r2rtest/CompilerRunner.cs @@ -32,7 +32,6 @@ namespace R2RTest { new FrameworkExclusion(ExclusionType.Ignore, "CommandLine", "Not a framework assembly"), new FrameworkExclusion(ExclusionType.Ignore, "R2RDump", "Not a framework assembly"), - new FrameworkExclusion(ExclusionType.Ignore, "System.Runtime.WindowsRuntime", "WinRT is currently not supported"), new FrameworkExclusion(ExclusionType.Ignore, "xunit.performance.api", "Not a framework assembly"), // TODO (DavidWr): IBC-related failures diff --git a/src/coreclr/src/utilcode/pedecoder.cpp b/src/coreclr/src/utilcode/pedecoder.cpp index 3ba2f15..6497c1b 100644 --- a/src/coreclr/src/utilcode/pedecoder.cpp +++ b/src/coreclr/src/utilcode/pedecoder.cpp @@ -317,9 +317,9 @@ CHECK PEDecoder::CheckNTHeaders() const // NOTE: the if condition is becuase of a design issue in the CLR and OS loader's remapping // of PE32 headers to PE32+. Because IMAGE_NT_HEADERS64 is bigger than IMAGE_NT_HEADERS32, // the remapping will expand this part of the header and push out the following - // IMAGE_SECTION_HEADER entries. When IMAGE_DOS_HEADER::e_lfanew is large enough (size is - // proportional to the number of tools used to produce the inputs to the C++ linker, and - // has become larger when producing some WinMD files) this can push the last section header + // IMAGE_SECTION_HEADER entries. When IMAGE_DOS_HEADER::e_lfanew is large enough + // (size is proportional to the number of tools used to produce the inputs to the C++ linker) + // this can push the last section header // beyond the boundary set by IMAGE_NT_HEADERS::OptionalHeader.SizeOfHeaders (e.g., this // was recently seen where the unaligned size of the headers was 0x1f8 and SizeOfHeaders was // 0x200, and the header remapping resulted in new headers size of 0x208). To compensate @@ -2344,10 +2344,10 @@ void *PEDecoder::GetExport(LPCSTR exportName) const { return NULL; } - + uint8_t *imageBase = (uint8_t *)GetBase(); const IMAGE_EXPORT_DIRECTORY *pExportDir = (const IMAGE_EXPORT_DIRECTORY *)GetDirectoryData(pExportDirectoryEntry); - + uint32_t namePointerCount = VAL32(pExportDir->NumberOfNames); uint32_t addressTableRVA = VAL32(pExportDir->AddressOfFunctions); uint32_t namePointersRVA = VAL32(pExportDir->AddressOfNames); diff --git a/src/coreclr/src/vm/.vscode/c_cpp_properties.json b/src/coreclr/src/vm/.vscode/c_cpp_properties.json index 2a68e99..569bf8c 100644 --- a/src/coreclr/src/vm/.vscode/c_cpp_properties.json +++ b/src/coreclr/src/vm/.vscode/c_cpp_properties.json @@ -78,7 +78,6 @@ "FEATURE_USE_SOFTWARE_WRITE_WATCH_FOR_GC_HEAP", "FEATURE_UTF8STRING=1", "FEATURE_WIN32_REGISTRY", - "FEATURE_WINMD_RESILIENT", "TARGET_WINDOWS=1", "PROFILING_SUPPORTED_DATA", "UNICODE", diff --git a/src/coreclr/src/vm/CMakeLists.txt b/src/coreclr/src/vm/CMakeLists.txt index dedb57d..00aa175 100644 --- a/src/coreclr/src/vm/CMakeLists.txt +++ b/src/coreclr/src/vm/CMakeLists.txt @@ -188,7 +188,6 @@ set(VM_HEADERS_DAC_AND_WKS_COMMON gctoclreventsink.h gcheaputilities.h generics.h - generics.inl hash.h hillclimbing.h ilinstrumentation.h @@ -353,7 +352,6 @@ set(VM_SOURCES_WKS fcall.cpp fieldmarshaler.cpp finalizerthread.cpp - frameworkexceptionloader.cpp gccover.cpp gcenv.ee.static.cpp gcenv.ee.common.cpp @@ -402,7 +400,6 @@ set(VM_SOURCES_WKS stubhelpers.cpp syncclean.cpp synch.cpp - synchronizationcontextnative.cpp tailcallhelp.cpp threaddebugblockinginfo.cpp threadsuspend.cpp @@ -474,7 +471,6 @@ set(VM_HEADERS_WKS fcall.h fieldmarshaler.h finalizerthread.h - frameworkexceptionloader.h gcenv.h gcenv.ee.h gcenv.os.h @@ -522,7 +518,6 @@ set(VM_HEADERS_WKS stubhelpers.h syncclean.hpp synch.h - synchronizationcontextnative.h tailcallhelp.h tieredcompilation.h threaddebugblockinginfo.h @@ -575,23 +570,17 @@ if(CLR_CMAKE_TARGET_WIN32) set(VM_SOURCES_DAC_AND_WKS_WIN32 amsi.cpp clrtocomcall.cpp - rcwwalker.cpp - winrttypenameconverter.cpp ) set(VM_HEADERS_DAC_AND_WKS_WIN32 amsi.h clrtocomcall.h - rcwwalker.h - winrttypenameconverter.h ) list(APPEND VM_SOURCES_WKS ${VM_SOURCES_DAC_AND_WKS_WIN32} # These should not be included for Linux classcompat.cpp - clrprivbinderwinrt.cpp - clrprivtypecachewinrt.cpp comcache.cpp comcallablewrapper.cpp comconnectionpoints.cpp @@ -612,15 +601,12 @@ list(APPEND VM_SOURCES_WKS stacksampler.cpp stdinterfaces.cpp stdinterfaces_wrapper.cpp - winrthelpers.cpp ) list(APPEND VM_HEADERS_WKS ${VM_HEADERS_DAC_AND_WKS_WIN32} # These should not be included for Linux classcompat.h - clrprivbinderwinrt.h - clrprivtypecachewinrt.h comcache.h comcallablewrapper.h comconnectionpoints.h @@ -641,21 +627,14 @@ list(APPEND VM_HEADERS_WKS stacksampler.h stdinterfaces.h stdinterfaces_internal.h - winrthelpers.h ) list(APPEND VM_SOURCES_DAC ${VM_SOURCES_DAC_AND_WKS_WIN32} - # These should not be included for Linux - clrprivbinderwinrt.cpp - clrprivtypecachewinrt.cpp ) list(APPEND VM_HEADERS_DAC ${VM_HEADERS_DAC_AND_WKS_WIN32} - # These should not be included for Linux - clrprivbinderwinrt.h - clrprivtypecachewinrt.h ) endif(CLR_CMAKE_TARGET_WIN32) diff --git a/src/coreclr/src/vm/appdomain.cpp b/src/coreclr/src/vm/appdomain.cpp index 2e39d01..ff0c708 100644 --- a/src/coreclr/src/vm/appdomain.cpp +++ b/src/coreclr/src/vm/appdomain.cpp @@ -69,8 +69,6 @@ #include "../binder/inc/bindertracing.h" #include "../binder/inc/clrprivbindercoreclr.h" -#include "clrprivtypecachewinrt.h" - // this file handles string conversion errors for itself #undef MAKE_TRANSLATIONFAILED @@ -677,7 +675,6 @@ BaseDomain::BaseDomain() #ifdef FEATURE_COMINTEROP m_pMngStdInterfacesInfo = NULL; - m_pWinRtBinder = NULL; #endif m_FileLoadLock.PreInit(); m_JITLock.PreInit(); @@ -712,8 +709,6 @@ void BaseDomain::Init() m_InteropDataCrst.Init(CrstInteropData, CRST_REENTRANCY); - m_WinRTFactoryCacheCrst.Init(CrstWinRTFactoryCache, CRST_UNSAFE_COOPGC); - // NOTE: CRST_UNSAFE_COOPGC prevents a GC mode switch to preemptive when entering this crst. // If you remove this flag, we will switch to preemptive mode when entering // m_FileLoadLock, which means all functions that enter it will become @@ -747,16 +742,6 @@ void BaseDomain::Init() #ifdef FEATURE_COMINTEROP // Allocate the managed standard interfaces information. m_pMngStdInterfacesInfo = new MngStdInterfacesInfo(); - - { - CLRPrivBinderWinRT::NamespaceResolutionKind fNamespaceResolutionKind = CLRPrivBinderWinRT::NamespaceResolutionKind_WindowsAPI; - if (CLRConfig::GetConfigValue(CLRConfig::EXTERNAL_DesignerNamespaceResolutionEnabled) != FALSE) - { - fNamespaceResolutionKind = CLRPrivBinderWinRT::NamespaceResolutionKind_DesignerResolveEvent; - } - CLRPrivTypeCacheWinRT * pWinRtTypeCache = CLRPrivTypeCacheWinRT::GetOrCreateTypeCache(); - m_pWinRtBinder = CLRPrivBinderWinRT::GetOrCreateBinder(pWinRtTypeCache, fNamespaceResolutionKind); - } #endif // FEATURE_COMINTEROP // Init the COM Interop data hash @@ -997,431 +982,8 @@ void AppDomain::InsertClassForCLSID(MethodTable* pMT, BOOL fForceInsert /*=FALSE #endif // DACCESS_COMPILE #ifdef FEATURE_COMINTEROP - -#ifndef DACCESS_COMPILE -void AppDomain::CacheTypeByName(const SString &ssClassName, const UINT vCacheVersion, TypeHandle typeHandle, BYTE bFlags, BOOL bReplaceExisting /*= FALSE*/) -{ - WRAPPER_NO_CONTRACT; - LockHolder lh(this); - CacheTypeByNameWorker(ssClassName, vCacheVersion, typeHandle, bFlags, bReplaceExisting); -} - -void AppDomain::CacheTypeByNameWorker(const SString &ssClassName, const UINT vCacheVersion, TypeHandle typeHandle, BYTE bFlags, BOOL bReplaceExisting /*= FALSE*/) -{ - CONTRACTL - { - THROWS; - GC_TRIGGERS; - PRECONDITION(!typeHandle.IsNull()); - } - CONTRACTL_END; - - NewArrayHolder wzClassName(DuplicateStringThrowing(ssClassName.GetUnicode())); - - if (m_vNameToTypeMapVersion != vCacheVersion) - return; - - if (m_pNameToTypeMap == nullptr) - { - m_pNameToTypeMap = new NameToTypeMapTable(); - } - - NameToTypeMapEntry e; - e.m_key.m_wzName = wzClassName; - e.m_key.m_cchName = ssClassName.GetCount(); - e.m_typeHandle = typeHandle; - e.m_nEpoch = this->m_nEpoch; - e.m_bFlags = bFlags; - if (!bReplaceExisting) - m_pNameToTypeMap->Add(e); - else - m_pNameToTypeMap->AddOrReplace(e); - - wzClassName.SuppressRelease(); -} -#endif // DACCESS_COMPILE - -TypeHandle AppDomain::LookupTypeByName(const SString &ssClassName, UINT* pvCacheVersion, BYTE *pbFlags) -{ - WRAPPER_NO_CONTRACT; - LockHolder lh(this); - return LookupTypeByNameWorker(ssClassName, pvCacheVersion, pbFlags); -} - -TypeHandle AppDomain::LookupTypeByNameWorker(const SString &ssClassName, UINT* pvCacheVersion, BYTE *pbFlags) -{ - CONTRACTL - { - THROWS; - GC_TRIGGERS; - SUPPORTS_DAC; - PRECONDITION(CheckPointer(pbFlags, NULL_OK)); - } - CONTRACTL_END; - - *pvCacheVersion = m_vNameToTypeMapVersion; - - if (m_pNameToTypeMap == nullptr) - return TypeHandle(); // a null TypeHandle - - NameToTypeMapEntry::Key key; - key.m_cchName = ssClassName.GetCount(); - key.m_wzName = ssClassName.GetUnicode(); - - const NameToTypeMapEntry * pEntry = m_pNameToTypeMap->LookupPtr(key); - if (pEntry == NULL) - return TypeHandle(); // a null TypeHandle - - if (pbFlags != NULL) - *pbFlags = pEntry->m_bFlags; - - return pEntry->m_typeHandle; -} - -PTR_MethodTable AppDomain::LookupTypeByGuid(const GUID & guid) -{ - CONTRACTL - { - THROWS; - GC_TRIGGERS; - MODE_ANY; - SUPPORTS_DAC; - } - CONTRACTL_END; - - SString sGuid; - { - WCHAR wszGuid[64]; - GuidToLPWSTR(guid, wszGuid, _countof(wszGuid)); - sGuid.Append(wszGuid); - } - UINT ver; - TypeHandle th = LookupTypeByName(sGuid, &ver, NULL); - - if (!th.IsNull()) - { - _ASSERTE(!th.IsTypeDesc()); - return th.AsMethodTable(); - } - -#ifdef FEATURE_PREJIT - else - { - // Next look in each ngen'ed image in turn - AssemblyIterator assemblyIterator = IterateAssembliesEx((AssemblyIterationFlags)( - kIncludeLoaded | kIncludeExecution)); - CollectibleAssemblyHolder pDomainAssembly; - while (assemblyIterator.Next(pDomainAssembly.This())) - { - CollectibleAssemblyHolder pAssembly = pDomainAssembly->GetLoadedAssembly(); - - DomainAssembly::ModuleIterator i = pDomainAssembly->IterateModules(kModIterIncludeLoaded); - while (i.Next()) - { - Module * pModule = i.GetLoadedModule(); - if (!pModule->HasNativeImage()) - continue; - _ASSERTE(!pModule->IsCollectible()); - PTR_MethodTable pMT = pModule->LookupTypeByGuid(guid); - if (pMT != NULL) - { - return pMT; - } - } - } - } -#endif // FEATURE_PREJIT - return NULL; -} - -#ifndef DACCESS_COMPILE -void AppDomain::CacheWinRTTypeByGuid(TypeHandle typeHandle) -{ - CONTRACTL - { - THROWS; - GC_TRIGGERS; - MODE_ANY; - PRECONDITION(!typeHandle.IsTypeDesc()); - PRECONDITION(CanCacheWinRTTypeByGuid(typeHandle)); - } - CONTRACTL_END; - - PTR_MethodTable pMT = typeHandle.AsMethodTable(); - - GUID guid; - if (pMT->GetGuidForWinRT(&guid)) - { - SString sGuid; - - { - WCHAR wszGuid[64]; - GuidToLPWSTR(guid, wszGuid, _countof(wszGuid)); - sGuid.Append(wszGuid); - } - - BYTE bFlags = 0x80; - TypeHandle th; - UINT vCacheVersion; - { - LockHolder lh(this); - th = LookupTypeByNameWorker(sGuid, &vCacheVersion, &bFlags); - - if (th.IsNull()) - { - // no other entry with the same GUID exists in the cache - CacheTypeByNameWorker(sGuid, vCacheVersion, typeHandle, bFlags); - } - else if (typeHandle.AsMethodTable() != th.AsMethodTable() && th.IsProjectedFromWinRT()) - { - // If we found a native WinRT type cached with the same GUID, replace it. - // Otherwise simply add the new mapping to the cache. - CacheTypeByNameWorker(sGuid, vCacheVersion, typeHandle, bFlags, TRUE); - } - } - } -} -#endif // DACCESS_COMPILE - -void AppDomain::GetCachedWinRTTypes( - SArray * pTypes, - SArray * pGuids, - UINT minEpoch, - UINT * pCurEpoch) -{ - CONTRACTL - { - THROWS; - GC_TRIGGERS; - MODE_ANY; - SUPPORTS_DAC; - } - CONTRACTL_END; - - LockHolder lh(this); - - for (auto it = m_pNameToTypeMap->Begin(), end = m_pNameToTypeMap->End(); - it != end; - ++it) - { - NameToTypeMapEntry entry = (NameToTypeMapEntry)(*it); - TypeHandle th = entry.m_typeHandle; - if (th.AsMethodTable() != NULL && - entry.m_key.m_wzName[0] == W('{') && - entry.m_nEpoch >= minEpoch) - { - _ASSERTE(!th.IsTypeDesc()); - PTR_MethodTable pMT = th.AsMethodTable(); - // we're parsing the GUID value from the cache, because projected types do not cache the - // COM GUID in their GetGuid() but rather the legacy GUID - GUID iid; - if (LPWSTRToGuid(&iid, entry.m_key.m_wzName, 38) && iid != GUID_NULL) - { - pTypes->Append(pMT); - pGuids->Append(iid); - } - } - } - -#ifdef FEATURE_PREJIT - // Next look in each ngen'ed image in turn - AssemblyIterator assemblyIterator = IterateAssembliesEx((AssemblyIterationFlags)( - kIncludeLoaded | kIncludeExecution)); - CollectibleAssemblyHolder pDomainAssembly; - while (assemblyIterator.Next(pDomainAssembly.This())) - { - CollectibleAssemblyHolder pAssembly = pDomainAssembly->GetLoadedAssembly(); - - DomainAssembly::ModuleIterator i = pDomainAssembly->IterateModules(kModIterIncludeLoaded); - while (i.Next()) - { - Module * pModule = i.GetLoadedModule(); - if (!pModule->HasNativeImage()) - continue; - _ASSERTE(!pModule->IsCollectible()); - - pModule->GetCachedWinRTTypes(pTypes, pGuids); - } - } -#endif // FEATURE_PREJIT - - if (pCurEpoch != NULL) - *pCurEpoch = m_nEpoch; - ++m_nEpoch; -} - #ifndef CROSSGEN_COMPILE #ifndef DACCESS_COMPILE -// static -void WinRTFactoryCacheTraits::OnDestructPerEntryCleanupAction(const WinRTFactoryCacheEntry& e) -{ - WRAPPER_NO_CONTRACT; - if (e.m_pCtxEntry != NULL) - { - e.m_pCtxEntry->Release(); - } - // the AD is going away, no need to destroy the OBJECTHANDLE -} - -void AppDomain::CacheWinRTFactoryObject(MethodTable *pClassMT, OBJECTREF *refFactory, LPVOID lpCtxCookie) -{ - CONTRACTL - { - THROWS; - GC_TRIGGERS; - MODE_COOPERATIVE; - PRECONDITION(CheckPointer(pClassMT)); - } - CONTRACTL_END; - - CtxEntryHolder pNewCtxEntry; - if (lpCtxCookie != NULL) - { - // We don't want to insert the context cookie in the cache because it's just an address - // of an internal COM data structure which will be freed when the apartment is torn down. - // What's worse, if another apartment is later created, its context cookie may have exactly - // the same value leading to incorrect cache hits. We'll use our CtxEntry instead which - // is ref-counted and keeps the COM data structure alive even after the apartment ceases - // to exist. - pNewCtxEntry = CtxEntryCache::GetCtxEntryCache()->FindCtxEntry(lpCtxCookie, GetThread()); - } - - WinRTFactoryCacheLockHolder lh(this); - - if (m_pWinRTFactoryCache == nullptr) - { - m_pWinRTFactoryCache = new WinRTFactoryCache(); - } - - WinRTFactoryCacheEntry *pEntry = const_cast(m_pWinRTFactoryCache->LookupPtr(pClassMT)); - if (!pEntry) - { - // - // No existing entry for this cache - // Create a new one - // - WinRTFactoryCacheEntry e; - - OBJECTHANDLEHolder ohNewHandle(CreateHandle(*refFactory)); - - e.key = pClassMT; - e.m_pCtxEntry = pNewCtxEntry; - e.m_ohFactoryObject = ohNewHandle; - - m_pWinRTFactoryCache->Add(e); - - // suppress release of the CtxEntry and handle after we successfully inserted the new entry - pNewCtxEntry.SuppressRelease(); - ohNewHandle.SuppressRelease(); - } - else - { - // - // Existing entry - // - // release the old CtxEntry and update the entry - CtxEntry *pTemp = pNewCtxEntry.Extract(); - pNewCtxEntry = pEntry->m_pCtxEntry; - pEntry->m_pCtxEntry = pTemp; - - IGCHandleManager *mgr = GCHandleUtilities::GetGCHandleManager(); - mgr->StoreObjectInHandle(pEntry->m_ohFactoryObject, OBJECTREFToObject(*refFactory)); - } -} - -OBJECTREF AppDomain::LookupWinRTFactoryObject(MethodTable *pClassMT, LPVOID lpCtxCookie) -{ - CONTRACTL - { - THROWS; - GC_NOTRIGGER; - MODE_COOPERATIVE; - PRECONDITION(CheckPointer(pClassMT)); - PRECONDITION(CheckPointer(m_pWinRTFactoryCache, NULL_OK)); - } - CONTRACTL_END; - - - if (m_pWinRTFactoryCache == nullptr) - return NULL; - - // - // Retrieve cached factory - // - WinRTFactoryCacheLockHolder lh(this); - - const WinRTFactoryCacheEntry *pEntry = m_pWinRTFactoryCache->LookupPtr(pClassMT); - if (pEntry == NULL) - return NULL; - - // - // Ignore factories from a different context, unless lpCtxCookie == NULL, - // which means the factory is free-threaded - // Note that we cannot touch the RCW to retrieve cookie at this point - // because the RCW might belong to a STA thread and that STA thread might die - // and take the RCW with it. Therefore we have to save cookie in this cache - // - if (pEntry->m_pCtxEntry == NULL || pEntry->m_pCtxEntry->GetCtxCookie() == lpCtxCookie) - return ObjectFromHandle(pEntry->m_ohFactoryObject); - - return NULL; -} - -void AppDomain::RemoveWinRTFactoryObjects(LPVOID pCtxCookie) -{ - CONTRACTL - { - THROWS; - GC_TRIGGERS; - MODE_ANY; - } - CONTRACTL_END; - - if (m_pWinRTFactoryCache == nullptr) - return; - - // helper class for delayed CtxEntry cleanup - class CtxEntryListReleaseHolder - { - public: - CQuickArrayList m_list; - - ~CtxEntryListReleaseHolder() - { - CONTRACTL - { - NOTHROW; - GC_TRIGGERS; - MODE_ANY; - } - CONTRACTL_END; - - for (SIZE_T i = 0; i < m_list.Size(); i++) - { - m_list[i]->Release(); - } - } - } ctxEntryListReleaseHolder; - - GCX_COOP(); - { - WinRTFactoryCacheLockHolder lh(this); - - // Go through the hash table and remove items in the given context - for (WinRTFactoryCache::Iterator it = m_pWinRTFactoryCache->Begin(); it != m_pWinRTFactoryCache->End(); it++) - { - if (it->m_pCtxEntry != NULL && it->m_pCtxEntry->GetCtxCookie() == pCtxCookie) - { - // Releasing the CtxEntry may trigger GC which we can't do under the lock so we push - // it on our local list and release them all after we're done iterating the hashtable. - ctxEntryListReleaseHolder.m_list.Push(it->m_pCtxEntry); - - DestroyHandle(it->m_ohFactoryObject); - m_pWinRTFactoryCache->Remove(it); - } - } - } -} OBJECTREF AppDomain::GetMissingObject() { @@ -2044,21 +1606,6 @@ void SystemDomain::LoadBaseSystemClasses() #ifdef FEATURE_COMINTEROP g_pBaseCOMObject = MscorlibBinder::GetClass(CLASS__COM_OBJECT); - g_pBaseRuntimeClass = MscorlibBinder::GetClass(CLASS__RUNTIME_CLASS); - - MscorlibBinder::GetClass(CLASS__IDICTIONARYGENERIC); - MscorlibBinder::GetClass(CLASS__IREADONLYDICTIONARYGENERIC); - MscorlibBinder::GetClass(CLASS__ATTRIBUTE); - MscorlibBinder::GetClass(CLASS__EVENT_HANDLERGENERIC); - - MscorlibBinder::GetClass(CLASS__IENUMERABLE); - MscorlibBinder::GetClass(CLASS__ICOLLECTION); - MscorlibBinder::GetClass(CLASS__ILIST); - MscorlibBinder::GetClass(CLASS__IDISPOSABLE); - -#ifdef _DEBUG - WinRTInterfaceRedirector::VerifyRedirectedInterfaceStubs(); -#endif // _DEBUG #endif #ifdef FEATURE_ICASTABLE @@ -2684,7 +2231,6 @@ AppDomain::AppDomain() #ifdef FEATURE_COMINTEROP m_pRCWCache = NULL; m_pRCWRefCache = NULL; - memset(m_rpCLRTypes, 0, sizeof(m_rpCLRTypes)); #endif // FEATURE_COMINTEROP m_handleStore = NULL; @@ -2711,13 +2257,6 @@ AppDomain::AppDomain() m_pTypeEquivalenceTable = NULL; #endif // FEATURE_TYPEEQUIVALENCE -#ifdef FEATURE_COMINTEROP - m_pNameToTypeMap = NULL; - m_vNameToTypeMapVersion = 0; - m_nEpoch = 0; - m_pWinRTFactoryCache = NULL; -#endif // FEATURE_COMINTEROP - #ifdef FEATURE_PREJIT m_pDomainFileWithNativeImageList = NULL; #endif @@ -2743,19 +2282,6 @@ AppDomain::~AppDomain() m_AssemblyCache.Clear(); -#ifdef FEATURE_COMINTEROP - if (m_pNameToTypeMap != nullptr) - { - delete m_pNameToTypeMap; - m_pNameToTypeMap = nullptr; - } - if (m_pWinRTFactoryCache != nullptr) - { - delete m_pWinRTFactoryCache; - m_pWinRTFactoryCache = nullptr; - } -#endif //FEATURE_COMINTEROP - #endif // CROSSGEN_COMPILE } @@ -2882,97 +2408,6 @@ void AppDomain::Stop() #endif // !CROSSGEN_COMPILE -#ifdef FEATURE_COMINTEROP -MethodTable *AppDomain::GetRedirectedType(WinMDAdapter::RedirectedTypeIndex index) -{ - CONTRACTL - { - THROWS; - GC_TRIGGERS; - MODE_ANY; - } - CONTRACTL_END; - - // If we have the type loaded already, use that - if (m_rpCLRTypes[index] != nullptr) - { - return m_rpCLRTypes[index]; - } - - WinMDAdapter::FrameworkAssemblyIndex frameworkAssemblyIndex; - WinMDAdapter::GetRedirectedTypeInfo(index, nullptr, nullptr, nullptr, &frameworkAssemblyIndex, nullptr, nullptr); - MethodTable * pMT = LoadRedirectedType(index, frameworkAssemblyIndex); - m_rpCLRTypes[index] = pMT; - return pMT; -} - -MethodTable* AppDomain::LoadRedirectedType(WinMDAdapter::RedirectedTypeIndex index, WinMDAdapter::FrameworkAssemblyIndex assembly) -{ - CONTRACTL - { - THROWS; - GC_TRIGGERS; - MODE_ANY; - PRECONDITION(index < WinMDAdapter::RedirectedTypeIndex_Count); - } - CONTRACTL_END; - - LPCSTR szClrNamespace; - LPCSTR szClrName; - LPCSTR szFullWinRTName; - WinMDAdapter::FrameworkAssemblyIndex nFrameworkAssemblyIndex; - - WinMDAdapter::GetRedirectedTypeInfo(index, &szClrNamespace, &szClrName, &szFullWinRTName, &nFrameworkAssemblyIndex, nullptr, nullptr); - - _ASSERTE(nFrameworkAssemblyIndex >= WinMDAdapter::FrameworkAssembly_Mscorlib && - nFrameworkAssemblyIndex < WinMDAdapter::FrameworkAssembly_Count); - - if (assembly != nFrameworkAssemblyIndex) - { - // The framework type does not live in the assembly we were requested to load redirected types from - return nullptr; - } - else if (nFrameworkAssemblyIndex == WinMDAdapter::FrameworkAssembly_Mscorlib) - { - return ClassLoader::LoadTypeByNameThrowing(MscorlibBinder::GetModule()->GetAssembly(), - szClrNamespace, - szClrName, - ClassLoader::ThrowIfNotFound, - ClassLoader::LoadTypes, - CLASS_LOAD_EXACTPARENTS).GetMethodTable(); - } - else - { - LPCSTR pSimpleName; - AssemblyMetaDataInternal context; - const BYTE * pbKeyToken; - DWORD cbKeyTokenLength; - DWORD dwFlags; - - WinMDAdapter::GetExtraAssemblyRefProps(nFrameworkAssemblyIndex, - &pSimpleName, - &context, - &pbKeyToken, - &cbKeyTokenLength, - &dwFlags); - - Assembly* pAssembly = AssemblySpec::LoadAssembly(pSimpleName, - &context, - pbKeyToken, - cbKeyTokenLength, - dwFlags); - - return ClassLoader::LoadTypeByNameThrowing( - pAssembly, - szClrNamespace, - szClrName, - ClassLoader::ThrowIfNotFound, - ClassLoader::LoadTypes, - CLASS_LOAD_EXACTPARENTS).GetMethodTable(); - } -} -#endif //FEATURE_COMINTEROP - #endif //!DACCESS_COMPILE #ifndef DACCESS_COMPILE @@ -3772,7 +3207,6 @@ DomainAssembly *AppDomain::LoadDomainAssemblyInternal(AssemblySpec* pIdentity, } // Cache result in all cases, since found pFile could be from a different AssemblyRef than pIdentity - // Do not cache WindowsRuntime assemblies, they are cached in code:CLRPrivTypeCacheWinRT if (pIdentity == NULL) { AssemblySpec spec; @@ -4060,9 +3494,6 @@ static void NormalizeAssemblySpecForNativeDependencies(AssemblySpec * pSpec) pContext->usMinorVersion = (USHORT)-1; pContext->usBuildNumber = (USHORT)-1; pContext->usRevisionNumber = (USHORT)-1; - - // Ignore the WinRT type while considering if two assemblies have the same identity. - pSpec->SetWindowsRuntimeType(NULL, NULL); } void AppDomain::CheckForMismatchedNativeImages(AssemblySpec * pSpec, const GUID * pGuid) @@ -4743,81 +4174,6 @@ PEAssembly * AppDomain::BindAssemblySpec( BinderTracing::AssemblyBindOperation bindOperation(pSpec); -#if defined(FEATURE_COMINTEROP) - // Handle WinRT assemblies in the classic/hybrid scenario. If this is an AppX process, - // then this case will be handled by the previous block as part of the full set of - // available binding hosts. - if (pSpec->IsContentType_WindowsRuntime()) - { - HRESULT hr = S_OK; - - // Get the assembly display name. - ReleaseHolder pAssemblyName; - - IfFailThrow(pSpec->CreateFusionName(&pAssemblyName, TRUE, TRUE)); - - - PEAssemblyHolder pAssembly; - - EX_TRY - { - hr = BindAssemblySpecForHostedBinder(pSpec, pAssemblyName, m_pWinRtBinder, &pAssembly); - if (FAILED(hr)) - goto EndTry2; // Goto end of try block. - - PTR_CLRPrivAssemblyWinRT assem = dac_cast(pAssembly->GetHostAssembly()); - assem->SetFallbackBinder(pSpec->GetFallbackLoadContextBinderForRequestingAssembly()); -EndTry2:; - } - // The combination of this conditional catch/ the following if statement which will throw reduces the count of exceptions - // thrown in scenarios where the exception does not escape the method. We cannot get rid of the try/catch block, as - // there are cases within some of the clrpriv binder's which throw. - // Note: In theory, FileNotFound should always come here as HRESULT, never as exception. - EX_CATCH_HRESULT_IF(hr, - !fThrowOnFileNotFound && Assembly::FileNotFound(hr)) - - if (FAILED(hr) && (fThrowOnFileNotFound || !Assembly::FileNotFound(hr))) - { - if (Assembly::FileNotFound(hr)) - { - _ASSERTE(fThrowOnFileNotFound); - // Uses defaultScope - EEFileLoadException::Throw(pSpec, hr); - } - - // WinRT type bind failures - _ASSERTE(pSpec->IsContentType_WindowsRuntime()); - if (hr == HRESULT_FROM_WIN32(APPMODEL_ERROR_NO_PACKAGE)) // Returned by RoResolveNamespace when using 3rd party WinRT types in classic process - { - if (fThrowOnFileNotFound) - { // Throw NotSupportedException (with custom message) wrapped by TypeLoadException to give user type name for diagnostics - // Note: TypeLoadException is equivalent of FileNotFound in WinRT world - EEMessageException ex(kNotSupportedException, IDS_EE_WINRT_THIRDPARTY_NOTSUPPORTED); - EX_THROW_WITH_INNER(EETypeLoadException, (pSpec->GetWinRtTypeNamespace(), pSpec->GetWinRtTypeClassName(), nullptr, nullptr, IDS_EE_WINRT_LOADFAILURE), &ex); - } - } - else if ((hr == CLR_E_BIND_UNRECOGNIZED_IDENTITY_FORMAT) || // Returned e.g. for WinRT type name without namespace - (hr == COR_E_PLATFORMNOTSUPPORTED)) // Using WinRT on pre-Win8 OS - { - if (fThrowOnFileNotFound) - { // Throw ArgumentException/PlatformNotSupportedException wrapped by TypeLoadException to give user type name for diagnostics - // Note: TypeLoadException is equivalent of FileNotFound in WinRT world - EEMessageException ex(hr); - EX_THROW_WITH_INNER(EETypeLoadException, (pSpec->GetWinRtTypeNamespace(), pSpec->GetWinRtTypeClassName(), nullptr, nullptr, IDS_EE_WINRT_LOADFAILURE), &ex); - } - } - else - { - IfFailThrow(hr); - } - } - _ASSERTE((FAILED(hr) && !fThrowOnFileNotFound) || pAssembly != nullptr); - - bindOperation.SetResult(pAssembly.GetValue()); - return pAssembly.Extract(); - } - else -#endif // FEATURE_COMINTEROP if (pSpec->HasUniqueIdentity()) { HRESULT hrBindResult = S_OK; @@ -5370,8 +4726,6 @@ void AppDomain::ReleaseRCWs(LPVOID pCtxCookie) WRAPPER_NO_CONTRACT; if (m_pRCWCache) m_pRCWCache->ReleaseWrappersWorker(pCtxCookie); - - RemoveWinRTFactoryObjects(pCtxCookie); } void AppDomain::DetachRCWs() @@ -6337,19 +5691,6 @@ HRESULT RuntimeInvokeHostAssemblyResolver(INT_PTR pManagedAssemblyLoadContextToB { _ASSERTE(pResolvedAssembly != NULL); -#ifdef FEATURE_COMINTEROP - // Is the assembly already bound using a binding context that will be incompatible? - // An example is attempting to consume an assembly bound to WinRT binder. - if (AreSameBinderInstance(pResolvedAssembly, GetAppDomain()->GetWinRtBinder())) - { - // It is invalid to return an assembly bound to an incompatible binder - *ppLoadedAssembly = NULL; - SString name; - spec.GetFileOrDisplayName(0, name); - COMPlusThrowHR(COR_E_INVALIDOPERATION, IDS_HOST_ASSEMBLY_RESOLVER_INCOMPATIBLE_BINDING_CONTEXT, name); - } -#endif // FEATURE_COMINTEROP - // Get the ICLRPrivAssembly reference to return back to. *ppLoadedAssembly = clr::SafeAddRef(pResolvedAssembly); hr = S_OK; @@ -6695,23 +6036,6 @@ void AppDomain::UnPublishHostedAssembly( } } -#if defined(FEATURE_COMINTEROP) -HRESULT AppDomain::SetWinrtApplicationContext(LPCWSTR pwzAppLocalWinMD) -{ - STANDARD_VM_CONTRACT; - - _ASSERTE(WinRTSupported()); - _ASSERTE(m_pWinRtBinder != nullptr); - - _ASSERTE(GetTPABinderContext() != NULL); - BINDER_SPACE::ApplicationContext *pApplicationContext = GetTPABinderContext()->GetAppContext(); - _ASSERTE(pApplicationContext != NULL); - - return m_pWinRtBinder->SetApplicationContext(pApplicationContext, pwzAppLocalWinMD); -} - -#endif // FEATURE_COMINTEROP - #endif //!DACCESS_COMPILE //--------------------------------------------------------------------------------------------------------------------- @@ -6756,9 +6080,6 @@ void ZapperSetBindingPaths(ICorCompilationDomain *pDomain, SString &trustedPlatf CLRPrivBinderCoreCLR *pBinder = ((CompilationDomain *)pDomain)->GetTPABinderContext(); _ASSERTE(pBinder != NULL); pBinder->SetupBindingPaths(trustedPlatformAssemblies, platformResourceRoots, appPaths, appNiPaths); -#ifdef FEATURE_COMINTEROP - ((CompilationDomain*)pDomain)->SetWinrtApplicationContext(NULL); -#endif } #endif diff --git a/src/coreclr/src/vm/appdomain.hpp b/src/coreclr/src/vm/appdomain.hpp index f017b42..afdee41 100644 --- a/src/coreclr/src/vm/appdomain.hpp +++ b/src/coreclr/src/vm/appdomain.hpp @@ -34,12 +34,6 @@ #include "multicorejit.h" #endif -#ifdef FEATURE_COMINTEROP -#include "clrprivbinderwinrt.h" -#include "..\md\winmd\inc\adapter.h" -#include "winrttypenameconverter.h" -#endif // FEATURE_COMINTEROP - #include "appxutil.h" #include "tieredcompilation.h" @@ -974,11 +968,6 @@ public: return m_pMngStdInterfacesInfo; } - - PTR_CLRPrivBinderWinRT GetWinRtBinder() - { - return m_pWinRtBinder; - } #endif // FEATURE_COMINTEROP #ifdef _DEBUG BOOL OwnDomainLocalBlockLock() @@ -1158,7 +1147,6 @@ protected: CrstExplicitInit m_InteropDataCrst; // Used for COM Interop compatiblilty // Used to protect the reference lists in the collectible loader allocators attached to this appdomain CrstExplicitInit m_crstLoaderAllocatorReferences; - CrstExplicitInit m_WinRTFactoryCacheCrst; // For WinRT factory cache //#AssemblyListLock // Used to protect the assembly list. Taken also by GC or debugger thread, therefore we have to avoid @@ -1182,9 +1170,6 @@ protected: #ifdef FEATURE_COMINTEROP // Information regarding the managed standard interfaces. MngStdInterfacesInfo *m_pMngStdInterfacesInfo; - - // WinRT binder - PTR_CLRPrivBinderWinRT m_pWinRtBinder; #endif // FEATURE_COMINTEROP // Protects allocation of slot IDs for thread statics @@ -1248,17 +1233,6 @@ public: } }; friend class LoadLockHolder; - class WinRTFactoryCacheLockHolder : public CrstHolder - { - public: - WinRTFactoryCacheLockHolder(BaseDomain *pD) - : CrstHolder(&pD->m_WinRTFactoryCacheCrst) - { - WRAPPER_NO_CONTRACT; - } - }; - friend class WinRTFactoryCacheLockHolder; - public: void InitVSD(); RangeList *GetCollectibleVSDRanges() { return &m_collVSDRanges; } @@ -1522,97 +1496,6 @@ struct FailedAssembly { } }; -#ifdef FEATURE_COMINTEROP - -// Cache used by COM Interop -struct NameToTypeMapEntry -{ - // Host space representation of the key - struct Key - { - LPCWSTR m_wzName; // The type name or registry string representation of the GUID "{}" - SIZE_T m_cchName; // wcslen(m_wzName) for faster hashtable lookup - }; - struct DacKey - { - PTR_CWSTR m_wzName; // The type name or registry string representation of the GUID "{}" - SIZE_T m_cchName; // wcslen(m_wzName) for faster hashtable lookup - } m_key; - TypeHandle m_typeHandle; // Using TypeHandle instead of MethodTable* to avoid losing information when sharing method tables. - UINT m_nEpoch; // tracks creation Epoch. This is incremented each time an external reader enumerate the cache - BYTE m_bFlags; -}; - -typedef DPTR(NameToTypeMapEntry) PTR_NameToTypeMapEntry; - -class NameToTypeMapTraits : public NoRemoveSHashTraits< DefaultSHashTraits > -{ -public: - typedef NameToTypeMapEntry::Key key_t; - - static const NameToTypeMapEntry Null() { NameToTypeMapEntry e; e.m_key.m_wzName = NULL; e.m_key.m_cchName = 0; return e; } - static bool IsNull(const NameToTypeMapEntry &e) { return e.m_key.m_wzName == NULL; } - static const key_t GetKey(const NameToTypeMapEntry &e) - { - key_t key; - key.m_wzName = (LPCWSTR)(e.m_key.m_wzName); // this cast brings the string over to the host, in a DAC build - key.m_cchName = e.m_key.m_cchName; - - return key; - } - static count_t Hash(const key_t &key) { WRAPPER_NO_CONTRACT; return HashStringN(key.m_wzName, key.m_cchName); } - - static BOOL Equals(const key_t &lhs, const key_t &rhs) - { - WRAPPER_NO_CONTRACT; - return (lhs.m_cchName == rhs.m_cchName) && memcmp(lhs.m_wzName, rhs.m_wzName, lhs.m_cchName * sizeof(WCHAR)) == 0; - } - - void OnDestructPerEntryCleanupAction(const NameToTypeMapEntry& e) - { - WRAPPER_NO_CONTRACT; - _ASSERTE(e.m_key.m_cchName == wcslen(e.m_key.m_wzName)); -#ifndef DACCESS_COMPILE - delete [] e.m_key.m_wzName; -#endif // DACCESS_COMPILE - } - static const bool s_DestructPerEntryCleanupAction = true; -}; - -typedef SHash NameToTypeMapTable; - -typedef DPTR(NameToTypeMapTable) PTR_NameToTypeMapTable; - -struct WinRTFactoryCacheEntry -{ - typedef MethodTable *Key; - Key key; // Type as KEY - - CtxEntry *m_pCtxEntry; // Context entry - used to verify whether the cache is a match - OBJECTHANDLE m_ohFactoryObject; // Handle to factory object -}; - -class WinRTFactoryCacheTraits : public DefaultSHashTraits -{ -public: - typedef WinRTFactoryCacheEntry::Key key_t; - static const WinRTFactoryCacheEntry Null() { WinRTFactoryCacheEntry e; e.key = NULL; return e; } - static bool IsNull(const WinRTFactoryCacheEntry &e) { return e.key == NULL; } - static const WinRTFactoryCacheEntry::Key GetKey(const WinRTFactoryCacheEntry& e) { return e.key; } - static count_t Hash(WinRTFactoryCacheEntry::Key key) { return (count_t)((size_t)key); } - static BOOL Equals(WinRTFactoryCacheEntry::Key lhs, WinRTFactoryCacheEntry::Key rhs) - { return lhs == rhs; } - static const WinRTFactoryCacheEntry Deleted() { WinRTFactoryCacheEntry e; e.key = (MethodTable *)-1; return e; } - static bool IsDeleted(const WinRTFactoryCacheEntry &e) { return e.key == (MethodTable *)-1; } - - static void OnDestructPerEntryCleanupAction(const WinRTFactoryCacheEntry& e); - static const bool s_DestructPerEntryCleanupAction = true; -}; - -typedef SHash WinRTFactoryCache; - -#endif // FEATURE_COMINTEROP - class AppDomainIterator; const DWORD DefaultADID = 1; @@ -1658,10 +1541,6 @@ public: // Initializes an AppDomain. (this functions is not called from the SystemDomain) void Init(); -#if defined(FEATURE_COMINTEROP) - HRESULT SetWinrtApplicationContext(LPCWSTR pwzAppLocalWinMD); -#endif // FEATURE_COMINTEROP - bool MustForceTrivialWaitOperations(); void SetForceTrivialWaitOperations(); @@ -1680,10 +1559,6 @@ public: OBJECTREF GetRawExposedObject() { LIMITED_METHOD_CONTRACT; return NULL; } OBJECTHANDLE GetRawExposedObjectHandleForDebugger() { LIMITED_METHOD_DAC_CONTRACT; return NULL; } -#ifdef FEATURE_COMINTEROP - MethodTable *GetRedirectedType(WinMDAdapter::RedirectedTypeIndex index); -#endif // FEATURE_COMINTEROP - //**************************************************************************************** @@ -2129,55 +2004,7 @@ public: void InsertClassForCLSID(MethodTable* pMT, BOOL fForceInsert = FALSE); #ifdef FEATURE_COMINTEROP -private: - void CacheTypeByNameWorker(const SString &ssClassName, const UINT vCacheVersion, TypeHandle typeHandle, BYTE flags, BOOL bReplaceExisting = FALSE); - TypeHandle LookupTypeByNameWorker(const SString &ssClassName, UINT *pvCacheVersion, BYTE *pbFlags); public: - // Used by COM Interop for mapping WinRT runtime class names to real types. - void CacheTypeByName(const SString &ssClassName, const UINT vCacheVersion, TypeHandle typeHandle, BYTE flags, BOOL bReplaceExisting = FALSE); - TypeHandle LookupTypeByName(const SString &ssClassName, UINT *pvCacheVersion, BYTE *pbFlags); - PTR_MethodTable LookupTypeByGuid(const GUID & guid); - -#ifndef DACCESS_COMPILE - inline BOOL CanCacheWinRTTypeByGuid(TypeHandle typeHandle) - { - CONTRACTL - { - THROWS; - GC_NOTRIGGER; - MODE_ANY; - } - CONTRACTL_END; - - // Only allow caching guid/types maps for types loaded during - // "normal" domain operation - if (IsCompilationDomain() || (m_Stage < STAGE_OPEN)) - return FALSE; - - MethodTable *pMT = typeHandle.GetMethodTable(); - if (pMT != NULL) - { - // Don't cache mscorlib-internal declarations of WinRT types. - if (pMT->GetModule()->IsSystem() && pMT->IsProjectedFromWinRT()) - return FALSE; - - // Don't cache redirected WinRT types. - if (WinRTTypeNameConverter::IsRedirectedWinRTSourceType(pMT)) - return FALSE; - } - - return TRUE; - } -#endif // !DACCESS_COMPILE - - void CacheWinRTTypeByGuid(TypeHandle typeHandle); - void GetCachedWinRTTypes(SArray * pTypes, SArray * pGuids, UINT minEpoch, UINT * pCurEpoch); - - // Used by COM Interop for caching WinRT factory objects. - void CacheWinRTFactoryObject(MethodTable *pClassMT, OBJECTREF *refFactory, LPVOID lpCtxCookie); - OBJECTREF LookupWinRTFactoryObject(MethodTable *pClassMT, LPVOID lpCtxCookie); - void RemoveWinRTFactoryObjects(LPVOID pCtxCookie); - MethodTable *LoadCOMClass(GUID clsid, BOOL bLoadRecord = FALSE, BOOL* pfAssemblyInReg = NULL); OBJECTREF GetMissingObject(); // DispatchInfo will call function to retrieve the Missing.Value object. #endif // FEATURE_COMINTEROP @@ -2327,10 +2154,6 @@ private: #ifdef FEATURE_COMINTEROP DispIDCache *m_pRefDispIDCache; OBJECTHANDLE m_hndMissing; //Handle points to Missing.Value Object which is used for [Optional] arg scenario during IDispatch CCW Call - - MethodTable* m_rpCLRTypes[WinMDAdapter::RedirectedTypeIndex_Count]; - - MethodTable* LoadRedirectedType(WinMDAdapter::RedirectedTypeIndex index, WinMDAdapter::FrameworkAssemblyIndex assembly); #endif // FEATURE_COMINTEROP public: @@ -2496,15 +2319,6 @@ private: PtrHashMap m_clsidHash; #ifdef FEATURE_COMINTEROP - // Hash table that maps WinRT class names to MethodTables. - PTR_NameToTypeMapTable m_pNameToTypeMap; - UINT m_vNameToTypeMapVersion; - - UINT m_nEpoch; // incremented each time m_pNameToTypeMap is enumerated - - // Hash table that remembers the last cached WinRT factory object per type per appdomain. - WinRTFactoryCache *m_pWinRTFactoryCache; - // this cache stores the RCWs in this domain RCWCache *m_pRCWCache; diff --git a/src/coreclr/src/vm/assembly.cpp b/src/coreclr/src/vm/assembly.cpp index 7f9c7f7..84a3585 100644 --- a/src/coreclr/src/vm/assembly.cpp +++ b/src/coreclr/src/vm/assembly.cpp @@ -118,8 +118,6 @@ Assembly::Assembly(BaseDomain *pDomain, PEAssembly* pFile, DebuggerAssemblyContr m_isDisabledPrivateReflection(0), #ifdef FEATURE_COMINTEROP m_pITypeLib(NULL), - m_winMDStatus(WinMDStatus_Unknown), - m_pManifestWinMDImport(NULL), #endif // FEATURE_COMINTEROP m_debuggerFlags(debuggerFlags), m_fTerminated(FALSE) @@ -254,11 +252,6 @@ Assembly::~Assembly() } #ifdef FEATURE_COMINTEROP - if (m_pManifestWinMDImport) - { - m_pManifestWinMDImport->Release(); - } - if (m_pITypeLib != nullptr && m_pITypeLib != Assembly::InvalidTypeLib) { m_pITypeLib->Release(); @@ -1042,47 +1035,22 @@ Module * Assembly::FindModuleByTypeRef( case mdtAssemblyRef: { + if(IsAfContentType_WindowsRuntime(pModule->GetAssemblyRefFlags(tkType))) + { + ThrowHR(COR_E_PLATFORMNOTSUPPORTED); + } + // Do this first because it has a strong contract Assembly * pAssembly = NULL; -#if defined(FEATURE_COMINTEROP) || !defined(DACCESS_COMPILE) - LPCUTF8 szNamespace = NULL; - LPCUTF8 szClassName = NULL; -#endif - -#ifdef FEATURE_COMINTEROP - if (pModule->HasBindableIdentity(tkType)) -#endif// FEATURE_COMINTEROP + if (loadFlag == Loader::SafeLookup) { - if (loadFlag == Loader::SafeLookup) - { - pAssembly = pModule->LookupAssemblyRef(tkType); - } - else - { - pAssembly = pModule->GetAssemblyIfLoaded(tkType); - } + pAssembly = pModule->LookupAssemblyRef(tkType); } -#ifdef FEATURE_COMINTEROP else { - _ASSERTE(IsAfContentType_WindowsRuntime(pModule->GetAssemblyRefFlags(tkType))); - - if (FAILED(pImport->GetNameOfTypeRef( - tkTopLevelEncloserTypeRef, - &szNamespace, - &szClassName))) - { - THROW_BAD_FORMAT(BFA_BAD_TYPEREF_TOKEN, pModule); - } - - pAssembly = pModule->GetAssemblyIfLoaded( - tkType, - szNamespace, - szClassName, - NULL); // pMDImportOverride + pAssembly = pModule->GetAssemblyIfLoaded(tkType); } -#endif // FEATURE_COMINTEROP if (pAssembly != NULL) { @@ -1098,10 +1066,7 @@ Module * Assembly::FindModuleByTypeRef( } - DomainAssembly * pDomainAssembly = pModule->LoadAssembly( - tkType, - szNamespace, - szClassName); + DomainAssembly * pDomainAssembly = pModule->LoadAssembly(tkType); if (pDomainAssembly == NULL) @@ -2196,75 +2161,6 @@ void DECLSPEC_NORETURN Assembly::ThrowBadImageException(LPCUTF8 pszNameSpace, COMPlusThrowHR(COR_E_BADIMAGEFORMAT, resIDWhy, fullName, displayName); } - -#ifdef FEATURE_COMINTEROP -Assembly::WinMDStatus Assembly::GetWinMDStatus() -{ - LIMITED_METHOD_CONTRACT; - - if (m_winMDStatus == WinMDStatus_Unknown) - { - IWinMDImport *pWinMDImport = GetManifestWinMDImport(); - if (pWinMDImport != NULL) - { - BOOL bIsWinMDExp; - VERIFY(SUCCEEDED(pWinMDImport->IsScenarioWinMDExp(&bIsWinMDExp))); - - if (bIsWinMDExp) - { - // this is a managed backed WinMD - m_winMDStatus = WinMDStatus_IsManagedWinMD; - } - else - { - // this is a pure WinMD - m_winMDStatus = WinMDStatus_IsPureWinMD; - } - } - else - { - // this is not a WinMD at all - m_winMDStatus = WinMDStatus_IsNotWinMD; - } - } - - return m_winMDStatus; -} - -bool Assembly::IsWinMD() -{ - LIMITED_METHOD_CONTRACT; - return GetWinMDStatus() != WinMDStatus_IsNotWinMD; -} - -bool Assembly::IsManagedWinMD() -{ - LIMITED_METHOD_CONTRACT; - return GetWinMDStatus() == WinMDStatus_IsManagedWinMD; -} - -IWinMDImport *Assembly::GetManifestWinMDImport() -{ - LIMITED_METHOD_CONTRACT; - - if (m_pManifestWinMDImport == NULL) - { - ReleaseHolder pWinMDImport; - if (SUCCEEDED(m_pManifest->GetMDImport()->QueryInterface(IID_IWinMDImport, (void **)&pWinMDImport))) - { - if (InterlockedCompareExchangeT(&m_pManifestWinMDImport, pWinMDImport, NULL) == NULL) - { - pWinMDImport.SuppressRelease(); - } - } - } - - return m_pManifestWinMDImport; -} - -#endif // FEATURE_COMINTEROP - - #endif // #ifndef DACCESS_COMPILE #ifndef DACCESS_COMPILE diff --git a/src/coreclr/src/vm/assembly.hpp b/src/coreclr/src/vm/assembly.hpp index 948ba8d..20ae17e 100644 --- a/src/coreclr/src/vm/assembly.hpp +++ b/src/coreclr/src/vm/assembly.hpp @@ -513,31 +513,11 @@ public: WRAPPER_NO_CONTRACT; return ((GetInteropAttributeMask() & INTEROP_ATTRIBUTE_PRIMARY_INTEROP_ASSEMBLY) != 0); } - - // Does this assembly contain windows metadata - bool IsWinMD(); - - // Does this assembly contain windows metadata with managed implementation - bool IsManagedWinMD(); - - // Returns the IWinMDImport interface of the manifest module metadata or NULL if this assembly is not a .winmd - IWinMDImport *GetManifestWinMDImport(); #endif protected: #ifdef FEATURE_COMINTEROP - enum WinMDStatus - { - WinMDStatus_Unknown, - WinMDStatus_IsPureWinMD, - WinMDStatus_IsManagedWinMD, - WinMDStatus_IsNotWinMD - }; - - // Determine if the assembly is a pure Windows Metadata file, contians managed implementation, or is not - // Windows Metadata at all. - WinMDStatus GetWinMDStatus(); enum InteropAttributeStatus { INTEROP_ATTRIBUTE_UNSET = 0, @@ -555,13 +535,10 @@ protected: int mask = INTEROP_ATTRIBUTE_UNSET; - if (!IsWinMD()) // ignore classic COM interop CAs in .winmd - { - if (GetManifestModule()->GetCustomAttribute(TokenFromRid(1, mdtAssembly), WellKnownAttribute::ImportedFromTypeLib, NULL, 0) == S_OK) - mask |= INTEROP_ATTRIBUTE_IMPORTED_FROM_TYPELIB; - if (GetManifestModule()->GetCustomAttribute(TokenFromRid(1, mdtAssembly), WellKnownAttribute::PrimaryInteropAssembly, NULL, 0) == S_OK) - mask |= INTEROP_ATTRIBUTE_PRIMARY_INTEROP_ASSEMBLY; - } + if (GetManifestModule()->GetCustomAttribute(TokenFromRid(1, mdtAssembly), WellKnownAttribute::ImportedFromTypeLib, NULL, 0) == S_OK) + mask |= INTEROP_ATTRIBUTE_IMPORTED_FROM_TYPELIB; + if (GetManifestModule()->GetCustomAttribute(TokenFromRid(1, mdtAssembly), WellKnownAttribute::PrimaryInteropAssembly, NULL, 0) == S_OK) + mask |= INTEROP_ATTRIBUTE_PRIMARY_INTEROP_ASSEMBLY; if (!IsDynamic()) { @@ -571,7 +548,7 @@ protected: return static_cast(mask); } -#endif // FEATURE_INTEROP +#endif // FEATURE_COMINTEROP private: @@ -606,9 +583,6 @@ private: // If a TypeLib is ever required for this module, cache the pointer here. ITypeLib *m_pITypeLib; InteropAttributeStatus m_InteropAttributeStatus; - - WinMDStatus m_winMDStatus; - IWinMDImport *m_pManifestWinMDImport; #endif // FEATURE_COMINTEROP DebuggerAssemblyControlFlags m_debuggerFlags; diff --git a/src/coreclr/src/vm/assemblynative.cpp b/src/coreclr/src/vm/assemblynative.cpp index 0cb1dba..3b85f68 100644 --- a/src/coreclr/src/vm/assemblynative.cpp +++ b/src/coreclr/src/vm/assemblynative.cpp @@ -412,26 +412,6 @@ void QCALLTYPE AssemblyNative::GetLocation(QCall::AssemblyHandle pAssembly, QCal END_QCALL; } - -#ifdef FEATURE_COMINTEROP_WINRT_MANAGED_ACTIVATION -void QCALLTYPE AssemblyNative::LoadTypeForWinRTTypeNameInContext(INT_PTR ptrAssemblyLoadContext, LPCWSTR pwzTypeName, QCall::ObjectHandleOnStack retType) -{ - QCALL_CONTRACT; - - BEGIN_QCALL; - - TypeHandle loadedType = WinRTTypeNameConverter::LoadManagedTypeForWinRTTypeName(pwzTypeName, (ICLRPrivBinder*)ptrAssemblyLoadContext, /* pbIsPrimitive */ nullptr); - - if (!loadedType.IsNull()) - { - GCX_COOP(); - retType.Set(loadedType.GetManagedClassObject()); - } - - END_QCALL; -} -#endif - void QCALLTYPE AssemblyNative::GetType(QCall::AssemblyHandle pAssembly, LPCWSTR wszName, BOOL bThrowOnError, @@ -469,7 +449,7 @@ void QCALLTYPE AssemblyNative::GetType(QCall::AssemblyHandle pAssembly, } // Load the class from this assembly (fail if it is in a different one). - retTypeHandle = TypeName::GetTypeManaged(wszName, pAssembly, bThrowOnError, bIgnoreCase, prohibitAsmQualifiedName, pAssembly->GetAssembly(), FALSE, (OBJECTREF*)keepAlive.m_ppObject, pPrivHostBinder); + retTypeHandle = TypeName::GetTypeManaged(wszName, pAssembly, bThrowOnError, bIgnoreCase, prohibitAsmQualifiedName, pAssembly->GetAssembly(), (OBJECTREF*)keepAlive.m_ppObject, pPrivHostBinder); if (!retTypeHandle.IsNull()) { diff --git a/src/coreclr/src/vm/assemblynative.hpp b/src/coreclr/src/vm/assemblynative.hpp index a74ca26..7c6c184 100644 --- a/src/coreclr/src/vm/assemblynative.hpp +++ b/src/coreclr/src/vm/assemblynative.hpp @@ -121,9 +121,6 @@ public: static void QCALLTYPE LoadFromInMemoryModule(INT_PTR ptrNativeAssemblyLoadContext, INT_PTR hModule, QCall::ObjectHandleOnStack retLoadedAssembly); #endif static Assembly* LoadFromPEImage(ICLRPrivBinder* pBinderContext, PEImage *pILImage, PEImage *pNIImage); -#ifdef FEATURE_COMINTEROP_WINRT_MANAGED_ACTIVATION - static void QCALLTYPE LoadTypeForWinRTTypeNameInContext(INT_PTR ptrAssemblyLoadContext, LPCWSTR pwzTypeName, QCall::ObjectHandleOnStack retType); -#endif static INT_PTR QCALLTYPE GetLoadContextForAssembly(QCall::AssemblyHandle pAssembly); static BOOL QCALLTYPE InternalTryGetRawMetadata(QCall::AssemblyHandle assembly, UINT8 **blobRef, INT32 *lengthRef); diff --git a/src/coreclr/src/vm/assemblyspec.cpp b/src/coreclr/src/vm/assemblyspec.cpp index 8c9c2f1..cbf8d4a 100644 --- a/src/coreclr/src/vm/assemblyspec.cpp +++ b/src/coreclr/src/vm/assemblyspec.cpp @@ -26,7 +26,6 @@ #ifdef FEATURE_COMINTEROP #include "clrprivbinderutil.h" -#include "winrthelpers.h" #endif #include "../binder/inc/bindertracing.h" @@ -208,22 +207,6 @@ HRESULT AssemblySpec::InitializeSpecInternal(mdToken kAssemblyToken, { IfFailThrow(BaseAssemblySpec::Init(kAssemblyToken,pImport)); - if (IsContentType_WindowsRuntime()) - { - if (!fAllowAllocation) - { // We don't support this because we must be able to allocate in order to - // extract embedded type names for the native image scenario. Currently, - // the only caller of this method with fAllowAllocation == FALSE is - // Module::GetAssemblyIfLoaded, and since this method will only check the - // assembly spec cache, and since we can't cache WinRT assemblies, this - // limitation should have no negative impact. - IfFailThrow(E_FAIL); - } - - // Extract embedded content, if present (currently used for embedded WinRT type names). - ParseEncodedName(); - } - // For static binds, we cannot reference a weakly named assembly from a strong named one. // (Note that this constraint doesn't apply to dynamic binds which is why this check is // not farther down the stack.) @@ -259,21 +242,6 @@ void AssemblySpec::InitializeSpec(PEAssembly * pFile) InitializeSpec(a, pImport, NULL); -#ifdef FEATURE_COMINTEROP - if (IsContentType_WindowsRuntime()) - { - LPCSTR szNamespace; - LPCSTR szTypeName; - SString ssFakeNameSpaceAllocationBuffer; - IfFailThrow(::GetFirstWinRTTypeDef(pImport, &szNamespace, &szTypeName, pFile->GetPath(), &ssFakeNameSpaceAllocationBuffer)); - - SetWindowsRuntimeType(szNamespace, szTypeName); - - // pFile is not guaranteed to stay around (it might be unloaded with the AppDomain), we have to copy the type name - CloneFields(WINRT_TYPE_NAME_OWNED); - } -#endif //FEATURE_COMINTEROP - // Set the binding context for the AssemblySpec ICLRPrivBinder* pCurrentBinder = GetBindingContext(); ICLRPrivBinder* pExpectedBinder = pFile->GetBindingContext(); @@ -431,9 +399,6 @@ HRESULT AssemblySpec::InitializeSpec(StackingAllocator* alloc, ASSEMBLYNAMEREF* CloneFieldsToStackingAllocator(alloc); - // Extract embedded WinRT name, if present. - ParseEncodedName(); - return S_OK; } @@ -780,32 +745,6 @@ ICLRPrivBinder* AssemblySpec::GetBindingContextFromParentAssembly(AppDomain *pDo } } -#if defined(FEATURE_COMINTEROP) - if (!IsContentType_WindowsRuntime() && (pParentAssemblyBinder != NULL)) - { - CLRPrivBinderWinRT *pWinRTBinder = pDomain->GetWinRtBinder(); - if (AreSameBinderInstance(pWinRTBinder, pParentAssemblyBinder)) - { - // We could be here when a non-WinRT assembly load is triggerred by a winmd (e.g. System.Runtime being loaded due to - // types being referenced from Windows.Foundation.Winmd). - // - // If the AssemblySpec does not correspond to WinRT type but our parent assembly binder is a WinRT binder, - // then such an assembly will not be found by the binder. - // In such a case, the parent binder should be the fallback binder for the WinRT assembly if one exists. - ICLRPrivBinder* pParentWinRTBinder = pParentAssemblyBinder; - pParentAssemblyBinder = NULL; - ReleaseHolder assembly; - if (SUCCEEDED(pParentWinRTBinder->QueryInterface(&assembly))) - { - pParentAssemblyBinder = dac_cast(assembly.GetValue())->GetFallbackBinder(); - - // The fallback binder should not be a WinRT binder. - _ASSERTE(!AreSameBinderInstance(pWinRTBinder, pParentAssemblyBinder)); - } - } - } -#endif // defined(FEATURE_COMINTEROP) - if (!pParentAssemblyBinder) { // We can be here when loading assemblies via the host (e.g. ICLRRuntimeHost2::ExecuteAssembly) or dealing with assemblies @@ -944,7 +883,7 @@ HRESULT AssemblySpec::EmitToken( EX_TRY { SmallStackSString ssName; - fMustBeBindable ? GetEncodedName(ssName) : GetName(ssName); + GetName(ssName); ASSEMBLYMETADATA AMD; @@ -1010,94 +949,6 @@ HRESULT AssemblySpec::EmitToken( // that were built from WinRT AssemblySpec objects, extracts the encoded type name, and sets // the type namespace and class name properties appropriately. -void AssemblySpec::ParseEncodedName() -{ - CONTRACTL { - THROWS; - GC_NOTRIGGER; - MODE_ANY; - } CONTRACTL_END - -#ifdef FEATURE_COMINTEROP - if (IsContentType_WindowsRuntime()) - { - StackSString ssEncodedName(SString::Utf8, m_pAssemblyName); - ssEncodedName.Normalize(); - - SString::Iterator itBang = ssEncodedName.Begin(); - if (ssEncodedName.Find(itBang, SL(W("!")))) - { - StackSString ssAssemblyName(ssEncodedName, ssEncodedName.Begin(), itBang - ssEncodedName.Begin()); - StackSString ssTypeName(ssEncodedName, ++itBang, ssEncodedName.End() - itBang); - SetName(ssAssemblyName); - SetWindowsRuntimeType(ssTypeName); - } - } -#endif -} - -void AssemblySpec::SetWindowsRuntimeType( - LPCUTF8 szNamespace, - LPCUTF8 szClassName) -{ - CONTRACTL - { - THROWS; - GC_NOTRIGGER; - MODE_ANY; - } - CONTRACTL_END; -#ifdef FEATURE_COMINTEROP - // Release already allocated string - if (m_ownedFlags & WINRT_TYPE_NAME_OWNED) - { - if (m_szWinRtTypeNamespace != nullptr) - delete [] m_szWinRtTypeNamespace; - if (m_szWinRtTypeClassName != nullptr) - delete [] m_szWinRtTypeClassName; - } - m_szWinRtTypeNamespace = szNamespace; - m_szWinRtTypeClassName = szClassName; - - m_ownedFlags &= ~WINRT_TYPE_NAME_OWNED; -#else - // Classic (non-phone) CoreCLR does not support WinRT interop; this should never be called with a non-empty type name - _ASSERTE((szNamespace == NULL) && (szClassName == NULL)); -#endif -} - -void AssemblySpec::SetWindowsRuntimeType( - SString const & _ssTypeName) -{ - CONTRACTL - { - THROWS; - GC_NOTRIGGER; - MODE_ANY; - } - CONTRACTL_END; - - // Release already allocated string - if (m_ownedFlags & WINRT_TYPE_NAME_OWNED) - { - if (m_szWinRtTypeNamespace != nullptr) - delete[] m_szWinRtTypeNamespace; - if (m_szWinRtTypeClassName != nullptr) - delete[] m_szWinRtTypeClassName; - m_ownedFlags &= ~WINRT_TYPE_NAME_OWNED; - } - - SString ssTypeName; - _ssTypeName.ConvertToUTF8(ssTypeName); - - LPUTF8 szTypeName = (LPUTF8)ssTypeName.GetUTF8NoConvert(); - ns::SplitInline(szTypeName, m_szWinRtTypeNamespace, m_szWinRtTypeClassName); - m_ownedFlags &= ~WINRT_TYPE_NAME_OWNED; - // Make a copy of the type name strings - CloneFields(WINRT_TYPE_NAME_OWNED); -} - - AssemblySpecBindingCache::AssemblySpecBindingCache() { LIMITED_METHOD_CONTRACT; diff --git a/src/coreclr/src/vm/assemblyspec.hpp b/src/coreclr/src/vm/assemblyspec.hpp index 9fa6ad38..ca7d73f 100644 --- a/src/coreclr/src/vm/assemblyspec.hpp +++ b/src/coreclr/src/vm/assemblyspec.hpp @@ -54,8 +54,6 @@ class AssemblySpec : public BaseAssemblySpec // functions that take special care (and thus are allowed to use the function) are listed below friend Assembly * Module::GetAssemblyIfLoaded( mdAssemblyRef kAssemblyRef, - LPCSTR szWinRtNamespace, - LPCSTR szWinRtClassName, IMDInternalImport * pMDImportOverride, BOOL fDoNotUtilizeExtraChecks, ICLRPrivBinder *pBindingContextForLoadedAssembly); @@ -232,11 +230,6 @@ class AssemblySpec : public BaseAssemblySpec return m_pAppDomain; } - void ParseEncodedName(); - - void SetWindowsRuntimeType(LPCUTF8 szNamespace, LPCUTF8 szClassName); - void SetWindowsRuntimeType(SString const & _ssTypeName); - inline HRESULT SetContentType(AssemblyContentType type) { LIMITED_METHOD_CONTRACT; @@ -247,8 +240,8 @@ class AssemblySpec : public BaseAssemblySpec } else if (type == AssemblyContentType_WindowsRuntime) { - m_dwFlags = (m_dwFlags & ~afContentType_Mask) | afContentType_WindowsRuntime; - return S_OK; + // WinRT assemblies are not supported as direct references. + return COR_E_PLATFORMNOTSUPPORTED; } else { @@ -257,20 +250,6 @@ class AssemblySpec : public BaseAssemblySpec } } - // Returns true if the object can be used to bind to the target assembly. - // One case in which this is not true is when the content type is WinRT - // but no type name has been set. - inline bool HasBindableIdentity() const - { - STATIC_CONTRACT_LIMITED_METHOD; -#ifdef FEATURE_COMINTEROP - return (HasUniqueIdentity() || - (IsContentType_WindowsRuntime() && (GetWinRtTypeClassName() != NULL))); -#else - return TRUE; -#endif - } - inline BOOL CanUseWithBindingCache() const { STATIC_CONTRACT_LIMITED_METHOD; diff --git a/src/coreclr/src/vm/baseassemblyspec.cpp b/src/coreclr/src/vm/baseassemblyspec.cpp index 0406ec1..515e811 100644 --- a/src/coreclr/src/vm/baseassemblyspec.cpp +++ b/src/coreclr/src/vm/baseassemblyspec.cpp @@ -69,26 +69,6 @@ VOID BaseAssemblySpec::CloneFieldsToStackingAllocator( StackingAllocator* alloc) m_wszCodeBase = temp; } - if ((~m_ownedFlags & WINRT_TYPE_NAME_OWNED)) { - if (m_szWinRtTypeNamespace) - { - S_UINT32 len = S_UINT32((DWORD) strlen(m_szWinRtTypeNamespace)) + S_UINT32(1); - if(len.IsOverflow()) COMPlusThrowHR(COR_E_OVERFLOW); - LPSTR temp = (LPSTR)alloc->Alloc(len*S_UINT32(sizeof(CHAR))); - strcpy_s(temp, len.Value(), m_szWinRtTypeNamespace); - m_szWinRtTypeNamespace = temp; - } - - if (m_szWinRtTypeClassName) - { - S_UINT32 len = S_UINT32((DWORD) strlen(m_szWinRtTypeClassName)) + S_UINT32(1); - if(len.IsOverflow()) COMPlusThrowHR(COR_E_OVERFLOW); - LPSTR temp = (LPSTR)alloc->Alloc(len*S_UINT32(sizeof(CHAR))); - strcpy_s(temp, len.Value(), m_szWinRtTypeClassName); - m_szWinRtTypeClassName = temp; - } - } - _ASSERTE(hash == Hash()); } @@ -362,40 +342,6 @@ BOOL BaseAssemblySpec::RefMatchesDef(const BaseAssemblySpec* pRef, const BaseAss } } -//=========================================================================================== -// This function may embed additional information, if required. -// -// For WinRT (ContentType=WindowsRuntime) assembly specs, this will embed the type name in -// the IAssemblyName's ASM_NAME_NAME property; otherwise this just creates an IAssemblyName -// for the provided assembly spec. - -void BaseAssemblySpec::GetEncodedName(SString & ssEncodedName) const -{ - CONTRACTL { - THROWS; - GC_NOTRIGGER; - MODE_ANY; - } CONTRACTL_END - -#ifdef FEATURE_COMINTEROP - if (IsContentType_WindowsRuntime() && GetWinRtTypeClassName() != NULL) - { - ssEncodedName.SetUTF8(GetName()); - ssEncodedName.Append(SL(W("!"))); - if (GetWinRtTypeNamespace() != NULL) - { - ssEncodedName.AppendUTF8(GetWinRtTypeNamespace()); - ssEncodedName.Append(SL(W("."))); - } - ssEncodedName.AppendUTF8(GetWinRtTypeClassName()); - } - else -#endif - { - ssEncodedName.SetUTF8(m_pAssemblyName); - } -} - VOID BaseAssemblySpec::SetName(SString const & ssName) { CONTRACTL @@ -620,7 +566,7 @@ HRESULT BaseAssemblySpec::CreateFusionName( NonVMComHolder< IAssemblyName > holder(NULL); SmallStackSString ssAssemblyName; - fMustBeBindable ? GetEncodedName(ssAssemblyName) : GetName(ssAssemblyName); + GetName(ssAssemblyName); IfFailGo(CreateAssemblyNameObject(&pFusionAssemblyName, ssAssemblyName.GetUnicode(), false /*parseDisplayName*/)); diff --git a/src/coreclr/src/vm/baseassemblyspec.h b/src/coreclr/src/vm/baseassemblyspec.h index f5495c5..57cf2eb 100644 --- a/src/coreclr/src/vm/baseassemblyspec.h +++ b/src/coreclr/src/vm/baseassemblyspec.h @@ -27,8 +27,6 @@ protected: DWORD m_cbPublicKeyOrToken; DWORD m_dwFlags; // CorAssemblyFlags LPCWSTR m_wszCodeBase; // URL to the code - LPCSTR m_szWinRtTypeNamespace; - LPCSTR m_szWinRtTypeClassName; int m_ownedFlags; ICLRPrivBinder *m_pBindingContext; @@ -40,7 +38,7 @@ public: CODE_BASE_OWNED = 0x04, LOCALE_OWNED = 0x08, CODEBASE_OWNED = 0x10, - WINRT_TYPE_NAME_OWNED = 0x20, + // unused = 0x20, // Set if ParseName() returned illegal textual identity. // Cannot process the string any further. BAD_NAME_OWNED = 0x40, @@ -112,20 +110,6 @@ public: BOOL IsMscorlibSatellite() const; BOOL IsMscorlib(); - // - // Windows Runtime functions that could not be refactored out to AssemblySpec - // - inline LPCSTR GetWinRtTypeNamespace() const - { - LIMITED_METHOD_CONTRACT; - return m_szWinRtTypeNamespace; - } - inline LPCSTR GetWinRtTypeClassName() const - { - LIMITED_METHOD_CONTRACT; - return m_szWinRtTypeClassName; - } - //**************************************************************************************** // // Creates an IAssemblyName object representing this AssemblySpec. @@ -140,27 +124,11 @@ public: BOOL fIncludeCodeBase = TRUE, /* Used by fusion only */ BOOL fMustBeBindable = FALSE) const; - inline BOOL IsContentType_WindowsRuntime() const - { - LIMITED_METHOD_CONTRACT; -#ifdef FEATURE_COMINTEROP - return IsAfContentType_WindowsRuntime(m_dwFlags); -#else - return FALSE; -#endif - } - - void GetEncodedName(SString & ssEncodedName) const; - - // Returns true if this object uniquely identifies a single assembly; - // false otherwise. This will return false for Windows Runtime assemblies, - // as WinRT assembly names do not represent an identity. This method - // does not take into account additional attributes such as type namespace - // and name. + // Returns true inline BOOL HasUniqueIdentity() const { STATIC_CONTRACT_LIMITED_METHOD; - return !IsContentType_WindowsRuntime(); + return TRUE; } enum CompareExFlags diff --git a/src/coreclr/src/vm/baseassemblyspec.inl b/src/coreclr/src/vm/baseassemblyspec.inl index 71e78f2..541a3b0 100644 --- a/src/coreclr/src/vm/baseassemblyspec.inl +++ b/src/coreclr/src/vm/baseassemblyspec.inl @@ -49,10 +49,6 @@ inline BaseAssemblySpec::~BaseAssemblySpec() delete [] m_wszCodeBase; if (m_ownedFlags & LOCALE_OWNED) delete [] m_context.szLocale; - if (m_szWinRtTypeClassName && (m_ownedFlags & WINRT_TYPE_NAME_OWNED)) - delete [] m_szWinRtTypeClassName; - if (m_szWinRtTypeNamespace && (m_ownedFlags & WINRT_TYPE_NAME_OWNED)) - delete [] m_szWinRtTypeNamespace; } inline HRESULT BaseAssemblySpec::Init(LPCSTR pAssemblyName, @@ -133,32 +129,6 @@ inline VOID BaseAssemblySpec::CloneFields(int ownedFlags) m_ownedFlags |= CODEBASE_OWNED; } - if ((~m_ownedFlags & WINRT_TYPE_NAME_OWNED) && (ownedFlags & WINRT_TYPE_NAME_OWNED)) { - - NewArrayHolder nameTemp, namespaceTemp; - - if (m_szWinRtTypeClassName) { - - size_t nameLen = strlen(m_szWinRtTypeClassName) + 1; - nameTemp = new CHAR [nameLen]; - strcpy_s(nameTemp, nameLen, m_szWinRtTypeClassName); - } - - if (m_szWinRtTypeNamespace){ - - size_t namespaceLen = strlen(m_szWinRtTypeNamespace) + 1; - namespaceTemp = new CHAR [namespaceLen]; - strcpy_s(namespaceTemp, namespaceLen, m_szWinRtTypeNamespace); - } - - m_szWinRtTypeClassName = nameTemp.Extract(); - m_szWinRtTypeNamespace = namespaceTemp.Extract(); - if (m_szWinRtTypeClassName != NULL || m_szWinRtTypeNamespace != NULL) - { - m_ownedFlags |= WINRT_TYPE_NAME_OWNED; - } - } - _ASSERTE(hash == Hash()); } @@ -209,24 +179,6 @@ inline VOID BaseAssemblySpec::CloneFieldsToLoaderHeap(int flags, LoaderHeap *pHe m_wszCodeBase = temp; } - if ((~m_ownedFlags & WINRT_TYPE_NAME_OWNED) && (flags & WINRT_TYPE_NAME_OWNED)) { - if (m_szWinRtTypeNamespace) - { - size_t len = strlen(m_szWinRtTypeNamespace) + 1; - LPSTR temp = (LPSTR)pamTracker->Track( pHeap->AllocMem(S_SIZE_T(len*sizeof(CHAR))) ); - strcpy_s(temp, len, m_szWinRtTypeNamespace); - m_szWinRtTypeNamespace = temp; - } - - if (m_szWinRtTypeClassName) - { - size_t len = strlen(m_szWinRtTypeClassName) + 1; - LPSTR temp = (LPSTR)pamTracker->Track( pHeap->AllocMem(S_SIZE_T(len*sizeof(CHAR))) ); - strcpy_s(temp, len, m_szWinRtTypeClassName); - m_szWinRtTypeClassName = temp; - } - } - _ASSERTE(hash == Hash()); } @@ -251,8 +203,6 @@ inline void BaseAssemblySpec::CopyFrom(const BaseAssemblySpec *pSpec) m_ownedFlags = 0; m_wszCodeBase=pSpec->m_wszCodeBase; - m_szWinRtTypeNamespace = pSpec->m_szWinRtTypeNamespace; - m_szWinRtTypeClassName = pSpec->m_szWinRtTypeClassName; m_context = pSpec->m_context; @@ -315,19 +265,6 @@ inline DWORD BaseAssemblySpec::Hash() hash ^= HashStringA(m_context.szLocale); hash = _rotl(hash, 4); - if (m_szWinRtTypeNamespace) - { - hash ^= HashStringA(m_szWinRtTypeNamespace); - hash = _rotl(hash, 4); - } - - if (m_szWinRtTypeClassName) - { - hash ^= HashStringA(m_szWinRtTypeClassName); - hash = _rotl(hash, 4); - } - - return hash; } diff --git a/src/coreclr/src/vm/callhelpers.cpp b/src/coreclr/src/vm/callhelpers.cpp index 935eac9..3145cd5 100644 --- a/src/coreclr/src/vm/callhelpers.cpp +++ b/src/coreclr/src/vm/callhelpers.cpp @@ -21,7 +21,7 @@ #if defined(FEATURE_MULTICOREJIT) && defined(_DEBUG) -// Allow system module, and first party WinMD files for Appx +// Allow system module for Appx void AssertMulticoreJitAllowedModule(PCODE pTarget) { @@ -29,7 +29,6 @@ void AssertMulticoreJitAllowedModule(PCODE pTarget) Module * pModule = pMethod->GetModule_NoLogging(); - _ASSERTE(pModule->IsSystem()); } diff --git a/src/coreclr/src/vm/ceeload.cpp b/src/coreclr/src/vm/ceeload.cpp index acd979f..de89ecd 100644 --- a/src/coreclr/src/vm/ceeload.cpp +++ b/src/coreclr/src/vm/ceeload.cpp @@ -575,8 +575,7 @@ void Module::Initialize(AllocMemTracker *pamTracker, LPCWSTR szName) if (IsSystem() || (strcmp(m_pSimpleName, "System") == 0) || - (strcmp(m_pSimpleName, "System.Core") == 0) || - (strcmp(m_pSimpleName, "Windows.Foundation") == 0)) + (strcmp(m_pSimpleName, "System.Core") == 0)) { FastInterlockOr(&m_dwPersistedFlags, LOW_LEVEL_SYSTEM_ASSEMBLY_BY_NAME); } @@ -650,14 +649,6 @@ void Module::Initialize(AllocMemTracker *pamTracker, LPCWSTR szName) m_pMemberRefToDescHashTable = MemberRefToDescHashTable::Create(this, pImport->GetCountWithTokenKind(mdtMemberRef)+1, pamTracker); } } - -#if defined(FEATURE_COMINTEROP) && defined(FEATURE_PREJIT) - if (IsCompilationProcess() && m_pGuidToTypeHash == NULL) - { - // only allocate this during NGEN-ing - m_pGuidToTypeHash = GuidToMethodTableHashTable::Create(this, GUID_TO_TYPE_HASH_BUCKETS, pamTracker); - } -#endif // FEATURE_COMINTEROP } // this will be initialized a bit later. @@ -905,103 +896,6 @@ void GuidToMethodTableHashTable::FixupEntry(DataImage *pImage, GuidToMethodTable #endif // FEATURE_NATIVE_IMAGE_GENERATION && !DACCESS_COMPILE - -#ifdef FEATURE_PREJIT - -#ifndef DACCESS_COMPILE -BOOL Module::CanCacheWinRTTypeByGuid(MethodTable *pMT) -{ - CONTRACTL - { - THROWS; - GC_NOTRIGGER; - MODE_ANY; - PRECONDITION(IsCompilationProcess()); - } - CONTRACTL_END; - - // Don't cache WinRT types in collectible modules. - if (IsCollectible()) - { - return FALSE; - } - - // Don't cache mscorlib-internal declarations of WinRT types. - if (IsSystem() && pMT->IsProjectedFromWinRT()) - return FALSE; - - // Don't cache redirected WinRT types. - if (WinRTTypeNameConverter::IsRedirectedWinRTSourceType(pMT)) - return FALSE; - -#ifdef FEATURE_NATIVE_IMAGE_GENERATION - // Don't cache in a module that's not the NGen target, since the result - // won't be saved, and since the such a module might be read-only. - if (GetAppDomain()->ToCompilationDomain()->GetTargetModule() != this) - return FALSE; -#endif - - return TRUE; -} - -void Module::CacheWinRTTypeByGuid(PTR_MethodTable pMT, PTR_GuidInfo pgi /*= NULL*/) -{ - CONTRACTL - { - STANDARD_VM_CHECK; - PRECONDITION(CheckPointer(pMT)); - PRECONDITION(pMT->IsLegalNonArrayWinRTType()); - PRECONDITION(pgi != NULL || pMT->GetGuidInfo() != NULL); - PRECONDITION(IsCompilationProcess()); - } - CONTRACTL_END; - - if (pgi == NULL) - { - pgi = pMT->GetGuidInfo(); - } - - AllocMemTracker amt; - m_pGuidToTypeHash->InsertValue(&pgi->m_Guid, pMT, TRUE, &amt); - amt.SuppressRelease(); -} - -#endif // !DACCESS_COMPILE - -PTR_MethodTable Module::LookupTypeByGuid(const GUID & guid) -{ - WRAPPER_NO_CONTRACT; - // Triton ni images do not have this hash. - if (m_pGuidToTypeHash != NULL) - return m_pGuidToTypeHash->GetValue(&guid, NULL); - else - return NULL; -} - -void Module::GetCachedWinRTTypes(SArray * pTypes, SArray * pGuids) -{ - CONTRACTL - { - STANDARD_VM_CHECK; - SUPPORTS_DAC; - } - CONTRACTL_END; - - // Triton ni images do not have this hash. - if (m_pGuidToTypeHash != NULL) - { - GuidToMethodTableHashTable::Iterator it(m_pGuidToTypeHash); - GuidToMethodTableEntry *pEntry; - while (m_pGuidToTypeHash->FindNext(&it, &pEntry)) - { - pTypes->Append(pEntry->m_pMT); - pGuids->Append(*pEntry->m_Guid); - } - } -} - -#endif // FEATURE_PREJIT - #endif // FEATURE_COMINTEROP #ifndef DACCESS_COMPILE @@ -1614,11 +1508,6 @@ static bool IsLikelyDependencyOf(Module * pModule, Module * pOtherModule) // collections from these low level system assemblies (like LinkedList) should be module of AppType. It would be module of the generic // collection without this check. // - // Similar problem exists for Windows.Foundation.winmd. There is a cycle between Windows.Foundation.winmd and Windows.Storage.winmd. This cycle - // would cause prefererred zap module for instantiations of foundation types (like IAsyncOperation) to be Windows.Foundation.winmd. - // It is a bad choice. It should be Windows.Storage.winmd instead. We explicitly push Windows.Foundation to lower level by treating it as - // low level system assembly to avoid this problem. - // if (pModule->IsLowLevelSystemAssemblyByName()) { if (!pOtherModule->IsLowLevelSystemAssemblyByName()) @@ -3300,36 +3189,6 @@ void Module::StartUnload() } #endif // CROSSGEN_COMPILE -//--------------------------------------------------------------------------------------- -// -// Simple wrapper around calling IsAfContentType_WindowsRuntime() against the flags -// returned from the PEAssembly's GetFlagsNoTrigger() -// -// Return Value: -// nonzero iff we successfully determined pModule is a WinMD. FALSE if pModule is not -// a WinMD, or we fail trying to find out. -// -BOOL Module::IsWindowsRuntimeModule() -{ - CONTRACTL - { - NOTHROW; - GC_NOTRIGGER; - CAN_TAKE_LOCK; // Accesses metadata directly, which takes locks - MODE_ANY; - } - CONTRACTL_END; - - BOOL fRet = FALSE; - - DWORD dwFlags; - - if (FAILED(GetAssembly()->GetManifestFile()->GetFlagsNoTrigger(&dwFlags))) - return FALSE; - - return IsAfContentType_WindowsRuntime(dwFlags); -} - BOOL Module::IsInCurrentVersionBubble() { LIMITED_METHOD_CONTRACT; @@ -3346,11 +3205,6 @@ BOOL Module::IsInCurrentVersionBubble() if (IsReadyToRunCompilation()) return IsLargeVersionBubbleEnabled(); -#ifdef FEATURE_COMINTEROP - if (g_fNGenWinMDResilient) - return !GetAssembly()->IsWinMD(); -#endif - return TRUE; #else // FEATURE_NATIVE_IMAGE_GENERATION return TRUE; @@ -3428,8 +3282,7 @@ BOOL Module::IsInSameVersionBubble(Module *target) //--------------------------------------------------------------------------------------- // -// WinMD-aware helper to grab a readable public metadata interface. Any place that thinks -// it wants to use Module::GetRWImporter + QI now should use this wrapper instead. +// Wrapper for Module::GetRWImporter + QI when writing is not needed. // // Arguments: // * dwOpenFlags - Combo from CorOpenFlags. Better not contain ofWrite! @@ -3446,16 +3299,13 @@ HRESULT Module::GetReadablePublicMetaDataInterface(DWORD dwOpenFlags, REFIID rii { NOTHROW; GC_NOTRIGGER; - CAN_TAKE_LOCK; // IsWindowsRuntimeModule accesses metadata directly, which takes locks + CAN_TAKE_LOCK; MODE_ANY; } CONTRACTL_END; _ASSERTE((dwOpenFlags & ofWrite) == 0); - // Temporary place to store public, AddRef'd interface pointers - ReleaseHolder pIUnkPublic; - // Temporary place to store the IUnknown from which we'll do the final QI to get the // requested public interface. Any assignment to pIUnk assumes pIUnk does not need // to do a Release() (either the interface was internal and not AddRef'd, or was @@ -3471,51 +3321,6 @@ HRESULT Module::GetReadablePublicMetaDataInterface(DWORD dwOpenFlags, REFIID rii } EX_CATCH_HRESULT_NO_ERRORINFO(hr); - if (FAILED(hr) && IsWindowsRuntimeModule()) - { - // WinMD modules don't like creating RW importers. They also (currently) - // have no plumbing to get to their public metadata interfaces from the - // Module. So we actually have to start from scratch at the dispenser. - - // To start with, get a dispenser, and get the metadata memory blob we've - // already loaded. If either of these fail, just return the error HRESULT - // from the above GetRWImporter() call. - - // We'll get an addref'd IMetaDataDispenser, so use a holder to release it - ReleaseHolder pDispenser; - if (FAILED(InternalCreateMetaDataDispenser(IID_IMetaDataDispenser, &pDispenser))) - { - _ASSERTE(FAILED(hr)); - return hr; - } - - COUNT_T cbMetadata = 0; - PTR_CVOID pvMetadata = GetAssembly()->GetManifestFile()->GetLoadedMetadata(&cbMetadata); - if ((pvMetadata == NULL) || (cbMetadata == 0)) - { - _ASSERTE(FAILED(hr)); - return hr; - } - - // Now that the pieces are ready, we can use the riid specified by the - // profiler in this call to the dispenser to get the requested interface. If - // this fails, then this is the interesting HRESULT for the caller to see. - // - // We'll get an AddRef'd public interface, so use a holder to release it - hr = pDispenser->OpenScopeOnMemory( - pvMetadata, - cbMetadata, - (dwOpenFlags | ofReadOnly), // Force ofReadOnly on behalf of the profiler - riid, - &pIUnkPublic); - if (FAILED(hr)) - return hr; - - // Set pIUnk so we can do the final QI from it below as we do in the other - // cases. - pIUnk = pIUnkPublic; - } - // Get the requested interface if (SUCCEEDED(hr) && (ppvInterface != NULL)) { @@ -3718,9 +3523,6 @@ ISymUnmanagedReader *Module::GetISymUnmanagedReader(void) // Call Fusion to ensure that any PDB's are shadow copied before // trying to get a symbol reader. This has to be done once per // Assembly. - // for this to work with winmds we cannot simply call GetRWImporter() as winmds are RO - // and thus don't implement the RW interface. so we call this wrapper function which knows - // how to get a IMetaDataImport interface regardless of the underlying module type. ReleaseHolder pUnk = NULL; hr = GetReadablePublicMetaDataInterface(ofReadOnly, IID_IMetaDataImport, &pUnk); if (SUCCEEDED(hr)) @@ -4618,7 +4420,7 @@ Assembly * Module::GetAssemblyIfLoadedFromNativeAssemblyRefWithRefDefMismatch(md { // Find out if THIS reference is satisfied // Specify fDoNotUtilizeExtraChecks to prevent recursion - Assembly *pAssemblyCandidate = this->GetAssemblyIfLoaded(foundAssemblyDef, NULL, NULL, pImportFoundNativeImage, TRUE /*fDoNotUtilizeExtraChecks*/); + Assembly *pAssemblyCandidate = this->GetAssemblyIfLoaded(foundAssemblyDef, pImportFoundNativeImage, TRUE /*fDoNotUtilizeExtraChecks*/); // This extended check is designed only to find assemblies loaded via an AssemblySpecBindingCache based binder. Verify that's what we found. if(pAssemblyCandidate != NULL) @@ -4643,12 +4445,9 @@ Assembly * Module::GetAssemblyIfLoadedFromNativeAssemblyRefWithRefDefMismatch(md } #endif // !defined(DACCESS_COMPILE) && defined(FEATURE_PREJIT) -// Fills ppContainingWinRtAppDomain only if WinRT type name is passed and if the assembly is found (return value != NULL). Assembly * Module::GetAssemblyIfLoaded( mdAssemblyRef kAssemblyRef, - LPCSTR szWinRtNamespace, // = NULL - LPCSTR szWinRtClassName, // = NULL IMDInternalImport * pMDImportOverride, // = NULL BOOL fDoNotUtilizeExtraChecks, // = FALSE ICLRPrivBinder *pBindingContextForLoadedAssembly // = NULL @@ -4667,8 +4466,7 @@ Module::GetAssemblyIfLoaded( CONTRACT_END; Assembly * pAssembly = NULL; - BOOL fCanUseRidMap = ((pMDImportOverride == NULL) && - (szWinRtNamespace == NULL)); + BOOL fCanUseRidMap = pMDImportOverride == NULL; #ifdef _DEBUG fCanUseRidMap = fCanUseRidMap && (CLRConfig::GetConfigValue(CLRConfig::INTERNAL_GetAssemblyIfLoadedIgnoreRidMap) == 0); @@ -4681,7 +4479,6 @@ Module::GetAssemblyIfLoaded( // Don't do a lookup if an override IMDInternalImport is provided, since the lookup is for the // standard IMDInternalImport and might result in an incorrect result. - // WinRT references also do not update RID map, so don't try to look it up if (fCanUseRidMap) { pAssembly = LookupAssemblyRef(kAssemblyRef); @@ -4717,32 +4514,6 @@ Module::GetAssemblyIfLoaded( continue; } -#ifdef FEATURE_COMINTEROP - if (szWinRtNamespace != NULL) - { - _ASSERTE(szWinRtClassName != NULL); - - CLRPrivBinderWinRT * pWinRtBinder = pAppDomainExamine->GetWinRtBinder(); - if (pWinRtBinder != nullptr) - { - ENABLE_FORBID_GC_LOADER_USE_IN_THIS_SCOPE(); - pAssembly = pWinRtBinder->FindAssemblyForTypeIfLoaded( - dac_cast(pAppDomainExamine), - szWinRtNamespace, - szWinRtClassName); - } - - // Never store WinMD AssemblyRefs into the rid map. - if (pAssembly != NULL) - { - break; - } - - // Never attemt to search the assembly spec binding cache for this form of WinRT assembly reference. - continue; - } -#endif // FEATURE_COMINTEROP - #ifndef DACCESS_COMPILE { IMDInternalImport * pMDImport = (pMDImportOverride == NULL) ? (GetMDImport()) : (pMDImportOverride); @@ -4802,8 +4573,6 @@ Module::GetAssemblyIfLoaded( // This restricts the scenario to a somewhat restricted case. BOOL eligibleForAdditionalChecks = TRUE; - if (szWinRtNamespace != NULL) - eligibleForAdditionalChecks = FALSE; // WinRT binds do not support this scan AssemblySpec specSearchAssemblyRef; @@ -4821,10 +4590,6 @@ Module::GetAssemblyIfLoaded( // This should not ever happen, due to the above checks, but this logic // is intended to be defensive against unexpected behavior. } - else if (specSearchAssemblyRef.IsContentType_WindowsRuntime()) - { - eligibleForAdditionalChecks = FALSE; // WinRT binds do not support this scan - } } if (eligibleForAdditionalChecks) @@ -4967,14 +4732,7 @@ Module::GetAssemblyRefFlags( } // Module::GetAssemblyRefFlags #ifndef DACCESS_COMPILE - -// Arguments: -// szWinRtTypeNamespace ... Namespace of WinRT type. -// szWinRtTypeClassName ... Name of WinRT type, NULL for non-WinRT (classic) types. -DomainAssembly * Module::LoadAssembly( - mdAssemblyRef kAssemblyRef, - LPCUTF8 szWinRtTypeNamespace, - LPCUTF8 szWinRtTypeClassName) +DomainAssembly * Module::LoadAssembly(mdAssemblyRef kAssemblyRef) { CONTRACT(DomainAssembly *) { @@ -4984,7 +4742,6 @@ DomainAssembly * Module::LoadAssembly( if (FORBIDGC_LOADER_USE_ENABLED()) FORBID_FAULT; else { INJECT_FAULT(COMPlusThrowOM();); } MODE_ANY; POSTCONDITION(CheckPointer(RETVAL, NULL_NOT_OK)); - //POSTCONDITION((CheckPointer(GetAssemblyIfLoaded(kAssemblyRef, szWinRtTypeNamespace, szWinRtTypeClassName)), NULL_NOT_OK)); } CONTRACT_END; @@ -4998,22 +4755,16 @@ DomainAssembly * Module::LoadAssembly( Assembly * pAssembly = LookupAssemblyRef(kAssemblyRef); if (pAssembly != NULL) { - _ASSERTE(HasBindableIdentity(kAssemblyRef)); - pDomainAssembly = pAssembly->GetDomainAssembly(); ::GetAppDomain()->LoadDomainFile(pDomainAssembly, FILE_LOADED); RETURN pDomainAssembly; } - bool fHasBindableIdentity = HasBindableIdentity(kAssemblyRef); - { PEAssemblyHolder pFile = GetDomainAssembly()->GetFile()->LoadAssembly( kAssemblyRef, - NULL, - szWinRtTypeNamespace, - szWinRtTypeClassName); + NULL); AssemblySpec spec; spec.InitializeSpec(kAssemblyRef, GetMDImport(), GetDomainAssembly()); // Set the binding context in the AssemblySpec if one is available. This can happen if the LoadAssembly ended up @@ -5024,28 +4775,19 @@ DomainAssembly * Module::LoadAssembly( { spec.SetBindingContext(pBindingContext); } - if (szWinRtTypeClassName != NULL) - { - spec.SetWindowsRuntimeType(szWinRtTypeNamespace, szWinRtTypeClassName); - } pDomainAssembly = GetAppDomain()->LoadDomainAssembly(&spec, pFile, FILE_LOADED); } if (pDomainAssembly != NULL) { _ASSERTE( - !fHasBindableIdentity || // GetAssemblyIfLoaded will not find non-bindable assemblies pDomainAssembly->IsSystem() || // GetAssemblyIfLoaded will not find mscorlib (see AppDomain::FindCachedFile) !pDomainAssembly->IsLoaded() || // GetAssemblyIfLoaded will not find not-yet-loaded assemblies - GetAssemblyIfLoaded(kAssemblyRef, NULL, NULL, NULL, FALSE, pDomainAssembly->GetFile()->GetHostAssembly()) != NULL); // GetAssemblyIfLoaded should find all remaining cases + GetAssemblyIfLoaded(kAssemblyRef, NULL, FALSE, pDomainAssembly->GetFile()->GetHostAssembly()) != NULL); // GetAssemblyIfLoaded should find all remaining cases - // Note: We cannot cache WinRT AssemblyRef, because it is meaningless without the TypeRef context if (pDomainAssembly->GetCurrentAssembly() != NULL) { - if (fHasBindableIdentity) - { - StoreAssemblyRef(kAssemblyRef, pDomainAssembly->GetCurrentAssembly()); - } + StoreAssemblyRef(kAssemblyRef, pDomainAssembly->GetCurrentAssembly()); } } @@ -7428,85 +7170,6 @@ MethodDesc* Module::LoadIBCMethodHelper(DataImage *image, CORBBTPROF_BLOB_PARAM_ RETURN pMethod; } // Module::LoadIBCMethodHelper -#ifdef FEATURE_COMINTEROP -//--------------------------------------------------------------------------------------- -// -// This function is a workaround for missing IBC data in WinRT assemblies and -// not-yet-implemented sharing of IL_STUB(__Canon arg) IL stubs for all interfaces. -// -static void ExpandWindowsRuntimeType(TypeHandle t, DataImage *image) -{ - CONTRACTL - { - STANDARD_VM_CHECK; - PRECONDITION(!t.IsNull()); - } - CONTRACTL_END - - if (t.IsTypeDesc()) - return; - - // This array contains our poor man's IBC data - instantiations that are known to - // be used by other assemblies. - static const struct - { - LPCUTF8 m_szTypeName; - BinderClassID m_GenericBinderClassID; - } - rgForcedInstantiations[] = { - { "Windows.UI.Xaml.Data.IGroupInfo", CLASS__IENUMERABLEGENERIC }, - { "Windows.UI.Xaml.UIElement", CLASS__ILISTGENERIC }, - { "Windows.UI.Xaml.Visibility", CLASS__CLRIREFERENCEIMPL }, - { "Windows.UI.Xaml.VerticalAlignment", CLASS__CLRIREFERENCEIMPL }, - { "Windows.UI.Xaml.HorizontalAlignment", CLASS__CLRIREFERENCEIMPL }, - // The following instantiations are used by Microsoft.PlayerFramework - http://playerframework.codeplex.com/ - { "Windows.UI.Xaml.Media.AudioCategory", CLASS__CLRIREFERENCEIMPL }, - { "Windows.UI.Xaml.Media.AudioDeviceType", CLASS__CLRIREFERENCEIMPL }, - { "Windows.UI.Xaml.Media.MediaElementState", CLASS__CLRIREFERENCEIMPL }, - { "Windows.UI.Xaml.Media.Stereo3DVideoRenderMode", CLASS__CLRIREFERENCEIMPL }, - { "Windows.UI.Xaml.Media.Stereo3DVideoPackingMode", CLASS__CLRIREFERENCEIMPL }, - }; - - DefineFullyQualifiedNameForClass(); - LPCUTF8 szTypeName = GetFullyQualifiedNameForClass(t.AsMethodTable()); - - for (SIZE_T i = 0; i < COUNTOF(rgForcedInstantiations); i++) - { - if (strcmp(szTypeName, rgForcedInstantiations[i].m_szTypeName) == 0) - { - EX_TRY - { - TypeHandle thGenericType = TypeHandle(MscorlibBinder::GetClass(rgForcedInstantiations[i].m_GenericBinderClassID)); - - Instantiation inst(&t, 1); - thGenericType.Instantiate(inst); - } - EX_CATCH - { - image->GetPreloader()->Error(t.GetCl(), GET_EXCEPTION()); - } - EX_END_CATCH(SwallowAllExceptions) - } - } - - if (strcmp(szTypeName, "Windows.Foundation.Collections.IObservableVector`1") == 0) - { - EX_TRY - { - TypeHandle thArg = TypeHandle(g_pObjectClass); - - Instantiation inst(&thArg, 1); - t.Instantiate(inst); - } - EX_CATCH - { - image->GetPreloader()->Error(t.GetCl(), GET_EXCEPTION()); - } - EX_END_CATCH(SwallowAllExceptions) - } -} -#endif // FEATURE_COMINTEROP - //--------------------------------------------------------------------------------------- // void Module::ExpandAll(DataImage *image) @@ -7540,33 +7203,6 @@ void Module::ExpandAll(DataImage *image) while (pInternalImport->EnumNext(&hEnum, &tk)) { -#ifdef FEATURE_COMINTEROP - // Skip the non-managed WinRT types since they're only used by Javascript and C++ - // - // With WinRT files, we want to exclude certain types that cause us problems: - // * Attribute types defined in Windows.Foundation. The constructor's methodimpl flags - // specify it is an internal runtime function and gets set as an FCALL when we parse - // the type - // - if (IsAfContentType_WindowsRuntime(assemblyFlags)) - { - mdToken tkExtends; - pInternalImport->GetTypeDefProps(tk, NULL, &tkExtends); - - if (TypeFromToken(tkExtends) == mdtTypeRef) - { - LPCSTR szNameSpace = NULL; - LPCSTR szName = NULL; - pInternalImport->GetNameOfTypeRef(tkExtends, &szNameSpace, &szName); - - if (!strcmp(szNameSpace, "System") && !_stricmp((szName), "Attribute")) - { - continue; - } - } - } -#endif // FEATURE_COMINTEROP - TypeHandle t = LoadTypeDefOrRefHelper(image, this, tk); if (t.IsNull()) // Skip this type @@ -7639,13 +7275,6 @@ void Module::ExpandAll(DataImage *image) m_GenericTypeDefToCanonMethodTableMap.AddElement(this, RidFromToken(pCanonMT->GetCl()), pCanonMT); } } - -#ifdef FEATURE_COMINTEROP - if (IsAfContentType_WindowsRuntime(assemblyFlags)) - { - ExpandWindowsRuntimeType(t, image); - } -#endif // FEATURE_COMINTEROP } } @@ -7661,39 +7290,10 @@ void Module::ExpandAll(DataImage *image) { mdToken tkResolutionScope = mdTokenNil; pInternalImport->GetResolutionScopeOfTypeRef(tk, &tkResolutionScope); - -#ifdef FEATURE_COMINTEROP - // WinRT first party files are authored with TypeRefs pointing to TypeDefs in the same module. - // This causes us to load types we do not want to NGen such as custom attributes. We will not - // expand any module local TypeRefs for WinMDs to prevent this. - if(TypeFromToken(tkResolutionScope)==mdtModule && IsAfContentType_WindowsRuntime(assemblyFlags)) - continue; -#endif // FEATURE_COMINTEROP TypeHandle t = LoadTypeDefOrRefHelper(image, this, tk); if (t.IsNull()) // Skip this type continue; - -#ifdef FEATURE_COMINTEROP - if (!g_fNGenWinMDResilient && TypeFromToken(tkResolutionScope) == mdtAssemblyRef) - { - DWORD dwAssemblyRefFlags; - IfFailThrow(pInternalImport->GetAssemblyRefProps(tkResolutionScope, NULL, NULL, NULL, NULL, NULL, NULL, &dwAssemblyRefFlags)); - - if (IsAfContentType_WindowsRuntime(dwAssemblyRefFlags)) - { - Assembly *pAssembly = t.GetAssembly(); - PEAssembly *pPEAssembly = pAssembly->GetManifestFile(); - AssemblySpec refSpec; - refSpec.InitializeSpec(tkResolutionScope, pInternalImport); - LPCSTR psznamespace; - LPCSTR pszname; - pInternalImport->GetNameOfTypeRef(tk, &psznamespace, &pszname); - refSpec.SetWindowsRuntimeType(psznamespace, pszname); - GetAppDomain()->ToCompilationDomain()->AddDependency(&refSpec,pPEAssembly); - } - } -#endif // FEATURE_COMINTEROP } } @@ -7825,40 +7425,6 @@ void Module::ExpandAll(DataImage *image) mdTypeRef parent; IfFailThrow(pInternalImport->GetParentOfMemberRef(tk, &parent)); -#ifdef FEATURE_COMINTEROP - if (IsAfContentType_WindowsRuntime(assemblyFlags) && TypeFromToken(parent) == mdtTypeRef) - { - mdToken tkResolutionScope = mdTokenNil; - pInternalImport->GetResolutionScopeOfTypeRef(parent, &tkResolutionScope); - // WinRT first party files are authored with TypeRefs pointing to TypeDefs in the same module. - // This causes us to load types we do not want to NGen such as custom attributes. We will not - // expand any module local TypeRefs for WinMDs to prevent this. - if(TypeFromToken(tkResolutionScope)==mdtModule) - continue; - - LPCSTR szNameSpace = NULL; - LPCSTR szName = NULL; - if (SUCCEEDED(pInternalImport->GetNameOfTypeRef(parent, &szNameSpace, &szName))) - { - if (WinMDAdapter::ConvertWellKnownTypeNameFromClrToWinRT(&szNameSpace, &szName)) - { - // - // This is a MemberRef from a redirected WinRT type - // We should skip it as managed view will never see this MemberRef anyway - // Not skipping this will result MissingMethodExceptions as members in redirected - // types doesn't exactly match their redirected CLR type counter part - // - // Typically we only need to do this for interfaces as we should never see MemberRef - // from non-interfaces, but here to keep things simple I'm skipping every memberref that - // belongs to redirected WinRT type - // - continue; - } - } - - } -#endif // FEATURE_COMINTEROP - // If the MethodRef has a TypeSpec as a parent (i.e. refers to a method on an array type // or on a generic class), then it could in turn refer to type variables of // an unknown class/method. So we don't preresolve any MemberRefs which have TypeSpecs as @@ -8629,14 +8195,6 @@ void Module::Save(DataImage *image) m_pStubMethodHashTable->Save(image, profileData); } -#ifdef FEATURE_COMINTEROP - // the type saving operations above had the side effect of populating m_pGuidToTypeHash - if (m_pGuidToTypeHash != NULL) - { - m_pGuidToTypeHash->Save(image, profileData); - } -#endif // FEATURE_COMINTEROP - // Compute and save the property name set PrecomputeMatchingProperties(image); image->StoreStructure(m_propertyNameSet, @@ -9438,13 +8996,6 @@ void Module::Fixup(DataImage *image) m_pStubMethodHashTable->Fixup(image); } -#ifdef FEATURE_COMINTEROP - if (m_pGuidToTypeHash) { - image->FixupPointerField(this, offsetof(Module, m_pGuidToTypeHash)); - m_pGuidToTypeHash->Fixup(image); - } -#endif // FEATURE_COMINTEROP - image->EndRegion(CORINFO_REGION_COLD); #ifdef _DEBUG diff --git a/src/coreclr/src/vm/ceeload.h b/src/coreclr/src/vm/ceeload.h index 3619378..c977066 100644 --- a/src/coreclr/src/vm/ceeload.h +++ b/src/coreclr/src/vm/ceeload.h @@ -42,10 +42,6 @@ #include "dataimage.h" #endif // FEATURE_PREJIT -#ifdef FEATURE_COMINTEROP -#include "winrttypenameconverter.h" -#endif // FEATURE_COMINTEROP - #ifdef FEATURE_READYTORUN #include "readytoruninfo.h" #endif @@ -1634,23 +1630,6 @@ private: #ifdef FEATURE_PREJIT PTR_NGenLayoutInfo m_pNGenLayoutInfo; - -#if defined(FEATURE_COMINTEROP) - public: - - #ifndef DACCESS_COMPILE - BOOL CanCacheWinRTTypeByGuid(MethodTable *pMT); - void CacheWinRTTypeByGuid(PTR_MethodTable pMT, PTR_GuidInfo pgi = NULL); - #endif // !DACCESS_COMPILE - - PTR_MethodTable LookupTypeByGuid(const GUID & guid); - void GetCachedWinRTTypes(SArray * pTypes, SArray * pGuids); - - private: - PTR_GuidToMethodTableHashTable m_pGuidToTypeHash; // A map from GUID to Type, for the "WinRT-interesting" types - -#endif // defined(FEATURE_COMINTEROP) - // Module wide static fields information ModuleCtorInfo m_ModuleCtorInfo; @@ -1949,8 +1928,6 @@ protected: HRESULT GetReadablePublicMetaDataInterface(DWORD dwOpenFlags, REFIID riid, LPVOID * ppvInterface); #endif // !DACCESS_COMPILE - BOOL IsWindowsRuntimeModule(); - BOOL IsInCurrentVersionBubble(); #if defined(FEATURE_READYTORUN) && !defined(FEATURE_READYTORUN_COMPILER) @@ -2171,8 +2148,6 @@ protected: // Module/Assembly traversal Assembly * GetAssemblyIfLoaded( mdAssemblyRef kAssemblyRef, - LPCSTR szWinRtNamespace = NULL, - LPCSTR szWinRtClassName = NULL, IMDInternalImport * pMDImportOverride = NULL, BOOL fDoNotUtilizeExtraChecks = FALSE, ICLRPrivBinder *pBindingContextForLoadedAssembly = NULL @@ -2183,21 +2158,12 @@ private: Assembly *GetAssemblyIfLoadedFromNativeAssemblyRefWithRefDefMismatch(mdAssemblyRef kAssemblyRef, BOOL *pfDiscoveredAssemblyRefMatchesTargetDefExactly); public: - DomainAssembly * LoadAssembly( - mdAssemblyRef kAssemblyRef, - LPCUTF8 szWinRtTypeNamespace = NULL, - LPCUTF8 szWinRtTypeClassName = NULL); + DomainAssembly * LoadAssembly(mdAssemblyRef kAssemblyRef); Module *GetModuleIfLoaded(mdFile kFile, BOOL onlyLoadedInAppDomain, BOOL loadAllowed); DomainFile *LoadModule(AppDomain *pDomain, mdFile kFile, BOOL loadResources = TRUE, BOOL bindOnly = FALSE); PTR_Module LookupModule(mdToken kFile, BOOL loadResources = TRUE); //wrapper over GetModuleIfLoaded, takes modulerefs as well DWORD GetAssemblyRefFlags(mdAssemblyRef tkAssemblyRef); - bool HasBindableIdentity(mdAssemblyRef tkAssemblyRef) - { - WRAPPER_NO_CONTRACT; - return !IsAfContentType_WindowsRuntime(GetAssemblyRefFlags(tkAssemblyRef)); - } - // RID maps TypeHandle LookupTypeDef(mdTypeDef token, ClassLoadLevel *pLoadLevel = NULL) { diff --git a/src/coreclr/src/vm/class.cpp b/src/coreclr/src/vm/class.cpp index d9357e8..56466a9 100644 --- a/src/coreclr/src/vm/class.cpp +++ b/src/coreclr/src/vm/class.cpp @@ -1514,31 +1514,28 @@ TypeHandle MethodTable::SetupCoClassForInterface() const BYTE *pVal = NULL; ULONG cbVal = 0; - if (!IsProjectedFromWinRT()) // ignore classic COM interop CA on WinRT types + HRESULT hr = GetCustomAttribute(WellKnownAttribute::CoClass, (const void **)&pVal, &cbVal); + if (hr == S_OK) { - HRESULT hr = GetCustomAttribute(WellKnownAttribute::CoClass, (const void **)&pVal, &cbVal); - if (hr == S_OK) - { - CustomAttributeParser cap(pVal, cbVal); + CustomAttributeParser cap(pVal, cbVal); - IfFailThrow(cap.SkipProlog()); + IfFailThrow(cap.SkipProlog()); - // Retrieve the COM source interface class name. - ULONG cbName; - LPCUTF8 szName; - IfFailThrow(cap.GetNonNullString(&szName, &cbName)); + // Retrieve the COM source interface class name. + ULONG cbName; + LPCUTF8 szName; + IfFailThrow(cap.GetNonNullString(&szName, &cbName)); - // Copy the name to a temporary buffer and NULL terminate it. - StackSString ss(SString::Utf8, szName, cbName); + // Copy the name to a temporary buffer and NULL terminate it. + StackSString ss(SString::Utf8, szName, cbName); - // Try to load the class using its name as a fully qualified name. If that fails, - // then we try to load it in the assembly of the current class. - CoClassType = TypeName::GetTypeUsingCASearchRules(ss.GetUnicode(), GetAssembly()); + // Try to load the class using its name as a fully qualified name. If that fails, + // then we try to load it in the assembly of the current class. + CoClassType = TypeName::GetTypeUsingCASearchRules(ss.GetUnicode(), GetAssembly()); - // Cache the coclass type - g_IBCLogger.LogEEClassCOWTableAccess(this); - GetClass_NoLogging()->SetCoClassForInterface(CoClassType); - } + // Cache the coclass type + g_IBCLogger.LogEEClassCOWTableAccess(this); + GetClass_NoLogging()->SetCoClassForInterface(CoClassType); } return CoClassType; } @@ -1887,22 +1884,19 @@ CorIfaceAttr MethodTable::GetComInterfaceType() if (ItfType != (CorIfaceAttr)-1) return ItfType; - if (IsProjectedFromWinRT()) + // Retrieve the interface type from the metadata. + HRESULT hr = GetMDImport()->GetIfaceTypeOfTypeDef(GetCl(), (ULONG*)&ItfType); + IfFailThrow(hr); + + if (hr != S_OK) { - // WinRT interfaces are always IInspectable-based - ItfType = ifInspectable; + // if not found in metadata, use the default + ItfType = ifDual; } - else - { - // Retrieve the interface type from the metadata. - HRESULT hr = GetMDImport()->GetIfaceTypeOfTypeDef(GetCl(), (ULONG*)&ItfType); - IfFailThrow(hr); - if (hr != S_OK) - { - // if not found in metadata, use the default - ItfType = ifDual; - } + if (ItfType == ifInspectable) + { + COMPlusThrow(kPlatformNotSupportedException, IDS_EE_NO_IINSPECTABLE); } // Cache the interface type @@ -2249,7 +2243,7 @@ CorClassIfaceAttr MethodTable::GetComClassInterfaceType() if (HasGenericClassInstantiationInHierarchy()) return clsIfNone; - // If the class does not support IClassX because it derives from or implements WinRT types, + // If the class does not support IClassX, // then it is considered ClassInterfaceType.None unless explicitly overriden by the CA if (!ClassSupportsIClassX(this)) return clsIfNone; @@ -2620,41 +2614,20 @@ void EEClass::Save(DataImage *image, MethodTable *pMT) if (pMT->IsInterface()) { - // Make sure our guid is computed - -#ifdef FEATURE_COMINTEROP - // Generic WinRT types can have their GUID computed only if the instantiation is WinRT-legal - if (!pMT->IsProjectedFromWinRT() || - !pMT->SupportsGenericInterop(TypeHandle::Interop_NativeToManaged) || - pMT->IsLegalNonArrayWinRTType()) -#endif // FEATURE_COMINTEROP + GUID dummy; + if (SUCCEEDED(pMT->GetGuidNoThrow(&dummy, TRUE, FALSE))) { - GUID dummy; - if (SUCCEEDED(pMT->GetGuidNoThrow(&dummy, TRUE, FALSE))) - { - GuidInfo* pGuidInfo = pMT->GetGuidInfo(); - _ASSERTE(pGuidInfo != NULL); - - image->StoreStructure(pGuidInfo, sizeof(GuidInfo), - DataImage::ITEM_GUID_INFO); + GuidInfo* pGuidInfo = pMT->GetGuidInfo(); + _ASSERTE(pGuidInfo != NULL); -#ifdef FEATURE_COMINTEROP - if (pMT->IsLegalNonArrayWinRTType()) - { - Module *pModule = pMT->GetModule(); - if (pModule->CanCacheWinRTTypeByGuid(pMT)) - { - pModule->CacheWinRTTypeByGuid(pMT, pGuidInfo); - } - } -#endif // FEATURE_COMINTEROP - } - else - { - // make sure we don't store a GUID_NULL guid in the NGEN image - // instead we'll compute the GUID at runtime, and throw, if appropriate - m_pGuidInfo.SetValueMaybeNull(NULL); - } + image->StoreStructure(pGuidInfo, sizeof(GuidInfo), + DataImage::ITEM_GUID_INFO); + } + else + { + // make sure we don't store a GUID_NULL guid in the NGEN image + // instead we'll compute the GUID at runtime, and throw, if appropriate + m_pGuidInfo.SetValueMaybeNull(NULL); } } diff --git a/src/coreclr/src/vm/class.h b/src/coreclr/src/vm/class.h index 9158760..441f5bf 100644 --- a/src/coreclr/src/vm/class.h +++ b/src/coreclr/src/vm/class.h @@ -47,9 +47,6 @@ #include "typectxt.h" #include "iterator_util.h" -#ifdef FEATURE_COMINTEROP -#include "..\md\winmd\inc\adapter.h" -#endif #include "packedfields.inl" #include "array.h" #define IBCLOG(x) g_IBCLogger.##x @@ -354,9 +351,6 @@ class EEClassLayoutInfo mdTypeDef cl, // cl of the NStruct being loaded BYTE packingSize, // packing size (from @dll.struct) BYTE nlType, // nltype (from @dll.struct) -#ifdef FEATURE_COMINTEROP - BOOL isWinRT, // Is the type a WinRT type -#endif // FEATURE_COMINTEROP BOOL fExplicitOffsets, // explicit offsets? MethodTable *pParentMT, // the loaded superclass ULONG cTotalFields, // total number of fields (instance and static) @@ -538,12 +532,6 @@ typedef struct #define GetFullyQualifiedNameForClassW(pClass) \ pClass->_GetFullyQualifiedNameForClass(_ssclsname_w_).GetUnicode() -#define GetFullyQualifiedNameForClassW_WinRT(pClass) \ - pClass->_GetFullyQualifiedNameForClass(_ssclsname_w_).GetUnicode() - -#define GetFullyQualifiedNameForClass_WinRT(pClass) \ - pClass->_GetFullyQualifiedNameForClass(_ssclsname_).GetUTF8(_scratchbuffer_) - // Structure containing EEClass fields used by a minority of EEClass instances. This separation allows us to // save memory and improve the density of accessed fields in the EEClasses themselves. This class is reached // via the m_rpOptionalFields field EEClass (use the GetOptionalFields() accessor rather than the field @@ -581,12 +569,10 @@ class EEClassOptionalFields TypeHandle m_pCoClassForIntf; // @TODO: Coclass for an interface #ifdef FEATURE_COMINTEROP_UNMANAGED_ACTIVATION - // Points to activation information if the type is an activatable COM/WinRT class. + // Points to activation information if the type is an activatable COM class. ClassFactoryBase *m_pClassFactory; #endif // FEATURE_COMINTEROP_UNMANAGED_ACTIVATION - WinMDAdapter::RedirectedTypeIndex m_WinRTRedirectedTypeIndex; - #endif // FEATURE_COMINTEROP // @@ -1241,16 +1227,6 @@ public: LIMITED_METHOD_CONTRACT; m_VMFlags |= (DWORD) VMFLAG_SPARSE_FOR_COMINTEROP; } - inline void SetProjectedFromWinRT() - { - LIMITED_METHOD_CONTRACT; - m_VMFlags |= (DWORD) VMFLAG_PROJECTED_FROM_WINRT; - } - inline void SetExportedToWinRT() - { - LIMITED_METHOD_CONTRACT; - m_VMFlags |= (DWORD) VMFLAG_EXPORTED_TO_WINRT; - } inline void SetMarshalingType(UINT32 mType) { LIMITED_METHOD_CONTRACT; @@ -1329,16 +1305,6 @@ public: LIMITED_METHOD_CONTRACT; return m_VMFlags & VMFLAG_SPARSE_FOR_COMINTEROP; } - BOOL IsProjectedFromWinRT() - { - LIMITED_METHOD_DAC_CONTRACT; - return m_VMFlags & VMFLAG_PROJECTED_FROM_WINRT; - } - BOOL IsExportedToWinRT() - { - LIMITED_METHOD_CONTRACT; - return m_VMFlags & VMFLAG_EXPORTED_TO_WINRT; - } BOOL IsMarshalingTypeSet() { LIMITED_METHOD_CONTRACT; @@ -1537,21 +1503,6 @@ public: GetOptionalFields()->m_pCoClassForIntf = th; } - inline WinMDAdapter::RedirectedTypeIndex GetWinRTRedirectedTypeIndex() - { - LIMITED_METHOD_CONTRACT; - return HasOptionalFields() ? GetOptionalFields()->m_WinRTRedirectedTypeIndex - : WinMDAdapter::RedirectedTypeIndex_Invalid; - } - - inline void SetWinRTRedirectedTypeIndex(WinMDAdapter::RedirectedTypeIndex index) - { - LIMITED_METHOD_CONTRACT; - _ASSERTE(HasOptionalFields()); - _ASSERTE(index != WinMDAdapter::RedirectedTypeIndex_Invalid); - GetOptionalFields()->m_WinRTRedirectedTypeIndex = index; - } - OBJECTHANDLE GetOHDelegate() { LIMITED_METHOD_CONTRACT; @@ -1740,9 +1691,9 @@ public: // interfaces may have a coclass attribute VMFLAG_HASCOCLASSATTRIB = 0x01000000, VMFLAG_COMEVENTITFMASK = 0x02000000, // class is a special COM event interface - VMFLAG_PROJECTED_FROM_WINRT = 0x04000000, - VMFLAG_EXPORTED_TO_WINRT = 0x08000000, #endif // FEATURE_COMINTEROP + // unused = 0x04000000, + // unused = 0x08000000, // This one indicates that the fields of the valuetype are // not tightly packed and is used to check whether we can diff --git a/src/coreclr/src/vm/class.inl b/src/coreclr/src/vm/class.inl index ffd8da3..bddef93 100644 --- a/src/coreclr/src/vm/class.inl +++ b/src/coreclr/src/vm/class.inl @@ -28,7 +28,6 @@ inline void EEClassOptionalFields::Init() #ifdef FEATURE_COMINTEROP_UNMANAGED_ACTIVATION m_pClassFactory = NULL; #endif // FEATURE_COMINTEROP_UNMANAGED_ACTIVATION - m_WinRTRedirectedTypeIndex = WinMDAdapter::RedirectedTypeIndex_Invalid; #endif // FEATURE_COMINTEROP m_cbModuleDynamicID = MODULE_NON_DYNAMIC_STATICS; #if defined(UNIX_AMD64_ABI) diff --git a/src/coreclr/src/vm/classcompat.cpp b/src/coreclr/src/vm/classcompat.cpp index f74c224..7cac36e 100644 --- a/src/coreclr/src/vm/classcompat.cpp +++ b/src/coreclr/src/vm/classcompat.cpp @@ -310,7 +310,7 @@ InteropMethodTableData *MethodTableBuilder::BuildInteropVTable(AllocMemTracker * // Com Import classes are special if (IsComImport() && !IsEnum() && !IsInterface() && !IsValueClass() && !IsDelegate()) { - _ASSERTE(pParentMethodTable == g_pBaseCOMObject || pThisMT->IsWinRTObjectType()); + _ASSERTE(pParentMethodTable == g_pBaseCOMObject); _ASSERTE(!(HasLayout())); // if the current class is imported diff --git a/src/coreclr/src/vm/classlayoutinfo.cpp b/src/coreclr/src/vm/classlayoutinfo.cpp index aa7923f..35b74be 100644 --- a/src/coreclr/src/vm/classlayoutinfo.cpp +++ b/src/coreclr/src/vm/classlayoutinfo.cpp @@ -548,9 +548,6 @@ VOID EEClassLayoutInfo::CollectLayoutFieldMetadataThrowing( mdTypeDef cl, // cl of the NStruct being loaded BYTE packingSize, // packing size (from @dll.struct) BYTE nlType, // nltype (from @dll.struct) -#ifdef FEATURE_COMINTEROP - BOOL isWinRT, // Is the type a WinRT type -#endif // FEATURE_COMINTEROP BOOL fExplicitOffsets, // explicit offsets? MethodTable *pParentMT, // the loaded superclass ULONG cTotalFields, // total number of fields (instance and static) @@ -637,13 +634,8 @@ VOID EEClassLayoutInfo::CollectLayoutFieldMetadataThrowing( ULONG cInstanceFields = 0; ParseNativeTypeFlags nativeTypeFlags = ParseNativeTypeFlags::None; -#ifdef FEATURE_COMINTEROP - if (isWinRT) - nativeTypeFlags = ParseNativeTypeFlags::IsWinRT; - else // WinRT types have nlType == nltAnsi but should be treated as Unicode -#endif // FEATURE_COMINTEROP - if (nlType == nltAnsi) - nativeTypeFlags = ParseNativeTypeFlags::IsAnsi; + if (nlType == nltAnsi) + nativeTypeFlags = ParseNativeTypeFlags::IsAnsi; BOOL isBlittable; @@ -820,13 +812,8 @@ EEClassNativeLayoutInfo* EEClassNativeLayoutInfo::CollectNativeLayoutFieldMetada CorNativeLinkType charSet = pMT->GetCharSet(); ParseNativeTypeFlags nativeTypeFlags = ParseNativeTypeFlags::None; -#ifdef FEATURE_COMINTEROP - if (pMT->IsProjectedFromWinRT()) - nativeTypeFlags = ParseNativeTypeFlags::IsWinRT; - else // WinRT types have nlType == nltAnsi but should be treated as Unicode -#endif // FEATURE_COMINTEROP - if (charSet == nltAnsi) - nativeTypeFlags = ParseNativeTypeFlags::IsAnsi; + if (charSet == nltAnsi) + nativeTypeFlags = ParseNativeTypeFlags::IsAnsi; ApproxFieldDescIterator fieldDescs(pMT, ApproxFieldDescIterator::INSTANCE_FIELDS); diff --git a/src/coreclr/src/vm/classnames.h b/src/coreclr/src/vm/classnames.h index 8385bf4..9ae2e5c 100644 --- a/src/coreclr/src/vm/classnames.h +++ b/src/coreclr/src/vm/classnames.h @@ -30,13 +30,9 @@ #define g_SystemRuntimeAsmName "System.Runtime" #define g_DrawingAsmName "System.Drawing" #define g_ObjectModelAsmName "System.ObjectModel" -#define g_SystemRuntimeWindowsRuntimeAsmName "System.Runtime.WindowsRuntime" #define g_ColorClassName "System.Drawing.Color" #define g_ColorTranslatorClassName "System.Drawing.ColorTranslator" #define g_SystemUriClassName "System.Uri" -#define g_WinRTUriClassName "Windows.Foundation.Uri" -#define g_WinRTUriClassNameW W("Windows.Foundation.Uri") -#define g_WinRTIUriRCFactoryName "Windows.Foundation.IUriRuntimeClassFactory" #define g_INotifyCollectionChangedName "System.Collections.Specialized.INotifyCollectionChanged" #define g_NotifyCollectionChangedEventHandlerName "System.Collections.Specialized.NotifyCollectionChangedEventHandler" #define g_NotifyCollectionChangedEventArgsName "System.Collections.Specialized.NotifyCollectionChangedEventArgs" @@ -44,23 +40,8 @@ #define g_INotifyPropertyChangedName "System.ComponentModel.INotifyPropertyChanged" #define g_PropertyChangedEventHandlerName "System.ComponentModel.PropertyChangedEventHandler" #define g_PropertyChangedEventArgsName "System.ComponentModel.PropertyChangedEventArgs" -#define g_PropertyChangedEventArgsMarshalerName "System.Runtime.InteropServices.WindowsRuntime.PropertyChangedEventArgsMarshaler" -#define g_WinRTIIteratorClassName "Windows.Foundation.Collections.IIterator`1" -#define g_WinRTIIteratorClassNameW W("Windows.Foundation.Collections.IIterator`1") #define g_ICommandName "System.Windows.Input.ICommand" #define g_ComObjectName "__ComObject" -#define g_RuntimeClassName "RuntimeClass" -#define g_INotifyCollectionChanged_WinRTName "System.Runtime.InteropServices.WindowsRuntime.INotifyCollectionChanged_WinRT" -#define g_NotifyCollectionChangedToManagedAdapterName "System.Runtime.InteropServices.WindowsRuntime.NotifyCollectionChangedToManagedAdapter" -#define g_NotifyCollectionChangedToWinRTAdapterName "System.Runtime.InteropServices.WindowsRuntime.NotifyCollectionChangedToWinRTAdapter" -#define g_INotifyPropertyChanged_WinRTName "System.Runtime.InteropServices.WindowsRuntime.INotifyPropertyChanged_WinRT" -#define g_NotifyPropertyChangedToManagedAdapterName "System.Runtime.InteropServices.WindowsRuntime.NotifyPropertyChangedToManagedAdapter" -#define g_NotifyPropertyChangedToWinRTAdapterName "System.Runtime.InteropServices.WindowsRuntime.NotifyPropertyChangedToWinRTAdapter" -#define g_ICommand_WinRTName "System.Runtime.InteropServices.WindowsRuntime.ICommand_WinRT" -#define g_ICommandToManagedAdapterName "System.Runtime.InteropServices.WindowsRuntime.ICommandToManagedAdapter" -#define g_ICommandToWinRTAdapterName "System.Runtime.InteropServices.WindowsRuntime.ICommandToWinRTAdapter" -#define g_NotifyCollectionChangedEventHandler_WinRT "System.Runtime.InteropServices.WindowsRuntime.NotifyCollectionChangedEventHandler_WinRT" -#define g_PropertyChangedEventHandler_WinRT_Name "System.Runtime.InteropServices.WindowsRuntime.PropertyChangedEventHandler_WinRT" #endif // FEATURE_COMINTEROP @@ -78,16 +59,6 @@ #define g_Vector256ClassName "System.Runtime.Intrinsics.Vector256`1" #define g_Vector256Name "Vector256`1" -#ifdef FEATURE_COMINTEROP - -#define g_WindowsFoundationActivatableAttributeClassName "Windows.Foundation.Metadata.ActivatableAttribute" -#define g_WindowsFoundationComposableAttributeClassName "Windows.Foundation.Metadata.ComposableAttribute" -#define g_WindowsFoundationStaticAttributeClassName "Windows.Foundation.Metadata.StaticAttribute" -#define g_WindowsFoundationDefaultClassName "Windows.Foundation.Metadata.DefaultAttribute" -#define g_WindowsFoundationMarshalingBehaviorAttributeClassName "Windows.Foundation.Metadata.MarshalingBehaviorAttribute" -#define g_WindowsFoundationGCPressureAttributeClassName "Windows.Foundation.Metadata.GCPressureAttribute" -#endif // FEATURE_COMINTEROP - #define g_EnumeratorToEnumClassName "System.Runtime.InteropServices.CustomMarshalers.EnumeratorToEnumVariantMarshaler" #define g_ExceptionClassName "System.Exception" #define g_ExecutionEngineExceptionClassName "System.ExecutionEngineException" diff --git a/src/coreclr/src/vm/clrex.cpp b/src/coreclr/src/vm/clrex.cpp index 29db692..4f1c71d 100644 --- a/src/coreclr/src/vm/clrex.cpp +++ b/src/coreclr/src/vm/clrex.cpp @@ -16,7 +16,6 @@ #include "typestring.h" #include "sigformat.h" #include "eeconfig.h" -#include "frameworkexceptionloader.h" #ifdef FEATURE_EH_FUNCLETS #include "exceptionhandling.h" @@ -978,38 +977,6 @@ void CLRException::HandlerState::SucceedCatch() // Array that is used to retrieve the right exception for a given HRESULT. //------------------------------------------------------------------------ -#ifdef FEATURE_COMINTEROP - -struct WinRtHR_to_ExceptionKind_Map -{ - RuntimeExceptionKind reKind; - int cHRs; - const HRESULT *aHRs; -}; - -enum WinRtOnly_ExceptionKind { -#define DEFINE_EXCEPTION_HR_WINRT_ONLY(ns, reKind, ...) kWinRtEx##reKind, -#define DEFINE_EXCEPTION(ns, reKind, bHRformessage, ...) -#define DEFINE_EXCEPTION_IN_OTHER_FX_ASSEMBLY(ns, reKind, assemblySimpleName, bHRformessage, ...) -#include "rexcep.h" -kWinRtExLastException -}; - -#define DEFINE_EXCEPTION_HR_WINRT_ONLY(ns, reKind, ...) static const HRESULT s_##reKind##WinRtOnlyHRs[] = { __VA_ARGS__ }; -#define DEFINE_EXCEPTION(ns, reKind, bHRformessage, ...) -#define DEFINE_EXCEPTION_IN_OTHER_FX_ASSEMBLY(ns, reKind, assemblySimpleName, bHRformessage, ...) -#include "rexcep.h" - -static const -WinRtHR_to_ExceptionKind_Map gWinRtHR_to_ExceptionKind_Maps[] = { -#define DEFINE_EXCEPTION_HR_WINRT_ONLY(ns, reKind, ...) { k##reKind, sizeof(s_##reKind##WinRtOnlyHRs) / sizeof(HRESULT), s_##reKind##WinRtOnlyHRs }, -#define DEFINE_EXCEPTION(ns, reKind, bHRformessage, ...) -#define DEFINE_EXCEPTION_IN_OTHER_FX_ASSEMBLY(ns, reKind, assemblySimpleName, bHRformessage, ...) -#include "rexcep.h" -}; - -#endif // FEATURE_COMINTEROP - struct ExceptionHRInfo { int cHRs; @@ -1017,15 +984,11 @@ struct ExceptionHRInfo }; #define DEFINE_EXCEPTION(ns, reKind, bHRformessage, ...) static const HRESULT s_##reKind##HRs[] = { __VA_ARGS__ }; -#define DEFINE_EXCEPTION_HR_WINRT_ONLY(ns, reKind, ...) -#define DEFINE_EXCEPTION_IN_OTHER_FX_ASSEMBLY(ns, reKind, assemblySimpleName, bHRformessage, ...) DEFINE_EXCEPTION(ns, reKind, bHRformessage, __VA_ARGS__) #include "rexcep.h" static const ExceptionHRInfo gExceptionHRInfos[] = { #define DEFINE_EXCEPTION(ns, reKind, bHRformessage, ...) {sizeof(s_##reKind##HRs) / sizeof(HRESULT), s_##reKind##HRs}, -#define DEFINE_EXCEPTION_HR_WINRT_ONLY(ns, reKind, ...) -#define DEFINE_EXCEPTION_IN_OTHER_FX_ASSEMBLY(ns, reKind, assemblySimpleName, bHRformessage, ...) DEFINE_EXCEPTION(ns, reKind, bHRformessage, __VA_ARGS__) #include "rexcep.h" }; @@ -1034,8 +997,6 @@ static const bool gShouldDisplayHR[] = { #define DEFINE_EXCEPTION(ns, reKind, bHRformessage, ...) bHRformessage, -#define DEFINE_EXCEPTION_HR_WINRT_ONLY(ns, reKind, ...) -#define DEFINE_EXCEPTION_IN_OTHER_FX_ASSEMBLY(ns, reKind, assemblySimpleName, bHRformessage, ...) DEFINE_EXCEPTION(ns, reKind, bHRformessage, __VA_ARGS__) #include "rexcep.h" }; @@ -1111,18 +1072,8 @@ void EEException::GetMessage(SString &result) return; // Otherwise, report the class's generic message - LPCUTF8 pszExceptionName = NULL; - if (m_kind <= kLastExceptionInMscorlib) - { - pszExceptionName = MscorlibBinder::GetExceptionName(m_kind); - result.SetUTF8(pszExceptionName); - } -#ifndef CROSSGEN_COMPILE - else - { - FrameworkExceptionLoader::GetExceptionName(m_kind, result); - } -#endif // CROSSGEN_COMPILE + LPCUTF8 pszExceptionName = MscorlibBinder::GetExceptionName(m_kind); + result.SetUTF8(pszExceptionName); } OBJECTREF EEException::CreateThrowable() @@ -1142,13 +1093,7 @@ OBJECTREF EEException::CreateThrowable() _ASSERTE(g_pPreallocatedOutOfMemoryException != NULL); static int allocCount = 0; - MethodTable *pMT = NULL; - if (m_kind <= kLastExceptionInMscorlib) - pMT = MscorlibBinder::GetException(m_kind); - else - { - pMT = FrameworkExceptionLoader::GetException(m_kind); - } + MethodTable *pMT = MscorlibBinder::GetException(m_kind); ThreadPreventAsyncHolder preventAsyncHolder(m_kind == kThreadAbortException); @@ -1185,29 +1130,9 @@ OBJECTREF EEException::CreateThrowable() #endif } -RuntimeExceptionKind EEException::GetKindFromHR(HRESULT hr, bool fIsWinRtMode /*= false*/) +RuntimeExceptionKind EEException::GetKindFromHR(HRESULT hr) { LIMITED_METHOD_CONTRACT; - - #ifdef FEATURE_COMINTEROP - // If we are in WinRT mode, try to get a WinRT specific mapping first: - if (fIsWinRtMode) - { - for (int i = 0; i < kWinRtExLastException; i++) - { - for (int j = 0; j < gWinRtHR_to_ExceptionKind_Maps[i].cHRs; j++) - { - if (gWinRtHR_to_ExceptionKind_Maps[i].aHRs[j] == hr) - { - return gWinRtHR_to_ExceptionKind_Maps[i].reKind; - } - } - } - } - #endif // FEATURE_COMINTEROP - - // Is not in WinRT mode OR did not find a WinRT specific mapping. Check normal mappings: - for (int i = 0; i < kLastException; i++) { for (int j = 0; j < gExceptionHRInfos[i].cHRs; j++) @@ -1217,7 +1142,7 @@ RuntimeExceptionKind EEException::GetKindFromHR(HRESULT hr, bool fIsWinRtMode /* } } - return (fIsWinRtMode ? kException : kCOMException); + return kCOMException; } // RuntimeExceptionKind EEException::GetKindFromHR() @@ -1793,8 +1718,7 @@ RuntimeExceptionKind EEFileLoadException::GetFileLoadKind(HRESULT hr) (hr == HRESULT_FROM_WIN32(ERROR_FILE_CORRUPT)) || (hr == (HRESULT) IDS_CLASSLOAD_32BITCLRLOADING64BITASSEMBLY) || (hr == COR_E_LOADING_REFERENCE_ASSEMBLY) || - (hr == META_E_BAD_SIGNATURE) || - (hr == COR_E_LOADING_WINMD_REFERENCE_ASSEMBLY)) + (hr == META_E_BAD_SIGNATURE)) return kBadImageFormatException; else { @@ -1899,12 +1823,6 @@ void DECLSPEC_NORETURN EEFileLoadException::Throw(AssemblySpec *pSpec, HRESULT COMPlusThrow(kThreadAbortException); if (hr == E_OUTOFMEMORY) COMPlusThrowOM(); -#ifdef FEATURE_COMINTEROP - if ((hr == RO_E_METADATA_NAME_NOT_FOUND) || (hr == CLR_E_BIND_TYPE_NOT_FOUND)) - { // These error codes behave like FileNotFound, but are exposed as TypeLoadException - EX_THROW_WITH_INNER(EETypeLoadException, (pSpec->GetWinRtTypeNamespace(), pSpec->GetWinRtTypeClassName(), nullptr, nullptr, IDS_EE_WINRT_LOADFAILURE), pInnerException); - } -#endif //FEATURE_COMINTEROP StackSString name; pSpec->GetFileOrDisplayName(0, name); @@ -2050,14 +1968,6 @@ EECOMException::EECOMException(EXCEPINFO *pExcepInfo) m_ED.dwHelpContext = pExcepInfo->dwHelpContext; m_ED.guid = GUID_NULL; -#ifdef FEATURE_COMINTEROP - m_ED.bstrReference = NULL; - m_ED.bstrRestrictedError = NULL; - m_ED.bstrCapabilitySid = NULL; - m_ED.pRestrictedErrorInfo = NULL; - m_ED.bHasLanguageRestrictedErrorInfo = FALSE; -#endif - // Zero the EXCEPINFO. memset(pExcepInfo, NULL, sizeof(EXCEPINFO)); } @@ -2075,12 +1985,9 @@ EECOMException::EECOMException(ExceptionData *pData) EECOMException::EECOMException( HRESULT hr, - IErrorInfo *pErrInfo, - bool fUseCOMException, // use System.Runtime.InteropServices.COMException as the default exception type (means as much as !IsWinRT) - IRestrictedErrorInfo* pRestrictedErrInfo, - BOOL bHasLanguageRestrictedErrInfo + IErrorInfo *pErrInfo COMMA_INDEBUG(BOOL bCheckInProcCCWTearOff)) - : EEException(GetKindFromHR(hr, !fUseCOMException)) + : EEException(GetKindFromHR(hr)) { WRAPPER_NO_CONTRACT; @@ -2088,7 +1995,6 @@ EECOMException::EECOMException( // Must use another path for managed IErrorInfos... // note that this doesn't cover out-of-proc managed IErrorInfos. _ASSERTE(!bCheckInProcCCWTearOff || !IsInProcCCWTearOff(pErrInfo)); - _ASSERTE(pRestrictedErrInfo == NULL || !bCheckInProcCCWTearOff || !IsInProcCCWTearOff(pRestrictedErrInfo)); #endif // FEATURE_COMINTEROP m_ED.hr = hr; @@ -2098,15 +2004,7 @@ EECOMException::EECOMException( m_ED.dwHelpContext = NULL; m_ED.guid = GUID_NULL; -#ifdef FEATURE_COMINTEROP - m_ED.bstrReference = NULL; - m_ED.bstrRestrictedError = NULL; - m_ED.bstrCapabilitySid = NULL; - m_ED.pRestrictedErrorInfo = NULL; - m_ED.bHasLanguageRestrictedErrorInfo = bHasLanguageRestrictedErrInfo; -#endif - - FillExceptionData(&m_ED, pErrInfo, pRestrictedErrInfo); + FillExceptionData(&m_ED, pErrInfo); } BOOL EECOMException::GetThrowableMessage(SString &result) @@ -2119,42 +2017,10 @@ BOOL EECOMException::GetThrowableMessage(SString &result) } CONTRACTL_END; -#ifdef FEATURE_COMINTEROP - if (m_ED.bstrDescription != NULL || m_ED.bstrRestrictedError != NULL) - { - // For cross language WinRT exceptions, general information will be available in the bstrDescription, - // which is populated from IErrorInfo::GetDescription and more specific information will be available - // in the bstrRestrictedError which comes from the IRestrictedErrorInfo. If both are available, we - // need to concatinate them to produce the final exception message. - - result.Clear(); - - // If we have a restricted description, start our message with that - if (m_ED.bstrDescription != NULL) - { - SString generalInformation(m_ED.bstrDescription, SysStringLen(m_ED.bstrDescription)); - result.Append(generalInformation); - - // If we're also going to have a specific error message, append a newline to separate the two - if (m_ED.bstrRestrictedError != NULL) - { - result.Append(W("\r\n")); - } - } - - // If we have additional error information, attach it to the end of the string - if (m_ED.bstrRestrictedError != NULL) - { - SString restrictedDescription(m_ED.bstrRestrictedError, SysStringLen(m_ED.bstrRestrictedError)); - result.Append(restrictedDescription); - } - } -#else // !FEATURE_COMINTEROP if (m_ED.bstrDescription != NULL) { result.Set(m_ED.bstrDescription, SysStringLen(m_ED.bstrDescription)); } -#endif // FEATURE_COMINTEROP else { GenerateTopLevelHRExceptionMessage(GetHR(), result); @@ -2227,80 +2093,6 @@ OBJECTREF EECOMException::CreateThrowable() } ((EXCEPTIONREF)throwable)->SetSource(sourceStr); -#ifdef FEATURE_COMINTEROP - // - // Support for WinRT interface IRestrictedErrorInfo - // - if (m_ED.pRestrictedErrorInfo) - { - - struct _gc { - STRINGREF RestrictedErrorRef; - STRINGREF ReferenceRef; - STRINGREF RestrictedCapabilitySidRef; - OBJECTREF RestrictedErrorInfoObjRef; - } gc; - ZeroMemory(&gc, sizeof(gc)); - - GCPROTECT_BEGIN(gc); - - EX_TRY - { - gc.RestrictedErrorRef = StringObject::NewString( - m_ED.bstrRestrictedError, - SysStringLen(m_ED.bstrRestrictedError) - ); - gc.ReferenceRef = StringObject::NewString( - m_ED.bstrReference, - SysStringLen(m_ED.bstrReference) - ); - - gc.RestrictedCapabilitySidRef = StringObject::NewString( - m_ED.bstrCapabilitySid, - SysStringLen(m_ED.bstrCapabilitySid) - ); - - // Convert IRestrictedErrorInfo into a managed object - don't care whether it is a RCW/CCW - GetObjectRefFromComIP( - &gc.RestrictedErrorInfoObjRef, - m_ED.pRestrictedErrorInfo, // IUnknown * - NULL, // ClassMT - NULL, // ItfMT - ObjFromComIP::CLASS_IS_HINT | ObjFromComIP::IGNORE_WINRT_AND_SKIP_UNBOXING - ); - - // - // Call Exception.AddExceptionDataForRestrictedErrorInfo and put error information - // from IRestrictedErrorInfo on Exception.Data - // - MethodDescCallSite addExceptionDataForRestrictedErrorInfo( - METHOD__EXCEPTION__ADD_EXCEPTION_DATA_FOR_RESTRICTED_ERROR_INFO, - &throwable - ); - - ARG_SLOT Args[] = - { - ObjToArgSlot(throwable), - ObjToArgSlot(gc.RestrictedErrorRef), - ObjToArgSlot(gc.ReferenceRef), - ObjToArgSlot(gc.RestrictedCapabilitySidRef), - ObjToArgSlot(gc.RestrictedErrorInfoObjRef), - BoolToArgSlot(m_ED.bHasLanguageRestrictedErrorInfo) - }; - - addExceptionDataForRestrictedErrorInfo.Call(Args); - - } - EX_CATCH - { - // IDictionary.Add may throw. Ignore all non terminal exceptions - } - EX_END_CATCH(RethrowTerminalExceptions) - - GCPROTECT_END(); - } -#endif // FEATURE_COMINTEROP - GCPROTECT_END(); @@ -2594,8 +2386,6 @@ ArrayReference GetHRESULTsForExceptionKind(RuntimeExceptionKind k case k##reKind: \ return ArrayReference(s_##reKind##HRs); \ break; - #define DEFINE_EXCEPTION_HR_WINRT_ONLY(ns, reKind, ...) - #define DEFINE_EXCEPTION_IN_OTHER_FX_ASSEMBLY(ns, reKind, assemblySimpleName, bHRformessage, ...) DEFINE_EXCEPTION(ns, reKind, bHRformessage, __VA_ARGS__) #include "rexcep.h" default: diff --git a/src/coreclr/src/vm/clrex.h b/src/coreclr/src/vm/clrex.h index 3a570a5..f92bbc8 100644 --- a/src/coreclr/src/vm/clrex.h +++ b/src/coreclr/src/vm/clrex.h @@ -247,7 +247,7 @@ class EEException : public CLRException // // each reKind is associated with one or more hresults. // every hresult is associated with exactly one reKind (with kCOMException being the catch-all.) - static RuntimeExceptionKind GetKindFromHR(HRESULT hr, bool fIsWinRtMode = false); + static RuntimeExceptionKind GetKindFromHR(HRESULT hr); protected: static HRESULT GetHRFromKind(RuntimeExceptionKind reKind); @@ -292,8 +292,6 @@ class EEMessageException : public EEException EEMessageException(HRESULT hr); - EEMessageException(HRESULT hr, bool fUseCOMException); - EEMessageException(HRESULT hr, UINT resID, LPCWSTR szArg1 = NULL, LPCWSTR szArg2 = NULL, LPCWSTR szArg3 = NULL, LPCWSTR szArg4 = NULL, LPCWSTR szArg5 = NULL, LPCWSTR szArg6 = NULL); @@ -404,14 +402,6 @@ struct ExceptionData BSTR bstrHelpFile; DWORD dwHelpContext; GUID guid; -#ifdef FEATURE_COMINTEROP - BSTR bstrRestrictedError; // Returned from IRestrictedErrorInfo::GetErrorDetails - BSTR bstrReference; // Returned from IRestrictedErrorInfo::GetReference - BSTR bstrCapabilitySid; // Returned from IRestrictedErrorInfo::GetErrorDetails - IUnknown *pRestrictedErrorInfo; // AddRef-ed RestrictedErrorInfo pointer - // We need to keep this alive as long as user need the reference - BOOL bHasLanguageRestrictedErrorInfo; -#endif // FEATURE_COMINTEROP }; class EECOMException : public EEException @@ -427,10 +417,7 @@ class EECOMException : public EEException EECOMException(ExceptionData *pED); EECOMException( HRESULT hr, - IErrorInfo *pErrInfo, - bool fUseCOMException, - IRestrictedErrorInfo *pRestrictedErrInfo, - BOOL bHasLanguageRestrictedErrorInfo + IErrorInfo *pErrInfo COMMA_INDEBUG(BOOL bCheckInProcCCWTearOff = TRUE)); ~EECOMException(); @@ -986,16 +973,6 @@ inline EEMessageException::EEMessageException(HRESULT hr) m_arg1.Printf("%.8x", hr); } -inline EEMessageException::EEMessageException(HRESULT hr, bool fUseCOMException) - : EEException(GetKindFromHR(hr, !fUseCOMException)), - m_hr(hr), - m_resID(0) -{ - WRAPPER_NO_CONTRACT; - - m_arg1.Printf("%.8x", hr); -} - //----------------------------------------------------------------------------- // Constructor with lots of defaults (to 0 / null) // kind -- "clr kind" of the exception diff --git a/src/coreclr/src/vm/clrprivbinderutil.cpp b/src/coreclr/src/vm/clrprivbinderutil.cpp index a62d4a0..0f1647c 100644 --- a/src/coreclr/src/vm/clrprivbinderutil.cpp +++ b/src/coreclr/src/vm/clrprivbinderutil.cpp @@ -66,30 +66,4 @@ namespace CLRPrivBinderUtil return hr; } - - //===================================================================================================================== - // Destroys list of strings (code:WStringList). - void - WStringList_Delete( - WStringList * pList) - { - LIMITED_METHOD_CONTRACT; - - if (pList != nullptr) - { - for (WStringListElem * pElem = pList->RemoveHead(); pElem != nullptr; pElem = pList->RemoveHead()) - { - // Delete the string - delete [] pElem->GetValue(); - delete pElem; - } - - delete pList; - } - } - - -//////////////////////////////////////////////////////////////////////////////////////////////////// -///// ----------------------------- Direct calls to VM ------------------------------------------- -//////////////////////////////////////////////////////////////////////////////////////////////////// } // namespace CLRPrivBinderUtil diff --git a/src/coreclr/src/vm/clrprivbinderwinrt.cpp b/src/coreclr/src/vm/clrprivbinderwinrt.cpp deleted file mode 100644 index fb53079..0000000 --- a/src/coreclr/src/vm/clrprivbinderwinrt.cpp +++ /dev/null @@ -1,1113 +0,0 @@ -// 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. -// - - -// -// Contains the types that implement code:ICLRPrivBinder and code:ICLRPrivAssembly for WinRT binding. -// -//============================================================================================= - -#include "common.h" // precompiled header - -#include "clrprivbinderwinrt.h" -#include "clrprivbinderutil.h" - -#ifndef DACCESS_COMPILE - -//===================================================================================================================== -#include "sstring.h" -#ifdef FEATURE_APPX -#include "appxutil.h" -#endif -#include -#include "delayloadhelpers.h" -#include "../binder/inc/applicationcontext.hpp" -#include "../binder/inc/assemblybinder.hpp" -#include "../binder/inc/assembly.hpp" -#include "../binder/inc/utils.hpp" -#include "../binder/inc/fusionassemblyname.hpp" - -#ifdef CROSSGEN_COMPILE -#include "crossgenroresolvenamespace.h" -#include "../binder/inc/fusionassemblyname.hpp" -#endif - - -using namespace CLRPrivBinderUtil; - - -//===================================================================================================================== -#define WINDOWS_NAMESPACE W("Windows") -#define WINDOWS_NAMESPACE_PREFIX WINDOWS_NAMESPACE W(".") - -#define WINDOWS_NAMESPACEA "Windows" -#define WINDOWS_NAMESPACE_PREFIXA WINDOWS_NAMESPACEA "." - -//===================================================================================================================== -static BOOL -IsWindowsNamespace(const WCHAR * wszNamespace) -{ - LIMITED_METHOD_CONTRACT; - - if (wcsncmp(wszNamespace, WINDOWS_NAMESPACE_PREFIX, (_countof(WINDOWS_NAMESPACE_PREFIX) - 1)) == 0) - { - return TRUE; - } - else if (wcscmp(wszNamespace, WINDOWS_NAMESPACE) == 0) - { - return TRUE; - } - - return FALSE; -} - - -//===================================================================================================================== -BOOL -IsWindowsNamespace(const char * wszNamespace) -{ - LIMITED_METHOD_CONTRACT; - - if (strncmp(wszNamespace, WINDOWS_NAMESPACE_PREFIXA, (_countof(WINDOWS_NAMESPACE_PREFIXA) - 1)) == 0) - { - return TRUE; - } - else if (strcmp(wszNamespace, WINDOWS_NAMESPACEA) == 0) - { - return TRUE; - } - - return FALSE; -} - - -//===================================================================================================================== -DELAY_LOADED_FUNCTION(WinTypes, RoResolveNamespace); - -//===================================================================================================================== -HRESULT RoResolveNamespace( - _In_opt_ const HSTRING name, - _In_opt_ const HSTRING windowsMetaDataDir, - _In_ const DWORD packageGraphDirsCount, - _In_reads_opt_(packageGraphDirsCount) const HSTRING *packageGraphDirs, - _Out_opt_ DWORD *metaDataFilePathsCount, - _Outptr_opt_result_buffer_(*metaDataFilePathsCount) HSTRING **metaDataFilePaths, - _Out_opt_ DWORD *subNamespacesCount, - _Outptr_opt_result_buffer_(*subNamespacesCount) HSTRING **subNamespaces) -{ - LIMITED_METHOD_CONTRACT; - HRESULT hr = S_OK; - - decltype(RoResolveNamespace) * pFunc = nullptr; - IfFailRet(DelayLoad::WinTypes::RoResolveNamespace.GetValue(&pFunc)); - - return (*pFunc)( - name, windowsMetaDataDir, packageGraphDirsCount, packageGraphDirs, metaDataFilePathsCount, - metaDataFilePaths, subNamespacesCount, subNamespaces); -} - -//===================================================================================================================== -CLRPrivBinderWinRT * CLRPrivBinderWinRT::s_pSingleton = nullptr; - -//===================================================================================================================== -CLRPrivBinderWinRT::CLRPrivBinderWinRT( - ICLRPrivBinder * pParentBinder, - CLRPrivTypeCacheWinRT * pWinRtTypeCache, - LPCWSTR * rgwzAltPath, - UINT cAltPaths, - NamespaceResolutionKind fNamespaceResolutionKind) - : m_pTypeCache(clr::SafeAddRef(pWinRtTypeCache)) - , m_pParentBinder(pParentBinder) // Do not addref, lifetime directly tied to parent. - , m_fNamespaceResolutionKind(fNamespaceResolutionKind) - , m_pApplicationContext(nullptr) - , m_appLocalWinMDPath(nullptr) -{ - STANDARD_VM_CONTRACT; - PRECONDITION(CheckPointer(pWinRtTypeCache)); - -#ifndef CROSSGEN_COMPILE - // - To prevent deadlock with GC thread, we cannot trigger GC while holding the lock - // - To prevent deadlock with profiler thread, we cannot allow thread suspension - m_MapsLock.Init( - CrstCLRPrivBinderMaps, - (CrstFlags)(CRST_REENTRANCY // Reentracy is needed for code:CLRPrivAssemblyWinRT::Release - | CRST_GC_NOTRIGGER_WHEN_TAKEN - | CRST_DEBUGGER_THREAD - INDEBUG(| CRST_DEBUG_ONLY_CHECK_FORBID_SUSPEND_THREAD))); - m_MapsAddLock.Init(CrstCLRPrivBinderMapsAdd); - - - // Copy altpaths - if (cAltPaths > 0) - { - m_rgAltPaths.Allocate(cAltPaths); - - for (UINT iAltPath = 0; iAltPath < cAltPaths; iAltPath++) - { - IfFailThrow(WindowsCreateString( - rgwzAltPath[iAltPath], - (UINT32)wcslen(rgwzAltPath[iAltPath]), - m_rgAltPaths.GetRawArray() + iAltPath)); - } - } -#endif //CROSSGEN_COMPILE - -} - -//===================================================================================================================== -CLRPrivBinderWinRT::~CLRPrivBinderWinRT() -{ - WRAPPER_NO_CONTRACT; - - if (m_pTypeCache != nullptr) - { - m_pTypeCache->Release(); - } -} - -//===================================================================================================================== -CLRPrivBinderWinRT * -CLRPrivBinderWinRT::GetOrCreateBinder( - CLRPrivTypeCacheWinRT * pWinRtTypeCache, - NamespaceResolutionKind fNamespaceResolutionKind) -{ - STANDARD_VM_CONTRACT; - HRESULT hr = S_OK; - - if (s_pSingleton == nullptr) - { - ReleaseHolder pBinder; - pBinder = clr::SafeAddRef(new CLRPrivBinderWinRT( - nullptr, // pParentBinder - pWinRtTypeCache, - nullptr, // rgwzAltPath - 0, // cAltPaths - fNamespaceResolutionKind - )); - - if (InterlockedCompareExchangeT(&s_pSingleton, pBinder, nullptr) == nullptr) - { - pBinder.SuppressRelease(); - } - } - _ASSERTE(s_pSingleton->m_fNamespaceResolutionKind == fNamespaceResolutionKind); - - return clr::SafeAddRef(s_pSingleton); -} - -//===================================================================================================================== -HRESULT CLRPrivBinderWinRT::BindWinRTAssemblyByName( - IAssemblyName * pAssemblyName, - CLRPrivAssemblyWinRT ** ppAssembly) -{ - STANDARD_VM_CONTRACT; - HRESULT hr = S_OK; - ReleaseHolder pAssembly; - LPWSTR wszFullTypeName = nullptr; - - VALIDATE_ARG_RET(pAssemblyName != nullptr); - VALIDATE_ARG_RET(ppAssembly != nullptr); - - DWORD dwContentType = AssemblyContentType_Default; - IfFailGo(hr = fusion::util::GetProperty(pAssemblyName, ASM_NAME_CONTENT_TYPE, &dwContentType)); - if ((hr != S_OK) || (dwContentType != AssemblyContentType_WindowsRuntime)) - { - IfFailGo(CLR_E_BIND_UNRECOGNIZED_IDENTITY_FORMAT); - } - - // Note: WinRT type resolution is supported also on pre-Win8 with DesignerResolveEvent - if (!WinRTSupported() && (m_fNamespaceResolutionKind != NamespaceResolutionKind_DesignerResolveEvent)) - { - IfFailGo(COR_E_PLATFORMNOTSUPPORTED); - } - - WCHAR wszAssemblySimpleName[_MAX_PATH]; - { - DWORD cchAssemblySimpleName = _MAX_PATH; - IfFailGo(pAssemblyName->GetName(&cchAssemblySimpleName, wszAssemblySimpleName)); - } - - wszFullTypeName = wcschr(wszAssemblySimpleName, W('!')); - - if (wszFullTypeName != nullptr) - { - _ASSERTE(wszAssemblySimpleName < wszFullTypeName); - if (!(wszAssemblySimpleName < wszFullTypeName)) - { - IfFailGo(E_UNEXPECTED); - } - - // Turns wszAssemblySimpleName into simple name, wszFullTypeName into type name. - *wszFullTypeName++ = W('\0'); - - CLRPrivBinderUtil::WStringList * pFileNameList = nullptr; - BOOL fIsWindowsNamespace = FALSE; - - { - // don't look past the first generics backtick (if any) - WCHAR *pGenericBegin = (WCHAR*)wcschr(wszFullTypeName, W('`')); - if (pGenericBegin != nullptr) - *pGenericBegin = W('\0'); - - LPWSTR wszSimpleTypeName = wcsrchr(wszFullTypeName, W('.')); - - // restore the generics backtick - if (pGenericBegin != nullptr) - *pGenericBegin = W('`'); - - if (wszSimpleTypeName == nullptr) - { - IfFailGo(CLR_E_BIND_UNRECOGNIZED_IDENTITY_FORMAT); - } - - // Turns wszFullTypeName into namespace name (without simple type name) - *wszSimpleTypeName = W('\0'); - - IfFailGo(GetFileNameListForNamespace(wszFullTypeName, &pFileNameList)); - - fIsWindowsNamespace = IsWindowsNamespace(wszFullTypeName); - - // Turns wszFullTypeName back into full type name (was namespace name) - *wszSimpleTypeName = W('.'); - } - - if (pFileNameList == nullptr) - { // There are no file associated with the namespace - IfFailGo(CLR_E_BIND_TYPE_NOT_FOUND); - } - - CLRPrivBinderUtil::WStringListElem * pFileNameElem = pFileNameList->GetHead(); - for (; pFileNameElem != nullptr; pFileNameElem = CLRPrivBinderUtil::WStringList::GetNext(pFileNameElem)) - { - const WCHAR * wszFileName = pFileNameElem->GetValue(); - pAssembly = FindAssemblyByFileName(wszFileName); - - WCHAR wszFileNameStripped[_MAX_PATH] = {0}; - SplitPath(wszFileName, NULL, NULL, NULL, NULL, wszFileNameStripped, _MAX_PATH, NULL, NULL); - - if (pAssembly == nullptr) - { - NewHolder pResource( - new CLRPrivResourcePathImpl(wszFileName)); - - // - // Creating the BindResult we will pass to the native binder to find native images. - // We strip off the type from the assembly name, leaving the simple assembly name. - // The native binder stores native images under subdirectories named after their - // simple name so we only want to pass the simple name portion of the name to it, - // which it uses along with the fingerprint matching in BindResult to find the - // native image for this WinRT assembly. - // The WinRT team has said that WinMDs will have the same simple name as the filename. - // - NewHolder pBindResult(new CoreBindResult()); - StackSString sAssemblyPath(pResource->GetPath()); - ReleaseHolder pBinderAssembly; - - IfFailGo(GetAssemblyAndTryFindNativeImage(sAssemblyPath, wszFileNameStripped, &pBinderAssembly)); - - pBindResult->Init(pBinderAssembly); - NewHolder pNewAssembly( - new CLRPrivAssemblyWinRT(this, pResource, pBindResult, fIsWindowsNamespace)); - - // pNewAssembly holds references to these now - pResource.SuppressRelease(); - pBindResult.SuppressRelease(); - - // Add the assembly into cache (multi-thread aware) - pAssembly = AddFileNameToAssemblyMapping(pResource->GetPath(), pNewAssembly); - - // We did not find an existing assembly in the cache and are using the newly created pNewAssembly. - // Stop it from being deleted when we go out of scope. - if (pAssembly == pNewAssembly) - { - pNewAssembly.SuppressRelease(); - } - - } - - // - // Look to see if there's a native image available. - // - hr = pAssembly->EnsureAvailableImageTypes(); - - // Determine if this is the assembly we really want to find. - IfFailGo(hr = m_pTypeCache->ContainsType(pAssembly, wszFullTypeName)); - if (hr == S_OK) - { // The type we are looking for has been found in this assembly - *ppAssembly = pAssembly.Extract(); - return (hr = S_OK); - } - _ASSERTE(hr == S_FALSE); - } - } - - // The type has not been found in any of the files from the type's namespace - hr = CLR_E_BIND_TYPE_NOT_FOUND; - ErrExit: - - return hr; -} // CLRPrivBinderWinRT::BindWinRTAssemblyByName - - - -//===================================================================================================================== -HRESULT CLRPrivBinderWinRT::BindWinRTAssemblyByName( - IAssemblyName * pAssemblyName, - ICLRPrivAssembly ** ppPrivAssembly) -{ - STANDARD_VM_CONTRACT; - HRESULT hr = S_OK; - - ReleaseHolder pWinRTAssembly; - IfFailRet(BindWinRTAssemblyByName(pAssemblyName, &pWinRTAssembly)); - IfFailRet(pWinRTAssembly->QueryInterface(__uuidof(ICLRPrivAssembly), (LPVOID *)ppPrivAssembly)); - - return hr; -} - -// -// This method opens the assembly using the CoreCLR Binder, which has logic supporting opening either the IL or -// even just the native image without IL present. -// RoResolveNamespace has already told us the IL file to open. We try and find a native image to open instead -// by looking in the TPA list and the App_Ni_Paths. -// -HRESULT CLRPrivBinderWinRT::GetAssemblyAndTryFindNativeImage(SString &sWinmdFilename, LPCWSTR pwzSimpleName, BINDER_SPACE::Assembly ** ppAssembly) -{ - HRESULT hr = S_OK; - - if (!m_pApplicationContext->IsTpaListProvided()) - return COR_E_FILENOTFOUND; - - BINDER_SPACE::SimpleNameToFileNameMap * tpaMap = m_pApplicationContext->GetTpaList(); - const BINDER_SPACE::SimpleNameToFileNameMapEntry *pTpaEntry = tpaMap->LookupPtr(pwzSimpleName); - if (pTpaEntry != nullptr) - { - ReleaseHolder pAssembly; - - if (pTpaEntry->m_wszNIFileName != nullptr) - { - SString fileName(pTpaEntry->m_wszNIFileName); - - // A GetAssembly overload perhaps, or just another parameter to the existing method - hr = BINDER_SPACE::AssemblyBinder::GetAssembly(fileName, - TRUE, /* fIsInGAC */ - TRUE /* fExplicitBindToNativeImage */, - &pAssembly, - sWinmdFilename.GetUnicode() - ); - - // On file not found, simply fall back to app ni path probing - if (hr != HRESULT_FROM_WIN32(ERROR_FILE_NOT_FOUND)) - { - // Any other error is fatal - IfFailRet(hr); - - *ppAssembly = pAssembly.Extract(); - return (hr = S_OK); - } - } - } - - StringArrayList *pBindingPaths = m_pApplicationContext->GetAppNiPaths(); - - // Loop through the binding paths looking for a matching assembly - for (DWORD i = 0; i < pBindingPaths->GetCount(); i++) - { - ReleaseHolder pAssembly; - LPCWSTR wszBindingPath = (*pBindingPaths)[i]; - - SString simpleName(pwzSimpleName); - SString fileName(wszBindingPath); - BINDER_SPACE::CombinePath(fileName, simpleName, fileName); - fileName.Append(W(".ni.DLL")); - - hr = BINDER_SPACE::AssemblyBinder::GetAssembly(fileName, - FALSE, /* fIsInGAC */ - TRUE /* fExplicitBindToNativeImage */, - &pAssembly); - - // Since we're probing, file not founds are ok and we should just try another - // probing path - if (hr == HRESULT_FROM_WIN32(ERROR_FILE_NOT_FOUND)) - { - continue; - } - - IfFailRet(hr); - - *ppAssembly = pAssembly.Extract(); - return (hr = S_OK); - } - - // We did not find a native image for this WinMD; open the WinMD file itself as the assembly to return. - hr = BINDER_SPACE::AssemblyBinder::GetAssembly(sWinmdFilename, - FALSE, /* fIsInGAC */ - FALSE /* fExplicitBindToNativeImage */, - ppAssembly); - - return hr; -} - -//===================================================================================================================== -HRESULT CLRPrivBinderWinRT::SetApplicationContext(BINDER_SPACE::ApplicationContext *pApplicationContext, LPCWSTR pwzAppLocalWinMD) -{ - STANDARD_VM_CONTRACT; - - HRESULT hr = S_OK; - - _ASSERTE(pApplicationContext != nullptr); - m_pApplicationContext = pApplicationContext; - - StringArrayList * pAppPaths = m_pApplicationContext->GetAppPaths(); - -#ifndef CROSSGEN_COMPILE - DWORD cAppPaths = pAppPaths->GetCount(); - m_rgAltPaths.Allocate(cAppPaths); - - for (DWORD i = 0; i < cAppPaths; i++) - { - IfFailRet(WindowsCreateString( - pAppPaths->Get(i).GetUnicode(), - (UINT32)(pAppPaths->Get(i).GetCount()), - m_rgAltPaths.GetRawArray() + i)); - } - - if (pwzAppLocalWinMD != NULL) - { - m_appLocalWinMDPath = DuplicateStringThrowing(pwzAppLocalWinMD); - } -#else - Crossgen::SetAppPaths(pAppPaths); -#endif - - return hr; -} - -//===================================================================================================================== -// Implements interface method code:ICLRPrivBinder::BindAssemblyByName. -// -HRESULT CLRPrivBinderWinRT::BindAssemblyByName( - IAssemblyName * pAssemblyName, - ICLRPrivAssembly ** ppAssembly) -{ - STANDARD_BIND_CONTRACT; - HRESULT hr = S_OK; - - VALIDATE_ARG_RET((pAssemblyName != nullptr) && (ppAssembly != nullptr)); - - EX_TRY - { - if (m_pParentBinder != nullptr) - { - // Delegate to parent binder. - hr = m_pParentBinder->BindAssemblyByName(pAssemblyName, ppAssembly); - } - else - { - hr = BindWinRTAssemblyByName(pAssemblyName, ppAssembly); - } - } - EX_CATCH_HRESULT(hr); - - return hr; -} - -//===================================================================================================================== -ReleaseHolder -CLRPrivBinderWinRT::FindAssemblyByFileName( - PCWSTR wszFileName) -{ - LIMITED_METHOD_CONTRACT; - STATIC_CONTRACT_CAN_TAKE_LOCK; - - ForbidSuspendThreadHolder suspend; - { - CrstHolder lock(&m_MapsLock); - - const FileNameToAssemblyWinRTMapEntry * pEntry = m_FileNameToAssemblyMap.LookupPtr(wszFileName); - return (pEntry == nullptr) ? nullptr : clr::SafeAddRef(pEntry->m_pAssembly); - } -} - -//===================================================================================================================== -// Add FileName -> CLRPrivAssemblyWinRT * mapping to the map (multi-thread safe). -// -ReleaseHolder -CLRPrivBinderWinRT::AddFileNameToAssemblyMapping( - PCWSTR wszFileName, - CLRPrivAssemblyWinRT * pAssembly) -{ - STANDARD_VM_CONTRACT; - - _ASSERTE(pAssembly != nullptr); - - // We have to serialize all Add operations - CrstHolder lock(&m_MapsAddLock); - - // Wrapper for m_FileNameToAssemblyMap.Add that avoids call out into host - FileNameToAssemblyWinRTMap::AddPhases addCall; - - // 1. Preallocate one element - addCall.PreallocateForAdd(&m_FileNameToAssemblyMap); - { - // 2. Take the reader lock which can be taken during stack walking - // We cannot call out into host from ForbidSuspend region (i.e. no allocations/deallocations) - ForbidSuspendThreadHolder suspend; - { - CrstHolder lock(&m_MapsLock); - - const FileNameToAssemblyWinRTMapEntry * pEntry = m_FileNameToAssemblyMap.LookupPtr(wszFileName); - CLRPrivAssemblyWinRT * pResultAssembly = nullptr; - if (pEntry != nullptr) - { - pResultAssembly = pEntry->m_pAssembly; - - // 3a. Use the newly allocated table (if any) to avoid allocation in the next call (no call out into host) - addCall.AddNothing_PublishPreallocatedTable(); - } - else - { - // 3b. Add the element to the hash table (no call out into host) - FileNameToAssemblyWinRTMapEntry e; - e.m_wszFileName = wszFileName; - e.m_pAssembly = pAssembly; - addCall.Add(e); - - pResultAssembly = pAssembly; - } - return clr::SafeAddRef(pResultAssembly); - } - } - // 4. Cleanup the old memory (if any) - will be called by destructor of addCall - //addCall.DeleteOldTable(); -} - -//===================================================================================================================== -void -CLRPrivBinderWinRT::RemoveFileNameToAssemblyMapping( - PCWSTR wszFileName) -{ - LIMITED_METHOD_CONTRACT; - STATIC_CONTRACT_CAN_TAKE_LOCK; - - ForbidSuspendThreadHolder suspend; - { - CrstHolder lock(&m_MapsLock); - - m_FileNameToAssemblyMap.Remove(wszFileName); - } -} - -//===================================================================================================================== -// Returns list of file names from code:m_NamespaceToFileNameListMap for the namespace -// -HRESULT -CLRPrivBinderWinRT::GetFileNameListForNamespace( - LPCWSTR wszNamespace, - CLRPrivBinderUtil::WStringList ** ppFileNameList) -{ - STANDARD_VM_CONTRACT; - STATIC_CONTRACT_CAN_TAKE_LOCK; - - HRESULT hr = S_OK; - - CLRPrivBinderUtil::WStringList * pFileNameList = nullptr; - { - ForbidSuspendThreadHolder suspend; - { - CrstHolder lock(&m_MapsLock); - - const NamespaceToFileNameListMapEntry * pEntry = m_NamespaceToFileNameListMap.LookupPtr(wszNamespace); - if (pEntry != nullptr) - { - // Entries from the map are never removed, so we do not have to protect the file name list with a lock - pFileNameList = pEntry->m_pFileNameList; - } - } - } - - if (pFileNameList != nullptr) - { - *ppFileNameList = pFileNameList; - } - else - { - CLRPrivBinderUtil::WStringListHolder hFileNameList; - LPCWSTR wszNamespaceRoResolve = wszNamespace; - -#ifndef CROSSGEN_COMPILE - if (m_fNamespaceResolutionKind == NamespaceResolutionKind_WindowsAPI) - { - CoTaskMemHSTRINGArrayHolder hFileNames; - - UINT32 cchNamespaceRoResolve; - IfFailRet(StringCchLength(wszNamespaceRoResolve, &cchNamespaceRoResolve)); - - CLRConfigStringHolder wszWinMDPathConfig; - LPWSTR wszWinMDPath = nullptr; - UINT32 cchWinMDPath = 0; - - wszWinMDPath = m_appLocalWinMDPath; - - if (wszWinMDPath != nullptr) - { - IfFailRet(StringCchLength(wszWinMDPath, &cchWinMDPath)); - } - - DWORD cFileNames = 0; - HSTRING * rgFileNames = nullptr; - hr = RoResolveNamespace( - WinRtStringRef(wszNamespaceRoResolve, cchNamespaceRoResolve), - wszWinMDPath != nullptr ? (HSTRING)WinRtStringRef(wszWinMDPath, cchWinMDPath) : nullptr, // hsWindowsSdkPath - m_rgAltPaths.GetCount(), // cPackageGraph - m_rgAltPaths.GetRawArray(), // rgPackageGraph - &cFileNames, - &rgFileNames, - nullptr, // pcDirectNamespaceChildren - nullptr); // rgDirectNamespaceChildren - // For CoreCLR, if the process is not AppX, deliver more appropriate error message - // when trying to bind to 3rd party WinMDs that is not confusing. - if (HRESULT_FROM_WIN32(APPMODEL_ERROR_NO_PACKAGE) == hr) - { - if (!AppX::IsAppXProcess()) - { - IfFailRet(HRESULT_FROM_WIN32(ERROR_NOT_SUPPORTED)); - } - } - - - IfFailRet(hr); - if (hr != S_OK) - { // Not expecting success codes other than S_OK. - IfFailRet(E_UNEXPECTED); - } - - hFileNames.Init(rgFileNames, cFileNames); - - for (DWORD i = 0; i < hFileNames.GetCount(); i++) - { - UINT32 cchFileName = 0; - LPCWSTR wszFileName = WindowsGetStringRawBuffer( - hFileNames.GetAt(i), - &cchFileName); - - BOOL fSkipFilename = FALSE; - if (!fSkipFilename) - hFileNameList.InsertTail(wszFileName); - } - } - else - { - // This code is desktop specific. - _ASSERTE(m_fNamespaceResolutionKind == NamespaceResolutionKind_DesignerResolveEvent); - - EX_TRY - { - m_pTypeCache->RaiseDesignerNamespaceResolveEvent(wszNamespace, &hFileNameList); - } - EX_CATCH - { - Exception * ex = GET_EXCEPTION(); - if (!ex->IsTransient()) - { // Exception was caused by user code - // Cache empty file name list for this namespace - (void)AddFileNameListForNamespace(wszNamespace, nullptr, ppFileNameList); - } - EX_RETHROW; - } - EX_END_CATCH_UNREACHABLE - } - -#else //CROSSGEN_COMPILE - - DWORD cFileNames = 0; - SString * rgFileNames = nullptr; - - hr = Crossgen::CrossgenRoResolveNamespace( - wszNamespaceRoResolve, - &cFileNames, - &rgFileNames); - - IfFailRet(hr); - - if (cFileNames > 0) - { - _ASSERTE(cFileNames == 1); //only support mapping to one file in coregen - hFileNameList.InsertTail(rgFileNames->GetUnicode()); - delete rgFileNames; - } - -#endif //CROSSGEN_COMPILE - - // Add the Namespace -> File name list entry into cache (even if the file name list is empty) - if (AddFileNameListForNamespace(wszNamespace, hFileNameList.GetValue(), ppFileNameList)) - { // The file name list was added to the cache - do not delete it - _ASSERTE(*ppFileNameList == hFileNameList.GetValue()); - (void)hFileNameList.Extract(); - } - } - - return hr; -} // CLRPrivBinderWinRT::GetFileNameListForNamespace - -//===================================================================================================================== -// Adds (thread-safe) list of file names to code:m_NamespaceToFileNameListMap for the namespace - returns the cached value. -// Returns TRUE, if pFileNameList was added to the cache and caller should NOT delete it. -// Returns FALSE, if pFileNameList was not added to the cache and caller should delete it. -// -BOOL -CLRPrivBinderWinRT::AddFileNameListForNamespace( - LPCWSTR wszNamespace, - CLRPrivBinderUtil::WStringList * pFileNameList, - CLRPrivBinderUtil::WStringList ** ppFileNameList) -{ - STANDARD_VM_CONTRACT; - - NewArrayHolder wszEntryNamespace = DuplicateStringThrowing(wszNamespace); - - NamespaceToFileNameListMapEntry entry; - entry.m_wszNamespace = wszEntryNamespace.GetValue(); - entry.m_pFileNameList = pFileNameList; - - // We have to serialize all Add operations - CrstHolder lock(&m_MapsAddLock); - - // Wrapper for m_NamespaceToFileNameListMap.Add that avoids call out into host - NamespaceToFileNameListMap::AddPhases addCall; - - // Status if the element was added to the hash table or not - BOOL fAddedToCache = FALSE; - - // 1. Preallocate one element - addCall.PreallocateForAdd(&m_NamespaceToFileNameListMap); - { - // 2. Take the reader lock which can be taken during stack walking - // We cannot call out into host from ForbidSuspend region (i.e. no allocations/deallocations) - ForbidSuspendThreadHolder suspend; - { - CrstHolder lock(&m_MapsLock); - - const NamespaceToFileNameListMapEntry * pEntry = m_NamespaceToFileNameListMap.LookupPtr(wszNamespace); - if (pEntry == nullptr) - { - // 3a. Add the element to the hash table (no call out into host) - addCall.Add(entry); - - // These values are now owned by the hash table element - wszEntryNamespace.SuppressRelease(); - *ppFileNameList = pFileNameList; - fAddedToCache = TRUE; - } - else - { // Another thread beat us adding this entry to the hash table - *ppFileNameList = pEntry->m_pFileNameList; - - // 3b. Use the newly allocated table (if any) to avoid allocation in the next call (no call out into host) - addCall.AddNothing_PublishPreallocatedTable(); - _ASSERTE(fAddedToCache == FALSE); - } - } - } - // 4. Cleanup the old memory (if any), also called from the destructor of addCall - addCall.DeleteOldTable(); - - return fAddedToCache; -} // CLRPrivBinderWinRT::AddFileNameListForNamespace - -#endif //!DACCESS_COMPILE - -//===================================================================================================================== -// Finds assembly with WinRT type if it is already loaded. -// -PTR_Assembly -CLRPrivBinderWinRT::FindAssemblyForTypeIfLoaded( - PTR_AppDomain pAppDomain, - LPCUTF8 szNamespace, - LPCUTF8 szClassName) -{ - CONTRACTL - { - NOTHROW; - GC_NOTRIGGER; - FORBID_FAULT; - MODE_ANY; - SUPPORTS_DAC; - } - CONTRACTL_END - - WCHAR wszNamespace[MAX_CLASSNAME_LENGTH]; - int cchNamespace = WszMultiByteToWideChar(CP_UTF8, 0, szNamespace, -1, wszNamespace, _countof(wszNamespace)); - if (cchNamespace == 0) - { - return NULL; - } - - CLRPrivBinderUtil::WStringListElem * pFileNameElem= nullptr; - const NamespaceToFileNameListMapEntry * pNamespaceEntry; - { - ForbidSuspendThreadHolder suspend; - { - CrstHolder lock(&m_MapsLock); - - pNamespaceEntry = m_NamespaceToFileNameListMap.LookupPtr(wszNamespace); - if ((pNamespaceEntry == nullptr) || (pNamespaceEntry->m_pFileNameList == nullptr)) - { - return NULL; - } - - pFileNameElem = pNamespaceEntry->m_pFileNameList->GetHead(); - } - } - - while (pFileNameElem != nullptr) - { - const WCHAR * wszFileName = pFileNameElem->GetValue(); - PTR_CLRPrivAssemblyWinRT pPrivAssembly=NULL; - const FileNameToAssemblyWinRTMapEntry * pFileNameEntry; - { - ForbidSuspendThreadHolder suspend; - { - CrstHolder lock(&m_MapsLock); - - pFileNameEntry = m_FileNameToAssemblyMap.LookupPtr(wszFileName); - if (pFileNameEntry == nullptr || pFileNameEntry->m_pAssembly == nullptr) - { - return NULL; - } - - pPrivAssembly = pFileNameEntry->m_pAssembly; - } - } - - if (pPrivAssembly == NULL) - { - return NULL; - } - - _ASSERT(((void *)(CLRPrivAssemblyWinRT *)0x100) == - ((void *)(ICLRPrivAssembly *)(CLRPrivAssemblyWinRT *)0x100)); - - PTR_Assembly pAssembly = NULL; - HRESULT hr = m_pTypeCache->ContainsTypeIfLoaded( - pAppDomain, - dac_cast(pPrivAssembly), - szNamespace, - szClassName, - &pAssembly); - if (hr == S_OK) - { // The type we are looking for has been found in this assembly - _ASSERTE(pAssembly != nullptr); - return pAssembly; - } - if (FAILED(hr)) - { // Assembly was not loaded - return NULL; - } - // Type was not found in the assembly - _ASSERTE(hr == S_FALSE); - - // Try next file name for this namespace - pFileNameElem = CLRPrivBinderUtil::WStringList::GetNext(pFileNameElem); - } - - return NULL; -} // CLRPrivBinderWinRT::FindAssemblyForTypeIfLoaded - -#ifndef DACCESS_COMPILE - - -//===================================================================================================================== -CLRPrivAssemblyWinRT::CLRPrivAssemblyWinRT( - CLRPrivBinderWinRT * pBinder, - CLRPrivResourcePathImpl * pResourceIL, - CoreBindResult * pBindResult, - BOOL fShareable) - : m_pBinder(nullptr), - m_pResourceIL(nullptr), - m_pIResourceNI(nullptr), - m_pBindResult(nullptr), - m_dwImageTypes(0), - m_FallbackBinder(nullptr) -{ - STANDARD_VM_CONTRACT; - VALIDATE_ARG_THROW((pBinder != nullptr) && (pResourceIL != nullptr) && (pBindResult != nullptr)); - - m_pBinder = clr::SafeAddRef(pBinder); - m_pResourceIL = clr::SafeAddRef(pResourceIL); - m_pBindResult = clr::SafeAddRef(pBindResult); -} - -//===================================================================================================================== -CLRPrivAssemblyWinRT::~CLRPrivAssemblyWinRT() -{ - LIMITED_METHOD_CONTRACT; - clr::SafeRelease(m_pIResourceNI); -} - -//===================================================================================================================== -// Implements interface method code:IUnknown::Release. -// Overridden to implement self-removal from assembly map code:CLRPrivBinderWinRT::m_FileNameToAssemblyMap. -// -ULONG CLRPrivAssemblyWinRT::Release() -{ - LIMITED_METHOD_CONTRACT; - STATIC_CONTRACT_CAN_TAKE_LOCK; - _ASSERTE(m_cRef > 0); - - ULONG cRef; - - { - // To achieve proper lifetime semantics, the name to assembly map elements' CLRPrivAssemblyWinRT - // instances are not ref counted. We cannot allow discovery of the object via m_FileNameToAssemblyMap - // when the ref count is 0 (to prevent another thread to AddRef and Release it back to 0 in parallel). - // All uses of the map are guarded by the map lock, so we have to decrease the ref count under that - // lock (to avoid the chance that 2 threads are running Release to ref count 0 at once). - ForbidSuspendThreadHolder suspend; - { - CrstHolder lock(&m_pBinder->m_MapsLock); - cRef = InterlockedDecrement(&m_cRef); - if (cRef == 0) - { - m_pBinder->RemoveFileNameToAssemblyMapping(m_pResourceIL->GetPath()); - } - } - } - - // Note: We cannot deallocate memory in the ForbidSuspendThread region - if (cRef == 0) - { - delete this; - } - - return cRef; -} // CLRPrivAssemblyWinRT::Release - -//===================================================================================================================== -// Implements interface method code:ICLRPrivAssembly::GetAvailableImageTypes. -// -HRESULT CLRPrivAssemblyWinRT::GetAvailableImageTypes( - LPDWORD pdwImageTypes) -{ - STANDARD_BIND_CONTRACT; - - HRESULT hr = S_OK; - - VALIDATE_ARG_RET(pdwImageTypes != nullptr); - - EX_TRY - { - IfFailGo(EnsureAvailableImageTypes()); - - *pdwImageTypes = m_dwImageTypes; - hr = S_OK; - ErrExit: - ; - } - EX_CATCH_HRESULT(hr); - - return hr; -} - - -//===================================================================================================================== -// Implements interface method code:ICLRPrivAssembly::GetImageResource. -// -HRESULT CLRPrivAssemblyWinRT::GetImageResource( - DWORD dwImageType, - DWORD * pdwImageType, - ICLRPrivResource ** ppIResource) -{ - STANDARD_BIND_CONTRACT; - HRESULT hr = S_OK; - - VALIDATE_ARG_RET((ppIResource != nullptr) && (m_pBindResult != nullptr)); - - EX_TRY - { - IfFailGo(EnsureAvailableImageTypes()); - - DWORD _dwImageType; - if (pdwImageType == nullptr) - { - pdwImageType = &_dwImageType; - } - - if ((dwImageType & ASSEMBLY_IMAGE_TYPE_NATIVE) == ASSEMBLY_IMAGE_TYPE_NATIVE) - { - if (m_pIResourceNI == nullptr) - { - IfFailGo(CLR_E_BIND_IMAGE_UNAVAILABLE); - } - - *ppIResource = clr::SafeAddRef(m_pIResourceNI); - *pdwImageType = ASSEMBLY_IMAGE_TYPE_NATIVE; - } - else if ((dwImageType & ASSEMBLY_IMAGE_TYPE_IL) == ASSEMBLY_IMAGE_TYPE_IL) - { - *ppIResource = clr::SafeAddRef(m_pResourceIL); - *pdwImageType = ASSEMBLY_IMAGE_TYPE_IL; - } - else - { - hr = CLR_E_BIND_IMAGE_UNAVAILABLE; - } - ErrExit: - ; - } - EX_CATCH_HRESULT(hr); - - return hr; -} - -//===================================================================================================================== -// Implements interface method code:ICLRPrivBinder::GetBinderID. -// -HRESULT CLRPrivBinderWinRT::GetBinderID( - UINT_PTR * pBinderId) -{ - LIMITED_METHOD_CONTRACT; - - *pBinderId = reinterpret_cast(this); - return S_OK; -} - -//===================================================================================================================== -HRESULT CLRPrivAssemblyWinRT::EnsureAvailableImageTypes() -{ - STANDARD_VM_CONTRACT; - HRESULT hr = S_OK; - - DWORD dwImageTypesLocal = m_dwImageTypes; - - // If image types has not yet been set, attempt to bind to native assembly - if (dwImageTypesLocal == 0) - { - if (m_pIResourceNI == nullptr) - { - if (m_pBindResult->HasNativeImage()) - { - SString sPath = m_pBindResult->GetNativeImage()->GetPath(); - m_pIResourceNI = new CLRPrivResourcePathImpl(sPath.GetUnicode()); - m_pIResourceNI->AddRef(); - } - IfFailGo(hr); - } - - DWORD dwImageTypes = 0; - - if (m_pResourceIL != nullptr) - dwImageTypes |= ASSEMBLY_IMAGE_TYPE_IL; - - if (m_pIResourceNI != nullptr) - dwImageTypes |= ASSEMBLY_IMAGE_TYPE_NATIVE; - - m_dwImageTypes = dwImageTypes; - } -ErrExit: - - return hr; -} - -#endif //!DACCESS_COMPILE diff --git a/src/coreclr/src/vm/clrprivbinderwinrt.h b/src/coreclr/src/vm/clrprivbinderwinrt.h deleted file mode 100644 index aba041c..0000000 --- a/src/coreclr/src/vm/clrprivbinderwinrt.h +++ /dev/null @@ -1,326 +0,0 @@ -// 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. -// - - -// -// Contains the types that implement code:ICLRPrivBinder and code:ICLRPrivAssembly for WinRT binding. -// -//============================================================================================= - -#pragma once - -#include "holder.h" -#include "internalunknownimpl.h" -#include "clrprivbinding.h" -#include "clrprivbinderutil.h" -#include "clrprivtypecachewinrt.h" -#include "clr_std/utility" -#include "winrt/windowsstring.h" -#include "appxutil.h" - -#include "coreclr/corebindresult.h" - -//===================================================================================================================== -// Forward declarations -class CLRPrivBinderWinRT; -class CLRPrivAssemblyWinRT; -class BINDER_SPACE::ApplicationContext; -class BINDER_SPACE::Assembly; - -typedef DPTR(CLRPrivBinderWinRT) PTR_CLRPrivBinderWinRT; -typedef DPTR(CLRPrivAssemblyWinRT) PTR_CLRPrivAssemblyWinRT; - -BOOL -IsWindowsNamespace(const char * wszNamespace); - -//===================================================================================================================== -//===================================================================================================================== -//===================================================================================================================== -class CLRPrivBinderWinRT : - public IUnknownCommon -{ - friend class CLRPrivAssemblyWinRT; - -public: - //============================================================================================= - // Options of namespace resolution - enum NamespaceResolutionKind - { - NamespaceResolutionKind_WindowsAPI, // Using RoResolveNamespace Win8 API - NamespaceResolutionKind_DesignerResolveEvent // Using DesignerNamespaceResolve event - }; - -private: - //============================================================================================= - // Data structures for Namespace -> FileNameList map (as returned by RoResolveNamespace API) - - // Entry in SHash table that maps namespace to list of files - struct NamespaceToFileNameListMapEntry - { - PTR_WSTR m_wszNamespace; - CLRPrivBinderUtil::PTR_WStringList m_pFileNameList; - }; - - // SHash traits for Namespace -> FileNameList hash - class NamespaceToFileNameListMapTraits : public NoRemoveSHashTraits< DefaultSHashTraits< NamespaceToFileNameListMapEntry > > - { - public: - typedef PCWSTR key_t; - static const NamespaceToFileNameListMapEntry Null() { NamespaceToFileNameListMapEntry e; e.m_wszNamespace = PTR_WSTR(nullptr); return e; } - static bool IsNull(const NamespaceToFileNameListMapEntry & e) { return e.m_wszNamespace == nullptr; } - static PCWSTR GetKey(const NamespaceToFileNameListMapEntry & e) { return e.m_wszNamespace; } - static count_t Hash(PCWSTR str) { return HashString(str); } - static BOOL Equals(PCWSTR lhs, PCWSTR rhs) { LIMITED_METHOD_CONTRACT; return (wcscmp(lhs, rhs) == 0); } - - void OnDestructPerEntryCleanupAction(const NamespaceToFileNameListMapEntry & e) - { - delete [] e.m_wszNamespace; - CLRPrivBinderUtil::WStringList_Delete(e.m_pFileNameList); - } - static const bool s_DestructPerEntryCleanupAction = true; - }; - - typedef SHash NamespaceToFileNameListMap; - - //============================================================================================= - // Data structure for FileName -> CLRPrivAssemblyWinRT * map - - struct FileNameToAssemblyWinRTMapEntry - { - PTR_CWSTR m_wszFileName; // File name (owned by m_pAssembly) - PTR_CLRPrivAssemblyWinRT m_pAssembly; - }; - - class FileNameToAssemblyWinRTMapTraits : public DefaultSHashTraits - { - public: - typedef PCWSTR key_t; - static const FileNameToAssemblyWinRTMapEntry Null() { FileNameToAssemblyWinRTMapEntry e; e.m_wszFileName = PTR_CWSTR(nullptr); return e; } - static bool IsNull(const FileNameToAssemblyWinRTMapEntry &e) { return e.m_wszFileName == PTR_CWSTR(nullptr); } - static const FileNameToAssemblyWinRTMapEntry Deleted() { FileNameToAssemblyWinRTMapEntry e; e.m_wszFileName = (PTR_CWSTR)-1; return e; } - static bool IsDeleted(const FileNameToAssemblyWinRTMapEntry & e) { return dac_cast(e.m_wszFileName) == (TADDR)-1; } - static PCWSTR GetKey(const FileNameToAssemblyWinRTMapEntry & e) { return e.m_wszFileName; } - static count_t Hash(PCWSTR str) { return HashString(str); } - static BOOL Equals(PCWSTR lhs, PCWSTR rhs) { LIMITED_METHOD_CONTRACT; return (wcscmp(lhs, rhs) == 0); } - }; - - typedef SHash FileNameToAssemblyWinRTMap; - -public: - //============================================================================================= - // ICLRPrivBinder interface methods - - // Implements interface method code:ICLRPrivBinder::BindAssemblyByName. - STDMETHOD(BindAssemblyByName)( - IAssemblyName * pAssemblyName, - ICLRPrivAssembly ** ppAssembly); - - // Implements interface method code:ICLRPrivBinder::GetBinderID. - STDMETHOD(GetBinderID)( - UINT_PTR * pBinderId); - - STDMETHOD(GetLoaderAllocator)( - LPVOID * pLoaderAllocator) - { - return E_FAIL; - } - - - //============================================================================================= - // Class methods - - CLRPrivBinderWinRT( - ICLRPrivBinder * pParentBinder, - CLRPrivTypeCacheWinRT * pWinRtTypeCache, - LPCWSTR * rgwzAltPath, - UINT cAltPaths, - NamespaceResolutionKind fNamespaceResolutionKind); - - static - CLRPrivBinderWinRT * GetOrCreateBinder( - CLRPrivTypeCacheWinRT * pWinRtTypeCache, - NamespaceResolutionKind fNamespaceResolutionKind); - - ~CLRPrivBinderWinRT(); - - // Binds WinRT assemblies only. - HRESULT BindWinRTAssemblyByName( - IAssemblyName * pIAssemblyName, - CLRPrivAssemblyWinRT ** ppAssembly); - - // Binds WinRT assemblies only. - HRESULT BindWinRTAssemblyByName( - IAssemblyName * pIAssemblyName, - ICLRPrivAssembly ** ppPrivAssembly); - - HRESULT GetAssemblyAndTryFindNativeImage(SString &sWinmdFilename, LPCWSTR pwzSimpleName, BINDER_SPACE::Assembly ** ppAssembly); - // On Phone the application's APP_PATH CoreCLR hosting config property is used as the app - // package graph for RoResolveNamespace to find 3rd party WinMDs. This method wires up - // the app paths so the WinRT binder will find 3rd party WinMDs. - HRESULT SetApplicationContext(BINDER_SPACE::ApplicationContext *pApplicationContext, LPCWSTR pwzAppLocalWinMD); - // Finds assembly with WinRT type if it is already loaded - PTR_Assembly FindAssemblyForTypeIfLoaded( - PTR_AppDomain pAppDomain, - LPCUTF8 szNamespace, - LPCUTF8 szClassName); - - -private: - //============================================================================================= - // Accessors for FileName -> CLRPrivAssemblyWinRT * map - - ReleaseHolder FindAssemblyByFileName( - PCWSTR wzsFileName); - - ReleaseHolder AddFileNameToAssemblyMapping( - PCWSTR wszFileName, - CLRPrivAssemblyWinRT * pAssembly); - - void RemoveFileNameToAssemblyMapping( - PCWSTR wszFileName); - - //============================================================================================= - // Internal methods - - // Returns list of file names from code:m_NamespaceToFileNameListMap for the namespace - HRESULT GetFileNameListForNamespace(LPCWSTR wszNamespace, CLRPrivBinderUtil::WStringList ** ppFileNameList); - - // Adds (thread-safe) list of file names to code:m_NamespaceToFileNameListMap for the namespace. - // Returns TRUE if the list was added to the cache. - BOOL AddFileNameListForNamespace( - LPCWSTR wszNamespace, - CLRPrivBinderUtil::WStringList * pFileNameList, - CLRPrivBinderUtil::WStringList ** ppFileNameList); - - -private: - //============================================================================================= - - // Namespace -> FileName list map ... items are never removed - NamespaceToFileNameListMap m_NamespaceToFileNameListMap; - // FileName -> CLRPrivAssemblyWinRT * map ... items can be removed when CLRPrivAssemblyWinRT dies - FileNameToAssemblyWinRTMap m_FileNameToAssemblyMap; - - // Lock for the above maps - CrstExplicitInit m_MapsLock; - // Lock for adding into the above maps, in addition to the read-lock above - CrstExplicitInit m_MapsAddLock; - - //============================================================================================= - - PTR_CLRPrivTypeCacheWinRT m_pTypeCache; - - // The kind of namespace resolution (RoResolveNamespace Win8 API or DesignerNamespaceResolve event) - NamespaceResolutionKind m_fNamespaceResolutionKind; - - static CLRPrivBinderWinRT * s_pSingleton; - - // Parent binder used to delegate bind requests up the binder hierarchy. - ICLRPrivBinder * m_pParentBinder; - -#ifndef CROSSGEN_COMPILE - // Alternative paths for use with RoGetNamespace api - CLRPrivBinderUtil::HSTRINGArrayHolder m_rgAltPaths; -#endif - - - - BINDER_SPACE::ApplicationContext * m_pApplicationContext; - NewArrayHolder m_appLocalWinMDPath; - - -}; // class CLRPrivBinderWinRT - - -//===================================================================================================================== -//===================================================================================================================== -//===================================================================================================================== -class CLRPrivAssemblyWinRT : - public IUnknownCommon2 -{ - friend class CLRPrivBinderWinRT; - -public: - //============================================================================================= - // Class methods - - CLRPrivAssemblyWinRT( - CLRPrivBinderWinRT * pBinder, - CLRPrivBinderUtil::CLRPrivResourcePathImpl * pResourceIL, - CoreBindResult * pBindResult, - BOOL fShareable); - - ~CLRPrivAssemblyWinRT(); - - //============================================================================================= - // IUnknown interface methods - - // Implements interface method code:IUnknown::Release. - // Overridden to implement self-removal from assembly map code:CLRPrivBinderWinRT::m_FileNameToAssemblyMap. - STDMETHOD_(ULONG, Release)(); - - //============================================================================================= - // ICLRPrivBinder interface methods - - // Implements interface method code:ICLRPrivBinder::BindAssemblyByName. - STDMETHOD(BindAssemblyByName)( - IAssemblyName * pAssemblyName, - ICLRPrivAssembly ** ppAssembly) - { - STATIC_CONTRACT_WRAPPER; - return m_pBinder->BindAssemblyByName(pAssemblyName, ppAssembly); - } - - // Implements interface method code:ICLRPrivBinder::GetBinderID. - STDMETHOD(GetBinderID)( - UINT_PTR * pBinderId) - { - STATIC_CONTRACT_WRAPPER; - return m_pBinder->GetBinderID(pBinderId); - } - - STDMETHOD(GetLoaderAllocator)( - LPVOID * pLoaderAllocator) - { - WRAPPER_NO_CONTRACT; - return m_pBinder->GetLoaderAllocator(pLoaderAllocator); - } - - //============================================================================================= - // ICLRPrivAssembly interface methods - - // Implements interface method code:ICLRPrivAssembly::GetAvailableImageTypes. - STDMETHOD(GetAvailableImageTypes)( - LPDWORD pdwImageTypes); - - // Implements interface method code:ICLRPrivAssembly::GetImageResource. - STDMETHOD(GetImageResource)( - DWORD dwImageType, - DWORD * pdwImageType, - ICLRPrivResource ** ppIResource); - - void SetFallbackBinder(ICLRPrivBinder* fallbackBinder) - { - m_FallbackBinder = clr::SafeAddRef(fallbackBinder); - } - - ICLRPrivBinder* GetFallbackBinder() - { - return m_FallbackBinder; - } - -private: - //============================================================================================= - - HRESULT EnsureAvailableImageTypes(); - - ReleaseHolder m_pBinder; - ReleaseHolder m_pResourceIL; - // This cannot be a holder as there can be a race to assign to it. - ICLRPrivResource * m_pIResourceNI; - ReleaseHolder m_pBindResult; - Volatile m_dwImageTypes; - ReleaseHolder m_FallbackBinder; -}; // class CLRPrivAssemblyWinRT diff --git a/src/coreclr/src/vm/clrprivtypecachewinrt.cpp b/src/coreclr/src/vm/clrprivtypecachewinrt.cpp deleted file mode 100644 index 2749dcc..0000000 --- a/src/coreclr/src/vm/clrprivtypecachewinrt.cpp +++ /dev/null @@ -1,238 +0,0 @@ -// 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. -// - -// -// Contains VM implementation of WinRT type cache for code:CLRPrivBinderWinRT binder. -// -//===================================================================================================================== - -#include "common.h" // precompiled header -#include "clrprivtypecachewinrt.h" - -#ifndef DACCESS_COMPILE - -//===================================================================================================================== -// S_OK - pAssembly contains type wszTypeName -// S_FALSE - pAssembly does not contain type wszTypeName -// -HRESULT -CLRPrivTypeCacheWinRT::ContainsType( - ICLRPrivAssembly * pPrivAssembly, - LPCWSTR wszTypeName) -{ - STANDARD_VM_CONTRACT; - - HRESULT hr = S_OK; - - AppDomain * pAppDomain = AppDomain::GetCurrentDomain(); - - ReleaseHolder pPEAssembly; - IfFailGo(pAppDomain->BindHostedPrivAssembly(nullptr, pPrivAssembly, nullptr, &pPEAssembly)); - _ASSERTE(pPEAssembly != nullptr); - - { - // Find DomainAssembly * (can be cached if this is too slow to call always) - DomainAssembly * pDomainAssembly = pAppDomain->LoadDomainAssembly( - nullptr, // pIdentity - pPEAssembly, - FILE_LOAD_DELIVER_EVENTS); - - // Convert the type name into namespace and class name in UTF8 - StackSString ssTypeNameWCHAR(wszTypeName); - - StackSString ssTypeName; - ssTypeNameWCHAR.ConvertToUTF8(ssTypeName); - LPUTF8 szTypeName = (LPUTF8)ssTypeName.GetUTF8NoConvert(); - - LPCUTF8 szNamespace; - LPCUTF8 szClassName; - ns::SplitInline(szTypeName, szNamespace, szClassName); - - hr = ContainsTypeHelper(pDomainAssembly->GetAssembly(), szNamespace, szClassName); - _ASSERTE((hr == S_OK) || (hr == S_FALSE)); - return hr; - } - -ErrExit: - return hr; -} // CLRPrivTypeCacheWinRT::ContainsType - -#endif //!DACCESS_COMPILE - -//===================================================================================================================== -// -// Checks if the type (szNamespace/szClassName) is present in the assembly pAssembly. -// -// Return value: -// S_OK - Type is present in the assembly. -// S_FALSE - Type is not present. -// No other error codes or success codes -// -HRESULT -CLRPrivTypeCacheWinRT::ContainsTypeHelper( - PTR_Assembly pAssembly, - LPCUTF8 szNamespace, - LPCUTF8 szClassName) -{ - CONTRACTL - { - if (FORBIDGC_LOADER_USE_ENABLED()) NOTHROW; else THROWS; - if (FORBIDGC_LOADER_USE_ENABLED()) GC_NOTRIGGER; else GC_TRIGGERS; - MODE_ANY; - SUPPORTS_DAC; - } - CONTRACTL_END - - NameHandle typeName(szNamespace, szClassName); - - // Find the type in the assembly (use existing hash of all type names defined in the assembly) - TypeHandle thType; - mdToken tkType; - Module * pTypeModule; - mdToken tkExportedType; - - if (pAssembly->GetLoader()->FindClassModuleThrowing( - &typeName, - &thType, - &tkType, - &pTypeModule, - &tkExportedType, - nullptr, // pFoundEntry - nullptr, // pLookInThisModuleOnly - Loader::DontLoad)) - { - return S_OK; - } - else - { - return S_FALSE; - } -} // CLRPrivTypeCacheWinRT::ContainsTypeHelper - -//===================================================================================================================== -// -// Checks if the assembly pPrivAssembly (referenced from assembly in pAppDomain) contains type (szNamespace/szClassName). -// Fills *ppAssembly if it contains the type. -// -// Return value: -// S_OK - Contains type (fills *ppAssembly). -// S_FALSE - Does not contain the type (*ppAssembly is not filled). -// E_FAIL - Assembly is not loaded. -// -HRESULT -CLRPrivTypeCacheWinRT::ContainsTypeIfLoaded( - PTR_AppDomain pAppDomain, - PTR_ICLRPrivAssembly pPrivAssembly, - LPCUTF8 szNamespace, - LPCUTF8 szClassName, - PTR_Assembly * ppAssembly) -{ - CONTRACTL - { - NOTHROW; - GC_NOTRIGGER; - FORBID_FAULT; - MODE_ANY; - SUPPORTS_DAC; - } - CONTRACTL_END - - HRESULT hr; - - PTR_DomainAssembly pDomainAssembly = pAppDomain->FindAssembly(pPrivAssembly); - if (pDomainAssembly == nullptr || !pDomainAssembly->IsLoaded()) - { // The assembly is not loaded into the AppDomain - return E_FAIL; - } - PTR_Assembly pAssembly = dac_cast(pDomainAssembly->GetLoadedAssembly()); - if (pAssembly == nullptr) - { // The assembly failed to load earlier (exception is cached on pDomainAssembly) - return E_FAIL; - } - - hr = ContainsTypeHelper(pAssembly, szNamespace, szClassName); - _ASSERTE((hr == S_OK) || (hr == S_FALSE)); - if (hr == S_OK) - { // The type is present in the assembly - *ppAssembly = pAssembly; - } - return hr; -} // CLRPrivTypeCacheWinRT::ContainsTypeIfLoaded - -#ifndef DACCESS_COMPILE - -#ifndef CROSSGEN_COMPILE -//===================================================================================================================== -// Raises user event DesignerNamespaceResolveEvent to get a list of files for this namespace. -// -void -CLRPrivTypeCacheWinRT::RaiseDesignerNamespaceResolveEvent( - LPCWSTR wszNamespace, - CLRPrivBinderUtil::WStringListHolder * pFileNameList) -{ - STANDARD_VM_CONTRACT; - - _ASSERTE(pFileNameList != nullptr); - - GCX_COOP(); - - struct _gc { - STRINGREF str; - } gc; - ZeroMemory(&gc, sizeof(gc)); - - GCPROTECT_BEGIN(gc); - MethodDescCallSite onNamespaceResolve(METHOD__WINDOWSRUNTIMEMETATADA__ON_DESIGNER_NAMESPACE_RESOLVE); - gc.str = StringObject::NewString(wszNamespace); - ARG_SLOT args[1] = - { - ObjToArgSlot(gc.str) - }; - PTRARRAYREF ResultingFileNameArrayRef = (PTRARRAYREF) onNamespaceResolve.Call_RetOBJECTREF(args); - if (ResultingFileNameArrayRef != NULL) - { - for (DWORD i = 0; i < ResultingFileNameArrayRef->GetNumComponents(); i++) - { - STRINGREF ResultingFileNameRef = (STRINGREF) ResultingFileNameArrayRef->GetAt(i); - _ASSERTE(ResultingFileNameRef != NULL); // Verified in the managed code OnDesignerNamespaceResolveEvent - - SString sFileName; - ResultingFileNameRef->GetSString(sFileName); - _ASSERTE(!sFileName.IsEmpty()); // Verified in the managed code OnDesignerNamespaceResolveEvent - - pFileNameList->InsertTail(sFileName.GetUnicode()); - } - } - GCPROTECT_END(); -} // CLRPrivTypeCacheWinRT::RaiseDesignerNamespaceResolveEvent - -//===================================================================================================================== -#endif // CROSSGEN_COMPILE - -CLRPrivTypeCacheWinRT * CLRPrivTypeCacheWinRT::s_pSingleton = nullptr; - -//===================================================================================================================== -CLRPrivTypeCacheWinRT * -CLRPrivTypeCacheWinRT::GetOrCreateTypeCache() -{ - STANDARD_VM_CONTRACT; - - if (s_pSingleton == nullptr) - { - ReleaseHolder pTypeCache; - pTypeCache = clr::SafeAddRef(new CLRPrivTypeCacheWinRT()); - - if (InterlockedCompareExchangeT(&s_pSingleton, pTypeCache, nullptr) == nullptr) - { - pTypeCache.SuppressRelease(); - } - } - - return s_pSingleton; -} - -//===================================================================================================================== - -#endif //!DACCESS_COMPILE diff --git a/src/coreclr/src/vm/clrprivtypecachewinrt.h b/src/coreclr/src/vm/clrprivtypecachewinrt.h deleted file mode 100644 index cf01ce7..0000000 --- a/src/coreclr/src/vm/clrprivtypecachewinrt.h +++ /dev/null @@ -1,70 +0,0 @@ -// 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. -// - -// -// Contains VM implementation of WinRT type cache for code:CLRPrivBinderWinRT binder. -// -//===================================================================================================================== - -#pragma once - -#include "internalunknownimpl.h" -#include "clrprivbinding.h" - -//===================================================================================================================== -class CLRPrivTypeCacheWinRT : - public IUnknownCommon -{ -public: - //============================================================================================= - // Class methods - - // S_OK - pAssembly contains type wszTypeName - // S_FALSE - pAssembly does not contain type wszTypeName - HRESULT ContainsType( - ICLRPrivAssembly * pAssembly, - LPCWSTR wszTypeName); - - // S_OK - pAssembly contains type wszTypeName - // S_FALSE - pAssembly does not contain type wszTypeName - // E_FAIL - assembly is not loaded - HRESULT ContainsTypeIfLoaded( - PTR_AppDomain pAppDomain, - PTR_ICLRPrivAssembly pPrivAssembly, - LPCUTF8 szNamespace, - LPCUTF8 szClassName, - PTR_Assembly * ppAssembly); - - static CLRPrivTypeCacheWinRT * GetOrCreateTypeCache(); - -#ifndef DACCESS_COMPILE - -#ifndef CROSSGEN_COMPILE - // Raises user event DesignerNamespaceResolveEvent to get a list of files for this namespace. - void RaiseDesignerNamespaceResolveEvent( - LPCWSTR wszNamespace, - CLRPrivBinderUtil::WStringListHolder * pFileNameList); -#endif // CROSSGEN_COMPILE - -#endif //!DACCESS_COMPILE - -private: - //============================================================================================= - // Private methods - - // Checks if the type (szNamespace/szClassName) is present in the assembly pAssembly. - HRESULT ContainsTypeHelper( - PTR_Assembly pAssembly, - LPCUTF8 szNamespace, - LPCUTF8 szClassName); - - //============================================================================================= - // Class fields - - static CLRPrivTypeCacheWinRT * s_pSingleton; - -}; // class CLRPrivTypeCaheWinRT - -typedef DPTR(CLRPrivTypeCacheWinRT) PTR_CLRPrivTypeCacheWinRT; diff --git a/src/coreclr/src/vm/clrtocomcall.cpp b/src/coreclr/src/vm/clrtocomcall.cpp index 6f8d7e3..1e31736 100644 --- a/src/coreclr/src/vm/clrtocomcall.cpp +++ b/src/coreclr/src/vm/clrtocomcall.cpp @@ -86,54 +86,25 @@ ComPlusCallInfo *ComPlusCall::PopulateComPlusCallMethodDesc(MethodDesc* pMD, DWO ComPlusCallInfo *pComInfo = ComPlusCallInfo::FromMethodDesc(pMD); _ASSERTE(pComInfo != NULL); - BOOL fWinRTCtor = FALSE; - BOOL fWinRTComposition = FALSE; - BOOL fWinRTStatic = FALSE; - BOOL fWinRTDelegate = FALSE; - if (pMD->IsInterface()) { pComInfo->m_cachedComSlot = pMD->GetComSlot(); pItfMT = pMT; pComInfo->m_pInterfaceMT = pItfMT; } - else if (pMT->IsWinRTDelegate()) - { - pComInfo->m_cachedComSlot = ComMethodTable::GetNumExtraSlots(ifVtable); - pItfMT = pMT; - pComInfo->m_pInterfaceMT = pItfMT; - - fWinRTDelegate = TRUE; - } else { - BOOL fIsWinRTClass = (!pMT->IsInterface() && pMT->IsProjectedFromWinRT()); MethodDesc *pItfMD; - if (fIsWinRTClass && pMD->IsCtor()) + pItfMD = pMD->GetInterfaceMD(); + if (pItfMD == NULL) { - // ctors on WinRT classes call factory interface methods - pItfMD = GetWinRTFactoryMethodForCtor(pMD, &fWinRTComposition); - fWinRTCtor = TRUE; - } - else if (fIsWinRTClass && pMD->IsStatic()) - { - // static members of WinRT classes call static interface methods - pItfMD = GetWinRTFactoryMethodForStatic(pMD); - fWinRTStatic = TRUE; - } - else - { - pItfMD = pMD->GetInterfaceMD(); - if (pItfMD == NULL) - { - // the method does not implement any interface - StackSString ssClassName; - pMT->_GetFullyQualifiedNameForClass(ssClassName); - StackSString ssMethodName(SString::Utf8, pMD->GetName()); + // the method does not implement any interface + StackSString ssClassName; + pMT->_GetFullyQualifiedNameForClass(ssClassName); + StackSString ssMethodName(SString::Utf8, pMD->GetName()); - COMPlusThrow(kInvalidOperationException, IDS_EE_COMIMPORT_METHOD_NO_INTERFACE, ssMethodName.GetUnicode(), ssClassName.GetUnicode()); - } + COMPlusThrow(kInvalidOperationException, IDS_EE_COMIMPORT_METHOD_NO_INTERFACE, ssMethodName.GetUnicode(), ssClassName.GetUnicode()); } pComInfo->m_cachedComSlot = pItfMD->GetComSlot(); @@ -162,53 +133,10 @@ ComPlusCallInfo *ComPlusCall::PopulateComPlusCallMethodDesc(MethodDesc* pMD, DWO if (fComEventCall) dwStubFlags |= NDIRECTSTUB_FL_COMEVENTCALL; - bool fIsWinRT = (pItfMT->IsProjectedFromWinRT() || pItfMT->IsWinRTRedirectedDelegate()); - if (!fIsWinRT && pItfMT->IsWinRTRedirectedInterface(TypeHandle::Interop_ManagedToNative)) - { - if (!pItfMT->HasInstantiation()) - { - // non-generic redirected interface needs to keep its pre-4.5 classic COM interop - // behavior so the IL stub will be special - it will conditionally tail-call to - // the new WinRT marshaling routines - dwStubFlags |= NDIRECTSTUB_FL_WINRTHASREDIRECTION; - } - else - { - fIsWinRT = true; - } - } - - if (fIsWinRT) - { - dwStubFlags |= NDIRECTSTUB_FL_WINRT; - - if (pMD->IsGenericComPlusCall()) - dwStubFlags |= NDIRECTSTUB_FL_WINRTSHAREDGENERIC; - } - - if (fWinRTCtor) - { - dwStubFlags |= NDIRECTSTUB_FL_WINRTCTOR; - - if (fWinRTComposition) - dwStubFlags |= NDIRECTSTUB_FL_WINRTCOMPOSITION; - } - - if (fWinRTStatic) - dwStubFlags |= NDIRECTSTUB_FL_WINRTSTATIC; - - if (fWinRTDelegate) - dwStubFlags |= NDIRECTSTUB_FL_WINRTDELEGATE | NDIRECTSTUB_FL_WINRT; - BOOL BestFit = TRUE; BOOL ThrowOnUnmappableChar = FALSE; - // Marshaling is fully described by the parameter type in WinRT. BestFit custom attributes - // are not going to affect the marshaling behavior. - if (!fIsWinRT) - { - ReadBestFitCustomAttribute(pMD, &BestFit, &ThrowOnUnmappableChar); - } + ReadBestFitCustomAttribute(pMD, &BestFit, &ThrowOnUnmappableChar); if (BestFit) dwStubFlags |= NDIRECTSTUB_FL_BESTFIT; @@ -224,147 +152,6 @@ ComPlusCallInfo *ComPlusCall::PopulateComPlusCallMethodDesc(MethodDesc* pMD, DWO return pComInfo; } -// static -MethodDesc *ComPlusCall::GetWinRTFactoryMethodForCtor(MethodDesc *pMDCtor, BOOL *pComposition) -{ - CONTRACTL - { - STANDARD_VM_CHECK; - PRECONDITION(CheckPointer(pMDCtor)); - PRECONDITION(pMDCtor->IsCtor()); - } - CONTRACTL_END; - - MethodTable *pMT = pMDCtor->GetMethodTable(); - _ASSERTE(pMT->IsProjectedFromWinRT()); - - // If someone is trying to access a WinRT attribute, block it since there is no actual implementation type - MethodTable *pParentMT = pMT->GetParentMethodTable(); - if (pParentMT == MscorlibBinder::GetClass(CLASS__ATTRIBUTE)) - { - DefineFullyQualifiedNameForClassW(); - COMPlusThrow(kInvalidOperationException, IDS_EE_WINRT_ATTRIBUTES_NOT_INVOKABLE, GetFullyQualifiedNameForClassW(pMT)); - } - - // build the expected factory method signature - PCCOR_SIGNATURE pSig; - DWORD cSig; - pMDCtor->GetSig(&pSig, &cSig); - SigParser ctorSig(pSig, cSig); - - ULONG numArgs; - - IfFailThrow(ctorSig.GetCallingConv(NULL)); // calling convention - IfFailThrow(ctorSig.GetData(&numArgs)); // number of args - IfFailThrow(ctorSig.SkipExactlyOne()); // skip return type - - // Get the class factory for the type - WinRTClassFactory *pFactory = GetComClassFactory(pMT)->AsWinRTClassFactory(); - BOOL fComposition = pFactory->IsComposition(); - - if (numArgs == 0 && !fComposition) - { - // this is a default ctor - it will use IActivationFactory::ActivateInstance - return MscorlibBinder::GetMethod(METHOD__IACTIVATIONFACTORY__ACTIVATE_INSTANCE); - } - - // Composition factory methods have two additional arguments - // For now a class has either composition factories or regular factories but never both. - // In future versions it's possible we may want to allow a class to become unsealed, in - // which case we'll probably need to support both and change how we find factory methods. - if (fComposition) - { - numArgs += 2; - } - - SigBuilder sigBuilder; - sigBuilder.AppendByte(IMAGE_CEE_CS_CALLCONV_HASTHIS); - sigBuilder.AppendData(numArgs); - - // the return type is the class that declares the ctor - sigBuilder.AppendElementType(ELEMENT_TYPE_INTERNAL); - sigBuilder.AppendPointer(pMT); - - // parameter types are identical - ctorSig.GetSignature(&pSig, &cSig); - sigBuilder.AppendBlob((const PVOID)pSig, cSig); - - if (fComposition) - { - // in: outer IInspectable to delegate to, or null - sigBuilder.AppendElementType(ELEMENT_TYPE_OBJECT); - - // out: non-delegating IInspectable for the created object - sigBuilder.AppendElementType(ELEMENT_TYPE_BYREF); - sigBuilder.AppendElementType(ELEMENT_TYPE_OBJECT); - } - - pSig = (PCCOR_SIGNATURE)sigBuilder.GetSignature(&cSig); - - // ask the factory to find a matching method - MethodDesc *pMD = pFactory->FindFactoryMethod(pSig, cSig, pMDCtor->GetModule()); - - if (pMD == NULL) - { - // @TODO: Do we want a richer exception message? - SString ctorMethodName(SString::Utf8, COR_CTOR_METHOD_NAME); - COMPlusThrowNonLocalized(kMissingMethodException, ctorMethodName.GetUnicode()); - } - - if (pComposition != NULL) - { - *pComposition = fComposition; - } - - return pMD; -} - -// static -MethodDesc *ComPlusCall::GetWinRTFactoryMethodForStatic(MethodDesc *pMDStatic) -{ - CONTRACTL - { - STANDARD_VM_CHECK; - PRECONDITION(CheckPointer(pMDStatic)); - PRECONDITION(pMDStatic->IsStatic()); - } - CONTRACTL_END; - - MethodTable *pMT = pMDStatic->GetMethodTable(); - _ASSERTE(pMT->IsProjectedFromWinRT()); - - // build the expected interface method signature - PCCOR_SIGNATURE pSig; - DWORD cSig; - pMDStatic->GetSig(&pSig, &cSig); - SigParser ctorSig(pSig, cSig); - - IfFailThrow(ctorSig.GetCallingConv(NULL)); // calling convention - - // use the "has this" calling convention because we're looking for an instance method - SigBuilder sigBuilder; - sigBuilder.AppendByte(IMAGE_CEE_CS_CALLCONV_HASTHIS); - - // return type and parameter types are identical - ctorSig.GetSignature(&pSig, &cSig); - sigBuilder.AppendBlob((const PVOID)pSig, cSig); - - pSig = (PCCOR_SIGNATURE)sigBuilder.GetSignature(&cSig); - - // ask the factory to find a matching method - WinRTClassFactory *pFactory = GetComClassFactory(pMT)->AsWinRTClassFactory(); - MethodDesc *pMD = pFactory->FindStaticMethod(pMDStatic->GetName(), pSig, cSig, pMDStatic->GetModule()); - - if (pMD == NULL) - { - // @TODO: Do we want a richer exception message? - SString staticMethodName(SString::Utf8, pMDStatic->GetName()); - COMPlusThrowNonLocalized(kMissingMethodException, staticMethodName.GetUnicode()); - } - - return pMD; -} - MethodDesc* ComPlusCall::GetILStubMethodDesc(MethodDesc* pMD, DWORD dwStubFlags) { STANDARD_VM_CONTRACT; diff --git a/src/coreclr/src/vm/clrtocomcall.h b/src/coreclr/src/vm/clrtocomcall.h index 4ada3cb..7c4691a 100644 --- a/src/coreclr/src/vm/clrtocomcall.h +++ b/src/coreclr/src/vm/clrtocomcall.h @@ -31,8 +31,6 @@ class ComPlusCall static PCODE GetStubForILStub(MethodDesc* pMD, MethodDesc** ppStubMD); static ComPlusCallInfo *PopulateComPlusCallMethodDesc(MethodDesc* pMD, DWORD* pdwStubFlags); - static MethodDesc *GetWinRTFactoryMethodForCtor(MethodDesc *pMDCtor, BOOL *pComposition); - static MethodDesc *GetWinRTFactoryMethodForStatic(MethodDesc *pMDStatic); #ifdef TARGET_X86 static void Init(); diff --git a/src/coreclr/src/vm/clsload.cpp b/src/coreclr/src/vm/clsload.cpp index d453eda..1d82d0f 100644 --- a/src/coreclr/src/vm/clsload.cpp +++ b/src/coreclr/src/vm/clsload.cpp @@ -275,39 +275,6 @@ PTR_Module ClassLoader::ComputeLoaderModuleForCompilation( pZapperLoaderModule = pTargetModule; } - // If generating WinMD resilient code and we so far choose to use the target module, - // we need to check if the definition module or any of the instantiation type can - // cause version resilient problems. - if (g_fNGenWinMDResilient && pZapperLoaderModule == pTargetModule) - { - if (pDefinitionModule != NULL && !pDefinitionModule->IsInCurrentVersionBubble()) - { - pZapperLoaderModule = pDefinitionModule; - goto ModuleAdjustedForVersionResiliency; - } - - for (DWORD i = 0; i < classInst.GetNumArgs(); i++) - { - Module * pModule = classInst[i].GetLoaderModule(); - if (!pModule->IsInCurrentVersionBubble()) - { - pZapperLoaderModule = pModule; - goto ModuleAdjustedForVersionResiliency; - } - } - - for (DWORD i = 0; i < methodInst.GetNumArgs(); i++) - { - Module * pModule = methodInst[i].GetLoaderModule(); - if (!pModule->IsInCurrentVersionBubble()) - { - pZapperLoaderModule = pModule; - goto ModuleAdjustedForVersionResiliency; - } - } -ModuleAdjustedForVersionResiliency: ; - } - // Record this choice just in case we're NGEN'ing multiple modules // to make sure we always do the same thing if we're asked to compute // the loader module again. @@ -973,34 +940,6 @@ VOID ClassLoader::PopulateAvailableClassHashTable(Module* pModule, HENUMInternal hTypeDefEnum; IMDInternalImport * pImport = pModule->GetMDImport(); - LPCSTR szWinRtNamespacePrefix = NULL; - DWORD cchWinRtNamespacePrefix = 0; - -#ifdef FEATURE_COMINTEROP - SString ssFileName; - StackScratchBuffer ssFileNameBuffer; - - if (pModule->GetAssembly()->IsWinMD()) - { // WinMD file in execution context (not ReflectionOnly context) - use its file name as WinRT namespace prefix - // (Windows requirement) - // Note: Reflection can work on 'unfinished' WinMD files where the types are in 'wrong' WinMD file (i.e. - // type namespace does not start with the file name) - - _ASSERTE(pModule->GetFile()->IsAssembly()); // No multi-module WinMD file support - _ASSERTE(!pModule->GetFile()->GetPath().IsEmpty()); - - SplitPath( - pModule->GetFile()->GetPath(), - NULL, // Drive - NULL, // Directory - &ssFileName, - NULL); // Extension - - szWinRtNamespacePrefix = ssFileName.GetUTF8(ssFileNameBuffer); - cchWinRtNamespacePrefix = (DWORD)strlen(szWinRtNamespacePrefix); - } -#endif //FEATURE_COMINTEROP - IfFailThrow(pImport->EnumTypeDefInit(&hTypeDefEnum)); // Now loop through all the classdefs adding the CVID and scope to the hash @@ -1008,9 +947,7 @@ VOID ClassLoader::PopulateAvailableClassHashTable(Module* pModule, AddAvailableClassHaveLock(pModule, td, - pamTracker, - szWinRtNamespacePrefix, - cchWinRtNamespacePrefix); + pamTracker); } pImport->EnumClose(&hTypeDefEnum); } @@ -4093,18 +4030,12 @@ VOID ClassLoader::AddAvailableClassDontHaveLock(Module *pModule, } CONTRACTL_END -#ifdef FEATURE_COMINTEROP - _ASSERTE(!pModule->GetAssembly()->IsWinMD()); // WinMD files should never get into this path, otherwise provide szWinRtNamespacePrefix -#endif - CrstHolder ch(&m_AvailableClassLock); AddAvailableClassHaveLock( pModule, classdef, - pamTracker, - NULL, // szWinRtNamespacePrefix - 0); // cchWinRtNamespacePrefix + pamTracker); } // This routine must be single threaded! The reason is that there are situations which allow @@ -4116,15 +4047,10 @@ VOID ClassLoader::AddAvailableClassDontHaveLock(Module *pModule, // This routine assumes you already have the lock. Use AddAvailableClassDontHaveLock() if you // don't have it. // -// Also validates that TypeDef namespace begins with szWinRTNamespacePrefix (if it is not NULL). -// The prefix should be NULL for normal non-WinRT .NET assemblies. -// VOID ClassLoader::AddAvailableClassHaveLock( Module * pModule, mdTypeDef classdef, - AllocMemTracker * pamTracker, - LPCSTR szWinRtNamespacePrefix, - DWORD cchWinRtNamespacePrefix) // Optimization for faster prefix comparison implementation + AllocMemTracker * pamTracker) // Optimization for faster prefix comparison implementation { CONTRACTL { @@ -4244,39 +4170,6 @@ VOID ClassLoader::AddAvailableClassHaveLock( if (pClassCaseInsHash) pClassCaseInsHash->InsertValueUsingPreallocatedEntry(pCaseInsEntry, pszLowerCaseNS, pszLowerCaseName, pEntry, pEntry->GetEncloser()); } - -#ifdef FEATURE_COMINTEROP - // Check WinRT namespace prefix if required - if (szWinRtNamespacePrefix != NULL) - { - DWORD dwAttr; - if (FAILED(pMDImport->GetTypeDefProps(classdef, &dwAttr, NULL))) - { - pModule->GetAssembly()->ThrowBadImageException(pszNameSpace, pszName, BFA_INVALID_TOKEN); - } - - // Check only public WinRT types that are not nested (i.e. only types available for binding, excluding NoPIA) - if (IsTdPublic(dwAttr) && IsTdWindowsRuntime(dwAttr)) - { - // Guaranteed by the caller - code:ClassLoader::PopulateAvailableClassHashTable - _ASSERTE(cchWinRtNamespacePrefix == strlen(szWinRtNamespacePrefix)); - - // Now make sure namespace is, or begins with the namespace-prefix (note: 'MyN' should not match namespace 'MyName') - // Note: Case insensitive comparison function has to be in sync with Win8 implementation - // (ExtractExactCaseNamespaceSegmentFromMetadataFile in com\WinRT\WinTypes\TypeResolution\NamespaceResolution.cpp) - BOOL fIsNamespaceSubstring = (pszNameSpace != NULL) && - ((strncmp(pszNameSpace, szWinRtNamespacePrefix, cchWinRtNamespacePrefix) == 0) || - (_strnicmp(pszNameSpace, szWinRtNamespacePrefix, cchWinRtNamespacePrefix) == 0)); - BOOL fIsSubNamespace = fIsNamespaceSubstring && - ((pszNameSpace[cchWinRtNamespacePrefix] == '\0') || - (pszNameSpace[cchWinRtNamespacePrefix] == '.')); - if (!fIsSubNamespace) - { - pModule->GetAssembly()->ThrowBadImageException(pszNameSpace, pszName, BFA_WINRT_INVALID_NAMESPACE_FOR_TYPE); - } - } - } -#endif // FEATURE_COMINTEROP } } diff --git a/src/coreclr/src/vm/clsload.hpp b/src/coreclr/src/vm/clsload.hpp index 23a051f..05996dc 100644 --- a/src/coreclr/src/vm/clsload.hpp +++ b/src/coreclr/src/vm/clsload.hpp @@ -494,7 +494,6 @@ class ClassLoader friend class Assembly; friend class Module; friend class InstantiatedMethodDesc; - friend class CLRPrivTypeCacheWinRT; // the following two classes are friends because they will call LoadTypeHandleForTypeKey by token directly friend class COMDynamicWrite; @@ -760,9 +759,7 @@ private: VOID AddAvailableClassHaveLock(Module * pModule, mdTypeDef classdef, - AllocMemTracker * pamTracker, - LPCSTR szWinRtNamespacePrefix, - DWORD cchWinRtNamespacePrefix); + AllocMemTracker * pamTracker); VOID AddExportedTypeDontHaveLock(Module *pManifestModule, mdExportedType cl, diff --git a/src/coreclr/src/vm/comcallablewrapper.cpp b/src/coreclr/src/vm/comcallablewrapper.cpp index 583d52d..0a830ef 100644 --- a/src/coreclr/src/vm/comcallablewrapper.cpp +++ b/src/coreclr/src/vm/comcallablewrapper.cpp @@ -42,8 +42,6 @@ #include "contractimpl.h" #include "caparser.h" #include "appdomain.inl" -#include "rcwwalker.h" -#include "winrttypenameconverter.h" #include "typestring.h" // The enum that describes the value of the IDispatchImplAttribute custom attribute. @@ -342,12 +340,6 @@ bool IsOleAutDispImplRequiredForClass(MethodTable *pClass) Assembly * pAssembly = pClass->GetAssembly(); IDispatchImplType DispImplType = SystemDefinedImpl; - if (pClass->IsWinRTObjectType() || pClass->IsExportedToWinRT()) - { - // IDispatch is not supported in WinRT - return false; - } - // First check for the IDispatchImplType custom attribute first. hr = pClass->GetCustomAttribute(WellKnownAttribute::IDispatchImpl, (const void**)&pVal, &cbVal); if (hr == S_OK) @@ -498,14 +490,6 @@ extern "C" PCODE ComPreStubWorker(ComPrestubMethodFrame *pPFrame, UINT64 *pError { MethodDesc* pTargetMD = pCMD->GetMethodDesc(); MetaSig::EnsureSigValueTypesLoaded(pTargetMD); - - if (pCMD->IsWinRTCtor() || pCMD->IsWinRTStatic() || pCMD->IsWinRTRedirectedMethod()) - { - // Activation, static method invocation, and call through a redirected interface may be the first - // managed code that runs in the module. Fully load it here so we don't have to call EnsureInstanceActive - // on every activation/static call. - pTargetMD->GetMethodTable()->EnsureInstanceActive(); - } } EX_CATCH { @@ -518,7 +502,7 @@ extern "C" PCODE ComPreStubWorker(ComPrestubMethodFrame *pPFrame, UINT64 *pError { // Transform the exception into an HRESULT. This also sets up // an IErrorInfo on the current thread for the exception. - hr = SetupErrorInfo(pADThrowable, pCMD); + hr = SetupErrorInfo(pADThrowable); pADThrowable = NULL; fExceptionThrown = TRUE; } @@ -548,7 +532,7 @@ extern "C" PCODE ComPreStubWorker(ComPrestubMethodFrame *pPFrame, UINT64 *pError { // Transform the exception into an HRESULT. This also sets up // an IErrorInfo on the current thread for the exception. - hr = SetupErrorInfo(pADThrowable, pCMD); + hr = SetupErrorInfo(pADThrowable); pADThrowable = NULL; } } @@ -570,7 +554,7 @@ extern "C" PCODE ComPreStubWorker(ComPrestubMethodFrame *pPFrame, UINT64 *pError { // Transform the exception into an HRESULT. This also sets up // an IErrorInfo on the current thread for the exception. - hr = SetupErrorInfo(pThrowable, pCMD); + hr = SetupErrorInfo(pThrowable); pThrowable = NULL; } } @@ -669,214 +653,6 @@ public: } }; - -WeakReferenceImpl::WeakReferenceImpl(SimpleComCallWrapper *pSimpleWrapper, Thread *pCurrentThread) -{ - CONTRACTL - { - THROWS; - GC_TRIGGERS; - MODE_PREEMPTIVE; - PRECONDITION(pCurrentThread == GetThread()); - } - CONTRACTL_END; - - // - // Create a short weak handle in the current domain and use it to track the lifetime of the object in this domain - // It is a short weak handle so that we can avoid client calling into a object that will be/is being/has been finalized - // We DONOT use the appdomain of the CCW because the object could be domain-agile and could bleed through - // appdomain boundary. In that case, the object becomes a different object from user's perspective, and the fact - // that it is the same object is just an optimization. Therefore, we always create a new WeakReferenceImpl - // instance based on the current domain, as if we were deaing with a copy of the object. - // - AppDomain *pDomain = pCurrentThread->GetDomain(); - - { - GCX_COOP_THREAD_EXISTS(pCurrentThread); - m_ppObject = pDomain->CreateShortWeakHandle(pSimpleWrapper->GetObjectRef()); - } - - // Start with ref count = 1 - AddRef(); -} - -WeakReferenceImpl::~WeakReferenceImpl() -{ - WRAPPER_NO_CONTRACT; - - // Ignore the HR. Cleanup must return HR though (due to BEGIN_EXTERNAL_ENTRYPOINT) - Cleanup(); -} - -HRESULT WeakReferenceImpl::Cleanup() -{ - SetupForComCallHR(); - - CONTRACTL - { - NOTHROW; - GC_TRIGGERS; - MODE_PREEMPTIVE; - } - CONTRACTL_END; - - HRESULT hr = S_OK; - - BEGIN_EXTERNAL_ENTRYPOINT(&hr) - { - // - // Destroy the handle if the AppDomain is still there - // The AppDomain is the domain where this WeakReferenceImpl is created - // - GCX_COOP_THREAD_EXISTS(GET_THREAD()); - - DestroyShortWeakHandle(m_ppObject); - - m_ppObject = NULL; - } - END_EXTERNAL_ENTRYPOINT; - - return S_OK; -} - -struct WeakReferenceResolveCallbackArgs -{ - WeakReferenceImpl *pThis; - Thread *pThread; - GUID iid; - IInspectable **ppvObject; - HRESULT *pHR; -}; - -HRESULT STDMETHODCALLTYPE WeakReferenceImpl::Resolve(REFIID riid, IInspectable **ppvObject) -{ - SetupForComCallHR(); - - CONTRACTL - { - NOTHROW; - GC_TRIGGERS; - MODE_PREEMPTIVE; - } - CONTRACTL_END; - - if (ppvObject == NULL) - return E_INVALIDARG; - - *ppvObject = NULL; - - HRESULT hr = S_OK; - - BEGIN_EXTERNAL_ENTRYPOINT(&hr) - { - Thread *pThread = GET_THREAD(); - - WeakReferenceResolveCallbackArgs args = { this, pThread, riid, ppvObject, &hr }; - - Resolve_Callback(&args); - } - END_EXTERNAL_ENTRYPOINT; - - return hr; -} - -void WeakReferenceImpl::Resolve_Callback(LPVOID lpData) -{ - CONTRACTL - { - THROWS; - GC_TRIGGERS; - MODE_PREEMPTIVE; - PRECONDITION(CheckPointer(lpData)); - } - CONTRACTL_END; - - WeakReferenceResolveCallbackArgs *lpArgs = reinterpret_cast(lpData); - - *(lpArgs->pHR) = lpArgs->pThis->ResolveInternal(lpArgs->pThread, lpArgs->iid, lpArgs->ppvObject); -} - -void WeakReferenceImpl::Resolve_Callback_SwitchToPreemp(LPVOID lpData) -{ - CONTRACTL - { - THROWS; - GC_TRIGGERS; - MODE_COOPERATIVE; - PRECONDITION(CheckPointer(lpData)); - } - CONTRACTL_END; - - WeakReferenceResolveCallbackArgs *lpArgs = reinterpret_cast(lpData); - - GCX_PREEMP_THREAD_EXISTS(lpArgs->pThread); - - Resolve_Callback(lpData); -} - -// -// Resolving WeakReference into a IInspectable* -// Must be called in the right domain where this WeakReference is created -// -HRESULT WeakReferenceImpl::ResolveInternal(Thread *pThread, REFIID riid, IInspectable **ppvObject) -{ - CONTRACTL - { - THROWS; - GC_TRIGGERS; - MODE_PREEMPTIVE; - PRECONDITION(CheckPointer(ppvObject)); - } - CONTRACTL_END; - - HRESULT hr = S_OK; - - SafeComHolder pUnk; - - { - GCX_COOP_THREAD_EXISTS(pThread); - - OBJECTREF refTarget = NULL; - GCPROTECT_BEGIN_THREAD(pThread, refTarget); - refTarget = ObjectFromHandle(m_ppObject); - if (refTarget != NULL) - { - // - // Retrieve the wrapper - // - // NOTE: Even though the object is alive, the old CCW (where you create the weakreference) - // could be gone if : - // 1. the object is domain-agile (for example, string), and - // 2. the domain A where the object used to live is unloaded, and - // 3. the domain B where we create WeakReferenceImpl is a in a different domain - // - // In the above case, the object is alive, and the CCW in domain A is neutered, - // and InlineGetWrapper creates a new CCW - // This means, you might get a different IUnknown* identity with Resolve in this case, - // but this has always been the case since whidbey. If we were to fix the identity - // problem, we need to make sure: - // 1. We hand out different CCW for each domain (instead of having "agile" CCWs), and - // 2. per-Domain SyncBlockInfo on SyncBlock - // - CCWHolder pWrap = ComCallWrapper::InlineGetWrapper(&refTarget); - - // - // Retrieve the pUnk pointer and AddRef - // - pUnk = pWrap->GetBasicIP(); - } - GCPROTECT_END(); - } - - if (pUnk != NULL) - { - hr = Unknown_QueryInterface(pUnk, riid, (void **)ppvObject); - } - - return hr; - -} - NOINLINE void LogCCWRefCountChange_BREAKPOINT(ComCallWrapper *pCCW) { LIMITED_METHOD_CONTRACT; @@ -1216,9 +992,6 @@ void SimpleComCallWrapper::InitNew(OBJECTREF oref, ComCallWrapperCache *pWrapper if (IsExtendsCOMObject()) m_rgpVtable[enum_IProvideClassInfo] = NULL; - // IStringable is valid only on classes that are exposed to WinRT. - m_rgpVtable[enum_IStringable] = NULL; - // IErrorInfo is valid only for exception classes m_rgpVtable[enum_IErrorInfo] = NULL; @@ -1468,31 +1241,6 @@ BOOL SimpleComCallWrapper::SupportsExceptions(MethodTable *pClass) } //-------------------------------------------------------------------------- -// Returns TRUE if the pClass represents a class and is exposed to WinRT. -//-------------------------------------------------------------------------- -BOOL SimpleComCallWrapper::SupportsIStringable(MethodTable *pClass) -{ - CONTRACTL - { - THROWS; - GC_TRIGGERS; - MODE_ANY; - PRECONDITION(CheckPointer(pClass, NULL_OK)); - } - CONTRACTL_END; - - // Support IStringable if the Methodtable represents a class. - if (pClass != NULL - && IsTdClass(pClass->GetAttrClass()) - ) - { - return TRUE; - } - - return FALSE; -} - -//-------------------------------------------------------------------------- // Returns TRUE if the COM+ object that this wrapper represents implements // IExpando. //-------------------------------------------------------------------------- @@ -1642,19 +1390,6 @@ IUnknown* SimpleComCallWrapper::QIStandardInterface(Enum_StdInterfaces index) pIntf = (IUnknown*)&m_rgpVtable[enum_IErrorInfo]; } } - else if(index == enum_IStringable) - { - if(SupportsIStringable(m_pMT)) - { - // Set up the vtable pointer so that next time we don't have to determine - // that the IStringable is provided by the managed class. - m_rgpVtable[enum_IStringable] = g_rgStdVtables[enum_IStringable]; - - // Return the interface pointer to the standard IStringable interface. - pIntf = (IUnknown*)&m_rgpVtable[enum_IStringable]; - } - } - else if (index == enum_IDispatchEx) { if (AppX::IsAppXProcess()) @@ -1723,11 +1458,6 @@ inline bool IsIUnknown(REFIID riid) IS_KNOWN_INTERFACE_CONTRACT(IID_IUnknown); RETURN IS_EQUAL_GUID(riid, 0x00000000,0x0000,0x0000,0xC0,0x00,0x00,0x00,0x00,0x00,0x00,0x46); } -inline bool IsIInspectable(REFIID riid) -{ - IS_KNOWN_INTERFACE_CONTRACT(IID_IInspectable); - RETURN IS_EQUAL_GUID(riid, 0xAF86E2E0,0xB12D,0x4c6a,0x9C,0x5A,0xD7,0xAA,0x65,0x10,0x1E,0x90); -} inline bool IsIDispatch(REFIID riid) { IS_KNOWN_INTERFACE_CONTRACT(IID_IDispatch); @@ -1738,11 +1468,6 @@ inline bool IsGUID_NULL(REFIID riid) IS_KNOWN_INTERFACE_CONTRACT(GUID_NULL); RETURN IS_EQUAL_GUID(riid, 0x00000000,0x0000,0x0000,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00); } -inline bool IsIAgileObject(REFIID riid) -{ - IS_KNOWN_INTERFACE_CONTRACT(IID_IAgileObject); - RETURN IS_EQUAL_GUID(riid, 0x94ea2b94,0xe9cc,0x49e0,0xc0,0xff,0xee,0x64,0xca,0x8f,0x5b,0x90); -} inline bool IsIErrorInfo(REFIID riid) { IS_KNOWN_INTERFACE_CONTRACT(IID_IErrorInfo); @@ -1763,59 +1488,23 @@ IUnknown* SimpleComCallWrapper::QIStandardInterface(REFIID riid) CONTRACT_END; // IID_IMarshal 00000003-0000-0000-C000-000000000046 - // IID_IWeakReferenceSource 00000038-0000-0000-C000-000000000046 // IID_IErrorInfo 1CF2B120-547D-101B-8E65-08002B2BD119 - // IID_ICCW 64BD43F8-BFEE-4EC4-B7EB-2935158DAE21 - // IID_ICustomPropertyProvider 7C925755-3E48-42B4-8677-76372267033F - // IID_IAgileObject 94ea2b94-e9cc-49e0-c0ff-ee64ca8f5b90 // IID_IDispatchEx A6EF9860-C720-11d0-9337-00A0C90DCAA9 // IID_IProvideClassInfo B196B283-BAB4-101A-B69C-00AA00341D07 // IID_IConnectionPointContainer B196B284-BAB4-101A-B69C-00AA00341D07 // IID_IObjectSafety CB5BDC81-93C1-11cf-8F20-00805F2CD064 // IID_ISupportErrorInfo DF0B3D60-548F-101B-8E65-08002B2BD119 - // IID_IStringable.................96369F54-8EB6-48f0-ABCE-C1B211E627C3 + // IID_IAgileObject 94ea2b94-e9cc-49e0-c0ff-ee64ca8f5b90 // Switch on the first DWORD since they're all (currently) unique. switch (riid.Data1) { HANDLE_IID_INLINE(enum_IMarshal ,0x00000003,0x0000,0x0000,0xC0,0x00,0x00,0x00,0x00,0x00,0x00,0x46); HANDLE_IID_INLINE(enum_IErrorInfo ,0x1CF2B120,0x547D,0x101B,0x8E,0x65,0x08,0x00,0x2B,0x2B,0xD1,0x19); - HANDLE_IID_INLINE(enum_ICCW ,0x64BD43F8,0xBFEE,0x4EC4,0xB7,0xEB,0x29,0x35,0x15,0x8D,0xAE,0x21); - HANDLE_IID_INLINE(enum_ICustomPropertyProvider ,0x7C925755,0x3E48,0x42B4,0x86,0x77,0x76,0x37,0x22,0x67,0x03,0x3F); // hit1, above HANDLE_IID_INLINE(enum_IDispatchEx ,0xA6EF9860,0xC720,0x11d0,0x93,0x37,0x00,0xA0,0xC9,0x0D,0xCA,0xA9); // hit3, != HANDLE_IID_INLINE(enum_ISupportsErrorInfo ,0xDF0B3D60,0x548F,0x101B,0x8E,0x65,0x08,0x00,0x2B,0x2B,0xD1,0x19); - HANDLE_IID_INLINE(enum_IStringable ,0x96369f54,0x8eb6,0x48f0,0xab,0xce,0xc1,0xb2,0x11,0xe6,0x27,0xc3); - - CASE_IID_INLINE( enum_IProvideClassInfo ,0xB196B283,0xBAB4,0x101A,0xB6,0x9C,0x00,0xAA,0x00,0x34,0x1D,0x07) // hit4, != - { - // respond only if this is a classic COM interop scenario - MethodTable *pClassMT = GetMethodTable(); - if (!pClassMT->IsExportedToWinRT() && !pClassMT->IsWinRTObjectType()) - { - RETURN QIStandardInterface(enum_IProvideClassInfo); - } - } - break; - - CASE_IID_INLINE( enum_IConnectionPointContainer,0xB196B284,0xBAB4,0x101A,0xB6,0x9C,0x00,0xAA,0x00,0x34,0x1D,0x07) // b196b284 101abab4 aa009cb6 071d3400 - { - // respond only if this is a classic COM interop scenario - MethodTable *pClassMT = GetMethodTable(); - if (!pClassMT->IsExportedToWinRT() && !pClassMT->IsWinRTObjectType()) - { - RETURN QIStandardInterface(enum_IConnectionPointContainer); - } - } - break; - - CASE_IID_INLINE( enum_IWeakReferenceSource ,0x00000038,0x0000,0x0000,0xC0,0x00,0x00,0x00,0x00,0x00,0x00,0x46) - { - // respond only if this type implements a WinRT interface - if (m_pTemplate->SupportsIInspectable()) - RETURN QIStandardInterface(enum_IWeakReferenceSource); - } - break; - + HANDLE_IID_INLINE(enum_IProvideClassInfo ,0xB196B283,0xBAB4,0x101A,0xB6,0x9C,0x00,0xAA,0x00,0x34,0x1D,0x07); // hit4, != + HANDLE_IID_INLINE(enum_IConnectionPointContainer,0xB196B284,0xBAB4,0x101A,0xB6,0x9C,0x00,0xAA,0x00,0x34,0x1D,0x07); // b196b284 101abab4 aa009cb6 071d3400 CASE_IID_INLINE( enum_IAgileObject ,0x94ea2b94,0xe9cc,0x49e0,0xc0,0xff,0xee,0x64,0xca,0x8f,0x5b,0x90) { // Don't implement IAgileObject if we are aggregated, if the object explicitly implements IMarshal, or if its ICustomQI returns @@ -2351,8 +2040,8 @@ void ComCallWrapper::Cleanup() LONGLONG llRefCount = m_pSimpleWrapper->GetRealRefCount(); LOG((LF_INTEROP, LL_INFO100, - "Calling ComCallWrapper::Cleanup on CCW 0x%p. cbRef = 0x%x, cbJupiterRef = 0x%x, IsPegged = %d, GlobalPeggingFlag = %d\n", - this, GET_COM_REF(llRefCount), GET_JUPITER_REF(llRefCount), IsPegged(), RCWWalker::IsGlobalPeggingOn())); + "Calling ComCallWrapper::Cleanup on CCW 0x%p. cbRef = 0x%x\n", + this, GET_COM_REF(llRefCount))); if (GET_COM_REF(llRefCount) != 0) { @@ -2365,30 +2054,6 @@ void ComCallWrapper::Cleanup() return; } - // If COMRef == 0 && JupiterRef > 0 && !Neutered - if ((GET_JUPITER_REF(llRefCount)) != 0 && - (llRefCount & SimpleComCallWrapper::CLEANUP_SENTINEL) == 0) - { - LOG((LF_INTEROP, LL_INFO100, "Neutering ComCallWrapper 0x%p: COM Ref = 0 but Jupiter Ref > 0\n", this)); - - // - // AppX ONLY: - // - // Skip cleaning up the handle on the CCW to avoid QueryInterface_ICCW crashing when - // accessing the handle, otherwise we could run into a race where the CCW is being neutered - // and has set m_ppThis to NULL before it sets the 'neutered' bit. - // - // It is only safe to do so under AppX because there are no AppDomains in AppX so there is - // no need to cleanup the handle immediately - // - // We'll clean up the handle later when Jupiter release the final ref - // - bool fSkipHandleCleanup = AppX::IsAppXProcess(); - m_pSimpleWrapper->Neuter(fSkipHandleCleanup); - - return; - } - STRESS_LOG1 (LF_INTEROP, LL_INFO100, "Cleaning up CCW 0x%p\n", this); // Retrieve the COM call wrapper cache before we clear anything @@ -2893,7 +2558,7 @@ static MethodTable *FindCovariantSubtype(MethodTable *pMT, REFIID riid) { // The internal base classes do not have guid. Skip them to avoid confusing exception being // thrown and swallowed inside GetGuidNoThrow. - if (thBaseClass != TypeHandle(g_pBaseCOMObject) && thBaseClass != TypeHandle(g_pBaseRuntimeClass)) + if (thBaseClass != TypeHandle(g_pBaseCOMObject)) { Instantiation newInst(&thBaseClass, 1); MethodTable *pItfMT = TypeHandle(pMT).Instantiate(newInst).AsMethodTable(); @@ -3023,159 +2688,6 @@ static IUnknown *GetComIPFromCCW_VariantInterface( RETURN ComCallWrapper::GetComIPFromCCW(pWrap->GetSimpleWrapper()->GetClassWrapper(), riid, pIntfMT, flags); } -// Like GetComIPFromCCW, but will try to find riid/pIntfMT among interfaces implemented by this -// object that have variance. Assumes that call GetComIPFromCCW with same arguments has failed. -static IUnknown* GetComIPFromCCW_UsingVariance(ComCallWrapper *pWrap, REFIID riid, MethodTable* pIntfMT, GetComIPFromCCW::flags flags) -{ - CONTRACTL - { - THROWS; - GC_TRIGGERS; - MODE_ANY; - PRECONDITION(CheckPointer(pWrap)); - PRECONDITION(pWrap->GetComCallWrapperTemplate()->SupportsVariantInterface()); - PRECONDITION(!pWrap->GetComCallWrapperTemplate()->RepresentsVariantInterface()); - } - CONTRACTL_END; - - // try the fast per-ComCallWrapperTemplate cache first - ComCallWrapperTemplate::IIDToInterfaceTemplateCache *pCache = pWrap->GetComCallWrapperTemplate()->GetOrCreateIIDToInterfaceTemplateCache(); - - GUID local_iid; - const IID *piid = &riid; - if (InlineIsEqualGUID(riid, GUID_NULL)) - { - // we have a fast IID -> ComCallWrapperTemplate cache so we need the IID first - _ASSERTE(pIntfMT != NULL); - - if (FAILED(pIntfMT->GetGuidNoThrow(&local_iid, TRUE))) - { - return NULL; - } - piid = &local_iid; - } - - ComCallWrapperTemplate *pIntfTemplate = NULL; - if (pCache->LookupInterfaceTemplate(*piid, &pIntfTemplate)) - { - // we've seen a QI for this IID before - if (pIntfTemplate == NULL) - { - // and it failed, so we can return immediately - return NULL; - } - - // make sure we pick up the MT stored in the ComMT because that's the WinRT one (for example - // IIterable) against which GetComIPFromCCW_VariantInterface is comparing its MT argument - _ASSERTE(pIntfMT == NULL || pIntfMT == pIntfTemplate->GetComMTForIndex(0)->GetMethodTable()); - pIntfMT = pIntfTemplate->GetComMTForIndex(0)->GetMethodTable(); - } - else if (pIntfMT == NULL) - { - _ASSERTE(riid != GUID_NULL); - - // Here we are, handling a QI for an IID that we don't recognize because the managed object we are wrapping - // does not implement that exact interface. However, it may implement another interface which is castable to - // what we are looking for via co- or contra-variance. The problem is that the IID computation algorithm is - // a one-way function so there's no way to deduce the interface while knowing only the IID. - - // try the AD-wide cache - pIntfMT = GetAppDomain()->LookupTypeByGuid(riid); - - if (pIntfMT == NULL) - { - // Now we should enumerate all types that are "related" to our object and try to find a match. This has - // a couple of issues. It can take a long time (imagine a type with n covariant generic parameters and - // us holding a type where these are instantantiated with classes, each with a hierarchy m levels deep - // - we are looking at loading m^n instantiations which may not be feasible and would make QI too slow). - // And it will not work for contravariance anyway (it's not quite possible to enumerate all subtypes of - // a given generic argument). - // - // We'll perform a simplified check which is limited only to covariance with one generic parameter (luckily - // all WinRT variant types currently fall into this bucket). - // - TypeHandle thClass = pWrap->GetComCallWrapperTemplate()->GetClassType(); - - ComCallWrapperTemplate::CCWInterfaceMapIterator it(thClass, NULL, false); - while (it.Next()) - { - MethodTable *pImplementedIntfMT = it.GetInterface(); - if (pImplementedIntfMT->HasVariance()) - { - pIntfMT = FindCovariantSubtype(pImplementedIntfMT, riid); - if (pIntfMT != NULL) - break; - } - } - } - } - - if (pIntfMT == NULL || !pIntfMT->IsInterface()) - { - // we did not recognize the IID - cache the negative result - pCache->InsertInterfaceTemplate(*piid, NULL); - } - else - { - if (pIntfTemplate == NULL) - { - // if we have an interface type but not the corresponding template so we have to do some extra work - MethodTable *pVariantIntfMT = NULL; - if (!pIntfMT->HasVariance()) - { - // We may be passed a WinRT interface which does not have variance from .NET type system - // point of view. Simply replace it with the corresponding .NET type if it is the case. - pVariantIntfMT = RCW::GetVariantMethodTable(pIntfMT); - } - else - { - pVariantIntfMT = pIntfMT; - } - - TypeHandle thClass = pWrap->GetComCallWrapperTemplate()->GetClassType(); - if (pVariantIntfMT != NULL && thClass.CanCastTo(pVariantIntfMT)) - { - _ASSERTE_MSG(!thClass.GetMethodTable()->ImplementsInterface(pVariantIntfMT), "This should have been taken care of by GetComIPFromCCW"); - - // At this point, conceptually we would like to add a new ComMethodTable to the ComCallWrapperTemplate - // representing pMT because we just discovered an interface that the unmanaged side is interested in. - // However, this does not fit very well to the overall CCW architecture and could use a lot of memory - // (each class that implements IEnumerable may end up with a ComMethodTable for IEnumerable - // for example) so we sacrifice a bit of run-time perf for this not-so-mainline scenario and create a - // CCW specifically for IEnumerable that is shared by all CCWs. - - // get the per-interface CCW template for pIntfMT - pIntfTemplate = ComCallWrapperTemplate::GetTemplate(pVariantIntfMT); - } - - // cache the pIntfTemplate (may be NULL) - pCache->InsertInterfaceTemplate(*piid, pIntfTemplate); - } - - if (pIntfTemplate != NULL) - { - // get a CCW for the template, associated with our object - CCWHolder pCCW; - { - GCX_COOP(); - OBJECTREF oref = NULL; - - GCPROTECT_BEGIN(oref); - { - oref = pWrap->GetObjectRef(); - pCCW = ComCallWrapper::InlineGetWrapper(&oref, pIntfTemplate, pWrap); - } - GCPROTECT_END(); - } - - // and let the per-interface CCW handle the QI - return GetComIPFromCCW_VariantInterface(pCCW, riid, pIntfMT, flags, pIntfTemplate); - } - } - - return NULL; -} - static IUnknown * GetComIPFromCCW_HandleExtendsCOMObject( ComCallWrapper * pWrap, REFIID riid, @@ -3197,39 +2709,28 @@ static IUnknown * GetComIPFromCCW_HandleExtendsCOMObject( if (imapIndex != -1) { MethodTable * pMT = pWrap->GetMethodTableOfObjectRef(); + MethodTable::InterfaceMapIterator intIt = pMT->IterateInterfaceMapFrom(intfIndex); - // Check if this index is actually an interface implemented by us - // if it belongs to the base COM object then we can hand over the call - // to it - if (pMT->IsWinRTObjectType()) + // If the number of slots is 0, then no need to proceed + if (intIt.GetInterface()->GetNumVirtuals() != 0) { - bDelegateToBase = pTemplate->GetComMTForIndex(intfIndex)->IsWinRTTrivialAggregate(); - } - else - { - MethodTable::InterfaceMapIterator intIt = pMT->IterateInterfaceMapFrom(intfIndex); - - // If the number of slots is 0, then no need to proceed - if (intIt.GetInterface()->GetNumVirtuals() != 0) - { - MethodDesc *pClsMD = NULL; + MethodDesc *pClsMD = NULL; - // Find the implementation for the first slot of the interface - DispatchSlot impl(pMT->FindDispatchSlot(intIt.GetInterface()->GetTypeID(), 0, FALSE /* throwOnConflict */)); - CONSISTENCY_CHECK(!impl.IsNull()); + // Find the implementation for the first slot of the interface + DispatchSlot impl(pMT->FindDispatchSlot(intIt.GetInterface()->GetTypeID(), 0, FALSE /* throwOnConflict */)); + CONSISTENCY_CHECK(!impl.IsNull()); - // Get the MethodDesc for this slot in the class - pClsMD = impl.GetMethodDesc(); + // Get the MethodDesc for this slot in the class + pClsMD = impl.GetMethodDesc(); - MethodTable * pClsMT = pClsMD->GetMethodTable(); - bDelegateToBase = (pClsMT->IsInterface() || pClsMT->IsComImport()) ? TRUE : FALSE; - } - else - { - // The interface has no methods so we cannot override it. Because of this - // it makes sense to delegate to the base COM component. - bDelegateToBase = TRUE; - } + MethodTable * pClsMT = pClsMD->GetMethodTable(); + bDelegateToBase = (pClsMT->IsInterface() || pClsMT->IsComImport()) ? TRUE : FALSE; + } + else + { + // The interface has no methods so we cannot override it. Because of this + // it makes sense to delegate to the base COM component. + bDelegateToBase = TRUE; } } @@ -3280,10 +2781,9 @@ static IUnknown * GetComIPFromCCW_ForIID_Worker( if (IsIClassX(pMT, riid, &pIntfComMT)) { // If the class that this IClassX's was generated for is marked - // as ClassInterfaceType.AutoDual or AutoDisp, or it is a WinRT - // delegate, then give out the IClassX IP. - if (pIntfComMT->GetClassInterfaceType() == clsIfAutoDual || pIntfComMT->GetClassInterfaceType() == clsIfAutoDisp || - pIntfComMT->IsWinRTDelegate()) + // as ClassInterfaceType.AutoDual or AutoDisp, + // then give out the IClassX IP. + if (pIntfComMT->GetClassInterfaceType() == clsIfAutoDual || pIntfComMT->GetClassInterfaceType() == clsIfAutoDisp) { // Make sure the all the base classes of the class this IClassX corresponds to // are visible to COM. @@ -3316,8 +2816,8 @@ static IUnknown *GetComIPFromCCW_ForIntfMT_Worker(ComCallWrapper *pWrap, MethodT // class method table if (pMT->CanCastToClass(pIntfMT)) { - // Make sure we're not trying to pass out a generic-based class interface (except for WinRT delegates) - if (pMT->HasInstantiation() && !pMT->SupportsGenericInterop(TypeHandle::Interop_NativeToManaged)) + // Make sure we're not trying to pass out a generic-based class interface + if (pMT->HasInstantiation()) { COMPlusThrow(kInvalidOperationException, IDS_EE_ATTEMPT_TO_CREATE_GENERIC_CCW); } @@ -3329,10 +2829,9 @@ static IUnknown *GetComIPFromCCW_ForIntfMT_Worker(ComCallWrapper *pWrap, MethodT ComMethodTable * pIntfComMT = pIntfCCWTemplate->GetClassComMT(); // If the class that this IClassX's was generated for is marked - // as ClassInterfaceType.AutoDual or AutoDisp, or it is a WinRT - // delegate, then give out the IClassX IP. - if (pIntfComMT->GetClassInterfaceType() == clsIfAutoDual || pIntfComMT->GetClassInterfaceType() == clsIfAutoDisp || - pIntfComMT->IsWinRTDelegate()) + // as ClassInterfaceType.AutoDual or AutoDisp, + // then give out the IClassX IP. + if (pIntfComMT->GetClassInterfaceType() == clsIfAutoDual || pIntfComMT->GetClassInterfaceType() == clsIfAutoDisp) { // Make sure the all the base classes of the class this IClassX corresponds to // are visible to COM. @@ -3448,7 +2947,7 @@ IUnknown* ComCallWrapper::GetComIPFromCCW(ComCallWrapper *pWrap, REFIID riid, Me if (IsIErrorInfo(riid) && AppX::IsAppXProcess()) { // Don't let the user override the default IErrorInfo implementation in AppX because - // Jupiter uses it for WER. See code:GetExceptionDescription for details. + // the AppX app model uses it for WER. See code:GetExceptionDescription for details. SimpleComCallWrapper* pSimpleWrap = pWrap->GetSimpleWrapper(); RETURN pSimpleWrap->QIStandardInterface(enum_IErrorInfo); } @@ -3463,12 +2962,6 @@ IUnknown* ComCallWrapper::GetComIPFromCCW(ComCallWrapper *pWrap, REFIID riid, Me RETURN pUnkCustomQIResult; } - if (IsIInspectable(riid)) - { - // ICustomPropertyProvider will be the cannonical IInspectable for every managed object - SimpleComCallWrapper* pSimpleWrap = pWrap->GetSimpleWrapper(); - RETURN pSimpleWrap->QIStandardInterface(enum_ICustomPropertyProvider); - } if (IsIDispatch(riid)) { if (AppX::IsAppXProcess()) @@ -3534,9 +3027,9 @@ IUnknown* ComCallWrapper::GetComIPFromCCW(ComCallWrapper *pWrap, REFIID riid, Me unsigned intfIndex = imapIndex; if (imapIndex != -1) { - // We don't support QI calls for non-WinRT interfaces that have generic arguments. + // We don't support QI calls for interfaces that have generic arguments. _ASSERTE(pIntfMT != NULL); - if (pIntfMT->HasInstantiation() && !pIntfMT->SupportsGenericInterop(TypeHandle::Interop_NativeToManaged, MethodTable::modeProjected)) + if (pIntfMT->HasInstantiation()) { COMPlusThrow(kInvalidOperationException, IDS_EE_ATTEMPT_TO_CREATE_GENERIC_CCW); } @@ -3550,22 +3043,9 @@ IUnknown* ComCallWrapper::GetComIPFromCCW(ComCallWrapper *pWrap, REFIID riid, Me // and one slot for the basic vtable pointer. imapIndex += Slot_FirstInterface; } - else if (pTemplate->SupportsVariantInterface()) - { - // We haven't found an interface corresponding to the incoming pIntfMT/IID because we don't implement it. - // However, we could still implement an interface that is castable to pIntfMT/IID via co-/contra-variance. - IUnknown * pIntf = GetComIPFromCCW_UsingVariance(pWrap, riid, pIntfMT, flags); - if (pIntf != NULL) - { - RETURN pIntf; - } - } // COM plus objects that extend from COM objects are special - // If we're being asked for just an IInspectable, we don't need to do this (we may be in the process - // of activating our aggregated object so can't use the RCW yet) - this is analagous to how IUnkown is handled - // specially with GetBasicIP at the top of this function. - if (pWrap->IsExtendsCOMObject() && !IsEqualGUID(riid, IID_IInspectable)) + if (pWrap->IsExtendsCOMObject()) { IUnknown * pIntf = GetComIPFromCCW_HandleExtendsCOMObject(pWrap, riid, pIntfMT, pTemplate, imapIndex, intfIndex); @@ -3588,16 +3068,7 @@ IUnknown* ComCallWrapper::GetComIPFromCCW(ComCallWrapper *pWrap, REFIID riid, Me ComMethodTable *pItfComMT = ComMethodTable::ComMethodTableFromIP((IUnknown*)ppVtable); if (!pItfComMT->IsLayoutComplete()) { - MethodTable *pClassMT; - if (pItfComMT->IsWinRTFactoryInterface() || pItfComMT->IsWinRTStaticInterface()) - { - // use the runtime class instead of the factory class - pClassMT = pTemplate->GetWinRTRuntimeClass(); - } - else - { - pClassMT = pTemplate->GetClassType().GetMethodTable(); - } + MethodTable *pClassMT = pTemplate->GetClassType().GetMethodTable(); if (!pItfComMT->LayOutInterfaceMethodTable(pClassMT)) RETURN NULL; } @@ -3646,7 +3117,6 @@ IDispatch* ComCallWrapper::GetIDispatchIP() MethodTable* pMT = pSimpleWrap->GetMethodTable(); // Retrieve the type of the default interface for the class. - // WinRT types always has DefaultInterfaceType_IUnknown and therefore won't support IDispatch TypeHandle hndDefItfClass; DefaultInterfaceType DefItfType = GetDefaultInterfaceForClassWrapper(TypeHandle(pMT), &hndDefItfClass); @@ -3659,7 +3129,6 @@ IDispatch* ComCallWrapper::GetIDispatchIP() } // If the class implements IReflect then use the IDispatchEx implementation. - // WinRT objects cannot implement IReflect as WinMDExp doesn't support exporting non-WinRT interfaces if (SimpleComCallWrapper::SupportsIReflect(pMT)) { // The class implements IReflect so lets let it handle IDispatch calls. @@ -3941,13 +3410,6 @@ void ComMethodTable::LayOutClassMethodTable() } CONTRACTL_END; - if (IsWinRTDelegate()) - { - // IClassX for WinRT delegates is a special interface - LayOutDelegateMethodTable(); - return; - } - GCX_PREEMP(); unsigned i; @@ -4439,15 +3901,6 @@ BOOL ComMethodTable::LayOutInterfaceMethodTable(MethodTable* pClsMT) pDispVtable->m_Invoke = (SLOT)Dispatch_Invoke_Wrapper; } } - else if (ItfType == ifInspectable) - { - // Setup the IInspectable vtable. - IInspectableVtable *pInspVtable = (IInspectableVtable *)pUnkVtable; - - pInspVtable->m_GetIIDs = (SLOT)Inspectable_GetIIDs_Wrapper; - pInspVtable->m_GetRuntimeClassName = (SLOT)Inspectable_GetRuntimeClassName_Wrapper; - pInspVtable->m_GetTrustLevel = (SLOT)Inspectable_GetTrustLevel_Wrapper; - } ArrayList NewCOMMethodDescs; ComCallMethodDescArrayHolder NewCOMMethodDescsHolder(&NewCOMMethodDescs); @@ -4472,28 +3925,7 @@ BOOL ComMethodTable::LayOutInterfaceMethodTable(MethodTable* pClsMT) } MethodDesc *pClassMD = NULL; - if (IsWinRTFactoryInterface()) - { - // lookup the .ctor corresponding this factory interface method - pClassMD = ComCall::GetCtorForWinRTFactoryMethod(pClsMT, pIntfMD); - _ASSERTE(pClassMD->IsCtor()); - } - else if (IsWinRTStaticInterface()) - { - // lookup the static method corresponding this factory interface method - pClassMD = ComCall::GetStaticForWinRTFactoryMethod(pClsMT, pIntfMD); - _ASSERTE(pClassMD->IsStatic()); - } - else if (IsWinRTRedirectedInterface()) - { - pClassMD = WinRTInterfaceRedirector::GetStubMethodForRedirectedInterface( - GetWinRTRedirectedInterfaceIndex(), - i, - TypeHandle::Interop_NativeToManaged, - FALSE, - m_pMT->GetInstantiation()); - } - else if (pClsMT != NULL) + if (pClsMT != NULL) { DispatchSlot impl(pClsMT->FindDispatchSlotForInterfaceMD(pIntfMD, FALSE /* throwOnConflict */)); pClassMD = impl.GetMethodDesc(); @@ -4501,15 +3933,12 @@ BOOL ComMethodTable::LayOutInterfaceMethodTable(MethodTable* pClsMT) if (pClassMD != NULL) { - pNewMD->InitMethod(pClassMD, pIntfMD, IsWinRTRedirectedInterface()); + pNewMD->InitMethod(pClassMD, pIntfMD); } else { // we will perform interface dispatch at run-time - // note that even in fully statically typed WinRT, we don't always have an implementation - // MethodDesc in the hierarchy because our metadata adapter does not make these up for - // redirected interfaces - pNewMD->InitMethod(pIntfMD, NULL, IsWinRTRedirectedInterface()); + pNewMD->InitMethod(pIntfMD, NULL); } pMethodDescMemory += (COMMETHOD_PREPAD + sizeof(ComCallMethodDesc)); @@ -4638,134 +4067,6 @@ void ComMethodTable::LayOutBasicMethodTable() } //-------------------------------------------------------------------------- -// Lay out a ComMethodTable that represents a WinRT delegate interface. -//-------------------------------------------------------------------------- -void ComMethodTable::LayOutDelegateMethodTable() -{ - CONTRACTL - { - THROWS; - GC_TRIGGERS; - MODE_ANY; - PRECONDITION(IsWinRTDelegate()); - } - CONTRACTL_END; - - GCX_PREEMP(); - - MethodTable *pDelegateMT = m_pMT; - ULONG cbExtraSlots = GetNumExtraSlots(ifVtable); - - BYTE *pMethodDescMemory = NULL; - IUnkVtable* pUnkVtable; - SLOT *pComVtable; - - // If this is a redirected delegate, then we need to get its WinRT ABI definition type - WinMDAdapter::RedirectedTypeIndex index = static_cast(0); - if (WinRTDelegateRedirector::ResolveRedirectedDelegate(pDelegateMT, &index)) - { - pDelegateMT = WinRTDelegateRedirector::GetWinRTTypeForRedirectedDelegateIndex(index); - - if (m_pMT->HasInstantiation()) - { - pDelegateMT = TypeHandle(pDelegateMT).Instantiate(m_pMT->GetInstantiation()).AsMethodTable(); - } - } - - LOG((LF_INTEROP, LL_INFO1000, "LayOutDelegateMethodTable: %s, this: %p\n", pDelegateMT->GetDebugClassName(), this)); - - unsigned cbSlots = 1; // one slot for the Invoke method - - // - // Allocate a temporary space to generate the vtable into. - // - S_UINT32 cbTempVtable = (S_UINT32(m_cbSlots) + S_UINT32(cbExtraSlots)) * S_UINT32(sizeof(SLOT)); - cbTempVtable += S_UINT32(cbSlots) * S_UINT32((COMMETHOD_PREPAD + sizeof(ComCallMethodDesc))); - - if (cbTempVtable.IsOverflow()) - ThrowHR(COR_E_OVERFLOW); - - NewArrayHolder pTempVtable = new BYTE[cbTempVtable.Value()]; - - pUnkVtable = (IUnkVtable *)pTempVtable.GetValue(); - pComVtable = ((SLOT*)pUnkVtable) + cbExtraSlots; - - // Method descs are at the end of the vtable - // m_cbSlots interfaces methods + IUnk methods - pMethodDescMemory = (BYTE *)&pComVtable[m_cbSlots]; - - // Setup IUnk vtable - pUnkVtable->m_qi = (SLOT)Unknown_QueryInterface; - pUnkVtable->m_addref = (SLOT)Unknown_AddRef; - pUnkVtable->m_release = (SLOT)Unknown_Release; - - // Some space for a CALL xx xx xx xx stub is reserved before the beginning of the MethodDesc - ComCallMethodDescHolder NewMDHolder = (ComCallMethodDesc *) (pMethodDescMemory + COMMETHOD_PREPAD); - MethodDesc* pInvokeMD = ((DelegateEEClass *)(pDelegateMT->GetClass()))->GetInvokeMethod(); - - if (pInvokeMD->IsSharedByGenericInstantiations()) - { - // we need an exact MD to represent the call - pInvokeMD = InstantiatedMethodDesc::FindOrCreateExactClassMethod(pDelegateMT, pInvokeMD); - } - - NewMDHolder.GetValue()->InitMethod(pInvokeMD, NULL); - _ASSERTE(cbSlots == 1); - - { - // Take the lock and copy data from the temporary vtable to this instance - CrstHolder ch(&g_CreateWrapperTemplateCrst); - - if (IsLayoutComplete()) - return; - - // IUnk vtable follows the header - CopyMemory(this + 1, pUnkVtable, cbTempVtable.Value()); - - // Finish by emitting stubs and initializing the slots - pUnkVtable = (IUnkVtable *)(this + 1); - pComVtable = ((SLOT *)pUnkVtable) + cbExtraSlots; - - // Method descs are at the end of the vtable - // m_cbSlots delegate methods + IUnk methods - pMethodDescMemory = (BYTE *)&pComVtable[m_cbSlots]; - - ComCallMethodDesc* pNewMD = (ComCallMethodDesc *) (pMethodDescMemory + COMMETHOD_PREPAD); - emitCOMStubCall(pNewMD, GetEEFuncEntryPoint(ComCallPreStub)); - - FillInComVtableSlot(pComVtable, 0, pNewMD); - _ASSERTE(cbSlots == 1); - - // Set the layout complete flag and release the lock. - m_Flags |= enum_LayoutComplete; - NewMDHolder.SuppressRelease(); - } - -#ifdef PROFILING_SUPPORTED - // Notify profiler of the CCW, so it can avoid double-counting. - { - BEGIN_PIN_PROFILER(CORProfilerTrackCCW()); -#if defined(_DEBUG) - WCHAR rIID[40]; // {00000000-0000-0000-0000-000000000000} - GuidToLPWSTR(m_IID, rIID, lengthof(rIID)); - LOG((LF_CORPROF, LL_INFO100, "COMClassicVTableCreated Class:%hs, IID:%ls, vTbl:%#08x\n", - pDelegateMT->GetDebugClassName(), rIID, pUnkVtable)); -#else - LOG((LF_CORPROF, LL_INFO100, "COMClassicVTableCreated Class:%#x, IID:{%08x-...}, vTbl:%#08x\n", - pDelegateMT, m_IID.Data1, pUnkVtable)); -#endif - g_profControlBlock.pProfInterface->COMClassicVTableCreated((ClassID) TypeHandle(pDelegateMT).AsPtr(), - m_IID, - pUnkVtable, - m_cbSlots+cbExtraSlots); - END_PIN_PROFILER(); - } -#endif // PROFILING_SUPPORTED - - LOG((LF_INTEROP, LL_INFO1000, "LayOutDelegateMethodTable: %s, this: %p [DONE]\n", pDelegateMT->GetDebugClassName(), this)); -} - -//-------------------------------------------------------------------------- // Retrieves the DispatchInfo associated with the COM method table. If // the DispatchInfo has not been initialized yet then it is initilized. //-------------------------------------------------------------------------- @@ -4934,7 +4235,7 @@ void ComCallWrapperTemplate::IIDToInterfaceTemplateCache::InsertInterfaceTemplat //--------------------------------------------------------- // ComCallWrapperTemplate::CCWInterfaceMapIterator //--------------------------------------------------------- -ComCallWrapperTemplate::CCWInterfaceMapIterator::CCWInterfaceMapIterator(TypeHandle thClass, WinRTManagedClassFactory *pClsFact, bool fIterateRedirectedInterfaces) +ComCallWrapperTemplate::CCWInterfaceMapIterator::CCWInterfaceMapIterator(TypeHandle thClass) { CONTRACTL { @@ -4952,86 +4253,14 @@ ComCallWrapperTemplate::CCWInterfaceMapIterator::CCWInterfaceMapIterator(TypeHan while (it.Next()) { MethodTable *pItfMT = it.GetInterface(); - AppendInterface(pItfMT, false); - - if (fIterateRedirectedInterfaces && WinRTSupported()) - { - WinMDAdapter::RedirectedTypeIndex redirectedIndex; - if (WinRTInterfaceRedirector::ResolveRedirectedInterface(pItfMT, &redirectedIndex) && pItfMT->IsLegalNonArrayWinRTType()) - { - MethodTable *pWinRTItfMT = WinRTInterfaceRedirector::GetWinRTTypeForRedirectedInterfaceIndex(redirectedIndex); - if (pItfMT->HasInstantiation()) - { - _ASSERTE(pWinRTItfMT->HasInstantiation()); - pWinRTItfMT = TypeHandle(pWinRTItfMT).Instantiate(pItfMT->GetInstantiation()).GetMethodTable(); - } - - AppendInterface(pWinRTItfMT, true).m_RedirectedIndex = redirectedIndex; - } - } - } - - // handle single dimensional arrays - if (WinRTSupported() && thClass.IsArray() && !pMT->IsMultiDimArray()) - { - // We treat arrays as if they implemented IIterable, IVector, and IVectorView (WinRT only) - TypeHandle thGenArg = thClass.GetArrayElementTypeHandle(); - Instantiation inst(&thGenArg, 1); - - BinderClassID id = (fIterateRedirectedInterfaces ? CLASS__IITERABLE : CLASS__IENUMERABLEGENERIC); - MethodTable *pWinRTItfMT = TypeHandle(MscorlibBinder::GetClass(id)).Instantiate(inst).AsMethodTable(); - - // if this IIterable/IEnumerable is an invalid WinRT type, skip it, so that the ComCallWrapperTemplate is still usable - if (pWinRTItfMT->IsLegalNonArrayWinRTType()) - { - // append IIterable/IEnumerable - AppendInterface(pWinRTItfMT, fIterateRedirectedInterfaces).m_RedirectedIndex = WinMDAdapter::RedirectedTypeIndex_System_Collections_Generic_IEnumerable; - - // append IVector/IList - id = (fIterateRedirectedInterfaces ? CLASS__IVECTOR : CLASS__ILISTGENERIC); - pWinRTItfMT = TypeHandle(MscorlibBinder::GetClass(id)).Instantiate(inst).AsMethodTable(); - _ASSERTE(pWinRTItfMT->IsLegalNonArrayWinRTType()); - - AppendInterface(pWinRTItfMT, fIterateRedirectedInterfaces).m_RedirectedIndex = WinMDAdapter::RedirectedTypeIndex_System_Collections_Generic_IList; - - // append IVectorView/IReadOnlyList - id = (fIterateRedirectedInterfaces ? CLASS__IVECTORVIEW : CLASS__IREADONLYLISTGENERIC); - pWinRTItfMT = TypeHandle(MscorlibBinder::GetClass(id)).Instantiate(inst).AsMethodTable(); - _ASSERTE(pWinRTItfMT->IsLegalNonArrayWinRTType()); - - AppendInterface(pWinRTItfMT, fIterateRedirectedInterfaces).m_RedirectedIndex = WinMDAdapter::RedirectedTypeIndex_System_Collections_Generic_IReadOnlyList; - } - } - - // add factory and static interfaces - if (pClsFact != NULL) - { - SArray *pExtraInterfaces = pClsFact->GetFactoryInterfaces(); - if (pExtraInterfaces != NULL) - { - COUNT_T NumInterfaces = pExtraInterfaces->GetCount(); - for (COUNT_T i = 0; i < NumInterfaces; i++) - { - AppendInterface((*pExtraInterfaces)[i], false).m_dwIsFactoryInterface = true; - } - } - - pExtraInterfaces = pClsFact->GetStaticInterfaces(); - if (pExtraInterfaces != NULL) - { - COUNT_T NumInterfaces = pExtraInterfaces->GetCount(); - for (COUNT_T i = 0; i < NumInterfaces; i++) - { - AppendInterface((*pExtraInterfaces)[i], false).m_dwIsStaticInterface = true; - } - } + AppendInterface(pItfMT); } Reset(); } // Append a new interface to the m_Interfaces array. -ComCallWrapperTemplate::CCWInterfaceMapIterator::InterfaceProps &ComCallWrapperTemplate::CCWInterfaceMapIterator::AppendInterface(MethodTable *pItfMT, bool isRedirected) +ComCallWrapperTemplate::CCWInterfaceMapIterator::InterfaceProps &ComCallWrapperTemplate::CCWInterfaceMapIterator::AppendInterface(MethodTable *pItfMT) { CONTRACTL { @@ -5044,10 +4273,6 @@ ComCallWrapperTemplate::CCWInterfaceMapIterator::InterfaceProps &ComCallWrapperT InterfaceProps &props = *m_Interfaces.Append(); props.m_pItfMT = pItfMT; - props.m_RedirectedIndex = (WinMDAdapter::RedirectedTypeIndex)-1; - props.m_dwIsRedirectedInterface = isRedirected; - props.m_dwIsFactoryInterface = false; - props.m_dwIsStaticInterface = false; return props; } @@ -5158,16 +4383,7 @@ ComMethodTable* ComCallWrapperTemplate::GetClassComMT() MethodTable *pMT = m_thClass.GetMethodTable(); // We haven't set it up yet, generate one. - ComMethodTable* pClassComMT; - if (pMT->IsDelegate() && (pMT->IsProjectedFromWinRT() || WinRTTypeNameConverter::IsRedirectedType(pMT))) - { - // WinRT delegates have a special class vtable - pClassComMT = CreateComMethodTableForDelegate(pMT); - } - else - { - pClassComMT = CreateComMethodTableForClass(pMT); - } + ComMethodTable* pClassComMT = CreateComMethodTableForClass(pMT); pClassComMT->AddRef(); // Cache it. @@ -5672,18 +4888,6 @@ ComMethodTable* ComCallWrapperTemplate::CreateComMethodTableForInterface(MethodT } #endif - MethodTable *pMT = m_thClass.GetMethodTable(); - MethodTable *pParentMT = pMT->GetParentMethodTable(); - if (pParentMT != NULL && pParentMT->IsProjectedFromWinRT()) - { - // Determine if this class has overriden any methods on the interface. If not, we'll - // set a flag so when a QI comes, we will return directly the base WinRT object. - if (pMT->HasSameInterfaceImplementationAsParent(pInterfaceMT, pParentMT)) - { - pComMT->m_Flags |= enum_IsWinRTTrivialAggregate; - } - } - LOG((LF_INTEROP, LL_INFO1000, "---------- end of CreateComMethodTableForInterface %s -----------\n", pItfClass->GetDebugClassName())); pComMT.SuppressRelease(); @@ -5798,19 +5002,9 @@ ComMethodTable* ComCallWrapperTemplate::CreateComMethodTableForDelegate(MethodTa pComMT->m_cbSlots = cbTotalSlots; // number of slots not counting IUnknown methods. // Set the flags. - pComMT->m_Flags = enum_ClassVtableMask | clsIfNone | enum_ComVisible | enum_IsWinRTDelegate; + pComMT->m_Flags = enum_ClassVtableMask | clsIfNone | enum_ComVisible; MethodTable *pMTForIID = pDelegateMT; - WinMDAdapter::RedirectedTypeIndex index = static_cast(0); - if (WinRTDelegateRedirector::ResolveRedirectedDelegate(pDelegateMT, &index)) - { - pMTForIID = WinRTDelegateRedirector::GetWinRTTypeForRedirectedDelegateIndex(index); - - if (pDelegateMT->HasInstantiation()) - { - pMTForIID = TypeHandle(pMTForIID).Instantiate(pDelegateMT->GetInstantiation()).AsMethodTable(); - } - } pMTForIID->GetGuid(&pComMT->m_IID, TRUE); pComMT->m_Flags |= enum_GuidGenerated; @@ -5849,25 +5043,12 @@ ComMethodTable *ComCallWrapperTemplate::InitializeForInterface(MethodTable *pPar pItfComMT = m_pParent->GetComMTForItf(pItfMT); if (pItfComMT != NULL) { - if (pItfComMT->IsWinRTTrivialAggregate()) - { - // if the parent COM MT is a trivial aggregate, we must verify that the same is true at this level - if (!m_thClass.GetMethodTable()->HasSameInterfaceImplementationAsParent(pItfMT, pParentMT)) - { - // the interface is implemented by parent but this class reimplemented/overrode - // its method(s) so we will need to build a new COM vtable for it - pItfComMT = NULL; - } - } - else + // if the parent COM MT is not a trivial aggregate, simple MethodTable slot check is enough + if (!m_thClass.GetMethodTable()->ImplementsInterfaceWithSameSlotsAsParent(pItfMT, pParentMT)) { - // if the parent COM MT is not a trivial aggregate, simple MethodTable slot check is enough - if (!m_thClass.GetMethodTable()->ImplementsInterfaceWithSameSlotsAsParent(pItfMT, pParentMT)) - { - // the interface is implemented by parent but this class reimplemented - // its method(s) so we will need to build a new COM vtable for it - pItfComMT = NULL; - } + // the interface is implemented by parent but this class reimplemented + // its method(s) so we will need to build a new COM vtable for it + pItfComMT = NULL; } } } @@ -5881,21 +5062,12 @@ ComMethodTable *ComCallWrapperTemplate::InitializeForInterface(MethodTable *pPar m_rgpIPtr[dwIndex] = (SLOT*)(pItfComMT + 1); pItfComMT->AddRef(); - if (pItfMT->HasVariance()) - { - m_flags |= enum_SupportsVariantInterface; - } - // update pItfMT in case code:CreateComMethodTableForInterface decided to redirect the interface pItfMT = pItfComMT->GetMethodTable(); if (pItfMT == MscorlibBinder::GetExistingClass(CLASS__ICUSTOM_QUERYINTERFACE)) { m_flags |= enum_ImplementsICustomQueryInterface; } - else if (pItfMT->GetComInterfaceType() == ifInspectable) - { - m_flags |= enum_SupportsIInspectable; - } else if (InlineIsEqualGUID(pItfComMT->GetIID(), IID_IMarshal)) { // detect IMarshal so we can handle IAgileObject in a backward compatible way @@ -5911,7 +5083,7 @@ ComMethodTable *ComCallWrapperTemplate::InitializeForInterface(MethodTable *pPar // create a template wrapper, which is cached in the class // used for initializing other wrappers for instances of the class //-------------------------------------------------------------------------- -ComCallWrapperTemplate* ComCallWrapperTemplate::CreateTemplate(TypeHandle thClass, WinRTManagedClassFactory *pClsFact /* = NULL */) +ComCallWrapperTemplate* ComCallWrapperTemplate::CreateTemplate(TypeHandle thClass) { CONTRACT (ComCallWrapperTemplate*) { @@ -5926,7 +5098,7 @@ ComCallWrapperTemplate* ComCallWrapperTemplate::CreateTemplate(TypeHandle thClas GCX_PREEMP(); - if (pClsFact == NULL && !thClass.IsTypeDesc() && !thClass.AsMethodTable()->HasCCWTemplate()) + if (!thClass.IsTypeDesc() && !thClass.AsMethodTable()->HasCCWTemplate()) { // Canonicalize the class type because we are going to stick the template pointer to EEClass. thClass = thClass.GetCanonicalMethodTable(); @@ -5946,7 +5118,7 @@ ComCallWrapperTemplate* ComCallWrapperTemplate::CreateTemplate(TypeHandle thClas } // Preload the policy for this interface - CCWInterfaceMapIterator it(thClass, pClsFact, true); + CCWInterfaceMapIterator it(thClass); // Num interfaces in the template. unsigned numInterfaces = it.GetCount(); @@ -5956,10 +5128,7 @@ ComCallWrapperTemplate* ComCallWrapperTemplate::CreateTemplate(TypeHandle thClas // Move this inside the scope so it is destroyed before its memory is. ComCallWrapperTemplateHolder pTemplate = NULL; - if (pClsFact != NULL) - pTemplate = pClsFact->GetComCallWrapperTemplate(); - else - pTemplate = thClass.GetComCallWrapperTemplate(); + pTemplate = thClass.GetComCallWrapperTemplate(); if (pTemplate) { @@ -5981,7 +5150,6 @@ ComCallWrapperTemplate* ComCallWrapperTemplate::CreateTemplate(TypeHandle thClas pTemplate->m_pClassComMT = NULL; // Defer setting this up. pTemplate->m_pBasicComMT = NULL; pTemplate->m_pDefaultItf = NULL; - pTemplate->m_pWinRTRuntimeClass = (pClsFact != NULL ? pClsFact->GetClass() : NULL); pTemplate->m_pICustomQueryInterfaceGetInterfaceMD = NULL; pTemplate->m_pIIDToInterfaceTemplateCache = NULL; pTemplate->m_flags = 0; @@ -5999,12 +5167,6 @@ ComCallWrapperTemplate* ComCallWrapperTemplate::CreateTemplate(TypeHandle thClas pTemplate->m_flags |= enum_SupportsIClassX; } - if (pMT->IsArray() && !pMT->IsMultiDimArray()) - { - // SZ arrays support covariant interfaces - pTemplate->m_flags |= enum_SupportsVariantInterface; - } - if (IsOleAutDispImplRequiredForClass(pMT)) { // Determine what IDispatch implementation this class should use @@ -6021,40 +5183,17 @@ ComCallWrapperTemplate* ComCallWrapperTemplate::CreateTemplate(TypeHandle thClas { MethodTable *pItfMT = it.GetInterface(); ComMethodTable *pItfComMT = pTemplate->InitializeForInterface(pParentMT, pItfMT, it.GetIndex()); - - if (it.IsRedirectedInterface()) - pItfComMT->SetWinRTRedirectedInterfaceIndex(it.GetRedirectedInterfaceIndex()); - else if (it.IsFactoryInterface()) - pItfComMT->SetIsWinRTFactoryInterface(); - else if (it.IsStaticInterface()) - pItfComMT->SetIsWinRTStaticInterface(); } - if (pClsFact != NULL) - { - // Cache the template in the class factory - if (!pClsFact->SetComCallWrapperTemplate(pTemplate)) - { - // another thread beat us to it - pTemplate = pClsFact->GetComCallWrapperTemplate(); - _ASSERTE(pTemplate != NULL); - - pTemplate.SuppressRelease(); - RETURN pTemplate; - } - } - else + // Cache the template in class. + if (!thClass.SetComCallWrapperTemplate(pTemplate)) { - // Cache the template in class. - if (!thClass.SetComCallWrapperTemplate(pTemplate)) - { - // another thread beat us to it - pTemplate = thClass.GetComCallWrapperTemplate(); - _ASSERTE(pTemplate != NULL); + // another thread beat us to it + pTemplate = thClass.GetComCallWrapperTemplate(); + _ASSERTE(pTemplate != NULL); - pTemplate.SuppressRelease(); - RETURN pTemplate; - } + pTemplate.SuppressRelease(); + RETURN pTemplate; } pTemplate.SuppressRelease(); @@ -6138,7 +5277,6 @@ ComCallWrapperTemplate *ComCallWrapperTemplate::CreateTemplateForInterface(Metho pTemplate->m_pClassComMT = NULL; pTemplate->m_pBasicComMT = NULL; pTemplate->m_pDefaultItf = pItfMT; - pTemplate->m_pWinRTRuntimeClass = NULL; pTemplate->m_pICustomQueryInterfaceGetInterfaceMD = NULL; pTemplate->m_pIIDToInterfaceTemplateCache = NULL; pTemplate->m_flags = enum_RepresentsVariantInterface; @@ -6146,20 +5284,7 @@ ComCallWrapperTemplate *ComCallWrapperTemplate::CreateTemplateForInterface(Metho // Initialize the one ComMethodTable ComMethodTable *pItfComMT; - WinMDAdapter::RedirectedTypeIndex redirectedInterfaceIndex; - if (WinRTInterfaceRedirector::ResolveRedirectedInterface(pItfMT, &redirectedInterfaceIndex)) - { - // pItfMT is redirected, initialize the ComMethodTable accordingly - MethodTable *pWinRTItfMT = WinRTInterfaceRedirector::GetWinRTTypeForRedirectedInterfaceIndex(redirectedInterfaceIndex); - pWinRTItfMT = TypeHandle(pWinRTItfMT).Instantiate(pItfMT->GetInstantiation()).GetMethodTable(); - - pItfComMT = pTemplate->InitializeForInterface(NULL, pWinRTItfMT, 0); - pItfComMT->SetWinRTRedirectedInterfaceIndex(redirectedInterfaceIndex); - } - else - { - pItfComMT = pTemplate->InitializeForInterface(NULL, pItfMT, 0); - } + pItfComMT = pTemplate->InitializeForInterface(NULL, pItfMT, 0); // Cache the template on the interface. if (!pItfMT->SetComCallWrapperTemplate(pTemplate)) diff --git a/src/coreclr/src/vm/comcallablewrapper.h b/src/coreclr/src/vm/comcallablewrapper.h index 9ef02ec..8c5fd42 100644 --- a/src/coreclr/src/vm/comcallablewrapper.h +++ b/src/coreclr/src/vm/comcallablewrapper.h @@ -23,7 +23,6 @@ #include "dispatchinfo.h" #include "wrappers.h" #include "internalunknownimpl.h" -#include "rcwwalker.h" #include "util.hpp" class CCacheLineAllocator; @@ -151,8 +150,6 @@ private: // //-------------------------------------------------------------------------------- -class WinRTManagedClassFactory; - //-------------------------------------------------------------------------------- // COM callable wrappers for CLR objects //-------------------------------------------------------------------------------- @@ -168,9 +165,7 @@ public: { enum { - // There is a small number of types that the class is castable to via variance and QI'ed for - // (typically just IFoo where the class implements IFoo and IFoo is covariant). - // There is also some number of IIDs QI'ed for by external code (e.g. Jupiter) that we won't + // There is also some number of IIDs QI'ed for by external code that we won't // recognize - this number is potentially unbounded so even if this was a different data // structure, we would want to limit its size. Simple sequentially searched array seems to // work the best both in terms of memory footprint and lookup performance. @@ -247,22 +242,13 @@ public: void InsertInterfaceTemplate(REFIID riid, ComCallWrapperTemplate *pTemplate); }; - // Iterates COM-exposed interfaces of a class. Handles arrays which support IIterable, - // IVector, and IVectorView, as well as WinRT class factories which support factory - // and static interfaces. It is also aware of redirected interfaces - both the .NET and the - // corresponding WinRT type are reported + // Iterates COM-exposed interfaces of a class. class CCWInterfaceMapIterator { private: struct InterfaceProps { MethodTable *m_pItfMT; - - WinMDAdapter::RedirectedTypeIndex m_RedirectedIndex; // valid if m_dwIsRedirectedInterface is set - - DWORD m_dwIsRedirectedInterface : 1; - DWORD m_dwIsFactoryInterface : 1; - DWORD m_dwIsStaticInterface : 1; }; StackSArray m_Interfaces; @@ -274,10 +260,10 @@ public: return m_Interfaces[(COUNT_T)m_Index]; } - InterfaceProps &AppendInterface(MethodTable *pItfMT, bool isRedirected); + InterfaceProps &AppendInterface(MethodTable *pItfMT); public: - CCWInterfaceMapIterator(TypeHandle thClass, WinRTManagedClassFactory *pClsFact, bool fIterateRedirectedInterfaces); + CCWInterfaceMapIterator(TypeHandle thClass); BOOL Next() { @@ -308,30 +294,6 @@ public: LIMITED_METHOD_CONTRACT; m_Index = (COUNT_T)-1; } - - BOOL IsFactoryInterface() const - { - LIMITED_METHOD_CONTRACT; - return GetCurrentInterfaceProps().m_dwIsFactoryInterface; - } - - BOOL IsStaticInterface() const - { - LIMITED_METHOD_CONTRACT; - return GetCurrentInterfaceProps().m_dwIsStaticInterface; - } - - BOOL IsRedirectedInterface() const - { - LIMITED_METHOD_CONTRACT; - return GetCurrentInterfaceProps().m_dwIsRedirectedInterface; - } - - WinMDAdapter::RedirectedTypeIndex GetRedirectedInterfaceIndex() const - { - LIMITED_METHOD_CONTRACT; - return GetCurrentInterfaceProps().m_RedirectedIndex; - } }; // Static initializer run at startup. @@ -376,18 +338,6 @@ public: return (m_flags & enum_ImplementsICustomQueryInterface); } - BOOL SupportsIInspectable() - { - LIMITED_METHOD_CONTRACT; - return (m_flags & enum_SupportsIInspectable); - } - - BOOL SupportsVariantInterface() - { - LIMITED_METHOD_CONTRACT; - return (m_flags & enum_SupportsVariantInterface); - } - BOOL RepresentsVariantInterface() { LIMITED_METHOD_CONTRACT; @@ -418,16 +368,10 @@ public: return m_thClass; } - MethodTable *GetWinRTRuntimeClass() - { - LIMITED_METHOD_CONTRACT; - return m_pWinRTRuntimeClass; - } - BOOL IsSafeTypeForMarshalling(); // Creates a new Template and caches it on the MethodTable or class factory. - static ComCallWrapperTemplate *CreateTemplate(TypeHandle thClass, WinRTManagedClassFactory *pClsFact = NULL); + static ComCallWrapperTemplate *CreateTemplate(TypeHandle thClass); // Creates a new Template for just one interface. Used for lazily created CCWs for interfaces with variance. static ComCallWrapperTemplate *CreateTemplateForInterface(MethodTable *pItfMT); @@ -457,7 +401,6 @@ private: ComCallWrapperTemplate* m_pParent; TypeHandle m_thClass; MethodTable* m_pDefaultItf; - MethodTable* m_pWinRTRuntimeClass; ComMethodTable* m_pClassComMT; ComMethodTable* m_pBasicComMT; @@ -469,10 +412,9 @@ private: enum_InvisibleParent = 0x20, enum_ImplementsICustomQueryInterface = 0x40, - enum_SupportsIInspectable = 0x80, + // enum_Unused = 0x80, enum_SupportsIClassX = 0x100, - enum_SupportsVariantInterface = 0x200, // this is a template for a class that implements an interface with variance enum_RepresentsVariantInterface = 0x400, // this is a template for an interface with variance enum_UseOleAutDispatchImpl = 0x800, // the class is decorated with IDispatchImplAttribute(CompatibleImpl) @@ -523,13 +465,6 @@ struct IDispatchVtable : IUnkVtable SLOT m_Invoke; }; -struct IInspectableVtable : IUnkVtable -{ - SLOT m_GetIIDs; - SLOT m_GetRuntimeClassName; - SLOT m_GetTrustLevel; -}; - enum Masks { enum_InterfaceTypeMask = 0x00000003, @@ -543,13 +478,11 @@ enum Masks enum_GuidGenerated = 0x00000400, // enum_unused = 0x00001000, enum_IsBasic = 0x00002000, - enum_IsWinRTDelegate = 0x00004000, - enum_IsWinRTTrivialAggregate = 0x00008000, - enum_IsWinRTFactoryInterface = 0x00010000, - enum_IsWinRTStaticInterface = 0x00020000, - enum_IsWinRTRedirectedInterface = 0x00040000, - - enum_WinRTRedirectedInterfaceMask = 0xFF000000, // the highest byte contains redirected interface index + // enum_unused = 0x00004000, + // enum_unused = 0x00008000, + // enum_unused = 0x00010000, + // enum_unused = 0x00020000, + // enum_unused = 0x00040000, }; typedef DPTR(struct ComMethodTable) PTR_ComMethodTable; @@ -565,7 +498,6 @@ struct ComMethodTable void LayOutClassMethodTable(); BOOL LayOutInterfaceMethodTable(MethodTable* pClsMT); void LayOutBasicMethodTable(); - void LayOutDelegateMethodTable(); // Accessor for the IDispatch information. DispatchInfo* GetDispatchInfo(); @@ -651,63 +583,6 @@ struct ComMethodTable return (m_Flags & enum_IsBasic) != 0; } - BOOL IsWinRTDelegate() - { - LIMITED_METHOD_CONTRACT; - return (m_Flags & enum_IsWinRTDelegate) != 0; - } - - BOOL IsWinRTTrivialAggregate() - { - LIMITED_METHOD_CONTRACT; - return (m_Flags & enum_IsWinRTTrivialAggregate) != 0; - } - - BOOL IsWinRTFactoryInterface() - { - LIMITED_METHOD_CONTRACT; - return (m_Flags & enum_IsWinRTFactoryInterface) != 0; - } - - BOOL IsWinRTStaticInterface() - { - LIMITED_METHOD_CONTRACT; - return (m_Flags & enum_IsWinRTStaticInterface) != 0; - } - - VOID SetIsWinRTFactoryInterface() - { - LIMITED_METHOD_CONTRACT; - m_Flags |= enum_IsWinRTFactoryInterface; - } - - VOID SetIsWinRTStaticInterface() - { - LIMITED_METHOD_CONTRACT; - m_Flags |= enum_IsWinRTStaticInterface; - } - - BOOL IsWinRTRedirectedInterface() - { - LIMITED_METHOD_CONTRACT; - return (m_Flags & enum_IsWinRTRedirectedInterface) != 0; - } - - WinMDAdapter::RedirectedTypeIndex GetWinRTRedirectedInterfaceIndex() - { - LIMITED_METHOD_CONTRACT; - return (WinMDAdapter::RedirectedTypeIndex)((m_Flags & enum_WinRTRedirectedInterfaceMask) >> 24); - } - - void SetWinRTRedirectedInterfaceIndex(WinMDAdapter::RedirectedTypeIndex index) - { - LIMITED_METHOD_CONTRACT; - - m_Flags |= ((size_t)index << 24); - m_Flags |= enum_IsWinRTRedirectedInterface; - _ASSERTE(GetWinRTRedirectedInterfaceIndex() == index); - } - BOOL HasInvisibleParent() { LIMITED_METHOD_CONTRACT; @@ -759,7 +634,6 @@ struct ComMethodTable switch (ItfType) { case ifVtable: return (sizeof(IUnkVtable) / sizeof(SLOT)); - case ifInspectable: return (sizeof(IInspectableVtable) / sizeof(SLOT)); default: return (sizeof(IDispatchVtable) / sizeof(SLOT)); } } @@ -1213,24 +1087,6 @@ public: // Release for a Wrapper object inline ULONG Release(); - // Get Jupiter RefCount - inline ULONG GetJupiterRefCount(); - - // AddRef Jupiter Ref Count - // Jupiter Ref count becomes strong ref if pegged, otherwise weak ref - inline ULONG AddJupiterRef(); - - // Release Jupiter Ref Count - // Jupiter Ref count becomes strong ref if pegged, otherwise weak ref - inline ULONG ReleaseJupiterRef(); - - // Return whether this CCW is pegged or not by Jupiter - inline BOOL IsPegged(); - - // Return whether this CCW is pegged or not (either by Jupiter, or globally) - // We globally peg every Jupiter CCW outside Gen 2 GCs - inline BOOL IsConsideredPegged(); - // Initialize the simple wrapper. static void InitSimpleWrapper(ComCallWrapper* pWrap, SimpleComCallWrapper* pSimpleWrap); @@ -1319,33 +1175,6 @@ public: Wrapper::operator=(p); } }; - -typedef DPTR(class WeakReferenceImpl) PTR_WeakReferenceImpl; - -// -// Represents a domain-bound weak reference to the object (not the CCW) -// -class WeakReferenceImpl : public IUnknownCommon -{ -private: - OBJECTHANDLE m_ppObject; // Short weak global handle points back to the object, - -public: - WeakReferenceImpl(SimpleComCallWrapper *pSimpleWrapper, Thread *pCurrentThread); - virtual ~WeakReferenceImpl(); - - // IWeakReference methods - virtual HRESULT STDMETHODCALLTYPE Resolve(REFIID riid, IInspectable **ppvObject); - -private : - static void Resolve_Callback(LPVOID lpData); - static void Resolve_Callback_SwitchToPreemp(LPVOID lpData); - - HRESULT ResolveInternal(Thread *pThread, REFIID riid, IInspectable **ppvObject); - - HRESULT Cleanup(); -}; - // // Uncommonly used data on Simple CCW // Created on-demand @@ -1356,7 +1185,6 @@ private : struct SimpleCCWAuxData { VolatilePtr m_pDispatchExInfo; // Information required by the IDispatchEx standard interface - // Not available on WinRT types SimpleCCWAuxData() { @@ -1386,7 +1214,6 @@ struct SimpleComCallWrapper private: friend class ComCallWrapper; friend class ClrDataAccess; - friend class WeakReferenceImpl; enum SimpleComCallWrapperFlags { @@ -1395,7 +1222,7 @@ private: enum_IsHandleWeak = 0x4, enum_IsComActivated = 0x8, // unused = 0x10, - enum_IsPegged = 0x80, + // unused = 0x80, // unused = 0x100, enum_CustomQIRespondsToIMarshal = 0x200, enum_CustomQIRespondsToIMarshal_Inited = 0x400, @@ -1406,14 +1233,10 @@ public : { CLEANUP_SENTINEL = 0x0000000080000000, // Sentinel -> 1 bit COM_REFCOUNT_MASK = 0x000000007FFFFFFF, // COM -> 31 bits - JUPITER_REFCOUNT_MASK = 0xFFFFFFFF00000000, // Jupiter -> 32 bits - JUPITER_REFCOUNT_SHIFT = 32, - JUPITER_REFCOUNT_INC = 0x0000000100000000, EXT_COM_REFCOUNT_MASK = 0x00000000FFFFFFFF, // For back-compat, preserve the higher-bit so that outside can observe it ALL_REFCOUNT_MASK = 0xFFFFFFFF7FFFFFFF, }; - #define GET_JUPITER_REF(x) ((ULONG)(((x) & SimpleComCallWrapper::JUPITER_REFCOUNT_MASK) >> SimpleComCallWrapper::JUPITER_REFCOUNT_SHIFT)) #define GET_COM_REF(x) ((ULONG)((x) & SimpleComCallWrapper::COM_REFCOUNT_MASK)) #define GET_EXT_COM_REF(x) ((ULONG)((x) & SimpleComCallWrapper::EXT_COM_REFCOUNT_MASK)) @@ -1589,33 +1412,11 @@ public: FastInterlockOr((ULONG*)&m_flags, enum_IsComActivated); } - inline BOOL IsPegged() - { - LIMITED_METHOD_DAC_CONTRACT; - - return m_flags & enum_IsPegged; - } - - inline void MarkPegged() - { - LIMITED_METHOD_CONTRACT; - - FastInterlockOr((ULONG*)&m_flags, enum_IsPegged); - } - - inline void UnMarkPegged() - { - LIMITED_METHOD_CONTRACT; - - FastInterlockAnd((ULONG*)&m_flags, ~enum_IsPegged); - } - // Used for the creation and deletion of simple wrappers static SimpleComCallWrapper* CreateSimpleWrapper(); // Determines if the type associated with the ComCallWrapper supports exceptions. static BOOL SupportsExceptions(MethodTable *pMT); - static BOOL SupportsIStringable(MethodTable *pMT); // Determines if the type supports IReflect / IExpando. static BOOL SupportsIReflect(MethodTable *pMT); @@ -1835,7 +1636,7 @@ public: // point unless newRefCount equals CLEANUP_SENTINEL (it's the only case when we know that Neuter // or another Release could not swoop in and destroy our data structures). - // If we hit the sentinel value in COM ref count and jupiter ref count == 0, it's our responsibility to clean up. + // If we hit the sentinel value in COM ref count == 0, it's our responsibility to clean up. if (newRefCount == CLEANUP_SENTINEL) { ReleaseImplCleanup(); @@ -1845,57 +1646,8 @@ public: return GET_EXT_COM_REF(newRefCount); } - inline ULONG AddJupiterRef() - { - WRAPPER_NO_CONTRACT; - - LONGLONG llOldRefCount; - LONGLONG llNewRefCount; - - do { - llOldRefCount = m_llRefCount; - llNewRefCount = llOldRefCount + JUPITER_REFCOUNT_INC; - } while (InterlockedCompareExchange64(&m_llRefCount, llNewRefCount, llOldRefCount) != llOldRefCount); - - LOG((LF_INTEROP, LL_INFO1000, - "SimpleComCallWrapper::AddJupiterRef() called on SimpleComCallWrapper 0x%p, cbRef = 0x%x, cbJupiterRef = 0x%x\n", this, GET_COM_REF(llNewRefCount), GET_JUPITER_REF(llNewRefCount))); - - return GET_JUPITER_REF(llNewRefCount); - } - - inline ULONG ReleaseJupiterRef() - { - WRAPPER_NO_CONTRACT; - - LONGLONG llOldRefCount; - LONGLONG llNewRefCount; - - do { - llOldRefCount = m_llRefCount; - llNewRefCount = llOldRefCount - JUPITER_REFCOUNT_INC; - } while (InterlockedCompareExchange64(&m_llRefCount, llNewRefCount, llOldRefCount) != llOldRefCount); - - LOG((LF_INTEROP, LL_INFO1000, - "SimpleComCallWrapper::ReleaseJupiterRef() called on SimpleComCallWrapper 0x%p, cbRef = 0x%x, cbJupiterRef = 0x%x\n", this, GET_COM_REF(llNewRefCount), GET_JUPITER_REF(llNewRefCount))); - - if (llNewRefCount == CLEANUP_SENTINEL) - { - // If we hit the sentinel value, it's our responsibility to clean up. - m_pWrap->Cleanup(); - } - - return GET_JUPITER_REF(llNewRefCount); - } - #endif // !defined(DACCESS_COMPILE) && !defined(CROSSGEN_COMPILE) - inline ULONG GetJupiterRefCount() - { - LIMITED_METHOD_CONTRACT; - - return GET_JUPITER_REF(READ_REF(m_llRefCount)); - } - MethodTable* GetMethodTable() { CONTRACT (MethodTable*) @@ -1938,25 +1690,6 @@ public: return m_pTemplate; } - // Creates new AddRef-ed IWeakReference* - IWeakReference *CreateWeakReference(Thread *pCurrentThread) - { - CONTRACTL - { - THROWS; - GC_TRIGGERS; - MODE_PREEMPTIVE; - PRECONDITION(pCurrentThread == GetThread()); - } - CONTRACTL_END; - - // Create a WeakReferenceImpl with RefCount = 1 - // No need to call AddRef - WeakReferenceImpl *pWeakRef = new WeakReferenceImpl(this, pCurrentThread); - - return pWeakRef; - } - // Returns TRUE if the ICustomQI implementation returns Handled or Failed for IID_IMarshal. BOOL CustomQIRespondsToIMarshal(); @@ -2020,7 +1753,8 @@ private: DWORD m_flags; - // This maintains both COM ref and Jupiter ref in 64-bit + // This maintains the 32-bit COM refcount in 64-bits + // to enable also tracking the Cleanup sentinel. See code:CLEANUP_SENTINEL LONGLONG m_llRefCount; }; @@ -2119,35 +1853,6 @@ inline ULONG ComCallWrapper::Release() return m_pSimpleWrapper->Release(); } -inline ULONG ComCallWrapper::AddJupiterRef() -{ - CONTRACTL - { - WRAPPER(THROWS); - WRAPPER(GC_TRIGGERS); - MODE_ANY; - INSTANCE_CHECK; - } - CONTRACTL_END; - - return m_pSimpleWrapper->AddJupiterRef(); -} - -inline ULONG ComCallWrapper::ReleaseJupiterRef() -{ - CONTRACTL - { - WRAPPER(THROWS); - WRAPPER(GC_TRIGGERS); - MODE_ANY; - INSTANCE_CHECK; - PRECONDITION(CheckPointer(m_pSimpleWrapper)); - } - CONTRACTL_END; - - return m_pSimpleWrapper->ReleaseJupiterRef(); -} - inline void ComCallWrapper::InitSimpleWrapper(ComCallWrapper* pWrap, SimpleComCallWrapper* pSimpleWrap) { CONTRACTL @@ -2190,41 +1895,6 @@ inline void ComCallWrapper::ClearSimpleWrapper(ComCallWrapper* pWrap) } #endif // !DACCESS_COMPILE && !CROSSGEN_COMPILE -inline BOOL ComCallWrapper::IsPegged() -{ - CONTRACTL - { - NOTHROW; - GC_NOTRIGGER; - MODE_ANY; - INSTANCE_CHECK; - } - CONTRACTL_END; - - return m_pSimpleWrapper->IsPegged(); -} - -inline BOOL ComCallWrapper::IsConsideredPegged() -{ - LIMITED_METHOD_DAC_CONTRACT; - - return m_pSimpleWrapper->IsPegged() || RCWWalker::IsGlobalPeggingOn(); -} - -inline ULONG ComCallWrapper::GetJupiterRefCount() -{ - CONTRACTL - { - NOTHROW; - GC_NOTRIGGER; - MODE_ANY; - INSTANCE_CHECK; - } - CONTRACTL_END; - - return m_pSimpleWrapper->GetJupiterRefCount(); -} - inline PTR_ComCallWrapper ComCallWrapper::GetWrapperFromIP(PTR_IUnknown pUnk) { CONTRACT (PTR_ComCallWrapper) @@ -2302,21 +1972,15 @@ inline BOOL ComCallWrapper::IsWrapperActive() LONGLONG llRefCount = m_pSimpleWrapper->GetRealRefCount(); ULONG cbRef = GET_COM_REF(llRefCount); - ULONG cbJupiterRef = GET_JUPITER_REF(llRefCount); - - // We only consider jupiter ref count to be a "strong" ref count if it is pegged and it is alive - // Note that there is no concern for resurrecting this CCW in the next Gen0/1 GC - // because this CCW will be promoted to Gen 2 very quickly - BOOL bHasJupiterStrongRefCount = (cbJupiterRef > 0 && IsConsideredPegged()); - BOOL bHasStrongCOMRefCount = ((cbRef > 0) || bHasJupiterStrongRefCount); + BOOL bHasStrongCOMRefCount = ((cbRef > 0)); BOOL bIsWrapperActive = (bHasStrongCOMRefCount && !m_pSimpleWrapper->IsHandleWeak()); LOG((LF_INTEROP, LL_INFO1000, - "CCW 0x%p: cbRef = 0x%x, cbJupiterRef = 0x%x, IsPegged = %d, GlobalPegging = %d, IsHandleWeak = %d\n", + "CCW 0x%p: cbRef = 0x%x, IsHandleWeak = %d\n", this, - cbRef, cbJupiterRef, m_pSimpleWrapper->IsPegged(), RCWWalker::IsGlobalPeggingOn(), m_pSimpleWrapper->IsHandleWeak())); + cbRef, m_pSimpleWrapper->IsHandleWeak())); LOG((LF_INTEROP, LL_INFO1000, "CCW 0x%p: IsWrapperActive returned %d\n", this, bIsWrapperActive)); return bIsWrapperActive; diff --git a/src/coreclr/src/vm/comdelegate.cpp b/src/coreclr/src/vm/comdelegate.cpp index e2b45fb..81b754b 100644 --- a/src/coreclr/src/vm/comdelegate.cpp +++ b/src/coreclr/src/vm/comdelegate.cpp @@ -342,7 +342,7 @@ BOOL GenerateShuffleArrayPortable(MethodDesc* pMethodSrc, MethodDesc *pMethodDst unsigned int argSlots = NUM_ARGUMENT_REGISTERS #ifdef NUM_FLOAT_ARGUMENT_REGISTERS - + NUM_FLOAT_ARGUMENT_REGISTERS + + NUM_FLOAT_ARGUMENT_REGISTERS #endif + sArgPlacerSrc.SizeOfArgStack() / sizeof(size_t); @@ -430,10 +430,10 @@ BOOL GenerateShuffleArrayPortable(MethodDesc* pMethodSrc, MethodDesc *pMethodDst pGraphNodes[i].isSource = false; } - // Build the directed graph representing register and stack slot shuffling. + // Build the directed graph representing register and stack slot shuffling. // The links are directed from destination to source. // During the build also set isSource flag for nodes that are sources of data. - // The ones that don't have the isSource flag set are beginnings of non-cyclic + // The ones that don't have the isSource flag set are beginnings of non-cyclic // segments of the graph. for (unsigned int i = 0; i < pShuffleEntryArray->GetCount(); i++) { @@ -448,7 +448,7 @@ BOOL GenerateShuffleArrayPortable(MethodDesc* pMethodSrc, MethodDesc *pMethodDst // Unmark the node to indicate that it was not processed yet pGraphNodes[srcIndex].isMarked = false; // The node contains a register / stack slot that is a source from which we move data to a destination one - pGraphNodes[srcIndex].isSource = true; + pGraphNodes[srcIndex].isSource = true; pGraphNodes[srcIndex].ofs = entry.srcofs; // Unmark the node to indicate that it was not processed yet @@ -1392,85 +1392,6 @@ OBJECTREF COMDelegate::ConvertToDelegate(LPVOID pCallback, MethodTable* pMT) return delObj; } -#ifdef FEATURE_COMINTEROP -// Marshals a WinRT delegate interface pointer to a managed Delegate -//static -OBJECTREF COMDelegate::ConvertWinRTInterfaceToDelegate(IUnknown *pIdentity, MethodTable* pMT) -{ - CONTRACTL - { - THROWS; - GC_TRIGGERS; - MODE_COOPERATIVE; - PRECONDITION(CheckPointer(pIdentity)); - PRECONDITION(CheckPointer(pMT)); - } - CONTRACTL_END; - - MethodDesc* pMD = FindDelegateInvokeMethod(pMT); - - if (pMD->IsSharedByGenericInstantiations()) - { - // we need an exact MD to represent the call - pMD = InstantiatedMethodDesc::FindOrCreateExactClassMethod(pMT, pMD); - } - else - { - // set up ComPlusCallInfo - PopulateComPlusCallInfo(pMT); - } - - ComPlusCallInfo *pComInfo = ComPlusCallInfo::FromMethodDesc(pMD); - PCODE pMarshalStub = (pComInfo == NULL ? NULL : pComInfo->m_pILStub); - - if (pMarshalStub == NULL) - { - GCX_PREEMP(); - - DWORD dwStubFlags = NDIRECTSTUB_FL_COM | NDIRECTSTUB_FL_WINRT | NDIRECTSTUB_FL_WINRTDELEGATE; - - pMarshalStub = GetStubForInteropMethod(pMD, dwStubFlags); - - // At this point we must have a non-NULL ComPlusCallInfo - pComInfo = ComPlusCallInfo::FromMethodDesc(pMD); - _ASSERTE(pComInfo != NULL); - - // Save this new stub on the ComPlusCallInfo - InterlockedCompareExchangeT(&pComInfo->m_pILStub, pMarshalStub, NULL); - - pMarshalStub = pComInfo->m_pILStub; - } - - _ASSERTE(pMarshalStub != NULL); - - ////////////////////////////////////////////////////////////////////////////////////////////////////////// - // Wire up the stub to the new delegate instance. - // - - LOG((LF_INTEROP, LL_INFO10000, "Created delegate for WinRT interface: pUnk: %p\n", pIdentity)); - - // Create the new delegate - DELEGATEREF delObj = (DELEGATEREF) pMT->Allocate(); - - { - // delObj is not protected - GCX_NOTRIGGER(); - - // Wire up the unmanaged call stub to the delegate. - delObj->SetTarget(delObj); // We are the "this" object - - // We save the entry point in the delegate's method pointer and the identity pUnk in the aux pointer. - delObj->SetMethodPtr(pMarshalStub); - delObj->SetMethodPtrAux((PCODE)pIdentity); - - // Also, mark this delegate as an unmanaged function pointer wrapper. - delObj->SetInvocationCount(DELEGATE_MARKER_UNMANAGEDFPTR); - } - - return delObj; -} -#endif // FEATURE_COMINTEROP - void COMDelegate::ValidateDelegatePInvoke(MethodDesc* pMD) { CONTRACTL @@ -1519,16 +1440,7 @@ MethodDesc* COMDelegate::GetILStubMethodDesc(EEImplMethodDesc* pDelegateMD, DWOR MethodTable *pMT = pDelegateMD->GetMethodTable(); -#ifdef FEATURE_COMINTEROP - if (pMT->IsWinRTDelegate()) - { - dwStubFlags |= NDIRECTSTUB_FL_COM | NDIRECTSTUB_FL_WINRT | NDIRECTSTUB_FL_WINRTDELEGATE; - } - else -#endif // FEATURE_COMINTEROP - { - dwStubFlags |= NDIRECTSTUB_FL_DELEGATE; - } + dwStubFlags |= NDIRECTSTUB_FL_DELEGATE; PInvokeStaticSigInfo sigInfo(pDelegateMD); return NDirect::CreateCLRToNativeILStub(&sigInfo, dwStubFlags, pDelegateMD); @@ -2989,8 +2901,7 @@ MethodDesc* COMDelegate::GetDelegateCtor(TypeHandle delegateType, MethodDesc *pT #ifdef FEATURE_COMINTEROP // We'll always force classic COM types to go down the slow path for security checks. - if ((pMT->IsComObjectType() && !pMT->IsWinRTObjectType()) || - (pMT->IsComImport() && !pMT->IsProjectedFromWinRT())) + if (pMT->IsComObjectType() || pMT->IsComImport()) { return NULL; } diff --git a/src/coreclr/src/vm/comdelegate.h b/src/coreclr/src/vm/comdelegate.h index 39db2e7..6cb36c3 100644 --- a/src/coreclr/src/vm/comdelegate.h +++ b/src/coreclr/src/vm/comdelegate.h @@ -94,9 +94,6 @@ public: static OBJECTREF ConvertToDelegate(LPVOID pCallback, MethodTable* pMT); #ifdef FEATURE_COMINTEROP - // Marshals a WinRT delegate interface pointer to a managed Delegate - static OBJECTREF ConvertWinRTInterfaceToDelegate(IUnknown *pUnk, MethodTable* pMT); - static ComPlusCallInfo * PopulateComPlusCallInfo(MethodTable * pDelMT); #endif // FEATURE_COMINTEROP diff --git a/src/coreclr/src/vm/cominterfacemarshaler.cpp b/src/coreclr/src/vm/cominterfacemarshaler.cpp index 16b2952..d8d57ab 100644 --- a/src/coreclr/src/vm/cominterfacemarshaler.cpp +++ b/src/coreclr/src/vm/cominterfacemarshaler.cpp @@ -17,7 +17,6 @@ #include "interopconverter.h" #include "notifyexternals.h" #include "comdelegate.h" -#include "winrttypenameconverter.h" #include "olecontexthelpers.h" @@ -40,10 +39,6 @@ COMInterfaceMarshaler::COMInterfaceMarshaler() m_pUnknown = NULL; m_pIdentity = NULL; - - m_fIReference = false; - m_fIReferenceArray = false; - m_fNonRCWType = false; m_flags = RCW::CF_None; m_pCallback = NULL; m_pThread = NULL; @@ -94,48 +89,6 @@ VOID COMInterfaceMarshaler::Init(IUnknown* pUnk, MethodTable* pClassMT, Thread * m_pThread = pThread; m_flags = flags; - - if (!SupportsIInspectable()) - { - if (!m_typeHandle.IsNull() && m_typeHandle.IsProjectedFromWinRT()) - m_flags |= RCW::CF_SupportsIInspectable; - } -} - -// Returns true if the type is WinRT-redirected and requires special marshaler functionality -// to convert an interface pointer to its corresponding managed instance. -static bool IsRedirectedToNonRCWType(MethodTable *pMT) -{ - CONTRACTL - { - THROWS; - GC_TRIGGERS; - MODE_ANY; - } - CONTRACTL_END; - - if (pMT == nullptr) - { - return false; - } - - WinMDAdapter::RedirectedTypeIndex index; - if (!WinRTTypeNameConverter::ResolveRedirectedType(pMT, &index)) - { - return false; - } - - if (index == WinMDAdapter::RedirectedTypeIndex_System_Collections_Generic_KeyValuePair) - { - // we need to convert IKeyValuePair to boxed KeyValuePair - return true; - } - - // redirected runtime classes are not RCWs - WinMDAdapter::WinMDTypeKind kind; - WinMDAdapter::GetRedirectedTypeInfo(index, nullptr, nullptr, nullptr, nullptr, nullptr, &kind); - - return kind == WinMDAdapter::WinMDTypeKind_Runtimeclass; } //-------------------------------------------------------------------------------- @@ -151,88 +104,24 @@ VOID COMInterfaceMarshaler::InitializeObjectClass(IUnknown *pIncomingIP) } CONTRACTL_END; - if (!DontResolveClass()) + // If we are in an APPX process we do not check for IProvideClassInfo. + if (m_typeHandle.IsNull() && !AppX::IsAppXProcess()) { - - // If we are not in an APPX process, and an object could have a strongly typed RCW as a COM CoClass, - // we prefer that to the WinRT class.This preserves compatibility for exisitng code. - // If we are in an APPX process we do not check for IProvideClassInfo. - if (m_typeHandle.IsNull() && !AppX::IsAppXProcess()) + EX_TRY { - EX_TRY - { - m_typeHandle = GetClassFromIProvideClassInfo(m_pUnknown); + m_typeHandle = GetClassFromIProvideClassInfo(m_pUnknown); - if (!m_typeHandle.IsNull() && !m_typeHandle.IsComObjectType()) - { - m_typeHandle = TypeHandle(); // Clear the existing one. - } - } - EX_CATCH + if (!m_typeHandle.IsNull() && !m_typeHandle.IsComObjectType()) { + m_typeHandle = TypeHandle(); // Clear the existing one. } - EX_END_CATCH(RethrowTerminalExceptions); - if(!m_typeHandle.IsNull()) - return; } - - // Note that the actual type may be a subtype of m_typeHandle if it's not sealed. - if ((m_typeHandle.IsNull() || !m_typeHandle.GetMethodTable()->IsSealed()) && WinRTSupported()) + EX_CATCH { - bool fInspectable = SupportsIInspectable(); - EX_TRY - { - // QI for IInspectable first. m_fInspectable at this point contains information about the interface - // pointer that we could gather from the signature or API call. But, since an object can be acquired - // as a plain IUnknown and later started being treated as a WinRT object, we always eagerly QI for - // IInspectable as part of the IInspectable::GetRuntimeClassName call. Also note that we may discover - // this IInspectable is really a IReference or IReferenceArray for WinRT-compatible T's. - TypeHandle typeHandle = GetClassFromIInspectable(pIncomingIP, &fInspectable, &m_fIReference, &m_fIReferenceArray); - - if (!typeHandle.IsNull()) - { - // GetRuntimeClassName could return a interface or projected value type name - if (m_fIReference || m_fIReferenceArray) - { - // this has already been pre-processed - it is the IReference/IReferenceArray generic argument - m_typeHandle = typeHandle; - } - if (typeHandle.IsInterface()) - { - m_itfTypeHandle = typeHandle; - } - else if (IsRedirectedToNonRCWType(typeHandle.GetMethodTable())) - { - m_typeHandle = typeHandle; - m_fNonRCWType = true; - } - else if (!typeHandle.IsValueType()) - { - // if the type returned from GetRuntimeClassName is a class, it must be derived from __ComObject - // or be a WinRT delegate for us to be able to build an RCW for it - if (typeHandle.IsComObjectType() || - (!typeHandle.IsTypeDesc() && typeHandle.GetMethodTable()->IsDelegate() && (typeHandle.IsProjectedFromWinRT() || WinRTTypeNameConverter::IsRedirectedType(typeHandle.GetMethodTable())))) - { - m_typeHandle = typeHandle; - } - } - } - } - EX_CATCH - { - } - EX_END_CATCH(RethrowTerminalExceptions); - - if (fInspectable) - { - m_flags |= RCW::CF_SupportsIInspectable; - } - else - { - _ASSERTE_MSG(m_typeHandle.IsNull() || !SupportsIInspectable(), - "Acquired an object which should be IInspectable according to metadata but the QI failed."); - } } + EX_END_CATCH(RethrowTerminalExceptions); + if(!m_typeHandle.IsNull()) + return; } if (m_typeHandle.IsNull()) @@ -252,7 +141,7 @@ void COMInterfaceMarshaler::CreateObjectRef(BOOL fDuplicate, OBJECTREF *pComObj, MODE_COOPERATIVE; PRECONDITION(IsProtectedByGCFrame(pComObj)); PRECONDITION(!m_typeHandle.IsNull()); - PRECONDITION(m_typeHandle.IsComObjectType() || (m_typeHandle.GetMethodTable()->IsDelegate() && (m_typeHandle.GetMethodTable()->IsProjectedFromWinRT() || WinRTTypeNameConverter::IsRedirectedType(m_typeHandle.GetMethodTable())))); + PRECONDITION(m_typeHandle.IsComObjectType()); PRECONDITION(m_pThread == GetThread()); PRECONDITION(pIncomingItfMT == NULL || pIncomingItfMT->IsInterface()); } @@ -273,11 +162,7 @@ void COMInterfaceMarshaler::CreateObjectRef(BOOL fDuplicate, OBJECTREF *pComObj, } else { - // If delegates were to take this path, we need to fix the identity in MethodPtrAux later - _ASSERTE(!(m_flags & RCW::CF_QueryForIdentity)); - - // delegate backed by a WinRT interface pointer - *pComObj = COMDelegate::ConvertWinRTInterfaceToDelegate(m_pIdentity, m_typeHandle.GetMethodTable()); + _ASSERTE(!"Creating a COM wrapper for WinRT delegates (which do not inherit from __ComObject) is not supported."); } // make sure we "pin" the syncblock before switching to preemptive mode @@ -337,55 +222,8 @@ void COMInterfaceMarshaler::CreateObjectRef(BOOL fDuplicate, OBJECTREF *pComObj, } // We expect that, at most, the first entry will already be allocated. - // (SetJupiterObject gets the first shot at this.) int nNextFreeIdx = pNewRCW->m_aInterfaceEntries[0].IsFree() ? 0 : 1; - // Only cache WinRT interfaces - // Note that we can't use SupportsIInspectable here because we could be talking to a CCW - // which supports IInspectable by default - if (ppIncomingIP != NULL && - *ppIncomingIP != NULL && - pIncomingItfMT != NULL && - pIncomingItfMT->IsLegalNonArrayWinRTType()) - { - _ASSERTE(pIncomingItfMT->IsInterface()); - _ASSERTE(pNewRCW->m_aInterfaceEntries[nNextFreeIdx].IsFree()); - - // - // The incoming interface pointer is of type m_pItfMT - // Cache the result into RCW for better performance and for variance support - // For example, GetFilesAsync() returns Windows.Storage.StorageFileView and this type - // is not in any WinMD. Because GetFilesAsync actually returns IVectorView, - // we know this RCW supports this interface, and putting it into the cache would make sure - // casting this RCW to IVectorView works - // - pNewRCW->m_aInterfaceEntries[nNextFreeIdx++].Init(pIncomingItfMT, *ppIncomingIP); - - // Don't hold ref count if RCW is aggregated - if (!pNewRCW->IsURTAggregated()) - { - if (bIncomingIPAddRefed) - { - // Transfer the ref from ppIncomingIP to internal cache - // This will only happen in WinRT scenarios to reduce risk of this change - *ppIncomingIP = NULL; - } - else - { - // Otherwise AddRef by ourselves - RCW_VTABLEPTR(pNewRCW); - SafeAddRef(*ppIncomingIP); - } - - RCWWalker::AfterInterfaceAddRef(pNewRCW); - } - - // Save GetEnumerator method if necessary - // Do this after we "AddRef" on ppIncomingIP otherwise we would call Release on it - // without a AddRef - pNewRCW->SetGetEnumeratorMethod(pIncomingItfMT); - } - if (!m_itfTypeHandle.IsNull() && !m_itfTypeHandle.IsTypeDesc()) { MethodTable *pItfMT = m_itfTypeHandle.AsMethodTable(); @@ -411,8 +249,6 @@ void COMInterfaceMarshaler::CreateObjectRef(BOOL fDuplicate, OBJECTREF *pComObj, if (!pNewRCW->IsURTAggregated()) { pItfIP.SuppressRelease(); - - RCWWalker::AfterInterfaceAddRef(pNewRCW); } } } @@ -424,8 +260,7 @@ void COMInterfaceMarshaler::CreateObjectRef(BOOL fDuplicate, OBJECTREF *pComObj, RCWHolder pRCW(m_pThread); pRCW.InitNoCheck(pNewRCW); - // We may get back an RCW from another STA thread (mainly in WinRT factory cache scenario, - // as those factories are typically singleton), and we can only touch the RCW if we hold the lock, + // We may get back an RCW from another STA thread and we can only touch the RCW if we hold the lock, // otherwise we may AV if the STA thread dies and takes the RCW with it RCWCache::LockHolder lh(m_pWrapperCache); @@ -503,290 +338,6 @@ void COMInterfaceMarshaler::CreateObjectRef(BOOL fDuplicate, OBJECTREF *pComObj, #endif } - -// OBJECTREF COMInterfaceMarshaler::IReferenceUnbox() -//-------------------------------------------------------------------------------- - -void COMInterfaceMarshaler::IReferenceUnbox(IUnknown **ppIncomingIP, OBJECTREF *poref, bool bIncomingIPAddRefed) -{ - CONTRACTL - { - THROWS; - GC_TRIGGERS; - MODE_COOPERATIVE; - PRECONDITION(m_fIReference); - PRECONDITION(m_pThread == GetThread()); - } - CONTRACTL_END; - - OBJECTREF unboxed = NULL; - _ASSERTE(m_typeHandle.AsMethodTable()->IsLegalNonArrayWinRTType()); - - // Create a temporary RCW. Call into managed. Let managed query for a closed generic instantiation - // like IReference (including the GUID calculation & QI) then call the Value property. That - // will use the existing interop code to safely marshal the value. - // Also, make sure we create a duplicate RCW in this case so that next time we won't end up getting - // this RCW from cache - COMInterfaceMarshaler marshaler; - - DWORD flags = RCW::CF_DontResolveClass | RCW::CF_NeedUniqueObject; - - marshaler.Init(m_pUnknown, g_pBaseCOMObject, m_pThread, flags); - - if (m_pCallback) - marshaler.SetCallback(m_pCallback); - - OBJECTREF oref = marshaler.FindOrCreateObjectRefInternal(ppIncomingIP, /* pIncomingItfMT = */ NULL, bIncomingIPAddRefed); - - IReferenceOrIReferenceArrayUnboxWorker(oref, m_typeHandle, FALSE, poref); -} - -// void COMInterfaceMarshaler::IReferenceOrIReferenceArrayUnboxWorker() -//-------------------------------------------------------------------------------- - -// static -void COMInterfaceMarshaler::IReferenceOrIReferenceArrayUnboxWorker(OBJECTREF oref, TypeHandle thT, BOOL fIsIReferenceArray, OBJECTREF *porefResult) -{ - CONTRACTL - { - THROWS; - GC_TRIGGERS; - MODE_COOPERATIVE; - } - CONTRACTL_END; - - GCPROTECT_BEGIN(oref); - - // Get IReference or IReferenceArray - Instantiation inst(&thT, 1); - TypeHandle openType; - MethodDesc* pMD = NULL; - if (fIsIReferenceArray) - { - openType = TypeHandle(MscorlibBinder::GetClass(CLASS__CLRIREFERENCEARRAYIMPL)); - pMD = MscorlibBinder::GetMethod(METHOD__CLRIREFERENCEARRAYIMPL__UNBOXHELPER); - } - else - { - openType = TypeHandle(MscorlibBinder::GetClass(CLASS__CLRIREFERENCEIMPL)); - pMD = MscorlibBinder::GetMethod(METHOD__CLRIREFERENCEIMPL__UNBOXHELPER); - } - TypeHandle closedType = openType.Instantiate(inst); - - // Call managed helper to get the real unboxed object now - MethodDesc* method = MethodDesc::FindOrCreateAssociatedMethodDesc( - pMD, - closedType.AsMethodTable(), - FALSE, - Instantiation(), - FALSE); - _ASSERTE(method != NULL); - - MethodDescCallSite unboxHelper(method); - ARG_SLOT args[] = - { - ObjToArgSlot(oref), - }; - - // Call CLRIReferenceImpl::UnboxHelper(Object) or CLRIReferenceArrayImpl::UnboxHelper(Object) - *porefResult = unboxHelper.Call_RetOBJECTREF(args); - GCPROTECT_END(); -} - -// void COMInterfaceMarshaler::IKeyValuePairUnboxWorker() -//-------------------------------------------------------------------------------- - -// static -void COMInterfaceMarshaler::IKeyValuePairUnboxWorker(OBJECTREF oref, OBJECTREF *porefResult) -{ - CONTRACTL - { - THROWS; - GC_TRIGGERS; - MODE_COOPERATIVE; - } - CONTRACTL_END; - - GCPROTECT_BEGIN(oref); - - _ASSERTE(oref->GetMethodTable()->HasSameTypeDefAs(MscorlibBinder::GetClass(CLASS__CLRIKEYVALUEPAIRIMPL))); - - MethodDesc *method = MethodDesc::FindOrCreateAssociatedMethodDesc( - MscorlibBinder::GetMethod(METHOD__CLRIKEYVALUEPAIRIMPL__UNBOXHELPER), - oref->GetMethodTable(), - FALSE, - Instantiation(), - FALSE); - _ASSERTE(method != NULL); - - MethodDescCallSite unboxHelper(method); - ARG_SLOT args[] = - { - ObjToArgSlot(oref), - }; - - // Call CLRIKeyValuePair::UnboxHelper(Object) - *porefResult = unboxHelper.Call_RetOBJECTREF(args); - GCPROTECT_END(); -} - -// OBJECTREF COMInterfaceMarshaler::IReferenceArrayUnbox() -//-------------------------------------------------------------------------------- - -void COMInterfaceMarshaler::IReferenceArrayUnbox(IUnknown **ppIncomingIP, OBJECTREF *poref, bool bIncomingIPAddRefed) -{ - CONTRACTL - { - THROWS; - GC_TRIGGERS; - MODE_COOPERATIVE; - PRECONDITION(m_fIReferenceArray); - PRECONDITION(m_pThread == GetThread()); - } - CONTRACTL_END; - - OBJECTREF unboxed = NULL; - TypeHandle elementType = m_typeHandle.GetArrayElementTypeHandle(); - _ASSERTE(elementType.AsMethodTable()->IsLegalNonArrayWinRTType()); - - // Create a temporary RCW. Call into managed. Let managed query for a closed generic instantiation - // like IReferenceArray (including the GUID calculation & QI) then call the Value property. That - // will use the existing interop code to safely marshal the value. - // Also, make sure we create a duplicate RCW in this case so that next time we won't end up getting - // this RCW from cache - COMInterfaceMarshaler marshaler; - - DWORD flags = RCW::CF_DontResolveClass | RCW::CF_NeedUniqueObject; - - marshaler.Init(m_pUnknown, g_pBaseCOMObject, m_pThread, flags); - - if (m_pCallback) - marshaler.SetCallback(m_pCallback); - - OBJECTREF oref = marshaler.FindOrCreateObjectRefInternal(ppIncomingIP, /* pIncomingItfMT = */ NULL, bIncomingIPAddRefed); - - IReferenceOrIReferenceArrayUnboxWorker(oref, elementType, TRUE, poref); -} - -void COMInterfaceMarshaler::MarshalToNonRCWType(OBJECTREF *poref) -{ - CONTRACTL - { - THROWS; - GC_TRIGGERS; - MODE_COOPERATIVE; - PRECONDITION(m_fNonRCWType); - } - CONTRACTL_END; - - _ASSERTE(IsRedirectedToNonRCWType(m_typeHandle.GetMethodTable())); - - struct - { - OBJECTREF refMarshaled; - STRINGREF refRawURI; - } - gc; - ZeroMemory(&gc, sizeof(gc)); - - WinMDAdapter::RedirectedTypeIndex index = static_cast(-1); - WinRTTypeNameConverter::ResolveRedirectedType(m_typeHandle.GetMethodTable(), &index); - _ASSERTE(index != -1); - - GCPROTECT_BEGIN(gc) - - switch (index) - { - case WinMDAdapter::RedirectedTypeIndex_System_Uri: - { - WinRtString hsRawUri; - { - GCX_PREEMP(); - - SafeComHolderPreemp pUriRuntimeClass; - HRESULT hr = SafeQueryInterfacePreemp(m_pUnknown, ABI::Windows::Foundation::IID_IUriRuntimeClass, (IUnknown **) &pUriRuntimeClass); - LogInteropQI(m_pUnknown, ABI::Windows::Foundation::IID_IUriRuntimeClass, hr, "IUriRuntimeClass"); - IfFailThrow(hr); - - IfFailThrow(pUriRuntimeClass->get_RawUri(hsRawUri.Address())); - } - - UINT32 cchRawUri; - LPCWSTR pwszRawUri = hsRawUri.GetRawBuffer(&cchRawUri); - gc.refRawURI = StringObject::NewString(pwszRawUri, cchRawUri); - - UriMarshalingInfo *pUriMarshalingInfo = GetAppDomain()->GetLoaderAllocator()->GetMarshalingData()->GetUriMarshalingInfo(); - MethodDesc* pSystemUriCtorMD = pUriMarshalingInfo->GetSystemUriCtorMD(); - - MethodTable *pMTSystemUri = pUriMarshalingInfo->GetSystemUriType().AsMethodTable(); - pMTSystemUri->EnsureInstanceActive(); - gc.refMarshaled = AllocateObject(pMTSystemUri, false); - - MethodDescCallSite uriCtor(pSystemUriCtorMD); - ARG_SLOT ctorArgs[] = - { - ObjToArgSlot(gc.refMarshaled), - ObjToArgSlot(gc.refRawURI) - }; - uriCtor.Call(ctorArgs); - } - break; - - case WinMDAdapter::RedirectedTypeIndex_System_Collections_Generic_KeyValuePair: - { - MethodDesc *pMD = MscorlibBinder::GetMethod(METHOD__KEYVALUEPAIRMARSHALER__CONVERT_TO_MANAGED_BOX); - - pMD = MethodDesc::FindOrCreateAssociatedMethodDesc( - pMD, - pMD->GetMethodTable(), - FALSE, // forceBoxedEntryPoint - m_typeHandle.GetInstantiation(), // methodInst - FALSE, // allowInstParam - TRUE); // forceRemotableMethod - - MethodDescCallSite marshalMethod(pMD); - ARG_SLOT methodArgs[] = - { - PtrToArgSlot(m_pUnknown) - }; - gc.refMarshaled = marshalMethod.Call_RetOBJECTREF(methodArgs); - } - break; - - case WinMDAdapter::RedirectedTypeIndex_System_Collections_Specialized_NotifyCollectionChangedEventArgs: - case WinMDAdapter::RedirectedTypeIndex_System_ComponentModel_PropertyChangedEventArgs: - { - MethodDesc *pMD; - EventArgsMarshalingInfo *pInfo = GetAppDomain()->GetLoaderAllocator()->GetMarshalingData()->GetEventArgsMarshalingInfo(); - - if (index == WinMDAdapter::RedirectedTypeIndex_System_Collections_Specialized_NotifyCollectionChangedEventArgs) - pMD = pInfo->GetWinRTNCCEventArgsToSystemNCCEventArgsMD(); - else - pMD = pInfo->GetWinRTPCEventArgsToSystemPCEventArgsMD(); - - MethodDescCallSite marshalMethod(pMD); - ARG_SLOT methodArgs[] = - { - PtrToArgSlot(m_pUnknown) - }; - gc.refMarshaled = marshalMethod.Call_RetOBJECTREF(methodArgs); - } - break; - - default: - { - // If we get here then there is a new redirected type being introduced to the system. You must - // add code to marshal that type above. Additionally, code may need to be added to GetComIPFromObjectRef, - // in order to handle the reverse case. - UNREACHABLE(); - } - } - - *poref = gc.refMarshaled; - - GCPROTECT_END(); -} - //-------------------------------------------------------------------------------- // OBJECTREF COMInterfaceMarshaler::FindOrCreateObjectRef() // Find the wrapper for this COM IP, might have to create one if not found. @@ -794,10 +345,8 @@ void COMInterfaceMarshaler::MarshalToNonRCWType(OBJECTREF *poref) // an IP that is disguised as an unmanaged object, sitting on top of a // managed object. // -// The ppIncomingIP parameter serves two purposes - it lets COMInterfaceMarshaler call methods on the -// interface pointer that came in from unmanaged code (pUnk could be the result of QI'ing such an IP for IUnknown), -// and it also implements the CF_SuppressAddRef flag in a reliable way by assigning NULL to *ppIncomingIP if and -// only if COMInterfaceMarshaler ended up creating a new RCW which took ownership of the interface pointer. +// The ppIncomingIP parameter lets COMInterfaceMarshaler call methods on the +// interface pointer that came in from unmanaged code (pUnk could be the result of QI'ing such an IP for IUnknown). // // If pIncomingItfMT is not NULL, we'll cache ppIncomingIP into the created RCW, so that // 1) RCW variance would work if we can't load the right type from RuntimeClassName, but the method returns a interface @@ -841,8 +390,7 @@ OBJECTREF COMInterfaceMarshaler::FindOrCreateObjectRefInternal(IUnknown **ppInco GCPROTECT_BEGIN_THREAD(m_pThread, oref); { - // We may get back an RCW from another STA thread (mainly in WinRT factory cache scenario, - // as those factories are typically singleton), and we can only touch the RCW if we hold the lock, + // We may get back an RCW from another STA thread and we can only touch the RCW if we hold the lock, // otherwise we may AV if the STA thread dies and takes the RCW with it RCWCache::LockHolder lh(m_pWrapperCache); @@ -888,14 +436,7 @@ OBJECTREF COMInterfaceMarshaler::FindOrCreateObjectRefInternal(IUnknown **ppInco GCPROTECT_BEGIN_THREAD(m_pThread, oref) { - if (m_fIReference) - IReferenceUnbox(ppIncomingIP, &oref, bIncomingIPAddRefed); - else if (m_fIReferenceArray) - IReferenceArrayUnbox(ppIncomingIP, &oref, bIncomingIPAddRefed); - else if (m_fNonRCWType) - MarshalToNonRCWType(&oref); - else - CreateObjectRef(NeedUniqueObject(), &oref, ppIncomingIP, pIncomingItfMT, bIncomingIPAddRefed); + CreateObjectRef(NeedUniqueObject(), &oref, ppIncomingIP, pIncomingItfMT, bIncomingIPAddRefed); } GCPROTECT_END(); @@ -982,18 +523,6 @@ VOID COMInterfaceMarshaler::EnsureCOMInterfacesSupported(OBJECTREF oref, MethodT GCPROTECT_END(); } -bool COMInterfaceMarshaler::SupportsIInspectable() -{ - LIMITED_METHOD_CONTRACT; - return (m_flags & RCW::CF_SupportsIInspectable) != 0; -} - -bool COMInterfaceMarshaler::DontResolveClass() -{ - LIMITED_METHOD_CONTRACT; - return (m_flags & RCW::CF_DontResolveClass) != 0; -} - bool COMInterfaceMarshaler::NeedUniqueObject() { LIMITED_METHOD_CONTRACT; diff --git a/src/coreclr/src/vm/cominterfacemarshaler.h b/src/coreclr/src/vm/cominterfacemarshaler.h index e94101d..3d2505a 100644 --- a/src/coreclr/src/vm/cominterfacemarshaler.h +++ b/src/coreclr/src/vm/cominterfacemarshaler.h @@ -61,19 +61,11 @@ public: VOID InitializeExistingComObject(OBJECTREF *pComObj, IUnknown **ppIncomingIP); - static void IReferenceOrIReferenceArrayUnboxWorker(OBJECTREF oref, TypeHandle tkT, BOOL fIsIReferenceArray, OBJECTREF *porefResult); - static void IKeyValuePairUnboxWorker(OBJECTREF oref, OBJECTREF *porefResult); - private: OBJECTREF FindOrCreateObjectRefInternal(IUnknown **ppIncomingIP, MethodTable *pIncomingItfMT, bool bIncomingIPAddRefed); VOID CreateObjectRef(BOOL fDuplicate, OBJECTREF *pComObj, IUnknown **ppIncomingIP, MethodTable *pIncomingItfMT, bool bIncomingIPAddRefed); - void IReferenceUnbox(IUnknown **ppIncomingIP, OBJECTREF *poref, bool bIncomingIPAddRefed); - void IReferenceArrayUnbox(IUnknown **ppIncomingIP, OBJECTREF *poref, bool bIncomingIPAddRefed); - void MarshalToNonRCWType(OBJECTREF *poref); static VOID EnsureCOMInterfacesSupported(OBJECTREF oref, MethodTable* pClassMT); - inline bool SupportsIInspectable(); - inline bool DontResolveClass(); inline bool NeedUniqueObject(); RCWCache* m_pWrapperCache; // initialization info @@ -82,11 +74,6 @@ private: TypeHandle m_typeHandle; // inited and computed if inited value is NULL. Need to represent all array information too. TypeHandle m_itfTypeHandle; // an interface supported by the object as returned from GetRuntimeClassName Thread* m_pThread; // Current thread - avoid calling GetThread multiple times - - bool m_fIReference; // Is this an IReference (ie, a WinRT "boxed" value type) - bool m_fIReferenceArray; // Is this an IReferenceArray (ie, an array wrapped in a WinRT interface) - bool m_fNonRCWType; // Is this redirected to a non-RCW CLR type - DWORD m_flags; ICOMInterfaceMarshalerCallback *m_pCallback; // Callback to call when we created a RCW or got back RCW from cache diff --git a/src/coreclr/src/vm/commodule.cpp b/src/coreclr/src/vm/commodule.cpp index 51160cf..e931488 100644 --- a/src/coreclr/src/vm/commodule.cpp +++ b/src/coreclr/src/vm/commodule.cpp @@ -767,7 +767,7 @@ void QCALLTYPE COMModule::GetType(QCall::ModuleHandle pModule, LPCWSTR wszName, BOOL prohibitAsmQualifiedName = TRUE; // Load the class from this assembly (fail if it is in a different one). - retTypeHandle = TypeName::GetTypeManaged(wszName, pAssembly, bThrowOnError, bIgnoreCase, prohibitAsmQualifiedName, NULL, FALSE, (OBJECTREF*)keepAlive.m_ppObject); + retTypeHandle = TypeName::GetTypeManaged(wszName, pAssembly, bThrowOnError, bIgnoreCase, prohibitAsmQualifiedName, NULL, (OBJECTREF*)keepAlive.m_ppObject); // Verify that it's in 'this' module // But, if it's in a different assembly than expected, that's okay, because diff --git a/src/coreclr/src/vm/common.h b/src/coreclr/src/vm/common.h index 7089b75..8c8a4df 100644 --- a/src/coreclr/src/vm/common.h +++ b/src/coreclr/src/vm/common.h @@ -347,10 +347,6 @@ namespace Loader #include "codeman.h" #include "threads.h" #include "clrex.inl" -#ifdef FEATURE_COMINTEROP - #include "windowsruntime.h" - #include "windowsstring.h" -#endif #include "loaderallocator.hpp" #include "appdomain.hpp" #include "appdomain.inl" @@ -424,10 +420,6 @@ extern DummyGlobalContract ___contract; #include "syncblk.inl" #include "threads.inl" #include "eehash.inl" -#ifdef FEATURE_COMINTEROP -#include "WinRTRedirector.h" -#include "winrtredirector.inl" -#endif // FEATURE_COMINTEROP #include "eventtrace.inl" #if defined(COMMON_TURNED_FPO_ON) diff --git a/src/coreclr/src/vm/commtmemberinfomap.cpp b/src/coreclr/src/vm/commtmemberinfomap.cpp index be3e77b..ae4198c 100644 --- a/src/coreclr/src/vm/commtmemberinfomap.cpp +++ b/src/coreclr/src/vm/commtmemberinfomap.cpp @@ -533,7 +533,7 @@ void ComMTMemberInfoMap::SetupPropsForInterface(size_t sizeOfPtr) // Retrieve the number of vtable slots the interface has. nSlots = m_pMT->GetNumVirtuals(); - // IDispatch, IUnknown, or IInspectable derived? + // IDispatch, IUnknown derived? ifaceType = (m_pMT->IsInterface() ? m_pMT->GetComInterfaceType() : ifDual); oVftBase = ComMethodTable::GetNumExtraSlots(ifaceType) * (SHORT)sizeOfPtr; @@ -817,14 +817,14 @@ void ComMTMemberInfoMap::EliminateDuplicateNames( CQuickBytes qb; UINT iCur; - CorIfaceAttr ifaceType; // VTBL, Dispinterface, IDispatch, or IInspectable + CorIfaceAttr ifaceType; // VTBL, Dispinterface, IDispatch ULONG cBaseNames; // Count of names in base interface. BOOL bDup; // Is the name a duplicate? HRESULT hr = S_OK; const size_t cchrcName = MAX_CLASSNAME_LENGTH; LPWSTR rcName = (LPWSTR)qb.AllocThrows(cchrcName * sizeof(WCHAR)); - // Tables of names of methods on IUnknown, IDispatch, and IInspectable. + // Tables of names of methods on IUnknown, IDispatch. static const LPCWSTR rBaseNames_Dispatch[] = { W("QueryInterface"), @@ -836,19 +836,9 @@ void ComMTMemberInfoMap::EliminateDuplicateNames( W("Invoke") }; - static const LPCWSTR rBaseNames_Inspectable[] = - { - W("QueryInterface"), - W("AddRef"), - W("Release"), - W("GetIIDs"), - W("GetRuntimeClassName"), - W("GetTrustLevel") - }; - // Determine which names are in the base interface. ifaceType = (m_pMT->IsInterface() ? m_pMT->GetComInterfaceType() : ifDual); - const LPCWSTR * rBaseNames = (ifaceType == ifInspectable ? rBaseNames_Inspectable : rBaseNames_Dispatch); + const LPCWSTR * rBaseNames = (rBaseNames_Dispatch); // Is it pure dispinterface? if (ifaceType == ifDispatch) diff --git a/src/coreclr/src/vm/compile.cpp b/src/coreclr/src/vm/compile.cpp index 2d02eb3..aa9112f 100644 --- a/src/coreclr/src/vm/compile.cpp +++ b/src/coreclr/src/vm/compile.cpp @@ -37,7 +37,6 @@ #ifdef FEATURE_COMINTEROP #include "clrtocomcall.h" #include "comtoclrcall.h" -#include "winrttypenameconverter.h" #endif // FEATURE_COMINTEROP #include "dllimportcallback.h" @@ -46,16 +45,6 @@ #include "cgensys.h" #include "peimagelayout.inl" - -#ifdef FEATURE_COMINTEROP -#include "clrprivbinderwinrt.h" -#include "winrthelpers.h" -#endif - -#ifdef CROSSGEN_COMPILE -#include "crossgenroresolvenamespace.h" -#endif - #ifndef NO_NGENPDB #include #endif @@ -297,54 +286,30 @@ HRESULT CEECompileInfo::LoadAssemblyByPath( AppDomain * pDomain = AppDomain::GetCurrentDomain(); PEAssemblyHolder pAssemblyHolder; - BOOL isWinRT = FALSE; -#ifdef FEATURE_COMINTEROP - isWinRT = spec.IsContentType_WindowsRuntime(); - if (isWinRT) - { - LPCSTR szNameSpace; - LPCSTR szTypeName; - // It does not make sense to pass the file name to recieve fake type name for empty WinMDs, because we would use the name - // for binding in next call to BindAssemblySpec which would fail for fake WinRT type name - // We will throw/return the error instead and the caller will recognize it and react to it by not creating the ngen image - - // see code:Zapper::ComputeDependenciesInCurrentDomain - IfFailThrow(::GetFirstWinRTTypeDef(pImage->GetMDImport(), &szNameSpace, &szTypeName, NULL, NULL)); - spec.SetWindowsRuntimeType(szNameSpace, szTypeName); - } -#endif //FEATURE_COMINTEROP - - // If there is a host binder then use it to bind the assembly. - if (isWinRT) - { - pAssemblyHolder = pDomain->BindAssemblySpec(&spec, TRUE); - } - else - { - //ExplicitBind - CoreBindResult bindResult; - spec.SetCodeBase(pImage->GetPath()); - spec.Bind( - pDomain, - TRUE, // fThrowOnFileNotFound - &bindResult, - - // fNgenExplicitBind: Generally during NGEN compilation, this is - // TRUE, meaning "I am NGEN, and I am doing an explicit bind to the IL - // image, so don't infer the NI and try to open it, because I already - // have it open". But if we're executing crossgen /CreatePDB, this should - // be FALSE so that downstream code doesn't assume we're explicitly - // trying to bind to an IL image (we're actually explicitly trying to - // open an NI). - !fExplicitBindToNativeImage, - - // fExplicitBindToNativeImage: Most callers want this FALSE; but crossgen - // /CreatePDB explicitly specifies NI names to open, and cannot assume - // that IL assemblies will be available. - fExplicitBindToNativeImage - ); - pAssemblyHolder = PEAssembly::Open(&bindResult,FALSE); - } + //ExplicitBind + CoreBindResult bindResult; + spec.SetCodeBase(pImage->GetPath()); + spec.Bind( + pDomain, + TRUE, // fThrowOnFileNotFound + &bindResult, + + // fNgenExplicitBind: Generally during NGEN compilation, this is + // TRUE, meaning "I am NGEN, and I am doing an explicit bind to the IL + // image, so don't infer the NI and try to open it, because I already + // have it open". But if we're executing crossgen /CreatePDB, this should + // be FALSE so that downstream code doesn't assume we're explicitly + // trying to bind to an IL image (we're actually explicitly trying to + // open an NI). + !fExplicitBindToNativeImage, + + // fExplicitBindToNativeImage: Most callers want this FALSE; but crossgen + // /CreatePDB explicitly specifies NI names to open, and cannot assume + // that IL assemblies will be available. + fExplicitBindToNativeImage + ); + pAssemblyHolder = PEAssembly::Open(&bindResult,FALSE); // Now load assembly into domain. DomainAssembly * pDomainAssembly = pDomain->LoadDomainAssembly(&spec, pAssemblyHolder, FILE_LOAD_BEGIN); @@ -376,71 +341,6 @@ HRESULT CEECompileInfo::LoadAssemblyByPath( return hr; } - -#ifdef FEATURE_COMINTEROP -HRESULT CEECompileInfo::LoadTypeRefWinRT( - IMDInternalImport *pAssemblyImport, - mdTypeRef ref, - CORINFO_ASSEMBLY_HANDLE *pHandle) -{ - STANDARD_VM_CONTRACT; - - HRESULT hr = S_OK; - - ReleaseHolder pAssemblyName; - - COOPERATIVE_TRANSITION_BEGIN(); - - EX_TRY - { - Assembly *pAssembly; - - mdToken tkResolutionScope; - if(FAILED(pAssemblyImport->GetResolutionScopeOfTypeRef(ref, &tkResolutionScope))) - hr = S_FALSE; - else if(TypeFromToken(tkResolutionScope) == mdtAssemblyRef) - { - DWORD dwAssemblyRefFlags; - IfFailThrow(pAssemblyImport->GetAssemblyRefProps(tkResolutionScope, NULL, NULL, - NULL, NULL, - NULL, NULL, &dwAssemblyRefFlags)); - if (IsAfContentType_WindowsRuntime(dwAssemblyRefFlags)) - { - LPCSTR psznamespace; - LPCSTR pszname; - IfFailThrow(pAssemblyImport->GetNameOfTypeRef(ref, &psznamespace, &pszname)); - AssemblySpec spec; - spec.InitializeSpec(tkResolutionScope, pAssemblyImport, NULL); - spec.SetWindowsRuntimeType(psznamespace, pszname); - - _ASSERTE(spec.HasBindableIdentity()); - - pAssembly = spec.LoadAssembly(FILE_LOADED); - - // - // Return the module handle - // - - *pHandle = CORINFO_ASSEMBLY_HANDLE(pAssembly); - } - else - { - hr = S_FALSE; - } - } - else - { - hr = S_FALSE; - } - } - EX_CATCH_HRESULT(hr); - - COOPERATIVE_TRANSITION_END(); - - return hr; -} -#endif - BOOL CEECompileInfo::IsInCurrentVersionBubble(CORINFO_MODULE_HANDLE hModule) { WRAPPER_NO_CONTRACT; @@ -1383,38 +1283,17 @@ void CEECompileInfo::EncodeModuleAsIndex(CORINFO_MODULE_HANDLE fromHandle, if (!pRefCache) ThrowOutOfMemory(); + result = pRefCache->m_sAssemblyRefMap.LookupValue((UPTR)assembly, NULL); - if (!assembly->GetManifestFile()->HasBindableIdentity()) - { - // If the module that we'd like to encode for a later fixup doesn't have - // a bindable identity, then this will fail at runtime. So, we ask the - // compilation domain for a matching assembly with a bindable identity. - // This is possible because this module must have been bound in the past, - // and the compilation domain will keep track of at least one corresponding - // bindable identity. - AssemblySpec defSpec; - defSpec.InitializeSpec(assembly->GetManifestFile()); - - AssemblySpec* pRefSpec = pDomain->FindAssemblyRefSpecForDefSpec(&defSpec); - _ASSERTE(pRefSpec != nullptr); - - IfFailThrow(pRefSpec->EmitToken(pAssemblyEmit, &token, TRUE, TRUE)); - token += fromModule->GetAssemblyRefMax(); - } + if (result == (UPTR)INVALIDENTRY) + token = fromModule->FindAssemblyRef(assembly); else - { - result = pRefCache->m_sAssemblyRefMap.LookupValue((UPTR)assembly, NULL); - - if (result == (UPTR)INVALIDENTRY) - token = fromModule->FindAssemblyRef(assembly); - else - token = (mdAssemblyRef) result; + token = (mdAssemblyRef) result; - if (IsNilToken(token)) - { - token = fromAssembly->AddAssemblyRef(assembly, pAssemblyEmit); - token += fromModule->GetAssemblyRefMax(); - } + if (IsNilToken(token)) + { + token = fromAssembly->AddAssemblyRef(assembly, pAssemblyEmit); + token += fromModule->GetAssemblyRefMax(); } *pIndex = RidFromToken(token); @@ -5050,24 +4929,6 @@ static void SpecializeEqualityComparer(SString& ss, Instantiation& inst) } } -#ifdef FEATURE_COMINTEROP -// Instantiation of WinRT types defined in non-WinRT module. This check is required to generate marshaling stubs for -// instantiations of shadow WinRT types like EventHandler in mscorlib. -static BOOL IsInstantationOfShadowWinRTType(MethodTable * pMT) -{ - STANDARD_VM_CONTRACT; - - Instantiation inst = pMT->GetInstantiation(); - for (DWORD i = 0; i < inst.GetNumArgs(); i++) - { - TypeHandle th = inst[i]; - if (th.IsProjectedFromWinRT() && !th.GetModule()->IsWindowsRuntimeModule()) - return TRUE; - } - return FALSE; -} -#endif - void CEEPreloader::ApplyTypeDependencyProductionsForType(TypeHandle t) { STANDARD_VM_CONTRACT; @@ -5081,52 +4942,6 @@ void CEEPreloader::ApplyTypeDependencyProductionsForType(TypeHandle t) if (!pMT->HasInstantiation() || pMT->ContainsGenericVariables()) return; -#ifdef FEATURE_COMINTEROP - // At run-time, generic redirected interfaces and delegates need matching instantiations - // of other types/methods in order to be marshaled across the interop boundary. - if (m_image->GetModule()->IsWindowsRuntimeModule() || IsInstantationOfShadowWinRTType(pMT)) - { - // We only apply WinRT dependencies when compiling .winmd assemblies since redirected - // types are heavily used in non-WinRT code as well and would bloat native images. - if (pMT->IsLegalNonArrayWinRTType()) - { - TypeHandle thWinRT; - WinMDAdapter::RedirectedTypeIndex index; - if (WinRTInterfaceRedirector::ResolveRedirectedInterface(pMT, &index)) - { - // redirected interface needs the mscorlib-local definition of the corresponding WinRT type - MethodTable *pWinRTMT = WinRTInterfaceRedirector::GetWinRTTypeForRedirectedInterfaceIndex(index); - thWinRT = TypeHandle(pWinRTMT); - - // and matching stub methods - WORD wNumSlots = pWinRTMT->GetNumVirtuals(); - for (WORD i = 0; i < wNumSlots; i++) - { - MethodDesc *pAdapterMD = WinRTInterfaceRedirector::GetStubMethodForRedirectedInterface( - index, - i, - TypeHandle::Interop_NativeToManaged, - FALSE, - pMT->GetInstantiation()); - - TriageMethodForZap(pAdapterMD, TRUE); - } - } - if (WinRTDelegateRedirector::ResolveRedirectedDelegate(pMT, &index)) - { - // redirected delegate needs the mscorlib-local definition of the corresponding WinRT type - thWinRT = TypeHandle(WinRTDelegateRedirector::GetWinRTTypeForRedirectedDelegateIndex(index)); - } - - if (!thWinRT.IsNull()) - { - thWinRT = thWinRT.Instantiate(pMT->GetInstantiation()); - TriageTypeForZap(thWinRT, TRUE); - } - } - } -#endif // FEATURE_COMINTEROP - pMT = pMT->GetCanonicalMethodTable(); // The TypeDependencyAttribute attribute is currently only allowed on mscorlib types @@ -5618,36 +5433,6 @@ void CEEPreloader::ExpandTypeDependencies(TypeHandle th) TriageTypeForZap(pMT->GetCanonicalMethodTable(), TRUE); } - if (pMT->SupportsGenericInterop(TypeHandle::Interop_ManagedToNative)) - { - MethodTable::IntroducedMethodIterator itr(pMT->GetCanonicalMethodTable()); - for (/**/; itr.IsValid(); itr.Next()) - { - MethodDesc *pMD = itr.GetMethodDesc(); - - if (!pMD->HasMethodInstantiation()) - { - if (pMT->IsInterface() || !pMD->IsSharedByGenericInstantiations()) - { - pMD = MethodDesc::FindOrCreateAssociatedMethodDesc( - pMD, - pMT, - FALSE, // forceBoxedEntryPoint - Instantiation(), // methodInst - FALSE, // allowInstParam - TRUE); // forceRemotableMethod - } - else - { - _ASSERTE(pMT->IsDelegate()); - pMD = InstantiatedMethodDesc::FindOrCreateExactClassMethod(pMT, pMD); - } - - AddToUncompiledMethods(pMD, TRUE); - } - } - } - // Make sure parent type is saved TriageTypeForZap(pMT->GetParentMethodTable(), TRUE); @@ -6084,19 +5869,7 @@ static void SetStubMethodDescOnInteropMethodDesc(MethodDesc* pInteropMD, MethodD } else { -#ifdef FEATURE_COMINTEROP - // We don't currently NGEN both the P/Invoke and WinRT stubs for WinRT delegates. - // If that changes, this function will need an extra parameter to tell what kind - // of stub is being passed. - if (pInteropMD->GetMethodTable()->IsWinRTDelegate()) - { - pDelegateClass->m_pComPlusCallInfo->m_pStubMD.SetValue(pStubMD); - } - else -#endif // FEATURE_COMINTEROP - { - pDelegateClass->m_pForwardStubMD = pStubMD; - } + pDelegateClass->m_pForwardStubMD = pStubMD; } } else @@ -6212,37 +5985,17 @@ void CEEPreloader::GenerateMethodStubs( MethodTable* pMT = pMD->GetMethodTable(); CONSISTENCY_CHECK(pMT->IsDelegate()); - // we can filter out non-WinRT generic delegates right off the top - if (!pMD->HasClassOrMethodInstantiation() || pMT->IsProjectedFromWinRT() -#ifdef FEATURE_COMINTEROP - || WinRTTypeNameConverter::IsRedirectedType(pMT) -#endif // FEATURE_COMINTEROP - ) + if (!pMD->HasClassOrMethodInstantiation()) { if (COMDelegate::IsDelegateInvokeMethod(pMD)) // build forward stub { -#ifdef FEATURE_COMINTEROP - if ((pMT->IsProjectedFromWinRT() || WinRTTypeNameConverter::IsRedirectedType(pMT)) && - (!pMT->HasInstantiation() || pMT->SupportsGenericInterop(TypeHandle::Interop_ManagedToNative))) // filter out shared generics - { - // Build the stub for all WinRT delegates, these will definitely be used for interop. - if (pMT->IsLegalNonArrayWinRTType()) - { - COMDelegate::PopulateComPlusCallInfo(pMT); - pStubMD = COMDelegate::GetILStubMethodDesc((EEImplMethodDesc *)pMD, dwNGenStubFlags); - } - } - else -#endif // FEATURE_COMINTEROP - { - // Build the stub only if the delegate is decorated with UnmanagedFunctionPointerAttribute. - // Forward delegate stubs are rare so we require this opt-in to avoid bloating NGEN images. + // Build the stub only if the delegate is decorated with UnmanagedFunctionPointerAttribute. + // Forward delegate stubs are rare so we require this opt-in to avoid bloating NGEN images. - if (S_OK == pMT->GetMDImport()->GetCustomAttributeByName( - pMT->GetCl(), g_UnmanagedFunctionPointerAttribute, NULL, NULL)) - { - pStubMD = COMDelegate::GetILStubMethodDesc((EEImplMethodDesc *)pMD, dwNGenStubFlags); - } + if (S_OK == pMT->GetMDImport()->GetCustomAttributeByName( + pMT->GetCl(), g_UnmanagedFunctionPointerAttribute, NULL, NULL)) + { + pStubMD = COMDelegate::GetILStubMethodDesc((EEImplMethodDesc *)pMD, dwNGenStubFlags); } } } @@ -6284,8 +6037,8 @@ void CEEPreloader::GenerateMethodStubs( // if (pMD->IsEEImpl() && COMDelegate::IsDelegateInvokeMethod(pMD)) { - // Reverse P/Invoke is not supported for generic methods and WinRT delegates - if (!pMD->HasClassOrMethodInstantiation() && !pMD->GetMethodTable()->IsProjectedFromWinRT()) + // Reverse P/Invoke is not supported for generic methods + if (!pMD->HasClassOrMethodInstantiation()) { EX_TRY { @@ -6953,102 +6706,43 @@ HRESULT CompilationDomain::AddDependency(AssemblySpec *pRefSpec, pRefSpec = &spec; } -#ifdef FEATURE_COMINTEROP - // Only cache ref specs that have a unique identity. This is needed to avoid caching - // things like WinRT type specs, which would benefit very little from being cached. - if (!pRefSpec->HasUniqueIdentity()) - { - // Successful bind of a reference with a non-unique assembly identity. - _ASSERTE(pRefSpec->IsContentType_WindowsRuntime()); - - AssemblySpec defSpec; - if (pFile != NULL) - { - defSpec.InitializeSpec(pFile); - - // Windows Runtime Native Image binding depends on details exclusively described by the definition winmd file. - // Therefore we can actually drop the existing ref spec here entirely. - // Also, Windows Runtime Native Image binding uses the simple name of the ref spec as the - // resolution rule for PreBind when finding definition assemblies. - // See comment on CLRPrivBinderWinRT::PreBind for further details. - pRefSpec = &defSpec; - } - - // Unfortunately, we don't have any choice regarding failures (pFile == NULL) because - // there is no value to canonicalize on (i.e., a def spec created from a non-NULL - // pFile) and so we must cache all non-unique-assembly-id failures. - const AssemblySpecDefRefMapEntry * pEntry = m_dependencyDefRefMap.LookupPtr(&defSpec); - if (pFile == NULL || pEntry == NULL) - { - mdAssemblyRef refToken = mdAssemblyRefNil; - IfFailRet(pRefSpec->EmitToken(m_pEmit, &refToken, TRUE, TRUE)); - - mdAssemblyRef defToken = mdAssemblyRefNil; - if (pFile != NULL) - { - IfFailRet(defSpec.EmitToken(m_pEmit, &defToken, TRUE, TRUE)); + _ASSERTE(pRefSpec->HasUniqueIdentity()); - NewHolder pNewDefSpec = new AssemblySpec(); - pNewDefSpec->CopyFrom(&defSpec); - pNewDefSpec->CloneFields(); + // + // See if we've already added the contents of the ref + // Else, emit token for the ref + // - NewHolder pNewRefSpec = new AssemblySpec(); - pNewRefSpec->CopyFrom(pRefSpec); - pNewRefSpec->CloneFields(); + if (m_pDependencyRefSpecs->Store(pRefSpec)) + return S_OK; - _ASSERTE(m_dependencyDefRefMap.LookupPtr(pNewDefSpec) == NULL); + mdAssemblyRef refToken; + IfFailRet(pRefSpec->EmitToken(m_pEmit, &refToken)); - AssemblySpecDefRefMapEntry e; - e.m_pDef = pNewDefSpec; - e.m_pRef = pNewRefSpec; - m_dependencyDefRefMap.Add(e); + // + // Make a spec for the bound assembly + // - pNewDefSpec.SuppressRelease(); - pNewRefSpec.SuppressRelease(); - } + mdAssemblyRef defToken = mdAssemblyRefNil; - IfFailRet(AddDependencyEntry(pFile, refToken, defToken)); - } - } - else -#endif // FEATURE_COMINTEROP + // All dependencies of a shared assembly need to be shared. So for a shared + // assembly, we want to remember the missing assembly ref during ngen, so that + // we can probe eagerly for the dependency at load time, and make sure that + // it is loaded as shared. + // In such a case, pFile will be NULL + if (pFile) { - // - // See if we've already added the contents of the ref - // Else, emit token for the ref - // + AssemblySpec assemblySpec; + assemblySpec.InitializeSpec(pFile); - if (m_pDependencyRefSpecs->Store(pRefSpec)) - return S_OK; - - mdAssemblyRef refToken; - IfFailRet(pRefSpec->EmitToken(m_pEmit, &refToken)); - - // - // Make a spec for the bound assembly - // - - mdAssemblyRef defToken = mdAssemblyRefNil; - - // All dependencies of a shared assembly need to be shared. So for a shared - // assembly, we want to remember the missing assembly ref during ngen, so that - // we can probe eagerly for the dependency at load time, and make sure that - // it is loaded as shared. - // In such a case, pFile will be NULL - if (pFile) - { - AssemblySpec assemblySpec; - assemblySpec.InitializeSpec(pFile); - - IfFailRet(assemblySpec.EmitToken(m_pEmit, &defToken)); - } + IfFailRet(assemblySpec.EmitToken(m_pEmit, &defToken)); + } - // - // Add the entry. Include the PEFile if we are not doing explicit bindings. - // + // + // Add the entry. Include the PEFile if we are not doing explicit bindings. + // - IfFailRet(AddDependencyEntry(pFile, refToken, defToken)); - } + IfFailRet(AddDependencyEntry(pFile, refToken, defToken)); return S_OK; } @@ -7160,21 +6854,11 @@ PEAssembly *CompilationDomain::BindAssemblySpec( // // Record missing dependencies // -#ifdef FEATURE_COMINTEROP - if (!g_fNGenWinMDResilient || pSpec->HasUniqueIdentity()) -#endif - { - IfFailThrow(AddDependency(pSpec, NULL)); - } + IfFailThrow(AddDependency(pSpec, NULL)); } EX_END_HOOK -#ifdef FEATURE_COMINTEROP - if (!g_fNGenWinMDResilient || pSpec->HasUniqueIdentity()) -#endif - { - IfFailThrow(AddDependency(pSpec, pFile)); - } + IfFailThrow(AddDependency(pSpec, pFile)); return pFile; } @@ -7227,49 +6911,6 @@ HRESULT #ifdef CROSSGEN_COMPILE -HRESULT CompilationDomain::SetPlatformWinmdPaths(LPCWSTR pwzPlatformWinmdPaths) -{ - STANDARD_VM_CONTRACT; - -#ifdef FEATURE_COMINTEROP - // Create the array list on the heap since it will be passed off for the Crossgen RoResolveNamespace mockup to keep for the life of the process - StringArrayList *saPaths = new StringArrayList(); - - SString strPaths(pwzPlatformWinmdPaths); - if (!strPaths.IsEmpty()) - { - for (SString::Iterator i = strPaths.Begin(); i != strPaths.End(); ) - { - // Skip any leading spaces or semicolons - if (strPaths.Skip(i, W(';'))) - { - continue; - } - - SString::Iterator iEnd = i; // Where current assembly name ends - SString::Iterator iNext; // Where next assembly name starts - if (strPaths.Find(iEnd, W(';'))) - { - iNext = iEnd + 1; - } - else - { - iNext = iEnd = strPaths.End(); - } - - _ASSERTE(i < iEnd); - if(i != iEnd) - { - saPaths->Append(SString(strPaths, i, iEnd)); - } - i = iNext; - } - } - Crossgen::SetFirstPartyWinMDPaths(saPaths); -#endif // FEATURE_COMINTEROP - - return S_OK; -} #ifdef FEATURE_READYTORUN_COMPILER diff --git a/src/coreclr/src/vm/compile.h b/src/coreclr/src/vm/compile.h index aaa25cf..7298b75 100644 --- a/src/coreclr/src/vm/compile.h +++ b/src/coreclr/src/vm/compile.h @@ -206,13 +206,6 @@ class CEECompileInfo : public ICorCompileInfo BOOL fExplicitBindToNativeImage, CORINFO_ASSEMBLY_HANDLE *pHandle); - -#ifdef FEATURE_COMINTEROP - HRESULT LoadTypeRefWinRT(IMDInternalImport *pAssemblyImport, - mdTypeRef ref, - CORINFO_ASSEMBLY_HANDLE *pHandle); -#endif - BOOL IsInCurrentVersionBubble(CORINFO_MODULE_HANDLE hModule); HRESULT LoadAssemblyModule(CORINFO_ASSEMBLY_HANDLE assembly, @@ -840,10 +833,6 @@ class CompilationDomain : public AppDomain, HRESULT GetDependencies(CORCOMPILE_DEPENDENCY **ppDependencies, DWORD *cDependencies) DAC_EMPTY_RET(E_FAIL); -#ifdef CROSSGEN_COMPILE - HRESULT SetPlatformWinmdPaths(LPCWSTR pwzPlatformWinmdPaths) DAC_EMPTY_RET(E_FAIL); -#endif - void SetDependencyEmitter(IMetaDataAssemblyEmit *pEmitter); }; diff --git a/src/coreclr/src/vm/comtoclrcall.cpp b/src/coreclr/src/vm/comtoclrcall.cpp index 5f9c7ab..7968613 100644 --- a/src/coreclr/src/vm/comtoclrcall.cpp +++ b/src/coreclr/src/vm/comtoclrcall.cpp @@ -336,16 +336,6 @@ OBJECTREF COMToCLRGetObjectAndTarget_Virtual(ComCallWrapper * pWrap, MethodDesc // this method represents an interface method and not an IClassX method. *ppManagedTargetOut = pCMD->GetCallMethodDesc()->GetSingleCallableAddrOfCode(); } - else if (pWrap->IsAggregated() && pWrap->GetComCallWrapperTemplate()->GetClassType().IsExportedToWinRT()) - { - // we know the slot number for this method desc, grab the actual - // address from the vtable for this slot. The slot number should - // remain the same through out the heirarchy. - // - // This is the WinRT inheritance case where we want to always call the method as - // most recently implemented in the managed world. - *ppManagedTargetOut = pWrap->GetComCallWrapperTemplate()->GetClassType().GetMethodTable()->GetSlot(pCMD->GetSlot()); - } else { // we know the slot number for this method desc, grab the actual @@ -419,19 +409,12 @@ void COMToCLRWorkerBody_Rare(Thread * pThread, ComMethodFrame * pFrame, ComCallW maskedFlags &= ~(enum_NativeR4Retval|enum_NativeR8Retval); - CONSISTENCY_CHECK(maskedFlags != ( enum_IsWinRTCtor|enum_IsVirtual)); - CONSISTENCY_CHECK(maskedFlags != (enum_IsDelegateInvoke|enum_IsWinRTCtor|enum_IsVirtual)); - CONSISTENCY_CHECK(maskedFlags != (enum_IsDelegateInvoke|enum_IsWinRTCtor )); switch (maskedFlags) { case enum_IsDelegateInvoke|enum_IsVirtual: case enum_IsDelegateInvoke: pObject = COMToCLRGetObjectAndTarget_Delegate(pWrap, &pManagedTarget); break; case enum_IsVirtual: pObject = COMToCLRGetObjectAndTarget_Virtual(pWrap, pRealMD, pCMD, &pManagedTarget); break; case 0: pObject = COMToCLRGetObjectAndTarget_NonVirtual(pWrap, pRealMD, pCMD, &pManagedTarget); break; - case enum_IsWinRTCtor: - if (!COMToCLRGetObjectAndTarget_WinRTCtor(pThread, pRealMD, pCMD, &pManagedTarget, &pObject, pRetValOut)) - return; - break; default: UNREACHABLE(); } @@ -498,25 +481,17 @@ void COMToCLRWorkerBody( DWORD mask = ( enum_IsDelegateInvoke | - enum_IsWinRTCtor | enum_IsVirtual | enum_NativeR4Retval | enum_NativeR8Retval); DWORD maskedFlags = pCMD->GetFlags() & mask; - CONSISTENCY_CHECK(maskedFlags != ( enum_IsWinRTCtor|enum_IsVirtual)); - CONSISTENCY_CHECK(maskedFlags != (enum_IsDelegateInvoke|enum_IsWinRTCtor|enum_IsVirtual)); - CONSISTENCY_CHECK(maskedFlags != (enum_IsDelegateInvoke|enum_IsWinRTCtor )); switch (maskedFlags) { case enum_IsDelegateInvoke|enum_IsVirtual: case enum_IsDelegateInvoke: pObject = COMToCLRGetObjectAndTarget_Delegate(pWrap, &pManagedTarget); break; case enum_IsVirtual: pObject = COMToCLRGetObjectAndTarget_Virtual(pWrap, pRealMD, pCMD, &pManagedTarget); break; case 0: pObject = COMToCLRGetObjectAndTarget_NonVirtual(pWrap, pRealMD, pCMD, &pManagedTarget); break; - case enum_IsWinRTCtor: - if (!COMToCLRGetObjectAndTarget_WinRTCtor(pThread, pRealMD, pCMD, &pManagedTarget, &pObject, pRetValOut)) - return; - break; default: COMToCLRWorkerBody_Rare(pThread, pFrame, pWrap, pRealMD, pCMD, maskedFlags, pRetValOut); return; @@ -728,7 +703,7 @@ static UINT64 __stdcall FieldCallWorker(Thread *pThread, ComMethodFrame* pFrame) { // Transform the exception into an HRESULT. This also sets up // an IErrorInfo on the current thread for the exception. - hrRetVal = SetupErrorInfo(pThrowable, pFrame->GetComCallMethodDesc()); + hrRetVal = SetupErrorInfo(pThrowable); } } @@ -835,7 +810,7 @@ PCODE ComCallMethodDesc::CreateCOMToCLRStub(DWORD dwStubFlags, MethodDesc **ppSt else { // if this represents a ctor or static, use the class method (i.e. the actual ctor or static) - MethodDesc *pMD = ((IsWinRTCtor() || IsWinRTStatic()) ? GetMethodDesc() : GetCallMethodDesc()); + MethodDesc *pMD = GetCallMethodDesc(); // first see if we have an NGENed stub pStubMD = GetStubMethodDescFromInteropMethodDesc(pMD, dwStubFlags); @@ -982,7 +957,7 @@ void ComCallMethodDesc::InitRuntimeNativeInfo(MethodDesc *pStubMD) } #endif //CROSSGEN_COMPILE -void ComCallMethodDesc::InitMethod(MethodDesc *pMD, MethodDesc *pInterfaceMD, BOOL fRedirectedInterface /* = FALSE */) +void ComCallMethodDesc::InitMethod(MethodDesc *pMD, MethodDesc *pInterfaceMD) { CONTRACTL { @@ -1004,27 +979,6 @@ void ComCallMethodDesc::InitMethod(MethodDesc *pMD, MethodDesc *pInterfaceMD, BO m_pwStubStackSlotOffsets = NULL; #endif // TARGET_X86 - if (fRedirectedInterface) - m_flags |= enum_IsWinRTRedirected; - - // check whether this is a WinRT ctor/static/event method - MethodDesc *pCallMD = GetCallMethodDesc(); - MethodTable *pCallMT = pCallMD->GetMethodTable(); - if (pCallMT->IsProjectedFromWinRT() || pCallMT->IsExportedToWinRT()) - { - m_flags |= enum_IsWinRTCall; - - if (pMD->IsCtor()) - { - m_flags |= enum_IsWinRTCtor; - } - else - { - if (pMD->IsStatic()) - m_flags |= enum_IsWinRTStatic; - } - } - if (!SystemDomain::GetCurrentDomain()->IsCompilationDomain()) { // Initialize the native type information size of native stack, native retval flags, etc). @@ -1111,7 +1065,7 @@ void ComCallMethodDesc::InitNativeInfo() ReadBestFitCustomAttribute(fsig.GetModule(), pFD->GetEnclosingMethodTable()->GetCl(), &BestFit, &ThrowOnUnmappableChar); MarshalInfo info(fsig.GetModule(), fsig.GetArgProps(), fsig.GetSigTypeContext(), pFD->GetMemberDef(), MarshalInfo::MARSHAL_SCENARIO_COMINTEROP, - (CorNativeLinkType)0, (CorNativeLinkFlags)0, + (CorNativeLinkType)0, (CorNativeLinkFlags)0, FALSE, 0, fsig.NumFixedArgs(), BestFit, ThrowOnUnmappableChar, FALSE, TRUE, NULL, FALSE #ifdef _DEBUG , szDebugName, szDebugClassName, 0 @@ -1179,18 +1133,10 @@ void ComCallMethodDesc::InitNativeInfo() } #endif - BOOL WinRTType = pMT->IsProjectedFromWinRT(); - // Look up the best fit mapping info via Assembly & Interface level attributes BOOL BestFit = TRUE; BOOL ThrowOnUnmappableChar = FALSE; - - // Marshaling is fully described by the parameter type in WinRT. BestFit custom attributes - // are not going to affect the marshaling behavior. - if (!WinRTType) - { - ReadBestFitCustomAttribute(pMD, &BestFit, &ThrowOnUnmappableChar); - } + ReadBestFitCustomAttribute(pMD, &BestFit, &ThrowOnUnmappableChar); int numArgs = msig.NumFixedArgs(); @@ -1216,7 +1162,7 @@ void ComCallMethodDesc::InitNativeInfo() nativeArgSize += StackElemSize(sizeof(LCID)); MarshalInfo info(msig.GetModule(), msig.GetArgProps(), msig.GetSigTypeContext(), params[iArg], - WinRTType ? MarshalInfo::MARSHAL_SCENARIO_WINRT : MarshalInfo::MARSHAL_SCENARIO_COMINTEROP, + MarshalInfo::MARSHAL_SCENARIO_COMINTEROP, (CorNativeLinkType)0, (CorNativeLinkFlags)0, TRUE, iArg, numArgs, BestFit, ThrowOnUnmappableChar, FALSE, TRUE, pMD, FALSE #ifdef _DEBUG @@ -1234,12 +1180,6 @@ void ComCallMethodDesc::InitNativeInfo() info.SetupArgumentSizes(); nativeArgSize += info.GetNativeArgSize(); - - if (info.GetMarshalType() == MarshalInfo::MARSHAL_TYPE_HIDDENLENGTHARRAY) - { - // count the hidden length - nativeArgSize += info.GetHiddenLengthParamStackSize(); - } } ++iArg; @@ -1278,7 +1218,7 @@ void ComCallMethodDesc::InitNativeInfo() { MarshalInfo info(msig.GetModule(), msig.GetReturnProps(), msig.GetSigTypeContext(), params[0], - WinRTType ? MarshalInfo::MARSHAL_SCENARIO_WINRT : MarshalInfo::MARSHAL_SCENARIO_COMINTEROP, + MarshalInfo::MARSHAL_SCENARIO_COMINTEROP, (CorNativeLinkType)0, (CorNativeLinkFlags)0, FALSE, 0, numArgs, BestFit, ThrowOnUnmappableChar, FALSE, TRUE, pMD, FALSE #ifdef _DEBUG @@ -1298,12 +1238,6 @@ void ComCallMethodDesc::InitNativeInfo() // count the output by-ref argument nativeArgSize += sizeof(void *); - if (info.GetMarshalType() == MarshalInfo::MARSHAL_TYPE_HIDDENLENGTHARRAY) - { - // count the output hidden length - nativeArgSize += info.GetHiddenLengthParamStackSize(); - } - goto Done; } #endif // TARGET_X86 @@ -1419,29 +1353,9 @@ void ComCall::PopulateComCallMethodDesc(ComCallMethodDesc *pCMD, DWORD *pdwStubF MethodDesc *pMD = pCMD->GetCallMethodDesc(); _ASSERTE(IsMethodVisibleFromCom(pMD) && "Calls are not permitted on this member since it isn't visible from COM. The only way you can have reached this code path is if your native interface doesn't match the managed interface."); - MethodTable *pMT = pMD->GetMethodTable(); - if (pMT->IsProjectedFromWinRT() || pMT->IsExportedToWinRT() || pCMD->IsWinRTRedirectedMethod()) - { - dwStubFlags |= NDIRECTSTUB_FL_WINRT; - - if (pMT->IsDelegate()) - dwStubFlags |= NDIRECTSTUB_FL_WINRTDELEGATE; - else if (pCMD->IsWinRTCtor()) - { - dwStubFlags |= NDIRECTSTUB_FL_WINRTCTOR; - } - else - { - if (pCMD->IsWinRTStatic()) - dwStubFlags |= NDIRECTSTUB_FL_WINRTSTATIC; - } - } - else - { - // Marshaling is fully described by the parameter type in WinRT. BestFit custom attributes - // are not going to affect the marshaling behavior. - ReadBestFitCustomAttribute(pMD, &BestFit, &ThrowOnUnmappableChar); - } + // Marshaling is fully described by the parameter type in WinRT. BestFit custom attributes + // are not going to affect the marshaling behavior. + ReadBestFitCustomAttribute(pMD, &BestFit, &ThrowOnUnmappableChar); } if (BestFit) diff --git a/src/coreclr/src/vm/comtoclrcall.h b/src/coreclr/src/vm/comtoclrcall.h index f39f5a2..88593d8 100644 --- a/src/coreclr/src/vm/comtoclrcall.h +++ b/src/coreclr/src/vm/comtoclrcall.h @@ -33,10 +33,10 @@ enum ComCallFlags enum_HasMarshalError = 0x0400, // The signature is not marshalable and m_StackBytes is a guess enum_IsDelegateInvoke = 0x0800, // The method is an 'Invoke' on a delegate // unused = 0x1000, - enum_IsWinRTCall = 0x2000, // The method is declared on a WinRT interface/delegate - enum_IsWinRTCtor = 0x4000, // The method is a WinRT constructor - enum_IsWinRTStatic = 0x8000, // The method is a WinRT static - enum_IsWinRTRedirected = 0x10000, // The method is declared on a redirected WinRT interface + // unused = 0x2000, + // unused = 0x4000, + // unused = 0x8000, + // unused = 0x10000 }; @@ -107,7 +107,7 @@ class ComCallMethodDesc public: // init method - void InitMethod(MethodDesc *pMD, MethodDesc *pInterfaceMD, BOOL fRedirectedInterface = FALSE); + void InitMethod(MethodDesc *pMD, MethodDesc *pInterfaceMD); // init field void InitField(FieldDesc* pField, BOOL isGetter); @@ -203,30 +203,6 @@ public: return m_flags & enum_IsDelegateInvoke; } - BOOL IsWinRTCall() - { - LIMITED_METHOD_CONTRACT; - return m_flags & enum_IsWinRTCall; - } - - BOOL IsWinRTCtor() - { - LIMITED_METHOD_CONTRACT; - return m_flags & enum_IsWinRTCtor; - } - - BOOL IsWinRTStatic() - { - LIMITED_METHOD_CONTRACT; - return m_flags & enum_IsWinRTStatic; - } - - BOOL IsWinRTRedirectedMethod() - { - LIMITED_METHOD_CONTRACT; - return m_flags & enum_IsWinRTRedirected; - } - BOOL IsNativeInfoInitialized() { LIMITED_METHOD_CONTRACT; diff --git a/src/coreclr/src/vm/corhost.cpp b/src/coreclr/src/vm/corhost.cpp index 15c2bd1..8025eda 100644 --- a/src/coreclr/src/vm/corhost.cpp +++ b/src/coreclr/src/vm/corhost.cpp @@ -38,10 +38,6 @@ #include "dwreport.h" #endif // !TARGET_UNIX -#ifdef FEATURE_COMINTEROP -#include "winrttypenameconverter.h" -#endif - #ifndef DACCESS_COMPILE extern void STDMETHODCALLTYPE EEShutDown(BOOL fIsDllUnloading); @@ -637,9 +633,6 @@ HRESULT CorHost2::CreateAppDomainWithManager( LPCWSTR pwzPlatformResourceRoots = NULL; LPCWSTR pwzAppPaths = NULL; LPCWSTR pwzAppNiPaths = NULL; -#ifdef FEATURE_COMINTEROP - LPCWSTR pwzAppLocalWinMD = NULL; -#endif for (int i = 0; i < nProperties; i++) { @@ -679,13 +672,6 @@ HRESULT CorHost2::CreateAppDomainWithManager( extern void ParseUseEntryPointFilter(LPCWSTR value); ParseUseEntryPointFilter(pPropertyValues[i]); } -#ifdef FEATURE_COMINTEROP - else - if (wcscmp(pPropertyNames[i], W("APP_LOCAL_WINMETADATA")) == 0) - { - pwzAppLocalWinMD = pPropertyValues[i]; - } -#endif } pDomain->SetNativeDllSearchDirectories(pwzNativeDllSearchDirectories); @@ -705,13 +691,6 @@ HRESULT CorHost2::CreateAppDomainWithManager( sAppNiPaths)); } -#ifdef FEATURE_COMINTEROP - if (WinRTSupported()) - { - pDomain->SetWinrtApplicationContext(pwzAppLocalWinMD); - } -#endif - *pAppDomainID=DefaultADID; m_fAppDomainCreated = TRUE; @@ -1125,7 +1104,7 @@ void SetupTLSForThread(Thread* pThread) void FreeClrDebugState(LPVOID pTlsData); #endif -// Called here from a thread detach or from destruction of a Thread object. +// Called here from a thread detach or from destruction of a Thread object. void ThreadDetaching() { // Can not cause memory allocation during thread detach, so no real contracts. @@ -1160,94 +1139,7 @@ void ThreadDetaching() HRESULT CorHost2::DllGetActivationFactory(DWORD appDomainID, LPCWSTR wszTypeName, IActivationFactory ** factory) { -#ifdef FEATURE_COMINTEROP_WINRT_MANAGED_ACTIVATION - // WinRT activation currently supported in default domain only - if (appDomainID != DefaultADID) - return HOST_E_INVALIDOPERATION; - - HRESULT hr = S_OK; - - Thread *pThread = GetThread(); - if (pThread == NULL) - { - pThread = SetupThreadNoThrow(&hr); - if (pThread == NULL) - { - return hr; - } - } - - return DllGetActivationFactoryImpl(NULL, wszTypeName, NULL, factory); -#else return E_NOTIMPL; -#endif } - -#ifdef FEATURE_COMINTEROP_WINRT_MANAGED_ACTIVATION - -HRESULT STDMETHODCALLTYPE DllGetActivationFactoryImpl(LPCWSTR wszAssemblyName, - LPCWSTR wszTypeName, - LPCWSTR wszCodeBase, - IActivationFactory ** factory) -{ - CONTRACTL - { - DISABLED(NOTHROW); - GC_TRIGGERS; - MODE_ANY; - ENTRY_POINT; - } - CONTRACTL_END; - - HRESULT hr = S_OK; - - BEGIN_ENTRYPOINT_NOTHROW; - - AppDomain* pDomain = SystemDomain::System()->DefaultDomain(); - _ASSERTE(pDomain); - - BEGIN_EXTERNAL_ENTRYPOINT(&hr); - { - GCX_COOP(); - - bool bIsPrimitive; - TypeHandle typeHandle = WinRTTypeNameConverter::LoadManagedTypeForWinRTTypeName(wszTypeName, /* pLoadBinder */ nullptr, &bIsPrimitive); - if (!bIsPrimitive && !typeHandle.IsNull() && !typeHandle.IsTypeDesc() && typeHandle.AsMethodTable()->IsExportedToWinRT()) - { - struct _gc { - OBJECTREF type; - } gc; - memset(&gc, 0, sizeof(gc)); - - - IActivationFactory* activationFactory; - GCPROTECT_BEGIN(gc); - - gc.type = typeHandle.GetManagedClassObject(); - - MethodDescCallSite mdcs(METHOD__WINDOWSRUNTIMEMARSHAL__GET_ACTIVATION_FACTORY_FOR_TYPE); - ARG_SLOT args[1] = { - ObjToArgSlot(gc.type) - }; - activationFactory = (IActivationFactory*)mdcs.Call_RetLPVOID(args); - - *factory = activationFactory; - - GCPROTECT_END(); - } - else - { - hr = COR_E_TYPELOAD; - } - } - END_EXTERNAL_ENTRYPOINT; - END_ENTRYPOINT_NOTHROW; - - return hr; -} - -#endif // !FEATURE_COMINTEROP_MANAGED_ACTIVATION - - #endif // !DACCESS_COMPILE diff --git a/src/coreclr/src/vm/crossgen/CMakeLists.txt b/src/coreclr/src/vm/crossgen/CMakeLists.txt index b532a9e..7a9ec51 100644 --- a/src/coreclr/src/vm/crossgen/CMakeLists.txt +++ b/src/coreclr/src/vm/crossgen/CMakeLists.txt @@ -133,7 +133,6 @@ set(VM_CROSSGEN_HEADERS ../fieldmarshaler.h ../genericdict.h ../generics.h - ../generics.inl ../hash.h ../ilinstrumentation.h ../ilmarshalers.h @@ -234,27 +233,16 @@ endif() if (CLR_CMAKE_TARGET_WIN32) list(APPEND VM_CROSSGEN_SOURCES ../classcompat.cpp - ../clrprivbinderwinrt.cpp - ../clrprivtypecachewinrt.cpp ../comtoclrcall.cpp ../clrtocomcall.cpp - ../crossgenroparsetypename.cpp - ../crossgenroresolvenamespace.cpp ../runtimecallablewrapper.cpp - ../winrthelpers.cpp - ../winrttypenameconverter.cpp ) list(APPEND VM_CROSSGEN_HEADERS ../classcompat.h - ../clrprivbinderwinrt.h - ../clrprivtypecachewinrt.h ../clrtocomcall.h ../comtoclrcall.h - ../crossgenroresolvenamespace.h ../runtimecallablewrapper.h - ../winrthelpers.h - ../winrttypenameconverter.h ) list(APPEND VM_CROSSGEN_SOURCES ${VM_CROSSGEN_HEADERS}) diff --git a/src/coreclr/src/vm/crossgenroparsetypename.cpp b/src/coreclr/src/vm/crossgenroparsetypename.cpp deleted file mode 100644 index af28672..0000000 --- a/src/coreclr/src/vm/crossgenroparsetypename.cpp +++ /dev/null @@ -1,494 +0,0 @@ -// 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: Enable parsing of parameterized and non-parameterized typenames -// -// Adapted from Windows sources. Modified to run on Windows version < Win8, so -// that we can use this in CrossGen. -// - -// -//----------------------------------------------------------------------------- - -#include "common.h" // precompiled header - -static const UINT32 g_uiMaxTypeName = 512; - -// Type name grammar: -// -// expression -> param -// -// pinterface_instance -> pinterface "<" params ">" -// { -// if (count(pinterface.params) != num) { error } -// } -// -// pinterface -> identifier "`" num -// -// params -> params "," param | param -// -// param -> identifier | pinterface_instance -// -// identifier -> all characters are allowed, except for white space, back tick, comma and left/right angle brackets. -// -// num -> [0-9]+ - -typedef enum -{ - TTT_PINTERFACE, - TTT_IDENTIFIER, - TTT_INVALID -} TYPENAME_TOKEN_TYPE; - -class TypeNameTokenizer -{ -public: - _When_(return == S_OK, _At_(pphstrTypeNameParts, __deref_out_ecount(*pdwPartsCount))) - _When_(return != S_OK, _At_(pphstrTypeNameParts, __deref_out)) - HRESULT TokenizeType(__in PCWSTR pszTypeName, __out DWORD *pdwPartsCount, SString **pphstrTypeNameParts); - - ~TypeNameTokenizer() - { - if (_sphstrTypeNameParts != nullptr) - delete[] _sphstrTypeNameParts; - } - -private: - HRESULT ParseNonParameterizedType(); - HRESULT ParseParameterizedType(); - - int CountTokens(); - TYPENAME_TOKEN_TYPE ReadNextToken(); - void SkipWhitespace(); - bool IsWhitespace(WCHAR ch); - bool TrimThenFetchAndCompareNextCharIfAny(__in WCHAR chExpectedSymbol); - bool TrimThenPeekAndCompareNextCharIfAny(__in WCHAR chExpectedSymbol); - HRESULT VerifyTrailingCloseBrackets(__in DWORD dwExpectedTrailingCloseBrackets); - - SString* _sphstrTypeNameParts; - WCHAR _pszTypeName[g_uiMaxTypeName]; - WCHAR *_pchTypeNamePtr; - WCHAR _pszCurrentToken[g_uiMaxTypeName]; - DWORD _cCurrentTokenParameters; - DWORD _cTokens; -}; - -_When_(return == S_OK, _At_(typeNameParts, __deref_out_ecount(*partsCount))) -_When_(return != S_OK, _At_(typeNameParts, __deref_out)) -__checkReturn extern "C" HRESULT WINAPI CrossgenRoParseTypeName( - __in SString* typeName, - __out DWORD *partsCount, - SString **typeNameParts) -{ - HRESULT hr = S_OK; - - // Clear output parameters. - *typeNameParts = nullptr; - *partsCount = 0; - - if (typeName->IsEmpty() /*|| typeName.HasEmbeddedNull() */) - { - hr = E_INVALIDARG; - } - - if (SUCCEEDED(hr)) - { - TypeNameTokenizer typeNameTokenizer; - hr = typeNameTokenizer.TokenizeType( - typeName->GetUnicode(), - partsCount, - typeNameParts); - } - - return hr; -} - -_When_(return == S_OK, _At_(pphstrTypeNameParts, __deref_out_ecount(*pdwPartsCount))) -_When_(return != S_OK, _At_(pphstrTypeNameParts, __deref_out)) -HRESULT TypeNameTokenizer::TokenizeType(__in PCWSTR pszTypeName, __out DWORD *pdwPartsCount, SString **pphstrTypeNameParts) -{ - _ASSERTE(pphstrTypeNameParts != nullptr); - _ASSERTE(pdwPartsCount != nullptr); - HRESULT hr = S_OK; - - _cTokens = 0; - hr = StringCchCopy(_pszTypeName, ARRAYSIZE(_pszTypeName), pszTypeName); - _pchTypeNamePtr = _pszTypeName; - - if (hr == STRSAFE_E_INSUFFICIENT_BUFFER) - { - hr = RO_E_METADATA_NAME_NOT_FOUND; - } - - if (SUCCEEDED(hr)) - { - *pdwPartsCount = CountTokens(); - - _sphstrTypeNameParts = new(nothrow) SString[*pdwPartsCount]; - if (_sphstrTypeNameParts == nullptr) - { - hr = E_OUTOFMEMORY; - } - } - - if (SUCCEEDED(hr)) - { - TYPENAME_TOKEN_TYPE tokenType = ReadNextToken(); - - if (tokenType == TTT_IDENTIFIER) - { - hr = ParseNonParameterizedType(); - } - else if (tokenType == TTT_PINTERFACE) - { - hr = ParseParameterizedType(); - } - else - { - hr = RO_E_METADATA_INVALID_TYPE_FORMAT; - } - } - - if (SUCCEEDED(hr)) - { - *pphstrTypeNameParts = _sphstrTypeNameParts; - _sphstrTypeNameParts = nullptr; - } - else - { - *pdwPartsCount = 0; - *pphstrTypeNameParts = nullptr; - } - - return hr; -} - -int TypeNameTokenizer::CountTokens() -{ - const size_t cTypeNameLength = wcslen(_pszTypeName); - int nCount = 1; - WCHAR ch; - - _ASSERTE(cTypeNameLength != 0); - - for (UINT32 nIndex = 0; nIndex < cTypeNameLength; nIndex++) - { - ch = _pszTypeName[nIndex]; - - if ((ch == W(',')) || (ch == W('<'))) - { - nCount++; - } - } - - return nCount; -} - -TYPENAME_TOKEN_TYPE TypeNameTokenizer::ReadNextToken() -{ - TYPENAME_TOKEN_TYPE tokenType = TTT_IDENTIFIER; - int nTokenIndex = 0; - WCHAR ch = *_pchTypeNamePtr; - - while ((ch != W('\0')) && - (ch != W('<')) && - (ch != W('>')) && - (ch != W(',')) && - (!IsWhitespace(ch))) - { - _pszCurrentToken[nTokenIndex++] = ch; - - if (ch == W('`')) - { - if (nTokenIndex > 1) - { - tokenType = TTT_PINTERFACE; - - // Store the pinterface's parameters count (limited to a single digit). - _pchTypeNamePtr++; - ch = *_pchTypeNamePtr; - - if (isdigit(ch)) - { - _pszCurrentToken[nTokenIndex++] = ch; - _cCurrentTokenParameters = ch - W('0'); - _pchTypeNamePtr++; - } - else - { - tokenType = TTT_INVALID; - } - } - else - { - // The back tick (`) was the first character in the token. - tokenType = TTT_INVALID; - } - - break; - } - - _pchTypeNamePtr++; - ch = *_pchTypeNamePtr; - } - - // Empty token is invalid. - if (nTokenIndex == 0) - { - tokenType = TTT_INVALID; - } - - - if ((tokenType == TTT_PINTERFACE) && (_cCurrentTokenParameters == 0)) - { - tokenType = TTT_INVALID; - } - - _pszCurrentToken[nTokenIndex] = W('\0'); - - return tokenType; -} - -bool TypeNameTokenizer::TrimThenPeekAndCompareNextCharIfAny(__in WCHAR chExpectedSymbol) -{ - // Trim leading spaces. - SkipWhitespace(); - - return (*_pchTypeNamePtr == chExpectedSymbol); -} - -bool TypeNameTokenizer::TrimThenFetchAndCompareNextCharIfAny(__in WCHAR chExpectedSymbol) -{ - bool fSymbolsMatch; - - // Trim leading spaces. - SkipWhitespace(); - - WCHAR ch = *_pchTypeNamePtr; - - // Do not move the typename pointer past the end of the typename string. - if (ch != W('\0')) - { - _pchTypeNamePtr++; - } - - fSymbolsMatch = (ch == chExpectedSymbol); - - // Trim trailing spaces. - SkipWhitespace(); - - return fSymbolsMatch; -} - -HRESULT TypeNameTokenizer::ParseNonParameterizedType() -{ - HRESULT hr = S_OK; - - // There should be no trailing symbols or spaces after a non-parameterized type. - if (!TrimThenFetchAndCompareNextCharIfAny(W('\0'))) - { - hr = RO_E_METADATA_INVALID_TYPE_FORMAT; - } - - if (SUCCEEDED(hr)) - { - _sphstrTypeNameParts[_cTokens++].Set(_pszCurrentToken); - //hr = WindowsCreateString(_pszCurrentToken, static_cast(wcslen(_pszCurrentToken)), &_sphstrTypeNameParts[_cTokens++]); - - //if (FAILED(hr)) - //{ - // _cTokens--; - //} - } - - //_ASSERTE(SUCCEEDED(hr) ? _cTokens == 1 : _cTokens == 0); - - return hr; -} - -HRESULT TypeNameTokenizer::ParseParameterizedType() -{ - HRESULT hr = S_OK; - - // For every pinterface in the typename (base and nested), there will be a corresponding entry in the - // anRemainingParameters array to hold the number of parameters that need to be matched for that pinterface. - // The count of parameters for a given pinterface is decremented after parsing each paramter and when the - // count reaches zero, the corresponding pinterface is considered completely parsed. - int nInnermostPinterfaceIndex = -1; - SArray anRemainingParameters; - DWORD dwExpectedTrailingCloseBrackets = 0; - TYPENAME_TOKEN_TYPE tokenType = TTT_PINTERFACE; - - do - { - switch (tokenType) - { - case TTT_PINTERFACE: - { - if (++nInnermostPinterfaceIndex > 0) - { - // This was a nested pinterface (i.e. a parameter of another pinterface), so we - // need to decrement the parameters count of its parent pinterface. - anRemainingParameters[nInnermostPinterfaceIndex - 1]--; - if (anRemainingParameters[nInnermostPinterfaceIndex - 1] == 0) - { - nInnermostPinterfaceIndex--; - } - } - - // Store pinterface's parameters count. - if (nInnermostPinterfaceIndex < (int)anRemainingParameters.GetCount()) - { - anRemainingParameters[nInnermostPinterfaceIndex] = _cCurrentTokenParameters; - } - else - { - anRemainingParameters.Append(_cCurrentTokenParameters); - } - - if (!TrimThenFetchAndCompareNextCharIfAny(W('<'))) - { - hr = RO_E_METADATA_INVALID_TYPE_FORMAT; - } - - dwExpectedTrailingCloseBrackets++; - } - break; - - case TTT_IDENTIFIER: - { - _ASSERTE(nInnermostPinterfaceIndex != -1); - _ASSERTE(anRemainingParameters[nInnermostPinterfaceIndex] != 0); - - anRemainingParameters[nInnermostPinterfaceIndex]--; - - if (anRemainingParameters[nInnermostPinterfaceIndex] == 0) - { - // This was the last parameter for the given pinterface. - nInnermostPinterfaceIndex--; - hr = VerifyTrailingCloseBrackets(1); - - if (SUCCEEDED(hr)) - { - dwExpectedTrailingCloseBrackets--; - - if (nInnermostPinterfaceIndex == -1) - { - // No more unparsed pinterfaces - hr = VerifyTrailingCloseBrackets(dwExpectedTrailingCloseBrackets); - - if (SUCCEEDED(hr)) - { - dwExpectedTrailingCloseBrackets = 0; - - if (!TrimThenFetchAndCompareNextCharIfAny(W('\0'))) - { - hr = RO_E_METADATA_INVALID_TYPE_FORMAT; - } - } - } - else - { - while (TrimThenPeekAndCompareNextCharIfAny(W('>'))) - { - if (dwExpectedTrailingCloseBrackets > 0) - { - TrimThenFetchAndCompareNextCharIfAny(W('>')); - dwExpectedTrailingCloseBrackets--; - } - else - { - hr = RO_E_METADATA_INVALID_TYPE_FORMAT; - break; - } - } - - // There are more parameters, so we expect a comma-separated list. - if (!TrimThenFetchAndCompareNextCharIfAny(W(','))) - { - hr = RO_E_METADATA_INVALID_TYPE_FORMAT; - } - } - } - } - else - { - // There are more parameters, so we expect a comma-separated list. - if (!TrimThenFetchAndCompareNextCharIfAny(W(','))) - { - hr = RO_E_METADATA_INVALID_TYPE_FORMAT; - } - } - } - break; - - default: - { - hr = RO_E_METADATA_INVALID_TYPE_FORMAT; - } - } - - // Store current token. - if (SUCCEEDED(hr)) - { - _sphstrTypeNameParts[_cTokens++].Set(_pszCurrentToken); - //hr = WindowsCreateString(_pszCurrentToken, static_cast(wcslen(_pszCurrentToken)), &_sphstrTypeNameParts[_cTokens++]); - - //if (FAILED(hr)) - //{ - // _cTokens--; - //} - } - - tokenType = ReadNextToken(); - - } while (SUCCEEDED(hr) && (nInnermostPinterfaceIndex != -1)); - - return hr; -} - -HRESULT TypeNameTokenizer::VerifyTrailingCloseBrackets(__in DWORD dwExpectedTrailingCloseBrackets) -{ - HRESULT hr = S_OK; - - for (DWORD dwClosingBracket = 0; dwClosingBracket < dwExpectedTrailingCloseBrackets; dwClosingBracket++) - { - if (!TrimThenFetchAndCompareNextCharIfAny(W('>'))) - { - hr = RO_E_METADATA_INVALID_TYPE_FORMAT; - } - } - - return hr; -} - -void TypeNameTokenizer::SkipWhitespace() -{ - while (IsWhitespace(*_pchTypeNamePtr)) - { - _pchTypeNamePtr++; - } -} - -bool TypeNameTokenizer::IsWhitespace(WCHAR ch) -{ - bool fIsWhitespace = false; - - switch (ch) - { - case ' ': - case '\t': - case '\r': - case '\f': - case '\n': - fIsWhitespace = true; - break; - } - - return fIsWhitespace; -} diff --git a/src/coreclr/src/vm/crossgenroresolvenamespace.cpp b/src/coreclr/src/vm/crossgenroresolvenamespace.cpp deleted file mode 100644 index 450e6bb..0000000 --- a/src/coreclr/src/vm/crossgenroresolvenamespace.cpp +++ /dev/null @@ -1,194 +0,0 @@ -// 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. - -//+---------------------------------------------------------------------------- -// - -// -// Adapted from Windows sources. Modified to run on Windows version < Win8, so -// that we can use this in CrossGen. -// - -// -//----------------------------------------------------------------------------- - -#include "common.h" -#include "crossgenroresolvenamespace.h" -#include "stringarraylist.h" - -namespace Crossgen -{ - -#define WINDOWS_NAMESPACE W("Windows") -#define WINDOWS_NAMESPACE_PREFIX WINDOWS_NAMESPACE W(".") -#define WINMD_FILE_EXTENSION_L W(".winmd") - -StringArrayList* g_wszWindowsNamespaceDirectories; -StringArrayList* g_wszUserNamespaceDirectories; - -BOOL -IsWindowsNamespace(const WCHAR * wszNamespace) -{ - LIMITED_METHOD_CONTRACT; - - if (wcsncmp(wszNamespace, WINDOWS_NAMESPACE_PREFIX, (_countof(WINDOWS_NAMESPACE_PREFIX) - 1)) == 0) - { - return TRUE; - } - else if (wcscmp(wszNamespace, WINDOWS_NAMESPACE) == 0) - { - return TRUE; - } - - return FALSE; -} - - -BOOL -DoesFileExist( - const WCHAR * wszFileName) -{ - LIMITED_METHOD_CONTRACT; - - BOOL fFileExists = TRUE; - DWORD dwFileAttributes; - dwFileAttributes = GetFileAttributesW(wszFileName); - - if ((dwFileAttributes == INVALID_FILE_ATTRIBUTES) || - (dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY)) - { - fFileExists = FALSE; - } - - return fFileExists; -} - - -HRESULT -FindNamespaceFileInDirectory( - const WCHAR * wszNamespace, - const WCHAR * wszDirectory, - DWORD * pcMetadataFiles, - SString ** ppMetadataFiles) -{ - LIMITED_METHOD_CONTRACT; - - if (wszDirectory == nullptr) - return ERROR_NOT_SUPPORTED; - - WCHAR wszFilePath[MAX_LONGPATH + 1]; - wcscpy_s( - wszFilePath, - _countof(wszFilePath), - wszDirectory); - - WCHAR * wszFirstFileNameChar = wszFilePath + wcslen(wszFilePath); - - // If there's no backslash, add one. - if (*(wszFirstFileNameChar - 1) != '\\') - *wszFirstFileNameChar++ = '\\'; - - WCHAR wszRemainingNamespace[MAX_PATH_FNAME +1]; - wcscpy_s( - wszRemainingNamespace, - _countof(wszRemainingNamespace), - wszNamespace); - - do - { - *wszFirstFileNameChar = W('\0'); - wcscat_s( - wszFilePath, - _countof(wszFilePath), - wszRemainingNamespace); - wcscat_s( - wszFilePath, - _countof(wszFilePath), - WINMD_FILE_EXTENSION_L); - - if (DoesFileExist(wszFilePath)) - { - *ppMetadataFiles = new SString(wszFilePath); - *pcMetadataFiles = 1; - return S_OK; - } - - WCHAR * wszLastDotChar = wcsrchr(wszRemainingNamespace, W('.')); - if (wszLastDotChar == nullptr) - { - *ppMetadataFiles = nullptr; - *pcMetadataFiles = 0; - return S_FALSE; - } - *wszLastDotChar = W('\0'); - } while (true); -} - - -__checkReturn -HRESULT WINAPI CrossgenRoResolveNamespace( - const LPCWSTR wszNamespace, - DWORD * pcMetadataFiles, - SString ** ppMetadataFiles) -{ - LIMITED_METHOD_CONTRACT; - HRESULT hr = S_OK; - - if (IsWindowsNamespace(wszNamespace)) - { - DWORD cAppPaths = g_wszWindowsNamespaceDirectories->GetCount(); - - for (DWORD i = 0; i < cAppPaths; i++) - { - // Returns S_FALSE on file not found so we continue proving app directory graph - IfFailRet(FindNamespaceFileInDirectory( - wszNamespace, - g_wszWindowsNamespaceDirectories->Get(i).GetUnicode(), - pcMetadataFiles, - ppMetadataFiles)); - - if (hr == S_OK) - { - return hr; - } - } - } - else - { - DWORD cAppPaths = g_wszUserNamespaceDirectories->GetCount(); - - for (DWORD i = 0; i < cAppPaths; i++) - { - // Returns S_FALSE on file not found so we continue proving app directory graph - IfFailRet(FindNamespaceFileInDirectory( - wszNamespace, - g_wszUserNamespaceDirectories->Get(i).GetUnicode(), - pcMetadataFiles, - ppMetadataFiles)); - - if (hr == S_OK) - { - return hr; - } - } - } - - return hr; -} // RoResolveNamespace - -void SetFirstPartyWinMDPaths(StringArrayList* saAppPaths) -{ - LIMITED_METHOD_CONTRACT; - - g_wszWindowsNamespaceDirectories = saAppPaths; -} - -void SetAppPaths(StringArrayList* saAppPaths) -{ - LIMITED_METHOD_CONTRACT; - - g_wszUserNamespaceDirectories = saAppPaths; -} - -}// Namespace Crossgen diff --git a/src/coreclr/src/vm/crossgenroresolvenamespace.h b/src/coreclr/src/vm/crossgenroresolvenamespace.h deleted file mode 100644 index b050b5e..0000000 --- a/src/coreclr/src/vm/crossgenroresolvenamespace.h +++ /dev/null @@ -1,27 +0,0 @@ -// 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. - -//+---------------------------------------------------------------------------- -// - -// - -// -//----------------------------------------------------------------------------- - -#ifndef __CROSSGENRORESOLVENAMESPACE_H -#define __CROSSGENRORESOLVENAMESPACE_H - -namespace Crossgen -{ - HRESULT WINAPI CrossgenRoResolveNamespace( - const LPCWSTR wszNamespace, - DWORD * pcMetadataFiles, - SString ** ppMetadataFiles); - - void SetFirstPartyWinMDPaths(StringArrayList* saAppPaths); - void SetAppPaths(StringArrayList* saAppPaths); -} - -#endif diff --git a/src/coreclr/src/vm/dllimport.cpp b/src/coreclr/src/vm/dllimport.cpp index 99a63ac..c351324 100644 --- a/src/coreclr/src/vm/dllimport.cpp +++ b/src/coreclr/src/vm/dllimport.cpp @@ -232,11 +232,6 @@ public: virtual void MarshalLCID(int argIdx) = 0; virtual void MarshalField(MarshalInfo* pInfo, UINT32 managedOffset, UINT32 nativeOffset, FieldDesc* pFieldDesc) = 0; -#ifdef FEATURE_COMINTEROP - virtual void MarshalHiddenLengthArgument(MarshalInfo *pInfo, BOOL isForReturnArray) = 0; - virtual void MarshalFactoryReturn() = 0; -#endif // FEATURE_COMINTEROP - virtual void EmitInvokeTarget(MethodDesc *pStubMD) = 0; virtual void FinishEmit(MethodDesc* pMD) = 0; @@ -336,170 +331,6 @@ public: } #ifdef FEATURE_COMINTEROP - // Marshal the hidden length parameter for the managed parameter in pInfo - virtual void MarshalHiddenLengthArgument(MarshalInfo *pInfo, BOOL isForReturnArray) - { - STANDARD_VM_CONTRACT; - - pInfo->MarshalHiddenLengthArgument(&m_slIL, SF_IsForwardStub(m_dwStubFlags), isForReturnArray); - } - - void MarshalFactoryReturn() - { - CONTRACTL - { - STANDARD_VM_CHECK; - PRECONDITION(SF_IsCOMStub(m_dwStubFlags)); - PRECONDITION(SF_IsWinRTCtorStub(m_dwStubFlags)); - } - CONTRACTL_END; - - ILCodeStream *pcsSetup = m_slIL.GetSetupCodeStream(); - ILCodeStream *pcsDispatch = m_slIL.GetDispatchCodeStream(); - ILCodeStream *pcsUnmarshal = m_slIL.GetReturnUnmarshalCodeStream(); - ILCodeStream *pcsCleanup = m_slIL.GetCleanupCodeStream(); - - /* - * SETUP - */ - - // create a local to hold the returned pUnk and initialize to 0 in case the factory fails - // and we try to release it during cleanup - LocalDesc locDescFactoryRetVal(ELEMENT_TYPE_I); - DWORD dwFactoryRetValLocalNum = pcsSetup->NewLocal(locDescFactoryRetVal); - pcsSetup->EmitLoadNullPtr(); - pcsSetup->EmitSTLOC(dwFactoryRetValLocalNum); - - DWORD dwInnerIInspectableLocalNum = -1; - DWORD dwOuterIInspectableLocalNum = -1; - if (SF_IsWinRTCompositionStub(m_dwStubFlags)) - { - // Create locals to store the outer and inner IInspectable values and initialize to null - // Note that we do this in the setup stream so that we're guaranteed to have a null-initialized - // value in the cleanup stream - LocalDesc locDescOuterIInspectable(ELEMENT_TYPE_I); - dwOuterIInspectableLocalNum = pcsSetup->NewLocal(locDescOuterIInspectable); - pcsSetup->EmitLoadNullPtr(); - pcsSetup->EmitSTLOC(dwOuterIInspectableLocalNum); - LocalDesc locDescInnerIInspectable(ELEMENT_TYPE_I); - dwInnerIInspectableLocalNum = pcsSetup->NewLocal(locDescInnerIInspectable); - pcsSetup->EmitLoadNullPtr(); - pcsSetup->EmitSTLOC(dwInnerIInspectableLocalNum); - } - - /* - * DISPATCH - */ - - // For composition factories, add the two extra params - if (SF_IsWinRTCompositionStub(m_dwStubFlags)) - { - // Get outer IInspectable. The helper will return NULL if this is the "top-level" constructor, - // and the appropriate outer pointer otherwise. - pcsDispatch->EmitLoadThis(); - m_slIL.EmitLoadStubContext(pcsDispatch, m_dwStubFlags); - pcsDispatch->EmitCALL(METHOD__STUBHELPERS__GET_OUTER_INSPECTABLE, 2, 1); - pcsDispatch->EmitSTLOC(dwOuterIInspectableLocalNum); - - // load the outer IInspectable (3rd last argument) - pcsDispatch->SetStubTargetArgType(ELEMENT_TYPE_I, false); - pcsDispatch->EmitLDLOC(dwOuterIInspectableLocalNum); - - // pass pointer to where inner non-delegating IInspectable should be stored (2nd last argument) - LocalDesc locDescInnerPtr(ELEMENT_TYPE_I); - locDescInnerPtr.MakeByRef(); - pcsDispatch->SetStubTargetArgType(&locDescInnerPtr, false); - pcsDispatch->EmitLDLOCA(dwInnerIInspectableLocalNum); - pcsDispatch->EmitCONV_I(); - } - - // pass pointer to the local to the factory method (last argument) - locDescFactoryRetVal.MakeByRef(); - pcsDispatch->SetStubTargetArgType(&locDescFactoryRetVal, false); - pcsDispatch->EmitLDLOCA(dwFactoryRetValLocalNum); - pcsDispatch->EmitCONV_I(); - - /* - * UNMARSHAL - */ - - // Mark that the factory method has succesfully returned and so cleanup will be necessary after - // this point. - m_slIL.EmitSetArgMarshalIndex(pcsUnmarshal, NDirectStubLinker::CLEANUP_INDEX_RETVAL_UNMARSHAL); - - // associate the 'this' RCW with one of the returned interface pointers - pcsUnmarshal->EmitLoadThis(); - - // now we need to find the right interface pointer to load - if (dwInnerIInspectableLocalNum != -1) - { - // We may have a composition scenario - ILCodeLabel* pNonCompositionLabel = pcsUnmarshal->NewCodeLabel(); - ILCodeLabel* pLoadedLabel = pcsUnmarshal->NewCodeLabel(); - - // Did we pass an outer IInspectable? - pcsUnmarshal->EmitLDLOC(dwOuterIInspectableLocalNum); - pcsUnmarshal->EmitBRFALSE(pNonCompositionLabel); - - // yes, this is a composition scenario - { - // ignore the delegating interface pointer (will be released in cleanup below) - we can - // re-create it by QI'ing the non-delegating one. - // Note that using this could be useful in the future (avoids an extra QueryInterface call) - // Just load the non-delegating interface pointer - pcsUnmarshal->EmitLDLOCA(dwInnerIInspectableLocalNum); - pcsUnmarshal->EmitBR(pLoadedLabel); - } - // else, no this is a non-composition scenario - { - pcsUnmarshal->EmitLabel(pNonCompositionLabel); - - // ignore the non-delegating interface pointer (which should be null, but will regardless get - // cleaned up below in the event the factory doesn't follow the pattern properly). - // Just load the regular delegating interface pointer - pcsUnmarshal->EmitLDLOCA(dwFactoryRetValLocalNum); - } - - pcsUnmarshal->EmitLabel(pLoadedLabel); - } - else - { - // Definitely can't be a composition scenario - use the only pointer we have - pcsUnmarshal->EmitLDLOCA(dwFactoryRetValLocalNum); - } - - pcsUnmarshal->EmitCALL(METHOD__WINDOWSRUNTIMEMARSHAL__INITIALIZE_WRAPPER, 2, 0); - - /* - * CLEANUP - */ - - // release the returned interface pointer in the finally block - m_slIL.SetCleanupNeeded(); - - ILCodeLabel *pSkipCleanupLabel = pcsCleanup->NewCodeLabel(); - - m_slIL.EmitCheckForArgCleanup(pcsCleanup, - NDirectStubLinker::CLEANUP_INDEX_RETVAL_UNMARSHAL, - NDirectStubLinker::BranchIfNotMarshaled, - pSkipCleanupLabel); - - EmitInterfaceClearNative(pcsCleanup, dwFactoryRetValLocalNum); - - // Note that it's a no-op to pass NULL to Clear_Native, so we call it even though we don't - // know if we assigned to the inner/outer IInspectable - if (dwInnerIInspectableLocalNum != -1) - { - EmitInterfaceClearNative(pcsCleanup, dwInnerIInspectableLocalNum); - } - if (dwOuterIInspectableLocalNum != -1) - { - EmitInterfaceClearNative(pcsCleanup, dwOuterIInspectableLocalNum); - } - - pcsCleanup->EmitLabel(pSkipCleanupLabel); - } - static void EmitInterfaceClearNative(ILCodeStream* pcsEmit, DWORD dwLocalNum) { STANDARD_VM_CONTRACT; @@ -511,7 +342,6 @@ public: pcsEmit->EmitCALL(METHOD__INTERFACEMARSHALER__CLEAR_NATIVE, 1, 0); pcsEmit->EmitLabel(pSkipClearNativeLabel); } - #endif // FEATURE_COMINTEROP void MarshalLCID(int argIdx) @@ -681,14 +511,7 @@ public: DWORD retvalLocalNum = m_slIL.GetReturnValueLocalNum(); BinderMethodID getHRForException; - if (SF_IsWinRTStub(m_dwStubFlags)) - { - getHRForException = METHOD__WINDOWSRUNTIMEMARSHAL__GET_HR_FOR_EXCEPTION; - } - else - { - getHRForException = METHOD__MARSHAL__GET_HR_FOR_EXCEPTION; - } + getHRForException = METHOD__MARSHAL__GET_HR_FOR_EXCEPTION; pcsExceptionHandler->EmitCALL(getHRForException, 0, // WARNING: This method takes 1 input arg, the exception object. But the ILStubLinker @@ -932,14 +755,7 @@ public: m_slIL.EmitLoadStubContext(pcsDispatch, m_dwStubFlags); m_slIL.EmitLoadRCWThis(pcsDispatch, m_dwStubFlags); - if (SF_IsWinRTStub(m_dwStubFlags)) - { - pcsDispatch->EmitCALL(METHOD__STUBHELPERS__GET_COM_HR_EXCEPTION_OBJECT_WINRT, 3, 1); - } - else - { - pcsDispatch->EmitCALL(METHOD__STUBHELPERS__GET_COM_HR_EXCEPTION_OBJECT, 3, 1); - } + pcsDispatch->EmitCALL(METHOD__STUBHELPERS__GET_COM_HR_EXCEPTION_OBJECT, 3, 1); } else #endif // FEATURE_COMINTEROP @@ -978,8 +794,7 @@ public: // Struct marshal stubs don't actually call anything so they do not need the secrect parameter. } #ifndef HOST_64BIT - else if (SF_IsForwardDelegateStub(m_dwStubFlags) || - (SF_IsForwardCOMStub(m_dwStubFlags) && SF_IsWinRTDelegateStub(m_dwStubFlags))) + else if (SF_IsForwardDelegateStub(m_dwStubFlags)) { // Forward delegate stubs get all the context they need in 'this' so they // don't use the secret parameter. Except for AMD64 where we use the secret @@ -1302,13 +1117,6 @@ public: #ifdef FEATURE_COMINTEROP LogOneFlag(dwStubFlags, NDIRECTSTUB_FL_FIELDGETTER, " NDIRECTSTUB_FL_FIELDGETTER\n", facility, level); LogOneFlag(dwStubFlags, NDIRECTSTUB_FL_FIELDSETTER, " NDIRECTSTUB_FL_FIELDSETTER\n", facility, level); - LogOneFlag(dwStubFlags, NDIRECTSTUB_FL_WINRT, " NDIRECTSTUB_FL_WINRT\n", facility, level); - LogOneFlag(dwStubFlags, NDIRECTSTUB_FL_WINRTDELEGATE, " NDIRECTSTUB_FL_WINRTDELEGATE\n", facility, level); - LogOneFlag(dwStubFlags, NDIRECTSTUB_FL_WINRTSHAREDGENERIC, " NDIRECTSTUB_FL_WINRTSHAREDGENERIC\n", facility, level); - LogOneFlag(dwStubFlags, NDIRECTSTUB_FL_WINRTCTOR, " NDIRECTSTUB_FL_WINRTCTOR\n", facility, level); - LogOneFlag(dwStubFlags, NDIRECTSTUB_FL_WINRTCOMPOSITION, " NDIRECTSTUB_FL_WINRTCOMPOSITION\n", facility, level); - LogOneFlag(dwStubFlags, NDIRECTSTUB_FL_WINRTSTATIC, " NDIRECTSTUB_FL_WINRTSTATIC\n", facility, level); - LogOneFlag(dwStubFlags, NDIRECTSTUB_FL_WINRTHASREDIRECTION, " NDIRECTSTUB_FL_WINRTHASREDIRECTION\n", facility, level); #endif // FEATURE_COMINTEROP // @@ -1336,12 +1144,6 @@ public: NDIRECTSTUB_FL_COMEVENTCALL | // internal NDIRECTSTUB_FL_FIELDGETTER | NDIRECTSTUB_FL_FIELDSETTER | - NDIRECTSTUB_FL_WINRT | - NDIRECTSTUB_FL_WINRTDELEGATE | - NDIRECTSTUB_FL_WINRTCTOR | - NDIRECTSTUB_FL_WINRTCOMPOSITION | - NDIRECTSTUB_FL_WINRTSTATIC | - NDIRECTSTUB_FL_WINRTHASREDIRECTION | #endif // FEATURE_COMINTEROP NULL; @@ -1588,7 +1390,7 @@ public: signature, pTypeContext, TRUE, - !SF_IsWinRTStaticStub(dwStubFlags), // fStubHasThis + TRUE, dwStubFlags, iLCIDParamIdx, pTargetMD) @@ -1615,85 +1417,33 @@ public: // convert 'this' to COM IP and the target method entry point m_slIL.EmitLoadRCWThis(pcsDispatch, m_dwStubFlags); -#ifdef TARGET_64BIT - if (SF_IsWinRTDelegateStub(m_dwStubFlags)) - { - // write the stub context (EEImplMethodDesc representing the Invoke) - // into the secret arg so it shows up in the InlinedCallFrame and can - // be used by stub for host - - pcsDispatch->EmitCALL(METHOD__STUBHELPERS__GET_STUB_CONTEXT_ADDR, 0, 1); - m_slIL.EmitLoadStubContext(pcsDispatch, dwStubFlags); - pcsDispatch->EmitSTIND_I(); - pcsDispatch->EmitCALL(METHOD__STUBHELPERS__GET_STUB_CONTEXT, 0, 1); - } - else -#endif // TARGET_64BIT - { - m_slIL.EmitLoadStubContext(pcsDispatch, dwStubFlags); - } + m_slIL.EmitLoadStubContext(pcsDispatch, dwStubFlags); pcsDispatch->EmitLDLOCA(m_slIL.GetTargetEntryPointLocalNum()); - BinderMethodID getCOMIPMethod; - bool fDoPostCallIPCleanup = true; - - if (SF_IsWinRTStub(dwStubFlags)) - { - // WinRT uses optimized helpers - if (SF_IsWinRTSharedGenericStub(dwStubFlags)) - getCOMIPMethod = METHOD__STUBHELPERS__GET_COM_IP_FROM_RCW_WINRT_SHARED_GENERIC; - else if (SF_IsWinRTDelegateStub(dwStubFlags)) - getCOMIPMethod = METHOD__STUBHELPERS__GET_COM_IP_FROM_RCW_WINRT_DELEGATE; - else - getCOMIPMethod = METHOD__STUBHELPERS__GET_COM_IP_FROM_RCW_WINRT; - - // GetCOMIPFromRCW_WinRT, GetCOMIPFromRCW_WinRTSharedGeneric, and GetCOMIPFromRCW_WinRTDelegate - // always cache the COM interface pointer so no post-call cleanup is needed - fDoPostCallIPCleanup = false; - } - else - { - // classic COM interop uses the non-optimized helper - getCOMIPMethod = METHOD__STUBHELPERS__GET_COM_IP_FROM_RCW; - } - - DWORD dwIPRequiresCleanupLocalNum = (DWORD)-1; - if (fDoPostCallIPCleanup) - { - dwIPRequiresCleanupLocalNum = pcsDispatch->NewLocal(ELEMENT_TYPE_BOOLEAN); - pcsDispatch->EmitLDLOCA(dwIPRequiresCleanupLocalNum); - - // StubHelpers.GetCOMIPFromRCW(object objSrc, IntPtr pCPCMD, out IntPtr ppTarget, out bool pfNeedsRelease) - pcsDispatch->EmitCALL(getCOMIPMethod, 4, 1); - } - else - { - // StubHelpers.GetCOMIPFromRCW_WinRT*(object objSrc, IntPtr pCPCMD, out IntPtr ppTarget) - pcsDispatch->EmitCALL(getCOMIPMethod, 3, 1); - } + DWORD dwIPRequiresCleanupLocalNum = pcsDispatch->NewLocal(ELEMENT_TYPE_BOOLEAN); + pcsDispatch->EmitLDLOCA(dwIPRequiresCleanupLocalNum); + // StubHelpers.GetCOMIPFromRCW(object objSrc, IntPtr pCPCMD, out IntPtr ppTarget, out bool pfNeedsRelease) + pcsDispatch->EmitCALL(METHOD__STUBHELPERS__GET_COM_IP_FROM_RCW, 4, 1); // save it because we'll need it to compute the CALLI target and release it pcsDispatch->EmitDUP(); pcsDispatch->EmitSTLOC(m_slIL.GetTargetInterfacePointerLocalNum()); - if (fDoPostCallIPCleanup) - { - // make sure it's Release()'ed after the call - m_slIL.SetCleanupNeeded(); - ILCodeStream *pcsCleanup = m_slIL.GetCleanupCodeStream(); + // make sure it's Release()'ed after the call + m_slIL.SetCleanupNeeded(); + ILCodeStream *pcsCleanup = m_slIL.GetCleanupCodeStream(); - ILCodeLabel *pSkipThisCleanup = pcsCleanup->NewCodeLabel(); + ILCodeLabel *pSkipThisCleanup = pcsCleanup->NewCodeLabel(); - // and if it requires cleanup (i.e. it's not taken from the RCW cache) - pcsCleanup->EmitLDLOC(dwIPRequiresCleanupLocalNum); - pcsCleanup->EmitBRFALSE(pSkipThisCleanup); + // and if it requires cleanup (i.e. it's not taken from the RCW cache) + pcsCleanup->EmitLDLOC(dwIPRequiresCleanupLocalNum); + pcsCleanup->EmitBRFALSE(pSkipThisCleanup); - pcsCleanup->EmitLDLOC(m_slIL.GetTargetInterfacePointerLocalNum()); - pcsCleanup->EmitCALL(METHOD__INTERFACEMARSHALER__CLEAR_NATIVE, 1, 0); - pcsCleanup->EmitLabel(pSkipThisCleanup); - } + pcsCleanup->EmitLDLOC(m_slIL.GetTargetInterfacePointerLocalNum()); + pcsCleanup->EmitCALL(METHOD__INTERFACEMARSHALER__CLEAR_NATIVE, 1, 0); + pcsCleanup->EmitLabel(pSkipThisCleanup); } }; @@ -1722,59 +1472,7 @@ public: ILStubState::BeginEmit(dwStubFlags); - if (!SF_IsWinRTStaticStub(dwStubFlags)) - { - // we are not loading 'this' because the target is static - // load this - m_slIL.GetDispatchCodeStream()->EmitLoadThis(); - } - } - - void MarshalFactoryReturn() - { - CONTRACTL - { - STANDARD_VM_CHECK; - PRECONDITION(SF_IsWinRTCtorStub(m_dwStubFlags)); - } - CONTRACTL_END; - - ILCodeStream *pcsSetup = m_slIL.GetSetupCodeStream(); - ILCodeStream *pcsDispatch = m_slIL.GetDispatchCodeStream(); - ILCodeStream *pcsUnmarshal = m_slIL.GetReturnUnmarshalCodeStream(); - ILCodeStream *pcsExCleanup = m_slIL.GetExceptionCleanupCodeStream(); - - LocalDesc locDescFactoryRetVal(ELEMENT_TYPE_I); - DWORD dwFactoryRetValLocalNum = pcsSetup->NewLocal(locDescFactoryRetVal); - pcsSetup->EmitLoadNullPtr(); - pcsSetup->EmitSTLOC(dwFactoryRetValLocalNum); - - locDescFactoryRetVal.MakeByRef(); - - // expect one additional argument - pointer to a location that receives the created instance - DWORD dwRetValArgNum = pcsDispatch->SetStubTargetArgType(&locDescFactoryRetVal, false); - - // convert 'this' to an interface pointer corresponding to the default interface of this class - pcsUnmarshal->EmitLoadThis(); - pcsUnmarshal->EmitCALL(METHOD__STUBHELPERS__GET_STUB_CONTEXT, 0, 1); - pcsUnmarshal->EmitCALL(METHOD__STUBHELPERS__GET_WINRT_FACTORY_RETURN_VALUE, 2, 1); - pcsUnmarshal->EmitSTLOC(dwFactoryRetValLocalNum); - - // assign it to the location pointed to by the argument - pcsUnmarshal->EmitLDARG(dwRetValArgNum); - pcsUnmarshal->EmitLDLOC(dwFactoryRetValLocalNum); - pcsUnmarshal->EmitSTIND_I(); - - // on exception, we want to release the IInspectable's and assign NULL to output locations - m_slIL.SetExceptionCleanupNeeded(); - - EmitInterfaceClearNative(pcsExCleanup, dwFactoryRetValLocalNum); - - // *retVal = NULL - pcsExCleanup->EmitLDARG(dwRetValArgNum); - pcsExCleanup->EmitLoadNullPtr(); - pcsExCleanup->EmitSTIND_I(); - + m_slIL.GetDispatchCodeStream()->EmitLoadThis(); } }; @@ -2076,26 +1774,7 @@ void NDirectStubLinker::EmitLoadRCWThis(ILCodeStream *pcsEmit, DWORD dwStubFlags { STANDARD_VM_CONTRACT; - if (SF_IsForwardStub(dwStubFlags) && - (SF_IsWinRTCtorStub(dwStubFlags) || SF_IsWinRTStaticStub(dwStubFlags))) - { - // WinRT ctor/static stubs make the call on the factory object instead of 'this' - if (m_dwWinRTFactoryObjectLocalNum == (DWORD)-1) - { - m_dwWinRTFactoryObjectLocalNum = NewLocal(ELEMENT_TYPE_OBJECT); - - // get the factory object - EmitLoadStubContext(m_pcsSetup, dwStubFlags); - m_pcsSetup->EmitCALL(METHOD__STUBHELPERS__GET_WINRT_FACTORY_OBJECT, 1, 1); - m_pcsSetup->EmitSTLOC(m_dwWinRTFactoryObjectLocalNum); - } - - pcsEmit->EmitLDLOC(m_dwWinRTFactoryObjectLocalNum); - } - else - { - pcsEmit->EmitLoadThis(); - } + pcsEmit->EmitLoadThis(); } #endif // FEATURE_COMINTEROP @@ -2236,33 +1915,6 @@ void NDirectStubLinker::Begin(DWORD dwStubFlags) { STANDARD_VM_CONTRACT; -#ifdef FEATURE_COMINTEROP - if (SF_IsWinRTHasRedirection(dwStubFlags)) - { - _ASSERTE(SF_IsForwardCOMStub(dwStubFlags)); - - // The very first thing we need to do is check whether the call should be routed to - // the marshaling stub for the corresponding projected WinRT interface. If so, we - // tail-call there. - m_pcsSetup->EmitLoadThis(); - EmitLoadStubContext(m_pcsSetup, dwStubFlags); - m_pcsSetup->EmitCALL(METHOD__STUBHELPERS__SHOULD_CALL_WINRT_INTERFACE, 2, 1); - - ILCodeLabel *pNoRedirection = m_pcsSetup->NewCodeLabel(); - m_pcsSetup->EmitBRFALSE(pNoRedirection); - - MethodDesc *pAdapterMD = WinRTInterfaceRedirector::GetStubMethodForRedirectedInterfaceMethod( - GetTargetMD(), - TypeHandle::Interop_ManagedToNative); - - CONSISTENCY_CHECK(pAdapterMD != NULL && !pAdapterMD->HasMethodInstantiation()); - - m_pcsSetup->EmitJMP(m_pcsSetup->GetToken(pAdapterMD)); - - m_pcsSetup->EmitLabel(pNoRedirection); - } -#endif // FEATURE_COMINTEROP - if (SF_IsForwardStub(dwStubFlags)) { @@ -2714,21 +2366,8 @@ void NDirectStubLinker::EmitLoadStubContext(ILCodeStream* pcsEmit, DWORD dwStubF CONSISTENCY_CHECK(!SF_IsForwardDelegateStub(dwStubFlags)); CONSISTENCY_CHECK(!SF_IsFieldGetterStub(dwStubFlags) && !SF_IsFieldSetterStub(dwStubFlags)); - -#ifdef FEATURE_COMINTEROP - if (SF_IsWinRTDelegateStub(dwStubFlags) && SF_IsForwardStub(dwStubFlags)) - { - // we have the delegate 'this' but we need the EEImpl/Instantiated 'Invoke' MD pointer - // (Delegate.GetInvokeMethod does not return exact instantiated MD so we call our own helper) - pcsEmit->EmitLoadThis(); - pcsEmit->EmitCALL(METHOD__STUBHELPERS__GET_DELEGATE_INVOKE_METHOD, 1, 1); - } - else -#endif // FEATURE_COMINTEROP - { - // get the secret argument via intrinsic - pcsEmit->EmitCALL(METHOD__STUBHELPERS__GET_STUB_CONTEXT, 0, 1); - } + // get the secret argument via intrinsic + pcsEmit->EmitCALL(METHOD__STUBHELPERS__GET_STUB_CONTEXT, 0, 1); } #ifdef FEATURE_COMINTEROP @@ -3617,10 +3256,7 @@ static MarshalInfo::MarshalType DoMarshalReturnValue(MetaSig& msig, #ifdef FEATURE_COMINTEROP if (SF_IsCOMStub(dwStubFlags)) { - if (SF_IsWinRTStub(dwStubFlags)) - ms = MarshalInfo::MARSHAL_SCENARIO_WINRT; - else - ms = MarshalInfo::MARSHAL_SCENARIO_COMINTEROP; + ms = MarshalInfo::MARSHAL_SCENARIO_COMINTEROP; } else #endif // FEATURE_COMINTEROP @@ -3628,21 +3264,6 @@ static MarshalInfo::MarshalType DoMarshalReturnValue(MetaSig& msig, ms = MarshalInfo::MARSHAL_SCENARIO_NDIRECT; } -#ifdef FEATURE_COMINTEROP - if (SF_IsWinRTCtorStub(dwStubFlags)) - { - _ASSERTE(msig.GetReturnType() == ELEMENT_TYPE_VOID); - _ASSERTE(SF_IsHRESULTSwapping(dwStubFlags)); - - pss->MarshalFactoryReturn(); - nativeStackOffset += sizeof(LPVOID); - if (SF_IsWinRTCompositionStub(dwStubFlags)) - { - nativeStackOffset += 2 * sizeof(LPVOID); - } - } - else -#endif // FEATURE_COMINTEROP if (msig.GetReturnType() != ELEMENT_TYPE_VOID) { MarshalInfo returnInfo(msig.GetModule(), @@ -3671,27 +3292,6 @@ static MarshalInfo::MarshalType DoMarshalReturnValue(MetaSig& msig, fStubNeedsCOM |= returnInfo.MarshalerRequiresCOM(); #ifdef FEATURE_COMINTEROP - if (marshalType == MarshalInfo::MARSHAL_TYPE_HIDDENLENGTHARRAY) - { - // Hidden length arrays are only valid with HRESULT swapping - if (!SF_IsHRESULTSwapping(dwStubFlags)) - { - COMPlusThrow(kMarshalDirectiveException, IDS_EE_COM_UNSUPPORTED_SIG); - } - - // We should be safe to cast here - giant signatures will fail to marashal later with IDS_EE_SIGTOOCOMPLEX - returnInfo.SetHiddenLengthParamIndex(static_cast(nativeArgIndex)); - - // Inject the hidden argument so that it winds up at the end of the method signature - pss->MarshalHiddenLengthArgument(&returnInfo, TRUE); - nativeStackOffset += returnInfo.GetHiddenLengthParamStackSize(); - - if (SF_IsReverseStub(dwStubFlags)) - { - ++argOffset; - } - } - if (SF_IsCOMStub(dwStubFlags)) { // We don't support native methods that return VARIANTs, non-blittable structs, GUIDs, or DECIMALs directly. @@ -3715,9 +3315,6 @@ static MarshalInfo::MarshalType DoMarshalReturnValue(MetaSig& msig, || marshalType == MarshalInfo::MARSHAL_TYPE_VALUECLASS || marshalType == MarshalInfo::MARSHAL_TYPE_GUID || marshalType == MarshalInfo::MARSHAL_TYPE_DECIMAL -#ifdef FEATURE_COMINTEROP - || marshalType == MarshalInfo::MARSHAL_TYPE_DATETIME -#endif // FEATURE_COMINTEROP ) { if (SF_IsHRESULTSwapping(dwStubFlags)) @@ -3773,91 +3370,6 @@ static inline UINT GetStackOffsetFromStackSize(UINT stackSize, bool fThisCall) return stackSize; } -#ifdef FEATURE_COMINTEROP - -struct HiddenParameterInfo -{ - MarshalInfo *pManagedParam; // Managed parameter which required the hidden parameter - int nativeIndex; // 0 based index into the native method signature where the hidden parameter should be injected -}; - -// Get the indexes of any hidden length parameters to be marshaled for the method -// -// At return, each value in the ppParamIndexes array is a 0 based index into the native method signature where -// the length parameter for a hidden length array should be passed. The MarshalInfo objects will also be -// updated such that they all have explicit marshaling information. -// -// The caller is responsible for freeing the memory pointed to by ppParamIndexes -void CheckForHiddenParameters(DWORD cParamMarshalInfo, - __in_ecount(cParamMarshalInfo) MarshalInfo *pParamMarshalInfo, - __out DWORD *pcHiddenNativeParameters, - __out HiddenParameterInfo **ppHiddenNativeParameters) -{ - CONTRACTL - { - STANDARD_VM_CHECK; - PRECONDITION(CheckPointer(pParamMarshalInfo)); - PRECONDITION(CheckPointer(pcHiddenNativeParameters)); - PRECONDITION(CheckPointer(ppHiddenNativeParameters)); - } - CONTRACTL_END; - - NewArrayHolder hiddenParamInfo(new HiddenParameterInfo[cParamMarshalInfo]); - DWORD foundInfoCount = 0; - - for (DWORD iParam = 0; iParam < cParamMarshalInfo; ++iParam) - { - // Look for hidden length arrays, which all require additional parameters to be added - if (pParamMarshalInfo[iParam].GetMarshalType() == MarshalInfo::MARSHAL_TYPE_HIDDENLENGTHARRAY) - { - DWORD currentNativeIndex = iParam + foundInfoCount; - - // The location of the length parameter is implicitly just before the array pointer. - // We'll give it our current index, and bumping the found count will push us back a slot. - - // We should be safe to cast here - giant signatures will fail to marashal later with IDS_EE_SIGTOOCOMPLEX - pParamMarshalInfo[iParam].SetHiddenLengthParamIndex(static_cast(currentNativeIndex)); - - hiddenParamInfo[foundInfoCount].nativeIndex = pParamMarshalInfo[iParam].HiddenLengthParamIndex(); - hiddenParamInfo[foundInfoCount].pManagedParam = &(pParamMarshalInfo[iParam]); - ++foundInfoCount; - } - } - - *pcHiddenNativeParameters = foundInfoCount; - *ppHiddenNativeParameters = hiddenParamInfo.Extract(); -} - -bool IsHiddenParameter(int nativeArgIndex, - DWORD cHiddenParameters, - __in_ecount(cHiddenParameters) HiddenParameterInfo *pHiddenParameters, - __out HiddenParameterInfo **ppHiddenParameterInfo) -{ - CONTRACTL - { - STANDARD_VM_CHECK; - PRECONDITION(cHiddenParameters == 0 || CheckPointer(pHiddenParameters)); - PRECONDITION(CheckPointer(ppHiddenParameterInfo)); - } - CONTRACTL_END; - - *ppHiddenParameterInfo = NULL; - - for (DWORD i = 0; i < cHiddenParameters; ++i) - { - _ASSERTE(pHiddenParameters[i].nativeIndex != -1); - if (pHiddenParameters[i].nativeIndex == nativeArgIndex) - { - *ppHiddenParameterInfo = &(pHiddenParameters[i]); - return true; - } - } - - return false; -} - -#endif // FEATURE_COMINTEROP - //--------------------------------------------------------- // Creates a new stub for a N/Direct call. Return refcount is 1. // Note that this function may now throw if it fails to create @@ -3928,9 +3440,6 @@ static void CreateNDirectStubWorker(StubState* pss, if (-1 != iLCIDArg) { - // LCID is not supported on WinRT - _ASSERTE(!SF_IsWinRTStub(dwStubFlags)); - // The code to handle the LCID will call MarshalLCID before calling MarshalArgument // on the argument the LCID should go after. So we just bump up the index here. iLCIDArg++; @@ -4010,10 +3519,7 @@ static void CreateNDirectStubWorker(StubState* pss, #ifdef FEATURE_COMINTEROP if (SF_IsCOMStub(dwStubFlags)) { - if (SF_IsWinRTStub(dwStubFlags)) - ms = MarshalInfo::MARSHAL_SCENARIO_WINRT; - else - ms = MarshalInfo::MARSHAL_SCENARIO_COMINTEROP; + ms = MarshalInfo::MARSHAL_SCENARIO_COMINTEROP; } else #endif // FEATURE_COMINTEROP @@ -4056,16 +3562,6 @@ static void CreateNDirectStubWorker(StubState* pss, DEBUG_ARG(i + 1)); } -#ifdef FEATURE_COMINTEROP - // Check to see if we need to inject any additional hidden parameters - DWORD cHiddenNativeParameters; - NewArrayHolder pHiddenNativeParameters; - CheckForHiddenParameters(numArgs, pParamMarshalInfo, &cHiddenNativeParameters, &pHiddenNativeParameters); - - // Hidden parameters and LCID do not mix - _ASSERTE(!(cHiddenNativeParameters > 0 && iLCIDArg != -1)); -#endif // FEATURE_COMINTEROP - // Marshal the parameters int argidx = 1; int nativeArgIndex = 0; @@ -4142,58 +3638,36 @@ static void CreateNDirectStubWorker(StubState* pss, while (argidx <= numArgs) { -#ifdef FEATURE_COMINTEROP - HiddenParameterInfo *pHiddenParameter; - // Check to see if we need to inject a hidden parameter - if (IsHiddenParameter(nativeArgIndex, cHiddenNativeParameters, pHiddenNativeParameters, &pHiddenParameter)) + // + // Check to see if this is the parameter after which we need to insert the LCID. + // + if (argidx == iLCIDArg) { - pss->MarshalHiddenLengthArgument(pHiddenParameter->pManagedParam, FALSE); - nativeStackSize += pHiddenParameter->pManagedParam->GetHiddenLengthParamStackSize(); + pss->MarshalLCID(argidx); + nativeStackSize += sizeof(LPVOID); if (SF_IsReverseStub(dwStubFlags)) - { - ++argOffset; - } + argOffset++; } - else -#endif // FEATURE_COMINTEROP - { - // - // Check to see if this is the parameter after which we need to insert the LCID. - // - if (argidx == iLCIDArg) - { - pss->MarshalLCID(argidx); - nativeStackSize += sizeof(LPVOID); - - if (SF_IsReverseStub(dwStubFlags)) - argOffset++; - } - - msig.NextArg(); - MarshalInfo &info = pParamMarshalInfo[argidx - 1]; - -#ifdef FEATURE_COMINTEROP - // For the hidden-length array, length parameters must occur before the parameter containing the array pointer - _ASSERTE(info.GetMarshalType() != MarshalInfo::MARSHAL_TYPE_HIDDENLENGTHARRAY || nativeArgIndex > info.HiddenLengthParamIndex()); -#endif // FEATURE_COMINTEROP + msig.NextArg(); - pss->MarshalArgument(&info, argOffset, GetStackOffsetFromStackSize(nativeStackSize, fThisCall)); - nativeStackSize += info.GetNativeArgSize(); + MarshalInfo &info = pParamMarshalInfo[argidx - 1]; - fStubNeedsCOM |= info.MarshalerRequiresCOM(); + pss->MarshalArgument(&info, argOffset, GetStackOffsetFromStackSize(nativeStackSize, fThisCall)); + nativeStackSize += info.GetNativeArgSize(); - if (fThisCall && argidx == 1) - { - // make sure that the first parameter is enregisterable - if (info.GetNativeArgSize() > sizeof(SLOT)) - COMPlusThrow(kMarshalDirectiveException, IDS_EE_NDIRECT_BADNATL_THISCALL); - } + fStubNeedsCOM |= info.MarshalerRequiresCOM(); - argidx++; + if (fThisCall && argidx == 1) + { + // make sure that the first parameter is enregisterable + if (info.GetNativeArgSize() > sizeof(SLOT)) + COMPlusThrow(kMarshalDirectiveException, IDS_EE_NDIRECT_BADNATL_THISCALL); } + argidx++; + ++nativeArgIndex; } @@ -4326,12 +3800,6 @@ static void CreateStructStub(ILStubState* pss, // Marshal the fields MarshalInfo::MarshalScenario ms = MarshalInfo::MARSHAL_SCENARIO_FIELD; -#ifdef FEATURE_COMINTEROP - if (pMT->IsProjectedFromWinRT()) - { - ms = MarshalInfo::MARSHAL_SCENARIO_WINRT_FIELD; - } -#endif // FEATURE_COMINTEROP EEClassNativeLayoutInfo const* pNativeLayoutInfo = pMT->GetNativeLayoutInfo(); @@ -4382,9 +3850,6 @@ static void CreateStructStub(ILStubState* pss, if (pMD->IsDynamicMethod()) { DynamicMethodDesc* pDMD = pMD->AsDynamicMethodDesc(); -#ifdef FEATURE_COMINTEROP - pDMD->SetStubNeedsCOMStarted(ms == MarshalInfo::MARSHAL_SCENARIO_WINRT_FIELD); -#endif pDMD->SetNativeStackArgSize(4 * sizeof(SLOT)); // The native stack arg size is constant since the signature for struct stubs is constant. } @@ -4674,19 +4139,6 @@ static void CreateNDirectStubAccessMetadata( } } -#ifdef FEATURE_COMINTEROP - if (SF_IsDelegateStub(*pdwStubFlags)) - { - _ASSERTE(!SF_IsWinRTStub(*pdwStubFlags)); - if (pSigDesc->m_pMD->GetMethodTable()->IsProjectedFromWinRT()) - { - // We do not allow P/Invoking via WinRT delegates to better segregate WinRT - // from classic interop scenarios. - COMPlusThrow(kMarshalDirectiveException, IDS_EE_DELEGATEPINVOKE_WINRT); - } - } -#endif // FEATURE_COMINTEROP - MetaSig msig(pSigDesc->m_sig, pSigDesc->m_pModule, &pSigDesc->m_typeContext); @@ -4710,19 +4162,6 @@ static void CreateNDirectStubAccessMetadata( &dwDescrOffset, &dwImplFlags)); -#ifdef FEATURE_COMINTEROP - if (SF_IsWinRTStub(*pdwStubFlags)) - { - // All WinRT methods do HRESULT swapping - if (IsMiPreserveSig(dwImplFlags)) - { - COMPlusThrow(kMarshalDirectiveException, IDS_EE_PRESERVESIG_WINRT); - } - - (*pdwStubFlags) |= NDIRECTSTUB_FL_DOHRESULTSWAPPING; - } - else -#endif // FEATURE_COMINTEROP if (SF_IsReverseStub(*pdwStubFlags)) { // only COM-to-CLR call supports hresult swapping in the reverse direction @@ -4756,7 +4195,7 @@ static void CreateNDirectStubAccessMetadata( (*piLCIDArg) = lcidArg; - if (SF_IsCOMStub(*pdwStubFlags) && !SF_IsWinRTStaticStub(*pdwStubFlags)) + if (SF_IsCOMStub(*pdwStubFlags)) { CONSISTENCY_CHECK(msig.HasThis()); } @@ -4859,22 +4298,6 @@ HRESULT FindPredefinedILStubMethod(MethodDesc *pTargetMD, DWORD dwStubFlags, Met MethodTable *pTargetMT = pTargetMD->GetMethodTable(); - // Check if this is a redirected interface - we have static stubs in mscorlib for those. - if (SF_IsForwardCOMStub(dwStubFlags) && pTargetMT->IsInterface()) - { - - // Redirect generic redirected interfaces to the corresponding adapter methods in mscorlib - if (pTargetMT->HasInstantiation()) - { - MethodDesc *pAdapterMD = WinRTInterfaceRedirector::GetStubMethodForRedirectedInterfaceMethod(pTargetMD, TypeHandle::Interop_ManagedToNative); - if (pAdapterMD != NULL) - { - *ppRetStubMD = pAdapterMD; - return S_OK; - } - } - } - // // Find out if we have the attribute // @@ -4882,7 +4305,7 @@ HRESULT FindPredefinedILStubMethod(MethodDesc *pTargetMD, DWORD dwStubFlags, Met ULONG cbBytes; // Support v-table forward classic COM interop calls only - if (SF_IsCOMStub(dwStubFlags) && SF_IsForwardStub(dwStubFlags) && !SF_IsWinRTStub(dwStubFlags)) + if (SF_IsCOMStub(dwStubFlags) && SF_IsForwardStub(dwStubFlags)) { if (pTargetMT->HasInstantiation()) { @@ -4900,7 +4323,6 @@ HRESULT FindPredefinedILStubMethod(MethodDesc *pTargetMD, DWORD dwStubFlags, Met if (pTargetMD->IsInterface()) { - _ASSERTE(!pTargetMD->GetAssembly()->IsWinMD()); hr = pTargetMD->GetCustomAttribute( WellKnownAttribute::ManagedToNativeComInteropStub, &pBytes, @@ -5729,24 +5151,11 @@ MethodDesc* NDirect::CreateCLRToNativeILStub(PInvokeStaticSigInfo* pSigInfo, StubSigDesc sigDesc(pMD, pSigInfo); - if (SF_IsWinRTDelegateStub(dwStubFlags)) - { - _ASSERTE(pMD->IsEEImpl()); - - return CreateCLRToNativeILStub(&sigDesc, - (CorNativeLinkType)0, - (CorNativeLinkFlags)0, - (CorPinvokeMap)0, - (pSigInfo->GetStubFlags() | dwStubFlags) & ~NDIRECTSTUB_FL_DELEGATE); - } - else - { - return CreateCLRToNativeILStub(&sigDesc, - pSigInfo->GetCharSet(), - pSigInfo->GetLinkFlags(), - pSigInfo->GetCallConv(), - pSigInfo->GetStubFlags() | dwStubFlags); - } + return CreateCLRToNativeILStub(&sigDesc, + pSigInfo->GetCharSet(), + pSigInfo->GetLinkFlags(), + pSigInfo->GetCallConv(), + pSigInfo->GetStubFlags() | dwStubFlags); } MethodDesc* NDirect::GetILStubMethodDesc(NDirectMethodDesc* pNMD, PInvokeStaticSigInfo* pSigInfo, DWORD dwStubFlags) @@ -5819,16 +5228,7 @@ MethodDesc* GetStubMethodDescFromInteropMethodDesc(MethodDesc* pMD, DWORD dwStub } else { -#ifdef FEATURE_COMINTEROP - if (SF_IsWinRTDelegateStub(dwStubFlags)) - { - return pClass->m_pComPlusCallInfo->m_pStubMD.GetValueMaybeNull(); - } - else -#endif // FEATURE_COMINTEROP - { - return pClass->m_pForwardStubMD; - } + return pClass->m_pForwardStubMD; } } else if (pMD->IsIL()) @@ -6524,18 +5924,6 @@ namespace return NULL; } -#ifdef FEATURE_COMINTEROP - CLRPrivBinderWinRT *pWinRTBinder = pDomain->GetWinRtBinder(); - if (AreSameBinderInstance(pCurrentBinder, pWinRTBinder)) - { - // We could be here when a non-WinRT assembly load is triggerred by a winmd (e.g. System.Runtime being loaded due to - // types being referenced from Windows.Foundation.Winmd) or when dealing with a winmd (which is bound using WinRT binder). - // - // For this, we should use the standard mechanism to make pinvoke call as well. - return NULL; - } -#endif // FEATURE_COMINTEROP - //Step 1: If the assembly was not bound using TPA, // Call System.Runtime.Loader.AssemblyLoadContext.ResolveUnmanagedDll to give // The custom assembly context a chance to load the unmanaged dll. @@ -6582,14 +5970,6 @@ namespace AppDomain *pDomain = GetAppDomain(); ICLRPrivBinder *pCurrentBinder = reinterpret_cast(assemblyBinderID); -#ifdef FEATURE_COMINTEROP - if (AreSameBinderInstance(pCurrentBinder, pDomain->GetWinRtBinder())) - { - // No ALC associated handle with WinRT Binders. - return NULL; - } -#endif // FEATURE_COMINTEROP - // The code here deals with two implementations of ICLRPrivBinder interface: // - CLRPrivBinderCoreCLR for the TPA binder in the default ALC, and // - CLRPrivBinderAssemblyLoadContext for custom ALCs. diff --git a/src/coreclr/src/vm/dllimport.h b/src/coreclr/src/vm/dllimport.h index afed587..035721f 100644 --- a/src/coreclr/src/vm/dllimport.h +++ b/src/coreclr/src/vm/dllimport.h @@ -147,14 +147,14 @@ enum NDirectStubFlags #ifdef FEATURE_COMINTEROP NDIRECTSTUB_FL_FIELDGETTER = 0x00002000, // COM->CLR field getter NDIRECTSTUB_FL_FIELDSETTER = 0x00004000, // COM->CLR field setter - NDIRECTSTUB_FL_WINRT = 0x00008000, - NDIRECTSTUB_FL_WINRTDELEGATE = 0x00010000, - NDIRECTSTUB_FL_WINRTSHAREDGENERIC = 0x00020000, // stub for methods on shared generic interfaces (only used in the forward direction) - NDIRECTSTUB_FL_WINRTCTOR = 0x00080000, - NDIRECTSTUB_FL_WINRTCOMPOSITION = 0x00100000, // set along with WINRTCTOR - NDIRECTSTUB_FL_WINRTSTATIC = 0x00200000, + // unused = 0x00008000, + // unused = 0x00010000, + // unused = 0x00020000, + // unused = 0x00080000, + // unused = 0x00100000, + // unused = 0x00200000, // unused = 0x00400000, - NDIRECTSTUB_FL_WINRTHASREDIRECTION = 0x00800000, // the stub may tail-call to a static stub in mscorlib, not shareable + // unused = 0x00800000, #endif // FEATURE_COMINTEROP // internal flags -- these won't ever show up in an NDirectStubHashBlob @@ -231,28 +231,15 @@ inline bool SF_IsTailCallCallTargetStub (DWORD dwStubFlags) { LIMITED_METHOD_CON inline bool SF_IsTailCallDispatcherStub (DWORD dwStubFlags) { LIMITED_METHOD_CONTRACT; return (dwStubFlags == ILSTUB_TAILCALL_DISPATCH); } inline bool SF_IsCOMStub (DWORD dwStubFlags) { LIMITED_METHOD_CONTRACT; return COM_ONLY(dwStubFlags < NDIRECTSTUB_FL_INVALID && 0 != (dwStubFlags & NDIRECTSTUB_FL_COM)); } -inline bool SF_IsWinRTStub (DWORD dwStubFlags) { LIMITED_METHOD_CONTRACT; return COM_ONLY(dwStubFlags < NDIRECTSTUB_FL_INVALID && 0 != (dwStubFlags & NDIRECTSTUB_FL_WINRT)); } inline bool SF_IsCOMLateBoundStub (DWORD dwStubFlags) { LIMITED_METHOD_CONTRACT; return COM_ONLY(dwStubFlags < NDIRECTSTUB_FL_INVALID && 0 != (dwStubFlags & NDIRECTSTUB_FL_COMLATEBOUND)); } inline bool SF_IsCOMEventCallStub (DWORD dwStubFlags) { LIMITED_METHOD_CONTRACT; return COM_ONLY(dwStubFlags < NDIRECTSTUB_FL_INVALID && 0 != (dwStubFlags & NDIRECTSTUB_FL_COMEVENTCALL)); } inline bool SF_IsFieldGetterStub (DWORD dwStubFlags) { LIMITED_METHOD_CONTRACT; return COM_ONLY(dwStubFlags < NDIRECTSTUB_FL_INVALID && 0 != (dwStubFlags & NDIRECTSTUB_FL_FIELDGETTER)); } inline bool SF_IsFieldSetterStub (DWORD dwStubFlags) { LIMITED_METHOD_CONTRACT; return COM_ONLY(dwStubFlags < NDIRECTSTUB_FL_INVALID && 0 != (dwStubFlags & NDIRECTSTUB_FL_FIELDSETTER)); } -inline bool SF_IsWinRTDelegateStub (DWORD dwStubFlags) { LIMITED_METHOD_CONTRACT; return COM_ONLY(dwStubFlags < NDIRECTSTUB_FL_INVALID && 0 != (dwStubFlags & NDIRECTSTUB_FL_WINRTDELEGATE)); } -inline bool SF_IsWinRTCtorStub (DWORD dwStubFlags) { LIMITED_METHOD_CONTRACT; return COM_ONLY(dwStubFlags < NDIRECTSTUB_FL_INVALID && 0 != (dwStubFlags & NDIRECTSTUB_FL_WINRTCTOR)); } -inline bool SF_IsWinRTCompositionStub (DWORD dwStubFlags) { LIMITED_METHOD_CONTRACT; return COM_ONLY(dwStubFlags < NDIRECTSTUB_FL_INVALID && 0 != (dwStubFlags & NDIRECTSTUB_FL_WINRTCOMPOSITION)); } -inline bool SF_IsWinRTStaticStub (DWORD dwStubFlags) { LIMITED_METHOD_CONTRACT; return COM_ONLY(dwStubFlags < NDIRECTSTUB_FL_INVALID && 0 != (dwStubFlags & NDIRECTSTUB_FL_WINRTSTATIC)); } -inline bool SF_IsWinRTSharedGenericStub(DWORD dwStubFlags) { LIMITED_METHOD_CONTRACT; return COM_ONLY(dwStubFlags < NDIRECTSTUB_FL_INVALID && 0 != (dwStubFlags & NDIRECTSTUB_FL_WINRTSHAREDGENERIC)); } -inline bool SF_IsWinRTHasRedirection (DWORD dwStubFlags) { LIMITED_METHOD_CONTRACT; return COM_ONLY(dwStubFlags < NDIRECTSTUB_FL_INVALID && 0 != (dwStubFlags & NDIRECTSTUB_FL_WINRTHASREDIRECTION)); } inline bool SF_IsSharedStub(DWORD dwStubFlags) { WRAPPER_NO_CONTRACT; - if (SF_IsWinRTHasRedirection(dwStubFlags)) - { - // tail-call to a target-specific mscorlib routine is burned into the stub - return false; - } - if (SF_IsTailCallStoreArgsStub(dwStubFlags) || SF_IsTailCallCallTargetStub(dwStubFlags) || SF_IsTailCallDispatcherStub(dwStubFlags)) { diff --git a/src/coreclr/src/vm/domainfile.cpp b/src/coreclr/src/vm/domainfile.cpp index ca7a86c..33a1f9d 100644 --- a/src/coreclr/src/vm/domainfile.cpp +++ b/src/coreclr/src/vm/domainfile.cpp @@ -31,8 +31,6 @@ #include "dllimportcallback.h" #include "peimagelayout.inl" -#include "winrthelpers.h" - #ifdef FEATURE_PERFMAP #include "perfmap.h" #endif // FEATURE_PERFMAP @@ -1000,44 +998,6 @@ void DomainFile::FinishLoad() // Are we absolutely required to use a native image? CheckZapRequired(); - -#if defined(FEATURE_COMINTEROP) - // If this is a winmd file, ensure that the ngen reference namespace is loadable. - // This is necessary as on the phone we don't check ngen image dependencies, and thus we can get in a situation - // where a winmd is loaded as a dependency of an ngen image, but the type used to build cross module references - // in winmd files isn't loaded. - PEFile* peFile = GetFile(); - if (peFile && peFile->AsAssembly()->IsWindowsRuntime() && peFile->HasHostAssembly()) - { - IMDInternalImport *pImport = GetFile()->GetPersistentMDImport(); - LPCSTR szNameSpace; - LPCSTR szTypeName; - // It does not make sense to pass the file name to recieve fake type name for empty WinMDs, because we would use the name - // for binding in next call to BindAssemblySpec which would fail for fake WinRT type name - // We will throw/return the error instead and the caller will recognize it and react to it by not creating the ngen image - - // see code:Zapper::ComputeDependenciesInCurrentDomain - if (SUCCEEDED(::GetFirstWinRTTypeDef(pImport, &szNameSpace, &szTypeName, NULL, NULL))) - { - // Build assembly spec to describe binding to that WinRT type. - AssemblySpec spec; - IfFailThrow(spec.Init("WindowsRuntimeAssemblyName, ContentType=WindowsRuntime")); - spec.SetWindowsRuntimeType(szNameSpace, szTypeName); - - // Bind to assembly using the CLRPriv binder infrastructure. (All WinRT loads are done through CLRPriv binders - ReleaseHolder pAssemblyName; - IfFailThrow(spec.CreateFusionName(&pAssemblyName, FALSE, TRUE)); - ReleaseHolder pPrivAssembly; - IfFailThrow(GetFile()->GetHostAssembly()->BindAssemblyByName(pAssemblyName, &pPrivAssembly)); - - // Verify that we found this. If this invariant doesn't hold, then the ngen images that reference this winmd are be invalid. - // ALSO, this winmd file is invalid as it doesn't follow spec about how it is distributed. - if (GetAppDomain()->FindAssembly(pPrivAssembly) != this) - { - ThrowHR(COR_E_BADIMAGEFORMAT); - } - } - } -#endif //defined(FEATURE_COMINTEROP) #endif // FEATURE_PREJIT // Flush any log messages diff --git a/src/coreclr/src/vm/ecall.cpp b/src/coreclr/src/vm/ecall.cpp index 7231cd3..deb4eeb 100644 --- a/src/coreclr/src/vm/ecall.cpp +++ b/src/coreclr/src/vm/ecall.cpp @@ -195,9 +195,9 @@ void ECall::PopulateManagedCastHelpers() pDest = pMD->GetMultiCallableAddrOfCode(); SetJitHelperFunction(CORINFO_HELP_UNBOX, pDest); - // Array element accessors are more perf sensitive than other managed helpers and indirection + // Array element accessors are more perf sensitive than other managed helpers and indirection // costs introduced by PreStub could be noticeable (7% to 30% depending on platform). - // Other helpers are either more complex, less common, or have their trivial case inlined by the JIT, + // Other helpers are either more complex, less common, or have their trivial case inlined by the JIT, // so indirection is not as big concern. // We JIT-compile the following helpers eagerly here to avoid indirection costs. @@ -468,7 +468,7 @@ PCODE ECall::GetFCallImpl(MethodDesc * pMD, BOOL * pfSharedOrDynamicFCallImpl /* // COM imported classes have special constructors if (pMT->IsComObjectType() #ifdef FEATURE_COMINTEROP - && pMT != g_pBaseCOMObject && pMT != g_pBaseRuntimeClass + && pMT != g_pBaseCOMObject #endif // FEATURE_COMINTEROP ) { @@ -478,7 +478,6 @@ PCODE ECall::GetFCallImpl(MethodDesc * pMD, BOOL * pfSharedOrDynamicFCallImpl /* // This has to be tlbimp constructor _ASSERTE(pMD->IsCtor()); - _ASSERTE(!pMT->IsProjectedFromWinRT()); // FCComCtor does not need to be in the fcall hashtable since it does not erect frame. return GetEEFuncEntryPoint(FCComCtor); diff --git a/src/coreclr/src/vm/ecalllist.h b/src/coreclr/src/vm/ecalllist.h index 955bf98..f183972 100644 --- a/src/coreclr/src/vm/ecalllist.h +++ b/src/coreclr/src/vm/ecalllist.h @@ -203,10 +203,6 @@ FCFuncStart(gSystem_RuntimeType) FCFuncElement("GetTypeFromCLSIDImpl", ReflectionInvocation::GetClassFromCLSID) FCFuncElement("GetTypeFromProgIDImpl", ReflectionInvocation::GetClassFromProgID) FCFuncElement("InvokeDispMethod", ReflectionInvocation::InvokeDispMethod) -#ifdef FEATURE_COMINTEROP_WINRT_MANAGED_ACTIVATION - FCFuncElement("IsTypeExportedToWindowsRuntime", RuntimeTypeHandle::IsTypeExportedToWindowsRuntime) -#endif - FCFuncElement("IsWindowsRuntimeObjectType", RuntimeTypeHandle::IsWindowsRuntimeObjectType) #endif // defined(FEATURE_COMINTEROP) FCFuncEnd() @@ -483,9 +479,6 @@ FCFuncStart(gAssemblyLoadContextFuncs) QCFuncElement("PrepareForAssemblyLoadContextRelease", AssemblyNative::PrepareForAssemblyLoadContextRelease) QCFuncElement("LoadFromPath", AssemblyNative::LoadFromPath) QCFuncElement("LoadFromStream", AssemblyNative::LoadFromStream) -#ifdef FEATURE_COMINTEROP_WINRT_MANAGED_ACTIVATION - QCFuncElement("LoadTypeForWinRTTypeNameInContextInternal", AssemblyNative::LoadTypeForWinRTTypeNameInContext) -#endif #ifndef TARGET_UNIX QCFuncElement("LoadFromInMemoryModuleInternal", AssemblyNative::LoadFromInMemoryModule) #endif @@ -812,16 +805,6 @@ FCFuncStart(gInteropMarshalFuncs) #endif // FEATURE_COMINTEROP FCFuncEnd() -#ifdef FEATURE_COMINTEROP -FCFuncStart(gWindowsRuntimeMarshalFuncs) - FCFuncElement("GetNativeActivationFactory", MarshalNative::GetNativeActivationFactory) - FCFuncElement("GetHRForException", MarshalNative::GetHRForException_WinRT) - FCFuncElement("GetUniqueObjectForIUnknownWithoutUnboxing", MarshalNative::GetUniqueObjectForIUnknownWithoutUnboxing) - FCFuncElement("InitializeManagedWinRTFactoryObject", MarshalNative::InitializeManagedWinRTFactoryObject) - FCFuncElement("InitializeWrapper", MarshalNative::InitializeWrapperForWinRT) -FCFuncEnd() -#endif - FCFuncStart(gInteropNativeLibraryFuncs) QCFuncElement("LoadFromPath", NativeLibraryNative::LoadFromPath) QCFuncElement("LoadByName", NativeLibraryNative::LoadByName) @@ -913,12 +896,6 @@ FCFuncStart(gRuntimeHelpers) FCFuncElement("GetMethodsJittedCount", GetJittedMethodsCount) FCFuncEnd() -FCFuncStart(gContextSynchronizationFuncs) -#ifdef FEATURE_APPX - QCFuncElement("GetWinRTDispatcherForCurrentThread", SynchronizationContextNative::GetWinRTDispatcherForCurrentThread) -#endif -FCFuncEnd() - FCFuncStart(gMngdFixedArrayMarshalerFuncs) FCFuncElement("CreateMarshaler", MngdFixedArrayMarshaler::CreateMarshaler) FCFuncElement("ConvertSpaceToNative", MngdFixedArrayMarshaler::ConvertSpaceToNative) @@ -949,12 +926,6 @@ FCFuncStart(gInterfaceMarshalerFuncs) FCFuncElement("ConvertToNative", StubHelpers::InterfaceMarshaler__ConvertToNative) FCFuncElement("ConvertToManaged", StubHelpers::InterfaceMarshaler__ConvertToManaged) QCFuncElement("ClearNative", StubHelpers::InterfaceMarshaler__ClearNative) - FCFuncElement("ConvertToManagedWithoutUnboxing", StubHelpers::InterfaceMarshaler__ConvertToManagedWithoutUnboxing) -FCFuncEnd() - -FCFuncStart(gUriMarshalerFuncs) - FCFuncElement("GetRawUriFromNative", StubHelpers::UriMarshaler__GetRawUriFromNative) - FCFuncElement("CreateNativeUriInstanceHelper", StubHelpers::UriMarshaler__CreateNativeUriInstance) FCFuncEnd() FCFuncStart(gMngdSafeArrayMarshalerFuncs) @@ -966,20 +937,6 @@ FCFuncStart(gMngdSafeArrayMarshalerFuncs) FCFuncElement("ClearNative", MngdSafeArrayMarshaler::ClearNative) FCFuncEnd() -FCFuncStart(gMngdHiddenLengthArrayMarshalerFuncs) - FCFuncElement("CreateMarshaler", MngdHiddenLengthArrayMarshaler::CreateMarshaler) - FCFuncElement("ConvertSpaceToNative", MngdHiddenLengthArrayMarshaler::ConvertSpaceToNative) - FCFuncElement("ConvertContentsToNative", MngdHiddenLengthArrayMarshaler::ConvertContentsToNative) - FCFuncElement("ConvertSpaceToManaged", MngdHiddenLengthArrayMarshaler::ConvertSpaceToManaged) - FCFuncElement("ConvertContentsToManaged", MngdHiddenLengthArrayMarshaler::ConvertContentsToManaged) - FCFuncElement("ClearNativeContents", MngdHiddenLengthArrayMarshaler::ClearNativeContents) -FCFuncEnd() - -FCFuncStart(gWinRTTypeNameConverterFuncs) - FCFuncElement("ConvertToWinRTTypeName", StubHelpers::WinRTTypeNameConverter__ConvertToWinRTTypeName) - FCFuncElement("GetTypeFromWinRTTypeName", StubHelpers::WinRTTypeNameConverter__GetTypeFromWinRTTypeName) -FCFuncEnd() - #endif // FEATURE_COMINTEROP #ifdef FEATURE_COMWRAPPERS @@ -1012,15 +969,6 @@ FCFuncStart(gStubHelperFuncs) #ifdef FEATURE_COMINTEROP FCFuncElement("InternalGetCOMHRExceptionObject", StubHelpers::GetCOMHRExceptionObject) FCFuncElement("GetCOMIPFromRCW", StubHelpers::GetCOMIPFromRCW) - FCFuncElement("GetCOMIPFromRCW_WinRT", StubHelpers::GetCOMIPFromRCW_WinRT) - FCFuncElement("GetCOMIPFromRCW_WinRTSharedGeneric", StubHelpers::GetCOMIPFromRCW_WinRTSharedGeneric) - FCFuncElement("GetCOMIPFromRCW_WinRTDelegate", StubHelpers::GetCOMIPFromRCW_WinRTDelegate) - FCFuncElement("ShouldCallWinRTInterface", StubHelpers::ShouldCallWinRTInterface) - FCFuncElement("GetTargetForAmbiguousVariantCall", StubHelpers::GetTargetForAmbiguousVariantCall) - FCFuncElement("GetDelegateInvokeMethod", StubHelpers::GetDelegateInvokeMethod) - FCFuncElement("GetWinRTFactoryObject", StubHelpers::GetWinRTFactoryObject) - FCFuncElement("GetWinRTFactoryReturnValue", StubHelpers::GetWinRTFactoryReturnValue) - FCFuncElement("GetOuterInspectable", StubHelpers::GetOuterInspectable) #endif // FEATURE_COMINTEROP #ifdef PROFILING_SUPPORTED FCFuncElement("ProfilerBeginTransitionCallback", StubHelpers::ProfilerBeginTransitionCallback) @@ -1088,17 +1036,6 @@ FCFuncStart(gEventPipeInternalFuncs) FCFuncEnd() #endif // FEATURE_PERFTRACING -#ifdef FEATURE_COMINTEROP -FCFuncStart(gRuntimeClassFuncs) - FCFuncElement("GetRedirectedGetHashCodeMD", ComObject::GetRedirectedGetHashCodeMD) - FCFuncElement("RedirectGetHashCode", ComObject::RedirectGetHashCode) - FCFuncElement("GetRedirectedToStringMD", ComObject::GetRedirectedToStringMD) - FCFuncElement("RedirectToString", ComObject::RedirectToString) - FCFuncElement("GetRedirectedEqualsMD", ComObject::GetRedirectedEqualsMD) - FCFuncElement("RedirectEquals", ComObject::RedirectEquals) -FCFuncEnd() -#endif // ifdef FEATURE_COMINTEROP - FCFuncStart(gWeakReferenceFuncs) FCFuncElement("Create", WeakReferenceNative::Create) FCFuncElement("Finalize", WeakReferenceNative::Finalize) @@ -1252,9 +1189,6 @@ FCClassElement("MdUtf8String", "System", gMdUtf8String) FCClassElement("MetadataImport", "System.Reflection", gMetaDataImport) FCClassElement("MissingMemberException", "System", gMissingMemberExceptionFuncs) FCClassElement("MngdFixedArrayMarshaler", "System.StubHelpers", gMngdFixedArrayMarshalerFuncs) -#ifdef FEATURE_COMINTEROP -FCClassElement("MngdHiddenLengthArrayMarshaler", "System.StubHelpers", gMngdHiddenLengthArrayMarshalerFuncs) -#endif // FEATURE_COMINTEROP FCClassElement("MngdNativeArrayMarshaler", "System.StubHelpers", gMngdNativeArrayMarshalerFuncs) FCClassElement("MngdRefCustomMarshaler", "System.StubHelpers", gMngdRefCustomMarshalerFuncs) #ifdef FEATURE_COMINTEROP @@ -1282,9 +1216,6 @@ FCClassElement("PunkSafeHandle", "System.Reflection.Emit", gSymWrapperCodePunkSa FCClassElement("RegisteredWaitHandleSafe", "System.Threading", gRegisteredWaitHandleFuncs) FCClassElement("RuntimeAssembly", "System.Reflection", gRuntimeAssemblyFuncs) -#ifdef FEATURE_COMINTEROP -FCClassElement("RuntimeClass", "System.Runtime.InteropServices.WindowsRuntime", gRuntimeClassFuncs) -#endif // FEATURE_COMINTEROP FCClassElement("RuntimeFieldHandle", "System", gCOMFieldHandleNewFuncs) FCClassElement("RuntimeHelpers", "System.Runtime.CompilerServices", gRuntimeHelpers) FCClassElement("RuntimeMethodHandle", "System", gRuntimeMethodHandle) @@ -1298,7 +1229,6 @@ FCClassElement("StackTrace", "System.Diagnostics", gDiagnosticsStackTrace) FCClassElement("Stream", "System.IO", gStreamFuncs) FCClassElement("String", "System", gStringFuncs) FCClassElement("StubHelpers", "System.StubHelpers", gStubHelperFuncs) -FCClassElement("SynchronizationContext", "System.Threading", gContextSynchronizationFuncs) FCClassElement("Thread", "System.Threading", gThreadFuncs) FCClassElement("ThreadPool", "System.Threading", gThreadPoolFuncs) FCClassElement("TimerQueue", "System.Threading", gTimerFuncs) @@ -1307,9 +1237,6 @@ FCClassElement("TypeBuilder", "System.Reflection.Emit", gCOMClassWriter) FCClassElement("TypeLoadException", "System", gTypeLoadExceptionFuncs) FCClassElement("TypeNameParser", "System", gTypeNameParser) FCClassElement("TypedReference", "System", gTypedReferenceFuncs) -#ifdef FEATURE_COMINTEROP -FCClassElement("UriMarshaler", "System.StubHelpers", gUriMarshalerFuncs) -#endif #ifdef FEATURE_UTF8STRING FCClassElement("Utf8String", "System", gUtf8StringFuncs) #endif // FEATURE_UTF8STRING @@ -1321,12 +1248,6 @@ FCClassElement("WaitHandle", "System.Threading", gWaitHandleFuncs) FCClassElement("WeakReference", "System", gWeakReferenceFuncs) FCClassElement("WeakReference`1", "System", gWeakReferenceOfTFuncs) -#ifdef FEATURE_COMINTEROP -FCClassElement("WinRTTypeNameConverter", "System.StubHelpers", gWinRTTypeNameConverterFuncs) -FCClassElement("WindowsRuntimeMarshal", "System.Runtime.InteropServices.WindowsRuntime", gWindowsRuntimeMarshalFuncs) -#endif // FEATURE_COMINTEROP - - #if defined(FEATURE_EVENTSOURCE_XPLAT) FCClassElement("XplatEventLogger", "System.Diagnostics.Tracing", gEventLogger) #endif //defined(FEATURE_EVENTSOURCE_XPLAT) diff --git a/src/coreclr/src/vm/eedbginterfaceimpl.cpp b/src/coreclr/src/vm/eedbginterfaceimpl.cpp index ae268d4..db0a0d0 100644 --- a/src/coreclr/src/vm/eedbginterfaceimpl.cpp +++ b/src/coreclr/src/vm/eedbginterfaceimpl.cpp @@ -813,8 +813,7 @@ MethodDesc *EEDbgInterfaceImpl::LoadMethodDef(Module* pModule, if (numGenericClassArgs > 0) { thOwner = ClassLoader::LoadGenericInstantiationThrowing(pModule, typeDef, Instantiation(pGenericClassArgs, numGenericClassArgs)); - // for classes supporting generic interop force remotable method descs - forceRemotable = thOwner.GetMethodTable()->SupportsGenericInterop(TypeHandle::Interop_ManagedToNative); + forceRemotable = false; } #endif // FEATURE_COMINTEROP } diff --git a/src/coreclr/src/vm/eventtrace.cpp b/src/coreclr/src/vm/eventtrace.cpp index 026eec4..1b8bf3d 100644 --- a/src/coreclr/src/vm/eventtrace.cpp +++ b/src/coreclr/src/vm/eventtrace.cpp @@ -914,7 +914,7 @@ VOID ETW::GCLog::FireGcStart(ETW_GC_INFO * pGcInfo) // the CLR to perform a GC. The important work here is to create a managed thread for // the current thread BEFORE the GC begins. On both ETW and profapi threads, there may // not yet be a managed thread object. But some scenarios require a managed thread -// object be present (notably if we need to call into Jupiter during the GC). +// object be present.. // // Return Value: // HRESULT indicating success or failure @@ -941,7 +941,7 @@ HRESULT ETW::GCLog::ForceGCForDiagnostics() // Caller should ensure we're past startup. _ASSERTE(IsGarbageCollectorFullyInitialized()); - // In immersive apps the GarbageCollect() call below will call into Jupiter, + // In immersive apps the GarbageCollect() call below will call into the WinUI reference tracker, // which will call back into the runtime to track references. This call // chain would cause a Thread object to be created for this thread while code // higher on the stack owns the ThreadStoreLock. This will lead to asserts @@ -960,7 +960,7 @@ HRESULT ETW::GCLog::ForceGCForDiagnostics() EX_TRY { // Need to switch to cooperative mode as the thread will access managed - // references (through Jupiter callbacks). + // references (through reference tracker callbacks). GCX_COOP(); #endif // FEATURE_REDHAWK @@ -1165,7 +1165,6 @@ void BulkComLogger::WriteCcw(ComCallWrapper *pCcw, Object **handle, Object *obj) #ifdef FEATURE_COMINTEROP IUnknown *iUnk = NULL; int refCount = 0; - ULONG jupiterRefCount = 0; ULONG flags = 0; if (pCcw) @@ -1175,13 +1174,9 @@ void BulkComLogger::WriteCcw(ComCallWrapper *pCcw, Object **handle, Object *obj) iUnk = pCcw->GetBasicIP(true); refCount = pCcw->GetRefCount(); - jupiterRefCount = pCcw->GetJupiterRefCount(); if (pCcw->IsWrapperActive()) flags |= EventCCWEntry::Strong; - - if (pCcw->IsPegged()) - flags |= EventCCWEntry::Pegged; } EventCCWEntry &ccw = m_etwCcwData[m_currCcw++]; @@ -1190,7 +1185,7 @@ void BulkComLogger::WriteCcw(ComCallWrapper *pCcw, Object **handle, Object *obj) ccw.TypeID = (ULONGLONG)obj->GetTypeHandle().AsTAddr(); ccw.IUnk = (ULONGLONG)iUnk; ccw.RefCount = refCount; - ccw.JupiterRefCount = jupiterRefCount; + ccw.JupiterRefCount = 0; ccw.Flags = flags; if (m_currCcw >= kMaxCcwCount) @@ -1772,8 +1767,8 @@ int BulkTypeEventLogger::LogSingleType(TypeHandle th) unsigned rank = th.GetRank(); if (rank < kEtwTypeFlagsArrayRankMax) { - // Only ranks less than kEtwTypeFlagsArrayRankMax are supported. - // Fortunately kEtwTypeFlagsArrayRankMax should be greater than the + // Only ranks less than kEtwTypeFlagsArrayRankMax are supported. + // Fortunately kEtwTypeFlagsArrayRankMax should be greater than the // number of ranks the type loader will support rank <<= kEtwTypeFlagsArrayRankShift; _ASSERTE((rank & kEtwTypeFlagsArrayRankMask) == rank); @@ -6247,8 +6242,8 @@ VOID ETW::MethodLog::SendMethodDetailsEvent(MethodDesc *pMethodDesc) EX_TRY { - if(ETW_TRACING_CATEGORY_ENABLED(MICROSOFT_WINDOWS_DOTNETRUNTIME_PROVIDER_DOTNET_Context, - TRACE_LEVEL_INFORMATION, + if(ETW_TRACING_CATEGORY_ENABLED(MICROSOFT_WINDOWS_DOTNETRUNTIME_PROVIDER_DOTNET_Context, + TRACE_LEVEL_INFORMATION, CLR_METHODDIAGNOSTIC_KEYWORD)) { if (pMethodDesc->IsDynamicMethod()) @@ -6283,7 +6278,7 @@ VOID ETW::MethodLog::SendMethodDetailsEvent(MethodDesc *pMethodDesc) } EX_END_CATCH(RethrowTerminalExceptions); if (!fSucceeded) - goto done; + goto done; // Log any referenced parameter types for (COUNT_T i=0; i < cParams; i++) diff --git a/src/coreclr/src/vm/excep.cpp b/src/coreclr/src/vm/excep.cpp index ff2e674..c0b89c0 100644 --- a/src/coreclr/src/vm/excep.cpp +++ b/src/coreclr/src/vm/excep.cpp @@ -251,67 +251,6 @@ void GetExceptionMessage(OBJECTREF throwable, SString &result) pString->GetSString(result); } // void GetExceptionMessage() -#if FEATURE_COMINTEROP -// This method returns IRestrictedErrorInfo associated with the ErrorObject. -// It checks whether the given managed exception object has __HasRestrictedLanguageErrorObject set -// in which case it returns the IRestrictedErrorInfo associated with the __RestrictedErrorObject. -IRestrictedErrorInfo* GetRestrictedErrorInfoFromErrorObject(OBJECTREF throwable) -{ - CONTRACTL - { - THROWS; - GC_TRIGGERS; - MODE_COOPERATIVE; - INJECT_FAULT(ThrowOutOfMemory()); - } - CONTRACTL_END; - - IRestrictedErrorInfo* pRestrictedErrorInfo = NULL; - - // If there is no object, there is no restricted error. - if (throwable == NULL) - return NULL; - - _ASSERTE(IsException(throwable->GetMethodTable())); // what is the pathway here? - if (!IsException(throwable->GetMethodTable())) - { - return NULL; - } - - struct _gc { - OBJECTREF Throwable; - OBJECTREF RestrictedErrorInfoObjRef; - } gc; - - ZeroMemory(&gc, sizeof(gc)); - GCPROTECT_BEGIN(gc); - - gc.Throwable = throwable; - - // Get the MethodDesc on which we'll call. - MethodDescCallSite getRestrictedLanguageErrorObject(METHOD__EXCEPTION__TRY_GET_RESTRICTED_LANGUAGE_ERROR_OBJECT, &gc.Throwable); - - // Make the call. - ARG_SLOT Args[] = - { - ObjToArgSlot(gc.Throwable), - PtrToArgSlot(&gc.RestrictedErrorInfoObjRef) - }; - - BOOL bHasLanguageRestrictedErrorObject = (BOOL)getRestrictedLanguageErrorObject.Call_RetBool(Args); - - if(bHasLanguageRestrictedErrorObject) - { - // The __RestrictedErrorObject represents IRestrictedErrorInfo RCW of a non-CLR platform. Lets get the corresponding IRestrictedErrorInfo for it. - pRestrictedErrorInfo = (IRestrictedErrorInfo *)GetComIPFromObjectRef(&gc.RestrictedErrorInfoObjRef, IID_IRestrictedErrorInfo); - } - - GCPROTECT_END(); - - return pRestrictedErrorInfo; -} -#endif - STRINGREF GetExceptionMessage(OBJECTREF throwable) { CONTRACTL @@ -3046,22 +2985,9 @@ void FreeExceptionData(ExceptionData *pedata) SysFreeString(pedata->bstrDescription); if (pedata->bstrHelpFile) SysFreeString(pedata->bstrHelpFile); -#ifdef FEATURE_COMINTEROP - if (pedata->bstrRestrictedError) - SysFreeString(pedata->bstrRestrictedError); - if (pedata->bstrReference) - SysFreeString(pedata->bstrReference); - if (pedata->bstrCapabilitySid) - SysFreeString(pedata->bstrCapabilitySid); - if (pedata->pRestrictedErrorInfo) - { - ULONG cbRef = SafeRelease(pedata->pRestrictedErrorInfo); - LogInteropRelease(pedata->pRestrictedErrorInfo, cbRef, "IRestrictedErrorInfo"); - } -#endif // FEATURE_COMINTEROP } -void GetExceptionForHR(HRESULT hr, IErrorInfo* pErrInfo, bool fUseCOMException, OBJECTREF* pProtectedThrowable, IRestrictedErrorInfo *pResErrorInfo, BOOL bHasLangRestrictedErrInfo) +void GetExceptionForHR(HRESULT hr, IErrorInfo* pErrInfo, OBJECTREF* pProtectedThrowable) { CONTRACTL { @@ -3105,7 +3031,7 @@ void GetExceptionForHR(HRESULT hr, IErrorInfo* pErrInfo, bool fUseCOMException, // the native IErrorInfo. if ((*pProtectedThrowable) == NULL) { - EECOMException ex(hr, pErrInfo, fUseCOMException, pResErrorInfo, bHasLangRestrictedErrInfo COMMA_INDEBUG(FALSE)); + EECOMException ex(hr, pErrInfo COMMA_INDEBUG(FALSE)); (*pProtectedThrowable) = ex.GetThrowable(); } } @@ -3115,18 +3041,11 @@ void GetExceptionForHR(HRESULT hr, IErrorInfo* pErrInfo, bool fUseCOMException, // so we'll create an exception based solely on the hresult. if ((*pProtectedThrowable) == NULL) { - EEMessageException ex(hr, fUseCOMException); + EEMessageException ex(hr); (*pProtectedThrowable) = ex.GetThrowable(); } } -void GetExceptionForHR(HRESULT hr, IErrorInfo* pErrInfo, OBJECTREF* pProtectedThrowable) -{ - WRAPPER_NO_CONTRACT; - - GetExceptionForHR(hr, pErrInfo, true, pProtectedThrowable); -} - void GetExceptionForHR(HRESULT hr, OBJECTREF* pProtectedThrowable) { CONTRACTL @@ -3144,7 +3063,7 @@ void GetExceptionForHR(HRESULT hr, OBJECTREF* pProtectedThrowable) pErrInfo = NULL; #endif - GetExceptionForHR(hr, pErrInfo, true, pProtectedThrowable); + GetExceptionForHR(hr, pErrInfo, pProtectedThrowable); } @@ -4115,7 +4034,7 @@ LONG WatsonLastChance( // EXCEPTION_CONTINUE_SEARCH, _CONTINUE_ // Crash dump generating program arguments if enabled. LPCWSTR g_createDumpCommandLine = nullptr; -static void +static void BuildCreateDumpCommandLine( SString& commandLine, LPCWSTR dumpName, @@ -6817,7 +6736,7 @@ AdjustContextForJITHelpers( SetSP(pContext, PCODE((BYTE*)GetSP(pContext) + sizeof(void*))); } - if ((f_IP >= (void *) JIT_StackProbe) && (f_IP <= (void *) JIT_StackProbe_End)) + if ((f_IP >= (void *) JIT_StackProbe) && (f_IP <= (void *) JIT_StackProbe_End)) { TADDR ebp = GetFP(pContext); void* callsite = (void *)*dac_cast(ebp + 4); @@ -11732,11 +11651,11 @@ VOID DECLSPEC_NORETURN RealCOMPlusThrowHR(HRESULT hr, IErrorInfo* pErrInfo, Exce { if (pInnerException == NULL) { - EX_THROW(EECOMException, (hr, pErrInfo, true, NULL, FALSE)); + EX_THROW(EECOMException, (hr, pErrInfo)); } else { - EX_THROW_WITH_INNER(EECOMException, (hr, pErrInfo, true, NULL, FALSE), pInnerException); + EX_THROW_WITH_INNER(EECOMException, (hr, pErrInfo), pInnerException); } } else diff --git a/src/coreclr/src/vm/excep.h b/src/coreclr/src/vm/excep.h index 661eefe..0f8504c 100644 --- a/src/coreclr/src/vm/excep.h +++ b/src/coreclr/src/vm/excep.h @@ -352,14 +352,10 @@ void ExceptionPreserveStackTrace(OBJECTREF throwable); // Create an exception object for an HRESULT //========================================================================== -void GetExceptionForHR(HRESULT hr, IErrorInfo* pErrInfo, bool fUseCOMException, OBJECTREF* pProtectedThrowable, IRestrictedErrorInfo *pResErrorInfo = NULL, BOOL bHasLanguageRestrictedErrorInfo = FALSE); void GetExceptionForHR(HRESULT hr, IErrorInfo* pErrInfo, OBJECTREF* pProtectedThrowable); void GetExceptionForHR(HRESULT hr, OBJECTREF* pProtectedThrowable); HRESULT GetHRFromThrowable(OBJECTREF throwable); -#if FEATURE_COMINTEROP -IRestrictedErrorInfo* GetRestrictedErrorInfoFromErrorObject(OBJECTREF throwable); -#endif //========================================================================== // Throw an ArithmeticException //========================================================================== diff --git a/src/coreclr/src/vm/fieldmarshaler.cpp b/src/coreclr/src/vm/fieldmarshaler.cpp index a168722..5b9133c 100644 --- a/src/coreclr/src/vm/fieldmarshaler.cpp +++ b/src/coreclr/src/vm/fieldmarshaler.cpp @@ -56,20 +56,13 @@ VOID ParseNativeType(Module* pModule, CONTRACTL_END; BOOL fAnsi = (flags == ParseNativeTypeFlags::IsAnsi); -#ifdef FEATURE_COMINTEROP - BOOL fIsWinRT = (flags == ParseNativeTypeFlags::IsWinRT); -#endif // FEATURE_COMINTEROP MarshalInfo mlInfo( pModule, sig, pTypeContext, pFD->GetMemberDef(), -#if FEATURE_COMINTEROP - fIsWinRT ? MarshalInfo::MARSHAL_SCENARIO_WINRT_FIELD : MarshalInfo::MARSHAL_SCENARIO_FIELD, -#else MarshalInfo::MARSHAL_SCENARIO_FIELD, -#endif fAnsi ? nltAnsi : nltUnicode, nlfNone, FALSE, @@ -158,12 +151,6 @@ VOID ParseNativeType(Module* pModule, *pNFD = NativeFieldDescriptor(pFD, NativeFieldCategory::INTEGER, sizeof(void*), sizeof(void*)); break; #ifdef FEATURE_COMINTEROP - case MarshalInfo::MARSHAL_TYPE_HSTRING: - *pNFD = NativeFieldDescriptor(pFD, NativeFieldCategory::INTEGER, sizeof(HSTRING), sizeof(HSTRING)); - break; - case MarshalInfo::MARSHAL_TYPE_DATETIME: - *pNFD = NativeFieldDescriptor(pFD, NativeFieldCategory::INTEGER, sizeof(INT64), sizeof(INT64)); - break; case MarshalInfo::MARSHAL_TYPE_INTERFACE: *pNFD = NativeFieldDescriptor(pFD, NativeFieldCategory::INTEGER, sizeof(IUnknown*), sizeof(IUnknown*)); break; @@ -210,17 +197,6 @@ VOID ParseNativeType(Module* pModule, case MarshalInfo::MARSHAL_TYPE_FIXED_WSTR: *pNFD = NativeFieldDescriptor(pFD, MscorlibBinder::GetClass(CLASS__UINT16), pargs->fs.fixedStringLength); break; -#ifdef FEATURE_COMINTEROP - case MarshalInfo::MARSHAL_TYPE_SYSTEMTYPE: - *pNFD = NativeFieldDescriptor(pFD, MscorlibBinder::GetClass(CLASS__TYPENAMENATIVE)); - break; - case MarshalInfo::MARSHAL_TYPE_EXCEPTION: - *pNFD = NativeFieldDescriptor(pFD, NativeFieldCategory::INTEGER, sizeof(int), sizeof(int)); - break; - case MarshalInfo::MARSHAL_TYPE_NULLABLE: - *pNFD = NativeFieldDescriptor(pFD, NativeFieldCategory::INTEGER, sizeof(IUnknown*), sizeof(IUnknown*)); - break; -#endif case MarshalInfo::MARSHAL_TYPE_UNKNOWN: default: *pNFD = NativeFieldDescriptor(pFD); @@ -246,11 +222,6 @@ bool IsFieldBlittable( nativeType = (CorNativeType)*marshalInfoSig; } - if (nativeType != NATIVE_TYPE_DEFAULT && flags == ParseNativeTypeFlags::IsWinRT) - { - return false; - } - bool isBlittable = false; EX_TRY @@ -289,10 +260,10 @@ bool IsFieldBlittable( isBlittable = (nativeType == NATIVE_TYPE_DEFAULT) || (nativeType == NATIVE_TYPE_INT) || (nativeType == NATIVE_TYPE_UINT); break; case ELEMENT_TYPE_PTR: - isBlittable = nativeType == NATIVE_TYPE_DEFAULT && flags != ParseNativeTypeFlags::IsWinRT; + isBlittable = nativeType == NATIVE_TYPE_DEFAULT; break; case ELEMENT_TYPE_FNPTR: - isBlittable = flags != ParseNativeTypeFlags::IsWinRT && (nativeType == NATIVE_TYPE_DEFAULT || nativeType == NATIVE_TYPE_FUNC); + isBlittable = nativeType == NATIVE_TYPE_DEFAULT || nativeType == NATIVE_TYPE_FUNC; break; case ELEMENT_TYPE_VALUETYPE: if (nativeType != NATIVE_TYPE_DEFAULT && nativeType != NATIVE_TYPE_STRUCT) @@ -305,19 +276,6 @@ bool IsFieldBlittable( // As a result, a field of type System.Decimal can't be blittable. isBlittable = false; } -#if FEATURE_COMINTEROP - else if (flags == ParseNativeTypeFlags::IsWinRT) - { - if (valueTypeHandle.GetMethodTable()->HasSameTypeDefAs(g_pNullableClass)) - { - isBlittable = false; - } - else if (valueTypeHandle.GetMethodTable()->HasSameTypeDefAs(MscorlibBinder::GetClass(CLASS__KEYVALUEPAIRGENERIC))) - { - isBlittable = false; - } - } -#endif else { isBlittable = !valueTypeHandle.GetMethodTable()->HasInstantiation() && valueTypeHandle.GetMethodTable()->IsBlittable(); diff --git a/src/coreclr/src/vm/fieldmarshaler.h b/src/coreclr/src/vm/fieldmarshaler.h index dbd8269..075f979 100644 --- a/src/coreclr/src/vm/fieldmarshaler.h +++ b/src/coreclr/src/vm/fieldmarshaler.h @@ -45,8 +45,7 @@ struct RawFieldPlacementInfo enum class ParseNativeTypeFlags : int { None = 0x00, - IsAnsi = 0x01, - IsWinRT = 0x02, + IsAnsi = 0x01 }; //======================================================================= diff --git a/src/coreclr/src/vm/frameworkexceptionloader.cpp b/src/coreclr/src/vm/frameworkexceptionloader.cpp deleted file mode 100644 index 72b1f93..0000000 --- a/src/coreclr/src/vm/frameworkexceptionloader.cpp +++ /dev/null @@ -1,97 +0,0 @@ -// 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. - - - -// Just the subset of functionality from the MscorlibBinder necessary for exceptions. - -#include "common.h" -#include "frameworkexceptionloader.h" -#include "typeparse.h" - - -struct ExceptionLocationData -{ - LPCUTF8 Namespace; - LPCUTF8 Name; - LPCUTF8 AssemblySimpleName; -}; - -static const -ExceptionLocationData g_ExceptionLocationData[] = { -#define DEFINE_EXCEPTION(ns, reKind, bHRformessage, ...) -#define DEFINE_EXCEPTION_HR_WINRT_ONLY(ns, reKind, ...) -#define DEFINE_EXCEPTION_IN_OTHER_FX_ASSEMBLY(ns, reKind, assemblySimpleName, bHRformessage, ...) { ns, PTR_CSTR((TADDR) # reKind), assemblySimpleName }, -#include "rexcep.h" -}; - - -// Note that some assemblies, like System.Runtime.WindowsRuntime, might not be installed on pre-Windows 8 machines. -// This may return null. -MethodTable* FrameworkExceptionLoader::GetException(RuntimeExceptionKind kind) -{ - CONTRACTL - { - THROWS; - GC_TRIGGERS; - - PRECONDITION(kind > kLastExceptionInMscorlib); - PRECONDITION(kind - (kLastExceptionInMscorlib + 1) < COUNTOF(g_ExceptionLocationData)); - } - CONTRACTL_END; - - // This is for loading rarely-used exception objects in arbitrary appdomains. - // The loader should do caching - let's not create a multi-appdomain cache of these exception types here. - // Note that some assemblies, like System.Runtime.WindowsRuntime, might not be installed on pre-Windows 8 machines. - int index = kind - (kLastExceptionInMscorlib + 1); - ExceptionLocationData exData = g_ExceptionLocationData[index]; - _ASSERTE(exData.Name != NULL && exData.AssemblySimpleName != NULL); // Was the exception defined in mscorlib instead? - StackSString assemblyQualifiedName; - _ASSERTE(exData.Namespace != NULL); // If we need to support stuff in a global namespace, fix this. - assemblyQualifiedName.SetUTF8(exData.Namespace); - assemblyQualifiedName.AppendUTF8("."); - assemblyQualifiedName.AppendUTF8(exData.Name); - assemblyQualifiedName.AppendUTF8(", "); - assemblyQualifiedName.AppendUTF8(exData.AssemblySimpleName); - - MethodTable* pMT = NULL; - // Loading will either succeed or throw a FileLoadException. Catch & swallow that exception. - EX_TRY - { - pMT = TypeName::GetTypeFromAsmQualifiedName(assemblyQualifiedName.GetUnicode()).GetMethodTable(); - - // Since this type is from another assembly, we must ensure that assembly has been sufficiently loaded. - pMT->EnsureActive(); - } - EX_CATCH - { - Exception *ex = GET_EXCEPTION(); - - // Let non-file-not-found exceptions propagate - if (EEFileLoadException::GetFileLoadKind(ex->GetHR()) != kFileNotFoundException) - EX_RETHROW; - - // Return COMException if we can't load the assembly we expect. - pMT = MscorlibBinder::GetException(kCOMException); - } - EX_END_CATCH(RethrowTerminalExceptions); - - return pMT; -} - -void FrameworkExceptionLoader::GetExceptionName(RuntimeExceptionKind kind, SString & exceptionName) -{ - CONTRACTL { - THROWS; - GC_NOTRIGGER; - MODE_ANY; - - PRECONDITION(kind > kLastExceptionInMscorlib); - PRECONDITION(kind - (kLastExceptionInMscorlib + 1) < COUNTOF(g_ExceptionLocationData)); - } CONTRACTL_END; - - exceptionName.SetUTF8(g_ExceptionLocationData[kind].Namespace); - exceptionName.AppendUTF8("."); - exceptionName.AppendUTF8(g_ExceptionLocationData[kind].Name); -} diff --git a/src/coreclr/src/vm/frameworkexceptionloader.h b/src/coreclr/src/vm/frameworkexceptionloader.h deleted file mode 100644 index 4c81e4a..0000000 --- a/src/coreclr/src/vm/frameworkexceptionloader.h +++ /dev/null @@ -1,26 +0,0 @@ -// 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. - -// Just the subset of functionality from the MscorlibBinder necessary for exceptions. -#ifndef _FRAMEWORKEXCEPTIONLOADER_H_ -#define _FRAMEWORKEXCEPTIONLOADER_H_ - -#include "runtimeexceptionkind.h" - -class MethodTable; - -// For loading exception types that are not defined in mscorlib.dll -class FrameworkExceptionLoader -{ - public: - // - // Utilities for exceptions - // - - static MethodTable *GetException(RuntimeExceptionKind kind); - - static void GetExceptionName(RuntimeExceptionKind kind, SString & exceptionName); -}; - -#endif // _FRAMEWORKEXCEPTIONLOADER_H_ diff --git a/src/coreclr/src/vm/gcenv.h b/src/coreclr/src/vm/gcenv.h index 8837e8b..d223694 100644 --- a/src/coreclr/src/vm/gcenv.h +++ b/src/coreclr/src/vm/gcenv.h @@ -13,10 +13,6 @@ #include "threadsuspend.h" -#ifdef FEATURE_COMINTEROP -#include -#endif - #include "stubhelpers.h" #include "eeprofinterfaces.inl" diff --git a/src/coreclr/src/vm/gchelpers.cpp b/src/coreclr/src/vm/gchelpers.cpp index 5f375da..60e0a03 100644 --- a/src/coreclr/src/vm/gchelpers.cpp +++ b/src/coreclr/src/vm/gchelpers.cpp @@ -34,8 +34,6 @@ #include "runtimecallablewrapper.h" #endif // FEATURE_COMINTEROP -#include "rcwwalker.h" - //======================================================================== // // ALLOCATION HELPERS @@ -982,7 +980,7 @@ OBJECTREF AllocateObject(MethodTable *pMT #ifdef FEATURE_COMINTEROP #ifdef FEATURE_COMINTEROP_UNMANAGED_ACTIVATION - if (fHandleCom && pMT->IsComObjectType() && !pMT->IsWinRTObjectType()) + if (fHandleCom && pMT->IsComObjectType()) { // Create a instance of __ComObject here is not allowed as we don't know what COM object to create if (pMT == g_pBaseCOMObject) diff --git a/src/coreclr/src/vm/generics.cpp b/src/coreclr/src/vm/generics.cpp index 5a19aac..4333002 100644 --- a/src/coreclr/src/vm/generics.cpp +++ b/src/coreclr/src/vm/generics.cpp @@ -24,11 +24,6 @@ #include "dumpcommon.h" #include "array.h" -#include "generics.inl" -#ifdef FEATURE_COMINTEROP -#include "winrttypenameconverter.h" -#endif // FEATURE_COMINTEROP - /* static */ TypeHandle ClassLoader::CanonicalizeGenericArg(TypeHandle thGenericArg) { @@ -256,8 +251,6 @@ ClassLoader::CreateTypeHandleForNonCanonicalGenericInstantiation( BOOL fHasGuidInfo = FALSE; BOOL fHasCCWTemplate = FALSE; - Generics::DetermineCCWTemplateAndGUIDPresenceOnNonCanonicalMethodTable(pOldMT, fContainsGenericVariables, &fHasGuidInfo, &fHasCCWTemplate); - DWORD dwMultipurposeSlotsMask = 0; dwMultipurposeSlotsMask |= MethodTable::enum_flag_HasPerInstInfo; if (wNumInterfaces != 0) diff --git a/src/coreclr/src/vm/generics.inl b/src/coreclr/src/vm/generics.inl deleted file mode 100644 index afb1bcd..0000000 --- a/src/coreclr/src/vm/generics.inl +++ /dev/null @@ -1,98 +0,0 @@ -// 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. -// -// File: generics.inl -// - -// -// Helper functions for generics implementation -// - -// -// ============================================================================ - -#ifndef GENERICS_INL -#define GENERICS_INL - -#ifdef FEATURE_COMINTEROP -#include "winrttypenameconverter.h" -#endif - -// Generics helper functions -namespace Generics -{ -#ifndef DACCESS_COMPILE - inline void DetermineCCWTemplateAndGUIDPresenceOnNonCanonicalMethodTable( - // Input - MethodTable *pOldMT, BOOL fNewMTContainsGenericVariables, - // Output - BOOL *pfHasGuidInfo, BOOL *pfHasCCWTemplate) - { - STANDARD_VM_CONTRACT; - -#ifdef FEATURE_COMINTEROP - WORD wNumInterfaces = static_cast(pOldMT->GetNumInterfaces()); - - InterfaceInfo_t * pOldIMap = (InterfaceInfo_t *)pOldMT->GetInterfaceMap(); - - BOOL fHasGuidInfo = FALSE; - - // Generic WinRT delegates expose a class interface and need the CCW template - BOOL fHasCCWTemplate = FALSE; - - if (!fNewMTContainsGenericVariables) - { - if (pOldMT->IsInterface()) - { - fHasGuidInfo = (pOldMT->IsProjectedFromWinRT() || WinRTTypeNameConverter::IsRedirectedType(pOldMT, WinMDAdapter::WinMDTypeKind_PInterface)); - } - else if (pOldMT->IsDelegate()) - { - fHasGuidInfo = (pOldMT->IsProjectedFromWinRT() || WinRTTypeNameConverter::IsRedirectedType(pOldMT, WinMDAdapter::WinMDTypeKind_PDelegate)); - - // Generic WinRT delegates expose a class interface and need a CCW template - fHasCCWTemplate = fHasGuidInfo; - } - - if (!fHasCCWTemplate) - { - if (pOldMT->IsInterface()) - { - // Interfaces need the CCW template if they are redirected and need variance - if (pOldMT->HasVariance() && - (pOldMT->IsProjectedFromWinRT() || WinRTTypeNameConverter::IsRedirectedType(pOldMT, WinMDAdapter::WinMDTypeKind_PInterface))) - { - fHasCCWTemplate = TRUE; - } - } - else - { - // Other types may need the CCW template if they implement generic interfaces - for (WORD iItf = 0; iItf < wNumInterfaces; iItf++) - { - // If the class implements a generic WinRT interface, it needs its own (per-instantiation) - // CCW template as the one on EEClass would be shared and hence useless. - OVERRIDE_TYPE_LOAD_LEVEL_LIMIT(CLASS_LOAD_APPROXPARENTS); - MethodTable *pItfMT = pOldIMap[iItf].GetApproxMethodTable(pOldMT->GetLoaderModule()); - if (pItfMT->HasInstantiation() && - (pItfMT->IsProjectedFromWinRT() || WinRTTypeNameConverter::IsRedirectedType(pItfMT, WinMDAdapter::WinMDTypeKind_PInterface))) - { - fHasCCWTemplate = TRUE; - break; - } - } - } - } - } -#else // FEATURE_COMINTEROP - BOOL fHasGuidInfo = FALSE; - BOOL fHasCCWTemplate = FALSE; -#endif // FEATURE_COMINTEROP - *pfHasGuidInfo = fHasGuidInfo; - *pfHasCCWTemplate = fHasCCWTemplate; - } -#endif // DACCESS_COMPILE -} - -#endif // GENERICS_INL diff --git a/src/coreclr/src/vm/genmeth.cpp b/src/coreclr/src/vm/genmeth.cpp index 1e6ca14..e1de988 100644 --- a/src/coreclr/src/vm/genmeth.cpp +++ b/src/coreclr/src/vm/genmeth.cpp @@ -383,7 +383,7 @@ InstantiatedMethodDesc::NewInstantiatedMethodDesc(MethodTable *pExactMT, else if (getWrappedCode) { pDL = DictionaryLayout::Allocate(NUM_DICTIONARY_SLOTS, pAllocator, &amt); -#ifdef _DEBUG +#ifdef _DEBUG { SString name; TypeString::AppendMethodDebug(name, pGenericMDescInRepMT); @@ -413,18 +413,6 @@ InstantiatedMethodDesc::NewInstantiatedMethodDesc(MethodTable *pExactMT, } BOOL forComInterop = FALSE; -#ifdef FEATURE_COMINTEROP - if (pExactMT->IsProjectedFromWinRT()) - { - forComInterop = (pExactMT->IsInterface() || (pExactMT->IsDelegate() && COMDelegate::IsDelegateInvokeMethod(pGenericMDescInRepMT))); - } - else - { - // redirected interfaces and delegates also support interop - forComInterop = (pExactMT->IsWinRTRedirectedInterface(TypeHandle::Interop_ManagedToNative) || - (pExactMT->IsWinRTRedirectedDelegate() && COMDelegate::IsDelegateInvokeMethod(pGenericMDescInRepMT))); - } -#endif // FEATURE_COMINTEROP // Create a new singleton chunk for the new instantiated method descriptor // Notice that we've passed in the method table pointer; this gets diff --git a/src/coreclr/src/vm/ilmarshalers.cpp b/src/coreclr/src/vm/ilmarshalers.cpp index a84d6ca..b7aaa3c 100644 --- a/src/coreclr/src/vm/ilmarshalers.cpp +++ b/src/coreclr/src/vm/ilmarshalers.cpp @@ -1369,26 +1369,6 @@ void ILInterfaceMarshaler::EmitConvertContentsCLRToNative(ILCodeStream* pslILEmi pslILEmit->EmitCALL(METHOD__INTERFACEMARSHALER__CONVERT_TO_NATIVE, 4, 1); EmitStoreNativeValue(pslILEmit); - - if (IsCLRToNative(m_dwMarshalFlags) && - m_pargs->m_pMarshalInfo->IsWinRTScenario()) - { - // If we are calling from CLR into WinRT and we are passing an interface to WinRT, we need to - // keep the object alive across unmanaged call because Jupiter might need to add this - // RCW into their live tree and whatever CCWs referenced by this RCW could get collected - // before the call to native, for example: - // - // Button btn = new Button(); - // btn.OnClick += ... - // m_grid.Children.Add(btn) - // - // In this case, btn could be collected and takes the delegate CCW with it, before Children.add - // native method is called, and as a result Jupiter will add the neutered CCW into the tree - // - // The fix is to extend the lifetime of the argument across the call to native by doing a GC.KeepAlive - // keep the delegate ref alive across the call-out to native - EmitKeepAliveManagedValue(); - } } void ILInterfaceMarshaler::EmitConvertContentsNativeToCLR(ILCodeStream* pslILEmit) @@ -1401,18 +1381,6 @@ void ILInterfaceMarshaler::EmitConvertContentsNativeToCLR(ILCodeStream* pslILEmi // the helper may assign NULL to the home (see below) EmitLoadNativeHomeAddr(pslILEmit); - if (IsCLRToNative(m_dwMarshalFlags) && m_pargs->m_pMarshalInfo->IsWinRTScenario()) - { - // We are converting an interface pointer to object in a CLR->native stub which means - // that the interface pointer has been AddRef'ed for us by the callee. If we end up - // wrapping it with a new RCW, we can omit another AddRef/Release pair. Note that if - // a new RCW is created the native home will be zeroed out by the helper so the call - // to InterfaceMarshaler__ClearNative will become a no-op. - - // Note that we are only doing this for WinRT scenarios to reduce the risk of this change - itfInfo.dwFlags |= ItfMarshalInfo::ITF_MARSHAL_SUPPRESS_ADDREF; - } - if (itfInfo.thItf.GetMethodTable()) { pslILEmit->EmitLDTOKEN(pslILEmit->GetToken(itfInfo.thItf.GetMethodTable())); @@ -1976,134 +1944,6 @@ void ILFixedCSTRMarshaler::EmitConvertContentsNativeToCLR(ILCodeStream* pslILEmi EmitStoreManagedValue(pslILEmit); } -#ifdef FEATURE_COMINTEROP - -LocalDesc ILHSTRINGMarshaler::GetNativeType() -{ - LIMITED_METHOD_CONTRACT; - return LocalDesc(ELEMENT_TYPE_I); // HSTRING -} - -LocalDesc ILHSTRINGMarshaler::GetManagedType() -{ - LIMITED_METHOD_CONTRACT; - return LocalDesc(ELEMENT_TYPE_STRING); -} - -bool ILHSTRINGMarshaler::NeedsClearNative() -{ - LIMITED_METHOD_CONTRACT; - return true; -} - -void ILHSTRINGMarshaler::EmitConvertContentsCLRToNative(ILCodeStream* pslILEmit) -{ - CONTRACTL - { - STANDARD_VM_CHECK; - PRECONDITION(CheckPointer(pslILEmit)); - } - CONTRACTL_END; - - // If we're only going into native code, then we can optimize and create a HSTRING reference over - // the pinned System.String. However, if the parameter will remain in native code as an out - // value, then we need to create a real HSTRING. - if (!IsOut(m_dwMarshalFlags) && !IsRetval(m_dwMarshalFlags)) - { - EmitConvertCLRToHSTRINGReference(pslILEmit); - } - else - { - EmitConvertCLRToHSTRING(pslILEmit); - } -} - -void ILHSTRINGMarshaler::EmitConvertCLRToHSTRINGReference(ILCodeStream* pslILEmit) -{ - CONTRACTL - { - STANDARD_VM_CHECK; - PRECONDITION(CheckPointer(pslILEmit)); - PRECONDITION(!IsOut(m_dwMarshalFlags)); - PRECONDITION(!IsRetval(m_dwMarshalFlags)); - } - CONTRACTL_END; - - // - // The general strategy for fast path marshaling a short lived System.String -> HSTRING is: - // 1. Pin the System.String - // 2. Create an HSTRING Reference over the pinned string - // 3. Pass that reference to native code - // - - // Local to hold the HSTRING_HEADER of the HSTRING reference - MethodTable *pHStringHeaderMT = MscorlibBinder::GetClass(CLASS__HSTRING_HEADER_MANAGED); - DWORD dwHStringHeaderLocal = pslILEmit->NewLocal(pHStringHeaderMT); - - // Local to hold the pinned input string - LocalDesc pinnedStringDesc = GetManagedType(); - pinnedStringDesc.MakePinned(); - DWORD dwPinnedStringLocal = pslILEmit->NewLocal(pinnedStringDesc); - - // pinnedString = managed - EmitLoadManagedValue(pslILEmit); - pslILEmit->EmitSTLOC(dwPinnedStringLocal); - - // hstring = HSTRINGMarshaler.ConvertManagedToNativeReference(pinnedString, out HStringHeader) - pslILEmit->EmitLDLOC(dwPinnedStringLocal); - pslILEmit->EmitLDLOCA(dwHStringHeaderLocal); - pslILEmit->EmitCALL(METHOD__HSTRINGMARSHALER__CONVERT_TO_NATIVE_REFERENCE, 2, 1); - - EmitLogNativeArgument(pslILEmit, dwPinnedStringLocal); - - EmitStoreNativeValue(pslILEmit); -} - -void ILHSTRINGMarshaler::EmitConvertCLRToHSTRING(ILCodeStream* pslILEmit) -{ - CONTRACTL - { - STANDARD_VM_CHECK; - PRECONDITION(CheckPointer(pslILEmit)); - } - CONTRACTL_END; - - // hstring = HSTRINGMarshaler.ConvertManagedToNative(managed); - EmitLoadManagedValue(pslILEmit); - pslILEmit->EmitCALL(METHOD__HSTRINGMARSHALER__CONVERT_TO_NATIVE, 1, 1); - EmitStoreNativeValue(pslILEmit); -} - -void ILHSTRINGMarshaler::EmitConvertContentsNativeToCLR(ILCodeStream* pslILEmit) -{ - STANDARD_VM_CONTRACT; - - // - // To convert an HSTRING to a CLR String: - // 1. WindowsGetStringRawBuffer() to get the raw string data - // 2. WindowsGetStringLen() to get the string length - // 3. Construct a System.String from these parameters - // 4. Release the HSTRING - // - - // string = HSTRINGMarshaler.ConvertNativeToManaged(native); - EmitLoadNativeValue(pslILEmit); - pslILEmit->EmitCALL(METHOD__HSTRINGMARSHALER__CONVERT_TO_MANAGED, 1, 1); - EmitStoreManagedValue(pslILEmit); -} - - -void ILHSTRINGMarshaler::EmitClearNative(ILCodeStream* pslILEmit) -{ - STANDARD_VM_CONTRACT; - - // HStringMarshaler.ClearNative(hstring) - EmitLoadNativeValue(pslILEmit); - pslILEmit->EmitCALL(METHOD__HSTRINGMARSHALER__CLEAR_NATIVE, 1, 0); -} - -#endif // FEATURE_COMINTEROP - LocalDesc ILCUTF8Marshaler::GetManagedType() { LIMITED_METHOD_CONTRACT; @@ -5045,1591 +4885,132 @@ FCIMPL3(void, MngdSafeArrayMarshaler::ClearNative, MngdSafeArrayMarshaler* pThis FCIMPLEND #endif // CROSSGEN_COMPILE +#endif // FEATURE_COMINTEROP - -LocalDesc ILHiddenLengthArrayMarshaler::GetNativeType() -{ - LIMITED_METHOD_CONTRACT; - return LocalDesc(ELEMENT_TYPE_I); -} - -LocalDesc ILHiddenLengthArrayMarshaler::GetManagedType() +void ILReferenceCustomMarshaler::EmitCreateMngdMarshaler(ILCodeStream* pslILEmit) { - LIMITED_METHOD_CONTRACT; - - return LocalDesc(ELEMENT_TYPE_OBJECT); -} + CONTRACTL + { + STANDARD_VM_CHECK; + PRECONDITION(-1 == m_dwMngdMarshalerLocalNum); + } + CONTRACTL_END; -void ILHiddenLengthArrayMarshaler::EmitCreateMngdMarshaler(ILCodeStream* pslILEmit) -{ - STANDARD_VM_CONTRACT; + // + // allocate space for marshaler + // m_dwMngdMarshalerLocalNum = pslILEmit->NewLocal(ELEMENT_TYPE_I); - pslILEmit->EmitLDC(sizeof(MngdHiddenLengthArrayMarshaler)); + pslILEmit->EmitLDC(sizeof(MngdRefCustomMarshaler)); pslILEmit->EmitLOCALLOC(); pslILEmit->EmitSTLOC(m_dwMngdMarshalerLocalNum); - MethodTable *pElementMT = m_pargs->m_pMarshalInfo->GetArrayElementTypeHandle().GetMethodTable(); - pslILEmit->EmitLDLOC(m_dwMngdMarshalerLocalNum); - pslILEmit->EmitLDTOKEN(pslILEmit->GetToken(pElementMT)); - pslILEmit->EmitCALL(METHOD__RT_TYPE_HANDLE__GETVALUEINTERNAL, 1, 1); - - pslILEmit->EmitLDC(m_pargs->na.m_cbElementSize); - pslILEmit->EmitLDC(m_pargs->na.m_vt); - - if (m_pargs->na.m_vt == VTHACK_NONBLITTABLERECORD) - { - pslILEmit->EmitLDFTN(pslILEmit->GetToken(NDirect::CreateStructMarshalILStub(pElementMT))); - } - else - { - pslILEmit->EmitLoadNullPtr(); - } - - pslILEmit->EmitCALL(METHOD__MNGD_HIDDEN_LENGTH_ARRAY_MARSHALER__CREATE_MARSHALER, 5, 0); -} + pslILEmit->EmitLDLOC(m_dwMngdMarshalerLocalNum); // arg to CreateMarshaler -void ILHiddenLengthArrayMarshaler::EmitMarshalViaPinning(ILCodeStream* pslILEmit) -{ - LocalDesc managedType = GetManagedType(); - managedType.MakePinned(); - DWORD dwPinnedLocal = pslILEmit->NewLocal(managedType); + // + // call CreateCustomMarshalerHelper + // - ILCodeLabel* pMarshalDoneLabel = pslILEmit->NewCodeLabel(); + pslILEmit->EmitLDTOKEN(pslILEmit->GetToken(m_pargs->rcm.m_pMD)); + pslILEmit->EmitCALL(METHOD__METHOD_HANDLE__GETVALUEINTERNAL, 1, 1); - // native = NULL - pslILEmit->EmitLoadNullPtr(); - EmitStoreNativeValue(pslILEmit); + pslILEmit->EmitLDC(m_pargs->rcm.m_paramToken); - // if (managed == null) goto MarshalDone - EmitLoadManagedValue(pslILEmit); - pslILEmit->EmitBRFALSE(pMarshalDoneLabel); + pslILEmit->EmitLDTOKEN(pslILEmit->GetToken(TypeHandle::FromPtr(m_pargs->rcm.m_hndManagedType))); + pslILEmit->EmitCALL(METHOD__RT_TYPE_HANDLE__GETVALUEINTERNAL, 1, 1); - // pinnedLocal = managed; - EmitLoadManagedValue(pslILEmit); - pslILEmit->EmitSTLOC(dwPinnedLocal); + pslILEmit->EmitCALL(METHOD__STUBHELPERS__CREATE_CUSTOM_MARSHALER_HELPER, 3, 1); // arg to CreateMarshaler - // native = pinnedLocal + dataOffset + // + // call MngdRefCustomMarshaler::CreateMarshaler + // - // COMPAT: We cannot generate the same code that the C# compiler generates for - // a fixed() statement on an array since we need to provide a non-null value - // for a 0-length array. For compat reasons, we need to preserve old behavior. - EmitLoadManagedValue(pslILEmit); - pslILEmit->EmitSTLOC(dwPinnedLocal); - pslILEmit->EmitLDLOC(dwPinnedLocal); - pslILEmit->EmitCONV_I(); - // Optimize marshalling by emitting the data ptr offset directly into the IL stream - // instead of doing an FCall to recalulate it each time. - pslILEmit->EmitLDC(ArrayBase::GetDataPtrOffset(m_pargs->m_pMarshalInfo->GetArrayElementTypeHandle().MakeSZArray().GetMethodTable())); - pslILEmit->EmitADD(); - EmitStoreNativeValue(pslILEmit); + pslILEmit->EmitCALL(METHOD__MNGD_REF_CUSTOM_MARSHALER__CREATE_MARSHALER, 2, 0); +} - EmitLogNativeArgument(pslILEmit, dwPinnedLocal); - // MarshalDone: - pslILEmit->EmitLabel(pMarshalDoneLabel); -} +#ifndef CROSSGEN_COMPILE -void ILHiddenLengthArrayMarshaler::EmitConvertSpaceNativeToCLR(ILCodeStream* pslILEmit) +FCIMPL2(void, MngdRefCustomMarshaler::CreateMarshaler, MngdRefCustomMarshaler* pThis, void* pCMHelper) { - STANDARD_VM_CONTRACT; - - EmitLoadMngdMarshaler(pslILEmit); - EmitLoadManagedHomeAddr(pslILEmit); - EmitLoadNativeHomeAddr(pslILEmit); - EmitLoadNativeArrayLength(pslILEmit); + FCALL_CONTRACT; - // MngdHiddenLengthArrayMarshaler::ConvertSpaceToManaged - pslILEmit->EmitCALL(pslILEmit->GetToken(GetConvertSpaceToManagedMethod()), 4, 0); + pThis->m_pCMHelper = (CustomMarshalerHelper*)pCMHelper; } +FCIMPLEND -void ILHiddenLengthArrayMarshaler::EmitConvertSpaceCLRToNative(ILCodeStream* pslILEmit) -{ - STANDARD_VM_CONTRACT; - // If we're marshaling out to native code, then we need to set the length out parameter - if (!IsCLRToNative(m_dwMarshalFlags)) +FCIMPL3(void, MngdRefCustomMarshaler::ConvertContentsToNative, MngdRefCustomMarshaler* pThis, OBJECTREF* pManagedHome, void** pNativeHome) +{ + CONTRACTL { - if (IsByref(m_dwMarshalFlags) || IsRetval(m_dwMarshalFlags) || IsOut(m_dwMarshalFlags)) - { - ILCodeLabel *pSkipGetLengthLabel = pslILEmit->NewCodeLabel(); - - // nativeLen = 0 - pslILEmit->EmitLDC(0); - pslILEmit->EmitCONV_T(m_pargs->m_pMarshalInfo->GetHiddenLengthParamElementType()); - pslILEmit->EmitSTLOC(m_pargs->m_pMarshalInfo->GetHiddenLengthNativeHome()); - - // if (array == null) goto SkipGetLength - EmitLoadManagedValue(pslILEmit); - pslILEmit->EmitBRFALSE(pSkipGetLengthLabel); - - // nativeLen = array.Length - // SkipGetLength: - EmitLoadManagedValue(pslILEmit); - pslILEmit->EmitLDLEN(); - pslILEmit->EmitCONV_T(m_pargs->m_pMarshalInfo->GetHiddenLengthParamElementType()); - pslILEmit->EmitSTLOC(m_pargs->m_pMarshalInfo->GetHiddenLengthNativeHome()); - pslILEmit->EmitLabel(pSkipGetLengthLabel); - - // nativeLenParam = nativeLen - LocalDesc nativeParamType(m_pargs->m_pMarshalInfo->GetHiddenLengthParamElementType()); - pslILEmit->EmitLDARG(m_pargs->m_pMarshalInfo->HiddenLengthParamIndex()); - pslILEmit->EmitLDLOC(m_pargs->m_pMarshalInfo->GetHiddenLengthNativeHome()); - pslILEmit->EmitSTIND_T(&nativeParamType); - } + FCALL_CHECK; + PRECONDITION(CheckPointer(pManagedHome)); } + CONTRACTL_END; - ILMngdMarshaler::EmitConvertSpaceCLRToNative(pslILEmit); -} - -void ILHiddenLengthArrayMarshaler::EmitConvertContentsCLRToNative(ILCodeStream* pslILEmit) -{ - STANDARD_VM_CONTRACT; + HELPER_METHOD_FRAME_BEGIN_0(); - if (m_pargs->na.m_vt == VTHACK_REDIRECTEDTYPE && - (m_pargs->na.m_redirectedTypeIndex == WinMDAdapter::RedirectedTypeIndex_System_Uri || - m_pargs->na.m_redirectedTypeIndex == WinMDAdapter::RedirectedTypeIndex_System_Collections_Specialized_NotifyCollectionChangedEventArgs || - m_pargs->na.m_redirectedTypeIndex == WinMDAdapter::RedirectedTypeIndex_System_ComponentModel_PropertyChangedEventArgs)) - { - // System.Uri/NotifyCollectionChangedEventArgs don't live in mscorlib so there's no marshaling helper to call - inline the loop - DWORD dwLoopCounterLocalNum = pslILEmit->NewLocal(ELEMENT_TYPE_I4); - DWORD dwNativePtrLocalNum = pslILEmit->NewLocal(ELEMENT_TYPE_I); - ILCodeLabel *pConditionLabel = pslILEmit->NewCodeLabel(); - ILCodeLabel *pLoopBodyLabel = pslILEmit->NewCodeLabel(); + *pNativeHome = pThis->m_pCMHelper->InvokeMarshalManagedToNativeMeth(*pManagedHome); - // for (IntPtr ptr = pNative, int i = 0; ... - pslILEmit->EmitLDC(0); - pslILEmit->EmitSTLOC(dwLoopCounterLocalNum); - EmitLoadNativeValue(pslILEmit); - pslILEmit->EmitSTLOC(dwNativePtrLocalNum); - pslILEmit->EmitBR(pConditionLabel); + HELPER_METHOD_FRAME_END(); +} +FCIMPLEND - // *ptr = EmitConvertCLR*ToWinRT*(pManaged[i]); - pslILEmit->EmitLabel(pLoopBodyLabel); - pslILEmit->EmitLDLOC(dwNativePtrLocalNum); - EmitLoadManagedValue(pslILEmit); - pslILEmit->EmitLDLOC(dwLoopCounterLocalNum); - pslILEmit->EmitLDELEM_REF(); - switch (m_pargs->na.m_redirectedTypeIndex) - { - case WinMDAdapter::RedirectedTypeIndex_System_Uri: - ILUriMarshaler::EmitConvertCLRUriToWinRTUri(pslILEmit, m_pargs->m_pMarshalInfo->GetModule()->GetLoaderAllocator()); - break; +FCIMPL3(void, MngdRefCustomMarshaler::ConvertContentsToManaged, MngdRefCustomMarshaler* pThis, OBJECTREF* pManagedHome, void** pNativeHome) +{ + CONTRACTL + { + FCALL_CHECK; + PRECONDITION(CheckPointer(pManagedHome)); + } + CONTRACTL_END; - case WinMDAdapter::RedirectedTypeIndex_System_Collections_Specialized_NotifyCollectionChangedEventArgs: - ILNCCEventArgsMarshaler::EmitConvertCLREventArgsToWinRTEventArgs(pslILEmit, m_pargs->m_pMarshalInfo->GetModule()->GetLoaderAllocator()); - break; + HELPER_METHOD_FRAME_BEGIN_0(); - case WinMDAdapter::RedirectedTypeIndex_System_ComponentModel_PropertyChangedEventArgs: - ILPCEventArgsMarshaler::EmitConvertCLREventArgsToWinRTEventArgs(pslILEmit, m_pargs->m_pMarshalInfo->GetModule()->GetLoaderAllocator()); - break; + SetObjectReference(pManagedHome, pThis->m_pCMHelper->InvokeMarshalNativeToManagedMeth(*pNativeHome)); - default: UNREACHABLE(); - } + HELPER_METHOD_FRAME_END(); +} +FCIMPLEND - pslILEmit->EmitSTIND_I(); +FCIMPL3(void, MngdRefCustomMarshaler::ClearNative, MngdRefCustomMarshaler* pThis, OBJECTREF* pManagedHome, void** pNativeHome) +{ + FCALL_CONTRACT; - // ... i++, ptr += IntPtr.Size ... - pslILEmit->EmitLDLOC(dwLoopCounterLocalNum); - pslILEmit->EmitLDC(1); - pslILEmit->EmitADD(); - pslILEmit->EmitSTLOC(dwLoopCounterLocalNum); - pslILEmit->EmitLDLOC(dwNativePtrLocalNum); - pslILEmit->EmitLDC(sizeof(LPVOID)); - pslILEmit->EmitADD(); - pslILEmit->EmitSTLOC(dwNativePtrLocalNum); + HELPER_METHOD_FRAME_BEGIN_0(); - // ... i < pManaged.Length; ... - pslILEmit->EmitLabel(pConditionLabel); - pslILEmit->EmitLDLOC(dwLoopCounterLocalNum); - EmitLoadNativeArrayLength(pslILEmit); - pslILEmit->EmitBLT(pLoopBodyLabel); - } - else + CONTRACTL { - ILMngdMarshaler::EmitConvertContentsCLRToNative(pslILEmit); + THROWS; + GC_TRIGGERS; + MODE_ANY; } + CONTRACTL_END; + + pThis->m_pCMHelper->InvokeCleanUpNativeMeth(*pNativeHome); + + HELPER_METHOD_FRAME_END(); } +FCIMPLEND -void ILHiddenLengthArrayMarshaler::EmitConvertContentsNativeToCLR(ILCodeStream* pslILEmit) +FCIMPL3(void, MngdRefCustomMarshaler::ClearManaged, MngdRefCustomMarshaler* pThis, OBJECTREF* pManagedHome, void** pNativeHome) { - STANDARD_VM_CONTRACT; - - if (m_pargs->na.m_vt == VTHACK_REDIRECTEDTYPE && - (m_pargs->na.m_redirectedTypeIndex == WinMDAdapter::RedirectedTypeIndex_System_Uri || - m_pargs->na.m_redirectedTypeIndex == WinMDAdapter::RedirectedTypeIndex_System_Collections_Specialized_NotifyCollectionChangedEventArgs || - m_pargs->na.m_redirectedTypeIndex == WinMDAdapter::RedirectedTypeIndex_System_ComponentModel_PropertyChangedEventArgs)) + CONTRACTL { - // System.Uri/NotifyCollectionChangedEventArgs don't live in mscorlib so there's no marshaling helper to call - inline the loop - DWORD dwLoopCounterLocalNum = pslILEmit->NewLocal(ELEMENT_TYPE_I4); - DWORD dwNativePtrLocalNum = pslILEmit->NewLocal(ELEMENT_TYPE_I); - ILCodeLabel *pConditionLabel = pslILEmit->NewCodeLabel(); - ILCodeLabel *pLoopBodyLabel = pslILEmit->NewCodeLabel(); - - // for (IntPtr ptr = pNative, int i = 0; ... - pslILEmit->EmitLDC(0); - pslILEmit->EmitSTLOC(dwLoopCounterLocalNum); - EmitLoadNativeValue(pslILEmit); - pslILEmit->EmitSTLOC(dwNativePtrLocalNum); - pslILEmit->EmitBR(pConditionLabel); - - // pManaged[i] = EmitConvertWinRT*ToCLR*(*ptr); - pslILEmit->EmitLabel(pLoopBodyLabel); - EmitLoadManagedValue(pslILEmit); - pslILEmit->EmitLDLOC(dwLoopCounterLocalNum); - pslILEmit->EmitLDLOC(dwNativePtrLocalNum); - pslILEmit->EmitLDIND_I(); - - switch (m_pargs->na.m_redirectedTypeIndex) - { - case WinMDAdapter::RedirectedTypeIndex_System_Uri: - ILUriMarshaler::EmitConvertWinRTUriToCLRUri(pslILEmit, m_pargs->m_pMarshalInfo->GetModule()->GetLoaderAllocator()); - break; - - case WinMDAdapter::RedirectedTypeIndex_System_Collections_Specialized_NotifyCollectionChangedEventArgs: - ILNCCEventArgsMarshaler::EmitConvertWinRTEventArgsToCLREventArgs(pslILEmit, m_pargs->m_pMarshalInfo->GetModule()->GetLoaderAllocator()); - break; - - case WinMDAdapter::RedirectedTypeIndex_System_ComponentModel_PropertyChangedEventArgs: - ILPCEventArgsMarshaler::EmitConvertWinRTEventArgsToCLREventArgs(pslILEmit, m_pargs->m_pMarshalInfo->GetModule()->GetLoaderAllocator()); - break; + FCALL_CHECK; + PRECONDITION(CheckPointer(pManagedHome)); + } + CONTRACTL_END; - default: UNREACHABLE(); - } + HELPER_METHOD_FRAME_BEGIN_0(); - pslILEmit->EmitSTELEM_REF(); + pThis->m_pCMHelper->InvokeCleanUpManagedMeth(*pManagedHome); - // ... i++, ptr += IntPtr.Size) - pslILEmit->EmitLDLOC(dwLoopCounterLocalNum); - pslILEmit->EmitLDC(1); - pslILEmit->EmitADD(); - pslILEmit->EmitSTLOC(dwLoopCounterLocalNum); - pslILEmit->EmitLDLOC(dwNativePtrLocalNum); - pslILEmit->EmitLDC(sizeof(LPVOID)); - pslILEmit->EmitADD(); - pslILEmit->EmitSTLOC(dwNativePtrLocalNum); + HELPER_METHOD_FRAME_END(); +} +FCIMPLEND - // ... i < pManaged.Length; ... - pslILEmit->EmitLabel(pConditionLabel); - pslILEmit->EmitLDLOC(dwLoopCounterLocalNum); - EmitLoadNativeArrayLength(pslILEmit); - pslILEmit->EmitBLT(pLoopBodyLabel); - } - else - { - ILMngdMarshaler::EmitConvertContentsNativeToCLR(pslILEmit); - } -} - -void ILHiddenLengthArrayMarshaler::EmitClearNative(ILCodeStream* pslILEmit) -{ - STANDARD_VM_CONTRACT; - - EmitClearNativeContents(pslILEmit); - - EmitLoadNativeValue(pslILEmit); - pslILEmit->EmitCALL(pslILEmit->GetToken(GetClearNativeMethod()), 1, 0); -} - -void ILHiddenLengthArrayMarshaler::EmitClearNativeContents(ILCodeStream* pslILEmit) -{ - STANDARD_VM_CONTRACT; - - MethodDesc *pMD = GetClearNativeContentsMethod(); - if (pMD != NULL) - { - MetaSig sig(pMD); - UINT numArgs = sig.NumFixedArgs(); - - if (numArgs == 3) - { - EmitLoadMngdMarshaler(pslILEmit); - } - else - { - _ASSERTE(numArgs == 2); - } - - EmitLoadNativeHomeAddr(pslILEmit); - EmitLoadNativeArrayLength(pslILEmit); - pslILEmit->EmitCALL(pslILEmit->GetToken(pMD), numArgs, 0); - } -} - -// Determine if we can simply pin the managed array, rather than doing a full marshal -bool ILHiddenLengthArrayMarshaler::CanMarshalViaPinning() -{ - STANDARD_VM_CONTRACT; - - // If the array is only going from managed to native, and it contains only blittable data, and - // we know where that data is located in the array then we can take the fast path - if (!IsCLRToNative(m_dwMarshalFlags)) - { - return false; - } - - if (m_pargs->na.m_vt != VTHACK_BLITTABLERECORD) - { - return false; - } - - if (IsByref(m_dwMarshalFlags)) - { - return false; - } - - if (!IsIn(m_dwMarshalFlags)) - { - return false; - } - - if (IsRetval(m_dwMarshalFlags)) - { - return false; - } - - return true; -} - -void ILHiddenLengthArrayMarshaler::EmitLoadNativeArrayLength(ILCodeStream *pslILEmit) -{ - STANDARD_VM_CONTRACT; - - // For return values, the native length won't yet be marshaled back to its managed home - // so it needs to be read directly - if (IsRetval(m_dwMarshalFlags)) - { - pslILEmit->EmitLDLOC(m_pargs->m_pMarshalInfo->GetHiddenLengthNativeHome()); - } - else - { - pslILEmit->EmitLDLOC(m_pargs->m_pMarshalInfo->GetHiddenLengthManagedHome()); - } - - pslILEmit->EmitCONV_OVF_I4(); -} - -MethodDesc *ILHiddenLengthArrayMarshaler::GetConvertContentsToManagedMethod() -{ - STANDARD_VM_CONTRACT; - - if (m_pargs->na.m_vt == VTHACK_REDIRECTEDTYPE) - { - switch (m_pargs->na.m_redirectedTypeIndex) - { - case WinMDAdapter::RedirectedTypeIndex_System_DateTimeOffset: - return MscorlibBinder::GetMethod(METHOD__MNGD_HIDDEN_LENGTH_ARRAY_MARSHALER__CONVERT_CONTENTS_TO_MANAGED_DATETIME); - - case WinMDAdapter::RedirectedTypeIndex_System_Type: - return MscorlibBinder::GetMethod(METHOD__MNGD_HIDDEN_LENGTH_ARRAY_MARSHALER__CONVERT_CONTENTS_TO_MANAGED_TYPE); - - case WinMDAdapter::RedirectedTypeIndex_System_Exception: - return MscorlibBinder::GetMethod(METHOD__MNGD_HIDDEN_LENGTH_ARRAY_MARSHALER__CONVERT_CONTENTS_TO_MANAGED_EXCEPTION); - - case WinMDAdapter::RedirectedTypeIndex_System_Nullable: - { - MethodDesc *pMD = MscorlibBinder::GetMethod(METHOD__MNGD_HIDDEN_LENGTH_ARRAY_MARSHALER__CONVERT_CONTENTS_TO_MANAGED_NULLABLE); - return GetExactMarshalerMethod(pMD); - } - - case WinMDAdapter::RedirectedTypeIndex_System_Collections_Generic_KeyValuePair: - { - MethodDesc *pMD = MscorlibBinder::GetMethod(METHOD__MNGD_HIDDEN_LENGTH_ARRAY_MARSHALER__CONVERT_CONTENTS_TO_MANAGED_KEYVALUEPAIR); - return GetExactMarshalerMethod(pMD); - } - - default: - UNREACHABLE_MSG("Unrecognized redirected type."); - } - } - return ILMngdMarshaler::GetConvertContentsToManagedMethod(); -} - -MethodDesc *ILHiddenLengthArrayMarshaler::GetConvertContentsToNativeMethod() -{ - STANDARD_VM_CONTRACT; - - if (m_pargs->na.m_vt == VTHACK_REDIRECTEDTYPE) - { - switch (m_pargs->na.m_redirectedTypeIndex) - { - case WinMDAdapter::RedirectedTypeIndex_System_DateTimeOffset: - return MscorlibBinder::GetMethod(METHOD__MNGD_HIDDEN_LENGTH_ARRAY_MARSHALER__CONVERT_CONTENTS_TO_NATIVE_DATETIME); - - case WinMDAdapter::RedirectedTypeIndex_System_Type: - return MscorlibBinder::GetMethod(METHOD__MNGD_HIDDEN_LENGTH_ARRAY_MARSHALER__CONVERT_CONTENTS_TO_NATIVE_TYPE); - - case WinMDAdapter::RedirectedTypeIndex_System_Exception: - return MscorlibBinder::GetMethod(METHOD__MNGD_HIDDEN_LENGTH_ARRAY_MARSHALER__CONVERT_CONTENTS_TO_NATIVE_EXCEPTION); - - case WinMDAdapter::RedirectedTypeIndex_System_Nullable: - { - MethodDesc *pMD = MscorlibBinder::GetMethod(METHOD__MNGD_HIDDEN_LENGTH_ARRAY_MARSHALER__CONVERT_CONTENTS_TO_NATIVE_NULLABLE); - return GetExactMarshalerMethod(pMD); - } - - case WinMDAdapter::RedirectedTypeIndex_System_Collections_Generic_KeyValuePair: - { - MethodDesc *pMD = MscorlibBinder::GetMethod(METHOD__MNGD_HIDDEN_LENGTH_ARRAY_MARSHALER__CONVERT_CONTENTS_TO_NATIVE_KEYVALUEPAIR); - return GetExactMarshalerMethod(pMD); - } - - default: - UNREACHABLE_MSG("Unrecognized redirected type."); - } - } - return ILMngdMarshaler::GetConvertContentsToNativeMethod(); -} - -MethodDesc *ILHiddenLengthArrayMarshaler::GetClearNativeContentsMethod() -{ - switch (m_pargs->na.m_vt) - { - // HSTRINGs, interface pointers, and non-blittable structs need contents cleanup - case VTHACK_HSTRING: - case VTHACK_INSPECTABLE: - case VTHACK_NONBLITTABLERECORD: - break; - - // blittable structs don't need contents cleanup - case VTHACK_BLITTABLERECORD: - return NULL; - - case VTHACK_REDIRECTEDTYPE: - { - switch (m_pargs->na.m_redirectedTypeIndex) - { - // System.Type, Uri, Nullable, KeyValuePair, NCCEventArgs, and PCEventArgs need cleanup - case WinMDAdapter::RedirectedTypeIndex_System_Type: - return MscorlibBinder::GetMethod(METHOD__MNGD_HIDDEN_LENGTH_ARRAY_MARSHALER__CLEAR_NATIVE_CONTENTS_TYPE); - - case WinMDAdapter::RedirectedTypeIndex_System_Uri: - case WinMDAdapter::RedirectedTypeIndex_System_Nullable: - case WinMDAdapter::RedirectedTypeIndex_System_Collections_Generic_KeyValuePair: - case WinMDAdapter::RedirectedTypeIndex_System_Collections_Specialized_NotifyCollectionChangedEventArgs: - case WinMDAdapter::RedirectedTypeIndex_System_ComponentModel_PropertyChangedEventArgs: - break; - - // other redirected types don't - default: - return NULL; - } - break; - } - - default: - UNREACHABLE_MSG("Unexpected hidden-length array element VT"); - } - - return ILMngdMarshaler::GetClearNativeContentsMethod(); -} - -MethodDesc *ILHiddenLengthArrayMarshaler::GetExactMarshalerMethod(MethodDesc *pGenericMD) -{ - STANDARD_VM_CONTRACT; - - return MethodDesc::FindOrCreateAssociatedMethodDesc( - pGenericMD, - pGenericMD->GetMethodTable(), - FALSE, // forceBoxedEntryPoint - m_pargs->m_pMarshalInfo->GetArrayElementTypeHandle().GetInstantiation(), // methodInst - FALSE, // allowInstParam - TRUE); // forceRemotableMethod -} - -#ifndef CROSSGEN_COMPILE - -FCIMPL5(void, MngdHiddenLengthArrayMarshaler::CreateMarshaler, MngdHiddenLengthArrayMarshaler* pThis, MethodTable* pMT, SIZE_T cbElementSize, UINT16 vt, PCODE pManagedMarshaler) -{ - FCALL_CONTRACT; - - pThis->m_pElementMT = pMT; - pThis->m_cbElementSize = cbElementSize; - pThis->m_vt = (VARTYPE)vt; - pThis->m_pManagedMarshaler = pManagedMarshaler; -} -FCIMPLEND - -FCIMPL3(void, MngdHiddenLengthArrayMarshaler::ConvertSpaceToNative, MngdHiddenLengthArrayMarshaler* pThis, OBJECTREF* pManagedHome, void** pNativeHome) -{ - FCALL_CONTRACT; - - BASEARRAYREF arrayRef = (BASEARRAYREF) *pManagedHome; - HELPER_METHOD_FRAME_BEGIN_1(arrayRef); - - if (arrayRef == NULL) - { - *pNativeHome = NULL; - } - else - { - SIZE_T cbArray = pThis->GetArraySize(arrayRef->GetNumComponents()); - - *pNativeHome = CoTaskMemAlloc(cbArray); - if (*pNativeHome == NULL) - { - ThrowOutOfMemory(); - } - - // initialize the array - FillMemory(*pNativeHome, cbArray, 0); - } - - HELPER_METHOD_FRAME_END(); -} -FCIMPLEND - -FCIMPL3(void, MngdHiddenLengthArrayMarshaler::ConvertContentsToNative, MngdHiddenLengthArrayMarshaler* pThis, OBJECTREF* pManagedHome, void** pNativeHome) -{ - FCALL_CONTRACT; - - struct - { - PTRARRAYREF arrayRef; - STRINGREF currentStringRef; - OBJECTREF currentObjectRef; - } - gc; - ZeroMemory(&gc, sizeof(gc)); - gc.arrayRef = (PTRARRAYREF)*pManagedHome; - - HELPER_METHOD_FRAME_BEGIN_PROTECT(gc); - - if (gc.arrayRef != NULL) - { - // There are these choices: - // * the array is made up of entirely blittable data, in which case we can directly copy it, - // * it is an array of strings that need to be marshaled as HSTRING, - // * it is an array of non-blittable structures - // * it is an array of interface pointers (interface, runtime class, delegate, System.Object) - switch (pThis->m_vt) - { - case VTHACK_BLITTABLERECORD: - { - // Just do a raw memcpy into the array - SIZE_T cbArray = pThis->GetArraySize(gc.arrayRef->GetNumComponents()); - memcpyNoGCRefs(*pNativeHome, gc.arrayRef->GetDataPtr(), cbArray); - break; - } - - case VTHACK_HSTRING: - { - // Marshal a string array as an array of HSTRINGs - if (!WinRTSupported()) - { - COMPlusThrow(kPlatformNotSupportedException, W("PlatformNotSupported_WinRT")); - } - - HSTRING *pDestinationStrings = reinterpret_cast(*pNativeHome); - - for (SIZE_T i = 0; i < gc.arrayRef->GetNumComponents(); ++i) - { - gc.currentStringRef = (STRINGREF)gc.arrayRef->GetAt(i); - if (gc.currentStringRef == NULL) - { - StackSString ssIndex; - ssIndex.Printf(W("%d"), i); - COMPlusThrow(kMarshalDirectiveException, IDS_EE_BADMARSHALARRAY_NULL_HSTRING, ssIndex.GetUnicode()); - } - - IfFailThrow(WindowsCreateString(gc.currentStringRef->GetBuffer(), gc.currentStringRef->GetStringLength(), &(pDestinationStrings[i]))); - } - break; - } - - case VTHACK_NONBLITTABLERECORD: - { - BYTE *pNativeStart = reinterpret_cast(*pNativeHome); - SIZE_T managedOffset = ArrayBase::GetDataPtrOffset(gc.arrayRef->GetMethodTable()); - SIZE_T nativeOffset = 0; - SIZE_T managedSize = gc.arrayRef->GetComponentSize(); - SIZE_T nativeSize = pThis->m_pElementMT->GetNativeSize(); - for (SIZE_T i = 0; i < gc.arrayRef->GetNumComponents(); ++i) - { - MarshalStructViaILStubCode(pThis->m_pManagedMarshaler, reinterpret_cast(&gc.arrayRef) + managedOffset, pNativeStart + nativeOffset, StructMarshalStubs::MarshalOperation::Marshal); - - managedOffset += managedSize; - nativeOffset += nativeSize; - } - break; - } - - case VTHACK_INSPECTABLE: - { - // interface pointers - IUnknown **pDestinationIPs = reinterpret_cast(*pNativeHome); - - // If this turns out to be a perf issue, we can precompute the ItfMarshalInfo - // and generate code that passes it to the marshaler at creation time. - ItfMarshalInfo itfInfo; - MarshalInfo::GetItfMarshalInfo(TypeHandle(pThis->m_pElementMT), TypeHandle(), FALSE, TRUE, MarshalInfo::MARSHAL_SCENARIO_WINRT, &itfInfo); - - for (SIZE_T i = 0; i < gc.arrayRef->GetNumComponents(); ++i) - { - gc.currentObjectRef = gc.arrayRef->GetAt(i); - pDestinationIPs[i] = MarshalObjectToInterface( - &gc.currentObjectRef, - itfInfo.thNativeItf.GetMethodTable(), - itfInfo.thClass.GetMethodTable(), - itfInfo.dwFlags); - } - break; - } - - default: - UNREACHABLE_MSG("Unrecognized array element VARTYPE"); - - } - } - HELPER_METHOD_FRAME_END(); -} -FCIMPLEND - -FCIMPL4(void, MngdHiddenLengthArrayMarshaler::ConvertSpaceToManaged, MngdHiddenLengthArrayMarshaler* pThis, OBJECTREF* pManagedHome, void** pNativeHome, INT32 cElements) -{ - FCALL_CONTRACT; - - HELPER_METHOD_FRAME_BEGIN_0(); - - if (*pNativeHome == NULL) - { - SetObjectReference(pManagedHome, NULL); - } - else - { - TypeHandle elementType(pThis->m_pElementMT); - TypeHandle arrayType = ClassLoader::LoadArrayTypeThrowing(elementType); - SetObjectReference(pManagedHome, AllocateSzArray(arrayType, cElements)); - } - - HELPER_METHOD_FRAME_END(); -} -FCIMPLEND - -FCIMPL3(void, MngdHiddenLengthArrayMarshaler::ConvertContentsToManaged, MngdHiddenLengthArrayMarshaler* pThis, OBJECTREF* pManagedHome, void** pNativeHome) -{ - FCALL_CONTRACT; - - struct - { - PTRARRAYREF arrayRef; - STRINGREF stringRef; - OBJECTREF objectRef; - } - gc; - ZeroMemory(&gc, sizeof(gc)); - gc.arrayRef = (PTRARRAYREF)*pManagedHome; - - HELPER_METHOD_FRAME_BEGIN_PROTECT(gc); - - if (*pNativeHome != NULL) - { - // There are these choices: - // * the array is made up of entirely blittable data, in which case we can directly copy it, - // * it is an array of strings that need to be marshaled as HSTRING, - // * it is an array of non-blittable structures - // * it is an array of interface pointers (interface, runtime class, delegate, System.Object) - switch (pThis->m_vt) - { - case VTHACK_BLITTABLERECORD: - { - // Just do a raw memcpy into the array - SIZE_T cbArray = pThis->GetArraySize(gc.arrayRef->GetNumComponents()); - memcpyNoGCRefs(gc.arrayRef->GetDataPtr(), *pNativeHome, cbArray); - break; - } - - case VTHACK_HSTRING: - { - // Strings are in HSRING format on the native side - if (!WinRTSupported()) - { - COMPlusThrow(kPlatformNotSupportedException, W("PlatformNotSupported_WinRT")); - } - - HSTRING *pSourceStrings = reinterpret_cast(*pNativeHome); - - for (SIZE_T i = 0; i < gc.arrayRef->GetNumComponents(); ++i) - { - // NULL HSTRINGS are equivilent to empty strings - UINT32 cchString = 0; - LPCWSTR pwszString = W(""); - - if (pSourceStrings[i] != NULL) - { - pwszString = WindowsGetStringRawBuffer(pSourceStrings[i], &cchString); - } - - gc.stringRef = StringObject::NewString(pwszString, cchString); - gc.arrayRef->SetAt(i, gc.stringRef); - } - break; - } - - case VTHACK_NONBLITTABLERECORD: - { - BYTE* pNativeStart = reinterpret_cast(*pNativeHome); - SIZE_T managedOffset = ArrayBase::GetDataPtrOffset(gc.arrayRef->GetMethodTable()); - SIZE_T nativeOffset = 0; - SIZE_T managedSize = gc.arrayRef->GetComponentSize(); - SIZE_T nativeSize = pThis->m_pElementMT->GetNativeSize(); - for (SIZE_T i = 0; i < gc.arrayRef->GetNumComponents(); ++i) - { - MarshalStructViaILStubCode(pThis->m_pManagedMarshaler, reinterpret_cast(&gc.arrayRef) + managedOffset, pNativeStart + nativeOffset, StructMarshalStubs::MarshalOperation::Unmarshal); - - managedOffset += managedSize; - nativeOffset += nativeSize; - } - break; - } - - case VTHACK_INSPECTABLE: - { - // interface pointers - IUnknown **pSourceIPs = reinterpret_cast(*pNativeHome); - - // If this turns out to be a perf issue, we can precompute the ItfMarshalInfo - // and generate code that passes it to the marshaler at creation time. - ItfMarshalInfo itfInfo; - MarshalInfo::GetItfMarshalInfo(TypeHandle(pThis->m_pElementMT), TypeHandle(), FALSE, TRUE, MarshalInfo::MARSHAL_SCENARIO_WINRT, &itfInfo); - - for (SIZE_T i = 0; i < gc.arrayRef->GetNumComponents(); ++i) - { - gc.objectRef = gc.arrayRef->GetAt(i); - UnmarshalObjectFromInterface( - &gc.objectRef, - &pSourceIPs[i], - itfInfo.thItf.GetMethodTable(), - itfInfo.thClass.GetMethodTable(), - itfInfo.dwFlags); - gc.arrayRef->SetAt(i, gc.objectRef); - } - break; - } - - default: - UNREACHABLE_MSG("Unrecognized array element VARTYPE"); - } - } - - HELPER_METHOD_FRAME_END(); -} -FCIMPLEND - -FCIMPL3(void, MngdHiddenLengthArrayMarshaler::ClearNativeContents, MngdHiddenLengthArrayMarshaler* pThis, void** pNativeHome, INT32 cElements) -{ - FCALL_CONTRACT; - - HELPER_METHOD_FRAME_BEGIN_0(); - - if (*pNativeHome != NULL) - { - pThis->DoClearNativeContents(pThis, pNativeHome, cElements); - } - - HELPER_METHOD_FRAME_END(); -} -FCIMPLEND - -#endif // CROSSGEN_COMPILE - - -SIZE_T MngdHiddenLengthArrayMarshaler::GetArraySize(SIZE_T elements) -{ - CONTRACTL - { - THROWS; - GC_TRIGGERS; - MODE_COOPERATIVE; - } - CONTRACTL_END; - - _ASSERTE_MSG(m_cbElementSize != 0, "You have to set the native size for your array element type"); - - SIZE_T cbArray; - - if (!ClrSafeInt::multiply(elements, m_cbElementSize, cbArray)) - { - COMPlusThrow(kArgumentException, IDS_EE_STRUCTARRAYTOOLARGE); - } - - // This array size limit is carried over from the equivilent limit for other array marshaling code - if (cbArray > MAX_SIZE_FOR_INTEROP) - { - COMPlusThrow(kArgumentException, IDS_EE_STRUCTARRAYTOOLARGE); - } - - return cbArray; -} - -#ifndef CROSSGEN_COMPILE -void MngdHiddenLengthArrayMarshaler::DoClearNativeContents(MngdHiddenLengthArrayMarshaler* pThis, void** pNativeHome, INT32 cElements) -{ - CONTRACTL - { - THROWS; - GC_TRIGGERS; - MODE_COOPERATIVE; - PRECONDITION(pNativeHome != NULL); - } - CONTRACTL_END; - - VARTYPE vt = m_vt; - if (vt == VTHACK_REDIRECTEDTYPE) - { - // the redirected types that use this helper are interface pointers on the WinRT side - vt = VTHACK_INSPECTABLE; - } - - switch (vt) - { - case VTHACK_HSTRING: - { - if (WinRTSupported()) - { - HSTRING *pStrings = reinterpret_cast(*pNativeHome); - for (INT32 i = 0; i < cElements; ++i) - { - if (pStrings[i] != NULL) - { - WindowsDeleteString(pStrings[i]); - } - } - } - break; - } - - case VTHACK_NONBLITTABLERECORD: - { - BYTE* pNativeStart = reinterpret_cast(*pNativeHome); - SIZE_T nativeOffset = 0; - SIZE_T nativeSize = pThis->m_pElementMT->GetNativeSize(); - for (INT32 i = 0; i < cElements; ++i) - { - MarshalStructViaILStubCode(pThis->m_pManagedMarshaler, nullptr, pNativeStart + nativeOffset, StructMarshalStubs::MarshalOperation::Cleanup); - nativeOffset += nativeSize; - } - break; - } - - case VTHACK_INSPECTABLE: - { - IInspectable **pIPs = reinterpret_cast(*pNativeHome); - for (INT32 i = 0; i < cElements; ++i) - { - if (pIPs[i] != NULL) - { - SafeRelease(pIPs[i]); - } - } - break; - } - - default: - UNREACHABLE_MSG("Unexpected hidden-length array element VT"); - } -} -#endif //CROSSGEN_COMPILE -#endif // FEATURE_COMINTEROP - -void ILReferenceCustomMarshaler::EmitCreateMngdMarshaler(ILCodeStream* pslILEmit) -{ - CONTRACTL - { - STANDARD_VM_CHECK; - PRECONDITION(-1 == m_dwMngdMarshalerLocalNum); - } - CONTRACTL_END; - - // - // allocate space for marshaler - // - - m_dwMngdMarshalerLocalNum = pslILEmit->NewLocal(ELEMENT_TYPE_I); - - pslILEmit->EmitLDC(sizeof(MngdRefCustomMarshaler)); - pslILEmit->EmitLOCALLOC(); - pslILEmit->EmitSTLOC(m_dwMngdMarshalerLocalNum); - - pslILEmit->EmitLDLOC(m_dwMngdMarshalerLocalNum); // arg to CreateMarshaler - - // - // call CreateCustomMarshalerHelper - // - - pslILEmit->EmitLDTOKEN(pslILEmit->GetToken(m_pargs->rcm.m_pMD)); - pslILEmit->EmitCALL(METHOD__METHOD_HANDLE__GETVALUEINTERNAL, 1, 1); - - pslILEmit->EmitLDC(m_pargs->rcm.m_paramToken); - - pslILEmit->EmitLDTOKEN(pslILEmit->GetToken(TypeHandle::FromPtr(m_pargs->rcm.m_hndManagedType))); - pslILEmit->EmitCALL(METHOD__RT_TYPE_HANDLE__GETVALUEINTERNAL, 1, 1); - - pslILEmit->EmitCALL(METHOD__STUBHELPERS__CREATE_CUSTOM_MARSHALER_HELPER, 3, 1); // arg to CreateMarshaler - - // - // call MngdRefCustomMarshaler::CreateMarshaler - // - - pslILEmit->EmitCALL(METHOD__MNGD_REF_CUSTOM_MARSHALER__CREATE_MARSHALER, 2, 0); -} - - -#ifndef CROSSGEN_COMPILE - -FCIMPL2(void, MngdRefCustomMarshaler::CreateMarshaler, MngdRefCustomMarshaler* pThis, void* pCMHelper) -{ - FCALL_CONTRACT; - - pThis->m_pCMHelper = (CustomMarshalerHelper*)pCMHelper; -} -FCIMPLEND - - -FCIMPL3(void, MngdRefCustomMarshaler::ConvertContentsToNative, MngdRefCustomMarshaler* pThis, OBJECTREF* pManagedHome, void** pNativeHome) -{ - CONTRACTL - { - FCALL_CHECK; - PRECONDITION(CheckPointer(pManagedHome)); - } - CONTRACTL_END; - - HELPER_METHOD_FRAME_BEGIN_0(); - - *pNativeHome = pThis->m_pCMHelper->InvokeMarshalManagedToNativeMeth(*pManagedHome); - - HELPER_METHOD_FRAME_END(); -} -FCIMPLEND - - -FCIMPL3(void, MngdRefCustomMarshaler::ConvertContentsToManaged, MngdRefCustomMarshaler* pThis, OBJECTREF* pManagedHome, void** pNativeHome) -{ - CONTRACTL - { - FCALL_CHECK; - PRECONDITION(CheckPointer(pManagedHome)); - } - CONTRACTL_END; - - HELPER_METHOD_FRAME_BEGIN_0(); - - SetObjectReference(pManagedHome, pThis->m_pCMHelper->InvokeMarshalNativeToManagedMeth(*pNativeHome)); - - HELPER_METHOD_FRAME_END(); -} -FCIMPLEND - -FCIMPL3(void, MngdRefCustomMarshaler::ClearNative, MngdRefCustomMarshaler* pThis, OBJECTREF* pManagedHome, void** pNativeHome) -{ - FCALL_CONTRACT; - - HELPER_METHOD_FRAME_BEGIN_0(); - - CONTRACTL - { - THROWS; - GC_TRIGGERS; - MODE_ANY; - } - CONTRACTL_END; - - pThis->m_pCMHelper->InvokeCleanUpNativeMeth(*pNativeHome); - - HELPER_METHOD_FRAME_END(); -} -FCIMPLEND - -FCIMPL3(void, MngdRefCustomMarshaler::ClearManaged, MngdRefCustomMarshaler* pThis, OBJECTREF* pManagedHome, void** pNativeHome) -{ - CONTRACTL - { - FCALL_CHECK; - PRECONDITION(CheckPointer(pManagedHome)); - } - CONTRACTL_END; - - HELPER_METHOD_FRAME_BEGIN_0(); - - pThis->m_pCMHelper->InvokeCleanUpManagedMeth(*pManagedHome); - - HELPER_METHOD_FRAME_END(); -} -FCIMPLEND - -#endif // CROSSGEN_COMPILE - - -#ifdef FEATURE_COMINTEROP - -/////////////////////////////////////////////////////////////////////////////////////////////////// -// ILUriMarshaler implementation -/////////////////////////////////////////////////////////////////////////////////////////////////// - -LocalDesc ILUriMarshaler::GetNativeType() -{ - LIMITED_METHOD_CONTRACT; - return LocalDesc(ELEMENT_TYPE_I); -} - -LocalDesc ILUriMarshaler::GetManagedType() -{ - STANDARD_VM_CONTRACT;; - LoaderAllocator* pLoader = m_pargs->m_pMarshalInfo->GetModule()->GetLoaderAllocator(); - TypeHandle hndUriType = pLoader->GetMarshalingData()->GetUriMarshalingInfo()->GetSystemUriType(); - - return LocalDesc(hndUriType); // System.Uri -} - -bool ILUriMarshaler::NeedsClearNative() -{ - LIMITED_METHOD_CONTRACT; - return true; -} - -// Note that this method expects the CLR Uri on top of the evaluation stack and leaves the WinRT Uri there. -//static -void ILUriMarshaler::EmitConvertCLRUriToWinRTUri(ILCodeStream* pslILEmit, LoaderAllocator* pLoader) -{ - STANDARD_VM_CONTRACT; - - UriMarshalingInfo* marshalingInfo = pLoader->GetMarshalingData()->GetUriMarshalingInfo(); - - ILCodeLabel *pNotNullLabel = pslILEmit->NewCodeLabel(); - ILCodeLabel *pDoneLabel = pslILEmit->NewCodeLabel(); - - pslILEmit->EmitDUP(); - pslILEmit->EmitBRTRUE(pNotNullLabel); - - pslILEmit->EmitPOP(); - pslILEmit->EmitLoadNullPtr(); - pslILEmit->EmitBR(pDoneLabel); - - pslILEmit->EmitLabel(pNotNullLabel); - - // System.Uri.get_OriginalString() - MethodDesc* pSystemUriOriginalStringMD = marshalingInfo->GetSystemUriOriginalStringMD(); - pslILEmit->EmitCALL(pslILEmit->GetToken(pSystemUriOriginalStringMD), 1, 1); - - pslILEmit->EmitCALL(METHOD__URIMARSHALER__CREATE_NATIVE_URI_INSTANCE, 1, 1); - - pslILEmit->EmitLabel(pDoneLabel); -} - -void ILUriMarshaler::EmitConvertContentsCLRToNative(ILCodeStream* pslILEmit) -{ - STANDARD_VM_CONTRACT; - - EmitLoadManagedValue(pslILEmit); - EmitConvertCLRUriToWinRTUri(pslILEmit, m_pargs->m_pMarshalInfo->GetModule()->GetLoaderAllocator()); - EmitStoreNativeValue(pslILEmit); -} - -// Note that this method expects the WinRT Uri on top of the evaluation stack and leaves the CLR Uri there. -//static -void ILUriMarshaler::EmitConvertWinRTUriToCLRUri(ILCodeStream* pslILEmit, LoaderAllocator* pLoader) -{ - STANDARD_VM_CONTRACT; - - MethodDesc* pSystemUriCtorMD = pLoader->GetMarshalingData()->GetUriMarshalingInfo()->GetSystemUriCtorMD(); - - ILCodeLabel *pNotNullLabel = pslILEmit->NewCodeLabel(); - ILCodeLabel *pDoneLabel = pslILEmit->NewCodeLabel(); - - pslILEmit->EmitDUP(); - pslILEmit->EmitBRTRUE(pNotNullLabel); - - pslILEmit->EmitPOP(); - pslILEmit->EmitLDNULL(); - pslILEmit->EmitBR(pDoneLabel); - - pslILEmit->EmitLabel(pNotNullLabel); - - // string UriMarshaler.GetRawUriFromNative(IntPtr) - pslILEmit->EmitCALL(METHOD__URIMARSHALER__GET_RAWURI_FROM_NATIVE, 1, 1); - - // System.Uri..ctor(string) - pslILEmit->EmitNEWOBJ(pslILEmit->GetToken(pSystemUriCtorMD), 1); - - pslILEmit->EmitLabel(pDoneLabel); -} - -void ILUriMarshaler::EmitConvertContentsNativeToCLR(ILCodeStream* pslILEmit) -{ - STANDARD_VM_CONTRACT; - - EmitLoadNativeValue(pslILEmit); - EmitConvertWinRTUriToCLRUri(pslILEmit, m_pargs->m_pMarshalInfo->GetModule()->GetLoaderAllocator()); - EmitStoreManagedValue(pslILEmit); -} - -void ILUriMarshaler::EmitClearNative(ILCodeStream* pslILEmit) -{ - STANDARD_VM_CONTRACT; - EmitInterfaceClearNative(pslILEmit); -} - -/////////////////////////////////////////////////////////////////////////////////////////////////// -// ILNCCEventArgsMarshaler implementation -/////////////////////////////////////////////////////////////////////////////////////////////////// - -LocalDesc ILNCCEventArgsMarshaler::GetNativeType() -{ - LIMITED_METHOD_CONTRACT; - return LocalDesc(ELEMENT_TYPE_I); -} - -LocalDesc ILNCCEventArgsMarshaler::GetManagedType() -{ - STANDARD_VM_CONTRACT;; - - LoaderAllocator *pLoader = m_pargs->m_pMarshalInfo->GetModule()->GetLoaderAllocator(); - TypeHandle hndNCCEventArgType = pLoader->GetMarshalingData()->GetEventArgsMarshalingInfo()->GetSystemNCCEventArgsType(); - - return LocalDesc(hndNCCEventArgType); // System.Collections.Specialized.NotifyCollectionChangedEventArgs -} - -bool ILNCCEventArgsMarshaler::NeedsClearNative() -{ - LIMITED_METHOD_CONTRACT; - return true; -} - -// Note that this method expects the CLR NotifyCollectionChangedEventArgs on top of the evaluation stack and -// leaves the WinRT NotifyCollectionChangedEventArgs IP there. -//static -void ILNCCEventArgsMarshaler::EmitConvertCLREventArgsToWinRTEventArgs(ILCodeStream *pslILEmit, LoaderAllocator* pLoader) -{ - STANDARD_VM_CONTRACT; - - MethodDesc *pConvertMD = pLoader->GetMarshalingData()->GetEventArgsMarshalingInfo()->GetSystemNCCEventArgsToWinRTNCCEventArgsMD(); - - // IntPtr System.Runtime.InteropServices.WindowsRuntime.NotifyCollectionChangedEventArgsMarshaler.ConvertToNative(NotifyCollectionChangedEventArgs) - pslILEmit->EmitCALL(pslILEmit->GetToken(pConvertMD), 1, 1); -} - -void ILNCCEventArgsMarshaler::EmitConvertContentsCLRToNative(ILCodeStream *pslILEmit) -{ - STANDARD_VM_CONTRACT; - - EmitLoadManagedValue(pslILEmit); - EmitConvertCLREventArgsToWinRTEventArgs(pslILEmit, m_pargs->m_pMarshalInfo->GetModule()->GetLoaderAllocator()); - EmitStoreNativeValue(pslILEmit); -} - -// Note that this method expects the WinRT NotifyCollectionChangedEventArgs on top of the evaluation stack and -// leaves the CLR NotifyCollectionChangedEventArgs there. -//static -void ILNCCEventArgsMarshaler::EmitConvertWinRTEventArgsToCLREventArgs(ILCodeStream* pslILEmit, LoaderAllocator* pLoader) -{ - STANDARD_VM_CONTRACT; - - MethodDesc *pConvertMD = pLoader->GetMarshalingData()->GetEventArgsMarshalingInfo()->GetWinRTNCCEventArgsToSystemNCCEventArgsMD(); - - // NotifyCollectionChangedEventArgs System.Runtime.InteropServices.WindowsRuntime.NotifyCollectionChangedEventArgsMarshaler.ConvertToManaged(IntPtr) - pslILEmit->EmitCALL(pslILEmit->GetToken(pConvertMD), 1, 1); -} - -void ILNCCEventArgsMarshaler::EmitConvertContentsNativeToCLR(ILCodeStream* pslILEmit) -{ - STANDARD_VM_CONTRACT; - - EmitLoadNativeValue(pslILEmit); - EmitConvertWinRTEventArgsToCLREventArgs(pslILEmit, m_pargs->m_pMarshalInfo->GetModule()->GetLoaderAllocator()); - EmitStoreManagedValue(pslILEmit); -} - -void ILNCCEventArgsMarshaler::EmitClearNative(ILCodeStream* pslILEmit) -{ - STANDARD_VM_CONTRACT; - EmitInterfaceClearNative(pslILEmit); -} - -/////////////////////////////////////////////////////////////////////////////////////////////////// -// ILPCEventArgsMarshaler implementation -/////////////////////////////////////////////////////////////////////////////////////////////////// - -LocalDesc ILPCEventArgsMarshaler::GetNativeType() -{ - LIMITED_METHOD_CONTRACT; - return LocalDesc(ELEMENT_TYPE_I); -} - -LocalDesc ILPCEventArgsMarshaler::GetManagedType() -{ - STANDARD_VM_CONTRACT;; - - LoaderAllocator* pLoader = m_pargs->m_pMarshalInfo->GetModule()->GetLoaderAllocator(); - TypeHandle hndPCEventArgType = pLoader->GetMarshalingData()->GetEventArgsMarshalingInfo()->GetSystemPCEventArgsType(); - - return LocalDesc(hndPCEventArgType); // System.ComponentModel.PropertyChangedEventArgs -} - -bool ILPCEventArgsMarshaler::NeedsClearNative() -{ - LIMITED_METHOD_CONTRACT; - return true; -} - -// Note that this method expects the CLR PropertyChangedEventArgs on top of the evaluation stack and -// leaves the WinRT PropertyChangedEventArgs IP there. -//static -void ILPCEventArgsMarshaler::EmitConvertCLREventArgsToWinRTEventArgs(ILCodeStream *pslILEmit, LoaderAllocator* pLoader) -{ - STANDARD_VM_CONTRACT; - - MethodDesc *pConvertMD = pLoader->GetMarshalingData()->GetEventArgsMarshalingInfo()->GetSystemPCEventArgsToWinRTPCEventArgsMD(); - - // IntPtr System.Runtime.InteropServices.WindowsRuntime.PropertyChangedEventArgsMarshaler.ConvertToNative(PropertyChangedEventArgs) - pslILEmit->EmitCALL(pslILEmit->GetToken(pConvertMD), 1, 1); -} - -void ILPCEventArgsMarshaler::EmitConvertContentsCLRToNative(ILCodeStream *pslILEmit) -{ - STANDARD_VM_CONTRACT; - - EmitLoadManagedValue(pslILEmit); - EmitConvertCLREventArgsToWinRTEventArgs(pslILEmit, m_pargs->m_pMarshalInfo->GetModule()->GetLoaderAllocator()); - EmitStoreNativeValue(pslILEmit); -} - -// Note that this method expects the WinRT PropertyChangedEventArgs on top of the evaluation stack and -// leaves the CLR PropertyChangedEventArgs there. -//static -void ILPCEventArgsMarshaler::EmitConvertWinRTEventArgsToCLREventArgs(ILCodeStream* pslILEmit, LoaderAllocator* pLoader) -{ - STANDARD_VM_CONTRACT; - - MethodDesc *pConvertMD = pLoader->GetMarshalingData()->GetEventArgsMarshalingInfo()->GetWinRTPCEventArgsToSystemPCEventArgsMD(); - - // PropertyChangedEventArgs System.Runtime.InteropServices.WindowsRuntime.PropertyChangedEventArgsMarshaler.ConvertToManaged(IntPtr) - pslILEmit->EmitCALL(pslILEmit->GetToken(pConvertMD), 1, 1); -} - -void ILPCEventArgsMarshaler::EmitConvertContentsNativeToCLR(ILCodeStream* pslILEmit) -{ - STANDARD_VM_CONTRACT; - - EmitLoadNativeValue(pslILEmit); - EmitConvertWinRTEventArgsToCLREventArgs(pslILEmit, m_pargs->m_pMarshalInfo->GetModule()->GetLoaderAllocator()); - EmitStoreManagedValue(pslILEmit); -} - -void ILPCEventArgsMarshaler::EmitClearNative(ILCodeStream* pslILEmit) -{ - STANDARD_VM_CONTRACT; - EmitInterfaceClearNative(pslILEmit); -} - -/////////////////////////////////////////////////////////////////////////////////////////////////// -// ILDateTimeMarshaler implementation -/////////////////////////////////////////////////////////////////////////////////////////////////// - -LocalDesc ILDateTimeMarshaler::GetNativeType() -{ - STANDARD_VM_CONTRACT;; - return LocalDesc(MscorlibBinder::GetClass(CLASS__DATETIMENATIVE)); -} - -LocalDesc ILDateTimeMarshaler::GetManagedType() -{ - STANDARD_VM_CONTRACT;; - return LocalDesc(MscorlibBinder::GetClass(CLASS__DATE_TIME_OFFSET)); -} - -bool ILDateTimeMarshaler::NeedsClearNative() -{ - LIMITED_METHOD_CONTRACT; - return false; -} - -void ILDateTimeMarshaler::EmitConvertContentsCLRToNative(ILCodeStream* pslILEmit) -{ - CONTRACTL - { - STANDARD_VM_CHECK; - PRECONDITION(CheckPointer(pslILEmit)); - } - CONTRACTL_END; - - // DateTimeOffsetMarshaler.ConvertManagedToNative(ref managedDTO, out nativeTicks); - EmitLoadManagedHomeAddr(pslILEmit); - EmitLoadNativeHomeAddr(pslILEmit); - pslILEmit->EmitCALL(METHOD__DATETIMEOFFSETMARSHALER__CONVERT_TO_NATIVE, 2, 0); -} - -void ILDateTimeMarshaler::EmitConvertContentsNativeToCLR(ILCodeStream* pslILEmit) -{ - STANDARD_VM_CONTRACT; - - // DateTimeOffsetMarshaler.ConvertNativeToManaged(out managedLocalDTO, ref nativeTicks); - EmitLoadManagedHomeAddr(pslILEmit); - EmitLoadNativeHomeAddr(pslILEmit); - pslILEmit->EmitCALL(METHOD__DATETIMEOFFSETMARSHALER__CONVERT_TO_MANAGED, 2, 0); -} - -void ILDateTimeMarshaler::EmitReInitNative(ILCodeStream* pslILEmit) -{ - STANDARD_VM_CONTRACT; - - EmitLoadNativeHomeAddr(pslILEmit); - pslILEmit->EmitINITOBJ(pslILEmit->GetToken(MscorlibBinder::GetClass(CLASS__DATETIMENATIVE))); -} - -/////////////////////////////////////////////////////////////////////////////////////////////////// -// ILNullableMarshaler implementation -/////////////////////////////////////////////////////////////////////////////////////////////////// - -LocalDesc ILNullableMarshaler::GetNativeType() -{ - LIMITED_METHOD_CONTRACT; - return LocalDesc(ELEMENT_TYPE_I); -} - -LocalDesc ILNullableMarshaler::GetManagedType() -{ - LIMITED_METHOD_CONTRACT;; - return LocalDesc(m_pargs->m_pMT); -} - -bool ILNullableMarshaler::NeedsClearNative() -{ - LIMITED_METHOD_CONTRACT; - return true; -} - -void ILNullableMarshaler::EmitConvertContentsCLRToNative(ILCodeStream* pslILEmit) -{ - CONTRACTL - { - STANDARD_VM_CHECK; - PRECONDITION(CheckPointer(pslILEmit)); - } - CONTRACTL_END; - - // pNative = NullableMarshaler.ConvertToNative(ref pManaged); - EmitLoadManagedHomeAddr(pslILEmit); - - MethodDesc *pMD = GetExactMarshalerMethod(MscorlibBinder::GetMethod(METHOD__NULLABLEMARSHALER__CONVERT_TO_NATIVE)); - pslILEmit->EmitCALL(pslILEmit->GetToken(pMD), 1, 1); - - EmitStoreNativeValue(pslILEmit); -} - -void ILNullableMarshaler::EmitConvertContentsNativeToCLR(ILCodeStream* pslILEmit) -{ - STANDARD_VM_CONTRACT; - - // pManaged = NullableMarshaler.ConvertToManaged(pNative); - EmitLoadNativeValue(pslILEmit); - - MethodDesc *pMD = GetExactMarshalerMethod(MscorlibBinder::GetMethod(METHOD__NULLABLEMARSHALER__CONVERT_TO_MANAGED)); - pslILEmit->EmitCALL(pslILEmit->GetToken(pMD), 1, 1); - - EmitStoreManagedValue(pslILEmit); -} - -void ILNullableMarshaler::EmitClearNative(ILCodeStream* pslILEmit) -{ - STANDARD_VM_CONTRACT; - EmitInterfaceClearNative(pslILEmit); -} - -MethodDesc *ILNullableMarshaler::GetExactMarshalerMethod(MethodDesc *pGenericMD) -{ - STANDARD_VM_CONTRACT; - - return MethodDesc::FindOrCreateAssociatedMethodDesc( - pGenericMD, - pGenericMD->GetMethodTable(), - FALSE, // forceBoxedEntryPoint - m_pargs->m_pMT->GetInstantiation(), // methodInst - FALSE, // allowInstParam - TRUE); // forceRemotableMethod -} - -/////////////////////////////////////////////////////////////////////////////////////////////////// -// ILSystemTypeMarshaler implementation -/////////////////////////////////////////////////////////////////////////////////////////////////// - -LocalDesc ILSystemTypeMarshaler::GetNativeType() -{ - STANDARD_VM_CONTRACT; - - return LocalDesc(MscorlibBinder::GetClass(CLASS__TYPENAMENATIVE)); -} - -LocalDesc ILSystemTypeMarshaler::GetManagedType() -{ - STANDARD_VM_CONTRACT; - - return LocalDesc(MscorlibBinder::GetClass(CLASS__TYPE)); -} - -bool ILSystemTypeMarshaler::NeedsClearNative() -{ - LIMITED_METHOD_CONTRACT; - return true; -} - -void ILSystemTypeMarshaler::EmitConvertContentsCLRToNative(ILCodeStream * pslILEmit) -{ - STANDARD_VM_CONTRACT; - - // SystemTypeMarshaler.ConvertToNative(Type, pTypeName); - EmitLoadManagedValue(pslILEmit); - EmitLoadNativeHomeAddr(pslILEmit); - pslILEmit->EmitCALL(METHOD__SYSTEMTYPEMARSHALER__CONVERT_TO_NATIVE, 2, 0); -} - -void ILSystemTypeMarshaler::EmitConvertContentsNativeToCLR(ILCodeStream * pslILEmit) -{ - STANDARD_VM_CONTRACT; - - // type = SystemTypeMarshaler.ConvertNativeToManaged(pTypeName, ref Type); - EmitLoadNativeHomeAddr(pslILEmit); - EmitLoadManagedHomeAddr(pslILEmit); - pslILEmit->EmitCALL(METHOD__SYSTEMTYPEMARSHALER__CONVERT_TO_MANAGED, 2, 0); -} - - -void ILSystemTypeMarshaler::EmitClearNative(ILCodeStream * pslILEmit) -{ - STANDARD_VM_CONTRACT; - - // SystemTypeMarshaler.ClearNative(pTypeName) - EmitLoadNativeHomeAddr(pslILEmit); - pslILEmit->EmitCALL(METHOD__SYSTEMTYPEMARSHALER__CLEAR_NATIVE, 1, 0); -} - -void ILSystemTypeMarshaler::EmitReInitNative(ILCodeStream * pslILEmit) -{ - EmitLoadNativeHomeAddr(pslILEmit); - pslILEmit->EmitINITOBJ(pslILEmit->GetToken(MscorlibBinder::GetClass(CLASS__TYPENAMENATIVE))); -} - -/////////////////////////////////////////////////////////////////////////////////////////////////// -// ILHResultExceptionMarshaler implementation -/////////////////////////////////////////////////////////////////////////////////////////////////// - -LocalDesc ILHResultExceptionMarshaler::GetNativeType() -{ - LIMITED_METHOD_CONTRACT; - return LocalDesc(ELEMENT_TYPE_I4); -} - -LocalDesc ILHResultExceptionMarshaler::GetManagedType() -{ - LIMITED_METHOD_CONTRACT; - _ASSERTE(m_pargs->m_pMT != NULL); - return LocalDesc(m_pargs->m_pMT); -} - -bool ILHResultExceptionMarshaler::NeedsClearNative() -{ - LIMITED_METHOD_CONTRACT; - return false; -} - -void ILHResultExceptionMarshaler::EmitConvertContentsCLRToNative(ILCodeStream* pslILEmit) -{ - CONTRACTL - { - STANDARD_VM_CHECK; - PRECONDITION(CheckPointer(pslILEmit)); - } - CONTRACTL_END; - - // int HResultExceptionMarshaler.ConvertManagedToNative(Exception); - EmitLoadManagedValue(pslILEmit); - pslILEmit->EmitCALL(METHOD__HRESULTEXCEPTIONMARSHALER__CONVERT_TO_NATIVE, 1, 1); - EmitStoreNativeValue(pslILEmit); -} - -void ILHResultExceptionMarshaler::EmitConvertContentsNativeToCLR(ILCodeStream* pslILEmit) -{ - CONTRACTL - { - STANDARD_VM_CHECK; - PRECONDITION(CheckPointer(pslILEmit)); - } - CONTRACTL_END; - - // Exception HResultExceptionMarshaler.ConvertNativeToManaged(int hr); - EmitLoadNativeValue(pslILEmit); - pslILEmit->EmitCALL(METHOD__HRESULTEXCEPTIONMARSHALER__CONVERT_TO_MANAGED, 1, 1); - EmitStoreManagedValue(pslILEmit); -} - -/////////////////////////////////////////////////////////////////////////////////////////////////// -// ILKeyValuePairMarshaler implementation -/////////////////////////////////////////////////////////////////////////////////////////////////// - -LocalDesc ILKeyValuePairMarshaler::GetNativeType() -{ - LIMITED_METHOD_CONTRACT; - return LocalDesc(ELEMENT_TYPE_I); -} - -LocalDesc ILKeyValuePairMarshaler::GetManagedType() -{ - LIMITED_METHOD_CONTRACT;; - return LocalDesc(m_pargs->m_pMT); -} - -bool ILKeyValuePairMarshaler::NeedsClearNative() -{ - LIMITED_METHOD_CONTRACT; - return true; -} - -void ILKeyValuePairMarshaler::EmitConvertContentsCLRToNative(ILCodeStream* pslILEmit) -{ - STANDARD_VM_CONTRACT; - - // Native = KeyValueMarshaler.ConvertToNative([In] ref Managed); - EmitLoadManagedHomeAddr(pslILEmit); - - MethodDesc *pMD = GetExactMarshalerMethod(MscorlibBinder::GetMethod(METHOD__KEYVALUEPAIRMARSHALER__CONVERT_TO_NATIVE)); - pslILEmit->EmitCALL(pslILEmit->GetToken(pMD), 1, 1); - - EmitStoreNativeValue(pslILEmit); -} - -void ILKeyValuePairMarshaler::EmitConvertContentsNativeToCLR(ILCodeStream* pslILEmit) -{ - STANDARD_VM_CONTRACT; - - // Managed = KeyValuePairMarshaler.ConvertToManaged(Native); - EmitLoadNativeValue(pslILEmit); - - MethodDesc *pMD = GetExactMarshalerMethod(MscorlibBinder::GetMethod(METHOD__KEYVALUEPAIRMARSHALER__CONVERT_TO_MANAGED)); - pslILEmit->EmitCALL(pslILEmit->GetToken(pMD), 1, 1); - - EmitStoreManagedValue(pslILEmit); -} - -void ILKeyValuePairMarshaler::EmitClearNative(ILCodeStream* pslILEmit) -{ - STANDARD_VM_CONTRACT; - EmitInterfaceClearNative(pslILEmit); -} - -MethodDesc *ILKeyValuePairMarshaler::GetExactMarshalerMethod(MethodDesc *pGenericMD) -{ - STANDARD_VM_CONTRACT; - - // KeyValuePairMarshaler methods are generic - find/create the exact method. - return MethodDesc::FindOrCreateAssociatedMethodDesc( - pGenericMD, - pGenericMD->GetMethodTable(), - FALSE, // forceBoxedEntryPoint - m_pargs->m_pMT->GetInstantiation(), // methodInst - FALSE, // allowInstParam - TRUE); // forceRemotableMethod -} - -#endif // FEATURE_COMINTEROP +#endif // CROSSGEN_COMPILE diff --git a/src/coreclr/src/vm/ilmarshalers.h b/src/coreclr/src/vm/ilmarshalers.h index 21e1b2d..3aae504 100644 --- a/src/coreclr/src/vm/ilmarshalers.h +++ b/src/coreclr/src/vm/ilmarshalers.h @@ -359,12 +359,6 @@ protected: return (0 != (dwMarshalFlags & MARSHAL_FLAG_IN_MEMBER_FUNCTION)); } - static inline bool IsHiddenLengthParam(DWORD dwMarshalFlags) - { - LIMITED_METHOD_CONTRACT; - return (0 != (dwMarshalFlags & MARSHAL_FLAG_HIDDENLENPARAM)); - } - static inline bool IsFieldMarshal(DWORD dwMarshalFlags) { LIMITED_METHOD_CONTRACT; @@ -561,124 +555,6 @@ public: } } -#ifdef FEATURE_COMINTEROP - void EmitMarshalHiddenLengthArgument(ILCodeStream *pcsMarshal, - ILCodeStream *pcsUnmarshal, - MarshalInfo *pArrayInfo, - UINT arrayIndex, - DWORD dwMarshalFlags, - UINT hiddenArgIndex, - OverrideProcArgs *pargs, - __out DWORD *pdwHiddenLengthManagedHomeLocal, - __out DWORD *pdwHiddenLengthNativeHomeLocal) - { - CONTRACTL - { - STANDARD_VM_CHECK; - PRECONDITION(IsHiddenLengthParam(dwMarshalFlags)); - } - CONTRACTL_END; - - Init(pcsMarshal, pcsUnmarshal, hiddenArgIndex, dwMarshalFlags, pargs); - - if (!CanMarshalViaPinning()) - { - EmitCreateMngdMarshaler(m_pslNDirect->GetSetupCodeStream()); - } - - EmitSetupArgumentForMarshalling(m_pslNDirect->GetSetupCodeStream()); - - // Create a local to be the home of the length parameter - DWORD dwManagedLocalHome = m_pcsMarshal->NewLocal(GetManagedType()); - m_managedHome.InitHome(ILStubMarshalHome::HomeType_ILLocal, dwManagedLocalHome); - *pdwHiddenLengthManagedHomeLocal = dwManagedLocalHome; - - // managed length = 0 - m_pcsMarshal->EmitLDC(0); - m_pcsMarshal->EmitCONV_T(pArrayInfo->GetHiddenLengthParamElementType()); - m_pcsMarshal->EmitSTLOC(dwManagedLocalHome); - - // And a local to be the home of the marshaled length - LocalDesc nativeArgType(GetNativeType()); - DWORD dwNativeHomeLocal = m_pcsMarshal->NewLocal(nativeArgType); - if (IsByref(dwMarshalFlags)) - { - nativeArgType.MakeByRef(); - } - m_nativeHome.InitHome(ILStubMarshalHome::HomeType_ILLocal, dwNativeHomeLocal); - *pdwHiddenLengthNativeHomeLocal = dwNativeHomeLocal; - - // Update the native signature to contain the new native parameter - m_pcsMarshal->SetStubTargetArgType(&nativeArgType, false); - - if (IsCLRToNative(dwMarshalFlags)) - { - // Load the length of the array into the local - if (IsIn(dwMarshalFlags)) - { - ILCodeLabel *pSkipGetLengthLabel = m_pcsMarshal->NewCodeLabel(); - m_pcsMarshal->EmitLDARG(arrayIndex); - m_pcsMarshal->EmitBRFALSE(pSkipGetLengthLabel); - - m_pcsMarshal->EmitLDARG(arrayIndex); - - if (IsByref(dwMarshalFlags)) - { - // if (*array == null) goto pSkipGetLengthLabel - m_pcsMarshal->EmitLDIND_REF(); - m_pcsMarshal->EmitBRFALSE(pSkipGetLengthLabel); - - // array = *array - m_pcsMarshal->EmitLDARG(arrayIndex); - m_pcsMarshal->EmitLDIND_REF(); - } - - m_pcsMarshal->EmitLDLEN(); - m_pcsMarshal->EmitCONV_T(pArrayInfo->GetHiddenLengthParamElementType()); - m_pcsMarshal->EmitSTLOC(dwManagedLocalHome); - m_pcsMarshal->EmitLabel(pSkipGetLengthLabel); - } - - if (IsByref(dwMarshalFlags)) - { - EmitMarshalArgumentContentsCLRToNativeByref(true); - } - else - { - EmitMarshalArgumentContentsCLRToNative(); - } - } - else - { - // Load the length of the array into the local - if (IsIn(dwMarshalFlags)) - { - m_pcsMarshal->EmitLDARG(hiddenArgIndex); - if (IsByref(dwMarshalFlags)) - { - LocalDesc nativeParamType(GetNativeType()); - m_pcsMarshal->EmitLDIND_T(&nativeParamType); - } - m_pcsMarshal->EmitSTLOC(dwNativeHomeLocal); - } - - if (IsByref(dwMarshalFlags)) - { - EmitMarshalArgumentContentsNativeToCLRByref(true); - } - else - { - EmitMarshalArgumentContentsNativeToCLR(); - } - - // We can't copy the final length back to the parameter just yet, since we don't know what - // local the array lives in. Instead, we rely on the hidden length array marshaler to copy - // the value into the out parameter for us. - } - } - -#endif // FEATURE_COMINTEROP - void EmitSetupArgumentForDispatch(ILCodeStream* pslILEmit) { STANDARD_VM_CONTRACT; @@ -1371,17 +1247,14 @@ protected: } // if there is an output buffer, zero it out so the caller does not get pointer to already freed data - if (!IsHiddenLengthParam(m_dwMarshalFlags)) + if (IsRetval(m_dwMarshalFlags) || (IsOut(m_dwMarshalFlags) && IsByref(m_dwMarshalFlags))) { - if (IsRetval(m_dwMarshalFlags) || (IsOut(m_dwMarshalFlags) && IsByref(m_dwMarshalFlags))) - { - m_pslNDirect->SetExceptionCleanupNeeded(); + m_pslNDirect->SetExceptionCleanupNeeded(); - EmitReInitNative(pcsCleanup); - if (IsHresultSwap(m_dwMarshalFlags) || IsOut(m_dwMarshalFlags)) - { - m_nativeHome.EmitCopyToByrefArgWithNullCheck(pcsCleanup, &nativeType, m_argidx); - } + EmitReInitNative(pcsCleanup); + if (IsHresultSwap(m_dwMarshalFlags) || IsOut(m_dwMarshalFlags)) + { + m_nativeHome.EmitCopyToByrefArgWithNullCheck(pcsCleanup, &nativeType, m_argidx); } } } @@ -2819,30 +2692,6 @@ protected: DWORD m_dwCCHLocal; }; - -class ILHSTRINGMarshaler : public ILMarshaler -{ -public: - enum - { - c_fInOnly = FALSE, - c_nativeSize = sizeof(HSTRING), - c_CLRSize = sizeof(OBJECTREF), - }; - -protected: - LocalDesc GetNativeType() override; - LocalDesc GetManagedType() override; - - void EmitConvertContentsCLRToNative(ILCodeStream* pslILEmit) override; - void EmitConvertCLRToHSTRINGReference(ILCodeStream* pslILEmit); - void EmitConvertCLRToHSTRING(ILCodeStream* pslILEmit); - - void EmitConvertContentsNativeToCLR(ILCodeStream* pslILEmit) override; - - bool NeedsClearNative() override; - void EmitClearNative(ILCodeStream* pslILEmit) override; -}; #endif // FEATURE_COMINTEROP @@ -3736,77 +3585,6 @@ public: BYTE m_fStatic; // StaticCheckStateFlags BYTE m_nolowerbounds; }; - -class ILHiddenLengthArrayMarshaler : public ILMngdMarshaler -{ - friend class MngdHiddenLengthArrayMarshaler; - -public: - enum - { - c_nativeSize = sizeof(LPVOID), - c_CLRSize = sizeof(OBJECTREF), - c_fInOnly = FALSE, - }; - - ILHiddenLengthArrayMarshaler() : - ILMngdMarshaler(METHOD__MNGD_HIDDEN_LENGTH_ARRAY_MARSHALER__CONVERT_SPACE_TO_MANAGED, - METHOD__MNGD_HIDDEN_LENGTH_ARRAY_MARSHALER__CONVERT_CONTENTS_TO_MANAGED, - METHOD__MNGD_HIDDEN_LENGTH_ARRAY_MARSHALER__CONVERT_SPACE_TO_NATIVE, - METHOD__MNGD_HIDDEN_LENGTH_ARRAY_MARSHALER__CONVERT_CONTENTS_TO_NATIVE, - METHOD__MARSHAL__FREE_CO_TASK_MEM, - METHOD__MNGD_HIDDEN_LENGTH_ARRAY_MARSHALER__CLEAR_NATIVE_CONTENTS, - METHOD__NIL) - { - LIMITED_METHOD_CONTRACT; - m_dwMngdMarshalerLocalNum = LOCAL_NUM_UNUSED; - } - -protected: - LocalDesc GetNativeType() override; - LocalDesc GetManagedType() override; - bool CanMarshalViaPinning() override; - - void EmitMarshalViaPinning(ILCodeStream* pslILEmit) override; - void EmitCreateMngdMarshaler(ILCodeStream* pslILEmit) override; - void EmitConvertSpaceCLRToNative(ILCodeStream* pslILEmit) override; - void EmitConvertSpaceNativeToCLR(ILCodeStream* pslILEmit) override; - void EmitConvertContentsCLRToNative(ILCodeStream* pslILEmit) override; - void EmitConvertContentsNativeToCLR(ILCodeStream* pslILEmit) override; - void EmitClearNative(ILCodeStream* pslILEmit) override; - void EmitClearNativeContents(ILCodeStream* pslILEmit) override; - -private: - void EmitLoadNativeArrayLength(ILCodeStream *pslILEmit); - - MethodDesc *GetConvertContentsToManagedMethod() override; - MethodDesc *GetConvertContentsToNativeMethod() override; - MethodDesc *GetClearNativeContentsMethod() override; - - MethodDesc *GetExactMarshalerMethod(MethodDesc *pGenericMD); -}; - -class MngdHiddenLengthArrayMarshaler -{ -public: - static FCDECL5(void, CreateMarshaler, MngdHiddenLengthArrayMarshaler* pThis, MethodTable* pMT, SIZE_T cbElement, UINT16 vt, PCODE pManagedMarshaler); - static FCDECL3(void, ConvertSpaceToNative, MngdHiddenLengthArrayMarshaler* pThis, OBJECTREF* pManagedHome, void** pNativeHome); - static FCDECL3(void, ConvertContentsToNative, MngdHiddenLengthArrayMarshaler* pThis, OBJECTREF* pManagedHome, void** pNativeHome); - static FCDECL4(void, ConvertSpaceToManaged, MngdHiddenLengthArrayMarshaler* pThis, OBJECTREF* pManagedHome, void** pNativeHome, INT32 cElements); - static FCDECL3(void, ConvertContentsToManaged, MngdHiddenLengthArrayMarshaler* pThis, OBJECTREF* pManagedHome, void** pNativeHome); - static FCDECL3(void, ClearNativeContents, MngdHiddenLengthArrayMarshaler* pThis, void** pNativeHome, INT32 cElements); - - -private: - SIZE_T GetArraySize(SIZE_T elements); - void DoClearNativeContents(MngdHiddenLengthArrayMarshaler* pThis, void** pNativeHome, INT32 cElements); - -private: - MethodTable* m_pElementMT; - PCODE m_pManagedMarshaler; - SIZE_T m_cbElementSize; - VARTYPE m_vt; -}; #endif // FEATURE_COMINTEROP @@ -3847,186 +3625,3 @@ public: CustomMarshalerHelper* m_pCMHelper; }; - - -#ifdef FEATURE_COMINTEROP -class ILUriMarshaler : public ILMarshaler -{ -public: - enum - { - c_fInOnly = TRUE, - c_nativeSize = sizeof(LPVOID), - c_CLRSize = sizeof(OBJECTREF), - }; - - static void EmitConvertCLRUriToWinRTUri(ILCodeStream* pslILEmit, LoaderAllocator* pLoader); - static void EmitConvertWinRTUriToCLRUri(ILCodeStream* pslILEmit, LoaderAllocator* pLoader); - -protected: - LocalDesc GetNativeType() override; - LocalDesc GetManagedType() override; - - void EmitConvertContentsCLRToNative(ILCodeStream* pslILEmit) override; - void EmitConvertContentsNativeToCLR(ILCodeStream* pslILEmit) override; - - bool NeedsClearNative() override; - void EmitClearNative(ILCodeStream* pslILEmit); -}; - -class ILNCCEventArgsMarshaler : public ILMarshaler -{ -public: - enum - { - c_fInOnly = TRUE, - c_nativeSize = sizeof(LPVOID), - c_CLRSize = sizeof(OBJECTREF), - }; - - static void EmitConvertCLREventArgsToWinRTEventArgs(ILCodeStream* pslILEmit, LoaderAllocator* pLoader); - static void EmitConvertWinRTEventArgsToCLREventArgs(ILCodeStream* pslILEmit, LoaderAllocator* pLoader); - -protected: - LocalDesc GetNativeType() override; - LocalDesc GetManagedType() override; - - void EmitConvertContentsCLRToNative(ILCodeStream* pslILEmit) override; - void EmitConvertContentsNativeToCLR(ILCodeStream* pslILEmit) override; - - bool NeedsClearNative() override; - void EmitClearNative(ILCodeStream* pslILEmit); -}; - -class ILPCEventArgsMarshaler : public ILMarshaler -{ -public: - enum - { - c_fInOnly = TRUE, - c_nativeSize = sizeof(LPVOID), - c_CLRSize = sizeof(OBJECTREF), - }; - - static void EmitConvertCLREventArgsToWinRTEventArgs(ILCodeStream* pslILEmit, LoaderAllocator* pLoader); - static void EmitConvertWinRTEventArgsToCLREventArgs(ILCodeStream* pslILEmit, LoaderAllocator* pLoader); - -protected: - LocalDesc GetNativeType() override; - LocalDesc GetManagedType() override; - - void EmitConvertContentsCLRToNative(ILCodeStream* pslILEmit) override; - void EmitConvertContentsNativeToCLR(ILCodeStream* pslILEmit) override; - - bool NeedsClearNative() override; - void EmitClearNative(ILCodeStream* pslILEmit); -}; - -class ILDateTimeMarshaler : public ILMarshaler -{ -public: - enum - { - c_fInOnly = FALSE, - c_nativeSize = sizeof(INT64), // = sizeof(Windows::Foundation::DateTime) - c_CLRSize = VARIABLESIZE, - }; - -protected: - LocalDesc GetNativeType() override; - LocalDesc GetManagedType() override; - - void EmitConvertContentsCLRToNative(ILCodeStream* pslILEmit) override; - void EmitConvertContentsNativeToCLR(ILCodeStream* pslILEmit) override; - - bool NeedsClearNative() override; - void EmitReInitNative(ILCodeStream* pslILEmit) override; -}; - -class ILNullableMarshaler : public ILMarshaler -{ -public: - enum - { - c_fInOnly = FALSE, - c_nativeSize = sizeof(LPVOID), - c_CLRSize = VARIABLESIZE, - }; - -protected: - LocalDesc GetNativeType() override; - LocalDesc GetManagedType() override; - bool NeedsClearNative() override; - void EmitConvertContentsCLRToNative(ILCodeStream* pslILEmit) override; - void EmitConvertContentsNativeToCLR(ILCodeStream* pslILEmit) override; - void EmitClearNative(ILCodeStream* pslILEmit) override; - -private: - MethodDesc *GetExactMarshalerMethod(MethodDesc *pGenericMD); -}; - -class ILSystemTypeMarshaler : public ILMarshaler -{ -public: - enum - { - c_fInOnly = FALSE, - c_nativeSize = sizeof(TypeNameNative), - c_CLRSize = sizeof(OBJECTREF) - }; - -protected: - LocalDesc GetNativeType() override; - LocalDesc GetManagedType() override; - - void EmitConvertContentsCLRToNative(ILCodeStream * pslILEmit) override; - void EmitConvertContentsNativeToCLR(ILCodeStream * pslILEmit) override; - - bool NeedsClearNative() override; - void EmitClearNative(ILCodeStream * pslILEmit) override; - void EmitReInitNative(ILCodeStream * pslILEmit) override; -}; - -class ILHResultExceptionMarshaler : public ILMarshaler -{ -public: - enum - { - c_fInOnly = FALSE, - c_nativeSize = sizeof(INT32), // = sizeof(Windows::Foundation::HResult) - c_CLRSize = sizeof(OBJECTREF), - }; - -protected: - LocalDesc GetNativeType() override; - LocalDesc GetManagedType() override; - - void EmitConvertContentsCLRToNative(ILCodeStream* pslILEmit) override; - void EmitConvertContentsNativeToCLR(ILCodeStream* pslILEmit) override; - - bool NeedsClearNative() override; -}; - -class ILKeyValuePairMarshaler : public ILMarshaler -{ -public: - enum - { - c_fInOnly = FALSE, - c_nativeSize = sizeof(LPVOID), - c_CLRSize = VARIABLESIZE, - }; - -protected: - LocalDesc GetNativeType() override; - LocalDesc GetManagedType() override; - bool NeedsClearNative() override; - void EmitConvertContentsCLRToNative(ILCodeStream* pslILEmit) override; - void EmitConvertContentsNativeToCLR(ILCodeStream* pslILEmit) override; - void EmitClearNative(ILCodeStream* pslILEmit) override; - -private: - MethodDesc *GetExactMarshalerMethod(MethodDesc *pGenericMD); -}; - -#endif // FEATURE_COMINTEROP diff --git a/src/coreclr/src/vm/ilstubcache.cpp b/src/coreclr/src/vm/ilstubcache.cpp index 0ea66d4..8ab1ea8 100644 --- a/src/coreclr/src/vm/ilstubcache.cpp +++ b/src/coreclr/src/vm/ilstubcache.cpp @@ -270,19 +270,14 @@ MethodDesc* ILStubCache::CreateNewMethodDesc(LoaderHeap* pCreationHeap, MethodTa { pMD->m_dwExtendedFlags |= DynamicMethodDesc::nomdReverseStub; - ILStubResolver::ILStubType type = (SF_IsWinRTStub(dwStubFlags) ? ILStubResolver::WinRTToCLRInteropStub : ILStubResolver::COMToCLRInteropStub); + ILStubResolver::ILStubType type = ILStubResolver::COMToCLRInteropStub; pMD->GetILStubResolver()->SetStubType(type); } else { - ILStubResolver::ILStubType type = (SF_IsWinRTStub(dwStubFlags) ? ILStubResolver::CLRToWinRTInteropStub : ILStubResolver::CLRToCOMInteropStub); + ILStubResolver::ILStubType type = ILStubResolver::CLRToCOMInteropStub; pMD->GetILStubResolver()->SetStubType(type); } - - if (SF_IsWinRTDelegateStub(dwStubFlags)) - { - pMD->m_dwExtendedFlags |= DynamicMethodDesc::nomdDelegateCOMStub; - } } else #endif diff --git a/src/coreclr/src/vm/ilstubresolver.cpp b/src/coreclr/src/vm/ilstubresolver.cpp index a0d19f1..7e3650d 100644 --- a/src/coreclr/src/vm/ilstubresolver.cpp +++ b/src/coreclr/src/vm/ilstubresolver.cpp @@ -73,10 +73,8 @@ LPCUTF8 ILStubResolver::GetStubMethodName() { case CLRToNativeInteropStub: return "IL_STUB_PInvoke"; case CLRToCOMInteropStub: return "IL_STUB_CLRtoCOM"; - case CLRToWinRTInteropStub: return "IL_STUB_CLRtoWinRT"; case NativeToCLRInteropStub: return "IL_STUB_ReversePInvoke"; case COMToCLRInteropStub: return "IL_STUB_COMtoCLR"; - case WinRTToCLRInteropStub: return "IL_STUB_WinRTtoCLR"; case StructMarshalInteropStub: return "IL_STUB_StructMarshal"; #ifdef FEATURE_ARRAYSTUB_AS_IL case ArrayOpStub: return "IL_STUB_Array"; diff --git a/src/coreclr/src/vm/ilstubresolver.h b/src/coreclr/src/vm/ilstubresolver.h index 3b31919..88b6c81 100644 --- a/src/coreclr/src/vm/ilstubresolver.h +++ b/src/coreclr/src/vm/ilstubresolver.h @@ -78,10 +78,8 @@ public: Unassigned = 0, CLRToNativeInteropStub, CLRToCOMInteropStub, - CLRToWinRTInteropStub, NativeToCLRInteropStub, COMToCLRInteropStub, - WinRTToCLRInteropStub, StructMarshalInteropStub, #ifdef FEATURE_ARRAYSTUB_AS_IL ArrayOpStub, diff --git a/src/coreclr/src/vm/interopconverter.cpp b/src/coreclr/src/vm/interopconverter.cpp index 00fa3cb..e46864e 100644 --- a/src/coreclr/src/vm/interopconverter.cpp +++ b/src/coreclr/src/vm/interopconverter.cpp @@ -18,7 +18,6 @@ #include "cominterfacemarshaler.h" #include "binder.h" #include -#include "winrttypenameconverter.h" #include "typestring.h" namespace @@ -160,7 +159,7 @@ IUnknown *GetComIPFromObjectRef(OBJECTREF *poref, ComIpType ReqIpType, ComIpType THROWS; GC_TRIGGERS; MODE_COOPERATIVE; - PRECONDITION((ReqIpType & (ComIpType_Dispatch | ComIpType_Unknown | ComIpType_Inspectable)) != 0); + PRECONDITION((ReqIpType & (ComIpType_Dispatch | ComIpType_Unknown)) != 0); PRECONDITION(CheckPointer(poref)); PRECONDITION(ReqIpType != 0); POSTCONDITION((*poref) != NULL ? CheckPointer(RETVAL) : CheckPointer(RETVAL, NULL_OK)); @@ -189,11 +188,6 @@ IUnknown *GetComIPFromObjectRef(OBJECTREF *poref, ComIpType ReqIpType, ComIpType hr = SafeQueryInterface(pUnk, IID_IDispatch, &pvObj); pUnk->Release(); } - else if (ReqIpType & ComIpType_Inspectable) - { - hr = SafeQueryInterface(pUnk, IID_IInspectable, &pvObj); - pUnk->Release(); - } else { pvObj = pUnk; @@ -226,157 +220,6 @@ IUnknown *GetComIPFromObjectRef(OBJECTREF *poref, ComIpType ReqIpType, ComIpType FetchedIpType = ComIpType_Dispatch; } - if (ReqIpType & ComIpType_Inspectable) - { - WinMDAdapter::RedirectedTypeIndex redirectedTypeIndex; - - MethodTable * pMT = (*poref)->GetMethodTable(); - - // - // Check whether this object is of a legal WinRT type (including array) - // - // Note that System.RuntimeType is a weird case - we only redirect System.Type at type - // level, but when we boxing the actual instance, we expect it to be a System.RuntimeType - // instance, which is not redirected and not a legal WinRT type - // - // Therefore, special case for System.RuntimeType and treat it as a legal WinRT type - // only for boxing - // - if (pMT->IsLegalWinRTType(poref) || - MscorlibBinder::IsClass(pMT, CLASS__CLASS)) - { - // The managed signature contains Object, and native signature is IInspectable. - // "Box" value types by allocating an IReference and storing them inside it. - // Similarly, String must be an IReference. Delegates get wrapped too. - // Arrays must be stored in an IReferenceArray. - // System.Type is in fact internal type System.RuntimeType (CLASS__CLASS) that inherits from it. - // Note: We do not allow System.ReflectionOnlyType that inherits from System.RuntimeType. - // KeyValuePair`2 must be exposed as CLRIKeyValuePair. - if (pMT->HasInstantiation() && pMT->HasSameTypeDefAs(MscorlibBinder::GetClass(CLASS__KEYVALUEPAIRGENERIC))) - { - TypeHandle th = TypeHandle(MscorlibBinder::GetClass(CLASS__CLRIKEYVALUEPAIRIMPL)).Instantiate(pMT->GetInstantiation()); - - MethodDesc *method = MethodDesc::FindOrCreateAssociatedMethodDesc( - MscorlibBinder::GetMethod(METHOD__CLRIKEYVALUEPAIRIMPL__BOXHELPER), - th.GetMethodTable(), - FALSE, - Instantiation(), - FALSE); - _ASSERTE(method != NULL); - - MethodDescCallSite boxHelper(method); - - ARG_SLOT Args[] = - { - ObjToArgSlot(*poref), - }; - OBJECTREF orCLRKeyValuePair = boxHelper.Call_RetOBJECTREF(Args); - - GCPROTECT_BEGIN(orCLRKeyValuePair); - CCWHolder pCCWHoldBoxed = ComCallWrapper::InlineGetWrapper(&orCLRKeyValuePair); - pUnk = ComCallWrapper::GetComIPFromCCW(pCCWHoldBoxed, IID_IInspectable, NULL); - GCPROTECT_END(); - } - else if ((pMT->IsValueType() || - pMT->IsStringOrArray() || - pMT->IsDelegate() || - MscorlibBinder::IsClass(pMT, CLASS__CLASS))) - { - OBJECTREF orBoxedIReference = NULL; - MethodDescCallSite createIReference(METHOD__FACTORYFORIREFERENCE__CREATE_IREFERENCE); - - ARG_SLOT Args[] = - { - ObjToArgSlot(*poref), - }; - - // Call FactoryForIReference::CreateIReference(Object) for an IReference or IReferenceArray. - orBoxedIReference = createIReference.Call_RetOBJECTREF(Args); - - GCPROTECT_BEGIN(orBoxedIReference); - CCWHolder pCCWHoldBoxed = ComCallWrapper::InlineGetWrapper(&orBoxedIReference); - pUnk = ComCallWrapper::GetComIPFromCCW(pCCWHoldBoxed, IID_IInspectable, NULL); - GCPROTECT_END(); - } - else if (WinRTTypeNameConverter::ResolveRedirectedType(pMT, &redirectedTypeIndex)) - { - // This is a redirected type - see if we need to manually marshal it - if (redirectedTypeIndex == WinMDAdapter::RedirectedTypeIndex_System_Uri) - { - UriMarshalingInfo *pUriMarshalInfo = GetAppDomain()->GetLoaderAllocator()->GetMarshalingData()->GetUriMarshalingInfo(); - struct - { - OBJECTREF ref; - STRINGREF refRawUri; - } - gc; - ZeroMemory(&gc, sizeof(gc)); - GCPROTECT_BEGIN(gc); - - gc.ref = *poref; - - MethodDescCallSite getRawURI(pUriMarshalInfo->GetSystemUriOriginalStringMD()); - ARG_SLOT getRawURIArgs[] = - { - ObjToArgSlot(gc.ref) - }; - - gc.refRawUri = (STRINGREF)getRawURI.Call_RetOBJECTREF(getRawURIArgs); - - DWORD cchRawUri = gc.refRawUri->GetStringLength(); - LPCWSTR wszRawUri = gc.refRawUri->GetBuffer(); - - { - GCX_PREEMP(); - pUnk = CreateWinRTUri(wszRawUri, static_cast(cchRawUri)); - } - - GCPROTECT_END(); - } - else if (redirectedTypeIndex == WinMDAdapter::RedirectedTypeIndex_System_Collections_Specialized_NotifyCollectionChangedEventArgs || - redirectedTypeIndex == WinMDAdapter::RedirectedTypeIndex_System_ComponentModel_PropertyChangedEventArgs) - { - MethodDesc *pMD; - EventArgsMarshalingInfo *pInfo = GetAppDomain()->GetLoaderAllocator()->GetMarshalingData()->GetEventArgsMarshalingInfo(); - - if (redirectedTypeIndex == WinMDAdapter::RedirectedTypeIndex_System_Collections_Specialized_NotifyCollectionChangedEventArgs) - pMD = pInfo->GetSystemNCCEventArgsToWinRTNCCEventArgsMD(); - else - pMD = pInfo->GetSystemPCEventArgsToWinRTPCEventArgsMD(); - - MethodDescCallSite marshalMethod(pMD); - ARG_SLOT methodArgs[] = - { - ObjToArgSlot(*poref) - }; - pUnk = (IUnknown *)marshalMethod.Call_RetLPVOID(methodArgs); - } - else - { - _ASSERTE(!W("Unexpected redirected type seen in GetComIPFromObjectRef")); - } - } - else - { - // - // WinRT reference type - marshal as IInspectable - // - pUnk = ComCallWrapper::GetComIPFromCCW(pCCWHold, IID_IInspectable, /* pIntfMT = */ NULL); - } - } - else - { - // - // Marshal non-WinRT types as IInspectable* to enable round-tripping (for example, TextBox.Tag property) - // By default, this returns ICustomPropertyProvider; - // - pUnk = ComCallWrapper::GetComIPFromCCW(pCCWHold, IID_IInspectable, /* pIntfMT = */ NULL); - } - - if (pUnk) - FetchedIpType = ComIpType_Inspectable; - } - // If the ObjectRef doesn't support IDispatch and the caller also accepts // an IUnknown pointer, then check for IUnknown. if (!pUnk && (ReqIpType & ComIpType_Unknown)) @@ -403,7 +246,7 @@ IUnknown *GetComIPFromObjectRef(OBJECTREF *poref, ComIpType ReqIpType, ComIpType RCWHolder pRCW(GetThread()); // This code is hot, use a simple RCWHolder check (i.e. don't increment the use count on the RCW). - // @TODO: Cache IInspectable & IDispatch so we don't have to QI every time we come here. + // @TODO: Cache IDispatch so we don't have to QI every time we come here. pRCW.InitFastCheck(pBlock); // If the user requested IDispatch, then check for IDispatch first. @@ -414,13 +257,6 @@ IUnknown *GetComIPFromObjectRef(OBJECTREF *poref, ComIpType ReqIpType, ComIpType FetchedIpType = ComIpType_Dispatch; } - if (ReqIpType & ComIpType_Inspectable) - { - pUnk = pRCW->GetIInspectable(); - if (pUnk) - FetchedIpType = ComIpType_Inspectable; - } - // If the ObjectRef doesn't support IDispatch and the caller also accepts // an IUnknown pointer, then check for IUnknown. if (!pUnk && (ReqIpType & ComIpType_Unknown)) @@ -583,46 +419,14 @@ void GetObjectRefFromComIP(OBJECTREF* pObjOut, IUnknown **ppUnk, MethodTable *pM *pObjOut = ccw->GetObjectRef(); } - if (*pObjOut != NULL) - { - if (!(dwFlags & ObjFromComIP::IGNORE_WINRT_AND_SKIP_UNBOXING)) - { - // Unbox objects from a CLRIReferenceImpl or CLRIReferenceArrayImpl. - MethodTable *pMT = (*pObjOut)->GetMethodTable(); - if (pMT->HasInstantiation()) - { - DWORD nGenericArgs = pMT->GetNumGenericArgs(); - if (nGenericArgs == 1) - { - // See if this type C is a G. - if (pMT->HasSameTypeDefAs(MscorlibBinder::GetClass(CLASS__CLRIREFERENCEIMPL))) - { - TypeHandle thType = pMT->GetInstantiation()[0]; - COMInterfaceMarshaler::IReferenceOrIReferenceArrayUnboxWorker(*pObjOut, thType, FALSE, pObjOut); - } - else if (pMT->HasSameTypeDefAs(MscorlibBinder::GetClass(CLASS__CLRIREFERENCEARRAYIMPL))) - { - TypeHandle thArrayElementType = pMT->GetInstantiation()[0]; - COMInterfaceMarshaler::IReferenceOrIReferenceArrayUnboxWorker(*pObjOut, thArrayElementType, TRUE, pObjOut); - } - } - else if ((nGenericArgs == 2) && pMT->HasSameTypeDefAs(MscorlibBinder::GetClass(CLASS__CLRIKEYVALUEPAIRIMPL))) - { - // Unbox IKeyValuePair from CLRIKeyValuePairImpl - COMInterfaceMarshaler::IKeyValuePairUnboxWorker(*pObjOut, pObjOut); - } - } - } - } - else + if (*pObjOut == NULL) { // Only pass in the class method table to the interface marshaler if - // it is a COM import (or COM import derived) class or a WinRT delegate. + // it is a COM import (or COM import derived) class. MethodTable *pComClassMT = NULL; if (pMTClass) { - if (pMTClass->IsComObjectType() || - (pMTClass->IsDelegate() && (pMTClass->IsProjectedFromWinRT() || WinRTTypeNameConverter::IsRedirectedType(pMTClass)))) + if (pMTClass->IsComObjectType()) { pComClassMT = pMTClass; } @@ -634,17 +438,7 @@ void GetObjectRefFromComIP(OBJECTREF* pObjOut, IUnknown **ppUnk, MethodTable *pM COMInterfaceMarshaler marshaler; marshaler.Init(pOuter, pComClassMT, pThread, flags); - - if (flags & ObjFromComIP::SUPPRESS_ADDREF) - { - // We can swallow the reference in ppUnk - // This only happens in WinRT - *pObjOut = marshaler.FindOrCreateObjectRef(ppUnk, pItfMT); - } - else - { - *pObjOut = marshaler.FindOrCreateObjectRef(pUnk, pItfMT); - } + *pObjOut = marshaler.FindOrCreateObjectRef(pUnk, pItfMT); } } @@ -656,22 +450,6 @@ void GetObjectRefFromComIP(OBJECTREF* pObjOut, IUnknown **ppUnk, MethodTable *pM { EnsureObjectRefIsValidForSpecifiedClass(pObjOut, dwFlags, pMTClass); } - else if (dwFlags & ObjFromComIP::REQUIRE_IINSPECTABLE) - { - MethodTable *pMT = (*pObjOut)->GetMethodTable(); - if (pMT->IsDelegate() && pMT->IsProjectedFromWinRT()) - { - // This is a WinRT delegate - WinRT delegate doesn't implement IInspectable but we allow unboxing a WinRT delegate - // from a IReference - } - else - { - // Just call GetComIPFromObjectRef. We could be more efficient here but the code would get complicated - // which doesn't seem to be worth it. The function throws an exception if the QI/cast fails. - SafeComHolder pInsp = GetComIPFromObjectRef(pObjOut, ComIpType_Inspectable, NULL); - _ASSERTE(pInsp != NULL); - } - } } } #endif // FEATURE_COMINTEROP diff --git a/src/coreclr/src/vm/interopconverter.h b/src/coreclr/src/vm/interopconverter.h index a41c169..eca3f91 100644 --- a/src/coreclr/src/vm/interopconverter.h +++ b/src/coreclr/src/vm/interopconverter.h @@ -13,12 +13,12 @@ struct ItfMarshalInfo { enum ItfMarshalFlags { - ITF_MARSHAL_INSP_ITF = 0x01, // IInspectable-based interface - ITF_MARSHAL_SUPPRESS_ADDREF = 0x02, + // unused = 0x01, + // unused = 0x02, ITF_MARSHAL_CLASS_IS_HINT = 0x04, ITF_MARSHAL_DISP_ITF = 0x08, ITF_MARSHAL_USE_BASIC_ITF = 0x10, - ITF_MARSHAL_WINRT_SCENARIO = 0x20, // WinRT scenario only + // unused = 0x20, }; TypeHandle thClass; @@ -31,25 +31,20 @@ struct ItfMarshalInfo enum CreationFlags // member of RCW struct { CF_None = 0x00, - CF_SupportsIInspectable = 0x01, // the underlying object supports IInspectable - CF_SuppressAddRef = 0x02, // do not AddRef the underlying interface pointer - CF_IsWeakReference = 0x04, // mark the RCW as "weak" + // unused = 0x01, + // unused = 0x02, + // unused = 0x04, CF_NeedUniqueObject = 0x08, // always create a new RCW/object even if we have one cached already - CF_DontResolveClass = 0x10, // don't attempt to create a strongly typed RCW + // unused = 0x10, }; */ /* -01 REQUIRE_IINSPECTABLE 01 ITF_MARSHAL_INSP_ITF 01 CF_SupportsIInspectable -02 SUPPRESS_ADDREF 02 ITF_MARSHAL_SUPPRESS_ADDREF - 04 CF_IsWeakReference 04 CLASS_IS_HINT 04 ITF_MARSHAL_CLASS_IS_HINT 08 UNIQUE_OBJECT 08 CF_NeedUniqueObject 08 ITF_MARSHAL_DISP_ITF -10 IGNORE_WINRT_AND_SKIP_UNBOXING 10 CF_DontResolveClass 10 ITF_MARSHAL_USE_BASIC_ITF - 20 ITF_MARSHAL_WINRT_SCENARIO */ struct ObjFromComIP @@ -57,23 +52,19 @@ struct ObjFromComIP enum flags { NONE = 0x00, - REQUIRE_IINSPECTABLE = 0x01, // ITF_MARSHAL_INSP_ITF = 0x01 // CF_SupportsIInspectable = 0x01 - SUPPRESS_ADDREF = 0x02, // ITF_MARSHAL_SUPPRESS_ADDREF = 0x02 // CF_SuppressAddRef = 0x02 + // unused = 0x01, + // unused = 0x02, CLASS_IS_HINT = 0x04, // ITF_MARSHAL_CLASS_IS_HINT = 0x04 UNIQUE_OBJECT = 0x08, // CF_NeedUniqueObject = 0x04 - IGNORE_WINRT_AND_SKIP_UNBOXING = 0x10, // CF_DontResolveClass = 0x10 + // unused = 0x10, }; static flags FromItfMarshalInfoFlags(DWORD dwFlags) { static_assert_no_msg(((DWORD)CLASS_IS_HINT) == ((DWORD)ItfMarshalInfo::ITF_MARSHAL_CLASS_IS_HINT)); - static_assert_no_msg(((DWORD)REQUIRE_IINSPECTABLE) == ((DWORD)ItfMarshalInfo::ITF_MARSHAL_INSP_ITF)); - static_assert_no_msg(((DWORD)SUPPRESS_ADDREF) == ((DWORD)ItfMarshalInfo::ITF_MARSHAL_SUPPRESS_ADDREF)); DWORD dwResult = (dwFlags & - (ItfMarshalInfo::ITF_MARSHAL_CLASS_IS_HINT| - ItfMarshalInfo::ITF_MARSHAL_INSP_ITF| - ItfMarshalInfo::ITF_MARSHAL_SUPPRESS_ADDREF)); + (ItfMarshalInfo::ITF_MARSHAL_CLASS_IS_HINT)); return (flags)dwResult; } }; @@ -106,7 +97,6 @@ enum ComIpType ComIpType_Dispatch = 0x2, ComIpType_Both = 0x3, ComIpType_OuterUnknown = 0x5, - ComIpType_Inspectable = 0x8, }; diff --git a/src/coreclr/src/vm/interoplibinterface.cpp b/src/coreclr/src/vm/interoplibinterface.cpp index 9040e817..a17bf75 100644 --- a/src/coreclr/src/vm/interoplibinterface.cpp +++ b/src/coreclr/src/vm/interoplibinterface.cpp @@ -5,7 +5,6 @@ // Runtime headers #include "common.h" #include "rcwrefcache.h" -#include "rcwwalker.h" #include "olecontexthelpers.h" #include "finalizerthread.h" @@ -802,6 +801,11 @@ namespace } } +namespace +{ + BOOL g_isGlobalPeggingOn = TRUE; +} + namespace InteropLibImports { void* MemAlloc(_In_ size_t sizeInBytes, _In_ AllocScenario scenario) noexcept @@ -981,7 +985,7 @@ namespace InteropLibImports } CONTRACTL_END; - return (RCWWalker::s_bIsGlobalPeggingOn != FALSE); + return (VolatileLoad(&g_isGlobalPeggingOn) != FALSE); } void SetGlobalPeggingState(_In_ bool state) noexcept @@ -995,7 +999,7 @@ namespace InteropLibImports CONTRACTL_END; BOOL newState = state ? TRUE : FALSE; - VolatileStore(&RCWWalker::s_bIsGlobalPeggingOn, newState); + VolatileStore(&g_isGlobalPeggingOn, newState); } HRESULT GetOrCreateTrackerTargetForExternal( @@ -1566,20 +1570,6 @@ void Interop::OnGCStarted(_In_ int nCondemnedGeneration) } CONTRACTL_END; -#ifdef FEATURE_COMINTEROP - // - // Let GC detect managed/native cycles with input from jupiter - // Jupiter will - // 1. Report reference from RCW to CCW based on native reference in Jupiter - // 2. Identify the subset of CCWs that needs to be rooted - // - // We'll build the references from RCW to CCW using - // 1. Preallocated arrays - // 2. Dependent handles - // - RCWWalker::OnGCStarted(nCondemnedGeneration); -#endif // FEATURE_COMINTEROP - #ifdef FEATURE_COMWRAPPERS // // Note that we could get nested GCStart/GCEnd calls, such as : @@ -1624,13 +1614,6 @@ void Interop::OnGCFinished(_In_ int nCondemnedGeneration) } CONTRACTL_END; -#ifdef FEATURE_COMINTEROP - // - // Tell Jupiter GC has finished - // - RCWWalker::OnGCFinished(nCondemnedGeneration); -#endif // FEATURE_COMINTEROP - #ifdef FEATURE_COMWRAPPERS // // Note that we could get nested GCStart/GCEnd calls, such as : diff --git a/src/coreclr/src/vm/interoputil.cpp b/src/coreclr/src/vm/interoputil.cpp index 4d705a5..33cad06 100644 --- a/src/coreclr/src/vm/interoputil.cpp +++ b/src/coreclr/src/vm/interoputil.cpp @@ -47,313 +47,13 @@ #include "stdinterfaces.h" #include "notifyexternals.h" #include "typeparse.h" -#include "..\md\winmd\inc\adapter.h" -#include "winrttypenameconverter.h" #include "interoputil.inl" #include "typestring.h" -#ifndef __ILanguageExceptionErrorInfo_INTERFACE_DEFINED__ -#define __ILanguageExceptionErrorInfo_INTERFACE_DEFINED__ - EXTERN_C const IID IID_ILanguageExceptionErrorInfo; - - MIDL_INTERFACE("04a2dbf3-df83-116c-0946-0812abf6e07d") - ILanguageExceptionErrorInfo : public IUnknown - { - public: - virtual HRESULT STDMETHODCALLTYPE GetLanguageException( - /* [out] */ __RPC__deref_out_opt IUnknown **languageException) = 0; - - }; -#endif // !__ILanguageExceptionErrorInfo_INTERFACE_DEFINED__ - #define STANDARD_DISPID_PREFIX W("[DISPID") #define STANDARD_DISPID_PREFIX_LENGTH 7 #define GET_ENUMERATOR_METHOD_NAME W("GetEnumerator") -// Note: All of the methods below must appear in the order in which the interfaces are defined in IL. -// WinRT -> CLR adapters -static const BinderMethodID s_stubsIterableToEnumerable[] = -{ - METHOD__ITERABLE_TO_ENUMERABLE_ADAPTER__GET_ENUMERATOR_STUB -}; -static const BinderMethodID s_stubsVectorToList[] = -{ - METHOD__VECTOR_TO_LIST_ADAPTER__INDEXER_GET, - METHOD__VECTOR_TO_LIST_ADAPTER__INDEXER_SET, - METHOD__VECTOR_TO_LIST_ADAPTER__INDEX_OF, - METHOD__VECTOR_TO_LIST_ADAPTER__INSERT, - METHOD__VECTOR_TO_LIST_ADAPTER__REMOVE_AT -}; -static const BinderMethodID s_stubsVectorToCollection[] = -{ - METHOD__VECTOR_TO_COLLECTION_ADAPTER__COUNT, - METHOD__VECTOR_TO_COLLECTION_ADAPTER__IS_READ_ONLY, - METHOD__VECTOR_TO_COLLECTION_ADAPTER__ADD, - METHOD__VECTOR_TO_COLLECTION_ADAPTER__CLEAR, - METHOD__VECTOR_TO_COLLECTION_ADAPTER__CONTAINS, - METHOD__VECTOR_TO_COLLECTION_ADAPTER__COPY_TO, - METHOD__VECTOR_TO_COLLECTION_ADAPTER__REMOVE -}; -static const BinderMethodID s_stubsMapToDictionary[] = -{ - METHOD__MAP_TO_DICTIONARY_ADAPTER__INDEXER_GET, - METHOD__MAP_TO_DICTIONARY_ADAPTER__INDEXER_SET, - METHOD__MAP_TO_DICTIONARY_ADAPTER__KEYS, - METHOD__MAP_TO_DICTIONARY_ADAPTER__VALUES, - METHOD__MAP_TO_DICTIONARY_ADAPTER__CONTAINS_KEY, - METHOD__MAP_TO_DICTIONARY_ADAPTER__ADD, - METHOD__MAP_TO_DICTIONARY_ADAPTER__REMOVE, - METHOD__MAP_TO_DICTIONARY_ADAPTER__TRY_GET_VALUE -}; -static const BinderMethodID s_stubsMapToCollection[] = -{ - METHOD__MAP_TO_COLLECTION_ADAPTER__COUNT, - METHOD__MAP_TO_COLLECTION_ADAPTER__IS_READ_ONLY, - METHOD__MAP_TO_COLLECTION_ADAPTER__ADD, - METHOD__MAP_TO_COLLECTION_ADAPTER__CLEAR, - METHOD__MAP_TO_COLLECTION_ADAPTER__CONTAINS, - METHOD__MAP_TO_COLLECTION_ADAPTER__COPY_TO, - METHOD__MAP_TO_COLLECTION_ADAPTER__REMOVE -}; -static const BinderMethodID s_stubsIVectorViewToIReadOnlyCollection[] = -{ - METHOD__IVECTORVIEW_TO_IREADONLYCOLLECTION_ADAPTER__COUNT, -}; -static const BinderMethodID s_stubsIVectorViewToIReadOnlyList[] = -{ - METHOD__IVECTORVIEW_TO_IREADONLYLIST_ADAPTER__INDEXER_GET, -}; -static const BinderMethodID s_stubsIMapViewToIReadOnlyCollection[] = -{ - METHOD__IMAPVIEW_TO_IREADONLYCOLLECTION_ADAPTER__COUNT, -}; -static const BinderMethodID s_stubsIMapViewToIReadOnlyDictionary[] = -{ - METHOD__IMAPVIEW_TO_IREADONLYDICTIONARY_ADAPTER__CONTAINSKEY, - METHOD__IMAPVIEW_TO_IREADONLYDICTIONARY_ADAPTER__TRYGETVALUE, - METHOD__IMAPVIEW_TO_IREADONLYDICTIONARY_ADAPTER__INDEXER_GET, - METHOD__IMAPVIEW_TO_IREADONLYDICTIONARY_ADAPTER__KEYS, - METHOD__IMAPVIEW_TO_IREADONLYDICTIONARY_ADAPTER__VALUES -}; -static const BinderMethodID s_stubsBindableIterableToEnumerable[] = -{ - METHOD__BINDABLEITERABLE_TO_ENUMERABLE_ADAPTER__GET_ENUMERATOR_STUB -}; -static const BinderMethodID s_stubsBindableVectorToList[] = -{ - METHOD__BINDABLEVECTOR_TO_LIST_ADAPTER__INDEXER_GET, - METHOD__BINDABLEVECTOR_TO_LIST_ADAPTER__INDEXER_SET, - METHOD__BINDABLEVECTOR_TO_LIST_ADAPTER__ADD, - METHOD__BINDABLEVECTOR_TO_LIST_ADAPTER__CONTAINS, - METHOD__BINDABLEVECTOR_TO_LIST_ADAPTER__CLEAR, - METHOD__BINDABLEVECTOR_TO_LIST_ADAPTER__IS_READ_ONLY, - METHOD__BINDABLEVECTOR_TO_LIST_ADAPTER__IS_FIXED_SIZE, - METHOD__BINDABLEVECTOR_TO_LIST_ADAPTER__INDEX_OF, - METHOD__BINDABLEVECTOR_TO_LIST_ADAPTER__INSERT, - METHOD__BINDABLEVECTOR_TO_LIST_ADAPTER__REMOVE, - METHOD__BINDABLEVECTOR_TO_LIST_ADAPTER__REMOVE_AT -}; -static const BinderMethodID s_stubsBindableVectorToCollection[] = -{ - METHOD__BINDABLEVECTOR_TO_COLLECTION_ADAPTER__COPY_TO, - METHOD__BINDABLEVECTOR_TO_COLLECTION_ADAPTER__COUNT, - METHOD__BINDABLEVECTOR_TO_COLLECTION_ADAPTER__SYNC_ROOT, - METHOD__BINDABLEVECTOR_TO_COLLECTION_ADAPTER__IS_SYNCHRONIZED -}; -static const BinderMethodID s_stubsNotifyCollectionChangedToManaged[] = -{ - (BinderMethodID)0, // add_CollectionChanged - (BinderMethodID)1, // remove_CollectionChanged -}; -static const BinderMethodID s_stubsNotifyPropertyChangedToManaged[] = -{ - (BinderMethodID)0, // add_PropertyChanged - (BinderMethodID)1, // remove_PropertyChanged -}; -static const BinderMethodID s_stubsICommandToManaged[] = -{ - (BinderMethodID)0, // add_CanExecuteChanged - (BinderMethodID)1, // remove_CanExecuteChanged - (BinderMethodID)2, // CanExecute - (BinderMethodID)3, // Execute -}; - -static const BinderMethodID s_stubsClosableToDisposable[] = -{ - METHOD__ICLOSABLE_TO_IDISPOSABLE_ADAPTER__DISPOSE -}; - -// CLR -> WinRT adapters -static const BinderMethodID s_stubsEnumerableToIterable[] = -{ - METHOD__ENUMERABLE_TO_ITERABLE_ADAPTER__FIRST_STUB -}; -static const BinderMethodID s_stubsListToVector[] = -{ - METHOD__LIST_TO_VECTOR_ADAPTER__GET_AT, - METHOD__LIST_TO_VECTOR_ADAPTER__SIZE, - METHOD__LIST_TO_VECTOR_ADAPTER__GET_VIEW, - METHOD__LIST_TO_VECTOR_ADAPTER__INDEX_OF, - METHOD__LIST_TO_VECTOR_ADAPTER__SET_AT, - METHOD__LIST_TO_VECTOR_ADAPTER__INSERT_AT, - METHOD__LIST_TO_VECTOR_ADAPTER__REMOVE_AT, - METHOD__LIST_TO_VECTOR_ADAPTER__APPEND, - METHOD__LIST_TO_VECTOR_ADAPTER__REMOVE_AT_END, - METHOD__LIST_TO_VECTOR_ADAPTER__CLEAR, - METHOD__LIST_TO_VECTOR_ADAPTER__GET_MANY, - METHOD__LIST_TO_VECTOR_ADAPTER__REPLACE_ALL, -}; -static const BinderMethodID s_stubsDictionaryToMap[] = -{ - METHOD__DICTIONARY_TO_MAP_ADAPTER__LOOKUP, - METHOD__DICTIONARY_TO_MAP_ADAPTER__SIZE, - METHOD__DICTIONARY_TO_MAP_ADAPTER__HAS_KEY, - METHOD__DICTIONARY_TO_MAP_ADAPTER__GET_VIEW, - METHOD__DICTIONARY_TO_MAP_ADAPTER__INSERT, - METHOD__DICTIONARY_TO_MAP_ADAPTER__REMOVE, - METHOD__DICTIONARY_TO_MAP_ADAPTER__CLEAR, -}; -static const BinderMethodID s_stubsIReadOnlyListToIVectorView[] = -{ - METHOD__IREADONLYLIST_TO_IVECTORVIEW_ADAPTER__GETAT, - METHOD__IREADONLYLIST_TO_IVECTORVIEW_ADAPTER__SIZE, - METHOD__IREADONLYLIST_TO_IVECTORVIEW_ADAPTER__INDEXOF, - METHOD__IREADONLYLIST_TO_IVECTORVIEW_ADAPTER__GETMANY, -}; -static const BinderMethodID s_stubsIReadOnlyDictionaryToIMapView[] = -{ - METHOD__IREADONLYDICTIONARY_TO_IMAPVIEW_ADAPTER__LOOKUP, - METHOD__IREADONLYDICTIONARY_TO_IMAPVIEW_ADAPTER__SIZE, - METHOD__IREADONLYDICTIONARY_TO_IMAPVIEW_ADAPTER__HASKEY, - METHOD__IREADONLYDICTIONARY_TO_IMAPVIEW_ADAPTER__SPLIT, -}; -static const BinderMethodID s_stubsEnumerableToBindableIterable[] = -{ - METHOD__ENUMERABLE_TO_BINDABLEITERABLE_ADAPTER__FIRST_STUB -}; -static const BinderMethodID s_stubsListToBindableVector[] = -{ - METHOD__LIST_TO_BINDABLEVECTOR_ADAPTER__GET_AT, - METHOD__LIST_TO_BINDABLEVECTOR_ADAPTER__SIZE, - METHOD__LIST_TO_BINDABLEVECTOR_ADAPTER__GET_VIEW, - METHOD__LIST_TO_BINDABLEVECTOR_ADAPTER__INDEX_OF, - METHOD__LIST_TO_BINDABLEVECTOR_ADAPTER__SET_AT, - METHOD__LIST_TO_BINDABLEVECTOR_ADAPTER__INSERT_AT, - METHOD__LIST_TO_BINDABLEVECTOR_ADAPTER__REMOVE_AT, - METHOD__LIST_TO_BINDABLEVECTOR_ADAPTER__APPEND, - METHOD__LIST_TO_BINDABLEVECTOR_ADAPTER__REMOVE_AT_END, - METHOD__LIST_TO_BINDABLEVECTOR_ADAPTER__CLEAR -}; -static const BinderMethodID s_stubsNotifyCollectionChangedToWinRT[] = -{ - (BinderMethodID)0, // add_CollectionChanged - (BinderMethodID)1, // remove_CollectionChanged -}; -static const BinderMethodID s_stubsNotifyPropertyChangedToWinRT[] = -{ - (BinderMethodID)0, // add_PropertyChanged - (BinderMethodID)1, // remove_PropertyChanged -}; -static const BinderMethodID s_stubsICommandToWinRT[] = -{ - (BinderMethodID)0, // add_CanExecuteChanged - (BinderMethodID)1, // remove_CanExecuteChanged - (BinderMethodID)2, // CanExecute - (BinderMethodID)3, // Execute -}; - - -static const LPCUTF8 s_stubNamesNotifyCollectionChanged[] = -{ - "add_CollectionChanged", // 0 - "remove_CollectionChanged", // 1 -}; - -static const LPCUTF8 s_stubNamesNotifyPropertyChanged[] = -{ - "add_PropertyChanged", // 0 - "remove_PropertyChanged", // 1 -}; - -static const LPCUTF8 s_stubNamesICommand[] = -{ - "add_CanExecuteChanged", // 0 - "remove_CanExecuteChanged", // 1 - "CanExecute", // 2 - "Execute", // 3 -}; - -static const BinderMethodID s_stubsDisposableToClosable[] = -{ - METHOD__IDISPOSABLE_TO_ICLOSABLE_ADAPTER__CLOSE -}; - -DEFINE_ASM_QUAL_TYPE_NAME(NCCWINRT_ASM_QUAL_TYPE_NAME, g_INotifyCollectionChanged_WinRTName, g_SystemRuntimeWindowsRuntimeAsmName); -DEFINE_ASM_QUAL_TYPE_NAME(NCCMA_ASM_QUAL_TYPE_NAME, g_NotifyCollectionChangedToManagedAdapterName, g_SystemRuntimeWindowsRuntimeAsmName); -DEFINE_ASM_QUAL_TYPE_NAME(NCCWA_ASM_QUAL_TYPE_NAME, g_NotifyCollectionChangedToWinRTAdapterName, g_SystemRuntimeWindowsRuntimeAsmName); -DEFINE_ASM_QUAL_TYPE_NAME(NPCWINRT_ASM_QUAL_TYPE_NAME, g_INotifyPropertyChanged_WinRTName, g_SystemRuntimeWindowsRuntimeAsmName); -DEFINE_ASM_QUAL_TYPE_NAME(NPCMA_ASM_QUAL_TYPE_NAME, g_NotifyPropertyChangedToManagedAdapterName, g_SystemRuntimeWindowsRuntimeAsmName); -DEFINE_ASM_QUAL_TYPE_NAME(NPCWA_ASM_QUAL_TYPE_NAME, g_NotifyPropertyChangedToWinRTAdapterName, g_SystemRuntimeWindowsRuntimeAsmName); -DEFINE_ASM_QUAL_TYPE_NAME(CMDWINRT_ASM_QUAL_TYPE_NAME, g_ICommand_WinRTName, g_SystemRuntimeWindowsRuntimeAsmName); -DEFINE_ASM_QUAL_TYPE_NAME(CMDMA_ASM_QUAL_TYPE_NAME, g_ICommandToManagedAdapterName, g_SystemRuntimeWindowsRuntimeAsmName); -DEFINE_ASM_QUAL_TYPE_NAME(CMDWA_ASM_QUAL_TYPE_NAME, g_ICommandToWinRTAdapterName, g_SystemRuntimeWindowsRuntimeAsmName); -DEFINE_ASM_QUAL_TYPE_NAME(NCCEHWINRT_ASM_QUAL_TYPE_NAME, g_NotifyCollectionChangedEventHandler_WinRT, g_SystemRuntimeWindowsRuntimeAsmName); -DEFINE_ASM_QUAL_TYPE_NAME(PCEHWINRT_ASM_QUAL_TYPE_NAME, g_PropertyChangedEventHandler_WinRT_Name, g_SystemRuntimeWindowsRuntimeAsmName); - -const WinRTInterfaceRedirector::NonMscorlibRedirectedInterfaceInfo WinRTInterfaceRedirector::s_rNonMscorlibInterfaceInfos[3] = -{ - { - NCCWINRT_ASM_QUAL_TYPE_NAME, - NCCMA_ASM_QUAL_TYPE_NAME, - NCCWA_ASM_QUAL_TYPE_NAME, - s_stubNamesNotifyCollectionChanged - }, - { - NPCWINRT_ASM_QUAL_TYPE_NAME, - NPCMA_ASM_QUAL_TYPE_NAME, - NPCWA_ASM_QUAL_TYPE_NAME, - s_stubNamesNotifyPropertyChanged - }, - { - CMDWINRT_ASM_QUAL_TYPE_NAME, - CMDMA_ASM_QUAL_TYPE_NAME, - CMDWA_ASM_QUAL_TYPE_NAME, - s_stubNamesICommand - }, -}; - -#define SYSTEMDLL__INOTIFYCOLLECTIONCHANGED ((BinderClassID)(WinRTInterfaceRedirector::NON_MSCORLIB_MARKER | 0)) -#define SYSTEMDLL__INOTIFYPROPERTYCHANGED ((BinderClassID)(WinRTInterfaceRedirector::NON_MSCORLIB_MARKER | 1)) -#define SYSTEMDLL__ICOMMAND ((BinderClassID)(WinRTInterfaceRedirector::NON_MSCORLIB_MARKER | 2)) - -const WinRTInterfaceRedirector::RedirectedInterfaceStubInfo WinRTInterfaceRedirector::s_rInterfaceStubInfos[2 * s_NumRedirectedInterfaces] = -{ - { CLASS__IITERABLE, _countof(s_stubsIterableToEnumerable), s_stubsIterableToEnumerable, _countof(s_stubsEnumerableToIterable), s_stubsEnumerableToIterable }, - { CLASS__IVECTOR, _countof(s_stubsVectorToList), s_stubsVectorToList, _countof(s_stubsListToVector), s_stubsListToVector }, - { CLASS__IMAP, _countof(s_stubsMapToDictionary), s_stubsMapToDictionary, _countof(s_stubsDictionaryToMap), s_stubsDictionaryToMap }, - { CLASS__IVECTORVIEW, _countof(s_stubsIVectorViewToIReadOnlyList), s_stubsIVectorViewToIReadOnlyList, _countof(s_stubsIReadOnlyListToIVectorView), s_stubsIReadOnlyListToIVectorView }, - { CLASS__IMAPVIEW, _countof(s_stubsIMapViewToIReadOnlyDictionary), s_stubsIMapViewToIReadOnlyDictionary, _countof(s_stubsIReadOnlyDictionaryToIMapView), s_stubsIReadOnlyDictionaryToIMapView }, - { CLASS__IBINDABLEITERABLE, _countof(s_stubsBindableIterableToEnumerable), s_stubsBindableIterableToEnumerable, _countof(s_stubsEnumerableToBindableIterable), s_stubsEnumerableToBindableIterable }, - { CLASS__IBINDABLEVECTOR, _countof(s_stubsBindableVectorToList), s_stubsBindableVectorToList, _countof(s_stubsListToBindableVector), s_stubsListToBindableVector }, - { SYSTEMDLL__INOTIFYCOLLECTIONCHANGED, _countof(s_stubsNotifyCollectionChangedToManaged), s_stubsNotifyCollectionChangedToManaged, _countof(s_stubsNotifyCollectionChangedToWinRT), s_stubsNotifyCollectionChangedToWinRT }, - { SYSTEMDLL__INOTIFYPROPERTYCHANGED, _countof(s_stubsNotifyPropertyChangedToManaged), s_stubsNotifyPropertyChangedToManaged, _countof(s_stubsNotifyPropertyChangedToWinRT), s_stubsNotifyPropertyChangedToWinRT }, - { SYSTEMDLL__ICOMMAND, _countof(s_stubsICommandToManaged), s_stubsICommandToManaged, _countof(s_stubsICommandToWinRT), s_stubsICommandToWinRT }, - { CLASS__ICLOSABLE, _countof(s_stubsClosableToDisposable), s_stubsClosableToDisposable, _countof(s_stubsClosableToDisposable), s_stubsDisposableToClosable }, - - // ICollection/ICollection<> stubs: - { (BinderClassID)0, 0, NULL, 0, NULL }, - { CLASS__IVECTOR, _countof(s_stubsVectorToCollection), s_stubsVectorToCollection, 0, NULL }, - { CLASS__IMAP, _countof(s_stubsMapToCollection), s_stubsMapToCollection, 0, NULL }, - { CLASS__IVECTORVIEW, _countof(s_stubsIVectorViewToIReadOnlyCollection), s_stubsIVectorViewToIReadOnlyCollection, 0, NULL }, - { CLASS__IMAPVIEW, _countof(s_stubsIMapViewToIReadOnlyCollection), s_stubsIMapViewToIReadOnlyCollection, 0, NULL }, - { (BinderClassID)0, 0, NULL, 0, NULL }, - { CLASS__IBINDABLEVECTOR, _countof(s_stubsBindableVectorToCollection), s_stubsBindableVectorToCollection, 0, NULL }, - { (BinderClassID)0, 0, NULL, 0, NULL }, - { (BinderClassID)0, 0, NULL, 0, NULL }, - { (BinderClassID)0, 0, NULL, 0, NULL }, - { (BinderClassID)0, 0, NULL, 0, NULL }, -}; - #ifdef _DEBUG VOID IntializeInteropLogging(); #endif @@ -379,277 +79,6 @@ void AllocateComClassObject(ComClassFactory* pComClsFac, OBJECTREF* pComObj); // setup error info for exception object // #ifdef FEATURE_COMINTEROP -HRESULT SetupErrorInfo(OBJECTREF pThrownObject, ComCallMethodDesc *pCMD) -{ - CONTRACTL - { - NOTHROW; - GC_TRIGGERS; - MODE_COOPERATIVE; - PRECONDITION(CheckPointer(pCMD)); - } - CONTRACTL_END; - - return SetupErrorInfo(pThrownObject, pCMD->IsWinRTCall()); -} - -typedef BOOL (*pfnRoOriginateLanguageException)(HRESULT error, - HSTRING message, - IUnknown* languageException); -typedef HRESULT (*pfnGetRestrictedErrorInfo)(IRestrictedErrorInfo ** ppRestrictedErrorInfo); -typedef HRESULT (*pfnSetRestrictedErrorInfo)(IRestrictedErrorInfo * pRestrictedErrorInfo); - -pfnRoOriginateLanguageException g_pfnRoOriginateLanguageException = nullptr; -pfnGetRestrictedErrorInfo g_pfnGetRestrictedErrorInfo = nullptr; -pfnSetRestrictedErrorInfo g_pfnSetRestrictedErrorInfo = nullptr; - -Volatile g_bCheckedWinRTErrorDllPresent = false; - -//-------------------------------------------------------------------------------- -// Attempts to load WinRT error API functions from the appropriate system library, -// and populates g_pfnRoOriginateLanguageException, g_pfnGetRestrictedErrorInfo, -// and g_pfnSetRestrictedErrorInfo. -// -// This is shared logic for loading the WinRT error libraries that should not be -// called directly. -void LoadProcAddressForWinRTErrorAPIs_Internal() -{ - WRAPPER_NO_CONTRACT; - - GCX_PREEMP(); - - if (!g_bCheckedWinRTErrorDllPresent) - { - HMODULE hModWinRTError11Dll = WszLoadLibraryEx(W("api-ms-win-core-winrt-error-l1-1-1.dll"), NULL, LOAD_LIBRARY_SEARCH_SYSTEM32); - - // We never release the library since we can only do it at AppDomain shutdown and there is no good way to release it then. - if (hModWinRTError11Dll) - { - g_pfnRoOriginateLanguageException = (pfnRoOriginateLanguageException)GetProcAddress(hModWinRTError11Dll, "RoOriginateLanguageException"); - g_pfnSetRestrictedErrorInfo = (pfnSetRestrictedErrorInfo)GetProcAddress(hModWinRTError11Dll, "SetRestrictedErrorInfo"); - g_pfnGetRestrictedErrorInfo = (pfnGetRestrictedErrorInfo)GetProcAddress(hModWinRTError11Dll, "GetRestrictedErrorInfo"); - } - else - { - // Downlevel versions of WinRT that do not have the language-projected exceptions will still have - // APIs for IRestrictedErrorInfo, so we should still try to load those. - HMODULE hModWinRTError10Dll = WszLoadLibraryEx(L"api-ms-win-core-winrt-error-l1-1-0.dll", NULL, LOAD_LIBRARY_SEARCH_SYSTEM32); - - if (hModWinRTError10Dll) - { - g_pfnSetRestrictedErrorInfo = (pfnSetRestrictedErrorInfo)GetProcAddress(hModWinRTError10Dll, "SetRestrictedErrorInfo"); - g_pfnGetRestrictedErrorInfo = (pfnGetRestrictedErrorInfo)GetProcAddress(hModWinRTError10Dll, "GetRestrictedErrorInfo"); - } - } - - g_bCheckedWinRTErrorDllPresent = true; - } -} - -//-------------------------------------------------------------------------------- -// Attempts to load the IRestrictedErrorInfo APIs into the function pointers -// g_pfnGetRestrictedErrorInfo and g_pfnSetRestrictedErrorInfo. This is used for -// WinRT scenarios where we don't care about support for language-projected exception -// support. Returns S_OK if both of these functions could be loaded, and E_FAIL -// otherwise. -HRESULT LoadProcAddressForRestrictedErrorInfoAPIs() -{ - WRAPPER_NO_CONTRACT; - - LoadProcAddressForWinRTErrorAPIs_Internal(); - - if (g_pfnSetRestrictedErrorInfo != NULL && g_pfnGetRestrictedErrorInfo != NULL) - return S_OK; - else - return E_FAIL; -} - -//-------------------------------------------------------------------------------- -// Attempts to load the RoOriginateLanguageException API for language-projected -// exceptions into the function pointer g_pfnRoOriginateLanguageException. Returns -// S_OK if this function could be loaded, and E_FAIL otherwise. -HRESULT LoadProcAddressForRoOriginateLanguageExceptionAPI() -{ - WRAPPER_NO_CONTRACT; - - LoadProcAddressForWinRTErrorAPIs_Internal(); - - if (g_pfnRoOriginateLanguageException != NULL) - return S_OK; - else - return E_FAIL; -} - -//-------------------------------------------------------------------------------- -// GetRestrictedErrorInfo helper, enables and disables GC during call-outs -HRESULT SafeGetRestrictedErrorInfo(IRestrictedErrorInfo **ppIRestrictedErrInfo) -{ - CONTRACTL - { - NOTHROW; - GC_TRIGGERS; - MODE_ANY; - PRECONDITION(CheckPointer(ppIRestrictedErrInfo)); - } - CONTRACTL_END; - - *ppIRestrictedErrInfo = NULL; - HRESULT hr = S_OK; - - if(SUCCEEDED(LoadProcAddressForRestrictedErrorInfoAPIs())) - { - GCX_PREEMP(); - - EX_TRY - { - hr = (*g_pfnGetRestrictedErrorInfo)(ppIRestrictedErrInfo); - } - EX_CATCH - { - hr = E_OUTOFMEMORY; - } - EX_END_CATCH(SwallowAllExceptions); - } - - return hr; -} - -// This method checks whether the given IErrorInfo is actually a managed CLR object. -BOOL IsManagedObject(IUnknown *pIUnknown) -{ - CONTRACTL - { - THROWS; - GC_TRIGGERS; - MODE_ANY; - INJECT_FAULT(COMPlusThrowOM()); - PRECONDITION(CheckPointer(pIUnknown)); - } - CONTRACTL_END; - - //Check based on IUnknown slots, i.e. we'll see whether the IP maps to a CCW. - if (MapIUnknownToWrapper(pIUnknown) != NULL) - { - // We found an existing CCW hence this is a managed exception. - return TRUE; - } - return FALSE; -} - -// This method returns the IErrorInfo associated with the IRestrictedErrorInfo. -// Return Value - a. IErrorInfo which corresponds to a managed exception object, where *bHasNonCLRLanguageErrorObject = FALSE -// b. IErrorInfo corresponding to a non-CLR exception object , where *bHasNonCLRLanguageErrorObject = TRUE -// c. NULL in case the current hr value is different from the one associated with IRestrictedErrorInfo. -IErrorInfo *GetCorrepondingErrorInfo_WinRT(HRESULT hr, IRestrictedErrorInfo *pResErrInfo, BOOL* bHasNonCLRLanguageErrorObject) -{ - CONTRACTL - { - THROWS; - GC_TRIGGERS; - MODE_ANY; - INJECT_FAULT(COMPlusThrowOM()); - PRECONDITION(CheckPointer(pResErrInfo)); - } - CONTRACTL_END; - - *bHasNonCLRLanguageErrorObject = FALSE; - // This function must run in preemptive GC mode. - { - GCX_PREEMP(); - HRESULT hrLocal = S_OK; - - SafeComHolderPreemp pLangException; - - // 1. Check whether the given IRestrictedErrorInfo supports ILanguageExceptionErrorInfo - // 2. If so, retrieve the language specific IInspectable by calling GetLanguageException. - // 3. Check whether the IInspectable is CLR specific. - // 4. If so, return the IInspectable as it is also the IErrorInfo. - // 5. If not, check whether the HResult returned by the API is same as the one stored in IRestrictedErrorInfo. - // 6. If so simply QI for IErrorInfo - // 7. If QI succeeds return IErrorInfo else return NULL. - - hrLocal = SafeQueryInterfacePreemp(pResErrInfo, IID_ILanguageExceptionErrorInfo, (IUnknown **) &pLangException); - LogInteropQI(pResErrInfo, IID_ILanguageExceptionErrorInfo, hr, "ILanguageExceptionErrorInfo"); - if (SUCCEEDED(hrLocal)) - { - IUnknown* pUnk; - if(pLangException != NULL && SUCCEEDED(pLangException->GetLanguageException((IUnknown**) &pUnk)) && pUnk != NULL) - { - if(IsManagedObject(pUnk)) - { - // Since this represent a managed CCW, this is our exception object and will always be an IErrorInfo. - // Hence type casting to IErrorInfo is safe. - return (IErrorInfo*)pUnk; - } - else - { - // pUnk represents an exception object of a different language. - // We simply need to store that the exception object represents a non-CLR exception and can release the actual exception object. - SafeReleasePreemp(pUnk); - *bHasNonCLRLanguageErrorObject = TRUE; - } - } - } - if(SUCCEEDED(GetRestrictedErrorDetails(pResErrInfo, NULL, NULL, &hrLocal, NULL))) - { - if(hr == hrLocal) - { - IErrorInfo *pErrInfo = NULL ; - hrLocal = SafeQueryInterfacePreemp(pResErrInfo, IID_IErrorInfo, (IUnknown **) &pErrInfo); - LogInteropQI(pResErrInfo, IID_IErrorInfo, hrLocal, "IErrorInfo"); - if(SUCCEEDED(hrLocal)) - { - return pErrInfo; - } - } - } - } - - return NULL; -} - -HRESULT GetRestrictedErrorDetails(IRestrictedErrorInfo *pRestrictedErrorInfo, BSTR *perrorDescription, BSTR *pErrorRestrictedDescription, HRESULT *pHr, BSTR *pErrorCapabilitySid) -{ - CONTRACTL - { - NOTHROW; - GC_TRIGGERS; - MODE_ANY; - PRECONDITION(CheckPointer(pRestrictedErrorInfo)); - } - CONTRACTL_END; - - GCX_PREEMP(); - - BSTR errDesc; - BSTR errResDesc; - BSTR errCapSid; - HRESULT hrLocal; - - if(SUCCEEDED(pRestrictedErrorInfo->GetErrorDetails(&errDesc, &hrLocal, &errResDesc, &errCapSid))) - { - if(perrorDescription) - *perrorDescription = errDesc; - else - ::SysFreeString(errDesc); - - if(pErrorRestrictedDescription) - *pErrorRestrictedDescription = errResDesc; - else - ::SysFreeString(errResDesc); - - if(pErrorCapabilitySid) - *pErrorCapabilitySid = errCapSid; - else - ::SysFreeString(errCapSid); - if(pHr) - *pHr = hrLocal; - - return S_OK; - } - - return E_FAIL; -} // HRESULT for CLR created IErrorInfo pointers are accessible // from the enclosing simple wrapper @@ -672,7 +101,7 @@ HRESULT GetHRFromCLRErrorInfo(IErrorInfo* pErr) } #endif // FEATURE_COMINTEROP -HRESULT SetupErrorInfo(OBJECTREF pThrownObject, BOOL bIsWinRTScenario /* = FALSE */) +HRESULT SetupErrorInfo(OBJECTREF pThrownObject) { CONTRACTL { @@ -730,69 +159,11 @@ HRESULT SetupErrorInfo(OBJECTREF pThrownObject, BOOL bIsWinRTScenario /* = FALSE IErrorInfo* pErr = NULL; EX_TRY { - // This handles a special case for a newer subset of WinRT scenarios, starting in Windows - // 8.1, where we have support for language-projected extensions. In this case, we can use - // the thrown object to set up a projected IErrorInfo that we'll send back to native code. - // - // In all other scenarios (including WinRT prior to Windows 8.1), we just use the legacy - // IErrorInfo COM APIs. - if (bIsWinRTScenario && - SUCCEEDED(LoadProcAddressForRestrictedErrorInfoAPIs()) && - SUCCEEDED(LoadProcAddressForRoOriginateLanguageExceptionAPI())) - { - // In case of WinRT we check whether we have an already existing uncaught language exception. - // If so we simply SetRestrictedErrorInfo on that ensuring that the other language can catch that exception - // and we do not RoOriginateError from our side. - IRestrictedErrorInfo *pRestrictedErrorInfo = GetRestrictedErrorInfoFromErrorObject(pThrownObject); - if(pRestrictedErrorInfo != NULL) - { - (*g_pfnSetRestrictedErrorInfo)(pRestrictedErrorInfo); - GetRestrictedErrorDetails(pRestrictedErrorInfo, NULL, NULL, &hr, NULL); - } - else - { - // If there is no existing language exception we save the errorInfo on the current thread by storing the following information - // 1. HResult - // 2. ErrorMsg - // 3. The managed exception object, which can be later retrieved if needed. - - pErr = (IErrorInfo *)GetComIPFromObjectRef(&pThrownObject, IID_IErrorInfo); - - StackSString message; - HRESULT errorHr; - HSTRING errorMsgString; - - GetExceptionMessage(pThrownObject, message); - errorHr = GetHRFromThrowable(pThrownObject); - - if(FAILED(WindowsCreateString(message.GetUnicode(), message.GetCount(), &errorMsgString))) - errorMsgString = NULL; - - // - // WinRT change to convert ObjectDisposedException into RO_E_CLOSED - // if we are calling into a WinRT managed object - // - if (errorHr == COR_E_OBJECTDISPOSED) - errorHr = RO_E_CLOSED; - - // Set the managed exception - { - GCX_PREEMP(); - // This Windows API call will store the pErr as the LanguageException and - // construct an IRestrictedErrorInfo from the errorHr and errorMsgString - // which can then be later retrieved using GetRestrictedErrorInfo. - (*g_pfnRoOriginateLanguageException)(errorHr, errorMsgString, pErr); - } - } - } - else + // set the error info object for the exception that was thrown. + pErr = (IErrorInfo *)GetComIPFromObjectRef(&pThrownObject, IID_IErrorInfo); { - // set the error info object for the exception that was thrown. - pErr = (IErrorInfo *)GetComIPFromObjectRef(&pThrownObject, IID_IErrorInfo); - { - GCX_PREEMP(); - SetErrorInfo(0, pErr); - } + GCX_PREEMP(); + SetErrorInfo(0, pErr); } // Release the pErr in case it exists. @@ -808,12 +179,6 @@ HRESULT SetupErrorInfo(OBJECTREF pThrownObject, BOOL bIsWinRTScenario /* = FALSE hr = GET_EXCEPTION()->GetHR(); } EX_END_CATCH(SwallowAllExceptions); - // - // WinRT change to convert ObjectDisposedException into RO_E_CLOSED - // if we are calling into a WinRT managed object - // - if (hr == COR_E_OBJECTDISPOSED && bIsWinRTScenario) - hr = RO_E_CLOSED; #endif // FEATURE_COMINTEROP } } @@ -833,8 +198,7 @@ HRESULT SetupErrorInfo(OBJECTREF pThrownObject, BOOL bIsWinRTScenario /* = FALSE //------------------------------------------------------------------- void FillExceptionData( _Inout_ ExceptionData* pedata, - _In_ IErrorInfo* pErrInfo, - _In_opt_ IRestrictedErrorInfo* pRestrictedErrorInfo) + _In_ IErrorInfo* pErrInfo) { CONTRACTL { @@ -857,38 +221,6 @@ void FillExceptionData( pErrInfo->GetHelpFile (&pedata->bstrHelpFile); pErrInfo->GetHelpContext (&pedata->dwHelpContext ); pErrInfo->GetGUID(&pedata->guid); - -#ifdef FEATURE_COMINTEROP - HRESULT hr = S_OK; - if(pRestrictedErrorInfo == NULL) - { - hr = SafeQueryInterfacePreemp(pErrInfo, IID_IRestrictedErrorInfo, (IUnknown **) &pRestrictedErrorInfo); - LogInteropQI(pErrInfo, IID_IRestrictedErrorInfo, hr, "IRestrictedErrorInfo"); - } - - if (SUCCEEDED(hr) && pRestrictedErrorInfo != NULL) - { - // Keep a AddRef-ed IRestrictedErrorInfo* - pedata->pRestrictedErrorInfo = pRestrictedErrorInfo; - - // Retrieve restricted error information - BSTR bstrDescription = NULL; - HRESULT hrError; - if (SUCCEEDED(GetRestrictedErrorDetails(pRestrictedErrorInfo, &bstrDescription, &pedata->bstrRestrictedError, &hrError, &pedata->bstrCapabilitySid))) - { - if (bstrDescription != NULL) - { - ::SysFreeString(pedata->bstrDescription); - pedata->bstrDescription = bstrDescription; - } - - _ASSERTE(hrError == pedata->hr); - } - - // Retrieve reference string and ignore error - pRestrictedErrorInfo->GetReference(&pedata->bstrReference); - } -#endif ULONG cbRef = SafeRelease(pErrInfo); // release the IErrorInfo interface pointer LogInteropRelease(pErrInfo, cbRef, "IErrorInfo"); } @@ -952,18 +284,15 @@ int GetLCIDParameterIndex(MethodDesc *pMD) const BYTE * pVal; ULONG cbVal; - if (!pMD->GetMethodTable()->IsProjectedFromWinRT()) // ignore LCIDConversionAttribute on WinRT methods + // Check to see if the method has the LCIDConversionAttribute. + hr = pMD->GetCustomAttribute(WellKnownAttribute::LCIDConversion, (const void**)&pVal, &cbVal); + if (hr == S_OK) { - // Check to see if the method has the LCIDConversionAttribute. - hr = pMD->GetCustomAttribute(WellKnownAttribute::LCIDConversion, (const void**)&pVal, &cbVal); - if (hr == S_OK) - { - CustomAttributeParser caLCID(pVal, cbVal); - CaArg args[1]; - args[0].Init(SERIALIZATION_TYPE_I4, 0); - IfFailGo(ParseKnownCaArgs(caLCID, args, lengthof(args))); - iLCIDParam = args[0].val.i4; - } + CustomAttributeParser caLCID(pVal, cbVal); + CaArg args[1]; + args[0].Init(SERIALIZATION_TYPE_I4, 0); + IfFailGo(ParseKnownCaArgs(caLCID, args, lengthof(args))); + iLCIDParam = args[0].val.i4; } ErrExit: @@ -1072,22 +401,19 @@ BOOL IsMemberVisibleFromCom(MethodTable *pDeclaringMT, mdToken tk, mdMethodDef m if (!IsMdPublic(dwFlags)) return FALSE; - if (!pDeclaringMT->IsProjectedFromWinRT() && !pDeclaringMT->IsExportedToWinRT() && !pDeclaringMT->IsWinRTObjectType()) + // Check to see if the associate has the ComVisible attribute set + hr = pModule->GetCustomAttribute(mdAssociate, WellKnownAttribute::ComVisible, (const void**)&pVal, &cbVal); + if (hr == S_OK) { - // Check to see if the associate has the ComVisible attribute set (non-WinRT members only). - hr = pModule->GetCustomAttribute(mdAssociate, WellKnownAttribute::ComVisible, (const void**)&pVal, &cbVal); - if (hr == S_OK) - { - CustomAttributeParser cap(pVal, cbVal); - if (FAILED(cap.SkipProlog())) - return FALSE; + CustomAttributeParser cap(pVal, cbVal); + if (FAILED(cap.SkipProlog())) + return FALSE; - UINT8 u1; - if (FAILED(cap.GetU1(&u1))) - return FALSE; + UINT8 u1; + if (FAILED(cap.GetU1(&u1))) + return FALSE; - return (BOOL)u1; - } + return (BOOL)u1; } break; @@ -1096,28 +422,49 @@ BOOL IsMemberVisibleFromCom(MethodTable *pDeclaringMT, mdToken tk, mdMethodDef m break; } - if (!pDeclaringMT->IsProjectedFromWinRT() && !pDeclaringMT->IsExportedToWinRT() && !pDeclaringMT->IsWinRTObjectType()) + // Check to see if the member has the ComVisible attribute set (non-WinRT members only). + hr = pModule->GetCustomAttribute(tk, WellKnownAttribute::ComVisible, (const void**)&pVal, &cbVal); + if (hr == S_OK) { - // Check to see if the member has the ComVisible attribute set (non-WinRT members only). - hr = pModule->GetCustomAttribute(tk, WellKnownAttribute::ComVisible, (const void**)&pVal, &cbVal); - if (hr == S_OK) - { - CustomAttributeParser cap(pVal, cbVal); - if (FAILED(cap.SkipProlog())) - return FALSE; + CustomAttributeParser cap(pVal, cbVal); + if (FAILED(cap.SkipProlog())) + return FALSE; - UINT8 u1; - if (FAILED(cap.GetU1(&u1))) - return FALSE; + UINT8 u1; + if (FAILED(cap.GetU1(&u1))) + return FALSE; - return (BOOL)u1; - } + return (BOOL)u1; } // The member is visible. return TRUE; } +#ifndef CROSSGEN_COMPILE +// This method checks whether the given IErrorInfo is actually a managed CLR object. +BOOL IsManagedObject(IUnknown *pIUnknown) +{ + CONTRACTL + { + THROWS; + GC_TRIGGERS; + MODE_ANY; + INJECT_FAULT(COMPlusThrowOM()); + PRECONDITION(CheckPointer(pIUnknown)); + } + CONTRACTL_END; +#if FEATURE_COMINTEROP + //Check based on IUnknown slots, i.e. we'll see whether the IP maps to a CCW. + if (MapIUnknownToWrapper(pIUnknown) != NULL) + { + // We found an existing CCW hence this is a managed exception. + return TRUE; + } +#endif + return FALSE; +} +#endif ULONG GetStringizedMethodDef(MethodTable *pDeclaringMT, mdToken tkMb, CQuickArray &rDef, ULONG cbCur) { @@ -1310,17 +657,10 @@ HRESULT GetStringizedTypeLibGuidForAssembly(Assembly *pAssembly, CQuickArrayIsWinMD()) - { - // ignore classic COM interop CA on .winmd - hr = S_FALSE; - } - else - { - // If the ComCompatibleVersionAttribute is set, then use the version - // number in the attribute when generating the GUID. - IfFailGo(pAssembly->GetCustomAttribute(TokenFromRid(1, mdtAssembly), WellKnownAttribute::ComCompatibleVersion, (const void**)&pbData, &cbData)); - } + // If the ComCompatibleVersionAttribute is set, then use the version + // number in the attribute when generating the GUID. + IfFailGo(pAssembly->GetCustomAttribute(TokenFromRid(1, mdtAssembly), WellKnownAttribute::ComCompatibleVersion, (const void**)&pbData, &cbData)); + if (hr == S_OK && cbData >= (2 + 4 * sizeof(INT32))) { @@ -1740,29 +1080,25 @@ CorClassIfaceAttr ReadClassInterfaceTypeCustomAttribute(TypeHandle type) } CONTRACTL_END - // Ignore classic COM interop CA on WinRT types - if (!type.GetMethodTable()->IsWinRTObjectType() && !type.GetMethodTable()->IsExportedToWinRT()) - { - CorClassIfaceAttr attrValueMaybe; + CorClassIfaceAttr attrValueMaybe; - // First look for the class interface attribute at the class level. - HRESULT hr = TryParseClassInterfaceAttribute(type.GetModule(), type.GetCl(), &attrValueMaybe); + // First look for the class interface attribute at the class level. + HRESULT hr = TryParseClassInterfaceAttribute(type.GetModule(), type.GetCl(), &attrValueMaybe); + if (FAILED(hr)) + ThrowHR(hr, BFA_BAD_CLASS_INT_CA_FORMAT); + + if (hr == S_FALSE) + { + // Check the class interface attribute at the assembly level. + Assembly *pAssembly = type.GetAssembly(); + hr = TryParseClassInterfaceAttribute(pAssembly->GetManifestModule(), pAssembly->GetManifestToken(), &attrValueMaybe); if (FAILED(hr)) ThrowHR(hr, BFA_BAD_CLASS_INT_CA_FORMAT); - - if (hr == S_FALSE) - { - // Check the class interface attribute at the assembly level. - Assembly *pAssembly = type.GetAssembly(); - hr = TryParseClassInterfaceAttribute(pAssembly->GetManifestModule(), pAssembly->GetManifestToken(), &attrValueMaybe); - if (FAILED(hr)) - ThrowHR(hr, BFA_BAD_CLASS_INT_CA_FORMAT); - } - - if (hr == S_OK) - return attrValueMaybe; } + if (hr == S_OK) + return attrValueMaybe; + return DEFAULT_CLASS_INTERFACE_TYPE; } @@ -2520,29 +1856,6 @@ BOOL ClassSupportsIClassX(MethodTable *pMT) } CONTRACTL_END; - // WinRT delegates use IClassX - if (pMT->IsWinRTDelegate()) - return TRUE; - - if (pMT->IsWinRTObjectType() || pMT->IsExportedToWinRT()) - { - // Other than that WinRT does not need IClassX so the goal is to return FALSE for - // anything that is guaranteed to not be a legacy classic COM interop scenario - return FALSE; - } - - // If the class is decorated with an explicit ClassInterfaceAttribute, we're going to say yes. - if (S_OK == pMT->GetCustomAttribute(WellKnownAttribute::ClassInterface, NULL, NULL)) - return TRUE; - - MethodTable::InterfaceMapIterator it = pMT->IterateInterfaceMap(); - while (it.Next()) - { - MethodTable *pItfMT = it.GetInterfaceInfo()->GetApproxMethodTable(pMT->GetLoaderModule()); - if (pItfMT->IsProjectedFromWinRT()) - return FALSE; - } - return TRUE; } @@ -2561,7 +1874,6 @@ OBJECTREF AllocateComObject_ForManaged(MethodTable* pMT) MODE_COOPERATIVE; PRECONDITION(CheckPointer(pMT)); PRECONDITION(pMT->IsComObjectType()); - PRECONDITION(!pMT->IsProjectedFromWinRT()); } CONTRACTL_END; @@ -2675,12 +1987,6 @@ DefaultInterfaceType GetDefaultInterfaceForClassInternal(TypeHandle hndClass, Ty PREFIX_ASSUME(pClassMT != NULL); - if (pClassMT->IsWinRTObjectType() || pClassMT->IsExportedToWinRT()) - { - // there's no point executing the rest of the function for WinRT classes - return DefaultInterfaceType_IUnknown; - } - if (pClassMT->IsComImport()) { ClassItfType = clsIfNone; @@ -2960,12 +2266,6 @@ void GetComSourceInterfacesForClass(MethodTable *pMT, CQuickArray // Reset the size of the interface list to 0. rItfList.Shrink(0); - if (pMT->IsWinRTObjectType() || pMT->IsExportedToWinRT()) - { - // classic COM eventing is not supported in WinRT - return; - } - // Starting at the specified class MT retrieve the COM source interfaces // of all the striped of the hierarchy. for (; pMT != NULL; pMT = pMT->GetParentMethodTable()) @@ -3396,11 +2696,8 @@ HRESULT GetTypeLibVersionForAssembly( const BYTE *pbData = nullptr; ULONG cbData = 0; - if (!pAssembly->IsWinMD()) - { - // Check to see if the TypeLibVersionAttribute is set. - IfFailRet(pAssembly->GetManifestImport()->GetCustomAttributeByName(TokenFromRid(1, mdtAssembly), INTEROP_TYPELIBVERSION_TYPE, (const void**)&pbData, &cbData)); - } + // Check to see if the TypeLibVersionAttribute is set. + IfFailRet(pAssembly->GetManifestImport()->GetCustomAttributeByName(TokenFromRid(1, mdtAssembly), INTEROP_TYPELIBVERSION_TYPE, (const void**)&pbData, &cbData)); // For attribute contents, see https://docs.microsoft.com/dotnet/api/system.runtime.interopservices.typelibversionattribute if (cbData >= (2 + 2 * sizeof(UINT32))) @@ -3499,10 +2796,6 @@ static BOOL SpecialIsGenericTypeVisibleFromCom(TypeHandle hndType) if (pMT->IsInterface() && pMT->IsComImport()) return TRUE; - // If the type is imported from WinRT (has the tdWindowsRuntime flag set), then it is visible from COM. - if (pMT->IsProjectedFromWinRT()) - return TRUE; - // If the type is an array, then it is not visible from COM. if (pMT->IsArray()) return FALSE; @@ -3582,12 +2875,9 @@ BOOL IsTypeVisibleFromCom(TypeHandle hndType) } CONTRACTL_END; - if (!hndType.SupportsGenericInterop(TypeHandle::Interop_NativeToManaged)) - { - // If the type is a generic type, then it is not visible from COM. - if (hndType.HasInstantiation() || hndType.IsGenericVariable()) - return FALSE; - } + // If the type is a generic type, then it is not visible from COM. + if (hndType.HasInstantiation() || hndType.IsGenericVariable()) + return FALSE; return SpecialIsGenericTypeVisibleFromCom(hndType); } @@ -3607,42 +2897,12 @@ BOOL MethodNeedsForwardComStub(MethodDesc *pMD, DataImage *pImage) MethodTable *pMT = pMD->GetMethodTable(); - if (pMT->HasInstantiation() && !pMT->SupportsGenericInterop(TypeHandle::Interop_ManagedToNative)) + if (pMT->HasInstantiation()) { // method is declared on an unsupported generic type -> stub not needed return FALSE; } - if (pMT->IsProjectedFromWinRT() && pMT->IsComImport() && pMD->IsPrivate()) - { - // private WinRT method -> stub not needed - return FALSE; - } - - if (pMT->IsWinRTObjectType()) - { - // WinRT runtime class -> stub needed - return TRUE; - } - - if (pMT->IsWinRTRedirectedInterface(TypeHandle::Interop_ManagedToNative)) - { - if (!pMT->HasInstantiation()) - { - // non-generic redirected interface -> stub needed - return TRUE; - } - - // Generating stubs for generic redirected interfaces into all assemblies would grow NetFX native images - // by several per cent. See BCL\System\Internal.cs if you need to add specific instantiations in mscorlib. - DWORD assemblyFlags = pImage->GetModule()->GetAssembly()->GetFlags(); - if (IsAfContentType_WindowsRuntime(assemblyFlags)) - { - // generic redirected interface while NGENing a .winmd -> stub needed - return TRUE; - } - } - GUID guid; pMT->GetGuid(&guid, FALSE); @@ -3677,34 +2937,12 @@ BOOL MethodNeedsReverseComStub(MethodDesc *pMD) if (!pMT->IsComImport() && !IsTypeVisibleFromCom(TypeHandle(pMT))) return FALSE; - if (pMT->HasInstantiation() && !pMT->SupportsGenericInterop(TypeHandle::Interop_NativeToManaged)) + if (pMT->HasInstantiation()) return FALSE; // declaring interface must be InterfaceIsIUnknown or InterfaceIsDual if (pMT->GetComInterfaceType() == ifDispatch) return FALSE; - - Assembly * pAssembly = pMT->GetAssembly(); - if (pAssembly->IsWinMD() && !pAssembly->IsManagedWinMD()) - { - // - // Internal interfaces defined in native winmds can only ever be implemented by native components. - // Managed classes won't be able to implement the internal interfaces, and so the reverse COM stubs - // are not needed for them. - // - if (IsTdNotPublic(pMT->GetClass()->GetProtection())) - { - // - // However, we do need CCWs for internal interfaces that define protected members of inheritable classes - // (for example, Windows.UI.Xaml.Application implements both IApplication, which we don't need - // a CCW for and IApplicationOverrides, which we do need). - // - if (!pMT->GetWriteableData()->IsOverridingInterface()) - { - return FALSE; - } - } - } } else { @@ -3713,27 +2951,14 @@ BOOL MethodNeedsReverseComStub(MethodDesc *pMD) if (pMT->IsDelegate()) { - // the 'Invoke' method of a WinRT delegate needs stub - return ((pMT->IsProjectedFromWinRT() || WinRTTypeNameConverter::IsRedirectedType(pMT)) && - pMD->HasSameMethodDefAs(COMDelegate::FindDelegateInvokeMethod(pMT))); + return FALSE; } - if (pMT->IsExportedToWinRT() && (pMD->IsCtor() || pMD->IsStatic())) - { - fIsAllowedCtorOrStatic = TRUE; - } - else - { - // declaring class must be AutoDual - if (pMT->GetComClassInterfaceType() != clsIfAutoDual) - return FALSE; - } + // declaring class must be AutoDual + if (pMT->GetComClassInterfaceType() != clsIfAutoDual) + return FALSE; } - // static methods and ctors are not exposed to COM except for WinRT - if (!fIsAllowedCtorOrStatic && (pMD->IsCtor() || pMD->IsStatic())) - return FALSE; - // NGen can't compile stubs for var arg methods if (pMD->IsVarArg()) return FALSE; @@ -4794,1175 +4019,140 @@ void GetComClassFromCLSID(REFCLSID clsid, STRINGREF srefServer, OBJECTREF *pRef) // // Allocate strings for the server. - // - - if (srefServer != NULL) - { - int len = srefServer->GetStringLength(); - - wszServer = new WCHAR[len+1]; - - if (len) - memcpy(wszServer, srefServer->GetBuffer(), (len*2)); - - wszServer[len] = W('\0'); - } - - - // - // If no server name has been specified, see if we can find the well known - // managed class for this CLSID. - // - - if (bServerIsLocal) - { - // @TODO(DM): Do we really need to be this forgiving ? We should - // look into letting the type load exceptions percolate - // up to the user instead of swallowing them and using __ComObject. - EX_TRY - { - pMT = GetTypeForCLSID(clsid); - } - EX_CATCH - { - } - EX_END_CATCH(RethrowTerminalExceptions) - } - - if (pMT != NULL) - { - // - // There is a managed class for this CLSID. - // - - *pRef = pMT->GetManagedClassObject(); - } - else - { - // Check if we have in the hash. - OBJECTHANDLE hRef; - ClassFactoryInfo ClassFactInfo; - ClassFactInfo.m_clsid = clsid; - ClassFactInfo.m_strServerName = wszServer; - EEClassFactoryInfoHashTable *pClassFactHash = GetAppDomain()->GetClassFactHash(); - - if (pClassFactHash->GetValue(&ClassFactInfo, (HashDatum*) &hRef)) - { - *pRef = ObjectFromHandle(hRef); - } - else - { - GetComClassHelper(pRef, pClassFactHash, &ClassFactInfo, NULL); - } - } - - // If we made it this far *pRef better be set. - _ASSERTE(*pRef != NULL); -} - -#endif // FEATURE_COMINTEROP_UNMANAGED_ACTIVATION && FEATURE_CLASSIC_COMINTEROP - -#endif //#ifndef CROSSGEN_COMPILE - - -#ifdef FEATURE_COMINTEROP_UNMANAGED_ACTIVATION -//------------------------------------------------------------- -// check if a ComClassFactory has been setup for this class -// if not set one up -ClassFactoryBase *GetComClassFactory(MethodTable* pClassMT) -{ - CONTRACT (ClassFactoryBase*) - { - THROWS; - GC_TRIGGERS; - MODE_ANY; - INJECT_FAULT(ThrowOutOfMemory()); - PRECONDITION(CheckPointer(pClassMT)); - PRECONDITION(pClassMT->IsComObjectType() || pClassMT->IsExportedToWinRT()); - POSTCONDITION(CheckPointer(RETVAL)); - } - CONTRACT_END; - - if (!pClassMT->IsExportedToWinRT()) - { - // Work our way up the hierachy until we find the first COM import type. - while (!pClassMT->IsComImport()) - { - pClassMT = pClassMT->GetParentMethodTable(); - _ASSERTE(pClassMT != NULL); - _ASSERTE(pClassMT->IsComObjectType()); - } - } - - // check if com data has been setup for this class - ClassFactoryBase *pClsFac = pClassMT->GetComClassFactory(); - - if (pClsFac == NULL) - { - // - // Collectible types do not support WinRT interop - // - if (pClassMT->Collectible() && (pClassMT->IsExportedToWinRT() || pClassMT->IsProjectedFromWinRT())) - { - COMPlusThrow(kNotSupportedException, W("NotSupported_CollectibleWinRT")); - } - - NewHolder pNewFactory; - - if (pClassMT->IsExportedToWinRT()) - { - WinRTManagedClassFactory *pWinRTMngClsFac = new WinRTManagedClassFactory(pClassMT); - pNewFactory = pWinRTMngClsFac; - - pWinRTMngClsFac->Init(); - } - else if (pClassMT->IsProjectedFromWinRT()) - { - WinRTClassFactory *pWinRTClsFac = new WinRTClassFactory(pClassMT); - pNewFactory = pWinRTClsFac; - - pWinRTClsFac->Init(); - } - else - { - GUID guid; - pClassMT->GetGuid(&guid, TRUE); - - ComClassFactory *pComClsFac = ComClassFactoryCreator::Create(guid); - - pNewFactory = pComClsFac; - - pComClsFac->Init(NULL, NULL, pClassMT); - } - - // store the class factory in EE Class - if (!pClassMT->SetComClassFactory(pNewFactory)) - { - // another thread beat us to it - pNewFactory = pClassMT->GetComClassFactory(); - } - - pClsFac = pNewFactory.Extract(); - } - - RETURN pClsFac; -} -#endif // FEATURE_COMINTEROP_UNMANAGED_ACTIVATION - - -//------------------------------------------------------------------- -// void InitializeComInterop() -// Called from EEStartup, to initialize com Interop specific data -// structures. -//------------------------------------------------------------------- -void InitializeComInterop() -{ - CONTRACTL - { - THROWS; - GC_TRIGGERS; - MODE_ANY; - } - CONTRACTL_END; - - InitializeSListHead(&RCW::s_RCWStandbyList); - ComCall::Init(); -#ifdef TARGET_X86 - ComPlusCall::Init(); -#endif -#ifndef CROSSGEN_COMPILE - CtxEntryCache::Init(); - ComCallWrapperTemplate::Init(); -#ifdef _DEBUG - IntializeInteropLogging(); -#endif //_DEBUG -#endif //CROSSGEN_COMPILE -} - -// Try to load a WinRT type. -TypeHandle LoadWinRTType(SString* ssTypeName, BOOL bThrowIfNotFound, ICLRPrivBinder* loadBinder /* =nullptr */) -{ - CONTRACT (TypeHandle) - { - MODE_ANY; - THROWS; - GC_TRIGGERS; - } - CONTRACT_END; - - TypeHandle typeHandle; - - SString ssAssemblyName(SString::Utf8Literal, "WindowsRuntimeAssemblyName, ContentType=WindowsRuntime"); - DomainAssembly *pAssembly = LoadDomainAssembly(&ssAssemblyName, nullptr, - loadBinder, - bThrowIfNotFound, ssTypeName); - if (pAssembly != NULL) - { - typeHandle = TypeName::GetTypeFromAssembly(*ssTypeName, pAssembly->GetAssembly(), bThrowIfNotFound); - } - - RETURN typeHandle; -} - -// Makes a IRoSimpleMetaDataBuilder callback for a runtime class. -// static -HRESULT WinRTGuidGenerator::MetaDataLocator::LocateTypeWithDefaultInterface(MethodTable *pMT, LPCWSTR pszName, IRoSimpleMetaDataBuilder &metaDataDestination) -{ - CONTRACTL - { - THROWS; - GC_TRIGGERS; - MODE_ANY; - PRECONDITION(CheckPointer(pMT)); - PRECONDITION(!pMT->IsInterface()); - PRECONDITION(CheckPointer(pszName)); - } - CONTRACTL_END; - - MethodTable *pDefItfMT = pMT->GetDefaultWinRTInterface(); - if (pDefItfMT == NULL) - { - StackSString ss; - TypeString::AppendType(ss, TypeHandle(pMT)); - COMPlusThrowHR(COR_E_BADIMAGEFORMAT, IDS_EE_WINRT_IID_NODEFAULTINTERFACE, ss.GetUnicode()); - } - - DefineFullyQualifiedNameForClassW(); - - GUID iid; - pDefItfMT->GetGuid(&iid, FALSE); - - if (pDefItfMT->HasInstantiation()) - { - SArray namesBuf; - PCWSTR *pNamePointers; - COUNT_T cNames; - PopulateNames(pDefItfMT, namesBuf, pNamePointers, cNames); - - // runtime class with generic default interface - return metaDataDestination.SetRuntimeClassParameterizedDefault( - pszName, - cNames, - pNamePointers); - } - else - { - LPCWSTR pszDefItfName = GetFullyQualifiedNameForClassW_WinRT(pDefItfMT); - - // runtime class with non-generic default interface - return metaDataDestination.SetRuntimeClassSimpleDefault( - pszName, - pszDefItfName, - &iid); - } -} - -// Makes a IRoSimpleMetaDataBuilder callback for a structure. -// static -HRESULT WinRTGuidGenerator::MetaDataLocator::LocateStructure(MethodTable *pMT, LPCWSTR pszName, IRoSimpleMetaDataBuilder &metaDataDestination) -{ - CONTRACTL - { - THROWS; - GC_TRIGGERS; - MODE_ANY; - PRECONDITION(CheckPointer(pMT)); - PRECONDITION(CheckPointer(pszName)); - } - CONTRACTL_END; - - SArray namesBuf; - COUNT_T cNames = 0; - - ApproxFieldDescIterator fieldIterator(pMT, ApproxFieldDescIterator::INSTANCE_FIELDS); - for (FieldDesc *pFD = fieldIterator.Next(); pFD != NULL; pFD = fieldIterator.Next()) - { - TypeHandle th = pFD->GetApproxFieldTypeHandleThrowing(); - if (th.IsTypeDesc()) - { - // WinRT structures should not have TypeDesc fields - IfFailThrowBF(E_FAIL, BFA_BAD_SIGNATURE, pMT->GetModule()); - } - - PopulateNamesAppendTypeName(th.AsMethodTable(), namesBuf, cNames); - } - - PCWSTR *pNamePointers; - PopulateNamesAppendNamePointers(pMT, namesBuf, pNamePointers, cNames); - - return metaDataDestination.SetStruct( - pszName, - cNames, - pNamePointers); -} - - -// -// Tables of information about the redirected types used to setup GUID marshaling -// - -struct RedirectedEnumInfo -{ - LPCWSTR wszBackingField; -}; - -#define DEFINE_PROJECTED_TYPE(szWinRTNS, szWinRTName, szClrNS, szClrName, nClrAsmIdx, nContractAsmIdx, nWinRTIndex, nClrIndex, nWinMDTypeKind) \ - { nullptr }, -#define DEFINE_PROJECTED_ENUM(szWinRTNamespace, szWinRTName, szClrNamespace, szClrName, nClrAssemblyIndex, nContractAsmIdx, WinRTRedirectedTypeIndex, ClrRedirectedTypeIndex, szBackingFieldSize) \ - { L ## szBackingFieldSize }, - -static const RedirectedEnumInfo g_redirectedEnumInfo[WinMDAdapter::RedirectedTypeIndex_Count] = -{ -#include "winrtprojectedtypes.h" -}; - -#undef DEFINE_PROJECTED_TYPE -#undef DEFINE_PROJECTED_ENUM - -struct RedirectedPInterfaceInfo -{ - DWORD cGenericParameters; - const GUID IID; -}; - -#define DEFINE_PROJECTED_TYPE(szWinRTNS, szWinRTName, szClrNS, szClrName, nClrAsmIdx, nContractAsmIdx, nWinRTIndex, nClrIndex, nWinMDTypeKind) \ - { 0, { 0 } }, -#define DEFINE_PROJECTED_INTERFACE(szWinRTNamespace, szWinRTName, szClrNamespace, szClrName, nClrAssemblyIndex, nContractAsmIdx, WinRTRedirectedTypeIndex, ClrRedirectedTypeIndex, PIID) \ - { 0, PIID }, -#define DEFINE_PROJECTED_PINTERFACE(szWinRTNamespace, szWinRTName, szClrNamespace, szClrName, nClrAssemblyIndex, nContractAsmIdx, WinRTRedirectedTypeIndex, ClrRedirectedTypeIndex, GenericTypeParameterCount, PIID) \ - { GenericTypeParameterCount, PIID }, - -static const RedirectedPInterfaceInfo g_redirectedPInterfaceInfo[] = -{ -#include "winrtprojectedtypes.h" -}; - -#undef DEFINE_PROJECTED_TYPE -#undef DEFINE_PROJECTED_INTERFACE -#undef DEFINE_PROJECTED_PINTERFACE - -struct RedirectedPDelegateInfo -{ - const DWORD cGenericParameters; - const GUID IID; -}; - -#define DEFINE_PROJECTED_TYPE(szWinRTNS, szWinRTName, szClrNS, szClrName, nClrAsmIdx, nContractAsmIdx, nWinRTIndex, nClrIndex, nWinMDTypeKind) \ - { 0, { 0 } }, -#define DEFINE_PROJECTED_DELEGATE(szWinRTNamespace, szWinRTName, szClrNamespace, szClrName, nClrAssemblyIndex, nContractAsmIdx, WinRTRedirectedTypeIndex, ClrRedirectedTypeIndex, PIID) \ - { 0, PIID }, -#define DEFINE_PROJECTED_PDELEGATE(szWinRTNamespace, szWinRTName, szClrNamespace, szClrName, nClrAssemblyIndex, nContractAsmIdx, WinRTRedirectedTypeIndex, ClrRedirectedTypeIndex, GenericTypeParameterCount, PIID) \ - { GenericTypeParameterCount, PIID }, - -static const RedirectedPDelegateInfo g_redirectedPDelegateInfo[] = -{ -#include "winrtprojectedtypes.h" -}; - -#undef DEFINE_PROJECTED_TYPE -#undef DEFINE_PROJECTED_DELEGATE -#undef DEFINE_PROJECTED_PDELEGATE - -struct RedirectedRuntimeclassInfo -{ - LPCWSTR wszDefaultIntefaceName; - const GUID IID; -}; - -#define DEFINE_PROJECTED_TYPE(szWinRTNS, szWinRTName, szClrNS, szClrName, nClrAsmIdx, nContractAsmIdx, nWinRTIndex, nClrIndex, nWinMDTypeKind) \ - { nullptr, { 0 } }, -#define DEFINE_PROJECTED_RUNTIMECLASS(szWinRTNamespace, szWinRTName, szClrNamespace, szClrName, nClrAssemblyIndex, nContractAsmIdx, WinRTRedirectedTypeIndex, ClrRedirectedTypeIndex, szDefaultInterfaceName, DefaultInterfaceIID) \ - { L ## szDefaultInterfaceName, DefaultInterfaceIID }, - -static RedirectedRuntimeclassInfo const g_redirectedRuntimeclassInfo[] = -{ -#include "winrtprojectedtypes.h" -}; - -#undef DEFINE_PROJECTED_TYPE -#undef DEFINE_PROJECTED_RUNTIMECLASS - -struct RedirectedStructInfo -{ - const DWORD cFields; - const LPCWSTR *pwzFields; -}; - -#define DEFINE_PROJECTED_TYPE(szWinRTNS, szWinRTName, szClrNS, szClrName, nClrAsmIdx, nContractAsmIdx, nWinRTIndex, nClrIndex, nWinMDTypeKind) -#define DEFINE_PROJECTED_STRUCT(szWinRTNamespace, szWinRTName, szClrNamespace, szClrName, nClrAssemblyIndex, nContractAsmIdx, WinRTRedirectedTypeIndex, ClrRedirectedTypeIndex, FieldSizes) \ -static const LPCWSTR g_ ## WinRTRedirectedTypeIndex ## _Fields[] = { FieldSizes }; -#define DEFINE_PROJECTED_JUPITER_STRUCT(szWinRTNamespace, szWinRTName, szClrNamespace, szClrName, nClrAssemblyIndex, nContractAsmIdx, WinRTRedirectedTypeIndex, ClrRedirectedTypeIndex, FieldSizes) \ -static const LPCWSTR g_ ## WinRTRedirectedTypeIndex ## _Fields[] = { FieldSizes }; -#include "winrtprojectedtypes.h" -#undef DEFINE_PROJECTED_TYPE -#undef DEFINE_PROJECTED_STRUCT -#undef DEFINE_PROJECTED_JUPITER_STRUCT - -#define DEFINE_PROJECTED_TYPE(szWinRTNS, szWinRTName, szClrNS, szClrName, nClrAsmIdx, nContractAsmIdx, nWinRTIndex, nClrIndex, nWinMDTypeKind) \ - { 0, nullptr }, -#define DEFINE_PROJECTED_STRUCT(szWinRTNamespace, szWinRTName, szClrNamespace, szClrName, nClrAssemblyIndex, nContractAsmIdx, WinRTRedirectedTypeIndex, ClrRedirectedTypeIndex, FieldSizes) \ - { COUNTOF(g_ ## WinRTRedirectedTypeIndex ## _Fields), g_ ## WinRTRedirectedTypeIndex ## _Fields }, -#define DEFINE_PROJECTED_JUPITER_STRUCT(szWinRTNamespace, szWinRTName, szClrNamespace, szClrName, nClrAssemblyIndex, nContractAsmIdx, WinRTRedirectedTypeIndex, ClrRedirectedTypeIndex, FieldSizes) \ - { COUNTOF(g_ ## WinRTRedirectedTypeIndex ## _Fields), g_ ## WinRTRedirectedTypeIndex ## _Fields }, - -static const RedirectedStructInfo g_redirectedStructInfo[WinMDAdapter::RedirectedTypeIndex_Count] = -{ -#include "winrtprojectedtypes.h" -}; - -#undef DEFINE_PROJECTED_TYPE -#undef DEFINE_PROJECTED_STRUCT -#undef DEFINE_PROJECTED_JUPITER_STRUCT - -// Makes a IRoSimpleMetaDataBuilder callback for a redirected type or returns S_FALSE. -// static -HRESULT WinRTGuidGenerator::MetaDataLocator::LocateRedirectedType( - MethodTable * pMT, - IRoSimpleMetaDataBuilder & metaDataDestination) -{ - CONTRACTL - { - THROWS; - GC_TRIGGERS; - MODE_ANY; - PRECONDITION(CheckPointer(pMT)); - } - CONTRACTL_END; - - WinMDAdapter::RedirectedTypeIndex nRedirectedTypeIndex; - if (!WinRTTypeNameConverter::ResolveRedirectedType(pMT, &nRedirectedTypeIndex)) - { - // this is not a redirected type - return S_FALSE; - } - - WinMDAdapter::WinMDTypeKind typeKind; - WinMDAdapter::GetRedirectedTypeInfo(nRedirectedTypeIndex, nullptr, nullptr, nullptr, nullptr, nullptr, &typeKind); - switch (typeKind) - { - case WinMDAdapter::WinMDTypeKind_Attribute: - { - // not a runtime class -> throw - StackSString ss; - TypeString::AppendType(ss, TypeHandle(pMT)); - COMPlusThrowHR(COR_E_BADIMAGEFORMAT, IDS_EE_WINRT_IID_NODEFAULTINTERFACE, ss.GetUnicode()); - } - - case WinMDAdapter::WinMDTypeKind_Enum: - return metaDataDestination.SetEnum(WinMDAdapter::GetRedirectedTypeFullWinRTName(nRedirectedTypeIndex), - g_redirectedEnumInfo[nRedirectedTypeIndex].wszBackingField); - - case WinMDAdapter::WinMDTypeKind_Delegate: - return metaDataDestination.SetDelegate(g_redirectedPDelegateInfo[nRedirectedTypeIndex].IID); - - case WinMDAdapter::WinMDTypeKind_PDelegate: - return metaDataDestination.SetParameterizedDelegate(g_redirectedPDelegateInfo[nRedirectedTypeIndex].IID, - g_redirectedPDelegateInfo[nRedirectedTypeIndex].cGenericParameters); - - case WinMDAdapter::WinMDTypeKind_Interface: - return metaDataDestination.SetWinRtInterface(g_redirectedPInterfaceInfo[nRedirectedTypeIndex].IID); - - case WinMDAdapter::WinMDTypeKind_PInterface: - return metaDataDestination.SetParameterizedInterface(g_redirectedPInterfaceInfo[nRedirectedTypeIndex].IID, - g_redirectedPInterfaceInfo[nRedirectedTypeIndex].cGenericParameters); - - case WinMDAdapter::WinMDTypeKind_Runtimeclass: - return metaDataDestination.SetRuntimeClassSimpleDefault(WinMDAdapter::GetRedirectedTypeFullWinRTName(nRedirectedTypeIndex), - g_redirectedRuntimeclassInfo[nRedirectedTypeIndex].wszDefaultIntefaceName, - &g_redirectedRuntimeclassInfo[nRedirectedTypeIndex].IID); - - case WinMDAdapter::WinMDTypeKind_Struct: - return metaDataDestination.SetStruct(WinMDAdapter::GetRedirectedTypeFullWinRTName(nRedirectedTypeIndex), - g_redirectedStructInfo[nRedirectedTypeIndex].cFields, - g_redirectedStructInfo[nRedirectedTypeIndex].pwzFields); - - default: - UNREACHABLE(); - } -} - -HRESULT STDMETHODCALLTYPE WinRTGuidGenerator::MetaDataLocator::Locate(PCWSTR nameElement, IRoSimpleMetaDataBuilder &metaDataDestination) const -{ - CONTRACTL - { - THROWS; - GC_TRIGGERS; - MODE_ANY; - PRECONDITION(CheckPointer(nameElement)); - } - CONTRACTL_END; - - // All names that we feed to RoGetParameterizedTypeInstanceIID begin with 'T' - // which is followed by the MethodTable address printed as a pointer (in hex). - MethodTable *pMT; - if (swscanf_s(nameElement, W("T%p"), (LPVOID *)&pMT) != 1) - { - // Except that it could be a field from a redirected structure - if (wcscmp(nameElement, W("Windows.Foundation.TimeSpan")) == 0) - { - LPCWSTR pwszFields[] = { W("Int64") }; - return metaDataDestination.SetStruct(nameElement, COUNTOF(pwszFields), pwszFields); - } - else if (wcscmp(nameElement, W("Windows.UI.Xaml.DurationType")) == 0) - { - return metaDataDestination.SetEnum(nameElement, W("Int32")); - } - else if (wcscmp(nameElement, W("Windows.UI.Xaml.GridUnitType")) == 0) - { - return metaDataDestination.SetEnum(nameElement, W("Int32")); - } - else if (wcscmp(nameElement, W("Windows.UI.Xaml.Interop.TypeKind")) == 0) - { - return metaDataDestination.SetEnum(nameElement, W("Int32")); - } - else if (wcscmp(nameElement, W("Windows.UI.Xaml.Media.Animation.RepeatBehaviorType")) == 0) - { - return metaDataDestination.SetEnum(nameElement, W("Int32")); - } - else if (wcscmp(nameElement, W("Windows.Foundation.Numerics.Vector3")) == 0) - { - LPCWSTR pwszFields[] = { W("Single"), W("Single"), W("Single") }; - return metaDataDestination.SetStruct(nameElement, COUNTOF(pwszFields), pwszFields); - } - - return E_FAIL; - } - - // do a check for a redirected type first - HRESULT hr = LocateRedirectedType(pMT, metaDataDestination); - if (hr == S_OK || FAILED(hr)) - { - // already handled by LocateRedirectedType - return hr; - } - - GUID iid; - DefineFullyQualifiedNameForClassW(); - - if (pMT->IsValueType()) - { - if (pMT->IsEnum()) - { - // enum - StackSString ssBaseType; - VERIFY(WinRTTypeNameConverter::AppendWinRTNameForPrimitiveType(MscorlibBinder::GetElementType(pMT->GetInternalCorElementType()), ssBaseType)); - - return metaDataDestination.SetEnum( - GetFullyQualifiedNameForClassW_WinRT(pMT), - ssBaseType.GetUnicode()); - } - else - { - // struct - return LocateStructure( - pMT, - GetFullyQualifiedNameForClassW_WinRT(pMT), - metaDataDestination); - } - } - else - { - if (pMT->IsInterface()) - { - pMT->GetGuid(&iid, FALSE); - if (pMT->HasInstantiation()) - { - // generic interface - return metaDataDestination.SetParameterizedInterface( - iid, - pMT->GetNumGenericArgs()); - } - else - { - // non-generic interface - return metaDataDestination.SetWinRtInterface(iid); - } - } - else - { - if (pMT->IsDelegate()) - { - pMT->GetGuid(&iid, FALSE); - if (pMT->HasInstantiation()) - { - // generic delegate - return metaDataDestination.SetParameterizedDelegate( - iid, - pMT->GetNumGenericArgs()); - } - else - { - // non-generic delegate - return metaDataDestination.SetDelegate(iid); - } - } - else - { - // runtime class - return LocateTypeWithDefaultInterface( - pMT, - GetFullyQualifiedNameForClassW_WinRT(pMT), - metaDataDestination); - } - } - } -} - - -void WinRTGuidGenerator::PopulateNames(MethodTable *pMT, SArray &namesBuf, PCWSTR* &pszNames, COUNT_T &cNames) -{ - CONTRACTL - { - THROWS; - GC_TRIGGERS; - MODE_ANY; - PRECONDITION(CheckPointer(pMT)); - } - CONTRACTL_END; - - cNames = 0; - - // Fill namesBuf with a pile of strings. - PopulateNamesAppendTypeName(pMT, namesBuf, cNames); - PopulateNamesAppendNamePointers(pMT, namesBuf, pszNames, cNames); -} - -void WinRTGuidGenerator::PopulateNamesAppendNamePointers(MethodTable *pMT, SArray &namesBuf, PCWSTR* &pszNames, COUNT_T cNames) -{ - CONTRACTL - { - THROWS; - GC_TRIGGERS; - MODE_ANY; - PRECONDITION(CheckPointer(pMT)); - } - CONTRACTL_END; - - // Get pointers to internal strings - COUNT_T cbNamesOld = (COUNT_T)ALIGN_UP(namesBuf.GetCount(), sizeof(PWSTR)); // End of strings is not necessarily pointer aligned, align so that the follow on pointers are aligned. - COUNT_T cbNamePointers = cNames * sizeof(PWSTR); // How much space do we need for the pointers to the names? - COUNT_T cbNamesNew = cbNamesOld + cbNamePointers; // Total space. - - BYTE *pBuffer = namesBuf.OpenRawBuffer(cbNamesNew); - - // Scan through strings, and build list of pointers to them. This assumes that the strings are seperated by a single null character - PWSTR pszName = (PWSTR)pBuffer; - pszNames = (PCWSTR*)(pBuffer + cbNamesOld); - for (COUNT_T i = 0; i < cNames; i++) - { - pszNames[i] = pszName; - pszName += wcslen(pszName) + 1; - } - - namesBuf.CloseRawBuffer(cbNamesNew); -} - -void WinRTGuidGenerator::PopulateNamesAppendTypeName(MethodTable *pMT, SArray &namesBuf, COUNT_T &cNames) -{ - CONTRACTL - { - THROWS; - GC_TRIGGERS; - MODE_ANY; - PRECONDITION(CheckPointer(pMT)); - } - CONTRACTL_END; - - SmallStackSString name; - -#ifdef _DEBUG - pMT->CheckLoadLevel(CLASS_LOAD_EXACTPARENTS); -#endif // _DEBUG - - if (!WinRTTypeNameConverter::AppendWinRTNameForPrimitiveType(pMT, name)) - { - if (pMT->HasInstantiation()) - { - // get the typical instantiation - TypeHandle typicalInst = ClassLoader::LoadTypeDefThrowing(pMT->GetModule(), - pMT->GetCl(), - ClassLoader::ThrowIfNotFound, - ClassLoader::PermitUninstDefOrRef - , tdNoTypes - , CLASS_LOAD_EXACTPARENTS - ); - - name.Printf(W("T%p"), typicalInst.AsPtr()); - } - else - { - name.Printf(W("T%p"), (void *)pMT); - } - } - - COUNT_T cbNamesOld = namesBuf.GetCount(); - COUNT_T cbNewName = (COUNT_T)(name.GetCount() + 1) * 2; - COUNT_T cbNamesNew = cbNamesOld + cbNewName; - memcpy(namesBuf.OpenRawBuffer(cbNamesNew) + cbNamesOld, name.GetUnicode(), cbNewName); - namesBuf.CloseRawBuffer(cbNamesNew); - cNames++; - - if (pMT->HasInstantiation()) - { - Instantiation inst = pMT->GetInstantiation(); - for (DWORD i = 0; i < inst.GetNumArgs(); i++) - { - PopulateNamesAppendTypeName(inst[i].GetMethodTable(), namesBuf, cNames); - } - } -} - -// We need to be able to compute IIDs of generic interfaces for WinRT interop even on Win7 when we NGEN. -// Otherwise Framework assemblies that contain projected WinRT types would end up with different native -// images depending on the OS they were compiled on. -namespace ParamInstanceAPI_StaticallyLinked -{ - // make sure that paraminstanceapi.h can be dropped in without extensive modifications - namespace std - { - static const NoThrow nothrow = ::nothrow; - } - -#pragma warning(push) -#pragma warning (disable: 4640) - #include "paraminstanceapi.h" -#pragma warning(pop) -} - -// Although the IRoMetaDataLocator and IRoSimpleMetaDataBuilder interfaces may currently be structurally -// equivalent, use proper wrappers instead of dirty casts. This will trigger compile errors if the two -// implementations diverge from each other in the future. -class MetaDataLocatorWrapper : public ParamInstanceAPI_StaticallyLinked::IRoMetaDataLocator -{ - class SimpleMetaDataBuilderWrapper : public ::IRoSimpleMetaDataBuilder - { - ParamInstanceAPI_StaticallyLinked::IRoSimpleMetaDataBuilder &m_destination; - - public: - SimpleMetaDataBuilderWrapper(ParamInstanceAPI_StaticallyLinked::IRoSimpleMetaDataBuilder &destination) - : m_destination(destination) - { } - - STDMETHOD(SetWinRtInterface)(GUID iid) - { WRAPPER_NO_CONTRACT; return m_destination.SetWinRtInterface(iid); } - - STDMETHOD(SetDelegate)(GUID iid) - { WRAPPER_NO_CONTRACT; return m_destination.SetDelegate(iid); } - - STDMETHOD(SetInterfaceGroupSimpleDefault)(PCWSTR name, PCWSTR defaultInterfaceName, const GUID *defaultInterfaceIID) - { WRAPPER_NO_CONTRACT; return m_destination.SetInterfaceGroupSimpleDefault(name, defaultInterfaceName, defaultInterfaceIID); } - - STDMETHOD(SetInterfaceGroupParameterizedDefault)(PCWSTR name, UINT32 elementCount, PCWSTR *defaultInterfaceNameElements) - { WRAPPER_NO_CONTRACT; return m_destination.SetInterfaceGroupParameterizedDefault(name, elementCount, defaultInterfaceNameElements); } - - STDMETHOD(SetRuntimeClassSimpleDefault)(PCWSTR name, PCWSTR defaultInterfaceName, const GUID *defaultInterfaceIID) - { WRAPPER_NO_CONTRACT; return m_destination.SetRuntimeClassSimpleDefault(name, defaultInterfaceName, defaultInterfaceIID); } - - STDMETHOD(SetRuntimeClassParameterizedDefault)(PCWSTR name, UINT32 elementCount, const PCWSTR *defaultInterfaceNameElements) - { WRAPPER_NO_CONTRACT; return m_destination.SetRuntimeClassParameterizedDefault(name, elementCount, const_cast(defaultInterfaceNameElements)); } - - STDMETHOD(SetStruct)(PCWSTR name, UINT32 numFields, const PCWSTR *fieldTypeNames) - { WRAPPER_NO_CONTRACT; return m_destination.SetStruct(name, numFields, const_cast(fieldTypeNames)); } - - STDMETHOD(SetEnum)(PCWSTR name, PCWSTR baseType) - { WRAPPER_NO_CONTRACT; return m_destination.SetEnum(name, baseType); } - - STDMETHOD(SetParameterizedInterface)(GUID piid, UINT32 numArgs) - { WRAPPER_NO_CONTRACT; return m_destination.SetParameterizedInterface(piid, numArgs); } - - STDMETHOD(SetParameterizedDelegate)(GUID piid, UINT32 numArgs) - { WRAPPER_NO_CONTRACT; return m_destination.SetParameterizedDelegate(piid, numArgs); } - }; - - ::IRoMetaDataLocator &m_locator; - -public: - MetaDataLocatorWrapper(::IRoMetaDataLocator &locator) - : m_locator(locator) - { } - - STDMETHOD(Locate)(PCWSTR nameElement, ParamInstanceAPI_StaticallyLinked::IRoSimpleMetaDataBuilder &destination) const - { - CONTRACTL - { - THROWS; - GC_TRIGGERS; - MODE_ANY; - } - CONTRACTL_END; - - SimpleMetaDataBuilderWrapper destinationWrapper(destination); - return m_locator.Locate(nameElement, destinationWrapper); - } -}; - - -//-------------------------------------------------------------------------- -// pGuid is filled with the constructed IID by the function. -// static -void WinRTGuidGenerator::ComputeGuidForGenericType(MethodTable *pMT, GUID *pGuid) -{ - CONTRACTL - { - THROWS; - GC_TRIGGERS; - MODE_ANY; - PRECONDITION(pMT->SupportsGenericInterop(TypeHandle::Interop_NativeToManaged)); - } - CONTRACTL_END; - - // throw a nice exception if the instantiation is not WinRT-legal - if (!pMT->IsLegalNonArrayWinRTType()) - { - StackSString ss; - TypeString::AppendType(ss, TypeHandle(pMT)); - COMPlusThrowHR(COR_E_BADIMAGEFORMAT, IDS_EE_WINRT_IID_ILLEGALTYPE, ss.GetUnicode()); - } - - // create an array of name elements describing the type - SArray namesBuf; - PCWSTR *pNamePointers; - COUNT_T cNames; - PopulateNames(pMT, namesBuf, pNamePointers, cNames); - - // pass the array to the REX API - MetaDataLocator metadataLocator; -#ifndef CROSSGEN_COMPILE - if (WinRTSupported()) - { - IfFailThrow(RoGetParameterizedTypeInstanceIID( - cNames, - pNamePointers, - metadataLocator, - pGuid, - NULL)); - -#ifdef _DEBUG - // assert that the two implementations computed the same Guid - GUID pGuidForAssert; - - MetaDataLocatorWrapper metadataLocatorWrapper(metadataLocator); - IfFailThrow(ParamInstanceAPI_StaticallyLinked::RoGetParameterizedTypeInstanceIID( - cNames, - pNamePointers, - metadataLocatorWrapper, - &pGuidForAssert, - NULL)); - - _ASSERTE_MSG(*pGuid == pGuidForAssert, "Guid computed by Win8 API does not match the one computed by statically linked RoGetParameterizedTypeInstanceIID"); -#endif // _DEBUG - } - else -#endif //#ifndef CROSSGEN_COMPILE - { - // we should not be calling this on downlevel outside of NGEN - _ASSERTE(GetAppDomain()->IsCompilationDomain()); - - MetaDataLocatorWrapper metadataLocatorWrapper(metadataLocator); - IfFailThrow(ParamInstanceAPI_StaticallyLinked::RoGetParameterizedTypeInstanceIID( - cNames, - pNamePointers, - metadataLocatorWrapper, - pGuid, - NULL)); - } -} - -// Returns MethodTable (typical instantiation) of the mscorlib copy of the specified redirected WinRT interface. -MethodTable *WinRTInterfaceRedirector::GetWinRTTypeForRedirectedInterfaceIndex(WinMDAdapter::RedirectedTypeIndex index) -{ - CONTRACT(MethodTable *) - { - THROWS; - GC_TRIGGERS; - MODE_ANY; - POSTCONDITION(CheckPointer(RETVAL)); - } - CONTRACT_END; - - BinderClassID id = s_rInterfaceStubInfos[GetStubInfoIndex(index)].m_WinRTInterface; - - if ((id & NON_MSCORLIB_MARKER) == 0) - { - // the redirected interface lives in mscorlib - RETURN MscorlibBinder::GetClass(id); - } - else - { - // the redirected interface lives in some other Framework assembly - const NonMscorlibRedirectedInterfaceInfo *pInfo = &s_rNonMscorlibInterfaceInfos[id & ~NON_MSCORLIB_MARKER]; - SString assemblyQualifiedTypeName(SString::Utf8, pInfo->m_szWinRTInterfaceAssemblyQualifiedTypeName); - - RETURN TypeName::GetTypeFromAsmQualifiedName(assemblyQualifiedTypeName.GetUnicode()).GetMethodTable(); - } -} - -// -MethodDesc *WinRTInterfaceRedirector::LoadMethodFromRedirectedAssembly(LPCUTF8 szAssemblyQualifiedTypeName, LPCUTF8 szMethodName) -{ - CONTRACTL - { - THROWS; - GC_TRIGGERS; - MODE_ANY; - } - CONTRACTL_END; - - SString assemblyQualifiedTypeName(SString::Utf8, szAssemblyQualifiedTypeName); - - MethodTable *pMT = TypeName::GetTypeFromAsmQualifiedName(assemblyQualifiedTypeName.GetUnicode()).GetMethodTable(); - return MemberLoader::FindMethodByName(pMT, szMethodName); -} - -#ifdef _DEBUG -void WinRTInterfaceRedirector::VerifyRedirectedInterfaceStubs() -{ - CONTRACTL - { - THROWS; - GC_TRIGGERS; - MODE_ANY; - } - CONTRACTL_END; - - // Verify signatures of all stub methods by calling GetStubMethodForRedirectedInterface with all valid - // combination of arguments. - for (int i = 0; i < WinMDAdapter::RedirectedTypeIndex_Count; i++) - { - if (i == WinMDAdapter::RedirectedTypeIndex_System_Collections_Generic_IEnumerable || - i == WinMDAdapter::RedirectedTypeIndex_System_Collections_Generic_IList || - i == WinMDAdapter::RedirectedTypeIndex_System_Collections_Generic_IDictionary || - i == WinMDAdapter::RedirectedTypeIndex_System_Collections_Generic_IReadOnlyList || - i == WinMDAdapter::RedirectedTypeIndex_System_Collections_Generic_IReadOnlyDictionary || - i == WinMDAdapter::RedirectedTypeIndex_System_IDisposable) - { - int stubInfoIndex = GetStubInfoIndex((WinMDAdapter::RedirectedTypeIndex)i); - - // WinRT -> CLR - for (int slot = 0; slot < s_rInterfaceStubInfos[stubInfoIndex].m_iCLRMethodCount; slot++) - { - GetStubMethodForRedirectedInterface((WinMDAdapter::RedirectedTypeIndex)i, slot, TypeHandle::Interop_ManagedToNative, FALSE); - } - if (i == WinMDAdapter::RedirectedTypeIndex_System_Collections_Generic_IList || - i == WinMDAdapter::RedirectedTypeIndex_System_Collections_Generic_IDictionary) - { - // WinRT -> CLR ICollection - for (int slot = 0; slot < s_rInterfaceStubInfos[stubInfoIndex + s_NumRedirectedInterfaces].m_iCLRMethodCount; slot++) - { - GetStubMethodForRedirectedInterface((WinMDAdapter::RedirectedTypeIndex)i, slot, TypeHandle::Interop_ManagedToNative, TRUE); - } - } - - // CLR -> WinRT - for (int slot = 0; slot < s_rInterfaceStubInfos[stubInfoIndex].m_iWinRTMethodCount; slot++) - { - GetStubMethodForRedirectedInterface((WinMDAdapter::RedirectedTypeIndex)i, slot, TypeHandle::Interop_NativeToManaged, FALSE); - } - } - } -} -#endif // _DEBUG + // -// Returns a MethodDesc to be used as an interop stub for the given redirected interface/slot/direction. -MethodDesc *WinRTInterfaceRedirector::GetStubMethodForRedirectedInterface(WinMDAdapter::RedirectedTypeIndex interfaceIndex, - int slot, - TypeHandle::InteropKind interopKind, - BOOL fICollectionStub, - Instantiation methodInst /*= Instantiation()*/) -{ - CONTRACTL + if (srefServer != NULL) { - THROWS; - GC_TRIGGERS; - MODE_ANY; - PRECONDITION(!(fICollectionStub && interopKind == TypeHandle::Interop_NativeToManaged)); - } - CONTRACTL_END; + int len = srefServer->GetStringLength(); - int stubInfoIndex = GetStubInfoIndex(interfaceIndex); - _ASSERTE(stubInfoIndex < s_NumRedirectedInterfaces); - _ASSERTE(stubInfoIndex < _countof(s_rInterfaceStubInfos)); + wszServer = new WCHAR[len+1]; - const RedirectedInterfaceStubInfo *pStubInfo; - pStubInfo = &s_rInterfaceStubInfos[fICollectionStub ? stubInfoIndex + s_NumRedirectedInterfaces : stubInfoIndex]; + if (len) + memcpy(wszServer, srefServer->GetBuffer(), (len*2)); - BinderMethodID method; - if (interopKind == TypeHandle::Interop_NativeToManaged) - { - _ASSERTE(slot < pStubInfo->m_iWinRTMethodCount); - method = pStubInfo->m_rWinRTStubMethods[slot]; - } - else - { - _ASSERTE(slot < pStubInfo->m_iCLRMethodCount); - method = pStubInfo->m_rCLRStubMethods[slot]; + wszServer[len] = W('\0'); } - MethodDesc *pMD; - if ((pStubInfo->m_WinRTInterface & NON_MSCORLIB_MARKER) == 0) + + // + // If no server name has been specified, see if we can find the well known + // managed class for this CLSID. + // + + if (bServerIsLocal) { - if (!methodInst.IsEmpty() && - (method == METHOD__ITERABLE_TO_ENUMERABLE_ADAPTER__GET_ENUMERATOR_STUB || - method == METHOD__IVECTORVIEW_TO_IREADONLYLIST_ADAPTER__INDEXER_GET)) + // @TODO(DM): Do we really need to be this forgiving ? We should + // look into letting the type load exceptions percolate + // up to the user instead of swallowing them and using __ComObject. + EX_TRY { - if (GetStructureBaseType(methodInst) != BaseType_None) - { - // This instantiation has ambiguous run-time behavior because it can be assigned by co-variance - // from another instantiation in which the type argument is not an interface pointer in the WinRT - // world. We have to use a special stub for these which performs a run-time check to see how to - // marshal the argument. - - method = (method == METHOD__ITERABLE_TO_ENUMERABLE_ADAPTER__GET_ENUMERATOR_STUB) ? - METHOD__ITERABLE_TO_ENUMERABLE_ADAPTER__GET_ENUMERATOR_VARIANCE_STUB : - METHOD__IVECTORVIEW_TO_IREADONLYLIST_ADAPTER__INDEXER_GET_VARIANCE; - } + pMT = GetTypeForCLSID(clsid); } - - pMD = MscorlibBinder::GetMethod(method); - } - else - { - // the stub method does not live in mscorlib - const NonMscorlibRedirectedInterfaceInfo *pInfo = &s_rNonMscorlibInterfaceInfos[pStubInfo->m_WinRTInterface & ~NON_MSCORLIB_MARKER]; - - pMD = LoadMethodFromRedirectedAssembly( - (interopKind == TypeHandle::Interop_NativeToManaged) ? pInfo->m_szWinRTStubClassAssemblyQualifiedTypeName : pInfo->m_szCLRStubClassAssemblyQualifiedTypeName, - pInfo->m_rszMethodNames[method]); + EX_CATCH + { + } + EX_END_CATCH(RethrowTerminalExceptions) } -#ifdef _DEBUG - // Verify that the signature of the stub method matches the corresponding interface method. - MethodTable *pItfMT = NULL; - Instantiation inst = pMD->GetMethodInstantiation(); - TypeHandle thKvPair; - - if (interopKind == TypeHandle::Interop_NativeToManaged) + if (pMT != NULL) { - // we are interested in the WinRT interface method - pItfMT = GetWinRTTypeForRedirectedInterfaceIndex(interfaceIndex); + // + // There is a managed class for this CLSID. + // + + *pRef = pMT->GetManagedClassObject(); } else { - // we are interested in the CLR interface method - if (fICollectionStub) - { - if (pMD->HasMethodInstantiation()) - { - if (interfaceIndex == WinMDAdapter::RedirectedTypeIndex_Windows_Foundation_Collections_IVectorView || - interfaceIndex == WinMDAdapter::RedirectedTypeIndex_Windows_Foundation_Collections_IMapView) - pItfMT = MscorlibBinder::GetExistingClass(CLASS__IREADONLYCOLLECTIONGENERIC); - else - pItfMT = MscorlibBinder::GetExistingClass(CLASS__ICOLLECTIONGENERIC); + // Check if we have in the hash. + OBJECTHANDLE hRef; + ClassFactoryInfo ClassFactInfo; + ClassFactInfo.m_clsid = clsid; + ClassFactInfo.m_strServerName = wszServer; + EEClassFactoryInfoHashTable *pClassFactHash = GetAppDomain()->GetClassFactHash(); - if (interfaceIndex == WinMDAdapter::RedirectedTypeIndex_System_Collections_Generic_IDictionary || - interfaceIndex == WinMDAdapter::RedirectedTypeIndex_System_Collections_Generic_IReadOnlyDictionary) - { - thKvPair = TypeHandle(MscorlibBinder::GetClass(CLASS__KEYVALUEPAIRGENERIC)).Instantiate(inst); - inst = Instantiation(&thKvPair, 1); - } - } - else - { - pItfMT = MscorlibBinder::GetExistingClass(CLASS__ICOLLECTION); - } + if (pClassFactHash->GetValue(&ClassFactInfo, (HashDatum*) &hRef)) + { + *pRef = ObjectFromHandle(hRef); } else { - pItfMT = GetAppDomain()->GetRedirectedType(interfaceIndex); + GetComClassHelper(pRef, pClassFactHash, &ClassFactInfo, NULL); } } - // get signature of the stub method - PCCOR_SIGNATURE pSig1; - DWORD cSig1; - - pMD->GetSig(&pSig1, &cSig1); - SigTypeContext typeContext1; - SigTypeContext::InitTypeContext(Instantiation(), pMD->GetMethodInstantiation(), &typeContext1); - MetaSig sig1(pSig1, cSig1, pMD->GetModule(), &typeContext1); - - // get signature of the interface method - PCCOR_SIGNATURE pSig2; - DWORD cSig2; - - MethodDesc *pItfMD = pItfMT->GetMethodDescForSlot(slot); - pItfMD->GetSig(&pSig2, &cSig2); - SigTypeContext typeContext2; - SigTypeContext::InitTypeContext(inst, Instantiation(), &typeContext2); - MetaSig sig2(pSig2, cSig2, pItfMD->GetModule(), &typeContext2); - - _ASSERTE_MSG(MetaSig::CompareMethodSigs(sig1, sig2, FALSE), "Stub method signature does not match the corresponding interface method."); -#endif // _DEBUG + // If we made it this far *pRef better be set. + _ASSERTE(*pRef != NULL); +} - if (!methodInst.IsEmpty()) - { - _ASSERTE(pMD->HasMethodInstantiation()); - _ASSERTE(pMD->GetNumGenericMethodArgs() == methodInst.GetNumArgs()); +#endif // FEATURE_COMINTEROP_UNMANAGED_ACTIVATION && FEATURE_CLASSIC_COMINTEROP - pMD = MethodDesc::FindOrCreateAssociatedMethodDesc( - pMD, - pMD->GetMethodTable(), - FALSE, // forceBoxedEntryPoint - methodInst, // methodInst - FALSE, // allowInstParam - TRUE); // forceRemotableMethod - } +#endif //#ifndef CROSSGEN_COMPILE - return pMD; -} -// static -MethodDesc *WinRTInterfaceRedirector::GetStubMethodForRedirectedInterfaceMethod(MethodDesc *pMD, TypeHandle::InteropKind interopKind) +#ifdef FEATURE_COMINTEROP_UNMANAGED_ACTIVATION +//------------------------------------------------------------- +// check if a ComClassFactory has been setup for this class +// if not set one up +ClassFactoryBase *GetComClassFactory(MethodTable* pClassMT) { - CONTRACTL + CONTRACT (ClassFactoryBase*) { THROWS; GC_TRIGGERS; MODE_ANY; + INJECT_FAULT(ThrowOutOfMemory()); + PRECONDITION(CheckPointer(pClassMT)); + PRECONDITION(pClassMT->IsComObjectType()); + POSTCONDITION(CheckPointer(RETVAL)); } - CONTRACTL_END; - - MethodTable *pMT = pMD->GetMethodTable(); + CONTRACT_END; - // - // If we are calling into a class method instead of interface method, - // convert it to first implemented interface method (we are always calling into the first - // one - see code:ComPlusCall::PopulateComPlusCallMethodDesc for more details) - // - if (!pMT->IsInterface()) + // Work our way up the hierachy until we find the first COM import type. + while (!pClassMT->IsComImport()) { - pMD = pMD->GetInterfaceMD(); - pMT = pMD->GetMethodTable(); + pClassMT = pClassMT->GetParentMethodTable(); + _ASSERTE(pClassMT != NULL); + _ASSERTE(pClassMT->IsComObjectType()); } - bool fICollectionStub = false; - if (interopKind == TypeHandle::Interop_ManagedToNative) + // check if com data has been setup for this class + ClassFactoryBase *pClsFac = pClassMT->GetComClassFactory(); + + if (pClsFac == NULL) { - MethodTable *pResolvedMT = RCW::ResolveICollectionInterface(pMT, TRUE /* fPreferIDictionary */, NULL); - if (pResolvedMT != NULL) + NewHolder pNewFactory; + + GUID guid; + pClassMT->GetGuid(&guid, TRUE); + + ComClassFactory *pComClsFac = ComClassFactoryCreator::Create(guid); + + pNewFactory = pComClsFac; + + pComClsFac->Init(NULL, NULL, pClassMT); + + // store the class factory in EE Class + if (!pClassMT->SetComClassFactory(pNewFactory)) { - fICollectionStub = true; - pMT = pResolvedMT; + // another thread beat us to it + pNewFactory = pClassMT->GetComClassFactory(); } - } - WinMDAdapter::RedirectedTypeIndex index; - if (WinRTInterfaceRedirector::ResolveRedirectedInterface(pMT, &index)) - { - // make sure we return an exact MD that takes no extra instantiating arguments - return WinRTInterfaceRedirector::GetStubMethodForRedirectedInterface( - index, - pMD->GetSlot(), - interopKind, - fICollectionStub, - pMT->GetInstantiation()); + pClsFac = pNewFactory.Extract(); } - return NULL; + RETURN pClsFac; } +#endif // FEATURE_COMINTEROP_UNMANAGED_ACTIVATION -// static -MethodTable *WinRTDelegateRedirector::GetWinRTTypeForRedirectedDelegateIndex(WinMDAdapter::RedirectedTypeIndex index) + +//------------------------------------------------------------------- +// void InitializeComInterop() +// Called from EEStartup, to initialize com Interop specific data +// structures. +//------------------------------------------------------------------- +void InitializeComInterop() { CONTRACTL { @@ -5972,26 +4162,18 @@ MethodTable *WinRTDelegateRedirector::GetWinRTTypeForRedirectedDelegateIndex(Win } CONTRACTL_END; - switch (index) - { - case WinMDAdapter::RedirectedTypeIndex_System_EventHandlerGeneric: - return MscorlibBinder::GetClass(CLASS__WINDOWS_FOUNDATION_EVENTHANDLER); - - case WinMDAdapter::RedirectedTypeIndex_System_Collections_Specialized_NotifyCollectionChangedEventHandler: - { - SString assemblyQualifiedTypeName(SString::Utf8, NCCEHWINRT_ASM_QUAL_TYPE_NAME); - return TypeName::GetTypeFromAsmQualifiedName(assemblyQualifiedTypeName.GetUnicode()).GetMethodTable(); - } - - case WinMDAdapter::RedirectedTypeIndex_System_ComponentModel_PropertyChangedEventHandler: - { - SString assemblyQualifiedTypeName(SString::Utf8, PCEHWINRT_ASM_QUAL_TYPE_NAME); - return TypeName::GetTypeFromAsmQualifiedName(assemblyQualifiedTypeName.GetUnicode()).GetMethodTable(); - } - - default: - UNREACHABLE(); - } + InitializeSListHead(&RCW::s_RCWStandbyList); + ComCall::Init(); +#ifdef TARGET_X86 + ComPlusCall::Init(); +#endif +#ifndef CROSSGEN_COMPILE + CtxEntryCache::Init(); + ComCallWrapperTemplate::Init(); +#ifdef _DEBUG + IntializeInteropLogging(); +#endif //_DEBUG +#endif //CROSSGEN_COMPILE } #ifndef CROSSGEN_COMPILE @@ -6317,12 +4499,10 @@ IUnknown* MarshalObjectToInterface(OBJECTREF* ppObject, MethodTable* pItfMT, Met // When an interface method table is specified, fDispIntf must be consistent with the // interface type. BOOL bDispatch = (dwFlags & ItfMarshalInfo::ITF_MARSHAL_DISP_ITF); - BOOL bInspectable = (dwFlags & ItfMarshalInfo::ITF_MARSHAL_INSP_ITF); BOOL bUseBasicItf = (dwFlags & ItfMarshalInfo::ITF_MARSHAL_USE_BASIC_ITF); _ASSERTE(!pItfMT || (!pItfMT->IsInterface() && bDispatch) || - (!!bDispatch == IsDispatchBasedItf(pItfMT->GetComInterfaceType())) || - (!!bInspectable == (pItfMT->GetComInterfaceType() == ifInspectable) || pItfMT->IsWinRTRedirectedInterface(TypeHandle::Interop_ManagedToNative))); + (!!bDispatch == IsDispatchBasedItf(pItfMT->GetComInterfaceType()))); if (pItfMT) { @@ -6334,7 +4514,7 @@ IUnknown* MarshalObjectToInterface(OBJECTREF* ppObject, MethodTable* pItfMT, Met } else { - ComIpType ReqIpType = bDispatch ? ComIpType_Dispatch : (bInspectable ? ComIpType_Inspectable : ComIpType_Unknown); + ComIpType ReqIpType = bDispatch ? ComIpType_Dispatch : ComIpType_Unknown; return GetComIPFromObjectRef(ppObject, ReqIpType, NULL); } } @@ -6368,15 +4548,12 @@ void UnmarshalObjectFromInterface(OBJECTREF *ppObjectDest, IUnknown **ppUnkSrc, if (fIsInterface) { - if ((dwFlags & ItfMarshalInfo::ITF_MARSHAL_WINRT_SCENARIO) == 0) + // We only verify that the object supports the interface for non-WinRT scenarios because we + // believe that the likelihood of improperly constructed programs is significantly lower + // with WinRT and the Object::SupportsInterface check is very expensive. + if (!Object::SupportsInterface(*ppObjectDest, pItfMT)) { - // We only verify that the object supports the interface for non-WinRT scenarios because we - // believe that the likelihood of improperly constructed programs is significantly lower - // with WinRT and the Object::SupportsInterface check is very expensive. - if (!Object::SupportsInterface(*ppObjectDest, pItfMT)) - { - COMPlusThrowInvalidCastException(ppObjectDest, TypeHandle(pItfMT)); - } + COMPlusThrowInvalidCastException(ppObjectDest, TypeHandle(pItfMT)); } } } @@ -6441,161 +4618,6 @@ MethodTable* GetClassFromIProvideClassInfo(IUnknown* pUnk) #endif // FEATURE_CLASSIC_COMINTEROP - -enum IInspectableQueryResults { - IInspectableQueryResults_SupportsIReference = 0x1, - IInspectableQueryResults_SupportsIReferenceArray = 0x2, -}; - -//-------------------------------------------------------------------------------- -// Try to get the class from IInspectable. If *pfSupportsIInspectable is true, pUnk -// is assumed to be an IInspectable-derived interface. Otherwise, this function will -// QI for IInspectable and set *pfSupportsIInspectable accordingly. - -TypeHandle GetClassFromIInspectable(IUnknown* pUnk, bool *pfSupportsIInspectable, bool *pfSupportsIReference, bool *pfSupportsIReferenceArray) -{ - CONTRACT (TypeHandle) - { - THROWS; - GC_TRIGGERS; - MODE_ANY; - PRECONDITION(CheckPointer(pUnk)); - PRECONDITION(CheckPointer(pfSupportsIInspectable)); - PRECONDITION(CheckPointer(pfSupportsIReference)); - PRECONDITION(CheckPointer(pfSupportsIReferenceArray)); - } - CONTRACT_END; - - *pfSupportsIReference = false; - *pfSupportsIReferenceArray = false; - - HRESULT hr = S_OK; - - SafeComHolder pInsp = NULL; - if (*pfSupportsIInspectable) - { - // we know that pUnk is an IInspectable - pInsp = static_cast(pUnk); - pInsp.SuppressRelease(); - } - else - { - hr = SafeQueryInterface(pUnk, IID_IInspectable, (IUnknown **)&pInsp); - LogInteropQI(pUnk, IID_IInspectable, hr, "GetClassFromIInspectable: QIing for IInspectable"); - - if (SUCCEEDED(hr)) - { - *pfSupportsIInspectable = true; - } - else - { - RETURN TypeHandle(); - } - } - - WinRtString winrtClassName; - { - GCX_PREEMP(); - if (FAILED(pInsp->GetRuntimeClassName(winrtClassName.Address()))) - { - RETURN TypeHandle(); - } - } - - // Early return if the class name is NULL - if (winrtClassName == NULL) - RETURN TypeHandle(); - - // we have a class name - UINT32 cchClassName; - LPCWSTR pwszClassName = winrtClassName.GetRawBuffer(&cchClassName); - SString ssClassName(SString::Literal, pwszClassName, cchClassName); - - - // Check a cache to see if this has already been looked up. - AppDomain *pDomain = GetAppDomain(); - UINT vCacheVersion = 0; - BYTE bFlags; - TypeHandle classTypeHandle = pDomain->LookupTypeByName(ssClassName, &vCacheVersion, &bFlags); - - if (!classTypeHandle.IsNull()) - { - *pfSupportsIReference = ((bFlags & IInspectableQueryResults_SupportsIReference) != 0); - *pfSupportsIReferenceArray = ((bFlags & IInspectableQueryResults_SupportsIReferenceArray) != 0); - } - else - { - // use a copy of the original class name in case we peel off IReference/IReferenceArray below - StackSString ssTmpClassName; - - // Check whether this is a value type, String, or T[] "boxed" in a IReference or IReferenceArray. - if (ssClassName.BeginsWith(W("Windows.Foundation.IReference`1<")) && ssClassName.EndsWith(W(">"))) - { - ssTmpClassName.Set(ssClassName); - ssTmpClassName.Delete(ssTmpClassName.Begin(), _countof(W("Windows.Foundation.IReference`1<")) - 1); - ssTmpClassName.Delete(ssTmpClassName.End() - 1, 1); - *pfSupportsIReference = true; - } - else if (ssClassName.BeginsWith(W("Windows.Foundation.IReferenceArray`1<")) && ssClassName.EndsWith(W(">"))) - { - ssTmpClassName.Set(ssClassName); - ssTmpClassName.Delete(ssTmpClassName.Begin(), _countof(W("Windows.Foundation.IReferenceArray`1<")) - 1); - ssTmpClassName.Delete(ssTmpClassName.End() - 1, 1); - *pfSupportsIReferenceArray = true; - } - - EX_TRY - { - LPCWSTR pszWinRTTypeName = (ssTmpClassName.IsEmpty() ? ssClassName : ssTmpClassName); - classTypeHandle = WinRTTypeNameConverter::LoadManagedTypeForWinRTTypeName(pszWinRTTypeName, /* pLoadBinder */ nullptr, /*pbIsPrimitive = */ nullptr); - } - EX_CATCH - { - } - EX_END_CATCH(RethrowTerminalExceptions) - - if (!classTypeHandle.IsNull()) - { - // cache the (positive) result - BYTE bFlags = 0; - if (*pfSupportsIReference) - bFlags |= IInspectableQueryResults_SupportsIReference; - if (*pfSupportsIReferenceArray) - bFlags |= IInspectableQueryResults_SupportsIReferenceArray; - pDomain->CacheTypeByName(ssClassName, vCacheVersion, classTypeHandle, bFlags); - } - } - - RETURN classTypeHandle; -} - - -ABI::Windows::Foundation::IUriRuntimeClass *CreateWinRTUri(LPCWSTR wszUri, INT32 cchUri) -{ - STANDARD_VM_CONTRACT; - - UriMarshalingInfo* marshalingInfo = GetAppDomain()->GetLoaderAllocator()->GetMarshalingData()->GetUriMarshalingInfo(); - - // Get the cached factory from the UriMarshalingInfo object of the current appdomain - ABI::Windows::Foundation::IUriRuntimeClassFactory* pFactory = marshalingInfo->GetUriFactory(); - - SafeComHolder pIUriRC; - HRESULT hrCreate = pFactory->CreateUri(WinRtStringRef(wszUri, cchUri), &pIUriRC); - if (FAILED(hrCreate)) - { - if (hrCreate == E_INVALIDARG) - { - COMPlusThrow(kArgumentException, IDS_EE_INVALIDARG_WINRT_INVALIDURI); - } - else - { - ThrowHR(hrCreate); - } - } - - return pIUriRC.Extract(); -} - static void DECLSPEC_NORETURN ThrowTypeLoadExceptionWithInner(MethodTable *pClassMT, LPCWSTR pwzName, HRESULT hr, unsigned resID) { CONTRACTL @@ -6629,72 +4651,7 @@ void GetNativeWinRTFactoryObject(MethodTable *pMT, Thread *pThread, MethodTable } CONTRACTL_END; - if (!WinRTSupported()) - { - COMPlusThrow(kPlatformNotSupportedException, W("PlatformNotSupported_WinRT")); - } - - HSTRING hName = GetComClassFactory(pMT)->AsWinRTClassFactory()->GetClassName(); - - HRESULT hr; - SafeComHolder pFactory; - { - GCX_PREEMP(); - hr = clr::winrt::GetActivationFactory(hName, &pFactory); - } - - // There are a few particular failures that we'd like to map a specific exception type to - // - the factory interface is for a WinRT type which is not registered => TypeLoadException - // - the factory interface is not a factory for the WinRT type => ArgumentException - if (hr == REGDB_E_CLASSNOTREG) - { - ThrowTypeLoadExceptionWithInner(pMT, WindowsGetStringRawBuffer(hName, nullptr), hr, IDS_EE_WINRT_TYPE_NOT_REGISTERED); - } - else if (hr == E_NOINTERFACE) - { - LPCWSTR wzTN = WindowsGetStringRawBuffer(hName, nullptr); - if (pFactoryIntfMT) - { - InlineSString ssFactoryName; - pFactoryIntfMT->_GetFullyQualifiedNameForClass(ssFactoryName); - EEMessageException ex(hr); - EX_THROW_WITH_INNER(EEMessageException, (kArgumentException, IDS_EE_WINRT_NOT_FACTORY_FOR_TYPE, ssFactoryName.GetUnicode(), wzTN), &ex); - } - else - { - EEMessageException ex(hr); - EX_THROW_WITH_INNER(EEMessageException, (kArgumentException, IDS_EE_WINRT_INVALID_FACTORY_FOR_TYPE, wzTN), &ex); - } - } - else - { - IfFailThrow(hr); - } - - DWORD flags = - RCW::CF_SupportsIInspectable | // Returns a WinRT RCW - RCW::CF_DontResolveClass; // Don't care about the exact type - - flags |= RCW::CF_DetectDCOMProxy; // Attempt to detect that the factory is a DCOM proxy in order to suppress caching - - if (bNeedUniqueRCW) - flags |= RCW::CF_NeedUniqueObject; // Returns a unique RCW - - COMInterfaceMarshaler marshaler; - marshaler.Init( - pFactory, - g_pBaseCOMObject, // Always System.__ComObject - pThread, - flags - ); - - if (pCallback) - marshaler.SetCallback(pCallback); - - // Find an existing RCW or create a new RCW - *prefFactory = marshaler.FindOrCreateObjectRef(pFactory); - - return; + COMPlusThrow(kPlatformNotSupportedException, W("PlatformNotSupported_WinRT")); } #endif //#ifndef CROSSGEN_COMPILE diff --git a/src/coreclr/src/vm/interoputil.h b/src/coreclr/src/vm/interoputil.h index 500bada..1b889b9 100644 --- a/src/coreclr/src/vm/interoputil.h +++ b/src/coreclr/src/vm/interoputil.h @@ -20,11 +20,6 @@ do {if ((EXPR) == 0) {ThrowOutOfMemory();} } while (0) #define GET_VERSION_USHORT_FROM_INT(x) ((x < 0) || (x > (INT)((USHORT)-1))) ? 0 : static_cast(x) #ifdef FEATURE_COMINTEROP -#include "winrttypenameconverter.h" -#include "roparameterizediid.h" -#include "../md/winmd/inc/adapter.h" -#include - // The format string to use to format unknown members to be passed to // invoke member #define DISPID_NAME_FORMAT_STRING W("[DISPID=%i]") @@ -64,18 +59,6 @@ class InteropSyncBlockInfo; #endif //FEATURE_COMINTEROP -#if FEATURE_COMINTEROP -#include -#endif -#ifndef __IRestrictedErrorInfo_INTERFACE_DEFINED__ -DEFINE_GUID(IID_IRestrictedErrorInfo, 0x82BA7092,0x4C88,0x427D,0xA7,0xBC,0x16,0xDD,0x93,0xFE,0xB6,0x7E); -MIDL_INTERFACE("82BA7092-4C88-427D-A7BC-16DD93FEB67E") -IRestrictedErrorInfo : public IUnknown -{ -public: -}; -#endif // !__IRestrictedErrorInfo_INTERFACE_DEFINED__ - class FieldDesc; struct ExceptionData; @@ -83,15 +66,10 @@ struct ExceptionData; // setup error info for exception object // #ifdef FEATURE_COMINTEROP -HRESULT SetupErrorInfo(OBJECTREF pThrownObject, ComCallMethodDesc *pCMD); -HRESULT SafeGetRestrictedErrorInfo(IRestrictedErrorInfo **ppIErrInfo); BOOL IsManagedObject(IUnknown *pErrInfo); -IErrorInfo *GetCorrepondingErrorInfo_WinRT(HRESULT hr, IRestrictedErrorInfo *pResErrInfo, BOOL* bHasLangRestrictedErrInfo); -HRESULT GetRestrictedErrorDetails(IRestrictedErrorInfo *pRestrictedErrorInfo, BSTR *perrorDescription, BSTR *pErrorRestrictedDescription, HRESULT *hr, BSTR *pErrorCapabilitySid); - #endif // FEATURE_COMINTEROP -HRESULT SetupErrorInfo(OBJECTREF pThrownObject, BOOL bIsWinRTScenario = FALSE); +HRESULT SetupErrorInfo(OBJECTREF pThrownObject); //-------------------------------------------------------------------------------- // Release helper, enables and disables GC during call-outs @@ -132,8 +110,7 @@ CorClassIfaceAttr ReadClassInterfaceTypeCustomAttribute(TypeHandle type); //------------------------------------------------------------------- void FillExceptionData( _Inout_ ExceptionData* pedata, - _In_ IErrorInfo* pErrInfo, - _In_opt_ IRestrictedErrorInfo* pRestrictedErrorInfo); + _In_ IErrorInfo* pErrInfo); //--------------------------------------------------------------------------- // If pImport has the DefaultDllImportSearchPathsAttribute, @@ -207,7 +184,7 @@ void MinorCleanupSyncBlockComData(InteropSyncBlockInfo* pInteropInfo); // Helper to release all of the RCWs in the specified context, across all caches. // If context is null, release all RCWs, otherwise release RCWs created in the -// given context, including Jupiter RCWs +// given context. void ReleaseRCWsInCaches(LPVOID pCtxCookie); // A wrapper that catches all exceptions - used in the OnThreadTerminate case. @@ -387,7 +364,7 @@ void GetComClassFromProgID(STRINGREF srefProgID, STRINGREF srefServer, OBJECTREF void GetComClassFromCLSID(REFCLSID clsid, STRINGREF srefServer, OBJECTREF* pRef); //------------------------------------------------------------- -// check if a ComClassFactory/WinRTClassFactory has been setup for this class +// check if a ComClassFactory has been setup for this class // if not set one up ClassFactoryBase *GetComClassFactory(MethodTable* pClassMT); #endif // FEATURE_COMINTEROP_UNMANAGED_ACTIVATION @@ -441,48 +418,12 @@ HRESULT GetCLSIDFromProgID(__in_z WCHAR *strProgId, GUID *pGuid); // out the class from there MethodTable* GetClassFromIProvideClassInfo(IUnknown* pUnk); -//-------------------------------------------------------------------------------- -// Try to load a WinRT type. -TypeHandle LoadWinRTType(SString* ssTypeName, BOOL bThrowIfNotFound, ICLRPrivBinder* loadBinder = nullptr); - -//-------------------------------------------------------------------------------- -// Try to get the class from IInspectable. -TypeHandle GetClassFromIInspectable(IUnknown* pUnk, bool *pfSupportsIInspectable, bool *pfSupportsIReference, bool *pfSupportsIReferenceArray); - -//-------------------------------------------------------------------------------- -// Build a WinRT URI for a given raw URI -ABI::Windows::Foundation::IUriRuntimeClass *CreateWinRTUri(LPCWSTR wszUri, INT32 cchUri); - -// Generates GUIDs for parameterized WinRT types. -class WinRTGuidGenerator -{ - class MetaDataLocator : public IRoMetaDataLocator - { - // IRoMetaDataLocator implementation: - STDMETHOD(Locate)(PCWSTR nameElement, IRoSimpleMetaDataBuilder &metaDataDestination) const; - - // helper methods: - static HRESULT LocateTypeWithDefaultInterface(MethodTable *pMT, LPCWSTR pszName, IRoSimpleMetaDataBuilder &metaDataDestination); - static HRESULT LocateStructure(MethodTable *pMT, LPCWSTR pszName, IRoSimpleMetaDataBuilder &metaDataDestination); - static HRESULT LocateRedirectedType(MethodTable *pMT, IRoSimpleMetaDataBuilder &metaDataDestination); - }; - - static void PopulateNames(MethodTable *pMT, SArray &namesBuf, PCWSTR* &pszNames, COUNT_T &cNames); - static void PopulateNamesAppendNamePointers(MethodTable *pMT, SArray &namesBuf, PCWSTR* &pszNames, COUNT_T cNames); - static void PopulateNamesAppendTypeName(MethodTable *pMT, SArray &namesBuf, COUNT_T &cNames); -public: - //-------------------------------------------------------------------------- - // pGuid is filled with the constructed IID by the function. - static void ComputeGuidForGenericType(MethodTable *pMT, GUID *pGuid); -}; // class WinRTGuidGenerator - IUnknown* MarshalObjectToInterface(OBJECTREF* ppObject, MethodTable* pItfMT, MethodTable* pClassMT, DWORD dwFlags); void UnmarshalObjectFromInterface(OBJECTREF *ppObjectDest, IUnknown **ppUnkSrc, MethodTable *pItfMT, MethodTable *pClassMT, DWORD dwFlags); #define DEFINE_ASM_QUAL_TYPE_NAME(varname, typename, asmname) static const char varname##[] = { typename##", "##asmname## }; class ICOMInterfaceMarshalerCallback; -void GetNativeWinRTFactoryObject(MethodTable *pMT, Thread *pThread, MethodTable *pFactoryIntfMT, BOOL bNeedUniqueRCW, ICOMInterfaceMarshalerCallback *pCallback, OBJECTREF *prefFactory); #else // FEATURE_COMINTEROP inline HRESULT EnsureComStartedNoThrow() diff --git a/src/coreclr/src/vm/interoputil.inl b/src/coreclr/src/vm/interoputil.inl index 2f8b5df..06363bf 100644 --- a/src/coreclr/src/vm/interoputil.inl +++ b/src/coreclr/src/vm/interoputil.inl @@ -5,7 +5,7 @@ // #include "comcallablewrapper.h" -#ifndef DACCESS_COMPILE +#if !defined(DACCESS_COMPILE) && !defined(CROSSGEN_COMPILE) inline BOOL ComInterfaceSlotIs(IUnknown* pUnk, int slot, LPVOID pvFunction) { CONTRACTL @@ -29,8 +29,7 @@ inline BOOL IsInProcCCWTearOff(IUnknown* pUnk) { WRAPPER_NO_CONTRACT; return ComInterfaceSlotIs(pUnk, 0, Unknown_QueryInterface) || - ComInterfaceSlotIs(pUnk, 0, Unknown_QueryInterface_IErrorInfo) || - ComInterfaceSlotIs(pUnk, 0, Unknown_QueryInterface_ICCW); + ComInterfaceSlotIs(pUnk, 0, Unknown_QueryInterface_IErrorInfo); } // is the tear-off represent one of the standard interfaces such as IProvideClassInfo, IErrorInfo etc. diff --git a/src/coreclr/src/vm/jitinterface.cpp b/src/coreclr/src/vm/jitinterface.cpp index 5006b90..1967821 100644 --- a/src/coreclr/src/vm/jitinterface.cpp +++ b/src/coreclr/src/vm/jitinterface.cpp @@ -13360,13 +13360,6 @@ BOOL LoadDynamicInfoEntry(Module *currentModule, // We do not emit activation fixups for version resilient references. Activate the target explicitly. th.AsMethodTable()->EnsureInstanceActive(); } - else - { -#ifdef FEATURE_WINMD_RESILIENT - // We do not emit activation fixups for version resilient references. Activate the target explicitly. - th.AsMethodTable()->EnsureInstanceActive(); -#endif - } } result = (size_t)th.AsPtr(); @@ -13500,13 +13493,6 @@ BOOL LoadDynamicInfoEntry(Module *currentModule, // We do not emit activation fixups for version resilient references. Activate the target explicitly. pMD->EnsureActive(); } - else - { -#ifdef FEATURE_WINMD_RESILIENT - // We do not emit activation fixups for version resilient references. Activate the target explicitly. - pMD->EnsureActive(); -#endif - } goto MethodEntry; } @@ -14145,7 +14131,7 @@ void CEEInfo::notifyInstructionSetUsage(CORINFO_InstructionSet instructionSet, bool supportEnabled) { LIMITED_METHOD_CONTRACT; - // Do nothing. This api does not provide value in JIT scenarios and + // Do nothing. This api does not provide value in JIT scenarios and // crossgen does not utilize the api either. } diff --git a/src/coreclr/src/vm/jupiterobject.h b/src/coreclr/src/vm/jupiterobject.h deleted file mode 100644 index 46e471c..0000000 --- a/src/coreclr/src/vm/jupiterobject.h +++ /dev/null @@ -1,91 +0,0 @@ -// 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. -// - -// - -/*============================================================ -** -** Header: IJupiterObject.h -** -** -** Purpose: Defines headers used in RCW walk -** -==============================================================*/ - -#ifndef _H_JUPITER_OBJECT_ -#define _H_JUPITER_OBJECT_ - -#ifdef FEATURE_COMINTEROP - -#include "internalunknownimpl.h" - -class ICCW; - -// Windows.UI.Xaml.Hosting.IReferenceTrackerHost -class DECLSPEC_UUID("29a71c6a-3c42-4416-a39d-e2825a07a773") ICLRServices : public IUnknown -{ -public : - STDMETHOD(DisconnectUnusedReferenceSources)(DWORD dwFlags) = 0; - STDMETHOD(ReleaseDisconnectedReferenceSources)() = 0; - STDMETHOD(NotifyEndOfReferenceTrackingOnThread)() = 0; - STDMETHOD(GetTrackerTarget)(IUnknown *pJupiterObject, ICCW **ppNewReference) = 0; - STDMETHOD(AddMemoryPressure)(UINT64 bytesAllocated) = 0; - STDMETHOD(RemoveMemoryPressure)(UINT64 bytesAllocated) = 0; -}; - -// Windows.UI.Xaml.Hosting.IReferenceTrackerManager -class DECLSPEC_UUID("3cf184b4-7ccb-4dda-8455-7e6ce99a3298") IJupiterGCManager : public IUnknown -{ -public : - STDMETHOD(ReferenceTrackingStarted)() = 0; - STDMETHOD(FindTrackerTargetsCompleted)(BOOL bWalkFailed) = 0; - STDMETHOD(ReferenceTrackingCompleted)() = 0; - STDMETHOD(SetReferenceTrackerHost)(/* [in] */ ICLRServices *pCLRServices) = 0; -}; - -// Windows.UI.Xaml.Hosting.IReferenceTrackerTarget -class DECLSPEC_UUID("64bd43f8-bfee-4ec4-b7eb-2935158dae21") ICCW : public IUnknown -{ - -public : - STDMETHOD_(ULONG, AddRefFromReferenceTracker)() = 0; - STDMETHOD_(ULONG, ReleaseFromReferenceTracker)() = 0; - STDMETHOD(Peg)() = 0; - STDMETHOD(Unpeg)() = 0; -}; - -// Windows.UI.Xaml.Hosting.IFindReferenceTargetsCallback -class DECLSPEC_UUID("04b3486c-4687-4229-8d14-505ab584dd88") IFindDependentWrappersCallback : public IUnknown -{ - -public : - STDMETHOD(FoundTrackerTarget)(/* [in] */ ICCW *pCCW) = 0; -}; - -// Windows.UI.Xaml.Hosting.IReferenceTracker -class DECLSPEC_UUID("11d3b13a-180e-4789-a8be-7712882893e6") IJupiterObject : public IUnknown -{ -public : - STDMETHOD(ConnectFromTrackerSource)() = 0; // Notify Jupiter that we've created a new RCW - STDMETHOD(DisconnectFromTrackerSource)() = 0; // Notify Jupiter that we are about to destroy this RCW - STDMETHOD(FindTrackerTargets)(/* [in] */ IFindDependentWrappersCallback *pCallback) = 0; - // Find list of dependent CCWs for this RCW - STDMETHOD(GetReferenceTrackerManager)(/* [out, retval] */ IJupiterGCManager **ppJupiterGCManager) = 0; - // Retrieve IJupiterGCManager interface - STDMETHOD(AddRefFromTrackerSource)() = 0; // Notify Jupiter that we've done a AddRef() - STDMETHOD(ReleaseFromTrackerSource)() = 0; // Notify Jupiter that we are about to do a Release() - STDMETHOD(PegFromTrackerSource)() = 0; // Notify Jupiter that we've returned this IJupiterObject as - // [out] parameter and this IJupiterObject object including - // all its reachable CCWs should be pegged -}; - -extern const IID IID_ICCW; -extern const IID IID_IJupiterObject; -extern const IID IID_IJupiterGCManager; -extern const IID IID_IFindDependentWrappersCallback; - -#endif // FEATURE_COMINTEROP - -#endif // _H_JUPITER_OBJECT_ diff --git a/src/coreclr/src/vm/marshalnative.cpp b/src/coreclr/src/vm/marshalnative.cpp index 75c1e51..ac0d201 100644 --- a/src/coreclr/src/vm/marshalnative.cpp +++ b/src/coreclr/src/vm/marshalnative.cpp @@ -694,25 +694,6 @@ FCIMPL1(int, MarshalNative::GetHRForException, Object* eUNSAFE) } FCIMPLEND -FCIMPL1(int, MarshalNative::GetHRForException_WinRT, Object* eUNSAFE) -{ - CONTRACTL { - NOTHROW; // Used by reverse COM IL stubs, so we must not throw exceptions back to COM - DISABLED(GC_TRIGGERS); // FCALLS with HELPER frames have issues with GC_TRIGGERS - MODE_COOPERATIVE; - } CONTRACTL_END; - - int retVal = 0; - OBJECTREF e = (OBJECTREF) eUNSAFE; - HELPER_METHOD_FRAME_BEGIN_RET_NOTHROW_1({ retVal = COR_E_STACKOVERFLOW; }, e); - - retVal = SetupErrorInfo(e, /* isWinRTScenario = */ TRUE); - - HELPER_METHOD_FRAME_END_NOTHROW(); - return retVal; -} -FCIMPLEND - #ifdef FEATURE_COMINTEROP //==================================================================== @@ -768,9 +749,6 @@ FCIMPL1(ITypeInfo*, MarshalNative::GetITypeInfoForType, ReflectClassBaseObject* TypeHandle th = refClass->GetType(); - if (th.GetMethodTable() != NULL && (th.IsProjectedFromWinRT() || th.IsExportedToWinRT())) - COMPlusThrowArgumentException(W("t"), W("Argument_ObjIsWinRTObject")); - if (th.HasInstantiation()) COMPlusThrowArgumentException(W("t"), W("Argument_NeedNonGenericType")); @@ -901,14 +879,11 @@ FCIMPL4(IUnknown*, MarshalNative::GetComInterfaceForObjectNative, Object* orefUN TypeHandle th = refClass->GetType(); - if (!th.SupportsGenericInterop(TypeHandle::Interop_NativeToManaged)) - { - if (th.HasInstantiation()) - COMPlusThrowArgumentException(W("t"), W("Argument_NeedNonGenericType")); + if (th.HasInstantiation()) + COMPlusThrowArgumentException(W("t"), W("Argument_NeedNonGenericType")); - if (oref->GetMethodTable()->HasInstantiation()) - COMPlusThrowArgumentException(W("o"), W("Argument_NeedNonGenericObject")); - } + if (oref->GetMethodTable()->HasInstantiation()) + COMPlusThrowArgumentException(W("o"), W("Argument_NeedNonGenericObject")); // If the IID being asked for does not represent an interface then // throw an argument exception. @@ -995,7 +970,7 @@ FCIMPL1(Object*, MarshalNative::GetUniqueObjectForIUnknownWithoutUnboxing, IUnkn // Ensure COM is started up. EnsureComStarted(); - GetObjectRefFromComIP(&oref, pUnk, NULL, NULL, ObjFromComIP::UNIQUE_OBJECT | ObjFromComIP::IGNORE_WINRT_AND_SKIP_UNBOXING); + GetObjectRefFromComIP(&oref, pUnk, NULL, NULL, ObjFromComIP::UNIQUE_OBJECT); HELPER_METHOD_FRAME_END(); return OBJECTREFToObject(oref); @@ -1034,9 +1009,6 @@ FCIMPL2(Object*, MarshalNative::GetTypedObjectForIUnknown, IUnknown* pUnk, Refle TypeHandle th = refClass->GetType(); - if (th.GetMethodTable() != NULL && (th.IsProjectedFromWinRT() || th.IsExportedToWinRT())) - COMPlusThrowArgumentException(W("t"), W("Argument_ObjIsWinRTObject")); - if (th.HasInstantiation()) COMPlusThrowArgumentException(W("t"), W("Argument_NeedNonGenericType")); @@ -1078,10 +1050,6 @@ FCIMPL2(IUnknown*, MarshalNative::CreateAggregatedObject, IUnknown* pOuter, Obje if (oref == NULL) COMPlusThrowArgumentNull(W("o")); - MethodTable *pMT = oref->GetMethodTable(); - if (pMT->IsWinRTObjectType() || pMT->IsExportedToWinRT()) - COMPlusThrowArgumentException(W("o"), W("Argument_ObjIsWinRTObject")); - // Ensure COM is started up. EnsureComStarted(); @@ -1810,162 +1778,6 @@ FCIMPL2(void, MarshalNative::ChangeWrapperHandleStrength, Object* orefUNSAFE, CL } FCIMPLEND -FCIMPL2(void, MarshalNative::InitializeWrapperForWinRT, Object *unsafe_pThis, IUnknown **ppUnk) -{ - FCALL_CONTRACT; - - OBJECTREF oref = ObjectToOBJECTREF(unsafe_pThis); - HELPER_METHOD_FRAME_BEGIN_1(oref); - - _ASSERTE(ppUnk != NULL); - if (*ppUnk == NULL) - { - // this should never happen but it's not nice to AV if the factory method is busted and returns NULL - COMPlusThrow(kNullReferenceException); - } - - // the object does not have the right RCW yet - COMInterfaceMarshaler marshaler; - marshaler.Init(*ppUnk, oref->GetMethodTable(), GET_THREAD(), RCW::CF_SupportsIInspectable | RCW::CF_QueryForIdentity); - - // the following will assign NULL to *ppUnk which signals to the caller that we successfully - // initialized the RCW so (*ppUnk)->Release() should be suppressed - marshaler.InitializeExistingComObject(&oref, ppUnk); - - HELPER_METHOD_FRAME_END(); -} -FCIMPLEND - -FCIMPL2(void, MarshalNative::InitializeManagedWinRTFactoryObject, Object *unsafe_pThis, ReflectClassBaseObject *unsafe_pType) -{ - FCALL_CONTRACT; - - OBJECTREF orefThis = ObjectToOBJECTREF(unsafe_pThis); - REFLECTCLASSBASEREF orefType = (REFLECTCLASSBASEREF)ObjectToOBJECTREF(unsafe_pType); - HELPER_METHOD_FRAME_BEGIN_2(orefThis, orefType); - - MethodTable *pMT = orefType->GetType().GetMethodTable(); - - // get the special "factory" template for the type - _ASSERTE(pMT->IsExportedToWinRT()); - WinRTManagedClassFactory *pFactory = GetComClassFactory(pMT)->AsWinRTManagedClassFactory(); - - ComCallWrapperTemplate *pTemplate = pFactory->GetOrCreateComCallWrapperTemplate(orefThis->GetMethodTable()); - - // create a CCW for the factory object using the template - CCWHolder pCCWHold = ComCallWrapper::InlineGetWrapper(&orefThis, pTemplate); - - HELPER_METHOD_FRAME_END(); -} -FCIMPLEND - -// -// Create activation factory and wraps it with a unique RCW -// -// This is necessary because WinRT factories are often implemented as a singleton, -// and getting back a RCW for such WinRT factory would usually get back a RCW from -// another apartment, even if the interface pointe returned from GetActivationFactory -// is a raw pointer. As a result, user would randomly get back RCWs for activation -// factories from other apartments and make transiton to those apartments and cause -// deadlocks and create objects in incorrect apartments -// -// The solution here is to always create a unique RCW -// -FCIMPL1(Object *, MarshalNative::GetNativeActivationFactory, ReflectClassBaseObject *unsafe_pType) -{ - FCALL_CONTRACT; - - REFLECTCLASSBASEREF orefType = (REFLECTCLASSBASEREF)ObjectToOBJECTREF(unsafe_pType); - OBJECTREF orefFactory = NULL; - HELPER_METHOD_FRAME_BEGIN_RET_2(orefFactory, orefType); - - MethodTable *pMT = orefType->GetType().GetMethodTable(); - - // Must be a native WinRT type - _ASSERTE(pMT->IsProjectedFromWinRT()); - - // - // Get the activation factory instance for this WinRT type and create a RCW for it - // - GetNativeWinRTFactoryObject( - pMT, - GET_THREAD(), - NULL, // No factory interface available at this point - TRUE, // Create unique RCW - See comments for this function for more details - NULL, // No callback necessary - &orefFactory // return value - ); - - HELPER_METHOD_FRAME_END(); - - return OBJECTREFToObject(orefFactory); -} -FCIMPLEND - -void QCALLTYPE MarshalNative::GetInspectableIIDs( - QCall::ObjectHandleOnStack hobj, - QCall::ObjectHandleOnStack retArrayGuids) -{ - CONTRACTL - { - QCALL_CHECK; - PRECONDITION(CheckPointer(*hobj.m_ppObject)); - } - CONTRACTL_END; - - BEGIN_QCALL; - - SyncBlock * pSyncBlock = NULL; - - { - GCX_COOP(); - - // set return to failure value - retArrayGuids.Set(NULL); - - OBJECTREF orComObject = NULL; - GCPROTECT_BEGIN(orComObject); - - orComObject = ObjectToOBJECTREF(*hobj.m_ppObject); - - // Validation: hobj represents a non-NULL System.__ComObject instance - if(orComObject == NULL) - COMPlusThrowArgumentNull(W("obj")); - - MethodTable* pMT = orComObject->GetMethodTable(); - PREFIX_ASSUME(pMT != NULL); - if(!pMT->IsComObjectType()) - COMPlusThrow(kArgumentException, IDS_EE_SRC_OBJ_NOT_COMOBJECT); - - // while in cooperative mode, retrieve the object's sync block - pSyncBlock = orComObject->PassiveGetSyncBlock(); - - GCPROTECT_END(); - } // close the GCX_COOP scope - - - InteropSyncBlockInfo * pInteropInfo; - RCW * pRCW; - SafeComHolderPreemp pInspectable; - - // Retrieve obj's IInspectable interface pointer - if (pSyncBlock != NULL - && (pInteropInfo = pSyncBlock->GetInteropInfoNoCreate()) != NULL - && (pRCW = pInteropInfo->GetRawRCW()) != NULL - && (pInspectable = pRCW->GetIInspectable()) != NULL) - { - // retrieve IIDs using IInspectable::GetIids() - ULONG size = 0; - CoTaskMemHolder rgIIDs(NULL); - if (SUCCEEDED(pInspectable->GetIids(&size, &rgIIDs))) - { - retArrayGuids.SetGuidArray(rgIIDs, size); - } - } - - END_QCALL; -} - //==================================================================== // Helper function used in the COM slot to method info mapping. //==================================================================== diff --git a/src/coreclr/src/vm/marshalnative.h b/src/coreclr/src/vm/marshalnative.h index 90e13cd..5d01e3e 100644 --- a/src/coreclr/src/vm/marshalnative.h +++ b/src/coreclr/src/vm/marshalnative.h @@ -46,7 +46,6 @@ public: //==================================================================== static FCDECL2(Object *, GetExceptionForHR, INT32 errorCode, LPVOID errorInfo); static FCDECL1(int, GetHRForException, Object* eUNSAFE); - static FCDECL1(int, GetHRForException_WinRT, Object* eUNSAFE); static FCDECL2(UINT32, SizeOfClass, ReflectClassBaseObject* refClass, CLR_BOOL throwIfNotMarshalable); @@ -200,11 +199,6 @@ public: static FCDECL1(Object*, WrapIUnknownWithComObject, IUnknown* pUnk); static FCDECL2(void, ChangeWrapperHandleStrength, Object* orefUNSAFE, CLR_BOOL fIsWeak); - static FCDECL2(void, InitializeWrapperForWinRT, Object *unsafe_pThis, IUnknown **ppUnk); - static FCDECL2(void, InitializeManagedWinRTFactoryObject, Object *unsafe_pThis, ReflectClassBaseObject *unsafe_pType); - static FCDECL1(Object *, GetNativeActivationFactory, ReflectClassBaseObject *unsafe_pType); - static void QCALLTYPE GetInspectableIIDs(QCall::ObjectHandleOnStack hobj, QCall::ObjectHandleOnStack retArrayGuids); - private: static int GetComSlotInfo(MethodTable *pMT, MethodTable **ppDefItfMT); static BOOL IsObjectInContext(OBJECTREF *pObj); diff --git a/src/coreclr/src/vm/metasig.h b/src/coreclr/src/vm/metasig.h index 30ca8fe..c939be6 100644 --- a/src/coreclr/src/vm/metasig.h +++ b/src/coreclr/src/vm/metasig.h @@ -186,16 +186,6 @@ DEFINE_METASIG(SM(IntPtr_IntPtr_RefIntPtr_RetObj, I I r(I), j)) #ifdef FEATURE_COMINTEROP DEFINE_METASIG(SM(Obj_IntPtr_RefIntPtr_RefBool_RetIntPtr, j I r(I) r(F), I)) DEFINE_METASIG(SM(Obj_IntPtr_RefIntPtr_RetIntPtr, j I r(I), I)) -DEFINE_METASIG_T(SM(Obj_Str_RetICustomProperty, j s, C(ICUSTOMPROPERTY))) -DEFINE_METASIG_T(SM(Obj_Str_PtrTypeName_RetICustomProperty, j s P(g(TYPENAMENATIVE)), C(ICUSTOMPROPERTY))) -DEFINE_METASIG_T(SM(Obj_PtrTypeName_RetVoid, j P(g(TYPENAMENATIVE)), v)) -DEFINE_METASIG_T(SM(Type_PtrTypeName_RetVoid, C(TYPE) P(g(TYPENAMENATIVE)), v)) -DEFINE_METASIG_T(SM(PtrTypeName_RefType_RetVoid, P(g(TYPENAMENATIVE)) r(C(TYPE)), v)) -DEFINE_METASIG_T(SM(ArrType_PtrTypeName_RetVoid, a(C(TYPE)) P(g(TYPENAMENATIVE)), v)) -DEFINE_METASIG_T(SM(PtrTypeName_ArrType_RetVoid, P(g(TYPENAMENATIVE)) a(C(TYPE)), v)) -DEFINE_METASIG_T(SM(PtrTypeName_RetVoid, P(g(TYPENAMENATIVE)), v)) -DEFINE_METASIG_T(SM(PtrTypeName_Int_RetVoid, P(g(TYPENAMENATIVE)) i, v)) -DEFINE_METASIG_T(SM(Exception_IntPtr_RetException, C(EXCEPTION) I, C(EXCEPTION))) DEFINE_METASIG_T(SM(Scenario_ComWrappers_Obj_CreateFlags_RefInt_RetPtrVoid, g(COMWRAPPERSSCENARIO) C(COMWRAPPERS) j g(CREATECOMINTERFACEFLAGS) r(i), P(v))) DEFINE_METASIG_T(SM(Scenario_ComWrappers_IntPtr_CreateFlags_RetObj, g(COMWRAPPERSSCENARIO) C(COMWRAPPERS) I g(CREATEOBJECTFLAGS), j)) DEFINE_METASIG_T(SM(ComWrappers_IEnumerable_RetVoid, C(COMWRAPPERS) C(IENUMERABLE), v)) @@ -350,10 +340,6 @@ DEFINE_METASIG(SM(Obj_Obj_RefArrByte_RetArrByte, j j r(a(b)), a(b))) DEFINE_METASIG_T(SM(Obj_Int_RefVariant_RetVoid, j i r(g(VARIANT)), v)) DEFINE_METASIG_T(SM(Obj_RefVariant_RetVoid, j r(g(VARIANT)), v)) DEFINE_METASIG_T(SM(RefVariant_RetObject, r(g(VARIANT)), j)) -DEFINE_METASIG_T(SM(Str_PtrHStringHeader_RetIntPtr, s P(g(HSTRING_HEADER_MANAGED)), I)) - -DEFINE_METASIG_T(SM(RefDateTimeOffset_RefDateTimeNative_RetVoid, r(g(DATE_TIME_OFFSET)) r(g(DATETIMENATIVE)), v)) - DEFINE_METASIG_T(IM(RuntimeTypeHandle_RefBool_RefIntPtr_RetVoid, g(RT_TYPE_HANDLE) r(F) r(I), v)) #endif @@ -399,9 +385,6 @@ DEFINE_METASIG(IM(RetBool, _, F)) DEFINE_METASIG(IM(RetArrByte, _, a(b))) DEFINE_METASIG_T(IM(RetArrParameterInfo, _, a(C(PARAMETER)))) DEFINE_METASIG_T(IM(RetCultureInfo, _, C(CULTURE_INFO))) -#ifdef FEATURE_COMINTEROP -DEFINE_METASIG_T(IM(RetCausalityTraceLevel, _, g(CAUSALITY_TRACE_LEVEL))) -#endif // FEATURE_COMINTEROP DEFINE_METASIG(IM(Bool_RetIntPtr, F, I)) DEFINE_METASIG_T(IM(Bool_RetMethodInfo, F, C(METHOD_INFO))) diff --git a/src/coreclr/src/vm/method.hpp b/src/coreclr/src/vm/method.hpp index ba5f6ae..1d81981 100644 --- a/src/coreclr/src/vm/method.hpp +++ b/src/coreclr/src/vm/method.hpp @@ -2612,7 +2612,7 @@ protected: nomdDelegateStub = 0x0040, nomdStructMarshalStub = 0x0080, nomdUnbreakable = 0x0100, - nomdDelegateCOMStub = 0x0200, // CLR->COM or COM->CLR call via a delegate (WinRT specific) + //unused = 0x0200, nomdSignatureNeedsRestore = 0x0400, nomdStubNeedsCOMStarted = 0x0800, // EnsureComStarted must be called before executing the method nomdMulticastStub = 0x1000, @@ -2718,7 +2718,6 @@ public: bool IsCOMToCLRStub() { LIMITED_METHOD_CONTRACT; _ASSERTE(IsILStub()); return ((0 == (m_dwExtendedFlags & mdStatic)) && IsReverseStub()); } bool IsPInvokeStub() { LIMITED_METHOD_CONTRACT; _ASSERTE(IsILStub()); return ((0 != (m_dwExtendedFlags & mdStatic)) && !IsReverseStub() && !IsCALLIStub() && !IsStructMarshalStub()); } bool IsUnbreakable() { LIMITED_METHOD_CONTRACT; _ASSERTE(IsILStub()); return (0 != (m_dwExtendedFlags & nomdUnbreakable)); } - bool IsDelegateCOMStub() { LIMITED_METHOD_CONTRACT; _ASSERTE(IsILStub()); return (0 != (m_dwExtendedFlags & nomdDelegateCOMStub)); } bool IsSignatureNeedsRestore() { LIMITED_METHOD_CONTRACT; _ASSERTE(IsILStub()); return (0 != (m_dwExtendedFlags & nomdSignatureNeedsRestore)); } bool IsStubNeedsCOMStarted() { LIMITED_METHOD_CONTRACT; _ASSERTE(IsILStub()); return (0 != (m_dwExtendedFlags & nomdStubNeedsCOMStarted)); } bool IsStructMarshalStub() { LIMITED_METHOD_CONTRACT; _ASSERTE(IsILStub()); return (0 != (m_dwExtendedFlags & nomdStructMarshalStub)); } @@ -2746,7 +2745,7 @@ public: bool HasMDContextArg() { LIMITED_METHOD_CONTRACT; - return ((IsCLRToCOMStub() && !IsDelegateCOMStub()) || IsPInvokeStub()); + return IsCLRToCOMStub() || IsPInvokeStub(); } void Restore(); diff --git a/src/coreclr/src/vm/methodtable.cpp b/src/coreclr/src/vm/methodtable.cpp index 2332f44..59990ed 100644 --- a/src/coreclr/src/vm/methodtable.cpp +++ b/src/coreclr/src/vm/methodtable.cpp @@ -51,7 +51,6 @@ #include "comcallablewrapper.h" #include "clrtocomcall.h" #include "runtimecallablewrapper.h" -#include "winrttypenameconverter.h" #endif // FEATURE_COMINTEROP #include "typeequivalencehash.hpp" @@ -3949,31 +3948,22 @@ void MethodTable::Save(DataImage *image, DWORD profilingFlags) if (HasGuidInfo()) { // Make sure our GUID is computed - - // Generic WinRT types can have their GUID computed only if the instantiation is WinRT-legal - if (IsLegalNonArrayWinRTType()) + GUID dummy; + if (SUCCEEDED(GetGuidNoThrow(&dummy, TRUE, FALSE))) { - GUID dummy; - if (SUCCEEDED(GetGuidNoThrow(&dummy, TRUE, FALSE))) - { - GuidInfo* pGuidInfo = GetGuidInfo(); - _ASSERTE(pGuidInfo != NULL); + GuidInfo* pGuidInfo = GetGuidInfo(); + _ASSERTE(pGuidInfo != NULL); - image->StoreStructure(pGuidInfo, - sizeof(GuidInfo), - DataImage::ITEM_GUID_INFO); + image->StoreStructure(pGuidInfo, + sizeof(GuidInfo), + DataImage::ITEM_GUID_INFO); - Module *pModule = GetModule(); - if (pModule->CanCacheWinRTTypeByGuid(this)) - { - pModule->CacheWinRTTypeByGuid(this, pGuidInfo); - } - } - else - { - GuidInfo** ppGuidInfo = GetGuidInfoPtr(); - *ppGuidInfo = NULL; - } + Module *pModule = GetModule(); + } + else + { + GuidInfo** ppGuidInfo = GetGuidInfoPtr(); + *ppGuidInfo = NULL; } } #endif // FEATURE_COMINTEROP @@ -5659,20 +5649,6 @@ void MethodTable::DoFullyLoad(Generics::RecursionGraph * const pVisited, const { case CLASS_DEPENDENCIES_LOADED: SetIsDependenciesLoaded(); - -#if defined(FEATURE_COMINTEROP) && !defined(DACCESS_COMPILE) - if (WinRTSupported() && g_fEEStarted) - { - _ASSERTE(GetAppDomain() != NULL); - - AppDomain* pAppDomain = GetAppDomain(); - if (pAppDomain->CanCacheWinRTTypeByGuid(this)) - { - pAppDomain->CacheWinRTTypeByGuid(this); - } - } -#endif // FEATURE_COMINTEROP && !DACCESS_COMPILE - break; case CLASS_LOADED: @@ -5902,27 +5878,9 @@ MethodTable* MethodTable::GetComPlusParentMethodTable() if (pParent && pParent->IsComImport()) { - if (pParent->IsProjectedFromWinRT()) - { - // skip all Com Import classes - do - { - pParent = pParent->GetParentMethodTable(); - _ASSERTE(pParent != NULL); - }while(pParent->IsComImport()); - - // Now we have either System.__ComObject or WindowsRuntime.RuntimeClass - if (pParent != g_pBaseCOMObject) - { - return pParent; - } - } - else - { - // Skip the single ComImport class we expect - _ASSERTE(pParent->GetParentMethodTable() != NULL); - pParent = pParent->GetParentMethodTable(); - } + // Skip the single ComImport class we expect + _ASSERTE(pParent->GetParentMethodTable() != NULL); + pParent = pParent->GetParentMethodTable(); _ASSERTE(!pParent->IsComImport()); // Skip over System.__ComObject, expect System.MarshalByRefObject @@ -5935,39 +5893,6 @@ MethodTable* MethodTable::GetComPlusParentMethodTable() return pParent; } -BOOL MethodTable::IsWinRTObjectType() -{ - LIMITED_METHOD_CONTRACT; - - // Try to determine if this object represents a WindowsRuntime object - i.e. is either - // ProjectedFromWinRT or derived from a class that is - - if (!IsComObjectType()) - return FALSE; - - // Ideally we'd compute this once in BuildMethodTable and track it with another - // flag, but we're now out of bits on m_dwFlags, and this is used very rarely - // so for now we'll just recompute it when necessary. - MethodTable* pMT = this; - do - { - if (pMT->IsProjectedFromWinRT()) - { - // Found a WinRT COM object - return TRUE; - } - if (pMT->IsComImport()) - { - // Found a class that is actually imported from COM but not WinRT - // this is definitely a non-WinRT COM object - return FALSE; - } - pMT = pMT->GetParentMethodTable(); - }while(pMT != NULL); - - return FALSE; -} - #endif // FEATURE_COMINTEROP #endif // !DACCESS_COMPILE @@ -6208,173 +6133,6 @@ void MethodTable::SetInternalCorElementType (CorElementType _NormType) #endif // !DACCESS_COMPILE -#ifdef FEATURE_COMINTEROP -#ifndef DACCESS_COMPILE - -#ifndef CROSSGEN_COMPILE -BOOL MethodTable::IsLegalWinRTType(OBJECTREF *poref) -{ - CONTRACTL - { - THROWS; - GC_TRIGGERS; - MODE_COOPERATIVE; - PRECONDITION(IsProtectedByGCFrame(poref)); - PRECONDITION(CheckPointer(poref)); - PRECONDITION((*poref) != NULL); - } - CONTRACTL_END - - if (IsArray()) - { - BASEARRAYREF arrayRef = (BASEARRAYREF)(*poref); - - // WinRT array must be one-dimensional array with 0 lower-bound - if (arrayRef->GetRank() == 1 && arrayRef->GetLowerBoundsPtr()[0] == 0) - { - MethodTable *pElementMT = ((BASEARRAYREF)(*poref))->GetArrayElementTypeHandle().GetMethodTable(); - - // Element must be a legal WinRT type and not an array - if (!pElementMT->IsArray() && pElementMT->IsLegalNonArrayWinRTType()) - return TRUE; - } - - return FALSE; - } - else - { - // Non-Array version of IsLegalNonArrayWinRTType - return IsLegalNonArrayWinRTType(); - } -} -#endif //#ifndef CROSSGEN_COMPILE - -BOOL MethodTable::IsLegalNonArrayWinRTType() -{ - CONTRACTL - { - THROWS; - GC_TRIGGERS; - MODE_ANY; - PRECONDITION(!IsArray()); // arrays are handled in the callers - } - CONTRACTL_END - - if (WinRTTypeNameConverter::IsWinRTPrimitiveType(this)) - return TRUE; - - // Attributes are not legal - MethodTable *pParentMT = GetParentMethodTable(); - if (pParentMT == MscorlibBinder::GetExistingClass(CLASS__ATTRIBUTE)) - { - return FALSE; - } - - bool fIsRedirected = false; - if (!IsProjectedFromWinRT() && !IsExportedToWinRT()) - { - // If the type is not primitive and not coming from .winmd, it can still be legal if - // it's one of the redirected types (e.g. IEnumerable). - if (!WinRTTypeNameConverter::IsRedirectedType(this)) - return FALSE; - - fIsRedirected = true; - } - - if (IsValueType()) - { - if (!fIsRedirected) - { - // check fields - ApproxFieldDescIterator fieldIterator(this, ApproxFieldDescIterator::INSTANCE_FIELDS); - for (FieldDesc *pFD = fieldIterator.Next(); pFD != NULL; pFD = fieldIterator.Next()) - { - TypeHandle thField = pFD->GetFieldTypeHandleThrowing(CLASS_LOAD_EXACTPARENTS); - - if (thField.IsTypeDesc()) - return FALSE; - - MethodTable *pFieldMT = thField.GetMethodTable(); - - // the only allowed reference types are System.String and types projected from WinRT value types - if (!pFieldMT->IsValueType() && !pFieldMT->IsString()) - { - WinMDAdapter::RedirectedTypeIndex index; - if (!WinRTTypeNameConverter::ResolveRedirectedType(pFieldMT, &index)) - return FALSE; - - WinMDAdapter::WinMDTypeKind typeKind; - WinMDAdapter::GetRedirectedTypeInfo(index, NULL, NULL, NULL, NULL, NULL, &typeKind); - if (typeKind != WinMDAdapter::WinMDTypeKind_Struct && typeKind != WinMDAdapter::WinMDTypeKind_Enum) - return FALSE; - } - - if (!pFieldMT->IsLegalNonArrayWinRTType()) - return FALSE; - } - } - } - - if (IsInterface() || IsDelegate() || (IsValueType() && fIsRedirected)) - { - // interfaces, delegates, and redirected structures can be generic - check the instantiation - if (HasInstantiation()) - { - Instantiation inst = GetInstantiation(); - for (DWORD i = 0; i < inst.GetNumArgs(); i++) - { - // arrays are not allowed as generic arguments - if (inst[i].IsArray()) - return FALSE; - - if (inst[i].IsTypeDesc()) - return FALSE; - - if (!inst[i].AsMethodTable()->IsLegalNonArrayWinRTType()) - return FALSE; - } - } - } - else - { - // generic structures and runtime clases are not supported - if (HasInstantiation()) - return FALSE; - } - - return TRUE; -} - -//========================================================================================== -// Returns the default WinRT interface if this is a WinRT class, NULL otherwise. -MethodTable *MethodTable::GetDefaultWinRTInterface() -{ - CONTRACTL - { - THROWS; - GC_TRIGGERS; - MODE_ANY; - } - CONTRACTL_END - - if (!IsProjectedFromWinRT() && !IsExportedToWinRT()) - return NULL; - - if (IsInterface()) - return NULL; - - // System.Runtime.InteropServices.WindowsRuntime.RuntimeClass is weird - // It is ProjectedFromWinRT but isn't really a WinRT class - if (this == g_pBaseRuntimeClass) - return NULL; - - WinRTClassFactory *pFactory = ::GetComClassFactory(this)->AsWinRTClassFactory(); - return pFactory->GetDefaultInterface(); -} - -#endif // !DACCESS_COMPILE -#endif // FEATURE_COMINTEROP - #ifdef FEATURE_TYPEEQUIVALENCE #ifndef DACCESS_COMPILE @@ -7452,13 +7210,6 @@ HRESULT MethodTable::GetGuidNoThrow(GUID *pGuid, BOOL bGenerateIfNotFound, BOOL // If metadata does not specify GUID for the type, GUID_NULL is returned (if bGenerateIfNotFound // is FALSE) or a GUID is auto-generated on the fly from the name and members of the type // (bGenerateIfNotFound is TRUE). -// -// Redirected WinRT types may have two GUIDs, the "classic" one which matches the return value -// of Type.Guid, and the new one which is the GUID of the WinRT type to which it is redirected. -// The bClassic parameter controls which one is returned from this method. Note that the parameter -// is ignored for genuine WinRT types, i.e. types loaded from .winmd files, those always return -// the new GUID. -// void MethodTable::GetGuid(GUID *pGuid, BOOL bGenerateIfNotFound, BOOL bClassic /*=TRUE*/) { CONTRACTL { @@ -7489,14 +7240,13 @@ void MethodTable::GetGuid(GUID *pGuid, BOOL bGenerateIfNotFound, BOOL bClassic / _ASSERTE(pGuid != NULL); _ASSERTE(!this->IsArray()); - // Use the per-EEClass GuidInfo if we are asked for the "classic" non-WinRT GUID of non-WinRT type - GuidInfo *pInfo = ((bClassic && !IsProjectedFromWinRT()) ? GetClass()->GetGuidInfo() : GetGuidInfo()); + GuidInfo *pInfo = GetClass()->GetGuidInfo(); // First check to see if we have already cached the guid for this type. // We currently only cache guids on interfaces and WinRT delegates. // In classic mode, though, ensure we don't retrieve the GuidInfo for redirected interfaces - if ((IsInterface() || IsWinRTDelegate()) && pInfo != NULL - && (!bClassic || !SupportsGenericInterop(TypeHandle::Interop_NativeToManaged, modeRedirected))) + if ((IsInterface()) && pInfo != NULL + && (!bClassic)) { if (pInfo->m_bGeneratedFromName) { @@ -7514,26 +7264,6 @@ void MethodTable::GetGuid(GUID *pGuid, BOOL bGenerateIfNotFound, BOOL bClassic / return; } -#ifdef FEATURE_COMINTEROP - if ((SupportsGenericInterop(TypeHandle::Interop_NativeToManaged, modeProjected)) - || (!bClassic - && SupportsGenericInterop(TypeHandle::Interop_NativeToManaged, modeRedirected) - && IsLegalNonArrayWinRTType())) - { - // Closed generic WinRT interfaces/delegates have their GUID computed - // based on the "PIID" in metadata and the instantiation. - // Note that we explicitly do this computation for redirected mscorlib - // interfaces only if !bClassic, so typeof(Enumerable).GUID - // for example still returns the same result as pre-v4.5 runtimes. - // ComputeGuidForGenericType() may throw for generics nested beyond 64 levels. - WinRTGuidGenerator::ComputeGuidForGenericType(this, pGuid); - - // This GUID is per-instantiation so make sure that the cache - // where we are going to keep it is per-instantiation as well. - _ASSERTE(IsCanonicalMethodTable() || HasGuidInfo()); - } - else -#endif // FEATURE_COMINTEROP if (GetClass()->HasNoGuid()) { *pGuid = GUID_NULL; @@ -7618,20 +7348,14 @@ void MethodTable::GetGuid(GUID *pGuid, BOOL bGenerateIfNotFound, BOOL bClassic / // Cache the guid in the type, if not already cached. // We currently only do this for interfaces. // Also, in classic mode do NOT cache GUID for redirected interfaces. - if ((IsInterface() || IsWinRTDelegate()) && (pInfo == NULL) && (*pGuid != GUID_NULL) -#ifdef FEATURE_COMINTEROP - && !(bClassic - && SupportsGenericInterop(TypeHandle::Interop_NativeToManaged, modeRedirected) - && IsLegalNonArrayWinRTType()) -#endif // FEATURE_COMINTEROP - ) + if ((IsInterface()) && (pInfo == NULL) && (*pGuid != GUID_NULL)) { AllocMemTracker amTracker; BOOL bStoreGuidInfoOnEEClass = false; PTR_LoaderAllocator pLoaderAllocator; #if FEATURE_COMINTEROP - if ((bClassic && !IsProjectedFromWinRT()) || !HasGuidInfo()) + if ((bClassic) || !HasGuidInfo()) { bStoreGuidInfoOnEEClass = true; } @@ -7666,7 +7390,7 @@ void MethodTable::GetGuid(GUID *pGuid, BOOL bGenerateIfNotFound, BOOL bClassic / pInfo->m_bGeneratedFromName = bGenerated; // Set in in the interface method table. - if (bClassic && !IsProjectedFromWinRT()) + if (bClassic) { // Set the per-EEClass GuidInfo if we are asked for the "classic" non-WinRT GUID. // The MethodTable may be NGENed and read-only - and there's no point in saving @@ -9864,83 +9588,6 @@ EEClassNativeLayoutInfo const* MethodTable::EnsureNativeLayoutInfoInitialized() #endif } -#ifdef FEATURE_COMINTEROP -//========================================================================================== -BOOL MethodTable::IsWinRTRedirectedDelegate() -{ - LIMITED_METHOD_DAC_CONTRACT; - - if (!IsDelegate()) - { - return FALSE; - } - - return !!WinRTDelegateRedirector::ResolveRedirectedDelegate(this, nullptr); -} - -//========================================================================================== -BOOL MethodTable::IsWinRTRedirectedInterface(TypeHandle::InteropKind interopKind) -{ - LIMITED_METHOD_CONTRACT; - - if (!IsInterface()) - return FALSE; - - if (!HasRCWPerTypeData()) - { - // All redirected interfaces have per-type RCW data - return FALSE; - } - -#ifdef DACCESS_COMPILE - RCWPerTypeData *pData = NULL; -#else // DACCESS_COMPILE - // We want to keep this function LIMITED_METHOD_CONTRACT so we call GetRCWPerTypeData with - // the non-throwing flag. pData can be NULL if it could not be allocated. - RCWPerTypeData *pData = GetRCWPerTypeData(false); -#endif // DACCESS_COMPILE - - DWORD dwFlags = (pData != NULL ? pData->m_dwFlags : 0); - if ((dwFlags & RCWPerTypeData::InterfaceFlagsInited) == 0) - { - dwFlags = RCWPerTypeData::InterfaceFlagsInited; - - if (WinRTInterfaceRedirector::ResolveRedirectedInterface(this, NULL)) - { - dwFlags |= RCWPerTypeData::IsRedirectedInterface; - } - else if (HasSameTypeDefAs(MscorlibBinder::GetExistingClass(CLASS__ICOLLECTIONGENERIC)) || - HasSameTypeDefAs(MscorlibBinder::GetExistingClass(CLASS__IREADONLYCOLLECTIONGENERIC)) || - this == MscorlibBinder::GetExistingClass(CLASS__ICOLLECTION)) - { - dwFlags |= RCWPerTypeData::IsICollectionGeneric; - } - - if (pData != NULL) - { - FastInterlockOr(&pData->m_dwFlags, dwFlags); - } - } - - if ((dwFlags & RCWPerTypeData::IsRedirectedInterface) != 0) - return TRUE; - - if (interopKind == TypeHandle::Interop_ManagedToNative) - { - // ICollection is redirected in the managed->WinRT direction (i.e. we have stubs - // that implement ICollection methods in terms of IVector/IMap), but it is not - // treated specially in the WinRT->managed direction (we don't build a WinRT vtable - // for a class that only implements ICollection). IReadOnlyCollection is - // treated similarly. - if ((dwFlags & RCWPerTypeData::IsICollectionGeneric) != 0) - return TRUE; - } - - return FALSE; -} - -#endif // FEATURE_COMINTEROP - #ifdef FEATURE_READYTORUN_COMPILER static BOOL ComputeIsLayoutFixedInCurrentVersionBubble(MethodTable * pMT) diff --git a/src/coreclr/src/vm/methodtable.h b/src/coreclr/src/vm/methodtable.h index f5aa745..0767673 100644 --- a/src/coreclr/src/vm/methodtable.h +++ b/src/coreclr/src/vm/methodtable.h @@ -312,7 +312,7 @@ struct MethodTableWriteableData enum_flag_IsNotFullyLoaded = 0x00000040, enum_flag_DependenciesLoaded = 0x00000080, // class and all depedencies loaded up to CLASS_LOADED_BUT_NOT_VERIFIED - enum_flag_SkipWinRTOverride = 0x00000100, // No WinRT override is needed + // enum_unused = 0x00000100, enum_flag_CanCompareBitsOrUseFastGetHashCode = 0x00000200, // Is any field type or sub field type overrode Equals or GetHashCode enum_flag_HasCheckedCanCompareBitsOrUseFastGetHashCode = 0x00000400, // Whether we have checked the overridden Equals or GetHashCode @@ -324,7 +324,7 @@ struct MethodTableWriteableData enum_flag_NGEN_IsFixedUp = 0x00010000, // This MT has been fixed up during NGEN enum_flag_NGEN_IsNeedsRestoreCached = 0x00020000, // Set if we have cached the results of needs restore computation enum_flag_NGEN_CachedNeedsRestore = 0x00040000, // The result of the needs restore computation - enum_flag_NGEN_OverridingInterface = 0x00080000, // Overriding interface that we should generate WinRT CCW stubs for. + // enum_unused = 0x00080000, #ifdef FEATURE_READYTORUN_COMPILER enum_flag_NGEN_IsLayoutFixedComputed = 0x0010000, // Set if we have cached the result of IsLayoutFixed computation @@ -420,26 +420,6 @@ public: m_dwFlags |= enum_flag_NGEN_IsNeedsRestoreCached; if (fNeedsRestore) m_dwFlags |= enum_flag_NGEN_CachedNeedsRestore; } - - inline void SetIsOverridingInterface() - { - CONTRACTL - { - THROWS; - GC_NOTRIGGER; - MODE_ANY; - } - CONTRACTL_END; - - if ((m_dwFlags & enum_flag_NGEN_OverridingInterface) != 0) return; - FastInterlockOr((ULONG *) &m_dwFlags, enum_flag_NGEN_OverridingInterface); - } - - inline BOOL IsOverridingInterface() const - { - LIMITED_METHOD_CONTRACT; - return (m_dwFlags & enum_flag_NGEN_OverridingInterface); - } #endif // FEATURE_PREJIT @@ -704,11 +684,6 @@ public: //------------------------------------------------------------------- // COM INTEROP // - BOOL IsProjectedFromWinRT(); - BOOL IsExportedToWinRT(); - BOOL IsWinRTDelegate(); - BOOL IsWinRTRedirectedInterface(TypeHandle::InteropKind interopKind); - BOOL IsWinRTRedirectedDelegate(); #ifdef FEATURE_COMINTEROP TypeHandle GetCoClassForInterface(); @@ -723,14 +698,6 @@ public: CorIfaceAttr GetComInterfaceType(); void SetComInterfaceType(CorIfaceAttr ItfType); - // Determines whether this is a WinRT-legal type - BOOL IsLegalWinRTType(OBJECTREF *poref); - - // Determines whether this is a WinRT-legal type - don't use it with array - BOOL IsLegalNonArrayWinRTType(); - - MethodTable *GetDefaultWinRTInterface(); - OBJECTHANDLE GetOHDelegate(); void SetOHDelegate (OBJECTHANDLE _ohDelegate); @@ -745,9 +712,6 @@ public: // the hierarchy MethodTable* GetComPlusParentMethodTable(); - // class is a WinRT object class (is itself or derives from a ProjectedFromWinRT class) - BOOL IsWinRTObjectType(); - DWORD IsComImport(); // class is a special COM event interface @@ -786,13 +750,6 @@ public: // NOTE: The current caller of this is ComInterop, and it makes calls // under its own lock to ensure not duplicates. InteropMethodTableData *GetComInteropData(); - -#else // !FEATURE_COMINTEROP - BOOL IsWinRTObjectType() - { - LIMITED_METHOD_CONTRACT; - return FALSE; - } #endif // !FEATURE_COMINTEROP // class is a com object class @@ -1090,18 +1047,6 @@ public: || (GetWriteableData()->m_dwFlags & MethodTableWriteableData::enum_flag_IsNotFullyLoaded) == 0; } - inline BOOL IsSkipWinRTOverride() - { - LIMITED_METHOD_CONTRACT; - return (GetWriteableData_NoLogging()->m_dwFlags & MethodTableWriteableData::enum_flag_SkipWinRTOverride); - } - - inline void SetSkipWinRTOverride() - { - WRAPPER_NO_CONTRACT; - FastInterlockOr(&GetWriteableDataForWrite_NoLogging()->m_dwFlags, MethodTableWriteableData::enum_flag_SkipWinRTOverride); - } - inline BOOL CanCompareBitsOrUseFastGetHashCode() { LIMITED_METHOD_CONTRACT; @@ -1347,16 +1292,6 @@ public: return !HasInstantiation() || IsGenericTypeDefinition(); } - typedef enum - { - modeProjected = 0x1, - modeRedirected = 0x2, - modeAll = modeProjected|modeRedirected - } Mode; - - // Is this a generic interface/delegate that can be used for COM interop? - inline BOOL SupportsGenericInterop(TypeHandle::InteropKind interopKind, Mode = modeAll); - BOOL HasSameTypeDefAs(MethodTable *pMT); BOOL HasSameTypeDefAs_NoLogging(MethodTable *pMT); diff --git a/src/coreclr/src/vm/methodtable.inl b/src/coreclr/src/vm/methodtable.inl index 788b531..1be871d 100644 --- a/src/coreclr/src/vm/methodtable.inl +++ b/src/coreclr/src/vm/methodtable.inl @@ -322,26 +322,6 @@ inline DWORD MethodTable::GetAttrClass() } //========================================================================================== -inline BOOL MethodTable::SupportsGenericInterop(TypeHandle::InteropKind interopKind, - MethodTable::Mode mode /*= modeAll*/) -{ - LIMITED_METHOD_CONTRACT; - -#ifdef FEATURE_COMINTEROP - return ((IsInterface() || IsDelegate()) && // interface or delegate - HasInstantiation() && // generic - !IsSharedByGenericInstantiations() && // unshared - !ContainsGenericVariables() && // closed over concrete types - // defined in .winmd or one of the redirected mscorlib interfaces - ((((mode & modeProjected) != 0) && IsProjectedFromWinRT()) || - (((mode & modeRedirected) != 0) && (IsWinRTRedirectedInterface(interopKind) || IsWinRTRedirectedDelegate())))); -#else // FEATURE_COMINTEROP - return FALSE; -#endif // FEATURE_COMINTEROP -} - - -//========================================================================================== inline BOOL MethodTable::IsNotTightlyPacked() { WRAPPER_NO_CONTRACT; @@ -446,14 +426,7 @@ inline BOOL MethodTable::GetGuidForWinRT(GUID *pGuid) SUPPORTS_DAC; } CONTRACTL_END; - BOOL bRes = FALSE; - if ((IsProjectedFromWinRT() && !HasInstantiation()) || - (SupportsGenericInterop(TypeHandle::Interop_NativeToManaged) && IsLegalNonArrayWinRTType())) - { - bRes = SUCCEEDED(GetGuidNoThrow(pGuid, TRUE, FALSE)); - } - - return bRes; + return FALSE; } #endif // FEATURE_COMINTEROP @@ -1047,55 +1020,6 @@ inline BOOL MethodTable::SetComClassFactory(ClassFactoryBase *pFactory) #endif // FEATURE_COMINTEROP #endif // DACCESS_COMPILE -#ifdef FEATURE_COMINTEROP -//========================================================================================== -inline BOOL MethodTable::IsProjectedFromWinRT() -{ - LIMITED_METHOD_DAC_CONTRACT; - _ASSERTE(GetClass()); - return GetClass()->IsProjectedFromWinRT(); -} - -//========================================================================================== -inline BOOL MethodTable::IsExportedToWinRT() -{ - LIMITED_METHOD_DAC_CONTRACT; - _ASSERTE(GetClass()); - return GetClass()->IsExportedToWinRT(); -} - -//========================================================================================== -inline BOOL MethodTable::IsWinRTDelegate() -{ - LIMITED_METHOD_DAC_CONTRACT; - return (IsProjectedFromWinRT() && IsDelegate()) || IsWinRTRedirectedDelegate(); -} - -#else // FEATURE_COMINTEROP - -//========================================================================================== -inline BOOL MethodTable::IsProjectedFromWinRT() -{ - LIMITED_METHOD_DAC_CONTRACT; - return FALSE; -} - -//========================================================================================== -inline BOOL MethodTable::IsExportedToWinRT() -{ - LIMITED_METHOD_DAC_CONTRACT; - return FALSE; -} - -//========================================================================================== -inline BOOL MethodTable::IsWinRTDelegate() -{ - LIMITED_METHOD_DAC_CONTRACT; - return FALSE; -} - -#endif // FEATURE_COMINTEROP - //========================================================================================== inline PTR_MethodTable MethodTable::GetCanonicalMethodTable() { diff --git a/src/coreclr/src/vm/methodtablebuilder.cpp b/src/coreclr/src/vm/methodtablebuilder.cpp index 5f389b1..54bdcec 100644 --- a/src/coreclr/src/vm/methodtablebuilder.cpp +++ b/src/coreclr/src/vm/methodtablebuilder.cpp @@ -162,49 +162,10 @@ MethodTableBuilder::CreateClass( Module *pModule, if (fHasLayout) pEEClass->SetHasLayout(); -#ifdef FEATURE_COMINTEROP if (IsTdWindowsRuntime(dwAttrClass)) { - Assembly *pAssembly = pModule->GetAssembly(); - - // On the desktop CLR, we do not allow non-FX assemblies to use/define WindowsRuntimeImport attribute. - // - // On CoreCLR, however, we do allow non-FX assemblies to have this attribute. This enables scenarios where we can - // activate 3rd-party WinRT components outside AppContainer - 1st party WinRT components are already allowed - // to be activated outside AppContainer (on both Desktop and CoreCLR). - - pEEClass->SetProjectedFromWinRT(); - } - - if (pEEClass->IsProjectedFromWinRT()) - { - if (IsTdInterface(dwAttrClass)) - { - // - // Check for GuidAttribute - // - BOOL bHasGuid = FALSE; - - GUID guid; - HRESULT hr = pModule->GetMDImport()->GetItemGuid(cl, &guid); - IfFailThrow(hr); - - if (IsEqualGUID(guid, GUID_NULL)) - { - // A WinRT interface should have a GUID - pModule->GetAssembly()->ThrowTypeLoadException(pModule->GetMDImport(), cl, IDS_EE_WINRT_INTERFACE_WITHOUT_GUID); - } - } - } - - WinMDAdapter::RedirectedTypeIndex redirectedTypeIndex; - redirectedTypeIndex = WinRTTypeNameConverter::GetRedirectedTypeIndexByName(pModule, cl); - if (redirectedTypeIndex != WinMDAdapter::RedirectedTypeIndex_Invalid) - { - EnsureOptionalFieldsAreAllocated(pEEClass, pamTracker, pAllocator->GetLowFrequencyHeap()); - pEEClass->SetWinRTRedirectedTypeIndex(redirectedTypeIndex); + COMPlusThrowHR(COR_E_TYPELOAD); } -#endif // FEAUTRE_COMINTEROP #ifdef _DEBUG pModule->GetClassLoader()->m_dwDebugClasses++; @@ -1544,15 +1505,9 @@ MethodTableBuilder::BuildMethodTableThrowing( if (IsComImport() && !IsEnum() && !IsInterface() && !IsValueClass() && !IsDelegate()) { #ifdef FEATURE_COMINTEROP - // ComImport classes must either extend from Object or be a WinRT class - // that extends from another WinRT class (and so form a chain of WinRT classes - // that ultimately extend from object). + // ComImport classes must either extend from Object MethodTable* pMTParent = GetParentMethodTable(); - if ((pMTParent == NULL) || !( - // is the parent valid? - (pMTParent == g_pObjectClass) || - (GetHalfBakedClass()->IsProjectedFromWinRT() && pMTParent->IsProjectedFromWinRT()) - )) + if ((pMTParent == NULL) || (pMTParent != g_pObjectClass)) { BuildMethodTableThrowException(IDS_CLASSLOAD_CANTEXTEND); } @@ -1566,11 +1521,7 @@ MethodTableBuilder::BuildMethodTableThrowing( if (pMTParent == g_pObjectClass) { // ComImport classes ultimately extend from our __ComObject or RuntimeClass class - MethodTable *pCOMMT = NULL; - if (GetHalfBakedClass()->IsProjectedFromWinRT()) - pCOMMT = g_pBaseRuntimeClass; - else - pCOMMT = g_pBaseCOMObject; + MethodTable *pCOMMT = g_pBaseCOMObject; _ASSERTE(pCOMMT); @@ -1587,15 +1538,6 @@ MethodTableBuilder::BuildMethodTableThrowing( } #ifdef FEATURE_COMINTEROP - if (GetHalfBakedClass()->IsProjectedFromWinRT() && IsValueClass() && !IsEnum()) - { - // WinRT structures must have sequential layout - if (!GetHalfBakedClass()->HasSequentialLayout()) - { - BuildMethodTableThrowException(IDS_EE_STRUCTLAYOUT_WINRT); - } - } - // Check for special COM interop types. CheckForSpecialTypes(); @@ -1879,7 +1821,7 @@ MethodTableBuilder::BuildMethodTableThrowing( #endif // UNIX_AMD64_ABI } -#ifdef _DEBUG +#ifdef _DEBUG pMT->SetDebugClassName(GetDebugClassName()); #endif @@ -2965,7 +2907,7 @@ MethodTableBuilder::EnumerateClassMethods() } //@GENERICS: // Generic methods or methods in generic classes - // may not be part of a COM Import class (except for WinRT), PInvoke, internal call outside mscorlib. + // may not be part of a COM Import class, PInvoke, internal call outside mscorlib. if ((bmtGenerics->GetNumGenericArgs() != 0 || numGenericMethodArgs != 0) && ( #ifdef FEATURE_COMINTEROP @@ -2975,12 +2917,7 @@ MethodTableBuilder::EnumerateClassMethods() IsMdPinvokeImpl(dwMemberAttrs) || (IsMiInternalCall(dwImplFlags) && !GetModule()->IsSystem()))) { -#ifdef FEATURE_COMINTEROP - if (!GetHalfBakedClass()->IsProjectedFromWinRT()) -#endif // FEATURE_COMINTEROP - { - BuildMethodTableThrowException(BFA_BAD_PLACE_FOR_GENERIC_METHOD); - } + BuildMethodTableThrowException(BFA_BAD_PLACE_FOR_GENERIC_METHOD); } // Generic methods may not be marked "runtime". However note that @@ -3050,10 +2987,7 @@ MethodTableBuilder::EnumerateClassMethods() if (hr == S_FALSE) { #ifdef FEATURE_COMINTEROP - if (fIsClassComImport - || GetHalfBakedClass()->IsProjectedFromWinRT() - || bmtProp->fComEventItfType - ) + if (fIsClassComImport || bmtProp->fComEventItfType) { // ComImport classes have methods which are just used // for implementing all interfaces the class supports @@ -3063,13 +2997,7 @@ MethodTableBuilder::EnumerateClassMethods() if (IsMdRTSpecialName(dwMemberAttrs)) { // Note: Method name (.ctor) will be checked in code:ValidateMethods - - // WinRT ctors are interop calls via stubs - if (!GetHalfBakedClass()->IsProjectedFromWinRT()) - { - // Ctor on a non-WinRT class - type = METHOD_TYPE_FCALL; - } + type = METHOD_TYPE_FCALL; } } else @@ -3148,11 +3076,9 @@ MethodTableBuilder::EnumerateClassMethods() type = METHOD_TYPE_NORMAL; } else if (bmtGenerics->GetNumGenericArgs() != 0 && - (bmtGenerics->fSharedByGenericInstantiations || (!bmtProp->fIsRedirectedInterface && !GetHalfBakedClass()->IsProjectedFromWinRT()))) + (bmtGenerics->fSharedByGenericInstantiations)) { // Methods in instantiated interfaces need nothing special - they are not visible from COM etc. - // mcComInterop is only useful for unshared instantiated WinRT interfaces. If the interface is - // shared by multiple instantiations, the MD would be useless for interop anyway. type = METHOD_TYPE_NORMAL; } else if (bmtProp->fIsMngStandardItf) @@ -6487,20 +6413,6 @@ VOID MethodTableBuilder::PlaceInterfaceDeclarationOnClass( pDecl->GetSlotIndex(), pImpl); -#ifdef FEATURE_PREJIT - if (IsCompilationProcess()) - { - // - // Mark this interface as overridable. It is used to skip generation of - // CCWs stubs during NGen (see code:MethodNeedsReverseComStub) - // - if (!IsMdFinal(pImpl->GetDeclAttrs())) - { - pDeclMT->GetWriteableDataForWrite()->SetIsOverridingInterface(); - } - } -#endif - #ifdef _DEBUG if (bmtInterface->dbg_fShouldInjectInterfaceDuplicates) { // We injected interface duplicates @@ -7466,23 +7378,6 @@ MethodTableBuilder::PlaceInterfaceMethods() } } -#ifdef FEATURE_COMINTEROP - // WinRT types always use methodimpls to line up methods with interface implementations, so we do not want to allow implicit - // interface implementations to kick in. This can especially cause problems with redirected interfaces, where the underlying - // runtimeclass doesn't actually implement the interfaces we claim it does. For example, a WinRT class which implements both - // IVector and ICalculator will be projected as implementing IList and ICalculator. In this case, we do not want the - // ICalculator Add(int) method to get lined up with the ICollection Add method, since that will cause us to dispatch to the - // wrong underlying COM interface. - // - // There are a special WinRT types in mscorlib (notably DisposableRuntimeClass) which do implement interfaces in the normal way - // so we skip this check for them. (Note that we can't use a methodimpl directly in mscorlib, since ComImport classes are - // forbidden from having implementation code by the C# compiler). - if (GetHalfBakedClass()->IsProjectedFromWinRT() && !GetModule()->IsSystem()) - { - continue; - } -#endif // FEATURE_COMINTEROP - // For each method declared in this interface bmtInterfaceEntry::InterfaceSlotIterator itfSlotIt = pCurItfEntry->IterateInterfaceSlots(GetStackingAllocator()); @@ -9746,17 +9641,14 @@ void MethodTableBuilder::CheckForSystemTypes() else { bool bIsComObject = false; - bool bIsRuntimeClass = false; if (strcmp(name, g_ComObjectName) == 0 && strcmp(nameSpace, g_SystemNS) == 0) bIsComObject = true; - if (strcmp(name, g_RuntimeClassName) == 0 && strcmp(nameSpace, g_WinRTNS) == 0) - bIsRuntimeClass = true; - if (bIsComObject || bIsRuntimeClass) + if (bIsComObject) { - // Make System.__ComObject/System.Runtime.InteropServices.WindowsRuntime.RuntimeClass a ComImport type + // Make System.__ComObject a ComImport type // We can't do it using attribute as C# won't allow putting code in ComImport types pMT->SetComObjectType(); @@ -9764,13 +9656,6 @@ void MethodTableBuilder::CheckForSystemTypes() // the optional field descriptor. EnsureOptionalFieldsAreAllocated(pClass, m_pAllocMemTracker, GetLoaderAllocator()->GetLowFrequencyHeap()); } - - if (bIsRuntimeClass) - { - // Note that we set it here to avoid type loader considering RuntimeClass as a normal WindowsImportType - // as functions in RuntimeClass doesn't go through COM interop - GetHalfBakedClass()->SetProjectedFromWinRT(); - } } #endif // FEATURE_COMINTEROP } @@ -10302,45 +10187,6 @@ MethodTableBuilder::SetupMethodTable2( EnsureOptionalFieldsAreAllocated(pClass, m_pAllocMemTracker, GetLoaderAllocator()->GetLowFrequencyHeap()); #endif // FEATURE_COMINTEROP } - -#ifdef FEATURE_COMINTEROP - if (pMT->GetAssembly()->IsManagedWinMD()) - { - // We need to mark classes that are implementations of managed WinRT runtime classes with - // the "exported to WinRT" flag. It's not quite possible to tell which ones these are by - // reading metadata so we ask the adapter. - - IWinMDImport *pWinMDImport = pMT->GetAssembly()->GetManifestWinMDImport(); - _ASSERTE(pWinMDImport != NULL); - - BOOL bResult; - IfFailThrow(pWinMDImport->IsRuntimeClassImplementation(GetCl(), &bResult)); - - if (bResult) - { - pClass->SetExportedToWinRT(); - - // We need optional fields for activation from WinRT. - EnsureOptionalFieldsAreAllocated(pClass, m_pAllocMemTracker, GetLoaderAllocator()->GetLowFrequencyHeap()); - } - } - - if (pClass->IsProjectedFromWinRT() || pClass->IsExportedToWinRT()) - { - const BYTE * pVal; - ULONG cbVal; - HRESULT hr = GetCustomAttribute(GetCl(), WellKnownAttribute::WinRTMarshalingBehaviorAttribute, (const void **) &pVal, &cbVal); - if (hr == S_OK) - { - CustomAttributeParser cap(pVal, cbVal); - IfFailThrow(cap.SkipProlog()); - UINT32 u = 0; - IfFailThrow(cap.GetU4(&u)); - if(u > 0) - pClass->SetMarshalingType(u); - } - } -#endif // FEATURE_COMINTEROP } else { @@ -10682,8 +10528,7 @@ MethodTableBuilder::SetupMethodTable2( // class // make sure any interface implementated by the COM Imported class // is overridden fully, (OR) not overridden at all.. - // We relax this for WinRT where we want to be able to override individual methods. - if (bmtProp->fIsComObjectType && !pMT->IsWinRTObjectType()) + if (bmtProp->fIsComObjectType) { MethodTable::InterfaceMapIterator intIt = pMT->IterateInterfaceMap(); while (intIt.Next()) @@ -10887,9 +10732,6 @@ void MethodTableBuilder::VerifyVirtualMethodsImplemented(MethodTable::MethodData return; #ifdef FEATURE_COMINTEROP - // Note that this is important for WinRT where redirected .NET interfaces appear on the interface - // impl list but their methods are not implemented (the adapter only hides the WinRT methods, it - // does not make up the .NET ones). if (bmtProp->fIsComObjectType) return; #endif // FEATURE_COMINTEROP @@ -11114,107 +10956,12 @@ VOID MethodTableBuilder::CheckForSpecialTypes() #undef MNGSTDITF_END_INTERFACE } while (FALSE); - - if (strcmp(pszFullyQualifiedName, g_CollectionsGenericCollectionItfName) == 0 || - strcmp(pszFullyQualifiedName, g_CollectionsGenericReadOnlyCollectionItfName) == 0 || - strcmp(pszFullyQualifiedName, g_CollectionsCollectionItfName) == 0) - { - // ICollection`1, ICollection and IReadOnlyCollection`1 are special cases the adapter is unaware of - bmtProp->fIsRedirectedInterface = true; - } - else - { - if (strcmp(pszFullyQualifiedName, WinMDAdapter::GetRedirectedTypeFullCLRName(WinMDAdapter::RedirectedTypeIndex_System_Collections_Generic_IEnumerable)) == 0 || - strcmp(pszFullyQualifiedName, WinMDAdapter::GetRedirectedTypeFullCLRName(WinMDAdapter::RedirectedTypeIndex_System_Collections_Generic_IList)) == 0 || - strcmp(pszFullyQualifiedName, WinMDAdapter::GetRedirectedTypeFullCLRName(WinMDAdapter::RedirectedTypeIndex_System_Collections_Generic_IDictionary)) == 0 || - strcmp(pszFullyQualifiedName, WinMDAdapter::GetRedirectedTypeFullCLRName(WinMDAdapter::RedirectedTypeIndex_System_Collections_Generic_IReadOnlyList)) == 0 || - strcmp(pszFullyQualifiedName, WinMDAdapter::GetRedirectedTypeFullCLRName(WinMDAdapter::RedirectedTypeIndex_System_Collections_Generic_IReadOnlyDictionary)) == 0 || - strcmp(pszFullyQualifiedName, WinMDAdapter::GetRedirectedTypeFullCLRName(WinMDAdapter::RedirectedTypeIndex_System_Collections_IEnumerable)) == 0 || - strcmp(pszFullyQualifiedName, WinMDAdapter::GetRedirectedTypeFullCLRName(WinMDAdapter::RedirectedTypeIndex_System_Collections_IList)) == 0 || - strcmp(pszFullyQualifiedName, WinMDAdapter::GetRedirectedTypeFullCLRName(WinMDAdapter::RedirectedTypeIndex_System_IDisposable)) == 0) - { - bmtProp->fIsRedirectedInterface = true; - } - } - - // We want to allocate the per-type RCW data optional MethodTable field for - // 1. Redirected interfaces - // 2. Mscorlib-declared [WindowsRuntimeImport] interfaces - bmtProp->fNeedsRCWPerTypeData = (bmtProp->fIsRedirectedInterface || GetHalfBakedClass()->IsProjectedFromWinRT()); - - if (!bmtProp->fNeedsRCWPerTypeData) - { - // 3. Non-generic IEnumerable - if (strcmp(pszFullyQualifiedName, g_CollectionsEnumerableItfName) == 0) - { - bmtProp->fNeedsRCWPerTypeData = true; - } - } - } - } - else if (IsDelegate() && bmtGenerics->HasInstantiation()) - { - // 4. Redirected delegates - if (GetHalfBakedClass()->GetWinRTRedirectedTypeIndex() - != WinMDAdapter::RedirectedTypeIndex_Invalid) - { - bmtProp->fNeedsRCWPerTypeData = true; - } - } - } - else if (bmtGenerics->HasInstantiation() && pModule->GetAssembly()->IsWinMD()) - { - // 5. WinRT types with variance - if (bmtGenerics->pVarianceInfo != NULL) - { - bmtProp->fNeedsRCWPerTypeData = true; - } - else if (IsInterface()) - { - // 6. Windows.Foundation.Collections.IIterator`1 - LPCUTF8 pszClassName; - LPCUTF8 pszClassNamespace; - if (SUCCEEDED(pMDImport->GetNameOfTypeDef(GetCl(), &pszClassName, &pszClassNamespace))) - { - LPUTF8 pszFullyQualifiedName = NULL; - MAKE_FULLY_QUALIFIED_NAME(pszFullyQualifiedName, pszClassNamespace, pszClassName); - - if (strcmp(pszFullyQualifiedName, g_WinRTIIteratorClassName) == 0) - { - bmtProp->fNeedsRCWPerTypeData = true; - } - } - } - } - else if ((IsInterface() || IsDelegate()) && - IsTdPublic(GetHalfBakedClass()->GetAttrClass()) && - GetHalfBakedClass()->GetWinRTRedirectedTypeIndex() != WinMDAdapter::RedirectedTypeIndex_Invalid) - { - // 7. System.Collections.Specialized.INotifyCollectionChanged - // 8. System.Collections.Specialized.NotifyCollectionChangedEventHandler - // 9. System.ComponentModel.INotifyPropertyChanged - // 10. System.ComponentModel.PropertyChangedEventHandler - // 11. System.Windows.Input.ICommand - LPCUTF8 pszClassName; - LPCUTF8 pszClassNamespace; - if (SUCCEEDED(pMDImport->GetNameOfTypeDef(GetCl(), &pszClassName, &pszClassNamespace))) - { - LPUTF8 pszFullyQualifiedName = NULL; - MAKE_FULLY_QUALIFIED_NAME(pszFullyQualifiedName, pszClassNamespace, pszClassName); - - if (strcmp(pszFullyQualifiedName, g_INotifyCollectionChangedName) == 0 || - strcmp(pszFullyQualifiedName, g_NotifyCollectionChangedEventHandlerName) == 0 || - strcmp(pszFullyQualifiedName, g_INotifyPropertyChangedName) == 0 || - strcmp(pszFullyQualifiedName, g_PropertyChangedEventHandlerName) == 0 || - strcmp(pszFullyQualifiedName, g_ICommandName) == 0) - { - bmtProp->fNeedsRCWPerTypeData = true; } } } // Check to see if the type is a COM event interface (classic COM interop only). - if (IsInterface() && !GetHalfBakedClass()->IsProjectedFromWinRT()) + if (IsInterface()) { HRESULT hr = GetCustomAttribute(GetCl(), WellKnownAttribute::ComEventInterface, NULL, NULL); if (hr == S_OK) @@ -11231,7 +10978,7 @@ bool ModulesAreDistributedAsAnIndivisibleUnit(Module* module1, Module* module2) { if (module1 == module2) return true; - + bool nativeImagesIdentical = false; if (module1->GetCompositeNativeImage() != NULL) { @@ -11593,18 +11340,14 @@ VOID MethodTableBuilder::EnsureRIDMapsCanBeFilled() void MethodTableBuilder::GetCoClassAttribInfo() { STANDARD_VM_CONTRACT; - - if (!GetHalfBakedClass()->IsProjectedFromWinRT()) // ignore classic COM interop CA on WinRT interfaces + // Retrieve the CoClassAttribute CA. + HRESULT hr = GetCustomAttribute(GetCl(), WellKnownAttribute::CoClass, NULL, NULL); + if (hr == S_OK) { - // Retrieve the CoClassAttribute CA. - HRESULT hr = GetCustomAttribute(GetCl(), WellKnownAttribute::CoClass, NULL, NULL); - if (hr == S_OK) - { - // COM class interfaces may lazily populate the m_pCoClassForIntf field of EEClass. This field is - // optional so we must ensure the optional field descriptor has been allocated. - EnsureOptionalFieldsAreAllocated(GetHalfBakedClass(), m_pAllocMemTracker, GetLoaderAllocator()->GetLowFrequencyHeap()); - SetIsComClassInterface(); - } + // COM class interfaces may lazily populate the m_pCoClassForIntf field of EEClass. This field is + // optional so we must ensure the optional field descriptor has been allocated. + EnsureOptionalFieldsAreAllocated(GetHalfBakedClass(), m_pAllocMemTracker, GetLoaderAllocator()->GetLowFrequencyHeap()); + SetIsComClassInterface(); } } #endif // FEATURE_COMINTEROP @@ -12302,9 +12045,6 @@ ClassLoader::CreateTypeHandleForTypeDefThrowing( cl, nstructPackingSize, nstructNLT, -#ifdef FEATURE_COMINTEROP - pClass->IsProjectedFromWinRT(), -#endif // FEATURE_COMINTEROP fExplicitOffsets, pParentMethodTable, cFields, diff --git a/src/coreclr/src/vm/methodtablebuilder.h b/src/coreclr/src/vm/methodtablebuilder.h index 7314c70..29c8d4d 100644 --- a/src/coreclr/src/vm/methodtablebuilder.h +++ b/src/coreclr/src/vm/methodtablebuilder.h @@ -1323,7 +1323,6 @@ private: #ifdef FEATURE_COMINTEROP bool fIsMngStandardItf; // Set to true if the interface is a manages standard interface. bool fComEventItfType; // Set to true if the class is a special COM event interface. - bool fIsRedirectedInterface; // Set to true if the class is an interface redirected for WinRT bool fNeedsRCWPerTypeData; // Set to true if the class needs optional RCW data attached to the MethodTable #endif // FEATURE_COMINTEROP #ifdef FEATURE_TYPEEQUIVALENCE diff --git a/src/coreclr/src/vm/mlinfo.cpp b/src/coreclr/src/vm/mlinfo.cpp index 5765c22..6038c0a 100644 --- a/src/coreclr/src/vm/mlinfo.cpp +++ b/src/coreclr/src/vm/mlinfo.cpp @@ -29,7 +29,6 @@ #include "comcallablewrapper.h" #include "runtimecallablewrapper.h" #include "dispparammarshaler.h" -#include "winrttypenameconverter.h" #endif // FEATURE_COMINTEROP @@ -48,21 +47,8 @@ DEFINE_ASM_QUAL_TYPE_NAME(COLOR_TRANSLATOR_ASM_QUAL_TYPE_NAME, g_ColorTranslatorClassName, g_DrawingAsmName); DEFINE_ASM_QUAL_TYPE_NAME(COLOR_ASM_QUAL_TYPE_NAME, g_ColorClassName, g_DrawingAsmName); - DEFINE_ASM_QUAL_TYPE_NAME(URI_ASM_QUAL_TYPE_NAME, g_SystemUriClassName, g_SystemRuntimeAsmName); - - DEFINE_ASM_QUAL_TYPE_NAME(NCCEVENTARGS_ASM_QUAL_TYPE_NAME, g_NotifyCollectionChangedEventArgsName, g_ObjectModelAsmName); - DEFINE_ASM_QUAL_TYPE_NAME(NCCEVENTARGS_MARSHALER_ASM_QUAL_TYPE_NAME, g_NotifyCollectionChangedEventArgsMarshalerName, g_SystemRuntimeWindowsRuntimeAsmName); - - DEFINE_ASM_QUAL_TYPE_NAME(PCEVENTARGS_ASM_QUAL_TYPE_NAME, g_PropertyChangedEventArgsName, g_ObjectModelAsmName); - DEFINE_ASM_QUAL_TYPE_NAME(PCEVENTARGS_MARSHALER_ASM_QUAL_TYPE_NAME, g_PropertyChangedEventArgsMarshalerName, g_SystemRuntimeWindowsRuntimeAsmName); - #define OLECOLOR_TO_SYSTEMCOLOR_METH_NAME "FromOle" #define SYSTEMCOLOR_TO_OLECOLOR_METH_NAME "ToOle" - - #define EVENTARGS_TO_WINRT_EVENTARGS_METH_NAME "ConvertToNative" - #define WINRT_EVENTARGS_TO_EVENTARGS_METH_NAME "ConvertToManaged" - - #define ORIGINALSTRING_PROPERTY_NAME "OriginalString" #endif // FEATURE_COMINTEROP @@ -868,155 +854,6 @@ VOID CollateParamTokens(IMDInternalImport *pInternalImport, mdMethodDef md, ULON #ifdef FEATURE_COMINTEROP - -void *EventArgsMarshalingInfo::operator new(size_t size, LoaderHeap *pHeap) -{ - CONTRACT (void*) - { - THROWS; - GC_NOTRIGGER; - MODE_ANY; - INJECT_FAULT(COMPlusThrowOM()); - PRECONDITION(CheckPointer(pHeap)); - POSTCONDITION(CheckPointer(RETVAL)); - } - CONTRACT_END; - - void* mem = pHeap->AllocMem(S_SIZE_T(size)); - - RETURN mem; -} - -void EventArgsMarshalingInfo::operator delete(void *pMem) -{ - LIMITED_METHOD_CONTRACT; - // Instances of this class are always allocated on the loader heap so - // the delete operator has nothing to do. -} - -EventArgsMarshalingInfo::EventArgsMarshalingInfo() -{ - CONTRACTL - { - THROWS; - GC_TRIGGERS; - MODE_ANY; - } - CONTRACTL_END; - - // Load the System.Collections.Specialized.NotifyCollectionChangedEventArgs class. - SString qualifiedNCCEventArgsTypeName(SString::Utf8, NCCEVENTARGS_ASM_QUAL_TYPE_NAME); - m_hndSystemNCCEventArgsType = TypeName::GetTypeFromAsmQualifiedName(qualifiedNCCEventArgsTypeName.GetUnicode()); - _ASSERTE(!m_hndSystemNCCEventArgsType.IsNull() && "Cannot load System.Collections.Specialized.NotifyCollectionChangedEventArgs!"); - - // Load the System.ComponentModel.PropertyChangedEventArgs class. - SString qualifiedPCEventArgsTypeName(SString::Utf8, PCEVENTARGS_ASM_QUAL_TYPE_NAME); - m_hndSystemPCEventArgsType = TypeName::GetTypeFromAsmQualifiedName(qualifiedPCEventArgsTypeName.GetUnicode()); - _ASSERTE(!m_hndSystemPCEventArgsType.IsNull() && "Cannot load System.ComponentModel.PropertyChangedEventArgs!"); - - // Load the NCCEventArgs marshaler class. - SString qualifiedNCCEventArgsMarshalerTypeName(SString::Utf8, NCCEVENTARGS_MARSHALER_ASM_QUAL_TYPE_NAME); - TypeHandle hndNCCEventArgsMarshalerType = TypeName::GetTypeFromAsmQualifiedName(qualifiedNCCEventArgsMarshalerTypeName.GetUnicode()); - - // Retrieve the method to convert a .NET NCCEventArgs to a WinRT NCCEventArgs. - m_pSystemNCCEventArgsToWinRTNCCEventArgsMD = MemberLoader::FindMethodByName(hndNCCEventArgsMarshalerType.GetMethodTable(), EVENTARGS_TO_WINRT_EVENTARGS_METH_NAME); - _ASSERTE(m_pSystemNCCEventArgsToWinRTNCCEventArgsMD && "Unable to find the marshaler method to convert a .NET NCCEventArgs to a WinRT NCCEventArgs!"); - - // Retrieve the method to convert a WinRT NCCEventArgs to a .NET NCCEventArgs. - m_pWinRTNCCEventArgsToSystemNCCEventArgsMD = MemberLoader::FindMethodByName(hndNCCEventArgsMarshalerType.GetMethodTable(), WINRT_EVENTARGS_TO_EVENTARGS_METH_NAME); - _ASSERTE(m_pWinRTNCCEventArgsToSystemNCCEventArgsMD && "Unable to find the marshaler method to convert a WinRT NCCEventArgs to a .NET NCCEventArgs!"); - - // Load the PCEventArgs marshaler class. - SString qualifiedPCEventArgsMarshalerTypeName(SString::Utf8, PCEVENTARGS_MARSHALER_ASM_QUAL_TYPE_NAME); - TypeHandle hndPCEventArgsMarshalerType = TypeName::GetTypeFromAsmQualifiedName(qualifiedPCEventArgsMarshalerTypeName.GetUnicode()); - - // Retrieve the method to convert a .NET PCEventArgs to a WinRT PCEventArgs. - m_pSystemPCEventArgsToWinRTPCEventArgsMD = MemberLoader::FindMethodByName(hndPCEventArgsMarshalerType.GetMethodTable(), EVENTARGS_TO_WINRT_EVENTARGS_METH_NAME); - _ASSERTE(m_pSystemPCEventArgsToWinRTPCEventArgsMD && "Unable to find the marshaler method to convert a .NET PCEventArgs to a WinRT PCEventArgs!"); - - // Retrieve the method to convert a WinRT PCEventArgs to a .NET PCEventArgs. - m_pWinRTPCEventArgsToSystemPCEventArgsMD = MemberLoader::FindMethodByName(hndPCEventArgsMarshalerType.GetMethodTable(), WINRT_EVENTARGS_TO_EVENTARGS_METH_NAME); - _ASSERTE(m_pWinRTPCEventArgsToSystemPCEventArgsMD && "Unable to find the marshaler method to convert a WinRT PCEventArgs to a .NET PCEventArgs!"); -} - -EventArgsMarshalingInfo::~EventArgsMarshalingInfo() -{ - LIMITED_METHOD_CONTRACT; -} - -void *UriMarshalingInfo::operator new(size_t size, LoaderHeap *pHeap) -{ - CONTRACT (void*) - { - THROWS; - GC_NOTRIGGER; - MODE_ANY; - INJECT_FAULT(COMPlusThrowOM()); - PRECONDITION(CheckPointer(pHeap)); - POSTCONDITION(CheckPointer(RETVAL)); - } - CONTRACT_END; - - void* mem = pHeap->AllocMem(S_SIZE_T(size)); - - RETURN mem; -} - - -void UriMarshalingInfo::operator delete(void *pMem) -{ - LIMITED_METHOD_CONTRACT; - // Instances of this class are always allocated on the loader heap so - // the delete operator has nothing to do. -} - -UriMarshalingInfo::UriMarshalingInfo() -{ - CONTRACTL - { - THROWS; - GC_TRIGGERS; - MODE_ANY; - } - CONTRACTL_END; - - // Create on-demand as we don't want to create the factories in NGEN time - m_pUriFactory = NULL; - - // Load the System.Uri class. - SString qualifiedUriTypeName(SString::Utf8, URI_ASM_QUAL_TYPE_NAME); - m_hndSystemUriType = TypeName::GetTypeFromAsmQualifiedName(qualifiedUriTypeName.GetUnicode()); - _ASSERTE(!m_hndSystemUriType.IsNull() && "Cannot load System.Uri!"); - - m_SystemUriOriginalStringGetterMD = MemberLoader::FindPropertyMethod(m_hndSystemUriType.GetMethodTable(), ORIGINALSTRING_PROPERTY_NAME, PropertyGet); - _ASSERTE(m_SystemUriOriginalStringGetterMD && "Unable to find the System.Uri.get_OriginalString()!"); - _ASSERTE(!m_SystemUriOriginalStringGetterMD->IsStatic() && "System.Uri.get_OriginalString() is static!"); - - // Windows.Foundation.Uri..ctor(string) and System.Uri..ctor(string) - MethodTable* pSystemUriMT = m_hndSystemUriType.AsMethodTable(); - m_SystemUriCtorMD = MemberLoader::FindConstructor(pSystemUriMT, &gsig_IM_Str_RetVoid); - _ASSERTE(m_SystemUriCtorMD && "Unable to find the constructor on System.Uri that takes a string!"); - _ASSERTE(m_SystemUriCtorMD->IsClassConstructorOrCtor() && !m_SystemUriCtorMD->IsStatic() && "The method retrieved from System.Uri is not a constructor!"); -} - -UriMarshalingInfo::~UriMarshalingInfo() -{ - CONTRACTL - { - NOTHROW; - GC_TRIGGERS; - MODE_ANY; - } - CONTRACTL_END; -#ifndef CROSSGEN_COMPILE - if (m_pUriFactory) - { - SafeRelease(m_pUriFactory); - m_pUriFactory = NULL; - } -#endif -} - OleColorMarshalingInfo::OleColorMarshalingInfo() : m_OleColorToSystemColorMD(NULL), m_SystemColorToOleColorMD(NULL) @@ -1121,18 +958,6 @@ EEMarshalingData::~EEMarshalingData() delete m_pOleColorInfo; m_pOleColorInfo = NULL; } - - if (m_pUriInfo) - { - delete m_pUriInfo; - m_pUriInfo = NULL; - } - - if (m_pEventArgsInfo) - { - delete m_pEventArgsInfo; - m_pEventArgsInfo = NULL; - } #endif } @@ -1314,62 +1139,6 @@ CustomMarshalerInfo *EEMarshalingData::GetCustomMarshalerInfo(SharedCustomMarsha #endif // CROSSGEN_COMPILE #ifdef FEATURE_COMINTEROP -UriMarshalingInfo *EEMarshalingData::GetUriMarshalingInfo() -{ - CONTRACT (UriMarshalingInfo*) - { - THROWS; - GC_TRIGGERS; - MODE_ANY; - INJECT_FAULT(COMPlusThrowOM()); - POSTCONDITION(CheckPointer(RETVAL)); - } - CONTRACT_END; - - if (m_pUriInfo == NULL) - { - UriMarshalingInfo *pUriInfo = new (m_pHeap) UriMarshalingInfo(); - - if (InterlockedCompareExchangeT(&m_pUriInfo, pUriInfo, NULL) != NULL) - { - // Another thread beat us to it. Delete on UriMarshalingInfo is an empty operation - // which is OK, since the possible leak is rare, small, and constant. This is the same - // pattern as in code:GetCustomMarshalerInfo. - delete pUriInfo; - } - } - - RETURN m_pUriInfo; -} - -EventArgsMarshalingInfo *EEMarshalingData::GetEventArgsMarshalingInfo() -{ - CONTRACT (EventArgsMarshalingInfo*) - { - THROWS; - GC_TRIGGERS; - MODE_ANY; - INJECT_FAULT(COMPlusThrowOM()); - POSTCONDITION(CheckPointer(RETVAL)); - } - CONTRACT_END; - - if (m_pEventArgsInfo == NULL) - { - EventArgsMarshalingInfo *pEventArgsInfo = new (m_pHeap) EventArgsMarshalingInfo(); - - if (InterlockedCompareExchangeT(&m_pEventArgsInfo, pEventArgsInfo, NULL) != NULL) - { - // Another thread beat us to it. Delete on EventArgsMarshalingInfo is an empty operation - // which is OK, since the possible leak is rare, small, and constant. This is the same - // pattern as in code:GetCustomMarshalerInfo. - delete pEventArgsInfo; - } - } - - RETURN m_pEventArgsInfo; -} - OleColorMarshalingInfo *EEMarshalingData::GetOleColorMarshalingInfo() { CONTRACT (OleColorMarshalingInfo*) @@ -1466,13 +1235,7 @@ MarshalInfo::MarshalInfo(Module* pModule, #ifdef FEATURE_COMINTEROP m_fDispItf = FALSE; - m_fInspItf = FALSE; m_fErrorNativeType = FALSE; - m_hiddenLengthParamIndex = (UINT16)-1; - m_dwHiddenLengthManagedHomeLocal= 0xFFFFFFFF; - m_dwHiddenLengthNativeHomeLocal = 0xFFFFFFFF; - - m_pDefaultItfMT = NULL; #endif // FEATURE_COMINTEROP @@ -1527,16 +1290,6 @@ MarshalInfo::MarshalInfo(Module* pModule, corElemType = sig.PeekElemTypeNormalized(pModule, pTypeContext); mtype = corElemType; -#ifdef FEATURE_COMINTEROP - if (IsWinRTScenario() && nativeType != NATIVE_TYPE_DEFAULT) - { - // Do not allow any MarshalAs in WinRT scenarios - marshaling is fully described by the parameter type. - m_type = MARSHAL_TYPE_UNKNOWN; - m_resID = IDS_EE_BADMARSHAL_WINRT_MARSHAL_AS; - IfFailGoto(E_FAIL, lFail); - } -#endif // FEATURE_COMINTEROP - // Make sure SizeParamIndex < numArgs when marshalling native arrays if (nativeType == NATIVE_TYPE_ARRAY && ParamInfo.m_SizeIsSpecified) { @@ -1583,16 +1336,6 @@ MarshalInfo::MarshalInfo(Module* pModule, // Check for valid ET_PTR signature if (mtype == ELEMENT_TYPE_PTR) { -#ifdef FEATURE_COMINTEROP - // WinRT does not support ET_PTR - if (IsWinRTScenario()) - { - m_type = MARSHAL_TYPE_UNKNOWN; - m_resID = IDS_EE_BADMARSHAL_WINRT_ILLEGAL_TYPE; - IfFailGoto(E_FAIL, lFail); - } -#endif // FEATURE_COMINTEROP - SigPointer sigtmp = sig; IfFailGoto(sigtmp.GetElemType(NULL), lFail); @@ -1749,11 +1492,6 @@ MarshalInfo::MarshalInfo(Module* pModule, // 2-byte COM VARIANT_BOOL m_type = MARSHAL_TYPE_VTBOOL; } - else if (IsWinRTScenario()) - { - // 1-byte WinRT bool - m_type = MARSHAL_TYPE_CBOOL; - } else #endif // FEATURE_COMINTEROP { @@ -1940,10 +1678,6 @@ MarshalInfo::MarshalInfo(Module* pModule, break; case ELEMENT_TYPE_PTR: -#ifdef FEATURE_COMINTEROP - _ASSERTE(!IsWinRTScenario()); // we checked for this earlier -#endif // FEATURE_COMINTEROP - if (nativeType != NATIVE_TYPE_DEFAULT) { m_resID = IDS_EE_BADMARSHAL_PTR; @@ -1957,14 +1691,6 @@ MarshalInfo::MarshalInfo(Module* pModule, break; case ELEMENT_TYPE_FNPTR: -#ifdef FEATURE_COMINTEROP - if (IsWinRTScenario()) - { - m_resID = IDS_EE_BADMARSHAL_WINRT_ILLEGAL_TYPE; - IfFailGoto(E_FAIL, lFail); - } -#endif // FEATURE_COMINTEROP - if (!(nativeType == NATIVE_TYPE_FUNC || nativeType == NATIVE_TYPE_DEFAULT)) { m_resID = IDS_EE_BADMARSHAL_FNPTR; @@ -1984,16 +1710,11 @@ MarshalInfo::MarshalInfo(Module* pModule, { TypeHandle sigTH = sig.GetTypeHandleThrowing(pModule, pTypeContext); - // Disallow marshaling generic types except for WinRT interfaces. + // Disallow marshaling generic types. if (sigTH.HasInstantiation()) { -#ifdef FEATURE_COMINTEROP - if (!sigTH.SupportsGenericInterop(TypeHandle::Interop_NativeToManaged)) -#endif // FEATURE_COMINTEROP - { - m_resID = IDS_EE_BADMARSHAL_GENERICS_RESTRICTION; - IfFailGoto(E_FAIL, lFail); - } + m_resID = IDS_EE_BADMARSHAL_GENERICS_RESTRICTION; + IfFailGoto(E_FAIL, lFail); } m_pMT = sigTH.GetMethodTable(); @@ -2001,30 +1722,6 @@ MarshalInfo::MarshalInfo(Module* pModule, IfFailGoto(COR_E_TYPELOAD, lFail); #ifdef FEATURE_COMINTEROP - MethodTable* pDefaultMT = NULL; - - // Look for marshaling of WinRT runtime classes - if ((m_pMT->IsProjectedFromWinRT() || m_pMT->IsExportedToWinRT()) && !m_pMT->HasExplicitGuid()) - { - // The type loader guarantees that there are no WinRT interfaces without explicit GUID - _ASSERTE(!m_pMT->IsInterface()); - - // Make sure that this is really a legal runtime class and not a custom attribute or delegate - if (!m_pMT->IsLegalNonArrayWinRTType() || m_pMT->IsDelegate()) - { - m_resID = IDS_EE_BADMARSHAL_WINRT_ILLEGAL_TYPE; - IfFailGoto(E_FAIL, lFail); - } - - // This class must have a default interface that describes how it is marshaled - pDefaultMT = m_pMT->GetDefaultWinRTInterface(); - if (pDefaultMT == NULL) - { - m_resID = IDS_EE_BADMARSHAL_WINRT_MISSING_GUID; - IfFailGoto(E_FAIL, lFail); - } - } - if (nativeType == NATIVE_TYPE_INTF) { // whatever... @@ -2036,62 +1733,14 @@ MarshalInfo::MarshalInfo(Module* pModule, if (COMDelegate::IsDelegate(m_pMT)) { - if (IsWinRTScenario()) - { - // In WinRT scenarios delegates must be WinRT delegates - if (!m_pMT->IsProjectedFromWinRT() && !WinRTTypeNameConverter::IsRedirectedType(m_pMT)) - { - m_resID = IDS_EE_BADMARSHAL_WINRT_DELEGATE; - IfFailGoto(E_FAIL, lFail); - } - } - else - { - // UnmanagedType.Interface for delegates used to mean the .NET Framework _Delegate interface. - // We don't support that interface in .NET Core, so we disallow marshalling as it here. - // The user can specify UnmanagedType.IDispatch and use the delegate through the IDispatch interface - // if they need an interface pointer. - m_resID = IDS_EE_BADMARSHAL_DELEGATE_TLB_INTERFACE; - IfFailGoto(E_FAIL, lFail); - } - } - m_type = MARSHAL_TYPE_INTERFACE; - } - else if (pDefaultMT != NULL && nativeType == NATIVE_TYPE_DEFAULT) - { - // Pretend this is really marshaling as the default interface type - - // Validate it's a WinRT interface with GUID - if (!pDefaultMT->IsInterface() || - (!pDefaultMT->IsProjectedFromWinRT() && !pDefaultMT->IsExportedToWinRT()) || - !pDefaultMT->HasExplicitGuid()) - { - // This might also be a redirected interface - which is also allowed - if (!pDefaultMT->IsWinRTRedirectedInterface(TypeHandle::Interop_NativeToManaged)) - { - m_resID = IDS_EE_BADMARSHAL_DEFAULTIFACE_NOT_WINRT_IFACE; - IfFailGoto(E_FAIL, lFail); - } - } - - // Validate that it's one of the component interfaces of the class in the signature - if (!m_pMT->ImplementsEquivalentInterface(pDefaultMT)) - { - m_resID = IDS_EE_BADMARSHAL_DEFAULTIFACE_NOT_SUBTYPE; - IfFailGoto(E_FAIL, lFail); - } - - // Make sure it's not an unexpected generic case (not clear we can actually get here in practice due - // to the above Implements check) - if (pDefaultMT->HasInstantiation() && !pDefaultMT->SupportsGenericInterop(TypeHandle::Interop_NativeToManaged)) - { - m_resID = IDS_EE_BADMARSHAL_GENERICS_RESTRICTION; + // UnmanagedType.Interface for delegates used to mean the .NET Framework _Delegate interface. + // We don't support that interface in .NET Core, so we disallow marshalling as it here. + // The user can specify UnmanagedType.IDispatch and use the delegate through the IDispatch interface + // if they need an interface pointer. + m_resID = IDS_EE_BADMARSHAL_DELEGATE_TLB_INTERFACE; IfFailGoto(E_FAIL, lFail); } - - // Store the marshal data just as if we were marshaling as this default interface type m_type = MARSHAL_TYPE_INTERFACE; - m_pDefaultItfMT = pDefaultMT; } else #endif // FEATURE_COMINTEROP @@ -2188,7 +1837,7 @@ MarshalInfo::MarshalInfo(Module* pModule, IfFailGoto(E_FAIL, lFail); } - m_type = MARSHAL_TYPE_HSTRING; + IfFailGoto(E_FAIL, lFail); break; } #endif // FEATURE_COMINTEROP @@ -2212,17 +1861,7 @@ MarshalInfo::MarshalInfo(Module* pModule, case NATIVE_TYPE_DEFAULT: { #ifdef FEATURE_COMINTEROP - if (IsWinRTScenario()) - { - if (builder) - { - m_resID = IDS_EE_BADMARSHALPARAM_STRINGBUILDER; - IfFailGoto(E_FAIL, lFail); - } - - m_type = MARSHAL_TYPE_HSTRING; - } - else if (m_ms == MARSHAL_SCENARIO_COMINTEROP) + if (m_ms == MARSHAL_SCENARIO_COMINTEROP) { m_type = builder ? MARSHAL_TYPE_LPWSTR_BUFFER : MARSHAL_TYPE_BSTR; } @@ -2321,34 +1960,11 @@ MarshalInfo::MarshalInfo(Module* pModule, IfFailGoto(E_FAIL, lFail); } m_type = MARSHAL_TYPE_INTERFACE; - - if (IsWinRTScenario()) - { - // all interfaces marshaled in WinRT scenarios are IInspectable-based - m_fInspItf = TRUE; - } - } - // Check for Windows.Foundation.HResult <-> Exception - else if (IsWinRTScenario() && MscorlibBinder::IsClass(m_pMT, CLASS__EXCEPTION)) - { - m_args.m_pMT = m_pMT; - m_type = MARSHAL_TYPE_EXCEPTION; } #endif // FEATURE_COMINTEROP else if (COMDelegate::IsDelegate(m_pMT)) { m_args.m_pMT = m_pMT; -#ifdef FEATURE_COMINTEROP - if (IsWinRTScenario()) - { - // Delegates must be imported from WinRT and marshaled as Interface - if (!m_pMT->IsProjectedFromWinRT() && !WinRTTypeNameConverter::IsRedirectedType(m_pMT)) - { - m_resID = IDS_EE_BADMARSHAL_WINRT_DELEGATE; - IfFailGoto(E_FAIL, lFail); - } - } -#endif // FEATURE_COMINTEROP switch (nativeType) { @@ -2358,11 +1974,7 @@ MarshalInfo::MarshalInfo(Module* pModule, case NATIVE_TYPE_DEFAULT: #ifdef FEATURE_COMINTEROP - if (IsWinRTScenario() || m_pMT->IsProjectedFromWinRT() || WinRTTypeNameConverter::IsRedirectedType(m_pMT)) - { - m_type = MARSHAL_TYPE_INTERFACE; - } - else if (m_ms == MARSHAL_SCENARIO_COMINTEROP) + if (m_ms == MARSHAL_SCENARIO_COMINTEROP) { // Default for COM marshalling for delegates used to mean the .NET Framework _Delegate interface. // We don't support that interface in .NET Core, so we disallow marshalling as it here. @@ -2407,33 +2019,13 @@ MarshalInfo::MarshalInfo(Module* pModule, m_type = IsFieldScenario() ? MARSHAL_TYPE_LAYOUTCLASS : MARSHAL_TYPE_LAYOUTCLASSPTR; m_args.m_pMT = m_pMT; } -#ifdef FEATURE_COMINTEROP - else if (IsWinRTScenario() && !IsFieldScenario() && sig.IsClassThrowing(pModule, g_SystemUriClassName, pTypeContext)) - { - m_type = MARSHAL_TYPE_URI; - } - else if (IsWinRTScenario() && !IsFieldScenario() && sig.IsClassThrowing(pModule, g_NotifyCollectionChangedEventArgsName, pTypeContext)) - { - m_type = MARSHAL_TYPE_NCCEVENTARGS; - } - else if (IsWinRTScenario() && !IsFieldScenario() && sig.IsClassThrowing(pModule, g_PropertyChangedEventArgsName, pTypeContext)) - { - m_type = MARSHAL_TYPE_PCEVENTARGS; - } -#endif // FEATURE_COMINTEROP else if (m_pMT->IsObjectClass()) { switch(nativeType) { #ifdef FEATURE_COMINTEROP case NATIVE_TYPE_DEFAULT: - if (IsWinRTScenario()) - { - m_fInspItf = TRUE; - m_type = MARSHAL_TYPE_INTERFACE; - break; - } - else if (ms == MARSHAL_SCENARIO_FIELD) + if (ms == MARSHAL_SCENARIO_FIELD) { m_type = MARSHAL_TYPE_INTERFACE; break; @@ -2454,8 +2046,7 @@ MarshalInfo::MarshalInfo(Module* pModule, break; case NATIVE_TYPE_IINSPECTABLE: - m_fInspItf = TRUE; - m_type = MARSHAL_TYPE_INTERFACE; + m_resID = IDS_EE_NO_IINSPECTABLE; break; #else case NATIVE_TYPE_DEFAULT: @@ -2483,12 +2074,6 @@ MarshalInfo::MarshalInfo(Module* pModule, #ifdef FEATURE_COMINTEROP else if (sig.IsClassThrowing(pModule, g_ArrayClassName, pTypeContext)) { - if (IsWinRTScenario()) - { - m_resID = IDS_EE_BADMARSHAL_WINRT_ILLEGAL_TYPE; - IfFailGoto(E_FAIL, lFail); - } - switch(nativeType) { case NATIVE_TYPE_DEFAULT: @@ -2533,21 +2118,9 @@ MarshalInfo::MarshalInfo(Module* pModule, _ASSERTE(!"This invalid signature should never be hit!"); IfFailGoto(E_FAIL, lFail); } - else if ((IsWinRTScenario()) && sig.IsClassThrowing(pModule, g_TypeClassName, pTypeContext)) - { - m_type = MARSHAL_TYPE_SYSTEMTYPE; - } #endif // FEATURE_COMINTEROP else if (!m_pMT->IsValueType()) { -#ifdef FEATURE_COMINTEROP - if (IsWinRTScenario() && !m_pMT->IsLegalNonArrayWinRTType()) - { - m_resID = IDS_EE_BADMARSHAL_WINRT_ILLEGAL_TYPE; - IfFailGoto(E_FAIL, lFail); - } -#endif // FEATURE_COMINTEROP - if (!(nativeType == NATIVE_TYPE_INTF || nativeType == NATIVE_TYPE_DEFAULT)) { m_resID = IDS_EE_BADMARSHAL_NOLAYOUT; @@ -2625,18 +2198,6 @@ MarshalInfo::MarshalInfo(Module* pModule, IfFailGoto(E_FAIL, lFail); } } -#ifdef FEATURE_COMINTEROP - else if (sig.IsClassThrowing(pModule, g_DateTimeOffsetClassName, pTypeContext)) - { - if (!(nativeType == NATIVE_TYPE_DEFAULT || nativeType == NATIVE_TYPE_STRUCT)) - { - m_resID = IDS_EE_BADMARSHAL_DATETIMEOFFSET; - IfFailGoto(E_FAIL, lFail); - } - m_type = MARSHAL_TYPE_DATETIME; - m_pMT = MscorlibBinder::GetClass(CLASS__DATE_TIME_OFFSET); - } -#endif // FEATURE_COMINTEROP else if (sig.IsClassThrowing(pModule, g_DateClassName, pTypeContext)) { if (!(nativeType == NATIVE_TYPE_DEFAULT || nativeType == NATIVE_TYPE_STRUCT)) @@ -2732,37 +2293,6 @@ MarshalInfo::MarshalInfo(Module* pModule, if (m_pMT == NULL) break; -#ifdef FEATURE_COMINTEROP - // Handle Nullable and KeyValuePair for WinRT - if (IsWinRTScenario()) - { - if (m_pMT->HasSameTypeDefAs(g_pNullableClass)) - { - m_type = MARSHAL_TYPE_NULLABLE; - m_args.m_pMT = m_pMT; - break; - } - - if (m_pMT->HasSameTypeDefAs(MscorlibBinder::GetClass(CLASS__KEYVALUEPAIRGENERIC))) - { - if (IsFieldScenario()) - { - m_resID = IDS_EE_BADMARSHAL_WINRT_ILLEGAL_TYPE; - IfFailGoto(E_FAIL, lFail); - } - m_type = MARSHAL_TYPE_KEYVALUEPAIR; - m_args.m_pMT = m_pMT; - break; - } - - if (!m_pMT->IsLegalNonArrayWinRTType()) - { - m_resID = IDS_EE_BADMARSHAL_WINRT_ILLEGAL_TYPE; - IfFailGoto(E_FAIL, lFail); - } - } -#endif // FEATURE_COMINTEROP - // Blittable generics are allowed to be marshalled with the following exceptions: // * ByReference: This represents an interior pointer and is not actually blittable // * Nullable: We don't want to be locked into the default behavior as we may want special handling later @@ -2824,16 +2354,6 @@ MarshalInfo::MarshalInfo(Module* pModule, { if (fNeedsCopyCtor && !IsFieldScenario()) // We don't support automatically discovering copy constructors for fields. { -#ifdef FEATURE_COMINTEROP - if (IsWinRTScenario()) - { - // our WinRT-optimized GetCOMIPFromRCW helpers don't support copy - // constructor stubs so make sure that this marshaler will not be used - m_resID = IDS_EE_BADMARSHAL_WINRT_COPYCTOR; - IfFailGoto(E_FAIL, lFail); - } -#endif - MethodDesc *pCopyCtor; MethodDesc *pDtor; FindCopyCtor(pModule, m_pMT, &pCopyCtor); @@ -2897,15 +2417,10 @@ MarshalInfo::MarshalInfo(Module* pModule, TypeHandle thElement = arrayTypeHnd.GetArrayElementTypeHandle(); -#ifdef FEATURE_COMINTEROP - if (m_ms != MARSHAL_SCENARIO_WINRT) -#endif // FEATURE_COMINTEROP + if (thElement.HasInstantiation() && !thElement.IsBlittable()) { - if (thElement.HasInstantiation() && !thElement.IsBlittable()) - { - m_resID = IDS_EE_BADMARSHAL_GENERICS_RESTRICTION; - IfFailGoto(E_FAIL, lFail); - } + m_resID = IDS_EE_BADMARSHAL_GENERICS_RESTRICTION; + IfFailGoto(E_FAIL, lFail); } m_args.na.m_pArrayMT = arrayTypeHnd.AsMethodTable(); @@ -2960,14 +2475,6 @@ lExit: COMPlusThrow(kPlatformNotSupportedException, m_resID); } - - if (IsWinRTScenario() && !IsSupportedForWinRT(m_type)) - { - // the marshaler we came up with is not supported in WinRT scenarios - m_type = MARSHAL_TYPE_UNKNOWN; - m_resID = IDS_EE_BADMARSHAL_WINRT_ILLEGAL_TYPE; - goto lReallyExit; - } #endif // FEATURE_COMINTEROP if (m_byref && !isParam) @@ -3102,7 +2609,7 @@ VOID MarshalInfo::EmitOrThrowInteropParamException(NDirectStubLinker* psl, BOOL #ifdef FEATURE_COMINTEROP // If this is not forward COM interop, throw the exception right away. We rely on this // for example in code:ComPreStubWorker when we fire the InvalidMemberDeclaration MDA. - if ((m_ms == MARSHAL_SCENARIO_COMINTEROP || IsWinRTScenario()) && fMngToNative && !IsFieldScenario()) + if (m_ms == MARSHAL_SCENARIO_COMINTEROP && fMngToNative && !IsFieldScenario()) { psl->SetInteropParamExceptionInfo(resID, paramIdx); return; @@ -3153,11 +2660,7 @@ HRESULT MarshalInfo::HandleArrayElemType(NativeTypeParamInfo *pParamInfo, TypeHa // #ifdef FEATURE_COMINTEROP - if (IsWinRTScenario()) - { - m_type = MARSHAL_TYPE_HIDDENLENGTHARRAY; - } - else if (pParamInfo->m_NativeType == NATIVE_TYPE_SAFEARRAY) + if (pParamInfo->m_NativeType == NATIVE_TYPE_SAFEARRAY) { m_type = MARSHAL_TYPE_SAFEARRAY; } @@ -3205,10 +2708,6 @@ HRESULT MarshalInfo::HandleArrayElemType(NativeTypeParamInfo *pParamInfo, TypeHa { arrayMarshalInfo.InitForSafeArray(m_ms, thElement, pParamInfo->m_SafeArrayElementVT, m_fAnsi); } - else if (m_type == MARSHAL_TYPE_HIDDENLENGTHARRAY) - { - arrayMarshalInfo.InitForHiddenLengthArray(thElement); - } else #endif // FEATURE_COMINTEROP if (m_type == MARSHAL_TYPE_FIXED_ARRAY) @@ -3257,14 +2756,6 @@ HRESULT MarshalInfo::HandleArrayElemType(NativeTypeParamInfo *pParamInfo, TypeHa } } } -#ifdef FEATURE_COMINTEROP - else if (m_type == MARSHAL_TYPE_HIDDENLENGTHARRAY) - { - m_args.na.m_vt = m_arrayElementType; - m_args.na.m_cbElementSize = arrayMarshalInfo.GetElementSize(); - m_args.na.m_redirectedTypeIndex = arrayMarshalInfo.GetRedirectedTypeIndex(); - } -#endif // FEATURE_COMINTEROP return S_OK; } @@ -3282,7 +2773,7 @@ ILMarshaler* CreateILMarshaler(MarshalInfo::MarshalType mtype, NDirectStubLinker switch (mtype) { -#define DEFINE_MARSHALER_TYPE(mt, mclass, fWinRTSupported) \ +#define DEFINE_MARSHALER_TYPE(mt, mclass) \ case MarshalInfo::mt: \ pMarshaler = new IL##mclass(); \ break; @@ -3602,7 +3093,7 @@ UINT16 MarshalInfo::GetNativeSize(MarshalType mtype) static const BYTE nativeSizes[]= { - #define DEFINE_MARSHALER_TYPE(mt, mclass, fWinRTSupported) IL##mclass::c_nativeSize, + #define DEFINE_MARSHALER_TYPE(mt, mclass) IL##mclass::c_nativeSize, #include "mtypes.h" }; @@ -3638,7 +3129,7 @@ bool MarshalInfo::IsInOnly(MarshalType mtype) static const bool ILMarshalerIsInOnly[] = { - #define DEFINE_MARSHALER_TYPE(mt, mclass, fWinRTSupported) \ + #define DEFINE_MARSHALER_TYPE(mt, mclass) \ (IL##mclass::c_fInOnly ? true : false), #include "mtypes.h" @@ -3647,27 +3138,6 @@ bool MarshalInfo::IsInOnly(MarshalType mtype) return ILMarshalerIsInOnly[mtype]; } -bool MarshalInfo::IsSupportedForWinRT(MarshalType mtype) -{ - CONTRACTL - { - NOTHROW; - GC_NOTRIGGER; - MODE_ANY; - } - CONTRACTL_END; - - static const bool MarshalerSupportsWinRT[] = - { - #define DEFINE_MARSHALER_TYPE(mt, mclass, fWinRTSupported) \ - fWinRTSupported, - - #include "mtypes.h" - }; - - return MarshalerSupportsWinRT[mtype]; -} - OVERRIDEPROC MarshalInfo::GetArgumentOverrideProc(MarshalType mtype) { CONTRACTL @@ -3680,7 +3150,7 @@ OVERRIDEPROC MarshalInfo::GetArgumentOverrideProc(MarshalType mtype) static const OVERRIDEPROC ILArgumentOverrideProcs[] = { - #define DEFINE_MARSHALER_TYPE(mt, mclass, fWinRTSupported) IL##mclass::ArgumentOverride, + #define DEFINE_MARSHALER_TYPE(mt, mclass) IL##mclass::ArgumentOverride, #include "mtypes.h" }; @@ -3700,7 +3170,7 @@ RETURNOVERRIDEPROC MarshalInfo::GetReturnOverrideProc(MarshalType mtype) static const RETURNOVERRIDEPROC ILReturnOverrideProcs[] = { - #define DEFINE_MARSHALER_TYPE(mt, mclass, fWinRTSupported) IL##mclass::ReturnOverride, + #define DEFINE_MARSHALER_TYPE(mt, mclass) IL##mclass::ReturnOverride, #include "mtypes.h" }; @@ -3713,18 +3183,12 @@ void MarshalInfo::GetItfMarshalInfo(ItfMarshalInfo* pInfo) STANDARD_VM_CONTRACT; GetItfMarshalInfo(TypeHandle(m_pMT), -#ifdef FEATURE_COMINTEROP - TypeHandle(m_pDefaultItfMT), -#else // FEATURE_COMINTEROP - TypeHandle(), -#endif // FEATURE_COMINTEROP m_fDispItf, - m_fInspItf, m_ms, pInfo); } -void MarshalInfo::GetItfMarshalInfo(TypeHandle th, TypeHandle thItf, BOOL fDispItf, BOOL fInspItf, MarshalScenario ms, ItfMarshalInfo *pInfo) +void MarshalInfo::GetItfMarshalInfo(TypeHandle th, BOOL fDispItf, MarshalScenario ms, ItfMarshalInfo *pInfo) { CONTRACTL { @@ -3752,96 +3216,64 @@ void MarshalInfo::GetItfMarshalInfo(TypeHandle th, TypeHandle thItf, BOOL fDispI // Set the class method table. pInfo->thClass = th; - if (th.IsTypeDesc() || !th.AsMethodTable()->IsWinRTDelegate()) - { - // If this is not a WinRT delegate, retrieve the default interface method table. - TypeHandle hndDefItfClass; - DefaultInterfaceType DefItfType; + TypeHandle hndDefItfClass; + DefaultInterfaceType DefItfType; - if (!thItf.IsNull()) + DefItfType = GetDefaultInterfaceForClassWrapper(th, &hndDefItfClass); + switch (DefItfType) + { + case DefaultInterfaceType_Explicit: { - hndDefItfClass = thItf; - DefItfType = DefaultInterfaceType_Explicit; + pInfo->thItf = hndDefItfClass; + switch (hndDefItfClass.GetComInterfaceType()) + { + case ifDispatch: + case ifDual: + pInfo->dwFlags |= ItfMarshalInfo::ITF_MARSHAL_DISP_ITF; + break; + } + break; } - else if (th.IsProjectedFromWinRT() || th.IsExportedToWinRT()) + + case DefaultInterfaceType_AutoDual: { - // WinRT classes use their WinRT default interface - hndDefItfClass = th.GetMethodTable()->GetDefaultWinRTInterface(); - DefItfType = DefaultInterfaceType_Explicit; + pInfo->thItf = hndDefItfClass; + pInfo->dwFlags |= ItfMarshalInfo::ITF_MARSHAL_DISP_ITF; + break; } - else + + case DefaultInterfaceType_IUnknown: + case DefaultInterfaceType_BaseComClass: { - DefItfType = GetDefaultInterfaceForClassWrapper(th, &hndDefItfClass); + break; } - switch (DefItfType) - { - case DefaultInterfaceType_Explicit: - { - pInfo->thItf = hndDefItfClass; - switch (hndDefItfClass.GetComInterfaceType()) - { - case ifDispatch: - case ifDual: - pInfo->dwFlags |= ItfMarshalInfo::ITF_MARSHAL_DISP_ITF; - break; - - case ifInspectable: - pInfo->dwFlags |= ItfMarshalInfo::ITF_MARSHAL_INSP_ITF; - break; - } - break; - } - - case DefaultInterfaceType_AutoDual: - { - pInfo->thItf = hndDefItfClass; - pInfo->dwFlags |= ItfMarshalInfo::ITF_MARSHAL_DISP_ITF; - break; - } - case DefaultInterfaceType_IUnknown: - case DefaultInterfaceType_BaseComClass: - { - break; - } - - case DefaultInterfaceType_AutoDispatch: - { - pInfo->thItf = hndDefItfClass; - pInfo->dwFlags |= ItfMarshalInfo::ITF_MARSHAL_DISP_ITF; - break; - } + case DefaultInterfaceType_AutoDispatch: + { + pInfo->thItf = hndDefItfClass; + pInfo->dwFlags |= ItfMarshalInfo::ITF_MARSHAL_DISP_ITF; + break; + } - default: - { - _ASSERTE(!"Invalid default interface type!"); - break; - } + default: + { + _ASSERTE(!"Invalid default interface type!"); + break; } } } else { - // The type will be marshalled as an IUnknown, IInspectable, or IDispatch pointer depending + // The type will be marshalled as an IUnknown or IDispatch pointer depending // on the value of fDispItf and fInspItf if (fDispItf) { pInfo->dwFlags |= ItfMarshalInfo::ITF_MARSHAL_DISP_ITF; } - else if (fInspItf) - { - pInfo->dwFlags |= ItfMarshalInfo::ITF_MARSHAL_INSP_ITF; - } pInfo->dwFlags |= ItfMarshalInfo::ITF_MARSHAL_USE_BASIC_ITF; } } - else if (fInspItf) - { - // IInspectable-based interfaces are simple - pInfo->thItf = th; - pInfo->dwFlags |= ItfMarshalInfo::ITF_MARSHAL_INSP_ITF; - } else { // Determine the interface this type will be marshalled as. @@ -3850,17 +3282,13 @@ void MarshalInfo::GetItfMarshalInfo(TypeHandle th, TypeHandle thItf, BOOL fDispI else pInfo->thItf = th; - // Determine if we are dealing with an IDispatch, IInspectable, or IUnknown based interface. + // Determine if we are dealing with an IDispatch or IUnknown based interface. switch (pInfo->thItf.GetComInterfaceType()) { case ifDispatch: case ifDual: pInfo->dwFlags |= ItfMarshalInfo::ITF_MARSHAL_DISP_ITF; break; - - case ifInspectable: - pInfo->dwFlags |= ItfMarshalInfo::ITF_MARSHAL_INSP_ITF; - break; } // Look to see if the interface has a coclass defined @@ -3874,53 +3302,6 @@ void MarshalInfo::GetItfMarshalInfo(TypeHandle th, TypeHandle thItf, BOOL fDispI // store the pre-redirection interface type as thNativeItf pInfo->thNativeItf = pInfo->thItf; - if (ms == MarshalInfo::MARSHAL_SCENARIO_WINRT || ms == MarshalInfo::MARSHAL_SCENARIO_WINRT_FIELD) - { - // Use the "class is hint" flag so GetObjectRefFromComIP doesn't verify that the - // WinRT object really supports IInspectable - note that we'll do the verification - // in UnmarshalObjectFromInterface for this exact pInfo->thItf. - pInfo->dwFlags |= ItfMarshalInfo::ITF_MARSHAL_CLASS_IS_HINT; - - pInfo->dwFlags |= ItfMarshalInfo::ITF_MARSHAL_WINRT_SCENARIO; - - // Perform interface redirection statically here. When the resulting ItfMarshalInfo - // is used for CLR->WinRT marshaling, this is necessary so we know which COM vtable - // to pass out (for instance IList could be marshaled out as IList or IBindableVector - // depending on the marshal scenario). In the WinRT->CLR direction, it's just an - // optimization which saves us from performing redirection at run-time. - - if (!pInfo->thItf.IsNull()) - { - MethodTable *pNewItfMT1; - MethodTable *pNewItfMT2; - switch (RCW::GetInterfacesForQI(pInfo->thItf.GetMethodTable(), &pNewItfMT1, &pNewItfMT2)) - { - case RCW::InterfaceRedirection_None: - case RCW::InterfaceRedirection_UnresolvedIEnumerable: - break; - - case RCW::InterfaceRedirection_IEnumerable_RetryOnFailure: - case RCW::InterfaceRedirection_IEnumerable: - case RCW::InterfaceRedirection_Other: - pInfo->thNativeItf = pNewItfMT1; - break; - - case RCW::InterfaceRedirection_Other_RetryOnFailure: - pInfo->thNativeItf = pNewItfMT2; - break; - } - } - - if (!pInfo->thNativeItf.IsNull()) - { - // The native interface is redirected WinRT interface - need to change the flags - _ASSERTE(pInfo->thNativeItf.AsMethodTable()->IsProjectedFromWinRT()); - - pInfo->dwFlags &= ~ItfMarshalInfo::ITF_MARSHAL_DISP_ITF; - pInfo->dwFlags |= ItfMarshalInfo::ITF_MARSHAL_INSP_ITF; - } - } - #else // FEATURE_COMINTEROP if (!th.IsInterface()) pInfo->thClass = th; @@ -3929,7 +3310,7 @@ void MarshalInfo::GetItfMarshalInfo(TypeHandle th, TypeHandle thItf, BOOL fDispI #endif // FEATURE_COMINTEROP } -HRESULT MarshalInfo::TryGetItfMarshalInfo(TypeHandle th, BOOL fDispItf, BOOL fInspItf, ItfMarshalInfo *pInfo) +HRESULT MarshalInfo::TryGetItfMarshalInfo(TypeHandle th, BOOL fDispItf, ItfMarshalInfo *pInfo) { CONTRACTL { @@ -3944,7 +3325,7 @@ HRESULT MarshalInfo::TryGetItfMarshalInfo(TypeHandle th, BOOL fDispItf, BOOL fIn EX_TRY { - GetItfMarshalInfo(th, TypeHandle(), fDispItf, fInspItf, + GetItfMarshalInfo(th, fDispItf, #ifdef FEATURE_COMINTEROP MARSHAL_SCENARIO_COMINTEROP, #else // FEATURE_COMINTEROP @@ -4064,7 +3445,6 @@ VOID MarshalInfo::DumpMarshalInfo(Module* pModule, SigPointer sig, const SigType #ifdef FEATURE_COMINTEROP XXXXX(NATIVE_TYPE_TBSTR) XXXXX(NATIVE_TYPE_ANSIBSTR) - XXXXX(NATIVE_TYPE_HSTRING) XXXXX(NATIVE_TYPE_BYVALSTR) XXXXX(NATIVE_TYPE_VARIANTBOOL) @@ -4166,7 +3546,7 @@ VOID MarshalInfo::DumpMarshalInfo(Module* pModule, SigPointer sig, const SigType } switch (m_type) { - #define DEFINE_MARSHALER_TYPE(mt, mc, fWinRTSupported) case mt: logbuf.AppendASCII( #mt " (IL" #mc ")"); break; + #define DEFINE_MARSHALER_TYPE(mt, mc) case mt: logbuf.AppendASCII( #mt " (IL" #mc ")"); break; #include "mtypes.h" case MARSHAL_TYPE_UNKNOWN: @@ -4255,7 +3635,7 @@ DispParamMarshaler *MarshalInfo::GenerateDispParamMarshaler() case MARSHAL_TYPE_INTERFACE: { ItfMarshalInfo itfInfo; - GetItfMarshalInfo(TypeHandle(m_pMT), TypeHandle(m_pDefaultItfMT), m_fDispItf, m_fInspItf, m_ms, &itfInfo); + GetItfMarshalInfo(TypeHandle(m_pMT), m_fDispItf, m_ms, &itfInfo); pDispParamMarshaler = new DispParamInterfaceMarshaler( itfInfo.dwFlags & ItfMarshalInfo::ITF_MARSHAL_DISP_ITF, itfInfo.thItf.GetMethodTable(), @@ -4316,7 +3696,7 @@ DispatchWrapperType MarshalInfo::GetDispWrapperType() case MARSHAL_TYPE_INTERFACE: { ItfMarshalInfo itfInfo; - GetItfMarshalInfo(TypeHandle(m_pMT), TypeHandle(m_pDefaultItfMT), m_fDispItf, m_fInspItf, m_ms, &itfInfo); + GetItfMarshalInfo(TypeHandle(m_pMT), m_fDispItf, m_ms, &itfInfo); WrapperType = !!(itfInfo.dwFlags & ItfMarshalInfo::ITF_MARSHAL_DISP_ITF) ? DispatchWrapperType_Dispatch : DispatchWrapperType_Unknown; break; } @@ -4384,7 +3764,7 @@ VOID MarshalInfo::MarshalTypeToString(SString& strMarshalType, BOOL fSizeIsSpeci else if (m_type == MARSHAL_TYPE_INTERFACE) { ItfMarshalInfo itfInfo; - GetItfMarshalInfo(TypeHandle(m_pMT), TypeHandle(m_pDefaultItfMT), m_fDispItf, m_fInspItf, m_ms, &itfInfo); + GetItfMarshalInfo(TypeHandle(m_pMT), m_fDispItf, m_ms, &itfInfo); if (!itfInfo.thItf.IsNull()) { @@ -4395,10 +3775,6 @@ VOID MarshalInfo::MarshalTypeToString(SString& strMarshalType, BOOL fSizeIsSpeci { strMarshalType.SetLiteral(W("IDispatch ")); } - else if (!!(itfInfo.dwFlags & ItfMarshalInfo::ITF_MARSHAL_INSP_ITF)) - { - strMarshalType.SetLiteral(W("IInspectable")); - } else { strMarshalType.SetLiteral(W("IUnknown ")); @@ -4416,8 +3792,6 @@ VOID MarshalInfo::MarshalTypeToString(SString& strMarshalType, BOOL fSizeIsSpeci { if (!!(itfInfo.dwFlags & ItfMarshalInfo::ITF_MARSHAL_DISP_ITF)) strRetVal = W("IDispatch"); - else if (!!(itfInfo.dwFlags & ItfMarshalInfo::ITF_MARSHAL_INSP_ITF)) - strRetVal = W("IInspectable"); else strRetVal = W("IUnknown"); } @@ -4736,16 +4110,6 @@ bool MarshalInfo::MarshalerRequiresCOM() case MARSHAL_TYPE_OLECOLOR: case MARSHAL_TYPE_SAFEARRAY: case MARSHAL_TYPE_INTERFACE: - - case MARSHAL_TYPE_URI: - case MARSHAL_TYPE_KEYVALUEPAIR: - case MARSHAL_TYPE_NULLABLE: - case MARSHAL_TYPE_SYSTEMTYPE: - case MARSHAL_TYPE_EXCEPTION: - case MARSHAL_TYPE_HIDDENLENGTHARRAY: - case MARSHAL_TYPE_HSTRING: - case MARSHAL_TYPE_NCCEVENTARGS: - case MARSHAL_TYPE_PCEVENTARGS: { // some of these types do not strictly require COM for the actual marshaling // but they tend to be used in COM context so we keep the logic we had in @@ -4772,89 +4136,6 @@ bool MarshalInfo::MarshalerRequiresCOM() return false; } -#ifdef FEATURE_COMINTEROP -MarshalInfo::MarshalType MarshalInfo::GetHiddenLengthParamMarshalType() -{ - LIMITED_METHOD_CONTRACT; - return MARSHAL_TYPE_GENERIC_U4; -} - -CorElementType MarshalInfo::GetHiddenLengthParamElementType() -{ - LIMITED_METHOD_CONTRACT; - return ELEMENT_TYPE_U4; -} - -UINT16 MarshalInfo::GetHiddenLengthParamStackSize() -{ - LIMITED_METHOD_CONTRACT; - return StackElemSize(GetNativeSize(GetHiddenLengthParamMarshalType())); -} - -void MarshalInfo::MarshalHiddenLengthArgument(NDirectStubLinker *psl, BOOL managedToNative, BOOL isForReturnArray) -{ - CONTRACTL - { - STANDARD_VM_CHECK; - PRECONDITION(CheckPointer(psl)); - PRECONDITION(m_type == MARSHAL_TYPE_HIDDENLENGTHARRAY); - PRECONDITION(m_dwHiddenLengthManagedHomeLocal == 0xFFFFFFFF); - PRECONDITION(m_dwHiddenLengthNativeHomeLocal == 0xFFFFFFFF); - } - CONTRACTL_END; - - NewHolder pHiddenLengthMarshaler = CreateILMarshaler(GetHiddenLengthParamMarshalType(), psl); - - - ILCodeStream *pcsMarshal = psl->GetMarshalCodeStream(); - ILCodeStream *pcsUnmarshal = psl->GetUnmarshalCodeStream(); - - pcsMarshal->EmitNOP("// hidden length argument { "); - pcsUnmarshal->EmitNOP("// hidden length argument { "); - - DWORD dwMarshalFlags = MARSHAL_FLAG_HIDDENLENPARAM; - if (isForReturnArray) - { - // This is a hidden length argument for an [out, retval] argument, so setup flags to match that - dwMarshalFlags |= CalculateArgumentMarshalFlags(TRUE, FALSE, TRUE, managedToNative); - } - else - { - // The length parameter needs to be an [in] parameter if the array itself is an [in] parameter. - // Additionally, in order to support the FillArray pattern: - // FillArray([in] UInt32 length, [out, size_is(length)] ElementType* value) - // - // We need to make sure that the length parameter is [in] if the array pointer is not byref, since - // this means that the caller is allocating the array. This includes array buffers which are [out] - // but not byref, since the [out] marshaling applies to the array contents but not the array pointer - // value itself. - BOOL marshalHiddenLengthIn = m_in || !m_byref; - dwMarshalFlags |= CalculateArgumentMarshalFlags(m_byref, marshalHiddenLengthIn, m_out, managedToNative); - } - pHiddenLengthMarshaler->EmitMarshalHiddenLengthArgument(pcsMarshal, - pcsUnmarshal, - this, - m_paramidx, - dwMarshalFlags, - HiddenLengthParamIndex(), - &m_args, - &m_dwHiddenLengthManagedHomeLocal, - &m_dwHiddenLengthNativeHomeLocal); - - pcsMarshal->EmitNOP("// } hidden length argument"); - pcsUnmarshal->EmitNOP("// } hidden length argument"); - - // Only emit into the dispatch stream for CLR -> Native cases - in the reverse, there is no argument - // to pass to the managed method. Instead, the length is encoded in the marshaled array. - if (managedToNative) - { - ILCodeStream* pcsDispatch = psl->GetDispatchCodeStream(); - pHiddenLengthMarshaler->EmitSetupArgumentForDispatch(pcsDispatch); - } -} - -#endif // FEATURE_COMINTEROP - #define ReportInvalidArrayMarshalInfo(resId) \ do \ { \ @@ -4899,112 +4180,6 @@ void ArrayMarshalInfo::InitForSafeArray(MarshalInfo::MarshalScenario ms, TypeHan } } } - -void ArrayMarshalInfo::InitForHiddenLengthArray(TypeHandle thElement) -{ - STANDARD_VM_CONTRACT; - - MethodTable *pMT = NULL; - - // WinRT supports arrays of any WinRT-legal types - if (thElement.IsArray()) - { - ReportInvalidArrayMarshalInfo(IDS_EE_BADMARSHAL_NESTEDARRAY); - } - else if (thElement.IsTypeDesc() || !thElement.GetMethodTable()->IsLegalNonArrayWinRTType()) - { - ReportInvalidArrayMarshalInfo(IDS_EE_BADMARSHAL_WINRT_ILLEGAL_TYPE); - } - - m_thElement = thElement; - - pMT = thElement.GetMethodTable(); - if (pMT->IsString()) - { - m_vtElement = VTHACK_HSTRING; - m_cbElementSize = sizeof(HSTRING); - } - else if (WinRTTypeNameConverter::ResolveRedirectedType(pMT, &m_redirectedTypeIndex)) - { - m_vtElement = VTHACK_REDIRECTEDTYPE; - - switch (m_redirectedTypeIndex) - { - case WinMDAdapter::RedirectedTypeIndex_System_DateTimeOffset: - m_cbElementSize = ILDateTimeMarshaler::c_nativeSize; - break; - - case WinMDAdapter::RedirectedTypeIndex_System_Type: - m_cbElementSize = ILSystemTypeMarshaler::c_nativeSize; - break; - - case WinMDAdapter::RedirectedTypeIndex_System_Exception: - m_cbElementSize = ILHResultExceptionMarshaler::c_nativeSize; - break; - - // WinRT delegates are IUnknown pointers - case WinMDAdapter::RedirectedTypeIndex_System_EventHandlerGeneric: - m_vtElement = VTHACK_INSPECTABLE; - m_cbElementSize = sizeof(IUnknown*); - break; - - case WinMDAdapter::RedirectedTypeIndex_System_Collections_Generic_KeyValuePair: - case WinMDAdapter::RedirectedTypeIndex_System_Nullable: - case WinMDAdapter::RedirectedTypeIndex_System_Uri: - case WinMDAdapter::RedirectedTypeIndex_System_Collections_Specialized_NotifyCollectionChangedEventArgs: - case WinMDAdapter::RedirectedTypeIndex_System_ComponentModel_PropertyChangedEventArgs: - { - m_cbElementSize = sizeof(IInspectable *); - break; - } - - default: - { - if (pMT->IsValueType()) - { - // other redirected structs are blittable and don't need special marshaling - m_vtElement = VTHACK_BLITTABLERECORD; - m_cbElementSize = pMT->GetNativeSize(); - } - else - { - // redirected interfaces should be treated as interface pointers - _ASSERTE(pMT->IsInterface()); - m_vtElement = VTHACK_INSPECTABLE; - m_cbElementSize = sizeof(IInspectable *); - } - break; - } - } - } - else if (pMT->IsBlittable() || pMT->IsTruePrimitive() || pMT->IsEnum()) - { - m_vtElement = VTHACK_BLITTABLERECORD; - - CorElementType elemType = pMT->GetInternalCorElementType(); - if (CorTypeInfo::IsPrimitiveType(elemType)) - { - // .NET and WinRT primitives have the same size - m_cbElementSize = CorTypeInfo::Size(elemType); - } - else - { - m_cbElementSize = pMT->GetNativeSize(); - } - } - else if (pMT->IsValueType()) - { - m_vtElement = VTHACK_NONBLITTABLERECORD; - m_cbElementSize = pMT->GetNativeSize(); - } - else - { - m_vtElement = VTHACK_INSPECTABLE; - m_cbElementSize = sizeof(IInspectable *); - } - -LExit:; -} #endif // FEATURE_COMINTEROP void ArrayMarshalInfo::InitElementInfo(CorNativeType arrayNativeType, MarshalInfo::MarshalScenario ms, TypeHandle thElement, CorNativeType ntElement, BOOL isAnsi) @@ -5275,7 +4450,7 @@ void ArrayMarshalInfo::InitElementInfo(CorNativeType arrayNativeType, MarshalInf // Compat: Even if the classes have layout, we still convert them to interface pointers. ItfMarshalInfo itfInfo; - MarshalInfo::GetItfMarshalInfo(m_thElement, TypeHandle(), FALSE, FALSE, ms, &itfInfo); + MarshalInfo::GetItfMarshalInfo(m_thElement, FALSE, ms, &itfInfo); // Compat: We must always do VT_UNKNOWN marshaling for parameters, even if the interface is marked late-bound. if (ms == MarshalInfo::MARSHAL_SCENARIO_FIELD) diff --git a/src/coreclr/src/vm/mlinfo.h b/src/coreclr/src/vm/mlinfo.h index 9135836..813bcbc 100644 --- a/src/coreclr/src/vm/mlinfo.h +++ b/src/coreclr/src/vm/mlinfo.h @@ -11,10 +11,6 @@ #include "stubgen.h" #include "custommarshalerinfo.h" -#ifdef FEATURE_COMINTEROP -#include -#endif - #ifndef _MLINFO_H_ #define _MLINFO_H_ @@ -55,7 +51,7 @@ enum MarshalFlags MARSHAL_FLAG_BYREF = 0x008, MARSHAL_FLAG_HRESULT_SWAP = 0x010, MARSHAL_FLAG_RETVAL = 0x020, - MARSHAL_FLAG_HIDDENLENPARAM = 0x040, + // unused = 0x040, MARSHAL_FLAG_FIELD = 0x080, MARSHAL_FLAG_IN_MEMBER_FUNCTION = 0x100 }; @@ -88,7 +84,6 @@ struct OverrideProcArgs VARTYPE m_vt; #ifdef FEATURE_COMINTEROP SIZE_T m_cbElementSize; - WinMDAdapter::RedirectedTypeIndex m_redirectedTypeIndex; #endif // FEATURE_COMINTEROP } na; @@ -207,140 +202,6 @@ BOOL IsFixedBuffer(mdFieldDef field, IMDInternalImport* pInternalImport); #endif #ifdef FEATURE_COMINTEROP - -class EventArgsMarshalingInfo -{ -public: - // Constructor. - EventArgsMarshalingInfo(); - - // Destructor. - ~EventArgsMarshalingInfo(); - - // EventArgsMarshalingInfo's are always allocated on the loader heap so we need to redefine - // the new and delete operators to ensure this. - void *operator new(size_t size, LoaderHeap *pHeap); - void operator delete(void *pMem); - - // Accessors. - TypeHandle GetSystemNCCEventArgsType() - { - LIMITED_METHOD_CONTRACT; - return m_hndSystemNCCEventArgsType; - } - - TypeHandle GetSystemPCEventArgsType() - { - LIMITED_METHOD_CONTRACT; - return m_hndSystemPCEventArgsType; - } - - MethodDesc *GetSystemNCCEventArgsToWinRTNCCEventArgsMD() - { - LIMITED_METHOD_CONTRACT; - return m_pSystemNCCEventArgsToWinRTNCCEventArgsMD; - } - - MethodDesc *GetWinRTNCCEventArgsToSystemNCCEventArgsMD() - { - LIMITED_METHOD_CONTRACT; - return m_pWinRTNCCEventArgsToSystemNCCEventArgsMD; - } - - MethodDesc *GetSystemPCEventArgsToWinRTPCEventArgsMD() - { - LIMITED_METHOD_CONTRACT; - return m_pSystemPCEventArgsToWinRTPCEventArgsMD; - } - - MethodDesc *GetWinRTPCEventArgsToSystemPCEventArgsMD() - { - LIMITED_METHOD_CONTRACT; - return m_pWinRTPCEventArgsToSystemPCEventArgsMD; - } - - -private: - TypeHandle m_hndSystemNCCEventArgsType; - TypeHandle m_hndSystemPCEventArgsType; - - MethodDesc *m_pSystemNCCEventArgsToWinRTNCCEventArgsMD; - MethodDesc *m_pWinRTNCCEventArgsToSystemNCCEventArgsMD; - MethodDesc *m_pSystemPCEventArgsToWinRTPCEventArgsMD; - MethodDesc *m_pWinRTPCEventArgsToSystemPCEventArgsMD; -}; - -class UriMarshalingInfo -{ -public: - // Constructor. - UriMarshalingInfo(); - - // Destructor - ~UriMarshalingInfo(); - - // UriMarshalingInfo's are always allocated on the loader heap so we need to redefine - // the new and delete operators to ensure this. - void *operator new(size_t size, LoaderHeap *pHeap); - void operator delete(void *pMem); - - // Accessors. - TypeHandle GetSystemUriType() - { - LIMITED_METHOD_CONTRACT; - return m_hndSystemUriType; - } - - ABI::Windows::Foundation::IUriRuntimeClassFactory* GetUriFactory() - { - CONTRACTL - { - THROWS; - GC_TRIGGERS; // For potential COOP->PREEMP->COOP switch - MODE_ANY; - PRECONDITION(!GetAppDomain()->IsCompilationDomain()); - } - CONTRACTL_END; - - if (m_pUriFactory.Load() == NULL) - { - GCX_PREEMP(); - - SafeComHolderPreemp pUriFactory; - - // IUriRuntimeClassFactory: 44A9796F-723E-4FDF-A218-033E75B0C084 - IfFailThrow(clr::winrt::GetActivationFactory(g_WinRTUriClassNameW, (ABI::Windows::Foundation::IUriRuntimeClassFactory **)&pUriFactory)); - _ASSERTE_MSG(pUriFactory, "Got Null Uri factory!"); - - if (InterlockedCompareExchangeT(&m_pUriFactory, (ABI::Windows::Foundation::IUriRuntimeClassFactory *) pUriFactory, NULL) == NULL) - pUriFactory.SuppressRelease(); - } - - return m_pUriFactory; - } - - MethodDesc *GetSystemUriCtorMD() - { - LIMITED_METHOD_CONTRACT; - return m_SystemUriCtorMD; - } - - MethodDesc *GetSystemUriOriginalStringMD() - { - LIMITED_METHOD_CONTRACT; - return m_SystemUriOriginalStringGetterMD; - } - - -private: - TypeHandle m_hndSystemUriType; - - MethodDesc* m_SystemUriCtorMD; - MethodDesc* m_SystemUriOriginalStringGetterMD; - - VolatilePtr m_pUriFactory; -}; - class OleColorMarshalingInfo { public: @@ -400,8 +261,6 @@ public: #ifdef FEATURE_COMINTEROP // This method retrieves OLE_COLOR marshaling info. OleColorMarshalingInfo *GetOleColorMarshalingInfo(); - UriMarshalingInfo *GetUriMarshalingInfo(); - EventArgsMarshalingInfo *GetEventArgsMarshalingInfo(); #endif // FEATURE_COMINTEROP @@ -416,8 +275,6 @@ private: CMINFOLIST m_pCMInfoList; #ifdef FEATURE_COMINTEROP OleColorMarshalingInfo* m_pOleColorInfo; - UriMarshalingInfo* m_pUriInfo; - EventArgsMarshalingInfo* m_pEventArgsInfo; #endif // FEATURE_COMINTEROP CrstBase* m_lock; }; @@ -429,7 +286,7 @@ class MarshalInfo public: enum MarshalType { -#define DEFINE_MARSHALER_TYPE(mtype, mclass, fWinRTSupported) mtype, +#define DEFINE_MARSHALER_TYPE(mtype, mclass) mtype, #include "mtypes.h" MARSHAL_TYPE_UNKNOWN }; @@ -439,8 +296,6 @@ public: MARSHAL_SCENARIO_NDIRECT, #ifdef FEATURE_COMINTEROP MARSHAL_SCENARIO_COMINTEROP, - MARSHAL_SCENARIO_WINRT, - MARSHAL_SCENARIO_WINRT_FIELD, #endif // FEATURE_COMINTEROP MARSHAL_SCENARIO_FIELD }; @@ -582,42 +437,6 @@ public: return m_nolowerbounds; } -#ifdef FEATURE_COMINTEROP - void SetHiddenLengthParamIndex(UINT16 index) - { - LIMITED_METHOD_CONTRACT; - _ASSERTE(m_hiddenLengthParamIndex == (UINT16)-1); - m_hiddenLengthParamIndex = index; - } - - UINT16 HiddenLengthParamIndex() - { - LIMITED_METHOD_CONTRACT; - _ASSERTE(m_hiddenLengthParamIndex != (UINT16)-1); - return m_hiddenLengthParamIndex; - } - - DWORD GetHiddenLengthManagedHome() - { - LIMITED_METHOD_CONTRACT; - _ASSERTE(m_dwHiddenLengthManagedHomeLocal != 0xFFFFFFFF); - return m_dwHiddenLengthManagedHomeLocal; - } - - DWORD GetHiddenLengthNativeHome() - { - LIMITED_METHOD_CONTRACT; - _ASSERTE(m_dwHiddenLengthNativeHomeLocal != 0xFFFFFFFF); - return m_dwHiddenLengthNativeHomeLocal; - } - - MarshalType GetHiddenLengthParamMarshalType(); - CorElementType GetHiddenLengthParamElementType(); - UINT16 GetHiddenLengthParamStackSize(); - - void MarshalHiddenLengthArgument(NDirectStubLinker *psl, BOOL managedToNative, BOOL isForReturnArray); -#endif // FEATURE_COMINTEROP - // used the same logic of tlbexp to check whether the argument of the method is a VarArg BOOL IsOleVarArgCandidate() { @@ -650,8 +469,8 @@ public: void GetItfMarshalInfo(ItfMarshalInfo* pInfo); // Helper functions used to map the specified type to its interface marshalling info. - static void GetItfMarshalInfo(TypeHandle th, TypeHandle thItf, BOOL fDispItf, BOOL fInspItf, MarshalScenario ms, ItfMarshalInfo *pInfo); - static HRESULT TryGetItfMarshalInfo(TypeHandle th, BOOL fDispItf, BOOL fInspItf, ItfMarshalInfo *pInfo); + static void GetItfMarshalInfo(TypeHandle th, BOOL fDispItf, MarshalScenario ms, ItfMarshalInfo *pInfo); + static HRESULT TryGetItfMarshalInfo(TypeHandle th, BOOL fDispItf, ItfMarshalInfo *pInfo); VOID MarshalTypeToString(SString& strMarshalType, BOOL fSizeIsSpecified); static VOID VarTypeToString(VARTYPE vt, SString& strVarType); @@ -671,30 +490,16 @@ public: return m_paramidx; } -#ifdef FEATURE_COMINTEROP - BOOL IsWinRTScenario() - { - LIMITED_METHOD_CONTRACT; - - return m_ms == MarshalInfo::MARSHAL_SCENARIO_WINRT || m_ms == MarshalInfo::MARSHAL_SCENARIO_WINRT_FIELD; - } -#endif // FEATURE_COMINTEROP - BOOL IsFieldScenario() { LIMITED_METHOD_CONTRACT; -#ifdef FEATURE_COMINTEROP - return m_ms == MarshalInfo::MARSHAL_SCENARIO_FIELD || m_ms == MarshalInfo::MARSHAL_SCENARIO_WINRT_FIELD; -#else return m_ms == MarshalInfo::MARSHAL_SCENARIO_FIELD; -#endif } private: UINT16 GetNativeSize(MarshalType mtype); static bool IsInOnly(MarshalType mtype); - static bool IsSupportedForWinRT(MarshalType mtype); static OVERRIDEPROC GetArgumentOverrideProc(MarshalType mtype); static RETURNOVERRIDEPROC GetReturnOverrideProc(MarshalType mtype); @@ -722,21 +527,11 @@ private: UINT32 m_additive; // additive for 'sizeis" UINT16 m_countParamIdx; // index of "sizeis" parameter -#ifdef FEATURE_COMINTEROP - // For NATIVE_TYPE_HIDDENLENGTHARRAY - UINT16 m_hiddenLengthParamIndex; // index of the injected hidden length parameter - DWORD m_dwHiddenLengthManagedHomeLocal; // home local for the managed hidden length parameter - DWORD m_dwHiddenLengthNativeHomeLocal; // home local for the native hidden length parameter - - MethodTable* m_pDefaultItfMT; // WinRT default interface (if m_pMT is a class) -#endif // FEATURE_COMINTEROP - UINT16 m_nativeArgSize; MarshalScenario m_ms; BOOL m_fAnsi; BOOL m_fDispItf; - BOOL m_fInspItf; #ifdef FEATURE_COMINTEROP BOOL m_fErrorNativeType; #endif // FEATURE_COMINTEROP @@ -792,7 +587,6 @@ public: , m_errorResourceId(0) , m_flags(flags) #ifdef FEATURE_COMINTEROP - , m_redirectedTypeIndex((WinMDAdapter::RedirectedTypeIndex)0) , m_cbElementSize(0) #endif // FEATURE_COMINTEROP { @@ -804,7 +598,6 @@ public: #ifdef FEATURE_COMINTEROP void InitForSafeArray(MarshalInfo::MarshalScenario ms, TypeHandle elemTypeHnd, VARTYPE elementVT, BOOL isAnsi); - void InitForHiddenLengthArray(TypeHandle elemTypeHnd); #endif // FEATURE_COMINTEROP TypeHandle GetElementTypeHandle() @@ -873,11 +666,6 @@ public: } #ifdef FEATURE_COMINTEROP - WinMDAdapter::RedirectedTypeIndex GetRedirectedTypeIndex() - { - LIMITED_METHOD_CONTRACT; - return m_redirectedTypeIndex; - } SIZE_T GetElementSize() { @@ -909,7 +697,6 @@ protected: ArrayMarshalInfoFlags m_flags; #ifdef FEATURE_COMINTEROP - WinMDAdapter::RedirectedTypeIndex m_redirectedTypeIndex; SIZE_T m_cbElementSize; #endif // FEATURE_COMINTEROP }; diff --git a/src/coreclr/src/vm/mngstdinterfaces.cpp b/src/coreclr/src/vm/mngstdinterfaces.cpp index d9dd7e5..23ec398 100644 --- a/src/coreclr/src/vm/mngstdinterfaces.cpp +++ b/src/coreclr/src/vm/mngstdinterfaces.cpp @@ -920,76 +920,9 @@ FCIMPL1(Object*, StdMngIEnumerable::GetEnumerator, Object* refThisUNSAFE) GCPROTECT_ARRAY_BEGIN(args[0], 1); - // There are three ways to handle calls via IEnumerable::GetEnumerator on an RCW: - // 1. Use BindableIterableToEnumerableAdapter (Jupiter data-binding scenario) - // 2. Use IterableToEnumerableAdapter if the object is known to implement IIterable (WinRT) - // 3. Use EnumerableToDispatchMarshaler in CustomMarshalers.dll (legacy COM interop) - SyncBlock *pSB = (*porefThis)->GetSyncBlock(); - if (pSB->GetInteropInfoNoCreate() != NULL && pSB->GetInteropInfoNoCreate()->GetRawRCW() != NULL) - { - RCWHolder pRCW(GetThread()); - RCWPROTECT_BEGIN(pRCW, pSB); - - if (pRCW->SupportsIInspectable()) - { - // - // Test which IEnumerable implementation we want - // Prefer WinRT case as WinRT is new scenario - // - if (pRCW->SupportsWinRTInteropInterface(MscorlibBinder::GetExistingClass(CLASS__IENUMERABLE))) - { - // - // Supports WinRT IEnumerable - // Could be either IIterable, IBindableIterable, or IDispatch+DISPID_NEWENUM - // - MethodDesc *pGetEnumeratorMethod = pRCW->GetGetEnumeratorMethod(); - if (pGetEnumeratorMethod) - { - // - // IIterable/IDispatch+DISPID_NEWENUM - The right enumerator method is saved in pGetEnumeratorMethod - // - MethodDescCallSite callSite(pGetEnumeratorMethod, porefThis); - - retVal = callSite.Call_RetOBJECTREF(args); - } - else - { - // - // IBindableIterable - // - MethodDescCallSite callSite(MscorlibBinder::GetMethod(METHOD__BINDABLEITERABLE_TO_ENUMERABLE_ADAPTER__GET_ENUMERATOR_STUB)); - retVal = callSite.Call_RetOBJECTREF(args); - } - } - else if (!pRCW->SupportsLegacyEnumerableInterface()) - { - // The object does not support IBindableEnumerable nor IDispatch DISPID_NEWENUM enumeration. - // Try to use IIterable, throw exception if it fails. - MethodDesc *pGetEnumeratorMethod = pRCW->GetGetEnumeratorMethod(); - if (pGetEnumeratorMethod != NULL) - { - // make a virtual call through the generic IEnumerable - MethodDescCallSite callSite(pGetEnumeratorMethod, porefThis); - - retVal = callSite.Call_RetOBJECTREF(args); - } - else - { - // If we haven't seen a cast to a generic IEnumerable and haven't been able to infer - // the interface statically, we have to throw an exception, suggesting a workaround. - // (This is an inherent limitation, we can't know what to do without type information.) - COMPlusThrow(kInvalidCastException, IDS_EE_WINRT_IENUMERABLE_BAD_CALL); - } - } - } - - RCWPROTECT_END(pRCW); - } - - if (retVal == NULL) - { - retVal = ObjectToOBJECTREF((Object*)GetEnumeratorWorker(args)); - } + // To handle calls via IEnumerable::GetEnumerator on an RCW we use + // EnumerableToDispatchMarshaler (legacy COM interop) + retVal = ObjectToOBJECTREF((Object*)GetEnumeratorWorker(args)); GCPROTECT_END(); HELPER_METHOD_FRAME_END(); diff --git a/src/coreclr/src/vm/mscorlib.cpp b/src/coreclr/src/vm/mscorlib.cpp index 3c787e0..f1153bc 100644 --- a/src/coreclr/src/vm/mscorlib.cpp +++ b/src/coreclr/src/vm/mscorlib.cpp @@ -56,7 +56,6 @@ #include "runtimehandles.h" #include "reflectioninvocation.h" #include "managedmdimport.hpp" -#include "synchronizationcontextnative.h" #include "typestring.h" #include "comdependenthandle.h" #include "weakreferencenative.h" @@ -348,8 +347,6 @@ const MscorlibClassDescription c_rgMscorlibClassDescriptions[] = // Include all exception types here that are defined in mscorlib. Omit exceptions defined elsewhere. #define DEFINE_EXCEPTION(ns, reKind, bHRformessage, ...) { ns , # reKind }, - #define DEFINE_EXCEPTION_HR_WINRT_ONLY(ns, reKind, ...) - #define DEFINE_EXCEPTION_IN_OTHER_FX_ASSEMBLY(ns, reKind, assemblySimpleName, bHRformessage, ...) #include "rexcep.h" }; const USHORT c_nMscorlibClassDescriptions = NumItems(c_rgMscorlibClassDescriptions); diff --git a/src/coreclr/src/vm/mscorlib.h b/src/coreclr/src/vm/mscorlib.h index 7c02584..ecf56b7 100644 --- a/src/coreclr/src/vm/mscorlib.h +++ b/src/coreclr/src/vm/mscorlib.h @@ -192,14 +192,15 @@ DEFINE_FIELD_U(m_ObjectToDataMap, ComObject, m_ObjectToDataMap DEFINE_CLASS(COM_OBJECT, System, __ComObject) DEFINE_METHOD(COM_OBJECT, RELEASE_ALL_DATA, ReleaseAllData, IM_RetVoid) DEFINE_METHOD(COM_OBJECT, GET_EVENT_PROVIDER, GetEventProvider, IM_Class_RetObj) +#ifdef FOR_ILLINK +DEFINE_METHOD(COM_OBJECT, CTOR, .ctor, IM_RetVoid) +#endif DEFINE_CLASS(LICENSE_INTEROP_PROXY, InternalInteropServices, LicenseInteropProxy) DEFINE_METHOD(LICENSE_INTEROP_PROXY, CREATE, Create, SM_RetObj) DEFINE_METHOD(LICENSE_INTEROP_PROXY, GETCURRENTCONTEXTINFO, GetCurrentContextInfo, IM_RuntimeTypeHandle_RefBool_RefIntPtr_RetVoid) DEFINE_METHOD(LICENSE_INTEROP_PROXY, SAVEKEYINCURRENTCONTEXT, SaveKeyInCurrentContext, IM_IntPtr_RetVoid) -DEFINE_CLASS(RUNTIME_CLASS, WinRT, RuntimeClass) - #endif // FEATURE_COMINTEROP DEFINE_CLASS_U(Interop, CriticalHandle, CriticalHandle) @@ -358,10 +359,6 @@ DEFINE_PROPERTY(EXCEPTION, MESSAGE, Message, DEFINE_PROPERTY(EXCEPTION, SOURCE, Source, Str) DEFINE_PROPERTY(EXCEPTION, HELP_LINK, HelpLink, Str) DEFINE_METHOD(EXCEPTION, INTERNAL_PRESERVE_STACK_TRACE, InternalPreserveStackTrace, IM_RetVoid) -#ifdef FEATURE_COMINTEROP -DEFINE_METHOD(EXCEPTION, ADD_EXCEPTION_DATA_FOR_RESTRICTED_ERROR_INFO, AddExceptionDataForRestrictedErrorInfo, IM_Str_Str_Str_Obj_Bool_RetVoid) -DEFINE_METHOD(EXCEPTION, TRY_GET_RESTRICTED_LANGUAGE_ERROR_OBJECT, TryGetRestrictedLanguageErrorObject, IM_RefObject_RetBool) -#endif // FEATURE_COMINTEROP DEFINE_CLASS(SYSTEM_EXCEPTION, System, SystemException) @@ -408,29 +405,6 @@ DEFINE_CLASS(FIELD_INFO, Reflection, FieldInfo) DEFINE_CLASS(GUID, System, Guid) #ifdef FEATURE_COMINTEROP -DEFINE_CLASS(HSTRING_HEADER_MANAGED, WinRT, HSTRING_HEADER) - -DEFINE_CLASS(ICUSTOMPROPERTY, WinRT, ICustomProperty) -DEFINE_CLASS(ICUSTOMPROPERTYPROVIDERIMPL, WinRT, ICustomPropertyProviderImpl) -DEFINE_METHOD(ICUSTOMPROPERTYPROVIDERIMPL, CREATE_PROPERTY, CreateProperty, SM_Obj_Str_RetICustomProperty) -DEFINE_METHOD(ICUSTOMPROPERTYPROVIDERIMPL, CREATE_INDEXED_PROPERTY, CreateIndexedProperty, SM_Obj_Str_PtrTypeName_RetICustomProperty) -DEFINE_METHOD(ICUSTOMPROPERTYPROVIDERIMPL, GET_TYPE, GetType, SM_Obj_PtrTypeName_RetVoid) -DEFINE_CLASS(ICUSTOMPROPERTYPROVIDERPROXY, WinRT, ICustomPropertyProviderProxy`2) -DEFINE_METHOD(ICUSTOMPROPERTYPROVIDERPROXY, CREATE_INSTANCE, CreateInstance, SM_Obj_RetObj) - -DEFINE_CLASS(FACTORYFORIREFERENCE, WinRT, IReferenceFactory) -DEFINE_METHOD(FACTORYFORIREFERENCE, CREATE_IREFERENCE, CreateIReference, SM_Obj_RetObj) -DEFINE_CLASS(CLRIREFERENCEIMPL, WinRT, CLRIReferenceImpl`1) -DEFINE_METHOD(CLRIREFERENCEIMPL, UNBOXHELPER, UnboxHelper, SM_Obj_RetObj) -DEFINE_CLASS(CLRIREFERENCEARRAYIMPL, WinRT, CLRIReferenceArrayImpl`1) -DEFINE_METHOD(CLRIREFERENCEARRAYIMPL,UNBOXHELPER, UnboxHelper, SM_Obj_RetObj) -DEFINE_CLASS(IREFERENCE, WinRT, IReference`1) -DEFINE_CLASS(CLRIKEYVALUEPAIRIMPL, WinRT, CLRIKeyValuePairImpl`2) -DEFINE_METHOD(CLRIKEYVALUEPAIRIMPL, BOXHELPER, BoxHelper, SM_Obj_RetObj) -DEFINE_METHOD(CLRIKEYVALUEPAIRIMPL, UNBOXHELPER, UnboxHelper, SM_Obj_RetObj) - -DEFINE_CLASS(WINDOWS_FOUNDATION_EVENTHANDLER, WinRT, WindowsFoundationEventHandler`1) - DEFINE_CLASS(VARIANT, System, Variant) DEFINE_METHOD(VARIANT, CONVERT_OBJECT_TO_VARIANT,MarshalHelperConvertObjectToVariant,SM_Obj_RefVariant_RetVoid) DEFINE_METHOD(VARIANT, CAST_VARIANT, MarshalHelperCastVariant, SM_Obj_Int_RefVariant_RetVoid) @@ -976,11 +950,6 @@ DEFINE_METHOD(ASSEMBLYLOADCONTEXT, START_ASSEMBLY_LOAD, StartAssemblyLoa DEFINE_METHOD(ASSEMBLYLOADCONTEXT, STOP_ASSEMBLY_LOAD, StopAssemblyLoad, SM_RefGuid_RetVoid) DEFINE_METHOD(ASSEMBLYLOADCONTEXT, INITIALIZE_DEFAULT_CONTEXT, InitializeDefaultContext, SM_RetVoid) -#ifdef FEATURE_COMINTEROP -DEFINE_CLASS(WINDOWSRUNTIMEMETATADA, WinRT, WindowsRuntimeMetadata) -DEFINE_METHOD(WINDOWSRUNTIMEMETATADA, ON_DESIGNER_NAMESPACE_RESOLVE, OnDesignerNamespaceResolve, SM_Str_RetArrStr) -#endif //FEATURE_COMINTEROP - DEFINE_CLASS(VALUE_TYPE, System, ValueType) DEFINE_METHOD(VALUE_TYPE, GET_HASH_CODE, GetHashCode, IM_RetInt) DEFINE_METHOD(VALUE_TYPE, EQUALS, Equals, IM_Obj_RetBool) @@ -1004,20 +973,6 @@ DEFINE_CLASS(BUFFER, System, Buffer) DEFINE_METHOD(BUFFER, MEMCPY_PTRBYTE_ARRBYTE, Memcpy, SM_PtrByte_Int_ArrByte_Int_Int_RetVoid) DEFINE_METHOD(BUFFER, MEMCPY, Memcpy, SM_PtrByte_PtrByte_Int_RetVoid) -#ifdef FEATURE_COMINTEROP -DEFINE_CLASS(WINDOWSRUNTIMEMARSHAL, WinRT, WindowsRuntimeMarshal) -DEFINE_METHOD(WINDOWSRUNTIMEMARSHAL, GET_HR_FOR_EXCEPTION, GetHRForException, SM_Exception_RetInt) -DEFINE_METHOD(WINDOWSRUNTIMEMARSHAL, INITIALIZE_WRAPPER, InitializeWrapper, SM_Obj_RefIntPtr_RetVoid) -#ifdef FEATURE_COMINTEROP_WINRT_MANAGED_ACTIVATION -DEFINE_METHOD(WINDOWSRUNTIMEMARSHAL, GET_ACTIVATION_FACTORY_FOR_TYPE, GetActivationFactoryForType, SM_Type_RetIntPtr) -#endif // FEATURE_COMINTEROP_WINRT_MANAGED_ACTIVATION - -DEFINE_CLASS(IACTIVATIONFACTORY, WinRT, IActivationFactory) -DEFINE_METHOD(IACTIVATIONFACTORY, ACTIVATE_INSTANCE, ActivateInstance, IM_RetObj) -DEFINE_CLASS(ISTRINGABLEHELPER, WinRT, IStringableHelper) -DEFINE_METHOD(ISTRINGABLEHELPER, TO_STRING, ToString, SM_Obj_RetStr) -#endif // FEATURE_COMINTEROP - DEFINE_CLASS(STUBHELPERS, StubHelpers, StubHelpers) DEFINE_METHOD(STUBHELPERS, IS_QCALL, IsQCall, SM_IntPtr_RetBool) DEFINE_METHOD(STUBHELPERS, INIT_DECLARING_TYPE, InitDeclaringType, SM_IntPtr_RetVoid) @@ -1025,16 +980,7 @@ DEFINE_METHOD(STUBHELPERS, GET_NDIRECT_TARGET, GetNDirectTarget, DEFINE_METHOD(STUBHELPERS, GET_DELEGATE_TARGET, GetDelegateTarget, SM_Delegate_RefIntPtr_RetIntPtr) #ifdef FEATURE_COMINTEROP DEFINE_METHOD(STUBHELPERS, GET_COM_HR_EXCEPTION_OBJECT, GetCOMHRExceptionObject, SM_Int_IntPtr_Obj_RetException) -DEFINE_METHOD(STUBHELPERS, GET_COM_HR_EXCEPTION_OBJECT_WINRT, GetCOMHRExceptionObject_WinRT, SM_Int_IntPtr_Obj_RetException) DEFINE_METHOD(STUBHELPERS, GET_COM_IP_FROM_RCW, GetCOMIPFromRCW, SM_Obj_IntPtr_RefIntPtr_RefBool_RetIntPtr) -DEFINE_METHOD(STUBHELPERS, GET_COM_IP_FROM_RCW_WINRT, GetCOMIPFromRCW_WinRT, SM_Obj_IntPtr_RefIntPtr_RetIntPtr) -DEFINE_METHOD(STUBHELPERS, GET_COM_IP_FROM_RCW_WINRT_SHARED_GENERIC, GetCOMIPFromRCW_WinRTSharedGeneric, SM_Obj_IntPtr_RefIntPtr_RetIntPtr) -DEFINE_METHOD(STUBHELPERS, GET_COM_IP_FROM_RCW_WINRT_DELEGATE, GetCOMIPFromRCW_WinRTDelegate, SM_Obj_IntPtr_RefIntPtr_RetIntPtr) -DEFINE_METHOD(STUBHELPERS, SHOULD_CALL_WINRT_INTERFACE, ShouldCallWinRTInterface, SM_Obj_IntPtr_RetBool) -DEFINE_METHOD(STUBHELPERS, GET_WINRT_FACTORY_OBJECT, GetWinRTFactoryObject, SM_IntPtr_RetObj) -DEFINE_METHOD(STUBHELPERS, GET_DELEGATE_INVOKE_METHOD, GetDelegateInvokeMethod, SM_Delegate_RetIntPtr) -DEFINE_METHOD(STUBHELPERS, GET_WINRT_FACTORY_RETURN_VALUE, GetWinRTFactoryReturnValue, SM_Obj_IntPtr_RetIntPtr) -DEFINE_METHOD(STUBHELPERS, GET_OUTER_INSPECTABLE, GetOuterInspectable, SM_Obj_IntPtr_RetIntPtr) #endif // FEATURE_COMINTEROP DEFINE_METHOD(STUBHELPERS, SET_LAST_ERROR, SetLastError, SM_RetVoid) DEFINE_METHOD(STUBHELPERS, CLEAR_LAST_ERROR, ClearLastError, SM_RetVoid) @@ -1081,15 +1027,6 @@ DEFINE_METHOD(STUBHELPERS, MULTICAST_DEBUGGER_TRACE_HELPER, Multicas DEFINE_CLASS(CLEANUP_WORK_LIST_ELEMENT, StubHelpers, CleanupWorkListElement) -#ifdef FEATURE_COMINTEROP -DEFINE_CLASS(DATETIMENATIVE, StubHelpers, DateTimeNative) -DEFINE_CLASS(TYPENAMENATIVE, StubHelpers, TypeNameNative) - -DEFINE_CLASS_U(StubHelpers, TypeNameNative, TypeNameNative) -DEFINE_FIELD_U(typeName, TypeNameNative, typeName) -DEFINE_FIELD_U(typeKind, TypeNameNative, typeKind) -#endif - DEFINE_CLASS(ANSICHARMARSHALER, StubHelpers, AnsiCharMarshaler) DEFINE_METHOD(ANSICHARMARSHALER, CONVERT_TO_NATIVE, ConvertToNative, SM_Char_Bool_Bool_RetByte) DEFINE_METHOD(ANSICHARMARSHALER, CONVERT_TO_MANAGED, ConvertToManaged, SM_Byte_RetChar) @@ -1121,16 +1058,6 @@ DEFINE_METHOD(OBJECTMARSHALER, CONVERT_TO_NATIVE, ConvertToNative, DEFINE_METHOD(OBJECTMARSHALER, CONVERT_TO_MANAGED, ConvertToManaged, SM_IntPtr_RetObj) DEFINE_METHOD(OBJECTMARSHALER, CLEAR_NATIVE, ClearNative, SM_IntPtr_RetVoid) -DEFINE_CLASS(HSTRINGMARSHALER, StubHelpers, HStringMarshaler) -DEFINE_METHOD(HSTRINGMARSHALER, CONVERT_TO_NATIVE_REFERENCE, ConvertToNativeReference, SM_Str_PtrHStringHeader_RetIntPtr) -DEFINE_METHOD(HSTRINGMARSHALER, CONVERT_TO_NATIVE, ConvertToNative, SM_Str_RetIntPtr) -DEFINE_METHOD(HSTRINGMARSHALER, CONVERT_TO_MANAGED, ConvertToManaged, SM_IntPtr_RetStr) -DEFINE_METHOD(HSTRINGMARSHALER, CLEAR_NATIVE, ClearNative, SM_IntPtr_RetVoid) - -DEFINE_CLASS(URIMARSHALER, StubHelpers, UriMarshaler) -DEFINE_METHOD(URIMARSHALER, GET_RAWURI_FROM_NATIVE, GetRawUriFromNative, SM_IntPtr_RetStr) -DEFINE_METHOD(URIMARSHALER, CREATE_NATIVE_URI_INSTANCE, CreateNativeUriInstance, SM_Str_RetIntPtr) - DEFINE_CLASS(INTERFACEMARSHALER, StubHelpers, InterfaceMarshaler) DEFINE_METHOD(INTERFACEMARSHALER, CONVERT_TO_NATIVE, ConvertToNative, SM_Obj_IntPtr_IntPtr_Int_RetIntPtr) DEFINE_METHOD(INTERFACEMARSHALER, CONVERT_TO_MANAGED, ConvertToManaged, SM_IntPtr_IntPtr_IntPtr_Int_RetObj) @@ -1144,52 +1071,6 @@ DEFINE_METHOD(MNGD_SAFE_ARRAY_MARSHALER, CONVERT_CONTENTS_TO_NATIVE, ConvertCon DEFINE_METHOD(MNGD_SAFE_ARRAY_MARSHALER, CONVERT_SPACE_TO_MANAGED, ConvertSpaceToManaged, SM_IntPtr_RefObj_IntPtr_RetVoid) DEFINE_METHOD(MNGD_SAFE_ARRAY_MARSHALER, CONVERT_CONTENTS_TO_MANAGED, ConvertContentsToManaged, SM_IntPtr_RefObj_IntPtr_RetVoid) DEFINE_METHOD(MNGD_SAFE_ARRAY_MARSHALER, CLEAR_NATIVE, ClearNative, SM_IntPtr_RefObj_IntPtr_RetVoid) - -DEFINE_CLASS(MNGD_HIDDEN_LENGTH_ARRAY_MARSHALER, StubHelpers, MngdHiddenLengthArrayMarshaler) -DEFINE_METHOD(MNGD_HIDDEN_LENGTH_ARRAY_MARSHALER, CREATE_MARSHALER, CreateMarshaler, SM_IntPtr_IntPtr_IntPtr_UShrt_IntPtr_RetVoid) -DEFINE_METHOD(MNGD_HIDDEN_LENGTH_ARRAY_MARSHALER, CONVERT_SPACE_TO_MANAGED, ConvertSpaceToManaged, SM_IntPtr_RefObj_IntPtr_Int_RetVoid) -DEFINE_METHOD(MNGD_HIDDEN_LENGTH_ARRAY_MARSHALER, CONVERT_CONTENTS_TO_MANAGED, ConvertContentsToManaged, SM_IntPtr_RefObj_IntPtr_RetVoid) -DEFINE_METHOD(MNGD_HIDDEN_LENGTH_ARRAY_MARSHALER, CONVERT_SPACE_TO_NATIVE, ConvertSpaceToNative, SM_IntPtr_RefObj_IntPtr_RetVoid) -DEFINE_METHOD(MNGD_HIDDEN_LENGTH_ARRAY_MARSHALER, CONVERT_CONTENTS_TO_NATIVE, ConvertContentsToNative, SM_IntPtr_RefObj_IntPtr_RetVoid) -DEFINE_METHOD(MNGD_HIDDEN_LENGTH_ARRAY_MARSHALER, CLEAR_NATIVE_CONTENTS, ClearNativeContents, SM_IntPtr_IntPtr_Int_RetVoid) -DEFINE_METHOD(MNGD_HIDDEN_LENGTH_ARRAY_MARSHALER, CLEAR_NATIVE_CONTENTS_TYPE, ClearNativeContents_Type, NoSig) - -DEFINE_METHOD(MNGD_HIDDEN_LENGTH_ARRAY_MARSHALER, CONVERT_CONTENTS_TO_MANAGED_DATETIME, ConvertContentsToManaged_DateTime, NoSig) -DEFINE_METHOD(MNGD_HIDDEN_LENGTH_ARRAY_MARSHALER, CONVERT_CONTENTS_TO_MANAGED_TYPE, ConvertContentsToManaged_Type, NoSig) -DEFINE_METHOD(MNGD_HIDDEN_LENGTH_ARRAY_MARSHALER, CONVERT_CONTENTS_TO_MANAGED_EXCEPTION, ConvertContentsToManaged_Exception, NoSig) -DEFINE_METHOD(MNGD_HIDDEN_LENGTH_ARRAY_MARSHALER, CONVERT_CONTENTS_TO_MANAGED_NULLABLE, ConvertContentsToManaged_Nullable, NoSig) -DEFINE_METHOD(MNGD_HIDDEN_LENGTH_ARRAY_MARSHALER, CONVERT_CONTENTS_TO_MANAGED_KEYVALUEPAIR, ConvertContentsToManaged_KeyValuePair, NoSig) - -DEFINE_METHOD(MNGD_HIDDEN_LENGTH_ARRAY_MARSHALER, CONVERT_CONTENTS_TO_NATIVE_DATETIME, ConvertContentsToNative_DateTime, NoSig) -DEFINE_METHOD(MNGD_HIDDEN_LENGTH_ARRAY_MARSHALER, CONVERT_CONTENTS_TO_NATIVE_TYPE, ConvertContentsToNative_Type, NoSig) -DEFINE_METHOD(MNGD_HIDDEN_LENGTH_ARRAY_MARSHALER, CONVERT_CONTENTS_TO_NATIVE_EXCEPTION, ConvertContentsToNative_Exception, NoSig) -DEFINE_METHOD(MNGD_HIDDEN_LENGTH_ARRAY_MARSHALER, CONVERT_CONTENTS_TO_NATIVE_NULLABLE, ConvertContentsToNative_Nullable, NoSig) -DEFINE_METHOD(MNGD_HIDDEN_LENGTH_ARRAY_MARSHALER, CONVERT_CONTENTS_TO_NATIVE_KEYVALUEPAIR, ConvertContentsToNative_KeyValuePair, NoSig) - -DEFINE_CLASS(DATETIMEOFFSETMARSHALER, StubHelpers, DateTimeOffsetMarshaler) -DEFINE_METHOD(DATETIMEOFFSETMARSHALER, CONVERT_TO_NATIVE, ConvertToNative, SM_RefDateTimeOffset_RefDateTimeNative_RetVoid) -DEFINE_METHOD(DATETIMEOFFSETMARSHALER, CONVERT_TO_MANAGED, ConvertToManaged, SM_RefDateTimeOffset_RefDateTimeNative_RetVoid) - -DEFINE_CLASS(NULLABLEMARSHALER, StubHelpers, NullableMarshaler) -DEFINE_METHOD(NULLABLEMARSHALER, CONVERT_TO_NATIVE, ConvertToNative, NoSig) -DEFINE_METHOD(NULLABLEMARSHALER, CONVERT_TO_MANAGED, ConvertToManaged, NoSig) -DEFINE_METHOD(NULLABLEMARSHALER, CONVERT_TO_MANAGED_RET_VOID, ConvertToManagedRetVoid, NoSig) - -DEFINE_CLASS(SYSTEMTYPEMARSHALER, StubHelpers, SystemTypeMarshaler) - -DEFINE_METHOD(SYSTEMTYPEMARSHALER, CONVERT_TO_NATIVE, ConvertToNative, SM_Type_PtrTypeName_RetVoid) -DEFINE_METHOD(SYSTEMTYPEMARSHALER, CONVERT_TO_MANAGED, ConvertToManaged, SM_PtrTypeName_RefType_RetVoid) -DEFINE_METHOD(SYSTEMTYPEMARSHALER, CLEAR_NATIVE, ClearNative, SM_PtrTypeName_RetVoid) - -DEFINE_CLASS(KEYVALUEPAIRMARSHALER, StubHelpers, KeyValuePairMarshaler) -DEFINE_METHOD(KEYVALUEPAIRMARSHALER, CONVERT_TO_NATIVE, ConvertToNative, NoSig) -DEFINE_METHOD(KEYVALUEPAIRMARSHALER, CONVERT_TO_MANAGED, ConvertToManaged, NoSig) -DEFINE_METHOD(KEYVALUEPAIRMARSHALER, CONVERT_TO_MANAGED_BOX, ConvertToManagedBox, NoSig) - -DEFINE_CLASS(HRESULTEXCEPTIONMARSHALER, StubHelpers, HResultExceptionMarshaler) -DEFINE_METHOD(HRESULTEXCEPTIONMARSHALER, CONVERT_TO_NATIVE, ConvertToNative, SM_Exception_RetInt) -DEFINE_METHOD(HRESULTEXCEPTIONMARSHALER, CONVERT_TO_MANAGED, ConvertToManaged, SM_Int_RetException) - #endif // FEATURE_COMINTEROP DEFINE_CLASS(DATEMARSHALER, StubHelpers, DateMarshaler) @@ -1239,161 +1120,6 @@ DEFINE_METHOD(HANDLE_MARSHALER, THROW_CRITICALHANDLE_FIELD_CHANGED, Thr DEFINE_CLASS(NATIVEVARIANT, StubHelpers, NativeVariant) DEFINE_CLASS(NATIVEDECIMAL, StubHelpers, NativeDecimal) -#ifdef FEATURE_COMINTEROP -DEFINE_CLASS(IITERABLE, WinRT, IIterable`1) -DEFINE_CLASS(IVECTOR, WinRT, IVector`1) -DEFINE_CLASS(IMAP, WinRT, IMap`2) -DEFINE_CLASS(IKEYVALUEPAIR, WinRT, IKeyValuePair`2) -DEFINE_CLASS(IVECTORVIEW, WinRT, IVectorView`1) -DEFINE_CLASS(IMAPVIEW, WinRT, IMapView`2) -DEFINE_CLASS(IITERATOR, WinRT, IIterator`1) -DEFINE_CLASS(IPROPERTYVALUE, WinRT, IPropertyValue) -DEFINE_CLASS(IBINDABLEITERABLE, WinRT, IBindableIterable) -DEFINE_CLASS(IBINDABLEITERATOR, WinRT, IBindableIterator) -DEFINE_CLASS(IBINDABLEVECTOR, WinRT, IBindableVector) -DEFINE_CLASS(ICLOSABLE, WinRT, IClosable) - -DEFINE_CLASS(GET_ENUMERATOR_DELEGATE, WinRT, GetEnumerator_Delegate`1) -DEFINE_CLASS(ITERABLE_TO_ENUMERABLE_ADAPTER, WinRT, IterableToEnumerableAdapter) -DEFINE_METHOD(ITERABLE_TO_ENUMERABLE_ADAPTER, GET_ENUMERATOR_STUB, GetEnumerator_Stub, NoSig) -DEFINE_METHOD(ITERABLE_TO_ENUMERABLE_ADAPTER, GET_ENUMERATOR_VARIANCE_STUB, GetEnumerator_Variance_Stub, NoSig) - -DEFINE_CLASS(VECTOR_TO_LIST_ADAPTER, WinRT, VectorToListAdapter) -DEFINE_METHOD(VECTOR_TO_LIST_ADAPTER, INDEXER_GET, Indexer_Get, NoSig) -DEFINE_METHOD(VECTOR_TO_LIST_ADAPTER, INDEXER_SET, Indexer_Set, NoSig) -DEFINE_METHOD(VECTOR_TO_LIST_ADAPTER, INDEX_OF, IndexOf, NoSig) -DEFINE_METHOD(VECTOR_TO_LIST_ADAPTER, INSERT, Insert, NoSig) -DEFINE_METHOD(VECTOR_TO_LIST_ADAPTER, REMOVE_AT, RemoveAt, NoSig) - -DEFINE_CLASS(MAP_TO_DICTIONARY_ADAPTER, WinRT, MapToDictionaryAdapter) -DEFINE_METHOD(MAP_TO_DICTIONARY_ADAPTER, INDEXER_GET, Indexer_Get, NoSig) -DEFINE_METHOD(MAP_TO_DICTIONARY_ADAPTER, INDEXER_SET, Indexer_Set, NoSig) -DEFINE_METHOD(MAP_TO_DICTIONARY_ADAPTER, KEYS, Keys, NoSig) -DEFINE_METHOD(MAP_TO_DICTIONARY_ADAPTER, VALUES, Values, NoSig) -DEFINE_METHOD(MAP_TO_DICTIONARY_ADAPTER, CONTAINS_KEY, ContainsKey, NoSig) -DEFINE_METHOD(MAP_TO_DICTIONARY_ADAPTER, ADD, Add, NoSig) -DEFINE_METHOD(MAP_TO_DICTIONARY_ADAPTER, REMOVE, Remove, NoSig) -DEFINE_METHOD(MAP_TO_DICTIONARY_ADAPTER, TRY_GET_VALUE, TryGetValue, NoSig) - -DEFINE_CLASS(VECTOR_TO_COLLECTION_ADAPTER, WinRT, VectorToCollectionAdapter) -DEFINE_METHOD(VECTOR_TO_COLLECTION_ADAPTER, COUNT, Count, NoSig) -DEFINE_METHOD(VECTOR_TO_COLLECTION_ADAPTER, IS_READ_ONLY, IsReadOnly, NoSig) -DEFINE_METHOD(VECTOR_TO_COLLECTION_ADAPTER, ADD, Add, NoSig) -DEFINE_METHOD(VECTOR_TO_COLLECTION_ADAPTER, CLEAR, Clear, NoSig) -DEFINE_METHOD(VECTOR_TO_COLLECTION_ADAPTER, CONTAINS, Contains, NoSig) -DEFINE_METHOD(VECTOR_TO_COLLECTION_ADAPTER, COPY_TO, CopyTo, NoSig) -DEFINE_METHOD(VECTOR_TO_COLLECTION_ADAPTER, REMOVE, Remove, NoSig) - -DEFINE_CLASS(MAP_TO_COLLECTION_ADAPTER, WinRT, MapToCollectionAdapter) -DEFINE_METHOD(MAP_TO_COLLECTION_ADAPTER, COUNT, Count, NoSig) -DEFINE_METHOD(MAP_TO_COLLECTION_ADAPTER, IS_READ_ONLY, IsReadOnly, NoSig) -DEFINE_METHOD(MAP_TO_COLLECTION_ADAPTER, ADD, Add, NoSig) -DEFINE_METHOD(MAP_TO_COLLECTION_ADAPTER, CLEAR, Clear, NoSig) -DEFINE_METHOD(MAP_TO_COLLECTION_ADAPTER, CONTAINS, Contains, NoSig) -DEFINE_METHOD(MAP_TO_COLLECTION_ADAPTER, COPY_TO, CopyTo, NoSig) -DEFINE_METHOD(MAP_TO_COLLECTION_ADAPTER, REMOVE, Remove, NoSig) - -DEFINE_CLASS(BINDABLEITERABLE_TO_ENUMERABLE_ADAPTER, WinRT, BindableIterableToEnumerableAdapter) -DEFINE_METHOD(BINDABLEITERABLE_TO_ENUMERABLE_ADAPTER, GET_ENUMERATOR_STUB, GetEnumerator_Stub, NoSig) - -DEFINE_CLASS(BINDABLEVECTOR_TO_LIST_ADAPTER, WinRT, BindableVectorToListAdapter) -DEFINE_METHOD(BINDABLEVECTOR_TO_LIST_ADAPTER, INDEXER_GET, Indexer_Get, NoSig) -DEFINE_METHOD(BINDABLEVECTOR_TO_LIST_ADAPTER, INDEXER_SET, Indexer_Set, NoSig) -DEFINE_METHOD(BINDABLEVECTOR_TO_LIST_ADAPTER, ADD, Add, NoSig) -DEFINE_METHOD(BINDABLEVECTOR_TO_LIST_ADAPTER, CONTAINS, Contains, NoSig) -DEFINE_METHOD(BINDABLEVECTOR_TO_LIST_ADAPTER, CLEAR, Clear, NoSig) -DEFINE_METHOD(BINDABLEVECTOR_TO_LIST_ADAPTER, IS_READ_ONLY, IsReadOnly, NoSig) -DEFINE_METHOD(BINDABLEVECTOR_TO_LIST_ADAPTER, IS_FIXED_SIZE, IsFixedSize, NoSig) -DEFINE_METHOD(BINDABLEVECTOR_TO_LIST_ADAPTER, INDEX_OF, IndexOf, NoSig) -DEFINE_METHOD(BINDABLEVECTOR_TO_LIST_ADAPTER, INSERT, Insert, NoSig) -DEFINE_METHOD(BINDABLEVECTOR_TO_LIST_ADAPTER, REMOVE, Remove, NoSig) -DEFINE_METHOD(BINDABLEVECTOR_TO_LIST_ADAPTER, REMOVE_AT, RemoveAt, NoSig) - -DEFINE_CLASS(BINDABLEVECTOR_TO_COLLECTION_ADAPTER, WinRT, BindableVectorToCollectionAdapter) -DEFINE_METHOD(BINDABLEVECTOR_TO_COLLECTION_ADAPTER, COPY_TO, CopyTo, NoSig) -DEFINE_METHOD(BINDABLEVECTOR_TO_COLLECTION_ADAPTER, COUNT, Count, NoSig) -DEFINE_METHOD(BINDABLEVECTOR_TO_COLLECTION_ADAPTER, SYNC_ROOT, SyncRoot, NoSig) -DEFINE_METHOD(BINDABLEVECTOR_TO_COLLECTION_ADAPTER, IS_SYNCHRONIZED, IsSynchronized, NoSig) - -DEFINE_CLASS(ENUMERABLE_TO_ITERABLE_ADAPTER, WinRT, EnumerableToIterableAdapter) -DEFINE_METHOD(ENUMERABLE_TO_ITERABLE_ADAPTER, FIRST_STUB, First_Stub, NoSig) - -DEFINE_CLASS(LIST_TO_VECTOR_ADAPTER, WinRT, ListToVectorAdapter) -DEFINE_METHOD(LIST_TO_VECTOR_ADAPTER, GET_AT, GetAt, NoSig) -DEFINE_METHOD(LIST_TO_VECTOR_ADAPTER, SIZE, Size, NoSig) -DEFINE_METHOD(LIST_TO_VECTOR_ADAPTER, GET_VIEW, GetView, NoSig) -DEFINE_METHOD(LIST_TO_VECTOR_ADAPTER, INDEX_OF, IndexOf, NoSig) -DEFINE_METHOD(LIST_TO_VECTOR_ADAPTER, SET_AT, SetAt, NoSig) -DEFINE_METHOD(LIST_TO_VECTOR_ADAPTER, INSERT_AT, InsertAt, NoSig) -DEFINE_METHOD(LIST_TO_VECTOR_ADAPTER, REMOVE_AT, RemoveAt, NoSig) -DEFINE_METHOD(LIST_TO_VECTOR_ADAPTER, APPEND, Append, NoSig) -DEFINE_METHOD(LIST_TO_VECTOR_ADAPTER, REMOVE_AT_END, RemoveAtEnd, NoSig) -DEFINE_METHOD(LIST_TO_VECTOR_ADAPTER, CLEAR, Clear, NoSig) -DEFINE_METHOD(LIST_TO_VECTOR_ADAPTER, GET_MANY, GetMany, NoSig) -DEFINE_METHOD(LIST_TO_VECTOR_ADAPTER, REPLACE_ALL, ReplaceAll, NoSig) - -DEFINE_CLASS(DICTIONARY_TO_MAP_ADAPTER, WinRT, DictionaryToMapAdapter) -DEFINE_METHOD(DICTIONARY_TO_MAP_ADAPTER, LOOKUP, Lookup, NoSig) -DEFINE_METHOD(DICTIONARY_TO_MAP_ADAPTER, SIZE, Size, NoSig) -DEFINE_METHOD(DICTIONARY_TO_MAP_ADAPTER, HAS_KEY, HasKey, NoSig) -DEFINE_METHOD(DICTIONARY_TO_MAP_ADAPTER, GET_VIEW, GetView, NoSig) -DEFINE_METHOD(DICTIONARY_TO_MAP_ADAPTER, INSERT, Insert, NoSig) -DEFINE_METHOD(DICTIONARY_TO_MAP_ADAPTER, REMOVE, Remove, NoSig) -DEFINE_METHOD(DICTIONARY_TO_MAP_ADAPTER, CLEAR, Clear, NoSig) - -DEFINE_CLASS(IVECTORVIEW_TO_IREADONLYCOLLECTION_ADAPTER, WinRT, VectorViewToReadOnlyCollectionAdapter) -DEFINE_METHOD(IVECTORVIEW_TO_IREADONLYCOLLECTION_ADAPTER, COUNT, Count, NoSig) - -DEFINE_CLASS(IMAPVIEW_TO_IREADONLYCOLLECTION_ADAPTER, WinRT, MapViewToReadOnlyCollectionAdapter) -DEFINE_METHOD(IMAPVIEW_TO_IREADONLYCOLLECTION_ADAPTER, COUNT, Count, NoSig) - -DEFINE_CLASS(IREADONLYLIST_TO_IVECTORVIEW_ADAPTER, WinRT, IReadOnlyListToIVectorViewAdapter) -DEFINE_METHOD(IREADONLYLIST_TO_IVECTORVIEW_ADAPTER, GETAT, GetAt, NoSig) -DEFINE_METHOD(IREADONLYLIST_TO_IVECTORVIEW_ADAPTER, GETMANY, GetMany, NoSig) -DEFINE_METHOD(IREADONLYLIST_TO_IVECTORVIEW_ADAPTER, INDEXOF, IndexOf, NoSig) -DEFINE_METHOD(IREADONLYLIST_TO_IVECTORVIEW_ADAPTER, SIZE, Size, NoSig) - -DEFINE_CLASS(INDEXER_GET_DELEGATE, WinRT, Indexer_Get_Delegate`1) -DEFINE_CLASS(IVECTORVIEW_TO_IREADONLYLIST_ADAPTER, WinRT, IVectorViewToIReadOnlyListAdapter) -DEFINE_METHOD(IVECTORVIEW_TO_IREADONLYLIST_ADAPTER, INDEXER_GET, Indexer_Get, NoSig) -DEFINE_METHOD(IVECTORVIEW_TO_IREADONLYLIST_ADAPTER, INDEXER_GET_VARIANCE, Indexer_Get_Variance, NoSig) - -DEFINE_CLASS(IREADONLYDICTIONARY_TO_IMAPVIEW_ADAPTER, WinRT, IReadOnlyDictionaryToIMapViewAdapter) -DEFINE_METHOD(IREADONLYDICTIONARY_TO_IMAPVIEW_ADAPTER, HASKEY, HasKey, NoSig) -DEFINE_METHOD(IREADONLYDICTIONARY_TO_IMAPVIEW_ADAPTER, LOOKUP, Lookup, NoSig) -DEFINE_METHOD(IREADONLYDICTIONARY_TO_IMAPVIEW_ADAPTER, SIZE, Size, NoSig) -DEFINE_METHOD(IREADONLYDICTIONARY_TO_IMAPVIEW_ADAPTER, SPLIT, Split, NoSig) - -DEFINE_CLASS(IMAPVIEW_TO_IREADONLYDICTIONARY_ADAPTER, WinRT, IMapViewToIReadOnlyDictionaryAdapter) -DEFINE_METHOD(IMAPVIEW_TO_IREADONLYDICTIONARY_ADAPTER, CONTAINSKEY, ContainsKey, NoSig) -DEFINE_METHOD(IMAPVIEW_TO_IREADONLYDICTIONARY_ADAPTER, INDEXER_GET, Indexer_Get, NoSig) -DEFINE_METHOD(IMAPVIEW_TO_IREADONLYDICTIONARY_ADAPTER, TRYGETVALUE, TryGetValue, NoSig) -DEFINE_METHOD(IMAPVIEW_TO_IREADONLYDICTIONARY_ADAPTER, KEYS, Keys, NoSig) -DEFINE_METHOD(IMAPVIEW_TO_IREADONLYDICTIONARY_ADAPTER, VALUES, Values, NoSig) - -DEFINE_CLASS(ENUMERABLE_TO_BINDABLEITERABLE_ADAPTER, WinRT, EnumerableToBindableIterableAdapter) -DEFINE_METHOD(ENUMERABLE_TO_BINDABLEITERABLE_ADAPTER, FIRST_STUB, First_Stub, NoSig) - -DEFINE_CLASS(LIST_TO_BINDABLEVECTOR_ADAPTER, WinRT, ListToBindableVectorAdapter) -DEFINE_METHOD(LIST_TO_BINDABLEVECTOR_ADAPTER, GET_AT, GetAt, NoSig) -DEFINE_METHOD(LIST_TO_BINDABLEVECTOR_ADAPTER, SIZE, Size, NoSig) -DEFINE_METHOD(LIST_TO_BINDABLEVECTOR_ADAPTER, GET_VIEW, GetView, NoSig) -DEFINE_METHOD(LIST_TO_BINDABLEVECTOR_ADAPTER, INDEX_OF, IndexOf, NoSig) -DEFINE_METHOD(LIST_TO_BINDABLEVECTOR_ADAPTER, SET_AT, SetAt, NoSig) -DEFINE_METHOD(LIST_TO_BINDABLEVECTOR_ADAPTER, INSERT_AT, InsertAt, NoSig) -DEFINE_METHOD(LIST_TO_BINDABLEVECTOR_ADAPTER, REMOVE_AT, RemoveAt, NoSig) -DEFINE_METHOD(LIST_TO_BINDABLEVECTOR_ADAPTER, APPEND, Append, NoSig) -DEFINE_METHOD(LIST_TO_BINDABLEVECTOR_ADAPTER, REMOVE_AT_END, RemoveAtEnd, NoSig) -DEFINE_METHOD(LIST_TO_BINDABLEVECTOR_ADAPTER, CLEAR, Clear, NoSig) - -DEFINE_CLASS(IDISPOSABLE_TO_ICLOSABLE_ADAPTER, WinRT, IDisposableToIClosableAdapter) -DEFINE_METHOD(IDISPOSABLE_TO_ICLOSABLE_ADAPTER, CLOSE, Close, NoSig) - -DEFINE_CLASS(ICLOSABLE_TO_IDISPOSABLE_ADAPTER, WinRT, IClosableToIDisposableAdapter) -DEFINE_METHOD(ICLOSABLE_TO_IDISPOSABLE_ADAPTER, DISPOSE, Dispose, NoSig) - -#endif // FEATURE_COMINTEROP - DEFINE_CLASS(SZARRAYHELPER, System, SZArrayHelper) // Note: The order of methods here has to match order they are implemented on the interfaces in // IEnumerable`1 @@ -1445,16 +1171,6 @@ DEFINE_FIELD_U(_kind, ContractExceptionObject, _Kind) DEFINE_FIELD_U(_userMessage, ContractExceptionObject, _UserMessage) DEFINE_FIELD_U(_condition, ContractExceptionObject, _Condition) -#ifdef FEATURE_COMINTEROP -DEFINE_CLASS(CAUSALITY_TRACE_LEVEL, WindowsFoundationDiag, CausalityTraceLevel) -DEFINE_CLASS(ASYNC_TRACING_EVENT_ARGS, WindowsFoundationDiag, TracingStatusChangedEventArgs) -DEFINE_PROPERTY(ASYNC_TRACING_EVENT_ARGS, ENABLED, Enabled, Bool) -DEFINE_PROPERTY(ASYNC_TRACING_EVENT_ARGS, TRACELEVEL, TraceLevel, CausalityTraceLevel) -DEFINE_CLASS(IASYNC_TRACING_EVENT_ARGS, WindowsFoundationDiag, ITracingStatusChangedEventArgs) -DEFINE_PROPERTY(IASYNC_TRACING_EVENT_ARGS, ENABLED, Enabled, Bool) -DEFINE_PROPERTY(IASYNC_TRACING_EVENT_ARGS, TRACELEVEL, TraceLevel, CausalityTraceLevel) -#endif // FEATURE_COMINTEROP - DEFINE_CLASS(MODULEBASE, Reflection, Module) #ifdef FEATURE_ICASTABLE diff --git a/src/coreclr/src/vm/mtypes.h b/src/coreclr/src/vm/mtypes.h index 2d0917e..f40c724 100644 --- a/src/coreclr/src/vm/mtypes.h +++ b/src/coreclr/src/vm/mtypes.h @@ -13,110 +13,95 @@ // ------------------------------------------------------------------------------------------------------------------ // Marshaler ID Marshaler class name Supported in WinRT scenarios -DEFINE_MARSHALER_TYPE(MARSHAL_TYPE_GENERIC_1, CopyMarshaler1, true) -DEFINE_MARSHALER_TYPE(MARSHAL_TYPE_GENERIC_U1, CopyMarshalerU1, true) -DEFINE_MARSHALER_TYPE(MARSHAL_TYPE_GENERIC_2, CopyMarshaler2, true) -DEFINE_MARSHALER_TYPE(MARSHAL_TYPE_GENERIC_U2, CopyMarshalerU2, true) -DEFINE_MARSHALER_TYPE(MARSHAL_TYPE_GENERIC_4, CopyMarshaler4, true) -DEFINE_MARSHALER_TYPE(MARSHAL_TYPE_GENERIC_U4, CopyMarshalerU4, true) -DEFINE_MARSHALER_TYPE(MARSHAL_TYPE_GENERIC_8, CopyMarshaler8, true) - -DEFINE_MARSHALER_TYPE(MARSHAL_TYPE_WINBOOL, WinBoolMarshaler, false) -DEFINE_MARSHALER_TYPE(MARSHAL_TYPE_CBOOL, CBoolMarshaler, true) +DEFINE_MARSHALER_TYPE(MARSHAL_TYPE_GENERIC_1, CopyMarshaler1) +DEFINE_MARSHALER_TYPE(MARSHAL_TYPE_GENERIC_U1, CopyMarshalerU1) +DEFINE_MARSHALER_TYPE(MARSHAL_TYPE_GENERIC_2, CopyMarshaler2) +DEFINE_MARSHALER_TYPE(MARSHAL_TYPE_GENERIC_U2, CopyMarshalerU2) +DEFINE_MARSHALER_TYPE(MARSHAL_TYPE_GENERIC_4, CopyMarshaler4) +DEFINE_MARSHALER_TYPE(MARSHAL_TYPE_GENERIC_U4, CopyMarshalerU4) +DEFINE_MARSHALER_TYPE(MARSHAL_TYPE_GENERIC_8, CopyMarshaler8) + +DEFINE_MARSHALER_TYPE(MARSHAL_TYPE_WINBOOL, WinBoolMarshaler) +DEFINE_MARSHALER_TYPE(MARSHAL_TYPE_CBOOL, CBoolMarshaler) #ifdef FEATURE_COMINTEROP -DEFINE_MARSHALER_TYPE(MARSHAL_TYPE_VTBOOL, VtBoolMarshaler, false) +DEFINE_MARSHALER_TYPE(MARSHAL_TYPE_VTBOOL, VtBoolMarshaler) #endif // FEATURE_COMINTEROP -DEFINE_MARSHALER_TYPE(MARSHAL_TYPE_ANSICHAR, AnsiCharMarshaler, false) +DEFINE_MARSHALER_TYPE(MARSHAL_TYPE_ANSICHAR, AnsiCharMarshaler) -DEFINE_MARSHALER_TYPE(MARSHAL_TYPE_FLOAT, FloatMarshaler, true) -DEFINE_MARSHALER_TYPE(MARSHAL_TYPE_DOUBLE, DoubleMarshaler, true) +DEFINE_MARSHALER_TYPE(MARSHAL_TYPE_FLOAT, FloatMarshaler) +DEFINE_MARSHALER_TYPE(MARSHAL_TYPE_DOUBLE, DoubleMarshaler) -DEFINE_MARSHALER_TYPE(MARSHAL_TYPE_CURRENCY, CurrencyMarshaler, false) -DEFINE_MARSHALER_TYPE(MARSHAL_TYPE_DECIMAL, DecimalMarshaler, false) -DEFINE_MARSHALER_TYPE(MARSHAL_TYPE_DECIMAL_PTR, DecimalPtrMarshaler, false) -DEFINE_MARSHALER_TYPE(MARSHAL_TYPE_GUID, GuidMarshaler, true) -DEFINE_MARSHALER_TYPE(MARSHAL_TYPE_GUID_PTR, GuidPtrMarshaler, false) -DEFINE_MARSHALER_TYPE(MARSHAL_TYPE_DATE, DateMarshaler, false) +DEFINE_MARSHALER_TYPE(MARSHAL_TYPE_CURRENCY, CurrencyMarshaler) +DEFINE_MARSHALER_TYPE(MARSHAL_TYPE_DECIMAL, DecimalMarshaler) +DEFINE_MARSHALER_TYPE(MARSHAL_TYPE_DECIMAL_PTR, DecimalPtrMarshaler) +DEFINE_MARSHALER_TYPE(MARSHAL_TYPE_GUID, GuidMarshaler) +DEFINE_MARSHALER_TYPE(MARSHAL_TYPE_GUID_PTR, GuidPtrMarshaler) +DEFINE_MARSHALER_TYPE(MARSHAL_TYPE_DATE, DateMarshaler) -DEFINE_MARSHALER_TYPE(MARSHAL_TYPE_LPWSTR, WSTRMarshaler, false) -DEFINE_MARSHALER_TYPE(MARSHAL_TYPE_LPSTR, CSTRMarshaler, false) -DEFINE_MARSHALER_TYPE(MARSHAL_TYPE_LPUTF8STR, CUTF8Marshaler, false) -DEFINE_MARSHALER_TYPE(MARSHAL_TYPE_BSTR, BSTRMarshaler, false) -DEFINE_MARSHALER_TYPE(MARSHAL_TYPE_ANSIBSTR, AnsiBSTRMarshaler, false) -#ifdef FEATURE_COMINTEROP -DEFINE_MARSHALER_TYPE(MARSHAL_TYPE_HSTRING, HSTRINGMarshaler, true) -DEFINE_MARSHALER_TYPE(MARSHAL_TYPE_DATETIME, DateTimeMarshaler, true) -DEFINE_MARSHALER_TYPE(MARSHAL_TYPE_URI, UriMarshaler, true) -DEFINE_MARSHALER_TYPE(MARSHAL_TYPE_NCCEVENTARGS, NCCEventArgsMarshaler, true) // NotifyCollectionChangedEventArgs -DEFINE_MARSHALER_TYPE(MARSHAL_TYPE_PCEVENTARGS, PCEventArgsMarshaler, true) // PropertyChangedEventArgs -#endif // FEATURE_COMINTEROP +DEFINE_MARSHALER_TYPE(MARSHAL_TYPE_LPWSTR, WSTRMarshaler) +DEFINE_MARSHALER_TYPE(MARSHAL_TYPE_LPSTR, CSTRMarshaler) +DEFINE_MARSHALER_TYPE(MARSHAL_TYPE_LPUTF8STR, CUTF8Marshaler) +DEFINE_MARSHALER_TYPE(MARSHAL_TYPE_BSTR, BSTRMarshaler) +DEFINE_MARSHALER_TYPE(MARSHAL_TYPE_ANSIBSTR, AnsiBSTRMarshaler) -DEFINE_MARSHALER_TYPE(MARSHAL_TYPE_LPWSTR_BUFFER, WSTRBufferMarshaler, false) -DEFINE_MARSHALER_TYPE(MARSHAL_TYPE_LPSTR_BUFFER, CSTRBufferMarshaler, false) -DEFINE_MARSHALER_TYPE(MARSHAL_TYPE_UTF8_BUFFER, UTF8BufferMarshaler, false) +DEFINE_MARSHALER_TYPE(MARSHAL_TYPE_LPWSTR_BUFFER, WSTRBufferMarshaler) +DEFINE_MARSHALER_TYPE(MARSHAL_TYPE_LPSTR_BUFFER, CSTRBufferMarshaler) +DEFINE_MARSHALER_TYPE(MARSHAL_TYPE_UTF8_BUFFER, UTF8BufferMarshaler) #if defined(FEATURE_COMINTEROP) // CoreCLR doesn't have any support for marshalling interface pointers. // Not even support for fake CCWs. -DEFINE_MARSHALER_TYPE(MARSHAL_TYPE_INTERFACE, InterfaceMarshaler, true) +DEFINE_MARSHALER_TYPE(MARSHAL_TYPE_INTERFACE, InterfaceMarshaler) #endif // defined(FEATURE_COMINTEROP) #ifdef FEATURE_COMINTEROP -DEFINE_MARSHALER_TYPE(MARSHAL_TYPE_SAFEARRAY, SafeArrayMarshaler, false) -DEFINE_MARSHALER_TYPE(MARSHAL_TYPE_HIDDENLENGTHARRAY, HiddenLengthArrayMarshaler, true) +DEFINE_MARSHALER_TYPE(MARSHAL_TYPE_SAFEARRAY, SafeArrayMarshaler) #endif // FEATURE_COMINTEROP -DEFINE_MARSHALER_TYPE(MARSHAL_TYPE_NATIVEARRAY, NativeArrayMarshaler, false) +DEFINE_MARSHALER_TYPE(MARSHAL_TYPE_NATIVEARRAY, NativeArrayMarshaler) -DEFINE_MARSHALER_TYPE(MARSHAL_TYPE_ASANYA, AsAnyAMarshaler, false) -DEFINE_MARSHALER_TYPE(MARSHAL_TYPE_ASANYW, AsAnyWMarshaler, false) +DEFINE_MARSHALER_TYPE(MARSHAL_TYPE_ASANYA, AsAnyAMarshaler) +DEFINE_MARSHALER_TYPE(MARSHAL_TYPE_ASANYW, AsAnyWMarshaler) -DEFINE_MARSHALER_TYPE(MARSHAL_TYPE_DELEGATE, DelegateMarshaler, false) +DEFINE_MARSHALER_TYPE(MARSHAL_TYPE_DELEGATE, DelegateMarshaler) -DEFINE_MARSHALER_TYPE(MARSHAL_TYPE_BLITTABLEPTR, BlittablePtrMarshaler, false) +DEFINE_MARSHALER_TYPE(MARSHAL_TYPE_BLITTABLEPTR, BlittablePtrMarshaler) #ifdef FEATURE_COMINTEROP -DEFINE_MARSHALER_TYPE(MARSHAL_TYPE_VBBYVALSTR, VBByValStrMarshaler, false) -DEFINE_MARSHALER_TYPE(MARSHAL_TYPE_VBBYVALSTRW, VBByValStrWMarshaler, false) +DEFINE_MARSHALER_TYPE(MARSHAL_TYPE_VBBYVALSTR, VBByValStrMarshaler) +DEFINE_MARSHALER_TYPE(MARSHAL_TYPE_VBBYVALSTRW, VBByValStrWMarshaler) #endif // FEATURE_COMINTEROP -DEFINE_MARSHALER_TYPE(MARSHAL_TYPE_LAYOUTCLASSPTR, LayoutClassPtrMarshaler, false) -DEFINE_MARSHALER_TYPE(MARSHAL_TYPE_ARRAYWITHOFFSET, ArrayWithOffsetMarshaler, false) +DEFINE_MARSHALER_TYPE(MARSHAL_TYPE_LAYOUTCLASSPTR, LayoutClassPtrMarshaler) +DEFINE_MARSHALER_TYPE(MARSHAL_TYPE_ARRAYWITHOFFSET, ArrayWithOffsetMarshaler) -DEFINE_MARSHALER_TYPE(MARSHAL_TYPE_BLITTABLEVALUECLASS, BlittableValueClassMarshaler, true) -DEFINE_MARSHALER_TYPE(MARSHAL_TYPE_VALUECLASS, ValueClassMarshaler, true) +DEFINE_MARSHALER_TYPE(MARSHAL_TYPE_BLITTABLEVALUECLASS, BlittableValueClassMarshaler) +DEFINE_MARSHALER_TYPE(MARSHAL_TYPE_VALUECLASS, ValueClassMarshaler) -DEFINE_MARSHALER_TYPE(MARSHAL_TYPE_REFERENCECUSTOMMARSHALER, ReferenceCustomMarshaler, false) -DEFINE_MARSHALER_TYPE(MARSHAL_TYPE_ARGITERATOR, ArgIteratorMarshaler, false) -DEFINE_MARSHALER_TYPE(MARSHAL_TYPE_BLITTABLEVALUECLASSWITHCOPYCTOR, BlittableValueClassWithCopyCtorMarshaler, false) +DEFINE_MARSHALER_TYPE(MARSHAL_TYPE_REFERENCECUSTOMMARSHALER, ReferenceCustomMarshaler) +DEFINE_MARSHALER_TYPE(MARSHAL_TYPE_ARGITERATOR, ArgIteratorMarshaler) +DEFINE_MARSHALER_TYPE(MARSHAL_TYPE_BLITTABLEVALUECLASSWITHCOPYCTOR, BlittableValueClassWithCopyCtorMarshaler) #ifdef FEATURE_COMINTEROP -DEFINE_MARSHALER_TYPE(MARSHAL_TYPE_OBJECT, ObjectMarshaler, false) +DEFINE_MARSHALER_TYPE(MARSHAL_TYPE_OBJECT, ObjectMarshaler) #endif // FEATURE_COMINTEROP -DEFINE_MARSHALER_TYPE(MARSHAL_TYPE_HANDLEREF, HandleRefMarshaler, false) -DEFINE_MARSHALER_TYPE(MARSHAL_TYPE_SAFEHANDLE, SafeHandleMarshaler, false) -DEFINE_MARSHALER_TYPE(MARSHAL_TYPE_CRITICALHANDLE, CriticalHandleMarshaler, false) +DEFINE_MARSHALER_TYPE(MARSHAL_TYPE_HANDLEREF, HandleRefMarshaler) +DEFINE_MARSHALER_TYPE(MARSHAL_TYPE_SAFEHANDLE, SafeHandleMarshaler) +DEFINE_MARSHALER_TYPE(MARSHAL_TYPE_CRITICALHANDLE, CriticalHandleMarshaler) #ifdef FEATURE_COMINTEROP -DEFINE_MARSHALER_TYPE(MARSHAL_TYPE_OLECOLOR, OleColorMarshaler, false) +DEFINE_MARSHALER_TYPE(MARSHAL_TYPE_OLECOLOR, OleColorMarshaler) #endif // FEATURE_COMINTEROP -DEFINE_MARSHALER_TYPE(MARSHAL_TYPE_RUNTIMETYPEHANDLE, RuntimeTypeHandleMarshaler, false) -DEFINE_MARSHALER_TYPE(MARSHAL_TYPE_RUNTIMEMETHODHANDLE, RuntimeMethodHandleMarshaler, false) -DEFINE_MARSHALER_TYPE(MARSHAL_TYPE_RUNTIMEFIELDHANDLE, RuntimeFieldHandleMarshaler, false) - -#ifdef FEATURE_COMINTEROP -DEFINE_MARSHALER_TYPE(MARSHAL_TYPE_NULLABLE, NullableMarshaler, true) -DEFINE_MARSHALER_TYPE(MARSHAL_TYPE_SYSTEMTYPE, SystemTypeMarshaler, true) -DEFINE_MARSHALER_TYPE(MARSHAL_TYPE_KEYVALUEPAIR, KeyValuePairMarshaler, true) -DEFINE_MARSHALER_TYPE(MARSHAL_TYPE_EXCEPTION, HResultExceptionMarshaler, true) // For WinRT, marshal exceptions as Windows.Foundation.HResult -#endif // FEATURE_COMINTEROP +DEFINE_MARSHALER_TYPE(MARSHAL_TYPE_RUNTIMETYPEHANDLE, RuntimeTypeHandleMarshaler) +DEFINE_MARSHALER_TYPE(MARSHAL_TYPE_RUNTIMEMETHODHANDLE, RuntimeMethodHandleMarshaler) +DEFINE_MARSHALER_TYPE(MARSHAL_TYPE_RUNTIMEFIELDHANDLE, RuntimeFieldHandleMarshaler) -DEFINE_MARSHALER_TYPE(MARSHAL_TYPE_FIXED_ARRAY, FixedArrayMarshaler, false) -DEFINE_MARSHALER_TYPE(MARSHAL_TYPE_FIXED_WSTR, FixedWSTRMarshaler, false) -DEFINE_MARSHALER_TYPE(MARSHAL_TYPE_FIXED_CSTR, FixedCSTRMarshaler, false) -DEFINE_MARSHALER_TYPE(MARSHAL_TYPE_BLITTABLE_LAYOUTCLASS, BlittableLayoutClassMarshaler, false) -DEFINE_MARSHALER_TYPE(MARSHAL_TYPE_LAYOUTCLASS, LayoutClassMarshaler, false) +DEFINE_MARSHALER_TYPE(MARSHAL_TYPE_FIXED_ARRAY, FixedArrayMarshaler) +DEFINE_MARSHALER_TYPE(MARSHAL_TYPE_FIXED_WSTR, FixedWSTRMarshaler) +DEFINE_MARSHALER_TYPE(MARSHAL_TYPE_FIXED_CSTR, FixedCSTRMarshaler) +DEFINE_MARSHALER_TYPE(MARSHAL_TYPE_BLITTABLE_LAYOUTCLASS, BlittableLayoutClassMarshaler) +DEFINE_MARSHALER_TYPE(MARSHAL_TYPE_LAYOUTCLASS, LayoutClassMarshaler) #undef DEFINE_MARSHALER_TYPE diff --git a/src/coreclr/src/vm/multicorejitimpl.h b/src/coreclr/src/vm/multicorejitimpl.h index 26e6a3b..d1e3ed5 100644 --- a/src/coreclr/src/vm/multicorejitimpl.h +++ b/src/coreclr/src/vm/multicorejitimpl.h @@ -162,8 +162,6 @@ inline unsigned RoundUp(unsigned val) return (val + 3) / 4 * 4; } -const unsigned short FLAG_LOADOKAY = 1; // Okay to load the module in background thread (e.g. for Appx first party WinMD) - // Used to mark a module that was loaded in the LOADFROM context. // First 16 bits are reserved for CorAssemblyFlags. Use the last bit (bit 31) to allow for expansion of CorAssemblyFlags. const unsigned int VERSIONFLAG_LOADCTX_LOADFROM = 0x40000000; diff --git a/src/coreclr/src/vm/multicorejitplayer.cpp b/src/coreclr/src/vm/multicorejitplayer.cpp index 754b783..601e5b8 100644 --- a/src/coreclr/src/vm/multicorejitplayer.cpp +++ b/src/coreclr/src/vm/multicorejitplayer.cpp @@ -174,13 +174,6 @@ public: return m_pModule != NULL; } - bool LoadOkay() const - { - LIMITED_METHOD_CONTRACT; - - return (m_pRecord->flags & FLAG_LOADOKAY) != 0; - } - // UpdateNeedLevel called bool IsDependency() const { @@ -700,7 +693,7 @@ HRESULT MulticoreJitProfilePlayer::UpdateModuleInfo() { PlayerModuleInfo & info = m_pModules[i]; - if (! info.LoadOkay() && info.IsDependency() && ! info.IsModuleLoaded()) + if (info.IsDependency() && ! info.IsModuleLoaded()) { MulticoreJitTrace((" Enumerate modules for player")); @@ -727,7 +720,7 @@ HRESULT MulticoreJitProfilePlayer::UpdateModuleInfo() { PlayerModuleInfo & info = m_pModules[i]; - if (! info.LoadOkay() && info.IsLowerLevel()) + if (info.IsLowerLevel()) { if (info.IsModuleLoaded()) { @@ -916,10 +909,7 @@ bool MulticoreJitProfilePlayer::HandleModuleDependency(unsigned jitInfo) if (mod.UpdateNeedLevel((FileLoadLevel) level)) { - if (! mod.LoadOkay()) // allow first part WinMD to load in background thread - { - m_nBlockingCount ++; - } + m_nBlockingCount ++; } } diff --git a/src/coreclr/src/vm/namespace.h b/src/coreclr/src/vm/namespace.h index 61943a9..76e0882 100644 --- a/src/coreclr/src/vm/namespace.h +++ b/src/coreclr/src/vm/namespace.h @@ -35,9 +35,6 @@ #define g_InteropNS g_RuntimeNS ".InteropServices" #define g_InteropTCENS g_InteropNS ".TCEAdapterGen" #define g_ExpandoNS g_InteropNS ".Expando" -#ifdef FEATURE_COMINTEROP -#define g_WinRTNS g_InteropNS ".WindowsRuntime" -#endif // FEATURE_COMINTEROP #define g_IntrinsicsNS g_RuntimeNS ".Intrinsics" #define g_NumericsNS g_SystemNS ".Numerics" @@ -72,16 +69,6 @@ #define g_StubHelpersNS g_SystemNS ".StubHelpers" -// Jupiter support requires accessing types in the System.Windows namespace & children, -// but these types may show up in the Windows.UI.Xaml namespace. -#define g_SysWindowsNS g_SystemNS ".Windows" - -#define g_DirectUINS "Windows.UI.Xaml" -#define g_AutomationNS g_DirectUINS ".Automation" -#define g_MarkupNS g_DirectUINS ".Markup" - -#define g_WindowsFoundationDiagNS "Windows.Foundation.Diagnostics" - #define g_ExceptionServicesNS g_RuntimeNS ".ExceptionServices" #define g_LoaderNS g_RuntimeNS ".Loader" diff --git a/src/coreclr/src/vm/object.h b/src/coreclr/src/vm/object.h index ba51875..48765cc 100644 --- a/src/coreclr/src/vm/object.h +++ b/src/coreclr/src/vm/object.h @@ -1755,21 +1755,6 @@ public: //----------------------------------------------------------- // Release all the data associated with the __ComObject. static void ReleaseAllData(OBJECTREF oref); - - //----------------------------------------------------------- - // Redirection for ToString - static FCDECL1(MethodDesc *, GetRedirectedToStringMD, Object *pThisUNSAFE); - static FCDECL2(StringObject *, RedirectToString, Object *pThisUNSAFE, MethodDesc *pToStringMD); - - //----------------------------------------------------------- - // Redirection for GetHashCode - static FCDECL1(MethodDesc *, GetRedirectedGetHashCodeMD, Object *pThisUNSAFE); - static FCDECL2(int, RedirectGetHashCode, Object *pThisUNSAFE, MethodDesc *pGetHashCodeMD); - - //----------------------------------------------------------- - // Redirection for Equals - static FCDECL1(MethodDesc *, GetRedirectedEqualsMD, Object *pThisUNSAFE); - static FCDECL3(FC_BOOL_RET, RedirectEquals, Object *pThisUNSAFE, Object *pOtherUNSAFE, MethodDesc *pEqualsMD); }; #ifdef USE_CHECKED_OBJECTREFS diff --git a/src/coreclr/src/vm/olevariant.h b/src/coreclr/src/vm/olevariant.h index a09616d..9fe3de8 100644 --- a/src/coreclr/src/vm/olevariant.h +++ b/src/coreclr/src/vm/olevariant.h @@ -18,7 +18,6 @@ // the COM interop marshaler. #define VTHACK_INSPECTABLE 247 #define VTHACK_HSTRING 248 -#define VTHACK_REDIRECTEDTYPE 249 #define VTHACK_CBOOL 250 #define VTHACK_NONBLITTABLERECORD 251 #define VTHACK_BLITTABLERECORD 252 diff --git a/src/coreclr/src/vm/pefile.cpp b/src/coreclr/src/vm/pefile.cpp index ae9c966..eec038f 100644 --- a/src/coreclr/src/vm/pefile.cpp +++ b/src/coreclr/src/vm/pefile.cpp @@ -1513,9 +1513,7 @@ void PEFile::GetEmbeddedResource(DWORD dwOffset, DWORD *cbResource, PBYTE *pbInM PEAssembly * PEFile::LoadAssembly( mdAssemblyRef kAssemblyRef, - IMDInternalImport * pImport, // = NULL - LPCUTF8 szWinRtTypeNamespace, // = NULL - LPCUTF8 szWinRtTypeClassName) // = NULL + IMDInternalImport * pImport) { CONTRACT(PEAssembly *) { @@ -1541,8 +1539,6 @@ PEFile::LoadAssembly( AssemblySpec spec; spec.InitializeSpec(kAssemblyRef, pImport, GetAppDomain()->FindAssembly(GetAssembly())); - if (szWinRtTypeClassName != NULL) - spec.SetWindowsRuntimeType(szWinRtTypeNamespace, szWinRtTypeClassName); RETURN GetAppDomain()->BindAssemblySpec(&spec, TRUE); } @@ -2481,14 +2477,6 @@ AssemblyLoadContext* PEFile::GetAssemblyLoadContext() IfFailThrow(pBindingContext->GetBinderID(&assemblyBinderID)); pOpaqueBinder = reinterpret_cast(assemblyBinderID); - -#ifdef FEATURE_COMINTEROP - // Treat WinRT assemblies (bound using the WinRT binder) as if they were loaded into the TPA ALC - if (AreSameBinderInstance(AppDomain::GetCurrentDomain()->GetWinRtBinder(), pOpaqueBinder)) - { - pOpaqueBinder = NULL; - } -#endif } return (pOpaqueBinder != NULL) ? (AssemblyLoadContext*)pOpaqueBinder : AppDomain::GetCurrentDomain()->GetTPABinderContext(); diff --git a/src/coreclr/src/vm/pefile.h b/src/coreclr/src/vm/pefile.h index a417c4b..c3282c4 100644 --- a/src/coreclr/src/vm/pefile.h +++ b/src/coreclr/src/vm/pefile.h @@ -195,7 +195,6 @@ public: CHECK CheckLoaded(BOOL allowNativeSkip = TRUE); void ValidateForExecution(); BOOL IsMarkedAsNoPlatform(); - BOOL IsMarkedAsContentTypeWindowsRuntime(); // ------------------------------------------------------------ @@ -381,9 +380,7 @@ public: PEAssembly * LoadAssembly( mdAssemblyRef kAssemblyRef, - IMDInternalImport * pImport = NULL, - LPCUTF8 szWinRtTypeNamespace = NULL, - LPCUTF8 szWinRtTypeClassName = NULL); + IMDInternalImport * pImport = NULL); // ------------------------------------------------------------ // Logging @@ -720,20 +717,11 @@ class PEAssembly : public PEFile PTR_PEFile GetCreator() { LIMITED_METHOD_CONTRACT; return m_creator; } - // Returns TRUE if the assembly is .winmd file (WinRT assembly) - bool IsWindowsRuntime(); - - // Used to determine if this assembly has an identity that may be used for - // binding purposes. Currently this is true for standard .NET assemblies - // and false for WinRT assemblies (where assemblies are identified by their - // member types). - bool HasBindableIdentity(); - // Indicates if the assembly can be cached in a binding cache such as AssemblySpecBindingCache. inline bool CanUseWithBindingCache() { STATIC_CONTRACT_WRAPPER; - return (HasBindableIdentity()); + return true; } }; diff --git a/src/coreclr/src/vm/pefile.inl b/src/coreclr/src/vm/pefile.inl index 6a6613b..b3de060 100644 --- a/src/coreclr/src/vm/pefile.inl +++ b/src/coreclr/src/vm/pefile.inl @@ -137,14 +137,7 @@ inline void PEFile::ValidateForExecution() { if (IsMarkedAsNoPlatform()) { - if (IsMarkedAsContentTypeWindowsRuntime()) - { - ThrowHR(COR_E_LOADING_WINMD_REFERENCE_ASSEMBLY); - } - else - { - ThrowHR(COR_E_BADIMAGEFORMAT); - } + ThrowHR(COR_E_BADIMAGEFORMAT); } } } @@ -156,12 +149,6 @@ inline BOOL PEFile::IsMarkedAsNoPlatform() return (IsAfPA_NoPlatform(GetFlags())); } -inline BOOL PEFile::IsMarkedAsContentTypeWindowsRuntime() -{ - WRAPPER_NO_CONTRACT; - return (IsAfContentType_WindowsRuntime(GetFlags())); -} - inline void PEFile::GetMVID(GUID *pMvid) { @@ -1445,34 +1432,4 @@ inline PEFile* PEFile::Dummy() { return (PEFile*)(-1); } - -inline bool PEAssembly::HasBindableIdentity() -{ - CONTRACTL - { - INSTANCE_CHECK; - if (FORBIDGC_LOADER_USE_ENABLED()) NOTHROW; else THROWS; - if (FORBIDGC_LOADER_USE_ENABLED()) GC_NOTRIGGER; else GC_TRIGGERS; - if (FORBIDGC_LOADER_USE_ENABLED()) FORBID_FAULT; else { INJECT_FAULT(COMPlusThrowOM()); } - MODE_ANY; - SUPPORTS_DAC; - } - CONTRACTL_END - - return !IsAfContentType_WindowsRuntime(GetFlags()); -} - -inline bool PEAssembly::IsWindowsRuntime() -{ - CONTRACTL - { - THROWS; - GC_TRIGGERS; - MODE_ANY; - } - CONTRACTL_END; - - return IsAfContentType_WindowsRuntime(GetFlags()); -} - #endif // PEFILE_INL_ diff --git a/src/coreclr/src/vm/prestub.cpp b/src/coreclr/src/vm/prestub.cpp index c32ca11..9261025 100644 --- a/src/coreclr/src/vm/prestub.cpp +++ b/src/coreclr/src/vm/prestub.cpp @@ -625,16 +625,6 @@ COR_ILMETHOD_DECODER* MethodDesc::GetAndVerifyMetadataILHeader(PrepareCodeConfig COR_ILMETHOD* ilHeader = pConfig->GetILHeader(); if (ilHeader == NULL) { -#ifdef FEATURE_COMINTEROP - // Abstract methods can be called through WinRT derivation if the deriving type - // is not implemented in managed code, and calls through the CCW to the abstract - // method. Throw a sensible exception in that case. - if (GetMethodTable()->IsExportedToWinRT() && IsAbstract()) - { - COMPlusThrowHR(E_NOTIMPL); - } -#endif // FEATURE_COMINTEROP - COMPlusThrowHR(COR_E_BADIMAGEFORMAT, BFA_BAD_IL); } @@ -1690,9 +1680,9 @@ Stub * MakeUnboxingStubWorker(MethodDesc *pMD) CPUSTUBLINKER sl; _ASSERTE(pUnboxedMD != NULL && pUnboxedMD != pMD); - // The shuffle for an unboxing stub of a method that doesn't capture the + // The shuffle for an unboxing stub of a method that doesn't capture the // type of the this pointer must be a no-op - _ASSERTE(pUnboxedMD->RequiresInstMethodTableArg() || (portableShuffle.GetCount() == 1)); + _ASSERTE(pUnboxedMD->RequiresInstMethodTableArg() || (portableShuffle.GetCount() == 1)); sl.EmitComputedInstantiatingMethodStub(pUnboxedMD, &portableShuffle[0], NULL); @@ -2171,7 +2161,7 @@ PCODE MethodDesc::DoPrestub(MethodTable *pDispatchingMT, CallerGCMode callerGCMo { if (GetModule()->IsReadyToRun() && GetModule()->GetReadyToRunInfo()->HasNonShareablePInvokeStubs() && MayUsePrecompiledILStub()) { - // In crossgen2, we compile non-shareable IL stubs for pinvokes. If we can find code for such + // In crossgen2, we compile non-shareable IL stubs for pinvokes. If we can find code for such // a stub, we'll use it directly instead and avoid emitting an IL stub. PrepareCodeConfig config(NativeCodeVersion(this), TRUE, TRUE); pCode = GetPrecompiledR2RCode(&config); @@ -2565,13 +2555,6 @@ EXTERN_C PCODE STDCALL ExternalMethodFixupWorker(TransitionBlock * pTransitionBl // We do not emit activation fixups for version resilient references. Activate the target explicitly. pMD->EnsureActive(); } - else - { -#ifdef FEATURE_WINMD_RESILIENT - // We do not emit activation fixups for version resilient references. Activate the target explicitly. - pMD->EnsureActive(); -#endif - } break; } diff --git a/src/coreclr/src/vm/proftoeeinterfaceimpl.cpp b/src/coreclr/src/vm/proftoeeinterfaceimpl.cpp index 6f83565..729d7b8 100644 --- a/src/coreclr/src/vm/proftoeeinterfaceimpl.cpp +++ b/src/coreclr/src/vm/proftoeeinterfaceimpl.cpp @@ -3917,7 +3917,7 @@ DWORD ProfToEEInterfaceImpl::GetModuleFlags(Module * pModule) { NOTHROW; GC_NOTRIGGER; - CAN_TAKE_LOCK; // IsWindowsRuntimeModule accesses metadata directly, which takes locks + CANNOT_TAKE_LOCK; MODE_ANY; } CONTRACTL_END; @@ -3983,11 +3983,6 @@ DWORD ProfToEEInterfaceImpl::GetModuleFlags(Module * pModule) dwRet |= COR_PRF_MODULE_RESOURCE; } - if (pModule->IsWindowsRuntimeModule()) - { - dwRet |= COR_PRF_MODULE_WINDOWS_RUNTIME; - } - return dwRet; } @@ -4639,8 +4634,7 @@ HRESULT ProfToEEInterfaceImpl::ForceGC() #ifdef FEATURE_EVENT_TRACE // This helper, used by ETW and profAPI ensures a managed thread gets created for - // this thread before forcing the GC (to work around Jupiter issues where it's - // expected this thread is already managed before starting the GC). + // this thread before forcing the GC. HRESULT hr = ETW::GCLog::ForceGCForDiagnostics(); #else // !FEATURE_EVENT_TRACE HRESULT hr = E_FAIL; diff --git a/src/coreclr/src/vm/rcwrefcache.cpp b/src/coreclr/src/vm/rcwrefcache.cpp index c22a84e..0451e85 100644 --- a/src/coreclr/src/vm/rcwrefcache.cpp +++ b/src/coreclr/src/vm/rcwrefcache.cpp @@ -191,28 +191,6 @@ void RCWRefCache::ShrinkDependentHandles() } // -// Add a reference from RCW to CCW -// -HRESULT RCWRefCache::AddReferenceFromRCWToCCW(RCW *pRCW, ComCallWrapper *pCCW) -{ - CONTRACTL - { - NOTHROW; - GC_NOTRIGGER; - MODE_COOPERATIVE; - PRECONDITION(CheckPointer(pRCW)); - PRECONDITION(CheckPointer(pCCW)); - PRECONDITION(CheckPointer(OBJECTREFToObject(pCCW->GetObjectRef()))); - PRECONDITION(pRCW->IsJupiterObject()); - PRECONDITION(pCCW->GetJupiterRefCount() > 0); - } - CONTRACTL_END; - - // Try adding reference using dependent handles - return AddReferenceUsingDependentHandle(pRCW->GetExposedObject(), pCCW->GetObjectRef()); -} - -// // Add a reference from obj1 to obj2 // HRESULT RCWRefCache::AddReferenceFromObjectToObject(OBJECTREF obj1, OBJECTREF obj2) diff --git a/src/coreclr/src/vm/rcwrefcache.h b/src/coreclr/src/vm/rcwrefcache.h index 4e9aa20..e59fb9a 100644 --- a/src/coreclr/src/vm/rcwrefcache.h +++ b/src/coreclr/src/vm/rcwrefcache.h @@ -18,7 +18,7 @@ #ifndef _H_RCWREFCACHE_ #define _H_RCWREFCACHE_ -#ifdef FEATURE_COMINTEROP +#ifdef FEATURE_COMWRAPPERS class RCWRefCache { @@ -27,57 +27,11 @@ public : ~RCWRefCache(); // - // Add a reference from RCW to CCW - // - HRESULT AddReferenceFromRCWToCCW(RCW *pRCW, ComCallWrapper *pCCW); - - // // Add a reference from obj1 to obj2 // HRESULT AddReferenceFromObjectToObject(OBJECTREF obj1, OBJECTREF obj2); // - // Enumerate all Jupiter RCWs in the RCW cache and do the callback - // I'm using template here so there is no perf penality - // - template HRESULT EnumerateAllJupiterRCWs(Function fn, T userData) - { - CONTRACTL - { - NOTHROW; - GC_NOTRIGGER; - MODE_COOPERATIVE; - } - CONTRACTL_END; - - HRESULT hr; - - // Go through the RCW cache and call the callback for all Jupiter objects - RCWCache *pRCWCache = m_pAppDomain->GetRCWCacheNoCreate(); - if (pRCWCache != NULL) - { - SHash *pHashMap = &pRCWCache->m_HashMap; - - for (SHash::Iterator it = pHashMap->Begin(); it != pHashMap->End(); it++) - { - RCW *pRCW = *it; - _ASSERTE(pRCW != NULL); - - if (pRCW->IsJupiterObject()) - { - hr = fn(pRCW, userData); - if (FAILED(hr)) - { - return hr; - } - } - } - } - - return S_OK; - } - - // // Reset dependent handle cache by assigning 0 to m_dwDepHndListFreeIndex. // void ResetDependentHandles(); @@ -103,6 +57,6 @@ private : DWORD m_dwShrinkHint; // Keep track of how many times we use less than half handles }; -#endif // FEATURE_COMINTEROP +#endif // FEATURE_COMWRAPPERS #endif // _H_RCWREFCACHE_ diff --git a/src/coreclr/src/vm/rcwwalker.cpp b/src/coreclr/src/vm/rcwwalker.cpp deleted file mode 100644 index 8c8e5f0..0000000 --- a/src/coreclr/src/vm/rcwwalker.cpp +++ /dev/null @@ -1,952 +0,0 @@ -// 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. -// - -// - -/*============================================================ -** -** Class: RCWWalker -** -** -** Purpose: The implementation of RCWWalker class which walks -** RCW objects -===========================================================*/ - -#include "common.h" - -#include "runtimecallablewrapper.h" -#include "comcallablewrapper.h" -#include "rcwwalker.h" -#include "olecontexthelpers.h" -#include "rcwrefcache.h" -#include "cominterfacemarshaler.h" -#include "excep.h" -#include "finalizerthread.h" -#include "interoputil.inl" - -const IID IID_ICLRServices = __uuidof(ICLRServices); - -const IID IID_ICCW = __uuidof(ICCW); - -const IID IID_IJupiterObject = __uuidof(IJupiterObject); - -const IID IID_IJupiterGCManager = __uuidof(IJupiterGCManager); - -const IID IID_IFindDependentWrappersCallback = __uuidof(IFindDependentWrappersCallback); - -VolatilePtr RCWWalker::s_pGCManager = NULL; // Global GC manager pointer -BOOL RCWWalker::s_bGCStarted = FALSE; // Has GC started? -SVAL_IMPL_INIT(BOOL, RCWWalker, s_bIsGlobalPeggingOn, TRUE); // Do we need to peg every jupiter CCW? - -#ifndef DACCESS_COMPILE - -// Our implementation of ICLRServices provided to Jupiter via IJupiterGCManager::SetReferenceTrackerHost. -class CLRServicesImpl : public IUnknownCommon -{ -private: - // flags for DisconnectUnusedReferenceSources(DWORD dwFlags) - enum { - GC_FOR_APPX_SUSPEND = 0x00000001 - }; -public: - STDMETHOD(DisconnectUnusedReferenceSources)(DWORD dwFlags); - STDMETHOD(ReleaseDisconnectedReferenceSources)(); - STDMETHOD(NotifyEndOfReferenceTrackingOnThread)(); - STDMETHOD(GetTrackerTarget)(IUnknown *pJupiterObject, ICCW **ppNewReference); - STDMETHOD(AddMemoryPressure)(UINT64 bytesAllocated); - STDMETHOD(RemoveMemoryPressure)(UINT64 bytesAllocated); -}; - -#pragma warning(push) -#pragma warning(disable : 4702) // Disable unreachable code warning for RCWWalker_UnhandledExceptionFilter - -// -// We never expect exceptions to be thrown outside of RCWWalker -// So make sure we fail fast here, instead of going through normal -// exception processing and fail later -// This will make analyzing dumps much easier -// -inline LONG RCWWalker_UnhandledExceptionFilter(EXCEPTION_POINTERS* pExceptionPointers, PVOID pv) -{ - WRAPPER_NO_CONTRACT; - - if ((pExceptionPointers->ExceptionRecord->ExceptionCode == STATUS_BREAKPOINT) || - (pExceptionPointers->ExceptionRecord->ExceptionCode == STATUS_SINGLE_STEP)) - { - // We don't want to fail fast on debugger exceptions - return EXCEPTION_CONTINUE_SEARCH; - } - - // Exceptions here are considered fatal - just fail fast - EEPolicy::HandleFatalError(COR_E_EXECUTIONENGINE, (UINT_PTR)GetIP(pExceptionPointers->ContextRecord), NULL, pExceptionPointers); - - // We may trigger C4702 warning as we'll never reach here - // I've temporarily disabled the warning. See #pragma above - UNREACHABLE(); - - return EXCEPTION_EXECUTE_HANDLER; -} - -#pragma warning(pop) - -// -// Release context-bound RCWs and Jupiter RCWs (which are free-threaded but context-bound) -// in the current apartment -// -STDMETHODIMP CLRServicesImpl::NotifyEndOfReferenceTrackingOnThread() -{ - CONTRACTL - { - NOTHROW; - GC_TRIGGERS; - MODE_PREEMPTIVE; - } - CONTRACTL_END; - - HRESULT hr = S_OK; - BEGIN_EXTERNAL_ENTRYPOINT(&hr) - { - ReleaseRCWsInCaches(GetCurrentCtxCookie()); - } - END_EXTERNAL_ENTRYPOINT; - return hr; -} - -STDMETHODIMP CLRServicesImpl::DisconnectUnusedReferenceSources(DWORD dwFlags) -{ - CONTRACTL - { - NOTHROW; - GC_TRIGGERS; - MODE_PREEMPTIVE; - } - CONTRACTL_END; - - HRESULT hr = S_OK; - BEGIN_EXTERNAL_ENTRYPOINT(&hr) - { - GCX_COOP_THREAD_EXISTS(GET_THREAD()); - if (dwFlags & GC_FOR_APPX_SUSPEND) { - GCHeapUtilities::GetGCHeap()->GarbageCollect(2, true, collection_blocking | collection_optimized); - } - else - GCHeapUtilities::GetGCHeap()->GarbageCollect(); - } - END_EXTERNAL_ENTRYPOINT; - return hr; -} - -STDMETHODIMP CLRServicesImpl::AddMemoryPressure(UINT64 bytesAllocated) -{ - CONTRACTL - { - THROWS; - GC_TRIGGERS; - MODE_ANY; - } - CONTRACTL_END; - HRESULT hr = S_OK; - BEGIN_EXTERNAL_ENTRYPOINT(&hr) - { - GCInterface::AddMemoryPressure(bytesAllocated); - } - END_EXTERNAL_ENTRYPOINT; - return hr; -} - -STDMETHODIMP CLRServicesImpl::RemoveMemoryPressure(UINT64 bytesAllocated) -{ - CONTRACTL - { - THROWS; - GC_TRIGGERS; - MODE_ANY; - } - CONTRACTL_END; - HRESULT hr = S_OK; - BEGIN_EXTERNAL_ENTRYPOINT(&hr) - { - GCInterface::RemoveMemoryPressure(bytesAllocated); - } - END_EXTERNAL_ENTRYPOINT; - return hr; -} - - -STDMETHODIMP CLRServicesImpl::ReleaseDisconnectedReferenceSources() -{ - CONTRACTL - { - NOTHROW; - GC_TRIGGERS; - MODE_PREEMPTIVE; - } - CONTRACTL_END; - - HRESULT hr = S_OK; - BEGIN_EXTERNAL_ENTRYPOINT(&hr) - { - FinalizerThread::FinalizerThreadWait(); - } - END_EXTERNAL_ENTRYPOINT; - return hr; -} - -// -// Creates a proxy object that points to the given RCW -// The proxy -// 1. Has a managed reference pointing to the RCW, and therefore forms a cycle that can be resolved by GC -// 2. Forwards data binding requests -// For example: -// -// Grid <---- RCW Grid <------RCW -// | ^ | ^ -// | | Becomes | | -// v | v | -// Rectangle Rectangle ----->Proxy -// -// Arguments -// pTarget - The identity IUnknown* where a RCW points to (Grid, in this case) -// Note that -// 1) we can either create a new RCW or get back an old one from cache -// 2) This pTarget could be a regular WinRT object (such as WinRT collection) for data binding -// ppNewReference - The ICCW* for the proxy created -// Jupiter will call ICCW to establish a jupiter reference -// -STDMETHODIMP CLRServicesImpl::GetTrackerTarget(IUnknown *pTarget, ICCW **ppNewReference) -{ - CONTRACTL - { - NOTHROW; - GC_TRIGGERS; - MODE_PREEMPTIVE; - PRECONDITION(CheckPointer(pTarget)); - PRECONDITION(CheckPointer(ppNewReference)); - } - CONTRACTL_END; - - HRESULT hr = S_OK; - BEGIN_EXTERNAL_ENTRYPOINT(&hr) - { - // - // QI for IUnknown to get the identity unknown - // - SafeComHolderPreemp pIdentity; - IfFailThrow(SafeQueryInterfacePreemp(pTarget, IID_IUnknown, &pIdentity)); - - // - // Get RCW for pJupiterObject - // - COMInterfaceMarshaler marshaler; - marshaler.Init( - pIdentity, - g_pBaseCOMObject, - GET_THREAD(), - RCW::CF_SupportsIInspectable // Returns a WinRT RCW - ); - - // - // Then create a proxy based on the RCW - // - { - GCX_COOP(); - - struct _gc { - OBJECTREF TargetObj; - OBJECTREF RetVal; - } gc; - ZeroMemory(&gc, sizeof(gc)); - - GCPROTECT_BEGIN(gc); - - gc.TargetObj = marshaler.FindOrCreateObjectRef(&pTarget); - - // - // Figure out the right IVector/IVectorView - // - MethodTable *pMT = gc.TargetObj->GetMethodTable(); - - TypeHandle thArgs[2]; - - // - // This RCW could be strongly typed - figure out T1/T2 using metadata - // - MethodTable::InterfaceMapIterator it = pMT->IterateInterfaceMap(); - while (it.Next()) - { - MethodTable *pItfMT = it.GetInterface(); - if (thArgs[0].IsNull() && pItfMT->HasSameTypeDefAs(MscorlibBinder::GetClass(CLASS__ILISTGENERIC))) - { - thArgs[0] = pItfMT->GetInstantiation()[0]; - - // Are we done? - if (!thArgs[1].IsNull()) - break; - } - - if (thArgs[1].IsNull() && pItfMT->HasSameTypeDefAs(MscorlibBinder::GetClass(CLASS__IREADONLYLISTGENERIC))) - { - thArgs[1] = pItfMT->GetInstantiation()[0]; - - // Are we done? - if (!thArgs[0].IsNull()) - break; - } - } - - if (thArgs[0].IsNull() || thArgs[1].IsNull()) - { - // - // Try the RCW cache if didn't find match for both types and this is a RCW - // - if (pMT->IsComObjectType()) - { - RCWHolder pRCW(GET_THREAD()); - pRCW.Init(gc.TargetObj); - - RCW::CachedInterfaceEntryIterator it = pRCW->IterateCachedInterfacePointers(); - while (it.Next()) - { - MethodTable *pItfMT = (MethodTable *)it.GetEntry()->m_pMT; - - // Unfortunately the iterator could return NULL entry - if (pItfMT == NULL) continue; - - if (thArgs[0].IsNull() && pItfMT->HasSameTypeDefAs(MscorlibBinder::GetClass(CLASS__ILISTGENERIC))) - { - thArgs[0] = pItfMT->GetInstantiation()[0]; - - // Are we done? - if (!thArgs[1].IsNull()) - break; - } - - if (thArgs[1].IsNull() && pItfMT->HasSameTypeDefAs(MscorlibBinder::GetClass(CLASS__IREADONLYLISTGENERIC))) - { - thArgs[1] = pItfMT->GetInstantiation()[0]; - - // Are we done? - if (!thArgs[0].IsNull()) - break; - } - } - } - } - - // - // If not found, use object (IInspectable*) as the last resort - // - if (thArgs[0].IsNull()) - thArgs[0] = TypeHandle(g_pObjectClass); - if (thArgs[1].IsNull()) - thArgs[1] = TypeHandle(g_pObjectClass); - - // - // Instantiate ICustomPropertyProviderProxy.CreateInstance - // - TypeHandle thCustomPropertyProviderProxy = TypeHandle(MscorlibBinder::GetClass(CLASS__ICUSTOMPROPERTYPROVIDERPROXY)); - - MethodTable *pthCustomPropertyProviderProxyExactMT = thCustomPropertyProviderProxy.Instantiate(Instantiation(thArgs, 2)).GetMethodTable(); - - MethodDesc *pCreateInstanceMD = MethodDesc::FindOrCreateAssociatedMethodDesc( - MscorlibBinder::GetMethod(METHOD__ICUSTOMPROPERTYPROVIDERPROXY__CREATE_INSTANCE), - pthCustomPropertyProviderProxyExactMT, - FALSE, - Instantiation(), - FALSE); - - // - // Call ICustomPropertyProviderProxy.CreateInstance - // - PREPARE_NONVIRTUAL_CALLSITE_USING_METHODDESC(pCreateInstanceMD); - DECLARE_ARGHOLDER_ARRAY(args, 1); - args[ARGNUM_0] = OBJECTREF_TO_ARGHOLDER(gc.TargetObj); - - CALL_MANAGED_METHOD_RETREF(gc.RetVal, OBJECTREF, args); - - CCWHolder pCCWHold = ComCallWrapper::InlineGetWrapper(&gc.RetVal); - *ppNewReference = (ICCW *)ComCallWrapper::GetComIPFromCCW(pCCWHold, IID_ICCW, /* pIntfMT = */ NULL); - GCPROTECT_END(); - } - } - END_EXTERNAL_ENTRYPOINT; - return hr; -} - -// -// Called when Jupiter RCW is being created -// We do one-time initialization for RCWWalker related stuff here -// This could throw -// -void RCWWalker::OnJupiterRCWCreated(RCW *pRCW, IJupiterObject *pJupiterObject) -{ - CONTRACTL - { - THROWS; - GC_TRIGGERS; - MODE_PREEMPTIVE; - PRECONDITION(CheckPointer(pRCW)); - PRECONDITION(CheckPointer(pJupiterObject)); - } - CONTRACTL_END; - - LOG((LF_INTEROP, LL_INFO100, "[RCW Walker] ----- RCWWalker::OnJupiterRCWCreated (RCW = 0x%p) BEGINS -----\n", pRCW)); - - // - // Retrieve IJupiterGCManager - // - if (!s_pGCManager) - { - SafeComHolderPreemp pGCManager; - HRESULT hr = pJupiterObject->GetReferenceTrackerManager(&pGCManager); - if (SUCCEEDED(hr)) - { - if (pGCManager == NULL) - { - LOG((LF_INTEROP, LL_INFO100, "\t[RCW Walker] ERROR: Failed to Retrieve IGCManager, IGCManager = NULL\n")); - COMPlusThrowHR(E_POINTER); - } - - // - // Perform all operation that could fail here - // - NewHolder pCLRServicesImpl = new CLRServicesImpl(); - ReleaseHolder pCLRServices; - IfFailThrow(pCLRServicesImpl->QueryInterface(IID_ICLRServices, (void **)&pCLRServices)); - - // Temporarily switch back to coop and disable GC to avoid racing with the very first RCW walk - GCX_COOP(); - GCX_FORBID(); - - if (FastInterlockCompareExchangePointer((IJupiterGCManager **)&s_pGCManager, (IJupiterGCManager *)pGCManager, NULL) == NULL) - { - // - // OK. It is time to do our RCWWalker initialization - // It's safe to do it here because we are in COOP and only one thread wins the race - // - LOG((LF_INTEROP, LL_INFO100, "\t[RCW Walker] Assigning RCWWalker::s_pIGCManager = 0x%p\n", (void *)pGCManager)); - - pGCManager.SuppressRelease(); - pCLRServicesImpl.SuppressRelease(); - pCLRServices.SuppressRelease(); - - LOG((LF_INTEROP, LL_INFO100, "\t[RCW Walker] Calling IGCManager::SetReferenceTrackerHost(0x%p)\n", (void *)pCLRServices)); - pGCManager->SetReferenceTrackerHost(pCLRServices); - } - } - else - { - LOG((LF_INTEROP, LL_INFO100, "\t[RCW Walker] ERROR: Failed to Retrieve IGCManager, hr = 0x%x\n", hr)); - COMPlusThrowHR(hr); - } - } - - LOG((LF_INTEROP, LL_INFO100, "[RCW Walker] ----- RCWWalker::OnJupiterRCWCreated (RCW = 0x%p) ENDS ----- \n", pRCW)); -} - -// -// Called after Jupiter RCW has been created -// This should never throw -// -void RCWWalker::AfterJupiterRCWCreated(RCW *pRCW) -{ - CONTRACTL - { - NOTHROW; - GC_NOTRIGGER; - MODE_COOPERATIVE; - PRECONDITION(CheckPointer(pRCW)); - PRECONDITION(pRCW->IsJupiterObject()); - } - CONTRACTL_END; - - LOG((LF_INTEROP, LL_INFO100, "[RCW Walker] ----- RCWWalker::AfterJupiterRCWCreated (RCW = 0x%p) BEGINS ----- \n", pRCW)); - - IJupiterObject *pJupiterObject = pRCW->GetJupiterObject(); - - // - // Notify Jupiter that we've created a new RCW for this Jupiter object - // To avoid surprises, we should notify them before we fire the first AddRefFromTrackerSource - // - STRESS_LOG2(LF_INTEROP, LL_INFO100, "[RCW Walker] Calling IJupiterObject::ConnectFromTrackerSource (IJupiterObject = 0x%p, RCW = 0x%p)\n", pJupiterObject, pRCW); - pJupiterObject->ConnectFromTrackerSource(); - - // - // Send out AddRefFromTrackerSource callbacks to notify Jupiter we've done AddRef for certain interfaces - // We should do this *after* we made a AddRef because we should never - // be in a state where report refs > actual refs - // - - // Send out AddRefFromTrackerSource for cached IUnknown - RCWWalker::AfterInterfaceAddRef(pRCW); - - if (!pRCW->IsURTAggregated()) - { - // Send out AddRefFromTrackerSource for cached IJupiterObject - RCWWalker::AfterInterfaceAddRef(pRCW); - } - - LOG((LF_INTEROP, LL_INFO100, "[RCW Walker] ----- RCWWalker::AfterJupiterRCWCreated (RCW = 0x%p) ENDS ----- \n", pRCW)); -} - -// -// Called before Jupiter RCW is about to be destroyed (the same lifetime as short weak handle) -// -void RCWWalker::BeforeJupiterRCWDestroyed(RCW *pRCW) -{ - CONTRACTL - { - NOTHROW; - GC_NOTRIGGER; - MODE_ANY; - PRECONDITION(CheckPointer(pRCW)); - PRECONDITION(pRCW->IsJupiterObject()); - } - CONTRACTL_END; - - LOG((LF_INTEROP, LL_INFO100, "[RCW Walker] ----- RCWWalker::BeforeJupiterRCWDestroyed (RCW = 0x%p) BEGINS ----- \n", pRCW)); - - IJupiterObject *pJupiterObject = pRCW->GetJupiterObject(); - _ASSERTE(pJupiterObject != NULL); - - // - // Notify Jupiter that we are about to destroy a RCW (same timing as short weak handle) - // for this Jupiter object. - // They need this information to disconnect weak refs and stop firing events, - // so that they can avoid resurrecting the Jupiter object (not the RCW - we prevent that) - // We only call this inside GC, so don't need to switch to preemptive here - // Ignore the failure as there is no way we can handle that failure during GC - // - STRESS_LOG2(LF_INTEROP, LL_INFO100, "[RCW Walker] Calling IJupiterObject::DisconnectFromTrackerSource (IJupiterObject = 0x%p, RCW = 0x%p)\n", pJupiterObject, pRCW); - pJupiterObject->DisconnectFromTrackerSource(); - - LOG((LF_INTEROP, LL_INFO100, "[RCW Walker] ----- RCWWalker::BeforeJupiterRCWDestroyed (RCW = 0x%p) ENDS ----- \n", pRCW)); -} - -// -// Walk all the jupiter RCWs in all AppDomains and build references from RCW -> CCW as we go -// -void RCWWalker::WalkRCWs() -{ - CONTRACTL { - NOTHROW; - GC_NOTRIGGER; - MODE_COOPERATIVE; - } - CONTRACTL_END; - - BOOL bWalkFailed = FALSE; - - HRESULT hr = S_OK; - EX_TRY - { - { - AppDomain *pDomain = ::GetAppDomain(); // There is only actually 1 AppDomain in CoreCLR, so no iterator - - RCWRefCache *pRCWRefCache = pDomain->GetRCWRefCache(); - _ASSERTE(pRCWRefCache != NULL); - - STRESS_LOG2(LF_INTEROP, LL_INFO100, "[RCW Walker] Walking all Jupiter RCWs in AppDomain 0x%p, RCWRefCache 0x%p\n", pDomain, pRCWRefCache); - - // - // Reset the cache - // - pRCWRefCache->ResetDependentHandles(); - - // - // Enumerate all Jupiter RCWs in that AppDomain - // - hr = pRCWRefCache->EnumerateAllJupiterRCWs(RCWWalker::WalkOneRCW, pRCWRefCache); - - // - // Shrink the dependent handle cache if necessary and clear unused handles. - // - pRCWRefCache->ShrinkDependentHandles(); - } - } - EX_CATCH - { - hr = GET_EXCEPTION()->GetHR(); - } - EX_END_CATCH(RethrowTerminalExceptions) - - if (FAILED(hr)) - { - // Remember the fact that we've failed and stop walking - STRESS_LOG1(LF_INTEROP, LL_INFO100, "[RCW Walker] RCW walk failed, hr = 0x%p\n", hr); - bWalkFailed = TRUE; - - STRESS_LOG0(LF_INTEROP, LL_INFO100, "[RCW Walker] Turning on global pegging flag as fail-safe\n"); - VolatileStore(&s_bIsGlobalPeggingOn, TRUE); - } - - // - // Let Jupiter know RCW walk is done and they need to: - // 1. Unpeg all CCWs if the CCW needs to be unpegged (when the CCW is only reachable by other jupiter RCWs) - // 2. Peg all CCWs if the CCW needs to be pegged (when the above condition is not true) - // 3. Unlock reference cache when they are done - // - // If the walk has failed - Jupiter doesn't need to do anything and could just return immediately - // - // Note: IGCManager should be free-threaded as it will be called on arbitary threads - // - LOG((LF_INTEROP, LL_INFO100, "[RCW Walker] Calling IGCManager::FindTrackerTargetsCompleted on 0x%p, bWalkFailed = %d\n", s_pGCManager, bWalkFailed)); - _ASSERTE(s_pGCManager); - s_pGCManager->FindTrackerTargetsCompleted(bWalkFailed); - - STRESS_LOG0 (LF_INTEROP, LL_INFO100, "[RCW Walker] RCW Walk finished\n"); -} - -// -// Callback implementation of IFindDependentWrappersCallback -// -class CFindDependentWrappersCallback : public IFindDependentWrappersCallback -{ -public : - CFindDependentWrappersCallback(RCW *pRCW, RCWRefCache*pRCWRefCache) - :m_pRCW(pRCW), m_pRCWRefCache(pRCWRefCache) - { -#ifdef _DEBUG - m_hr = S_OK; - m_dwCreatedRefs = 0; -#endif // _DEBUG - } - - STDMETHOD_(ULONG, AddRef)() - { - - // Lifetime maintained by stack - we don't care about ref counts - return 1; - } - - STDMETHOD_(ULONG, Release)() - { - // Lifetime maintained by stack - we don't care about ref counts - return 1; - } - - STDMETHOD(QueryInterface)(REFIID riid, void **ppvObject) - { - if (IsEqualIID(riid, IID_IUnknown) || IsEqualIID(riid, IID_IFindDependentWrappersCallback)) - { - *ppvObject = this; - return S_OK; - } - else - { - *ppvObject = NULL; - return E_NOINTERFACE; - } - } - - - STDMETHOD(FoundTrackerTarget)(ICCW *pUnk) - { -#ifdef _DEBUG - _ASSERTE(SUCCEEDED(m_hr) && W("Should not receive FoundTrackerTarget again if failed")); -#endif // _DEBUG - _ASSERTE(pUnk != NULL); - - ComCallWrapper *pCCW = MapIUnknownToWrapper(pUnk); - _ASSERTE(pCCW != NULL); - - LOG((LF_INTEROP, LL_INFO1000, "\t[RCW Walker] IFindDependentWrappersCallback::FoundTrackerTarget being called: RCW 0x%p, CCW 0x%p\n", m_pRCW, pCCW)); - - // - // Skip dependent handle creation if RCW/CCW points to the same managed object - // - if (m_pRCW->GetSyncBlock() == pCCW->GetSyncBlock()) - return S_OK; - - // - // Jupiter might return CCWs with outstanding references that are either : - // 1. Neutered - in this case it is unsafe to touch m_ppThis - // 2. RefCounted handle NULLed out by GC - // - // Skip those to avoid crashes - // - if (pCCW->GetSimpleWrapper()->IsNeutered() || - pCCW->GetObjectRef() == NULL) - return S_OK; - - // - // Add a reference from pRCW -> pCCW so that GC knows about this reference - // - STRESS_LOG4( - LF_INTEROP, LL_INFO1000, - "\t[RCW Walker] Adding reference: RCW 0x%p (Managed Object = 0x%p) -> CCW 0x%p (Managed Object = 0x%p)\n", - m_pRCW, OBJECTREFToObject(m_pRCW->GetExposedObject()), pCCW, OBJECTREFToObject(pCCW->GetObjectRef()) - ); - - HRESULT hr = m_pRCWRefCache->AddReferenceFromRCWToCCW(m_pRCW, pCCW); - -#ifdef _DEBUG - m_dwCreatedRefs++; -#endif // _DEBUG - - if (FAILED(hr)) - { -#ifdef _DEBUG - m_hr = hr; -#endif // _DEBUG - STRESS_LOG1(LF_INTEROP, LL_INFO1000, "[RCW Walker] Adding reference failed, hr = 0x%x", hr); - - return E_FAIL; - } - - return S_OK; - } - -#ifdef _DEBUG - HRESULT GetHRESULT() - { - - return m_hr; - } - - DWORD GetCreatedRefs() - { - - return m_dwCreatedRefs; - } -#endif // _DEBUG - -private : - RCW *m_pRCW; - RCWRefCache *m_pRCWRefCache; - -#ifdef _DEBUG - HRESULT m_hr; // Holds the last failed HRESULT to make sure our contract with Jupiter is correctly honored - DWORD m_dwCreatedRefs; // Total number of refs created from this RCW -#endif // _DEBUG -}; - -// -// Ask Jupiter all the CCWs referenced (through native code) by this RCW and build reference for RCW -> CCW -// so that GC knows about this reference -// -HRESULT RCWWalker::WalkOneRCW(RCW *pRCW, RCWRefCache *pRCWRefCache) -{ - CONTRACTL { - NOTHROW; - GC_NOTRIGGER; - MODE_COOPERATIVE; - PRECONDITION(CheckPointer(pRCW)); - } - CONTRACTL_END; - - LOG((LF_INTEROP, LL_INFO1000, "\t[RCW Walker] ----- RCWWalker::WalkOneRCW (RCW = 0x%p) BEGINS ----- \n", pRCW)); - - _ASSERTE(pRCW->IsJupiterObject()); - - HRESULT hr = S_OK; - - // Get IJupiterObject * from RCW - we can call IJupiterObject* from any thread and it won't be a proxy - IJupiterObject *pJupiterObject = pRCW->GetJupiterObject(); - _ASSERTE(pJupiterObject); - - _ASSERTE(pRCW->GetExposedObject() != NULL); - - CFindDependentWrappersCallback callback(pRCW, pRCWRefCache); - - STRESS_LOG2 (LF_INTEROP, LL_INFO1000, "\t[RCW Walker] Walking RCW 0x%p (Managed Object = 0x%p)\n", pRCW, OBJECTREFToObject(pRCW->GetExposedObject())); - - LOG((LF_INTEROP, LL_INFO1000, "\t[RCW Walker] Calling IJupiterObject::FindTrackerTargets\n", pRCW)); - hr = pJupiterObject->FindTrackerTargets(&callback); - -#ifdef _DEBUG - if (FAILED(callback.GetHRESULT())) - { - _ASSERTE(callback.GetHRESULT() == hr && W("FindDepedentWrappers should return the failed result from the callback method FoundTrackerTarget")); - } - - LOG((LF_INTEROP, LL_INFO1000, "\t[RCW Walker] Total %d refs created for RCW 0x%p\n", callback.GetCreatedRefs(), pRCW)); -#endif // _DEBUG - - LOG((LF_INTEROP, LL_INFO1000, "\t[RCW Walker] ----- RCWWalker::WalkOneRCW (RCW = 0x%p) ENDS -----\n", pRCW)); - return hr; -} - -typedef void (*OnGCEventProc)(); -inline void SetupFailFastFilterAndCall(OnGCEventProc pGCEventProc) -{ - STATIC_CONTRACT_GC_NOTRIGGER; - STATIC_CONTRACT_NOTHROW; - STATIC_CONTRACT_MODE_ANY; - - // - // Use RCWWalker_UnhandledExceptionFilter to fail fast and early in case any exception is thrown - // See code:RCWWalker_UnhandledExceptionFilter for more details why we need this - // - PAL_TRY_NAKED - { - // Call the internal worker function which has the runtime contracts - pGCEventProc(); - } - PAL_EXCEPT_FILTER_NAKED(RCWWalker_UnhandledExceptionFilter, NULL) - { - _ASSERT(!W("Should not get here")); - } - PAL_ENDTRY_NAKED -} - -// -// Called when GC started -// We do most of our work here -// -// Note that we could get nested GCStart/GCEnd calls, such as : -// GCStart for Gen 2 background GC -// GCStart for Gen 0/1 foregorund GC -// GCEnd for Gen 0/1 foreground GC -// .... -// GCEnd for Gen 2 background GC -// -// The nCondemnedGeneration >= 2 check takes care of this nesting problem -// -void RCWWalker::OnGCStarted(int nCondemnedGeneration) -{ - CONTRACTL { - NOTHROW; - GC_NOTRIGGER; - MODE_ANY; - } - CONTRACTL_END; - - LOG((LF_INTEROP, LL_INFO100, "[RCW Walker] ----- RCWWalker::OnGCStarted (nCondemnedGeneration = %d) BEGINS ----- \n", nCondemnedGeneration)); - - if (RCWWalker::NeedToWalkRCWs()) // Have we seen Jupiter RCWs? - { - if (nCondemnedGeneration >= 2) // We are only doing walk in Gen2 GC - { - // Make sure we fail fast if anything goes wrong when we interact with Jupiter - SetupFailFastFilterAndCall(RCWWalker::OnGCStartedWorker); - } - else - { - LOG((LF_INTEROP, LL_INFO100, "[RCW Walker] GC skipped: Not a Gen2 GC \n")); - } - } - else - { - - LOG((LF_INTEROP, LL_INFO100, "[RCW Walker] GC skipped: No Jupiter RCWs seen \n")); - } - - LOG((LF_INTEROP, LL_INFO100, "[RCW Walker] ----- RCWWalker::OnGCStarted (nCondemnedGeneration = %d) ENDS -----\n", nCondemnedGeneration)); -} - -// -// Called when GC finished -// -// Note that we could get nested GCStart/GCEnd calls, such as : -// GCStart for Gen 2 background GC -// GCStart for Gen 0/1 foregorund GC -// GCEnd for Gen 0/1 foreground GC -// .... -// GCEnd for Gen 2 background GC -// -// The nCondemnedGeneration >= 2 check takes care of this nesting problem -// -void RCWWalker::OnGCFinished(int nCondemnedGeneration) -{ - CONTRACTL { - NOTHROW; - GC_NOTRIGGER; - MODE_ANY; - } - CONTRACTL_END; - - LOG((LF_INTEROP, LL_INFO100, "[RCW Walker] ----- RCWWalker::OnGCFinished(nCondemnedGeneration = %d) BEGINS ----- \n", nCondemnedGeneration)); - - // - // Note that we need to check in both OnGCFinished and OnGCStarted - // As there could be multiple OnGCFinished with nCondemnedGeneration < 2 in the case of Gen 2 GC - // - // Also, if this is background GC, the NeedToWalkRCWs predicate may change from FALSE to TRUE while - // the GC is running. We don't want to do any work if it's the case (i.e. if s_bGCStarted is FALSE). - // - if (RCWWalker::NeedToWalkRCWs() && // Have we seen Jupiter RCWs? - s_bGCStarted && // Had we seen Jupiter RCWs when the GC started? - nCondemnedGeneration >= 2 // We are only doing walk in Gen2 GC - ) - { - // Make sure we fail fast if anything goes wrong when we interact with Jupiter - SetupFailFastFilterAndCall(RCWWalker::OnGCFinishedWorker); - } - - LOG((LF_INTEROP, LL_INFO100, "[RCW Walker] ----- RCWWalker::OnGCFinished(nCondemnedGeneration = %d) ENDS ----- \n", nCondemnedGeneration)); -} - -void RCWWalker::OnGCStartedWorker() -{ - CONTRACTL { - NOTHROW; - GC_NOTRIGGER; - MODE_ANY; - } - CONTRACTL_END; - - STRESS_LOG0 (LF_INTEROP, LL_INFO100, "[RCW Walker] Gen 2 GC Started - Ready to walk Jupiter RCWs\n"); - - // Due to the nesting GCStart/GCEnd pairs (see comment for this function), we need to check - // those flags inside nCondemnedGeneration >= 2 check - _ASSERTE(!s_bGCStarted); - _ASSERTE(VolatileLoad(&s_bIsGlobalPeggingOn)); - - s_bGCStarted = TRUE; - - _ASSERTE(s_pGCManager); - - // - // Let Jupiter know we are about to walk RCWs so that they can lock their reference cache - // Note that Jupiter doesn't need to unpeg all CCWs at this point and they can do the pegging/unpegging in FindTrackerTargetsCompleted - // - // Note: IGCManager should be free-threaded as it will be called on arbitary threads - // - LOG((LF_INTEROP, LL_INFO100, "[RCW Walker] Calling IGCManager::ReferenceTrackingStarted on 0x%p\n", s_pGCManager)); - s_pGCManager->ReferenceTrackingStarted(); - - // From this point, jupiter decides whether a CCW should be pegged or not as global pegging flag is now off - s_bIsGlobalPeggingOn = FALSE; - LOG((LF_INTEROP, LL_INFO100, "[RCW Walker] Global pegging flag is off\n")); - - // - // OK. Time to walk all the Jupiter RCWs - // - WalkRCWs(); -} - -void RCWWalker::OnGCFinishedWorker() -{ - CONTRACTL { - NOTHROW; - GC_NOTRIGGER; - MODE_ANY; - } - CONTRACTL_END; - - // - // Let Jupiter know RCW walk is done and they need to: - // 1. Unpeg all CCWs if the CCW needs to be unpegged (when the CCW is only reachable by other jupiter RCWs) - // 2. Peg all CCWs if the CCW needs to be pegged (when the above condition is not true) - // 3. Unlock reference cache when they are done - // - // If the walk has failed - Jupiter doesn't need to do anything and could just return immediately - // - // Note: We can IJupiterGCManager from any thread and it is guaranteed by Jupiter - // - _ASSERTE(s_pGCManager); - LOG((LF_INTEROP, LL_INFO100, "[RCW Walker] Calling IGCManager::ReferenceTrackingCompleted on 0x%p\n", s_pGCManager)); - s_pGCManager->ReferenceTrackingCompleted(); - - s_bIsGlobalPeggingOn = TRUE; - LOG((LF_INTEROP, LL_INFO100, "[RCW Walker] Global pegging flag is on\n")); - - s_bGCStarted = FALSE; - - STRESS_LOG0 (LF_INTEROP, LL_INFO100, "[RCW Walker] Gen 2 GC Finished\n"); -} - -#endif // DACCESS_COMPILE diff --git a/src/coreclr/src/vm/rcwwalker.h b/src/coreclr/src/vm/rcwwalker.h deleted file mode 100644 index f625725..0000000 --- a/src/coreclr/src/vm/rcwwalker.h +++ /dev/null @@ -1,152 +0,0 @@ -// 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. -// - -// - -/*============================================================ -** -** Header: RCWWalker.h -** -** -** Purpose: Solve native/manage cyclic reference issue by -** walking RCW objects -** -==============================================================*/ - -#ifndef _H_RCWWALKER_ -#define _H_RCWWALKER_ - -#ifdef FEATURE_COMINTEROP - -#include "internalunknownimpl.h" -#include "utilcode.h" -#include "runtimecallablewrapper.h" - - -// -// RCW Walker -// Walks jupiter RCW objects and create references from RCW to referenced CCW (in native side) -// -class RCWWalker -{ - friend struct _DacGlobals; - -private: - static VolatilePtr s_pGCManager; // The one and only GCManager instance - static BOOL s_bGCStarted; // Has GC started? - -public: - SVAL_DECL(BOOL, s_bIsGlobalPeggingOn); // Do we need to peg every CCW? - -#ifndef DACCESS_COMPILE - static void OnJupiterRCWCreated(RCW *pRCW, IJupiterObject *pJupiterObject); - static void AfterJupiterRCWCreated(RCW *pRCW); - static void BeforeJupiterRCWDestroyed(RCW *pRCW); - - // - // Send out a AddRefFromTrackerSource callback to notify Jupiter we've done a AddRef - // We should do this *after* we made a AddRef because we should never - // be in a state where reported refs > actual refs - // - FORCEINLINE static void AfterInterfaceAddRef(RCW *pRCW) - { - - CONTRACTL { - NOTHROW; - GC_NOTRIGGER; - MODE_ANY; - } - CONTRACTL_END; - - IJupiterObject *pJupiterObject = pRCW->GetJupiterObject(); - if (pJupiterObject) - { - STRESS_LOG2(LF_INTEROP, LL_INFO100, "[RCW Walker] Calling IJupiterObject::AddRefFromTrackerSource (IJupiterObject = 0x%p, RCW = 0x%p)\n", pJupiterObject, pRCW); - pJupiterObject->AddRefFromTrackerSource(); - } - } - - // - // Send out ReleaseFromTrackerSource callback for every cached interface pointer - // This needs to be made before call Release because we should never be in a - // state that reported refs > actual refs - // - FORCEINLINE static void BeforeInterfaceRelease(RCW *pRCW) - { - CONTRACTL { - NOTHROW; - GC_NOTRIGGER; - MODE_ANY; - } - CONTRACTL_END; - - IJupiterObject *pJupiterObject = pRCW->GetJupiterObject(); - if (pJupiterObject) - { - STRESS_LOG2(LF_INTEROP, LL_INFO100, "[RCW Walker] Calling IJupiterObject::ReleaseFromTrackerSource before Release (IJupiterObject = 0x%p, RCW = 0x%p)\n", pJupiterObject, pRCW); - pJupiterObject->ReleaseFromTrackerSource(); - } - } - - -#endif // !DACCESS_COMPILE - - -public : - // - // Called in ComCallableWrapper::IsWrapperActive - // Used to override the individual pegging flag on CCWs and force pegging every jupiter referenced CCW - // See IsWrapperActive for more details - // - static FORCEINLINE BOOL IsGlobalPeggingOn() - { - // We need this weird cast because s_bIsGlobalPeggingOn is used in DAC and defined as - // __GlobalVal in DAC build - // C++'s operator magic didn't work if two levels of operator overloading are involved... - return VolatileLoad((BOOL *)&s_bIsGlobalPeggingOn); - } - -#ifndef DACCESS_COMPILE - // - // Tells GC whether walking all the Jupiter RCW is necessary, which only should happen - // if we have seen jupiter RCWs - // - static FORCEINLINE BOOL NeedToWalkRCWs() - { - LIMITED_METHOD_CONTRACT; - - return (((IJupiterGCManager *)s_pGCManager) != NULL); - } - - // - // Whether a GC has been started and we need to RCW walk - // - static FORCEINLINE BOOL HasGCStarted() - { - return s_bGCStarted; - } - - // - // Called when GC started - // We do most of our work here - // - static void OnGCStarted(int nCondemnedGeneration); - - // - // Called when GC finished - // - static void OnGCFinished(int nCondemnedGeneration); - -private : - static void OnGCStartedWorker(); - static void OnGCFinishedWorker(); - static void WalkRCWs(); - static HRESULT WalkOneRCW(RCW *pRCW, RCWRefCache *pRCWRefCache); -#endif // DACCESS_COMPILE -}; - -#endif // FEATURE_COMINTEROP - -#endif // _H_RCWWALKER_ diff --git a/src/coreclr/src/vm/rexcep.h b/src/coreclr/src/vm/rexcep.h index 4801e26..beffa51 100644 --- a/src/coreclr/src/vm/rexcep.h +++ b/src/coreclr/src/vm/rexcep.h @@ -79,30 +79,6 @@ #include "namespace.h" - -// Temporary workaround - adding some HRESULTs that the Jupiter team will define and -// add to one of their header files for errors. Once these have been RI'ed into -// windows and are in a file adjacent to winerror.h, we can remove these constants. -// Given integration time, remove this by August 2011 at the very latest. -#ifndef E_XAMLPARSEFAILED -#define E_XAMLPARSEFAILED _HRESULT_TYPEDEF_(0x802B000AL) -#endif -#ifndef E_LAYOUTCYCLE -#define E_LAYOUTCYCLE _HRESULT_TYPEDEF_(0x802B0014L) -#endif -#ifndef E_ELEMENTNOTENABLED -#define E_ELEMENTNOTENABLED _HRESULT_TYPEDEF_(0x802B001EL) -#endif -#ifndef E_ELEMENTNOTAVAILABLE -#define E_ELEMENTNOTAVAILABLE _HRESULT_TYPEDEF_(0x802B001FL) -#endif -#ifndef RO_E_CLOSED -#define RO_E_CLOSED _HRESULT_TYPEDEF_(0x80000013L) -#endif -#ifndef APPMODEL_ERROR_NO_PACKAGE -#define APPMODEL_ERROR_NO_PACKAGE 15700L -#endif - // // Actual definition of the exceptions and their matching HRESULT's. // HRESULTs are expected to be defined in CorError.h, and must also be @@ -140,8 +116,7 @@ DEFINE_EXCEPTION(g_SystemNS, BadImageFormatException, true, HRESULT_FROM_WIN32(ERROR_FILE_CORRUPT), IDS_CLASSLOAD_32BITCLRLOADING64BITASSEMBLY, COR_E_LOADING_REFERENCE_ASSEMBLY, - META_E_BAD_SIGNATURE, - COR_E_LOADING_WINMD_REFERENCE_ASSEMBLY) + META_E_BAD_SIGNATURE) // CannotUnloadAppDomainException is removed in CoreCLR #define kCannotUnloadAppDomainException kException @@ -212,14 +187,6 @@ DEFINE_EXCEPTION(g_InteropNS, InvalidOleVariantTypeException, false, C DEFINE_EXCEPTION(g_SystemNS, InvalidOperationException, false, COR_E_INVALIDOPERATION) -#ifdef FEATURE_COMINTEROP -DEFINE_EXCEPTION_HR_WINRT_ONLY(g_SystemNS, InvalidOperationException, COR_E_INVALIDOPERATION, - E_ILLEGAL_STATE_CHANGE, - E_ILLEGAL_METHOD_CALL, - E_ILLEGAL_DELEGATE_ASSIGNMENT, - HRESULT_FROM_WIN32(APPMODEL_ERROR_NO_PACKAGE)) -#endif // FEATURE_COMINTEROP - DEFINE_EXCEPTION(g_SystemNS, InvalidProgramException, false, COR_E_INVALIDPROGRAM) DEFINE_EXCEPTION(g_IONS, IOException, false, COR_E_IO, CTL_E_DEVICEIOERROR, STD_CTL_SCODE(31036), STD_CTL_SCODE(31037)) @@ -245,9 +212,11 @@ DEFINE_EXCEPTION(g_SystemNS, NullReferenceException, false, C // Note: this has to come after NullReferenceException since we want NullReferenceException to be created // when E_POINTER is returned from COM interfaces. DEFINE_EXCEPTION(g_SystemNS, AccessViolationException, false, E_POINTER) - +#ifdef TARGET_WINDOWS DEFINE_EXCEPTION(g_SystemNS, ObjectDisposedException, false, COR_E_OBJECTDISPOSED, RO_E_CLOSED) - +#else +DEFINE_EXCEPTION(g_SystemNS, ObjectDisposedException, false, COR_E_OBJECTDISPOSED) +#endif DEFINE_EXCEPTION(g_SystemNS, OperationCanceledException, false, COR_E_OPERATIONCANCELED) DEFINE_EXCEPTION(g_SystemNS, OverflowException, false, COR_E_OVERFLOW, CTL_E_OVERFLOW) @@ -317,17 +286,8 @@ DEFINE_EXCEPTION(g_SystemNS, ArgumentNullException, false, E // All exceptions defined in other .NET Framework assemblies have to be at the end // -#ifdef FEATURE_COMINTEROP -// Jupiter needs some HRESULTs mapped to exceptions in .NET Framework assemblies other than mscorlib. -DEFINE_EXCEPTION_IN_OTHER_FX_ASSEMBLY(g_MarkupNS, XamlParseException, "System.Runtime.WindowsRuntime.UI.Xaml", false, E_XAMLPARSEFAILED) -DEFINE_EXCEPTION_IN_OTHER_FX_ASSEMBLY(g_AutomationNS, ElementNotAvailableException, "System.Runtime.WindowsRuntime.UI.Xaml", false, E_ELEMENTNOTAVAILABLE) -DEFINE_EXCEPTION_IN_OTHER_FX_ASSEMBLY(g_AutomationNS, ElementNotEnabledException, "System.Runtime.WindowsRuntime.UI.Xaml", false, E_ELEMENTNOTENABLED) -DEFINE_EXCEPTION_IN_OTHER_FX_ASSEMBLY(g_DirectUINS, LayoutCycleException, "System.Runtime.WindowsRuntime.UI.Xaml", false, E_LAYOUTCYCLE) -#endif // FEATURE_COMINTEROP // Please see comments on at the top of this list #undef DEFINE_EXCEPTION -#undef DEFINE_EXCEPTION_HR_WINRT_ONLY -#undef DEFINE_EXCEPTION_IN_OTHER_FX_ASSEMBLY diff --git a/src/coreclr/src/vm/runtimecallablewrapper.cpp b/src/coreclr/src/vm/runtimecallablewrapper.cpp index d15ae5e..e93250f 100644 --- a/src/coreclr/src/vm/runtimecallablewrapper.cpp +++ b/src/coreclr/src/vm/runtimecallablewrapper.cpp @@ -33,7 +33,6 @@ class Object; #include "comdelegate.h" #include "comcache.h" #include "notifyexternals.h" -#include "winrttypenameconverter.h" #include "../md/compiler/custattr.h" #include "olevariant.h" #include "interopconverter.h" @@ -41,7 +40,6 @@ class Object; #include "caparser.h" #include "classnames.h" #include "objectnative.h" -#include "rcwwalker.h" #include "finalizerthread.h" // static @@ -746,37 +744,6 @@ IUnknown *AppXComClassFactory::CreateInstanceInternal(IUnknown *pOuter, BOOL *pf #endif //FEATURE_APPX //------------------------------------------------------------- -MethodTable *WinRTClassFactory::GetTypeFromAttribute(IMDInternalImport *pImport, mdCustomAttribute tkAttribute) -{ - CONTRACTL - { - THROWS; - GC_TRIGGERS; - MODE_ANY; - } - CONTRACTL_END; - - // get raw custom attribute - const BYTE *pbAttr = NULL; - ULONG cbAttr = 0; - IfFailThrowBF(pImport->GetCustomAttributeAsBlob(tkAttribute, (const void **)&pbAttr, &cbAttr), BFA_INVALID_TOKEN, m_pClassMT->GetModule()); - - CustomAttributeParser cap(pbAttr, cbAttr); - IfFailThrowBF(cap.ValidateProlog(), BFA_BAD_CA_HEADER, m_pClassMT->GetModule()); - - // retrieve the factory interface name - LPCUTF8 szName; - ULONG cbName; - IfFailThrow(cap.GetNonNullString(&szName, &cbName)); - - // copy the name to a temporary buffer and NULL terminate it - StackSString ss(SString::Utf8, szName, cbName); - - // load the factory interface - return TypeName::GetTypeUsingCASearchRules(ss.GetUnicode(), m_pClassMT->GetAssembly()).GetMethodTable(); -} - -//------------------------------------------------------------- // Returns true if the first parameter of the CA's method ctor is a System.Type static BOOL AttributeFirstParamIsSystemType(mdCustomAttribute tkAttribute, IMDInternalImport *pImport) { @@ -858,320 +825,6 @@ static BOOL AttributeFirstParamIsSystemType(mdCustomAttribute tkAttribute, IMDIn return TRUE; } -//------------------------------------------------------------- -void WinRTClassFactory::Init() -{ - CONTRACTL - { - THROWS; - GC_TRIGGERS; - MODE_ANY; - } - CONTRACTL_END; - - HRESULT hr; - IMDInternalImport *pImport = m_pClassMT->GetMDImport(); - - { - // Sealed classes may have Windows.Foundation.Activatable attributes. Such classes must be sealed, because we'd - // have no way to use their ctor from a derived class (no composition) - // Unsealed classes may have Windows.Foundation.Composable attributes. These are currently mutually exclusive, but we - // may need to relax this in the future for versioning reasons (so a class can be unsealed in a new version without - // being binary breaking). - // Note that we just ignore activation attributes if they occur on the wrong type of class - LPCSTR attributeName; - if (IsComposition()) - { - attributeName = g_WindowsFoundationComposableAttributeClassName; - } - else - { - attributeName = g_WindowsFoundationActivatableAttributeClassName; - } - - MDEnumHolder hEnum(pImport); - - // find and parse all WindowsFoundationActivatableAttribute/WindowsFoundationComposableAttribute attributes - hr = pImport->EnumCustomAttributeByNameInit(m_pClassMT->GetCl(), attributeName, &hEnum); - IfFailThrow(hr); - - if (hr == S_OK) // there are factory interfaces - { - mdCustomAttribute tkAttribute; - while (pImport->EnumNext(&hEnum, &tkAttribute)) - { - if (!AttributeFirstParamIsSystemType(tkAttribute, pImport)) - { - // The first parameter of the Composable/Activatable attribute is not a System.Type - // and therefore the attribute does not specify a factory interface so we ignore the attribute - continue; - } - // get raw custom attribute - const BYTE *pbAttr = NULL; - ULONG cbAttr = 0; - IfFailThrowBF(pImport->GetCustomAttributeAsBlob(tkAttribute, (const void **)&pbAttr, &cbAttr), BFA_INVALID_TOKEN, m_pClassMT->GetModule()); - CustomAttributeParser cap(pbAttr, cbAttr); - IfFailThrowBF(cap.ValidateProlog(), BFA_BAD_CA_HEADER, m_pClassMT->GetModule()); - - // The activation factory interface is stored in the attribute by type name - LPCUTF8 szFactoryInterfaceName; - ULONG cbFactoryInterfaceName; - IfFailThrow(cap.GetNonNullString(&szFactoryInterfaceName, &cbFactoryInterfaceName)); - - StackSString strFactoryInterface(SString::Utf8, szFactoryInterfaceName, cbFactoryInterfaceName); - MethodTable *pMTFactoryInterface = LoadWinRTType(&strFactoryInterface, /* bThrowIfNotFound = */ TRUE).GetMethodTable(); - - _ASSERTE(pMTFactoryInterface); - m_factoryInterfaces.Append(pMTFactoryInterface); - } - } - } - - { - // find and parse all Windows.Foundation.Static attributes - MDEnumHolder hEnum(pImport); - hr = pImport->EnumCustomAttributeByNameInit(m_pClassMT->GetCl(), g_WindowsFoundationStaticAttributeClassName, &hEnum); - IfFailThrow(hr); - - if (hr == S_OK) // there are static interfaces - { - mdCustomAttribute tkAttribute; - while (pImport->EnumNext(&hEnum, &tkAttribute)) - { - if (!AttributeFirstParamIsSystemType(tkAttribute, pImport)) - { - // The first parameter of the Static attribute is not a System.Type - // and therefore the attribute does not specify a factory interface so we ignore the attribute - continue; - } - - const BYTE *pbAttr = NULL; - ULONG cbAttr = 0; - IfFailThrowBF(pImport->GetCustomAttributeAsBlob(tkAttribute, (const void **)&pbAttr, &cbAttr), BFA_INVALID_TOKEN, m_pClassMT->GetModule()); - - CustomAttributeParser cap(pbAttr, cbAttr); - IfFailThrowBF(cap.ValidateProlog(), BFA_BAD_CA_HEADER, m_pClassMT->GetModule()); - - // retrieve the factory interface name - LPCUTF8 szName; - ULONG cbName; - IfFailThrow(cap.GetNonNullString(&szName, &cbName)); - - // copy the name to a temporary buffer and NULL terminate it - StackSString ss(SString::Utf8, szName, cbName); - TypeHandle th = LoadWinRTType(&ss, /* bThrowIfNotFound = */ TRUE); - - MethodTable *pMTStaticInterface = th.GetMethodTable(); - m_staticInterfaces.Append(pMTStaticInterface); - } - } - } - - { - - // Special case (not pretty): WinMD types requires you to put DefaultAttribute on interfaceImpl to - // mark the interface as default interface. But C# doesn't allow you to do that so we have - // to do it manually here. - MethodTable* pAsyncTracingEventArgsMT = MscorlibBinder::GetClass(CLASS__ASYNC_TRACING_EVENT_ARGS); - if(pAsyncTracingEventArgsMT == m_pClassMT) - { - m_pDefaultItfMT = MscorlibBinder::GetClass(CLASS__IASYNC_TRACING_EVENT_ARGS); - } - else - { - // parse the DefaultAttribute to figure out the default interface of the class - HENUMInternalHolder hEnumInterfaceImpl(pImport); - hEnumInterfaceImpl.EnumInit(mdtInterfaceImpl, m_pClassMT->GetCl()); - - DWORD cInterfaces = pImport->EnumGetCount(&hEnumInterfaceImpl); - if (cInterfaces != 0) - { - mdInterfaceImpl ii; - while (pImport->EnumNext(&hEnumInterfaceImpl, &ii)) - { - const BYTE *pbAttr; - ULONG cbAttr; - HRESULT hr = pImport->GetCustomAttributeByName(ii, g_WindowsFoundationDefaultClassName, (const void **)&pbAttr, &cbAttr); - IfFailThrow(hr); - if (hr == S_OK) - { - mdToken typeRefOrDefOrSpec; - IfFailThrow(pImport->GetTypeOfInterfaceImpl(ii, &typeRefOrDefOrSpec)); - - TypeHandle th = ClassLoader::LoadTypeDefOrRefOrSpecThrowing( - m_pClassMT->GetModule(), - typeRefOrDefOrSpec, - NULL, - ClassLoader::ThrowIfNotFound, - ClassLoader::FailIfUninstDefOrRef, - ClassLoader::LoadTypes, CLASS_LOAD_EXACTPARENTS); - - m_pDefaultItfMT = th.GetMethodTable(); - break; - } - } - } - } - } - - // initialize m_hClassName - InlineSString ssClassName; - m_pClassMT->_GetFullyQualifiedNameForClass(ssClassName); - -#ifndef CROSSGEN_COMPILE - if (!GetAppDomain()->IsCompilationDomain()) - { - // don't bother creating the HSTRING when NGENing - we may run on downlevel - IfFailThrow(WindowsCreateString(ssClassName.GetUnicode(), ssClassName.GetCount(), &m_hClassName)); - } -#endif - - if (ssClassName.BeginsWith(SL(W("Windows.")))) - { - // parse the GCPressureAttribute only on first party runtime classes - const BYTE *pVal = NULL; - ULONG cbVal = 0; - - if (S_OK == pImport->GetCustomAttributeByName(m_pClassMT->GetCl(), g_WindowsFoundationGCPressureAttributeClassName, (const void **)&pVal, &cbVal)) - { - CustomAttributeParser cap(pVal, cbVal); - CaNamedArg namedArgs[1]; - - // First, the void constructor - IfFailThrow(ParseKnownCaArgs(cap, NULL, 0)); - - // Then, find the named argument - namedArgs[0].InitI4FieldEnum("amount", "Windows.Foundation.Metadata.GCPressureAmount", -1); - - IfFailThrow(ParseKnownCaNamedArgs(cap, namedArgs, lengthof(namedArgs))); - - static_assert(RCW::GCPressureSize_WinRT_Medium == RCW::GCPressureSize_WinRT_Low + 1, "RCW::GCPressureSize does not match Windows.Foundation.Metadata.GCPressureAmount"); - static_assert(RCW::GCPressureSize_WinRT_High == RCW::GCPressureSize_WinRT_Medium + 1, "RCW::GCPressureSize does not match Windows.Foundation.Metadata.GCPressureAmount"); - - int amount = namedArgs[0].val.i4; - if (amount >= 0 && amount < (RCW::GCPressureSize_COUNT - RCW::GCPressureSize_WinRT_Low)) - { - m_GCPressure = (RCW::GCPressureSize)(amount + RCW::GCPressureSize_WinRT_Low); - } - } - } -} - -//------------------------------------------------------------- -MethodDesc *WinRTClassFactory::FindFactoryMethod(PCCOR_SIGNATURE pSig, DWORD cSig, Module *pModule) -{ - CONTRACTL - { - STANDARD_VM_CHECK; - PRECONDITION(CheckPointer(pSig)); - PRECONDITION(CheckPointer(pModule)); - } - CONTRACTL_END; - - COUNT_T count = m_factoryInterfaces.GetCount(); - for (UINT i = 0; i < count; i++) - { - MethodTable *pMT = m_factoryInterfaces[i]; - - MethodDesc *pMD = MemberLoader::FindMethod(pMT, "", pSig, cSig, pModule, MemberLoader::FM_IgnoreName); - if (pMD != NULL) - { - return pMD; - } - } - - return NULL; -} - -//------------------------------------------------------------- -MethodDesc *WinRTClassFactory::FindStaticMethod(LPCUTF8 pszName, PCCOR_SIGNATURE pSig, DWORD cSig, Module *pModule) -{ - CONTRACTL - { - STANDARD_VM_CHECK; - PRECONDITION(CheckPointer(pszName)); - PRECONDITION(CheckPointer(pSig)); - PRECONDITION(CheckPointer(pModule)); - } - CONTRACTL_END; - - COUNT_T count = m_staticInterfaces.GetCount(); - for (UINT i = 0; i < count; i++) - { - MethodTable *pMT = m_staticInterfaces[i]; - - MethodDesc *pMD = MemberLoader::FindMethod(pMT, pszName, pSig, cSig, pModule); - if (pMD != NULL) - { - return pMD; - } - } - - return NULL; -} - -//------------------------------------------------------------- -void WinRTClassFactory::Cleanup() -{ - LIMITED_METHOD_CONTRACT; - - if (m_hClassName != NULL) - { - // HSTRING has been created, which means combase should have been loaded. - // Delay load will not fail. - _ASSERTE(WszGetModuleHandle(W("combase.dll")) != NULL); - CONTRACT_VIOLATION(ThrowsViolation); - -#ifndef CROSSGEN_COMPILE - WindowsDeleteString(m_hClassName); -#endif - } - delete m_pWinRTOverrideInfo; - delete this; -} - -//------------------------------------------------------------- -void WinRTManagedClassFactory::Cleanup() -{ - CONTRACTL - { - NOTHROW; - GC_TRIGGERS; - MODE_ANY; - } - CONTRACTL_END; - - if (m_pCCWTemplate != NULL) - { - m_pCCWTemplate->Release(); - m_pCCWTemplate = NULL; - } - - WinRTClassFactory::Cleanup(); // deletes 'this' -} -#ifndef CROSSGEN_COMPILE -//------------------------------------------------------------- -ComCallWrapperTemplate *WinRTManagedClassFactory::GetOrCreateComCallWrapperTemplate(MethodTable *pFactoryMT) -{ - CONTRACT (ComCallWrapperTemplate *) - { - THROWS; - GC_TRIGGERS; - MODE_ANY; - PRECONDITION(CheckPointer(pFactoryMT)); - POSTCONDITION(CheckPointer(RETVAL)); - } - CONTRACT_END; - - if (m_pCCWTemplate == NULL) - { - ComCallWrapperTemplate::CreateTemplate(TypeHandle(pFactoryMT), this); - } - - RETURN m_pCCWTemplate; -} -#endif // CROSSGEN_COMPILE - #endif // FEATURE_COMINTEROP_UNMANAGED_ACTIVATION #ifndef CROSSGEN_COMPILE @@ -1365,7 +1018,7 @@ BOOL RCWCache::FindOrInsertWrapper_NoLock(IUnknown* pIdentity, RCWHolder* pRCW, //-------------------------------------------------------------------------------- // ULONG RCWCache::ReleaseWrappers() // Helper to release the complus wrappers in the cache that lives in the specified -// context (including Jupiter RCWs) or all the wrappers in the cache if the pCtxCookie is null. +// context or all the wrappers in the cache if the pCtxCookie is null. void RCWCache::ReleaseWrappersWorker(LPVOID pCtxCookie) { CONTRACTL @@ -1404,12 +1057,11 @@ void RCWCache::ReleaseWrappersWorker(LPVOID pCtxCookie) _ASSERTE(pWrap != NULL); // If a context cookie was specified, then only clean up wrappers that - // are in that context, including non-FTM regular RCWs, and FTM Jupiter objects + // are in that context, including non-FTM regular RCWs // Otherwise clean up all the wrappers. // Ignore RCWs that aggregate the FTM if we are cleaning up context - // specific RCWs (note that we rely on this behavior in WinRT factory cache code) - // Note that Jupiter RCWs are special and they are considered to be context-bound - if (!pCtxCookie || ((pWrap->GetWrapperCtxCookie() == pCtxCookie) && (pWrap->IsJupiterObject() || !pWrap->IsFreeThreaded()))) + // specific RCWs + if (!pCtxCookie || ((pWrap->GetWrapperCtxCookie() == pCtxCookie) && !pWrap->IsFreeThreaded())) { if (!pWrap->IsURTAggregated()) CleanupList.AddWrapper_NoLock(pWrap); @@ -1505,9 +1157,6 @@ public: // No need to use InterlockedOr here since every other place that modifies the flags // runs in cooperative GC mode (i.e. definitely not concurrently with this function). pRCW->m_Flags.m_Detached = 1; - - if (pRCW->IsJupiterObject()) - RCWWalker::BeforeJupiterRCWDestroyed(pRCW); } } } @@ -2053,10 +1702,6 @@ const int RCW::s_rGCPressureTable[GCPressureSize_COUNT] = GC_PRESSURE_PROCESS_LOCAL, // GCPressureSize_ProcessLocal GC_PRESSURE_MACHINE_LOCAL, // GCPressureSize_MachineLocal GC_PRESSURE_REMOTE, // GCPressureSize_Remote - GC_PRESSURE_WINRT_BASE, // GCPressureSize_WinRT_Base - GC_PRESSURE_WINRT_LOW, // GCPressureSize_WinRT_Low - GC_PRESSURE_WINRT_MEDIUM, // GCPressureSize_WinRT_Medium - GC_PRESSURE_WINRT_HIGH, // GCPressureSize_WinRT_High }; // Deletes all items in code:s_RCWStandbyList. @@ -2073,8 +1718,7 @@ void RCW::FlushStandbyList() } } //-------------------------------------------------------------------------------- -// The IUnknown passed in is AddRef'ed if we succeed in creating the wrapper unless -// the CF_SuppressAddRef flag is set. +// The IUnknown passed in is AddRef'ed if we succeed in creating the wrapper. RCW* RCW::CreateRCW(IUnknown *pUnk, DWORD dwSyncBlockIndex, DWORD flags, MethodTable *pClassMT) { CONTRACT (RCW*) @@ -2093,10 +1737,6 @@ RCW* RCW::CreateRCW(IUnknown *pUnk, DWORD dwSyncBlockIndex, DWORD flags, MethodT pRCW = RCW::CreateRCWInternal(pUnk, dwSyncBlockIndex, flags, pClassMT); } - // No exception after this point - if (pRCW->IsJupiterObject()) - RCWWalker::AfterJupiterRCWCreated(pRCW); - RETURN pRCW; } @@ -2151,31 +1791,11 @@ RCW* RCW::CreateRCWInternal(IUnknown *pUnk, DWORD dwSyncBlockIndex, DWORD flags, // Log the creation LogRCWCreate(pWrap, pUnk); - // Remember that the object is known to support IInspectable - pWrap->m_Flags.m_fSupportsIInspectable = !!(flags & CF_SupportsIInspectable); - // Initialize wrapper pWrap->Initialize(pUnk, dwSyncBlockIndex, pClassMT); - if (flags & CF_SupportsIInspectable) - { - // WinRT objects always apply some GC pressure - GCPressureSize pressureSize = GCPressureSize_WinRT_Base; - - // if we have a strongly-typed non-delegate RCW, we may have read the GC pressure amount from metadata - if (pClassMT->IsProjectedFromWinRT() && !pClassMT->IsDelegate()) - { - WinRTClassFactory *pFactory = GetComClassFactory(pClassMT)->AsWinRTClassFactory(); - pressureSize = pFactory->GetGCPressure(); - } - - pWrap->AddMemoryPressure(pressureSize); - } - - // Check to see if this is a DCOM proxy if either we've been explicitly asked to, or if - // we're talking to a non-WinRT object and we need to add memory pressure - const bool checkForDCOMProxy = (flags & CF_DetectDCOMProxy) || - !(flags & CF_SupportsIInspectable); + // Check to see if this is a DCOM proxy + const bool checkForDCOMProxy = (flags & CF_DetectDCOMProxy); if (checkForDCOMProxy) { @@ -2196,24 +1816,20 @@ RCW* RCW::CreateRCWInternal(IUnknown *pUnk, DWORD dwSyncBlockIndex, DWORD flags, pWrap->m_Flags.m_fIsDCOMProxy = 1; } - // Only add memory pressure for proxies for non-WinRT objects - if (!(flags & CF_SupportsIInspectable)) + switch(dwValue) { - switch(dwValue) - { - case SERVER_LOCALITY_PROCESS_LOCAL: - pressureSize = GCPressureSize_ProcessLocal; - break; - case SERVER_LOCALITY_MACHINE_LOCAL: - pressureSize = GCPressureSize_MachineLocal; - break; - case SERVER_LOCALITY_REMOTE: - pressureSize = GCPressureSize_Remote; - break; - default: - pressureSize = GCPressureSize_None; - break; - } + case SERVER_LOCALITY_PROCESS_LOCAL: + pressureSize = GCPressureSize_ProcessLocal; + break; + case SERVER_LOCALITY_MACHINE_LOCAL: + pressureSize = GCPressureSize_MachineLocal; + break; + case SERVER_LOCALITY_REMOTE: + pressureSize = GCPressureSize_Remote; + break; + default: + pressureSize = GCPressureSize_None; + break; } } } @@ -2298,39 +1914,6 @@ void RCW::Initialize(IUnknown* pUnk, DWORD dwSyncBlockIndex, MethodTable *pClass // Store the sync block index. m_SyncBlockIndex = dwSyncBlockIndex; - // Check if this object is a Jupiter object (only for WinRT scenarios) - _ASSERTE(m_Flags.m_fIsJupiterObject == 0); - if (SupportsIInspectable()) - { - SafeComHolderPreemp pJupiterObject = NULL; - HRESULT hr = SafeQueryInterfacePreemp(pUnk, IID_IJupiterObject, (IUnknown **)&pJupiterObject); - LogInteropQI(pUnk, IID_IJupiterObject, hr, "QI for IJupiterObject"); - - if (SUCCEEDED(hr)) - { - // A Jupiter object that is not free threaded is not allowed - if (!IsFreeThreaded()) - { - StackSString ssObjClsName; - StackSString ssDestClsName; - - pClassMT->_GetFullyQualifiedNameForClass(ssObjClsName); - - COMPlusThrow(kInvalidCastException, IDS_EE_CANNOTCAST, - ssObjClsName.GetUnicode(), W("IAgileObject")); - } - - RCWWalker::OnJupiterRCWCreated(this, pJupiterObject); - - SetJupiterObject(pJupiterObject); - - if (!IsURTAggregated()) - { - pJupiterObject.SuppressRelease(); - } - } - } - // Log the wrapper initialization. LOG((LF_INTEROP, LL_INFO100, "Initializing RCW %p with SyncBlock index %d\n", this, dwSyncBlockIndex)); @@ -2367,18 +1950,6 @@ VOID RCW::MarkURTAggregated() } CONTRACTL_END; - if (!m_Flags.m_fURTAggregated && m_Flags.m_fIsJupiterObject) - { - // Notify Jupiter that we are about to release IJupiterObject - RCWWalker::BeforeInterfaceRelease(this); - - // If we mark this RCW as aggregated and we've done a QI for IJupiterObject, - // release it to account for the extra ref - // Note that this is a quick fix for PDC-2 and eventually we should replace - // this with a better fix - SafeRelease(GetJupiterObject()); - } - m_Flags.m_fURTAggregated = 1; } @@ -2633,9 +2204,6 @@ void RCW::MinorCleanup() // wrappers from wrapper cache, pCache->RemoveWrapper(this); - if (IsJupiterObject() && !IsDetached()) - RCWWalker::BeforeJupiterRCWDestroyed(this); - // Clear the SyncBlockIndex as the object is being GC'd and the index will become // invalid as soon as the object is collected. m_SyncBlockIndex = 0; @@ -2740,8 +2308,6 @@ void RCW::CreateDuplicateWrapper(MethodTable *pNewMT, RCWHolder* pNewRCW) pAutoUnk = GetIUnknown(); DWORD flags = 0; - if (SupportsIInspectable()) - flags |= CF_SupportsIInspectable; // make sure we "pin" the syncblock before switching to preemptive mode SyncBlock *pSB = NewWrapperObj->GetSyncBlock(); @@ -2915,14 +2481,6 @@ IDispatch *RCW::GetIDispatch() return (IDispatch *)GetWellKnownInterface(IID_IDispatch); } -//----------------------------------------------------------------- -// Get the IInspectable pointer for the wrapper -IInspectable *RCW::GetIInspectable() -{ - WRAPPER_NO_CONTRACT; - return (IInspectable *)GetWellKnownInterface(IID_IInspectable); -} - //----------------------------------------------- // Free GC handle and remove SyncBlock entry void RCW::DecoupleFromObject() @@ -2937,9 +2495,6 @@ void RCW::DecoupleFromObject() if (m_SyncBlockIndex != 0) { - if (IsJupiterObject() && !IsDetached()) - RCWWalker::BeforeJupiterRCWDestroyed(this); - // remove reference to wrapper from sync block SyncBlock* pSB = GetSyncBlock(); _ASSERTE(pSB); @@ -3001,86 +2556,6 @@ HRESULT RCW::SafeQueryInterfaceRemoteAware(REFIID iid, IUnknown** ppResUnk) #endif //#ifndef CROSSGEN_COMPILE -//----------------------------------------------------------------- -// Returns a redirected collection interface corresponding to a given ICollection/ICollection or NULL -// if the given interface is not ICollection/ICollection. This also works for IReadOnlyCollection. -// The BOOL parameters help resolve the ambiguity around ICollection>. -// static -MethodTable *RCW::ResolveICollectionInterface(MethodTable *pItfMT, BOOL fPreferIDictionary, BOOL *pfChosenIDictionary) -{ - CONTRACTL - { - THROWS; - GC_TRIGGERS; - MODE_ANY; - PRECONDITION(CheckPointer(pItfMT)); - PRECONDITION(CheckPointer(pfChosenIDictionary, NULL_OK)); - } - CONTRACTL_END; - - if (pfChosenIDictionary != NULL) - *pfChosenIDictionary = FALSE; - - // Casting/calling via ICollection means QI/calling through IVector, casting/calling via ICollection> means - // QI/calling via IMap OR IVector>. See which case it is. - if (pItfMT->HasSameTypeDefAs(MscorlibBinder::GetExistingClass(CLASS__ICOLLECTIONGENERIC))) - { - Instantiation inst = pItfMT->GetInstantiation(); - TypeHandle arg = inst[0]; - - if (fPreferIDictionary) - { - if (!arg.IsTypeDesc() && arg.GetMethodTable()->HasSameTypeDefAs(MscorlibBinder::GetClass(CLASS__KEYVALUEPAIRGENERIC))) - { - // ICollection> -> IDictionary - if (pfChosenIDictionary != NULL) - *pfChosenIDictionary = TRUE; - - pItfMT = GetAppDomain()->GetRedirectedType(WinMDAdapter::RedirectedTypeIndex_System_Collections_Generic_IDictionary); - return TypeHandle(pItfMT).Instantiate(arg.GetInstantiation()).GetMethodTable(); - } - } - - // ICollection -> IList - pItfMT = GetAppDomain()->GetRedirectedType(WinMDAdapter::RedirectedTypeIndex_System_Collections_Generic_IList); - return TypeHandle(pItfMT).Instantiate(inst).GetMethodTable(); - } - - // Casting/calling via IReadOnlyCollection means QI/calling through IVectorView, casting/calling via IReadOnlyCollection> means - // QI/calling via IMapView OR IVectorView>. See which case it is. - if (pItfMT->HasSameTypeDefAs(MscorlibBinder::GetExistingClass(CLASS__IREADONLYCOLLECTIONGENERIC))) - { - Instantiation inst = pItfMT->GetInstantiation(); - TypeHandle arg = inst[0]; - - if (fPreferIDictionary) - { - if (!arg.IsTypeDesc() && arg.GetMethodTable()->HasSameTypeDefAs(MscorlibBinder::GetClass(CLASS__KEYVALUEPAIRGENERIC))) - { - // IReadOnlyCollection> -> IReadOnlyDictionary - if (pfChosenIDictionary != NULL) - *pfChosenIDictionary = TRUE; - - pItfMT = GetAppDomain()->GetRedirectedType(WinMDAdapter::RedirectedTypeIndex_System_Collections_Generic_IReadOnlyDictionary); - return TypeHandle(pItfMT).Instantiate(arg.GetInstantiation()).GetMethodTable(); - } - } - - // IReadOnlyCollection -> IReadOnlyList - pItfMT = GetAppDomain()->GetRedirectedType(WinMDAdapter::RedirectedTypeIndex_System_Collections_Generic_IReadOnlyList); - return TypeHandle(pItfMT).Instantiate(inst).GetMethodTable(); - } - - // Casting/calling via ICollection means QI/calling through IBindableVector (projected to IList). - if (pItfMT == MscorlibBinder::GetExistingClass(CLASS__ICOLLECTION)) - { - return MscorlibBinder::GetExistingClass(CLASS__ILIST); - } - - // none of the above - return NULL; -} - // Helper method to allow us to compare a MethodTable against a known method table // from mscorlib. If the mscorlib type isn't loaded, we don't load it because we // know that it can't be the MethodTable we're curious about. @@ -3101,615 +2576,11 @@ static bool MethodTableHasSameTypeDefAsMscorlibClass(MethodTable* pMT, BinderCla return (pMT->HasSameTypeDefAs(pMT_MscorlibClass) != FALSE); } -// Returns an interface with variance corresponding to pMT or NULL if pMT does not support variance. -// The reason why we don't just call HasVariance() is that we also deal with the WinRT interfaces -// like IIterable which do not (and cannot) have variance from .NET type system point of view. -// static -MethodTable *RCW::GetVariantMethodTable(MethodTable *pMT) +#ifndef CROSSGEN_COMPILE +// Performs QI for the given interface, optionally instantiating it with the given generic args. +HRESULT RCW::CallQueryInterface(MethodTable *pMT, Instantiation inst, IID *piid, IUnknown **ppUnk) { - CONTRACT(MethodTable *) - { - THROWS; - GC_TRIGGERS; - MODE_ANY; - PRECONDITION(CheckPointer(pMT)); - POSTCONDITION(RETVAL == NULL || RETVAL->HasVariance()); - } - CONTRACT_END; - - RCWPerTypeData *pData = pMT->GetRCWPerTypeData(); - if (pData == NULL) - { - // if this type has no RCW data allocated, we know for sure that pMT has no - // corresponding MethodTable with variance - _ASSERTE(ComputeVariantMethodTable(pMT) == NULL); - RETURN NULL; - } - - if ((pData->m_dwFlags & RCWPerTypeData::VariantTypeInited) == 0) - { - pData->m_pVariantMT = ComputeVariantMethodTable(pMT); - FastInterlockOr(&pData->m_dwFlags, RCWPerTypeData::VariantTypeInited); - } - RETURN pData->m_pVariantMT; -} - -// static -MethodTable *RCW::ComputeVariantMethodTable(MethodTable *pMT) -{ - CONTRACT(MethodTable *) - { - THROWS; - GC_TRIGGERS; - MODE_ANY; - PRECONDITION(CheckPointer(pMT)); - POSTCONDITION(RETVAL == NULL || RETVAL->HasVariance()); - } - CONTRACT_END; - - if (!pMT->IsProjectedFromWinRT() && !WinRTTypeNameConverter::ResolveRedirectedType(pMT, NULL)) - { - RETURN NULL; - } - - if (pMT->HasVariance()) - { - RETURN pMT; - } - - // IIterable and IVectorView are not marked as covariant. Check them explicitly and - // return the corresponding IEnumerable / IReadOnlyList instantiation. - if (MethodTableHasSameTypeDefAsMscorlibClass(pMT, CLASS__IITERABLE)) - { - RETURN TypeHandle(MscorlibBinder::GetExistingClass(CLASS__IENUMERABLEGENERIC)). - Instantiate(pMT->GetInstantiation()).AsMethodTable(); - } - if (MethodTableHasSameTypeDefAsMscorlibClass(pMT, CLASS__IVECTORVIEW)) - { - RETURN TypeHandle(MscorlibBinder::GetExistingClass(CLASS__IREADONLYLISTGENERIC)). - Instantiate(pMT->GetInstantiation()).AsMethodTable(); - } - - // IIterator is not marked as covariant either. Return the covariant IEnumerator. - DefineFullyQualifiedNameForClassW(); - if (MethodTableHasSameTypeDefAsMscorlibClass(pMT, CLASS__IITERATOR) || - wcscmp(GetFullyQualifiedNameForClassW_WinRT(pMT), g_WinRTIIteratorClassNameW) == 0) - { - RETURN TypeHandle(MscorlibBinder::GetClass(CLASS__IENUMERATORGENERIC)). - Instantiate(pMT->GetInstantiation()).AsMethodTable(); - } - - RETURN NULL; -} - -#ifndef CROSSGEN_COMPILE -//----------------------------------------------------------------- -// Determines the interface that should be QI'ed for when the RCW is cast to pItfMT. -RCW::InterfaceRedirectionKind RCW::GetInterfaceForQI(MethodTable *pItfMT, MethodTable **pNewItfMT) -{ - CONTRACTL - { - THROWS; - GC_TRIGGERS; - MODE_ANY; - PRECONDITION(CheckPointer(pItfMT)); - PRECONDITION(CheckPointer(pNewItfMT)); - } - CONTRACTL_END; - - // We don't want to be redirecting interfaces if the underlying COM object is not a WinRT type - if (SupportsIInspectable() || pItfMT->IsWinRTRedirectedDelegate()) - { - MethodTable *pNewItfMT1; - MethodTable *pNewItfMT2; - InterfaceRedirectionKind redirectionKind = GetInterfacesForQI(pItfMT, &pNewItfMT1, &pNewItfMT2); - - // - // IEnumerable may need three QI attempts: - // 1. IEnumerable/IDispatch+DISPID_NEWENUM - // 2. IBindableIterable - // 3. IIterable for a T - // - // Is this 3rd attempt on IEnumerable (non-generic)? - if (redirectionKind == InterfaceRedirection_Other_RetryOnFailure && - pItfMT != *pNewItfMT && *pNewItfMT != NULL && - pItfMT == MscorlibBinder::GetExistingClass(CLASS__IENUMERABLE)) - { - // Yes - we are at 3rd attempt; - // QI for IEnumerable/IDispatch+DISPID_NEWENUM and for IBindableIterable failed - // and we are about to see if we know of an IIterable to use. - - MethodDesc *pMD = GetGetEnumeratorMethod(); - if (pMD != NULL) - { - // we have already determined what casting to IEnumerable means for this RCW - TypeHandle th = TypeHandle(MscorlibBinder::GetClass(CLASS__IITERABLE)); - *pNewItfMT = th.Instantiate(pMD->GetClassInstantiation()).GetMethodTable(); - return InterfaceRedirection_IEnumerable; - } - - // The last attempt failed, this is an error. - return InterfaceRedirection_UnresolvedIEnumerable; - } - - if ((redirectionKind != InterfaceRedirection_IEnumerable_RetryOnFailure && - redirectionKind != InterfaceRedirection_Other_RetryOnFailure) || *pNewItfMT == NULL) - { - // First attempt - use pNewItfMT1 - *pNewItfMT = pNewItfMT1; - return redirectionKind; - } - else - { - // Second attempt - use pNewItfMT2 - *pNewItfMT = pNewItfMT2; - - if (redirectionKind == InterfaceRedirection_IEnumerable_RetryOnFailure) - return InterfaceRedirection_IEnumerable; - - // Get ready for the 3rd attmpt if 2nd attempt fails - // This only happens for non-generic IEnumerable - if (pItfMT == MscorlibBinder::GetExistingClass(CLASS__IENUMERABLE)) - return InterfaceRedirection_IEnumerable_RetryOnFailure; - - return InterfaceRedirection_IEnumerable; - } - } - - *pNewItfMT = pItfMT; - return InterfaceRedirection_None; -} -#endif // !CROSSGEN_COMPILE - -// static -RCW::InterfaceRedirectionKind RCW::GetInterfacesForQI(MethodTable *pItfMT, MethodTable **ppNewItfMT1, MethodTable **ppNewItfMT2) -{ - CONTRACTL - { - THROWS; - GC_TRIGGERS; - MODE_ANY; - PRECONDITION(CheckPointer(pItfMT)); - PRECONDITION(CheckPointer(ppNewItfMT1)); - PRECONDITION(CheckPointer(ppNewItfMT2)); - } - CONTRACTL_END; - - RCWPerTypeData *pData = pItfMT->GetRCWPerTypeData(); - if (pData == NULL) - { -#ifdef _DEBUG - // verify that if the per-type data is NULL, the type has indeed no redirection - MethodTable *pNewItfMT1; - MethodTable *pNewItfMT2; - _ASSERTE(ComputeInterfacesForQI(pItfMT, &pNewItfMT1, &pNewItfMT2) == InterfaceRedirection_None); -#endif // _DEBUG - - *ppNewItfMT1 = pItfMT; - *ppNewItfMT2 = NULL; - return InterfaceRedirection_None; - } - else - { - if ((pData->m_dwFlags & RCWPerTypeData::RedirectionInfoInited) == 0) - { - pData->m_RedirectionKind = ComputeInterfacesForQI(pItfMT, &pData->m_pMTForQI1, &pData->m_pMTForQI2); - FastInterlockOr(&pData->m_dwFlags, RCWPerTypeData::RedirectionInfoInited); - } - - *ppNewItfMT1 = pData->m_pMTForQI1; - *ppNewItfMT2 = pData->m_pMTForQI2; - return pData->m_RedirectionKind; - } -} - -// static -RCW::InterfaceRedirectionKind RCW::ComputeInterfacesForQI(MethodTable *pItfMT, MethodTable **ppNewItfMT1, MethodTable **ppNewItfMT2) -{ - CONTRACTL - { - THROWS; - GC_TRIGGERS; - MODE_ANY; - PRECONDITION(CheckPointer(pItfMT)); - PRECONDITION(CheckPointer(ppNewItfMT1)); - PRECONDITION(CheckPointer(ppNewItfMT2)); - } - CONTRACTL_END; - - if (pItfMT->IsProjectedFromWinRT()) - { - // If we're casting to IIterable directly, then while we do want to QI IIterable, also - // make a note that it is redirected from IEnumerable - if (pItfMT->HasInstantiation() && pItfMT->HasSameTypeDefAs(MscorlibBinder::GetClass(CLASS__IITERABLE))) - { - *ppNewItfMT1 = pItfMT; - return InterfaceRedirection_IEnumerable; - } - } - else - { - WinMDAdapter::RedirectedTypeIndex redirectedInterfaceIndex; - RCW::InterfaceRedirectionKind redirectionKind = InterfaceRedirection_None; - - BOOL fChosenIDictionary; - MethodTable *pResolvedItfMT = ResolveICollectionInterface(pItfMT, TRUE, &fChosenIDictionary); - if (pResolvedItfMT == NULL) - { - pResolvedItfMT = pItfMT; - // Let ResolveRedirectedType convert IDictionary/IList to the corresponding WinRT type as usual - } - - if (WinRTInterfaceRedirector::ResolveRedirectedInterface(pResolvedItfMT, &redirectedInterfaceIndex)) - { - TypeHandle th = WinRTInterfaceRedirector::GetWinRTTypeForRedirectedInterfaceIndex(redirectedInterfaceIndex); - - if (th.HasInstantiation()) - { - *ppNewItfMT1 = th.Instantiate(pResolvedItfMT->GetInstantiation()).GetMethodTable(); - if (pItfMT->CanCastToInterface(MscorlibBinder::GetClass(CLASS__IENUMERABLE))) - { - redirectionKind = InterfaceRedirection_IEnumerable; - } - else - { - _ASSERTE(!fChosenIDictionary); - redirectionKind = InterfaceRedirection_Other; - } - } - else - { - // pItfMT is a non-generic redirected interface - for compat reasons do QI for the interface first, - // and if it fails, use redirection - *ppNewItfMT1 = pItfMT; - *ppNewItfMT2 = th.GetMethodTable(); - redirectionKind = InterfaceRedirection_Other_RetryOnFailure; - } - } - - if (fChosenIDictionary) - { - // pItfMT is the ambiguous ICollection> and *ppNewItfMT1 at this point is the - // corresponding IMap, now we are going to assign IVector> to *ppNewItfMT2 - pResolvedItfMT = ResolveICollectionInterface(pItfMT, FALSE, NULL); - - VERIFY(WinRTInterfaceRedirector::ResolveRedirectedInterface(pResolvedItfMT, &redirectedInterfaceIndex)); - TypeHandle th = WinRTInterfaceRedirector::GetWinRTTypeForRedirectedInterfaceIndex(redirectedInterfaceIndex); - - *ppNewItfMT2 = th.Instantiate(pItfMT->GetInstantiation()).GetMethodTable(); - redirectionKind = InterfaceRedirection_IEnumerable_RetryOnFailure; - } - - if (redirectionKind != InterfaceRedirection_None) - { - return redirectionKind; - } - - if (WinRTDelegateRedirector::ResolveRedirectedDelegate(pItfMT, &redirectedInterfaceIndex)) - { - TypeHandle th = TypeHandle(WinRTDelegateRedirector::GetWinRTTypeForRedirectedDelegateIndex(redirectedInterfaceIndex)); - - if (pItfMT->HasInstantiation()) - { - th = th.Instantiate(pItfMT->GetInstantiation()); - } - - *ppNewItfMT1 = th.GetMethodTable(); - return InterfaceRedirection_Other; - } - } - - *ppNewItfMT1 = pItfMT; - return InterfaceRedirection_None; -} - -#ifndef CROSSGEN_COMPILE -//----------------------------------------------------------------- -// Returns a known working IEnumerable::GetEnumerator to be used in lieu of the non-generic -// IEnumerable::GetEnumerator. -MethodDesc *RCW::GetGetEnumeratorMethod() -{ - CONTRACTL - { - THROWS; - GC_TRIGGERS; - MODE_ANY; - } - CONTRACTL_END; - - if (m_pAuxiliaryData == NULL || m_pAuxiliaryData->m_pGetEnumeratorMethod == NULL) - { - MethodTable *pClsMT; - { - GCX_COOP(); - pClsMT = GetExposedObject()->GetMethodTable(); - } - - SetGetEnumeratorMethod(pClsMT); - } - - return (m_pAuxiliaryData == NULL ? NULL : m_pAuxiliaryData->m_pGetEnumeratorMethod); -} - -//----------------------------------------------------------------- -// Sets the first "known" GetEnumerator method on the RCW if not set already. -void RCW::SetGetEnumeratorMethod(MethodTable *pMT) -{ - CONTRACTL - { - THROWS; - GC_TRIGGERS; - MODE_ANY; - } - CONTRACTL_END; - - if (m_pAuxiliaryData != NULL && m_pAuxiliaryData->m_pGetEnumeratorMethod != NULL) - return; - - // Retrieve cached GetEnumerator method or compute the right one for this pMT - MethodDesc *pMD = GetOrComputeGetEnumeratorMethodForType(pMT); - - if (pMD != NULL) - { - // We successfully got a GetEnumerator method - cache it in the RCW - // We can have multiple casts going on concurrently, make sure that - // the result of this method is stable. - InterlockedCompareExchangeT(&GetOrCreateAuxiliaryData()->m_pGetEnumeratorMethod, pMD, NULL); - } -} - -// Retrieve cached GetEnumerator method or compute the right one for a specific type -MethodDesc *RCW::GetOrComputeGetEnumeratorMethodForType(MethodTable *pMT) -{ - CONTRACTL - { - THROWS; - GC_TRIGGERS; - MODE_ANY; - } - CONTRACTL_END; - - MethodDesc *pMD = NULL; - - RCWPerTypeData *pData = pMT->GetRCWPerTypeData(); - if (pData != NULL) - { - if ((pData->m_dwFlags & RCWPerTypeData::GetEnumeratorInited) == 0) - { - pData->m_pGetEnumeratorMethod = ComputeGetEnumeratorMethodForType(pMT); - FastInterlockOr(&pData->m_dwFlags, RCWPerTypeData::GetEnumeratorInited); - } - - pMD = pData->m_pGetEnumeratorMethod; - } - else - { - pMD = ComputeGetEnumeratorMethodForType(pMT); - } - - return pMD; -} - -// Compute the first GetEnumerator for a specific type -MethodDesc *RCW::ComputeGetEnumeratorMethodForType(MethodTable *pMT) -{ - CONTRACTL - { - THROWS; - GC_TRIGGERS; - MODE_ANY; - } - CONTRACTL_END; - - MethodDesc *pMD = ComputeGetEnumeratorMethodForTypeInternal(pMT); - - // Walk the interface impl and use these interfaces to compute - MethodTable::InterfaceMapIterator it = pMT->IterateInterfaceMap(); - while (pMD == NULL && it.Next()) - { - pMT = it.GetInterface(); - pMD = GetOrComputeGetEnumeratorMethodForType(pMT); - } - - return pMD; -} - -// Get the GetEnumerator method for IEnumerable or IIterable -MethodDesc *RCW::ComputeGetEnumeratorMethodForTypeInternal(MethodTable *pMT) -{ - CONTRACTL - { - THROWS; - GC_TRIGGERS; - MODE_ANY; - } - CONTRACTL_END; - - if (!pMT->HasSameTypeDefAs(MscorlibBinder::GetExistingClass(CLASS__IENUMERABLEGENERIC))) - { - // If we have an IIterable, we want to get the enumerator for the equivalent - // instantiation of IEnumerable - if (pMT->HasSameTypeDefAs(MscorlibBinder::GetClass(CLASS__IITERABLE))) - { - TypeHandle thEnumerable = TypeHandle(MscorlibBinder::GetExistingClass(CLASS__IENUMERABLEGENERIC)); - pMT = thEnumerable.Instantiate(pMT->GetInstantiation()).GetMethodTable(); - } - else - { - return NULL; - } - } - - MethodDesc *pMD = pMT->GetMethodDescForSlot(0); - _ASSERTE(strcmp(pMD->GetName(), "GetEnumerator") == 0); - - if (pMD->IsSharedByGenericInstantiations()) - { - pMD = MethodDesc::FindOrCreateAssociatedMethodDesc( - pMD, - pMT, - FALSE, // forceBoxedEntryPoint - Instantiation(), // methodInst - FALSE, // allowInstParam - TRUE); // forceRemotableMethod - } - - return pMD; -} - - -//----------------------------------------------------------------- -// Notifies the RCW of an interface that is known to be supported by the COM object. -// pItfMT is the type which the object directly supports, originalInst is the instantiation -// that we asked for. I.e. we know that the object supports pItfMT via -// variance because the QI for IID(pItfMT) succeeded. -void RCW::SetSupportedInterface(MethodTable *pItfMT, Instantiation originalInst) -{ - CONTRACTL - { - THROWS; - GC_TRIGGERS; - MODE_ANY; - } - CONTRACTL_END; - - BOOL fIsEnumerable = (pItfMT->HasSameTypeDefAs(MscorlibBinder::GetExistingClass(CLASS__IENUMERABLEGENERIC)) || - pItfMT->HasSameTypeDefAs(MscorlibBinder::GetClass(CLASS__IITERABLE))); - - if (fIsEnumerable || pItfMT->HasSameTypeDefAs(MscorlibBinder::GetExistingClass(CLASS__IREADONLYLISTGENERIC)) || - pItfMT->HasSameTypeDefAs(MscorlibBinder::GetClass(CLASS__IVECTORVIEW))) - { - WinRTInterfaceRedirector::WinRTLegalStructureBaseType baseType; - if (!originalInst.IsEmpty()) - { - // use the original instantiation if available - baseType = WinRTInterfaceRedirector::GetStructureBaseType(originalInst); - } - else - { - baseType = WinRTInterfaceRedirector::GetStructureBaseType(pItfMT->GetInstantiation()); - } - - switch (baseType) - { - case WinRTInterfaceRedirector::BaseType_Object: - { - OBJECTHANDLE *pohHandleField = fIsEnumerable ? - &GetOrCreateAuxiliaryData()->m_ohObjectVariantCallTarget_IEnumerable : - &GetOrCreateAuxiliaryData()->m_ohObjectVariantCallTarget_IReadOnlyList; - - if (*pohHandleField != NULL) - { - // we've already established the behavior so we can skip the code below - break; - } - - if (!originalInst.IsEmpty()) - { - MethodTable *pInstArgMT = pItfMT->GetInstantiation()[0].GetMethodTable(); - - if (pInstArgMT == g_pStringClass) - { - // We are casting the RCW to IEnumerable or IReadOnlyList - we special-case this common case - // so we don't have to create the delegate. - FastInterlockCompareExchangePointer(pohHandleField, VARIANCE_STUB_TARGET_USE_STRING, NULL); - } - else if (pInstArgMT == g_pExceptionClass || - pInstArgMT == MscorlibBinder::GetClass(CLASS__TYPE) || - pInstArgMT->IsArray() || - pInstArgMT->IsDelegate()) - { - // We are casting the RCW to IEnumerable or IReadOnlyList where T is Type/Exception/an array/a delegate - // i.e. an unbounded set of types. We'll create a delegate pointing to the right stub and cache it on the RCW - // so we can handle the calls via GetEnumerator/Indexer_Get as fast as possible. - - MethodDesc *pTargetMD = MscorlibBinder::GetMethod(fIsEnumerable ? - METHOD__ITERABLE_TO_ENUMERABLE_ADAPTER__GET_ENUMERATOR_STUB : - METHOD__IVECTORVIEW_TO_IREADONLYLIST_ADAPTER__INDEXER_GET); - - pTargetMD = MethodDesc::FindOrCreateAssociatedMethodDesc( - pTargetMD, - pTargetMD->GetMethodTable(), - FALSE, // forceBoxedEntryPoint - pItfMT->GetInstantiation(), // methodInst - FALSE, // allowInstParam - TRUE); // forceRemotableMethod - - MethodTable *pMT = MscorlibBinder::GetClass(fIsEnumerable ? - CLASS__GET_ENUMERATOR_DELEGATE : - CLASS__INDEXER_GET_DELEGATE); - - pMT = TypeHandle(pMT).Instantiate(pItfMT->GetInstantiation()).AsMethodTable(); - - GCX_COOP(); - - DELEGATEREF pDelObj = NULL; - GCPROTECT_BEGIN(pDelObj); - - pDelObj = (DELEGATEREF)AllocateObject(pMT); - pDelObj->SetTarget(GetExposedObject()); - pDelObj->SetMethodPtr(pTargetMD->GetMultiCallableAddrOfCode()); - - OBJECTHANDLEHolder oh = GetAppDomain()->CreateHandle(pDelObj); - if (FastInterlockCompareExchangePointer(pohHandleField, oh, NULL) == NULL) - { - oh.SuppressRelease(); - } - - GCPROTECT_END(); - } - } - - // the default is "use T", i.e. handle the call as normal - if (*pohHandleField == NULL) - { - FastInterlockCompareExchangePointer(pohHandleField, VARIANCE_STUB_TARGET_USE_T, NULL); - } - break; - } - - case WinRTInterfaceRedirector::BaseType_IEnumerable: - case WinRTInterfaceRedirector::BaseType_IEnumerableOfChar: - { - // The only WinRT-legal type that implements IEnumerable or IEnumerable> or - // IReadOnlyList or IReadOnlyList> AND is not an IInspectable on the WinRT - // side is string. We'll use a couple of flags here since the number of options is small. - - InterfaceVarianceBehavior varianceBehavior = (fIsEnumerable ? IEnumerableSupported : IReadOnlyListSupported); - - if (!originalInst.IsEmpty()) - { - MethodTable *pInstArgMT = pItfMT->GetInstantiation()[0].GetMethodTable(); - if (pInstArgMT == g_pStringClass) - { - varianceBehavior = (InterfaceVarianceBehavior) - (varianceBehavior | (fIsEnumerable ? IEnumerableSupportedViaStringInstantiation : IReadOnlyListSupportedViaStringInstantiation)); - } - - RCWAuxiliaryData::RCWAuxFlags newAuxFlags = { 0 }; - - if (baseType == WinRTInterfaceRedirector::BaseType_IEnumerable) - { - newAuxFlags.m_InterfaceVarianceBehavior_OfIEnumerable = varianceBehavior; - } - else - { - _ASSERTE(baseType == WinRTInterfaceRedirector::BaseType_IEnumerableOfChar); - newAuxFlags.m_InterfaceVarianceBehavior_OfIEnumerableOfChar = varianceBehavior; - } - - RCWAuxiliaryData *pAuxData = GetOrCreateAuxiliaryData(); - FastInterlockOr(&pAuxData->m_AuxFlags.m_dwFlags, newAuxFlags.m_dwFlags); - } - } - } - } -} - -// Performs QI for the given interface, optionally instantiating it with the given generic args. -HRESULT RCW::CallQueryInterface(MethodTable *pMT, Instantiation inst, IID *piid, IUnknown **ppUnk) -{ - CONTRACTL + CONTRACTL { THROWS; GC_TRIGGERS; @@ -3718,156 +2589,14 @@ HRESULT RCW::CallQueryInterface(MethodTable *pMT, Instantiation inst, IID *piid, CONTRACTL_END; HRESULT hr; - MethodTable *pCastToMT = pMT; - MethodTable *pCOMItfMT = NULL; - InterfaceRedirectionKind redirection = InterfaceRedirection_None; if (!inst.IsEmpty()) { pMT = TypeHandle(pMT).Instantiate(inst).GetMethodTable(); } - do - { - redirection = GetInterfaceForQI(pMT, &pCOMItfMT); - - if (redirection == InterfaceRedirection_UnresolvedIEnumerable) - { - // We just say no in this case. If we threw an exception, we would make the "as" operator - // throwing which would be ECMA violation. - return E_NOINTERFACE; - } - - // To avoid throwing BadImageFormatException later in ComputeGuidForGenericTypes we must fail early if this is a generic type and not a legal WinRT type. - if (pCOMItfMT->SupportsGenericInterop(TypeHandle::Interop_NativeToManaged, MethodTable::modeProjected) && !pCOMItfMT->IsLegalNonArrayWinRTType()) - { - return E_NOINTERFACE; - } - else - { - // Retrieve the IID of the interface. - pCOMItfMT->GetGuid(piid, TRUE); - } - - // QI for the interface. - hr = SafeQueryInterfaceRemoteAware(*piid, ppUnk); - } - while (hr == E_NOINTERFACE && // Terminate the loop if the QI failed for some other reasons (for example, context transition failure) - (redirection == InterfaceRedirection_IEnumerable_RetryOnFailure || redirection == InterfaceRedirection_Other_RetryOnFailure)); - - if (SUCCEEDED(hr)) - { - if (redirection == InterfaceRedirection_IEnumerable) - { - // remember the first IEnumerable interface we successfully QI'ed for - SetGetEnumeratorMethod(pMT); - } - - // remember successful QI's for interesting interfaces passing the original instantiation so we know that variance was involved - SetSupportedInterface(pCOMItfMT, pCastToMT->GetInstantiation()); - } - - return hr; -} - -// Performs QI for interfaces that are castable to pMT using co-/contra-variance. -HRESULT RCW::CallQueryInterfaceUsingVariance(MethodTable *pMT, IUnknown **ppUnk) -{ - CONTRACTL - { - THROWS; - GC_TRIGGERS; - MODE_ANY; - } - CONTRACTL_END; - - HRESULT hr = E_NOINTERFACE; - - // see if pMT is an interface with variance, if not we return NULL - MethodTable *pVariantMT = GetVariantMethodTable(pMT); - - if (pVariantMT != NULL) - { - MethodTable *pItfMT = NULL; - IID variantIid; - - MethodTable *pClassMT; - - { - GCX_COOP(); - pClassMT = GetExposedObject()->GetMethodTable(); - } - - // Try interfaces that we know about from metadata - if (pClassMT != NULL && pClassMT != g_pBaseCOMObject) - { - MethodTable::InterfaceMapIterator it = pClassMT->IterateInterfaceMap(); - while (FAILED(hr) && it.Next()) - { - pItfMT = GetVariantMethodTable(it.GetInterface()); - if (pItfMT != NULL && pItfMT->CanCastByVarianceToInterfaceOrDelegate(pVariantMT, NULL)) - { - hr = CallQueryInterface(pMT, pItfMT->GetInstantiation(), &variantIid, ppUnk); - } - } - } - - // Then try the interface pointer cache - CachedInterfaceEntryIterator it = IterateCachedInterfacePointers(); - while (FAILED(hr) && it.Next()) - { - MethodTable *pCachedItfMT = (MethodTable *)it.GetEntry()->m_pMT; - if (pCachedItfMT != NULL) - { - pItfMT = GetVariantMethodTable(pCachedItfMT); - if (pItfMT != NULL && pItfMT->CanCastByVarianceToInterfaceOrDelegate(pVariantMT, NULL)) - { - hr = CallQueryInterface(pMT, pItfMT->GetInstantiation(), &variantIid, ppUnk); - } - - // The cached interface may not support variance, but one of its base interfaces can - if (FAILED(hr)) - { - MethodTable::InterfaceMapIterator it = pCachedItfMT->IterateInterfaceMap(); - while (FAILED(hr) && it.Next()) - { - pItfMT = GetVariantMethodTable(it.GetInterface()); - if (pItfMT != NULL && pItfMT->CanCastByVarianceToInterfaceOrDelegate(pVariantMT, NULL)) - { - hr = CallQueryInterface(pMT, pItfMT->GetInstantiation(), &variantIid, ppUnk); - } - } - } - } - } - - // If we still haven't succeeded, enumerate the variant interface cache - if (FAILED(hr) && m_pAuxiliaryData != NULL && m_pAuxiliaryData->m_prVariantInterfaces != NULL) - { - // make a copy of the cache under the lock - ArrayList rVariantInterfacesCopy; - { - CrstHolder ch(&m_pAuxiliaryData->m_VarianceCacheCrst); - - ArrayList::Iterator it = m_pAuxiliaryData->m_prVariantInterfaces->Iterate(); - while (it.Next()) - { - rVariantInterfacesCopy.Append(it.GetElement()); - } - } - - ArrayList::Iterator it = rVariantInterfacesCopy.Iterate(); - while (FAILED(hr) && it.Next()) - { - pItfMT = (MethodTable *)it.GetElement(); - if (pItfMT->CanCastByVarianceToInterfaceOrDelegate(pVariantMT, NULL)) - { - hr = CallQueryInterface(pMT, pItfMT->GetInstantiation(), &variantIid, ppUnk); - } - } - } - } - + pMT->GetGuid(piid, TRUE); + hr = SafeQueryInterfaceRemoteAware(*piid, ppUnk); return hr; } @@ -3933,31 +2662,10 @@ IUnknown* RCW::GetComIPForMethodTableFromCache(MethodTable* pMT) // First, try to QI for the interface that we were asked for hr = CallQueryInterface(pMT, Instantiation(), &iid, &pUnk); - // If that failed and the interface has variance, we'll try to find another instantiation - bool fVarianceUsed = false; - if (FAILED(hr)) - { - hr = CallQueryInterfaceUsingVariance(pMT, &pUnk); - if (pUnk != NULL) - { - fVarianceUsed = true; - } - } - if (pUnk == NULL) RETURN NULL; - bool fAllowOutOfContextCache = true; - if (!pMT->IsProjectedFromWinRT() && !pMT->IsWinRTRedirectedInterface(TypeHandle::Interop_ManagedToNative) && !pMT->IsWinRTRedirectedDelegate()) - { - // This is not a WinRT interface and we could in theory use the out-of-context auxiliary cache, - // at worst we would just do - // fAllowOutOfContextCache = !IsURTAggregated() - // however such a change has some breaking potential (COM proxies would live much longer) and is - // considered to risky for an in-place release. - - fAllowOutOfContextCache = false; - } + bool fAllowOutOfContextCache = false; // try to cache the interface pointer in the inline cache. This cache can only store interface pointers // returned from QI's in the same context where we created the RCW. @@ -3974,11 +2682,6 @@ IUnknown* RCW::GetComIPForMethodTableFromCache(MethodTable* pMT) // Get an extra addref to hold this reference alive in our cache cbRef = SafeAddRef(pUnk); LogInteropAddRef(pUnk, cbRef, "RCW::GetComIPForMethodTableFromCache: Addref because storing pUnk in InterfaceEntry cache"); - - // Notify Jupiter we have done a AddRef - // We should do this *after* we made a AddRef because we should never - // be in a state where report refs > actual refs - RCWWalker::AfterInterfaceAddRef(this); } fInterfaceCached = true; @@ -3999,31 +2702,11 @@ IUnknown* RCW::GetComIPForMethodTableFromCache(MethodTable* pMT) // Get an extra addref to hold this reference alive in our cache cbRef = SafeAddRef(pUnk); LogInteropAddRef(pUnk, cbRef, "RCW::GetComIPForMethodTableFromCache: Addref because storing pUnk in the auxiliary interface pointer cache"); - - // Notify Jupiter we have done a AddRef - // We should do this *after* we made a AddRef because we should never - // be in a state where report refs > actual refs - RCWWalker::AfterInterfaceAddRef(this); } fInterfaceCached = true; } - // Make sure we cache successful QI's for variant interfaces. This is so we can cast an RCW for - // example to IEnumerable if we previously successfully QI'ed for IEnumerable. We - // only need to do this if we actually didn't use variance for this QI. - if (!fVarianceUsed) - { - MethodTable *pVariantMT = GetVariantMethodTable(pMT); - - // We can also skip the potentially expensive CacheVariantInterface call if we already inserted - // the variant interface into our interface pointer cache. - if (pVariantMT != NULL && (!fInterfaceCached || pVariantMT != pMT)) - { - GetOrCreateAuxiliaryData()->CacheVariantInterface(pVariantMT); - } - } - RETURN pUnk; } @@ -4181,19 +2864,12 @@ HRESULT __stdcall RCW::ReleaseAllInterfacesCallBack(LPVOID pData) if (pCurrentCtxCookie == NULL || pCurrentCtxCookie == it.GetCtxCookie() || pWrap->IsFreeThreaded()) { - // Notify Jupiter we are about to do a Release() for every cached interface pointer - // This needs to be made before call Release because we should never be in a - // state that we report more than the actual ref - RCWWalker::BeforeInterfaceRelease(pWrap); - // make sure we never try to clean this up again pEntry->Free(); SafeReleasePreemp(pUnk, pWrap); } else { - _ASSERTE(!pWrap->IsJupiterObject()); - // Retrieve the addref'ed context entry that the wrapper lives in. CtxEntryHolder pCtxEntry = it.GetCtxEntry(); @@ -4234,11 +2910,6 @@ void RCW::ReleaseAllInterfaces() RCW_VTABLEPTR(this); - // Notify Jupiter we are about to do a Release() for IUnknown - // This needs to be made before call Release because we should never be in a - // state that we report more than the actual ref - RCWWalker::BeforeInterfaceRelease(this); - // Release the pUnk held by IUnkEntry m_UnkEntry.ReleaseInterface(this); @@ -4252,11 +2923,6 @@ void RCW::ReleaseAllInterfaces() if (!m_aInterfaceEntries[i].IsFree()) { - // Notify Jupiter we are about to do a Release() for every cached interface pointer - // This needs to be made before call Release because we should never be in a - // state that we report more than the actual ref - RCWWalker::BeforeInterfaceRelease(this); - DWORD cbRef = SafeReleasePreemp(m_aInterfaceEntries[i].m_pUnknown, this); LogInteropRelease(m_aInterfaceEntries[i].m_pUnknown, cbRef, "RCW::ReleaseAllInterfaces: Releasing ref from InterfaceEntry table"); } @@ -4321,227 +2987,51 @@ bool RCW::SupportsMngStdInterface(MethodTable *pItfMT) return true; } else - { - // - // Handle casts to IEnumerable. - // - - // If the requested interface is IEnumerable then we need to check to see if the - // COM object implements IDispatch and has a member with DISPID_NEWENUM. - if (pItfMT == MscorlibBinder::GetExistingClass(CLASS__IENUMERABLE)) - { - SafeComHolder pDisp = NULL; - if (!AppX::IsAppXProcess()) - { - // Get the IDispatch on the current thread. - pDisp = GetIDispatch(); - } - if (pDisp) - { - DISPPARAMS DispParams = {0, 0, NULL, NULL}; - VariantHolder VarResult; - - // Initialize the return variant. - SafeVariantInit(&VarResult); - - HRESULT hr = E_FAIL; - { - // We are about to make a call to COM so switch to preemptive GC. - GCX_PREEMP(); - - // Call invoke with DISPID_NEWENUM to see if such a member exists. - hr = pDisp->Invoke( - DISPID_NEWENUM, - IID_NULL, - LOCALE_USER_DEFAULT, - DISPATCH_METHOD | DISPATCH_PROPERTYGET, - &DispParams, - &VarResult, - NULL, - NULL - ); - } - - // If the invoke succeeded then the component has a member DISPID_NEWENUM - // so we can expose it as an IEnumerable. - if (SUCCEEDED(hr)) - return true; - } - } - } - - return false; -} - -//--------------------------------------------------------------------- -// Determines whether a call through the given interface should use new -// WinRT interop (as opposed to classic COM). -TypeHandle::CastResult RCW::SupportsWinRTInteropInterfaceNoGC(MethodTable *pItfMT) -{ - CONTRACTL - { - NOTHROW; - GC_NOTRIGGER; - MODE_ANY; - } - CONTRACTL_END; - - WinMDAdapter::RedirectedTypeIndex index; - - // @TODO: Make this nicer? - RedirectionBehavior redirectionBehavior; - if (pItfMT == MscorlibBinder::GetExistingClass(CLASS__IENUMERABLE)) - redirectionBehavior = (RedirectionBehavior)m_Flags.m_RedirectionBehavior_IEnumerable; - else if (pItfMT == MscorlibBinder::GetExistingClass(CLASS__ICOLLECTION)) - redirectionBehavior = (RedirectionBehavior)m_Flags.m_RedirectionBehavior_ICollection; - else if (pItfMT == MscorlibBinder::GetExistingClass(CLASS__ILIST)) - redirectionBehavior = (RedirectionBehavior)m_Flags.m_RedirectionBehavior_IList; - else if (WinRTInterfaceRedirector::ResolveRedirectedInterface(pItfMT, &index) && index == WinMDAdapter::RedirectedTypeIndex_System_Collections_Specialized_INotifyCollectionChanged) - redirectionBehavior = (RedirectionBehavior)m_Flags.m_RedirectionBehavior_INotifyCollectionChanged; - else if (WinRTInterfaceRedirector::ResolveRedirectedInterface(pItfMT, &index) && index == WinMDAdapter::RedirectedTypeIndex_System_ComponentModel_INotifyPropertyChanged) - redirectionBehavior = (RedirectionBehavior)m_Flags.m_RedirectionBehavior_INotifyPropertyChanged; - else if (WinRTInterfaceRedirector::ResolveRedirectedInterface(pItfMT, &index) && index == WinMDAdapter::RedirectedTypeIndex_System_Windows_Input_ICommand) - redirectionBehavior = (RedirectionBehavior)m_Flags.m_RedirectionBehavior_ICommand; - else if (WinRTInterfaceRedirector::ResolveRedirectedInterface(pItfMT, &index) && index == WinMDAdapter::RedirectedTypeIndex_System_IDisposable) - redirectionBehavior = (RedirectionBehavior)m_Flags.m_RedirectionBehavior_IDisposable; - else - { - UNREACHABLE_MSG("Unknown redirected interface"); - } - - if ((redirectionBehavior & RedirectionBehaviorComputed) == 0) - { - // we don't know yet what the behavior should be - return TypeHandle::MaybeCast; - } - - return ((redirectionBehavior & RedirectionBehaviorEnabled) == 0 ? - TypeHandle::CannotCast : - TypeHandle::CanCast); -} - -//--------------------------------------------------------------------- -// This is a GC-triggering variant of code:SupportsWinRTInteropInterfaceNoGC. -bool RCW::SupportsWinRTInteropInterface(MethodTable *pItfMT) -{ - CONTRACTL - { - THROWS; - GC_TRIGGERS; - MODE_COOPERATIVE; - } - CONTRACTL_END; - - TypeHandle::CastResult result = SupportsWinRTInteropInterfaceNoGC(pItfMT); - switch (result) - { - case TypeHandle::CanCast: return true; - case TypeHandle::CannotCast: return false; - } - - WinMDAdapter::RedirectedTypeIndex index; - bool fLegacySupported; - - // @TODO: Make this nicer? - RedirectionBehavior redirectionBehavior; - RCWFlags newFlags = { 0 }; - - if (pItfMT == MscorlibBinder::GetExistingClass(CLASS__IENUMERABLE)) - { - redirectionBehavior = ComputeRedirectionBehavior(pItfMT, &fLegacySupported); - newFlags.m_RedirectionBehavior_IEnumerable = redirectionBehavior; - newFlags.m_RedirectionBehavior_IEnumerable_LegacySupported = fLegacySupported; - } - else if (pItfMT == MscorlibBinder::GetExistingClass(CLASS__ICOLLECTION)) - { - redirectionBehavior = ComputeRedirectionBehavior(pItfMT, &fLegacySupported); - newFlags.m_RedirectionBehavior_ICollection = redirectionBehavior; - } - else if (pItfMT == MscorlibBinder::GetExistingClass(CLASS__ILIST)) - { - redirectionBehavior = ComputeRedirectionBehavior(pItfMT, &fLegacySupported); - newFlags.m_RedirectionBehavior_IList = redirectionBehavior; - } - else if (WinRTInterfaceRedirector::ResolveRedirectedInterface(pItfMT, &index) && index == WinMDAdapter::RedirectedTypeIndex_System_Collections_Specialized_INotifyCollectionChanged) - { - redirectionBehavior = ComputeRedirectionBehavior(pItfMT, &fLegacySupported); - newFlags.m_RedirectionBehavior_INotifyCollectionChanged = redirectionBehavior; - } - else if (WinRTInterfaceRedirector::ResolveRedirectedInterface(pItfMT, &index) && index == WinMDAdapter::RedirectedTypeIndex_System_ComponentModel_INotifyPropertyChanged) - { - redirectionBehavior = ComputeRedirectionBehavior(pItfMT, &fLegacySupported); - newFlags.m_RedirectionBehavior_INotifyPropertyChanged = redirectionBehavior; - } - else if (WinRTInterfaceRedirector::ResolveRedirectedInterface(pItfMT, &index) && index == WinMDAdapter::RedirectedTypeIndex_System_Windows_Input_ICommand) - { - redirectionBehavior = ComputeRedirectionBehavior(pItfMT, &fLegacySupported); - newFlags.m_RedirectionBehavior_ICommand = redirectionBehavior; - } - else if (WinRTInterfaceRedirector::ResolveRedirectedInterface(pItfMT, &index) && index == WinMDAdapter::RedirectedTypeIndex_System_IDisposable) - { - redirectionBehavior = ComputeRedirectionBehavior(pItfMT, &fLegacySupported); - newFlags.m_RedirectionBehavior_IDisposable = redirectionBehavior; - } - else - { - UNREACHABLE_MSG("Unknown redirected interface"); - } - - // Use interlocked operation so we don't race with other threads trying to set some other flags on the RCW. - // Note that since we are in cooperative mode, we don't race with RCWCache::DetachWrappersWorker here. - FastInterlockOr(&m_Flags.m_dwFlags, newFlags.m_dwFlags); - - _ASSERTE((redirectionBehavior & RedirectionBehaviorComputed) != 0); - return ((redirectionBehavior & RedirectionBehaviorEnabled) != 0); -} - -//--------------------------------------------------------------------- -// Computes the result of code:SupportsWinRTInteropInterface. -RCW::RedirectionBehavior RCW::ComputeRedirectionBehavior(MethodTable *pItfMT, bool *pfLegacySupported) -{ - CONTRACTL - { - THROWS; - GC_TRIGGERS; - MODE_COOPERATIVE; - } - CONTRACTL_END; - - *pfLegacySupported = false; + { + // + // Handle casts to IEnumerable. + // - // @TODO: It may be possible to take advantage of metadata (e.g. non-WinRT ComImport class says it implements ICollection -> use classic COM) - // and/or the interface cache but for now we'll just QI. + // If the requested interface is IEnumerable then we need to check to see if the + // COM object implements IDispatch and has a member with DISPID_NEWENUM. + if (pItfMT == MscorlibBinder::GetClass(CLASS__IENUMERABLE)) + { + SafeComHolder pDisp = GetIDispatch(); + if (pDisp) + { + DISPPARAMS DispParams = {0, 0, NULL, NULL}; + VariantHolder VarResult; - IID iid; - pItfMT->GetGuid(&iid, TRUE, TRUE); + // Initialize the return variant. + SafeVariantInit(&VarResult); - SafeComHolder pUnk; - if (SUCCEEDED(SafeQueryInterfaceRemoteAware(iid, &pUnk))) - { - // if the object supports the legacy COM interface we don't use redirection - *pfLegacySupported = true; - return RedirectionBehaviorComputed; - } + HRESULT hr = E_FAIL; + { + // We are about to make a call to COM so switch to preemptive GC. + GCX_PREEMP(); - if (SupportsMngStdInterface(pItfMT)) - { - // if the object supports the corresponding "managed std" interface we don't use redirection - *pfLegacySupported = true; - return RedirectionBehaviorComputed; - } + // Call invoke with DISPID_NEWENUM to see if such a member exists. + hr = pDisp->Invoke( + DISPID_NEWENUM, + IID_NULL, + LOCALE_USER_DEFAULT, + DISPATCH_METHOD | DISPATCH_PROPERTYGET, + &DispParams, + &VarResult, + NULL, + NULL + ); + } - COMOBJECTREF oref = GetExposedObject(); - if (ComObject::SupportsInterface(oref, pItfMT)) - { - // the cast succeeded but we know that the legacy COM interface is not implemented - // -> we know for sure that the object supports the WinRT redirected interface - return (RedirectionBehavior)(RedirectionBehaviorComputed | RedirectionBehaviorEnabled); + // If the invoke succeeded then the component has a member DISPID_NEWENUM + // so we can expose it as an IEnumerable. + if (SUCCEEDED(hr)) + return true; + } + } } - // The object does not support anything which means that we are in a failure case and an - // exception will be thrown. For back compat we want the exception message to include the - // classic COM IID so we'll return the "no redirection" result. - return RedirectionBehaviorComputed; + return false; } //-------------------------------------------------------------------------------- @@ -4665,20 +3155,17 @@ BOOL ComObject::SupportsInterface(OBJECTREF oref, MethodTable* pIntfTable) if (!pMT->FindDynamicallyAddedInterface(pIntfTable)) { // It's not there. - if (!pMT->IsWinRTObjectType()) + // Check if the object supports all of these interfaces only if this is a classic COM interop + // scenario. This is a perf optimization (no need to QI for base interfaces if we don't really + // need them just yet) and also has a usability aspect. If this SupportsInterface call failed + // because one of the base interfaces is not supported, the exception we'd throw would contain + // only the name of the "top level" interface which would confuse the developer. + MethodTable::InterfaceMapIterator it = pIntfTable->IterateInterfaceMap(); + while (it.Next()) { - // Check if the object supports all of these interfaces only if this is a classic COM interop - // scenario. This is a perf optimization (no need to QI for base interfaces if we don't really - // need them just yet) and also has a usability aspect. If this SupportsInterface call failed - // because one of the base interfaces is not supported, the exception we'd throw would contain - // only the name of the "top level" interface which would confuse the developer. - MethodTable::InterfaceMapIterator it = pIntfTable->IterateInterfaceMap(); - while (it.Next()) - { - bSupportsItf = Object::SupportsInterface(oref, it.GetInterface()); - if (!bSupportsItf) - break; - } + bSupportsItf = Object::SupportsInterface(oref, it.GetInterface()); + if (!bSupportsItf) + break; } // If the object supports all these interfaces, attempt to add the interface table @@ -4749,39 +3236,17 @@ void ComObject::ThrowInvalidCastException(OBJECTREF *pObj, MethodTable *pCastToM pRCW.Init(*pObj); // Retrieve the IID of the interface. - MethodTable *pCOMItfMT = NULL; - if (pRCW->GetInterfaceForQI(thCastTo.GetMethodTable(), &pCOMItfMT) == RCW::InterfaceRedirection_UnresolvedIEnumerable) - { - // A special exception message for the case where we are unable to figure out the - // redirected interface because we haven't seen a cast to a generic IEnumerable yet. - COMPlusThrow(kInvalidCastException, IDS_EE_WINRT_IENUMERABLE_BAD_CAST); - } + MethodTable *pCOMItfMT = thCastTo.GetMethodTable(); - if (pCOMItfMT->IsProjectedFromWinRT()) - { - // pCOMItfMT could be a generic WinRT-illegal interface in which case GetGuid would throw a confusing BadImageFormatException - // so we swallow the exception and throw the generic InvalidCastException instead - if (FAILED(pCOMItfMT->GetGuidNoThrow(&iid, FALSE))) - { - COMPlusThrow(kInvalidCastException, IDS_EE_CANNOTCAST, strComObjClassName.GetUnicode(), strCastToName.GetUnicode()); - } - } - else - { - // keep calling the throwing GetGuid for non-WinRT interfaces (back compat) - pCOMItfMT->GetGuid(&iid, TRUE); - } + // keep calling the throwing GetGuid (back compat) + pCOMItfMT->GetGuid(&iid, TRUE); // Query for the interface to determine the failure HRESULT. hr = pRCW->SafeQueryInterfaceRemoteAware(iid, (IUnknown**)&pItf); // If this function was called, it means the QI call failed in the past. If it // no longer fails now, we still need to throw, so throw a generic invalid cast exception. - if (SUCCEEDED(hr) || - // Also throw the generic exception if the QI failed with E_NOINTERFACE and this is - // a WinRT scenario - the user is very likely not interested in details like IID and - // HRESULT, they just want to get the "managed" experience. - (hr == E_NOINTERFACE && (thClass.GetMethodTable()->IsWinRTObjectType() || pCOMItfMT->IsProjectedFromWinRT()))) + if (SUCCEEDED(hr)) { COMPlusThrow(kInvalidCastException, IDS_EE_CANNOTCAST, strComObjClassName.GetUnicode(), strCastToName.GetUnicode()); } @@ -4848,13 +3313,6 @@ void ComObject::ThrowInvalidCastException(OBJECTREF *pObj, MethodTable *pCastToM // Validate that this function wasn't erroneously called. _ASSERTE(!thClass.CanCastTo(thCastTo)); - if (thClass.GetMethodTable()->IsWinRTObjectType() || thCastTo.IsProjectedFromWinRT() || thCastTo.GetMethodTable()->IsWinRTObjectType()) - { - // don't mention any "COM components" in the exception if we failed to cast a WinRT object or - // to a WinRT object, throw the simple generic InvalidCastException instead - COMPlusThrow(kInvalidCastException, IDS_EE_CANNOTCAST, strComObjClassName.GetUnicode(), strCastToName.GetUnicode()); - } - if (thCastTo.IsComObjectType()) { if (IsComObjectClass(thClass)) @@ -4959,396 +3417,6 @@ IUnknown *ComObject::GetComIPFromRCWThrowing(OBJECTREF *pObj, MethodTable* pIntf RETURN pIUnk; } - -// -// Create override information based on interface lookup -// -WinRTOverrideInfo::WinRTOverrideInfo(EEClass *pClass) -{ - CONTRACTL - { - THROWS; - GC_TRIGGERS; - MODE_COOPERATIVE; - PRECONDITION(CheckPointer(pClass)); - } - CONTRACTL_END; - - ::ZeroMemory(this, sizeof(WinRTOverrideInfo)); - - MethodTable *pMT = pClass->GetMethodTable(); - - _ASSERTE(IsTdClass(pClass->GetAttrClass())); - // - // Iterate through each implemented interface - // Note that the interface map is laid from parent to child - // So we start from the most derived class, and climb our way up to parent, instead of - // inspecting interface map directly - // - while (pMT != g_pBaseCOMObject) - { - MethodTable *pParentMT = pMT->GetParentMethodTable(); - unsigned dwParentInterfaces = 0; - if (pParentMT) - dwParentInterfaces = pParentMT->GetNumInterfaces(); - - DWORD dwFound = 0; - - // - // Scanning only current class only if the current class have more interface than parent - // - if (pMT->GetNumInterfaces() > dwParentInterfaces) - { - MethodTable::InterfaceMapIterator it = pMT->IterateInterfaceMapFrom(dwParentInterfaces); - while (!it.Finished()) - { - MethodTable *pImplementedIntfMT = it.GetInterface(); - - // Only check private interfaces as they are exclusive - if (IsTdNotPublic(pImplementedIntfMT->GetAttrClass()) && pImplementedIntfMT->IsProjectedFromWinRT()) - { - if (m_pToStringMD == NULL) - { - m_pToStringMD = MemberLoader::FindMethod( - pImplementedIntfMT, - "ToString", - &gsig_IM_RetStr); - if (m_pToStringMD != NULL) - dwFound++; - } - - if (m_pGetHashCodeMD == NULL) - { - m_pGetHashCodeMD = MemberLoader::FindMethod( - pImplementedIntfMT, - "GetHashCode", - &gsig_IM_RetInt); - if (m_pGetHashCodeMD != NULL) - dwFound++; - } - - if (m_pEqualsMD == NULL) - { - m_pEqualsMD = MemberLoader::FindMethod( - pImplementedIntfMT, - "Equals", - &gsig_IM_Obj_RetBool); - if (m_pEqualsMD != NULL) - dwFound++; - } - - if (dwFound == 3) - return; - } - - it.Next(); - } - } - - // - // Parent has no more interfaces (including parents of parent). We are done - // - if (dwParentInterfaces == 0) - break; - - pMT = pParentMT; - } -} - -// -// If WinRTOverrideInfo is not created, create one. Otherwise return existing one -// -WinRTOverrideInfo *WinRTOverrideInfo::GetOrCreateWinRTOverrideInfo(MethodTable *pMT) -{ - CONTRACT (WinRTOverrideInfo*) - { - THROWS; - GC_TRIGGERS; - MODE_ANY; - CAN_TAKE_LOCK; - PRECONDITION(CheckPointer(pMT)); - POSTCONDITION(CheckPointer(RETVAL, NULL_OK)); - } - CONTRACT_END; - - _ASSERTE(pMT != NULL); - - EEClass *pClass = pMT->GetClass(); - - // - // Retrieve the WinRTOverrideInfo from WinRT class factory - // It is kind of sub-optimal but saves a EEClass field - // - WinRTClassFactory *pClassFactory = GetComClassFactory(pMT)->AsWinRTClassFactory(); - - WinRTOverrideInfo *pOverrideInfo = pClassFactory->GetWinRTOverrideInfo(); - if (pOverrideInfo == NULL) - { - // - // Create the override information - // - NewHolder pNewOverrideInfo = new WinRTOverrideInfo(pClass); - - if (pNewOverrideInfo->m_pEqualsMD == NULL && - pNewOverrideInfo->m_pGetHashCodeMD == NULL && - pNewOverrideInfo->m_pToStringMD == NULL) - { - // Special optimization for where there is no override found - pMT->SetSkipWinRTOverride(); - - RETURN NULL; - } - else - { - if (pClassFactory->SetWinRTOverrideInfo(pNewOverrideInfo)) - { - // We win the race - pNewOverrideInfo.SuppressRelease(); - RETURN pNewOverrideInfo; - } - else - { - // Lost the race - retrieve again - RETURN pClassFactory->GetWinRTOverrideInfo(); - } - } - } - - RETURN pOverrideInfo; -} - -// -// Redirection for ToString -// -NOINLINE static MethodDesc *GetRedirectedToStringMDHelper(Object *pThisUNSAFE, MethodTable *pMT) -{ - FC_INNER_PROLOG(ComObject::GetRedirectedToStringMD); - - MethodDesc *pRetMD = NULL; - - // Creates helper frame for GetOrCreateWinRTOverrideInfo (which throws) - HELPER_METHOD_FRAME_BEGIN_RET_ATTRIB(Frame::FRAME_ATTR_EXACT_DEPTH|Frame::FRAME_ATTR_CAPTURE_DEPTH_2); - - WinRTOverrideInfo *pOverrideInfo = WinRTOverrideInfo::GetOrCreateWinRTOverrideInfo(pMT); - if (pOverrideInfo && pOverrideInfo->m_pToStringMD != NULL) - { - pRetMD = pOverrideInfo->m_pToStringMD; - } - - HELPER_METHOD_FRAME_END(); - - FC_INNER_EPILOG(); - - return pRetMD; -} - -FCIMPL1(MethodDesc *, ComObject::GetRedirectedToStringMD, Object *pThisUNSAFE) -{ - CONTRACTL - { - FCALL_CHECK; - PRECONDITION(CheckPointer(pThisUNSAFE)); - } - CONTRACTL_END; - - MethodTable *pMT = pThisUNSAFE->GetMethodTable(); - if (pMT->IsSkipWinRTOverride()) - return NULL; - - FC_INNER_RETURN(MethodDesc*, ::GetRedirectedToStringMDHelper(pThisUNSAFE, pMT)); -} -FCIMPLEND - -FCIMPL2(StringObject *, ComObject::RedirectToString, Object *pThisUNSAFE, MethodDesc *pToStringMD) -{ - CONTRACTL - { - FCALL_CHECK; - PRECONDITION(CheckPointer(pThisUNSAFE)); - } - CONTRACTL_END; - - OBJECTREF refThis = ObjectToOBJECTREF(pThisUNSAFE); - STRINGREF refString = NULL; - - HELPER_METHOD_FRAME_BEGIN_RET_2(refThis, refString); - - // Note that this has to be virtual. Consider this case - // - // interface INativeA - // { - - // string ToString(); - // } - // - // class NativeA : INativeA - // { - // protected override ToString() - // { - // .override IA.ToString() - // } - // } - // - // class Managed : NativeA - // { - // override ToString(); - // } - // - // If we call IA.ToString virtually, we'll land on INativeA.ToString() which is not correct. - // Calling it virtually will solve this problem - PREPARE_VIRTUAL_CALLSITE_USING_METHODDESC(pToStringMD, refThis); - - DECLARE_ARGHOLDER_ARRAY(ToStringArgs, 1); - ToStringArgs[ARGNUM_0] = OBJECTREF_TO_ARGHOLDER(refThis); - - CALL_MANAGED_METHOD_RETREF(refString, STRINGREF, ToStringArgs); - - HELPER_METHOD_FRAME_END(); - - return STRINGREFToObject(refString); -} -FCIMPLEND - -// -// Redirection for GetHashCode -// -NOINLINE static MethodDesc *GetRedirectedGetHashCodeMDHelper(Object *pThisUNSAFE, MethodTable *pMT) -{ - FC_INNER_PROLOG(ComObject::GetRedirectedGetHashCodeMD); - - MethodDesc *pRetMD = NULL; - - // Creates helper frame for GetOrCreateWinRTOverrideInfo (which throws) - HELPER_METHOD_FRAME_BEGIN_RET_ATTRIB(Frame::FRAME_ATTR_EXACT_DEPTH|Frame::FRAME_ATTR_CAPTURE_DEPTH_2); - - WinRTOverrideInfo *pOverrideInfo = WinRTOverrideInfo::GetOrCreateWinRTOverrideInfo(pMT); - if (pOverrideInfo && pOverrideInfo->m_pGetHashCodeMD != NULL) - { - pRetMD = pOverrideInfo->m_pGetHashCodeMD; - } - - HELPER_METHOD_FRAME_END(); - - FC_INNER_EPILOG(); - - return pRetMD; -} - -FCIMPL1(MethodDesc *, ComObject::GetRedirectedGetHashCodeMD, Object *pThisUNSAFE) -{ - CONTRACTL - { - FCALL_CHECK; - PRECONDITION(CheckPointer(pThisUNSAFE)); - } - CONTRACTL_END; - - MethodTable *pMT = pThisUNSAFE->GetMethodTable(); - if (pMT->IsSkipWinRTOverride()) - return NULL; - - FC_INNER_RETURN(MethodDesc*, ::GetRedirectedGetHashCodeMDHelper(pThisUNSAFE, pMT)); -} -FCIMPLEND - -FCIMPL2(int, ComObject::RedirectGetHashCode, Object *pThisUNSAFE, MethodDesc *pGetHashCodeMD) -{ - CONTRACTL - { - FCALL_CHECK; - PRECONDITION(CheckPointer(pThisUNSAFE)); - } - CONTRACTL_END; - - OBJECTREF refThis = ObjectToOBJECTREF(pThisUNSAFE); - int hash = 0; - - HELPER_METHOD_FRAME_BEGIN_RET_1(refThis); - - // Note that this has to be virtual. See RedirectToString for more details - PREPARE_VIRTUAL_CALLSITE_USING_METHODDESC(pGetHashCodeMD, refThis); - - DECLARE_ARGHOLDER_ARRAY(GetHashCodeArgs, 1); - GetHashCodeArgs[ARGNUM_0] = OBJECTREF_TO_ARGHOLDER(refThis); - - CALL_MANAGED_METHOD(hash, int, GetHashCodeArgs); - - HELPER_METHOD_FRAME_END(); - - return hash; -} -FCIMPLEND - -NOINLINE static MethodDesc *GetRedirectedEqualsMDHelper(Object *pThisUNSAFE, MethodTable *pMT) -{ - FC_INNER_PROLOG(ComObject::GetRedirectedEqualsMD); - - MethodDesc *pRetMD = NULL; - - // Creates helper frame for GetOrCreateWinRTOverrideInfo (which throws) - HELPER_METHOD_FRAME_BEGIN_RET_ATTRIB(Frame::FRAME_ATTR_EXACT_DEPTH|Frame::FRAME_ATTR_CAPTURE_DEPTH_2); - - WinRTOverrideInfo *pOverrideInfo = WinRTOverrideInfo::GetOrCreateWinRTOverrideInfo(pMT); - if (pOverrideInfo && pOverrideInfo->m_pEqualsMD!= NULL) - { - pRetMD = pOverrideInfo->m_pEqualsMD; - } - - HELPER_METHOD_FRAME_END(); - - FC_INNER_EPILOG(); - - return pRetMD; -} - -FCIMPL1(MethodDesc *, ComObject::GetRedirectedEqualsMD, Object *pThisUNSAFE) -{ - CONTRACTL - { - FCALL_CHECK; - PRECONDITION(CheckPointer(pThisUNSAFE)); - } - CONTRACTL_END; - - MethodTable *pMT = pThisUNSAFE->GetMethodTable(); - if (pMT->IsSkipWinRTOverride()) - return NULL; - - FC_INNER_RETURN(MethodDesc*, ::GetRedirectedEqualsMDHelper(pThisUNSAFE, pMT)); -} -FCIMPLEND - -FCIMPL3(FC_BOOL_RET, ComObject::RedirectEquals, Object *pThisUNSAFE, Object *pOtherUNSAFE, MethodDesc *pEqualsMD) -{ - CONTRACTL - { - FCALL_CHECK; - PRECONDITION(CheckPointer(pThisUNSAFE)); - } - CONTRACTL_END; - - OBJECTREF refThis = ObjectToOBJECTREF(pThisUNSAFE); - OBJECTREF refOther = ObjectToOBJECTREF(pOtherUNSAFE); - - CLR_BOOL ret = FALSE; - - HELPER_METHOD_FRAME_BEGIN_RET_2(refThis, refOther); - - // Note that this has to be virtual. See RedirectToString for more details - PREPARE_VIRTUAL_CALLSITE_USING_METHODDESC(pEqualsMD, refThis); - - DECLARE_ARGHOLDER_ARRAY(EqualArgs, 2); - EqualArgs[ARGNUM_0] = OBJECTREF_TO_ARGHOLDER(refThis); - EqualArgs[ARGNUM_1] = OBJECTREF_TO_ARGHOLDER(refOther); - - CALL_MANAGED_METHOD(ret, CLR_BOOL, EqualArgs); - - HELPER_METHOD_FRAME_END(); - - FC_RETURN_BOOL(ret); -} -FCIMPLEND - #endif // #ifndef DACCESS_COMPILE #endif //#ifndef CROSSGEN_COMPILE diff --git a/src/coreclr/src/vm/runtimecallablewrapper.h b/src/coreclr/src/vm/runtimecallablewrapper.h index d27d70f..82eca9c 100644 --- a/src/coreclr/src/vm/runtimecallablewrapper.h +++ b/src/coreclr/src/vm/runtimecallablewrapper.h @@ -68,7 +68,6 @@ #include "comcache.h" #include "threads.h" #include "comcache.h" -#include "jupiterobject.h" class Object; class ComCallWrapper; @@ -78,18 +77,6 @@ class Thread; #define GC_PRESSURE_MACHINE_LOCAL 4004 #define GC_PRESSURE_REMOTE 4824 -#ifdef HOST_64BIT -#define GC_PRESSURE_WINRT_BASE 1000 -#define GC_PRESSURE_WINRT_LOW 12000 -#define GC_PRESSURE_WINRT_MEDIUM 120000 -#define GC_PRESSURE_WINRT_HIGH 1200000 -#else // HOST_64BIT -#define GC_PRESSURE_WINRT_BASE 750 -#define GC_PRESSURE_WINRT_LOW 8000 -#define GC_PRESSURE_WINRT_MEDIUM 80000 -#define GC_PRESSURE_WINRT_HIGH 800000 -#endif // HOST_64BIT - enum {INTERFACE_ENTRY_CACHE_SIZE = 8}; struct RCWAuxiliaryData; @@ -280,11 +267,11 @@ struct RCW enum CreationFlags { CF_None = 0x00, - CF_SupportsIInspectable = 0x01, // the underlying object supports IInspectable + // unused = 0x01, CF_QueryForIdentity = 0x02, // Need to QI for the real identity IUnknown during creating RCW - CF_IsWeakReference = 0x04, // mark the RCW as "weak" + // unused = 0x04, CF_NeedUniqueObject = 0x08, // always create a new RCW/object even if we have one cached already - CF_DontResolveClass = 0x10, // don't attempt to create a strongly typed RCW + // unused = 0x10, CF_DetectDCOMProxy = 0x20, // attempt to determine if the RCW is for a DCOM proxy }; @@ -479,117 +466,32 @@ struct RCW #endif // #ifndef DACCESS_COMPILE - enum InterfaceRedirectionKind - { - InterfaceRedirection_None, - InterfaceRedirection_IEnumerable, // IEnumerable`1 - based interface - InterfaceRedirection_IEnumerable_RetryOnFailure, // IEnumerable`1 - based interface, retry on QI failure - InterfaceRedirection_UnresolvedIEnumerable, // unknown IEnumerable`1 instantiation - InterfaceRedirection_Other, // other interface - InterfaceRedirection_Other_RetryOnFailure, // non-generic redirected interface - }; - - // Returns a redirected collection interface corresponding to a given ICollection, IReadOnlyCollection, or NULL. - static MethodTable *ResolveICollectionInterface(MethodTable *pItfMT, BOOL fPreferIDictionary, BOOL *pfChosenIDictionary); - - // Returns an interface with variance corresponding to pMT or NULL if pMT does not support variance. - static MethodTable *GetVariantMethodTable(MethodTable *pMT); - static MethodTable *ComputeVariantMethodTable(MethodTable *pMT); - - // Determines the interface that should be QI'ed for when the RCW is cast to pItfMT. - // Returns the kind of interface redirection that has been performed. - InterfaceRedirectionKind GetInterfaceForQI(MethodTable *pItfMT, MethodTable **pNewItfMT); - static InterfaceRedirectionKind GetInterfacesForQI(MethodTable *pItfMT, MethodTable **ppNewItfMT1, MethodTable **ppNewItfMT2); - static InterfaceRedirectionKind ComputeInterfacesForQI(MethodTable *pItfMT, MethodTable **ppNewItfMT1, MethodTable **ppNewItfMT2); - // Performs QI for the given interface, optionally instantiating it with the given generic args. HRESULT CallQueryInterface(MethodTable *pMT, Instantiation inst, IID *piid, IUnknown **ppUnk); - // Performs QI for interfaces that are castable to pMT using co-/contra-variance. - HRESULT CallQueryInterfaceUsingVariance(MethodTable *pMT, IUnknown **ppUnk); - - // Returns the GetEnumerator method of the first IEnumerable this RCW was successfully - // cast to, or NULL if no such cast has ever succeeded. - MethodDesc *GetGetEnumeratorMethod(); - - // Sets the first "known" GetEnumerator method if not set already. - void SetGetEnumeratorMethod(MethodTable *pMT); - - // Retrieve cached GetEnumerator method or compute the right one for a specific type - static MethodDesc *GetOrComputeGetEnumeratorMethodForType(MethodTable *pMT); - - // Compute the first GetEnumerator for a specific type - static MethodDesc *ComputeGetEnumeratorMethodForType(MethodTable *pMT); - - // Get the GetEnumerator method for IEnumerable or IIterable - static MethodDesc *ComputeGetEnumeratorMethodForTypeInternal(MethodTable *pMT); - - // Notifies the RCW of an interface that is known to be supported by the COM object. - void SetSupportedInterface(MethodTable *pItfMT, Instantiation originalInst); - //----------------------------------------------------------------- // Retrieve correct COM IP for the current apartment. // use the cache /update the cache IUnknown* GetComIPForMethodTableFromCache(MethodTable * pMT); - // helpers to get to IUnknown, IDispatch, and IInspectable interfaces + // helpers to get to IUnknown, IDispatch interfaces // Returns an addref'd pointer - caller must Release IUnknown* GetWellKnownInterface(REFIID riid); IUnknown* GetIUnknown(); IUnknown* GetIUnknown_NoAddRef(); IDispatch* GetIDispatch(); - IInspectable* GetIInspectable(); ULONG GetRefCount() { return m_cbRefCount; } - IJupiterObject *GetJupiterObjectNoCheck() - { - LIMITED_METHOD_CONTRACT; - - _ASSERTE(IsJupiterObject()); - - // We saved IJupiterObject * on the first slot - _ASSERTE((IUnknown *)m_aInterfaceEntries[0].m_pUnknown != NULL); - _ASSERTE((MethodTable *)m_aInterfaceEntries[0].m_pMT == NULL); - - return (IJupiterObject *)m_aInterfaceEntries[0].m_pUnknown.Load(); - } - - IJupiterObject *GetJupiterObject() - { - LIMITED_METHOD_CONTRACT; - - if (IsJupiterObject()) - { - return GetJupiterObjectNoCheck(); - } - - return NULL; - } - void GetCachedInterfaceTypes(BOOL bIInspectableOnly, SArray * rgItfTables) { LIMITED_METHOD_DAC_CONTRACT; - CachedInterfaceEntryIterator it = IterateCachedInterfacePointers(); - while (it.Next()) - { - PTR_MethodTable pMT = dac_cast((TADDR)(it.GetEntry()->m_pMT.Load())); - if (pMT != NULL && - (!bIInspectableOnly || pMT->IsProjectedFromWinRT() || pMT->SupportsGenericInterop(TypeHandle::Interop_NativeToManaged))) - { - // Don't return mscorlib-internal declarations of WinRT types. - if (!(pMT->GetModule()->IsSystem() && pMT->IsProjectedFromWinRT())) - { - rgItfTables->Append(pMT); - } - } - } } void GetCachedInterfacePointers(BOOL bIInspectableOnly, @@ -602,7 +504,7 @@ struct RCW { PTR_MethodTable pMT = dac_cast((TADDR)(it.GetEntry()->m_pMT.Load())); if (pMT != NULL && - (!bIInspectableOnly || pMT->IsProjectedFromWinRT() || pMT->SupportsGenericInterop(TypeHandle::Interop_NativeToManaged))) + (!bIInspectableOnly)) { TADDR taUnk = (TADDR)(it.GetEntry()->m_pUnknown.Load()); if (taUnk != NULL) @@ -613,24 +515,6 @@ struct RCW } } - // Save IJupiterObject * on the first slot - // Only call this in Initialize code - void SetJupiterObject(IJupiterObject *pJupiterObject) - { - - LIMITED_METHOD_CONTRACT; - - m_Flags.m_fIsJupiterObject = 1; - - // - // Save pJupiterObject* on the first SLOT - // Only AddRef if not aggregated - // - _ASSERTE(m_aInterfaceEntries[0].IsFree()); - - m_aInterfaceEntries[0].Init(NULL, pJupiterObject); - } - LPVOID GetVTablePtr() { LIMITED_METHOD_CONTRACT; return m_vtablePtr; } // Remoting aware QI that will attempt to re-unmarshal on object disconnect. @@ -674,12 +558,6 @@ struct RCW return m_Flags.m_fURTContained == 1; } - BOOL SupportsIInspectable() - { - LIMITED_METHOD_DAC_CONTRACT; - return m_Flags.m_fSupportsIInspectable == 1; - } - // // This COM object aggregates FTM? // @@ -708,13 +586,6 @@ struct RCW return (m_Flags.m_MarshalingType == MarshalingType_Inhibit) ; } - BOOL IsJupiterObject() - { - LIMITED_METHOD_CONTRACT; - - return m_Flags.m_fIsJupiterObject == 1; - } - // Returns TRUE if this RCW has been detached. Detached RCWs are fully functional but have been found // dead during GC, before finalizable/f-reachable objects were promoted. If we ever find such an RCW // in the RCW cache during marshaling (i.e. an interface pointer with the same identity enters managed @@ -794,107 +665,6 @@ struct RCW // interop mechanisms. bool SupportsMngStdInterface(MethodTable *pItfMT); - //--------------------------------------------------------------------- - // Determines whether a call through the given interface should use new - // WinRT interop (as opposed to classic COM). pItfMT should be a non-generic - // redirected interface such as IEnumerable whose interop behavior is - // ambiguous. This is a NoGC variant, if it returns TypeHandle::MaybeCast, - // SupportsWinRTInteropInterface should be called. - TypeHandle::CastResult SupportsWinRTInteropInterfaceNoGC(MethodTable *pItfMT); - - //--------------------------------------------------------------------- - // This is a GC-triggering variant of code:SupportsWinRTInteropInterfaceNoGC. - bool SupportsWinRTInteropInterface(MethodTable *pItfMT); - - //--------------------------------------------------------------------- - // True if the object supports legacy (not WinRT) IEnumerable marshaling. - bool SupportsLegacyEnumerableInterface() - { - LIMITED_METHOD_CONTRACT; - - _ASSERTE(SupportsWinRTInteropInterfaceNoGC(MscorlibBinder::GetExistingClass(CLASS__IENUMERABLE)) == TypeHandle::CannotCast); - return m_Flags.m_RedirectionBehavior_IEnumerable_LegacySupported; - } - - enum RedirectionBehavior - { - RedirectionBehaviorComputed = 1, // the second bit is valid - RedirectionBehaviorEnabled = 2 // if RedirectionBehaviorComputed is set, true means the interface is redirected on this RCW - }; - - enum InterfaceVarianceBehavior - { - IEnumerableSupported = 1, // IEnumerable is supported on this RCW - IEnumerableSupportedViaStringInstantiation = 2, // the object failed QI for IEnumerable but succeeded QI for IEnumerable - - IReadOnlyListSupported = 4, // IReadOnlyList is supported on this RCW - IReadOnlyListSupportedViaStringInstantiation = 8, // the object failed QI for IReadOnlyList but succeeded QI for IReadOnlyList - }; - - // Returns a delegate object that points to the right GetEnumerator/Indexer_Get stub that should be used when calling these methods via - // IEnumerable/IReadOnlyList or NULL in which case the BOOL argument are relevant: - // *pfUseString == true means that the caller should use IEnumerable/IReadOnlyList - // *pfUseT == true means that the caller should handle the call as normal, i.e. invoking the stub instantiated over T. - OBJECTREF GetTargetForAmbiguousVariantCall(BOOL fIsEnumerable, WinRTInterfaceRedirector::WinRTLegalStructureBaseType baseType, BOOL *pfUseString, BOOL *pfUseT) - { - LIMITED_METHOD_CONTRACT; - - if (m_pAuxiliaryData != NULL) - { - if (baseType == WinRTInterfaceRedirector::BaseType_Object) - { - if (fIsEnumerable) - { - if (VARIANCE_STUB_TARGET_IS_HANDLE(m_pAuxiliaryData->m_ohObjectVariantCallTarget_IEnumerable)) - return ObjectFromHandle(m_pAuxiliaryData->m_ohObjectVariantCallTarget_IEnumerable); - - if (m_pAuxiliaryData->m_ohObjectVariantCallTarget_IEnumerable == VARIANCE_STUB_TARGET_USE_STRING) - *pfUseString = TRUE; - else if (m_pAuxiliaryData->m_ohObjectVariantCallTarget_IEnumerable == VARIANCE_STUB_TARGET_USE_T) - *pfUseT = TRUE; - } - else - { - if (VARIANCE_STUB_TARGET_IS_HANDLE(m_pAuxiliaryData->m_ohObjectVariantCallTarget_IReadOnlyList)) - return ObjectFromHandle(m_pAuxiliaryData->m_ohObjectVariantCallTarget_IReadOnlyList); - - if (m_pAuxiliaryData->m_ohObjectVariantCallTarget_IReadOnlyList == VARIANCE_STUB_TARGET_USE_STRING) - *pfUseString = TRUE; - else if (m_pAuxiliaryData->m_ohObjectVariantCallTarget_IReadOnlyList == VARIANCE_STUB_TARGET_USE_T) - *pfUseT = TRUE; - } - } - else - { - InterfaceVarianceBehavior varianceBehavior = (baseType == WinRTInterfaceRedirector::BaseType_IEnumerable) ? - (InterfaceVarianceBehavior)m_pAuxiliaryData->m_AuxFlags.m_InterfaceVarianceBehavior_OfIEnumerable : - (InterfaceVarianceBehavior)m_pAuxiliaryData->m_AuxFlags.m_InterfaceVarianceBehavior_OfIEnumerableOfChar; - - if (fIsEnumerable) - { - if ((varianceBehavior & IEnumerableSupported) != 0) - { - if ((varianceBehavior & IEnumerableSupportedViaStringInstantiation) != 0) - *pfUseString = TRUE; - else - *pfUseT = TRUE; - } - } - else - { - if ((varianceBehavior & IReadOnlyListSupported) != 0) - { - if ((varianceBehavior & IReadOnlyListSupportedViaStringInstantiation) != 0) - *pfUseString = TRUE; - else - *pfUseT = TRUE; - } - } - } - } - return NULL; - } - #ifdef _DEBUG // Does not throw if m_UnkEntry.m_pUnknown is no longer valid, debug only. IUnknown *GetRawIUnknown_NoAddRef_NoThrow() @@ -953,10 +723,6 @@ struct RCW private: //--------------------------------------------------------------------- - // Computes the result of code:SupportsWinRTInteropInterface. - RedirectionBehavior ComputeRedirectionBehavior(MethodTable *pItfMT, bool *pfLegacySupported); - - //--------------------------------------------------------------------- // Callback called to release the interfaces in the auxiliary cache. static HRESULT __stdcall ReleaseAuxInterfacesCallBack(LPVOID pData); @@ -1005,23 +771,10 @@ public: DWORD m_fURTAggregated:1; // this RCW represents a COM object aggregated by a managed object DWORD m_fURTContained:1; // this RCW represents a COM object contained by a managed object DWORD m_fAllowEagerSTACleanup:1; // this RCW can be cleaned up eagerly (as opposed to via CleanupUnusedObjectsInCurrentContext) - DWORD m_fSupportsIInspectable:1; // the underlying COM object is known to support IInspectable - DWORD m_fIsJupiterObject:1; // this RCW represents a COM object from Jupiter static_assert((1 << 3) >= GCPressureSize_COUNT, "m_GCPressure needs a bigger data type"); DWORD m_GCPressure:3; // index into s_rGCPressureTable - // RedirectionBehavior of non-generic redirected interfaces: - DWORD m_RedirectionBehavior_IEnumerable:2; - DWORD m_RedirectionBehavior_IEnumerable_LegacySupported:1; // one extra bit for IEnumerable - - DWORD m_RedirectionBehavior_ICollection:2; - DWORD m_RedirectionBehavior_IList:2; - DWORD m_RedirectionBehavior_INotifyCollectionChanged:2; - DWORD m_RedirectionBehavior_INotifyPropertyChanged:2; - DWORD m_RedirectionBehavior_ICommand:2; - DWORD m_RedirectionBehavior_IDisposable:2; - // Reserve 2 bits for marshaling behavior DWORD m_MarshalingType:2; // MarshalingBehavior of the COM object. @@ -1111,32 +864,18 @@ inline RCW::CreationFlags operator|=(RCW::CreationFlags & lhs, RCW::CreationFlag // can absorb the cost of one stack slot and one instruction to improve debuggability. #define RCW_VTABLEPTR(pRCW) Volatile __vtablePtr = (pRCW)->m_vtablePtr - -// 01 REQUIRE_IINSPECTABLE 01 ITF_MARSHAL_INSP_ITF 01 CF_SupportsIInspectable -// 02 SUPPRESS_ADDREF 02 ITF_MARSHAL_SUPPRESS_ADDREF 02 CF_SuppressAddRef -// 04 CF_IsWeakReference // 04 CLASS_IS_HINT 04 ITF_MARSHAL_CLASS_IS_HINT // 08 UNIQUE_OBJECT 08 CF_NeedUniqueObject // 08 ITF_MARSHAL_DISP_ITF -// 10 IGNORE_WINRT_AND_SKIP_UNBOXING 10 CF_DontResolveClass // 10 ITF_MARSHAL_USE_BASIC_ITF -// 20 ITF_MARSHAL_WINRT_SCENARIO inline RCW::CreationFlags RCW::CreationFlagsFromObjForComIPFlags(ObjFromComIP::flags dwFlags) { LIMITED_METHOD_CONTRACT; static_assert_no_msg(CF_NeedUniqueObject == ObjFromComIP::UNIQUE_OBJECT); - static_assert_no_msg(CF_SupportsIInspectable == ObjFromComIP::REQUIRE_IINSPECTABLE); - static_assert_no_msg(CF_DontResolveClass == ObjFromComIP::IGNORE_WINRT_AND_SKIP_UNBOXING); RCW::CreationFlags result = (RCW::CreationFlags)(dwFlags & - (ObjFromComIP::UNIQUE_OBJECT - | ObjFromComIP::IGNORE_WINRT_AND_SKIP_UNBOXING)); - if ((dwFlags & (ObjFromComIP::REQUIRE_IINSPECTABLE|ObjFromComIP::CLASS_IS_HINT)) - == (ObjFromComIP::REQUIRE_IINSPECTABLE|ObjFromComIP::CLASS_IS_HINT)) - { - result |= CF_SupportsIInspectable; - } + (ObjFromComIP::UNIQUE_OBJECT)); return result; } @@ -1149,28 +888,18 @@ struct RCWPerTypeData // Corresponding type with variance or NULL if the type does not exhibit variant behavior. MethodTable *m_pVariantMT; - // Types that should be used for QI. m_pMTForQI1 is tried first; if it fails and m_pMTForQI2 - // is not NULL, QI for m_pMTForQI2 is performed. We need two types to supports ambiguous casts - // to ICollection>. - MethodTable *m_pMTForQI1; - MethodTable *m_pMTForQI2; - // The corresponding IEnumerator::GetEnumerator instantiation or NULL if the type does not // act like IEnumerable. MethodDesc *m_pGetEnumeratorMethod; - // The kind of redirection performed by QI'ing for m_pMTForQI1. - RCW::InterfaceRedirectionKind m_RedirectionKind; - enum { VariantTypeInited = 0x01, // m_pVariantMT is set - RedirectionInfoInited = 0x02, // m_pMTForQI1, m_pMTForQI2, and m_RedirectionKind are set + //unused = 0x02, GetEnumeratorInited = 0x04, // m_pGetEnumeratorMethod is set - InterfaceFlagsInited = 0x08, // IsRedirectedInterface and IsICollectionGeneric are set - - IsRedirectedInterface = 0x10, // the type is a redirected interface - IsICollectionGeneric = 0x20, // the type is ICollection`1 + // unused = 0x08, + // unused = 0x10, + // unused = 0x20, }; DWORD m_dwFlags; }; @@ -1178,8 +907,6 @@ struct RCWPerTypeData #ifdef FEATURE_COMINTEROP_UNMANAGED_ACTIVATION class ComClassFactory; -class WinRTClassFactory; -class WinRTManagedClassFactory; class ClassFactoryBase { @@ -1191,24 +918,8 @@ public: ComClassFactory *AsComClassFactory() { LIMITED_METHOD_CONTRACT; - _ASSERTE(m_pClassMT == NULL || (!m_pClassMT->IsProjectedFromWinRT() && !m_pClassMT->IsExportedToWinRT())); return (ComClassFactory *)this; } - - WinRTClassFactory *AsWinRTClassFactory() - { - LIMITED_METHOD_CONTRACT; - _ASSERTE(m_pClassMT->IsProjectedFromWinRT() || m_pClassMT->IsExportedToWinRT()); - return (WinRTClassFactory *)this; - } - - WinRTManagedClassFactory *AsWinRTManagedClassFactory() - { - LIMITED_METHOD_CONTRACT; - _ASSERTE(m_pClassMT->IsExportedToWinRT()); - return (WinRTManagedClassFactory *)this; - } - protected: ClassFactoryBase(MethodTable *pClassMT = NULL) : m_pClassMT(pClassMT) @@ -1306,20 +1017,6 @@ private: BOOL m_bManagedVersion; }; -// -// WinRT override information for ToString/GetHashCode/Equals -// -struct WinRTOverrideInfo -{ - MethodDesc *m_pToStringMD; - MethodDesc *m_pGetHashCodeMD; - MethodDesc *m_pEqualsMD; - - WinRTOverrideInfo(EEClass *pClass); - static WinRTOverrideInfo *GetOrCreateWinRTOverrideInfo(MethodTable *pMT); - MethodDesc* GetIStringableToStringMD(MethodTable *pMT); -}; - //-------------------------------------------------------------- // Special ComClassFactory for AppX scenarios only // Call CoCreateInstanceFromApp to ensure compatibility @@ -1365,145 +1062,8 @@ public : RETURN new ComClassFactory(rclsid); } }; -//------------------------------------------------------------------------- -// Encapsulates data needed to instantiate WinRT runtime classes. -class WinRTClassFactory : public ClassFactoryBase -{ -public: - WinRTClassFactory(MethodTable *pClassMT) - : ClassFactoryBase(pClassMT) - { - LIMITED_METHOD_CONTRACT; - - m_hClassName = NULL; - m_pDefaultItfMT = NULL; - m_pWinRTOverrideInfo = NULL; - m_GCPressure = RCW::GCPressureSize_WinRT_Base; - } - - //------------------------------------------------------------- - // Initialize this instance by parsing factory-related attributes. - void Init(); - - //------------------------------------------------------------- - // Returns a factory method that matches the given signature. - MethodDesc *FindFactoryMethod(PCCOR_SIGNATURE pSig, DWORD cSig, Module *pModule); - - //------------------------------------------------------------- - // Returns a static interface method that matches the given signature. - MethodDesc *FindStaticMethod(LPCUTF8 pszName, PCCOR_SIGNATURE pSig, DWORD cSig, Module *pModule); - - //------------------------------------------------------------- - // Function to clean up - void Cleanup(); - - // If true, the class can be activated only using the composition pattern - BOOL IsComposition() - { - LIMITED_METHOD_CONTRACT; - return !m_pClassMT->IsSealed(); - } - - MethodTable *GetClass() - { - LIMITED_METHOD_CONTRACT; - return m_pClassMT; - } - - HSTRING GetClassName() - { - LIMITED_METHOD_CONTRACT; - return m_hClassName; - } - - SArray *GetFactoryInterfaces() - { - LIMITED_METHOD_CONTRACT; - return &m_factoryInterfaces; - } - - SArray *GetStaticInterfaces() - { - LIMITED_METHOD_CONTRACT; - return &m_staticInterfaces; - } - - MethodTable *GetDefaultInterface() - { - LIMITED_METHOD_CONTRACT; - return m_pDefaultItfMT; - } - - RCW::GCPressureSize GetGCPressure() - { - LIMITED_METHOD_CONTRACT; - return m_GCPressure; - } - - FORCEINLINE WinRTOverrideInfo *GetWinRTOverrideInfo () - { - LIMITED_METHOD_CONTRACT; - return m_pWinRTOverrideInfo; - } - - BOOL SetWinRTOverrideInfo (WinRTOverrideInfo *pWinRTOverrideInfo) - { - LIMITED_METHOD_CONTRACT; - - return (InterlockedCompareExchangeT(&m_pWinRTOverrideInfo, pWinRTOverrideInfo, NULL) == NULL); - } - -protected: - MethodTable *GetTypeFromAttribute(IMDInternalImport *pImport, mdCustomAttribute tkAttribute); - - HSTRING m_hClassName; - - InlineSArray m_factoryInterfaces; - InlineSArray m_staticInterfaces; - - MethodTable *m_pDefaultItfMT; // Default interface of the class - - WinRTOverrideInfo *m_pWinRTOverrideInfo; // ToString/GetHashCode/GetValue override information - - RCW::GCPressureSize m_GCPressure; // GC pressure size associated with instances of this class -}; #endif // FEATURE_COMINTEROP_UNMANAGED_ACTIVATION -//------------------------------------------------------------------------- -// Encapsulates data needed to instantiate WinRT runtime classes implemented -// in managed code. -class WinRTManagedClassFactory : public WinRTClassFactory -{ -public: - WinRTManagedClassFactory(MethodTable *pClassMT) - : WinRTClassFactory(pClassMT) - { - m_pCCWTemplate = NULL; - LIMITED_METHOD_CONTRACT; - } - - //------------------------------------------------------------- - // Function to clean up - void Cleanup(); - - ComCallWrapperTemplate *GetComCallWrapperTemplate() - { - LIMITED_METHOD_CONTRACT; - return m_pCCWTemplate; - } - - BOOL SetComCallWrapperTemplate(ComCallWrapperTemplate *pTemplate) - { - LIMITED_METHOD_CONTRACT; - return (InterlockedCompareExchangeT(&m_pCCWTemplate, pTemplate, NULL) == NULL); - } - - ComCallWrapperTemplate *GetOrCreateComCallWrapperTemplate(MethodTable *pFactoryMT); - -protected: - ComCallWrapperTemplate *m_pCCWTemplate; // CCW template for the factory object -}; - FORCEINLINE void NewRCWHolderRelease(RCW* p) { CONTRACTL diff --git a/src/coreclr/src/vm/runtimeexceptionkind.h b/src/coreclr/src/vm/runtimeexceptionkind.h index 6a988e4..d68af41 100644 --- a/src/coreclr/src/vm/runtimeexceptionkind.h +++ b/src/coreclr/src/vm/runtimeexceptionkind.h @@ -12,8 +12,6 @@ //========================================================================== enum RuntimeExceptionKind { #define DEFINE_EXCEPTION(ns, reKind, bHRformessage, ...) k##reKind, -#define DEFINE_EXCEPTION_HR_WINRT_ONLY(ns, reKind, ...) -#define DEFINE_EXCEPTION_IN_OTHER_FX_ASSEMBLY(ns, reKind, assemblySimpleName, bHRformessage, ...) DEFINE_EXCEPTION(ns, reKind, bHRformessage, __VA_ARGS__) #include "rexcep.h" kLastException }; diff --git a/src/coreclr/src/vm/runtimehandles.cpp b/src/coreclr/src/vm/runtimehandles.cpp index 82c793b..f2d7c62 100644 --- a/src/coreclr/src/vm/runtimehandles.cpp +++ b/src/coreclr/src/vm/runtimehandles.cpp @@ -379,49 +379,6 @@ FCIMPLEND #include - - - -#ifdef FEATURE_COMINTEROP -FCIMPL1(FC_BOOL_RET, RuntimeTypeHandle::IsWindowsRuntimeObjectType, ReflectClassBaseObject *rtTypeUNSAFE) -{ - FCALL_CONTRACT; - - BOOL isWindowsRuntimeType = FALSE; - - TypeHandle typeHandle = rtTypeUNSAFE->GetType(); - MethodTable *pMT = typeHandle.GetMethodTable(); - - if (pMT != NULL) - { - isWindowsRuntimeType = pMT->IsWinRTObjectType(); - } - - FC_RETURN_BOOL(isWindowsRuntimeType); -} -FCIMPLEND - -#ifdef FEATURE_COMINTEROP_WINRT_MANAGED_ACTIVATION -FCIMPL1(FC_BOOL_RET, RuntimeTypeHandle::IsTypeExportedToWindowsRuntime, ReflectClassBaseObject *rtTypeUNSAFE) -{ - FCALL_CONTRACT; - - BOOL isExportedToWinRT = FALSE; - - TypeHandle typeHandle = rtTypeUNSAFE->GetType(); - MethodTable *pMT = typeHandle.GetMethodTable(); - - if (pMT != NULL) - { - isExportedToWinRT = pMT->IsExportedToWinRT(); - } - - FC_RETURN_BOOL(isExportedToWinRT); -} -FCIMPLEND -#endif -#endif // FEATURE_COMINTEROP - NOINLINE static MethodDesc * RestoreMethodHelper(MethodDesc * pMethod, LPVOID __me) { FC_INNER_PROLOG_NO_ME_SETUP(); @@ -1417,7 +1374,7 @@ void QCALLTYPE RuntimeTypeHandle::GetTypeByNameUsingCARules(LPCWSTR pwzClassName void QCALLTYPE RuntimeTypeHandle::GetTypeByName(LPCWSTR pwzClassName, BOOL bThrowOnError, BOOL bIgnoreCase, QCall::StackCrawlMarkHandle pStackMark, QCall::ObjectHandleOnStack pAssemblyLoadContext, - BOOL bLoadTypeFromPartialNameHack, QCall::ObjectHandleOnStack retType, + QCall::ObjectHandleOnStack retType, QCall::ObjectHandleOnStack keepAlive) { QCALL_CONTRACT; @@ -1445,7 +1402,7 @@ void QCALLTYPE RuntimeTypeHandle::GetTypeByName(LPCWSTR pwzClassName, BOOL bThro typeHandle = TypeName::GetTypeManaged(pwzClassName, NULL, bThrowOnError, bIgnoreCase, /*bProhibitAsmQualifiedName =*/ FALSE, SystemDomain::GetCallersAssembly(pStackMark), - bLoadTypeFromPartialNameHack, (OBJECTREF*)keepAlive.m_ppObject, + (OBJECTREF*)keepAlive.m_ppObject, pPrivHostBinder); } diff --git a/src/coreclr/src/vm/runtimehandles.h b/src/coreclr/src/vm/runtimehandles.h index 7787e01..e479c2b 100644 --- a/src/coreclr/src/vm/runtimehandles.h +++ b/src/coreclr/src/vm/runtimehandles.h @@ -155,14 +155,6 @@ public: static FCDECL2(FC_BOOL_RET, TypeEQ, Object* left, Object* right); static FCDECL2(FC_BOOL_RET, TypeNEQ, Object* left, Object* right); - -#ifdef FEATURE_COMINTEROP - static FCDECL1(FC_BOOL_RET, IsWindowsRuntimeObjectType, ReflectClassBaseObject *rtTypeUNSAFE); -#ifdef FEATURE_COMINTEROP_WINRT_MANAGED_ACTIVATION - static FCDECL1(FC_BOOL_RET, IsTypeExportedToWindowsRuntime, ReflectClassBaseObject *rtTypeUNSAFE); -#endif -#endif //FEATURE_COMINTEROP - static void QCALLTYPE PrepareMemberInfoCache(QCall::TypeHandle pMemberInfoCache); @@ -176,7 +168,7 @@ public: void QCALLTYPE GetTypeByName(LPCWSTR pwzClassName, BOOL bThrowOnError, BOOL bIgnoreCase, QCall::StackCrawlMarkHandle pStackMark, QCall::ObjectHandleOnStack pAssemblyLoadContext, - BOOL bLoadTypeFromPartialNameHack, QCall::ObjectHandleOnStack retType, + QCall::ObjectHandleOnStack retType, QCall::ObjectHandleOnStack keepAlive); static FCDECL1(AssemblyBaseObject*, GetAssembly, ReflectClassBaseObject *pType); diff --git a/src/coreclr/src/vm/stdinterfaces.cpp b/src/coreclr/src/vm/stdinterfaces.cpp index 240bdc9..bdeefba 100644 --- a/src/coreclr/src/vm/stdinterfaces.cpp +++ b/src/coreclr/src/vm/stdinterfaces.cpp @@ -39,8 +39,6 @@ #include "cominterfacemarshaler.h" #include "eecontract.h" #include "stdinterfaces_internal.h" -#include // IRestrictedErrorInfo -#include "winrttypenameconverter.h" #include "interoputil.inl" @@ -57,10 +55,6 @@ // {00020430-0000-0000-C000-000000000046} static const GUID LIBID_STDOLE2 = { 0x00020430, 0x0000, 0x0000, { 0xc0, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x46 } }; -// The uuid.lib doesn't have IID_IRestrictedErrorInfo in their lib. Remove this once it is included in the lib -static const GUID IID_IRestrictedErrorInfo = { 0x82BA7092, 0x4C88, 0x427D, { 0xA7, 0xBC, 0x16, 0xDD, 0x93, 0xFE, 0xB6, 0x7E } }; -EXTERN_C SELECTANY const IID IID_ILanguageExceptionErrorInfo = { 0x04a2dbf3, 0xdf83, 0x116c, { 0x09, 0x46, 0x08, 0x12, 0xab, 0xf6, 0xe0, 0x7d } }; - // Until the Windows SDK is updated, just hard-code the IAgileObject IID #ifndef __IAgileObject_INTERFACE_DEFINED__ EXTERN_C SELECTANY const GUID IID_IAgileObject = { 0x94ea2b94, 0xe9cc, 0x49e0, { 0xc0, 0xff, 0xee, 0x64, 0xca, 0x8f, 0x5b, 0x90 } }; @@ -86,23 +80,9 @@ const SLOT * const g_rgStdVtables[] = (SLOT*)&g_IConnectionPointContainer.m_vtable, (SLOT*)&g_IObjectSafety.m_vtable, (SLOT*)&g_IDispatchEx.m_vtable, - (SLOT*)&g_IWeakReferenceSource.m_vtable, - (SLOT*)&g_ICustomPropertyProvider.m_vtable, - (SLOT*)&g_ICCW.m_vtable, - (SLOT*)&g_IAgileObject.m_vtable, - (SLOT*)&g_IStringable.m_vtable + (SLOT*)&g_IAgileObject.m_vtable }; - -const IID IID_IWeakReferenceSource = __uuidof(IWeakReferenceSource); -const IID IID_IWeakReference = __uuidof(IWeakReference); - -// {7C925755-3E48-42B4-8677-76372267033F} -const IID IID_ICustomPropertyProvider = {0x7C925755,0x3E48,0x42B4,{0x86, 0x77, 0x76, 0x37, 0x22, 0x67, 0x03, 0x3F}}; - -const IID IID_IStringable = {0x96369f54,0x8eb6,0x48f0, {0xab,0xce,0xc1,0xb2,0x11,0xe6,0x27,0xc3}}; - - //------------------------------------------------------------------------------------------ // IUnknown methods for CLR objects @@ -657,12 +637,6 @@ HRESULT GetITypeInfoForEEClass(MethodTable *pClass, ITypeInfo **ppTI, bool bClas SafeComHolder pTIDef = NULL; // Default typeinfo of a coclass. ComCallWrapperTemplate *pTemplate = NULL; - if (pClass->IsProjectedFromWinRT() || pClass->IsExportedToWinRT()) - { - // ITypeInfo is not used in the WinRT world - return E_NOTIMPL; - } - GCX_PREEMP(); // Get the typeinfo. @@ -847,7 +821,7 @@ HRESULT GetITypeInfoForMT(ComMethodTable *pMT, ITypeInfo **ppTI) // helper function to locate error info (if any) after a call, and make sure // that the error info comes from that call -IErrorInfo *GetSupportedErrorInfo(IUnknown *iface, REFIID riid, BOOL checkForIRestrictedErrInfo) +IErrorInfo *GetSupportedErrorInfo(IUnknown *iface, REFIID riid) { CONTRACTL { @@ -892,22 +866,6 @@ IErrorInfo *GetSupportedErrorInfo(IUnknown *iface, REFIID riid, BOOL checkForIRe } } } - - if (!bUseThisErrorInfo && pErrorInfo != NULL && checkForIRestrictedErrInfo) - { - - // Do we support IRestrictedErrorInfo? - SafeComHolderPreemp pRestrictedErrorInfo; - hr = SafeQueryInterfacePreemp(pErrorInfo, IID_IRestrictedErrorInfo, (IUnknown **) &pRestrictedErrorInfo); - LogInteropQI(pErrorInfo, IID_IRestrictedErrorInfo, hr, "IRestrictedErrorInfo"); - if (SUCCEEDED(hr)) - { - - // This is a WinRT IRestrictedErrorInfo scenario - bUseThisErrorInfo = TRUE; - } - } - if (bUseThisErrorInfo) { pRetErrorInfo = pErrorInfo; @@ -2217,184 +2175,6 @@ HRESULT __stdcall DispatchEx_InvokeEx ( return hr; } -HRESULT __stdcall Inspectable_GetIIDs ( - IInspectable *pInsp, - ULONG *iidCount, - IID **iids) -{ - CONTRACTL - { - NOTHROW; - GC_NOTRIGGER; - MODE_PREEMPTIVE; - PRECONDITION(CheckPointer(pInsp)); - PRECONDITION(IsInProcCCWTearOff(pInsp)); - } - CONTRACTL_END; - - HRESULT hr = S_OK; - - if (iidCount == NULL || iids == NULL) - return E_POINTER; - - *iidCount = 0; - *iids = NULL; - - // Either it is ICustomPropertyProvider or IWeakReferenceSource - ComCallWrapper *pWrap = MapIUnknownToWrapper(pInsp); - - ComCallWrapperTemplate *pTemplate = pWrap->GetComCallWrapperTemplate(); - - ULONG numInterfaces = pTemplate->GetNumInterfaces(); - - // determine the number of IIDs to return - // Always add IID_ICustomPropertyProvider and skip any managed WinRT interface that is IID_ICustomPropertyProvider - ULONG numInspectables = 1; - for (ULONG i = 0; i < numInterfaces; i++) - { - ComMethodTable *pComMT = pTemplate->GetComMTForIndex(i); - - // Skip any managed WinRT interface that is IID_ICustomPropertyProvider - if (pComMT != NULL && pComMT->GetInterfaceType() == ifInspectable && - !IsEqualGUID(pComMT->GetIID(), IID_ICustomPropertyProvider)) - { - numInspectables++; - } - } - - - // we shouldn't ever come here if the CCW does not support IInspectable - _ASSERTE(numInspectables > 0); - - // as per the spec, make sure *iidCount is set even if the allocation fails - *iidCount = numInspectables; - - S_UINT32 cbAlloc = S_UINT32(numInspectables) * S_UINT32(sizeof(IID)); - if (cbAlloc.IsOverflow()) - return E_OUTOFMEMORY; - - NewArrayHolder result = (IID *)CoTaskMemAlloc(cbAlloc.Value()); - if (result == NULL) - return E_OUTOFMEMORY; - - // now fill out the output array with IIDs - result[0] = IID_ICustomPropertyProvider; - - ULONG index = 1; - for (ULONG i = 0; i < numInterfaces; i++) - { - ComMethodTable *pComMT = pTemplate->GetComMTForIndex(i); - - // Skip any managed WinRT interface that is IID_ICustomPropertyProvider - if (pComMT != NULL && pComMT->GetInterfaceType() == ifInspectable && - !IsEqualGUID(pComMT->GetIID(), IID_ICustomPropertyProvider)) - { - result[index] = pComMT->GetIID(); - index++; - } - } - _ASSERTE(index == numInspectables); - - *iids = result.Extract(); - return hr; -} - - -HRESULT __stdcall Inspectable_GetRuntimeClassName(IInspectable *pInsp, HSTRING *className) -{ - CONTRACTL - { - NOTHROW; - GC_TRIGGERS; - MODE_PREEMPTIVE; - PRECONDITION(CheckPointer(pInsp)); - PRECONDITION(IsInProcCCWTearOff(pInsp)); - } - CONTRACTL_END; - - if (className == NULL) - return E_POINTER; - - HRESULT hr = S_OK; - ComCallWrapper *pWrap = MapIUnknownToWrapper(pInsp); - - *className = NULL; - - MethodTable *pMT = pWrap->GetSimpleWrapper()->GetMethodTable(); - _ASSERTE(pMT != NULL); - - EX_TRY - { - StackSString strClassName; - TypeHandle thManagedType; - - { - GCX_COOP(); - OBJECTREF objref = NULL; - - GCPROTECT_BEGIN(objref); - { - objref = pWrap->GetObjectRef(); - thManagedType = objref->GetTypeHandle(); - } - GCPROTECT_END(); - } - - bool bIsPrimitive = false; - if (WinRTTypeNameConverter::AppendWinRTTypeNameForManagedType( - thManagedType, // thManagedType - strClassName, // strWinRTTypeName - TRUE, // bForGetRuntimeClassName, - &bIsPrimitive // pbIsPrimitiveType - ) - && !bIsPrimitive) - { - hr = WindowsCreateString(strClassName.GetUnicode(), strClassName.GetCount(), className); - } - } - EX_CATCH - { - hr = GET_EXCEPTION()->GetHR(); - } - EX_END_CATCH(SwallowAllExceptions); - - return hr; -} - -HRESULT __stdcall WeakReferenceSource_GetWeakReference ( - IWeakReferenceSource *pRefSrc, - IWeakReference **weakReference) -{ - CONTRACTL - { - NOTHROW; - GC_TRIGGERS; - MODE_PREEMPTIVE; - PRECONDITION(CheckPointer(pRefSrc)); - PRECONDITION(IsInProcCCWTearOff(pRefSrc)); - } - CONTRACTL_END; - - if (weakReference == NULL) - return E_INVALIDARG; - - *weakReference = NULL; - - HRESULT hr = S_OK; - BEGIN_EXTERNAL_ENTRYPOINT(&hr) - { - SimpleComCallWrapper *pWrap = SimpleComCallWrapper::GetWrapperFromIP(pRefSrc); - - // Creates a new WeakReferenceImpl that tracks the object lifetime in the current domain - // Note that this WeakReferenceImpl is not bound to a specific CCW - *weakReference = pWrap->CreateWeakReference(GET_THREAD()); - } - END_EXTERNAL_ENTRYPOINT; - - return hr; -} - - // Helper to setup IMarshal HRESULT GetSpecialMarshaler(IMarshal* pMarsh, SimpleComCallWrapper* pSimpleWrap, ULONG dwDestContext, IMarshal **ppMarshalRet) { @@ -2733,449 +2513,3 @@ HRESULT __stdcall ObjectSafety_SetInterfaceSafetyOptions(IUnknown* pUnk, return S_OK; } - -HRESULT __stdcall ICustomPropertyProvider_GetProperty(IUnknown *pPropertyProvider, HSTRING hstrName, IUnknown **ppProperty) -{ - CONTRACTL - { - NOTHROW; - GC_TRIGGERS; - MODE_PREEMPTIVE; - PRECONDITION(CheckPointer(pPropertyProvider)); - PRECONDITION(IsSimpleTearOff(pPropertyProvider)); - PRECONDITION(CheckPointer(ppProperty, NULL_OK)); - } - CONTRACTL_END; - - if (ppProperty == NULL) - return E_POINTER; - - // Initialize [out] parameters - *ppProperty = NULL; - - HRESULT hr; - - BEGIN_EXTERNAL_ENTRYPOINT(&hr) - { - _ASSERTE(IsSimpleTearOff(pPropertyProvider)); - SimpleComCallWrapper *pSimpleWrap = SimpleComCallWrapper::GetWrapperFromIP(pPropertyProvider); - - GCX_COOP(); - - struct _gc { - OBJECTREF TargetObj; - STRINGREF StringRef; - OBJECTREF RetVal; - } gc; - ZeroMemory(&gc, sizeof(gc)); - - GCPROTECT_BEGIN(gc); - - gc.TargetObj = pSimpleWrap->GetObjectRef(); - - // - // Marshal HSTRING to String object - // NULL HSTRINGS are equivilent to empty strings - // - UINT32 cchString = 0; - LPCWSTR pwszString = W(""); - if (hstrName != NULL) - { - pwszString = WindowsGetStringRawBuffer(hstrName, &cchString); - } - - gc.StringRef = StringObject::NewString(pwszString, cchString); - - // - // Call ICustomPropertyProviderImpl.CreateProperty - // - PREPARE_NONVIRTUAL_CALLSITE(METHOD__ICUSTOMPROPERTYPROVIDERIMPL__CREATE_PROPERTY); - DECLARE_ARGHOLDER_ARRAY(args, 2); - args[ARGNUM_0] = OBJECTREF_TO_ARGHOLDER(gc.TargetObj); - args[ARGNUM_1] = OBJECTREF_TO_ARGHOLDER(gc.StringRef); - - CALL_MANAGED_METHOD_RETREF(gc.RetVal, OBJECTREF, args); - - if (gc.RetVal != NULL) - { - // The object is a CustomPropertyImpl. Get the ICustomProperty implementation from CCW and return that - *ppProperty = GetComIPFromObjectRef(&gc.RetVal, MscorlibBinder::GetClass(CLASS__ICUSTOMPROPERTY)); - } - - GCPROTECT_END(); - } - END_EXTERNAL_ENTRYPOINT; - - // Don't fail if property can't be found - just return S_OK and NULL property - return S_OK; -} - -HRESULT __stdcall ICustomPropertyProvider_GetIndexedProperty(IUnknown *pPropertyProvider, - HSTRING hstrName, - TypeNameNative indexedParamType, - /* [out, retval] */ IUnknown **ppProperty) -{ - CONTRACTL - { - NOTHROW; - GC_TRIGGERS; - MODE_PREEMPTIVE; - PRECONDITION(CheckPointer(pPropertyProvider)); - PRECONDITION(IsSimpleTearOff(pPropertyProvider)); - PRECONDITION(CheckPointer(ppProperty, NULL_OK)); - } - CONTRACTL_END; - - if (ppProperty == NULL) - return E_POINTER; - - // Initialize [out] parameters - *ppProperty = NULL; - - HRESULT hr; - - BEGIN_EXTERNAL_ENTRYPOINT(&hr) - { - _ASSERTE(IsSimpleTearOff(pPropertyProvider)); - SimpleComCallWrapper *pSimpleWrap = SimpleComCallWrapper::GetWrapperFromIP(pPropertyProvider); - - GCX_COOP(); - - struct _gc { - OBJECTREF TargetObj; - STRINGREF StringRef; - OBJECTREF RetVal; - } gc; - ZeroMemory(&gc, sizeof(gc)); - - GCPROTECT_BEGIN(gc); - - gc.TargetObj = pSimpleWrap->GetObjectRef(); - - // - // Marshal HSTRING to String object - // NULL HSTRINGS are equivilent to empty strings - // - UINT32 cchString = 0; - LPCWSTR pwszString = W(""); - if (hstrName != NULL) - { - pwszString = WindowsGetStringRawBuffer(hstrName, &cchString); - } - - gc.StringRef = StringObject::NewString(pwszString, cchString); - - // - // Call ICustomPropertyProviderImpl.CreateIndexedProperty - // - PREPARE_NONVIRTUAL_CALLSITE(METHOD__ICUSTOMPROPERTYPROVIDERIMPL__CREATE_INDEXED_PROPERTY); - DECLARE_ARGHOLDER_ARRAY(args, 3); - args[ARGNUM_0] = OBJECTREF_TO_ARGHOLDER(gc.TargetObj); - args[ARGNUM_1] = OBJECTREF_TO_ARGHOLDER(gc.StringRef); - args[ARGNUM_2] = PTR_TO_ARGHOLDER(&indexedParamType); - - CALL_MANAGED_METHOD_RETREF(gc.RetVal, OBJECTREF, args); - - if (gc.RetVal != NULL) - { - // The object is a CustomPropertyImpl. Get the ICustomProperty implementation from CCW and return that - *ppProperty = GetComIPFromObjectRef(&gc.RetVal, MscorlibBinder::GetClass(CLASS__ICUSTOMPROPERTY)); - } - - GCPROTECT_END(); - } - END_EXTERNAL_ENTRYPOINT; - - // Don't fail if property can't be found - just return S_OK and NULL property - return S_OK; -} - -HRESULT __stdcall ICustomPropertyProvider_GetStringRepresentation(IUnknown *pPropertyProvider, - /* [out, retval] */ HSTRING *phstrStringRepresentation) -{ - CONTRACTL - { - NOTHROW; - GC_TRIGGERS; - MODE_PREEMPTIVE; - PRECONDITION(CheckPointer(pPropertyProvider)); - PRECONDITION(IsSimpleTearOff(pPropertyProvider)); - PRECONDITION(CheckPointer(phstrStringRepresentation, NULL_OK)); - } - CONTRACTL_END; - - if (phstrStringRepresentation == NULL) - return E_POINTER; - - // Initialize [out] parameters - *phstrStringRepresentation = NULL; - - HRESULT hr; - - BEGIN_EXTERNAL_ENTRYPOINT(&hr) - { - _ASSERTE(IsSimpleTearOff(pPropertyProvider)); - SimpleComCallWrapper *pSimpleWrap = SimpleComCallWrapper::GetWrapperFromIP(pPropertyProvider); - - GCX_COOP(); - - struct _gc { - OBJECTREF TargetObj; - STRINGREF RetVal; - } gc; - ZeroMemory(&gc, sizeof(gc)); - - GCPROTECT_BEGIN(gc); - - gc.TargetObj = pSimpleWrap->GetObjectRef(); - - // - // Call IStringableHelper.ToString() to get string representation either from IStringable.ToString() or ToString() - // - PREPARE_NONVIRTUAL_CALLSITE(METHOD__ISTRINGABLEHELPER__TO_STRING); - DECLARE_ARGHOLDER_ARRAY(args, 1); - args[ARGNUM_0] = OBJECTREF_TO_ARGHOLDER(gc.TargetObj); - CALL_MANAGED_METHOD_RETREF(gc.RetVal, STRINGREF, args); - - // - // Convert managed string to HSTRING - // - if (gc.RetVal == NULL) - *phstrStringRepresentation = NULL; - else - hr = ::WindowsCreateString(gc.RetVal->GetBuffer(), gc.RetVal->GetStringLength(), phstrStringRepresentation); - - GCPROTECT_END(); - - } - END_EXTERNAL_ENTRYPOINT; - - return hr; -} - -HRESULT __stdcall ICustomPropertyProvider_GetType(IUnknown *pPropertyProvider, - /* [out, retval] */ TypeNameNative *pTypeIdentifier) -{ - CONTRACTL - { - NOTHROW; - GC_TRIGGERS; - MODE_PREEMPTIVE; - PRECONDITION(CheckPointer(pPropertyProvider)); - PRECONDITION(IsSimpleTearOff(pPropertyProvider)); - PRECONDITION(CheckPointer(pTypeIdentifier)); - } - CONTRACTL_END; - - if (pTypeIdentifier == NULL) - return E_POINTER; - - // Initialize [out] parameters - ::ZeroMemory(pTypeIdentifier, sizeof(TypeNameNative)); - - HRESULT hr; - - BEGIN_EXTERNAL_ENTRYPOINT(&hr) - { - _ASSERTE(IsSimpleTearOff(pPropertyProvider)); - SimpleComCallWrapper *pSimpleWrap = SimpleComCallWrapper::GetWrapperFromIP(pPropertyProvider); - - GCX_COOP(); - - OBJECTREF refTargetObj = NULL; - GCPROTECT_BEGIN(refTargetObj); - - refTargetObj = pSimpleWrap->GetObjectRef(); - - // - // Call ICustomPropertyProviderImpl.GetType() - // - PREPARE_NONVIRTUAL_CALLSITE(METHOD__ICUSTOMPROPERTYPROVIDERIMPL__GET_TYPE); - DECLARE_ARGHOLDER_ARRAY(args, 2); - args[ARGNUM_0] = OBJECTREF_TO_ARGHOLDER(refTargetObj); - args[ARGNUM_1] = PTR_TO_ARGHOLDER(pTypeIdentifier); - - CALL_MANAGED_METHOD_NORET(args); - - GCPROTECT_END(); - } - END_EXTERNAL_ENTRYPOINT; - - return S_OK; -} - -HRESULT __stdcall IStringable_ToString(IUnknown* pStringable, - /* [out, retval] */ HSTRING* pResult) -{ - CONTRACTL - { - NOTHROW; - GC_TRIGGERS; - MODE_PREEMPTIVE; - PRECONDITION(CheckPointer(pStringable)); - PRECONDITION(IsSimpleTearOff(pStringable)); - PRECONDITION(CheckPointer(pResult, NULL_OK)); - } - CONTRACTL_END; - - if (pResult == NULL) - return E_POINTER; - - // Initialize [out] parameters - *pResult = NULL; - - HRESULT hr; - - BEGIN_EXTERNAL_ENTRYPOINT(&hr) - { - _ASSERTE(IsSimpleTearOff(pStringable)); - SimpleComCallWrapper *pSimpleWrap = SimpleComCallWrapper::GetWrapperFromIP(pStringable); - - GCX_COOP(); - - struct _gc { - OBJECTREF TargetObj; - STRINGREF RetVal; - } gc; - ZeroMemory(&gc, sizeof(gc)); - - GCPROTECT_BEGIN(gc); - - gc.TargetObj = pSimpleWrap->GetObjectRef(); - MethodDesc* pToStringMD = NULL; - - MethodTable* pMT = gc.TargetObj->GetMethodTable(); - - - // Get the MethodTable for Windows.Foundation.IStringable. - StackSString strIStringable(SString::Utf8, W("Windows.Foundation.IStringable")); - MethodTable *pMTIStringable = LoadWinRTType(&strIStringable, /* bThrowIfNotFound = */ FALSE).GetMethodTable(); - - if (pMT != NULL && pMTIStringable != NULL && pMT->ImplementsInterface(pMTIStringable)) - { - // Find the ToString() method of the interface. - pToStringMD = MemberLoader::FindMethod( - pMTIStringable, - "ToString", - &gsig_IM_RetStr); - - _ASSERTE(pToStringMD != NULL); - } - else - { - // The object does not implement IStringable interface we need to call the default implementation using Object.ToString() call. - pToStringMD = MscorlibBinder::GetMethod(METHOD__OBJECT__TO_STRING); - _ASSERTE(pToStringMD != NULL); - } - - - - PREPARE_VIRTUAL_CALLSITE_USING_METHODDESC(pToStringMD, gc.TargetObj); - DECLARE_ARGHOLDER_ARRAY(args, 1); - args[ARGNUM_0] = OBJECTREF_TO_ARGHOLDER(gc.TargetObj); - - CALL_MANAGED_METHOD_RETREF(gc.RetVal, STRINGREF, args); - - // - // Convert managed string to HSTRING - // - if (gc.RetVal == NULL) - *pResult = NULL; - else - hr = ::WindowsCreateString(gc.RetVal->GetBuffer(), gc.RetVal->GetStringLength(), pResult); - - GCPROTECT_END(); - - } - END_EXTERNAL_ENTRYPOINT; - - return hr; - -} - - -ULONG __stdcall -ICCW_AddRefFromJupiter(IUnknown* pUnk) -{ - CONTRACTL - { - NOTHROW; - GC_NOTRIGGER; - MODE_ANY; - PRECONDITION(CheckPointer(pUnk)); - PRECONDITION(IsSimpleTearOff(pUnk)); - } - CONTRACTL_END; - - SimpleComCallWrapper *pSimpleWrap = SimpleComCallWrapper::GetWrapperFromIP(pUnk); - - return pSimpleWrap->AddJupiterRef(); -} - -ULONG __stdcall -ICCW_ReleaseFromJupiter(IUnknown* pUnk) -{ - CONTRACTL - { - NOTHROW; - GC_TRIGGERS; - MODE_PREEMPTIVE; - PRECONDITION(CheckPointer(pUnk)); - } - CONTRACTL_END; - - ULONG cbRef = -1; - - HRESULT hr; - BEGIN_EXTERNAL_ENTRYPOINT(&hr) - { - SimpleComCallWrapper *pSimpleWrap = SimpleComCallWrapper::GetWrapperFromIP(pUnk); - - cbRef = pSimpleWrap->ReleaseJupiterRef(); - } - END_EXTERNAL_ENTRYPOINT; - - return cbRef; -} - -HRESULT __stdcall -ICCW_Peg(IUnknown* pUnk) -{ - CONTRACTL - { - NOTHROW; - GC_NOTRIGGER; - MODE_ANY; - PRECONDITION(CheckPointer(pUnk)); - } - CONTRACTL_END; - - SimpleComCallWrapper *pSimpleWrap = SimpleComCallWrapper::GetWrapperFromIP(pUnk); - - pSimpleWrap->MarkPegged(); - - STRESS_LOG1(LF_INTEROP, LL_INFO1000, "CCW 0x%p pegged\n", (ComCallWrapper *)pSimpleWrap->GetMainWrapper()); - - return S_OK; -} - -HRESULT __stdcall -ICCW_Unpeg(IUnknown* pUnk) -{ - CONTRACTL - { - NOTHROW; - GC_NOTRIGGER; - MODE_ANY; - PRECONDITION(CheckPointer(pUnk)); - } - CONTRACTL_END; - - SimpleComCallWrapper *pSimpleWrap = SimpleComCallWrapper::GetWrapperFromIP(pUnk); - - pSimpleWrap->UnMarkPegged(); - - STRESS_LOG1(LF_INTEROP, LL_INFO1000, "CCW 0x%p unpegged\n", (ComCallWrapper *)pSimpleWrap->GetMainWrapper()); - - return S_OK; -} diff --git a/src/coreclr/src/vm/stdinterfaces.h b/src/coreclr/src/vm/stdinterfaces.h index 9ff3289..1092235 100644 --- a/src/coreclr/src/vm/stdinterfaces.h +++ b/src/coreclr/src/vm/stdinterfaces.h @@ -19,21 +19,6 @@ #include "weakreference.h" #include "common.h" -extern const IID IID_IWeakReferenceSource; -extern const IID IID_IWeakReference; -extern const IID IID_ICustomPropertyProvider; -extern const IID IID_ICCW; - -// Until the Windows SDK is updated, just hard-code the IAgileObject IID -#ifndef __IAgileObject_INTERFACE_DEFINED__ -DEFINE_GUID(IID_IAgileObject,0x94ea2b94,0xe9cc,0x49e0,0xc0,0xff,0xee,0x64,0xca,0x8f,0x5b,0x90); -MIDL_INTERFACE("94ea2b94-e9cc-49e0-c0ff-ee64ca8f5b90") -IAgileObject : public IUnknown -{ -public: -}; -#endif // !__IAgileObject_INTERFACE_DEFINED__ - // Until the Windows SDK is updated, just hard-code the INoMarshal IID #ifndef __INoMarshal_INTERFACE_DEFINED__ DEFINE_GUID(IID_INoMarshal,0xecc8691b,0xc1db,0x4dc0,0x85,0x5e,0x65,0xf6,0xc5,0x51,0xaf,0x49); @@ -67,11 +52,7 @@ enum Enum_StdInterfaces enum_IConnectionPointContainer, enum_IObjectSafety, enum_IDispatchEx, - enum_IWeakReferenceSource, - enum_ICustomPropertyProvider, - enum_ICCW, enum_IAgileObject, - enum_IStringable, // add your favorite std interface here enum_LastStdVtable, @@ -120,11 +101,7 @@ extern const StdInterfaceDesc<8> g_IErrorInfo; extern const StdInterfaceDesc<5> g_IConnectionPointContainer; extern const StdInterfaceDesc<5> g_IObjectSafety; extern const StdInterfaceDesc<15> g_IDispatchEx; -extern const StdInterfaceDesc<4> g_IWeakReferenceSource; -extern const StdInterfaceDesc<10> g_ICustomPropertyProvider; -extern const StdInterfaceDesc<7> g_ICCW; extern const StdInterfaceDesc<3> g_IAgileObject; -extern const StdInterfaceDesc<7> g_IStringable; // enum class types enum ComClassType @@ -327,32 +304,6 @@ HRESULT __stdcall DispatchEx_InvokeEx_Wrapper ( IServiceProvider *pspCaller); //------------------------------------------------------------------------------------------ -// IInspectable methods for managed objects - -// IInspectable::GetIIDs -HRESULT __stdcall Inspectable_GetIIDs_Wrapper ( - IInspectable *pInsp, - ULONG *iidCount, - IID **iids); - -// IInspectable::GetRuntimeClassName -HRESULT __stdcall Inspectable_GetRuntimeClassName_Wrapper ( - IInspectable *pInsp, - HSTRING *className); - -// IInspectable::GetTrustLevel -HRESULT __stdcall Inspectable_GetTrustLevel_Wrapper ( - IInspectable *pInsp, - TrustLevel *trustLevel); - -//------------------------------------------------------------------------------------------ -// IWeakReferenceSource methods for managed objects - -HRESULT __stdcall WeakReferenceSource_GetWeakReference_Wrapper ( - IWeakReferenceSource *pRefSrc, - IWeakReference **weakReference); - -//------------------------------------------------------------------------------------------ // IMarshal methods for COM+ objects HRESULT __stdcall Marshal_GetUnmarshalClass_Wrapper ( @@ -411,51 +362,10 @@ HRESULT __stdcall ObjectSafety_SetInterfaceSafetyOptions_Wrapper(IUnknown* pUnk, DWORD dwOptionSetMask, DWORD dwEnabledOptions); - -//------------------------------------------------------------------------------------------ -// ICustomPropertyProvider methods for Jupiter -HRESULT __stdcall ICustomPropertyProvider_GetProperty_Wrapper(IUnknown *pPropertyProvider, - HSTRING hstrName, - /* [out] */ IUnknown **ppProperty); - -// Windows.UI.DirectUI.Xaml.TypeNameNative -struct TypeNameNative -{ - HSTRING typeName; - int typeKind; -}; - -HRESULT __stdcall ICustomPropertyProvider_GetIndexedProperty_Wrapper(IUnknown *pPropertyProvider, - HSTRING hstrName, - TypeNameNative indexedParamType, - /* [out, retval] */ IUnknown **ppProperty); - -HRESULT __stdcall ICustomPropertyProvider_GetStringRepresentation_Wrapper(IUnknown *pPropertyProvider, - /* [out, retval] */ HSTRING *phstrStringRepresentation); - -HRESULT __stdcall ICustomPropertyProvider_GetType_Wrapper(IUnknown *pPropertyProvider, - /* [out, retval] */ TypeNameNative *pTypeIdentifier); - -HRESULT __stdcall IStringable_ToString_Wrapper(IUnknown* pStringable, - /* [out, retval] */ HSTRING* result); - -//------------------------------------------------------------------------------------------ -// ICCW methods for Jupiter -ULONG __stdcall ICCW_AddRefFromJupiter_Wrapper(IUnknown *pUnk); - -ULONG __stdcall ICCW_ReleaseFromJupiter_Wrapper(IUnknown *pUnk); - -HRESULT __stdcall ICCW_Peg_Wrapper(IUnknown *pUnk); - -HRESULT __stdcall ICCW_Unpeg_Wrapper(IUnknown *pUnk); - - - // IUNKNOWN wrappers // prototypes IUnknown methods HRESULT __stdcall Unknown_QueryInterface(IUnknown* pUnk, REFIID riid, void** ppv); -HRESULT __stdcall Unknown_QueryInterface_ICCW(IUnknown *pUnk, REFIID riid, void **ppv); ULONG __stdcall Unknown_AddRef(IUnknown* pUnk); ULONG __stdcall Unknown_Release(IUnknown* pUnk); @@ -495,7 +405,7 @@ InternalDispatchImpl_Invoke ( //------------------------------------------------------------------------------------------ // Helper to get the current IErrorInfo if the specified interface supports it. -IErrorInfo *GetSupportedErrorInfo(IUnknown *iface, REFIID riid, BOOL checkForIRestrictedErrInfo = TRUE); +IErrorInfo *GetSupportedErrorInfo(IUnknown *iface, REFIID riid); //------------------------------------------------------------------------------------------ // Helpers to get the ITypeInfo* for a type. diff --git a/src/coreclr/src/vm/stdinterfaces_internal.h b/src/coreclr/src/vm/stdinterfaces_internal.h index 0b2fba0..ac261fa 100644 --- a/src/coreclr/src/vm/stdinterfaces_internal.h +++ b/src/coreclr/src/vm/stdinterfaces_internal.h @@ -241,46 +241,6 @@ HRESULT __stdcall DispatchEx_InvokeEx ( IServiceProvider *pspCaller); //------------------------------------------------------------------------------------------ -// IInspectable methods for managed objects - -// IInspectable::GetIIDs -HRESULT __stdcall Inspectable_GetIIDs ( - IInspectable *pInsp, - ULONG *iidCount, - IID **iids); - -HRESULT __stdcall Inspectable_GetRuntimeClassName ( - IInspectable *pInsp, - HSTRING *className); - -//------------------------------------------------------------------------------------------ -// IWeakReferenceSource methods for managed objects - -// IWeakReferenceSource::GetWeakReference -HRESULT __stdcall WeakReferenceSource_GetWeakReference ( - IWeakReferenceSource *pRefSrc, - IWeakReference **weakReference); - -//------------------------------------------------------------------------------------------ -// ICustomPropertyProvider methods for Jupiter data binding -HRESULT __stdcall ICustomPropertyProvider_GetProperty(IUnknown *pPropertyProvider, - HSTRING hstrName, - /* [out, retval] */ IUnknown **ppProperty); - -HRESULT __stdcall ICustomPropertyProvider_GetIndexedProperty(IUnknown *pPropertyProvider, - HSTRING hstrName, - TypeNameNative indexedParamType, - /* [out, retval] */ IUnknown **ppProperty); - -HRESULT __stdcall ICustomPropertyProvider_GetStringRepresentation(IUnknown *pPropertyProvider, - /* [out, retval] */ HSTRING *phstrStringRepresentation); -HRESULT __stdcall ICustomPropertyProvider_GetType(IUnknown *pPropertyProvider, - /* [out, retval] */ TypeNameNative *pTypeIdentifier); - -HRESULT __stdcall IStringable_ToString(IUnknown* pStringable, - /* [out, retval] */ HSTRING* pResult); - -//------------------------------------------------------------------------------------------ // IMarshal methods for COM+ objects HRESULT __stdcall Marshal_GetUnmarshalClass ( @@ -342,15 +302,5 @@ HRESULT __stdcall ObjectSafety_SetInterfaceSafetyOptions(IUnknown* pUnk, HRESULT __stdcall ClassInfo_GetClassInfo(IUnknown* pUnk, ITypeInfo** ppTI //Address of output variable that receives the type info. ); -//------------------------------------------------------------------------- -// ICCW methods -ULONG __stdcall ICCW_AddRefFromJupiter(IUnknown* pUnk); - -ULONG __stdcall ICCW_ReleaseFromJupiter(IUnknown* pUnk); - -HRESULT __stdcall ICCW_Peg(IUnknown* pUnk); - -HRESULT __stdcall ICCW_Unpeg(IUnknown* pUnk); - #endif diff --git a/src/coreclr/src/vm/stdinterfaces_wrapper.cpp b/src/coreclr/src/vm/stdinterfaces_wrapper.cpp index 30febca..f7a5584 100644 --- a/src/coreclr/src/vm/stdinterfaces_wrapper.cpp +++ b/src/coreclr/src/vm/stdinterfaces_wrapper.cpp @@ -175,51 +175,6 @@ const StdInterfaceDesc<15> g_IDispatchEx = } }; -// global IWeakReferenceSource vtable -const StdInterfaceDesc<4> g_IWeakReferenceSource = -{ - enum_IWeakReferenceSource, - { - (UINT_PTR*)Unknown_QueryInterface, - (UINT_PTR*)Unknown_AddRefSpecial, - (UINT_PTR*)Unknown_ReleaseSpecial, - (UINT_PTR*)WeakReferenceSource_GetWeakReference_Wrapper - } -}; - -// global ICustomPropertyProvider vtable -const StdInterfaceDesc<10> g_ICustomPropertyProvider = -{ - enum_ICustomPropertyProvider, - { - (UINT_PTR*)Unknown_QueryInterface, - (UINT_PTR*)Unknown_AddRefSpecial, - (UINT_PTR*)Unknown_ReleaseSpecial, - (UINT_PTR*)Inspectable_GetIIDs_Wrapper, - (UINT_PTR*)Inspectable_GetRuntimeClassName_Wrapper, - (UINT_PTR*)Inspectable_GetTrustLevel_Wrapper, - (UINT_PTR*)ICustomPropertyProvider_GetProperty_Wrapper, - (UINT_PTR*)ICustomPropertyProvider_GetIndexedProperty_Wrapper, - (UINT_PTR*)ICustomPropertyProvider_GetStringRepresentation_Wrapper, - (UINT_PTR*)ICustomPropertyProvider_GetType_Wrapper - } -}; - -// global ICCW vtable -const StdInterfaceDesc<7> g_ICCW = -{ - enum_ICCW, - { - (UINT_PTR*)Unknown_QueryInterface_ICCW, - (UINT_PTR*)Unknown_AddRefSpecial, - (UINT_PTR*)Unknown_ReleaseSpecial, - (UINT_PTR*)ICCW_AddRefFromJupiter_Wrapper, - (UINT_PTR*)ICCW_ReleaseFromJupiter_Wrapper, - (UINT_PTR*)ICCW_Peg_Wrapper, - (UINT_PTR*)ICCW_Unpeg_Wrapper - } -}; - // global IAgileObject vtable const StdInterfaceDesc<3> g_IAgileObject = { @@ -231,22 +186,6 @@ const StdInterfaceDesc<3> g_IAgileObject = } }; -// global IStringable vtable -const StdInterfaceDesc<7> g_IStringable = -{ - enum_IStringable, - { - (UINT_PTR*)Unknown_QueryInterface, - (UINT_PTR*)Unknown_AddRefSpecial, - (UINT_PTR*)Unknown_ReleaseSpecial, - (UINT_PTR*)Inspectable_GetIIDs_Wrapper, - (UINT_PTR*)Inspectable_GetRuntimeClassName_Wrapper, - (UINT_PTR*)Inspectable_GetTrustLevel_Wrapper, - (UINT_PTR*)IStringable_ToString_Wrapper - } -}; - - // Generic helper to check if AppDomain matches and perform a DoCallBack otherwise inline BOOL IsCurrentDomainValid(ComCallWrapper* pWrap, Thread* pThread) { @@ -398,77 +337,6 @@ HRESULT __stdcall Unknown_QueryInterface(IUnknown* pUnk, REFIID riid, void** ppv } } -// -// Non crashing version of Unknown_QueryInterface for ICCW -// This will either succeed and return a valid AddRef-ed interface pointer, or -// fail with COR_E_ACCESS_CCW -// -HRESULT __stdcall Unknown_QueryInterface_ICCW(IUnknown *pUnk, REFIID riid, void **ppv) -{ - SetupThreadForComCall(E_OUTOFMEMORY); - - CONTRACTL - { - NOTHROW; - GC_TRIGGERS; - MODE_PREEMPTIVE; - PRECONDITION(CheckPointer(pUnk)); - PRECONDITION(CheckPointer(ppv, NULL_OK)); - } - CONTRACTL_END; - - ComCallWrapper* pWrap = MapIUnknownToWrapper(pUnk); - - // - // AddRef to keep the object alive - // AddRef is "safe" at this point because if it is a CCW with outstanding Jupiter Ref, - // we know for sure the CCW is no claimed yet (but the object itself could be) - // - pWrap->AddRef(); - - CCWHolder pCCW = pWrap; - - // - // Check if the object is still alive, if it is, it'll be kept alive until we release the extra - // ref in CCWHolder - // We need to do this in COOP mode to make sure next GC will observe the AddRef change on RefCountHandle - // and avoids a race that GC could in the middle of NULL-ing out the RefCountHandle - // - { - GCX_COOP_THREAD_EXISTS(GET_THREAD()); - - SimpleComCallWrapper *pSimpleWrap = pWrap->GetSimpleWrapper(); - - // - // For CCWs that have outstanding Jupiter-reference, they could be either: - // 1. Neutered - in this case it is unsafe to touch m_ppThis - // 2. RefCounted handle NULLed out by GC - // - if (pWrap->GetSimpleWrapper()->IsNeutered() || - pWrap->GetObjectRef() == NULL) - { - // In those cases, it is unsafe to proceed with a QueryInterface call - return COR_E_ACCESSING_CCW; - } - } - - // - // OK. Now the CCW is going to be alive until the end of this scope. We can go ahead and do the - // QI now - // - if (IsCurrentDomainValid(pWrap, GET_THREAD())) - { - return Unknown_QueryInterface_Internal(pWrap, pUnk, riid, ppv); - } - else - { - HRESULT hr = S_OK; - QIArgs args = {pWrap, pUnk, &riid, ppv, &hr}; - Unknown_QueryInterface_CallBack(&args); - return hr; - } -} - struct AddRefReleaseArgs { IUnknown* pUnk; @@ -1981,182 +1849,6 @@ HRESULT __stdcall DispatchEx_InvokeEx_Wrapper(IDispatchEx* pDisp, DISPID id, LCI } // --------------------------------------------------------------------------- -// Interface IInspectable - -struct InspectableGetIIDsArgs -{ - IInspectable *pInsp; - ULONG *iidCount; - IID **iids; - HRESULT* hr; -}; - -VOID __stdcall Inspectable_GetIIDs_CallBack(LPVOID ptr) -{ - CONTRACTL - { - NOTHROW; - GC_TRIGGERS; - MODE_PREEMPTIVE; - PRECONDITION(CheckPointer(ptr)); - } - CONTRACTL_END; - - InspectableGetIIDsArgs* pArgs = (InspectableGetIIDsArgs *)ptr; - ComCallWrapper *pWrap = MapIUnknownToWrapper(pArgs->pInsp); - if (IsCurrentDomainValid(pWrap)) - { - *(pArgs->hr) = Inspectable_GetIIDs(pArgs->pInsp, pArgs->iidCount, pArgs->iids); - } - else - { - AppDomainDoCallBack(pWrap, Inspectable_GetIIDs_CallBack, pArgs, pArgs->hr); - } -} - -HRESULT __stdcall Inspectable_GetIIDs_Wrapper(IInspectable *pInsp, ULONG *iidCount, IID **iids) -{ - SetupForComCallHR(); - - CONTRACTL - { - NOTHROW; - GC_TRIGGERS; - MODE_PREEMPTIVE; - PRECONDITION(CheckPointer(pInsp)); - } - CONTRACTL_END; - - HRESULT hr = S_OK; - InspectableGetIIDsArgs args = {pInsp, iidCount, iids, &hr}; - Inspectable_GetIIDs_CallBack(&args); - return hr; -} - -struct InspectableGetRuntimeClassNameArgs -{ - IInspectable *pInsp; - HSTRING *className; - HRESULT* hr; -}; - -VOID Inspectable_GetRuntimeClassName_Callback(LPVOID ptr) -{ - CONTRACTL - { - NOTHROW; - GC_TRIGGERS; - MODE_PREEMPTIVE; - PRECONDITION(CheckPointer(ptr)); - } - CONTRACTL_END; - - InspectableGetRuntimeClassNameArgs* pArgs = (InspectableGetRuntimeClassNameArgs *)ptr; - ComCallWrapper *pWrap = MapIUnknownToWrapper(pArgs->pInsp); - if (IsCurrentDomainValid(pWrap)) - { - *(pArgs->hr) = Inspectable_GetRuntimeClassName(pArgs->pInsp, pArgs->className); - } - else - { - AppDomainDoCallBack(pWrap, Inspectable_GetRuntimeClassName_Callback, pArgs, pArgs->hr); - } -} - -HRESULT __stdcall Inspectable_GetRuntimeClassName_Wrapper(IInspectable *pInsp, HSTRING *className) -{ - SetupForComCallHR(); - - CONTRACTL - { - NOTHROW; - GC_TRIGGERS; - MODE_PREEMPTIVE; - PRECONDITION(CheckPointer(pInsp)); - } - CONTRACTL_END; - - HRESULT hr = S_OK; - InspectableGetRuntimeClassNameArgs args = { pInsp, className, &hr }; - Inspectable_GetRuntimeClassName_Callback(&args); - - return hr; -} - -HRESULT __stdcall Inspectable_GetTrustLevel_Wrapper(IInspectable *pInsp, TrustLevel *trustLevel) -{ - SetupForComCallHR(); - - CONTRACTL - { - NOTHROW; - GC_TRIGGERS; - MODE_PREEMPTIVE; - PRECONDITION(CheckPointer(pInsp)); - } - CONTRACTL_END; - - if (trustLevel == NULL) - return E_POINTER; - - // all managed WinRT objects are BaseTrust for now - *trustLevel = BaseTrust; - return S_OK; -} - -// --------------------------------------------------------------------------- -// Interface IWeakReferenceSource - -struct GetWeakReferenceArgs -{ - IWeakReferenceSource *pRefSrc; - IWeakReference **weakReference; - HRESULT* hr; -}; - -VOID __stdcall WeakReferenceSource_GetWeakReference_CallBack(LPVOID ptr) -{ - CONTRACTL - { - NOTHROW; - GC_TRIGGERS; - MODE_PREEMPTIVE; - PRECONDITION(CheckPointer(ptr)); - } - CONTRACTL_END; - - GetWeakReferenceArgs* pArgs = (GetWeakReferenceArgs *)ptr; - ComCallWrapper *pWrap = MapIUnknownToWrapper(pArgs->pRefSrc); - if (IsCurrentDomainValid(pWrap)) - { - *(pArgs->hr) = WeakReferenceSource_GetWeakReference(pArgs->pRefSrc, pArgs->weakReference); - } - else - { - AppDomainDoCallBack(pWrap, WeakReferenceSource_GetWeakReference_CallBack, pArgs, pArgs->hr); - } -} - -HRESULT __stdcall WeakReferenceSource_GetWeakReference_Wrapper(IWeakReferenceSource *pRefSrc, IWeakReference **weakReference) -{ - SetupForComCallHR(); - - CONTRACTL - { - NOTHROW; - GC_TRIGGERS; - MODE_PREEMPTIVE; - PRECONDITION(CheckPointer(pRefSrc)); - } - CONTRACTL_END; - - HRESULT hr = S_OK; - GetWeakReferenceArgs args = {pRefSrc, weakReference, &hr}; - WeakReferenceSource_GetWeakReference_CallBack(&args); - return hr; -} - -// --------------------------------------------------------------------------- // Interface IMarshal struct GetUnmarshalClassArgs @@ -2719,280 +2411,3 @@ HRESULT __stdcall ObjectSafety_SetInterfaceSafetyOptions_Wrapper(IUnknown* pUnk, ObjectSafety_SetInterfaceSafetyOptions_CallBack(&args); return hr; } - -//------------------------------------------------------------------------------------------ -// ICustomPropertyProvider methods for Jupiter - -#define APPDOMAIN_DOCALLBACK_CONTRACT \ - CONTRACTL \ - { \ - NOTHROW; \ - GC_TRIGGERS; \ - MODE_PREEMPTIVE; \ - PRECONDITION(CheckPointer(ptr)); \ - } \ - CONTRACTL_END; \ - - -struct ICustomPropertyProvider_GetProperty_Args -{ - IUnknown *pPropertyProvider; - HSTRING hstrName; - IUnknown **ppProperty; - HRESULT *pHR; -}; - -VOID __stdcall ICustomPropertyProvider_GetProperty_Callback(LPVOID ptr) -{ - APPDOMAIN_DOCALLBACK_CONTRACT; - - ICustomPropertyProvider_GetProperty_Args* pArgs = (ICustomPropertyProvider_GetProperty_Args*)ptr; - *(pArgs->pHR) = ICustomPropertyProvider_GetProperty(pArgs->pPropertyProvider, pArgs->hstrName, pArgs->ppProperty); -} - -HRESULT __stdcall ICustomPropertyProvider_GetProperty_Wrapper(IUnknown *pPropertyProvider, HSTRING hstrName, /* [out] */ IUnknown **ppProperty) -{ - SetupThreadForComCall(E_OUTOFMEMORY); - - CONTRACTL - { - NOTHROW; - GC_TRIGGERS; - MODE_PREEMPTIVE; - PRECONDITION(CheckPointer(pPropertyProvider)); - } - CONTRACTL_END; - - if (ppProperty == NULL) - return E_POINTER; - - - HRESULT hr = S_OK; - ComCallWrapper* pWrap = MapIUnknownToWrapper(pPropertyProvider); - if (IsCurrentDomainValid(pWrap)) - { - hr = ICustomPropertyProvider_GetProperty(pPropertyProvider, hstrName, ppProperty); - } - else - { - ICustomPropertyProvider_GetProperty_Args args = { pPropertyProvider, hstrName, ppProperty, &hr }; - AppDomainDoCallBack(pWrap, ICustomPropertyProvider_GetProperty_Callback, &args, &hr); - } - return hr; -} - -struct ICustomPropertyProvider_GetIndexedProperty_Args -{ - IUnknown *pPropertyProvider; - HSTRING hstrName; - TypeNameNative indexedParamType; - IUnknown **ppProperty; - HRESULT *pHR; -}; - -VOID __stdcall ICustomPropertyProvider_GetIndexedProperty_Callback(LPVOID ptr) -{ - APPDOMAIN_DOCALLBACK_CONTRACT; - - ICustomPropertyProvider_GetIndexedProperty_Args* pArgs = (ICustomPropertyProvider_GetIndexedProperty_Args*)ptr; - *(pArgs->pHR) = ICustomPropertyProvider_GetIndexedProperty(pArgs->pPropertyProvider, pArgs->hstrName, pArgs->indexedParamType, pArgs->ppProperty); -} - -HRESULT __stdcall ICustomPropertyProvider_GetIndexedProperty_Wrapper(IUnknown *pPropertyProvider, - HSTRING hstrName, - TypeNameNative indexedParamType, - /* [out, retval] */ IUnknown **ppProperty) -{ - SetupThreadForComCall(E_OUTOFMEMORY); - - CONTRACTL - { - NOTHROW; - GC_TRIGGERS; - MODE_PREEMPTIVE; - PRECONDITION(CheckPointer(pPropertyProvider)); - } - CONTRACTL_END; - - - HRESULT hr = S_OK; - ComCallWrapper* pWrap = MapIUnknownToWrapper(pPropertyProvider); - if (IsCurrentDomainValid(pWrap)) - { - hr = ICustomPropertyProvider_GetIndexedProperty(pPropertyProvider, hstrName, indexedParamType, ppProperty); - } - else - { - ICustomPropertyProvider_GetIndexedProperty_Args args = { pPropertyProvider, hstrName, indexedParamType, ppProperty, &hr }; - AppDomainDoCallBack(pWrap, ICustomPropertyProvider_GetIndexedProperty_Callback, &args, &hr); - } - - return hr; -} - -struct ICustomPropertyProvider_GetStringRepresentation_Args -{ - IUnknown *pPropertyProvider; - HSTRING *phstrStringRepresentation; - HRESULT *pHR; -}; - -VOID __stdcall ICustomPropertyProvider_GetStringRepresentation_Callback(LPVOID ptr) -{ - APPDOMAIN_DOCALLBACK_CONTRACT; - - ICustomPropertyProvider_GetStringRepresentation_Args* pArgs = (ICustomPropertyProvider_GetStringRepresentation_Args*)ptr; - *(pArgs->pHR) = ICustomPropertyProvider_GetStringRepresentation(pArgs->pPropertyProvider, pArgs->phstrStringRepresentation); -} - -HRESULT __stdcall ICustomPropertyProvider_GetStringRepresentation_Wrapper(IUnknown *pPropertyProvider, - /* [out, retval] */ HSTRING *phstrStringRepresentation) -{ - SetupThreadForComCall(E_OUTOFMEMORY); - - CONTRACTL - { - NOTHROW; - GC_TRIGGERS; - MODE_PREEMPTIVE; - PRECONDITION(CheckPointer(pPropertyProvider)); - } - CONTRACTL_END; - - HRESULT hr = S_OK; - ComCallWrapper* pWrap = MapIUnknownToWrapper(pPropertyProvider); - if (IsCurrentDomainValid(pWrap)) - { - hr = ICustomPropertyProvider_GetStringRepresentation(pPropertyProvider, phstrStringRepresentation); - } - else - { - ICustomPropertyProvider_GetStringRepresentation_Args args = { pPropertyProvider, phstrStringRepresentation, &hr }; - AppDomainDoCallBack(pWrap, ICustomPropertyProvider_GetStringRepresentation_Callback, &args, &hr); - } - - return hr; -} - -struct ICustomPropertyProvider_GetType_Args -{ - IUnknown *pPropertyProvider; - TypeNameNative *pTypeIdentifier; - HRESULT *pHR; -}; - -VOID __stdcall ICustomPropertyProvider_GetType_Callback(LPVOID ptr) -{ - APPDOMAIN_DOCALLBACK_CONTRACT; - - ICustomPropertyProvider_GetType_Args* pArgs = (ICustomPropertyProvider_GetType_Args*)ptr; - *(pArgs->pHR) = ICustomPropertyProvider_GetType(pArgs->pPropertyProvider, pArgs->pTypeIdentifier); -} - -HRESULT __stdcall ICustomPropertyProvider_GetType_Wrapper(IUnknown *pPropertyProvider, - /* [out, retval] */ TypeNameNative *pTypeIdentifier) -{ - SetupThreadForComCall(E_OUTOFMEMORY); - - CONTRACTL - { - NOTHROW; - GC_TRIGGERS; - MODE_PREEMPTIVE; - PRECONDITION(CheckPointer(pPropertyProvider)); - } - CONTRACTL_END; - - HRESULT hr = S_OK; - ComCallWrapper* pWrap = MapIUnknownToWrapper(pPropertyProvider); - if (IsCurrentDomainValid(pWrap)) - { - hr = ICustomPropertyProvider_GetType(pPropertyProvider, pTypeIdentifier); - } - else - { - ICustomPropertyProvider_GetType_Args args = { pPropertyProvider, pTypeIdentifier, &hr }; - AppDomainDoCallBack(pWrap, ICustomPropertyProvider_GetType_Callback, &args, &hr); - } - return hr; -} - - -struct IStringable_ToString_Args -{ - IUnknown *pStringable; - HSTRING *pResult; - HRESULT *pHR; -}; - -VOID __stdcall IStringable_ToString_Callback(LPVOID ptr) -{ - APPDOMAIN_DOCALLBACK_CONTRACT; - - IStringable_ToString_Args* pArgs = (IStringable_ToString_Args*)ptr; - *(pArgs->pHR) = IStringable_ToString(pArgs->pStringable, pArgs->pResult); -} - -HRESULT __stdcall IStringable_ToString_Wrapper(IUnknown *pStringable, - /* [out, retval] */ HSTRING *pResult) -{ - SetupThreadForComCall(E_OUTOFMEMORY); - - CONTRACTL - { - NOTHROW; - GC_TRIGGERS; - MODE_PREEMPTIVE; - PRECONDITION(CheckPointer(pStringable)); - } - CONTRACTL_END; - - HRESULT hr = S_OK; - ComCallWrapper* pWrap = MapIUnknownToWrapper(pStringable); - if (IsCurrentDomainValid(pWrap)) - { - hr = IStringable_ToString(pStringable, pResult); - } - else - { - IStringable_ToString_Args args = { pStringable, pResult, &hr }; - AppDomainDoCallBack(pWrap, IStringable_ToString_Callback, &args, &hr); - } - - return hr; -} - - -ULONG __stdcall ICCW_AddRefFromJupiter_Wrapper(IUnknown *pUnk) -{ - SetupForComCallDWORD(); - - WRAPPER_NO_CONTRACT; - - return ICCW_AddRefFromJupiter(pUnk); -} - -ULONG __stdcall ICCW_ReleaseFromJupiter_Wrapper(IUnknown *pUnk) -{ - SetupForComCallDWORD(); - - WRAPPER_NO_CONTRACT; - - return ICCW_ReleaseFromJupiter(pUnk); -} - -HRESULT __stdcall ICCW_Peg_Wrapper(IUnknown *pUnk) -{ - SetupForComCallHR(); - WRAPPER_NO_CONTRACT; - - return ICCW_Peg(pUnk); -} - -HRESULT __stdcall ICCW_Unpeg_Wrapper(IUnknown *pUnk) -{ - SetupForComCallHR(); - WRAPPER_NO_CONTRACT; - - return ICCW_Unpeg(pUnk); -} diff --git a/src/coreclr/src/vm/stubhelpers.cpp b/src/coreclr/src/vm/stubhelpers.cpp index 324597d..123885c 100644 --- a/src/coreclr/src/vm/stubhelpers.cpp +++ b/src/coreclr/src/vm/stubhelpers.cpp @@ -28,7 +28,6 @@ #include "comcallablewrapper.h" #include "clrtocomcall.h" #include "cominterfacemarshaler.h" -#include "winrttypenameconverter.h" #endif #ifdef VERIFY_HEAP @@ -329,14 +328,6 @@ NOINLINE static IUnknown* GetCOMIPFromRCWHelper(LPVOID pFCall, OBJECTREF pSrc, M ComPlusCallInfo *pComInfo = ComPlusCallInfo::FromMethodDesc(pMD); pRetUnk = ComObject::GetComIPFromRCWThrowing(&pSrc, pComInfo->m_pInterfaceMT); - if (pFCall == StubHelpers::GetCOMIPFromRCW_WinRT || - pFCall == StubHelpers::GetCOMIPFromRCW_WinRTSharedGeneric || - pFCall == StubHelpers::GetCOMIPFromRCW_WinRTDelegate) - { - pRetUnk.Release(); - } - - *ppTarget = GetCOMIPFromRCW_GetTarget(pRetUnk, pComInfo); _ASSERTE(*ppTarget != NULL); @@ -359,7 +350,7 @@ NOINLINE static IUnknown* GetCOMIPFromRCWHelper(LPVOID pFCall, OBJECTREF pSrc, M #include -// This helper can handle any CLR->COM call (classic COM, WinRT, WinRT delegate, WinRT generic), it supports hosting, +// This helper can handle any CLR->COM call, it supports hosting, // and clears FP state on x86 for compatibility with VB6. FCIMPL4(IUnknown*, StubHelpers::GetCOMIPFromRCW, Object* pSrcUNSAFE, MethodDesc* pMD, void **ppTarget, CLR_BOOL* pfNeedsRelease) { @@ -396,199 +387,8 @@ FCIMPL4(IUnknown*, StubHelpers::GetCOMIPFromRCW, Object* pSrcUNSAFE, MethodDesc* } FCIMPLEND -// This helper can handle only non-generic WinRT calls, does not support hosting/interception, and does not clear FP state. -FCIMPL3(IUnknown*, StubHelpers::GetCOMIPFromRCW_WinRT, Object* pSrcUNSAFE, MethodDesc* pMD, void** ppTarget) -{ - CONTRACTL - { - FCALL_CHECK; - PRECONDITION(pMD->IsComPlusCall()); - } - CONTRACTL_END; - - OBJECTREF pSrc = ObjectToOBJECTREF(pSrcUNSAFE); - - ComPlusCallInfo *pComInfo = ((ComPlusCallMethodDesc *)pMD)->m_pComPlusCallInfo; - RCW *pRCW = pSrc->PassiveGetSyncBlock()->GetInteropInfoNoCreate()->GetRawRCW(); - if (pRCW != NULL) - { - IUnknown *pUnk = GetCOMIPFromRCW_GetIUnknownFromRCWCache_NoInterception(pRCW, pComInfo, ppTarget); - if (pUnk != NULL) - { - return pUnk; - } - } - - /* if we didn't find the COM interface pointer in the cache we will have to erect an HMF */ - FC_INNER_RETURN(IUnknown*, GetCOMIPFromRCWHelper(StubHelpers::GetCOMIPFromRCW_WinRT, pSrc, pMD, ppTarget)); -} -FCIMPLEND - -// This helper can handle only generic WinRT calls, does not support hosting, and does not clear FP state. -FCIMPL3(IUnknown*, StubHelpers::GetCOMIPFromRCW_WinRTSharedGeneric, Object* pSrcUNSAFE, MethodDesc* pMD, void** ppTarget) -{ - CONTRACTL - { - FCALL_CHECK; - PRECONDITION(pMD->IsGenericComPlusCall()); - } - CONTRACTL_END; - - OBJECTREF pSrc = ObjectToOBJECTREF(pSrcUNSAFE); - - ComPlusCallInfo *pComInfo = pMD->AsInstantiatedMethodDesc()->IMD_GetComPlusCallInfo(); - RCW *pRCW = pSrc->PassiveGetSyncBlock()->GetInteropInfoNoCreate()->GetRawRCW(); - if (pRCW != NULL) - { - IUnknown *pUnk = GetCOMIPFromRCW_GetIUnknownFromRCWCache_NoInterception(pRCW, pComInfo, ppTarget); - if (pUnk != NULL) - { - return pUnk; - } - } - - /* if we didn't find the COM interface pointer in the cache we will have to erect an HMF */ - FC_INNER_RETURN(IUnknown*, GetCOMIPFromRCWHelper(StubHelpers::GetCOMIPFromRCW_WinRTSharedGeneric, pSrc, pMD, ppTarget)); -} -FCIMPLEND - -// This helper can handle only delegate WinRT calls, does not support hosting, and does not clear FP state. -FCIMPL3(IUnknown*, StubHelpers::GetCOMIPFromRCW_WinRTDelegate, Object* pSrcUNSAFE, MethodDesc* pMD, void** ppTarget) -{ - CONTRACTL - { - FCALL_CHECK; - PRECONDITION(pMD->IsEEImpl()); - } - CONTRACTL_END; - - OBJECTREF pSrc = ObjectToOBJECTREF(pSrcUNSAFE); - - ComPlusCallInfo *pComInfo = ((DelegateEEClass *)pMD->GetClass())->m_pComPlusCallInfo; - RCW *pRCW = pSrc->PassiveGetSyncBlock()->GetInteropInfoNoCreate()->GetRawRCW(); - if (pRCW != NULL) - { - IUnknown *pUnk = GetCOMIPFromRCW_GetIUnknownFromRCWCache_NoInterception(pRCW, pComInfo, ppTarget); - if (pUnk != NULL) - { - return pUnk; - } - } - - /* if we didn't find the COM interface pointer in the cache we will have to erect an HMF */ - FC_INNER_RETURN(IUnknown*, GetCOMIPFromRCWHelper(StubHelpers::GetCOMIPFromRCW_WinRTDelegate, pSrc, pMD, ppTarget)); -} -FCIMPLEND - #include - -NOINLINE static FC_BOOL_RET ShouldCallWinRTInterfaceHelper(RCW *pRCW, MethodTable *pItfMT) -{ - FC_INNER_PROLOG(StubHelpers::ShouldCallWinRTInterface); - - bool result = false; - - HELPER_METHOD_FRAME_BEGIN_RET_ATTRIB(Frame::FRAME_ATTR_EXACT_DEPTH|Frame::FRAME_ATTR_CAPTURE_DEPTH_2); - - // call the GC-triggering version - result = pRCW->SupportsWinRTInteropInterface(pItfMT); - - HELPER_METHOD_FRAME_END(); - FC_INNER_EPILOG(); - - FC_RETURN_BOOL(result); -} - -FCIMPL2(FC_BOOL_RET, StubHelpers::ShouldCallWinRTInterface, Object *pSrcUNSAFE, MethodDesc *pMD) -{ - FCALL_CONTRACT; - - OBJECTREF pSrc = ObjectToOBJECTREF(pSrcUNSAFE); - - ComPlusCallInfo *pComInfo = ComPlusCallInfo::FromMethodDesc(pMD); - RCW *pRCW = pSrc->PassiveGetSyncBlock()->GetInteropInfoNoCreate()->GetRawRCW(); - if (pRCW == NULL) - { - // Pretend that we are not redirected WinRT type - // We'll throw InvalidComObjectException later in GetComIPFromRCW - return false; - } - - TypeHandle::CastResult result = pRCW->SupportsWinRTInteropInterfaceNoGC(pComInfo->m_pInterfaceMT); - switch (result) - { - case TypeHandle::CanCast: FC_RETURN_BOOL(true); - case TypeHandle::CannotCast: FC_RETURN_BOOL(false); - } - - FC_INNER_RETURN(FC_BOOL_RET, ShouldCallWinRTInterfaceHelper(pRCW, pComInfo->m_pInterfaceMT)); -} -FCIMPLEND - -NOINLINE static DelegateObject *GetTargetForAmbiguousVariantCallHelper(RCW *pRCW, MethodTable *pMT, BOOL fIsEnumerable, CLR_BOOL *pfUseString) -{ - FC_INNER_PROLOG(StubHelpers::GetTargetForAmbiguousVariantCall); - - DelegateObject *pRetVal = NULL; - - HELPER_METHOD_FRAME_BEGIN_RET_ATTRIB(Frame::FRAME_ATTR_EXACT_DEPTH|Frame::FRAME_ATTR_CAPTURE_DEPTH_2); - - // Note that if the call succeeds, it will set the right OBJECTHANDLE/flags on the RCW so we won't have to do this - // next time. If the call fails, we don't care because it is an error and an exception will be thrown later. - SafeComHolder pUnk = pRCW->GetComIPFromRCW(pMT); - - WinRTInterfaceRedirector::WinRTLegalStructureBaseType baseType = WinRTInterfaceRedirector::GetStructureBaseType(pMT->GetInstantiation()); - - BOOL fUseString = FALSE; - BOOL fUseT = FALSE; - pRetVal = (DelegateObject *)OBJECTREFToObject(pRCW->GetTargetForAmbiguousVariantCall(fIsEnumerable, baseType, &fUseString, &fUseT)); - - *pfUseString = !!fUseString; - - HELPER_METHOD_FRAME_END(); - FC_INNER_EPILOG(); - - return pRetVal; -} - -// Performs a run-time check to see how an ambiguous variant call on an RCW should be handled. Returns a delegate which should -// be called, or sets *pfUseString to true which means that the caller should use the instantiation. If NULL is returned -// and *pfUseString is false, the caller should attempt to handle the call as usual. -FCIMPL3(DelegateObject*, StubHelpers::GetTargetForAmbiguousVariantCall, Object *pSrcUNSAFE, MethodTable *pMT, CLR_BOOL *pfUseString) -{ - FCALL_CONTRACT; - - OBJECTREF pSrc = ObjectToOBJECTREF(pSrcUNSAFE); - - RCW *pRCW = pSrc->PassiveGetSyncBlock()->GetInteropInfoNoCreate()->GetRawRCW(); - if (pRCW == NULL) - { - // ignore this - the call we'll attempt to make later will throw the right exception - *pfUseString = false; - return NULL; - } - - BOOL fIsEnumerable = pMT->HasSameTypeDefAs(MscorlibBinder::GetExistingClass(CLASS__IENUMERABLEGENERIC)); - _ASSERTE(fIsEnumerable || pMT->HasSameTypeDefAs(MscorlibBinder::GetExistingClass(CLASS__IREADONLYLISTGENERIC))); - - WinRTInterfaceRedirector::WinRTLegalStructureBaseType baseType = WinRTInterfaceRedirector::GetStructureBaseType(pMT->GetInstantiation()); - - BOOL fUseString = FALSE; - BOOL fUseT = FALSE; - DelegateObject *pRetVal = (DelegateObject *)OBJECTREFToObject(pRCW->GetTargetForAmbiguousVariantCall(fIsEnumerable, baseType, &fUseString, &fUseT)); - - if (pRetVal != NULL || fUseT || fUseString) - { - *pfUseString = !!fUseString; - return pRetVal; - } - - // we haven't seen QI for the interface yet, trigger it now - FC_INNER_RETURN(DelegateObject*, GetTargetForAmbiguousVariantCallHelper(pRCW, pMT, fIsEnumerable, pfUseString)); -} -FCIMPLEND - FCIMPL2(void, StubHelpers::ObjectMarshaler__ConvertToNative, Object* pSrcUNSAFE, VARIANT* pDest) { FCALL_CONTRACT; @@ -697,245 +497,6 @@ void QCALLTYPE StubHelpers::InterfaceMarshaler__ClearNative(IUnknown * pUnk) } #include - - - -FCIMPL1(StringObject*, StubHelpers::UriMarshaler__GetRawUriFromNative, ABI::Windows::Foundation::IUriRuntimeClass* pIUriRC) -{ - FCALL_CONTRACT; - - if (NULL == pIUriRC) - { - return NULL; - } - - STRINGREF strRef = NULL; - UINT32 cchRawUri = 0; - LPCWSTR pwszRawUri = NULL; - - HELPER_METHOD_FRAME_BEGIN_RET_1(strRef); - - WinRtString hsRawUriName; - - { - GCX_PREEMP(); - - // Get the RawUri string from the WinRT URI object - IfFailThrow(pIUriRC->get_RawUri(hsRawUriName.Address())); - - pwszRawUri = hsRawUriName.GetRawBuffer(&cchRawUri); - } - - strRef = StringObject::NewString(pwszRawUri, cchRawUri); - - HELPER_METHOD_FRAME_END(); - - return STRINGREFToObject(strRef); -} -FCIMPLEND - -FCIMPL2(IUnknown*, StubHelpers::UriMarshaler__CreateNativeUriInstance, WCHAR* pRawUri, UINT strLen) -{ - CONTRACTL { - FCALL_CHECK; - PRECONDITION(CheckPointer(pRawUri)); - } - CONTRACTL_END; - - ABI::Windows::Foundation::IUriRuntimeClass* pIUriRC = NULL; - - HELPER_METHOD_FRAME_BEGIN_RET_0(); - - GCX_PREEMP(); - pIUriRC = CreateWinRTUri(pRawUri, strLen); - - HELPER_METHOD_FRAME_END(); - - return pIUriRC; -} -FCIMPLEND - -// A helper to convert an IP to object using special flags. -FCIMPL1(Object *, StubHelpers::InterfaceMarshaler__ConvertToManagedWithoutUnboxing, IUnknown *pNative) -{ - FCALL_CONTRACT; - - OBJECTREF oref = NULL; - - HELPER_METHOD_FRAME_BEGIN_RET_1(oref); - - // - // Get a wrapper for pNative - // Note that we need to skip WinRT unboxing at this point because - // 1. We never know whether GetObjectRefFromComIP went through unboxing path. - // For example, user could just pass a IUnknown * to T and we'll happily convert that to T - // 2. If for some reason we end up getting something that does not implement IReference, - // we'll get a nice message later when we do the cast in CLRIReferenceImpl.UnboxHelper - // - GetObjectRefFromComIP( - &oref, - pNative, // pUnk - g_pBaseCOMObject, // Use __ComObject - NULL, // pItfMT - ObjFromComIP::CLASS_IS_HINT | // No cast check - we'll do cast later - ObjFromComIP::UNIQUE_OBJECT | // Do not cache the object - To ensure that the unboxing code is called on this object always - // and the object is not retrieved from the cache as an __ComObject. - // Don't call GetRuntimeClassName - I just want a RCW of __ComObject - ObjFromComIP::IGNORE_WINRT_AND_SKIP_UNBOXING // Skip unboxing - ); - - HELPER_METHOD_FRAME_END(); - - return OBJECTREFToObject(oref); -} -FCIMPLEND - -FCIMPL2(StringObject *, StubHelpers::WinRTTypeNameConverter__ConvertToWinRTTypeName, - ReflectClassBaseObject *pTypeUNSAFE, CLR_BOOL *pbIsWinRTPrimitive) -{ - CONTRACTL - { - FCALL_CHECK; - PRECONDITION(CheckPointer(pTypeUNSAFE)); - PRECONDITION(CheckPointer(pbIsWinRTPrimitive)); - } - CONTRACTL_END; - - REFLECTCLASSBASEREF refClass = (REFLECTCLASSBASEREF) pTypeUNSAFE; - STRINGREF refString= NULL; - HELPER_METHOD_FRAME_BEGIN_RET_2(refClass, refString); - - SString strWinRTTypeName; - bool bIsPrimitive; - if (WinRTTypeNameConverter::AppendWinRTTypeNameForManagedType( - refClass->GetType(), // thManagedType - strWinRTTypeName, // strWinRTTypeName to append - FALSE, // for type conversion, not for GetRuntimeClassName - &bIsPrimitive - )) - { - *pbIsWinRTPrimitive = bIsPrimitive; - refString = AllocateString(strWinRTTypeName); - } - else - { - *pbIsWinRTPrimitive = FALSE; - refString = NULL; - } - - HELPER_METHOD_FRAME_END(); - - return STRINGREFToObject(refString); -} -FCIMPLEND - -FCIMPL2(ReflectClassBaseObject *, StubHelpers::WinRTTypeNameConverter__GetTypeFromWinRTTypeName, StringObject *pWinRTTypeNameUNSAFE, CLR_BOOL *pbIsPrimitive) -{ - CONTRACTL - { - FCALL_CHECK; - PRECONDITION(CheckPointer(pWinRTTypeNameUNSAFE)); - } - CONTRACTL_END; - - OBJECTREF refClass = NULL; - STRINGREF refString = ObjectToSTRINGREF(pWinRTTypeNameUNSAFE); - HELPER_METHOD_FRAME_BEGIN_RET_2(refClass, refString); - - bool isPrimitive; - TypeHandle th = WinRTTypeNameConverter::LoadManagedTypeForWinRTTypeName(refString->GetBuffer(), /* pLoadBinder */ nullptr, &isPrimitive); - *pbIsPrimitive = isPrimitive; - - refClass = th.GetManagedClassObject(); - - HELPER_METHOD_FRAME_END(); - - return (ReflectClassBaseObject *)OBJECTREFToObject(refClass); -} -FCIMPLEND - -FCIMPL1(MethodDesc*, StubHelpers::GetDelegateInvokeMethod, DelegateObject *pThisUNSAFE) -{ - FCALL_CONTRACT; - - MethodDesc *pMD = NULL; - - OBJECTREF pThis = ObjectToOBJECTREF(pThisUNSAFE); - HELPER_METHOD_FRAME_BEGIN_RET_1(pThis); - - MethodTable *pDelMT = pThis->GetMethodTable(); - - pMD = COMDelegate::FindDelegateInvokeMethod(pDelMT); - if (pMD->IsSharedByGenericInstantiations()) - { - // we need the exact MethodDesc - pMD = InstantiatedMethodDesc::FindOrCreateExactClassMethod(pDelMT, pMD); - } - - HELPER_METHOD_FRAME_END(); - - _ASSERTE(pMD); - return pMD; -} -FCIMPLEND - -// Called from COM-to-CLR factory method stubs to get the return value (the delegating interface pointer -// corresponding to the default WinRT interface of the class which we are constructing). -FCIMPL2(IInspectable *, StubHelpers::GetWinRTFactoryReturnValue, Object *pThisUNSAFE, PCODE pCtorEntry) -{ - FCALL_CONTRACT; - - IInspectable *pInsp = NULL; - - OBJECTREF pThis = ObjectToOBJECTREF(pThisUNSAFE); - HELPER_METHOD_FRAME_BEGIN_RET_1(pThis); - - // COM-to-CLR stubs use the target method entry point as their stub context - MethodDesc *pCtorMD = Entry2MethodDesc(pCtorEntry, NULL); - MethodTable *pClassMT = pCtorMD->GetMethodTable(); - - // make sure that we talk to the right CCW - ComCallWrapperTemplate *pTemplate = ComCallWrapperTemplate::GetTemplate(TypeHandle(pClassMT)); - CCWHolder pWrap = ComCallWrapper::InlineGetWrapper(&pThis, pTemplate); - - MethodTable *pDefaultItf = pClassMT->GetDefaultWinRTInterface(); - const IID &riid = (pDefaultItf == NULL ? IID_IInspectable : IID_NULL); - - pInsp = static_cast(ComCallWrapper::GetComIPFromCCW(pWrap, riid, pDefaultItf, - GetComIPFromCCW::CheckVisibility)); - - HELPER_METHOD_FRAME_END(); - - return pInsp; -} -FCIMPLEND - -// Called from CLR-to-COM factory method stubs to get the outer IInspectable to pass -// to the underlying factory object. -FCIMPL2(IInspectable *, StubHelpers::GetOuterInspectable, Object *pThisUNSAFE, MethodDesc *pCtorMD) -{ - FCALL_CONTRACT; - - IInspectable *pInsp = NULL; - - OBJECTREF pThis = ObjectToOBJECTREF(pThisUNSAFE); - - if (pThis->GetMethodTable() != pCtorMD->GetMethodTable()) - { - // this is a composition scenario - HELPER_METHOD_FRAME_BEGIN_RET_1(pThis); - - // we don't have the "outer" yet, marshal the object - pInsp = static_cast - (MarshalObjectToInterface(&pThis, NULL, NULL, ItfMarshalInfo::ITF_MARSHAL_INSP_ITF | ItfMarshalInfo::ITF_MARSHAL_USE_BASIC_ITF)); - - HELPER_METHOD_FRAME_END(); - } - - return pInsp; -} -FCIMPLEND - #endif // FEATURE_COMINTEROP FCIMPL0(void, StubHelpers::SetLastError) @@ -1120,8 +681,6 @@ public : { LIMITED_METHOD_CONTRACT; - _ASSERTE(pRCW->SupportsIInspectable()); - // Is this a free threaded RCW or a context-bound RCW created in the same context if (pRCW->IsFreeThreaded() || pRCW->GetWrapperCtxCookie() == m_pCtxCookie) @@ -1179,86 +738,6 @@ private : bool m_bIsDCOMProxy; // Is this a proxy to an object in a different process }; -// -// Retrieve cached WinRT factory RCW or create a new one, according to the MethodDesc of the .ctor -// -FCIMPL1(Object*, StubHelpers::GetWinRTFactoryObject, MethodDesc *pCMD) -{ - FCALL_CONTRACT; - - OBJECTREF refFactory = NULL; - - HELPER_METHOD_FRAME_BEGIN_RET_1(refFactory); - - MethodTable *pMTOfTypeToCreate = pCMD->GetMethodTable(); - AppDomain *pDomain = GetAppDomain(); - - // - // Look up cached WinRT factory according to type to create + current context cookie - // For each type in AppDomain, we cache only the last WinRT factory object - // We don't cache factory per context in order to avoid explosion of objects if there are - // multiple STA apartments - // - // Note that if cached WinRT factory is FTM, we'll get it back regardless of the supplied cookie - // - LPVOID lpCtxCookie = GetCurrentCtxCookie(); - refFactory = pDomain->LookupWinRTFactoryObject(pMTOfTypeToCreate, lpCtxCookie); - if (refFactory == NULL) - { - // - // Didn't find a cached factory that matches the context - // Time to create a new factory and wrap it in a RCW - // - - // - // Creates a callback to checks for singleton WinRT factory during RCW creation - // - // If we get back an existing RCW from a different context, this callback - // will make the RCW a context-agile (but not free-threaded) RCW. Being context-agile - // in this case means RCW will not make any context transition. As long as we are only - // calling this RCW from where we got it back (using IInspectable* as identity), we should - // be fine (as we are supposed to call that pointer directly anyway) - // - // See code:COMInterfaceMarshalerCallback for more details - // - COMInterfaceMarshalerCallback callback(GET_THREAD(), lpCtxCookie); - - // - // Get the activation factory instance for this WinRT type and create a RCW for it - // - GetNativeWinRTFactoryObject( - pMTOfTypeToCreate, - GET_THREAD(), - ComPlusCallInfo::FromMethodDesc(pCMD)->m_pInterfaceMT, // Factory interface - FALSE, // Don't need a unique RCW - // it is only needed in WindowsRuntimeMarshal.GetActivationFactory API - &callback, - &refFactory); - - // - // If this is free-threaded factory RCW, set lpCtxCookie = NULL, which means - // this RCW can be used anywhere - // Otherwise, we can only use this RCW from current thread - // - if (callback.IsFreeThreaded()) - lpCtxCookie = NULL; - - // Cache the result in the AD-wide cache, unless this is a proxy to a DCOM object. - // Out of process WinRT servers can have lifetimes independent of the application, - // and the cache may wind up with stale pointers if we save proxies to OOP factories. - if (!callback.IsDCOMProxy()) - { - pDomain->CacheWinRTFactoryObject(pMTOfTypeToCreate, &refFactory, lpCtxCookie); - } - } - - HELPER_METHOD_FRAME_END(); - - return OBJECTREFToObject(refFactory); -} -FCIMPLEND - - #endif #ifdef PROFILING_SUPPORTED @@ -1404,7 +883,7 @@ FCIMPL1(Object*, StubHelpers::GetHRExceptionObject, HRESULT hr) FCIMPLEND #ifdef FEATURE_COMINTEROP -FCIMPL4(Object*, StubHelpers::GetCOMHRExceptionObject, HRESULT hr, MethodDesc *pMD, Object *unsafe_pThis, CLR_BOOL fForWinRT) +FCIMPL3(Object*, StubHelpers::GetCOMHRExceptionObject, HRESULT hr, MethodDesc *pMD, Object *unsafe_pThis) { FCALL_CONTRACT; @@ -1417,21 +896,6 @@ FCIMPL4(Object*, StubHelpers::GetCOMHRExceptionObject, HRESULT hr, MethodDesc *p { IErrorInfo *pErrInfo = NULL; - IRestrictedErrorInfo *pResErrorInfo = NULL; - BOOL bHasNonCLRLanguageErrorObject = FALSE; - - if (fForWinRT) - { - SafeGetRestrictedErrorInfo(&pResErrorInfo); - if (pResErrorInfo != NULL) - { - // If we have a restricted error Info lets try and find the corresponding errorInfo, - // bHasNonCLRLanguageErrorObject can be TRUE|FALSE depending on whether we have an associtated LanguageExceptionObject - // and whether it is CLR exceptionObject => bHasNonCLRLanguageErrorObject = FALSE; - // or whether it is a non-CLRExceptionObject => bHasNonCLRLanguageErrorObject = TRUE; - pErrInfo = GetCorrepondingErrorInfo_WinRT(hr, pResErrorInfo, &bHasNonCLRLanguageErrorObject); - } - } if (pErrInfo == NULL && pMD != NULL) { // Retrieve the interface method table. @@ -1444,14 +908,14 @@ FCIMPL4(Object*, StubHelpers::GetCOMHRExceptionObject, HRESULT hr, MethodDesc *p // Check to see if the component supports error information for this interface. IID ItfIID; pItfMT->GetGuid(&ItfIID, TRUE); - pErrInfo = GetSupportedErrorInfo(pUnk, ItfIID, !fForWinRT); + pErrInfo = GetSupportedErrorInfo(pUnk, ItfIID); DWORD cbRef = SafeRelease(pUnk); LogInteropRelease(pUnk, cbRef, "IUnk to QI for ISupportsErrorInfo"); } } - GetExceptionForHR(hr, pErrInfo, !fForWinRT, &oThrowable, pResErrorInfo, bHasNonCLRLanguageErrorObject); + GetExceptionForHR(hr, pErrInfo, &oThrowable); } HELPER_METHOD_FRAME_END(); diff --git a/src/coreclr/src/vm/stubhelpers.h b/src/coreclr/src/vm/stubhelpers.h index cbc1c60..5c047bd 100644 --- a/src/coreclr/src/vm/stubhelpers.h +++ b/src/coreclr/src/vm/stubhelpers.h @@ -48,12 +48,6 @@ public: #ifdef FEATURE_COMINTEROP static FCDECL4(IUnknown*, GetCOMIPFromRCW, Object* pSrcUNSAFE, MethodDesc* pMD, void **ppTarget, CLR_BOOL* pfNeedsRelease); - static FCDECL3(IUnknown*, GetCOMIPFromRCW_WinRT, Object* pSrcUNSAFE, MethodDesc* pMD, void **ppTarget); - static FCDECL3(IUnknown*, GetCOMIPFromRCW_WinRTSharedGeneric, Object* pSrcUNSAFE, MethodDesc* pMD, void **ppTarget); - static FCDECL3(IUnknown*, GetCOMIPFromRCW_WinRTDelegate, Object* pSrcUNSAFE, MethodDesc* pMD, void **ppTarget); - - static FCDECL2(FC_BOOL_RET, ShouldCallWinRTInterface, Object* pSrcUNSAFE, MethodDesc* pMD); - static FCDECL3(DelegateObject*, GetTargetForAmbiguousVariantCall, Object* pSrcUNSAFE, MethodTable* pMT, CLR_BOOL *pfUseString); static FCDECL2(void, ObjectMarshaler__ConvertToNative, Object* pSrcUNSAFE, VARIANT* pDest); static FCDECL1(Object*, ObjectMarshaler__ConvertToManaged, VARIANT* pSrc); @@ -63,13 +57,6 @@ public: static FCDECL4(Object*, InterfaceMarshaler__ConvertToManaged, IUnknown **ppUnk, MethodTable *pItfMT, MethodTable *pClsMT, DWORD dwFlags); static void QCALLTYPE InterfaceMarshaler__ClearNative(IUnknown * pUnk); static FCDECL1(Object *, InterfaceMarshaler__ConvertToManagedWithoutUnboxing, IUnknown *pNative); - - static FCDECL1(StringObject*, UriMarshaler__GetRawUriFromNative, ABI::Windows::Foundation::IUriRuntimeClass* pIUriRC); - static FCDECL2(IUnknown*, UriMarshaler__CreateNativeUriInstance, __in_ecount(strLen) CLR_CHAR* pRawUriObj, UINT strLen); - - static FCDECL1(MethodDesc *, GetDelegateInvokeMethod, DelegateObject *pThisUNSAFE); - static FCDECL2(IInspectable *, GetWinRTFactoryReturnValue, Object *pThisUNSAFE, PCODE pCtorEntry); - static FCDECL2(IInspectable *, GetOuterInspectable, Object *pThisUNSAFE, MethodDesc *pCtorMD); #endif // FEATURE_COMINTEROP static FCDECL0(void, SetLastError ); @@ -84,7 +71,7 @@ public: static FCDECL1(Object*, GetHRExceptionObject, HRESULT hr); #ifdef FEATURE_COMINTEROP - static FCDECL4(Object*, GetCOMHRExceptionObject, HRESULT hr, MethodDesc *pMD, Object *unsafe_pThis, CLR_BOOL fForWinRT); + static FCDECL3(Object*, GetCOMHRExceptionObject, HRESULT hr, MethodDesc *pMD, Object *unsafe_pThis); #endif // FEATURE_COMINTEROP static FCDECL3(void*, CreateCustomMarshalerHelper, MethodDesc* pMD, mdToken paramToken, TypeHandle hndManagedType); @@ -104,10 +91,6 @@ public: static FCDECL3(void, ValidateObject, Object *pObjUNSAFE, MethodDesc *pMD, Object *pThisUNSAFE); static FCDECL3(void, ValidateByref, void *pByref, MethodDesc *pMD, Object *pThisUNSAFE); -#ifdef FEATURE_COMINTEROP - static FCDECL1(Object*, GetWinRTFactoryObject, MethodDesc *pCMD); -#endif // FEATURE_COMINTEROP - #ifdef PROFILING_SUPPORTED //------------------------------------------------------- // Profiler helper @@ -120,11 +103,6 @@ public: static FCDECL2(void, ArrayTypeCheck, Object*, PtrArray*); #endif -#ifdef FEATURE_COMINTEROP - static FCDECL2(StringObject *, WinRTTypeNameConverter__ConvertToWinRTTypeName, ReflectClassBaseObject *pTypeUNSAFE, CLR_BOOL *pbIsWinRTPrimitive); - static FCDECL2(ReflectClassBaseObject *, WinRTTypeNameConverter__GetTypeFromWinRTTypeName, StringObject *pWinRTTypeNameUNSAFE, CLR_BOOL *pbIsPrimitive); -#endif // FEATURE_COMINTEROP - #ifdef FEATURE_MULTICASTSTUB_AS_IL static FCDECL2(void, MulticastDebuggerTraceHelper, Object*, INT32); #endif diff --git a/src/coreclr/src/vm/stubmgr.cpp b/src/coreclr/src/vm/stubmgr.cpp index 12cbd48..3477154 100644 --- a/src/coreclr/src/vm/stubmgr.cpp +++ b/src/coreclr/src/vm/stubmgr.cpp @@ -1687,50 +1687,6 @@ PCODE ILStubManager::GetCOMTarget(Object *pThis, ComPlusCallInfo *pComPlusCallIn PCODE target = (PCODE)lpVtbl[pComPlusCallInfo->m_cachedComSlot]; return target; } - -// This function should return the same result as StubHelpers::GetWinRTFactoryObject followed by -// ILStubManager::GetCOMTarget. The difference is that it does not allocate managed memory, so it -// does not trigger GC. -// -// The reason why GC (and potentially a stack walk for other purposes, such as exception handling) -// would be problematic is that we are stopped at the first instruction of an IL stub which is -// not a GC-safe point. Technically, the function still has the GC_TRIGGERS contract but we should -// not see GC in practice here without allocating. -// -// Note that the GC suspension logic detects the debugger-is-attached-at-GC-unsafe-point case and -// will back off and retry. This means that it suffices to ensure that this thread does not trigger -// GC, allocations on other threads will wait and not cause major trouble. -PCODE ILStubManager::GetWinRTFactoryTarget(ComPlusCallMethodDesc *pCMD) -{ - CONTRACTL - { - THROWS; - GC_TRIGGERS; - MODE_COOPERATIVE; - } - CONTRACTL_END; - - MethodTable *pMT = pCMD->GetMethodTable(); - - // GetComClassFactory could load types and trigger GC, get class name manually - InlineSString ssClassName; - pMT->_GetFullyQualifiedNameForClass(ssClassName); - - IID iid; - pCMD->m_pComPlusCallInfo->m_pInterfaceMT->GetGuid(&iid, FALSE, FALSE); - - SafeComHolder pFactory; - { - GCX_PREEMP(); - if (SUCCEEDED(RoGetActivationFactory(WinRtStringRef(ssClassName.GetUnicode(), ssClassName.GetCount()), iid, &pFactory))) - { - LPVOID *lpVtbl = *(LPVOID **)(IUnknown *)pFactory; - return (PCODE)lpVtbl[pCMD->m_pComPlusCallInfo->m_cachedComSlot]; - } - } - - return NULL; -} #endif // FEATURE_COMINTEROP #ifndef CROSSGEN_COMPILE @@ -1831,19 +1787,6 @@ BOOL ILStubManager::TraceManager(Thread *thread, LOG((LF_CORDB, LL_INFO10000, "ILSM::TraceManager: Unmanaged CALLI case 0x%x\n", target)); trace->InitForUnmanaged(target); } -#ifdef FEATURE_COMINTEROP - else if (pStubMD->IsDelegateCOMStub()) - { - // This is a delegate, but the target is COM. - DelegateObject *pDel = (DelegateObject *)pThis; - DelegateEEClass *pClass = (DelegateEEClass *)pDel->GetMethodTable()->GetClass(); - - target = GetCOMTarget(pThis, pClass->m_pComPlusCallInfo); - - LOG((LF_CORDB, LL_INFO10000, "ILSM::TraceManager: CLR-to-COM via delegate case 0x%x\n", target)); - trace->InitForUnmanaged(target); - } -#endif // FEATURE_COMINTEROP else if (pStubMD->IsStructMarshalStub()) { // There's no "target" for struct marshalling stubs @@ -1866,27 +1809,7 @@ BOOL ILStubManager::TraceManager(Thread *thread, { _ASSERTE(pMD->IsComPlusCall()); ComPlusCallMethodDesc *pCMD = (ComPlusCallMethodDesc *)pMD; - - if (pCMD->IsStatic() || pCMD->IsCtor()) - { - // pThis is not the object we'll be calling, we need to get the factory object instead - MethodTable *pMTOfTypeToCreate = pCMD->GetMethodTable(); - pThis = OBJECTREFToObject(GetAppDomain()->LookupWinRTFactoryObject(pMTOfTypeToCreate, GetCurrentCtxCookie())); - - if (pThis == NULL) - { - // If we don't have an RCW of the factory object yet, don't create it. We would - // risk triggering GC which is not safe here because the IL stub is not at a GC - // safe point. Instead, query WinRT directly and release the factory immediately. - target = GetWinRTFactoryTarget(pCMD); - - if (target != NULL) - { - LOG((LF_CORDB, LL_INFO10000, "ILSM::TraceManager: CLR-to-COM WinRT factory RCW-does-not-exist-yet case 0x%x\n", target)); - trace->InitForUnmanaged(target); - } - } - } + _ASSERTE(!pCMD->IsStatic() && !pCMD->IsCtor() && "Static methods and constructors are not supported for built-in classic COM"); if (pThis != NULL) { diff --git a/src/coreclr/src/vm/stubmgr.h b/src/coreclr/src/vm/stubmgr.h index 409bb88..dba33f4 100644 --- a/src/coreclr/src/vm/stubmgr.h +++ b/src/coreclr/src/vm/stubmgr.h @@ -714,7 +714,6 @@ class ILStubManager : public StubManager #ifndef DACCESS_COMPILE #ifdef FEATURE_COMINTEROP static PCODE GetCOMTarget(Object *pThis, ComPlusCallInfo *pComPlusCallInfo); - static PCODE GetWinRTFactoryTarget(ComPlusCallMethodDesc *pCMD); #endif // FEATURE_COMINTEROP virtual BOOL TraceManager(Thread *thread, diff --git a/src/coreclr/src/vm/synchronizationcontextnative.cpp b/src/coreclr/src/vm/synchronizationcontextnative.cpp deleted file mode 100644 index 447053c..0000000 --- a/src/coreclr/src/vm/synchronizationcontextnative.cpp +++ /dev/null @@ -1,152 +0,0 @@ -// 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. - -/*============================================================ -** -** Implementation: SynchronizationContextNative.cpp -** -** -** Purpose: Native methods on System.Threading.SynchronizationContext. -** -** -===========================================================*/ - -#include "common.h" - -#ifdef FEATURE_APPX -#include -#include -#include "winrtdispatcherqueue.h" -#include "synchronizationcontextnative.h" - -Volatile g_pICoreWindowStatic; - -void* QCALLTYPE SynchronizationContextNative::GetWinRTDispatcherForCurrentThread() -{ - QCALL_CONTRACT; - void* result = NULL; - BEGIN_QCALL; - - _ASSERTE(WinRTSupported()); - - // - // Get access to ICoreWindow's statics. We grab just one ICoreWindowStatic for the whole process. - // - ABI::Windows::UI::Core::ICoreWindowStatic* pICoreWindowStatic = g_pICoreWindowStatic; - if (pICoreWindowStatic == NULL) - { - SafeComHolderPreemp pNewICoreWindowStatic; - { - HRESULT hr = clr::winrt::GetActivationFactory(RuntimeClass_Windows_UI_Core_CoreWindow, (ABI::Windows::UI::Core::ICoreWindowStatic**)pNewICoreWindowStatic.GetAddr()); - - // - // Older Windows builds don't support ICoreWindowStatic. We should just return a null CoreDispatcher - // in that case, rather than throwing. - // - if (hr != E_NOTIMPL) - IfFailThrow(hr); - } - - if (pNewICoreWindowStatic != NULL) - { - ABI::Windows::UI::Core::ICoreWindowStatic* old = InterlockedCompareExchangeT(&g_pICoreWindowStatic, pNewICoreWindowStatic, NULL); - if (old == NULL) - { - pNewICoreWindowStatic.SuppressRelease(); - pICoreWindowStatic = pNewICoreWindowStatic; - } - else - { - pICoreWindowStatic = old; - } - } - } - - - if (pICoreWindowStatic != NULL) - { - // - // Get the current ICoreWindow - // - SafeComHolderPreemp pCoreWindow; - - // - // workaround: we're currently ignoring the HRESULT from get_Current, because Windows is returning errors for threads that have no CoreWindow. - // A better behavior would be to return S_OK, with a NULL CoreWindow. If/when Windows does the right thing here, we can change this - // back to checking the HRESULT. - // - pICoreWindowStatic->GetForCurrentThread(&pCoreWindow); - - if (pCoreWindow != NULL) - { - // - // Get the ICoreDispatcher for this window - // - SafeComHolderPreemp pCoreDispatcher; - IfFailThrow(pCoreWindow->get_Dispatcher(&pCoreDispatcher)); - - if (pCoreDispatcher != NULL) - { - // - // Does the dispatcher belong to the current thread? - // - boolean hasThreadAccess = FALSE; - IfFailThrow(pCoreDispatcher->get_HasThreadAccess(&hasThreadAccess)); - if (hasThreadAccess) - { - // - // This is the dispatcher for the current thread. Return it. - // - pCoreDispatcher.SuppressRelease(); - result = (void*)pCoreDispatcher; - } - } - } - } - - // If we didn't find a CoreDispatcher for the thread, let's see if we can get a DispatcherQueue. - if (result == NULL) - { - SafeComHolderPreemp pDispatcherQueueStatics; - { - HRESULT hr = clr::winrt::GetActivationFactory(RuntimeClass_Windows_System_DispatcherQueue, - (Windows::System::IDispatcherQueueStatics**)pDispatcherQueueStatics.GetAddr()); - - // This interface was added in RS3 along with the public DispatcherQueue support. Older - // Windows builds don't support it and will return one of two HRESULTs from the call - // to GetActivationFactory above: - // - Pre-RS2 will return REGDB_E_CLASSNOTREG since Windows.System.DispatcherQueue - // does not exist at all. - // - RS2 will return E_NOINTERFACE since Windows.System.DispatcherQueue does exist - // in a limited fashion, but does not support the interface ID that we want. - // - // We should just return null if we see these two HRESULTs rather than throwing. - if (hr != REGDB_E_CLASSNOTREG && hr != E_NOINTERFACE) - { - IfFailThrow(hr); - } - } - - if (pDispatcherQueueStatics != NULL) - { - // - // Get the current IDispatcherQueue - // - SafeComHolderPreemp pDispatcherQueue; - - pDispatcherQueueStatics->GetForCurrentThread(&pDispatcherQueue); - - if (pDispatcherQueue != NULL) - { - pDispatcherQueue.SuppressRelease(); - result = (void*)pDispatcherQueue; - } - } - } - - END_QCALL; - return result; -} - -#endif //FEATURE_APPX diff --git a/src/coreclr/src/vm/synchronizationcontextnative.h b/src/coreclr/src/vm/synchronizationcontextnative.h deleted file mode 100644 index 3d563c5..0000000 --- a/src/coreclr/src/vm/synchronizationcontextnative.h +++ /dev/null @@ -1,27 +0,0 @@ -// 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. - -/*============================================================ -** -** Header: SynchronizationContextNative.h -** -** -** Purpose: Native methods on System.Threading.SynchronizationContext. -** -** -===========================================================*/ - -#ifndef _SYNCHRONIZATIONCONTEXTNATIVE_H -#define _SYNCHRONIZATIONCONTEXTNATIVE_H - -class SynchronizationContextNative -{ -public: - -#ifdef FEATURE_APPX - static void* QCALLTYPE GetWinRTDispatcherForCurrentThread(); -#endif -}; -#endif // _SYNCHRONIZATIONCONTEXTNATIVE_H - diff --git a/src/coreclr/src/vm/threads.cpp b/src/coreclr/src/vm/threads.cpp index 324c65d..b3103e6 100644 --- a/src/coreclr/src/vm/threads.cpp +++ b/src/coreclr/src/vm/threads.cpp @@ -48,6 +48,7 @@ #ifdef FEATURE_COMINTEROP_APARTMENT_SUPPORT #include "olecontexthelpers.h" +#include "roapi.h" #endif // FEATURE_COMINTEROP_APARTMENT_SUPPORT #ifdef FEATURE_PERFTRACING @@ -5066,8 +5067,6 @@ Thread::ApartmentState Thread::SetApartment(ApartmentState state, BOOL fFireMDAO _ASSERTE(!"Unexpected HRESULT returned from CoInitializeEx!"); } -#ifdef FEATURE_COMINTEROP - // If WinRT is supported on this OS, also initialize it at the same time. Since WinRT sits on top of COM // we need to make sure that it is initialized in the same threading mode as we just started COM itself // with (or that we detected COM had already been started with). @@ -5112,7 +5111,6 @@ Thread::ApartmentState Thread::SetApartment(ApartmentState state, BOOL fFireMDAO // Since we've just called CoInitialize, COM has effectively been started up. // To ensure the CLR is aware of this, we need to call EnsureComStarted. EnsureComStarted(FALSE); -#endif // FEATURE_COMINTEROP return GetApartment(); } diff --git a/src/coreclr/src/vm/typehandle.cpp b/src/coreclr/src/vm/typehandle.cpp index d9b1a9c..48af30c 100644 --- a/src/coreclr/src/vm/typehandle.cpp +++ b/src/coreclr/src/vm/typehandle.cpp @@ -245,7 +245,7 @@ TypeHandle TypeHandle::GetTypeParam() const if (IsTypeDesc()) return AsTypeDesc()->GetTypeParam(); - + return TypeHandle(); } @@ -286,7 +286,7 @@ TypeHandle TypeHandle::MakeArray(int rank) const TypeHandle TypeHandle::MakeNativeValueType() const { STATIC_CONTRACT_WRAPPER; - + return ClassLoader::LoadNativeValueTypeThrowing(*this); } @@ -524,20 +524,6 @@ TypeHandle TypeHandle::GetDefItfForComClassItf() const return GetMethodTable()->GetDefItfForComClassItf(); } -BOOL TypeHandle::IsProjectedFromWinRT() const -{ - LIMITED_METHOD_CONTRACT; - PREFIX_ASSUME(GetMethodTable() != NULL); - return GetMethodTable()->IsProjectedFromWinRT(); -} - -BOOL TypeHandle::IsExportedToWinRT() const -{ - LIMITED_METHOD_CONTRACT; - PREFIX_ASSUME(GetMethodTable() != NULL); - return GetMethodTable()->IsExportedToWinRT(); -} - ComCallWrapperTemplate *TypeHandle::GetComCallWrapperTemplate() const { LIMITED_METHOD_CONTRACT; diff --git a/src/coreclr/src/vm/typehandle.h b/src/coreclr/src/vm/typehandle.h index 526ad6c..c7dd727 100644 --- a/src/coreclr/src/vm/typehandle.h +++ b/src/coreclr/src/vm/typehandle.h @@ -315,14 +315,6 @@ public: //Equivalent to (!HasInstantiation() || IsGenericTypeDefinition()); inline BOOL IsTypicalTypeDefinition() const; - enum InteropKind - { - Interop_ManagedToNative, // use for RCW-related queries - Interop_NativeToManaged, // use for CCW-related queries - }; - - inline BOOL SupportsGenericInterop(InteropKind interopKind) const; - BOOL IsSharedByGenericInstantiations() const; // Recursively search the type arguments and if @@ -399,9 +391,6 @@ public: CorIfaceAttr GetComInterfaceType() const; TypeHandle GetDefItfForComClassItf() const; - BOOL IsProjectedFromWinRT() const; - BOOL IsExportedToWinRT() const; - ComCallWrapperTemplate *GetComCallWrapperTemplate() const; BOOL SetComCallWrapperTemplate(ComCallWrapperTemplate *pTemplate); #endif // FEATURE_COMINTEROP @@ -409,10 +398,10 @@ public: #endif // Unlike AsMethodTable, GetMethodTable will get the method table - // of the type, regardless of whether it is a TypeDesc. - // Note, however this method table may be non-exact/shared for TypeDescs. + // of the type, regardless of whether it is a TypeDesc. + // Note, however this method table may be non-exact/shared for TypeDescs. // for example all pointers and function pointers use ELEMENT_TYPE_U. - // And some types (like ByRef or generic type parameters) have no + // And some types (like ByRef or generic type parameters) have no // method table and this function returns NULL for them. inline PTR_MethodTable GetMethodTable() const; diff --git a/src/coreclr/src/vm/typehandle.inl b/src/coreclr/src/vm/typehandle.inl index 30dac6f..33beb92 100644 --- a/src/coreclr/src/vm/typehandle.inl +++ b/src/coreclr/src/vm/typehandle.inl @@ -142,12 +142,6 @@ inline BOOL TypeHandle::IsTypicalTypeDefinition() const return !HasInstantiation() || IsGenericTypeDefinition(); } -inline BOOL TypeHandle::SupportsGenericInterop(InteropKind interopKind) const -{ - LIMITED_METHOD_CONTRACT; - return (!IsTypeDesc() && AsMethodTable()->SupportsGenericInterop(interopKind)); -} - inline BOOL TypeHandle::HasTypeEquivalence() const { LIMITED_METHOD_CONTRACT; diff --git a/src/coreclr/src/vm/typeparse.cpp b/src/coreclr/src/vm/typeparse.cpp index e1bbc48..f38c829 100644 --- a/src/coreclr/src/vm/typeparse.cpp +++ b/src/coreclr/src/vm/typeparse.cpp @@ -864,7 +864,6 @@ TypeHandle TypeName::GetTypeUsingCASearchRules(LPCWSTR szTypeName, Assembly *pRe /*fProhibitAsmQualifiedName = */ FALSE, pRequestingAssembly, nullptr, - FALSE, &keepAlive); ASSERT(!th.IsNull()); @@ -902,7 +901,6 @@ TypeHandle TypeName::GetTypeUsingCASearchRules(LPCWSTR szTypeName, Assembly *pRe BOOL bIgnoreCase, BOOL bProhibitAsmQualifiedName, Assembly* pRequestingAssembly, - BOOL bLoadTypeFromPartialNameHack, OBJECTREF *pKeepAlive, ICLRPrivBinder * pPrivHostBinder) { @@ -913,10 +911,6 @@ TypeHandle TypeName::GetTypeUsingCASearchRules(LPCWSTR szTypeName, Assembly *pRe DWORD error = (DWORD)-1; - /* Partial name workaround loading must not load a collectible type */ - if (bLoadTypeFromPartialNameHack) - pKeepAlive = NULL; - #ifdef __GNUC__ // When compiling under GCC we have to use the -fstack-check option to ensure we always spot stack // overflow. But this option is intolerant of locals growing too large, so we have to cut back a bit @@ -952,7 +946,6 @@ TypeHandle TypeName::GetTypeUsingCASearchRules(LPCWSTR szTypeName, Assembly *pRe bProhibitAsmQualifiedName, pRequestingAssembly, pPrivHostBinder, - bLoadTypeFromPartialNameHack, pKeepAlive); if (bPeriodPrefix && result.IsNull()) @@ -981,7 +974,6 @@ TypeHandle TypeName::GetTypeUsingCASearchRules(LPCWSTR szTypeName, Assembly *pRe bProhibitAsmQualifiedName, pRequestingAssembly, pPrivHostBinder, - bLoadTypeFromPartialNameHack, pKeepAlive); } @@ -1040,7 +1032,7 @@ TypeHandle TypeName::GetTypeUsingCASearchRules(LPCWSTR szTypeName, Assembly *pRe return pTypeName->GetTypeWorker(bThrowIfNotFound, /*bIgnoreCase = */FALSE, pAssembly, /*fEnableCASearchRules = */FALSE, FALSE, NULL, nullptr, // pPrivHostBinder - FALSE, NULL /* cannot find a collectible type unless it is in assembly */); + NULL /* cannot find a collectible type unless it is in assembly */); } //------------------------------------------------------------------------------------------- @@ -1106,7 +1098,6 @@ TypeHandle TypeName::GetTypeFromAsm() FALSE, NULL, nullptr, // pPrivHostBinder - FALSE, NULL /* cannot find a collectible type */); } @@ -1123,12 +1114,10 @@ TypeHandle TypeName::GetTypeFromAsm() BOOL bThrowIfNotFound, BOOL bIgnoreCase, Assembly* pAssemblyGetType, - BOOL fEnableCASearchRules, BOOL bProhibitAsmQualifiedName, Assembly* pRequestingAssembly, ICLRPrivBinder * pPrivHostBinder, - BOOL bLoadTypeFromPartialNameHack, OBJECTREF *pKeepAlive) { CONTRACT(TypeHandle) @@ -1168,40 +1157,12 @@ TypeHandle TypeName::GetTypeFromAsm() } } - SString * pssOuterTypeName = NULL; - if (GetNames().GetCount() > 0) - { - pssOuterTypeName = GetNames()[0]; - } - - // We want to catch the exception if we're going to later try a partial bind. - if (bLoadTypeFromPartialNameHack) - { - EX_TRY - { - DomainAssembly *pDomainAssembly = LoadDomainAssembly(GetAssembly(), pRequestingAssembly, - pPrivHostBinder, - bThrowIfNotFound, pssOuterTypeName); - if (pDomainAssembly) - { - th = GetTypeHaveAssembly(pDomainAssembly->GetAssembly(), bThrowIfNotFound, bIgnoreCase, pKeepAlive); - } - } - EX_CATCH - { - th = TypeHandle(); - } - EX_END_CATCH(RethrowTransientExceptions); - } - else + DomainAssembly *pDomainAssembly = LoadDomainAssembly(GetAssembly(), pRequestingAssembly, + pPrivHostBinder, + bThrowIfNotFound); + if (pDomainAssembly) { - DomainAssembly *pDomainAssembly = LoadDomainAssembly(GetAssembly(), pRequestingAssembly, - pPrivHostBinder, - bThrowIfNotFound, pssOuterTypeName); - if (pDomainAssembly) - { - th = GetTypeHaveAssembly(pDomainAssembly->GetAssembly(), bThrowIfNotFound, bIgnoreCase, pKeepAlive); - } + th = GetTypeHaveAssembly(pDomainAssembly->GetAssembly(), bThrowIfNotFound, bIgnoreCase, pKeepAlive); } } @@ -1284,7 +1245,6 @@ TypeHandle TypeName::GetTypeFromAsm() bThrowIfNotFound, bIgnoreCase, pAssemblyGetType, fEnableCASearchRules, bProhibitAsmQualifiedName, pRequestingAssembly, pPrivHostBinder, - bLoadTypeFromPartialNameHack, (pKeepAlive != NULL) ? &gc.keepAlive : NULL /* Only pass a keepalive parameter if we were passed a keepalive parameter */); if (thGenericArg.IsNull()) @@ -1495,8 +1455,7 @@ DomainAssembly * LoadDomainAssembly( SString * psszAssemblySpec, Assembly * pRequestingAssembly, ICLRPrivBinder * pPrivHostBinder, - BOOL bThrowIfNotFound, - SString * pssOuterTypeName) + BOOL bThrowIfNotFound) { CONTRACTL { @@ -1513,12 +1472,6 @@ DomainAssembly * LoadDomainAssembly( LPCUTF8 szAssemblySpec = psszAssemblySpec ? psszAssemblySpec->GetUTF8(buffer) : NULL; IfFailThrow(spec.Init(szAssemblySpec)); - if (spec.IsContentType_WindowsRuntime()) - { - _ASSERTE(pssOuterTypeName != NULL); - spec.SetWindowsRuntimeType(*pssOuterTypeName); - } - if (pRequestingAssembly) { GCX_PREEMP(); diff --git a/src/coreclr/src/vm/typeparse.h b/src/coreclr/src/vm/typeparse.h index 846ccd7..2ce593b 100644 --- a/src/coreclr/src/vm/typeparse.h +++ b/src/coreclr/src/vm/typeparse.h @@ -16,12 +16,6 @@ #include "class.h" #include "typehandle.h" -// To work around a warning about redefining "TypeName" include the file -// that defines Windows.UI.Xaml.Interop.TypeName now. -#ifdef FEATURE_COMINTEROP -#include -#endif - //#define TYPE_NAME_RESERVED_CHAR W(",[]&*+\\") bool inline IsTypeNameReservedChar(WCHAR ch) @@ -49,8 +43,7 @@ DomainAssembly * LoadDomainAssembly( SString * psszAssemblySpec, Assembly * pRequestingAssembly, ICLRPrivBinder * pPrivHostBinder, - BOOL bThrowIfNotFound, - SString * pssOuterTypeName); + BOOL bThrowIfNotFound); class TypeName { @@ -337,7 +330,6 @@ public: BOOL bIgnoreCase, BOOL bProhibitAssemblyQualifiedName, Assembly* pRequestingAssembly, - BOOL bLoadTypeFromPartialNameHack, OBJECTREF *pKeepAlive, ICLRPrivBinder * pPrivHostBinder = nullptr); @@ -403,7 +395,6 @@ private: Assembly* pRequestingAssembly, ICLRPrivBinder * pPrivHostBinder, - BOOL bLoadTypeFromPartialNameHack, OBJECTREF *pKeepAlive); //---------------------------------------------------------------------------------------------------------------- diff --git a/src/coreclr/src/vm/typestring.h b/src/coreclr/src/vm/typestring.h index c259e43..b1223ac 100644 --- a/src/coreclr/src/vm/typestring.h +++ b/src/coreclr/src/vm/typestring.h @@ -37,7 +37,7 @@ private: friend SString* TypeName::ToString(SString*, BOOL, BOOL, BOOL); friend TypeHandle TypeName::GetTypeWorker(BOOL, BOOL, Assembly*, BOOL, BOOL, Assembly*, ICLRPrivBinder * pPrivHostBinder, - BOOL, OBJECTREF *); + OBJECTREF *); HRESULT OpenGenericArguments(); HRESULT CloseGenericArguments(); HRESULT OpenGenericArgument(); diff --git a/src/coreclr/src/vm/vars.cpp b/src/coreclr/src/vm/vars.cpp index 9e6cf27..e9c2b60 100644 --- a/src/coreclr/src/vm/vars.cpp +++ b/src/coreclr/src/vm/vars.cpp @@ -85,7 +85,6 @@ GPTR_IMPL(MethodTable, g_TypedReferenceMT); #ifdef FEATURE_COMINTEROP GPTR_IMPL(MethodTable, g_pBaseCOMObject); -GPTR_IMPL(MethodTable, g_pBaseRuntimeClass); #endif #ifdef FEATURE_ICASTABLE diff --git a/src/coreclr/src/vm/vars.hpp b/src/coreclr/src/vm/vars.hpp index 997c215..52c4d8c 100644 --- a/src/coreclr/src/vm/vars.hpp +++ b/src/coreclr/src/vm/vars.hpp @@ -392,7 +392,6 @@ GPTR_DECL(MethodTable, g_TypedReferenceMT); #ifdef FEATURE_COMINTEROP GPTR_DECL(MethodTable, g_pBaseCOMObject); -GPTR_DECL(MethodTable, g_pBaseRuntimeClass); #endif #ifdef FEATURE_ICASTABLE diff --git a/src/coreclr/src/vm/virtualcallstub.cpp b/src/coreclr/src/vm/virtualcallstub.cpp index a124ed7..14a76b7 100644 --- a/src/coreclr/src/vm/virtualcallstub.cpp +++ b/src/coreclr/src/vm/virtualcallstub.cpp @@ -2262,28 +2262,7 @@ VirtualCallStubManager::Resolver( MethodTable * pItfMT = GetTypeFromToken(token); implSlot = pItfMT->FindDispatchSlot(TYPE_ID_THIS_CLASS, token.GetSlotNumber(), throwOnConflict); - if (pItfMT->HasInstantiation()) - { - DispatchSlot ds(implSlot); - MethodDesc * pTargetMD = ds.GetMethodDesc(); - if (!pTargetMD->HasMethodInstantiation()) - { - _ASSERTE(pItfMT->IsProjectedFromWinRT() || pItfMT->IsWinRTRedirectedInterface(TypeHandle::Interop_ManagedToNative)); - - MethodDesc *pInstMD = MethodDesc::FindOrCreateAssociatedMethodDesc( - pTargetMD, - pItfMT, - FALSE, // forceBoxedEntryPoint - Instantiation(), // methodInst - FALSE, // allowInstParam - TRUE); // forceRemotableMethod - - _ASSERTE(pInstMD->IsComPlusCall() || pInstMD->IsGenericComPlusCall()); - - *ppTarget = pInstMD->GetStableEntryPoint(); - return TRUE; - } - } + _ASSERTE(!pItfMT->HasInstantiation()); fShouldPatch = TRUE; } diff --git a/src/coreclr/src/vm/winrtdispatcherqueue.h b/src/coreclr/src/vm/winrtdispatcherqueue.h deleted file mode 100644 index 9b97beb..0000000 --- a/src/coreclr/src/vm/winrtdispatcherqueue.h +++ /dev/null @@ -1,101 +0,0 @@ -// 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. -/*============================================================ -** -** Header: winrtdispatcherqueue.h -** -===========================================================*/ - -#ifndef _WINRTDISPATCHERQUEUE_H -#define _WINRTDISPATCHERQUEUE_H - -#include - -// The following definitions were taken from windows.system.h. -// Use windows.system.h from the RS3 SDK instead of this when that SDK is available. -namespace Windows { - namespace System { - /* [v1_enum] */ - enum DispatcherQueuePriority - { - DispatcherQueuePriority_Low = -10, - DispatcherQueuePriority_Normal = 0, - DispatcherQueuePriority_High = 10 - } ; - - MIDL_INTERFACE("DFA2DC9C-1A2D-4917-98F2-939AF1D6E0C8") - IDispatcherQueueHandler : public IUnknown - { - public: - virtual HRESULT STDMETHODCALLTYPE Invoke( void) = 0; - }; - - MIDL_INTERFACE("5FEABB1D-A31C-4727-B1AC-37454649D56A") - IDispatcherQueueTimer : public IInspectable - { - public: - virtual HRESULT STDMETHODCALLTYPE Start( void) = 0; - - virtual HRESULT STDMETHODCALLTYPE Stop( void) = 0; - - virtual /* [propget] */ HRESULT STDMETHODCALLTYPE get_Interval( - /* [out][retval] */ __RPC__out ABI::Windows::Foundation::TimeSpan *value) = 0; - - virtual /* [propput] */ HRESULT STDMETHODCALLTYPE put_Interval( - /* [in] */ ABI::Windows::Foundation::TimeSpan value) = 0; - - virtual /* [propget] */ HRESULT STDMETHODCALLTYPE get_IsStarted( - /* [out][retval] */ __RPC__out boolean *value) = 0; - - virtual /* [propget] */ HRESULT STDMETHODCALLTYPE get_IsRepeating( - /* [out][retval] */ __RPC__out boolean *value) = 0; - - virtual /* [propput] */ HRESULT STDMETHODCALLTYPE put_IsRepeating( - /* [in] */ boolean value) = 0; - -#if 0 // We don't use these functions - virtual HRESULT STDMETHODCALLTYPE add_Tick( - /* [in] */ __RPC__in_opt __FITypedEventHandler_2_Windows__CSystem__CDispatcherQueueTimer_IInspectable *handler, - /* [out][retval] */ __RPC__out EventRegistrationToken *token) = 0; - - virtual HRESULT STDMETHODCALLTYPE remove_Tick( - /* [in] */ EventRegistrationToken token) = 0; -#endif - }; - - MIDL_INTERFACE("603E88E4-A338-4FFE-A457-A5CFB9CEB899") - IDispatcherQueue : public IInspectable - { - public: - virtual HRESULT STDMETHODCALLTYPE CreateTimer( - /* [out][retval] */ __RPC__deref_out_opt Windows::System::IDispatcherQueueTimer **result) = 0; - - virtual HRESULT STDMETHODCALLTYPE TryEnqueue( - /* [in] */ __RPC__in_opt Windows::System::IDispatcherQueueHandler *callback, - /* [out][retval] */ __RPC__out boolean *result) = 0; - - virtual HRESULT STDMETHODCALLTYPE TryEnqueueWithPriority( - /* [in] */ Windows::System::DispatcherQueuePriority priority, - /* [in] */ __RPC__in_opt Windows::System::IDispatcherQueueHandler *callback, - /* [out][retval] */ __RPC__out boolean *result) = 0; - }; - - MIDL_INTERFACE("A96D83D7-9371-4517-9245-D0824AC12C74") - IDispatcherQueueStatics : public IInspectable - { - public: - virtual HRESULT STDMETHODCALLTYPE GetForCurrentThread( - /* [out][retval] */ __RPC__deref_out_opt Windows::System::IDispatcherQueue **result) = 0; - }; - - extern const __declspec(selectany) IID & IID_IDispatcherQueueStatics = __uuidof(IDispatcherQueueStatics); - } -} - -#ifndef RUNTIMECLASS_Windows_System_DispatcherQueue_DEFINED -#define RUNTIMECLASS_Windows_System_DispatcherQueue_DEFINED - extern const __declspec(selectany) _Null_terminated_ WCHAR RuntimeClass_Windows_System_DispatcherQueue[] = L"Windows.System.DispatcherQueue"; -#endif - -#endif // _WINRTDISPATCHERQUEUE_H diff --git a/src/coreclr/src/vm/winrthelpers.cpp b/src/coreclr/src/vm/winrthelpers.cpp deleted file mode 100644 index 0bf1cd5..0000000 --- a/src/coreclr/src/vm/winrthelpers.cpp +++ /dev/null @@ -1,163 +0,0 @@ -// 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. -// -// winrthelpers.inl -// - -// -// Helpers to fetch the first WinRT Type def from metadata import -// -// ====================================================================================== - -#include "common.h" - -// -------------------------------------------------------------------------------------- -// Return the first public WinRT type's namespace and typename - the names have the lifetime of the MetaData scope. -// -//static -HRESULT GetFirstWinRTTypeDef( - IMDInternalImport * pMDInternalImport, - LPCSTR * pszNameSpace, // Tight to the lifetime of pssFakeNameSpaceAllocationBuffer when the WinMD file is empty - LPCSTR * pszTypeName, - LPCWSTR wszAssemblyPath, // Used for creating fake binding type name in case the WinMD file is empty - SString * pssFakeNameSpaceAllocationBuffer) // Used as allocation buffer for fake namespace -{ - CONTRACTL - { - THROWS; - GC_TRIGGERS; - MODE_ANY; - } - CONTRACTL_END; - - _ASSERTE((wszAssemblyPath == NULL) || (pssFakeNameSpaceAllocationBuffer != NULL)); - - static const char const_szWinRTPrefix[] = ""; - - HRESULT hr = S_OK; - HENUMInternalHolder hEnum(pMDInternalImport); - mdToken tk; - - hEnum.EnumTypeDefInit(); - - while (pMDInternalImport->EnumNext(&hEnum, &tk)) - { - DWORD dwAttr; - IfFailRet(pMDInternalImport->GetTypeDefProps(tk, &dwAttr, NULL)); - if (IsTdPublic(dwAttr) && IsTdWindowsRuntime(dwAttr)) - { - IfFailRet(pMDInternalImport->GetNameOfTypeDef(tk, pszTypeName, pszNameSpace)); - return hr; - } - } - - // We didn't find any public Windows runtime types. In the case of 1st party WinMDs, this means - // it's not exporting anything so we really cannot bind to it. - // For WinMDs built with WinMDExp, it's because the adapter has promoted the CLR implementation to - // public (no WindowsRuntime flag, though), and made the WinRT copy private. - // So there should exist a public type (not nested, not an interface), which has a corresponding - // private type with the same name prepended with that is marked as windows runtime - // This isn't very efficient O(n^2) but we expect all public types in WinMDs to have WinRT visible - // versions too so it should early out in the first iteration in almost all cases. - HENUMInternalHolder hEnum2(pMDInternalImport); - hEnum2.EnumTypeDefInit(); - - while (pMDInternalImport->EnumNext(&hEnum2, &tk)) - { - DWORD dwAttr; - IfFailRet(pMDInternalImport->GetTypeDefProps(tk, &dwAttr, NULL)); - if (IsTdPublic(dwAttr) && !IsTdInterface(dwAttr)) - { - // Look for a matching private windows runtime type - mdToken tkPrivate; - HENUMInternalHolder hSubEnum(pMDInternalImport); - - LPCSTR szNameSpace = NULL; - LPCSTR szName = NULL; - IfFailRet(pMDInternalImport->GetNameOfTypeDef(tk, &szName, &szNameSpace)); - - hSubEnum.EnumTypeDefInit(); - - while (pMDInternalImport->EnumNext(&hSubEnum, &tkPrivate)) - { - DWORD dwSubAttr; - IfFailRet(pMDInternalImport->GetTypeDefProps(tkPrivate, &dwSubAttr, NULL)); - if (IsTdNotPublic(dwSubAttr) && IsTdWindowsRuntime(dwSubAttr)) - { - LPCSTR szSubNameSpace = NULL; - LPCSTR szSubName = NULL; - IfFailRet(pMDInternalImport->GetNameOfTypeDef(tkPrivate, &szSubName, &szSubNameSpace)); - if (!strncmp(szSubName, const_szWinRTPrefix, strlen(const_szWinRTPrefix))) - { - szSubName += strlen(const_szWinRTPrefix); - // Skip over the prefix. Now pointing at type name - if (!strcmp(szSubNameSpace, szNameSpace) && - !strcmp(szSubName, szName)) - { - *pszNameSpace = szNameSpace; - *pszTypeName = szName; - return S_OK; - } - } - } - } - } - } - // The .winmd file is empty - i.e. there is no type we can bind to - - if ((wszAssemblyPath != NULL) && (*wszAssemblyPath != 0)) - { // Create fake name for WinMD binding purposes (used when .winmd file is loaded by file path - ngen, NativeBinder, etc.) - // We will use WinMD file name as namespace and use fake hardcoded type name - SString ssAssemblyPath(wszAssemblyPath); - SString ssAssemblyName; - SplitPath(ssAssemblyPath, - NULL, // drive - NULL, // dir - &ssAssemblyName, // name - NULL); // ext - if (!ssAssemblyName.IsEmpty()) - { - *pszTypeName = "FakeTypeNameForCLRBinding"; - ssAssemblyName.ConvertToUTF8(*pssFakeNameSpaceAllocationBuffer); - *pszNameSpace = pssFakeNameSpaceAllocationBuffer->GetUTF8NoConvert(); - return S_OK; - } - } - - return CLR_E_BIND_TYPE_NOT_FOUND; -} // GetFirstWinRTTypeDef - -// -------------------------------------------------------------------------------------- -//static -HRESULT -GetBindableWinRTName( - IMDInternalImport * pMDInternalImport, - IAssemblyName * pIAssemblyName) -{ - STANDARD_VM_CONTRACT; - - HRESULT hr = S_OK; - - LPCSTR szNameSpace; - LPCSTR szTypeName; - - // Note: This function is used only by native binder which does not support empty WinMDs - see code:CEECompileInfo::LoadAssemblyByPath - // Therefore we do not have to use file name to create fake type name - IfFailRet(GetFirstWinRTTypeDef(pMDInternalImport, &szNameSpace, &szTypeName, NULL, NULL)); - - WCHAR wzAsmName[MAX_PATH_FNAME]; - DWORD dwSize = sizeof(wzAsmName); - - IfFailRet(pIAssemblyName->GetProperty(ASM_NAME_NAME, wzAsmName, &dwSize)); - - StackSString sNamespaceAndType(wzAsmName); - sNamespaceAndType.Append(W("!")); - sNamespaceAndType.AppendUTF8(szNameSpace); - sNamespaceAndType.Append(W(".")); - sNamespaceAndType.AppendUTF8(szTypeName); - - pIAssemblyName->SetProperty(ASM_NAME_NAME, sNamespaceAndType.GetUnicode(), (sNamespaceAndType.GetCount() + 1) * sizeof(WCHAR)); - - return hr; -} diff --git a/src/coreclr/src/vm/winrthelpers.h b/src/coreclr/src/vm/winrthelpers.h deleted file mode 100644 index a1bdd5b..0000000 --- a/src/coreclr/src/vm/winrthelpers.h +++ /dev/null @@ -1,30 +0,0 @@ -// 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. -// -// WinRtHelpers.h -// - -// -// Helpers to fetch the first WinRT Type def from metadata import -// -// ====================================================================================== - -#pragma once - -#ifdef FEATURE_COMINTEROP - -// -------------------------------------------------------------------------------------- -// Return the first public WinRT type's namespace and typename - the names have the lifetime of the MetaData scope. -HRESULT GetFirstWinRTTypeDef( - IMDInternalImport * pMDInternalImport, - LPCSTR * pszNameSpace, // Tight to the lifetime of pssFakeNameSpaceAllocationBuffer when the WinMD file is empty - LPCSTR * pszTypeName, - LPCWSTR wszAssemblyPath, // Used for creating fake binding type name in case the WinMD file is empty - SString * pssFakeNameSpaceAllocationBuffer); // Used as allocation buffer for fake namespace - -HRESULT GetBindableWinRTName( - IMDInternalImport * pMDInternalImport, - IAssemblyName * pIAssemblyName); - -#endif //FEATURE_COMINTEROP diff --git a/src/coreclr/src/vm/winrtredirector.h b/src/coreclr/src/vm/winrtredirector.h deleted file mode 100644 index 1c16250..0000000 --- a/src/coreclr/src/vm/winrtredirector.h +++ /dev/null @@ -1,143 +0,0 @@ -// 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. -// -// File: winrtredirector.h -// - -// - -// -// ============================================================================ - -#ifndef WINRT_DELEGATE_REDIRECTOR_H -#define WINRT_DELEGATE_REDIRECTOR_H - -#include "winrttypenameconverter.h" - -// Provides functionality related to redirecting WinRT interfaces. -// @TODO: This should take advantage of the macros in WinRTProjectedTypes.h instead of hardcoding -// the knowledge about redirected interfaces here. -class WinRTInterfaceRedirector -{ -public: - // Returns a MethodDesc to be used as an interop stub for the given redirected interface/slot/direction. - static MethodDesc *GetStubMethodForRedirectedInterface( - WinMDAdapter::RedirectedTypeIndex interfaceIndex, // redirected interface index - int slot, // slot number of the method for which a stub is needed - TypeHandle::InteropKind interopKind, // Interop_ManagedToNative (stub for RCW) or Interop_NativeToManaged (stub for CCW) - BOOL fICollectionStub, // need stub for ICollection`1 (only valid with Interop_ManagedToNative) - Instantiation methodInst = Instantiation()); // requested method instantiation if the stub method is generic - - // Returns a MethodDesc to be used as an interop stub for the given method and direction. - static MethodDesc *GetStubMethodForRedirectedInterfaceMethod(MethodDesc *pMD, TypeHandle::InteropKind interopKind); - - // Returns MethodTable (typical instantiation) of the Framework copy of the specified redirected WinRT interface. - static MethodTable *GetWinRTTypeForRedirectedInterfaceIndex(WinMDAdapter::RedirectedTypeIndex index); - - // Loads a method from the given Framework assembly. - static MethodDesc *LoadMethodFromRedirectedAssembly(LPCUTF8 szAssemblyQualifiedTypeName, LPCUTF8 szMethodName); - - // Lists WinRT-legal types assignable from .NET reference types that are projected from WinRT structures/arrays/delegates. - enum WinRTLegalStructureBaseType - { - BaseType_None, - BaseType_Object, // System.Object (assignable from Type, string, Exception) - BaseType_IEnumerable, // System.Collections.IEnumerable (assignable from string) - BaseType_IEnumerableOfChar // System.Collections.Generic.IEnumerable (assignable from string) - }; - - // Determines if the generic argument in the given instantiation is a WinRT-legal base type of a WinRT structure type. - static WinRTLegalStructureBaseType GetStructureBaseType(Instantiation inst) - { - LIMITED_METHOD_CONTRACT; - - _ASSERTE(inst.GetNumArgs() == 1); - - if (!inst[0].IsTypeDesc()) - { - MethodTable *pInstArgMT = inst[0].AsMethodTable(); - - if (pInstArgMT == g_pObjectClass) - return BaseType_Object; - - if (pInstArgMT == MscorlibBinder::GetExistingClass(CLASS__IENUMERABLE)) - return BaseType_IEnumerable; - - if (pInstArgMT->HasSameTypeDefAs(MscorlibBinder::GetExistingClass(CLASS__IENUMERABLEGENERIC)) && - pInstArgMT->GetInstantiation()[0].GetSignatureCorElementType() == ELEMENT_TYPE_CHAR) - return BaseType_IEnumerableOfChar; - } - return BaseType_None; - } - - // Returns the redirection index if the MethodTable* is a redirected interface. - static inline bool ResolveRedirectedInterface(MethodTable *pMT, WinMDAdapter::RedirectedTypeIndex * pIndex); - -#ifdef _DEBUG - static void VerifyRedirectedInterfaceStubs(); -#endif // _DEBUG - -private: - static inline int GetStubInfoIndex(WinMDAdapter::RedirectedTypeIndex index) - { - LIMITED_METHOD_CONTRACT; - - switch (index) - { - case WinMDAdapter::RedirectedTypeIndex_System_Collections_Generic_IEnumerable: return 0; - case WinMDAdapter::RedirectedTypeIndex_System_Collections_Generic_IList: return 1; - case WinMDAdapter::RedirectedTypeIndex_System_Collections_Generic_IDictionary: return 2; - case WinMDAdapter::RedirectedTypeIndex_System_Collections_Generic_IReadOnlyList: return 3; - case WinMDAdapter::RedirectedTypeIndex_System_Collections_Generic_IReadOnlyDictionary: return 4; - case WinMDAdapter::RedirectedTypeIndex_System_Collections_IEnumerable: return 5; - case WinMDAdapter::RedirectedTypeIndex_System_Collections_IList: return 6; - case WinMDAdapter::RedirectedTypeIndex_System_Collections_Specialized_INotifyCollectionChanged: return 7; - case WinMDAdapter::RedirectedTypeIndex_System_ComponentModel_INotifyPropertyChanged: return 8; - case WinMDAdapter::RedirectedTypeIndex_System_Windows_Input_ICommand: return 9; - case WinMDAdapter::RedirectedTypeIndex_System_IDisposable: return 10; - default: - UNREACHABLE(); - } - } - - struct RedirectedInterfaceStubInfo - { - const BinderClassID m_WinRTInterface; - const int m_iCLRMethodCount; - const BinderMethodID *m_rCLRStubMethods; - const int m_iWinRTMethodCount; - const BinderMethodID *m_rWinRTStubMethods; - }; - - struct NonMscorlibRedirectedInterfaceInfo - { - const LPCUTF8 m_szWinRTInterfaceAssemblyQualifiedTypeName; - const LPCUTF8 m_szCLRStubClassAssemblyQualifiedTypeName; - const LPCUTF8 m_szWinRTStubClassAssemblyQualifiedTypeName; - const LPCUTF8 *m_rszMethodNames; - }; - - enum - { - s_NumRedirectedInterfaces = 11 - }; - - // Describes stubs used for marshaling of redirected interfaces. - const static RedirectedInterfaceStubInfo s_rInterfaceStubInfos[2 * s_NumRedirectedInterfaces]; - const static NonMscorlibRedirectedInterfaceInfo s_rNonMscorlibInterfaceInfos[3]; - - const static int NON_MSCORLIB_MARKER = 0x80000000; -}; - - -// Provides functionality related to redirecting WinRT delegates. -class WinRTDelegateRedirector -{ -public: - static MethodTable *GetWinRTTypeForRedirectedDelegateIndex(WinMDAdapter::RedirectedTypeIndex index); - - static bool ResolveRedirectedDelegate(MethodTable *pMT, WinMDAdapter::RedirectedTypeIndex *pIndex); -}; - -#endif // WINRT_DELEGATE_REDIRECTOR_H diff --git a/src/coreclr/src/vm/winrtredirector.inl b/src/coreclr/src/vm/winrtredirector.inl deleted file mode 100644 index de6949d..0000000 --- a/src/coreclr/src/vm/winrtredirector.inl +++ /dev/null @@ -1,70 +0,0 @@ -// 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. -// -// File: winrtredirector.inl -// - -// - -// -// ============================================================================ - -#if !defined(WINRT_DELEGATE_REDIRECTOR_INL) && defined(WINRT_DELEGATE_REDIRECTOR_H) -#define WINRT_DELEGATE_REDIRECTOR_INL - -#ifdef FEATURE_COMINTEROP - -/*static*/ -inline bool WinRTInterfaceRedirector::ResolveRedirectedInterface(MethodTable *pMT, WinMDAdapter::RedirectedTypeIndex * pIndex) -{ - LIMITED_METHOD_CONTRACT; - - WinMDAdapter::RedirectedTypeIndex index; - WinMDAdapter::WinMDTypeKind kind; - - if (WinRTTypeNameConverter::ResolveRedirectedType(pMT, &index, &kind)) - { - if ((kind == WinMDAdapter::WinMDTypeKind_Interface || kind == WinMDAdapter::WinMDTypeKind_PInterface) && - // filter out KeyValuePair and Nullable which are structures projected from WinRT interfaces - index != WinMDAdapter::RedirectedTypeIndex_System_Collections_Generic_KeyValuePair && - index != WinMDAdapter::RedirectedTypeIndex_System_Nullable) - { - if (pIndex != NULL) - { - *pIndex = index; - } - return true; - } - } - - return false; -} - -/*static */ -inline bool WinRTDelegateRedirector::ResolveRedirectedDelegate(MethodTable *pMT, WinMDAdapter::RedirectedTypeIndex *pIndex) -{ - LIMITED_METHOD_CONTRACT; - - WinMDAdapter::RedirectedTypeIndex index; - WinMDAdapter::WinMDTypeKind kind; - - if (WinRTTypeNameConverter::ResolveRedirectedType(pMT, &index, &kind)) - { - if (kind == WinMDAdapter::WinMDTypeKind_Delegate || - kind == WinMDAdapter::WinMDTypeKind_PDelegate) - { - if (pIndex != NULL) - { - *pIndex = index; - } - return true; - } - } - - return false; -} - -#endif // FEATURE_COMINTEROP - -#endif // WINRT_DELEGATE_REDIRECTOR_INL diff --git a/src/coreclr/src/vm/winrttypenameconverter.cpp b/src/coreclr/src/vm/winrttypenameconverter.cpp deleted file mode 100644 index 9f2f375..0000000 --- a/src/coreclr/src/vm/winrttypenameconverter.cpp +++ /dev/null @@ -1,1050 +0,0 @@ -// 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. -// -// File: WinRTTypeNameConverter.cpp -// - -// - -// -// ============================================================================ - -#include "common.h" - -#ifdef FEATURE_COMINTEROP -#include "winrttypenameconverter.h" -#include "typeresolution.h" - -struct RedirectedTypeNames -{ - LPCSTR szClrNamespace; - LPCSTR szClrName; - WinMDAdapter::FrameworkAssemblyIndex assembly; - WinMDAdapter::WinMDTypeKind kind; -}; - -#define DEFINE_PROJECTED_TYPE(szWinRTNS, szWinRTName, szClrNS, szClrName, nClrAsmIdx, ncontractAsmIndex, nWinRTIndex, nClrIndex, nWinMDTypeKind) \ - { szClrNS, szClrName, WinMDAdapter::FrameworkAssembly_ ## nClrAsmIdx, WinMDAdapter::WinMDTypeKind_ ## nWinMDTypeKind }, - -static const RedirectedTypeNames g_redirectedTypeNames[WinMDAdapter::RedirectedTypeIndex_Count] = -{ -#include "winrtprojectedtypes.h" -}; - -#undef DEFINE_PROJECTED_TYPE - -struct RedirectedTypeNamesKey -{ - RedirectedTypeNamesKey(LPCSTR szNamespace, LPCSTR szName) : - m_szNamespace(szNamespace), - m_szName(szName) - { - LIMITED_METHOD_CONTRACT; - } - - LPCSTR m_szNamespace; - LPCSTR m_szName; -}; - -class RedirectedTypeNamesTraits : public NoRemoveSHashTraits< DefaultSHashTraits > -{ -public: - typedef RedirectedTypeNamesKey key_t; - - static key_t GetKey(element_t e) - { - LIMITED_METHOD_CONTRACT; - return RedirectedTypeNamesKey(e->szClrNamespace, e->szClrName); - } - static BOOL Equals(key_t k1, key_t k2) - { - LIMITED_METHOD_CONTRACT; - return (strcmp(k1.m_szName, k2.m_szName) == 0) && (strcmp(k1.m_szNamespace, k2.m_szNamespace) == 0); - } - static count_t Hash(key_t k) - { - LIMITED_METHOD_CONTRACT; - // Only use the Name when calculating the hash value. Many redirected types share the same namespace so - // there isn't a lot of value in using the namespace when calculating the hash value. - return HashStringA(k.m_szName); - } - - static const element_t Null() { LIMITED_METHOD_CONTRACT; return NULL; } - static bool IsNull(const element_t &e) { LIMITED_METHOD_CONTRACT; return e == NULL; } -}; - -typedef SHash< RedirectedTypeNamesTraits > RedirectedTypeNamesHashTable; -static RedirectedTypeNamesHashTable * s_pRedirectedTypeNamesHashTable = NULL; - -// -// Return the redirection index and type kind if the MethodTable* is a redirected type -// -bool WinRTTypeNameConverter::ResolveRedirectedType(MethodTable *pMT, WinMDAdapter::RedirectedTypeIndex * pIndex, WinMDAdapter::WinMDTypeKind * pKind /*=NULL*/) -{ - LIMITED_METHOD_CONTRACT; - - WinMDAdapter::RedirectedTypeIndex index = pMT->GetClass()->GetWinRTRedirectedTypeIndex(); - if (index == WinMDAdapter::RedirectedTypeIndex_Invalid) - return false; - - if (pIndex != NULL) - *pIndex = index; - - if (pKind != NULL) - *pKind = g_redirectedTypeNames[index].kind; - - return true; -} - -#ifndef DACCESS_COMPILE - -class MethodTableListNode; - -// Information to help in generating a runtimeclass name for a managed type -// implementing a generic WinRT interface -struct WinRTTypeNameInfo -{ - MethodTableListNode* PreviouslyVisitedTypes; - CorGenericParamAttr CurrentTypeParameterVariance; - - WinRTTypeNameInfo(MethodTableListNode* pPreviouslyVisitedTypes) : - PreviouslyVisitedTypes(pPreviouslyVisitedTypes), - CurrentTypeParameterVariance(gpNonVariant) - { - LIMITED_METHOD_CONTRACT; - _ASSERTE(pPreviouslyVisitedTypes != nullptr); - } -}; - -// Helper data structure to build a stack allocated reverse linked list of MethodTables that we're examining -// while building up WinRT runtimeclass name -class MethodTableListNode -{ - MethodTable* m_pMT; // Type examined while building the runtimeclass name - MethodTableListNode* m_pPrevious; // Previous node in the list - -public: - MethodTableListNode(MethodTable* pMT, WinRTTypeNameInfo* pCurrent) - : m_pMT(pMT), - m_pPrevious(nullptr) - { - LIMITED_METHOD_CONTRACT; - _ASSERTE(pMT != nullptr); - - if (pCurrent != nullptr) - { - m_pPrevious = pCurrent->PreviouslyVisitedTypes; - } - } - - bool Contains(MethodTable* pMT) - { - LIMITED_METHOD_CONTRACT; - - if (pMT == m_pMT) - { - return true; - } - else if (m_pPrevious == nullptr) - { - return false; - } - else - { - return m_pPrevious->Contains(pMT); - } - } -}; - -// -// Append WinRT type name for the specified type handle -// -bool WinRTTypeNameConverter::AppendWinRTTypeNameForManagedType( - TypeHandle thManagedType, - SString &strWinRTTypeName, - bool bForGetRuntimeClassName, - bool *pbIsPrimitive) -{ - WRAPPER_NO_CONTRACT; - return AppendWinRTTypeNameForManagedType(thManagedType, strWinRTTypeName, bForGetRuntimeClassName, pbIsPrimitive, nullptr); -} - -bool WinRTTypeNameConverter::AppendWinRTTypeNameForManagedType( - TypeHandle thManagedType, - SString &strWinRTTypeName, - bool bForGetRuntimeClassName, - bool *pbIsPrimitive, - WinRTTypeNameInfo *pCurrentTypeInfo) -{ - CONTRACTL - { - THROWS; - GC_TRIGGERS; - MODE_ANY; - PRECONDITION(!thManagedType.IsNull()); - PRECONDITION(CheckPointer(pbIsPrimitive, NULL_OK)); - PRECONDITION(CheckPointer(pCurrentTypeInfo, NULL_OK)); - } - CONTRACTL_END; - - if (pbIsPrimitive) - *pbIsPrimitive = false; - - MethodTable *pMT = thManagedType.GetMethodTable(); - BOOL fIsIReference = FALSE, fIsIReferenceArray = FALSE; - if (pMT->GetNumGenericArgs() == 1) - { - fIsIReference = pMT->HasSameTypeDefAs(MscorlibBinder::GetClass(CLASS__CLRIREFERENCEIMPL)); - fIsIReferenceArray = pMT->HasSameTypeDefAs(MscorlibBinder::GetClass(CLASS__CLRIREFERENCEARRAYIMPL)); - } - - WinMDAdapter::RedirectedTypeIndex index; - if (ResolveRedirectedType(pMT, &index)) - { - // Redirected types - // Use the redirected WinRT name - strWinRTTypeName.Append(WinMDAdapter::GetRedirectedTypeFullWinRTName(index)); - } - else if (fIsIReference || fIsIReferenceArray) - { - // - // Convert CLRIReferenceImpl/CLRIReferenceArrayImpl to a WinRT Type - // - // If GetRuntimeClassName = true, return IReference/IReferenceArray - // Otherwise, return T/IReferenceArray`1 - // - Instantiation inst = pMT->GetInstantiation(); - _ASSERTE(inst.GetNumArgs() == 1); - TypeHandle th = inst[0]; - - // I'm sure there are ways to avoid duplication here but I prefer this way - it is easier to understand - if (fIsIReference) - { - if (bForGetRuntimeClassName) - { - // - // IReference - // - strWinRTTypeName.Append(W("Windows.Foundation.IReference`1<")); - - if (!AppendWinRTTypeNameForManagedType( - th, - strWinRTTypeName, - bForGetRuntimeClassName, - NULL - )) - return false; - - strWinRTTypeName.Append(W('>')); - - return true; - } - else - { - // - // T - // - return AppendWinRTTypeNameForManagedType( - th, - strWinRTTypeName, - bForGetRuntimeClassName, - pbIsPrimitive - ); - } - } - else - { - // - // IReferenceArray - // - strWinRTTypeName.Append(W("Windows.Foundation.IReferenceArray`1<")); - - if (!AppendWinRTTypeNameForManagedType( - th, - strWinRTTypeName, - bForGetRuntimeClassName, - NULL)) - return false; - - strWinRTTypeName.Append(W('>')); - - return true; - } - } - else if (pMT->IsProjectedFromWinRT() || pMT->IsExportedToWinRT()) - { - // - // WinRT type - // - SString strTypeName; - pMT->_GetFullyQualifiedNameForClassNestedAware(strTypeName); - strWinRTTypeName.Append(strTypeName); - } - else if (AppendWinRTNameForPrimitiveType(pMT, strWinRTTypeName)) - { - // - // WinRT primitive type, return immediately - // - if (pbIsPrimitive) - *pbIsPrimitive = true; - return true; - } - else if (pMT->IsArray()) - { - if (bForGetRuntimeClassName) - { - // - // An array is not a valid WinRT type - it must be wrapped in IReferenceArray to be a valid - // WinRT type - // - return false; - } - else - { - // - // System.Type marshaling - convert array type into IReferenceArray - // - strWinRTTypeName.Append(W("Windows.Foundation.IReferenceArray`1<")); - - if (!AppendWinRTTypeNameForManagedType(thManagedType.GetArrayElementTypeHandle(), strWinRTTypeName, bForGetRuntimeClassName, NULL)) - return false; - - strWinRTTypeName.Append(W('>')); - } - } - else if (bForGetRuntimeClassName) - { - // - // Not a WinRT type or a WinRT Primitive type, - // but if it implements a WinRT interface we will return the interface name. - // Which interface should we return if it implements multiple WinRT interfaces? - // For now we return the top most interface. And if there are more than one - // top most interfaces, we return the first one we encounter during the interface enumeration. - // - // - // We also need to keep track of the types we've already considered, so we don't wind up in an - // infinite recursion processing generic interfaces. - // For example, in the case where we have: - // - // class ManagedType : IEnumerable - // - // We do not want to keep recursing on the ManagedType type parameter. Instead, we should - // discover that we've already attempted to figure out what the best representation for - // ManagedType is, and bail out. - // - // This is a linear search, however that shouldn't generally be a problem, since generic - // nesting should not be very large in the common case. - - if (pCurrentTypeInfo != nullptr && pCurrentTypeInfo->PreviouslyVisitedTypes->Contains(pMT)) - { - // We should only be restricting this recursion on non-WinRT types that may have WinRT interfaces - _ASSERTE(!pMT->IsProjectedFromWinRT() && !pMT->IsExportedToWinRT() && !pMT->IsTruePrimitive()); - - // We have two choices. If this is a reference type and the interface parameter is covariant, we - // can use IInspectable as the closure. Otherwise, we need to simply fail out with no possible - // type name. - if (pCurrentTypeInfo->CurrentTypeParameterVariance == gpCovariant && - thManagedType.IsBoxedAndCanCastTo(TypeHandle(g_pObjectClass), nullptr)) - { - // Object is used in runtime class names for generics closed over IInspectable at the ABI - strWinRTTypeName.Append(W("Object")); - return true; - } - else - { - return false; - } - } - - // This is the "top" most redirected interface implemented by pMT. - // E.g. if pMT implements both IList`1 and IEnumerable`1, we pick IList`1. - - MethodTable* pTopIfaceMT = NULL; - WinMDAdapter::RedirectedTypeIndex idxTopIface = (WinMDAdapter::RedirectedTypeIndex)-1; - - MethodTable::InterfaceMapIterator it = pMT->IterateInterfaceMap(); - while (it.Next()) - { - MethodTable* pIfaceMT = it.GetInterface(); - if (ResolveRedirectedType(pIfaceMT, &index) || - pIfaceMT->IsProjectedFromWinRT()) - { - if (pTopIfaceMT == NULL || pIfaceMT->ImplementsInterface(pTopIfaceMT)) - { - pTopIfaceMT = pIfaceMT; - - // If pIfaceMT is not a redirected type, idxTopIface will contain garbage. - // But that is fine because we will only use idxTopIface if pTopIfaceMT - // is a redirected type. - idxTopIface = index; - } - } - } - - if (pTopIfaceMT != NULL) - { - if (pTopIfaceMT->IsProjectedFromWinRT()) - { - // Mscorlib contains copies of WinRT interfaces - don't return their names, - // instead return names of the corresponding interfaces in Windows.Foundation.winmd. - - if (pTopIfaceMT->HasSameTypeDefAs(MscorlibBinder::GetClass(CLASS__IKEYVALUEPAIR))) - strWinRTTypeName.Append(W("Windows.Foundation.Collections.IKeyValuePair`2")); - else if (pTopIfaceMT->HasSameTypeDefAs(MscorlibBinder::GetClass(CLASS__IITERATOR))) - strWinRTTypeName.Append(W("Windows.Foundation.Collections.IIterator`1")); - else if (pTopIfaceMT->HasSameTypeDefAs(MscorlibBinder::GetClass(CLASS__IPROPERTYVALUE))) - strWinRTTypeName.Append(W("Windows.Foundation.IPropertyValue")); - else - { - SString strTypeName; - pTopIfaceMT->_GetFullyQualifiedNameForClassNestedAware(strTypeName); - strWinRTTypeName.Append(strTypeName); - } - } - else - strWinRTTypeName.Append(WinMDAdapter::GetRedirectedTypeFullWinRTName(idxTopIface)); - - // Since we are returning the typeName for the pTopIfaceMT we should use the same interfaceType - // to check for instantiation and creating the closed generic. - pMT = pTopIfaceMT; - } - else - return false; - } - else - { - // - // Non-WinRT type, Non-WinRT-Primitive type - // - - return false; - } - - // We allow typeName generation for only open types or completely instantiated types. - // In case it is a generic type definition like IList we return the typeName as IVector'1 only - // and hence we do not need to visit the arguments. - if (pMT->HasInstantiation() && (!pMT->IsGenericTypeDefinition())) - { - // Add the current type we're trying to get a runtimeclass name for to the list of types - // we've already seen, so we can check for infinite recursion on the generic parameters. - MethodTableListNode examinedTypeList(thManagedType.GetMethodTable(), pCurrentTypeInfo); - - - strWinRTTypeName.Append(W('<')); - - // - // Convert each arguments - // - Instantiation inst = pMT->GetInstantiation(); - for (DWORD i = 0; i < inst.GetNumArgs(); ++i) - { - TypeHandle th = inst[i]; - - // We have a partial open type with us and hence we should throw. - if(th.ContainsGenericVariables()) - COMPlusThrowArgumentException(W("th"), W("Argument_TypeNotValid")); - - if (i > 0) - strWinRTTypeName.Append(W(',')); - - // In the recursive case, we can sometimes do a better job of getting a runtimeclass name if - // the actual instantiated type can be substitued for a different type due to variance on the - // generic type parameter. In order to allow that to occur when processing this parameter, - // make a note of the variance properties to pass along with the previously examined type list - WinRTTypeNameInfo currentParameterInfo(&examinedTypeList); - if (pMT->HasVariance()) - { - currentParameterInfo.CurrentTypeParameterVariance = pMT->GetClass()->GetVarianceOfTypeParameter(i); - } - - // Convert to WinRT type name - // If it is not a WinRT type, return immediately - if (!AppendWinRTTypeNameForManagedType(th, strWinRTTypeName, bForGetRuntimeClassName, NULL, ¤tParameterInfo)) - return false; - } - - strWinRTTypeName.Append(W('>')); - } - - return true; -} - -// -// Lookup table : CorElementType -> WinRT primitive type name -// -LPCWSTR const s_wszCorElementTypeToWinRTNameMapping[] = -{ - NULL, // ELEMENT_TYPE_END = 0x0, - NULL, // ELEMENT_TYPE_VOID = 0x1, - W("Boolean"), // ELEMENT_TYPE_BOOLEAN = 0x2, - W("Char16"), // ELEMENT_TYPE_CHAR = 0x3, - NULL, // ELEMENT_TYPE_I1 = 0x4, - W("UInt8"), // ELEMENT_TYPE_U1 = 0x5, - W("Int16"), // ELEMENT_TYPE_I2 = 0x6, - W("UInt16"), // ELEMENT_TYPE_U2 = 0x7, - W("Int32"), // ELEMENT_TYPE_I4 = 0x8, - W("UInt32"), // ELEMENT_TYPE_U4 = 0x9, - W("Int64"), // ELEMENT_TYPE_I8 = 0xa, - W("UInt64"), // ELEMENT_TYPE_U8 = 0xb, - W("Single"), // ELEMENT_TYPE_R4 = 0xc, - W("Double"), // ELEMENT_TYPE_R8 = 0xd, - W("String"), // ELEMENT_TYPE_STRING = 0xe, - NULL, // ELEMENT_TYPE_PTR = 0xf, - NULL, // ELEMENT_TYPE_BYREF = 0x10, - NULL, // ELEMENT_TYPE_VALUETYPE = 0x11, - NULL, // ELEMENT_TYPE_CLASS = 0x12, - NULL, // ??? = 0x13, - NULL, // ELEMENT_TYPE_ARRAY = 0x14, - NULL, // ??? = 0x15, - NULL, // ELEMENT_TYPE_TYPEDBYREF = 0x16, - NULL, // ELEMENT_TYPE_I = 0x18, - NULL, // ELEMENT_TYPE_U = 0x19, - NULL, // ??? = 0x1A, - NULL, // ELEMENT_TYPE_FNPTR = 0x1B, - W("Object"), // ELEMENT_TYPE_OBJECT = 0x1C, -}; - -// -// Get predefined WinRT name for a primitive type -// -bool WinRTTypeNameConverter::GetWinRTNameForPrimitiveType(MethodTable *pMT, SString *pName) -{ - CONTRACTL - { - THROWS; - GC_NOTRIGGER; - MODE_ANY; - PRECONDITION(CheckPointer(pMT)); - PRECONDITION(CheckPointer(pMT, NULL_OK)); - } - CONTRACTL_END; - - CorElementType elemType = TypeHandle(pMT).GetSignatureCorElementType(); - - // - // Try to find it in a lookup table - // - if (elemType >= 0 && elemType < _countof(s_wszCorElementTypeToWinRTNameMapping)) - { - LPCWSTR wszName = s_wszCorElementTypeToWinRTNameMapping[elemType]; - - if (wszName != NULL) - { - if (pName != NULL) - { - pName->SetLiteral(wszName); - } - - return true; - } - } - - if (elemType == ELEMENT_TYPE_VALUETYPE) - { - if (pMT->GetModule()->IsSystem() && - IsTypeRefOrDef(g_GuidClassName, pMT->GetModule(), pMT->GetCl())) - { - if (pName != NULL) - { - pName->SetLiteral(W("Guid")); - } - - return true; - } - } - else if (elemType == ELEMENT_TYPE_CLASS) - { - if (pMT == g_pObjectClass) - { - if (pName != NULL) - { - pName->SetLiteral(W("Object")); - } - - return true; - } - if (pMT == g_pStringClass) - { - if (pName != NULL) - { - pName->SetLiteral(W("String")); - } - - return true; - } - } - - // it's not a primitive - return false; -} - -// -// Append the WinRT type name for the method table, if it is a WinRT primitive type -// -bool WinRTTypeNameConverter::AppendWinRTNameForPrimitiveType(MethodTable *pMT, SString &strName) -{ - CONTRACTL - { - THROWS; - GC_NOTRIGGER; - MODE_ANY; - PRECONDITION(CheckPointer(pMT)); - PRECONDITION(CheckPointer(pMT, NULL_OK)); - } - CONTRACTL_END; - - SString strPrimitiveTypeName; - if (GetWinRTNameForPrimitiveType(pMT, &strPrimitiveTypeName)) - { - strName.Append(strPrimitiveTypeName); - return true; - } - - return false; -} - -// static -bool WinRTTypeNameConverter::IsRedirectedType(MethodTable *pMT, WinMDAdapter::WinMDTypeKind kind) -{ - LIMITED_METHOD_CONTRACT; - - WinMDAdapter::RedirectedTypeIndex index; - return (ResolveRedirectedType(pMT, &index) && (g_redirectedTypeNames[index].kind == kind)); -} - -// -// Determine if the given type redirected only by doing name comparisons. This is used to -// calculate the redirected type index at EEClass creation time. -// - -// static -WinMDAdapter::RedirectedTypeIndex WinRTTypeNameConverter::GetRedirectedTypeIndexByName( - Module *pModule, - mdTypeDef token) -{ - CONTRACTL - { - STANDARD_VM_CHECK; - PRECONDITION(CheckPointer(pModule)); - } - CONTRACTL_END; - - // If the redirected type hashtable has not been initialized initialize it - if (s_pRedirectedTypeNamesHashTable == NULL) - { - NewHolder pRedirectedTypeNamesHashTable = new RedirectedTypeNamesHashTable(); - pRedirectedTypeNamesHashTable->Reallocate(2 * COUNTOF(g_redirectedTypeNames)); - - for (int i = 0; i < COUNTOF(g_redirectedTypeNames); ++i) - { - pRedirectedTypeNamesHashTable->Add(&(g_redirectedTypeNames[i])); - } - - if (InterlockedCompareExchangeT(&s_pRedirectedTypeNamesHashTable, pRedirectedTypeNamesHashTable.GetValue(), NULL) == NULL) - { - pRedirectedTypeNamesHashTable.SuppressRelease(); - } - } - - IMDInternalImport *pInternalImport = pModule->GetMDImport(); - LPCSTR szName; - LPCSTR szNamespace; - IfFailThrow(pInternalImport->GetNameOfTypeDef(token, &szName, &szNamespace)); - - const RedirectedTypeNames *const * ppRedirectedNames = s_pRedirectedTypeNamesHashTable->LookupPtr(RedirectedTypeNamesKey(szNamespace, szName)); - if (ppRedirectedNames == NULL) - { - return WinMDAdapter::RedirectedTypeIndex_Invalid; - } - - UINT redirectedTypeIndex = (UINT)(*ppRedirectedNames - g_redirectedTypeNames); - _ASSERTE(redirectedTypeIndex < COUNTOF(g_redirectedTypeNames)); - - // If the redirected assembly is mscorlib just compare it directly. This is necessary because - // WinMDAdapter::GetExtraAssemblyRefProps does not support mscorlib - if (g_redirectedTypeNames[redirectedTypeIndex].assembly == WinMDAdapter::FrameworkAssembly_Mscorlib) - { - return MscorlibBinder::GetModule()->GetAssembly() == pModule->GetAssembly() ? - (WinMDAdapter::RedirectedTypeIndex)redirectedTypeIndex : - WinMDAdapter::RedirectedTypeIndex_Invalid; - } - - LPCSTR pSimpleName; - AssemblyMetaDataInternal context; - const BYTE * pbKeyToken; - DWORD cbKeyTokenLength; - DWORD dwFlags; - WinMDAdapter::GetExtraAssemblyRefProps( - g_redirectedTypeNames[redirectedTypeIndex].assembly, - &pSimpleName, - &context, - &pbKeyToken, - &cbKeyTokenLength, - &dwFlags); - - AssemblySpec spec; - IfFailThrow(spec.Init( - pSimpleName, - &context, - pbKeyToken, - cbKeyTokenLength, - dwFlags)); - Assembly* pRedirectedAssembly = spec.LoadAssembly( - FILE_LOADED, - FALSE); // fThrowOnFileNotFound - - if (pRedirectedAssembly == NULL) - { - return WinMDAdapter::RedirectedTypeIndex_Invalid; - } - - // Resolve the name in the redirected assembly to the actual type def and assembly - NameHandle nameHandle(szNamespace, szName); - nameHandle.SetTokenNotToLoad(tdAllTypes); - Module * pTypeDefModule; - mdTypeDef typeDefToken; - - if (ClassLoader::ResolveNameToTypeDefThrowing( - pRedirectedAssembly->GetManifestModule(), - &nameHandle, - &pTypeDefModule, - &typeDefToken, - Loader::DontLoad)) - { - // Finally check if the assembly from this type def token mathes the assembly type forwareded from the - // redirected assembly - if (pTypeDefModule->GetAssembly() == pModule->GetAssembly()) - { - return (WinMDAdapter::RedirectedTypeIndex)redirectedTypeIndex; - } - } - - return WinMDAdapter::RedirectedTypeIndex_Invalid; -} - -struct WinRTPrimitiveTypeMapping -{ - - BinderClassID binderID; - LPCWSTR wszWinRTName; -}; - -#define DEFINE_PRIMITIVE_TYPE_MAPPING(elementType, winrtTypeName) { elementType, L##winrtTypeName }, - -// -// Pre-sorted mapping : WinRT primitive type string -> BinderClassID -// -const WinRTPrimitiveTypeMapping s_winRTPrimitiveTypeMapping[] = -{ - DEFINE_PRIMITIVE_TYPE_MAPPING(CLASS__BOOLEAN, "Boolean") - DEFINE_PRIMITIVE_TYPE_MAPPING(CLASS__CHAR, "Char16") - DEFINE_PRIMITIVE_TYPE_MAPPING(CLASS__DOUBLE, "Double") - DEFINE_PRIMITIVE_TYPE_MAPPING(CLASS__GUID, "Guid") - DEFINE_PRIMITIVE_TYPE_MAPPING(CLASS__INT16, "Int16") - DEFINE_PRIMITIVE_TYPE_MAPPING(CLASS__INT32, "Int32") - DEFINE_PRIMITIVE_TYPE_MAPPING(CLASS__INT64, "Int64") - DEFINE_PRIMITIVE_TYPE_MAPPING(CLASS__OBJECT, "Object") - DEFINE_PRIMITIVE_TYPE_MAPPING(CLASS__SINGLE, "Single") - DEFINE_PRIMITIVE_TYPE_MAPPING(CLASS__STRING, "String") - DEFINE_PRIMITIVE_TYPE_MAPPING(CLASS__UINT16, "UInt16") - DEFINE_PRIMITIVE_TYPE_MAPPING(CLASS__UINT32, "UInt32") - DEFINE_PRIMITIVE_TYPE_MAPPING(CLASS__UINT64, "UInt64") - DEFINE_PRIMITIVE_TYPE_MAPPING(CLASS__BYTE, "UInt8") -}; - -// -// Return MethodTable* for the specified WinRT primitive type name -// -bool WinRTTypeNameConverter::GetMethodTableFromWinRTPrimitiveType(LPCWSTR wszTypeName, UINT32 uTypeNameLen, MethodTable **ppMT) -{ - CONTRACTL - { - THROWS; - GC_TRIGGERS; - MODE_ANY; - PRECONDITION(CheckPointer(ppMT)); - } - CONTRACTL_END; - - if (uTypeNameLen >= 4 && uTypeNameLen <= 7) - { - // - // Binary search the lookup table - // - int begin = 0, end = _countof(s_winRTPrimitiveTypeMapping) - 1; - while (begin <= end) - { - _ASSERTE(begin >= 0 && begin <= _countof(s_winRTPrimitiveTypeMapping) - 1); - _ASSERTE(end >= 0 && end <= _countof(s_winRTPrimitiveTypeMapping) - 1); - - int mid = (begin + end) / 2; - int ret = wcscmp(wszTypeName, s_winRTPrimitiveTypeMapping[mid].wszWinRTName); - if (ret == 0) - { - *ppMT = MscorlibBinder::GetClass(s_winRTPrimitiveTypeMapping[mid].binderID); - return true; - } - else if (ret > 0) - { - begin = mid + 1; - } - else - { - end = mid - 1; - } - } - } - - // it's not a primitive - return false; -} - -// Is the specified MethodTable a redirected WinRT type? -bool WinRTTypeNameConverter::IsRedirectedWinRTSourceType(MethodTable *pMT) -{ - CONTRACTL - { - THROWS; - GC_NOTRIGGER; - MODE_ANY; - } - CONTRACTL_END; - - if (!pMT->IsProjectedFromWinRT()) - return false; - - // redirected types are hidden (made internal) by the adapter - if (IsTdPublic(pMT->GetClass()->GetProtection())) - return false; - - DefineFullyQualifiedNameForClassW(); - LPCWSTR pszName = GetFullyQualifiedNameForClassW_WinRT(pMT); - - return !!WinMDAdapter::ConvertWellKnownFullTypeNameFromWinRTToClr(&pszName, NULL); -} - -// -// Get TypeHandle from a WinRT type name -// Parse the WinRT type name in the form of WinRTType=TypeName[] -// -TypeHandle WinRTTypeNameConverter::LoadManagedTypeForWinRTTypeName(LPCWSTR wszWinRTTypeName, ICLRPrivBinder * loadBinder, bool *pbIsPrimitive) -{ - CONTRACTL - { - THROWS; - GC_TRIGGERS; - MODE_ANY; - PRECONDITION(CheckPointer(wszWinRTTypeName)); - PRECONDITION(CheckPointer(pbIsPrimitive, NULL_OK)); - } - CONTRACTL_END; - - SString ssTypeName(SString::Literal, wszWinRTTypeName); - - TypeHandle th = LoadManagedTypeForWinRTTypeNameInternal(&ssTypeName, loadBinder, pbIsPrimitive); - if (th.IsNull()) - { - COMPlusThrowArgumentException(W("typeName"), NULL); - } - - return th; -} - -// Helper used by code:GetWinRTType to compose a generic type from an array of components. -// For example [IDictionary`2, int, IList`1, string] yields IDictionary`2>. -static TypeHandle ComposeTypeRecursively(CQuickArray &rqPartTypes, DWORD *pIndex) -{ - CONTRACTL - { - MODE_ANY; - THROWS; - GC_TRIGGERS; - PRECONDITION(*pIndex < rqPartTypes.Size()); - } - CONTRACTL_END; - - DWORD index = (*pIndex)++; - TypeHandle th = rqPartTypes[index]; - - if (th.HasInstantiation()) - { - DWORD dwArgCount = th.GetNumGenericArgs(); - for (DWORD i = 0; i < dwArgCount; i++) - { - // we scan rqPartTypes linearly so we know that the elements can be reused - rqPartTypes[i + index] = ComposeTypeRecursively(rqPartTypes, pIndex); - } - - Instantiation inst(rqPartTypes.Ptr() + index, dwArgCount); - th = th.Instantiate(inst); - } - else if (th == g_pArrayClass) - { - // Support for arrays - rqPartTypes[index] = ComposeTypeRecursively(rqPartTypes, pIndex); - th = ClassLoader::LoadArrayTypeThrowing(rqPartTypes[index], ELEMENT_TYPE_SZARRAY, 1); - } - - return th; -} - -#ifdef CROSSGEN_COMPILE -// -// In crossgen, we use a mockup of RoParseTypeName since we need to run on pre-Win8 machines. -// -extern "C" HRESULT WINAPI CrossgenRoParseTypeName(SString* typeName, DWORD *partsCount, SString **typeNameParts); -#endif - -// -// Return TypeHandle for the specified WinRT type name (supports generic type) -// Updates wszWinRTTypeName pointer as it parse the string -// -TypeHandle WinRTTypeNameConverter::LoadManagedTypeForWinRTTypeNameInternal(SString *ssTypeName, ICLRPrivBinder* loadBinder, bool *pbIsPrimitive) -{ - CONTRACTL - { - THROWS; - GC_TRIGGERS; - MODE_ANY; - PRECONDITION(CheckPointer(ssTypeName)); - PRECONDITION(CheckPointer(pbIsPrimitive, NULL_OK)); - } - CONTRACTL_END; - - if (pbIsPrimitive) - *pbIsPrimitive = false; - - if (ssTypeName->IsEmpty()) - return TypeHandle(); - - TypeHandle typeHandle; - - SString::Iterator it = ssTypeName->Begin(); - if (ssTypeName->Find(it, W('<'))) - { - // this is a generic type - use RoParseTypeName to break it down into components - CQuickArray rqPartTypes; - -#ifndef CROSSGEN_COMPILE - - DWORD dwPartsCount = 0; - HSTRING *rhsPartNames; - - CoTaskMemHSTRINGArrayHolder hsNamePartsHolder; - IfFailThrow(RoParseTypeName(WinRtStringRef(ssTypeName->GetUnicode(), ssTypeName->GetCount()), &dwPartsCount, &rhsPartNames)); - hsNamePartsHolder.Init(rhsPartNames, dwPartsCount); - - rqPartTypes.AllocThrows(dwPartsCount); - - // load the components - for (DWORD i = 0; i < dwPartsCount; i++) - { - UINT32 cchPartLength; - PCWSTR wszPart = WindowsGetStringRawBuffer(rhsPartNames[i], &cchPartLength); - - StackSString ssPartName(wszPart, cchPartLength); - rqPartTypes[i] = GetManagedTypeFromSimpleWinRTNameInternal(&ssPartName, loadBinder, nullptr); - } - -#else //CROSSGEN_COMPILE - - // - // In crossgen, we use a mockup of RoParseTypeName since we need to run on pre-Win8 machines. - // - DWORD dwPartsCount = 0; - SString *rhsPartNames; - - IfFailThrow(CrossgenRoParseTypeName(ssTypeName, &dwPartsCount, &rhsPartNames)); - _ASSERTE(rhsPartNames != nullptr); - - rqPartTypes.AllocThrows(dwPartsCount); - - // load the components - for (DWORD i = 0; i < dwPartsCount; i++) - { - rqPartTypes[i] = GetManagedTypeFromSimpleWinRTNameInternal(&rhsPartNames[i], loadBinder, NULL); - } - - delete[] rhsPartNames; - -#endif //CROSSGEN_COMPILE - - // and instantiate the generic type - DWORD dwIndex = 0; - typeHandle = ComposeTypeRecursively(rqPartTypes, &dwIndex); - - _ASSERTE(dwIndex == rqPartTypes.Size()); - - return typeHandle; - } - else - { - return GetManagedTypeFromSimpleWinRTNameInternal(ssTypeName, loadBinder, pbIsPrimitive); - } -} - -// -// Return MethodTable* for the specified WinRT primitive type name (non-generic type) -// Updates wszWinRTTypeName pointer as it parse the string -// -TypeHandle WinRTTypeNameConverter::GetManagedTypeFromSimpleWinRTNameInternal(SString *ssTypeName, ICLRPrivBinder* loadBinder, bool *pbIsPrimitive) -{ - CONTRACTL - { - THROWS; - GC_TRIGGERS; - MODE_ANY; - PRECONDITION(CheckPointer(ssTypeName)); - PRECONDITION(CheckPointer(pbIsPrimitive, NULL_OK)); - } - CONTRACTL_END; - - if (pbIsPrimitive) - *pbIsPrimitive = false; - - if (ssTypeName->IsEmpty()) - return TypeHandle(); - - // - // Redirection - // - LPCWSTR pwszTypeName = ssTypeName->GetUnicode(); - WinMDAdapter::RedirectedTypeIndex uIndex; - MethodTable *pMT = NULL; - - if (WinMDAdapter::ConvertWellKnownFullTypeNameFromWinRTToClr(&pwszTypeName, &uIndex)) - { - // - // Well known redirected types - // - return TypeHandle(GetAppDomain()->GetRedirectedType(uIndex)); - } - else if (GetMethodTableFromWinRTPrimitiveType(pwszTypeName, ssTypeName->GetCount(), &pMT)) - { - - // - // Primitive type - // - if (pbIsPrimitive) - *pbIsPrimitive = true; - return TypeHandle(pMT); - } - else if (wcscmp(pwszTypeName, W("Windows.Foundation.IReferenceArray`1")) == 0) - { - // - // Handle array case - return the array and we'll create the array later - // - return TypeHandle(g_pArrayClass); - } - else - { - // - // A regular WinRT type - // - return LoadWinRTType(ssTypeName, TRUE, loadBinder); - } -} - -#endif // !DACCESS_COMPILE -#endif // FEATURE_COMINTEROP diff --git a/src/coreclr/src/vm/winrttypenameconverter.h b/src/coreclr/src/vm/winrttypenameconverter.h deleted file mode 100644 index 0cff28a..0000000 --- a/src/coreclr/src/vm/winrttypenameconverter.h +++ /dev/null @@ -1,126 +0,0 @@ -// 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. -// -// File: WinRTTypeNameConverter.cpp -// - -// - -// -// ============================================================================ - -#ifndef FEATURE_COMINTEROP -#error This file should only be included when FEATURE_COMINTEROP is defined -#endif - -#pragma once - -#include "..\md\winmd\inc\adapter.h" -#include "clrprivbinding.h" - -struct WinRTTypeNameInfo; - -// -// Converts between a WinRT type name and TypeHandle -// -class WinRTTypeNameConverter -{ -public : - //============================================================================================== - // Managed -> WinRT - //============================================================================================== - - // - // Append WinRT type name for the specified type handle - // - static bool AppendWinRTTypeNameForManagedType( - TypeHandle thManagedType, - SString &strWinRTTypeName, - bool bForGetRuntimeClassName, - bool *pbIsPrimitive); - - // - // Return the redirection index and type kind if the MethodTable* is a redirected type - // - static bool ResolveRedirectedType(MethodTable *pMT, WinMDAdapter::RedirectedTypeIndex * pIndex, WinMDAdapter::WinMDTypeKind * pKind = NULL); - - // - // Append the WinRT type name for the method table, if it is a WinRT primitive type - // - static bool AppendWinRTNameForPrimitiveType(MethodTable *pMT, SString &strName); - - // - // Is the specified MethodTable a WinRT primitive type - // - static bool IsWinRTPrimitiveType(MethodTable *pMT) - { - WRAPPER_NO_CONTRACT; - return GetWinRTNameForPrimitiveType(pMT, NULL); - } - - // - // Is the specified MethodTable a redirected CLR type? - // - static bool IsRedirectedType(MethodTable *pMT) - { - WRAPPER_NO_CONTRACT; - return ResolveRedirectedType(pMT, NULL); - } - - static bool IsRedirectedType(MethodTable *pMT, WinMDAdapter::WinMDTypeKind kind); - - // - // Determine if the given type redirected only by doing name comparisons. This is used to - // calculate the redirected type index at EEClass creation time. - // - static WinMDAdapter::RedirectedTypeIndex GetRedirectedTypeIndexByName( - Module *pModule, - mdTypeDef token); -public : - //============================================================================================== - // WinRT -> Managed - //============================================================================================== - - // - // Is the specified MethodTable a redirected WinRT type? - // - static bool IsRedirectedWinRTSourceType(MethodTable *pMT); - - // - // Get TypeHandle from a WinRT type name - // Parse the WinRT type name in the form of WinRTType=TypeName[] - // - static TypeHandle LoadManagedTypeForWinRTTypeName(LPCWSTR wszWinRTTypeName, ICLRPrivBinder * loadBinder, bool *pbIsPrimitive); - -private : - - // - // Get predefined WinRT name for a primitive type - // - static bool GetWinRTNameForPrimitiveType(MethodTable *pMT, SString *pName); - - // - // Return MethodTable* for the specified WinRT primitive type name - // - static bool GetMethodTableFromWinRTPrimitiveType(LPCWSTR wszTypeName, UINT32 uTypeNameLen, MethodTable **ppMT); - - // - // Return TypeHandle for the specified WinRT type name (supports generic type) - // Updates wszWinRTTypeName pointer as it parse the string - // - static TypeHandle LoadManagedTypeForWinRTTypeNameInternal(SString *ssTypeName, ICLRPrivBinder* loadBinder, bool *pbIsPrimitive); - - // - // Return MethodTable* for the specified WinRT primitive type name (non-generic type) - // Updates wszWinRTTypeName pointer as it parse the string - // - static TypeHandle GetManagedTypeFromSimpleWinRTNameInternal(SString *ssTypeName, ICLRPrivBinder* loadBinder, bool *pbIsPrimitive); - - static bool AppendWinRTTypeNameForManagedType( - TypeHandle thManagedType, - SString &strWinRTTypeName, - bool bForGetRuntimeClassName, - bool *pbIsPrimitive, - WinRTTypeNameInfo *pCurrentTypeInfo); -}; diff --git a/src/coreclr/src/vm/wrappers.h b/src/coreclr/src/vm/wrappers.h index a256cb5..4599cd7 100644 --- a/src/coreclr/src/vm/wrappers.h +++ b/src/coreclr/src/vm/wrappers.h @@ -8,9 +8,6 @@ #include "metadata.h" #include "interoputil.h" -#ifdef FEATURE_COMINTEROP -#include "windowsstring.h" -#endif class MDEnumHolder { @@ -117,40 +114,6 @@ using SafeComHolder = SpecializedWrapper<_TYPE, SafeComRelease<_TYPE>>; template using SafeComHolderPreemp = SpecializedWrapper<_TYPE, SafeComReleasePreemp<_TYPE>>; - - -#ifdef FEATURE_COMINTEROP -#ifdef CROSSGEN_COMPILE - namespace clr - { - namespace winrt - { - template inline - HRESULT GetActivationFactory( - __in WinRtStringRef const & wzActivatableClassId, - __deref_out ItfT** ppItf) - { - LIMITED_METHOD_CONTRACT; - return GetActivationFactory(wzActivatableClassId, ppItf); - } - - template inline - HRESULT GetActivationFactory( - __in WinRtStringRef const & wzActivatableClassId, - __out typename SafeComHolderPreemp* pItf) - { - STATIC_CONTRACT_WRAPPER; - - if (pItf == nullptr) - return E_INVALIDARG; - - return GetActivationFactory(wzActivatableClassId, (ItfT**)&(*pItf)); - } - } - } -#endif //CROSSGEN_COMPILE -#endif //FEATURE_COMINTEROP - //----------------------------------------------------------------------------- // NewPreempHolder : New'ed memory holder, deletes in preemp mode. // diff --git a/src/coreclr/src/vm/zapsig.cpp b/src/coreclr/src/vm/zapsig.cpp index 515ea2f..dc7a004 100644 --- a/src/coreclr/src/vm/zapsig.cpp +++ b/src/coreclr/src/vm/zapsig.cpp @@ -704,10 +704,6 @@ Module *ZapSig::DecodeModuleFromIndexIfLoaded(Module *fromModule, ? nativeImage->GetManifestMetadata() : fromModule->GetNativeAssemblyImport(FALSE)); if (pMDImportOverride != NULL) { - CHAR szFullName[MAX_CLASS_NAME + 1]; - LPCSTR szWinRtNamespace = NULL; - LPCSTR szWinRtClassName = NULL; - BOOL fValidAssemblyRef = TRUE; LPCSTR pAssemblyName; DWORD dwFlags; @@ -723,49 +719,10 @@ Module *ZapSig::DecodeModuleFromIndexIfLoaded(Module *fromModule, fValidAssemblyRef = FALSE; } - if (fValidAssemblyRef && IsAfContentType_WindowsRuntime(dwFlags)) - { - // Find the encoded type name - LPCSTR pTypeName = NULL; - if (pAssemblyName != NULL) - pTypeName = strchr(pAssemblyName, '!'); - - if (pTypeName != NULL) - { - pTypeName++; - // pTypeName now contains the full type name (namespace + name) - - strcpy_s(szFullName, _countof(szFullName), pTypeName); - LPSTR pszName = strrchr(szFullName, '.'); - - // WinRT types must have a namespace - if (pszName != NULL) - { - // Replace . between namespace and name with null terminator. - // This breaks the string into a namespace and name pair. - *pszName = '\0'; - pszName++; - - szWinRtNamespace = szFullName; - szWinRtClassName = pszName; - } - else - { // Namespace '.' separator not found - invalid type name (namespace has to be always present) - fValidAssemblyRef = FALSE; - } - } - else - { // Type name separator in assembly name '!' not found - fValidAssemblyRef = FALSE; - } - } - if (fValidAssemblyRef) { pAssembly = fromModule->GetAssemblyIfLoaded( tkAssemblyRef, - szWinRtNamespace, - szWinRtClassName, pMDImportOverride); } } diff --git a/src/coreclr/src/zap/zapimage.cpp b/src/coreclr/src/zap/zapimage.cpp index 258ebcf..e4ab0b9 100644 --- a/src/coreclr/src/zap/zapimage.cpp +++ b/src/coreclr/src/zap/zapimage.cpp @@ -166,11 +166,8 @@ void ZapImage::InitializeSections() m_pHelperThunks = new (GetHeap()) ZapNode * [CORINFO_HELP_COUNT]; - if (!m_zapper->m_pOpt->m_fNoMetaData) - { - m_pILMetaData = new (GetHeap()) ZapILMetaData(this); - m_pILMetaDataSection->Place(m_pILMetaData); - } + m_pILMetaData = new (GetHeap()) ZapILMetaData(this); + m_pILMetaDataSection->Place(m_pILMetaData); m_pDebugInfoTable = new (GetHeap()) ZapDebugInfoTable(this); m_pDebugSection->Place(m_pDebugInfoTable); diff --git a/src/coreclr/src/zap/zapmetadata.cpp b/src/coreclr/src/zap/zapmetadata.cpp index e343390..d5b9b72 100644 --- a/src/coreclr/src/zap/zapmetadata.cpp +++ b/src/coreclr/src/zap/zapmetadata.cpp @@ -270,7 +270,7 @@ void ZapILMetaData::CopyMetaData() V_BSTR(&versionOption) = strVersion; IfFailThrow(pMetaDataDispenser->SetOption(MetaDataRuntimeVersion, &versionOption)); - // Preserve local refs. WinMD adapter depends on them at runtime. + // Preserve local refs. VARIANT preserveLocalRefsOption; V_VT(&preserveLocalRefsOption) = VT_UI4; V_UI4(&preserveLocalRefsOption) = MDPreserveLocalTypeRef | MDPreserveLocalMemberRef; diff --git a/src/coreclr/src/zap/zapper.cpp b/src/coreclr/src/zap/zapper.cpp index eb79402..4bc8e51 100644 --- a/src/coreclr/src/zap/zapper.cpp +++ b/src/coreclr/src/zap/zapper.cpp @@ -15,15 +15,12 @@ extern const WCHAR g_pwBaseLibrary[]; extern bool g_fAllowNativeImages; bool g_fNGenMissingDependenciesOk; -bool g_fNGenWinMDResilient; #ifdef FEATURE_READYTORUN_COMPILER bool g_fReadyToRunCompilation; bool g_fLargeVersionBubble; #endif -static bool s_fNGenNoMetaData; - /* --------------------------------------------------------------------------- * * Public entry points for ngen * --------------------------------------------------------------------------- */ @@ -31,7 +28,7 @@ static bool s_fNGenNoMetaData; // Zapper Object instead of creating one on your own. -STDAPI NGenWorker(LPCWSTR pwzFilename, DWORD dwFlags, LPCWSTR pwzPlatformAssembliesPaths, LPCWSTR pwzTrustedPlatformAssemblies, LPCWSTR pwzPlatformResourceRoots, LPCWSTR pwzAppPaths, LPCWSTR pwzOutputFilename=NULL, SIZE_T customBaseAddress=0, LPCWSTR pwzPlatformWinmdPaths=NULL, ICorSvcLogger *pLogger = NULL, LPCWSTR pwszCLRJITPath = nullptr) +STDAPI NGenWorker(LPCWSTR pwzFilename, DWORD dwFlags, LPCWSTR pwzPlatformAssembliesPaths, LPCWSTR pwzTrustedPlatformAssemblies, LPCWSTR pwzPlatformResourceRoots, LPCWSTR pwzAppPaths, LPCWSTR pwzOutputFilename=NULL, SIZE_T customBaseAddress=0, ICorSvcLogger *pLogger = NULL, LPCWSTR pwszCLRJITPath = nullptr) { HRESULT hr = S_OK; @@ -74,8 +71,6 @@ STDAPI NGenWorker(LPCWSTR pwzFilename, DWORD dwFlags, LPCWSTR pwzPlatformAssembl ngo.fNgenLastRetry = false; - s_fNGenNoMetaData = (dwFlags & NGENWORKER_FLAGS_NO_METADATA) != 0; - zap = Zapper::NewZapper(&ngo); if (pwzOutputFilename) @@ -95,9 +90,6 @@ STDAPI NGenWorker(LPCWSTR pwzFilename, DWORD dwFlags, LPCWSTR pwzPlatformAssembl if (pwzAppPaths != nullptr) zap->SetAppPaths(pwzAppPaths); - if (pwzPlatformWinmdPaths != nullptr) - zap->SetPlatformWinmdPaths(pwzPlatformWinmdPaths); - #if !defined(FEATURE_MERGE_JIT_AND_ENGINE) if (pwszCLRJITPath != nullptr) zap->SetCLRJITPath(pwszCLRJITPath); @@ -105,10 +97,6 @@ STDAPI NGenWorker(LPCWSTR pwzFilename, DWORD dwFlags, LPCWSTR pwzPlatformAssembl g_fNGenMissingDependenciesOk = !!(dwFlags & NGENWORKER_FLAGS_MISSINGDEPENDENCIESOK); -#ifdef FEATURE_WINMD_RESILIENT - g_fNGenWinMDResilient = !!(dwFlags & NGENWORKER_FLAGS_WINMD_RESILIENT); -#endif - #ifdef FEATURE_READYTORUN_COMPILER g_fReadyToRunCompilation = !!(dwFlags & NGENWORKER_FLAGS_READYTORUN); g_fLargeVersionBubble = !!(dwFlags & NGENWORKER_FLAGS_LARGEVERSIONBUBBLE); @@ -128,7 +116,7 @@ STDAPI NGenWorker(LPCWSTR pwzFilename, DWORD dwFlags, LPCWSTR pwzPlatformAssembl return hr; } -STDAPI CreatePDBWorker(LPCWSTR pwzAssemblyPath, LPCWSTR pwzPlatformAssembliesPaths, LPCWSTR pwzTrustedPlatformAssemblies, LPCWSTR pwzPlatformResourceRoots, LPCWSTR pwzAppPaths, LPCWSTR pwzAppNiPaths, LPCWSTR pwzPdbPath, BOOL fGeneratePDBLinesInfo, LPCWSTR pwzManagedPdbSearchPath, LPCWSTR pwzPlatformWinmdPaths, LPCWSTR pwzDiasymreaderPath) +STDAPI CreatePDBWorker(LPCWSTR pwzAssemblyPath, LPCWSTR pwzPlatformAssembliesPaths, LPCWSTR pwzTrustedPlatformAssemblies, LPCWSTR pwzPlatformResourceRoots, LPCWSTR pwzAppPaths, LPCWSTR pwzAppNiPaths, LPCWSTR pwzPdbPath, BOOL fGeneratePDBLinesInfo, LPCWSTR pwzManagedPdbSearchPath, LPCWSTR pwzDiasymreaderPath) { HRESULT hr = S_OK; @@ -164,9 +152,6 @@ STDAPI CreatePDBWorker(LPCWSTR pwzAssemblyPath, LPCWSTR pwzPlatformAssembliesPat if (pwzAppNiPaths != nullptr) zap->SetAppNiPaths(pwzAppNiPaths); - if (pwzPlatformWinmdPaths != nullptr) - zap->SetPlatformWinmdPaths(pwzPlatformWinmdPaths); - #if !defined(NO_NGENPDB) if (pwzDiasymreaderPath != nullptr) zap->SetDiasymreaderPath(pwzDiasymreaderPath); @@ -217,8 +202,7 @@ ZapperOptions::ZapperOptions() : m_fPartialNGen(false), m_fPartialNGenSet(false), m_fNGenLastRetry(false), - m_compilerFlags(), - m_fNoMetaData(s_fNGenNoMetaData) + m_compilerFlags() { SetCompilerFlags(); @@ -898,10 +882,6 @@ void Zapper::CreateCompilationDomain() fForceProfile, fForceInstrument)); -#ifdef CROSSGEN_COMPILE - IfFailThrow(m_pDomain->SetPlatformWinmdPaths(m_platformWinmdPaths)); -#endif - // we support only TPA binding on CoreCLR if (!m_trustedPlatformAssemblies.IsEmpty()) @@ -1678,12 +1658,6 @@ void Zapper::SetAppNiPaths(LPCWSTR pwzAppNiPaths) m_appNiPaths.Set(pwzAppNiPaths); } -void Zapper::SetPlatformWinmdPaths(LPCWSTR pwzPlatformWinmdPaths) -{ - m_platformWinmdPaths.Set(pwzPlatformWinmdPaths); -} - - void Zapper::SetOutputFilename(LPCWSTR pwzOutputFilename) { m_outputFilename.Set(pwzOutputFilename); diff --git a/src/coreclr/tests/src/Common/CoreCLRTestLibrary/Utilities.cs b/src/coreclr/tests/src/Common/CoreCLRTestLibrary/Utilities.cs index e596d55..835ccbf 100644 --- a/src/coreclr/tests/src/Common/CoreCLRTestLibrary/Utilities.cs +++ b/src/coreclr/tests/src/Common/CoreCLRTestLibrary/Utilities.cs @@ -67,9 +67,8 @@ namespace TestLibrary public static bool IsLinux => RuntimeInformation.IsOSPlatform(OSPlatform.Linux); public static bool IsMacOSX => RuntimeInformation.IsOSPlatform(OSPlatform.OSX); public static bool IsWindows7 => IsWindows && Environment.OSVersion.Version.Major == 6 && Environment.OSVersion.Version.Minor == 1; - public static bool IsWinRTSupported => IsWindows && !IsWindows7 && !IsWindowsNanoServer; public static bool IsWindowsNanoServer => (!IsWindowsIoTCore && GetInstallationType().Equals("Nano Server", StringComparison.OrdinalIgnoreCase)); - + // Windows 10 October 2018 Update public static bool IsWindows10Version1809OrGreater => IsWindows && GetWindowsVersion() == 10 && GetWindowsMinorVersion() == 0 && GetWindowsBuildNumber() >= 17763; @@ -119,7 +118,7 @@ namespace TestLibrary return true; } - // Given a string, display the unicode characters in hex format, optionally displaying each + // Given a string, display the unicode characters in hex format, optionally displaying each // characters unicode category public static string FormatHexStringFromUnicodeString(string string1, bool includeUnicodeCategory) { @@ -145,7 +144,7 @@ namespace TestLibrary return returnString; } - // Given a character, display its unicode value in hex format. ProjectN doens't support + // Given a character, display its unicode value in hex format. ProjectN doens't support // unicode category as a Property on Char. public static string FormatHexStringFromUnicodeChar(char char1, bool includeUnicodeCategory) { @@ -293,7 +292,7 @@ namespace TestLibrary } internal static unsafe string RtlGetVersion() - { + { const string Version = "Microsoft Windows"; if (RtlGetVersionEx(out RTL_OSVERSIONINFOEX osvi) == 0) { diff --git a/src/coreclr/tests/src/Interop/CMakeLists.txt b/src/coreclr/tests/src/Interop/CMakeLists.txt index 778d9ab..4e1e20f 100644 --- a/src/coreclr/tests/src/Interop/CMakeLists.txt +++ b/src/coreclr/tests/src/Interop/CMakeLists.txt @@ -82,7 +82,6 @@ if(CLR_CMAKE_TARGET_WIN32) add_subdirectory(COM/NativeClients/Events) add_subdirectory(COM/ComWrappers/MockReferenceTrackerRuntime) add_subdirectory(COM/ComWrappers/WeakReference) - add_subdirectory(WinRT/NativeComponent) # IJW isn't supported on ARM64 if(NOT CLR_CMAKE_HOST_ARCH_ARM64) diff --git a/src/coreclr/tests/src/Interop/COM/ComWrappers/GlobalInstance/GlobalInstance.cs b/src/coreclr/tests/src/Interop/COM/ComWrappers/GlobalInstance/GlobalInstance.cs index b362bc6..7c58c46 100644 --- a/src/coreclr/tests/src/Interop/COM/ComWrappers/GlobalInstance/GlobalInstance.cs +++ b/src/coreclr/tests/src/Interop/COM/ComWrappers/GlobalInstance/GlobalInstance.cs @@ -41,12 +41,6 @@ namespace ComWrappersTests.GlobalInstance [MarshalAs(UnmanagedType.IDispatch)] out object ret); [DllImport(nameof(MockReferenceTrackerRuntime))] - extern public static int UpdateTestObjectAsIInspectable( - [MarshalAs(UnmanagedType.IInspectable)] object testObj, - int i, - [MarshalAs(UnmanagedType.IInspectable)] out object ret); - - [DllImport(nameof(MockReferenceTrackerRuntime))] extern public static int UpdateTestObjectAsInterface( [MarshalAs(UnmanagedType.Interface)] ITest testObj, int i, @@ -339,9 +333,6 @@ namespace ComWrappersTests.GlobalInstance { Console.WriteLine($" -- Validate MarshalAs IDispatch..."); ValidateInterfaceMarshaler(MarshalInterface.UpdateTestObjectAsIDispatch, shouldSucceed: true, new TestEx(IID_IDISPATCH)); - - Console.WriteLine($" -- Validate MarshalAs IInspectable..."); - ValidateInterfaceMarshaler(MarshalInterface.UpdateTestObjectAsIInspectable, shouldSucceed: true, new TestEx(IID_IINSPECTABLE)); } Console.WriteLine($" -- Validate MarshalAs Interface..."); diff --git a/src/coreclr/tests/src/Interop/COM/ComWrappers/MockReferenceTrackerRuntime/ReferenceTrackerRuntime.cpp b/src/coreclr/tests/src/Interop/COM/ComWrappers/MockReferenceTrackerRuntime/ReferenceTrackerRuntime.cpp index 54cf0bb..e3897cd 100644 --- a/src/coreclr/tests/src/Interop/COM/ComWrappers/MockReferenceTrackerRuntime/ReferenceTrackerRuntime.cpp +++ b/src/coreclr/tests/src/Interop/COM/ComWrappers/MockReferenceTrackerRuntime/ReferenceTrackerRuntime.cpp @@ -361,14 +361,6 @@ extern "C" DLL_EXPORT int STDMETHODCALLTYPE UpdateTestObjectAsIDispatch(IDispatc return UpdateTestObjectAsIUnknown(obj, i, (IUnknown**)out); } -extern "C" DLL_EXPORT int STDMETHODCALLTYPE UpdateTestObjectAsIInspectable(IInspectable * obj, int i, IInspectable **out) -{ - if (obj == nullptr) - return E_POINTER; - - return UpdateTestObjectAsIUnknown(obj, i, (IUnknown **)out); -} - extern "C" DLL_EXPORT int STDMETHODCALLTYPE UpdateTestObjectAsInterface(ITest *obj, int i, ITest **out) { if (obj == nullptr) diff --git a/src/coreclr/tests/src/Interop/WinRT/Contracts/Component.Contracts.cs b/src/coreclr/tests/src/Interop/WinRT/Contracts/Component.Contracts.cs deleted file mode 100644 index 068bbd7..0000000 --- a/src/coreclr/tests/src/Interop/WinRT/Contracts/Component.Contracts.cs +++ /dev/null @@ -1,118 +0,0 @@ -// 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.Collections.Generic; -using System.Collections.Specialized; -using System.ComponentModel; -using System.Runtime.InteropServices; -using System.Runtime.InteropServices.WindowsRuntime; - -namespace Component.Contracts -{ - [ComImport] - [Guid("971AF13A-9793-4AF7-B2F2-72D829195592")] - [WindowsRuntimeImport] - public interface IBooleanTesting - { - bool And(bool left, bool right); - } - - [ComImport] - [Guid("C6F1F632-47B6-4A52-86D2-A89807ED2677")] - [WindowsRuntimeImport] - public interface IStringTesting - { - string ConcatStrings(string left, string right); - } - - [ComImport] - [Guid("939D4EE5-8D41-4C4B-8948-86017CEB9244")] - [WindowsRuntimeImport] - public interface INullableTesting - { - bool IsNull(int? value); - int GetIntValue(int? value); - } - - [ComImport] - [Guid("BB545A14-9AE7-491A-874D-1C03D239FB70")] - [WindowsRuntimeImport] - public interface ITypeTesting - { - string GetTypeName(Type type); - } - - [ComImport] - [Guid("9162201d-b591-4f30-8f41-f0f79f6ecea3")] - [WindowsRuntimeImport] - public interface IExceptionTesting - { - void ThrowException(Exception ex); - Exception GetException(int hResultToReturn); - } - - [ComImport] - [Guid("ccd10099-3a45-4382-970d-b76f52780bcd")] - [WindowsRuntimeImport] - public interface IKeyValuePairTesting - { - KeyValuePair MakeSimplePair(int key, int value); - KeyValuePair MakeMarshaledPair(string key, string value); - KeyValuePair> MakeProjectedPair(int key, int[] values); - } - - [ComImport] - [Guid("e0af24b3-e6c6-4e89-b8d1-a332979ef398")] - [WindowsRuntimeImport] - public interface IUriTesting - { - string GetFromUri(Uri uri); - Uri CreateUriFromString(string uri); - } - - [ComImport] - [Guid("821B532D-CC5E-4218-90AB-A8361AC92794")] - [WindowsRuntimeImport] - public interface IArrayTesting - { - int Sum(int[] array); - bool Xor(bool[] array); - } - - [ComImport] - [Guid("4bb923ae-986a-4aad-9bfb-13e0b5ecffa4")] - [WindowsRuntimeImport] - public interface IBindingViewModel - { - INotifyCollectionChanged Collection { get; } - void AddElement(int i); - string Name { get; set; } - } - - [ComImport] - [Guid("857e28e1-3e7f-4f6f-8554-efc73feba286")] - [WindowsRuntimeImport] - public interface IBindingProjectionsTesting - { - IBindingViewModel CreateViewModel(); - IDisposable InitializeXamlFrameworkForCurrentThread(); - } - - public enum TestEnum - { - A = 1, - B = 2, - C = 3 - } - - [ComImport] - [Guid("d89d71b2-2671-444d-8576-536d206dea49")] - [WindowsRuntimeImport] - public interface IEnumTesting - { - TestEnum GetA(); - Boolean IsB(TestEnum val); - } -} diff --git a/src/coreclr/tests/src/Interop/WinRT/Contracts/Component.Contracts.idl b/src/coreclr/tests/src/Interop/WinRT/Contracts/Component.Contracts.idl deleted file mode 100644 index 9126829..0000000 --- a/src/coreclr/tests/src/Interop/WinRT/Contracts/Component.Contracts.idl +++ /dev/null @@ -1,104 +0,0 @@ -// 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 Component.Contracts -{ - [interface_name("Component.Contracts.IBooleanTesting", 971AF13A-9793-4AF7-B2F2-72D829195592)] - runtimeclass BooleanTesting - { - BooleanTesting(); - Boolean And(Boolean left, Boolean right); - } - - [interface_name("Component.Contracts.IStringTesting", C6F1F632-47B6-4A52-86D2-A89807ED2677)] - runtimeclass StringTesting - { - StringTesting(); - String ConcatStrings(String left, String right); - } - - [interface_name("Component.Contracts.INullableTesting", 939D4EE5-8D41-4C4B-8948-86017CEB9244)] - runtimeclass NullableTesting - { - NullableTesting(); - Boolean IsNull(Windows.Foundation.IReference value); - Int32 GetIntValue(Windows.Foundation.IReference value); - } - - [interface_name("Component.Contracts.ITypeTesting", BB545A14-9AE7-491A-874D-1C03D239FB70)] - runtimeclass TypeTesting - { - TypeTesting(); - String GetTypeName(Windows.UI.Xaml.Interop.TypeName typeName); - } - - [interface_name("Component.Contracts.IExceptionTesting", 9162201d-b591-4f30-8f41-f0f79f6ecea3)] - runtimeclass ExceptionTesting - { - ExceptionTesting(); - void ThrowException(Windows.Foundation.HResult hr); - Windows.Foundation.HResult GetException(Int32 hr); - } - - [interface_name("Component.Contracts.IKeyValuePairTesting", ccd10099-3a45-4382-970d-b76f52780bcd)] - runtimeclass KeyValuePairTesting - { - KeyValuePairTesting(); - Windows.Foundation.Collections.IKeyValuePair MakeSimplePair(Int32 key, Int32 value); - Windows.Foundation.Collections.IKeyValuePair MakeMarshaledPair(String key, String value); - Windows.Foundation.Collections.IKeyValuePair > MakeProjectedPair(Int32 key, Int32[] values); - } - - [interface_name("Component.Contracts.IUriTesting", e0af24b3-e6c6-4e89-b8d1-a332979ef398)] - runtimeclass UriTesting - { - UriTesting(); - String GetFromUri(Windows.Foundation.Uri uri); - Windows.Foundation.Uri CreateUriFromString(String uri); - } - - [interface_name("Component.Contracts.IArrayTesting", 821B532D-CC5E-4218-90AB-A8361AC92794)] - runtimeclass ArrayTesting - { - ArrayTesting(); - Int32 Sum(Int32[] array); - Boolean Xor(Boolean[] array); - } - - [uuid(4bb923ae-986a-4aad-9bfb-13e0b5ecffa4)] - interface IBindingViewModel - { - Windows.UI.Xaml.Interop.INotifyCollectionChanged Collection { get; }; - void AddElement(Int32 i); - String Name { get; set; }; - } - - runtimeclass BindingViewModel : [default] IBindingViewModel, Windows.UI.Xaml.Data.INotifyPropertyChanged - { - BindingViewModel(); - } - - [interface_name("Component.Contracts.IBindingProjectionsTesting", 857e28e1-3e7f-4f6f-8554-efc73feba286)] - runtimeclass BindingProjectionsTesting - { - BindingProjectionsTesting(); - IBindingViewModel CreateViewModel(); - Windows.Foundation.IClosable InitializeXamlFrameworkForCurrentThread(); - } - - enum TestEnum - { - A = 1, - B = 2, - C = 3 - }; - - [interface_name("Component.Contracts.IEnumTesting", d89d71b2-2671-444d-8576-536d206dea49)] - runtimeclass EnumTesting - { - EnumTesting(); - TestEnum GetA(); - Boolean IsB(TestEnum val); - } -} diff --git a/src/coreclr/tests/src/Interop/WinRT/Contracts/NativeComponent.cs b/src/coreclr/tests/src/Interop/WinRT/Contracts/NativeComponent.cs deleted file mode 100644 index 0b4903e..0000000 --- a/src/coreclr/tests/src/Interop/WinRT/Contracts/NativeComponent.cs +++ /dev/null @@ -1,16 +0,0 @@ -// 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.Runtime.InteropServices; -using System.Runtime.InteropServices.WindowsRuntime; - -public static class WinRTNativeComponent -{ - [DllImport(nameof(WinRTNativeComponent), PreserveSig = false)] - private static extern IActivationFactory DllGetActivationFactory([MarshalAs(UnmanagedType.HString)] string typeName); - - public static object GetObjectFromNativeComponent(string typeName) - { - return DllGetActivationFactory(typeName).ActivateInstance(); - } -} diff --git a/src/coreclr/tests/src/Interop/WinRT/NETClients/Bindings/BindingTests.cs b/src/coreclr/tests/src/Interop/WinRT/NETClients/Bindings/BindingTests.cs deleted file mode 100644 index da88636..0000000 --- a/src/coreclr/tests/src/Interop/WinRT/NETClients/Bindings/BindingTests.cs +++ /dev/null @@ -1,58 +0,0 @@ -// 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.Collections.Specialized; -using System.ComponentModel; -using System.Linq; -using TestLibrary; -using Component.Contracts; - -namespace NetClient -{ - public class BindingTests - { - public static void RunTest() - { - IBindingProjectionsTesting target = (IBindingProjectionsTesting)WinRTNativeComponent.GetObjectFromNativeComponent("Component.Contracts.BindingProjectionsTesting"); - using (target.InitializeXamlFrameworkForCurrentThread()) - { - IBindingViewModel vm = target.CreateViewModel(); - RunINotifyPropertyChangedTest(vm); - RunINotifyCollectionChangedTest(vm); - } - } - - private static void RunINotifyPropertyChangedTest(IBindingViewModel viewModel) - { - bool propertyChangedEventFired = false; - INotifyPropertyChanged notifyPropertyChanged = (INotifyPropertyChanged)viewModel; - PropertyChangedEventHandler handler = (o, e) => propertyChangedEventFired = (e.PropertyName == nameof(viewModel.Name)); - notifyPropertyChanged.PropertyChanged += handler; - viewModel.Name = "New Name"; - Assert.IsTrue(propertyChangedEventFired); - notifyPropertyChanged.PropertyChanged -= handler; - propertyChangedEventFired = false; - viewModel.Name = "Old Name"; - Assert.IsFalse(propertyChangedEventFired); - } - - private static void RunINotifyCollectionChangedTest(IBindingViewModel viewModel) - { - bool notifyCollectionChangedEventFired = false; - int addedElement = 42; - viewModel.Collection.CollectionChanged += (o, e) => - { - notifyCollectionChangedEventFired = - e.Action == NotifyCollectionChangedAction.Add - && e.NewItems.Count == 1 - && e.NewItems[0] is int i - && i == addedElement; - }; - - viewModel.AddElement(addedElement); - - Assert.IsTrue(notifyCollectionChangedEventFired); - } - } -} diff --git a/src/coreclr/tests/src/Interop/WinRT/NETClients/Bindings/NETClientBindings.csproj b/src/coreclr/tests/src/Interop/WinRT/NETClients/Bindings/NETClientBindings.csproj deleted file mode 100644 index 7d18fc6..0000000 --- a/src/coreclr/tests/src/Interop/WinRT/NETClients/Bindings/NETClientBindings.csproj +++ /dev/null @@ -1,22 +0,0 @@ - - - Exe - - true - true - true - - true - - - - - - - - - - - - - diff --git a/src/coreclr/tests/src/Interop/WinRT/NETClients/Primitives/ArrayTests.cs b/src/coreclr/tests/src/Interop/WinRT/NETClients/Primitives/ArrayTests.cs deleted file mode 100644 index a4f24c2..0000000 --- a/src/coreclr/tests/src/Interop/WinRT/NETClients/Primitives/ArrayTests.cs +++ /dev/null @@ -1,34 +0,0 @@ -// 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.Linq; -using TestLibrary; - -namespace NetClient -{ - public class ArrayTests - { - public static void RunTest() - { - Component.Contracts.IArrayTesting target = (Component.Contracts.IArrayTesting)WinRTNativeComponent.GetObjectFromNativeComponent("Component.Contracts.ArrayTesting"); - TestIntArray(target); - TestBoolArray(target); - } - - private static void TestIntArray(Component.Contracts.IArrayTesting target) - { - int[] array = Enumerable.Range(1, 30).ToArray(); - Assert.AreEqual(array.Sum(), target.Sum(array)); - - } - - private static void TestBoolArray(Component.Contracts.IArrayTesting target) - { - bool[] array = new []{ true, false, true, true, true, false, false}; - bool expected = array.Aggregate(false, (left, right) => left ^ right); - - Assert.AreEqual(expected, target.Xor(array)); - } - } -} diff --git a/src/coreclr/tests/src/Interop/WinRT/NETClients/Primitives/BooleanTests.cs b/src/coreclr/tests/src/Interop/WinRT/NETClients/Primitives/BooleanTests.cs deleted file mode 100644 index 479161e..0000000 --- a/src/coreclr/tests/src/Interop/WinRT/NETClients/Primitives/BooleanTests.cs +++ /dev/null @@ -1,17 +0,0 @@ -// 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 TestLibrary; - -namespace NetClient -{ - public class BooleanTests - { - public static void RunTest() - { - Component.Contracts.IBooleanTesting target = (Component.Contracts.IBooleanTesting)WinRTNativeComponent.GetObjectFromNativeComponent("Component.Contracts.BooleanTesting"); - Assert.IsTrue(target.And(true, true)); - Assert.IsFalse(target.And(false, true)); - } - } -} diff --git a/src/coreclr/tests/src/Interop/WinRT/NETClients/Primitives/EnumTests.cs b/src/coreclr/tests/src/Interop/WinRT/NETClients/Primitives/EnumTests.cs deleted file mode 100644 index 3830405..0000000 --- a/src/coreclr/tests/src/Interop/WinRT/NETClients/Primitives/EnumTests.cs +++ /dev/null @@ -1,17 +0,0 @@ -// 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 TestLibrary; - -namespace NetClient -{ - public class EnumTests - { - public static void RunTest() - { - Component.Contracts.IEnumTesting target = (Component.Contracts.IEnumTesting)WinRTNativeComponent.GetObjectFromNativeComponent("Component.Contracts.EnumTesting"); - Assert.AreEqual(Component.Contracts.TestEnum.A, target.GetA()); - Assert.IsTrue(target.IsB(Component.Contracts.TestEnum.B)); - } - } -} diff --git a/src/coreclr/tests/src/Interop/WinRT/NETClients/Primitives/ExceptionTests.cs b/src/coreclr/tests/src/Interop/WinRT/NETClients/Primitives/ExceptionTests.cs deleted file mode 100644 index a26b81f..0000000 --- a/src/coreclr/tests/src/Interop/WinRT/NETClients/Primitives/ExceptionTests.cs +++ /dev/null @@ -1,22 +0,0 @@ -// 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 TestLibrary; - -namespace NetClient -{ - public class ExceptionTests - { - public static void RunTest() - { - Component.Contracts.IExceptionTesting target = (Component.Contracts.IExceptionTesting)WinRTNativeComponent.GetObjectFromNativeComponent("Component.Contracts.ExceptionTesting"); - - Assert.Throws(() => target.ThrowException(new InvalidOperationException())); - - Assert.OfType(target.GetException(new ArgumentOutOfRangeException().HResult)); - Assert.OfType(target.GetException(new ArgumentNullException().HResult)); - Assert.OfType(target.GetException(new NullReferenceException().HResult)); - } - } -} diff --git a/src/coreclr/tests/src/Interop/WinRT/NETClients/Primitives/KeyValuePairTests.cs b/src/coreclr/tests/src/Interop/WinRT/NETClients/Primitives/KeyValuePairTests.cs deleted file mode 100644 index 622771b..0000000 --- a/src/coreclr/tests/src/Interop/WinRT/NETClients/Primitives/KeyValuePairTests.cs +++ /dev/null @@ -1,34 +0,0 @@ -// 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.Generic; -using TestLibrary; - -namespace NetClient -{ - public class KeyValuePairTests - { - public static void RunTest() - { - Component.Contracts.IKeyValuePairTesting target = (Component.Contracts.IKeyValuePairTesting)WinRTNativeComponent.GetObjectFromNativeComponent("Component.Contracts.KeyValuePairTesting"); - TestSimplePair(target); - TestMarshaledPair(target); - } - - private static void TestSimplePair(Component.Contracts.IKeyValuePairTesting target) - { - int key = 5; - int value = 27; - - Assert.AreEqual(new KeyValuePair(key, value), target.MakeSimplePair(key, value)); - } - - private static void TestMarshaledPair(Component.Contracts.IKeyValuePairTesting target) - { - string key = "Key"; - string value = "Value"; - - Assert.AreEqual(new KeyValuePair(key, value), target.MakeMarshaledPair(key, value)); - } - } -} diff --git a/src/coreclr/tests/src/Interop/WinRT/NETClients/Primitives/NETClientPrimitives.csproj b/src/coreclr/tests/src/Interop/WinRT/NETClients/Primitives/NETClientPrimitives.csproj deleted file mode 100644 index 1bd87b6..0000000 --- a/src/coreclr/tests/src/Interop/WinRT/NETClients/Primitives/NETClientPrimitives.csproj +++ /dev/null @@ -1,29 +0,0 @@ - - - Exe - - true - true - - true - - - - - - - - - - - - - - - - - - - - - diff --git a/src/coreclr/tests/src/Interop/WinRT/NETClients/Primitives/NullableTests.cs b/src/coreclr/tests/src/Interop/WinRT/NETClients/Primitives/NullableTests.cs deleted file mode 100644 index ed450c2..0000000 --- a/src/coreclr/tests/src/Interop/WinRT/NETClients/Primitives/NullableTests.cs +++ /dev/null @@ -1,18 +0,0 @@ -// 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 TestLibrary; - -namespace NetClient -{ - public class NullableTests - { - public static void RunTest() - { - Component.Contracts.INullableTesting target = (Component.Contracts.INullableTesting)WinRTNativeComponent.GetObjectFromNativeComponent("Component.Contracts.NullableTesting"); - Assert.IsTrue(target.IsNull(null)); - Assert.IsFalse(target.IsNull(5)); - Assert.AreEqual(5, target.GetIntValue(5)); - } - } -} diff --git a/src/coreclr/tests/src/Interop/WinRT/NETClients/Primitives/Program.cs b/src/coreclr/tests/src/Interop/WinRT/NETClients/Primitives/Program.cs deleted file mode 100644 index bd27361..0000000 --- a/src/coreclr/tests/src/Interop/WinRT/NETClients/Primitives/Program.cs +++ /dev/null @@ -1,38 +0,0 @@ -// 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 NetClient -{ - using System; - - class Program - { - static int Main(string[] args) - { - if (!TestLibrary.Utilities.IsWinRTSupported) - { - return 100; - } - - try - { - BooleanTests.RunTest(); - EnumTests.RunTest(); - StringTests.RunTest(); - NullableTests.RunTest(); - TypeTests.RunTest(); - ExceptionTests.RunTest(); - ArrayTests.RunTest(); - KeyValuePairTests.RunTest(); - UriTests.RunTest(); - } - catch (System.Exception ex) - { - Console.WriteLine(ex); - return 101; - } - return 100; - } - } -} diff --git a/src/coreclr/tests/src/Interop/WinRT/NETClients/Primitives/StringTests.cs b/src/coreclr/tests/src/Interop/WinRT/NETClients/Primitives/StringTests.cs deleted file mode 100644 index 57ce5b0..0000000 --- a/src/coreclr/tests/src/Interop/WinRT/NETClients/Primitives/StringTests.cs +++ /dev/null @@ -1,18 +0,0 @@ -// 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 TestLibrary; - -namespace NetClient -{ - public class StringTests - { - public static void RunTest() - { - Component.Contracts.IStringTesting target = (Component.Contracts.IStringTesting)WinRTNativeComponent.GetObjectFromNativeComponent("Component.Contracts.StringTesting"); - string left = "Hello C++/WinRT"; - string right = " from .NET"; - Assert.AreEqual(string.Concat(left, right), target.ConcatStrings(left, right)); - } - } -} diff --git a/src/coreclr/tests/src/Interop/WinRT/NETClients/Primitives/TypeTests.cs b/src/coreclr/tests/src/Interop/WinRT/NETClients/Primitives/TypeTests.cs deleted file mode 100644 index c2f1364..0000000 --- a/src/coreclr/tests/src/Interop/WinRT/NETClients/Primitives/TypeTests.cs +++ /dev/null @@ -1,25 +0,0 @@ -// 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 TestLibrary; - -namespace NetClient -{ - public class TypeTests - { - public static void RunTest() - { - Component.Contracts.ITypeTesting target = (Component.Contracts.ITypeTesting)WinRTNativeComponent.GetObjectFromNativeComponent("Component.Contracts.TypeTesting"); - - // Non-WinRT managed types pass their assembly-qualified name - Assert.AreEqual(typeof(TypeTests).AssemblyQualifiedName, target.GetTypeName(typeof(TypeTests))); - - // WinRT types pass their full name (not assembly-qualified) - Assert.AreEqual(typeof(Component.Contracts.ITypeTesting).FullName, target.GetTypeName(typeof(Component.Contracts.ITypeTesting))); - - // Projected types pass the name of the type they are projected from - Assert.AreEqual("Windows.UI.Xaml.Interop.TypeName", target.GetTypeName(typeof(Type))); - } - } -} diff --git a/src/coreclr/tests/src/Interop/WinRT/NETClients/Primitives/UriTests.cs b/src/coreclr/tests/src/Interop/WinRT/NETClients/Primitives/UriTests.cs deleted file mode 100644 index 0d319f1..0000000 --- a/src/coreclr/tests/src/Interop/WinRT/NETClients/Primitives/UriTests.cs +++ /dev/null @@ -1,19 +0,0 @@ -// 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 TestLibrary; - -namespace NetClient -{ - public class UriTests - { - public static void RunTest() - { - Component.Contracts.IUriTesting target = (Component.Contracts.IUriTesting)WinRTNativeComponent.GetObjectFromNativeComponent("Component.Contracts.UriTesting"); - Uri managedUri = new Uri("https://dot.net"); - Assert.AreEqual(managedUri.ToString(), target.GetFromUri(managedUri)); - Assert.AreEqual(managedUri, target.CreateUriFromString(managedUri.ToString())); - } - } -} diff --git a/src/coreclr/tests/src/Interop/WinRT/NativeComponent/CMakeLists.txt b/src/coreclr/tests/src/Interop/WinRT/NativeComponent/CMakeLists.txt deleted file mode 100644 index 5ba0d7f..0000000 --- a/src/coreclr/tests/src/Interop/WinRT/NativeComponent/CMakeLists.txt +++ /dev/null @@ -1,114 +0,0 @@ -project (WinRTNativeComponent) -include_directories( ${INC_PLATFORM_DIR} ) -include ("${CLR_INTEROP_TEST_ROOT}/Interop.cmake") -include_directories("../Contracts") -include_directories(${CMAKE_CURRENT_SOURCE_DIR}) - -add_compile_definitions(WINRT_NO_MAKE_DETECTION) - -set(SOURCES - Component.Contracts.ArrayTesting.cpp - Component.Contracts.BindingProjectionsTesting.cpp - Component.Contracts.BindingViewModel.cpp - Component.Contracts.BooleanTesting.cpp - Component.Contracts.EnumTesting.cpp - Component.Contracts.ExceptionTesting.cpp - Component.Contracts.KeyValuePairTesting.cpp - Component.Contracts.NullableTesting.cpp - Component.Contracts.StringTesting.cpp - Component.Contracts.TypeTesting.cpp - Component.Contracts.UriTesting.cpp -) - -set (MIDL_GENERATED_WINMD ${CMAKE_CURRENT_BINARY_DIR}/WinMD/Component.Contracts.winmd) -file(TO_NATIVE_PATH ${MIDL_GENERATED_WINMD} MIDL_GENERATED_WINMD_WINDOWS_PATH) - -if(NOT DEFINED CMAKE_VS_WINDOWS_TARGET_PLATFORM_VERSION OR CMAKE_VS_WINDOWS_TARGET_PLATFORM_VERSION STREQUAL "" ) - message(FATAL_ERROR "Windows SDK is required for the WinRT interop tests build.") -else() - message("Using Windows SDK version ${CMAKE_VS_WINDOWS_TARGET_PLATFORM_VERSION} for WinRT interop tests.") -endif() - -file(TO_CMAKE_PATH "$ENV{WindowsSdkDir}" WINDOWS_KITS_DIR) - -set (METADATA_DIR "${WINDOWS_KITS_DIR}/References/${CMAKE_VS_WINDOWS_TARGET_PLATFORM_VERSION}/windows.foundation.foundationcontract/*" ) -set (REFERENCE_WINMDS - "${WINDOWS_KITS_DIR}/References/${CMAKE_VS_WINDOWS_TARGET_PLATFORM_VERSION}/Windows.Foundation.FoundationContract/*/Windows.Foundation.FoundationContract.winmd" - "${WINDOWS_KITS_DIR}/References/${CMAKE_VS_WINDOWS_TARGET_PLATFORM_VERSION}/Windows.Foundation.UniversalApiContract/*/Windows.Foundation.UniversalApiContract.winmd") - -file(GLOB RESOLVED_METADATA_DIR ${METADATA_DIR}) -file(TO_NATIVE_PATH ${RESOLVED_METADATA_DIR} METADATA_DIR_ARGUMENT) - -file(GLOB_RECURSE RESOLVED_REFERENCE_WINMDS ${REFERENCE_WINMDS}) - -set (REFERENCE_WINMD_ARGS "") -foreach(WINMD ${RESOLVED_REFERENCE_WINMDS}) - file(TO_NATIVE_PATH ${WINMD} WINMD_WINDOWS) - set(WINMD_WINDOWS "${WINMD_WINDOWS}") - string(PREPEND WINMD_WINDOWS "/reference") - list(APPEND REFERENCE_WINMD_ARGS ${WINMD_WINDOWS}) -endforeach() - -set (MIDL_FILE ../Contracts/Component.Contracts.idl) -set (MIDL_COMMAND_LINE_ARGS - /winrt - /metadata_dir ${METADATA_DIR_ARGUMENT} - /W1 - /enum_class - /ns_prefix - /target "NT60" - /nomidl - /h "nul" - ${REFERENCE_WINMD_ARGS} -) - -find_program(MIDLRT midlrt) - -add_custom_command( - OUTPUT ${MIDL_GENERATED_WINMD} - COMMAND ${MIDLRT} ${MIDL_COMMAND_LINE_ARGS} ${MIDL_FILE} /winmd ${MIDL_GENERATED_WINMD_WINDOWS_PATH} - WORKING_DIRECTORY ${CMAKE_CURRENT_SOURCE_DIR} - DEPENDS ${MIDL_FILE} -) - -set_source_files_properties(${MIDL_GENERATED_WINMD} PROPERTIES GENERATED TRUE) - -set (CPP_WINRT_OUTPUT_FOLDER ${CMAKE_CURRENT_BINARY_DIR}/Generated) - -set (CPP_WINRT_OUTPUT_FILES - ${CPP_WINRT_OUTPUT_FOLDER}/winrt/impl/Component.Contracts.0.h - ${CPP_WINRT_OUTPUT_FOLDER}/winrt/impl/Component.Contracts.1.h - ${CPP_WINRT_OUTPUT_FOLDER}/winrt/impl/Component.Contracts.2.h - ${CPP_WINRT_OUTPUT_FOLDER}/winrt/Component.Contracts.h - ${CPP_WINRT_OUTPUT_FOLDER}/module.g.cpp -) - -include_directories(${CPP_WINRT_OUTPUT_FOLDER}) - -find_program(CPPWINRT cppwinrt) - -add_custom_command( - OUTPUT ${CPP_WINRT_OUTPUT_FILES} - COMMAND ${CPPWINRT} -name Contracts -comp ${CMAKE_CURRENT_SOURCE_DIR} -in ${MIDL_GENERATED_WINMD} -ref ${CMAKE_VS_WINDOWS_TARGET_PLATFORM_VERSION} -out ${CPP_WINRT_OUTPUT_FOLDER} - DEPENDS ${MIDL_GENERATED_WINMD} -) - -set_source_files_properties(${CPP_WINRT_OUTPUT_FILES} PROPERTIES GENERATED TRUE) - -list(APPEND SOURCES ${CPP_WINRT_OUTPUT_FOLDER}/module.g.cpp) - -if (CLR_CMAKE_TARGET_WIN32) - list(APPEND SOURCES Exports.def) -endif() - -# add the executable -add_library (WinRTNativeComponent SHARED ${SOURCES}) -target_link_libraries(WinRTNativeComponent ${LINK_LIBRARIES_ADDITIONAL}) -set_target_properties(WinRTNativeComponent PROPERTIES CXX_STANDARD 17) - -if(CLR_CMAKE_TARGET_WIN32) - target_link_libraries(WinRTNativeComponent RuntimeObject.lib) -endif() - -# add the install targets -install (TARGETS WinRTNativeComponent DESTINATION bin) diff --git a/src/coreclr/tests/src/Interop/WinRT/NativeComponent/Component.Contracts.ArrayTesting.cpp b/src/coreclr/tests/src/Interop/WinRT/NativeComponent/Component.Contracts.ArrayTesting.cpp deleted file mode 100644 index 28b3cc8..0000000 --- a/src/coreclr/tests/src/Interop/WinRT/NativeComponent/Component.Contracts.ArrayTesting.cpp +++ /dev/null @@ -1,19 +0,0 @@ -// 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. -#include "pch.h" -#include "Component.Contracts.ArrayTesting.h" -#include - -namespace winrt::Component::Contracts::implementation -{ - int32_t ArrayTesting::Sum(array_view array) - { - return std::accumulate(array.begin(), array.end(), 0); - } - - bool ArrayTesting::Xor(array_view array) - { - return std::accumulate(array.begin(), array.end(), false, [](bool left, bool right) { return left ^ right; }); - } -} diff --git a/src/coreclr/tests/src/Interop/WinRT/NativeComponent/Component.Contracts.ArrayTesting.h b/src/coreclr/tests/src/Interop/WinRT/NativeComponent/Component.Contracts.ArrayTesting.h deleted file mode 100644 index 168022c..0000000 --- a/src/coreclr/tests/src/Interop/WinRT/NativeComponent/Component.Contracts.ArrayTesting.h +++ /dev/null @@ -1,24 +0,0 @@ -// 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. -#pragma once - -#include "Component/Contracts/ArrayTesting.g.h" - -namespace winrt::Component::Contracts::implementation -{ - struct ArrayTesting : ArrayTestingT - { - ArrayTesting() = default; - - int32_t Sum(array_view array); - bool Xor(array_view array); - }; -} - -namespace winrt::Component::Contracts::factory_implementation -{ - struct ArrayTesting : ArrayTestingT - { - }; -} diff --git a/src/coreclr/tests/src/Interop/WinRT/NativeComponent/Component.Contracts.BindingProjectionsTesting.cpp b/src/coreclr/tests/src/Interop/WinRT/NativeComponent/Component.Contracts.BindingProjectionsTesting.cpp deleted file mode 100644 index 3d7688f..0000000 --- a/src/coreclr/tests/src/Interop/WinRT/NativeComponent/Component.Contracts.BindingProjectionsTesting.cpp +++ /dev/null @@ -1,20 +0,0 @@ -// 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. -#include "pch.h" -#include "Component.Contracts.BindingProjectionsTesting.h" -#include "Component.Contracts.BindingViewModel.h" -#include - -namespace winrt::Component::Contracts::implementation -{ - Component::Contracts::IBindingViewModel BindingProjectionsTesting::CreateViewModel() - { - return make(); - } - - Windows::Foundation::IClosable BindingProjectionsTesting::InitializeXamlFrameworkForCurrentThread() - { - return Windows::UI::Xaml::Hosting::WindowsXamlManager::InitializeForCurrentThread(); - } -} diff --git a/src/coreclr/tests/src/Interop/WinRT/NativeComponent/Component.Contracts.BindingProjectionsTesting.h b/src/coreclr/tests/src/Interop/WinRT/NativeComponent/Component.Contracts.BindingProjectionsTesting.h deleted file mode 100644 index aeae54f..0000000 --- a/src/coreclr/tests/src/Interop/WinRT/NativeComponent/Component.Contracts.BindingProjectionsTesting.h +++ /dev/null @@ -1,25 +0,0 @@ -// 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. -#pragma once - -#include "Component/Contracts/BindingProjectionsTesting.g.h" - -namespace winrt::Component::Contracts::implementation -{ - struct BindingProjectionsTesting : BindingProjectionsTestingT - { - BindingProjectionsTesting() = default; - - Component::Contracts::IBindingViewModel CreateViewModel(); - - Windows::Foundation::IClosable InitializeXamlFrameworkForCurrentThread(); - }; -} - -namespace winrt::Component::Contracts::factory_implementation -{ - struct BindingProjectionsTesting : BindingProjectionsTestingT - { - }; -} diff --git a/src/coreclr/tests/src/Interop/WinRT/NativeComponent/Component.Contracts.BindingViewModel.cpp b/src/coreclr/tests/src/Interop/WinRT/NativeComponent/Component.Contracts.BindingViewModel.cpp deleted file mode 100644 index f4eb514..0000000 --- a/src/coreclr/tests/src/Interop/WinRT/NativeComponent/Component.Contracts.BindingViewModel.cpp +++ /dev/null @@ -1,40 +0,0 @@ -// 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. -#include "pch.h" -#include "Component.Contracts.BindingViewModel.h" -#include - -namespace winrt::Component::Contracts::implementation -{ - Windows::UI::Xaml::Interop::INotifyCollectionChanged BindingViewModel::Collection() - { - return m_collection; - } - - void BindingViewModel::AddElement(int32_t i) - { - m_collection.push_back(i); - } - - hstring BindingViewModel::Name() - { - return m_name; - } - - void BindingViewModel::Name(hstring const& value) - { - m_name = value; - m_propertyChangedEvent(*this, Windows::UI::Xaml::Data::PropertyChangedEventArgs(hstring(W("Name")))); - } - - winrt::event_token BindingViewModel::PropertyChanged(Windows::UI::Xaml::Data::PropertyChangedEventHandler const& handler) - { - return m_propertyChangedEvent.add(handler); - } - - void BindingViewModel::PropertyChanged(winrt::event_token const& token) noexcept - { - m_propertyChangedEvent.remove(token); - } -} diff --git a/src/coreclr/tests/src/Interop/WinRT/NativeComponent/Component.Contracts.BindingViewModel.h b/src/coreclr/tests/src/Interop/WinRT/NativeComponent/Component.Contracts.BindingViewModel.h deleted file mode 100644 index 95b1853..0000000 --- a/src/coreclr/tests/src/Interop/WinRT/NativeComponent/Component.Contracts.BindingViewModel.h +++ /dev/null @@ -1,163 +0,0 @@ -// 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. -#pragma once - -#include "Component/Contracts/BindingViewModel.g.h" -#include "winrt/Windows.Foundation.Collections.h" -#include "winrt/Windows.UI.Xaml.Interop.h" -#include - -template -struct BindableIteratorWrapper : winrt::implements, winrt::Windows::UI::Xaml::Interop::IBindableIterator> -{ - BindableIteratorWrapper(winrt::Windows::Foundation::Collections::IIterator&& iterator) - :m_iterator(std::move(iterator)) - {} - - winrt::Windows::Foundation::IInspectable Current() - { - return winrt::box_value(m_iterator.Current()); - } - - bool HasCurrent() - { - return m_iterator.HasCurrent(); - } - - bool MoveNext() - { - return m_iterator.MoveNext(); - } - -private: - winrt::Windows::Foundation::Collections::IIterator m_iterator; -}; - -template -struct BindableVectorWrapper : winrt::implements, winrt::Windows::UI::Xaml::Interop::IBindableVector> -{ - BindableVectorWrapper(winrt::Windows::Foundation::Collections::IVector&& elements) - :m_elements(std::move(elements)) - { - } - - winrt::Windows::UI::Xaml::Interop::IBindableIterator First() - { - return winrt::make>(m_elements.First()); - } - - uint32_t Size() - { - return m_elements.Size(); - } - - void Append(winrt::Windows::Foundation::IInspectable const& value) - { - m_elements.Append(winrt::unbox_value(value)); - } - - void Clear() - { - m_elements.Clear(); - } - - winrt::Windows::Foundation::IInspectable GetAt(uint32_t index) - { - return winrt::box_value(m_elements.GetAt(index)); - } - - winrt::Windows::UI::Xaml::Interop::IBindableVectorView GetView() - { - throw winrt::hresult_not_implemented(); - } - - bool IndexOf(winrt::Windows::Foundation::IInspectable const& value, uint32_t& index) - { - return m_elements.IndexOf(winrt::unbox_value(value), index); - } - - void InsertAt(uint32_t index, winrt::Windows::Foundation::IInspectable const& value) - { - m_elements.InsertAt(index, winrt::unbox_value(value)); - } - - void RemoveAt(uint32_t index) - { - m_elements.RemoveAt(index); - } - - void RemoveAtEnd() - { - m_elements.RemoveAtEnd(); - } - - void SetAt(uint32_t index, winrt::Windows::Foundation::IInspectable const& value) - { - m_elements.SetAt(index, winrt::unbox_value(value)); - } -private: - winrt::Windows::Foundation::Collections::IVector m_elements; -}; - -template> -struct ObservableCollection : winrt::implements, winrt::Windows::UI::Xaml::Interop::INotifyCollectionChanged> -{ - ObservableCollection() = default; - - winrt::event_token CollectionChanged(winrt::Windows::UI::Xaml::Interop::NotifyCollectionChangedEventHandler const& handler) - { - return m_CollectionChangedEvent.add(handler); - } - - void CollectionChanged(winrt::event_token const& token) noexcept - { - m_CollectionChangedEvent.remove(token); - } - - void push_back(const T& value) - { - m_elements.push_back(value); - - winrt::Windows::UI::Xaml::Interop::NotifyCollectionChangedEventArgs args( - winrt::Windows::UI::Xaml::Interop::NotifyCollectionChangedAction::Add, - winrt::make>(winrt::single_threaded_vector(std::vector{value})), - nullptr, - (int32_t)(m_elements.size() - 1), - -1 - ); - m_CollectionChangedEvent(*this, args); - } - -private: - Container m_elements; - winrt::event m_CollectionChangedEvent; -}; - - -namespace winrt::Component::Contracts::implementation -{ - struct BindingViewModel : BindingViewModelT - { - BindingViewModel() = default; - - Windows::UI::Xaml::Interop::INotifyCollectionChanged Collection(); - void AddElement(int32_t i); - hstring Name(); - void Name(hstring const& value); - winrt::event_token PropertyChanged(Windows::UI::Xaml::Data::PropertyChangedEventHandler const& handler); - void PropertyChanged(winrt::event_token const& token) noexcept; - - private: - hstring m_name; - winrt::event m_propertyChangedEvent; - ObservableCollection m_collection; - }; -} - -namespace winrt::Component::Contracts::factory_implementation -{ - struct BindingViewModel : BindingViewModelT - { - }; -} diff --git a/src/coreclr/tests/src/Interop/WinRT/NativeComponent/Component.Contracts.BooleanTesting.cpp b/src/coreclr/tests/src/Interop/WinRT/NativeComponent/Component.Contracts.BooleanTesting.cpp deleted file mode 100644 index 2abf2a2..0000000 --- a/src/coreclr/tests/src/Interop/WinRT/NativeComponent/Component.Contracts.BooleanTesting.cpp +++ /dev/null @@ -1,13 +0,0 @@ -// 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. -#include "pch.h" -#include "Component.Contracts.BooleanTesting.h" - -namespace winrt::Component::Contracts::implementation -{ - bool BooleanTesting::And(bool left, bool right) - { - return left && right; - } -} diff --git a/src/coreclr/tests/src/Interop/WinRT/NativeComponent/Component.Contracts.BooleanTesting.h b/src/coreclr/tests/src/Interop/WinRT/NativeComponent/Component.Contracts.BooleanTesting.h deleted file mode 100644 index b1054f9..0000000 --- a/src/coreclr/tests/src/Interop/WinRT/NativeComponent/Component.Contracts.BooleanTesting.h +++ /dev/null @@ -1,23 +0,0 @@ -// 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. -#pragma once - -#include "Component/Contracts/BooleanTesting.g.h" - -namespace winrt::Component::Contracts::implementation -{ - struct BooleanTesting : BooleanTestingT - { - BooleanTesting() = default; - - bool And(bool left, bool right); - }; -} - -namespace winrt::Component::Contracts::factory_implementation -{ - struct BooleanTesting : BooleanTestingT - { - }; -} diff --git a/src/coreclr/tests/src/Interop/WinRT/NativeComponent/Component.Contracts.EnumTesting.cpp b/src/coreclr/tests/src/Interop/WinRT/NativeComponent/Component.Contracts.EnumTesting.cpp deleted file mode 100644 index 825d56a..0000000 --- a/src/coreclr/tests/src/Interop/WinRT/NativeComponent/Component.Contracts.EnumTesting.cpp +++ /dev/null @@ -1,15 +0,0 @@ -#include "pch.h" -#include "Component.Contracts.EnumTesting.h" - -namespace winrt::Component::Contracts::implementation -{ - Component::Contracts::TestEnum EnumTesting::GetA() - { - return TestEnum::A; - } - - bool EnumTesting::IsB(Component::Contracts::TestEnum const& val) - { - return val == TestEnum::B; - } -} diff --git a/src/coreclr/tests/src/Interop/WinRT/NativeComponent/Component.Contracts.EnumTesting.h b/src/coreclr/tests/src/Interop/WinRT/NativeComponent/Component.Contracts.EnumTesting.h deleted file mode 100644 index 7bf886d..0000000 --- a/src/coreclr/tests/src/Interop/WinRT/NativeComponent/Component.Contracts.EnumTesting.h +++ /dev/null @@ -1,21 +0,0 @@ -#pragma once - -#include "Component/Contracts/EnumTesting.g.h" - -namespace winrt::Component::Contracts::implementation -{ - struct EnumTesting : EnumTestingT - { - EnumTesting() = default; - - Component::Contracts::TestEnum GetA(); - bool IsB(Component::Contracts::TestEnum const& val); - }; -} - -namespace winrt::Component::Contracts::factory_implementation -{ - struct EnumTesting : EnumTestingT - { - }; -} diff --git a/src/coreclr/tests/src/Interop/WinRT/NativeComponent/Component.Contracts.ExceptionTesting.cpp b/src/coreclr/tests/src/Interop/WinRT/NativeComponent/Component.Contracts.ExceptionTesting.cpp deleted file mode 100644 index 0b0cfb2..0000000 --- a/src/coreclr/tests/src/Interop/WinRT/NativeComponent/Component.Contracts.ExceptionTesting.cpp +++ /dev/null @@ -1,18 +0,0 @@ -// 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. -#include "pch.h" -#include "Component.Contracts.ExceptionTesting.h" - -namespace winrt::Component::Contracts::implementation -{ - void ExceptionTesting::ThrowException(winrt::hresult const& hr) - { - winrt::throw_hresult(hr); - } - - winrt::hresult ExceptionTesting::GetException(int32_t hr) - { - return {hr}; - } -} diff --git a/src/coreclr/tests/src/Interop/WinRT/NativeComponent/Component.Contracts.ExceptionTesting.h b/src/coreclr/tests/src/Interop/WinRT/NativeComponent/Component.Contracts.ExceptionTesting.h deleted file mode 100644 index 3254cb0..0000000 --- a/src/coreclr/tests/src/Interop/WinRT/NativeComponent/Component.Contracts.ExceptionTesting.h +++ /dev/null @@ -1,24 +0,0 @@ -// 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. -#pragma once - -#include "Component/Contracts/ExceptionTesting.g.h" - -namespace winrt::Component::Contracts::implementation -{ - struct ExceptionTesting : ExceptionTestingT - { - ExceptionTesting() = default; - - void ThrowException(winrt::hresult const& hr); - winrt::hresult GetException(int32_t hr); - }; -} - -namespace winrt::Component::Contracts::factory_implementation -{ - struct ExceptionTesting : ExceptionTestingT - { - }; -} diff --git a/src/coreclr/tests/src/Interop/WinRT/NativeComponent/Component.Contracts.KeyValuePairTesting.cpp b/src/coreclr/tests/src/Interop/WinRT/NativeComponent/Component.Contracts.KeyValuePairTesting.cpp deleted file mode 100644 index c7cc5c3..0000000 --- a/src/coreclr/tests/src/Interop/WinRT/NativeComponent/Component.Contracts.KeyValuePairTesting.cpp +++ /dev/null @@ -1,49 +0,0 @@ -// 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. -#include "pch.h" -#include "Component.Contracts.KeyValuePairTesting.h" -#include "winrt/Windows.Foundation.Collections.h" -#include -#include - -template -struct pair_wrapper : winrt::implements, winrt::Windows::Foundation::Collections::IKeyValuePair> -{ - pair_wrapper(const K& key, const V& value) - :key{ key }, - value{ value } - {} - - K Key() - { - return key; - } - - V Value() - { - return value; - } - -private: - K key; - V value; -}; - -namespace winrt::Component::Contracts::implementation -{ - Windows::Foundation::Collections::IKeyValuePair KeyValuePairTesting::MakeSimplePair(int32_t key, int32_t value) - { - return make>(key, value); - } - - Windows::Foundation::Collections::IKeyValuePair KeyValuePairTesting::MakeMarshaledPair(hstring const& key, hstring const& value) - { - return make>(key, value); - } - - Windows::Foundation::Collections::IKeyValuePair> KeyValuePairTesting::MakeProjectedPair(int32_t key, array_view values) - { - return pair_wrapper>{key, winrt::single_threaded_vector(std::vector(values.begin(), values.end()))}; - } -} diff --git a/src/coreclr/tests/src/Interop/WinRT/NativeComponent/Component.Contracts.KeyValuePairTesting.h b/src/coreclr/tests/src/Interop/WinRT/NativeComponent/Component.Contracts.KeyValuePairTesting.h deleted file mode 100644 index 820bdfc..0000000 --- a/src/coreclr/tests/src/Interop/WinRT/NativeComponent/Component.Contracts.KeyValuePairTesting.h +++ /dev/null @@ -1,25 +0,0 @@ -// 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. -#pragma once - -#include "Component/Contracts/KeyValuePairTesting.g.h" - -namespace winrt::Component::Contracts::implementation -{ - struct KeyValuePairTesting : KeyValuePairTestingT - { - KeyValuePairTesting() = default; - - Windows::Foundation::Collections::IKeyValuePair MakeSimplePair(int32_t key, int32_t value); - Windows::Foundation::Collections::IKeyValuePair MakeMarshaledPair(hstring const& key, hstring const& value); - Windows::Foundation::Collections::IKeyValuePair> MakeProjectedPair(int32_t key, array_view values); - }; -} - -namespace winrt::Component::Contracts::factory_implementation -{ - struct KeyValuePairTesting : KeyValuePairTestingT - { - }; -} diff --git a/src/coreclr/tests/src/Interop/WinRT/NativeComponent/Component.Contracts.NullableTesting.cpp b/src/coreclr/tests/src/Interop/WinRT/NativeComponent/Component.Contracts.NullableTesting.cpp deleted file mode 100644 index 55d284e..0000000 --- a/src/coreclr/tests/src/Interop/WinRT/NativeComponent/Component.Contracts.NullableTesting.cpp +++ /dev/null @@ -1,20 +0,0 @@ -// 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. -#include "pch.h" -#include "Component.Contracts.NullableTesting.h" -#include "winrt/Windows.Foundation.h" - - -namespace winrt::Component::Contracts::implementation -{ - bool NullableTesting::IsNull(Windows::Foundation::IReference const& value) - { - return value == nullptr; - } - - int32_t NullableTesting::GetIntValue(Windows::Foundation::IReference const& value) - { - return winrt::unbox_value(value); - } -} diff --git a/src/coreclr/tests/src/Interop/WinRT/NativeComponent/Component.Contracts.NullableTesting.h b/src/coreclr/tests/src/Interop/WinRT/NativeComponent/Component.Contracts.NullableTesting.h deleted file mode 100644 index 4701955..0000000 --- a/src/coreclr/tests/src/Interop/WinRT/NativeComponent/Component.Contracts.NullableTesting.h +++ /dev/null @@ -1,24 +0,0 @@ -// 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. -#pragma once - -#include "Component/Contracts/NullableTesting.g.h" - -namespace winrt::Component::Contracts::implementation -{ - struct NullableTesting : NullableTestingT - { - NullableTesting() = default; - - bool IsNull(Windows::Foundation::IReference const& value); - int32_t GetIntValue(Windows::Foundation::IReference const& value); - }; -} - -namespace winrt::Component::Contracts::factory_implementation -{ - struct NullableTesting : NullableTestingT - { - }; -} diff --git a/src/coreclr/tests/src/Interop/WinRT/NativeComponent/Component.Contracts.StringTesting.cpp b/src/coreclr/tests/src/Interop/WinRT/NativeComponent/Component.Contracts.StringTesting.cpp deleted file mode 100644 index edbb719..0000000 --- a/src/coreclr/tests/src/Interop/WinRT/NativeComponent/Component.Contracts.StringTesting.cpp +++ /dev/null @@ -1,13 +0,0 @@ -// 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. -#include "pch.h" -#include "Component.Contracts.StringTesting.h" - -namespace winrt::Component::Contracts::implementation -{ - hstring StringTesting::ConcatStrings(hstring const& left, hstring const& right) - { - return left + right; - } -} diff --git a/src/coreclr/tests/src/Interop/WinRT/NativeComponent/Component.Contracts.StringTesting.h b/src/coreclr/tests/src/Interop/WinRT/NativeComponent/Component.Contracts.StringTesting.h deleted file mode 100644 index 10c0967..0000000 --- a/src/coreclr/tests/src/Interop/WinRT/NativeComponent/Component.Contracts.StringTesting.h +++ /dev/null @@ -1,23 +0,0 @@ -// 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. -#pragma once - -#include "Component/Contracts/StringTesting.g.h" - -namespace winrt::Component::Contracts::implementation -{ - struct StringTesting : StringTestingT - { - StringTesting() = default; - - hstring ConcatStrings(hstring const& left, hstring const& right); - }; -} - -namespace winrt::Component::Contracts::factory_implementation -{ - struct StringTesting : StringTestingT - { - }; -} diff --git a/src/coreclr/tests/src/Interop/WinRT/NativeComponent/Component.Contracts.TypeTesting.cpp b/src/coreclr/tests/src/Interop/WinRT/NativeComponent/Component.Contracts.TypeTesting.cpp deleted file mode 100644 index 70972a3..0000000 --- a/src/coreclr/tests/src/Interop/WinRT/NativeComponent/Component.Contracts.TypeTesting.cpp +++ /dev/null @@ -1,13 +0,0 @@ -// 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. -#include "pch.h" -#include "Component.Contracts.TypeTesting.h" - -namespace winrt::Component::Contracts::implementation -{ - hstring TypeTesting::GetTypeName(Windows::UI::Xaml::Interop::TypeName const& typeName) - { - return typeName.Name; - } -} diff --git a/src/coreclr/tests/src/Interop/WinRT/NativeComponent/Component.Contracts.TypeTesting.h b/src/coreclr/tests/src/Interop/WinRT/NativeComponent/Component.Contracts.TypeTesting.h deleted file mode 100644 index 896183a..0000000 --- a/src/coreclr/tests/src/Interop/WinRT/NativeComponent/Component.Contracts.TypeTesting.h +++ /dev/null @@ -1,23 +0,0 @@ -// 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. -#pragma once - -#include "Component/Contracts/TypeTesting.g.h" - -namespace winrt::Component::Contracts::implementation -{ - struct TypeTesting : TypeTestingT - { - TypeTesting() = default; - - hstring GetTypeName(Windows::UI::Xaml::Interop::TypeName const& typeName); - }; -} - -namespace winrt::Component::Contracts::factory_implementation -{ - struct TypeTesting : TypeTestingT - { - }; -} diff --git a/src/coreclr/tests/src/Interop/WinRT/NativeComponent/Component.Contracts.UriTesting.cpp b/src/coreclr/tests/src/Interop/WinRT/NativeComponent/Component.Contracts.UriTesting.cpp deleted file mode 100644 index c295b64..0000000 --- a/src/coreclr/tests/src/Interop/WinRT/NativeComponent/Component.Contracts.UriTesting.cpp +++ /dev/null @@ -1,19 +0,0 @@ -// 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. -#include "pch.h" -#include "Component.Contracts.UriTesting.h" -#include "winrt/Windows.Foundation.h" - -namespace winrt::Component::Contracts::implementation -{ - hstring UriTesting::GetFromUri(Windows::Foundation::Uri const& uri) - { - return uri.ToString(); - } - - Windows::Foundation::Uri UriTesting::CreateUriFromString(hstring const& uri) - { - return {uri}; - } -} diff --git a/src/coreclr/tests/src/Interop/WinRT/NativeComponent/Component.Contracts.UriTesting.h b/src/coreclr/tests/src/Interop/WinRT/NativeComponent/Component.Contracts.UriTesting.h deleted file mode 100644 index dcf5ad8..0000000 --- a/src/coreclr/tests/src/Interop/WinRT/NativeComponent/Component.Contracts.UriTesting.h +++ /dev/null @@ -1,24 +0,0 @@ -// 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. -#pragma once - -#include "Component/Contracts/UriTesting.g.h" - -namespace winrt::Component::Contracts::implementation -{ - struct UriTesting : UriTestingT - { - UriTesting() = default; - - hstring GetFromUri(Windows::Foundation::Uri const& uri); - Windows::Foundation::Uri CreateUriFromString(hstring const& uri); - }; -} - -namespace winrt::Component::Contracts::factory_implementation -{ - struct UriTesting : UriTestingT - { - }; -} diff --git a/src/coreclr/tests/src/Interop/WinRT/NativeComponent/Exports.def b/src/coreclr/tests/src/Interop/WinRT/NativeComponent/Exports.def deleted file mode 100644 index 6e3d53b..0000000 --- a/src/coreclr/tests/src/Interop/WinRT/NativeComponent/Exports.def +++ /dev/null @@ -1,3 +0,0 @@ -EXPORTS - DllCanUnloadNow = WINRT_CanUnloadNow PRIVATE - DllGetActivationFactory = WINRT_GetActivationFactory PRIVATE diff --git a/src/coreclr/tests/src/Interop/WinRT/NativeComponent/pch.h b/src/coreclr/tests/src/Interop/WinRT/NativeComponent/pch.h deleted file mode 100644 index ebe6de1..0000000 --- a/src/coreclr/tests/src/Interop/WinRT/NativeComponent/pch.h +++ /dev/null @@ -1,10 +0,0 @@ -// 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. - -// The cppwinrt tool expects there to be a pch.h file in an include-directory that includes -// winrt/base.h. -#ifndef PCH_H -#define PCH_H -#include -#endif diff --git a/src/coreclr/tests/src/Interop/WinRT/NETClients/Bindings/Program.cs b/src/coreclr/tests/src/Interop/WinRT/Program.cs similarity index 52% rename from src/coreclr/tests/src/Interop/WinRT/NETClients/Bindings/Program.cs rename to src/coreclr/tests/src/Interop/WinRT/Program.cs index 5795195..c76afb5 100644 --- a/src/coreclr/tests/src/Interop/WinRT/NETClients/Bindings/Program.cs +++ b/src/coreclr/tests/src/Interop/WinRT/Program.cs @@ -2,23 +2,26 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -namespace NetClient +using System; +using System.Runtime.CompilerServices; +using System.Runtime.InteropServices.WindowsRuntime; +using TestLibrary; + +namespace WinRT { - using System; + [WindowsRuntimeImport] + interface I {} class Program { - static int Main(string[] args) - { - if (!TestLibrary.Utilities.IsWinRTSupported || !TestLibrary.Utilities.IsWindows10Version1809OrGreater) - { - Console.WriteLine("XAML Islands are unsupported on this platform."); - return 100; - } + [MethodImpl(MethodImplOptions.NoInlining)] + private static bool ObjectIsI(object o) => o is I; + public static int Main(string[] args) + { try { - BindingTests.RunTest(); + Assert.Throws(() => ObjectIsI(new object())); } catch (System.Exception ex) { @@ -29,3 +32,4 @@ namespace NetClient } } } + diff --git a/src/coreclr/tests/src/Interop/WinRT/WinRT.csproj b/src/coreclr/tests/src/Interop/WinRT/WinRT.csproj new file mode 100644 index 0000000..676e6bc --- /dev/null +++ b/src/coreclr/tests/src/Interop/WinRT/WinRT.csproj @@ -0,0 +1,13 @@ + + + Exe + true + + true + true + + + + + + diff --git a/src/coreclr/tests/src/Interop/WinRT/Contracts/WindowsRuntimeImportAttribute.cs b/src/coreclr/tests/src/Interop/WinRT/WindowsRuntimeImportAttribute.cs similarity index 100% rename from src/coreclr/tests/src/Interop/WinRT/Contracts/WindowsRuntimeImportAttribute.cs rename to src/coreclr/tests/src/Interop/WinRT/WindowsRuntimeImportAttribute.cs diff --git a/src/installer/corehost/build.proj b/src/installer/corehost/build.proj index 79f4c0a..4a475a4 100644 --- a/src/installer/corehost/build.proj +++ b/src/installer/corehost/build.proj @@ -64,9 +64,6 @@ .NET IJW Host - - .NET WinRT Host - .NET Component Host diff --git a/src/installer/corehost/cli/CMakeLists.txt b/src/installer/corehost/cli/CMakeLists.txt index 3c1bdb1..022aba4 100644 --- a/src/installer/corehost/cli/CMakeLists.txt +++ b/src/installer/corehost/cli/CMakeLists.txt @@ -11,5 +11,4 @@ add_subdirectory(test) if(CLR_CMAKE_TARGET_WIN32) add_subdirectory(comhost) add_subdirectory(ijwhost) - add_subdirectory(winrthost) endif() diff --git a/src/installer/corehost/cli/hostpolicy/hostpolicy.cpp b/src/installer/corehost/cli/hostpolicy/hostpolicy.cpp index c2a933e..0fcb98c 100644 --- a/src/installer/corehost/cli/hostpolicy/hostpolicy.cpp +++ b/src/installer/corehost/cli/hostpolicy/hostpolicy.cpp @@ -477,11 +477,7 @@ namespace "LoadInMemoryAssembly", delegate); case coreclr_delegate_type::winrt_activation: - return coreclr->create_delegate( - "System.Private.CoreLib", - "Internal.Runtime.InteropServices.WindowsRuntime.ActivationFactoryLoader", - "GetActivationFactory", - delegate); + return StatusCode::InvalidArgFailure; case coreclr_delegate_type::com_register: return coreclr->create_delegate( "System.Private.CoreLib", diff --git a/src/installer/corehost/cli/winrthost/CMakeLists.txt b/src/installer/corehost/cli/winrthost/CMakeLists.txt deleted file mode 100644 index 22b32e9..0000000 --- a/src/installer/corehost/cli/winrthost/CMakeLists.txt +++ /dev/null @@ -1,35 +0,0 @@ -# Copyright (c) .NET Foundation and contributors. All rights reserved. -# Licensed under the MIT license. See LICENSE file in the project root for full license information. - -project(winrthost) - -set(DOTNET_PROJECT_NAME "winrthost") - -# Include directories -include_directories(../fxr) - -# CMake does not recommend using globbing since it messes with the freshness checks - -set (SOURCES - winrthost.cpp - ../redirected_error_writer.cpp - ../fxr_resolver.cpp -) - -if(CLR_CMAKE_TARGET_WIN32) - list(APPEND SOURCES - Exports.def) -endif() - -include(../lib.cmake) - -add_definitions(-DFEATURE_LIBHOST=1) - -# Specify non-default Windows libs to be used for Arm/Arm64 builds -if (CLR_CMAKE_TARGET_WIN32 AND (CLR_CMAKE_TARGET_ARCH_ARM OR CLR_CMAKE_TARGET_ARCH_ARM64)) - target_link_libraries(winrthost Advapi32.lib Ole32.lib OleAut32.lib) -endif() - -target_link_libraries(winrthost RuntimeObject.lib libhostcommon) - -install_with_stripped_symbols(winrthost TARGETS corehost) diff --git a/src/installer/corehost/cli/winrthost/Exports.def b/src/installer/corehost/cli/winrthost/Exports.def deleted file mode 100644 index f82e6db..0000000 --- a/src/installer/corehost/cli/winrthost/Exports.def +++ /dev/null @@ -1,3 +0,0 @@ -EXPORTS - DllGetActivationFactory PRIVATE - DllCanUnloadNow PRIVATE diff --git a/src/installer/corehost/cli/winrthost/winrthost.cpp b/src/installer/corehost/cli/winrthost/winrthost.cpp deleted file mode 100644 index 7f67bfd..0000000 --- a/src/installer/corehost/cli/winrthost/winrthost.cpp +++ /dev/null @@ -1,84 +0,0 @@ -// 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. - -#include "redirected_error_writer.h" -#include "hostfxr.h" -#include "fxr_resolver.h" -#include "pal.h" -#include "trace.h" -#include "error_codes.h" -#include "utils.h" -#include -#include -#include - - -#if defined(_WIN32) - -// WinRT entry points are defined without the __declspec(dllexport) attribute. -// The issue here is that the compiler will throw an error regarding linkage -// redefinion. The solution here is to the use a .def file on Windows. -#define WINRT_API extern "C" - -#else - -#define WINRT_API SHARED_API - -#endif // _WIN32 - -using winrt_activation_fn = pal::hresult_t(STDMETHODCALLTYPE*)(const pal::char_t* appPath, HSTRING activatableClassId, IActivationFactory** factory); - -namespace -{ - int get_winrt_activation_delegate(pal::string_t* app_path, winrt_activation_fn *delegate) - { - return load_fxr_and_get_delegate( - hostfxr_delegate_type::hdt_winrt_activation, - [app_path](const pal::string_t& host_path, pal::string_t* config_path_out) - { - // Change the extension to get the 'app' and config - size_t idx = host_path.rfind(_X(".dll")); - assert(idx != pal::string_t::npos); - - pal::string_t app_path_local{ host_path }; - app_path_local.replace(app_path_local.begin() + idx, app_path_local.end(), _X(".winmd")); - *app_path = std::move(app_path_local); - - pal::string_t config_path_local { host_path }; - config_path_local.replace(config_path_local.begin() + idx, config_path_local.end(), _X(".runtimeconfig.json")); - *config_path_out = std::move(config_path_local); - - return StatusCode::Success; - }, - delegate - ); - } -} - - -WINRT_API HRESULT STDMETHODCALLTYPE DllGetActivationFactory(_In_ HSTRING activatableClassId, _Out_ IActivationFactory** factory) -{ - HRESULT hr; - pal::string_t app_path; - winrt_activation_fn activator; - { - trace::setup(); - reset_redirected_error_writer(); - error_writer_scope_t writer_scope(redirected_error_writer); - - int ec = get_winrt_activation_delegate(&app_path, &activator); - if (ec != StatusCode::Success) - { - RoOriginateErrorW(__HRESULT_FROM_WIN32(ec), 0 /* message is null-terminated */, get_redirected_error_string().c_str()); - return __HRESULT_FROM_WIN32(ec); - } - } - - return activator(app_path.c_str(), activatableClassId, factory); -} - -WINRT_API HRESULT STDMETHODCALLTYPE DllCanUnloadNow(void) -{ - return S_FALSE; -} diff --git a/src/installer/pkg/projects/Directory.Build.targets b/src/installer/pkg/projects/Directory.Build.targets index cfe8c64..c34fe88 100644 --- a/src/installer/pkg/projects/Directory.Build.targets +++ b/src/installer/pkg/projects/Directory.Build.targets @@ -16,10 +16,10 @@ - @@ -364,8 +364,6 @@ - - - <_winmdPackageDir>$(NuGetPackageRoot)$(MicrosoftTargetingPackPrivateWinRTPackage.ToLowerInvariant())/$(MicrosoftTargetingPackPrivateWinRTVersion)/ <_diaSymReaderPackageDir>$(NuGetPackageRoot)microsoft.diasymreader.native/$(MicrosoftDiaSymReaderNativeVersion)/ @@ -24,21 +23,12 @@ <_crossDir Condition="'$(_crossHostArch)' != ''">/$(_crossHostArch)_$(TargetArchitecture) - - - <_requiredProperty Include="_winmdPackageDir" /> - - - - - - <_windowsWinMD Include="$(_winmdPackageDir)**/Windows.winmd" /> <_diaSymReaderAssembly Include="$(_diaSymReaderPackageDir)**\Microsoft.DiaSymReader.Native.*.dll" /> @@ -56,10 +46,6 @@ <_jitPath>$([MSBuild]::NormalizePath('$(CoreCLRArtifactsPath)', '$(CoreCLRCrossTargetComponentDirName)', 'sharedFramework', '$(LibraryFilePrefix)clrjit$(LibraryFileExtension)')) - - <_windowsWinMDDirectory>%(_windowsWinMD.RootDir)%(_windowsWinMD.Directory) - - <_diaSymReaderToolDir>%(_diaSymReaderAssembly.RootDir)%(_diaSymReaderAssembly.Directory) @@ -72,10 +58,6 @@ <_diaSymReaderToolDir>$(IntermediateOutputPath) - - - - @@ -1630,11 +1622,6 @@ - - - - - Common\Interop\Unix\Interop.Errors.cs diff --git a/src/libraries/System.Private.CoreLib/src/System/Reflection/EventInfo.cs b/src/libraries/System.Private.CoreLib/src/System/Reflection/EventInfo.cs index 43cefea..84ba268 100644 --- a/src/libraries/System.Private.CoreLib/src/System/Reflection/EventInfo.cs +++ b/src/libraries/System.Private.CoreLib/src/System/Reflection/EventInfo.cs @@ -5,10 +5,6 @@ using System.Diagnostics; using System.Runtime.CompilerServices; -#if FEATURE_COMINTEROP -using EventRegistrationToken = System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken; -#endif //#if FEATURE_COMINTEROP - namespace System.Reflection { public abstract class EventInfo : MemberInfo @@ -71,11 +67,6 @@ namespace System.Reflection if (addMethod == null) throw new InvalidOperationException(SR.InvalidOperation_NoPublicAddMethod); -#if FEATURE_COMINTEROP - if (addMethod.ReturnType == typeof(EventRegistrationToken)) - throw new InvalidOperationException(SR.InvalidOperation_NotSupportedOnWinRTEvent); -#endif //#if FEATURE_COMINTEROP - addMethod.Invoke(target, new object?[] { handler }); } @@ -88,12 +79,6 @@ namespace System.Reflection if (removeMethod == null) throw new InvalidOperationException(SR.InvalidOperation_NoPublicRemoveMethod); -#if FEATURE_COMINTEROP - ParameterInfo[] parameters = removeMethod.GetParametersNoCopy(); - if (parameters[0].ParameterType == typeof(EventRegistrationToken)) - throw new InvalidOperationException(SR.InvalidOperation_NotSupportedOnWinRTEvent); -#endif //#if FEATURE_COMINTEROP - removeMethod.Invoke(target, new object?[] { handler }); } diff --git a/src/libraries/System.Private.CoreLib/src/System/Resources/ResourceManager.Uap.cs b/src/libraries/System.Private.CoreLib/src/System/Resources/ResourceManager.Uap.cs deleted file mode 100644 index 2a8d737..0000000 --- a/src/libraries/System.Private.CoreLib/src/System/Resources/ResourceManager.Uap.cs +++ /dev/null @@ -1,203 +0,0 @@ -// 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.IO; -using System.Globalization; -using System.Reflection; -using System.Diagnostics; -using System.Runtime.CompilerServices; -using Internal.Resources; - -namespace System.Resources -{ - public partial class ResourceManager - { - private WindowsRuntimeResourceManagerBase? _WinRTResourceManager; - private PRIExceptionInfo? _PRIExceptionInfo; - private bool _PRIInitialized; - private bool _useUapResourceManagement; - - private string? GetStringFromPRI(string stringName, CultureInfo? culture, string? neutralResourcesCulture) - { - Debug.Assert(_useUapResourceManagement); - Debug.Assert(_WinRTResourceManager != null); - Debug.Assert(_PRIInitialized); - - // If the caller explicitly passed in a culture that was obtained by calling CultureInfo.CurrentUICulture, - // null it out, so that we re-compute it. If we use modern resource lookup, we may end up getting a "better" - // match, since CultureInfo objects can't represent all the different languages the Uap resource model supports. - if (object.ReferenceEquals(culture, CultureInfo.CurrentUICulture)) - { - culture = null; - } - - string? startingCulture = culture?.Name; - - if (!_PRIInitialized) - { - // Always throw if we did not fully succeed in initializing the WinRT Resource Manager. - - if (_PRIExceptionInfo != null && _PRIExceptionInfo.PackageSimpleName != null && _PRIExceptionInfo.ResWFile != null) - throw new MissingManifestResourceException(SR.Format(SR.MissingManifestResource_ResWFileNotLoaded, _PRIExceptionInfo.ResWFile, _PRIExceptionInfo.PackageSimpleName)); - - throw new MissingManifestResourceException(SR.MissingManifestResource_NoPRIresources); - } - - if (stringName.Length == 0) - return null; - - // Do not handle exceptions. See the comment in SetUapConfiguration about throwing - // exception types that the ResourceManager class is not documented to throw. - return _WinRTResourceManager.GetString( - stringName, - string.IsNullOrEmpty(startingCulture) ? null : startingCulture, - string.IsNullOrEmpty(neutralResourcesCulture) ? null : neutralResourcesCulture); - } - - // Since we can't directly reference System.Runtime.WindowsRuntime from System.Private.CoreLib, we have to get the type via reflection. - // It would be better if we could just implement WindowsRuntimeResourceManager in System.Private.CoreLib, but we can't, because - // we can do very little with WinRT in System.Private.CoreLib. - // The attribute is necessary because linker can't add new assemblies to the closure when recognizing Type.GetType - // so even though the GetType call below is analyzable, the PreserveDependency is still necessary to actually include - // the assembly in the trimmed closure. - [PreserveDependency(".ctor()", "System.Resources.WindowsRuntimeResourceManager", "System.Runtime.WindowsRuntime")] - internal static WindowsRuntimeResourceManagerBase GetWinRTResourceManager() - { - Type WinRTResourceManagerType = Type.GetType("System.Resources.WindowsRuntimeResourceManager, System.Runtime.WindowsRuntime", throwOnError: true)!; - return (WindowsRuntimeResourceManagerBase)Activator.CreateInstance(WinRTResourceManagerType, nonPublic: true)!; - } - - // CoreCLR: When running under AppX, the following rules apply for resource lookup: - // - // 1) For Framework assemblies, we always use satellite assembly based lookup. - // 2) For non-FX assemblies: - // - // a) If the assembly lives under PLATFORM_RESOURCE_ROOTS (as specified by the host during AppDomain creation), - // then we will use satellite assembly based lookup in assemblies like *.resources.dll. - // - // b) For any other non-FX assembly, we will use the modern resource manager with the premise that app package - // contains the PRI resources. - // - // .NET Native: If it is framework assembly we'll return true. The reason is in .NetNative we don't merge the - // resources to the app PRI file. - // The framework assemblies are tagged with attribute [assembly: AssemblyMetadata(".NETFrameworkAssembly", "")] - private static bool ShouldUseUapResourceManagement(Assembly resourcesAssembly) - { - if (resourcesAssembly == typeof(object).Assembly) // We are not loading resources for System.Private.CoreLib - return false; - - // Check to see if the assembly is under PLATFORM_RESOURCE_ROOTS. If it is, then we should use satellite assembly lookup for it. - string? platformResourceRoots = AppContext.GetData("PLATFORM_RESOURCE_ROOTS") as string; - if (!string.IsNullOrEmpty(platformResourceRoots)) - { - string resourceAssemblyPath = resourcesAssembly.Location; - - // Loop through the PLATFORM_RESOURCE_ROOTS and see if the assembly is contained in it. - foreach (string pathPlatformResourceRoot in platformResourceRoots.Split(Path.PathSeparator)) - { - if (resourceAssemblyPath.StartsWith(pathPlatformResourceRoot, StringComparison.CurrentCultureIgnoreCase)) - { - // Found the resource assembly to be present in one of the PLATFORM_RESOURCE_ROOT, so stop the enumeration loop. - return false; - } - } - } - - return true; - } - - // Only call SetUapConfiguration from ResourceManager constructors, and nowhere else. - // Throws MissingManifestResourceException and WinRT HResults - private void SetUapConfiguration() - { - Debug.Assert(!_useUapResourceManagement); // Only this function writes to this member - Debug.Assert(_WinRTResourceManager == null); // Only this function writes to this member - Debug.Assert(!_PRIInitialized); // Only this function writes to this member - Debug.Assert(_PRIExceptionInfo == null); // Only this function writes to this member - - if (!ApplicationModel.IsUap) - return; - - Debug.Assert(MainAssembly != null); - if (!ShouldUseUapResourceManagement(MainAssembly)) - return; - - _useUapResourceManagement = true; - - // If we have the type information from the ResourceManager(Type) constructor, we use it. Otherwise, we use BaseNameField. - string? reswFilename = _locationInfo == null ? BaseNameField : _locationInfo.FullName; - - // The only way this can happen is if a class inherited from ResourceManager and - // did not set the BaseNameField before calling the protected ResourceManager() constructor. - // For other constructors, we would already have thrown an ArgumentNullException by now. - // Throwing an ArgumentNullException now is not the right thing to do because technically - // ResourceManager() takes no arguments, and because it is not documented as throwing - // any exceptions. Instead, let's go through the rest of the initialization with this set to - // an empty string. We may in fact fail earlier for another reason, but otherwise we will - // throw a MissingManifestResourceException when GetString is called indicating that a - // resW filename called "" could not be found. - reswFilename ??= string.Empty; - - // At this point it is important NOT to set _useUapResourceManagement to false - // if the PRI file does not exist because we are now certain we need to load PRI - // resources. We want to fail by throwing a MissingManifestResourceException - // if WindowsRuntimeResourceManager.Initialize fails to locate the PRI file. We do not - // want to fall back to using satellite assemblies anymore. Note that we would not throw - // the MissingManifestResourceException from this function, but from GetString. See the - // comment below on the reason for this. - - _WinRTResourceManager = GetWinRTResourceManager(); - - try - { - _PRIInitialized = _WinRTResourceManager.Initialize(MainAssembly.Location, reswFilename, out _PRIExceptionInfo); - // Note that _PRIExceptionInfo might be null - this is OK. - // In that case we will just throw the generic - // MissingManifestResource_NoPRIresources exception. - // See the implementation of GetString for more details. - } - // We would like to be able to throw a MissingManifestResourceException here if PRI resources - // could not be loaded for a recognized reason. However, the ResourceManager constructors - // that call SetUapConfiguration are not documented as throwing MissingManifestResourceException, - // and since they are part of the portable profile, we cannot start throwing a new exception type - // as that would break existing portable libraries. Hence we must save the exception information - // now and throw the exception on the first call to GetString. - catch (FileNotFoundException) - { - // We will throw MissingManifestResource_NoPRIresources from GetString - // when we see that _PRIInitialized is false. - } - catch (Exception e) - { - // ERROR_MRM_MAP_NOT_FOUND can be thrown by the call to ResourceManager.get_AllResourceMaps - // in WindowsRuntimeResourceManager.Initialize. - // In this case _PRIExceptionInfo is now null and we will just throw the generic - // MissingManifestResource_NoPRIresources exception. - // See the implementation of GetString for more details. - if (e.HResult != HResults.ERROR_MRM_MAP_NOT_FOUND) - throw; // Unexpected exception code. Bubble it up to the caller. - } - - if (!_PRIInitialized) - { - _useUapResourceManagement = false; - } - - // Allow all other exception types to bubble up to the caller. - - // Yes, this causes us to potentially throw exception types that are not documented. - - // Ultimately the tradeoff is the following: - // -We could ignore unknown exceptions or rethrow them as inner exceptions - // of exceptions that the ResourceManager class is already documented as throwing. - // This would allow existing portable libraries to gracefully recover if they don't care - // too much about the ResourceManager object they are using. However it could - // mask potentially fatal errors that we are not aware of, such as a disk drive failing. - - // The alternative, which we chose, is to throw unknown exceptions. This may tear - // down the process if the portable library and app don't expect this exception type. - // On the other hand, this won't mask potentially fatal errors we don't know about. - } - } -} diff --git a/src/libraries/System.Private.CoreLib/src/System/Resources/ResourceManager.cs b/src/libraries/System.Private.CoreLib/src/System/Resources/ResourceManager.cs index 8e3dbf9..fa49f63 100644 --- a/src/libraries/System.Private.CoreLib/src/System/Resources/ResourceManager.cs +++ b/src/libraries/System.Private.CoreLib/src/System/Resources/ResourceManager.cs @@ -238,10 +238,6 @@ namespace System.Resources [MemberNotNull(nameof(_resourceGroveler))] private void CommonAssemblyInit() { -#if FEATURE_APPX - SetUapConfiguration(); -#endif - // Now we can use the managed resources even when using PRI's to support the APIs GetObject, GetStream...etc. _useManifest = true; @@ -600,15 +596,6 @@ namespace System.Resources if (null == name) throw new ArgumentNullException(nameof(name)); -#if FEATURE_APPX - if (_useUapResourceManagement) - { - // Throws WinRT hresults. - Debug.Assert(_neutralResourcesCulture != null); - return GetStringFromPRI(name, culture, _neutralResourcesCulture.Name); - } -#endif - culture ??= CultureInfo.CurrentUICulture; ResourceSet? last = GetFirstResourceSet(culture); diff --git a/src/libraries/System.Private.CoreLib/src/System/Runtime/InteropServices/WindowsRuntime/Attributes.cs b/src/libraries/System.Private.CoreLib/src/System/Runtime/InteropServices/WindowsRuntime/Attributes.cs deleted file mode 100644 index 3c3f853..0000000 --- a/src/libraries/System.Private.CoreLib/src/System/Runtime/InteropServices/WindowsRuntime/Attributes.cs +++ /dev/null @@ -1,94 +0,0 @@ -// 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 System.Runtime.InteropServices.WindowsRuntime -{ - // DefaultInterfaceAttribute marks a WinRT class (or interface group) that has its default interface specified. - [AttributeUsage(AttributeTargets.Class | AttributeTargets.Interface, AllowMultiple = false, Inherited = false)] - public sealed class DefaultInterfaceAttribute : Attribute - { - private readonly Type m_defaultInterface; - - public DefaultInterfaceAttribute(Type defaultInterface) - { - m_defaultInterface = defaultInterface; - } - - public Type DefaultInterface => m_defaultInterface; - } - - // WindowsRuntimeImport is a pseudo custom attribute which causes us to emit the tdWindowsRuntime bit - // onto types which are decorated with the attribute. This is needed to mark Windows Runtime types - // which are redefined in mscorlib.dll and System.Runtime.WindowsRuntime.dll, as the C# compiler does - // not have a built in syntax to mark tdWindowsRuntime. These two assemblies are special as they - // implement the CLR's support for WinRT, so this type is internal as marking tdWindowsRuntime should - // generally be done via winmdexp for user code. - [AttributeUsage(AttributeTargets.Class | AttributeTargets.Interface | AttributeTargets.Enum | AttributeTargets.Struct | AttributeTargets.Delegate, Inherited = false)] - internal sealed class WindowsRuntimeImportAttribute : Attribute - { - internal WindowsRuntimeImportAttribute() { } - } - - // This attribute is applied to class interfaces in a generated projection assembly. It is used by Visual Studio - // and other tools to find out what version of a component (eg. Windows) a WinRT class began to implement - // a particular interfaces. - [AttributeUsage(AttributeTargets.Class | AttributeTargets.Interface, Inherited = false, AllowMultiple = true)] - public sealed class InterfaceImplementedInVersionAttribute : Attribute - { - public InterfaceImplementedInVersionAttribute(Type interfaceType, byte majorVersion, byte minorVersion, byte buildVersion, byte revisionVersion) - { - m_interfaceType = interfaceType; - m_majorVersion = majorVersion; - m_minorVersion = minorVersion; - m_buildVersion = buildVersion; - m_revisionVersion = revisionVersion; - } - - public Type InterfaceType => m_interfaceType; - - public byte MajorVersion => m_majorVersion; - - public byte MinorVersion => m_minorVersion; - - public byte BuildVersion => m_buildVersion; - - public byte RevisionVersion => m_revisionVersion; - - private readonly Type m_interfaceType; - private readonly byte m_majorVersion; - private readonly byte m_minorVersion; - private readonly byte m_buildVersion; - private readonly byte m_revisionVersion; - } - - // Applies to read-only array parameters - [AttributeUsage(AttributeTargets.Parameter, Inherited = false, AllowMultiple = false)] - public sealed class ReadOnlyArrayAttribute : Attribute - { - public ReadOnlyArrayAttribute() { } - } - - // Applies to write-only array parameters - [AttributeUsage(AttributeTargets.Parameter, Inherited = false, AllowMultiple = false)] - public sealed class WriteOnlyArrayAttribute : Attribute - { - public WriteOnlyArrayAttribute() { } - } - - // This attribute is applied on the return value to specify the name of the return value. - // In WindowsRuntime all parameters including return value need to have unique names. - // This is essential in JS as one of the ways to get at the results of a method in JavaScript is via a Dictionary object keyed by parameter name. - [AttributeUsage(AttributeTargets.ReturnValue | AttributeTargets.Delegate, AllowMultiple = false, Inherited = false)] - public sealed class ReturnValueNameAttribute : Attribute - { - private readonly string m_Name; - - public ReturnValueNameAttribute(string name) - { - m_Name = name; - } - - public string Name => m_Name; - } -} diff --git a/src/libraries/System.Private.CoreLib/src/System/Runtime/InteropServices/WindowsRuntime/EventRegistrationToken.cs b/src/libraries/System.Private.CoreLib/src/System/Runtime/InteropServices/WindowsRuntime/EventRegistrationToken.cs deleted file mode 100644 index 15b4a83..0000000 --- a/src/libraries/System.Private.CoreLib/src/System/Runtime/InteropServices/WindowsRuntime/EventRegistrationToken.cs +++ /dev/null @@ -1,34 +0,0 @@ -// 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 System.Runtime.InteropServices.WindowsRuntime -{ - // Event registration tokens are 64 bit opaque structures returned from WinRT style event adders, in order - // to signify a registration of a particular delegate to an event. The token's only real use is to - // unregister the same delgate from the event at a later time. - public struct EventRegistrationToken : IEquatable - { - private readonly ulong _value; - - [CLSCompliant(false)] - public EventRegistrationToken(ulong value) => _value = value; - - [CLSCompliant(false)] - public ulong Value => _value; - - public static bool operator ==(EventRegistrationToken left, EventRegistrationToken right) => - left.Equals(right); - - public static bool operator !=(EventRegistrationToken left, EventRegistrationToken right) => - !left.Equals(right); - - public override bool Equals(object? obj) => - obj is EventRegistrationToken && - ((EventRegistrationToken)obj)._value == _value; - - public override int GetHashCode() => _value.GetHashCode(); - - public bool Equals(EventRegistrationToken other) => other._value == _value; - } -} diff --git a/src/libraries/System.Private.CoreLib/src/System/Runtime/InteropServices/WindowsRuntime/IActivationFactory.cs b/src/libraries/System.Private.CoreLib/src/System/Runtime/InteropServices/WindowsRuntime/IActivationFactory.cs deleted file mode 100644 index 38de7e7..0000000 --- a/src/libraries/System.Private.CoreLib/src/System/Runtime/InteropServices/WindowsRuntime/IActivationFactory.cs +++ /dev/null @@ -1,14 +0,0 @@ -// 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 System.Runtime.InteropServices.WindowsRuntime -{ - [ComImport] - [Guid("00000035-0000-0000-C000-000000000046")] - [WindowsRuntimeImport] - public interface IActivationFactory - { - object ActivateInstance(); - } -} diff --git a/src/libraries/System.Private.CoreLib/src/System/Threading/SynchronizationContext.cs b/src/libraries/System.Private.CoreLib/src/System/Threading/SynchronizationContext.cs index 7ce1cd9..524c7a0 100644 --- a/src/libraries/System.Private.CoreLib/src/System/Threading/SynchronizationContext.cs +++ b/src/libraries/System.Private.CoreLib/src/System/Threading/SynchronizationContext.cs @@ -12,9 +12,7 @@ namespace System.Threading { } -#if !FEATURE_APPX public static SynchronizationContext? Current => Thread.CurrentThread._synchronizationContext; -#endif protected void SetWaitNotificationRequired() => _requireWaitNotification = true; diff --git a/src/libraries/System.Private.CoreLib/src/System/Threading/Tasks/Task.cs b/src/libraries/System.Private.CoreLib/src/System/Threading/Tasks/Task.cs index 61f6e4a..a7c027f 100644 --- a/src/libraries/System.Private.CoreLib/src/System/Threading/Tasks/Task.cs +++ b/src/libraries/System.Private.CoreLib/src/System/Threading/Tasks/Task.cs @@ -1881,13 +1881,6 @@ namespace System.Threading.Tasks #if CORERT RuntimeExceptionHelpers.ReportUnhandledException(edi.SourceException); #else - -#if FEATURE_COMINTEROP - // If we have the new error reporting APIs, report this error. - if (System.Runtime.InteropServices.WindowsRuntime.WindowsRuntimeMarshal.ReportUnhandledError(edi.SourceException)) - return; -#endif - // Propagate the exception(s) on the ThreadPool ThreadPool.QueueUserWorkItem(state => ((ExceptionDispatchInfo)state!).Throw(), edi); diff --git a/src/libraries/System.Runtime.InteropServices.WindowsRuntime/Directory.Build.props b/src/libraries/System.Runtime.InteropServices.WindowsRuntime/Directory.Build.props deleted file mode 100644 index 5f6e490..0000000 --- a/src/libraries/System.Runtime.InteropServices.WindowsRuntime/Directory.Build.props +++ /dev/null @@ -1,7 +0,0 @@ - - - - Microsoft - true - - diff --git a/src/libraries/System.Runtime.InteropServices.WindowsRuntime/System.Runtime.InteropServices.WindowsRuntime.sln b/src/libraries/System.Runtime.InteropServices.WindowsRuntime/System.Runtime.InteropServices.WindowsRuntime.sln deleted file mode 100644 index d68c441..0000000 --- a/src/libraries/System.Runtime.InteropServices.WindowsRuntime/System.Runtime.InteropServices.WindowsRuntime.sln +++ /dev/null @@ -1,60 +0,0 @@ -Microsoft Visual Studio Solution File, Format Version 12.00 -# Visual Studio 15 -VisualStudioVersion = 15.0.27213.1 -MinimumVisualStudioVersion = 10.0.40219.1 -Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "System.Runtime.InteropServices.WindowsRuntime.Tests", "tests\System.Runtime.InteropServices.WindowsRuntime.Tests.csproj", "{27F624C8-06E3-455D-B5D1-C0FEB343EFAA}" - ProjectSection(ProjectDependencies) = postProject - {5655C5E4-9B76-489B-87AF-42BD60570A00} = {5655C5E4-9B76-489B-87AF-42BD60570A00} - EndProjectSection -EndProject -Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "System.Runtime.InteropServices.WindowsRuntime", "src\System.Runtime.InteropServices.WindowsRuntime.csproj", "{5655C5E4-9B76-489B-87AF-42BD60570A00}" - ProjectSection(ProjectDependencies) = postProject - {DC485335-D0D7-4E28-9593-445B7B6BEFA7} = {DC485335-D0D7-4E28-9593-445B7B6BEFA7} - EndProjectSection -EndProject -Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "System.Runtime.InteropServices.WindowsRuntime", "ref\System.Runtime.InteropServices.WindowsRuntime.csproj", "{DC485335-D0D7-4E28-9593-445B7B6BEFA7}" -EndProject -Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "tests", "tests", "{1A2F9F4A-A032-433E-B914-ADD5992BB178}" -EndProject -Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "src", "src", "{E107E9C1-E893-4E87-987E-04EF0DCEAEFD}" -EndProject -Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "ref", "ref", "{2E666815-2EDB-464B-9DF6-380BF4789AD4}" -EndProject -Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "TestUtilities", "..\Common\tests\TestUtilities\TestUtilities.csproj", "{69886A25-B37B-4D7F-AC77-970576EB3661}" -EndProject -Global - GlobalSection(SolutionConfigurationPlatforms) = preSolution - Debug|Any CPU = Debug|Any CPU - Release|Any CPU = Release|Any CPU - EndGlobalSection - GlobalSection(ProjectConfigurationPlatforms) = postSolution - {27F624C8-06E3-455D-B5D1-C0FEB343EFAA}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {27F624C8-06E3-455D-B5D1-C0FEB343EFAA}.Debug|Any CPU.Build.0 = Debug|Any CPU - {27F624C8-06E3-455D-B5D1-C0FEB343EFAA}.Release|Any CPU.ActiveCfg = Release|Any CPU - {27F624C8-06E3-455D-B5D1-C0FEB343EFAA}.Release|Any CPU.Build.0 = Release|Any CPU - {5655C5E4-9B76-489B-87AF-42BD60570A00}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {5655C5E4-9B76-489B-87AF-42BD60570A00}.Debug|Any CPU.Build.0 = Debug|Any CPU - {5655C5E4-9B76-489B-87AF-42BD60570A00}.Release|Any CPU.ActiveCfg = Release|Any CPU - {5655C5E4-9B76-489B-87AF-42BD60570A00}.Release|Any CPU.Build.0 = Release|Any CPU - {DC485335-D0D7-4E28-9593-445B7B6BEFA7}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {DC485335-D0D7-4E28-9593-445B7B6BEFA7}.Debug|Any CPU.Build.0 = Debug|Any CPU - {DC485335-D0D7-4E28-9593-445B7B6BEFA7}.Release|Any CPU.ActiveCfg = Release|Any CPU - {DC485335-D0D7-4E28-9593-445B7B6BEFA7}.Release|Any CPU.Build.0 = Release|Any CPU - {69886A25-B37B-4D7F-AC77-970576EB3661}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {69886A25-B37B-4D7F-AC77-970576EB3661}.Debug|Any CPU.Build.0 = Debug|Any CPU - {69886A25-B37B-4D7F-AC77-970576EB3661}.Release|Any CPU.ActiveCfg = Release|Any CPU - {69886A25-B37B-4D7F-AC77-970576EB3661}.Release|Any CPU.Build.0 = Release|Any CPU - EndGlobalSection - GlobalSection(SolutionProperties) = preSolution - HideSolutionNode = FALSE - EndGlobalSection - GlobalSection(NestedProjects) = preSolution - {27F624C8-06E3-455D-B5D1-C0FEB343EFAA} = {1A2F9F4A-A032-433E-B914-ADD5992BB178} - {5655C5E4-9B76-489B-87AF-42BD60570A00} = {E107E9C1-E893-4E87-987E-04EF0DCEAEFD} - {DC485335-D0D7-4E28-9593-445B7B6BEFA7} = {2E666815-2EDB-464B-9DF6-380BF4789AD4} - {69886A25-B37B-4D7F-AC77-970576EB3661} = {1A2F9F4A-A032-433E-B914-ADD5992BB178} - EndGlobalSection - GlobalSection(ExtensibilityGlobals) = postSolution - SolutionGuid = {5F15FD50-438B-4DD9-B565-FBFE1875DFC9} - EndGlobalSection -EndGlobal diff --git a/src/libraries/System.Runtime.InteropServices.WindowsRuntime/ref/System.Runtime.InteropServices.WindowsRuntime.cs b/src/libraries/System.Runtime.InteropServices.WindowsRuntime/ref/System.Runtime.InteropServices.WindowsRuntime.cs deleted file mode 100644 index ba115be..0000000 --- a/src/libraries/System.Runtime.InteropServices.WindowsRuntime/ref/System.Runtime.InteropServices.WindowsRuntime.cs +++ /dev/null @@ -1,73 +0,0 @@ -// 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. -// ------------------------------------------------------------------------------ -// Changes to this file must follow the https://aka.ms/api-review process. -// ------------------------------------------------------------------------------ - -namespace System.Runtime.InteropServices.WindowsRuntime -{ - [System.AttributeUsageAttribute(System.AttributeTargets.Class | System.AttributeTargets.Interface, AllowMultiple=false, Inherited=false)] - public sealed partial class DefaultInterfaceAttribute : System.Attribute - { - public DefaultInterfaceAttribute(System.Type defaultInterface) { } - public System.Type DefaultInterface { get { throw null; } } - } - public partial struct EventRegistrationToken - { - private int _dummyPrimitive; - public override bool Equals(object? obj) { throw null; } - public override int GetHashCode() { throw null; } - public static bool operator ==(System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken left, System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken right) { throw null; } - public static bool operator !=(System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken left, System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken right) { throw null; } - } - public sealed partial class EventRegistrationTokenTable where T : class - { - public EventRegistrationTokenTable() { } - public T? InvocationList { get { throw null; } set { } } - public System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken AddEventHandler(T? handler) { throw null; } - public static System.Runtime.InteropServices.WindowsRuntime.EventRegistrationTokenTable GetOrCreateEventRegistrationTokenTable(ref System.Runtime.InteropServices.WindowsRuntime.EventRegistrationTokenTable? refEventTable) { throw null; } - public void RemoveEventHandler(System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken token) { } - public void RemoveEventHandler(T? handler) { } - } - public partial interface IActivationFactory - { - object ActivateInstance(); - } - [System.AttributeUsageAttribute(System.AttributeTargets.Class | System.AttributeTargets.Interface, Inherited=false, AllowMultiple=true)] - public sealed partial class InterfaceImplementedInVersionAttribute : System.Attribute - { - public InterfaceImplementedInVersionAttribute(System.Type interfaceType, byte majorVersion, byte minorVersion, byte buildVersion, byte revisionVersion) { } - public byte BuildVersion { get { throw null; } } - public System.Type InterfaceType { get { throw null; } } - public byte MajorVersion { get { throw null; } } - public byte MinorVersion { get { throw null; } } - public byte RevisionVersion { get { throw null; } } - } - [System.AttributeUsageAttribute(System.AttributeTargets.Parameter, Inherited=false, AllowMultiple=false)] - public sealed partial class ReadOnlyArrayAttribute : System.Attribute - { - public ReadOnlyArrayAttribute() { } - } - [System.AttributeUsageAttribute(System.AttributeTargets.Delegate | System.AttributeTargets.ReturnValue, AllowMultiple=false, Inherited=false)] - public sealed partial class ReturnValueNameAttribute : System.Attribute - { - public ReturnValueNameAttribute(string name) { } - public string Name { get { throw null; } } - } - public static partial class WindowsRuntimeMarshal - { - public static void AddEventHandler(System.Func addMethod, System.Action removeMethod, T handler) { } - public static void FreeHString(System.IntPtr ptr) { } - public static System.Runtime.InteropServices.WindowsRuntime.IActivationFactory GetActivationFactory(System.Type type) { throw null; } - public static string PtrToStringHString(System.IntPtr ptr) { throw null; } - public static void RemoveAllEventHandlers(System.Action removeMethod) { } - public static void RemoveEventHandler(System.Action removeMethod, T handler) { } - public static System.IntPtr StringToHString(string s) { throw null; } - } - [System.AttributeUsageAttribute(System.AttributeTargets.Parameter, Inherited=false, AllowMultiple=false)] - public sealed partial class WriteOnlyArrayAttribute : System.Attribute - { - public WriteOnlyArrayAttribute() { } - } -} diff --git a/src/libraries/System.Runtime.InteropServices.WindowsRuntime/ref/System.Runtime.InteropServices.WindowsRuntime.csproj b/src/libraries/System.Runtime.InteropServices.WindowsRuntime/ref/System.Runtime.InteropServices.WindowsRuntime.csproj deleted file mode 100644 index 5b6b958..0000000 --- a/src/libraries/System.Runtime.InteropServices.WindowsRuntime/ref/System.Runtime.InteropServices.WindowsRuntime.csproj +++ /dev/null @@ -1,12 +0,0 @@ - - - $(NetCoreAppCurrent) - enable - - - - - - - - \ No newline at end of file diff --git a/src/libraries/System.Runtime.InteropServices.WindowsRuntime/src/MatchingRefApiCompatBaseline.txt b/src/libraries/System.Runtime.InteropServices.WindowsRuntime/src/MatchingRefApiCompatBaseline.txt deleted file mode 100644 index 4a3d206..0000000 --- a/src/libraries/System.Runtime.InteropServices.WindowsRuntime/src/MatchingRefApiCompatBaseline.txt +++ /dev/null @@ -1,8 +0,0 @@ -Compat issues with assembly System.Runtime.InteropServices.WindowsRuntime: -CannotRemoveBaseTypeOrInterface : Type 'System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken' does not implement interface 'System.IEquatable' in the reference but it does in the implementation. -MembersMustExist : Member 'public void System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken..ctor(System.UInt64)' does not exist in the reference but it does exist in the implementation. -MembersMustExist : Member 'public System.Boolean System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken.Equals(System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken)' does not exist in the reference but it does exist in the implementation. -MembersMustExist : Member 'public System.UInt64 System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken.Value.get()' does not exist in the reference but it does exist in the implementation. -MembersMustExist : Member 'public System.Boolean System.Runtime.InteropServices.WindowsRuntime.EventRegistrationTokenTable.RemoveEventHandler(System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken, T)' does not exist in the reference but it does exist in the implementation. -MembersMustExist : Member 'public System.Object System.Runtime.InteropServices.WindowsRuntime.WindowsRuntimeMarshal.GetUniqueObjectForIUnknownWithoutUnboxing(System.IntPtr)' does not exist in the reference but it does exist in the implementation. -Total Issues: 6 diff --git a/src/libraries/System.Runtime.InteropServices.WindowsRuntime/src/Resources/Strings.resx b/src/libraries/System.Runtime.InteropServices.WindowsRuntime/src/Resources/Strings.resx deleted file mode 100644 index a1e87ad..0000000 --- a/src/libraries/System.Runtime.InteropServices.WindowsRuntime/src/Resources/Strings.resx +++ /dev/null @@ -1,63 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - text/microsoft-resx - - - 2.0 - - - System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 - - - System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 - - - Operations with Windows Runtime are only supported on Windows platforms. - - \ No newline at end of file diff --git a/src/libraries/System.Runtime.InteropServices.WindowsRuntime/src/System.Runtime.InteropServices.WindowsRuntime.csproj b/src/libraries/System.Runtime.InteropServices.WindowsRuntime/src/System.Runtime.InteropServices.WindowsRuntime.csproj deleted file mode 100644 index 62f693b..0000000 --- a/src/libraries/System.Runtime.InteropServices.WindowsRuntime/src/System.Runtime.InteropServices.WindowsRuntime.csproj +++ /dev/null @@ -1,26 +0,0 @@ - - - System.Runtime.InteropServices.WindowsRuntime - true - $(NetCoreAppCurrent)-Windows_NT;$(NetCoreAppCurrent) - enable - false - - - - - - - - - - - - - - - - - SR.PlatformNotSupported_WindowsRuntime - - diff --git a/src/libraries/System.Runtime.InteropServices.WindowsRuntime/tests/System.Runtime.InteropServices.WindowsRuntime.Tests.csproj b/src/libraries/System.Runtime.InteropServices.WindowsRuntime/tests/System.Runtime.InteropServices.WindowsRuntime.Tests.csproj deleted file mode 100644 index 6ed8a0f..0000000 --- a/src/libraries/System.Runtime.InteropServices.WindowsRuntime/tests/System.Runtime.InteropServices.WindowsRuntime.Tests.csproj +++ /dev/null @@ -1,18 +0,0 @@ - - - $(NetCoreAppCurrent)-Windows_NT;$(NetCoreAppCurrent) - true - - - - - - - - - - - - - - \ No newline at end of file diff --git a/src/libraries/System.Runtime.InteropServices.WindowsRuntime/tests/System/Runtime/InteropServices/WindowsRuntime/DefaultInterfaceAttributeTests.cs b/src/libraries/System.Runtime.InteropServices.WindowsRuntime/tests/System/Runtime/InteropServices/WindowsRuntime/DefaultInterfaceAttributeTests.cs deleted file mode 100644 index b96cedf..0000000 --- a/src/libraries/System.Runtime.InteropServices.WindowsRuntime/tests/System/Runtime/InteropServices/WindowsRuntime/DefaultInterfaceAttributeTests.cs +++ /dev/null @@ -1,20 +0,0 @@ -// 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 Xunit; - -namespace System.Runtime.InteropServices.WindowsRuntime.Tests -{ - public class DefaultInterfaceAttributeTests - { - [Theory] - [InlineData(null)] - [InlineData(typeof(int))] - public void Ctor_DefaultInterface(Type defaultInterface) - { - var attribute = new ComDefaultInterfaceAttribute(defaultInterface); - Assert.Equal(defaultInterface, attribute.Value); - } - } -} diff --git a/src/libraries/System.Runtime.InteropServices.WindowsRuntime/tests/System/Runtime/InteropServices/WindowsRuntime/EmptyAttributeTests.cs b/src/libraries/System.Runtime.InteropServices.WindowsRuntime/tests/System/Runtime/InteropServices/WindowsRuntime/EmptyAttributeTests.cs deleted file mode 100644 index 446e449..0000000 --- a/src/libraries/System.Runtime.InteropServices.WindowsRuntime/tests/System/Runtime/InteropServices/WindowsRuntime/EmptyAttributeTests.cs +++ /dev/null @@ -1,18 +0,0 @@ -// 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 Xunit; - -namespace System.Runtime.InteropServices.WindowsRuntime.Tests -{ - public class EmptyAttributeTests - { - [Fact] - public void EmptyAttributes_Ctor_Success() - { - new ReadOnlyArrayAttribute(); - new WriteOnlyArrayAttribute(); - } - } -} diff --git a/src/libraries/System.Runtime.InteropServices.WindowsRuntime/tests/System/Runtime/InteropServices/WindowsRuntime/EventRegistrationTokenTableTests.cs b/src/libraries/System.Runtime.InteropServices.WindowsRuntime/tests/System/Runtime/InteropServices/WindowsRuntime/EventRegistrationTokenTableTests.cs deleted file mode 100644 index 1be0d5d..0000000 --- a/src/libraries/System.Runtime.InteropServices.WindowsRuntime/tests/System/Runtime/InteropServices/WindowsRuntime/EventRegistrationTokenTableTests.cs +++ /dev/null @@ -1,179 +0,0 @@ -// 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 Xunit; - -namespace System.Runtime.InteropServices.WindowsRuntime.Tests -{ - [ActiveIssue("https://github.com/dotnet/runtime/issues/34749", TestPlatforms.Windows, TargetFrameworkMonikers.Netcoreapp, TestRuntimes.Mono)] - public class EventRegistrationTokenTableTests - { - [Fact] - public void Ctor_Default() - { - var tokenTable = new EventRegistrationTokenTable(); - Assert.Null(tokenTable.InvocationList); - } - - [Fact] - public void Ctor_NonDelegateType_ThrowsInvalidOperationException() - { - Assert.Throws(() => new EventRegistrationTokenTable()); - } - - [Fact] - public void AddEventHandler_SingleInvocationList_AddsSingleDelegateToInvocationList() - { - EventHandler handler = new EventHandler(EventHandlerMethod1); - var tokenTable = new EventRegistrationTokenTable(); - - EventRegistrationToken token = tokenTable.AddEventHandler(handler); - Assert.NotEqual(0, token.GetHashCode()); - Assert.Equal(new Delegate[] { handler }, tokenTable.InvocationList.GetInvocationList()); - } - - [Fact] - public void AddEventHandler_MultipleInvocationList_AddsAllDelegateToInvocationLists() - { - EventHandler handler1 = new EventHandler(EventHandlerMethod1); - EventHandler handler2 = new EventHandler(EventHandlerMethod2); - EventHandler combinedHandler = (EventHandler)Delegate.Combine(handler1, handler2); - - var tokenTable = new EventRegistrationTokenTable(); - - EventRegistrationToken token = tokenTable.AddEventHandler(combinedHandler); - Assert.NotEqual(0, token.GetHashCode()); - Assert.Equal(new Delegate[] { handler1, handler2 }, tokenTable.InvocationList.GetInvocationList()); - } - - [Fact] - public void AddEventHandler_MultipleTimes_AddsEachDelegateToInvocationList() - { - EventHandler handler = new EventHandler(EventHandlerMethod1); - var tokenTable = new EventRegistrationTokenTable(); - - EventRegistrationToken token1 = tokenTable.AddEventHandler(handler); - Assert.NotEqual(0, token1.GetHashCode()); - - EventRegistrationToken token2 = tokenTable.AddEventHandler(handler); - Assert.NotEqual(token1.GetHashCode(), token2.GetHashCode()); - - Assert.Equal(new Delegate[] { handler, handler }, tokenTable.InvocationList.GetInvocationList()); - } - - [Fact] - public void AddEventHandler_Null_ReturnsZeroToken() - { - var tokenTable = new EventRegistrationTokenTable(); - EventRegistrationToken token = tokenTable.AddEventHandler(null); - Assert.Equal(0, token.GetHashCode()); - - // Removing this token should be a nop. - tokenTable.RemoveEventHandler(token); - } - - [Fact] - public void RemoveEventHandler_Token_RemovesFromTable() - { - EventHandler handler = new EventHandler(EventHandlerMethod1); - var tokenTable = new EventRegistrationTokenTable(); - EventRegistrationToken token = tokenTable.AddEventHandler(handler); - - tokenTable.RemoveEventHandler(token); - Assert.Null(tokenTable.InvocationList); - - // Calls to RemoveEventHandler after removal are nops. - tokenTable.RemoveEventHandler(token); - } - - [Fact] - public void RemoveEventHandler_Delegate_RemovesFromTable() - { - EventHandler handler1 = new EventHandler(EventHandlerMethod1); - EventHandler handler2 = new EventHandler(EventHandlerMethod2); - EventHandler combinedHandler = (EventHandler)Delegate.Combine(handler1, handler2); - - var tokenTable = new EventRegistrationTokenTable(); - tokenTable.AddEventHandler(combinedHandler); - - tokenTable.RemoveEventHandler(handler1); - tokenTable.RemoveEventHandler(handler2); - Assert.Equal(new Delegate[] { handler1, handler2 }, tokenTable.InvocationList.GetInvocationList()); - - tokenTable.RemoveEventHandler(combinedHandler); - Assert.Null(tokenTable.InvocationList); - - // Calls to RemoveEventHandler after removal are nops. - tokenTable.RemoveEventHandler(combinedHandler); - } - - [Fact] - public void RemoveEventHandler_MultipleTimes_RemovesSingleDelegateFromTable() - { - EventHandler handler = new EventHandler(EventHandlerMethod1); - var tokenTable = new EventRegistrationTokenTable(); - - tokenTable.AddEventHandler(handler); - tokenTable.AddEventHandler(handler); - - tokenTable.RemoveEventHandler(handler); - Assert.Equal(new Delegate[] { handler }, tokenTable.InvocationList.GetInvocationList()); - - tokenTable.RemoveEventHandler(handler); - Assert.Null(tokenTable.InvocationList); - } - - [Fact] - public void RemoveEventHandler_NullDelegate_Nop() - { - var tokenTable = new EventRegistrationTokenTable(); - tokenTable.RemoveEventHandler(null); - } - - [Fact] - public void GetOrCreateEventRegistrationTokenTable_NullTable_ReturnsNewTable() - { - EventRegistrationTokenTable tokenTable = null; - EventRegistrationTokenTable result = EventRegistrationTokenTable.GetOrCreateEventRegistrationTokenTable(ref tokenTable); - Assert.Null(result.InvocationList); - } - - [Fact] - public void GetOrCreateEventRegistrationTokenTable_NonNullTable_ReturnsEventTable() - { - var tokenTable = new EventRegistrationTokenTable(); - EventRegistrationTokenTable result = EventRegistrationTokenTable.GetOrCreateEventRegistrationTokenTable(ref tokenTable); - Assert.Same(tokenTable, result); - } - - [Fact] - public void GetOrCreateEventRegistrationTokenTable_NonDelegateType_ThrowsInvalidOperationException() - { - EventRegistrationTokenTable tokenTable = null; - Assert.Throws(() => EventRegistrationTokenTable.GetOrCreateEventRegistrationTokenTable(ref tokenTable)); - } - - [Fact] - public void InvocationList_SetNull_GetReturnsNull() - { - var tokenTable = new EventRegistrationTokenTable(); - tokenTable.AddEventHandler(new EventHandler(EventHandlerMethod1)); - - tokenTable.InvocationList = null; - Assert.Null(tokenTable.InvocationList); - } - - [Fact] - public void InvocationList_SetDelegate_GetReturnsExpected() - { - Delegate invocationList = new EventHandler(EventHandlerMethod1); - var tokenTable = new EventRegistrationTokenTable() { InvocationList = invocationList }; - - Assert.Equal(new Delegate[] { invocationList }, tokenTable.InvocationList.GetInvocationList()); - } - - private static void EventHandlerMethod1(object sender, EventArgs e) { } - private static void EventHandlerMethod2(object sender, EventArgs e) { } - } -} diff --git a/src/libraries/System.Runtime.InteropServices.WindowsRuntime/tests/System/Runtime/InteropServices/WindowsRuntime/EventRegistrationTokenTests.cs b/src/libraries/System.Runtime.InteropServices.WindowsRuntime/tests/System/Runtime/InteropServices/WindowsRuntime/EventRegistrationTokenTests.cs deleted file mode 100644 index 6be9734..0000000 --- a/src/libraries/System.Runtime.InteropServices.WindowsRuntime/tests/System/Runtime/InteropServices/WindowsRuntime/EventRegistrationTokenTests.cs +++ /dev/null @@ -1,44 +0,0 @@ -// 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.Generic; -using Xunit; - -namespace System.Runtime.InteropServices.WindowsRuntime.Tests -{ - [ActiveIssue("https://github.com/dotnet/runtime/issues/34749", TestPlatforms.Windows, TargetFrameworkMonikers.Netcoreapp, TestRuntimes.Mono)] - public class EventRegistrationTokenTests - { - public static IEnumerable Equals_TestData() - { - var tokenTable = new EventRegistrationTokenTable(); - EventRegistrationToken token = tokenTable.AddEventHandler(new EventHandler(EventHandlerMethod1)); - EventRegistrationToken emptyToken = tokenTable.AddEventHandler(null); - - yield return new object[] { token, token, true }; - yield return new object[] { token, emptyToken, false }; - yield return new object[] { emptyToken, emptyToken, true }; - yield return new object[] { emptyToken, new EventRegistrationToken(), true }; - - yield return new object[] { token, new object(), false }; - yield return new object[] { token, null, false }; - } - - [Theory] - [MemberData(nameof(Equals_TestData))] - public void Equals_Object_ReturnsExpected(EventRegistrationToken token, object other, bool expected) - { - Assert.Equal(expected, token.Equals(other)); - if (other is EventRegistrationToken otherToken) - { - Assert.Equal(expected, token == otherToken); - Assert.Equal(!expected, token != otherToken); - Assert.Equal(expected, token.GetHashCode().Equals(other.GetHashCode())); - } - } - - private static void EventHandlerMethod1(object sender, EventArgs e) { } - private static void EventHandlerMethod2(object sender, EventArgs e) { } - } -} diff --git a/src/libraries/System.Runtime.InteropServices.WindowsRuntime/tests/System/Runtime/InteropServices/WindowsRuntime/InterfaceImplementedInVersionAttributeTests.cs b/src/libraries/System.Runtime.InteropServices.WindowsRuntime/tests/System/Runtime/InteropServices/WindowsRuntime/InterfaceImplementedInVersionAttributeTests.cs deleted file mode 100644 index a55554b..0000000 --- a/src/libraries/System.Runtime.InteropServices.WindowsRuntime/tests/System/Runtime/InteropServices/WindowsRuntime/InterfaceImplementedInVersionAttributeTests.cs +++ /dev/null @@ -1,25 +0,0 @@ -// 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 Xunit; - -namespace System.Runtime.InteropServices.WindowsRuntime.Tests -{ - public class InterfaceImplementedInVersionAttributeTests - { - [Theory] - [ActiveIssue("https://github.com/dotnet/runtime/issues/34749", TestPlatforms.Windows, TargetFrameworkMonikers.Netcoreapp, TestRuntimes.Mono)] - [InlineData(null, 0, 0, 0, 0)] - [InlineData(typeof(int), 255, 255, 255, 255)] - public void Ctor_DefaultInterface(Type interfaceType, byte majorVersion, byte minorVersion, byte buildVersion, byte revisionVersion) - { - var attribute = new InterfaceImplementedInVersionAttribute(interfaceType, majorVersion, minorVersion, buildVersion, revisionVersion); - Assert.Equal(interfaceType, attribute.InterfaceType); - Assert.Equal(majorVersion, attribute.MajorVersion); - Assert.Equal(minorVersion, attribute.MinorVersion); - Assert.Equal(buildVersion, attribute.BuildVersion); - Assert.Equal(revisionVersion, attribute.RevisionVersion); - } - } -} diff --git a/src/libraries/System.Runtime.InteropServices.WindowsRuntime/tests/System/Runtime/InteropServices/WindowsRuntime/ReturnValueNameAttributeTests.cs b/src/libraries/System.Runtime.InteropServices.WindowsRuntime/tests/System/Runtime/InteropServices/WindowsRuntime/ReturnValueNameAttributeTests.cs deleted file mode 100644 index 00bcafc..0000000 --- a/src/libraries/System.Runtime.InteropServices.WindowsRuntime/tests/System/Runtime/InteropServices/WindowsRuntime/ReturnValueNameAttributeTests.cs +++ /dev/null @@ -1,20 +0,0 @@ -// 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 Xunit; - -namespace System.Runtime.InteropServices.WindowsRuntime.Tests -{ - public class ReturnValueNameAttributeTests - { - [Theory] - [InlineData(null)] - [InlineData("Name")] - public void Ctor_Name(string name) - { - var attribute = new ReturnValueNameAttribute(name); - Assert.Equal(name, attribute.Name); - } - } -} diff --git a/src/libraries/System.Runtime.InteropServices.WindowsRuntime/tests/System/Runtime/InteropServices/WindowsRuntime/UnixTests.cs b/src/libraries/System.Runtime.InteropServices.WindowsRuntime/tests/System/Runtime/InteropServices/WindowsRuntime/UnixTests.cs deleted file mode 100644 index c4dd9e9..0000000 --- a/src/libraries/System.Runtime.InteropServices.WindowsRuntime/tests/System/Runtime/InteropServices/WindowsRuntime/UnixTests.cs +++ /dev/null @@ -1,89 +0,0 @@ -// 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 Xunit; - -namespace System.Runtime.InteropServices.WindowsRuntime.Tests -{ - public class UnixTests - { - [Fact] - public void DefaultInterfaceAttribute_Ctor_ThrowsPlatformNotSupportedException() - { - Assert.Throws(() => new DefaultInterfaceAttribute(typeof(int))); - } - - [Fact] - public void InterfaceImplementedInVersionAttribute_Ctor_ThrowsPlatformNotSupportedException() - { - Assert.Throws(() => new InterfaceImplementedInVersionAttribute(typeof(int), 1, 2, 3, 4)); - } - - [Fact] - public void ReadOnlyArrayAttribute_Ctor_ThrowsPlatformNotSupportedException() - { - Assert.Throws(() => new ReadOnlyArrayAttribute()); - } - - [Fact] - public void ReturnValueNameAttribute_Ctor_ThrowsPlatformNotSupportedException() - { - Assert.Throws(() => new ReturnValueNameAttribute("Name")); - } - - [Fact] - public void WriteOnlyArrayAttribute_Ctor_ThrowsPlatformNotSupportedException() - { - Assert.Throws(() => new WriteOnlyArrayAttribute()); - } - - [Fact] - public void EventRegistrationTokenTake_Ctor_ThrowsPlatformNotSupportedException() - { - Assert.Throws(() => new EventRegistrationTokenTable()); - } - - [Fact] - public void WindowsRuntimeMarshal_AddEventHandler_ThrowsPlatformNotSupportedException() - { - Assert.Throws(() => WindowsRuntimeMarshal.AddEventHandler(null, null, 0)); - } - - [Fact] - public void WindowsRuntimeMarshal_RemoveEventHandler_ThrowsPlatformNotSupportedException() - { - Assert.Throws(() => WindowsRuntimeMarshal.RemoveEventHandler(null, 0)); - } - - [Fact] - public void WindowsRuntimeMarshal_RemoveAllEventHandlers_ThrowsPlatformNotSupportedException() - { - Assert.Throws(() => WindowsRuntimeMarshal.RemoveAllEventHandlers(null)); - } - - [Fact] - public void WindowsRuntimeMarshal_StringToHString_ThrowsPlatformNotSupportedException() - { - Assert.Throws(() => WindowsRuntimeMarshal.StringToHString(null)); - } - - [Fact] - public void WindowsRuntimeMarshal_PtrToStringHString_ThrowsPlatformNotSupportedException() - { - Assert.Throws(() => WindowsRuntimeMarshal.PtrToStringHString(IntPtr.Zero)); - } - - [Fact] - public void WindowsRuntimeMarshal_FreeHString_ThrowsPlatformNotSupportedException() - { - Assert.Throws(() => WindowsRuntimeMarshal.FreeHString(IntPtr.Zero)); - } - - [Fact] - public void WindowsRuntimeMarshal_GetActivationFactory_ThrowsPlatformNotSupportedException() - { - Assert.Throws(() => WindowsRuntimeMarshal.GetActivationFactory(null)); - } - } -} diff --git a/src/libraries/System.Runtime.InteropServices.WindowsRuntime/tests/System/Runtime/InteropServices/WindowsRuntime/WindowsRuntimeMarshalTests.cs b/src/libraries/System.Runtime.InteropServices.WindowsRuntime/tests/System/Runtime/InteropServices/WindowsRuntime/WindowsRuntimeMarshalTests.cs deleted file mode 100644 index ec82bf6..0000000 --- a/src/libraries/System.Runtime.InteropServices.WindowsRuntime/tests/System/Runtime/InteropServices/WindowsRuntime/WindowsRuntimeMarshalTests.cs +++ /dev/null @@ -1,324 +0,0 @@ -// 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.Generic; -using Xunit; - -namespace System.Runtime.InteropServices.WindowsRuntime.Tests -{ - [ActiveIssue("https://github.com/dotnet/runtime/issues/34749", TestPlatforms.Windows, TargetFrameworkMonikers.Netcoreapp, TestRuntimes.Mono)] - public class WindowsRuntimeMarshalTests - { - [Fact] - public void AddEventHandler_RemoveMethodHasTarget_Success() - { - bool addMethodCalled = false; - bool removeMethodCalled = false; - Delegate handler = new EventHandler(EventHandlerMethod1); - - Func addMethod = eventHandler => - { - Assert.False(addMethodCalled); - addMethodCalled = true; - Assert.Same(handler, eventHandler); - - return new EventRegistrationToken(); - }; - - WindowsRuntimeMarshal.AddEventHandler(addMethod, token => removeMethodCalled = true, handler); - Assert.True(addMethodCalled); - Assert.False(removeMethodCalled); - } - - [Fact] - public void AddEventHandler_RemoveMethodHasNoTarget_Success() - { - bool removeMethodCalled = false; - ExpectedHandler = new EventHandler(EventHandlerMethod1); - - WindowsRuntimeMarshal.AddEventHandler(AddMethod, token => removeMethodCalled = true, ExpectedHandler); - Assert.True(AddMethodCalled); - Assert.False(removeMethodCalled); - } - - private static bool AddMethodCalled { get; set; } - private static Delegate ExpectedHandler { get; set; } - - private static EventRegistrationToken AddMethod(Delegate eventHandler) - { - Assert.False(AddMethodCalled); - AddMethodCalled = true; - Assert.Same(ExpectedHandler, eventHandler); - - return new EventRegistrationToken(); - } - - [Fact] - public void AddEventHandler_NullHandler_Nop() - { - bool addMethodCalled = false; - bool removeMethodCalled = false; - WindowsRuntimeMarshal.AddEventHandler(eventHandler => { - addMethodCalled = true; - return new EventRegistrationToken(); - }, token => removeMethodCalled = true, null); - - Assert.False(addMethodCalled); - Assert.False(removeMethodCalled); - } - - [Fact] - public void AddEventHandler_NullAddMethod_ThrowsArgumentNullException() - { - AssertExtensions.Throws("addMethod", () => WindowsRuntimeMarshal.AddEventHandler(null, token => { }, new EventHandler(EventHandlerMethod1))); - } - - [Fact] - public void AddEventHandler_NullRemoveMethod_ThrowsArgumentNullException() - { - AssertExtensions.Throws("removeMethod", () => WindowsRuntimeMarshal.AddEventHandler(eventHandler => new EventRegistrationToken(), null, new EventHandler(EventHandlerMethod1))); - } - - [Fact] - public void RemoveEventHandler_RemoveMethodHasTarget_Success() - { - bool removeMethodCalled = false; - Delegate handler = new EventHandler(EventHandlerMethod1); - - var tokenTable = new EventRegistrationTokenTable(); - EventRegistrationToken addToken = tokenTable.AddEventHandler(handler); - - Action removeMethod = token => - { - Assert.False(removeMethodCalled); - removeMethodCalled = true; - Assert.Equal(addToken, token); - }; - WindowsRuntimeMarshal.AddEventHandler(eventHandler => addToken, removeMethod, handler); - - // Removing with the same handler but with a different method is a nop. - WindowsRuntimeMarshal.RemoveEventHandler(token => removeMethodCalled = true, handler); - Assert.False(removeMethodCalled); - - WindowsRuntimeMarshal.RemoveEventHandler(DifferentRemoveMethod, handler); - Assert.False(removeMethodCalled); - - // Removing with a different handler but with the same method is a nop. - WindowsRuntimeMarshal.RemoveEventHandler(removeMethod, new EventHandler(EventHandlerMethod2)); - Assert.False(removeMethodCalled); - - // Removing the same handler and the same method works. - WindowsRuntimeMarshal.RemoveEventHandler(removeMethod, handler); - Assert.True(removeMethodCalled); - } - - [Fact] - public void RemoveEventHandler_RemoveMethodHasNoTarget_Success() - { - Delegate handler = new EventHandler(EventHandlerMethod1); - - var tokenTable = new EventRegistrationTokenTable(); - ExpectedRemoveToken = tokenTable.AddEventHandler(handler); - - Action removeMethod = RemoveMethod; - WindowsRuntimeMarshal.AddEventHandler(eventHandler => ExpectedRemoveToken, removeMethod, handler); - - // Removing with the same handler but with a different method is a nop. - WindowsRuntimeMarshal.RemoveEventHandler(token => RemoveMethodCalled = true, handler); - Assert.False(RemoveMethodCalled); - - WindowsRuntimeMarshal.RemoveEventHandler(DifferentRemoveMethod, handler); - Assert.False(RemoveMethodCalled); - - // Removing with a different handler but with the same method is a nop. - WindowsRuntimeMarshal.RemoveEventHandler(removeMethod, new EventHandler(EventHandlerMethod2)); - Assert.False(RemoveMethodCalled); - - // Removing the same handler and the same method works. - WindowsRuntimeMarshal.RemoveEventHandler(removeMethod, handler); - Assert.True(RemoveMethodCalled); - } - - private static EventRegistrationToken ExpectedRemoveToken { get; set; } - private static bool RemoveMethodCalled { get; set; } - - private static void RemoveMethod(EventRegistrationToken token) - { - Assert.False(RemoveMethodCalled); - RemoveMethodCalled = true; - Assert.Equal(ExpectedRemoveToken, token); - } - - private static void DifferentRemoveMethod(EventRegistrationToken token) => RemoveMethodCalled = true; - - [Fact] - public void RemoveEventHandler_NullHandler_Nop() - { - bool removeMethodCalled = false; - Delegate handler = new EventHandler(EventHandlerMethod1); - - var tokenTable = new EventRegistrationTokenTable(); - EventRegistrationToken addToken = tokenTable.AddEventHandler(handler); - - Action removeMethod = token => removeMethodCalled = true; - WindowsRuntimeMarshal.AddEventHandler(eventHandler => addToken, removeMethod, handler); - - WindowsRuntimeMarshal.RemoveEventHandler(removeMethod, null); - Assert.False(removeMethodCalled); - } - - [Fact] - public void RemoveEventHandler_NullRemoveMethod_ThrowsArgumentNullException() - { - AssertExtensions.Throws("removeMethod", () => WindowsRuntimeMarshal.RemoveEventHandler(null, new EventHandler(EventHandlerMethod1))); - } - - [Fact] - public void RemoveAllEventHandlers_RemoveMethodHasTarget_Success() - { - Delegate handler = new EventHandler(EventHandlerMethod1); - - var tokenTable = new EventRegistrationTokenTable(); - EventRegistrationToken token1 = tokenTable.AddEventHandler(handler); - EventRegistrationToken token2 = tokenTable.AddEventHandler(handler); - EventRegistrationToken token3 = tokenTable.AddEventHandler(handler); - - var removedTokens = new List(); - Action removeMethod = token => removedTokens.Add(token); - - WindowsRuntimeMarshal.AddEventHandler(eventHandler => token1, removeMethod, handler); - WindowsRuntimeMarshal.AddEventHandler(eventHandler => token2, removeMethod, handler); - - bool removeMethodWithTargetCalled = false; - WindowsRuntimeMarshal.AddEventHandler(eventHandler => token3, token => removeMethodWithTargetCalled = false, handler); - - // Removing with the same handler but with a different method is a nop. - WindowsRuntimeMarshal.RemoveAllEventHandlers(token => RemoveMethodCalled = true); - Assert.Empty(removedTokens); - Assert.False(DifferentRemoveAllMethodCalled); - Assert.False(removeMethodWithTargetCalled); - - WindowsRuntimeMarshal.RemoveAllEventHandlers(DifferentRemoveAllMethod); - Assert.Empty(removedTokens); - Assert.False(DifferentRemoveAllMethodCalled); - Assert.False(removeMethodWithTargetCalled); - - // Removing the same handler and the same method works. - WindowsRuntimeMarshal.RemoveAllEventHandlers(removeMethod); - Assert.Equal(new EventRegistrationToken[] { token1, token2 }, removedTokens); - Assert.False(DifferentRemoveAllMethodCalled); - Assert.False(removeMethodWithTargetCalled); - } - - [Fact] - public void RemoveAllEventHandlers_RemoveMethodHasNoTarget_Success() - { - Delegate handler = new EventHandler(EventHandlerMethod1); - - var tokenTable = new EventRegistrationTokenTable(); - EventRegistrationToken token1 = tokenTable.AddEventHandler(handler); - EventRegistrationToken token2 = tokenTable.AddEventHandler(handler); - EventRegistrationToken token3 = tokenTable.AddEventHandler(handler); - - Action removeMethod = RemoveAllMethod; - WindowsRuntimeMarshal.AddEventHandler(eventHandler => token1, removeMethod, handler); - WindowsRuntimeMarshal.AddEventHandler(eventHandler => token2, removeMethod, handler); - - bool removeMethodWithTargetCalled = false; - WindowsRuntimeMarshal.AddEventHandler(eventHandler => token3, token => removeMethodWithTargetCalled = false, handler); - - // Removing with the same handler but with a different method is a nop. - WindowsRuntimeMarshal.RemoveAllEventHandlers(token => RemoveMethodCalled = true); - Assert.Empty(RemoveAllTokens); - Assert.False(DifferentRemoveAllMethodCalled); - Assert.False(removeMethodWithTargetCalled); - - WindowsRuntimeMarshal.RemoveAllEventHandlers(DifferentRemoveAllMethod); - Assert.Empty(RemoveAllTokens); - Assert.False(DifferentRemoveAllMethodCalled); - Assert.False(removeMethodWithTargetCalled); - - // Removing the same handler and the same method works. - WindowsRuntimeMarshal.RemoveAllEventHandlers(removeMethod); - Assert.Equal(new EventRegistrationToken[] { token1, token2 }, RemoveAllTokens); - Assert.False(DifferentRemoveAllMethodCalled); - Assert.False(removeMethodWithTargetCalled); - } - - private static List RemoveAllTokens { get; } = new List(); - private static void RemoveAllMethod(EventRegistrationToken token) => RemoveAllTokens.Add(token); - - private static bool DifferentRemoveAllMethodCalled { get; set; } - private static void DifferentRemoveAllMethod(EventRegistrationToken token) => DifferentRemoveAllMethodCalled = true; - - [Fact] - public void RemoveAllEventHandlers_NullRemoveMethod_ThrowsArgumentNullException() - { - AssertExtensions.Throws("removeMethod", () => WindowsRuntimeMarshal.RemoveAllEventHandlers(null)); - } - - [ConditionalTheory(typeof(PlatformDetection), nameof(PlatformDetection.IsWinRTSupported))] - [InlineData("")] - [InlineData("HString")] - public void StringToHString_PtrToHString_ReturnsExpected(string s) - { - IntPtr ptr = WindowsRuntimeMarshal.StringToHString(s); - try - { - if (s.Length == 0) - { - Assert.Equal(IntPtr.Zero, ptr); - } - else - { - Assert.NotEqual(IntPtr.Zero, ptr); - } - Assert.Equal(s, WindowsRuntimeMarshal.PtrToStringHString(ptr)); - } - finally - { - WindowsRuntimeMarshal.FreeHString(ptr); - } - } - - [ConditionalFact(typeof(PlatformDetection), nameof(PlatformDetection.IsWinRTSupported))] - public void StringToHString_NullString_ThrowsArgumentNullException() - { - AssertExtensions.Throws("s", () => WindowsRuntimeMarshal.StringToHString(null)); - } - - [ConditionalFact(typeof(PlatformDetection), nameof(PlatformDetection.IsNotWinRTSupported))] - public void StringToHString_WinRTNotSupported_ThrowsPlatformNotSupportedException() - { - Assert.Throws(() => WindowsRuntimeMarshal.StringToHString(null)); - } - - [ConditionalFact(typeof(PlatformDetection), nameof(PlatformDetection.IsNotWinRTSupported))] - public void PtrToStringHString_WinRTNotSupported_ThrowsPlatformNotSupportedException() - { - Assert.Throws(() => WindowsRuntimeMarshal.PtrToStringHString(IntPtr.Zero)); - } - - [ConditionalFact(typeof(PlatformDetection), nameof(PlatformDetection.IsNotWinRTSupported))] - public void FreeHString_WinRTNotSupported_ThrowsPlatformNotSupportedException() - { - Assert.Throws(() => WindowsRuntimeMarshal.FreeHString(IntPtr.Zero)); - } - - [Fact] - public void GetActivationFactory_NullType_ThrowsArgumentNullException() - { - AssertExtensions.Throws("type", () => WindowsRuntimeMarshal.GetActivationFactory(null)); - } - - [Fact] - public void GetActivationFactory_NotExportedType_ThrowsArgumentException() - { - AssertExtensions.Throws("type", () => WindowsRuntimeMarshal.GetActivationFactory(typeof(int))); - } - - private static void EventHandlerMethod1(object sender, EventArgs e) { } - private static void EventHandlerMethod2(object sender, EventArgs e) { } - } -} diff --git a/src/libraries/System.Runtime.InteropServices/tests/System/Runtime/InteropServices/Marshal/ChangeWrapperHandleStrengthTests.Windows.cs b/src/libraries/System.Runtime.InteropServices/tests/System/Runtime/InteropServices/Marshal/ChangeWrapperHandleStrengthTests.Windows.cs index c24508e..a3cf340 100644 --- a/src/libraries/System.Runtime.InteropServices/tests/System/Runtime/InteropServices/Marshal/ChangeWrapperHandleStrengthTests.Windows.cs +++ b/src/libraries/System.Runtime.InteropServices/tests/System/Runtime/InteropServices/Marshal/ChangeWrapperHandleStrengthTests.Windows.cs @@ -17,7 +17,6 @@ namespace System.Runtime.InteropServices.Tests yield return new object[] { new DualComObject() }; yield return new object[] { new IUnknownComObject() }; yield return new object[] { new IDispatchComObject() }; - yield return new object[] { new IInspectableComObject() }; yield return new object[] { new NonDualComObject() }; yield return new object[] { new AutoDispatchComObject() }; diff --git a/src/libraries/System.Runtime.InteropServices/tests/System/Runtime/InteropServices/Marshal/Common/CommonTypes.Windows.cs b/src/libraries/System.Runtime.InteropServices/tests/System/Runtime/InteropServices/Marshal/Common/CommonTypes.Windows.cs index 7bb32c0..867392b 100644 --- a/src/libraries/System.Runtime.InteropServices/tests/System/Runtime/InteropServices/Marshal/Common/CommonTypes.Windows.cs +++ b/src/libraries/System.Runtime.InteropServices/tests/System/Runtime/InteropServices/Marshal/Common/CommonTypes.Windows.cs @@ -60,6 +60,8 @@ namespace System.Runtime.InteropServices.Tests.Common [ClassInterface(ClassInterfaceType.None)] public class IInspectableComObject : IInspectableInterface { } + public class IInspectableManagedObject : IInspectableInterface {} + public class SubComImportObject : ComImportObject { } public class GenericSubComImportObject : ComImportObject { } diff --git a/src/libraries/System.Runtime.InteropServices/tests/System/Runtime/InteropServices/Marshal/GetIDispatchForObjectTests.Windows.cs b/src/libraries/System.Runtime.InteropServices/tests/System/Runtime/InteropServices/Marshal/GetIDispatchForObjectTests.Windows.cs index ba3c0e5..7fe9ccc 100644 --- a/src/libraries/System.Runtime.InteropServices/tests/System/Runtime/InteropServices/Marshal/GetIDispatchForObjectTests.Windows.cs +++ b/src/libraries/System.Runtime.InteropServices/tests/System/Runtime/InteropServices/Marshal/GetIDispatchForObjectTests.Windows.cs @@ -42,5 +42,11 @@ namespace System.Runtime.InteropServices.Tests Marshal.Release(ptr); } } + + [ConditionalFact(typeof(PlatformDetection), nameof (PlatformDetection.IsNotWindowsNanoServer))] + public void GetIDispatchForObject_ManagedIInspectableObject_Fail() + { + Assert.Throws(() => Marshal.GetIDispatchForObject(new IInspectableManagedObject())); + } } } diff --git a/src/libraries/System.Runtime.InteropServices/tests/System/Runtime/InteropServices/Marshal/GetNativeVariantForObjectTests.Windows.cs b/src/libraries/System.Runtime.InteropServices/tests/System/Runtime/InteropServices/Marshal/GetNativeVariantForObjectTests.Windows.cs index da77206..1f8b168 100644 --- a/src/libraries/System.Runtime.InteropServices/tests/System/Runtime/InteropServices/Marshal/GetNativeVariantForObjectTests.Windows.cs +++ b/src/libraries/System.Runtime.InteropServices/tests/System/Runtime/InteropServices/Marshal/GetNativeVariantForObjectTests.Windows.cs @@ -100,8 +100,6 @@ namespace System.Runtime.InteropServices.Tests yield return new object[] { new DualComObject[] { new DualComObject() } }; yield return new object[] { new IUnknownComObject[] { new IUnknownComObject(), null } }; yield return new object[] { new IDispatchComObject[] { new IDispatchComObject(), null } }; - yield return new object[] { new IInspectableComObject[] { new IInspectableComObject(), null } }; - yield return new object[] { new NonDualComObject[] { new NonDualComObject(), null } }; yield return new object[] { new AutoDispatchComObject[] { new AutoDispatchComObject(), null } }; yield return new object[] { new AutoDualComObject[] { new AutoDualComObject(), null } }; diff --git a/src/libraries/System.Runtime.InteropServices/tests/System/Runtime/InteropServices/Marshal/GetStartComSlotTests.Windows.cs b/src/libraries/System.Runtime.InteropServices/tests/System/Runtime/InteropServices/Marshal/GetStartComSlotTests.Windows.cs index bb4addb..1c3220d 100644 --- a/src/libraries/System.Runtime.InteropServices/tests/System/Runtime/InteropServices/Marshal/GetStartComSlotTests.Windows.cs +++ b/src/libraries/System.Runtime.InteropServices/tests/System/Runtime/InteropServices/Marshal/GetStartComSlotTests.Windows.cs @@ -21,11 +21,9 @@ namespace System.Runtime.InteropServices.Tests yield return new object[] { typeof(DualInterface), 7}; yield return new object[] { typeof(IUnknownInterface), 3}; yield return new object[] { typeof(IDispatchInterface), 7}; - yield return new object[] { typeof(IInspectableInterface), 6}; yield return new object[] { typeof(DualComObject), 7}; yield return new object[] { typeof(IUnknownComObject), 3}; yield return new object[] { typeof(IDispatchComObject), 7}; - yield return new object[] { typeof(IInspectableComObject), 6}; yield return new object[] { typeof(NonDualComObject), 7}; yield return new object[] { typeof(AutoDispatchComObject), 7}; yield return new object[] { typeof(AutoDualComObject), 7}; @@ -48,5 +46,12 @@ namespace System.Runtime.InteropServices.Tests { Assert.Equal(expected, Marshal.GetStartComSlot(type)); } + + + [ConditionalFact(typeof(PlatformDetection), nameof (PlatformDetection.IsNotWindowsNanoServer))] + public void GetStartComSlot_ManagedIInspectableObject_Fail() + { + Assert.Throws(() => Marshal.GetStartComSlot(typeof(IInspectableInterface))); + } } } diff --git a/src/libraries/System.Runtime.InteropServices/tests/System/Runtime/InteropServices/Marshal/QueryInterfaceTests.Windows.cs b/src/libraries/System.Runtime.InteropServices/tests/System/Runtime/InteropServices/Marshal/QueryInterfaceTests.Windows.cs index 026ac38..f25e5ba 100644 --- a/src/libraries/System.Runtime.InteropServices/tests/System/Runtime/InteropServices/Marshal/QueryInterfaceTests.Windows.cs +++ b/src/libraries/System.Runtime.InteropServices/tests/System/Runtime/InteropServices/Marshal/QueryInterfaceTests.Windows.cs @@ -10,6 +10,8 @@ namespace System.Runtime.InteropServices.Tests { public partial class QueryInterfaceTests { + public const string IID_IINSPECTABLE = "AF86E2E0-B12D-4c6a-9C5A-D7AA65101E90"; + public static IEnumerable QueryInterface_ValidComObjectInterface_TestData() { yield return new object[] { new ComImportObject(), IID_IUNKNOWN }; @@ -21,8 +23,6 @@ namespace System.Runtime.InteropServices.Tests yield return new object[] { new IUnknownComObject(), IID_IDISPATCH }; yield return new object[] { new IDispatchComObject(), IID_IUNKNOWN }; yield return new object[] { new IDispatchComObject(), IID_IDISPATCH }; - yield return new object[] { new IInspectableComObject(), IID_IUNKNOWN }; - yield return new object[] { new IInspectableComObject(), IID_IDISPATCH }; yield return new object[] { new NonDualComObject(), IID_IUNKNOWN }; yield return new object[] { new NonDualComObject(), IID_IDISPATCH }; diff --git a/src/libraries/System.Runtime.InteropServices/tests/System/Runtime/InteropServices/Marshal/QueryInterfaceTests.cs b/src/libraries/System.Runtime.InteropServices/tests/System/Runtime/InteropServices/Marshal/QueryInterfaceTests.cs index e1c72ee..a18b3a9 100644 --- a/src/libraries/System.Runtime.InteropServices/tests/System/Runtime/InteropServices/Marshal/QueryInterfaceTests.cs +++ b/src/libraries/System.Runtime.InteropServices/tests/System/Runtime/InteropServices/Marshal/QueryInterfaceTests.cs @@ -14,69 +14,54 @@ namespace System.Runtime.InteropServices.Tests public const int E_NOINTERFACE = unchecked((int)0x80004002); public const string IID_IUNKNOWN = "00000000-0000-0000-C000-000000000046"; public const string IID_IDISPATCH = "00020400-0000-0000-C000-000000000046"; - public const string IID_IINSPECTABLE = "AF86E2E0-B12D-4c6a-9C5A-D7AA65101E90"; - public const string IID_IKEYVALUEPAIR = "02b51929-c1c4-4a7e-8940-0312b5c18500"; public static IEnumerable QueryInterface_ValidInterface_TestData() { yield return new object[] { new object(), IID_IUNKNOWN }; yield return new object[] { new object(), IID_IDISPATCH }; - yield return new object[] { new object(), IID_IINSPECTABLE }; yield return new object[] { 10, IID_IUNKNOWN }; if (!PlatformDetection.IsNetCore) { yield return new object[] { 10, IID_IDISPATCH }; } - yield return new object[] { 10, IID_IINSPECTABLE }; yield return new object[] { "string", IID_IUNKNOWN }; if (!PlatformDetection.IsNetCore) { yield return new object[] { "string", IID_IDISPATCH }; } - yield return new object[] { "string", IID_IINSPECTABLE }; yield return new object[] { new NonGenericClass(), IID_IUNKNOWN }; if (!PlatformDetection.IsNetCore) { yield return new object[] { new NonGenericClass(), IID_IDISPATCH }; } - yield return new object[] { new NonGenericClass(), IID_IINSPECTABLE }; yield return new object[] { new GenericClass(), IID_IUNKNOWN }; - yield return new object[] { new GenericClass(), IID_IINSPECTABLE }; yield return new object[] { new NonGenericStruct(), IID_IUNKNOWN }; if (!PlatformDetection.IsNetCore) { yield return new object[] { new NonGenericStruct(), IID_IDISPATCH }; } - yield return new object[] { new NonGenericStruct(), IID_IINSPECTABLE }; yield return new object[] { new GenericStruct(), IID_IUNKNOWN }; - yield return new object[] { new GenericStruct(), IID_IINSPECTABLE }; yield return new object[] { Int32Enum.Value1, IID_IUNKNOWN }; if (!PlatformDetection.IsNetCore) { yield return new object[] { Int32Enum.Value1, IID_IDISPATCH }; } - yield return new object[] { Int32Enum.Value1, IID_IINSPECTABLE }; yield return new object[] { new int[] { 10 }, IID_IUNKNOWN }; - yield return new object[] { new int[] { 10 }, IID_IINSPECTABLE }; yield return new object[] { new int[][] { new int[] { 10 } }, IID_IUNKNOWN }; - yield return new object[] { new int[][] { new int[] { 10 } }, IID_IINSPECTABLE }; yield return new object[] { new int[,] { { 10 } }, IID_IUNKNOWN }; - yield return new object[] { new int[,] { { 10 } }, IID_IINSPECTABLE }; MethodInfo method = typeof(GetObjectForIUnknownTests).GetMethod(nameof(NonGenericMethod), BindingFlags.NonPublic | BindingFlags.Static); Delegate d = method.CreateDelegate(typeof(NonGenericDelegate)); yield return new object[] { d, IID_IUNKNOWN }; yield return new object[] { d, IID_IDISPATCH }; - yield return new object[] { d, IID_IINSPECTABLE }; yield return new object[] { new KeyValuePair("key", 10), IID_IUNKNOWN }; - yield return new object[] { new KeyValuePair("key", 10), IID_IINSPECTABLE }; } [Theory] @@ -118,7 +103,6 @@ namespace System.Runtime.InteropServices.Tests yield return new object[] { new Dictionary(), IID_IDISPATCH }; yield return new object[] { new GenericStruct(), IID_IDISPATCH }; yield return new object[] { new KeyValuePair(), IID_IDISPATCH }; - yield return new object[] { new KeyValuePair("key", 10), IID_IKEYVALUEPAIR }; } [Theory] diff --git a/src/libraries/System.Runtime.WindowsRuntime.UI.Xaml/Directory.Build.props b/src/libraries/System.Runtime.WindowsRuntime.UI.Xaml/Directory.Build.props deleted file mode 100644 index 940bc0c..0000000 --- a/src/libraries/System.Runtime.WindowsRuntime.UI.Xaml/Directory.Build.props +++ /dev/null @@ -1,9 +0,0 @@ - - - - 4.0.4.0 - ECMA - true - false - - \ No newline at end of file diff --git a/src/libraries/System.Runtime.WindowsRuntime.UI.Xaml/System.Runtime.WindowsRuntime.UI.Xaml.sln b/src/libraries/System.Runtime.WindowsRuntime.UI.Xaml/System.Runtime.WindowsRuntime.UI.Xaml.sln deleted file mode 100644 index ae40513..0000000 --- a/src/libraries/System.Runtime.WindowsRuntime.UI.Xaml/System.Runtime.WindowsRuntime.UI.Xaml.sln +++ /dev/null @@ -1,60 +0,0 @@ -Microsoft Visual Studio Solution File, Format Version 12.00 -# Visual Studio 15 -VisualStudioVersion = 15.0.27213.1 -MinimumVisualStudioVersion = 10.0.40219.1 -Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "System.Runtime.WindowsRuntime.UI.Xaml.Tests", "tests\System.Runtime.WindowsRuntime.UI.Xaml.Tests.csproj", "{69FC7EB5-64FD-4464-88B1-B8ADD3870640}" - ProjectSection(ProjectDependencies) = postProject - {263DA4F1-C3BC-4B43-98E7-9F38B419A131} = {263DA4F1-C3BC-4B43-98E7-9F38B419A131} - EndProjectSection -EndProject -Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "System.Runtime.WindowsRuntime.UI.Xaml", "src\System.Runtime.WindowsRuntime.UI.Xaml.csproj", "{263DA4F1-C3BC-4B43-98E7-9F38B419A131}" - ProjectSection(ProjectDependencies) = postProject - {AA1600B8-C4D3-42A9-A28A-04D0C8282566} = {AA1600B8-C4D3-42A9-A28A-04D0C8282566} - EndProjectSection -EndProject -Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "System.Runtime.WindowsRuntime.UI.Xaml", "ref\System.Runtime.WindowsRuntime.UI.Xaml.csproj", "{AA1600B8-C4D3-42A9-A28A-04D0C8282566}" -EndProject -Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "tests", "tests", "{1A2F9F4A-A032-433E-B914-ADD5992BB178}" -EndProject -Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "src", "src", "{E107E9C1-E893-4E87-987E-04EF0DCEAEFD}" -EndProject -Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "ref", "ref", "{2E666815-2EDB-464B-9DF6-380BF4789AD4}" -EndProject -Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "TestUtilities", "..\Common\tests\TestUtilities\TestUtilities.csproj", "{AB5B0B7D-C85B-4830-8EF2-DAE3F000104D}" -EndProject -Global - GlobalSection(SolutionConfigurationPlatforms) = preSolution - Debug|Any CPU = Debug|Any CPU - Release|Any CPU = Release|Any CPU - EndGlobalSection - GlobalSection(ProjectConfigurationPlatforms) = postSolution - {69FC7EB5-64FD-4464-88B1-B8ADD3870640}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {69FC7EB5-64FD-4464-88B1-B8ADD3870640}.Debug|Any CPU.Build.0 = Debug|Any CPU - {69FC7EB5-64FD-4464-88B1-B8ADD3870640}.Release|Any CPU.ActiveCfg = Release|Any CPU - {69FC7EB5-64FD-4464-88B1-B8ADD3870640}.Release|Any CPU.Build.0 = Release|Any CPU - {263DA4F1-C3BC-4B43-98E7-9F38B419A131}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {263DA4F1-C3BC-4B43-98E7-9F38B419A131}.Debug|Any CPU.Build.0 = Debug|Any CPU - {263DA4F1-C3BC-4B43-98E7-9F38B419A131}.Release|Any CPU.ActiveCfg = Release|Any CPU - {263DA4F1-C3BC-4B43-98E7-9F38B419A131}.Release|Any CPU.Build.0 = Release|Any CPU - {AA1600B8-C4D3-42A9-A28A-04D0C8282566}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {AA1600B8-C4D3-42A9-A28A-04D0C8282566}.Debug|Any CPU.Build.0 = Debug|Any CPU - {AA1600B8-C4D3-42A9-A28A-04D0C8282566}.Release|Any CPU.ActiveCfg = Release|Any CPU - {AA1600B8-C4D3-42A9-A28A-04D0C8282566}.Release|Any CPU.Build.0 = Release|Any CPU - {AB5B0B7D-C85B-4830-8EF2-DAE3F000104D}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {AB5B0B7D-C85B-4830-8EF2-DAE3F000104D}.Debug|Any CPU.Build.0 = Debug|Any CPU - {AB5B0B7D-C85B-4830-8EF2-DAE3F000104D}.Release|Any CPU.ActiveCfg = Release|Any CPU - {AB5B0B7D-C85B-4830-8EF2-DAE3F000104D}.Release|Any CPU.Build.0 = Release|Any CPU - EndGlobalSection - GlobalSection(SolutionProperties) = preSolution - HideSolutionNode = FALSE - EndGlobalSection - GlobalSection(NestedProjects) = preSolution - {69FC7EB5-64FD-4464-88B1-B8ADD3870640} = {1A2F9F4A-A032-433E-B914-ADD5992BB178} - {263DA4F1-C3BC-4B43-98E7-9F38B419A131} = {E107E9C1-E893-4E87-987E-04EF0DCEAEFD} - {AA1600B8-C4D3-42A9-A28A-04D0C8282566} = {2E666815-2EDB-464B-9DF6-380BF4789AD4} - {AB5B0B7D-C85B-4830-8EF2-DAE3F000104D} = {1A2F9F4A-A032-433E-B914-ADD5992BB178} - EndGlobalSection - GlobalSection(ExtensibilityGlobals) = postSolution - SolutionGuid = {FC561FC1-C012-48C5-9A7A-DD35875B6AB1} - EndGlobalSection -EndGlobal diff --git a/src/libraries/System.Runtime.WindowsRuntime.UI.Xaml/pkg/System.Runtime.WindowsRuntime.UI.Xaml.pkgproj b/src/libraries/System.Runtime.WindowsRuntime.UI.Xaml/pkg/System.Runtime.WindowsRuntime.UI.Xaml.pkgproj deleted file mode 100644 index 85ed5cc..0000000 --- a/src/libraries/System.Runtime.WindowsRuntime.UI.Xaml/pkg/System.Runtime.WindowsRuntime.UI.Xaml.pkgproj +++ /dev/null @@ -1,58 +0,0 @@ - - - - - net461;netcoreapp2.0;uap10.0.16299;$(AllXamarinFrameworks) - - - - - - net45;netcore45;wpa81;netcoreapp1.0 - - - - - .NETCore,Version=v4.5.1;WindowsPhoneApp,Version=v8.1 - - - - - - - - runtimes/win-aot/lib/uap10.0.16299 - - - runtimes/win/lib/uap10.0.16299 - - - - - - - - - - - \build\net45\ - - - \build\net461\ - - - - - - - \ No newline at end of file diff --git a/src/libraries/System.Runtime.WindowsRuntime.UI.Xaml/pkg/build/net45/System.Runtime.WindowsRuntime.UI.Xaml.targets b/src/libraries/System.Runtime.WindowsRuntime.UI.Xaml/pkg/build/net45/System.Runtime.WindowsRuntime.UI.Xaml.targets deleted file mode 100644 index 886c9a2..0000000 --- a/src/libraries/System.Runtime.WindowsRuntime.UI.Xaml/pkg/build/net45/System.Runtime.WindowsRuntime.UI.Xaml.targets +++ /dev/null @@ -1,31 +0,0 @@ - - - - - - - <_HasReferenceToSystemRuntime>true - - - - - false - - false - - - - - - - - - - - diff --git a/src/libraries/System.Runtime.WindowsRuntime.UI.Xaml/pkg/build/net461/System.Runtime.WindowsRuntime.UI.Xaml.targets b/src/libraries/System.Runtime.WindowsRuntime.UI.Xaml/pkg/build/net461/System.Runtime.WindowsRuntime.UI.Xaml.targets deleted file mode 100644 index 21dd94d..0000000 --- a/src/libraries/System.Runtime.WindowsRuntime.UI.Xaml/pkg/build/net461/System.Runtime.WindowsRuntime.UI.Xaml.targets +++ /dev/null @@ -1,31 +0,0 @@ - - - - - - - true - - - - - false - - false - - - - - - - - - - - diff --git a/src/libraries/System.Runtime.WindowsRuntime.UI.Xaml/ref/System.Runtime.WindowsRuntime.UI.Xaml.cs b/src/libraries/System.Runtime.WindowsRuntime.UI.Xaml/ref/System.Runtime.WindowsRuntime.UI.Xaml.cs deleted file mode 100644 index 3a5592a..0000000 --- a/src/libraries/System.Runtime.WindowsRuntime.UI.Xaml/ref/System.Runtime.WindowsRuntime.UI.Xaml.cs +++ /dev/null @@ -1,252 +0,0 @@ -// 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. -// ------------------------------------------------------------------------------ -// Changes to this file must follow the https://aka.ms/api-review process. -// ------------------------------------------------------------------------------ - -namespace Windows.UI.Xaml -{ - public partial struct CornerRadius - { - private int _dummyPrimitive; - public CornerRadius(double uniformRadius) { throw null; } - public CornerRadius(double topLeft, double topRight, double bottomRight, double bottomLeft) { throw null; } - public double BottomLeft { get { throw null; } set { } } - public double BottomRight { get { throw null; } set { } } - public double TopLeft { get { throw null; } set { } } - public double TopRight { get { throw null; } set { } } - public override bool Equals(object? obj) { throw null; } - public bool Equals(Windows.UI.Xaml.CornerRadius cornerRadius) { throw null; } - public override int GetHashCode() { throw null; } - public static bool operator ==(Windows.UI.Xaml.CornerRadius cr1, Windows.UI.Xaml.CornerRadius cr2) { throw null; } - public static bool operator !=(Windows.UI.Xaml.CornerRadius cr1, Windows.UI.Xaml.CornerRadius cr2) { throw null; } - public override string ToString() { throw null; } - } - public partial struct Duration - { - private int _dummyPrimitive; - public Duration(System.TimeSpan timeSpan) { throw null; } - public static Windows.UI.Xaml.Duration Automatic { get { throw null; } } - public static Windows.UI.Xaml.Duration Forever { get { throw null; } } - public bool HasTimeSpan { get { throw null; } } - public System.TimeSpan TimeSpan { get { throw null; } } - public Windows.UI.Xaml.Duration Add(Windows.UI.Xaml.Duration duration) { throw null; } - public static int Compare(Windows.UI.Xaml.Duration t1, Windows.UI.Xaml.Duration t2) { throw null; } - public override bool Equals(object? value) { throw null; } - public bool Equals(Windows.UI.Xaml.Duration duration) { throw null; } - public static bool Equals(Windows.UI.Xaml.Duration t1, Windows.UI.Xaml.Duration t2) { throw null; } - public override int GetHashCode() { throw null; } - public static Windows.UI.Xaml.Duration operator +(Windows.UI.Xaml.Duration t1, Windows.UI.Xaml.Duration t2) { throw null; } - public static bool operator ==(Windows.UI.Xaml.Duration t1, Windows.UI.Xaml.Duration t2) { throw null; } - public static bool operator >(Windows.UI.Xaml.Duration t1, Windows.UI.Xaml.Duration t2) { throw null; } - public static bool operator >=(Windows.UI.Xaml.Duration t1, Windows.UI.Xaml.Duration t2) { throw null; } - public static implicit operator Windows.UI.Xaml.Duration (System.TimeSpan timeSpan) { throw null; } - public static bool operator !=(Windows.UI.Xaml.Duration t1, Windows.UI.Xaml.Duration t2) { throw null; } - public static bool operator <(Windows.UI.Xaml.Duration t1, Windows.UI.Xaml.Duration t2) { throw null; } - public static bool operator <=(Windows.UI.Xaml.Duration t1, Windows.UI.Xaml.Duration t2) { throw null; } - public static Windows.UI.Xaml.Duration operator -(Windows.UI.Xaml.Duration t1, Windows.UI.Xaml.Duration t2) { throw null; } - public static Windows.UI.Xaml.Duration operator +(Windows.UI.Xaml.Duration duration) { throw null; } - public Windows.UI.Xaml.Duration Subtract(Windows.UI.Xaml.Duration duration) { throw null; } - public override string ToString() { throw null; } - } - public enum DurationType - { - Automatic = 0, - TimeSpan = 1, - Forever = 2, - } - public partial struct GridLength - { - private int _dummyPrimitive; - public GridLength(double pixels) { throw null; } - public GridLength(double value, Windows.UI.Xaml.GridUnitType type) { throw null; } - public static Windows.UI.Xaml.GridLength Auto { get { throw null; } } - public Windows.UI.Xaml.GridUnitType GridUnitType { get { throw null; } } - public bool IsAbsolute { get { throw null; } } - public bool IsAuto { get { throw null; } } - public bool IsStar { get { throw null; } } - public double Value { get { throw null; } } - public override bool Equals(object? oCompare) { throw null; } - public bool Equals(Windows.UI.Xaml.GridLength gridLength) { throw null; } - public override int GetHashCode() { throw null; } - public static bool operator ==(Windows.UI.Xaml.GridLength gl1, Windows.UI.Xaml.GridLength gl2) { throw null; } - public static bool operator !=(Windows.UI.Xaml.GridLength gl1, Windows.UI.Xaml.GridLength gl2) { throw null; } - public override string ToString() { throw null; } - } - public enum GridUnitType - { - Auto = 0, - Pixel = 1, - Star = 2, - } - public partial class LayoutCycleException : System.Exception - { - public LayoutCycleException() { } - protected LayoutCycleException(System.Runtime.Serialization.SerializationInfo serializationInfo, System.Runtime.Serialization.StreamingContext streamingContext) { } - public LayoutCycleException(string? message) { } - public LayoutCycleException(string? message, System.Exception? innerException) { } - } - public partial struct Thickness - { - private int _dummyPrimitive; - public Thickness(double uniformLength) { throw null; } - public Thickness(double left, double top, double right, double bottom) { throw null; } - public double Bottom { get { throw null; } set { } } - public double Left { get { throw null; } set { } } - public double Right { get { throw null; } set { } } - public double Top { get { throw null; } set { } } - public override bool Equals(object? obj) { throw null; } - public bool Equals(Windows.UI.Xaml.Thickness thickness) { throw null; } - public override int GetHashCode() { throw null; } - public static bool operator ==(Windows.UI.Xaml.Thickness t1, Windows.UI.Xaml.Thickness t2) { throw null; } - public static bool operator !=(Windows.UI.Xaml.Thickness t1, Windows.UI.Xaml.Thickness t2) { throw null; } - public override string ToString() { throw null; } - } -} -namespace Windows.UI.Xaml.Automation -{ - public partial class ElementNotAvailableException : System.Exception - { - public ElementNotAvailableException() { } - protected ElementNotAvailableException(System.Runtime.Serialization.SerializationInfo serializationInfo, System.Runtime.Serialization.StreamingContext streamingContext) { } - public ElementNotAvailableException(string? message) { } - public ElementNotAvailableException(string? message, System.Exception? innerException) { } - } - public partial class ElementNotEnabledException : System.Exception - { - public ElementNotEnabledException() { } - public ElementNotEnabledException(string? message) { } - public ElementNotEnabledException(string? message, System.Exception? innerException) { } - } -} -namespace Windows.UI.Xaml.Controls.Primitives -{ - public partial struct GeneratorPosition - { - private int _dummyPrimitive; - public GeneratorPosition(int index, int offset) { throw null; } - public int Index { get { throw null; } set { } } - public int Offset { get { throw null; } set { } } - public override bool Equals(object? o) { throw null; } - public override int GetHashCode() { throw null; } - public static bool operator ==(Windows.UI.Xaml.Controls.Primitives.GeneratorPosition gp1, Windows.UI.Xaml.Controls.Primitives.GeneratorPosition gp2) { throw null; } - public static bool operator !=(Windows.UI.Xaml.Controls.Primitives.GeneratorPosition gp1, Windows.UI.Xaml.Controls.Primitives.GeneratorPosition gp2) { throw null; } - public override string ToString() { throw null; } - } -} -namespace Windows.UI.Xaml.Markup -{ - public partial class XamlParseException : System.Exception - { - public XamlParseException() { } - public XamlParseException(string? message) { } - public XamlParseException(string? message, System.Exception? innerException) { } - } -} -namespace Windows.UI.Xaml.Media -{ - public partial struct Matrix : System.IFormattable - { - private int _dummyPrimitive; - public Matrix(double m11, double m12, double m21, double m22, double offsetX, double offsetY) { throw null; } - public static Windows.UI.Xaml.Media.Matrix Identity { get { throw null; } } - public bool IsIdentity { get { throw null; } } - public double M11 { get { throw null; } set { } } - public double M12 { get { throw null; } set { } } - public double M21 { get { throw null; } set { } } - public double M22 { get { throw null; } set { } } - public double OffsetX { get { throw null; } set { } } - public double OffsetY { get { throw null; } set { } } - public override bool Equals(object? o) { throw null; } - public bool Equals(Windows.UI.Xaml.Media.Matrix value) { throw null; } - public override int GetHashCode() { throw null; } - public static bool operator ==(Windows.UI.Xaml.Media.Matrix matrix1, Windows.UI.Xaml.Media.Matrix matrix2) { throw null; } - public static bool operator !=(Windows.UI.Xaml.Media.Matrix matrix1, Windows.UI.Xaml.Media.Matrix matrix2) { throw null; } - string System.IFormattable.ToString(string? format, System.IFormatProvider? provider) { throw null; } - public override string ToString() { throw null; } - public string ToString(System.IFormatProvider? provider) { throw null; } - public Windows.Foundation.Point Transform(Windows.Foundation.Point point) { throw null; } - } -} -namespace Windows.UI.Xaml.Media.Animation -{ - public partial struct KeyTime - { - private int _dummyPrimitive; - public System.TimeSpan TimeSpan { get { throw null; } } - public override bool Equals(object? value) { throw null; } - public bool Equals(Windows.UI.Xaml.Media.Animation.KeyTime value) { throw null; } - public static bool Equals(Windows.UI.Xaml.Media.Animation.KeyTime keyTime1, Windows.UI.Xaml.Media.Animation.KeyTime keyTime2) { throw null; } - public static Windows.UI.Xaml.Media.Animation.KeyTime FromTimeSpan(System.TimeSpan timeSpan) { throw null; } - public override int GetHashCode() { throw null; } - public static bool operator ==(Windows.UI.Xaml.Media.Animation.KeyTime keyTime1, Windows.UI.Xaml.Media.Animation.KeyTime keyTime2) { throw null; } - public static implicit operator Windows.UI.Xaml.Media.Animation.KeyTime (System.TimeSpan timeSpan) { throw null; } - public static bool operator !=(Windows.UI.Xaml.Media.Animation.KeyTime keyTime1, Windows.UI.Xaml.Media.Animation.KeyTime keyTime2) { throw null; } - public override string ToString() { throw null; } - } - public partial struct RepeatBehavior : System.IFormattable - { - private int _dummyPrimitive; - public RepeatBehavior(double count) { throw null; } - public RepeatBehavior(System.TimeSpan duration) { throw null; } - public double Count { get { throw null; } set { } } - public System.TimeSpan Duration { get { throw null; } set { } } - public static Windows.UI.Xaml.Media.Animation.RepeatBehavior Forever { get { throw null; } } - public bool HasCount { get { throw null; } } - public bool HasDuration { get { throw null; } } - public Windows.UI.Xaml.Media.Animation.RepeatBehaviorType Type { get { throw null; } set { } } - public override bool Equals(object? value) { throw null; } - public bool Equals(Windows.UI.Xaml.Media.Animation.RepeatBehavior repeatBehavior) { throw null; } - public static bool Equals(Windows.UI.Xaml.Media.Animation.RepeatBehavior repeatBehavior1, Windows.UI.Xaml.Media.Animation.RepeatBehavior repeatBehavior2) { throw null; } - public override int GetHashCode() { throw null; } - public static bool operator ==(Windows.UI.Xaml.Media.Animation.RepeatBehavior repeatBehavior1, Windows.UI.Xaml.Media.Animation.RepeatBehavior repeatBehavior2) { throw null; } - public static bool operator !=(Windows.UI.Xaml.Media.Animation.RepeatBehavior repeatBehavior1, Windows.UI.Xaml.Media.Animation.RepeatBehavior repeatBehavior2) { throw null; } - string System.IFormattable.ToString(string? format, System.IFormatProvider? formatProvider) { throw null; } - public override string ToString() { throw null; } - public string ToString(System.IFormatProvider? formatProvider) { throw null; } - } - public enum RepeatBehaviorType - { - Count = 0, - Duration = 1, - Forever = 2, - } -} -namespace Windows.UI.Xaml.Media.Media3D -{ - public partial struct Matrix3D : System.IFormattable - { - private int _dummyPrimitive; - public Matrix3D(double m11, double m12, double m13, double m14, double m21, double m22, double m23, double m24, double m31, double m32, double m33, double m34, double offsetX, double offsetY, double offsetZ, double m44) { throw null; } - public bool HasInverse { get { throw null; } } - public static Windows.UI.Xaml.Media.Media3D.Matrix3D Identity { get { throw null; } } - public bool IsIdentity { get { throw null; } } - public double M11 { get { throw null; } set { } } - public double M12 { get { throw null; } set { } } - public double M13 { get { throw null; } set { } } - public double M14 { get { throw null; } set { } } - public double M21 { get { throw null; } set { } } - public double M22 { get { throw null; } set { } } - public double M23 { get { throw null; } set { } } - public double M24 { get { throw null; } set { } } - public double M31 { get { throw null; } set { } } - public double M32 { get { throw null; } set { } } - public double M33 { get { throw null; } set { } } - public double M34 { get { throw null; } set { } } - public double M44 { get { throw null; } set { } } - public double OffsetX { get { throw null; } set { } } - public double OffsetY { get { throw null; } set { } } - public double OffsetZ { get { throw null; } set { } } - public override bool Equals(object? o) { throw null; } - public bool Equals(Windows.UI.Xaml.Media.Media3D.Matrix3D value) { throw null; } - public override int GetHashCode() { throw null; } - public void Invert() { } - public static bool operator ==(Windows.UI.Xaml.Media.Media3D.Matrix3D matrix1, Windows.UI.Xaml.Media.Media3D.Matrix3D matrix2) { throw null; } - public static bool operator !=(Windows.UI.Xaml.Media.Media3D.Matrix3D matrix1, Windows.UI.Xaml.Media.Media3D.Matrix3D matrix2) { throw null; } - public static Windows.UI.Xaml.Media.Media3D.Matrix3D operator *(Windows.UI.Xaml.Media.Media3D.Matrix3D matrix1, Windows.UI.Xaml.Media.Media3D.Matrix3D matrix2) { throw null; } - string System.IFormattable.ToString(string? format, System.IFormatProvider? provider) { throw null; } - public override string ToString() { throw null; } - public string ToString(System.IFormatProvider? provider) { throw null; } - } -} diff --git a/src/libraries/System.Runtime.WindowsRuntime.UI.Xaml/ref/System.Runtime.WindowsRuntime.UI.Xaml.csproj b/src/libraries/System.Runtime.WindowsRuntime.UI.Xaml/ref/System.Runtime.WindowsRuntime.UI.Xaml.csproj deleted file mode 100644 index dfc0e20..0000000 --- a/src/libraries/System.Runtime.WindowsRuntime.UI.Xaml/ref/System.Runtime.WindowsRuntime.UI.Xaml.csproj +++ /dev/null @@ -1,17 +0,0 @@ - - - $(NetCoreAppCurrent);netstandard2.0 - true - enable - - - - - - - - - - - - \ No newline at end of file diff --git a/src/libraries/System.Runtime.WindowsRuntime.UI.Xaml/src/Resources/Strings.resx b/src/libraries/System.Runtime.WindowsRuntime.UI.Xaml/src/Resources/Strings.resx deleted file mode 100644 index 56adff4..0000000 --- a/src/libraries/System.Runtime.WindowsRuntime.UI.Xaml/src/Resources/Strings.resx +++ /dev/null @@ -1,81 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - text/microsoft-resx - - - 2.0 - - - System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 - - - System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 - - - Invalid value for {0} property on CornerRadius. - - - Invalid argument. - - - The element is not available. - - - The element is not enabled. - - - XAML parsing failed. - - - A cycle occurred while laying out the GUI. - - - Windows Runtime (WinRT) is not supported on this platform. - - \ No newline at end of file diff --git a/src/libraries/System.Runtime.WindowsRuntime.UI.Xaml/src/Resources/System.Runtime.WindowsRuntime.UI.Xaml.rd.xml b/src/libraries/System.Runtime.WindowsRuntime.UI.Xaml/src/Resources/System.Runtime.WindowsRuntime.UI.Xaml.rd.xml deleted file mode 100644 index 7f0f85f..0000000 --- a/src/libraries/System.Runtime.WindowsRuntime.UI.Xaml/src/Resources/System.Runtime.WindowsRuntime.UI.Xaml.rd.xml +++ /dev/null @@ -1,10 +0,0 @@ - - - - - - - - - - diff --git a/src/libraries/System.Runtime.WindowsRuntime.UI.Xaml/src/System.Runtime.WindowsRuntime.UI.Xaml.csproj b/src/libraries/System.Runtime.WindowsRuntime.UI.Xaml/src/System.Runtime.WindowsRuntime.UI.Xaml.csproj deleted file mode 100644 index eec5f2a..0000000 --- a/src/libraries/System.Runtime.WindowsRuntime.UI.Xaml/src/System.Runtime.WindowsRuntime.UI.Xaml.csproj +++ /dev/null @@ -1,45 +0,0 @@ - - - $(NetCoreAppCurrent)-Windows_NT;netstandard1.1;netstandard2.0;netcoreapp3.0-Windows_NT - true - enable - - - - SR.PlatformNotSupported_WindowsRuntime - true - 4.0.1.0 - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/src/libraries/System.Runtime.WindowsRuntime.UI.Xaml/src/System/Runtime/InteropServices/HResults.cs b/src/libraries/System.Runtime.WindowsRuntime.UI.Xaml/src/System/Runtime/InteropServices/HResults.cs deleted file mode 100644 index 2f5935e7..0000000 --- a/src/libraries/System.Runtime.WindowsRuntime.UI.Xaml/src/System/Runtime/InteropServices/HResults.cs +++ /dev/null @@ -1,23 +0,0 @@ -// 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; - -namespace System.Runtime.InteropServices -{ - /// - /// mscorlib defines the HRESULT constants it uses in the internal class System.__HResults. - /// Since we cannot use that internal class in this assembly, we define the constants we need - /// in this class. - /// - internal static class HResults - { - internal const int E_XAMLPARSEFAILED = unchecked((int)0x802B000A); - internal const int E_LAYOUTCYCLE = unchecked((int)0x802B0014); - internal const int E_ELEMENTNOTENABLED = unchecked((int)0x802B001E); - internal const int E_ELEMENTNOTAVAILABLE = unchecked((int)0x802B001F); - } // internal static sealed class HResults -} // namespace System.Runtime.InteropServices.WindowsRuntime - -// HResults.cs diff --git a/src/libraries/System.Runtime.WindowsRuntime.UI.Xaml/src/System/Windows/Automation/ElementNotAvailableException.cs b/src/libraries/System.Runtime.WindowsRuntime.UI.Xaml/src/System/Windows/Automation/ElementNotAvailableException.cs deleted file mode 100644 index 5daa094..0000000 --- a/src/libraries/System.Runtime.WindowsRuntime.UI.Xaml/src/System/Windows/Automation/ElementNotAvailableException.cs +++ /dev/null @@ -1,46 +0,0 @@ -// 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: Exception class for representing Jupiter failures of some kind. -** Corresponds with E_ELEMENTNOTAVAILABLE. -** -** -=============================================================================*/ -using System; -using System.Runtime.InteropServices; -using System.Runtime.Serialization; - -namespace Windows.UI.Xaml.Automation -{ - [Serializable] - public class ElementNotAvailableException : Exception - { - public ElementNotAvailableException() - : base(SR.ElementNotAvailable_Default) - { - HResult = HResults.E_ELEMENTNOTAVAILABLE; - } - - public ElementNotAvailableException(string? message) - : base(message) - { - HResult = HResults.E_ELEMENTNOTAVAILABLE; - } - - public ElementNotAvailableException(string? message, Exception? innerException) - : base(message, innerException) - { - HResult = HResults.E_ELEMENTNOTAVAILABLE; - } - - protected ElementNotAvailableException(SerializationInfo serializationInfo, StreamingContext streamingContext) - : base(serializationInfo, streamingContext) - { - } - } -} diff --git a/src/libraries/System.Runtime.WindowsRuntime.UI.Xaml/src/System/Windows/Automation/ElementNotEnabledException.cs b/src/libraries/System.Runtime.WindowsRuntime.UI.Xaml/src/System/Windows/Automation/ElementNotEnabledException.cs deleted file mode 100644 index 4c3d1ac..0000000 --- a/src/libraries/System.Runtime.WindowsRuntime.UI.Xaml/src/System/Windows/Automation/ElementNotEnabledException.cs +++ /dev/null @@ -1,39 +0,0 @@ -// 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: Exception class for representing Jupiter failures of some kind. -** Corresponds with E_ELEMENTNOTENABLED. -** -** -=============================================================================*/ -using System; -using System.Runtime.InteropServices; - -namespace Windows.UI.Xaml.Automation -{ - public class ElementNotEnabledException : Exception - { - public ElementNotEnabledException() - : base(SR.ElementNotEnabled_Default) - { - HResult = HResults.E_ELEMENTNOTENABLED; - } - - public ElementNotEnabledException(string? message) - : base(message) - { - HResult = HResults.E_ELEMENTNOTENABLED; - } - - public ElementNotEnabledException(string? message, Exception? innerException) - : base(message, innerException) - { - HResult = HResults.E_ELEMENTNOTENABLED; - } - } -} diff --git a/src/libraries/System.Runtime.WindowsRuntime.UI.Xaml/src/System/Windows/Controls/Primitives/GeneratorPosition.cs b/src/libraries/System.Runtime.WindowsRuntime.UI.Xaml/src/System/Windows/Controls/Primitives/GeneratorPosition.cs deleted file mode 100644 index 7ef8cce..0000000 --- a/src/libraries/System.Runtime.WindowsRuntime.UI.Xaml/src/System/Windows/Controls/Primitives/GeneratorPosition.cs +++ /dev/null @@ -1,70 +0,0 @@ -// 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.Globalization; -using System.Runtime.InteropServices; - -#pragma warning disable 436 // Redefining types from Windows.Foundation - -namespace Windows.UI.Xaml.Controls.Primitives -{ - // - // GeneratorPosition is the managed projection of Windows.UI.Xaml.Controls.Primitives.GeneratorPosition. - // Any changes to the layout of this type must be exactly mirrored on the native WinRT side as well. - // - // Note that this type is owned by the Jupiter team. Please contact them before making any - // changes here. - // - - [StructLayout(LayoutKind.Sequential)] - public struct GeneratorPosition - { - private int _index; - private int _offset; - - public int Index { get { return _index; } set { _index = value; } } - public int Offset { get { return _offset; } set { _offset = value; } } - - public GeneratorPosition(int index, int offset) - { - _index = index; - _offset = offset; - } - - public override int GetHashCode() - { - return _index.GetHashCode() + _offset.GetHashCode(); - } - - public override string ToString() - { - return string.Concat("GeneratorPosition (", _index.ToString(CultureInfo.InvariantCulture), ",", _offset.ToString(CultureInfo.InvariantCulture), ")"); - } - - public override bool Equals(object? o) - { - if (o is GeneratorPosition) - { - GeneratorPosition that = (GeneratorPosition)o; - return _index == that._index && - _offset == that._offset; - } - return false; - } - - public static bool operator ==(GeneratorPosition gp1, GeneratorPosition gp2) - { - return gp1._index == gp2._index && - gp1._offset == gp2._offset; - } - - public static bool operator !=(GeneratorPosition gp1, GeneratorPosition gp2) - { - return !(gp1 == gp2); - } - } -} - -#pragma warning restore 436 diff --git a/src/libraries/System.Runtime.WindowsRuntime.UI.Xaml/src/System/Windows/CornerRadius.cs b/src/libraries/System.Runtime.WindowsRuntime.UI.Xaml/src/System/Windows/CornerRadius.cs deleted file mode 100644 index 1ecc201..0000000 --- a/src/libraries/System.Runtime.WindowsRuntime.UI.Xaml/src/System/Windows/CornerRadius.cs +++ /dev/null @@ -1,163 +0,0 @@ -// 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.Globalization; -using System.Runtime.InteropServices; -using System.Text; - -#pragma warning disable 436 // Redefining types from Windows.Foundation -namespace Windows.UI.Xaml -{ - // - // CornerRadius is the managed projection of Windows.UI.Xaml.CornerRadius. Any changes to the layout - // of this type must be exactly mirrored on the native WinRT side as well. - // - // Note that this type is owned by the Jupiter team. Please contact them before making any - // changes here. - // - - [StructLayout(LayoutKind.Sequential)] - public struct CornerRadius - { - private double _TopLeft; - private double _TopRight; - private double _BottomRight; - private double _BottomLeft; - - public CornerRadius(double uniformRadius) - { - Validate(uniformRadius, uniformRadius, uniformRadius, uniformRadius); - _TopLeft = _TopRight = _BottomRight = _BottomLeft = uniformRadius; - } - - public CornerRadius(double topLeft, double topRight, double bottomRight, double bottomLeft) - { - Validate(topLeft, topRight, bottomRight, bottomLeft); - - _TopLeft = topLeft; - _TopRight = topRight; - _BottomRight = bottomRight; - _BottomLeft = bottomLeft; - } - - private static void Validate(double topLeft, double topRight, double bottomRight, double bottomLeft) - { - if (topLeft < 0.0 || double.IsNaN(topLeft)) - throw new ArgumentException(SR.Format(SR.DirectUI_CornerRadius_InvalidMember, "TopLeft")); - - if (topRight < 0.0 || double.IsNaN(topRight)) - throw new ArgumentException(SR.Format(SR.DirectUI_CornerRadius_InvalidMember, "TopRight")); - - if (bottomRight < 0.0 || double.IsNaN(bottomRight)) - throw new ArgumentException(SR.Format(SR.DirectUI_CornerRadius_InvalidMember, "BottomRight")); - - if (bottomLeft < 0.0 || double.IsNaN(bottomLeft)) - throw new ArgumentException(SR.Format(SR.DirectUI_CornerRadius_InvalidMember, "BottomLeft")); - } - - public override string ToString() - { - return ToString(CultureInfo.InvariantCulture); - } - - internal string ToString(CultureInfo? cultureInfo) - { - char listSeparator = TokenizerHelper.GetNumericListSeparator(cultureInfo); - - // Initial capacity [64] is an estimate based on a sum of: - // 48 = 4x double (twelve digits is generous for the range of values likely) - // 8 = 4x Unit Type string (approx two characters) - // 4 = 4x separator characters - StringBuilder sb = new StringBuilder(64); - - sb.Append(InternalToString(_TopLeft, cultureInfo)); - sb.Append(listSeparator); - sb.Append(InternalToString(_TopRight, cultureInfo)); - sb.Append(listSeparator); - sb.Append(InternalToString(_BottomRight, cultureInfo)); - sb.Append(listSeparator); - sb.Append(InternalToString(_BottomLeft, cultureInfo)); - return sb.ToString(); - } - - internal string InternalToString(double l, CultureInfo? cultureInfo) - { - if (double.IsNaN(l)) return "Auto"; - return Convert.ToString(l, cultureInfo); - } - - public override bool Equals(object? obj) - { - if (obj is CornerRadius) - { - CornerRadius otherObj = (CornerRadius)obj; - return (this == otherObj); - } - return (false); - } - - public bool Equals(CornerRadius cornerRadius) - { - return (this == cornerRadius); - } - - public override int GetHashCode() - { - return _TopLeft.GetHashCode() ^ _TopRight.GetHashCode() ^ _BottomLeft.GetHashCode() ^ _BottomRight.GetHashCode(); - } - - public static bool operator ==(CornerRadius cr1, CornerRadius cr2) - { - return cr1._TopLeft == cr2._TopLeft && cr1._TopRight == cr2._TopRight && cr1._BottomRight == cr2._BottomRight && cr1._BottomLeft == cr2._BottomLeft; - } - - public static bool operator !=(CornerRadius cr1, CornerRadius cr2) - { - return (!(cr1 == cr2)); - } - - public double TopLeft - { - get { return _TopLeft; } - set - { - Validate(value, 0, 0, 0); - _TopLeft = value; - } - } - - public double TopRight - { - get { return _TopRight; } - set - { - Validate(0, value, 0, 0); - _TopRight = value; - } - } - - public double BottomRight - { - get { return _BottomRight; } - set - { - Validate(0, 0, value, 0); - _BottomRight = value; - } - } - - public double BottomLeft - { - get { return _BottomLeft; } - set - { - Validate(0, 0, 0, value); - _BottomLeft = value; - } - } - } -} - -#pragma warning restore 436 diff --git a/src/libraries/System.Runtime.WindowsRuntime.UI.Xaml/src/System/Windows/Duration.cs b/src/libraries/System.Runtime.WindowsRuntime.UI.Xaml/src/System/Windows/Duration.cs deleted file mode 100644 index 569f585..0000000 --- a/src/libraries/System.Runtime.WindowsRuntime.UI.Xaml/src/System/Windows/Duration.cs +++ /dev/null @@ -1,317 +0,0 @@ -// 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.InteropServices; - -#pragma warning disable 436 // Redefining types from Windows.Foundation - -namespace Windows.UI.Xaml -{ - // - // Duration is the managed projection of Windows.UI.Xaml.Duration. Any changes to the layout - // of this type must be exactly mirrored on the native WinRT side as well. - // - // DurationType is the managed projection of Windows.UI.Xaml.DurationType. Any changes to this - // enumeration must be exactly mirrored on the native WinRT side as well. - // - // Note that these types are owned by the Jupiter team. Please contact them before making any - // changes here. - // - - public enum DurationType - { - Automatic, - TimeSpan, - Forever - } - - [StructLayout(LayoutKind.Sequential)] - public struct Duration - { - private readonly TimeSpan _timeSpan; - private DurationType _durationType; - - public Duration(TimeSpan timeSpan) - { - _durationType = DurationType.TimeSpan; - _timeSpan = timeSpan; - } - - public static implicit operator Duration(TimeSpan timeSpan) - { - return new Duration(timeSpan); - } - - public static Duration operator +(Duration t1, Duration t2) - { - if (t1.HasTimeSpan && t2.HasTimeSpan) - { - return new Duration(t1._timeSpan + t2._timeSpan); - } - else if (t1._durationType != DurationType.Automatic - && t2._durationType != DurationType.Automatic) - { - return Duration.Forever; - } - else - { - // Automatic + anything is Automatic - return Duration.Automatic; - } - } - - public static Duration operator -(Duration t1, Duration t2) - { - if (t1.HasTimeSpan && t2.HasTimeSpan) - { - return new Duration(t1._timeSpan - t2._timeSpan); - } - else if (t1._durationType == DurationType.Forever - && t2.HasTimeSpan) - { - return Duration.Forever; - } - else - { - return Duration.Automatic; - } - } - - public static bool operator ==(Duration t1, Duration t2) - { - return t1.Equals(t2); - } - - public static bool operator !=(Duration t1, Duration t2) - { - return !(t1.Equals(t2)); - } - - public static bool operator >(Duration t1, Duration t2) - { - if (t1.HasTimeSpan && t2.HasTimeSpan) - { - return t1._timeSpan > t2._timeSpan; - } - else if (t1.HasTimeSpan && t2._durationType == DurationType.Forever) - { - return false; - } - else if (t1._durationType == DurationType.Forever && t2.HasTimeSpan) - { - return true; - } - else - { - return false; - } - } - - public static bool operator >=(Duration t1, Duration t2) - { - if (t1._durationType == DurationType.Automatic && t2._durationType == DurationType.Automatic) - { - return true; - } - else if (t1._durationType == DurationType.Automatic || t2._durationType == DurationType.Automatic) - { - return false; - } - else - { - return !(t1 < t2); - } - } - - public static bool operator <(Duration t1, Duration t2) - { - if (t1.HasTimeSpan && t2.HasTimeSpan) - { - return t1._timeSpan < t2._timeSpan; - } - else if (t1.HasTimeSpan && t2._durationType == DurationType.Forever) - { - return true; - } - else if (t1._durationType == DurationType.Forever && t2.HasTimeSpan) - { - return false; - } - else - { - return false; - } - } - - public static bool operator <=(Duration t1, Duration t2) - { - if (t1._durationType == DurationType.Automatic && t2._durationType == DurationType.Automatic) - { - return true; - } - else if (t1._durationType == DurationType.Automatic || t2._durationType == DurationType.Automatic) - { - return false; - } - else - { - return !(t1 > t2); - } - } - - public static int Compare(Duration t1, Duration t2) - { - if (t1._durationType == DurationType.Automatic) - { - if (t2._durationType == DurationType.Automatic) - { - return 0; - } - else - { - return -1; - } - } - else if (t2._durationType == DurationType.Automatic) - { - return 1; - } - else - { - if (t1 < t2) - { - return -1; - } - else if (t1 > t2) - { - return 1; - } - else - { - return 0; - } - } - } - - public static Duration operator +(Duration duration) - { - return duration; - } - - public bool HasTimeSpan - { - get - { - return (_durationType == DurationType.TimeSpan); - } - } - - public static Duration Automatic - { - get - { - Duration duration = default; - duration._durationType = DurationType.Automatic; - - return duration; - } - } - - public static Duration Forever - { - get - { - Duration duration = default; - duration._durationType = DurationType.Forever; - - return duration; - } - } - - public TimeSpan TimeSpan - { - get - { - if (HasTimeSpan) - { - return _timeSpan; - } - else - { - throw new InvalidOperationException(); - } - } - } - - public Duration Add(Duration duration) - { - return this + duration; - } - - public override bool Equals(object? value) - { - return value is Duration && Equals((Duration)value); - } - - public bool Equals(Duration duration) - { - if (HasTimeSpan) - { - if (duration.HasTimeSpan) - { - return _timeSpan == duration._timeSpan; - } - else - { - return false; - } - } - else - { - return _durationType == duration._durationType; - } - } - - public static bool Equals(Duration t1, Duration t2) - { - return t1.Equals(t2); - } - - public override int GetHashCode() - { - if (HasTimeSpan) - { - return _timeSpan.GetHashCode(); - } - else - { - return _durationType.GetHashCode() + 17; - } - } - - public Duration Subtract(Duration duration) - { - return this - duration; - } - - public override string ToString() - { - if (HasTimeSpan) - { - return _timeSpan.ToString(); // "00"; //TypeDescriptor.GetConverter(_timeSpan).ConvertToString(_timeSpan); - } - else if (_durationType == DurationType.Forever) - { - return "Forever"; - } - else // IsAutomatic - { - return "Automatic"; - } - } - } -} - -#pragma warning restore 436 diff --git a/src/libraries/System.Runtime.WindowsRuntime.UI.Xaml/src/System/Windows/GridLength.cs b/src/libraries/System.Runtime.WindowsRuntime.UI.Xaml/src/System/Windows/GridLength.cs deleted file mode 100644 index cdced48..0000000 --- a/src/libraries/System.Runtime.WindowsRuntime.UI.Xaml/src/System/Windows/GridLength.cs +++ /dev/null @@ -1,137 +0,0 @@ -// 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.Globalization; -using System.Runtime.InteropServices; -using System.Text; - -#pragma warning disable 436 // Redefining types from Windows.Foundation -namespace Windows.UI.Xaml -{ - // - // GridLength is the managed projection of Windows.UI.Xaml.GridLength. Any changes to the layout - // of this type must be exactly mirrored on the native WinRT side as well. - // - // GridUnitType is the managed projection of Windows.UI.Xaml.GridUnitType. Any changes to this - // enumeration must be exactly mirrored on the native WinRT side as well. - // - // Note that these types are owned by the Jupiter team. Please contact them before making any - // changes here. - // - public enum GridUnitType - { - Auto = 0, - Pixel, - Star, - } - - [StructLayout(LayoutKind.Sequential)] - public struct GridLength - { - private readonly double _unitValue; - private readonly GridUnitType _unitType; - - private const double Default = 1.0; - private static readonly GridLength s_auto = new GridLength(Default, GridUnitType.Auto); - - public GridLength(double pixels) - : this(pixels, GridUnitType.Pixel) - { - } - - public GridLength(double value, GridUnitType type) - { - if (!double.IsFinite(value) || value < 0.0) - { - throw new ArgumentException(SR.DirectUI_InvalidArgument, nameof(value)); - } - if (type != GridUnitType.Auto && type != GridUnitType.Pixel && type != GridUnitType.Star) - { - throw new ArgumentException(SR.DirectUI_InvalidArgument, nameof(type)); - } - - _unitValue = (type == GridUnitType.Auto) ? Default : value; - _unitType = type; - } - - - public double Value { get { return ((_unitType == GridUnitType.Auto) ? s_auto._unitValue : _unitValue); } } - public GridUnitType GridUnitType { get { return (_unitType); } } - - - public bool IsAbsolute { get { return (_unitType == GridUnitType.Pixel); } } - public bool IsAuto { get { return (_unitType == GridUnitType.Auto); } } - public bool IsStar { get { return (_unitType == GridUnitType.Star); } } - - public static GridLength Auto - { - get { return (s_auto); } - } - - - public static bool operator ==(GridLength gl1, GridLength gl2) - { - return (gl1.GridUnitType == gl2.GridUnitType - && gl1.Value == gl2.Value); - } - - public static bool operator !=(GridLength gl1, GridLength gl2) - { - return (gl1.GridUnitType != gl2.GridUnitType - || gl1.Value != gl2.Value); - } - - public override bool Equals(object? oCompare) - { - if (oCompare is GridLength) - { - GridLength l = (GridLength)oCompare; - return (this == l); - } - else - return false; - } - - public bool Equals(GridLength gridLength) - { - return (this == gridLength); - } - - public override int GetHashCode() - { - return ((int)_unitValue + (int)_unitType); - } - - public override string ToString() - { - return this.ToString(CultureInfo.InvariantCulture); - } - - internal string ToString(CultureInfo? cultureInfo) - { - char listSeparator = TokenizerHelper.GetNumericListSeparator(cultureInfo); - - // Initial capacity [64] is an estimate based on a sum of: - // 12 = 1x double (twelve digits is generous for the range of values likely) - // 8 = 4x Unit Type string (approx two characters) - // 2 = 2x separator characters - - if (_unitType == GridUnitType.Auto) - { - return "Auto"; - } - else if (_unitType == GridUnitType.Pixel) - { - return Convert.ToString(_unitValue, cultureInfo); - } - else - { - return Convert.ToString(_unitValue, cultureInfo) + "*"; - } - } - } -} - -#pragma warning restore 436 diff --git a/src/libraries/System.Runtime.WindowsRuntime.UI.Xaml/src/System/Windows/LayoutCycleException.cs b/src/libraries/System.Runtime.WindowsRuntime.UI.Xaml/src/System/Windows/LayoutCycleException.cs deleted file mode 100644 index 96c1bbb..0000000 --- a/src/libraries/System.Runtime.WindowsRuntime.UI.Xaml/src/System/Windows/LayoutCycleException.cs +++ /dev/null @@ -1,46 +0,0 @@ -// 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: Exception class for representing Jupiter GUI layout problems, -** corresponding with E_LAYOUTCYCLE. -** -** -=============================================================================*/ -using System; -using System.Runtime.InteropServices; -using System.Runtime.Serialization; - -namespace Windows.UI.Xaml -{ - [Serializable] - public class LayoutCycleException : Exception - { - public LayoutCycleException() - : base(SR.LayoutCycle_Default) - { - HResult = HResults.E_LAYOUTCYCLE; - } - - public LayoutCycleException(string? message) - : base(message) - { - HResult = HResults.E_LAYOUTCYCLE; - } - - public LayoutCycleException(string? message, Exception? innerException) - : base(message, innerException) - { - HResult = HResults.E_LAYOUTCYCLE; - } - - protected LayoutCycleException(SerializationInfo serializationInfo, StreamingContext streamingContext) - : base(serializationInfo, streamingContext) - { - } - } -} diff --git a/src/libraries/System.Runtime.WindowsRuntime.UI.Xaml/src/System/Windows/Markup/XamlParseException.cs b/src/libraries/System.Runtime.WindowsRuntime.UI.Xaml/src/System/Windows/Markup/XamlParseException.cs deleted file mode 100644 index 989cd8e..0000000 --- a/src/libraries/System.Runtime.WindowsRuntime.UI.Xaml/src/System/Windows/Markup/XamlParseException.cs +++ /dev/null @@ -1,40 +0,0 @@ -// 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: Exception class for representing Jupiter XAML parsing failures, -** corresponding with E_XAMLPARSEFAILED. -** -** -=============================================================================*/ - -using System; -using System.Runtime.InteropServices; - -namespace Windows.UI.Xaml.Markup -{ - public class XamlParseException : Exception - { - public XamlParseException() - : base(SR.XamlParse_Default) - { - HResult = HResults.E_XAMLPARSEFAILED; - } - - public XamlParseException(string? message) - : base(message) - { - HResult = HResults.E_XAMLPARSEFAILED; - } - - public XamlParseException(string? message, Exception? innerException) - : base(message, innerException) - { - HResult = HResults.E_XAMLPARSEFAILED; - } - } -} diff --git a/src/libraries/System.Runtime.WindowsRuntime.UI.Xaml/src/System/Windows/Media/Animation/KeyTime.cs b/src/libraries/System.Runtime.WindowsRuntime.UI.Xaml/src/System/Windows/Media/Animation/KeyTime.cs deleted file mode 100644 index f216f34..0000000 --- a/src/libraries/System.Runtime.WindowsRuntime.UI.Xaml/src/System/Windows/Media/Animation/KeyTime.cs +++ /dev/null @@ -1,89 +0,0 @@ -// 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.InteropServices; - -#pragma warning disable 436 // Redefining types from Windows.Foundation - -namespace Windows.UI.Xaml.Media.Animation -{ - // - // KeyTime is the managed projection of Windows.UI.Xaml.Media.Animation.KeyTime. - // Any changes to the layout of this type must be exactly mirrored on the native WinRT side as well. - // - // Note that these types are owned by the Jupiter team. Please contact them before making any - // changes here. - // - - [StructLayout(LayoutKind.Sequential)] - public struct KeyTime - { - private TimeSpan _timeSpan; - - public static KeyTime FromTimeSpan(TimeSpan timeSpan) - { - if (timeSpan < TimeSpan.Zero) - { - throw new ArgumentOutOfRangeException(nameof(timeSpan)); - } - - KeyTime keyTime = default; - - keyTime._timeSpan = timeSpan; - - return keyTime; - } - - public static bool Equals(KeyTime keyTime1, KeyTime keyTime2) - { - return (keyTime1._timeSpan == keyTime2._timeSpan); - } - - public static bool operator ==(KeyTime keyTime1, KeyTime keyTime2) - { - return KeyTime.Equals(keyTime1, keyTime2); - } - - public static bool operator !=(KeyTime keyTime1, KeyTime keyTime2) - { - return !KeyTime.Equals(keyTime1, keyTime2); - } - - public bool Equals(KeyTime value) - { - return KeyTime.Equals(this, value); - } - - public override bool Equals(object? value) - { - return value is KeyTime && this == (KeyTime)value; - } - - public override int GetHashCode() - { - return _timeSpan.GetHashCode(); - } - - public override string ToString() - { - return _timeSpan.ToString(); - } - - public static implicit operator KeyTime(TimeSpan timeSpan) - { - return KeyTime.FromTimeSpan(timeSpan); - } - - public TimeSpan TimeSpan - { - get - { - return _timeSpan; - } - } - } -} - -#pragma warning restore 436 diff --git a/src/libraries/System.Runtime.WindowsRuntime.UI.Xaml/src/System/Windows/Media/Animation/RepeatBehavior.cs b/src/libraries/System.Runtime.WindowsRuntime.UI.Xaml/src/System/Windows/Media/Animation/RepeatBehavior.cs deleted file mode 100644 index 615723f..0000000 --- a/src/libraries/System.Runtime.WindowsRuntime.UI.Xaml/src/System/Windows/Media/Animation/RepeatBehavior.cs +++ /dev/null @@ -1,212 +0,0 @@ -// 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.InteropServices; -using System.Text; - -#pragma warning disable 436 // Redefining types from Windows.Foundation - -namespace Windows.UI.Xaml.Media.Animation -{ - // - // RepeatBehavior is the managed projection of Windows.UI.Xaml.Media.Animation.RepeatBehavior. - // Any changes to the layout of this type must be exactly mirrored on the native WinRT side as well. - // - // RepeatBehaviorType is the managed projection of Windows.UI.Xaml.Media.Animation.RepeatBehaviorType. - // Any changes to this enumeration must be exactly mirrored on the native WinRT side as well. - // - // Note that these types are owned by the Jupiter team. Please contact them before making any - // changes here. - // - - public enum RepeatBehaviorType - { - Count, - Duration, - Forever - } - - [StructLayout(LayoutKind.Sequential)] - public struct RepeatBehavior : IFormattable - { - private double _Count; - private TimeSpan _Duration; - private RepeatBehaviorType _Type; - - public RepeatBehavior(double count) - { - if (!double.IsFinite(count) || count < 0.0) - { - throw new ArgumentOutOfRangeException(nameof(count)); - } - - _Duration = new TimeSpan(0); - _Count = count; - _Type = RepeatBehaviorType.Count; - } - - public RepeatBehavior(TimeSpan duration) - { - if (duration < new TimeSpan(0)) - { - throw new ArgumentOutOfRangeException(nameof(duration)); - } - - _Duration = duration; - _Count = 0.0; - _Type = RepeatBehaviorType.Duration; - } - - public static RepeatBehavior Forever - { - get - { - RepeatBehavior forever = default; - forever.Type = RepeatBehaviorType.Forever; - - return forever; - } - } - - public bool HasCount - { - get - { - return Type == RepeatBehaviorType.Count; - } - } - - public bool HasDuration - { - get - { - return Type == RepeatBehaviorType.Duration; - } - } - - public double Count - { - get { return _Count; } - set { _Count = value; } - } - - public TimeSpan Duration - { - get { return _Duration; } - set { _Duration = value; } - } - - public RepeatBehaviorType Type - { - get { return _Type; } - set { _Type = value; } - } - - public override string ToString() - { - return InternalToString(null, null); - } - - public string ToString(IFormatProvider? formatProvider) - { - return InternalToString(null, formatProvider); - } - - string IFormattable.ToString(string? format, IFormatProvider? formatProvider) - { - return InternalToString(format, formatProvider); - } - - internal string InternalToString(string? format, IFormatProvider? formatProvider) - { - switch (_Type) - { - case RepeatBehaviorType.Forever: - - return "Forever"; - - case RepeatBehaviorType.Count: - - StringBuilder sb = new StringBuilder(); - - sb.AppendFormat( - formatProvider, - "{0:" + format + "}x", - _Count); - - return sb.ToString(); - - case RepeatBehaviorType.Duration: - - return _Duration.ToString(); - - default: - return string.Empty; - } - } - - public override bool Equals(object? value) - { - if (value is RepeatBehavior) - { - return this.Equals((RepeatBehavior)value); - } - else - { - return false; - } - } - - public bool Equals(RepeatBehavior repeatBehavior) - { - if (_Type == repeatBehavior._Type) - { - return _Type switch - { - RepeatBehaviorType.Forever => true, - RepeatBehaviorType.Count => _Count == repeatBehavior._Count, - RepeatBehaviorType.Duration => _Duration == repeatBehavior._Duration, - _ => false, - }; - } - else - { - return false; - } - } - - public static bool Equals(RepeatBehavior repeatBehavior1, RepeatBehavior repeatBehavior2) - { - return repeatBehavior1.Equals(repeatBehavior2); - } - - public override int GetHashCode() - { - return _Type switch - { - RepeatBehaviorType.Count => _Count.GetHashCode(), - RepeatBehaviorType.Duration => _Duration.GetHashCode(), - - // We try to choose an unlikely hash code value for Forever. - // All Forevers need to return the same hash code value. - RepeatBehaviorType.Forever => int.MaxValue - 42, - - _ => base.GetHashCode(), - }; - } - - public static bool operator ==(RepeatBehavior repeatBehavior1, RepeatBehavior repeatBehavior2) - { - return repeatBehavior1.Equals(repeatBehavior2); - } - - public static bool operator !=(RepeatBehavior repeatBehavior1, RepeatBehavior repeatBehavior2) - { - return !repeatBehavior1.Equals(repeatBehavior2); - } - } -} - -#pragma warning restore 436 diff --git a/src/libraries/System.Runtime.WindowsRuntime.UI.Xaml/src/System/Windows/Media/Matrix.cs b/src/libraries/System.Runtime.WindowsRuntime.UI.Xaml/src/System/Windows/Media/Matrix.cs deleted file mode 100644 index 6fdf70d..0000000 --- a/src/libraries/System.Runtime.WindowsRuntime.UI.Xaml/src/System/Windows/Media/Matrix.cs +++ /dev/null @@ -1,262 +0,0 @@ -// 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.InteropServices; -using Point = Windows.Foundation.Point; - -using Windows.Foundation; - -#pragma warning disable 436 // Redefining types from Windows.Foundation - -namespace Windows.UI.Xaml.Media -{ - // - // Matrix is the managed projection of Windows.UI.Xaml.Media.Matrix. Any changes to the layout of - // this type must be exactly mirrored on the native WinRT side as well. - // - // Note that this type is owned by the Jupiter team. Please contact them before making any - // changes here. - // - - [StructLayout(LayoutKind.Sequential)] - public struct Matrix : IFormattable - { - public Matrix(double m11, double m12, - double m21, double m22, - double offsetX, double offsetY) - { - _m11 = m11; - _m12 = m12; - _m21 = m21; - _m22 = m22; - _offsetX = offsetX; - _offsetY = offsetY; - } - - // the transform is identity by default - private static Matrix s_identity = CreateIdentity(); - - public double M11 - { - get - { - return _m11; - } - set - { - _m11 = value; - } - } - - public double M12 - { - get - { - return _m12; - } - set - { - _m12 = value; - } - } - - public double M21 - { - get - { - return _m21; - } - set - { - _m21 = value; - } - } - - public double M22 - { - get - { - return _m22; - } - set - { - _m22 = value; - } - } - - public double OffsetX - { - get - { - return _offsetX; - } - set - { - _offsetX = value; - } - } - - public double OffsetY - { - get - { - return _offsetY; - } - set - { - _offsetY = value; - } - } - - public static Matrix Identity - { - get - { - return s_identity; - } - } - - public bool IsIdentity - { - get - { - return (_m11 == 1 && _m12 == 0 && _m21 == 0 && _m22 == 1 && _offsetX == 0 && _offsetY == 0); - } - } - - public override string ToString() - { - // Delegate to the internal method which implements all ToString calls. - return ConvertToString(null /* format string */, null /* format provider */); - } - - public string ToString(IFormatProvider? provider) - { - // Delegate to the internal method which implements all ToString calls. - return ConvertToString(null /* format string */, provider); - } - - string IFormattable.ToString(string? format, IFormatProvider? provider) - { - // Delegate to the internal method which implements all ToString calls. - return ConvertToString(format, provider); - } - - private string ConvertToString(string? format, IFormatProvider? provider) - { - if (IsIdentity) - { - return "Identity"; - } - - // Helper to get the numeric list separator for a given culture. - char separator = TokenizerHelper.GetNumericListSeparator(provider); - return string.Format(provider, - "{1:" + format + "}{0}{2:" + format + "}{0}{3:" + format + "}{0}{4:" + format + "}{0}{5:" + format + "}{0}{6:" + format + "}", - separator, - _m11, - _m12, - _m21, - _m22, - _offsetX, - _offsetY); - } - - public Point Transform(Point point) - { - float x = (float)point.X; - float y = (float)point.Y; - this.MultiplyPoint(ref x, ref y); - Point point2 = new Point(x, y); - return point2; - } - - public override int GetHashCode() - { - // Perform field-by-field XOR of HashCodes - return M11.GetHashCode() ^ - M12.GetHashCode() ^ - M21.GetHashCode() ^ - M22.GetHashCode() ^ - OffsetX.GetHashCode() ^ - OffsetY.GetHashCode(); - } - - public override bool Equals(object? o) - { - return o is Matrix && Matrix.Equals(this, (Matrix)o); - } - - public bool Equals(Matrix value) - { - return Matrix.Equals(this, value); - } - - public static bool operator ==(Matrix matrix1, Matrix matrix2) - { - return matrix1.M11 == matrix2.M11 && - matrix1.M12 == matrix2.M12 && - matrix1.M21 == matrix2.M21 && - matrix1.M22 == matrix2.M22 && - matrix1.OffsetX == matrix2.OffsetX && - matrix1.OffsetY == matrix2.OffsetY; - } - - public static bool operator !=(Matrix matrix1, Matrix matrix2) - { - return !(matrix1 == matrix2); - } - - private static Matrix CreateIdentity() - { - Matrix matrix = default; - matrix.SetMatrix(1, 0, - 0, 1, - 0, 0); - return matrix; - } - - private void SetMatrix(double m11, double m12, - double m21, double m22, - double offsetX, double offsetY) - { - _m11 = m11; - _m12 = m12; - _m21 = m21; - _m22 = m22; - _offsetX = offsetX; - _offsetY = offsetY; - } - - private void MultiplyPoint(ref float x, ref float y) - { - double num = (y * _m21) + _offsetX; - double num2 = (x * _m12) + _offsetY; - x *= (float)_m11; - x += (float)num; - y *= (float)_m22; - y += (float)num2; - } - - private static bool Equals(Matrix matrix1, Matrix matrix2) - { - return matrix1.M11.Equals(matrix2.M11) && - matrix1.M12.Equals(matrix2.M12) && - matrix1.M21.Equals(matrix2.M21) && - matrix1.M22.Equals(matrix2.M22) && - matrix1.OffsetX.Equals(matrix2.OffsetX) && - matrix1.OffsetY.Equals(matrix2.OffsetY); - } - - private double _m11; - private double _m12; - private double _m21; - private double _m22; - private double _offsetX; - private double _offsetY; - } -} - -#pragma warning restore 436 diff --git a/src/libraries/System.Runtime.WindowsRuntime.UI.Xaml/src/System/Windows/Media/Media3D/Matrix3D.cs b/src/libraries/System.Runtime.WindowsRuntime.UI.Xaml/src/System/Windows/Media/Media3D/Matrix3D.cs deleted file mode 100644 index dfd7d46..0000000 --- a/src/libraries/System.Runtime.WindowsRuntime.UI.Xaml/src/System/Windows/Media/Media3D/Matrix3D.cs +++ /dev/null @@ -1,708 +0,0 @@ -// 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.InteropServices; - -using Windows.Foundation; - -#pragma warning disable 436 // Redefining types from Windows.Foundation - -namespace Windows.UI.Xaml.Media.Media3D -{ - // - // Matrix3D is the managed projection of Windows.UI.Xaml.Media.Media3D.Matrix3D. Any - // changes to the layout of this type must be exactly mirrored on the native WinRT side as well. - // - // Note that this type is owned by the Jupiter team. Please contact them before making any - // changes here. - // - - [StructLayout(LayoutKind.Sequential)] - public struct Matrix3D : IFormattable - { - // Assuming this matrix has fourth column of 0,0,0,1 and isn't identity this function: - // Returns false if HasInverse is false, otherwise inverts the matrix. - private bool NormalizedAffineInvert() - { - double z20 = _m12 * _m23 - _m22 * _m13; - double z10 = _m32 * _m13 - _m12 * _m33; - double z00 = _m22 * _m33 - _m32 * _m23; - double det = _m31 * z20 + _m21 * z10 + _m11 * z00; - - if (IsZero(det)) - { - return false; - } - - // Compute 3x3 non-zero cofactors for the 2nd column - double z21 = _m21 * _m13 - _m11 * _m23; - double z11 = _m11 * _m33 - _m31 * _m13; - double z01 = _m31 * _m23 - _m21 * _m33; - - // Compute all six 2x2 determinants of 1st two columns - double y01 = _m11 * _m22 - _m21 * _m12; - double y02 = _m11 * _m32 - _m31 * _m12; - double y03 = _m11 * _offsetY - _offsetX * _m12; - double y12 = _m21 * _m32 - _m31 * _m22; - double y13 = _m21 * _offsetY - _offsetX * _m22; - double y23 = _m31 * _offsetY - _offsetX * _m32; - - // Compute all non-zero and non-one 3x3 cofactors for 2nd - // two columns - double z23 = _m23 * y03 - _offsetZ * y01 - _m13 * y13; - double z13 = _m13 * y23 - _m33 * y03 + _offsetZ * y02; - double z03 = _m33 * y13 - _offsetZ * y12 - _m23 * y23; - double z22 = y01; - double z12 = -y02; - double z02 = y12; - - double rcp = 1.0 / det; - - // Multiply all 3x3 cofactors by reciprocal & transpose - _m11 = (z00 * rcp); - _m12 = (z10 * rcp); - _m13 = (z20 * rcp); - - _m21 = (z01 * rcp); - _m22 = (z11 * rcp); - _m23 = (z21 * rcp); - - _m31 = (z02 * rcp); - _m32 = (z12 * rcp); - _m33 = (z22 * rcp); - - _offsetX = (z03 * rcp); - _offsetY = (z13 * rcp); - _offsetZ = (z23 * rcp); - - return true; - } - - // RETURNS true if has inverse & invert was done. Otherwise returns false & leaves matrix unchanged. - private bool InvertCore() - { - if (IsAffine) - { - return NormalizedAffineInvert(); - } - - // compute all six 2x2 determinants of 2nd two columns - double y01 = _m13 * _m24 - _m23 * _m14; - double y02 = _m13 * _m34 - _m33 * _m14; - double y03 = _m13 * _m44 - _offsetZ * _m14; - double y12 = _m23 * _m34 - _m33 * _m24; - double y13 = _m23 * _m44 - _offsetZ * _m24; - double y23 = _m33 * _m44 - _offsetZ * _m34; - - // Compute 3x3 cofactors for 1st the column - double z30 = _m22 * y02 - _m32 * y01 - _m12 * y12; - double z20 = _m12 * y13 - _m22 * y03 + _offsetY * y01; - double z10 = _m32 * y03 - _offsetY * y02 - _m12 * y23; - double z00 = _m22 * y23 - _m32 * y13 + _offsetY * y12; - - // Compute 4x4 determinant - double det = _offsetX * z30 + _m31 * z20 + _m21 * z10 + _m11 * z00; - - if (IsZero(det)) - { - return false; - } - - // Compute 3x3 cofactors for the 2nd column - double z31 = _m11 * y12 - _m21 * y02 + _m31 * y01; - double z21 = _m21 * y03 - _offsetX * y01 - _m11 * y13; - double z11 = _m11 * y23 - _m31 * y03 + _offsetX * y02; - double z01 = _m31 * y13 - _offsetX * y12 - _m21 * y23; - - // Compute all six 2x2 determinants of 1st two columns - y01 = _m11 * _m22 - _m21 * _m12; - y02 = _m11 * _m32 - _m31 * _m12; - y03 = _m11 * _offsetY - _offsetX * _m12; - y12 = _m21 * _m32 - _m31 * _m22; - y13 = _m21 * _offsetY - _offsetX * _m22; - y23 = _m31 * _offsetY - _offsetX * _m32; - - // Compute all 3x3 cofactors for 2nd two columns - double z33 = _m13 * y12 - _m23 * y02 + _m33 * y01; - double z23 = _m23 * y03 - _offsetZ * y01 - _m13 * y13; - double z13 = _m13 * y23 - _m33 * y03 + _offsetZ * y02; - double z03 = _m33 * y13 - _offsetZ * y12 - _m23 * y23; - double z32 = _m24 * y02 - _m34 * y01 - _m14 * y12; - double z22 = _m14 * y13 - _m24 * y03 + _m44 * y01; - double z12 = _m34 * y03 - _m44 * y02 - _m14 * y23; - double z02 = _m24 * y23 - _m34 * y13 + _m44 * y12; - - double rcp = 1.0 / det; - - // Multiply all 3x3 cofactors by reciprocal & transpose - _m11 = (z00 * rcp); - _m12 = (z10 * rcp); - _m13 = (z20 * rcp); - _m14 = (z30 * rcp); - - _m21 = (z01 * rcp); - _m22 = (z11 * rcp); - _m23 = (z21 * rcp); - _m24 = (z31 * rcp); - - _m31 = (z02 * rcp); - _m32 = (z12 * rcp); - _m33 = (z22 * rcp); - _m34 = (z32 * rcp); - - _offsetX = (z03 * rcp); - _offsetY = (z13 * rcp); - _offsetZ = (z23 * rcp); - _m44 = (z33 * rcp); - - return true; - } - - public Matrix3D(double m11, double m12, double m13, double m14, - double m21, double m22, double m23, double m24, - double m31, double m32, double m33, double m34, - double offsetX, double offsetY, double offsetZ, double m44) - { - _m11 = m11; - _m12 = m12; - _m13 = m13; - _m14 = m14; - _m21 = m21; - _m22 = m22; - _m23 = m23; - _m24 = m24; - _m31 = m31; - _m32 = m32; - _m33 = m33; - _m34 = m34; - _offsetX = offsetX; - _offsetY = offsetY; - _offsetZ = offsetZ; - _m44 = m44; - } - - // the transform is identity by default - // Actually fill in the fields - some (internal) code uses the fields directly for perf. - private static Matrix3D s_identity = CreateIdentity(); - - public double M11 - { - get - { - return _m11; - } - set - { - _m11 = value; - } - } - - public double M12 - { - get - { - return _m12; - } - set - { - _m12 = value; - } - } - - public double M13 - { - get - { - return _m13; - } - set - { - _m13 = value; - } - } - - public double M14 - { - get - { - return _m14; - } - set - { - _m14 = value; - } - } - - public double M21 - { - get - { - return _m21; - } - set - { - _m21 = value; - } - } - - public double M22 - { - get - { - return _m22; - } - set - { - _m22 = value; - } - } - - public double M23 - { - get - { - return _m23; - } - set - { - _m23 = value; - } - } - - public double M24 - { - get - { - return _m24; - } - set - { - _m24 = value; - } - } - - public double M31 - { - get - { - return _m31; - } - set - { - _m31 = value; - } - } - - public double M32 - { - get - { - return _m32; - } - set - { - _m32 = value; - } - } - - public double M33 - { - get - { - return _m33; - } - set - { - _m33 = value; - } - } - - public double M34 - { - get - { - return _m34; - } - set - { - _m34 = value; - } - } - - public double OffsetX - { - get - { - return _offsetX; - } - set - { - _offsetX = value; - } - } - - public double OffsetY - { - get - { - return _offsetY; - } - set - { - _offsetY = value; - } - } - - public double OffsetZ - { - get - { - return _offsetZ; - } - set - { - _offsetZ = value; - } - } - - public double M44 - { - get - { - return _m44; - } - set - { - _m44 = value; - } - } - - public static Matrix3D Identity - { - get - { - return s_identity; - } - } - - public bool IsIdentity - { - get - { - return (_m11 == 1 && _m12 == 0 && _m13 == 0 && _m14 == 0 && - _m21 == 0 && _m22 == 1 && _m23 == 0 && _m24 == 0 && - _m31 == 0 && _m32 == 0 && _m33 == 1 && _m34 == 0 && - _offsetX == 0 && _offsetY == 0 && _offsetZ == 0 && _m44 == 1); - } - } - - public override string ToString() - { - // Delegate to the internal method which implements all ToString calls. - return ConvertToString(null /* format string */, null /* format provider */); - } - - public string ToString(IFormatProvider? provider) - { - // Delegate to the internal method which implements all ToString calls. - return ConvertToString(null /* format string */, provider); - } - - string IFormattable.ToString(string? format, IFormatProvider? provider) - { - // Delegate to the internal method which implements all ToString calls. - return ConvertToString(format, provider); - } - - private string ConvertToString(string? format, IFormatProvider? provider) - { - if (IsIdentity) - { - return "Identity"; - } - - // Helper to get the numeric list separator for a given culture. - char separator = TokenizerHelper.GetNumericListSeparator(provider); - return string.Format(provider, - "{1:" + format + "}{0}{2:" + format + "}{0}{3:" + format + "}{0}{4:" + format + "}{0}{5:" + format + - "}{0}{6:" + format + "}{0}{7:" + format + "}{0}{8:" + format + "}{0}{9:" + format + "}{0}{10:" + format + - "}{0}{11:" + format + "}{0}{12:" + format + "}{0}{13:" + format + "}{0}{14:" + format + "}{0}{15:" + format + "}{0}{16:" + format + "}", - separator, - _m11, _m12, _m13, _m14, - _m21, _m22, _m23, _m24, - _m31, _m32, _m33, _m34, - _offsetX, _offsetY, _offsetZ, _m44); - } - - public override int GetHashCode() - { - // Perform field-by-field XOR of HashCodes - return M11.GetHashCode() ^ - M12.GetHashCode() ^ - M13.GetHashCode() ^ - M14.GetHashCode() ^ - M21.GetHashCode() ^ - M22.GetHashCode() ^ - M23.GetHashCode() ^ - M24.GetHashCode() ^ - M31.GetHashCode() ^ - M32.GetHashCode() ^ - M33.GetHashCode() ^ - M34.GetHashCode() ^ - OffsetX.GetHashCode() ^ - OffsetY.GetHashCode() ^ - OffsetZ.GetHashCode() ^ - M44.GetHashCode(); - } - - public override bool Equals(object? o) - { - return o is Matrix3D && Matrix3D.Equals(this, (Matrix3D)o); - } - - public bool Equals(Matrix3D value) - { - return Matrix3D.Equals(this, value); - } - - public static bool operator ==(Matrix3D matrix1, Matrix3D matrix2) - { - return matrix1.M11 == matrix2.M11 && - matrix1.M12 == matrix2.M12 && - matrix1.M13 == matrix2.M13 && - matrix1.M14 == matrix2.M14 && - matrix1.M21 == matrix2.M21 && - matrix1.M22 == matrix2.M22 && - matrix1.M23 == matrix2.M23 && - matrix1.M24 == matrix2.M24 && - matrix1.M31 == matrix2.M31 && - matrix1.M32 == matrix2.M32 && - matrix1.M33 == matrix2.M33 && - matrix1.M34 == matrix2.M34 && - matrix1.OffsetX == matrix2.OffsetX && - matrix1.OffsetY == matrix2.OffsetY && - matrix1.OffsetZ == matrix2.OffsetZ && - matrix1.M44 == matrix2.M44; - } - - public static bool operator !=(Matrix3D matrix1, Matrix3D matrix2) - { - return !(matrix1 == matrix2); - } - - public static Matrix3D operator *(Matrix3D matrix1, Matrix3D matrix2) - { - Matrix3D matrix3D = default; - - matrix3D.M11 = matrix1.M11 * matrix2.M11 + - matrix1.M12 * matrix2.M21 + - matrix1.M13 * matrix2.M31 + - matrix1.M14 * matrix2.OffsetX; - matrix3D.M12 = matrix1.M11 * matrix2.M12 + - matrix1.M12 * matrix2.M22 + - matrix1.M13 * matrix2.M32 + - matrix1.M14 * matrix2.OffsetY; - matrix3D.M13 = matrix1.M11 * matrix2.M13 + - matrix1.M12 * matrix2.M23 + - matrix1.M13 * matrix2.M33 + - matrix1.M14 * matrix2.OffsetZ; - matrix3D.M14 = matrix1.M11 * matrix2.M14 + - matrix1.M12 * matrix2.M24 + - matrix1.M13 * matrix2.M34 + - matrix1.M14 * matrix2.M44; - matrix3D.M21 = matrix1.M21 * matrix2.M11 + - matrix1.M22 * matrix2.M21 + - matrix1.M23 * matrix2.M31 + - matrix1.M24 * matrix2.OffsetX; - matrix3D.M22 = matrix1.M21 * matrix2.M12 + - matrix1.M22 * matrix2.M22 + - matrix1.M23 * matrix2.M32 + - matrix1.M24 * matrix2.OffsetY; - matrix3D.M23 = matrix1.M21 * matrix2.M13 + - matrix1.M22 * matrix2.M23 + - matrix1.M23 * matrix2.M33 + - matrix1.M24 * matrix2.OffsetZ; - matrix3D.M24 = matrix1.M21 * matrix2.M14 + - matrix1.M22 * matrix2.M24 + - matrix1.M23 * matrix2.M34 + - matrix1.M24 * matrix2.M44; - matrix3D.M31 = matrix1.M31 * matrix2.M11 + - matrix1.M32 * matrix2.M21 + - matrix1.M33 * matrix2.M31 + - matrix1.M34 * matrix2.OffsetX; - matrix3D.M32 = matrix1.M31 * matrix2.M12 + - matrix1.M32 * matrix2.M22 + - matrix1.M33 * matrix2.M32 + - matrix1.M34 * matrix2.OffsetY; - matrix3D.M33 = matrix1.M31 * matrix2.M13 + - matrix1.M32 * matrix2.M23 + - matrix1.M33 * matrix2.M33 + - matrix1.M34 * matrix2.OffsetZ; - matrix3D.M34 = matrix1.M31 * matrix2.M14 + - matrix1.M32 * matrix2.M24 + - matrix1.M33 * matrix2.M34 + - matrix1.M34 * matrix2.M44; - matrix3D.OffsetX = matrix1.OffsetX * matrix2.M11 + - matrix1.OffsetY * matrix2.M21 + - matrix1.OffsetZ * matrix2.M31 + - matrix1.M44 * matrix2.OffsetX; - matrix3D.OffsetY = matrix1.OffsetX * matrix2.M12 + - matrix1.OffsetY * matrix2.M22 + - matrix1.OffsetZ * matrix2.M32 + - matrix1.M44 * matrix2.OffsetY; - matrix3D.OffsetZ = matrix1.OffsetX * matrix2.M13 + - matrix1.OffsetY * matrix2.M23 + - matrix1.OffsetZ * matrix2.M33 + - matrix1.M44 * matrix2.OffsetZ; - matrix3D.M44 = matrix1.OffsetX * matrix2.M14 + - matrix1.OffsetY * matrix2.M24 + - matrix1.OffsetZ * matrix2.M34 + - matrix1.M44 * matrix2.M44; - - // matrix3D._type is not set. - - return matrix3D; - } - - public bool HasInverse - { - get - { - return !IsZero(Determinant); - } - } - - public void Invert() - { - if (!InvertCore()) - { - throw new InvalidOperationException(); - } - } - - private static Matrix3D CreateIdentity() - { - Matrix3D matrix3D = default; - matrix3D.SetMatrix(1, 0, 0, 0, - 0, 1, 0, 0, - 0, 0, 1, 0, - 0, 0, 0, 1); - return matrix3D; - } - - private void SetMatrix(double m11, double m12, double m13, double m14, - double m21, double m22, double m23, double m24, - double m31, double m32, double m33, double m34, - double offsetX, double offsetY, double offsetZ, double m44) - { - _m11 = m11; - _m12 = m12; - _m13 = m13; - _m14 = m14; - _m21 = m21; - _m22 = m22; - _m23 = m23; - _m24 = m24; - _m31 = m31; - _m32 = m32; - _m33 = m33; - _m34 = m34; - _offsetX = offsetX; - _offsetY = offsetY; - _offsetZ = offsetZ; - _m44 = m44; - } - - private static bool Equals(Matrix3D matrix1, Matrix3D matrix2) - { - return matrix1.M11.Equals(matrix2.M11) && - matrix1.M12.Equals(matrix2.M12) && - matrix1.M13.Equals(matrix2.M13) && - matrix1.M14.Equals(matrix2.M14) && - matrix1.M21.Equals(matrix2.M21) && - matrix1.M22.Equals(matrix2.M22) && - matrix1.M23.Equals(matrix2.M23) && - matrix1.M24.Equals(matrix2.M24) && - matrix1.M31.Equals(matrix2.M31) && - matrix1.M32.Equals(matrix2.M32) && - matrix1.M33.Equals(matrix2.M33) && - matrix1.M34.Equals(matrix2.M34) && - matrix1.OffsetX.Equals(matrix2.OffsetX) && - matrix1.OffsetY.Equals(matrix2.OffsetY) && - matrix1.OffsetZ.Equals(matrix2.OffsetZ) && - matrix1.M44.Equals(matrix2.M44); - } - - private double GetNormalizedAffineDeterminant() - { - double z20 = _m12 * _m23 - _m22 * _m13; - double z10 = _m32 * _m13 - _m12 * _m33; - double z00 = _m22 * _m33 - _m32 * _m23; - - return _m31 * z20 + _m21 * z10 + _m11 * z00; - } - - private bool IsAffine - { - get - { - return (_m14 == 0.0 && _m24 == 0.0 && _m34 == 0.0 && _m44 == 1.0); - } - } - - private double Determinant - { - get - { - if (IsAffine) - { - return GetNormalizedAffineDeterminant(); - } - - // compute all six 2x2 determinants of 2nd two columns - double y01 = _m13 * _m24 - _m23 * _m14; - double y02 = _m13 * _m34 - _m33 * _m14; - double y03 = _m13 * _m44 - _offsetZ * _m14; - double y12 = _m23 * _m34 - _m33 * _m24; - double y13 = _m23 * _m44 - _offsetZ * _m24; - double y23 = _m33 * _m44 - _offsetZ * _m34; - - // Compute 3x3 cofactors for 1st the column - double z30 = _m22 * y02 - _m32 * y01 - _m12 * y12; - double z20 = _m12 * y13 - _m22 * y03 + _offsetY * y01; - double z10 = _m32 * y03 - _offsetY * y02 - _m12 * y23; - double z00 = _m22 * y23 - _m32 * y13 + _offsetY * y12; - - return _offsetX * z30 + _m31 * z20 + _m21 * z10 + _m11 * z00; - } - } - - private static bool IsZero(double value) - { - return Math.Abs(value) < 10.0 * DBL_EPSILON_RELATIVE_1; - } - - private const double DBL_EPSILON_RELATIVE_1 = 1.1102230246251567e-016; /* smallest such that 1.0+DBL_EPSILON != 1.0 */ - - private double _m11; - private double _m12; - private double _m13; - private double _m14; - private double _m21; - private double _m22; - private double _m23; - private double _m24; - private double _m31; - private double _m32; - private double _m33; - private double _m34; - private double _offsetX; - private double _offsetY; - private double _offsetZ; - private double _m44; - } -} - -#pragma warning restore 436 diff --git a/src/libraries/System.Runtime.WindowsRuntime.UI.Xaml/src/System/Windows/Thickness.cs b/src/libraries/System.Runtime.WindowsRuntime.UI.Xaml/src/System/Windows/Thickness.cs deleted file mode 100644 index 2a3a4b7..0000000 --- a/src/libraries/System.Runtime.WindowsRuntime.UI.Xaml/src/System/Windows/Thickness.cs +++ /dev/null @@ -1,129 +0,0 @@ -// 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.Globalization; -using System.Runtime.InteropServices; -using System.Text; - -#pragma warning disable 436 // Redefining types from Windows.Foundation -namespace Windows.UI.Xaml -{ - // - // Thickness is the managed projection of Windows.UI.Xaml.Thickness. Any changes to the layout - // of this type must be exactly mirrored on the native WinRT side as well. - // - // Note that this type is owned by the Jupiter team. Please contact them before making any - // changes here. - // - - [StructLayout(LayoutKind.Sequential)] - public struct Thickness - { - private double _Left; - private double _Top; - private double _Right; - private double _Bottom; - - public Thickness(double uniformLength) - { - _Left = _Top = _Right = _Bottom = uniformLength; - } - - public Thickness(double left, double top, double right, double bottom) - { - _Left = left; - _Top = top; - _Right = right; - _Bottom = bottom; - } - - public double Left - { - get { return _Left; } - set { _Left = value; } - } - - public double Top - { - get { return _Top; } - set { _Top = value; } - } - - public double Right - { - get { return _Right; } - set { _Right = value; } - } - - public double Bottom - { - get { return _Bottom; } - set { _Bottom = value; } - } - - public override string ToString() - { - return ToString(CultureInfo.InvariantCulture); - } - - internal string ToString(CultureInfo? cultureInfo) - { - char listSeparator = TokenizerHelper.GetNumericListSeparator(cultureInfo); - - // Initial capacity [64] is an estimate based on a sum of: - // 48 = 4x double (twelve digits is generous for the range of values likely) - // 8 = 4x Unit Type string (approx two characters) - // 4 = 4x separator characters - StringBuilder sb = new StringBuilder(64); - - sb.Append(InternalToString(_Left, cultureInfo)); - sb.Append(listSeparator); - sb.Append(InternalToString(_Top, cultureInfo)); - sb.Append(listSeparator); - sb.Append(InternalToString(_Right, cultureInfo)); - sb.Append(listSeparator); - sb.Append(InternalToString(_Bottom, cultureInfo)); - return sb.ToString(); - } - - internal string InternalToString(double l, CultureInfo? cultureInfo) - { - if (double.IsNaN(l)) return "Auto"; - return Convert.ToString(l, cultureInfo); - } - - public override bool Equals(object? obj) - { - if (obj is Thickness) - { - Thickness otherObj = (Thickness)obj; - return (this == otherObj); - } - return (false); - } - - public bool Equals(Thickness thickness) - { - return (this == thickness); - } - - public override int GetHashCode() - { - return _Left.GetHashCode() ^ _Top.GetHashCode() ^ _Right.GetHashCode() ^ _Bottom.GetHashCode(); - } - - public static bool operator ==(Thickness t1, Thickness t2) - { - return t1._Left == t2._Left && t1._Top == t2._Top && t1._Right == t2._Right && t1._Bottom == t2._Bottom; - } - - public static bool operator !=(Thickness t1, Thickness t2) - { - return (!(t1 == t2)); - } - } -} - -#pragma warning restore 436 diff --git a/src/libraries/System.Runtime.WindowsRuntime.UI.Xaml/src/System/Windows/TokenizerHelper.cs b/src/libraries/System.Runtime.WindowsRuntime.UI.Xaml/src/System/Windows/TokenizerHelper.cs deleted file mode 100644 index 8ddd773..0000000 --- a/src/libraries/System.Runtime.WindowsRuntime.UI.Xaml/src/System/Windows/TokenizerHelper.cs +++ /dev/null @@ -1,44 +0,0 @@ -// 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.Globalization; -using System.Runtime.InteropServices; - -#pragma warning disable 436 // Redefining types from Windows.Foundation -namespace Windows.UI.Xaml -{ - // - // Note that this type is owned by the Jupiter team. Please contact them before making any - // changes here. - // - - internal static class TokenizerHelper - { - internal static char GetNumericListSeparator(IFormatProvider? provider) - { - char numericSeparator = ','; - - // Get the NumberFormatInfo out of the provider, if possible - // If the IFormatProvider doesn't not contain a NumberFormatInfo, then - // this method returns the current culture's NumberFormatInfo. - NumberFormatInfo numberFormat = NumberFormatInfo.GetInstance(provider); - - // Is the decimal separator is the same as the list separator? - // If so, we use the ";". - if ((numberFormat.NumberDecimalSeparator.Length > 0) && (numericSeparator == numberFormat.NumberDecimalSeparator[0])) - { - numericSeparator = ';'; - } - - return numericSeparator; - } - } -} - -#pragma warning restore 436 diff --git a/src/libraries/System.Runtime.WindowsRuntime.UI.Xaml/tests/System.Runtime.WindowsRuntime.UI.Xaml.Tests.csproj b/src/libraries/System.Runtime.WindowsRuntime.UI.Xaml/tests/System.Runtime.WindowsRuntime.UI.Xaml.Tests.csproj deleted file mode 100644 index 42a1b76..0000000 --- a/src/libraries/System.Runtime.WindowsRuntime.UI.Xaml/tests/System.Runtime.WindowsRuntime.UI.Xaml.Tests.csproj +++ /dev/null @@ -1,23 +0,0 @@ - - - $(NetCoreAppCurrent)-Windows_NT - - - - - - - - - - - - - - - - - - - - \ No newline at end of file diff --git a/src/libraries/System.Runtime.WindowsRuntime.UI.Xaml/tests/Windows/UI/Xaml/Automation/ElementNotAvailableExceptionTests.cs b/src/libraries/System.Runtime.WindowsRuntime.UI.Xaml/tests/Windows/UI/Xaml/Automation/ElementNotAvailableExceptionTests.cs deleted file mode 100644 index 393867d..0000000 --- a/src/libraries/System.Runtime.WindowsRuntime.UI.Xaml/tests/Windows/UI/Xaml/Automation/ElementNotAvailableExceptionTests.cs +++ /dev/null @@ -1,43 +0,0 @@ -// 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 Xunit; - -namespace Windows.UI.Xaml.Automation.Tests -{ - [ConditionalClass(typeof(PlatformDetection), nameof(PlatformDetection.IsWinUISupported))] - public class ElementNotAvailableExceptionTests - { - private const int E_ELEMENTNOTAVAILABLE = unchecked((int)0x802B001F); - - [Fact] - public void Ctor_Default() - { - var exception = new ElementNotAvailableException(); - Assert.NotEmpty(exception.Message); - Assert.Null(exception.InnerException); - Assert.Equal(E_ELEMENTNOTAVAILABLE, exception.HResult); - } - - [Fact] - public void Ctor_Message() - { - var exception = new ElementNotAvailableException("Message"); - Assert.Equal("Message", exception.Message); - Assert.Null(exception.InnerException); - Assert.Equal(E_ELEMENTNOTAVAILABLE, exception.HResult); - } - - [Fact] - public void Ctor_Message_InnerException() - { - var innerException = new Exception(); - var exception = new ElementNotAvailableException("Message", innerException); - Assert.Equal("Message", exception.Message); - Assert.Same(innerException, exception.InnerException); - Assert.Equal(E_ELEMENTNOTAVAILABLE, exception.HResult); - } - } -} \ No newline at end of file diff --git a/src/libraries/System.Runtime.WindowsRuntime.UI.Xaml/tests/Windows/UI/Xaml/Automation/ElementNotEnabledExceptionTests.cs b/src/libraries/System.Runtime.WindowsRuntime.UI.Xaml/tests/Windows/UI/Xaml/Automation/ElementNotEnabledExceptionTests.cs deleted file mode 100644 index 99fa64a..0000000 --- a/src/libraries/System.Runtime.WindowsRuntime.UI.Xaml/tests/Windows/UI/Xaml/Automation/ElementNotEnabledExceptionTests.cs +++ /dev/null @@ -1,43 +0,0 @@ -// 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 Xunit; - -namespace Windows.UI.Xaml.Automation.Tests -{ - [ConditionalClass(typeof(PlatformDetection), nameof(PlatformDetection.IsWinUISupported))] - public class ElementNotEnabledExceptionTests - { - private const int E_ELEMENTNOTENABLED = unchecked((int)0x802B001E); - - [Fact] - public void Ctor_Default() - { - var exception = new ElementNotEnabledException(); - Assert.NotEmpty(exception.Message); - Assert.Null(exception.InnerException); - Assert.Equal(E_ELEMENTNOTENABLED, exception.HResult); - } - - [Fact] - public void Ctor_Message() - { - var exception = new ElementNotEnabledException("Message"); - Assert.Equal("Message", exception.Message); - Assert.Null(exception.InnerException); - Assert.Equal(E_ELEMENTNOTENABLED, exception.HResult); - } - - [Fact] - public void Ctor_Message_InnerException() - { - var innerException = new Exception(); - var exception = new ElementNotEnabledException("Message", innerException); - Assert.Equal("Message", exception.Message); - Assert.Same(innerException, exception.InnerException); - Assert.Equal(E_ELEMENTNOTENABLED, exception.HResult); - } - } -} \ No newline at end of file diff --git a/src/libraries/System.Runtime.WindowsRuntime.UI.Xaml/tests/Windows/UI/Xaml/Controls/Primitives/GeneratorPositionTests.cs b/src/libraries/System.Runtime.WindowsRuntime.UI.Xaml/tests/Windows/UI/Xaml/Controls/Primitives/GeneratorPositionTests.cs deleted file mode 100644 index 3cb21da..0000000 --- a/src/libraries/System.Runtime.WindowsRuntime.UI.Xaml/tests/Windows/UI/Xaml/Controls/Primitives/GeneratorPositionTests.cs +++ /dev/null @@ -1,85 +0,0 @@ -// 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.Collections.Generic; -using System.Runtime.InteropServices; -using Xunit; - -namespace Windows.UI.Xaml.Controls.Primitives.Tests -{ - [ConditionalClass(typeof(PlatformDetection), nameof(PlatformDetection.IsWinUISupported))] - public class GeneratorPositionTests - { - [Fact] - public void Ctor_Default() - { - var position = new GeneratorPosition(); - Assert.Equal(0, position.Index); - Assert.Equal(0, position.Offset); - } - - [Theory] - [InlineData(-1, -2)] - [InlineData(0, 0)] - [InlineData(1, 2)] - public void Ctor_Index_Offset(int index, int offset) - { - var position = new GeneratorPosition(index, offset); - Assert.Equal(index, position.Index); - Assert.Equal(offset, position.Offset); - } - - [Theory] - [InlineData(-1)] - [InlineData(0)] - [InlineData(1)] - public void Index_Set_GetReturnsExpected(int value) - { - var thickness = new GeneratorPosition { Index = value }; - Assert.Equal(value, thickness.Index); - } - - [Theory] - [InlineData(-1)] - [InlineData(0)] - [InlineData(1)] - public void Offset_Set_GetReturnsExpected(int value) - { - var thickness = new GeneratorPosition { Offset = value }; - Assert.Equal(value, thickness.Offset); - } - - public static IEnumerable Equals_TestData() - { - yield return new object[] { new GeneratorPosition(1, 2), new GeneratorPosition(1, 2), true }; - yield return new object[] { new GeneratorPosition(1, 2), new GeneratorPosition(2, 2), false }; - yield return new object[] { new GeneratorPosition(1, 2), new GeneratorPosition(1, 3), false }; - - yield return new object[] { new GeneratorPosition(1, 2), new object(), false }; - yield return new object[] { new GeneratorPosition(1, 2), null, false }; - } - - [Theory] - [MemberData(nameof(Equals_TestData))] - public void Equals_Object_ReturnsExpected(GeneratorPosition position, object other, bool expected) - { - Assert.Equal(expected, position.Equals(other)); - if (other is GeneratorPosition otherPosition) - { - Assert.Equal(expected, position.Equals(otherPosition)); - Assert.Equal(expected, position == otherPosition); - Assert.Equal(!expected, position != otherPosition); - Assert.Equal(expected, position.GetHashCode().Equals(otherPosition.GetHashCode())); - } - } - - [Fact] - public void ToString_Invoke_ReturnsExpected() - { - var position = new GeneratorPosition(1, 2); - Assert.Equal("GeneratorPosition (1,2)", position.ToString()); - } - } -} \ No newline at end of file diff --git a/src/libraries/System.Runtime.WindowsRuntime.UI.Xaml/tests/Windows/UI/Xaml/CornerRadiusTests.cs b/src/libraries/System.Runtime.WindowsRuntime.UI.Xaml/tests/Windows/UI/Xaml/CornerRadiusTests.cs deleted file mode 100644 index 0644f4d..0000000 --- a/src/libraries/System.Runtime.WindowsRuntime.UI.Xaml/tests/Windows/UI/Xaml/CornerRadiusTests.cs +++ /dev/null @@ -1,220 +0,0 @@ -// 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.Collections.Generic; -using System.Linq; -using System.Runtime.InteropServices; -using Xunit; - -namespace Windows.UI.Xaml.Tests -{ - [ConditionalClass(typeof(PlatformDetection), nameof(PlatformDetection.IsWinUISupported))] - public class CornerRadiusTests - { - [Fact] - public void Ctor_Default() - { - var cornerRadius = new CornerRadius(); - Assert.Equal(0, cornerRadius.TopLeft); - Assert.Equal(0, cornerRadius.TopRight); - Assert.Equal(0, cornerRadius.BottomRight); - Assert.Equal(0, cornerRadius.BottomLeft); - } - - public static IEnumerable ValidDoubles_TestData() - { - yield return new object[] { 0 }; - yield return new object[] { 1 }; - yield return new object[] { double.MaxValue }; - yield return new object[] { double.PositiveInfinity }; - } - - [Theory] - [MemberData(nameof(ValidDoubles_TestData))] - public void Ctor_UniformRadius(double uniformRadius) - { - var cornerRadius = new CornerRadius(uniformRadius); - Assert.Equal(uniformRadius, cornerRadius.TopLeft); - Assert.Equal(uniformRadius, cornerRadius.TopRight); - Assert.Equal(uniformRadius, cornerRadius.BottomRight); - Assert.Equal(uniformRadius, cornerRadius.BottomLeft); - } - - private static List InvalidDoubles { get; } = new List { -1, double.NaN, double.NegativeInfinity }; - - public static IEnumerable InvalidDoubles_TestData() => InvalidDoubles.Select(f => new object[] { f }); - - [Theory] - [MemberData(nameof(InvalidDoubles_TestData))] - public void Ctor_InvalidUniformRadius_ThrowsArgumentException(double uniformRadius) - { - AssertExtensions.Throws(null, () => new CornerRadius(uniformRadius)); - } - - [Theory] - [InlineData(0, 0, 0, 0)] - [InlineData(1, 2, 3, 4)] - [InlineData(double.PositiveInfinity, double.PositiveInfinity, double.PositiveInfinity, double.PositiveInfinity)] - [InlineData(double.MaxValue, double.MaxValue, double.MaxValue, double.MaxValue)] - public void Ctor_TopLeft_TopRight_BottomRight_BottomLeft(double topLeft, double topRight, double bottomRight, double bottomLeft) - { - var cornerRadius = new CornerRadius(topLeft, topRight, bottomRight, bottomLeft); - Assert.Equal(topLeft, cornerRadius.TopLeft); - Assert.Equal(topRight, cornerRadius.TopRight); - Assert.Equal(bottomRight, cornerRadius.BottomRight); - Assert.Equal(bottomLeft, cornerRadius.BottomLeft); - } - - public static IEnumerable Ctor_InvalidValues_TestData() - { - foreach (double invalidValue in InvalidDoubles) - { - yield return new object[] { invalidValue, 0, 0, 0 }; - yield return new object[] { 0, invalidValue, 0, 0 }; - yield return new object[] { 0, 0, invalidValue, 0 }; - yield return new object[] { 0, 0, 0, invalidValue }; - } - } - - [Theory] - [MemberData(nameof(Ctor_InvalidValues_TestData))] - public void Ctor_InvalidValues_ThrowsArgumentException(double topLeft, double topRight, double bottomRight, double bottomLeft) - { - AssertExtensions.Throws(null, () => new CornerRadius(topLeft, topRight, bottomRight, bottomLeft)); - } - - [Theory] - [MemberData(nameof(ValidDoubles_TestData))] - public void TopLeft_SetValid_GetReturnsExpected(double value) - { - var cornerRadius = new CornerRadius { TopLeft = value }; - Assert.Equal(value, cornerRadius.TopLeft); - } - - [Theory] - [MemberData(nameof(InvalidDoubles_TestData))] - public void TopLeft_SetInvalid_ThrowsArgumentException(double value) - { - var cornerRadius = new CornerRadius(); - AssertExtensions.Throws(null, () => cornerRadius.TopLeft = value); - } - - [Theory] - [MemberData(nameof(ValidDoubles_TestData))] - public void TopRight_SetValid_GetReturnsExpected(double value) - { - var cornerRadius = new CornerRadius { TopRight = value }; - Assert.Equal(value, cornerRadius.TopRight); - } - - [Theory] - [MemberData(nameof(InvalidDoubles_TestData))] - public void TopRight_SetInvalid_ThrowsArgumentException(double value) - { - var cornerRadius = new CornerRadius(); - AssertExtensions.Throws(null, () => cornerRadius.TopRight = value); - } - - [Theory] - [MemberData(nameof(ValidDoubles_TestData))] - public void BottomRight_SetValid_GetReturnsExpected(double value) - { - var cornerRadius = new CornerRadius { BottomRight = value }; - Assert.Equal(value, cornerRadius.BottomRight); - } - - [Theory] - [MemberData(nameof(InvalidDoubles_TestData))] - public void BottomRight_SetInvalid_ThrowsArgumentException(double value) - { - var cornerRadius = new CornerRadius(); - AssertExtensions.Throws(null, () => cornerRadius.BottomRight = value); - } - - [Theory] - [MemberData(nameof(ValidDoubles_TestData))] - public void BottomLeft_SetValid_GetReturnsExpected(double value) - { - var cornerRadius = new CornerRadius { BottomLeft = value }; - Assert.Equal(value, cornerRadius.BottomLeft); - } - - [Theory] - [MemberData(nameof(InvalidDoubles_TestData))] - public void BottomLeft_SetInvalid_ThrowsArgumentException(double value) - { - var cornerRadius = new CornerRadius(); - AssertExtensions.Throws(null, () => cornerRadius.BottomLeft = value); - } - - public static IEnumerable Equals_TestData() - { - yield return new object[] { new CornerRadius(1, 2, 3, 4), new CornerRadius(1, 2, 3, 4), true }; - yield return new object[] { new CornerRadius(1, 2, 3, 4), new CornerRadius(2, 2, 3, 4), false }; - yield return new object[] { new CornerRadius(1, 2, 3, 4), new CornerRadius(1, 3, 3, 4), false }; - yield return new object[] { new CornerRadius(1, 2, 3, 4), new CornerRadius(1, 2, 4, 4), false }; - yield return new object[] { new CornerRadius(1, 2, 3, 4), new CornerRadius(1, 2, 3, 5), false }; - - yield return new object[] { new CornerRadius(1, 2, 3, 4), new object(), false }; - yield return new object[] { new CornerRadius(1, 2, 3, 4), null, false }; - } - - [Theory] - [MemberData(nameof(Equals_TestData))] - public void Equals_Object_ReturnsExpected(CornerRadius cornerRadius, object other, bool expected) - { - Assert.Equal(expected, cornerRadius.Equals(other)); - if (other is CornerRadius otherCornerRadius) - { - Assert.Equal(expected, cornerRadius.Equals(otherCornerRadius)); - Assert.Equal(expected, cornerRadius == otherCornerRadius); - Assert.Equal(!expected, cornerRadius != otherCornerRadius); - Assert.Equal(expected, cornerRadius.GetHashCode().Equals(otherCornerRadius.GetHashCode())); - } - } - - [Fact] - public void ToString_Invoke_ReturnsExpected() - { - var cornerRadius = new CornerRadius(1, 2.2, 3, 4); - Assert.Equal("1,2.2,3,4", cornerRadius.ToString()); - } - - [Fact] - public void ToString_NaN_ReturnsAuto() - { - CornerRadius cornerRadius = new FakeCornerRadius - { - TopLeft = double.NaN, - TopRight = double.NaN, - BottomRight = double.NaN, - BottomLeft = double.NaN - }.ToActual(); - Assert.Equal("Auto,Auto,Auto,Auto", cornerRadius.ToString()); - } - - public struct FakeCornerRadius - { - public double TopRight; - public double TopLeft; - public double BottomRight; - public double BottomLeft; - - public CornerRadius ToActual() - { - CornerRadiusWrapper wrapper = default(CornerRadiusWrapper); - wrapper.Fake = this; - return wrapper.Actual; - } - } - - [StructLayout(LayoutKind.Explicit)] - public struct CornerRadiusWrapper - { - [FieldOffset(0)] public CornerRadius Actual; - [FieldOffset(0)] public FakeCornerRadius Fake; - } - } -} \ No newline at end of file diff --git a/src/libraries/System.Runtime.WindowsRuntime.UI.Xaml/tests/Windows/UI/Xaml/DurationTests.cs b/src/libraries/System.Runtime.WindowsRuntime.UI.Xaml/tests/Windows/UI/Xaml/DurationTests.cs deleted file mode 100644 index 3b19ad9..0000000 --- a/src/libraries/System.Runtime.WindowsRuntime.UI.Xaml/tests/Windows/UI/Xaml/DurationTests.cs +++ /dev/null @@ -1,174 +0,0 @@ -// 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.Collections.Generic; -using Xunit; - -namespace Windows.UI.Xaml.Tests -{ - [ConditionalClass(typeof(PlatformDetection), nameof(PlatformDetection.IsWinUISupported))] - public class DurationTests - { - [Fact] - public void Ctor_Default() - { - var duration = new Duration(); - Assert.False(duration.HasTimeSpan); - Assert.Throws(() => duration.TimeSpan); - } - - [Fact] - public void Ctor_TimeSpan() - { - var duration = new Duration(TimeSpan.FromSeconds(2)); - Assert.True(duration.HasTimeSpan); - Assert.Equal(TimeSpan.FromSeconds(2), duration.TimeSpan); - } - - [Fact] - public void Operator_Duration_ReturnsExpected() - { - Duration duration = TimeSpan.FromSeconds(2); - Assert.True(duration.HasTimeSpan); - Assert.Equal(TimeSpan.FromSeconds(2), duration.TimeSpan); - } - - [Fact] - public void Operator_UnaryPlus_ReturnsExpected() - { - Duration duration = +new Duration(TimeSpan.FromSeconds(2)); - Assert.True(duration.HasTimeSpan); - Assert.Equal(TimeSpan.FromSeconds(2), duration.TimeSpan); - } - - [Fact] - public void Automatic_Get_ReturnsExpected() - { - Duration duration = Duration.Automatic; - Assert.False(duration.HasTimeSpan); - Assert.Throws(() => duration.TimeSpan); - } - - [Fact] - public void Forever_Get_ReturnsExpected() - { - Duration duration = Duration.Forever; - Assert.False(duration.HasTimeSpan); - Assert.Throws(() => duration.TimeSpan); - } - - public static IEnumerable Add_TestData() - { - yield return new object[] { Duration.Automatic, Duration.Automatic, Duration.Automatic }; - yield return new object[] { Duration.Automatic, Duration.Forever, Duration.Automatic }; - yield return new object[] { Duration.Forever, Duration.Forever, Duration.Forever }; - - yield return new object[] { Duration.Automatic, new Duration(TimeSpan.FromSeconds(2)), Duration.Automatic }; - yield return new object[] { Duration.Forever, new Duration(TimeSpan.FromSeconds(2)), Duration.Forever }; - - yield return new object[] { new Duration(TimeSpan.FromSeconds(1)), new Duration(TimeSpan.FromSeconds(2)), new Duration(TimeSpan.FromSeconds(3)) }; - } - - [Theory] - [MemberData(nameof(Add_TestData))] - public void Add_Durations_ReturnsExpected(Duration duration1, Duration duration2, Duration expected) - { - Assert.Equal(expected, duration1.Add(duration2)); - Assert.Equal(expected, duration1 + duration2); - - Assert.Equal(expected, duration2.Add(duration1)); - Assert.Equal(expected, duration2 + duration1); - } - - public static IEnumerable Subtract_TestData() - { - yield return new object[] { Duration.Automatic, Duration.Automatic, Duration.Automatic }; - yield return new object[] { Duration.Automatic, Duration.Forever, Duration.Automatic }; - yield return new object[] { Duration.Forever, Duration.Automatic, Duration.Automatic }; - yield return new object[] { Duration.Forever, Duration.Forever, Duration.Automatic }; - - yield return new object[] { Duration.Automatic, new Duration(TimeSpan.FromSeconds(2)), Duration.Automatic }; - yield return new object[] { Duration.Forever, new Duration(TimeSpan.FromSeconds(2)), Duration.Forever }; - - yield return new object[] { new Duration(TimeSpan.FromSeconds(3)), new Duration(TimeSpan.FromSeconds(2)), new Duration(TimeSpan.FromSeconds(1)) }; - } - - [Theory] - [MemberData(nameof(Subtract_TestData))] - public void Subtract_Durations_ReturnsExpected(Duration duration1, Duration duration2, Duration expected) - { - Assert.Equal(expected, duration1.Subtract(duration2)); - Assert.Equal(expected, duration1 - duration2); - } - - public static IEnumerable Compare_TestData_Data() - { - yield return new object[] { new Duration(TimeSpan.FromSeconds(1)), new Duration(TimeSpan.FromSeconds(2)), -1 }; - yield return new object[] { new Duration(TimeSpan.FromSeconds(2)), new Duration(TimeSpan.FromSeconds(1)), 1 }; - yield return new object[] { new Duration(TimeSpan.FromSeconds(1)), new Duration(TimeSpan.FromSeconds(1)), 0 }; - yield return new object[] { new Duration(TimeSpan.FromSeconds(1)), Duration.Automatic, 1 }; - yield return new object[] { new Duration(TimeSpan.FromSeconds(2)), Duration.Forever, -1 }; - - yield return new object[] { Duration.Forever, Duration.Forever, 0 }; - yield return new object[] { Duration.Forever, new Duration(TimeSpan.FromSeconds(2)), 1 }; - yield return new object[] { Duration.Forever, Duration.Automatic, 1 }; - - yield return new object[] { Duration.Automatic, Duration.Automatic, 0 }; - yield return new object[] { Duration.Automatic, new Duration(TimeSpan.FromSeconds(2)), -1 }; - yield return new object[] { Duration.Automatic, Duration.Forever, -1 }; - } - - [Theory] - [MemberData(nameof(Compare_TestData_Data))] - public void Compare_TestData(Duration duration1, Duration duration2, int expected) - { - bool bothOrNoneAutomatic = (duration1 == Duration.Automatic) == (duration2 == Duration.Automatic); - - Assert.Equal(expected, Duration.Compare(duration1, duration2)); - - Assert.Equal(expected <= 0 && bothOrNoneAutomatic, duration1 <= duration2); - Assert.Equal(expected < 0 && bothOrNoneAutomatic, duration1 < duration2); - - Assert.Equal(expected == 0 && bothOrNoneAutomatic, duration1 == duration2); - Assert.Equal(expected != 0, duration1 != duration2); - - Assert.Equal(expected >= 0 && bothOrNoneAutomatic, duration1 >= duration2); - Assert.Equal(expected > 0 && bothOrNoneAutomatic, duration1 > duration2); - } - public static IEnumerable Equals_TestData() - { - yield return new object[] { new Duration(), new object(), -1 }; - yield return new object[] { new Duration(), null, -1 }; - } - - [Theory] - [MemberData(nameof(Equals_TestData))] - [MemberData(nameof(Compare_TestData_Data))] - public void Equals_Object_ReturnsExpected(Duration duration, object other, int expected) - { - Assert.Equal(expected == 0, duration.Equals(other)); - if (other is Duration otherDuration) - { - Assert.Equal(expected == 0, Duration.Equals(duration, otherDuration)); - Assert.Equal(expected == 0, duration.Equals(otherDuration)); - Assert.Equal(expected == 0, duration.GetHashCode().Equals(otherDuration.GetHashCode())); - } - } - - public static IEnumerable ToString_TestData() - { - yield return new object[] { Duration.Automatic, "Automatic" }; - yield return new object[] { Duration.Forever, "Forever" }; - yield return new object[] { new Duration(TimeSpan.FromSeconds(2)), TimeSpan.FromSeconds(2).ToString() }; - } - - [Theory] - [MemberData(nameof(ToString_TestData))] - public void ToString_Invoke_ReturnsExpected(Duration duration, string expected) - { - Assert.Equal(expected, duration.ToString()); - } - } -} diff --git a/src/libraries/System.Runtime.WindowsRuntime.UI.Xaml/tests/Windows/UI/Xaml/GridLengthTests.cs b/src/libraries/System.Runtime.WindowsRuntime.UI.Xaml/tests/Windows/UI/Xaml/GridLengthTests.cs deleted file mode 100644 index f99066e..0000000 --- a/src/libraries/System.Runtime.WindowsRuntime.UI.Xaml/tests/Windows/UI/Xaml/GridLengthTests.cs +++ /dev/null @@ -1,125 +0,0 @@ -// 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.Collections.Generic; -using Xunit; - -namespace Windows.UI.Xaml.Tests -{ - [ConditionalClass(typeof(PlatformDetection), nameof(PlatformDetection.IsWinUISupported))] - public class GridLengthTests - { - [Fact] - public void Ctor_Default() - { - var gridLength = new GridLength(); - Assert.Equal(GridUnitType.Auto, gridLength.GridUnitType); - Assert.False(gridLength.IsAbsolute); - Assert.True(gridLength.IsAuto); - Assert.False(gridLength.IsStar); - Assert.Equal(1, gridLength.Value); - } - - [Theory] - [InlineData(0)] - [InlineData(10)] - [InlineData(float.MaxValue)] - public void Ctor_Pixels(double pixels) - { - var gridLength = new GridLength(pixels); - Assert.Equal(GridUnitType.Pixel, gridLength.GridUnitType); - Assert.True(gridLength.IsAbsolute); - Assert.False(gridLength.IsAuto); - Assert.False(gridLength.IsStar); - Assert.Equal(pixels, gridLength.Value); - } - - [Theory] - [InlineData(0, GridUnitType.Auto, 1)] - [InlineData(0, GridUnitType.Pixel, 0)] - [InlineData(0, GridUnitType.Star, 0)] - [InlineData(10, GridUnitType.Pixel, 10)] - [InlineData(float.MaxValue, GridUnitType.Star, float.MaxValue)] - public void Ctor_Value_UnitType(double value, GridUnitType unitType, double expectedValue) - { - var gridLength = new GridLength(value, unitType); - Assert.Equal(unitType, gridLength.GridUnitType); - Assert.Equal(unitType == GridUnitType.Pixel, gridLength.IsAbsolute); - Assert.Equal(unitType == GridUnitType.Auto, gridLength.IsAuto); - Assert.Equal(unitType == GridUnitType.Star, gridLength.IsStar); - Assert.Equal(expectedValue, gridLength.Value); - } - - [Theory] - [InlineData(-1)] - [InlineData(double.NaN)] - [InlineData(double.PositiveInfinity)] - [InlineData(double.NegativeInfinity)] - public void Ctor_InvalidValue_ThrowsArgumentException(double value) - { - AssertExtensions.Throws("value", () => new GridLength(value)); - AssertExtensions.Throws("value", () => new GridLength(value, GridUnitType.Pixel)); - } - - [Theory] - [InlineData(GridUnitType.Auto - 1)] - [InlineData(GridUnitType.Star + 1)] - public void Ctor_InvalidUnitType_ThrowsArgumentException(GridUnitType unitType) - { - AssertExtensions.Throws("type", () => new GridLength(1, unitType)); - } - - [Fact] - public void Auto_Get_ReturnsExpected() - { - GridLength gridLength = GridLength.Auto; - Assert.Equal(GridUnitType.Auto, gridLength.GridUnitType); - Assert.False(gridLength.IsAbsolute); - Assert.True(gridLength.IsAuto); - Assert.False(gridLength.IsStar); - Assert.Equal(1, gridLength.Value); - } - - public static IEnumerable Equals_TestData() - { - yield return new object[] { new GridLength(10, GridUnitType.Pixel), new GridLength(10, GridUnitType.Pixel), true }; - yield return new object[] { new GridLength(10, GridUnitType.Pixel), new GridLength(11, GridUnitType.Pixel), false }; - yield return new object[] { new GridLength(10, GridUnitType.Pixel), new GridLength(10, GridUnitType.Auto), false }; - yield return new object[] { new GridLength(10, GridUnitType.Pixel), new GridLength(10, GridUnitType.Star), false }; - yield return new object[] { new GridLength(10, GridUnitType.Auto), GridLength.Auto, true }; - - yield return new object[] { new GridLength(10, GridUnitType.Pixel), new object(), false }; - yield return new object[] { new GridLength(10, GridUnitType.Pixel), null, false }; - } - - [Theory] - [MemberData(nameof(Equals_TestData))] - public void Equals_Object_ReturnsExpected(GridLength gridLength, object other, bool expected) - { - Assert.Equal(expected, gridLength.Equals(other)); - if (other is GridLength otherGridLength) - { - Assert.Equal(expected, gridLength.Equals(otherGridLength)); - Assert.Equal(expected, gridLength == otherGridLength); - Assert.Equal(!expected, gridLength != otherGridLength); - Assert.Equal(expected, gridLength.GetHashCode().Equals(otherGridLength.GetHashCode())); - } - } - - public static IEnumerable ToString_TestData() - { - yield return new object[] { GridLength.Auto, "Auto" }; - yield return new object[] { new GridLength(10, GridUnitType.Pixel), "10" }; - yield return new object[] { new GridLength(10, GridUnitType.Star), "10*" }; - } - - [Theory] - [MemberData(nameof(ToString_TestData))] - public void ToString_Invoke_ReturnsExpected(GridLength gridLength, string expected) - { - Assert.Equal(expected, gridLength.ToString()); - } - } -} \ No newline at end of file diff --git a/src/libraries/System.Runtime.WindowsRuntime.UI.Xaml/tests/Windows/UI/Xaml/LayoutCycleExceptionTests.cs b/src/libraries/System.Runtime.WindowsRuntime.UI.Xaml/tests/Windows/UI/Xaml/LayoutCycleExceptionTests.cs deleted file mode 100644 index 9546605..0000000 --- a/src/libraries/System.Runtime.WindowsRuntime.UI.Xaml/tests/Windows/UI/Xaml/LayoutCycleExceptionTests.cs +++ /dev/null @@ -1,43 +0,0 @@ -// 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 Xunit; - -namespace Windows.UI.Xaml.Tests -{ - [ConditionalClass(typeof(PlatformDetection), nameof(PlatformDetection.IsWinUISupported))] - public class LayoutCycleExceptionTests - { - private const int E_LAYOUTCYCLE = unchecked((int)0x802B0014); - - [Fact] - public void Ctor_Default() - { - var exception = new LayoutCycleException(); - Assert.NotEmpty(exception.Message); - Assert.Null(exception.InnerException); - Assert.Equal(E_LAYOUTCYCLE, exception.HResult); - } - - [Fact] - public void Ctor_Message() - { - var exception = new LayoutCycleException("Message"); - Assert.Equal("Message", exception.Message); - Assert.Null(exception.InnerException); - Assert.Equal(E_LAYOUTCYCLE, exception.HResult); - } - - [Fact] - public void Ctor_Message_InnerException() - { - var innerException = new Exception(); - var exception = new LayoutCycleException("Message", innerException); - Assert.Equal("Message", exception.Message); - Assert.Same(innerException, exception.InnerException); - Assert.Equal(E_LAYOUTCYCLE, exception.HResult); - } - } -} \ No newline at end of file diff --git a/src/libraries/System.Runtime.WindowsRuntime.UI.Xaml/tests/Windows/UI/Xaml/Markup/XamlParseExceptionTests.cs b/src/libraries/System.Runtime.WindowsRuntime.UI.Xaml/tests/Windows/UI/Xaml/Markup/XamlParseExceptionTests.cs deleted file mode 100644 index 800ce8f..0000000 --- a/src/libraries/System.Runtime.WindowsRuntime.UI.Xaml/tests/Windows/UI/Xaml/Markup/XamlParseExceptionTests.cs +++ /dev/null @@ -1,43 +0,0 @@ -// 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 Xunit; - -namespace Windows.UI.Xaml.Markup.Tests -{ - [ConditionalClass(typeof(PlatformDetection), nameof(PlatformDetection.IsWinUISupported))] - public class XamlParseExceptionTests - { - private const int E_XAMLPARSEFAILED = unchecked((int)0x802B000A); - - [Fact] - public void Ctor_Default() - { - var exception = new XamlParseException(); - Assert.NotEmpty(exception.Message); - Assert.Null(exception.InnerException); - Assert.Equal(E_XAMLPARSEFAILED, exception.HResult); - } - - [Fact] - public void Ctor_Message() - { - var exception = new XamlParseException("Message"); - Assert.Equal("Message", exception.Message); - Assert.Null(exception.InnerException); - Assert.Equal(E_XAMLPARSEFAILED, exception.HResult); - } - - [Fact] - public void Ctor_Message_InnerException() - { - var innerException = new Exception(); - var exception = new XamlParseException("Message", innerException); - Assert.Equal("Message", exception.Message); - Assert.Same(innerException, exception.InnerException); - Assert.Equal(E_XAMLPARSEFAILED, exception.HResult); - } - } -} \ No newline at end of file diff --git a/src/libraries/System.Runtime.WindowsRuntime.UI.Xaml/tests/Windows/UI/Xaml/Media/Animation/KeyTimeTests.cs b/src/libraries/System.Runtime.WindowsRuntime.UI.Xaml/tests/Windows/UI/Xaml/Media/Animation/KeyTimeTests.cs deleted file mode 100644 index 3348c53..0000000 --- a/src/libraries/System.Runtime.WindowsRuntime.UI.Xaml/tests/Windows/UI/Xaml/Media/Animation/KeyTimeTests.cs +++ /dev/null @@ -1,86 +0,0 @@ -// 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.Collections.Generic; -using Xunit; - -namespace Windows.UI.Xaml.Media.Animation.Tests -{ - [ConditionalClass(typeof(PlatformDetection), nameof(PlatformDetection.IsWinUISupported))] - public class KeyTimeTests - { - [Fact] - public void Ctor_Default() - { - var keyTime = new KeyTime(); - Assert.Equal(TimeSpan.Zero, keyTime.TimeSpan); - } - - [Theory] - [InlineData(0)] - [InlineData(1)] - public void FromTimeSpan_ValidTimeSpan_ReturnsExpected(int seconds) - { - KeyTime keyTime = KeyTime.FromTimeSpan(TimeSpan.FromSeconds(seconds)); - Assert.Equal(TimeSpan.FromSeconds(seconds), keyTime.TimeSpan); - } - - [Fact] - public void FromTimeSpan_NegativeTimeSpan_ThrowsArgumentOutOfRangeException() - { - AssertExtensions.Throws("timeSpan", () => KeyTime.FromTimeSpan(TimeSpan.FromTicks(-1))); - } - - [Fact] - public void Operator_ValidTimeSpan_ReturnsExpected() - { - KeyTime keyTime = TimeSpan.FromSeconds(2); - Assert.Equal(TimeSpan.FromSeconds(2), keyTime); - } - - [Fact] - public void Operator_NegativeTimeSpan_ThrowsArgumentOutOfRangeException() - { - TimeSpan timeSpan = TimeSpan.FromTicks(-1); - AssertExtensions.Throws("timeSpan", () => (KeyTime)timeSpan); - } - - public static IEnumerable Equals_TestData() - { - yield return new object[] { KeyTime.FromTimeSpan(TimeSpan.FromSeconds(2)), KeyTime.FromTimeSpan(TimeSpan.FromSeconds(2)), true }; - yield return new object[] { KeyTime.FromTimeSpan(TimeSpan.FromSeconds(2)), KeyTime.FromTimeSpan(TimeSpan.FromSeconds(1)), false }; - - yield return new object[] { KeyTime.FromTimeSpan(TimeSpan.FromSeconds(2)), new object(), false }; - yield return new object[] { KeyTime.FromTimeSpan(TimeSpan.FromSeconds(2)), null, false }; - } - - [Theory] - [MemberData(nameof(Equals_TestData))] - public void Equals_Object_ReturnsExpected(KeyTime keyTime, object other, bool expected) - { - Assert.Equal(expected, keyTime.Equals(other)); - if (other is KeyTime otherKeyTime) - { - Assert.Equal(expected, keyTime.Equals(otherKeyTime)); - Assert.Equal(expected, keyTime == otherKeyTime); - Assert.Equal(!expected, keyTime != otherKeyTime); - Assert.Equal(expected, keyTime.GetHashCode().Equals(otherKeyTime.GetHashCode())); - } - } - - public static IEnumerable ToString_TestData() - { - yield return new object[] { new KeyTime(), TimeSpan.Zero.ToString() }; - yield return new object[] { KeyTime.FromTimeSpan(TimeSpan.FromSeconds(2)), TimeSpan.FromSeconds(2).ToString() }; - } - - [Theory] - [MemberData(nameof(ToString_TestData))] - public void ToString_Invoke_ReturnsExpected(KeyTime keyTime, string expected) - { - Assert.Equal(expected, keyTime.ToString()); - } - } -} \ No newline at end of file diff --git a/src/libraries/System.Runtime.WindowsRuntime.UI.Xaml/tests/Windows/UI/Xaml/Media/Animation/RepeatBehaviorTests.cs b/src/libraries/System.Runtime.WindowsRuntime.UI.Xaml/tests/Windows/UI/Xaml/Media/Animation/RepeatBehaviorTests.cs deleted file mode 100644 index 667c1ea..0000000 --- a/src/libraries/System.Runtime.WindowsRuntime.UI.Xaml/tests/Windows/UI/Xaml/Media/Animation/RepeatBehaviorTests.cs +++ /dev/null @@ -1,216 +0,0 @@ -// 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.Collections.Generic; -using System.Globalization; -using Xunit; - -namespace Windows.UI.Xaml.Media.Animation.Tests -{ - [ConditionalClass(typeof(PlatformDetection), nameof(PlatformDetection.IsWinUISupported))] - public class RepeatBehaviorTests - { - [Fact] - public void Ctor_Default() - { - var repeatBehaviour = new RepeatBehavior(); - Assert.True(repeatBehaviour.HasCount); - Assert.Equal(0, repeatBehaviour.Count); - - Assert.False(repeatBehaviour.HasDuration); - Assert.Equal(TimeSpan.Zero, repeatBehaviour.Duration); - - Assert.Equal(RepeatBehaviorType.Count, repeatBehaviour.Type); - } - - [Theory] - [InlineData(0)] - [InlineData(10)] - [InlineData(double.MaxValue)] - public void Ctor_Count(double count) - { - var repeatBehaviour = new RepeatBehavior(count); - Assert.True(repeatBehaviour.HasCount); - Assert.Equal(count, repeatBehaviour.Count); - - Assert.False(repeatBehaviour.HasDuration); - Assert.Equal(TimeSpan.Zero, repeatBehaviour.Duration); - - Assert.Equal(RepeatBehaviorType.Count, repeatBehaviour.Type); - Assert.Equal(count.GetHashCode(), repeatBehaviour.GetHashCode()); - } - - [Theory] - [InlineData(-1)] - [InlineData(double.NaN)] - [InlineData(double.PositiveInfinity)] - [InlineData(double.NegativeInfinity)] - public void Ctor_InvalidCount_ThrowsArgumentOutOfRangeException(double count) - { - AssertExtensions.Throws("count", () => new RepeatBehavior(count)); - } - - [Theory] - [InlineData(0)] - [InlineData(1)] - public void Ctor_TimeSpan(int seconds) - { - var repeatBehaviour = new RepeatBehavior(TimeSpan.FromSeconds(seconds)); - Assert.False(repeatBehaviour.HasCount); - Assert.Equal(0, repeatBehaviour.Count); - - Assert.True(repeatBehaviour.HasDuration); - Assert.Equal(TimeSpan.FromSeconds(seconds), repeatBehaviour.Duration); - - Assert.Equal(RepeatBehaviorType.Duration, repeatBehaviour.Type); - Assert.Equal(TimeSpan.FromSeconds(seconds).GetHashCode(), repeatBehaviour.GetHashCode()); - } - - [Fact] - public void Ctor_NegativeTimeSpan_ThrowsArgumentOutOfRangeException() - { - AssertExtensions.Throws("duration", () => new RepeatBehavior(TimeSpan.FromTicks(-1))); - } - - [Fact] - public void Forever_Get_ReturnsExpected() - { - RepeatBehavior forever = RepeatBehavior.Forever; - Assert.False(forever.HasCount); - Assert.Equal(0, forever.Count); - - Assert.False(forever.HasDuration); - Assert.Equal(TimeSpan.Zero, forever.Duration); - - Assert.Equal(RepeatBehaviorType.Forever, forever.Type); - - Assert.Equal(int.MaxValue - 42, forever.GetHashCode()); - } - - [Theory] - [InlineData(-1)] - [InlineData(0)] - [InlineData(10)] - [InlineData(double.MaxValue)] - [InlineData(double.NaN)] - [InlineData(double.PositiveInfinity)] - [InlineData(double.NegativeInfinity)] - public void Count_Set_GetReturnsExpected(double value) - { - var repeatBehaviour = new RepeatBehavior(TimeSpan.MaxValue) { Count = value }; - Assert.False(repeatBehaviour.HasCount); - Assert.Equal(value, repeatBehaviour.Count); - - // Although we set a count, the type is unchanged. - Assert.Equal(RepeatBehaviorType.Duration, repeatBehaviour.Type); - } - - [Theory] - [InlineData(0)] - [InlineData(1)] - [InlineData(-1)] - public void Duration_Set_GetReturnsExpected(int seconds) - { - var repeatBehaviour = new RepeatBehavior(1) { Duration = TimeSpan.FromSeconds(seconds) }; - Assert.False(repeatBehaviour.HasDuration); - Assert.Equal(TimeSpan.FromSeconds(seconds), repeatBehaviour.Duration); - - // Although we set a duration, the type is unchanged. - Assert.Equal(RepeatBehaviorType.Count, repeatBehaviour.Type); - } - - [Theory] - [InlineData(RepeatBehaviorType.Count - 1)] - [InlineData(RepeatBehaviorType.Count)] - [InlineData(RepeatBehaviorType.Duration)] - [InlineData(RepeatBehaviorType.Forever)] - [InlineData(RepeatBehaviorType.Forever + 1)] - public void Type_Set_GetReturnsExpected(RepeatBehaviorType type) - { - var repeatBehaviour = new RepeatBehavior(1) { Type = type }; - Assert.Equal(type == RepeatBehaviorType.Count, repeatBehaviour.HasCount); - Assert.Equal(type == RepeatBehaviorType.Duration, repeatBehaviour.HasDuration); - } - - public static IEnumerable Equals_TestData() - { - yield return new object[] { new RepeatBehavior(2), new RepeatBehavior(2), true }; - yield return new object[] { new RepeatBehavior(2), new RepeatBehavior(1), false }; - yield return new object[] { new RepeatBehavior(2), RepeatBehavior.Forever, false }; - yield return new object[] { new RepeatBehavior(2), new RepeatBehavior(TimeSpan.FromSeconds(2)), false }; - - yield return new object[] { new RepeatBehavior(TimeSpan.FromSeconds(2)), new RepeatBehavior(TimeSpan.FromSeconds(2)), true }; - yield return new object[] { new RepeatBehavior(TimeSpan.FromSeconds(2)), new RepeatBehavior(TimeSpan.FromSeconds(1)), false }; - yield return new object[] { new RepeatBehavior(TimeSpan.FromSeconds(2)), RepeatBehavior.Forever, false }; - yield return new object[] { new RepeatBehavior(TimeSpan.FromSeconds(2)), new RepeatBehavior(2), false }; - - yield return new object[] { RepeatBehavior.Forever, RepeatBehavior.Forever, true }; - yield return new object[] { RepeatBehavior.Forever, new RepeatBehavior(TimeSpan.FromSeconds(2)), false }; - yield return new object[] { RepeatBehavior.Forever, new RepeatBehavior(2), false }; - - yield return new object[] { new RepeatBehavior { Type = RepeatBehaviorType.Count - 1 }, new RepeatBehavior { Type = RepeatBehaviorType.Count - 1 }, false }; - yield return new object[] { new RepeatBehavior { Type = RepeatBehaviorType.Forever + 1 }, new RepeatBehavior { Type = RepeatBehaviorType.Count + 1 }, false }; - yield return new object[] { new RepeatBehavior(TimeSpan.FromSeconds(2)), new object(), false }; - yield return new object[] { new RepeatBehavior(TimeSpan.FromSeconds(2)), null, false }; - } - - [Theory] - [MemberData(nameof(Equals_TestData))] - public void Equals_Object_ReturnsExpected(RepeatBehavior repeatBehaviour, object other, bool expected) - { - Assert.Equal(expected, repeatBehaviour.Equals(other)); - if (other is RepeatBehavior otherRepeatBehaviour) - { - Assert.Equal(expected, RepeatBehavior.Equals(repeatBehaviour, otherRepeatBehaviour)); - Assert.Equal(expected, repeatBehaviour.Equals(otherRepeatBehaviour)); - Assert.Equal(expected, repeatBehaviour == otherRepeatBehaviour); - Assert.Equal(!expected, repeatBehaviour != otherRepeatBehaviour); - - if (repeatBehaviour.Type >= RepeatBehaviorType.Count && repeatBehaviour.Type <= RepeatBehaviorType.Forever) - { - Assert.Equal(expected, repeatBehaviour.GetHashCode().Equals(otherRepeatBehaviour.GetHashCode())); - } - else if (repeatBehaviour.Type == otherRepeatBehaviour.Type) - { - Assert.Equal(repeatBehaviour.GetHashCode(), otherRepeatBehaviour.GetHashCode()); - } - } - } - - public static IEnumerable ToString_TestData() - { - yield return new object[] { RepeatBehavior.Forever, null, null, "Forever" }; - yield return new object[] { RepeatBehavior.Forever, "InvalidFormat", CultureInfo.CurrentCulture, "Forever" }; - - yield return new object[] { new RepeatBehavior(TimeSpan.FromSeconds(2)), null, null, TimeSpan.FromSeconds(2).ToString() }; - yield return new object[] { new RepeatBehavior(TimeSpan.FromSeconds(2)), "InvalidFormat", CultureInfo.CurrentCulture, TimeSpan.FromSeconds(2).ToString() }; - - var culture = new CultureInfo("en-US"); - culture.NumberFormat.NumberDecimalSeparator = "|"; - yield return new object[] { new RepeatBehavior(2.2), "abc", culture, "abcx" }; - yield return new object[] { new RepeatBehavior(2.2), "N4", culture, "2|2000x" }; - yield return new object[] { new RepeatBehavior(2.2), null, culture, "2|2x" }; - - yield return new object[] { new RepeatBehavior(2.2), null, null, $"{2.2.ToString()}x" }; - } - - [Theory] - [MemberData(nameof(ToString_TestData))] - public void ToString_Invoke_ReturnsExpected(RepeatBehavior keyTime, string format, IFormatProvider formatProvider, string expected) - { - if (format == null) - { - if (formatProvider == null) - { - Assert.Equal(expected, keyTime.ToString()); - } - - Assert.Equal(expected, keyTime.ToString(formatProvider)); - } - - Assert.Equal(expected, ((IFormattable)keyTime).ToString(format, formatProvider)); - } - } -} \ No newline at end of file diff --git a/src/libraries/System.Runtime.WindowsRuntime.UI.Xaml/tests/Windows/UI/Xaml/Media/MatrixTests.cs b/src/libraries/System.Runtime.WindowsRuntime.UI.Xaml/tests/Windows/UI/Xaml/Media/MatrixTests.cs deleted file mode 100644 index 8f5acba..0000000 --- a/src/libraries/System.Runtime.WindowsRuntime.UI.Xaml/tests/Windows/UI/Xaml/Media/MatrixTests.cs +++ /dev/null @@ -1,369 +0,0 @@ -// 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.Collections.Generic; -using System.Globalization; -using Windows.Foundation; -using Xunit; - -namespace Windows.UI.Xaml.Media.Media3D.Tests -{ - [ConditionalClass(typeof(PlatformDetection), nameof(PlatformDetection.IsWinUISupported))] - public class Matrix3DTests - { - [Fact] - public void Ctor_Default() - { - var matrix = new Matrix3D(); - Assert.Equal(0, matrix.M11); - Assert.Equal(0, matrix.M12); - Assert.Equal(0, matrix.M13); - Assert.Equal(0, matrix.M14); - Assert.Equal(0, matrix.M21); - Assert.Equal(0, matrix.M22); - Assert.Equal(0, matrix.M23); - Assert.Equal(0, matrix.M24); - Assert.Equal(0, matrix.M31); - Assert.Equal(0, matrix.M32); - Assert.Equal(0, matrix.M33); - Assert.Equal(0, matrix.M34); - Assert.Equal(0, matrix.OffsetX); - Assert.Equal(0, matrix.OffsetY); - Assert.Equal(0, matrix.OffsetZ); - Assert.Equal(0, matrix.M44); - - Assert.False(matrix.IsIdentity); - } - - [Theory] - [InlineData(-1, -2, -3, -4, -5, -6, -7, -8, -9, -10, -11, -12, -13, -14, -15, -16, false, false)] - [InlineData(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, false, false)] - [InlineData(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, false, false)] - [InlineData(1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, true, true)] - [InlineData(1, 2, 0, 0, 0, 1, 2, 0, 4, 0, 1, 2, 0, 4, 0, 1, false, true)] - [InlineData(double.NaN, double.NaN, double.NaN, double.NaN, double.NaN, double.NaN, double.NaN, double.NaN, double.NaN, double.NaN, double.NaN, double.NaN, double.NaN, double.NaN, double.NaN, double.NaN, false, true)] - [InlineData(double.PositiveInfinity, double.PositiveInfinity, double.PositiveInfinity, double.PositiveInfinity, double.PositiveInfinity, double.PositiveInfinity, double.PositiveInfinity, double.PositiveInfinity, double.PositiveInfinity, double.PositiveInfinity, double.PositiveInfinity, double.PositiveInfinity, double.PositiveInfinity, double.PositiveInfinity, double.PositiveInfinity, double.PositiveInfinity, false, true)] - [InlineData(double.NegativeInfinity, double.NegativeInfinity, double.NegativeInfinity, double.NegativeInfinity, double.NegativeInfinity, double.NegativeInfinity, double.NegativeInfinity, double.NegativeInfinity, double.NegativeInfinity, double.NegativeInfinity, double.NegativeInfinity, double.NegativeInfinity, double.NegativeInfinity, double.NegativeInfinity, double.NegativeInfinity, double.NegativeInfinity, false, true)] - public void Ctor_Values(double m11, double m12, double m13, double m14, - double m21, double m22, double m23, double m24, - double m31, double m32, double m33, double m34, - double offsetX, double offsetY, double offsetZ, double m44, bool expectedIsIdentity, bool expectedHasInverse) - { - var matrix = new Matrix3D(m11, m12, m13, m14, m21, m22, m23, m24, m31, m32, m33, m34, offsetX, offsetY, offsetZ, m44); - Assert.Equal(m11, matrix.M11); - Assert.Equal(m12, matrix.M12); - Assert.Equal(m13, matrix.M13); - Assert.Equal(m14, matrix.M14); - Assert.Equal(m21, matrix.M21); - Assert.Equal(m22, matrix.M22); - Assert.Equal(m23, matrix.M23); - Assert.Equal(m24, matrix.M24); - Assert.Equal(m31, matrix.M31); - Assert.Equal(m32, matrix.M32); - Assert.Equal(m33, matrix.M33); - Assert.Equal(m34, matrix.M34); - Assert.Equal(offsetX, matrix.OffsetX); - Assert.Equal(offsetY, matrix.OffsetY); - Assert.Equal(offsetZ, matrix.OffsetZ); - Assert.Equal(m44, matrix.M44); - - Assert.Equal(expectedIsIdentity, matrix.IsIdentity); - Assert.Equal(expectedHasInverse, matrix.HasInverse); - } - - [Fact] - public void Identity_Get_ReturnsExpected() - { - Matrix3D matrix = Matrix3D.Identity; - Assert.Equal(1, matrix.M11); - Assert.Equal(0, matrix.M12); - Assert.Equal(0, matrix.M13); - Assert.Equal(0, matrix.M14); - Assert.Equal(0, matrix.M21); - Assert.Equal(1, matrix.M22); - Assert.Equal(0, matrix.M23); - Assert.Equal(0, matrix.M24); - Assert.Equal(0, matrix.M31); - Assert.Equal(0, matrix.M32); - Assert.Equal(1, matrix.M33); - Assert.Equal(0, matrix.M34); - Assert.Equal(0, matrix.OffsetX); - Assert.Equal(0, matrix.OffsetY); - Assert.Equal(0, matrix.OffsetZ); - Assert.Equal(1, matrix.M44); - - Assert.True(matrix.IsIdentity); - Assert.True(matrix.HasInverse); - } - - public static IEnumerable Values_TestData() - { - yield return new object[] { -1 }; - yield return new object[] { 0 }; - yield return new object[] { 1 }; - yield return new object[] { float.NaN }; - yield return new object[] { float.PositiveInfinity }; - yield return new object[] { float.NegativeInfinity }; - } - - [Theory] - [MemberData(nameof(Values_TestData))] - public void M11_Set_GetReturnsExpected(double value) - { - var matrix = new Matrix3D { M11 = value }; - Assert.Equal(value, matrix.M11); - } - - [Theory] - [MemberData(nameof(Values_TestData))] - public void M12_Set_GetReturnsExpected(double value) - { - var matrix = new Matrix3D { M12 = value }; - Assert.Equal(value, matrix.M12); - } - - [Theory] - [MemberData(nameof(Values_TestData))] - public void M13_Set_GetReturnsExpected(double value) - { - var matrix = new Matrix3D { M13 = value }; - Assert.Equal(value, matrix.M13); - } - - [Theory] - [MemberData(nameof(Values_TestData))] - public void M14_Set_GetReturnsExpected(double value) - { - var matrix = new Matrix3D { M14 = value }; - Assert.Equal(value, matrix.M14); - } - - [Theory] - [MemberData(nameof(Values_TestData))] - public void M21_Set_GetReturnsExpected(double value) - { - var matrix = new Matrix3D { M21 = value }; - Assert.Equal(value, matrix.M21); - } - - [Theory] - [MemberData(nameof(Values_TestData))] - public void M22_Set_GetReturnsExpected(double value) - { - var matrix = new Matrix3D { M22 = value }; - Assert.Equal(value, matrix.M22); - } - - [Theory] - [MemberData(nameof(Values_TestData))] - public void M23_Set_GetReturnsExpected(double value) - { - var matrix = new Matrix3D { M23 = value }; - Assert.Equal(value, matrix.M23); - } - - [Theory] - [MemberData(nameof(Values_TestData))] - public void M24_Set_GetReturnsExpected(double value) - { - var matrix = new Matrix3D { M24 = value }; - Assert.Equal(value, matrix.M24); - } - [Theory] - [MemberData(nameof(Values_TestData))] - public void M31_Set_GetReturnsExpected(double value) - { - var matrix = new Matrix3D { M31 = value }; - Assert.Equal(value, matrix.M31); - } - - [Theory] - [MemberData(nameof(Values_TestData))] - public void M32_Set_GetReturnsExpected(double value) - { - var matrix = new Matrix3D { M32 = value }; - Assert.Equal(value, matrix.M32); - } - - [Theory] - [MemberData(nameof(Values_TestData))] - public void M33_Set_GetReturnsExpected(double value) - { - var matrix = new Matrix3D { M33 = value }; - Assert.Equal(value, matrix.M33); - } - - [Theory] - [MemberData(nameof(Values_TestData))] - public void M34_Set_GetReturnsExpected(double value) - { - var matrix = new Matrix3D { M34 = value }; - Assert.Equal(value, matrix.M34); - } - - [Theory] - [MemberData(nameof(Values_TestData))] - public void OffsetX_Set_GetReturnsExpected(double value) - { - var matrix = new Matrix3D { OffsetX = value }; - Assert.Equal(value, matrix.OffsetX); - } - - [Theory] - [MemberData(nameof(Values_TestData))] - public void OffsetY_Set_GetReturnsExpected(double value) - { - var matrix = new Matrix3D { OffsetY = value }; - Assert.Equal(value, matrix.OffsetY); - } - - [Theory] - [MemberData(nameof(Values_TestData))] - public void OffsetZ_Set_GetReturnsExpected(double value) - { - var matrix = new Matrix3D { OffsetZ = value }; - Assert.Equal(value, matrix.OffsetZ); - } - - [Theory] - [MemberData(nameof(Values_TestData))] - public void M44_Set_GetReturnsExpected(double value) - { - var matrix = new Matrix3D { M44 = value }; - Assert.Equal(value, matrix.M44); - } - - public static IEnumerable Equals_TestData() - { - var matrix = new Matrix3D(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16); - - yield return new object[] { matrix, new Matrix3D(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16), true }; - yield return new object[] { matrix, new Matrix3D(2, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16), false }; - yield return new object[] { matrix, new Matrix3D(1, 3, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16), false }; - yield return new object[] { matrix, new Matrix3D(1, 2, 4, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16), false }; - yield return new object[] { matrix, new Matrix3D(1, 2, 3, 5, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16), false }; - yield return new object[] { matrix, new Matrix3D(1, 2, 3, 4, 6, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16), false }; - yield return new object[] { matrix, new Matrix3D(1, 2, 3, 4, 5, 7, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16), false }; - yield return new object[] { matrix, new Matrix3D(1, 2, 3, 4, 5, 6, 8, 8, 9, 10, 11, 12, 13, 14, 15, 16), false }; - yield return new object[] { matrix, new Matrix3D(1, 2, 3, 4, 5, 6, 7, 9, 9, 10, 11, 12, 13, 14, 15, 16), false }; - yield return new object[] { matrix, new Matrix3D(1, 2, 3, 4, 5, 6, 7, 8, 10, 10, 11, 12, 13, 14, 15, 16), false }; - yield return new object[] { matrix, new Matrix3D(1, 2, 3, 4, 5, 6, 7, 8, 9, 11, 11, 12, 13, 14, 15, 16), false }; - yield return new object[] { matrix, new Matrix3D(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 12, 12, 13, 14, 15, 16), false }; - yield return new object[] { matrix, new Matrix3D(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 13, 13, 14, 15, 16), false }; - yield return new object[] { matrix, new Matrix3D(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 14, 14, 15, 16), false }; - yield return new object[] { matrix, new Matrix3D(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 15, 15, 16), false }; - yield return new object[] { matrix, new Matrix3D(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 16, 16), false }; - yield return new object[] { matrix, new Matrix3D(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 16, 17), false }; - - yield return new object[] { Matrix3D.Identity, Matrix3D.Identity, true }; - yield return new object[] { Matrix3D.Identity, new Matrix3D(1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1), true }; - yield return new object[] { Matrix3D.Identity, new Matrix3D(1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1), false }; - - yield return new object[] { Matrix3D.Identity, new object(), false }; - yield return new object[] { Matrix3D.Identity, null, false }; - } - - [Theory] - [MemberData(nameof(Equals_TestData))] - public void Equals_Object_ReturnsExpected(Matrix3D matrix, object other, bool expected) - { - Assert.Equal(expected, matrix.Equals(other)); - if (other is Matrix3D otherMatrix) - { - Assert.Equal(expected, matrix.Equals(otherMatrix)); - Assert.Equal(expected, matrix == otherMatrix); - Assert.Equal(!expected, matrix != otherMatrix); - Assert.Equal(expected, matrix.GetHashCode().Equals(otherMatrix.GetHashCode())); - } - } - - [Fact] - public void Multiply_Matrices_ReturnsExpected() - { - var matrix1 = new Matrix3D(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16); - var matrix2 = new Matrix3D(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16); - - Matrix3D result = matrix1 * matrix2; - Assert.Equal(new Matrix3D(90, 100, 110, 120, 202, 228, 254, 280, 314, 356, 398, 440, 426, 484, 542, 600), result); - - Assert.False(result.IsIdentity); - Assert.False(result.HasInverse); - } - - [Fact] - public void Invert_Affine_ReturnsExpected() - { - var matrix = new Matrix3D(1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1); - matrix.Invert(); - - Assert.Equal(new Matrix3D(1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1), matrix); - } - - [Fact] - public void Invert_NonAffine_ReturnsExpected() - { - var matrix = new Matrix3D(1, 2, 0, 0, 0, 1, 2, 0, 4, 0, 1, 2, 0, 4, 0, 1); - matrix.Invert(); - - string expected = ((IFormattable)new Matrix3D(0.515151515151515, -0.0606060606060606, 0.121212121212121, -0.242424242424242, 0.242424242424242, 0.0303030303030303, -0.0606060606060606, 0.121212121212121, -0.121212121212121, 0.484848484848485, 0.0303030303030303, -0.0606060606060606, -0.96969696969697, -0.121212121212121, 0.242424242424242, 0.515151515151515)).ToString("N2", null); - Assert.Equal(expected, ((IFormattable)matrix).ToString("N2", null)); - } - - [Fact] - public void Invert_NotInvertible_ThrowsInvalidOperationException() - { - var matrix = new Matrix3D(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16); - Assert.Throws(() => matrix.Invert()); - } - - [Fact] - public void Invert_AffineNotInvertible_ThrowsInvalidOperationException() - { - var matrix = new Matrix3D(1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1); - Assert.Throws(() => matrix.Invert()); - } - - public static IEnumerable ToString_TestData() - { - string cultureSeparator = CultureInfo.CurrentCulture.NumberFormat.NumberDecimalSeparator; - char decimalSeparator = cultureSeparator.Length > 0 && cultureSeparator[0] == ',' ? ';' : ','; - - yield return new object[] { Matrix3D.Identity, null, null, "Identity" }; - yield return new object[] { Matrix3D.Identity, "InvalidFormat", CultureInfo.CurrentCulture, "Identity" }; - yield return new object[] { new Matrix3D(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16), null, null, $"1{decimalSeparator}2{decimalSeparator}3{decimalSeparator}4{decimalSeparator}5{decimalSeparator}6{decimalSeparator}7{decimalSeparator}8{decimalSeparator}9{decimalSeparator}10{decimalSeparator}11{decimalSeparator}12{decimalSeparator}13{decimalSeparator}14{decimalSeparator}15{decimalSeparator}16" }; - - var matrix = new Matrix3D(2.2, 2.2, 2.2, 2.2, 2.2, 2.2, 2.2, 2.2, 2.2, 2.2, 2.2, 2.2, 2.2, 2.2, 2.2, 2.2); - - var culture = new CultureInfo("en-US"); - culture.NumberFormat.NumberDecimalSeparator = "|"; - yield return new object[] { matrix, "abc", culture, "abc,abc,abc,abc,abc,abc,abc,abc,abc,abc,abc,abc,abc,abc,abc,abc" }; - yield return new object[] { matrix, "N4", culture, "2|2000,2|2000,2|2000,2|2000,2|2000,2|2000,2|2000,2|2000,2|2000,2|2000,2|2000,2|2000,2|2000,2|2000,2|2000,2|2000" }; - yield return new object[] { matrix, null, culture, "2|2,2|2,2|2,2|2,2|2,2|2,2|2,2|2,2|2,2|2,2|2,2|2,2|2,2|2,2|2,2|2" }; - - var commaCulture = new CultureInfo("en-US"); - commaCulture.NumberFormat.NumberDecimalSeparator = ","; - yield return new object[] { matrix, null, commaCulture, "2,2;2,2;2,2;2,2;2,2;2,2;2,2;2,2;2,2;2,2;2,2;2,2;2,2;2,2;2,2;2,2" }; - - yield return new object[] { matrix, null, null, $"{2.2.ToString()}{decimalSeparator}{2.2.ToString()}{decimalSeparator}{2.2.ToString()}{decimalSeparator}{2.2.ToString()}{decimalSeparator}{2.2.ToString()}{decimalSeparator}{2.2.ToString()}{decimalSeparator}{2.2.ToString()}{decimalSeparator}{2.2.ToString()}{decimalSeparator}{2.2.ToString()}{decimalSeparator}{2.2.ToString()}{decimalSeparator}{2.2.ToString()}{decimalSeparator}{2.2.ToString()}{decimalSeparator}{2.2.ToString()}{decimalSeparator}{2.2.ToString()}{decimalSeparator}{2.2.ToString()}{decimalSeparator}{2.2.ToString()}" }; - } - - [Theory] - [MemberData(nameof(ToString_TestData))] - public void ToString_Invoke_ReturnsExpected(Matrix3D matrix, string format, IFormatProvider formatProvider, string expected) - { - if (format == null) - { - if (formatProvider == null) - { - Assert.Equal(expected, matrix.ToString()); - } - - Assert.Equal(expected, matrix.ToString(formatProvider)); - } - - Assert.Equal(expected, ((IFormattable)matrix).ToString(format, formatProvider)); - } - } -} diff --git a/src/libraries/System.Runtime.WindowsRuntime.UI.Xaml/tests/Windows/UI/Xaml/Media3D/Matrix3DTests.cs b/src/libraries/System.Runtime.WindowsRuntime.UI.Xaml/tests/Windows/UI/Xaml/Media3D/Matrix3DTests.cs deleted file mode 100644 index 074cdbd..0000000 --- a/src/libraries/System.Runtime.WindowsRuntime.UI.Xaml/tests/Windows/UI/Xaml/Media3D/Matrix3DTests.cs +++ /dev/null @@ -1,212 +0,0 @@ -// 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.Collections.Generic; -using System.Diagnostics; -using System.Globalization; -using Windows.Foundation; -using Xunit; - -namespace Windows.UI.Xaml.Media.Tests -{ - [ConditionalClass(typeof(PlatformDetection), nameof(PlatformDetection.IsWinUISupported))] - public class MatrixTests - { - [Fact] - public void Ctor_Default() - { - var matrix = new Matrix(); - Assert.Equal(0, matrix.M11); - Assert.Equal(0, matrix.M12); - Assert.Equal(0, matrix.M21); - Assert.Equal(0, matrix.M22); - Assert.Equal(0, matrix.OffsetX); - Assert.Equal(0, matrix.OffsetY); - - Assert.False(matrix.IsIdentity); - } - - [Theory] - [InlineData(-1, -2, -3, -4, -5, -6, false)] - [InlineData(0, 0, 0, 0, 0, 0, false)] - [InlineData(1, 1, 1, 1, 1, 1, false)] - [InlineData(1, 0, 0, 1, 0, 0, true)] - [InlineData(double.NaN, double.NaN, double.NaN, double.NaN, double.NaN, double.NaN, false)] - [InlineData(double.PositiveInfinity, double.PositiveInfinity, double.PositiveInfinity, double.PositiveInfinity, double.PositiveInfinity, double.PositiveInfinity, false)] - [InlineData(double.NegativeInfinity, double.NegativeInfinity, double.NegativeInfinity, double.NegativeInfinity, double.NegativeInfinity, double.NegativeInfinity, false)] - public void Ctor_Values(double m11, double m12, double m21, double m22, double offsetX, double offsetY, bool expectedIsIdentity) - { - var matrix = new Matrix(m11, m12, m21, m22, offsetX, offsetY); - Assert.Equal(m11, matrix.M11); - Assert.Equal(m12, matrix.M12); - Assert.Equal(m21, matrix.M21); - Assert.Equal(m22, matrix.M22); - Assert.Equal(offsetX, matrix.OffsetX); - Assert.Equal(offsetY, matrix.OffsetY); - - Assert.Equal(expectedIsIdentity, matrix.IsIdentity); - } - - [Fact] - public void Identity_Get_ReturnsExpected() - { - Matrix matrix = Matrix.Identity; - Assert.Equal(1, matrix.M11); - Assert.Equal(0, matrix.M12); - Assert.Equal(0, matrix.M21); - Assert.Equal(1, matrix.M22); - Assert.Equal(0, matrix.OffsetX); - Assert.Equal(0, matrix.OffsetY); - - Assert.True(matrix.IsIdentity); - } - - public static IEnumerable Values_TestData() - { - yield return new object[] { -1 }; - yield return new object[] { 0 }; - yield return new object[] { 1 }; - yield return new object[] { float.NaN }; - yield return new object[] { float.PositiveInfinity }; - yield return new object[] { float.NegativeInfinity }; - } - - [Theory] - [MemberData(nameof(Values_TestData))] - public void M11_Set_GetReturnsExpected(double value) - { - var matrix = new Matrix { M11 = value }; - Assert.Equal(value, matrix.M11); - } - - [Theory] - [MemberData(nameof(Values_TestData))] - public void M12_Set_GetReturnsExpected(double value) - { - var matrix = new Matrix { M12 = value }; - Assert.Equal(value, matrix.M12); - } - - [Theory] - [MemberData(nameof(Values_TestData))] - public void M21_Set_GetReturnsExpected(double value) - { - var matrix = new Matrix { M21 = value }; - Assert.Equal(value, matrix.M21); - } - - [Theory] - [MemberData(nameof(Values_TestData))] - public void M22_Set_GetReturnsExpected(double value) - { - var matrix = new Matrix { M22 = value }; - Assert.Equal(value, matrix.M22); - } - - [Theory] - [MemberData(nameof(Values_TestData))] - public void OffsetX_Set_GetReturnsExpected(double value) - { - var matrix = new Matrix { OffsetX = value }; - Assert.Equal(value, matrix.OffsetX); - } - - [Theory] - [MemberData(nameof(Values_TestData))] - public void OffsetY_Set_GetReturnsExpected(double value) - { - var matrix = new Matrix { OffsetY = value }; - Assert.Equal(value, matrix.OffsetY); - } - - [Fact] - public void Transform_Identity_ReturnsPoint() - { - Point transformedPoint = Matrix.Identity.Transform(new Point(1, 2)); - Assert.Equal(new Point(1, 2), transformedPoint); - } - - [Fact] - public void Transform_Point_ReturnsExpected() - { - var matrix = new Matrix(1, 2, 3, 4, 5, 6); - var point = new Point(1, 2); - - Point transformedPoint = matrix.Transform(point); - Assert.Equal(new Point(12, 16), transformedPoint); - } - - public static IEnumerable Equals_TestData() - { - yield return new object[] { new Matrix(1, 2, 3, 4, 5, 6), new Matrix(1, 2, 3, 4, 5, 6), true }; - yield return new object[] { new Matrix(1, 2, 3, 4, 5, 6), new Matrix(2, 2, 3, 4, 5, 6), false }; - yield return new object[] { new Matrix(1, 2, 3, 4, 5, 6), new Matrix(1, 3, 3, 4, 5, 6), false }; - yield return new object[] { new Matrix(1, 2, 3, 4, 5, 6), new Matrix(1, 2, 4, 4, 5, 6), false }; - yield return new object[] { new Matrix(1, 2, 3, 4, 5, 6), new Matrix(1, 2, 3, 5, 5, 6), false }; - yield return new object[] { new Matrix(1, 2, 3, 4, 5, 6), new Matrix(1, 2, 3, 4, 6, 6), false }; - yield return new object[] { new Matrix(1, 2, 3, 4, 5, 6), new Matrix(1, 2, 3, 4, 5, 7), false }; - - yield return new object[] { Matrix.Identity, Matrix.Identity, true }; - yield return new object[] { Matrix.Identity, new Matrix(1, 0, 0, 1, 0, 0), true }; - yield return new object[] { Matrix.Identity, new Matrix(1, 0, 0, 0, 0, 0), false }; - - yield return new object[] { new Matrix(1, 2, 3, 4, 5, 6), new object(), false }; - yield return new object[] { new Matrix(1, 2, 3, 4, 5, 6), null, false }; - } - - [Theory] - [MemberData(nameof(Equals_TestData))] - public void Equals_Object_ReturnsExpected(Matrix matrix, object other, bool expected) - { - Assert.Equal(expected, matrix.Equals(other)); - if (other is Matrix otherMatrix) - { - Assert.Equal(expected, matrix.Equals(otherMatrix)); - Assert.Equal(expected, matrix == otherMatrix); - Assert.Equal(!expected, matrix != otherMatrix); - Assert.Equal(expected, matrix.GetHashCode().Equals(otherMatrix.GetHashCode())); - } - } - - public static IEnumerable ToString_TestData() - { - string cultureSeparator = CultureInfo.CurrentCulture.NumberFormat.NumberDecimalSeparator; - char decimalSeparator = cultureSeparator.Length > 0 && cultureSeparator[0] == ',' ? ';' : ','; - - yield return new object[] { Matrix.Identity, null, null, "Identity" }; - yield return new object[] { Matrix.Identity, "InvalidFormat", CultureInfo.CurrentCulture, "Identity" }; - yield return new object[] { new Matrix(1, 2, 3, 4, 5, 6), null, null, $"1{decimalSeparator}2{decimalSeparator}3{decimalSeparator}4{decimalSeparator}5{decimalSeparator}6" }; - - var culture = new CultureInfo("en-US"); - culture.NumberFormat.NumberDecimalSeparator = "|"; - yield return new object[] { new Matrix(2.2, 2.2, 2.2, 2.2, 2.2, 2.2), "abc", culture, "abc,abc,abc,abc,abc,abc" }; - yield return new object[] { new Matrix(2.2, 2.2, 2.2, 2.2, 2.2, 2.2), "N4", culture, "2|2000,2|2000,2|2000,2|2000,2|2000,2|2000" }; - yield return new object[] { new Matrix(2.2, 2.2, 2.2, 2.2, 2.2, 2.2), null, culture, "2|2,2|2,2|2,2|2,2|2,2|2" }; - - var commaCulture = new CultureInfo("en-US"); - commaCulture.NumberFormat.NumberDecimalSeparator = ","; - yield return new object[] { new Matrix(2.2, 2.2, 2.2, 2.2, 2.2, 2.2), null, commaCulture, "2,2;2,2;2,2;2,2;2,2;2,2" }; - - yield return new object[] { new Matrix(2.2, 2.2, 2.2, 2.2, 2.2, 2.2), null, null, $"{2.2.ToString()}{decimalSeparator}{2.2.ToString()}{decimalSeparator}{2.2.ToString()}{decimalSeparator}{2.2.ToString()}{decimalSeparator}{2.2.ToString()}{decimalSeparator}{2.2.ToString()}" }; - } - - [Theory] - [MemberData(nameof(ToString_TestData))] - public void ToString_Invoke_ReturnsExpected(Matrix matrix, string format, IFormatProvider formatProvider, string expected) - { - if (format == null) - { - if (formatProvider == null) - { - Assert.Equal(expected, matrix.ToString()); - } - - Assert.Equal(expected, matrix.ToString(formatProvider)); - } - - Assert.Equal(expected, ((IFormattable)matrix).ToString(format, formatProvider)); - } - } -} \ No newline at end of file diff --git a/src/libraries/System.Runtime.WindowsRuntime.UI.Xaml/tests/Windows/UI/Xaml/ThicknessTests.cs b/src/libraries/System.Runtime.WindowsRuntime.UI.Xaml/tests/Windows/UI/Xaml/ThicknessTests.cs deleted file mode 100644 index 9efa20a..0000000 --- a/src/libraries/System.Runtime.WindowsRuntime.UI.Xaml/tests/Windows/UI/Xaml/ThicknessTests.cs +++ /dev/null @@ -1,163 +0,0 @@ -// 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.Collections.Generic; -using System.Runtime.InteropServices; -using Xunit; - -namespace Windows.UI.Xaml.Tests -{ - [ConditionalClass(typeof(PlatformDetection), nameof(PlatformDetection.IsWinUISupported))] - public class ThicknessTests - { - [Fact] - public void Ctor_Default() - { - var thickness = new Thickness(); - Assert.Equal(0, thickness.Left); - Assert.Equal(0, thickness.Top); - Assert.Equal(0, thickness.Right); - Assert.Equal(0, thickness.Bottom); - } - - public static IEnumerable Values_TestData() - { - yield return new object[] { -1 }; - yield return new object[] { 0 }; - yield return new object[] { 1 }; - yield return new object[] { double.MaxValue }; - yield return new object[] { double.NaN }; - yield return new object[] { double.PositiveInfinity }; - yield return new object[] { double.NegativeInfinity }; - } - - [Theory] - [MemberData(nameof(Values_TestData))] - public void Ctor_WithLengthParameter(double uniformLength) - { - var thickness = new Thickness(uniformLength); - Assert.Equal(uniformLength, thickness.Left); - Assert.Equal(uniformLength, thickness.Top); - Assert.Equal(uniformLength, thickness.Right); - Assert.Equal(uniformLength, thickness.Bottom); - } - - [Theory] - [InlineData(-1, -2, -3, -4)] - [InlineData(0, 0, 0, 0)] - [InlineData(1, 2, 3, 4)] - [InlineData(double.NaN, double.NaN, double.NaN, double.NaN)] - [InlineData(double.PositiveInfinity, double.PositiveInfinity, double.PositiveInfinity, double.PositiveInfinity)] - [InlineData(double.NegativeInfinity, double.NegativeInfinity, double.NegativeInfinity, double.NegativeInfinity)] - public void Ctor_Left_Top_Right_Bottom(double left, double top, double right, double bottom) - { - var thickness = new Thickness(left, top, right, bottom); - Assert.Equal(left, thickness.Left); - Assert.Equal(top, thickness.Top); - Assert.Equal(right, thickness.Right); - Assert.Equal(bottom, thickness.Bottom); - } - - [Theory] - [MemberData(nameof(Values_TestData))] - public void Left_Set_GetReturnsExpected(double value) - { - var thickness = new Thickness { Left = value }; - Assert.Equal(value, thickness.Left); - } - - [Theory] - [MemberData(nameof(Values_TestData))] - public void Top_Set_GetReturnsExpected(double value) - { - var thickness = new Thickness { Top = value }; - Assert.Equal(value, thickness.Top); - } - - [Theory] - [MemberData(nameof(Values_TestData))] - public void Right_Set_GetReturnsExpected(double value) - { - var thickness = new Thickness { Right = value }; - Assert.Equal(value, thickness.Right); - } - - [Theory] - [MemberData(nameof(Values_TestData))] - public void Bottom_Set_GetReturnsExpected(double value) - { - var cornerRadius = new Thickness { Bottom = value }; - Assert.Equal(value, cornerRadius.Bottom); - } - - public static IEnumerable Equals_TestData() - { - yield return new object[] { new Thickness(1, 2, 3, 4), new Thickness(1, 2, 3, 4), true }; - yield return new object[] { new Thickness(1, 2, 3, 4), new Thickness(2, 2, 3, 4), false }; - yield return new object[] { new Thickness(1, 2, 3, 4), new Thickness(1, 3, 3, 4), false }; - yield return new object[] { new Thickness(1, 2, 3, 4), new Thickness(1, 2, 4, 4), false }; - yield return new object[] { new Thickness(1, 2, 3, 4), new Thickness(1, 2, 3, 5), false }; - - yield return new object[] { new Thickness(1, 2, 3, 4), new object(), false }; - yield return new object[] { new Thickness(1, 2, 3, 4), null, false }; - } - - [Theory] - [MemberData(nameof(Equals_TestData))] - public void Equals_Object_ReturnsExpected(Thickness thickness, object other, bool expected) - { - Assert.Equal(expected, thickness.Equals(other)); - if (other is Thickness otherThickness) - { - Assert.Equal(expected, thickness.Equals(otherThickness)); - Assert.Equal(expected, thickness == otherThickness); - Assert.Equal(!expected, thickness != otherThickness); - Assert.Equal(expected, thickness.GetHashCode().Equals(otherThickness.GetHashCode())); - } - } - - [Fact] - public void ToString_Invoke_ReturnsExpected() - { - var thickness = new Thickness(1, 2.2, 3, 4); - Assert.Equal("1,2.2,3,4", thickness.ToString()); - } - - [Fact] - public void ToString_NaN_ReturnsAuto() - { - Thickness thickness = new FakeThickness - { - Left = double.NaN, - Top = double.NaN, - Right = double.NaN, - Bottom = double.NaN - }.ToActual(); - Assert.Equal("Auto,Auto,Auto,Auto", thickness.ToString()); - } - - public struct FakeThickness - { - public double Left; - public double Top; - public double Right; - public double Bottom; - - public Thickness ToActual() - { - ThicknessWrapper wrapper = default(ThicknessWrapper); - wrapper.Fake = this; - return wrapper.Actual; - } - } - - [StructLayout(LayoutKind.Explicit)] - public struct ThicknessWrapper - { - [FieldOffset(0)] public Thickness Actual; - [FieldOffset(0)] public FakeThickness Fake; - } - } -} diff --git a/src/libraries/System.Runtime.WindowsRuntime/Directory.Build.props b/src/libraries/System.Runtime.WindowsRuntime/Directory.Build.props deleted file mode 100644 index e314b47..0000000 --- a/src/libraries/System.Runtime.WindowsRuntime/Directory.Build.props +++ /dev/null @@ -1,9 +0,0 @@ - - - - 4.0.14.0 - ECMA - true - false - - \ No newline at end of file diff --git a/src/libraries/System.Runtime.WindowsRuntime/System.Runtime.WindowsRuntime.sln b/src/libraries/System.Runtime.WindowsRuntime/System.Runtime.WindowsRuntime.sln deleted file mode 100644 index d5377c9..0000000 --- a/src/libraries/System.Runtime.WindowsRuntime/System.Runtime.WindowsRuntime.sln +++ /dev/null @@ -1,88 +0,0 @@ -Microsoft Visual Studio Solution File, Format Version 12.00 -# Visual Studio 15 -VisualStudioVersion = 15.0.27213.1 -MinimumVisualStudioVersion = 10.0.40219.1 -Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "System.Runtime.WindowsRuntime.Tests", "tests\System.Runtime.WindowsRuntime.Tests.csproj", "{C4854B44-ABFE-4BB5-8F89-F35FE6201338}" - ProjectSection(ProjectDependencies) = postProject - {844A2A0B-4169-49C3-B367-AFDC4894E487} = {844A2A0B-4169-49C3-B367-AFDC4894E487} - EndProjectSection -EndProject -Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "System.Runtime.WindowsRuntime", "src\System.Runtime.WindowsRuntime.csproj", "{844A2A0B-4169-49C3-B367-AFDC4894E487}" - ProjectSection(ProjectDependencies) = postProject - {FDDA3E4A-B182-4CD1-B624-EBD72D8A05DA} = {FDDA3E4A-B182-4CD1-B624-EBD72D8A05DA} - EndProjectSection -EndProject -Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "System.Runtime.WindowsRuntime", "ref\System.Runtime.WindowsRuntime.csproj", "{FDDA3E4A-B182-4CD1-B624-EBD72D8A05DA}" -EndProject -Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "tests", "tests", "{1A2F9F4A-A032-433E-B914-ADD5992BB178}" -EndProject -Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "src", "src", "{E107E9C1-E893-4E87-987E-04EF0DCEAEFD}" -EndProject -Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "ref", "ref", "{2E666815-2EDB-464B-9DF6-380BF4789AD4}" -EndProject -Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "TestUtilities", "..\Common\tests\TestUtilities\TestUtilities.csproj", "{A6BDC72A-9423-4A0D-915F-996A8951EAC9}" -EndProject -Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "System.Runtime", "..\System.Runtime\src\System.Runtime.csproj", "{BF53DBB0-B4DF-49B2-8D86-EEEB484CC3C2}" -EndProject -Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "System.Runtime.Extensions", "..\System.Runtime.Extensions\src\System.Runtime.Extensions.csproj", "{BC43843F-659C-4128-B78D-323BCD9B861D}" -EndProject -Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "System.Runtime.InteropServices.WindowsRuntime", "..\System.Runtime.InteropServices.WindowsRuntime\src\System.Runtime.InteropServices.WindowsRuntime.csproj", "{B4D3A07A-9DD1-4C2F-9F4F-729A95F0F8A0}" -EndProject -Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "System.ObjectModel", "..\System.ObjectModel\src\System.ObjectModel.csproj", "{7E205DA8-F34E-4995-A902-79B5107674DC}" -EndProject -Global - GlobalSection(SolutionConfigurationPlatforms) = preSolution - Debug|Any CPU = Debug|Any CPU - Release|Any CPU = Release|Any CPU - EndGlobalSection - GlobalSection(ProjectConfigurationPlatforms) = postSolution - {C4854B44-ABFE-4BB5-8F89-F35FE6201338}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {C4854B44-ABFE-4BB5-8F89-F35FE6201338}.Debug|Any CPU.Build.0 = Debug|Any CPU - {C4854B44-ABFE-4BB5-8F89-F35FE6201338}.Release|Any CPU.ActiveCfg = Release|Any CPU - {C4854B44-ABFE-4BB5-8F89-F35FE6201338}.Release|Any CPU.Build.0 = Release|Any CPU - {844A2A0B-4169-49C3-B367-AFDC4894E487}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {844A2A0B-4169-49C3-B367-AFDC4894E487}.Debug|Any CPU.Build.0 = Debug|Any CPU - {844A2A0B-4169-49C3-B367-AFDC4894E487}.Release|Any CPU.ActiveCfg = Release|Any CPU - {844A2A0B-4169-49C3-B367-AFDC4894E487}.Release|Any CPU.Build.0 = Release|Any CPU - {FDDA3E4A-B182-4CD1-B624-EBD72D8A05DA}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {FDDA3E4A-B182-4CD1-B624-EBD72D8A05DA}.Debug|Any CPU.Build.0 = Debug|Any CPU - {FDDA3E4A-B182-4CD1-B624-EBD72D8A05DA}.Release|Any CPU.ActiveCfg = Release|Any CPU - {FDDA3E4A-B182-4CD1-B624-EBD72D8A05DA}.Release|Any CPU.Build.0 = Release|Any CPU - {A6BDC72A-9423-4A0D-915F-996A8951EAC9}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {A6BDC72A-9423-4A0D-915F-996A8951EAC9}.Debug|Any CPU.Build.0 = Debug|Any CPU - {A6BDC72A-9423-4A0D-915F-996A8951EAC9}.Release|Any CPU.ActiveCfg = Release|Any CPU - {A6BDC72A-9423-4A0D-915F-996A8951EAC9}.Release|Any CPU.Build.0 = Release|Any CPU - {BF53DBB0-B4DF-49B2-8D86-EEEB484CC3C2}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {BF53DBB0-B4DF-49B2-8D86-EEEB484CC3C2}.Debug|Any CPU.Build.0 = Debug|Any CPU - {BF53DBB0-B4DF-49B2-8D86-EEEB484CC3C2}.Release|Any CPU.ActiveCfg = Release|Any CPU - {BF53DBB0-B4DF-49B2-8D86-EEEB484CC3C2}.Release|Any CPU.Build.0 = Release|Any CPU - {BC43843F-659C-4128-B78D-323BCD9B861D}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {BC43843F-659C-4128-B78D-323BCD9B861D}.Debug|Any CPU.Build.0 = Debug|Any CPU - {BC43843F-659C-4128-B78D-323BCD9B861D}.Release|Any CPU.ActiveCfg = Release|Any CPU - {BC43843F-659C-4128-B78D-323BCD9B861D}.Release|Any CPU.Build.0 = Release|Any CPU - {B4D3A07A-9DD1-4C2F-9F4F-729A95F0F8A0}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {B4D3A07A-9DD1-4C2F-9F4F-729A95F0F8A0}.Debug|Any CPU.Build.0 = Debug|Any CPU - {B4D3A07A-9DD1-4C2F-9F4F-729A95F0F8A0}.Release|Any CPU.ActiveCfg = Release|Any CPU - {B4D3A07A-9DD1-4C2F-9F4F-729A95F0F8A0}.Release|Any CPU.Build.0 = Release|Any CPU - {7E205DA8-F34E-4995-A902-79B5107674DC}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {7E205DA8-F34E-4995-A902-79B5107674DC}.Debug|Any CPU.Build.0 = Debug|Any CPU - {7E205DA8-F34E-4995-A902-79B5107674DC}.Release|Any CPU.ActiveCfg = Release|Any CPU - {7E205DA8-F34E-4995-A902-79B5107674DC}.Release|Any CPU.Build.0 = Release|Any CPU - EndGlobalSection - GlobalSection(SolutionProperties) = preSolution - HideSolutionNode = FALSE - EndGlobalSection - GlobalSection(NestedProjects) = preSolution - {C4854B44-ABFE-4BB5-8F89-F35FE6201338} = {1A2F9F4A-A032-433E-B914-ADD5992BB178} - {844A2A0B-4169-49C3-B367-AFDC4894E487} = {E107E9C1-E893-4E87-987E-04EF0DCEAEFD} - {FDDA3E4A-B182-4CD1-B624-EBD72D8A05DA} = {2E666815-2EDB-464B-9DF6-380BF4789AD4} - {A6BDC72A-9423-4A0D-915F-996A8951EAC9} = {1A2F9F4A-A032-433E-B914-ADD5992BB178} - {BF53DBB0-B4DF-49B2-8D86-EEEB484CC3C2} = {E107E9C1-E893-4E87-987E-04EF0DCEAEFD} - {BC43843F-659C-4128-B78D-323BCD9B861D} = {E107E9C1-E893-4E87-987E-04EF0DCEAEFD} - {B4D3A07A-9DD1-4C2F-9F4F-729A95F0F8A0} = {E107E9C1-E893-4E87-987E-04EF0DCEAEFD} - {7E205DA8-F34E-4995-A902-79B5107674DC} = {E107E9C1-E893-4E87-987E-04EF0DCEAEFD} - EndGlobalSection - GlobalSection(ExtensibilityGlobals) = postSolution - SolutionGuid = {61FA1A49-D9AA-4129-AFD5-9951C32B2CF5} - EndGlobalSection -EndGlobal diff --git a/src/libraries/System.Runtime.WindowsRuntime/pkg/System.Runtime.WindowsRuntime.pkgproj b/src/libraries/System.Runtime.WindowsRuntime/pkg/System.Runtime.WindowsRuntime.pkgproj deleted file mode 100644 index 92ea152..0000000 --- a/src/libraries/System.Runtime.WindowsRuntime/pkg/System.Runtime.WindowsRuntime.pkgproj +++ /dev/null @@ -1,65 +0,0 @@ - - - - - net461;netcoreapp2.0;uap10.0.16299;$(AllXamarinFrameworks) - - - - - - netcore45;wp8;net45 - - - net451;netcore451;wpa81;netcoreapp1.0 - - - - - .NETCore,Version=v4.5.1;WindowsPhoneApp,Version=v8.1 - - - - - - - - - - runtimes/win-aot/lib/uap10.0.16299 - - - runtimes/win/lib/uap10.0.16299 - - - - - - - - - - - <_buildTargetsTFMs Include="net45;net451;net461" - TFM="%(Identity)" - SourceFile=".\build\%(TFM)\$(Id).targets" /> - - - - - - - - - diff --git a/src/libraries/System.Runtime.WindowsRuntime/pkg/build/net45/System.Runtime.WindowsRuntime.targets b/src/libraries/System.Runtime.WindowsRuntime/pkg/build/net45/System.Runtime.WindowsRuntime.targets deleted file mode 100644 index b20cd38..0000000 --- a/src/libraries/System.Runtime.WindowsRuntime/pkg/build/net45/System.Runtime.WindowsRuntime.targets +++ /dev/null @@ -1,32 +0,0 @@ - - - - - - - <_HasReferenceToSystemRuntime>true - - - - - - false - - false - - - - - - - - - - - diff --git a/src/libraries/System.Runtime.WindowsRuntime/pkg/build/net451/System.Runtime.WindowsRuntime.targets b/src/libraries/System.Runtime.WindowsRuntime/pkg/build/net451/System.Runtime.WindowsRuntime.targets deleted file mode 100644 index 3d279ba..0000000 --- a/src/libraries/System.Runtime.WindowsRuntime/pkg/build/net451/System.Runtime.WindowsRuntime.targets +++ /dev/null @@ -1,31 +0,0 @@ - - - - - - - <_HasReferenceToSystemRuntime>true - - - - - false - - false - - - - - - - - - - - diff --git a/src/libraries/System.Runtime.WindowsRuntime/pkg/build/net461/System.Runtime.WindowsRuntime.targets b/src/libraries/System.Runtime.WindowsRuntime/pkg/build/net461/System.Runtime.WindowsRuntime.targets deleted file mode 100644 index 3c95db8..0000000 --- a/src/libraries/System.Runtime.WindowsRuntime/pkg/build/net461/System.Runtime.WindowsRuntime.targets +++ /dev/null @@ -1,31 +0,0 @@ - - - - - - - true - - - - - false - - false - - - - - - - - - - - diff --git a/src/libraries/System.Runtime.WindowsRuntime/ref/System.Runtime.WindowsRuntime.Manual.cs b/src/libraries/System.Runtime.WindowsRuntime/ref/System.Runtime.WindowsRuntime.Manual.cs deleted file mode 100644 index f7ef82e..0000000 --- a/src/libraries/System.Runtime.WindowsRuntime/ref/System.Runtime.WindowsRuntime.Manual.cs +++ /dev/null @@ -1,34 +0,0 @@ -// 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. -// ------------------------------------------------------------------------------ -// Changes to this file must follow the https://aka.ms/api-review process. -// ------------------------------------------------------------------------------ - - -using System; -using System.Security; - -// Including the explicit implementations of IFormattable because if we use what -// the tool generates we will end up with a member name "global::System.IFormattable.ToString" -// which is different then what is in the implementation. We can avoid it in the manual -// file because of the usings at the top of this file instead of fully qualify with global::. - -namespace Windows.Foundation -{ - public partial struct Point : IFormattable - { - string IFormattable.ToString(string? format, IFormatProvider? provider) { throw null; } - } - public partial struct Rect : IFormattable - { - string IFormattable.ToString(string? format, IFormatProvider? provider) { throw null; } - } -} -namespace Windows.UI -{ - public partial struct Color : IFormattable - { - string IFormattable.ToString(string? format, IFormatProvider? provider) { throw null; } - } -} diff --git a/src/libraries/System.Runtime.WindowsRuntime/ref/System.Runtime.WindowsRuntime.cs b/src/libraries/System.Runtime.WindowsRuntime/ref/System.Runtime.WindowsRuntime.cs deleted file mode 100644 index c3e6e2f..0000000 --- a/src/libraries/System.Runtime.WindowsRuntime/ref/System.Runtime.WindowsRuntime.cs +++ /dev/null @@ -1,210 +0,0 @@ -// 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. -// ------------------------------------------------------------------------------ -// Changes to this file must follow the https://aka.ms/api-review process. -// ------------------------------------------------------------------------------ - -namespace System -{ - [System.CLSCompliantAttribute(false)] - public static partial class WindowsRuntimeSystemExtensions - { - public static global::Windows.Foundation.IAsyncAction AsAsyncAction(this System.Threading.Tasks.Task source) { throw null; } - public static global::Windows.Foundation.IAsyncOperation AsAsyncOperation(this System.Threading.Tasks.Task source) { throw null; } - public static System.Threading.Tasks.Task AsTask(this global::Windows.Foundation.IAsyncAction source) { throw null; } - public static System.Threading.Tasks.Task AsTask(this global::Windows.Foundation.IAsyncAction source, System.Threading.CancellationToken cancellationToken) { throw null; } - public static System.Threading.Tasks.Task AsTask(this global::Windows.Foundation.IAsyncActionWithProgress source) { throw null; } - public static System.Threading.Tasks.Task AsTask(this global::Windows.Foundation.IAsyncActionWithProgress source, System.IProgress? progress) { throw null; } - public static System.Threading.Tasks.Task AsTask(this global::Windows.Foundation.IAsyncActionWithProgress source, System.Threading.CancellationToken cancellationToken) { throw null; } - public static System.Threading.Tasks.Task AsTask(this global::Windows.Foundation.IAsyncActionWithProgress source, System.Threading.CancellationToken cancellationToken, System.IProgress? progress) { throw null; } - public static System.Threading.Tasks.Task AsTask(this global::Windows.Foundation.IAsyncOperation source) { throw null; } - public static System.Threading.Tasks.Task AsTask(this global::Windows.Foundation.IAsyncOperation source, System.Threading.CancellationToken cancellationToken) { throw null; } - public static System.Threading.Tasks.Task AsTask(this global::Windows.Foundation.IAsyncOperationWithProgress source) { throw null; } - public static System.Threading.Tasks.Task AsTask(this global::Windows.Foundation.IAsyncOperationWithProgress source, System.IProgress? progress) { throw null; } - public static System.Threading.Tasks.Task AsTask(this global::Windows.Foundation.IAsyncOperationWithProgress source, System.Threading.CancellationToken cancellationToken) { throw null; } - public static System.Threading.Tasks.Task AsTask(this global::Windows.Foundation.IAsyncOperationWithProgress source, System.Threading.CancellationToken cancellationToken, System.IProgress? progress) { throw null; } - [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)] - public static System.Runtime.CompilerServices.TaskAwaiter GetAwaiter(this global::Windows.Foundation.IAsyncAction source) { throw null; } - [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)] - public static System.Runtime.CompilerServices.TaskAwaiter GetAwaiter(this global::Windows.Foundation.IAsyncActionWithProgress source) { throw null; } - [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)] - public static System.Runtime.CompilerServices.TaskAwaiter GetAwaiter(this global::Windows.Foundation.IAsyncOperation source) { throw null; } - [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)] - public static System.Runtime.CompilerServices.TaskAwaiter GetAwaiter(this global::Windows.Foundation.IAsyncOperationWithProgress source) { throw null; } - } -} -namespace System.IO -{ - public static partial class WindowsRuntimeStorageExtensions - { - [System.CLSCompliantAttribute(false)] - public static Microsoft.Win32.SafeHandles.SafeFileHandle CreateSafeFileHandle(this global::Windows.Storage.IStorageFile windowsRuntimeFile, System.IO.FileAccess access = System.IO.FileAccess.ReadWrite, System.IO.FileShare share = System.IO.FileShare.Read, System.IO.FileOptions options = System.IO.FileOptions.None) { throw null; } - [System.CLSCompliantAttribute(false)] - public static Microsoft.Win32.SafeHandles.SafeFileHandle CreateSafeFileHandle(this global::Windows.Storage.IStorageFolder rootDirectory, string relativePath, System.IO.FileMode mode) { throw null; } - [System.CLSCompliantAttribute(false)] - public static Microsoft.Win32.SafeHandles.SafeFileHandle CreateSafeFileHandle(this global::Windows.Storage.IStorageFolder rootDirectory, string relativePath, System.IO.FileMode mode, System.IO.FileAccess access, System.IO.FileShare share = System.IO.FileShare.Read, System.IO.FileOptions options = System.IO.FileOptions.None) { throw null; } - [System.CLSCompliantAttribute(false)] - public static System.Threading.Tasks.Task OpenStreamForReadAsync(this global::Windows.Storage.IStorageFile windowsRuntimeFile) { throw null; } - [System.CLSCompliantAttribute(false)] - public static System.Threading.Tasks.Task OpenStreamForReadAsync(this global::Windows.Storage.IStorageFolder rootDirectory, string relativePath) { throw null; } - [System.CLSCompliantAttribute(false)] - public static System.Threading.Tasks.Task OpenStreamForWriteAsync(this global::Windows.Storage.IStorageFile windowsRuntimeFile) { throw null; } - [System.CLSCompliantAttribute(false)] - public static System.Threading.Tasks.Task OpenStreamForWriteAsync(this global::Windows.Storage.IStorageFolder rootDirectory, string relativePath, global::Windows.Storage.CreationCollisionOption creationCollisionOption) { throw null; } - } - public static partial class WindowsRuntimeStreamExtensions - { - [System.CLSCompliantAttribute(false)] - public static global::Windows.Storage.Streams.IInputStream AsInputStream(this System.IO.Stream stream) { throw null; } - [System.CLSCompliantAttribute(false)] - public static global::Windows.Storage.Streams.IOutputStream AsOutputStream(this System.IO.Stream stream) { throw null; } - [System.CLSCompliantAttribute(false)] - public static global::Windows.Storage.Streams.IRandomAccessStream AsRandomAccessStream(this System.IO.Stream stream) { throw null; } - [System.CLSCompliantAttribute(false)] - public static System.IO.Stream AsStream(this global::Windows.Storage.Streams.IRandomAccessStream windowsRuntimeStream) { throw null; } - [System.CLSCompliantAttribute(false)] - public static System.IO.Stream AsStream(this global::Windows.Storage.Streams.IRandomAccessStream windowsRuntimeStream, int bufferSize) { throw null; } - [System.CLSCompliantAttribute(false)] - public static System.IO.Stream AsStreamForRead(this global::Windows.Storage.Streams.IInputStream windowsRuntimeStream) { throw null; } - [System.CLSCompliantAttribute(false)] - public static System.IO.Stream AsStreamForRead(this global::Windows.Storage.Streams.IInputStream windowsRuntimeStream, int bufferSize) { throw null; } - [System.CLSCompliantAttribute(false)] - public static System.IO.Stream AsStreamForWrite(this global::Windows.Storage.Streams.IOutputStream windowsRuntimeStream) { throw null; } - [System.CLSCompliantAttribute(false)] - public static System.IO.Stream AsStreamForWrite(this global::Windows.Storage.Streams.IOutputStream windowsRuntimeStream, int bufferSize) { throw null; } - } -} -namespace System.Runtime.InteropServices.WindowsRuntime -{ - [System.CLSCompliantAttribute(false)] - public static partial class AsyncInfo - { - public static global::Windows.Foundation.IAsyncAction Run(System.Func taskProvider) { throw null; } - public static global::Windows.Foundation.IAsyncActionWithProgress Run(System.Func, System.Threading.Tasks.Task> taskProvider) { throw null; } - public static global::Windows.Foundation.IAsyncOperation Run(System.Func> taskProvider) { throw null; } - public static global::Windows.Foundation.IAsyncOperationWithProgress Run(System.Func, System.Threading.Tasks.Task> taskProvider) { throw null; } - } - public sealed partial class WindowsRuntimeBuffer - { - internal WindowsRuntimeBuffer() { } - [System.CLSCompliantAttribute(false)] - public static global::Windows.Storage.Streams.IBuffer Create(byte[] data, int offset, int length, int capacity) { throw null; } - [System.CLSCompliantAttribute(false)] - public static global::Windows.Storage.Streams.IBuffer Create(int capacity) { throw null; } - } - public static partial class WindowsRuntimeBufferExtensions - { - [System.CLSCompliantAttribute(false)] - public static global::Windows.Storage.Streams.IBuffer AsBuffer(this byte[] source) { throw null; } - [System.CLSCompliantAttribute(false)] - public static global::Windows.Storage.Streams.IBuffer AsBuffer(this byte[] source, int offset, int length) { throw null; } - [System.CLSCompliantAttribute(false)] - public static global::Windows.Storage.Streams.IBuffer AsBuffer(this byte[] source, int offset, int length, int capacity) { throw null; } - [System.CLSCompliantAttribute(false)] - public static System.IO.Stream AsStream(this global::Windows.Storage.Streams.IBuffer source) { throw null; } - [System.CLSCompliantAttribute(false)] - public static void CopyTo(this byte[] source, int sourceIndex, global::Windows.Storage.Streams.IBuffer destination, uint destinationIndex, int count) { } - [System.CLSCompliantAttribute(false)] - public static void CopyTo(this byte[] source, global::Windows.Storage.Streams.IBuffer destination) { } - [System.CLSCompliantAttribute(false)] - public static void CopyTo(this global::Windows.Storage.Streams.IBuffer source, byte[] destination) { } - [System.CLSCompliantAttribute(false)] - public static void CopyTo(this global::Windows.Storage.Streams.IBuffer source, uint sourceIndex, byte[] destination, int destinationIndex, int count) { } - [System.CLSCompliantAttribute(false)] - public static void CopyTo(this global::Windows.Storage.Streams.IBuffer source, uint sourceIndex, global::Windows.Storage.Streams.IBuffer destination, uint destinationIndex, uint count) { } - [System.CLSCompliantAttribute(false)] - public static void CopyTo(this global::Windows.Storage.Streams.IBuffer source, global::Windows.Storage.Streams.IBuffer destination) { } - [System.CLSCompliantAttribute(false)] - public static byte GetByte(this global::Windows.Storage.Streams.IBuffer source, uint byteOffset) { throw null; } - [System.CLSCompliantAttribute(false)] - public static global::Windows.Storage.Streams.IBuffer GetWindowsRuntimeBuffer(this System.IO.MemoryStream underlyingStream) { throw null; } - [System.CLSCompliantAttribute(false)] - public static global::Windows.Storage.Streams.IBuffer GetWindowsRuntimeBuffer(this System.IO.MemoryStream underlyingStream, int positionInStream, int length) { throw null; } - [System.CLSCompliantAttribute(false)] - public static bool IsSameData(this global::Windows.Storage.Streams.IBuffer buffer, global::Windows.Storage.Streams.IBuffer? otherBuffer) { throw null; } - [System.CLSCompliantAttribute(false)] - public static byte[] ToArray(this global::Windows.Storage.Streams.IBuffer source) { throw null; } - [System.CLSCompliantAttribute(false)] - public static byte[] ToArray(this global::Windows.Storage.Streams.IBuffer source, uint sourceIndex, int count) { throw null; } - } -} -namespace Windows.Foundation -{ - public partial struct Point : global::System.IFormattable - { - private int _dummyPrimitive; - public Point(double x, double y) { throw null; } - public double X { get { throw null; } set { } } - public double Y { get { throw null; } set { } } - public override bool Equals(object? o) { throw null; } - public bool Equals(global::Windows.Foundation.Point value) { throw null; } - public override int GetHashCode() { throw null; } - public static bool operator ==(global::Windows.Foundation.Point point1, global::Windows.Foundation.Point point2) { throw null; } - public static bool operator !=(global::Windows.Foundation.Point point1, global::Windows.Foundation.Point point2) { throw null; } - public override string ToString() { throw null; } - public string ToString(global::System.IFormatProvider? provider) { throw null; } - } - public partial struct Rect : global::System.IFormattable - { - private int _dummyPrimitive; - public Rect(double x, double y, double width, double height) { throw null; } - public Rect(global::Windows.Foundation.Point point1, global::Windows.Foundation.Point point2) { throw null; } - public Rect(global::Windows.Foundation.Point location, global::Windows.Foundation.Size size) { throw null; } - public double Bottom { get { throw null; } } - public static global::Windows.Foundation.Rect Empty { get { throw null; } } - public double Height { get { throw null; } set { } } - public bool IsEmpty { get { throw null; } } - public double Left { get { throw null; } } - public double Right { get { throw null; } } - public double Top { get { throw null; } } - public double Width { get { throw null; } set { } } - public double X { get { throw null; } set { } } - public double Y { get { throw null; } set { } } - public bool Contains(global::Windows.Foundation.Point point) { throw null; } - public override bool Equals(object? o) { throw null; } - public bool Equals(global::Windows.Foundation.Rect value) { throw null; } - public override int GetHashCode() { throw null; } - public void Intersect(global::Windows.Foundation.Rect rect) { } - public static bool operator ==(global::Windows.Foundation.Rect rect1, global::Windows.Foundation.Rect rect2) { throw null; } - public static bool operator !=(global::Windows.Foundation.Rect rect1, global::Windows.Foundation.Rect rect2) { throw null; } - public override string ToString() { throw null; } - public string ToString(global::System.IFormatProvider? provider) { throw null; } - public void Union(global::Windows.Foundation.Point point) { } - public void Union(global::Windows.Foundation.Rect rect) { } - } - public partial struct Size - { - private int _dummyPrimitive; - public Size(double width, double height) { throw null; } - public static global::Windows.Foundation.Size Empty { get { throw null; } } - public double Height { get { throw null; } set { } } - public bool IsEmpty { get { throw null; } } - public double Width { get { throw null; } set { } } - public override bool Equals(object? o) { throw null; } - public bool Equals(global::Windows.Foundation.Size value) { throw null; } - public override int GetHashCode() { throw null; } - public static bool operator ==(global::Windows.Foundation.Size size1, global::Windows.Foundation.Size size2) { throw null; } - public static bool operator !=(global::Windows.Foundation.Size size1, global::Windows.Foundation.Size size2) { throw null; } - public override string ToString() { throw null; } - } -} -namespace Windows.UI -{ - public partial struct Color : global::System.IFormattable - { - private int _dummyPrimitive; - public byte A { get { throw null; } set { } } - public byte B { get { throw null; } set { } } - public byte G { get { throw null; } set { } } - public byte R { get { throw null; } set { } } - public override bool Equals(object? o) { throw null; } - public bool Equals(global::Windows.UI.Color color) { throw null; } - public static global::Windows.UI.Color FromArgb(byte a, byte r, byte g, byte b) { throw null; } - public override int GetHashCode() { throw null; } - public static bool operator ==(global::Windows.UI.Color color1, global::Windows.UI.Color color2) { throw null; } - public static bool operator !=(global::Windows.UI.Color color1, global::Windows.UI.Color color2) { throw null; } - public override string ToString() { throw null; } - public string ToString(global::System.IFormatProvider? provider) { throw null; } - } -} diff --git a/src/libraries/System.Runtime.WindowsRuntime/ref/System.Runtime.WindowsRuntime.csproj b/src/libraries/System.Runtime.WindowsRuntime/ref/System.Runtime.WindowsRuntime.csproj deleted file mode 100644 index 93a7d07..0000000 --- a/src/libraries/System.Runtime.WindowsRuntime/ref/System.Runtime.WindowsRuntime.csproj +++ /dev/null @@ -1,31 +0,0 @@ - - - - $(NoWarn);1698 - $(NetCoreAppCurrent);netstandard2.0 - true - enable - - - - - - - - - - - - - - - - diff --git a/src/libraries/System.Runtime.WindowsRuntime/src/MatchingRefApiCompatBaseline.txt b/src/libraries/System.Runtime.WindowsRuntime/src/MatchingRefApiCompatBaseline.txt deleted file mode 100644 index 95830eb..0000000 --- a/src/libraries/System.Runtime.WindowsRuntime/src/MatchingRefApiCompatBaseline.txt +++ /dev/null @@ -1,5 +0,0 @@ -Compat issues with assembly System.Runtime.WindowsRuntime: -CannotRemoveBaseTypeOrInterface : Type 'System.Runtime.InteropServices.WindowsRuntime.WindowsRuntimeBuffer' does not implement interface 'Windows.Storage.Streams.IBuffer' in the reference but it does in the implementation. -TypesMustExist : Type 'System.Threading.DispatcherQueueHandler' does not exist in the reference but it does exist in the implementation. -TypesMustExist : Type 'System.Threading.DispatcherQueuePriority' does not exist in the reference but it does exist in the implementation. -Total Issues: 3 diff --git a/src/libraries/System.Runtime.WindowsRuntime/src/PinvokeAnalyzerExceptionList.analyzerdata b/src/libraries/System.Runtime.WindowsRuntime/src/PinvokeAnalyzerExceptionList.analyzerdata deleted file mode 100644 index 23fd0eb..0000000 --- a/src/libraries/System.Runtime.WindowsRuntime/src/PinvokeAnalyzerExceptionList.analyzerdata +++ /dev/null @@ -1 +0,0 @@ -api-ms-win-core-winrt-l1-1-0.dll!RoGetActivationFactory \ No newline at end of file diff --git a/src/libraries/System.Runtime.WindowsRuntime/src/Resources/Strings.resx b/src/libraries/System.Runtime.WindowsRuntime/src/Resources/Strings.resx deleted file mode 100644 index 806231d..0000000 --- a/src/libraries/System.Runtime.WindowsRuntime/src/Resources/Strings.resx +++ /dev/null @@ -1,344 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - text/microsoft-resx - - - 2.0 - - - System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 - - - System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 - - - The specified buffer index is not within the buffer capacity. - - - The specified useful data length exceeds the capacity of this buffer. - - - The specified index is out of bounds of the specified array. - - - The specified Windows Runtime stream supports the IRandomAccessStream interface and its CanRead property returns TRUE, however it does not implement the IInputStream interface. Windows Runtime streams with such inconsistent capabilities cannot be converted to managed Stream objects. IRandomAccessStream instances whose CanRead property returns TRUE must implement the IInputStream interface. - - - The specified Windows Runtime stream supports the IRandomAccessStream interface and its CanWrite property returns TRUE, however it does not implement the IOutputStream interface. Windows Runtime streams with such inconsistent capabilities cannot be converted to managed Stream objects. IRandomAccessStream instances whose CanWrite property returns TRUE must implement the IOutputStream interface. - - - The specified array does not contain the specified number of elements starting at the specified offset. - - - The specified buffer capacity is not sufficient to hold data of the specified length. - - - The specified source buffer does not contain the specified number of elements starting at the specified offset. - - - The specified destination buffer is not large enough to hold the specified number of bytes starting at the specified offset. - - - Cannot convert the specified Stream object to a Windows Runtime stream because it does not have sufficient capabilities. In order to convert a System.IO.Stream instance to a Windows Runtime stream at least one of the properties CanRead, CanWrite, CanSeek must return TRUE; however, none of these properties returns TRUE for the specified Stream. - - - The specified object cannot be converted to a System.IO.Stream instance because it is not a Windows Runtime stream. In order to convert an object to a Stream instance it must implement at least one of the following 3 Windows Runtime stream interfaces: IInputStream, IOutputStream, IRandomAccessStream. - - - The specified relative path may not consist of whitespace only - - - The specified stream position is beyond the end of the stream. - - - The specified AsyncResult does not correspond to any outstanding IO operation. - - - The specified Windows Runtime stream does not support reading nor writing. Windows Runtime streams with such capabilities cannot be converted to managed Stream objects. Use a Windows Runtime stream that can support reading, writing or both. - - - Cannot set the length of a stream to a negative value. - - - Cannot seek to an absolute stream position that is negative. - - - The specified value is not a valid member of the InputStreamOptions enumeration. - - - Non-negative number required. - - - The buffer size for a Windows Runtime stream adapter may not be negative. Use a positive buffer size or 0 to disable buffering. - - - The state of this object does not permit invoking this method. - - - Cannot convert the specified Windows Runtime stream to a managed System.IO.Stream object with the specified buffer size because this Windows Runtime stream has been previously converted to a managed Stream object with a different buffer size. Ensure that the 'bufferSize' argument matches the existing buffer or use the '{0}'-overload without the 'bufferSize' argument to convert the specified Windows Runtime stream to a Stream object with the same buffer size as previously. - - - Cannot convert the specified Windows Runtime stream to a managed System.IO.Stream object without a buffer because this Windows Runtime stream has been previously converted to a managed Stream object with a buffer. Ensure that the 'bufferSize' argument matches the existing buffer or use the '{0}'-overload without the 'bufferSize' argument to convert the specified Windows Runtime stream to a Stream object with the same buffer size as previously. - - - Cannot call GetResults on this asynchronous info because the underlying operation has not completed. - - - The 'Completed' handler delegate cannot be set more than once, but this handler has already been set. - - - Cannot set the size of this stream because it cannot be written to. - - - The specified state transition is illegal for the current state of this object. - - - The asynchronous operation could not be completed. - - - A callback for the same asynchronous IO operation was invoked more than once. - - - The Task provider delegate specified for this IAsyncInfo instance returned a Task object that was not started. Task instances must be run immediately upon creation. - - - This AsyncResult or Task corresponds to a different asynchronous operation ID than the one that invoked the completion callback. - - - The specified underlying Task is not started. Task instances must be run immediately upon creation. - - - Cannot seek to an absolute stream position that is larger than 2^63 - 1 bytes. (2^63 - 1 = 0x7FFFFFFFFFFFFFFF = Int64.MaxValue). - - - This Windows Runtime stream is backed by a .NET Stream; its size cannot be set to a value that is larger than 2^63 - 1 bytes. (2^63 - 1 = 0x7FFFFFFFFFFFFFFF = Int64.MaxValue). - - - An IO error occurred in the Windows runtime system. - - - This Stream is backed by a Windows Runtime stream with a length that exceeds 2^63 - 1 bytes. Operations related to the stream's length or position cannot be performed on streams when the length exceeds 2^63 - 1 bytes. (2^63 - 1 = 0x7FFFFFFFFFFFFFFF = Int64.MaxValue = approx. 8000 PetaBytes.) - - - A native library routine was not found: {0}. - - - Cannot use the specified Stream as a Windows Runtime IInputStream because this Stream is not readable. - - - Cannot use the specified Stream as a Windows Runtime IRandomAccessStream because this Stream does not support seeking. - - - Cannot use the specified Stream as a Windows Runtime IOutputStream because this Stream is not writable. - - - This stream does not support read access. - - - This stream does not support seeking. - - - This stream does not support the Length property because it is not seekable. - - - This stream does not support the Position property because it is not seekable. - - - This stream does not support write access. - - - This IRandomAccessStream does not support the {0} method because it requires cloning and this stream does not support cloning. - - - The Windows Runtime stream that underlies this System.IO.Stream object has invoked an IO completion callback and specified null for the IAsyncInfo instance that describes the completed IO operation. This behavior is not supported because results cannot be retrieved from a null operation. Either the underlying Windows Runtime stream has a faulty implementation, or you are using a Windows Runtime object in an unsupported runtime environment. - - - The task provider delegate used to create this asynchronous operation returned null, but a valid Task object was expected. - - - The requested invocation is not permitted because this IAsyncInfo instance has already been closed. - - - The requested operation cannot be performed because this stream has already been disposed. - - - An error has occurred. - - - Cannot access a closed stream. - - - Stream does not support seeking. - - - Stream does not support reading. - - - Stream does not support writing. - - - Invalid seek origin. - - - Empty. - - - Send is not supported in the Windows Runtime SynchronizationContext - - - MemoryStream's internal buffer cannot be accessed. - - - Inheritable is not a supported option. - - - Encrypted is not a supported option. - - - Unable to find the specified file. - - - Could not find file '{0}'. - - - Could not find a part of the path. - - - Could not find a part of the path '{0}'. - - - Access to the path is denied. - - - Access to the path '{0}' is denied. - - - Cannot create '{0}' because a file or directory with the same name already exists. - - - The specified file name or path is too long, or a component of the specified path is too long. - - - The process cannot access the file '{0}' because it is being used by another process. - - - The process cannot access the file because it is being used by another process. - - - The file '{0}' already exists. - - - The path '{0}' is too long, or a component of the specified path is too long. - - - Windows Runtime (WinRT) is not supported on this platform. - - - Invalid action value: '{0}'. - - \ No newline at end of file diff --git a/src/libraries/System.Runtime.WindowsRuntime/src/System.Runtime.WindowsRuntime.csproj b/src/libraries/System.Runtime.WindowsRuntime/src/System.Runtime.WindowsRuntime.csproj deleted file mode 100644 index 6dae361..0000000 --- a/src/libraries/System.Runtime.WindowsRuntime/src/System.Runtime.WindowsRuntime.csproj +++ /dev/null @@ -1,98 +0,0 @@ - - - true - $(NoWarn);CS1573 - - - $(NoWarn);1698;0436 - $(NetCoreAppCurrent)-Windows_NT;netstandard1.0;netstandard1.2;netstandard2.0 - true - enable - - - - SR.PlatformNotSupported_WindowsRuntime - true - 4.0.0.0 - 4.0.11.0 - $(DefineConstants);FEATURE_APPX - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/src/libraries/System.Runtime.WindowsRuntime/src/System/IO/HANDLE_ACCESS_OPTIONS.cs b/src/libraries/System.Runtime.WindowsRuntime/src/System/IO/HANDLE_ACCESS_OPTIONS.cs deleted file mode 100644 index e513f0f..0000000 --- a/src/libraries/System.Runtime.WindowsRuntime/src/System/IO/HANDLE_ACCESS_OPTIONS.cs +++ /dev/null @@ -1,33 +0,0 @@ -// 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 System.IO -{ - [Flags] - internal enum HANDLE_ACCESS_OPTIONS : uint - { - HAO_NONE = 0, - HAO_READ_ATTRIBUTES = 0x80, - // 0x120089 - HAO_READ = SYNCHRONIZE | READ_CONTROL | HAO_READ_ATTRIBUTES | FILE_READ_EA | FILE_READ_DATA, - // 0x120116 - HAO_WRITE = SYNCHRONIZE | READ_CONTROL | FILE_WRITE_ATTRIBUTES | FILE_WRITE_EA | FILE_APPEND_DATA | FILE_WRITE_DATA, - HAO_DELETE = 0x10000, - - // These are defined elsewhere, adding here for clarity - // on what the HANDLE_ACCESS_OPTIONS represent. - - // DELETE = 0x00010000, - READ_CONTROL = 0x00020000, - SYNCHRONIZE = 0x00100000, - FILE_READ_DATA = 0x00000001, - FILE_WRITE_DATA = 0x00000002, - FILE_APPEND_DATA = 0x00000004, - FILE_READ_EA = 0x00000008, - FILE_WRITE_EA = 0x00000010, - FILE_EXECUTE = 0x00000020, - // FILE_READ_ATTRIBUTES = 0x00000080, - FILE_WRITE_ATTRIBUTES = 0x00000100, - } -} diff --git a/src/libraries/System.Runtime.WindowsRuntime/src/System/IO/HANDLE_CREATION_OPTIONS.cs b/src/libraries/System.Runtime.WindowsRuntime/src/System/IO/HANDLE_CREATION_OPTIONS.cs deleted file mode 100644 index dd37458..0000000 --- a/src/libraries/System.Runtime.WindowsRuntime/src/System/IO/HANDLE_CREATION_OPTIONS.cs +++ /dev/null @@ -1,15 +0,0 @@ -// 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 System.IO -{ - internal enum HANDLE_CREATION_OPTIONS : uint - { - HCO_CREATE_NEW = 0x1, - HCO_CREATE_ALWAYS = 0x2, - HCO_OPEN_EXISTING = 0x3, - HCO_OPEN_ALWAYS = 0x4, - HCO_TRUNCATE_EXISTING = 0x5, - } -} diff --git a/src/libraries/System.Runtime.WindowsRuntime/src/System/IO/HANDLE_OPTIONS.cs b/src/libraries/System.Runtime.WindowsRuntime/src/System/IO/HANDLE_OPTIONS.cs deleted file mode 100644 index 23ec169..0000000 --- a/src/libraries/System.Runtime.WindowsRuntime/src/System/IO/HANDLE_OPTIONS.cs +++ /dev/null @@ -1,19 +0,0 @@ -// 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 System.IO -{ - [Flags] - internal enum HANDLE_OPTIONS : uint - { - HO_NONE = 0, - HO_OPEN_REQUIRING_OPLOCK = 0x40000, - HO_DELETE_ON_CLOSE = 0x4000000, - HO_SEQUENTIAL_SCAN = 0x8000000, - HO_RANDOM_ACCESS = 0x10000000, - HO_NO_BUFFERING = 0x20000000, - HO_OVERLAPPED = 0x40000000, - HO_WRITE_THROUGH = 0x80000000 - } -} diff --git a/src/libraries/System.Runtime.WindowsRuntime/src/System/IO/HANDLE_SHARING_OPTION.cs b/src/libraries/System.Runtime.WindowsRuntime/src/System/IO/HANDLE_SHARING_OPTION.cs deleted file mode 100644 index b5ae5bc..0000000 --- a/src/libraries/System.Runtime.WindowsRuntime/src/System/IO/HANDLE_SHARING_OPTION.cs +++ /dev/null @@ -1,15 +0,0 @@ -// 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 System.IO -{ - [Flags] - internal enum HANDLE_SHARING_OPTIONS : uint - { - HSO_SHARE_NONE = 0, - HSO_SHARE_READ = 0x1, - HSO_SHARE_WRITE = 0x2, - HSO_SHARE_DELETE = 0x4 - } -} diff --git a/src/libraries/System.Runtime.WindowsRuntime/src/System/IO/IStorageFolderHandleAccess.cs b/src/libraries/System.Runtime.WindowsRuntime/src/System/IO/IStorageFolderHandleAccess.cs deleted file mode 100644 index 667bc1a..0000000 --- a/src/libraries/System.Runtime.WindowsRuntime/src/System/IO/IStorageFolderHandleAccess.cs +++ /dev/null @@ -1,26 +0,0 @@ -// 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.SafeHandles; -using System.Runtime.InteropServices; - -namespace System.IO -{ - // Available in 14393 (RS1) and later - [ComImport] - [Guid("DF19938F-5462-48A0-BE65-D2A3271A08D6")] - [InterfaceType(ComInterfaceType.InterfaceIsIUnknown)] - internal interface IStorageFolderHandleAccess - { - [PreserveSig] - int Create( - [MarshalAs(UnmanagedType.LPWStr)] string fileName, - HANDLE_CREATION_OPTIONS creationOptions, - HANDLE_ACCESS_OPTIONS accessOptions, - HANDLE_SHARING_OPTIONS sharingOptions, - HANDLE_OPTIONS options, - IntPtr oplockBreakingHandler, - out SafeFileHandle interopHandle); - } -} diff --git a/src/libraries/System.Runtime.WindowsRuntime/src/System/IO/IStorageItemHandleAccess.cs b/src/libraries/System.Runtime.WindowsRuntime/src/System/IO/IStorageItemHandleAccess.cs deleted file mode 100644 index 78fb311..0000000 --- a/src/libraries/System.Runtime.WindowsRuntime/src/System/IO/IStorageItemHandleAccess.cs +++ /dev/null @@ -1,24 +0,0 @@ -// 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.SafeHandles; -using System.Runtime.InteropServices; - -namespace System.IO -{ - // Available in 14393 (RS1) and later - [ComImport] - [Guid("5CA296B2-2C25-4D22-B785-B885C8201E6A")] - [InterfaceType(ComInterfaceType.InterfaceIsIUnknown)] - internal interface IStorageItemHandleAccess - { - [PreserveSig] - int Create( - HANDLE_ACCESS_OPTIONS accessOptions, - HANDLE_SHARING_OPTIONS sharingOptions, - HANDLE_OPTIONS options, - IntPtr oplockBreakingHandler, - out SafeFileHandle interopHandle); - } -} diff --git a/src/libraries/System.Runtime.WindowsRuntime/src/System/IO/NetFxToWinRtStreamAdapter.cs b/src/libraries/System.Runtime.WindowsRuntime/src/System/IO/NetFxToWinRtStreamAdapter.cs deleted file mode 100644 index b9402ac..0000000 --- a/src/libraries/System.Runtime.WindowsRuntime/src/System/IO/NetFxToWinRtStreamAdapter.cs +++ /dev/null @@ -1,451 +0,0 @@ -// 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 System.IO; -using System.Runtime.InteropServices.WindowsRuntime; -using System.Runtime.InteropServices; -using System.Threading.Tasks; -using System.Threading; -using Windows.Foundation; -using Windows.Storage.Streams; -using System.Diagnostics.CodeAnalysis; - -namespace System.IO -{ - /// - /// An wrapper for a managed stream that implements all WinRT stream operations. - /// This class must not implement any WinRT stream interfaces directly. - /// We never create instances of this class directly; instead we use classes defined in - /// the region Interface adapters to implement WinRT ifaces and create instances of those types. - /// See comment in that region for technical details. - /// - internal abstract class NetFxToWinRtStreamAdapter : IDisposable - { - #region Construction - - #region Interface adapters - - // Instances of private types defined in this section will be returned from NetFxToWinRtStreamAdapter.Create(..). - // Depending on the capabilities of the .NET stream for which we need to construct the adapter, we need to return - // an object that can be QIed (COM speak for "cast") to a well-defined set of ifaces. - // E.g, if the specified stream CanRead, but not CanSeek and not CanWrite, then we *must* return an object that - // can be QIed to IInputStream, but *not* IRandomAccessStream and *not* IOutputStream. - // There are two ways to do that: - // - We could explicitly implement ICustomQueryInterface and respond to QI requests by analyzing the stream capabilities - // - We can use the runtime's ability to do that for us, based on the ifaces the concrete class implements (or does not). - // The latter is much more elegant, and likely also faster. - - - private class InputStream : NetFxToWinRtStreamAdapter, IInputStream, IDisposable - { - internal InputStream(Stream stream, StreamReadOperationOptimization readOptimization) - : base(stream, readOptimization) - { - } - } - - - private class OutputStream : NetFxToWinRtStreamAdapter, IOutputStream, IDisposable - { - internal OutputStream(Stream stream, StreamReadOperationOptimization readOptimization) - : base(stream, readOptimization) - { - } - } - - - private class RandomAccessStream : NetFxToWinRtStreamAdapter, IRandomAccessStream, IInputStream, IOutputStream, IDisposable - { - internal RandomAccessStream(Stream stream, StreamReadOperationOptimization readOptimization) - : base(stream, readOptimization) - { - } - } - - - private class InputOutputStream : NetFxToWinRtStreamAdapter, IInputStream, IOutputStream, IDisposable - { - internal InputOutputStream(Stream stream, StreamReadOperationOptimization readOptimization) - : base(stream, readOptimization) - { - } - } - - #endregion Interface adapters - - // We may want to define different behaviour for different types of streams. - // For instance, ReadAsync treats MemoryStream special for performance reasons. - // The enum 'StreamReadOperationOptimization' describes the read optimization to employ for a - // given NetFxToWinRtStreamAdapter instance. In future, we might define other enums to follow a - // similar pattern, e.g. 'StreamWriteOperationOptimization' or 'StreamFlushOperationOptimization'. - private enum StreamReadOperationOptimization - { - AbstractStream = 0, MemoryStream - } - - - internal static NetFxToWinRtStreamAdapter Create(Stream stream) - { - if (stream == null) - throw new ArgumentNullException(nameof(stream)); - - StreamReadOperationOptimization readOptimization = StreamReadOperationOptimization.AbstractStream; - if (stream.CanRead) - readOptimization = DetermineStreamReadOptimization(stream); - - NetFxToWinRtStreamAdapter adapter; - - if (stream.CanSeek) - adapter = new RandomAccessStream(stream, readOptimization); - - else if (stream.CanRead && stream.CanWrite) - adapter = new InputOutputStream(stream, readOptimization); - - else if (stream.CanRead) - adapter = new InputStream(stream, readOptimization); - - else if (stream.CanWrite) - adapter = new OutputStream(stream, readOptimization); - - else - throw new ArgumentException(SR.Argument_NotSufficientCapabilitiesToConvertToWinRtStream); - - return adapter; - } - - - private static StreamReadOperationOptimization DetermineStreamReadOptimization(Stream stream) - { - Debug.Assert(stream != null); - - if (CanApplyReadMemoryStreamOptimization(stream)) - return StreamReadOperationOptimization.MemoryStream; - - return StreamReadOperationOptimization.AbstractStream; - } - - - private static bool CanApplyReadMemoryStreamOptimization(Stream stream) - { - MemoryStream? memStream = stream as MemoryStream; - if (memStream == null) - return false; - - ArraySegment arrSeg; - return memStream.TryGetBuffer(out arrSeg); - } - - - private NetFxToWinRtStreamAdapter(Stream stream, StreamReadOperationOptimization readOptimization) - { - Debug.Assert(stream != null); - Debug.Assert(stream.CanRead || stream.CanWrite || stream.CanSeek); - Debug.Assert(!stream.CanRead || (stream.CanRead && this is IInputStream)); - Debug.Assert(!stream.CanWrite || (stream.CanWrite && this is IOutputStream)); - Debug.Assert(!stream.CanSeek || (stream.CanSeek && this is IRandomAccessStream)); - - _readOptimization = readOptimization; - _managedStream = stream; - } - - #endregion Construction - - - #region Instance variables - - private Stream? _managedStream = null; - private bool _leaveUnderlyingStreamOpen = true; - private readonly StreamReadOperationOptimization _readOptimization; - - #endregion Instance variables - - - #region Tools and Helpers - - /// - /// We keep tables for mappings between managed and WinRT streams to make sure to always return the same adapter for a given underlying stream. - /// However, in order to avoid global locks on those tables, several instances of this type may be created and then can race to be entered - /// into the appropriate map table. All except for the winning instances will be thrown away. However, we must ensure that when the losers are - /// finalized, they do not dispose the underlying stream. To ensure that, we must call this method on the winner to notify it that it is safe to - /// dispose the underlying stream. - /// - internal void SetWonInitializationRace() - { - _leaveUnderlyingStreamOpen = false; - } - - - public Stream? GetManagedStream() - { - return _managedStream; - } - - - private Stream EnsureNotDisposed() - { - Stream? str = _managedStream; - - if (str == null) - { - ObjectDisposedException ex = new ObjectDisposedException(SR.ObjectDisposed_CannotPerformOperation); - ex.HResult = __HResults.RO_E_CLOSED; - throw ex; - } - - return str; - } - - #endregion Tools and Helpers - - - #region Common public interface - - /// Implements IDisposable.Dispose (IClosable.Close in WinRT) - void IDisposable.Dispose() - { - Stream? str = _managedStream; - if (str == null) - return; - - _managedStream = null; - - if (!_leaveUnderlyingStreamOpen) - str.Dispose(); - } - - #endregion Common public interface - - - #region IInputStream public interface - - public IAsyncOperationWithProgress ReadAsync(IBuffer buffer, uint count, InputStreamOptions options) - { - if (buffer == null) - { - // Mapped to E_POINTER. - throw new ArgumentNullException(nameof(buffer)); - } - - if (count < 0 || int.MaxValue < count) - { - ArgumentOutOfRangeException ex = new ArgumentOutOfRangeException(nameof(count)); - ex.HResult = __HResults.E_INVALIDARG; - throw ex; - } - - if (buffer.Capacity < count) - { - ArgumentException ex = new ArgumentException(SR.Argument_InsufficientBufferCapacity); - ex.HResult = __HResults.E_INVALIDARG; - throw ex; - } - - if (!(options == InputStreamOptions.None || options == InputStreamOptions.Partial || options == InputStreamOptions.ReadAhead)) - { - ArgumentOutOfRangeException ex = new ArgumentOutOfRangeException(nameof(options), - SR.ArgumentOutOfRange_InvalidInputStreamOptionsEnumValue); - ex.HResult = __HResults.E_INVALIDARG; - throw ex; - } - - Stream str = EnsureNotDisposed(); - - IAsyncOperationWithProgress readAsyncOperation; - switch (_readOptimization) - { - case StreamReadOperationOptimization.MemoryStream: - readAsyncOperation = StreamOperationsImplementation.ReadAsync_MemoryStream(str, buffer, count); - break; - - case StreamReadOperationOptimization.AbstractStream: - readAsyncOperation = StreamOperationsImplementation.ReadAsync_AbstractStream(str, buffer, count, options); - break; - - // Use this pattern to add more optimisation options if necessary: - //case StreamReadOperationOptimization.XxxxStream: - // readAsyncOperation = StreamOperationsImplementation.ReadAsync_XxxxStream(str, buffer, count, options); - // break; - - default: - Debug.Fail("We should never get here. Someone forgot to handle an input stream optimisation option."); - readAsyncOperation = null; - break; - } - - return readAsyncOperation; - } - - #endregion IInputStream public interface - - - #region IOutputStream public interface - - public IAsyncOperationWithProgress WriteAsync(IBuffer buffer) - { - if (buffer == null) - { - // Mapped to E_POINTER. - throw new ArgumentNullException(nameof(buffer)); - } - - if (buffer.Capacity < buffer.Length) - { - ArgumentException ex = new ArgumentException(SR.Argument_BufferLengthExceedsCapacity); - ex.HResult = __HResults.E_INVALIDARG; - throw ex; - } - - Stream str = EnsureNotDisposed(); - return StreamOperationsImplementation.WriteAsync_AbstractStream(str, buffer); - } - - - public IAsyncOperation FlushAsync() - { - Stream str = EnsureNotDisposed(); - return StreamOperationsImplementation.FlushAsync_AbstractStream(str); - } - - #endregion IOutputStream public interface - - - #region IRandomAccessStream public interface - - - #region IRandomAccessStream public interface: Not cloning related - - public void Seek(ulong position) - { - if (position > long.MaxValue) - { - ArgumentException ex = new ArgumentException(SR.IO_CannotSeekBeyondInt64MaxValue); - ex.HResult = __HResults.E_INVALIDARG; - throw ex; - } - - Stream str = EnsureNotDisposed(); - long pos = unchecked((long)position); - - Debug.Assert(str != null); - Debug.Assert(str.CanSeek, "The underlying str is expected to support Seek, but it does not."); - Debug.Assert(0 <= pos, "Unexpected pos=" + pos + "."); - - str.Seek(pos, SeekOrigin.Begin); - } - - - public bool CanRead - { - get - { - Stream str = EnsureNotDisposed(); - return str.CanRead; - } - } - - - public bool CanWrite - { - get - { - Stream str = EnsureNotDisposed(); - return str.CanWrite; - } - } - - - public ulong Position - { - get - { - Stream str = EnsureNotDisposed(); - return (ulong)str.Position; - } - } - - - public ulong Size - { - get - { - Stream str = EnsureNotDisposed(); - return (ulong)str.Length; - } - - set - { - if (value > long.MaxValue) - { - ArgumentException ex = new ArgumentException(SR.IO_CannotSetSizeBeyondInt64MaxValue); - ex.HResult = __HResults.E_INVALIDARG; - throw ex; - } - - Stream str = EnsureNotDisposed(); - - if (!str.CanWrite) - { - InvalidOperationException ex = new InvalidOperationException(SR.InvalidOperation_CannotSetStreamSizeCannotWrite); - ex.HResult = __HResults.E_ILLEGAL_METHOD_CALL; - throw ex; - } - - long val = unchecked((long)value); - - Debug.Assert(str != null); - Debug.Assert(str.CanSeek, "The underlying str is expected to support Seek, but it does not."); - Debug.Assert(0 <= val, "Unexpected val=" + val + "."); - - str.SetLength(val); - } - } - - #endregion IRandomAccessStream public interface: Not cloning related - - - #region IRandomAccessStream public interface: Cloning related - - // We do not want to support the cloning-related operation for now. - // They appear to mainly target corner-case scenarios in Windows itself, - // and are (mainly) a historical artefact of abandoned early designs - // for IRandonAccessStream. - // Cloning can be added in future, however, it would be quite complex - // to support it correctly for generic streams. - [DoesNotReturn] - private static void ThrowCloningNotSupported(string methodName) - { - NotSupportedException nse = new NotSupportedException(SR.Format(SR.NotSupported_CloningNotSupported, methodName)); - nse.HResult = __HResults.E_NOTIMPL; - throw nse; - } - - - public IRandomAccessStream CloneStream() - { - ThrowCloningNotSupported("CloneStream"); - return null; - } - - - public IInputStream GetInputStreamAt(ulong position) - { - ThrowCloningNotSupported("GetInputStreamAt"); - return null; - } - - - public IOutputStream GetOutputStreamAt(ulong position) - { - ThrowCloningNotSupported("GetOutputStreamAt"); - return null; - } - #endregion IRandomAccessStream public interface: Cloning related - - #endregion IRandomAccessStream public interface - - } // class NetFxToWinRtStreamAdapter -} // namespace - -// NetFxToWinRtStreamAdapter.cs diff --git a/src/libraries/System.Runtime.WindowsRuntime/src/System/IO/StreamOperationAsyncResult.cs b/src/libraries/System.Runtime.WindowsRuntime/src/System/IO/StreamOperationAsyncResult.cs deleted file mode 100644 index c94c172..0000000 --- a/src/libraries/System.Runtime.WindowsRuntime/src/System/IO/StreamOperationAsyncResult.cs +++ /dev/null @@ -1,392 +0,0 @@ -// 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 Internal.Runtime.InteropServices.WindowsRuntime; -using System.Diagnostics; -using System.Runtime.ExceptionServices; -using System.Runtime.InteropServices.WindowsRuntime; -using System.Runtime.InteropServices; -using System.Threading.Tasks; -using System.Threading; -using Windows.Foundation; -using Windows.Storage.Streams; -using System.Diagnostics.CodeAnalysis; - -namespace System.IO -{ - #region class StreamOperationAsyncResult - - internal abstract partial class StreamOperationAsyncResult : IAsyncResult - { - private readonly AsyncCallback? _userCompletionCallback = null; - private readonly object? _userAsyncStateInfo = null; - - private IAsyncInfo? _asyncStreamOperation = null; - - private volatile bool _completed = false; - private volatile bool _callbackInvoked = false; - private volatile ManualResetEvent? _waitHandle = null; - - private long _bytesCompleted = 0; - - private ExceptionDispatchInfo? _errorInfo = null; - - private readonly bool _processCompletedOperationInCallback; - private IAsyncInfo? _completedOperation = null; - - - protected internal StreamOperationAsyncResult(IAsyncInfo asyncStreamOperation, - AsyncCallback? userCompletionCallback, object? userAsyncStateInfo, - bool processCompletedOperationInCallback) - { - if (asyncStreamOperation == null) - throw new ArgumentNullException(nameof(asyncStreamOperation)); - - _userCompletionCallback = userCompletionCallback; - _userAsyncStateInfo = userAsyncStateInfo; - - _asyncStreamOperation = asyncStreamOperation; - - _completed = false; - _callbackInvoked = false; - - _bytesCompleted = 0; - - _errorInfo = null; - - _processCompletedOperationInCallback = processCompletedOperationInCallback; - } - - - public object? AsyncState - { - get { return _userAsyncStateInfo; } - } - - - internal bool ProcessCompletedOperationInCallback - { - get { return _processCompletedOperationInCallback; } - } - - - public WaitHandle AsyncWaitHandle - { - get - { - ManualResetEvent? wh = _waitHandle; - if (wh != null) - return wh; - - // What if someone calls this public property and decides to wait on it? - // > Use 'completed' in the ctor - this way the handle wait will return as appropriate. - wh = new ManualResetEvent(_completed); - - ManualResetEvent? otherHandle = Interlocked.CompareExchange(ref _waitHandle, wh, null); - - // We lost the race. Dispose OUR handle and return OTHER handle: - if (otherHandle != null) - { - wh.Dispose(); - return otherHandle; - } - - // We won the race. Return OUR new handle: - return wh; - } - } - - public bool CompletedSynchronously - { - get { return false; } - } - - - public bool IsCompleted - { - get { return _completed; } - } - - - internal void Wait() - { - if (_completed) - return; - - WaitHandle wh = AsyncWaitHandle; - - while (_completed == false) - wh.WaitOne(); - } - - - internal long BytesCompleted - { - get { return _bytesCompleted; } - } - - - internal bool HasError - { - get { return _errorInfo != null; } - } - - - internal void ThrowCachedError() - { - if (_errorInfo == null) - return; - - _errorInfo.Throw(); - } - - - internal bool CancelStreamOperation() - { - if (_callbackInvoked) - return false; - - if (_asyncStreamOperation != null) - { - _asyncStreamOperation.Cancel(); - _asyncStreamOperation = null; - } - - return true; - } - - internal void CloseStreamOperation() - { - try - { - if (_asyncStreamOperation != null) - _asyncStreamOperation.Close(); - } - catch { } - _asyncStreamOperation = null; - } - - - ~StreamOperationAsyncResult() - { - // This finalisation is not critical, but we can still make an effort to notify the underlying WinRT stream - // that we are not any longer interested in the results: - CancelStreamOperation(); - } - - - internal abstract void ProcessConcreteCompletedOperation(IAsyncInfo completedOperation, out long bytesCompleted); - - [DoesNotReturn] - private static void ProcessCompletedOperation_InvalidOperationThrowHelper(ExceptionDispatchInfo? errInfo, string errMsg) - { - Exception? errInfoSrc = (errInfo == null) ? null : errInfo.SourceException; - - if (errInfoSrc == null) - throw new InvalidOperationException(errMsg); - else - throw new InvalidOperationException(errMsg, errInfoSrc); - } - - - internal void ProcessCompletedOperation() - { - // The error handling is slightly tricky here: - // Before processing the IO results, we are verifying some basic assumptions and if they do not hold, we are - // throwing InvalidOperation. However, by the time this method is called, we might have already stored something - // into errorInfo, e.g. if an error occurred in StreamOperationCompletedCallback. If that is the case, then that - // previous exception might include some important info relevant for detecting the problem. So, we take that - // previous exception and attach it as the inner exception to the InvalidOperationException being thrown. - // In cases where we have a good understanding of the previously saved errorInfo, and we know for sure that it - // the immediate reason for the state validation to fail, we can avoid throwing InvalidOperation altogether - // and only rethrow the errorInfo. - - if (!_callbackInvoked) - ProcessCompletedOperation_InvalidOperationThrowHelper(_errorInfo, SR.InvalidOperation_CannotCallThisMethodInCurrentState); - - if (!_processCompletedOperationInCallback && !_completed) - ProcessCompletedOperation_InvalidOperationThrowHelper(_errorInfo, SR.InvalidOperation_CannotCallThisMethodInCurrentState); - - if (_completedOperation == null) - { - ExceptionDispatchInfo? errInfo = _errorInfo; - Exception? errInfoSrc = (errInfo == null) ? null : errInfo.SourceException; - - // See if errorInfo is set because we observed completedOperation == null previously (being slow is Ok on error path): - if (errInfoSrc != null && errInfoSrc is NullReferenceException - && SR.NullReference_IOCompletionCallbackCannotProcessNullAsyncInfo.Equals(errInfoSrc.Message)) - { - errInfo!.Throw(); - } - else - { - throw new InvalidOperationException(SR.InvalidOperation_CannotCallThisMethodInCurrentState); - } - } - - if (_completedOperation.Id != _asyncStreamOperation!.Id) - ProcessCompletedOperation_InvalidOperationThrowHelper(_errorInfo, SR.InvalidOperation_UnexpectedAsyncOperationID); - - if (_completedOperation.Status == AsyncStatus.Error) - { - _bytesCompleted = 0; - ThrowWithIOExceptionDispatchInfo(_completedOperation.ErrorCode); - } - - ProcessConcreteCompletedOperation(_completedOperation, out _bytesCompleted); - } - - - internal void StreamOperationCompletedCallback(IAsyncInfo completedOperation, AsyncStatus unusedCompletionStatus) - { - try - { - if (_callbackInvoked) - throw new InvalidOperationException(SR.InvalidOperation_MultipleIOCompletionCallbackInvocation); - - _callbackInvoked = true; - - // This happens in rare stress cases in Console mode and the WinRT folks said they are unlikely to fix this in Dev11. - // Moreover, this can happen if the underlying WinRT stream has a faulty user implementation. - // If we did not do this check, we would either get the same exception without the explaining message when dereferencing - // completedOperation later, or we will get an InvalidOperation when processing the Op. With the check, they will be - // aggregated and the user will know what went wrong. - if (completedOperation == null) - throw new NullReferenceException(SR.NullReference_IOCompletionCallbackCannotProcessNullAsyncInfo); - - _completedOperation = completedOperation; - - // processCompletedOperationInCallback == false indicates that the stream is doing a blocking wait on the waitHandle of this IAsyncResult. - // In that case calls on completedOperation may deadlock if completedOperation is not free threaded. - // By setting processCompletedOperationInCallback to false the stream that created this IAsyncResult indicated that it - // will call ProcessCompletedOperation after the waitHandle is signalled to fetch the results. - - if (_processCompletedOperationInCallback) - ProcessCompletedOperation(); - } - catch (Exception ex) - { - _bytesCompleted = 0; - _errorInfo = ExceptionDispatchInfo.Capture(ex); - } - finally - { - _completed = true; - Interlocked.MemoryBarrier(); - // From this point on, AsyncWaitHandle would create a handle that is readily set, - // so we do not need to check if it is being produced asynchronously. - if (_waitHandle != null) - _waitHandle.Set(); - } - - if (_userCompletionCallback != null) - _userCompletionCallback(this); - } - - private void ThrowWithIOExceptionDispatchInfo(Exception e) - { - WinRtIOHelper.NativeExceptionToIOExceptionInfo(ExceptionSupport.AttachRestrictedErrorInfo(_completedOperation!.ErrorCode)!).Throw(); - } - } // class StreamOperationAsyncResult - - #endregion class StreamOperationAsyncResult - - - #region class StreamReadAsyncResult - - internal class StreamReadAsyncResult : StreamOperationAsyncResult - { - private readonly IBuffer _userBuffer; - - internal StreamReadAsyncResult(IAsyncOperationWithProgress asyncStreamReadOperation, IBuffer buffer, - AsyncCallback? userCompletionCallback, object? userAsyncStateInfo, - bool processCompletedOperationInCallback) - - : base(asyncStreamReadOperation, userCompletionCallback, userAsyncStateInfo, processCompletedOperationInCallback) - { - if (buffer == null) - throw new ArgumentNullException(nameof(buffer)); - - _userBuffer = buffer; - asyncStreamReadOperation.Completed = this.StreamOperationCompletedCallback; - } - - - internal override void ProcessConcreteCompletedOperation(IAsyncInfo completedOperation, out long bytesCompleted) - { - ProcessConcreteCompletedOperation((IAsyncOperationWithProgress)completedOperation, out bytesCompleted); - } - - - private void ProcessConcreteCompletedOperation(IAsyncOperationWithProgress completedOperation, out long bytesCompleted) - { - IBuffer resultBuffer = completedOperation.GetResults(); - Debug.Assert(resultBuffer != null); - - WinRtIOHelper.EnsureResultsInUserBuffer(_userBuffer!, resultBuffer); - bytesCompleted = _userBuffer!.Length; - } - } // class StreamReadAsyncResult - - #endregion class StreamReadAsyncResult - - - #region class StreamWriteAsyncResult - - internal class StreamWriteAsyncResult : StreamOperationAsyncResult - { - internal StreamWriteAsyncResult(IAsyncOperationWithProgress asyncStreamWriteOperation, - AsyncCallback? userCompletionCallback, object? userAsyncStateInfo, - bool processCompletedOperationInCallback) - - : base(asyncStreamWriteOperation, userCompletionCallback, userAsyncStateInfo, processCompletedOperationInCallback) - { - asyncStreamWriteOperation.Completed = this.StreamOperationCompletedCallback; - } - - - internal override void ProcessConcreteCompletedOperation(IAsyncInfo completedOperation, out long bytesCompleted) - { - ProcessConcreteCompletedOperation((IAsyncOperationWithProgress)completedOperation, out bytesCompleted); - } - - - private void ProcessConcreteCompletedOperation(IAsyncOperationWithProgress completedOperation, out long bytesCompleted) - { - uint bytesWritten = completedOperation.GetResults(); - bytesCompleted = bytesWritten; - } - } // class StreamWriteAsyncResult - - #endregion class StreamWriteAsyncResult - - - #region class StreamFlushAsyncResult - - internal class StreamFlushAsyncResult : StreamOperationAsyncResult - { - internal StreamFlushAsyncResult(IAsyncOperation asyncStreamFlushOperation, bool processCompletedOperationInCallback) - - : base(asyncStreamFlushOperation, null, null, processCompletedOperationInCallback) - { - asyncStreamFlushOperation.Completed = this.StreamOperationCompletedCallback; - } - - - internal override void ProcessConcreteCompletedOperation(IAsyncInfo completedOperation, out long bytesCompleted) - { - ProcessConcreteCompletedOperation((IAsyncOperation)completedOperation, out bytesCompleted); - } - - - private void ProcessConcreteCompletedOperation(IAsyncOperation completedOperation, out long bytesCompleted) - { - bool success = completedOperation.GetResults(); - bytesCompleted = (success ? 0 : -1); - } - } // class StreamFlushAsyncResult - #endregion class StreamFlushAsyncResult -} // namespace - -// StreamOperationAsyncResult.cs diff --git a/src/libraries/System.Runtime.WindowsRuntime/src/System/IO/StreamOperationsImplementation.cs b/src/libraries/System.Runtime.WindowsRuntime/src/System/IO/StreamOperationsImplementation.cs deleted file mode 100644 index 5fd829c..0000000 --- a/src/libraries/System.Runtime.WindowsRuntime/src/System/IO/StreamOperationsImplementation.cs +++ /dev/null @@ -1,245 +0,0 @@ -// 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 System.IO; -using System.Runtime.InteropServices.WindowsRuntime; -using System.Runtime.InteropServices; -using System.Threading.Tasks; -using System.Threading; -using Windows.Foundation; -using Windows.Storage.Streams; - -namespace System.IO -{ - /// Depending on the concrete type of the stream managed by a NetFxToWinRtStreamAdapter, - /// we want the ReadAsync / WriteAsync / FlushAsync / etc. operation to be implemented - /// differently. This is for best performance as we can take advantage of the specifics of particular stream - /// types. For instance, ReadAsync currently has a special implementation for memory streams. - /// Moreover, knowledge about the actual runtime type of the IBuffer can also help choosing the optimal - /// implementation. This type provides static methods that encapsulate the performance logic and can be used - /// by NetFxToWinRtStreamAdapter. - internal static class StreamOperationsImplementation - { - #region ReadAsync implementations - - internal static IAsyncOperationWithProgress ReadAsync_MemoryStream(Stream stream, IBuffer buffer, uint count) - { - Debug.Assert(stream != null); - Debug.Assert(stream is MemoryStream); - Debug.Assert(stream.CanRead); - Debug.Assert(stream.CanSeek); - Debug.Assert(buffer != null); - Debug.Assert(buffer is IBufferByteAccess); - Debug.Assert(0 <= count); - Debug.Assert(count <= int.MaxValue); - Debug.Assert(count <= buffer.Capacity); - - // We will return a different buffer to the user backed directly by the memory stream (avoids memory copy). - // This is permitted by the WinRT stream contract. - // The user specified buffer will not have any data put into it: - buffer.Length = 0; - - MemoryStream? memStream = stream as MemoryStream; - Debug.Assert(memStream != null); - - try - { - IBuffer dataBuffer = memStream.GetWindowsRuntimeBuffer((int)memStream.Position, (int)count); - if (dataBuffer.Length > 0) - memStream.Seek(dataBuffer.Length, SeekOrigin.Current); - - return AsyncInfo.CreateCompletedOperation(dataBuffer); - } - catch (Exception ex) - { - return AsyncInfo.CreateFaultedOperation(ex); - } - } // ReadAsync_MemoryStream - - - internal static IAsyncOperationWithProgress ReadAsync_AbstractStream(Stream stream, IBuffer buffer, uint count, - InputStreamOptions options) - { - Debug.Assert(stream != null); - Debug.Assert(stream.CanRead); - Debug.Assert(buffer != null); - Debug.Assert(buffer is IBufferByteAccess); - Debug.Assert(0 <= count); - Debug.Assert(count <= int.MaxValue); - Debug.Assert(count <= buffer.Capacity); - Debug.Assert(options == InputStreamOptions.None || options == InputStreamOptions.Partial || options == InputStreamOptions.ReadAhead); - - int bytesRequested = (int)count; - - // Check if the buffer is our implementation. - // IF YES: In that case, we can read directly into its data array. - // IF NO: The buffer is of unknown implementation. It's not backed by a managed array, but the wrapped stream can only - // read into a managed array. If we used the user-supplied buffer we would need to copy data into it after every read. - // The spec allows to return a buffer instance that is not the same as passed by the user. So, we will create an own - // buffer instance, read data *directly* into the array backing it and then return it to the user. - // Note: the allocation costs we are paying for the new buffer are unavoidable anyway, as we would need to create - // an array to read into either way. - - IBuffer? dataBuffer = buffer as WindowsRuntimeBuffer; - - if (dataBuffer == null) - dataBuffer = WindowsRuntimeBuffer.Create((int)Math.Min((uint)int.MaxValue, buffer.Capacity)); - - // This operation delegate will we run inside of the returned IAsyncOperationWithProgress: - Func, Task> readOperation = async (cancelToken, progressListener) => - { - // No bytes read yet: - dataBuffer.Length = 0; - - // Get the buffer backing array: - byte[]? data; - int offset; - bool managedBufferAssert = dataBuffer.TryGetUnderlyingData(out data, out offset); - Debug.Assert(managedBufferAssert); - - // Init tracking values: - bool done = cancelToken.IsCancellationRequested; - int bytesCompleted = 0; - - // Loop until EOS, cancelled or read enough data according to options: - while (!done) - { - int bytesRead = 0; - - try - { - // Read asynchronously: - bytesRead = await stream.ReadAsync(data!.AsMemory(offset + bytesCompleted, bytesRequested - bytesCompleted), cancelToken) - .ConfigureAwait(continueOnCapturedContext: false); - - // We will continue here on a different thread when read async completed: - bytesCompleted += bytesRead; - // We will handle a cancelation exception and re-throw all others: - } - catch (OperationCanceledException) - { - // We assume that cancelToken.IsCancellationRequested is has been set and simply proceed. - // (we check cancelToken.IsCancellationRequested later) - Debug.Assert(cancelToken.IsCancellationRequested); - - // This is because if the cancellation came after we read some bytes we want to return the results we got instead - // of an empty cancelled task, so if we have not yet read anything at all, then we can throw cancellation: - if (bytesCompleted == 0 && bytesRead == 0) - throw; - } - - // Update target buffer: - dataBuffer.Length = (uint)bytesCompleted; - - Debug.Assert(bytesCompleted <= bytesRequested); - - // Check if we are done: - done = options == InputStreamOptions.Partial // If no complete read was requested, any amount of data is OK - || bytesRead == 0 // this implies EndOfStream - || bytesCompleted == bytesRequested // read all requested bytes - || cancelToken.IsCancellationRequested; // operation was cancelled - - // Call user Progress handler: - if (progressListener != null) - progressListener.Report(dataBuffer.Length); - } // while (!done) - - // If we got here, then no error was detected. Return the results buffer: - return dataBuffer; - }; // readOperation - - return AsyncInfo.Run(readOperation); - } // ReadAsync_AbstractStream - - #endregion ReadAsync implementations - - - #region WriteAsync implementations - - internal static IAsyncOperationWithProgress WriteAsync_AbstractStream(Stream stream, IBuffer buffer) - { - Debug.Assert(stream != null); - Debug.Assert(stream.CanWrite); - Debug.Assert(buffer != null); - - // Choose the optimal writing strategy for the kind of buffer supplied: - Func, Task> writeOperation; - byte[]? data; - int offset; - - // If buffer is backed by a managed array: - if (buffer.TryGetUnderlyingData(out data, out offset)) - { - writeOperation = async (cancelToken, progressListener) => - { - if (cancelToken.IsCancellationRequested) // CancellationToken is non-nullable - return 0; - - Debug.Assert(buffer.Length <= int.MaxValue); - - int bytesToWrite = (int)buffer.Length; - - await stream.WriteAsync(data.AsMemory(offset, bytesToWrite), cancelToken).ConfigureAwait(continueOnCapturedContext: false); - - if (progressListener != null) - progressListener.Report((uint)bytesToWrite); - - return (uint)bytesToWrite; - }; - // Otherwise buffer is of an unknown implementation: - } - else - { - writeOperation = async (cancelToken, progressListener) => - { - if (cancelToken.IsCancellationRequested) // CancellationToken is non-nullable - return 0; - - uint bytesToWrite = buffer.Length; - Stream dataStream = buffer.AsStream(); - - int buffSize = 0x4000; - if (bytesToWrite < buffSize) - buffSize = (int)bytesToWrite; - - await dataStream.CopyToAsync(stream, buffSize, cancelToken).ConfigureAwait(continueOnCapturedContext: false); - - if (progressListener != null) - progressListener.Report((uint)bytesToWrite); - - return (uint)bytesToWrite; - }; - } // if-else - - // Construct and run the async operation: - return AsyncInfo.Run(writeOperation); - } // WriteAsync_AbstractStream - - #endregion WriteAsync implementations - - - #region FlushAsync implementations - - internal static IAsyncOperation FlushAsync_AbstractStream(Stream stream) - { - Debug.Assert(stream != null); - Debug.Assert(stream.CanWrite); - - Func> flushOperation = async (cancelToken) => - { - if (cancelToken.IsCancellationRequested) // CancellationToken is non-nullable - return false; - - await stream.FlushAsync(cancelToken).ConfigureAwait(continueOnCapturedContext: false); - return true; - }; - - // Construct and run the async operation: - return AsyncInfo.Run(flushOperation); - } - #endregion FlushAsync implementations - - } // class StreamOperationsImplementation -} // namespace diff --git a/src/libraries/System.Runtime.WindowsRuntime/src/System/IO/WinRtIOHelper.cs b/src/libraries/System.Runtime.WindowsRuntime/src/System/IO/WinRtIOHelper.cs deleted file mode 100644 index 97e5a37..0000000 --- a/src/libraries/System.Runtime.WindowsRuntime/src/System/IO/WinRtIOHelper.cs +++ /dev/null @@ -1,55 +0,0 @@ -// 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 System.Runtime.ExceptionServices; -using System.Runtime.InteropServices.WindowsRuntime; -using System.Runtime.InteropServices; -using Windows.Storage.Streams; - -namespace System.IO -{ - internal static class WinRtIOHelper - { - internal const int DefaultIOBufferSize = 0x3000; // = 12 KBytes = 12288 Bytes - - - internal static ExceptionDispatchInfo NativeExceptionToIOExceptionInfo(Exception nativeException) - { - // If the interop layer gave us a specific exception type, we assume it knew what it was doing. - // If it gave us an ExternalException or a generic Exception, we assume that it hit a - // general/unknown case and wrap it into an IOException as this is what Stream users expect. - - // We will return a captured ExceptionDispatchInfo such that we can invoke .Throw() close to where - // nativeException was caught - this will result in the most readable call stack. - - Debug.Assert(nativeException != null); - - if (!(nativeException.GetType().Equals(typeof(Exception)) /*|| nativeException is ExternalException */)) - return ExceptionDispatchInfo.Capture(nativeException); - - // If we do not have a meaningful message, we use a general IO error message: - string message = nativeException.Message; - if (string.IsNullOrWhiteSpace(message)) - message = SR.IO_General; - - return ExceptionDispatchInfo.Capture(new IOException(message, nativeException)); - } - - - internal static void EnsureResultsInUserBuffer(IBuffer userBuffer, IBuffer resultBuffer) - { - // Results buffer may be different from user specified buffer. If so - copy data to the user. - - Debug.Assert(userBuffer != null); - Debug.Assert(resultBuffer != null); - - if (resultBuffer.IsSameData(userBuffer)) - return; - - resultBuffer.CopyTo(userBuffer); - userBuffer.Length = resultBuffer.Length; - } - } // class WinRtIOHelper -} // namespace diff --git a/src/libraries/System.Runtime.WindowsRuntime/src/System/IO/WinRtToNetFxStreamAdapter.cs b/src/libraries/System.Runtime.WindowsRuntime/src/System/IO/WinRtToNetFxStreamAdapter.cs deleted file mode 100644 index 5da6d2b..0000000 --- a/src/libraries/System.Runtime.WindowsRuntime/src/System/IO/WinRtToNetFxStreamAdapter.cs +++ /dev/null @@ -1,800 +0,0 @@ -// 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 System.Diagnostics.Contracts; -using System.Runtime.InteropServices.WindowsRuntime; -using System.Runtime.InteropServices; -using System.Threading.Tasks; -using System.Threading; -using Windows.Foundation; -using Windows.Storage.Streams; -using System.Diagnostics.CodeAnalysis; - -namespace System.IO -{ - /// - /// A Stream used to wrap a Windows Runtime stream to expose it as a managed steam. - /// - internal class WinRtToNetFxStreamAdapter : Stream, IDisposable - { - #region Construction - - internal static WinRtToNetFxStreamAdapter Create(object windowsRuntimeStream) - { - if (windowsRuntimeStream == null) - throw new ArgumentNullException(nameof(windowsRuntimeStream)); - - bool canRead = windowsRuntimeStream is IInputStream; - bool canWrite = windowsRuntimeStream is IOutputStream; - bool canSeek = windowsRuntimeStream is IRandomAccessStream; - - if (!canRead && !canWrite && !canSeek) - throw new ArgumentException(SR.Argument_ObjectMustBeWinRtStreamToConvertToNetFxStream); - - // Proactively guard against a non-conforming curstomer implementations: - if (canSeek) - { - IRandomAccessStream iras = (IRandomAccessStream)windowsRuntimeStream; - - if (!canRead && iras.CanRead) - throw new ArgumentException(SR.Argument_InstancesImplementingIRASThatCanReadMustImplementIIS); - - if (!canWrite && iras.CanWrite) - throw new ArgumentException(SR.Argument_InstancesImplementingIRASThatCanWriteMustImplementIOS); - - if (!iras.CanRead) - canRead = false; - - if (!iras.CanWrite) - canWrite = false; - } - - if (!canRead && !canWrite) - throw new ArgumentException(SR.Argument_WinRtStreamCannotReadOrWrite); - - return new WinRtToNetFxStreamAdapter(windowsRuntimeStream, canRead, canWrite, canSeek); - } - - - private WinRtToNetFxStreamAdapter(object winRtStream, bool canRead, bool canWrite, bool canSeek) - { - Debug.Assert(winRtStream != null); - Debug.Assert(winRtStream is IInputStream || winRtStream is IOutputStream || winRtStream is IRandomAccessStream); - - Debug.Assert((canSeek && (winRtStream is IRandomAccessStream)) || (!canSeek && !(winRtStream is IRandomAccessStream))); - - Debug.Assert((canRead && (winRtStream is IInputStream)) - || - (!canRead && ( - !(winRtStream is IInputStream) - || - (winRtStream is IRandomAccessStream && !((IRandomAccessStream)winRtStream).CanRead) - )) - ); - - Debug.Assert((canWrite && (winRtStream is IOutputStream)) - || - (!canWrite && ( - !(winRtStream is IOutputStream) - || - (winRtStream is IRandomAccessStream && !((IRandomAccessStream)winRtStream).CanWrite) - )) - ); - - _winRtStream = winRtStream; - _canRead = canRead; - _canWrite = canWrite; - _canSeek = canSeek; - } - - #endregion Construction - - - #region Instance variables - - private byte[]? _oneByteBuffer = null; - private bool _leaveUnderlyingStreamOpen = true; - - private object? _winRtStream; - private readonly bool _canRead; - private readonly bool _canWrite; - private readonly bool _canSeek; - - #endregion Instance variables - - - #region Tools and Helpers - - /// - /// We keep tables for mappings between managed and WinRT streams to make sure to always return the same adapter for a given underlying stream. - /// However, in order to avoid global locks on those tables, several instances of this type may be created and then can race to be entered - /// into the appropriate map table. All except for the winning instances will be thrown away. However, we must ensure that when the losers are - /// finalized, the do not dispose the underlying stream. To ensure that, we must call this method on the winner to notify it that it is safe to - /// dispose the underlying stream. - /// - internal void SetWonInitializationRace() - { - _leaveUnderlyingStreamOpen = false; - } - - - public TWinRtStream? GetWindowsRuntimeStream() where TWinRtStream : class - { - object? wrtStr = _winRtStream; - - if (wrtStr == null) - return null; - - Debug.Assert(wrtStr is TWinRtStream, - $"Attempted to get the underlying WinRT stream typed as \"{typeof(TWinRtStream)}\", " + - $"but the underlying WinRT stream cannot be cast to that type. Its actual type is \"{wrtStr.GetType()}\"."); - - return wrtStr as TWinRtStream; - } - - - private byte[] OneByteBuffer - { - get - { - byte[]? obb = _oneByteBuffer; - if (obb == null) // benign race for multiple init - _oneByteBuffer = obb = new byte[1]; - return obb; - } - } - - private TWinRtStream? EnsureNotDisposed() where TWinRtStream : class - { - object? wrtStr = _winRtStream; - - if (wrtStr == null) - throw new ObjectDisposedException(SR.ObjectDisposed_CannotPerformOperation); - - return (wrtStr as TWinRtStream); - } - - - private void EnsureNotDisposed() - { - if (_winRtStream == null) - throw new ObjectDisposedException(SR.ObjectDisposed_CannotPerformOperation); - } - - - private void EnsureCanRead() - { - if (!_canRead) - throw new NotSupportedException(SR.NotSupported_CannotReadFromStream); - } - - - private void EnsureCanWrite() - { - if (!_canWrite) - throw new NotSupportedException(SR.NotSupported_CannotWriteToStream); - } - - #endregion Tools and Helpers - - - #region Simple overrides - - protected override void Dispose(bool disposing) - { - // WinRT streams should implement IDisposable (IClosable in WinRT), but let's be defensive: - if (disposing && _winRtStream != null && !_leaveUnderlyingStreamOpen) - { - IDisposable? disposableWinRtStream = _winRtStream as IDisposable; // benign race on winRtStream - if (disposableWinRtStream != null) - disposableWinRtStream.Dispose(); - } - - _winRtStream = null; - base.Dispose(disposing); - } - - - public override bool CanRead - { - [Pure] - get - { return (_canRead && _winRtStream != null); } - } - - - public override bool CanWrite - { - [Pure] - get - { return (_canWrite && _winRtStream != null); } - } - - - public override bool CanSeek - { - [Pure] - get - { return (_canSeek && _winRtStream != null); } - } - - #endregion Simple overrides - - - #region Length and Position functions - - public override long Length - { - get - { - IRandomAccessStream? wrtStr = EnsureNotDisposed(); - - if (!_canSeek) - throw new NotSupportedException(SR.NotSupported_CannotUseLength_StreamNotSeekable); - - Debug.Assert(wrtStr != null); - - ulong size = wrtStr.Size; - - // These are over 8000 PetaBytes, we do not expect this to happen. However, let's be defensive: - if (size > (ulong)long.MaxValue) - throw new IOException(SR.IO_UnderlyingWinRTStreamTooLong_CannotUseLengthOrPosition); - - return unchecked((long)size); - } - } - - - public override long Position - { - get - { - IRandomAccessStream? wrtStr = EnsureNotDisposed(); - - if (!_canSeek) - throw new NotSupportedException(SR.NotSupported_CannotUsePosition_StreamNotSeekable); - - Debug.Assert(wrtStr != null); - - ulong pos = wrtStr.Position; - - // These are over 8000 PetaBytes, we do not expect this to happen. However, let's be defensive: - if (pos > (ulong)long.MaxValue) - throw new IOException(SR.IO_UnderlyingWinRTStreamTooLong_CannotUseLengthOrPosition); - - return unchecked((long)pos); - } - - set - { - if (value < 0) - throw new ArgumentOutOfRangeException(nameof(Position), SR.ArgumentOutOfRange_IO_CannotSeekToNegativePosition); - - IRandomAccessStream? wrtStr = EnsureNotDisposed(); - - if (!_canSeek) - throw new NotSupportedException(SR.NotSupported_CannotUsePosition_StreamNotSeekable); - - Debug.Assert(wrtStr != null); - - wrtStr.Seek(unchecked((ulong)value)); - } - } - - - public override long Seek(long offset, SeekOrigin origin) - { - IRandomAccessStream? wrtStr = EnsureNotDisposed(); - - if (!_canSeek) - throw new NotSupportedException(SR.NotSupported_CannotSeekInStream); - - Debug.Assert(wrtStr != null); - - switch (origin) - { - case SeekOrigin.Begin: - { - Position = offset; - return offset; - } - - case SeekOrigin.Current: - { - long curPos = Position; - - if (long.MaxValue - curPos < offset) - throw new IOException(SR.IO_CannotSeekBeyondInt64MaxValue); - - long newPos = curPos + offset; - - if (newPos < 0) - throw new IOException(SR.ArgumentOutOfRange_IO_CannotSeekToNegativePosition); - - Position = newPos; - return newPos; - } - - case SeekOrigin.End: - { - ulong size = wrtStr.Size; - long newPos; - - if (size > (ulong)long.MaxValue) - { - if (offset >= 0) - throw new IOException(SR.IO_CannotSeekBeyondInt64MaxValue); - - Debug.Assert(offset < 0); - - ulong absOffset = (offset == long.MinValue) ? ((ulong)long.MaxValue) + 1 : (ulong)(-offset); - Debug.Assert(absOffset <= size); - - ulong np = size - absOffset; - if (np > (ulong)long.MaxValue) - throw new IOException(SR.IO_CannotSeekBeyondInt64MaxValue); - - newPos = (long)np; - } - else - { - Debug.Assert(size <= (ulong)long.MaxValue); - - long s = unchecked((long)size); - - if (long.MaxValue - s < offset) - throw new IOException(SR.IO_CannotSeekBeyondInt64MaxValue); - - newPos = s + offset; - - if (newPos < 0) - throw new IOException(SR.ArgumentOutOfRange_IO_CannotSeekToNegativePosition); - } - - Position = newPos; - return newPos; - } - - default: - { - throw new ArgumentException(SR.Argument_InvalidSeekOrigin, nameof(origin)); - } - } - } - - - public override void SetLength(long value) - { - if (value < 0) - throw new ArgumentOutOfRangeException(nameof(value), SR.ArgumentOutOfRange_CannotResizeStreamToNegative); - - IRandomAccessStream? wrtStr = EnsureNotDisposed(); - - if (!_canSeek) - throw new NotSupportedException(SR.NotSupported_CannotSeekInStream); - - EnsureCanWrite(); - - Debug.Assert(wrtStr != null); - - wrtStr.Size = unchecked((ulong)value); - - // If the length is set to a value < that the current position, then we need to set the position to that value - // Because we can't directly set the position, we are going to seek to it. - if (wrtStr.Size < wrtStr.Position) - wrtStr.Seek(unchecked((ulong)value)); - } - - #endregion Length and Position functions - - - #region Reading - - private IAsyncResult BeginRead(byte[] buffer, int offset, int count, AsyncCallback? callback, object? state, bool usedByBlockingWrapper) - { - // This method is somewhat tricky: We could consider just calling ReadAsync (recall that Task implements IAsyncResult). - // It would be OK for cases where BeginRead is invoked directly by the public user. - // However, in cases where it is invoked by Read to achieve a blocking (synchronous) IO operation, the ReadAsync-approach may deadlock: - // - // The sync-over-async IO operation will be doing a blocking wait on the completion of the async IO operation assuming that - // a wait handle would be signalled by the completion handler. Recall that the IAsyncInfo representing the IO operation may - // not be free-threaded and not "free-marshalled"; it may also belong to an ASTA compartment because the underlying WinRT - // stream lives in an ASTA compartment. The completion handler is invoked on a pool thread, i.e. in MTA. - // That handler needs to fetch the results from the async IO operation, which requires a cross-compartment call from MTA into ASTA. - // But because the ASTA thread is busy waiting this call will deadlock. - // (Recall that although WaitOne pumps COM, ASTA specifically schedules calls on the outermost ?idle? pump only.) - // - // The solution is to make sure that: - // - In cases where main thread is waiting for the async IO to complete: - // Fetch results on the main thread after it has been signalled by the completion callback. - // - In cases where main thread is not waiting for the async IO to complete: - // Fetch results in the completion callback. - // - // But the Task-plumbing around IAsyncInfo.AsTask *always* fetches results in the completion handler because it has - // no way of knowing whether or not someone is waiting. So, instead of using ReadAsync here we implement our own IAsyncResult - // and our own completion handler which can behave differently according to whether it is being used by a blocking IO - // operation wrapping a BeginRead/EndRead pair, or by an actual async operation based on the old Begin/End pattern. - - if (buffer == null) - throw new ArgumentNullException(nameof(buffer)); - - if (offset < 0) - throw new ArgumentOutOfRangeException(nameof(offset)); - - if (count < 0) - throw new ArgumentOutOfRangeException(nameof(count)); - - if (buffer.Length - offset < count) - throw new ArgumentException(SR.Argument_InsufficientSpaceInTargetBuffer); - - IInputStream? wrtStr = EnsureNotDisposed(); - EnsureCanRead(); - - Debug.Assert(wrtStr != null); - - IBuffer userBuffer = buffer.AsBuffer(offset, count); - IAsyncOperationWithProgress asyncReadOperation = wrtStr.ReadAsync(userBuffer, - unchecked((uint)count), - InputStreamOptions.Partial); - - StreamReadAsyncResult asyncResult = new StreamReadAsyncResult(asyncReadOperation, userBuffer, callback, state, - processCompletedOperationInCallback: !usedByBlockingWrapper); - - // The StreamReadAsyncResult will set a private instance method to act as a Completed handler for asyncOperation. - // This will cause a CCW to be created for the delegate and the delegate has a reference to its target, i.e. to - // asyncResult, so asyncResult will not be collected. If we loose the entire AppDomain, then asyncResult and its CCW - // will be collected but the stub will remain and the callback will fail gracefully. The underlying buffer is the only - // item to which we expose a direct pointer and this is properly pinned using a mechanism similar to Overlapped. - - return asyncResult; - } - - public override int EndRead(IAsyncResult asyncResult) - { - if (asyncResult == null) - throw new ArgumentNullException(nameof(asyncResult)); - - EnsureNotDisposed(); - EnsureCanRead(); - - StreamOperationAsyncResult? streamAsyncResult = asyncResult as StreamOperationAsyncResult; - if (streamAsyncResult == null) - throw new ArgumentException(SR.Argument_UnexpectedAsyncResult, nameof(asyncResult)); - - streamAsyncResult.Wait(); - - try - { - // If the async result did NOT process the async IO operation in its completion handler (i.e. check for errors, - // cache results etc), then we need to do that processing now. This is to allow blocking-over-async IO operations. - // See the big comment in BeginRead for details. - - if (!streamAsyncResult.ProcessCompletedOperationInCallback) - streamAsyncResult.ProcessCompletedOperation(); - - // Rethrow errors caught in the completion callback, if any: - if (streamAsyncResult.HasError) - { - streamAsyncResult.CloseStreamOperation(); - streamAsyncResult.ThrowCachedError(); - } - - // Done: - - long bytesCompleted = streamAsyncResult.BytesCompleted; - Debug.Assert(bytesCompleted <= unchecked((long)int.MaxValue)); - - return (int)bytesCompleted; - } - finally - { - // Closing multiple times is Ok. - streamAsyncResult.CloseStreamOperation(); - } - } - - public override Task ReadAsync(byte[] buffer, int offset, int count, CancellationToken cancellationToken) - { - if (buffer == null) - throw new ArgumentNullException(nameof(buffer)); - - if (offset < 0) - throw new ArgumentOutOfRangeException(nameof(offset)); - - if (count < 0) - throw new ArgumentOutOfRangeException(nameof(count)); - - if (buffer.Length - offset < count) - throw new ArgumentException(SR.Argument_InsufficientSpaceInTargetBuffer); - - EnsureNotDisposed(); - EnsureCanRead(); - - // If already cancelled, bail early: - cancellationToken.ThrowIfCancellationRequested(); - - // State is Ok. Do the actual read: - return ReadAsyncInternal(buffer, offset, count, cancellationToken); - } - - - public override int Read(byte[] buffer, int offset, int count) - { - // Arguments validation and not-disposed validation are done in BeginRead. - - IAsyncResult asyncResult = BeginRead(buffer, offset, count, null, null, usedByBlockingWrapper: true); - int bytesRead = EndRead(asyncResult); - return bytesRead; - } - - - public override int ReadByte() - { - // EnsureNotDisposed will be called in Read->BeginRead. - - byte[] oneByteArray = OneByteBuffer; - - if (0 == Read(oneByteArray, 0, 1)) - return -1; - - int value = oneByteArray[0]; - return value; - } - - #endregion Reading - - - #region Writing - - - public override IAsyncResult BeginWrite(byte[] buffer, int offset, int count, AsyncCallback? callback, object? state) - { - return BeginWrite(buffer, offset, count, callback, state, usedByBlockingWrapper: false); - } - - private IAsyncResult BeginWrite(byte[] buffer, int offset, int count, AsyncCallback? callback, object? state, bool usedByBlockingWrapper) - { - // See the large comment in BeginRead about why we are not using this.WriteAsync, - // and instead using a custom implementation of IAsyncResult. - - if (buffer == null) - throw new ArgumentNullException(nameof(buffer)); - - if (offset < 0) - throw new ArgumentOutOfRangeException(nameof(offset)); - - if (count < 0) - throw new ArgumentOutOfRangeException(nameof(count)); - - if (buffer.Length - offset < count) - throw new ArgumentException(SR.Argument_InsufficientArrayElementsAfterOffset); - - IOutputStream? wrtStr = EnsureNotDisposed(); - EnsureCanWrite(); - - Debug.Assert(wrtStr != null); - - IBuffer asyncWriteBuffer = buffer.AsBuffer(offset, count); - - IAsyncOperationWithProgress asyncWriteOperation = wrtStr.WriteAsync(asyncWriteBuffer); - - StreamWriteAsyncResult asyncResult = new StreamWriteAsyncResult(asyncWriteOperation, callback, state, - processCompletedOperationInCallback: !usedByBlockingWrapper); - - // The StreamReadAsyncResult will set a private instance method to act as a Completed handler for asyncOperation. - // This will cause a CCW to be created for the delegate and the delegate has a reference to its target, i.e. to - // asyncResult, so asyncResult will not be collected. If we loose the entire AppDomain, then asyncResult and its CCW - // will be collected but the stub will remain and the callback will fail gracefully. The underlying buffer if the only - // item to which we expose a direct pointer and this is properly pinned using a mechanism similar to Overlapped. - - return asyncResult; - } - - public override void EndWrite(IAsyncResult asyncResult) - { - if (asyncResult == null) - throw new ArgumentNullException(nameof(asyncResult)); - - EnsureNotDisposed(); - EnsureCanWrite(); - - StreamOperationAsyncResult? streamAsyncResult = asyncResult as StreamOperationAsyncResult; - if (streamAsyncResult == null) - throw new ArgumentException(SR.Argument_UnexpectedAsyncResult, nameof(asyncResult)); - - streamAsyncResult.Wait(); - - try - { - // If the async result did NOT process the async IO operation in its completion handler (i.e. check for errors, - // cache results etc), then we need to do that processing now. This is to allow blocking-over-async IO operations. - // See the big comment in BeginWrite for details. - - if (!streamAsyncResult.ProcessCompletedOperationInCallback) - streamAsyncResult.ProcessCompletedOperation(); - - // Rethrow errors caught in the completion callback, if any: - if (streamAsyncResult.HasError) - { - streamAsyncResult.CloseStreamOperation(); - streamAsyncResult.ThrowCachedError(); - } - } - finally - { - // Closing multiple times is Ok. - streamAsyncResult.CloseStreamOperation(); - } - } - - public override Task WriteAsync(byte[] buffer, int offset, int count, CancellationToken cancellationToken) - { - if (buffer == null) - throw new ArgumentNullException(nameof(buffer)); - - if (offset < 0) - throw new ArgumentOutOfRangeException(nameof(offset)); - - if (count < 0) - throw new ArgumentOutOfRangeException(nameof(count)); - - if (buffer.Length - offset < count) - throw new ArgumentException(SR.Argument_InsufficientArrayElementsAfterOffset); - - IOutputStream? wrtStr = EnsureNotDisposed(); - EnsureCanWrite(); - - Debug.Assert(wrtStr != null); - - // If already cancelled, bail early: - cancellationToken.ThrowIfCancellationRequested(); - - IBuffer asyncWriteBuffer = buffer.AsBuffer(offset, count); - - IAsyncOperationWithProgress asyncWriteOperation = wrtStr.WriteAsync(asyncWriteBuffer); - Task asyncWriteTask = asyncWriteOperation.AsTask(cancellationToken); - - // The underlying IBuffer is the only object to which we expose a direct pointer to native, - // and that is properly pinned using a mechanism similar to Overlapped. - - return asyncWriteTask; - } - - - public override void Write(byte[] buffer, int offset, int count) - { - // Arguments validation and not-disposed validation are done in BeginWrite. - - IAsyncResult asyncResult = BeginWrite(buffer, offset, count, null, null, usedByBlockingWrapper: true); - EndWrite(asyncResult); - } - - - public override void WriteByte(byte value) - { - // EnsureNotDisposed will be called in Write->BeginWrite. - - byte[] oneByteArray = OneByteBuffer; - oneByteArray[0] = value; - - Write(oneByteArray, 0, 1); - } - - #endregion Writing - - - #region Flushing - - public override void Flush() - { - // See the large comment in BeginRead about why we are not using this.FlushAsync, - // and instead using a custom implementation of IAsyncResult. - - IOutputStream? wrtStr = EnsureNotDisposed(); - - // Calling Flush in a non-writable stream is a no-op, not an error: - if (!_canWrite) - return; - - Debug.Assert(wrtStr != null); - - IAsyncOperation asyncFlushOperation = wrtStr.FlushAsync(); - StreamFlushAsyncResult asyncResult = new StreamFlushAsyncResult(asyncFlushOperation, processCompletedOperationInCallback: false); - - asyncResult.Wait(); - - try - { - // We got signaled, so process the async Flush operation back on this thread: - // (This is to allow blocking-over-async IO operations. See the big comment in BeginRead for details.) - asyncResult.ProcessCompletedOperation(); - - // Rethrow errors cached by the async result, if any: - if (asyncResult.HasError) - { - asyncResult.CloseStreamOperation(); - asyncResult.ThrowCachedError(); - } - } - finally - { - // Closing multiple times is Ok. - asyncResult.CloseStreamOperation(); - } - } - - - public override Task FlushAsync(CancellationToken cancellationToken) - { - IOutputStream? wrtStr = EnsureNotDisposed(); - - // Calling Flush in a non-writable stream is a no-op, not an error: - if (!_canWrite) - return Task.CompletedTask; - - Debug.Assert(wrtStr != null); - - cancellationToken.ThrowIfCancellationRequested(); - - IAsyncOperation asyncFlushOperation = wrtStr.FlushAsync(); - Task asyncFlushTask = asyncFlushOperation.AsTask(cancellationToken); - return asyncFlushTask; - } - - #endregion Flushing - - - #region ReadAsyncInternal implementation - // Moved it to the end while using Dev10 VS because it does not understand async and everything that follows looses intellisense. - // Should move this code into the Reading regios once using Dev11 VS becomes the norm. - - private async Task ReadAsyncInternal(byte[] buffer, int offset, int count, CancellationToken cancellationToken) - { - Debug.Assert(buffer != null); - Debug.Assert(offset >= 0); - Debug.Assert(count >= 0); - Debug.Assert(buffer.Length - offset >= count); - Debug.Assert(_canRead); - - IInputStream? wrtStr = EnsureNotDisposed(); - - Debug.Assert(wrtStr != null); - - try - { - IBuffer userBuffer = buffer.AsBuffer(offset, count); - IAsyncOperationWithProgress asyncReadOperation = wrtStr.ReadAsync(userBuffer, - unchecked((uint)count), - InputStreamOptions.Partial); - - IBuffer resultBuffer = await asyncReadOperation.AsTask(cancellationToken).ConfigureAwait(continueOnCapturedContext: false); - - // If cancellationToken was cancelled until now, then we are currently propagating the corresponding cancellation exception. - // (It will be correctly rethrown by the catch block below and overall we will return a cancelled task.) - // But if the underlying operation managed to complete before it was cancelled, we want - // the entire task to complete as well. This is ok as the continuation is very lightweight: - - if (resultBuffer == null) - return 0; - - WinRtIOHelper.EnsureResultsInUserBuffer(userBuffer, resultBuffer); - - Debug.Assert(resultBuffer.Length <= unchecked((uint)int.MaxValue)); - return (int)resultBuffer.Length; - } - catch (Exception ex) - { - // If the interop layer gave us an Exception, we assume that it hit a general/unknown case and wrap it into - // an IOException as this is what Stream users expect. - WinRtIOHelper.NativeExceptionToIOExceptionInfo(ex).Throw(); - return 0; - } - } - #endregion ReadAsyncInternal implementation - - } // class WinRtToNetFxStreamAdapter -} // namespace - -// WinRtToNetFxStreamAdapter.cs diff --git a/src/libraries/System.Runtime.WindowsRuntime/src/System/IO/WindowsRuntimeStorageExtensions.cs b/src/libraries/System.Runtime.WindowsRuntime/src/System/IO/WindowsRuntimeStorageExtensions.cs deleted file mode 100644 index 09f870b..0000000 --- a/src/libraries/System.Runtime.WindowsRuntime/src/System/IO/WindowsRuntimeStorageExtensions.cs +++ /dev/null @@ -1,312 +0,0 @@ -// 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 System.Threading.Tasks; -using Microsoft.Win32.SafeHandles; -using Windows.Storage; -using Windows.Storage.FileProperties; -using Windows.Storage.Streams; - -namespace System.IO -{ - /// - /// Contains extension methods that provide convenience helpers for WinRT IO. - /// - public static class WindowsRuntimeStorageExtensions - { - [CLSCompliant(false)] - public static Task OpenStreamForReadAsync(this IStorageFile windowsRuntimeFile) - { - if (windowsRuntimeFile == null) - throw new ArgumentNullException(nameof(windowsRuntimeFile)); - - return OpenStreamForReadAsyncCore(windowsRuntimeFile); - } - - private static async Task OpenStreamForReadAsyncCore(this IStorageFile windowsRuntimeFile) - { - Debug.Assert(windowsRuntimeFile != null); - - try - { - IRandomAccessStream windowsRuntimeStream = await windowsRuntimeFile.OpenAsync(FileAccessMode.Read) - .AsTask().ConfigureAwait(continueOnCapturedContext: false); - Stream managedStream = windowsRuntimeStream.AsStreamForRead(); - return managedStream; - } - catch (Exception ex) - { - // From this API, managed dev expect IO exceptions for "something wrong": - WinRtIOHelper.NativeExceptionToIOExceptionInfo(ex).Throw(); - return null; - } - } - - [CLSCompliant(false)] - public static Task OpenStreamForWriteAsync(this IStorageFile windowsRuntimeFile) - { - if (windowsRuntimeFile == null) - throw new ArgumentNullException(nameof(windowsRuntimeFile)); - - return OpenStreamForWriteAsyncCore(windowsRuntimeFile, 0); - } - - private static async Task OpenStreamForWriteAsyncCore(this IStorageFile windowsRuntimeFile, long offset) - { - Debug.Assert(windowsRuntimeFile != null); - Debug.Assert(offset >= 0); - - try - { - IRandomAccessStream windowsRuntimeStream = await windowsRuntimeFile.OpenAsync(FileAccessMode.ReadWrite) - .AsTask().ConfigureAwait(continueOnCapturedContext: false); - Stream managedStream = windowsRuntimeStream.AsStreamForWrite(); - managedStream.Position = offset; - return managedStream; - } - catch (Exception ex) - { - // From this API, managed dev expect IO exceptions for "something wrong": - WinRtIOHelper.NativeExceptionToIOExceptionInfo(ex).Throw(); - return null; - } - } - - [CLSCompliant(false)] - public static Task OpenStreamForReadAsync(this IStorageFolder rootDirectory, string relativePath) - { - if (rootDirectory == null) - throw new ArgumentNullException(nameof(rootDirectory)); - - if (relativePath == null) - throw new ArgumentNullException(nameof(relativePath)); - - if (string.IsNullOrWhiteSpace(relativePath)) - throw new ArgumentException(SR.Argument_RelativePathMayNotBeWhitespaceOnly, nameof(relativePath)); - - return OpenStreamForReadAsyncCore(rootDirectory, relativePath); - } - - private static async Task OpenStreamForReadAsyncCore(this IStorageFolder rootDirectory, string relativePath) - { - Debug.Assert(rootDirectory != null); - Debug.Assert(!string.IsNullOrWhiteSpace(relativePath)); - - try - { - IStorageFile windowsRuntimeFile = await rootDirectory.GetFileAsync(relativePath) - .AsTask().ConfigureAwait(continueOnCapturedContext: false); - Stream managedStream = await windowsRuntimeFile.OpenStreamForReadAsync() - .ConfigureAwait(continueOnCapturedContext: false); - return managedStream; - } - catch (Exception ex) - { - // From this API, managed dev expect IO exceptions for "something wrong": - WinRtIOHelper.NativeExceptionToIOExceptionInfo(ex).Throw(); - return null; - } - } - - [CLSCompliant(false)] - public static Task OpenStreamForWriteAsync(this IStorageFolder rootDirectory, string relativePath, - CreationCollisionOption creationCollisionOption) - { - if (rootDirectory == null) - throw new ArgumentNullException(nameof(rootDirectory)); - - if (relativePath == null) - throw new ArgumentNullException(nameof(relativePath)); - - if (string.IsNullOrWhiteSpace(relativePath)) - throw new ArgumentException(SR.Argument_RelativePathMayNotBeWhitespaceOnly, nameof(relativePath)); - - return OpenStreamForWriteAsyncCore(rootDirectory, relativePath, creationCollisionOption); - } - - - private static async Task OpenStreamForWriteAsyncCore(this IStorageFolder rootDirectory, string relativePath, - CreationCollisionOption creationCollisionOption) - { - Debug.Assert(rootDirectory != null); - Debug.Assert(!string.IsNullOrWhiteSpace(relativePath)); - - Debug.Assert(creationCollisionOption == CreationCollisionOption.FailIfExists - || creationCollisionOption == CreationCollisionOption.GenerateUniqueName - || creationCollisionOption == CreationCollisionOption.OpenIfExists - || creationCollisionOption == CreationCollisionOption.ReplaceExisting, - "The specified creationCollisionOption has a value that is not a value we considered when devising the" - + " policy about Append-On-OpenIfExists used in this method. Apparently a new enum value was added to the" - + " CreationCollisionOption type and we need to make sure that the policy still makes sense."); - - try - { - // Open file and set up default options for opening it: - - IStorageFile windowsRuntimeFile = await rootDirectory.CreateFileAsync(relativePath, creationCollisionOption) - .AsTask().ConfigureAwait(continueOnCapturedContext: false); - long offset = 0; - - // If the specified creationCollisionOption was OpenIfExists, then we will try to APPEND, otherwise we will OVERWRITE: - - if (creationCollisionOption == CreationCollisionOption.OpenIfExists) - { - BasicProperties fileProperties = await windowsRuntimeFile.GetBasicPropertiesAsync() - .AsTask().ConfigureAwait(continueOnCapturedContext: false); - ulong fileSize = fileProperties.Size; - - Debug.Assert(fileSize <= long.MaxValue, ".NET streams assume that file sizes are not larger than Int64.MaxValue," - + " so we are not supporting the situation where this is not the case."); - offset = checked((long)fileSize); - } - - // Now open a file with the correct options: - - Stream managedStream = await OpenStreamForWriteAsyncCore(windowsRuntimeFile, offset).ConfigureAwait(continueOnCapturedContext: false); - return managedStream; - } - catch (Exception ex) - { - // From this API, managed dev expect IO exceptions for "something wrong": - WinRtIOHelper.NativeExceptionToIOExceptionInfo(ex).Throw(); - return null; - } - } - - [CLSCompliant(false)] - public static SafeFileHandle? CreateSafeFileHandle( - this IStorageFile windowsRuntimeFile, - FileAccess access = FileAccess.ReadWrite, - FileShare share = FileShare.Read, - FileOptions options = FileOptions.None) - { - if (windowsRuntimeFile == null) - throw new ArgumentNullException(nameof(windowsRuntimeFile)); - - HANDLE_ACCESS_OPTIONS accessOptions = FileAccessToHandleAccessOptions(access); - HANDLE_SHARING_OPTIONS sharingOptions = FileShareToHandleSharingOptions(share); - HANDLE_OPTIONS handleOptions = FileOptionsToHandleOptions(options); - - IStorageItemHandleAccess? handleAccess = ((object)windowsRuntimeFile) as IStorageItemHandleAccess; - - if (handleAccess == null) - return null; - - SafeFileHandle handle; - - int result = handleAccess.Create( - accessOptions, - sharingOptions, - handleOptions, - IntPtr.Zero, - out handle); - - if (result != 0) - throw Win32Marshal.GetExceptionForWin32Error(Win32Marshal.TryMakeWin32ErrorCodeFromHR(result), windowsRuntimeFile.Name); - - return handle; - } - - [CLSCompliant(false)] - public static SafeFileHandle? CreateSafeFileHandle( - this IStorageFolder rootDirectory, - string relativePath, - FileMode mode) - { - return rootDirectory.CreateSafeFileHandle(relativePath, mode, (mode == FileMode.Append ? FileAccess.Write : FileAccess.ReadWrite)); - } - - [CLSCompliant(false)] - public static SafeFileHandle? CreateSafeFileHandle( - this IStorageFolder rootDirectory, - string relativePath, - FileMode mode, - FileAccess access, - FileShare share = FileShare.Read, - FileOptions options = FileOptions.None) - { - if (rootDirectory == null) - throw new ArgumentNullException(nameof(rootDirectory)); - if (relativePath == null) - throw new ArgumentNullException(nameof(relativePath)); - - HANDLE_CREATION_OPTIONS creationOptions = FileModeToCreationOptions(mode); - HANDLE_ACCESS_OPTIONS accessOptions = FileAccessToHandleAccessOptions(access); - HANDLE_SHARING_OPTIONS sharingOptions = FileShareToHandleSharingOptions(share); - HANDLE_OPTIONS handleOptions = FileOptionsToHandleOptions(options); - - IStorageFolderHandleAccess? handleAccess = ((object)rootDirectory) as IStorageFolderHandleAccess; - - if (handleAccess == null) - return null; - - SafeFileHandle handle; - - int result = handleAccess.Create( - relativePath, - creationOptions, - accessOptions, - sharingOptions, - handleOptions, - IntPtr.Zero, - out handle); - - if (result != 0) - throw Win32Marshal.GetExceptionForWin32Error(Win32Marshal.TryMakeWin32ErrorCodeFromHR(result), relativePath); - - return handle; - } - - private static HANDLE_ACCESS_OPTIONS FileAccessToHandleAccessOptions(FileAccess access) => - access switch - { - FileAccess.ReadWrite => HANDLE_ACCESS_OPTIONS.HAO_READ | HANDLE_ACCESS_OPTIONS.HAO_WRITE, - FileAccess.Read => HANDLE_ACCESS_OPTIONS.HAO_READ, - FileAccess.Write => HANDLE_ACCESS_OPTIONS.HAO_WRITE, - _ => throw new ArgumentOutOfRangeException(nameof(access), access, null), - }; - - private static HANDLE_SHARING_OPTIONS FileShareToHandleSharingOptions(FileShare share) - { - if ((share & FileShare.Inheritable) != 0) - throw new NotSupportedException(SR.NotSupported_Inheritable); - if (share < FileShare.None || share > (FileShare.ReadWrite | FileShare.Delete)) - throw new ArgumentOutOfRangeException(nameof(share), share, null); - - HANDLE_SHARING_OPTIONS sharingOptions = HANDLE_SHARING_OPTIONS.HSO_SHARE_NONE; - if ((share & FileShare.Read) != 0) - sharingOptions |= HANDLE_SHARING_OPTIONS.HSO_SHARE_READ; - if ((share & FileShare.Write) != 0) - sharingOptions |= HANDLE_SHARING_OPTIONS.HSO_SHARE_WRITE; - if ((share & FileShare.Delete) != 0) - sharingOptions |= HANDLE_SHARING_OPTIONS.HSO_SHARE_DELETE; - - return sharingOptions; - } - - private static HANDLE_OPTIONS FileOptionsToHandleOptions(FileOptions options) - { - if ((options & FileOptions.Encrypted) != 0) - throw new NotSupportedException(SR.NotSupported_Encrypted); - if (options != FileOptions.None && (options & - ~(FileOptions.WriteThrough | FileOptions.Asynchronous | FileOptions.RandomAccess | FileOptions.DeleteOnClose | - FileOptions.SequentialScan | (FileOptions)0x20000000 /* NoBuffering */)) != 0) - throw new ArgumentOutOfRangeException(nameof(options), options, null); - - return (HANDLE_OPTIONS)options; - } - - private static HANDLE_CREATION_OPTIONS FileModeToCreationOptions(FileMode mode) - { - if (mode < FileMode.CreateNew || mode > FileMode.Append) - throw new ArgumentOutOfRangeException(nameof(mode), mode, null); - - if (mode == FileMode.Append) - return HANDLE_CREATION_OPTIONS.HCO_CREATE_ALWAYS; - - return (HANDLE_CREATION_OPTIONS)mode; - } - } -} diff --git a/src/libraries/System.Runtime.WindowsRuntime/src/System/IO/WindowsRuntimeStreamExtensions.cs b/src/libraries/System.Runtime.WindowsRuntime/src/System/IO/WindowsRuntimeStreamExtensions.cs deleted file mode 100644 index e84c3a8..0000000 --- a/src/libraries/System.Runtime.WindowsRuntime/src/System/IO/WindowsRuntimeStreamExtensions.cs +++ /dev/null @@ -1,347 +0,0 @@ -// 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.ComponentModel; -using System.Diagnostics; -using System.IO; -using System.Runtime.CompilerServices; -using System.Runtime.InteropServices; -using System.Threading.Tasks; -using Windows.Foundation; -using Windows.Storage.Streams; - -namespace System.IO -{ - /// - /// Contains extension methods for conversion between WinRT streams and managed streams. - /// This class is the public facade for the stream adapters library. - /// - public static class WindowsRuntimeStreamExtensions - { - #region Constants and static Fields - - private const int DefaultBufferSize = 16384; // = 0x4000 = 16 KBytes. - - private static readonly ConditionalWeakTable s_winRtToNetFxAdapterMap - = new ConditionalWeakTable(); - - private static readonly ConditionalWeakTable s_netFxToWinRtAdapterMap - = new ConditionalWeakTable(); - - #endregion Constants and static Fields - - - #region Helpers - -#if DEBUG - private static void AssertMapContains(ConditionalWeakTable map, TKey key, TValue value, - bool valueMayBeWrappedInBufferedStream) - where TKey : class - where TValue : class - { - TValue? valueInMap; - - Debug.Assert(key != null); - - bool hasValueForKey = map.TryGetValue(key, out valueInMap); - - Debug.Assert(hasValueForKey); - - if (valueMayBeWrappedInBufferedStream) - { - BufferedStream? bufferedValueInMap = valueInMap as BufferedStream; - Debug.Assert(object.ReferenceEquals(value, valueInMap) - || (bufferedValueInMap != null && object.ReferenceEquals(value, bufferedValueInMap.UnderlyingStream))); - } - else - { - Debug.Assert(object.ReferenceEquals(value, valueInMap)); - } - } -#endif // DEBUG - - private static void EnsureAdapterBufferSize(Stream adapter, int requiredBufferSize, string methodName) - { - Debug.Assert(adapter != null); - Debug.Assert(!string.IsNullOrWhiteSpace(methodName)); - - int currentBufferSize = 0; - BufferedStream? bufferedAdapter = adapter as BufferedStream; - if (bufferedAdapter != null) - currentBufferSize = bufferedAdapter.BufferSize; - - if (requiredBufferSize != currentBufferSize) - { - if (requiredBufferSize == 0) - throw new InvalidOperationException(SR.Format(SR.InvalidOperation_CannotChangeBufferSizeOfWinRtStreamAdapterToZero, methodName)); - - throw new InvalidOperationException(SR.Format(SR.InvalidOperation_CannotChangeBufferSizeOfWinRtStreamAdapter, methodName)); - } - } - - #endregion Helpers - - - #region WinRt-to-NetFx conversion - - [CLSCompliant(false)] - public static Stream AsStreamForRead(this IInputStream windowsRuntimeStream) - { - return AsStreamInternal(windowsRuntimeStream, DefaultBufferSize, "AsStreamForRead", forceBufferSize: false); - } - - - [CLSCompliant(false)] - public static Stream AsStreamForRead(this IInputStream windowsRuntimeStream, int bufferSize) - { - return AsStreamInternal(windowsRuntimeStream, bufferSize, "AsStreamForRead", forceBufferSize: true); - } - - - [CLSCompliant(false)] - public static Stream AsStreamForWrite(this IOutputStream windowsRuntimeStream) - { - return AsStreamInternal(windowsRuntimeStream, DefaultBufferSize, "AsStreamForWrite", forceBufferSize: false); - } - - - [CLSCompliant(false)] - public static Stream AsStreamForWrite(this IOutputStream windowsRuntimeStream, int bufferSize) - { - return AsStreamInternal(windowsRuntimeStream, bufferSize, "AsStreamForWrite", forceBufferSize: true); - } - - - [CLSCompliant(false)] - public static Stream AsStream(this IRandomAccessStream windowsRuntimeStream) - { - return AsStreamInternal(windowsRuntimeStream, DefaultBufferSize, "AsStream", forceBufferSize: false); - } - - - [CLSCompliant(false)] - public static Stream AsStream(this IRandomAccessStream windowsRuntimeStream, int bufferSize) - { - return AsStreamInternal(windowsRuntimeStream, bufferSize, "AsStream", forceBufferSize: true); - } - - - private static Stream AsStreamInternal(object windowsRuntimeStream, int bufferSize, string invokedMethodName, bool forceBufferSize) - { - if (windowsRuntimeStream == null) - throw new ArgumentNullException(nameof(windowsRuntimeStream)); - - if (bufferSize < 0) - throw new ArgumentOutOfRangeException(nameof(bufferSize), SR.ArgumentOutOfRange_WinRtAdapterBufferSizeMayNotBeNegative); - - Debug.Assert(!string.IsNullOrWhiteSpace(invokedMethodName)); - - // If the WinRT stream is actually a wrapped managed stream, we will unwrap it and return the original. - // In that case we do not need to put the wrapper into the map. - - // We currently do capability-based adapter selection for WinRt->NetFx, but not vice versa (time constraints). - // Once we added the reverse direction, we will be able replce this entire section with just a few lines. - NetFxToWinRtStreamAdapter? sAdptr = windowsRuntimeStream as NetFxToWinRtStreamAdapter; - if (sAdptr != null) - { - Stream? wrappedNetFxStream = sAdptr.GetManagedStream(); - if (wrappedNetFxStream == null) - throw new ObjectDisposedException(nameof(windowsRuntimeStream), SR.ObjectDisposed_CannotPerformOperation); - -#if DEBUG // In Chk builds, verify that the original managed stream is correctly entered into the NetFx->WinRT map: - AssertMapContains(s_netFxToWinRtAdapterMap, wrappedNetFxStream, sAdptr, - valueMayBeWrappedInBufferedStream: false); -#endif // DEBUG - - return wrappedNetFxStream; - } - - // We have a real WinRT stream. - - Stream? adapter; - bool adapterExists = s_winRtToNetFxAdapterMap.TryGetValue(windowsRuntimeStream, out adapter); - - // There is already an adapter: - if (adapterExists) - { - Debug.Assert((adapter is BufferedStream && ((BufferedStream)adapter).UnderlyingStream is WinRtToNetFxStreamAdapter) - || (adapter is WinRtToNetFxStreamAdapter)); - - if (forceBufferSize) - EnsureAdapterBufferSize(adapter, bufferSize, invokedMethodName); - - return adapter; - } - - // We do not have an adapter for this WinRT stream yet and we need to create one. - // Do that in a thread-safe manner in a separate method such that we only have to pay for the compiler allocating - // the required closure if this code path is hit: - - return AsStreamInternalFactoryHelper(windowsRuntimeStream, bufferSize, invokedMethodName, forceBufferSize); - } - - - // Separate method so we only pay for closure allocation if this code is executed: - private static Stream WinRtToNetFxAdapterMap_GetValue(object winRtStream) - { - return s_winRtToNetFxAdapterMap.GetValue(winRtStream, (wrtStr) => WinRtToNetFxStreamAdapter.Create(wrtStr)); - } - - - // Separate method so we only pay for closure allocation if this code is executed: - private static Stream WinRtToNetFxAdapterMap_GetValue(object winRtStream, int bufferSize) - { - return s_winRtToNetFxAdapterMap.GetValue(winRtStream, (wrtStr) => new BufferedStream(WinRtToNetFxStreamAdapter.Create(wrtStr), bufferSize)); - } - - - private static Stream AsStreamInternalFactoryHelper(object windowsRuntimeStream, int bufferSize, string invokedMethodName, bool forceBufferSize) - { - Debug.Assert(windowsRuntimeStream != null); - Debug.Assert(bufferSize >= 0); - Debug.Assert(!string.IsNullOrWhiteSpace(invokedMethodName)); - - // Get the adapter for this windowsRuntimeStream again (it may have been created concurrently). - // If none exists yet, create a new one: - Stream adapter = (bufferSize == 0) - ? WinRtToNetFxAdapterMap_GetValue(windowsRuntimeStream) - : WinRtToNetFxAdapterMap_GetValue(windowsRuntimeStream, bufferSize); - - Debug.Assert(adapter != null); - Debug.Assert((adapter is BufferedStream && ((BufferedStream)adapter).UnderlyingStream is WinRtToNetFxStreamAdapter) - || (adapter is WinRtToNetFxStreamAdapter)); - - if (forceBufferSize) - EnsureAdapterBufferSize(adapter, bufferSize, invokedMethodName); - - WinRtToNetFxStreamAdapter? actualAdapter = adapter as WinRtToNetFxStreamAdapter; - if (actualAdapter == null) - actualAdapter = ((BufferedStream)adapter).UnderlyingStream as WinRtToNetFxStreamAdapter; - - actualAdapter!.SetWonInitializationRace(); - - return adapter; - } - - #endregion WinRt-to-NetFx conversion - - - #region NetFx-to-WinRt conversion - - [CLSCompliant(false)] - public static IInputStream AsInputStream(this Stream stream) - { - if (stream == null) - throw new ArgumentNullException(nameof(stream)); - - if (!stream.CanRead) - throw new NotSupportedException(SR.NotSupported_CannotConvertNotReadableToInputStream); - - object adapter = AsWindowsRuntimeStreamInternal(stream); - - IInputStream? winRtStream = adapter as IInputStream; - Debug.Assert(winRtStream != null); - - return winRtStream; - } - - - [CLSCompliant(false)] - public static IOutputStream AsOutputStream(this Stream stream) - { - if (stream == null) - throw new ArgumentNullException(nameof(stream)); - - if (!stream.CanWrite) - throw new NotSupportedException(SR.NotSupported_CannotConvertNotWritableToOutputStream); - - object adapter = AsWindowsRuntimeStreamInternal(stream); - - IOutputStream? winRtStream = adapter as IOutputStream; - Debug.Assert(winRtStream != null); - - return winRtStream; - } - - - [CLSCompliant(false)] - public static IRandomAccessStream AsRandomAccessStream(this Stream stream) - { - if (stream == null) - throw new ArgumentNullException(nameof(stream)); - - if (!stream.CanSeek) - throw new NotSupportedException(SR.NotSupported_CannotConvertNotSeekableToRandomAccessStream); - - object adapter = AsWindowsRuntimeStreamInternal(stream); - - IRandomAccessStream? winRtStream = adapter as IRandomAccessStream; - Debug.Assert(winRtStream != null); - - return winRtStream; - } - - - private static object AsWindowsRuntimeStreamInternal(Stream stream) - { - // Check to see if the managed stream is actually a wrapper of a WinRT stream: - // (This can be either an adapter directly, or an adapter wrapped in a BufferedStream.) - WinRtToNetFxStreamAdapter? sAdptr = stream as WinRtToNetFxStreamAdapter; - if (sAdptr == null) - { - BufferedStream? buffAdptr = stream as BufferedStream; - if (buffAdptr != null) - sAdptr = buffAdptr.UnderlyingStream as WinRtToNetFxStreamAdapter; - } - - // If the managed stream us actually a WinRT stream, we will unwrap it and return the original. - // In that case we do not need to put the wrapper into the map. - if (sAdptr != null) - { - object? wrappedWinRtStream = sAdptr.GetWindowsRuntimeStream(); - if (wrappedWinRtStream == null) - throw new ObjectDisposedException(nameof(stream), SR.ObjectDisposed_CannotPerformOperation); - -#if DEBUG // In Chk builds, verify that the original WinRT stream is correctly entered into the WinRT->NetFx map: - AssertMapContains(s_winRtToNetFxAdapterMap, wrappedWinRtStream, sAdptr, valueMayBeWrappedInBufferedStream: true); -#endif // DEBUG - return wrappedWinRtStream; - } - - // We have a real managed Stream. - - // See if the managed stream already has an adapter: - NetFxToWinRtStreamAdapter? adapter; - bool adapterExists = s_netFxToWinRtAdapterMap.TryGetValue(stream, out adapter); - - // There is already an adapter: - if (adapterExists) - return adapter!; - - // We do not have an adapter for this managed stream yet and we need to create one. - // Do that in a thread-safe manner in a separate method such that we only have to pay for the compiler allocating - // the required closure if this code path is hit: - return AsWindowsRuntimeStreamInternalFactoryHelper(stream); - } - - - private static NetFxToWinRtStreamAdapter AsWindowsRuntimeStreamInternalFactoryHelper(Stream stream) - { - Debug.Assert(stream != null); - - // Get the adapter for managed stream again (it may have been created concurrently). - // If none exists yet, create a new one: - NetFxToWinRtStreamAdapter adapter = s_netFxToWinRtAdapterMap.GetValue(stream, (str) => NetFxToWinRtStreamAdapter.Create(str)); - - Debug.Assert(adapter != null); - adapter.SetWonInitializationRace(); - - return adapter; - } - #endregion NetFx-to-WinRt conversion - - } // class WindowsRuntimeStreamExtensions -} // namespace - -// WindowsRuntimeStreamExtensions.cs diff --git a/src/libraries/System.Runtime.WindowsRuntime/src/System/Resources/WindowsRuntimeResourceManager.cs b/src/libraries/System.Runtime.WindowsRuntime/src/System/Resources/WindowsRuntimeResourceManager.cs deleted file mode 100644 index 3e9de88..0000000 --- a/src/libraries/System.Runtime.WindowsRuntime/src/System/Resources/WindowsRuntimeResourceManager.cs +++ /dev/null @@ -1,652 +0,0 @@ -// 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. - -#if FEATURE_APPX -using Internal.Resources; -#endif -using System; -using System.Collections.Generic; -using System.Diagnostics; -using System.Globalization; -using System.Resources; -using System.Runtime.CompilerServices; -using System.Security; -using System.Text; // For UriEncode -using Windows.ApplicationModel.Resources.Core; -using Windows.ApplicationModel; -using Windows.Foundation.Collections; -using Windows.Storage; - -namespace System.Resources -{ -#if FEATURE_APPX - // Please see the comments regarding thread safety preceding the implementations - // of Initialize() and GetString() below. - internal sealed class WindowsRuntimeResourceManager : WindowsRuntimeResourceManagerBase - { - // Setting invariant culture to Windows Runtime doesn't work because Windows Runtime expects language name in the form of BCP-47 tags while - // invariant name is an empty string. We will use the private invariant culture name x-VL instead. - private const string c_InvariantCulturePrivateName = "x-VL"; - - private ResourceMap? _resourceMap; - private ResourceContext? _clonedResourceContext; - private string? _clonedResourceContextFallBackList; - - private static char[]? s_charCultureSeparator; - - private struct PackageInfo - { - public string? Path; - public string? Name; - public string? FullName; - } - - private static PackageInfo s_currentPackageInfo; - - private static List? s_dependentPackageInfoList; - - private static ResourceContext? s_globalResourceContext; // Read from it but do not modify it or call Reset() on it as that would affect the app-wide state - - private static volatile string? s_globalResourceContextFallBackList; - private static volatile CultureInfo? s_globalResourceContextBestFitCultureInfo; - private static volatile global::Windows.ApplicationModel.Resources.Core.ResourceManager? s_globalResourceManager; - - private static readonly object s_objectForLock = new object(); // Used by InitializeStatics - - private static bool InitializeStatics() - { - global::Windows.ApplicationModel.Resources.Core.ResourceManager? globalResourceManager = null; - - if (s_globalResourceManager == null) - { - lock (s_objectForLock) - { - if (s_globalResourceManager == null) - { - globalResourceManager = global::Windows.ApplicationModel.Resources.Core.ResourceManager.Current; - - InitializeStaticGlobalResourceContext(globalResourceManager); - - s_charCultureSeparator = new char[] { ';' }; - - Package currentPackage = Package.Current; - if (currentPackage != null) - { - StorageFolder currentPackageLocation = currentPackage.InstalledLocation; - - s_currentPackageInfo.Path = null; - s_currentPackageInfo.Name = null; - s_currentPackageInfo.FullName = null; - - if (currentPackageLocation != null) - s_currentPackageInfo.Path = currentPackageLocation.Path; - - PackageId id = currentPackage.Id; - if (id != null) - { - s_currentPackageInfo.Name = id.Name; // We do not enforce this to be non-null. - s_currentPackageInfo.FullName = id.FullName; - } - } - - if (globalResourceManager != null && - s_globalResourceContext != null && - s_globalResourceContextFallBackList != null && - s_globalResourceContextFallBackList.Length > 0 && // Should never be empty - s_charCultureSeparator != null && - s_currentPackageInfo.Path != null) - s_globalResourceManager = globalResourceManager; - } - } - } - - return s_globalResourceManager != null; - } - - private static void InitializeStaticGlobalResourceContext(global::Windows.ApplicationModel.Resources.Core.ResourceManager? resourceManager) - { - if (s_globalResourceContext == null) - { - lock (s_objectForLock) - { - if (s_globalResourceContext == null) - { - resourceManager = resourceManager ?? global::Windows.ApplicationModel.Resources.Core.ResourceManager.Current; - - if (resourceManager != null) - { -#pragma warning disable 618 - ResourceContext globalResourceContext = resourceManager.DefaultContext; -#pragma warning restore 618 - if (globalResourceContext != null) - { - List languages = new List(globalResourceContext.Languages); - - s_globalResourceContextBestFitCultureInfo = GetBestFitCultureFromLanguageList(languages); - s_globalResourceContextFallBackList = ReadOnlyListToString(languages); - s_globalResourceContext = globalResourceContext; - s_globalResourceContext.QualifierValues.MapChanged += new MapChangedEventHandler(GlobalResourceContextChanged); - } - } - } - } - } - } - - - // Returns the CultureInfo representing the first language in the list that we can construct a CultureInfo for or null if - // no such culture exists. - private static unsafe CultureInfo? GetBestFitCultureFromLanguageList(List languages) - { - char* localeNameBuffer = stackalloc char[Interop.Kernel32.LOCALE_NAME_MAX_LENGTH]; // LOCALE_NAME_MAX_LENGTH includes null terminator - - for (int i = 0; i < languages.Count; i++) - { - if (WindowsRuntimeResourceManagerBase.IsValidCulture(languages[i])) - { - return new CultureInfo(languages[i]); - } - - int result = Interop.Kernel32.ResolveLocaleName(languages[i], localeNameBuffer, Interop.Kernel32.LOCALE_NAME_MAX_LENGTH); - if (result != 0) - { - string localeName = new string(localeNameBuffer, 0, result - 1); // result length includes null terminator - - if (WindowsRuntimeResourceManagerBase.IsValidCulture(localeName)) - { - return new CultureInfo(localeName); - } - } - } - - return null; - } - // Can be called independently of/simultaneously with InitializeStatics. - // Does not use the results of InitializeStatics. - // Does not require the use of a lock because, given that the results of all the callees of - // this function are idempotent for the process lifetime, this function will always store - // the same information in s_dependentPackagePath no matter how many times it is called. - private static void InitializeStaticsForDependentPackages() - { - if (s_dependentPackageInfoList == null) - { - // Create an empty list. If there are no dependencies, this will be our way of knowing that we ran - // through this function once. - List dependentPackageInfoList = new List(); - - // We call Package.Current here and in InitializeStatics. This may cause a small perf hit. - // In theory we could have cached it as a static variable. - // However, we don't want to have to keep a reference to it alive for the lifetime of the AppDomain. - // Also having InitializeStaticsForDependentPackages not depend on InitializeStatics leads to a simpler design. - Package currentPackage = Package.Current; - - if (currentPackage != null) - { - IReadOnlyList dependencies = currentPackage.Dependencies; - if (dependencies != null) - { - int dependenciesCount = dependencies.Count; - - if (dependenciesCount > 0) - { - // We have dependencies. Throw away the old empty list, and create a list with - // capacity exactly equal to the number of dependencies. - dependentPackageInfoList = new List(dependenciesCount); - - foreach (Package package in dependencies) - { - if (package != null) - { - StorageFolder dependentPackageLocation = package.InstalledLocation; - PackageInfo dependentPackageInfo; - - dependentPackageInfo.Path = null; - dependentPackageInfo.Name = null; - dependentPackageInfo.FullName = null; - - if (dependentPackageLocation != null) - dependentPackageInfo.Path = dependentPackageLocation.Path; - - PackageId id = package.Id; - if (id != null) - { - dependentPackageInfo.Name = id.Name; - dependentPackageInfo.FullName = id.FullName; - } - - dependentPackageInfoList.Add(dependentPackageInfo); - } - } - } - } - } - - // Assign even if the list is empty. That way we know we ran through this function once. - s_dependentPackageInfoList = dependentPackageInfoList; - } - - Debug.Assert(s_dependentPackageInfoList != null); - } - - private static void GlobalResourceContextChanged(object sender, IMapChangedEventArgs e) - { - Debug.Assert(s_globalResourceContextFallBackList != null); - Debug.Assert(s_globalResourceContext != null); - - IReadOnlyList langs; - - try - { - langs = s_globalResourceContext.Languages; - } - catch (ArgumentException) - { - // Sometimes Windows Runtime fails and we get Argument Exception which can fail fast the whole app - // to avoid that we ignore the exception. - return; - } - - List languages = new List(langs); - - if (languages.Count > 0 && languages[0] == c_InvariantCulturePrivateName) - { - languages[0] = CultureInfo.InvariantCulture.Name; - } - - s_globalResourceContextBestFitCultureInfo = GetBestFitCultureFromLanguageList(languages); - s_globalResourceContextFallBackList = ReadOnlyListToString(languages); - } - - private static bool LibpathMatchesPackagepath(string libpath, string packagepath) - { - Debug.Assert(libpath != null); - Debug.Assert(packagepath != null); - - return packagepath.Length < libpath.Length && - string.Compare(packagepath, 0, - libpath, 0, - packagepath.Length, - StringComparison.OrdinalIgnoreCase) == 0 && - // Ensure wzPackagePath is not just a prefix, but a path prefix - // This says: packagepath is c:\foo || c:\foo\ - (libpath[packagepath.Length] == '\\' || packagepath.EndsWith("\\", StringComparison.Ordinal)); - } - -#if NETSTANDARD2_0 || NETCOREAPP - /* Returns true if libpath is path to an ni image and if the path contains packagename as a subfolder */ - private static bool LibpathContainsPackagename(string libpath, string packagename) - { - Debug.Assert(libpath != null); - Debug.Assert(packagename != null); - - return libpath.IndexOf("\\" + packagename + "\\", StringComparison.OrdinalIgnoreCase) >= 0 && - (libpath.EndsWith("ni.dll", StringComparison.OrdinalIgnoreCase) || libpath.EndsWith("ni.exe", StringComparison.OrdinalIgnoreCase)); - } -#endif - - private static string? FindPackageSimpleNameForFilename(string libpath) - { - Debug.Assert(libpath != null); - Debug.Assert(s_currentPackageInfo.Path != null); // Set in InitializeStatics() - // s_currentPackageInfo.Name may be null (see note below) - - if (LibpathMatchesPackagepath(libpath, s_currentPackageInfo.Path)) - return s_currentPackageInfo.Name; // This may be null, in which case we failed to get the name (in InitializeStatics), but matched the path, so stop looking. - else // Look at dependent packages - { - InitializeStaticsForDependentPackages(); - - // s_dependentPackageInfoList is empty (but non-null) if there are no dependent packages. - foreach (PackageInfo dependentPackageInfo in s_dependentPackageInfoList!) - { - if (LibpathMatchesPackagepath(libpath, dependentPackageInfo.Path!)) - return dependentPackageInfo.Name; // This may be null, in which case we failed to get the name (in InitializeStaticsForDependentPackages), but matched the path, so stop looking. - } - } - -#if NETSTANDARD2_0 || NETCOREAPP - /* On phone libpath is usually ni path and not IL path as we do not touch the IL on phone. - On Phone NI images are no longer under package root. Due to this above logic fails to - find the package to which the library belongs. We assume that NI paths usually have - package name as subfolder in its path. Based on this assumption we can find the package - to which an NI belongs. Below code does that. - */ - if (LibpathContainsPackagename(libpath, s_currentPackageInfo.FullName!)) - return s_currentPackageInfo.Name; - else // Look at dependent packages - { - // s_dependentPackageInfoList is empty (but non-null) if there are no dependent packages. - foreach (PackageInfo dependentPackageInfo in s_dependentPackageInfoList) - { - if (LibpathContainsPackagename(libpath, dependentPackageInfo.FullName!)) - return dependentPackageInfo.Name; - } - } -#endif - return null; - } - - // Obtain instances of the Resource Map and Resource Context provided by - // the Windows Modern Resource Manager (MRM). - - // Not thread-safe. Only call this once on one thread for each object instance. - // For example, System.Runtime.ResourceManager only calls this from its constructors, - // guaranteeing that this only gets called once, on one thread, for each new instance - // of System.Runtime.ResourceManager. - - // Throws exceptions - // Only returns true if the function succeeded completely. - // Outputs exceptionInfo since it may be needed for debugging purposes - // if an exception is thrown by one of Initialize's callees. - public override bool Initialize(string libpath, string reswFilename, out PRIExceptionInfo? exceptionInfo) - { - Debug.Assert(libpath != null); - Debug.Assert(reswFilename != null); - exceptionInfo = null; - - if (InitializeStatics()) - { - // AllResourceMaps can throw ERROR_MRM_MAP_NOT_FOUND, - // although in that case we are not sure for which package it failed to find - // resources (if we are looking for resources for a framework package, - // it might throw ERROR_MRM_MAP_NOT_FOUND if the app package - // resources could not be loaded, even if the framework package - // resources are properly configured). So we will not fill in the - // exceptionInfo structure at this point since we don't have any - // reliable information to include in it. - - IReadOnlyDictionary - resourceMapDictionary = s_globalResourceManager!.AllResourceMaps; - - if (resourceMapDictionary != null) - { - string? packageSimpleName = FindPackageSimpleNameForFilename(libpath); - -#if NETSTANDARD2_0 || NETCOREAPP - // If we have found a simple package name for the assembly, lets make sure it is not *.resource.dll that - // an application may have packaged in its AppX. This is to enforce AppX apps to use PRI resources. - if (packageSimpleName != null) - { - if (packageSimpleName.EndsWith(".resources.dll", StringComparison.CurrentCultureIgnoreCase)) - { - // Pretend we didn't get a package name. When an attempt is made to get resource string, GetString implementation - // will see that we are going to use modern resource manager but we don't have PRI and will thrown an exception indicating - // so. This will force the developer to have a valid PRI based resource. - packageSimpleName = null; - } - } -#endif - if (packageSimpleName != null) - { - ResourceMap? packageResourceMap = null; - - // Win8 enforces that package simple names are unique (for example, the App Store will not - // allow two apps with the same package simple name). That is why the Modern Resource Manager - // keys access to resources based on the package simple name. - if (resourceMapDictionary.TryGetValue(packageSimpleName, out packageResourceMap)) - { - if (packageResourceMap != null) - { - // GetSubtree returns null when it cannot find resource strings - // named "reswFilename/*" for the package we are looking up. - - reswFilename = UriUtility.UriEncode(reswFilename)!; - _resourceMap = packageResourceMap.GetSubtree(reswFilename); - - if (_resourceMap == null) - { - exceptionInfo = new PRIExceptionInfo(); - exceptionInfo.PackageSimpleName = packageSimpleName; - exceptionInfo.ResWFile = reswFilename; - } - else - { - _clonedResourceContext = s_globalResourceContext!.Clone(); - - if (_clonedResourceContext != null) - { - // Will need to be changed the first time it is used. But we can't set it to "" since we will take a lock on it. - _clonedResourceContextFallBackList = ReadOnlyListToString(_clonedResourceContext.Languages); - - if (_clonedResourceContextFallBackList != null) - return true; - } - } - } - } - } - } - } - - return false; - } - - private static IReadOnlyList StringToReadOnlyList(string s) - { - Debug.Assert(s != null); - Debug.Assert(s_charCultureSeparator != null); - - List newList = new List(s.Split(s_charCultureSeparator)); - return newList.AsReadOnly(); - } - - private static string ReadOnlyListToString(IReadOnlyList list) - { - Debug.Assert(list != null); - - return string.Join(";", list); - } - - public override CultureInfo GlobalResourceContextBestFitCultureInfo - { - get - { - InitializeStaticGlobalResourceContext(null); - return s_globalResourceContextBestFitCultureInfo!; - } - } - - // This method will set the culture ci as default language in the default resource context - // which is global for the whole app - public override bool SetGlobalResourceContextDefaultCulture(CultureInfo ci) - { - Debug.Assert(ci != null); - InitializeStaticGlobalResourceContext(null); - - if (s_globalResourceContext == null) - { - return false; - } - - if (s_globalResourceContextBestFitCultureInfo != null && s_globalResourceContextBestFitCultureInfo.Name.Equals(ci.Name, StringComparison.OrdinalIgnoreCase)) - { - if (!ReferenceEquals(s_globalResourceContextBestFitCultureInfo, ci)) - { - // We have same culture name but different reference, we'll need to update s_globalResourceContextBestFitCultureInfo only as ci can - // be a customized subclassed culture which setting different values for NFI, DTFI...etc. - s_globalResourceContextBestFitCultureInfo = ci; - } - - // the default culture is already set. nothing more need to be done - return true; - } - - List languages = new List(s_globalResourceContext.Languages); - languages.Insert(0, ci.Name == CultureInfo.InvariantCulture.Name ? c_InvariantCulturePrivateName : ci.Name); - - // remove any duplication in the list - int i = languages.Count - 1; - while (i > 0) - { - if (languages[i].Equals(ci.Name, StringComparison.OrdinalIgnoreCase)) - { - languages.RemoveAt(i); - } - i--; - } - s_globalResourceContext.Languages = languages; - - // update s_globalResourceContextBestFitCultureInfo and don't wait to be overridden by GlobalResourceContextChanged - // to avoid any timing problem - s_globalResourceContextBestFitCultureInfo = ci; - return true; - } - - // Obtains a resource string given the name of the string resource, and optional starting - // and neutral resource cultures (e.g. "de-DE"). - - // Thread-safe provided that the call to Initialize() happened only once on one thread - // and has already completed successfully, and that the WinRT APIs called below - // continue to be thread-safe. - - // Throws exceptions - public override string? GetString(string stringName, string? startingCulture, string? neutralResourcesCulture) - { - Debug.Assert(stringName != null); - Debug.Assert(_resourceMap != null); // Should have been initialized by now - - ResourceCandidate? resourceCandidate = null; - - stringName = UriUtility.UriEncode(stringName)!; - - if (startingCulture == null && neutralResourcesCulture == null) - { -#pragma warning disable 618 - resourceCandidate = _resourceMap.GetValue(stringName); -#pragma warning restore 618 - } - else - { - Debug.Assert(_clonedResourceContext != null); // Should have been initialized by now - Debug.Assert(_clonedResourceContextFallBackList != null); // Should have been initialized by now - Debug.Assert(s_globalResourceContextFallBackList != null); // Should have been initialized by now - Debug.Assert(s_globalResourceContextFallBackList.Length > 0); // Should never be empty - - // We need to modify the culture fallback list used by the Modern Resource Manager - // The starting culture has to be looked up first, and neutral resources culture has - // to be looked up last. - - string? newResourceFallBackList = null; - - newResourceFallBackList = - (startingCulture == null ? "" : startingCulture + ";") + - s_globalResourceContextFallBackList + // Our tests do not test this line of code, so be extra careful if you modify or move it. - (neutralResourcesCulture == null ? "" : ";" + neutralResourcesCulture); - - lock (_clonedResourceContext) - { - // s_globalResourceContextFallBackList may have changed on another thread by now. - // We cannot prevent that from happening because it may have happened on a native - // thread, and we do not share the same lock mechanisms with native code. - // The worst that can happen is that a string is unexpectedly missing - // or in the wrong language. - - if (!string.Equals(newResourceFallBackList, _clonedResourceContextFallBackList, StringComparison.Ordinal)) - { - _clonedResourceContext.Languages = StringToReadOnlyList(newResourceFallBackList); - _clonedResourceContextFallBackList = newResourceFallBackList; - } - - resourceCandidate = _resourceMap.GetValue(stringName, _clonedResourceContext); - } - } - - if (resourceCandidate != null) - return resourceCandidate.ValueAsString; - - return null; - } - } - - // Adapted from the UrlEncode functions at file:alm\tfs_core\framework\common\UriUtility\HttpUtility.cs - // using methods which were in turn borrowed from - // file:ndp\fx\src\xsp\system\web\util\httpencoder.cs - // file:ndp\fx\src\xsp\system\web\httpserverutility.cs - // and file:ndp\fx\src\xsp\system\web\util\httpencoderutility.cs - internal static class UriUtility - { - // This method percent encodes the UTF8 encoding of a string. - // All characters are percent encoded except the unreserved characters from RFC 3986. - - // We cannot use the System.Uri class since by default it respects - // the set of unreserved characters from RFC 2396, which is different - // by the 5 characters !*'() - - // Adapted from the UrlEncode methods originally - // in file:ndp\fx\src\xsp\system\web\httpserverutility.cs - // and file:ndp\fx\src\xsp\system\web\util\httpencoder.cs - public static string? UriEncode(string str) - { - if (str == null) - return null; - - byte[] bytes = Encoding.UTF8.GetBytes(str); - - int count = bytes.Length; - - if (count == 0) - return null; - - int cBytesToEncode = 0; - - // count them first - for (int i = 0; i < count; i++) - { - if (!IsUriUnreservedChar((char)bytes[i])) - cBytesToEncode++; - } - - byte[]? expandedBytes = null; - - // nothing to expand? - if (cBytesToEncode == 0) - expandedBytes = bytes; - else - { - // expand not 'safe' characters into %xx - expandedBytes = new byte[count + cBytesToEncode * 2]; - int pos = 0; - - for (int i = 0; i < count; i++) - { - byte b = bytes[i]; - - if (IsUriUnreservedChar((char)b)) - { - expandedBytes[pos++] = b; - } - else - { - expandedBytes[pos++] = (byte)'%'; - expandedBytes[pos++] = (byte)HexConverter.ToCharLower(b >> 4); - expandedBytes[pos++] = (byte)HexConverter.ToCharLower(b); - } - } - } - - // Since all the bytes in expandedBytes are ascii characters UTF8 encoding can be used - return Encoding.UTF8.GetString(expandedBytes); - } - - // Modified from IsUrlSafeChar originally in file:ndp\fx\src\xsp\system\web\util\httpencoderutility.cs - // Set of unreserved characters from RFC 3986 - private static bool IsUriUnreservedChar(char ch) - { - if (ch >= 'a' && ch <= 'z' || ch >= 'A' && ch <= 'Z' || ch >= '0' && ch <= '9') - return true; - - switch (ch) - { - case '-': - case '_': - case '.': - case '~': - return true; - } - - return false; - } - } -#endif //FEATURE_APPX -} diff --git a/src/libraries/System.Runtime.WindowsRuntime/src/System/Runtime/InteropServices/HResults.cs b/src/libraries/System.Runtime.WindowsRuntime/src/System/Runtime/InteropServices/HResults.cs deleted file mode 100644 index c20a1ef..0000000 --- a/src/libraries/System.Runtime.WindowsRuntime/src/System/Runtime/InteropServices/HResults.cs +++ /dev/null @@ -1,26 +0,0 @@ -// 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; - -namespace System.Runtime.InteropServices -{ - /// - /// HRESULT values used in this assembly. - /// - internal static class __HResults - { - internal const int S_OK = unchecked((int)0x00000000); - internal const int E_BOUNDS = unchecked((int)0x8000000B); - internal const int E_ILLEGAL_STATE_CHANGE = unchecked((int)0x8000000D); - internal const int E_ILLEGAL_METHOD_CALL = unchecked((int)0x8000000E); - internal const int RO_E_CLOSED = unchecked((int)0x80000013); - internal const int E_ILLEGAL_DELEGATE_ASSIGNMENT = unchecked((int)0x80000018); - internal const int E_NOTIMPL = unchecked((int)0x80004001); - internal const int E_FAIL = unchecked((int)0x80004005); - internal const int E_INVALIDARG = unchecked((int)0x80070057); - } // internal static class HResults -} // namespace - -// HResults.cs diff --git a/src/libraries/System.Runtime.WindowsRuntime/src/System/Runtime/InteropServices/IAgileObject.cs b/src/libraries/System.Runtime.WindowsRuntime/src/System/Runtime/InteropServices/IAgileObject.cs deleted file mode 100644 index 6851848..0000000 --- a/src/libraries/System.Runtime.WindowsRuntime/src/System/Runtime/InteropServices/IAgileObject.cs +++ /dev/null @@ -1,22 +0,0 @@ -// 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; - -namespace System.Runtime.InteropServices -{ - /// - /// Managed declaration of the IAgileObject COM interface. - /// - [Guid("94ea2b94-e9cc-49e0-c0ff-ee64ca8f5b90")] - [InterfaceType(ComInterfaceType.InterfaceIsIUnknown)] - [ComImport] - internal interface IAgileObject - { - // this is an empty marker interface - - } // interface IAgileObject -} // namespace - -// IAgileObject.cs diff --git a/src/libraries/System.Runtime.WindowsRuntime/src/System/Runtime/InteropServices/IMarshal.cs b/src/libraries/System.Runtime.WindowsRuntime/src/System/Runtime/InteropServices/IMarshal.cs deleted file mode 100644 index d79c7b0..0000000 --- a/src/libraries/System.Runtime.WindowsRuntime/src/System/Runtime/InteropServices/IMarshal.cs +++ /dev/null @@ -1,31 +0,0 @@ -// 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; - -namespace System.Runtime.InteropServices -{ - /// - /// Managed declaration of the IMarshal COM interface. - /// - [Guid("00000003-0000-0000-c000-000000000046")] - [InterfaceType(ComInterfaceType.InterfaceIsIUnknown)] - [ComImport] - internal interface IMarshal - { - void GetUnmarshalClass([In] ref Guid riid, IntPtr pv, uint dwDestContext, IntPtr pvDestContext, uint mshlFlags, out Guid pCid); - - void GetMarshalSizeMax([In] ref Guid riid, IntPtr pv, uint dwDestContext, IntPtr pvDestContext, uint mshlflags, out uint pSize); - - void MarshalInterface(IntPtr pStm, [In] ref Guid riid, IntPtr pv, uint dwDestContext, IntPtr pvDestContext, uint mshlflags); - - void UnmarshalInterface(IntPtr pStm, [In] ref Guid riid, out IntPtr ppv); - - void ReleaseMarshalData(IntPtr pStm); - - void DisconnectObject(uint dwReserved); - } // interface IMarshal -} // namespace - -// IMarshal.cs diff --git a/src/libraries/System.Runtime.WindowsRuntime/src/System/Runtime/InteropServices/WindowsRuntime/AsyncInfo.cs b/src/libraries/System.Runtime.WindowsRuntime/src/System/Runtime/InteropServices/WindowsRuntime/AsyncInfo.cs deleted file mode 100644 index 2288620..0000000 --- a/src/libraries/System.Runtime.WindowsRuntime/src/System/Runtime/InteropServices/WindowsRuntime/AsyncInfo.cs +++ /dev/null @@ -1,206 +0,0 @@ -// 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 System.Threading; -using System.Threading.Tasks; -using Windows.Foundation; - -namespace System.Runtime.InteropServices.WindowsRuntime -{ - ///

Provides factory methods to construct WinRT-compatible representations of asynchronous operations.

- ///

The factory methods take as inputs functions (delegates) that provide managed Task objects; - /// Different factory methods return different sub-interfaces of Windows.Foundation.IAyncInfo. - /// When an asynchronous operation created by this factory is actually started (by calling Start()), - /// the specified Task-provider delegate will be invoked to create the Task that will - /// be wrapped by the to-WinRT adapter.

- [CLSCompliant(false)] - public static class AsyncInfo - { - #region Factory methods for creating "normal" IAsyncInfo instances backed by a Task created by a pastProvider delegate - - /// - /// Creates and starts an instance from a function that generates - /// a . - /// Use this overload if your task supports cancellation in order to hook-up the Cancel - /// mechanism exposed by the created asynchronous action and the cancellation of your task. - /// The function to invoke to create the task when the IAsyncInfo is started. - /// The function is passed a that the task may monitor - /// to be notified of a cancellation request; - /// you may ignore the CancellationToken if your task does not support cancellation. - /// An unstarted instance. - public static IAsyncAction Run(Func taskProvider) - { - if (taskProvider == null) - throw new ArgumentNullException(nameof(taskProvider)); - - return new TaskToAsyncActionAdapter(taskProvider); - } - - - /// - /// Creates and starts an instance from a function - /// that generates a . - /// Use this overload if your task supports cancellation and progress monitoring is order to: - /// (1) hook-up the Cancel mechanism of the created asynchronous action and the cancellation of your task, - /// and (2) hook-up the Progress update delegate exposed by the created async action and the progress updates - /// published by your task. - /// The function to invoke to create the task when the IAsyncInfo is started. - /// The function is passed a that the task may monitor - /// to be notified of a cancellation request; - /// you may ignore the CancellationToken if your task does not support cancellation. - /// It is also passed a instance to which progress updates may be published; - /// you may ignore the IProgress if your task does not support progress reporting. - /// An unstarted instance. - public static IAsyncActionWithProgress Run(Func, Task> taskProvider) - { - if (taskProvider == null) - throw new ArgumentNullException(nameof(taskProvider)); - - return new TaskToAsyncActionWithProgressAdapter(taskProvider); - } - - - /// - /// Creates and starts an instance from a function - /// that generates a . - /// Use this overload if your task supports cancellation in order to hook-up the Cancel - /// mechanism exposed by the created asynchronous operation and the cancellation of your task. - /// The function to invoke to create the task when the IAsyncInfo is started. - /// The function is passed a that the task may monitor - /// to be notified of a cancellation request; - /// you may ignore the CancellationToken if your task does not support cancellation. - /// An unstarted instance. - public static IAsyncOperation Run(Func> taskProvider) - { - // This is only internal to reduce the number of public overloads. - // Code execution flows through this method when the method above is called. We can always make this public. - - if (taskProvider == null) - throw new ArgumentNullException(nameof(taskProvider)); - - return new TaskToAsyncOperationAdapter(taskProvider); - } - - - /// - /// Creates and starts an instance - /// from a function that generates a .
- /// Use this overload if your task supports cancellation and progress monitoring is order to: - /// (1) hook-up the Cancel mechanism of the created asynchronous operation and the cancellation of your task, - /// and (2) hook-up the Progress update delegate exposed by the created async operation and the progress - /// updates published by your task.
- /// The result type of the task. - /// The type used for progress notifications. - /// The function to invoke to create the task when the IAsyncOperationWithProgress is started.
- /// The function is passed a that the task may monitor - /// to be notified of a cancellation request; - /// you may ignore the CancellationToken if your task does not support cancellation. - /// It is also passed a instance to which progress updates may be published; - /// you may ignore the IProgress if your task does not support progress reporting. - /// An unstarted instance. - public static IAsyncOperationWithProgress Run( - Func, Task> taskProvider) - { - if (taskProvider == null) - throw new ArgumentNullException(nameof(taskProvider)); - - return new TaskToAsyncOperationWithProgressAdapter(taskProvider); - } - - #endregion Factory methods for creating "normal" IAsyncInfo instances backed by a Task created by a pastProvider delegate - - - #region Factory methods for creating IAsyncInfo instances that have already completed synchronously - - internal static IAsyncAction CreateCompletedAction() - { - var asyncInfo = new TaskToAsyncActionAdapter(isCanceled: false); - return asyncInfo; - } - - - internal static IAsyncActionWithProgress CreateCompletedAction() - { - var asyncInfo = new TaskToAsyncActionWithProgressAdapter(isCanceled: false); - return asyncInfo; - } - - - internal static IAsyncOperation CreateCompletedOperation(TResult synchronousResult) - { - var asyncInfo = new TaskToAsyncOperationAdapter(synchronousResult); - return asyncInfo; - } - - - internal static IAsyncOperationWithProgress CreateCompletedOperation(TResult synchronousResult) - { - var asyncInfo = new TaskToAsyncOperationWithProgressAdapter(synchronousResult); - return asyncInfo; - } - - #endregion Factory methods for creating IAsyncInfo instances that have already completed synchronously - - - #region Factory methods for creating IAsyncInfo instances that have already completed synchronously with an error - - internal static IAsyncAction CreateFaultedAction(Exception error) - { - if (error == null) - throw new ArgumentNullException(nameof(error)); - - var asyncInfo = new TaskToAsyncActionAdapter(isCanceled: false); - - asyncInfo.DangerousSetError(error); - Debug.Assert(asyncInfo.Status == AsyncStatus.Error); - - return asyncInfo; - } - - - internal static IAsyncActionWithProgress CreateFaultedAction(Exception error) - { - if (error == null) - throw new ArgumentNullException(nameof(error)); - - var asyncInfo = new TaskToAsyncActionWithProgressAdapter(isCanceled: false); - - asyncInfo.DangerousSetError(error); - Debug.Assert(asyncInfo.Status == AsyncStatus.Error); - - return asyncInfo; - } - - - internal static IAsyncOperation CreateFaultedOperation(Exception error) - { - if (error == null) - throw new ArgumentNullException(nameof(error)); - - var asyncInfo = new TaskToAsyncOperationAdapter(default(TResult)); - - asyncInfo.DangerousSetError(error); - Debug.Assert(asyncInfo.Status == AsyncStatus.Error); - - return asyncInfo; - } - - - internal static IAsyncOperationWithProgress CreateFaultedOperation(Exception error) - { - if (error == null) - throw new ArgumentNullException(nameof(error)); - - var asyncInfo = new TaskToAsyncOperationWithProgressAdapter(default(TResult)); - - asyncInfo.DangerousSetError(error); - Debug.Assert(asyncInfo.Status == AsyncStatus.Error); - - return asyncInfo; - } - #endregion Factory methods for creating IAsyncInfo instances that have already completed synchronously with an error - - } // class AsyncInfo -} // namespace diff --git a/src/libraries/System.Runtime.WindowsRuntime/src/System/Runtime/InteropServices/WindowsRuntime/IBufferByteAccess.cs b/src/libraries/System.Runtime.WindowsRuntime/src/System/Runtime/InteropServices/WindowsRuntime/IBufferByteAccess.cs deleted file mode 100644 index 59ec525..0000000 --- a/src/libraries/System.Runtime.WindowsRuntime/src/System/Runtime/InteropServices/WindowsRuntime/IBufferByteAccess.cs +++ /dev/null @@ -1,23 +0,0 @@ -// 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.Security; -using GUID = System.Runtime.InteropServices.GuidAttribute; - -namespace System.Runtime.InteropServices.WindowsRuntime -{ - /// - /// WinRT's IBufferByteAccess interface definition. - /// - [ComImport] - [GUID("905a0fef-bc53-11df-8c49-001e4fc686da")] - [InterfaceType(ComInterfaceType.InterfaceIsIUnknown)] - internal interface IBufferByteAccess - { - // This needs to be a function - MCG doesn't support properties/events for [ComImport] interface yet - IntPtr GetBuffer(); - } // interface IBufferByteAccess -} // namespace - -// IBufferByteAccess.cs diff --git a/src/libraries/System.Runtime.WindowsRuntime/src/System/Runtime/InteropServices/WindowsRuntime/MarshalingHelpers.cs b/src/libraries/System.Runtime.WindowsRuntime/src/System/Runtime/InteropServices/WindowsRuntime/MarshalingHelpers.cs deleted file mode 100644 index 9daa7cf..0000000 --- a/src/libraries/System.Runtime.WindowsRuntime/src/System/Runtime/InteropServices/WindowsRuntime/MarshalingHelpers.cs +++ /dev/null @@ -1,527 +0,0 @@ -// 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; -using System.Collections.Specialized; -using System.ComponentModel; -using System.Diagnostics; -using System.Runtime.CompilerServices; -using System.Security; -using System.Windows.Input; - -using Internal.Runtime.CompilerServices; - -namespace System.Runtime.InteropServices.WindowsRuntime -{ - // Local definition of Windows.UI.Xaml.Interop.INotifyCollectionChangedEventArgs - [ComImport] - [Guid("4cf68d33-e3f2-4964-b85e-945b4f7e2f21")] - [WindowsRuntimeImport] - internal interface INotifyCollectionChangedEventArgs - { - NotifyCollectionChangedAction Action { get; } - IList NewItems { get; } - IList OldItems { get; } - int NewStartingIndex { get; } - int OldStartingIndex { get; } - } - - // Local definition of Windows.UI.Xaml.Data.IPropertyChangedEventArgs - [ComImport] - [Guid("4f33a9a0-5cf4-47a4-b16f-d7faaf17457e")] - [WindowsRuntimeImport] - internal interface IPropertyChangedEventArgs - { - string PropertyName { get; } - } - - // Local definition of Windows.UI.Xaml.Interop.INotifyCollectionChanged - [ComImport] - [Guid("28b167d5-1a31-465b-9b25-d5c3ae686c40")] - [WindowsRuntimeImport] - internal interface INotifyCollectionChanged_WinRT - { - EventRegistrationToken add_CollectionChanged(NotifyCollectionChangedEventHandler value); - void remove_CollectionChanged(EventRegistrationToken token); - } - - // Local definition of Windows.UI.Xaml.Data.INotifyPropertyChanged - [ComImport] - [Guid("cf75d69c-f2f4-486b-b302-bb4c09baebfa")] - [WindowsRuntimeImport] - internal interface INotifyPropertyChanged_WinRT - { - EventRegistrationToken add_PropertyChanged(PropertyChangedEventHandler value); - void remove_PropertyChanged(EventRegistrationToken token); - } - - // Local definition of Windows.UI.Xaml.Input.ICommand - [ComImport] - [Guid("e5af3542-ca67-4081-995b-709dd13792df")] - [WindowsRuntimeImport] - internal interface ICommand_WinRT - { - EventRegistrationToken add_CanExecuteChanged(EventHandler value); - void remove_CanExecuteChanged(EventRegistrationToken token); - bool CanExecute(object parameter); - void Execute(object parameter); - } - - // Local definition of Windows.UI.Xaml.Interop.NotifyCollectionChangedEventHandler - [Guid("ca10b37c-f382-4591-8557-5e24965279b0")] - [WindowsRuntimeImport] - internal delegate void NotifyCollectionChangedEventHandler_WinRT(object sender, NotifyCollectionChangedEventArgs e); - - // Local definition of Windows.UI.Xaml.Data.PropertyChangedEventHandler - [Guid("50f19c16-0a22-4d8e-a089-1ea9951657d2")] - [WindowsRuntimeImport] - internal delegate void PropertyChangedEventHandler_WinRT(object sender, PropertyChangedEventArgs e); - - // Local definition of Windows.UI.Xaml.Interop.INotifyCollectionChangedEventArgsFactory - [ComImport] - [Guid("b30c3e3a-df8d-44a5-9a38-7ac0d08ce63d")] - [WindowsRuntimeImport] - internal interface INotifyCollectionChangedEventArgsFactory - { - // The return type for this function is actually an INotifyCollectionChangedEventArgs* - // but we need to make sure we don't accidentally project our native object back to managed - // when marshalling it to native (which happens when correctly typing the return type as an INotifyCollectionChangedEventArgs). - IntPtr CreateInstanceWithAllParameters(int action, IList? newItems, IList? oldItems, int newIndex, int oldIndex, object? outer, ref object? inner); - } - - // Local definition of Windows.UI.Xaml.Data.INotifyCollectionChangedEventArgsFactory - [ComImport] - [Guid("6dcc9c03-e0c7-4eee-8ea9-37e3406eeb1c")] - [WindowsRuntimeImport] - internal interface IPropertyChangedEventArgsFactory - { - // The return type for this function is actually an IPropertyChangedEventArgs* - // but we need to make sure we don't accidentally project our native object back to managed - // when marshalling it to native (which happens when correctly typing the return type as an IPropertyChangedEventArgs). - IntPtr CreateInstance(string? name, object? outer, ref object? inner); - } - - internal static class NotifyCollectionChangedEventArgsMarshaler - { - private const string WinRTNotifyCollectionChangedEventArgsName = "Windows.UI.Xaml.Interop.NotifyCollectionChangedEventArgs"; - - private static INotifyCollectionChangedEventArgsFactory? s_EventArgsFactory; - - // Extracts properties from a managed NotifyCollectionChangedEventArgs and passes them to - // a VM-implemented helper that creates a WinRT NotifyCollectionChangedEventArgs instance. - // This method is called from IL stubs and needs to have its token stabilized. - internal static IntPtr ConvertToNative(NotifyCollectionChangedEventArgs managedArgs) - { - if (managedArgs == null) - return IntPtr.Zero; - - if (s_EventArgsFactory == null) - { - object? factory = null; - Guid guid = typeof(INotifyCollectionChangedEventArgsFactory).GUID; - int hr = Interop.mincore.RoGetActivationFactory(WinRTNotifyCollectionChangedEventArgsName, ref guid, out factory); - if (hr < 0) - Marshal.ThrowExceptionForHR(hr); - - s_EventArgsFactory = (INotifyCollectionChangedEventArgsFactory)factory; - } - - object? inner = null; - return s_EventArgsFactory.CreateInstanceWithAllParameters((int)managedArgs.Action, managedArgs.NewItems, managedArgs.OldItems, managedArgs.NewStartingIndex, managedArgs.OldStartingIndex, null, ref inner); - } - - // Extracts properties from a WinRT NotifyCollectionChangedEventArgs and creates a new - // managed NotifyCollectionChangedEventArgs instance. - // This method is called from IL stubs and needs to have its token stabilized. - internal static NotifyCollectionChangedEventArgs? ConvertToManaged(IntPtr nativeArgsIP) - { - if (nativeArgsIP == IntPtr.Zero) - return null; - - object obj = WindowsRuntimeMarshal.GetUniqueObjectForIUnknownWithoutUnboxing(nativeArgsIP); - INotifyCollectionChangedEventArgs nativeArgs = (INotifyCollectionChangedEventArgs)obj; - - return CreateNotifyCollectionChangedEventArgs( - nativeArgs.Action, - nativeArgs.NewItems, - nativeArgs.OldItems, - nativeArgs.NewStartingIndex, - nativeArgs.OldStartingIndex); - } - - internal static NotifyCollectionChangedEventArgs CreateNotifyCollectionChangedEventArgs( - NotifyCollectionChangedAction action, IList newItems, IList oldItems, int newStartingIndex, int oldStartingIndex) => - action switch - { - NotifyCollectionChangedAction.Add => new NotifyCollectionChangedEventArgs(action, newItems, newStartingIndex), - NotifyCollectionChangedAction.Remove => new NotifyCollectionChangedEventArgs(action, oldItems, oldStartingIndex), - NotifyCollectionChangedAction.Replace => new NotifyCollectionChangedEventArgs(action, newItems, oldItems, newStartingIndex), - NotifyCollectionChangedAction.Move => new NotifyCollectionChangedEventArgs(action, newItems, newStartingIndex, oldStartingIndex), - NotifyCollectionChangedAction.Reset => new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Reset), - _ => throw new ArgumentException(SR.Format(SR.InvalidAction, action)), - }; - } - - internal static class PropertyChangedEventArgsMarshaler - { - private const string WinRTPropertyChangedEventArgsName = "Windows.UI.Xaml.Data.PropertyChangedEventArgs"; - - private static IPropertyChangedEventArgsFactory? s_pPCEventArgsFactory; - - // Extracts PropertyName from a managed PropertyChangedEventArgs and passes them to - // a VM-implemented helper that creates a WinRT PropertyChangedEventArgs instance. - // This method is called from IL stubs and needs to have its token stabilized. - internal static IntPtr ConvertToNative(PropertyChangedEventArgs managedArgs) - { - if (managedArgs == null) - return IntPtr.Zero; - - if (s_pPCEventArgsFactory == null) - { - object? factory = null; - Guid guid = typeof(IPropertyChangedEventArgsFactory).GUID; - int hr = Interop.mincore.RoGetActivationFactory(WinRTPropertyChangedEventArgsName, ref guid, out factory); - if (hr < 0) - Marshal.ThrowExceptionForHR(hr); - - s_pPCEventArgsFactory = (IPropertyChangedEventArgsFactory)factory; - } - - object? inner = null; - return s_pPCEventArgsFactory.CreateInstance(managedArgs.PropertyName, null, ref inner); - } - - // Extracts properties from a WinRT PropertyChangedEventArgs and creates a new - // managed PropertyChangedEventArgs instance. - // This method is called from IL stubs and needs to have its token stabilized. - internal static PropertyChangedEventArgs? ConvertToManaged(IntPtr nativeArgsIP) - { - if (nativeArgsIP == IntPtr.Zero) - return null; - - object obj = WindowsRuntimeMarshal.GetUniqueObjectForIUnknownWithoutUnboxing(nativeArgsIP); - IPropertyChangedEventArgs nativeArgs = (IPropertyChangedEventArgs)obj; - - return new PropertyChangedEventArgs(nativeArgs.PropertyName); - } - } - - // This is a set of stub methods implementing the support for the managed INotifyCollectionChanged - // interface on WinRT objects that support the WinRT INotifyCollectionChanged. Used by the interop - // mashaling infrastructure. - internal sealed class NotifyCollectionChangedToManagedAdapter - { - private NotifyCollectionChangedToManagedAdapter() - { - Debug.Fail("This class is never instantiated"); - } - - internal event NotifyCollectionChangedEventHandler CollectionChanged - { - // void CollectionChanged.add(NotifyCollectionChangedEventHandler) - add - { - INotifyCollectionChanged_WinRT _this = Unsafe.As(this); - - // call the WinRT eventing support in mscorlib to subscribe the event - Func addMethod = - new Func(_this.add_CollectionChanged); - Action removeMethod = - new Action(_this.remove_CollectionChanged); - - WindowsRuntimeMarshal.AddEventHandler(addMethod, removeMethod, value); - } - - // void CollectionChanged.remove(NotifyCollectionChangedEventHandler) - remove - { - INotifyCollectionChanged_WinRT _this = Unsafe.As(this); - - // call the WinRT eventing support in mscorlib to unsubscribe the event - Action removeMethod = - new Action(_this.remove_CollectionChanged); - - WindowsRuntimeMarshal.RemoveEventHandler(removeMethod, value); - } - } - } - - // This is a set of stub methods implementing the support for the WinRT INotifyCollectionChanged - // interface on managed objects that support the managed INotifyCollectionChanged. Used by the interop - // mashaling infrastructure. - internal sealed class NotifyCollectionChangedToWinRTAdapter - { - private NotifyCollectionChangedToWinRTAdapter() - { - Debug.Fail("This class is never instantiated"); - } - - // An instance field typed as EventRegistrationTokenTable is injected into managed classed by the compiler when compiling for /t:winmdobj. - // Since here the class can be an arbitrary implementation of INotifyCollectionChanged, we have to keep the EventRegistrationTokenTable's - // separately, associated with the implementations using ConditionalWeakTable. - private static readonly ConditionalWeakTable> s_weakTable = - new ConditionalWeakTable>(); - - // EventRegistrationToken CollectionChanged.add(NotifyCollectionChangedEventHandler value) - internal EventRegistrationToken add_CollectionChanged(NotifyCollectionChangedEventHandler value) - { - INotifyCollectionChanged _this = Unsafe.As(this); - EventRegistrationTokenTable table = s_weakTable.GetOrCreateValue(_this); - - EventRegistrationToken token = table.AddEventHandler(value); - _this.CollectionChanged += value; - - return token; - } - - // void CollectionChanged.remove(EventRegistrationToken token) - internal void remove_CollectionChanged(EventRegistrationToken token) - { - INotifyCollectionChanged _this = Unsafe.As(this); - EventRegistrationTokenTable table = s_weakTable.GetOrCreateValue(_this); - - if (table.RemoveEventHandler(token, out NotifyCollectionChangedEventHandler? handler)) - { - _this.CollectionChanged -= handler; - } - } - } - - // This is a set of stub methods implementing the support for the managed INotifyPropertyChanged - // interface on WinRT objects that support the WinRT INotifyPropertyChanged. Used by the interop - // mashaling infrastructure. - internal sealed class NotifyPropertyChangedToManagedAdapter - { - private NotifyPropertyChangedToManagedAdapter() - { - Debug.Fail("This class is never instantiated"); - } - - internal event PropertyChangedEventHandler PropertyChanged - { - // void PropertyChanged.add(PropertyChangedEventHandler) - add - { - INotifyPropertyChanged_WinRT _this = Unsafe.As(this); - - // call the WinRT eventing support in mscorlib to subscribe the event - Func addMethod = - new Func(_this.add_PropertyChanged); - Action removeMethod = - new Action(_this.remove_PropertyChanged); - - WindowsRuntimeMarshal.AddEventHandler(addMethod, removeMethod, value); - } - - // void PropertyChanged.remove(PropertyChangedEventHandler) - remove - { - INotifyPropertyChanged_WinRT _this = Unsafe.As(this); - - // call the WinRT eventing support in mscorlib to unsubscribe the event - Action removeMethod = - new Action(_this.remove_PropertyChanged); - - WindowsRuntimeMarshal.RemoveEventHandler(removeMethod, value); - } - } - } - - // This is a set of stub methods implementing the support for the WinRT INotifyPropertyChanged - // interface on managed objects that support the managed INotifyPropertyChanged. Used by the interop - // mashaling infrastructure. - internal sealed class NotifyPropertyChangedToWinRTAdapter - { - private NotifyPropertyChangedToWinRTAdapter() - { - Debug.Fail("This class is never instantiated"); - } - - // An instance field typed as EventRegistrationTokenTable is injected into managed classed by the compiler when compiling for /t:winmdobj. - // Since here the class can be an arbitrary implementation of INotifyCollectionChanged, we have to keep the EventRegistrationTokenTable's - // separately, associated with the implementations using ConditionalWeakTable. - private static readonly ConditionalWeakTable> s_weakTable = - new ConditionalWeakTable>(); - - // EventRegistrationToken PropertyChanged.add(PropertyChangedEventHandler value) - internal EventRegistrationToken add_PropertyChanged(PropertyChangedEventHandler value) - { - INotifyPropertyChanged _this = Unsafe.As(this); - EventRegistrationTokenTable table = s_weakTable.GetOrCreateValue(_this); - - EventRegistrationToken token = table.AddEventHandler(value); - _this.PropertyChanged += value; - - return token; - } - - // void PropertyChanged.remove(EventRegistrationToken token) - internal void remove_PropertyChanged(EventRegistrationToken token) - { - INotifyPropertyChanged _this = Unsafe.As(this); - EventRegistrationTokenTable table = s_weakTable.GetOrCreateValue(_this); - - if (table.RemoveEventHandler(token, out PropertyChangedEventHandler? handler)) - { - _this.PropertyChanged -= handler; - } - } - } - - // This is a set of stub methods implementing the support for the managed ICommand - // interface on WinRT objects that support the WinRT ICommand_WinRT. - // Used by the interop mashaling infrastructure. - // Instances of this are really RCWs of ICommand_WinRT (not ICommandToManagedAdapter or any ICommand). - internal sealed class ICommandToManagedAdapter /*: System.Windows.Input.ICommand*/ - { - private static readonly ConditionalWeakTable> s_weakTable = - new ConditionalWeakTable>(); - - private ICommandToManagedAdapter() - { - Debug.Fail("This class is never instantiated"); - } - - private event EventHandler CanExecuteChanged - { - // void CanExecuteChanged.add(EventHandler) - add - { - ICommand_WinRT _this = Unsafe.As(this); - - // call the WinRT eventing support in mscorlib to subscribe the event - Func, EventRegistrationToken> addMethod = - new Func, EventRegistrationToken>(_this.add_CanExecuteChanged); - Action removeMethod = - new Action(_this.remove_CanExecuteChanged); - - // value is of type System.EventHandler, but ICommand_WinRT (and thus WindowsRuntimeMarshal.AddEventHandler) - // expects an instance of EventHandler. So we get/create a wrapper of value here. - EventHandler handler_WinRT = s_weakTable.GetValue(value, ICommandAdapterHelpers.CreateWrapperHandler); - WindowsRuntimeMarshal.AddEventHandler>(addMethod, removeMethod, handler_WinRT); - } - - // void CanExecuteChanged.remove(EventHandler) - remove - { - ICommand_WinRT _this = Unsafe.As(this); - - // call the WinRT eventing support in mscorlib to unsubscribe the event - Action removeMethod = - new Action(_this.remove_CanExecuteChanged); - - // value is of type System.EventHandler, but ICommand_WinRT (and thus WindowsRuntimeMarshal.RemoveEventHandler) - // expects an instance of EventHandler. So we get/create a wrapper of value here. - - // Also we do a value check rather than an instance check to ensure that different instances of the same delegates are treated equal. - EventHandler handler_WinRT = ICommandAdapterHelpers.GetValueFromEquivalentKey(s_weakTable, value, ICommandAdapterHelpers.CreateWrapperHandler); - WindowsRuntimeMarshal.RemoveEventHandler>(removeMethod, handler_WinRT); - } - } - - private bool CanExecute(object parameter) - { - ICommand_WinRT _this = Unsafe.As(this); - return _this.CanExecute(parameter); - } - - private void Execute(object parameter) - { - ICommand_WinRT _this = Unsafe.As(this); - _this.Execute(parameter); - } - } - - // This is a set of stub methods implementing the support for the WinRT ICommand_WinRT - // interface on managed objects that support the managed ICommand interface. - // Used by the interop mashaling infrastructure. - // Instances of this are really CCWs of ICommand (not ICommandToWinRTAdapter or any ICommand_WinRT). - internal sealed class ICommandToWinRTAdapter /*: ICommand_WinRT*/ - { - private ICommandToWinRTAdapter() - { - Debug.Fail("This class is never instantiated"); - } - - // An instance field typed as EventRegistrationTokenTable is injected into managed classed by the compiler when compiling for /t:winmdobj. - // Since here the class can be an arbitrary implementation of ICommand, we have to keep the EventRegistrationTokenTable's - // separately, associated with the implementations using ConditionalWeakTable. - private static readonly ConditionalWeakTable> s_weakTable = - new ConditionalWeakTable>(); - - // EventRegistrationToken PropertyChanged.add(EventHandler value) - private EventRegistrationToken add_CanExecuteChanged(EventHandler value) - { - ICommand _this = Unsafe.As(this); - EventRegistrationTokenTable table = s_weakTable.GetOrCreateValue(_this); - - EventHandler handler = ICommandAdapterHelpers.CreateWrapperHandler(value); - EventRegistrationToken token = table.AddEventHandler(handler); - _this.CanExecuteChanged += handler; - - return token; - } - - // void PropertyChanged.remove(EventRegistrationToken token) - private void remove_CanExecuteChanged(EventRegistrationToken token) - { - ICommand _this = Unsafe.As(this); - EventRegistrationTokenTable table = s_weakTable.GetOrCreateValue(_this); - - if (table.RemoveEventHandler(token, out EventHandler? handler)) - { - _this.CanExecuteChanged -= handler; - } - } - - private bool CanExecute(object parameter) - { - ICommand _this = Unsafe.As(this); - return _this.CanExecute(parameter); - } - - private void Execute(object parameter) - { - ICommand _this = Unsafe.As(this); - _this.Execute(parameter); - } - } - - // A couple of ICommand adapter helpers need to be transparent, and so are in their own type - internal static class ICommandAdapterHelpers - { - internal static EventHandler CreateWrapperHandler(EventHandler handler) - { - // Check whether it is a round-tripping case i.e. the sender is of the type eventArgs, - // If so we use it else we pass EventArgs.Empty - return (object? sender, object e) => - { - EventArgs? eventArgs = e as EventArgs; - handler(sender, (eventArgs == null ? System.EventArgs.Empty : eventArgs)); - }; - } - - internal static EventHandler CreateWrapperHandler(EventHandler handler) - { - return (object? sender, EventArgs e) => handler(sender, e); - } - - internal static EventHandler GetValueFromEquivalentKey( - ConditionalWeakTable> table, - EventHandler key, - ConditionalWeakTable>.CreateValueCallback callback) - { - foreach (KeyValuePair> item in table) - { - if (object.Equals(item.Key, key)) - return item.Value; - } - - EventHandler value = callback(key); - table.Add(key, value); - return value; - } - } -} diff --git a/src/libraries/System.Runtime.WindowsRuntime/src/System/Runtime/InteropServices/WindowsRuntime/WindowsRuntimeBuffer.cs b/src/libraries/System.Runtime.WindowsRuntime/src/System/Runtime/InteropServices/WindowsRuntime/WindowsRuntimeBuffer.cs deleted file mode 100644 index 04847a7..0000000 --- a/src/libraries/System.Runtime.WindowsRuntime/src/System/Runtime/InteropServices/WindowsRuntime/WindowsRuntimeBuffer.cs +++ /dev/null @@ -1,308 +0,0 @@ -// 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 System.Diagnostics.CodeAnalysis; -using System.Runtime.CompilerServices; -using System.Runtime.InteropServices; -using System.Security; -using System.Threading; -using Windows.Foundation; -using Windows.Storage.Streams; - -namespace System.Runtime.InteropServices.WindowsRuntime -{ - /// - /// Contains an implementation of the WinRT IBuffer interface that conforms to all requirements on classes that implement that interface, - /// such as implementing additional interfaces. - /// - public sealed class WindowsRuntimeBuffer : IBuffer, IBufferByteAccess, IMarshal, IAgileObject - { - #region Constants - - private const string WinTypesDLL = "WinTypes.dll"; - - private enum MSHCTX : int { Local = 0, NoSharedMem = 1, DifferentMachine = 2, InProc = 3, CrossCtx = 4 } - private enum MSHLFLAGS : int { Normal = 0, TableStrong = 1, TableWeak = 2, NoPing = 4 } - - - #endregion Constants - - - #region Static factory methods - - [CLSCompliant(false)] - public static IBuffer Create(int capacity) - { - if (capacity < 0) throw new ArgumentOutOfRangeException(nameof(capacity)); - - return new WindowsRuntimeBuffer(capacity); - } - - - [CLSCompliant(false)] - public static IBuffer Create(byte[] data, int offset, int length, int capacity) - { - if (data == null) throw new ArgumentNullException(nameof(data)); - if (offset < 0) throw new ArgumentOutOfRangeException(nameof(offset)); - if (length < 0) throw new ArgumentOutOfRangeException(nameof(length)); - if (capacity < 0) throw new ArgumentOutOfRangeException(nameof(capacity)); - if (data.Length - offset < length) throw new ArgumentException(SR.Argument_InsufficientArrayElementsAfterOffset); - if (data.Length - offset < capacity) throw new ArgumentException(SR.Argument_InsufficientArrayElementsAfterOffset); - if (capacity < length) throw new ArgumentException(SR.Argument_InsufficientBufferCapacity); - - byte[] underlyingData = new byte[capacity]; - Buffer.BlockCopy(data, offset, underlyingData, 0, length); - return new WindowsRuntimeBuffer(underlyingData, 0, length, capacity); - } - - #endregion Static factory methods - - - #region Static fields and helpers - - // This object handles IMarshal calls for us: - [ThreadStatic] - private static IMarshal? t_winRtMarshalProxy = null; - - private static void EnsureHasMarshalProxy() - { - if (t_winRtMarshalProxy != null) - return; - - try - { - IMarshal proxy; - int hr = Interop.mincore.RoGetBufferMarshaler(out proxy); - t_winRtMarshalProxy = proxy; - - if (hr != __HResults.S_OK) - { - Exception ex = new Exception(string.Format("{0} ({1}!RoGetBufferMarshaler)", SR.WinRtCOM_Error, WinTypesDLL)); - ex.HResult = hr; - throw ex; - } - - if (proxy == null) - throw new NullReferenceException(string.Format("{0} ({1}!RoGetBufferMarshaler)", SR.WinRtCOM_Error, WinTypesDLL)); - } - catch (DllNotFoundException ex) - { - throw new NotImplementedException(SR.Format(SR.NotImplemented_NativeRoutineNotFound, - string.Format("{0}!RoGetBufferMarshaler", WinTypesDLL)), - ex); - } - } - - #endregion Static fields and helpers - - - #region Fields - - private readonly byte[] _data; - private readonly int _dataStartOffs = 0; - private int _usefulDataLength = 0; - private readonly int _maxDataCapacity = 0; - private GCHandle _pinHandle; - - // Pointer to data[dataStartOffs] when data is pinned: - private IntPtr _dataPtr = IntPtr.Zero; - - #endregion Fields - - - #region Constructors - - internal WindowsRuntimeBuffer(int capacity) - { - if (capacity < 0) - throw new ArgumentOutOfRangeException(nameof(capacity)); - - _data = new byte[capacity]; - _dataStartOffs = 0; - _usefulDataLength = 0; - _maxDataCapacity = capacity; - _dataPtr = IntPtr.Zero; - } - - - internal WindowsRuntimeBuffer(byte[] data, int offset, int length, int capacity) - { - if (data == null) throw new ArgumentNullException(nameof(data)); - if (offset < 0) throw new ArgumentOutOfRangeException(nameof(offset)); - if (length < 0) throw new ArgumentOutOfRangeException(nameof(length)); - if (capacity < 0) throw new ArgumentOutOfRangeException(nameof(capacity)); - if (data.Length - offset < length) throw new ArgumentException(SR.Argument_InsufficientArrayElementsAfterOffset); - if (data.Length - offset < capacity) throw new ArgumentException(SR.Argument_InsufficientArrayElementsAfterOffset); - if (capacity < length) throw new ArgumentException(SR.Argument_InsufficientBufferCapacity); - - _data = data; - _dataStartOffs = offset; - _usefulDataLength = length; - _maxDataCapacity = capacity; - _dataPtr = IntPtr.Zero; - } - - #endregion Constructors - - - #region Helpers - - internal void GetUnderlyingData([NotNull] out byte[]? underlyingDataArray, out int underlyingDataArrayStartOffset) - { - underlyingDataArray = _data!; - underlyingDataArrayStartOffset = _dataStartOffs; - } - - - private unsafe byte* PinUnderlyingData() - { - GCHandle gcHandle = default(GCHandle); - bool ptrWasStored = false; - IntPtr buffPtr; - - try { } - finally - { - try - { - // Pin the data array: - gcHandle = GCHandle.Alloc(_data, GCHandleType.Pinned); - buffPtr = gcHandle.AddrOfPinnedObject() + _dataStartOffs; - - // Store the pin IFF it has not been assigned: - ptrWasStored = (Interlocked.CompareExchange(ref _dataPtr, buffPtr, IntPtr.Zero) == IntPtr.Zero); - } - finally - { - if (!ptrWasStored) - { - // There is a race with another thread also trying to create a pin and they were first - // in assigning to data pin. That's ok, just give it up. - // Unpin again (the pin from the other thread remains): - gcHandle.Free(); - } - else - { - if (_pinHandle.IsAllocated) - _pinHandle.Free(); - - // Make sure we keep track of the handle - _pinHandle = gcHandle; - } - } - } - - // Ok, now all is good: - return (byte*)buffPtr; - } - - ~WindowsRuntimeBuffer() - { - if (_pinHandle.IsAllocated) - _pinHandle.Free(); - } - - #endregion Helpers - - - #region Implementation of Windows.Foundation.IBuffer - - uint IBuffer.Capacity - { - get { return unchecked((uint)_maxDataCapacity); } - } - - - uint IBuffer.Length - { - get - { - return unchecked((uint)_usefulDataLength); - } - - set - { - if (value > ((IBuffer)this).Capacity) - { - ArgumentOutOfRangeException ex = new ArgumentOutOfRangeException(nameof(value), SR.Argument_BufferLengthExceedsCapacity); - ex.HResult = __HResults.E_BOUNDS; - throw ex; - } - - // Capacity is ensured to not exceed Int32.MaxValue, so Length is within this limit and this cast is safe: - Debug.Assert(((IBuffer)this).Capacity <= int.MaxValue); - _usefulDataLength = unchecked((int)value); - } - } - - #endregion Implementation of Windows.Foundation.IBuffer - - - #region Implementation of IBufferByteAccess - - unsafe IntPtr IBufferByteAccess.GetBuffer() - { - // Get pin handle: - IntPtr buffPtr = Volatile.Read(ref _dataPtr); - - // If we are already pinned, return the pointer and have a nice day: - if (buffPtr != IntPtr.Zero) - return buffPtr; - - // Ok, we are not yet pinned. Let's do it. - return new IntPtr(PinUnderlyingData()); - } - - #endregion Implementation of IBufferByteAccess - - - #region Implementation of IMarshal - - void IMarshal.DisconnectObject(uint dwReserved) - { - EnsureHasMarshalProxy(); - t_winRtMarshalProxy!.DisconnectObject(dwReserved); - } - - - void IMarshal.GetMarshalSizeMax(ref Guid riid, IntPtr pv, uint dwDestContext, IntPtr pvDestContext, uint mshlflags, out uint pSize) - { - EnsureHasMarshalProxy(); - t_winRtMarshalProxy!.GetMarshalSizeMax(ref riid, pv, dwDestContext, pvDestContext, mshlflags, out pSize); - } - - - void IMarshal.GetUnmarshalClass(ref Guid riid, IntPtr pv, uint dwDestContext, IntPtr pvDestContext, uint mshlFlags, out Guid pCid) - { - EnsureHasMarshalProxy(); - t_winRtMarshalProxy!.GetUnmarshalClass(ref riid, pv, dwDestContext, pvDestContext, mshlFlags, out pCid); - } - - - void IMarshal.MarshalInterface(IntPtr pStm, ref Guid riid, IntPtr pv, uint dwDestContext, IntPtr pvDestContext, uint mshlflags) - { - EnsureHasMarshalProxy(); - t_winRtMarshalProxy!.MarshalInterface(pStm, ref riid, pv, dwDestContext, pvDestContext, mshlflags); - } - - - void IMarshal.ReleaseMarshalData(IntPtr pStm) - { - EnsureHasMarshalProxy(); - t_winRtMarshalProxy!.ReleaseMarshalData(pStm); - } - - - void IMarshal.UnmarshalInterface(IntPtr pStm, ref Guid riid, out IntPtr ppv) - { - EnsureHasMarshalProxy(); - t_winRtMarshalProxy!.UnmarshalInterface(pStm, ref riid, out ppv); - } - #endregion Implementation of IMarshal - - } // class WindowsRuntimeBuffer -} // namespace - -// WindowsRuntimeBuffer.cs diff --git a/src/libraries/System.Runtime.WindowsRuntime/src/System/Runtime/InteropServices/WindowsRuntime/WindowsRuntimeBufferExtensions.cs b/src/libraries/System.Runtime.WindowsRuntime/src/System/Runtime/InteropServices/WindowsRuntime/WindowsRuntimeBufferExtensions.cs deleted file mode 100644 index 35a4bae..0000000 --- a/src/libraries/System.Runtime.WindowsRuntime/src/System/Runtime/InteropServices/WindowsRuntime/WindowsRuntimeBufferExtensions.cs +++ /dev/null @@ -1,515 +0,0 @@ -// 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 System.Diagnostics.CodeAnalysis; -using System.IO; -using Windows.Foundation; -using Windows.Storage.Streams; - -namespace System.Runtime.InteropServices.WindowsRuntime -{ - /// - /// Contains extension methods that expose operations on WinRT Windows.Foundation.IBuffer. - /// - public static class WindowsRuntimeBufferExtensions - { - #region (Byte []).AsBuffer extensions - - [CLSCompliant(false)] - public static IBuffer AsBuffer(this byte[] source) - { - if (source == null) throw new ArgumentNullException(nameof(source)); - - return AsBuffer(source, 0, source.Length, source.Length); - } - - - [CLSCompliant(false)] - public static IBuffer AsBuffer(this byte[] source, int offset, int length) - { - if (source == null) throw new ArgumentNullException(nameof(source)); - if (offset < 0) throw new ArgumentOutOfRangeException(nameof(offset)); - if (length < 0) throw new ArgumentOutOfRangeException(nameof(length)); - if (source.Length - offset < length) throw new ArgumentException(SR.Argument_InsufficientArrayElementsAfterOffset); - - return AsBuffer(source, offset, length, length); - } - - - [CLSCompliant(false)] - public static IBuffer AsBuffer(this byte[] source, int offset, int length, int capacity) - { - if (source == null) throw new ArgumentNullException(nameof(source)); - if (offset < 0) throw new ArgumentOutOfRangeException(nameof(offset)); - if (length < 0) throw new ArgumentOutOfRangeException(nameof(length)); - if (capacity < 0) throw new ArgumentOutOfRangeException(nameof(capacity)); - if (source.Length - offset < length) throw new ArgumentException(SR.Argument_InsufficientArrayElementsAfterOffset); - if (source.Length - offset < capacity) throw new ArgumentException(SR.Argument_InsufficientArrayElementsAfterOffset); - if (capacity < length) throw new ArgumentException(SR.Argument_InsufficientBufferCapacity); - - return new WindowsRuntimeBuffer(source, offset, length, capacity); - } - - #endregion (Byte []).AsBuffer extensions - - - #region (Byte []).CopyTo extensions for copying to an (IBuffer) - - /// - /// Copies the contents of source to destination starting at offset 0. - /// This method does NOT update destination.Length. - /// - /// Array to copy data from. - /// The buffer to copy to. - [CLSCompliant(false)] - public static void CopyTo(this byte[] source, IBuffer destination) - { - if (source == null) throw new ArgumentNullException(nameof(source)); - if (destination == null) throw new ArgumentNullException(nameof(destination)); - - CopyTo(source, 0, destination, 0, source.Length); - } - - - /// - /// Copies count bytes from source starting at offset sourceIndex - /// to destination starting at destinationIndex. - /// This method does NOT update destination.Length. - /// - /// Array to copy data from. - /// Position in the array from where to start copying. - /// The buffer to copy to. - /// Position in the buffer to where to start copying. - /// The number of bytes to copy. - [CLSCompliant(false)] - public static void CopyTo(this byte[] source, int sourceIndex, IBuffer destination, uint destinationIndex, int count) - { - if (source == null) throw new ArgumentNullException(nameof(source)); - if (destination == null) throw new ArgumentNullException(nameof(destination)); - if (count < 0) throw new ArgumentOutOfRangeException(nameof(count)); - if (sourceIndex < 0) throw new ArgumentOutOfRangeException(nameof(sourceIndex)); - if (source.Length <= sourceIndex) throw new ArgumentException(SR.Argument_IndexOutOfArrayBounds, nameof(sourceIndex)); - if (source.Length - sourceIndex < count) throw new ArgumentException(SR.Argument_InsufficientArrayElementsAfterOffset); - if (destination.Capacity - destinationIndex < count) throw new ArgumentException(SR.Argument_InsufficientSpaceInTargetBuffer); - - // If destination is backed by a managed array, use the array instead of the pointer as it does not require pinning: - byte[]? destDataArr; - int destDataOffs; - if (destination.TryGetUnderlyingData(out destDataArr, out destDataOffs)) - { - Buffer.BlockCopy(source, sourceIndex, destDataArr, (int)(destDataOffs + destinationIndex), count); - return; - } - - IntPtr destPtr = destination.GetPointerAtOffset(destinationIndex); - Marshal.Copy(source, sourceIndex, destPtr, count); - } - - #endregion (Byte []).CopyTo extensions for copying to an (IBuffer) - - - #region (IBuffer).ToArray extensions for copying to a new (Byte []) - - [CLSCompliant(false)] - public static byte[] ToArray(this IBuffer source) - { - if (source == null) throw new ArgumentNullException(nameof(source)); - - return ToArray(source, 0, checked((int)source.Length)); - } - - - [CLSCompliant(false)] - public static byte[] ToArray(this IBuffer source, uint sourceIndex, int count) - { - if (source == null) throw new ArgumentNullException(nameof(source)); - if (count < 0) throw new ArgumentOutOfRangeException(nameof(count)); - if (source.Capacity <= sourceIndex) throw new ArgumentException(SR.Argument_BufferIndexExceedsCapacity); - if (source.Capacity - sourceIndex < count) throw new ArgumentException(SR.Argument_InsufficientSpaceInSourceBuffer); - - if (count == 0) - return Array.Empty(); - - byte[] destination = new byte[count]; - source.CopyTo(sourceIndex, destination, 0, count); - return destination; - } - - #endregion (IBuffer).ToArray extensions for copying to a new (Byte []) - - - #region (IBuffer).CopyTo extensions for copying to a (Byte []) - - [CLSCompliant(false)] - public static void CopyTo(this IBuffer source, byte[] destination) - { - if (source == null) throw new ArgumentNullException(nameof(source)); - if (destination == null) throw new ArgumentNullException(nameof(destination)); - - CopyTo(source, 0, destination, 0, checked((int)source.Length)); - } - - - [CLSCompliant(false)] - public static void CopyTo(this IBuffer source, uint sourceIndex, byte[] destination, int destinationIndex, int count) - { - if (source == null) throw new ArgumentNullException(nameof(source)); - if (destination == null) throw new ArgumentNullException(nameof(destination)); - if (count < 0) throw new ArgumentOutOfRangeException(nameof(count)); - if (destinationIndex < 0) throw new ArgumentOutOfRangeException(nameof(destinationIndex)); - if (source.Capacity <= sourceIndex) throw new ArgumentException(SR.Argument_BufferIndexExceedsCapacity); - if (source.Capacity - sourceIndex < count) throw new ArgumentException(SR.Argument_InsufficientSpaceInSourceBuffer); - if (destination.Length <= destinationIndex) throw new ArgumentException(SR.Argument_IndexOutOfArrayBounds); - if (destination.Length - destinationIndex < count) throw new ArgumentException(SR.Argument_InsufficientArrayElementsAfterOffset); - - // If source is backed by a managed array, use the array instead of the pointer as it does not require pinning: - byte[]? srcDataArr; - int srcDataOffs; - if (source.TryGetUnderlyingData(out srcDataArr, out srcDataOffs)) - { - Buffer.BlockCopy(srcDataArr, (int)(srcDataOffs + sourceIndex), destination, destinationIndex, count); - return; - } - - IntPtr srcPtr = source.GetPointerAtOffset(sourceIndex); - Marshal.Copy(srcPtr, destination, destinationIndex, count); - } - - #endregion (IBuffer).CopyTo extensions for copying to a (Byte []) - - - #region (IBuffer).CopyTo extensions for copying to an (IBuffer) - - [CLSCompliant(false)] - public static void CopyTo(this IBuffer source, IBuffer destination) - { - if (source == null) throw new ArgumentNullException(nameof(source)); - if (destination == null) throw new ArgumentNullException(nameof(destination)); - - CopyTo(source, 0, destination, 0, source.Length); - } - - - [CLSCompliant(false)] - public static void CopyTo(this IBuffer source, uint sourceIndex, IBuffer destination, uint destinationIndex, uint count) - { - if (source == null) throw new ArgumentNullException(nameof(source)); - if (destination == null) throw new ArgumentNullException(nameof(destination)); - if (source.Capacity <= sourceIndex) throw new ArgumentException(SR.Argument_BufferIndexExceedsCapacity); - if (source.Capacity - sourceIndex < count) throw new ArgumentException(SR.Argument_InsufficientSpaceInSourceBuffer); - if (destination.Capacity <= destinationIndex) throw new ArgumentException(SR.Argument_BufferIndexExceedsCapacity); - if (destination.Capacity - destinationIndex < count) throw new ArgumentException(SR.Argument_InsufficientSpaceInTargetBuffer); - - // If source are destination are backed by managed arrays, use the arrays instead of the pointers as it does not require pinning: - byte[]? srcDataArr, destDataArr; - int srcDataOffs, destDataOffs; - - bool srcIsManaged = source.TryGetUnderlyingData(out srcDataArr, out srcDataOffs); - bool destIsManaged = destination.TryGetUnderlyingData(out destDataArr, out destDataOffs); - - if (srcIsManaged && destIsManaged) - { - Debug.Assert(count <= int.MaxValue); - Debug.Assert(sourceIndex <= int.MaxValue); - Debug.Assert(destinationIndex <= int.MaxValue); - - Buffer.BlockCopy(srcDataArr!, srcDataOffs + (int)sourceIndex, destDataArr!, destDataOffs + (int)destinationIndex, (int)count); - return; - } - - IntPtr srcPtr, destPtr; - - if (srcIsManaged) - { - Debug.Assert(count <= int.MaxValue); - Debug.Assert(sourceIndex <= int.MaxValue); - - destPtr = destination.GetPointerAtOffset(destinationIndex); - Marshal.Copy(srcDataArr!, srcDataOffs + (int)sourceIndex, destPtr, (int)count); - return; - } - - if (destIsManaged) - { - Debug.Assert(count <= int.MaxValue); - Debug.Assert(destinationIndex <= int.MaxValue); - - srcPtr = source.GetPointerAtOffset(sourceIndex); - Marshal.Copy(srcPtr, destDataArr!, destDataOffs + (int)destinationIndex, (int)count); - return; - } - - srcPtr = source.GetPointerAtOffset(sourceIndex); - destPtr = destination.GetPointerAtOffset(destinationIndex); - MemCopy(srcPtr, destPtr, count); - } - - #endregion (IBuffer).CopyTo extensions for copying to an (IBuffer) - - - #region Access to underlying array optimised for IBuffers backed by managed arrays (to avoid pinning) - - /// - /// If the specified IBuffer is backed by a managed array, this method will return true and - /// set underlyingDataArray to refer to that array - /// and underlyingDataArrayStartOffset to the value at which the buffer data begins in that array. - /// If the specified IBuffer is not backed by a managed array, this method will return false. - /// This method is required by managed APIs that wish to use the buffer's data with other managed APIs that use - /// arrays without a need for a memory copy. - /// - /// An IBuffer. - /// Will be set to the data array backing buffer or to null. - /// Will be set to the start offset of the buffer data in the backing array - /// or to -1. - /// Whether the IBuffer is backed by a managed byte array. - internal static bool TryGetUnderlyingData(this IBuffer buffer, [NotNullWhen(true)] out byte[]? underlyingDataArray, out int underlyingDataArrayStartOffset) - { - if (buffer == null) - throw new ArgumentNullException(nameof(buffer)); - - WindowsRuntimeBuffer? winRtBuffer = buffer as WindowsRuntimeBuffer; - if (winRtBuffer == null) - { - underlyingDataArray = null; - underlyingDataArrayStartOffset = -1; - return false; - } - - winRtBuffer.GetUnderlyingData(out underlyingDataArray, out underlyingDataArrayStartOffset); - return true; - } - - - /// - /// Checks if the underlying memory backing two IBuffer instances is actually the same memory. - /// When applied to IBuffer instances backed by managed arrays this method is preferable to a naive comparison - /// (such as ((IBufferByteAccess) buffer).Buffer == ((IBufferByteAccess) otherBuffer).Buffer) because it avoids - /// pinning the backing array which would be necessary if a direct memory pointer was obtained. - /// - /// An IBuffer instance. - /// An IBuffer instance or null. - /// true if the underlying Buffer memory pointer is the same for both specified - /// IBuffer instances (i.e. if they are backed by the same memory); false otherwise. - [CLSCompliant(false)] - public static bool IsSameData(this IBuffer buffer, IBuffer? otherBuffer) - { - if (buffer == null) - throw new ArgumentNullException(nameof(buffer)); - - if (otherBuffer == null) - return false; - - if (buffer == otherBuffer) - return true; - - byte[]? thisDataArr, otherDataArr; - int thisDataOffs, otherDataOffs; - - bool thisIsManaged = buffer.TryGetUnderlyingData(out thisDataArr, out thisDataOffs); - bool otherIsManaged = otherBuffer.TryGetUnderlyingData(out otherDataArr, out otherDataOffs); - - if (thisIsManaged != otherIsManaged) - return false; - - if (thisIsManaged) - return (thisDataArr == otherDataArr) && (thisDataOffs == otherDataOffs); - - IBufferByteAccess thisBuff = (IBufferByteAccess)buffer; - IBufferByteAccess otherBuff = (IBufferByteAccess)otherBuffer; - - unsafe - { - return (thisBuff.GetBuffer() == otherBuff.GetBuffer()); - } - } - - #endregion Access to underlying array optimised for IBuffers backed by managed arrays (to avoid pinning) - - - #region Extensions for co-operation with memory streams (share mem stream data; expose data as managed/unmanaged mem stream) - /// - /// Creates a new IBuffer instance backed by the same memory as is backing the specified MemoryStream. - /// The MemoryStream may re-sized in future, as a result the stream will be backed by a different memory region. - /// In such case, the buffer created by this method will remain backed by the memory behind the stream at the time the buffer was created.
- /// This method can throw an ObjectDisposedException if the specified stream is closed.
- /// This method can throw an UnauthorizedAccessException if the specified stream cannot expose its underlying memory buffer. - ///
- /// A memory stream to share the data memory with the buffer being created. - /// A new IBuffer backed by the same memory as this specified stream. - // The naming inconsistency with (Byte []).AsBuffer is intentional: as this extension method will appear on - // MemoryStream, consistency with method names on MemoryStream is more important. There we already have an API - // called GetBuffer which returns the underlying array. - [CLSCompliant(false)] - public static IBuffer GetWindowsRuntimeBuffer(this MemoryStream underlyingStream) - { - if (underlyingStream == null) - throw new ArgumentNullException(nameof(underlyingStream)); - - ArraySegment streamData; - if (!underlyingStream.TryGetBuffer(out streamData)) - { - throw new UnauthorizedAccessException(SR.UnauthorizedAccess_InternalBuffer); - } - return new WindowsRuntimeBuffer(streamData.Array!, (int)streamData.Offset, (int)underlyingStream.Length, underlyingStream.Capacity); - } - - - /// - /// Creates a new IBuffer instance backed by the same memory as is backing the specified MemoryStream. - /// The MemoryStream may re-sized in future, as a result the stream will be backed by a different memory region. - /// In such case buffer created by this method will remain backed by the memory behind the stream at the time the buffer was created.
- /// This method can throw an ObjectDisposedException if the specified stream is closed.
- /// This method can throw an UnauthorizedAccessException if the specified stream cannot expose its underlying memory buffer. - /// The created buffer begins at position positionInStream in the stream and extends over up to length bytes. - /// If the stream has less than length bytes after the specified starting position, the created buffer covers only as many - /// bytes as available in the stream. In either case, the Length and the Capacity properties of the created - /// buffer are set accordingly: Capacity - number of bytes between positionInStream and the stream capacity end, - /// but not more than length; Length - number of bytes between positionInStream and the stream - /// length end, or zero if positionInStream is beyond stream length end, but not more than length. - ///
- /// A memory stream to share the data memory with the buffer being created. - /// The position of the shared memory region. - /// The maximum size of the shared memory region. - /// A new IBuffer backed by the same memory as this specified stream. - [CLSCompliant(false)] - public static IBuffer GetWindowsRuntimeBuffer(this MemoryStream underlyingStream, int positionInStream, int length) - { - // The naming inconsistency with (Byte []).AsBuffer is intentional: as this extension method will appear on - // MemoryStream, consistency with method names on MemoryStream is more important. There we already have an API - // called GetBuffer which returns the underlying array. - - if (underlyingStream == null) - throw new ArgumentNullException(nameof(underlyingStream)); - - if (positionInStream < 0) - throw new ArgumentOutOfRangeException(nameof(positionInStream)); - - if (length < 0) - throw new ArgumentOutOfRangeException(nameof(length)); - - if (underlyingStream.Capacity <= positionInStream) - throw new ArgumentException(SR.Argument_StreamPositionBeyondEOS); - - ArraySegment streamData; - - if (!underlyingStream.TryGetBuffer(out streamData)) - { - throw new UnauthorizedAccessException(SR.UnauthorizedAccess_InternalBuffer); - } - - int originInStream = streamData.Offset; - int buffCapacity = Math.Min(length, underlyingStream.Capacity - positionInStream); - int buffLength = Math.Max(0, Math.Min(length, ((int)underlyingStream.Length) - positionInStream)); - return new WindowsRuntimeBuffer(streamData.Array!, originInStream + positionInStream, buffLength, buffCapacity); - } - - - [CLSCompliant(false)] - public static Stream AsStream(this IBuffer source) - { - if (source == null) - throw new ArgumentNullException(nameof(source)); - - byte[]? dataArr; - int dataOffs; - if (source.TryGetUnderlyingData(out dataArr, out dataOffs)) - { - Debug.Assert(source.Capacity < int.MaxValue); - return new MemoryStream(dataArr, dataOffs, (int)source.Capacity, true); - } - - unsafe - { - IBufferByteAccess bufferByteAccess = (IBufferByteAccess)source; - return new WindowsRuntimeBufferUnmanagedMemoryStream(source, (byte*)bufferByteAccess.GetBuffer()); - } - } - - #endregion Extensions for co-operation with memory streams (share mem stream data; expose data as managed/unmanaged mem stream) - - - #region Extensions for direct by-offset access to buffer data elements - - [CLSCompliant(false)] - public static byte GetByte(this IBuffer source, uint byteOffset) - { - if (source == null) throw new ArgumentNullException(nameof(source)); - if (source.Capacity <= byteOffset) throw new ArgumentException(SR.Argument_BufferIndexExceedsCapacity, nameof(byteOffset)); - - byte[]? srcDataArr; - int srcDataOffs; - if (source.TryGetUnderlyingData(out srcDataArr, out srcDataOffs)) - { - return srcDataArr[srcDataOffs + byteOffset]; - } - - IntPtr srcPtr = source.GetPointerAtOffset(byteOffset); - unsafe - { - // Let's avoid an unnesecary call to Marshal.ReadByte(): - byte* ptr = (byte*)srcPtr; - return *ptr; - } - } - - #endregion Extensions for direct by-offset access to buffer data elements - - - #region Private plumbing - - private class WindowsRuntimeBufferUnmanagedMemoryStream : UnmanagedMemoryStream - { - // We need this class because if we construct an UnmanagedMemoryStream on an IBuffer backed by native memory, - // we must keep around a reference to the IBuffer from which we got the memory pointer. Otherwise the ref count - // of the underlying COM object may drop to zero and the memory may get freed. - - private readonly IBuffer _sourceBuffer; - - internal unsafe WindowsRuntimeBufferUnmanagedMemoryStream(IBuffer sourceBuffer, byte* dataPtr) - - : base(dataPtr, (long)sourceBuffer.Length, (long)sourceBuffer.Capacity, FileAccess.ReadWrite) - { - _sourceBuffer = sourceBuffer; - } - } // class WindowsRuntimeBufferUnmanagedMemoryStream - - private static IntPtr GetPointerAtOffset(this IBuffer buffer, uint offset) - { - Debug.Assert(0 <= offset); - Debug.Assert(offset < buffer.Capacity); - - unsafe - { - IntPtr buffPtr = ((IBufferByteAccess)buffer).GetBuffer(); - return new IntPtr((byte*)buffPtr + offset); - } - } - - private static unsafe void MemCopy(IntPtr src, IntPtr dst, uint count) - { - if (count > int.MaxValue) - { - MemCopy(src, dst, int.MaxValue); - MemCopy(src + int.MaxValue, dst + int.MaxValue, count - int.MaxValue); - return; - } - - Debug.Assert(count <= int.MaxValue); - int bCount = (int)count; - - - // Copy via buffer. - // Note: if becomes perf critical, we will port the routine that - // copies the data without using Marshal (and byte[]) - byte[] tmp = new byte[bCount]; - Marshal.Copy(src, tmp, 0, bCount); - Marshal.Copy(tmp, 0, dst, bCount); - return; - } - #endregion Private plumbing - } // class WindowsRuntimeBufferExtensions -} // namespace - -// WindowsRuntimeBufferExtensions.cs diff --git a/src/libraries/System.Runtime.WindowsRuntime/src/System/Threading/Tasks/AsyncInfoIdGenerator.cs b/src/libraries/System.Runtime.WindowsRuntime/src/System/Threading/Tasks/AsyncInfoIdGenerator.cs deleted file mode 100644 index 09e4ffd..0000000 --- a/src/libraries/System.Runtime.WindowsRuntime/src/System/Threading/Tasks/AsyncInfoIdGenerator.cs +++ /dev/null @@ -1,80 +0,0 @@ -// 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.Threading; - -namespace System.Threading.Tasks -{ - /// - /// Reusable component to generate unique IDs for ann the different implementations of IAsyncInfo in this assembly. - /// - internal static class AsyncInfoIdGenerator - { - /// - /// We will never generate this Id, so this value can be used as an invalid, uninitialised or a no-Id value. - /// - internal const uint InvalidId = int.MaxValue; - - - /// - /// We want to avoid ending up with the same ID as a Windows-implemented async info. - /// At the same time we want to be reproducible. So we use a random generator with a fixed seed. - /// - private static readonly Random s_idGenerator = new Random(19830118); - - - /// - /// Generate a unique ID that can be used for an IAsyncInfo object. - /// The returned value will never be equal to AsyncInfoIdGenerator.InvalidId. - /// - /// A new unique IAsyncInfo Id. - internal static uint CreateNext() - { - lock (s_idGenerator) - { - int newId = s_idGenerator.Next(1, (int)InvalidId); // Valid IDs will be larger than zero and smaller than InvalidId - return unchecked((uint)newId); - } - } - - - /// - /// Initialises the specified id to a unique Id-value that can be used for an IAsyncInfo object under the - /// assumption that another thread may also attempt to initialise id. The thread that changes id - /// first from AsyncInfoIdGenerator.InvalidId to another value wins and all other threads will respect that - /// choice and leave id unchanged. The method returns the Id that was agreed upon by the race. - /// - /// The IAsyncInfo ID to initialise. - /// The unique value to which the specified reference target was initialised. - internal static uint EnsureInitializedThreadsafe(ref uint id) - { - if (id != InvalidId) - return id; - - uint newId = CreateNext(); - - // There is no overload of Interlocked.CompareExchange that accepts an UInt32. - // We apply some pointer tricks to pass the arguments to the overload that takes an Int32. - // In clear-text, the following unsafe/fixed statement does this: - // UInt32 asyncIdVal = Interlocked.CompareExchange(ref id, newId, InvalidId); - // if (asyncIdVal == InvalidId) - // return newId; - - unsafe - { - fixed (uint* idPtr = &id) - { - uint asyncIdVal = unchecked((uint)Interlocked.CompareExchange(ref *(int*)idPtr, (int)newId, (int)InvalidId)); - if (asyncIdVal == InvalidId) - return newId; - - return asyncIdVal; - } - } - } - } // class AsyncInfoIdGenerator -} // namespace - -// AsyncInfoIdGenerator.cs diff --git a/src/libraries/System.Runtime.WindowsRuntime/src/System/Threading/Tasks/AsyncInfoToTaskBridge.cs b/src/libraries/System.Runtime.WindowsRuntime/src/System/Threading/Tasks/AsyncInfoToTaskBridge.cs deleted file mode 100644 index ff8f1f0..0000000 --- a/src/libraries/System.Runtime.WindowsRuntime/src/System/Threading/Tasks/AsyncInfoToTaskBridge.cs +++ /dev/null @@ -1,245 +0,0 @@ -// 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 Internal.Runtime.InteropServices.WindowsRuntime; -using Internal.Threading.Tasks; -using System.ComponentModel; -using System.Diagnostics; -using System.Runtime.CompilerServices; -using System.Runtime.InteropServices; -using System.Runtime.InteropServices.WindowsRuntime; -using System.Threading; -using Windows.Foundation; - -namespace System.Threading.Tasks -{ - /// Provides a bridge between IAsyncOperation* and Task. - /// Specifies the type of the result of the asynchronous operation. - /// Specifies the type of progress notification data. - internal sealed class AsyncInfoToTaskBridge : TaskCompletionSource - { - /// The CancellationToken associated with this operation. - private readonly CancellationToken _ct; - - /// A registration for cancellation that needs to be disposed of when the operation completes. - private CancellationTokenRegistration _ctr; - - /// A flag set to true as soon as the completion callback begins to execute. - private bool _completing; - - internal AsyncInfoToTaskBridge(CancellationToken cancellationToken) - { - if (AsyncCausalitySupport.LoggingOn) - AsyncCausalitySupport.TraceOperationCreation(this.Task, "WinRT Operation as Task"); - AsyncCausalitySupport.AddToActiveTasks(this.Task); - - _ct = cancellationToken; - } - - /// The synchronization object to use for protecting the state of this bridge. - private object StateLock - { - get { return this; } // "this" isn't available publicly, so we can safely use it as a syncobj - } - - /// Registers the async operation for cancellation. - /// The asynchronous operation. - internal void RegisterForCancellation(IAsyncInfo asyncInfo) - { - Debug.Assert(asyncInfo != null); - - try - { - if (_ct.CanBeCanceled && !_completing) - { // benign race on m_completing... it's ok if it's not up-to-date. - var ctr = _ct.Register(ai => ((IAsyncInfo)ai!).Cancel(), asyncInfo); // delegate cached by compiler - - // The operation may already be completing by this time, in which case - // we might need to dispose of our new cancellation registration here. - bool disposeOfCtr = false; - lock (StateLock) - { - if (_completing) - disposeOfCtr = true; - else - _ctr = ctr; // under lock to avoid torn writes - } - - if (disposeOfCtr) - ctr.Unregister(); - } - } - catch (Exception ex) - { - // We do not want exceptions propagating out of the AsTask / GetAwaiter calls, as the - // Completed handler will instead store the exception into the returned Task. - // Such exceptions should cause the Completed handler to be invoked synchronously and thus the Task should already be completed. - - if (!base.Task.IsFaulted) - { - Debug.Fail($"Expected base task to already be faulted but found it in state {base.Task.Status}"); - base.TrySetException(ex); - } - } - } - - - /// Bridge to Completed handler on IAsyncAction. - internal void CompleteFromAsyncAction(IAsyncAction asyncInfo, AsyncStatus asyncStatus) - { - Complete(asyncInfo, null, asyncStatus); - } - - /// Bridge to Completed handler on IAsyncActionWithProgress{TProgress}. - internal void CompleteFromAsyncActionWithProgress(IAsyncActionWithProgress asyncInfo, AsyncStatus asyncStatus) - { - Complete(asyncInfo, null, asyncStatus); - } - - /// Bridge to Completed handler on IAsyncOperation{TResult}. - internal void CompleteFromAsyncOperation(IAsyncOperation asyncInfo, AsyncStatus asyncStatus) - { - Complete(asyncInfo, ai => ((IAsyncOperation)ai).GetResults(), asyncStatus); // delegate cached by compiler - } - - /// Bridge to Completed handler on IAsyncOperationWithProgress{TResult,TProgress}. - internal void CompleteFromAsyncOperationWithProgress(IAsyncOperationWithProgress asyncInfo, AsyncStatus asyncStatus) - { - // delegate cached by compiler: - Complete(asyncInfo, ai => ((IAsyncOperationWithProgress)ai).GetResults(), asyncStatus); - } - - /// Completes the task from the completed asynchronous operation. - /// The asynchronous operation. - /// A function used to retrieve the TResult from the async operation; may be null. - /// The status of the asynchronous operation. - private void Complete(IAsyncInfo asyncInfo, Func? getResultsFunction, AsyncStatus asyncStatus) - { - if (asyncInfo == null) - throw new ArgumentNullException(nameof(asyncInfo)); - - AsyncCausalitySupport.RemoveFromActiveTasks(this.Task); - - try - { - Debug.Assert(asyncInfo.Status == asyncStatus, - "asyncInfo.Status does not match asyncStatus; are we dealing with a faulty IAsyncInfo implementation?"); - - // Assuming a correct underlying implementation, the task should not have been - // completed yet. If it is completed, we shouldn't try to do any further work - // with the operation or the task, as something is horked. - bool taskAlreadyCompleted = Task.IsCompleted; - - Debug.Assert(!taskAlreadyCompleted, "Expected the task to not yet be completed."); - - if (taskAlreadyCompleted) - throw new InvalidOperationException(SR.InvalidOperation_InvalidAsyncCompletion); - - // Clean up our registration with the cancellation token, noting that we're now in the process of cleaning up. - CancellationTokenRegistration ctr; - lock (StateLock) - { - _completing = true; - ctr = _ctr; // under lock to avoid torn reads - _ctr = default(CancellationTokenRegistration); - } - ctr.Unregister(); // It's ok if we end up unregistering a not-initialized registration; it'll just be a nop. - - try - { - // Find out how the async operation completed. It must be in a terminal state. - bool terminalState = asyncStatus == AsyncStatus.Completed - || asyncStatus == AsyncStatus.Canceled - || asyncStatus == AsyncStatus.Error; - - Debug.Assert(terminalState, "The async operation should be in a terminal state."); - - if (!terminalState) - throw new InvalidOperationException(SR.InvalidOperation_InvalidAsyncCompletion); - - // Retrieve the completion data from the IAsyncInfo. - TResult result = default(TResult); - Exception? error = null; - if (asyncStatus == AsyncStatus.Error) - { - error = asyncInfo.ErrorCode; - - // Defend against a faulty IAsyncInfo implementation: - if (error == null) - { - Debug.Fail("IAsyncInfo.Status == Error, but ErrorCode returns a null Exception (implying S_OK)."); - error = new InvalidOperationException(SR.InvalidOperation_InvalidAsyncCompletion); - } - else - { - error = ExceptionSupport.AttachRestrictedErrorInfo(asyncInfo.ErrorCode); - } - } - else if (asyncStatus == AsyncStatus.Completed && getResultsFunction != null) - { - try - { - result = getResultsFunction(asyncInfo); - } - catch (Exception resultsEx) - { - // According to the WinRT team, this can happen in some egde cases, such as marshalling errors in GetResults. - error = resultsEx; - asyncStatus = AsyncStatus.Error; - } - } - - // Nothing to retrieve for a canceled operation or for a completed operation with no result. - - // Complete the task based on the previously retrieved results: - bool success = false; - switch (asyncStatus) - { - case AsyncStatus.Completed: - if (AsyncCausalitySupport.LoggingOn) - AsyncCausalitySupport.TraceOperationCompletedSuccess(this.Task); - success = base.TrySetResult(result!); - break; - - case AsyncStatus.Error: - Debug.Assert(error != null, "The error should have been retrieved previously."); - success = base.TrySetException(error); - break; - - case AsyncStatus.Canceled: - success = base.TrySetCanceled(_ct.IsCancellationRequested ? _ct : new CancellationToken(true)); - break; - } - - Debug.Assert(success, "Expected the outcome to be successfully transfered to the task."); - } - catch (Exception exc) - { - // This really shouldn't happen, but could in a variety of misuse cases - // such as a faulty underlying IAsyncInfo implementation. - Debug.Fail($"Unexpected exception in Complete: {exc}"); - - if (AsyncCausalitySupport.LoggingOn) - AsyncCausalitySupport.TraceOperationCompletedError(this.Task); - - // For these cases, store the exception into the task so that it makes its way - // back to the caller. Only if something went horribly wrong and we can't store the exception - // do we allow it to be propagated out to the invoker of the Completed handler. - if (!base.TrySetException(exc)) - { - Debug.Fail("The task was already completed and thus the exception couldn't be stored."); - throw; - } - } - } - finally - { - // We may be called on an STA thread which we don't own, so make sure that the RCW is released right - // away. Otherwise, if we leave it up to the finalizer, the apartment may already be gone. - if (Marshal.IsComObject(asyncInfo)) - Marshal.ReleaseComObject(asyncInfo); - } - } // private void Complete(..) - } // class AsyncInfoToTaskBridge -} // namespace diff --git a/src/libraries/System.Runtime.WindowsRuntime/src/System/Threading/Tasks/ExceptionDispatchHelper.cs b/src/libraries/System.Runtime.WindowsRuntime/src/System/Threading/Tasks/ExceptionDispatchHelper.cs deleted file mode 100644 index 6d1f215..0000000 --- a/src/libraries/System.Runtime.WindowsRuntime/src/System/Threading/Tasks/ExceptionDispatchHelper.cs +++ /dev/null @@ -1,56 +0,0 @@ -// 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.ExceptionServices; -using System.Threading; - -namespace System.Threading.Tasks -{ - internal static class ExceptionDispatchHelper - { - internal static void ThrowAsync(Exception? exception, SynchronizationContext? targetContext) - { - if (exception == null) - return; - - // TODO - decide how to cleanly do it so it lights up if TA is defined - //if (exception is ThreadAbortException) - // return; - - - ExceptionDispatchInfo exceptionDispatchInfo = ExceptionDispatchInfo.Capture(exception); - - if (targetContext != null) - { - try - { - targetContext.Post((edi) => ((ExceptionDispatchInfo)edi!).Throw(), exceptionDispatchInfo); - } - catch - { - // Something went wrong in the Post; let's try using the thread pool instead: - ThrowAsync(exception, null); - } - return; - } - - bool scheduled = true; - try - { - new SynchronizationContext().Post((edi) => ((ExceptionDispatchInfo)edi!).Throw(), exceptionDispatchInfo); - } - catch - { - // Something went wrong when scheduling the thrower; we do our best by throwing the exception here: - scheduled = false; - } - - if (!scheduled) - exceptionDispatchInfo.Throw(); - } - } // ExceptionDispatchHelper -} // namespace - -// ExceptionDispatchHelper.cs diff --git a/src/libraries/System.Runtime.WindowsRuntime/src/System/Threading/Tasks/TaskToAsyncActionAdapter.cs b/src/libraries/System.Runtime.WindowsRuntime/src/System/Threading/Tasks/TaskToAsyncActionAdapter.cs deleted file mode 100644 index 2869fd6..0000000 --- a/src/libraries/System.Runtime.WindowsRuntime/src/System/Threading/Tasks/TaskToAsyncActionAdapter.cs +++ /dev/null @@ -1,54 +0,0 @@ -// 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.Diagnostics; -using System.Threading; -using System.Threading.Tasks; -using Windows.Foundation; - -namespace System.Threading.Tasks -{ - internal class TaskToAsyncActionAdapter - : TaskToAsyncInfoAdapter, - IAsyncAction - { - internal TaskToAsyncActionAdapter(Delegate taskGenerator) - - : base(taskGenerator) - { - } - - - internal TaskToAsyncActionAdapter(Task underlyingTask, CancellationTokenSource? underlyingCancelTokenSource) - - : base(underlyingTask, underlyingCancelTokenSource, underlyingProgressDispatcher: null) - { - } - - - internal TaskToAsyncActionAdapter(bool isCanceled) - - : base(default(VoidValueTypeParameter)) - { - if (isCanceled) - DangerousSetCanceled(); - } - - - public virtual void GetResults() - { - GetResultsInternal(); - } - - - internal override void OnCompleted(AsyncActionCompletedHandler userCompletionHandler, AsyncStatus asyncStatus) - { - Debug.Assert(userCompletionHandler != null); - userCompletionHandler(this, asyncStatus); - } - } // class TaskToAsyncActionAdapter -} // namespace - -// TaskToAsyncActionAdapter.cs diff --git a/src/libraries/System.Runtime.WindowsRuntime/src/System/Threading/Tasks/TaskToAsyncActionWithProgressAdapter.cs b/src/libraries/System.Runtime.WindowsRuntime/src/System/Threading/Tasks/TaskToAsyncActionWithProgressAdapter.cs deleted file mode 100644 index 9b104d4..0000000 --- a/src/libraries/System.Runtime.WindowsRuntime/src/System/Threading/Tasks/TaskToAsyncActionWithProgressAdapter.cs +++ /dev/null @@ -1,67 +0,0 @@ -// 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.Diagnostics; -using System.Threading; -using System.Threading.Tasks; -using Windows.Foundation; - -namespace System.Threading.Tasks -{ - internal class TaskToAsyncActionWithProgressAdapter - : TaskToAsyncInfoAdapter, - AsyncActionProgressHandler, - VoidValueTypeParameter, - TProgress>, - IAsyncActionWithProgress - { - internal TaskToAsyncActionWithProgressAdapter(Delegate taskGenerator) - - : base(taskGenerator) - { - } - - - // This is currently not used, so commented out to save code. - // Leaving this is the source to be uncommented in case we decide to support IAsyncActionWithProgress-consturction from a Task. - // - //internal TaskToAsyncActionWithProgressAdapter(Task underlyingTask, CancellationTokenSource underlyingCancelTokenSource, - // Progress underlyingProgressDispatcher) - // - // : base(underlyingTask, underlyingCancelTokenSource, underlyingProgressDispatcher) { - //} - - - internal TaskToAsyncActionWithProgressAdapter(bool isCanceled) - - : base(default(VoidValueTypeParameter)) - { - if (isCanceled) - DangerousSetCanceled(); - } - - - public virtual void GetResults() - { - GetResultsInternal(); - } - - - internal override void OnCompleted(AsyncActionWithProgressCompletedHandler userCompletionHandler, AsyncStatus asyncStatus) - { - Debug.Assert(userCompletionHandler != null); - userCompletionHandler(this, asyncStatus); - } - - - internal override void OnProgress(AsyncActionProgressHandler userProgressHandler, TProgress progressInfo) - { - Debug.Assert(userProgressHandler != null); - userProgressHandler(this, progressInfo); - } - } // class TaskToAsyncActionWithProgressAdapter -} // namespace - -// TaskToAsyncActionWithProgressAdapter.cs diff --git a/src/libraries/System.Runtime.WindowsRuntime/src/System/Threading/Tasks/TaskToAsyncInfoAdapter.cs b/src/libraries/System.Runtime.WindowsRuntime/src/System/Threading/Tasks/TaskToAsyncInfoAdapter.cs deleted file mode 100644 index 6b3b8bd..0000000 --- a/src/libraries/System.Runtime.WindowsRuntime/src/System/Threading/Tasks/TaskToAsyncInfoAdapter.cs +++ /dev/null @@ -1,1009 +0,0 @@ -// 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.Diagnostics; -using System.Diagnostics.CodeAnalysis; -using System.Diagnostics.Contracts; -using System.Runtime.ExceptionServices; -using System.Runtime.InteropServices; -using System.Threading; -using Windows.Foundation; - -namespace System.Threading.Tasks -{ - /// - /// Implements a wrapper that allows to expose managed System.Threading.Tasks.Task objects as - /// through the WinRT Windows.Foundation.IAsyncInfo interface. - /// - internal class TaskToAsyncInfoAdapter - : IAsyncInfo, IProgress - where TCompletedHandler : class - where TProgressHandler : class - { - #region Private Types, Statics and Constants - - // ! THIS DIAGRAM ILLUSTRATES THE CONSTANTS BELOW. UPDATE THIS IF UPDATING THE CONSTANTS BELOW!: - // 3 2 1 0 - // 10987654321098765432109876543210 - // X............................... Reserved such that we can use Int32 and not worry about negative-valued state constants - // ..X............................. STATEFLAG_COMPLETED_SYNCHRONOUSLY - // ...X............................ STATEFLAG_MUST_RUN_COMPLETION_HNDL_WHEN_SET - // ....X........................... STATEFLAG_COMPLETION_HNDL_NOT_YET_INVOKED - // ................................ STATE_NOT_INITIALIZED - // ...............................X STATE_STARTED - // ..............................X. STATE_RUN_TO_COMPLETION - // .............................X.. STATE_CANCELLATION_REQUESTED - // ............................X... STATE_CANCELLATION_COMPLETED - // ...........................X.... STATE_ERROR - // ..........................X..... STATE_CLOSED - // ..........................XXXXXX STATEMASK_SELECT_ANY_ASYNC_STATE - // XXXXXXXXXXXXXXXXXXXXXXXXXX...... STATEMASK_CLEAR_ALL_ASYNC_STATES - // 3 2 1 0 - // 10987654321098765432109876543210 - - // These STATE_XXXX constants describe the async state of this object. - // Objects of this type are in exactly in one of these states at any given time: - private const int STATE_NOT_INITIALIZED = 0; // 0x00 - private const int STATE_STARTED = 1; // 0x01 - private const int STATE_RUN_TO_COMPLETION = 2; // 0x02 - private const int STATE_CANCELLATION_REQUESTED = 4; // 0x04 - private const int STATE_CANCELLATION_COMPLETED = 8; // 0x08 - private const int STATE_ERROR = 16; // 0x10 - private const int STATE_CLOSED = 32; // 0x20 - - // The STATEFLAG_XXXX constants can be bitmasked with the states to describe additional - // state info that cannot be easily inferred from the async state: - private const int STATEFLAG_COMPLETED_SYNCHRONOUSLY = 0x20000000; - private const int STATEFLAG_MUST_RUN_COMPLETION_HNDL_WHEN_SET = 0x10000000; - private const int STATEFLAG_COMPLETION_HNDL_NOT_YET_INVOKED = 0x8000000; - - // These two masks are used to select any STATE_XXXX bits and clear all other (i.e. STATEFLAG_XXXX) bits. - // It is set to (next power of 2 after the largest STATE_XXXX value) - 1. - // !!! Make sure to update this if a new STATE_XXXX value is added above !! - private const int STATEMASK_SELECT_ANY_ASYNC_STATE = (64 - 1); - - // These two masks are used to clear all STATE_XXXX bits and leave any STATEFLAG_XXXX bits. - private const int STATEMASK_CLEAR_ALL_ASYNC_STATES = ~STATEMASK_SELECT_ANY_ASYNC_STATE; - - private static InvalidOperationException CreateCannotGetResultsFromIncompleteOperationException(Exception? cause) - { - InvalidOperationException ex = (cause == null) - ? new InvalidOperationException(SR.InvalidOperation_CannotGetResultsFromIncompleteOperation) - : new InvalidOperationException(SR.InvalidOperation_CannotGetResultsFromIncompleteOperation, cause); - ex.HResult = __HResults.E_ILLEGAL_METHOD_CALL; - return ex; - } - - #endregion Private Types, Statics and Constants - - - #region Instance variables - - /// The token source used to cancel running operations. - private CancellationTokenSource? _cancelTokenSource = null; - - /// The async info's ID. InvalidAsyncId stands for not yet been initialised. - private uint _id = AsyncInfoIdGenerator.InvalidId; - - /// The cached error code used to avoid creating several exception objects if the ErrorCode - /// property is accessed several times. null indicates either no error or that ErrorCode - /// has not yet been called. - private Exception? _error = null; - - /// The state of the async info. Interlocked operations are used to manipulate this field. - private volatile int _state = STATE_NOT_INITIALIZED; - - /// For IAsyncInfo instances that completed synchronously (at creation time) this field holds the result; - /// for instances backed by an actual Task, this field holds a reference to the task generated by the task generator. - /// Since we always know which of the above is the case, we can always cast this field to TResult in the former case - /// or to one of Task or Task{TResult} in the latter case. This approach allows us to save a field on all IAsyncInfos. - /// Notably, this makes us pay the added cost of boxing for synchronously completing IAsyncInfos where TResult is a - /// value type, however, this is expected to occur rather rare compared to non-synchronously completed user-IAsyncInfos. - private object? _dataContainer; - - /// Registered completed handler. - private TCompletedHandler? _completedHandler; - - /// Registered progress handler. - private TProgressHandler? _progressHandler; - - /// The synchronization context on which this instance was created/started. Used to callback invocations. - private SynchronizationContext? _startingContext; - - #endregion Instance variables - - - #region Constructors and Destructor - - /// Creates an IAsyncInfo from the specified delegate. The delegate will be called to construct a task that will - /// represent the future encapsulated by this IAsyncInfo. - /// The task generator to use for creating the task. - internal TaskToAsyncInfoAdapter(Delegate taskProvider) - { - Debug.Assert(taskProvider != null); - Debug.Assert((null != (taskProvider as Func)) - || (null != (taskProvider as Func)) - || (null != (taskProvider as Func, Task>)) - || (null != (taskProvider as Func, Task>))); - - // The IAsyncInfo is reasonably expected to be created/started by the same code that wires up the Completed and Progress handlers. - // Record the current SynchronizationContext so that we can invoke completion and progress callbacks in it later. - _startingContext = GetStartingContext(); - - // Construct task from the specified provider: - Task task = InvokeTaskProvider(taskProvider); - - if (task == null) - throw new NullReferenceException(SR.NullReference_TaskProviderReturnedNull); - - if (task.Status == TaskStatus.Created) - throw new InvalidOperationException(SR.InvalidOperation_TaskProviderReturnedUnstartedTask); - - _dataContainer = task; - _state = (STATEFLAG_COMPLETION_HNDL_NOT_YET_INVOKED | STATE_STARTED); - - // Set the completion routine and let the task running: - task.ContinueWith( - (_, this_) => ((TaskToAsyncInfoAdapter)this_!).TaskCompleted(), - this, CancellationToken.None, TaskContinuationOptions.ExecuteSynchronously, TaskScheduler.Default); - } - - - /// - /// Creates an IAsyncInfo from the Task object. The specified task represents the future encapsulated by this IAsyncInfo. - /// The specified CancellationTokenSource and Progress are assumed to be the source of the specified Task's cancellation and - /// the Progress that receives reports from the specified Task. - /// - /// The Task whose operation is represented by this IAsyncInfo - /// The cancellation control for the cancellation token observed - /// by underlyingTask. - /// A progress listener/pugblisher that receives progress notifications - /// form underlyingTask. - internal TaskToAsyncInfoAdapter(Task underlyingTask, - CancellationTokenSource? underlyingCancelTokenSource, Progress? underlyingProgressDispatcher) - { - if (underlyingTask == null) - throw new ArgumentNullException(nameof(underlyingTask)); - - // Throw InvalidOperation and not Argument for parity with the constructor that takes Delegate taskProvider: - if (underlyingTask.Status == TaskStatus.Created) - throw new InvalidOperationException(SR.InvalidOperation_UnstartedTaskSpecified); - - // The IAsyncInfo is reasonably expected to be created/started by the same code that wires up the Completed and Progress handlers. - // Record the current SynchronizationContext so that we can invoke completion and progress callbacks in it later. - _startingContext = GetStartingContext(); - - // We do not need to invoke any delegates to get the task, it is provided for us: - _dataContainer = underlyingTask; - - // This must be the cancellation source for the token that the specified underlyingTask observes for cancellation: - // (it may also be null in cases where the specified underlyingTask does nto support cancellation) - _cancelTokenSource = underlyingCancelTokenSource; - - // Iff the specified underlyingTask reports progress, chain the reports to this IAsyncInfo's reporting method: - if (underlyingProgressDispatcher != null) - underlyingProgressDispatcher.ProgressChanged += OnReportChainedProgress; - - _state = (STATEFLAG_COMPLETION_HNDL_NOT_YET_INVOKED | STATE_STARTED); - - underlyingTask.ContinueWith( - (_, this_) => ((TaskToAsyncInfoAdapter)this_!).TaskCompleted(), - this, CancellationToken.None, TaskContinuationOptions.ExecuteSynchronously, TaskScheduler.Default); - } - - - /// - /// Creates an IAsyncInfo from the specified result value. The IAsyncInfo is created in the Completed state and the - /// specified synchronousResult is used as the result value. - /// - /// The result of this synchronously completed IAsyncInfo. - internal TaskToAsyncInfoAdapter([AllowNull] TResult synchronousResult) - { - // We already completed. There will be no progress callback invokations and a potential completed handler invokation will be synchronous. - // We do not need the starting SynchronizationContext: - _startingContext = null; - - // Set the synchronous result: - _dataContainer = synchronousResult; - - // CompletedSynchronously + MustRunCompletionHandleImmediatelyWhenSet + CompletionHandlerNotYetInvoked + RUN_TO_COMPLETION: - // (same state as assigned by DangerousSetCompleted()) - _state = (STATEFLAG_COMPLETED_SYNCHRONOUSLY - | STATEFLAG_MUST_RUN_COMPLETION_HNDL_WHEN_SET - | STATEFLAG_COMPLETION_HNDL_NOT_YET_INVOKED - | STATE_RUN_TO_COMPLETION); - } - - - ~TaskToAsyncInfoAdapter() - { - TransitionToClosed(); - } - - #endregion Constructors and Destructor - - - #region Synchronous completion controls - - /// This method sets the result on a *synchronously completed* IAsyncInfo. - /// It does not try to deal with the inherit races: Use it only when constructing a synchronously - /// completed IAsyncInfo in a desired state when you understand the threading conditions well. - /// The new result of this synchronously completed IAsyncInfo (may be default(TResult)) - /// FALSE if this IAsyncInfo has not actually completed synchronously and this method had no effects, TRUE otherwise. - internal bool DangerousSetCompleted(TResult synchronousResult) - { - if (!CompletedSynchronously) - return false; - - _dataContainer = synchronousResult; - _error = null; - - // CompletedSynchronously + MustRunCompletionHandleImmediatelyWhenSet + CompletionHandlerNotYetInvoked + RUN_TO_COMPLETION: - _state = (STATEFLAG_COMPLETED_SYNCHRONOUSLY - | STATEFLAG_MUST_RUN_COMPLETION_HNDL_WHEN_SET - | STATEFLAG_COMPLETION_HNDL_NOT_YET_INVOKED - | STATE_RUN_TO_COMPLETION); - return true; - } - - - internal bool DangerousSetCanceled() - { - if (!CompletedSynchronously) - return false; - - // Here we do not try to deal with the inherit races: Use this method only when constructing a synchronously - // completed IAsyncInfo in a desired state when you understand the threading conditions well. - - _dataContainer = null; - _error = null; - - // CompletedSynchronously + MustRunCompletionHandleImmediatelyWhenSet + CompletionHandlerNotYetInvoked + CANCELLATION_COMPLETED: - _state = (STATEFLAG_COMPLETED_SYNCHRONOUSLY - | STATEFLAG_MUST_RUN_COMPLETION_HNDL_WHEN_SET - | STATEFLAG_COMPLETION_HNDL_NOT_YET_INVOKED - | STATE_CANCELLATION_COMPLETED); - return true; - } - - - internal bool DangerousSetError(Exception error) - { - if (!CompletedSynchronously) - return false; - - if (error == null) - throw new ArgumentNullException(nameof(error)); - - // Here we do not try to deal with the inherit races: Use this method only when constructing a synchronously - // completed IAsyncInfo in a desired state when you understand the threading conditions well. - - _dataContainer = null; - _error = error; - - // CompletedSynchronously + MustRunCompletionHandleImmediatelyWhenSet + CompletionHandlerNotYetInvoked + ERROR: - _state = (STATEFLAG_COMPLETED_SYNCHRONOUSLY - | STATEFLAG_MUST_RUN_COMPLETION_HNDL_WHEN_SET - | STATEFLAG_COMPLETION_HNDL_NOT_YET_INVOKED - | STATE_ERROR); - return true; - } - - #endregion Synchronous completion controls - - - #region State bit field operations - - internal bool CompletedSynchronously { [Pure] get { return (0 != (_state & STATEFLAG_COMPLETED_SYNCHRONOUSLY)); } } - - private bool IsInStartedState { [Pure] get { return (0 != (_state & STATE_STARTED)); } } - - private bool IsInRunToCompletionState { [Pure] get { return (0 != (_state & STATE_RUN_TO_COMPLETION)); } } - - private bool IsInErrorState { [Pure] get { return (0 != (_state & STATE_ERROR)); } } - - private bool IsInClosedState { [Pure] get { return (0 != (_state & STATE_CLOSED)); } } - - private bool IsInRunningState - { - [Pure] - get - { - return (0 != (_state & (STATE_STARTED - | STATE_CANCELLATION_REQUESTED))); - } - } - - private bool IsInTerminalState - { - [Pure] - get - { - return (0 != (_state & (STATE_RUN_TO_COMPLETION - | STATE_CANCELLATION_COMPLETED - | STATE_ERROR))); - } - } - - [Pure] - private bool CheckUniqueAsyncState(int state) - { - unchecked - { - uint asyncState = (uint)state; - return (asyncState & (~asyncState + 1)) == asyncState; // This checks if asyncState is 0 or a power of 2. - } - } - - #endregion State bit field operations - - - #region Infrastructure methods - - private SynchronizationContext? GetStartingContext() - { -#if DESKTOP // as a reminder that on most platforms we want a different behavior - return SynchronizationContext.CurrentNoFlow; -#else - return SynchronizationContext.Current; -#endif - } - - - internal Task? Task - { - get - { - EnsureNotClosed(); - - if (CompletedSynchronously) - return null; - - return (Task?)_dataContainer; - } - } - - - internal CancellationTokenSource? CancelTokenSource - { - get { return _cancelTokenSource; } - } - - - [Pure] - internal void EnsureNotClosed() - { - if (!IsInClosedState) - return; - - ObjectDisposedException ex = new ObjectDisposedException(SR.ObjectDisposed_AsyncInfoIsClosed); - ex.HResult = __HResults.E_ILLEGAL_METHOD_CALL; - throw ex; - } - - - internal virtual void OnCompleted(TCompletedHandler userCompletionHandler, AsyncStatus asyncStatus) - { - Debug.Fail("This (sub-)type of IAsyncInfo does not support completion notifications " - + " (" + this.GetType().ToString() + ")"); - } - - - internal virtual void OnProgress(TProgressHandler userProgressHandler, TProgressInfo progressInfo) - { - Debug.Fail("This (sub-)type of IAsyncInfo does not support progress notifications " - + " (" + this.GetType().ToString() + ")"); - } - - - private void OnCompletedInvoker(AsyncStatus status) - { - bool conditionFailed; - - // Get the handler: - TCompletedHandler? handler = Volatile.Read(ref _completedHandler); - - // If we might not run the handler now, we need to remember that if it is set later, it will need to be run then: - if (handler == null) - { - // Remember to run the handler when it is set: - SetState(STATEFLAG_MUST_RUN_COMPLETION_HNDL_WHEN_SET, ~STATEFLAG_MUST_RUN_COMPLETION_HNDL_WHEN_SET, - conditionBitMask: 0, useCondition: false, conditionFailed: out conditionFailed); - - // The handler may have been set concurrently before we managed to SetState, so check for it again: - handler = Volatile.Read(ref _completedHandler); - - // If handler was not set cuncurrently after all, then no worries: - if (handler == null) - return; - } - - // This method might be running cuncurrently. Create a block by emulating an interlocked un-set of - // the STATEFLAG_COMPLETION_HNDL_NOT_YET_INVOKED-bit in the m_state bit field. Only the thread that wins the race - // for unsetting this bit, wins, others give up: - SetState(0, ~STATEFLAG_COMPLETION_HNDL_NOT_YET_INVOKED, - conditionBitMask: STATEFLAG_COMPLETION_HNDL_NOT_YET_INVOKED, useCondition: true, conditionFailed: out conditionFailed); - - if (conditionFailed) - return; - - // Invoke the user handler: - OnCompleted(handler, status); - } - - - // This is a separate method from IProgress.Report to avoid alocating the closure if it is not used. - private void OnProgressInvokerCrossContext(TProgressHandler handler, TProgressInfo progressInfo) - { - Debug.Assert(handler != null); - Debug.Assert(_startingContext != null); - - _startingContext.Post((tupleObject) => - { - var tuple = (Tuple, - TProgressHandler, - TProgressInfo>)tupleObject!; - - tuple.Item1.OnProgress(tuple.Item2, tuple.Item3); - }, Tuple.Create(this, handler, progressInfo)); - } - - - /// Reports a progress update. - /// The new progress value to report. - void IProgress.Report(TProgressInfo value) - { - // If no progress handler is set, there is nothing to do: - TProgressHandler? handler = Volatile.Read(ref _progressHandler); - if (handler == null) - return; - - // Try calling progress handler in the right synchronization context. - // If the user callback throws an exception, it will bubble up through here and reach the - // user worker code running as this async future. The user should catch it. - // If the user does not catch it, it will be treated just as any other exception coming from the async execution code: - // this AsyncInfo will be faulted. - - if (_startingContext == null) - { - // The starting context is null, invoke directly: - OnProgress(handler, value); - } - else - { - // Invoke callback in the right context: - OnProgressInvokerCrossContext(handler, value); - } - } - - - private void OnReportChainedProgress(object? sender, TProgressInfo progressInfo) - { - ((IProgress)this).Report(progressInfo); - } - - - /// - /// Sets the m_state bit field to reflect the specified async state with the corresponding STATE_XXX bit mask. - /// - /// Must be one of the STATE_XXX (not STATEYYY_ZZZ !) constants defined in this class. - /// If useCondition is FALSE: this field is ignored. - /// If useCondition is TRUE: Unless this value has at least one bit with m_state in - /// common, this method will not perform any action. - /// If TRUE, use conditionBitMask to determine whether the state should be set; - /// If FALSE, ignore conditionBitMask. - /// If useCondition is FALSE: this field is set to FALSE; - /// If useCondition is TRUE: this field indicated whether the specified conditionBitMask - /// had at least one bit in common with m_state (TRUE) - /// or not (FALSE). - /// (!) Note that the meaning of this parameter to the caller is not quite the same as whether m_state - /// is/was set to the specified value, because m_state may already have had the specified value, or it - /// may be set and then immediately changed by another thread. The true meaning of this parameter is whether or not - /// the specified condition did hold before trying to change the state. - /// The value at which the current invocation of this method left m_state. - private int SetAsyncState(int newAsyncState, int conditionBitMask, bool useCondition, out bool conditionFailed) - { - Debug.Assert(CheckUniqueAsyncState(newAsyncState & STATEMASK_SELECT_ANY_ASYNC_STATE)); - Debug.Assert(CheckUniqueAsyncState(_state & STATEMASK_SELECT_ANY_ASYNC_STATE)); - - int resultState = SetState(newAsyncState, STATEMASK_CLEAR_ALL_ASYNC_STATES, conditionBitMask, useCondition, out conditionFailed); - Debug.Assert(CheckUniqueAsyncState(resultState & STATEMASK_SELECT_ANY_ASYNC_STATE)); - - return resultState; - } - - - /// - /// Sets the specified bits in the m_state bit field according to the specified bit-mask parameters. - /// - /// The bits to turn ON in the m_state bit field - /// Any bits that are OFF in this value will get turned OFF, - /// unless they are explicitly switched on by newStateSetMask. - /// If useCondition is FALSE: this field is ignored. - /// If useCondition is TRUE: Unless this value has at least one bit with m_state in - /// common, this method will not perform any action. - /// If TRUE, use conditionBitMask to determine whether the state should be set; - /// If FALSE, ignore conditionBitMask. - /// If useCondition is FALSE: this field is set to FALSE; - /// If useCondition is TRUE: this field indicated whether the specified conditionBitMask - /// had at least one bit in common with m_state (TRUE) - /// or not (FALSE). - /// (!) Note that the meaning of this parameter to the caller is not quite the same as whether m_state - /// is/was set to the specified value, because m_state may already have had the specified value, or it - /// may be set and then immediately changed by another thread. The true meaning of this parameter is whether or not - /// the specified condition did hold before trying to change the state. - /// The value at which the current invocation of this method left m_state. - private int SetState(int newStateSetMask, int newStateIgnoreMask, int conditionBitMask, bool useCondition, out bool conditionFailed) - { - int origState = _state; - - if (useCondition && 0 == (origState & conditionBitMask)) - { - conditionFailed = true; - return origState; - } - - int newState = (origState & newStateIgnoreMask) | newStateSetMask; - int prevState = Interlocked.CompareExchange(ref _state, newState, origState); - - // If m_state changed concurrently, we want to make sure that the change being made is based on a bitmask that is up to date: - // (this relies of the fact that all state machines that save their state in m_state have no cycles) - while (true) - { - if (prevState == origState) - { - conditionFailed = false; - return newState; - } - - origState = _state; - - if (useCondition && 0 == (origState & conditionBitMask)) - { - conditionFailed = true; - return origState; - } - - newState = (origState & newStateIgnoreMask) | newStateSetMask; - prevState = Interlocked.CompareExchange(ref _state, newState, origState); - } - } - - - private int TransitionToTerminalState() - { - Debug.Assert(IsInRunningState); - Debug.Assert(!CompletedSynchronously); - - Task? task = _dataContainer as Task; - Debug.Assert(task != null); - Debug.Assert(task.IsCompleted); - - // Recall that STATE_CANCELLATION_REQUESTED and STATE_CANCELLATION_COMPLETED both map to the public CANCELED state. - // So, we are STARTED or CANCELED. We will ask the task how it completed and possibly transition out of CANCELED. - // This may happen if cancellation was requested while in STARTED state, but the task does not support cancellation, - // or if it can support cancellation in principle, but the Cancel request came in while still STARTED, but after the - // last opportunity to cancel. - // If the underlying operation was not able to react to the cancellation request and instead either run to completion - // or faulted, then the state will transition into COMPLETED or ERROR accordingly. If the operation was really cancelled, - // the state will remain CANCELED. - - // If the switch below defaults, we have an erroneous implementation. - int terminalAsyncState = STATE_ERROR; - - switch (task.Status) - { - case TaskStatus.RanToCompletion: - terminalAsyncState = STATE_RUN_TO_COMPLETION; - break; - - case TaskStatus.Canceled: - terminalAsyncState = STATE_CANCELLATION_COMPLETED; - break; - - case TaskStatus.Faulted: - terminalAsyncState = STATE_ERROR; - break; - - default: - Debug.Fail("Unexpected task.Status: It should be terminal if TaskCompleted() is called."); - break; - } - - bool ignore; - int newState = SetAsyncState(terminalAsyncState, - conditionBitMask: STATEMASK_SELECT_ANY_ASYNC_STATE, useCondition: true, conditionFailed: out ignore); - - Debug.Assert((newState & STATEMASK_SELECT_ANY_ASYNC_STATE) == terminalAsyncState); - Debug.Assert((_state & STATEMASK_SELECT_ANY_ASYNC_STATE) == terminalAsyncState || IsInClosedState, - "We must either be in a state we just entered or we were concurrently closed"); - - return newState; - } - - - private void TaskCompleted() - { - int terminalState = TransitionToTerminalState(); - Debug.Assert(IsInTerminalState); - - // We transitioned into a terminal state, so it became legal to close us concurrently. - // So we use data from this stack and not m_state to get the completion status. - // On this code path we will also fetch m_completedHandler, however that race is benign because in CLOSED the handler - // can only change to null, so it won't be invoked, which is appropriate for CLOSED. - AsyncStatus terminationStatus = GetStatus(terminalState); - - // Try calling completed handler in the right synchronization context. - // If the user callback throws an exception, it will bubble up through here. - // If we let it though, it will be caught and swallowed by the Task subsystem, which is just below us on the stack. - // Instead we follow the same pattern as Task and other parallel libs and re-throw the excpetion on the threadpool - // to ensure a diagnostic message and a fail-fast-like teardown. - try - { - if (_startingContext == null) - { - // The starting context is null, invoking directly: - OnCompletedInvoker(terminationStatus); - } - else - { - // Invoke callback in the right context (delegate cached by compiler): - _startingContext.Post((tupleObject) => - { - var tuple = (Tuple, AsyncStatus>)tupleObject!; - tuple.Item1.OnCompletedInvoker(tuple.Item2); - }, Tuple.Create(this, terminationStatus)); - } - } - catch (Exception ex) - { - ExceptionDispatchHelper.ThrowAsync(ex, _startingContext); - } - } - - - private AsyncStatus GetStatus(int state) - { - int asyncState = state & STATEMASK_SELECT_ANY_ASYNC_STATE; - Debug.Assert(CheckUniqueAsyncState(asyncState)); - - switch (asyncState) - { - case STATE_NOT_INITIALIZED: - Debug.Fail("STATE_NOT_INITIALIZED should only occur when this object was not" - + " fully constructed, in which case we should never get here"); - return AsyncStatus.Error; - - case STATE_STARTED: - return AsyncStatus.Started; - - case STATE_RUN_TO_COMPLETION: - return AsyncStatus.Completed; - - case STATE_CANCELLATION_REQUESTED: - case STATE_CANCELLATION_COMPLETED: - return AsyncStatus.Canceled; - - case STATE_ERROR: - return AsyncStatus.Error; - - case STATE_CLOSED: - Debug.Fail("This method should never be called is this IAsyncInfo is CLOSED"); - return AsyncStatus.Error; - } - - Debug.Fail("The switch above is missing a case"); - return AsyncStatus.Error; - } - - internal TResult GetResultsInternal() - { - EnsureNotClosed(); - - // If this IAsyncInfo has actually faulted, GetResults will throw the same error as returned by ErrorCode: - if (IsInErrorState) - { - Exception? error = ErrorCode; - Debug.Assert(error != null); - ExceptionDispatchInfo.Capture(error).Throw(); - } - - // IAsyncInfo throws E_ILLEGAL_METHOD_CALL when called in a state other than COMPLETED: - if (!IsInRunToCompletionState) - throw CreateCannotGetResultsFromIncompleteOperationException(null); - - - // If this is a synchronous operation, use the cached result: - if (CompletedSynchronously) - return (TResult)_dataContainer!; - - // The operation is asynchronous: - Task? task = _dataContainer as Task; - - // Since CompletedSynchronously is false and EnsureNotClosed() did not throw, task can only be null if: - // - this IAsyncInfo has completed synchronously, however we checked for this above; - // - it was not converted to Task, which means it is a non-generic Task. In that case we cannot get a result from Task. - if (task == null) - return default(TResult)!; - - Debug.Assert(IsInRunToCompletionState); - - // Pull out the task result and return. - // Any exceptions thrown in the task will be rethrown. - // If this exception is a cancelation exception, meaning there was actually no error except for being cancelled, - // return an error code appropriate for WinRT instead (InvalidOperation with E_ILLEGAL_METHOD_CALL). - try - { - return task.GetAwaiter().GetResult(); - } - catch (TaskCanceledException tcEx) - { - throw CreateCannotGetResultsFromIncompleteOperationException(tcEx); - } - } - - - private Task InvokeTaskProvider(Delegate taskProvider) - { - var funcVoidTask = taskProvider as Func; - if (funcVoidTask != null) - { - return funcVoidTask(); - } - - var funcCTokTask = taskProvider as Func; - if (funcCTokTask != null) - { - _cancelTokenSource = new CancellationTokenSource(); - return funcCTokTask(_cancelTokenSource.Token); - } - - var funcIPrgrTask = taskProvider as Func, Task>; - if (funcIPrgrTask != null) - { - return funcIPrgrTask(this); - } - - var funcCTokIPrgrTask = taskProvider as Func, Task>; - if (funcCTokIPrgrTask != null) - { - _cancelTokenSource = new CancellationTokenSource(); - return funcCTokIPrgrTask(_cancelTokenSource.Token, this); - } - - Debug.Fail("We should never get here!" - + " Public methods creating instances of this class must be typesafe to ensure that taskProvider" - + " can always be cast to one of the above Func types." - + " The taskProvider is " + (taskProvider == null - ? "null." - : "a " + taskProvider.GetType().ToString()) + "."); - return null; - } - - - private void TransitionToClosed() - { - // From the finaliser we always call this Close version since finalisation can happen any time, even when STARTED (e.g. process ends) - // and we do not want to throw in those cases. - - // Always go to closed, even from STATE_NOT_INITIALIZED. - // Any checking whether it is legal to call CLosed inthe current state, should occur in Close(). - bool ignore; - SetAsyncState(STATE_CLOSED, 0, useCondition: false, conditionFailed: out ignore); - - _cancelTokenSource = null; - _dataContainer = null; - _error = null; - _completedHandler = null; - _progressHandler = null; - _startingContext = null; - } - - #endregion Infrastructure methods - - - #region Implementation of IAsyncInfo - - /// - /// Gets or sets the completed handler. - /// - /// We will set the completion handler even when this IAsyncInfo is already started (no other choice). - /// If we the completion handler is set BEFORE this IAsyncInfo completed, then the handler will be called upon completion as normal. - /// If we the completion handler is set AFTER this IAsyncInfo already completed, then this setter will invoke the handler synchronously - /// on the current context. - /// - public virtual TCompletedHandler? Completed - { - get - { - TCompletedHandler? handler = Volatile.Read(ref _completedHandler); - EnsureNotClosed(); - return handler; - } - - set - { - EnsureNotClosed(); - - // Try setting completion handler, but only if this has not yet been done: - // (Note: We allow setting Completed to null multiple times iff it has not yet been set to anything else than null. - // Some other WinRT projection languages do not allow setting the Completed handler more than once, even if it is set to null. - // We could do the same by introducing a new STATEFLAG_COMPLETION_HNDL_SET bit-flag constant and saving a this state into - // the m_state field to indicate that the completion handler has been set previously, but we choose not to do this.) - TCompletedHandler? handlerBefore = Interlocked.CompareExchange(ref _completedHandler, value, null); - if (handlerBefore != null) - { - InvalidOperationException ex = new InvalidOperationException(SR.InvalidOperation_CannotSetCompletionHanlderMoreThanOnce); - ex.HResult = __HResults.E_ILLEGAL_DELEGATE_ASSIGNMENT; - throw ex; - } - - if (value == null) - return; - - // If STATEFLAG_MUST_RUN_COMPLETION_HNDL_WHEN_SET is OFF then we are done (i.e. no need to invoke the handler synchronously) - if (0 == (_state & STATEFLAG_MUST_RUN_COMPLETION_HNDL_WHEN_SET)) - return; - - // We have changed the handler and at some point this IAsyncInfo may have transitioned to the Closed state. - // This is OK, but if this happened we need to ensure that we only leave a null handler behind: - if (IsInClosedState) - { - Interlocked.Exchange(ref _completedHandler, null); - return; - } - - // The STATEFLAG_MUST_RUN_COMPLETION_HNDL_WHEN_SET-flag was set, so we need to call the completion handler now: - Debug.Assert(IsInTerminalState); - OnCompletedInvoker(Status); - } - } - - - /// Gets or sets the progress handler. - public virtual TProgressHandler? Progress - { - get - { - TProgressHandler? handler = Volatile.Read(ref _progressHandler); - EnsureNotClosed(); - - return handler; - } - - set - { - EnsureNotClosed(); - - Interlocked.Exchange(ref _progressHandler, value); - - // We transitioned into CLOSED after the above check, we will need to null out m_progressHandler: - if (IsInClosedState) - Interlocked.Exchange(ref _progressHandler, null); - } - } - - - /// Cancels the async info. - public virtual void Cancel() - { - // Cancel will be ignored in any terminal state including CLOSED. - // In other words, it is ignored in any state except STARTED. - - bool stateWasNotStarted; - SetAsyncState(STATE_CANCELLATION_REQUESTED, conditionBitMask: STATE_STARTED, useCondition: true, conditionFailed: out stateWasNotStarted); - - if (!stateWasNotStarted) - { // i.e. if state was different from STATE_STARTED: - if (_cancelTokenSource != null) - _cancelTokenSource.Cancel(); - } - } - - - /// Close the async info. - public virtual void Close() - { - if (IsInClosedState) - return; - - // Cannot Close from a non-terminal state: - if (!IsInTerminalState) - { - // If we are STATE_NOT_INITIALIZED, the we probably threw from the ctor. - // The finalizer will be called anyway and we need to free this partially constructed object correctly. - // So we avoid throwing when we are in STATE_NOT_INITIALIZED. - // In other words throw only if *some* async state is set: - if (0 != (_state & STATEMASK_SELECT_ANY_ASYNC_STATE)) - { - InvalidOperationException ex = new InvalidOperationException(SR.InvalidOperation_IllegalStateChange); - ex.HResult = __HResults.E_ILLEGAL_STATE_CHANGE; - throw ex; - } - } - - TransitionToClosed(); - } - - - /// Gets the error code for the async info. - public virtual Exception? ErrorCode - { - get - { - EnsureNotClosed(); - - // If the task is faulted, hand back an HR representing its first exception. - // Otherwise, hand back S_OK (which is a null Exception). - - if (!IsInErrorState) - return null; - - Exception? error = Volatile.Read(ref _error); - - // ERROR is a terminal state. SO if we have an error, just return it. - // If we completed synchronously, we return the current error iven if it is null since we do not expect this to change: - if (error != null || CompletedSynchronously) - return error; - - Task? task = _dataContainer as Task; - Debug.Assert(task != null); - - AggregateException? aggregateException = task.Exception; - - // By spec, if task.IsFaulted is true, then task.Exception must not be null and its InnerException must - // also not be null. However, in case something is unexpected on the Task side of the road, let?s be defensive - // instead of failing with an inexplicable NullReferenceException: - - if (aggregateException == null) - { - error = new Exception(SR.WinRtCOM_Error); - error.HResult = __HResults.E_FAIL; - } - else - { - Exception? innerException = aggregateException.InnerException; - - error = (innerException == null) - ? aggregateException - : innerException; - } - - // If m_error was set concurrently, setError will be non-null. Then we use that - as it is the first m_error - // that was set. If setError we know that we won any races and we can return error: - Exception? setError = Interlocked.CompareExchange(ref _error, error, null); - return setError ?? error; - } - } - - - public virtual uint Id - { - get - { - EnsureNotClosed(); - - if (_id != AsyncInfoIdGenerator.InvalidId) - return _id; - - return AsyncInfoIdGenerator.EnsureInitializedThreadsafe(ref _id); - } - } - - - /// Gets the status of the async info. - public virtual AsyncStatus Status - { - get - { - EnsureNotClosed(); - return GetStatus(_state); - } - } - #endregion Implementation of IAsyncInfo - } // class TaskToAsyncInfoAdapter -} // namespace - -// TaskToAsyncInfoAdapter.cs diff --git a/src/libraries/System.Runtime.WindowsRuntime/src/System/Threading/Tasks/TaskToAsyncOperationAdapter.cs b/src/libraries/System.Runtime.WindowsRuntime/src/System/Threading/Tasks/TaskToAsyncOperationAdapter.cs deleted file mode 100644 index 63744b6..0000000 --- a/src/libraries/System.Runtime.WindowsRuntime/src/System/Threading/Tasks/TaskToAsyncOperationAdapter.cs +++ /dev/null @@ -1,52 +0,0 @@ -// 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.Diagnostics; -using System.Diagnostics.CodeAnalysis; -using System.Threading; -using System.Threading.Tasks; -using Windows.Foundation; - -namespace System.Threading.Tasks -{ - internal class TaskToAsyncOperationAdapter - : TaskToAsyncInfoAdapter, VoidReferenceTypeParameter, TResult, VoidValueTypeParameter>, - IAsyncOperation - { - internal TaskToAsyncOperationAdapter(Delegate taskGenerator) - - : base(taskGenerator) - { - } - - - internal TaskToAsyncOperationAdapter(Task underlyingTask, CancellationTokenSource? underlyingCancelTokenSource) - - : base(underlyingTask, underlyingCancelTokenSource, underlyingProgressDispatcher: null) - { - } - - - internal TaskToAsyncOperationAdapter([AllowNull] TResult synchronousResult) - - : base(synchronousResult) - { - } - - public virtual TResult GetResults() - { - return GetResultsInternal(); - } - - - internal override void OnCompleted(AsyncOperationCompletedHandler userCompletionHandler, AsyncStatus asyncStatus) - { - Debug.Assert(userCompletionHandler != null); - userCompletionHandler(this, asyncStatus); - } - } // class TaskToAsyncOperationAdapter -} // namespace - -// TaskToAsyncOperationAdapter.cs diff --git a/src/libraries/System.Runtime.WindowsRuntime/src/System/Threading/Tasks/TaskToAsyncOperationWithProgressAdapter.cs b/src/libraries/System.Runtime.WindowsRuntime/src/System/Threading/Tasks/TaskToAsyncOperationWithProgressAdapter.cs deleted file mode 100644 index 7a1ce71..0000000 --- a/src/libraries/System.Runtime.WindowsRuntime/src/System/Threading/Tasks/TaskToAsyncOperationWithProgressAdapter.cs +++ /dev/null @@ -1,65 +0,0 @@ -// 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.Diagnostics; -using System.Diagnostics.CodeAnalysis; -using System.Threading; -using System.Threading.Tasks; -using Windows.Foundation; - -namespace System.Threading.Tasks -{ - internal class TaskToAsyncOperationWithProgressAdapter - : TaskToAsyncInfoAdapter, - AsyncOperationProgressHandler, - TResult, - TProgress>, - IAsyncOperationWithProgress - { - internal TaskToAsyncOperationWithProgressAdapter(Delegate taskGenerator) - - : base(taskGenerator) - { - } - - // This is currently not used, so commented out to save code. - // Leaving this is the source to be uncommented in case we decide to support IAsyncOperationWithProgress-consturction from a Task. - // - //internal TaskToAsyncOperationWithProgressAdapter(Task underlyingTask, CancellationTokenSource underlyingCancelTokenSource, - // Progress underlyingProgressDispatcher) - // - // : base(underlyingTask, underlyingCancelTokenSource, underlyingProgressDispatcher) { - //} - - - internal TaskToAsyncOperationWithProgressAdapter([AllowNull] TResult synchronousResult) - - : base(synchronousResult) - { - } - - public virtual TResult GetResults() - { - return GetResultsInternal(); - } - - - internal override void OnCompleted(AsyncOperationWithProgressCompletedHandler userCompletionHandler, - AsyncStatus asyncStatus) - { - Debug.Assert(userCompletionHandler != null); - userCompletionHandler(this, asyncStatus); - } - - - internal override void OnProgress(AsyncOperationProgressHandler userProgressHandler, TProgress progressInfo) - { - Debug.Assert(userProgressHandler != null); - userProgressHandler(this, progressInfo); - } - } // class TaskToAsyncOperationWithProgressAdapter -} // namespace - -// TaskToAsyncOperationWithProgressAdapter.cs diff --git a/src/libraries/System.Runtime.WindowsRuntime/src/System/Threading/WindowsRuntimeSynchronizationContext.cs b/src/libraries/System.Runtime.WindowsRuntime/src/System/Threading/WindowsRuntimeSynchronizationContext.cs deleted file mode 100644 index da60f6a..0000000 --- a/src/libraries/System.Runtime.WindowsRuntime/src/System/Threading/WindowsRuntimeSynchronizationContext.cs +++ /dev/null @@ -1,222 +0,0 @@ -// 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 Internal.Runtime.InteropServices.WindowsRuntime; -using System; -using System.Diagnostics; -using System.Diagnostics.Tracing; -using System.Reflection; -using System.Runtime.CompilerServices; -using System.Runtime.ExceptionServices; -using System.Runtime.InteropServices; -using System.Runtime.InteropServices.WindowsRuntime; -using System.Security; -using System.Threading; -using Windows.Foundation; -using Windows.UI.Core; - -namespace System.Threading -{ -#if FEATURE_APPX - [WindowsRuntimeImport] - [Guid("DFA2DC9C-1A2D-4917-98F2-939AF1D6E0C8")] - public delegate void DispatcherQueueHandler(); - - public enum DispatcherQueuePriority - { - Low = -10, - Normal = 0, - High = 10 - } - - [ComImport] - [WindowsRuntimeImport] - [Guid("603E88E4-A338-4FFE-A457-A5CFB9CEB899")] - internal interface IDispatcherQueue - { - // This returns a DispatcherQueueTimer but we don't use this method, so I - // just made it 'object' to avoid declaring it. - object CreateTimer(); - - bool TryEnqueue(DispatcherQueueHandler callback); - - bool TryEnqueue(DispatcherQueuePriority priority, DispatcherQueueHandler callback); - } - - #region class WinRTSynchronizationContextFactory - - internal sealed class WinRTSynchronizationContextFactory - { - // - // It's important that we always return the same SynchronizationContext object for any particular ICoreDispatcher - // object, as long as any existing instance is still reachable. This allows reference equality checks against the - // SynchronizationContext to determine if two instances represent the same dispatcher. Async frameworks rely on this. - // To accomplish this, we use a ConditionalWeakTable to track which instances of WinRTSynchronizationContext are bound - // to each ICoreDispatcher instance. - // - private static readonly ConditionalWeakTable s_coreDispatcherContextCache = - new ConditionalWeakTable(); - - private static readonly ConditionalWeakTable s_dispatcherQueueContextCache = - new ConditionalWeakTable(); - - // System.Private.Corelib will call WinRTSynchronizationContextFactory.Create() via reflection - public static SynchronizationContext Create(object dispatcherObj) - { - Debug.Assert(dispatcherObj != null); - Debug.Assert(dispatcherObj is CoreDispatcher || dispatcherObj is IDispatcherQueue); - - if (dispatcherObj is CoreDispatcher) - { - // - // Get the RCW for the dispatcher - // - CoreDispatcher dispatcher = (CoreDispatcher)dispatcherObj; - - // - // The dispatcher is supposed to belong to this thread - // - Debug.Assert(dispatcher == CoreWindow.GetForCurrentThread().Dispatcher); - Debug.Assert(dispatcher.HasThreadAccess); - - // - // Get the WinRTSynchronizationContext instance that represents this CoreDispatcher. - // - return s_coreDispatcherContextCache.GetValue(dispatcher, _dispatcher => new WinRTCoreDispatcherBasedSynchronizationContext(_dispatcher)); - } - else // dispatcherObj is IDispatcherQueue - { - // - // Get the RCW for the dispatcher - // - IDispatcherQueue dispatcherQueue = (IDispatcherQueue)dispatcherObj; - - // - // Get the WinRTSynchronizationContext instance that represents this IDispatcherQueue. - // - return s_dispatcherQueueContextCache.GetValue(dispatcherQueue, _dispatcherQueue => new WinRTDispatcherQueueBasedSynchronizationContext(_dispatcherQueue)); - } - } - } - - #endregion class WinRTSynchronizationContextFactory - - - #region class WinRTSynchronizationContext - - internal sealed class WinRTCoreDispatcherBasedSynchronizationContext : WinRTSynchronizationContextBase - { - private readonly CoreDispatcher _dispatcher; - internal WinRTCoreDispatcherBasedSynchronizationContext(CoreDispatcher dispatcher) - { - _dispatcher = dispatcher; - } - - public override void Post(SendOrPostCallback d, object? state) - { - if (d == null) - throw new ArgumentNullException(nameof(d)); - - _ = _dispatcher.RunAsync(CoreDispatcherPriority.Normal, new Invoker(d, state).Invoke); - } - - public override SynchronizationContext CreateCopy() - { - return new WinRTCoreDispatcherBasedSynchronizationContext(_dispatcher); - } - } - - internal sealed class WinRTDispatcherQueueBasedSynchronizationContext : WinRTSynchronizationContextBase - { - private readonly IDispatcherQueue _dispatcherQueue; - internal WinRTDispatcherQueueBasedSynchronizationContext(IDispatcherQueue dispatcherQueue) - { - _dispatcherQueue = dispatcherQueue; - } - - public override void Post(SendOrPostCallback d, object? state) - { - if (d == null) - throw new ArgumentNullException(nameof(d)); - - // We explicitly choose to ignore the return value here. This enqueue operation might fail if the - // dispatcher queue was shut down before we got here. In that case, we choose to just move on and - // pretend nothing happened. - _ = _dispatcherQueue.TryEnqueue(DispatcherQueuePriority.Normal, new Invoker(d, state).Invoke); - } - - public override SynchronizationContext CreateCopy() - { - return new WinRTDispatcherQueueBasedSynchronizationContext(_dispatcherQueue); - } - } - - internal abstract class WinRTSynchronizationContextBase : SynchronizationContext - { - #region class WinRTSynchronizationContext.Invoker - - protected class Invoker - { - private readonly ExecutionContext? _executionContext; - private readonly SendOrPostCallback _callback; - private readonly object? _state; - - private static readonly ContextCallback s_contextCallback = new ContextCallback(InvokeInContext); - - public Invoker(SendOrPostCallback callback, object? state) - { - _executionContext = ExecutionContext.Capture(); - _callback = callback; - _state = state; - } - - public void Invoke() - { - if (_executionContext == null) - InvokeCore(); - else - ExecutionContext.Run(_executionContext, s_contextCallback, this); - } - - private static void InvokeInContext(object? thisObj) - { - ((Invoker)thisObj!).InvokeCore(); - } - - private void InvokeCore() - { - try - { - _callback(_state); - } - catch (Exception ex) - { - // - // If we let exceptions propagate to CoreDispatcher, it will swallow them with the idea that someone will - // observe them later using the IAsyncInfo returned by CoreDispatcher.RunAsync. However, we ignore - // that IAsyncInfo, because there's nothing Post can do with it (since Post returns void). - // So, to avoid these exceptions being lost forever, we post them to the ThreadPool. - // - if (!(ex is ThreadAbortException)) - { - if (!ExceptionSupport.ReportUnhandledError(ex)) - { - var edi = ExceptionDispatchInfo.Capture(ex); - ThreadPool.QueueUserWorkItem(o => ((ExceptionDispatchInfo)o!).Throw(), edi); - } - } - } - } - } - - #endregion class WinRTSynchronizationContext.Invoker - - public override void Send(SendOrPostCallback d, object? state) - { - throw new NotSupportedException(SR.InvalidOperation_SendNotSupportedOnWindowsRTSynchronizationContext); - } - } - #endregion class WinRTSynchronizationContext -#endif //FEATURE_APPX -} // namespace diff --git a/src/libraries/System.Runtime.WindowsRuntime/src/System/VoidTypeParameter.cs b/src/libraries/System.Runtime.WindowsRuntime/src/System/VoidTypeParameter.cs deleted file mode 100644 index 196a041..0000000 --- a/src/libraries/System.Runtime.WindowsRuntime/src/System/VoidTypeParameter.cs +++ /dev/null @@ -1,14 +0,0 @@ -// 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 System -{ - /// Empty struct used as placeholder for generic type parameters when none is needed. - internal struct VoidValueTypeParameter { } - - /// This can be used instead of VoidValueTypeParameter when a reference type is required. - /// In case of an actual instantiation (e.g. through default(T)), - /// using VoidValueTypeParameter offers better performance. - internal class VoidReferenceTypeParameter { } -} // namespace diff --git a/src/libraries/System.Runtime.WindowsRuntime/src/System/Windows/Point.cs b/src/libraries/System.Runtime.WindowsRuntime/src/System/Windows/Point.cs deleted file mode 100644 index 505b40d..0000000 --- a/src/libraries/System.Runtime.WindowsRuntime/src/System/Windows/Point.cs +++ /dev/null @@ -1,118 +0,0 @@ -// 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.Globalization; -using System.Runtime.InteropServices; - -#if !FEATURE_SLJ_PROJECTION_COMPAT -#pragma warning disable 436 // Redefining types from Windows.Foundation -#endif // !FEATURE_SLJ_PROJECTION_COMPAT - -#if FEATURE_SLJ_PROJECTION_COMPAT -namespace System.Windows -#else // !FEATURE_SLJ_PROJECTION_COMPAT - - -namespace Windows.Foundation -#endif // FEATURE_SLJ_PROJECTION_COMPAT -{ - // - // Point is the managed projection of Windows.Foundation.Point. Any changes to the layout - // of this type must be exactly mirrored on the native WinRT side as well. - // - // Note that this type is owned by the Jupiter team. Please contact them before making any - // changes here. - // - - [StructLayout(LayoutKind.Sequential)] - public struct Point : IFormattable - { - internal float _x; - internal float _y; - - public Point(double x, double y) - { - _x = (float)x; - _y = (float)y; - } - - public double X - { - get { return _x; } - set { _x = (float)value; } - } - - public double Y - { - get { return _y; } - set { _y = (float)value; } - } - - public override string ToString() - { - // Delegate to the internal method which implements all ToString calls. - return ConvertToString(null /* format string */, null /* format provider */); - } - - public string ToString(IFormatProvider? provider) - { - // Delegate to the internal method which implements all ToString calls. - return ConvertToString(null /* format string */, provider); - } - - string IFormattable.ToString(string? format, IFormatProvider? provider) - { - // Delegate to the internal method which implements all ToString calls. - return ConvertToString(format, provider); - } - - private string ConvertToString(string? format, IFormatProvider? provider) - { - // Helper to get the numeric list separator for a given culture. - char separator = TokenizerHelper.GetNumericListSeparator(provider); - return string.Format(provider, - "{1:" + format + "}{0}{2:" + format + "}", - separator, - _x, - _y); - } - - public static bool operator ==(Point point1, Point point2) - { - return point1.X == point2.X && - point1.Y == point2.Y; - } - - public static bool operator !=(Point point1, Point point2) - { - return !(point1 == point2); - } - - public override bool Equals(object? o) - { - return o is Point && this == (Point)o; - } - - public bool Equals(Point value) - { - return (this == value); - } - - public override int GetHashCode() - { - // Perform field-by-field XOR of HashCodes - return X.GetHashCode() ^ - Y.GetHashCode(); - } - } -} - -#if !FEATURE_SLJ_PROJECTION_COMPAT -#pragma warning restore 436 -#endif // !FEATURE_SLJ_PROJECTION_COMPAT diff --git a/src/libraries/System.Runtime.WindowsRuntime/src/System/Windows/Rect.cs b/src/libraries/System.Runtime.WindowsRuntime/src/System/Windows/Rect.cs deleted file mode 100644 index 4ea7cb8..0000000 --- a/src/libraries/System.Runtime.WindowsRuntime/src/System/Windows/Rect.cs +++ /dev/null @@ -1,350 +0,0 @@ -// 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.Globalization; -using System.Runtime.InteropServices; - -#if !FEATURE_SLJ_PROJECTION_COMPAT -#pragma warning disable 436 // Redefining types from Windows.Foundation -#endif // !FEATURE_SLJ_PROJECTION_COMPAT - -#if FEATURE_SLJ_PROJECTION_COMPAT -namespace System.Windows -#else // !FEATURE_SLJ_PROJECTION_COMPAT - - -namespace Windows.Foundation -#endif // FEATURE_SLJ_PROJECTION_COMPAT -{ - // - // Rect is the managed projection of Windows.Foundation.Rect. Any changes to the layout - // of this type must be exactly mirrored on the native WinRT side as well. - // - // Note that this type is owned by the Jupiter team. Please contact them before making any - // changes here. - // - - [StructLayout(LayoutKind.Sequential)] - public struct Rect : IFormattable - { - private float _x; - private float _y; - private float _width; - private float _height; - - private const double EmptyX = double.PositiveInfinity; - private const double EmptyY = double.PositiveInfinity; - private const double EmptyWidth = double.NegativeInfinity; - private const double EmptyHeight = double.NegativeInfinity; - - private static readonly Rect s_empty = CreateEmptyRect(); - - public Rect(double x, - double y, - double width, - double height) - { - if (width < 0) - throw new ArgumentOutOfRangeException(nameof(width), SR.ArgumentOutOfRange_NeedNonNegNum); - if (height < 0) - throw new ArgumentOutOfRangeException(nameof(height), SR.ArgumentOutOfRange_NeedNonNegNum); - - _x = (float)x; - _y = (float)y; - _width = (float)width; - _height = (float)height; - } - - public Rect(Point point1, - Point point2) - { - _x = (float)Math.Min(point1.X, point2.X); - _y = (float)Math.Min(point1.Y, point2.Y); - - _width = (float)Math.Max(Math.Max(point1.X, point2.X) - _x, 0); - _height = (float)Math.Max(Math.Max(point1.Y, point2.Y) - _y, 0); - } - - public Rect(Point location, Size size) - { - if (size.IsEmpty) - { - this = s_empty; - } - else - { - _x = (float)location.X; - _y = (float)location.Y; - _width = (float)size.Width; - _height = (float)size.Height; - } - } - - public double X - { - get { return _x; } - set { _x = (float)value; } - } - - public double Y - { - get { return _y; } - set { _y = (float)value; } - } - - public double Width - { - get { return _width; } - set - { - if (value < 0) - throw new ArgumentOutOfRangeException(nameof(Width), SR.ArgumentOutOfRange_NeedNonNegNum); - - _width = (float)value; - } - } - - public double Height - { - get { return _height; } - set - { - if (value < 0) - throw new ArgumentOutOfRangeException(nameof(Height), SR.ArgumentOutOfRange_NeedNonNegNum); - - _height = (float)value; - } - } - - public double Left - { - get { return _x; } - } - - public double Top - { - get { return _y; } - } - - public double Right - { - get - { - if (IsEmpty) - { - return double.NegativeInfinity; - } - - return _x + _width; - } - } - - public double Bottom - { - get - { - if (IsEmpty) - { - return double.NegativeInfinity; - } - - return _y + _height; - } - } - - public static Rect Empty - { - get { return s_empty; } - } - - public bool IsEmpty - { - get { return _width < 0; } - } - - public bool Contains(Point point) - { - return ContainsInternal(point.X, point.Y); - } - - public void Intersect(Rect rect) - { - if (!this.IntersectsWith(rect)) - { - this = s_empty; - } - else - { - double left = Math.Max(X, rect.X); - double top = Math.Max(Y, rect.Y); - - // Max with 0 to prevent double weirdness from causing us to be (-epsilon..0) - Width = Math.Max(Math.Min(X + Width, rect.X + rect.Width) - left, 0); - Height = Math.Max(Math.Min(Y + Height, rect.Y + rect.Height) - top, 0); - - X = left; - Y = top; - } - } - - public void Union(Rect rect) - { - if (IsEmpty) - { - this = rect; - } - else if (!rect.IsEmpty) - { - double left = Math.Min(Left, rect.Left); - double top = Math.Min(Top, rect.Top); - - - // We need this check so that the math does not result in NaN - if ((rect.Width == double.PositiveInfinity) || (Width == double.PositiveInfinity)) - { - Width = double.PositiveInfinity; - } - else - { - // Max with 0 to prevent double weirdness from causing us to be (-epsilon..0) - double maxRight = Math.Max(Right, rect.Right); - Width = Math.Max(maxRight - left, 0); - } - - // We need this check so that the math does not result in NaN - if ((rect.Height == double.PositiveInfinity) || (Height == double.PositiveInfinity)) - { - Height = double.PositiveInfinity; - } - else - { - // Max with 0 to prevent double weirdness from causing us to be (-epsilon..0) - double maxBottom = Math.Max(Bottom, rect.Bottom); - Height = Math.Max(maxBottom - top, 0); - } - - X = left; - Y = top; - } - } - - public void Union(Point point) - { - Union(new Rect(point, point)); - } - - private bool ContainsInternal(double x, double y) - { - return ((x >= X) && (x - Width <= X) && - (y >= Y) && (y - Height <= Y)); - } - - internal bool IntersectsWith(Rect rect) - { - if (Width < 0 || rect.Width < 0) - { - return false; - } - - return (rect.X <= X + Width) && - (rect.X + rect.Width >= X) && - (rect.Y <= Y + Height) && - (rect.Y + rect.Height >= Y); - } - - private static Rect CreateEmptyRect() - { - Rect rect = default; - - // TODO: for consistency with width/height we should change these - // to assign directly to the backing fields. - rect.X = EmptyX; - rect.Y = EmptyY; - - // the width and height properties prevent assignment of - // negative numbers so assign directly to the backing fields. - rect._width = (float)EmptyWidth; - rect._height = (float)EmptyHeight; - - return rect; - } - - public override string ToString() - { - // Delegate to the internal method which implements all ToString calls. - return ConvertToString(null /* format string */, null /* format provider */); - } - - public string ToString(IFormatProvider? provider) - { - // Delegate to the internal method which implements all ToString calls. - return ConvertToString(null /* format string */, provider); - } - - string IFormattable.ToString(string? format, IFormatProvider? provider) - { - // Delegate to the internal method which implements all ToString calls. - return ConvertToString(format, provider); - } - - internal string ConvertToString(string? format, IFormatProvider? provider) - { - if (IsEmpty) - { - return SR.DirectUI_Empty; - } - - // Helper to get the numeric list separator for a given culture. - char separator = TokenizerHelper.GetNumericListSeparator(provider); - return string.Format(provider, - "{1:" + format + "}{0}{2:" + format + "}{0}{3:" + format + "}{0}{4:" + format + "}", - separator, - _x, - _y, - _width, - _height); - } - - public bool Equals(Rect value) - { - return (this == value); - } - - public static bool operator ==(Rect rect1, Rect rect2) - { - return rect1.X == rect2.X && - rect1.Y == rect2.Y && - rect1.Width == rect2.Width && - rect1.Height == rect2.Height; - } - - public static bool operator !=(Rect rect1, Rect rect2) - { - return !(rect1 == rect2); - } - - public override bool Equals(object? o) - { - return o is Rect && this == (Rect)o; - } - - public override int GetHashCode() - { - // Perform field-by-field XOR of HashCodes - return X.GetHashCode() ^ - Y.GetHashCode() ^ - Width.GetHashCode() ^ - Height.GetHashCode(); - } - } -} - -#if !FEATURE_SLJ_PROJECTION_COMPAT -#pragma warning restore 436 -#endif // !FEATURE_SLJ_PROJECTION_COMPAT diff --git a/src/libraries/System.Runtime.WindowsRuntime/src/System/Windows/Size.cs b/src/libraries/System.Runtime.WindowsRuntime/src/System/Windows/Size.cs deleted file mode 100644 index 39e73f9..0000000 --- a/src/libraries/System.Runtime.WindowsRuntime/src/System/Windows/Size.cs +++ /dev/null @@ -1,157 +0,0 @@ -// 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.InteropServices; - -#if !FEATURE_SLJ_PROJECTION_COMPAT -#pragma warning disable 436 // Redefining types from Windows.Foundation -#endif // !FEATURE_SLJ_PROJECTION_COMPAT - -#if FEATURE_SLJ_PROJECTION_COMPAT -namespace System.Windows -#else // !FEATURE_SLJ_PROJECTION_COMPAT - - -namespace Windows.Foundation -#endif // FEATURE_SLJ_PROJECTION_COMPAT -{ - // - // Size is the managed projection of Windows.Foundation.Size. Any changes to the layout - // of this type must be exactly mirrored on the native WinRT side as well. - // - // Note that this type is owned by the Jupiter team. Please contact them before making any - // changes here. - // - - [StructLayout(LayoutKind.Sequential)] - public struct Size - { - private float _width; - private float _height; - - private static readonly Size s_empty = CreateEmptySize(); - - public Size(double width, double height) - { - if (width < 0) - throw new ArgumentOutOfRangeException(nameof(width), SR.ArgumentOutOfRange_NeedNonNegNum); - if (height < 0) - throw new ArgumentOutOfRangeException(nameof(height), SR.ArgumentOutOfRange_NeedNonNegNum); - _width = (float)width; - _height = (float)height; - } - - public double Width - { - get { return _width; } - set - { - if (value < 0) - throw new ArgumentOutOfRangeException(nameof(Width), SR.ArgumentOutOfRange_NeedNonNegNum); - - _width = (float)value; - } - } - - public double Height - { - get { return _height; } - set - { - if (value < 0) - throw new ArgumentOutOfRangeException(nameof(Height), SR.ArgumentOutOfRange_NeedNonNegNum); - - _height = (float)value; - } - } - - public static Size Empty - { - get { return s_empty; } - } - - - public bool IsEmpty - { - get { return Width < 0; } - } - - private static Size CreateEmptySize() - { - Size size = default; - // We can't set these via the property setters because negatives widths - // are rejected in those APIs. - size._width = float.NegativeInfinity; - size._height = float.NegativeInfinity; - return size; - } - - public static bool operator ==(Size size1, Size size2) - { - return size1.Width == size2.Width && - size1.Height == size2.Height; - } - - public static bool operator !=(Size size1, Size size2) - { - return !(size1 == size2); - } - - public override bool Equals(object? o) - { - return o is Size && Size.Equals(this, (Size)o); - } - - public bool Equals(Size value) - { - return Size.Equals(this, value); - } - - public override int GetHashCode() - { - if (IsEmpty) - { - return 0; - } - else - { - // Perform field-by-field XOR of HashCodes - return Width.GetHashCode() ^ - Height.GetHashCode(); - } - } - - private static bool Equals(Size size1, Size size2) - { - if (size1.IsEmpty) - { - return size2.IsEmpty; - } - else - { - return size1.Width.Equals(size2.Width) && - size1.Height.Equals(size2.Height); - } - } - - public override string ToString() - { - if (IsEmpty) - { - return "Empty"; - } - - return string.Format("{0},{1}", _width, _height); - } - } -} - -#if !FEATURE_SLJ_PROJECTION_COMPAT -#pragma warning restore 436 -#endif // !FEATURE_SLJ_PROJECTION_COMPAT diff --git a/src/libraries/System.Runtime.WindowsRuntime/src/System/Windows/TokenizerHelper.cs b/src/libraries/System.Runtime.WindowsRuntime/src/System/Windows/TokenizerHelper.cs deleted file mode 100644 index c93ce56..0000000 --- a/src/libraries/System.Runtime.WindowsRuntime/src/System/Windows/TokenizerHelper.cs +++ /dev/null @@ -1,55 +0,0 @@ -// 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.Globalization; -using System.Runtime.InteropServices; - -#if !FEATURE_SLJ_PROJECTION_COMPAT -#pragma warning disable 436 // Redefining types from Windows.Foundation -#endif // !FEATURE_SLJ_PROJECTION_COMPAT - -#if FEATURE_SLJ_PROJECTION_COMPAT -namespace System.Windows -#else // !FEATURE_SLJ_PROJECTION_COMPAT - - -namespace Windows.Foundation -#endif // FEATURE_SLJ_PROJECTION_COMPAT -{ - // - // Note that this type is owned by the Jupiter team. Please contact them before making any - // changes here. - // - - internal static class TokenizerHelper - { - internal static char GetNumericListSeparator(IFormatProvider? provider) - { - char numericSeparator = ','; - - // Get the NumberFormatInfo out of the provider, if possible - // If the IFormatProvider doesn't not contain a NumberFormatInfo, then - // this method returns the current culture's NumberFormatInfo. - NumberFormatInfo numberFormat = NumberFormatInfo.GetInstance(provider); - - // Is the decimal separator is the same as the list separator? - // If so, we use the ";". - if ((numberFormat.NumberDecimalSeparator.Length > 0) && (numericSeparator == numberFormat.NumberDecimalSeparator[0])) - { - numericSeparator = ';'; - } - - return numericSeparator; - } - } -} - -#if !FEATURE_SLJ_PROJECTION_COMPAT -#pragma warning restore 436 -#endif // !FEATURE_SLJ_PROJECTION_COMPAT diff --git a/src/libraries/System.Runtime.WindowsRuntime/src/System/Windows/UI/Color.cs b/src/libraries/System.Runtime.WindowsRuntime/src/System/Windows/UI/Color.cs deleted file mode 100644 index 72574c4..0000000 --- a/src/libraries/System.Runtime.WindowsRuntime/src/System/Windows/UI/Color.cs +++ /dev/null @@ -1,153 +0,0 @@ -// 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.InteropServices; -using System.Text; -using Windows.Foundation; - -#if !FEATURE_SLJ_PROJECTION_COMPAT -#pragma warning disable 436 // Redefining types from Windows.Foundation -#endif // !FEATURE_SLJ_PROJECTION_COMPAT - -#if FEATURE_SLJ_PROJECTION_COMPAT -namespace System.Windows -#else // !FEATURE_SLJ_PROJECTION_COMPAT - - -namespace Windows.UI -#endif // FEATURE_SLJ_PROJECTION_COMPAT -{ - // - // Color is the managed projection of Windows.Foundation.Color. Any changes to the layout of - // this type must be exactly mirrored on the native WinRT side as well. - // - // Note that this type is owned by the Jupiter team. Please contact them before making any - // changes here. - // - - [StructLayout(LayoutKind.Sequential)] - public struct Color : IFormattable - { - private byte _A; - private byte _R; - private byte _G; - private byte _B; - - public static Color FromArgb(byte a, byte r, byte g, byte b) - { - Color c1 = default; - - c1.A = a; - c1.R = r; - c1.G = g; - c1.B = b; - - return c1; - } - - public byte A - { - get { return _A; } - set { _A = value; } - } - - public byte R - { - get { return _R; } - set { _R = value; } - } - - public byte G - { - get { return _G; } - set { _G = value; } - } - - public byte B - { - get { return _B; } - set { _B = value; } - } - - public override string ToString() - { - // Delegate to the internal method which implements all ToString calls. - return ConvertToString(null, null); - } - - public string ToString(IFormatProvider? provider) - { - // Delegate to the internal method which implements all ToString calls. - return ConvertToString(null, provider); - } - - string IFormattable.ToString(string? format, IFormatProvider? provider) - { - // Delegate to the internal method which implements all ToString calls. - return ConvertToString(format, provider); - } - - internal string ConvertToString(string? format, IFormatProvider? provider) - { - StringBuilder sb = new StringBuilder(); - - if (format == null) - { - sb.AppendFormat(provider, "#{0:X2}", _A); - sb.AppendFormat(provider, "{0:X2}", _R); - sb.AppendFormat(provider, "{0:X2}", _G); - sb.AppendFormat(provider, "{0:X2}", _B); - } - else - { - // Helper to get the numeric list separator for a given culture. - char separator = TokenizerHelper.GetNumericListSeparator(provider); - - sb.AppendFormat(provider, - "sc#{1:" + format + "}{0} {2:" + format + "}{0} {3:" + format + "}{0} {4:" + format + "}", - separator, _A, _R, _G, _B); - } - - return sb.ToString(); - } - - public override int GetHashCode() - { - return _A.GetHashCode() ^ _R.GetHashCode() ^ _G.GetHashCode() ^ _B.GetHashCode(); - } - - public override bool Equals(object? o) - { - return o is Color && this == (Color)o; - } - - public bool Equals(Color color) - { - return this == color; - } - - public static bool operator ==(Color color1, Color color2) - { - return - color1.R == color2.R && - color1.G == color2.G && - color1.B == color2.B && - color1.A == color2.A; - } - - public static bool operator !=(Color color1, Color color2) - { - return (!(color1 == color2)); - } - } -} - -#if !FEATURE_SLJ_PROJECTION_COMPAT -#pragma warning restore 436 -#endif // !FEATURE_SLJ_PROJECTION_COMPAT diff --git a/src/libraries/System.Runtime.WindowsRuntime/src/System/WindowsRuntimeSystemExtensions.cs b/src/libraries/System.Runtime.WindowsRuntime/src/System/WindowsRuntimeSystemExtensions.cs deleted file mode 100644 index 6a0f150..0000000 --- a/src/libraries/System.Runtime.WindowsRuntime/src/System/WindowsRuntimeSystemExtensions.cs +++ /dev/null @@ -1,461 +0,0 @@ -// 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 Internal.Runtime.InteropServices.WindowsRuntime; -using System.ComponentModel; -using System.Diagnostics; -using System.Runtime.CompilerServices; -using System.Runtime.InteropServices.WindowsRuntime; -using System.Threading; -using System.Threading.Tasks; -using Windows.Foundation; - -namespace System -{ - /// Provides extension methods in the System namespace for working with the Windows Runtime.
- /// Currently contains:
- ///
    - ///
  • Extension methods for conversion between Windows.Foundation.IAsyncInfo and deriving generic interfaces - /// and System.Threading.Tasks.Task.
  • - ///
  • Extension methods for conversion between System.Threading.Tasks.Task - /// and Windows.Foundation.IAsyncInfo and deriving generic interfaces.
  • - ///
- [CLSCompliant(false)] - public static class WindowsRuntimeSystemExtensions - { - #region Converters from Windows.Foundation.IAsyncInfo (and interfaces that derive from it) to System.Threading.Tasks.Task - - #region Convenience Helpers - - private static void ConcatenateCancelTokens(CancellationToken source, CancellationTokenSource sink, Task concatenationLifetime) - { - Debug.Assert(sink != null); - - CancellationTokenRegistration ctReg = source.Register((state) => { ((CancellationTokenSource)state!).Cancel(); }, - sink); - - concatenationLifetime.ContinueWith((_, state) => { ((CancellationTokenRegistration)state!).Dispose(); }, - ctReg, CancellationToken.None, TaskContinuationOptions.ExecuteSynchronously, TaskScheduler.Default); - } - - - private static void ConcatenateProgress(IAsyncActionWithProgress source, IProgress sink) - { - // This is separated out into a separate method so that we only pay the costs of compiler-generated closure if progress is non-null. - source.Progress += new AsyncActionProgressHandler((_, info) => sink.Report(info)); - } - - - private static void ConcatenateProgress(IAsyncOperationWithProgress source, IProgress sink) - { - // This is separated out into a separate method so that we only pay the costs of compiler-generated closure if progress is non-null. - source.Progress += new AsyncOperationProgressHandler((_, info) => sink.Report(info)); - } - - #endregion Convenience Helpers - - - #region Converters from IAsyncAction to Task - - /// Gets an awaiter used to await this asynchronous operation. - /// An awaiter instance. - /// This method is intended for compiler user rather than use directly in code. - [EditorBrowsable(EditorBrowsableState.Never)] - public static TaskAwaiter GetAwaiter(this IAsyncAction source) - { - return AsTask(source).GetAwaiter(); - } - - - /// Gets a Task to represent the asynchronous operation. - /// The asynchronous operation. - /// The Task representing the asynchronous operation. - public static Task AsTask(this IAsyncAction source) - { - return AsTask(source, CancellationToken.None); - } - - - /// Gets a Task to represent the asynchronous operation. - /// The asynchronous operation. - /// The token used to request cancellation of the asynchronous operation. - /// The Task representing the asynchronous operation. - public static Task AsTask(this IAsyncAction source, CancellationToken cancellationToken) - { - if (source == null) - throw new ArgumentNullException(nameof(source)); - - // If source is actually a NetFx-to-WinRT adapter, unwrap it instead of creating a new Task: - var wrapper = source as TaskToAsyncActionAdapter; - if (wrapper != null && !wrapper.CompletedSynchronously) - { - Task? innerTask = wrapper.Task; - Debug.Assert(innerTask != null); - Debug.Assert(innerTask.Status != TaskStatus.Created); - - if (!innerTask.IsCompleted) - { - // The race here is benign: If the task completes here, the concatination is useless, but not damaging. - if (cancellationToken.CanBeCanceled && wrapper.CancelTokenSource != null) - ConcatenateCancelTokens(cancellationToken, wrapper.CancelTokenSource, innerTask); - } - - return innerTask; - } - - // Fast path to return a completed Task if the operation has already completed: - switch (source.Status) - { - case AsyncStatus.Completed: - return Task.CompletedTask; - - case AsyncStatus.Error: - return Task.FromException(ExceptionSupport.AttachRestrictedErrorInfo(source.ErrorCode)); - - case AsyncStatus.Canceled: - return Task.FromCanceled(cancellationToken.IsCancellationRequested ? cancellationToken : new CancellationToken(true)); - } - - // Benign race: source may complete here. Things still work, just not taking the fast path. - - // Source is not a NetFx-to-WinRT adapter, but a native future. Hook up the task: - var bridge = new AsyncInfoToTaskBridge(cancellationToken); - - source.Completed = new AsyncActionCompletedHandler(bridge.CompleteFromAsyncAction); - bridge.RegisterForCancellation(source); - return bridge.Task; - } - - #endregion Converters from IAsyncAction to Task - - - #region Converters from IAsyncOperation to Task - - /// Gets an awaiter used to await this asynchronous operation. - /// An awaiter instance. - /// This method is intended for compiler user rather than use directly in code. - [EditorBrowsable(EditorBrowsableState.Never)] - public static TaskAwaiter GetAwaiter(this IAsyncOperation source) - { - return AsTask(source).GetAwaiter(); - } - - - /// Gets a Task to represent the asynchronous operation. - /// The asynchronous operation. - /// The Task representing the asynchronous operation. - public static Task AsTask(this IAsyncOperation source) - { - return AsTask(source, CancellationToken.None); - } - - - /// Gets a Task to represent the asynchronous operation. - /// The asynchronous operation. - /// The token used to request cancellation of the asynchronous operation. - /// The Task representing the asynchronous operation. - public static Task AsTask(this IAsyncOperation source, CancellationToken cancellationToken) - { - if (source == null) - throw new ArgumentNullException(nameof(source)); - - // If source is actually a NetFx-to-WinRT adapter, unwrap it instead of creating a new Task: - var wrapper = source as TaskToAsyncOperationAdapter; - if (wrapper != null && !wrapper.CompletedSynchronously) - { - Task? innerTask = wrapper.Task as Task; - Debug.Assert(innerTask != null); - Debug.Assert(innerTask.Status != TaskStatus.Created); // Is WaitingForActivation a legal state at this moment? - - if (!innerTask.IsCompleted) - { - // The race here is benign: If the task completes here, the concatination is useless, but not damaging. - if (cancellationToken.CanBeCanceled && wrapper.CancelTokenSource != null) - ConcatenateCancelTokens(cancellationToken, wrapper.CancelTokenSource, innerTask); - } - - return innerTask; - } - - // Fast path to return a completed Task if the operation has already completed - switch (source.Status) - { - case AsyncStatus.Completed: - return Task.FromResult(source.GetResults()); - - case AsyncStatus.Error: - return Task.FromException(ExceptionSupport.AttachRestrictedErrorInfo(source.ErrorCode)); - - case AsyncStatus.Canceled: - return Task.FromCanceled(cancellationToken.IsCancellationRequested ? cancellationToken : new CancellationToken(true)); - } - - // Benign race: source may complete here. Things still work, just not taking the fast path. - - // Source is not a NetFx-to-WinRT adapter, but a native future. Hook up the task: - var bridge = new AsyncInfoToTaskBridge(cancellationToken); - - source.Completed = new AsyncOperationCompletedHandler(bridge.CompleteFromAsyncOperation); - bridge.RegisterForCancellation(source); - - return bridge.Task; - } - - #endregion Converters from IAsyncOperation to Task - - - #region Converters from IAsyncActionWithProgress to Task - - /// Gets an awaiter used to await this asynchronous operation. - /// An awaiter instance. - /// This method is intended for compiler user rather than use directly in code. - [EditorBrowsable(EditorBrowsableState.Never)] - public static TaskAwaiter GetAwaiter(this IAsyncActionWithProgress source) - { - return AsTask(source).GetAwaiter(); - } - - - /// Gets a Task to represent the asynchronous operation. - /// The asynchronous operation. - /// The Task representing the asynchronous operation. - public static Task AsTask(this IAsyncActionWithProgress source) - { - return AsTask(source, CancellationToken.None, null); - } - - - /// Gets a Task to represent the asynchronous operation. - /// The asynchronous operation. - /// The token used to request cancellation of the asynchronous operation. - /// The Task representing the asynchronous operation. - public static Task AsTask(this IAsyncActionWithProgress source, CancellationToken cancellationToken) - { - return AsTask(source, cancellationToken, null); - } - - - /// Gets a Task to represent the asynchronous operation. - /// The asynchronous operation. - /// The progress object used to receive progress updates. - /// The Task representing the asynchronous operation. - public static Task AsTask(this IAsyncActionWithProgress source, IProgress? progress) - { - return AsTask(source, CancellationToken.None, progress); - } - - - /// Gets a Task to represent the asynchronous operation. - /// The asynchronous operation. - /// The token used to request cancellation of the asynchronous operation. - /// The progress object used to receive progress updates. - /// The Task representing the asynchronous operation. - public static Task AsTask(this IAsyncActionWithProgress source, - CancellationToken cancellationToken, IProgress? progress) - { - if (source == null) - throw new ArgumentNullException(nameof(source)); - - // If source is actually a NetFx-to-WinRT adapter, unwrap it instead of creating a new Task: - var wrapper = source as TaskToAsyncActionWithProgressAdapter; - if (wrapper != null && !wrapper.CompletedSynchronously) - { - Task? innerTask = wrapper.Task; - Debug.Assert(innerTask != null); - Debug.Assert(innerTask.Status != TaskStatus.Created); // Is WaitingForActivation a legal state at this moment? - - if (!innerTask.IsCompleted) - { - // The race here is benign: If the task completes here, the concatinations are useless, but not damaging. - - if (cancellationToken.CanBeCanceled && wrapper.CancelTokenSource != null) - ConcatenateCancelTokens(cancellationToken, wrapper.CancelTokenSource, innerTask); - - if (progress != null) - ConcatenateProgress(source, progress); - } - - return innerTask; - } - - // Fast path to return a completed Task if the operation has already completed: - switch (source.Status) - { - case AsyncStatus.Completed: - return Task.CompletedTask; - - case AsyncStatus.Error: - return Task.FromException(ExceptionSupport.AttachRestrictedErrorInfo(source.ErrorCode)); - - case AsyncStatus.Canceled: - return Task.FromCanceled(cancellationToken.IsCancellationRequested ? cancellationToken : new CancellationToken(true)); - } - - // Benign race: source may complete here. Things still work, just not taking the fast path. - - // Forward progress reports: - if (progress != null) - ConcatenateProgress(source, progress); - - // Source is not a NetFx-to-WinRT adapter, but a native future. Hook up the task: - var bridge = new AsyncInfoToTaskBridge(cancellationToken); - - source.Completed = new AsyncActionWithProgressCompletedHandler(bridge.CompleteFromAsyncActionWithProgress); - bridge.RegisterForCancellation(source); - - return bridge.Task; - } - - #endregion Converters from IAsyncActionWithProgress to Task - - - #region Converters from IAsyncOperationWithProgress to Task - - /// Gets an awaiter used to await this asynchronous operation. - /// An awaiter instance. - /// This method is intended for compiler user rather than use directly in code. - [EditorBrowsable(EditorBrowsableState.Never)] - public static TaskAwaiter GetAwaiter(this IAsyncOperationWithProgress source) - { - return AsTask(source).GetAwaiter(); - } - - - /// Gets a Task to represent the asynchronous operation. - /// The asynchronous operation. - /// The Task representing the started asynchronous operation. - public static Task AsTask(this IAsyncOperationWithProgress source) - { - return AsTask(source, CancellationToken.None, null); - } - - - /// Gets a Task to represent the asynchronous operation. - /// The asynchronous operation. - /// The token used to request cancellation of the asynchronous operation. - /// The Task representing the asynchronous operation. - public static Task AsTask(this IAsyncOperationWithProgress source, - CancellationToken cancellationToken) - { - return AsTask(source, cancellationToken, null); - } - - - /// Gets a Task to represent the asynchronous operation. - /// The asynchronous operation. - /// The progress object used to receive progress updates. - /// The Task representing the asynchronous operation. - public static Task AsTask(this IAsyncOperationWithProgress source, - IProgress? progress) - { - return AsTask(source, CancellationToken.None, progress); - } - - - /// Gets a Task to represent the asynchronous operation. - /// The asynchronous operation. - /// The token used to request cancellation of the asynchronous operation. - /// The progress object used to receive progress updates. - /// The Task representing the asynchronous operation. - public static Task AsTask(this IAsyncOperationWithProgress source, - CancellationToken cancellationToken, IProgress? progress) - { - if (source == null) - throw new ArgumentNullException(nameof(source)); - - // If source is actually a NetFx-to-WinRT adapter, unwrap it instead of creating a new Task: - var wrapper = source as TaskToAsyncOperationWithProgressAdapter; - if (wrapper != null && !wrapper.CompletedSynchronously) - { - Task? innerTask = wrapper.Task as Task; - Debug.Assert(innerTask != null); - Debug.Assert(innerTask.Status != TaskStatus.Created); // Is WaitingForActivation a legal state at this moment? - - if (!innerTask.IsCompleted) - { - // The race here is benign: If the task completes here, the concatinations are useless, but not damaging. - - if (cancellationToken.CanBeCanceled && wrapper.CancelTokenSource != null) - ConcatenateCancelTokens(cancellationToken, wrapper.CancelTokenSource, innerTask); - - if (progress != null) - ConcatenateProgress(source, progress); - } - - return innerTask; - } - - // Fast path to return a completed Task if the operation has already completed - switch (source.Status) - { - case AsyncStatus.Completed: - return Task.FromResult(source.GetResults()); - - case AsyncStatus.Error: - return Task.FromException(ExceptionSupport.AttachRestrictedErrorInfo(source.ErrorCode)); - - case AsyncStatus.Canceled: - return Task.FromCanceled(cancellationToken.IsCancellationRequested ? cancellationToken : new CancellationToken(true)); - } - - // Benign race: source may complete here. Things still work, just not taking the fast path. - - // Forward progress reports: - if (progress != null) - ConcatenateProgress(source, progress); - - // Source is not a NetFx-to-WinRT adapter, but a native future. Hook up the task: - var bridge = new AsyncInfoToTaskBridge(cancellationToken); - - source.Completed = new AsyncOperationWithProgressCompletedHandler(bridge.CompleteFromAsyncOperationWithProgress); - bridge.RegisterForCancellation(source); - - return bridge.Task; - } - - #endregion Converters from IAsyncOperationWithProgress to Task - - #endregion Converters from Windows.Foundation.IAsyncInfo (and interfaces that derive from it) to System.Threading.Tasks.Task - - - #region Converters from System.Threading.Tasks.Task to Windows.Foundation.IAsyncInfo (and interfaces that derive from it) - - - public static IAsyncAction AsAsyncAction(this Task source) - { - if (source == null) - throw new ArgumentNullException(nameof(source)); - - return new TaskToAsyncActionAdapter(source, underlyingCancelTokenSource: null); - } - - - public static IAsyncOperation AsAsyncOperation(this Task source) - { - if (source == null) - throw new ArgumentNullException(nameof(source)); - - return new TaskToAsyncOperationAdapter(source, underlyingCancelTokenSource: null); - } - - - #endregion Converters from System.Threading.Tasks.Task to Windows.Foundation.IAsyncInfo (and interfaces that derive from it) - - private static void CommonlyUsedGenericInstantiations() - { - // This method is an aid for NGen to save common generic - // instantiations into the ngen image. - ((IAsyncOperation)null!).AsTask(); - ((IAsyncOperation)null!).AsTask(); - ((IAsyncOperation)null!).AsTask(); - ((IAsyncOperation)null!).AsTask(); - - ((IAsyncOperationWithProgress)null!).AsTask(); - ((IAsyncOperationWithProgress)null!).AsTask(); - ((IAsyncOperationWithProgress)null!).AsTask(); - } - } // class WindowsRuntimeSystemExtensions -} // namespace - -// WindowsRuntimeExtensions.cs diff --git a/src/libraries/System.Runtime.WindowsRuntime/tests/Resources/System.Runtime.WindowsRuntime.Tests.rd.xml b/src/libraries/System.Runtime.WindowsRuntime/tests/Resources/System.Runtime.WindowsRuntime.Tests.rd.xml deleted file mode 100644 index a46c95c..0000000 --- a/src/libraries/System.Runtime.WindowsRuntime/tests/Resources/System.Runtime.WindowsRuntime.Tests.rd.xml +++ /dev/null @@ -1,6 +0,0 @@ - - - - - - \ No newline at end of file diff --git a/src/libraries/System.Runtime.WindowsRuntime/tests/System.Runtime.WindowsRuntime.Tests.csproj b/src/libraries/System.Runtime.WindowsRuntime/tests/System.Runtime.WindowsRuntime.Tests.csproj deleted file mode 100644 index 8633fff..0000000 --- a/src/libraries/System.Runtime.WindowsRuntime/tests/System.Runtime.WindowsRuntime.Tests.csproj +++ /dev/null @@ -1,23 +0,0 @@ - - - $(NetCoreAppCurrent)-Windows_NT - true - - - - - - - - - - - - - - - - - - - \ No newline at end of file diff --git a/src/libraries/System.Runtime.WindowsRuntime/tests/System/IO/AsWinRTStreamTests.cs b/src/libraries/System.Runtime.WindowsRuntime/tests/System/IO/AsWinRTStreamTests.cs deleted file mode 100644 index 0e7541a..0000000 --- a/src/libraries/System.Runtime.WindowsRuntime/tests/System/IO/AsWinRTStreamTests.cs +++ /dev/null @@ -1,397 +0,0 @@ -// 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.InteropServices.WindowsRuntime; -using System.Threading; -using Windows.Foundation; -using Windows.Storage.Streams; -using Xunit; - -namespace System.IO -{ - [ConditionalClass(typeof(PlatformDetection), nameof(PlatformDetection.IsWinUISupported))] - [ActiveIssue("https://github.com/dotnet/runtime/issues/34578", TestPlatforms.Windows, TargetFrameworkMonikers.Netcoreapp, TestRuntimes.Mono)] - public class AsWinRTStreamTests - { - [Fact] - public static void AsInputStream_FromReadOnlyStream() - { - Stream managedStream = TestStreamProvider.CreateReadOnlyStream(); - using (IInputStream ins = managedStream.AsInputStream()) - { - Assert.NotNull(ins); - - // Adapting a read-only managed Stream to IOutputStream must throw a NotSupportedException - Assert.Throws(() => { IOutputStream outs = managedStream.AsOutputStream(); }); - } - } - - [Fact] - public static void AsOutputStream_FromWriteOnlyStream() - { - Stream managedStream = TestStreamProvider.CreateWriteOnlyStream(); - using (IOutputStream outs = managedStream.AsOutputStream()) - { - Assert.NotNull(outs); - - // Adapting a write-only managed Stream to IInputStream must throw a NotSupportedException - Assert.Throws(() => { IInputStream ins = managedStream.AsInputStream(); }); - } - } - - [Fact] - public static void AsInputStream_WrapsToSameInstance() - { - Stream managedStream = TestStreamProvider.CreateReadOnlyStream(); - using (IInputStream ins = managedStream.AsInputStream()) - { - Assert.NotNull(ins); - Assert.Same(ins, managedStream.AsInputStream()); - } - } - - [Fact] - public static void AsOutputStream_WrapsToSameInstance() - { - Stream managedStream = TestStreamProvider.CreateWriteOnlyStream(); - using (IOutputStream outs = managedStream.AsOutputStream()) - { - Assert.NotNull(outs); - Assert.Same(outs, managedStream.AsOutputStream()); - } - } - - [Fact] - public static void AsInputStream_RoundtripUnwrap() - { - // .NET Framework Stream -> IInputStream -> .NET Framework Stream -> roundtrip reference equality is preserved - Stream managedStream = TestStreamProvider.CreateReadOnlyStream(); - using (IInputStream ins = managedStream.AsInputStream()) - { - Assert.Same(managedStream, ins.AsStreamForRead()); - } - } - - [Fact] - public static void AsOutputStream_RoundtripUnwrap() - { - // .NET Framework Stream -> IOutputStream -> .NET Framework Stream -> roundtrip reference equality is preserved - Stream managedStream = TestStreamProvider.CreateWriteOnlyStream(); - using (IOutputStream outs = managedStream.AsOutputStream()) - { - Assert.Same(managedStream, outs.AsStreamForWrite()); - } - } - - [Fact] - public static void AsInputStream_Equal() - { - Stream stream = TestStreamProvider.CreateReadOnlyStream(); - - using (IInputStream insOne = stream.AsInputStream()) - using (IInputStream insTwo = stream.AsInputStream()) - { - Assert.Equal(insOne, insTwo); - } - } - - [Fact] - public static void AsInputStream_NotEqual() - { - Stream streamOne = TestStreamProvider.CreateReadOnlyStream(); - Stream streamTwo = TestStreamProvider.CreateReadOnlyStream(); - - Assert.NotEqual(streamOne, streamTwo); - - using (IInputStream insOne = streamOne.AsInputStream()) - using (IInputStream insTwo = streamTwo.AsInputStream()) - { - Assert.NotEqual(insOne, insTwo); - } - } - - [Fact] - public static void AsOutputStream_Equal() - { - Stream stream = TestStreamProvider.CreateWriteOnlyStream(); - - using (IOutputStream outsOne = stream.AsOutputStream()) - using (IOutputStream outsTwo = stream.AsOutputStream()) - { - Assert.Equal(outsOne, outsOne); - } - } - - [Fact] - public static void AsOutputStream_NotEqual() - { - Stream streamOne = TestStreamProvider.CreateWriteOnlyStream(); - Stream streamTwo = TestStreamProvider.CreateWriteOnlyStream(); - - Assert.NotEqual(streamOne, streamTwo); - - using (IOutputStream outsOne = streamOne.AsOutputStream()) - using (IOutputStream outsTwo = streamTwo.AsOutputStream()) - { - Assert.NotEqual(outsOne, outsTwo); - } - } - - [Fact] - public static void TestRead_MemoryStream_None() - { - DoTestRead(TestStreamProvider.CreateMemoryStreamAsInputStream, InputStreamOptions.None, mustInvokeProgressHandler: false, completesSynchronously: true); - } - - [Fact] - public static void TestRead_MemoryStream_Partial() - { - DoTestRead(TestStreamProvider.CreateMemoryStreamAsInputStream, InputStreamOptions.Partial, mustInvokeProgressHandler: false, completesSynchronously: true); - } - - [Fact] - public static void TestWrite_MemoryStream() - { - DoTestWrite(TestStreamProvider.CreateMemoryStream, mustInvokeProgressHandler: false); - } - - private static void DoTestRead(Func createStreamFunc, InputStreamOptions inputStreamOptions, bool mustInvokeProgressHandler, bool completesSynchronously) - { - - IInputStream stream = createStreamFunc(); - IBuffer buffer = WindowsRuntimeBuffer.Create(TestStreamProvider.ModelStreamLength); - - IAsyncOperationWithProgress readOp = stream.ReadAsync(buffer, (uint)TestStreamProvider.ModelStreamLength, inputStreamOptions); - - if (completesSynchronously) - { - // New readOp for a stream where we know that reading is sycnhronous must have Status = Completed - Assert.Equal(AsyncStatus.Completed, readOp.Status); - } - else - { - // Note the race. By the tie we get here, the status of the op may be started or already completed. - AsyncStatus readOpStatus = readOp.Status; - Assert.True(readOpStatus == AsyncStatus.Completed || readOpStatus == AsyncStatus.Started, "New readOp must have Status = Started or Completed (race)"); - } - - bool progressCallbackInvoked = false; - bool completedCallbackInvoked = false; - - uint readOpId = readOp.Id; - EventWaitHandle waitHandle = new ManualResetEvent(false); - - readOp.Progress = (asyncReadOp, bytesCompleted) => - { - progressCallbackInvoked = true; - - // asyncReadOp.Id in a progress callback must match the ID of the asyncReadOp to which the callback was assigned - Assert.Equal(readOpId, asyncReadOp.Id); - - // asyncReadOp.Status must be 'Started' for an asyncReadOp in progress - Assert.Equal(AsyncStatus.Started, asyncReadOp.Status); - - // bytesCompleted must be in range [0, maxBytesToRead] asyncReadOp in progress - Assert.InRange(bytesCompleted, 0u, (uint)TestStreamProvider.ModelStreamLength); - }; - - readOp.Completed = (asyncReadOp, passedStatus) => - { - try - { - completedCallbackInvoked = true; - - // asyncReadOp.Id in a completion callback must match the ID of the asyncReadOp to which the callback was assigned - Assert.Equal(readOpId, asyncReadOp.Id); - - // asyncReadOp.Status must match passedStatus for a completed asyncReadOp - Assert.Equal(passedStatus, asyncReadOp.Status); - - // asyncReadOp.Status must be 'Completed' for a completed asyncReadOp - Assert.Equal(AsyncStatus.Completed, asyncReadOp.Status); - - IBuffer resultBuffer = asyncReadOp.GetResults(); - - // asyncReadOp.GetResults() must not return null for a completed asyncReadOp - Assert.NotNull(resultBuffer); - - AssertExtensions.GreaterThan(resultBuffer.Capacity, 0u, "resultBuffer.Capacity should be more than zero in completed callback"); - AssertExtensions.GreaterThan(resultBuffer.Length, 0u, "resultBuffer.Length should be more than zero in completed callback"); - AssertExtensions.LessThanOrEqualTo(resultBuffer.Length, resultBuffer.Capacity, "resultBuffer.Length should be <= Capacity in completed callback"); - - if (inputStreamOptions == InputStreamOptions.None) - { - // resultBuffer.Length must be equal to requested number of bytes when an asyncReadOp with - // InputStreamOptions.None completes successfully - Assert.Equal(resultBuffer.Length, (uint)TestStreamProvider.ModelStreamLength); - } - - if (inputStreamOptions == InputStreamOptions.Partial) - { - AssertExtensions.LessThanOrEqualTo(resultBuffer.Length, (uint)TestStreamProvider.ModelStreamLength, - "resultBuffer.Length must be <= requested number of bytes with InputStreamOptions.Partial in completed callback"); - } - buffer = resultBuffer; - } - finally - { - waitHandle.Set(); - } - }; - - // Now, let's block until the read op is complete. - // We speculate that it will complete within 3500 msec, although under high load it may not be. - // If the test fails we should use a better way to determine if callback is really not invoked, or if it's just too slow. - waitHandle.WaitOne(500); - waitHandle.WaitOne(1000); - waitHandle.WaitOne(2000); - - if (mustInvokeProgressHandler) - { - Assert.True(progressCallbackInvoked, - "Progress callback specified to ReadAsync callback must be invoked when reading from this kind of stream"); - } - - Assert.True(completedCallbackInvoked, - "Completion callback specified to ReadAsync callback must be invoked"); - - // readOp.Status must be 'Completed' for a completed async readOp - Assert.Equal(AsyncStatus.Completed, readOp.Status); - - AssertExtensions.GreaterThan(buffer.Capacity, 0u, "buffer.Capacity should be greater than zero bytes"); - AssertExtensions.GreaterThan(buffer.Length, 0u, "buffer.Length should be greater than zero bytes"); - AssertExtensions.LessThanOrEqualTo(buffer.Length, buffer.Capacity, "buffer.Length <= buffer.Capacity is required for a completed async readOp"); - - if (inputStreamOptions == InputStreamOptions.None) - { - // buffer.Length must be equal to requested number of bytes when an async readOp with - // InputStreamOptions.None completes successfully - Assert.Equal((uint)TestStreamProvider.ModelStreamLength, buffer.Length); - } - - if (inputStreamOptions == InputStreamOptions.Partial) - { - AssertExtensions.LessThanOrEqualTo(buffer.Length, (uint)TestStreamProvider.ModelStreamLength, - "resultBuffer.Length must be <= requested number of bytes with InputStreamOptions.Partial"); - } - - byte[] results = new byte[buffer.Length]; - buffer.CopyTo(0, results, 0, (int)buffer.Length); - - Assert.True(TestStreamProvider.CheckContent(results, 0, (int)buffer.Length), - "Result data returned from AsyncRead must be the same as expected from the test data source"); - } - - private static void DoTestWrite(Func createStreamFunc, bool mustInvokeProgressHandler) - { - Stream backingStream = createStreamFunc(); - using (IOutputStream stream = backingStream.AsOutputStream()) - { - // Create test data - Random rnd = new Random(20100720); // Must be a different seed than used for TestStreamProvider.ModelStreamContents - byte[] modelWriteData = new byte[0xA000]; - rnd.NextBytes(modelWriteData); - - // Start test - - IBuffer buffer = modelWriteData.AsBuffer(); - - // ibuffer.Length for IBuffer created by Array.ToBuffer(void) must equal to array.Length - Assert.Equal((uint)modelWriteData.Length, buffer.Length); - - // ibuffer.Capacity for IBuffer created by Array.ToBuffer(void) must equal to array.Length - Assert.Equal((uint)modelWriteData.Length, buffer.Capacity); - - IAsyncOperationWithProgress writeOp = stream.WriteAsync(buffer); - - // Note the race. By the tie we get here, the status of the op may be started or already completed. - AsyncStatus writeOpStatus = writeOp.Status; - Assert.True(writeOpStatus == AsyncStatus.Completed || writeOpStatus == AsyncStatus.Started, "New writeOp must have Status = Started or Completed (race)"); - - uint writeOpId = writeOp.Id; - bool progressCallbackInvoked = false; - bool completedCallbackInvoked = false; - uint resultBytesWritten = 0; - - EventWaitHandle waitHandle = new ManualResetEvent(false); - - writeOp.Progress = (asyncWriteOp, bytesCompleted) => - { - progressCallbackInvoked = true; - - // asyncWriteOp.Id in a progress callback must match the ID of the asyncWriteOp to which the callback was assigned - Assert.Equal(writeOpId, asyncWriteOp.Id); - - // asyncWriteOp.Status must be 'Started' for an asyncWriteOp in progress - Assert.Equal(AsyncStatus.Started, asyncWriteOp.Status); - - // bytesCompleted must be in range [0, maxBytesToWrite] asyncWriteOp in progress - Assert.InRange(bytesCompleted, 0u, (uint)TestStreamProvider.ModelStreamLength); - }; - - writeOp.Completed = (asyncWriteOp, passedStatus) => - { - try - { - completedCallbackInvoked = true; - - // asyncWriteOp.Id in a completion callback must match the ID of the asyncWriteOp to which the callback was assigned - Assert.Equal(writeOpId, asyncWriteOp.Id); - - // asyncWriteOp.Status must match passedStatus for a completed asyncWriteOp - Assert.Equal(passedStatus, asyncWriteOp.Status); - - // asyncWriteOp.Status must be 'Completed' for a completed asyncWriteOp - Assert.Equal(AsyncStatus.Completed, asyncWriteOp.Status); - - uint bytesWritten = asyncWriteOp.GetResults(); - - // asyncWriteOp.GetResults() must return that all required bytes were written for a completed asyncWriteOp - Assert.Equal((uint)modelWriteData.Length, bytesWritten); - - resultBytesWritten = bytesWritten; - } - finally - { - waitHandle.Set(); - } - }; - - // Now, let's block until the write op is complete. - // We speculate that it will complete within 3500 msec, although under high load it may not be. - // If the test fails we should use a better way to determine if callback is really not invoked, or if it's just too slow. - waitHandle.WaitOne(500); - waitHandle.WaitOne(1000); - waitHandle.WaitOne(2000); - - if (mustInvokeProgressHandler) - { - Assert.True(progressCallbackInvoked, - "Progress callback specified to WriteAsync callback must be invoked when reading from this kind of stream"); - } - - Assert.True(completedCallbackInvoked, "Completion callback specified to WriteAsync callback must be invoked"); - - // writeOp.Status must be 'Completed' for a completed async writeOp - Assert.Equal(AsyncStatus.Completed, writeOp.Status); - - // writeOp.GetResults() must return that all required bytes were written for a completed async writeOp - Assert.Equal((uint)modelWriteData.Length, resultBytesWritten); - - // Check contents - - backingStream.Seek(0, SeekOrigin.Begin); - byte[] verifyBuff = new byte[modelWriteData.Length + 1024]; - - int r = backingStream.Read(verifyBuff, 0, verifyBuff.Length); - - for (int i = 0; i < modelWriteData.Length; i++) - { - Assert.Equal(modelWriteData[i], verifyBuff[i]); - } - } - } - } -} diff --git a/src/libraries/System.Runtime.WindowsRuntime/tests/System/IO/CreateSafeFileHandleTests.cs b/src/libraries/System.Runtime.WindowsRuntime/tests/System/IO/CreateSafeFileHandleTests.cs deleted file mode 100644 index bd49eb2..0000000 --- a/src/libraries/System.Runtime.WindowsRuntime/tests/System/IO/CreateSafeFileHandleTests.cs +++ /dev/null @@ -1,235 +0,0 @@ -// 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.SafeHandles; -using Windows.Storage; -using Xunit; - -namespace System.IO -{ - [ConditionalClass(typeof(PlatformDetection), nameof(PlatformDetection.IsWinUISupported))] - [ActiveIssue("https://github.com/dotnet/runtime/issues/34578", TestPlatforms.Windows, TargetFrameworkMonikers.Netcoreapp, TestRuntimes.Mono)] - public class CreateSafeFileHandleTests - { - [Fact] - public void NullStorageFile_ThrowsArgumentNull() - { - IStorageFile file = null; - AssertExtensions.Throws("windowsRuntimeFile", () => file.CreateSafeFileHandle()); - } - - [Fact] - public void FromStorageFile_BadAccessThrowsOutOfRange() - { - IStorageFile file = new StorageFileMock(); - AssertExtensions.Throws("access", () => file.CreateSafeFileHandle((FileAccess)100)); - } - - [Fact] - public void FromStorageFile_BadSharingThrowsOutOfRange() - { - IStorageFile file = new StorageFileMock(); - AssertExtensions.Throws("share", () => file.CreateSafeFileHandle(FileAccess.ReadWrite, (FileShare)100)); - } - - [Fact] - public void FromStorageFile_BadOptionsThrowsOutOfRange() - { - IStorageFile file = new StorageFileMock(); - AssertExtensions.Throws("options", () => file.CreateSafeFileHandle(FileAccess.ReadWrite, FileShare.Read, (FileOptions)100)); - } - - [Fact] - public void FromStorageFile_InheritableThrowsNotSupported() - { - IStorageFile file = new StorageFileMock(); - Assert.Throws(() => file.CreateSafeFileHandle(FileAccess.ReadWrite, FileShare.Inheritable)); - } - - [Fact] - public void FromStorageFile_EncryptedThrowsNotSupported() - { - IStorageFile file = new StorageFileMock(); - Assert.Throws(() => file.CreateSafeFileHandle(FileAccess.ReadWrite, FileShare.Read, FileOptions.Encrypted)); - } - - [Fact] - public void FromStorageFile_NoInterfaceReturnsNull() - { - // If the provided IStorageFile object can't be cast to the COM interface needed it should return null - IStorageFile file = new StorageFileMock(); - Assert.Null(file.CreateSafeFileHandle()); - } - - [Fact] - public void NullStorageFolder_ThrowsArgumentNull() - { - IStorageFolder folder = null; - AssertExtensions.Throws("rootDirectory", () => folder.CreateSafeFileHandle("foo", FileMode.OpenOrCreate)); - } - - [Fact] - public void NullStorageFolder_ThrowsArgumentNull2() - { - IStorageFolder folder = null; - AssertExtensions.Throws("rootDirectory", () => folder.CreateSafeFileHandle("foo", FileMode.OpenOrCreate, FileAccess.Write)); - } - - [Fact] - public void FromStorageFolder_BadModeThrowsOutOfRange() - { - IStorageFolder folder = new StorageFolderMock(); - AssertExtensions.Throws("mode", () => folder.CreateSafeFileHandle("Foo", (FileMode)100)); - } - - [Fact] - public void FromStorageFolder_BadAccessThrowsOutOfRange() - { - IStorageFolder folder = new StorageFolderMock(); - AssertExtensions.Throws("access", () => folder.CreateSafeFileHandle("Foo", FileMode.OpenOrCreate, (FileAccess)100)); - } - - [Fact] - public void FromStorageFolder_BadSharingThrowsOutOfRange() - { - IStorageFolder folder = new StorageFolderMock(); - AssertExtensions.Throws("share", () => folder.CreateSafeFileHandle("Foo", FileMode.OpenOrCreate, FileAccess.ReadWrite, (FileShare)100)); - } - - [Fact] - public void FromStorageFolder_BadOptionsThrowsOutOfRange() - { - IStorageFolder folder = new StorageFolderMock(); - AssertExtensions.Throws("options", () => folder.CreateSafeFileHandle("Foo", FileMode.OpenOrCreate, FileAccess.ReadWrite, FileShare.Read, (FileOptions)100)); - } - - [Fact] - public void FromStorageFolder_InheritableThrowsNotSupported() - { - IStorageFolder folder = new StorageFolderMock(); - Assert.Throws(() => folder.CreateSafeFileHandle("Foo", FileMode.OpenOrCreate, FileAccess.ReadWrite, FileShare.Inheritable)); - } - - [Fact] - public void FromStorageFolder_EncryptedThrowsNotSupported() - { - IStorageFolder folder = new StorageFolderMock(); - Assert.Throws(() => folder.CreateSafeFileHandle("Foo", FileMode.OpenOrCreate, FileAccess.ReadWrite, FileShare.Read, FileOptions.Encrypted)); - } - - [ConditionalFact(typeof(PlatformDetection), nameof(PlatformDetection.IsInAppContainer))] - public void FromStorageFolder_Basic() - { - StorageFolder folder = ApplicationData.Current.TemporaryFolder; - string filename = "FromStorageFolder_Basic_" + Path.GetRandomFileName(); - using (SafeFileHandle handle = folder.CreateSafeFileHandle(filename, FileMode.CreateNew)) - { - Assert.NotNull(handle); - Assert.False(handle.IsInvalid); - } - File.Delete(Path.Combine(folder.Path, filename)); - } - - [ConditionalFact(typeof(PlatformDetection), nameof(PlatformDetection.IsInAppContainer))] - public void FromStorageFolder_SurfaceIOException() - { - StorageFolder folder = ApplicationData.Current.TemporaryFolder; - string filename = "FromStorageFolder_SurfaceIOException_" + Path.GetRandomFileName(); - using (SafeFileHandle handle = folder.CreateSafeFileHandle(filename, FileMode.CreateNew)) - { - Assert.NotNull(handle); - Assert.False(handle.IsInvalid); - } - Assert.Contains( - filename, - Assert.Throws(() => folder.CreateSafeFileHandle(filename, FileMode.CreateNew)).Message); - File.Delete(Path.Combine(folder.Path, filename)); - } - - [ConditionalFact(typeof(PlatformDetection), nameof(PlatformDetection.IsInAppContainer))] - public void FromStorageFolder_SurfaceNotFoundException() - { - StorageFolder folder = ApplicationData.Current.TemporaryFolder; - string filename = "FromStorageFolder_SurfaceNotFoundException_" + Path.GetRandomFileName(); - Assert.Contains( - filename, - Assert.Throws(() => folder.CreateSafeFileHandle(filename, FileMode.Open)).Message); - } - - [ConditionalFact(typeof(PlatformDetection), nameof(PlatformDetection.IsInAppContainer))] - public void FromStorageFolder_FileStream() - { - StorageFolder folder = ApplicationData.Current.TemporaryFolder; - string filename = "FromStorageFolder_FileStream_" + Path.GetRandomFileName(); - SafeFileHandle handle = folder.CreateSafeFileHandle(filename, FileMode.CreateNew, FileAccess.ReadWrite); - Assert.NotNull(handle); - Assert.False(handle.IsInvalid); - using (FileStream fs = new FileStream(handle, FileAccess.ReadWrite)) - { - byte[] data = { 0xDE, 0xAD, 0xBE, 0xEF }; - fs.Write(data, 0, data.Length); - fs.Flush(); - fs.Position = 0; - byte[] input = new byte[4]; - Assert.Equal(4, fs.Read(input, 0, 4)); - Assert.Equal(data, input); - } - - File.Delete(Path.Combine(folder.Path, filename)); - } - - [ConditionalFact(typeof(PlatformDetection), nameof(PlatformDetection.IsInAppContainer))] - public void FromStorageFile_Basic() - { - StorageFolder folder = ApplicationData.Current.TemporaryFolder; - string filename = "FromStorageFile_Basic_" + Path.GetRandomFileName(); - StorageFile file = folder.CreateFileAsync(filename, CreationCollisionOption.FailIfExists).AsTask().Result; - using (SafeFileHandle handle = file.CreateSafeFileHandle()) - { - Assert.NotNull(handle); - Assert.False(handle.IsInvalid); - } - file.DeleteAsync().AsTask().Wait(); - } - - [ConditionalFact(typeof(PlatformDetection), nameof(PlatformDetection.IsInAppContainer))] - public void FromStorageFile_FileStream() - { - StorageFolder folder = ApplicationData.Current.TemporaryFolder; - string filename = "FromStorageFile_FileStream_" + Path.GetRandomFileName(); - StorageFile file = folder.CreateFileAsync(filename, CreationCollisionOption.FailIfExists).AsTask().Result; - SafeFileHandle handle = file.CreateSafeFileHandle(); - Assert.NotNull(handle); - Assert.False(handle.IsInvalid); - using (FileStream fs = new FileStream(handle, FileAccess.ReadWrite)) - { - byte[] data = { 0xAB, 0xBA, 0xCA, 0xDA, 0xBA }; - fs.Write(data, 0, data.Length); - fs.Flush(); - fs.Position = 0; - byte[] input = new byte[5]; - Assert.Equal(5, fs.Read(input, 0, 5)); - Assert.Equal(data, input); - } - - file.DeleteAsync().AsTask().Wait(); - } - - [ConditionalFact(typeof(PlatformDetection), nameof(PlatformDetection.IsInAppContainer))] - public void FromStorageFile_SurfaceIOException() - { - StorageFolder folder = ApplicationData.Current.TemporaryFolder; - string filename = "FromStorageFile_SurfaceIOException_" + Path.GetRandomFileName(); - StorageFile file = folder.CreateFileAsync(filename, CreationCollisionOption.FailIfExists).AsTask().Result; - using (SafeFileHandle handle = file.CreateSafeFileHandle(FileAccess.ReadWrite, FileShare.None)) - { - Assert.Contains( - filename, - Assert.Throws(() => file.CreateSafeFileHandle(FileAccess.ReadWrite, FileShare.None)).Message); - } - - file.DeleteAsync().AsTask().Wait(); - } - } -} diff --git a/src/libraries/System.Runtime.WindowsRuntime/tests/System/IO/StorageFileMock.cs b/src/libraries/System.Runtime.WindowsRuntime/tests/System/IO/StorageFileMock.cs deleted file mode 100644 index d61120b..0000000 --- a/src/libraries/System.Runtime.WindowsRuntime/tests/System/IO/StorageFileMock.cs +++ /dev/null @@ -1,116 +0,0 @@ -// 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 Windows.Foundation; -using Windows.Storage; -using Windows.Storage.FileProperties; -using Windows.Storage.Streams; - -namespace System.IO -{ - internal class StorageFileMock : IStorageFile - { - public IAsyncOperation OpenAsync(FileAccessMode accessMode) - { - throw new NotImplementedException(); - } - - public IAsyncOperation OpenTransactedWriteAsync() - { - throw new NotImplementedException(); - } - - public IAsyncOperation CopyAsync(IStorageFolder destinationFolder) - { - throw new NotImplementedException(); - } - - public IAsyncOperation CopyAsync(IStorageFolder destinationFolder, string desiredNewName) - { - throw new NotImplementedException(); - } - - public IAsyncOperation CopyAsync(IStorageFolder destinationFolder, string desiredNewName, NameCollisionOption option) - { - throw new NotImplementedException(); - } - - public IAsyncAction CopyAndReplaceAsync(IStorageFile fileToReplace) - { - throw new NotImplementedException(); - } - - public IAsyncAction MoveAsync(IStorageFolder destinationFolder) - { - throw new NotImplementedException(); - } - - public IAsyncAction MoveAsync(IStorageFolder destinationFolder, string desiredNewName) - { - throw new NotImplementedException(); - } - - public IAsyncAction MoveAsync(IStorageFolder destinationFolder, string desiredNewName, NameCollisionOption option) - { - throw new NotImplementedException(); - } - - public IAsyncAction MoveAndReplaceAsync(IStorageFile fileToReplace) - { - throw new NotImplementedException(); - } - - public string ContentType => throw new NotImplementedException(); - - public string FileType => throw new NotImplementedException(); - - public IAsyncAction RenameAsync(string desiredName) - { - throw new NotImplementedException(); - } - - public IAsyncAction RenameAsync(string desiredName, NameCollisionOption option) - { - throw new NotImplementedException(); - } - - public IAsyncAction DeleteAsync() - { - throw new NotImplementedException(); - } - - public IAsyncAction DeleteAsync(StorageDeleteOption option) - { - throw new NotImplementedException(); - } - - public IAsyncOperation GetBasicPropertiesAsync() - { - throw new NotImplementedException(); - } - - public bool IsOfType(StorageItemTypes type) - { - throw new NotImplementedException(); - } - - public global::Windows.Storage.FileAttributes Attributes => throw new NotImplementedException(); - - public DateTimeOffset DateCreated => throw new NotImplementedException(); - - public string Name => throw new NotImplementedException(); - - public string Path => throw new NotImplementedException(); - - public IAsyncOperation OpenReadAsync() - { - throw new NotImplementedException(); - } - - public IAsyncOperation OpenSequentialReadAsync() - { - throw new NotImplementedException(); - } - } -} diff --git a/src/libraries/System.Runtime.WindowsRuntime/tests/System/IO/StorageFolderMock.cs b/src/libraries/System.Runtime.WindowsRuntime/tests/System/IO/StorageFolderMock.cs deleted file mode 100644 index 96a8190..0000000 --- a/src/libraries/System.Runtime.WindowsRuntime/tests/System/IO/StorageFolderMock.cs +++ /dev/null @@ -1,102 +0,0 @@ -// 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.Generic; -using Windows.Foundation; -using Windows.Storage; -using Windows.Storage.FileProperties; - -namespace System.IO -{ - internal class StorageFolderMock : IStorageFolder - { - public IAsyncOperation CreateFileAsync(string desiredName) - { - throw new NotImplementedException(); - } - - public IAsyncOperation CreateFileAsync(string desiredName, CreationCollisionOption options) - { - throw new NotImplementedException(); - } - - public IAsyncOperation CreateFolderAsync(string desiredName) - { - throw new NotImplementedException(); - } - - public IAsyncOperation CreateFolderAsync(string desiredName, CreationCollisionOption options) - { - throw new NotImplementedException(); - } - - public IAsyncOperation GetFileAsync(string name) - { - throw new NotImplementedException(); - } - - public IAsyncOperation GetFolderAsync(string name) - { - throw new NotImplementedException(); - } - - public IAsyncOperation GetItemAsync(string name) - { - throw new NotImplementedException(); - } - - public IAsyncOperation> GetFilesAsync() - { - throw new NotImplementedException(); - } - - public IAsyncOperation> GetFoldersAsync() - { - throw new NotImplementedException(); - } - - public IAsyncOperation> GetItemsAsync() - { - throw new NotImplementedException(); - } - - public IAsyncAction RenameAsync(string desiredName) - { - throw new NotImplementedException(); - } - - public IAsyncAction RenameAsync(string desiredName, NameCollisionOption option) - { - throw new NotImplementedException(); - } - - public IAsyncAction DeleteAsync() - { - throw new NotImplementedException(); - } - - public IAsyncAction DeleteAsync(StorageDeleteOption option) - { - throw new NotImplementedException(); - } - - public IAsyncOperation GetBasicPropertiesAsync() - { - throw new NotImplementedException(); - } - - public bool IsOfType(StorageItemTypes type) - { - throw new NotImplementedException(); - } - - public global::Windows.Storage.FileAttributes Attributes => throw new NotImplementedException(); - - public DateTimeOffset DateCreated => throw new NotImplementedException(); - - public string Name => throw new NotImplementedException(); - - public string Path => throw new NotImplementedException(); - } -} diff --git a/src/libraries/System.Runtime.WindowsRuntime/tests/System/IO/TestStreamProvider.cs b/src/libraries/System.Runtime.WindowsRuntime/tests/System/IO/TestStreamProvider.cs deleted file mode 100644 index 43c0320..0000000 --- a/src/libraries/System.Runtime.WindowsRuntime/tests/System/IO/TestStreamProvider.cs +++ /dev/null @@ -1,112 +0,0 @@ -// 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 Windows.Storage.Streams; - -namespace System.IO -{ - public class TestStreamProvider - { - private const string TempFileNameBase = @"WinRT.Testing.IO.Streams.NetFxStreamProvider.DataFile"; - private const string TempFileNameExt = @".tmp"; - private const string TempFileName = TempFileNameBase + TempFileNameExt; - - private static byte[] s_modelStreamContents = null; - private static int s_modelStreamLength = 0x100000; - - private static readonly string s_tempFileFolder; - private static readonly string s_tempFilePath; - - static TestStreamProvider() - { - s_tempFileFolder = "."; - s_tempFilePath = Path.Combine(s_tempFileFolder, TempFileName); - } - - public static byte[] ModelStreamContents - { - get - { - if (s_modelStreamContents != null) - return s_modelStreamContents; - - const int randomSeed = 20090918; - - Random rnd = new Random(randomSeed); - s_modelStreamContents = new byte[ModelStreamLength]; - rnd.NextBytes(s_modelStreamContents); - - return s_modelStreamContents; - } - } - - public static int ModelStreamLength - { - get - { - return s_modelStreamLength; - } - set - { - s_modelStreamContents = null; - s_modelStreamLength = value; - } - } - - public static bool CheckContent(byte[] values, int offsInModelContents, int count) - { - for (int i = 0; i < count; i++) - { - - if (!CheckContent(values[i], i + offsInModelContents)) - { - - Console.WriteLine("Fail on {0}, {1}, {2}, {3}", i, i + offsInModelContents, values[i], ModelStreamContents[i + offsInModelContents]); - - return false; - } - } - - return true; - } - - public static bool CheckContent(byte value, int index) - { - return value == ModelStreamContents[index]; - } - - public static MemoryStream CreateMemoryStream() - { - byte[] data = new byte[ModelStreamLength]; - Array.Copy(ModelStreamContents, data, data.Length); - - MemoryStream stream = new MemoryStream(data, 0, data.Length, true); - return stream; - } - - public static Stream CreateReadOnlyStream() - { - byte[] data = new byte[ModelStreamLength]; - Array.Copy(ModelStreamContents, data, data.Length); - - MemoryStream stream = new MemoryStream(data, 0, data.Length, false); - return stream; - } - - public static Stream CreateWriteOnlyStream() - { - byte[] data = new byte[ModelStreamLength]; - Array.Copy(ModelStreamContents, data, data.Length); - - MemoryStream stream = new WriteOnlyStream(data); - return stream; - } - - public static IInputStream CreateMemoryStreamAsInputStream() - { - MemoryStream memStream = CreateMemoryStream(); - return memStream.AsInputStream(); - } - } -} diff --git a/src/libraries/System.Runtime.WindowsRuntime/tests/System/IO/WriteOnlyStream.cs b/src/libraries/System.Runtime.WindowsRuntime/tests/System/IO/WriteOnlyStream.cs deleted file mode 100644 index 6eef149..0000000 --- a/src/libraries/System.Runtime.WindowsRuntime/tests/System/IO/WriteOnlyStream.cs +++ /dev/null @@ -1,16 +0,0 @@ -// 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 System.IO -{ - public class WriteOnlyStream : MemoryStream - { - internal WriteOnlyStream(byte[] data) : base(data, 0, data.Length, true) { } - public override bool CanRead { get { return false; } } - public override int Read(byte[] buffer, int offset, int count) { throw new NotSupportedException("This is a write-only stream"); } - public override int ReadByte() { throw new NotSupportedException("This is a write-only stream"); } - public override byte[] ToArray() { throw new NotSupportedException("This is a write-only stream"); } - public override void WriteTo(Stream stream) { throw new NotSupportedException("This is a write-only stream"); } - } -} diff --git a/src/libraries/System.Runtime.WindowsRuntime/tests/System/Runtime/InteropServices/WindowsRuntimeBufferExtensionsTests.cs b/src/libraries/System.Runtime.WindowsRuntime/tests/System/Runtime/InteropServices/WindowsRuntimeBufferExtensionsTests.cs deleted file mode 100644 index 9919a27..0000000 --- a/src/libraries/System.Runtime.WindowsRuntime/tests/System/Runtime/InteropServices/WindowsRuntimeBufferExtensionsTests.cs +++ /dev/null @@ -1,465 +0,0 @@ -// 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.Generic; -using System.IO; -using Windows.Storage.Streams; -using Xunit; - -namespace System.Runtime.InteropServices.WindowsRuntime.Tests -{ - [ConditionalClass(typeof(PlatformDetection), nameof(PlatformDetection.IsWinUISupported))] - [ActiveIssue("https://github.com/dotnet/runtime/issues/34768", TestPlatforms.Windows, TargetFrameworkMonikers.Netcoreapp, TestRuntimes.Mono)] - public class WindowsRuntimeBufferExtensionsTests - { - public static IEnumerable AsBuffer_TestData() - { - yield return new object[] { new byte[0], 0, 0, 0 }; - yield return new object[] { new byte[] { 1, 2, 3 }, 2, 0, 0 }; - yield return new object[] { new byte[] { 1, 2, 3 }, 2, 0, 1 }; - yield return new object[] { new byte[] { 1, 2, 3 }, 0, 3, 3 }; - yield return new object[] { new byte[] { 1, 2, 3 }, 1, 2, 2 }; - } - - [Theory] - [MemberData(nameof(AsBuffer_TestData))] - public void AsBuffer_Buffer_ReturnsExpected(byte[] source, int offset, int length, int capacity) - { - if (capacity == length) - { - if (offset == 0 && length == source.Length) - { - Verify(WindowsRuntimeBufferExtensions.AsBuffer(source), source, offset, length, capacity); - } - - Verify(WindowsRuntimeBufferExtensions.AsBuffer(source, offset, length), source, offset, length, capacity); - } - - Verify(WindowsRuntimeBufferExtensions.AsBuffer(source, offset, length, capacity), source, offset, length, capacity); - } - - [Fact] - public void AsBuffer_NullBuffer_ThrowsArgumentNullException() - { - AssertExtensions.Throws("source", () => WindowsRuntimeBufferExtensions.AsBuffer(null)); - AssertExtensions.Throws("source", () => WindowsRuntimeBufferExtensions.AsBuffer(null, 0, 0)); - AssertExtensions.Throws("source", () => WindowsRuntimeBufferExtensions.AsBuffer(null, 0, 0, 0)); - } - - [Fact] - public void AsBuffer_NegativeOffset_ThrowsArgumentOutOfRangeException() - { - AssertExtensions.Throws("offset", () => WindowsRuntimeBufferExtensions.AsBuffer(new byte[0], -1, 0)); - AssertExtensions.Throws("offset", () => WindowsRuntimeBufferExtensions.AsBuffer(new byte[0], -1, 0, 0)); - } - - [Fact] - public void AsBuffer_NegativeLength_ThrowsArgumentOutOfRangeException() - { - AssertExtensions.Throws("length", () => WindowsRuntimeBufferExtensions.AsBuffer(new byte[0], 0, -1)); - AssertExtensions.Throws("length", () => WindowsRuntimeBufferExtensions.AsBuffer(new byte[0], 0, -1, 0)); - } - - [Theory] - [InlineData(new byte[0], 0, 1, 0)] - [InlineData(new byte[0], 1, 0, 0)] - [InlineData(new byte[] { 0, 0 }, 1, 2, 0)] - [InlineData(new byte[] { 0, 0 }, int.MaxValue, 0, 0)] - [InlineData(new byte[] { 0, 0 }, 0, 0, 3)] - [InlineData(new byte[] { 0, 0 }, 0, 0, int.MaxValue)] - [InlineData(new byte[] { 0, 0 }, 0, 2, 1)] - public void AsBuffer_InvalidOffsetLengthCapacity_ThrowsArgumentException(byte[] data, int offset, int length, int capacity) - { - if (capacity == 0) - { - AssertExtensions.Throws(null, () => WindowsRuntimeBufferExtensions.AsBuffer(data, offset, length)); - } - - AssertExtensions.Throws(null, () => WindowsRuntimeBufferExtensions.AsBuffer(data, offset, length, capacity)); - } - - [Fact] - public void AsBuffer_NegativeCapacity_ThrowsArgumentOutOfRangeException() - { - AssertExtensions.Throws("capacity", () => WindowsRuntimeBufferExtensions.AsBuffer(new byte[0], 0, 0, -1)); - } - - public static IEnumerable AsStream_TestData() - { - yield return new object[] { new byte[0].AsBuffer(), new byte[0] }; - yield return new object[] { new byte[] { 1, 2, 3 }.AsBuffer(), new byte[] { 1, 2, 3 } }; - yield return new object[] { new byte[] { 1, 2, 3 }.AsBuffer(1, 2), new byte[] { 2, 3 } }; - } - - [Theory] - [MemberData(nameof(AsStream_TestData))] - public void AsStream_Buffer_Success(IBuffer buffer, byte[] expected) - { - using (MemoryStream stream = (MemoryStream)buffer.AsStream()) - { - Assert.Equal(expected.Length, stream.Length); - Assert.True(stream.CanWrite); - - Assert.Equal(expected, stream.ToArray()); - } - } - - [Fact] - public void AsStream_NullBuffer_ThrowsArgumentNullException() - { - AssertExtensions.Throws("source", () => WindowsRuntimeBufferExtensions.AsStream(null)); - } - - [Fact] - public void AsStream_CustomBuffer_ThrowsInvalidCastException() - { - Assert.Throws(() => WindowsRuntimeBufferExtensions.AsStream(new CustomBuffer())); - } - - public static IEnumerable CopyTo_TestData() - { - yield return new object[] { new byte[] { 1, 2, 3 }, 0, new byte[] { 2, 3, 4 }, 0, 3, new byte[] { 1, 2, 3 } }; - yield return new object[] { new byte[] { 1, 2, 3, 4, 5 }, 3, new byte[] { 255, 254, 253, 252 }, 2, 1, new byte[] { 255, 254, 4, 252 } }; - yield return new object[] { new byte[] { 1, 2, 3, 4, 5 }, 0, new byte[] { 255, 254, 253, 252 }, 0, 0, new byte[] { 255, 254, 253, 252 } }; - } - - [Theory] - [MemberData(nameof(CopyTo_TestData))] - public void CopyTo_Buffer_Success(byte[] source, int sourceIndex, byte[] destination, int destinationIndex, int count, byte[] expected) - { - byte[] Clone(byte[] array) => (byte[])array.Clone(); - IBuffer Buffer(byte[] array) => Clone(array).AsBuffer(); - - if (sourceIndex == 0 && destinationIndex == 0 && count == source.Length) - { - // CopyTo(byte[], IBuffer) - byte[] source1 = Clone(source); - IBuffer destination1 = Buffer(destination); - WindowsRuntimeBufferExtensions.CopyTo(source1, destination1); - Assert.Equal(expected, destination1.ToArray()); - - // CopyTo(IBuffer, byte[]) - IBuffer source2 = Buffer(source); - byte[] destination2 = Clone(destination); - WindowsRuntimeBufferExtensions.CopyTo(source2, destination2); - Assert.Equal(expected, destination2); - - // CopyTo(IBuffer, IBuffer) - IBuffer source3 = Buffer(source); - IBuffer destination3 = Buffer(destination); - WindowsRuntimeBufferExtensions.CopyTo(source3, destination3); - Assert.Equal(expected, destination3.ToArray()); - } - - // CopyTo(byte[], int, IBuffer, int, int) - byte[] source4 = Clone(source); - IBuffer destination4 = Buffer(destination); - WindowsRuntimeBufferExtensions.CopyTo(source4, sourceIndex, destination4, (uint)destinationIndex, count); - Assert.Equal(expected, destination4.ToArray()); - - // CopyTo(IBuffer, int, byte[], int, int) - IBuffer source5 = Buffer(source); - byte[] destination5 = Clone(destination); - WindowsRuntimeBufferExtensions.CopyTo(source5, (uint)sourceIndex, destination5, destinationIndex, count); - Assert.Equal(expected, destination5); - - // CopyTo(IBuffer, int, IBuffer, int, int) - IBuffer source6 = Buffer(source); - IBuffer destination6 = Buffer(destination); - WindowsRuntimeBufferExtensions.CopyTo(source6, (uint)sourceIndex, destination6, (uint)destinationIndex, (uint)count); - Assert.Equal(expected, destination6.ToArray()); - } - - [Fact] - public void CopyTo_NullSource_ThrowsArgumentNullException() - { - IBuffer buffer = WindowsRuntimeBufferExtensions.AsBuffer(new byte[0]); - AssertExtensions.Throws("source", () => WindowsRuntimeBufferExtensions.CopyTo((byte[])null, buffer)); - AssertExtensions.Throws("source", () => WindowsRuntimeBufferExtensions.CopyTo(null, new byte[0])); - AssertExtensions.Throws("source", () => WindowsRuntimeBufferExtensions.CopyTo((IBuffer)null, buffer)); - AssertExtensions.Throws("source", () => WindowsRuntimeBufferExtensions.CopyTo(null, 0, buffer, 0, 0)); - AssertExtensions.Throws("source", () => WindowsRuntimeBufferExtensions.CopyTo(null, 0, new byte[0], 0, 0)); - AssertExtensions.Throws("source", () => WindowsRuntimeBufferExtensions.CopyTo((IBuffer)null, 0, buffer, 0, 0)); - } - - [Fact] - public void CopyTo_NullDestination_ThrowsArgumentNullException() - { - IBuffer buffer = WindowsRuntimeBufferExtensions.AsBuffer(new byte[0]); - AssertExtensions.Throws("destination", () => WindowsRuntimeBufferExtensions.CopyTo(new byte[0], null)); - AssertExtensions.Throws("destination", () => WindowsRuntimeBufferExtensions.CopyTo(buffer, (IBuffer)null)); - AssertExtensions.Throws("destination", () => WindowsRuntimeBufferExtensions.CopyTo(buffer, (byte[])null)); - AssertExtensions.Throws("destination", () => WindowsRuntimeBufferExtensions.CopyTo(new byte[0], 0, null, 0, 0)); - AssertExtensions.Throws("destination", () => WindowsRuntimeBufferExtensions.CopyTo(buffer, 0, null, 0, 0)); - AssertExtensions.Throws("destination", () => WindowsRuntimeBufferExtensions.CopyTo(buffer, 0, (IBuffer)null, 0, 0)); - } - - [Fact] - public void CopyTo_NegativeSourceIndex_ThrowsArgumentOutOfRangeException() - { - IBuffer buffer = WindowsRuntimeBufferExtensions.AsBuffer(new byte[0]); - AssertExtensions.Throws("sourceIndex", () => WindowsRuntimeBufferExtensions.CopyTo(new byte[0], -1, buffer, 0, 0)); - } - - [Fact] - public void CopyTo_NegativeDestinationIndex_ThrowsArgumentOutOfRangeException() - { - IBuffer buffer = WindowsRuntimeBufferExtensions.AsBuffer(new byte[0]); - AssertExtensions.Throws("destinationIndex", () => WindowsRuntimeBufferExtensions.CopyTo(buffer, 0, new byte[0], -1, 0)); - } - - [Fact] - public void CopyTo_LargeSourceIndex_ThrowsArgumentException() - { - IBuffer buffer = WindowsRuntimeBufferExtensions.AsBuffer(new byte[0]); - AssertExtensions.Throws("sourceIndex", () => WindowsRuntimeBufferExtensions.CopyTo(new byte[0], 1, buffer, 0, 0)); - AssertExtensions.Throws(null, () => WindowsRuntimeBufferExtensions.CopyTo(buffer, 1, buffer, 0, 0)); - AssertExtensions.Throws(null, () => WindowsRuntimeBufferExtensions.CopyTo(buffer, 1, new byte[0], 0, 0)); - } - - [Fact] - public void CopyTo_NegativeCount_ThrowsArgumentOutOfRangeException() - { - IBuffer buffer = WindowsRuntimeBufferExtensions.AsBuffer(new byte[0]); - AssertExtensions.Throws("count", () => WindowsRuntimeBufferExtensions.CopyTo(new byte[0], 0, buffer, 0, -1)); - AssertExtensions.Throws("count", () => WindowsRuntimeBufferExtensions.CopyTo(buffer, 0, new byte[0], 0, -1)); - } - - [Theory] - [InlineData(new byte[0], 0, 0)] - [InlineData(new byte[0], 0, 1)] - [InlineData(new byte[] { 0, 0 }, 2, 0)] - [InlineData(new byte[] { 0, 0 }, 1, 2)] - public void CopyTo_InvalidSourceIndexCount_ThrowsArgumentException(byte[] bytes, uint sourceIndex, uint count) - { - IBuffer buffer = WindowsRuntimeBufferExtensions.AsBuffer(bytes); - AssertExtensions.Throws(sourceIndex >= bytes.Length ? "sourceIndex" : null, () => WindowsRuntimeBufferExtensions.CopyTo(bytes, (int)sourceIndex, buffer, 0, (int)count)); - AssertExtensions.Throws(null, () => WindowsRuntimeBufferExtensions.CopyTo(buffer, sourceIndex, buffer, 0, count)); - AssertExtensions.Throws(null, () => WindowsRuntimeBufferExtensions.CopyTo(buffer, sourceIndex, new byte[0], 0, (int)count)); - } - - [Theory] - [InlineData(new byte[] { 0, 0 }, 2, 1)] - [InlineData(new byte[] { 0, 0 }, 1, 2)] - public void CopyTo_InvalidDestinationIndexCount_ThrowsArgumentException(byte[] bytes, uint destinationIndex, uint count) - { - IBuffer buffer = WindowsRuntimeBufferExtensions.AsBuffer(bytes); - AssertExtensions.Throws(null, () => WindowsRuntimeBufferExtensions.CopyTo(new byte[10], 0, buffer, destinationIndex, (int)count)); - AssertExtensions.Throws(null, () => WindowsRuntimeBufferExtensions.CopyTo(new byte[10].AsBuffer(), 0, bytes, (int)destinationIndex, (int)count)); - AssertExtensions.Throws(null, () => WindowsRuntimeBufferExtensions.CopyTo(new byte[10].AsBuffer(), 0, buffer, destinationIndex, count)); - } - - [Fact] - public void CopyTo_CustomBuffer_ThrowsInvalidCastException() - { - Assert.Throws(() => WindowsRuntimeBufferExtensions.CopyTo(new byte[10], new CustomBuffer())); - Assert.Throws(() => WindowsRuntimeBufferExtensions.CopyTo(new CustomBuffer(), new byte[10])); - Assert.Throws(() => WindowsRuntimeBufferExtensions.CopyTo(new CustomBuffer(), new CustomBuffer())); - Assert.Throws(() => WindowsRuntimeBufferExtensions.CopyTo(new byte[10], 0, new CustomBuffer(), 0, 0)); - Assert.Throws(() => WindowsRuntimeBufferExtensions.CopyTo(new CustomBuffer(), 0, new byte[10], 0, 0)); - - Assert.Throws(() => WindowsRuntimeBufferExtensions.CopyTo(new CustomBuffer(), 0, new CustomBuffer(), 0, 0)); - Assert.Throws(() => WindowsRuntimeBufferExtensions.CopyTo(new CustomBuffer(), 0, new byte[10].AsBuffer(), 0, 0)); - Assert.Throws(() => WindowsRuntimeBufferExtensions.CopyTo(new byte[10].AsBuffer(), 0, new CustomBuffer(), 0, 0)); - } - - public static IEnumerable IsSameData_TestData() - { - byte[] data = new byte[] { 1, 2, 3 }; - IBuffer buffer = data.AsBuffer(); - yield return new object[] { buffer, buffer, true }; - yield return new object[] { buffer, data.AsBuffer(), true }; - yield return new object[] { buffer, new byte[] { 1, 3, 3 }.AsBuffer(), false }; - - yield return new object[] { buffer, new CustomBuffer(), false }; - yield return new object[] { buffer, null, false }; - } - - [Theory] - [MemberData(nameof(IsSameData_TestData))] - public void IsSameData_Buffer_ReturnsExpected(IBuffer buffer, IBuffer other, bool expected) - { - Assert.Equal(expected, WindowsRuntimeBufferExtensions.IsSameData(buffer, other)); - } - - [Fact] - public void IsSameData_CustomBuffer_ThrowsInvalidCastException() - { - Assert.Throws(() => WindowsRuntimeBufferExtensions.IsSameData(new CustomBuffer(), new CustomBuffer())); - } - - [Fact] - public void IsSameData_NullBuffer_ThrowsArgumentNullException() - { - AssertExtensions.Throws("buffer", () => WindowsRuntimeBufferExtensions.IsSameData(null, new byte[0].AsBuffer())); - } - - [Fact] - public void GetByte_NullBuffer_ThrowsArgumentNullException() - { - AssertExtensions.Throws("source", () => WindowsRuntimeBufferExtensions.GetByte(null, 0)); - } - - [Theory] - [InlineData(1)] - [InlineData(2)] - public void GetByte_InvalidOffset_ThrowsArgumentException(uint byteOffset) - { - IBuffer buffer = new byte[1].AsBuffer(); - AssertExtensions.Throws("byteOffset", () => WindowsRuntimeBufferExtensions.GetByte(buffer, byteOffset)); - } - - [Fact] - public void GetByte_CustomBuffer_ThrowsInvalidCastExceptionException() - { - Assert.Throws(() => WindowsRuntimeBufferExtensions.GetByte(new CustomBuffer(), 2)); - } - - public static IEnumerable GetWindowsRuntimeBuffer_TestData() - { - yield return new object[] { new byte[] { 1, 2, 3 }, 0, 3 }; - yield return new object[] { new byte[] { 1, 2, 3 }, 1, 2 }; - yield return new object[] { new byte[] { 1, 2, 3 }, 3, 0 }; - } - - [Theory] - [MemberData(nameof(GetWindowsRuntimeBuffer_TestData))] - public void GetWindowsRuntimeBuffer_Stream_Success(byte[] bytes, int positionInStream, int length) - { - using (var stream = new MemoryStream()) - { - stream.Write(bytes, 0, bytes.Length); - stream.Position = 0; - - if (positionInStream == 0 && length == bytes.Length) - { - Verify(WindowsRuntimeBufferExtensions.GetWindowsRuntimeBuffer(stream), bytes, positionInStream, length, stream.Capacity); - } - - stream.Position = 0; - Verify(WindowsRuntimeBufferExtensions.GetWindowsRuntimeBuffer(stream, positionInStream, length), bytes, positionInStream, length, length); - } - } - - [Fact] - public void GetWindowsRuntimeBuffer_NullStream_ThrowsArgumentNullException() - { - AssertExtensions.Throws("underlyingStream", () => WindowsRuntimeBufferExtensions.GetWindowsRuntimeBuffer(null)); - AssertExtensions.Throws("underlyingStream", () => WindowsRuntimeBufferExtensions.GetWindowsRuntimeBuffer(null, 0, 0)); - } - - [Fact] - public void GetWindowsRuntimeBuffer_NonWritableStream_ThrowsUnauthorizedAccessException() - { - var memoryStream = new MemoryStream(new byte[10], false); - Assert.Throws(() => WindowsRuntimeBufferExtensions.GetWindowsRuntimeBuffer(memoryStream)); - Assert.Throws(() => WindowsRuntimeBufferExtensions.GetWindowsRuntimeBuffer(memoryStream, 0, 0)); - } - - [Fact] - public void GetWindowsRuntimeBuffer_NegativePositionInStream_ThrowsArgumentOufOfRangeException() - { - var memoryStream = new MemoryStream(); - AssertExtensions.Throws("positionInStream", () => WindowsRuntimeBufferExtensions.GetWindowsRuntimeBuffer(memoryStream, -1, 0)); - } - - [Fact] - public void GetWindowsRuntimeBuffer_NegativeLength_ThrowsArgumentOufOfRangeException() - { - var memoryStream = new MemoryStream(); - AssertExtensions.Throws("length", () => WindowsRuntimeBufferExtensions.GetWindowsRuntimeBuffer(memoryStream, 0, -1)); - } - - [Fact] - public void GetWindowsRuntimeBuffer_EmptyStream_ThrowsArgumentException() - { - using (var stream = new MemoryStream()) - { - Assert.Throws(null, () => WindowsRuntimeBufferExtensions.GetWindowsRuntimeBuffer(stream, 0, 0)); - } - } - - [Theory] - [InlineData(1)] - [InlineData(2)] - public void GetWindowsRuntimeBuffer_PositonInStreamGreaterOrEqualToCapacity_ThrowsArgumentException(int positionInStream) - { - var memoryStream = new MemoryStream(1); - AssertExtensions.Throws(null, () => WindowsRuntimeBufferExtensions.GetWindowsRuntimeBuffer(memoryStream, positionInStream, 0)); - } - - [Fact] - public void GetWindowsRuntimeBuffer_BufferWithLengthGreaterThanIntMax_Throws() - { - var memoryStream = new SubMemoryStream(10); - WindowsRuntimeBufferExtensions.GetWindowsRuntimeBuffer(memoryStream, 0, 0); - } - - public static IEnumerable ToArray_TestData() - { - yield return new object[] { new byte[] { 1, 2, 3 }, 0, 3, new byte[] { 1, 2, 3 } }; - yield return new object[] { new byte[] { 1, 2, 3 }, 2, 0, new byte[0] }; - yield return new object[] { new byte[] { 1, 2, 3 }, 1, 2, new byte[] { 2, 3 } }; - } - - [Theory] - [MemberData(nameof(ToArray_TestData))] - public void ToArray_Buffer_ReturnsExpected(byte[] buffer, uint index, int count, byte[] expected) - { - if (index == 0 && count == buffer.Length) - { - Assert.Equal(expected, buffer.AsBuffer().ToArray()); - } - - Assert.Equal(expected, buffer.AsBuffer().ToArray(index, count)); - } - - [Fact] - public void ToArray_NullBuffer_ThrowsArgumentNullException() - { - AssertExtensions.Throws("source", () => WindowsRuntimeBufferExtensions.ToArray(null)); - AssertExtensions.Throws("source", () => WindowsRuntimeBufferExtensions.ToArray(null, 0, 0)); - } - - [Fact] - public void ToArray_NegativeCount_ThrowsArgumentOutOfRangeException() - { - AssertExtensions.Throws("count", () => WindowsRuntimeBufferExtensions.ToArray(new byte[0].AsBuffer(), 0, -1)); - } - - [Theory] - [InlineData(new byte[0], 0, 0)] - [InlineData(new byte[] { 0 }, 1, 0)] - [InlineData(new byte[] { 0, 0, 0 }, 0, 4)] - [InlineData(new byte[] { 0, 0, 0 }, 1, 3)] - public void ToArray_InvalidIndexCount_ThrowsArgumentException(byte[] buffer, uint index, int count) - { - AssertExtensions.Throws(null, () => WindowsRuntimeBufferExtensions.ToArray(buffer.AsBuffer(), index, count)); - } - - private static void Verify(IBuffer buffer, byte[] source, int offset, int length, int capacity) - { - Assert.Equal(length, (int)buffer.Length); - Assert.Equal(capacity, (int)buffer.Capacity); - - for (uint i = 0; i < length; i++) - { - Assert.Equal(source[i + offset], buffer.GetByte(i)); - } - } - - private class SubMemoryStream : MemoryStream - { - public SubMemoryStream(int capacity) : base(capacity) { } - - public override long Length => long.MaxValue; - } - - private class CustomBuffer : IBuffer - { - public uint Capacity => 10; - public uint Length { get; set; } = 10; - } - } -} diff --git a/src/libraries/System.Runtime.WindowsRuntime/tests/System/Runtime/InteropServices/WindowsRuntimeBufferTests.cs b/src/libraries/System.Runtime.WindowsRuntime/tests/System/Runtime/InteropServices/WindowsRuntimeBufferTests.cs deleted file mode 100644 index 6c236e0..0000000 --- a/src/libraries/System.Runtime.WindowsRuntime/tests/System/Runtime/InteropServices/WindowsRuntimeBufferTests.cs +++ /dev/null @@ -1,99 +0,0 @@ -// 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.Generic; -using Windows.Storage.Streams; -using Xunit; - -namespace System.Runtime.InteropServices.WindowsRuntime.Tests -{ - [ConditionalClass(typeof(PlatformDetection), nameof(PlatformDetection.IsWinUISupported))] - [ActiveIssue("https://github.com/dotnet/runtime/issues/34768", TestPlatforms.Windows, TargetFrameworkMonikers.Netcoreapp, TestRuntimes.Mono)] - public class WindowsRuntimeBufferTests - { - [Theory] - [InlineData(0)] - [InlineData(1)] - public void Create_Capacity_ReturnsExpected(int capacity) - { - IBuffer buffer = WindowsRuntimeBuffer.Create(capacity); - Assert.Equal(capacity, (int)buffer.Capacity); - Assert.Equal(0, (int)buffer.Length); - } - - public static IEnumerable Create_TestData() - { - yield return new object[] { new byte[0], 0, 0, 0 }; - yield return new object[] { new byte[] { 1, 2, 3 }, 0, 3, 3 }; - yield return new object[] { new byte[] { 1, 2, 3, 4, 5, 6 }, 2, 1, 4 }; - yield return new object[] { new byte[] { 1, 2, 3 }, 1, 2, 2 }; - } - - [Theory] - [MemberData(nameof(Create_TestData))] - public void Create_Buffer_ReturnsExpected(byte[] source, int offset, int length, int capacity) - { - IBuffer buffer = WindowsRuntimeBuffer.Create(source, offset, length, capacity); - Assert.Equal(capacity, (int)buffer.Capacity); - Assert.Equal(length, (int)buffer.Length); - - for (uint i = 0; i < length; i++) - { - Assert.Equal(source[i + offset], buffer.GetByte(i)); - } - - // The source byte array should be copied. - if (source.Length > 0) - { - source[0] = 45; - Assert.NotEqual(45, buffer.GetByte(0)); - } - } - - [Fact] - public void Create_NegativeCapacity_ThrowsArgumentOutOfRangeException() - { - AssertExtensions.Throws("capacity", () => WindowsRuntimeBuffer.Create(-1)); - AssertExtensions.Throws("capacity", () => WindowsRuntimeBuffer.Create(new byte[0], 0, 0, -1)); - } - - [Fact] - public void Create_NullData_ThrowsArgumentNullException() - { - AssertExtensions.Throws("data", () => WindowsRuntimeBuffer.Create(null, 0, 0, 0)); - } - - [Fact] - public void Create_NegativeOffset_ThrowsArgumentOutOfRangeException() - { - AssertExtensions.Throws("offset", () => WindowsRuntimeBuffer.Create(new byte[0], -1, 0, 0)); - } - - [Fact] - public void Create_NegativeLength_ThrowsArgumentOutOfRangeException() - { - AssertExtensions.Throws("length", () => WindowsRuntimeBuffer.Create(new byte[0], 0, -1, 0)); - } - - [Theory] - [InlineData(new byte[0], 0, 1, 0)] - [InlineData(new byte[0], 1, 0, 0)] - [InlineData(new byte[] { 0, 0 }, 1, 2, 0)] - [InlineData(new byte[] { 0, 0 }, int.MaxValue, 0, 0)] - [InlineData(new byte[] { 0, 0 }, 0, 0, 3)] - [InlineData(new byte[] { 0, 0 }, 0, 0, int.MaxValue)] - [InlineData(new byte[] { 0, 0 }, 0, 2, 1)] - public void Create_InvalidOffsetLengthCapacity_ThrowsArgumentException(byte[] data, int offset, int length, int capacity) - { - AssertExtensions.Throws(null, () => WindowsRuntimeBuffer.Create(data, offset, length, capacity)); - } - - [Fact] - public void Length_SetGreaterThanCapacity_ThrowsArgumentException() - { - IBuffer buffer = WindowsRuntimeBuffer.Create(2); - AssertExtensions.Throws("value", () => buffer.Length = 3); - } - } -} diff --git a/src/libraries/System.Runtime.WindowsRuntime/tests/Windows/Foundation/PointTests.cs b/src/libraries/System.Runtime.WindowsRuntime/tests/Windows/Foundation/PointTests.cs deleted file mode 100644 index ba787e4..0000000 --- a/src/libraries/System.Runtime.WindowsRuntime/tests/Windows/Foundation/PointTests.cs +++ /dev/null @@ -1,120 +0,0 @@ -// 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.Collections.Generic; -using System.Globalization; -using Xunit; - -namespace Windows.Foundation.Tests -{ - [ConditionalClass(typeof(PlatformDetection), nameof(PlatformDetection.IsWinUISupported))] - public class PointTests - { - [Fact] - public void Ctor_Default() - { - var point = new Point(); - Assert.Equal(0, point.X); - Assert.Equal(0, point.Y); - } - - [Theory] - [InlineData(double.MinValue, double.MinValue, double.NegativeInfinity, double.NegativeInfinity)] - [InlineData(-1, -2, -1 , -2)] - [InlineData(0, 0, 0, 0)] - [InlineData(1, 2, 1, 2)] - [InlineData(double.MaxValue, double.MaxValue, double.PositiveInfinity, double.PositiveInfinity)] - [InlineData(double.NaN, double.NaN, double.NaN, double.NaN)] - [InlineData(double.PositiveInfinity, double.PositiveInfinity, double.PositiveInfinity, double.PositiveInfinity)] - [InlineData(double.NegativeInfinity, double.NegativeInfinity, double.NegativeInfinity, double.NegativeInfinity)] - public void Ctor_X_Y(double x, double y, double expectedX, double expectedY) - { - var point = new Point(x, y); - Assert.Equal(expectedX, point.X); - Assert.Equal(expectedY, point.Y); - } - - public static IEnumerable Coordinate_TestData() - { - yield return new object[] { double.MinValue, double.NegativeInfinity }; - yield return new object[] { -1, -1 }; - yield return new object[] { 0, 0 }; - yield return new object[] { 1, 1 }; - yield return new object[] { double.MaxValue, double.PositiveInfinity }; - yield return new object[] { double.NaN, double.NaN }; - yield return new object[] { double.NegativeInfinity, double.NegativeInfinity }; - } - - [Theory] - [MemberData(nameof(Coordinate_TestData))] - public void X_Set_GetReturnsExpected(double x, double expectedX) - { - var point = new Point { X = x }; - Assert.Equal(expectedX, point.X); - } - - [Theory] - [MemberData(nameof(Coordinate_TestData))] - public void Y_Set_GetReturnsExpected(double y, double expectedY) - { - var point = new Point { Y = y }; - Assert.Equal(expectedY, point.Y); - } - - public static IEnumerable Equals_TestData() - { - yield return new object[] { new Point(1, 2), new Point(1, 2), true }; - yield return new object[] { new Point(1, 2), new Point(2, 2), false }; - yield return new object[] { new Point(1, 2), new Point(1, 3), false }; - - yield return new object[] { new Point(1, 2), new object(), false }; - yield return new object[] { new Point(1, 2), null, false }; - } - - [Theory] - [MemberData(nameof(Equals_TestData))] - public void Equals_Other_ReturnsExpected(Point point, object other, bool expected) - { - Assert.Equal(expected, point.Equals(other)); - if (other is Point otherPoint) - { - Assert.Equal(expected, point == otherPoint); - Assert.Equal(!expected, point != otherPoint); - Assert.Equal(expected, point.Equals(otherPoint)); - Assert.Equal(expected, point.GetHashCode().Equals(other.GetHashCode())); - } - } - - public static IEnumerable ToString_TestData() - { - yield return new object[] { new Point(1, 2), null, null, "1,2" }; - yield return new object[] { new Point(1, 2), null, CultureInfo.InvariantCulture, "1,2" }; - - yield return new object[] { new Point(1, 2), "", CultureInfo.InvariantCulture, "1,2" }; - yield return new object[] { new Point(1, 2), "abc", null, "abc,abc" }; - yield return new object[] { new Point(1, 2), "N4", CultureInfo.InvariantCulture, "1.0000,2.0000" }; - - yield return new object[] { new Point(1, 2), "", new NumberFormatInfo { NumberDecimalSeparator = "," }, "1;2" }; - } - - [Theory] - [ActiveIssue("https://github.com/dotnet/runtime/issues/31197")] - [MemberData(nameof(ToString_TestData))] - public void ToString_Invoke_ReturnsExpected(Point point, string format, IFormatProvider formatProvider, string expected) - { - if (format == null) - { - if (formatProvider == null) - { - Assert.Equal(expected, point.ToString()); - } - - Assert.Equal(expected, point.ToString(formatProvider)); - } - - Assert.Equal(expected, ((IFormattable)point).ToString(format, formatProvider)); - } - } -} diff --git a/src/libraries/System.Runtime.WindowsRuntime/tests/Windows/Foundation/RectTests.cs b/src/libraries/System.Runtime.WindowsRuntime/tests/Windows/Foundation/RectTests.cs deleted file mode 100644 index bd46574..0000000 --- a/src/libraries/System.Runtime.WindowsRuntime/tests/Windows/Foundation/RectTests.cs +++ /dev/null @@ -1,328 +0,0 @@ -// 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.Collections.Generic; -using System.Globalization; -using Xunit; - -namespace Windows.Foundation.Tests -{ - [ConditionalClass(typeof(PlatformDetection), nameof(PlatformDetection.IsWinUISupported))] - public class RectTests - { - [Fact] - public void Ctor_Default() - { - var rect = new Rect(); - Assert.Equal(0, rect.X); - Assert.Equal(0, rect.Y); - Assert.Equal(0, rect.Width); - Assert.Equal(0, rect.Height); - - Assert.Equal(0, rect.Left); - Assert.Equal(0, rect.Right); - Assert.Equal(0, rect.Top); - Assert.Equal(0, rect.Bottom); - - Assert.False(rect.IsEmpty); - } - - [Theory] - [InlineData(0, 0, 0, 0, 0, 0, 0, 0)] - [InlineData(1, 2, 3, 4, 1, 2, 3, 4)] - [InlineData(double.MaxValue, double.MaxValue, double.MaxValue, double.MaxValue, double.PositiveInfinity, double.PositiveInfinity, double.PositiveInfinity, double.PositiveInfinity)] - [InlineData(double.NaN, double.NaN, double.NaN, double.NaN, double.NaN, double.NaN, double.NaN, double.NaN)] - [InlineData(double.PositiveInfinity, double.PositiveInfinity, double.PositiveInfinity, double.PositiveInfinity, double.PositiveInfinity, double.PositiveInfinity, double.PositiveInfinity, double.PositiveInfinity)] - public void Ctor_X_Y_Width_Height(double x, double y, double width, double height, double expectedX, double expectedY, double expectedWidth, double expectedHeight) - { - var rect = new Rect(x, y, width, height); - Assert.Equal(expectedX, rect.X); - Assert.Equal(expectedY, rect.Y); - Assert.Equal(expectedWidth, rect.Width); - Assert.Equal(expectedHeight, rect.Height); - - Assert.Equal(expectedX, rect.Left); - Assert.Equal(expectedX + expectedWidth, rect.Right); - Assert.Equal(expectedY, rect.Top); - Assert.Equal(expectedY + expectedHeight, rect.Bottom); - - Assert.False(rect.IsEmpty); - } - - [Theory] - [InlineData(-1)] - [InlineData(double.NegativeInfinity)] - public void Ctor_NegativeWidth_ThrowsArgumentOutOfRangeException(double width) - { - AssertExtensions.Throws("width", () => new Rect(1, 1, width, 1)); - } - - [Theory] - [InlineData(-1)] - [InlineData(double.NegativeInfinity)] - public void Ctor_NegativeHeight_ThrowsArgumentOutOfRangeException(double height) - { - AssertExtensions.Throws("height", () => new Rect(1, 1, 1, height)); - } - - public static IEnumerable Ctor_Point_Point_TestData() - { - yield return new object[] { new Point(1, 2), new Point(1, 2), 1, 2, 0, 0 }; - yield return new object[] { new Point(1, 2), new Point(3, 4), 1, 2, 2, 2 }; - yield return new object[] { new Point(3, 4), new Point(1, 2), 1, 2, 2, 2 }; - } - - [Theory] - [MemberData(nameof(Ctor_Point_Point_TestData))] - public void Ctor_Point_Point(Point point1, Point point2, double expectedX, double expectedY, double expectedWidth, double expectedHeight) - { - var rect = new Rect(point1, point2); - Assert.Equal(expectedX, rect.X); - Assert.Equal(expectedY, rect.Y); - Assert.Equal(expectedWidth, rect.Width); - Assert.Equal(expectedHeight, rect.Height); - } - - public static IEnumerable Ctor_Point_Size_TestData() - { - yield return new object[] { new Point(1, 2), Size.Empty, double.PositiveInfinity, double.PositiveInfinity, double.NegativeInfinity, double.NegativeInfinity }; - yield return new object[] { new Point(1, 2), new Size(0, 0), 1, 2, 0, 0 }; - yield return new object[] { new Point(1, 2), new Size(3, 4), 1, 2, 3, 4 }; - yield return new object[] { new Point(1, 2), new Size(double.MaxValue, double.MaxValue), 1, 2, double.PositiveInfinity, double.PositiveInfinity }; - } - - [Theory] - [MemberData(nameof(Ctor_Point_Size_TestData))] - public void Ctor_Point_Size(Point point, Size size, double expectedX, double expectedY, double expectedWidth, double expectedHeight) - { - var rect = new Rect(point, size); - Assert.Equal(expectedX, rect.X); - Assert.Equal(expectedY, rect.Y); - Assert.Equal(expectedWidth, rect.Width); - Assert.Equal(expectedHeight, rect.Height); - } - - [Fact] - public void Empty_Get_ReturnsExpected() - { - Rect rect = Rect.Empty; - Assert.Equal(double.PositiveInfinity, rect.X); - Assert.Equal(double.PositiveInfinity, rect.Y); - Assert.Equal(double.NegativeInfinity, rect.Width); - Assert.Equal(double.NegativeInfinity, rect.Height); - - Assert.Equal(double.PositiveInfinity, rect.Left); - Assert.Equal(double.NegativeInfinity, rect.Right); - Assert.Equal(double.PositiveInfinity, rect.Top); - Assert.Equal(double.NegativeInfinity, rect.Bottom); - - Assert.True(rect.IsEmpty); - } - - public static IEnumerable Coordinate_TestData() - { - yield return new object[] { double.MinValue, double.NegativeInfinity }; - yield return new object[] { -1, -1 }; - yield return new object[] { 0, 0 }; - yield return new object[] { 1, 1 }; - yield return new object[] { double.MaxValue, double.PositiveInfinity }; - yield return new object[] { double.NaN, double.NaN }; - yield return new object[] { double.NegativeInfinity, double.NegativeInfinity }; - } - - [Theory] - [MemberData(nameof(Coordinate_TestData))] - public void X_Set_GetReturnsExpected(double x, double expectedX) - { - var rect = new Rect { X = x }; - Assert.Equal(expectedX, rect.X); - } - - [Theory] - [MemberData(nameof(Coordinate_TestData))] - public void Y_Set_GetReturnsExpected(double y, double expectedY) - { - var rect = new Rect { Y = y }; - Assert.Equal(expectedY, rect.Y); - } - - public static IEnumerable Size_TestData() - { - yield return new object[] { 0, 0 }; - yield return new object[] { 1, 1 }; - yield return new object[] { double.MaxValue, double.PositiveInfinity }; - } - - [Theory] - [MemberData(nameof(Size_TestData))] - public void Width_SetValid_GetReturnsExpected(double width, double expectedWidth) - { - var rect = new Rect { Width = width }; - Assert.Equal(expectedWidth, rect.Width); - } - - [Theory] - [InlineData(-1)] - [InlineData(double.NegativeInfinity)] - public void Width_SetNegative_ThrowsArgumentOutOfRangeException(double width) - { - var rect = new Rect(); - AssertExtensions.Throws("Width", () => rect.Width = width); - } - - [Theory] - [MemberData(nameof(Size_TestData))] - public void Height_SetValid_GetReturnsExpected(double height, double expectedHeight) - { - var rect = new Rect { Height = height }; - Assert.Equal(expectedHeight, rect.Height); - } - - [Theory] - [InlineData(-1)] - [InlineData(double.NegativeInfinity)] - public void Height_SetNegative_ThrowsArgumentOutOfRangeException(double height) - { - var rect = new Rect(); - AssertExtensions.Throws("Height", () => rect.Height = height); - } - - public static IEnumerable Contains_TestData() - { - yield return new object[] { new Rect(1, 2, 3, 4), new Point(1, 2), true }; - yield return new object[] { new Rect(1, 2, 3, 4), new Point(3, 4), true }; - yield return new object[] { new Rect(1, 2, 3, 4), new Point(4, 6), true }; - yield return new object[] { new Rect(1, 2, 3, 4), new Point(5, 7), false }; - yield return new object[] { Rect.Empty, new Point(1, 2), false }; - } - - [Theory] - [MemberData(nameof(Contains_TestData))] - public void Contains_Point_ReturnsExpected(Rect rect, Point point, bool expected) - { - Assert.Equal(expected, rect.Contains(point)); - } - - public static IEnumerable Intersect_TestData() - { - yield return new object[] { Rect.Empty, Rect.Empty, Rect.Empty }; - yield return new object[] { Rect.Empty, new Rect(1,2 , 3, 4), Rect.Empty }; - yield return new object[] { new Rect(1, 2, 3, 4), Rect.Empty, Rect.Empty }; - yield return new object[] { new Rect(1, 2, 3, 4), new Rect(1, 2, 3, 4), new Rect(1, 2, 3, 4) }; - yield return new object[] { new Rect(1, 2, 3, 4), new Rect(0, 0, 0, 0), Rect.Empty }; - yield return new object[] { new Rect(1, 2, 3, 4), new Rect(2, 2, 6, 6), new Rect(2, 2, 2, 4) }; - yield return new object[] { new Rect(1, 2, 3, 4), new Rect(2, 2, 2, 2), new Rect(2, 2, 2, 2) }; - yield return new object[] { new Rect(1, 2, 3, 4), new Rect(-2, -2, 12, 12), new Rect(1, 2, 3, 4) }; - } - - [Theory] - [MemberData(nameof(Intersect_TestData))] - public void Intersect_Rect_ReturnsExpected(Rect rect, Rect other, Rect expected) - { - rect.Intersect(other); - Assert.Equal(expected, rect); - } - - public static IEnumerable Union_Rect_TestData() - { - yield return new object[] { Rect.Empty, Rect.Empty, Rect.Empty }; - yield return new object[] { Rect.Empty, new Rect(1, 2, 3, 4), new Rect(1, 2, 3, 4) }; - yield return new object[] { new Rect(1, 2, 3, 4), Rect.Empty, new Rect(1, 2, 3, 4) }; - yield return new object[] { new Rect(1, 2, 3, 4), new Rect(1, 2, 3, 4), new Rect(1, 2, 3, 4) }; - yield return new object[] { new Rect(1, 2, 3, 4), new Rect(0, 0, 0, 0), new Rect(0, 0, 4, 6) }; - yield return new object[] { new Rect(1, 2, 3, 4), new Rect(2, 2, 6, 6), new Rect(1, 2, 7, 6) }; - yield return new object[] { new Rect(1, 2, 3, 4), new Rect(2, 2, 2, 2), new Rect(1, 2, 3, 4) }; - yield return new object[] { new Rect(1, 2, 3, 4), new Rect(-2, -2, 2, 2), new Rect(-2, -2, 6, 8) }; - yield return new object[] { new Rect(-1, -2, 3, 4), new Rect(2, 2, 2, 2), new Rect(-1, -2, 5, 6) }; - - yield return new object[] { new Rect(1, 2, double.PositiveInfinity, double.PositiveInfinity), new Rect(-1, -2, 3, 4), new Rect(-1, -2, double.PositiveInfinity, double.PositiveInfinity) }; - yield return new object[] { new Rect(-1, -2, 3, 4), new Rect(1, 2, double.PositiveInfinity, double.PositiveInfinity), new Rect(-1, -2, double.PositiveInfinity, double.PositiveInfinity) }; - } - - [Theory] - [MemberData(nameof(Union_Rect_TestData))] - public void Union_Rect_ReturnsExpected(Rect rect, Rect other, Rect expected) - { - rect.Union(other); - Assert.Equal(expected, rect); - } - - public static IEnumerable Union_Point_TestData() - { - yield return new object[] { Rect.Empty, new Point(1, 2), new Rect(1, 2, 0, 0) }; - yield return new object[] { new Rect(2, 3, 4, 5), new Point(1, 2), new Rect(1, 2, 5, 6) }; - yield return new object[] { new Rect(2, 3, 4, 5), new Point(-1, -2), new Rect(-1, -2, 7, 10) }; - yield return new object[] { new Rect(2, 3, 4, 5), new Point(2, 3), new Rect(2, 3, 4, 5) }; - } - - [Theory] - [MemberData(nameof(Union_Point_TestData))] - public void Union_Point_ReturnsExpected(Rect rect, Point point, Rect expected) - { - rect.Union(point); - Assert.Equal(expected, rect); - } - - public static IEnumerable Equals_TestData() - { - yield return new object[] { new Rect(1, 2, 3, 4), new Rect(1, 2, 3, 4), true }; - yield return new object[] { new Rect(1, 2, 3, 4), new Rect(2, 2, 3, 4), false }; - yield return new object[] { new Rect(1, 2, 3, 4), new Rect(1, 3, 3, 4), false }; - yield return new object[] { new Rect(1, 2, 3, 4), new Rect(1, 2, 4, 4), false }; - yield return new object[] { new Rect(1, 2, 3, 4), new Rect(1, 3, 3, 5), false }; - yield return new object[] { new Rect(1, 2, 3, 4), Rect.Empty, false }; - - yield return new object[] { Rect.Empty, Rect.Empty, true }; - yield return new object[] { Rect.Empty, new Rect(1, 2, 3, 4), false }; - - yield return new object[] { new Rect(1, 2, 3, 4), new object(), false }; - yield return new object[] { new Rect(1, 2, 3, 4), null, false }; - } - - [Theory] - [MemberData(nameof(Equals_TestData))] - public void Equals_Other_ReturnsExpected(Rect rect, object other, bool expected) - { - Assert.Equal(expected, rect.Equals(other)); - if (other is Rect otherRect) - { - Assert.Equal(expected, rect == otherRect); - Assert.Equal(!expected, rect != otherRect); - Assert.Equal(expected, rect.Equals(otherRect)); - Assert.Equal(expected, rect.GetHashCode().Equals(other.GetHashCode())); - } - } - - public static IEnumerable ToString_TestData() - { - yield return new object[] { new Rect(1, 2, 3, 4), null, null, "1,2,3,4" }; - yield return new object[] { new Rect(1, 2, 3, 4), null, CultureInfo.InvariantCulture, "1,2,3,4" }; - - yield return new object[] { new Rect(1, 2, 3, 4), "", CultureInfo.InvariantCulture, "1,2,3,4" }; - yield return new object[] { new Rect(1, 2, 3, 4), "abc", null, "abc,abc,abc,abc" }; - yield return new object[] { new Rect(1, 2, 3, 4), "N4", CultureInfo.InvariantCulture, "1.0000,2.0000,3.0000,4.0000" }; - - yield return new object[] { new Rect(1, 2, 3, 4), "", new NumberFormatInfo { NumberDecimalSeparator = "," }, "1;2;3;4" }; - } - - [Theory] - [ActiveIssue("https://github.com/dotnet/runtime/issues/31197")] - [MemberData(nameof(ToString_TestData))] - public void ToString_Invoke_ReturnsExpected(Rect rect, string format, IFormatProvider formatProvider, string expected) - { - if (format == null) - { - if (formatProvider == null) - { - Assert.Equal(expected, rect.ToString()); - } - - Assert.Equal(expected, rect.ToString(formatProvider)); - } - - Assert.Equal(expected, ((IFormattable)rect).ToString(format, formatProvider)); - } - } -} diff --git a/src/libraries/System.Runtime.WindowsRuntime/tests/Windows/Foundation/SizeTests.cs b/src/libraries/System.Runtime.WindowsRuntime/tests/Windows/Foundation/SizeTests.cs deleted file mode 100644 index 64ba04a..0000000 --- a/src/libraries/System.Runtime.WindowsRuntime/tests/Windows/Foundation/SizeTests.cs +++ /dev/null @@ -1,146 +0,0 @@ -// 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.Collections.Generic; -using Xunit; - -namespace Windows.Foundation.Tests -{ - [ConditionalClass(typeof(PlatformDetection), nameof(PlatformDetection.IsWinUISupported))] - public class SizeTests - { - [Fact] - public void Ctor_Default() - { - var size = new Size(); - Assert.Equal(0, size.Width); - Assert.Equal(0, size.Height); - - Assert.False(size.IsEmpty); - } - - [Theory] - [InlineData(0, 0, 0, 0)] - [InlineData(1, 2, 1, 2)] - [InlineData(double.NaN, double.NaN, double.NaN, double.NaN)] - [InlineData(double.MaxValue, double.MaxValue, double.PositiveInfinity, double.PositiveInfinity)] - [InlineData(double.PositiveInfinity, double.PositiveInfinity, double.PositiveInfinity, double.PositiveInfinity)] - public void Ctor_Width_Height(double width, double height, double expectedWidth, double expectedHeight) - { - var size = new Size(width, height); - Assert.Equal(expectedWidth, size.Width); - Assert.Equal(expectedHeight, size.Height); - - Assert.False(size.IsEmpty); - } - - [Theory] - [InlineData(-1)] - [InlineData(double.NegativeInfinity)] - public void Ctor_NegativeWidth_ThrowsArgumentOutOfRangeException(double width) - { - AssertExtensions.Throws("width", () => new Size(width, 1)); - } - - [Theory] - [InlineData(-1)] - [InlineData(double.NegativeInfinity)] - public void Ctor_NegativeHeight_ThrowsArgumentOutOfRangeException(double height) - { - AssertExtensions.Throws("height", () => new Size(1, height)); - } - - [Theory] - [InlineData(0)] - [InlineData(1)] - [InlineData(double.PositiveInfinity)] - [InlineData(double.NaN)] - public void Width_SetValid_GetReturnsExpected(double width) - { - var size = new Size { Width = width }; - Assert.Equal(width, size.Width); - } - - [Theory] - [InlineData(-1)] - [InlineData(double.NegativeInfinity)] - public void Width_SetNegative_ThrowsArgumentOutOfRangeException(double width) - { - var size = new Size(); - AssertExtensions.Throws("Width", () => size.Width = width); - } - - [Theory] - [InlineData(0)] - [InlineData(1)] - [InlineData(double.PositiveInfinity)] - [InlineData(double.NaN)] - public void Height_SetValid_GetReturnsExpected(double height) - { - var size = new Size { Height = height }; - Assert.Equal(height, size.Height); - } - - [Theory] - [InlineData(-1)] - [InlineData(double.NegativeInfinity)] - public void Height_SetNegative_ThrowsArgumentOutOfRangeException(double height) - { - var size = new Size(); - AssertExtensions.Throws("Height", () => size.Height = height); - } - - [Fact] - public void Empty_Get_ReturnsExpected() - { - Size size = Size.Empty; - Assert.Equal(double.NegativeInfinity, size.Width); - Assert.Equal(double.NegativeInfinity, size.Height); - Assert.True(size.IsEmpty); - } - - public static IEnumerable Equals_TestData() - { - yield return new object[] { new Size(1, 2), new Size(1, 2), true }; - yield return new object[] { new Size(1, 2), new Size(2, 2), false }; - yield return new object[] { new Size(1, 2), new Size(1, 3), false }; - yield return new object[] { new Size(1, 2), Size.Empty, false }; - - yield return new object[] { Size.Empty, Size.Empty, true }; - yield return new object[] { Size.Empty, new Size(1, 2), false }; - - yield return new object[] { new Size(1, 2), new object(), false }; - yield return new object[] { new Size(1, 2), null, false }; - } - - [Theory] - [MemberData(nameof(Equals_TestData))] - public void Equals_Other_ReturnsExpected(Size size, object other, bool expected) - { - Assert.Equal(expected, size.Equals(other)); - if (other is Size otherSize) - { - Assert.Equal(expected, size == otherSize); - Assert.Equal(!expected, size != otherSize); - Assert.Equal(expected, size.Equals(otherSize)); - Assert.Equal(expected, size.GetHashCode().Equals(other.GetHashCode())); - } - } - - public static IEnumerable ToString_TestData() - { - yield return new object[] { Size.Empty, "Empty" }; - yield return new object[] { new Size(0, 0), "0,0" }; - yield return new object[] { new Size(1, 2), "1,2" }; - } - - [Theory] - [MemberData(nameof(ToString_TestData))] - public void ToString_Invoke_ReturnsExpected(Size size, string expected) - { - Assert.Equal(expected, size.ToString()); - } - } -} diff --git a/src/libraries/System.Runtime.WindowsRuntime/tests/Windows/UI/ColorTests.cs b/src/libraries/System.Runtime.WindowsRuntime/tests/Windows/UI/ColorTests.cs deleted file mode 100644 index 523d191..0000000 --- a/src/libraries/System.Runtime.WindowsRuntime/tests/Windows/UI/ColorTests.cs +++ /dev/null @@ -1,94 +0,0 @@ -// 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.Collections.Generic; -using System.Globalization; -using Xunit; - -namespace Windows.UI.Tests -{ - [ConditionalClass(typeof(PlatformDetection), nameof(PlatformDetection.IsWinUISupported))] - public class ColorTests - { - [Fact] - public void Ctor_Default() - { - var color = new Color(); - Assert.Equal(0, color.A); - Assert.Equal(0, color.R); - Assert.Equal(0, color.G); - Assert.Equal(0, color.B); - } - - [Theory] - [InlineData(0, 0, 0, 0)] - [InlineData(1, 2, 3, 4)] - [InlineData(255, 255, 255, 255)] - public void FromArgb_Invoke_ReturnsExpectedColor(byte a, byte r, byte g, byte b) - { - Color color = Color.FromArgb(a, r, g, b); - Assert.Equal(a, color.A); - Assert.Equal(r, color.R); - Assert.Equal(g, color.G); - Assert.Equal(b, color.B); - } - - public static IEnumerable Equals_TestData() - { - yield return new object[] { Color.FromArgb(1, 2, 3, 4), Color.FromArgb(1, 2, 3, 4), true }; - yield return new object[] { Color.FromArgb(1, 2, 3, 4), Color.FromArgb(2, 2, 3, 4), false }; - yield return new object[] { Color.FromArgb(1, 2, 3, 4), Color.FromArgb(1, 3, 3, 4), false }; - yield return new object[] { Color.FromArgb(1, 2, 3, 4), Color.FromArgb(1, 2, 4, 4), false }; - yield return new object[] { Color.FromArgb(1, 2, 3, 4), Color.FromArgb(1, 2, 3, 5), false }; - - yield return new object[] { Color.FromArgb(1, 2, 3, 4), new object(), false }; - yield return new object[] { Color.FromArgb(1, 2, 3, 4), null, false }; - } - - [Theory] - [MemberData(nameof(Equals_TestData))] - public void Equals_Other_ReturnsExpected(Color color, object other, bool expected) - { - Assert.Equal(expected, color.Equals(other)); - if (other is Color otherColor) - { - Assert.Equal(expected, color == otherColor); - Assert.Equal(!expected, color != otherColor); - Assert.Equal(expected, color.Equals(otherColor)); - Assert.Equal(expected, color.GetHashCode().Equals(other.GetHashCode())); - } - } - - public static IEnumerable ToString_TestData() - { - yield return new object[] { Color.FromArgb(1, 2, 3, 4), null, null, "#01020304" }; - yield return new object[] { Color.FromArgb(1, 2, 3, 4), null, CultureInfo.InvariantCulture, "#01020304" }; - - yield return new object[] { Color.FromArgb(1, 2, 3, 4), "", CultureInfo.InvariantCulture, "sc#1, 2, 3, 4" }; - yield return new object[] { Color.FromArgb(1, 2, 3, 4), "abc", null, "sc#abc, abc, abc, abc" }; - yield return new object[] { Color.FromArgb(1, 2, 3, 4), "D4", CultureInfo.InvariantCulture, "sc#0001, 0002, 0003, 0004" }; - - yield return new object[] { Color.FromArgb(1, 2, 3, 4), "", new NumberFormatInfo { NumberDecimalSeparator = "," }, "sc#1; 2; 3; 4" }; - } - - [Theory] - [ActiveIssue("https://github.com/dotnet/runtime/issues/31197")] - [MemberData(nameof(ToString_TestData))] - public void ToString_Invoke_ReturnsExpected(Color color, string format, IFormatProvider formatProvider, string expected) - { - if (format == null) - { - if (formatProvider == null) - { - Assert.Equal(expected, color.ToString()); - } - - Assert.Equal(expected, color.ToString(formatProvider)); - } - - Assert.Equal(expected, ((IFormattable)color).ToString(format, formatProvider)); - } - } -} diff --git a/src/libraries/System.Runtime/tests/System/ActivatorTests.cs b/src/libraries/System.Runtime/tests/System/ActivatorTests.cs index ae21111..3bd763b 100644 --- a/src/libraries/System.Runtime/tests/System/ActivatorTests.cs +++ b/src/libraries/System.Runtime/tests/System/ActivatorTests.cs @@ -776,22 +776,6 @@ namespace System.Tests yield return new object[] { "mscorlib", "SyStEm.NULLABLE`1[[System.Int32, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]]", true, BindingFlags.Public | BindingFlags.Instance, Type.DefaultBinder, new object[0], CultureInfo.InvariantCulture, null, "", true }; } - [ConditionalTheory(typeof(PlatformDetection), nameof(PlatformDetection.IsWinUISupported))] - [ActiveIssue("https://github.com/dotnet/runtime/issues/34396", TestPlatforms.Windows, TargetFrameworkMonikers.Netcoreapp, TestRuntimes.Mono)] - [PlatformSpecific(TestPlatforms.Windows)] - [MemberData(nameof(TestingCreateInstanceObjectHandleFullSignatureWinRTData))] - public static void TestingCreateInstanceObjectHandleFullSignatureWinRT(string assemblyName, string type, bool ignoreCase, BindingFlags bindingAttr, Binder binder, object[] args, CultureInfo culture, object[] activationAttributes, string returnedFullNameType) - { - ObjectHandle oh = Activator.CreateInstance(assemblyName: assemblyName, typeName: type, ignoreCase: ignoreCase, bindingAttr: bindingAttr, binder: binder, args: args, culture: culture, activationAttributes: activationAttributes); - CheckValidity(oh, returnedFullNameType); - } - - public static IEnumerable TestingCreateInstanceObjectHandleFullSignatureWinRTData() - { - // string assemblyName, string typeName, bool ignoreCase, BindingFlags bindingAttr, Binder binder, object[] args, CultureInfo culture, object[] activationAttributes, returnedFullNameType - yield return new object[] { "Windows, Version=255.255.255.255, Culture=neutral, PublicKeyToken=null, ContentType=WindowsRuntime", "Windows.Foundation.Collections.StringMap", false, BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Instance, Type.DefaultBinder, new object[0], CultureInfo.InvariantCulture, null, "Windows.Foundation.Collections.StringMap" }; - } - private static void CheckValidity(ObjectHandle instance, string expected) { Assert.NotNull(instance); diff --git a/src/libraries/pkg/descriptions.json b/src/libraries/pkg/descriptions.json index 6d2b585..fbfa4e0 100644 --- a/src/libraries/pkg/descriptions.json +++ b/src/libraries/pkg/descriptions.json @@ -1793,34 +1793,6 @@ ] }, { - "Name": "System.Runtime.WindowsRuntime", - "Description": "Provides extensions methods that improve interoperation between managed code and the Windows Runtime.", - "CommonTypes": [ - "System.WindowsRuntimeSystemExtensions", - "System.IO.WindowsRuntimeStorageExtensions", - "System.IO.WindowsRuntimeStreamExtensions", - "System.Runtime.InteropServices.WindowsRuntime.AsyncInfo", - "System.Runtime.InteropServices.WindowsRuntime.WindowsRuntimeBuffer" - ] - }, - { - "Name": "System.Runtime.WindowsRuntime.UI.Xaml", - "Description": "Provides managed equivalents of Extensible Application Markup Language (XAML) UI types from Windows Runtime.", - "CommonTypes": [ - "Windows.UI.Xaml.CornerRadius", - "Windows.UI.Xaml.Duration", - "Windows.UI.Xaml.DurationType", - "Windows.UI.Xaml.GridLength", - "Windows.UI.Xaml.GridUnitType", - "Windows.UI.Xaml.Thickness", - "Windows.UI.Xaml.Media.Matrix", - "Windows.UI.Xaml.Media.Animation.KeyTime", - "Windows.UI.Xaml.Media.Animation.RepeatBehavior", - "Windows.UI.Xaml.Media.Animation.RepeatBehaviorType", - "Windows.UI.Xaml.Media.Media3D.Matrix3D" - ] - }, - { "Name": "System.Security.AccessControl", "Description": "Provides base classes that enable managing access and audit control lists on securable objects.", "CommonTypes": [ diff --git a/src/libraries/shims/ApiCompatBaseline.PreviousNetCoreApp.txt b/src/libraries/shims/ApiCompatBaseline.PreviousNetCoreApp.txt index 5845d09..99ad677 100644 --- a/src/libraries/shims/ApiCompatBaseline.PreviousNetCoreApp.txt +++ b/src/libraries/shims/ApiCompatBaseline.PreviousNetCoreApp.txt @@ -20,4 +20,23 @@ CannotRemoveAttribute : Attribute 'System.ComponentModel.DefaultValueAttribute' CannotRemoveAttribute : Attribute 'System.ComponentModel.DefaultValueAttribute' exists on 'System.Diagnostics.ProcessStartInfo.Environment' in the contract but not the implementation. CannotChangeAttribute : Attribute 'System.ComponentModel.DefaultValueAttribute' on 'System.Diagnostics.ProcessStartInfo.Verb' changed from '[DefaultValueAttribute(null)]' in the contract to '[DefaultValueAttribute("")]' in the implementation. CannotRemoveAttribute : Attribute 'System.ComponentModel.DefaultValueAttribute' exists on 'System.Diagnostics.ProcessStartInfo.WindowStyle' in the contract but not the implementation. -Total Issues: 18 +Compat issues due to removal of System.Runtime.InteropServices.WindowsRuntime +TypesMustExist : Type 'System.Runtime.InteropServices.WindowsRuntime.DefaultInterfaceAttribute' does not exist in the implementation but it does exist in the contract. +TypesMustExist : Type 'System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken' does not exist in the implementation but it does exist in the contract. +TypesMustExist : Type 'System.Runtime.InteropServices.WindowsRuntime.EventRegistrationTokenTable' does not exist in the implementation but it does exist in the contract. +TypesMustExist : Type 'System.Runtime.InteropServices.WindowsRuntime.IActivationFactory' does not exist in the implementation but it does exist in the contract. +TypesMustExist : Type 'System.Runtime.InteropServices.WindowsRuntime.InterfaceImplementedInVersionAttribute' does not exist in the implementation but it does exist in the contract. +TypesMustExist : Type 'System.Runtime.InteropServices.WindowsRuntime.ReadOnlyArrayAttribute' does not exist in the implementation but it does exist in the contract. +TypesMustExist : Type 'System.Runtime.InteropServices.WindowsRuntime.ReturnValueNameAttribute' does not exist in the implementation but it does exist in the contract. +TypesMustExist : Type 'System.Runtime.InteropServices.WindowsRuntime.WindowsRuntimeMarshal' does not exist in the implementation but it does exist in the contract. +TypesMustExist : Type 'System.Runtime.InteropServices.WindowsRuntime.WriteOnlyArrayAttribute' does not exist in the implementation but it does exist in the contract. +TypesMustExist : Type 'System.Runtime.InteropServices.WindowsRuntime.DefaultInterfaceAttribute' does not exist in the implementation but it does exist in the contract. +TypesMustExist : Type 'System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken' does not exist in the implementation but it does exist in the contract. +TypesMustExist : Type 'System.Runtime.InteropServices.WindowsRuntime.EventRegistrationTokenTable' does not exist in the implementation but it does exist in the contract. +TypesMustExist : Type 'System.Runtime.InteropServices.WindowsRuntime.IActivationFactory' does not exist in the implementation but it does exist in the contract. +TypesMustExist : Type 'System.Runtime.InteropServices.WindowsRuntime.InterfaceImplementedInVersionAttribute' does not exist in the implementation but it does exist in the contract. +TypesMustExist : Type 'System.Runtime.InteropServices.WindowsRuntime.ReadOnlyArrayAttribute' does not exist in the implementation but it does exist in the contract. +TypesMustExist : Type 'System.Runtime.InteropServices.WindowsRuntime.ReturnValueNameAttribute' does not exist in the implementation but it does exist in the contract. +TypesMustExist : Type 'System.Runtime.InteropServices.WindowsRuntime.WindowsRuntimeMarshal' does not exist in the implementation but it does exist in the contract. +TypesMustExist : Type 'System.Runtime.InteropServices.WindowsRuntime.WriteOnlyArrayAttribute' does not exist in the implementation but it does exist in the contract. +Total Issues: 36 -- 2.7.4