Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@ namespace System.Diagnostics.CodeAnalysis
/// </remarks>
[AttributeUsage(AttributeTargets.Method | AttributeTargets.Constructor | AttributeTargets.Property, Inherited = false)]
[Conditional("DEBUG")]
internal sealed class RequiresUnsafeAttribute : Attribute
public sealed class RequiresUnsafeAttribute : Attribute
{
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -267,6 +267,15 @@ private static IncrementalStubGenerationContext CalculateStubInformation(

var methodSyntaxTemplate = new ContainingSyntax(originalSyntax.Modifiers, SyntaxKind.MethodDeclaration, originalSyntax.Identifier, originalSyntax.TypeParameterList);

// If [RequiresUnsafe] is available, set the flag so it can be added to the stub later.
// Don't add if the user's declaration already has it (to avoid duplicate attribute error).
var environmentFlags = environment.EnvironmentFlags;
if (environment.RequiresUnsafeAttrType is not null
&& !symbol.GetAttributes().Any(a => SymbolEqualityComparer.Default.Equals(a.AttributeClass, environment.RequiresUnsafeAttrType)))
{
environmentFlags |= EnvironmentFlags.RequiresUnsafeAvailable;
}

List<AttributeSyntax> additionalAttributes = GenerateSyntaxForForwardedAttributes(suppressGCTransitionAttribute, unmanagedCallConvAttribute, defaultDllImportSearchPathsAttribute, wasmImportLinkageAttribute, stackTraceHiddenAttribute);
return new IncrementalStubGenerationContext(
signatureContext,
Expand All @@ -276,7 +285,7 @@ private static IncrementalStubGenerationContext CalculateStubInformation(
new SequenceEqualImmutableArray<AttributeSyntax>(additionalAttributes.ToImmutableArray(), SyntaxEquivalentComparer.Instance),
LibraryImportData.From(libraryImportData),
options,
environment.EnvironmentFlags);
environmentFlags);
}

private static MemberDeclarationSyntax GenerateSource(
Expand Down Expand Up @@ -330,7 +339,17 @@ private static MemberDeclarationSyntax GenerateSource(
dllImport = dllImport.WithLeadingTrivia(Comment("// Local P/Invoke"));
code = code.AddStatements(dllImport);

return pinvokeStub.ContainingSyntaxContext.WrapMemberInContainingSyntaxWithUnsafeModifier(PrintGeneratedSource(pinvokeStub.StubMethodSyntaxTemplate, pinvokeStub.SignatureContext, code));
var signatureContext = pinvokeStub.SignatureContext;
if (pinvokeStub.EnvironmentFlags.HasFlag(EnvironmentFlags.RequiresUnsafeAvailable))
{
signatureContext = signatureContext with
{
AdditionalAttributes = signatureContext.AdditionalAttributes.Add(
AttributeList(SingletonSeparatedList(Attribute(NameSyntaxes.System_Diagnostics_CodeAnalysis_RequiresUnsafeAttribute))))
};
}

return pinvokeStub.ContainingSyntaxContext.WrapMemberInContainingSyntaxWithUnsafeModifier(PrintGeneratedSource(pinvokeStub.StubMethodSyntaxTemplate, signatureContext, code));
}

private static MemberDeclarationSyntax PrintForwarderStub(ContainingSyntax userDeclaredMethod, IncrementalStubGenerationContext stub)
Expand Down Expand Up @@ -361,6 +380,12 @@ private static MemberDeclarationSyntax PrintForwarderStub(ContainingSyntax userD
SingletonSeparatedList(
CreateForwarderDllImport(pinvokeData))));

if (stub.EnvironmentFlags.HasFlag(EnvironmentFlags.RequiresUnsafeAvailable))
{
stubMethod = stubMethod.AddAttributeLists(
AttributeList(SingletonSeparatedList(Attribute(NameSyntaxes.System_Diagnostics_CodeAnalysis_RequiresUnsafeAttribute))));
}

MemberDeclarationSyntax toPrint = stub.ContainingSyntaxContext.WrapMemberInContainingSyntaxWithUnsafeModifier(stubMethod);

return toPrint;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ public enum EnvironmentFlags
None = 0,
SkipLocalsInit = 0x1,
DisableRuntimeMarshalling = 0x2,
RequiresUnsafeAvailable = 0x4,
}

public sealed record StubEnvironment(
Expand Down Expand Up @@ -101,5 +102,19 @@ public INamedTypeSymbol? StackTraceHiddenAttrType
return _stackTraceHiddenAttrType.Value;
}
}

private Optional<INamedTypeSymbol?> _requiresUnsafeAttrType;
public INamedTypeSymbol? RequiresUnsafeAttrType
{
get
{
if (_requiresUnsafeAttrType.HasValue)
{
return _requiresUnsafeAttrType.Value;
}
_requiresUnsafeAttrType = new Optional<INamedTypeSymbol?>(Compilation.GetTypeByMetadataName(TypeNames.System_Diagnostics_CodeAnalysis_RequiresUnsafeAttribute));
return _requiresUnsafeAttrType.Value;
}
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -44,6 +44,9 @@ public static class NameSyntaxes
public static NameSyntax System_Runtime_InteropServices_StructLayoutAttribute => _System_Runtime_InteropServices_StructLayoutAttribute ??= ParseName(TypeNames.GlobalAlias + TypeNames.System_Runtime_InteropServices_StructLayoutAttribute);
private static NameSyntax? _System_Diagnostics_StackTraceHiddenAttribute;
public static NameSyntax System_Diagnostics_StackTraceHiddenAttribute => _System_Diagnostics_StackTraceHiddenAttribute ??= ParseName(TypeNames.GlobalAlias + TypeNames.System_Diagnostics_StackTraceHiddenAttribute);

private static NameSyntax? _System_Diagnostics_CodeAnalysis_RequiresUnsafeAttribute;
public static NameSyntax System_Diagnostics_CodeAnalysis_RequiresUnsafeAttribute => _System_Diagnostics_CodeAnalysis_RequiresUnsafeAttribute ??= ParseName(TypeNames.GlobalAlias + TypeNames.System_Diagnostics_CodeAnalysis_RequiresUnsafeAttribute);
}

public static class TypeSyntaxes
Expand Down Expand Up @@ -202,6 +205,8 @@ public static class TypeNames

public const string System_Diagnostics_StackTraceHiddenAttribute = "System.Diagnostics.StackTraceHiddenAttribute";

public const string System_Diagnostics_CodeAnalysis_RequiresUnsafeAttribute = "System.Diagnostics.CodeAnalysis.RequiresUnsafeAttribute";

public static string MarshalEx(InteropGenerationOptions options)
{
return options.UseMarshalType ? System_Runtime_InteropServices_Marshal : System_Runtime_InteropServices_MarshalEx;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -115,6 +115,54 @@ partial class C
await VerifySourceGeneratorAsync(source, "C", "Method", typeof(System.CodeDom.Compiler.GeneratedCodeAttribute).FullName, attributeAdded: false);
}

[Fact]
public async Task RequiresUnsafeAdded()
{
string source = """
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Runtime.InteropServices.Marshalling;
[assembly:DisableRuntimeMarshalling]
partial class C
{
[LibraryImportAttribute("DoesNotExist")]
public static partial S Method();
}

[NativeMarshalling(typeof(Marshaller))]
struct S
{
}

struct Native
{
}

[CustomMarshaller(typeof(S), MarshalMode.Default, typeof(Marshaller))]
static class Marshaller
{
public static Native ConvertToUnmanaged(S s) => default;

public static S ConvertToManaged(Native n) => default;
}
""";
await VerifySourceGeneratorAsync(source, "C", "Method", "System.Diagnostics.CodeAnalysis.RequiresUnsafeAttribute", attributeAdded: true);
}

[Fact]
public async Task RequiresUnsafeAddedOnForwardingStub()
{
string source = """
using System.Runtime.InteropServices;
partial class C
{
[LibraryImportAttribute("DoesNotExist")]
public static partial void Method();
}
""";
await VerifySourceGeneratorAsync(source, "C", "Method", "System.Diagnostics.CodeAnalysis.RequiresUnsafeAttribute", attributeAdded: true);
}

public static IEnumerable<object[]> GetDownlevelTargetFrameworks()
{
yield return new object[] { TestTargetFramework.Standard2_0, false };
Expand Down
6 changes: 6 additions & 0 deletions src/libraries/System.Runtime/ref/System.Runtime.cs
Original file line number Diff line number Diff line change
Expand Up @@ -9110,6 +9110,12 @@ public RequiresUnreferencedCodeAttribute(string message) { }
public string Message { get { throw null; } }
public string? Url { get { throw null; } set { } }
}
[System.AttributeUsageAttribute(System.AttributeTargets.Constructor | System.AttributeTargets.Method | System.AttributeTargets.Property, Inherited=false)]
[System.Diagnostics.ConditionalAttribute("DEBUG")]
public sealed partial class RequiresUnsafeAttribute : System.Attribute
{
public RequiresUnsafeAttribute() { }
}
[System.AttributeUsageAttribute(System.AttributeTargets.Constructor, AllowMultiple=false, Inherited=false)]
public sealed partial class SetsRequiredMembersAttribute : System.Attribute
{
Expand Down
Loading