From 9bd0e0dc36398910d8edaed8dcf44432ba7270ec Mon Sep 17 00:00:00 2001 From: Jeremy Koritzinsky Date: Tue, 19 Sep 2023 12:11:38 -0700 Subject: [PATCH] Remove "Is supported on this TFM" logic from marshalling generators and instead handle it during factory construction (#91768) Co-authored-by: Jackson Schuster <36744439+jtschuster@users.noreply.github.com> --- .../Marshaling/BaseJSGenerator.cs | 1 - .../Marshaling/EmptyJSGenerator.cs | 1 - .../ComInterfaceDispatchMarshallerFactory.cs | 2 - ...anagedHResultExceptionMarshallerFactory.cs | 2 - .../ObjectUnwrapperMarshallerFactory.cs | 1 - .../StructAsHResultMarshallerFactory.cs | 2 - .../gen/Common/Resources/Strings.resx | 57 +++--- .../gen/Common/Resources/xlf/Strings.cs.xlf | 5 - .../gen/Common/Resources/xlf/Strings.de.xlf | 5 - .../gen/Common/Resources/xlf/Strings.es.xlf | 5 - .../gen/Common/Resources/xlf/Strings.fr.xlf | 5 - .../gen/Common/Resources/xlf/Strings.it.xlf | 5 - .../gen/Common/Resources/xlf/Strings.ja.xlf | 5 - .../gen/Common/Resources/xlf/Strings.ko.xlf | 5 - .../gen/Common/Resources/xlf/Strings.pl.xlf | 5 - .../Common/Resources/xlf/Strings.pt-BR.xlf | 5 - .../gen/Common/Resources/xlf/Strings.ru.xlf | 5 - .../gen/Common/Resources/xlf/Strings.tr.xlf | 5 - .../Common/Resources/xlf/Strings.zh-Hans.xlf | 5 - .../Common/Resources/xlf/Strings.zh-Hant.xlf | 5 - .../LibraryImportGenerator.cs | 18 +- .../LibraryImportGeneratorHelpers.cs | 25 ++- .../PInvokeStubCodeGenerator.cs | 20 +- .../Marshalling/BlittableMarshaller.cs | 2 - .../Marshalling/BoolMarshaller.cs | 2 - .../Marshalling/CharMarshaller.cs | 6 - .../CustomTypeMarshallingGenerator.cs | 5 - .../Marshalling/DelegateMarshaller.cs | 2 - .../Marshalling/Forwarder.cs | 2 - .../MarshalAsMarshallingGeneratorFactory.cs | 16 -- .../Marshalling/MarshallingGenerator.cs | 8 - .../Marshalling/SafeHandleMarshaller.cs | 192 ------------------ .../StaticPinnableManagedValueMarshaller.cs | 3 - ...nagedToManagedOwnershipTrackingStrategy.cs | 1 - .../SafeHandleMarshallingInfoProvider.cs | 14 +- 35 files changed, 61 insertions(+), 386 deletions(-) delete mode 100644 src/libraries/System.Runtime.InteropServices/gen/Microsoft.Interop.SourceGeneration/Marshalling/SafeHandleMarshaller.cs diff --git a/src/libraries/System.Runtime.InteropServices.JavaScript/gen/JSImportGenerator/Marshaling/BaseJSGenerator.cs b/src/libraries/System.Runtime.InteropServices.JavaScript/gen/JSImportGenerator/Marshaling/BaseJSGenerator.cs index 97d158bb319de..798be15bc45df 100644 --- a/src/libraries/System.Runtime.InteropServices.JavaScript/gen/JSImportGenerator/Marshaling/BaseJSGenerator.cs +++ b/src/libraries/System.Runtime.InteropServices.JavaScript/gen/JSImportGenerator/Marshaling/BaseJSGenerator.cs @@ -22,7 +22,6 @@ protected BaseJSGenerator(MarshalerType marshalerType, IMarshallingGenerator inn } public ManagedTypeInfo AsNativeType(TypePositionInfo info) => _inner.AsNativeType(info); - public bool IsSupported(TargetFramework target, Version version) => _inner.IsSupported(target, version); public virtual bool UsesNativeIdentifier(TypePositionInfo info, StubCodeContext context) => _inner.UsesNativeIdentifier(info, context); public SignatureBehavior GetNativeSignatureBehavior(TypePositionInfo info) => _inner.GetNativeSignatureBehavior(info); public ValueBoundaryBehavior GetValueBoundaryBehavior(TypePositionInfo info, StubCodeContext context) => _inner.GetValueBoundaryBehavior(info, context); diff --git a/src/libraries/System.Runtime.InteropServices.JavaScript/gen/JSImportGenerator/Marshaling/EmptyJSGenerator.cs b/src/libraries/System.Runtime.InteropServices.JavaScript/gen/JSImportGenerator/Marshaling/EmptyJSGenerator.cs index 075d464b2bde7..060902fc1098a 100644 --- a/src/libraries/System.Runtime.InteropServices.JavaScript/gen/JSImportGenerator/Marshaling/EmptyJSGenerator.cs +++ b/src/libraries/System.Runtime.InteropServices.JavaScript/gen/JSImportGenerator/Marshaling/EmptyJSGenerator.cs @@ -14,7 +14,6 @@ internal sealed class EmptyJSGenerator : IJSMarshallingGenerator public IEnumerable GenerateBind(TypePositionInfo info, StubCodeContext context) => Array.Empty(); public SignatureBehavior GetNativeSignatureBehavior(TypePositionInfo info) => SignatureBehavior.ManagedTypeAndAttributes; public ValueBoundaryBehavior GetValueBoundaryBehavior(TypePositionInfo info, StubCodeContext context) => ValueBoundaryBehavior.ManagedIdentifier; - public bool IsSupported(TargetFramework target, Version version) => false; public ByValueMarshalKindSupport SupportsByValueMarshalKind(ByValueContentsMarshalKind marshalKind, TypePositionInfo info, StubCodeContext context, out GeneratorDiagnostic? diagnostic) => ByValueMarshalKindSupportDescriptor.Default.GetSupport(marshalKind, info, context, out diagnostic); public bool UsesNativeIdentifier(TypePositionInfo info, StubCodeContext context) => false; diff --git a/src/libraries/System.Runtime.InteropServices/gen/ComInterfaceGenerator/Marshallers/ComInterfaceDispatchMarshallerFactory.cs b/src/libraries/System.Runtime.InteropServices/gen/ComInterfaceGenerator/Marshallers/ComInterfaceDispatchMarshallerFactory.cs index a75cd8cad7726..86c67cbd4dadc 100644 --- a/src/libraries/System.Runtime.InteropServices/gen/ComInterfaceGenerator/Marshallers/ComInterfaceDispatchMarshallerFactory.cs +++ b/src/libraries/System.Runtime.InteropServices/gen/ComInterfaceGenerator/Marshallers/ComInterfaceDispatchMarshallerFactory.cs @@ -59,8 +59,6 @@ public IEnumerable Generate(TypePositionInfo info, StubCodeCont public SignatureBehavior GetNativeSignatureBehavior(TypePositionInfo info) => SignatureBehavior.NativeType; public ValueBoundaryBehavior GetValueBoundaryBehavior(TypePositionInfo info, StubCodeContext context) => ValueBoundaryBehavior.NativeIdentifier; - public bool IsSupported(TargetFramework target, Version version) - => target == TargetFramework.Net && version >= new Version(5, 0); public ByValueMarshalKindSupport SupportsByValueMarshalKind(ByValueContentsMarshalKind marshalKind, TypePositionInfo info, StubCodeContext context, out GeneratorDiagnostic? diagnostic) => ByValueMarshalKindSupportDescriptor.Default.GetSupport(marshalKind, info, context, out diagnostic); public bool UsesNativeIdentifier(TypePositionInfo info, StubCodeContext context) => true; diff --git a/src/libraries/System.Runtime.InteropServices/gen/ComInterfaceGenerator/Marshallers/ManagedHResultExceptionMarshallerFactory.cs b/src/libraries/System.Runtime.InteropServices/gen/ComInterfaceGenerator/Marshallers/ManagedHResultExceptionMarshallerFactory.cs index 0e6b17bd2ee43..c2f02efffeac1 100644 --- a/src/libraries/System.Runtime.InteropServices/gen/ComInterfaceGenerator/Marshallers/ManagedHResultExceptionMarshallerFactory.cs +++ b/src/libraries/System.Runtime.InteropServices/gen/ComInterfaceGenerator/Marshallers/ManagedHResultExceptionMarshallerFactory.cs @@ -68,7 +68,6 @@ public IEnumerable Generate(TypePositionInfo info, StubCodeCont public SignatureBehavior GetNativeSignatureBehavior(TypePositionInfo info) => SignatureBehavior.NativeType; public ValueBoundaryBehavior GetValueBoundaryBehavior(TypePositionInfo info, StubCodeContext context) => ValueBoundaryBehavior.ManagedIdentifier; - public bool IsSupported(TargetFramework target, Version version) => true; public ByValueMarshalKindSupport SupportsByValueMarshalKind(ByValueContentsMarshalKind marshalKind, TypePositionInfo info, StubCodeContext context, out GeneratorDiagnostic? diagnostic) => ByValueMarshalKindSupportDescriptor.Default.GetSupport(marshalKind, info, context, out diagnostic); public bool UsesNativeIdentifier(TypePositionInfo info, StubCodeContext context) => false; @@ -106,7 +105,6 @@ public IEnumerable Generate(TypePositionInfo info, StubCodeCont public SignatureBehavior GetNativeSignatureBehavior(TypePositionInfo info) => SignatureBehavior.NativeType; public ValueBoundaryBehavior GetValueBoundaryBehavior(TypePositionInfo info, StubCodeContext context) => ValueBoundaryBehavior.ManagedIdentifier; - public bool IsSupported(TargetFramework target, Version version) => true; public ByValueMarshalKindSupport SupportsByValueMarshalKind(ByValueContentsMarshalKind marshalKind, TypePositionInfo info, StubCodeContext context, out GeneratorDiagnostic? diagnostic) => ByValueMarshalKindSupportDescriptor.Default.GetSupport(marshalKind, info, context, out diagnostic); public bool UsesNativeIdentifier(TypePositionInfo info, StubCodeContext context) => false; diff --git a/src/libraries/System.Runtime.InteropServices/gen/ComInterfaceGenerator/Marshallers/ObjectUnwrapperMarshallerFactory.cs b/src/libraries/System.Runtime.InteropServices/gen/ComInterfaceGenerator/Marshallers/ObjectUnwrapperMarshallerFactory.cs index 75a7aa5064b73..2ca351cf53827 100644 --- a/src/libraries/System.Runtime.InteropServices/gen/ComInterfaceGenerator/Marshallers/ObjectUnwrapperMarshallerFactory.cs +++ b/src/libraries/System.Runtime.InteropServices/gen/ComInterfaceGenerator/Marshallers/ObjectUnwrapperMarshallerFactory.cs @@ -54,7 +54,6 @@ public IEnumerable Generate(TypePositionInfo info, StubCodeCont public SignatureBehavior GetNativeSignatureBehavior(TypePositionInfo info) => SignatureBehavior.NativeType; public ValueBoundaryBehavior GetValueBoundaryBehavior(TypePositionInfo info, StubCodeContext context) => ValueBoundaryBehavior.NativeIdentifier; - public bool IsSupported(TargetFramework target, Version version) => true; public ByValueMarshalKindSupport SupportsByValueMarshalKind(ByValueContentsMarshalKind marshalKind, TypePositionInfo info, StubCodeContext context, out GeneratorDiagnostic? diagnostic) => ByValueMarshalKindSupportDescriptor.Default.GetSupport(marshalKind, info, context, out diagnostic); public bool UsesNativeIdentifier(TypePositionInfo info, StubCodeContext context) => true; diff --git a/src/libraries/System.Runtime.InteropServices/gen/ComInterfaceGenerator/Marshallers/StructAsHResultMarshallerFactory.cs b/src/libraries/System.Runtime.InteropServices/gen/ComInterfaceGenerator/Marshallers/StructAsHResultMarshallerFactory.cs index e6eb9627b5acc..d8b41ca6e3732 100644 --- a/src/libraries/System.Runtime.InteropServices/gen/ComInterfaceGenerator/Marshallers/StructAsHResultMarshallerFactory.cs +++ b/src/libraries/System.Runtime.InteropServices/gen/ComInterfaceGenerator/Marshallers/StructAsHResultMarshallerFactory.cs @@ -98,8 +98,6 @@ public ValueBoundaryBehavior GetValueBoundaryBehavior(TypePositionInfo info, Stu return ValueBoundaryBehavior.NativeIdentifier; } - public bool IsSupported(TargetFramework target, Version version) => target == TargetFramework.Net && version.Major >= 8; - public ByValueMarshalKindSupport SupportsByValueMarshalKind(ByValueContentsMarshalKind marshalKind, TypePositionInfo info, StubCodeContext context, out GeneratorDiagnostic? diagnostic) => ByValueMarshalKindSupportDescriptor.Default.GetSupport(marshalKind, info, context, out diagnostic); diff --git a/src/libraries/System.Runtime.InteropServices/gen/Common/Resources/Strings.resx b/src/libraries/System.Runtime.InteropServices/gen/Common/Resources/Strings.resx index 2da298e8a7b0d..bce2c5ae18804 100644 --- a/src/libraries/System.Runtime.InteropServices/gen/Common/Resources/Strings.resx +++ b/src/libraries/System.Runtime.InteropServices/gen/Common/Resources/Strings.resx @@ -1,17 +1,17 @@  - @@ -144,9 +144,6 @@ Marshalling string or char without explicit marshalling information is not supported. Specify '{0}.StringMarshalling', '{0}.StringMarshallingCustomType', 'MarshalUsingAttribute' or 'MarshalAsAttribute'. - - An abstract type derived from 'SafeHandle' cannot be marshalled by reference. The provided type must be concrete. - This element cannot depend on '{0}' for collection size information without creating a dependency cycle diff --git a/src/libraries/System.Runtime.InteropServices/gen/Common/Resources/xlf/Strings.cs.xlf b/src/libraries/System.Runtime.InteropServices/gen/Common/Resources/xlf/Strings.cs.xlf index 48a9bc03b73a6..9f769d6c35c06 100644 --- a/src/libraries/System.Runtime.InteropServices/gen/Common/Resources/xlf/Strings.cs.xlf +++ b/src/libraries/System.Runtime.InteropServices/gen/Common/Resources/xlf/Strings.cs.xlf @@ -1022,11 +1022,6 @@ Aby se povolilo zařazování tohoto typu, musí se v tomto projektu zakázat zařazování modulu runtime použitím atributu System.Runtime.CompilerServices.DisableRuntimeMarshallingAttribute u sestavení. - - An abstract type derived from 'SafeHandle' cannot be marshalled by reference. The provided type must be concrete. - Abstraktní typ odvozený ze SafeHandle nelze zařadit pomocí odkazu. Poskytnutý typ musí být konkrétní. - - The size of parameter '{0}' that is marshalled to the callee must be defined when the method is called, but count parameter '{1}' is an 'out' parameter. Při volání metody musí být definována velikost parametru{0}, která je zařazena do volané metody, ale parametr count {1} je parametr out. diff --git a/src/libraries/System.Runtime.InteropServices/gen/Common/Resources/xlf/Strings.de.xlf b/src/libraries/System.Runtime.InteropServices/gen/Common/Resources/xlf/Strings.de.xlf index 3135aa3bbe7ea..a23a817897757 100644 --- a/src/libraries/System.Runtime.InteropServices/gen/Common/Resources/xlf/Strings.de.xlf +++ b/src/libraries/System.Runtime.InteropServices/gen/Common/Resources/xlf/Strings.de.xlf @@ -1022,11 +1022,6 @@ Das Runtime-Marshalling muss in diesem Projekt deaktiviert werden, indem „System.Runtime.CompilerServices.DisableRuntimeMarshallingAttribute“ auf die Assembly angewendet wird, um das Marshalling dieses Typs zu ermöglichen. - - An abstract type derived from 'SafeHandle' cannot be marshalled by reference. The provided type must be concrete. - Ein abstrakter Typ, der von \"SafeHandle\" abgeleitet wird, kann nicht als Verweis gemarshallt werden. Der angegebene Typ muss ein konkretes Element sein. - - The size of parameter '{0}' that is marshalled to the callee must be defined when the method is called, but count parameter '{1}' is an 'out' parameter. Die Größe des Parameters "{0}", der an den Aufgerufenen gemarshallt wird, muss definiert werden, wenn die Methode aufgerufen wird. Der Count-Parameter "{1}" ist jedoch ein "Out"-Parameter. diff --git a/src/libraries/System.Runtime.InteropServices/gen/Common/Resources/xlf/Strings.es.xlf b/src/libraries/System.Runtime.InteropServices/gen/Common/Resources/xlf/Strings.es.xlf index f0e4701f345cc..7d4da3d239110 100644 --- a/src/libraries/System.Runtime.InteropServices/gen/Common/Resources/xlf/Strings.es.xlf +++ b/src/libraries/System.Runtime.InteropServices/gen/Common/Resources/xlf/Strings.es.xlf @@ -1022,11 +1022,6 @@ La serialización en tiempo de ejecución debe deshabilitarse en este proyecto aplicando \"System.Runtime.CompilerServices.DisableRuntimeMars contosoingAttribute\" al ensamblado para habilitar la serialización de este tipo. - - An abstract type derived from 'SafeHandle' cannot be marshalled by reference. The provided type must be concrete. - Un tipo abstracto derivado de “SafeHandle” no se puede serializar por referencia. El tipo proporcionado debe ser concreto. - - The size of parameter '{0}' that is marshalled to the callee must be defined when the method is called, but count parameter '{1}' is an 'out' parameter. El tamaño del parámetro "{0}" que se serializa al destinatario debe definirse cuando se llama al método, pero el parámetro de recuento "{1}" es un parámetro "out". diff --git a/src/libraries/System.Runtime.InteropServices/gen/Common/Resources/xlf/Strings.fr.xlf b/src/libraries/System.Runtime.InteropServices/gen/Common/Resources/xlf/Strings.fr.xlf index 228abb0f43b9c..467413d83f430 100644 --- a/src/libraries/System.Runtime.InteropServices/gen/Common/Resources/xlf/Strings.fr.xlf +++ b/src/libraries/System.Runtime.InteropServices/gen/Common/Resources/xlf/Strings.fr.xlf @@ -1022,11 +1022,6 @@ Le marshaling du runtime doit être désactivé dans ce projet en appliquant « System.Runtime.CompilerServices.DisableRuntimeMarshallingAttribute » à l’assembly pour activer le marshaling de ce type. - - An abstract type derived from 'SafeHandle' cannot be marshalled by reference. The provided type must be concrete. - Un type abstrait dérivé de « SafeHandle » ne peut pas être marshalé par référence. Le type fourni doit être concret. - - The size of parameter '{0}' that is marshalled to the callee must be defined when the method is called, but count parameter '{1}' is an 'out' parameter. La taille du paramètre '{0}' qui est marshalé à l'appelé doit être définie lorsque la méthode est appelée, mais le paramètre count '{1}' est un paramètre 'out'. diff --git a/src/libraries/System.Runtime.InteropServices/gen/Common/Resources/xlf/Strings.it.xlf b/src/libraries/System.Runtime.InteropServices/gen/Common/Resources/xlf/Strings.it.xlf index 58c83094b063b..7af807ca8b6f6 100644 --- a/src/libraries/System.Runtime.InteropServices/gen/Common/Resources/xlf/Strings.it.xlf +++ b/src/libraries/System.Runtime.InteropServices/gen/Common/Resources/xlf/Strings.it.xlf @@ -1022,11 +1022,6 @@ Il marshalling di runtime in questo progetto deve essere disabilitato applicando 'System.Runtime.CompilerServices.DisableRuntimeMarshallingAttribute' all'assembly per abilitare il marshalling di questo tipo. - - An abstract type derived from 'SafeHandle' cannot be marshalled by reference. The provided type must be concrete. - Non è possibile effettuare il marshalling per riferimento di un tipo astratto derivato da 'SafeHandle'. Il tipo specificato deve essere concreto. - - The size of parameter '{0}' that is marshalled to the callee must be defined when the method is called, but count parameter '{1}' is an 'out' parameter. Le dimensioni del parametro '{0}' di cui viene eseguito il marshalling al destinatario della chiamata devono essere definite quando viene chiamato il metodo, ma il parametro conteggio '{1}' è un parametro 'out'. diff --git a/src/libraries/System.Runtime.InteropServices/gen/Common/Resources/xlf/Strings.ja.xlf b/src/libraries/System.Runtime.InteropServices/gen/Common/Resources/xlf/Strings.ja.xlf index 331eb28eaa414..900871e573895 100644 --- a/src/libraries/System.Runtime.InteropServices/gen/Common/Resources/xlf/Strings.ja.xlf +++ b/src/libraries/System.Runtime.InteropServices/gen/Common/Resources/xlf/Strings.ja.xlf @@ -1022,11 +1022,6 @@ このプロジェクトでは、アセンブリに 'System.Runtime.CompilerServices.DisableRuntimeMarshallingAttribute' を適用してランタイム マーシャリングを無効にし、この型のマーシャリングを有効にする必要があります。 - - An abstract type derived from 'SafeHandle' cannot be marshalled by reference. The provided type must be concrete. - 'SafeHandle' から派生した抽象型は、参照でマーシャリングできません。指定される型は具象型である必要があります。 - - The size of parameter '{0}' that is marshalled to the callee must be defined when the method is called, but count parameter '{1}' is an 'out' parameter. 呼び出し先にマーシャリングされるパラメーター '{0}' のサイズは、メソッドが呼び出されたときに定義する必要がありますが、count パラメーター '{1}' は 'out' パラメーターです。 diff --git a/src/libraries/System.Runtime.InteropServices/gen/Common/Resources/xlf/Strings.ko.xlf b/src/libraries/System.Runtime.InteropServices/gen/Common/Resources/xlf/Strings.ko.xlf index aedf84c829c06..c2061f1c47ed0 100644 --- a/src/libraries/System.Runtime.InteropServices/gen/Common/Resources/xlf/Strings.ko.xlf +++ b/src/libraries/System.Runtime.InteropServices/gen/Common/Resources/xlf/Strings.ko.xlf @@ -1022,11 +1022,6 @@ 이 형식의 마샬링을 활성화하려면 어셈블리에 'System.Runtime.CompilerServices.DisableRuntimeMarshallingAttribute'를 적용하여 이 프로젝트에서 런타임 마샬링을 비활성화해야 합니다. - - An abstract type derived from 'SafeHandle' cannot be marshalled by reference. The provided type must be concrete. - 'SafeHandle'에서 파생된 추상 형식은 참조로 마샬링할 수 없습니다. 제공된 형식은 구체적이어야 합니다. - - The size of parameter '{0}' that is marshalled to the callee must be defined when the method is called, but count parameter '{1}' is an 'out' parameter. 메서드를 호출할 때 호출 수신자로 마샬링되는 매개 변수 '{0}'의 크기를 정의해야 하지만 count 매개 변수 '{1}'은(는) 'out' 매개 변수입니다. diff --git a/src/libraries/System.Runtime.InteropServices/gen/Common/Resources/xlf/Strings.pl.xlf b/src/libraries/System.Runtime.InteropServices/gen/Common/Resources/xlf/Strings.pl.xlf index f051d95f3b9c9..4a5bed01000cb 100644 --- a/src/libraries/System.Runtime.InteropServices/gen/Common/Resources/xlf/Strings.pl.xlf +++ b/src/libraries/System.Runtime.InteropServices/gen/Common/Resources/xlf/Strings.pl.xlf @@ -1022,11 +1022,6 @@ Marshalling środowiska uruchomieniowego musi być wyłączony w tym projekcie przez zastosowanie do zestawu atrybutu „System.Runtime.InteropServices.DisableRuntimeMarshallingAttribute”, aby umożliwić marshalling tego typu. - - An abstract type derived from 'SafeHandle' cannot be marshalled by reference. The provided type must be concrete. - Typ abstrakcyjny pochodzący od elementu „SafeHandle” nie może być skierowany przez odwołanie. Podany typ musi być konkretny. - - The size of parameter '{0}' that is marshalled to the callee must be defined when the method is called, but count parameter '{1}' is an 'out' parameter. Rozmiar parametru „{0}”, który jest kierowany do obiektu wywołującego, musi być zdefiniowany podczas wywoływania metody, ale parametr ILE.LICZB „{1}” jest parametrem „out”. diff --git a/src/libraries/System.Runtime.InteropServices/gen/Common/Resources/xlf/Strings.pt-BR.xlf b/src/libraries/System.Runtime.InteropServices/gen/Common/Resources/xlf/Strings.pt-BR.xlf index c1bc60315bc05..a2dcb00fc8aa2 100644 --- a/src/libraries/System.Runtime.InteropServices/gen/Common/Resources/xlf/Strings.pt-BR.xlf +++ b/src/libraries/System.Runtime.InteropServices/gen/Common/Resources/xlf/Strings.pt-BR.xlf @@ -1022,11 +1022,6 @@ O marshalling de tempo de execução deve ser desabilitado neste projeto aplicando o 'System.Runtime.CompilerServices.DisableRuntimeMarshallingAttribute' ao assembly para habilitar o marshalling desse tipo. - - An abstract type derived from 'SafeHandle' cannot be marshalled by reference. The provided type must be concrete. - Um tipo abstrato derivado de 'SafeHandle' não pode ser marshalled por referência. O tipo fornecido deve ser concreto. - - The size of parameter '{0}' that is marshalled to the callee must be defined when the method is called, but count parameter '{1}' is an 'out' parameter. O tamanho do parâmetro '{0}' que é empacotado para o receptor deve ser definido quando o método é chamado, mas o parâmetro de contagem '{1}' é um parâmetro 'out'. diff --git a/src/libraries/System.Runtime.InteropServices/gen/Common/Resources/xlf/Strings.ru.xlf b/src/libraries/System.Runtime.InteropServices/gen/Common/Resources/xlf/Strings.ru.xlf index 891ef9d077eb6..9631d6c981aac 100644 --- a/src/libraries/System.Runtime.InteropServices/gen/Common/Resources/xlf/Strings.ru.xlf +++ b/src/libraries/System.Runtime.InteropServices/gen/Common/Resources/xlf/Strings.ru.xlf @@ -1022,11 +1022,6 @@ В этом проекте следует отключить маршализацию среды выполнения путем применения к сборке атрибута \"System.Runtime.CompilerServices.DisableRuntimeMarshallingAttribute\" для включения маршализации этого типа. - - An abstract type derived from 'SafeHandle' cannot be marshalled by reference. The provided type must be concrete. - Абстрактный тип, производный от \"SafeHandle\", нельзя маршализировать по ссылке. Указанный тип должен быть конкретным. - - The size of parameter '{0}' that is marshalled to the callee must be defined when the method is called, but count parameter '{1}' is an 'out' parameter. При вызове метода должен быть определен размер параметра "{0}", который был маршалирован вызываемому абоненту, но исчисляемый параметр "{1}" является выходным. diff --git a/src/libraries/System.Runtime.InteropServices/gen/Common/Resources/xlf/Strings.tr.xlf b/src/libraries/System.Runtime.InteropServices/gen/Common/Resources/xlf/Strings.tr.xlf index 6748b1305030b..06f7c1279e14a 100644 --- a/src/libraries/System.Runtime.InteropServices/gen/Common/Resources/xlf/Strings.tr.xlf +++ b/src/libraries/System.Runtime.InteropServices/gen/Common/Resources/xlf/Strings.tr.xlf @@ -1022,11 +1022,6 @@ Bu türü sıralamayı etkinleştirmek için derlemeye 'System.Runtime.CompilerServices.DisableRuntimeMarshallingAttribute' uygulanarak bu projede çalışma zamanı sıralaması devre dışı bırakılmalıdır. - - An abstract type derived from 'SafeHandle' cannot be marshalled by reference. The provided type must be concrete. - 'SafeHandle' özelliğinden türetilen soyut türler, başvuruya göre sıralanamaz. Sağlanan tür somut olmalıdır. - - The size of parameter '{0}' that is marshalled to the callee must be defined when the method is called, but count parameter '{1}' is an 'out' parameter. Aramanın alıcısına hazırlanan '{0}' parametresinin boyutu yöntem çağrıldığında tanımlanmalıdır ancak '{1}' sayı parametresi bir ‘çıkış’ parametresidir. diff --git a/src/libraries/System.Runtime.InteropServices/gen/Common/Resources/xlf/Strings.zh-Hans.xlf b/src/libraries/System.Runtime.InteropServices/gen/Common/Resources/xlf/Strings.zh-Hans.xlf index de0d085a227a7..9cf9ccbc906f5 100644 --- a/src/libraries/System.Runtime.InteropServices/gen/Common/Resources/xlf/Strings.zh-Hans.xlf +++ b/src/libraries/System.Runtime.InteropServices/gen/Common/Resources/xlf/Strings.zh-Hans.xlf @@ -1022,11 +1022,6 @@ 必须通过将 \"System.Runtime.CompilerServices.DisableRuntimeMarshallingAttribute\" 应用到程序集来在此项目中禁用运行时封送,以启用此类型的封送处理。 - - An abstract type derived from 'SafeHandle' cannot be marshalled by reference. The provided type must be concrete. - 无法通过引用封送派生自 “SafeHandle” 的抽象类型。提供的类型必须是具体的。 - - The size of parameter '{0}' that is marshalled to the callee must be defined when the method is called, but count parameter '{1}' is an 'out' parameter. 调用方法时,必须定义封送给被调用方的参数“{0}”的大小,但计数参数“{1}”是一个 "out" 参数。 diff --git a/src/libraries/System.Runtime.InteropServices/gen/Common/Resources/xlf/Strings.zh-Hant.xlf b/src/libraries/System.Runtime.InteropServices/gen/Common/Resources/xlf/Strings.zh-Hant.xlf index 408df3131a3be..08a0d9ac8eb54 100644 --- a/src/libraries/System.Runtime.InteropServices/gen/Common/Resources/xlf/Strings.zh-Hant.xlf +++ b/src/libraries/System.Runtime.InteropServices/gen/Common/Resources/xlf/Strings.zh-Hant.xlf @@ -1022,11 +1022,6 @@ 必須將 'System.Runtime.CompilerServices.DisableRuntimeMarshallingAttribute' 套用到組件,以停用此專案中的執行階段封送處理,以啟用此類型的封送處理。 - - An abstract type derived from 'SafeHandle' cannot be marshalled by reference. The provided type must be concrete. - 衍生自 'SafeHandle' 的抽象類型無法依參考排列。提供的類型必須是實體。 - - The size of parameter '{0}' that is marshalled to the callee must be defined when the method is called, but count parameter '{1}' is an 'out' parameter. 呼叫方法時,必須定義封送處理給被呼叫者的參數 '{0}' 的大小,但 count 參數 '{1}' 是 'out' 參數。 diff --git a/src/libraries/System.Runtime.InteropServices/gen/LibraryImportGenerator/LibraryImportGenerator.cs b/src/libraries/System.Runtime.InteropServices/gen/LibraryImportGenerator/LibraryImportGenerator.cs index 6b3bd18466497..b3fdc79bdec95 100644 --- a/src/libraries/System.Runtime.InteropServices/gen/LibraryImportGenerator/LibraryImportGenerator.cs +++ b/src/libraries/System.Runtime.InteropServices/gen/LibraryImportGenerator/LibraryImportGenerator.cs @@ -313,6 +313,20 @@ private static (MemberDeclarationSyntax, ImmutableArray) Generat return (PrintForwarderStub(pinvokeStub.StubMethodSyntaxTemplate, explicitForwarding: true, pinvokeStub, diagnostics), pinvokeStub.Diagnostics.Array.AddRange(diagnostics.Diagnostics)); } + bool supportsTargetFramework = !pinvokeStub.LibraryImportData.SetLastError + || options.GenerateForwarders + || (pinvokeStub.GeneratorFactoryKey.Key.TargetFramework == TargetFramework.Net + && pinvokeStub.GeneratorFactoryKey.Key.Version.Major >= 6); + + foreach (TypePositionInfo typeInfo in pinvokeStub.SignatureContext.ElementTypeInformation) + { + if (typeInfo.MarshallingAttributeInfo is MissingSupportMarshallingInfo) + { + supportsTargetFramework = false; + break; + } + } + // Generate stub code var stubGenerator = new PInvokeStubCodeGenerator( pinvokeStub.GeneratorFactoryKey.Key.TargetFramework, @@ -325,9 +339,9 @@ private static (MemberDeclarationSyntax, ImmutableArray) Generat // Check if the generator should produce a forwarder stub - regular DllImport. // This is done if the signature is blittable or the target framework is not supported. if (stubGenerator.StubIsBasicForwarder - || !stubGenerator.SupportsTargetFramework) + || !supportsTargetFramework) { - return (PrintForwarderStub(pinvokeStub.StubMethodSyntaxTemplate, !stubGenerator.SupportsTargetFramework, pinvokeStub, diagnostics), pinvokeStub.Diagnostics.Array.AddRange(diagnostics.Diagnostics)); + return (PrintForwarderStub(pinvokeStub.StubMethodSyntaxTemplate, !supportsTargetFramework, pinvokeStub, diagnostics), pinvokeStub.Diagnostics.Array.AddRange(diagnostics.Diagnostics)); } ImmutableArray forwardedAttributes = pinvokeStub.ForwardedAttributes.Array; diff --git a/src/libraries/System.Runtime.InteropServices/gen/LibraryImportGenerator/LibraryImportGeneratorHelpers.cs b/src/libraries/System.Runtime.InteropServices/gen/LibraryImportGenerator/LibraryImportGeneratorHelpers.cs index d07d101732b04..44e316c419ff2 100644 --- a/src/libraries/System.Runtime.InteropServices/gen/LibraryImportGenerator/LibraryImportGeneratorHelpers.cs +++ b/src/libraries/System.Runtime.InteropServices/gen/LibraryImportGenerator/LibraryImportGeneratorHelpers.cs @@ -48,17 +48,20 @@ internal static class LibraryImportGeneratorHelpers InteropGenerationOptions interopGenerationOptions = new(options.UseMarshalType); generatorFactory = new MarshalAsMarshallingGeneratorFactory(interopGenerationOptions, generatorFactory); - IMarshallingGeneratorFactory elementFactory = new AttributedMarshallingModelGeneratorFactory( - // Since the char type in an array will not be part of the P/Invoke signature, we can - // use the regular blittable marshaller in all cases. - new CharMarshallingGeneratorFactory(generatorFactory, useBlittableMarshallerForUtf16: true, TypeNames.LibraryImportAttribute_ShortName), - new AttributedMarshallingModelOptions(runtimeMarshallingDisabled, MarshalMode.ElementIn, MarshalMode.ElementRef, MarshalMode.ElementOut)); - // We don't need to include the later generator factories for collection elements - // as the later generator factories only apply to parameters. - generatorFactory = new AttributedMarshallingModelGeneratorFactory( - generatorFactory, - elementFactory, - new AttributedMarshallingModelOptions(runtimeMarshallingDisabled, MarshalMode.ManagedToUnmanagedIn, MarshalMode.ManagedToUnmanagedRef, MarshalMode.ManagedToUnmanagedOut)); + if (env.TargetFramework == TargetFramework.Net || env.TargetFrameworkVersion.Major >= 7) + { + IMarshallingGeneratorFactory elementFactory = new AttributedMarshallingModelGeneratorFactory( + // Since the char type in an array will not be part of the P/Invoke signature, we can + // use the regular blittable marshaller in all cases. + new CharMarshallingGeneratorFactory(generatorFactory, useBlittableMarshallerForUtf16: true, TypeNames.LibraryImportAttribute_ShortName), + new AttributedMarshallingModelOptions(runtimeMarshallingDisabled, MarshalMode.ElementIn, MarshalMode.ElementRef, MarshalMode.ElementOut)); + // We don't need to include the later generator factories for collection elements + // as the later generator factories only apply to parameters. + generatorFactory = new AttributedMarshallingModelGeneratorFactory( + generatorFactory, + elementFactory, + new AttributedMarshallingModelOptions(runtimeMarshallingDisabled, MarshalMode.ManagedToUnmanagedIn, MarshalMode.ManagedToUnmanagedRef, MarshalMode.ManagedToUnmanagedOut)); + } generatorFactory = new ByValueContentsMarshalKindValidator(generatorFactory); } diff --git a/src/libraries/System.Runtime.InteropServices/gen/LibraryImportGenerator/PInvokeStubCodeGenerator.cs b/src/libraries/System.Runtime.InteropServices/gen/LibraryImportGenerator/PInvokeStubCodeGenerator.cs index 2a1ac3921188c..ec9283cc46598 100644 --- a/src/libraries/System.Runtime.InteropServices/gen/LibraryImportGenerator/PInvokeStubCodeGenerator.cs +++ b/src/libraries/System.Runtime.InteropServices/gen/LibraryImportGenerator/PInvokeStubCodeGenerator.cs @@ -28,8 +28,6 @@ namespace Microsoft.Interop /// internal sealed class PInvokeStubCodeGenerator { - public bool SupportsTargetFramework { get; } - public bool StubIsBasicForwarder { get; } /// @@ -57,18 +55,6 @@ public PInvokeStubCodeGenerator( { _setLastError = setLastError; - // Support for SetLastError logic requires .NET 6+. Initialize the - // supports target framework value with this value. - if (_setLastError) - { - SupportsTargetFramework = targetFramework == TargetFramework.Net - && targetFrameworkVersion.Major >= 6; - } - else - { - SupportsTargetFramework = true; - } - _context = new ManagedToNativeStubCodeContext(targetFramework, targetFrameworkVersion, ReturnIdentifier, ReturnIdentifier); _marshallers = BoundGenerators.Create(argTypes, generatorFactory, _context, new Forwarder(), out var bindingDiagnostics); @@ -84,17 +70,13 @@ public PInvokeStubCodeGenerator( foreach (BoundGenerator generator in _marshallers.SignatureMarshallers) { - // Check if marshalling info and generator support the current target framework. - SupportsTargetFramework &= generator.TypeInfo.MarshallingAttributeInfo is not MissingSupportMarshallingInfo - && generator.Generator.IsSupported(targetFramework, targetFrameworkVersion); - // Check if generator is either blittable or just a forwarder. noMarshallingNeeded &= generator is { Generator: BlittableMarshaller, TypeInfo.IsByRef: false } or { Generator: Forwarder }; } StubIsBasicForwarder = !setLastError - && _marshallers.ManagedNativeSameReturn // If the managed return has native return position, then it's the return for both. + && _marshallers.ManagedNativeSameReturn && noMarshallingNeeded; } diff --git a/src/libraries/System.Runtime.InteropServices/gen/Microsoft.Interop.SourceGeneration/Marshalling/BlittableMarshaller.cs b/src/libraries/System.Runtime.InteropServices/gen/Microsoft.Interop.SourceGeneration/Marshalling/BlittableMarshaller.cs index ef2542dd87bc8..76577d497cb82 100644 --- a/src/libraries/System.Runtime.InteropServices/gen/Microsoft.Interop.SourceGeneration/Marshalling/BlittableMarshaller.cs +++ b/src/libraries/System.Runtime.InteropServices/gen/Microsoft.Interop.SourceGeneration/Marshalling/BlittableMarshaller.cs @@ -11,8 +11,6 @@ namespace Microsoft.Interop { public sealed class BlittableMarshaller : IMarshallingGenerator { - public bool IsSupported(TargetFramework target, Version version) => true; - public ManagedTypeInfo AsNativeType(TypePositionInfo info) { return info.ManagedType; diff --git a/src/libraries/System.Runtime.InteropServices/gen/Microsoft.Interop.SourceGeneration/Marshalling/BoolMarshaller.cs b/src/libraries/System.Runtime.InteropServices/gen/Microsoft.Interop.SourceGeneration/Marshalling/BoolMarshaller.cs index a86df409e84a7..dbb1b3ee08c91 100644 --- a/src/libraries/System.Runtime.InteropServices/gen/Microsoft.Interop.SourceGeneration/Marshalling/BoolMarshaller.cs +++ b/src/libraries/System.Runtime.InteropServices/gen/Microsoft.Interop.SourceGeneration/Marshalling/BoolMarshaller.cs @@ -26,8 +26,6 @@ protected BoolMarshallerBase(ManagedTypeInfo nativeType, int trueValue, int fals _compareToTrue = compareToTrue; } - public bool IsSupported(TargetFramework target, Version version) => true; - public ManagedTypeInfo AsNativeType(TypePositionInfo info) { Debug.Assert(info.ManagedType is SpecialTypeInfo(_, _, SpecialType.System_Boolean)); diff --git a/src/libraries/System.Runtime.InteropServices/gen/Microsoft.Interop.SourceGeneration/Marshalling/CharMarshaller.cs b/src/libraries/System.Runtime.InteropServices/gen/Microsoft.Interop.SourceGeneration/Marshalling/CharMarshaller.cs index 3357dc86fa333..e02bf7826a85d 100644 --- a/src/libraries/System.Runtime.InteropServices/gen/Microsoft.Interop.SourceGeneration/Marshalling/CharMarshaller.cs +++ b/src/libraries/System.Runtime.InteropServices/gen/Microsoft.Interop.SourceGeneration/Marshalling/CharMarshaller.cs @@ -15,12 +15,6 @@ public sealed class Utf16CharMarshaller : IMarshallingGenerator { private static readonly ManagedTypeInfo s_nativeType = new SpecialTypeInfo("ushort", "ushort", SpecialType.System_UInt16); - public Utf16CharMarshaller() - { - } - - public bool IsSupported(TargetFramework target, Version version) => true; - public ValueBoundaryBehavior GetValueBoundaryBehavior(TypePositionInfo info, StubCodeContext context) { if (IsPinningPathSupported(info, context)) diff --git a/src/libraries/System.Runtime.InteropServices/gen/Microsoft.Interop.SourceGeneration/Marshalling/CustomTypeMarshallingGenerator.cs b/src/libraries/System.Runtime.InteropServices/gen/Microsoft.Interop.SourceGeneration/Marshalling/CustomTypeMarshallingGenerator.cs index 30f333d59540e..9c65fdc5e7c50 100644 --- a/src/libraries/System.Runtime.InteropServices/gen/Microsoft.Interop.SourceGeneration/Marshalling/CustomTypeMarshallingGenerator.cs +++ b/src/libraries/System.Runtime.InteropServices/gen/Microsoft.Interop.SourceGeneration/Marshalling/CustomTypeMarshallingGenerator.cs @@ -23,11 +23,6 @@ public CustomTypeMarshallingGenerator(ICustomTypeMarshallingStrategy nativeTypeM _isPinned = isPinned; } - public bool IsSupported(TargetFramework target, Version version) - { - return target is TargetFramework.Net && version.Major >= 6; - } - public ValueBoundaryBehavior GetValueBoundaryBehavior(TypePositionInfo info, StubCodeContext context) { return info.IsByRef ? ValueBoundaryBehavior.AddressOfNativeIdentifier : ValueBoundaryBehavior.NativeIdentifier; diff --git a/src/libraries/System.Runtime.InteropServices/gen/Microsoft.Interop.SourceGeneration/Marshalling/DelegateMarshaller.cs b/src/libraries/System.Runtime.InteropServices/gen/Microsoft.Interop.SourceGeneration/Marshalling/DelegateMarshaller.cs index 4dddd38948c6d..5f52ad6e4e730 100644 --- a/src/libraries/System.Runtime.InteropServices/gen/Microsoft.Interop.SourceGeneration/Marshalling/DelegateMarshaller.cs +++ b/src/libraries/System.Runtime.InteropServices/gen/Microsoft.Interop.SourceGeneration/Marshalling/DelegateMarshaller.cs @@ -12,8 +12,6 @@ namespace Microsoft.Interop { public sealed class DelegateMarshaller : IMarshallingGenerator { - public bool IsSupported(TargetFramework target, Version version) => true; - public ManagedTypeInfo AsNativeType(TypePositionInfo info) { return SpecialTypeInfo.IntPtr; diff --git a/src/libraries/System.Runtime.InteropServices/gen/Microsoft.Interop.SourceGeneration/Marshalling/Forwarder.cs b/src/libraries/System.Runtime.InteropServices/gen/Microsoft.Interop.SourceGeneration/Marshalling/Forwarder.cs index 79c2fd999f00a..9679a2e7449c9 100644 --- a/src/libraries/System.Runtime.InteropServices/gen/Microsoft.Interop.SourceGeneration/Marshalling/Forwarder.cs +++ b/src/libraries/System.Runtime.InteropServices/gen/Microsoft.Interop.SourceGeneration/Marshalling/Forwarder.cs @@ -9,8 +9,6 @@ namespace Microsoft.Interop { public sealed class Forwarder : IMarshallingGenerator { - public bool IsSupported(TargetFramework target, Version version) => true; - public ManagedTypeInfo AsNativeType(TypePositionInfo info) { return info.ManagedType; diff --git a/src/libraries/System.Runtime.InteropServices/gen/Microsoft.Interop.SourceGeneration/Marshalling/MarshalAsMarshallingGeneratorFactory.cs b/src/libraries/System.Runtime.InteropServices/gen/Microsoft.Interop.SourceGeneration/Marshalling/MarshalAsMarshallingGeneratorFactory.cs index 1aa0d96779f9c..a79f14c02ed12 100644 --- a/src/libraries/System.Runtime.InteropServices/gen/Microsoft.Interop.SourceGeneration/Marshalling/MarshalAsMarshallingGeneratorFactory.cs +++ b/src/libraries/System.Runtime.InteropServices/gen/Microsoft.Interop.SourceGeneration/Marshalling/MarshalAsMarshallingGeneratorFactory.cs @@ -18,7 +18,6 @@ public sealed class MarshalAsMarshallingGeneratorFactory : IMarshallingGenerator private static readonly Forwarder s_forwarder = new(); private static readonly BlittableMarshaller s_blittable = new(); private static readonly DelegateMarshaller s_delegate = new(); - private static readonly SafeHandleMarshaller s_safeHandle = new(); private InteropGenerationOptions Options { get; } private IMarshallingGeneratorFactory InnerFactory { get; } @@ -90,21 +89,6 @@ public ResolvedGenerator Create( case { ManagedType: DelegateTypeInfo, MarshallingAttributeInfo: NoMarshallingInfo or MarshalAsInfo(UnmanagedType.FunctionPtr, _) }: return ResolvedGenerator.Resolved(s_delegate); - // SafeHandle types with source-generator-emitted marshalling - case { MarshallingAttributeInfo: SafeHandleMarshallingInfo(_, bool isAbstract) }: - if (!context.AdditionalTemporaryStateLivesAcrossStages || context.Direction != MarshalDirection.ManagedToUnmanaged) - { - return ResolvedGenerator.NotSupported(new(info, context)); - } - if (info.IsByRef && isAbstract) - { - return ResolvedGenerator.NotSupported(new(info, context) - { - NotSupportedDetails = SR.SafeHandleByRefMustBeConcrete - }); - } - return ResolvedGenerator.Resolved(s_safeHandle); - // void case { ManagedType: SpecialTypeInfo { SpecialType: SpecialType.System_Void } }: return ResolvedGenerator.Resolved(s_forwarder); diff --git a/src/libraries/System.Runtime.InteropServices/gen/Microsoft.Interop.SourceGeneration/Marshalling/MarshallingGenerator.cs b/src/libraries/System.Runtime.InteropServices/gen/Microsoft.Interop.SourceGeneration/Marshalling/MarshallingGenerator.cs index 598ba38002894..d320624651f00 100644 --- a/src/libraries/System.Runtime.InteropServices/gen/Microsoft.Interop.SourceGeneration/Marshalling/MarshallingGenerator.cs +++ b/src/libraries/System.Runtime.InteropServices/gen/Microsoft.Interop.SourceGeneration/Marshalling/MarshallingGenerator.cs @@ -94,14 +94,6 @@ public enum ByValueMarshalKindSupport /// public interface IMarshallingGenerator { - /// - /// Determine if the generator is supported for the supplied version of the framework. - /// - /// The framework to target. - /// The version of the framework. - /// True if the marshaller is supported, otherwise false. - bool IsSupported(TargetFramework target, Version version); - /// /// Get the native type syntax for /// diff --git a/src/libraries/System.Runtime.InteropServices/gen/Microsoft.Interop.SourceGeneration/Marshalling/SafeHandleMarshaller.cs b/src/libraries/System.Runtime.InteropServices/gen/Microsoft.Interop.SourceGeneration/Marshalling/SafeHandleMarshaller.cs deleted file mode 100644 index 3f813787e61e5..0000000000000 --- a/src/libraries/System.Runtime.InteropServices/gen/Microsoft.Interop.SourceGeneration/Marshalling/SafeHandleMarshaller.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. - -using System; -using System.Collections.Generic; -using System.Runtime.InteropServices; -using Microsoft.CodeAnalysis; -using Microsoft.CodeAnalysis.CSharp; -using Microsoft.CodeAnalysis.CSharp.Syntax; -using static Microsoft.CodeAnalysis.CSharp.SyntaxFactory; -using static Microsoft.Interop.SyntaxFactoryExtensions; - -namespace Microsoft.Interop -{ - public sealed class SafeHandleMarshaller : IMarshallingGenerator - { - public bool IsSupported(TargetFramework target, Version version) - { - return target is TargetFramework.Net && version.Major >= 6; - } - - public ManagedTypeInfo AsNativeType(TypePositionInfo info) - { - return SpecialTypeInfo.IntPtr; - } - - public SignatureBehavior GetNativeSignatureBehavior(TypePositionInfo info) - { - return info.IsByRef ? SignatureBehavior.PointerToNativeType : SignatureBehavior.NativeType; - } - - public ValueBoundaryBehavior GetValueBoundaryBehavior(TypePositionInfo info, StubCodeContext context) - { - return info.IsByRef ? ValueBoundaryBehavior.AddressOfNativeIdentifier : ValueBoundaryBehavior.NativeIdentifier; - } - - public IEnumerable Generate(TypePositionInfo info, StubCodeContext context) - { - // The high level logic (note that the parameter may be in, out or both): - // 1) If this is an input parameter we need to AddRef the SafeHandle. - // 2) If this is an output parameter we need to preallocate a SafeHandle to wrap the new native handle value. We - // must allocate this before the native call to avoid a failure point when we already have a native resource - // allocated. We must allocate a new SafeHandle even if we have one on input since both input and output native - // handles need to be tracked and released by a SafeHandle. - // 3) Initialize a local IntPtr that will be passed to the native call. If we have an input SafeHandle the value - // comes from there otherwise we get it from the new SafeHandle (which is guaranteed to be initialized to an - // invalid handle value). - // 4) If this is a out parameter we also store the original handle value (that we just computed above) in a local - // variable. - // 5) If we successfully AddRef'd the incoming SafeHandle, we need to Release it before we return. - // 6) After the native call, if this is an output parameter and the handle value we passed to native differs from - // the local copy we made then the new handle value is written into the output SafeHandle and that SafeHandle - // is propagated back to the caller. - - (string managedIdentifier, string nativeIdentifier) = context.GetIdentifiers(info); - string addRefdIdentifier = $"{managedIdentifier}__addRefd"; - string newHandleObjectIdentifier = info.IsManagedReturnPosition - ? managedIdentifier - : $"{managedIdentifier}__newHandle"; - string handleValueBackupIdentifier = $"{nativeIdentifier}__original"; - switch (context.CurrentStage) - { - case StubCodeContext.Stage.Setup: - if (!info.IsManagedReturnPosition && info.RefKind != RefKind.Out) - { - yield return LocalDeclarationStatement( - VariableDeclaration( - PredefinedType(Token(SyntaxKind.BoolKeyword)), - SingletonSeparatedList( - VariableDeclarator(addRefdIdentifier) - .WithInitializer(EqualsValueClause(LiteralExpression(SyntaxKind.FalseLiteralExpression)))))); - } - - ExpressionSyntax safeHandleCreationExpression = ((SafeHandleMarshallingInfo)info.MarshallingAttributeInfo).AccessibleDefaultConstructor - ? ObjectCreationExpression(info.ManagedType.Syntax, ArgumentList(), initializer: null) - : CastExpression( - info.ManagedType.Syntax, - MethodInvocation( - TypeSyntaxes.System_Activator, - IdentifierName("CreateInstance"), - Argument(TypeOfExpression(info.ManagedType.Syntax)), - Argument(LiteralExpression(SyntaxKind.TrueLiteralExpression)) - .WithNameColon(NameColon(IdentifierName("nonPublic"))))); - - if (info.IsManagedReturnPosition) - { - yield return AssignmentStatement(IdentifierName(managedIdentifier), safeHandleCreationExpression); - } - else if (info.IsByRef && info.RefKind != RefKind.In) - { - // We create the new handle in the Setup phase - // so we eliminate the possible failure points during unmarshalling, where we would - // leak the handle if we failed to create the handle. - yield return Declare(info.ManagedType.Syntax, newHandleObjectIdentifier, safeHandleCreationExpression); - - if (info.RefKind != RefKind.Out) - { - // IntPtr = newHandleObjectIdentifier.DangerousGetHandle(); - yield return Declare( - AsNativeType(info).Syntax, - handleValueBackupIdentifier, - MethodInvocation( - IdentifierName(newHandleObjectIdentifier), - IdentifierName(nameof(SafeHandle.DangerousGetHandle)))); - } - } - break; - case StubCodeContext.Stage.Marshal: - if (!info.IsManagedReturnPosition && info.RefKind != RefKind.Out) - { - // .DangerousAddRef(ref ); - yield return MethodInvocationStatement( - IdentifierName(managedIdentifier), - IdentifierName(nameof(SafeHandle.DangerousAddRef)), - RefArgument(IdentifierName(addRefdIdentifier))); - - - // = .DangerousGetHandle() - ExpressionSyntax assignHandleToNativeExpression = - AssignmentExpression(SyntaxKind.SimpleAssignmentExpression, - IdentifierName(nativeIdentifier), - MethodInvocation( - IdentifierName(managedIdentifier), - IdentifierName(nameof(SafeHandle.DangerousGetHandle)))); - if (info.IsByRef && info.RefKind != RefKind.In) - { - yield return AssignmentStatement(IdentifierName(handleValueBackupIdentifier), assignHandleToNativeExpression); - } - else - { - yield return ExpressionStatement(assignHandleToNativeExpression); - } - } - break; - case StubCodeContext.Stage.GuaranteedUnmarshal: - StatementSyntax unmarshalStatement = MethodInvocationStatement( - TypeSyntaxes.System_Runtime_InteropServices_Marshal, - IdentifierName("InitHandle"), - Argument(IdentifierName(newHandleObjectIdentifier)), - Argument(IdentifierName(nativeIdentifier))); - - if (info.IsManagedReturnPosition) - { - yield return unmarshalStatement; - } - else if (info.RefKind == RefKind.Out) - { - yield return unmarshalStatement; - yield return AssignmentStatement(IdentifierName(managedIdentifier), IdentifierName(newHandleObjectIdentifier)); - } - else if (info.RefKind == RefKind.Ref) - { - // Decrement refcount on original SafeHandle if we addrefd - yield return IfStatement( - IdentifierName(addRefdIdentifier), - MethodInvocationStatement( - IdentifierName(managedIdentifier), - IdentifierName(nameof(SafeHandle.DangerousRelease)))); - - // Do not unmarshal the handle if the value didn't change. - yield return IfStatement( - BinaryExpression(SyntaxKind.NotEqualsExpression, - IdentifierName(handleValueBackupIdentifier), - IdentifierName(nativeIdentifier)), - Block( - unmarshalStatement, - AssignmentStatement( - IdentifierName(managedIdentifier), - IdentifierName(newHandleObjectIdentifier)))); - } - break; - case StubCodeContext.Stage.CleanupCallerAllocated: - if (!info.IsManagedReturnPosition && (!info.IsByRef || info.RefKind == RefKind.In)) - { - yield return IfStatement( - IdentifierName(addRefdIdentifier), - MethodInvocationStatement( - IdentifierName(managedIdentifier), - IdentifierName(nameof(SafeHandle.DangerousRelease)))); - } - break; - default: - break; - } - } - - public bool UsesNativeIdentifier(TypePositionInfo info, StubCodeContext context) => true; - - public ByValueMarshalKindSupport SupportsByValueMarshalKind(ByValueContentsMarshalKind marshalKind, TypePositionInfo info, StubCodeContext context, out GeneratorDiagnostic? diagnostic) - => ByValueMarshalKindSupportDescriptor.Default.GetSupport(marshalKind, info, context, out diagnostic); - } -} diff --git a/src/libraries/System.Runtime.InteropServices/gen/Microsoft.Interop.SourceGeneration/Marshalling/StaticPinnableManagedValueMarshaller.cs b/src/libraries/System.Runtime.InteropServices/gen/Microsoft.Interop.SourceGeneration/Marshalling/StaticPinnableManagedValueMarshaller.cs index 039d78ed35006..07bb36a2edaba 100644 --- a/src/libraries/System.Runtime.InteropServices/gen/Microsoft.Interop.SourceGeneration/Marshalling/StaticPinnableManagedValueMarshaller.cs +++ b/src/libraries/System.Runtime.InteropServices/gen/Microsoft.Interop.SourceGeneration/Marshalling/StaticPinnableManagedValueMarshaller.cs @@ -21,9 +21,6 @@ public StaticPinnableManagedValueMarshaller(IMarshallingGenerator innerMarshalli _getPinnableReferenceType = getPinnableReferenceType; } - public bool IsSupported(TargetFramework target, Version version) - => _innerMarshallingGenerator.IsSupported(target, version); - public ValueBoundaryBehavior GetValueBoundaryBehavior(TypePositionInfo info, StubCodeContext context) { if (IsPinningPathSupported(info, context)) diff --git a/src/libraries/System.Runtime.InteropServices/gen/Microsoft.Interop.SourceGeneration/Marshalling/UnmanagedToManagedOwnershipTrackingStrategy.cs b/src/libraries/System.Runtime.InteropServices/gen/Microsoft.Interop.SourceGeneration/Marshalling/UnmanagedToManagedOwnershipTrackingStrategy.cs index ba43659536d52..3b41fa0efbfa6 100644 --- a/src/libraries/System.Runtime.InteropServices/gen/Microsoft.Interop.SourceGeneration/Marshalling/UnmanagedToManagedOwnershipTrackingStrategy.cs +++ b/src/libraries/System.Runtime.InteropServices/gen/Microsoft.Interop.SourceGeneration/Marshalling/UnmanagedToManagedOwnershipTrackingStrategy.cs @@ -178,7 +178,6 @@ IEnumerable GenerateStatementsFromInner(StubCodeContext context public SignatureBehavior GetNativeSignatureBehavior(TypePositionInfo info) => _inner.GetNativeSignatureBehavior(info); public ValueBoundaryBehavior GetValueBoundaryBehavior(TypePositionInfo info, StubCodeContext context) => _inner.GetValueBoundaryBehavior(info, context); - public bool IsSupported(TargetFramework target, Version version) => _inner.IsSupported(target, version); public ByValueMarshalKindSupport SupportsByValueMarshalKind(ByValueContentsMarshalKind marshalKind, TypePositionInfo info, StubCodeContext context, out GeneratorDiagnostic? diagnostic) => _inner.SupportsByValueMarshalKind(marshalKind, info, context, out diagnostic); public bool UsesNativeIdentifier(TypePositionInfo info, StubCodeContext context) => _inner.UsesNativeIdentifier(info, context); diff --git a/src/libraries/System.Runtime.InteropServices/gen/Microsoft.Interop.SourceGeneration/SafeHandleMarshallingInfoProvider.cs b/src/libraries/System.Runtime.InteropServices/gen/Microsoft.Interop.SourceGeneration/SafeHandleMarshallingInfoProvider.cs index a5c2f2a1f93f9..dd30b31b14ff0 100644 --- a/src/libraries/System.Runtime.InteropServices/gen/Microsoft.Interop.SourceGeneration/SafeHandleMarshallingInfoProvider.cs +++ b/src/libraries/System.Runtime.InteropServices/gen/Microsoft.Interop.SourceGeneration/SafeHandleMarshallingInfoProvider.cs @@ -10,11 +10,6 @@ namespace Microsoft.Interop { - /// - /// The type of the element is a SafeHandle-derived type with no marshalling attributes. - /// - public sealed record SafeHandleMarshallingInfo(bool AccessibleDefaultConstructor, bool IsAbstract) : MarshallingInfo; - /// /// This class supports generating marshalling info for SafeHandle-derived types. /// @@ -52,7 +47,6 @@ public bool CanProvideMarshallingInfoForType(ITypeSymbol type) public MarshallingInfo GetMarshallingInfo(ITypeSymbol type, int indirectionDepth, UseSiteAttributeProvider useSiteAttributes, GetMarshallingInfoCallback marshallingInfoCallback) { bool hasDefaultConstructor = false; - bool hasAccessibleDefaultConstructor = false; if (type is INamedTypeSymbol named && !named.IsAbstract && named.InstanceConstructors.Length > 0) { foreach (IMethodSymbol ctor in named.InstanceConstructors) @@ -60,18 +54,16 @@ public MarshallingInfo GetMarshallingInfo(ITypeSymbol type, int indirectionDepth if (ctor.Parameters.Length == 0) { hasDefaultConstructor = ctor.DeclaredAccessibility == Accessibility.Public; - hasAccessibleDefaultConstructor = _compilation.IsSymbolAccessibleWithin(ctor, _containingScope); break; } } } - // If we don't have the SafeHandleMarshaller type, then we'll use the built-in support in the generator. - // This support will be removed when dotnet/runtime doesn't build any packages for platforms below .NET 8 - // as the downlevel support is dotnet/runtime specific. + // If we don't have the SafeHandleMarshaller type, then we'll return a MissingSupportMarshallingInfo + // indicating that we don't support marshalling SafeHandles with source-generated marshalling. if (_safeHandleMarshallerType is null) { - return new SafeHandleMarshallingInfo(hasAccessibleDefaultConstructor, type.IsAbstract); + return new MissingSupportMarshallingInfo(); } INamedTypeSymbol entryPointType = _safeHandleMarshallerType.Construct(type);