Skip to content

Commit

Permalink
[GR-46386] Throw missing registration errors for JNI calls
Browse files Browse the repository at this point in the history
PullRequest: graal/17755
  • Loading branch information
loicottet committed Jun 6, 2024
2 parents 3446ce5 + 5d7f240 commit d9445f8
Show file tree
Hide file tree
Showing 19 changed files with 639 additions and 132 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -42,30 +42,50 @@ private SignatureUtil() {
* @return the parsed return type descriptor
*/
public static String parseSignature(String signature, List<String> parameters) {
if (signature.length() == 0) {
throw new IllegalArgumentException("Signature cannot be empty");
return parseSignatureInternal(signature, parameters, true, false);
}

/*
* If throwOnInvalidFormat is not set, returns null if signature parsing failed.
*/
private static String parseSignatureInternal(String signature, List<String> parameters, boolean throwOnInvalidFormat, boolean acceptMissingReturnType) {
if (signature.isEmpty()) {
return throwOrReturn(throwOnInvalidFormat, null, "Signature cannot be empty");
}
if (signature.charAt(0) == '(') {
int cur = 1;
while (cur < signature.length() && signature.charAt(cur) != ')') {
int nextCur = parseSignature(signature, cur);
parameters.add(signature.substring(cur, nextCur));
int nextCur = parseParameterSignature(signature, cur, throwOnInvalidFormat);
if (nextCur == -1) {
assert !throwOnInvalidFormat : "parseParameterSignature can only return -1 if throwOnInvalidFormat is not set";
return null;
}
if (parameters != null) {
parameters.add(signature.substring(cur, nextCur));
}
cur = nextCur;
}

cur++;
int nextCur = parseSignature(signature, cur);
if (acceptMissingReturnType && cur == signature.length()) {
return "";
}
int nextCur = parseParameterSignature(signature, cur, throwOnInvalidFormat);
if (nextCur == -1) {
assert !throwOnInvalidFormat : "parseParameterSignature can only return -1 if throwOnInvalidFormat is not set";
return null;
}
String returnType = signature.substring(cur, nextCur);
if (nextCur != signature.length()) {
throw new IllegalArgumentException("Extra characters at end of signature: " + signature);
return throwOrReturn(throwOnInvalidFormat, null, "Extra characters at end of signature: " + signature);
}
return returnType;
} else {
throw new IllegalArgumentException("Signature must start with a '(': " + signature);
return throwOrReturn(throwOnInvalidFormat, null, "Signature must start with a '(': " + signature);
}
}

private static int parseSignature(String signature, int start) {
private static int parseParameterSignature(String signature, int start, boolean throwOnInvalidFormat) {
try {
int cur = start;
char first;
Expand All @@ -78,7 +98,7 @@ private static int parseSignature(String signature, int start) {
case 'L':
while (signature.charAt(cur) != ';') {
if (signature.charAt(cur) == '.') {
throw new IllegalArgumentException("Class name in signature contains '.' at index " + cur + ": " + signature);
return throwOrReturn(throwOnInvalidFormat, -1, "Class name in signature contains '.' at index " + cur + ": " + signature);
}
cur++;
}
Expand All @@ -95,11 +115,32 @@ private static int parseSignature(String signature, int start) {
case 'Z':
break;
default:
throw new IllegalArgumentException("Invalid character '" + signature.charAt(cur - 1) + "' at index " + (cur - 1) + " in signature: " + signature);
return throwOrReturn(throwOnInvalidFormat, -1, "Invalid character '" + signature.charAt(cur - 1) + "' at index " + (cur - 1) + " in signature: " + signature);
}
return cur;
} catch (StringIndexOutOfBoundsException e) {
throw new IllegalArgumentException("Truncated signature: " + signature);
return throwOrReturn(throwOnInvalidFormat, -1, "Truncated signature: " + signature);
}
}

/**
* Checks if the given signature can be succesfully parsed by
* {@link #parseSignature(String, List)}.
*
* @param signature the signature to check
* @param acceptMissingReturnType whether a signature without a return type is considered to be
* valid
* @return whether the signature can be successfully parsed
*/
public static boolean isSignatureValid(String signature, boolean acceptMissingReturnType) {
return parseSignatureInternal(signature, null, false, acceptMissingReturnType) != null;
}

private static <T> T throwOrReturn(boolean shouldThrow, T returnValue, String errorMessage) {
if (shouldThrow) {
throw new IllegalArgumentException(errorMessage);
} else {
return returnValue;
}
}
}
9 changes: 9 additions & 0 deletions sdk/src/org.graalvm.nativeimage/snapshot.sigtest
Original file line number Diff line number Diff line change
Expand Up @@ -233,6 +233,15 @@ meth public java.lang.String getElementName()
supr java.lang.Error
hfds declaringClass,elementName,elementType,parameterTypes,serialVersionUID

CLSS public final org.graalvm.nativeimage.MissingJNIRegistrationError
cons public init(java.lang.String,java.lang.Class<?>,java.lang.Class<?>,java.lang.String,java.lang.String)
meth public java.lang.Class<?> getDeclaringClass()
meth public java.lang.Class<?> getElementType()
meth public java.lang.String getSignature()
meth public java.lang.String getElementName()
supr java.lang.Error
hfds declaringClass,elementName,elementType,signature,serialVersionUID

CLSS public abstract interface org.graalvm.nativeimage.ObjectHandle
intf org.graalvm.word.ComparableWord

Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,132 @@
/*
* Copyright (c) 2024, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* The Universal Permissive License (UPL), Version 1.0
*
* Subject to the condition set forth below, permission is hereby granted to any
* person obtaining a copy of this software, associated documentation and/or
* data (collectively the "Software"), free of charge and under any and all
* copyright rights in the Software, and any and all patent rights owned or
* freely licensable by each licensor hereunder covering either (i) the
* unmodified Software as contributed to or provided by such licensor, or (ii)
* the Larger Works (as defined below), to deal in both
*
* (a) the Software, and
*
* (b) any piece of software and/or hardware listed in the lrgrwrks.txt file if
* one is included with the Software each a "Larger Work" to which the Software
* is contributed by such licensors),
*
* without restriction, including without limitation the rights to copy, create
* derivative works of, display, perform, and distribute the Software and make,
* use, sell, offer for sale, import, export, have made, and have sold the
* Software and the Larger Work(s), and to sublicense the foregoing rights on
* either these or other terms.
*
* This license is subject to the following condition:
*
* The above copyright notice and either this complete permission notice or at a
* minimum a reference to the UPL must be included in all copies or substantial
* portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package org.graalvm.nativeimage;

import java.io.Serial;
import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.Method;

/**
* This exception is thrown when a JNI query tries to access an element that was not
* <a href= "https://www.graalvm.org/latest/reference-manual/native-image/metadata/#jni">registered
* for JNI access</a> in the program. When an element is not registered, the exception will be
* thrown both for elements that exist and elements that do not exist on the given classpath.
* <p/>
* The purpose of this exception is to easily discover unregistered elements and to assure that all
* JNI operations for registered elements have the expected behaviour.
* <p/>
* Queries will succeed (or throw the expected error) if the element was registered for JNI access.
* If that is not the case, a {@link MissingJNIRegistrationError} will be thrown.
* <p/>
* The exception thrown by the JNI query is a <em>pending</em> exception that needs to be explicitly
* checked by the calling native code.
* </ol>
* Examples:
* <p/>
* Registration: {@code "fields": [{"name": "registeredField"}, {"name":
* "registeredNonexistentField"}]}<br>
* {@code GetFieldID(declaringClass, "registeredField")} will return the expected field.<br>
* {@code GetFieldID(declaringClass, "registeredNonexistentField")} will throw a
* {@link NoSuchFieldError}.<br>
* {@code GetFieldID(declaringClass, "unregisteredField")} will throw a
* {@link MissingJNIRegistrationError}.<br>
* {@code GetFieldID(declaringClass, "unregisteredNonexistentField")} will throw a
* {@link MissingJNIRegistrationError}.<br>
*
* @since 24.1
*/
public final class MissingJNIRegistrationError extends Error {
@Serial private static final long serialVersionUID = -8940056537864516986L;

private final Class<?> elementType;

private final Class<?> declaringClass;

private final String elementName;

private final String signature;

/**
* @since 24.1
*/
public MissingJNIRegistrationError(String message, Class<?> elementType, Class<?> declaringClass, String elementName, String signature) {
super(message);
this.elementType = elementType;
this.declaringClass = declaringClass;
this.elementName = elementName;
this.signature = signature;
}

/**
* @return The type of the element trying to be queried ({@link Class}, {@link Method},
* {@link Field} or {@link Constructor}).
* @since 23.0
*/
public Class<?> getElementType() {
return elementType;
}

/**
* @return The class on which the missing query was tried, or null on static queries.
* @since 23.0
*/
public Class<?> getDeclaringClass() {
return declaringClass;
}

/**
* @return The name of the queried element.
* @since 23.0
*/
public String getElementName() {
return elementName;
}

/**
* @return The signature passed to the query, or null if the query doesn't take a signature as
* argument.
* @since 23.0
*/
public String getSignature() {
return signature;
}
}
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
/*
* Copyright (c) 2017, 2023, Oracle and/or its affiliates. All rights reserved.
* Copyright (c) 2017, 2024, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* The Universal Permissive License (UPL), Version 1.0
Expand Down Expand Up @@ -55,4 +55,11 @@ default void register(ConfigurationCondition condition, Class<?>... classes) {

void register(ConfigurationCondition condition, boolean finalIsWritable, Field... fields);

void registerClassLookup(ConfigurationCondition condition, String typeName);

void registerFieldLookup(ConfigurationCondition condition, Class<?> declaringClass, String fieldName);

void registerMethodLookup(ConfigurationCondition condition, Class<?> declaringClass, String methodName, Class<?>... parameterTypes);

void registerConstructorLookup(ConfigurationCondition condition, Class<?> declaringClass, Class<?>... parameterTypes);
}
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
/*
* Copyright (c) 2017, 2023, Oracle and/or its affiliates. All rights reserved.
* Copyright (c) 2017, 2024, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* The Universal Permissive License (UPL), Version 1.0
Expand Down Expand Up @@ -67,12 +67,4 @@ public interface RuntimeReflectionSupport extends ReflectionRegistry {
void registerAllSignersQuery(ConfigurationCondition condition, Class<?> clazz);

void registerClassLookupException(ConfigurationCondition condition, String typeName, Throwable t);

void registerClassLookup(ConfigurationCondition condition, String typeName);

void registerFieldLookup(ConfigurationCondition condition, Class<?> declaringClass, String fieldName);

void registerMethodLookup(ConfigurationCondition condition, Class<?> declaringClass, String methodName, Class<?>... parameterTypes);

void registerConstructorLookup(ConfigurationCondition condition, Class<?> declaringClass, Class<?>... parameterTypes);
}
1 change: 1 addition & 0 deletions substratevm/CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,7 @@ This changelog summarizes major changes to GraalVM Native Image.
* (GR-18214) In-place compacting garbage collection for the Serial GC old generation with `-H:+CompactingOldGen`.
* (GR-52844) Add `-Os`, a new optimization mode to configure the optimizer in a way to get the smallest code size.
* (GR-49770) Add support for glob patterns in resource-config files in addition to regexp. The Tracing agent now prints entries in the glob format.
* (GR-46386) Throw missing registration errors for JNI queries when the query was not included in the reachability metadata.

## GraalVM for JDK 22 (Internal Version 24.0.0)
* (GR-48304) Red Hat added support for the JFR event ThreadAllocationStatistics.
Expand Down
Loading

0 comments on commit d9445f8

Please sign in to comment.