Skip to content

Commit e31d9c6

Browse files
authored
`Java.Inteorp.JniEnvironment.Types.RegisterNatives()` is overloaded: namespace Java.Interop { partial class JniEnvironment { partial class Types { public static void RegisterNatives (JniObjectReference type, JniNativeMethodRegistration[] methods); public static void RegisterNatives (JniObjectReference type, JniNativeMethodRegistration[] methods, int numMethods); } } } If the `int numMethods` overload is used, then: 1. it should be possible to pass an array which contains *more* than `numMethods` elements, and 2. Passing such an array shouldn't throw an exception. For example: var methods = new JniNativeMethodRegistration [10]; JniEnvironment.Types.RegisterNatives (type, methods, 0); Instead, when using a Debug configuration build of `Java.Interop.dll`, a `NullReferenceException` would be thrown, because the `foreach` loop would traverse *every element*, not just the first `numMethods` elements, which could result in accessing `methods[i].Marshaler.GetType()`, which could be `null`. Fix the `DEBUG && NETCOREAPP` check so that only the first `numMethods` elements are accessed, *not* all of them, and add a `null` check around `JniNativeMethodRegistration.Marshaler` access. This prevents the `NullReferenceException`. Additionally, add some parameter validation and throw an `ArgumentOutOfRangeException` if `numMethods` is negative or is greater than `methods.Length`.
1 parent d3ea180 commit e31d9c6

File tree

1 file changed

+8
-2
lines changed

1 file changed

+8
-2
lines changed

src/Java.Interop/Java.Interop/JniEnvironment.Types.cs

Lines changed: 8 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -200,9 +200,15 @@ public static void RegisterNatives (JniObjectReference type, JniNativeMethodRegi
200200

201201
public static void RegisterNatives (JniObjectReference type, JniNativeMethodRegistration [] methods, int numMethods)
202202
{
203+
if ((numMethods < 0) ||
204+
(numMethods > (methods?.Length ?? 0))) {
205+
throw new ArgumentOutOfRangeException (nameof (numMethods), numMethods,
206+
$"`numMethods` must be between 0 and `methods.Length` ({methods?.Length ?? 0})!");
207+
}
203208
#if DEBUG && NETCOREAPP
204-
foreach (var m in methods) {
205-
if (m.Marshaler.GetType ().GenericTypeArguments.Length != 0) {
209+
for (int i = 0; methods != null && i < numMethods; ++i) {
210+
var m = methods [i];
211+
if (m.Marshaler != null && m.Marshaler.GetType ().GenericTypeArguments.Length != 0) {
206212
var method = m.Marshaler.Method;
207213
Debug.WriteLine ($"JNIEnv::RegisterNatives() given a generic delegate type `{m.Marshaler.GetType()}`. .NET Core doesn't like this.");
208214
Debug.WriteLine ($" Java: {m.Name}{m.Signature}");

0 commit comments

Comments
 (0)