Skip to content

Implement object_isinst and object_get_class #129

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

Merged
merged 1 commit into from
Mar 17, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
16 changes: 8 additions & 8 deletions src/coreclr/vm/mono/mono_coreclr.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -60,6 +60,8 @@ struct HostStruct
uintptr_t (*gchandle_new_weakref_v2)(MonoObject* obj, gboolean track_resurrection);
intptr_t (*load_assembly_from_data)(const char* data, int64_t size);
intptr_t (*load_assembly_from_path)(const char* path, int32_t length);
MonoClass* (*object_get_class)(MonoObject* obj);
MonoObject* (*object_isinst)(MonoObject* obj, MonoClass* klass);
ManagedStringPtr_t (*string_from_utf16)(const gunichar2* text);
ManagedStringPtr_t (*string_new_len)(MonoDomain* domain, const char* text, guint32 length);
ManagedStringPtr_t (*string_new_utf16)(MonoDomain* domain, const guint16* text, gint32 length);
Expand Down Expand Up @@ -2395,10 +2397,10 @@ extern "C" EXPORT_API MonoMethodSignature* EXPORT_CC mono_method_signature_check
return NULL;
}

extern "C" EXPORT_API MonoClass* EXPORT_CC mono_object_get_class(MonoObject *obj)
// Generated by UnityEmbedHost.Generator - Commit these changes
extern "C" EXPORT_API MonoClass* EXPORT_CC mono_object_get_class(MonoObject* obj)
{
MonoClass_clr* klass = reinterpret_cast<MonoObject_clr*>(obj)->GetMethodTable();
return (MonoClass*)klass;
return g_HostStruct->object_get_class(obj);
}

extern "C" EXPORT_API guint32 EXPORT_CC mono_object_get_size(MonoObject *obj)
Expand Down Expand Up @@ -2430,12 +2432,10 @@ extern "C" EXPORT_API MonoMethod* EXPORT_CC mono_object_get_virtual_method(MonoO
return (MonoMethod*)m2;
}

extern "C" EXPORT_API MonoObject* EXPORT_CC mono_object_isinst(MonoObject *obj, MonoClass* klass)
// Generated by UnityEmbedHost.Generator - Commit these changes
extern "C" EXPORT_API MonoObject* EXPORT_CC mono_object_isinst(MonoObject* obj, MonoClass* klass)
{
MonoClass* clazz = mono_object_get_class(obj);
if (mono_class_is_subclass_of(clazz, klass, TRUE))
return obj;
return NULL;
return g_HostStruct->object_isinst(obj, klass);
}

extern "C" EXPORT_API MonoObject* EXPORT_CC mono_object_new(MonoDomain *domain, MonoClass *klass)
Expand Down
14 changes: 8 additions & 6 deletions unity/UnityEmbedHost.Tests/CoreCLRHostTestingWrappers.cs
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.

using System.Runtime.CompilerServices;
using Unity.CoreCLRHelpers;

namespace UnityEmbedHost.Tests;
Expand All @@ -12,11 +11,14 @@ namespace UnityEmbedHost.Tests;
static class CoreCLRHostTestingWrappers
{
public static nint gchandle_new_v2(object obj, bool pinned)
=> CoreCLRHost.gchandle_new_v2(Unsafe.As<object, IntPtr>(ref obj), pinned);
=> CoreCLRHost.gchandle_new_v2(obj.UnsafeAsIntPtr(), pinned);

public static object? gchandle_get_target_v2(nint handleIn)
{
var result = CoreCLRHost.gchandle_get_target_v2(handleIn);
return Unsafe.As<IntPtr, object>(ref result);
}
=> CoreCLRHost.gchandle_get_target_v2(handleIn).UnsafeAs<object>();

public static object? object_isinst(object obj, Type klass)
=> CoreCLRHost.object_isinst(obj.UnsafeAsIntPtr(), klass.TypeHandleIntPtr()).UnsafeAs<object>();

public static Type object_get_class(object obj)
=> CoreCLRHost.object_get_class(obj.UnsafeAsIntPtr()).TypeFromHandleIntPtr();
}
121 changes: 121 additions & 0 deletions unity/UnityEmbedHost.Tests/EmbeddingApiTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -55,4 +55,125 @@ public void GCHandleNewAndGetTarget()
GCHandle.FromIntPtr(handle1).Free();
GCHandle.FromIntPtr(handle2).Free();
}

// Classes and classes
[TestCase(typeof(object), typeof(object), true)]
Copy link
Member

Choose a reason for hiding this comment

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

What runtime are these tests running on? Mono? Our CoreCLR with our GC?

Copy link
Collaborator Author

Choose a reason for hiding this comment

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

From Rider they are going to run on whatever coreclr rider is using.

From the CI scripts, I'm not sure. Maybe the system installed, maybe our fork. @UnityAlex do you know?

Copy link
Member

@joncham joncham Mar 16, 2023

Choose a reason for hiding this comment

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

The Unsafe calls making objects into IntPtr's are actually unsafe ;-) on stock CoreCLR as objects may be moved by the GC.

Copy link
Collaborator

Choose a reason for hiding this comment

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

From Rider they are going to run on whatever coreclr rider is using.

From the CI scripts, I'm not sure. Maybe the system installed, maybe our fork. @UnityAlex do you know?

Yes the way it's setup currently it's just running dotnet so whatever is on the PATH env var.

Copy link
Collaborator Author

Choose a reason for hiding this comment

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

The Unsafe calls making objects into IntPtr's are actually unsafe ;-) on stock CoreCLR as objects may be moved by the GC.

Makes sense. I didn't think about that. I guess we'll see how long we get lucky for 😄

[TestCase(typeof(Mammal), typeof(Mammal), true)]
[TestCase(typeof(Mammal), typeof(Anaimal), true)]
[TestCase(typeof(Cat), typeof(Anaimal), true)]
[TestCase(typeof(Rock), typeof(Anaimal), false)]

// Classes and interfaces
[TestCase(typeof(Mammal), typeof(IMammal), true)]
[TestCase(typeof(Mammal), typeof(IAnimal), true)]
[TestCase(typeof(Cat), typeof(IAnimal), true)]
[TestCase(typeof(CatOnlyInterface), typeof(IAnimal), true)]

[TestCase(typeof(Rock), typeof(IAnimal), false)]
[TestCase(typeof(NoInterfaces), typeof(IAnimal), false)]
[TestCase(typeof(object), typeof(IRock), false)]

// Structs and ValueType
[TestCase(typeof(ValueMammal), typeof(ValueType), true)]

// Structs and interfaces
[TestCase(typeof(ValueMammal), typeof(IMammal), true)]
[TestCase(typeof(ValueMammal), typeof(IAnimal), true)]
[TestCase(typeof(ValueCat), typeof(IAnimal), true)]

[TestCase(typeof(ValueRock), typeof(IAnimal), false)]
[TestCase(typeof(ValueNoInterfaces), typeof(IAnimal), false)]
public void IsInst(Type obj, Type type, bool shouldBeInstanceOfType)
{
var instance = Activator.CreateInstance(obj)!;

CheckObjectIsInstance(obj, type, shouldBeInstanceOfType, instance);
}

[TestCase(typeof(Mammal), 1, typeof(Mammal), 1, true)]
[TestCase(typeof(Mammal), 1, typeof(Anaimal), 1, true)]

[TestCase(typeof(Mammal), 1, typeof(Mammal), 3, false)]

[TestCase(typeof(ValueMammal), 1, typeof(ValueMammal), 1, true)]
[TestCase(typeof(ValueMammal), 1, typeof(IMammal), 1, false)]

[TestCase(typeof(ValueMammal), 1, typeof(ValueMammal), 3, false)]

[TestCase(typeof(Mammal), 1, typeof(IMammal), 1, true)]
[TestCase(typeof(Mammal), 1, typeof(IAnimal), 1, true)]
[TestCase(typeof(Mammal), 1, typeof(IMammal), 2, false)]
public void IsInstArrays(Type obj, int rank, Type checkType, int checkRank, bool shouldBeInstanceOfType)
{
var instance = Array.CreateInstance(obj, new int[rank]);
Type arrayType = Array.CreateInstance(checkType, new int[checkRank]).GetType();
CheckObjectIsInstance(instance.GetType(), arrayType, shouldBeInstanceOfType, instance);
}

[TestCase(typeof(Mammal), typeof(Mammal), 1, false)]
[TestCase(typeof(Mammal), typeof(Anaimal), 1, false)]

[TestCase(typeof(Mammal), typeof(Mammal), 2, false)]

[TestCase(typeof(ValueMammal),typeof(ValueMammal), 1, false)]
[TestCase(typeof(ValueMammal), typeof(IMammal), 1, false)]

[TestCase(typeof(ValueMammal), typeof(ValueMammal), 2, false)]

[TestCase(typeof(Mammal), typeof(IMammal), 1, false)]
[TestCase(typeof(Mammal), typeof(IAnimal), 1, false)]
[TestCase(typeof(Mammal), typeof(IMammal), 2, false)]
public void IsInstNoneArrayToArrays(Type obj, Type checkType, int checkRank, bool shouldBeInstanceOfType)
{
var instance = Activator.CreateInstance(obj)!;

CheckObjectIsInstance(instance.GetType(), Array.CreateInstance(checkType, new int[checkRank]).GetType(), shouldBeInstanceOfType, instance);
}

[TestCase(typeof(Mammal), 1, typeof(Mammal), false)]
[TestCase(typeof(Mammal), 1, typeof(Anaimal), false)]

[TestCase(typeof(Mammal), 1, typeof(Mammal), false)]

[TestCase(typeof(ValueMammal), 1, typeof(ValueMammal), false)]
[TestCase(typeof(ValueMammal), 1, typeof(IMammal), false)]

[TestCase(typeof(ValueMammal), 1, typeof(ValueMammal), false)]

[TestCase(typeof(Mammal), 1, typeof(IMammal), false)]
[TestCase(typeof(Mammal), 1, typeof(IAnimal), false)]
[TestCase(typeof(Mammal), 1, typeof(IMammal), false)]
public void IsInstArrayToNoneArray(Type obj, int rank, Type checkType, bool shouldBeInstanceOfType)
{
var instance = Array.CreateInstance(obj, new int[rank]);

CheckObjectIsInstance(instance.GetType(), checkType, shouldBeInstanceOfType, instance);
}

private static void CheckObjectIsInstance(Type obj, Type type, bool shouldBeInstanceOfType, object instance)
{
var result = CoreCLRHostTestingWrappers.object_isinst(instance, type);

if (shouldBeInstanceOfType)
{
if (result == null)
Assert.Fail($"Expected {obj} to be of type {type}, but {nameof(CoreCLRHost.object_isinst)} claimed it wasn't");

Assert.That(result, Is.EqualTo(instance));
}
else
{
if (result != null)
Assert.Fail($"Expected {obj} to NOT be of type {type}, but {nameof(CoreCLRHost.object_isinst)} claimed it was");

Assert.That(result, Is.Null);
}
}

[TestCase(typeof(Anaimal))]
[TestCase(typeof(ValueAnimal))]
public void GetClass(Type type)
{
Assert.That(CoreCLRHostTestingWrappers.object_get_class(Activator.CreateInstance(type)!), Is.EqualTo(type));
}
}
69 changes: 69 additions & 0 deletions unity/UnityEmbedHost.Tests/Samples.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,69 @@
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.

namespace UnityEmbedHost.Tests;

class Mammal : Anaimal, IMammal
{
}

class Cat : Mammal, ICat
{
}

class CatOnlyInterface : ICat
{
}

class Rock : IRock
{
}

class Anaimal : IAnimal
{
}

class NoInterfaces
{
}

interface IAnimal
{
}

interface IMammal : IAnimal
{
}

interface ICat : IMammal
{
}

interface IRock
{
}

struct MyStruct
{

}

struct ValueMammal : IMammal
{
}

struct ValueCat : ICat
{
}

struct ValueRock : IRock
{
}

struct ValueAnimal : IAnimal
{
}

struct ValueNoInterfaces
{
}
18 changes: 11 additions & 7 deletions unity/unity-embed-host/CoreCLRHost.cs
Original file line number Diff line number Diff line change
Expand Up @@ -76,24 +76,28 @@ public static StringPtr string_new_utf16([NativeCallbackType("MonoDomain*")] voi
[return: NativeCallbackType("uintptr_t")]
public static IntPtr gchandle_new_v2([NativeCallbackType("MonoObject*")] IntPtr obj, bool pinned)
{
GCHandle handle = GCHandle.Alloc(Unsafe.As<IntPtr, Object>(ref obj), pinned ? GCHandleType.Pinned : GCHandleType.Normal);
GCHandle handle = GCHandle.Alloc(obj.UnsafeAs<object>(), pinned ? GCHandleType.Pinned : GCHandleType.Normal);
return GCHandle.ToIntPtr(handle);
}

[return: NativeCallbackType("uintptr_t")]
public static IntPtr gchandle_new_weakref_v2([NativeCallbackType("MonoObject*")] IntPtr obj, bool track_resurrection)
{
GCHandle handle = GCHandle.Alloc(Unsafe.As<IntPtr, Object>(ref obj), track_resurrection ? GCHandleType.WeakTrackResurrection : GCHandleType.Weak);
GCHandle handle = GCHandle.Alloc(obj.UnsafeAs<object>(), track_resurrection ? GCHandleType.WeakTrackResurrection : GCHandleType.Weak);
return GCHandle.ToIntPtr(handle);
}

[return: NativeWrapperType("MonoObject*")]
public static IntPtr gchandle_get_target_v2([NativeWrapperType("uintptr_t")] IntPtr handleIn)
{
GCHandle handle = GCHandle.FromIntPtr(handleIn);
object obj = handle.Target;
return Unsafe.As<object, IntPtr>(ref obj);
}
=> handleIn.ToGCHandle().Target.UnsafeAsIntPtr();

[return: NativeCallbackType("MonoObject*")]
public static IntPtr object_isinst([NativeCallbackType("MonoObject*")] IntPtr obj, [NativeCallbackType("MonoClass*")] IntPtr klass)
=> obj.UnsafeAs<object>().GetType().IsAssignableTo(klass.TypeFromHandleIntPtr()) ? obj : nint.Zero;

[return: NativeCallbackType("MonoClass*")]
public static IntPtr object_get_class([NativeCallbackType("MonoObject*")] IntPtr obj)
=> obj.UnsafeAs<object>().TypeHandleIntPtr();

static StringPtr StringToPtr(string s)
{
Expand Down
32 changes: 32 additions & 0 deletions unity/unity-embed-host/Extensions.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.

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

namespace Unity.CoreCLRHelpers;

static class Extensions
{
public static Type TypeFromHandleIntPtr(this nint intPtrToTypeHandle)
=> Type.GetTypeFromHandle(RuntimeTypeHandle.FromIntPtr(intPtrToTypeHandle));

public static nint TypeHandleIntPtr(this object obj)
=> obj.GetType().TypeHandleIntPtr();

public static nint TypeHandleIntPtr(this Type type)
=> RuntimeTypeHandle.ToIntPtr(type.TypeHandle);

public static T UnsafeAs<T>(this nint intPtr)
Copy link
Member

Choose a reason for hiding this comment

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

Nit, the extension below is clearly to convert an object to an IntPtr/nint representation in the embedding API. I'm not sure of the best way of organizing it, but we want to make sure we keep all object<->nint and nint<->object conversions in one place (and only use methods for that) because at some point that will switch from just an unsafe cast to allocating/retrieving GC Handles.

Copy link
Member

Choose a reason for hiding this comment

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

Basically, any objects (reference types) being passes as parameters or as a return value on the embedding interface need special handling.

Copy link
Collaborator Author

Choose a reason for hiding this comment

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

Are you suggesting I rename / refactor the methods to be more like

ToNativeRepresentation
FromNativeRepresentation

?

Copy link
Member

Choose a reason for hiding this comment

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

That's my initial thought. I don't think it's required, just want to ensure we keep those specific operations isolated to we can change them easily without having to re-audit all the code.

=> Unsafe.As<nint, T>(ref intPtr);

public static nint UnsafeAsIntPtr(this object obj)
=> obj.UnsafeAs<nint>();

public static T UnsafeAs<T>(this object obj)
=> Unsafe.As<object, T>(ref obj);

public static GCHandle ToGCHandle(this nint intPtr)
=> GCHandle.FromIntPtr(intPtr);
}