Implement `SkymetalBridge` with basic support for symbol lookups and downcall handles. A plain `Linker#downcallHandle` is invisible in a stack trace when invoked. Our version wraps the handle in a non-hidden `com.google.devtools.build.lib.skymetal.Downcall$<id>.<symbol>(FFM downcall)` trampoline to make it visible. PiperOrigin-RevId: 1029304076 Change-Id: Ie6d496db31f2fdaa3e354f6c1f1d1c6096d07638
diff --git a/src/main/java/com/google/devtools/build/lib/skymetal/BUILD b/src/main/java/com/google/devtools/build/lib/skymetal/BUILD index 80a3684..febabc0 100644 --- a/src/main/java/com/google/devtools/build/lib/skymetal/BUILD +++ b/src/main/java/com/google/devtools/build/lib/skymetal/BUILD
@@ -12,6 +12,16 @@ ) java_library( + name = "skymetal_bridge", + srcs = ["SkymetalBridge.java"], + deps = [ + "//src/main/java/com/google/devtools/build/lib/jni", + "//third_party/java/error_prone:annotations", + "//third_party/java/guava:base", + ], +) + +java_library( name = "skymetal_feature", srcs = ["SkymetalFeature.java"], deps = ["//third_party/java/flogger"],
diff --git a/src/main/java/com/google/devtools/build/lib/skymetal/SkymetalBridge.java b/src/main/java/com/google/devtools/build/lib/skymetal/SkymetalBridge.java new file mode 100644 index 0000000..2b80ab6 --- /dev/null +++ b/src/main/java/com/google/devtools/build/lib/skymetal/SkymetalBridge.java
@@ -0,0 +1,166 @@ +// Copyright 2026 The Bazel Authors. All rights reserved. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +package com.google.devtools.build.lib.skymetal; + +import static com.google.common.base.Preconditions.checkNotNull; +import static java.lang.classfile.ClassFile.ACC_FINAL; +import static java.lang.classfile.ClassFile.ACC_PUBLIC; +import static java.lang.classfile.ClassFile.ACC_STATIC; +import static java.lang.classfile.ClassFile.ACC_SUPER; + +import com.google.devtools.build.lib.jni.JniLoader; +import com.google.errorprone.annotations.CompileTimeConstant; +import java.lang.classfile.ClassFile; +import java.lang.classfile.TypeKind; +import java.lang.classfile.attribute.SourceFileAttribute; +import java.lang.constant.ClassDesc; +import java.lang.constant.ConstantDescs; +import java.lang.constant.MethodTypeDesc; +import java.lang.foreign.FunctionDescriptor; +import java.lang.foreign.Linker; +import java.lang.foreign.MemorySegment; +import java.lang.foreign.SymbolLookup; +import java.lang.invoke.MethodHandle; +import java.lang.invoke.MethodHandles; +import java.lang.invoke.MethodType; +import java.util.concurrent.atomic.AtomicInteger; + +/** + * Foreign Function and Memory (FFM) facilities for Skymetal. + * + * <p>Facilities in this class should be used in preference to the bare {@link Linker} and {@link + * SymbolLookup} APIs to interact with Skymetal. + */ +public final class SkymetalBridge { + private static final String DOWNCALL_CLASS_PREFIX = + "com.google.devtools.build.lib.skymetal.Downcall$"; + private static final String DOWNCALL_SOURCE_FILE = "FFM downcall"; + + private static final Linker NATIVE_LINKER = Linker.nativeLinker(); + private static final SymbolLookup SYMBOL_LOOKUP = createLookup(); + private static final MethodHandles.Lookup LOOKUP = MethodHandles.lookup(); + private static final ClassFile CLASS_FILE = ClassFile.of(); + private static final AtomicInteger NEXT_CLASS_ID = new AtomicInteger(); + + /** Returns a {@link SymbolLookup} for symbols in the server's native library. */ + public static SymbolLookup symbolLookup() { + return SYMBOL_LOOKUP; + } + + /** + * Resolves {@code name} in the server's native library and returns a downcall method handle for + * it. + * + * <p>Unlike a regular downcall handle created by {@link Linker#downcallHandle}, which is + * invisible in a Java stack trace, the returned handle will, upon invocation, add a stack frame + * with the name of the native method being called. + * + * <p>Each call defines a new class that remains loaded for the lifetime of this classloader. + * Callers should store the returned handle in a {@code static final} field rather than calling + * this method repeatedly, which both avoids unbounded metaspace growth and enables JIT inlining. + * + * @throws UnsatisfiedLinkError if {@code name} cannot be found + * @throws IllegalArgumentException if {@code name} is not a valid Java method name or if {@link + * Linker#downcallHandle} rejects the arguments + */ + public static MethodHandle downcallHandle( + @CompileTimeConstant String name, FunctionDescriptor function, Linker.Option... options) { + validateMethodName(name); + MemorySegment address = + SYMBOL_LOOKUP + .find(name) + .orElseThrow(() -> new UnsatisfiedLinkError("undefined symbol: " + name)); + MethodHandle raw = NATIVE_LINKER.downcallHandle(address, function, options); + return wrapInStackFrame(name, raw); + } + + private static SymbolLookup createLookup() { + JniLoader.loadJni(); + SymbolLookup lookup = SymbolLookup.loaderLookup(); + return lookup; + } + + private static void validateMethodName(String name) { + checkNotNull(name, "name"); + if (name.isEmpty() + || !Character.isJavaIdentifierStart(name.codePointAt(0)) + || !name.codePoints().skip(1).allMatch(Character::isJavaIdentifierPart)) { + throw new IllegalArgumentException("Invalid Java method name: " + name); + } + } + + /** + * Wraps {@code target} in a dynamically generated trampoline method named {@code methodName} so + * invocations appear on Java stack traces as {@code + * com.google.devtools.build.lib.skymetal.Downcall$<id>.<methodName>(FFM downcall)}. + * + * <p>Generates and loads a regular (non-hidden) class in this package with a single static method + * equivalent to: + * + * <pre>{@code + * final class Downcall$<id> { + * public static R <methodName>(MethodHandle target, A... args) throws Throwable { + * return (R) target.invokeExact(args...); + * } + * } + * }</pre> + * + * <p>The class is defined via {@link MethodHandles.Lookup#defineClass} (rather than a hidden + * class) so its frame is retained in stack traces and thread dumps, with a unique numeric suffix + * so multiple handles for the same symbol name do not collide. Passing {@code target} as a + * leading parameter bound via {@link MethodHandles#insertArguments} avoids static fields while + * still allowing the JIT to constant-fold {@code target} and inline through the trampoline. + */ + private static MethodHandle wrapInStackFrame( + @CompileTimeConstant String methodName, MethodHandle target) { + MethodType targetType = target.type(); + MethodType trampolineType = targetType.insertParameterTypes(0, MethodHandle.class); + String className = DOWNCALL_CLASS_PREFIX + NEXT_CLASS_ID.incrementAndGet(); + ClassDesc classDesc = ClassDesc.of(className); + MethodTypeDesc trampolineDesc = MethodTypeDesc.ofDescriptor(trampolineType.descriptorString()); + MethodTypeDesc invokeExactDesc = MethodTypeDesc.ofDescriptor(targetType.descriptorString()); + + byte[] classBytes = + CLASS_FILE.build( + classDesc, + clb -> + clb.withFlags(ACC_FINAL | ACC_SUPER) + .with(SourceFileAttribute.of(DOWNCALL_SOURCE_FILE)) + .withMethodBody( + methodName, + trampolineDesc, + ACC_PUBLIC | ACC_STATIC, + cob -> { + for (int i = 0; i < trampolineType.parameterCount(); i++) { + cob.loadLocal( + TypeKind.from(trampolineType.parameterType(i)), + cob.parameterSlot(i)); + } + cob.invokevirtual( + ConstantDescs.CD_MethodHandle, "invokeExact", invokeExactDesc) + .return_(TypeKind.from(targetType.returnType())); + })); + + try { + Class<?> defined = LOOKUP.defineClass(classBytes); + MethodHandle trampoline = LOOKUP.findStatic(defined, methodName, trampolineType); + return MethodHandles.insertArguments(trampoline, 0, target); + } catch (ReflectiveOperationException e) { + throw new IllegalStateException("Failed to link downcall trampoline for " + methodName, e); + } + } + + private SkymetalBridge() {} +}
diff --git a/src/test/java/com/google/devtools/build/lib/skymetal/BUILD b/src/test/java/com/google/devtools/build/lib/skymetal/BUILD index 74bce3c..71c2015 100644 --- a/src/test/java/com/google/devtools/build/lib/skymetal/BUILD +++ b/src/test/java/com/google/devtools/build/lib/skymetal/BUILD
@@ -1,4 +1,6 @@ +load("@rules_cc//cc:cc_binary.bzl", "cc_binary") load("@rules_java//java:defs.bzl", "java_test") +load("@rules_rust//rust:defs.bzl", "rust_library") package( default_applicable_licenses = ["//:license"], @@ -13,6 +15,54 @@ visibility = ["//src/test/java/com/google/devtools/build/lib:__pkg__"], ) +rust_library( + name = "native_test_lib_rs", + srcs = ["native_test_lib.rs"], + alwayslink = True, +) + +cc_binary( + name = "native_test_lib", + linkopts = select({ + # Rust libstd system libraries (omitted by rules_rs on Windows MSVC). + "@rules_cc//cc/compiler:msvc-cl": [ + "ntdll.lib", + "synchronization.lib", + ], + "@rules_cc//cc/compiler:clang-cl": [ + "ntdll.lib", + "synchronization.lib", + ], + "@platforms//os:linux": [ + "-ldl", + "-lpthread", + ], + "//conditions:default": [], + }), + linkshared = True, + win_def_file = "native_test_lib.def", + deps = [ + ":native_test_lib_rs", + ], +) + +java_test( + name = "SkymetalBridgeTest", + srcs = ["SkymetalBridgeTest.java"], + data = [":native_test_lib"], + jvm_flags = [ + "--enable-native-access=ALL-UNNAMED", + "-Dnative.test.lib=$(rlocationpath :native_test_lib)", + ], + test_class = "com.google.devtools.build.lib.skymetal.SkymetalBridgeTest", + deps = [ + "//src/main/java/com/google/devtools/build/lib/skymetal:skymetal_bridge", + "//third_party/java/junit", + "//third_party/java/truth", + "@rules_java//java/runfiles", + ], +) + java_test( name = "SkymetalFeatureTest", timeout = "short",
diff --git a/src/test/java/com/google/devtools/build/lib/skymetal/SkymetalBridgeTest.java b/src/test/java/com/google/devtools/build/lib/skymetal/SkymetalBridgeTest.java new file mode 100644 index 0000000..ecda4bd --- /dev/null +++ b/src/test/java/com/google/devtools/build/lib/skymetal/SkymetalBridgeTest.java
@@ -0,0 +1,126 @@ +// Copyright 2026 The Bazel Authors. All rights reserved. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +package com.google.devtools.build.lib.skymetal; + +import static com.google.common.truth.Truth.assertThat; +import static java.lang.foreign.ValueLayout.ADDRESS; +import static java.lang.foreign.ValueLayout.JAVA_DOUBLE; +import static java.lang.foreign.ValueLayout.JAVA_INT; +import static java.lang.foreign.ValueLayout.JAVA_LONG; +import static org.junit.Assert.assertThrows; + +import com.google.devtools.build.runfiles.Runfiles; +import java.io.IOException; +import java.lang.foreign.Arena; +import java.lang.foreign.FunctionDescriptor; +import java.lang.foreign.Linker; +import java.lang.foreign.MemorySegment; +import java.lang.invoke.MethodHandle; +import java.lang.invoke.MethodHandles; +import java.lang.invoke.MethodType; +import java.nio.file.Path; +import java.util.concurrent.atomic.AtomicReference; +import org.junit.BeforeClass; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.junit.runners.JUnit4; + +@RunWith(JUnit4.class) +public final class SkymetalBridgeTest { + @BeforeClass + public static void loadNativeLibrary() throws IOException { + String libPath = Runfiles.preload().unmapped().rlocation(System.getProperty("native.test.lib")); + System.load(Path.of(libPath).toAbsolutePath().toString()); + } + + @Test + public void downcallHandle_appearsInStackTrace() throws Throwable { + MethodHandle invokeCallback = + SkymetalBridge.downcallHandle( + "bazel_test_invoke_callback", FunctionDescriptor.ofVoid(ADDRESS)); + AtomicReference<StackTraceElement[]> captured = new AtomicReference<>(); + + try (Arena arena = Arena.ofConfined()) { + MethodHandle callback = + MethodHandles.lookup() + .bind( + (Runnable) () -> captured.set(new Exception().getStackTrace()), + "run", + MethodType.methodType(void.class)); + MemorySegment stub = + Linker.nativeLinker().upcallStub(callback, FunctionDescriptor.ofVoid(), arena); + invokeCallback.invokeExact(stub); + } + + StackTraceElement[] trace = captured.get(); + assertThat(trace.length).isAtLeast(3); + + assertThat(trace[0].getClassName()).isEqualTo(SkymetalBridgeTest.class.getName()); + + assertThat(trace[1].getClassName()) + .startsWith("com.google.devtools.build.lib.skymetal.Downcall$"); + assertThat(trace[1].getMethodName()).isEqualTo("bazel_test_invoke_callback"); + assertThat(trace[1].getFileName()).isEqualTo("FFM downcall"); + assertThat(trace[1].getLineNumber()).isEqualTo(-1); + assertThat(trace[1].isNativeMethod()).isFalse(); + assertThat(trace[1].toString()) + .matches( + "com\\.google\\.devtools\\.build\\.lib\\.skymetal\\.Downcall\\$\\d+" + + "\\.bazel_test_invoke_callback\\(FFM downcall\\)"); + + assertThat(trace[2].getClassName()).isEqualTo(SkymetalBridgeTest.class.getName()); + assertThat(trace[2].getMethodName()).isEqualTo("downcallHandle_appearsInStackTrace"); + } + + @Test + public void downcallHandle_mixedTypesAndOptions() throws Throwable { + // critical(true) is required to pass a heap-backed MemorySegment, verifying option forwarding. + MethodHandle mixedTypes = + SkymetalBridge.downcallHandle( + "bazel_test_mixed_types", + FunctionDescriptor.of(JAVA_LONG, JAVA_INT, JAVA_LONG, JAVA_DOUBLE, ADDRESS), + Linker.Option.critical(/* allowHeapAccess= */ true)); + + long sum = (long) mixedTypes.invokeExact(1, 2L, 3.0d, MemorySegment.ofArray(new int[] {40})); + assertThat(sum).isEqualTo(46L); + } + + @Test + public void downcallHandle_duplicateSymbolNames_doNotCollide() throws Throwable { + FunctionDescriptor desc = + FunctionDescriptor.of(JAVA_LONG, JAVA_INT, JAVA_LONG, JAVA_DOUBLE, ADDRESS); + Linker.Option critical = Linker.Option.critical(/* allowHeapAccess= */ true); + MethodHandle first = SkymetalBridge.downcallHandle("bazel_test_mixed_types", desc, critical); + MethodHandle second = SkymetalBridge.downcallHandle("bazel_test_mixed_types", desc, critical); + + MemorySegment cell = MemorySegment.ofArray(new int[] {40}); + assertThat((long) first.invokeExact(1, 2L, 3.0d, cell)).isEqualTo(46L); + assertThat((long) second.invokeExact(10, 20L, 30.0d, cell)).isEqualTo(100L); + } + + @Test + public void downcallHandle_invalidInputs_throwExpectedExceptions() { + FunctionDescriptor desc = FunctionDescriptor.ofVoid(); + + assertThrows(NullPointerException.class, () -> SkymetalBridge.downcallHandle(null, desc)); + assertThrows(IllegalArgumentException.class, () -> SkymetalBridge.downcallHandle("", desc)); + assertThrows( + IllegalArgumentException.class, () -> SkymetalBridge.downcallHandle("123bad", desc)); + assertThrows(IllegalArgumentException.class, () -> SkymetalBridge.downcallHandle("a.b", desc)); + assertThrows( + UnsatisfiedLinkError.class, + () -> SkymetalBridge.downcallHandle("bazel_test_nonexistent_symbol", desc)); + } +}
diff --git a/src/test/java/com/google/devtools/build/lib/skymetal/native_test_lib.def b/src/test/java/com/google/devtools/build/lib/skymetal/native_test_lib.def new file mode 100644 index 0000000..d484d8c --- /dev/null +++ b/src/test/java/com/google/devtools/build/lib/skymetal/native_test_lib.def
@@ -0,0 +1,3 @@ +EXPORTS + bazel_test_invoke_callback + bazel_test_mixed_types
diff --git a/src/test/java/com/google/devtools/build/lib/skymetal/native_test_lib.rs b/src/test/java/com/google/devtools/build/lib/skymetal/native_test_lib.rs new file mode 100644 index 0000000..3ae387c --- /dev/null +++ b/src/test/java/com/google/devtools/build/lib/skymetal/native_test_lib.rs
@@ -0,0 +1,31 @@ +// Copyright 2026 The Bazel Authors. All rights reserved. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +//! Native C-ABI test helpers for `SkymetalBridgeTest`. + +/// Invokes the C-ABI callback `cb`. +// SAFETY: `bazel_test_invoke_callback` is unique in the linked test shared library and no other +// object defines a symbol with this name. +#[unsafe(no_mangle)] +pub extern "C" fn bazel_test_invoke_callback(cb: extern "C" fn()) { + cb(); +} + +/// Sums arguments of mixed primitive and pointer types. +// SAFETY: `bazel_test_mixed_types` is unique in the linked test shared library and no other +// object defines a symbol with this name. +#[unsafe(no_mangle)] +pub extern "C" fn bazel_test_mixed_types(i: i32, j: i64, d: f64, p: &i32) -> i64 { + i64::from(i) + j + (d as i64) + i64::from(*p) +}