Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Passing null for array of blittable types results in NullReferenceException #1051

Closed
elinor-fung opened this issue Apr 30, 2021 · 5 comments
Closed
Assignees
Labels
area-DllImportGenerator Source Generated stubs for P/Invokes in C#

Comments

@elinor-fung
Copy link
Member

Generated code doesn't handle null when marshalling an array of blittable types.

[GeneratedDllImport(NativeExportsNE_Binary, EntryPoint = "sum_int_array")]
public static partial int Sum(int[] values, int numValues);
...
NativeExportsNE.Sum(null, 0);

In the generated code, we pass null to MemoryMarshal.GetArrayDataReference throws NullReferenceException:

fixed (int* __values_gen_native = &System.Runtime.InteropServices.MemoryMarshal.GetArrayDataReference(values))
    __retVal = Sum__PInvoke__(__values_gen_native, numValues);

cc @AaronRobinsonMSFT @jkoritzinsky

@elinor-fung elinor-fung added the area-DllImportGenerator Source Generated stubs for P/Invokes in C# label Apr 30, 2021
@jkotas
Copy link
Member

jkotas commented Apr 30, 2021

Also, this should generate just fixed (int* __values_gen_native = values) for concrete arrays.

@jkoritzinsky
Copy link
Member

We can't just do fixed (int* __values_gen_native = values) because that results in a null pointer for a zero-length array, which breaks P/Invokes to libraries like GDI+.

@AaronRobinsonMSFT
Copy link
Member

AaronRobinsonMSFT commented Apr 30, 2021

@jkoritzinsky I recall this being an issue we wanted to fix but given the compat burden we decided not to do that. We should have a conversation around the GDI+ API surface and see if it is something we want to support. I'm not convinced a single API surface should force this decision.

@jkotas
Copy link
Member

jkotas commented Apr 30, 2021

These bogus null pointer checks are not unusual in the Windows APIs. For example here: https://github.com/dotnet/runtime/blob/01b7e73cd378145264a7cb7a09365b41ed42b240/src/libraries/System.Private.CoreLib/src/System/Globalization/CompareInfo.Icu.cs#L733 or here https://github.com/dotnet/runtime/pull/52030/files#diff-4b9bcd238c75b08d184c630e8e90372464f848bbb2ed0466c0c3bafe74ee27b7R23

The eventual marshaling of Spans will hit similar problem.

@jkoritzinsky
Copy link
Member

Fixed by #1063

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
area-DllImportGenerator Source Generated stubs for P/Invokes in C#
Projects
None yet
Development

No branches or pull requests

4 participants