undefect. CWE-407 — 63 sites patched across 27 ecosystems
Authors: russell@unturf.com · brackishbert@gmail.com · foxhop.net · TimeHexOn.com Patches, unit tests, benchmarks, whitepaper, and outreach briefs. Public domain — no copyright claimed. Use freely.
This commit is contained in:
commit
0a580b313d
70422 changed files with 17213626 additions and 0 deletions
286
test/jdk/java/rmi/testlibrary/JavaVM.java
Normal file
286
test/jdk/java/rmi/testlibrary/JavaVM.java
Normal file
|
|
@ -0,0 +1,286 @@
|
|||
/*
|
||||
* Copyright (c) 1998, 2021, Oracle and/or its affiliates. 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.
|
||||
*
|
||||
* 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.
|
||||
*/
|
||||
|
||||
import java.io.BufferedReader;
|
||||
import java.io.ByteArrayOutputStream;
|
||||
import java.io.DataInputStream;
|
||||
import java.io.File;
|
||||
import java.io.IOException;
|
||||
import java.io.InputStreamReader;
|
||||
import java.io.OutputStream;
|
||||
import java.util.Arrays;
|
||||
import java.util.StringTokenizer;
|
||||
import java.util.concurrent.TimeoutException;
|
||||
|
||||
/**
|
||||
* RMI regression test utility class that uses Runtime.exec to spawn a
|
||||
* java process that will run a named java class.
|
||||
*/
|
||||
public class JavaVM {
|
||||
|
||||
static class CachedOutputStream extends OutputStream {
|
||||
ByteArrayOutputStream ba;
|
||||
OutputStream os;
|
||||
|
||||
public CachedOutputStream(OutputStream os) {
|
||||
this.os = os;
|
||||
this.ba = new ByteArrayOutputStream();
|
||||
}
|
||||
|
||||
public void write(int b) throws IOException {
|
||||
ba.write(b);
|
||||
os.write(b);
|
||||
}
|
||||
|
||||
public void reset() throws IOException {
|
||||
os.flush();
|
||||
ba.reset();
|
||||
}
|
||||
}
|
||||
|
||||
public static final long POLLTIME_MS = 100L;
|
||||
|
||||
protected Process vm = null;
|
||||
|
||||
private String classname = "";
|
||||
protected String args = "";
|
||||
protected String options = "";
|
||||
protected CachedOutputStream outputStream = new CachedOutputStream(System.out);
|
||||
protected CachedOutputStream errorStream = new CachedOutputStream(System.err);
|
||||
private String policyFileName = null;
|
||||
private StreamPipe outPipe;
|
||||
private StreamPipe errPipe;
|
||||
|
||||
private static void mesg(Object mesg) {
|
||||
System.err.println("JAVAVM: " + mesg.toString());
|
||||
}
|
||||
|
||||
/** string name of the program execd by JavaVM */
|
||||
private static String javaProgram = "java";
|
||||
|
||||
static {
|
||||
try {
|
||||
javaProgram = TestLibrary.getProperty("java.home", "") +
|
||||
File.separator + "bin" + File.separator + javaProgram;
|
||||
} catch (SecurityException se) {
|
||||
}
|
||||
}
|
||||
|
||||
public JavaVM(String classname,
|
||||
String options, String args) {
|
||||
this.classname = classname;
|
||||
this.options = options;
|
||||
this.args = args;
|
||||
}
|
||||
|
||||
public JavaVM(String classname,
|
||||
String options, String args,
|
||||
OutputStream out, OutputStream err) {
|
||||
this(classname, options, args);
|
||||
this.outputStream = new CachedOutputStream(out);
|
||||
this.errorStream = new CachedOutputStream(err);
|
||||
}
|
||||
|
||||
// Prepends passed opts array to current options
|
||||
public void addOptions(String... opts) {
|
||||
String newOpts = "";
|
||||
for (int i = 0 ; i < opts.length ; i ++) {
|
||||
newOpts += " " + opts[i];
|
||||
}
|
||||
newOpts += " ";
|
||||
options = newOpts + options;
|
||||
}
|
||||
|
||||
// Prepends passed arguments array to current args
|
||||
public void addArguments(String... arguments) {
|
||||
String newArgs = "";
|
||||
for (int i = 0 ; i < arguments.length ; i ++) {
|
||||
newArgs += " " + arguments[i];
|
||||
}
|
||||
newArgs += " ";
|
||||
args = newArgs + args;
|
||||
}
|
||||
|
||||
public void setPolicyFile(String policyFileName) {
|
||||
this.policyFileName = policyFileName;
|
||||
}
|
||||
|
||||
/**
|
||||
* This method is used for setting VM options on spawned VMs.
|
||||
* It returns the extra command line options required
|
||||
* to turn on jcov code coverage analysis.
|
||||
*/
|
||||
protected static String getCodeCoverageOptions() {
|
||||
return TestLibrary.getExtraProperty("jcov.options","");
|
||||
}
|
||||
|
||||
/**
|
||||
* Exec the VM as specified in this object's constructor.
|
||||
*/
|
||||
private void start0() throws IOException {
|
||||
outputStream.reset();
|
||||
errorStream.reset();
|
||||
|
||||
if (vm != null)
|
||||
throw new IllegalStateException("JavaVM already started");
|
||||
|
||||
/*
|
||||
* If specified, add option for policy file
|
||||
*/
|
||||
if (policyFileName != null) {
|
||||
String option = "-Djava.security.policy=" + policyFileName;
|
||||
addOptions(new String[] { option });
|
||||
}
|
||||
|
||||
addOptions(new String[] {
|
||||
getCodeCoverageOptions(),
|
||||
TestParams.testJavaOpts,
|
||||
TestParams.testVmOpts
|
||||
});
|
||||
|
||||
StringTokenizer optionsTokenizer = new StringTokenizer(options);
|
||||
StringTokenizer argsTokenizer = new StringTokenizer(args);
|
||||
int optionsCount = optionsTokenizer.countTokens();
|
||||
int argsCount = argsTokenizer.countTokens();
|
||||
|
||||
String javaCommand[] = new String[optionsCount + argsCount + 2];
|
||||
int count = 0;
|
||||
|
||||
javaCommand[count++] = JavaVM.javaProgram;
|
||||
while (optionsTokenizer.hasMoreTokens()) {
|
||||
javaCommand[count++] = optionsTokenizer.nextToken();
|
||||
}
|
||||
javaCommand[count++] = classname;
|
||||
while (argsTokenizer.hasMoreTokens()) {
|
||||
javaCommand[count++] = argsTokenizer.nextToken();
|
||||
}
|
||||
|
||||
mesg("command = " + Arrays.asList(javaCommand).toString());
|
||||
|
||||
vm = Runtime.getRuntime().exec(javaCommand);
|
||||
}
|
||||
|
||||
public void start() throws IOException {
|
||||
start0();
|
||||
|
||||
/* output from the exec'ed process may optionally be captured. */
|
||||
outPipe = StreamPipe.plugTogether(vm.getInputStream(), this.outputStream);
|
||||
errPipe = StreamPipe.plugTogether(vm.getErrorStream(), this.errorStream);
|
||||
}
|
||||
|
||||
public void destroy() {
|
||||
if (vm != null) {
|
||||
vm.destroyForcibly();
|
||||
}
|
||||
vm = null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Return exit value for vm process.
|
||||
* @return exit value for vm process
|
||||
* @throws IllegalThreadStateException if the vm process has not yet terminated
|
||||
*/
|
||||
public int exitValue() {
|
||||
return vm.exitValue();
|
||||
}
|
||||
|
||||
/**
|
||||
* Destroy the vm process, and do necessary cleanup.
|
||||
*/
|
||||
public void cleanup() {
|
||||
destroy();
|
||||
}
|
||||
|
||||
/**
|
||||
* Destroys the VM, waits for it to terminate, and returns
|
||||
* its exit status.
|
||||
*
|
||||
* @throws IllegalStateException if the VM has already been destroyed
|
||||
* @throws InterruptedException if the caller is interrupted while waiting
|
||||
*/
|
||||
public int terminate() throws InterruptedException {
|
||||
if (vm == null) {
|
||||
throw new IllegalStateException("JavaVM already destroyed");
|
||||
}
|
||||
|
||||
vm.destroy();
|
||||
int status = waitFor();
|
||||
vm = null;
|
||||
return status;
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Waits for the subprocess to exit, joins the pipe threads to ensure that
|
||||
* all output is collected, and returns its exit status.
|
||||
*/
|
||||
public int waitFor() throws InterruptedException {
|
||||
if (vm == null)
|
||||
throw new IllegalStateException("can't wait for JavaVM that isn't running");
|
||||
|
||||
int status = vm.waitFor();
|
||||
outPipe.join();
|
||||
errPipe.join();
|
||||
return status;
|
||||
}
|
||||
|
||||
/**
|
||||
* Causes the current thread to wait the vm process to exit, if necessary,
|
||||
* wait until the vm process has terminated, or the specified waiting time
|
||||
* elapses. Release allocated input/output after vm process has terminated.
|
||||
* @param timeout the maximum milliseconds to wait.
|
||||
* @return exit value for vm process.
|
||||
* @throws InterruptedException if the current thread is interrupted
|
||||
* while waiting.
|
||||
* @throws TimeoutException if subprocess does not end after timeout
|
||||
* milliseconds passed
|
||||
*/
|
||||
public int waitFor(long timeout)
|
||||
throws InterruptedException, TimeoutException {
|
||||
if (vm == null)
|
||||
throw new IllegalStateException("can't wait for JavaVM that isn't running");
|
||||
long deadline = TestLibrary.computeDeadline(System.currentTimeMillis(), timeout);
|
||||
|
||||
while (true) {
|
||||
try {
|
||||
int status = vm.exitValue();
|
||||
outPipe.join();
|
||||
errPipe.join();
|
||||
return status;
|
||||
} catch (IllegalThreadStateException ignore) { }
|
||||
|
||||
if (System.currentTimeMillis() > deadline)
|
||||
throw new TimeoutException();
|
||||
|
||||
Thread.sleep(POLLTIME_MS);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Starts the subprocess, waits for it to exit, and returns its exit status.
|
||||
*/
|
||||
public int execute() throws IOException, InterruptedException {
|
||||
start();
|
||||
return waitFor();
|
||||
}
|
||||
}
|
||||
70
test/jdk/java/rmi/testlibrary/README.jcov
Normal file
70
test/jdk/java/rmi/testlibrary/README.jcov
Normal file
|
|
@ -0,0 +1,70 @@
|
|||
########################################################################
|
||||
# This file contains example scripts and property files for collecting
|
||||
# code coverage data of the RMI regression suite.
|
||||
#
|
||||
# Since many RMI regression tests spawn child VMs,
|
||||
# special support is required for setting
|
||||
# command line options and arguments needed by jcov - the code coverage
|
||||
# instrumentation and collection tool. This special support is provided
|
||||
# by properties in the test.props file. If a file named ../../test.props
|
||||
# exists (assuming the working directory is "<path>/JTwork/scratch", this
|
||||
# will find "<path>/test.props"), then it will be used by test library
|
||||
# code that spawns VMs. See the example test.props
|
||||
# file below for the properties that may be defined.
|
||||
|
||||
|
||||
########################################################################
|
||||
# The following is a script used to execute RMI regression tests
|
||||
# on Solaris and collect code coverage data.
|
||||
|
||||
#!/bin/ksh
|
||||
export JAVA_HOME=<path to special JDK jcov instrumented build>
|
||||
export JT_HOME=<path to special JTREG build with jcov hooks>
|
||||
export CLASSPATH=.:${JT_HOME}/javatest.jar
|
||||
export OPTS="-Xms256m -Xmx256m -XX:+UseUnsupportedDeprecatedJVMPI -XX:+EnableJVMPIInstructionStartEvent -XX:-UseFastEmptyMethods -XX:-UseFastAccessorMethods -timeoutFactor:4"
|
||||
export TESTBASE=/files/<JDK workspace>/test
|
||||
${JT_HOME}/solaris/bin/jtreg -Xrunjcov:file=/files/rmi.jcov ${OPTS} -va -w:/tmp/JT -r:/tmp/JTreport -jdk:${JAVA_HOME} ${TESTBASE}
|
||||
|
||||
|
||||
########################################################################
|
||||
# The following section is an example test.props property file
|
||||
# used for collecting code coverage data for JDK 1.6. These properties
|
||||
# are currently supported:
|
||||
# jcov.options are the jcov options that should be added to VMs
|
||||
# system properties
|
||||
# jcov.sleep.multiplier is an integer that will be multiplied by
|
||||
# various wait times in the test library; the
|
||||
# default value used is '1'
|
||||
|
||||
jcov.options=-Xrunjcov:file=/files/rmi.jcov -Xms256m -Xmx256m -XX:+UseUnsupportedDeprecatedJVMPI -XX:+EnableJVMPIInstructionStartEvent -XX:-UseFastEmptyMethods -XX:-UseFastAccessorMethods
|
||||
|
||||
jcov.sleep.multiplier=3
|
||||
|
||||
|
||||
########################################################################
|
||||
# The following section is an example script that generates the
|
||||
# jcov report. The important documentation here is the list of Java
|
||||
# packages and classes that are included in the RMI coverage report.
|
||||
|
||||
#!/bin/ksh
|
||||
|
||||
export CLASSPATH=<path to jcov.jar>
|
||||
export SRCS=<path to sources of the instrumented JDK build>
|
||||
java com.sun.tdk.jcov.MergerMain <path to jcov 'A' template for the build>template_a.jcov /files/rmi.jcov
|
||||
java -Xms256m -Xmx512m com.sun.tdk.jcov.RepGenMain -fmt=html_ns -src_root=${SRCS} \
|
||||
-include=java.rmi.* \
|
||||
-include=java.rmi.dgc.* \
|
||||
-include=java.rmi.registry.* \
|
||||
-include=java.rmi.server.* \
|
||||
-include=sun.rmi.log.* \
|
||||
-include=sun.rmi.registry.* \
|
||||
-include=sun.rmi.runtime.* \
|
||||
-include=sun.rmi.server.* \
|
||||
-include=sun.rmi.transport.* \
|
||||
-include=sun.rmi.transport.proxy.* \
|
||||
-include=sun.rmi.transport.tcp.* \
|
||||
-include=java.lang.reflect.Proxy \
|
||||
-include=sun.misc.ProxyGenerator \
|
||||
-exclude=javax.rmi.ssl.* \
|
||||
java.jcov
|
||||
|
||||
79
test/jdk/java/rmi/testlibrary/RMIRegistryRunner.java
Normal file
79
test/jdk/java/rmi/testlibrary/RMIRegistryRunner.java
Normal file
|
|
@ -0,0 +1,79 @@
|
|||
/*
|
||||
* Copyright (c) 2017, Oracle and/or its affiliates. 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.
|
||||
*
|
||||
* 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.
|
||||
*/
|
||||
|
||||
/**/
|
||||
|
||||
import java.rmi.*;
|
||||
import java.rmi.registry.*;
|
||||
import java.rmi.server.*;
|
||||
|
||||
/**
|
||||
* Class to run a rmiregistry whose VM can be told to exit remotely;
|
||||
* Difference between this class and RegistryRunner is that this class
|
||||
* simulate rmiregistry closer than RegistryRunner.
|
||||
*/
|
||||
public class RMIRegistryRunner extends RegistryRunner
|
||||
{
|
||||
public RMIRegistryRunner() throws RemoteException {
|
||||
}
|
||||
|
||||
/**
|
||||
* port 0 means to use ephemeral port to start registry.
|
||||
*
|
||||
* @param args command line arguments passed in from main
|
||||
* @return the port number on which registry accepts requests
|
||||
*/
|
||||
protected static int init(String[] args) {
|
||||
try {
|
||||
if (args.length == 0) {
|
||||
System.err.println("Usage: <port>");
|
||||
System.exit(0);
|
||||
}
|
||||
int port = -1;
|
||||
port = Integer.parseInt(args[0]);
|
||||
|
||||
// call RegistryImpl.createRegistry to simulate rmiregistry.
|
||||
registry = sun.rmi.registry.RegistryImpl.createRegistry(port);
|
||||
if (port == 0) {
|
||||
port = TestLibrary.getRegistryPort(registry);
|
||||
}
|
||||
|
||||
// create a remote object to tell this VM to exit
|
||||
exiter = new RMIRegistryRunner();
|
||||
Naming.rebind("rmi://localhost:" + port +
|
||||
"/RemoteExiter", exiter);
|
||||
|
||||
return port;
|
||||
} catch (Exception e) {
|
||||
System.err.println(e.getMessage());
|
||||
e.printStackTrace();
|
||||
System.exit(1);
|
||||
}
|
||||
return -1;
|
||||
}
|
||||
|
||||
public static void main(String[] args) {
|
||||
int port = init(args);
|
||||
notify(port);
|
||||
}
|
||||
}
|
||||
153
test/jdk/java/rmi/testlibrary/RegistryRunner.java
Normal file
153
test/jdk/java/rmi/testlibrary/RegistryRunner.java
Normal file
|
|
@ -0,0 +1,153 @@
|
|||
/*
|
||||
* Copyright (c) 1999, 2017, Oracle and/or its affiliates. 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.
|
||||
*
|
||||
* 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.
|
||||
*/
|
||||
|
||||
/**/
|
||||
|
||||
import java.rmi.*;
|
||||
import java.rmi.registry.*;
|
||||
import java.rmi.server.*;
|
||||
|
||||
/**
|
||||
* Class to run a registry whose VM can be told to exit remotely; using
|
||||
* a registry (in a sub-process) in this fashion makes tests more robust under
|
||||
* windows where Process.destroy() seems not to be 100% reliable.
|
||||
*/
|
||||
public class RegistryRunner extends UnicastRemoteObject
|
||||
implements RemoteExiter
|
||||
{
|
||||
private static final String PORT_LABEL_START = "RegistryRunner.port.start:";
|
||||
private static final String PORT_LABEL_END = ":RegistryRunner.port.end";
|
||||
|
||||
protected static Registry registry = null;
|
||||
protected static RemoteExiter exiter = null;
|
||||
|
||||
public RegistryRunner() throws RemoteException {
|
||||
}
|
||||
|
||||
/**
|
||||
* Ask the registry to exit instead of forcing it do so; this
|
||||
* works better on windows...
|
||||
*/
|
||||
public void exit() throws RemoteException {
|
||||
// REMIND: create a thread to do this to avoid
|
||||
// a remote exception?
|
||||
System.err.println("received call to exit");
|
||||
System.exit(0);
|
||||
}
|
||||
|
||||
/**
|
||||
* Request that the registry process exit and handle
|
||||
* related exceptions.
|
||||
*/
|
||||
public static void requestExit(int port) {
|
||||
|
||||
try {
|
||||
RemoteExiter e =
|
||||
(RemoteExiter)
|
||||
Naming.lookup("rmi://localhost:" +
|
||||
port +
|
||||
"/RemoteExiter");
|
||||
try {
|
||||
e.exit();
|
||||
} catch (RemoteException re) {
|
||||
}
|
||||
e = null;
|
||||
|
||||
} catch (java.net.MalformedURLException mfue) {
|
||||
// will not happen
|
||||
} catch (NotBoundException nbe) {
|
||||
TestLibrary.bomb("exiter not bound?", nbe);
|
||||
} catch (RemoteException re) {
|
||||
TestLibrary.bomb("remote exception trying to exit",
|
||||
re);
|
||||
}
|
||||
}
|
||||
|
||||
public static int getRegistryPort(String output) {
|
||||
int idxStart = output.indexOf(PORT_LABEL_START);
|
||||
int idxEnd = output.indexOf(PORT_LABEL_END);
|
||||
if (idxStart == -1 || idxEnd == -1) {
|
||||
return -1;
|
||||
}
|
||||
idxStart = idxStart+PORT_LABEL_START.length();
|
||||
String portStr = output.substring(idxStart, idxEnd);
|
||||
int port = Integer.valueOf(portStr);
|
||||
System.err.println("registry is running at port: " + port);
|
||||
return port;
|
||||
}
|
||||
|
||||
/**
|
||||
* port 0 means to use ephemeral port to start registry.
|
||||
*
|
||||
* @param args command line arguments passed in from main
|
||||
* @return the port number on which registry accepts requests
|
||||
*/
|
||||
protected static int init(String[] args) {
|
||||
try {
|
||||
if (args.length == 0) {
|
||||
System.err.println("Usage: <port>");
|
||||
System.exit(0);
|
||||
}
|
||||
int port = -1;
|
||||
port = Integer.parseInt(args[0]);
|
||||
|
||||
// create a registry
|
||||
registry = LocateRegistry.createRegistry(port);
|
||||
if (port == 0) {
|
||||
port = TestLibrary.getRegistryPort(registry);
|
||||
}
|
||||
|
||||
// create a remote object to tell this VM to exit
|
||||
exiter = new RegistryRunner();
|
||||
Naming.rebind("rmi://localhost:" + port +
|
||||
"/RemoteExiter", exiter);
|
||||
|
||||
return port;
|
||||
} catch (Exception e) {
|
||||
System.err.println(e.getMessage());
|
||||
e.printStackTrace();
|
||||
System.exit(-1);
|
||||
}
|
||||
return -1;
|
||||
}
|
||||
|
||||
/**
|
||||
* RegistryVM.start() will filter the output of registry subprocess,
|
||||
* when valid port is detected, RegistryVM.start() returns.
|
||||
* So, for subclass, it's important to call this method after registry
|
||||
* is initialized and necessary remote objects have been bound.
|
||||
*
|
||||
* @param port the port on which registry accepts requests
|
||||
*/
|
||||
protected static void notify(int port) {
|
||||
// this output is important for RegistryVM to get the port
|
||||
// where rmiregistry is serving
|
||||
System.out.println(PORT_LABEL_START + port + PORT_LABEL_END);
|
||||
System.out.flush();
|
||||
}
|
||||
|
||||
public static void main(String[] args) {
|
||||
int port = init(args);
|
||||
notify(port);
|
||||
}
|
||||
}
|
||||
184
test/jdk/java/rmi/testlibrary/RegistryVM.java
Normal file
184
test/jdk/java/rmi/testlibrary/RegistryVM.java
Normal file
|
|
@ -0,0 +1,184 @@
|
|||
/*
|
||||
* Copyright (c) 2017, Oracle and/or its affiliates. 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.
|
||||
*
|
||||
* 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.
|
||||
*/
|
||||
|
||||
import java.io.OutputStream;
|
||||
import java.io.IOException;
|
||||
|
||||
/**
|
||||
* Class to run and control registry/rmiregistry in a sub-process.
|
||||
* The behaviour changes when use different runner, currently
|
||||
* there are 2 built-in runners, RegistryRunner and RMIRegistryRunner.
|
||||
*
|
||||
* We can't kill a registry if we have too-close control
|
||||
* over it. We must make it in a subprocess, and then kill the
|
||||
* subprocess when it has served our needs.
|
||||
*/
|
||||
public class RegistryVM extends JavaVM {
|
||||
|
||||
private static final double START_TIMEOUT =
|
||||
20_000 * TestLibrary.getTimeoutFactor();
|
||||
private static final String DEFAULT_RUNNER = "RegistryRunner";
|
||||
|
||||
private int port = -1;
|
||||
|
||||
private RegistryVM(String runner, OutputStream out, OutputStream err,
|
||||
String options, int port) {
|
||||
super(runner, options, Integer.toString(port), out, err);
|
||||
try {
|
||||
Class runnerClass = Class.forName(runner);
|
||||
if (!RegistryRunner.class.isAssignableFrom(runnerClass)) {
|
||||
throw new RuntimeException("runner class must be RegistryRunner"
|
||||
+ " or its sub class");
|
||||
}
|
||||
} catch (ClassNotFoundException ex) {
|
||||
throw new RuntimeException(ex);
|
||||
}
|
||||
this.port = port;
|
||||
}
|
||||
|
||||
/**
|
||||
* Create a RegistryVM instance on an ephemeral port.
|
||||
*
|
||||
* @return a RegistryVM instance
|
||||
*/
|
||||
public static RegistryVM createRegistryVM() {
|
||||
return createRegistryVMWithRunner(DEFAULT_RUNNER, System.out, System.err, "", 0);
|
||||
}
|
||||
|
||||
/**
|
||||
* Create a RegistryVM instance on an ephemeral port with additional
|
||||
* command line options.
|
||||
*
|
||||
* @param options command line options
|
||||
* @return a RegistryVM instance
|
||||
*/
|
||||
public static RegistryVM createRegistryVM(String options) {
|
||||
return createRegistryVMWithRunner(
|
||||
DEFAULT_RUNNER, System.out, System.err, options, 0);
|
||||
}
|
||||
|
||||
/**
|
||||
* Create a RegistryVM instance on a specified port capturing stdout and
|
||||
* stderr with additional command line options.
|
||||
*
|
||||
* @param out the OutputStream where the normal output of the
|
||||
* registry subprocess goes
|
||||
* @param err the OutputStream where the error output of the
|
||||
* registry subprocess goes
|
||||
* @param options the command line options
|
||||
* @param port the port on which Registry accepts requests
|
||||
* @return a RegistryVM instance
|
||||
*/
|
||||
public static RegistryVM createRegistryVM(OutputStream out, OutputStream err,
|
||||
String options, int port) {
|
||||
return createRegistryVMWithRunner(DEFAULT_RUNNER, out, err, options, port);
|
||||
}
|
||||
|
||||
/**
|
||||
* Create a RegistryVM instance on an ephemeral port with additional
|
||||
* command line options and a specified runner.
|
||||
*
|
||||
* @param runner the runner class name
|
||||
* @param options command line options
|
||||
* @return a RegistryVM instance
|
||||
*/
|
||||
public static RegistryVM createRegistryVMWithRunner(String runner, String options) {
|
||||
return createRegistryVMWithRunner(runner, System.out, System.err, options, 0);
|
||||
}
|
||||
|
||||
/**
|
||||
* Create a RegistryVM instance on a specified port capturing stdout and
|
||||
* stderr with additional command line options and a specified runner.
|
||||
*
|
||||
* @param runner the runner class name
|
||||
* @param out the OutputStream where the normal output of the
|
||||
* registry subprocess goes
|
||||
* @param err the OutputStream where the error output of the
|
||||
* registry subprocess goes
|
||||
* @param options the command line options
|
||||
* @param port the port on which Registry accepts requests
|
||||
* @return a RegistryVM instance
|
||||
*/
|
||||
public static RegistryVM createRegistryVMWithRunner(String runner, OutputStream out,
|
||||
OutputStream err, String options, int port) {
|
||||
options += " --add-exports=java.rmi/sun.rmi.registry=ALL-UNNAMED"
|
||||
+ " --add-exports=java.rmi/sun.rmi.server=ALL-UNNAMED"
|
||||
+ " --add-exports=java.rmi/sun.rmi.transport=ALL-UNNAMED"
|
||||
+ " --add-exports=java.rmi/sun.rmi.transport.tcp=ALL-UNNAMED";
|
||||
RegistryVM reg = new RegistryVM(runner, out, err, options, port);
|
||||
reg.setPolicyFile(TestParams.defaultRegistryPolicy);
|
||||
return reg;
|
||||
}
|
||||
|
||||
/**
|
||||
* Starts the registry in a sub-process and waits up to
|
||||
* the given timeout period to confirm that it's running,
|
||||
* and get the port where it's running.
|
||||
*
|
||||
* @throws IOException if fails to start subprocess
|
||||
*/
|
||||
public void start() throws IOException {
|
||||
super.start();
|
||||
long startTime = System.currentTimeMillis();
|
||||
long deadline = TestLibrary.computeDeadline(startTime, (long)START_TIMEOUT);
|
||||
while (true) {
|
||||
try {
|
||||
Thread.sleep(1000);
|
||||
} catch (InterruptedException ignore) { }
|
||||
|
||||
String output = outputStream.ba.toString();
|
||||
port = RegistryRunner.getRegistryPort(output);
|
||||
if (port != -1) {
|
||||
break;
|
||||
}
|
||||
try {
|
||||
int exit = vm.exitValue();
|
||||
TestLibrary.bomb("[RegistryVM] registry sub-process exited with status "
|
||||
+ exit + ".");
|
||||
} catch (IllegalThreadStateException ignore) { }
|
||||
|
||||
if (System.currentTimeMillis() > deadline) {
|
||||
TestLibrary.bomb("Failed to start registry, giving up after " +
|
||||
(System.currentTimeMillis() - startTime) + "ms.", null);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Shuts down the registry.
|
||||
*/
|
||||
@Override
|
||||
public void cleanup() {
|
||||
RegistryRunner.requestExit(port);
|
||||
super.destroy();
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets the port where the registry is serving.
|
||||
*
|
||||
* @return the port where the registry is serving
|
||||
*/
|
||||
public int getPort() {
|
||||
return port;
|
||||
}
|
||||
}
|
||||
31
test/jdk/java/rmi/testlibrary/RemoteExiter.java
Normal file
31
test/jdk/java/rmi/testlibrary/RemoteExiter.java
Normal file
|
|
@ -0,0 +1,31 @@
|
|||
/*
|
||||
* Copyright (c) 1999, Oracle and/or its affiliates. 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.
|
||||
*
|
||||
* 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.
|
||||
*/
|
||||
|
||||
/**
|
||||
*
|
||||
*/
|
||||
import java.rmi.Remote;
|
||||
import java.rmi.RemoteException;
|
||||
public interface RemoteExiter extends Remote {
|
||||
void exit() throws RemoteException;
|
||||
}
|
||||
85
test/jdk/java/rmi/testlibrary/StreamPipe.java
Normal file
85
test/jdk/java/rmi/testlibrary/StreamPipe.java
Normal file
|
|
@ -0,0 +1,85 @@
|
|||
/*
|
||||
* Copyright (c) 1998, 2012, Oracle and/or its affiliates. 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.
|
||||
*
|
||||
* 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.
|
||||
*/
|
||||
|
||||
import java.io.InputStream;
|
||||
import java.io.InterruptedIOException;
|
||||
import java.io.IOException;
|
||||
import java.io.OutputStream;
|
||||
|
||||
/**
|
||||
* Pipe output of one stream into input of another.
|
||||
*/
|
||||
public class StreamPipe extends Thread {
|
||||
|
||||
private InputStream in;
|
||||
private OutputStream out;
|
||||
|
||||
private static Object countLock = new Object();
|
||||
private static int count = 0;
|
||||
|
||||
/**
|
||||
* StreamPipe constructor : should only be called by plugTogether() method.
|
||||
*/
|
||||
private StreamPipe(InputStream in, OutputStream out, String name) {
|
||||
super(name);
|
||||
this.in = in;
|
||||
this.out = out;
|
||||
}
|
||||
|
||||
/**
|
||||
* Creates a StreamPipe thread that copies in to out and returns
|
||||
* the created instance.
|
||||
*/
|
||||
public static StreamPipe plugTogether(InputStream in, OutputStream out) {
|
||||
String name;
|
||||
|
||||
synchronized (countLock) {
|
||||
name = "java.rmi.testlibrary.StreamPipe-" + (count++);
|
||||
}
|
||||
|
||||
StreamPipe pipe = new StreamPipe(in, out, name);
|
||||
pipe.setDaemon(true);
|
||||
pipe.start();
|
||||
return pipe;
|
||||
}
|
||||
|
||||
// Starts redirection of streams.
|
||||
public void run() {
|
||||
try {
|
||||
byte[] buf = new byte[1024];
|
||||
|
||||
while (true) {
|
||||
int nr = in.read(buf);
|
||||
if (nr == -1)
|
||||
break;
|
||||
out.write(buf, 0, nr);
|
||||
}
|
||||
} catch (InterruptedIOException iioe) {
|
||||
// Thread interrupted during IO operation. Terminate StreamPipe.
|
||||
return;
|
||||
} catch (IOException e) {
|
||||
System.err.println("*** IOException in StreamPipe.run:");
|
||||
e.printStackTrace();
|
||||
}
|
||||
}
|
||||
}
|
||||
82
test/jdk/java/rmi/testlibrary/TestFailedException.java
Normal file
82
test/jdk/java/rmi/testlibrary/TestFailedException.java
Normal file
|
|
@ -0,0 +1,82 @@
|
|||
/*
|
||||
* Copyright (c) 1999, Oracle and/or its affiliates. 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.
|
||||
*
|
||||
* 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.
|
||||
*/
|
||||
|
||||
/**/
|
||||
|
||||
|
||||
/**
|
||||
* Simple class to wrap test failure exceptions in a RuntimeException.
|
||||
* Provides a detail exception and a message.
|
||||
*/
|
||||
public class TestFailedException extends java.lang.RuntimeException {
|
||||
public Throwable detail;
|
||||
|
||||
public TestFailedException() {}
|
||||
|
||||
public TestFailedException(String s) {
|
||||
super(s);
|
||||
}
|
||||
|
||||
public TestFailedException(String s, Throwable ex) {
|
||||
super(s);
|
||||
detail = ex;
|
||||
}
|
||||
|
||||
public String getMessage() {
|
||||
if (detail == null)
|
||||
return super.getMessage();
|
||||
else
|
||||
return super.getMessage() +
|
||||
"; nested exception is: \n\t" +
|
||||
detail.toString();
|
||||
}
|
||||
|
||||
public void printStackTrace(java.io.PrintStream ps)
|
||||
{
|
||||
if (detail == null) {
|
||||
super.printStackTrace(ps);
|
||||
} else {
|
||||
synchronized(ps) {
|
||||
ps.println(this);
|
||||
detail.printStackTrace(ps);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public void printStackTrace()
|
||||
{
|
||||
printStackTrace(System.err);
|
||||
}
|
||||
|
||||
public void printStackTrace(java.io.PrintWriter pw)
|
||||
{
|
||||
if (detail == null) {
|
||||
super.printStackTrace(pw);
|
||||
} else {
|
||||
synchronized(pw) {
|
||||
pw.println(this);
|
||||
detail.printStackTrace(pw);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
532
test/jdk/java/rmi/testlibrary/TestLibrary.java
Normal file
532
test/jdk/java/rmi/testlibrary/TestLibrary.java
Normal file
|
|
@ -0,0 +1,532 @@
|
|||
/*
|
||||
* Copyright (c) 1998, 2024, Oracle and/or its affiliates. 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.
|
||||
*
|
||||
* 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.
|
||||
*/
|
||||
|
||||
/**
|
||||
*
|
||||
*
|
||||
* @author Adrian Colley
|
||||
* @author Laird Dornin
|
||||
* @author Peter Jones
|
||||
* @author Ann Wollrath
|
||||
*
|
||||
* The rmi library directory contains a set of simple utiltity classes
|
||||
* for use in rmi regression tests.
|
||||
*
|
||||
* NOTE: The JavaTest group has recommended that regression tests do
|
||||
* not make use of packages.
|
||||
*/
|
||||
|
||||
import java.io.ByteArrayOutputStream;
|
||||
import java.io.File;
|
||||
import java.io.FileInputStream;
|
||||
import java.io.FileOutputStream;
|
||||
import java.io.IOException;
|
||||
import java.io.PrintStream;
|
||||
import java.net.MalformedURLException;
|
||||
import java.net.ServerSocket;
|
||||
import java.net.URL;
|
||||
import java.rmi.NoSuchObjectException;
|
||||
import java.rmi.Remote;
|
||||
import java.rmi.RemoteException;
|
||||
import java.rmi.registry.LocateRegistry;
|
||||
import java.rmi.registry.Registry;
|
||||
import java.rmi.server.RemoteRef;
|
||||
import java.rmi.server.UnicastRemoteObject;
|
||||
import java.util.Enumeration;
|
||||
import java.util.Properties;
|
||||
|
||||
import sun.rmi.registry.RegistryImpl;
|
||||
import sun.rmi.server.UnicastServerRef;
|
||||
import sun.rmi.transport.Endpoint;
|
||||
import sun.rmi.transport.LiveRef;
|
||||
import sun.rmi.transport.tcp.TCPEndpoint;
|
||||
|
||||
/**
|
||||
* Class of utility/library methods (i.e. procedures) that assist with
|
||||
* the writing and maintainance of rmi regression tests.
|
||||
*/
|
||||
public class TestLibrary {
|
||||
/**
|
||||
* IMPORTANT!
|
||||
*
|
||||
* RMI tests are run concurrently and port conflicts result when a single
|
||||
* port number is used by multiple tests. When needing a port, use
|
||||
* getUnusedRandomPort() wherever possible. If getUnusedRandomPort() cannot
|
||||
* be used, reserve and specify a port to use for your test here. This
|
||||
* will ensure there are no port conflicts amongst the RMI tests. The
|
||||
* port numbers specified here may also be specified in the respective
|
||||
* tests. Do not change the reserved port numbers here without also
|
||||
* changing the port numbers in the respective tests.
|
||||
*
|
||||
* When needing an instance of the RMIRegistry, use
|
||||
* createRegistryOnUnusedPort wherever possible to prevent port conflicts.
|
||||
*
|
||||
* Reserved port range: FIXED_PORT_MIN to FIXED_PORT_MAX (inclusive) for
|
||||
* tests which cannot use a random port. If new fixed ports are added below
|
||||
* FIXED_PORT_MIN or above FIXED_PORT_MAX, then adjust
|
||||
* FIXED_PORT_MIN/MAX appropriately.
|
||||
*/
|
||||
public final static int FIXED_PORT_MIN = 60001;
|
||||
public final static int FIXED_PORT_MAX = 60010;
|
||||
public final static int INHERITEDCHANNELNOTSERVERSOCKET_ACTIVATION_PORT = 60003;
|
||||
public final static int INHERITEDCHANNELNOTSERVERSOCKET_REGISTRY_PORT = 60004;
|
||||
public final static int READTEST_REGISTRY_PORT = 60005;
|
||||
private final static int MAX_SERVER_SOCKET_TRIES = 2*(FIXED_PORT_MAX-FIXED_PORT_MIN+1);
|
||||
|
||||
static void mesg(Object mesg) {
|
||||
System.err.println("TEST_LIBRARY: " + mesg.toString());
|
||||
}
|
||||
|
||||
/**
|
||||
* Routines that enable rmi tests to fail in a uniformly
|
||||
* informative fashion.
|
||||
*/
|
||||
public static void bomb(String message, Exception e) {
|
||||
String testFailed = "TEST FAILED: ";
|
||||
|
||||
if ((message == null) && (e == null)) {
|
||||
testFailed += " No relevant information";
|
||||
} else if (e == null) {
|
||||
testFailed += message;
|
||||
}
|
||||
|
||||
System.err.println(testFailed);
|
||||
if (e != null) {
|
||||
System.err.println("Test failed with: " +
|
||||
e.getMessage());
|
||||
e.printStackTrace(System.err);
|
||||
}
|
||||
throw new TestFailedException(testFailed, e);
|
||||
}
|
||||
public static void bomb(String message) {
|
||||
bomb(message, null);
|
||||
}
|
||||
public static void bomb(Exception e) {
|
||||
bomb(null, e);
|
||||
}
|
||||
|
||||
/**
|
||||
* Helper method to determine if registry has started
|
||||
*
|
||||
* @param port The port number to check
|
||||
* @param msTimeout The amount of milliseconds to spend checking
|
||||
*/
|
||||
|
||||
public static boolean checkIfRegistryRunning(int port, int msTimeout) {
|
||||
final long POLLTIME_MS = 100L;
|
||||
long stopTime = computeDeadline(System.currentTimeMillis(), msTimeout);
|
||||
do {
|
||||
try {
|
||||
Registry r = LocateRegistry.getRegistry(port);
|
||||
String[] s = r.list();
|
||||
// no exception. We're now happy that registry is running
|
||||
return true;
|
||||
} catch (RemoteException e) {
|
||||
// problem - not ready ? Try again
|
||||
try {
|
||||
Thread.sleep(POLLTIME_MS);
|
||||
} catch (InterruptedException ie) {
|
||||
// not expected
|
||||
}
|
||||
}
|
||||
} while (System.currentTimeMillis() < stopTime);
|
||||
return false;
|
||||
}
|
||||
|
||||
public static String getProperty(final String property,
|
||||
final String defaultVal) {
|
||||
try {
|
||||
return java.security.AccessController.doPrivileged(
|
||||
new java.security.PrivilegedAction<String>() {
|
||||
public String run() {
|
||||
return System.getProperty(property, defaultVal);
|
||||
}
|
||||
});
|
||||
} catch (Exception ex) {
|
||||
bomb("Exception getting property " + property, ex);
|
||||
throw new AssertionError("this should be unreachable");
|
||||
}
|
||||
}
|
||||
|
||||
public static double getTimeoutFactor() {
|
||||
String prop = getProperty("test.timeout.factor", "1.0");
|
||||
double timeoutFactor = 1.0;
|
||||
|
||||
try {
|
||||
timeoutFactor = Double.parseDouble(prop);
|
||||
} catch (NumberFormatException ignore) { }
|
||||
|
||||
return timeoutFactor;
|
||||
}
|
||||
|
||||
/**
|
||||
* Computes a deadline from a timestamp and a timeout value.
|
||||
* Maximum timeout (before multipliers are applied) is one hour.
|
||||
*/
|
||||
public static long computeDeadline(long timestamp, long timeout) {
|
||||
if (timeout < 0L) {
|
||||
throw new IllegalArgumentException("timeout " + timeout + "ms out of range");
|
||||
}
|
||||
|
||||
return timestamp + (long)(timeout * getTimeoutFactor());
|
||||
}
|
||||
|
||||
/**
|
||||
* Property mutators
|
||||
*/
|
||||
public static void setBoolean(String property, boolean value) {
|
||||
setProperty(property, (new Boolean(value)).toString());
|
||||
}
|
||||
public static void setInteger(String property, int value) {
|
||||
setProperty(property, Integer.toString(value));
|
||||
}
|
||||
public static void setProperty(String property, String value) {
|
||||
final String prop = property;
|
||||
final String val = value;
|
||||
java.security.AccessController.doPrivileged(
|
||||
new java.security.PrivilegedAction<Void>() {
|
||||
public Void run() {
|
||||
System.setProperty(prop, val);
|
||||
return null;
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Routines to print out a test's properties environment.
|
||||
*/
|
||||
public static void printEnvironment() {
|
||||
printEnvironment(System.err);
|
||||
}
|
||||
public static void printEnvironment(PrintStream out) {
|
||||
out.println("-------------------Test environment----------" +
|
||||
"---------");
|
||||
|
||||
for(Enumeration<?> keys = System.getProperties().keys();
|
||||
keys.hasMoreElements();) {
|
||||
|
||||
String property = (String) keys.nextElement();
|
||||
out.println(property + " = " + getProperty(property, null));
|
||||
}
|
||||
out.println("---------------------------------------------" +
|
||||
"---------");
|
||||
}
|
||||
|
||||
/**
|
||||
* Routine that "works-around" a limitation in jtreg.
|
||||
* Currently it is not possible for a test to specify that the
|
||||
* test harness should build a given source file and install the
|
||||
* resulting class in a location that is not accessible from the
|
||||
* test's classpath. This method enables a test to move a
|
||||
* compiled test class file from the test's class directory into a
|
||||
* given "codebase" directory. As a result the test can only
|
||||
* access the class file for <code>className</code>if the test loads
|
||||
* it from a classloader (e.g. RMIClassLoader).
|
||||
*
|
||||
* Tests that use this routine must have the following permissions
|
||||
* granted to them:
|
||||
*
|
||||
* getProperty user.dir
|
||||
* getProperty etc.
|
||||
*/
|
||||
public static URL installClassInCodebase(String className,
|
||||
String codebase)
|
||||
throws MalformedURLException
|
||||
{
|
||||
return installClassInCodebase(className, codebase, true);
|
||||
}
|
||||
|
||||
public static URL installClassInCodebase(String className,
|
||||
String codebase,
|
||||
boolean delete)
|
||||
throws MalformedURLException
|
||||
{
|
||||
/*
|
||||
* NOTES/LIMITATIONS: The class must not be in a named package,
|
||||
* and the codebase must be a relative path (it's created relative
|
||||
* to the working directory).
|
||||
*/
|
||||
String classFileName = className + ".class";
|
||||
|
||||
/*
|
||||
* Specify the file to contain the class definition. Make sure
|
||||
* that the codebase directory exists (underneath the working
|
||||
* directory).
|
||||
*/
|
||||
File dstDir = (new File(getProperty("user.dir", "."), codebase));
|
||||
|
||||
if (!dstDir.exists()) {
|
||||
if (!dstDir.mkdir()) {
|
||||
throw new RuntimeException(
|
||||
"could not create codebase directory");
|
||||
}
|
||||
}
|
||||
File dstFile = new File(dstDir, classFileName);
|
||||
|
||||
/*
|
||||
* Obtain the URL for the codebase.
|
||||
*/
|
||||
URL codebaseURL = dstDir.toURI().toURL();
|
||||
|
||||
/*
|
||||
* Specify where we will copy the class definition from, if
|
||||
* necessary. After the test is built, the class file can be
|
||||
* found in the "test.classes" directory.
|
||||
*/
|
||||
File srcDir = new File(getProperty("test.classes", "."));
|
||||
File srcFile = new File(srcDir, classFileName);
|
||||
|
||||
mesg(srcFile);
|
||||
mesg(dstFile);
|
||||
|
||||
/*
|
||||
* If the class definition is not already located at the codebase,
|
||||
* copy it there from the test build area.
|
||||
*/
|
||||
if (!dstFile.exists()) {
|
||||
if (!srcFile.exists()) {
|
||||
throw new RuntimeException(
|
||||
"could not find class file to install in codebase " +
|
||||
"(try rebuilding the test): " + srcFile);
|
||||
}
|
||||
|
||||
try {
|
||||
copyFile(srcFile, dstFile);
|
||||
} catch (IOException e) {
|
||||
throw new RuntimeException(
|
||||
"could not install class file in codebase");
|
||||
}
|
||||
|
||||
mesg("Installed class \"" + className +
|
||||
"\" in codebase " + codebaseURL);
|
||||
}
|
||||
|
||||
/*
|
||||
* After the class definition is successfully installed at the
|
||||
* codebase, delete it from the test's CLASSPATH, so that it will
|
||||
* not be found there first before the codebase is searched.
|
||||
*/
|
||||
if (srcFile.exists()) {
|
||||
if (delete && !srcFile.delete()) {
|
||||
throw new RuntimeException(
|
||||
"could not delete duplicate class file in CLASSPATH");
|
||||
}
|
||||
}
|
||||
|
||||
return codebaseURL;
|
||||
}
|
||||
|
||||
public static void copyFile(File srcFile, File dstFile)
|
||||
throws IOException
|
||||
{
|
||||
FileInputStream src = new FileInputStream(srcFile);
|
||||
FileOutputStream dst = new FileOutputStream(dstFile);
|
||||
|
||||
byte[] buf = new byte[32768];
|
||||
while (true) {
|
||||
int count = src.read(buf);
|
||||
if (count < 0) {
|
||||
break;
|
||||
}
|
||||
dst.write(buf, 0, count);
|
||||
}
|
||||
|
||||
dst.close();
|
||||
src.close();
|
||||
}
|
||||
|
||||
/** routine to unexport an object */
|
||||
public static void unexport(Remote obj) {
|
||||
if (obj != null) {
|
||||
try {
|
||||
mesg("unexporting object...");
|
||||
UnicastRemoteObject.unexportObject(obj, true);
|
||||
} catch (NoSuchObjectException munch) {
|
||||
} catch (Exception e) {
|
||||
e.getMessage();
|
||||
e.printStackTrace();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Creates an RMI {@link Registry} on a random, un-reserved port.
|
||||
*
|
||||
* @return an RMI Registry, using a random port.
|
||||
* @throws RemoteException if there was a problem creating a Registry.
|
||||
*/
|
||||
public static Registry createRegistryOnUnusedPort() throws RemoteException {
|
||||
return LocateRegistry.createRegistry(getUnusedRandomPort());
|
||||
}
|
||||
|
||||
/**
|
||||
* Creates an RMI {@link Registry} on an ephemeral port.
|
||||
*
|
||||
* @return an RMI Registry
|
||||
* @throws RemoteException if there was a problem creating a Registry.
|
||||
*/
|
||||
public static Registry createRegistryOnEphemeralPort() throws RemoteException {
|
||||
return LocateRegistry.createRegistry(0);
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the port number the RMI {@link Registry} is running on.
|
||||
*
|
||||
* @param registry the registry to find the port of.
|
||||
* @return the port number the registry is using.
|
||||
* @throws RuntimeException if there was a problem getting the port number.
|
||||
*/
|
||||
public static int getRegistryPort(Registry registry) {
|
||||
int port = -1;
|
||||
|
||||
try {
|
||||
RemoteRef remoteRef = ((RegistryImpl)registry).getRef();
|
||||
LiveRef liveRef = ((UnicastServerRef)remoteRef).getLiveRef();
|
||||
Endpoint endpoint = liveRef.getChannel().getEndpoint();
|
||||
TCPEndpoint tcpEndpoint = (TCPEndpoint) endpoint;
|
||||
port = tcpEndpoint.getPort();
|
||||
} catch (Exception ex) {
|
||||
throw new RuntimeException("Error getting registry port.", ex);
|
||||
}
|
||||
|
||||
return port;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns an unused random port number which is not a reserved port. Will
|
||||
* try up to 10 times to get a random port before giving up and throwing a
|
||||
* RuntimeException.
|
||||
*
|
||||
* @return an unused random port number.
|
||||
* @throws RuntimeException if there was a problem getting a port.
|
||||
*/
|
||||
public static int getUnusedRandomPort() {
|
||||
int numTries = 0;
|
||||
IOException ex = null;
|
||||
|
||||
while (numTries++ < MAX_SERVER_SOCKET_TRIES) {
|
||||
int unusedRandomPort = -1;
|
||||
ex = null; //reset
|
||||
|
||||
try (ServerSocket ss = new ServerSocket(0)) {
|
||||
unusedRandomPort = ss.getLocalPort();
|
||||
} catch (IOException e) {
|
||||
ex = e;
|
||||
// temporarily print stack trace here until we find out why
|
||||
// tests are failing.
|
||||
System.err.println("TestLibrary.getUnusedRandomPort() caught "
|
||||
+ "exception on iteration " + numTries
|
||||
+ (numTries==MAX_SERVER_SOCKET_TRIES ? " (the final try)."
|
||||
: "."));
|
||||
ex.printStackTrace();
|
||||
}
|
||||
|
||||
if (unusedRandomPort >= 0) {
|
||||
if (isReservedPort(unusedRandomPort)) {
|
||||
System.out.println("INFO: On try # " + numTries
|
||||
+ (numTries==MAX_SERVER_SOCKET_TRIES ? ", the final try, ": ",")
|
||||
+ " ServerSocket(0) returned the reserved port "
|
||||
+ unusedRandomPort
|
||||
+ " in TestLibrary.getUnusedRandomPort() ");
|
||||
} else {
|
||||
return unusedRandomPort;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// If we're here, then either an exception was thrown or the port is
|
||||
// a reserved port.
|
||||
if (ex==null) {
|
||||
throw new RuntimeException("Error getting unused random port. The"
|
||||
+" last port returned by ServerSocket(0) was a reserved port");
|
||||
} else {
|
||||
throw new RuntimeException("Error getting unused random port.", ex);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Determines if a port is one of the reserved port numbers.
|
||||
*
|
||||
* @param port the port to test.
|
||||
* @return {@code true} if the port is a reserved port, otherwise
|
||||
* {@code false}.
|
||||
*/
|
||||
public static boolean isReservedPort(int port) {
|
||||
return ((port >= FIXED_PORT_MIN) && (port <= FIXED_PORT_MAX) ||
|
||||
(port == 1099));
|
||||
}
|
||||
|
||||
/**
|
||||
* Method to capture the stack trace of an exception and return it
|
||||
* as a string.
|
||||
*/
|
||||
public String stackTraceToString(Exception e) {
|
||||
ByteArrayOutputStream bos = new ByteArrayOutputStream();
|
||||
PrintStream ps = new PrintStream(bos);
|
||||
|
||||
e.printStackTrace(ps);
|
||||
return bos.toString();
|
||||
}
|
||||
|
||||
/** extra properties */
|
||||
private static Properties props;
|
||||
|
||||
/**
|
||||
* Returns extra test properties. Looks for the file "../../test.props"
|
||||
* and reads it in as a Properties file. Assuming the working directory
|
||||
* is "<path>/JTwork/scratch", this will find "<path>/test.props".
|
||||
*/
|
||||
private static synchronized Properties getExtraProperties() {
|
||||
if (props != null) {
|
||||
return props;
|
||||
}
|
||||
props = new Properties();
|
||||
File f = new File(".." + File.separator + ".." + File.separator +
|
||||
"test.props");
|
||||
if (!f.exists()) {
|
||||
return props;
|
||||
}
|
||||
try {
|
||||
FileInputStream in = new FileInputStream(f);
|
||||
try {
|
||||
props.load(in);
|
||||
} finally {
|
||||
in.close();
|
||||
}
|
||||
} catch (IOException e) {
|
||||
e.printStackTrace();
|
||||
throw new RuntimeException("extra property setup failed", e);
|
||||
}
|
||||
return props;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns an extra test property. Looks for the file "../../test.props"
|
||||
* and reads it in as a Properties file. Assuming the working directory
|
||||
* is "<path>/JTwork/scratch", this will find "<path>/test.props".
|
||||
* If the property isn't found, defaultVal is returned.
|
||||
*/
|
||||
public static String getExtraProperty(String property, String defaultVal) {
|
||||
return getExtraProperties().getProperty(property, defaultVal);
|
||||
}
|
||||
}
|
||||
696
test/jdk/java/rmi/testlibrary/TestLoaderHandler.java
Normal file
696
test/jdk/java/rmi/testlibrary/TestLoaderHandler.java
Normal file
|
|
@ -0,0 +1,696 @@
|
|||
/*
|
||||
* Copyright (c) 1996, 2024, Oracle and/or its affiliates. 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.
|
||||
*
|
||||
* 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.
|
||||
*/
|
||||
|
||||
import java.lang.ref.ReferenceQueue;
|
||||
import java.lang.ref.SoftReference;
|
||||
import java.lang.ref.WeakReference;
|
||||
import java.lang.reflect.Modifier;
|
||||
import java.lang.reflect.Proxy;
|
||||
import java.net.MalformedURLException;
|
||||
import java.net.URL;
|
||||
import java.net.URLClassLoader;
|
||||
import java.rmi.server.RMIClassLoaderSpi;
|
||||
import java.util.Collections;
|
||||
import java.util.HashMap;
|
||||
import java.util.IdentityHashMap;
|
||||
import java.util.Map;
|
||||
import java.util.Set;
|
||||
import java.util.StringTokenizer;
|
||||
import java.util.WeakHashMap;
|
||||
|
||||
/**
|
||||
* Derived from <code>LoaderHandler</code> to provides the implementation of the
|
||||
* static methods of the <code>java.rmi.server.RMIClassLoader</code> class.
|
||||
*
|
||||
* WARNING: this loader will load classes from codebase annotations received over the
|
||||
* wire, without performing any security checks. It is intended only for testing.
|
||||
*
|
||||
* @author Ann Wollrath
|
||||
* @author Peter Jones
|
||||
* @author Laird Dornin
|
||||
*/
|
||||
@SuppressWarnings("deprecation")
|
||||
public final class TestLoaderHandler extends RMIClassLoaderSpi {
|
||||
|
||||
/**
|
||||
* value of "java.rmi.server.codebase" property, as cached at class
|
||||
* initialization time. It may be null or contain malformed URLs.
|
||||
*/
|
||||
private static String codebaseProperty = null;
|
||||
static {
|
||||
String prop = System.getProperty("java.rmi.server.codebase");
|
||||
if (prop != null && prop.trim().length() > 0) {
|
||||
codebaseProperty = prop;
|
||||
}
|
||||
}
|
||||
|
||||
/** list of URLs represented by the codebase property, if valid */
|
||||
private static URL[] codebaseURLs = null;
|
||||
|
||||
/** table of class loaders that use codebase property for annotation */
|
||||
private static final Set<ClassLoader> codebaseLoaders =
|
||||
Collections.synchronizedSet(Collections.newSetFromMap(new IdentityHashMap<>(5)));
|
||||
static {
|
||||
for (ClassLoader codebaseLoader = ClassLoader.getSystemClassLoader();
|
||||
codebaseLoader != null;
|
||||
codebaseLoader = codebaseLoader.getParent())
|
||||
{
|
||||
codebaseLoaders.add(codebaseLoader);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* table mapping codebase URL path and context class loader pairs
|
||||
* to class loader instances. Entries hold class loaders with weak
|
||||
* references, so this table does not prevent loaders from being
|
||||
* garbage collected.
|
||||
*/
|
||||
private static final HashMap<LoaderKey, LoaderEntry> loaderTable
|
||||
= new HashMap<>(5);
|
||||
|
||||
/** reference queue for cleared class loader entries */
|
||||
private static final ReferenceQueue<Loader> refQueue = new ReferenceQueue<>();
|
||||
|
||||
public TestLoaderHandler() {
|
||||
System.err.println("*** TestLoaderHandler created ***");
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns an array of URLs initialized with the value of the
|
||||
* java.rmi.server.codebase property as the URL path.
|
||||
*/
|
||||
private static synchronized URL[] getDefaultCodebaseURLs()
|
||||
throws MalformedURLException
|
||||
{
|
||||
/*
|
||||
* If it hasn't already been done, convert the codebase property
|
||||
* into an array of URLs; this may throw a MalformedURLException.
|
||||
*/
|
||||
if (codebaseURLs == null) {
|
||||
if (codebaseProperty != null) {
|
||||
codebaseURLs = pathToURLs(codebaseProperty);
|
||||
} else {
|
||||
codebaseURLs = new URL[0];
|
||||
}
|
||||
}
|
||||
return codebaseURLs;
|
||||
}
|
||||
|
||||
/**
|
||||
* Load a class from a network location (one or more URLs),
|
||||
* but first try to resolve the named class through the given
|
||||
* "default loader".
|
||||
*/
|
||||
public Class<?> loadClass(String codebase, String name,
|
||||
ClassLoader defaultLoader)
|
||||
throws MalformedURLException, ClassNotFoundException
|
||||
{
|
||||
URL[] urls;
|
||||
if (codebase != null) {
|
||||
urls = pathToURLs(codebase);
|
||||
} else {
|
||||
urls = getDefaultCodebaseURLs();
|
||||
}
|
||||
|
||||
if (defaultLoader != null) {
|
||||
try {
|
||||
return Class.forName(name, false, defaultLoader);
|
||||
} catch (ClassNotFoundException e) {
|
||||
}
|
||||
}
|
||||
|
||||
return loadClass(urls, name);
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the class annotation (representing the location for
|
||||
* a class) that RMI will use to annotate the call stream when
|
||||
* marshalling objects of the given class.
|
||||
*/
|
||||
public String getClassAnnotation(Class<?> cl) {
|
||||
String name = cl.getName();
|
||||
|
||||
/*
|
||||
* Class objects for arrays of primitive types never need an
|
||||
* annotation, because they never need to be (or can be) downloaded.
|
||||
*
|
||||
* REMIND: should we (not) be annotating classes that are in
|
||||
* "java.*" packages?
|
||||
*/
|
||||
int nameLength = name.length();
|
||||
if (nameLength > 0 && name.charAt(0) == '[') {
|
||||
// skip past all '[' characters (see bugid 4211906)
|
||||
int i = 1;
|
||||
while (nameLength > i && name.charAt(i) == '[') {
|
||||
i++;
|
||||
}
|
||||
if (nameLength > i && name.charAt(i) != 'L') {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
/*
|
||||
* Get the class's class loader. If it is null, the system class
|
||||
* loader, an ancestor of the base class loader (such as the loader
|
||||
* for installed extensions), return the value of the
|
||||
* "java.rmi.server.codebase" property.
|
||||
*/
|
||||
ClassLoader loader = cl.getClassLoader();
|
||||
if (loader == null || codebaseLoaders.contains(loader)) {
|
||||
return codebaseProperty;
|
||||
}
|
||||
|
||||
/*
|
||||
* Get the codebase URL path for the class loader, if it supports
|
||||
* such a notion (i.e., if it is a URLClassLoader or subclass).
|
||||
*/
|
||||
String annotation = null;
|
||||
if (loader instanceof Loader) {
|
||||
/*
|
||||
* If the class loader is one of our RMI class loaders, we have
|
||||
* already computed the class annotation string, and no
|
||||
* permissions are required to know the URLs.
|
||||
*/
|
||||
annotation = ((Loader) loader).getClassAnnotation();
|
||||
|
||||
} else if (loader instanceof URLClassLoader) {
|
||||
URL[] urls = ((URLClassLoader) loader).getURLs();
|
||||
if (urls != null) {
|
||||
annotation = urlsToPath(urls);
|
||||
}
|
||||
}
|
||||
|
||||
if (annotation != null) {
|
||||
return annotation;
|
||||
} else {
|
||||
return codebaseProperty; // REMIND: does this make sense??
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns a classloader that loads classes from the given codebase URL
|
||||
* path. The parent classloader of the returned classloader is the
|
||||
* context class loader.
|
||||
*/
|
||||
public ClassLoader getClassLoader(String codebase)
|
||||
throws MalformedURLException
|
||||
{
|
||||
ClassLoader parent = getRMIContextClassLoader();
|
||||
|
||||
URL[] urls;
|
||||
if (codebase != null) {
|
||||
urls = pathToURLs(codebase);
|
||||
} else {
|
||||
urls = getDefaultCodebaseURLs();
|
||||
}
|
||||
|
||||
return lookupLoader(urls, parent);
|
||||
}
|
||||
|
||||
/**
|
||||
* Return the security context of the given class loader.
|
||||
*/
|
||||
public static Object getSecurityContext(ClassLoader loader) {
|
||||
/*
|
||||
* REMIND: This is a bogus JDK1.1-compatible implementation.
|
||||
* This method should never be called by application code anyway
|
||||
* (hence the deprecation), but should it do something different
|
||||
* and perhaps more useful, like return a String or a URL[]?
|
||||
*/
|
||||
if (loader instanceof Loader) {
|
||||
URL[] urls = ((Loader) loader).getURLs();
|
||||
if (urls.length > 0) {
|
||||
return urls[0];
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Register a class loader as one whose classes should always be
|
||||
* annotated with the value of the "java.rmi.server.codebase" property.
|
||||
*/
|
||||
public static void registerCodebaseLoader(ClassLoader loader) {
|
||||
codebaseLoaders.add(loader);
|
||||
}
|
||||
|
||||
/**
|
||||
* Load a class from the RMI class loader corresponding to the given
|
||||
* codebase URL path in the current execution context.
|
||||
*/
|
||||
private Class<?> loadClass(URL[] urls, String name)
|
||||
throws ClassNotFoundException
|
||||
{
|
||||
ClassLoader parent = getRMIContextClassLoader();
|
||||
|
||||
/*
|
||||
* Get or create the RMI class loader for this codebase URL path
|
||||
* and parent class loader pair.
|
||||
*/
|
||||
Loader loader = lookupLoader(urls, parent);
|
||||
|
||||
return Class.forName(name, false, loader);
|
||||
}
|
||||
|
||||
/**
|
||||
* Define and return a dynamic proxy class in a class loader with
|
||||
* URLs supplied in the given location. The proxy class will
|
||||
* implement interface classes named by the given array of
|
||||
* interface names.
|
||||
*/
|
||||
public Class<?> loadProxyClass(String codebase, String[] interfaces,
|
||||
ClassLoader defaultLoader)
|
||||
throws MalformedURLException, ClassNotFoundException
|
||||
{
|
||||
/*
|
||||
* This method uses a fairly complex algorithm to load the
|
||||
* proxy class and its interface classes in order to maximize
|
||||
* the likelihood that the proxy's codebase annotation will be
|
||||
* preserved. The algorithm is (assuming that all of the
|
||||
* proxy interface classes are public):
|
||||
*
|
||||
* If the default loader is not null, try to load the proxy
|
||||
* interfaces through that loader. If the interfaces can be
|
||||
* loaded in that loader, try to define the proxy class in an
|
||||
* RMI class loader (child of the context class loader) before
|
||||
* trying to define the proxy in the default loader. If the
|
||||
* attempt to define the proxy class succeeds, the codebase
|
||||
* annotation is preserved. If the attempt fails, try to
|
||||
* define the proxy class in the default loader.
|
||||
*
|
||||
* If the interface classes can not be loaded from the default
|
||||
* loader or the default loader is null, try to load them from
|
||||
* the RMI class loader. Then try to define the proxy class
|
||||
* in the RMI class loader.
|
||||
*
|
||||
* Additionally, if any of the proxy interface classes are not
|
||||
* public, all of the non-public interfaces must reside in the
|
||||
* same class loader or it will be impossible to define the
|
||||
* proxy class (an IllegalAccessError will be thrown). An
|
||||
* attempt to load the interfaces from the default loader is
|
||||
* made. If the attempt fails, a second attempt will be made
|
||||
* to load the interfaces from the RMI loader. If all of the
|
||||
* non-public interfaces classes do reside in the same class
|
||||
* loader, then we attempt to define the proxy class in the
|
||||
* class loader of the non-public interfaces. No other
|
||||
* attempt to define the proxy class will be made.
|
||||
*/
|
||||
ClassLoader parent = getRMIContextClassLoader();
|
||||
|
||||
URL[] urls;
|
||||
if (codebase != null) {
|
||||
urls = pathToURLs(codebase);
|
||||
} else {
|
||||
urls = getDefaultCodebaseURLs();
|
||||
}
|
||||
|
||||
/*
|
||||
* Get or create the RMI class loader for this codebase URL path
|
||||
* and parent class loader pair.
|
||||
*/
|
||||
Loader loader = lookupLoader(urls, parent);
|
||||
|
||||
return loadProxyClass(interfaces, defaultLoader, loader, true);
|
||||
}
|
||||
|
||||
/**
|
||||
* Define a proxy class in the default loader if appropriate.
|
||||
* Define the class in an RMI class loader otherwise. The proxy
|
||||
* class will implement classes which are named in the supplied
|
||||
* interfaceNames.
|
||||
*/
|
||||
private Class<?> loadProxyClass(String[] interfaceNames,
|
||||
ClassLoader defaultLoader,
|
||||
ClassLoader codebaseLoader,
|
||||
boolean preferCodebase)
|
||||
throws ClassNotFoundException
|
||||
{
|
||||
ClassLoader proxyLoader = null;
|
||||
Class<?>[] classObjs = new Class<?>[interfaceNames.length];
|
||||
boolean[] nonpublic = { false };
|
||||
|
||||
defaultLoaderCase:
|
||||
if (defaultLoader != null) {
|
||||
try {
|
||||
proxyLoader =
|
||||
loadProxyInterfaces(interfaceNames, defaultLoader,
|
||||
classObjs, nonpublic);
|
||||
} catch (ClassNotFoundException e) {
|
||||
break defaultLoaderCase;
|
||||
}
|
||||
if (!nonpublic[0]) {
|
||||
if (preferCodebase) {
|
||||
try {
|
||||
return Proxy.getProxyClass(codebaseLoader, classObjs);
|
||||
} catch (IllegalArgumentException e) {
|
||||
}
|
||||
}
|
||||
proxyLoader = defaultLoader;
|
||||
}
|
||||
return loadProxyClass(proxyLoader, classObjs);
|
||||
}
|
||||
|
||||
nonpublic[0] = false;
|
||||
proxyLoader = loadProxyInterfaces(interfaceNames, codebaseLoader,
|
||||
classObjs, nonpublic);
|
||||
if (!nonpublic[0]) {
|
||||
proxyLoader = codebaseLoader;
|
||||
}
|
||||
return loadProxyClass(proxyLoader, classObjs);
|
||||
}
|
||||
|
||||
/**
|
||||
* Define a proxy class in the given class loader. The proxy
|
||||
* class will implement the given interfaces Classes.
|
||||
*/
|
||||
private Class<?> loadProxyClass(ClassLoader loader, Class<?>[] interfaces)
|
||||
throws ClassNotFoundException
|
||||
{
|
||||
try {
|
||||
return Proxy.getProxyClass(loader, interfaces);
|
||||
} catch (IllegalArgumentException e) {
|
||||
throw new ClassNotFoundException(
|
||||
"error creating dynamic proxy class", e);
|
||||
}
|
||||
}
|
||||
|
||||
/*
|
||||
* Load Class objects for the names in the interfaces array from
|
||||
* the given class loader.
|
||||
*
|
||||
* We pass classObjs and nonpublic arrays to avoid needing a
|
||||
* multi-element return value. nonpublic is an array to enable
|
||||
* the method to take a boolean argument by reference.
|
||||
*
|
||||
* nonpublic array is needed to signal when the return value of
|
||||
* this method should be used as the proxy class loader. Because
|
||||
* null represents a valid class loader, that value is
|
||||
* insufficient to signal that the return value should not be used
|
||||
* as the proxy class loader.
|
||||
*/
|
||||
private static ClassLoader loadProxyInterfaces(String[] interfaces,
|
||||
ClassLoader loader,
|
||||
Class<?>[] classObjs,
|
||||
boolean[] nonpublic)
|
||||
throws ClassNotFoundException
|
||||
{
|
||||
/* loader of a non-public interface class */
|
||||
ClassLoader nonpublicLoader = null;
|
||||
|
||||
for (int i = 0; i < interfaces.length; i++) {
|
||||
Class<?> cl =
|
||||
(classObjs[i] = Class.forName(interfaces[i], false, loader));
|
||||
|
||||
if (!Modifier.isPublic(cl.getModifiers())) {
|
||||
ClassLoader current = cl.getClassLoader();
|
||||
if (!nonpublic[0]) {
|
||||
nonpublicLoader = current;
|
||||
nonpublic[0] = true;
|
||||
} else if (current != nonpublicLoader) {
|
||||
throw new IllegalAccessError(
|
||||
"non-public interfaces defined in different " +
|
||||
"class loaders");
|
||||
}
|
||||
}
|
||||
}
|
||||
return nonpublicLoader;
|
||||
}
|
||||
|
||||
/**
|
||||
* Convert a string containing a space-separated list of URLs into a
|
||||
* corresponding array of URL objects, throwing a MalformedURLException
|
||||
* if any of the URLs are invalid.
|
||||
*/
|
||||
private static URL[] pathToURLs(String path)
|
||||
throws MalformedURLException
|
||||
{
|
||||
synchronized (pathToURLsCache) {
|
||||
Object[] v = pathToURLsCache.get(path);
|
||||
if (v != null) {
|
||||
return ((URL[])v[0]);
|
||||
}
|
||||
}
|
||||
StringTokenizer st = new StringTokenizer(path); // divide by spaces
|
||||
URL[] urls = new URL[st.countTokens()];
|
||||
for (int i = 0; st.hasMoreTokens(); i++) {
|
||||
@SuppressWarnings("deprecation")
|
||||
var url = new URL(st.nextToken());
|
||||
urls[i] = url;
|
||||
}
|
||||
synchronized (pathToURLsCache) {
|
||||
pathToURLsCache.put(path,
|
||||
new Object[] {urls, new SoftReference<String>(path)});
|
||||
}
|
||||
return urls;
|
||||
}
|
||||
|
||||
/** map from weak(key=string) to [URL[], soft(key)] */
|
||||
private static final Map<String, Object[]> pathToURLsCache
|
||||
= new WeakHashMap<>(5);
|
||||
|
||||
/**
|
||||
* Convert an array of URL objects into a corresponding string
|
||||
* containing a space-separated list of URLs.
|
||||
*
|
||||
* Note that if the array has zero elements, the return value is
|
||||
* null, not the empty string.
|
||||
*/
|
||||
private static String urlsToPath(URL[] urls) {
|
||||
if (urls.length == 0) {
|
||||
return null;
|
||||
} else if (urls.length == 1) {
|
||||
return urls[0].toExternalForm();
|
||||
} else {
|
||||
StringBuilder path = new StringBuilder(urls[0].toExternalForm());
|
||||
for (int i = 1; i < urls.length; i++) {
|
||||
path.append(' ');
|
||||
path.append(urls[i].toExternalForm());
|
||||
}
|
||||
return path.toString();
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Return the class loader to be used as the parent for an RMI class
|
||||
* loader used in the current execution context.
|
||||
*/
|
||||
private static ClassLoader getRMIContextClassLoader() {
|
||||
/*
|
||||
* The current implementation simply uses the current thread's
|
||||
* context class loader.
|
||||
*/
|
||||
return Thread.currentThread().getContextClassLoader();
|
||||
}
|
||||
|
||||
/**
|
||||
* Look up the RMI class loader for the given codebase URL path
|
||||
* and the given parent class loader. A new class loader instance
|
||||
* will be created and returned if no match is found.
|
||||
*/
|
||||
@SuppressWarnings("removal")
|
||||
private static Loader lookupLoader(final URL[] urls,
|
||||
final ClassLoader parent)
|
||||
{
|
||||
/*
|
||||
* If the requested codebase URL path is empty, the supplied
|
||||
* parent class loader will be sufficient.
|
||||
*
|
||||
* REMIND: To be conservative, this optimization is commented out
|
||||
* for now so that it does not open a security hole in the future
|
||||
* by providing untrusted code with direct access to the public
|
||||
* loadClass() method of a class loader instance that it cannot
|
||||
* get a reference to. (It's an unlikely optimization anyway.)
|
||||
*
|
||||
* if (urls.length == 0) {
|
||||
* return parent;
|
||||
* }
|
||||
*/
|
||||
|
||||
LoaderEntry entry;
|
||||
Loader loader;
|
||||
|
||||
synchronized (TestLoaderHandler.class) {
|
||||
/*
|
||||
* Take this opportunity to remove from the table entries
|
||||
* whose weak references have been cleared.
|
||||
*/
|
||||
while ((entry = (LoaderEntry) refQueue.poll()) != null) {
|
||||
if (!entry.removed) { // ignore entries removed below
|
||||
loaderTable.remove(entry.key);
|
||||
}
|
||||
}
|
||||
|
||||
/*
|
||||
* Look up the codebase URL path and parent class loader pair
|
||||
* in the table of RMI class loaders.
|
||||
*/
|
||||
LoaderKey key = new LoaderKey(urls, parent);
|
||||
entry = loaderTable.get(key);
|
||||
|
||||
if (entry == null || (loader = entry.get()) == null) {
|
||||
/*
|
||||
* If entry was in table but it's weak reference was cleared,
|
||||
* remove it from the table and mark it as explicitly cleared,
|
||||
* so that new matching entry that we put in the table will
|
||||
* not be erroneously removed when this entry is processed
|
||||
* from the weak reference queue.
|
||||
*/
|
||||
if (entry != null) {
|
||||
loaderTable.remove(key);
|
||||
entry.removed = true;
|
||||
}
|
||||
|
||||
/*
|
||||
* A matching loader was not found, so create a new class
|
||||
* loader instance for the requested codebase URL path and
|
||||
* parent class loader. The instance is created within an
|
||||
* access control context restricted to the permissions
|
||||
* necessary to load classes from its codebase URL path.
|
||||
*/
|
||||
loader = new Loader(urls, parent);
|
||||
|
||||
/*
|
||||
* Finally, create an entry to hold the new loader with a
|
||||
* weak reference and store it in the table with the key.
|
||||
*/
|
||||
entry = new LoaderEntry(key, loader);
|
||||
loaderTable.put(key, entry);
|
||||
}
|
||||
}
|
||||
|
||||
return loader;
|
||||
}
|
||||
|
||||
/**
|
||||
* LoaderKey holds a codebase URL path and parent class loader pair
|
||||
* used to look up RMI class loader instances in its class loader cache.
|
||||
*/
|
||||
private static class LoaderKey {
|
||||
|
||||
private URL[] urls;
|
||||
|
||||
private ClassLoader parent;
|
||||
|
||||
private int hashValue;
|
||||
|
||||
public LoaderKey(URL[] urls, ClassLoader parent) {
|
||||
this.urls = urls;
|
||||
this.parent = parent;
|
||||
|
||||
if (parent != null) {
|
||||
hashValue = parent.hashCode();
|
||||
}
|
||||
for (int i = 0; i < urls.length; i++) {
|
||||
hashValue ^= urls[i].hashCode();
|
||||
}
|
||||
}
|
||||
|
||||
public int hashCode() {
|
||||
return hashValue;
|
||||
}
|
||||
|
||||
public boolean equals(Object obj) {
|
||||
if (obj instanceof LoaderKey) {
|
||||
LoaderKey other = (LoaderKey) obj;
|
||||
if (parent != other.parent) {
|
||||
return false;
|
||||
}
|
||||
if (urls == other.urls) {
|
||||
return true;
|
||||
}
|
||||
if (urls.length != other.urls.length) {
|
||||
return false;
|
||||
}
|
||||
for (int i = 0; i < urls.length; i++) {
|
||||
if (!urls[i].equals(other.urls[i])) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
return true;
|
||||
} else {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* LoaderEntry contains a weak reference to an RMIClassLoader. The
|
||||
* weak reference is registered with the private static "refQueue"
|
||||
* queue. The entry contains the codebase URL path and parent class
|
||||
* loader key for the loader so that the mapping can be removed from
|
||||
* the table efficiently when the weak reference is cleared.
|
||||
*/
|
||||
private static class LoaderEntry extends WeakReference<Loader> {
|
||||
|
||||
public LoaderKey key;
|
||||
|
||||
/**
|
||||
* set to true if the entry has been removed from the table
|
||||
* because it has been replaced, so it should not be attempted
|
||||
* to be removed again
|
||||
*/
|
||||
public boolean removed = false;
|
||||
|
||||
public LoaderEntry(LoaderKey key, Loader loader) {
|
||||
super(loader, refQueue);
|
||||
this.key = key;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Loader is the actual class of the RMI class loaders created
|
||||
* by the RMIClassLoader static methods.
|
||||
*/
|
||||
private static class Loader extends URLClassLoader {
|
||||
|
||||
/** string form of loader's codebase URL path, also an optimization */
|
||||
private String annotation;
|
||||
|
||||
private Loader(URL[] urls, ClassLoader parent) {
|
||||
super(urls, parent);
|
||||
|
||||
/*
|
||||
* Caching the value of class annotation string here assumes
|
||||
* that the protected method addURL() is never called on this
|
||||
* class loader.
|
||||
*/
|
||||
annotation = urlsToPath(urls);
|
||||
}
|
||||
|
||||
/**
|
||||
* Return the string to be annotated with all classes loaded from
|
||||
* this class loader.
|
||||
*/
|
||||
public String getClassAnnotation() {
|
||||
return annotation;
|
||||
}
|
||||
|
||||
/**
|
||||
* Return a string representation of this loader (useful for
|
||||
* debugging).
|
||||
*/
|
||||
public String toString() {
|
||||
return super.toString() + "[\"" + annotation + "\"]";
|
||||
}
|
||||
}
|
||||
}
|
||||
79
test/jdk/java/rmi/testlibrary/TestParams.java
Normal file
79
test/jdk/java/rmi/testlibrary/TestParams.java
Normal file
|
|
@ -0,0 +1,79 @@
|
|||
/*
|
||||
* Copyright (c) 1998, 2021, Oracle and/or its affiliates. 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.
|
||||
*
|
||||
* 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.
|
||||
*/
|
||||
|
||||
/**
|
||||
*
|
||||
*/
|
||||
import java.io.File;
|
||||
|
||||
/**
|
||||
* Setup static variables to represent properties in test environment.
|
||||
*/
|
||||
public class TestParams {
|
||||
|
||||
/** variables that hold value property values */
|
||||
public static final String testSrc;
|
||||
public static final String testClasses;
|
||||
public static final String testClassPath;
|
||||
|
||||
/** name of default security policy for test JVM */
|
||||
public static final String defaultPolicy;
|
||||
|
||||
/** name of default security policy for RegistryVM */
|
||||
public static final String defaultRegistryPolicy;
|
||||
|
||||
/** name of default security manager */
|
||||
public static final String defaultSecurityManager;
|
||||
|
||||
/** VM options string */
|
||||
public static final String testVmOpts;
|
||||
|
||||
/** Java options string */
|
||||
public static final String testJavaOpts;
|
||||
|
||||
/* Initalize commonly used strings */
|
||||
static {
|
||||
testSrc = TestLibrary.getProperty("test.src", ".");
|
||||
testClasses = TestLibrary.getProperty("test.classes", ".");
|
||||
testClassPath = TestLibrary.getProperty("test.class.path", ".");
|
||||
|
||||
String dp = TestLibrary.getProperty("java.security.policy", null);
|
||||
if (dp == null) {
|
||||
dp = testSrc + File.separatorChar + "security.policy";
|
||||
}
|
||||
defaultPolicy = dp;
|
||||
|
||||
defaultRegistryPolicy =
|
||||
testSrc + File.separatorChar + "registry.security.policy";
|
||||
|
||||
String tmp = TestLibrary.getProperty("java.security.manager", null);
|
||||
if (tmp == null || tmp.equals("allow")) {
|
||||
tmp = "java.lang.SecurityManager";
|
||||
}
|
||||
defaultSecurityManager = tmp;
|
||||
|
||||
testVmOpts = TestLibrary.getProperty("test.vm.opts", "");
|
||||
|
||||
testJavaOpts = TestLibrary.getProperty("test.java.opts", "");
|
||||
}
|
||||
}
|
||||
844
test/jdk/java/rmi/testlibrary/TestSocketFactory.java
Normal file
844
test/jdk/java/rmi/testlibrary/TestSocketFactory.java
Normal file
|
|
@ -0,0 +1,844 @@
|
|||
/*
|
||||
* Copyright (c) 2017, 2019, Oracle and/or its affiliates. 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.
|
||||
*
|
||||
* 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.
|
||||
*/
|
||||
|
||||
import java.io.ByteArrayOutputStream;
|
||||
import java.io.FilterInputStream;
|
||||
import java.io.IOException;
|
||||
import java.io.InputStream;
|
||||
import java.io.OutputStream;
|
||||
import java.io.Serializable;
|
||||
import java.net.InetAddress;
|
||||
import java.net.ServerSocket;
|
||||
import java.net.Socket;
|
||||
import java.net.SocketAddress;
|
||||
import java.net.SocketException;
|
||||
import java.net.SocketOption;
|
||||
import java.nio.channels.ServerSocketChannel;
|
||||
import java.nio.channels.SocketChannel;
|
||||
import java.rmi.server.RMIClientSocketFactory;
|
||||
import java.rmi.server.RMIServerSocketFactory;
|
||||
import java.rmi.server.RMISocketFactory;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Arrays;
|
||||
import java.util.List;
|
||||
import java.util.Objects;
|
||||
import java.util.Set;
|
||||
|
||||
import org.testng.Assert;
|
||||
import org.testng.annotations.Test;
|
||||
import org.testng.annotations.DataProvider;
|
||||
|
||||
/*
|
||||
* @test
|
||||
* @summary TestSocket Factory and tests of the basic trigger, match, and replace functions
|
||||
* @run testng TestSocketFactory
|
||||
* @bug 8186539
|
||||
*/
|
||||
|
||||
/**
|
||||
* A RMISocketFactory utility factory to log RMI stream contents and to
|
||||
* trigger, and then match and replace output stream contents to simulate failures.
|
||||
* <p>
|
||||
* The trigger is a sequence of bytes that must be found before looking
|
||||
* for the bytes to match and replace. If the trigger sequence is empty
|
||||
* matching is immediately enabled. While waiting for the trigger to be found
|
||||
* bytes written to the streams are written through to the output stream.
|
||||
* The when triggered and when a trigger is non-empty, matching looks for
|
||||
* the sequence of bytes supplied. If the sequence is empty, no matching or
|
||||
* replacement is performed.
|
||||
* While waiting for a complete match, the partial matched bytes are not
|
||||
* written to the output stream. When the match is incomplete, the partial
|
||||
* matched bytes are written to the output. When a match is complete the
|
||||
* full replacement byte array is written to the output.
|
||||
* <p>
|
||||
* The trigger, match, and replacement bytes arrays can be changed at any
|
||||
* time and immediately reset and restart matching. Changes are propagated
|
||||
* to all of the sockets created from the factories immediately.
|
||||
*/
|
||||
public class TestSocketFactory extends RMISocketFactory
|
||||
implements RMIClientSocketFactory, RMIServerSocketFactory, Serializable {
|
||||
|
||||
private static final long serialVersionUID = 1L;
|
||||
|
||||
private volatile transient byte[] triggerBytes;
|
||||
|
||||
private volatile transient byte[] matchBytes;
|
||||
|
||||
private volatile transient byte[] replaceBytes;
|
||||
|
||||
private transient final List<InterposeSocket> sockets = new ArrayList<>();
|
||||
|
||||
private transient final List<InterposeServerSocket> serverSockets = new ArrayList<>();
|
||||
|
||||
static final byte[] EMPTY_BYTE_ARRAY = new byte[0];
|
||||
|
||||
// True to enable logging of matches and replacements.
|
||||
private static volatile boolean debugLogging = false;
|
||||
|
||||
/**
|
||||
* Debugging output can be synchronized with logging of RMI actions.
|
||||
*
|
||||
* @param format a printf format
|
||||
* @param args any args
|
||||
*/
|
||||
public static void DEBUG(String format, Object... args) {
|
||||
if (debugLogging) {
|
||||
System.err.printf(format, args);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Create a socket factory that creates InputStreams
|
||||
* and OutputStreams that log.
|
||||
*/
|
||||
public TestSocketFactory() {
|
||||
this.triggerBytes = EMPTY_BYTE_ARRAY;
|
||||
this.matchBytes = EMPTY_BYTE_ARRAY;
|
||||
this.replaceBytes = EMPTY_BYTE_ARRAY;
|
||||
}
|
||||
|
||||
/**
|
||||
* Set debug to true to generate logging output of matches and substitutions.
|
||||
* @param debug {@code true} to generate logging output
|
||||
* @return the previous value
|
||||
*/
|
||||
public static boolean setDebug(boolean debug) {
|
||||
boolean oldDebug = debugLogging;
|
||||
debugLogging = debug;
|
||||
return oldDebug;
|
||||
}
|
||||
|
||||
/**
|
||||
* Set the match and replacement bytes, with an empty trigger.
|
||||
* The match and replacements are propagated to all existing sockets.
|
||||
*
|
||||
* @param matchBytes bytes to match
|
||||
* @param replaceBytes bytes to replace the matched bytes
|
||||
*/
|
||||
public void setMatchReplaceBytes(byte[] matchBytes, byte[] replaceBytes) {
|
||||
setMatchReplaceBytes(EMPTY_BYTE_ARRAY, matchBytes, replaceBytes);
|
||||
}
|
||||
|
||||
/**
|
||||
* Set the trigger, match, and replacement bytes.
|
||||
* The trigger, match, and replacements are propagated to all existing sockets.
|
||||
*
|
||||
* @param triggerBytes array of bytes to use as a trigger, may be zero length
|
||||
* @param matchBytes bytes to match after the trigger has been seen
|
||||
* @param replaceBytes bytes to replace the matched bytes
|
||||
*/
|
||||
public synchronized void setMatchReplaceBytes(byte[] triggerBytes, byte[] matchBytes,
|
||||
byte[] replaceBytes) {
|
||||
this.triggerBytes = Objects.requireNonNull(triggerBytes, "triggerBytes");
|
||||
this.matchBytes = Objects.requireNonNull(matchBytes, "matchBytes");
|
||||
this.replaceBytes = Objects.requireNonNull(replaceBytes, "replaceBytes");
|
||||
sockets.forEach( s -> s.setMatchReplaceBytes(triggerBytes, matchBytes,
|
||||
replaceBytes));
|
||||
serverSockets.forEach( s -> s.setMatchReplaceBytes(triggerBytes, matchBytes,
|
||||
replaceBytes));
|
||||
}
|
||||
|
||||
@Override
|
||||
public synchronized Socket createSocket(String host, int port) throws IOException {
|
||||
Socket socket = RMISocketFactory.getDefaultSocketFactory()
|
||||
.createSocket(host, port);
|
||||
InterposeSocket s = new InterposeSocket(socket,
|
||||
triggerBytes, matchBytes, replaceBytes);
|
||||
sockets.add(s);
|
||||
return s;
|
||||
}
|
||||
|
||||
/**
|
||||
* Return the current list of sockets.
|
||||
* @return Return a snapshot of the current list of sockets
|
||||
*/
|
||||
public synchronized List<InterposeSocket> getSockets() {
|
||||
List<InterposeSocket> snap = new ArrayList<>(sockets);
|
||||
return snap;
|
||||
}
|
||||
|
||||
@Override
|
||||
public synchronized ServerSocket createServerSocket(int port) throws IOException {
|
||||
|
||||
ServerSocket serverSocket = RMISocketFactory.getDefaultSocketFactory()
|
||||
.createServerSocket(port);
|
||||
InterposeServerSocket ss = new InterposeServerSocket(serverSocket,
|
||||
triggerBytes, matchBytes, replaceBytes);
|
||||
serverSockets.add(ss);
|
||||
return ss;
|
||||
}
|
||||
|
||||
/**
|
||||
* Return the current list of server sockets.
|
||||
* @return Return a snapshot of the current list of server sockets
|
||||
*/
|
||||
public synchronized List<InterposeServerSocket> getServerSockets() {
|
||||
List<InterposeServerSocket> snap = new ArrayList<>(serverSockets);
|
||||
return snap;
|
||||
}
|
||||
|
||||
/**
|
||||
* An InterposeSocket wraps a socket that produces InputStreams
|
||||
* and OutputStreams that log the traffic.
|
||||
* The OutputStreams it produces watch for a trigger and then
|
||||
* match an array of bytes and replace them.
|
||||
* Useful for injecting protocol and content errors.
|
||||
*/
|
||||
public static class InterposeSocket extends Socket {
|
||||
private final Socket socket;
|
||||
private InputStream in;
|
||||
private MatchReplaceOutputStream out;
|
||||
private volatile byte[] triggerBytes;
|
||||
private volatile byte[] matchBytes;
|
||||
private volatile byte[] replaceBytes;
|
||||
private final ByteArrayOutputStream inLogStream;
|
||||
private final ByteArrayOutputStream outLogStream;
|
||||
private final String name;
|
||||
private static volatile int num = 0; // index for created Interpose509s
|
||||
|
||||
/**
|
||||
* Construct a socket that interposes on a socket to match and replace.
|
||||
* The trigger is empty.
|
||||
* @param socket the underlying socket
|
||||
* @param matchBytes the bytes that must match
|
||||
* @param replaceBytes the replacement bytes
|
||||
*/
|
||||
public InterposeSocket(Socket socket, byte[] matchBytes, byte[] replaceBytes) {
|
||||
this(socket, EMPTY_BYTE_ARRAY, matchBytes, replaceBytes);
|
||||
}
|
||||
|
||||
/**
|
||||
* Construct a socket that interposes on a socket to match and replace.
|
||||
* @param socket the underlying socket
|
||||
* @param triggerBytes array of bytes to enable matching
|
||||
* @param matchBytes the bytes that must match
|
||||
* @param replaceBytes the replacement bytes
|
||||
*/
|
||||
public InterposeSocket(Socket socket, byte[]
|
||||
triggerBytes, byte[] matchBytes, byte[] replaceBytes) {
|
||||
this.socket = socket;
|
||||
this.triggerBytes = Objects.requireNonNull(triggerBytes, "triggerBytes");
|
||||
this.matchBytes = Objects.requireNonNull(matchBytes, "matchBytes");
|
||||
this.replaceBytes = Objects.requireNonNull(replaceBytes, "replaceBytes");
|
||||
this.inLogStream = new ByteArrayOutputStream();
|
||||
this.outLogStream = new ByteArrayOutputStream();
|
||||
this.name = "IS" + ++num + "::"
|
||||
+ Thread.currentThread().getName() + ": "
|
||||
+ socket.getLocalPort() + " < " + socket.getPort();
|
||||
}
|
||||
|
||||
/**
|
||||
* Set the match and replacement bytes, with an empty trigger.
|
||||
* The match and replacements are propagated to all existing sockets.
|
||||
*
|
||||
* @param matchBytes bytes to match
|
||||
* @param replaceBytes bytes to replace the matched bytes
|
||||
*/
|
||||
public void setMatchReplaceBytes(byte[] matchBytes, byte[] replaceBytes) {
|
||||
this.setMatchReplaceBytes(EMPTY_BYTE_ARRAY, matchBytes, replaceBytes);
|
||||
}
|
||||
|
||||
/**
|
||||
* Set the trigger, match, and replacement bytes.
|
||||
* The trigger, match, and replacements are propagated to the
|
||||
* MatchReplaceOutputStream, if it has been created.
|
||||
*
|
||||
* @param triggerBytes array of bytes to use as a trigger, may be zero length
|
||||
* @param matchBytes bytes to match after the trigger has been seen
|
||||
* @param replaceBytes bytes to replace the matched bytes
|
||||
*/
|
||||
public synchronized void setMatchReplaceBytes(byte[] triggerBytes, byte[] matchBytes,
|
||||
byte[] replaceBytes) {
|
||||
this.triggerBytes = triggerBytes;
|
||||
this.matchBytes = matchBytes;
|
||||
this.replaceBytes = replaceBytes;
|
||||
if (out != null) {
|
||||
out.setMatchReplaceBytes(triggerBytes, matchBytes, replaceBytes);
|
||||
} else {
|
||||
DEBUG("InterposeSocket.setMatchReplaceBytes with out == null%n");
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public void connect(SocketAddress endpoint) throws IOException {
|
||||
socket.connect(endpoint);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void connect(SocketAddress endpoint, int timeout) throws IOException {
|
||||
socket.connect(endpoint, timeout);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void bind(SocketAddress bindpoint) throws IOException {
|
||||
socket.bind(bindpoint);
|
||||
}
|
||||
|
||||
@Override
|
||||
public InetAddress getInetAddress() {
|
||||
return socket.getInetAddress();
|
||||
}
|
||||
|
||||
@Override
|
||||
public InetAddress getLocalAddress() {
|
||||
return socket.getLocalAddress();
|
||||
}
|
||||
|
||||
@Override
|
||||
public int getPort() {
|
||||
return socket.getPort();
|
||||
}
|
||||
|
||||
@Override
|
||||
public int getLocalPort() {
|
||||
return socket.getLocalPort();
|
||||
}
|
||||
|
||||
@Override
|
||||
public SocketAddress getRemoteSocketAddress() {
|
||||
return socket.getRemoteSocketAddress();
|
||||
}
|
||||
|
||||
@Override
|
||||
public SocketAddress getLocalSocketAddress() {
|
||||
return socket.getLocalSocketAddress();
|
||||
}
|
||||
|
||||
@Override
|
||||
public SocketChannel getChannel() {
|
||||
return socket.getChannel();
|
||||
}
|
||||
|
||||
@Override
|
||||
public synchronized void close() throws IOException {
|
||||
socket.close();
|
||||
}
|
||||
|
||||
@Override
|
||||
public String toString() {
|
||||
return "InterposeSocket " + name + ": " + socket.toString();
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean isConnected() {
|
||||
return socket.isConnected();
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean isBound() {
|
||||
return socket.isBound();
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean isClosed() {
|
||||
return socket.isClosed();
|
||||
}
|
||||
|
||||
@Override
|
||||
public <T> Socket setOption(SocketOption<T> name, T value) throws IOException {
|
||||
return socket.setOption(name, value);
|
||||
}
|
||||
|
||||
@Override
|
||||
public <T> T getOption(SocketOption<T> name) throws IOException {
|
||||
return socket.getOption(name);
|
||||
}
|
||||
|
||||
@Override
|
||||
public Set<SocketOption<?>> supportedOptions() {
|
||||
return socket.supportedOptions();
|
||||
}
|
||||
|
||||
@Override
|
||||
public synchronized InputStream getInputStream() throws IOException {
|
||||
if (in == null) {
|
||||
in = socket.getInputStream();
|
||||
String name = Thread.currentThread().getName() + ": "
|
||||
+ socket.getLocalPort() + " < " + socket.getPort();
|
||||
in = new LoggingInputStream(in, name, inLogStream);
|
||||
DEBUG("Created new LoggingInputStream: %s%n", name);
|
||||
}
|
||||
return in;
|
||||
}
|
||||
|
||||
@Override
|
||||
public synchronized OutputStream getOutputStream() throws IOException {
|
||||
if (out == null) {
|
||||
OutputStream o = socket.getOutputStream();
|
||||
String name = Thread.currentThread().getName() + ": "
|
||||
+ socket.getLocalPort() + " > " + socket.getPort();
|
||||
out = new MatchReplaceOutputStream(o, name, outLogStream,
|
||||
triggerBytes, matchBytes, replaceBytes);
|
||||
DEBUG("Created new MatchReplaceOutputStream: %s%n", name);
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
/**
|
||||
* Return the bytes logged from the input stream.
|
||||
* @return Return the bytes logged from the input stream.
|
||||
*/
|
||||
public byte[] getInLogBytes() {
|
||||
return inLogStream.toByteArray();
|
||||
}
|
||||
|
||||
/**
|
||||
* Return the bytes logged from the output stream.
|
||||
* @return Return the bytes logged from the output stream.
|
||||
*/
|
||||
public byte[] getOutLogBytes() {
|
||||
return outLogStream.toByteArray();
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
/**
|
||||
* InterposeServerSocket is a ServerSocket that wraps each Socket it accepts
|
||||
* with an InterposeSocket so that its input and output streams can be monitored.
|
||||
*/
|
||||
public static class InterposeServerSocket extends ServerSocket {
|
||||
private final ServerSocket socket;
|
||||
private volatile byte[] triggerBytes;
|
||||
private volatile byte[] matchBytes;
|
||||
private volatile byte[] replaceBytes;
|
||||
private final List<InterposeSocket> sockets = new ArrayList<>();
|
||||
|
||||
/**
|
||||
* Construct a server socket that interposes on a socket to match and replace.
|
||||
* The trigger is empty.
|
||||
* @param socket the underlying socket
|
||||
* @param matchBytes the bytes that must match
|
||||
* @param replaceBytes the replacement bytes
|
||||
*/
|
||||
public InterposeServerSocket(ServerSocket socket, byte[] matchBytes,
|
||||
byte[] replaceBytes) throws IOException {
|
||||
this(socket, EMPTY_BYTE_ARRAY, matchBytes, replaceBytes);
|
||||
}
|
||||
|
||||
/**
|
||||
* Construct a server socket that interposes on a socket to match and replace.
|
||||
* @param socket the underlying socket
|
||||
* @param triggerBytes array of bytes to enable matching
|
||||
* @param matchBytes the bytes that must match
|
||||
* @param replaceBytes the replacement bytes
|
||||
*/
|
||||
public InterposeServerSocket(ServerSocket socket, byte[] triggerBytes,
|
||||
byte[] matchBytes, byte[] replaceBytes) throws IOException {
|
||||
this.socket = socket;
|
||||
this.triggerBytes = Objects.requireNonNull(triggerBytes, "triggerBytes");
|
||||
this.matchBytes = Objects.requireNonNull(matchBytes, "matchBytes");
|
||||
this.replaceBytes = Objects.requireNonNull(replaceBytes, "replaceBytes");
|
||||
}
|
||||
|
||||
/**
|
||||
* Set the match and replacement bytes, with an empty trigger.
|
||||
* The match and replacements are propagated to all existing sockets.
|
||||
*
|
||||
* @param matchBytes bytes to match
|
||||
* @param replaceBytes bytes to replace the matched bytes
|
||||
*/
|
||||
public void setMatchReplaceBytes(byte[] matchBytes, byte[] replaceBytes) {
|
||||
setMatchReplaceBytes(EMPTY_BYTE_ARRAY, matchBytes, replaceBytes);
|
||||
}
|
||||
|
||||
/**
|
||||
* Set the trigger, match, and replacement bytes.
|
||||
* The trigger, match, and replacements are propagated to all existing sockets.
|
||||
*
|
||||
* @param triggerBytes array of bytes to use as a trigger, may be zero length
|
||||
* @param matchBytes bytes to match after the trigger has been seen
|
||||
* @param replaceBytes bytes to replace the matched bytes
|
||||
*/
|
||||
public synchronized void setMatchReplaceBytes(byte[] triggerBytes, byte[] matchBytes,
|
||||
byte[] replaceBytes) {
|
||||
this.triggerBytes = triggerBytes;
|
||||
this.matchBytes = matchBytes;
|
||||
this.replaceBytes = replaceBytes;
|
||||
sockets.forEach(s -> s.setMatchReplaceBytes(triggerBytes, matchBytes, replaceBytes));
|
||||
}
|
||||
/**
|
||||
* Return a snapshot of the current list of sockets created from this server socket.
|
||||
* @return Return a snapshot of the current list of sockets
|
||||
*/
|
||||
public synchronized List<InterposeSocket> getSockets() {
|
||||
List<InterposeSocket> snap = new ArrayList<>(sockets);
|
||||
return snap;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void bind(SocketAddress endpoint) throws IOException {
|
||||
socket.bind(endpoint);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void bind(SocketAddress endpoint, int backlog) throws IOException {
|
||||
socket.bind(endpoint, backlog);
|
||||
}
|
||||
|
||||
@Override
|
||||
public InetAddress getInetAddress() {
|
||||
return socket.getInetAddress();
|
||||
}
|
||||
|
||||
@Override
|
||||
public int getLocalPort() {
|
||||
return socket.getLocalPort();
|
||||
}
|
||||
|
||||
@Override
|
||||
public SocketAddress getLocalSocketAddress() {
|
||||
return socket.getLocalSocketAddress();
|
||||
}
|
||||
|
||||
@Override
|
||||
public Socket accept() throws IOException {
|
||||
Socket s = socket.accept();
|
||||
synchronized(this) {
|
||||
InterposeSocket aSocket = new InterposeSocket(s, matchBytes,
|
||||
replaceBytes);
|
||||
sockets.add(aSocket);
|
||||
return aSocket;
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public void close() throws IOException {
|
||||
socket.close();
|
||||
}
|
||||
|
||||
@Override
|
||||
public ServerSocketChannel getChannel() {
|
||||
return socket.getChannel();
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean isClosed() {
|
||||
return socket.isClosed();
|
||||
}
|
||||
|
||||
@Override
|
||||
public String toString() {
|
||||
return socket.toString();
|
||||
}
|
||||
|
||||
@Override
|
||||
public <T> ServerSocket setOption(SocketOption<T> name, T value)
|
||||
throws IOException {
|
||||
return socket.setOption(name, value);
|
||||
}
|
||||
|
||||
@Override
|
||||
public <T> T getOption(SocketOption<T> name) throws IOException {
|
||||
return socket.getOption(name);
|
||||
}
|
||||
|
||||
@Override
|
||||
public Set<SocketOption<?>> supportedOptions() {
|
||||
return socket.supportedOptions();
|
||||
}
|
||||
|
||||
@Override
|
||||
public synchronized void setSoTimeout(int timeout) throws SocketException {
|
||||
socket.setSoTimeout(timeout);
|
||||
}
|
||||
|
||||
@Override
|
||||
public synchronized int getSoTimeout() throws IOException {
|
||||
return socket.getSoTimeout();
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* LoggingInputStream is a stream and logs all bytes read to it.
|
||||
* For identification it is given a name.
|
||||
*/
|
||||
public static class LoggingInputStream extends FilterInputStream {
|
||||
private int bytesIn = 0;
|
||||
private final String name;
|
||||
private final OutputStream log;
|
||||
|
||||
public LoggingInputStream(InputStream in, String name, OutputStream log) {
|
||||
super(in);
|
||||
this.name = name;
|
||||
this.log = log;
|
||||
}
|
||||
|
||||
@Override
|
||||
public int read() throws IOException {
|
||||
int b = super.read();
|
||||
if (b >= 0) {
|
||||
log.write(b);
|
||||
bytesIn++;
|
||||
}
|
||||
return b;
|
||||
}
|
||||
|
||||
@Override
|
||||
public int read(byte[] b, int off, int len) throws IOException {
|
||||
int bytes = super.read(b, off, len);
|
||||
if (bytes > 0) {
|
||||
log.write(b, off, bytes);
|
||||
bytesIn += bytes;
|
||||
}
|
||||
return bytes;
|
||||
}
|
||||
|
||||
@Override
|
||||
public int read(byte[] b) throws IOException {
|
||||
return read(b, 0, b.length);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void close() throws IOException {
|
||||
super.close();
|
||||
}
|
||||
|
||||
@Override
|
||||
public String toString() {
|
||||
return String.format("%s: In: (%d)", name, bytesIn);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* An OutputStream that looks for a trigger to enable matching and
|
||||
* replaces one string of bytes with another.
|
||||
* If any range matches, the match starts after the partial match.
|
||||
*/
|
||||
static class MatchReplaceOutputStream extends OutputStream {
|
||||
private final OutputStream out;
|
||||
private final String name;
|
||||
private volatile byte[] triggerBytes;
|
||||
private volatile byte[] matchBytes;
|
||||
private volatile byte[] replaceBytes;
|
||||
int triggerIndex;
|
||||
int matchIndex;
|
||||
private int bytesOut = 0;
|
||||
private final OutputStream log;
|
||||
|
||||
MatchReplaceOutputStream(OutputStream out, String name, OutputStream log,
|
||||
byte[] matchBytes, byte[] replaceBytes) {
|
||||
this(out, name, log, EMPTY_BYTE_ARRAY, matchBytes, replaceBytes);
|
||||
}
|
||||
|
||||
MatchReplaceOutputStream(OutputStream out, String name, OutputStream log,
|
||||
byte[] triggerBytes, byte[] matchBytes,
|
||||
byte[] replaceBytes) {
|
||||
this.out = out;
|
||||
this.name = name;
|
||||
this.triggerBytes = Objects.requireNonNull(triggerBytes, "triggerBytes");
|
||||
triggerIndex = 0;
|
||||
this.matchBytes = Objects.requireNonNull(matchBytes, "matchBytes");
|
||||
this.replaceBytes = Objects.requireNonNull(replaceBytes, "replaceBytes");
|
||||
matchIndex = 0;
|
||||
this.log = log;
|
||||
}
|
||||
|
||||
public void setMatchReplaceBytes(byte[] matchBytes, byte[] replaceBytes) {
|
||||
setMatchReplaceBytes(EMPTY_BYTE_ARRAY, matchBytes, replaceBytes);
|
||||
}
|
||||
|
||||
public void setMatchReplaceBytes(byte[] triggerBytes, byte[] matchBytes,
|
||||
byte[] replaceBytes) {
|
||||
this.triggerBytes = Objects.requireNonNull(triggerBytes, "triggerBytes");
|
||||
triggerIndex = 0;
|
||||
this.matchBytes = Objects.requireNonNull(matchBytes, "matchBytes");
|
||||
this.replaceBytes = Objects.requireNonNull(replaceBytes, "replaceBytes");
|
||||
matchIndex = 0;
|
||||
}
|
||||
|
||||
|
||||
public void write(int b) throws IOException {
|
||||
b = b & 0xff;
|
||||
if (matchBytes.length == 0) {
|
||||
// fast path, no match
|
||||
out.write(b);
|
||||
log.write(b);
|
||||
bytesOut++;
|
||||
return;
|
||||
}
|
||||
// if trigger not satisfied, keep looking
|
||||
if (triggerBytes.length != 0 && triggerIndex < triggerBytes.length) {
|
||||
out.write(b);
|
||||
log.write(b);
|
||||
bytesOut++;
|
||||
|
||||
triggerIndex = (b == (triggerBytes[triggerIndex] & 0xff))
|
||||
? ++triggerIndex // matching advance
|
||||
: 0; // no match, reset
|
||||
} else {
|
||||
// trigger not used or has been satisfied
|
||||
if (b == (matchBytes[matchIndex] & 0xff)) {
|
||||
if (++matchIndex >= matchBytes.length) {
|
||||
matchIndex = 0;
|
||||
triggerIndex = 0; // match/replace ok, reset trigger
|
||||
DEBUG("TestSocketFactory MatchReplace %s replaced %d bytes " +
|
||||
"at offset: %d (x%04x)%n",
|
||||
name, replaceBytes.length, bytesOut, bytesOut);
|
||||
out.write(replaceBytes);
|
||||
log.write(replaceBytes);
|
||||
bytesOut += replaceBytes.length;
|
||||
}
|
||||
} else {
|
||||
if (matchIndex > 0) {
|
||||
// mismatch, write out any that matched already
|
||||
DEBUG("Partial match %s matched %d bytes at offset: %d (0x%04x), " +
|
||||
" expected: x%02x, actual: x%02x%n",
|
||||
name, matchIndex, bytesOut, bytesOut, matchBytes[matchIndex], b);
|
||||
out.write(matchBytes, 0, matchIndex);
|
||||
log.write(matchBytes, 0, matchIndex);
|
||||
bytesOut += matchIndex;
|
||||
matchIndex = 0;
|
||||
}
|
||||
if (b == (matchBytes[matchIndex] & 0xff)) {
|
||||
matchIndex++;
|
||||
} else {
|
||||
out.write(b);
|
||||
log.write(b);
|
||||
bytesOut++;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public void flush() throws IOException {
|
||||
if (matchIndex > 0) {
|
||||
// write out any that matched already to avoid consumer hang.
|
||||
// Match/replace across a flush is not supported.
|
||||
DEBUG( "Flush partial match %s matched %d bytes at offset: %d (0x%04x)%n",
|
||||
name, matchIndex, bytesOut, bytesOut);
|
||||
out.write(matchBytes, 0, matchIndex);
|
||||
log.write(matchBytes, 0, matchIndex);
|
||||
bytesOut += matchIndex;
|
||||
matchIndex = 0;
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public String toString() {
|
||||
return String.format("%s: Out: (%d)", name, bytesOut);
|
||||
}
|
||||
}
|
||||
|
||||
private static byte[] obj1Data = new byte[] {
|
||||
0x7e, 0x7e, 0x7e,
|
||||
(byte) 0x80, 0x05,
|
||||
0x7f, 0x7f, 0x7f,
|
||||
0x73, 0x72, 0x00, 0x10, // TC_OBJECT, TC_CLASSDESC, length = 16
|
||||
(byte)'j', (byte)'a', (byte)'v', (byte)'a', (byte)'.',
|
||||
(byte)'l', (byte)'a', (byte)'n', (byte)'g', (byte)'.',
|
||||
(byte)'n', (byte)'u', (byte)'m', (byte)'b', (byte)'e', (byte)'r'
|
||||
};
|
||||
private static byte[] obj1Result = new byte[] {
|
||||
0x7e, 0x7e, 0x7e,
|
||||
(byte) 0x80, 0x05,
|
||||
0x7f, 0x7f, 0x7f,
|
||||
0x73, 0x72, 0x00, 0x11, // TC_OBJECT, TC_CLASSDESC, length = 17
|
||||
(byte)'j', (byte)'a', (byte)'v', (byte)'a', (byte)'.',
|
||||
(byte)'l', (byte)'a', (byte)'n', (byte)'g', (byte)'.',
|
||||
(byte)'I', (byte)'n', (byte)'t', (byte)'e', (byte)'g', (byte)'e', (byte)'r'
|
||||
};
|
||||
private static byte[] obj1Trigger = new byte[] {
|
||||
(byte) 0x80, 0x05
|
||||
};
|
||||
private static byte[] obj1Trigger2 = new byte[] {
|
||||
0x7D, 0x7D, 0x7D, 0x7D,
|
||||
};
|
||||
private static byte[] obj1Trigger3 = new byte[] {
|
||||
0x7F,
|
||||
};
|
||||
private static byte[] obj1Match = new byte[] {
|
||||
0x73, 0x72, 0x00, 0x10, // TC_OBJECT, TC_CLASSDESC, length = 16
|
||||
(byte)'j', (byte)'a', (byte)'v', (byte)'a', (byte)'.',
|
||||
(byte)'l', (byte)'a', (byte)'n', (byte)'g', (byte)'.',
|
||||
(byte)'n', (byte)'u', (byte)'m', (byte)'b', (byte)'e', (byte)'r'
|
||||
};
|
||||
private static byte[] obj1Repl = new byte[] {
|
||||
0x73, 0x72, 0x00, 0x11, // TC_OBJECT, TC_CLASSDESC, length = 17
|
||||
(byte)'j', (byte)'a', (byte)'v', (byte)'a', (byte)'.',
|
||||
(byte)'l', (byte)'a', (byte)'n', (byte)'g', (byte)'.',
|
||||
(byte)'I', (byte)'n', (byte)'t', (byte)'e', (byte)'g', (byte)'e', (byte)'r'
|
||||
};
|
||||
|
||||
@DataProvider(name = "MatchReplaceData")
|
||||
static Object[][] matchReplaceData() {
|
||||
byte[] empty = new byte[0];
|
||||
byte[] byte1 = new byte[]{1, 2, 3, 4, 5, 6};
|
||||
byte[] bytes2 = new byte[]{1, 2, 4, 3, 5, 6};
|
||||
byte[] bytes3 = new byte[]{6, 5, 4, 3, 2, 1};
|
||||
byte[] bytes4 = new byte[]{1, 2, 0x10, 0x20, 0x30, 0x40, 5, 6};
|
||||
byte[] bytes4a = new byte[]{1, 2, 0x10, 0x20, 0x30, 0x40, 5, 7}; // mostly matches bytes4
|
||||
byte[] bytes5 = new byte[]{0x30, 0x40, 5, 6};
|
||||
byte[] bytes6 = new byte[]{1, 2, 0x10, 0x20, 0x30};
|
||||
|
||||
return new Object[][]{
|
||||
{EMPTY_BYTE_ARRAY, new byte[]{}, new byte[]{},
|
||||
empty, empty},
|
||||
{EMPTY_BYTE_ARRAY, new byte[]{}, new byte[]{},
|
||||
byte1, byte1},
|
||||
{EMPTY_BYTE_ARRAY, new byte[]{3, 4}, new byte[]{4, 3},
|
||||
byte1, bytes2}, //swap bytes
|
||||
{EMPTY_BYTE_ARRAY, new byte[]{3, 4}, new byte[]{0x10, 0x20, 0x30, 0x40},
|
||||
byte1, bytes4}, // insert
|
||||
{EMPTY_BYTE_ARRAY, new byte[]{1, 2, 0x10, 0x20}, new byte[]{},
|
||||
bytes4, bytes5}, // delete head
|
||||
{EMPTY_BYTE_ARRAY, new byte[]{0x40, 5, 6}, new byte[]{},
|
||||
bytes4, bytes6}, // delete tail
|
||||
{EMPTY_BYTE_ARRAY, new byte[]{0x40, 0x50}, new byte[]{0x60, 0x50},
|
||||
bytes4, bytes4}, // partial match, replace nothing
|
||||
{EMPTY_BYTE_ARRAY, bytes4a, bytes3,
|
||||
bytes4, bytes4}, // long partial match, not replaced
|
||||
{EMPTY_BYTE_ARRAY, obj1Match, obj1Repl,
|
||||
obj1Match, obj1Repl},
|
||||
{obj1Trigger, obj1Match, obj1Repl,
|
||||
obj1Data, obj1Result},
|
||||
{obj1Trigger3, obj1Match, obj1Repl,
|
||||
obj1Data, obj1Result}, // different trigger, replace
|
||||
{obj1Trigger2, obj1Match, obj1Repl,
|
||||
obj1Data, obj1Data}, // no trigger, no replace
|
||||
};
|
||||
}
|
||||
|
||||
@Test(dataProvider = "MatchReplaceData")
|
||||
public static void test1(byte[] trigger, byte[] match, byte[] replace,
|
||||
byte[] input, byte[] expected) {
|
||||
System.out.printf("trigger: %s, match: %s, replace: %s%n", Arrays.toString(trigger),
|
||||
Arrays.toString(match), Arrays.toString(replace));
|
||||
try (ByteArrayOutputStream output = new ByteArrayOutputStream();
|
||||
ByteArrayOutputStream log = new ByteArrayOutputStream();
|
||||
OutputStream out = new MatchReplaceOutputStream(output, "test3",
|
||||
log, trigger, match, replace)) {
|
||||
out.write(input);
|
||||
byte[] actual = output.toByteArray();
|
||||
long index = Arrays.mismatch(actual, expected);
|
||||
|
||||
if (index >= 0) {
|
||||
System.out.printf("array mismatch, offset: %d%n", index);
|
||||
System.out.printf("actual: %s%n", Arrays.toString(actual));
|
||||
System.out.printf("expected: %s%n", Arrays.toString(expected));
|
||||
}
|
||||
Assert.assertEquals(actual, expected, "match/replace fail");
|
||||
} catch (IOException ioe) {
|
||||
Assert.fail("unexpected exception", ioe);
|
||||
}
|
||||
}
|
||||
}
|
||||
Loading…
Add table
Add a link
Reference in a new issue