Skip to content

Commit

Permalink
Support JDK serialization
Browse files Browse the repository at this point in the history
  • Loading branch information
ziyilin committed Aug 21, 2020
1 parent 717f601 commit 13c898b
Show file tree
Hide file tree
Showing 30 changed files with 1,005 additions and 47 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,7 @@

import static com.oracle.svm.core.util.VMError.guarantee;
import static com.oracle.svm.jni.JNIObjectHandles.nullHandle;
import static com.oracle.svm.jvmtiagentbase.Support.callObjectMethod;
import static com.oracle.svm.jvmtiagentbase.Support.check;
import static com.oracle.svm.jvmtiagentbase.Support.checkJni;
import static com.oracle.svm.jvmtiagentbase.Support.checkNoException;
Expand All @@ -37,11 +38,13 @@
import static com.oracle.svm.jvmtiagentbase.Support.getClassNameOr;
import static com.oracle.svm.jvmtiagentbase.Support.getClassNameOrNull;
import static com.oracle.svm.jvmtiagentbase.Support.getDirectCallerClass;
import static com.oracle.svm.jvmtiagentbase.Support.getObjectField;
import static com.oracle.svm.jvmtiagentbase.Support.getMethodDeclaringClass;
import static com.oracle.svm.jvmtiagentbase.Support.getObjectArgument;
import static com.oracle.svm.jvmtiagentbase.Support.jniFunctions;
import static com.oracle.svm.jvmtiagentbase.Support.jvmtiEnv;
import static com.oracle.svm.jvmtiagentbase.Support.jvmtiFunctions;
import static com.oracle.svm.jvmtiagentbase.Support.newObjectL;
import static com.oracle.svm.jvmtiagentbase.Support.testException;
import static com.oracle.svm.jvmtiagentbase.Support.toCString;
import static com.oracle.svm.jvmtiagentbase.jvmti.JvmtiEvent.JVMTI_EVENT_BREAKPOINT;
Expand Down Expand Up @@ -81,6 +84,7 @@
import com.oracle.svm.agent.restrict.ProxyAccessVerifier;
import com.oracle.svm.agent.restrict.ReflectAccessVerifier;
import com.oracle.svm.agent.restrict.ResourceAccessVerifier;
import com.oracle.svm.agent.restrict.SerializationAccessVerifier;
import com.oracle.svm.configure.config.ConfigurationMethod;
import com.oracle.svm.core.c.function.CEntryPointOptions;
import com.oracle.svm.core.util.VMError;
Expand Down Expand Up @@ -129,6 +133,7 @@ final class BreakpointInterceptor {
private static ReflectAccessVerifier accessVerifier;
private static ProxyAccessVerifier proxyVerifier;
private static ResourceAccessVerifier resourceVerifier;
private static SerializationAccessVerifier serializationAccessVerifier;
private static NativeImageAgent agent;

private static Map<Long, Breakpoint> installedBreakpoints;
Expand Down Expand Up @@ -162,6 +167,8 @@ final class BreakpointInterceptor {

private static final ThreadLocal<Boolean> recursive = ThreadLocal.withInitial(() -> Boolean.FALSE);

private static final String[] EMPTY_STRING_ARRAY = new String[0];

private static void traceBreakpoint(JNIEnvironment env, JNIObjectHandle clazz, JNIObjectHandle declaringClass, JNIObjectHandle callerClass, String function, Object result, Object... args) {
if (traceWriter != null) {
traceWriter.traceCall("reflect",
Expand Down Expand Up @@ -913,6 +920,69 @@ private static String asInternalSignature(Object paramTypesArray) {
return null;
}

private static boolean objectStreamClassConstructor(JNIEnvironment jni, Breakpoint bp) {
JNIObjectHandle callerClass = getDirectCallerClass();
JNIObjectHandle self = getObjectArgument(0);
JNIObjectHandle serializeTargetClass = getObjectArgument(1);
String serializeTargetClassName = getClassNameOrNull(jni, serializeTargetClass);
Object parameterTypeNames = EMPTY_STRING_ARRAY;
Object checkedExceptionNames = EMPTY_STRING_ARRAY;
int modifiers = 0;
String targetConstructorClassName = "";

JNIObjectHandle objectStreamClassInstance = newObjectL(jni, bp.clazz, bp.method, serializeTargetClass);
Object result = nullHandle().notEqual(objectStreamClassInstance);
if (clearException(jni)) {
result = false;
}
if (result.equals(true)) {
JNIObjectHandle cons = getObjectField(jni, bp.clazz, objectStreamClassInstance, "cons", "Ljava/lang/reflect/Constructor;");
if (nullHandle().notEqual(cons)) {
JNIObjectHandle constructorClazz = jniFunctions().getGetObjectClass().invoke(jni, cons);
try (CCharPointerHolder getDeclaringClassNameHolder = toCString("getDeclaringClass");
CCharPointerHolder getDeclaringClassSigHolder = toCString("()Ljava/lang/Class;");
CCharPointerHolder getParaTypesNameHolder = toCString("getParameterTypes");
CCharPointerHolder getCheckedExceptionNameHolder = toCString("getExceptionTypes");
CCharPointerHolder classArrayRetSigHolder = toCString("()[Ljava/lang/Class;");
CCharPointerHolder getModifiersNameHolder = toCString("getModifiers");
CCharPointerHolder getModifiersSigHolder = toCString("()I");) {
JNIMethodId getDeclaringClassMId = jniFunctions().getGetMethodID().invoke(jni, constructorClazz, getDeclaringClassNameHolder.get(), getDeclaringClassSigHolder.get());
targetConstructorClassName = getClassNameOrNull(jni, callObjectMethod(jni, cons, getDeclaringClassMId));

JNIMethodId getParameterTypesMid = jniFunctions().getGetMethodID().invoke(jni, constructorClazz, getParaTypesNameHolder.get(), classArrayRetSigHolder.get());
parameterTypeNames = getClassArrayNames(jni, callObjectMethod(jni, cons, getParameterTypesMid));

JNIMethodId getExceptionTypesMid = jniFunctions().getGetMethodID().invoke(jni, constructorClazz, getCheckedExceptionNameHolder.get(), classArrayRetSigHolder.get());
checkedExceptionNames = getClassArrayNames(jni, callObjectMethod(jni, cons, getExceptionTypesMid));

JNIMethodId getModifiersMid = jniFunctions().getGetMethodID().invoke(jni, constructorClazz, getModifiersNameHolder.get(), getModifiersSigHolder.get());
modifiers = jniFunctions().getCallIntMethod().invoke(jni, cons, getModifiersMid);
}
}
}

if (traceWriter != null) {
traceWriter.traceCall("serialization",
"ObjectStreamClass.<init>",
null,
null,
null,
result,
serializeTargetClassName, parameterTypeNames,
checkedExceptionNames, modifiers, targetConstructorClassName);
guarantee(!testException(jni));
}
boolean allowed = (serializationAccessVerifier == null || serializationAccessVerifier.verifyObjectStreamClassConstructor(jni, serializeTargetClassName, (String[]) parameterTypeNames,
(String[]) checkedExceptionNames, modifiers, targetConstructorClassName, self, callerClass));
if (!allowed) {
try (CCharPointerHolder message = toCString(
NativeImageAgent.MESSAGE_PREFIX + "configuration does not permit SerializationConstructorAccessor class for class: " + serializeTargetClassName)) {
jniFunctions().getThrowNew().invoke(jni, agent.handles().javaLangSecurityException, message.get());
}
}
return allowed;
}

@CEntryPoint
@CEntryPointOptions(prologue = AgentIsolate.Prologue.class)
private static void onBreakpoint(@SuppressWarnings("unused") JvmtiEnv jvmti, JNIEnvironment jni,
Expand Down Expand Up @@ -991,12 +1061,14 @@ private static void installBreakpointIfClassLoader(JNIEnvironment jni, JNIObject
JvmtiEnv.class, JNIEnvironment.class, JNIObjectHandle.class, JNIObjectHandle.class);

public static void onLoad(JvmtiEnv jvmti, JvmtiEventCallbacks callbacks, TraceWriter writer, ReflectAccessVerifier verifier,
ProxyAccessVerifier prverifier, ResourceAccessVerifier resverifier, NativeImageAgent nativeImageTracingAgent, boolean exptlClassLoaderSupport) {
ProxyAccessVerifier prverifier, ResourceAccessVerifier resverifier, SerializationAccessVerifier serializationAccessVerifier, NativeImageAgent nativeImageTracingAgent,
boolean exptlClassLoaderSupport) {

BreakpointInterceptor.traceWriter = writer;
BreakpointInterceptor.accessVerifier = verifier;
BreakpointInterceptor.proxyVerifier = prverifier;
BreakpointInterceptor.resourceVerifier = resverifier;
BreakpointInterceptor.serializationAccessVerifier = serializationAccessVerifier;
BreakpointInterceptor.agent = nativeImageTracingAgent;
BreakpointInterceptor.experimentalClassLoaderSupport = exptlClassLoaderSupport;

Expand Down Expand Up @@ -1218,6 +1290,7 @@ private interface BreakpointHandler {
brk("java/lang/reflect/Proxy", "newProxyInstance",
"(Ljava/lang/ClassLoader;[Ljava/lang/Class;Ljava/lang/reflect/InvocationHandler;)Ljava/lang/Object;", BreakpointInterceptor::newProxyInstance),

brk("java/io/ObjectStreamClass", "<init>", "(Ljava/lang/Class;)V", BreakpointInterceptor::objectStreamClassConstructor),
optionalBrk("java/util/ResourceBundle",
"getBundleImpl",
"(Ljava/lang/String;Ljava/util/Locale;Ljava/lang/ClassLoader;Ljava/util/ResourceBundle$Control;)Ljava/util/ResourceBundle;",
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -53,6 +53,7 @@
import java.util.function.Function;
import java.util.regex.Pattern;

import com.oracle.svm.agent.restrict.SerializationAccessVerifier;
import org.graalvm.compiler.options.OptionKey;
import org.graalvm.nativeimage.ProcessProperties;

Expand Down Expand Up @@ -92,6 +93,7 @@ public final class NativeImageAgent extends JvmtiAgentBase<NativeImageAgentJNIHa
private static final String oHReflectionConfigurationResources = oH(ConfigurationFiles.Options.ReflectionConfigurationResources);
private static final String oHDynamicProxyConfigurationResources = oH(ConfigurationFiles.Options.DynamicProxyConfigurationResources);
private static final String oHResourceConfigurationResources = oH(ConfigurationFiles.Options.ResourceConfigurationResources);
private static final String oHSerializationConfigurationResources = oH(ConfigurationFiles.Options.SerializationConfigurationResources);
private static final String oHConfigurationResourceRoots = oH(ConfigurationFiles.Options.ConfigurationResourceRoots);

private static <T> String oH(OptionKey<T> option) {
Expand Down Expand Up @@ -256,7 +258,7 @@ protected int onLoadCallback(JNIJavaVM vm, JvmtiEnv jvmti, JvmtiEventCallbacks c
// They should use the same filter sets, however.
AccessAdvisor advisor = createAccessAdvisor(builtinHeuristicFilter, callerFilter, accessFilter);
TraceProcessor processor = new TraceProcessor(advisor, mergeConfigs.loadJniConfig(handler), mergeConfigs.loadReflectConfig(handler),
mergeConfigs.loadProxyConfig(handler), mergeConfigs.loadResourceConfig(handler));
mergeConfigs.loadProxyConfig(handler), mergeConfigs.loadResourceConfig(handler), mergeConfigs.loadSerializationConfig(handler));
traceWriter = new TraceProcessorWriterAdapter(processor);
} catch (Throwable t) {
System.err.println(MESSAGE_PREFIX + t);
Expand Down Expand Up @@ -298,7 +300,11 @@ protected int onLoadCallback(JNIJavaVM vm, JvmtiEnv jvmti, JvmtiEventCallbacks c
if (!restrictConfigs.getResourceConfigPaths().isEmpty()) {
resourceVerifier = new ResourceAccessVerifier(restrictConfigs.loadResourceConfig(ConfigurationSet.FAIL_ON_EXCEPTION), accessAdvisor);
}
BreakpointInterceptor.onLoad(jvmti, callbacks, traceWriter, verifier, proxyVerifier, resourceVerifier, this, experimentalClassLoaderSupport);
SerializationAccessVerifier serializationAccessVerifier = null;
if (!restrictConfigs.getSerializationConfigPaths().isEmpty()) {
serializationAccessVerifier = new SerializationAccessVerifier(restrictConfigs.loadSerializationConfig(ConfigurationSet.FAIL_ON_EXCEPTION), accessAdvisor);
}
BreakpointInterceptor.onLoad(jvmti, callbacks, traceWriter, verifier, proxyVerifier, resourceVerifier, serializationAccessVerifier, this, experimentalClassLoaderSupport);
} catch (Throwable t) {
System.err.println(MESSAGE_PREFIX + t);
return 3;
Expand Down Expand Up @@ -439,12 +445,15 @@ private static boolean addRestrictConfigs(JvmtiEnv jvmti, ConfigurationSet restr
addURI.add(restrictConfigs.getProxyConfigPaths(), cpEntry, optionParts[1]);
} else if (oHResourceConfigurationResources.equals(argName)) {
addURI.add(restrictConfigs.getResourceConfigPaths(), cpEntry, optionParts[1]);
} else if (oHSerializationConfigurationResources.equals(argName)) {
addURI.add(restrictConfigs.getSerializationConfigPaths(), cpEntry, optionParts[1]);
} else if (oHConfigurationResourceRoots.equals(argName)) {
String resourceLocation = optionParts[1];
addURI.add(restrictConfigs.getJniConfigPaths(), cpEntry, resourceLocation + "/" + ConfigurationFiles.JNI_NAME);
addURI.add(restrictConfigs.getReflectConfigPaths(), cpEntry, resourceLocation + "/" + ConfigurationFiles.REFLECTION_NAME);
addURI.add(restrictConfigs.getProxyConfigPaths(), cpEntry, resourceLocation + "/" + ConfigurationFiles.DYNAMIC_PROXY_NAME);
addURI.add(restrictConfigs.getResourceConfigPaths(), cpEntry, resourceLocation + "/" + ConfigurationFiles.RESOURCES_NAME);
addURI.add(restrictConfigs.getSerializationConfigPaths(), cpEntry, resourceLocation + "/" + ConfigurationFiles.SERIALIZATION_NAME);
}
}
});
Expand Down Expand Up @@ -557,6 +566,7 @@ private void writeConfigurationFiles() {
allConfigFiles.put(ConfigurationFiles.JNI_NAME, p.getJniConfiguration());
allConfigFiles.put(ConfigurationFiles.DYNAMIC_PROXY_NAME, p.getProxyConfiguration());
allConfigFiles.put(ConfigurationFiles.RESOURCES_NAME, p.getResourceConfiguration());
allConfigFiles.put(ConfigurationFiles.SERIALIZATION_NAME, p.getSerializationConfiguration());

for (Map.Entry<String, JsonPrintable> configFile : allConfigFiles.entrySet()) {
Path tempPath = tempDirectory.resolve(configFile.getKey());
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,48 @@
/*
* Copyright (c) 2019, 2020, Oracle and/or its affiliates. All rights reserved.
* Copyright (c) 2020 Alibaba Group Holding Limited. All Rights Reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package com.oracle.svm.agent.restrict;

import com.oracle.svm.configure.config.SerializationConfiguration;
import com.oracle.svm.configure.trace.AccessAdvisor;
import com.oracle.svm.jni.nativeapi.JNIEnvironment;
import com.oracle.svm.jni.nativeapi.JNIObjectHandle;

public class SerializationAccessVerifier extends AbstractAccessVerifier {
private final SerializationConfiguration configuration;

public SerializationAccessVerifier(SerializationConfiguration configuration, AccessAdvisor advisor) {
super(advisor);
this.configuration = configuration;
}

public boolean verifyObjectStreamClassConstructor(JNIEnvironment env, String serializationTargetClass, String[] parameterTypes, String[] checkedExceptions,
int modifiers, String targetConstructorClass, JNIObjectHandle queriedClass, JNIObjectHandle callerClass) {
if (shouldApproveWithoutChecks(env, queriedClass, callerClass)) {
return true;
}
return configuration.contains(serializationTargetClass, parameterTypes, checkedExceptions, modifiers, targetConstructorClass);
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -189,6 +189,12 @@ private static void generate(Iterator<String> argsIter, boolean acceptTraceFileA
set.getResourceConfigPaths().add(requirePathUri(current, value));
break;

case "--serialization-input":
set = inputSet; // fall through
case "--serialization-output":
set.getSerializationConfigPaths().add(requirePathUri(current, value));
break;

case "--trace-input":
traceInputs.add(requirePathUri(current, value));
break;
Expand Down Expand Up @@ -249,7 +255,8 @@ private static void generate(Iterator<String> argsIter, boolean acceptTraceFileA
TraceProcessor p;
try {
p = new TraceProcessor(advisor, inputSet.loadJniConfig(ConfigurationSet.FAIL_ON_EXCEPTION), inputSet.loadReflectConfig(ConfigurationSet.FAIL_ON_EXCEPTION),
inputSet.loadProxyConfig(ConfigurationSet.FAIL_ON_EXCEPTION), inputSet.loadResourceConfig(ConfigurationSet.FAIL_ON_EXCEPTION));
inputSet.loadProxyConfig(ConfigurationSet.FAIL_ON_EXCEPTION), inputSet.loadResourceConfig(ConfigurationSet.FAIL_ON_EXCEPTION),
inputSet.loadSerializationConfig(ConfigurationSet.FAIL_ON_EXCEPTION));
} catch (IOException e) {
throw e;
} catch (Throwable t) {
Expand Down Expand Up @@ -287,6 +294,11 @@ private static void generate(Iterator<String> argsIter, boolean acceptTraceFileA
p.getResourceConfiguration().printJson(writer);
}
}
for (URI uri : outputSet.getSerializationConfigPaths()) {
try (JsonWriter writer = new JsonWriter(Paths.get(uri))) {
p.getSerializationConfiguration().printJson(writer);
}
}
}

private static void generateFilterRules(Iterator<String> argsIter) throws IOException {
Expand Down
Loading

0 comments on commit 13c898b

Please sign in to comment.