]> source.dussan.org Git - javassist.git/commitdiff
HotSwap support
authorchiba <chiba@30ef5769-5b8d-40dd-aea6-55b5d6557bb3>
Tue, 21 Jun 2005 16:39:16 +0000 (16:39 +0000)
committerchiba <chiba@30ef5769-5b8d-40dd-aea6-55b5d6557bb3>
Tue, 21 Jun 2005 16:39:16 +0000 (16:39 +0000)
git-svn-id: http://anonsvn.jboss.org/repos/javassist/trunk@184 30ef5769-5b8d-40dd-aea6-55b5d6557bb3

Readme.html
build.xml
sample/hotswap/HelloWorld.java [new file with mode: 0644]
sample/hotswap/Test.java [new file with mode: 0644]
sample/hotswap/logging/HelloWorld.java [new file with mode: 0644]
src/main/javassist/Dump.java [deleted file]
src/main/javassist/tool/Dump.java [new file with mode: 0644]
src/main/javassist/tool/HotSwapper.java [new file with mode: 0644]
src/main/javassist/tool/package.html [new file with mode: 0644]

index 63aa00943239acb6e28337fcad8959ecec0d336e..dce5997a266093676462aac9ef2a95303c7b98e3 100644 (file)
@@ -240,6 +240,33 @@ with a web browser running
    on the local host.
 (Or, see <a href="sample/evolve/start.html">sample/evolve/start.html</a>.)
 
+<h3>8. sample/hotswap/*.java</h3>
+
+<p>This shows dynamic class reloading by the JPDA.
+To run, first type the following commands:
+
+<ul><pre>
+% cd sample/hotswap
+% javac *.java
+% cd logging
+% javac *.java
+% cd ..
+</pre></ul>
+
+<p>If your Java is 1.4, then type:
+
+<ul><pre>
+% java -Xdebug -Xrunjdwp:transport=dt_socket,server=y,suspend=n,address=8000 Test
+</pre></ul>
+
+<p>If you are using Java 5, then type:
+
+<ul><pre>
+% java -agentlib:jdwp=transport=dt_socket,server=y,suspend=n,address=8000 Test
+</pre></ul>
+
+<p>Note that the class path must include <code>JAVA_HOME/lib/tools.jar</code>.
+
 <h2>Hints</h2>
 
 <p>To know the version number, type this command:
@@ -258,6 +285,8 @@ see javassist.Dump.
 <p>- version 3.1
 
 <ul>
+  <li>javassist.tool.HotSwapper was added.
+  <li>javassist.Dump was moved to javassist.tool.Dump.
 </ul>
 
 <p>- version 3.0 in January 18, 2005
index 712c782774db03d58f8e4f2c73111e58e821d17f..3c3e3bdccf1ed67e338d2c873ee8bd7711110e0f 100644 (file)
--- a/build.xml
+++ b/build.xml
@@ -6,7 +6,7 @@
 
 <project name="javassist" default="jar" basedir=".">
 
-  <property name="dist-version" value="javassist-3.0"/>
+  <property name="dist-version" value="javassist-3.1"/>
 
   <property environment="env"/>
   <property name="target.jar" value="javassist.jar"/>
            debug="on"
            deprecation="on"
            optimize="off"
-           includes="sample/**">
+           includes="sample/**"
+           excludes="sample/hotswap/**">
+            <classpath refid="classpath"/>
+    </javac>
+    <javac srcdir="${basedir}/sample/hotswap"
+           destdir="${build.classes.dir}"
+           debug="on"
+           deprecation="on"
+           optimize="off"
+           includes="*">
+            <classpath refid="classpath"/>
+    </javac>
+    <mkdir dir="${build.classes.dir}/logging"/>
+    <javac srcdir="${basedir}/sample/hotswap/logging"
+           destdir="${build.classes.dir}/logging"
+           debug="on"
+           deprecation="on"
+           optimize="off"
+           includes="*">
             <classpath refid="classpath"/>
     </javac>
     <copy file="sample/vector/Test.j"
@@ -59,7 +77,7 @@
     <copy todir="${build.classes.dir}/sample/evolve">
       <fileset dir="sample/evolve"/>
     </copy>
-    <echo>To run the sample programs, change the current directory 
+    <echo>To run the sample programs without ant, change the current directory 
 to ${build.classes.dir}.</echo>
   </target>
 
@@ -175,4 +193,21 @@ Copyright (C) 1999-2005 Shigeru Chiba. All Rights Reserved.</i>]]></bottom>
     </java>
   </target>
 
+  <!-- for JDK 1.4 -->
+  <target name = "sample-hotswap" depends="sample">
+    <echo>** JAVA_HOME/lib/tools.jar must be included in CLASS_PATH</echo>
+    <java fork="true" dir="${run.dir}" classname="Test">
+      <jvmarg line="-Xdebug -Xrunjdwp:transport=dt_socket,server=y,suspend=n,address=8000" />
+      <classpath refid="classpath"/>
+    </java>
+  </target>
+
+  <!-- for Java 5 -->
+  <target name = "sample-hotswap5" depends="sample">
+    <echo>** JAVA_HOME/lib/tools.jar must be included in CLASS_PATH</echo>
+    <java fork="true" dir="${run.dir}" classname="Test">
+      <jvmarg line="-agentlib:jdwp=transport=dt_socket,server=y,suspend=n,address=8000" />
+      <classpath refid="classpath"/>
+    </java>
+  </target>
 </project>
diff --git a/sample/hotswap/HelloWorld.java b/sample/hotswap/HelloWorld.java
new file mode 100644 (file)
index 0000000..51d8fcd
--- /dev/null
@@ -0,0 +1,5 @@
+public class HelloWorld {
+    public void print() {
+        System.out.println("hello world");
+    }
+}
diff --git a/sample/hotswap/Test.java b/sample/hotswap/Test.java
new file mode 100644 (file)
index 0000000..c0ae177
--- /dev/null
@@ -0,0 +1,25 @@
+import java.io.*;
+import javassist.tool.HotSwapper;
+
+public class Test {
+    public static void main(String[] args) throws Exception {
+        HotSwapper hs = new HotSwapper(8000);
+        new HelloWorld().print();
+
+        File newfile = new File("logging/HelloWorld.class");
+        byte[] bytes = new byte[(int)newfile.length()];
+        new FileInputStream(newfile).read(bytes);
+        System.out.println("** reload a logging version");
+
+        hs.reload("HelloWorld", bytes);
+        new HelloWorld().print();
+
+        newfile = new File("HelloWorld.class");
+        bytes = new byte[(int)newfile.length()];
+        new FileInputStream(newfile).read(bytes);
+        System.out.println("** reload the original version");
+
+        hs.reload("HelloWorld", bytes);
+        new HelloWorld().print();
+    }
+}
diff --git a/sample/hotswap/logging/HelloWorld.java b/sample/hotswap/logging/HelloWorld.java
new file mode 100644 (file)
index 0000000..88f0866
--- /dev/null
@@ -0,0 +1,6 @@
+public class HelloWorld {
+    public void print() {
+        System.out.println("** HelloWorld.print()");
+        System.out.println("hello world");
+    }
+}
diff --git a/src/main/javassist/Dump.java b/src/main/javassist/Dump.java
deleted file mode 100644 (file)
index 69ba462..0000000
+++ /dev/null
@@ -1,57 +0,0 @@
-/*
- * Javassist, a Java-bytecode translator toolkit.
- * Copyright (C) 1999-2005 Shigeru Chiba. All Rights Reserved.
- *
- * The contents of this file are subject to the Mozilla Public License Version
- * 1.1 (the "License"); you may not use this file except in compliance with
- * the License.  Alternatively, the contents of this file may be used under
- * the terms of the GNU Lesser General Public License Version 2.1 or later.
- *
- * Software distributed under the License is distributed on an "AS IS" basis,
- * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
- * for the specific language governing rights and limitations under the
- * License.
- */
-
-package javassist;
-
-import java.io.*;
-import javassist.bytecode.ClassFile;
-import javassist.bytecode.ClassFileWriter;
-
-/**
- * Dump is a tool for viewing the class definition in the given
- * class file.  Unlike the JDK javap tool, Dump works even if
- * the class file is broken.
- *
- * <p>For example,
- * <ul><pre>% java javassist.Dump foo.class</pre></ul>
- *
- * <p>prints the contents of the constant pool and the list of methods
- * and fields.
- */
-public class Dump {
-    private Dump() {}
-
-    /**
-     * Main method.
-     *
-     * @param args           <code>args[0]</code> is the class file name.
-     */
-    public static void main(String[] args) throws Exception {
-        if (args.length != 1) {
-            System.err.println("Usage: java Dump <class file name>");
-            return;
-        }
-
-        DataInputStream in = new DataInputStream(
-                                         new FileInputStream(args[0]));
-        ClassFile w = new ClassFile(in);
-        PrintWriter out = new PrintWriter(System.out, true);
-        out.println("*** constant pool ***");
-        w.getConstPool().print(out);
-        out.println();
-        out.println("*** members ***");
-        ClassFileWriter.print(w, out);
-    }
-}
diff --git a/src/main/javassist/tool/Dump.java b/src/main/javassist/tool/Dump.java
new file mode 100644 (file)
index 0000000..f8a1a5d
--- /dev/null
@@ -0,0 +1,57 @@
+/*
+ * Javassist, a Java-bytecode translator toolkit.
+ * Copyright (C) 1999-2005 Shigeru Chiba. All Rights Reserved.
+ *
+ * The contents of this file are subject to the Mozilla Public License Version
+ * 1.1 (the "License"); you may not use this file except in compliance with
+ * the License.  Alternatively, the contents of this file may be used under
+ * the terms of the GNU Lesser General Public License Version 2.1 or later.
+ *
+ * Software distributed under the License is distributed on an "AS IS" basis,
+ * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
+ * for the specific language governing rights and limitations under the
+ * License.
+ */
+
+package javassist.tool;
+
+import java.io.*;
+import javassist.bytecode.ClassFile;
+import javassist.bytecode.ClassFileWriter;
+
+/**
+ * Dump is a tool for viewing the class definition in the given
+ * class file.  Unlike the JDK javap tool, Dump works even if
+ * the class file is broken.
+ *
+ * <p>For example,
+ * <ul><pre>% java javassist.tool.Dump foo.class</pre></ul>
+ *
+ * <p>prints the contents of the constant pool and the list of methods
+ * and fields.
+ */
+public class Dump {
+    private Dump() {}
+
+    /**
+     * Main method.
+     *
+     * @param args           <code>args[0]</code> is the class file name.
+     */
+    public static void main(String[] args) throws Exception {
+        if (args.length != 1) {
+            System.err.println("Usage: java Dump <class file name>");
+            return;
+        }
+
+        DataInputStream in = new DataInputStream(
+                                         new FileInputStream(args[0]));
+        ClassFile w = new ClassFile(in);
+        PrintWriter out = new PrintWriter(System.out, true);
+        out.println("*** constant pool ***");
+        w.getConstPool().print(out);
+        out.println();
+        out.println("*** members ***");
+        ClassFileWriter.print(w, out);
+    }
+}
diff --git a/src/main/javassist/tool/HotSwapper.java b/src/main/javassist/tool/HotSwapper.java
new file mode 100644 (file)
index 0000000..4df6cca
--- /dev/null
@@ -0,0 +1,250 @@
+/*
+ * Javassist, a Java-bytecode translator toolkit.
+ * Copyright (C) 1999-2005 Shigeru Chiba. All Rights Reserved.
+ *
+ * The contents of this file are subject to the Mozilla Public License Version
+ * 1.1 (the "License"); you may not use this file except in compliance with
+ * the License.  Alternatively, the contents of this file may be used under
+ * the terms of the GNU Lesser General Public License Version 2.1 or later.
+ *
+ * Software distributed under the License is distributed on an "AS IS" basis,
+ * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
+ * for the specific language governing rights and limitations under the
+ * License.
+ */
+
+package javassist.tool;
+
+import com.sun.jdi.*;
+import com.sun.jdi.connect.*;
+import com.sun.jdi.event.*;
+import com.sun.jdi.request.*;
+import java.io.*;
+import java.util.*;
+
+class Trigger {
+    void doSwap() {}
+}
+
+/**
+ * A utility class for dynamically reloading a class by
+ * the Java Platform Debugger Architecture (JPDA), or <it>HotSwap</code>.
+ * It works only with JDK 1.4 and later.
+ *
+ * <p><b>Note:</b> The new definition of the reloaded class must declare
+ * the same set of methods and fields as the original definition.  The
+ * schema change between the original and new definitions is not allowed
+ * by the JPDA. 
+ *
+ * <p>To use this class, the JVM must be launched with the following
+ * command line options:
+ *
+ * <ul>
+ * <p>For Java 1.4,<br>
+ * <pre>java -Xdebug -Xrunjdwp:transport=dt_socket,server=y,suspend=n,address=8000</pre>
+ * <p>For Java 5,<br>
+ * <pre>java -agentlib:jdwp=transport=dt_socket,server=y,suspend=n,address=8000</pre>
+ * </ul>
+ *
+ * <p>Note that 8000 is the port number used by <code>HotSwapper</code>.
+ * Any port number can be specified.  Since <code>HotSwapper</code> does not
+ * launch another JVM for running a target application, this port number
+ * is used only for inter-thread communication.
+ *
+ * <p>Furthermore, <code>JAVA_HOME/lib/tools.jar</code> must be included
+ * in the class path.
+ *
+ * <p>Using <code>HotSwapper</code> is easy.  See the following example:
+ *
+ * <ul><pre>
+ * CtClass clazz = ...
+ * byte[] classFile = clazz.toBytecode();
+ * HotSwapper hs = new HostSwapper(8000);  // 8000 is a port number.
+ * hs.reload("Test", classFile);
+ * </pre></ul>
+ *
+ * <p><code>reload()</code>
+ * first unload the <code>Test</code> class and load a new version of
+ * the <code>Test</code> class.
+ * <code>classFile</code> is a byte array containing the new contents of
+ * the class file for the <code>Test</code> class.  The developers can
+ * repatedly call <code>reload()</code> on the same <code>HotSwapper</code>
+ * object so that they can reload a number of classes.
+ *
+ * @since 3.1
+ */
+public class HotSwapper {
+    private VirtualMachine jvm;
+    private MethodEntryRequest request;
+    private Map newClassFiles;
+
+    private Trigger trigger;
+
+    private static final String HOST_NAME = "localhost";
+    private static final String TRIGGER_NAME = "javassist.tool.Trigger";
+
+    /**
+     * Connects to the JVM.
+     *
+     * @param port     the port number used for the connection to the JVM.
+     */
+    public HotSwapper(int port)
+        throws IOException, IllegalConnectorArgumentsException
+    {
+        this(Integer.toString(port));
+    }
+
+    /**
+     * Connects to the JVM.
+     *
+     * @param port     the port number used for the connection to the JVM.
+     */
+    public HotSwapper(String port)
+        throws IOException, IllegalConnectorArgumentsException
+    {
+        jvm = null;
+        request = null;
+        newClassFiles = null;
+        trigger = new Trigger();
+        AttachingConnector connector
+            = (AttachingConnector)findConnector("com.sun.jdi.SocketAttach");
+
+        Map arguments = connector.defaultArguments();
+        ((Connector.Argument)arguments.get("hostname")).setValue(HOST_NAME);
+        ((Connector.Argument)arguments.get("port")).setValue(port);
+        jvm = connector.attach(arguments);
+        EventRequestManager manager = jvm.eventRequestManager();
+        request = methodEntryRequests(manager, TRIGGER_NAME);
+    }
+
+    private Connector findConnector(String connector) throws IOException {
+        List connectors = Bootstrap.virtualMachineManager().allConnectors();
+        Iterator iter = connectors.iterator();
+        while (iter.hasNext()) {
+            Connector con = (Connector)iter.next();
+            if (con.name().equals(connector)) {
+                return con;
+            }
+        }
+
+        throw new IOException("Not found: " + connector);
+    }
+
+    private static MethodEntryRequest methodEntryRequests(
+                                EventRequestManager manager,
+                                String classpattern) {
+        MethodEntryRequest mereq = manager.createMethodEntryRequest();
+        mereq.addClassFilter(classpattern);
+        mereq.setSuspendPolicy(EventRequest.SUSPEND_EVENT_THREAD);
+        return mereq;
+    }
+
+    private void deleteEventRequest(EventRequestManager manager,
+                                    MethodEntryRequest request) {
+        manager.deleteEventRequest(request);
+    }
+
+    /**
+     * Reloads a class.
+     *
+     * @param className                the fully-qualified class name.
+     * @param classFile                the contents of the class file.
+     */
+    public void reload(String className, byte[] classFile) {
+        ReferenceType classtype = toRefType(className);
+        Map map = new HashMap();
+        map.put(classtype, classFile);
+        reload2(map, className);
+    }
+
+    /**
+     * Reloads a class.
+     *
+     * @param classFiles       a map between fully-qualified class names
+     *                         and class files.  The type of the class names
+     *                         is <code>String</code> and the type of the
+     *                         class files is <code>byte[]</code>.
+     */
+    public void reload(Map classFiles) {
+        Set set = classFiles.entrySet();
+        Iterator it = set.iterator();
+        Map map = new HashMap();
+        String className = null;
+        while (it.hasNext()) {
+            Map.Entry e = (Map.Entry)it.next();
+            className = (String)e.getKey();
+            map.put(toRefType(className), e.getValue());
+        }
+
+        if (className != null)
+            reload2(map, className + " etc.");
+    }
+
+    private ReferenceType toRefType(String className) {
+        List list = jvm.classesByName(className);
+        if (list == null || list.isEmpty())
+            throw new RuntimeException("no such a class: " + className);
+        else
+            return (ReferenceType)list.get(0);
+    }
+
+    private void reload2(Map map, String msg) {
+        synchronized (trigger) {
+            startDaemon();
+            newClassFiles = map;
+            request.enable();
+            trigger.doSwap();
+            request.disable();
+            Map ncf = newClassFiles;
+            if (ncf != null) {
+                newClassFiles = null;
+                throw new RuntimeException("failed to reload: " + msg);
+            }
+        }
+    }
+
+    private void startDaemon() {
+        new Thread() {
+            private void errorMsg(Throwable e) {
+                System.err.print("Exception in thread \"HotSwap\" ");
+                e.printStackTrace(System.err);
+            }
+
+            public void run() {
+                EventSet events = null;
+                try {
+                    events = waitEvent();
+                    EventIterator iter = events.eventIterator();
+                    while (iter.hasNext()) {
+                        Event event = iter.nextEvent();
+                        if (event instanceof MethodEntryEvent) {
+                            hotswap();
+                            break;
+                        }
+                    }
+                }
+                catch (Throwable e) {
+                    errorMsg(e);
+                }
+                try {
+                    if (events != null)
+                        events.resume();
+                }
+                catch (Throwable e) {
+                    errorMsg(e);
+                }
+            }
+        }.start();
+    }
+
+    EventSet waitEvent() throws InterruptedException {
+        EventQueue queue = jvm.eventQueue();
+        return queue.remove();
+    }
+
+    void hotswap() {
+        Map map = newClassFiles;
+        jvm.redefineClasses(map);
+        newClassFiles = null;
+    }
+}
diff --git a/src/main/javassist/tool/package.html b/src/main/javassist/tool/package.html
new file mode 100644 (file)
index 0000000..1566e12
--- /dev/null
@@ -0,0 +1,6 @@
+<html>
+<body>
+Utility classes.
+
+</body>
+</html>