Weird behaviour of Java MethodHandle.invokeExact
Asked Answered
C

1

7

Here is a minimal working example (requires Java 22 or later):

(just using libc free for elaborating the behaviour)

import java.lang.foreign.*;
import java.lang.invoke.MethodHandle;

public class Main {
    public static final Linker nativeLinker = Linker.nativeLinker();
    public static final SymbolLookup stdlibLookup = nativeLinker.defaultLookup();
    public static final SymbolLookup loaderLookup = SymbolLookup.loaderLookup();

    private static final FunctionDescriptor DESCRIPTOR$free = FunctionDescriptor.ofVoid(ValueLayout.ADDRESS);
    private static final MethodHandle HANDLE$free =
            loaderLookup.find("free")
                    .or(() -> stdlibLookup.find("free"))
                    .map(symbolSegment -> nativeLinker.downcallHandle(symbolSegment, DESCRIPTOR$free))
                    .orElseThrow(() -> new RuntimeException("libc function free not found but y?"));

    public static void free(MemorySegment address) {
        try {
            // I want to allow user code to use Java null and MemorySegment.NULL (C NULL) interchangeably
            HANDLE$free.invokeExact(address != null ? address : MemorySegment.NULL);
        } catch (Throwable throwable) {
            throwable.printStackTrace(System.err);
        }
    }

    public static void main(String[] args) {
        free(null); // free(MemorySegment.NULL) will produce same result
    }
}

Run program and there will be an exception:

java.lang.invoke.WrongMethodTypeException: handle's method type (MemorySegment)void but found (Object)void
    at java.base/java.lang.invoke.Invokers.newWrongMethodTypeException(Invokers.java:521)
    at java.base/java.lang.invoke.Invokers.checkExactType(Invokers.java:530)
    at Main.free(Main.java:19)
    at Main.main(Main.java:26)

Java complains that the argument used to call invokeExact is an Object, not MemorySegment. However, the expression

address != null ? address : MemorySegment.NULL

should have type MemorySegment of course. And if we make a small modification to the code:

    public static void free(MemorySegment address) {
        try {
            MemorySegment temp = address != null ? address : MemorySegment.NULL;
            HANDLE$free.invokeExact(temp);
        } catch (Throwable throwable) {
            throwable.printStackTrace(System.err);
        }
    }

it works correctly.

Also

  • HANDLE$free.invoke(address != null ? address : MemorySegment.NULL) works
  • HANDLE$free.invokeExact((MemorySegment)(address != null ? address : MemorySegment.NULL)) works, but
  • HANDLE$free.invokeExact((address != null ? address : MemorySegment.NULL)) does not work

Is this some kind of deliberate design, implementation limitation or JVM bugs?

Costly answered 25/9 at 5:32 Comment(0)
H
10

Note that since invokeExact is signature polymorphic, it is the compiler's job to determine the method type of the method you are trying to call, based on the argument expressions. It doesn't matter what type the expression evaluates to at runtime, if the compiler finds a non-matching method type.

Indeed, the type of the conditional expression (the ternary operator expression) is Object.

From JLS 15.25.3,

A reference conditional expression is a poly expression if it appears in an assignment context or an invocation context (§5.2. §5.3). Otherwise, it is a standalone expression.

...

The type of a poly reference conditional expression is the same as its target type.

In the case of

HANDLE$free.invokeExact(address != null ? address : MemorySegment.NULL);

The target type for the conditional operator is Object, as invokeExact is declared to take Object....

invoke is more permissive than invokeExact, so using invoke works.

In all the other cases you showed, the type of the argument expression can be easily shown to be MemorySegment, so they work too.

Husk answered 25/9 at 5:58 Comment(6)
It's odd that the result of the ternary operator is Object, when both the true and the false expressions are both of type MemorySegment. I can perfectly understand the confusion.Isocracy
There are not many places where using the target type does not do the desired thing for the target that provided the target type. In general, I’d avoid complex expressions in arguments to invokeExact. Otherwise, you’ll likely find more sources of surprise…Eng
I just wonder why in var temp = address != null ? address : MemorySegment.NULL) temp has the type MemorySegment.Caves
@JohannesKuhn when determine the inferred type of a var, the expression is treated as a standalone expression, not a poly expression. (14.4.1) The type of a standalone conditional expression is determined differently (see the rest of 15.25.3).Husk
But it appears in an assignment context, so it should be a poly expression, right?Caves
@JohannesKuhn No, this is a special case. When determining the type of var, the expression is treated as if it is not in an assignment context. See section 14.4.1.Husk

© 2022 - 2024 — McMap. All rights reserved.