Skip to content

Refactor CreateHardLink PInvoke - #18707

Closed
xtqqczze wants to merge 1 commit into
PowerShell:masterfrom
xtqqczze:patch-2
Closed

xtqqczze wants to merge 1 commit into
PowerShell:masterfrom
xtqqczze:patch-2

Conversation

@xtqqczze

@xtqqczze xtqqczze commented Dec 1, 2022 •

Copy link
Copy Markdown
Contributor

WIP

@daxian-dbw

Dongbo Wang (daxian-dbw) commented Dec 2, 2022 •

Copy link
Copy Markdown
Member

xtqqczze Isn't nint mapping to IntPtr, just like int maps to Int32?

@xtqqczze

xtqqczze commented Dec 2, 2022

Copy link
Copy Markdown
Contributor Author

It is true that in .NET 7, nint is an alias for System.IntPtr, however by convention PInvoke signatures use IntPtr to represent opaque pointers.

@xtqqczze

xtqqczze commented Dec 2, 2022

Copy link
Copy Markdown
Contributor Author

error SYSLIB1051: The type 'IntPtr' is not supported by source-generated P/Invokes. The generated source will not handle marshalling of parameter 'lpSecurityAttributes'. [D:\a\1\s\src\System.Management.Automation\System.Management.Automation.csproj]

@daxian-dbw

Copy link
Copy Markdown
Member

xtqqczze The CI of the PR that introduced this file passed: #18603. Does that mean we indeed should use nint instead of IntPtr?

@xtqqczze

xtqqczze commented Dec 2, 2022

Copy link
Copy Markdown
Contributor Author

xtqqczze The CI of the PR that introduced this file passed: #18603. Does that mean we indeed should use nint instead of IntPtr?

Dongbo Wang (@daxian-dbw) I guess that's why Ilya (@iSazonov) replaced IntPtr with nint in that PR.

I think the best option here is to use void* and wrap the PInvoke as in 6e52da5. The correct type is LPSECURITY_ATTRIBUTES*, but documentation specifies that lpSecurityAttributes is reserved and must be null.

@xtqqczze xtqqczze changed the title Fix definition for CreateHardLink pinvoke Refactor CreateHardLink PInvoke Dec 2, 2022
@iSazonov

Ilya (iSazonov) commented Dec 2, 2022 •

Copy link
Copy Markdown
Collaborator

The old style (using IntPtr and void*) forces using unsafe context.
Now .Net team introduced nint to use pointer arithmetic and to avoid unsafe.
We will have analyzer/fixer for recommended patterns dotnet/runtime#74518
For better understanding see also:
dotnet/csharplang#6065
https://github.com/dotnet/csharplang/blob/main/proposals/csharp-11.0/numeric-intptr.md

GitHub
The official repo for the design of the C# programming language - csharplang/numeric-intptr.md at main · dotnet/csharplang

@jborean93 Jordan Borean (jborean93) Dec 2, 2022 •

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Is there any benefit to using a custom BOOL enum here? Dotnet can handle all that for you as it was before. Why use void* when IntPtr or nint would suffice (as mentioned above) and remove the need for the unsafe context.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I've removed the enum and explained (#18707 (comment)) why we shouldn't avoid unsafe context.

@SeeminglyScience

Copy link
Copy Markdown
Contributor

The old style (using IntPtr and void*) forces using unsafe context. Now .Net team introduced nint to use pointer arithmetic and to avoid unsafe. We will have analyzer/fixer for recommended patterns dotnet/runtime#74518 For better understanding see also: dotnet/csharplang#6065 dotnet/csharplang@main/proposals/csharp-11.0/numeric-intptr.md

nint was introduced to allow using native sized integers as you would other numbers. Primarily for when it does not represent an actual pointer. Despite the name, there's nothing inherently more unsafe about unsafe contexts compared to using IntPtr.

Now while I did want to clarify that point... if we're never going to actually use the parameter then I agree that nint works just fine.

@daxian-dbw

Copy link
Copy Markdown
Member

I'm really confused 😅 Can someone please explain the following questions to me?

  1. Is nint interchangeable with IntPtr when used as a parameter type like in this case?
  2. Why this PR is needed? (why is using nint here is not appropriate?)

@iSazonov

Ilya (iSazonov) commented Dec 2, 2022 •

Copy link
Copy Markdown
Collaborator

I'm really confused 😅 Can someone please explain the following questions to me?

  1. Is nint interchangeable with IntPtr when used as a parameter type like in this case?

Yes. From design docs referenced above

In short, we now treat nint/nuint as simple types aliasing System.IntPtr/System.UIntPtr, like we do for int in relation to System.Int32.

  1. Why this PR is needed? (why is using nint here is not appropriate?)

We have no need the PR. The intention of the .Net team is to explicitly use nint where pointer arithmetic is used and most likely in other cases (although there are doubts about readability)
Also from CreateHardLink docs:

lpSecurityAttributes
Reserved; must be NULL.

@daxian-dbw

Copy link
Copy Markdown
Member

Thanks Ilya (@iSazonov). In this case then, xtqqczze shall we close this PR?

@xtqqczze
xtqqczze marked this pull request as draft December 2, 2022 20:16
@xtqqczze

xtqqczze commented Dec 2, 2022

Copy link
Copy Markdown
Contributor Author

The old style (using IntPtr and void*) forces using unsafe context. Now .Net team introduced nint to use _pointer

There is no reason to avoid unsafe contexts in Pinvokes. In fact, it is an error (SYSLIB1062) to use LibraryImportAttribute without AllowUnsafeBlocks set to true.

@xtqqczze

xtqqczze commented Dec 2, 2022

Copy link
Copy Markdown
Contributor Author

We have no need the PR. The intention of the .Net team is to explicitly use nint where pointer arithmetic is used and most likely in other cases (although there are doubts about readability)

I believe the .NET team recommends replacing IntPtr with actual pointer types if the parameter is a pointer, e.g. dotnet/runtime@c77f524

@xtqqczze xtqqczze closed this Dec 2, 2022
@xtqqczze xtqqczze reopened this Dec 2, 2022
@daxian-dbw

Dongbo Wang (daxian-dbw) commented Dec 2, 2022 •

Copy link
Copy Markdown
Member

The old style (using IntPtr and void*) forces using unsafe context. Now .Net team introduced nint to use _pointer

There is no reason to avoid unsafe contexts in Pinvokes. In fact, it is an error (SYSLIB1062) to use LibraryImportAttribute without AllowUnsafeBlocks set to true.

This I agree. unsafe context will be used in the generated partial method anyways.


With regard to the reference dotnet code dotnet/runtime@c77f524, it changes to WaitForMultipleObjects(..., nint* handles, ...) because HANDLE * is a pointer to another pointer. But for LPSECURITY_ATTRIBUTES, it's a pointer to a SECURITY_ATTRIBUTES struct (shown below), so nint should be sufficient, isn't it?

typedef struct _SECURITY_ATTRIBUTES {
            DWORD nLength;
            LPVOID lpSecurityDescriptor;
            BOOL bInheritHandle;
} SECURITY_ATTRIBUTES, *PSECURITY_ATTRIBUTES, *LPSECURITY_ATTRIBUTES;

@jborean93

Jordan Borean (jborean93) commented Dec 2, 2022 •

Copy link
Copy Markdown
Collaborator

so nint should be sufficient, isn't it?

Yep that’s correct, and it being null is the same as IntPtr.Zero here. If you wanted to actually strictly type it you would need to define SECURITY_ATTRIBUTES and set the type as SECURITY_ATTRIBUTES*.

@iSazonov

Ilya (iSazonov) commented Dec 3, 2022 •

Copy link
Copy Markdown
Collaborator

The old style (using IntPtr and void*) forces using unsafe context. Now .Net team introduced nint to use _pointer

There is no reason to avoid unsafe contexts in Pinvokes. In fact, it is an error (SYSLIB1062) to use LibraryImportAttribute without AllowUnsafeBlocks set to true.

This I agree. unsafe context will be used in the generated partial method anyways.

To be clear - the PR uses "unsafe" keyword even though it is not necessary. Programming languages exist precisely to avoid unverifiable constructs and unsafe is just an indication that the developer is trying to use unverifiable code which can be dangerous. (unverifiable term comes from https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/unsafe-code)
From docs https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/unsafe

The unsafe keyword denotes an unsafe context, which is required for any operation involving pointers.

We have no need to do any operations with pointers in the PR.
Although C# does not completely avoid unsafe in some cases no doubt developers of C# languages will strive to do so.

With regard to the reference dotnet code dotnet/runtime@c77f524, it changes to WaitForMultipleObjects(..., nint* handles, ...) because HANDLE * is a pointer to another pointer. But for LPSECURITY_ATTRIBUTES, it's a pointer to a SECURITY_ATTRIBUTES struct (shown below), so nint should be sufficient, isn't it?

typedef struct _SECURITY_ATTRIBUTES {
            DWORD nLength;
            LPVOID lpSecurityDescriptor;
            BOOL bInheritHandle;
} SECURITY_ATTRIBUTES, *PSECURITY_ATTRIBUTES, *LPSECURITY_ATTRIBUTES;

Correct.
In fact, we can only use blittable types for native function parameters.
This creates two problems - readability and conversion of managed types to blittable types.
So the best thing we can do is to move everything related to pinvokes from the main code to separate files( or a file), as more as possible.
After migrating a few pinvokes, we can already see that our main code is much more readable, although there are still (readability) issues with the code that directly implements the pinvokes. We need to keep an eye on what the .Net team will offer us in .Net 8.

Learn about unsafe code, pointers, and function pointers. C# requires you to declare an unsafe context to use these features to directly manipulate memory or function pointers (unmanaged delegates).
unsafe keyword - C# Reference

@ghost ghost added the Waiting on Author The PR was reviewed and requires changes or comments from the author before being accept label Dec 6, 2022
@ghost ghost removed the Waiting on Author The PR was reviewed and requires changes or comments from the author before being accept label Dec 13, 2022
@pull-request-quantifier-deprecated

Copy link
Copy Markdown

This PR has 8 quantified lines of changes. In general, a change size of upto 200 lines is ideal for the best PR experience!


Quantification details

Label      : Extra Small
Size       : +5 -3
Percentile : 3.2%

Total files changed: 2

Change summary by file extension:
.cs : +5 -3

Change counts above are quantified counts, based on the PullRequestQuantifier customizations.

Why proper sizing of changes matters

Optimal pull request sizes drive a better predictable PR flow as they strike a
balance between between PR complexity and PR review overhead. PRs within the
optimal size (typical small, or medium sized PRs) mean:

  • Fast and predictable releases to production:
    • Optimal size changes are more likely to be reviewed faster with fewer
      iterations.
    • Similarity in low PR complexity drives similar review times.
  • Review quality is likely higher as complexity is lower:
    • Bugs are more likely to be detected.
    • Code inconsistencies are more likely to be detected.
  • Knowledge sharing is improved within the participants:
    • Small portions can be assimilated better.
  • Better engineering practices are exercised:
    • Solving big problems by dividing them in well contained, smaller problems.
    • Exercising separation of concerns within the code changes.

What can I do to optimize my changes

  • Use the PullRequestQuantifier to quantify your PR accurately
    • Create a context profile for your repo using the context generator
    • Exclude files that are not necessary to be reviewed or do not increase the review complexity. Example: Autogenerated code, docs, project IDE setting files, binaries, etc. Check out the Excluded section from your prquantifier.yaml context profile.
    • Understand your typical change complexity, drive towards the desired complexity by adjusting the label mapping in your prquantifier.yaml context profile.
    • Only use the labels that matter to you, see context specification to customize your prquantifier.yaml context profile.
  • Change your engineering behaviors
    • For PRs that fall outside of the desired spectrum, review the details and check if:
      • Your PR could be split in smaller, self-contained PRs instead
      • Your PR only solves one particular issue. (For example, don't refactor and code new features in the same PR).

How to interpret the change counts in git diff output

  • One line was added: +1 -0
  • One line was deleted: +0 -1
  • One line was modified: +1 -1 (git diff doesn't know about modified, it will
    interpret that line like one addition plus one deletion)
  • Change percentiles: Change characteristics (addition, deletion, modification)
    of this PR in relation to all other PRs within the repository.


Was this comment helpful? 👍  :ok_hand:  :thumbsdown: (Email)
Customize PullRequestQuantifier for this repository.

@ghost ghost added the Waiting on Author The PR was reviewed and requires changes or comments from the author before being accept label Dec 16, 2022
@ghost ghost added the Stale label Dec 31, 2022
@ghost

Copy link
Copy Markdown

This pull request has been automatically marked as stale because it has been marked as requiring author feedback but has not had any activity for 15 days. It will be closed if no further activity occurs within 10 days of this comment.

@ghost ghost closed this Jan 11, 2023
This pull request was closed.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

Extra Small Stale Waiting on Author The PR was reviewed and requires changes or comments from the author before being accept

Projects

None yet

Development

Successfully merging this pull request may close these issues.

5 participants