Skip to content

Generate HKL IsNull helper #610

Closed as not planned
Closed as not planned

Description

As per dotnet/winforms#7451 (comment) HKL is missing the IsNull helper talked about in #206

Activity

  1. added
    bug
    on Jul 21, 2022
  2. changed the title [-]Generated HKL IsNull helper[/-] [+]Generate HKL IsNull helper[/+] on Jul 21, 2022
  3. elachlan commented on Jul 21, 2022

    @elachlan
    ContributorAuthor

    Is this where we make the change?

    private bool IsHandle(TypeDefinitionHandle typeDefHandle, out string? releaseMethodName)
    {
    if (this.MetadataIndex.HandleTypeReleaseMethod.TryGetValue(typeDefHandle, out releaseMethodName))
    {
    return true;
    }
    // Special case handles that do not carry RAIIFree attributes.
    releaseMethodName = null;
    TypeDefinition typeDef = this.Reader.GetTypeDefinition(typeDefHandle);
    return this.Reader.StringComparer.Equals(typeDef.Name, "HGDIOBJ")
    || this.Reader.StringComparer.Equals(typeDef.Name, "HWND");
    }

  4. elachlan commented on Jul 21, 2022

    @elachlan
    ContributorAuthor

    Foundation.HWND doesn't seem to have an IsNull property, Graphics.Gdi.HGDIOBJ does.

    Error CS1061 'HWND' does not contain a definition for 'IsNull' and no accessible extension method 'IsNull' accepting a first argument of type 'HWND' could be found (are you missing a using directive or an assembly reference?

  5. elachlan commented on Jul 21, 2022

    @elachlan
    ContributorAuthor

    Andrew Arnott (@AArnott) I think the issue is because Foundation.HWND uses nint and Graphics.Gdi.HGDIOBJ uses IntPtr.

    This code only checks IntPtr and UIntPtr.

    // If this typedef struct represents a pointer, add an IsNull property.
    if (fieldType is IdentifierNameSyntax { Identifier: { Value: nameof(IntPtr) or nameof(UIntPtr) } })
    {
    // internal static bool IsNull => value == default;
    yield return PropertyDeclaration(PredefinedType(TokenWithSpace(SyntaxKind.BoolKeyword)), "IsNull")
    .AddModifiers(TokenWithSpace(this.Visibility))
    .WithExpressionBody(ArrowExpressionClause(BinaryExpression(SyntaxKind.EqualsExpression, fieldName, LiteralExpression(SyntaxKind.DefaultLiteralExpression))))
    .WithSemicolonToken(SemicolonWithLineFeed);
    }

    I think this:

    if (fieldType is IdentifierNameSyntax { Identifier: { Value: nameof(IntPtr) or nameof(UIntPtr) } })

    needs to change to:

    if (fieldType is IdentifierNameSyntax { Identifier: { Value: nameof(IntPtr) or nameof(UIntPtr) or nameof(nint) or nameof(nuint) } })

    I'll create a PR if you are happy with that.

  6. AArnott commented on Jul 21, 2022

    @AArnott
    Member

    That's where I suspected the bug to be too. We have had a little churn in whether we generate IntPtr or nint lately. I think though, rather than update the condition check to allow for nint, I'd rather fix the generator to produce IntPtr as it is intended to. I realize in C# 11 it's equivalent, but that's not out yet, and IntPtr does a better job of conveying "this is a pointer-sized opaque value" than nint does.

  7. elachlan commented on Jul 21, 2022

    @elachlan
    ContributorAuthor

    I played around with it and I think its caused by PreferNativeInt on the generalTypeSettings in Generator:

    this.generalTypeSettings = new TypeSyntaxSettings(
    this,
    PreferNativeInt: this.LanguageVersion >= LanguageVersion.CSharp9,
    PreferMarshaledTypes: false,
    AllowMarshaling: options.AllowMarshaling,
    QualifyNames: false);
    this.fieldTypeSettings = this.generalTypeSettings with { QualifyNames = true, IsField = true };
    this.delegateSignatureTypeSettings = this.generalTypeSettings with { QualifyNames = true };

    This causes the output to change:

    internal static TypeSyntax ToTypeSyntax(PrimitiveTypeCode typeCode, bool preferNativeInt)
    {
    return typeCode switch
    {
    PrimitiveTypeCode.Char => PredefinedType(Token(SyntaxKind.CharKeyword)),
    PrimitiveTypeCode.Boolean => PredefinedType(Token(SyntaxKind.BoolKeyword)),
    PrimitiveTypeCode.SByte => PredefinedType(Token(SyntaxKind.SByteKeyword)),
    PrimitiveTypeCode.Byte => PredefinedType(Token(SyntaxKind.ByteKeyword)),
    PrimitiveTypeCode.Int16 => PredefinedType(Token(SyntaxKind.ShortKeyword)),
    PrimitiveTypeCode.UInt16 => PredefinedType(Token(SyntaxKind.UShortKeyword)),
    PrimitiveTypeCode.Int32 => PredefinedType(Token(SyntaxKind.IntKeyword)),
    PrimitiveTypeCode.UInt32 => PredefinedType(Token(SyntaxKind.UIntKeyword)),
    PrimitiveTypeCode.Int64 => PredefinedType(Token(SyntaxKind.LongKeyword)),
    PrimitiveTypeCode.UInt64 => PredefinedType(Token(SyntaxKind.ULongKeyword)),
    PrimitiveTypeCode.Single => PredefinedType(Token(SyntaxKind.FloatKeyword)),
    PrimitiveTypeCode.Double => PredefinedType(Token(SyntaxKind.DoubleKeyword)),
    PrimitiveTypeCode.Object => PredefinedType(Token(SyntaxKind.ObjectKeyword)),
    PrimitiveTypeCode.String => PredefinedType(Token(SyntaxKind.StringKeyword)),
    PrimitiveTypeCode.IntPtr => preferNativeInt ? IdentifierName("nint") : IdentifierName(nameof(IntPtr)),
    PrimitiveTypeCode.UIntPtr => preferNativeInt ? IdentifierName("nuint") : IdentifierName(nameof(UIntPtr)),
    PrimitiveTypeCode.Void => PredefinedType(Token(SyntaxKind.VoidKeyword)),
    _ => throw new NotSupportedException("Unsupported type code: " + typeCode),
    };
    }

    So I guess we hardcode it for now and update it once LanguageVersion.CSharp11 is included in Microsoft.CodeAnalysis.CSharp?

  8. AArnott commented on Jul 21, 2022

    @AArnott
    Member

    Thanks for looking.

    We want the general type settings to prefer nint over IntPtr though. It's only in the handle structs that we want to prefer IntPtr. We have code to do this, but it's failing... somewhere.

    I wouldn't bother changing it again for C# 11, since if they are equivalent, there's no value in switching from one to the other.

  9. jnm2 commented on Jul 21, 2022

    @jnm2
    Contributor

    And in C# 11 I still feel like showing the type as IntPtr versus nint carries useful expectations on the meaning of the contents.

  10. AArnott commented on Jul 21, 2022

    @AArnott
    Member

    While I agree with you, Joseph Musser (@jnm2), I suspect time will judge differently. When everyone is using C# 11+ and the two are truly aliases of each other, I suspect people will consider them as equivalent as int and Int32. These days we do still split hairs (at least I do) in preferring int but using Int32 when I want to be explicit about its length -- not because I have to, but it can be useful when implementing network protocols. Time will tell how people feel about IntPtr vs. nint at that point. But it certainly can do no harm to continue to use IntPtr here, and it certainly is useful to do so in the hear and now.

  11. elachlan commented on Jul 22, 2022

    @elachlan
    ContributorAuthor

    This is the code where it decides if a Handle struct is a handle:

    private bool IsHandle(TypeDefinitionHandle typeDefHandle, out string? releaseMethodName)
    {
    if (this.MetadataIndex.HandleTypeReleaseMethod.TryGetValue(typeDefHandle, out releaseMethodName))
    {
    return true;
    }
    // Special case handles that do not carry RAIIFree attributes.
    releaseMethodName = null;
    TypeDefinition typeDef = this.Reader.GetTypeDefinition(typeDefHandle);
    return this.Reader.StringComparer.Equals(typeDef.Name, "HGDIOBJ")
    || this.Reader.StringComparer.Equals(typeDef.Name, "HWND");
    }

    I think because there is no method for releasing the HKL, there is no hit in MetadataIndex.HandleTypeReleaseMethod. So then its up to the special cases section.

    A lot of these types are DECLARE_HANDLE and have the InvalidHandleValues value. Could we use that?
    https://github.com/microsoft/win32metadata/blob/5687b3cb4868c3142b98091ee970464f55219406/generation/WinSDK/autoTypes.json#L114-L118

    Would IsNull still make sense in that context?

  12. elachlan commented on Jul 22, 2022

    @elachlan
    ContributorAuthor

    I think this works, but might need a type check for intptr?

    private bool IsHandle(TypeDefinitionHandle typeDefHandle, out string? releaseMethodName)
    {
        if (this.MetadataIndex.HandleTypeReleaseMethod.TryGetValue(typeDefHandle, out releaseMethodName))
        {
            return true;
        }
        else if (this.GetInvalidHandleValues(typeDefHandle).Count > 0) {
            return true;
        }
    
        // Special case handles that do not carry RAIIFree attributes.
        releaseMethodName = null;
        TypeDefinition typeDef = this.Reader.GetTypeDefinition(typeDefHandle);
        return this.Reader.StringComparer.Equals(typeDef.Name, "HGDIOBJ")
            || this.Reader.StringComparer.Equals(typeDef.Name, "HWND");
    }

    But CreateCommonTypeDefMembers would need to change to again check for invalid values and then generate code which checked for the invalid values instead of default?

    // If this typedef struct represents a pointer, add an IsNull property.
    if (fieldType is IdentifierNameSyntax { Identifier: { Value: nameof(IntPtr) or nameof(UIntPtr) } })
    {
    // internal static bool IsNull => value == default;
    yield return PropertyDeclaration(PredefinedType(TokenWithSpace(SyntaxKind.BoolKeyword)), "IsNull")
    .AddModifiers(TokenWithSpace(this.Visibility))
    .WithExpressionBody(ArrowExpressionClause(BinaryExpression(SyntaxKind.EqualsExpression, fieldName, LiteralExpression(SyntaxKind.DefaultLiteralExpression))))
    .WithSemicolonToken(SemicolonWithLineFeed);
    }

  13. elachlan commented on Jul 22, 2022

    @elachlan
    ContributorAuthor

    The typedef structs are (mostly) strongly-typed wrappers for handles.
    microsoft/win32metadata#21 (comment)

    Can you clarify mostly?

    My above attempts I believe were wrong. I think DeclareTypeDefStruct needs to always have isHandle=true, as its only called when the metadata has the NativeTypedef attribute. Additionally, the section in CreateCommonTypeDefMembers which adds IsNull checks for IntPtr and UIntPtr, so that covers the "mostly" part as far as I can tell.

    If there is a counter example we can add it to the tests and see if we need additional information from the metadata.

  14. elachlan commented on Jul 25, 2022

    @elachlan
    ContributorAuthor

    Andrew Arnott (@AArnott) should the win32metadata repo just explicitly tag each typedef struct which is a handle? Are all the structs with intptr values handles?

  15. 1 remaining item

  16. elachlan commented on Jul 25, 2022

    @elachlan
    ContributorAuthor

    Good question. I don't know. Maybe CsWin32's need for a 'handle' designation is flawed, if the information simply isn't in the header files either.

    Can you think of an example of a NativeTypedef struct with an IntPtr which isn't a handle?

  17. AArnott commented on Jul 25, 2022

    @AArnott
    Member

    No. So far I've coded CsWin32 to consider that all typedef structs with intptr are the same.

  18. elachlan commented on Jul 26, 2022

    @elachlan
    ContributorAuthor

    I think we can refactor the code where ishandle is called. If you ignore the result, the all nativetypedef structs with intptr are generated with IsNull.

  19. elachlan commented on Aug 16, 2022

    @elachlan
    ContributorAuthor

    Steve Otteson (@sotteson1) We are looking at how to distinguish between a NativeTypedef which is a handle and one that just has an IntPtr. It seems like not all NativeTypedefs with IntPtr are handles since some are defined in autotypes with "ValueType": "DECLARE_HANDLE" and so a new attribute might be required. Am I way off the mark with this?

  20. elachlan commented on Aug 17, 2022

    @elachlan
    ContributorAuthor

    Jeremy Kuhne (@JeremyKuhne) can I get your thoughts?

  21. elachlan commented on Aug 19, 2022

    @elachlan
    ContributorAuthor

    Found this comment in Winforms, which might help sway us towards wanting to use nint/nuint over IntPtr/UIntPtr.

    // It is particularly dangerous to cast to/from IntPtr on 64 bit platforms as casts are checked.
    // Doing so leads to hard-to-find overflow exceptions. We've mitigated this historically by trying
    // to first cast to long when casting out of IntPtr and first casting to int when casting into an
    // IntPtr. That pattern, unfortunately, is difficult to audit and has negative performance implications,
    // particularly on 32bit.
    //
    // Using the new nint/nuint types allows casting to follow with the default project settings, which
    // is unchecked. Casting works just like casting between other intrinsic types (short, int, long, etc.).
    

    https://github.com/dotnet/winforms/blob/179df82381b5df175d043c2190306354f8b46cae/src/System.Windows.Forms.Primitives/src/System/Windows/Forms/Message.cs#L39-L50

  22. AArnott commented on Aug 19, 2022

    @AArnott
    Member

    Lachlan Ennis (@elachlan), that comment is interesting and I'd like to learn more. But why post it here on an issue about adding IsNull, which may be closed as Won't Fix, but this casting concern should likely have its own discussion lifetime?

  23. elachlan commented on Aug 19, 2022

    @elachlan
    ContributorAuthor

    Lachlan Ennis (@elachlan), that comment is interesting and I'd like to learn more. But why post it here on an issue about adding IsNull, which may be closed as Won't Fix, but this casting concern should likely have its own discussion lifetime?

    Basically this issue is caused by the setting for preferring nint over IntPtr.

  24. elachlan commented on Aug 19, 2022

    @elachlan
    ContributorAuthor

    Adding this here based on Andrew's question in the PR:

    Given how hard it is to get this right, I wonder if it's worth it. Particularly because all this change would do is enable an .IsNull syntax where == default would already do the same. Why is this so important?

    I think its less about .IsNull and more about CsWin32 and other Win32Metadata consumers not knowing how to tell if something is a handle or not. An attribute in the metadata would remove that ambiguity. Really .IsNull is just a symptom of the problem and if the ambiguity isn't rectified in the metadata, I imagine there will be other "symptoms".

  25. AArnott commented on Aug 19, 2022

    @AArnott
    Member

    if the ambiguity isn't rectified in the metadata, I imagine there will be other "symptoms".

    I would be content to leave the metadata alone so they can focus on more meaningful changes, until one of these other symptoms shows up with a compelling case for fixing. I don't think IsNull is compelling enough.

    Lachlan Ennis (@elachlan), if your concern about IntPtr checked casting remains (I suspect it does), can you please file a new issue to track that? Consider that I would like handle typedef's to use IntPtr instead of nint as their field type. At one point this worked, but I don't know whether that still works. So even if we have nint now, we may have IntPtr later unless a discussion (on a new issue) compels me to give it up and use nint to avoid checked cast exceptions.

  26. added
    wontfix
    and removed
    bug
    on Aug 19, 2022
  27. elachlan commented on Aug 19, 2022

    @elachlan
    ContributorAuthor

    New issue is at #661

  28. elachlan commented on Aug 19, 2022

    @elachlan
    ContributorAuthor

    I mean, the majority of the typedefstructs work. So the PR isn't a complete failure. Its just if you want complete coverage of all handles then we would need more info from the metadata.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    partnerwontfix

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions