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

[Java.Interop] Allow JniRuntime init from JavaVM* and JNIEnv* #1158

Merged
merged 2 commits into from
Nov 9, 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
31 changes: 28 additions & 3 deletions src/Java.Interop/Java.Interop/JniRuntime.cs
Original file line number Diff line number Diff line change
Expand Up @@ -165,8 +165,8 @@ protected JniRuntime (CreationOptions options)
{
if (options == null)
throw new ArgumentNullException (nameof (options));
if (options.InvocationPointer == IntPtr.Zero)
throw new ArgumentException ("options.InvocationPointer is null", nameof (options));
if (options.InvocationPointer == IntPtr.Zero && options.EnvironmentPointer == IntPtr.Zero)
throw new ArgumentException ("Need either options.InvocationPointer or options.EnvironmentPointer!", nameof (options));

TrackIDs = options.TrackIDs;
DestroyRuntimeOnDispose = options.DestroyRuntimeOnDispose;
Expand All @@ -175,7 +175,12 @@ protected JniRuntime (CreationOptions options)
NewObjectRequired = options.NewObjectRequired;

JniVersion = options.JniVersion;
InvocationPointer = options.InvocationPointer;

if (options.InvocationPointer == IntPtr.Zero && options.EnvironmentPointer != IntPtr.Zero) {
InvocationPointer = GetInvocationPointerFromEnvironmentPointer (options.EnvironmentPointer);
} else {
InvocationPointer = options.InvocationPointer;
}
Invoker = CreateInvoker (InvocationPointer);

SetValueManager (options);
Expand Down Expand Up @@ -230,6 +235,26 @@ protected JniRuntime (CreationOptions options)
#endif // !XA_JI_EXCLUDE
}

static unsafe IntPtr GetInvocationPointerFromEnvironmentPointer (IntPtr envp)
{
IntPtr vm = IntPtr.Zero;
#if FEATURE_JNIENVIRONMENT_JI_FUNCTION_POINTERS
if (JniNativeMethods.GetJavaVM (envp, &vm) is int r &&
r != JNI_OK) {
throw new InvalidOperationException ($"Could not obtain JavaVM* from JNIEnv*; JNIEnv::GetJavaVM() returned {r}!");
}
#elif FEATURE_JNIENVIRONMENT_JI_PINVOKES
if (NativeMethods.java_interop_jnienv_get_java_vm (envp, out vm) is int r &&
r != JNI_OK) {
throw new InvalidOperationException ($"Could not obtain JavaVM* from JNIEnv*; JNIEnv::GetJavaVM() returned {r}!");
}
#else // !FEATURE_JNIENVIRONMENT_JI_FUNCTION_POINTERS && !FEATURE_JNIENVIRONMENT_JI_PINVOKES
throw new NotSupportedException ("Cannot obtain JavaVM* from JNIEnv*! " +
"Rebuild with FEATURE_JNIENVIRONMENT_JI_FUNCTION_POINTERS or FEATURE_JNIENVIRONMENT_JI_PINVOKES set!");
#endif // !FEATURE_JNIENVIRONMENT_JI_FUNCTION_POINTERS && !FEATURE_JNIENVIRONMENT_JI_PINVOKES
return vm;
}

T SetRuntime<T> (T value)
where T : class, ISetRuntime
{
Expand Down
22 changes: 15 additions & 7 deletions src/Java.Runtime.Environment/Java.Interop/JreRuntime.cs
Original file line number Diff line number Diff line change
Expand Up @@ -39,11 +39,7 @@ public class JreRuntimeOptions : JniRuntime.CreationOptions {
public JreRuntimeOptions ()
{
JniVersion = JniVersion.v1_2;
ClassPath = new Collection<string> () {
Path.Combine (
Path.GetDirectoryName (typeof (JreRuntimeOptions).Assembly.Location) ?? throw new NotSupportedException (),
"java-interop.jar"),
};
ClassPath = new Collection<string> ();
Copy link
Member

Choose a reason for hiding this comment

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

What is Collection<string>? I've never heard of this? It would be an API break to change it, so probably can't be a List<string>.

Copy link
Member Author

Choose a reason for hiding this comment

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

Collection<T>. It's existed since .NET Framework 2.0, and is the recommended collection type in the .NET Framework Design Guidelines:

✔️ DO use Collection or a subclass of Collection<T> for properties or return values representing read/write collections.

This isn't an API break because the type hasn't changed at all, and -- again -- Collection<T> is in fact the preferred collection type here.

Copy link
Member

Choose a reason for hiding this comment

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

TIL, List vs Collection: https://stackoverflow.com/a/271842

Copy link
Member Author

Choose a reason for hiding this comment

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

Additionally, we've never "shipped" Java.Runtime.Environment.dll, so I'm fine witih making API breaks here if warranted.

}

public JreRuntimeOptions AddOption (string option)
Expand Down Expand Up @@ -80,7 +76,9 @@ static unsafe JreRuntimeOptions CreateJreVM (JreRuntimeOptions builder)
{
if (builder == null)
throw new ArgumentNullException ("builder");
if (string.IsNullOrEmpty (builder.JvmLibraryPath))
if (builder.InvocationPointer == IntPtr.Zero &&
builder.EnvironmentPointer == IntPtr.Zero &&
string.IsNullOrEmpty (builder.JvmLibraryPath))
throw new InvalidOperationException ($"Member `{nameof (JreRuntimeOptions)}.{nameof (JreRuntimeOptions.JvmLibraryPath)}` must be set.");

builder.LibraryHandler = JvmLibraryHandler.Create ();
Expand All @@ -99,11 +97,21 @@ static unsafe JreRuntimeOptions CreateJreVM (JreRuntimeOptions builder)
builder.ObjectReferenceManager = builder.ObjectReferenceManager ?? new ManagedObjectReferenceManager (builder.JniGlobalReferenceLogWriter, builder.JniLocalReferenceLogWriter);
}

if (builder.InvocationPointer != IntPtr.Zero)
if (builder.InvocationPointer != IntPtr.Zero || builder.EnvironmentPointer != IntPtr.Zero)
return builder;

builder.LibraryHandler.LoadJvmLibrary (builder.JvmLibraryPath!);

if (!builder.ClassPath.Any (p => p.EndsWith ("java-interop.jar", StringComparison.OrdinalIgnoreCase))) {
var loc = typeof (JreRuntimeOptions).Assembly.Location;
var dir = string.IsNullOrEmpty (loc) ? null : Path.GetDirectoryName (loc);
var jij = string.IsNullOrEmpty (dir) ? null : Path.Combine (dir, "java-interop.jar");
if (!File.Exists (jij)) {
throw new FileNotFoundException ($"`java-interop.jar` is required. Please add to `JreRuntimeOptions.ClassPath`. Tried to find it in `{jij}`.");
}
builder.ClassPath.Add (jij);
}

var args = new JavaVMInitArgs () {
version = builder.JniVersion,
nOptions = builder.Options.Count + 1,
Expand Down
19 changes: 19 additions & 0 deletions tests/Java.Interop-Tests/Java.Interop/JniRuntimeTest.cs
Original file line number Diff line number Diff line change
Expand Up @@ -36,6 +36,25 @@ public void JDK_OnlySupportsOneVM ()
Assert.Fail ("Expected NotSupportedException; got: {0}", e);
}
}

[Test]
public void UseInvocationPointerOnNewThread ()
Comment on lines +40 to +41
Copy link
Member

Choose a reason for hiding this comment

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

This file is old, but could we start adding new tests with the pattern:

public async Task UseInvocationPointerOnNewThread ()
{
    await Task.Run(() => ...);
}

Copy link
Member Author

Choose a reason for hiding this comment

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

@jonathanpeppers: what's the benefit to using the Task-based version? Other than ability to use async/await?

Copy link
Member

Choose a reason for hiding this comment

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

I cringe when I see Thread.Join() that is the only reason, lol.

{
var InvocationPointer = JniRuntime.CurrentRuntime.InvocationPointer;

var t = new Thread (() => {
try {
var second = new JreRuntimeOptions () {
InvocationPointer = InvocationPointer,
}.CreateJreVM ();
}
catch (Exception e) {
Assert.Fail ("Expected no exception, got: {0}", e);
}
});
t.Start ();
t.Join ();
}
#endif // !__ANDROID__

[Test]
Expand Down