Skip to content

Commit

Permalink
Move the metadata update related APIs to the MetadataUpdater class
Browse files Browse the repository at this point in the history
The old APIs AssemblyExtensions.ApplyUpdate() and AssemblyExtensions.GetApplyUpdateCapabilities() will be removed
after all the references to them have been changed to the new APIs.

Add the new IsSupported API described in issue dotnet#51159.

Change the tests to use the MetadataUpdater APIs.
  • Loading branch information
mikem8361 committed Jun 24, 2021
1 parent 5306472 commit 72bc435
Show file tree
Hide file tree
Showing 9 changed files with 179 additions and 60 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -189,6 +189,7 @@
<Compile Include="$(BclSourcesRoot)\System\Reflection\MdImport.cs" />
<Compile Include="$(BclSourcesRoot)\System\Reflection\MemberInfo.Internal.cs" />
<Compile Include="$(BclSourcesRoot)\System\Reflection\Metadata\AssemblyExtensions.cs" />
<Compile Include="$(BclSourcesRoot)\System\Reflection\Metadata\MetadataUpdater.cs" />
<Compile Include="$(BclSourcesRoot)\System\Reflection\MethodBase.CoreCLR.cs" />
<Compile Include="$(BclSourcesRoot)\System\Reflection\RtFieldInfo.cs" />
<Compile Include="$(BclSourcesRoot)\System\Reflection\RuntimeAssembly.cs" />
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,63 @@
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.

using System.Diagnostics;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;

namespace System.Reflection.Metadata
{
public static class MetadataUpdater
{
[DllImport(RuntimeHelpers.QCall)]
private static extern unsafe void ApplyUpdate(QCallAssembly assembly, byte* metadataDelta, int metadataDeltaLength, byte* ilDelta, int ilDeltaLength, byte* pdbDelta, int pdbDeltaLength);

/// <summary>
/// Updates the specified assembly using the provided metadata, IL and PDB deltas.
/// </summary>
/// <remarks>
/// Currently executing methods will continue to use the existing IL. New executions of modified methods will
/// use the new IL. Different runtimes may have different limitations on what kinds of changes are supported,
/// and runtimes make no guarantees as to the state of the assembly and process if the delta includes
/// unsupported changes.
/// </remarks>
/// <param name="assembly">The assembly to update.</param>
/// <param name="metadataDelta">The metadata changes to be applied.</param>
/// <param name="ilDelta">The IL changes to be applied.</param>
/// <param name="pdbDelta">The PDB changes to be applied.</param>
/// <exception cref="ArgumentNullException">The assembly argument is null.</exception>
/// <exception cref="NotSupportedException">The update could not be applied.</exception>
public static void ApplyUpdate(Assembly assembly, ReadOnlySpan<byte> metadataDelta, ReadOnlySpan<byte> ilDelta, ReadOnlySpan<byte> pdbDelta)
{
if (assembly == null)
{
throw new ArgumentNullException(nameof(assembly));
}

RuntimeAssembly? runtimeAssembly = assembly as RuntimeAssembly;
if (runtimeAssembly == null)
{
throw new ArgumentException(SR.Argument_MustBeRuntimeAssembly);
}

unsafe
{
RuntimeAssembly rtAsm = runtimeAssembly;
fixed (byte* metadataDeltaPtr = metadataDelta, ilDeltaPtr = ilDelta, pdbDeltaPtr = pdbDelta)
{
ApplyUpdate(new QCallAssembly(ref rtAsm), metadataDeltaPtr, metadataDelta.Length, ilDeltaPtr, ilDelta.Length, pdbDeltaPtr, pdbDelta.Length);
}
}
}

/// <summary>
/// Returns the metadata update capabilities.
/// </summary>
public static string GetCapabilities() => "Baseline AddMethodToExistingType AddStaticFieldToExistingType AddInstanceFieldToExistingType NewTypeDefinition";

/// <summary>
/// Returns true if the apply assembly update is enabled and available.
/// </summary>
public static bool IsSupported => Debugger.IsAttached || Environment.GetEnvironmentVariable("DOTNET_MODIFIABLE_ASSEMBLIES") != "" || Environment.GetEnvironmentVariable("COMPlus_ForceEnc") == "1";
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,12 @@ public static partial class AssemblyExtensions
public unsafe static bool TryGetRawMetadata(this System.Reflection.Assembly assembly, out byte* blob, out int length) { throw null; }
public static void ApplyUpdate(Assembly assembly, ReadOnlySpan<byte> metadataDelta, ReadOnlySpan<byte> ilDelta, ReadOnlySpan<byte> pdbDelta) { throw null; }
}
public static partial class MetadataUpdater
{
public static void ApplyUpdate(Assembly assembly, ReadOnlySpan<byte> metadataDelta, ReadOnlySpan<byte> ilDelta, ReadOnlySpan<byte> pdbDelta) { throw null; }
public static string GetCapabilities() { throw null; }
public static bool IsSupported { get { throw null; } }
}
[System.AttributeUsage(System.AttributeTargets.Assembly, AllowMultiple = true)]
public sealed class MetadataUpdateHandlerAttribute : System.Attribute
{
Expand Down
38 changes: 38 additions & 0 deletions src/libraries/System.Runtime.Loader/tests/ApplyUpdateTest.cs
Original file line number Diff line number Diff line change
Expand Up @@ -83,5 +83,43 @@ void ClassWithCustomAttributes()
Assert.Equal(attrType, cattrs[0].GetType());
});
}

class NonRuntimeAssembly : Assembly
{
}

[Fact]
public static void ApplyUpdateInvalidParameters()
{
// Dummy delta arrays
var metadataDelta = new byte[20];
var ilDelta = new byte[20];

// Assembly can't be null
Assert.Throws<ArgumentNullException>("assembly", () =>
MetadataUpdater.ApplyUpdate(null, new ReadOnlySpan<byte>(metadataDelta), new ReadOnlySpan<byte>(ilDelta), ReadOnlySpan<byte>.Empty));

// Tests fail on non-runtime assemblies
Assert.Throws<ArgumentException>(() =>
MetadataUpdater.ApplyUpdate(new NonRuntimeAssembly(), new ReadOnlySpan<byte>(metadataDelta), new ReadOnlySpan<byte>(ilDelta), ReadOnlySpan<byte>.Empty));

// Tests that this assembly isn't not editable
Assert.Throws<InvalidOperationException>(() =>
MetadataUpdater.ApplyUpdate(typeof(AssemblyExtensions).Assembly, new ReadOnlySpan<byte>(metadataDelta), new ReadOnlySpan<byte>(ilDelta), ReadOnlySpan<byte>.Empty));
}

[Fact]
public static void GetCapabilities()
{
string result = MetadataUpdater.GetCapabilities();
Assert.NotNull(result);
}

[Fact]
public static void IsSupported()
{
bool result = MetadataUpdater.IsSupported;
Assert.False(result);
}
}
}
16 changes: 5 additions & 11 deletions src/libraries/System.Runtime.Loader/tests/ApplyUpdateUtil.cs
Original file line number Diff line number Diff line change
Expand Up @@ -48,16 +48,10 @@ internal static bool CheckSupportedMonoConfiguration()

internal static bool HasApplyUpdateCapabilities()
{
var ty = typeof(AssemblyExtensions);
var mi = ty.GetMethod("GetApplyUpdateCapabilities", BindingFlags.NonPublic | BindingFlags.Static, Array.Empty<Type>());

if (mi == null)
return false;

var caps = mi.Invoke(null, null);
string caps = MetadataUpdater.GetCapabilities();

// any non-empty string, assumed to be at least "baseline"
return caps is string {Length: > 0};
return caps.Length > 0;
}

private static System.Collections.Generic.Dictionary<Assembly, int> assembly_count = new();
Expand All @@ -83,15 +77,15 @@ internal static void ApplyUpdate (System.Reflection.Assembly assm)
byte[] dil_data = System.IO.File.ReadAllBytes(dil_name);
byte[] dpdb_data = null; // TODO also use the dpdb data

AssemblyExtensions.ApplyUpdate(assm, dmeta_data, dil_data, dpdb_data);
MetadataUpdater.ApplyUpdate(assm, dmeta_data, dil_data, dpdb_data);
}

internal static bool UseRemoteExecutor => !IsModifiableAssembliesSet;

internal static void AddRemoteInvokeOptions (ref RemoteInvokeOptions options)
{
options = options ?? new RemoteInvokeOptions();
options.StartInfo.EnvironmentVariables.Add(DotNetModifiableAssembliesSwitch, DotNetModifiableAssembliesValue);
options = options ?? new RemoteInvokeOptions();
options.StartInfo.EnvironmentVariables.Add(DotNetModifiableAssembliesSwitch, DotNetModifiableAssembliesValue);
}

/// Run the given test case, which applies updates to the given assembly.
Expand Down

This file was deleted.

Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,6 @@
<ItemGroup>
<Compile Include="ApplyUpdateTest.cs" />
<Compile Include="ApplyUpdateUtil.cs" />
<Compile Include="AssemblyExtensionsTest.cs" />
<Compile Include="AssemblyLoadContextTest.cs" />
<Compile Include="CollectibleAssemblyLoadContextTest.cs" />
<Compile Include="ContextualReflection.cs" />
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -239,6 +239,7 @@
<Compile Include="$(BclSourcesRoot)\System\Reflection\Emit\TypeBuilderInstantiation.cs" />
<Compile Include="$(BclSourcesRoot)\System\Reflection\Emit\UnmanagedMarshal.cs" />
<Compile Include="$(BclSourcesRoot)\System\Reflection\Metadata\AssemblyExtensions.cs" />
<Compile Include="$(BclSourcesRoot)\System\Reflection\Metadata\MetadataUpdater.cs" />
<Compile Include="$(BclSourcesRoot)\System\Resources\ManifestBasedResourceGroveler.Mono.cs" />
<Compile Include="$(BclSourcesRoot)\System\Runtime\GCSettings.Mono.cs" />
<Compile Include="$(BclSourcesRoot)\System\Runtime\CompilerServices\DependentHandle.cs" />
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,65 @@
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.

using System.Diagnostics;
using System.Runtime.CompilerServices;

namespace System.Reflection.Metadata
{
public static class MetadataUpdater
{
/// <summary>
/// Updates the specified assembly using the provided metadata, IL and PDB deltas.
/// </summary>
/// <remarks>
/// Currently executing methods will continue to use the existing IL. New executions of modified methods will
/// use the new IL. Different runtimes may have different limitations on what kinds of changes are supported,
/// and runtimes make no guarantees as to the state of the assembly and process if the delta includes
/// unsupported changes.
/// </remarks>
/// <param name="assembly">The assembly to update.</param>
/// <param name="metadataDelta">The metadata changes to be applied.</param>
/// <param name="ilDelta">The IL changes to be applied.</param>
/// <param name="pdbDelta">The PDB changes to be applied.</param>
/// <exception cref="ArgumentNullException">The assembly argument is null.</exception>
/// <exception cref="NotSupportedException">The update could not be applied.</exception>
public static void ApplyUpdate(Assembly assembly, ReadOnlySpan<byte> metadataDelta, ReadOnlySpan<byte> ilDelta, ReadOnlySpan<byte> pdbDelta)
{
if (assembly is not RuntimeAssembly runtimeAssembly)
{
if (assembly is null) throw new ArgumentNullException(nameof(assembly));
throw new ArgumentException(SR.Argument_MustBeRuntimeAssembly);
}

// System.Private.CoreLib is not editable
if (runtimeAssembly == typeof(AssemblyExtensions).Assembly)
throw new InvalidOperationException (SR.InvalidOperation_AssemblyNotEditable);

unsafe
{
IntPtr monoAssembly = runtimeAssembly.GetUnderlyingNativeHandle ();
fixed (byte* metadataDeltaPtr = metadataDelta, ilDeltaPtr = ilDelta, pdbDeltaPtr = pdbDelta)
{
ApplyUpdate_internal(monoAssembly, metadataDeltaPtr, metadataDelta.Length, ilDeltaPtr, ilDelta.Length, pdbDeltaPtr, pdbDelta.Length);
}
}
}

private static Lazy<string> s_ApplyUpdateCapabilities = new Lazy<string>(() => InitializeApplyUpdateCapabilities());

public static string GetCapabilities() => s_ApplyUpdateCapabilities.Value;

private static string InitializeApplyUpdateCapabilities()
{
return ApplyUpdateEnabled() != 0 ? "Baseline" : string.Empty ;
}

public static bool IsSupported => Debugger.IsAttached || Environment.GetEnvironmentVariable("DOTNET_MODIFIABLE_ASSEMBLIES") != "";

[MethodImpl (MethodImplOptions.InternalCall)]
private static extern int ApplyUpdateEnabled ();

[MethodImpl (MethodImplOptions.InternalCall)]
private static unsafe extern void ApplyUpdate_internal (IntPtr base_assm, byte* dmeta_bytes, int dmeta_length, byte *dil_bytes, int dil_length, byte *dpdb_bytes, int dpdb_length);
}
}

0 comments on commit 72bc435

Please sign in to comment.