Skip to content

Commit

Permalink
Update DllImportGenerator to the latest version (#59117)
Browse files Browse the repository at this point in the history
  • Loading branch information
jkoritzinsky authored Sep 14, 2021
1 parent 5f0f7a1 commit 5b8ce63
Show file tree
Hide file tree
Showing 30 changed files with 274 additions and 17 deletions.
2 changes: 1 addition & 1 deletion eng/Versions.props
Original file line number Diff line number Diff line change
Expand Up @@ -189,6 +189,6 @@
<WixPackageVersion>3.14.0-dotnet</WixPackageVersion>
<MonoWorkloadManifestVersion>6.0.0-preview.5.21275.7</MonoWorkloadManifestVersion>
<!-- Experimental -->
<MicrosoftInteropDllImportGeneratorVersion>1.0.0-alpha.21301.2</MicrosoftInteropDllImportGeneratorVersion>
<MicrosoftInteropDllImportGeneratorVersion>1.0.0-alpha.21464.1</MicrosoftInteropDllImportGeneratorVersion>
</PropertyGroup>
</Project>
11 changes: 10 additions & 1 deletion eng/generators.targets
Original file line number Diff line number Diff line change
Expand Up @@ -8,13 +8,19 @@
<PropertyGroup Condition="'$(EnableDllImportGenerator)' == 'true'">
<DllImportGenerator_UseMarshalType>true</DllImportGenerator_UseMarshalType>
</PropertyGroup>
<PropertyGroup Condition="'$(MSBuildProjectName)' == 'System.Private.CoreLib' or
('@(ProjectReference)' != '' and @(ProjectReference->AnyHaveMetadataValue('Identity', '$(CoreLibProject)')))">
<DllImportGenerator_UseInternalUnsafeType>true</DllImportGenerator_UseInternalUnsafeType>
<DefineConstants>$(DefineConstants);DLLIMPORTGENERATOR_INTERNALUNSAFE</DefineConstants>
</PropertyGroup>
<ItemGroup Condition="'$(EnableDllImportGenerator)' == 'true' and $([MSBuild]::IsTargetFrameworkCompatible('$(TargetFramework)', 'net6.0'))">
<PackageReference Include="Microsoft.Interop.DllImportGenerator" Version="$(MicrosoftInteropDllImportGeneratorVersion)" PrivateAssets="all" />

<!-- For testing purposes, compile sources files with attributes directly into the project.
This is mimicking the case where the source generator always generates the attributes. -->
<Compile Include="$(LibrariesProjectRoot)Common/src/System/Runtime/InteropServices/GeneratedDllImportAttribute.cs" />
<Compile Include="$(LibrariesProjectRoot)Common/src/System/Runtime/InteropServices/GeneratedMarshallingAttribute.cs" />
<Compile Include="$(LibrariesProjectRoot)Common/src/System/Runtime/InteropServices/ArrayMarshaller.cs" />
</ItemGroup>
</Target>

Expand All @@ -28,7 +34,10 @@
<EnableDllImportGenerator Condition="'$(MSBuildProjectName)' == 'System.Private.CoreLib'">true</EnableDllImportGenerator>

<!-- Enable DllImportGenerator by default for NETCoreApp libraries that reference either System.Runtime.InteropServices or System.Private.CoreLib -->
<EnableDllImportGenerator Condition="'@(Reference)' != '' and @(Reference->AnyHaveMetadataValue('Identity', 'System.Runtime.InteropServices'))">true</EnableDllImportGenerator>
<EnableDllImportGenerator Condition="'@(Reference)' != ''
and @(Reference->AnyHaveMetadataValue('Identity', 'System.Runtime.InteropServices'))
and @(Reference->AnyHaveMetadataValue('Identity', 'System.Runtime.CompilerServices.Unsafe'))
and @(Reference->AnyHaveMetadataValue('Identity', 'System.Memory'))">true</EnableDllImportGenerator>
<EnableDllImportGenerator Condition="'@(ProjectReference)' != '' and @(ProjectReference->AnyHaveMetadataValue('Identity', '$(CoreLibProject)'))">true</EnableDllImportGenerator>
</PropertyGroup>
</Target>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@ internal static partial class Sys
/// Returns the number of bytes placed into the buffer on success; bufferSize if the buffer is too small; and -1 on error.
/// </returns>
[GeneratedDllImport(Libraries.SystemNative, EntryPoint = "SystemNative_ReadLink", SetLastError = true)]
private static extern int ReadLink(ref byte path, byte[] buffer, int bufferSize);
private static partial int ReadLink(ref byte path, byte[] buffer, int bufferSize);

/// <summary>
/// Takes a path to a symbolic link and returns the link target path.
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ internal static partial class Interop
internal static partial class Sys
{
[GeneratedDllImport(Libraries.SystemNative, EntryPoint = "SystemNative_Stat", SetLastError = true)]
internal static extern int Stat(ref byte path, out FileStatus output);
internal static partial int Stat(ref byte path, out FileStatus output);

internal static int Stat(ReadOnlySpan<char> path, out FileStatus output)
{
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ internal static partial class Interop
internal static partial class Crypto
{
[GeneratedDllImport(Libraries.CryptoNative)]
private static extern SafeEvpPKeyHandle CryptoNative_EvpPKeyCreateRsa(IntPtr rsa);
private static partial SafeEvpPKeyHandle CryptoNative_EvpPKeyCreateRsa(IntPtr rsa);

internal static SafeEvpPKeyHandle EvpPKeyCreateRsa(IntPtr rsa)
{
Expand All @@ -29,8 +29,8 @@ internal static SafeEvpPKeyHandle EvpPKeyCreateRsa(IntPtr rsa)
return pkey;
}

[DllImport(Libraries.CryptoNative)]
private static extern SafeEvpPKeyHandle CryptoNative_RsaGenerateKey(int keySize);
[GeneratedDllImport(Libraries.CryptoNative)]
private static partial SafeEvpPKeyHandle CryptoNative_RsaGenerateKey(int keySize);

internal static SafeEvpPKeyHandle RsaGenerateKey(int keySize)
{
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -44,16 +44,16 @@ internal static SafeEvpPKeyHandle EvpPKeyDuplicate(
internal static partial int EvpPKeySize(SafeEvpPKeyHandle pkey);

[GeneratedDllImport(Libraries.CryptoNative, EntryPoint = "CryptoNative_UpRefEvpPkey")]
internal static extern int UpRefEvpPkey(SafeEvpPKeyHandle handle);
internal static partial int UpRefEvpPkey(SafeEvpPKeyHandle handle);

[DllImport(Libraries.CryptoNative)]
private static extern unsafe SafeEvpPKeyHandle CryptoNative_DecodeSubjectPublicKeyInfo(
[GeneratedDllImport(Libraries.CryptoNative)]
private static unsafe partial SafeEvpPKeyHandle CryptoNative_DecodeSubjectPublicKeyInfo(
byte* buf,
int len,
int algId);

[DllImport(Libraries.CryptoNative)]
private static extern unsafe SafeEvpPKeyHandle CryptoNative_DecodePkcs8PrivateKey(
[GeneratedDllImport(Libraries.CryptoNative)]
private static unsafe partial SafeEvpPKeyHandle CryptoNative_DecodePkcs8PrivateKey(
byte* buf,
int len,
int algId);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -75,7 +75,7 @@ internal static partial class Ssl
internal static partial int SslRead(SafeSslHandle ssl, ref byte buf, int num);

[GeneratedDllImport(Libraries.CryptoNative, EntryPoint = "CryptoNative_SslRenegotiate")]
internal static extern int SslRenegotiate(SafeSslHandle ssl);
internal static partial int SslRenegotiate(SafeSslHandle ssl);

[GeneratedDllImport(Libraries.CryptoNative, EntryPoint = "CryptoNative_IsSslRenegotiatePending")]
[return: MarshalAs(UnmanagedType.Bool)]
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,225 @@
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.

//
// Types in this file are used for generated p/invokes (docs/design/features/source-generator-pinvokes.md).
// See the DllImportGenerator experiment in https://github.com/dotnet/runtimelab.
//
#if DLLIMPORTGENERATOR_INTERNALUNSAFE
using Internal.Runtime.CompilerServices;
#else
using System.Runtime.CompilerServices;
#endif
using System.Diagnostics;

namespace System.Runtime.InteropServices.GeneratedMarshalling
{
internal unsafe ref struct ArrayMarshaller<T>
{
private T[]? _managedArray;
private readonly int _sizeOfNativeElement;
private IntPtr _allocatedMemory;

public ArrayMarshaller(int sizeOfNativeElement)
:this()
{
_sizeOfNativeElement = sizeOfNativeElement;
}

public ArrayMarshaller(T[]? managed, int sizeOfNativeElement)
{
_allocatedMemory = default;
_sizeOfNativeElement = sizeOfNativeElement;
if (managed is null)
{
_managedArray = null;
NativeValueStorage = default;
return;
}
_managedArray = managed;
// Always allocate at least one byte when the array is zero-length.
int spaceToAllocate = Math.Max(managed.Length * _sizeOfNativeElement, 1);
_allocatedMemory = Marshal.AllocCoTaskMem(spaceToAllocate);
NativeValueStorage = new Span<byte>((void*)_allocatedMemory, spaceToAllocate);
}

public ArrayMarshaller(T[]? managed, Span<byte> stackSpace, int sizeOfNativeElement)
{
_allocatedMemory = default;
_sizeOfNativeElement = sizeOfNativeElement;
if (managed is null)
{
_managedArray = null;
NativeValueStorage = default;
return;
}
_managedArray = managed;
// Always allocate at least one byte when the array is zero-length.
int spaceToAllocate = Math.Max(managed.Length * _sizeOfNativeElement, 1);
if (spaceToAllocate <= stackSpace.Length)
{
NativeValueStorage = stackSpace[0..spaceToAllocate];
}
else
{
_allocatedMemory = Marshal.AllocCoTaskMem(spaceToAllocate);
NativeValueStorage = new Span<byte>((void*)_allocatedMemory, spaceToAllocate);
}
}

/// <summary>
/// Stack-alloc threshold set to 256 bytes to enable small arrays to be passed on the stack.
/// Number kept small to ensure that P/Invokes with a lot of array parameters doesn't
/// blow the stack since this is a new optimization in the code-generated interop.
/// </summary>
public const int StackBufferSize = 0x200;

public Span<T> ManagedValues => _managedArray;

public Span<byte> NativeValueStorage { get; private set; }

public ref byte GetPinnableReference() => ref MemoryMarshal.GetReference(NativeValueStorage);

public void SetUnmarshalledCollectionLength(int length)
{
_managedArray = new T[length];
}

public byte* Value
{
get
{
Debug.Assert(_managedArray is null || _allocatedMemory != IntPtr.Zero);
return (byte*)_allocatedMemory;
}
set
{
if (value == null)
{
_managedArray = null;
NativeValueStorage = default;
}
else
{
_allocatedMemory = (IntPtr)value;
NativeValueStorage = new Span<byte>(value, (_managedArray?.Length ?? 0) * _sizeOfNativeElement);
}
}
}

public T[]? ToManaged() => _managedArray;

public void FreeNative()
{
if (_allocatedMemory != IntPtr.Zero)
{
Marshal.FreeCoTaskMem(_allocatedMemory);
}
}
}

internal unsafe ref struct PtrArrayMarshaller<T> where T : unmanaged
{
private T*[]? _managedArray;
private readonly int _sizeOfNativeElement;
private IntPtr _allocatedMemory;

public PtrArrayMarshaller(int sizeOfNativeElement)
: this()
{
_sizeOfNativeElement = sizeOfNativeElement;
}

public PtrArrayMarshaller(T*[]? managed, int sizeOfNativeElement)
{
_allocatedMemory = default;
_sizeOfNativeElement = sizeOfNativeElement;
if (managed is null)
{
_managedArray = null;
NativeValueStorage = default;
return;
}
_managedArray = managed;
// Always allocate at least one byte when the array is zero-length.
int spaceToAllocate = Math.Max(managed.Length * _sizeOfNativeElement, 1);
_allocatedMemory = Marshal.AllocCoTaskMem(spaceToAllocate);
NativeValueStorage = new Span<byte>((void*)_allocatedMemory, spaceToAllocate);
}

public PtrArrayMarshaller(T*[]? managed, Span<byte> stackSpace, int sizeOfNativeElement)
{
_allocatedMemory = default;
_sizeOfNativeElement = sizeOfNativeElement;
if (managed is null)
{
_managedArray = null;
NativeValueStorage = default;
return;
}
_managedArray = managed;
// Always allocate at least one byte when the array is zero-length.
int spaceToAllocate = Math.Max(managed.Length * _sizeOfNativeElement, 1);
if (spaceToAllocate <= stackSpace.Length)
{
NativeValueStorage = stackSpace[0..spaceToAllocate];
}
else
{
_allocatedMemory = Marshal.AllocCoTaskMem(spaceToAllocate);
NativeValueStorage = new Span<byte>((void*)_allocatedMemory, spaceToAllocate);
}
}

/// <summary>
/// Stack-alloc threshold set to 256 bytes to enable small arrays to be passed on the stack.
/// Number kept small to ensure that P/Invokes with a lot of array parameters doesn't
/// blow the stack since this is a new optimization in the code-generated interop.
/// </summary>
public const int StackBufferSize = 0x200;

public Span<IntPtr> ManagedValues => Unsafe.As<IntPtr[]>(_managedArray);

public Span<byte> NativeValueStorage { get; private set; }

public ref byte GetPinnableReference() => ref MemoryMarshal.GetReference(NativeValueStorage);

public void SetUnmarshalledCollectionLength(int length)
{
_managedArray = new T*[length];
}

public byte* Value
{
get
{
Debug.Assert(_managedArray is null || _allocatedMemory != IntPtr.Zero);
return (byte*)_allocatedMemory;
}
set
{
if (value == null)
{
_managedArray = null;
NativeValueStorage = default;
}
else
{
_allocatedMemory = (IntPtr)value;
NativeValueStorage = new Span<byte>(value, (_managedArray?.Length ?? 0) * _sizeOfNativeElement);
}

}
}

public T*[]? ToManaged() => _managedArray;

public void FreeNative()
{
if (_allocatedMemory != IntPtr.Zero)
{
Marshal.FreeCoTaskMem(_allocatedMemory);
}
}
}
}
1 change: 1 addition & 0 deletions src/libraries/System.Console/src/System.Console.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -219,6 +219,7 @@
<Reference Include="System.Collections" />
<Reference Include="System.Memory" />
<Reference Include="System.Runtime" />
<Reference Include="System.Runtime.CompilerServices.Unsafe" />
<Reference Include="System.Runtime.Extensions" />
<Reference Include="System.Runtime.InteropServices" />
<Reference Include="System.Text.Encoding.Extensions" />
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -41,7 +41,9 @@
</ItemGroup>
<ItemGroup>
<Reference Include="System.IO.FileSystem" />
<Reference Include="System.Memory" />
<Reference Include="System.Runtime" />
<Reference Include="System.Runtime.CompilerServices.Unsafe" />
<Reference Include="System.Runtime.Extensions" />
<Reference Include="System.Runtime.InteropServices" />
</ItemGroup>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -364,6 +364,7 @@
<Reference Include="System.Memory" />
<Reference Include="System.IO.Pipes" />
<Reference Include="System.Runtime" />
<Reference Include="System.Runtime.CompilerServices.Unsafe" />
<Reference Include="System.Runtime.Extensions" />
<Reference Include="System.Runtime.InteropServices" />
<Reference Include="System.Text.Encoding.Extensions" />
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@ internal static void ConfigureTerminalForChildProcesses(int increment, bool conf
Debug.Assert(configureConsole);

// At least one child is using the terminal.
Interop.Sys.ConfigureTerminalForChildProcess(childUsesTerminal: true);
Interop.Sys.ConfigureTerminalForChildProcess(childUsesTerminal: 1);
}
else
{
Expand All @@ -30,7 +30,7 @@ internal static void ConfigureTerminalForChildProcesses(int increment, bool conf
if (childrenUsingTerminalRemaining == 0 && configureConsole)
{
// No more children are using the terminal.
Interop.Sys.ConfigureTerminalForChildProcess(childUsesTerminal: false);
Interop.Sys.ConfigureTerminalForChildProcess(childUsesTerminal: 0);
}
}
}
Expand All @@ -50,7 +50,7 @@ private static void DelayedSigChildConsoleConfiguration()
if (s_childrenUsingTerminalCount == 0)
{
// No more children are using the terminal.
Interop.Sys.ConfigureTerminalForChildProcess(childUsesTerminal: false);
Interop.Sys.ConfigureTerminalForChildProcess(childUsesTerminal: 0);
}
}
finally
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -42,6 +42,7 @@
<Reference Include="System.Memory" />
<Reference Include="System.Runtime" />
<Reference Include="System.Runtime.Extensions" />
<Reference Include="System.Runtime.CompilerServices.Unsafe" />
<Reference Include="System.Runtime.InteropServices" />
<Reference Include="System.Threading" />
</ItemGroup>
Expand Down
Loading

0 comments on commit 5b8ce63

Please sign in to comment.