Initial load
diff --git a/jdk/test/java/lang/Appendable/Basic.java b/jdk/test/java/lang/Appendable/Basic.java
new file mode 100644
index 0000000..509105a
--- /dev/null
+++ b/jdk/test/java/lang/Appendable/Basic.java
@@ -0,0 +1,394 @@
+/*
+ * Copyright 2004 Sun Microsystems, Inc.  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 Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
+ * CA 95054 USA or visit www.sun.com if you need additional information or
+ * have any questions.
+ */
+
+/* @test
+ * @bug 5067405
+ * @summary Basic test for classes which implement Appendable.
+ */
+
+import java.io.BufferedReader;
+import java.io.BufferedWriter;
+import java.io.ByteArrayOutputStream;
+import java.io.CharArrayWriter;
+import java.io.File;
+import java.io.FileReader;
+import java.io.FileWriter;
+import java.io.IOException;
+import java.io.OutputStreamWriter;
+import java.io.PrintStream;
+import java.io.PrintWriter;
+import java.io.StringWriter;
+import java.io.Writer;
+import java.nio.ByteBuffer;
+import java.nio.CharBuffer;
+
+interface BasicRunnable extends Runnable {
+    void init(Appendable a, String csq, String exp);
+    Appendable reset(Appendable csq);
+}
+
+public class Basic {
+
+    private static final String s = "Beware the Jabberwock, my son!";
+    private static CharArrayWriter gw = new CharArrayWriter();
+    private static ByteArrayOutputStream gos = new ByteArrayOutputStream();
+
+    private static File newFile() {
+        File f = null;
+        try {
+            f = File.createTempFile("append", ".txt");
+            f.deleteOnExit();
+        } catch (IOException x) {
+            fail(x);
+        }
+        return f;
+    }
+    private static File gf = newFile();
+
+    private static int fail = 0;
+    private static int pass = 0;
+
+    private static Throwable first;
+
+    static void pass() {
+        pass++;
+    }
+
+    static void fail(Throwable ex) {
+        if (first == null)
+            first = ex;
+        System.err.println("FAILED: unexpected exception");
+        fail++;
+    }
+
+    static void fail(String fs, Throwable ex) {
+        String s = "'" + fs + "': " + ex.getClass().getName() + " not thrown";
+        if (first == null)
+            first = ex;
+        System.err.println("FAILED: " + s);
+        fail++;
+    }
+
+    static void fail(String fs, String exp, String got) {
+        String s = "'" + fs + "': Expected '" + exp + "', got '" + got + "'";
+        if (first == null)
+            first = new RuntimeException(s);
+        System.err.println("FAILED: " + s);
+        fail++;
+    }
+
+    static void ck(String s, String exp, String got) {
+        if (!exp.equals(got))
+            fail(s, exp, got);
+        else
+            pass();
+    }
+
+    private static BasicRunnable testBufferedWriter =
+        new BasicRunnable() {
+            private String csn, exp;
+            public void init(Appendable bw, String csn, String exp) {
+                try {
+                    ((BufferedWriter)bw).flush();
+                } catch (IOException x) {
+                    fail(x);
+                }
+                this.csn = csn;
+                this.exp = exp;
+            }
+            public void run() {
+                ck("BufferedWriter.append(" + csn + ")", exp, gw.toString());
+            }
+            public Appendable reset(Appendable bw) {
+                gw.reset();
+                return bw;
+            }};
+
+    private static BasicRunnable testCharArrayWriter =
+        new BasicRunnable() {
+            private String csn, exp;
+            private CharArrayWriter cw;
+            public void init(Appendable cw, String csn, String exp) {
+                this.cw = (CharArrayWriter)cw;
+                this.csn = csn;
+                this.exp = exp;
+            }
+            public void run() {
+                ck("CharArrayWriter.append(" + csn + ")", exp, cw.toString());
+            }
+            public Appendable reset(Appendable cw) {
+                ((CharArrayWriter)cw).reset();
+                return cw;
+            }};
+
+    private static BasicRunnable testFileWriter =
+        new BasicRunnable() {
+            private String csn, exp;
+            public void init(Appendable fw, String csn, String exp) {
+                try {
+                    ((FileWriter)fw).flush();
+                } catch (IOException x) {
+                    fail(x);
+                }
+                this.csn = csn;
+                this.exp = exp;
+            }
+            public void run() {
+                StringBuilder sb = new StringBuilder();
+                try {
+                    BufferedReader in = new BufferedReader(new FileReader(gf));
+                    String line;
+                    while (true) {
+                        if ((line = in.readLine()) == null)
+                            break;
+                        sb.append(line);
+                    }
+                } catch (IOException x) {
+                    fail(x);
+                }
+                ck("FileWriter.append(" + csn + ")", exp, sb.toString());
+            }
+            public Appendable reset(Appendable fw) {
+                try {
+                    fw = new FileWriter(gf);
+                } catch (IOException x) {
+                    fail(x);
+                }
+                return fw;
+            }};
+
+    private static BasicRunnable testOutputStreamWriter =
+        new BasicRunnable() {
+            private String csn, exp;
+            public void init(Appendable osw, String csn, String exp) {
+                try {
+                    ((OutputStreamWriter)osw).flush();
+                } catch (IOException x) {
+                    fail(x);
+                }
+                this.csn = csn;
+                this.exp = exp;
+            }
+            public void run() {
+                ck("OutputStreamWriter.append(" + csn + ")", exp, gos.toString());
+            }
+            public Appendable reset(Appendable osw) {
+                gos.reset();
+                return osw;
+            }};
+
+    private static BasicRunnable testPrintWriter =
+        new BasicRunnable() {
+            private String csn, exp;
+            public void init(Appendable pw, String csn, String exp) {
+                ((PrintWriter)pw).flush();
+                this.csn = csn;
+                this.exp = exp;
+            }
+            public void run() {
+                ck("PrintWriter.append(" + csn + ")", exp, gw.toString());
+            }
+            public Appendable reset(Appendable pw) {
+                gw.reset();
+                return pw;
+            }};
+
+    private static BasicRunnable testStringWriter =
+        new BasicRunnable() {
+            private String csn, exp;
+            private StringWriter sw;
+            public void init(Appendable sw, String csn, String exp) {
+                this.sw = (StringWriter)sw;
+                this.csn = csn;
+                this.exp = exp;
+            }
+            public void run() {
+                ck("StringWriter.append(" + csn + ")", exp, sw.toString());
+            }
+            public Appendable reset(Appendable sw) {
+                return new StringWriter();
+            }};
+
+    private static BasicRunnable testPrintStream =
+        new BasicRunnable() {
+            private String csn, exp;
+            public void init(Appendable ps, String csn, String exp) {
+                ((PrintStream)ps).flush();
+                this.csn = csn;
+                this.exp = exp;
+            }
+            public void run() {
+                ck("PrintStream.append(" + csn + ")", exp, gos.toString());
+            }
+            public Appendable reset(Appendable ps) {
+                gos.reset();
+                return ps;
+            }};
+
+    private static BasicRunnable testCharBuffer =
+        new BasicRunnable() {
+            private String csn, exp;
+            private CharBuffer cb;
+            public void init(Appendable cb, String csn, String exp) {
+                this.cb = (CharBuffer)cb;
+                this.csn = csn;
+                this.exp = exp;
+            }
+            public void run() {
+                cb.limit(cb.position()).rewind();
+                ck("CharBuffer.append(" + csn + ")", exp, cb.toString());
+            }
+            public Appendable reset(Appendable cb) {
+                ((CharBuffer)cb).clear();
+                return cb;
+            }};
+
+    private static BasicRunnable testStringBuffer =
+        new BasicRunnable() {
+            private String csn, exp;
+            private StringBuffer sb;
+            public void init(Appendable sb, String csn, String exp) {
+                this.sb = (StringBuffer)sb;
+                this.csn = csn;
+                this.exp = exp;
+            }
+            public void run() {
+                ck("StringBuffer.append(" + csn + ")", exp, sb.toString());
+            }
+            public Appendable reset(Appendable sb) {
+                return new StringBuffer();
+            }};
+
+    private static BasicRunnable testStringBuilder =
+        new BasicRunnable() {
+            private String csn, exp;
+            private StringBuilder sb;
+            public void init(Appendable sb, String csn, String exp) {
+                this.sb = (StringBuilder)sb;
+                this.csn = csn;
+                this.exp = exp;
+            }
+            public void run() {
+                ck("StringBuilder.append(" + csn + ")", exp, sb.toString());
+            }
+            public Appendable reset(Appendable sb) {
+                return new StringBuilder();
+            }};
+
+    private static void test(Appendable a, CharSequence csq, BasicRunnable thunk) {
+        // appends that should always work
+        int [][] sp = { { 0, 0 }, { 11, 11 }, { 11, 21 }, { 0, 7 },
+                        { 0, s.length() }, { s.length(), s.length() },
+        };
+        for (int j = 0; j < sp.length; j++) {
+            int start = sp[j][0];
+            int end = sp[j][1];
+            try {
+                thunk.init(a.append(csq, start, end),
+                           csq.getClass().getName(),
+                           s.subSequence(start, end).toString());
+                thunk.run();
+                a = thunk.reset(a);
+            } catch (IOException x) {
+                fail(x);
+            }
+        }
+
+        // appends that should always throw IndexOutOfBoundsException
+        int [][] sf = { { -1, 0 }, { 0, -1 }, { 11, 10 },
+                        { 0, s.length() + 1},
+        };
+        for (int j = 0; j < sf.length; j++) {
+            int start = sf[j][0];
+            int end = sf[j][1];
+            try {
+                a.append(csq, start, end);
+                fail("start = " + start + ", end = " + end,
+                     new IndexOutOfBoundsException());
+                a = thunk.reset(a);
+            } catch (IndexOutOfBoundsException x) {
+                pass();
+            } catch (IOException x) {
+                fail(x);
+            }
+        }
+
+        // appends of null
+        int start = 1;
+        int end = 2;
+        try {
+            thunk.init(a.append(null, start, end), "null",
+                       "null".subSequence(start, end).toString());
+            thunk.run();
+            a = thunk.reset(a);
+        } catch (IOException x) {
+            fail(x);
+        }
+    }
+
+    public static void main(String [] args) throws Exception {
+        // CharSequences
+        CharBuffer cb = CharBuffer.allocate(128).put(s);
+        cb.limit(s.length()).rewind();
+        CharBuffer dcb = ByteBuffer.allocateDirect(128).asCharBuffer().put(s);
+        dcb.limit(s.length()).rewind();
+        CharSequence [] ca = { s,
+                               new StringBuffer(s),
+                               new StringBuilder(s),
+                               cb,
+                               dcb,
+        };
+
+        // Appendables/Writers
+        Object [][] wa = { { new CharArrayWriter(), testCharArrayWriter },
+                           { new BufferedWriter(gw), testBufferedWriter },
+                           // abstract, no implementing classes in jdk
+                           // { new FilterWriter(), testFilterWriter },
+                           { new FileWriter(gf), testFileWriter },
+                           { new OutputStreamWriter(gos), testOutputStreamWriter },
+                           // covered by previous two test cases
+                           // { new PipedWriter(gw), testPipedWriter },
+                           { new PrintWriter(gw), testPrintWriter },
+                           { new StringWriter(), testStringWriter },
+        };
+
+        for (int i = 0; i < ca.length; i++) {
+            CharSequence a = ca[i];
+            for (int j = 0; j < wa.length; j++)
+                test((Writer)wa[j][0], a, (BasicRunnable)wa[j][1]);
+
+            // other Appendables
+            test(new PrintStream(gos), a, testPrintStream);
+            test(CharBuffer.allocate(128), a, testCharBuffer);
+            test(ByteBuffer.allocateDirect(128).asCharBuffer(), a, testCharBuffer);
+            test(new StringBuffer(), a, testStringBuffer);
+            test(new StringBuilder(), a, testStringBuilder);
+        }
+
+        if (fail != 0)
+            throw new RuntimeException((fail + pass) + " tests: "
+                                       + fail + " failure(s), first", first);
+        else
+            System.out.println("all " + (fail + pass) + " tests passed");
+    }
+}
diff --git a/jdk/test/java/lang/AssertionError/Cause.java b/jdk/test/java/lang/AssertionError/Cause.java
new file mode 100644
index 0000000..31ae2c7
--- /dev/null
+++ b/jdk/test/java/lang/AssertionError/Cause.java
@@ -0,0 +1,41 @@
+/*
+ * Copyright 2001 Sun Microsystems, Inc.  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 Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
+ * CA 95054 USA or visit www.sun.com if you need additional information or
+ * have any questions.
+ */
+
+/**
+ * @test
+ * @bug 4513384
+ * @summary Object Constructor now sets cause if Object is an instance of Throwable.
+ * @author Josh Bloch
+ */
+
+public class Cause {
+    public static void main(String[] args) throws Exception {
+        Exception e = new Exception();
+        AssertionError ae = new AssertionError(e);
+        if (ae.getCause() != e)
+            throw new Exception("Cause not set.");
+        ae = new AssertionError("gosh it's late");
+        if (ae.getCause() != null)
+            throw new Exception("Cause set erroneously: " + ae.getCause());
+    }
+}
diff --git a/jdk/test/java/lang/Class/Cast.java b/jdk/test/java/lang/Class/Cast.java
new file mode 100644
index 0000000..0f57c22
--- /dev/null
+++ b/jdk/test/java/lang/Class/Cast.java
@@ -0,0 +1,42 @@
+/*
+ * Copyright 2003 Sun Microsystems, Inc.  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 Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
+ * CA 95054 USA or visit www.sun.com if you need additional information or
+ * have any questions.
+ */
+
+/*
+ * @test
+ * @bug 4881275
+ * @summary (reflect) Class.cast() - typesafe cast desired
+ *
+ * @compile -source 1.5 Cast.java
+ * @run main Cast
+ */
+
+public class Cast {
+    static class Foo {}
+
+    public static void main(String argv[]) throws Exception {
+        Object o = Foo.class.newInstance();
+        Foo f = Foo.class.cast(o);
+        if (f == null) throw new Error();
+        Foo f2 = Foo.class.cast(null);
+    }
+}
diff --git a/jdk/test/java/lang/Class/EnumPoseur.class b/jdk/test/java/lang/Class/EnumPoseur.class
new file mode 100644
index 0000000..3a8575d
--- /dev/null
+++ b/jdk/test/java/lang/Class/EnumPoseur.class
Binary files differ
diff --git a/jdk/test/java/lang/Class/EnumPoseur.java.src b/jdk/test/java/lang/Class/EnumPoseur.java.src
new file mode 100644
index 0000000..5d30fdb
--- /dev/null
+++ b/jdk/test/java/lang/Class/EnumPoseur.java.src
@@ -0,0 +1,11 @@
+/*
+ *
+ *
+ * This file is used indirectly by the IsEnum.java test.  The class
+ * file generated from this source file has class file version 48;
+ * i.e. it is not a version 49 class file generated by target 1.5.
+ */
+class EnumPoseur extends java.lang.Enum {
+    private EnumPoseur(){
+    }
+}
diff --git a/jdk/test/java/lang/Class/IsAnnotationType.java b/jdk/test/java/lang/Class/IsAnnotationType.java
new file mode 100644
index 0000000..0019cf3
--- /dev/null
+++ b/jdk/test/java/lang/Class/IsAnnotationType.java
@@ -0,0 +1,64 @@
+/*
+ * Copyright 2003-2004 Sun Microsystems, Inc.  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 Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
+ * CA 95054 USA or visit www.sun.com if you need additional information or
+ * have any questions.
+ */
+
+/*
+ * @test
+ * @bug 4891872 4988155
+ * @summary Check isAnnotation() method
+ * @author Joseph D. Darcy
+ */
+
+import java.lang.annotation.*;
+
+public class IsAnnotationType {
+    interface AnnotationPoseur extends Annotation {
+    }
+
+    static int test(Class clazz, boolean expected) {
+        int status = (clazz.isAnnotation() == expected)?0:1;
+
+        if (status == 1) {
+            System.err.println("Unexpected annotation status for " + clazz);
+        }
+        return status;
+    }
+
+    public static void main(String argv[]) {
+        int failures = 0;
+
+        failures += test(String.class, false);
+        failures += test(Enum.class, false);
+        failures += test(java.math.RoundingMode.class, false);
+        // Classes in java.lang.annoation
+        failures += test(Annotation.class, false);
+        failures += test(Retention.class, true);
+        failures += test(RetentionPolicy.class, false);
+        failures += test(Target.class, true);
+        failures += test(AnnotationPoseur.class, false);
+
+        if (failures > 0) {
+            throw new RuntimeException("Unexepcted annotation " +
+                                       "status detected.");
+        }
+    }
+}
diff --git a/jdk/test/java/lang/Class/IsEnum.java b/jdk/test/java/lang/Class/IsEnum.java
new file mode 100644
index 0000000..1b4ccb7
--- /dev/null
+++ b/jdk/test/java/lang/Class/IsEnum.java
@@ -0,0 +1,81 @@
+/*
+ * Copyright 2003-2004 Sun Microsystems, Inc.  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 Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
+ * CA 95054 USA or visit www.sun.com if you need additional information or
+ * have any questions.
+ */
+
+/*
+ * @test
+ * @bug 4891872 4989735 4990789 5020490
+ * @summary Check isEnum() method
+ * @author Joseph D. Darcy
+ * @compile -source 1.5 IsEnum.java
+ * @run main IsEnum
+ */
+
+import java.lang.annotation.*;
+
+public class IsEnum {
+
+    static int test(Class clazz, boolean expected) {
+        int status = (clazz.isEnum() == expected)?0:1;
+
+        if (status == 1) {
+            System.err.println("Unexpected enum status for " + clazz);
+        }
+        return status;
+    }
+
+    public static void main(String argv[]) {
+        int failures = 0;
+
+        failures += test(IsEnum.class, false);
+        failures += test(String.class, false);
+        failures += test(Enum.class, false);
+        failures += test(java.math.RoundingMode.class, true);
+
+        // Classes in java.lang.annoation
+        failures += test(Annotation.class, false);
+        failures += test(ElementType.class, true);
+        failures += test(Retention.class, false);
+        failures += test(RetentionPolicy.class, true);
+        failures += test(Target.class, false);
+        failures += test(EnumPoseur.class, false);
+
+        // Classes for specialized enum constants aren't enum's
+        failures += test(SpecialEnum.class, true);
+        failures += test(SpecialEnum.RED.getClass(), false);
+        failures += test(SpecialEnum.GREEN.getClass(), true);
+
+        if (failures > 0) {
+            throw new RuntimeException("Unexepcted enum status detected.");
+        }
+    }
+}
+
+enum SpecialEnum {
+    RED {
+        String special() {return "riding hood";}
+    },
+
+    GREEN;
+
+    String special() {return "how was my valley";}
+}
diff --git a/jdk/test/java/lang/Class/IsSynthetic.java b/jdk/test/java/lang/Class/IsSynthetic.java
new file mode 100644
index 0000000..11950f3
--- /dev/null
+++ b/jdk/test/java/lang/Class/IsSynthetic.java
@@ -0,0 +1,82 @@
+/*
+ * Copyright 2004 Sun Microsystems, Inc.  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 Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
+ * CA 95054 USA or visit www.sun.com if you need additional information or
+ * have any questions.
+ */
+
+/*
+ * @test
+ * @bug 5012133
+ * @summary Check Class.isSynthetic method
+ * @author Joseph D. Darcy
+ */
+
+import java.lang.reflect.*;
+
+public class IsSynthetic {
+
+    static class NestedClass {
+    }
+
+    static int test(Class<?> clazz, boolean expected) {
+        if (clazz.isSynthetic() == expected)
+            return 0;
+        else {
+            System.err.println("Unexpected synthetic status for " +
+                               clazz.getName() + " expected: " + expected +
+                               " got: " + (!expected));
+            return 1;
+        }
+    }
+
+    public static void main(String argv[]) {
+        int failures = 0;
+        class LocalClass {}
+
+        Cloneable clone = new Cloneable() {};
+
+        failures += test(IsSynthetic.class,             false);
+        failures += test(java.lang.String.class,        false);
+        failures += test(LocalClass.class,              false);
+        failures += test(NestedClass.class,             false);
+        failures += test(clone.getClass(),              false);
+
+        for(Constructor c: Tricky.class.getDeclaredConstructors()) {
+            Class<?>[] paramTypes = c.getParameterTypes();
+            if (paramTypes.length > 0) {
+                System.out.println("Testing class that should be synthetic.");
+                for(Class paramType: paramTypes) {
+                    failures += test(paramType, true);
+                }
+            }
+        }
+
+        if (failures != 0)
+            throw new RuntimeException("Test failed with " + failures  + " failures.");
+    }
+}
+
+class Tricky {
+    private Tricky() {}
+
+    public static class Nested {
+        Tricky t = new Tricky();
+    }
+}
diff --git a/jdk/test/java/lang/Class/TypeCheckMicroBenchmark.java b/jdk/test/java/lang/Class/TypeCheckMicroBenchmark.java
new file mode 100644
index 0000000..223ad14
--- /dev/null
+++ b/jdk/test/java/lang/Class/TypeCheckMicroBenchmark.java
@@ -0,0 +1,199 @@
+/*
+ * Copyright 2007 Sun Microsystems, Inc.  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 Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
+ * CA 95054 USA or visit www.sun.com if you need additional information or
+ * have any questions.
+ */
+
+/*
+ * This is not a regression test, but a micro-benchmark.
+ *
+ * I have run this as follows:
+ *
+ * repeat 5 for f in -client -server; do mergeBench dolphin . jr -dsa -da $f TypeCheckMicroBenchmark.java; done
+ *
+ *
+ * @author Martin Buchholz
+ */
+
+import java.util.*;
+
+public class TypeCheckMicroBenchmark {
+    abstract static class Job {
+        private final String name;
+        Job(String name) { this.name = name; }
+        String name() { return name; }
+        abstract void work() throws Throwable;
+    }
+
+    private static void collectAllGarbage() {
+        final java.util.concurrent.CountDownLatch drained
+            = new java.util.concurrent.CountDownLatch(1);
+        try {
+            System.gc();        // enqueue finalizable objects
+            new Object() { protected void finalize() {
+                drained.countDown(); }};
+            System.gc();        // enqueue detector
+            drained.await();    // wait for finalizer queue to drain
+            System.gc();        // cleanup finalized objects
+        } catch (InterruptedException e) { throw new Error(e); }
+    }
+
+    /**
+     * Runs each job for long enough that all the runtime compilers
+     * have had plenty of time to warm up, i.e. get around to
+     * compiling everything worth compiling.
+     * Returns array of average times per job per run.
+     */
+    private static long[] time0(Job ... jobs) throws Throwable {
+        final long warmupNanos = 10L * 1000L * 1000L * 1000L;
+        long[] nanoss = new long[jobs.length];
+        for (int i = 0; i < jobs.length; i++) {
+            collectAllGarbage();
+            long t0 = System.nanoTime();
+            long t;
+            int j = 0;
+            do { jobs[i].work(); j++; }
+            while ((t = System.nanoTime() - t0) < warmupNanos);
+            nanoss[i] = t/j;
+        }
+        return nanoss;
+    }
+
+    private static void time(Job ... jobs) throws Throwable {
+
+        long[] warmup = time0(jobs); // Warm up run
+        long[] nanoss = time0(jobs); // Real timing run
+        long[] milliss = new long[jobs.length];
+        double[] ratios = new double[jobs.length];
+
+        final String nameHeader   = "Method";
+        final String millisHeader = "Millis";
+        final String ratioHeader  = "Ratio";
+
+        int nameWidth   = nameHeader.length();
+        int millisWidth = millisHeader.length();
+        int ratioWidth  = ratioHeader.length();
+
+        for (int i = 0; i < jobs.length; i++) {
+            nameWidth = Math.max(nameWidth, jobs[i].name().length());
+
+            milliss[i] = nanoss[i]/(1000L * 1000L);
+            millisWidth = Math.max(millisWidth,
+                                   String.format("%d", milliss[i]).length());
+
+            ratios[i] = (double) nanoss[i] / (double) nanoss[0];
+            ratioWidth = Math.max(ratioWidth,
+                                  String.format("%.3f", ratios[i]).length());
+        }
+
+        String format = String.format("%%-%ds %%%dd %%%d.3f%%n",
+                                      nameWidth, millisWidth, ratioWidth);
+        String headerFormat = String.format("%%-%ds %%%ds %%%ds%%n",
+                                            nameWidth, millisWidth, ratioWidth);
+        System.out.printf(headerFormat, "Method", "Millis", "Ratio");
+
+        // Print out absolute and relative times, calibrated against first job
+        for (int i = 0; i < jobs.length; i++)
+            System.out.printf(format, jobs[i].name(), milliss[i], ratios[i]);
+    }
+
+    private static String keywordValue(String[] args, String keyword) {
+        for (String arg : args)
+            if (arg.startsWith(keyword))
+                return arg.substring(keyword.length() + 1);
+        return null;
+    }
+
+    private static int intArg(String[] args, String keyword, int defaultValue) {
+        String val = keywordValue(args, keyword);
+        return val == null ? defaultValue : Integer.parseInt(val);
+    }
+
+    private static java.util.regex.Pattern patternArg(String[] args,
+                                                      String keyword) {
+        String val = keywordValue(args, keyword);
+        return val == null ? null : java.util.regex.Pattern.compile(val);
+    }
+
+    private static Job[] filter(java.util.regex.Pattern filter,
+                                Job[] jobs) {
+        if (filter == null) return jobs;
+        Job[] newJobs = new Job[jobs.length];
+        int n = 0;
+        for (Job job : jobs)
+            if (filter.matcher(job.name()).find())
+                newJobs[n++] = job;
+        // Arrays.copyOf not available in JDK 5
+        Job[] ret = new Job[n];
+        System.arraycopy(newJobs, 0, ret, 0, n);
+        return ret;
+    }
+
+    /**
+     * Usage: [iterations=N] [size=N] [filter=REGEXP]
+     */
+    public static void main(String[] args) throws Throwable {
+        final int iterations = intArg(args, "iterations", 30000);
+        final int size       = intArg(args, "size", 1000);
+        final java.util.regex.Pattern filter
+            = patternArg(args, "filter");
+
+        final List<Integer> list = new ArrayList<Integer>();
+        final Random rnd = new Random();
+        for (int i = 0; i < size; i++)
+            list.add(rnd.nextInt());
+        final Class klazz = Integer.class;
+
+        final Job[] jobs = {
+            new Job("toArray(T[])") { void work() {
+                Object[] a = new Integer[0];
+                for (int i = 0; i < iterations; i++) {
+                    try { list.toArray(a); }
+                    catch (ArrayStoreException ase) {
+                        throw new ClassCastException(); }}}},
+            new Job("isInstance") { void work() {
+                for (int i = 0; i < iterations; i++) {
+                    for (Object x : list.toArray())
+                        if (! (x != null && klazz.isInstance(x)))
+                            throw new ClassCastException(); }}},
+            new Job("Class.cast") { void work() {
+                for (int i = 0; i < iterations; i++) {
+                    for (Object x : list.toArray())
+                        klazz.cast(x); }}},
+            new Job("write into array") { void work() {
+                Object[] a = new Integer[1];
+                for (int i = 0; i < iterations; i++) {
+                    for (Object x : list.toArray()) {
+                        try { a[0] = x; }
+                        catch (ArrayStoreException _) {
+                            throw new ClassCastException(); }}}}},
+            new Job("write into dynamic array") { void work() {
+                for (int i = 0; i < iterations; i++) {
+                    for (Object x : list.toArray()) {
+                        Object[] a = (Object[])
+                            java.lang.reflect.Array.newInstance(klazz, 1);
+                        try { a[0] = x; }
+                        catch (ArrayStoreException _) {
+                            throw new ClassCastException(); }}}}}
+        };
+
+        time(filter(filter, jobs));
+    }
+}
diff --git a/jdk/test/java/lang/Class/asSubclass/BasicUnit.java b/jdk/test/java/lang/Class/asSubclass/BasicUnit.java
new file mode 100644
index 0000000..68cf1c3
--- /dev/null
+++ b/jdk/test/java/lang/Class/asSubclass/BasicUnit.java
@@ -0,0 +1,51 @@
+/*
+ * Copyright 2004 Sun Microsystems, Inc.  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 Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
+ * CA 95054 USA or visit www.sun.com if you need additional information or
+ * have any questions.
+ */
+
+/*
+ * @test
+ * @bug 5030212
+ * @summary please add a typesafe cast for Class<?> types
+ * @author gafter
+ *
+ * @compile -Xlint:unchecked -Werror -source 1.5 BasicUnit.java
+ * @run main BasicUnit
+ */
+
+interface Int {
+    void main();
+}
+
+class MyInt implements Int {
+    public void main() {
+        System.out.println("Hello, world!");
+    }
+}
+
+public class BasicUnit {
+    static <T extends Int> T factory(Class<T> c) throws Throwable {
+        return c.newInstance();
+    }
+    public static void main(String[] args) throws Throwable {
+        factory(Class.forName("MyInt").asSubclass(Int.class)).main();
+    }
+}
diff --git a/jdk/test/java/lang/Class/forName/InitArg.java b/jdk/test/java/lang/Class/forName/InitArg.java
new file mode 100644
index 0000000..12a3be2
--- /dev/null
+++ b/jdk/test/java/lang/Class/forName/InitArg.java
@@ -0,0 +1,52 @@
+/*
+ * Copyright 1998 Sun Microsystems, Inc.  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 Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
+ * CA 95054 USA or visit www.sun.com if you need additional information or
+ * have any questions.
+ */
+
+/* @test
+   @bug 4131701
+   @summary This is a basic sanity test for the Class.forName
+            variant that the 'whether-initialize' arg.
+ */
+
+class x123 {
+    static {
+        InitArg.x123Initialized = true;
+    }
+}
+
+public class InitArg {
+
+    public static boolean x123Initialized = false;
+
+    public static void main(String[] args) throws Exception {
+        Class c = Class.forName("x123", false,
+                                InitArg.class.getClassLoader());
+        if (x123Initialized) {
+            throw new Exception("forName should not run initializer");
+        }
+        Class d = Class.forName("x123", true,
+                                InitArg.class.getClassLoader());
+        if (!x123Initialized) {
+            throw new Exception("forName not running initializer");
+        }
+    }
+}
diff --git a/jdk/test/java/lang/Class/forName/InvalidNameWithSlash.java b/jdk/test/java/lang/Class/forName/InvalidNameWithSlash.java
new file mode 100644
index 0000000..ae31307
--- /dev/null
+++ b/jdk/test/java/lang/Class/forName/InvalidNameWithSlash.java
@@ -0,0 +1,42 @@
+/*
+ * Copyright 1998 Sun Microsystems, Inc.  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 Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
+ * CA 95054 USA or visit www.sun.com if you need additional information or
+ * have any questions.
+ */
+
+/* @test
+   @bug 4104861
+   @summary forName is accepting methods with slashes
+   @author James Bond/007
+ */
+
+public class InvalidNameWithSlash {
+    public static void main(String[] args) throws Exception {
+        boolean exceptionOccurred = false;
+        try {
+            Class c = Class.forName("java/lang.Object");
+        } catch (Exception e) {
+            exceptionOccurred = true;
+        }
+        if (!exceptionOccurred) {
+            throw new Exception("forName accepting names with slashes?");
+        }
+    }
+}
diff --git a/jdk/test/java/lang/Class/forName/NonJavaNames.java b/jdk/test/java/lang/Class/forName/NonJavaNames.java
new file mode 100644
index 0000000..5c18179
--- /dev/null
+++ b/jdk/test/java/lang/Class/forName/NonJavaNames.java
@@ -0,0 +1,100 @@
+/*
+ * Copyright 2003 Sun Microsystems, Inc.  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 Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
+ * CA 95054 USA or visit www.sun.com if you need additional information or
+ * have any questions.
+ */
+
+/*
+ * Used by NonJavaNames.sh; needs to be run with a classpath including
+ * test/java/lang/Class/forName/classes
+ */
+
+public class NonJavaNames {
+    public static class Baz {
+        public Baz(){}
+    }
+
+    public static interface myInterface {
+    }
+
+     NonJavaNames.myInterface create(){
+         // With target 1.5, this class's name will include a '+'
+         // instead of a '$'.
+         class Baz2 implements NonJavaNames.myInterface {
+             public Baz2(){}
+         }
+
+        return new Baz2();
+     }
+
+    public static void main(String[] args) throws Exception {
+        NonJavaNames.Baz bz = new NonJavaNames.Baz();
+
+        String name;
+
+        if (Class.forName(name=bz.getClass().getName()) != NonJavaNames.Baz.class) {
+            System.err.println("Class object from forName does not match object.class.");
+            System.err.println("Failures for class ``" + name + "''.");
+            throw new RuntimeException();
+        }
+
+        NonJavaNames.myInterface bz2 = (new NonJavaNames()).create();
+        if (Class.forName(name=bz2.getClass().getName()) != bz2.getClass()) {
+            System.err.println("Class object from forName does not match getClass.");
+            System.err.println("Failures for class ``" + name + "''.");
+            throw new RuntimeException();
+        }
+
+        String goodNonJavaClassNames []  = {
+            ",",
+            "+",
+            "-",
+            "0",
+            "3",
+            // ":", These names won't work under windows.
+            // "<",
+            // ">",
+            "Z",
+            "]"
+        };
+
+        for(String s : goodNonJavaClassNames) {
+            System.out.println("Testing good class name ``" + s + "''");
+            Class.forName(s);
+        }
+
+        String badNonJavaClassNames []  = {
+            ";",
+            "[",
+            "."
+        };
+
+        for(String s : badNonJavaClassNames) {
+            System.out.println("Testing bad class name ``" + s + "''");
+            try {
+                Class.forName(s);
+            } catch (Exception e) {
+                // Expected behavior
+                continue;
+            }
+            throw new RuntimeException("Bad class name ``" + s + "'' accepted.");
+        }
+    }
+}
diff --git a/jdk/test/java/lang/Class/forName/NonJavaNames.sh b/jdk/test/java/lang/Class/forName/NonJavaNames.sh
new file mode 100644
index 0000000..0071f9e
--- /dev/null
+++ b/jdk/test/java/lang/Class/forName/NonJavaNames.sh
@@ -0,0 +1,110 @@
+#
+# Copyright 2003 Sun Microsystems, Inc.  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 Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
+# CA 95054 USA or visit www.sun.com if you need additional information or
+# have any questions.
+#
+
+# @test
+# @bug 4952558
+# @summary Verify names that aren't legal Java names are accepted by forName.
+# @author Joseph D. Darcy
+# @compile -source 1.5 -target 1.5 NonJavaNames.java
+# @run shell NonJavaNames.sh
+
+# This test uses hand-generated class files stored in the ./classes
+# directory.  After the renaming done below, those class files have
+# single character names that are legal class names under class file
+# version 49 but *not* legal Java language identifiers; e.g. "3" and
+# "+".  First, Z.java is compiled to Z.class using "-target 1.5."
+# Next, to create a test class file, the appropriate name structures
+# within the class files are updated, as is the "Hello world" string
+# the class's main method prints out.  If the definition of the
+# semantics of "-target 1.5" changes, the test class files should be
+# regenerated.
+
+# Verify directory context variables are set
+if [ "${TESTJAVA}" = "" ]
+then
+  echo "TESTJAVA not set.  Test cannot execute.  Failed."
+  exit 1
+fi
+
+if [ "${TESTSRC}" = "" ]
+then
+  echo "TESTSRC not set.  Test cannot execute.  Failed."
+  exit 1
+fi
+
+if [ "${TESTCLASSES}" = "" ]
+then
+  echo "TESTCLASSES not set.  Test cannot execute.  Failed."
+  exit 1
+fi
+
+# All preconditions are met; run the tests
+
+OS=`uname -s`;
+# Set classpath separator
+case "$OS" in
+        Windows* | CYGWIN* )
+	SEP=";"
+        ;;
+
+	* )
+	SEP=":"
+esac
+
+# Copy "hyphen.class" to "-.class"
+
+COPYHYPHEN="cp ${TESTSRC}/classes/hyphen.class ${TESTCLASSES}/-.class"
+$COPYHYPHEN
+
+COPYCOMMA="cp ${TESTSRC}/classes/comma.class ${TESTCLASSES}/,.class"
+$COPYCOMMA
+
+COPYPERIOD="cp ${TESTSRC}/classes/period.class ${TESTCLASSES}/..class"
+$COPYPERIOD
+
+COPYLEFTSQUARE="cp ${TESTSRC}/classes/left-square.class ${TESTCLASSES}/[.class"
+$COPYLEFTSQUARE
+
+COPYRIGHTSQUARE="cp ${TESTSRC}/classes/right-square.class ${TESTCLASSES}/].class"
+$COPYRIGHTSQUARE
+
+COPYPLUS="cp ${TESTSRC}/classes/plus.class ${TESTCLASSES}/+.class"
+$COPYPLUS
+
+COPYSEMICOLON="cp ${TESTSRC}/classes/semicolon.class ${TESTCLASSES}/;.class"
+$COPYSEMICOLON
+
+JAVA="$TESTJAVA/bin/java -classpath ${TESTSRC}/classes${SEP}${TESTCLASSES}"
+
+$JAVA NonJavaNames
+RESULT=$?
+
+case "$RESULT" in
+        0 )
+        exit 0;
+        ;;
+
+        * )
+        exit 1
+esac
+
diff --git a/jdk/test/java/lang/Class/forName/Z.java b/jdk/test/java/lang/Class/forName/Z.java
new file mode 100644
index 0000000..661fa44
--- /dev/null
+++ b/jdk/test/java/lang/Class/forName/Z.java
@@ -0,0 +1,32 @@
+/*
+ * Copyright 2003 Sun Microsystems, Inc.  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 Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
+ * CA 95054 USA or visit www.sun.com if you need additional information or
+ * have any questions.
+ */
+
+/*
+ * Source used to generated primordial class file for NonJavaNames
+ * test.
+ */
+public class Z {
+    public static void main(String argv[]) {
+        System.out.println("Hello world.");
+    }
+}
diff --git a/jdk/test/java/lang/Class/forName/classes/0.class b/jdk/test/java/lang/Class/forName/classes/0.class
new file mode 100644
index 0000000..b5b6c8f
--- /dev/null
+++ b/jdk/test/java/lang/Class/forName/classes/0.class
Binary files differ
diff --git a/jdk/test/java/lang/Class/forName/classes/3.class b/jdk/test/java/lang/Class/forName/classes/3.class
new file mode 100644
index 0000000..4d183b0
--- /dev/null
+++ b/jdk/test/java/lang/Class/forName/classes/3.class
Binary files differ
diff --git a/jdk/test/java/lang/Class/forName/classes/Z.class b/jdk/test/java/lang/Class/forName/classes/Z.class
new file mode 100644
index 0000000..cedf4a3
--- /dev/null
+++ b/jdk/test/java/lang/Class/forName/classes/Z.class
Binary files differ
diff --git a/jdk/test/java/lang/Class/forName/classes/comma.class b/jdk/test/java/lang/Class/forName/classes/comma.class
new file mode 100644
index 0000000..7d21d71
--- /dev/null
+++ b/jdk/test/java/lang/Class/forName/classes/comma.class
Binary files differ
diff --git a/jdk/test/java/lang/Class/forName/classes/hyphen.class b/jdk/test/java/lang/Class/forName/classes/hyphen.class
new file mode 100644
index 0000000..9ca3213
--- /dev/null
+++ b/jdk/test/java/lang/Class/forName/classes/hyphen.class
Binary files differ
diff --git a/jdk/test/java/lang/Class/forName/classes/left-square.class b/jdk/test/java/lang/Class/forName/classes/left-square.class
new file mode 100644
index 0000000..8d5009d
--- /dev/null
+++ b/jdk/test/java/lang/Class/forName/classes/left-square.class
Binary files differ
diff --git a/jdk/test/java/lang/Class/forName/classes/period.class b/jdk/test/java/lang/Class/forName/classes/period.class
new file mode 100644
index 0000000..2581aab
--- /dev/null
+++ b/jdk/test/java/lang/Class/forName/classes/period.class
Binary files differ
diff --git a/jdk/test/java/lang/Class/forName/classes/plus.class b/jdk/test/java/lang/Class/forName/classes/plus.class
new file mode 100644
index 0000000..32037d7
--- /dev/null
+++ b/jdk/test/java/lang/Class/forName/classes/plus.class
Binary files differ
diff --git a/jdk/test/java/lang/Class/forName/classes/right-square.class b/jdk/test/java/lang/Class/forName/classes/right-square.class
new file mode 100644
index 0000000..0b61551
--- /dev/null
+++ b/jdk/test/java/lang/Class/forName/classes/right-square.class
Binary files differ
diff --git a/jdk/test/java/lang/Class/forName/classes/semicolon.class b/jdk/test/java/lang/Class/forName/classes/semicolon.class
new file mode 100644
index 0000000..a152408
--- /dev/null
+++ b/jdk/test/java/lang/Class/forName/classes/semicolon.class
Binary files differ
diff --git a/jdk/test/java/lang/Class/getClasses/Sanity.java b/jdk/test/java/lang/Class/getClasses/Sanity.java
new file mode 100644
index 0000000..3e504eb
--- /dev/null
+++ b/jdk/test/java/lang/Class/getClasses/Sanity.java
@@ -0,0 +1,52 @@
+/*
+ * Copyright 1998 Sun Microsystems, Inc.  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 Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
+ * CA 95054 USA or visit www.sun.com if you need additional information or
+ * have any questions.
+ */
+
+/* @test
+   @bug 4028577
+   @summary Sanity check that Class.getClasses() works.
+   @author Anand Palaniswamy
+ */
+public class Sanity {
+    public class Base {
+        public class BInner { }
+        protected class BProtected { }
+        class BPackage { }
+    }
+
+    public class Derived extends Base {
+        public class DInner { }
+        protected class DProtected { }
+        class DPackage { }
+    }
+
+    public static void main(String[] args) throws Exception {
+        Class[] c = Derived.class.getClasses();
+        if (c.length != 2)
+            throw new Exception("Incorrect number of public classes returned");
+        for (int i = 0; i < c.length; i++) {
+            if (c[i] != Base.BInner.class &&
+                c[i] != Derived.DInner.class)
+               throw new Exception("Garbage in declared classes");
+        }
+    }
+}
diff --git a/jdk/test/java/lang/Class/getDeclaredClasses/Sanity.java b/jdk/test/java/lang/Class/getDeclaredClasses/Sanity.java
new file mode 100644
index 0000000..6acb891
--- /dev/null
+++ b/jdk/test/java/lang/Class/getDeclaredClasses/Sanity.java
@@ -0,0 +1,48 @@
+/*
+ * Copyright 1998-2002 Sun Microsystems, Inc.  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 Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
+ * CA 95054 USA or visit www.sun.com if you need additional information or
+ * have any questions.
+ */
+
+/* @test
+ * @bug 4028577 4726689
+ * @summary Sanity check that Class.getDeclaredClasses() works.
+ */
+public class Sanity {
+    static class Toplevel { }
+    class Nested { }
+
+    public static void main(String[] args) throws Exception {
+        class BlockLocal { };
+        new Object() { };
+        Class[] c = Sanity.class.getDeclaredClasses();
+        if (c.length < 2)
+             throw new Exception("Incorrect number of declared classes");
+
+        for (int i = 0; i < c.length; i++) {
+            String name = c[i].getName();
+            System.out.println(name);
+
+            if (c[i] != Nested.class && c[i] != Toplevel.class
+                && !name.matches("\\D\\w*\\$\\d*"))
+                throw new Exception("Unexpected class: " + name);
+        }
+    }
+}
diff --git a/jdk/test/java/lang/Class/getDeclaredClasses/TypeTag.java b/jdk/test/java/lang/Class/getDeclaredClasses/TypeTag.java
new file mode 100644
index 0000000..7316cf4
--- /dev/null
+++ b/jdk/test/java/lang/Class/getDeclaredClasses/TypeTag.java
@@ -0,0 +1,62 @@
+/*
+ * Copyright 1998-2002 Sun Microsystems, Inc.  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 Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
+ * CA 95054 USA or visit www.sun.com if you need additional information or
+ * have any questions.
+ */
+
+/* @test
+ * @bug 4185857 4726689
+ * @summary The array returned by getDeclaredClasses doesn't have the
+ *          array element type tag.
+ */
+public class TypeTag {
+
+    private static class Inner { }
+
+    public static void main(String[] args) throws Exception {
+        Class[] v = null;
+
+        v = Integer.TYPE.getDeclaredClasses();
+        if (v == null || v.length != 0)
+            throw new Exception("Integer.TYPE.getDeclaredClasses is not working");
+        System.out.println("Integer.TYPE: "+ v.toString());
+
+        v = TypeTag.class.getDeclaredClasses();
+        if (v == null)
+            throw new Exception("TypeTag.class.getDeclaredClasses returned null");
+        System.out.println("TypeTag.class: " + v.toString());
+
+        int n = 0;
+        for (int i = 0; i < v.length; i++) {
+            String name = v[i].getName();
+            System.out.print(name);
+
+            if (!name.matches("\\D\\w*\\$\\d*")) {
+                n++;
+                System.out.println(" -- user class");
+            } else {
+                System.out.println();
+            }
+        }
+
+        if (n != 1)
+            throw new Exception("TypeTag.class.getDeclaredClasses found too many classes");
+    }
+}
diff --git a/jdk/test/java/lang/Class/getDeclaredField/Exceptions.java b/jdk/test/java/lang/Class/getDeclaredField/Exceptions.java
new file mode 100644
index 0000000..96ebf06
--- /dev/null
+++ b/jdk/test/java/lang/Class/getDeclaredField/Exceptions.java
@@ -0,0 +1,64 @@
+/*
+ * Copyright 2002 Sun Microsystems, Inc.  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 Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
+ * CA 95054 USA or visit www.sun.com if you need additional information or
+ * have any questions.
+ */
+
+/**
+ * @test
+ * @bug 4319910
+ * @summary Verify that exceptions are thrown as expected.
+ */
+
+public class Exceptions {
+    int f0;
+    public int f1;
+    private int f2;
+    protected int f4;
+
+    private static final String [] npe = {null};
+    private static final String [] nsfe = {"f6"};
+    private static final String [] pass = {"f0", "f1", "f2", "f4"};
+
+    private void test(String s, Class ex) {
+        Throwable t = null;
+        try {
+            getClass().getDeclaredField(s);
+        } catch (Throwable x) {
+            if (ex.isAssignableFrom(x.getClass()))
+                t = x;
+        }
+        if ((t == null) && (ex != null))
+            throw new RuntimeException("expected " + ex.getName()
+                                       + " for " + s);
+        else
+            System.out.println(s + " OK");
+    }
+
+    public static void main(String [] args) {
+        Exceptions e = new Exceptions();
+        for (int i = 0; i < npe.length; i++)
+            e.test(npe[i], NullPointerException.class);
+        for (int i = 0; i < nsfe.length; i++)
+            e.test(nsfe[i], NoSuchFieldException.class);
+        for (int i = 0; i < pass.length; i++)
+            e.test(pass[i], null);
+    }
+}
diff --git a/jdk/test/java/lang/Class/getDeclaredMethod/Exceptions.java b/jdk/test/java/lang/Class/getDeclaredMethod/Exceptions.java
new file mode 100644
index 0000000..d4d75c7
--- /dev/null
+++ b/jdk/test/java/lang/Class/getDeclaredMethod/Exceptions.java
@@ -0,0 +1,64 @@
+/*
+ * Copyright 2002 Sun Microsystems, Inc.  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 Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
+ * CA 95054 USA or visit www.sun.com if you need additional information or
+ * have any questions.
+ */
+
+/**
+ * @test
+ * @bug 4319910
+ * @summary Verify that exceptions are thrown as expected.
+ */
+
+public class Exceptions {
+    void m0() {}
+    public void m1() {}
+    private void m2() {}
+    protected void m4() {}
+
+    private static final String [] npe = {null};
+    private static final String [] nsme = {"m6"};
+    private static final String [] pass = {"m0", "m1", "m2", "m4"};
+
+    private void test(String s, Class ex) {
+        Throwable t = null;
+        try {
+            getClass().getDeclaredMethod(s, new Class[] {});
+        } catch (Throwable x) {
+            if (ex.isAssignableFrom(x.getClass()))
+                t = x;
+        }
+        if ((t == null) && (ex != null))
+            throw new RuntimeException("expected " + ex.getName()
+                                       + " for " + s);
+        else
+            System.out.println(s + " OK");
+    }
+
+    public static void main(String [] args) {
+        Exceptions e = new Exceptions();
+        for (int i = 0; i < npe.length; i++)
+            e.test(npe[i], NullPointerException.class);
+        for (int i = 0; i < nsme.length; i++)
+            e.test(nsme[i], NoSuchMethodException.class);
+        for (int i = 0; i < pass.length; i++)
+            e.test(pass[i], null);
+    }
+}
diff --git a/jdk/test/java/lang/Class/getDeclaringClass/Sanity.java b/jdk/test/java/lang/Class/getDeclaringClass/Sanity.java
new file mode 100644
index 0000000..5ecac5e
--- /dev/null
+++ b/jdk/test/java/lang/Class/getDeclaringClass/Sanity.java
@@ -0,0 +1,47 @@
+/*
+ * Copyright 1998 Sun Microsystems, Inc.  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 Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
+ * CA 95054 USA or visit www.sun.com if you need additional information or
+ * have any questions.
+ */
+
+/* @test
+   @bug 4028577
+   @summary Sanity check that Class.getDeclaringClass() works.
+   @author Anand Palaniswamy
+ */
+public class Sanity {
+    class Nested  {
+    }
+
+    public static void main(String[] args) throws Exception {
+        if (Nested.class.getDeclaringClass() != Sanity.class)
+            throw new Exception("Not finding declaring class");
+
+        /* This will pass on old VM's that return null when this
+         * method was unimplemented. But write the test to keep
+         * regression from happening in the current code.
+         */
+        class BlockLocal {
+        };
+
+        if (BlockLocal.class.getDeclaringClass() != null)
+            throw new Exception("Finding declaring class for block local");
+    }
+}
diff --git a/jdk/test/java/lang/Class/getEnclosingClass/EnclosingClass.java b/jdk/test/java/lang/Class/getEnclosingClass/EnclosingClass.java
new file mode 100644
index 0000000..1b6675c
--- /dev/null
+++ b/jdk/test/java/lang/Class/getEnclosingClass/EnclosingClass.java
@@ -0,0 +1,363 @@
+/*
+ * Copyright 2004 Sun Microsystems, Inc.  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 Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
+ * CA 95054 USA or visit www.sun.com if you need additional information or
+ * have any questions.
+ */
+
+/*
+ *
+ * @summary Check getEnclosingClass and other methods
+ * @author Peter von der Ah\u00e9
+ *
+ * a) Top level classes
+ * b) Nested classes (static member classes)
+ * c) Inner classes (non-static member classes)
+ * d) Local classes (named classes declared within a method)
+ * e) Anonymous classes
+ */
+
+/*
+ * TODO:
+ * Test annotations
+ * Test Locals in static initializers
+ * Test Locals in methods
+ * Test Locals in constructors
+ * Test interfaces
+ * Test enums
+ * Test method with a String[] argument
+ */
+
+//package
+
+import common.TestMe;
+
+interface MakeClass {
+    Class<?> make();
+}
+
+public class EnclosingClass {
+    public EnclosingClass() {
+        aec = (new Object() {}).getClass();
+    }
+    static class Nested {
+        static class NestedNested {
+        }
+        class NestedInner {
+        }
+        Class<?> nestedLocal0;
+        Class<?> nestedLocal1;
+        Class<?> nestedLocal2;
+        {
+            class NestedLocal0 {};
+            nestedLocal0 = NestedLocal0.class;
+            nestedMethod1();
+            nestedMethod2(null);
+        }
+        void nestedMethod1() {
+            class NestedLocal1 {}
+            nestedLocal1 = NestedLocal1.class;
+        }
+        void nestedMethod2(String[] args) {
+            class NestedLocal2 {}
+            nestedLocal2 = NestedLocal2.class;
+        }
+        Class<?> nestedAnonymous = (new Object() {}).getClass();
+        static enum NestedNestedEnum {
+        }
+        enum NestedInnerEnum {
+        }
+    }
+
+    class Inner {
+        class InnerInner {
+        }
+        Class<?> innerLocal0;
+        Class<?> innerLocal1;
+        Class<?> innerLocal2;
+        {
+            class InnerLocal0 {
+            };
+            innerLocal0 = InnerLocal0.class;
+            innerMethod1();
+            innerMethod2(null);
+        }
+        void innerMethod1() {
+            class InnerLocal1 {}
+            innerLocal1 = InnerLocal1.class;
+        }
+        void innerMethod2(String[] args) {
+            class InnerLocal2 {}
+            innerLocal2 = InnerLocal2.class;
+        }
+        Class<?> innerAnonymous = (new Object() {}).getClass();
+    }
+
+    @TestMe(desc="top level class",
+            encl="null",
+            simple="EnclosingClass",
+            canonical="EnclosingClass")
+        public Class<?> a = EnclosingClass.class;
+
+    @TestMe(desc="nested class within top level class",
+            encl="class EnclosingClass",
+            simple="Nested",
+            canonical="EnclosingClass.Nested")
+        public Class<?> ab = Nested.class;
+    @TestMe(desc="inner class within top level class",
+            encl="class EnclosingClass",
+            simple="Inner",
+            canonical="EnclosingClass.Inner")
+        public Class<?> ac = Inner.class;
+    @TestMe(desc="local class within top level class",
+            encl="class EnclosingClass",
+            simple="Local0",
+            hasCanonical=false)
+        public Class<?> ad0;
+    @TestMe(desc="local class within top level class",
+            encl="class EnclosingClass",
+            simple="Local1",
+            hasCanonical=false)
+        public Class<?> ad1;
+    @TestMe(desc="local class within top level class",
+            encl="class EnclosingClass",
+            simple="Local2",
+            hasCanonical=false)
+        public Class<?> ad2;
+    @TestMe(desc="local class within a top level class static initializer" ,
+            encl="class EnclosingClass",
+            simple="StaticLocal0",
+            hasCanonical=false)
+        public Class<?> sad0;
+    @TestMe(desc="local class within a top level class static method" ,
+            encl="class EnclosingClass",
+            simple="StaticLocal1",
+            hasCanonical=false)
+        public Class<?> sad1;
+    @TestMe(desc="local class within a top level class static method",
+            encl="class EnclosingClass",
+            simple="StaticLocal2",
+            hasCanonical=false)
+        public Class<?> sad2;
+    {
+        class Local0 {
+            class LocalInner {}
+            {
+                class LocalLocal {};
+                dd = LocalLocal.class;
+                de = (new Object() {}).getClass();
+            }
+        };
+        ad0 = Local0.class;
+        dc = Local0.LocalInner.class;
+        new Local0();
+        method1();
+        method2(null);
+        sad0 = staticLocal0;
+        sad1 = staticMethod1();
+        sad2 = staticMethod2(null);
+    }
+    static Class<?> staticLocal0;
+    static {
+        class StaticLocal0 {};
+        staticLocal0 = StaticLocal0.class;
+    }
+    static Class<?> staticMethod1() {
+        class StaticLocal1 {};
+        return StaticLocal1.class;
+    }
+    static Class<?> staticMethod2(String[] args) {
+        class StaticLocal2 {};
+        return StaticLocal2.class;
+    }
+    void method1() {
+        class Local1 {};
+        ad1 = Local1.class;
+    }
+    void method2(String[] args) {
+        class Local2 {};
+        ad2 = Local2.class;
+    }
+    @TestMe(desc="anonymous class within top level class",
+            encl="class EnclosingClass",
+            simple="",
+            hasCanonical=false)
+        public Class<?> ae = (new Object() {}).getClass();
+    @TestMe(desc="anonymous class within top level class constructor",
+            encl="class EnclosingClass",
+            simple="",
+            hasCanonical=false)
+        public Class<?> aec;
+
+    @TestMe(desc="nested class within nested class",
+            encl="class EnclosingClass$Nested",
+            simple="NestedNested",
+            canonical="EnclosingClass.Nested.NestedNested")
+        public Class<?> bb = Nested.NestedNested.class;
+    @TestMe(desc="inner class within nested class",
+            encl="class EnclosingClass$Nested",
+            simple="NestedInner",
+            canonical="EnclosingClass.Nested.NestedInner")
+        public Class<?> bc = Nested.NestedInner.class;
+    @TestMe(desc="local class within nested class",
+            encl="class EnclosingClass$Nested",
+            simple="NestedLocal0",
+            hasCanonical=false)
+        public Class<?> bd0 = (new Nested()).nestedLocal0;
+    @TestMe(desc="local class within nested class",
+            encl="class EnclosingClass$Nested",
+            simple="NestedLocal1",
+            hasCanonical=false)
+        public Class<?> bd1 = (new Nested()).nestedLocal1;
+    @TestMe(desc="local class within nested class",
+            encl="class EnclosingClass$Nested",
+            simple="NestedLocal2",
+            hasCanonical=false)
+        public Class<?> bd2 = (new Nested()).nestedLocal2;
+    @TestMe(desc="anonymous class within nested class",
+            encl="class EnclosingClass$Nested",
+            simple="",
+            hasCanonical=false)
+        public Class<?> be = (new Nested()).nestedAnonymous;
+
+    @TestMe(desc="nested class within an inner class", encl="", simple="")
+        public Class<?> cb = Void.class; // not legal
+    @TestMe(desc="inner class within an inner class",
+            encl="class EnclosingClass$Inner",
+            simple="InnerInner",
+            canonical="EnclosingClass.Inner.InnerInner")
+        public Class<?> cc = ((new Inner()).new InnerInner()).getClass();
+    @TestMe(desc="local class within an inner class",
+            encl="class EnclosingClass$Inner",
+            simple="InnerLocal0",
+            hasCanonical=false)
+        public Class<?> cd = (new Inner()).innerLocal0;
+    @TestMe(desc="anonymous class within an inner class",
+            encl="class EnclosingClass$Inner",
+            simple="",
+            hasCanonical=false)
+        public Class<?> ce = (new Inner()).innerAnonymous;
+
+    @TestMe(desc="nested class within a local class", encl="", simple="")
+        public Class<?> db = Void.class; // not legal
+    @TestMe(desc="inner class within a local class",
+            encl="class EnclosingClass$1Local0",
+            simple="LocalInner",
+            hasCanonical=false)
+        public Class<?> dc; // initialized above
+    @TestMe(desc="local class within a local class",
+            encl="class EnclosingClass$1Local0",
+            simple="LocalLocal",
+            hasCanonical=false)
+        public Class<?> dd; // initialized above
+    @TestMe(desc="anonymous class within a local class",
+            encl="class EnclosingClass$1Local0",
+            simple="",
+            hasCanonical=false)
+        public Class<?> de; // initialized above
+
+    @TestMe(desc="nested class within an anonymous class", encl="", simple="")
+        public Class<?> eb = Void.class; // not legal
+    @TestMe(desc="inner class within an anonymous class",
+            encl="class EnclosingClass$3",
+            simple="AnonymousInner",
+            hasCanonical=false)
+        public Class<?> ec = new MakeClass() {
+                class AnonymousInner {}
+                public Class<?> make() { return AnonymousInner.class; }
+            }.make();
+    @TestMe(desc="local class within an anonymous class",
+            encl="class EnclosingClass$4",
+            simple="AnonymousLocal",
+            hasCanonical=false)
+        public Class<?> ed = new MakeClass() {
+                Class<?> c;
+                {
+                    class AnonymousLocal {}
+                    c = AnonymousLocal.class;
+                }
+                public Class<?> make() { return c; }
+            }.make();
+    @TestMe(desc="anonymous class within an anonymous class",
+            encl="class EnclosingClass$5",
+            simple="",
+            hasCanonical=false)
+        public Class<?> ee = new MakeClass() {
+                Class<?> c;
+                {
+                    c = new Object() {}.getClass();
+                }
+                public Class<?> make() { return c; }
+            }.make();
+
+    @TestMe(desc="the primitive boolean type",
+            encl="null",
+            simple="boolean",
+            canonical="boolean")
+        public Class<?> booleanClass = boolean.class;
+
+    @TestMe(desc="the primitive char type",
+            encl="null",
+            simple="char",
+            canonical="char")
+        public Class<?> charClass = char.class;
+
+    @TestMe(desc="the primitive byte type",
+            encl="null",
+            simple="byte",
+            canonical="byte")
+        public Class<?> byteClass = byte.class;
+
+    @TestMe(desc="the primitive short type",
+            encl="null",
+            simple="short",
+            canonical="short")
+        public Class<?> shortClass = short.class;
+
+    @TestMe(desc="the primitive int type",
+            encl="null",
+            simple="int",
+            canonical="int")
+        public Class<?> intClass = int.class;
+
+    @TestMe(desc="the primitive long type",
+            encl="null",
+            simple="long",
+            canonical="long")
+        public Class<?> longClass = long.class;
+
+    @TestMe(desc="the primitive float type",
+            encl="null",
+            simple="float",
+            canonical="float")
+        public Class<?> floatClass = float.class;
+
+    @TestMe(desc="the primitive double type",
+            encl="null",
+            simple="double",
+            canonical="double")
+        public Class<?> doubleClass = double.class;
+
+    @TestMe(desc="the primitive void type",
+            encl="null",
+            simple="void",
+            canonical="void")
+        public Class<?> voidClass = void.class;
+
+}
diff --git a/jdk/test/java/lang/Class/getEnclosingClass/EnclosingClassTest.java b/jdk/test/java/lang/Class/getEnclosingClass/EnclosingClassTest.java
new file mode 100644
index 0000000..a2be80b
--- /dev/null
+++ b/jdk/test/java/lang/Class/getEnclosingClass/EnclosingClassTest.java
@@ -0,0 +1,140 @@
+/*
+ * Copyright 2004 Sun Microsystems, Inc.  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 Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
+ * CA 95054 USA or visit www.sun.com if you need additional information or
+ * have any questions.
+ */
+
+/*
+ * @test
+ * @bug 4992173 4992170
+ *
+ * @run shell make_src.sh
+ * @run shell build.sh
+ * @run main/othervm -esa -ea EnclosingClassTest
+ *
+ * @summary Check getEnclosingClass and other methods
+ * @author Peter von der Ah\u00e9
+ */
+
+/*
+ * We have five kinds of classes:
+ * a) Top level classes
+ * b) Nested classes (static member classes)
+ * c) Inner classes (non-static member classes)
+ * d) Local classes (named classes declared within a method)
+ * e) Anonymous classes
+ *
+ * Each one can be within a package or not.
+ * Kinds b-e can/must be within kinds a-e.
+ * This gives us a three dimensional space:
+ * 1. dimension: b-e
+ * 2. dimension: a-e
+ * 3. dimension: packages
+ *
+ * We make a two dimensional matrix of (b-e)x(a-e) and change the
+ * package configuration on that:
+ *
+ *   b c d e
+ * a x x x x
+ * b x x x x
+ * c o x x x  where o means "not legal"
+ * d o x x x
+ * e o x x x
+ */
+
+import java.util.List;
+import java.util.LinkedList;
+import java.lang.reflect.Field;
+import common.TestMe;
+
+public class EnclosingClassTest {
+    static void info(Class<?> c, Class<?> encClass, String desc) {
+        if (!"".equals(desc))
+            System.out.println(desc + ":");
+        System.out.println(c);
+        System.out.println("\tis enclosed by:\t\t" + encClass);
+        System.out.println("\thas simple name:\t`" +
+                           c.getSimpleName() + "'");
+        System.out.println("\thas canonical name:\t`" +
+                           c.getCanonicalName() + "'");
+    }
+
+    static void match(String actual, String expected) {
+        assert((actual == null && expected == null) || actual.equals(expected));
+        System.out.println("\t`" +
+                           actual + "' matches expected `" +
+                           expected + "'");
+    }
+
+    static void check(Class<?> c, Class<?> enc,
+                      String encName, String encNameExpected,
+                      String simpleName, String simpleNameExpected,
+                      String canonicalName, String canonicalNameExpected) {
+        match(encName, encNameExpected);
+        match(simpleName, simpleNameExpected);
+        match(canonicalName, canonicalNameExpected);
+    }
+
+    static void testClass(Class<?> c, TestMe annotation, Field f) {
+        if (Void.class.equals(c))
+            return;
+        Class<?> encClass = c.getEnclosingClass();
+        c.getEnclosingMethod(); // make sure it does not crash
+        c.getEnclosingConstructor(); // make sure it does not crash
+        info(c, encClass, annotation.desc());
+        check(c, encClass,
+              ""+encClass, annotation.encl(),
+              c.getSimpleName(), annotation.simple(),
+              c.getCanonicalName(),
+              annotation.hasCanonical() ? annotation.canonical() : null);
+        if (void.class.equals(c))
+            return;
+        Class<?> array = java.lang.reflect.Array.newInstance(c, 0).getClass();
+        check(array, array.getEnclosingClass(),
+              "", "",
+              array.getSimpleName(), annotation.simple()+"[]",
+              array.getCanonicalName(),
+              annotation.hasCanonical() ? annotation.canonical()+"[]" : null);
+    }
+
+    static void test(Object tests) {
+        for (Field f : tests.getClass().getFields()) {
+            TestMe annotation = f.getAnnotation(TestMe.class);
+            if (annotation != null) {
+                try {
+                    testClass((Class<?>)f.get(tests), annotation, f);
+                } catch (AssertionError ex) {
+                    System.err.println("Error in " +
+                                       tests.getClass().getName() +
+                                       "." + f.getName());
+                    throw ex;
+                } catch (IllegalAccessException ex) {
+                    ex.printStackTrace();
+                    throw new RuntimeException(ex);
+                }
+            }
+        }
+    }
+    public static void main(String[] args) {
+        test(new EnclosingClass());
+        test(new pkg1.EnclosingClass());
+        test(new pkg1.pkg2.EnclosingClass());
+    }
+}
diff --git a/jdk/test/java/lang/Class/getEnclosingClass/T4992170.java b/jdk/test/java/lang/Class/getEnclosingClass/T4992170.java
new file mode 100644
index 0000000..6304377
--- /dev/null
+++ b/jdk/test/java/lang/Class/getEnclosingClass/T4992170.java
@@ -0,0 +1,48 @@
+/*
+ * Copyright 2004 Sun Microsystems, Inc.  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 Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
+ * CA 95054 USA or visit www.sun.com if you need additional information or
+ * have any questions.
+ */
+
+/*
+ * @test
+ * @bug 4992170
+ *
+ * @run main/othervm -esa -ea T4992170
+ *
+ * @summary enclosing type parameter missing in anonymous and local classes
+ * @author Neal Gafter
+ */
+
+import java.lang.reflect.*;
+
+class A<T> {
+    Object o = new Object() {
+        public T t;
+    };
+}
+
+public class T4992170 {
+    public static void main(String[] args) throws NoSuchFieldException {
+        Type t = new A<Integer>().o.getClass().getField("t").getGenericType();
+        if (!(t instanceof TypeVariable))
+            throw new Error("" + t);
+    }
+}
diff --git a/jdk/test/java/lang/Class/getEnclosingClass/build.sh b/jdk/test/java/lang/Class/getEnclosingClass/build.sh
new file mode 100644
index 0000000..29099af
--- /dev/null
+++ b/jdk/test/java/lang/Class/getEnclosingClass/build.sh
@@ -0,0 +1,41 @@
+#
+# Copyright 2004 Sun Microsystems, Inc.  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 Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
+# CA 95054 USA or visit www.sun.com if you need additional information or
+# have any questions.
+#
+
+# -*- shell-script -*-
+#
+# @summary Check getEnclosingClass and other methods
+# @author Peter von der Ahé
+
+OS=`uname -s`;
+case "${OS}" in
+        Windows* | CYGWIN* )
+                SEP=";"
+        ;;
+
+        * )
+        SEP=":"
+        ;;
+esac
+
+JAVAC=${TESTJAVA}/bin/javac
+${JAVAC} -d ${TESTCLASSES} -sourcepath ${TESTSRC}${SEP}. ${TESTSRC}/EnclosingClassTest.java
diff --git a/jdk/test/java/lang/Class/getEnclosingClass/common/TestMe.java b/jdk/test/java/lang/Class/getEnclosingClass/common/TestMe.java
new file mode 100644
index 0000000..2425c36
--- /dev/null
+++ b/jdk/test/java/lang/Class/getEnclosingClass/common/TestMe.java
@@ -0,0 +1,41 @@
+/*
+ * Copyright 2004 Sun Microsystems, Inc.  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 Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
+ * CA 95054 USA or visit www.sun.com if you need additional information or
+ * have any questions.
+ */
+
+/*
+ * @summary Check getEnclosingClass and other methods
+ * @author Peter von der Ah\u00e9
+ */
+
+package common;
+
+import java.lang.annotation.Retention;
+import java.lang.annotation.RetentionPolicy;
+
+@Retention(RetentionPolicy.RUNTIME)
+public @interface TestMe {
+    String desc();
+    String encl();
+    String simple();
+    boolean hasCanonical() default true;
+    String canonical() default "";
+}
diff --git a/jdk/test/java/lang/Class/getEnclosingClass/make_src.sh b/jdk/test/java/lang/Class/getEnclosingClass/make_src.sh
new file mode 100644
index 0000000..ee61ac8
--- /dev/null
+++ b/jdk/test/java/lang/Class/getEnclosingClass/make_src.sh
@@ -0,0 +1,40 @@
+#
+# Copyright 2004 Sun Microsystems, Inc.  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 Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
+# CA 95054 USA or visit www.sun.com if you need additional information or
+# have any questions.
+#
+
+# -*- shell-script -*-
+# @summary Check getEnclosingClass and other methods
+# @author Peter von der Ahé
+
+rm -rf   pkg1
+mkdir    pkg1
+mkdir -p pkg1/pkg2
+
+sed '
+s/canonical="EnclosingClass/canonical="pkg1.EnclosingClass/g;
+s/"class EnclosingClass/"class pkg1.EnclosingClass/g;
+s/\/\/package/package pkg1;/g' < ${TESTSRC}/EnclosingClass.java > pkg1/EnclosingClass.java
+
+sed '
+s/canonical="EnclosingClass/canonical="pkg1.pkg2.EnclosingClass/g;
+s/"class EnclosingClass/"class pkg1.pkg2.EnclosingClass/g;
+s/\/\/package/package pkg1.pkg2;/g' < ${TESTSRC}/EnclosingClass.java > pkg1/pkg2/EnclosingClass.java
diff --git a/jdk/test/java/lang/Class/getEnclosingConstructor/EnclosingConstructorTests.java b/jdk/test/java/lang/Class/getEnclosingConstructor/EnclosingConstructorTests.java
new file mode 100644
index 0000000..fe963fb
--- /dev/null
+++ b/jdk/test/java/lang/Class/getEnclosingConstructor/EnclosingConstructorTests.java
@@ -0,0 +1,102 @@
+/*
+ * Copyright 2004 Sun Microsystems, Inc.  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 Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
+ * CA 95054 USA or visit www.sun.com if you need additional information or
+ * have any questions.
+ */
+
+/*
+ * @test
+ * @bug 4962341
+ * @summary Check getEnclosingMethod method
+ * @author Joseph D. Darcy
+ */
+
+import java.lang.reflect.Constructor;
+import java.lang.annotation.*;
+
+public class EnclosingConstructorTests {
+    static Class<?> anonymousClass;
+    static Class<?> localClass;
+    static Class<?> anotherLocalClass;
+
+    static {
+        Cloneable c = new Cloneable() {}; // anonymous cloneable
+        anonymousClass = c.getClass();
+    }
+
+    @ConstructorDescriptor("EnclosingConstructorTests()")
+    EnclosingConstructorTests() {
+        class Local {};
+        Local l = new Local();
+        localClass = l.getClass();
+    }
+
+
+    @ConstructorDescriptor("private EnclosingConstructorTests(int)")
+    private EnclosingConstructorTests(int i) {
+        class Local {};
+        Local l = new Local();
+        anotherLocalClass = l.getClass();
+    }
+
+
+    static int examine(Class enclosedClass, String constructorSig) {
+        Constructor c = enclosedClass.getEnclosingConstructor();
+        if (c == null && constructorSig == null)
+            return 0;
+
+        if (c != null &&
+            c.getAnnotation(ConstructorDescriptor.class).value().equals(constructorSig))
+            return 0; // everything is okay
+        else {
+            System.err.println("\nUnexpected constructor value; expected:\t" + constructorSig +
+                               "\ngot:\t" + c);
+            return 1;
+        }
+    }
+
+
+    public static void main(String argv[]) {
+        int failures = 0;
+        class StaticLocal {};
+        EnclosingConstructorTests ect = new EnclosingConstructorTests();
+        ect = new EnclosingConstructorTests(5);
+
+        failures += examine(StaticLocal.class,
+                            null);
+
+        failures += examine(localClass,
+                             "EnclosingConstructorTests()");
+
+        failures += examine(anotherLocalClass,
+                            "private EnclosingConstructorTests(int)");
+
+        failures += examine(anonymousClass,
+                            null);
+
+        if (failures > 0)
+            throw new RuntimeException("Test failed.");
+    }
+}
+
+@Retention(RetentionPolicy.RUNTIME)
+@interface ConstructorDescriptor {
+    String value();
+}
diff --git a/jdk/test/java/lang/Class/getEnclosingMethod/EnclosingMethodTests.java b/jdk/test/java/lang/Class/getEnclosingMethod/EnclosingMethodTests.java
new file mode 100644
index 0000000..88f7c33
--- /dev/null
+++ b/jdk/test/java/lang/Class/getEnclosingMethod/EnclosingMethodTests.java
@@ -0,0 +1,89 @@
+/*
+ * Copyright 2004 Sun Microsystems, Inc.  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 Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
+ * CA 95054 USA or visit www.sun.com if you need additional information or
+ * have any questions.
+ */
+
+/*
+ * @test
+ * @bug 4962341
+ * @summary Check getEnclosingMethod method
+ * @author Joseph D. Darcy
+ */
+
+import java.lang.reflect.Method;
+import java.lang.annotation.*;
+
+public class EnclosingMethodTests {
+    static Class<?> anonymousClass;
+
+    static {
+        Cloneable c = new Cloneable() {}; // anonymous cloneable
+        anonymousClass = c.getClass();
+    }
+
+    EnclosingMethodTests() {}
+
+    @MethodDescriptor("java.lang.Class EnclosingMethodTests.getLocalClass(Object o)")
+    Class getLocalClass(Object o) {
+        class Local {};
+        Local l = new Local();
+        return l.getClass();
+    }
+
+    static int examine(Class enclosedClass, String methodSig) {
+        Method m = enclosedClass.getEnclosingMethod();
+        if (m == null && methodSig == null)
+            return 0;
+
+        if (m != null &&
+            m.getAnnotation(MethodDescriptor.class).value().equals(methodSig))
+            return 0; // everything is okay
+        else {
+            System.err.println("\nUnexpected method value; expected:\t" + methodSig +
+                               "\ngot:\t" + m);
+            return 1;
+        }
+    }
+
+    @MethodDescriptor("public static void EnclosingMethodTests.main(java.lang.String[])")
+    public static void main(String argv[]) {
+        int failures = 0;
+        class StaticLocal {};
+
+        failures += examine(StaticLocal.class,
+                            "public static void EnclosingMethodTests.main(java.lang.String[])");
+
+        failures += examine( (new EnclosingMethodTests()).getLocalClass(null),
+                             "java.lang.Class EnclosingMethodTests.getLocalClass(Object o)");
+
+        failures += examine(EnclosingMethodTests.class, null);
+
+        failures += examine(anonymousClass, null);
+
+        if (failures > 0)
+            throw new RuntimeException("Test failed.");
+    }
+}
+
+@Retention(RetentionPolicy.RUNTIME)
+@interface MethodDescriptor {
+    String value();
+}
diff --git a/jdk/test/java/lang/Class/getField/Exceptions.java b/jdk/test/java/lang/Class/getField/Exceptions.java
new file mode 100644
index 0000000..9eb3285
--- /dev/null
+++ b/jdk/test/java/lang/Class/getField/Exceptions.java
@@ -0,0 +1,70 @@
+/*
+ * Copyright 2002 Sun Microsystems, Inc.  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 Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
+ * CA 95054 USA or visit www.sun.com if you need additional information or
+ * have any questions.
+ */
+
+/**
+ * @test
+ * @bug 4319910
+ * @summary Verify that exceptions are thrown as expected.
+ */
+
+public class Exceptions {
+    private static boolean ok = true;
+
+    int f0;
+    public int f1;
+    private int f2;
+    protected int f4;
+
+    private static final String [] npe = {null};
+    private static final String [] nsfe = {"f0", "f2", "f4", "f6"};
+    private static final String [] pass = {"f1"};
+
+    private void test(String s, Class ex) {
+        Throwable t = null;
+        try {
+            getClass().getField(s);
+        } catch (Throwable x) {
+            if (ex.isAssignableFrom(x.getClass()))
+                t = x;
+        }
+        if ((t == null) && (ex != null)) {
+            ok = false;
+            System.out.println("expected " + ex.getName() + " for " + s
+                               + " -- FAILED");
+        } else {
+            System.out.println(s + " -- OK");
+        }
+    }
+
+    public static void main(String [] args) {
+        Exceptions e = new Exceptions();
+        for (int i = 0; i < npe.length; i++)
+            e.test(npe[i], NullPointerException.class);
+        for (int i = 0; i < nsfe.length; i++)
+            e.test(nsfe[i], NoSuchFieldException.class);
+        for (int i = 0; i < pass.length; i++)
+            e.test(pass[i], null);
+        if (!ok)
+            throw new RuntimeException("some tests failed");
+    }
+}
diff --git a/jdk/test/java/lang/Class/getMethod/Exceptions.java b/jdk/test/java/lang/Class/getMethod/Exceptions.java
new file mode 100644
index 0000000..39b5223
--- /dev/null
+++ b/jdk/test/java/lang/Class/getMethod/Exceptions.java
@@ -0,0 +1,64 @@
+/*
+ * Copyright 2002 Sun Microsystems, Inc.  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 Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
+ * CA 95054 USA or visit www.sun.com if you need additional information or
+ * have any questions.
+ */
+
+/**
+ * @test
+ * @bug 4319910
+ * @summary Verify that exceptions are thrown as expected.
+ */
+
+public class Exceptions {
+    void m0() {}
+    public void m1() {}
+    private void m2() {}
+    protected void m4() {}
+
+    private static final String [] npe = {null};
+    private static final String [] nsme = {"m0", "m2", "m4", "m6"};
+    private static final String [] pass = {"m1"};
+
+    private void test(String s, Class ex) {
+        Throwable t = null;
+        try {
+            getClass().getMethod(s, new Class[] {});
+        } catch (Throwable x) {
+            if (ex.isAssignableFrom(x.getClass()))
+                t = x;
+        }
+        if ((t == null) && (ex != null))
+            throw new RuntimeException("expected " + ex.getName()
+                                       + " for " + s);
+        else
+            System.out.println(s + " OK");
+    }
+
+    public static void main(String [] args) {
+        Exceptions e = new Exceptions();
+        for (int i = 0; i < npe.length; i++)
+            e.test(npe[i], NullPointerException.class);
+        for (int i = 0; i < nsme.length; i++)
+            e.test(nsme[i], NoSuchMethodException.class);
+        for (int i = 0; i < pass.length; i++)
+            e.test(pass[i], null);
+    }
+}
diff --git a/jdk/test/java/lang/Class/getMethod/NullInParamList.java b/jdk/test/java/lang/Class/getMethod/NullInParamList.java
new file mode 100644
index 0000000..ccb6253
--- /dev/null
+++ b/jdk/test/java/lang/Class/getMethod/NullInParamList.java
@@ -0,0 +1,46 @@
+/*
+ * Copyright 2002 Sun Microsystems, Inc.  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 Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
+ * CA 95054 USA or visit www.sun.com if you need additional information or
+ * have any questions.
+ */
+
+/**
+ * @test
+ * @bug 4684974
+ * @summary Verify that NoSuchMethodException is thrown.
+ */
+
+import java.lang.reflect.Method;
+
+class A {
+    public void m(Object o) {}
+}
+
+public class NullInParamList {
+    public static void main(String [] args) {
+        try {
+            Class [] ca = {null};
+            Method m = A.class.getMethod("m", ca);
+        } catch (NoSuchMethodException x) {
+            return;
+        }
+        throw new RuntimeException("FAIL: expected NoSuchMethodException");
+    }
+}
diff --git a/jdk/test/java/lang/Class/getMethods/NonPublicStaticInitializer.java b/jdk/test/java/lang/Class/getMethods/NonPublicStaticInitializer.java
new file mode 100644
index 0000000..acdef06
--- /dev/null
+++ b/jdk/test/java/lang/Class/getMethods/NonPublicStaticInitializer.java
@@ -0,0 +1,52 @@
+/*
+ * Copyright 1999 Sun Microsystems, Inc.  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 Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
+ * CA 95054 USA or visit www.sun.com if you need additional information or
+ * have any questions.
+ */
+
+/* @test
+   @bug 4187388
+   @summary <clinit> in interfaces need not be public
+*/
+
+import java.lang.reflect.Method;
+import java.lang.reflect.Modifier;
+
+interface TestedInterface {
+    String s = System.getProperty("Test");
+
+    void foo();
+    void bar();
+}
+
+
+public class NonPublicStaticInitializer {
+    public static void main(String args[]) throws Exception {
+        Method m[] = TestedInterface.class.getMethods();
+        for (int i = 0; i < m.length; i++) {
+            System.out.println("Found: " +
+                               Modifier.toString(m[i].getModifiers()) +
+                               " " + m[i].getName());
+            if (m[i].getName().equals("<clinit>")) {
+                throw new Exception("Shouldn't have found <clinit>");
+            }
+        }
+    }
+}
diff --git a/jdk/test/java/lang/Class/getMethods/StarInheritance.java b/jdk/test/java/lang/Class/getMethods/StarInheritance.java
new file mode 100644
index 0000000..6ac7c93
--- /dev/null
+++ b/jdk/test/java/lang/Class/getMethods/StarInheritance.java
@@ -0,0 +1,98 @@
+/*
+ * Copyright 2002 Sun Microsystems, Inc.  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 Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
+ * CA 95054 USA or visit www.sun.com if you need additional information or
+ * have any questions.
+ */
+
+/**
+ * @test
+ * @bug 4654698
+ * @summary Verify that expected methods are returned for star inheritance.
+ */
+
+import java.lang.reflect.Method;
+import java.util.Arrays;
+import java.util.ArrayList;
+
+// D.m
+interface A1 extends B1, C1 {}
+interface B1 extends D1 {}
+interface C1 extends D1 {}
+interface D1 { void m(); }
+
+// A.m
+interface A2 extends B2, C2 { void m(); }
+interface B2 extends D2 {}
+interface C2 extends D2 {}
+interface D2 { void m(); }
+
+// B.m, C.m
+interface A3 extends B3, C3 {}
+interface B3 extends D3 { void m(); }
+interface C3 extends D3 { void m(); }
+interface D3 { void m() ; }
+
+// B.m, D.m
+interface A4 extends B4, C4 {}
+interface B4 extends D4 { void m(); }
+interface C4 extends D4 {}
+interface D4 { void m(); }
+
+public class StarInheritance {
+    private static int n = 1;
+
+    private static void test(Method [] ma, ArrayList expect) {
+        System.out.println("Test " + n++);
+
+        if (expect.size() != ma.length) {
+            System.err.println("  found methods: " + Arrays.asList(ma));
+            System.err.println("  expected locations: " + expect);
+            throw new RuntimeException("found = " + ma.length
+                                       +"; expected = " + expect.size());
+        }
+
+        for (int i = 0; i < ma.length; i++) {
+            Method m = ma[i];
+            System.out.println("  " + m.toString());
+            int n;
+            if (m.getName().equals("m")
+                && (n = expect.indexOf(m.getDeclaringClass())) != -1) {
+                expect.remove(n);
+            } else {
+                throw new RuntimeException("unable to locate method in class: "
+                                           + m.getDeclaringClass());
+            }
+        }
+    }
+
+    public static void main(String [] args) {
+        Class [] l1 = {D1.class};
+        test(A1.class.getMethods(), new ArrayList(Arrays.asList(l1)));
+
+        Class [] l2 = {A2.class};
+        test(A2.class.getMethods(), new ArrayList(Arrays.asList(l2)));
+
+        Class [] l3 = {B3.class, C3.class};
+        test(A3.class.getMethods(), new ArrayList(Arrays.asList(l3)));
+
+        Class [] l4 = {B4.class, D4.class};
+        test(A4.class.getMethods(), new ArrayList(Arrays.asList(l4)));
+    }
+}
diff --git a/jdk/test/java/lang/Class/getModifiers/ForInnerClass.java b/jdk/test/java/lang/Class/getModifiers/ForInnerClass.java
new file mode 100644
index 0000000..4b15a7e
--- /dev/null
+++ b/jdk/test/java/lang/Class/getModifiers/ForInnerClass.java
@@ -0,0 +1,54 @@
+/*
+ * Copyright 1998 Sun Microsystems, Inc.  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 Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
+ * CA 95054 USA or visit www.sun.com if you need additional information or
+ * have any questions.
+ */
+
+/* @test
+   @bug 4109635
+   @summary For an inner class, the access bits must come from the
+            InnerClasses attribute, not from the class block's access.
+            Note however that the VM should not rely on these access
+            flags from the attribute!
+ */
+import java.lang.reflect.Modifier;
+public class ForInnerClass {
+    private class Inner {
+    }
+
+    protected class Protected {
+    }
+
+    public static void main(String[] args) throws Exception {
+        /* We are not testing for the ACC_SUPER bug, so strip we strip
+         * synchorized. */
+
+        int m = 0;
+
+        m = Inner.class.getModifiers() & (~Modifier.SYNCHRONIZED);
+        if (m != Modifier.PRIVATE)
+            throw new Exception("Access bits for innerclass not from " +
+                                "InnerClasses attribute");
+
+        m = Protected.class.getModifiers() & (~Modifier.SYNCHRONIZED);
+        if (m != Modifier.PROTECTED)
+            throw new Exception("Protected inner class wronged modifiers");
+    }
+}
diff --git a/jdk/test/java/lang/Class/getModifiers/ForStaticInnerClass.java b/jdk/test/java/lang/Class/getModifiers/ForStaticInnerClass.java
new file mode 100644
index 0000000..4107418
--- /dev/null
+++ b/jdk/test/java/lang/Class/getModifiers/ForStaticInnerClass.java
@@ -0,0 +1,39 @@
+/*
+ * Copyright 1998 Sun Microsystems, Inc.  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 Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
+ * CA 95054 USA or visit www.sun.com if you need additional information or
+ * have any questions.
+ */
+
+/* @test
+   @bug 4163105
+   @summary VM loses static modifier of inner class.
+ */
+
+import java.lang.reflect.Modifier;
+
+public class ForStaticInnerClass {
+    static class Static {
+    }
+
+    public static void main(String[] args) throws Exception {
+        if (!Modifier.isStatic(Static.class.getModifiers()))
+            throw new Exception("VM lost static modifier of innerclass.");
+    }
+}
diff --git a/jdk/test/java/lang/Class/getModifiers/ResolveFrom.java b/jdk/test/java/lang/Class/getModifiers/ResolveFrom.java
new file mode 100644
index 0000000..9425433
--- /dev/null
+++ b/jdk/test/java/lang/Class/getModifiers/ResolveFrom.java
@@ -0,0 +1,41 @@
+/*
+ * Copyright 1998 Sun Microsystems, Inc.  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 Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
+ * CA 95054 USA or visit www.sun.com if you need additional information or
+ * have any questions.
+ */
+
+/* @test
+   @bug 4127549
+   @summary getModifiers should resolve constant pool entries from
+            its own class.
+   @author  James Bond
+ */
+import java.lang.reflect.Modifier;
+public class ResolveFrom {
+    private class Inner {
+        int i;
+    }
+
+    public static void main(String argv[]) throws Exception {
+        int m = ResolveFrom.class.getModifiers();
+        System.out.println("ResolveFrom has modifiers = " +
+                           Modifier.toString(m));
+    }
+}
diff --git a/jdk/test/java/lang/Class/getModifiers/StripACC_SUPER.java b/jdk/test/java/lang/Class/getModifiers/StripACC_SUPER.java
new file mode 100644
index 0000000..3a6c660
--- /dev/null
+++ b/jdk/test/java/lang/Class/getModifiers/StripACC_SUPER.java
@@ -0,0 +1,38 @@
+/*
+ * Copyright 1998 Sun Microsystems, Inc.  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 Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
+ * CA 95054 USA or visit www.sun.com if you need additional information or
+ * have any questions.
+ */
+
+/* @test
+   @bug 4109635
+   @summary VM adds ACC_SUPER bit to access flags of a class. This must
+            be stripped by the Class.getModifiers method, or else this
+            shows up as though the class is synchronized and that doesn't
+            make any sense.
+   @author Anand Palaniswamy
+ */
+public class StripACC_SUPER {
+    public static void main(String[] args) throws Exception {
+        int access = StripACC_SUPER.class.getModifiers();
+        if (java.lang.reflect.Modifier.isSynchronized(access))
+            throw new Exception("ACC_SUPER bit is not being stripped");
+    }
+}
diff --git a/jdk/test/java/lang/ClassLoader/Assert.java b/jdk/test/java/lang/ClassLoader/Assert.java
new file mode 100644
index 0000000..33d3c09
--- /dev/null
+++ b/jdk/test/java/lang/ClassLoader/Assert.java
@@ -0,0 +1,205 @@
+/*
+ * Copyright 2000-2002 Sun Microsystems, Inc.  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 Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
+ * CA 95054 USA or visit www.sun.com if you need additional information or
+ * have any questions.
+ */
+
+/*
+ * @test
+ * @bug 4290640 4785473
+ * @run shell/timeout=300 Assert.sh
+ * @summary Test the assertion facility
+ * @author Mike McCloskey
+ */
+
+import package1.*;
+import package2.*;
+import package1.package3.*;
+import java.io.*;
+import java.util.Random;
+
+public class Assert {
+
+    private static Class1 testClass1;
+    private static Class2 testClass2;
+    private static Class3 testClass3;
+    private static final  boolean debug = false;
+    private static Random generator = new Random();
+
+    /**
+     * The first invocation of this test starts a loop which exhaustively tests
+     * the object tree with all of its different settings.
+     * There are 7 test objects in a tree that has 7 different places to set
+     * assertions untouched/on/off so this tests 3^7 or 2187 different
+     * configurations.
+     *
+     * This test spawns a new VM for each run because assertions are set on or
+     * off at class load time. Once the class is loaded its assertion status
+     * does not change.
+     */
+    public static void main(String[] args) throws Exception {
+
+        // Switch values: 0=don't touch, 1=off, 2 = on
+        int[] switches = new int[7];
+
+        int switchSource = 0;
+        if (args.length == 0) { // This is master version
+
+            // This code is for an exhaustive test
+            //while(switchSource < 2187) {
+            //    int temp = switchSource++;
+
+            // This code is for a weaker but faster test
+            for(int x=0; x<100; x++) {
+                int temp = generator.nextInt(2187);
+                for(int i=0; i<7; i++) {
+                    switches[i] = temp % 3;
+                    temp = temp / 3;
+                }
+
+                // Spawn new VM and load classes
+                String command = System.getProperty("java.home") +
+                    File.separator + "bin" + File.separator + "java Assert";
+
+                StringBuffer commandString = new StringBuffer(command);
+                for(int j=0; j<7; j++)
+                    commandString.append(" "+switches[j]);
+
+                Process p = null;
+                p = Runtime.getRuntime().exec(commandString.toString());
+
+                if (debug) { // See output of test VMs
+                    BufferedReader blah = new BufferedReader(
+                                          new InputStreamReader(p.getInputStream()));
+                    String outString = blah.readLine();
+                    while (outString != null) {
+                        System.out.println("from slave:"+outString);
+                        outString = blah.readLine();
+                    }
+                }
+
+                p.waitFor();
+                int result = p.exitValue();
+                if (debug) { // See which switch configs failed
+                    if (result == 0) {
+                        for(int k=6; k>=0; k--)
+                            System.out.print(switches[k]);
+                        System.out.println();
+                    } else {
+                        System.out.print("Nonzero Exit: ");
+                        for(int k=6; k>=0; k--)
+                            System.out.print(switches[k]);
+                        System.out.println();
+                    }
+                } else {
+                    if (result != 0) {
+                        System.err.print("Nonzero Exit: ");
+                        for(int k=6; k>=0; k--)
+                            System.err.print(switches[k]);
+                        System.err.println();
+                        throw new RuntimeException("Assertion test failure.");
+                    }
+                }
+            }
+        } else { // This is a test spawn
+            for(int i=0; i<7; i++)
+                switches[i] = Integer.parseInt(args[i]);
+
+            SetAssertionSwitches(switches);
+            ConstructClassTree();
+            TestClassTree(switches);
+        }
+    }
+
+    /*
+     * Activate/Deactivate the assertions in the tree according to the
+     * specified switches.
+     */
+    private static void SetAssertionSwitches(int[] switches) {
+        ClassLoader loader = ClassLoader.getSystemClassLoader();
+
+        if (switches[0] != 0)
+            loader.setDefaultAssertionStatus(switches[0]==2);
+        if (switches[1] != 0)
+            loader.setPackageAssertionStatus("package1", switches[1]==2);
+        if (switches[2] != 0)
+            loader.setPackageAssertionStatus("package2", switches[2]==2);
+        if (switches[3] != 0)
+            loader.setPackageAssertionStatus("package1.package3", switches[3]==2);
+        if (switches[4] != 0)
+            loader.setClassAssertionStatus("package1.Class1", switches[4]==2);
+        if (switches[5] != 0)
+            loader.setClassAssertionStatus("package2.Class2", switches[5]==2);
+        if (switches[6] != 0)
+            loader.setClassAssertionStatus("package1.package3.Class3", switches[6]==2);
+    }
+
+    /*
+     * Verify that the assertions are activated or deactivated as specified
+     * by the switches.
+     */
+    private static void TestClassTree(int[] switches) {
+
+        // Class1 and anonymous inner class
+        boolean assertsOn = (switches[4]==2) ? true : (switches[4]==1) ? false :
+            (switches[1]==2) ? true : (switches[1]==1) ? false : (switches[0]==2) ?
+            true: false;
+        testClass1.testAssert(assertsOn);
+
+        // Class1 inner class Class11
+        assertsOn = (switches[4]==2) ? true : (switches[4]==1) ? false :
+            (switches[1]==2) ? true : (switches[1]==1) ? false : (switches[0]==2) ?
+            true: false;
+        Class1.Class11.testAssert(assertsOn);
+
+        // Class2
+        assertsOn = (switches[5]==2) ? true : (switches[5]==1) ? false :
+            (switches[2]==2) ? true : (switches[2]==1) ? false : (switches[0]==2) ?
+            true: false;
+        testClass2.testAssert(assertsOn);
+
+        // Class3 and anonymous inner class
+        assertsOn = (switches[6]==2) ? true : (switches[6]==1) ? false :
+                    (switches[3]==2) ? true : (switches[3]==1) ? false :
+                    (switches[1]==2) ? true : (switches[1]==1) ? false :
+                    (switches[0]==2) ? true: false;
+        testClass3.testAssert(assertsOn);
+
+        // Class3 inner class Class31
+        assertsOn = (switches[6]==2) ? true : (switches[6]==1) ? false :
+                    (switches[3]==2) ? true : (switches[3]==1) ? false :
+                    (switches[1]==2) ? true : (switches[1]==1) ? false :
+                    (switches[0]==2) ? true : false;
+        Class3.Class31.testAssert(assertsOn);
+
+    }
+
+    /*
+     * Create the class tree to be tested. Each test run must reload the classes
+     * of the tree since assertion status is determined at class load time.
+     */
+    private static void ConstructClassTree() {
+        testClass1 = new Class1();
+        testClass2 = new Class2();
+        testClass3 = new Class3();
+    }
+
+
+}
diff --git a/jdk/test/java/lang/ClassLoader/Assert.sh b/jdk/test/java/lang/ClassLoader/Assert.sh
new file mode 100644
index 0000000..4744def
--- /dev/null
+++ b/jdk/test/java/lang/ClassLoader/Assert.sh
@@ -0,0 +1,63 @@
+#
+# Copyright 2001-2002 Sun Microsystems, Inc.  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 Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
+# CA 95054 USA or visit www.sun.com if you need additional information or
+# have any questions.
+#
+
+#
+
+if [ "${TESTSRC}" = "" ]
+then
+  echo "TESTSRC not set.  Test cannot execute.  Failed."
+  exit 1
+fi
+echo "TESTSRC=${TESTSRC}"
+if [ "${TESTJAVA}" = "" ]
+then
+  echo "TESTJAVA not set.  Test cannot execute.  Failed."
+  exit 1
+fi
+echo "TESTJAVA=${TESTJAVA}"
+if [ "${TESTCLASSES}" = "" ]
+then
+  echo "TESTCLASSES not set.  Test cannot execute.  Failed."
+  exit 1
+fi
+echo "TESTCLASSES=${TESTCLASSES}"
+echo "CLASSPATH=${CLASSPATH}"
+
+cp ${TESTSRC}/Assert.java .
+cp -R ${TESTSRC}/package1 .
+cp -R ${TESTSRC}/package2 .
+
+${TESTJAVA}/bin/javac -source 1.4 Assert.java 
+
+${TESTJAVA}/bin/java Assert
+
+result=$?
+if [ $result -eq 0 ]
+then
+  echo "Passed"
+else
+  echo "Failed"
+fi
+exit $result
+
+
diff --git a/jdk/test/java/lang/ClassLoader/ExceptionHidingLoader.java b/jdk/test/java/lang/ClassLoader/ExceptionHidingLoader.java
new file mode 100644
index 0000000..c6d1f87
--- /dev/null
+++ b/jdk/test/java/lang/ClassLoader/ExceptionHidingLoader.java
@@ -0,0 +1,52 @@
+/*
+ * Copyright 1998 Sun Microsystems, Inc.  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 Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
+ * CA 95054 USA or visit www.sun.com if you need additional information or
+ * have any questions.
+ */
+
+/* @test
+   @bug 4135104
+   @summary If a badly behaved ClassLoader returns null but doesn't
+            raise an exception, the VM core dumps.
+*/
+
+
+public class ExceptionHidingLoader extends ClassLoader {
+
+    protected Class findClass(String name) throws ClassNotFoundException {
+        return null;
+    }
+
+    public static void main(String[] args) throws Exception {
+        boolean exception = false;
+
+        try {
+            Class.forName("aha", false, new ExceptionHidingLoader());
+        } catch (ClassNotFoundException e) {
+            /* VM was smart enough to detect the problem and raise an
+               exception. */
+            exception = true;
+        }
+        if (!exception) {
+            throw new Exception("Bogus loader behavior not being corrected");
+        }
+    }
+
+}
diff --git a/jdk/test/java/lang/ClassLoader/GetDotResource.java b/jdk/test/java/lang/ClassLoader/GetDotResource.java
new file mode 100644
index 0000000..cd2217b
--- /dev/null
+++ b/jdk/test/java/lang/ClassLoader/GetDotResource.java
@@ -0,0 +1,44 @@
+/*
+ * Copyright 1999 Sun Microsystems, Inc.  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 Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
+ * CA 95054 USA or visit www.sun.com if you need additional information or
+ * have any questions.
+ */
+
+/*
+ * @test
+ * @bug 4273031
+ * @summary ClassLoader.getResouce() should be able to
+ *          find resources with leading "." in their names
+ * @build GetDotResource
+ * @run shell getdotresource.sh
+ */
+
+import java.net.URL;
+import java.net.URLClassLoader;
+
+
+public class GetDotResource {
+    public static void main(String[] args) throws Exception {
+        if (GetDotResource.class.getClassLoader().
+            getResourceAsStream(".resource") == null)
+            throw new Exception("Could not find resource with " +
+                                "leading . in their names");
+    }
+}
diff --git a/jdk/test/java/lang/ClassLoader/GetPackage.java b/jdk/test/java/lang/ClassLoader/GetPackage.java
new file mode 100644
index 0000000..2c777cd
--- /dev/null
+++ b/jdk/test/java/lang/ClassLoader/GetPackage.java
@@ -0,0 +1,68 @@
+/*
+ * Copyright 1999 Sun Microsystems, Inc.  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 Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
+ * CA 95054 USA or visit www.sun.com if you need additional information or
+ * have any questions.
+ */
+
+/*
+ * @test
+ * @bug 4256589
+ * @summary Test if getPackage() and getPackages()
+ *          return consistent values.
+ */
+
+public class GetPackage {
+    public static void main(String arg[]) throws Exception {
+        TestClassLoader parent = new TestClassLoader();
+        TestClassLoader child = new TestClassLoader(parent);
+        // child define a package first
+        child.defineEmptyPackage("foo");
+        // parent then define another package with the same name
+        parent.defineEmptyPackage("foo");
+        if (!child.testPackageView("foo"))
+            throw new Exception("Inconsistent packages view");
+    }
+}
+
+class TestClassLoader extends ClassLoader {
+    public TestClassLoader() {
+        super();
+    }
+
+    public TestClassLoader(ClassLoader parent) {
+        super(parent);
+    }
+
+    public Package defineEmptyPackage(String name) {
+        return definePackage(name, null, null, null, null, null, null, null);
+    }
+
+    /* test to see if getPackage() and getPackages()
+     * are consistent.
+     */
+    public boolean testPackageView(String name) {
+        Package[] pkgs = getPackages();
+        Package pkg = getPackage(name);
+        for(int i = 0; i < pkgs.length; i++)
+            if (pkgs[i].getName().equals(name) && pkgs[i] == pkg)
+                return true;
+        return false;
+    }
+}
diff --git a/jdk/test/java/lang/ClassLoader/LoadNullClass.java b/jdk/test/java/lang/ClassLoader/LoadNullClass.java
new file mode 100644
index 0000000..9073a71
--- /dev/null
+++ b/jdk/test/java/lang/ClassLoader/LoadNullClass.java
@@ -0,0 +1,55 @@
+/*
+ * Copyright 1999 Sun Microsystems, Inc.  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 Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
+ * CA 95054 USA or visit www.sun.com if you need additional information or
+ * have any questions.
+ */
+
+/*
+ * @test
+ * @bug 4263588 4292814
+ * @summary ClassLoader.loadClass() should not core dump
+ *          on null class names.
+ */
+
+import java.io.File;
+import java.net.URL;
+import java.net.URLClassLoader;
+
+
+public class LoadNullClass {
+    public static void main(String[] args) throws Exception {
+        File f = new File(System.getProperty("test.src", "."));
+        // give the class loader a good but useless url
+        FileClassLoader cl = new FileClassLoader
+            (new URL[]{new URL("file:"+ f.getAbsolutePath())});
+        cl.testFindLoadedClass(null);
+    }
+}
+
+class FileClassLoader extends URLClassLoader {
+
+    public FileClassLoader(URL[] urls) {
+        super(urls);
+    }
+
+    public void testFindLoadedClass(String name) throws Exception {
+        super.findLoadedClass(name);
+    }
+}
diff --git a/jdk/test/java/lang/ClassLoader/defineClass/DefineClassByteBuffer.java b/jdk/test/java/lang/ClassLoader/defineClass/DefineClassByteBuffer.java
new file mode 100644
index 0000000..1200985
--- /dev/null
+++ b/jdk/test/java/lang/ClassLoader/defineClass/DefineClassByteBuffer.java
@@ -0,0 +1,126 @@
+/*
+ * Copyright 2003 Sun Microsystems, Inc.  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 Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
+ * CA 95054 USA or visit www.sun.com if you need additional information or
+ * have any questions.
+ */
+
+/*
+ * @test
+ * @bug 4894899
+ * @summary Test various cases of passing java.nio.ByteBuffers
+ * to defineClass().
+ *
+ * @build DefineClassByteBuffer TestClass
+ * @run main DefineClassByteBuffer
+ */
+
+import java.nio.*;
+import java.nio.channels.*;
+import java.io.*;
+
+public class DefineClassByteBuffer {
+
+    static void test(ClassLoader cl) throws Exception {
+        Class c = Class.forName("TestClass", true, cl);
+        if (!"TestClass".equals(c.getName())) {
+            throw new RuntimeException("Got wrong class: " + c);
+        }
+    }
+
+    public static void main(String arg[]) throws Exception {
+        ClassLoader[] cls = new ClassLoader[DummyClassLoader.MAX_TYPE];
+        for (int i = 0; i < cls.length; i++) {
+            cls[i] = new DummyClassLoader(i);
+        }
+
+        /* Create several instances of the class using different classloaders,
+           which are using different types of ByteBuffer. */
+        for (int i = 0; i < cls.length; i++) {
+          test(cls[i]);
+        }
+    }
+
+    /** Always loads the same class, using various types of ByteBuffers */
+    public static class DummyClassLoader extends ClassLoader {
+
+        public static final String CLASS_NAME = "TestClass";
+
+        public static final int MAPPED_BUFFER = 0;
+        public static final int DIRECT_BUFFER = 1;
+        public static final int ARRAY_BUFFER = 2;
+        public static final int WRAPPED_BUFFER = 3;
+        public static final int READ_ONLY_ARRAY_BUFFER = 4;
+        public static final int READ_ONLY_DIRECT_BUFFER = 5;
+        public static final int DUP_ARRAY_BUFFER = 6;
+        public static final int DUP_DIRECT_BUFFER = 7;
+        public static final int MAX_TYPE = 7;
+
+        int loaderType;
+
+        DummyClassLoader(int loaderType) {
+            this.loaderType = loaderType;
+        }
+
+        static ByteBuffer[] buffers = new ByteBuffer[MAX_TYPE + 1];
+
+        static ByteBuffer readClassFile(String name) {
+            try {
+                File f = new File(System.getProperty("test.classes", "."),
+                                  name);
+                FileInputStream fin = new FileInputStream(f);
+                FileChannel fc = fin.getChannel();
+                return fc.map(FileChannel.MapMode.READ_ONLY, 0, fc.size());
+            } catch (FileNotFoundException e) {
+                throw new RuntimeException("Can't open file: " + name, e);
+            } catch (IOException e) {
+                throw new RuntimeException("Can't open file: " + name, e);
+            }
+        }
+
+        static {
+            /* create a bunch of different ByteBuffers, starting with a mapped
+               buffer from a class file, and create various duplicate and wrapped
+               buffers. */
+            buffers[MAPPED_BUFFER] = readClassFile(CLASS_NAME + ".class");
+            byte[] array = new byte[buffers[MAPPED_BUFFER].limit()];
+
+            buffers[DIRECT_BUFFER] = ByteBuffer.allocateDirect(array.length);
+            buffers[DIRECT_BUFFER].put(array);
+
+            buffers[ARRAY_BUFFER] = ByteBuffer.allocate(array.length);
+            buffers[ARRAY_BUFFER].put(array);
+
+            buffers[WRAPPED_BUFFER] = ByteBuffer.wrap(array);
+
+            buffers[READ_ONLY_ARRAY_BUFFER] = buffers[ARRAY_BUFFER].asReadOnlyBuffer();
+
+            buffers[READ_ONLY_DIRECT_BUFFER] = buffers[DIRECT_BUFFER].asReadOnlyBuffer();
+
+            buffers[DUP_ARRAY_BUFFER] = buffers[ARRAY_BUFFER].duplicate();
+
+            buffers[DUP_DIRECT_BUFFER] = buffers[DIRECT_BUFFER].duplicate();
+        }
+
+         public Class findClass(String name) {
+             return defineClass(name, buffers[loaderType], null);
+         }
+    } /* DummyClassLoader */
+
+} /* DefineClassByteBuffer */
diff --git a/jdk/test/java/lang/ClassLoader/defineClass/TestClass.java b/jdk/test/java/lang/ClassLoader/defineClass/TestClass.java
new file mode 100644
index 0000000..9e93d3c
--- /dev/null
+++ b/jdk/test/java/lang/ClassLoader/defineClass/TestClass.java
@@ -0,0 +1,28 @@
+/*
+ * Copyright 2003 Sun Microsystems, Inc.  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 Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
+ * CA 95054 USA or visit www.sun.com if you need additional information or
+ * have any questions.
+ */
+
+public class TestClass {
+    public static String foo() {
+        return "OK";
+    }
+}
diff --git a/jdk/test/java/lang/ClassLoader/findSystemClass/Loadee.classfile b/jdk/test/java/lang/ClassLoader/findSystemClass/Loadee.classfile
new file mode 100644
index 0000000..b98aaa7
--- /dev/null
+++ b/jdk/test/java/lang/ClassLoader/findSystemClass/Loadee.classfile
Binary files differ
diff --git a/jdk/test/java/lang/ClassLoader/findSystemClass/Loadee.java b/jdk/test/java/lang/ClassLoader/findSystemClass/Loadee.java
new file mode 100644
index 0000000..4ece146
--- /dev/null
+++ b/jdk/test/java/lang/ClassLoader/findSystemClass/Loadee.java
@@ -0,0 +1,29 @@
+/*
+ * Copyright 1998 Sun Microsystems, Inc.  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 Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
+ * CA 95054 USA or visit www.sun.com if you need additional information or
+ * have any questions.
+ */
+
+public class Loadee {
+    Loader app;
+    public Loadee() {
+        app = new Loader();
+    }
+}
diff --git a/jdk/test/java/lang/ClassLoader/findSystemClass/Loadee.resource b/jdk/test/java/lang/ClassLoader/findSystemClass/Loadee.resource
new file mode 100644
index 0000000..9a60964
--- /dev/null
+++ b/jdk/test/java/lang/ClassLoader/findSystemClass/Loadee.resource
@@ -0,0 +1,2 @@
+It really doesn't matter what is in this file, so long as this file is
+there.
diff --git a/jdk/test/java/lang/ClassLoader/findSystemClass/Loader.java b/jdk/test/java/lang/ClassLoader/findSystemClass/Loader.java
new file mode 100644
index 0000000..e84a9c2
--- /dev/null
+++ b/jdk/test/java/lang/ClassLoader/findSystemClass/Loader.java
@@ -0,0 +1,148 @@
+/*
+ * Copyright 1998-2001 Sun Microsystems, Inc.  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 Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
+ * CA 95054 USA or visit www.sun.com if you need additional information or
+ * have any questions.
+ */
+
+/* @test
+   @bug 4147599 4478150
+   @summary In 1.2beta4-I ClassLoader loaded classes can not link
+            against application classes.
+*/
+
+/*
+ * We are trying to test that certain methods of ClassLoader look at the same
+ * paths as they did in 1.1.  To run this test on 1.1, you will have to pass
+ * "-1.1" as option on the command line.
+ *
+ * The required files are:
+ *
+ *      - Loader.java            (a 1.1 style class loader)
+ *      - Loadee.java            (source for a class that refers to Loader)
+ *      - Loadee.classfile       (to test findSystemClass)
+ *      - Loadee.resource        (to test getSystemResource)
+ *      - java/lang/Object.class (to test getSystemResources)
+ *
+ * The extension ".classfile" is so the class file is not seen by any loader
+ * other than Loader.  If you need to make any changes you will have to
+ * compile Loadee.java and rename Loadee.class to Loadee.classfile.
+ */
+
+import java.io.File;
+import java.io.DataInputStream;
+import java.io.FileInputStream;
+import java.io.IOException;
+import java.net.URL;
+import java.util.HashSet;
+
+
+/**
+ * A 1.1-style ClassLoader.  The only class it can really load is "Loadee".
+ * For other classes it might be asked to load, it relies on loaders set up by
+ * the launcher.
+ */
+public class Loader extends ClassLoader {
+
+    public Class loadClass(String name, boolean resolve)
+        throws ClassNotFoundException {
+        Class c = null;
+        try {
+            c = findSystemClass(name);
+        } catch (ClassNotFoundException cnfe) {
+        }
+        if (c == null) {
+            if (!name.equals("Loadee"))
+                throw new Error("java.lang.ClassLoader.findSystemClass() " +
+                                "did not find class " + name);
+            byte[] b = locateBytes();
+            c = defineClass(name, b, 0, b.length);
+        }
+        if (resolve) {
+            resolveClass(c);
+        }
+        return c;
+    }
+
+    private byte[] locateBytes() {
+        try {
+            File f   = new File(System.getProperty("test.src", "."),
+                                "Loadee.classfile");
+            long l   = f.length();
+            byte[] b = new byte[(int)l];
+            DataInputStream in =
+                new DataInputStream(new FileInputStream(f));
+            in.readFully(b);
+            return b;
+        } catch (IOException ioe) {
+            ioe.printStackTrace();
+            throw new Error("Test failed due to IOException!");
+        }
+    }
+
+    private static final int FIND      = 0x1;
+    private static final int RESOURCE  = 0x2;
+    private static final int RESOURCES = 0x4;
+
+    public static void main(String[] args) throws Exception {
+        int tests = FIND | RESOURCE | RESOURCES;
+
+        if (args.length == 1 && args[0].equals("-1.1")) {
+            tests &= ~RESOURCES; /* Do not run getResources test. */
+        }
+
+        if ((tests & FIND) == FIND) {
+            report("findSystemClass()");
+            ClassLoader l = new Loader();
+            Class       c = l.loadClass("Loadee");
+            Object      o = c.newInstance();
+        }
+
+        if ((tests & RESOURCE) == RESOURCE) {
+            report("getSystemResource()");
+            URL u = getSystemResource("Loadee.resource");
+            if (u == null)
+                throw new Exception
+                    ("java.lang.ClassLoader.getSystemResource() test failed!");
+        }
+
+        if ((tests & RESOURCES) == RESOURCES) {
+            report("getSystemResources()");
+            java.util.Enumeration e =
+                getSystemResources("java/lang/Object.class");
+            HashSet hs = new HashSet();
+            while (e.hasMoreElements()) {
+                URL u = (URL)e.nextElement();
+                if (u == null)
+                    break;
+                System.out.println("url: " + u);
+                hs.add(u);
+            }
+            if (hs.size() != 2) {
+                throw
+                    new Exception("java.lang.ClassLoader.getSystemResources()"+
+                                  " did not find all resources");
+            }
+        }
+    }
+
+    private static void report(String s) {
+        System.out.println("Testing java.lang.ClassLoader." + s + " ...");
+    }
+}
diff --git a/jdk/test/java/lang/ClassLoader/findSystemClass/java/lang/Object.class b/jdk/test/java/lang/ClassLoader/findSystemClass/java/lang/Object.class
new file mode 100644
index 0000000..0549a31
--- /dev/null
+++ b/jdk/test/java/lang/ClassLoader/findSystemClass/java/lang/Object.class
@@ -0,0 +1 @@
+Fake resource, to test the getResources() variant.
diff --git a/jdk/test/java/lang/ClassLoader/getdotresource.sh b/jdk/test/java/lang/ClassLoader/getdotresource.sh
new file mode 100644
index 0000000..e8ba854
--- /dev/null
+++ b/jdk/test/java/lang/ClassLoader/getdotresource.sh
@@ -0,0 +1,36 @@
+#! /bin/sh
+
+#
+# Copyright 1999 Sun Microsystems, Inc.  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 Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
+# CA 95054 USA or visit www.sun.com if you need additional information or
+# have any questions.
+#
+
+#
+
+if [ x"$TESTJAVA" = x ]; then 
+        TESTJAVA=$1 
+        shift 
+fi
+if [ x"$TESTCLASSES" = x ]; then TESTCLASSES=.; fi
+if [ x"$TESTSRC" = x ]; then TESTSRC=.; fi
+
+# now start the test
+${TESTJAVA}/bin/java -Djava.ext.dirs=$TESTSRC -cp $TESTCLASSES GetDotResource
\ No newline at end of file
diff --git a/jdk/test/java/lang/ClassLoader/package1/Class1.java b/jdk/test/java/lang/ClassLoader/package1/Class1.java
new file mode 100644
index 0000000..69205a2
--- /dev/null
+++ b/jdk/test/java/lang/ClassLoader/package1/Class1.java
@@ -0,0 +1,54 @@
+/*
+ * Copyright 2000 Sun Microsystems, Inc.  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 Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
+ * CA 95054 USA or visit www.sun.com if you need additional information or
+ * have any questions.
+ */
+
+package package1;
+
+public class Class1 {
+    public void testAssert(boolean assertsShouldBeOn) {
+        boolean assertsEnabled = false;
+        assert assertsEnabled = true;
+        if (assertsEnabled != assertsShouldBeOn)
+            throw new RuntimeException("Failure of Asserts Facility.");
+
+        Class1 anonTest =  new Class1() {
+            public void testAssert(boolean assertsShouldBeOn) {
+                boolean assertsEnabled2 = false;
+                assert assertsEnabled2 = true;
+                if (assertsEnabled2 != assertsShouldBeOn)
+                    throw new RuntimeException("Failure of Asserts Facility.");
+            }
+        };
+        anonTest.testAssert(assertsShouldBeOn);
+    }
+
+    // Named inner class
+    public static class Class11 {
+        public static void testAssert(boolean assertsShouldBeOn) {
+            boolean assertsEnabled3 = false;
+            assert assertsEnabled3 = true;
+            if (assertsEnabled3 != assertsShouldBeOn)
+                throw new RuntimeException("Failure of Asserts Facility.");
+        }
+    }
+
+}
diff --git a/jdk/test/java/lang/ClassLoader/package1/package3/Class3.java b/jdk/test/java/lang/ClassLoader/package1/package3/Class3.java
new file mode 100644
index 0000000..64a8cc6
--- /dev/null
+++ b/jdk/test/java/lang/ClassLoader/package1/package3/Class3.java
@@ -0,0 +1,53 @@
+/*
+ * Copyright 2000 Sun Microsystems, Inc.  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 Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
+ * CA 95054 USA or visit www.sun.com if you need additional information or
+ * have any questions.
+ */
+
+package package1.package3;
+
+public class Class3 {
+    public void testAssert(boolean assertsShouldBeOn) {
+        boolean assertsEnabled = false;
+        assert(assertsEnabled = true);
+        if (assertsEnabled != assertsShouldBeOn)
+            throw new RuntimeException("Failure of Asserts Facility.");
+
+        Class3 anonTest =  new Class3() {
+            public void testAssert(boolean assertsShouldBeOn) {
+                boolean assertsEnabled = false;
+                assert(assertsEnabled = true);
+                if (assertsEnabled != assertsShouldBeOn)
+                    throw new RuntimeException("Failure of Asserts Facility.");
+            }
+        };
+        anonTest.testAssert(assertsShouldBeOn);
+    }
+
+    // Named inner class
+    public static class Class31 {
+        public static void testAssert(boolean assertsShouldBeOn) {
+            boolean assertsEnabled = false;
+            assert(assertsEnabled = true);
+            if (assertsEnabled != assertsShouldBeOn)
+                throw new RuntimeException("Failure of Asserts Facility.");
+        }
+    }
+}
diff --git a/jdk/test/java/lang/ClassLoader/package2/Class2.java b/jdk/test/java/lang/ClassLoader/package2/Class2.java
new file mode 100644
index 0000000..7d459ec
--- /dev/null
+++ b/jdk/test/java/lang/ClassLoader/package2/Class2.java
@@ -0,0 +1,33 @@
+/*
+ * Copyright 2000 Sun Microsystems, Inc.  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 Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
+ * CA 95054 USA or visit www.sun.com if you need additional information or
+ * have any questions.
+ */
+
+package package2;
+
+public class Class2 {
+    public void testAssert(boolean assertsShouldBeOn) {
+        boolean assertsEnabled = false;
+        assert(assertsEnabled = true);
+        if (assertsEnabled != assertsShouldBeOn)
+            throw new RuntimeException("Failure of Asserts Facility.");
+    }
+}
diff --git a/jdk/test/java/lang/ClassLoader/resource.jar b/jdk/test/java/lang/ClassLoader/resource.jar
new file mode 100644
index 0000000..6920016
--- /dev/null
+++ b/jdk/test/java/lang/ClassLoader/resource.jar
Binary files differ
diff --git a/jdk/test/java/lang/InheritableThreadLocal/Basic.java b/jdk/test/java/lang/InheritableThreadLocal/Basic.java
new file mode 100644
index 0000000..79221f8
--- /dev/null
+++ b/jdk/test/java/lang/InheritableThreadLocal/Basic.java
@@ -0,0 +1,83 @@
+/*
+ * Copyright 1999 Sun Microsystems, Inc.  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 Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
+ * CA 95054 USA or visit www.sun.com if you need additional information or
+ * have any questions.
+ */
+
+/*
+ * @test
+ * @summary Basic functional test of InheritableThreadLocal
+ * @author Josh Bloch
+ */
+
+public class Basic {
+    static InheritableThreadLocal n = new InheritableThreadLocal() {
+        protected Object initialValue() {
+            return new Integer(0);
+        }
+
+        protected Object childValue(Object parentValue) {
+            return new Integer(((Integer)parentValue).intValue() + 1);
+        }
+    };
+
+    static int threadCount = 100;
+    static int x[];
+
+    public static void main(String args[]) throws Exception {
+        x = new int[threadCount];
+        Thread progenitor = new MyThread();
+        progenitor.start();
+
+        // Wait for *all* threads to complete
+        progenitor.join();
+
+        // Check results
+        for(int i=0; i<threadCount; i++)
+            if (x[i] != i)
+                throw(new Exception("x[" + i + "] =" + x[i]));
+    }
+
+    private static class MyThread extends Thread {
+        public void run() {
+            Thread child = null;
+            if (((Integer)(n.get())).intValue() < threadCount-1) {
+                child = new MyThread();
+                child.start();
+            }
+            Thread.currentThread().yield();
+
+            int threadId = ((Integer)(n.get())).intValue();
+            for (int j=0; j<threadId; j++) {
+                x[threadId]++;
+                Thread.currentThread().yield();
+            }
+
+            // Wait for child (if any)
+            if (child != null) {
+                try {
+                    child.join();
+                } catch(InterruptedException e) {
+                    throw(new RuntimeException("Interrupted"));
+                }
+            }
+        }
+    }
+}
diff --git a/jdk/test/java/lang/InheritableThreadLocal/ITLRemoveTest.java b/jdk/test/java/lang/InheritableThreadLocal/ITLRemoveTest.java
new file mode 100644
index 0000000..08738b5
--- /dev/null
+++ b/jdk/test/java/lang/InheritableThreadLocal/ITLRemoveTest.java
@@ -0,0 +1,130 @@
+/*
+ * Copyright 2004 Sun Microsystems, Inc.  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 Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
+ * CA 95054 USA or visit www.sun.com if you need additional information or
+ * have any questions.
+ */
+
+/*
+ * @test
+ * @summary Basic functional test of remove method for InheritableThreadLocal
+ * @author Seetharama Avadhanam
+ */
+
+public class ITLRemoveTest {
+    private static final int INITIAL_VALUE = Integer.MIN_VALUE;
+    private static final int REMOVE_SET_VALUE = Integer.MAX_VALUE;
+
+    static InheritableThreadLocal<Integer> n = new InheritableThreadLocal<Integer>() {
+        protected Integer initialValue() {
+            return INITIAL_VALUE;
+        }
+
+        protected Integer childValue(Integer parentValue) {
+            return(parentValue + 1);
+        }
+    };
+
+    static int threadCount = 100;
+    static int x[];
+    static Throwable exceptions[];
+    static final int[] removeNode = {10,20,45,38,88};
+    /* ThreadLocal values will be removed for these threads. */
+    static final int[] removeAndSet = {12,34,10};
+    /* ThreadLocal values will be removed and sets new values */
+
+    public static void main(String args[]) throws Throwable {
+        x = new int[threadCount];
+        exceptions = new Throwable[threadCount];
+
+        Thread progenitor = new MyThread();
+        progenitor.start();
+
+        // Wait for *all* threads to complete
+        progenitor.join();
+
+        for(int i = 0; i<threadCount; i++){
+            int checkValue = i+INITIAL_VALUE;
+
+            /* If the remove method is called then the ThreadLocal value will
+             * be its initial value */
+            for(int removeId : removeNode)
+                if(removeId == i){
+                    checkValue = INITIAL_VALUE;
+                    break;
+                }
+
+            for(int removeId : removeAndSet)
+                if(removeId == i){
+                    checkValue = REMOVE_SET_VALUE;
+                    break;
+                }
+
+            if(exceptions[i] != null)
+                throw(exceptions[i]);
+            if(x[i] != checkValue)
+                throw(new Throwable("x[" + i + "] =" + x[i]));
+        }
+    }
+    private static class MyThread extends Thread {
+        public void run() {
+
+            Thread child = null;
+            int threadId=0;
+            try{
+                threadId = n.get();
+                // Creating child thread...
+                if (threadId < (threadCount-1+INITIAL_VALUE)) {
+                    child = new MyThread();
+                    child.start();
+                }
+
+                for (int j = 0; j<threadId; j++)
+                    Thread.currentThread().yield();
+
+
+                // To remove the ThreadLocal value...
+                for(int removeId  : removeNode)
+                   if((threadId-INITIAL_VALUE) == removeId){
+                       n.remove();
+                       break;
+                   }
+
+                 // To remove the ThreadLocal value and set new value ...
+                 for(int removeId  : removeAndSet)
+                    if((threadId-INITIAL_VALUE) == removeId){
+                        n.remove();
+                        n.set(REMOVE_SET_VALUE);
+                        break;
+                    }
+                x[threadId-INITIAL_VALUE] =  n.get();
+            }catch(Throwable ex){
+                exceptions[threadId-INITIAL_VALUE] = ex;
+            }
+             // Wait for child (if any)
+            if (child != null) {
+                try {
+                     child.join();
+                } catch(InterruptedException e) {
+                     throw(new RuntimeException("Interrupted"));
+                }
+            }
+        }
+    }
+}
diff --git a/jdk/test/java/lang/ProcessBuilder/Basic.java b/jdk/test/java/lang/ProcessBuilder/Basic.java
new file mode 100644
index 0000000..4a57ad9
--- /dev/null
+++ b/jdk/test/java/lang/ProcessBuilder/Basic.java
@@ -0,0 +1,1525 @@
+/*
+ * Copyright 2003-2007 Sun Microsystems, Inc.  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 Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
+ * CA 95054 USA or visit www.sun.com if you need additional information or
+ * have any questions.
+ */
+
+/*
+ * @test
+ * @bug 4199068 4738465 4937983 4930681 4926230 4931433 4932663 4986689
+ *      5026830 5023243 5070673 4052517 4811767 6192449 6397034 6413313
+ *      6464154 6523983 6206031
+ * @summary Basic tests for Process and Environment Variable code
+ * @run main/othervm Basic
+ * @author Martin Buchholz
+ */
+
+import java.io.*;
+import java.util.*;
+import java.security.*;
+import java.util.regex.Pattern;
+import static java.lang.System.getenv;
+import static java.lang.System.out;
+import static java.lang.Boolean.TRUE;
+import static java.util.AbstractMap.SimpleImmutableEntry;
+
+public class Basic {
+
+    private static String commandOutput(Reader r) throws Throwable {
+        StringBuilder sb = new StringBuilder();
+        int c;
+        while ((c = r.read()) > 0)
+            if (c != '\r')
+                sb.append((char) c);
+        return sb.toString();
+    }
+
+    private static String commandOutput(Process p) throws Throwable {
+        check(p.getInputStream()  == p.getInputStream());
+        check(p.getOutputStream() == p.getOutputStream());
+        check(p.getErrorStream()  == p.getErrorStream());
+        Reader r = new InputStreamReader(p.getInputStream(),"UTF-8");
+        String output = commandOutput(r);
+        equal(p.waitFor(), 0);
+        equal(p.exitValue(), 0);
+        return output;
+    }
+
+    private static String commandOutput(ProcessBuilder pb) {
+        try {
+            return commandOutput(pb.start());
+        } catch (Throwable t) {
+            String commandline = "";
+            for (String arg : pb.command())
+                commandline += " " + arg;
+            System.out.println("Exception trying to run process: " + commandline);
+            unexpected(t);
+            return "";
+        }
+    }
+
+    private static String commandOutput(String...command) {
+        try {
+            return commandOutput(Runtime.getRuntime().exec(command));
+        } catch (Throwable t) {
+            String commandline = "";
+            for (String arg : command)
+                commandline += " " + arg;
+            System.out.println("Exception trying to run process: " + commandline);
+            unexpected(t);
+            return "";
+        }
+    }
+
+    private static void checkCommandOutput(ProcessBuilder pb,
+                                           String expected,
+                                           String failureMsg) {
+        String got = commandOutput(pb);
+        check(got.equals(expected),
+              failureMsg + "\n" +
+              "Expected: \"" + expected + "\"\n" +
+              "Got: \"" + got + "\"");
+    }
+
+    private static String absolutifyPath(String path) {
+        StringBuilder sb = new StringBuilder();
+        for (String file : path.split(File.pathSeparator)) {
+            if (sb.length() != 0)
+                sb.append(File.pathSeparator);
+            sb.append(new File(file).getAbsolutePath());
+        }
+        return sb.toString();
+    }
+
+    // compare windows-style, by canonicalizing to upper case,
+    // not lower case as String.compareToIgnoreCase does
+    private static class WindowsComparator
+        implements Comparator<String> {
+        public int compare(String x, String y) {
+            return x.toUpperCase(Locale.US)
+                .compareTo(y.toUpperCase(Locale.US));
+        }
+    }
+
+    private static String sortedLines(String lines) {
+        String[] arr = lines.split("\n");
+        List<String> ls = new ArrayList<String>();
+        for (String s : arr)
+            ls.add(s);
+        Collections.sort(ls, new WindowsComparator());
+        StringBuilder sb = new StringBuilder();
+        for (String s : ls)
+            sb.append(s + "\n");
+        return sb.toString();
+    }
+
+    private static void compareLinesIgnoreCase(String lines1, String lines2) {
+        if (! (sortedLines(lines1).equalsIgnoreCase(sortedLines(lines2)))) {
+            String dashes =
+                "-----------------------------------------------------";
+            out.println(dashes);
+            out.print(sortedLines(lines1));
+            out.println(dashes);
+            out.print(sortedLines(lines2));
+            out.println(dashes);
+            out.println("sizes: " + sortedLines(lines1).length() +
+                        " " + sortedLines(lines2).length());
+
+            fail("Sorted string contents differ");
+        }
+    }
+
+    private static final Runtime runtime = Runtime.getRuntime();
+
+    private static final String[] winEnvCommand = {"cmd.exe", "/c", "set"};
+
+    private static String winEnvFilter(String env) {
+        return env.replaceAll("\r", "")
+            .replaceAll("(?m)^(?:COMSPEC|PROMPT|PATHEXT)=.*\n","");
+    }
+
+    private static String unixEnvProg() {
+        return new File("/usr/bin/env").canExecute() ? "/usr/bin/env"
+            : "/bin/env";
+    }
+
+    private static String nativeEnv(String[] env) {
+        try {
+            if (Windows.is()) {
+                return winEnvFilter
+                    (commandOutput(runtime.exec(winEnvCommand, env)));
+            } else {
+                return commandOutput(runtime.exec(unixEnvProg(), env));
+            }
+        } catch (Throwable t) { throw new Error(t); }
+    }
+
+    private static String nativeEnv(ProcessBuilder pb) {
+        try {
+            if (Windows.is()) {
+                pb.command(winEnvCommand);
+                return winEnvFilter(commandOutput(pb));
+            } else {
+                pb.command(new String[]{unixEnvProg()});
+                return commandOutput(pb);
+            }
+        } catch (Throwable t) { throw new Error(t); }
+    }
+
+    private static void checkSizes(Map<String,String> environ, int size) {
+        try {
+            equal(size, environ.size());
+            equal(size, environ.entrySet().size());
+            equal(size, environ.keySet().size());
+            equal(size, environ.values().size());
+
+            boolean isEmpty = (size == 0);
+            equal(isEmpty, environ.isEmpty());
+            equal(isEmpty, environ.entrySet().isEmpty());
+            equal(isEmpty, environ.keySet().isEmpty());
+            equal(isEmpty, environ.values().isEmpty());
+        } catch (Throwable t) { unexpected(t); }
+    }
+
+    private interface EnvironmentFrobber {
+        void doIt(Map<String,String> environ);
+    }
+
+    private static void testVariableDeleter(EnvironmentFrobber fooDeleter) {
+        try {
+            Map<String,String> environ = new ProcessBuilder().environment();
+            environ.put("Foo", "BAAR");
+            fooDeleter.doIt(environ);
+            equal(environ.get("Foo"), null);
+            equal(environ.remove("Foo"), null);
+        } catch (Throwable t) { unexpected(t); }
+    }
+
+    private static void testVariableAdder(EnvironmentFrobber fooAdder) {
+        try {
+            Map<String,String> environ = new ProcessBuilder().environment();
+            environ.remove("Foo");
+            fooAdder.doIt(environ);
+            equal(environ.get("Foo"), "Bahrein");
+        } catch (Throwable t) { unexpected(t); }
+    }
+
+    private static void testVariableModifier(EnvironmentFrobber fooModifier) {
+        try {
+            Map<String,String> environ = new ProcessBuilder().environment();
+            environ.put("Foo","OldValue");
+            fooModifier.doIt(environ);
+            equal(environ.get("Foo"), "NewValue");
+        } catch (Throwable t) { unexpected(t); }
+    }
+
+    private static void printUTF8(String s) throws IOException {
+        out.write(s.getBytes("UTF-8"));
+    }
+
+    private static String getenvAsString(Map<String,String> environment) {
+        StringBuilder sb = new StringBuilder();
+        for (Map.Entry<String,String> e : environment.entrySet())
+            // Ignore magic environment variables added by the launcher
+            if (! e.getKey().equals("NLSPATH") &&
+                ! e.getKey().equals("XFILESEARCHPATH") &&
+                ! e.getKey().equals("LD_LIBRARY_PATH"))
+                sb.append(e.getKey())
+                    .append('=')
+                    .append(e.getValue())
+                    .append(',');
+        return sb.toString();
+    }
+
+    static void print4095(OutputStream s) throws Throwable {
+        byte[] bytes = new byte[4095];
+        Arrays.fill(bytes, (byte) '!');
+        s.write(bytes);         // Might hang!
+    }
+
+    public static class JavaChild {
+        public static void main(String args[]) throws Throwable {
+            String action = args[0];
+            if (action.equals("System.getenv(String)")) {
+                String val = System.getenv(args[1]);
+                printUTF8(val == null ? "null" : val);
+            } else if (action.equals("System.getenv(\\u1234)")) {
+                String val = System.getenv("\u1234");
+                printUTF8(val == null ? "null" : val);
+            } else if (action.equals("System.getenv()")) {
+                printUTF8(getenvAsString(System.getenv()));
+            } else if (action.equals("pwd")) {
+                printUTF8(new File(System.getProperty("user.dir"))
+                          .getCanonicalPath());
+            } else if (action.equals("print4095")) {
+                print4095(System.out);
+                System.exit(5);
+            } else if (action.equals("OutErr")) {
+                // You might think the system streams would be
+                // buffered, and in fact they are implemented using
+                // BufferedOutputStream, but each and every print
+                // causes immediate operating system I/O.
+                System.out.print("out");
+                System.err.print("err");
+                System.out.print("out");
+                System.err.print("err");
+            } else if (action.equals("null PATH")) {
+                equal(System.getenv("PATH"), null);
+                check(new File("/bin/true").exists());
+                check(new File("/bin/false").exists());
+                ProcessBuilder pb1 = new ProcessBuilder();
+                ProcessBuilder pb2 = new ProcessBuilder();
+                pb2.environment().put("PATH", "anyOldPathIgnoredAnyways");
+                ProcessResults r;
+
+                for (final ProcessBuilder pb :
+                         new ProcessBuilder[] {pb1, pb2}) {
+                    pb.command("true");
+                    r = run(pb.start());
+                    equal(r.exitValue(), True.exitValue());
+
+                    pb.command("false");
+                    r = run(pb.start());
+                    equal(r.exitValue(), False.exitValue());
+                }
+
+                if (failed != 0) throw new Error("null PATH");
+            } else if (action.equals("PATH search algorithm")) {
+                equal(System.getenv("PATH"), "dir1:dir2:");
+                check(new File("/bin/true").exists());
+                check(new File("/bin/false").exists());
+                String[] cmd = {"prog"};
+                ProcessBuilder pb1 = new ProcessBuilder(cmd);
+                ProcessBuilder pb2 = new ProcessBuilder(cmd);
+                ProcessBuilder pb3 = new ProcessBuilder(cmd);
+                pb2.environment().put("PATH", "anyOldPathIgnoredAnyways");
+                pb3.environment().remove("PATH");
+
+                for (final ProcessBuilder pb :
+                         new ProcessBuilder[] {pb1, pb2, pb3}) {
+                    try {
+                        // Not on PATH at all; directories don't exist
+                        try {
+                            pb.start();
+                            fail("Expected IOException not thrown");
+                        } catch (IOException e) {
+                            String m = e.getMessage();
+                            if (EnglishUnix.is() &&
+                                ! matches(m, "No such file"))
+                                unexpected(e);
+                        } catch (Throwable t) { unexpected(t); }
+
+                        // Not on PATH at all; directories exist
+                        new File("dir1").mkdirs();
+                        new File("dir2").mkdirs();
+                        try {
+                            pb.start();
+                            fail("Expected IOException not thrown");
+                        } catch (IOException e) {
+                            String m = e.getMessage();
+                            if (EnglishUnix.is() &&
+                                ! matches(m, "No such file"))
+                                unexpected(e);
+                        } catch (Throwable t) { unexpected(t); }
+
+                        // Can't execute a directory -- permission denied
+                        // Report EACCES errno
+                        new File("dir1/prog").mkdirs();
+                        try {
+                            pb.start();
+                            fail("Expected IOException not thrown");
+                        } catch (IOException e) {
+                            String m = e.getMessage();
+                            if (EnglishUnix.is() &&
+                                ! matches(m, "Permission denied"))
+                                unexpected(e);
+                        } catch (Throwable t) { unexpected(t); }
+
+                        // continue searching if EACCES
+                        copy("/bin/true", "dir2/prog");
+                        equal(run(pb.start()).exitValue(), True.exitValue());
+                        new File("dir1/prog").delete();
+                        new File("dir2/prog").delete();
+
+                        new File("dir2/prog").mkdirs();
+                        copy("/bin/true", "dir1/prog");
+                        equal(run(pb.start()).exitValue(), True.exitValue());
+
+                        // Check empty PATH component means current directory
+                        new File("dir1/prog").delete();
+                        new File("dir2/prog").delete();
+                        copy("/bin/true", "./prog");
+                        equal(run(pb.start()).exitValue(), True.exitValue());
+
+                        // If prog found on both parent and child's PATH,
+                        // parent's is used.
+                        new File("dir1/prog").delete();
+                        new File("dir2/prog").delete();
+                        new File("prog").delete();
+                        new File("dir3").mkdirs();
+                        copy("/bin/true", "dir1/prog");
+                        copy("/bin/false", "dir3/prog");
+                        pb.environment().put("PATH","dir3");
+                        equal(run(pb.start()).exitValue(), True.exitValue());
+                        copy("/bin/true", "dir3/prog");
+                        copy("/bin/false", "dir1/prog");
+                        equal(run(pb.start()).exitValue(), False.exitValue());
+
+                    } finally {
+                        // cleanup
+                        new File("dir1/prog").delete();
+                        new File("dir2/prog").delete();
+                        new File("dir3/prog").delete();
+                        new File("dir1").delete();
+                        new File("dir2").delete();
+                        new File("dir3").delete();
+                        new File("prog").delete();
+                    }
+                }
+
+                if (failed != 0) throw new Error("PATH search algorithm");
+            }
+            else throw new Error("JavaChild invocation error");
+        }
+    }
+
+    private static void copy(String src, String dst) {
+        system("/bin/cp", "-fp", src, dst);
+    }
+
+    private static void system(String... command) {
+        try {
+            ProcessBuilder pb = new ProcessBuilder(command);
+            ProcessResults r = run(pb.start());
+            equal(r.exitValue(), 0);
+            equal(r.out(), "");
+            equal(r.err(), "");
+        } catch (Throwable t) { unexpected(t); }
+    }
+
+    private static String javaChildOutput(ProcessBuilder pb, String...args) {
+        List<String> list = new ArrayList<String>(javaChildArgs);
+        for (String arg : args)
+            list.add(arg);
+        pb.command(list);
+        return commandOutput(pb);
+    }
+
+    private static String getenvInChild(ProcessBuilder pb) {
+        return javaChildOutput(pb, "System.getenv()");
+    }
+
+    private static String getenvInChild1234(ProcessBuilder pb) {
+        return javaChildOutput(pb, "System.getenv(\\u1234)");
+    }
+
+    private static String getenvInChild(ProcessBuilder pb, String name) {
+        return javaChildOutput(pb, "System.getenv(String)", name);
+    }
+
+    private static String pwdInChild(ProcessBuilder pb) {
+        return javaChildOutput(pb, "pwd");
+    }
+
+    private static final String javaExe =
+        System.getProperty("java.home") +
+        File.separator + "bin" + File.separator + "java";
+
+    private static final String classpath =
+        System.getProperty("java.class.path");
+
+    private static final List<String> javaChildArgs =
+        Arrays.asList(new String[]
+            { javaExe, "-classpath", absolutifyPath(classpath),
+              "Basic$JavaChild"});
+
+    private static void testEncoding(String encoding, String tested) {
+        try {
+            // If round trip conversion works, should be able to set env vars
+            // correctly in child.
+            if (new String(tested.getBytes()).equals(tested)) {
+                out.println("Testing " + encoding + " environment values");
+                ProcessBuilder pb = new ProcessBuilder();
+                pb.environment().put("ASCIINAME",tested);
+                equal(getenvInChild(pb,"ASCIINAME"), tested);
+            }
+        } catch (Throwable t) { unexpected(t); }
+    }
+
+    static class Windows {
+        public static boolean is() { return is; }
+        private static final boolean is =
+            System.getProperty("os.name").startsWith("Windows");
+    }
+
+    static class Unix {
+        public static boolean is() { return is; }
+        private static final boolean is =
+            (! Windows.is() &&
+             new File("/bin/sh").exists() &&
+             new File("/bin/true").exists() &&
+             new File("/bin/false").exists());
+    }
+
+    static class UnicodeOS {
+        public static boolean is() { return is; }
+        private static final String osName = System.getProperty("os.name");
+        private static final boolean is =
+            // MacOS X would probably also qualify
+            osName.startsWith("Windows")   &&
+            ! osName.startsWith("Windows 9") &&
+            ! osName.equals("Windows Me");
+    }
+
+    static class True {
+        public static int exitValue() { return 0; }
+    }
+
+    private static class False {
+        public static int exitValue() { return exitValue; }
+        private static final int exitValue = exitValue0();
+        private static int exitValue0() {
+            // /bin/false returns an *unspecified* non-zero number.
+            try {
+                if (! Unix.is())
+                    return -1;
+                else {
+                    int rc = new ProcessBuilder("/bin/false")
+                        .start().waitFor();
+                    check(rc != 0);
+                    return rc;
+                }
+            } catch (Throwable t) { unexpected(t); return -1; }
+        }
+    }
+
+    static class EnglishUnix {
+        private final static Boolean is =
+            (! Windows.is() && isEnglish("LANG") && isEnglish("LC_ALL"));
+
+        private static boolean isEnglish(String envvar) {
+            String val = getenv(envvar);
+            return (val == null) || val.matches("en.*");
+        }
+
+        /** Returns true if we can expect English OS error strings */
+        static boolean is() { return is; }
+    }
+
+    private static boolean matches(String str, String regex) {
+        return Pattern.compile(regex).matcher(str).find();
+    }
+
+    private static String sortByLinesWindowsly(String text) {
+        String[] lines = text.split("\n");
+        Arrays.sort(lines, new WindowsComparator());
+        StringBuilder sb = new StringBuilder();
+        for (String line : lines)
+            sb.append(line).append("\n");
+        return sb.toString();
+    }
+
+    private static void checkMapSanity(Map<String,String> map) {
+        try {
+            Set<String> keySet = map.keySet();
+            Collection<String> values = map.values();
+            Set<Map.Entry<String,String>> entrySet = map.entrySet();
+
+            equal(entrySet.size(), keySet.size());
+            equal(entrySet.size(), values.size());
+
+            StringBuilder s1 = new StringBuilder();
+            for (Map.Entry<String,String> e : entrySet)
+                s1.append(e.getKey() + "=" + e.getValue() + "\n");
+
+            StringBuilder s2 = new StringBuilder();
+            for (String var : keySet)
+                s2.append(var + "=" + map.get(var) + "\n");
+
+            equal(s1.toString(), s2.toString());
+
+            Iterator<String> kIter = keySet.iterator();
+            Iterator<String> vIter = values.iterator();
+            Iterator<Map.Entry<String,String>> eIter = entrySet.iterator();
+
+            while (eIter.hasNext()) {
+                Map.Entry<String,String> entry = eIter.next();
+                String key   = kIter.next();
+                String value = vIter.next();
+                check(entrySet.contains(entry));
+                check(keySet.contains(key));
+                check(values.contains(value));
+                check(map.containsKey(key));
+                check(map.containsValue(value));
+                equal(entry.getKey(), key);
+                equal(entry.getValue(), value);
+            }
+            check(! kIter.hasNext() &&
+                  ! vIter.hasNext());
+
+        } catch (Throwable t) { unexpected(t); }
+    }
+
+    private static void checkMapEquality(Map<String,String> map1,
+                                         Map<String,String> map2) {
+        try {
+            equal(map1.size(), map2.size());
+            equal(map1.isEmpty(), map2.isEmpty());
+            for (String key : map1.keySet()) {
+                equal(map1.get(key), map2.get(key));
+                check(map2.keySet().contains(key));
+            }
+            equal(map1, map2);
+            equal(map2, map1);
+            equal(map1.entrySet(), map2.entrySet());
+            equal(map2.entrySet(), map1.entrySet());
+            equal(map1.keySet(), map2.keySet());
+            equal(map2.keySet(), map1.keySet());
+
+            equal(map1.hashCode(), map2.hashCode());
+            equal(map1.entrySet().hashCode(), map2.entrySet().hashCode());
+            equal(map1.keySet().hashCode(), map2.keySet().hashCode());
+        } catch (Throwable t) { unexpected(t); }
+    }
+
+    private static void realMain(String[] args) throws Throwable {
+        if (Windows.is())
+            System.out.println("This appears to be a Windows system.");
+        if (Unix.is())
+            System.out.println("This appears to be a Unix system.");
+        if (UnicodeOS.is())
+            System.out.println("This appears to be a Unicode-based OS.");
+
+        //----------------------------------------------------------------
+        // Basic tests for setting, replacing and deleting envvars
+        //----------------------------------------------------------------
+        try {
+            ProcessBuilder pb = new ProcessBuilder();
+            Map<String,String> environ = pb.environment();
+
+            // New env var
+            environ.put("QUUX", "BAR");
+            equal(environ.get("QUUX"), "BAR");
+            equal(getenvInChild(pb,"QUUX"), "BAR");
+
+            // Modify env var
+            environ.put("QUUX","bear");
+            equal(environ.get("QUUX"), "bear");
+            equal(getenvInChild(pb,"QUUX"), "bear");
+            checkMapSanity(environ);
+
+            // Remove env var
+            environ.remove("QUUX");
+            equal(environ.get("QUUX"), null);
+            equal(getenvInChild(pb,"QUUX"), "null");
+            checkMapSanity(environ);
+
+            // Remove non-existent env var
+            environ.remove("QUUX");
+            equal(environ.get("QUUX"), null);
+            equal(getenvInChild(pb,"QUUX"), "null");
+            checkMapSanity(environ);
+        } catch (Throwable t) { unexpected(t); }
+
+        //----------------------------------------------------------------
+        // Pass Empty environment to child
+        //----------------------------------------------------------------
+        try {
+            ProcessBuilder pb = new ProcessBuilder();
+            pb.environment().clear();
+            equal(getenvInChild(pb), "");
+        } catch (Throwable t) { unexpected(t); }
+
+        //----------------------------------------------------------------
+        // System.getenv() is read-only.
+        //----------------------------------------------------------------
+        THROWS(UnsupportedOperationException.class,
+            new Fun(){void f(){ getenv().put("FOO","BAR");}},
+            new Fun(){void f(){ getenv().remove("PATH");}},
+            new Fun(){void f(){ getenv().keySet().remove("PATH");}},
+            new Fun(){void f(){ getenv().values().remove("someValue");}});
+
+        try {
+            Collection<Map.Entry<String,String>> c = getenv().entrySet();
+            if (! c.isEmpty())
+                try {
+                    c.iterator().next().setValue("foo");
+                    fail("Expected UnsupportedOperationException not thrown");
+                } catch (UnsupportedOperationException e) {} // OK
+        } catch (Throwable t) { unexpected(t); }
+
+        //----------------------------------------------------------------
+        // System.getenv() always returns the same object in our implementation.
+        //----------------------------------------------------------------
+        try {
+            check(System.getenv() == System.getenv());
+        } catch (Throwable t) { unexpected(t); }
+
+        //----------------------------------------------------------------
+        // You can't create an env var name containing "=",
+        // or an env var name or value containing NUL.
+        //----------------------------------------------------------------
+        {
+            final Map<String,String> m = new ProcessBuilder().environment();
+            THROWS(IllegalArgumentException.class,
+                new Fun(){void f(){ m.put("FOO=","BAR");}},
+                new Fun(){void f(){ m.put("FOO\u0000","BAR");}},
+                new Fun(){void f(){ m.put("FOO","BAR\u0000");}});
+        }
+
+        //----------------------------------------------------------------
+        // Commands must never be null.
+        //----------------------------------------------------------------
+        THROWS(NullPointerException.class,
+               new Fun(){void f(){
+                   new ProcessBuilder((List<String>)null);}},
+               new Fun(){void f(){
+                   new ProcessBuilder().command((List<String>)null);}});
+
+        //----------------------------------------------------------------
+        // Put in a command; get the same one back out.
+        //----------------------------------------------------------------
+        try {
+            List<String> command = new ArrayList<String>();
+            ProcessBuilder pb = new ProcessBuilder(command);
+            check(pb.command() == command);
+            List<String> command2 = new ArrayList<String>(2);
+            command2.add("foo");
+            command2.add("bar");
+            pb.command(command2);
+            check(pb.command() == command2);
+            pb.command("foo", "bar");
+            check(pb.command() != command2 && pb.command().equals(command2));
+            pb.command(command2);
+            command2.add("baz");
+            equal(pb.command().get(2), "baz");
+        } catch (Throwable t) { unexpected(t); }
+
+        //----------------------------------------------------------------
+        // Commands must contain at least one element.
+        //----------------------------------------------------------------
+        THROWS(IndexOutOfBoundsException.class,
+            new Fun() { void f() throws IOException {
+                new ProcessBuilder().start();}},
+            new Fun() { void f() throws IOException {
+                new ProcessBuilder(new ArrayList<String>()).start();}},
+            new Fun() { void f() throws IOException {
+                Runtime.getRuntime().exec(new String[]{});}});
+
+        //----------------------------------------------------------------
+        // Commands must not contain null elements at start() time.
+        //----------------------------------------------------------------
+        THROWS(NullPointerException.class,
+            new Fun() { void f() throws IOException {
+                new ProcessBuilder("foo",null,"bar").start();}},
+            new Fun() { void f() throws IOException {
+                new ProcessBuilder((String)null).start();}},
+            new Fun() { void f() throws IOException {
+                new ProcessBuilder(new String[]{null}).start();}},
+            new Fun() { void f() throws IOException {
+                new ProcessBuilder(new String[]{"foo",null,"bar"}).start();}});
+
+        //----------------------------------------------------------------
+        // Command lists are growable.
+        //----------------------------------------------------------------
+        try {
+            new ProcessBuilder().command().add("foo");
+            new ProcessBuilder("bar").command().add("foo");
+            new ProcessBuilder(new String[]{"1","2"}).command().add("3");
+        } catch (Throwable t) { unexpected(t); }
+
+        //----------------------------------------------------------------
+        // Nulls in environment updates generate NullPointerException
+        //----------------------------------------------------------------
+        try {
+            final Map<String,String> env = new ProcessBuilder().environment();
+            THROWS(NullPointerException.class,
+                new Fun(){void f(){ env.put("foo",null);}},
+                new Fun(){void f(){ env.put(null,"foo");}},
+                new Fun(){void f(){ env.remove(null);}},
+                new Fun(){void f(){
+                    for (Map.Entry<String,String> e : env.entrySet())
+                        e.setValue(null);}},
+                new Fun() { void f() throws IOException {
+                    Runtime.getRuntime().exec(new String[]{"foo"},
+                                              new String[]{null});}});
+        } catch (Throwable t) { unexpected(t); }
+
+        //----------------------------------------------------------------
+        // Non-String types in environment updates generate ClassCastException
+        //----------------------------------------------------------------
+        try {
+            final Map<String,String> env = new ProcessBuilder().environment();
+            THROWS(ClassCastException.class,
+                new Fun(){void f(){ env.remove(TRUE);}},
+                new Fun(){void f(){ env.keySet().remove(TRUE);}},
+                new Fun(){void f(){ env.values().remove(TRUE);}},
+                new Fun(){void f(){ env.entrySet().remove(TRUE);}});
+        } catch (Throwable t) { unexpected(t); }
+
+        //----------------------------------------------------------------
+        // Check query operations on environment maps
+        //----------------------------------------------------------------
+        try {
+            List<Map<String,String>> envs =
+                new ArrayList<Map<String,String>>(2);
+            envs.add(System.getenv());
+            envs.add(new ProcessBuilder().environment());
+            for (final Map<String,String> env : envs) {
+                //----------------------------------------------------------------
+                // Nulls in environment queries are forbidden.
+                //----------------------------------------------------------------
+                THROWS(NullPointerException.class,
+                    new Fun(){void f(){ getenv(null);}},
+                    new Fun(){void f(){ env.get(null);}},
+                    new Fun(){void f(){ env.containsKey(null);}},
+                    new Fun(){void f(){ env.containsValue(null);}},
+                    new Fun(){void f(){ env.keySet().contains(null);}},
+                    new Fun(){void f(){ env.values().contains(null);}});
+
+                //----------------------------------------------------------------
+                // Non-String types in environment queries are forbidden.
+                //----------------------------------------------------------------
+                THROWS(ClassCastException.class,
+                    new Fun(){void f(){ env.get(TRUE);}},
+                    new Fun(){void f(){ env.containsKey(TRUE);}},
+                    new Fun(){void f(){ env.containsValue(TRUE);}},
+                    new Fun(){void f(){ env.keySet().contains(TRUE);}},
+                    new Fun(){void f(){ env.values().contains(TRUE);}});
+
+                //----------------------------------------------------------------
+                // Illegal String values in environment queries are (grumble) OK
+                //----------------------------------------------------------------
+                equal(env.get("\u0000"), null);
+                check(! env.containsKey("\u0000"));
+                check(! env.containsValue("\u0000"));
+                check(! env.keySet().contains("\u0000"));
+                check(! env.values().contains("\u0000"));
+            }
+
+        } catch (Throwable t) { unexpected(t); }
+
+        try {
+            final Set<Map.Entry<String,String>> entrySet =
+                new ProcessBuilder().environment().entrySet();
+            THROWS(NullPointerException.class,
+                   new Fun(){void f(){ entrySet.contains(null);}});
+            THROWS(ClassCastException.class,
+                new Fun(){void f(){ entrySet.contains(TRUE);}},
+                new Fun(){void f(){
+                    entrySet.contains(
+                        new SimpleImmutableEntry<Boolean,String>(TRUE,""));}});
+
+            check(! entrySet.contains
+                  (new SimpleImmutableEntry<String,String>("", "")));
+        } catch (Throwable t) { unexpected(t); }
+
+        //----------------------------------------------------------------
+        // Put in a directory; get the same one back out.
+        //----------------------------------------------------------------
+        try {
+            ProcessBuilder pb = new ProcessBuilder();
+            File foo = new File("foo");
+            equal(pb.directory(), null);
+            equal(pb.directory(foo).directory(), foo);
+            equal(pb.directory(null).directory(), null);
+        } catch (Throwable t) { unexpected(t); }
+
+        //----------------------------------------------------------------
+        // If round-trip conversion works, check envvar pass-through to child
+        //----------------------------------------------------------------
+        try {
+            testEncoding("ASCII",   "xyzzy");
+            testEncoding("Latin1",  "\u00f1\u00e1");
+            testEncoding("Unicode", "\u22f1\u11e1");
+        } catch (Throwable t) { unexpected(t); }
+
+        //----------------------------------------------------------------
+        // A surprisingly large number of ways to delete an environment var.
+        //----------------------------------------------------------------
+        testVariableDeleter(new EnvironmentFrobber() {
+                public void doIt(Map<String,String> environ) {
+                    environ.remove("Foo");}});
+
+        testVariableDeleter(new EnvironmentFrobber() {
+                public void doIt(Map<String,String> environ) {
+                    environ.keySet().remove("Foo");}});
+
+        testVariableDeleter(new EnvironmentFrobber() {
+                public void doIt(Map<String,String> environ) {
+                    environ.values().remove("BAAR");}});
+
+        testVariableDeleter(new EnvironmentFrobber() {
+                public void doIt(Map<String,String> environ) {
+                    // Legally fabricate a ProcessEnvironment.StringEntry,
+                    // even though it's private.
+                    Map<String,String> environ2
+                        = new ProcessBuilder().environment();
+                    environ2.clear();
+                    environ2.put("Foo","BAAR");
+                    // Subtlety alert.
+                    Map.Entry<String,String> e
+                        = environ2.entrySet().iterator().next();
+                    environ.entrySet().remove(e);}});
+
+        testVariableDeleter(new EnvironmentFrobber() {
+                public void doIt(Map<String,String> environ) {
+                    Map.Entry<String,String> victim = null;
+                    for (Map.Entry<String,String> e : environ.entrySet())
+                        if (e.getKey().equals("Foo"))
+                            victim = e;
+                    if (victim != null)
+                        environ.entrySet().remove(victim);}});
+
+        testVariableDeleter(new EnvironmentFrobber() {
+                public void doIt(Map<String,String> environ) {
+                    Iterator<String> it = environ.keySet().iterator();
+                    while (it.hasNext()) {
+                        String val = it.next();
+                        if (val.equals("Foo"))
+                            it.remove();}}});
+
+        testVariableDeleter(new EnvironmentFrobber() {
+                public void doIt(Map<String,String> environ) {
+                    Iterator<Map.Entry<String,String>> it
+                        = environ.entrySet().iterator();
+                    while (it.hasNext()) {
+                        Map.Entry<String,String> e = it.next();
+                        if (e.getKey().equals("Foo"))
+                            it.remove();}}});
+
+        testVariableDeleter(new EnvironmentFrobber() {
+                public void doIt(Map<String,String> environ) {
+                    Iterator<String> it = environ.values().iterator();
+                    while (it.hasNext()) {
+                        String val = it.next();
+                        if (val.equals("BAAR"))
+                            it.remove();}}});
+
+        //----------------------------------------------------------------
+        // A surprisingly small number of ways to add an environment var.
+        //----------------------------------------------------------------
+        testVariableAdder(new EnvironmentFrobber() {
+                public void doIt(Map<String,String> environ) {
+                    environ.put("Foo","Bahrein");}});
+
+        //----------------------------------------------------------------
+        // A few ways to modify an environment var.
+        //----------------------------------------------------------------
+        testVariableModifier(new EnvironmentFrobber() {
+                public void doIt(Map<String,String> environ) {
+                    environ.put("Foo","NewValue");}});
+
+        testVariableModifier(new EnvironmentFrobber() {
+                public void doIt(Map<String,String> environ) {
+                    for (Map.Entry<String,String> e : environ.entrySet())
+                        if (e.getKey().equals("Foo"))
+                            e.setValue("NewValue");}});
+
+        //----------------------------------------------------------------
+        // Fiddle with environment sizes
+        //----------------------------------------------------------------
+        try {
+            Map<String,String> environ = new ProcessBuilder().environment();
+            int size = environ.size();
+            checkSizes(environ, size);
+
+            environ.put("UnLiKeLYeNVIROmtNam", "someVal");
+            checkSizes(environ, size+1);
+
+            // Check for environment independence
+            new ProcessBuilder().environment().clear();
+
+            environ.put("UnLiKeLYeNVIROmtNam", "someOtherVal");
+            checkSizes(environ, size+1);
+
+            environ.remove("UnLiKeLYeNVIROmtNam");
+            checkSizes(environ, size);
+
+            environ.clear();
+            checkSizes(environ, 0);
+
+            environ.clear();
+            checkSizes(environ, 0);
+
+            environ = new ProcessBuilder().environment();
+            environ.keySet().clear();
+            checkSizes(environ, 0);
+
+            environ = new ProcessBuilder().environment();
+            environ.entrySet().clear();
+            checkSizes(environ, 0);
+
+            environ = new ProcessBuilder().environment();
+            environ.values().clear();
+            checkSizes(environ, 0);
+        } catch (Throwable t) { unexpected(t); }
+
+        //----------------------------------------------------------------
+        // Check that various map invariants hold
+        //----------------------------------------------------------------
+        checkMapSanity(new ProcessBuilder().environment());
+        checkMapSanity(System.getenv());
+        checkMapEquality(new ProcessBuilder().environment(),
+                         new ProcessBuilder().environment());
+
+
+        //----------------------------------------------------------------
+        // Check effects on external "env" command.
+        //----------------------------------------------------------------
+        try {
+            Set<String> env1 = new HashSet<String>
+                (Arrays.asList(nativeEnv((String[])null).split("\n")));
+
+            ProcessBuilder pb = new ProcessBuilder();
+            pb.environment().put("QwErTyUiOp","AsDfGhJk");
+
+            Set<String> env2 = new HashSet<String>
+                (Arrays.asList(nativeEnv(pb).split("\n")));
+
+            check(env2.size() == env1.size() + 1);
+            env1.add("QwErTyUiOp=AsDfGhJk");
+            check(env1.equals(env2));
+        } catch (Throwable t) { unexpected(t); }
+
+        //----------------------------------------------------------------
+        // Test Runtime.exec(...envp...)
+        // Check for sort order of environment variables on Windows.
+        //----------------------------------------------------------------
+        try {
+            // '+' < 'A' < 'Z' < '_' < 'a' < 'z' < '~'
+            String[]envp = {"FOO=BAR","BAZ=GORP","QUUX=",
+                            "+=+", "_=_", "~=~"};
+            String output = nativeEnv(envp);
+            String expected = "+=+\nBAZ=GORP\nFOO=BAR\nQUUX=\n_=_\n~=~\n";
+            // On Windows, Java must keep the environment sorted.
+            // Order is random on Unix, so this test does the sort.
+            if (! Windows.is())
+                output = sortByLinesWindowsly(output);
+            equal(output, expected);
+        } catch (Throwable t) { unexpected(t); }
+
+        //----------------------------------------------------------------
+        // System.getenv() must be consistent with System.getenv(String)
+        //----------------------------------------------------------------
+        try {
+            for (Map.Entry<String,String> e : getenv().entrySet())
+                equal(getenv(e.getKey()), e.getValue());
+        } catch (Throwable t) { unexpected(t); }
+
+        //----------------------------------------------------------------
+        // Fiddle with working directory in child
+        //----------------------------------------------------------------
+        try {
+            String canonicalUserDir =
+                new File(System.getProperty("user.dir")).getCanonicalPath();
+            String[] sdirs = new String[]
+                {".", "..", "/", "/bin",
+                 "C:", "c:", "C:/", "c:\\", "\\", "\\bin" };
+            for (String sdir : sdirs) {
+                File dir = new File(sdir);
+                if (! (dir.isDirectory() && dir.exists()))
+                    continue;
+                out.println("Testing directory " + dir);
+                dir = new File(dir.getCanonicalPath());
+
+                ProcessBuilder pb = new ProcessBuilder();
+                equal(pb.directory(), null);
+                equal(pwdInChild(pb), canonicalUserDir);
+
+                pb.directory(dir);
+                equal(pb.directory(), dir);
+                equal(pwdInChild(pb), dir.toString());
+
+                pb.directory(null);
+                equal(pb.directory(), null);
+                equal(pwdInChild(pb), canonicalUserDir);
+
+                pb.directory(dir);
+            }
+        } catch (Throwable t) { unexpected(t); }
+
+        //----------------------------------------------------------------
+        // Windows has tricky semi-case-insensitive semantics
+        //----------------------------------------------------------------
+        if (Windows.is())
+            try {
+                out.println("Running case insensitve variable tests");
+                for (String[] namePair :
+                         new String[][]
+                    { new String[]{"PATH","PaTh"},
+                      new String[]{"home","HOME"},
+                      new String[]{"SYSTEMROOT","SystemRoot"}}) {
+                    check((getenv(namePair[0]) == null &&
+                           getenv(namePair[1]) == null)
+                          ||
+                          getenv(namePair[0]).equals(getenv(namePair[1])),
+                          "Windows environment variables are not case insensitive");
+                }
+            } catch (Throwable t) { unexpected(t); }
+
+        //----------------------------------------------------------------
+        // Test proper Unicode child environment transfer
+        //----------------------------------------------------------------
+        if (UnicodeOS.is())
+            try {
+                ProcessBuilder pb = new ProcessBuilder();
+                pb.environment().put("\u1234","\u5678");
+                pb.environment().remove("PATH");
+                equal(getenvInChild1234(pb), "\u5678");
+            } catch (Throwable t) { unexpected(t); }
+
+
+        //----------------------------------------------------------------
+        // Test Runtime.exec(...envp...) with envstrings with initial `='
+        //----------------------------------------------------------------
+        try {
+            List<String> childArgs = new ArrayList<String>(javaChildArgs);
+            childArgs.add("System.getenv()");
+            String[] cmdp = childArgs.toArray(new String[childArgs.size()]);
+            String[] envp = {"=ExitValue=3", "=C:=\\"};
+            Process p = Runtime.getRuntime().exec(cmdp, envp);
+            String expected = Windows.is() ? "=C:=\\,=ExitValue=3," : "=C:=\\,";
+            equal(commandOutput(p), expected);
+            if (Windows.is()) {
+                ProcessBuilder pb = new ProcessBuilder(childArgs);
+                pb.environment().clear();
+                pb.environment().put("=ExitValue", "3");
+                pb.environment().put("=C:", "\\");
+                equal(commandOutput(pb), expected);
+            }
+        } catch (Throwable t) { unexpected(t); }
+
+        //----------------------------------------------------------------
+        // Test Runtime.exec(...envp...) with envstrings without any `='
+        //----------------------------------------------------------------
+        try {
+            String[] cmdp = {"echo"};
+            String[] envp = {"Hello", "World"}; // Yuck!
+            Process p = Runtime.getRuntime().exec(cmdp, envp);
+            equal(commandOutput(p), "\n");
+        } catch (Throwable t) { unexpected(t); }
+
+        //----------------------------------------------------------------
+        // Test Runtime.exec(...envp...) with envstrings containing NULs
+        //----------------------------------------------------------------
+        try {
+            List<String> childArgs = new ArrayList<String>(javaChildArgs);
+            childArgs.add("System.getenv()");
+            String[] cmdp = childArgs.toArray(new String[childArgs.size()]);
+            String[] envp = {"LC_ALL=C\u0000\u0000", // Yuck!
+                             "FO\u0000=B\u0000R"};
+            Process p = Runtime.getRuntime().exec(cmdp, envp);
+            check(commandOutput(p).equals("LC_ALL=C,"),
+                  "Incorrect handling of envstrings containing NULs");
+        } catch (Throwable t) { unexpected(t); }
+
+        //----------------------------------------------------------------
+        // Test the redirectErrorStream property
+        //----------------------------------------------------------------
+        try {
+            ProcessBuilder pb = new ProcessBuilder();
+            equal(pb.redirectErrorStream(), false);
+            equal(pb.redirectErrorStream(true), pb);
+            equal(pb.redirectErrorStream(), true);
+            equal(pb.redirectErrorStream(false), pb);
+            equal(pb.redirectErrorStream(), false);
+        } catch (Throwable t) { unexpected(t); }
+
+        try {
+            List<String> childArgs = new ArrayList<String>(javaChildArgs);
+            childArgs.add("OutErr");
+            ProcessBuilder pb = new ProcessBuilder(childArgs);
+            {
+                ProcessResults r = run(pb.start());
+                equal(r.out(), "outout");
+                equal(r.err(), "errerr");
+            }
+            {
+                pb.redirectErrorStream(true);
+                ProcessResults r = run(pb.start());
+                equal(r.out(), "outerrouterr");
+                equal(r.err(), "");
+            }
+        } catch (Throwable t) { unexpected(t); }
+
+        if (! Windows.is() &&
+            new File("/bin/true").exists() &&
+            new File("/bin/false").exists()) {
+            //----------------------------------------------------------------
+            // We can find true and false when PATH is null
+            //----------------------------------------------------------------
+            try {
+                List<String> childArgs = new ArrayList<String>(javaChildArgs);
+                childArgs.add("null PATH");
+                ProcessBuilder pb = new ProcessBuilder(childArgs);
+                pb.environment().remove("PATH");
+                ProcessResults r = run(pb.start());
+                equal(r.out(), "");
+                equal(r.err(), "");
+                equal(r.exitValue(), 0);
+            } catch (Throwable t) { unexpected(t); }
+
+            //----------------------------------------------------------------
+            // PATH search algorithm on Unix
+            //----------------------------------------------------------------
+            try {
+                List<String> childArgs = new ArrayList<String>(javaChildArgs);
+                childArgs.add("PATH search algorithm");
+                ProcessBuilder pb = new ProcessBuilder(childArgs);
+                pb.environment().put("PATH", "dir1:dir2:");
+                ProcessResults r = run(pb.start());
+                equal(r.out(), "");
+                equal(r.err(), "");
+                equal(r.exitValue(), True.exitValue());
+            } catch (Throwable t) { unexpected(t); }
+
+            //----------------------------------------------------------------
+            // Parent's, not child's PATH is used
+            //----------------------------------------------------------------
+            try {
+                new File("suBdiR").mkdirs();
+                copy("/bin/true", "suBdiR/unliKely");
+                final ProcessBuilder pb =
+                    new ProcessBuilder(new String[]{"unliKely"});
+                pb.environment().put("PATH", "suBdiR");
+                THROWS(IOException.class,
+                       new Fun() {void f() throws Throwable {pb.start();}});
+            } catch (Throwable t) { unexpected(t);
+            } finally {
+                new File("suBdiR/unliKely").delete();
+                new File("suBdiR").delete();
+            }
+        }
+
+        //----------------------------------------------------------------
+        // Attempt to start bogus program ""
+        //----------------------------------------------------------------
+        try {
+            new ProcessBuilder("").start();
+            fail("Expected IOException not thrown");
+        } catch (IOException e) {
+            String m = e.getMessage();
+            if (EnglishUnix.is() &&
+                ! matches(m, "No such file or directory"))
+                unexpected(e);
+        } catch (Throwable t) { unexpected(t); }
+
+        //----------------------------------------------------------------
+        // Check that attempt to execute program name with funny
+        // characters throws an exception containing those characters.
+        //----------------------------------------------------------------
+        for (String programName : new String[] {"\u00f0", "\u01f0"})
+            try {
+                new ProcessBuilder(programName).start();
+                fail("Expected IOException not thrown");
+            } catch (IOException e) {
+                String m = e.getMessage();
+                Pattern p = Pattern.compile(programName);
+                if (! matches(m, programName)
+                    || (EnglishUnix.is()
+                        && ! matches(m, "No such file or directory")))
+                    unexpected(e);
+            } catch (Throwable t) { unexpected(t); }
+
+        //----------------------------------------------------------------
+        // Attempt to start process in nonexistent directory fails.
+        //----------------------------------------------------------------
+        try {
+            new ProcessBuilder("echo")
+                .directory(new File("UnLiKeLY"))
+                .start();
+            fail("Expected IOException not thrown");
+        } catch (IOException e) {
+            String m = e.getMessage();
+            if (! matches(m, "in directory")
+                || (EnglishUnix.is() &&
+                    ! matches(m, "No such file or directory")))
+                unexpected(e);
+        } catch (Throwable t) { unexpected(t); }
+
+        //----------------------------------------------------------------
+        // This would deadlock, if not for the fact that
+        // interprocess pipe buffers are at least 4096 bytes.
+        //----------------------------------------------------------------
+        try {
+            List<String> childArgs = new ArrayList<String>(javaChildArgs);
+            childArgs.add("print4095");
+            Process p = new ProcessBuilder(childArgs).start();
+            print4095(p.getOutputStream()); // Might hang!
+            p.waitFor();                    // Might hang!
+            equal(p.exitValue(), 5);
+        } catch (Throwable t) { unexpected(t); }
+
+        //----------------------------------------------------------------
+        // Attempt to start process with insufficient permissions fails.
+        //----------------------------------------------------------------
+        try {
+            new File("emptyCommand").delete();
+            new FileOutputStream("emptyCommand").close();
+            new File("emptyCommand").setExecutable(false);
+            new ProcessBuilder("./emptyCommand").start();
+            fail("Expected IOException not thrown");
+        } catch (IOException e) {
+            new File("./emptyCommand").delete();
+            String m = e.getMessage();
+            //e.printStackTrace();
+            if (EnglishUnix.is() &&
+                ! matches(m, "Permission denied"))
+                unexpected(e);
+        } catch (Throwable t) { unexpected(t); }
+
+        new File("emptyCommand").delete();
+
+        //----------------------------------------------------------------
+        // Check for correct security permission behavior
+        //----------------------------------------------------------------
+        final Policy policy = new Policy();
+        Policy.setPolicy(policy);
+        System.setSecurityManager(new SecurityManager());
+
+        try {
+            // No permissions required to CREATE a ProcessBuilder
+            policy.setPermissions(/* Nothing */);
+            new ProcessBuilder("env").directory(null).directory();
+            new ProcessBuilder("env").directory(new File("dir")).directory();
+            new ProcessBuilder("env").command("??").command();
+        } catch (Throwable t) { unexpected(t); }
+
+        THROWS(SecurityException.class,
+            new Fun() { void f() throws IOException {
+                policy.setPermissions(/* Nothing */);
+                System.getenv("foo");}},
+            new Fun() { void f() throws IOException {
+                policy.setPermissions(/* Nothing */);
+                System.getenv();}},
+            new Fun() { void f() throws IOException {
+                policy.setPermissions(/* Nothing */);
+                new ProcessBuilder("echo").start();}},
+            new Fun() { void f() throws IOException {
+                policy.setPermissions(/* Nothing */);
+                Runtime.getRuntime().exec("echo");}},
+            new Fun() { void f() throws IOException {
+                policy.setPermissions(new RuntimePermission("getenv.bar"));
+                System.getenv("foo");}});
+
+        try {
+            policy.setPermissions(new RuntimePermission("getenv.foo"));
+            System.getenv("foo");
+
+            policy.setPermissions(new RuntimePermission("getenv.*"));
+            System.getenv("foo");
+            System.getenv();
+            new ProcessBuilder().environment();
+        } catch (Throwable t) { unexpected(t); }
+
+
+        final Permission execPermission
+            = new FilePermission("<<ALL FILES>>", "execute");
+
+        THROWS(SecurityException.class,
+            new Fun() { void f() throws IOException {
+                // environment permission by itself insufficient
+                policy.setPermissions(new RuntimePermission("getenv.*"));
+                ProcessBuilder pb = new ProcessBuilder("env");
+                pb.environment().put("foo","bar");
+                pb.start();}},
+            new Fun() { void f() throws IOException {
+                 // exec permission by itself insufficient
+                 policy.setPermissions(execPermission);
+                 ProcessBuilder pb = new ProcessBuilder("env");
+                 pb.environment().put("foo","bar");
+                 pb.start();}});
+
+        try {
+            // Both permissions? OK.
+            policy.setPermissions(new RuntimePermission("getenv.*"),
+                                  execPermission);
+            ProcessBuilder pb = new ProcessBuilder("env");
+            pb.environment().put("foo","bar");
+            pb.start();
+        } catch (IOException e) { // OK
+        } catch (Throwable t) { unexpected(t); }
+
+        try {
+            // Don't need environment permission unless READING environment
+            policy.setPermissions(execPermission);
+            Runtime.getRuntime().exec("env", new String[]{});
+        } catch (IOException e) { // OK
+        } catch (Throwable t) { unexpected(t); }
+
+        try {
+            // Don't need environment permission unless READING environment
+            policy.setPermissions(execPermission);
+            new ProcessBuilder("env").start();
+        } catch (IOException e) { // OK
+        } catch (Throwable t) { unexpected(t); }
+
+        // Restore "normal" state without a security manager
+        policy.setPermissions(new RuntimePermission("setSecurityManager"));
+        System.setSecurityManager(null);
+
+    }
+
+    //----------------------------------------------------------------
+    // A Policy class designed to make permissions fiddling very easy.
+    //----------------------------------------------------------------
+    private static class Policy extends java.security.Policy {
+        private Permissions perms;
+
+        public void setPermissions(Permission...permissions) {
+            perms = new Permissions();
+            for (Permission permission : permissions)
+                perms.add(permission);
+        }
+
+        public Policy() { setPermissions(/* Nothing */); }
+
+        public PermissionCollection getPermissions(CodeSource cs) {
+            return perms;
+        }
+
+        public PermissionCollection getPermissions(ProtectionDomain pd) {
+            return perms;
+        }
+
+        public boolean implies(ProtectionDomain pd, Permission p) {
+            return perms.implies(p);
+        }
+
+        public void refresh() {}
+    }
+
+    private static class StreamAccumulator extends Thread {
+        private final InputStream is;
+        private final StringBuilder sb = new StringBuilder();
+        private Throwable throwable = null;
+
+        public String result () throws Throwable {
+            if (throwable != null)
+                throw throwable;
+            return sb.toString();
+        }
+
+        StreamAccumulator (InputStream is) {
+            this.is = is;
+        }
+
+        public void run() {
+            try {
+                Reader r = new InputStreamReader(is);
+                char[] buf = new char[4096];
+                int n;
+                while ((n = r.read(buf)) > 0) {
+                    sb.append(buf,0,n);
+                }
+            } catch (Throwable t) {
+                throwable = t;
+            }
+        }
+    }
+
+    private static ProcessResults run(Process p) {
+        Throwable throwable = null;
+        int exitValue = -1;
+        String out = "";
+        String err = "";
+
+        StreamAccumulator outAccumulator =
+            new StreamAccumulator(p.getInputStream());
+        StreamAccumulator errAccumulator =
+            new StreamAccumulator(p.getErrorStream());
+
+        try {
+            outAccumulator.start();
+            errAccumulator.start();
+
+            exitValue = p.waitFor();
+
+            outAccumulator.join();
+            errAccumulator.join();
+
+            out = outAccumulator.result();
+            err = errAccumulator.result();
+        } catch (Throwable t) {
+            throwable = t;
+        }
+
+        return new ProcessResults(out, err, exitValue, throwable);
+    }
+
+    //----------------------------------------------------------------
+    // Results of a command
+    //----------------------------------------------------------------
+    private static class ProcessResults {
+        private final String out;
+        private final String err;
+        private final int exitValue;
+        private final Throwable throwable;
+
+        public ProcessResults(String out,
+                              String err,
+                              int exitValue,
+                              Throwable throwable) {
+            this.out = out;
+            this.err = err;
+            this.exitValue = exitValue;
+            this.throwable = throwable;
+        }
+
+        public String out()          { return out; }
+        public String err()          { return err; }
+        public int exitValue()       { return exitValue; }
+        public Throwable throwable() { return throwable; }
+
+        public String toString() {
+            StringBuilder sb = new StringBuilder();
+            sb.append("<STDOUT>\n" + out() + "</STDOUT>\n")
+                .append("<STDERR>\n" + err() + "</STDERR>\n")
+                .append("exitValue = " + exitValue + "\n");
+            if (throwable != null)
+                sb.append(throwable.getStackTrace());
+            return sb.toString();
+        }
+    }
+
+    //--------------------- Infrastructure ---------------------------
+    static volatile int passed = 0, failed = 0;
+    static void pass() {passed++;}
+    static void fail() {failed++; Thread.dumpStack();}
+    static void fail(String msg) {System.out.println(msg); fail();}
+    static void unexpected(Throwable t) {failed++; t.printStackTrace();}
+    static void check(boolean cond) {if (cond) pass(); else fail();}
+    static void check(boolean cond, String m) {if (cond) pass(); else fail(m);}
+    static void equal(Object x, Object y) {
+        if (x == null ? y == null : x.equals(y)) pass();
+        else fail(x + " not equal to " + y);}
+    public static void main(String[] args) throws Throwable {
+        try {realMain(args);} catch (Throwable t) {unexpected(t);}
+        System.out.printf("%nPassed = %d, failed = %d%n%n", passed, failed);
+        if (failed > 0) throw new AssertionError("Some tests failed");}
+    private static abstract class Fun {abstract void f() throws Throwable;}
+    static void THROWS(Class<? extends Throwable> k, Fun... fs) {
+        for (Fun f : fs)
+            try { f.f(); fail("Expected " + k.getName() + " not thrown"); }
+            catch (Throwable t) {
+                if (k.isAssignableFrom(t.getClass())) pass();
+                else unexpected(t);}}
+}
diff --git a/jdk/test/java/lang/ProcessBuilder/FeelingLucky.java b/jdk/test/java/lang/ProcessBuilder/FeelingLucky.java
new file mode 100644
index 0000000..304e1be
--- /dev/null
+++ b/jdk/test/java/lang/ProcessBuilder/FeelingLucky.java
@@ -0,0 +1,78 @@
+/*
+ * Copyright 2006 Sun Microsystems, Inc.  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 Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
+ * CA 95054 USA or visit www.sun.com if you need additional information or
+ * have any questions.
+ */
+
+/*
+ * A test for
+ * 6469606: (process) Process.destroy() can kill wrong process (Unix)
+ * that is not suitable for use as a regression test, because it must
+ * create 32768 processes, and depends on perl.
+ */
+import java.io.*;
+
+public class FeelingLucky {
+
+    public static void main(String[] args) throws Throwable {
+        final Runtime rt = Runtime.getRuntime();
+        final String[] pidPrinter = {"/bin/sh", "-c", "echo $$"};
+        final Process minedProcess = rt.exec(pidPrinter);
+        int minedPid = 0;
+        final InputStream is = minedProcess.getInputStream();
+        int c;
+        while ((c = is.read()) >= '0' && c <= '9')
+            minedPid = 10 * minedPid + (c - '0');
+        System.out.printf("minedPid=%d%n", minedPid);
+        minedProcess.waitFor();
+
+        final String[] magnum = {
+            "perl", "-e",
+            "my $punk = getppid();" +
+            "open TTY, '> /dev/tty';" +
+            "print TTY \"punk=$punk\\n\";" +
+            "for (my $i = 0; $i < 32768; $i++) {" +
+            "  my $pid = fork();" +
+            "  if ($pid == 0) {" +
+            "    if ($$ == " + minedPid + ") {" +
+            "      print TTY \"MATCH $$ $punk\\n\";" +
+            "      $SIG{TERM} = sub {" +
+            "        print TTY \"Got TERM $$ $punk\\n\";" +
+            "        kill 9, $punk;" +
+            "        exit; };" +
+            "      $| = 1; print 'Go ahead.  Make my day.';" +
+            "      sleep 100;" +
+            "    }" +
+            "    exit;" +
+            "  } else { " +
+            "    waitpid($pid,0);" +
+            "    break if $pid == " + minedPid + ";" +
+            "  }" +
+            "}"
+        };
+
+        Process p = rt.exec(magnum);
+        if (p.getInputStream().read() != -1) {
+            System.out.println("got a char");
+            minedProcess.destroy();
+            Thread.sleep(1000);
+        }
+    }
+}
diff --git a/jdk/test/java/lang/ProcessBuilder/Zombies.java b/jdk/test/java/lang/ProcessBuilder/Zombies.java
new file mode 100644
index 0000000..e871896
--- /dev/null
+++ b/jdk/test/java/lang/ProcessBuilder/Zombies.java
@@ -0,0 +1,67 @@
+/*
+ * Copyright 2006 Sun Microsystems, Inc.  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 Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
+ * CA 95054 USA or visit www.sun.com if you need additional information or
+ * have any questions.
+ */
+
+/*
+ * @test
+ * @bug 6474073
+ * @summary Make sure zombies don't get created on Unix
+ * @author Martin Buchholz
+ */
+
+import java.io.*;
+
+public class Zombies {
+    public static void main(String[] args) throws Throwable {
+        if (! new File("/usr/bin/perl").canExecute() ||
+            ! new File("/bin/ps").canExecute())
+            return;
+        System.out.println("Looks like a Unix system.");
+        final Runtime rt = Runtime.getRuntime();
+
+        try {
+            rt.exec("no-such-file");
+            throw new Error("expected IOException not thrown");
+        } catch (IOException _) {/* OK */}
+
+        try {
+            rt.exec(".");
+            throw new Error("expected IOException not thrown");
+        } catch (IOException _) {/* OK */}
+
+        try {
+            rt.exec("/bin/true", null, new File("no-such-dir"));
+            throw new Error("expected IOException not thrown");
+        } catch (IOException _) {/* OK */}
+
+        rt.exec("/bin/true").waitFor();
+
+        // Count all the zombies that are children of this Java process
+        final String[] zombieCounter = {
+            "/usr/bin/perl", "-e",
+            "exit @{[`/bin/ps -eo ppid,s` =~ /^ *@{[getppid]} +Z$/mog]}"
+        };
+
+        int zombies = rt.exec(zombieCounter).waitFor();
+        if (zombies != 0) throw new Error(zombies + " zombies!");
+    }
+}
diff --git a/jdk/test/java/lang/Runtime/exec/ArgWithSpaceAndFinalBackslash.java b/jdk/test/java/lang/Runtime/exec/ArgWithSpaceAndFinalBackslash.java
new file mode 100644
index 0000000..24be7c1
--- /dev/null
+++ b/jdk/test/java/lang/Runtime/exec/ArgWithSpaceAndFinalBackslash.java
@@ -0,0 +1,76 @@
+/*
+ * Copyright 2003 Sun Microsystems, Inc.  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 Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
+ * CA 95054 USA or visit www.sun.com if you need additional information or
+ * have any questions.
+ */
+
+/* @test
+ * @bug 4794652
+ * @summary Ensure that a command argument that contains a space and a final
+ *          backslash is handled correctly
+ */
+
+import java.io.*;
+import java.util.*;
+
+
+public class ArgWithSpaceAndFinalBackslash {
+
+    private static String getJavaCommand() {
+        String javaHome = System.getProperty("java.home");
+        if (javaHome != null && javaHome.length() > 0)
+            return (javaHome
+                    + File.separatorChar + "bin"
+                    + File.separatorChar + "java");
+        else
+            return "java";
+    }
+
+    public static void main(String[] args) throws Exception {
+
+        if (args.length > 0) {
+            System.err.println(args[0]);
+            return;
+        }
+
+        String[] cmd = new String[5];
+        int i = 0;
+        cmd[i++] = getJavaCommand();
+        cmd[i++] = "-cp";
+        String cp = System.getProperty("test.classes");
+        if (cp == null)
+            cp = ".";
+        cmd[i++] = cp;
+        cmd[i++] = "ArgWithSpaceAndFinalBackslash";
+        cmd[i++] = "foo bar\\baz\\";
+
+        Process process = Runtime.getRuntime().exec(cmd);
+        InputStream in = process.getErrorStream();
+        byte[] buf = new byte[1024];
+        int n = 0, d;
+        while ((d = in.read(buf, n, buf.length - n)) >= 0)
+            n += d;
+        String s = new String(buf, 0, n, "US-ASCII").trim();
+        if (!s.equals(cmd[i - 1]))
+            throw new Exception("Test failed: Got \"" + s
+                                + "\", expected \"" + cmd[i - 1] + "\"");
+    }
+
+}
diff --git a/jdk/test/java/lang/Runtime/exec/BadEnvp.java b/jdk/test/java/lang/Runtime/exec/BadEnvp.java
new file mode 100644
index 0000000..2a7ad32
--- /dev/null
+++ b/jdk/test/java/lang/Runtime/exec/BadEnvp.java
@@ -0,0 +1,57 @@
+/*
+ * Copyright 2003 Sun Microsystems, Inc.  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 Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
+ * CA 95054 USA or visit www.sun.com if you need additional information or
+ * have any questions.
+ */
+
+/* @test
+   @bug 4925610
+   @summary Check for the appropriate exceptions when a bad envp is passed.
+   @author Martin Buchholz
+*/
+
+public class BadEnvp {
+
+    public static void main(String[] args) throws Exception {
+        Runtime r = Runtime.getRuntime();
+        java.io.File dir = new java.io.File(".");
+
+        String[] envpWithNull = {"FOO=BAR",null};
+        try {
+            r.exec("echo", envpWithNull);
+            throw new Exception("Expected NullPointerException not thrown");
+        } catch (NullPointerException e) {} // OK
+
+        try {
+            r.exec("echo", envpWithNull, dir);
+            throw new Exception("Expected NullPointerException not thrown");
+        } catch (NullPointerException e) {} // OK
+
+        try {
+            r.exec(new String[]{"echo"}, envpWithNull);
+            throw new Exception("Expected NullPointerException not thrown");
+        } catch (NullPointerException e) {} // OK
+
+        try {
+            r.exec(new String[]{"echo"}, envpWithNull, dir);
+            throw new Exception("Expected NullPointerException not thrown");
+        } catch (NullPointerException e) {} // OK
+    }
+}
diff --git a/jdk/test/java/lang/Runtime/exec/ConcurrentRead.java b/jdk/test/java/lang/Runtime/exec/ConcurrentRead.java
new file mode 100644
index 0000000..349d87b
--- /dev/null
+++ b/jdk/test/java/lang/Runtime/exec/ConcurrentRead.java
@@ -0,0 +1,78 @@
+/*
+ * Copyright 2002 Sun Microsystems, Inc.  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 Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
+ * CA 95054 USA or visit www.sun.com if you need additional information or
+ * have any questions.
+ */
+
+/**
+ * @test
+ * @bug 4619744
+ * @summary Test that Process input/out can be concurrently read/written
+ * @author kladko
+ */
+
+import java.io.InputStream;
+import java.io.OutputStream;
+import java.io.File;
+import java.io.IOException;
+
+public class ConcurrentRead {
+
+    static volatile Exception savedException;
+    static final String TEE = "/usr/bin/tee";
+
+    public static void main(String[] args) throws Exception {
+
+        if (File.separatorChar == '\\' ||                // Windows
+                                !new File(TEE).exists()) // no tee
+            return;
+
+        Process p = Runtime.getRuntime().exec(TEE);
+        OutputStream out = p.getOutputStream();
+        InputStream in = p.getInputStream();
+        Thread t1 = new WriterThread(out, in);
+        t1.start();
+        Thread t2 = new WriterThread(out, in);
+        t2.start();
+        t1.join();
+        t2.join();
+        if (savedException != null)
+            throw savedException;
+    }
+
+    static class WriterThread extends Thread {
+        OutputStream out;
+        InputStream in;
+        WriterThread(OutputStream out, InputStream in) {
+            this.out = out;
+            this.in = in;
+        }
+        public void run(){
+            try {
+                out.write('a');
+                out.flush();
+                if (in.read() == -1) // got end-of-stream
+                    throw new Exception("End of stream in writer thread");
+            } catch (Exception e) {
+                savedException = e;
+            }
+        }
+    }
+}
diff --git a/jdk/test/java/lang/Runtime/exec/Duped.java b/jdk/test/java/lang/Runtime/exec/Duped.java
new file mode 100644
index 0000000..ee41ea3
--- /dev/null
+++ b/jdk/test/java/lang/Runtime/exec/Duped.java
@@ -0,0 +1,89 @@
+/*
+ * Copyright 1999-2001 Sun Microsystems, Inc.  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 Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
+ * CA 95054 USA or visit www.sun.com if you need additional information or
+ * have any questions.
+ */
+
+/* @test
+   @bug 4180429
+   @summary Lossage in dup2 if System.in is closed.
+   @run main/othervm Duped
+ */
+
+import java.io.BufferedReader;
+import java.io.PrintStream;
+import java.io.InputStreamReader;
+import java.io.File;
+
+public class Duped {
+
+    public static class Echo {
+        public static void main(String args[]) throws Exception {
+            StringBuffer s = new StringBuffer();
+            int c;
+            while ((System.in.available() != 0)
+                           && ((c = System.in.read()) != -1))
+                s.append((char)c);
+            System.out.println(s);
+        }
+    }
+
+    public static void main(String[] args) throws Exception {
+
+        String command =
+            System.getProperty("java.home") +
+            File.separator +
+            "bin" +
+            File.separator +
+            "java -classpath " +
+            System.getProperty("java.class.path") +
+            " Duped$Echo";
+
+        if (args.length == 1 && args[0].equals("-dont")) {
+            /*
+             * To quickly check that this test is working when it is
+             * supposed to, just run it with -dont and it shouldn't
+             * complain at all.
+             */
+        } else {
+            /*
+             * In normal runs we just close in, and that causes
+             * lossage on fork.
+             */
+            System.in.close();
+        }
+
+        Process p = Runtime.getRuntime().exec(command);
+        PrintStream out = new PrintStream(p.getOutputStream());
+        out.println(HELLO);
+        out.close();
+
+        BufferedReader in =
+            new BufferedReader(new InputStreamReader(p.getInputStream()));
+        String read = in.readLine();
+
+        if (!HELLO.equals(read)) {
+            throw new Exception("Failed, read ``" + read + "''");
+        }
+    }
+
+    static final String HELLO = "Hello, world!";
+
+}
diff --git a/jdk/test/java/lang/Runtime/exec/ExecEmptyString.java b/jdk/test/java/lang/Runtime/exec/ExecEmptyString.java
new file mode 100644
index 0000000..b006073
--- /dev/null
+++ b/jdk/test/java/lang/Runtime/exec/ExecEmptyString.java
@@ -0,0 +1,42 @@
+/*
+ * Copyright 2001-2003 Sun Microsystems, Inc.  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 Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
+ * CA 95054 USA or visit www.sun.com if you need additional information or
+ * have any questions.
+ */
+
+/* @test
+   @bug 4248426 4766029
+   @author Konstantin Kladko
+*/
+
+public class ExecEmptyString {
+
+    public static void main(String[] args) throws Exception {
+        try {
+            Runtime.getRuntime().exec("");
+            throw new Exception("Expected IllegalArgumentException not thrown");
+        } catch (IllegalArgumentException e) {} // OK
+
+        try {
+            Runtime.getRuntime().exec(new String());
+            throw new Exception("Expected IllegalArgumentException not thrown");
+        } catch (IllegalArgumentException e) {} // OK
+    }
+}
diff --git a/jdk/test/java/lang/Runtime/exec/ExecWithDir.java b/jdk/test/java/lang/Runtime/exec/ExecWithDir.java
new file mode 100644
index 0000000..2f36e75
--- /dev/null
+++ b/jdk/test/java/lang/Runtime/exec/ExecWithDir.java
@@ -0,0 +1,56 @@
+/*
+ * Copyright 2002-2007 Sun Microsystems, Inc.  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 Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
+ * CA 95054 USA or visit www.sun.com if you need additional information or
+ * have any questions.
+ */
+
+/* @test
+ * @bug 4750978
+ * @summary Ensure that we can fork-and-exec repeatedly when a new working
+ *          directory is specified
+ */
+
+import java.io.*;
+
+public class ExecWithDir {
+
+    private static final String CMD = "/bin/true";
+    private static final int N = 500;
+
+    public static void main(String args[]) throws Exception {
+        if (! new File(CMD).canExecute())
+            return;
+        File dir = new File(".");
+        for (int i = 1; i <= N; i++) {
+            System.out.print(i);
+            System.out.print(" e");
+            Process p = Runtime.getRuntime().exec(CMD, null, dir);
+            System.out.print('w');
+            int s = p.waitFor();
+            System.out.println("x " + s);
+            if (s != 0) throw new Error("Unexpected return code " + s);
+
+            // Avoid "Too many open files"
+            p.getInputStream().close();
+            p.getOutputStream().close();
+            p.getErrorStream().close();
+        }
+    }
+}
diff --git a/jdk/test/java/lang/Runtime/exec/ExecWithInput.java b/jdk/test/java/lang/Runtime/exec/ExecWithInput.java
new file mode 100644
index 0000000..4ee815a
--- /dev/null
+++ b/jdk/test/java/lang/Runtime/exec/ExecWithInput.java
@@ -0,0 +1,127 @@
+/*
+ * Copyright 2002 Sun Microsystems, Inc.  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 Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
+ * CA 95054 USA or visit www.sun.com if you need additional information or
+ * have any questions.
+ */
+
+/* @test
+ * @bug 4763384
+ * @summary Ensure that piped input always works with exec'd processes
+ */
+
+import java.io.*;
+
+
+/**
+ * This class demonstrates a regression in java1.4.1 in the handling of the
+ * Process OutputStream (exec'd process stdin).  The subprocess completes 100%
+ * of the time in 1.4, but about only about 50% of the time under 1.4.1.  Issue
+ * exists for client JVM, Linux Redhat 6.2 not sure about other variants of
+ * Linux or other OSes, or server JVM.
+ */
+
+public class ExecWithInput {
+
+    private static final String CAT = "/bin/cat";
+    private static final int N = 200;
+
+    static int go(int i) throws Exception {
+        /*
+         * Execute /bin/cat supplying two lines of input. cat should
+         * read the input lines and copy them to stdout. On completion,
+         * p.waitFor should return and the exit status is printed and this
+         * program exits. Under 1.4.1, cat sometimes gets stuck on a pipe
+         * read and never terminates.
+         */
+        //Process p = Runtime.getRuntime().exec(new String[] { CAT } );
+        Process p = Runtime.getRuntime().exec(CAT);
+
+        String input = i + ": line 1\n" + i + ": line 2\n";
+        StringBufferInputStream in = new StringBufferInputStream(input);
+        // create threads to handle I/O streams
+        IO ioIn = new IO("stdin", in, p.getOutputStream());
+        IO ioOut = new IO("stdout", p.getInputStream(), System.out);
+        IO ioErr = new IO("stderr", p.getErrorStream(), System.err);
+
+        // wait for process to exit
+        return p.waitFor();
+    }
+
+    public static void main(String[] args) throws Exception {
+        if (!System.getProperty("os.name").equals("Linux"))
+            return;
+        if (File.separatorChar == '\\') {
+            // no /bin/cat on windows
+            return;
+        }
+        for (int i = 0; i < N; i++)
+            go(i);
+    }
+
+    /**
+     * Handle IO. Thread is started in constructor.
+     */
+    static class IO extends Thread {
+
+        private InputStream in;
+        private OutputStream out;
+
+        IO(String name, InputStream in, OutputStream out)
+        {
+            this.in = in;
+            this.out = out;
+            setName(name);
+            start();
+        }
+
+        public void run() {
+            try {
+                int c;
+                byte[] buf = new byte[8192];
+                int n;
+                while ((n = in.read(buf)) != -1) {
+                    out.write(buf, 0, n);
+                    out.flush();
+                }
+                /*
+                while ((c = in.read()) != -1) {
+                    out.write(c);
+                    if (c == '\n')
+                        out.flush();
+                }
+                out.flush();
+                */
+            } catch (IOException e) {
+                e.printStackTrace();
+            } finally {
+                if (!System.out.equals(out) && !System.err.equals(out)) {
+                    // Note: in order to get an exec'd java process to
+                    // see EOF on input, it is necessary to close stdin
+                    if (out != null) {
+                        try { out.close(); } catch (Exception e) {
+                            e.printStackTrace();
+                        }
+                    }
+                }
+            }
+        }
+    }
+
+}
diff --git a/jdk/test/java/lang/Runtime/exec/ExecWithLotsOfArgs.java b/jdk/test/java/lang/Runtime/exec/ExecWithLotsOfArgs.java
new file mode 100644
index 0000000..4366c6a
--- /dev/null
+++ b/jdk/test/java/lang/Runtime/exec/ExecWithLotsOfArgs.java
@@ -0,0 +1,117 @@
+/*
+ * Copyright 1997 Sun Microsystems, Inc.  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 Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
+ * CA 95054 USA or visit www.sun.com if you need additional information or
+ * have any questions.
+ */
+
+/* @test
+   @bug 4033560
+   @summary 4033560 limited args of exec to 198 on Solaris. We check
+            that we can actually exec more args than that.
+   @author Anand Palaniswamy
+   @run main/othervm ExecWithLotsOfArgs
+*/
+
+import java.io.BufferedReader;
+import java.io.InputStreamReader;
+import java.io.File;
+import java.io.IOException;
+
+public class ExecWithLotsOfArgs {
+
+    public static class EchoingHelper {
+        public static void main(String[] args) {
+            for (int i = 0; i < args.length; i++) {
+                System.out.println(args[i]);
+            }
+        }
+    }
+
+    public static void main(String[] args) throws Exception {
+        String[] command = new String[300];
+        int n = 0;
+
+        /*
+         * The Java program to exec. This is slightly fragile. Works
+         * on Solaris and Win32.
+         */
+        command[n++] = System.getProperty("java.home") + File.separator +
+            "bin" + File.separator + "java";
+        if (System.getProperty("java.class.path") != null) {
+            command[n++] = "-classpath";
+            command[n++] = System.getProperty("java.class.path");
+        }
+
+        /*
+         * The class with main() that the exec'd VM will run.
+         */
+        command[n++] = "ExecWithLotsOfArgs$EchoingHelper";
+
+        /*
+         * Make a long set of args n, n + 1, ... , 300.
+         */
+        for (int i = n; i < command.length; i++) {
+            command[i] = new String(new Integer(i).toString());
+        }
+
+        /*
+         * Do the exec.
+         */
+        Process p = null;
+        p = Runtime.getRuntime().exec(command);
+        BufferedReader in = new BufferedReader
+            (new InputStreamReader(p.getInputStream()));
+
+        /*
+         * Read back all the strings and that the same were returned.
+         */
+        String s;
+        int count = n;
+        while ((s = in.readLine()) != null) {
+            if (count >= command.length) {
+                failed("Was expecting " + (command.length - 2) +
+                       " strings to be echo'ed back, but got " +
+                       (count - 1) + " instead");
+            }
+            if (!s.equals(command[count])) {
+                failed("Exec'd process returned \"" +
+                       s + "\", was expecting \""  +
+                       command[count] + "\"");
+            }
+            count++;
+        }
+
+        /*
+         * Did we read anything at all?
+         */
+        if (count == n) {
+            /* Try reading the error stream to see if we got any diagnostics */
+            in = new BufferedReader(new InputStreamReader(p.getErrorStream()));
+            while ((s = in.readLine()) != null) {
+                System.err.println("Error output: " + s);
+            }
+            failed("Exec'd process didn't writing anything to its stdout");
+        }
+    }
+
+    private static void failed(String s) {
+        throw new RuntimeException("Failed: " + s);
+    }
+}
diff --git a/jdk/test/java/lang/Runtime/exec/ExitValue.java b/jdk/test/java/lang/Runtime/exec/ExitValue.java
new file mode 100644
index 0000000..db6b82a
--- /dev/null
+++ b/jdk/test/java/lang/Runtime/exec/ExitValue.java
@@ -0,0 +1,106 @@
+/*
+ * Copyright 2002-2007 Sun Microsystems, Inc.  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 Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
+ * CA 95054 USA or visit www.sun.com if you need additional information or
+ * have any questions.
+ */
+
+/*
+ * @test
+ * @bug 4680945 4873419
+ * @summary Check process exit code
+ * @author kladko, Martin Buchholz
+ */
+
+import java.io.File;
+
+public class ExitValue
+{
+
+    public static String join(String separator, String[] elts) {
+        String result = elts[0];
+        for (int i = 1; i < elts.length; ++i)
+            result = result + separator + elts[i];
+        return result;
+    }
+
+    public static void checkExitValue(String[] commandArgs,
+                                      int expectedExitValue)
+        throws Exception
+    {
+        if (! (new File(commandArgs[0]).exists()))
+            return;
+
+        System.out.println("Running command: " + join(" ", commandArgs));
+        Process proc = Runtime.getRuntime().exec(commandArgs);
+        int val;
+        byte[] buf = new byte[4096];
+        int n = proc.getErrorStream().read(buf);
+        if (n > 0)
+            throw new Exception
+                ("Unexpected stderr: "
+                 + new String(buf, 0, n, "ASCII"));
+        if ((val = proc.waitFor()) != expectedExitValue)
+            throw new Exception
+                ("waitFor() returned unexpected value " + val);
+        if ((val = proc.exitValue()) != expectedExitValue)
+            throw new Exception
+                ("exitValue() returned unexpected value " + val);
+    }
+
+    public static void checkPosixShellExitValue(String posixShellProgram,
+                                                int expectedExitValue)
+        throws Exception
+    {
+        checkExitValue(new String[] { "/bin/sh", "-c", posixShellProgram },
+                       expectedExitValue);
+    }
+
+    final static int EXIT_CODE = 5;
+
+    public static void main(String[] args) throws Exception {
+
+        String java = join(File.separator, new String []
+            { System.getProperty("java.home"), "bin", "java" });
+
+        checkExitValue(new String[]
+            { java,
+              "-classpath", System.getProperty("test.classes", "."),
+              "ExitValue$Run", String.valueOf(EXIT_CODE)
+            }, EXIT_CODE);
+
+        checkExitValue(new String[] { "/bin/true" }, 0);
+
+        checkPosixShellExitValue("exit", 0);
+
+        checkPosixShellExitValue("exit 7", 7);
+
+        if (new File("/bin/kill").exists()) {
+            int sigoffset =
+                System.getProperty("os.name").equals("SunOS") ? 0 : 128;
+            checkPosixShellExitValue("/bin/kill -9 $$", sigoffset+9);
+        }
+    }
+
+    public static class Run {
+        public static void main (String[] argv) {
+            System.exit(Integer.parseInt(argv[0]));
+        }
+    }
+}
diff --git a/jdk/test/java/lang/Runtime/exec/LotsOfDestroys.java b/jdk/test/java/lang/Runtime/exec/LotsOfDestroys.java
new file mode 100644
index 0000000..f08e3b1
--- /dev/null
+++ b/jdk/test/java/lang/Runtime/exec/LotsOfDestroys.java
@@ -0,0 +1,47 @@
+/*
+ * Copyright 2002 Sun Microsystems, Inc.  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 Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
+ * CA 95054 USA or visit www.sun.com if you need additional information or
+ * have any questions.
+ */
+
+/**
+ * @test
+ * @bug 4637504 4653814
+ * @summary Destroy should close stderr, stdout and stdin
+ * @author kladko
+ */
+
+import java.io.File;
+
+public class LotsOfDestroys {
+    static final int RUNS = 400;
+    static final String ECHO = "/usr/bin/echo";
+
+    public static void main(String[] args) throws Exception {
+        if (File.separatorChar == '\\' ||                // Windows
+                                !new File(ECHO).exists()) // no echo
+            return;
+
+        for (int i = 0; i<= RUNS; i++) {
+            Process process = Runtime.getRuntime().exec(ECHO + " x");
+            process.destroy();
+        }
+    }
+}
diff --git a/jdk/test/java/lang/Runtime/exec/LotsOfOutput.java b/jdk/test/java/lang/Runtime/exec/LotsOfOutput.java
new file mode 100644
index 0000000..3af1ccd
--- /dev/null
+++ b/jdk/test/java/lang/Runtime/exec/LotsOfOutput.java
@@ -0,0 +1,49 @@
+/*
+ * Copyright 2002 Sun Microsystems, Inc.  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 Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
+ * CA 95054 USA or visit www.sun.com if you need additional information or
+ * have any questions.
+ */
+
+/**
+ * @test
+ * @bug 4369826
+ * @summary Process with lots of output should not crash VM
+ * @author kladko
+ */
+
+import java.io.File;
+
+public class LotsOfOutput {
+    static final String CAT = "/usr/bin/cat";
+
+    public static void main(String[] args) throws Exception{
+        if (File.separatorChar == '\\' ||                // Windows
+                                !new File(CAT).exists()) // no cat
+            return;
+        Process p = Runtime.getRuntime().exec(CAT + " /dev/zero");
+        long initMemory = Runtime.getRuntime().totalMemory();
+        for (int i=1; i< 10; i++) {
+            Thread.sleep(100);
+            if (Runtime.getRuntime().totalMemory() > initMemory + 1000000)
+                throw new Exception("Process consumes memory.");
+        }
+
+    }
+}
diff --git a/jdk/test/java/lang/Runtime/exec/SetCwd.java b/jdk/test/java/lang/Runtime/exec/SetCwd.java
new file mode 100644
index 0000000..c07eb3e
--- /dev/null
+++ b/jdk/test/java/lang/Runtime/exec/SetCwd.java
@@ -0,0 +1,79 @@
+/*
+ * Copyright 1999 Sun Microsystems, Inc.  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 Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
+ * CA 95054 USA or visit www.sun.com if you need additional information or
+ * have any questions.
+ */
+
+/*
+ * @test
+ * @bug 4156278
+ * @summary Basic functional test for
+ *          Runtime.exec(String[] command, String[] env, File path) and
+ *          Runtime.exec(String command, String[] env, File path).
+ *
+ * @build SetCwd
+ * @run shell setcwd.sh
+ */
+import java.io.*;
+
+public class SetCwd {
+    public static void testExec(String cmd, String[] cmdarray, boolean flag)
+        throws Exception {
+        File dir = new File(".");
+        File[] files = dir.listFiles();
+        String curDir = dir.getCanonicalPath();
+
+        for (int i = 0; i < files.length; i++) {
+            File f = files[i];
+            if (f.isDirectory() && (new File(f, "SetCwd.class")).exists()) {
+                String newDir = f.getCanonicalPath();
+                // exec a new SetCwd in the sub directory
+                Process p = null;
+                if (flag) {
+                    p = Runtime.getRuntime().exec(cmd, null, f);
+                } else {
+                    p = Runtime.getRuntime().exec(cmdarray, null, f);
+                }
+
+                BufferedReader in = new BufferedReader
+                    (new InputStreamReader(p.getInputStream()));
+                // Read back output from child
+                String s = in.readLine();
+                if (!s.startsWith(newDir)) {
+                    throw new Exception("inconsistent directory after exec");
+                }
+                // Join on the child
+                p.waitFor();
+            }
+        }
+        System.out.println(curDir);
+    }
+
+    public static void main (String args[]) throws Exception {
+        String cmdarray[] = new String[2];
+        cmdarray[0] = System.getProperty("java.home") + File.separator +
+            "bin" + File.separator + "java";
+        cmdarray[1] = "SetCwd";
+        String cmd = cmdarray[0] + " " + cmdarray[1];
+        // test the two new methods
+        testExec(cmd, null, true);
+        testExec(null, cmdarray, false);
+    }
+}
diff --git a/jdk/test/java/lang/Runtime/exec/SleepyCat.java b/jdk/test/java/lang/Runtime/exec/SleepyCat.java
new file mode 100644
index 0000000..b107c12
--- /dev/null
+++ b/jdk/test/java/lang/Runtime/exec/SleepyCat.java
@@ -0,0 +1,164 @@
+/*
+ * Copyright 2003 Sun Microsystems, Inc.  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 Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
+ * CA 95054 USA or visit www.sun.com if you need additional information or
+ * have any questions.
+ */
+
+/* @test
+   @bug 4843136 4763384
+   @summary Various race conditions caused exec'ed processes to have
+   extra unused file descriptors, which caused hard-to-reproduce hangs.
+   @author Martin Buchholz
+*/
+
+import java.util.Timer;
+import java.util.TimerTask;
+import java.io.IOException;
+
+public class SleepyCat {
+
+    private static void destroy (Process[] deathRow) {
+        for (int i = 0; i < deathRow.length; ++i)
+            if (deathRow[i] != null)
+                deathRow[i].destroy();
+    }
+
+    static class TimeoutTask extends TimerTask {
+        private Process[] deathRow;
+        private boolean timedOut;
+
+        TimeoutTask (Process[] deathRow) {
+            this.deathRow = deathRow;
+            this.timedOut = false;
+        }
+
+        public void run() {
+            timedOut = true;
+            destroy(deathRow);
+        }
+
+        public boolean timedOut() {
+            return timedOut;
+        }
+    }
+
+    private static boolean hang1() throws IOException, InterruptedException {
+        // Time out was reproducible on Solaris 50% of the time;
+        // on Linux 80% of the time.
+        //
+        // Scenario: After fork(), parent executes and closes write end of child's stdin.
+        // This causes child to retain a write end of the same pipe.
+        // Thus the child will never see an EOF on its stdin, and will hang.
+        Runtime rt = Runtime.getRuntime();
+        // Increasing the iteration count makes the bug more
+        // reproducible not only for the obvious reason, but also for
+        // the subtle reason that it makes reading /proc/getppid()/fd
+        // slower, making the child more likely to win the race!
+        int iterations = 20;
+        int timeout = 30;
+        String[] catArgs   = new String[] {"/bin/cat"};
+        String[] sleepArgs = new String[] {"/bin/sleep",
+                                            String.valueOf(timeout+1)};
+        Process[] cats   = new Process[iterations];
+        Process[] sleeps = new Process[iterations];
+        Timer timer = new Timer(true);
+        TimeoutTask catExecutioner = new TimeoutTask(cats);
+        timer.schedule(catExecutioner, timeout * 1000);
+
+        for (int i = 0; i < cats.length; ++i) {
+            cats[i] = rt.exec(catArgs);
+            java.io.OutputStream s = cats[i].getOutputStream();
+            Process sleep = rt.exec(sleepArgs);
+            s.close(); // race condition here
+            sleeps[i] = sleep;
+        }
+
+        for (int i = 0; i < cats.length; ++i)
+            cats[i].waitFor(); // hangs?
+
+        timer.cancel();
+
+        destroy(sleeps);
+
+        if (catExecutioner.timedOut())
+            System.out.println("Child process has a hidden writable pipe fd for its stdin.");
+        return catExecutioner.timedOut();
+    }
+
+    private static boolean hang2() throws Exception {
+        // Inspired by the imaginative test case for
+        // 4850368 (process) getInputStream() attaches to forked background processes (Linux)
+
+        // Time out was reproducible on Linux 80% of the time;
+        // never on Solaris because of explicit close in Solaris-specific code.
+
+        // Scenario: After fork(), the parent naturally closes the
+        // child's stdout write end.  The child dup2's the write end
+        // of its stdout onto fd 1.  On Linux, it fails to explicitly
+        // close the original fd, and because of the parent's close()
+        // of the fd, the child retains it.  The child thus ends up
+        // with two copies of its stdout.  Thus closing one of those
+        // write fds does not have the desired effect of causing an
+        // EOF on the parent's read end of that pipe.
+        Runtime rt = Runtime.getRuntime();
+        int iterations = 10;
+        Timer timer = new Timer(true);
+        int timeout = 30;
+        Process[] backgroundSleepers = new Process[iterations];
+        TimeoutTask sleeperExecutioner = new TimeoutTask(backgroundSleepers);
+        timer.schedule(sleeperExecutioner, timeout * 1000);
+        byte[] buffer = new byte[10];
+        String[] args =
+            new String[] {"/bin/sh", "-c",
+                          "exec sleep " + (timeout+1) + " >/dev/null"};
+
+        for (int i = 0;
+             i < backgroundSleepers.length && !sleeperExecutioner.timedOut();
+             ++i) {
+            backgroundSleepers[i] = rt.exec(args); // race condition here
+            try {
+                // should get immediate EOF, but might hang
+                if (backgroundSleepers[i].getInputStream().read() != -1)
+                    throw new Exception("Expected EOF, got a byte");
+            } catch (IOException e) {
+                // Stream closed by sleeperExecutioner
+                break;
+            }
+        }
+
+        timer.cancel();
+
+        destroy(backgroundSleepers);
+
+        if (sleeperExecutioner.timedOut())
+            System.out.println("Child process has two (should be one) writable pipe fds for its stdout.");
+        return sleeperExecutioner.timedOut();
+    }
+
+    public static void main (String[] args) throws Exception {
+        try {
+            if (hang1() | hang2())
+                throw new Exception("Read from closed pipe hangs");
+        } catch (IOException e) {
+            // We will get here on non-Posix systems,
+            // which don't have cat and sleep and sh.
+        }
+    }
+}
diff --git a/jdk/test/java/lang/Runtime/exec/Space.java b/jdk/test/java/lang/Runtime/exec/Space.java
new file mode 100644
index 0000000..cbcee84
--- /dev/null
+++ b/jdk/test/java/lang/Runtime/exec/Space.java
@@ -0,0 +1,47 @@
+/*
+ * Copyright 1999-2001 Sun Microsystems, Inc.  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 Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
+ * CA 95054 USA or visit www.sun.com if you need additional information or
+ * have any questions.
+ */
+
+/* @test 1.4 00/10/18
+   @bug 4231349
+   @summary test runtime.exec on windows for extra space in cmd
+ */
+import java.io.*;
+
+public class Space {
+    public static void main(String[] args) throws Exception {
+        if (File.separatorChar == '\\') {
+            try {
+            Process p = Runtime.getRuntime().exec( "cmd /c echo hello" );
+            BufferedReader reader = new BufferedReader(
+                                    new InputStreamReader(p.getInputStream()));
+            p.waitFor();
+            String echo = reader.readLine();
+            if (echo.length() == 6)
+                throw new RuntimeException("Extra space in command.");
+            } catch (IOException e) {
+            // not Win NT - cmd doesnt exist
+            return;
+            }
+        }
+    }
+}
diff --git a/jdk/test/java/lang/Runtime/exec/Status.java b/jdk/test/java/lang/Runtime/exec/Status.java
new file mode 100644
index 0000000..b4ed60a
--- /dev/null
+++ b/jdk/test/java/lang/Runtime/exec/Status.java
@@ -0,0 +1,53 @@
+/*
+ * Copyright 2002 Sun Microsystems, Inc.  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 Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
+ * CA 95054 USA or visit www.sun.com if you need additional information or
+ * have any questions.
+ */
+
+/* @test
+ * @bug 4763362
+ * @summary Ensure that Process.waitFor returns the correct status code
+ *          even for very short-running subprocesses
+ */
+
+
+public class Status {
+
+    private static int N = 160;
+
+    public static void main(String args[])
+        throws Exception
+    {
+        if (!System.getProperty("os.name").equals("Linux"))
+            return;
+        for (int i = 0; i < N; i++) {
+            Process p = Runtime.getRuntime().exec("false");
+            int s = p.waitFor();
+            System.out.print(s);
+            System.out.print(' ');
+            if (s != 1) {
+                System.out.println();
+                throw new Exception("Wrong status");
+            }
+        }
+        System.out.println();
+    }
+
+}
diff --git a/jdk/test/java/lang/Runtime/exec/StreamsSurviveDestroy.java b/jdk/test/java/lang/Runtime/exec/StreamsSurviveDestroy.java
new file mode 100644
index 0000000..d510bc9
--- /dev/null
+++ b/jdk/test/java/lang/Runtime/exec/StreamsSurviveDestroy.java
@@ -0,0 +1,182 @@
+/*
+ * Copyright 2003 Sun Microsystems, Inc.  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 Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
+ * CA 95054 USA or visit www.sun.com if you need additional information or
+ * have any questions.
+ */
+
+/* @test
+ * @bug 4820217
+ * @summary Ensure that pending reads on stdout and stderr streams
+ *          return -1 when the process is destroyed
+ */
+
+import java.io.*;
+
+
+public class StreamsSurviveDestroy {
+
+    private static class Copier extends Thread {
+
+        String name;
+        InputStream in;
+        OutputStream out;
+        boolean wantInterrupt;
+        boolean acceptException;
+        Exception exc = null;
+
+        Copier(String name, InputStream in, OutputStream out,
+               boolean ae, boolean wi)
+        {
+            this.name = name;
+            this.in = in;
+            this.out = out;
+            this.acceptException = ae;
+            this.wantInterrupt = wi;
+            setName(name);
+            start();
+        }
+
+        private void log(String s) {
+            System.err.println("  " + name + ": " + s);
+        }
+
+        public void run() {
+            byte[] buf = new byte[4242];
+            for (;;) {
+                try {
+                    int n = in.read(buf);
+                    if (n < 0) {
+                        System.err.println("  EOF");
+                        break;
+                    }
+                    out.write(buf, 0, n);
+                } catch (IOException x) {
+                    if (wantInterrupt) {
+                        if (x instanceof InterruptedIOException) {
+                            log("Interrupted as expected");
+                            return;
+                        }
+                        exc = new Exception(name
+                                            + ": Not interrupted as expected");
+                        return;
+                    }
+                    exc = x;
+                    if (acceptException) {
+                        log("Thrown, but okay: " + x);
+                        return;
+                    }
+                    return;
+                }
+            }
+        }
+
+        public void check() throws Exception {
+            if (!acceptException && exc != null)
+                throw new Exception(name + ": Exception thrown", exc);
+        }
+
+    }
+
+    static void test() throws Exception {
+        System.err.println("test");
+        Process p = Runtime.getRuntime().exec("/bin/cat");
+        Copier cp1 = new Copier("out", p.getInputStream(), System.err,
+                               false, false);
+        Copier cp2 = new Copier("err", p.getErrorStream(), System.err,
+                               false, false);
+        Thread.sleep(100);
+        p.destroy();
+        System.err.println("  exit: " + p.waitFor());
+        cp1.join();
+        cp1.check();
+        cp2.join();
+        cp2.check();
+    }
+
+    static void testCloseBeforeDestroy() throws Exception {
+        System.err.println("testCloseBeforeDestroy");
+        Process p = Runtime.getRuntime().exec("/bin/cat");
+        Copier cp1 = new Copier("out", p.getInputStream(), System.err,
+                                true, false);
+        Copier cp2 = new Copier("err", p.getErrorStream(), System.err,
+                                true, false);
+        Thread.sleep(100);
+        p.getInputStream().close();
+        p.getErrorStream().close();
+        p.destroy();
+        System.err.println("  exit: " + p.waitFor());
+        cp1.join();
+        cp1.check();
+        cp2.join();
+        cp2.check();
+    }
+
+    static void testCloseAfterDestroy() throws Exception {
+        System.err.println("testCloseAfterDestroy");
+        Process p = Runtime.getRuntime().exec("/bin/cat");
+        Copier cp1 = new Copier("out", p.getInputStream(), System.err,
+                                true, false);
+        Copier cp2 = new Copier("err", p.getErrorStream(), System.err,
+                                true, false);
+        Thread.sleep(100);
+        p.destroy();
+        p.getInputStream().close();
+        p.getErrorStream().close();
+        System.err.println("  exit: " + p.waitFor());
+        cp1.join();
+        cp1.check();
+        cp2.join();
+        cp2.check();
+    }
+
+    static void testInterrupt() throws Exception {
+        System.err.println("testInterrupt");
+        Process p = Runtime.getRuntime().exec("/bin/cat");
+        Copier cp1 = new Copier("out", p.getInputStream(), System.err,
+                                false, true);
+        Copier cp2 = new Copier("err", p.getErrorStream(), System.err,
+                                false, true);
+        Thread.sleep(100);
+        cp1.interrupt();
+        cp2.interrupt();
+        Thread.sleep(100);
+        p.destroy();
+        System.err.println("  exit: " + p.waitFor());
+        cp1.join();
+        cp1.check();
+        cp2.join();
+        cp2.check();
+    }
+
+    public static void main(String[] args) throws Exception {
+
+        // Applies only to Solaris; Linux and Windows
+        // behave a little differently
+        if (!System.getProperty("os.name").equals("SunOS"))
+            return;
+
+        test();
+        testCloseBeforeDestroy();
+        testCloseAfterDestroy();
+        testInterrupt();
+
+    }
+
+}
diff --git a/jdk/test/java/lang/Runtime/exec/WinCommand.java b/jdk/test/java/lang/Runtime/exec/WinCommand.java
new file mode 100644
index 0000000..37e17a1
--- /dev/null
+++ b/jdk/test/java/lang/Runtime/exec/WinCommand.java
@@ -0,0 +1,186 @@
+/*
+ * Copyright 2004 Sun Microsystems, Inc.  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 Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
+ * CA 95054 USA or visit www.sun.com if you need additional information or
+ * have any questions.
+ */
+
+/* @test
+ * @bug 5006520
+ * @summary Check many different ways to run Windows programs
+ * @author Martin Buchholz
+ *
+ * @compile -source 1.5 WinCommand.java
+ * @run main WinCommand
+ */
+
+import java.io.*;
+import java.util.*;
+import static java.lang.System.*;
+
+class StreamDrainer extends Thread {
+    private final InputStream is;
+    private final ByteArrayOutputStream os = new ByteArrayOutputStream();
+    public StreamDrainer(InputStream is) { this.is = is; }
+    public void run() {
+        try {
+            int i;
+            while ((i = is.read()) >= 0)
+                os.write(i);
+        } catch (Exception e) {}
+    }
+    public String toString() { return os.toString(); }
+}
+
+class CommandRunner {
+    private static Random generator = new Random();
+    public final int exitValue;
+    public final String out;
+    public final String err;
+    CommandRunner(String... args) throws Exception {
+        Process p = (generator.nextInt(2) == 0)
+            ? new ProcessBuilder(args).start()
+            : Runtime.getRuntime().exec(args);
+        StreamDrainer d1 = new StreamDrainer(p.getInputStream());
+        StreamDrainer d2 = new StreamDrainer(p.getErrorStream());
+        d1.start();
+        d2.start();
+        p.waitFor();
+        d1.join();
+        d2.join();
+        this.exitValue = p.exitValue();
+        this.out = d1.toString();
+        this.err = d2.toString();
+    }
+}
+
+public class WinCommand {
+    private static int failed = 0;
+
+    private static void fail(String msg) {
+        err.printf("FAIL: %s%n", msg);
+        failed++;
+    }
+
+    private static String outputOf(String... args) {
+        try {
+            CommandRunner cr = new CommandRunner(args);
+            if (cr.exitValue != 0)
+                fail("exitValue != 0");
+            if (! cr.err.equals(""))
+                fail("stderr: " + cr.err);
+            return cr.out.replaceFirst("[\r\n]+$", "");
+        } catch (Exception e) {
+            fail(e.toString());
+            return "";
+        }
+    }
+
+    private static void checkCD(String... filespecs) {
+        String firstCD = null;
+        for (String filespec : filespecs) {
+            String CD = outputOf(filespec, "/C", "CD");
+            out.printf("%s CD ==> %s%n", filespec, CD);
+            if (firstCD == null) {
+                firstCD = CD;
+                checkDir(CD);
+            }
+            if (! CD.equals(firstCD)) {
+                fail("Inconsistent result from CD subcommand");
+                checkDir(CD);
+            }
+        }
+    }
+
+    private static void checkDir(String dirname) {
+        if (! new File(dirname).isDirectory())
+            fail(String.format("Not a directory: %s%n", dirname));
+    }
+
+    private static void writeFile(String filename, String contents) {
+        try {
+            FileOutputStream fos = new FileOutputStream(filename);
+            fos.write(contents.getBytes());
+            fos.close();
+        } catch (Exception e) {
+            fail("Unexpected exception" + e.toString());
+        }
+    }
+
+    public static void main(String[] args) throws Exception {
+        File systemRoot =
+            getenv("SystemRoot") != null ? new File(getenv("SystemRoot")) :
+            getenv("WINDIR")     != null ? new File(getenv ("WINDIR")) :
+            null;
+        if (systemRoot == null || ! systemRoot.isDirectory())
+            return; // Not Windows as we know it
+
+        String systemDirW = new File(systemRoot, "System32").getPath();
+        String systemDirM = systemDirW.replace('\\', '/');
+        out.printf("systemDirW=%s%n", systemDirW);
+        out.printf("systemDirM=%s%n", systemDirM);
+
+        // Win9x systems don't have a cmd.exe
+        if (new File(systemDirW, "cmd.exe").exists()) {
+            try {
+                out.println("Running cmd.exe tests...");
+                writeFile("cdcmd.cmd", "@echo off\r\nCD\r\n");
+                writeFile("cdbat.bat", "@echo off\r\nCD\r\n");
+                checkCD("cmd",
+                        "cmd.exe",
+                        systemDirW + "\\cmd.exe",
+                        // Only the ".exe" extension can be omitted
+                        systemDirW + "\\cmd",
+                        systemDirM + "/cmd.exe",
+                        systemDirM + "/cmd",
+                        "/" + systemDirM + "/cmd",
+                        "cdcmd.cmd", "./cdcmd.cmd", ".\\cdcmd.cmd",
+                        "cdbat.bat", "./cdbat.bat", ".\\cdbat.bat");
+            } finally {
+                new File("cdcmd.cmd").delete();
+                new File("cdbat.bat").delete();
+            }
+        }
+
+        // 16-bit apps like command.com must have a console;
+        // fix this someday...
+
+//      // Win64 systems don't have a command.com
+//      if (new File(systemDirW, "command.com").exists()
+//          // no output if running without a console;
+//          // fix this in Mustang
+//          && ! outputOf("command.com", "/C", "CD").equals("")) {
+//          out.println("Running command.com tests...");
+//          checkCD("command.com",
+//                  systemDirM + "/command.com",
+//                  systemDirW + "\\command.com");
+//      }
+
+        // Win9x systems have a %SYSTEMDRIVE%\command.com
+//      if (new File("C:\\COMMAND.COM").exists()
+//          && ! outputOf("COMMAND.COM", "/C", "CD").equals("")) {
+//          out.println("Running COMMAND.COM tests...");
+//          checkCD("C:/command.com",
+//                  "C:\\command.com");
+//      }
+
+        if (failed > 0)
+            throw new Exception(failed + " tests failed");
+    }
+}
diff --git a/jdk/test/java/lang/Runtime/exec/setcwd.sh b/jdk/test/java/lang/Runtime/exec/setcwd.sh
new file mode 100644
index 0000000..498dea2
--- /dev/null
+++ b/jdk/test/java/lang/Runtime/exec/setcwd.sh
@@ -0,0 +1,40 @@
+#! /bin/sh
+
+#
+# Copyright 1999 Sun Microsystems, Inc.  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 Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
+# CA 95054 USA or visit www.sun.com if you need additional information or
+# have any questions.
+#
+
+#
+
+if [ x"$TESTJAVA" = x ]; then 
+        TESTJAVA=$1 
+        shift 
+fi
+if [ x"$TESTCLASSES" = x ]; then TESTCLASSES=.; fi
+
+# copy the class to our working directory
+mkdir foo
+cp ${TESTCLASSES}/SetCwd.class .
+cp ${TESTCLASSES}/SetCwd.class foo
+
+# now start the test
+${TESTJAVA}/bin/java SetCwd
\ No newline at end of file
diff --git a/jdk/test/java/lang/RuntimePermission/ExitVM.java b/jdk/test/java/lang/RuntimePermission/ExitVM.java
new file mode 100644
index 0000000..395f24b
--- /dev/null
+++ b/jdk/test/java/lang/RuntimePermission/ExitVM.java
@@ -0,0 +1,128 @@
+/*
+ * Copyright 2005 Sun Microsystems, Inc.  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 Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
+ * CA 95054 USA or visit www.sun.com if you need additional information or
+ * have any questions.
+ */
+
+/*
+ * @test
+ * @bug 6268673
+ * @summary Test new RuntimePermission.exitVM wildcard syntax
+ * @author Sean Mullan
+ */
+
+import java.security.PermissionCollection;
+
+public class ExitVM {
+
+    public static void main(String[]args) throws Exception {
+
+        RuntimePermission newWildcard = new RuntimePermission("exitVM.*");
+        RuntimePermission oldWildcard = new RuntimePermission("exitVM");
+        RuntimePermission other = new RuntimePermission("exitVM.23");
+        System.out.println("Testing RuntimePermission(\"exitVM.*\")");
+        System.out.println("    testing getName()");
+        if (!newWildcard.getName().equals("exitVM.*")) {
+            throw new Exception
+                ("expected: exitVM.* received:" + newWildcard.getName());
+        }
+        System.out.println
+            ("    testing equals(new RuntimePermission(\"exitVM.*\"))");
+        if (!newWildcard.equals(new RuntimePermission("exitVM.*"))) {
+            throw new Exception("expected true, received false");
+        }
+        System.out.println
+            ("    testing equals(new RuntimePermission(\"exitVM.23\"))");
+        if (newWildcard.equals(other)) {
+            throw new Exception("expected false, received true");
+        }
+        System.out.println
+            ("    testing implies(new RuntimePermission(\"exitVM.23\"))");
+        if (!newWildcard.implies(other)) {
+            throw new Exception("expected true, received false");
+        }
+        System.out.println
+            ("    testing implies(new RuntimePermission(\"exitVM.*\"))");
+        if (!newWildcard.implies(new RuntimePermission("exitVM.*"))) {
+            throw new Exception("expected true, received false");
+        }
+        System.out.println
+            ("    testing implies(new RuntimePermission(\"exitVM\"))");
+        if (!newWildcard.implies(oldWildcard)) {
+            throw new Exception("expected true, received false");
+        }
+        System.out.println("Testing RuntimePermission(\"exitVM\")");
+        System.out.println
+            ("    testing implies(new RuntimePermission(\"exitVM.*\"))");
+        if (!oldWildcard.implies(newWildcard)) {
+            throw new Exception("expected true, received false");
+        }
+        System.out.println
+            ("    testing implies(new RuntimePermission(\"exitVM\"))");
+        if (!oldWildcard.implies(new RuntimePermission("exitVM"))) {
+            throw new Exception("expected true, received false");
+        }
+        System.out.println
+            ("    testing implies(new RuntimePermission(\"exitVM.23\"))");
+        if (!oldWildcard.implies(other)) {
+            throw new Exception("expected true, received false");
+        }
+
+        // now test permission collections
+        System.out.println("Testing PermissionCollection containing " +
+                           "RuntimePermission(\"exitVM.*\")");
+        PermissionCollection newPC = newWildcard.newPermissionCollection();
+        newPC.add(newWildcard);
+        System.out.println
+            ("    testing implies(new RuntimePermission(\"exitVM.23\"))");
+        if (!newPC.implies(other)) {
+            throw new Exception("expected true, received false");
+        }
+        System.out.println
+            ("    testing implies(new RuntimePermission(\"exitVM.*\"))");
+        if (!newPC.implies(new RuntimePermission("exitVM.*"))) {
+            throw new Exception("expected true, received false");
+        }
+        System.out.println
+            ("    testing implies(new RuntimePermission(\"exitVM\"))");
+        if (!newPC.implies(oldWildcard)) {
+            throw new Exception("expected true, received false");
+        }
+        System.out.println("Testing PermissionCollection containing " +
+                           "RuntimePermission(\"exitVM\")");
+        PermissionCollection oldPC = oldWildcard.newPermissionCollection();
+        oldPC.add(oldWildcard);
+        System.out.println
+            ("    testing implies(new RuntimePermission(\"exitVM.23\"))");
+        if (!oldPC.implies(other)) {
+            throw new Exception("expected true, received false");
+        }
+        System.out.println
+            ("    testing implies(new RuntimePermission(\"exitVM.*\"))");
+        if (!oldPC.implies(new RuntimePermission("exitVM.*"))) {
+            throw new Exception("expected true, received false");
+        }
+        System.out.println
+            ("    testing implies(new RuntimePermission(\"exitVM\"))");
+        if (!oldPC.implies(oldWildcard)) {
+            throw new Exception("expected true, received false");
+        }
+    }
+}
diff --git a/jdk/test/java/lang/StackTraceElement/PublicConstructor.java b/jdk/test/java/lang/StackTraceElement/PublicConstructor.java
new file mode 100644
index 0000000..fb3e2c9
--- /dev/null
+++ b/jdk/test/java/lang/StackTraceElement/PublicConstructor.java
@@ -0,0 +1,49 @@
+/*
+ * Copyright 2003 Sun Microsystems, Inc.  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 Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
+ * CA 95054 USA or visit www.sun.com if you need additional information or
+ * have any questions.
+ */
+
+/*
+ * @test
+ * @bug     4712607
+ * @summary Basic test for StackTraceElementPublic constructor
+ * @author  Josh Bloch
+ */
+
+import java.util.*;
+
+public class PublicConstructor {
+    public static void main(String args[]) {
+        StackTraceElement ste = new StackTraceElement("com.acme.Widget",
+            "frobnicate", "Widget.java", 42);
+        if (!(ste.getClassName().equals("com.acme.Widget")  &&
+              ste.getFileName().equals("Widget.java") &&
+              ste.getMethodName().equals("frobnicate") &&
+              ste.getLineNumber() == 42))
+            throw new RuntimeException("1");
+        if (ste.isNativeMethod())
+            throw new RuntimeException("2");
+        StackTraceElement ste2 = new StackTraceElement("com.acme.Widget",
+            "frobnicate", "Widget.java", -2);
+        if (!ste2.isNativeMethod())
+            throw new RuntimeException("3");
+    }
+}
diff --git a/jdk/test/java/lang/String/CaseConvertSameInstance.java b/jdk/test/java/lang/String/CaseConvertSameInstance.java
new file mode 100644
index 0000000..28d44b7
--- /dev/null
+++ b/jdk/test/java/lang/String/CaseConvertSameInstance.java
@@ -0,0 +1,59 @@
+/*
+ * Copyright 1998 Sun Microsystems, Inc.  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 Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
+ * CA 95054 USA or visit www.sun.com if you need additional information or
+ * have any questions.
+ */
+
+/* @test
+   @bug 4130097
+   @summary toUpperCase and toLowerCase always return a new String,
+            whereas if there is no conversion that needs to be done,
+            they should be returning the same instance.
+   @author James Bond/007
+*/
+public class CaseConvertSameInstance {
+    public static void main(String[] args) throws Exception {
+        /* these two are the real tests for this bug. */
+        if ("foobar".toLowerCase() != "foobar")
+            throw new Exception("toLowerCase returned different object");
+        if ("FOOBAR".toUpperCase() != "FOOBAR")
+            throw new Exception("toUpperCase returned different object");
+
+        /* sanity test toLowerCase with some border conditions. */
+        if (!("FooBar".toLowerCase().equals("foobar")))
+            throw new Exception("toLowerCase broken");
+        if (!("fooBar".toLowerCase().equals("foobar")))
+            throw new Exception("toLowerCase broken");
+        if (!("foobaR".toLowerCase().equals("foobar")))
+            throw new Exception("toLowerCase broken");
+        if (!("FOOBAR".toLowerCase().equals("foobar")))
+            throw new Exception("toLowerCase broken");
+
+        /* sanity test toUpperCase with some border conditions. */
+        if (!("FooBar".toUpperCase().equals("FOOBAR")))
+            throw new Exception("toUpperCase broken");
+        if (!("fooBar".toUpperCase().equals("FOOBAR")))
+            throw new Exception("toUpperCase broken");
+        if (!("foobaR".toUpperCase().equals("FOOBAR")))
+            throw new Exception("toUpperCase broken");
+        if (!("foobar".toUpperCase().equals("FOOBAR")))
+            throw new Exception("toUpperCase broken");
+    }
+}
diff --git a/jdk/test/java/lang/String/CompareIC.java b/jdk/test/java/lang/String/CompareIC.java
new file mode 100644
index 0000000..5168dbf
--- /dev/null
+++ b/jdk/test/java/lang/String/CompareIC.java
@@ -0,0 +1,60 @@
+/*
+ * Copyright 1998 Sun Microsystems, Inc.  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 Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
+ * CA 95054 USA or visit www.sun.com if you need additional information or
+ * have any questions.
+ */
+
+/*
+ * @test
+ * @bug 4124769
+ * @summary Test ignore-case comparison
+ *
+ */
+
+import java.net.*;
+import java.io.InputStream;
+import java.io.IOException;
+
+public class CompareIC {
+
+    public static void main(String[] args) throws Exception {
+        String test1 = "Tess";
+        String test2 = "Test";
+        String test3 = "Tesu";
+        CompareIC comparer = new CompareIC();
+
+        comparer.testTriplet(test1, test2, test3);
+        test2 = test2.toUpperCase();
+        comparer.testTriplet(test1, test2, test3);
+        test2 = test2.toLowerCase();
+        comparer.testTriplet(test1, test2, test3);
+    }
+
+    private void testTriplet(String one, String two, String three)
+        throws Exception {
+            if (one.compareToIgnoreCase(two) > 0)
+                throw new RuntimeException("Comparison failure1");
+            if (two.compareToIgnoreCase(three) > 0)
+                throw new RuntimeException("Comparison failure2");
+            if (three.compareToIgnoreCase(one) < 0)
+                throw new RuntimeException("Comparison failure3");
+    }
+
+}
diff --git a/jdk/test/java/lang/String/ContentEquals.java b/jdk/test/java/lang/String/ContentEquals.java
new file mode 100644
index 0000000..a562d96
--- /dev/null
+++ b/jdk/test/java/lang/String/ContentEquals.java
@@ -0,0 +1,121 @@
+/*
+ * Copyright 2000-2004 Sun Microsystems, Inc.  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 Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
+ * CA 95054 USA or visit www.sun.com if you need additional information or
+ * have any questions.
+ */
+
+/*
+ * @test
+ * @bug 4242309 4982981
+ * @summary Test equals and contentEquals in String
+ */
+import java.util.Random;
+import java.nio.CharBuffer;
+
+// Yes, I used cut and paste for this test. Yes more code
+// sharing could have been accomplished.
+public class ContentEquals {
+
+    private static Random rnd = new Random();
+    private static final int ITERATIONS = 1000;
+    private static final int STR_LEN = 20;
+
+    public static void main(String[] args) throws Exception {
+        testStringBuffer();
+        testStringBuilder();
+        testString();
+        testCharSequence();
+    }
+
+    // Test a StringBuffer, which uses the old method from 1.4
+    public static void testStringBuffer() throws Exception {
+        for (int i=0; i<ITERATIONS; i++) {
+            int length = rnd.nextInt(STR_LEN) + 1;
+            StringBuffer testStringBuffer = new StringBuffer();
+            for(int x=0; x<length; x++) {
+                char aChar = (char)rnd.nextInt();
+                testStringBuffer.append(aChar);
+            }
+            String testString = testStringBuffer.toString();
+            char c = testStringBuffer.charAt(0);
+            testStringBuffer.setCharAt(0, 'c');
+            testStringBuffer.setCharAt(0, c);
+            if (!testString.contentEquals(testStringBuffer))
+                throw new RuntimeException("ContentsEqual failure");
+        }
+    }
+
+    // Test StringBuilder as a CharSequence using new method in 1.5
+    public static void testStringBuilder() throws Exception {
+        for (int i=0; i<ITERATIONS; i++) {
+            int length = rnd.nextInt(STR_LEN) + 1;
+            StringBuilder testStringBuilder = new StringBuilder();
+            for(int x=0; x<length; x++) {
+                char aChar = (char)rnd.nextInt();
+                testStringBuilder.append(aChar);
+            }
+            String testString = testStringBuilder.toString();
+            char c = testStringBuilder.charAt(0);
+            testStringBuilder.setCharAt(0, 'c');
+            testStringBuilder.setCharAt(0, c);
+            if (!testString.contentEquals(testStringBuilder))
+                throw new RuntimeException("ContentsEqual failure");
+        }
+    }
+
+    // Test a String as a CharSequence. This takes a different codepath in
+    // the new method in 1.5
+    public static void testString() throws Exception {
+        for (int i=0; i<ITERATIONS; i++) {
+            int length = rnd.nextInt(STR_LEN) + 1;
+            StringBuilder testStringBuilder = new StringBuilder();
+            for(int x=0; x<length; x++) {
+                char aChar = (char)rnd.nextInt();
+                testStringBuilder.append(aChar);
+            }
+            String testString = testStringBuilder.toString();
+            char c = testStringBuilder.charAt(0);
+            testStringBuilder.setCharAt(0, 'c');
+            testStringBuilder.setCharAt(0, c);
+            if (!testString.contentEquals(testStringBuilder.toString()))
+                throw new RuntimeException("ContentsEqual failure");
+        }
+    }
+
+    // Test a CharSequence that is not an AbstractStringBuilder,
+    // this takes a different codepath in the new method in 1.5
+    public static void testCharSequence() throws Exception {
+        for (int i=0; i<ITERATIONS; i++) {
+            int length = rnd.nextInt(STR_LEN) + 1;
+            StringBuilder testStringBuilder = new StringBuilder();
+            for(int x=0; x<length; x++) {
+                char aChar = (char)rnd.nextInt();
+                testStringBuilder.append(aChar);
+            }
+            String testString = testStringBuilder.toString();
+            char c = testStringBuilder.charAt(0);
+            testStringBuilder.setCharAt(0, 'c');
+            testStringBuilder.setCharAt(0, c);
+            CharBuffer buf = CharBuffer.wrap(testStringBuilder.toString());
+            if (!testString.contentEquals(buf))
+                throw new RuntimeException("ContentsEqual failure");
+        }
+    }
+}
diff --git a/jdk/test/java/lang/String/Encodings.java b/jdk/test/java/lang/String/Encodings.java
new file mode 100644
index 0000000..11949a4
--- /dev/null
+++ b/jdk/test/java/lang/String/Encodings.java
@@ -0,0 +1,179 @@
+/*
+ * Copyright 1999-2006 Sun Microsystems, Inc.  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 Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
+ * CA 95054 USA or visit www.sun.com if you need additional information or
+ * have any questions.
+ */
+
+/* @test
+ * @bug 4085160 4139951 5005831
+ * @summary Test that required character encodings are supported
+ */
+
+import java.io.InputStreamReader;
+import java.io.OutputStreamWriter;
+import java.io.ByteArrayInputStream;
+import java.io.ByteArrayOutputStream;
+import java.nio.charset.Charset;
+import java.nio.charset.UnsupportedCharsetException;
+
+
+public class Encodings {
+
+
+    static boolean equals(byte[] a, byte[] b) {
+        if (a.length != b.length) return false;
+        for (int i = 0; i < a.length; i++)
+            if (a[i] != b[i]) return false;
+        return true;
+    }
+
+
+    static void go(String enc, String str, final byte[] bytes, boolean bidir)
+        throws Exception
+    {
+        final Charset charset = Charset.forName(enc);
+
+        /* String(byte[] bs, String enc) */
+        if (!(new String(bytes, enc).equals(str)))
+            throw new Exception(enc + ": String constructor failed");
+
+        /* String(byte[] bs, Charset charset) */
+        if (!(new String(bytes, charset).equals(str)))
+            throw new Exception(charset + ": String constructor failed");
+
+        /* String(byte[] bs, int off, int len, Charset charset) */
+        String start = str.substring(0, 2);
+        String end = str.substring(2);
+        if (enc.equals("UTF-16BE") || enc.equals("UTF-16LE")) {
+            if (!(new String(bytes, 0, 4, charset).equals(start)))
+                throw new Exception(charset + ": String constructor failed");
+            if (!(new String(bytes, 4, bytes.length - 4, charset).equals(end)))
+                throw new Exception(charset + ": String constructor failed");
+        } else if (enc.equals("UTF-16")) {
+            if (!(new String(bytes, 0, 6, charset).equals(start)))
+                throw new Exception(charset + ": String constructor failed");
+        } else {
+            if (!(new String(bytes, 0, 2, charset).equals(start)))
+                throw new Exception(charset + ": String constructor failed");
+            if (!(new String(bytes, 2, bytes.length - 2, charset).equals(end)))
+                throw new Exception(charset + ": String constructor failed");
+        }
+
+        /* InputStreamReader */
+        ByteArrayInputStream bi = new ByteArrayInputStream(bytes);
+        InputStreamReader r = new InputStreamReader(bi, enc);
+        String inEnc = r.getEncoding();
+        int n = str.length();
+        char[] cs = new char[n];
+        for (int i = 0; i < n;) {
+            int m;
+            if ((m = r.read(cs, i, n - i)) < 0)
+                throw new Exception(enc + ": EOF on InputStreamReader");
+            i += m;
+        }
+        if (!(new String(cs).equals(str)))
+            throw new Exception(enc + ": InputStreamReader failed");
+
+        if (!bidir) {
+            System.err.println(enc + " --> " + inEnc);
+            return;
+        }
+
+        /* String.getBytes(String enc) */
+        byte[] bs = str.getBytes(enc);
+        if (!equals(bs, bytes))
+            throw new Exception(enc + ": String.getBytes failed");
+
+        /* String.getBytes(Charset charset) */
+        bs = str.getBytes(charset);
+        if (!equals(bs, bytes))
+            throw new Exception(charset + ": String.getBytes failed");
+
+        // Calls to String.getBytes(Charset) shouldn't automatically
+        // use the cached thread-local encoder.
+        if (charset.name().equals("UTF-16BE")) {
+            String s = new String(bytes, charset);
+            // Replace the thread-local encoder with this one.
+            byte[] bb = s.getBytes(Charset.forName("UTF-16LE"));
+            if (bytes.length != bb.length) {
+                // Incidental test.
+                throw new RuntimeException("unequal length: "
+                                           + bytes.length + " != "
+                                           + bb.length);
+            } else {
+                boolean diff = false;
+                // Expect different byte[] between UTF-16LE and UTF-16BE
+                // even though encoder was previously cached by last call
+                // to getBytes().
+                for (int i = 0; i < bytes.length; i++) {
+                    if (bytes[i] != bb[i])
+                        diff = true;
+                }
+                if (!diff)
+                    throw new RuntimeException("byte arrays equal");
+            }
+        }
+
+        /* OutputStreamWriter */
+        ByteArrayOutputStream bo = new ByteArrayOutputStream();
+        OutputStreamWriter w = new OutputStreamWriter(bo, enc);
+        String outEnc = w.getEncoding();
+        w.write(str);
+        w.close();
+        bs = bo.toByteArray();
+        if (!equals(bs, bytes))
+            throw new Exception(enc + ": OutputStreamWriter failed");
+
+        System.err.println(enc + " --> " + inEnc + " / " + outEnc);
+    }
+
+
+    static void go(String enc, String str, byte[] bytes) throws Exception {
+        go(enc, str, bytes, true);
+    }
+
+
+    public static void main(String[] args) throws Exception {
+
+        go("US-ASCII", "abc", new byte[] { 'a', 'b', 'c' });
+        go("us-ascii", "abc", new byte[] { 'a', 'b', 'c' });
+        go("ISO646-US", "abc", new byte[] { 'a', 'b', 'c' });
+        go("ISO-8859-1", "ab\u00c7", new byte[] { 'a', 'b', (byte)'\u00c7' });
+        go("UTF-8", "ab\u1e09",
+           new byte[] { 'a', 'b',
+                        (byte)(0xe0 | (0x0f & (0x1e09 >> 12))),
+                        (byte)(0x80 | (0x3f & (0x1e09 >> 6))),
+                        (byte)(0x80 | (0x3f & 0x1e09)) });
+        go("UTF-16BE", "ab\u1e09",
+           new byte[] { 0, 'a', 0, 'b', 0x1e, 0x09 });
+        go("UTF-16LE", "ab\u1e09",
+           new byte[] { 'a', 0, 'b', 0, 0x09, 0x1e });
+
+        /* UTF-16 accepts both byte orders on input but always uses big-endian
+         * on output, so test all three cases
+         */
+        go("UTF-16", "ab\u1e09",
+           new byte[] { (byte)0xfe, (byte)0xff, 0, 'a', 0, 'b', 0x1e, 0x09 });
+        go("UTF-16", "ab\u1e09",
+           new byte[] { (byte)0xff, (byte)0xfe, 'a', 0, 'b', 0, 0x09, 0x1e },
+           false);
+    }
+
+}
diff --git a/jdk/test/java/lang/String/Exceptions.java b/jdk/test/java/lang/String/Exceptions.java
new file mode 100644
index 0000000..9e7fde9
--- /dev/null
+++ b/jdk/test/java/lang/String/Exceptions.java
@@ -0,0 +1,669 @@
+/*
+ * Copyright 2002-2006 Sun Microsystems, Inc.  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 Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
+ * CA 95054 USA or visit www.sun.com if you need additional information or
+ * have any questions.
+ */
+
+/**
+ * @test
+ * @bug 4472841 4703640 4705681 4705683 4833095 5005831
+ * @summary Verify that constructor exceptions are thrown as expected.
+ */
+
+import java.io.UnsupportedEncodingException;
+import java.nio.charset.Charset;
+
+public class Exceptions {
+    private static final byte [] b = { 0x48, 0x69, 0x2c, 0x20,
+                                       0x44, 0x75, 0x6b, 0x65, 0x21 };
+
+    private static final char [] c
+        = "Attack of the Killer Tomatoes!".toCharArray();
+
+    private static boolean ok = true;
+
+    private static void fail(Class ex, String s) {
+        ok = false;
+        System.err.println("expected " + ex.getName() + " for " + s
+                               + " - FAILED");
+    }
+
+    private static void pass(String s) {
+        System.out.println(s + " -- OK");
+    }
+
+    private static void tryCatch(String s, Class ex, Runnable thunk) {
+        Throwable t = null;
+        try {
+            thunk.run();
+        } catch (Throwable x) {
+            if (ex.isAssignableFrom(x.getClass()))
+                t = x;
+            else
+                x.printStackTrace();
+        }
+        if ((t == null) && (ex != null))
+            fail(ex, s);
+        else
+            pass(s);
+    }
+
+    // -- Constructors --
+
+    private static void noArgs() {
+        System.out.println("String()");
+        tryCatch("  default ctor", null, new Runnable() {
+                public void run() {
+                    new String();
+                }});
+    }
+
+    private static void string() {
+        System.out.println("String(String original)");
+        tryCatch("  \"foo\"", null, new Runnable() {
+                public void run() {
+                    new String("foo");
+                }});
+        tryCatch("  null", NullPointerException.class, new Runnable() {
+                public void run() {
+                    new String((String) null);
+                }});
+    }
+
+    private static void charArray() {
+        System.out.println("String(char value[])");
+        tryCatch("  char [] = \"Duke says \"Hi!\"\"", null, new Runnable() {
+                public void run() {
+                    new String("Duke says \"Hi!\"".toCharArray());
+                }});
+        tryCatch("  null", NullPointerException.class, new Runnable() {
+                public void run() {
+                    new String((char []) null);
+                }});
+    }
+
+    private static void charArrayOffCount() {
+        System.out.println("String(char value[], int offset, int count)");
+        tryCatch("  c, 0, 3", null, new Runnable() {
+                public void run() {
+                    new String(c, 0, 3);
+                }});
+        tryCatch("  null, 1, 2", NullPointerException.class, new Runnable() {
+                public void run() {
+                    new String((char []) null, 1, 2);
+                }});
+        tryCatch("  c, -1, 4", IndexOutOfBoundsException.class,
+                 new Runnable() {
+                         public void run() {
+                             new String(c, -1, 4);
+                         }});
+        tryCatch("  c, 1, -1", IndexOutOfBoundsException.class,
+                 new Runnable() {
+                         public void run() {
+                             new String(c, 1, -1);
+                         }});
+        tryCatch("  c, c.lengh + 1, 1", IndexOutOfBoundsException.class,
+                 new Runnable() {
+                         public void run() {
+                             new String(c, c.length + 1, 1);
+                         }});
+        tryCatch("  c, 0, c.length + 1", IndexOutOfBoundsException.class,
+                 new Runnable() {
+                         public void run() {
+                             new String(c, 0, c.length + 1);
+                         }});
+    }
+
+    private static void byteArrayHiOffCount() {
+        System.out.println("String(byte ascii[], int hibyte, int offset, "
+                           + "int count)");
+        tryCatch("  b, 0, 0, b.length", null, new Runnable() {
+                public void run() {
+                    System.out.println(new String(b, 0, 0, b.length));
+                }});
+
+        tryCatch("  b, -1, 4, 4", null, new Runnable() {
+                public void run() {
+                    new String(b, -1, 4, 4);
+                }});
+        tryCatch("  null, 0, 0, 0", NullPointerException.class,
+                 new Runnable() {
+                         public void run() {
+                             new String((byte[]) null, 0, 0, 0);
+                         }});
+        tryCatch("  b, 0, -1, r", IndexOutOfBoundsException.class,
+                 new Runnable() {
+                         public void run() {
+                             new String(b, 0, -1, 4);
+                         }});
+        tryCatch("  b, 0, 4, -1", IndexOutOfBoundsException.class,
+                 new Runnable() {
+                         public void run() {
+                             new String(b, 0, 4, -1);
+                         }});
+        tryCatch("  b, 0, b.length + 1, 1", IndexOutOfBoundsException.class,
+                 new Runnable() {
+                         public void run() {
+                             new String(b, 0, b.length + 1, 1);
+                         }});
+        tryCatch("  b, 0, 0, b.length + 1", IndexOutOfBoundsException.class,
+                 new Runnable() {
+                         public void run() {
+                             new String(b, 0, 0, b.length + 1);
+                         }});
+    }
+
+    private static void byteArrayHi() {
+        System.out.println("String(byte ascii[], int hibyte)");
+        tryCatch("  b, 0", null, new Runnable() {
+                public void run() {
+                    new String(b, 0);
+                }});
+        tryCatch("  null, 0", NullPointerException.class, new Runnable() {
+                public void run() {
+                    new String((byte []) null, 0);
+                }});
+    }
+
+    private static void byteArrayOffLengthCharset0(String s, Class ex,
+                                                   byte [] b, int off,
+                                                   int len, Object cs)
+    {
+        Throwable t = null;
+        try {
+            if (cs instanceof String)
+                new String(b, off, len, (String)cs);
+            else // (cs instanceof Charset)
+                new String(b, off, len, (Charset)cs);
+        } catch (Throwable x) {
+            if (ex.isAssignableFrom(x.getClass()))
+                t = x;
+            else
+                x.printStackTrace();
+        }
+        if ((t == null) && (ex != null))
+            fail(ex, s);
+        else
+            pass(s);
+    }
+
+    private static void byteArrayOffLengthCharsetName() {
+        System.out.println("String(byte bytes[], int offset, int length, "
+                           + "String charsetName)");
+        System.out.println("  throws UnsupportedEncodingException");
+        String enc = "UTF-8";
+        byteArrayOffLengthCharset0("  b, 0, 0," + enc, null, b, 0, 0, enc);
+        byteArrayOffLengthCharset0("  null, 0, 0," + enc,
+                                   NullPointerException.class,
+                                   (byte []) null, 0, 0, enc);
+        byteArrayOffLengthCharset0("  b, -1, 0, " + enc,
+                                   IndexOutOfBoundsException.class,
+                                   b, -1, 0, enc);
+        byteArrayOffLengthCharset0("  b, 0, -1, " + enc,
+                                   IndexOutOfBoundsException.class,
+                                   b, 0, -1, enc);
+        byteArrayOffLengthCharset0("  b, b.length + 1, 1, " + enc,
+                                   IndexOutOfBoundsException.class,
+                                   b, b.length + 1, 1, enc);
+        byteArrayOffLengthCharset0("  b, 0, b.length + 1 " + enc,
+                                   IndexOutOfBoundsException.class,
+                                   b, 0, b.length + 1, enc);
+        byteArrayOffLengthCharset0("  b, -1, 0, null",
+                                   NullPointerException.class,
+                                   b, -1, 0, null);
+        byteArrayOffLengthCharset0("  b, 0, b.length, foo",
+                                   UnsupportedEncodingException.class,
+                                   b, 0, b.length, "foo");
+    }
+
+    private static void byteArrayOffLengthCharset() {
+        System.out.println("String(byte bytes[], int offset, int length, "
+                           + "Charset charset)");
+        Charset cs = Charset.forName("UTF-16BE");
+        byteArrayOffLengthCharset0("  b, 0, 0," + cs, null, b, 0, 0, cs);
+        byteArrayOffLengthCharset0("  null, 0, 0," + cs,
+                                   NullPointerException.class,
+                                   (byte []) null, 0, 0, cs);
+        byteArrayOffLengthCharset0("  b, -1, 0, " + cs,
+                                   IndexOutOfBoundsException.class,
+                                   b, -1, 0, cs);
+        byteArrayOffLengthCharset0("  b, 0, -1, " + cs,
+                                   IndexOutOfBoundsException.class,
+                                   b, 0, -1, cs);
+        byteArrayOffLengthCharset0("  b, b.length + 1, 1, " + cs,
+                                   IndexOutOfBoundsException.class,
+                                   b, b.length + 1, 1, cs);
+        byteArrayOffLengthCharset0("  b, 0, b.length + 1 " + cs,
+                                   IndexOutOfBoundsException.class,
+                                   b, 0, b.length + 1, cs);
+        byteArrayOffLengthCharset0("  b, -1, 0, null",
+                                   NullPointerException.class,
+                                   b, -1, 0, null);
+    }
+
+    private static void byteArrayCharset0(String s, Class ex, byte [] b,
+                                          Object cs)
+    {
+        Throwable t = null;
+        try {
+            if (cs instanceof String)
+                new String(b, (String)cs);
+            else // (cs instanceof Charset)
+                new String(b, (Charset)cs);
+        } catch (Throwable x) {
+            if (ex.isAssignableFrom(x.getClass()))
+                t = x;
+            else
+                x.printStackTrace();
+        }
+        if ((t == null) && (ex != null))
+            fail(ex, s);
+        else
+            pass(s);
+    }
+
+    private static void byteArrayCharsetName() {
+        System.out.println("String(byte bytes[], String charsetName)");
+        System.out.println("  throws UnsupportedEncodingException");
+        String enc = "US-ASCII";
+        byteArrayCharset0("  b, " + enc, null, b, enc);
+        byteArrayCharset0("  null, " + enc, NullPointerException.class,
+                          (byte []) null, enc);
+        byteArrayCharset0("  b, null", NullPointerException.class, b, null);
+        byteArrayCharset0("  null, null", NullPointerException.class,
+                          (byte []) null, null);
+        byteArrayCharset0("  b, bar", UnsupportedEncodingException.class,
+                          b, "bar");
+    }
+
+    private static void byteArrayCharset() {
+        System.out.println("String(byte bytes[], Charset charset)");
+        Charset cs = Charset.forName("ISO-8859-1");
+        byteArrayCharset0("  b, " + cs, null, b, cs);
+        byteArrayCharset0("  null, " + cs, NullPointerException.class,
+                          (byte []) null, cs);
+        byteArrayCharset0("  b, null", NullPointerException.class, b, null);
+        byteArrayCharset0("  null, null", NullPointerException.class,
+                          (byte []) null, null);
+    }
+
+    private static void byteArrayOffLength() {
+        System.out.println("String(byte bytes[], int offset, int length)");
+        tryCatch("  b, 0, b.length", null, new Runnable() {
+                public void run() {
+                    new String(b, 0, b.length);
+                }});
+        tryCatch("  null, 0, 0", NullPointerException.class, new Runnable() {
+                public void run() {
+                    new String((byte []) null, 0, 0);
+                }});
+        tryCatch("  b, -1, b.length", IndexOutOfBoundsException.class,
+                 new Runnable() {
+                         public void run() {
+                             new String(b, -1, b.length);
+                         }});
+        tryCatch("  b, 0, -1", IndexOutOfBoundsException.class,
+                 new Runnable() {
+                         public void run() {
+                             new String(b, 0, -1);
+                         }});
+        tryCatch("  b, b.length + 1, 1", IndexOutOfBoundsException.class,
+                 new Runnable() {
+                         public void run() {
+                             new String(b, b.length + 1, 1);
+                         }});
+        tryCatch("  b, 0, b.length", IndexOutOfBoundsException.class,
+                 new Runnable() {
+                         public void run() {
+                             new String(b, 0, b.length + 1);
+                         }});
+    }
+
+    private static void byteArray() {
+        System.out.println("String(byte bytes[])");
+        tryCatch("  b", null, new Runnable() {
+                public void run() {
+                    new String(b);
+                }});
+        tryCatch("  null", NullPointerException.class, new Runnable() {
+                public void run() {
+                    new String((byte []) null);
+                }});
+    }
+
+    private static void stringBuffer() {
+        System.out.println("String(StringBuffer buffer)");
+        tryCatch("  \"bar\"", null, new Runnable() {
+                public void run() {
+                    new String(new StringBuffer("bar"));
+                }});
+        tryCatch("  null", NullPointerException.class, new Runnable() {
+                public void run() {
+                    new String((StringBuffer) null);
+                }});
+    }
+
+    // -- Methods --
+
+        private static void getChars() {
+        System.out.println("getChars.(int srcBegin, int srcEnd, char dst[], "
+                           + " int dstBegin");
+        tryCatch("  null", NullPointerException.class, new Runnable() {
+                public void run() {
+                    "foo".getChars(1, 2, null, 1);
+                }});
+    }
+
+    private static void getBytes() {
+        System.out.println("getChars.(int srcBegin, int srcEnd, char dst[], "
+                           + " int dstBegin");
+        tryCatch("  1, 2, null, 1", NullPointerException.class, new Runnable() {
+                public void run() {
+                    "foo".getBytes(1, 2, null, 1);
+                }});
+
+        System.out.println("getBytes.(String charsetName)"
+                           + " throws UnsupportedEncodingException");
+        tryCatch("  null", NullPointerException.class, new Runnable() {
+                public void run() {
+                    try {
+                        "foo".getBytes((String)null);
+                    } catch (UnsupportedEncodingException x) {
+                        throw new RuntimeException(x);
+                    }
+                }});
+
+        System.out.println("getBytes.(Charset charset)");
+        tryCatch("  null", NullPointerException.class, new Runnable() {
+                public void run() {
+                    "foo".getBytes((Charset)null);
+                }});
+    }
+
+    private static void contentEquals() {
+        System.out.println("contentEquals(StringBuffer sb)");
+        tryCatch("  null", NullPointerException.class, new Runnable() {
+                public void run() {
+                    "foo".contentEquals(null);
+                }});
+    }
+
+    private static void compareTo() {
+        System.out.println("compareTo(String anotherString)");
+        tryCatch("  (String) null", NullPointerException.class, new Runnable() {
+                public void run() {
+                    "foo".compareTo((String) null);
+                }});
+
+        /* 4830291 (javac generics bug) causes this test to fail
+        System.out.println("compareTo(Object o)");
+        tryCatch("  (Object) null", NullPointerException.class, new Runnable() {
+                public void run() {
+                    "foo".compareTo((Object) null);
+                }});
+        */
+    }
+
+    private static void compareToIgnoreCase() {
+        System.out.println("compareToIgnoreCase(String anotherString)");
+        tryCatch("  null", NullPointerException.class, new Runnable() {
+                public void run() {
+                    "foo".compareToIgnoreCase((String) null);
+                }});
+    }
+
+    private static void regionMatches() {
+        System.out.println("regionMatches(int toffset, String other,"
+                           + " int ooffset, int len)");
+        tryCatch("  1, null, 1, 1", NullPointerException.class, new Runnable() {
+                public void run() {
+                    "foo".regionMatches(1, null, 1, 1);
+                }});
+
+        System.out.println("regionMatches(boolean ignore, int toffset,"
+                           + " String other, int ooffset, int len)");
+        tryCatch("  true, 1, null, 1, 1", NullPointerException.class,
+                 new Runnable() {
+                         public void run() {
+                             "foo".regionMatches(true, 1, null, 1, 1);
+                         }});
+    }
+
+    private static void startsWith() {
+        System.out.println("startsWith(String prefix, int toffset)");
+        tryCatch("  null, 1", NullPointerException.class, new Runnable() {
+                public void run() {
+                    "foo".startsWith(null, 1);
+                }});
+
+        System.out.println("startsWith(String prefix)");
+        tryCatch("  null", NullPointerException.class, new Runnable() {
+                public void run() {
+                    "foo".startsWith(null);
+                }});
+    }
+
+    private static void endsWith() {
+        System.out.println("endsWith(String suffix)");
+        tryCatch("  null", NullPointerException.class, new Runnable() {
+                public void run() {
+                    "foo".endsWith(null);
+                }});
+    }
+
+    private static void indexOf() {
+        System.out.println("indexOf(String str)");
+        tryCatch("  null", NullPointerException.class, new Runnable() {
+                public void run() {
+                    "foo".indexOf(null);
+                }});
+
+        System.out.println("indexOf(String str, int fromIndex)");
+        tryCatch("  null, 1", NullPointerException.class, new Runnable() {
+                public void run() {
+                    "foo".indexOf(null, 1);
+                }});
+    }
+
+    private static void lastIndexOf() {
+        System.out.println("lastIndexOf(String str)");
+        tryCatch("  null", NullPointerException.class, new Runnable() {
+                public void run() {
+                    "foo".lastIndexOf(null);
+                }});
+
+        System.out.println("lastIndexOf(String str, int fromIndex)");
+        tryCatch("  null, 1", NullPointerException.class, new Runnable() {
+                public void run() {
+                    "foo".lastIndexOf(null, 1);
+                }});
+    }
+
+    private static void concat() {
+        System.out.println("concat(String str)");
+        tryCatch("  null", NullPointerException.class, new Runnable() {
+                public void run() {
+                    "foo".concat(null);
+                }});
+    }
+
+    private static void matches() {
+        System.out.println("matches(String regex)");
+        tryCatch("  null", NullPointerException.class, new Runnable() {
+                public void run() {
+                    "foo".matches(null);
+                }});
+    }
+
+    private static void replaceFirst() {
+        System.out.println("replaceFirst(String regex, String replacement)");
+        tryCatch("  \".\", null", NullPointerException.class, new Runnable() {
+                public void run() {
+                    "foo".replaceFirst(".", null);
+                }});
+        tryCatch("  null, \"-\"", NullPointerException.class, new Runnable() {
+                public void run() {
+                    "foo".replaceFirst(null, "-");
+                }});
+    }
+
+    private static void replaceAll() {
+        System.out.println("replaceAll(String regex, String replacement)");
+        tryCatch("  \".\", null", NullPointerException.class, new Runnable() {
+                public void run() {
+                    "foo".replaceAll(".", null);
+                }});
+        tryCatch("  null, \"-\"", NullPointerException.class, new Runnable() {
+                public void run() {
+                    "foo".replaceAll(null, "-");
+                }});
+    }
+
+    private static void split() {
+        System.out.println("split(String regex, int limit)");
+        tryCatch("  null, 1", NullPointerException.class, new Runnable() {
+                public void run() {
+                    "foo".split(null, 1);
+                }});
+
+        System.out.println("split(String regex, int limit)");
+        tryCatch("  null", NullPointerException.class, new Runnable() {
+                public void run() {
+                    "foo".split(null);
+                }});
+    }
+
+    private static void toLowerCase() {
+        System.out.println("toLowerCase(Locale locale)");
+        tryCatch("  null", NullPointerException.class, new Runnable() {
+                public void run() {
+                    "foo".toLowerCase(null);
+                }});
+    }
+
+    private static void toUpperCase() {
+        System.out.println("toUpperCase(Locale locale)");
+        tryCatch("  null", NullPointerException.class, new Runnable() {
+                public void run() {
+                    "foo".toUpperCase(null);
+                }});
+    }
+
+    private static void valueOf() {
+        System.out.println("valueOf(Object obj)");
+        tryCatch("  null", null, new Runnable() {
+                public void run() {
+                    String.valueOf((Object) null);
+                }});
+
+        System.out.println("valueOf(char data[])");
+        tryCatch("  null", NullPointerException.class, new Runnable() {
+                public void run() {
+                    String.valueOf((char []) null);
+                }});
+
+        System.out.println("valueOf(char data[], int offset, int count)");
+        tryCatch("  null, 1, 2", NullPointerException.class, new Runnable() {
+                public void run() {
+                    String.valueOf((char []) null, 1, 2);
+                }});
+
+    }
+
+    private static void copyValueOf() {
+        System.out.println("copyValueOf(char data[], int offset, int count)");
+        tryCatch("  null, 1, 2", NullPointerException.class, new Runnable() {
+                public void run() {
+                    "foo".copyValueOf((char []) null, 1, 2);
+                }});
+
+        System.out.println("copyVlueOf(char data[])");
+        tryCatch("  null", NullPointerException.class, new Runnable() {
+                public void run() {
+                    String.copyValueOf((char []) null);
+                }});
+    }
+
+    public static void main(String [] args) {
+
+        // -- Constructors --
+
+        noArgs();             // String()
+        string();             // String(String original)
+        charArray();          // String(char value[])
+        charArrayOffCount();  // String(char value[], int offset, int count)
+
+        // String(byte ascii[], int hibyte, int offset, int count)
+        byteArrayHiOffCount();
+
+        byteArrayHi();        // String(byte ascii[], int hibyte)
+
+        // String(byte bytes[], int offset, int length, String charsetName)
+        //   throws UnsupportedEncodingException
+        byteArrayOffLengthCharsetName();
+
+        // String(byte bytes[], int offset, int length, Charset charset)
+        byteArrayOffLengthCharset();
+
+        // String(byte bytes[], String charsetName)
+        //   throws UnsupportedEncodingException
+        byteArrayCharsetName();
+
+        // String(byte bytes[], Charset charset)
+        byteArrayCharset();
+
+        byteArrayOffLength(); // String(byte bytes[], int offset, int length)
+        byteArray();          // String(byte bytes[])
+        stringBuffer();       // String(StringBuffer buffer)
+
+        // -- Methods --
+
+        getChars();           // getChars(int, int. char [], int)
+        getBytes();           // getBytes(int, int, byte [], int),
+                              //   getBytes(Locale)
+                              //   getBytes(String)
+                              //   getBytes(Charset)
+        contentEquals();      // contentEquals(StringBuffer)
+        compareTo();          // compareTo(String), compareTo(Object)
+        compareToIgnoreCase();// compareToIgnoreCase(String)
+        regionMatches();      // regionMatches(int, String, int, int)
+                              //   regionMatches(boolean, int, String, int, int)
+        startsWith();         // startsWith(String, int), startsWith(String)
+        endsWith();           // endsWith(String)
+        indexOf();            // indexOf(String), indexOf(String, int),
+        lastIndexOf();        // lastIndexOf(String), lastIndexOf(String, int)
+        concat();             // concat(String)
+        matches();            // matches(String)
+        replaceFirst();       // replaceFirst(String, String)
+        replaceAll();         // replaceAll(String, String)
+        split();              // split(String, int), split(String)
+        toLowerCase();        // toLowerCase(Locale)
+        toUpperCase();        // toUpperCase(Locale)
+        valueOf();            // valueOf(Object), valueOf(char []),
+                              //   valueOf(char [], int, int)
+        copyValueOf();        // copyValueOf(char [], int, int),
+                              //    copyValueOf(char [])
+
+        if (!ok)
+            throw new RuntimeException("Some tests FAILED");
+        else
+            System.out.println("All tests PASSED");
+    }
+}
diff --git a/jdk/test/java/lang/String/ICCBasher.java b/jdk/test/java/lang/String/ICCBasher.java
new file mode 100644
index 0000000..e564d96
--- /dev/null
+++ b/jdk/test/java/lang/String/ICCBasher.java
@@ -0,0 +1,111 @@
+/*
+ * Copyright 1998-2002 Sun Microsystems, Inc.  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 Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
+ * CA 95054 USA or visit www.sun.com if you need additional information or
+ * have any questions.
+ */
+
+/**
+ * @test
+ * @bug 4152868
+ * @summary test Case Insensitive Comparator in String
+ */
+
+import java.util.*;
+
+public class ICCBasher {
+
+    static final int TEST_SIZE = 20;
+    static final int STRING_SIZE = 5;
+    static final int CHAR_VALUE_LIMIT = 128;
+
+    public static void main(String[] args) throws Exception {
+        LinkedList L1 = new LinkedList();
+        LinkedList L2 = new LinkedList();
+        LinkedList L3 = new LinkedList();
+        LinkedList L4 = new LinkedList();
+
+        // First generate L1 and L2 with random lower case chars
+        //System.out.println("Generate L1 and L2");
+        Random generator = new Random();
+        int achar=0;
+        StringBuffer entryBuffer = new StringBuffer(10);
+        String snippet = null;
+        for (int x=0; x<TEST_SIZE * 2; x++) {
+            for(int y=0; y<STRING_SIZE; y++) {
+                achar = generator.nextInt(CHAR_VALUE_LIMIT);
+                char test = (char)(achar);
+                entryBuffer.append(test);
+            }
+            snippet = entryBuffer.toString();
+            snippet.toLowerCase();
+            if (x < TEST_SIZE)
+                L1.add(snippet);
+            else
+                L2.add(snippet);
+        }
+
+        // Concatenate L1 and L2 to form L3
+        //System.out.println("Generate L3");
+        for (int x=0; x<TEST_SIZE; x++) {
+            String entry = (String)L1.get(x) + (String)L2.get(x);
+            L3.add(entry);
+        }
+
+        // Randomly toUpper L1 and L2
+        //System.out.println("Modify L1 and L2");
+        for (int x=0; x<TEST_SIZE; x++) {
+            achar = generator.nextInt();
+            if (achar > 0) {
+                String mod = (String)L1.get(x);
+                mod = mod.toUpperCase();
+                L1.set(x, mod);
+            }
+            achar = generator.nextInt();
+            if (achar > 0) {
+                String mod = (String)L2.get(x);
+                mod = mod.toUpperCase();
+                L2.set(x, mod);
+            }
+        }
+
+        // Concatenate L1 and L2 to form L4
+        //System.out.println("Generate L4");
+        for (int x=0; x<TEST_SIZE; x++) {
+            String entry = (String)L1.get(x) + (String)L2.get(x);
+            L4.add(entry);
+        }
+
+        // Sort L3 and L4 using case insensitive comparator
+        //System.out.println("Sort L3 and L4");
+        Collections.sort(L3, String.CASE_INSENSITIVE_ORDER);
+        Collections.sort(L4, String.CASE_INSENSITIVE_ORDER);
+
+        // Check to see that order of L3 and L4 are identical
+        // ignoring case considerations
+        //System.out.println("Check order of L3 and L4");
+        for (int x=0; x<TEST_SIZE; x++) {
+            String one = (String)L3.get(x);
+            String two = (String)L4.get(x);
+            if (!one.equalsIgnoreCase(two))
+                throw new RuntimeException("Case Insensitive Sort Failure.");
+        }
+
+    }
+}
diff --git a/jdk/test/java/lang/String/IndexOfEmptyInEmpty.java b/jdk/test/java/lang/String/IndexOfEmptyInEmpty.java
new file mode 100644
index 0000000..1ba52ba
--- /dev/null
+++ b/jdk/test/java/lang/String/IndexOfEmptyInEmpty.java
@@ -0,0 +1,36 @@
+/*
+ * Copyright 1998 Sun Microsystems, Inc.  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 Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
+ * CA 95054 USA or visit www.sun.com if you need additional information or
+ * have any questions.
+ */
+
+/* @test
+   @bug 4096273
+   @summary new String("").indexOf("") must give 0, not -1
+   @author Anand Palaniswamy
+ */
+public class IndexOfEmptyInEmpty {
+    public static void main(String[] args) throws Exception {
+        int result = new String("").indexOf("");
+        if (result != 0) {
+            throw new Exception("new String(\"\").indexOf(\"\") must be 0, but got " + result);
+        }
+    }
+}
diff --git a/jdk/test/java/lang/String/IsEmpty.java b/jdk/test/java/lang/String/IsEmpty.java
new file mode 100644
index 0000000..1d31287
--- /dev/null
+++ b/jdk/test/java/lang/String/IsEmpty.java
@@ -0,0 +1,47 @@
+/*
+ * Copyright 2004 Sun Microsystems, Inc.  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 Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
+ * CA 95054 USA or visit www.sun.com if you need additional information or
+ * have any questions.
+ */
+
+/**
+ * @test
+ * @summary Basic isEmpty functionality
+ * @bug 6189137
+ */
+
+public class IsEmpty {
+    private static String [] tests = { "", " ", "a",
+                                       "It was the best of times, it was the worst of times, it was the age of wisdom, it was the age of foolishness, it was the epoch of belief, it was the epoch of incredulity, it was the season of Light, it was the season of Darkness, it was the spring of hope, it was the winter of despair, we had everything before us, we had nothing before us, we were all going direct to Heaven, we were all going direct the other way- in short, the period was so far like the present period, that some of its noisiest authorities insisted on its being received, for good or for evil, in the superlative degree of comparison only.  -- Charles Dickens, Tale of Two Cities"
+    };
+
+    public static void main(String [] args) {
+        for (int i = 0; i < tests.length; i++) {
+            String s = tests[i];
+            int len = s.length();
+            boolean empty = s.isEmpty();
+
+            if ((len != 0 && empty) || (len == 0 && !empty))
+                throw new RuntimeException("String \"" + s + "\": "
+                                           + " isEmpty = " + empty
+                                           + ", length = " + len);
+        }
+    }
+}
diff --git a/jdk/test/java/lang/String/NonCharacterMapping.java b/jdk/test/java/lang/String/NonCharacterMapping.java
new file mode 100644
index 0000000..e0bd8ad
--- /dev/null
+++ b/jdk/test/java/lang/String/NonCharacterMapping.java
@@ -0,0 +1,84 @@
+/*
+ * Copyright 2004 Sun Microsystems, Inc.  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 Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
+ * CA 95054 USA or visit www.sun.com if you need additional information or
+ * have any questions.
+ */
+
+/*
+ *  @test
+ *  @bug 5101626
+ *  @summary Case conversion should not trip over non-character code points.
+ */
+
+import java.util.Locale;
+
+public class NonCharacterMapping {
+
+    private static final Locale ENGLISH = new Locale("en");
+    private static final Locale TURKISH = new Locale("tr");
+
+    public static void main(String[] args) {
+        if (Character.toLowerCase('\uFFFF') != '\uFFFF') {
+            throw new RuntimeException();
+        }
+        if (Character.toUpperCase('\uFFFF') != '\uFFFF') {
+            throw new RuntimeException();
+        }
+        if (Character.toTitleCase('\uFFFF') != '\uFFFF') {
+            throw new RuntimeException();
+        }
+        if (!"\uFFFF".toLowerCase(ENGLISH).equals("\uFFFF")) {
+            throw new RuntimeException();
+        }
+        if (!"\uFFFF".toUpperCase(ENGLISH).equals("\uFFFF")) {
+            throw new RuntimeException();
+        }
+        if (!"\uFFFF".toLowerCase(TURKISH).equals("\uFFFF")) {
+            throw new RuntimeException();
+        }
+        if (!"\uFFFF".toUpperCase(TURKISH).equals("\uFFFF")) {
+            throw new RuntimeException();
+        }
+        if (!"A\uFFFF".toLowerCase(ENGLISH).equals("a\uFFFF")) {
+            throw new RuntimeException();
+        }
+        if (!"A\uFFFF".toUpperCase(ENGLISH).equals("A\uFFFF")) {
+            throw new RuntimeException();
+        }
+        if (!"A\uFFFF".toLowerCase(TURKISH).equals("a\uFFFF")) {
+            throw new RuntimeException();
+        }
+        if (!"A\uFFFF".toUpperCase(TURKISH).equals("A\uFFFF")) {
+            throw new RuntimeException();
+        }
+        if (!"a\uFFFF".toLowerCase(ENGLISH).equals("a\uFFFF")) {
+            throw new RuntimeException();
+        }
+        if (!"a\uFFFF".toUpperCase(ENGLISH).equals("A\uFFFF")) {
+            throw new RuntimeException();
+        }
+        if (!"a\uFFFF".toLowerCase(TURKISH).equals("a\uFFFF")) {
+            throw new RuntimeException();
+        }
+        if (!"a\uFFFF".toUpperCase(TURKISH).equals("A\uFFFF")) {
+            throw new RuntimeException();
+        }
+    }
+}
diff --git a/jdk/test/java/lang/String/Regex.java b/jdk/test/java/lang/String/Regex.java
new file mode 100644
index 0000000..88a4a63
--- /dev/null
+++ b/jdk/test/java/lang/String/Regex.java
@@ -0,0 +1,98 @@
+/*
+ * Copyright 2001-2003 Sun Microsystems, Inc.  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 Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
+ * CA 95054 USA or visit www.sun.com if you need additional information or
+ * have any questions.
+ */
+
+/* @test
+ * @bug 4808962
+ * @summary Unit tests for String regex methods
+ */
+
+
+public class Regex {
+
+    static void ck(boolean x, boolean ans) throws Exception {
+        if (x != ans)
+            throw new Exception("Test failed");
+    }
+
+    static void ck(String x, String ans) throws Exception {
+        if (!x.equals(ans))
+            throw new Exception("Test failed");
+    }
+
+    static void ck(String[] x, String[] ans) throws Exception {
+        if (x.length != ans.length)
+            throw new Exception("Test failed");
+        for (int i = 0; i < x.length; i++) {
+            if (!x[i].equals(ans[i]))
+                throw new Exception("Test failed");
+        }
+    }
+
+    static void testLiteralReplacement() throws Exception {
+        // Test straightforward replacement
+        String data = "abcdefghi";
+        String result = data.replace("def", "abc");
+        if (!result.equals("abcabcghi"))
+            throw new Exception("Test failed");
+
+        // Test replacement with target that has metacharacters
+        data = "abc(def)?ghi";
+        result = data.replace("(def)?", "abc");
+        if (!result.equals("abcabcghi"))
+            throw new Exception("Test failed");
+
+        // Test replacement with replacement that has metacharacters
+        data = "abcdefghi";
+        result = data.replace("def", "\\ab$c");
+        if (!result.equals("abc\\ab$cghi"))
+            throw new Exception("Test failed");
+    }
+
+    public static void main(String[] args) throws Exception {
+
+        // These don't need to be thorough, they just need to check
+        // that we're properly hooked up to java.util.regex
+
+        String foo = "boo:and:foo";
+
+        ck(foo.matches("b+"), false);
+        ck(foo.matches("o+"), false);
+        ck(foo.matches("b..:and:f.*"), true);
+
+        ck(foo.replaceAll("oo", "uu"), "buu:and:fuu");
+        ck(foo.replaceAll("o+", "<$0>"), "b<oo>:and:f<oo>");
+
+        ck(foo.replaceFirst("oo", "uu"), "buu:and:foo");
+        ck(foo.replaceFirst("o+", "<$0>"), "b<oo>:and:foo");
+
+        ck(foo.split(":"), new String[] { "boo", "and", "foo" });
+        ck(foo.split("o"), new String[] { "b", "", ":and:f" });
+
+        ck(foo.split(":", 2), new String[] { "boo", "and:foo" });
+        ck(foo.split("o", -2), new String[] { "b", "", ":and:f", "", "" });
+
+        testLiteralReplacement();
+    }
+
+
+}
diff --git a/jdk/test/java/lang/String/RegionMatches.java b/jdk/test/java/lang/String/RegionMatches.java
new file mode 100644
index 0000000..3cc924e
--- /dev/null
+++ b/jdk/test/java/lang/String/RegionMatches.java
@@ -0,0 +1,40 @@
+/*
+ * Copyright 1998 Sun Microsystems, Inc.  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 Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
+ * CA 95054 USA or visit www.sun.com if you need additional information or
+ * have any questions.
+ */
+
+/**
+ * @test
+ * @bug 4016509
+ * @summary test regionMatches corner case
+ */
+
+
+public class RegionMatches {
+
+  public static void main (String args[]) throws Exception {
+      String s1="abc";
+      String s2="def";
+
+      if (!s1.regionMatches(0,s2,0,Integer.MIN_VALUE))
+          throw new RuntimeException("Integer overflow in RegionMatches");
+  }
+}
diff --git a/jdk/test/java/lang/String/SBConstructor.java b/jdk/test/java/lang/String/SBConstructor.java
new file mode 100644
index 0000000..4003093
--- /dev/null
+++ b/jdk/test/java/lang/String/SBConstructor.java
@@ -0,0 +1,50 @@
+/*
+ * Copyright 2003 Sun Microsystems, Inc.  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 Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
+ * CA 95054 USA or visit www.sun.com if you need additional information or
+ * have any questions.
+ */
+
+/*
+ * @test
+ * @bug 4915187
+ * @summary Test java.lang.String constructor that takes StringBuilder
+ *
+ */
+import java.util.*;
+
+public class SBConstructor {
+    private static Random rnd = new Random();
+    public static void main (String[] argvs) throws Exception {
+        for (int i=0; i<1000; i++) {
+            int length = rnd.nextInt(20) + 1;
+            StringBuffer testStringBuffer = new StringBuffer();
+            StringBuilder testStringBuilder = new StringBuilder();
+            for(int x=0; x<length; x++) {
+                char aChar = (char)rnd.nextInt();
+                testStringBuffer.append(aChar);
+                testStringBuilder.append(aChar);
+            }
+            String testString1 = new String(testStringBuffer);
+            String testString2 = new String(testStringBuilder);
+            if (!testString1.equals(testString2))
+                throw new RuntimeException("Test failure");
+        }
+    }
+}
diff --git a/jdk/test/java/lang/String/Split.java b/jdk/test/java/lang/String/Split.java
new file mode 100644
index 0000000..b4ab5fb
--- /dev/null
+++ b/jdk/test/java/lang/String/Split.java
@@ -0,0 +1,84 @@
+/*
+ * Copyright 2000-2001 Sun Microsystems, Inc.  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 Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
+ * CA 95054 USA or visit www.sun.com if you need additional information or
+ * have any questions.
+ */
+
+/**
+ * @test
+ * @summary test String.split()
+ */
+import java.util.regex.*;
+
+public class Split {
+
+    public static void main(String[] args) throws Exception {
+        String source = "0123456789";
+        for (int limit=-2; limit<3; limit++) {
+            for (int x=0; x<10; x++) {
+                String[] result = source.split(Integer.toString(x), limit);
+                int expectedLength = limit < 1 ? 2 : limit;
+
+                if ((limit == 0) && (x == 9)) {
+                    // expected dropping of ""
+                    if (result.length != 1)
+                        throw new RuntimeException("String.split failure 1");
+                    if (!result[0].equals("012345678")) {
+                        throw new RuntimeException("String.split failure 2");
+                    }
+                } else {
+                    if (result.length != expectedLength) {
+                        throw new RuntimeException("String.split failure 3");
+                    }
+                    if (!result[0].equals(source.substring(0,x))) {
+                        if (limit != 1) {
+                            throw new RuntimeException(
+                                "String.split failure 4");
+                        } else {
+                            if (!result[0].equals(source.substring(0,10))) {
+                            throw new RuntimeException(
+                                "String.split failure 10");
+                            }
+                        }
+                    }
+                    if (expectedLength > 1) { // Check segment 2
+                       if (!result[1].equals(source.substring(x+1,10)))
+                          throw new RuntimeException("String.split failure 5");
+                    }
+                }
+            }
+        }
+        // Check the case for no match found
+        for (int limit=-2; limit<3; limit++) {
+            String[] result = source.split("e", limit);
+            if (result.length != 1)
+                throw new RuntimeException("String.split failure 6");
+            if (!result[0].equals(source))
+                throw new RuntimeException("String.split failure 7");
+        }
+        // Check the case for limit == 0, source = "";
+        source = "";
+        String[] result = source.split("e", 0);
+        if (result.length != 1)
+            throw new RuntimeException("String.split failure 8");
+        if (!result[0].equals(source))
+            throw new RuntimeException("String.split failure 9");
+    }
+}
diff --git a/jdk/test/java/lang/String/Supplementary.java b/jdk/test/java/lang/String/Supplementary.java
new file mode 100644
index 0000000..f7bc3c5
--- /dev/null
+++ b/jdk/test/java/lang/String/Supplementary.java
@@ -0,0 +1,643 @@
+/*
+ * Copyright 2003-2005 Sun Microsystems, Inc.  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 Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
+ * CA 95054 USA or visit www.sun.com if you need additional information or
+ * have any questions.
+ */
+
+/*
+ *
+ * @test
+ * @bug 4533872 4915683 4922962 4985217 5017280 6242664 6588260
+ * @summary Unit tests for supplementary character support (JSR-204)
+ */
+
+public class Supplementary {
+
+    public static void main(String[] args) {
+        test1();        // Test for codePointAt(int index)
+        test2();        // Test for codePointBefore(int index)
+        test3();        // Test for indexOf(int ch)
+        test4();        // Test for indexOf(int ch, int fromIndex)
+        test5();        // Test for lastIndexOf(int ch)
+        test6();        // Test for lastIndexOf(int ch, int fromIndex)
+        test7();        // Test for String(int[] codePoint, int offset, int count)
+        test8();        // Test for codePointCount(int beginIndex, int endIndex)
+        test9();        // Test for offsetByCodePoints(int index, int offset)
+        test10();       // Test for offsetByCodePoints(int index, int offset)
+                        // To verify the fix for 6242664
+    }
+
+    /* Text strings which are used as input data.
+     * The comment above each text string means the index of each 16-bit char
+     * for convenience.
+     */
+    static final String[] input = {
+      /*                               111     1     111111     22222
+         0123     4     5678     9     012     3     456789     01234 */
+        "abc\uD800\uDC00def\uD800\uD800ab\uD800\uDC00cdefa\uDC00bcdef",
+      /*                          1     1111     1111     1     222
+         0     12345     6789     0     1234     5678     9     012     */
+        "\uD800defg\uD800hij\uD800\uDC00klm\uDC00nop\uDC00\uD800rt\uDC00",
+      /*                          11     1     1111     1     112     222
+         0     12345     6     78901     2     3456     7     890     123     */
+        "\uDC00abcd\uDBFF\uDFFFefgh\uD800\uDC009ik\uDC00\uDC00lm\uDC00no\uD800",
+      /*                                    111     111111     1 22     2
+         0     1     2345     678     9     012     345678     9 01     2     */
+        "\uD800\uDC00!#$\uD800%&\uD800\uDC00;+\uDC00<>;=^\uDC00\\@\uD800\uDC00",
+
+        // includes an undefined supprementary characters in Unicode 4.0.0
+      /*                                    1     11     1     1111     1
+         0     1     2345     6     789     0     12     3     4567     8     */
+        "\uDB40\uDE00abc\uDE01\uDB40de\uDB40\uDE02f\uDB40\uDE03ghi\uDB40\uDE02",
+
+        // all supplementary characters
+      /*                                                             1     1
+         0     1     2     3     4     5     6     7     8     9     0     1     */
+        "\uD800\uDC00\uD800\uDC01\uD800\uDC02\uD800\uDC03\uD800\uDC04\uD800\uDC05"+
+      /* 1     1     1     1     1     1     1     1     2     2     2     2
+         2     3     4     5     6     7     8     9     0     1     2     3     */
+        "\uD800\uDC06\uD800\uDC07\uD800\uDC08\uD800\uDC08\uD800\uDC09\uD800\uDC0A"+
+      /* 2     2     2     2     2     2     3     3     3     3     3     3
+         4     5     6     7     8     9     0     1     2     3     4     5     */
+        "\uD800\uDC0B\uD800\uDC0C\uD800\uDC0D\uD800\uDC0A\uD800\uDC0F\uD800\uDC10"
+    };
+
+
+    /* Expected results for:
+     *     test1(): for codePointAt()
+     *
+     * Each character in each array is the golden data for each text string
+     * in the above input data. For example, the first data in each array is
+     * for the first input string.
+     */
+    static final int[][] golden1 = {
+        {'a',    0xD800,  0xDC00, 0x10000, 0xE0200, 0x10000},// codePointAt(0)
+        {0xD800, 0x10000, 'g',    0xDC00,  0xE0202, 0xDC04}, // codePointAt(9)
+        {'f',    0xDC00,  0xD800, 0xDC00,  0xDE02,  0xDC10}, // codePointAt(length-1)
+        {'f',    'p',     0xDC00, '^',     0xE0202, 0xDC08}, // codePointAt() for a substring
+    };
+
+    /*
+     * Test for codePointAt(int index) method
+     */
+    static void test1() {
+
+        for (int i = 0; i < input.length; i++) {
+            String s = input[i];
+
+            /*
+             * Normal case
+             */
+            testCodePoint(At, s, 0, golden1[0][i]);
+            testCodePoint(At, s, 9, golden1[1][i]);
+            testCodePoint(At, s, s.length()-1, golden1[2][i]);
+            testCodePoint(At, s.substring(17), 0, golden1[3][i]);
+
+            /*
+             * Abnormal case - verify that an exception is thrown.
+             */
+            testCodePoint(At, s, -1);
+            testCodePoint(At, s, s.length());
+        }
+    }
+
+
+    /* Expected results for:
+     *     test2(): for codePointBefore()
+     *
+     * Each character in each array is the golden data for each text string
+     * in the above input data. For example, the first data in each array is
+     * for the first input string.
+     */
+    static final int[][] golden2 = {
+        {'a',    0xD800, 0xDC00,  0xD800,  0xDB40,  0xD800}, // codePointBefore(1)
+        {0xD800, 'l',    0x10000, 0xDC00,  0xDB40,  0xD800}, // codePointBefore(13)
+        {'f',    0xDC00, 0xD800,  0x10000, 0xE0202, 0x10010},// codePointBefore(length)
+        {'b',    'd',    'a',     0xDC00,  0xDE00,  0xDC00}, // codePointBefore() for a substring
+    };
+
+    /*
+     * Test for codePointBefore(int index) method
+     */
+    static void test2() {
+
+        for (int i = 0; i < input.length; i++) {
+            String s = input[i];
+
+            /*
+             * Normal case
+             */
+            testCodePoint(Before, s, 1, golden2[0][i]);
+            testCodePoint(Before, s, 13, golden2[1][i]);
+            testCodePoint(Before, s, s.length(), golden2[2][i]);
+            testCodePoint(Before, s.substring(1), 1, golden2[3][i]);
+
+            /*
+             * Abnormal case - verify that an exception is thrown.
+             */
+            testCodePoint(Before, s, 0);
+            testCodePoint(Before, s, s.length()+1);
+        }
+    }
+
+
+    /* Expected results for:
+     *     test3(): for indexOf(int ch)
+     *     test4(): for indexOf(int ch, int fromIndex)
+     *     test5(): for lastIndexOf(int ch)
+     *     test6(): for lastIndexOf(int ch, int fromIndex)
+     *
+     * Unlike golden1 and golden2, golden3[m][] is the golden data for text
+     * string in input[m].
+     *
+     * The meaning of each element in golden3[][n]
+     *   golden3[][0]: characater which is searched.
+     *   golden3[][2]: the golden data for indexOf(int ch)
+     *   From golden3[][2] to golden3[][n-1]:
+     *       the golden data for indexOf(int ch, int fromIndex)
+     *   The golden3[][n-2]: the golden data for lastIndexOf(int ch)
+     *   From golden3[][1] to golden3[][n-2]:
+     *       the golden data for lastIndexOf(int ch, int fromIndex)
+     *
+     *   In other words, the data format is
+     *     { ch, -1, index1, index2, ..., -1}
+     *   where index1, index2, ... are all indices of the ch occurrences.
+     */
+    static final int[][] golden3 = {
+      /* ch       indices */
+        {'b',     -1,  1, 11, 20,  -1},
+        {0xD800,  -1,  0,  5,  9,  19, -1},
+        {0xDC00,  -1,  0, 12, 16,  17, 20, -1},
+        {0x10000, -1,  0,  8, 21,  -1},
+        {0xE0202, -1,  9, 17, -1},
+        {0x1000A, -1, 22, 30, -1}
+    };
+
+    /*
+     * Test for indexOf(int ch) method
+     */
+    static void test3() {
+
+        for (int i = 0; i < input.length; i++) {
+            String s = input[i];
+
+            /*
+             * Normal case
+             */
+            testIndexOf(First, s, golden3[i][0], golden3[i][2]);
+
+            /*
+             * Abnormal case - char which isn't included in the string.
+             */
+            testIndexOf(First, s, 'Z', -1);
+            testIndexOf(First, s, 0xDB98, -1);
+            testIndexOf(First, s, 0xDE76, -1);
+            testIndexOf(First, s, 0x12345, -1);
+            testIndexOf(First, s, -1, -1);
+            testIndexOf(First, s, 0x110000, -1);
+        }
+    }
+
+    /*
+     * Test for indexOf(int ch, int fromIndex) method
+     */
+    static void test4() {
+
+        for (int i = 0; i < input.length; i++) {
+            String s = input[i];
+            int ch = golden3[i][0];
+
+            /*
+             * Normal case
+             */
+            int fromIndex = 0;
+            for (int j = 2; j < golden3[i].length; j++) {
+                fromIndex = testIndexOf(First, s, fromIndex, ch,
+                                        golden3[i][j]) + 1;
+            }
+
+            /*
+             * Abnormal case1 - char is included in the string but fromIndex
+             *                  is incorrect.
+             */
+            testIndexOf(First, s, -1, ch, golden3[i][2]);
+            testIndexOf(First, s, s.length(), ch,
+                        golden3[i][golden3[i].length-1]);
+
+            /*
+             * Abnormal case2 - char which isn't included in the string.
+             */
+            testIndexOf(First, s, 0, 'Z', -1);
+            testIndexOf(First, s, 0, 0xDB98, -1);
+            testIndexOf(First, s, 0, 0xDE76, -1);
+            testIndexOf(First, s, 0, 0x12345, -1);
+            testIndexOf(First, s, 0, -1, -1);
+            testIndexOf(First, s, 0, 0x110000, -1);
+        }
+    }
+
+    /*
+     * Test for lastIndexOf(int ch) method
+     */
+    static void test5() {
+
+        for (int i = 0; i < input.length; i++) {
+            String s = input[i];
+
+            /*
+             * Normal case
+             */
+            testIndexOf(Last, s, golden3[i][0],
+                        golden3[i][golden3[i].length-2]);
+
+            /*
+             * Abnormal case - char which isn't included in the string.
+             */
+            testIndexOf(Last, s, 'Z', -1);
+            testIndexOf(Last, s, 0xDB98, -1);
+            testIndexOf(Last, s, 0xDE76, -1);
+            testIndexOf(Last, s, 0x12345, -1);
+            testIndexOf(Last, s, -1, -1);
+            testIndexOf(Last, s, 0x110000, -1);
+        }
+    }
+
+    /*
+     * Test for lastIndexOf(int ch, int fromIndex) method
+     */
+    static void test6() {
+
+        for (int i = 0; i < input.length; i++) {
+            String s = input[i];
+            int ch = golden3[i][0];
+            int len = s.length();
+
+            /*
+             * Normal case
+             */
+            int fromIndex = len - 1;
+            for (int j = golden3[i].length - 2; j > 0; j--) {
+                fromIndex = testIndexOf(Last, s, fromIndex, ch,
+                                        golden3[i][j]) - 1;
+            }
+
+            /*
+             * Abnormal case1 - char is included in the string but fromIndex
+             *                  is incorrect.
+             */
+            testIndexOf(Last, s, -1, ch, golden3[i][1]);
+            testIndexOf(Last, s, len, ch, golden3[i][golden3[i].length-2]);
+
+            /*
+             * Abnormal case2 - char which isn't included in the string.
+             */
+            testIndexOf(Last, s, len, 'Z', -1);
+            testIndexOf(Last, s, len, 0xDB98, -1);
+            testIndexOf(Last, s, len, 0xDE76, -1);
+            testIndexOf(Last, s, len, 0x12345, -1);
+            testIndexOf(Last, s, len, -1, -1);
+            testIndexOf(Last, s, len, 0x110000, -1);
+        }
+    }
+
+    /**
+     * Test for String(int[] codePoint, int offset, int count).
+     */
+    static void test7() {
+        for (int i = 0; i < input.length; i++) {
+            String s = input[i];
+            int nCodePoints = 0;
+            int c;
+            for (int j = 0; j < s.length(); j += Character.charCount(c)) {
+                c = s.codePointAt(j);
+                nCodePoints++;
+            }
+            int[] codePoints = new int[nCodePoints];
+            int count = 0, mid = 0, offset = 0;
+            for (int j = 0; j < s.length(); j += Character.charCount(c)) {
+                if (mid == 0 && j >= s.length()/2) {
+                    mid = j;
+                    offset = count;
+                }
+                c = s.codePointAt(j);
+                codePoints[count++] = c;
+            }
+
+            String cps = new String(codePoints, 0, count);
+            check(!s.equals(cps), "new String(int[]...) with input[" + i + "]");
+
+            cps = new String(codePoints, 0, offset);
+            check(!s.substring(0, mid).equals(cps),
+                  "first half: new String(int[]...) with input[" + i + "]");
+
+            cps = new String(codePoints, offset, count - offset);
+            check(!s.substring(mid).equals(cps),
+                  "second half: new String(int[]...) with input[" + i + "]");
+
+            // test exceptions
+            testNewString(null, 0, count, NullPointerException.class);
+            testNewString(codePoints, -1, count, IndexOutOfBoundsException.class);
+            testNewString(codePoints, 0, count+1, IndexOutOfBoundsException.class);
+            testNewString(codePoints, offset, count, IndexOutOfBoundsException.class);
+            testNewString(codePoints, offset, -1, IndexOutOfBoundsException.class);
+            testNewString(codePoints, count, 1, IndexOutOfBoundsException.class);
+            codePoints[offset] = -1;
+            testNewString(codePoints, 0, count, IllegalArgumentException.class);
+            codePoints[offset] = Character.MAX_CODE_POINT+1;
+            testNewString(codePoints, 0, count, IllegalArgumentException.class);
+        }
+
+        {
+            // 6588260: (str) ArrayIndexOutOfBoundsException when trying
+            // to create a String from codePoints
+            //int[] x = new int[Character.MAX_CODE_POINT+1];
+            int[] x = new int[Character.MAX_CODE_POINT];
+            for (int i = 0; i < x.length; i++)
+                if (i != 0xdbff) // For round-trip safety
+                    x[i] = i;
+            final String s = new String(x, 0, x.length);
+            check(s.codePointCount(0, s.length()) != x.length,
+                  "s.codePointCount(0, s.length()) != x.length");
+            check(s.length() <= x.length,
+                  "s.length() <= x.length");
+            for (int i = 0, j = 0; i < x.length; i++) {
+                int c = s.codePointAt(j);
+                check(c != x[i], "c != x[i]");
+                j += Character.charCount(c);
+            }
+        }
+    }
+
+    /**
+     * Test codePointCount(int, int)
+     *
+     * This test case assumes that
+     * Character.codePointCount(CharSequence, int, int) works
+     * correctly.
+     */
+    static void test8() {
+        for (int i = 0; i < input.length; i++) {
+            String str = input[i];
+            int length = str.length();
+            for (int j = 0; j <= length; j++) {
+                int result = str.codePointCount(j, length);
+                int expected = Character.codePointCount(str, j, length);
+                check(result != expected, "codePointCount(input["+i+"], "+j+", "+length+")",
+                      result, expected);
+                // Create a substring of the text range. It shares the
+                // underlying char[] of the String str.
+                String substr = str.substring(j, length);
+                result = substr.codePointCount(0, substr.length());
+                check(result != expected, "substring:codePointCount(input["+i+"], "+j+", "+length+")",
+                      result, expected);
+            }
+            for (int j = length; j >= 0; j--) {
+                int result = str.codePointCount(0, j);
+                int expected = Character.codePointCount(str, 0, j);
+                check(result != expected, "codePointCount(input["+i+"], 0, "+j+")",
+                      result, expected);
+                String substr = str.substring(0, j);
+                result = substr.codePointCount(0, substr.length());
+                check(result != expected, "substring:codePointCount(input["+i+"], 0, "+j+")",
+                      result, expected);
+            }
+
+            // test exceptions
+            testCodePointCount(null, 0, 0, NullPointerException.class);
+            testCodePointCount(str, -1, length, IndexOutOfBoundsException.class);
+            testCodePointCount(str, 0, length+1, IndexOutOfBoundsException.class);
+            testCodePointCount(str, length, length-1, IndexOutOfBoundsException.class);
+        }
+    }
+
+    /**
+     * Test offsetByCodePoints(int, int)
+     *
+     * This test case assumes that
+     * Character.codePointCount(CharSequence, int, int) works
+     * correctly.
+     */
+    static void test9() {
+        for (int i = 0; i < input.length; i++) {
+            String str = input[i];
+            int length = str.length();
+            for (int j = 0; j <= length; j++) {
+                int nCodePoints = Character.codePointCount(str, j, length);
+                int result = str.offsetByCodePoints(j, nCodePoints);
+                check(result != length,
+                      "offsetByCodePoints(input["+i+"], "+j+", "+nCodePoints+")",
+                      result, length);
+                result = str.offsetByCodePoints(length, -nCodePoints);
+                int expected = j;
+                if (j > 0 && j < length) {
+                    int cp = str.codePointBefore(j+1);
+                    if (Character.isSupplementaryCodePoint(cp)) {
+                        expected--;
+                    }
+                }
+                check(result != expected,
+                      "offsetByCodePoints(input["+i+"], "+j+", "+(-nCodePoints)+")",
+                      result, expected);
+            }
+            for (int j = length; j >= 0; j--) {
+                int nCodePoints = Character.codePointCount(str, 0, j);
+                int result = str.offsetByCodePoints(0, nCodePoints);
+                int expected = j;
+                if (j > 0 && j < length) {
+                    int cp = str.codePointAt(j-1);
+                     if (Character.isSupplementaryCodePoint(cp)) {
+                        expected++;
+                    }
+                }
+                check(result != expected,
+                      "offsetByCodePoints(input["+i+"], 0, "+nCodePoints+")",
+                      result, expected);
+                result = str.offsetByCodePoints(j, -nCodePoints);
+                check(result != 0,
+                      "offsetBycodePoints(input["+i+"], "+j+", "+(-nCodePoints)+")",
+                      result, 0);
+            }
+
+            // test exceptions
+            testOffsetByCodePoints(null, 0, 0, NullPointerException.class);
+            testOffsetByCodePoints(str, -1, length, IndexOutOfBoundsException.class);
+            testOffsetByCodePoints(str, 0, length+1, IndexOutOfBoundsException.class);
+            testOffsetByCodePoints(str, 1, -2, IndexOutOfBoundsException.class);
+            testOffsetByCodePoints(str, length, length-1, IndexOutOfBoundsException.class);
+            testOffsetByCodePoints(str, length, -(length+1), IndexOutOfBoundsException.class);
+        }
+    }
+
+    /**
+     * Test offsetByCodePoints(int, int) - to verify the fix for 6242664
+     *
+     * This test case assumes that
+     * Character.codePointCount(CharSequence, int, int) works
+     * correctly.
+     */
+    static void test10() {
+        String header = "H\uD800e\uDFFFa\uDBFF\uDC00der<";
+        for (int i = 0; i < input.length; i++) {
+            String wholeString = header + input[i];
+            String str = wholeString.substring(header.length());
+            int length = str.length();
+            for (int j = 0; j <= length; j++) {
+                int nCodePoints = Character.codePointCount(str, j, length);
+                int result = str.offsetByCodePoints(j, nCodePoints);
+                check(result != length,
+                      "offsetByCodePoints(input["+i+"], "+j+", "+nCodePoints+")",
+                      result, length);
+                result = str.offsetByCodePoints(length, -nCodePoints);
+                int expected = j;
+                if (j > 0 && j < length) {
+                    int cp = str.codePointBefore(j+1);
+                    if (Character.isSupplementaryCodePoint(cp)) {
+                        expected--;
+                    }
+                }
+                check(result != expected,
+                      "offsetByCodePoints(input["+i+"], "+j+", "+(-nCodePoints)+")",
+                      result, expected);
+            }
+            for (int j = length; j >= 0; j--) {
+                int nCodePoints = Character.codePointCount(str, 0, j);
+                int result = str.offsetByCodePoints(0, nCodePoints);
+                int expected = j;
+                if (j > 0 && j < length) {
+                    int cp = str.codePointAt(j-1);
+                     if (Character.isSupplementaryCodePoint(cp)) {
+                        expected++;
+                    }
+                }
+                check(result != expected,
+                      "offsetByCodePoints(input["+i+"], 0, "+nCodePoints+")",
+                      result, expected);
+                result = str.offsetByCodePoints(j, -nCodePoints);
+                check(result != 0,
+                      "offsetBycodePoints(input["+i+"], "+j+", "+(-nCodePoints)+")",
+                      result, 0);
+            }
+        }
+    }
+
+
+    static final boolean At = true, Before = false;
+    static final boolean First = true, Last = false;
+
+    static void testCodePoint(boolean isAt, String s, int index, int expected) {
+        int c = isAt ? s.codePointAt(index) : s.codePointBefore(index);
+
+        check(c != expected,
+              "codePoint" + (isAt ? "At" : "Before") + "(" + index + ") for <"
+              + s + ">", c, expected);
+    }
+
+    static void testCodePoint(boolean isAt, String s, int index) {
+        boolean exceptionOccurred = false;
+
+        try {
+            int c = isAt ? s.codePointAt(index) : s.codePointBefore(index);
+        }
+        catch (StringIndexOutOfBoundsException e) {
+            exceptionOccurred = true;
+        }
+        check(!exceptionOccurred,
+              "codePoint" + (isAt ? "At" : "Before") + "(" + index + ") for <"
+              + s + "> should throw StringIndexOutOfBoundsPointerException.");
+    }
+
+    static void testIndexOf(boolean isFirst, String s, int c, int expected) {
+        int index = isFirst ? s.indexOf(c) : s.lastIndexOf(c);
+
+        check(index != expected,
+              (isFirst ? "i" : "lastI") + "ndexOf(" + toHexString(c)
+              + ") for <" + s + ">", index, expected);
+    }
+
+    static int testIndexOf(boolean isFirst, String s, int fromIndex, int c,
+                           int expected) {
+        int index = isFirst ? s.indexOf(c, fromIndex) :
+                              s.lastIndexOf(c, fromIndex);
+
+        check(index != expected,
+              (isFirst ? "i" : "lastI") + "ndexOf(" + toHexString(c) + ", "
+              + fromIndex + ") for <" + s + ">", index, expected);
+
+        return index;
+    }
+
+    static void testNewString(int[] codePoints, int offset, int count, Class expectedException) {
+        try {
+            String s = new String(codePoints, offset, count);
+        } catch (Exception e) {
+            if (expectedException.isInstance(e)) {
+                return;
+            }
+            throw new RuntimeException("Error: Unexpected exception", e);
+        }
+        check(true, "new String(int[]...) didn't throw " + expectedException.getName());
+    }
+
+    static void testCodePointCount(String str, int beginIndex, int endIndex,
+                                   Class expectedException) {
+        try {
+            int n = str.codePointCount(beginIndex, endIndex);
+        } catch (Exception e) {
+            if (expectedException.isInstance(e)) {
+                return;
+            }
+            throw new RuntimeException("Error: Unexpected exception", e);
+        }
+        check(true, "codePointCount() didn't throw " + expectedException.getName());
+    }
+
+    static void testOffsetByCodePoints(String str, int index, int offset,
+                                       Class expectedException) {
+        try {
+            int n = str.offsetByCodePoints(index, offset);
+        } catch (Exception e) {
+            if (expectedException.isInstance(e)) {
+                return;
+            }
+            throw new RuntimeException("Error: Unexpected exception", e);
+        }
+        check(true, "offsetByCodePoints() didn't throw " + expectedException.getName());
+    }
+
+    static void check(boolean err, String msg) {
+        if (err) {
+            throw new RuntimeException("Error: " + msg);
+        }
+    }
+
+    static void check(boolean err, String s, int got, int expected) {
+        if (err) {
+            throw new RuntimeException("Error: " + s
+                                       + " returned an unexpected value. got "
+                                       + toHexString(got)
+                                       + ", expected "
+                                       + toHexString(expected));
+        }
+    }
+
+    private static String toHexString(int c) {
+        return "0x" + Integer.toHexString(c);
+    }
+}
diff --git a/jdk/test/java/lang/String/ToLowerCase.java b/jdk/test/java/lang/String/ToLowerCase.java
new file mode 100644
index 0000000..84d5d5a
--- /dev/null
+++ b/jdk/test/java/lang/String/ToLowerCase.java
@@ -0,0 +1,116 @@
+/*
+ * Copyright 2003 Sun Microsystems, Inc.  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 Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
+ * CA 95054 USA or visit www.sun.com if you need additional information or
+ * have any questions.
+ */
+
+/*
+    @test
+    @bug 4217441 4533872 4900935
+    @summary toLowerCase should lower-case Greek Sigma correctly depending
+             on the context (final/non-final).  Also it should handle
+             Locale specific (lt, tr, and az) lowercasings and supplementary
+             characters correctly.
+*/
+
+import java.util.Locale;
+
+public class ToLowerCase {
+
+    public static void main(String[] args) {
+        Locale turkish = new Locale("tr", "TR");
+        Locale lt = new Locale("lt"); // Lithanian
+        Locale az = new Locale("az"); // Azeri
+
+        // Greek Sigma final/non-final tests
+        test("\u03A3", Locale.US, "\u03C3");
+        test("LAST\u03A3", Locale.US, "last\u03C2");
+        test("MID\u03A3DLE", Locale.US, "mid\u03C3dle");
+        test("WORD1 \u03A3 WORD3", Locale.US, "word1 \u03C3 word3");
+        test("WORD1 LAST\u03A3 WORD3", Locale.US, "word1 last\u03C2 word3");
+        test("WORD1 MID\u03A3DLE WORD3", Locale.US, "word1 mid\u03C3dle word3");
+        test("\u0399\u0395\u03a3\u03a5\u03a3 \u03a7\u03a1\u0399\u03a3\u03a4\u039f\u03a3", Locale.US,
+             "\u03b9\u03b5\u03c3\u03c5\u03c2 \u03c7\u03c1\u03b9\u03c3\u03c4\u03bf\u03c2"); // "IESUS XRISTOS"
+
+        // Explicit dot above for I's and J's whenever there are more accents above (Lithanian)
+        test("I", lt, "i");
+        test("I\u0300", lt, "i\u0307\u0300"); // "I" followed by COMBINING GRAVE ACCENT (cc==230)
+        test("I\u0316", lt, "i\u0316"); // "I" followed by COMBINING GRAVE ACCENT BELOW (cc!=230)
+        test("J", lt, "j");
+        test("J\u0300", lt, "j\u0307\u0300"); // "J" followed by COMBINING GRAVE ACCENT (cc==230)
+        test("J\u0316", lt, "j\u0316"); // "J" followed by COMBINING GRAVE ACCENT BELOW (cc!=230)
+        test("\u012E", lt, "\u012F");
+        test("\u012E\u0300", lt, "\u012F\u0307\u0300"); // "I (w/ OGONEK)" followed by COMBINING GRAVE ACCENT (cc==230)
+        test("\u012E\u0316", lt, "\u012F\u0316"); // "I (w/ OGONEK)" followed by COMBINING GRAVE ACCENT BELOW (cc!=230)
+        test("\u00CC", lt, "i\u0307\u0300");
+        test("\u00CD", lt, "i\u0307\u0301");
+        test("\u0128", lt, "i\u0307\u0303");
+        test("I\u0300", Locale.US, "i\u0300"); // "I" followed by COMBINING GRAVE ACCENT (cc==230)
+        test("J\u0300", Locale.US, "j\u0300"); // "J" followed by COMBINING GRAVE ACCENT (cc==230)
+        test("\u012E\u0300", Locale.US, "\u012F\u0300"); // "I (w/ OGONEK)" followed by COMBINING GRAVE ACCENT (cc==230)
+        test("\u00CC", Locale.US, "\u00EC");
+        test("\u00CD", Locale.US, "\u00ED");
+        test("\u0128", Locale.US, "\u0129");
+
+        // I-dot tests (Turkish and Azeri)
+        test("\u0130", turkish, "i");
+        test("\u0130", az, "i");
+        test("\u0130", Locale.US, "i");
+
+        // Remove dot_above in the sequence I + dot_above (Turkish and Azeri)
+        test("I\u0307", turkish, "i");
+        test("I\u0307", az, "i");
+        test("J\u0307", turkish, "j\u0307");
+        test("J\u0307", az, "j\u0307");
+
+        // Unless an I is before a dot_above, it turns into a dotless i (Turkish and Azeri)
+        test("I", turkish, "\u0131");
+        test("I", az, "\u0131");
+        test("I", Locale.US, "i");
+        test("IABC", turkish, "\u0131abc");
+        test("IABC", az, "\u0131abc");
+        test("IABC", Locale.US, "iabc");
+
+        // Supplementary character tests
+        //
+        // U+10400 ("\uD801\uDC00"): DESERET CAPITAL LETTER LONG I
+        // U+10401 ("\uD801\uDC01"): DESERET CAPITAL LETTER LONG E
+        // U+10402 ("\uD801\uDC02"): DESERET CAPITAL LETTER LONG A
+        // U+10428 ("\uD801\uDC28"): DESERET SMALL LETTER LONG I
+        // U+10429 ("\uD801\uDC29"): DESERET SMALL LETTER LONG E
+        // U+1042A ("\uD801\uDC2A"): DESERET SMALL LETTER LONG A
+        //
+        // valid code point tests:
+        test("\uD801\uDC00\uD801\uDC01\uD801\uDC02", Locale.US, "\uD801\uDC28\uD801\uDC29\uD801\uDC2A");
+        test("\uD801\uDC00A\uD801\uDC01B\uD801\uDC02C", Locale.US, "\uD801\uDC28a\uD801\uDC29b\uD801\uDC2Ac");
+        // invalid code point tests:
+        test("\uD800\uD800\uD801A\uDC00\uDC00\uDC00B", Locale.US, "\uD800\uD800\uD801a\uDC00\uDC00\uDC00b");
+
+    }
+
+    static void test(String in, Locale locale, String expected) {
+        String result = in.toLowerCase(locale);
+        if (!result.equals(expected)) {
+            System.err.println("input: " + in + ", locale: " + locale +
+                    ", expected: " + expected + ", actual: " + result);
+            throw new RuntimeException();
+        }
+   }
+}
diff --git a/jdk/test/java/lang/String/ToUpperCase.java b/jdk/test/java/lang/String/ToUpperCase.java
new file mode 100644
index 0000000..a928f60
--- /dev/null
+++ b/jdk/test/java/lang/String/ToUpperCase.java
@@ -0,0 +1,104 @@
+/*
+ * Copyright 2000-2003 Sun Microsystems, Inc.  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 Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
+ * CA 95054 USA or visit www.sun.com if you need additional information or
+ * have any questions.
+ */
+
+/*
+    @test
+    @bug 4219630 4304573 4533872 4900935
+    @summary toUpperCase should upper-case German sharp s correctly even if
+             it's the only character in the string. should also uppercase
+             all of the 1:M char mappings correctly.  Also it should handle
+             Locale specific (lt, tr, and az) uppercasings and supplementary
+             characters correctly.
+*/
+
+import java.util.Locale;
+
+public class ToUpperCase {
+
+    public static void main(String[] args) {
+        Locale turkish = new Locale("tr", "TR");
+        Locale lt = new Locale("lt"); // Lithanian
+        Locale az = new Locale("az"); // Azeri
+
+        test("\u00DF", turkish, "SS");
+        test("a\u00DF", turkish, "ASS");
+        test("i", turkish, "\u0130");
+        test("i", az, "\u0130");
+        test("\u0131", turkish, "I");
+        test("\u00DF", Locale.GERMANY, "SS");
+        test("a\u00DF", Locale.GERMANY, "ASS");
+        test("i", Locale.GERMANY, "I");
+
+        // test some of the 1:M uppercase mappings
+        test("abc\u00DF", Locale.US, "ABC\u0053\u0053");
+        test("\u0149abc", Locale.US, "\u02BC\u004EABC");
+        test("\u0149abc", turkish, "\u02BC\u004EABC");
+        test("\u1F52", Locale.US, "\u03A5\u0313\u0300");
+        test("\u0149\u1F52", Locale.US, "\u02BC\u004E\u03A5\u0313\u0300");
+        test("\u1F54ZZZ", Locale.US, "\u03A5\u0313\u0301ZZZ");
+        test("\u1F54ZZZ", turkish, "\u03A5\u0313\u0301ZZZ");
+        test("a\u00DF\u1F56", Locale.US, "ASS\u03A5\u0313\u0342");
+        test("\u1FAD", turkish, "\u1F6D\u0399");
+        test("i\u1FC7", turkish, "\u0130\u0397\u0342\u0399");
+        test("i\u1FC7", az, "\u0130\u0397\u0342\u0399");
+        test("i\u1FC7", Locale.US, "I\u0397\u0342\u0399");
+        test("\uFB04", Locale.US, "\u0046\u0046\u004C");
+        test("\uFB17AbCdEfi", turkish, "\u0544\u053DABCDEF\u0130");
+        test("\uFB17AbCdEfi", az, "\u0544\u053DABCDEF\u0130");
+
+        // Remove DOT ABOVE after "i" in Lithuanian
+        test("i\u0307", lt, "I");
+        test("\u0307", lt, "\u0307");
+        test("\u0307i", lt, "\u0307I");
+        test("j\u0307", lt, "J");
+        test("abci\u0307def", lt, "ABCIDEF");
+        test("a\u0307", lt, "A\u0307");
+        test("abc\u0307def", lt, "ABC\u0307DEF");
+        test("i\u0307", Locale.US, "I\u0307");
+        test("i\u0307", turkish, "\u0130\u0307");
+
+        // Supplementary character tests
+        //
+        // U+10400 ("\uD801\uDC00"): DESERET CAPITAL LETTER LONG I
+        // U+10401 ("\uD801\uDC01"): DESERET CAPITAL LETTER LONG E
+        // U+10402 ("\uD801\uDC02"): DESERET CAPITAL LETTER LONG A
+        // U+10428 ("\uD801\uDC28"): DESERET SMALL LETTER LONG I
+        // U+10429 ("\uD801\uDC29"): DESERET SMALL LETTER LONG E
+        // U+1042A ("\uD801\uDC2A"): DESERET SMALL LETTER LONG A
+        //
+        // valid code point tests:
+        test("\uD801\uDC28\uD801\uDC29\uD801\uDC2A", Locale.US, "\uD801\uDC00\uD801\uDC01\uD801\uDC02");
+        test("\uD801\uDC28a\uD801\uDC29b\uD801\uDC2Ac", Locale.US, "\uD801\uDC00A\uD801\uDC01B\uD801\uDC02C");
+        // invalid code point tests:
+        test("\uD800\uD800\uD801a\uDC00\uDC00\uDC00b", Locale.US, "\uD800\uD800\uD801A\uDC00\uDC00\uDC00B");
+    }
+
+    static void test(String in, Locale locale, String expected) {
+        String result = in.toUpperCase(locale);
+        if (!result.equals(expected)) {
+            System.err.println("input: " + in + ", locale: " + locale +
+                    ", expected: " + expected + ", actual: " + result);
+            throw new RuntimeException();
+        }
+   }
+}
diff --git a/jdk/test/java/lang/StringBuffer/AppendCharSequence.java b/jdk/test/java/lang/StringBuffer/AppendCharSequence.java
new file mode 100644
index 0000000..05e3e62
--- /dev/null
+++ b/jdk/test/java/lang/StringBuffer/AppendCharSequence.java
@@ -0,0 +1,234 @@
+/*
+ * Copyright 2003-2004 Sun Microsystems, Inc.  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 Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
+ * CA 95054 USA or visit www.sun.com if you need additional information or
+ * have any questions.
+ */
+
+/* @test
+ * @bug 4812591 4705328 5019111
+ * @summary Test append and insert methods with CharSequence params
+ */
+
+import java.util.Random;
+
+public class AppendCharSequence {
+    private static Random generator = new Random();
+
+    public static void main(String[] args) throws Exception {
+        bash();
+        checkNulls();
+        checkOffsets();
+        checkConstructor();
+    }
+
+    // Sanity test of contents
+    private static void bash() throws Exception {
+        for (int i=0; i<1000; i++) {
+            StringBuffer sb1 = generateTestBuffer(0, 100);
+            StringBuffer sb2 = generateTestBuffer(0, 100);
+            StringBuffer sb3 = generateTestBuffer(0, 100);
+            StringBuffer sb4 = generateTestBuffer(0, 100);
+            StringBuffer sb5 = new StringBuffer();
+
+            String s1 = sb1.toString();
+            String s2 = sb2.toString();
+            String s3 = sb3.toString();
+            String s4 = sb4.toString();
+            String s5 = null;
+
+            // append(CharSequence cs)
+            sb5.append((CharSequence)sb1);
+            s5 = sb1.toString();
+
+            if (!sb5.toString().equals(s5))
+                throw new RuntimeException("StringBuffer.append failure 1");
+
+            // append (CharSequence cs, int start, int end)
+            int index = generator.nextInt(100);
+            int len = generator.nextInt(100);
+            while (index > sb2.length() - len) {
+                index = generator.nextInt(100);
+                len = generator.nextInt(100);
+            }
+            sb5.append((CharSequence)sb2, index, index + len);
+            s5 = s5 + sb2.toString().substring(index, index + len);
+
+            if (!sb5.toString().equals(s5))
+                throw new RuntimeException("StringBuffer.append failure 2");
+
+            // insert(int dstOffset, CharSequence cs)
+            index = generator.nextInt(100);
+            while (index > s5.length()) {
+                index = generator.nextInt(100);
+            }
+            sb5.insert(index, (CharSequence)sb3);
+            s5 = new StringBuffer(s5).insert(index, sb3).toString();
+
+            if (!sb5.toString().equals(s5))
+                throw new RuntimeException("StringBuffer.insert failure 1");
+
+            // insert(int dstOffset, CharSequence s, int start, int end)
+            int index1 = generator.nextInt(100);
+            while (index1 > s5.length()) {
+                index1 = generator.nextInt(100);
+            }
+            int index2 = generator.nextInt(100);
+            len = generator.nextInt(100);
+            while (index2 > sb4.length() - len) {
+                index2 = generator.nextInt(100);
+                len = generator.nextInt(100);
+            }
+            sb5.insert(index1, (CharSequence)sb4, index2, index2 + len);
+            s5 = new StringBuffer(s5).insert(index1, s4.toCharArray(),
+                                             index2, len).toString();
+
+            if (!sb5.toString().equals(s5))
+                throw new RuntimeException("StringBuffer.insert failure 2");
+        }
+    }
+
+    private static int getRandomIndex(int constraint1, int constraint2) {
+        int range = constraint2 - constraint1;
+        int x = generator.nextInt(range);
+        return constraint1 + x;
+    }
+
+    private static StringBuffer generateTestBuffer(int min, int max) {
+        StringBuffer aNewStringBuffer = new StringBuffer();
+        int aNewLength = getRandomIndex(min, max);
+        for(int y=0; y<aNewLength; y++) {
+            int achar = generator.nextInt(30)+30;
+            char test = (char)(achar);
+            aNewStringBuffer.append(test);
+        }
+        return aNewStringBuffer;
+    }
+
+    // Check handling of null as "null"
+    private static void checkNulls() throws Exception {
+        StringBuffer sb1 = new StringBuffer();
+        CharSequence cs = null;
+        sb1.append("test");
+        sb1.append(cs);
+        if (!sb1.toString().equals("testnull"))
+            throw new RuntimeException("StringBuffer.append failure 3");
+
+        sb1 = new StringBuffer();
+        sb1.append("test", 0, 2);
+        sb1.append(cs, 0, 2);
+        if (!sb1.toString().equals("tenu"))
+            throw new RuntimeException("StringBuffer.append failure 4");
+
+        sb1 = new StringBuffer("test");
+        sb1.insert(2, cs);
+        if (!sb1.toString().equals("tenullst"))
+            throw new RuntimeException("StringBuffer.insert failure 3");
+
+        sb1 = new StringBuffer("test");
+        sb1.insert(2, cs, 0, 2);
+        if (!sb1.toString().equals("tenust"))
+            throw new RuntimeException("StringBuffer.insert failure 4");
+    }
+
+    // Test the bounds checking
+    private static void checkOffsets() throws Exception {
+
+        // append (CharSeqeunce cs, int start, int end)
+        for (int i=0; i<100; i++) {
+            StringBuffer sb = generateTestBuffer(0, 80);
+            CharSequence cs = (CharSequence)generateTestBuffer(0, 80);
+            int index = 0;
+            int len = 0;
+            while (index <= cs.length() - len) {
+                index = generator.nextInt(100) - 50;
+                len = generator.nextInt(100) - 50;
+                if (index < 0)
+                    break;
+                if (len < 0)
+                    break;
+            }
+            try {
+                sb.append(cs, index, index + len);
+                throw new RuntimeException("Append bounds checking failure");
+            } catch (IndexOutOfBoundsException e) {
+                // Correct result
+            }
+        }
+
+        // insert(int dstOffset, CharSequence cs)
+        for (int i=0; i<100; i++) {
+            StringBuffer sb = new StringBuffer("test1");
+            CharSequence cs = (CharSequence)new StringBuffer("test2");
+            int index = 0;
+            while (index <= sb.length()) {
+                index = generator.nextInt(100) - 50;
+                if (index < 0)
+                    break;
+            }
+            try {
+                sb.insert(index, cs);
+                throw new RuntimeException("Insert bounds checking failure");
+            } catch (IndexOutOfBoundsException e) {
+                // Correct result
+            }
+        }
+
+        // insert(int dstOffset, CharSequence s, int start, int end)
+        for (int i=0; i<100; i++) {
+            StringBuffer sb = new StringBuffer("test1");
+            CharSequence cs = (CharSequence)new StringBuffer("test2");
+            int index1 = 0;
+            while (index1 <= sb.length()) {
+                index1 = generator.nextInt(100) - 50;
+                if (index1 < 0)
+                    break;
+            }
+            int index2 = 0;
+            int len = 0;
+            while (index2 < sb.length() - len) {
+                index2 = generator.nextInt(100) - 50;
+                len = generator.nextInt(100) - 50;
+                if (index2 < 0)
+                    break;
+                if (len < 0)
+                    break;
+            }
+            try {
+                sb.insert(index1, cs, index2, index2 + len);
+                throw new RuntimeException("Insert bounds checking failure");
+            } catch (IndexOutOfBoundsException e) {
+                // Correct result
+            }
+        }
+    }
+
+    // Test the CharSequence constructor
+    private static void checkConstructor() throws Exception {
+        for (int i=0; i<100; i++) {
+            StringBuffer sb = generateTestBuffer(0, 100);
+            CharSequence cs = (CharSequence)sb;
+            StringBuffer sb2 = new StringBuffer(cs);
+            if (!sb.toString().equals(sb2.toString())) {
+                throw new RuntimeException("CharSequence constructor failure");
+            }
+        }
+    }
+
+}
diff --git a/jdk/test/java/lang/StringBuffer/AppendSB.java b/jdk/test/java/lang/StringBuffer/AppendSB.java
new file mode 100644
index 0000000..32097d4
--- /dev/null
+++ b/jdk/test/java/lang/StringBuffer/AppendSB.java
@@ -0,0 +1,71 @@
+/*
+ * Copyright 2000 Sun Microsystems, Inc.  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 Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
+ * CA 95054 USA or visit www.sun.com if you need additional information or
+ * have any questions.
+ */
+
+/* @test
+ * @bug 4144267
+ * @summary Test StringBuffer.append(StringBuffer);
+ */
+
+import java.util.Random;
+
+public class AppendSB {
+    private static Random generator = new Random();
+
+    public static void main(String[] args) throws Exception {
+        for (int i=0; i<1000; i++) {
+            StringBuffer sb1 = generateTestBuffer(10, 100);
+            StringBuffer sb2 = generateTestBuffer(10, 100);
+            StringBuffer sb3 = generateTestBuffer(10, 100);
+            String s1 = sb1.toString();
+            String s2 = sb2.toString();
+            String s3 = sb3.toString();
+
+            String concatResult = new String(s1+s2+s3);
+
+            StringBuffer test = new StringBuffer();
+            test.append(sb1);
+            test.append(sb2);
+            test.append(sb3);
+
+            if (!test.toString().equals(concatResult))
+                throw new RuntimeException("StringBuffer.append failure");
+        }
+    }
+
+    private static int getRandomIndex(int constraint1, int constraint2) {
+        int range = constraint2 - constraint1;
+        int x = generator.nextInt(range);
+        return constraint1 + x;
+    }
+
+    private static StringBuffer generateTestBuffer(int min, int max) {
+        StringBuffer aNewStringBuffer = new StringBuffer(120);
+        int aNewLength = getRandomIndex(min, max);
+        for(int y=0; y<aNewLength; y++) {
+            int achar = generator.nextInt(30)+30;
+            char test = (char)(achar);
+            aNewStringBuffer.append(test);
+        }
+        return aNewStringBuffer;
+    }
+}
diff --git a/jdk/test/java/lang/StringBuffer/Exceptions.java b/jdk/test/java/lang/StringBuffer/Exceptions.java
new file mode 100644
index 0000000..40e08d5
--- /dev/null
+++ b/jdk/test/java/lang/StringBuffer/Exceptions.java
@@ -0,0 +1,124 @@
+/*
+ * Copyright 2002-2005 Sun Microsystems, Inc.  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 Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
+ * CA 95054 USA or visit www.sun.com if you need additional information or
+ * have any questions.
+ */
+
+/**
+ * @test
+ * @bug 4414306 6248507
+ * @summary Verify that exceptions are thrown as expected.
+ */
+
+public class Exceptions {
+    private static boolean ok = true;
+
+     private static void fail(Throwable ex, String s, Throwable got) {
+        ok = false;
+        System.err.println("expected "
+                           + ex.getClass().getName() + ": " + ex.getMessage()
+                           + " for " + s
+                           + " got "
+                           + got.getClass().getName() + ": " + got.getMessage()
+                           + " - FAILED");
+    }
+
+    private static void pass(String s) {
+        System.out.println(s + " -- OK");
+    }
+
+    private static void tryCatch(String s, Throwable ex, Runnable thunk) {
+        Throwable t = null;
+        try {
+            thunk.run();
+        } catch (Throwable x) {
+//          x.printStackTrace();
+            if (ex.getClass().isAssignableFrom(x.getClass()))
+                t = x;
+            else
+                x.printStackTrace();
+        }
+        if ((t == null) && (ex != null))
+            fail(ex, s, t);
+
+        String msg = (ex == null ? null : ex.getMessage());
+        if ((msg != null) && !msg.equals(t.getMessage()))
+            fail(ex, s, t);
+        else
+            pass(s);
+    }
+
+    public static void main(String [] args) {
+        System.out.println("StringBuffer()");
+        tryCatch("  no args", null, new Runnable() {
+                public void run() {
+                    new StringBuffer();
+                }});
+
+        System.out.println("StringBuffer(int length)");
+        tryCatch("  1", null, new Runnable() {
+                public void run() {
+                    new StringBuffer(1);
+                }});
+        tryCatch("  -1", new NegativeArraySizeException(), new Runnable() {
+                public void run() {
+                    new StringBuffer(-1);
+                }});
+
+        System.out.println("StringBuffer(String str)");
+        tryCatch("  null", new NullPointerException(), new Runnable() {
+                public void run() {
+                    new StringBuffer(null);
+                }});
+        tryCatch("  foo", null, new Runnable() {
+                public void run() {
+                    new StringBuffer("foo");
+                }});
+
+        System.out.println("StringBuffer.replace(int start, int end, String str)");
+        tryCatch("  -1, 2, \" \"",
+                 new StringIndexOutOfBoundsException(-1),
+                 new Runnable() {
+                public void run() {
+                    StringBuffer sb = new StringBuffer("hilbert");
+                    sb.replace(-1, 2, " ");
+                }});
+
+        tryCatch("  7, 8, \" \"",
+                 new StringIndexOutOfBoundsException("start > length()"),
+                 new Runnable() {
+                public void run() {
+                    StringBuffer sb = new StringBuffer("banach");
+                    sb.replace(7, 8, " ");
+                }});
+        tryCatch("  2, 1, \" \"",
+                 new StringIndexOutOfBoundsException("start > end"),
+                 new Runnable() {
+                public void run() {
+                    StringBuffer sb = new StringBuffer("riemann");
+                    sb.replace(2, 1, " ");
+                }});
+
+        if (!ok)
+            throw new RuntimeException("Some tests FAILED");
+        else
+            System.out.println("All tests PASSED");
+    }
+}
diff --git a/jdk/test/java/lang/StringBuffer/GetCharsOverLength.java b/jdk/test/java/lang/StringBuffer/GetCharsOverLength.java
new file mode 100644
index 0000000..76b4e38
--- /dev/null
+++ b/jdk/test/java/lang/StringBuffer/GetCharsOverLength.java
@@ -0,0 +1,56 @@
+/*
+ * Copyright 1999 Sun Microsystems, Inc.  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 Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
+ * CA 95054 USA or visit www.sun.com if you need additional information or
+ * have any questions.
+ */
+
+/**
+ * @test
+ * @bug 4230290
+ * @summary Test GetChars method parameter checking
+ */
+
+public class GetCharsOverLength {
+
+   public static void main (String argv[]) {
+
+    StringBuffer sb = new StringBuffer("sample string buffer");
+    char dst[] = new char[30];
+    boolean failed = false;
+
+    int a[][] = {
+                  {0, 0, dst.length + 1},
+                  {0, 0, dst.length + 2},
+                  {0, 0, dst.length + 20},
+                  {5, 5, dst.length + 1},
+                  {5, 5, dst.length + 2},
+                  {5, 5, dst.length + 20}
+    };
+
+    for (int i = 0; i < a.length; i++) {
+        try {
+            sb.getChars(a[i][0], a[i][1], dst, a[i][2]);
+            throw new RuntimeException("Bounds test failed");
+        } catch (IndexOutOfBoundsException iobe) {
+            // Test passed
+        }
+    }
+  }
+}
diff --git a/jdk/test/java/lang/StringBuffer/GetCharsSrcEndLarger.java b/jdk/test/java/lang/StringBuffer/GetCharsSrcEndLarger.java
new file mode 100644
index 0000000..b4f0000
--- /dev/null
+++ b/jdk/test/java/lang/StringBuffer/GetCharsSrcEndLarger.java
@@ -0,0 +1,43 @@
+/*
+ * Copyright 1998 Sun Microsystems, Inc.  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 Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
+ * CA 95054 USA or visit www.sun.com if you need additional information or
+ * have any questions.
+ */
+
+/* @test
+   @bug 4096341
+   @summary StringBuffer.getChars(): JLS requires exception if
+            srcBegin > srcEnd
+   @author Anand Palaniswamy
+ */
+public class GetCharsSrcEndLarger {
+    public static void main(String[] args) throws Exception {
+        boolean exceptionOccurred = false;
+        try {
+            new StringBuffer("abc").getChars(1, 0, new char[10], 0);
+        } catch (StringIndexOutOfBoundsException sioobe) {
+            exceptionOccurred = true;
+        }
+        if (!exceptionOccurred) {
+            throw new Exception("StringBuffer.getChars() must throw" +
+                                " an exception if srcBegin > srcEnd");
+        }
+    }
+}
diff --git a/jdk/test/java/lang/StringBuffer/IndexOf.java b/jdk/test/java/lang/StringBuffer/IndexOf.java
new file mode 100644
index 0000000..c19497c
--- /dev/null
+++ b/jdk/test/java/lang/StringBuffer/IndexOf.java
@@ -0,0 +1,187 @@
+/*
+ * Copyright 2000 Sun Microsystems, Inc.  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 Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
+ * CA 95054 USA or visit www.sun.com if you need additional information or
+ * have any questions.
+ */
+
+/* @test
+ * @bug 4162796 4162796
+ * @summary Test indexOf and lastIndexOf
+ */
+
+import java.util.Random;
+
+public class IndexOf {
+
+    static Random generator = new Random();
+    private static boolean failure = false;
+
+    public static void main(String[] args) throws Exception {
+        simpleTest();
+        compareIndexOfLastIndexOf();
+        compareStringStringBuffer();
+
+        if (failure)
+           throw new RuntimeException("One or more BitSet failures.");
+    }
+
+    private static void report(String testName, int failCount) {
+        System.err.println(testName+": " +
+                         (failCount==0 ? "Passed":"Failed("+failCount+")"));
+        if (failCount > 0)
+            failure = true;
+    }
+
+    private static String generateTestString(int min, int max) {
+        StringBuffer aNewString = new StringBuffer(120);
+        int aNewLength = getRandomIndex(min, max);
+        for(int y=0; y<aNewLength; y++) {
+            int achar = generator.nextInt(30)+30;
+            char test = (char)(achar);
+            aNewString.append(test);
+        }
+        return aNewString.toString();
+    }
+
+    private static int getRandomIndex(int constraint1, int constraint2) {
+        int range = constraint2 - constraint1;
+        int x = generator.nextInt(range);
+        return constraint1 + x;
+    }
+
+    private static void simpleTest() {
+        int failCount = 0;
+        String sourceString;
+        StringBuffer sourceBuffer;
+        String targetString;
+
+        for (int i=0; i<10000; i++) {
+            do {
+                sourceString = generateTestString(99, 100);
+                sourceBuffer = new StringBuffer(sourceString);
+                targetString = generateTestString(10, 11);
+            } while (sourceString.indexOf(targetString) != -1);
+
+            int index1 = generator.nextInt(90) + 5;
+            sourceBuffer = sourceBuffer.replace(index1, index1, targetString);
+
+            if (sourceBuffer.indexOf(targetString) != index1)
+                failCount++;
+            if (sourceBuffer.indexOf(targetString, 5) != index1)
+                failCount++;
+            if (sourceBuffer.indexOf(targetString, 99) == index1)
+                failCount++;
+        }
+
+        report("Basic Test                   ", failCount);
+    }
+
+    // Note: it is possible although highly improbable that failCount will
+    // be > 0 even if everthing is working ok
+    private static void compareIndexOfLastIndexOf() {
+        int failCount = 0;
+        String sourceString;
+        StringBuffer sourceBuffer;
+        String targetString;
+
+        for (int i=0; i<10000; i++) {
+            do {
+                sourceString = generateTestString(99, 100);
+                sourceBuffer = new StringBuffer(sourceString);
+                targetString = generateTestString(10, 11);
+            } while (sourceString.indexOf(targetString) != -1);
+
+            int index1 = generator.nextInt(100);
+            sourceBuffer = sourceBuffer.replace(index1, index1, targetString);
+
+            // extremely remote possibility of > 1 match
+            int matches = 0;
+            int index2 = -1;
+            while((index2 = sourceBuffer.indexOf(targetString,index2+1)) != -1)
+                matches++;
+            if (matches > 1)
+                continue;
+
+            if (sourceBuffer.indexOf(targetString) !=
+                sourceBuffer.lastIndexOf(targetString))
+                failCount++;
+            sourceString = sourceBuffer.toString();
+            if (sourceString.indexOf(targetString) !=
+                sourceString.lastIndexOf(targetString))
+                failCount++;
+        }
+
+        report("IndexOf vs LastIndexOf       ", failCount);
+    }
+
+    private static void compareStringStringBuffer() {
+        int failCount = 0;
+
+        for (int x=0; x<10000; x++) {
+            String testString = generateTestString(1, 100);
+            int len = testString.length();
+
+            StringBuffer testBuffer = new StringBuffer(len);
+            testBuffer.append(testString);
+            if (!testString.equals(testBuffer.toString()))
+                throw new RuntimeException("Initial equality failure");
+
+            int x1 = 0;
+            int x2 = 1000;
+            while(x2 > testString.length()) {
+                x1 = generator.nextInt(len);
+                x2 = generator.nextInt(100);
+                x2 = x1 + x2;
+            }
+            String fragment = testString.substring(x1,x2);
+
+            int sAnswer = testString.indexOf(fragment);
+            int sbAnswer = testBuffer.indexOf(fragment);
+
+            if (sAnswer != sbAnswer)
+                failCount++;
+
+            int testIndex = getRandomIndex(-100, 100);
+
+            sAnswer = testString.indexOf(fragment, testIndex);
+            sbAnswer = testBuffer.indexOf(fragment, testIndex);
+
+            if (sAnswer != sbAnswer)
+                failCount++;
+
+            sAnswer = testString.lastIndexOf(fragment);
+            sbAnswer = testBuffer.lastIndexOf(fragment);
+
+            if (sAnswer != sbAnswer)
+                failCount++;
+
+            testIndex = getRandomIndex(-100, 100);
+
+            sAnswer = testString.lastIndexOf(fragment, testIndex);
+            sbAnswer = testBuffer.lastIndexOf(fragment, testIndex);
+
+            if (sAnswer != sbAnswer)
+                failCount++;
+        }
+
+        report("String vs StringBuffer       ", failCount);
+    }
+
+}
diff --git a/jdk/test/java/lang/StringBuffer/InsertMaxValue.java b/jdk/test/java/lang/StringBuffer/InsertMaxValue.java
new file mode 100644
index 0000000..3466d18
--- /dev/null
+++ b/jdk/test/java/lang/StringBuffer/InsertMaxValue.java
@@ -0,0 +1,54 @@
+/*
+ * Copyright 1999 Sun Microsystems, Inc.  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 Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
+ * CA 95054 USA or visit www.sun.com if you need additional information or
+ * have any questions.
+ */
+
+/**
+ * @test
+ * @bug 4231107
+ * @summary Test Insert method parameter checking
+ */
+
+public class InsertMaxValue {
+
+   public static void main (String argv[]) throws Exception {
+       StringBuffer sb = new StringBuffer("");
+       StringBuffer sb1 = new StringBuffer("Some test StringBuffer");
+
+       try {
+           sb.insert(0, new char[5], 1, Integer.MAX_VALUE);
+           throw new RuntimeException("Exception expected");
+       } catch (StringIndexOutOfBoundsException sobe) {
+           // Test passed
+       } catch (OutOfMemoryError oome) {
+           throw new RuntimeException("Wrong exception thrown.");
+       }
+
+       try {
+           sb1.insert(2, new char[25], 5, Integer.MAX_VALUE);
+           throw new RuntimeException("Exception expected");
+       } catch (StringIndexOutOfBoundsException sobe) {
+           // Test passed
+       } catch (ArrayIndexOutOfBoundsException aioe) {
+           throw new RuntimeException("Wrong exception thrown.");
+       }
+   }
+}
diff --git a/jdk/test/java/lang/StringBuffer/InsertNullString.java b/jdk/test/java/lang/StringBuffer/InsertNullString.java
new file mode 100644
index 0000000..d14847f
--- /dev/null
+++ b/jdk/test/java/lang/StringBuffer/InsertNullString.java
@@ -0,0 +1,45 @@
+/*
+ * Copyright 1998 Sun Microsystems, Inc.  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 Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
+ * CA 95054 USA or visit www.sun.com if you need additional information or
+ * have any questions.
+ */
+
+/* @test
+   @bug 4085679
+   @summary JLS requires that if you insert a null string, the string
+            "null" must be inserted.
+   @author Anand Palaniswamy
+ */
+public class InsertNullString {
+    public static void main(String[] args) throws Exception {
+        StringBuffer s = new StringBuffer("FOOBAR");
+
+        try {
+            String nullstr = null;
+            s.insert(3, nullstr); /* this will throw null pointer exception
+                                  before the bug was fixed. */
+            if (!s.toString().equals("FOOnullBAR")) {
+                throw new Exception("StringBuffer.insert() did not insert!");
+            }
+        } catch (NullPointerException npe) {
+            throw new Exception("StringBuffer.insert() of null String reference threw a NullPointerException");
+        }
+    }
+}
diff --git a/jdk/test/java/lang/StringBuffer/Replace.java b/jdk/test/java/lang/StringBuffer/Replace.java
new file mode 100644
index 0000000..63f6df8
--- /dev/null
+++ b/jdk/test/java/lang/StringBuffer/Replace.java
@@ -0,0 +1,36 @@
+/*
+ * Copyright 1998 Sun Microsystems, Inc.  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 Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
+ * CA 95054 USA or visit www.sun.com if you need additional information or
+ * have any questions.
+ */
+
+/* @test
+   @bug 4174396
+   @summary Use replace to append chars; No OutOfMemoryException should result
+*/
+
+public class Replace {
+    public static void main(String[] arg) throws Exception {
+        StringBuffer sb = new StringBuffer();
+        for (int i = 0; i < 200; i++) {
+            sb.replace(i, i+1, "a");
+        }
+    }
+}
diff --git a/jdk/test/java/lang/StringBuffer/SBBasher.java b/jdk/test/java/lang/StringBuffer/SBBasher.java
new file mode 100644
index 0000000..6141128
--- /dev/null
+++ b/jdk/test/java/lang/StringBuffer/SBBasher.java
@@ -0,0 +1,162 @@
+/*
+ * Copyright 1998 Sun Microsystems, Inc.  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 Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
+ * CA 95054 USA or visit www.sun.com if you need additional information or
+ * have any questions.
+ */
+
+/*
+ * @test
+ * @bug 4120694
+ * @summary Test new methods in StringBuffer
+ *
+ */
+
+import java.lang.*;
+import java.util.*;
+
+public class SBBasher {
+    public static void main(String[] args) throws Exception {
+        SBBasher basher = new SBBasher();
+
+        for (int iterations=0; iterations<100; iterations++) {
+            String testString = basher.generateTestString();
+            boolean result = basher.Test1(testString);
+            if (result == false)
+                throw new RuntimeException("Substring or replace failure.");
+        }
+
+        for (int iterations=0; iterations<100; iterations++) {
+            String testString = basher.generateTestString();
+            boolean result = basher.Test2(testString);
+            if (result == false)
+                throw new RuntimeException("Insert or delete failure.");
+        }
+
+        for (int iterations=0; iterations<100; iterations++) {
+            String testString = basher.generateTestString();
+            boolean result = basher.Test3(testString);
+            if (result == false)
+              throw new RuntimeException("Insert, delete or replace failure.");
+        }
+
+    }
+
+    private int getRandomIndex(int constraint1, int constraint2) {
+        int range = constraint2 - constraint1;
+        int x = generator.nextInt();
+        return constraint1 + Math.abs(x % range);
+    }
+
+    static Random generator = new Random();
+
+    private String generateTestString() {
+        StringBuffer aNewString = new StringBuffer(120);
+        int aNewLength = getRandomIndex(1,100);
+        for(int y=0; y<aNewLength; y++) {
+            int achar = generator.nextInt();
+            char test = (char)(achar);
+            aNewString.append(test);
+        }
+        return aNewString.toString();
+    }
+
+    /**
+     * first test, get substring of a random string
+     * and replace same spot with same substring
+     * then check for equality with original
+     * this tests both substrings and the replace method
+     */
+    private boolean Test1(String before) {
+        StringBuffer bashed = new StringBuffer(before);
+        String slice;
+        for (int i=0; i<100; i++) {
+            int startIndex = getRandomIndex(0, before.length());
+            int endIndex = getRandomIndex(startIndex, before.length());
+            if (endIndex < bashed.length()) {
+                slice = bashed.substring(startIndex, endIndex);
+            }
+            else {
+                slice = bashed.substring(startIndex);
+            }
+            bashed.replace(startIndex, endIndex, slice);
+        }
+        String after = bashed.toString();
+        if (!before.equals(after))
+            return false;
+        else
+            return true;
+    }
+
+    /**
+     * second test, delete random section of string
+     * then insert same section back again
+     * then check for equality with original
+     * this tests both substrings, both deletes and insert method
+     */
+    private boolean Test2(String before) {
+        StringBuffer bashed = new StringBuffer(before);
+        String slice;
+        for (int i=0; i<100; i++) {
+            int startIndex = getRandomIndex(0, before.length());
+            int endIndex = getRandomIndex(startIndex, before.length());
+            if (endIndex < bashed.length())
+                slice = bashed.substring(startIndex, endIndex);
+            else
+                slice = bashed.substring(startIndex);
+            if (slice.length() == 1)
+                bashed.deleteCharAt(startIndex);
+            else
+                bashed.delete(startIndex, endIndex);
+            bashed.insert(startIndex, slice.toCharArray(), 0, slice.length());
+        }
+        String after = bashed.toString();
+        if (!before.equals(after))
+            return false;
+        else
+            return true;
+    }
+
+    /**
+     * Third test, clone string and make sure that the
+     * replace operation is equivalent to a delete followed
+     * by an insert with the equivalent arguments
+     * this tests replace, delete and insert
+     */
+    private boolean Test3(String before) {
+        StringBuffer bashed1 = new StringBuffer(before);
+        StringBuffer bashed2 = new StringBuffer(before);
+        int startIndex = getRandomIndex(0, bashed1.length());
+        int endIndex = getRandomIndex(startIndex, bashed2.length());
+
+        String insertString = generateTestString();
+
+        bashed1.delete(startIndex, endIndex);
+        bashed1.insert(startIndex, insertString);
+        bashed2.replace(startIndex, endIndex, insertString);
+
+        String result1 = bashed1.toString();
+        String result2 = bashed2.toString();
+        if (!result1.equals(result2))
+            return false;
+        else
+            return true;
+    }
+
+}
diff --git a/jdk/test/java/lang/StringBuffer/SetLength.java b/jdk/test/java/lang/StringBuffer/SetLength.java
new file mode 100644
index 0000000..557e234
--- /dev/null
+++ b/jdk/test/java/lang/StringBuffer/SetLength.java
@@ -0,0 +1,47 @@
+/*
+ * Copyright 1997 Sun Microsystems, Inc.  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 Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
+ * CA 95054 USA or visit www.sun.com if you need additional information or
+ * have any questions.
+ */
+
+/* @test
+   @bug 4089062
+   @summary A String created from a StringBuffer can be overwritten
+   if setLength() to a value less than the buffer length is called
+   on the StringBuffer and then the StringBuffer is appended to.
+   @author Robert Field
+*/
+
+public class SetLength {
+    public static void main(String[] argv) throws Exception {
+        StringBuffer active = new StringBuffer();
+        active.append("first one");
+        String a = active.toString();
+        active.setLength(0);
+        active.append("second");
+        String b = active.toString();
+        active.setLength(0);
+        System.out.println("first: " + a);
+        System.out.println("second: " + b);
+        if (!a.equals("first one")) {
+            throw new Exception("StringBuffer.setLength() overwrote string");
+        }
+    }
+}
diff --git a/jdk/test/java/lang/StringBuffer/Substring.java b/jdk/test/java/lang/StringBuffer/Substring.java
new file mode 100644
index 0000000..849cfef
--- /dev/null
+++ b/jdk/test/java/lang/StringBuffer/Substring.java
@@ -0,0 +1,36 @@
+/*
+ * Copyright 2003 Sun Microsystems, Inc.  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 Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
+ * CA 95054 USA or visit www.sun.com if you need additional information or
+ * have any questions.
+ */
+
+/* @test
+ * @bug 4853816
+ * @summary Test StringBuffer.substring(int)
+ */
+
+public class Substring {
+    public static void main(String[] args) {
+        StringBuffer buffer = new StringBuffer();
+        buffer.append("Guten Morgen!");
+        if (buffer.substring(0).length() != 13)
+            throw new RuntimeException();
+    }
+}
diff --git a/jdk/test/java/lang/StringBuffer/Supplementary.java b/jdk/test/java/lang/StringBuffer/Supplementary.java
new file mode 100644
index 0000000..0dd9dd6
--- /dev/null
+++ b/jdk/test/java/lang/StringBuffer/Supplementary.java
@@ -0,0 +1,417 @@
+/*
+ * Copyright 2003-2004 Sun Microsystems, Inc.  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 Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
+ * CA 95054 USA or visit www.sun.com if you need additional information or
+ * have any questions.
+ */
+
+/*
+ *
+ * @test
+ * @bug 4533872 4915683 4985217 5017280
+ * @summary Unit tests for supplementary character support (JSR-204)
+ */
+
+public class Supplementary {
+
+    public static void main(String[] args) {
+        test1();        // Test for codePointAt(int index)
+        test2();        // Test for codePointBefore(int index)
+        test3();        // Test for reverse()
+        test4();        // Test for appendCodePoint(int codePoint)
+        test5();        // Test for codePointCount(int beginIndex, int endIndex)
+        test6();        // Test for offsetByCodePoints(int index, int offset)
+    }
+
+    /* Text strings which are used as input data.
+     * The comment above each text string means the index of each 16-bit char
+     * for convenience.
+     */
+    static final String[] input = {
+      /*                               111     1     111111     22222
+         0123     4     5678     9     012     3     456789     01234 */
+        "abc\uD800\uDC00def\uD800\uD800ab\uD800\uDC00cdefa\uDC00bcdef",
+      /*                          1     1111     1111     1     222
+         0     12345     6789     0     1234     5678     9     012     */
+        "\uD800defg\uD800hij\uD800\uDC00klm\uDC00nop\uDC00\uD800rt\uDC00",
+      /*                          11     1     1111     1     112     222
+         0     12345     6     78901     2     3456     7     890     123     */
+        "\uDC00abcd\uDBFF\uDFFFefgh\uD800\uDC009ik\uDC00\uDC00lm\uDC00no\uD800",
+      /*                                    111     111111     1 22     2
+         0     1     2345     678     9     012     345678     9 01     2     */
+        "\uD800\uDC00!#$\uD800%&\uD800\uDC00;+\uDC00<>;=^\uDC00\\@\uD800\uDC00",
+
+        // includes an undefined supprementary characters in Unicode 4.0.0
+      /*                                    1     11     1     1111     1
+         0     1     2345     6     789     0     12     3     4567     8     */
+        "\uDB40\uDE00abc\uDE01\uDB40de\uDB40\uDE02f\uDB40\uDE03ghi\uDB40\uDE02",
+    };
+
+
+    /* Expected results for:
+     *     test1(): for codePointAt()
+     *
+     * Each character in each array is the golden data for each text string
+     * in the above input data. For example, the first data in each array is
+     * for the first input string.
+     */
+    static final int[][] golden1 = {
+        {'a',    0xD800, 0xDC00,  0x10000, 0xE0200}, // codePointAt(0)
+        {0xD800, 0x10000, 'g',    0xDC00,  0xE0202}, // codePointAt(9)
+        {'f',    0xDC00,  0xD800, 0xDC00,  0xDE02},  // codePointAt(length-1)
+    };
+
+    /*
+     * Test for codePointAt(int index) method
+     */
+    static void test1() {
+
+        for (int i = 0; i < input.length; i++) {
+            StringBuffer sb = new StringBuffer(input[i]);
+
+            /*
+             * Normal case
+             */
+            testCodePoint(At, sb, 0, golden1[0][i]);
+            testCodePoint(At, sb, 9, golden1[1][i]);
+            testCodePoint(At, sb, sb.length()-1, golden1[2][i]);
+
+            /*
+             * Abnormal case - verify that an exception is thrown.
+             */
+            testCodePoint(At, sb, -1);
+            testCodePoint(At, sb, sb.length());
+        }
+    }
+
+
+    /* Expected results for:
+     *     test2(): for codePointBefore()
+     *
+     * Each character in each array is the golden data for each text string
+     * in the above input data. For example, the first data in each array is
+     * for the first input string.
+     */
+    static final int[][] golden2 = {
+        {'a',    0xD800, 0xDC00,  0xD800,  0xDB40},  // codePointBefore(1)
+        {0xD800, 'l',    0x10000, 0xDC00,  0xDB40},  // codePointBefore(13)
+        {'f',    0xDC00, 0xD800,  0x10000, 0xE0202}, // codePointBefore(length)
+    };
+
+    /*
+     * Test for codePointBefore(int index) method
+     */
+    static void test2() {
+
+        for (int i = 0; i < input.length; i++) {
+            StringBuffer sb = new StringBuffer(input[i]);
+
+            /*
+             * Normal case
+             */
+            testCodePoint(Before, sb, 1, golden2[0][i]);
+            testCodePoint(Before, sb, 13, golden2[1][i]);
+            testCodePoint(Before, sb, sb.length(), golden2[2][i]);
+
+            /*
+             * Abnormal case - verify that an exception is thrown.
+             */
+            testCodePoint(Before, sb, 0);
+            testCodePoint(Before, sb, sb.length()+1);
+        }
+    }
+
+
+    /* Expected results for:
+     *     test3(): for reverse()
+     *
+     * Unlike golden1 and golden2, each array is the golden data for each text
+     * string in the above input data. For example, the first array is  for
+     * the first input string.
+     */
+    static final String[] golden3 = {
+        "fedcb\uDC00afedc\uD800\uDC00ba\uD800\uD800fed\uD800\uDC00cba",
+        "\uDC00tr\uD800\uDC00pon\uDC00mlk\uD800\uDC00jih\uD800gfed\uD800",
+        "\uD800on\uDC00ml\uDC00\uDC00ki9\uD800\uDC00hgfe\uDBFF\uDFFFdcba\uDC00",
+        "\uD800\uDC00@\\\uDC00^=;><\uDC00+;\uD800\uDC00&%\uD800$#!\uD800\uDC00",
+
+        // includes an undefined supprementary characters in Unicode 4.0.0
+        "\uDB40\uDE02ihg\uDB40\uDE03f\uDB40\uDE02ed\uDB40\uDE01cba\uDB40\uDE00",
+    };
+
+    // Additional input data & expected result for test3()
+    static final String[][] testdata1 = {
+        {"a\uD800\uDC00", "\uD800\uDC00a"},
+        {"a\uDC00\uD800", "\uD800\uDC00a"},
+        {"\uD800\uDC00a", "a\uD800\uDC00"},
+        {"\uDC00\uD800a", "a\uD800\uDC00"},
+        {"\uDC00\uD800\uD801", "\uD801\uD800\uDC00"},
+        {"\uDC00\uD800\uDC01", "\uD800\uDC01\uDC00"},
+        {"\uD801\uD800\uDC00", "\uD800\uDC00\uD801"},
+        {"\uD800\uDC01\uDC00", "\uDC00\uD800\uDC01"},
+        {"\uD800\uDC00\uDC01\uD801", "\uD801\uDC01\uD800\uDC00"},
+    };
+
+    /*
+     * Test for reverse() method
+     */
+    static void test3() {
+        for (int i = 0; i < input.length; i++) {
+            StringBuffer sb = new StringBuffer(input[i]).reverse();
+
+            check(!golden3[i].equals(new String(sb)),
+                 "reverse() for <" + toHexString(input[i]) + ">",
+                 sb, golden3[i]);
+        }
+
+        for (int i = 0; i < testdata1.length; i++) {
+            StringBuffer sb = new StringBuffer(testdata1[i][0]).reverse();
+
+            check(!testdata1[i][1].equals(new String(sb)),
+                 "reverse() for <" + toHexString(testdata1[i][0]) + ">",
+                 sb, testdata1[i][1]);
+        }
+    }
+
+    /**
+     * Test for appendCodePoint() method
+     */
+    static void test4() {
+        for (int i = 0; i < input.length; i++) {
+            String s = input[i];
+            StringBuffer sb = new StringBuffer();
+            int c;
+            for (int j = 0; j < s.length(); j += Character.charCount(c)) {
+                c = s.codePointAt(j);
+                StringBuffer rsb = sb.appendCodePoint(c);
+                check(sb != rsb, "appendCodePoint returned a wrong object");
+                int sbc = sb.codePointAt(j);
+                check(sbc != c, "appendCodePoint(j) != c", sbc, c);
+            }
+            check(!s.equals(sb.toString()),
+                  "appendCodePoint() produced a wrong result with input["+i+"]");
+        }
+
+        // test exception
+        testAppendCodePoint(-1, IllegalArgumentException.class);
+        testAppendCodePoint(Character.MAX_CODE_POINT+1, IllegalArgumentException.class);
+    }
+
+    /**
+     * Test codePointCount(int, int)
+     *
+     * This test case assumes that
+     * Character.codePointCount(CharSequence, int, int) works
+     * correctly.
+     */
+    static void test5() {
+        for (int i = 0; i < input.length; i++) {
+            String s = input[i];
+            StringBuffer sb = new StringBuffer(s);
+            int length = sb.length();
+            for (int j = 0; j <= length; j++) {
+                int result = sb.codePointCount(j, length);
+                int expected = Character.codePointCount(sb, j, length);
+                check(result != expected, "codePointCount(input["+i+"], "+j+", "+length+")",
+                      result, expected);
+            }
+            for (int j = length; j >= 0; j--) {
+                int result = sb.codePointCount(0, j);
+                int expected = Character.codePointCount(sb, 0, j);
+                check(result != expected, "codePointCount(input["+i+"], 0, "+j+")",
+                      result, expected);
+            }
+
+            // test exceptions
+            testCodePointCount(null, 0, 0, NullPointerException.class);
+            testCodePointCount(sb, -1, length, IndexOutOfBoundsException.class);
+            testCodePointCount(sb, 0, length+1, IndexOutOfBoundsException.class);
+            testCodePointCount(sb, length, length-1, IndexOutOfBoundsException.class);
+        }
+    }
+
+    /**
+     * Test offsetByCodePoints(int, int)
+     *
+     * This test case assumes that
+     * Character.codePointCount(CharSequence, int, int) works
+     * correctly.
+     */
+    static void test6() {
+        for (int i = 0; i < input.length; i++) {
+            String s = input[i];
+            StringBuffer sb = new StringBuffer(s);
+            int length = s.length();
+            for (int j = 0; j <= length; j++) {
+                int nCodePoints = Character.codePointCount(sb, j, length);
+                int result = sb.offsetByCodePoints(j, nCodePoints);
+                check(result != length,
+                      "offsetByCodePoints(input["+i+"], "+j+", "+nCodePoints+")",
+                      result, length);
+                result = sb.offsetByCodePoints(length, -nCodePoints);
+                int expected = j;
+                if (j > 0 && j < length) {
+                    int cp = sb.codePointBefore(j+1);
+                    if (Character.isSupplementaryCodePoint(cp)) {
+                        expected--;
+                    }
+                }
+                check(result != expected,
+                      "offsetByCodePoints(input["+i+"], "+j+", "+(-nCodePoints)+")",
+                      result, expected);
+            }
+            for (int j = length; j >= 0; j--) {
+                int nCodePoints = Character.codePointCount(sb, 0, j);
+                int result = sb.offsetByCodePoints(0, nCodePoints);
+                int expected = j;
+                if (j > 0 && j < length) {
+                    int cp = sb.codePointAt(j-1);
+                     if (Character.isSupplementaryCodePoint(cp)) {
+                        expected++;
+                    }
+                }
+                check(result != expected,
+                      "offsetByCodePoints(input["+i+"], 0, "+nCodePoints+")",
+                      result, expected);
+                result = sb.offsetByCodePoints(j, -nCodePoints);
+                check(result != 0,
+                      "offsetBycodePoints(input["+i+"], "+j+", "+(-nCodePoints)+")",
+                      result, 0);
+            }
+
+            // test exceptions
+            testOffsetByCodePoints(null, 0, 0, NullPointerException.class);
+            testOffsetByCodePoints(sb, -1, length, IndexOutOfBoundsException.class);
+            testOffsetByCodePoints(sb, 0, length+1, IndexOutOfBoundsException.class);
+            testOffsetByCodePoints(sb, 1, -2, IndexOutOfBoundsException.class);
+            testOffsetByCodePoints(sb, length, length-1, IndexOutOfBoundsException.class);
+            testOffsetByCodePoints(sb, length, -(length+1), IndexOutOfBoundsException.class);
+        }
+    }
+
+
+    static final boolean At = true, Before = false;
+
+    static void testCodePoint(boolean isAt, StringBuffer sb, int index, int expected) {
+        int c = isAt ? sb.codePointAt(index) : sb.codePointBefore(index);
+
+        check(c != expected,
+              "codePoint" + (isAt ? "At" : "Before") + "(" + index + ") for <"
+              + sb + ">", c, expected);
+    }
+
+    static void testCodePoint(boolean isAt, StringBuffer sb, int index) {
+        boolean exceptionOccurred = false;
+
+        try {
+            int c = isAt ? sb.codePointAt(index) : sb.codePointBefore(index);
+        }
+        catch (StringIndexOutOfBoundsException e) {
+            exceptionOccurred = true;
+        }
+        check(!exceptionOccurred,
+              "codePoint" + (isAt ? "At" : "Before") + "(" + index + ") for <"
+              + sb + "> should throw StringIndexOutOfBoundsPointerException.");
+    }
+
+    static void testAppendCodePoint(int codePoint, Class expectedException) {
+        try {
+            new StringBuffer().appendCodePoint(codePoint);
+        } catch (Exception e) {
+            if (expectedException.isInstance(e)) {
+                return;
+            }
+            throw new RuntimeException("Error: Unexpected exception", e);
+        }
+        check(true, "appendCodePoint(" + toHexString(codePoint) + ") didn't throw "
+              + expectedException.getName());
+    }
+
+    static void testCodePointCount(StringBuffer sb, int beginIndex, int endIndex,
+                                   Class expectedException) {
+        try {
+            int n = sb.codePointCount(beginIndex, endIndex);
+        } catch (Exception e) {
+            if (expectedException.isInstance(e)) {
+                return;
+            }
+            throw new RuntimeException("Error: Unexpected exception", e);
+        }
+        check(true, "codePointCount() didn't throw " + expectedException.getName());
+    }
+
+    static void testOffsetByCodePoints(StringBuffer sb, int index, int offset,
+                                       Class expectedException) {
+        try {
+            int n = sb.offsetByCodePoints(index, offset);
+        } catch (Exception e) {
+            if (expectedException.isInstance(e)) {
+                return;
+            }
+            throw new RuntimeException("Error: Unexpected exception", e);
+        }
+        check(true, "offsetByCodePoints() didn't throw " + expectedException.getName());
+    }
+
+    static void check(boolean err, String msg) {
+        if (err) {
+            throw new RuntimeException("Error: " + msg);
+        }
+    }
+
+    static void check(boolean err, String s, int got, int expected) {
+        if (err) {
+            throw new RuntimeException("Error: " + s
+                                       + " returned an unexpected value. got "
+                                       + toHexString(got)
+                                       + ", expected "
+                                       + toHexString(expected));
+        }
+    }
+
+    static void check(boolean err, String s, StringBuffer got, String expected) {
+        if (err) {
+            throw new RuntimeException("Error: " + s
+                                       + " returned an unexpected value. got <"
+                                       + toHexString(new String(got))
+                                       + ">, expected <"
+                                       + toHexString(expected)
+                                       + ">");
+        }
+    }
+
+    private static String toHexString(int c) {
+        return "0x" + Integer.toHexString(c);
+    }
+
+    private static String toHexString(String s) {
+        StringBuffer sb = new StringBuffer();
+        for (int i = 0; i < s.length(); i++) {
+            char c = s.charAt(i);
+
+            sb.append(" 0x");
+            if (c < 0x10) sb.append('0');
+            if (c < 0x100) sb.append('0');
+            if (c < 0x1000) sb.append('0');
+            sb.append(Integer.toHexString(c));
+        }
+        sb.append(' ');
+        return sb.toString();
+    }
+}
diff --git a/jdk/test/java/lang/StringBuffer/Trim.java b/jdk/test/java/lang/StringBuffer/Trim.java
new file mode 100644
index 0000000..c3fd831
--- /dev/null
+++ b/jdk/test/java/lang/StringBuffer/Trim.java
@@ -0,0 +1,118 @@
+/*
+ * Copyright 2003-2004 Sun Microsystems, Inc.  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 Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
+ * CA 95054 USA or visit www.sun.com if you need additional information or
+ * have any questions.
+ */
+
+/* @test
+ * @bug 4546734 5007612
+ * @summary Test StringBuffer.trimToSize
+ */
+
+import java.util.Random;
+
+public class Trim {
+    private static Random generator = new Random();
+
+    public static void main(String[] args) throws Exception {
+        bash();
+        //capacityCheck();
+    }
+
+    // Make sure trimToSize is safe to use; it should never cause an
+    // exception or mutation
+    private static void bash() throws Exception {
+        for (int i=0; i<1000; i++) {
+            StringBuffer sb1 = generateTestBuffer(0, 100);
+            StringBuffer sb2 = new StringBuffer(sb1);
+            sb1.trimToSize();
+            if (!sb1.toString().equals(sb2.toString()))
+                throw new RuntimeException(
+                    "trim mutated stringbuffer contents");
+            // Append a random sb
+            StringBuffer sb3 = generateTestBuffer(0, 100);
+            sb1.append(sb3);
+            sb2.append(sb3);
+            if (generator.nextInt(2) == 0)
+                sb1.trimToSize();
+            else
+                sb2.trimToSize();
+            if (!sb1.toString().equals(sb2.toString()))
+                throw new RuntimeException(
+                    "trim mutated stringbuffer contents");
+            // Append sb with lots of extra space
+            sb3 = new StringBuffer(100);
+            sb3.append("a");
+            sb1.append(sb3);
+            sb2.append(sb3);
+            if (generator.nextInt(2) == 0)
+                sb1.trimToSize();
+            else
+                sb2.trimToSize();
+            if (!sb1.toString().equals(sb2.toString()))
+                throw new RuntimeException(
+                    "trim mutated stringbuffer contents");
+        }
+    }
+
+    // This test gives some assurance that trimToSize is working but
+    // it should not be part of an automated run, and a failure here
+    // is not against spec; this method is provided simply to be run
+    // by hand and assure the engineer that it is working. The test
+    // may stop working at some time in the future depending on
+    // how String and StringBuffer are implemented because it depends
+    // upon the capacity method.
+    private static void capacityCheck() {
+        for (int i=0; i<100; i++) {
+            int sizeNeeded = generator.nextInt(1000)+1;
+            int sizeExtra = generator.nextInt(100) + 1;
+            StringBuffer sb = new StringBuffer(sizeNeeded + sizeExtra);
+            StringBuffer sb2 = generateTestBuffer(sizeNeeded, sizeNeeded);
+            if (sb2.length() != sizeNeeded)
+                throw new RuntimeException("sb generated incorrectly");
+            sb.append(sb2);
+            int oldCapacity = sb.capacity();
+            sb.trimToSize();
+            int newCapacity = sb.capacity();
+            if (oldCapacity == newCapacity)
+                throw new RuntimeException("trim failed");
+        }
+    }
+
+    private static int getRandomIndex(int constraint1, int constraint2) {
+        int range = constraint2 - constraint1;
+        if (range <= 0)
+            return constraint1;
+        int x = generator.nextInt(range);
+        return constraint1 + x;
+    }
+
+    private static StringBuffer generateTestBuffer(int min, int max) {
+        StringBuffer aNewStringBuffer = new StringBuffer();
+        int aNewLength = getRandomIndex(min, max);
+        for(int y=0; y<aNewLength; y++) {
+            int achar = generator.nextInt(30)+30;
+            char test = (char)(achar);
+            aNewStringBuffer.append(test);
+        }
+        return aNewStringBuffer;
+    }
+
+}
diff --git a/jdk/test/java/lang/StringBuilder/Exceptions.java b/jdk/test/java/lang/StringBuilder/Exceptions.java
new file mode 100644
index 0000000..810a3dd
--- /dev/null
+++ b/jdk/test/java/lang/StringBuilder/Exceptions.java
@@ -0,0 +1,123 @@
+/*
+ * Copyright 2005 Sun Microsystems, Inc.  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 Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
+ * CA 95054 USA or visit www.sun.com if you need additional information or
+ * have any questions.
+ */
+
+/**
+ * @test
+ * @bug 6248507
+ * @summary Verify that exceptions are thrown as expected.
+ */
+
+public class Exceptions {
+    private static boolean ok = true;
+
+    private static void fail(Throwable ex, String s, Throwable got) {
+        ok = false;
+        System.err.println("expected "
+                           + ex.getClass().getName() + ": " + ex.getMessage()
+                           + " for " + s
+                           + " got "
+                           + got.getClass().getName() + ": " + got.getMessage()
+                           + " - FAILED");
+    }
+
+    private static void pass(String s) {
+        System.out.println(s + " -- OK");
+    }
+
+    private static void tryCatch(String s, Throwable ex, Runnable thunk) {
+        Throwable t = null;
+        try {
+            thunk.run();
+        } catch (Throwable x) {
+//          x.printStackTrace();
+            if (ex.getClass().isAssignableFrom(x.getClass()))
+                t = x;
+            else
+                x.printStackTrace();
+        }
+        if ((t == null) && (ex != null))
+            fail(ex, s, t);
+
+        String msg = (ex == null ? null : ex.getMessage());
+        if ((msg != null) && !msg.equals(t.getMessage()))
+            fail(ex, s, t);
+        else
+            pass(s);
+    }
+
+    public static void main(String [] args) {
+        System.out.println("StringBuilder()");
+        tryCatch("  no args", null, new Runnable() {
+                public void run() {
+                    new StringBuilder();
+                }});
+
+        System.out.println("StringBuilder(int length)");
+        tryCatch("  1", null, new Runnable() {
+                public void run() {
+                    new StringBuilder(1);
+                }});
+        tryCatch("  -1", new NegativeArraySizeException(), new Runnable() {
+                public void run() {
+                    new StringBuilder(-1);
+                }});
+
+        System.out.println("StringBuilder(String str)");
+        tryCatch("  null", new NullPointerException(), new Runnable() {
+                public void run() {
+                    new StringBuilder(null);
+                }});
+        tryCatch("  foo", null, new Runnable() {
+                public void run() {
+                    new StringBuilder("foo");
+                }});
+
+        System.out.println("StringBuilder.replace(int start, int end, String str)");
+        tryCatch("  -1, 2, \" \"",
+                 new StringIndexOutOfBoundsException(-1),
+                 new Runnable() {
+                public void run() {
+                    StringBuilder sb = new StringBuilder("hilbert");
+                    sb.replace(-1, 2, " ");
+                }});
+        tryCatch("  7, 8, \" \"",
+                 new StringIndexOutOfBoundsException("start > length()"),
+                 new Runnable() {
+                public void run() {
+                    StringBuilder sb = new StringBuilder("banach");
+                    sb.replace(7, 8, " ");
+                }});
+        tryCatch("  2, 1, \" \"",
+                 new StringIndexOutOfBoundsException("start > end"),
+                 new Runnable() {
+                public void run() {
+                    StringBuilder sb = new StringBuilder("riemann");
+                    sb.replace(2, 1, " ");
+                }});
+
+        if (!ok)
+            throw new RuntimeException("Some tests FAILED");
+        else
+            System.out.println("All tests PASSED");
+    }
+}
diff --git a/jdk/test/java/lang/StringBuilder/Insert.java b/jdk/test/java/lang/StringBuilder/Insert.java
new file mode 100644
index 0000000..4519fe5
--- /dev/null
+++ b/jdk/test/java/lang/StringBuilder/Insert.java
@@ -0,0 +1,35 @@
+/*
+ * Copyright 2003 Sun Microsystems, Inc.  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 Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
+ * CA 95054 USA or visit www.sun.com if you need additional information or
+ * have any questions.
+ */
+
+/**
+ * @test
+ * @bug 4914802
+ * @summary Test Insert method for infinite loop
+ */
+
+public class Insert {
+   public static void main (String argv[]) throws Exception {
+       StringBuilder sb = new StringBuilder();
+       sb.insert(0, false);
+   }
+}
diff --git a/jdk/test/java/lang/StringBuilder/Supplementary.java b/jdk/test/java/lang/StringBuilder/Supplementary.java
new file mode 100644
index 0000000..32337b1
--- /dev/null
+++ b/jdk/test/java/lang/StringBuilder/Supplementary.java
@@ -0,0 +1,417 @@
+/*
+ * Copyright 2003-2004 Sun Microsystems, Inc.  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 Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
+ * CA 95054 USA or visit www.sun.com if you need additional information or
+ * have any questions.
+ */
+
+/*
+ *
+ * @test
+ * @bug 4533872 4915683 4985217 5017280
+ * @summary Unit tests for supplementary character support (JSR-204)
+ */
+
+public class Supplementary {
+
+    public static void main(String[] args) {
+        test1();        // Test for codePointAt(int index)
+        test2();        // Test for codePointBefore(int index)
+        test3();        // Test for reverse()
+        test4();        // Test for appendCodePoint(int codePoint)
+        test5();        // Test for codePointCount(int beginIndex, int endIndex)
+        test6();        // Test for offsetByCodePoints(int index, int offset)
+    }
+
+    /* Text strings which are used as input data.
+     * The comment above each text string means the index of each 16-bit char
+     * for convenience.
+     */
+    static final String[] input = {
+      /*                               111     1     111111     22222
+         0123     4     5678     9     012     3     456789     01234 */
+        "abc\uD800\uDC00def\uD800\uD800ab\uD800\uDC00cdefa\uDC00bcdef",
+      /*                          1     1111     1111     1     222
+         0     12345     6789     0     1234     5678     9     012     */
+        "\uD800defg\uD800hij\uD800\uDC00klm\uDC00nop\uDC00\uD800rt\uDC00",
+      /*                          11     1     1111     1     112     222
+         0     12345     6     78901     2     3456     7     890     123     */
+        "\uDC00abcd\uDBFF\uDFFFefgh\uD800\uDC009ik\uDC00\uDC00lm\uDC00no\uD800",
+      /*                                    111     111111     1 22     2
+         0     1     2345     678     9     012     345678     9 01     2     */
+        "\uD800\uDC00!#$\uD800%&\uD800\uDC00;+\uDC00<>;=^\uDC00\\@\uD800\uDC00",
+
+        // includes an undefined supprementary characters in Unicode 4.0.0
+      /*                                    1     11     1     1111     1
+         0     1     2345     6     789     0     12     3     4567     8     */
+        "\uDB40\uDE00abc\uDE01\uDB40de\uDB40\uDE02f\uDB40\uDE03ghi\uDB40\uDE02",
+    };
+
+
+    /* Expected results for:
+     *     test1(): for codePointAt()
+     *
+     * Each character in each array is the golden data for each text string
+     * in the above input data. For example, the first data in each array is
+     * for the first input string.
+     */
+    static final int[][] golden1 = {
+        {'a',    0xD800, 0xDC00,  0x10000, 0xE0200}, // codePointAt(0)
+        {0xD800, 0x10000, 'g',    0xDC00,  0xE0202}, // codePointAt(9)
+        {'f',    0xDC00,  0xD800, 0xDC00,  0xDE02},  // codePointAt(length-1)
+    };
+
+    /*
+     * Test for codePointAt(int index) method
+     */
+    static void test1() {
+
+        for (int i = 0; i < input.length; i++) {
+            StringBuilder sb = new StringBuilder(input[i]);
+
+            /*
+             * Normal case
+             */
+            testCodePoint(At, sb, 0, golden1[0][i]);
+            testCodePoint(At, sb, 9, golden1[1][i]);
+            testCodePoint(At, sb, sb.length()-1, golden1[2][i]);
+
+            /*
+             * Abnormal case - verify that an exception is thrown.
+             */
+            testCodePoint(At, sb, -1);
+            testCodePoint(At, sb, sb.length());
+        }
+    }
+
+
+    /* Expected results for:
+     *     test2(): for codePointBefore()
+     *
+     * Each character in each array is the golden data for each text string
+     * in the above input data. For example, the first data in each array is
+     * for the first input string.
+     */
+    static final int[][] golden2 = {
+        {'a',    0xD800, 0xDC00,  0xD800,  0xDB40},  // codePointBefore(1)
+        {0xD800, 'l',    0x10000, 0xDC00,  0xDB40},  // codePointBefore(13)
+        {'f',    0xDC00, 0xD800,  0x10000, 0xE0202}, // codePointBefore(length)
+    };
+
+    /*
+     * Test for codePointBefore(int index) method
+     */
+    static void test2() {
+
+        for (int i = 0; i < input.length; i++) {
+            StringBuilder sb = new StringBuilder(input[i]);
+
+            /*
+             * Normal case
+             */
+            testCodePoint(Before, sb, 1, golden2[0][i]);
+            testCodePoint(Before, sb, 13, golden2[1][i]);
+            testCodePoint(Before, sb, sb.length(), golden2[2][i]);
+
+            /*
+             * Abnormal case - verify that an exception is thrown.
+             */
+            testCodePoint(Before, sb, 0);
+            testCodePoint(Before, sb, sb.length()+1);
+        }
+    }
+
+
+    /* Expected results for:
+     *     test3(): for reverse()
+     *
+     * Unlike golden1 and golden2, each array is the golden data for each text
+     * string in the above input data. For example, the first array is  for
+     * the first input string.
+     */
+    static final String[] golden3 = {
+        "fedcb\uDC00afedc\uD800\uDC00ba\uD800\uD800fed\uD800\uDC00cba",
+        "\uDC00tr\uD800\uDC00pon\uDC00mlk\uD800\uDC00jih\uD800gfed\uD800",
+        "\uD800on\uDC00ml\uDC00\uDC00ki9\uD800\uDC00hgfe\uDBFF\uDFFFdcba\uDC00",
+        "\uD800\uDC00@\\\uDC00^=;><\uDC00+;\uD800\uDC00&%\uD800$#!\uD800\uDC00",
+
+        // includes an undefined supprementary characters in Unicode 4.0.0
+        "\uDB40\uDE02ihg\uDB40\uDE03f\uDB40\uDE02ed\uDB40\uDE01cba\uDB40\uDE00",
+    };
+
+    // Additional input data & expected result for test3()
+    static final String[][] testdata1 = {
+        {"a\uD800\uDC00", "\uD800\uDC00a"},
+        {"a\uDC00\uD800", "\uD800\uDC00a"},
+        {"\uD800\uDC00a", "a\uD800\uDC00"},
+        {"\uDC00\uD800a", "a\uD800\uDC00"},
+        {"\uDC00\uD800\uD801", "\uD801\uD800\uDC00"},
+        {"\uDC00\uD800\uDC01", "\uD800\uDC01\uDC00"},
+        {"\uD801\uD800\uDC00", "\uD800\uDC00\uD801"},
+        {"\uD800\uDC01\uDC00", "\uDC00\uD800\uDC01"},
+        {"\uD800\uDC00\uDC01\uD801", "\uD801\uDC01\uD800\uDC00"},
+    };
+
+    /*
+     * Test for reverse() method
+     */
+    static void test3() {
+        for (int i = 0; i < input.length; i++) {
+            StringBuilder sb = new StringBuilder(input[i]).reverse();
+
+            check(!golden3[i].equals(sb.toString()),
+                 "reverse() for <" + toHexString(input[i]) + ">",
+                 sb, golden3[i]);
+        }
+
+        for (int i = 0; i < testdata1.length; i++) {
+            StringBuilder sb = new StringBuilder(testdata1[i][0]).reverse();
+
+            check(!testdata1[i][1].equals(sb.toString()),
+                 "reverse() for <" + toHexString(testdata1[i][0]) + ">",
+                 sb, testdata1[i][1]);
+        }
+    }
+
+    /**
+     * Test for appendCodePoint() method
+     */
+    static void test4() {
+        for (int i = 0; i < input.length; i++) {
+            String s = input[i];
+            StringBuilder sb = new StringBuilder();
+            int c;
+            for (int j = 0; j < s.length(); j += Character.charCount(c)) {
+                c = s.codePointAt(j);
+                StringBuilder rsb = sb.appendCodePoint(c);
+                check(sb != rsb, "appendCodePoint returned a wrong object");
+                int sbc = sb.codePointAt(j);
+                check(sbc != c, "appendCodePoint("+j+") != c", sbc, c);
+            }
+            check(!s.equals(sb.toString()),
+                  "appendCodePoint() produced a wrong result with input["+i+"]");
+        }
+
+        // test exception
+        testAppendCodePoint(-1, IllegalArgumentException.class);
+        testAppendCodePoint(Character.MAX_CODE_POINT+1, IllegalArgumentException.class);
+    }
+
+    /**
+     * Test codePointCount(int, int)
+     *
+     * This test case assumes that
+     * Character.codePointCount(CharSequence, int, int) works
+     * correctly.
+     */
+    static void test5() {
+        for (int i = 0; i < input.length; i++) {
+            String s = input[i];
+            StringBuilder sb = new StringBuilder(s);
+            int length = sb.length();
+            for (int j = 0; j <= length; j++) {
+                int result = sb.codePointCount(j, length);
+                int expected = Character.codePointCount(sb, j, length);
+                check(result != expected, "codePointCount(input["+i+"], "+j+", "+length+")",
+                      result, expected);
+            }
+            for (int j = length; j >= 0; j--) {
+                int result = sb.codePointCount(0, j);
+                int expected = Character.codePointCount(sb, 0, j);
+                check(result != expected, "codePointCount(input["+i+"], 0, "+j+")",
+                      result, expected);
+            }
+
+            // test exceptions
+            testCodePointCount(null, 0, 0, NullPointerException.class);
+            testCodePointCount(sb, -1, length, IndexOutOfBoundsException.class);
+            testCodePointCount(sb, 0, length+1, IndexOutOfBoundsException.class);
+            testCodePointCount(sb, length, length-1, IndexOutOfBoundsException.class);
+        }
+    }
+
+    /**
+     * Test offsetByCodePoints(int, int)
+     *
+     * This test case assumes that
+     * Character.codePointCount(CharSequence, int, int) works
+     * correctly.
+     */
+    static void test6() {
+        for (int i = 0; i < input.length; i++) {
+            String s = input[i];
+            StringBuilder sb = new StringBuilder(s);
+            int length = s.length();
+            for (int j = 0; j <= length; j++) {
+                int nCodePoints = Character.codePointCount(sb, j, length);
+                int result = sb.offsetByCodePoints(j, nCodePoints);
+                check(result != length,
+                      "offsetByCodePoints(input["+i+"], "+j+", "+nCodePoints+")",
+                      result, length);
+                result = sb.offsetByCodePoints(length, -nCodePoints);
+                int expected = j;
+                if (j > 0 && j < length) {
+                    int cp = sb.codePointBefore(j+1);
+                    if (Character.isSupplementaryCodePoint(cp)) {
+                        expected--;
+                    }
+                }
+                check(result != expected,
+                      "offsetByCodePoints(input["+i+"], "+j+", "+(-nCodePoints)+")",
+                      result, expected);
+            }
+            for (int j = length; j >= 0; j--) {
+                int nCodePoints = Character.codePointCount(sb, 0, j);
+                int result = sb.offsetByCodePoints(0, nCodePoints);
+                int expected = j;
+                if (j > 0 && j < length) {
+                    int cp = sb.codePointAt(j-1);
+                     if (Character.isSupplementaryCodePoint(cp)) {
+                        expected++;
+                    }
+                }
+                check(result != expected,
+                      "offsetByCodePoints(input["+i+"], 0, "+nCodePoints+")",
+                      result, expected);
+                result = sb.offsetByCodePoints(j, -nCodePoints);
+                check(result != 0,
+                      "offsetBycodePoints(input["+i+"], "+j+", "+(-nCodePoints)+")",
+                      result, 0);
+            }
+
+            // test exceptions
+            testOffsetByCodePoints(null, 0, 0, NullPointerException.class);
+            testOffsetByCodePoints(sb, -1, length, IndexOutOfBoundsException.class);
+            testOffsetByCodePoints(sb, 0, length+1, IndexOutOfBoundsException.class);
+            testOffsetByCodePoints(sb, 1, -2, IndexOutOfBoundsException.class);
+            testOffsetByCodePoints(sb, length, length-1, IndexOutOfBoundsException.class);
+            testOffsetByCodePoints(sb, length, -(length+1), IndexOutOfBoundsException.class);
+        }
+    }
+
+
+    static final boolean At = true, Before = false;
+
+    static void testCodePoint(boolean isAt, StringBuilder sb, int index, int expected) {
+        int c = isAt ? sb.codePointAt(index) : sb.codePointBefore(index);
+
+        check(c != expected,
+              "codePoint" + (isAt ? "At" : "Before") + "(" + index + ") for <"
+              + sb + ">", c, expected);
+    }
+
+    static void testCodePoint(boolean isAt, StringBuilder sb, int index) {
+        boolean exceptionOccurred = false;
+
+        try {
+            int c = isAt ? sb.codePointAt(index) : sb.codePointBefore(index);
+        }
+        catch (StringIndexOutOfBoundsException e) {
+            exceptionOccurred = true;
+        }
+        check(!exceptionOccurred,
+              "codePoint" + (isAt ? "At" : "Before") + "(" + index + ") for <"
+              + sb + "> should throw StringIndexOutOfBoundsPointerException.");
+    }
+
+    static void testAppendCodePoint(int codePoint, Class expectedException) {
+        try {
+            new StringBuilder().appendCodePoint(codePoint);
+        } catch (Exception e) {
+            if (expectedException.isInstance(e)) {
+                return;
+            }
+            throw new RuntimeException("Error: Unexpected exception", e);
+        }
+        check(true, "appendCodePoint(" + toHexString(codePoint) + ") didn't throw "
+              + expectedException.getName());
+    }
+
+    static void testCodePointCount(StringBuilder sb, int beginIndex, int endIndex,
+                                   Class expectedException) {
+        try {
+            int n = sb.codePointCount(beginIndex, endIndex);
+        } catch (Exception e) {
+            if (expectedException.isInstance(e)) {
+                return;
+            }
+            throw new RuntimeException("Error: Unexpected exception", e);
+        }
+        check(true, "codePointCount() didn't throw " + expectedException.getName());
+    }
+
+    static void testOffsetByCodePoints(StringBuilder sb, int index, int offset,
+                                       Class expectedException) {
+        try {
+            int n = sb.offsetByCodePoints(index, offset);
+        } catch (Exception e) {
+            if (expectedException.isInstance(e)) {
+                return;
+            }
+            throw new RuntimeException("Error: Unexpected exception", e);
+        }
+        check(true, "offsetByCodePoints() didn't throw " + expectedException.getName());
+    }
+
+    static void check(boolean err, String msg) {
+        if (err) {
+            throw new RuntimeException("Error: " + msg);
+        }
+    }
+
+    static void check(boolean err, String s, int got, int expected) {
+        if (err) {
+            throw new RuntimeException("Error: " + s
+                                       + " returned an unexpected value. got "
+                                       + toHexString(got)
+                                       + ", expected "
+                                       + toHexString(expected));
+        }
+    }
+
+    static void check(boolean err, String s, StringBuilder got, String expected) {
+        if (err) {
+            throw new RuntimeException("Error: " + s
+                                       + " returned an unexpected value. got <"
+                                       + toHexString(got.toString())
+                                       + ">, expected <"
+                                       + toHexString(expected)
+                                       + ">");
+        }
+    }
+
+    private static String toHexString(int c) {
+        return "0x" + Integer.toHexString(c);
+    }
+
+    private static String toHexString(String s) {
+        StringBuilder sb = new StringBuilder();
+        for (int i = 0; i < s.length(); i++) {
+            char c = s.charAt(i);
+
+            sb.append(" 0x");
+            if (c < 0x10) sb.append('0');
+            if (c < 0x100) sb.append('0');
+            if (c < 0x1000) sb.append('0');
+            sb.append(Integer.toHexString(c));
+        }
+        sb.append(' ');
+        return sb.toString();
+    }
+}
diff --git a/jdk/test/java/lang/StringCoding/CheckEncodings.sh b/jdk/test/java/lang/StringCoding/CheckEncodings.sh
new file mode 100644
index 0000000..6fa20c4
--- /dev/null
+++ b/jdk/test/java/lang/StringCoding/CheckEncodings.sh
@@ -0,0 +1,70 @@
+#
+# Copyright 2002 Sun Microsystems, Inc.  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 Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
+# CA 95054 USA or visit www.sun.com if you need additional information or
+# have any questions.
+#
+
+# @test
+# @summary Verify that unsupported encodings are handled gracefully.
+# @bug 4629543 4785473
+#
+# @run shell/timeout=300 CheckEncodings.sh
+
+# set platform-dependent variables
+OS=`uname -s`
+case "$OS" in
+  SunOS | Linux ) ;;
+  Windows* )
+    echo "Passed"; exit 0 ;;
+  * ) echo "Unrecognized system!" ;  exit 1 ;;
+esac
+
+expectPass() {
+  if [ $1 -eq 0 ]
+  then echo "--- passed as expected"
+  else
+    echo "--- failed"
+    exit $1
+  fi
+}
+
+runTest() {
+  echo "Testing:" ${1}
+  set LC_ALL="${1}"; export LC_ALL
+  locale
+  ${TESTJAVA}/bin/java -version 2>&1
+  expectPass $?
+}
+
+
+locale -a > machine_locales.txt
+
+# ${TESTSRC}/locales.txt contains the list of "fully supported" locales
+# as defined by the i18n doc for 1.4
+cat ${TESTSRC}/locales.txt machine_locales.txt | sort | uniq > locale_union.txt
+
+for i in `xargs < locale_union.txt` ; do
+  runTest ${i}
+done
+  
+# random strings
+for i in FOO 1234 ZZ; do
+  runTest ${i}
+done
diff --git a/jdk/test/java/lang/StringCoding/Enormous.java b/jdk/test/java/lang/StringCoding/Enormous.java
new file mode 100644
index 0000000..052da74
--- /dev/null
+++ b/jdk/test/java/lang/StringCoding/Enormous.java
@@ -0,0 +1,39 @@
+/*
+ * Copyright 2004 Sun Microsystems, Inc.  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 Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
+ * CA 95054 USA or visit www.sun.com if you need additional information or
+ * have any questions.
+ */
+
+/* @test
+ * @bug 4949631
+ * @summary Check for ability to recode arrays of odd sizes > 16MB
+ * @run main/othervm -Xms100m -Xmx200m Enormous
+ */
+
+public class Enormous {
+    public static void main(String[] args) throws Exception {
+        new String(new char[16777217]).getBytes("ASCII");
+        byte[] bytes = new byte[16777217];
+        new String(bytes,"ASCII");
+
+        // Another manifestation of this bug, reported in bug 6192102.
+        new sun.misc.BASE64Encoder().encode(bytes);
+    }
+}
diff --git a/jdk/test/java/lang/StringCoding/locales.txt b/jdk/test/java/lang/StringCoding/locales.txt
new file mode 100644
index 0000000..4780335
--- /dev/null
+++ b/jdk/test/java/lang/StringCoding/locales.txt
@@ -0,0 +1,25 @@
+ar_SA
+zh_CN 
+zh_TW 
+nl_NL 
+nl_NL_EURO 
+en_AU 
+en_CA 
+en_GB 
+en_US 
+fr_CA
+fr_FR 
+fr_FR_EURO 
+de_DE 
+de_DE_EURO 
+iw_IL 
+hi_IN 
+it_IT 
+it_IT_EURO 
+ja_JP
+ko_KR 
+pt_BR 
+es_ES 
+es_ES_EURO 
+sv_SE 
+th_TH 
diff --git a/jdk/test/java/lang/System/Available.java b/jdk/test/java/lang/System/Available.java
new file mode 100644
index 0000000..beff558
--- /dev/null
+++ b/jdk/test/java/lang/System/Available.java
@@ -0,0 +1,39 @@
+/*
+ * Copyright 1998 Sun Microsystems, Inc.  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 Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
+ * CA 95054 USA or visit www.sun.com if you need additional information or
+ * have any questions.
+ */
+
+/*
+ * This class tests to see if System.in.available starts
+ * with an appropriate value
+ *
+ * @test
+ * @bug 4104888
+ * @summary Test for System.in.available
+ */
+
+public class Available {
+    public static void main(String args[]) throws Exception {
+        int bytesAvailable = System.in.available();
+        if (bytesAvailable != 0)
+            throw new RuntimeException("System.in.available returned non-zero");
+        }
+}
diff --git a/jdk/test/java/lang/System/ExitFinalizersAndJIT.java b/jdk/test/java/lang/System/ExitFinalizersAndJIT.java
new file mode 100644
index 0000000..619b036
--- /dev/null
+++ b/jdk/test/java/lang/System/ExitFinalizersAndJIT.java
@@ -0,0 +1,35 @@
+/*
+ * Copyright 1998-2007 Sun Microsystems, Inc.  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 Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
+ * CA 95054 USA or visit www.sun.com if you need additional information or
+ * have any questions.
+ */
+
+/* @test
+   @bug 4119554
+   @summary runFinalizersOnExit(true) causes JIT to be unloaded and
+            crashes the VM.  Interim fix for 1.2 beta4 -- don't unload
+            native libraries loaded by system classes.
+*/
+
+public class ExitFinalizersAndJIT {
+    public static void main(String[] args) throws Exception {
+        System.runFinalizersOnExit(true);
+    }
+}
diff --git a/jdk/test/java/lang/System/IHashCode.java b/jdk/test/java/lang/System/IHashCode.java
new file mode 100644
index 0000000..d90ebc7
--- /dev/null
+++ b/jdk/test/java/lang/System/IHashCode.java
@@ -0,0 +1,36 @@
+/*
+ * Copyright 1999 Sun Microsystems, Inc.  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 Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
+ * CA 95054 USA or visit www.sun.com if you need additional information or
+ * have any questions.
+ */
+
+/**
+ * @test
+ * @bug 4228188
+ * @summary test System.identityHashCode(null)
+ */
+
+public class IHashCode {
+  public static void main (String argv[]) throws Exception {
+       int test = System.identityHashCode(null);
+       if (test != 0)
+           throw new RuntimeException("identityHashCode(null) is "+test);
+  }
+}
diff --git a/jdk/test/java/lang/System/IgnoreNullSecurityManager.java b/jdk/test/java/lang/System/IgnoreNullSecurityManager.java
new file mode 100644
index 0000000..949ef29
--- /dev/null
+++ b/jdk/test/java/lang/System/IgnoreNullSecurityManager.java
@@ -0,0 +1,36 @@
+/*
+ * Copyright 1999 Sun Microsystems, Inc.  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 Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
+ * CA 95054 USA or visit www.sun.com if you need additional information or
+ * have any questions.
+ */
+
+/*
+ * @test
+ * @bug 4213876
+ * @summary Make sure "null" security manager is ignored, as specified in the
+ * javadocs
+ */
+
+public class IgnoreNullSecurityManager {
+
+    public static void main(String argv[]) throws Exception {
+        System.setSecurityManager(null);
+    }
+}
diff --git a/jdk/test/java/lang/System/SecurityRace.java b/jdk/test/java/lang/System/SecurityRace.java
new file mode 100644
index 0000000..c563d34
--- /dev/null
+++ b/jdk/test/java/lang/System/SecurityRace.java
@@ -0,0 +1,202 @@
+/*
+ * Copyright 2005 Sun Microsystems, Inc.  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 Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
+ * CA 95054 USA or visit www.sun.com if you need additional information or
+ * have any questions.
+ */
+
+/*
+ * @test
+ * @bug 6302839
+ * @summary SecurityRace System field accesses in two threads
+ * @author Pete Soper
+ * @build SecurityRace
+ * @run main/othervm/policy=System.policy SecurityRace
+ */
+
+/*
+ * By default the test runs for a very short time.  Use main arg "stress"
+ * to have a real chance of exposing races. Use main arg "time" to report
+ * the average nanoseconds per invocation of System.setSecurityManager and
+ * System.getSecurityManager. No testing for access races is performed with
+ * argument "time."
+ *
+ * Requires security permissions "setSecurityManager" and
+ * "createSecurityManager."
+ */
+
+
+
+public class SecurityRace implements Runnable {
+
+    // Number of iterations to "warm up" and get methods compiled/inlined.
+    // (this is conservative)
+    static final int WARMUP_LOOPS = 100000;
+
+    // Number of timing trials
+    static final int TIMING_TRIALS = 10;
+
+    // Seconds to run this in "stress" mode. This is double the average
+    // time to expose the races of bug 6302839 on a Blade 1000. Invoke
+    // the program with the "stress" option multiple times for more
+    // confidence.
+    static final int STRESS_MILLISECONDS = 300000;
+    static final int SET_TIMING_LOOPS    = 10000;
+
+    // Max seconds to run before terminating the test ("declaring victory").
+    static int MAX_MILLISECONDS = 100;
+
+    // Number of iterations to time
+    static final int GET_TIMING_LOOPS = 10000000;
+
+    // Set true by main thread when NPE caught or time to terminate.
+    // Set true by other thread when NPE caught. It makes
+    // no difference where the NPE is thrown.
+    static volatile boolean stopthreads = false;
+
+    // Number of getProperty invocations between main loop checks
+    static final int       GETPROPERTY_LOOPS = 30000;
+
+    // Used by race and timing tests. Must get set non-null at lease once.
+    static SecurityManager sm = new SecurityManager();
+
+    public static void main(String[] argv) throws Exception {
+        String s;
+
+        if (argv.length > 0) {
+            if (argv[0].equals("time")) {
+
+                // Run the timing method
+                // First warm up the method to make sure it gets compiled
+                for (int i = 0; i < WARMUP_LOOPS; i++) {
+                    timeit(1, 1, 1);
+                }
+
+                System.out.println("boo");
+
+                // Now do the actual timing
+                timeit(TIMING_TRIALS, GET_TIMING_LOOPS, SET_TIMING_LOOPS);
+            } else if (argv[0].equals("stress")) {
+
+                // For stress test the test duration is boosted
+                MAX_MILLISECONDS = STRESS_MILLISECONDS;
+            } else {
+                throw new RuntimeException(
+                    "SecurityRace: " + argv[0]
+                    + " argument to main not recognized");
+            }    // if argv
+        }        // if length
+
+        long start = System.currentTimeMillis(),
+             end   = start + MAX_MILLISECONDS;
+
+        // Create and start racing thread
+        (new Thread(new SecurityRace())).start();
+
+        // main thread alternates batches of getProperty() with time checks
+        try {
+            do {
+                if (stopthreads) {
+
+                    // other thread suffered an NPE
+                    throw new RuntimeException("SecurityRace failed with NPE");
+                }
+
+                for (int i = 0; i < GETPROPERTY_LOOPS; i++) {
+                    s = System.getProperty("java.version");
+                }
+            } while (System.currentTimeMillis() < end);
+        } catch (NullPointerException e) {
+            throw new RuntimeException("SecurityRace failed with NPE");
+        } finally {
+
+            // make sure other thread terminates
+            stopthreads = true;
+        }
+    }    // main
+
+    // System.security mutator.
+    public void run() {
+        try {
+            while (true) {
+                if (stopthreads) {
+                    return;
+                }
+
+                System.setSecurityManager(sm);
+
+                // The goal is to catch another thread testing the
+                // value set above and trying to use it after it's
+                // nulled below.
+                System.setSecurityManager(null);
+            }
+        } catch (NullPointerException e) {
+            stopthreads = true;
+
+            return;
+        }
+    }
+
+    // Time method execution. Collects trials number of timings
+    // for the number of accessor and mutator invocation loops
+    // specified.
+    public static void timeit(int timing_trials, int get_timing_loops,
+                              int set_timing_loops) {
+        try {
+            long start;
+
+            // Time the methods and report average.
+            // Time multiple trials so noise is apparent and a
+            // T test can be used to establish significance.
+            for (int j = 0; j < timing_trials; j++) {
+                start = System.nanoTime();
+
+                for (int i = 0; i < get_timing_loops; i++) {
+                    sm = System.getSecurityManager();
+                }
+
+                // Don't print for "warmup" case. This might mean that
+                // the compiler fails to compile the println (setting it
+                // up to execute via interpretation using an "uncommon trap")
+                // but we don't care if this println runs slowly!
+                if (timing_trials > 1) {
+                    System.out.println((float) (System.nanoTime() - start)
+                                       / (float) get_timing_loops);
+                }
+            }
+
+            for (int j = 0; j < timing_trials; j++) {
+                start = System.nanoTime();
+
+                for (int i = 0; i < set_timing_loops; i++) {
+                    System.setSecurityManager(sm);
+                }
+
+                if (timing_trials > 1) {
+                    System.out.println((float) (System.nanoTime() - start)
+                                       / (float) set_timing_loops);
+                }
+            }
+
+            return;
+        } catch (Exception e) {
+            throw new RuntimeException("SecurityRace got unexpected: " + e);
+        }
+    }    // timeit
+}    // SecurityRace
diff --git a/jdk/test/java/lang/System/System.policy b/jdk/test/java/lang/System/System.policy
new file mode 100644
index 0000000..9ce33d1
--- /dev/null
+++ b/jdk/test/java/lang/System/System.policy
@@ -0,0 +1,55 @@
+//
+// Used by SecurityRace.java 
+// Standard extensions get all permissions by default
+
+grant codeBase "file:${{java.ext.dirs}}/*" {
+	permission java.security.AllPermission;
+};
+
+// default permissions granted to all domains
+
+grant { 
+	// Allows any thread to stop itself using the java.lang.Thread.stop()
+	// method that takes no argument.
+	// Note that this permission is granted by default only to remain
+	// backwards compatible.
+	// It is strongly recommended that you either remove this permission
+	// from this policy file or further restrict it to code sources
+	// that you specify, because Thread.stop() is potentially unsafe.
+	// See "http://java.sun.com/notes" for more information.
+	permission java.lang.RuntimePermission "stopThread";
+
+	// These two added for SecurityRace test
+
+	permission java.lang.RuntimePermission "setSecurityManager";
+	permission java.lang.RuntimePermission "createSecurityManager";
+
+	// allows anyone to listen on un-privileged ports
+	permission java.net.SocketPermission "localhost:1024-", "listen";
+
+	// "standard" properies that can be read by anyone
+
+	permission java.util.PropertyPermission "java.version", "read";
+	permission java.util.PropertyPermission "java.vendor", "read";
+	permission java.util.PropertyPermission "java.vendor.url", "read";
+	permission java.util.PropertyPermission "java.class.version", "read";
+	permission java.util.PropertyPermission "os.name", "read";
+	permission java.util.PropertyPermission "os.version", "read";
+	permission java.util.PropertyPermission "os.arch", "read";
+	permission java.util.PropertyPermission "file.separator", "read";
+	permission java.util.PropertyPermission "path.separator", "read";
+	permission java.util.PropertyPermission "line.separator", "read";
+
+	permission java.util.PropertyPermission "java.specification.version", "read";
+	permission java.util.PropertyPermission "java.specification.vendor", "read";
+	permission java.util.PropertyPermission "java.specification.name", "read";
+
+	permission java.util.PropertyPermission "java.vm.specification.version", "read";
+	permission java.util.PropertyPermission "java.vm.specification.vendor", "read";
+	permission java.util.PropertyPermission "java.vm.specification.name", "read";
+	permission java.util.PropertyPermission "java.vm.version", "read";
+	permission java.util.PropertyPermission "java.vm.vendor", "read";
+	permission java.util.PropertyPermission "java.vm.name", "read";
+	permission java.util.PropertyPermission "java.vm.name", "read";
+};
+
diff --git a/jdk/test/java/lang/System/Versions.java b/jdk/test/java/lang/System/Versions.java
new file mode 100644
index 0000000..d94d3b4
--- /dev/null
+++ b/jdk/test/java/lang/System/Versions.java
@@ -0,0 +1,101 @@
+/*
+ * Copyright 2004-2005 Sun Microsystems, Inc.  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 Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
+ * CA 95054 USA or visit www.sun.com if you need additional information or
+ * have any questions.
+ */
+
+/**
+ * @test
+ * @bug 4989690 6259855
+ * @summary Check that version-related system property invariants hold.
+ * @author Martin Buchholz
+ */
+
+import java.io.*;
+import java.net.URLClassLoader;
+import java.net.URL;
+
+public class Versions {
+    static String getProperty(String prop) throws Exception {
+        String value = System.getProperty(prop);
+        if (value == null)
+            throw new Exception("No such system property: " + prop);
+        System.out.printf("%s=%s%n", prop, value);
+        return value;
+    }
+
+    static ClassLoader cl;
+
+    static void checkClassVersion(int major, int minor, boolean expectSupported)
+        throws Exception
+    {
+        final String className  = "ClassVersionTest";
+        final String classFile  = className + ".class";
+
+        // We create an invalid class file, (only magic and version info),
+        // but the version info must be checked before the body.
+        final DataOutputStream dos =
+            new DataOutputStream(new FileOutputStream(classFile));
+        dos.writeLong((0xCafeBabel << 32) + (minor << 16) + major);
+        dos.close();
+
+        boolean supported = true;
+        try {
+            Class.forName(className, false, cl);
+        } catch (UnsupportedClassVersionError e) {
+            supported = false;
+        } catch (Throwable t) {
+            // We expect an Exception indicating invalid class file
+        }
+        new File(classFile).delete();
+        if (supported != expectSupported)
+            throw new Exception("Forgot to update java.class.version?");
+    }
+
+    public static void main(String [] args) throws Exception {
+        String classVersion   = getProperty("java.class.version");
+        String javaVersion    = getProperty("java.version");
+        String VMVersion      = getProperty("java.vm.version");
+        String runtimeVersion = getProperty("java.runtime.version");
+        String specVersion    = getProperty("java.specification.version");
+
+        if (! (javaVersion.startsWith(specVersion) &&
+               runtimeVersion.startsWith(specVersion)))
+            throw new Exception("Invalid version-related system properties");
+
+        //----------------------------------------------------------------
+        // Check that java.class.version is correct.
+        // Injecting a larger major or minor version number into a
+        // .class file should result in UnsupportedClassVersionError.
+        //----------------------------------------------------------------
+        String[] versions = classVersion.split("\\.");
+        int majorVersion = Integer.parseInt(versions[0]);
+        int minorVersion = Integer.parseInt(versions[1]);
+        System.out.printf("majorVersion=%s%n",majorVersion);
+        System.out.printf("minorVersion=%s%n",minorVersion);
+
+        // Look in ".", and *not* in CLASSPATH
+        cl = new URLClassLoader(new URL[]{new File("./").toURL()}, null);
+
+        checkClassVersion(majorVersion    , minorVersion    , true );
+        checkClassVersion(majorVersion + 1, minorVersion    , false);
+        checkClassVersion(majorVersion    , minorVersion + 1, false);
+    }
+}
diff --git a/jdk/test/java/lang/System/finalization/FinExit.java b/jdk/test/java/lang/System/finalization/FinExit.java
new file mode 100644
index 0000000..26664f2
--- /dev/null
+++ b/jdk/test/java/lang/System/finalization/FinExit.java
@@ -0,0 +1,54 @@
+/*
+ * Copyright 1998 Sun Microsystems, Inc.  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 Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
+ * CA 95054 USA or visit www.sun.com if you need additional information or
+ * have any questions.
+ */
+
+/* @test
+   @bug 4116016
+   @summary Ensure that finalizers are not invoked more than once when on-exit
+            finalization is enabled and a finalizer invokes System.exit after
+            System.exit has already been invoked
+   @build FinExit
+   @run shell FinExit.sh
+ */
+
+
+public class FinExit {
+
+    boolean finalized = false;
+
+    public void finalize() {
+        if (finalized) {
+            System.out.println("2");
+        } else {
+            finalized = true;
+            System.out.println("1");
+            System.exit(0);
+        }
+    }
+
+    public static void main(String[] args) throws Exception {
+        System.runFinalizersOnExit(true);
+        Object o = new FinExit();
+        System.exit(0);
+    }
+
+}
diff --git a/jdk/test/java/lang/System/finalization/FinExit.sh b/jdk/test/java/lang/System/finalization/FinExit.sh
new file mode 100644
index 0000000..d2e48da
--- /dev/null
+++ b/jdk/test/java/lang/System/finalization/FinExit.sh
@@ -0,0 +1,34 @@
+#! /bin/sh
+
+#
+# Copyright 1998 Sun Microsystems, Inc.  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 Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
+# CA 95054 USA or visit www.sun.com if you need additional information or
+# have any questions.
+#
+
+#
+x=`$TESTJAVA/bin/java -cp $TESTCLASSES FinExit`
+echo $x
+if [ "x$x" != "x1" ]; then
+  echo On-exit finalizer invoked twice
+  exit 1
+else
+  exit 0
+fi
diff --git a/jdk/test/java/lang/System/finalization/FinThreads.java b/jdk/test/java/lang/System/finalization/FinThreads.java
new file mode 100644
index 0000000..fd91c1b
--- /dev/null
+++ b/jdk/test/java/lang/System/finalization/FinThreads.java
@@ -0,0 +1,131 @@
+/*
+ * Copyright 1998 Sun Microsystems, Inc.  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 Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
+ * CA 95054 USA or visit www.sun.com if you need additional information or
+ * have any questions.
+ */
+
+/* @test
+   @bug 4026895
+   @summary Ensure that System.runFinalization does not run finalizers in the
+            thread that invokes it
+ */
+
+
+public class FinThreads {
+
+    static Thread mainThread;
+
+    static Object lock = new Object();    /* Protects following two fields */
+    static Thread finalizerThread = null;
+    static Thread finalizedBy = null;
+
+
+    static class Foo {
+
+        boolean catchFinalizer = false;
+
+        /* Instances are only created in an auxiliary thread, in order to
+           guard against stray references from the current thread's stack
+         */
+        static public void create(final boolean catchFinalizer)
+            throws InterruptedException
+        {
+            Thread t = new Thread(new Runnable() {
+                public void run() {
+                    new Foo(catchFinalizer);
+                }});
+            t.start();
+            t.join();
+        }
+
+        public Foo(boolean catchFinalizer) {
+            this.catchFinalizer = catchFinalizer;
+        }
+
+        public void finalize() throws InterruptedException {
+            if (catchFinalizer) {
+                boolean gotFinalizer = false;
+                synchronized (lock) {
+                    if (finalizerThread == null) {
+                        finalizerThread = Thread.currentThread();
+                        gotFinalizer = true;
+                    }
+                }
+                if (gotFinalizer) {
+                    System.err.println("Caught finalizer thread; sleeping...");
+                    Thread.sleep(Long.MAX_VALUE);
+                }
+            } else {
+                synchronized (lock) {
+                    finalizedBy = Thread.currentThread();
+                }
+                System.err.println("Test object finalized by " + finalizedBy);
+            }
+        }
+
+    }
+
+
+    static void alarm(final Thread sleeper, final long delay)
+        throws InterruptedException
+    {
+        Thread t = new Thread(new Runnable() {
+            public void run() {
+                try {
+                    Thread.sleep(delay);
+                    System.err.println("Waking " + sleeper);
+                    sleeper.interrupt();
+                } catch (InterruptedException x) { }
+            }});
+        t.setDaemon(true);
+        t.start();
+    }
+
+
+    public static void main(String[] args) throws Exception {
+
+        mainThread = Thread.currentThread();
+
+        /* Find the finalizer thread and put it to sleep */
+        for (;;) {
+            Foo.create(true);
+            System.gc();
+            synchronized (lock) {
+                if (finalizerThread != null) break;
+            }
+        }
+
+        /* Now create a finalizable object and run finalization */
+        alarm(finalizerThread, 5000);
+        Foo.create(false);
+        for (;;) {
+            System.gc();
+            System.runFinalization();
+            synchronized (lock) {
+                if (finalizedBy != null) break;
+            }
+        }
+
+        if (finalizedBy == mainThread)
+            throw new Exception("Finalizer run in main thread");
+
+    }
+
+}
diff --git a/jdk/test/java/lang/Thread/GenerifyStackTraces.java b/jdk/test/java/lang/Thread/GenerifyStackTraces.java
new file mode 100644
index 0000000..e10080c0
--- /dev/null
+++ b/jdk/test/java/lang/Thread/GenerifyStackTraces.java
@@ -0,0 +1,181 @@
+/*
+ * Copyright 2004 Sun Microsystems, Inc.  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 Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
+ * CA 95054 USA or visit www.sun.com if you need additional information or
+ * have any questions.
+ */
+
+/*
+ * @test
+ * @bug     4919105
+ * @summary Generified basic unit test of Thread.getAllStackTraces()
+ * @author  Mandy Chung
+ *
+ * @compile -source 1.5 GenerifyStackTraces.java
+ * @run main GenerifyStackTraces
+ */
+
+import java.util.*;
+
+public class GenerifyStackTraces {
+
+    private static Object go = new Object();
+    private static Object dumpObj = new Object();
+    private static String[] methodNames = {"run", "A", "B", "C", "Done"};
+    private static int DONE_DEPTH = 5;
+    private static boolean testFailed = false;
+
+    private static Thread one;
+    private static boolean trace = false;
+    public static void main(String[] args) throws Exception {
+        if (args.length > 0 && args[0].equals("trace")) {
+            trace = true;
+        }
+
+        one = new ThreadOne();
+        one.start();
+
+        Thread dt = new DumpThread();
+        dt.setDaemon(true);
+        dt.start();
+
+        if (testFailed) {
+            throw new RuntimeException("Test Failed.");
+        }
+    }
+
+    static class DumpThread extends Thread {
+        public void run() {
+            int depth = 2;
+            while (true) {
+                // At each iterator, wait until ThreadOne blocks
+                // to wait for thread dump.
+                // Then dump stack trace and notify ThreadOne to continue.
+                try {
+                    sleep(2000);
+                    dumpStacks(depth);
+                    depth++;
+                    finishDump();
+                } catch (Exception e) {
+                    e.printStackTrace();
+                    testFailed = true;
+                }
+            }
+        }
+    }
+
+    static class ThreadOne extends Thread {
+        public void run() {
+            A();
+        }
+        private void A() {
+            waitForDump();
+            B();
+        }
+        private void B() {
+            waitForDump();
+            C();
+        }
+        private void C() {
+            waitForDump();
+            Done();
+        }
+        private void Done() {
+            waitForDump();
+
+            // Get stack trace of current thread
+            StackTraceElement[] stack = getStackTrace();
+            try {
+                checkStack(this, stack, DONE_DEPTH);
+            } catch (Exception e) {
+                e.printStackTrace();
+                testFailed = true;
+            }
+        }
+
+    }
+
+
+    static private void waitForDump() {
+        synchronized(go) {
+            try {
+               go.wait();
+            } catch (Exception e) {
+               throw new RuntimeException("Unexpected exception" + e);
+            }
+        }
+    }
+
+    static private void finishDump() {
+        synchronized(go) {
+            try {
+               go.notifyAll();
+            } catch (Exception e) {
+               throw new RuntimeException("Unexpected exception" + e);
+            }
+        }
+    }
+
+    public static void dumpStacks(int depth) throws Exception {
+        // Get stack trace of another thread
+        StackTraceElement[] stack = one.getStackTrace();
+        checkStack(one, stack, depth);
+
+
+        // Get stack traces of all Threads
+        for (Map.Entry<Thread, StackTraceElement[]> entry :
+                 Thread.getAllStackTraces().entrySet()) {
+            Thread t = entry.getKey();
+            stack = entry.getValue();
+            if (t == null || stack == null) {
+                throw new RuntimeException("Null thread or stacktrace returned");
+            }
+            if (t == one) {
+                checkStack(t, stack, depth);
+            }
+        }
+    }
+
+    private static void checkStack(Thread t, StackTraceElement[] stack,
+                                   int depth) throws Exception {
+        if (trace) {
+            printStack(t, stack);
+        }
+        int frame = stack.length - 1;
+        for (int i = 0; i < depth; i++) {
+            if (! stack[frame].getMethodName().equals(methodNames[i])) {
+                throw new RuntimeException("Expected " + methodNames[i] +
+                                           " in frame " + frame + " but got " +
+                                           stack[frame].getMethodName());
+            }
+            frame--;
+        }
+    }
+
+    private static void printStack(Thread t, StackTraceElement[] stack) {
+        System.out.println(t +
+                           " stack: (length = " + stack.length + ")");
+        if (t != null) {
+            for (int j = 0; j < stack.length; j++) {
+                System.out.println(stack[j]);
+            }
+            System.out.println();
+        }
+    }
+}
diff --git a/jdk/test/java/lang/Thread/HoldsLock.java b/jdk/test/java/lang/Thread/HoldsLock.java
new file mode 100644
index 0000000..7276a99
--- /dev/null
+++ b/jdk/test/java/lang/Thread/HoldsLock.java
@@ -0,0 +1,75 @@
+/*
+ * Copyright 2000 Sun Microsystems, Inc.  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 Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
+ * CA 95054 USA or visit www.sun.com if you need additional information or
+ * have any questions.
+ */
+
+/*
+ * @test
+ * @bug     4363076
+ * @summary Basic functional test of Thread.holdsLock(Object)
+ * @author  Josh Bloch and Steffen Grarup
+ */
+
+public class HoldsLock {
+    private static Object target = null;
+
+    private static void checkLock(boolean value) {
+        if (Thread.holdsLock(target) != value)
+            throw new RuntimeException("Should be " + value);
+    }
+
+    static class LockThread extends Thread {
+        public void run() {
+            checkLock(false);
+            synchronized(target) {
+                checkLock(true);
+            }
+            checkLock(false);
+        }
+    }
+
+    public static void main(String args[]) throws Exception {
+        // Test null obj case
+        try {
+            checkLock(false);
+            throw new RuntimeException("NullPointerException not thrown");
+        } catch (NullPointerException e) {
+        };
+
+        // Test uncontested case
+        target = new Object();
+        checkLock(false);
+        synchronized(target) {
+            checkLock(true);
+        }
+        checkLock(false);
+
+        // Test contested case
+        synchronized(target) {
+            checkLock(true);
+            new LockThread().start();
+            checkLock(true);
+            Thread.sleep(100);
+            checkLock(true);
+        }
+        checkLock(false);
+    }
+}
diff --git a/jdk/test/java/lang/Thread/MainThreadTest.java b/jdk/test/java/lang/Thread/MainThreadTest.java
new file mode 100644
index 0000000..e0a77eb
--- /dev/null
+++ b/jdk/test/java/lang/Thread/MainThreadTest.java
@@ -0,0 +1,44 @@
+/*
+ * Copyright 2003 Sun Microsystems, Inc.  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 Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
+ * CA 95054 USA or visit www.sun.com if you need additional information or
+ * have any questions.
+ */
+
+/*
+ * @test
+ * @bug     4533087
+ * @summary Test to see if the main thread is in its thread group
+ */
+
+public class MainThreadTest {
+    public static void main(String args[]) {
+        ThreadGroup tg = Thread.currentThread().getThreadGroup();
+        int n = tg.activeCount();
+        Thread[] ts = new Thread[n];
+        int m = tg.enumerate(ts);
+        for (int i = 0; i < ts.length; i++) {
+            if (Thread.currentThread() == ts[i]) {
+                return;
+            }
+        }
+        throw new RuntimeException(
+            "Current thread is not in its own thread group!");
+    }
+}
diff --git a/jdk/test/java/lang/Thread/NullStackTrace.java b/jdk/test/java/lang/Thread/NullStackTrace.java
new file mode 100644
index 0000000..43ef51e
--- /dev/null
+++ b/jdk/test/java/lang/Thread/NullStackTrace.java
@@ -0,0 +1,45 @@
+/*
+ * Copyright 2007 Sun Microsystems, Inc.  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 Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
+ * CA 95054 USA or visit www.sun.com if you need additional information or
+ * have any questions.
+ */
+
+/*
+ * @test
+ * @bug     6571589
+ * @summary java.lang.Thread#getStackTrace() returns null.
+ */
+
+public class NullStackTrace
+{
+    static final int TIMES = 1000;
+
+    public static void main(String[] args)
+    {
+        for (int i=0; i<TIMES; i++) {
+            Thread t = new Thread();
+            t.start();
+
+            StackTraceElement[] ste = t.getStackTrace();
+            if (ste == null)
+                throw new RuntimeException("Failed: Thread.getStackTrace should not return null");
+        }
+    }
+}
diff --git a/jdk/test/java/lang/Thread/StackTraces.java b/jdk/test/java/lang/Thread/StackTraces.java
new file mode 100644
index 0000000..504af23
--- /dev/null
+++ b/jdk/test/java/lang/Thread/StackTraces.java
@@ -0,0 +1,182 @@
+/*
+ * Copyright 2003 Sun Microsystems, Inc.  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 Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
+ * CA 95054 USA or visit www.sun.com if you need additional information or
+ * have any questions.
+ */
+
+/*
+ * @test
+ * @bug     4593133
+ * @summary Basic unit test of Thread.getStackTraces()
+ * @author  Mandy Chung
+ */
+
+import java.util.*;
+
+public class StackTraces {
+
+    private static Object go = new Object();
+    private static Object dumpObj = new Object();
+    private static String[] methodNames = {"run", "A", "B", "C", "Done"};
+    private static int DONE_DEPTH = 5;
+    private static boolean testFailed = false;
+
+    private static Thread one;
+    private static boolean trace = false;
+    public static void main(String[] args) throws Exception {
+        if (args.length > 0 && args[0].equals("trace")) {
+            trace = true;
+        }
+
+        one = new ThreadOne();
+        one.start();
+
+        Thread dt = new DumpThread();
+        dt.setDaemon(true);
+        dt.start();
+
+        if (testFailed) {
+            throw new RuntimeException("Test Failed.");
+        }
+    }
+
+    static class DumpThread extends Thread {
+        public void run() {
+            int depth = 2;
+            while (true) {
+                // At each iterator, wait until ThreadOne blocks
+                // to wait for thread dump.
+                // Then dump stack trace and notify ThreadOne to continue.
+                try {
+                    sleep(2000);
+                    dumpStacks(depth);
+                    depth++;
+                    finishDump();
+                } catch (Exception e) {
+                    e.printStackTrace();
+                    testFailed = true;
+                }
+            }
+        }
+    }
+
+    static class ThreadOne extends Thread {
+        public void run() {
+            A();
+        }
+        private void A() {
+            waitForDump();
+            B();
+        }
+        private void B() {
+            waitForDump();
+            C();
+        }
+        private void C() {
+            waitForDump();
+            Done();
+        }
+        private void Done() {
+            waitForDump();
+
+            // Get stack trace of current thread
+            StackTraceElement[] stack = getStackTrace();
+            try {
+                checkStack(this, stack, DONE_DEPTH);
+            } catch (Exception e) {
+                e.printStackTrace();
+                testFailed = true;
+            }
+        }
+
+    }
+
+
+    static private void waitForDump() {
+        synchronized(go) {
+            try {
+               go.wait();
+            } catch (Exception e) {
+               throw new RuntimeException("Unexpected exception" + e);
+            }
+        }
+    }
+
+    static private void finishDump() {
+        synchronized(go) {
+            try {
+               go.notifyAll();
+            } catch (Exception e) {
+               throw new RuntimeException("Unexpected exception" + e);
+            }
+        }
+    }
+
+    public static void dumpStacks(int depth) throws Exception {
+        // Get stack trace of another thread
+        StackTraceElement[] stack = one.getStackTrace();
+        checkStack(one, stack, depth);
+
+        // Get stack traces of all Threads
+        Map m = Thread.getAllStackTraces();
+        Set s = m.entrySet();
+        Iterator iter = s.iterator();
+
+        Map.Entry entry;
+        while (iter.hasNext()) {
+            entry = (Map.Entry) iter.next();
+            Thread t = (Thread) entry.getKey();
+            stack = (StackTraceElement[]) entry.getValue();
+            if (t == null || stack == null) {
+               throw new RuntimeException("Null thread or stacktrace returned");
+            }
+            if (t == one) {
+                checkStack(t, stack, depth);
+            }
+        }
+    }
+
+    private static void checkStack(Thread t, StackTraceElement[] stack,
+                                   int depth) throws Exception {
+        if (trace) {
+            printStack(t, stack);
+        }
+        int frame = stack.length - 1;
+        for (int i = 0; i < depth; i++) {
+            if (! stack[frame].getMethodName().equals(methodNames[i])) {
+                throw new RuntimeException("Expected " + methodNames[i] +
+                                           " in frame " + frame + " but got " +
+                                           stack[frame].getMethodName());
+            }
+            frame--;
+        }
+    }
+
+    private static void printStack(Thread t, StackTraceElement[] stack) {
+        System.out.println(t +
+                           " stack: (length = " + stack.length + ")");
+        if (t != null) {
+            for (int j = 0; j < stack.length; j++) {
+                System.out.println(stack[j]);
+            }
+            System.out.println();
+        }
+    }
+}
diff --git a/jdk/test/java/lang/Thread/StartOOMTest.java b/jdk/test/java/lang/Thread/StartOOMTest.java
new file mode 100644
index 0000000..dd8b519
--- /dev/null
+++ b/jdk/test/java/lang/Thread/StartOOMTest.java
@@ -0,0 +1,89 @@
+/*
+ * Copyright 2007 Sun Microsystems, Inc.  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 Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
+ * CA 95054 USA or visit www.sun.com if you need additional information or
+ * have any questions.
+ */
+
+/*
+ * @test
+ * @bug 6379235
+ * @run main/othervm -server -Xmx32m -Xms32m -Xss256m StartOOMTest
+ * @summary ThreadGroup accounting mistake possible with failure of Thread.start()
+ */
+
+import java.util.*;
+
+public class StartOOMTest
+{
+    public static void main(String[] args) throws Throwable {
+        Runnable r = new SleepRunnable();
+        ThreadGroup tg = new ThreadGroup("buggy");
+        List<Thread> threads = new ArrayList<Thread>();
+        Thread failedThread;
+        int i = 0;
+        for (i = 0; ; i++) {
+            Thread t = new Thread(tg, r);
+            try {
+                t.start();
+                threads.add(t);
+            } catch (Throwable x) {
+                failedThread = t;
+                System.out.println(x);
+                System.out.println(i);
+                break;
+            }
+        }
+
+        int j = 0;
+        for (Thread t : threads)
+            t.interrupt();
+
+        while (tg.activeCount() > i/2)
+            Thread.yield();
+        failedThread.start();
+        failedThread.interrupt();
+
+        for (Thread t : threads)
+            t.join();
+        failedThread.join();
+
+        try {
+            Thread.sleep(1000);
+        } catch (Throwable ignore) {
+        }
+
+        int activeCount = tg.activeCount();
+        System.out.println("activeCount = " + activeCount);
+
+        if (activeCount > 0) {
+            throw new RuntimeException("Failed: there  should be no active Threads in the group");
+        }
+    }
+
+    static class SleepRunnable implements Runnable
+    {
+        public void run() {
+            try {
+                Thread.sleep(60*1000);
+            } catch (Throwable t) {
+            }
+        }
+    }
+}
diff --git a/jdk/test/java/lang/Thread/StopBeforeStart.java b/jdk/test/java/lang/Thread/StopBeforeStart.java
new file mode 100644
index 0000000..a0ae20a
--- /dev/null
+++ b/jdk/test/java/lang/Thread/StopBeforeStart.java
@@ -0,0 +1,132 @@
+/*
+ * Copyright 2005 Sun Microsystems, Inc.  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 Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
+ * CA 95054 USA or visit www.sun.com if you need additional information or
+ * have any questions.
+ */
+
+/*
+ * @test
+ * @bug     4519200
+ * @summary Confirm a Thread.stop before start complies with the spec
+ * @author  Pete Soper
+ *
+ * Confirm that a thread that had its stop method invoked before start
+ * does properly terminate with expected exception behavior. NOTE that
+ * arbitrary application threads could return from their run methods faster
+ * than the VM can throw an async exception.
+ */
+public class StopBeforeStart {
+
+    private static final int JOIN_TIMEOUT=10000;
+
+    private class MyThrowable extends Throwable {
+    }
+
+    private class Catcher implements Thread.UncaughtExceptionHandler {
+        private boolean nullaryStop;
+        private Throwable theThrowable;
+        private Throwable expectedThrowable;
+        private boolean exceptionThrown;
+
+        Catcher(boolean nullaryStop) {
+            this.nullaryStop = nullaryStop;
+            if (!nullaryStop) {
+                expectedThrowable = new MyThrowable();
+            }
+        }
+
+        public void uncaughtException(Thread t, Throwable th) {
+            exceptionThrown = true;
+            theThrowable = th;
+        }
+
+        void check(String label) throws Throwable {
+            if (!exceptionThrown) {
+                throw new RuntimeException(label +
+                        " test:" + " missing uncaught exception");
+            }
+
+            if (nullaryStop) {
+                if (! (theThrowable instanceof ThreadDeath)) {
+                    throw new RuntimeException(label +
+                        " test:" + " expected ThreadDeath in uncaught handler");
+                }
+            } else if (theThrowable != expectedThrowable) {
+                throw new RuntimeException(label +
+                        " test:" + " wrong Throwable in uncaught handler");
+            }
+        }
+    }
+
+    private class MyRunnable implements Runnable {
+        public void run() {
+            while(true)
+                ;
+        }
+    }
+
+    private class MyThread extends Thread {
+        public void run() {
+            while(true)
+                ;
+        }
+    }
+
+
+    public static void main(String args[]) throws Throwable {
+        (new StopBeforeStart()).doit();
+        System.out.println("Test passed");
+    }
+
+    private void doit() throws Throwable {
+
+        runit(false, new Thread(new MyRunnable()),"Thread");
+        runit(true, new Thread(new MyRunnable()),"Thread");
+        runit(false, new MyThread(),"Runnable");
+        runit(true, new MyThread(),"Runnable");
+    }
+
+    private void runit(boolean nullaryStop, Thread thread,
+                        String type) throws Throwable {
+
+        Catcher c = new Catcher(nullaryStop);
+        thread.setUncaughtExceptionHandler(c);
+
+        if (nullaryStop) {
+            thread.stop();
+        } else {
+            thread.stop(c.expectedThrowable);
+        }
+
+        thread.start();
+        thread.join(JOIN_TIMEOUT);
+
+        if (thread.getState() != Thread.State.TERMINATED) {
+
+            thread.stop();
+
+            // Under high load this could be a false positive
+            throw new RuntimeException(type +
+                        " test:" + " app thread did not terminate");
+        }
+
+        c.check(type);
+    }
+}
diff --git a/jdk/test/java/lang/Thread/ThreadStateTest.java b/jdk/test/java/lang/Thread/ThreadStateTest.java
new file mode 100644
index 0000000..c658e0c
--- /dev/null
+++ b/jdk/test/java/lang/Thread/ThreadStateTest.java
@@ -0,0 +1,386 @@
+/*
+ * Copyright 2004 Sun Microsystems, Inc.  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 Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
+ * CA 95054 USA or visit www.sun.com if you need additional information or
+ * have any questions.
+ */
+
+/*
+ * @test
+ * @bug     5014783
+ * @summary Basic unit test of thread states returned by
+ *          Thread.getState().
+ *
+ * @author  Mandy Chung
+ *
+ * @build ThreadStateTest
+ * @run main ThreadStateTest
+ */
+
+import java.util.concurrent.locks.LockSupport;
+import java.util.concurrent.Semaphore;
+
+public class ThreadStateTest {
+    private static boolean testFailed = false;
+
+    static class Lock {
+        private String name;
+        Lock(String name) {
+            this.name = name;
+        }
+        public String toString() {
+            return name;
+        }
+    }
+    private static Lock globalLock = new Lock("my lock");
+
+    public static void main(String[] argv) {
+        // Call Thread.getState to force all initialization done
+        // before test verification begins.
+        Thread.currentThread().getState();
+        MyThread myThread = new MyThread("MyThread");
+
+        // before myThread starts
+        checkThreadState(myThread, Thread.State.NEW);
+
+        myThread.start();
+        myThread.waitUntilStarted();
+        checkThreadState(myThread, Thread.State.RUNNABLE);
+
+        synchronized (globalLock) {
+            myThread.goBlocked();
+            checkThreadState(myThread, Thread.State.BLOCKED);
+        }
+
+        myThread.goWaiting();
+        checkThreadState(myThread, Thread.State.WAITING);
+
+        myThread.goTimedWaiting();
+        checkThreadState(myThread, Thread.State.TIMED_WAITING);
+
+
+      /*
+       *********** park and parkUntil seems not working
+       * ignore this case for now.
+       * Bug ID 5062095
+       ***********************************************
+
+        myThread.goParked();
+        checkThreadState(myThread, Thread.State.WAITING);
+
+        myThread.goTimedParked();
+        checkThreadState(myThread, Thread.State.TIMED_WAITING);
+       */
+
+
+        myThread.goSleeping();
+        checkThreadState(myThread, Thread.State.TIMED_WAITING);
+
+        myThread.terminate();
+        checkThreadState(myThread, Thread.State.TERMINATED);
+
+        try {
+            myThread.join();
+        } catch (InterruptedException e) {
+            e.printStackTrace();
+            System.out.println("Unexpected exception.");
+            testFailed = true;
+        }
+        if (testFailed)
+            throw new RuntimeException("TEST FAILED.");
+        System.out.println("Test passed.");
+    }
+
+    private static void checkThreadState(Thread t, Thread.State expected) {
+        Thread.State state = t.getState();
+        System.out.println("Checking thread state " + state);
+        if (state == null) {
+            throw new RuntimeException(t.getName() + " expected to have " +
+                expected + " but got null.");
+        }
+
+        if (state != expected) {
+            throw new RuntimeException(t.getName() + " expected to have " +
+                expected + " but got " + state);
+        }
+    }
+
+    private static String getLockName(Object lock) {
+        if (lock == null) return null;
+
+        return lock.getClass().getName() + '@' +
+            Integer.toHexString(System.identityHashCode(lock));
+    }
+
+    private static void goSleep(long ms) {
+        try {
+            Thread.sleep(ms);
+        } catch (InterruptedException e) {
+            e.printStackTrace();
+            System.out.println("Unexpected exception.");
+            testFailed = true;
+        }
+    }
+
+    static class MyThread extends Thread {
+        private ThreadExecutionSynchronizer thrsync = new ThreadExecutionSynchronizer();
+
+        MyThread(String name) {
+            super(name);
+        }
+
+        private final int RUNNABLE = 0;
+        private final int BLOCKED = 1;
+        private final int WAITING = 2;
+        private final int TIMED_WAITING = 3;
+        private final int PARKED = 4;
+        private final int TIMED_PARKED = 5;
+        private final int SLEEPING = 6;
+        private final int TERMINATE = 7;
+        private int state = RUNNABLE;
+
+        private boolean done = false;
+        public void run() {
+            // Signal main thread to continue.
+            thrsync.signal();
+            while (!done) {
+                switch (state) {
+                    case RUNNABLE: {
+                        double sum = 0;
+                        for (int i = 0; i < 1000; i++) {
+                           double r = Math.random();
+                           double x = Math.pow(3, r);
+                           sum += x - r;
+                        }
+                        break;
+                    }
+                    case BLOCKED: {
+                        // signal main thread.
+                        thrsync.signal();
+                        System.out.println("  myThread is going to block.");
+                        synchronized (globalLock) {
+                            // finish blocking
+                            state = RUNNABLE;
+                        }
+                        break;
+                    }
+                    case WAITING: {
+                        synchronized (globalLock) {
+                            // signal main thread.
+                            thrsync.signal();
+                            System.out.println("  myThread is going to wait.");
+                            try {
+                                globalLock.wait();
+                            } catch (InterruptedException e) {
+                                // ignore
+                            }
+                        }
+                        break;
+                    }
+                    case TIMED_WAITING: {
+                        synchronized (globalLock) {
+                            // signal main thread.
+                            thrsync.signal();
+                            System.out.println("  myThread is going to timed wait.");
+                            try {
+                                globalLock.wait(10000);
+                            } catch (InterruptedException e) {
+                                // ignore
+                            }
+                        }
+                        break;
+                    }
+                    case PARKED: {
+                        // signal main thread.
+                        thrsync.signal();
+                        System.out.println("  myThread is going to park.");
+                        LockSupport.park();
+                        // give a chance for the main thread to block
+                        goSleep(10);
+                        break;
+                    }
+                    case TIMED_PARKED: {
+                        // signal main thread.
+                        thrsync.signal();
+                        System.out.println("  myThread is going to timed park.");
+                        long deadline = System.currentTimeMillis() + 10000*1000;
+                        LockSupport.parkUntil(deadline);
+
+                        // give a chance for the main thread to block
+                        goSleep(10);
+                        break;
+                    }
+                    case SLEEPING: {
+                        // signal main thread.
+                        thrsync.signal();
+                        System.out.println("  myThread is going to sleep.");
+                        try {
+                            Thread.sleep(1000000);
+                        } catch (InterruptedException e) {
+                            // finish sleeping
+                            interrupted();
+                        }
+                        break;
+                    }
+                    case TERMINATE: {
+                        done = true;
+                        // signal main thread.
+                        thrsync.signal();
+                        break;
+                    }
+                    default:
+                        break;
+                }
+            }
+        }
+        public void waitUntilStarted() {
+            // wait for MyThread.
+            thrsync.waitForSignal();
+            goSleep(10);
+        }
+
+        public void goBlocked() {
+            System.out.println("Waiting myThread to go blocked.");
+            setState(BLOCKED);
+            // wait for MyThread to get blocked
+            thrsync.waitForSignal();
+            goSleep(20);
+        }
+
+        public void goWaiting() {
+            System.out.println("Waiting myThread to go waiting.");
+            setState(WAITING);
+            // wait for  MyThread to wait on object.
+            thrsync.waitForSignal();
+            goSleep(20);
+        }
+        public void goTimedWaiting() {
+            System.out.println("Waiting myThread to go timed waiting.");
+            setState(TIMED_WAITING);
+            // wait for MyThread timed wait call.
+            thrsync.waitForSignal();
+            goSleep(20);
+        }
+        public void goParked() {
+            System.out.println("Waiting myThread to go parked.");
+            setState(PARKED);
+            // wait for  MyThread state change to PARKED.
+            thrsync.waitForSignal();
+            goSleep(20);
+        }
+        public void goTimedParked() {
+            System.out.println("Waiting myThread to go timed parked.");
+            setState(TIMED_PARKED);
+            // wait for  MyThread.
+            thrsync.waitForSignal();
+            goSleep(20);
+        }
+
+        public void goSleeping() {
+            System.out.println("Waiting myThread to go sleeping.");
+            setState(SLEEPING);
+            // wait for  MyThread.
+            thrsync.waitForSignal();
+            goSleep(20);
+        }
+        public void terminate() {
+            System.out.println("Waiting myThread to terminate.");
+            setState(TERMINATE);
+            // wait for  MyThread.
+            thrsync.waitForSignal();
+            goSleep(20);
+        }
+
+        private void setState(int newState) {
+            switch (state) {
+                case BLOCKED:
+                    while (state == BLOCKED) {
+                        goSleep(20);
+                    }
+                    state = newState;
+                    break;
+                case WAITING:
+                case TIMED_WAITING:
+                    state = newState;
+                    synchronized (globalLock) {
+                        globalLock.notify();
+                    }
+                    break;
+                case PARKED:
+                case TIMED_PARKED:
+                    state = newState;
+                    LockSupport.unpark(this);
+                    break;
+                case SLEEPING:
+                    state = newState;
+                    this.interrupt();
+                    break;
+                default:
+                    state = newState;
+                    break;
+            }
+        }
+    }
+
+
+
+    static class ThreadExecutionSynchronizer {
+
+        private boolean  waiting;
+        private Semaphore semaphore;
+
+        public ThreadExecutionSynchronizer() {
+            semaphore = new Semaphore(1);
+        waiting = false;
+        }
+
+        // Synchronizes two threads execution points.
+        // Basically any thread could get scheduled to run and
+        // it is not possible to know which thread reaches expected
+        // execution point. So whichever thread reaches a execution
+        // point first wait for the second thread. When the second thread
+        // reaches the expected execution point will wake up
+        // the thread which is waiting here.
+        void stopOrGo() {
+        semaphore.acquireUninterruptibly(); // Thread can get blocked.
+        if (!waiting) {
+            waiting = true;
+            // Wait for second thread to enter this method.
+            while(!semaphore.hasQueuedThreads()) {
+                try {
+                    Thread.sleep(20);
+                } catch (InterruptedException xx) {}
+            }
+            semaphore.release();
+        } else {
+            waiting = false;
+            semaphore.release();
+        }
+        }
+
+        // Wrapper function just for code readability.
+        void waitForSignal() {
+        stopOrGo();
+        }
+
+        void signal() {
+        stopOrGo();
+        }
+    }
+}
diff --git a/jdk/test/java/lang/Thread/UncaughtExceptions.sh b/jdk/test/java/lang/Thread/UncaughtExceptions.sh
new file mode 100644
index 0000000..43b56c8
--- /dev/null
+++ b/jdk/test/java/lang/Thread/UncaughtExceptions.sh
@@ -0,0 +1,205 @@
+#!/bin/sh
+
+#
+# Copyright 2004 Sun Microsystems, Inc.  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 Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
+# CA 95054 USA or visit www.sun.com if you need additional information or
+# have any questions.
+#
+
+#
+# @test
+# @bug 4833089 4992454
+# @summary Check for proper handling of uncaught exceptions
+# @author Martin Buchholz
+#
+# @run shell UncaughtExceptions.sh
+
+# To run this test manually, simply do ./UncaughtExceptions.sh
+
+ java="${TESTJAVA+${TESTJAVA}/bin/}java"
+javac="${TESTJAVA+${TESTJAVA}/bin/}javac"
+
+failed=""
+Fail() { echo "FAIL: $1"; failed="${failed}."; }
+
+Die() { printf "%s\n" "$*"; exit 1; }
+
+Sys() {
+    "$@"; rc="$?";
+    test "$rc" -eq 0 || Die "Command \"$*\" failed with exitValue $rc";
+}
+
+HorizontalRule() {
+    echo "-----------------------------------------------------------------"
+}
+
+Bottom() {
+    test "$#" = 1 -a "$1" = "Line" || Die "Usage: Bottom Line"
+
+    HorizontalRule
+    if test -n "$failed"; then
+	count=`printf "%s" "$failed" | wc -c | tr -d ' '`
+	echo "FAIL: $count tests failed"
+	exit 1
+    else
+	echo "PASS: all tests gave expected results"
+	exit 0
+    fi
+}
+
+Cleanup() { Sys rm -f Seppuku* OK.class; }
+
+set -u
+
+checkOutput() {
+    name="$1" expected="$2" got="$3"
+    printf "$name:\n"; cat "$got"
+    if test -z "$expected"; then
+	test "`cat $got`" != "" && \
+	    Fail "Unexpected $name: `cat $got`"
+    else
+	grep "$expected" "$got" >/dev/null || \
+	    Fail "Expected \"$expected\", got `cat $got`"
+    fi
+}
+
+CheckCommandResults() {
+    expectedRC="$1" expectedOut="$2" expectedErr="$3"; shift 3
+    saveFailed="${failed}"
+    "$@" >TmpTest.Out 2>TmpTest.Err; rc="$?";
+    printf "==> %s (rc=%d)\n" "$*" "$rc"
+    checkOutput "stdout" "$expectedOut" "TmpTest.Out"
+    checkOutput "stderr" "$expectedErr" "TmpTest.Err"
+    test "${saveFailed}" = "${failed}" && \
+	echo "PASS: command completed as expected"
+    Sys rm -f TmpTest.Out TmpTest.Err
+}
+
+Run() {
+    expectedRC="$1" expectedOut="$2" expectedErr="$3" mainBody="$4"
+    cat > Seppuku.java <<EOJAVA
+import static java.lang.Thread.*;
+import static java.lang.System.*;
+
+class OK implements UncaughtExceptionHandler {
+    public void uncaughtException(Thread t, Throwable e) {
+	out.println("OK");
+    }
+}
+
+class NeverInvoked implements UncaughtExceptionHandler {
+    public void uncaughtException(Thread t, Throwable e) {
+	err.println("Test failure: This handler should never be invoked!");
+    }
+}
+
+public class Seppuku extends Thread implements Runnable {
+    public static void seppuku() { throw new RuntimeException("Seppuku!"); }
+
+    public void run() {	seppuku(); }
+
+    public static void main(String[] args) throws Exception {
+	$mainBody
+    }
+}
+EOJAVA
+
+    Sys "$javac" "-source" "1.5" "Seppuku.java"
+    CheckCommandResults "$expectedRC" "$expectedOut" "$expectedErr" \
+	"$java" "Seppuku"
+    Cleanup
+}
+
+#----------------------------------------------------------------
+# A thread is never alive after you've join()ed it.
+#----------------------------------------------------------------
+Run 0 "OK" "Exception in thread \"Thread-0\".*Seppuku" "
+    Thread t = new Seppuku();
+    t.start(); t.join();
+    if (! t.isAlive())
+	out.println(\"OK\");"
+
+#----------------------------------------------------------------
+# Even the main thread is mortal - here it terminates "abruptly"
+#----------------------------------------------------------------
+Run 1 "OK" "Exception in thread \"main\".*Seppuku" "
+    final Thread mainThread = currentThread();
+    new Thread() { public void run() {
+	try { mainThread.join(); }
+	catch (InterruptedException e) {}
+	if (! mainThread.isAlive())
+	    out.println(\"OK\");
+    }}.start();
+    seppuku();"
+
+#----------------------------------------------------------------
+# Even the main thread is mortal - here it terminates normally.
+#----------------------------------------------------------------
+Run 0 "OK" "" "
+    final Thread mainThread = currentThread();
+    new Thread() { public void run() {
+	try { mainThread.join(); }
+	catch (InterruptedException e) {}
+	if (! mainThread.isAlive())
+	    out.println(\"OK\");
+    }}.start();"
+
+#----------------------------------------------------------------
+# Check uncaught exception handler mechanism on the main thread.
+# Check that thread-level handler overrides global default handler.
+#----------------------------------------------------------------
+Run 1 "OK" "" "
+    currentThread().setUncaughtExceptionHandler(new OK());
+    setDefaultUncaughtExceptionHandler(new NeverInvoked());
+    seppuku();"
+
+Run 1 "OK" "" "
+    setDefaultUncaughtExceptionHandler(new OK());
+    seppuku();"
+
+#----------------------------------------------------------------
+# Check uncaught exception handler mechanism on non-main threads.
+#----------------------------------------------------------------
+Run 0 "OK" "" "
+    Thread t = new Seppuku();
+    t.setUncaughtExceptionHandler(new OK());
+    t.start();"
+
+Run 0 "OK" "" "
+    setDefaultUncaughtExceptionHandler(new OK());
+    new Seppuku().start();"
+
+#----------------------------------------------------------------
+# Test ThreadGroup based uncaught exception handler mechanism.
+# Since the handler for the main thread group cannot be changed,
+# there are no tests for the main thread here.
+#----------------------------------------------------------------
+Run 0 "OK" "" "
+    setDefaultUncaughtExceptionHandler(new NeverInvoked());
+    new Thread(
+	new ThreadGroup(\"OK\") {
+	    public void uncaughtException(Thread t, Throwable e) {
+		out.println(\"OK\");}},
+	new Seppuku()
+    ).start();"
+
+Cleanup
+
+Bottom Line
diff --git a/jdk/test/java/lang/ThreadGroup/Daemon.java b/jdk/test/java/lang/ThreadGroup/Daemon.java
new file mode 100644
index 0000000..07247bb
--- /dev/null
+++ b/jdk/test/java/lang/ThreadGroup/Daemon.java
@@ -0,0 +1,60 @@
+/*
+ * Copyright 2003 Sun Microsystems, Inc.  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 Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
+ * CA 95054 USA or visit www.sun.com if you need additional information or
+ * have any questions.
+ */
+
+/*
+ * @test
+ * @bug 4950216 4089701 4956093
+ * @summary Test for premature destruction of daemon threadgroups
+ */
+
+public class Daemon {
+
+    public static void main(String args[]) throws Exception {
+        ThreadGroup tg = new ThreadGroup("madbot-threads");
+        Thread myThread = new MadThread(tg,"mad");
+        ThreadGroup aGroup = new ThreadGroup(tg, "ness");
+        tg.setDaemon(true);
+        if (tg.activeCount() != 0)
+            throw new RuntimeException("activeCount");
+        aGroup.destroy();
+        if (tg.isDestroyed())
+            throw new RuntimeException("destroy");
+        try {
+            Thread anotherThread = new MadThread(aGroup, "bot");
+            throw new RuntimeException("illegal");
+        } catch (IllegalThreadStateException itse) {
+            // Correct result
+        }
+    }
+}
+
+class MadThread extends Thread {
+    String name;
+    MadThread(ThreadGroup tg, String name) {
+        super(tg, name);
+        this.name = name;
+    }
+    public void run() {
+        System.out.println("me run "+name);
+    }
+}
diff --git a/jdk/test/java/lang/ThreadGroup/SetMaxPriority.java b/jdk/test/java/lang/ThreadGroup/SetMaxPriority.java
new file mode 100644
index 0000000..b0fd10d
--- /dev/null
+++ b/jdk/test/java/lang/ThreadGroup/SetMaxPriority.java
@@ -0,0 +1,69 @@
+/*
+ * Copyright 2007 Sun Microsystems, Inc.  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 Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
+ * CA 95054 USA or visit www.sun.com if you need additional information or
+ * have any questions.
+ */
+
+/*
+ * @test
+ * @bug 4708197 6497629
+ * @summary Test for max priority setting that matches spec
+ * @author Pete Soper
+ */
+
+public class SetMaxPriority {
+
+    public static void main(String args[]) throws Exception {
+        ThreadGroup tg = new ThreadGroup("foo");
+        ThreadGroup ptg = tg.getParent();
+        int currentMaxPriority = tg.getMaxPriority();
+        int halfMaxPriority = ptg.getMaxPriority() / 2;
+        if (halfMaxPriority - Thread.MIN_PRIORITY < 2) {
+            throw new RuntimeException("SetMaxPriority test no longer valid: starting parent max priority too close to Thread.MIN_PRIORITY");
+        }
+        tg.setMaxPriority(halfMaxPriority - 2);
+        currentMaxPriority = tg.getMaxPriority();
+        if (currentMaxPriority != halfMaxPriority - 2) {
+            throw new RuntimeException("SetMaxPriority failed: max priority not changed");
+        }
+
+        // This will fail if bug 6497629 is present because the min tests is
+        // being made with the (just lowered) max instead of the parent max,
+        // preventing the priority from being moved back up.
+        tg.setMaxPriority(currentMaxPriority + 1);
+        int newMaxPriority = tg.getMaxPriority();
+        if (newMaxPriority != currentMaxPriority + 1) {
+            throw new RuntimeException("SetMaxPriority failed: defect 6497629 present");
+        }
+
+        // Confirm that max priorities out of range on both ends have no
+        // effect.
+        for (int badPriority : new int[] {Thread.MIN_PRIORITY - 1,
+                                          Thread.MAX_PRIORITY + 1}) {
+            int oldPriority = tg.getMaxPriority();
+            tg.setMaxPriority(badPriority);
+            if (oldPriority != tg.getMaxPriority())
+                throw new RuntimeException(
+                    "setMaxPriority bad arg not ignored as specified");
+        }
+
+        System.out.println("SetMaxPriority passed");
+    }
+}
diff --git a/jdk/test/java/lang/ThreadGroup/Stop.java b/jdk/test/java/lang/ThreadGroup/Stop.java
new file mode 100644
index 0000000..75fbb87
--- /dev/null
+++ b/jdk/test/java/lang/ThreadGroup/Stop.java
@@ -0,0 +1,66 @@
+/*
+ * Copyright 1999 Sun Microsystems, Inc.  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 Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
+ * CA 95054 USA or visit www.sun.com if you need additional information or
+ * have any questions.
+ */
+
+/**
+ * @test
+ * @bug 4176355
+ * @summary Stopping a ThreadGroup that contains the current thread has
+ *          unpredictable results.
+ */
+
+public class Stop implements Runnable {
+    private static Thread first=null;
+    private static Thread second=null;
+    private static ThreadGroup group = new ThreadGroup("");
+
+    Stop() {
+        Thread thread = new Thread(group, this);
+        if (first == null)
+            first = thread;
+        else
+            second = thread;
+
+        thread.start();
+    }
+
+    public void run() {
+        while (true) {
+            try {
+                Thread.sleep(1000); // Give other thread a chance to start
+                if (Thread.currentThread() == first)
+                    group.stop();
+            } catch(InterruptedException e){
+            }
+        }
+    }
+
+    public static void main(String[] args) throws Exception {
+        for (int i=0; i<2; i++)
+            new Stop();
+        Thread.sleep(3000);
+        boolean failed = second.isAlive();
+        first.stop(); second.stop();
+        if (failed)
+            throw new RuntimeException("Failure.");
+    }
+}
diff --git a/jdk/test/java/lang/ThreadGroup/Suspend.java b/jdk/test/java/lang/ThreadGroup/Suspend.java
new file mode 100644
index 0000000..6e54d3f1
--- /dev/null
+++ b/jdk/test/java/lang/ThreadGroup/Suspend.java
@@ -0,0 +1,69 @@
+/*
+ * Copyright 1999 Sun Microsystems, Inc.  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 Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
+ * CA 95054 USA or visit www.sun.com if you need additional information or
+ * have any questions.
+ */
+
+/**
+ * @test
+ * @bug 4176355
+ * @summary Suspending a ThreadGroup that contains the current thread has
+ *          unpredictable results.
+ */
+
+public class Suspend implements Runnable {
+    private static Thread first=null;
+    private static Thread second=null;
+    private static ThreadGroup group = new ThreadGroup("");
+    private static int count = 0;
+
+    Suspend() {
+        Thread thread = new Thread(group, this);
+        if (first == null)
+            first = thread;
+        else
+            second = thread;
+
+        thread.start();
+    }
+
+    public void run() {
+        while (true) {
+            try {
+                Thread.sleep(1000); // Give other thread a chance to start
+                if (Thread.currentThread() == first)
+                    group.suspend();
+                else
+                    count++;
+            } catch(InterruptedException e){
+            }
+        }
+    }
+
+    public static void main(String[] args) throws Exception {
+        for (int i=0; i<2; i++)
+            new Suspend();
+        Thread.sleep(3000);
+        boolean failed = (count > 1);
+        first.stop(); second.stop();
+        if (failed)
+            throw new RuntimeException("Failure.");
+    }
+}
diff --git a/jdk/test/java/lang/ThreadLocal/Basic.java b/jdk/test/java/lang/ThreadLocal/Basic.java
new file mode 100644
index 0000000..90edc50
--- /dev/null
+++ b/jdk/test/java/lang/ThreadLocal/Basic.java
@@ -0,0 +1,66 @@
+/*
+ * Copyright 1999 Sun Microsystems, Inc.  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 Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
+ * CA 95054 USA or visit www.sun.com if you need additional information or
+ * have any questions.
+ */
+
+/*
+ * @test
+ * @summary Basic functional test of ThreadLocal
+ * @author Josh Bloch
+ */
+
+public class Basic {
+    static ThreadLocal n = new ThreadLocal() {
+        int i = 0;
+        protected synchronized Object initialValue() {
+            return new Integer(i++);
+        }
+    };
+
+    public static void main(String args[]) throws Exception {
+        int threadCount = 100;
+        Thread th[] = new Thread[threadCount];
+        final int x[] = new int[threadCount];
+
+        // Start the threads
+        for(int i=0; i<threadCount; i++) {
+            th[i] = new Thread() {
+                public void run() {
+                    int threadId = ((Integer)(n.get())).intValue();
+                    for (int j=0; j<threadId; j++) {
+                        x[threadId]++;
+                        Thread.currentThread().yield();
+                    }
+                }
+            };
+            th[i].start();
+        }
+
+        // Wait for the threads to finish
+        for(int i=0; i<threadCount; i++)
+            th[i].join();
+
+        // Check results
+        for(int i=0; i<threadCount; i++)
+            if (x[i] != i)
+                throw(new Exception("x[" + i + "] =" + x[i]));
+    }
+}
diff --git a/jdk/test/java/lang/ThreadLocal/ImmutableLocal.java b/jdk/test/java/lang/ThreadLocal/ImmutableLocal.java
new file mode 100644
index 0000000..df6c86d
--- /dev/null
+++ b/jdk/test/java/lang/ThreadLocal/ImmutableLocal.java
@@ -0,0 +1,53 @@
+/*
+ * Copyright 2006 Sun Microsystems, Inc.  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 Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
+ * CA 95054 USA or visit www.sun.com if you need additional information or
+ * have any questions.
+ */
+
+/*
+ * @test
+ * @bug     6387919
+ * @summary Confirm ThreadLocal.set() usage is not a side effect of get()
+ * @author  Pete Soper
+ */
+public class ImmutableLocal
+{
+    /**
+     * {@link ThreadLocal} guaranteed to always return the same reference.
+     */
+    abstract public static class ImmutableThreadLocal extends ThreadLocal {
+        public void set(final Object value) {
+            throw new RuntimeException("ImmutableThreadLocal set called");
+        }
+
+        // force override
+        abstract protected Object initialValue();
+    }
+
+    private static final ThreadLocal cache = new ImmutableThreadLocal() {
+        public Object initialValue() {
+            return Thread.currentThread().getName();
+        }
+    };
+
+    public static void main(final String[] args) {
+        System.out.println("cache.get() = " + cache.get());
+    }
+}
diff --git a/jdk/test/java/lang/ThreadLocal/InitialValue.java b/jdk/test/java/lang/ThreadLocal/InitialValue.java
new file mode 100644
index 0000000..61d5feb
--- /dev/null
+++ b/jdk/test/java/lang/ThreadLocal/InitialValue.java
@@ -0,0 +1,74 @@
+/*
+ * Copyright 2005 Sun Microsystems, Inc.  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 Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
+ * CA 95054 USA or visit www.sun.com if you need additional information or
+ * have any questions.
+ */
+
+/*
+ * @test
+ * @bug     5025230
+ * @summary Tests to see that a set nested in initialValue works OK
+ * @author  Pete Soper
+ */
+public class InitialValue implements Runnable {
+
+    static ThreadLocal<String> other;
+    static boolean passed;
+
+    public class MyLocal extends ThreadLocal<String> {
+        String val;
+        protected String initialValue() {
+            other = new ThreadLocal<String>();
+            // This should reuse the map that the containing get() created
+            // or visa versa (i.e. instead of a second map being created).
+            other.set("Other");
+            return "Initial";
+        }
+    }
+
+    public void run() {
+        MyLocal l = new MyLocal();
+        // This should pick up the initial value
+        String s1 = l.get();
+        // And this should pick up the other local in this thread's locals map
+        String s2 = other.get();
+        if ((s2 != null) && s2.equals("Other")) {
+            // JMM guarantees this will be visible to
+            // another thread joining with this thread's
+            // termination: no need for this to be volatile.
+            passed = true;
+        }
+    }
+
+    public static void main(String[] args) {
+        // Starting with Mustang the main thread already has an initialized
+        // ThreadLocal map at this point, so test with a second thread.
+        Thread t = new Thread(new InitialValue());
+        t.start();
+        try {
+            t.join();
+        } catch (InterruptedException e) {
+            throw new RuntimeException("Test Interrupted: failed");
+        }
+        if (!passed) {
+            throw new RuntimeException("Test Failed");
+        }
+    }
+}
diff --git a/jdk/test/java/lang/ThreadLocal/MemoryLeak.java b/jdk/test/java/lang/ThreadLocal/MemoryLeak.java
new file mode 100644
index 0000000..8e90df5
--- /dev/null
+++ b/jdk/test/java/lang/ThreadLocal/MemoryLeak.java
@@ -0,0 +1,39 @@
+/*
+ * Copyright 2001 Sun Microsystems, Inc.  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 Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
+ * CA 95054 USA or visit www.sun.com if you need additional information or
+ * have any questions.
+ */
+
+/*
+ * @test
+ * @bug     4414045
+ * @summary Tests to see that memory leak no longer exists.
+ * @author  Josh Bloch
+ */
+
+public class MemoryLeak {
+    public static void main(String[] args) {
+        for (int i = 0; i < 1100000; i++) {
+            ThreadLocal t = new ThreadLocal();
+            t.set(new Object());
+            t.set(null);
+        }
+    }
+}
diff --git a/jdk/test/java/lang/ThreadLocal/TLRemoveTest.java b/jdk/test/java/lang/ThreadLocal/TLRemoveTest.java
new file mode 100644
index 0000000..46f3a8a
--- /dev/null
+++ b/jdk/test/java/lang/ThreadLocal/TLRemoveTest.java
@@ -0,0 +1,115 @@
+/*
+ * Copyright 2004 Sun Microsystems, Inc.  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 Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
+ * CA 95054 USA or visit www.sun.com if you need additional information or
+ * have any questions.
+ */
+
+/*
+ * @test
+ * @summary Basic functional test of remove method for ThreadLocal
+ * @author Seetharama Avadhanam
+ */
+
+public class TLRemoveTest {
+    private static final int INITIAL_VALUE = 101;
+    private static final int REMOVE_SET_VALUE = 102;
+
+    static ThreadLocal<Integer> n = new ThreadLocal<Integer>() {
+        protected synchronized Integer initialValue() {
+            return INITIAL_VALUE;
+        }
+    };
+
+    public static void main(String args[]) throws Throwable {
+        int threadCount = 100;
+        final int[] removeNode = {10,20,45,38};
+        // ThreadLocal values will be removed for these threads.
+        final int[] removeAndSet = {12,34,10};
+        // ThreadLocal values will be removed and sets new values..
+
+        Thread th[] = new Thread[threadCount];
+        final int x[] = new int[threadCount];
+        final Throwable exceptions[] = new Throwable[threadCount];
+
+        for(int i = 0; i<threadCount; i++) {
+            final int threadId = i;
+            th[i] = new Thread() {
+                public void run() {
+                    try{
+                        n.set(threadId); // Sets threadId as threadlocal value...
+                        for (int j = 0; j<threadId; j++)
+                            Thread.currentThread().yield();
+
+                        // To remove the ThreadLocal ....
+                        for(int removeId  : removeNode)
+                            if(threadId == removeId){
+                               n.remove(); // Removes ThreadLocal values..
+                               break;
+                            }
+
+                        // To remove the ThreadLocal value and set new value ...
+                        for(int removeId  : removeAndSet)
+                            if(threadId == removeId){
+                               n.remove(); // Removes the ThreadLocal Value...
+                               n.set(REMOVE_SET_VALUE); /* Setting new Values to
+                                                          ThreadLocal */
+                               break;
+                            }
+                            /* Storing the threadlocal values in 'x'
+                               ...so that it can be used for checking results... */
+                        x[threadId] = n.get();
+                    }
+                    catch(Throwable ex){
+                        exceptions[threadId] = ex;
+                    }
+                }
+            };
+            th[i].start();
+        }
+
+        // Wait for the threads to finish
+        for(int i = 0; i<threadCount; i++)
+            th[i].join();
+
+        // Check results
+        for(int i = 0; i<threadCount; i++){
+            int checkValue = i;
+
+            /* If the remove method is called then the ThreadLocal value will
+             * be its initial value */
+            for(int removeId : removeNode)
+                if(removeId == i){
+                    checkValue = INITIAL_VALUE;
+                    break;
+                }
+
+            for(int removeId : removeAndSet)
+                if(removeId == i){
+                    checkValue = REMOVE_SET_VALUE;
+                    break;
+                }
+
+            if(exceptions[i] != null)
+                throw(exceptions[i]);
+            if(x[i] != checkValue)
+                throw(new Throwable("x[" + i + "] =" + x[i]));
+        }
+    }
+}
diff --git a/jdk/test/java/lang/ThreadLocal/TestThreadId.java b/jdk/test/java/lang/ThreadLocal/TestThreadId.java
new file mode 100644
index 0000000..4380547
--- /dev/null
+++ b/jdk/test/java/lang/ThreadLocal/TestThreadId.java
@@ -0,0 +1,93 @@
+/*
+ * Copyright 2007 Sun Microsystems, Inc.  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 Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
+ * CA 95054 USA or visit www.sun.com if you need additional information or
+ * have any questions.
+ */
+
+/*
+ * @test
+ * @bug     6434084
+ * @summary Exercise ThreadLocal javadoc "demo" class ThreadId
+ * @author  Pete Soper
+ */
+
+public final class TestThreadId extends Thread {
+
+    // number of times to create threads and gather their ids
+    private static final int ITERATIONCOUNT = 50;
+
+    // Threads constructed per iteration. ITERATIONCOUNT=50 and
+    // THREADCOUNT=50 takes about one second on a sun Blade 1000 (2x750mhz)
+    private static final int THREADCOUNT = 50;
+
+    // The thread local storage object for holding per-thread ids
+    private static ThreadId id = new ThreadId();
+
+    // Holds the per-thread so main method thread can collect it. JMM
+    // guarantees this is valid after this thread joins main method thread.
+    private int value;
+
+    private synchronized int getIdValue() {
+        return value;
+    }
+
+    // Each child thread just publishes its id value for validation
+    public void run() {
+        value = id.get();
+    }
+
+    public static void main(String args[]) throws Throwable {
+
+        // holds true corresponding to a used id value
+        boolean check[] = new boolean[THREADCOUNT*ITERATIONCOUNT];
+
+        // the test threads
+        TestThreadId u[] = new TestThreadId[THREADCOUNT];
+
+        for (int i = 0; i < ITERATIONCOUNT; i++) {
+            // Create and start the threads
+            for (int t=0;t<THREADCOUNT;t++) {
+                u[t] = new TestThreadId();
+                u[t].start();
+            }
+            // Join with each thread and get/check its id
+            for (int t=0;t<THREADCOUNT;t++) {
+                try {
+                    u[t].join();
+                } catch (InterruptedException e) {
+                     throw new RuntimeException(
+                        "TestThreadId: Failed with unexpected exception" + e);
+                }
+                try {
+                    if (check[u[t].getIdValue()]) {
+                        throw new RuntimeException(
+                            "TestThreadId: Failed with duplicated id: " +
+                                u[t].getIdValue());
+                    } else {
+                        check[u[t].getIdValue()] = true;
+                    }
+                } catch (Exception e) {
+                    throw new RuntimeException(
+                        "TestThreadId: Failed with unexpected id value" + e);
+                }
+            }
+        }
+    } // main
+} // TestThreadId
diff --git a/jdk/test/java/lang/ThreadLocal/ThreadId.java b/jdk/test/java/lang/ThreadLocal/ThreadId.java
new file mode 100644
index 0000000..dd58b34
--- /dev/null
+++ b/jdk/test/java/lang/ThreadLocal/ThreadId.java
@@ -0,0 +1,52 @@
+/*
+ * Copyright 2007 Sun Microsystems, Inc.  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 Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
+ * CA 95054 USA or visit www.sun.com if you need additional information or
+ * have any questions.
+ */
+
+/*
+ *
+ *
+ * Example class from java.lang.ThreadLocal class doc. Used by
+ * TestThreadId.java
+ */
+
+// Josh Bloch suggested this latest version after many inputs from other
+// EG members and JUC list subscribers
+
+import java.util.concurrent.atomic.AtomicInteger;
+
+public class ThreadId {
+    // Atomic integer containing the next thread ID to be assigned
+    private static final AtomicInteger nextId = new AtomicInteger(0);
+
+    // Thread local variable containing each thread's ID
+    private static final ThreadLocal<Integer> threadId =
+        new ThreadLocal<Integer>() {
+            @Override protected Integer initialValue() {
+                return nextId.getAndIncrement();
+        }
+    };
+
+    // Returns the current thread's unique ID, assigning it if necessary
+    public static int get() {
+        return threadId.get();
+    }
+}
diff --git a/jdk/test/java/lang/Throwable/ChainedExceptions.java b/jdk/test/java/lang/Throwable/ChainedExceptions.java
new file mode 100644
index 0000000..a6577ba
--- /dev/null
+++ b/jdk/test/java/lang/Throwable/ChainedExceptions.java
@@ -0,0 +1,92 @@
+/*
+ * @test    /nodynamiccopyright/
+ * @bug     4209652 4363318
+ * @summary Basic test for chained exceptions & Exception.getStackTrace().
+ * @author  Josh Bloch
+ */
+
+public class ChainedExceptions {
+    public static void main(String args[]) {
+        try {
+            a();
+        } catch(HighLevelException e) {
+            StackTraceElement[] highTrace = e.getStackTrace();
+            int depthTrim = highTrace.length - 2;
+
+            check(highTrace[0], "a",    48);
+            check(highTrace[1], "main", 11);
+
+            Throwable mid = e.getCause();
+            StackTraceElement[] midTrace = mid.getStackTrace();
+            if (midTrace.length - depthTrim != 4)
+                throw new RuntimeException("Mid depth");
+            check(midTrace[0], "c",    58);
+            check(midTrace[1], "b",    52);
+            check(midTrace[2], "a",    46);
+            check(midTrace[3], "main", 11);
+
+            Throwable low = mid.getCause();
+            StackTraceElement[] lowTrace = low.getStackTrace();
+            if (lowTrace.length - depthTrim != 6)
+                throw new RuntimeException("Low depth");
+            check(lowTrace[0], "e",    65);
+            check(lowTrace[1], "d",    62);
+            check(lowTrace[2], "c",    56);
+            check(lowTrace[3], "b",    52);
+            check(lowTrace[4], "a",    46);
+            check(lowTrace[5], "main", 11);
+
+            if (low.getCause() != null)
+                throw new RuntimeException("Low cause != null");
+        }
+    }
+
+    static void a() throws HighLevelException {
+        try {
+            b();
+        } catch(MidLevelException e) {
+            throw new HighLevelException(e);
+        }
+    }
+    static void b() throws MidLevelException {
+        c();
+    }
+    static void c() throws MidLevelException {
+        try {
+            d();
+        } catch(LowLevelException e) {
+            throw new MidLevelException(e);
+        }
+    }
+    static void d() throws LowLevelException {
+       e();
+    }
+    static void e() throws LowLevelException {
+        throw new LowLevelException();
+    }
+
+    private static final String OUR_CLASS  = ChainedExceptions.class.getName();
+    private static final String OUR_FILE_NAME = "ChainedExceptions.java";
+
+    private static void check(StackTraceElement e, String methodName, int n) {
+        if (!e.getClassName().equals(OUR_CLASS))
+            throw new RuntimeException("Class: " + e);
+        if (!e.getMethodName().equals(methodName))
+            throw new RuntimeException("Method name: " + e);
+        if (!e.getFileName().equals(OUR_FILE_NAME))
+            throw new RuntimeException("File name: " + e);
+        if (e.getLineNumber() != n)
+            throw new RuntimeException("Line number: " + e);
+    }
+}
+
+class HighLevelException extends Exception {
+    HighLevelException(Throwable cause) { super(cause); }
+}
+
+class MidLevelException extends Exception {
+    MidLevelException(Throwable cause)  { super(cause); }
+}
+
+class LowLevelException extends Exception {
+}
diff --git a/jdk/test/java/lang/Throwable/LegacyChainedExceptionSerialization.java b/jdk/test/java/lang/Throwable/LegacyChainedExceptionSerialization.java
new file mode 100644
index 0000000..efa478e
--- /dev/null
+++ b/jdk/test/java/lang/Throwable/LegacyChainedExceptionSerialization.java
@@ -0,0 +1,59 @@
+/*
+ * Copyright 2000 Sun Microsystems, Inc.  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 Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
+ * CA 95054 USA or visit www.sun.com if you need additional information or
+ * have any questions.
+ */
+
+import java.io.*;
+
+/**
+ * @test
+ * @bug     4385429
+ * @summary Certain legacy chained exceptions throw IllegalArgumentException
+ *          upon deserialization if "causative exception" is null.
+ * @author  Josh Bloch
+ */
+public class LegacyChainedExceptionSerialization {
+    private static Throwable[] broken = {
+        new ClassNotFoundException(),
+        new ExceptionInInitializerError(),
+        new java.lang.reflect.UndeclaredThrowableException(null),
+        new java.lang.reflect.InvocationTargetException(null),
+        new java.security.PrivilegedActionException(null),
+        new java.awt.print.PrinterIOException(null)
+    };
+
+    public static void main(String[] args) throws Exception {
+        for (int i=0; i<broken.length; i++)
+            test(broken[i]);
+    }
+
+    private static void test(Throwable e) throws Exception {
+        ByteArrayOutputStream bout = new ByteArrayOutputStream();
+        ObjectOutputStream out = new ObjectOutputStream(bout);
+        out.writeObject(e);
+        out.flush();
+
+        ByteArrayInputStream bin =
+            new ByteArrayInputStream(bout.toByteArray());
+        ObjectInputStream in = new ObjectInputStream(bin);
+        Throwable clone = (Throwable) in.readObject();
+    }
+}
diff --git a/jdk/test/java/lang/Throwable/LocalizedMessage.java b/jdk/test/java/lang/Throwable/LocalizedMessage.java
new file mode 100644
index 0000000..f19acd3
--- /dev/null
+++ b/jdk/test/java/lang/Throwable/LocalizedMessage.java
@@ -0,0 +1,53 @@
+/*
+ * Copyright 1998-2000 Sun Microsystems, Inc.  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 Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
+ * CA 95054 USA or visit www.sun.com if you need additional information or
+ * have any questions.
+ */
+
+/* @test
+   @bug 4059406
+   @summary Throwable.toString() should call getLocalizedMessage()
+   @author Anand Palaniswamy
+ */
+public class LocalizedMessage {
+
+    static class LocalizedException extends Throwable {
+
+        boolean localizedMessageCalled = false;
+
+        LocalizedException() {
+            localizedMessageCalled = false;
+        }
+
+        public String getLocalizedMessage() {
+            localizedMessageCalled = true;
+            return new String("FOOBAR");
+        }
+    }
+
+    public static void main(String[] args) throws Exception {
+        LocalizedException e = new LocalizedException();
+        e.toString();
+        if (!e.localizedMessageCalled) {
+            throw new Exception("Throwable.toString() must call " +
+                                "getLocalizedMessage()");
+        }
+    }
+}
diff --git a/jdk/test/java/lang/Throwable/NewChainedExceptions.java b/jdk/test/java/lang/Throwable/NewChainedExceptions.java
new file mode 100644
index 0000000..2b38e6c
--- /dev/null
+++ b/jdk/test/java/lang/Throwable/NewChainedExceptions.java
@@ -0,0 +1,81 @@
+/*
+ * Copyright 2003 Sun Microsystems, Inc.  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 Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
+ * CA 95054 USA or visit www.sun.com if you need additional information or
+ * have any questions.
+ */
+
+/*
+ * @test
+ * @bug     4836801
+ * @summary Basic test for new chained exceptions added in 1.5
+ * @author  Josh Bloch
+ */
+
+public class NewChainedExceptions {
+    public static void main(String args[]) {
+        Throwable interior = new Exception();
+        String    message  = "Good heavens!";
+
+        try {
+            throw new IllegalStateException(message, interior);
+        } catch(IllegalStateException e) {
+            if (!(e.getCause() == interior && e.getMessage() == message))
+                throw new RuntimeException("1");
+        }
+
+        try {
+            throw new IllegalStateException(interior);
+        } catch(IllegalStateException e) {
+            if (!(e.getCause() == interior &&
+                  e.getMessage().equals(interior.toString())))
+                throw new RuntimeException("2");
+        }
+
+        try {
+            throw new IllegalArgumentException(message, interior);
+        } catch(IllegalArgumentException e) {
+            if (!(e.getCause() == interior && e.getMessage() == message))
+                throw new RuntimeException("3");
+        }
+
+        try {
+            throw new IllegalArgumentException(interior);
+        } catch(IllegalArgumentException e) {
+            if (!(e.getCause() == interior &&
+                  e.getMessage().equals(interior.toString())))
+                throw new RuntimeException("4");
+        }
+
+        try {
+            throw new UnsupportedOperationException(message, interior);
+        } catch(UnsupportedOperationException e) {
+            if (!(e.getCause() == interior && e.getMessage() == message))
+                throw new RuntimeException("5");
+        }
+
+        try {
+            throw new UnsupportedOperationException(interior);
+        } catch(UnsupportedOperationException e) {
+            if (!(e.getCause() == interior &&
+                  e.getMessage().equals(interior.toString())))
+                throw new RuntimeException("6");
+        }
+    }
+}
diff --git a/jdk/test/java/lang/Throwable/StackTraceSerialization.java b/jdk/test/java/lang/Throwable/StackTraceSerialization.java
new file mode 100644
index 0000000..2fb0473
--- /dev/null
+++ b/jdk/test/java/lang/Throwable/StackTraceSerialization.java
@@ -0,0 +1,114 @@
+/*
+ * Copyright 2000-2001 Sun Microsystems, Inc.  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 Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
+ * CA 95054 USA or visit www.sun.com if you need additional information or
+ * have any questions.
+ */
+
+import java.io.*;
+import java.util.*;
+
+/*
+ * @test
+ * @bug     4202914 4363318
+ * @summary Basic test of serialization of stack trace information
+ * @author  Josh Bloch
+ */
+
+public class StackTraceSerialization {
+    public static void main(String args[]) throws Exception {
+        Throwable original = null;
+        try {
+            a();
+        } catch(HighLevelException e) {
+            original = e;
+        }
+
+        ByteArrayOutputStream bout = new ByteArrayOutputStream();
+        ObjectOutputStream out = new ObjectOutputStream(bout);
+        out.writeObject(original);
+        out.flush();
+        ByteArrayInputStream bin =
+            new ByteArrayInputStream(bout.toByteArray());
+        ObjectInputStream in = new ObjectInputStream(bin);
+        Throwable clone = (Throwable) in.readObject();
+
+        if (!equal(original, clone))
+            throw new Exception();
+    }
+
+    /**
+     * Returns true if e1 and e2 have equal stack traces and their causes
+     * are recursively equal (by the same definition).  Returns false
+     * or throws NullPointerExeption otherwise.
+     */
+    private static boolean equal(Throwable t1, Throwable t2) {
+        return t1==t2 || (Arrays.equals(t1.getStackTrace(), t2.getStackTrace())
+                          && equal(t1.getCause(), t2.getCause()));
+    }
+
+    static void a() throws HighLevelException {
+        try {
+            b();
+        } catch(MidLevelException e) {
+            throw new HighLevelException(e);
+        }
+    }
+    static void b() throws MidLevelException {
+        c();
+    }
+    static void c() throws MidLevelException {
+        try {
+            d();
+        } catch(LowLevelException e) {
+            throw new MidLevelException(e);
+        }
+    }
+    static void d() throws LowLevelException {
+       e();
+    }
+    static void e() throws LowLevelException {
+        throw new LowLevelException();
+    }
+
+    private static final String OUR_CLASS  = StackTraceSerialization.class.getName();
+    private static final String OUR_FILE_NAME = "StackTraceSerialization.java";
+
+    private static void check(StackTraceElement e, String methodName, int n) {
+        if (!e.getClassName().equals(OUR_CLASS))
+            throw new RuntimeException("Class: " + e);
+        if (!e.getMethodName().equals(methodName))
+            throw new RuntimeException("Method name: " + e);
+        if (!e.getFileName().equals(OUR_FILE_NAME))
+            throw new RuntimeException("File name: " + e);
+        if (e.getLineNumber() != n)
+            throw new RuntimeException("Line number: " + e);
+    }
+}
+
+class HighLevelException extends Exception {
+    HighLevelException(Throwable cause) { super(cause); }
+}
+
+class MidLevelException extends Exception {
+    MidLevelException(Throwable cause)  { super(cause); }
+}
+
+class LowLevelException extends Exception {
+}
diff --git a/jdk/test/java/lang/instrument/AInstrumentationTestCase.java b/jdk/test/java/lang/instrument/AInstrumentationTestCase.java
new file mode 100644
index 0000000..d4d6ea1
--- /dev/null
+++ b/jdk/test/java/lang/instrument/AInstrumentationTestCase.java
@@ -0,0 +1,47 @@
+/*
+ * Copyright 2003 Sun Microsystems, Inc.  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 Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
+ * CA 95054 USA or visit www.sun.com if you need additional information or
+ * have any questions.
+ */
+
+import  java.lang.instrument.*;
+
+public abstract class AInstrumentationTestCase extends ATestCaseScaffold {
+
+    protected Instrumentation   fInst;
+
+    protected
+    AInstrumentationTestCase(String name) {
+        super(name);
+    }
+
+    protected void
+    setUp()
+        throws Exception {
+        fInst = InstrumentationHandoff.getInstrumentationOrThrow();
+    }
+
+    protected void
+    tearDown()
+        throws Exception {
+        fInst = null;
+    }
+
+}
diff --git a/jdk/test/java/lang/instrument/ASimpleInstrumentationTestCase.java b/jdk/test/java/lang/instrument/ASimpleInstrumentationTestCase.java
new file mode 100644
index 0000000..27074ac
--- /dev/null
+++ b/jdk/test/java/lang/instrument/ASimpleInstrumentationTestCase.java
@@ -0,0 +1,81 @@
+/*
+ * Copyright 2003 Sun Microsystems, Inc.  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 Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
+ * CA 95054 USA or visit www.sun.com if you need additional information or
+ * have any questions.
+ */
+
+import java.lang.instrument.*;
+import java.security.ProtectionDomain;
+import java.util.*;
+import java.io.*;
+import java.net.*;
+import java.lang.reflect.*;
+
+
+/*
+ * Copyright 2003 Wily Technology, Inc.
+ */
+
+/**
+ * Simple tests for the Instrumentation
+ *
+ */
+public abstract class
+ASimpleInstrumentationTestCase
+    extends AInstrumentationTestCase
+{
+
+    /**
+     * Constructor for ASimpleInstrumentationTestCase.
+     */
+    public ASimpleInstrumentationTestCase(String name)
+    {
+        super(name);
+
+    }
+
+    protected void
+    assertClassArrayContainsClass(Class[] list, Class target)
+        {
+        boolean inList = false;
+        for ( int x = 0; x < list.length; x++ )
+            {
+            if ( list[x] == target )
+                {
+                inList = true;
+                }
+            }
+        assertTrue(inList);
+        }
+
+    protected void
+    assertClassArrayDoesNotContainClassByName(Class[] list, String name)
+        {
+        boolean inList = false;
+        for ( int x = 0; x < list.length; x++ )
+            {
+            if ( list[x].getName().equals(name) )
+                {
+                fail();
+                }
+            }
+        }
+
+}
diff --git a/jdk/test/java/lang/instrument/ATestCaseScaffold.java b/jdk/test/java/lang/instrument/ATestCaseScaffold.java
new file mode 100644
index 0000000..8f3bbc8
--- /dev/null
+++ b/jdk/test/java/lang/instrument/ATestCaseScaffold.java
@@ -0,0 +1,186 @@
+/*
+ * Copyright 2003-2005 Sun Microsystems, Inc.  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 Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
+ * CA 95054 USA or visit www.sun.com if you need additional information or
+ * have any questions.
+ */
+
+/*
+ * Copyright 2003 Wily Technology, Inc.
+ */
+
+/**
+ *  This class serves as a bridge between the Wily JUnit-style tests and the
+ *  Sun test framework.
+ *
+ *  This is a replacement for the JUnit TestCase base class. Provides surrogate
+ *  functionality for the setup/teardown calls, and for all the verification and
+ *  assertion services.
+ *
+ *  The Sun framework relies on each test case being a separate class with a separate main,
+ *  which throws if the test fails and does not throw if the test succeeds.
+ */
+
+
+public abstract class ATestCaseScaffold {
+    private String      fName;
+    private boolean     fVerbose;
+
+
+    protected
+    ATestCaseScaffold(String name) {
+        fName = name;
+        fVerbose = false;
+    }
+
+    public final void
+    runTest()
+        throws Throwable {
+        Throwable toRethrow = null;
+
+        setUp();
+
+        try {
+            doRunTest();
+        }
+        finally {
+            tearDown();
+        }
+
+    }
+
+    protected void
+    setUp()
+        throws Exception {
+    }
+
+    protected void
+    tearDown()
+        throws Exception {
+    }
+
+    protected abstract void
+    doRunTest()
+        throws Throwable;
+
+    /**
+     * Be verbose: print out what happens after this
+     */
+    public void
+    beVerbose()
+    {
+        fVerbose = true;
+    }
+
+    /**
+     * Print a string, if and only if verbose printing is enabled.
+     */
+    public void
+    verbosePrint(String message)
+    {
+        if (fVerbose)
+        {
+            System.out.println("Debugging message: " + message);
+        }
+    }
+
+    /*
+     *  Replacement verification methods
+     *  Shaped the same as the JUnit ones to make reusing the JUnit test possible
+     *  Didn't implement them all, only the ones our existing tests use.
+     */
+
+    public final void
+    fail() {
+        throw new TestCaseScaffoldException();
+    }
+
+    public final void
+    fail(String message) {
+        throw new TestCaseScaffoldException(message);
+    }
+
+    public final void
+    assertTrue(boolean condition) {
+        if ( !condition ) {
+            fail();
+        }
+    }
+
+    public final void
+    assertTrue(String message, boolean condition) {
+        if ( !condition ) {
+            fail(message);
+        }
+    }
+
+    public final void
+    assertNotNull(Object o) {
+        assertTrue(o != null);
+    }
+
+    public final void
+    assertNotNull(String message, Object o) {
+        assertTrue(message, o != null);
+    }
+
+    public final void
+    assertEquals(String message, Object expected, Object actual) {
+        if ( (expected == null) && (actual == null) ) {
+            return;
+        }
+        else if ( (expected != null) && (expected.equals(actual)) ) {
+            return;
+        }
+        else {
+            throw new TestCaseScaffoldException(message + ". Expected: '" + expected +
+                                                "'. Actual: '" + actual + "'.");
+        }
+    }
+
+    public final void
+    assertEquals(Object expected, Object actual) {
+        assertEquals(null, expected, actual);
+    }
+
+    public final void
+    assertEquals(String message, int expected, int actual) {
+        assertEquals(message, new Integer(expected), new Integer(actual));
+    }
+
+    public final void
+    assertEquals(int expected, int actual) {
+        assertEquals("Expected equality", expected, actual);
+    }
+
+    public final static class
+    TestCaseScaffoldException extends RuntimeException {
+        public
+        TestCaseScaffoldException() {
+            super();
+        }
+
+        public
+        TestCaseScaffoldException(String m) {
+            super(m);
+        }
+
+    }
+
+}
diff --git a/jdk/test/java/lang/instrument/ATransformerManagementTestCase.java b/jdk/test/java/lang/instrument/ATransformerManagementTestCase.java
new file mode 100644
index 0000000..0a8f709
--- /dev/null
+++ b/jdk/test/java/lang/instrument/ATransformerManagementTestCase.java
@@ -0,0 +1,319 @@
+/*
+ * Copyright 2003-2005 Sun Microsystems, Inc.  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 Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
+ * CA 95054 USA or visit www.sun.com if you need additional information or
+ * have any questions.
+ */
+
+
+import java.io.*;
+import java.lang.instrument.*;
+
+import java.security.ProtectionDomain;
+import java.util.*;
+
+
+/**
+ * Simple tests for the TransformerManager
+ *
+ */
+public abstract class
+ATransformerManagementTestCase
+    extends AInstrumentationTestCase
+{
+    private static final String redefinedClassName = "DummyClass";
+
+    protected int   kModSamples = 2;
+    public final    ClassFileTransformer[] kTransformerSamples = new ClassFileTransformer[]
+        {
+            new MyClassFileTransformer(         Integer.toString(0)),
+            new MyClassFileTransformer( Integer.toString(1)),
+            new MyClassFileTransformer(         Integer.toString(2)),
+            new MyClassFileTransformer( Integer.toString(3)),
+            new MyClassFileTransformer(         Integer.toString(4)),
+            new MyClassFileTransformer( Integer.toString(5)),
+            new MyClassFileTransformer(         Integer.toString(6)),
+            new MyClassFileTransformer( Integer.toString(7)),
+            new MyClassFileTransformer(         Integer.toString(8)),
+            new MyClassFileTransformer( Integer.toString(9)),
+            new MyClassFileTransformer(         Integer.toString(10)),
+            new MyClassFileTransformer( Integer.toString(11)),
+            new MyClassFileTransformer( Integer.toString(12)),
+            new MyClassFileTransformer( Integer.toString(13)),
+            new MyClassFileTransformer(         Integer.toString(14)),
+            new MyClassFileTransformer( Integer.toString(15)),
+            new MyClassFileTransformer(         Integer.toString(16)),
+            new MyClassFileTransformer(         Integer.toString(17)),
+            new MyClassFileTransformer( Integer.toString(18)),
+        };
+
+    private ArrayList           fTransformers;       // The list of transformers
+    private int                 fTransformerIndex;   // The number of transformers encountered
+    private String              fDelayedFailure;     // Set non-null if failed in transformer
+
+
+    /**
+     * Constructor for ATransformerManagementTestCase.
+     */
+    public ATransformerManagementTestCase(String name)
+    {
+        super(name);
+    }
+
+
+    /**
+     * Returns one of the sample transformers
+     * @return a random transformer
+     */
+    protected ClassFileTransformer
+    getRandomTransformer()
+    {
+        int randIndex = (int)Math.floor(Math.random() * kTransformerSamples.length);
+        verbosePrint("Choosing random transformer #" + randIndex);
+        return kTransformerSamples[randIndex];
+    }
+
+    /**
+     * Method addTransformerToManager.
+     * @param manager
+     * @param transformer
+     */
+    protected void
+    addTransformerToManager(
+        Instrumentation         manager,
+        ClassFileTransformer    transformer)
+    {
+        if (transformer != null)
+        {
+            fTransformers.add(transformer);
+        }
+        manager.addTransformer(transformer);
+        verbosePrint("Added transformer " + transformer);
+    }
+
+    /**
+     * Remove transformer from manager and list
+     * @param manager
+     * @param transformer
+     */
+    protected void
+    removeTransformerFromManager(
+        Instrumentation manager,
+        ClassFileTransformer transformer)
+    {
+        assertTrue("Transformer not found in manager ("+transformer+")", manager.removeTransformer(transformer));
+
+        if (transformer != null)
+        {
+            fTransformers.remove(transformer);
+        }
+        verbosePrint("Removed transformer " + transformer);
+    }
+
+    /**
+     * Decrements the transformer index as well as removes transformer
+     * @param fInst         manager
+     * @param transformer       transformer to remove
+     * @param decrementIndex    the tranformer index gets out of sync with transformers
+     *                          that are removed from the manager
+     */
+    protected void
+    removeTransformerFromManager(   Instrumentation manager,
+                                    ClassFileTransformer transformer,
+                                    boolean decrementIndex)
+    {
+        removeTransformerFromManager(manager, transformer);
+        if (decrementIndex)
+        {
+            fTransformerIndex--;
+            verbosePrint("removeTransformerFromManager fTransformerIndex decremented to: " +
+                         fTransformerIndex);
+        }
+    }
+
+    /**
+     * verify transformer by asserting that the number of transforms that occured
+     * is the same as the number of valid transformers added to the list.
+     * @param manager
+     */
+    protected void
+    verifyTransformers(Instrumentation manager)
+    {
+        File f = new File(System.getProperty("test.classes", "."), redefinedClassName + ".class");
+        System.out.println("Reading test class from " + f);
+        try
+        {
+            InputStream redefineStream = new FileInputStream(f);
+            byte[] bytes = NamedBuffer.loadBufferFromStream(redefineStream);
+            ClassDefinition cd = new ClassDefinition(DummyClass.class, bytes);
+            fInst.redefineClasses(new ClassDefinition[]{ cd });
+            verbosePrint("verifyTransformers redefined " + redefinedClassName);
+        }
+        catch (IOException e)
+        {
+            fail("Could not load the class: " + redefinedClassName);
+        }
+        catch (ClassNotFoundException e)
+        {
+            fail("Could not find the class: " + redefinedClassName);
+        }
+        catch (UnmodifiableClassException e)
+        {
+            fail("Could not modify the class: " + redefinedClassName);
+        }
+
+        // Report any delayed failures
+        assertTrue(fDelayedFailure, fDelayedFailure == null);
+
+        assertEquals("The number of transformers that were run does not match the expected number added to manager",
+                        fTransformers.size(), fTransformerIndex);
+    }
+
+
+    /**
+     * Asserts that the transformer being checked by the manager is the correct
+     * one (as far as order goes) and updates the number of transformers that have
+     * been called.  Note that since this is being called inside of a transformer,
+     * a standard assert (which throws an exception) cannot be used since it would
+     * simply cancel the transformation and otherwise be ignored.  Instead, note
+     * the failure for delayed processing.
+     * @param ClassFileTransformer
+     */
+    private void
+    checkInTransformer(ClassFileTransformer transformer)
+    {
+        verbosePrint("checkInTransformer: " + transformer);
+        if (fDelayedFailure == null)
+        {
+            if (fTransformers.size() <= fTransformerIndex)
+            {
+                String msg = "The number of transformers that have checked in (" +(fTransformerIndex+1) +
+                    ") is greater number of tranformers created ("+fTransformers.size()+")";
+                fDelayedFailure = msg;
+                System.err.println("Delayed failure: " + msg);
+                verbosePrint("Delayed failure: " + msg);
+            }
+            if (!fTransformers.get(fTransformerIndex).equals(transformer))
+            {
+                String msg = "Transformer " + fTransformers.get(fTransformerIndex) +
+                    " should be the same as " + transformer;
+                fDelayedFailure = msg;
+                System.err.println("Delayed failure: " + msg);
+                verbosePrint("Delayed failure: " + msg);
+            }
+            fTransformerIndex++;
+            verbosePrint("fTransformerIndex incremented to: " + fTransformerIndex);
+        }
+    }
+
+    /**
+     * Create a new manager, a new transformer list, and initializes the number of transformers
+     * indexed to zero.
+     */
+    protected void
+    setUp()
+        throws Exception
+    {
+        super.setUp();
+        fTransformers = new ArrayList();
+        fTransformerIndex = 0;
+        fDelayedFailure = null;
+        verbosePrint("setUp completed");
+    }
+
+    /**
+     * Sets the manager and transformers to null so that setUp needs to update.
+     */
+    protected void
+    tearDown()
+        throws Exception
+    {
+        verbosePrint("tearDown beginning");
+        fTransformers = null;
+        super.tearDown();
+    }
+
+    /*
+     *  Simple transformer that registers when it transforms
+     */
+    public class MyClassFileTransformer extends SimpleIdentityTransformer {
+        private final String fID;
+
+        public MyClassFileTransformer(String id) {
+            super();
+            fID = id;
+        }
+
+        public String toString() {
+            return MyClassFileTransformer.this.getClass().getName() + fID;
+        }
+
+        public byte[]
+        transform(
+            ClassLoader loader,
+            String className,
+            Class<?> classBeingRedefined,
+            ProtectionDomain    protectionDomain,
+            byte[] classfileBuffer) {
+
+            // The transform testing is triggered by redefine, ignore others
+            if (classBeingRedefined != null) checkInTransformer(MyClassFileTransformer.this);
+
+            return super.transform(    loader,
+                                        className,
+                                        classBeingRedefined,
+                                        protectionDomain,
+                                        classfileBuffer);
+        }
+    }
+
+
+    /**
+     * Class loader that does nothing
+     */
+    public class MyClassLoader extends ClassLoader
+    {
+        /**
+         * Constructor for MyClassLoader.
+         */
+        public MyClassLoader()
+        {
+            super();
+        }
+
+    }
+
+    public String debug_byteArrayToString(byte[] b) {
+        if (b == null) return "null";
+
+        StringBuffer buf = new StringBuffer();
+        buf.append("byte[");
+        buf.append(b.length);
+        buf.append("] (");
+        for (int i = 0; i < b.length; i++)
+        {
+            buf.append(b[i]);
+            buf.append(",");
+        }
+        buf.deleteCharAt(buf.length()-1);
+        buf.append(")");
+
+        return buf.toString();
+    }
+}
diff --git a/jdk/test/java/lang/instrument/AddTransformerTest.java b/jdk/test/java/lang/instrument/AddTransformerTest.java
new file mode 100644
index 0000000..a6a0a7c
--- /dev/null
+++ b/jdk/test/java/lang/instrument/AddTransformerTest.java
@@ -0,0 +1,75 @@
+/*
+ * Copyright 2003-2004 Sun Microsystems, Inc.  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 Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
+ * CA 95054 USA or visit www.sun.com if you need additional information or
+ * have any questions.
+ */
+
+/**
+ * @test
+ * @bug 4882798
+ * @summary confirms that added transformers all really run
+ * @author Gabriel Adauto, Wily Technology
+ *
+ * @run build AddTransformerTest ATransformerManagementTestCase
+ * @run shell MakeJAR.sh redefineAgent
+ * @run main/othervm -javaagent:redefineAgent.jar AddTransformerTest AddTransformerTest
+ */
+public class
+AddTransformerTest
+    extends ATransformerManagementTestCase
+{
+
+    /**
+     * Constructor for AddTransformerTest.
+     * @param name
+     */
+    public AddTransformerTest(String name)
+    {
+        super(name);
+    }
+
+    public static void
+    main (String[] args)
+        throws Throwable {
+        ATestCaseScaffold   test = new AddTransformerTest(args[0]);
+        test.runTest();
+    }
+
+    protected final void
+    doRunTest()
+        throws Throwable {
+        testAddTransformer();
+    }
+
+    /**
+     * Add and check a bunch of transformers to the manager
+     */
+    public void
+    testAddTransformer()
+    {
+        for (int i = 0; i < kTransformerSamples.length; i++)
+        {
+            addTransformerToManager(fInst, kTransformerSamples[i]);
+        }
+
+        verifyTransformers(fInst);
+    }
+
+}
diff --git a/jdk/test/java/lang/instrument/AppendToBootstrapClassPathSetUp.sh b/jdk/test/java/lang/instrument/AppendToBootstrapClassPathSetUp.sh
new file mode 100644
index 0000000..62a030a
--- /dev/null
+++ b/jdk/test/java/lang/instrument/AppendToBootstrapClassPathSetUp.sh
@@ -0,0 +1,57 @@
+#!/bin/sh
+
+#
+# Copyright 2003 Sun Microsystems, Inc.  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 Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
+# CA 95054 USA or visit www.sun.com if you need additional information or
+# have any questions.
+#
+
+
+#
+#
+#
+
+if [ "${TESTSRC}" = "" ]
+then
+  echo "TESTSRC not set.  Test cannot execute.  Failed."
+  exit 1
+fi
+echo "TESTSRC=${TESTSRC}"
+
+if [ "${TESTJAVA}" = "" ]
+then
+  echo "TESTJAVA not set.  Test cannot execute.  Failed."
+  exit 1
+fi
+echo "TESTJAVA=${TESTJAVA}"
+
+if [ "${TESTCLASSES}" = "" ]
+then
+  echo "TESTCLASSES not set.  Test cannot execute.  Failed."
+  exit 1
+fi
+
+echo "TESTCLASSES=${TESTCLASSES}"
+echo "CLASSPATH=${CLASSPATH}"
+
+JAVAC="${TESTJAVA}/bin/javac -g"
+
+mkdir -p hidden
+mv ${TESTCLASSES}/ExampleForBootClassPath.class hidden
diff --git a/jdk/test/java/lang/instrument/AppendToBootstrapClassPathTest.java b/jdk/test/java/lang/instrument/AppendToBootstrapClassPathTest.java
new file mode 100644
index 0000000..4a84b4d
--- /dev/null
+++ b/jdk/test/java/lang/instrument/AppendToBootstrapClassPathTest.java
@@ -0,0 +1,71 @@
+/*
+ * Copyright 2003-2004 Sun Microsystems, Inc.  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 Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
+ * CA 95054 USA or visit www.sun.com if you need additional information or
+ * have any questions.
+ */
+
+/**
+ * @test
+ * @bug 4882798
+ * @summary simple test for the Boot-Class-Path manifest attribute
+ * @author Gabriel Adauto, Wily Technology, Robert Field, Sun Microsystems
+ *
+ * @run build AppendToBootstrapClassPathTest ExampleForBootClassPath
+ * @run shell AppendToBootstrapClassPathSetUp.sh
+ * @run shell MakeJAR.sh bootclasspathAgent
+ * @run main/othervm -javaagent:bootclasspathAgent.jar AppendToBootstrapClassPathTest AppendToBootstrapClassPathTest
+ */
+
+import java.io.*;
+
+public class
+AppendToBootstrapClassPathTest
+    extends ASimpleInstrumentationTestCase
+{
+
+    /**
+     * Constructor for AppendToBootstrapClassPathTest.
+     * @param name
+     */
+    public AppendToBootstrapClassPathTest(String name) {
+        super(name);
+    }
+
+    public static void main (String[] args)  throws Throwable {
+        ATestCaseScaffold   test = new AppendToBootstrapClassPathTest(args[0]);
+        test.runTest();
+    }
+
+    protected final void doRunTest() {
+        testAppendToBootstrapClassPath();
+    }
+
+    public void  testAppendToBootstrapClassPath() {
+        // load the "hidden" class, it should be loaded by the boot loader
+        Object instance = loadExampleClass();
+        assertTrue(instance.getClass().getClassLoader() == null);
+    }
+
+    Object loadExampleClass() {
+        ExampleForBootClassPath instance = new ExampleForBootClassPath();
+        assertTrue(instance.fifteen() == 15);
+        return instance;
+    }
+}
diff --git a/jdk/test/java/lang/instrument/AppendToClassPathSetUp.sh b/jdk/test/java/lang/instrument/AppendToClassPathSetUp.sh
new file mode 100644
index 0000000..b8ebb48
--- /dev/null
+++ b/jdk/test/java/lang/instrument/AppendToClassPathSetUp.sh
@@ -0,0 +1,60 @@
+#!/bin/sh
+
+#
+# Copyright 2003 Sun Microsystems, Inc.  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 Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
+# CA 95054 USA or visit www.sun.com if you need additional information or
+# have any questions.
+#
+
+
+#
+#
+#
+
+if [ "${TESTSRC}" = "" ]
+then
+  echo "TESTSRC not set.  Test cannot execute.  Failed."
+  exit 1
+fi
+echo "TESTSRC=${TESTSRC}"
+
+if [ "${TESTJAVA}" = "" ]
+then
+  echo "TESTJAVA not set.  Test cannot execute.  Failed."
+  exit 1
+fi
+echo "TESTJAVA=${TESTJAVA}"
+
+if [ "${TESTCLASSES}" = "" ]
+then
+  echo "TESTCLASSES not set.  Test cannot execute.  Failed."
+  exit 1
+fi
+
+echo "TESTCLASSES=${TESTCLASSES}"
+echo "CLASSPATH=${CLASSPATH}"
+
+JAVAC="${TESTJAVA}/bin/javac -g"
+
+cp ${TESTSRC}/ExampleForClassPath.java ExampleForClassPath.java
+${JAVAC} ExampleForClassPath.java
+mkdir -p hidden
+mv ExampleForClassPath.class hidden
+rm -f ExampleForClassPath.java
diff --git a/jdk/test/java/lang/instrument/AppendToClassPathTest.java b/jdk/test/java/lang/instrument/AppendToClassPathTest.java
new file mode 100644
index 0000000..58fc4ce
--- /dev/null
+++ b/jdk/test/java/lang/instrument/AppendToClassPathTest.java
@@ -0,0 +1,79 @@
+/*
+ * Copyright 2003-2004 Sun Microsystems, Inc.  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 Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
+ * CA 95054 USA or visit www.sun.com if you need additional information or
+ * have any questions.
+ */
+
+/**
+ * @test
+ * @bug 4882798
+ * @summary simple test for the Class-Path manifest attribute
+ * @author Gabriel Adauto, Wily Technology; Robert Field, Sun Microsystems
+ *
+ * @run build AppendToClassPathTest
+ * @run shell AppendToClassPathSetUp.sh
+ * @run shell MakeJAR.sh classpathAgent
+ * @run main/othervm -javaagent:classpathAgent.jar AppendToClassPathTest AppendToClassPathTest
+ */
+
+import java.io.*;
+
+public class
+AppendToClassPathTest
+    extends ASimpleInstrumentationTestCase
+{
+
+    /**
+     * Constructor for AppendToClassPathTest.
+     * @param name
+     */
+    public AppendToClassPathTest(String name)
+    {
+        super(name);
+    }
+
+    public static void
+    main (String[] args)
+        throws Throwable {
+        ATestCaseScaffold   test = new AppendToClassPathTest(args[0]);
+        test.runTest();
+    }
+
+    protected final void
+    doRunTest()
+        throws Throwable {
+        testAppendToClassPath();
+    }
+
+
+    public void
+    testAppendToClassPath()
+        throws  IOException,
+                ClassNotFoundException
+    {
+        Class sentinelClass;
+        ClassLoader loader = this.getClass().getClassLoader();
+
+        // load the "hidden" class, it should be loaded by the system loader
+        sentinelClass = loader.loadClass("ExampleForClassPath");
+        assertTrue(sentinelClass.getClassLoader() == ClassLoader.getSystemClassLoader());
+    }
+
+}
diff --git a/jdk/test/java/lang/instrument/BootClassPath/Agent.java b/jdk/test/java/lang/instrument/BootClassPath/Agent.java
new file mode 100644
index 0000000..eec9dbf
--- /dev/null
+++ b/jdk/test/java/lang/instrument/BootClassPath/Agent.java
@@ -0,0 +1,48 @@
+/*
+ * Copyright 2004 Sun Microsystems, Inc.  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 Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
+ * CA 95054 USA or visit www.sun.com if you need additional information or
+ * have any questions.
+ */
+
+/*
+ *
+ *
+ * Used by BootClassPath.sh
+ *
+ * Loads a supporting class and tests that the class is loaded from the boot
+ * class path.
+ */
+import java.lang.instrument.Instrumentation;
+
+public class Agent {
+    public static void premain(String options, Instrumentation ins) throws Exception {
+        String bootclasspath = System.getProperty("sun.boot.class.path");
+        System.out.println("bootclasspath: " + bootclasspath);
+
+        Class c = Class.forName("AgentSupport");
+        ClassLoader cl = c.getClassLoader();
+        if (cl != null) {
+            System.err.println("AgentSupport loaded by: " + cl);
+            throw new RuntimeException("AgentSupport class not loaded by boot class loader");
+        } else {
+            System.out.println("AgentSupport loaded by boot class loader");
+        }
+    }
+}
diff --git a/jdk/test/java/lang/instrument/BootClassPath/AgentSupport.java b/jdk/test/java/lang/instrument/BootClassPath/AgentSupport.java
new file mode 100644
index 0000000..d025a87
--- /dev/null
+++ b/jdk/test/java/lang/instrument/BootClassPath/AgentSupport.java
@@ -0,0 +1,32 @@
+/*
+ * Copyright 2004 Sun Microsystems, Inc.  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 Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
+ * CA 95054 USA or visit www.sun.com if you need additional information or
+ * have any questions.
+ */
+
+/*
+ *
+ *
+ * Used by BootClassPath.sh - supporting class for java agent.
+ */
+public class AgentSupport {
+    public AgentSupport() {
+    }
+}
diff --git a/jdk/test/java/lang/instrument/BootClassPath/BootClassPathTest.sh b/jdk/test/java/lang/instrument/BootClassPath/BootClassPathTest.sh
new file mode 100644
index 0000000..f5b79a6
--- /dev/null
+++ b/jdk/test/java/lang/instrument/BootClassPath/BootClassPathTest.sh
@@ -0,0 +1,83 @@
+#
+# Copyright 2004-2005 Sun Microsystems, Inc.  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 Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
+# CA 95054 USA or visit www.sun.com if you need additional information or
+# have any questions.
+#
+
+# @test
+# @bug 5055293
+# @summary Test non US-ASCII characters in the value of the Boot-Class-Path 
+#          attribute.
+
+if [ "${TESTJAVA}" = "" ]
+then
+  echo "TESTJAVA not set.  Test cannot execute.  Failed."
+  exit 1
+fi
+
+if [ "${TESTSRC}" = "" ]
+then
+  echo "TESTSRC not set.  Test cannot execute.  Failed."
+  exit 1
+fi
+
+if [ "${TESTCLASSES}" = "" ]
+then
+  echo "TESTCLASSES not set.  Test cannot execute.  Failed."
+  exit 1
+fi
+
+JAVAC="${TESTJAVA}"/bin/javac
+JAVA="${TESTJAVA}"/bin/java
+JAR="${TESTJAVA}"/bin/jar
+
+echo "Creating manifest file..."
+
+"$JAVAC" -d "${TESTCLASSES}" "${TESTSRC}"/Setup.java
+
+# java Setup <workdir> <premain-class>
+# - outputs boot class path to boot.dir
+
+"$JAVA" -classpath "${TESTCLASSES}" Setup "${TESTCLASSES}" Agent
+BOOTDIR=`cat ${TESTCLASSES}/boot.dir`
+
+echo "Created ${BOOTDIR}"
+
+echo "Building test classes..."
+
+"$JAVAC" -d "${TESTCLASSES}" "${TESTSRC}"/Agent.java "${TESTSRC}"/DummyMain.java
+"$JAVAC" -d "${BOOTDIR}" "${TESTSRC}"/AgentSupport.java
+
+echo "Creating agent jar file..."
+
+"$JAR" -cvfm "${TESTCLASSES}"/Agent.jar "${TESTCLASSES}"/MANIFEST.MF \
+    -C "${TESTCLASSES}" Agent.class || exit 1
+
+echo "Running test..."
+
+"${JAVA}" -javaagent:"${TESTCLASSES}"/Agent.jar -classpath "${TESTCLASSES}" DummyMain
+result=$?
+
+echo "Cleanup..."
+
+"$JAVAC" -d "${TESTCLASSES}" "${TESTSRC}"/Cleanup.java
+"$JAVA" -classpath "${TESTCLASSES}" Cleanup "${BOOTDIR}"
+
+exit $result
diff --git a/jdk/test/java/lang/instrument/BootClassPath/Cleanup.java b/jdk/test/java/lang/instrument/BootClassPath/Cleanup.java
new file mode 100644
index 0000000..a4e39bb
--- /dev/null
+++ b/jdk/test/java/lang/instrument/BootClassPath/Cleanup.java
@@ -0,0 +1,54 @@
+/*
+ * Copyright 2004 Sun Microsystems, Inc.  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 Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
+ * CA 95054 USA or visit www.sun.com if you need additional information or
+ * have any questions.
+ */
+
+/*
+ *
+ *
+ * Used by BootClassPath.sh to remove a directory and its contents after a
+ * test run.
+ */
+import java.io.File;
+
+public class Cleanup {
+
+    public static void main(String[] args) {
+        File file = new File(args[0]);
+
+        // paranoia is healthy in rm -rf
+        String name = file.toString();
+        if (name.equals(".") || name.equals("..") ||
+                name.endsWith(File.separator + ".") ||
+                name.endsWith(File.separator + "..")) {
+            throw new RuntimeException("too risky to process: " + name);
+        }
+        if (file.isDirectory()) {
+            File[] contents = file.listFiles();
+            for (int i = 0; i < contents.length; i++) {
+                contents[i].delete();
+            }
+        }
+        if (!file.delete()) {
+            throw new RuntimeException("Unable to delete " + file);
+        }
+    }
+}
diff --git a/jdk/test/java/lang/instrument/BootClassPath/DummyMain.java b/jdk/test/java/lang/instrument/BootClassPath/DummyMain.java
new file mode 100644
index 0000000..97227d4
--- /dev/null
+++ b/jdk/test/java/lang/instrument/BootClassPath/DummyMain.java
@@ -0,0 +1,32 @@
+/*
+ * Copyright 2004 Sun Microsystems, Inc.  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 Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
+ * CA 95054 USA or visit www.sun.com if you need additional information or
+ * have any questions.
+ */
+
+/*
+ *
+ *
+ * Used by BootClassPath.sh - dummay "main application" which doesn't do anything
+ */
+public class DummyMain {
+    public static void main(String[] args) {
+    }
+}
diff --git a/jdk/test/java/lang/instrument/BootClassPath/Setup.java b/jdk/test/java/lang/instrument/BootClassPath/Setup.java
new file mode 100644
index 0000000..bf2c3b1
--- /dev/null
+++ b/jdk/test/java/lang/instrument/BootClassPath/Setup.java
@@ -0,0 +1,174 @@
+/*
+ * Copyright 2004-2005 Sun Microsystems, Inc.  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 Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
+ * CA 95054 USA or visit www.sun.com if you need additional information or
+ * have any questions.
+ */
+
+/*
+ *
+ *
+ * Used by BootClassPath.sh.
+ *
+ * Given a "work directory" this class creates a sub-directory with a
+ * name that uses locale specific characters. It the creates a jar
+ * manifest file in the work directory with a Boot-Class-Path that
+ * encodes the created sub-directory. Finally it creates a file
+ * "boot.dir" in the work directory with the name of the sub-directory.
+ */
+import java.io.File;
+import java.io.FileOutputStream;
+import java.nio.charset.Charset;
+
+public class Setup {
+
+    public static void main(String[] args) throws Exception {
+        if (args.length < 2) {
+            System.err.println("Usage: java Setup <work-dir> <premain-class>");
+            return;
+        }
+        String workDir = args[0];
+        String premainClass = args[1];
+
+        String manifestFile = workDir + fileSeparator + "MANIFEST.MF";
+        String bootClassPath = "boot" + suffix();
+
+        String bootDir = workDir + fileSeparator + bootClassPath;
+
+
+        /*
+         * Create sub-directory
+         */
+        File f = new File(bootDir);
+        f.mkdir();
+
+        /*
+         * Create manifest file with Boot-Class-Path encoding the
+         * sub-directory name.
+         */
+        FileOutputStream out = new FileOutputStream(manifestFile);
+        out.write("Manifest-Version: 1.0\n".getBytes("UTF-8"));
+
+        byte[] premainBytes = ("Premain-Class: " + premainClass + "\n").getBytes("UTF-8");
+        out.write(premainBytes);
+
+        out.write( "Boot-Class-Path: ".getBytes("UTF-8") );
+
+        byte[] value = bootClassPath.getBytes("UTF-8");
+        for (int i=0; i<value.length; i++) {
+            int v = (int)value[i];
+            if (v < 0) v += 256;
+            byte[] escaped =  ("%" + Integer.toHexString(v)).getBytes("UTF-8");
+            out.write(escaped);
+        }
+        out.write( "\n\n".getBytes("UTF-8") );
+        out.close();
+
+        /*
+         * Write the name of the boot dir to "boot.dir"
+         */
+        f = new File(workDir + fileSeparator + "boot.dir");
+        out = new FileOutputStream(f);
+        out.write(bootDir.getBytes(defaultEncoding));
+        out.close();
+    }
+
+    /* ported from test/sun/tools/launcher/UnicodeTest.java */
+
+    private static final String fileSeparator = System.getProperty("file.separator");
+    private static final String osName = System.getProperty("os.name");
+    private static final String defaultEncoding = Charset.defaultCharset().name();
+
+    // language names taken from java.util.Locale.getDisplayLanguage for the respective language
+    private static final String arabic = "\u0627\u0644\u0639\u0631\u0628\u064a\u0629";
+    private static final String s_chinese = "\u4e2d\u6587";
+    private static final String t_chinese = "\u4e2d\u6587";
+    private static final String russian = "\u0440\u0443\u0441\u0441\u043A\u0438\u0439";
+    private static final String hindi = "\u0939\u093f\u0902\u0926\u0940";
+    private static final String greek = "\u03b5\u03bb\u03bb\u03b7\u03bd\u03b9\u03ba\u03ac";
+    private static final String hebrew = "\u05e2\u05d1\u05e8\u05d9\u05ea";
+    private static final String japanese = "\u65e5\u672c\u8a9e";
+    private static final String korean = "\ud55c\uad6d\uc5b4";
+    private static final String lithuanian = "Lietuvi\u0173";
+    private static final String czech = "\u010de\u0161tina";
+    private static final String turkish = "T\u00fcrk\u00e7e";
+    private static final String spanish = "espa\u00f1ol";
+    private static final String thai = "\u0e44\u0e17\u0e22";
+    private static final String unicode = arabic + s_chinese + t_chinese
+            + russian + hindi + greek + hebrew + japanese + korean
+            + lithuanian + czech + turkish + spanish + thai;
+
+    private static String suffix() {
+
+        // Mapping from main platform encodings to language names
+        // for Unix and Windows, respectively. Use empty suffix
+        // for Windows encodings where OEM encoding differs.
+        // Use null if encoding isn't used.
+        String[][] names = {
+            { "UTF-8",          unicode,        ""              },
+            { "windows-1256",   null,           ""              },
+            { "iso-8859-6",     arabic,         null            },
+            { "GBK",            s_chinese,      s_chinese       },
+            { "GB18030",        s_chinese,      s_chinese       },
+            { "GB2312",         s_chinese,      null            },
+            { "x-windows-950",  null,           t_chinese       },
+            { "x-MS950-HKSCS",  null,           t_chinese       },
+            { "x-euc-tw",       t_chinese,      null            },
+            { "Big5",           t_chinese,      null            },
+            { "Big5-HKSCS",     t_chinese,      null            },
+            { "windows-1251",   null,           ""              },
+            { "iso-8859-5",     russian,        null            },
+            { "koi8-r",         russian,        null            },
+            { "windows-1253",   null,           ""              },
+            { "iso-8859-7",     greek,          null            },
+            { "windows-1255",   null,           ""              },
+            { "iso8859-8",      hebrew,         null            },
+            { "windows-31j",    null,           japanese        },
+            { "x-eucJP-Open",   japanese,       null            },
+            { "x-EUC-JP-LINUX", japanese,       null            },
+            { "x-pck",          japanese,       null            },
+            { "x-windows-949",  null,           korean          },
+            { "euc-kr",         korean,         null            },
+            { "windows-1257",   null,           ""              },
+            { "iso-8859-13",    lithuanian,     null            },
+            { "windows-1250",   null,           ""              },
+            { "iso-8859-2",     czech,          null            },
+            { "windows-1254",   null,           ""              },
+            { "iso-8859-9",     turkish,        null            },
+            { "windows-1252",   null,           ""              },
+            { "iso-8859-1",     spanish,        null            },
+            { "iso-8859-15",    spanish,        null            },
+            { "x-windows-874",  null,           thai            },
+            { "tis-620",        thai,           null            },
+        };
+
+        int column;
+        if (osName.startsWith("Windows")) {
+            column = 2;
+        } else {
+            column = 1;
+        }
+        for (int i = 0; i < names.length; i++) {
+             if (names[i][0].equalsIgnoreCase(defaultEncoding)) {
+                 return names[i][column];
+             }
+         }
+         return "";
+    }
+}
diff --git a/jdk/test/java/lang/instrument/BufferClassLoader.java b/jdk/test/java/lang/instrument/BufferClassLoader.java
new file mode 100644
index 0000000..2308da4
--- /dev/null
+++ b/jdk/test/java/lang/instrument/BufferClassLoader.java
@@ -0,0 +1,65 @@
+/*
+ * Copyright 2003 Sun Microsystems, Inc.  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 Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
+ * CA 95054 USA or visit www.sun.com if you need additional information or
+ * have any questions.
+ */
+
+
+import  java.security.*;
+
+/*
+ * Copyright 2003 Wily Technology, Inc.
+ */
+
+public class BufferClassLoader extends SecureClassLoader
+{
+    private final NamedBuffer[] fBuffers;
+
+    public
+    BufferClassLoader(  ClassLoader     parent,
+                        NamedBuffer[]   buffers)
+        {
+        super(parent);
+        fBuffers = buffers;     // maybe should copy
+        }
+
+
+    protected Class
+    findClass(String name)
+        throws ClassNotFoundException
+        {
+        for ( int x = 0; x < fBuffers.length; x++ )
+            {
+            if ( fBuffers[x].getName().equals(name) )
+                {
+                byte[] buffer = fBuffers[x].getBuffer();
+                return defineClass( name,
+                                    buffer,
+                                    0,
+                                    buffer.length,
+                                    (CodeSource) null);
+                }
+            }
+
+        throw new ClassNotFoundException(name);
+        }
+
+
+}
diff --git a/jdk/test/java/lang/instrument/Counter.java b/jdk/test/java/lang/instrument/Counter.java
new file mode 100644
index 0000000..bc76626
--- /dev/null
+++ b/jdk/test/java/lang/instrument/Counter.java
@@ -0,0 +1,49 @@
+/*
+ * Copyright 2003 Sun Microsystems, Inc.  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 Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
+ * CA 95054 USA or visit www.sun.com if you need additional information or
+ * have any questions.
+ */
+
+/*
+ * Copyright 2003 Wily Technology, Inc.
+ */
+
+public class Counter
+    {
+    private int     fCounter;
+
+    public
+    Counter()
+        {
+        fCounter = 0;
+        }
+
+    public int
+    get()
+        {
+        return fCounter;
+        }
+
+    public void
+    increment()
+        {
+        fCounter++;
+        }
+    }
diff --git a/jdk/test/java/lang/instrument/Different_ExampleRedefine.java b/jdk/test/java/lang/instrument/Different_ExampleRedefine.java
new file mode 100644
index 0000000..689ed7c
--- /dev/null
+++ b/jdk/test/java/lang/instrument/Different_ExampleRedefine.java
@@ -0,0 +1,53 @@
+/*
+ * Copyright 2003 Sun Microsystems, Inc.  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 Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
+ * CA 95054 USA or visit www.sun.com if you need additional information or
+ * have any questions.
+ */
+
+/*
+ * Copyright 2003 Wily Technology, Inc.
+ */
+
+public class ExampleRedefine
+    {
+    private Counter fCounter;
+
+    public
+    ExampleRedefine()
+        {
+        super();
+        System.out.println("Simple ExampleRedefine constructor");
+        fCounter = new Counter();
+        }
+
+    public int
+    get()
+        {
+        return fCounter.get();
+        }
+
+    // this redefined version of the class correctly increments the counter.
+    // Meant to be compared with "uncorrected" bytecode
+    public void
+    doSomething()
+        {
+        fCounter.increment();
+        }
+    }
diff --git a/jdk/test/java/lang/instrument/DummyClass.java b/jdk/test/java/lang/instrument/DummyClass.java
new file mode 100644
index 0000000..0dea078
--- /dev/null
+++ b/jdk/test/java/lang/instrument/DummyClass.java
@@ -0,0 +1,31 @@
+/*
+ * Copyright 2003 Sun Microsystems, Inc.  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 Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
+ * CA 95054 USA or visit www.sun.com if you need additional information or
+ * have any questions.
+ */
+
+/*
+ * Copyright 2003 Wily Technology, Inc.
+ */
+
+public class DummyClass
+{
+
+}
diff --git a/jdk/test/java/lang/instrument/ExampleForBootClassPath.java b/jdk/test/java/lang/instrument/ExampleForBootClassPath.java
new file mode 100644
index 0000000..06ce85d
--- /dev/null
+++ b/jdk/test/java/lang/instrument/ExampleForBootClassPath.java
@@ -0,0 +1,32 @@
+/*
+ * Copyright 2003 Sun Microsystems, Inc.  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 Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
+ * CA 95054 USA or visit www.sun.com if you need additional information or
+ * have any questions.
+ */
+
+/*
+ * Copyright 2003 Wily Technology, Inc.
+ */
+
+public class ExampleForBootClassPath {
+    public int fifteen() {
+       return 15;
+    }
+}
diff --git a/jdk/test/java/lang/instrument/ExampleForClassPath.java b/jdk/test/java/lang/instrument/ExampleForClassPath.java
new file mode 100644
index 0000000..f0ad1d1
--- /dev/null
+++ b/jdk/test/java/lang/instrument/ExampleForClassPath.java
@@ -0,0 +1,31 @@
+/*
+ * Copyright 2003 Sun Microsystems, Inc.  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 Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
+ * CA 95054 USA or visit www.sun.com if you need additional information or
+ * have any questions.
+ */
+
+/*
+ * Copyright 2003 Wily Technology, Inc.
+ */
+
+public class ExampleForClassPath
+{
+
+}
diff --git a/jdk/test/java/lang/instrument/ExampleRedefine.java b/jdk/test/java/lang/instrument/ExampleRedefine.java
new file mode 100644
index 0000000..58cf3f6
--- /dev/null
+++ b/jdk/test/java/lang/instrument/ExampleRedefine.java
@@ -0,0 +1,52 @@
+/*
+ * Copyright 2003 Sun Microsystems, Inc.  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 Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
+ * CA 95054 USA or visit www.sun.com if you need additional information or
+ * have any questions.
+ */
+
+/*
+ * Copyright 2003 Wily Technology, Inc.
+ */
+
+public class ExampleRedefine
+    {
+    private Counter fCounter;
+
+    public
+    ExampleRedefine()
+        {
+        super();
+        System.out.println("Simple ExampleRedefine constructor");
+        fCounter = new Counter();
+        }
+
+    public int
+    get()
+        {
+        return fCounter.get();
+        }
+
+    // this version of the class "accidentally" does nothing. Meant to be compared with "corrected" bytecode
+    public void
+    doSomething()
+        {
+
+        }
+    }
diff --git a/jdk/test/java/lang/instrument/FakeTestDriver.java b/jdk/test/java/lang/instrument/FakeTestDriver.java
new file mode 100644
index 0000000..bd47023
--- /dev/null
+++ b/jdk/test/java/lang/instrument/FakeTestDriver.java
@@ -0,0 +1,142 @@
+/*
+ * Copyright 2003 Sun Microsystems, Inc.  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 Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
+ * CA 95054 USA or visit www.sun.com if you need additional information or
+ * have any questions.
+ */
+
+
+/*
+ * Copyright 2003 Wily Technology, Inc.
+ */
+
+/**
+ *  Cheesy class to run all of our test cases in a hard-coded fashion.
+ *  Will be replaced by Sun's iterator that uses the source decorations to figure out what to do.
+ */
+
+import  java.lang.reflect.*;
+
+public class FakeTestDriver  {
+
+    private String[] fTestList = {
+        "javafake.lang.instrument.AddTransformerTest",
+        "javafake.lang.instrument.AppendToBootstrapClassPathTest",
+        "javafake.lang.instrument.AppendToClassPathTest",
+        "javafake.lang.instrument.GetAllLoadedClassesTest",
+        "javafake.lang.instrument.GetInitiatedClassesTest",
+        "javafake.lang.instrument.GetObjectSizeTest",
+        "javafake.lang.instrument.NoTransformerAddedTest",
+        "javafake.lang.instrument.NullTransformerAddTest",
+        "javafake.lang.instrument.RedefineClassesTests",
+        "javafake.lang.instrument.RemoveAbsentTransformerTest",
+        "javafake.lang.instrument.RemoveTransformerTest",
+        "javafake.lang.instrument.SingleTransformerTest",
+        "javafake.lang.instrument.TransformerManagementThreadAddTests",
+        "javafake.lang.instrument.TransformerManagementThreadRemoveTests",
+        "javafake.lang.instrument.TransformMethodTest",
+    };
+
+    public static void
+    main(String[] args) {
+        (new FakeTestDriver()).runSuppliedTests(args);
+    }
+
+    private
+    FakeTestDriver() {
+    }
+
+    private void
+    runAllTests() {
+        runSuppliedTests(fTestList);
+    }
+
+    private void
+    runSuppliedTests(String[] classnames) {
+        for (int x = 0; x < classnames.length; x++ ) {
+            loadAndRunOneTest(classnames[x]);
+        }
+    }
+
+    private void
+    loadAndRunOneTest(String classname) {
+        log("trying to run: " + classname);
+
+        Class testclass = loadOneTest(classname);
+
+        if ( testclass != null ) {
+            boolean result = runOneTest(testclass);
+            if ( result ) {
+                log(classname + " SUCCEEDED");
+            }
+            else {
+                log(classname + " FAILED");
+            }
+        }
+        else {
+            log(classname + " could not be loaded");
+        }
+    }
+
+    private Class
+    loadOneTest(String classname) {
+        Class result = null;
+
+        try {
+            result = Class.forName(classname);
+        }
+        catch (Throwable t) {
+            t.printStackTrace();
+            result = null;
+        }
+        return result;
+    }
+
+    private boolean
+    runOneTest(Class testclass) {
+        Method mainMethod = null;
+
+        try {
+            String[]    forType = new String[0];
+            mainMethod = testclass.getMethod("main",
+                                                    new Class[] {
+                                                        forType.getClass()
+                                                     });
+        }
+        catch (Throwable t) {
+            log(testclass.getName() + " is malformed");
+            t.printStackTrace();
+            return false;
+        }
+
+        try {
+            mainMethod.invoke(null, new Object[] {new String[] {testclass.getName()}});
+            return true;
+        }
+        catch (Throwable t) {
+            t.printStackTrace();
+            return false;
+        }
+    }
+
+    private void
+    log(String m) {
+        System.out.println(m);
+    }
+}
diff --git a/jdk/test/java/lang/instrument/FromShutdownHook.java b/jdk/test/java/lang/instrument/FromShutdownHook.java
new file mode 100644
index 0000000..f55fbec
--- /dev/null
+++ b/jdk/test/java/lang/instrument/FromShutdownHook.java
@@ -0,0 +1,60 @@
+/*
+ * Copyright 2004 Sun Microsystems, Inc.  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 Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
+ * CA 95054 USA or visit www.sun.com if you need additional information or
+ * have any questions.
+ */
+
+/*
+ * @test
+ * @bug 5050487
+ * @summary Check that Instrumentation methods can execute from a runtime
+ *          shutdown hook
+ * @run build FromShutdownHook
+ * @run shell MakeJAR.sh basicAgent
+ * @run main/othervm -javaagent:basicAgent.jar FromShutdownHook FromShutdownHook
+ */
+import java.lang.instrument.Instrumentation;
+
+public class FromShutdownHook
+    extends ASimpleInstrumentationTestCase
+{
+    public FromShutdownHook(String name) {
+        super(name);
+    }
+    public static void main(String args[] ) throws Throwable {
+        FromShutdownHook fsh = new FromShutdownHook(args[0]);
+        fsh.runTest();
+    }
+
+    Instrumentation ins;
+
+    protected final void doRunTest() {
+        // keep reference to Instrumentation
+        ins = fInst;
+
+        // install shutdown hook
+        Runtime.getRuntime().addShutdownHook(new Thread() {
+            public void run() {
+                System.err.println(ins.getAllLoadedClasses().length +
+                        " classes loaded.");
+            }
+        });
+    }
+}
diff --git a/jdk/test/java/lang/instrument/GetAllLoadedClassesTest.java b/jdk/test/java/lang/instrument/GetAllLoadedClassesTest.java
new file mode 100644
index 0000000..e54a08b
--- /dev/null
+++ b/jdk/test/java/lang/instrument/GetAllLoadedClassesTest.java
@@ -0,0 +1,86 @@
+/*
+ * Copyright 2003-2004 Sun Microsystems, Inc.  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 Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
+ * CA 95054 USA or visit www.sun.com if you need additional information or
+ * have any questions.
+ */
+
+/**
+ * @test
+ * @bug 4882798
+ * @summary simple tests for getAllLoadedClasses (is Object there? does a newly loaded class show up?)
+ * @author Gabriel Adauto, Wily Technology
+ *
+ * @run build GetAllLoadedClassesTest DummyClass
+ * @run shell MakeJAR.sh basicAgent
+ * @run main/othervm -javaagent:basicAgent.jar GetAllLoadedClassesTest GetAllLoadedClassesTest
+ */
+
+import  java.net.*;
+
+public class
+GetAllLoadedClassesTest
+    extends ASimpleInstrumentationTestCase
+{
+
+    /**
+     * Constructor for GetAllLoadedClassesTest.
+     * @param name
+     */
+    public GetAllLoadedClassesTest(String name)
+    {
+        super(name);
+    }
+
+    public static void
+    main (String[] args)
+        throws Throwable {
+        ATestCaseScaffold   test = new GetAllLoadedClassesTest(args[0]);
+        test.runTest();
+    }
+
+    protected final void
+    doRunTest()
+        throws Throwable {
+        testGetAllLoadedClasses();
+    }
+
+    public void
+    testGetAllLoadedClasses()
+        throws  Throwable
+    {
+        ClassLoader loader = getClass().getClassLoader();
+
+        Class[] classes = fInst.getAllLoadedClasses();
+        assertNotNull(classes);
+        assertClassArrayDoesNotContainClassByName(classes, "DummyClass");
+        assertClassArrayContainsClass(classes, Object.class);
+
+        Class dummy = loader.loadClass("DummyClass");
+        assertEquals("DummyClass", dummy.getName());
+
+        // double check that we can make an instance (just to prove the loader is kosher)
+        Object testInstance = dummy.newInstance();
+
+        Class[] classes2 = fInst.getAllLoadedClasses();
+        assertNotNull(classes2);
+        assertClassArrayContainsClass(classes2, dummy);
+    }
+
+}
diff --git a/jdk/test/java/lang/instrument/GetInitiatedClassesTest.java b/jdk/test/java/lang/instrument/GetInitiatedClassesTest.java
new file mode 100644
index 0000000..6e31d55
--- /dev/null
+++ b/jdk/test/java/lang/instrument/GetInitiatedClassesTest.java
@@ -0,0 +1,82 @@
+/*
+ * Copyright 2003-2006 Sun Microsystems, Inc.  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 Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
+ * CA 95054 USA or visit www.sun.com if you need additional information or
+ * have any questions.
+ */
+
+/**
+ * @test
+ * @bug 4882798
+ * @summary simple tests for getInitiatedClasses (does a newly loaded class show up?)
+ * @author Gabriel Adauto, Wily Technology
+ *
+ * @run build GetInitiatedClassesTest DummyClass
+ * @run shell MakeJAR.sh basicAgent
+ * @run main/othervm -javaagent:basicAgent.jar GetInitiatedClassesTest GetInitiatedClassesTest
+ */
+
+public class
+GetInitiatedClassesTest
+    extends ASimpleInstrumentationTestCase
+{
+
+    /**
+     * Constructor for GetInitiatedClassesTest.
+     * @param name
+     */
+    public GetInitiatedClassesTest(String name)
+    {
+        super(name);
+    }
+
+    public static void
+    main (String[] args)
+        throws Throwable {
+        ATestCaseScaffold   test = new GetInitiatedClassesTest(args[0]);
+        test.runTest();
+    }
+
+    protected final void
+    doRunTest()
+        throws Throwable {
+        testGetInitiatedClasses();
+    }
+
+    public void
+    testGetInitiatedClasses()
+        throws  Throwable
+    {
+        ClassLoader loader = getClass().getClassLoader();
+
+        Class[] classes = fInst.getInitiatedClasses(loader);
+        assertNotNull(classes);
+
+        Class dummy = loader.loadClass("DummyClass");
+        assertEquals("DummyClass", dummy.getName());
+
+        // double check that we can make an instance (just to prove the loader is kosher)
+        Object testInstance = dummy.newInstance();
+
+        Class[] classes2 = fInst.getInitiatedClasses(loader);
+        assertNotNull(classes2);
+        assertClassArrayContainsClass(classes2, dummy);
+    }
+
+}
diff --git a/jdk/test/java/lang/instrument/GetObjectSizeTest.java b/jdk/test/java/lang/instrument/GetObjectSizeTest.java
new file mode 100644
index 0000000..11e63f0
--- /dev/null
+++ b/jdk/test/java/lang/instrument/GetObjectSizeTest.java
@@ -0,0 +1,85 @@
+/*
+ * Copyright 2003-2004 Sun Microsystems, Inc.  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 Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
+ * CA 95054 USA or visit www.sun.com if you need additional information or
+ * have any questions.
+ */
+
+/**
+ * @test
+ * @bug 4882798
+ * @summary round-trip test for getObjectSize (does it return, and is the result non-zero?)
+ * @author Gabriel Adauto, Wily Technology
+ *
+ * @run build GetObjectSizeTest
+ * @run shell MakeJAR.sh basicAgent
+ * @run main/othervm -javaagent:basicAgent.jar GetObjectSizeTest GetObjectSizeTest
+ */
+import java.util.*;
+
+public class
+GetObjectSizeTest
+    extends ASimpleInstrumentationTestCase
+{
+
+    /**
+     * Constructor for GetObjectSizeTest.
+     * @param name
+     */
+    public GetObjectSizeTest(String name)
+    {
+        super(name);
+    }
+
+    public static void
+    main (String[] args)
+        throws Throwable {
+        ATestCaseScaffold   test = new GetObjectSizeTest(args[0]);
+        test.runTest();
+    }
+
+    protected final void
+    doRunTest()
+        throws Throwable {
+        testGetObjectSize();
+    }
+
+    /*
+     *  Lame test just to show we can do the roundtrip
+     */
+    public void
+    testGetObjectSize()
+    {
+        Object[] objects = new Object[] {
+            "Hello World",
+            new Integer(8),
+            this,
+            new StringBuffer("Another test object"),
+            new Vector(99),
+            // Add more objects here
+            };
+        for (int i = 0; i < objects.length; i++)
+        {
+            Object o = objects[i];
+            long size = fInst.getObjectSize(o);
+            assertTrue(size > 0);
+        }
+    }
+
+}
diff --git a/jdk/test/java/lang/instrument/InstrumentationHandoff.java b/jdk/test/java/lang/instrument/InstrumentationHandoff.java
new file mode 100644
index 0000000..d6d7a3f
--- /dev/null
+++ b/jdk/test/java/lang/instrument/InstrumentationHandoff.java
@@ -0,0 +1,72 @@
+/*
+ * Copyright 2003 Sun Microsystems, Inc.  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 Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
+ * CA 95054 USA or visit www.sun.com if you need additional information or
+ * have any questions.
+ */
+
+import java.lang.instrument.Instrumentation;
+
+/*
+ * Copyright 2003 Wily Technology, Inc.
+ */
+
+/**
+ * A JPLIS agent that makes the Instrumentation available via a static accessor.
+ * Used so that unit test frameworks that run as apps can exercise the Instrumentation--
+ * configure this guy as a JPLIS agent, then call the Instrumentation fetcher from the test case.
+ *
+ */
+public class InstrumentationHandoff
+{
+    private static Instrumentation      sInstrumentation;
+
+    // disallow construction
+    private
+    InstrumentationHandoff()
+        {
+        }
+
+    public static void
+    premain(String options, Instrumentation inst)
+    {
+        System.out.println("InstrumentationHandoff JPLIS agent initialized");
+        sInstrumentation = inst;
+    }
+
+    // may return null
+    public static Instrumentation
+    getInstrumentation()
+    {
+        return sInstrumentation;
+    }
+
+    public static Instrumentation
+    getInstrumentationOrThrow()
+    {
+        Instrumentation result = getInstrumentation();
+        if ( result == null )
+            {
+            throw new NullPointerException("instrumentation instance not initialized");
+            }
+        return result;
+    }
+
+
+}
diff --git a/jdk/test/java/lang/instrument/IsModifiableClassAgent.java b/jdk/test/java/lang/instrument/IsModifiableClassAgent.java
new file mode 100644
index 0000000..37759d0
--- /dev/null
+++ b/jdk/test/java/lang/instrument/IsModifiableClassAgent.java
@@ -0,0 +1,89 @@
+/*
+ * Copyright 2005-2007 Sun Microsystems, Inc.  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 Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
+ * CA 95054 USA or visit www.sun.com if you need additional information or
+ * have any questions.
+ */
+
+/**
+ * @test
+ * @bug 6331574
+ * @summary test isModifiableClass
+ * @author Robert Field, Sun Microsystems
+ *
+ * @run build IsModifiableClassApp IsModifiableClassAgent
+ * @run shell MakeJAR3.sh IsModifiableClassAgent 'Can-Retransform-Classes: true'
+ * @run main/othervm -javaagent:IsModifiableClassAgent.jar IsModifiableClassApp
+ */
+import java.lang.instrument.*;
+
+public class IsModifiableClassAgent
+{
+    public static boolean fail = false;
+    public static boolean completed = false;
+
+    public static void
+    premain(    String agentArgs,
+                Instrumentation instrumentation)
+        {
+            System.out.println("IsModifiableClassAgent started");
+
+            Class[] allClasses = instrumentation.getAllLoadedClasses();
+            int modCount = 0;
+            int unmodCount = 0;
+
+            for (int i = 0; i < allClasses.length; i++)
+                {
+                    Class klass = allClasses[i];
+                    boolean isMod = instrumentation.isModifiableClass(klass);
+                    if (isMod && klass.isArray()) {
+                        System.err.println("Error: array class returned as modifiable: " + klass);
+                        fail = true;
+                    }
+                    if (isMod && klass.isPrimitive()) {
+                        System.err.println("Error: primitive class returned as modifiable: " + klass);
+                        fail = true;
+                    }
+                    try {
+                        instrumentation.retransformClasses(klass);
+                        if (!isMod) {
+                            System.err.println("Error: unmodifiable class retransformable: " + klass);
+                            fail = true;
+                        }
+                    } catch (UnmodifiableClassException e) {
+                        if (isMod) {
+                            System.err.println("Error: modifiable class not retransformable: " + klass);
+                            System.err.println("  exception: " + e);
+                            fail = true;
+                        }
+                    } catch (Throwable e) {
+                        System.err.println("Error: bad return from retransform: " + klass);
+                        System.err.println("  ERROR: " + e);
+                        fail = true;
+                    }
+                    if (isMod) {
+                        ++modCount;
+                    } else {
+                        ++unmodCount;
+                    }
+                }
+            System.out.println("modifiable: " + modCount + ". unmodifiable: " + unmodCount);
+            completed = true;
+        }
+}
diff --git a/jdk/test/java/lang/instrument/IsModifiableClassApp.java b/jdk/test/java/lang/instrument/IsModifiableClassApp.java
new file mode 100644
index 0000000..1ee79c0
--- /dev/null
+++ b/jdk/test/java/lang/instrument/IsModifiableClassApp.java
@@ -0,0 +1,44 @@
+/*
+ * Copyright 2005 Sun Microsystems, Inc.  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 Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
+ * CA 95054 USA or visit www.sun.com if you need additional information or
+ * have any questions.
+ */
+
+
+import java.io.PrintStream;
+import java.util.*;
+
+public class IsModifiableClassApp {
+
+    public static void main(String args[]) throws Exception {
+        (new IsModifiableClassApp()).run(args, System.out);
+    }
+
+    public void run(String args[], PrintStream out) throws Exception {
+        if (!IsModifiableClassAgent.completed) {
+            throw new Exception("ERROR: IsModifiableClassAgent did not complete.");
+        }
+        if (IsModifiableClassAgent.fail) {
+            throw new Exception("ERROR: IsModifiableClass failed.");
+        } else {
+            out.println("IsModifiableClass succeeded.");
+        }
+    }
+}
diff --git a/jdk/test/java/lang/instrument/MakeJAR.sh b/jdk/test/java/lang/instrument/MakeJAR.sh
new file mode 100644
index 0000000..feeacfe
--- /dev/null
+++ b/jdk/test/java/lang/instrument/MakeJAR.sh
@@ -0,0 +1,53 @@
+#!/bin/sh
+
+#
+# Copyright 2004 Sun Microsystems, Inc.  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 Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
+# CA 95054 USA or visit www.sun.com if you need additional information or
+# have any questions.
+#
+
+
+if [ "${TESTSRC}" = "" ]
+then
+  echo "TESTSRC not set.  Test cannot execute.  Failed."
+  exit 1
+fi
+echo "TESTSRC=${TESTSRC}"
+
+if [ "${TESTJAVA}" = "" ]
+then
+  echo "TESTJAVA not set.  Test cannot execute.  Failed."
+  exit 1
+fi
+echo "TESTJAVA=${TESTJAVA}"
+
+if [ "${TESTCLASSES}" = "" ]
+then
+  echo "TESTCLASSES not set.  Test cannot execute.  Failed."
+  exit 1
+fi
+
+JAVAC="${TESTJAVA}/bin/javac -g"
+JAR="${TESTJAVA}/bin/jar"
+
+cp ${TESTSRC}/InstrumentationHandoff.java InstrumentationHandoff.java
+${JAVAC} InstrumentationHandoff.java
+${JAR} cvfm $1.jar ${TESTSRC}/$1.mf InstrumentationHandoff.class
+rm -f InstrumentationHandoff.class InstrumentationHandoff.java
diff --git a/jdk/test/java/lang/instrument/MakeJAR2.sh b/jdk/test/java/lang/instrument/MakeJAR2.sh
new file mode 100644
index 0000000..2ee0c12
--- /dev/null
+++ b/jdk/test/java/lang/instrument/MakeJAR2.sh
@@ -0,0 +1,95 @@
+#!/bin/sh
+
+#
+# Copyright 2005 Sun Microsystems, Inc.  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 Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
+# CA 95054 USA or visit www.sun.com if you need additional information or
+# have any questions.
+#
+
+
+AGENT="$1"
+APP="$2"
+
+if [ "${TESTSRC}" = "" ]
+then
+  echo "TESTSRC not set.  Test cannot execute.  Failed."
+  exit 1
+fi
+echo "TESTSRC=${TESTSRC}"
+
+if [ "${TESTJAVA}" = "" ]
+then
+  echo "TESTJAVA not set.  Test cannot execute.  Failed."
+  exit 1
+fi
+echo "TESTJAVA=${TESTJAVA}"
+
+if [ "${TESTCLASSES}" = "" ]
+then
+  echo "TESTCLASSES not set.  Test cannot execute.  Failed."
+  exit 1
+fi
+
+OS=`uname -s`
+case "$OS" in
+   SunOS | Linux )
+      PATHSEP=":"
+      ;;
+
+   Windows* | CYGWIN*)
+      PATHSEP=";"
+      ;;
+
+   # catch all other OSs
+   * )
+      echo "Unrecognized system!  $OS"
+      fail "Unrecognized system!  $OS"
+      ;;
+esac
+
+JAVAC="${TESTJAVA}/bin/javac -g"
+JAR="${TESTJAVA}/bin/jar"
+
+cp ${TESTSRC}/${AGENT}.java .
+cp ${TESTSRC}/${APP}.java .
+rm -rf ilib
+cp -r ${TESTSRC}/ilib .
+mkdir bootpath
+cp -r ${TESTSRC}/bootreporter bootpath
+
+cd bootpath
+${JAVAC} bootreporter/*.java
+cd ..
+
+${JAVAC} ${AGENT}.java ilib/*.java
+${JAVAC} -classpath .${PATHSEP}bootpath ${APP}.java
+
+echo "Manifest-Version: 1.0"    >  ${AGENT}.mf
+echo Premain-Class: ${AGENT} >> ${AGENT}.mf
+echo Boot-Class-Path: bootpath >> ${AGENT}.mf
+shift 2
+while [ $# != 0 ] ; do
+  echo $1 >> ${AGENT}.mf
+  shift
+done
+
+${JAR} cvfm ${AGENT}.jar ${AGENT}.mf ${AGENT}*.class ilib/*.class
+
+# rm -rf  ${AGENT}.java ilib ${AGENT}.mf ${AGENT}*.class
diff --git a/jdk/test/java/lang/instrument/MakeJAR3.sh b/jdk/test/java/lang/instrument/MakeJAR3.sh
new file mode 100644
index 0000000..bc24139
--- /dev/null
+++ b/jdk/test/java/lang/instrument/MakeJAR3.sh
@@ -0,0 +1,63 @@
+#!/bin/sh
+
+#
+# Copyright 2005 Sun Microsystems, Inc.  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 Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
+# CA 95054 USA or visit www.sun.com if you need additional information or
+# have any questions.
+#
+
+AGENT="$1"
+
+if [ "${TESTSRC}" = "" ]
+then
+  echo "TESTSRC not set.  Test cannot execute.  Failed."
+  exit 1
+fi
+echo "TESTSRC=${TESTSRC}"
+
+if [ "${TESTJAVA}" = "" ]
+then
+  echo "TESTJAVA not set.  Test cannot execute.  Failed."
+  exit 1
+fi
+echo "TESTJAVA=${TESTJAVA}"
+
+if [ "${TESTCLASSES}" = "" ]
+then
+  echo "TESTCLASSES not set.  Test cannot execute.  Failed."
+  exit 1
+fi
+
+JAVAC="${TESTJAVA}/bin/javac -g"
+JAR="${TESTJAVA}/bin/jar"
+
+cp ${TESTSRC}/${AGENT}.java .
+${JAVAC} ${AGENT}.java
+
+echo "Manifest-Version: 1.0"    >  ${AGENT}.mf
+echo Premain-Class: ${AGENT} >> ${AGENT}.mf
+shift
+while [ $# != 0 ] ; do
+  echo $1 >> ${AGENT}.mf
+  shift
+done
+
+
+${JAR} cvfm ${AGENT}.jar ${AGENT}.mf ${AGENT}*.class
diff --git a/jdk/test/java/lang/instrument/NamedBuffer.java b/jdk/test/java/lang/instrument/NamedBuffer.java
new file mode 100644
index 0000000..128a981
--- /dev/null
+++ b/jdk/test/java/lang/instrument/NamedBuffer.java
@@ -0,0 +1,87 @@
+/*
+ * Copyright 2003 Sun Microsystems, Inc.  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 Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
+ * CA 95054 USA or visit www.sun.com if you need additional information or
+ * have any questions.
+ */
+
+import  java.io.*;
+
+/*
+ * Copyright 2003 Wily Technology, Inc.
+ */
+
+public class NamedBuffer
+{
+    private final String    fName;
+    private final byte[]    fBuffer;
+
+    public
+    NamedBuffer(    String  name,
+                    byte[]  buffer)
+        {
+        fName =     name;
+        fBuffer =   buffer;
+        }
+
+    public
+    NamedBuffer(    String      name,
+                    InputStream stream)
+        throws IOException
+        {
+        this(   name,
+                loadBufferFromStream(stream));
+        }
+
+    public String
+    getName()
+        {
+        return fName;
+        }
+
+    public byte[]
+    getBuffer()
+        {
+        return fBuffer;
+        }
+
+    public static byte[]
+    loadBufferFromStream(InputStream stream)
+        throws IOException
+        {
+        // hack for now, just assume the stream will fit in our reasonable size buffer.
+        // if not, panic
+        int bufferLimit = 200 * 1024;
+        byte[]  readBuffer = new byte[bufferLimit];
+        int actualSize = stream.read(readBuffer);
+        if ( actualSize >= bufferLimit )
+            {
+            // if there might be more bytes, just surrender
+            throw new IOException("too big for buffer");
+            }
+
+        byte[] resultBuffer = new byte[actualSize];
+        System.arraycopy(   readBuffer,
+                            0,
+                            resultBuffer,
+                            0,
+                            actualSize);
+        return resultBuffer;
+        }
+}
diff --git a/jdk/test/java/lang/instrument/NativeMethodPrefixAgent.java b/jdk/test/java/lang/instrument/NativeMethodPrefixAgent.java
new file mode 100644
index 0000000..a31a4d1
--- /dev/null
+++ b/jdk/test/java/lang/instrument/NativeMethodPrefixAgent.java
@@ -0,0 +1,117 @@
+/*
+ * Copyright 2005-2006 Sun Microsystems, Inc.  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 Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
+ * CA 95054 USA or visit www.sun.com if you need additional information or
+ * have any questions.
+ */
+
+/**
+ * @test
+ * @bug 6263319
+ * @summary test setNativeMethodPrefix
+ * @author Robert Field, Sun Microsystems
+ *
+ * @run shell MakeJAR2.sh NativeMethodPrefixAgent NativeMethodPrefixApp 'Can-Retransform-Classes: true' 'Can-Set-Native-Method-Prefix: true'
+ * @run main/othervm -javaagent:NativeMethodPrefixAgent.jar NativeMethodPrefixApp
+ */
+
+import java.lang.instrument.*;
+import java.security.ProtectionDomain;
+import java.io.*;
+
+import ilib.*;
+
+class NativeMethodPrefixAgent {
+
+    static ClassFileTransformer t0, t1, t2;
+    static Instrumentation inst;
+
+    static class Tr implements ClassFileTransformer {
+        final String trname;
+        final int transformId;
+
+        Tr(int transformId) {
+            this.trname = "tr" + transformId;
+            this.transformId = transformId;
+        }
+
+        public byte[]
+        transform(
+            ClassLoader loader,
+            String className,
+            Class<?> classBeingRedefined,
+            ProtectionDomain    protectionDomain,
+            byte[] classfileBuffer) {
+            boolean redef = classBeingRedefined != null;
+            System.out.println(trname + ": " +
+                               (redef? "Retransforming " : "Loading ") + className);
+            if (className != null) {
+                Options opt = new Options();
+                opt.shouldInstrumentNativeMethods = true;
+                opt.trackerClassName = "bootreporter/StringIdCallbackReporter";
+                opt.wrappedTrackerMethodName = "tracker";
+                opt.fixedIndex = transformId;
+                opt.wrappedPrefix = "wrapped_" + trname + "_";
+                try {
+                    byte[] newcf =  Inject.instrumentation(opt, loader, className, classfileBuffer);
+                    return redef? null : newcf;
+                } catch (Throwable ex) {
+                    System.err.println("ERROR: Injection failure: " + ex);
+                    ex.printStackTrace();
+                    System.err.println("Returning bad class file, to cause test failure");
+                    return new byte[0];
+                }
+            }
+            return null;
+        }
+
+    }
+
+    // for debugging
+    static void write_buffer(String fname, byte[]buffer) {
+        try {
+            FileOutputStream outStream = new FileOutputStream(fname);
+            outStream.write(buffer, 0, buffer.length);
+            outStream.close();
+        } catch (Exception ex) {
+            System.err.println("EXCEPTION in write_buffer: " + ex);
+        }
+    }
+
+    public static void
+    premain (String agentArgs, Instrumentation instArg)
+        throws IOException, IllegalClassFormatException,
+        ClassNotFoundException, UnmodifiableClassException {
+        inst = instArg;
+        System.out.println("Premain");
+
+        t1 = new Tr(1);
+        t2 = new Tr(2);
+        t0 = new Tr(0);
+        inst.addTransformer(t1, true);
+        inst.addTransformer(t2, false);
+        inst.addTransformer(t0, true);
+        instArg.setNativeMethodPrefix(t0, "wrapped_tr0_");
+        instArg.setNativeMethodPrefix(t1, "wrapped_tr1_");
+        instArg.setNativeMethodPrefix(t2, "wrapped_tr2_");
+
+        // warm up: cause load of transformer classes before used during class load
+        instArg.retransformClasses(Runtime.class);
+    }
+}
diff --git a/jdk/test/java/lang/instrument/NativeMethodPrefixApp.java b/jdk/test/java/lang/instrument/NativeMethodPrefixApp.java
new file mode 100644
index 0000000..2678ad2
--- /dev/null
+++ b/jdk/test/java/lang/instrument/NativeMethodPrefixApp.java
@@ -0,0 +1,66 @@
+/*
+ * Copyright 2005-2006 Sun Microsystems, Inc.  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 Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
+ * CA 95054 USA or visit www.sun.com if you need additional information or
+ * have any questions.
+ */
+
+
+import java.io.PrintStream;
+import java.util.*;
+import java.lang.management.*;
+import bootreporter.*;
+
+public class NativeMethodPrefixApp implements StringIdCallback {
+
+    // This test is fragile like a golden file test.
+    // It assumes that a specific non-native library method will call a specific
+    // native method.  The below may need to be updated based on library changes.
+    static String goldenNativeMethodName = "getStartupTime";
+
+    static boolean gotIt[] = {false, false, false};
+
+    public static void main(String args[]) throws Exception {
+        (new NativeMethodPrefixApp()).run(args, System.err);
+    }
+
+    public void run(String args[], PrintStream out) throws Exception {
+        StringIdCallbackReporter.registerCallback(this);
+        System.err.println("start");
+
+        java.lang.reflect.Array.getLength(new short[5]);
+        RuntimeMXBean mxbean = ManagementFactory.getRuntimeMXBean();
+        System.err.println(mxbean.getVmVendor());
+
+        for (int i = 0; i < gotIt.length; ++i) {
+            if (!gotIt[i]) {
+                throw new Exception("ERROR: Missing callback for transform " + i);
+            }
+        }
+    }
+
+    public void tracker(String name, int id) {
+        if (name.endsWith(goldenNativeMethodName)) {
+            System.err.println("Tracked #" + id + ": MATCHED -- " + name);
+            gotIt[id] = true;
+        } else {
+            System.err.println("Tracked #" + id + ": " + name);
+        }
+    }
+}
diff --git a/jdk/test/java/lang/instrument/NoTransformerAddedTest.java b/jdk/test/java/lang/instrument/NoTransformerAddedTest.java
new file mode 100644
index 0000000..c1cd17e
--- /dev/null
+++ b/jdk/test/java/lang/instrument/NoTransformerAddedTest.java
@@ -0,0 +1,70 @@
+/*
+ * Copyright 2003-2004 Sun Microsystems, Inc.  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 Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
+ * CA 95054 USA or visit www.sun.com if you need additional information or
+ * have any questions.
+ */
+
+/**
+ * @test
+ * @bug 4882798
+ * @summary make sure no transformers run when none are registered
+ * @author Gabriel Adauto, Wily Technology
+ *
+ * @run build NoTransformerAddedTest
+ * @run shell MakeJAR.sh redefineAgent
+ * @run main/othervm -javaagent:redefineAgent.jar NoTransformerAddedTest NoTransformerAddedTest
+ */
+public class
+NoTransformerAddedTest
+    extends ATransformerManagementTestCase
+{
+
+    /**
+     * Constructor for NoTransformerAddedTest.
+     * @param name
+     */
+    public NoTransformerAddedTest(String name)
+    {
+        super(name);
+    }
+
+    public static void
+    main (String[] args)
+        throws Throwable {
+        ATestCaseScaffold   test = new NoTransformerAddedTest(args[0]);
+        test.runTest();
+    }
+
+    protected final void
+    doRunTest()
+        throws Throwable {
+        testNoTransformersAdded();
+    }
+
+    /**
+     * Add no transformers to the the manager and check it
+     */
+    public void
+    testNoTransformersAdded()
+    {
+        verifyTransformers(fInst);
+    }
+
+}
diff --git a/jdk/test/java/lang/instrument/NullGetObjectSizeTest.java b/jdk/test/java/lang/instrument/NullGetObjectSizeTest.java
new file mode 100644
index 0000000..e4c578b
--- /dev/null
+++ b/jdk/test/java/lang/instrument/NullGetObjectSizeTest.java
@@ -0,0 +1,73 @@
+/*
+ * Copyright 2003-2004 Sun Microsystems, Inc.  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 Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
+ * CA 95054 USA or visit www.sun.com if you need additional information or
+ * have any questions.
+ */
+
+/**
+ * @test
+ * @bug 4920005 4882798
+ * @summary make sure getObjectSize(null) throws NullPointerException.
+ * @author Robert Field as modified from the code of Gabriel Adauto, Wily Technology
+ *
+ * @run build NullGetObjectSizeTest
+ * @run shell MakeJAR.sh basicAgent
+ * @run main/othervm -javaagent:basicAgent.jar NullGetObjectSizeTest NullGetObjectSizeTest
+ */
+
+public class
+NullGetObjectSizeTest
+    extends ASimpleInstrumentationTestCase
+{
+
+    /**
+     * Constructor for NullGetObjectSizeTest.
+     * @param name
+     */
+    public NullGetObjectSizeTest(String name) {
+        super(name);
+    }
+
+    public static void
+    main (String[] args) throws Throwable {
+        ATestCaseScaffold   test = new NullGetObjectSizeTest(args[0]);
+        test.runTest();
+    }
+
+    protected final void
+    doRunTest() {
+        testNullGetObjectSize();
+    }
+
+
+    public void
+    testNullGetObjectSize() {
+        boolean caught = false;
+
+        // Test that a null argument throws NullPointerException
+        try {
+            fInst.getObjectSize(null);
+        } catch (NullPointerException npe) {
+            caught = true;
+        }
+        assertTrue(caught);
+    }
+
+}
diff --git a/jdk/test/java/lang/instrument/NullRedefineClassesTests.java b/jdk/test/java/lang/instrument/NullRedefineClassesTests.java
new file mode 100644
index 0000000..afa8c9f
--- /dev/null
+++ b/jdk/test/java/lang/instrument/NullRedefineClassesTests.java
@@ -0,0 +1,113 @@
+/*
+ * Copyright 2003-2004 Sun Microsystems, Inc.  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 Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
+ * CA 95054 USA or visit www.sun.com if you need additional information or
+ * have any questions.
+ */
+
+/**
+ * @test
+ * @bug 4920005 4882798
+ * @summary make sure redefineClasses throws NullPointerException in the right places.
+ * @author Robert Field as modified from the code of Gabriel Adauto, Wily Technology
+ *
+ * @run build NullRedefineClassesTests
+ * @run shell MakeJAR.sh redefineAgent
+ * @run main/othervm -javaagent:redefineAgent.jar NullRedefineClassesTests NullRedefineClassesTests
+ */
+
+import java.lang.instrument.ClassDefinition;
+import java.lang.instrument.UnmodifiableClassException;
+
+public class
+NullRedefineClassesTests
+    extends ASimpleInstrumentationTestCase
+{
+
+    /**
+     * Constructor for NullRedefineClassesTests.
+     * @param name
+     */
+    public NullRedefineClassesTests(String name) {
+        super(name);
+    }
+
+    public static void
+    main (String[] args) throws Throwable {
+        ATestCaseScaffold   test = new NullRedefineClassesTests(args[0]);
+        test.runTest();
+    }
+
+    protected final void
+    doRunTest() throws ClassNotFoundException, UnmodifiableClassException  {
+        testNullRedefineClasses();
+    }
+
+
+    public void
+    testNullRedefineClasses() throws ClassNotFoundException, UnmodifiableClassException {
+        boolean caught;
+
+        // Test that a null argument throws NullPointerException
+        caught = false;
+        try {
+            fInst.redefineClasses(null);
+        } catch (NullPointerException npe) {
+            caught = true;
+        }
+        assertTrue(caught);
+
+        // Test that a null element throws NullPointerException
+        caught = false;
+        try {
+            fInst.redefineClasses(new ClassDefinition[]{ null });
+        } catch (NullPointerException npe) {
+            caught = true;
+        }
+        assertTrue(caught);
+
+        // Test that a null element amonst others throws NullPointerException
+        caught = false;
+        ClassDefinition cd = new ClassDefinition(DummyClass.class, new byte[] {1, 2, 3});
+        try {
+            fInst.redefineClasses(new ClassDefinition[]{ cd, null });
+        } catch (NullPointerException npe) {
+            caught = true;
+        }
+        assertTrue(caught);
+
+        // Test that a null class throws NullPointerException
+        caught = false;
+        try {
+            new ClassDefinition(null, new byte[] {1, 2, 3});
+        } catch (NullPointerException npe) {
+            caught = true;
+        }
+        assertTrue(caught);
+
+        // Test that a null byte array throws NullPointerException
+        caught = false;
+        try {
+            new ClassDefinition(DummyClass.class, null);
+        } catch (NullPointerException npe) {
+            caught = true;
+        }
+        assertTrue(caught);
+    }
+}
diff --git a/jdk/test/java/lang/instrument/NullTransformerAddTest.java b/jdk/test/java/lang/instrument/NullTransformerAddTest.java
new file mode 100644
index 0000000..0c8b3b8
--- /dev/null
+++ b/jdk/test/java/lang/instrument/NullTransformerAddTest.java
@@ -0,0 +1,80 @@
+/*
+ * Copyright 2003-2004 Sun Microsystems, Inc.  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 Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
+ * CA 95054 USA or visit www.sun.com if you need additional information or
+ * have any questions.
+ */
+
+/**
+ * @test
+ * @bug 4882798
+ * @summary make sure addTransformer(null) throws what it should
+ * @author Gabriel Adauto, Wily Technology
+ *
+ * @run build NullTransformerAddTest
+ * @run shell MakeJAR.sh redefineAgent
+ * @run main/othervm -javaagent:redefineAgent.jar NullTransformerAddTest NullTransformerAddTest
+ */
+public class
+NullTransformerAddTest
+    extends ATransformerManagementTestCase
+{
+
+    /**
+     * Constructor for NullTransformerAddTest.
+     * @param name
+     */
+    public NullTransformerAddTest(String name)
+    {
+        super(name);
+    }
+
+    public static void
+    main (String[] args)
+        throws Throwable {
+        ATestCaseScaffold   test = new NullTransformerAddTest(args[0]);
+        test.runTest();
+    }
+
+    protected final void
+    doRunTest()
+        throws Throwable {
+        testNullTransformerAdd();
+    }
+
+
+    /**
+     * Add null transformers to the the manager and check it
+     */
+    public void
+    testNullTransformerAdd()
+    {
+        boolean caughtIt = false;
+        try
+            {
+            addTransformerToManager(fInst, null);
+            }
+        catch (NullPointerException npe)
+            {
+            caughtIt = true;
+            }
+        assertTrue(caughtIt);
+    }
+
+}
diff --git a/jdk/test/java/lang/instrument/NullTransformerRemoveTest.java b/jdk/test/java/lang/instrument/NullTransformerRemoveTest.java
new file mode 100644
index 0000000..8c7299b
--- /dev/null
+++ b/jdk/test/java/lang/instrument/NullTransformerRemoveTest.java
@@ -0,0 +1,75 @@
+/*
+ * Copyright 2003-2004 Sun Microsystems, Inc.  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 Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
+ * CA 95054 USA or visit www.sun.com if you need additional information or
+ * have any questions.
+ */
+
+/**
+ * @test
+ * @bug 4920005 4882798
+ * @summary make sure removeTransformer(null) throws NullPointerException
+ * @author Robert Field as modified from the code of Gabriel Adauto, Wily Technology
+ *
+ * @run build NullTransformerRemoveTest
+ * @run shell MakeJAR.sh redefineAgent
+ * @run main/othervm -javaagent:redefineAgent.jar NullTransformerRemoveTest NullTransformerRemoveTest
+ */
+public class
+NullTransformerRemoveTest
+    extends ATransformerManagementTestCase
+{
+
+    /**
+     * Constructor for NullTransformerRemoveTest.
+     * @param name
+     */
+    public NullTransformerRemoveTest(String name) {
+        super(name);
+    }
+
+    public static void
+    main (String[] args)  throws Throwable {
+        ATestCaseScaffold   test = new NullTransformerRemoveTest(args[0]);
+        test.runTest();
+    }
+
+    protected final void
+    doRunTest() {
+        testNullTransformerRemove();
+    }
+
+
+    /**
+     * Remove null transformers from the the manager and check
+     * that it throws NullPointerException
+     */
+    public void
+    testNullTransformerRemove() {
+        boolean caught = false;
+
+        try {
+            fInst.removeTransformer(null);
+        } catch (NullPointerException npe) {
+            caught = true;
+        }
+        assertTrue(caught);
+    }
+
+}
diff --git a/jdk/test/java/lang/instrument/PremainClass/Agent.jar b/jdk/test/java/lang/instrument/PremainClass/Agent.jar
new file mode 100644
index 0000000..a698d7d
--- /dev/null
+++ b/jdk/test/java/lang/instrument/PremainClass/Agent.jar
Binary files differ
diff --git a/jdk/test/java/lang/instrument/PremainClass/CreateFiles.java b/jdk/test/java/lang/instrument/PremainClass/CreateFiles.java
new file mode 100644
index 0000000..2a9966c
--- /dev/null
+++ b/jdk/test/java/lang/instrument/PremainClass/CreateFiles.java
@@ -0,0 +1,64 @@
+/*
+ * Copyright 2004 Sun Microsystems, Inc.  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 Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
+ * CA 95054 USA or visit www.sun.com if you need additional information or
+ * have any questions.
+ */
+
+/*
+ *
+ *
+ * Creates a "no-op" agent with a non US-Ascii class name, and a corresponding
+ * jar manifest file with the Premain-Class attribute value set to the
+ * name of the agent class.
+ */
+import java.io.File;
+import java.io.FileOutputStream;
+
+public class CreateFiles {
+
+    static void output(FileOutputStream fos, String s) throws Exception {
+        fos.write( s.getBytes("UTF8") );
+        fos.write( "\n".getBytes("UTF8") );
+    }
+
+    public static void main(String [] args) throws Exception {
+        File f;
+        FileOutputStream fos;
+
+        String name = "\u20ac";
+
+        f = new File(name + ".java");
+        fos = new FileOutputStream(f);
+        output(fos, "import java.lang.instrument.Instrumentation;" );
+        output(fos, "public class " +name + " {" );
+        output(fos, "    public static void premain(String ops, Instrumentation ins) {" );
+        output(fos, "        System.out.println(\"premain running\"); ");
+        output(fos, "    }");
+        output(fos, "}");
+        fos.close();
+
+        f = new File("agent.mf");
+        fos = new FileOutputStream(f);
+        output(fos, "Manifest-Version: 1.0");
+        output(fos, "Premain-Class: " + name);
+        output(fos, "");
+        fos.close();
+    }
+}
diff --git a/jdk/test/java/lang/instrument/PremainClass/DummyMain.java b/jdk/test/java/lang/instrument/PremainClass/DummyMain.java
new file mode 100644
index 0000000..e5fd157
--- /dev/null
+++ b/jdk/test/java/lang/instrument/PremainClass/DummyMain.java
@@ -0,0 +1,32 @@
+/*
+ * Copyright 2004 Sun Microsystems, Inc.  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 Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
+ * CA 95054 USA or visit www.sun.com if you need additional information or
+ * have any questions.
+ */
+
+/*
+ *
+ *
+ * Used by PremainClassTest.sh - dummy "main application" which doesn't do anything
+ */
+public class DummyMain {
+    public static void main(String[] args) {
+    }
+}
diff --git a/jdk/test/java/lang/instrument/PremainClass/PremainClassTest.sh b/jdk/test/java/lang/instrument/PremainClass/PremainClassTest.sh
new file mode 100644
index 0000000..7295c34
--- /dev/null
+++ b/jdk/test/java/lang/instrument/PremainClass/PremainClassTest.sh
@@ -0,0 +1,55 @@
+#
+# Copyright 2004 Sun Microsystems, Inc.  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 Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
+# CA 95054 USA or visit www.sun.com if you need additional information or
+# have any questions.
+#
+
+# @test
+# @bug 5055293
+# @summary Test non US-ASCII characters in the value of the Premain-Class
+#          attribute.
+
+if [ "${TESTJAVA}" = "" ]
+then
+  echo "TESTJAVA not set.  Test cannot execute.  Failed."
+  exit 1
+fi
+
+if [ "${TESTSRC}" = "" ]
+then
+  echo "TESTSRC not set.  Test cannot execute.  Failed."
+  exit 1
+fi
+
+if [ "${TESTCLASSES}" = "" ]
+then
+  echo "TESTCLASSES not set.  Test cannot execute.  Failed."
+  exit 1
+fi
+
+JAVAC="${TESTJAVA}"/bin/javac
+JAVA="${TESTJAVA}"/bin/java
+
+"$JAVAC" -d "${TESTCLASSES}" "${TESTSRC}"/DummyMain.java
+
+"${JAVA}" -javaagent:"${TESTSRC}"/Agent.jar -classpath "${TESTCLASSES}" DummyMain
+result=$?
+
+exit $result
diff --git a/jdk/test/java/lang/instrument/PremainClass/README b/jdk/test/java/lang/instrument/PremainClass/README
new file mode 100644
index 0000000..a0a1186
--- /dev/null
+++ b/jdk/test/java/lang/instrument/PremainClass/README
@@ -0,0 +1,22 @@
+
+This directory contains a test to exercise the Premain-Class attribute with
+a non US-ASCII class name. As the file system may not support a file with 
+this name the test is compiled off-line and the jar file checked into SCCS.
+
+In the event that Agent.jar needs to be re-built here are the steps which
+must be performed on a system that supports the the EURO in a file name
+(Windows 2000 is fine) :-
+
+1. Create the agent source file and agent.mf :-
+
+    javac CreateFiles.java
+    java CreateFiles
+
+2. Re-create the agent jar file :-
+
+    rm CreateFiles.class
+    javac -encoding utf8 *.java
+    jar cfm Agent.jar agent.mf *.class
+
+3. Check Agent.jar into SCCS.
+
diff --git a/jdk/test/java/lang/instrument/RedefineClassesDisabledTest.java b/jdk/test/java/lang/instrument/RedefineClassesDisabledTest.java
new file mode 100644
index 0000000..ecbc9bf
--- /dev/null
+++ b/jdk/test/java/lang/instrument/RedefineClassesDisabledTest.java
@@ -0,0 +1,111 @@
+/*
+ * Copyright 2004 Sun Microsystems, Inc.  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 Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
+ * CA 95054 USA or visit www.sun.com if you need additional information or
+ * have any questions.
+ */
+
+/**
+ * @test
+ * @bug 4882798
+ * @summary test that redefineClasses and isRedefineClassesSupported behave correctly when redefine is not enabled
+ * @author Robert Field, Sun Microsystems -- as modified from the work of Gabriel Adauto, Wily Technology
+ *
+ * @run build RedefineClassesDisabledTest
+ * @run shell RedefineSetUp.sh
+ * @run shell MakeJAR.sh basicAgent
+ * @run main/othervm -javaagent:basicAgent.jar RedefineClassesDisabledTest RedefineClassesDisabledTest
+ */
+
+import java.io.*;
+import java.lang.instrument.*;
+import java.lang.reflect.*;
+public class
+RedefineClassesDisabledTest
+    extends ASimpleInstrumentationTestCase
+{
+
+    /**
+     * Constructor for RedefineClassesDisabledTest.
+     * @param name
+     */
+    public RedefineClassesDisabledTest(String name)
+    {
+        super(name);
+    }
+
+    public static void
+    main (String[] args)
+        throws Throwable {
+        ATestCaseScaffold   test = new RedefineClassesDisabledTest(args[0]);
+        test.runTest();
+    }
+
+    protected final void
+    doRunTest()
+        throws Throwable {
+        testIsRedefineClassesSupported();
+        testSimpleRedefineClasses();
+    }
+
+
+    public void
+    testIsRedefineClassesSupported()
+    {
+        boolean canRedef = fInst.isRedefineClassesSupported();
+        assertTrue("Can redefine classes flag set incorrectly (true)", !canRedef);
+    }
+
+    public void
+    testSimpleRedefineClasses()
+        throws Throwable
+    {
+        // first load the class and prove that it is the right one
+        ExampleRedefine ex = new ExampleRedefine();
+
+        // with this version of the class, doSomething is a nop
+        int firstGet = ex.get();
+        ex.doSomething();
+        int secondGet = ex.get();
+
+        assertEquals(firstGet, secondGet);
+
+        // now redefine the class. This will change doSomething to be an increment
+
+        // this class is stored in a different place (scratch directory) to avoid collisions
+        File f = new File("Different_ExampleRedefine.class");
+        System.out.println("Reading test class from " + f);
+        InputStream redefineStream = new FileInputStream(f);
+
+        byte[] redefineBuffer = NamedBuffer.loadBufferFromStream(redefineStream);
+
+        ClassDefinition redefineParamBlock = new ClassDefinition(   ExampleRedefine.class,
+                                                                    redefineBuffer);
+
+        // test that the redefine fails with an UnsupportedOperationException
+        boolean caught = false;
+        try {
+            fInst.redefineClasses(new ClassDefinition[] {redefineParamBlock});
+        } catch (UnsupportedOperationException uoe) {
+            caught = true;
+        }
+        assertTrue(caught);
+    }
+
+}
diff --git a/jdk/test/java/lang/instrument/RedefineClassesTests.java b/jdk/test/java/lang/instrument/RedefineClassesTests.java
new file mode 100644
index 0000000..3a39a42
--- /dev/null
+++ b/jdk/test/java/lang/instrument/RedefineClassesTests.java
@@ -0,0 +1,141 @@
+/*
+ * Copyright 2003-2005 Sun Microsystems, Inc.  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 Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
+ * CA 95054 USA or visit www.sun.com if you need additional information or
+ * have any questions.
+ */
+
+/**
+ * @test
+ * @bug 4882798 5067523
+ * @summary insure redefine is supported. exercise a class, then redefine it and do it again
+ * @author Gabriel Adauto, Wily Technology
+ *
+ * @run build RedefineClassesTests
+ * @run shell RedefineSetUp.sh
+ * @run shell MakeJAR.sh redefineAgent
+ * @run main/othervm -javaagent:redefineAgent.jar RedefineClassesTests RedefineClassesTests
+ */
+
+import java.io.*;
+import java.lang.instrument.*;
+import java.lang.reflect.*;
+public class
+RedefineClassesTests
+    extends ASimpleInstrumentationTestCase
+{
+
+    /**
+     * Constructor for RedefineClassesTests.
+     * @param name
+     */
+    public RedefineClassesTests(String name)
+    {
+        super(name);
+    }
+
+    public static void
+    main (String[] args)
+        throws Throwable {
+        ATestCaseScaffold   test = new RedefineClassesTests(args[0]);
+        test.runTest();
+    }
+
+    protected final void
+    doRunTest()
+        throws Throwable {
+        testIsRedefineClassesSupported();
+        testSimpleRedefineClasses();
+        testUnmodifiableClassException();
+    }
+
+
+    public void
+    testIsRedefineClassesSupported()
+    {
+        boolean canRedef = fInst.isRedefineClassesSupported();
+        assertTrue("Cannot redefine classes", canRedef);
+    }
+
+    public void
+    testSimpleRedefineClasses()
+        throws Throwable
+    {
+        // first load the class and prove that it is the right one
+        ExampleRedefine ex = new ExampleRedefine();
+
+        // with this version of the class, doSomething is a nop
+        int firstGet = ex.get();
+        ex.doSomething();
+        int secondGet = ex.get();
+
+        assertEquals(firstGet, secondGet);
+
+        // now redefine the class. This will change doSomething to be an increment
+
+        // this class is stored in a different place (scratch directory) to avoid collisions
+        File f = new File("Different_ExampleRedefine.class");
+        System.out.println("Reading test class from " + f);
+        InputStream redefineStream = new FileInputStream(f);
+
+        byte[] redefineBuffer = NamedBuffer.loadBufferFromStream(redefineStream);
+
+        ClassDefinition redefineParamBlock = new ClassDefinition(   ExampleRedefine.class,
+                                                                    redefineBuffer);
+
+        fInst.redefineClasses(new ClassDefinition[] {redefineParamBlock});
+
+        int thirdGet = ex.get();
+        ex.doSomething();
+        int fourthGet = ex.get();
+        assertEquals(thirdGet + 1, fourthGet);
+    }
+
+    public void
+    testUnmodifiableClassException()
+        throws Throwable
+    {
+        System.out.println("Testing UnmodifiableClassException");
+
+        // Load any class
+        File f = new File("Different_ExampleRedefine.class");
+        InputStream redefineStream = new FileInputStream(f);
+        byte[] redefineBuffer = NamedBuffer.loadBufferFromStream(redefineStream);
+
+        System.out.println("Try to redefine class for primitive type");
+        try {
+            ClassDefinition redefineParamBlock =
+                new ClassDefinition( byte.class, redefineBuffer );
+            fInst.redefineClasses(new ClassDefinition[] {redefineParamBlock});
+            fail();
+        } catch (UnmodifiableClassException x) {
+        }
+
+        System.out.println("Try to redefine class for array type");
+        try {
+            ClassDefinition redefineParamBlock =
+                new ClassDefinition( byte[].class, redefineBuffer );
+            fInst.redefineClasses(new ClassDefinition[] {redefineParamBlock});
+            fail();
+        } catch (UnmodifiableClassException x) {
+        }
+
+    }
+
+}
diff --git a/jdk/test/java/lang/instrument/RedefineSetUp.sh b/jdk/test/java/lang/instrument/RedefineSetUp.sh
new file mode 100644
index 0000000..9f9eeb1
--- /dev/null
+++ b/jdk/test/java/lang/instrument/RedefineSetUp.sh
@@ -0,0 +1,64 @@
+#!/bin/sh
+
+#
+# Copyright 2003 Sun Microsystems, Inc.  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 Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
+# CA 95054 USA or visit www.sun.com if you need additional information or
+# have any questions.
+#
+
+
+#
+#
+
+if [ "${TESTSRC}" = "" ]
+then
+  echo "TESTSRC not set.  Test cannot execute.  Failed."
+  exit 1
+fi
+echo "TESTSRC=${TESTSRC}"
+
+if [ "${TESTJAVA}" = "" ]
+then
+  echo "TESTJAVA not set.  Test cannot execute.  Failed."
+  exit 1
+fi
+echo "TESTJAVA=${TESTJAVA}"
+
+if [ "${TESTCLASSES}" = "" ]
+then
+  echo "TESTCLASSES not set.  Test cannot execute.  Failed."
+  exit 1
+fi
+
+echo "TESTCLASSES=${TESTCLASSES}"
+echo "CLASSPATH=${CLASSPATH}"
+
+JAVAC="${TESTJAVA}/bin/javac -g"
+
+cp ${TESTSRC}/Different_ExampleRedefine.java ExampleRedefine.java
+cp ${TESTSRC}/Counter.java .
+${JAVAC} ExampleRedefine.java
+mv ExampleRedefine.class Different_ExampleRedefine.class
+rm -f ExampleRedefine.java Counter.java
+
+cp ${TESTSRC}/ExampleRedefine.java ExampleRedefine.java
+cp ${TESTSRC}/Counter.java .
+${JAVAC} ExampleRedefine.java
+rm -f ExampleRedefine.java Counter.java
diff --git a/jdk/test/java/lang/instrument/RemoveAbsentTransformerTest.java b/jdk/test/java/lang/instrument/RemoveAbsentTransformerTest.java
new file mode 100644
index 0000000..ee58a2a
--- /dev/null
+++ b/jdk/test/java/lang/instrument/RemoveAbsentTransformerTest.java
@@ -0,0 +1,82 @@
+/*
+ * Copyright 2003-2004 Sun Microsystems, Inc.  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 Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
+ * CA 95054 USA or visit www.sun.com if you need additional information or
+ * have any questions.
+ */
+
+/**
+ * @test
+ * @bug 4882798
+ * @summary remove an transformer that was never added
+ * @author Gabriel Adauto, Wily Technology
+ *
+ * @run build RemoveAbsentTransformerTest
+ * @run shell MakeJAR.sh redefineAgent
+ * @run main/othervm -javaagent:redefineAgent.jar RemoveAbsentTransformerTest RemoveAbsentTransformerTest
+ */
+import java.lang.instrument.*;
+
+public class
+RemoveAbsentTransformerTest
+    extends ATransformerManagementTestCase
+{
+
+    /**
+     * Constructor for RemoveAbsentTransformerTest.
+     * @param name
+     */
+    public RemoveAbsentTransformerTest(String name)
+    {
+        super(name);
+    }
+
+    public static void
+    main (String[] args)
+        throws Throwable {
+        ATestCaseScaffold   test = new RemoveAbsentTransformerTest(args[0]);
+        test.runTest();
+    }
+
+    protected final void
+    doRunTest()
+        throws Throwable {
+        testRemoveNonExistentTransformer();
+    }
+
+    /**
+     * Remove transformers that were not added
+     */
+    public void
+    testRemoveNonExistentTransformer()
+    {
+        boolean result;
+        ClassFileTransformer moreThanMeetsTheEye = new MyClassFileTransformer("NonExistent");
+
+        addTransformerToManager(fInst, moreThanMeetsTheEye);
+        removeTransformerFromManager(fInst, moreThanMeetsTheEye);
+        result = fInst.removeTransformer(new MyClassFileTransformer("NonExistent2"));
+        assertTrue(!result);
+        result = fInst.removeTransformer(moreThanMeetsTheEye);
+        assertTrue(!result);
+
+        verifyTransformers(fInst);
+    }
+
+}
diff --git a/jdk/test/java/lang/instrument/RemoveTransformerTest.java b/jdk/test/java/lang/instrument/RemoveTransformerTest.java
new file mode 100644
index 0000000..c255197
--- /dev/null
+++ b/jdk/test/java/lang/instrument/RemoveTransformerTest.java
@@ -0,0 +1,81 @@
+/*
+ * Copyright 2003-2004 Sun Microsystems, Inc.  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 Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
+ * CA 95054 USA or visit www.sun.com if you need additional information or
+ * have any questions.
+ */
+
+/**
+ * @test
+ * @bug 4882798
+ * @summary simple remove of a transformer that was added
+ * @author Gabriel Adauto, Wily Technology
+ *
+ * @run build RemoveTransformerTest
+ * @run shell MakeJAR.sh redefineAgent
+ * @run main/othervm -javaagent:redefineAgent.jar RemoveTransformerTest RemoveTransformerTest
+ */
+public class
+RemoveTransformerTest
+    extends ATransformerManagementTestCase
+{
+
+    /**
+     * Constructor for RemoveTransformerTest.
+     * @param name
+     */
+    public RemoveTransformerTest(String name)
+    {
+        super(name);
+    }
+
+    public static void
+    main (String[] args)
+        throws Throwable {
+        ATestCaseScaffold   test = new RemoveTransformerTest(args[0]);
+        test.runTest();
+    }
+
+    protected final void
+    doRunTest()
+        throws Throwable {
+        testRemoveTransformer();
+    }
+
+
+    /**
+     * Add and remove a bunch of transformers to the manager and
+     * check that they get called.
+     */
+    public void
+    testRemoveTransformer()
+    {
+        for (int i = 0; i < kTransformerSamples.length; i++)
+        {
+            addTransformerToManager(fInst, kTransformerSamples[i]);
+            if (i % kModSamples == 1)
+            {
+                removeTransformerFromManager(fInst, kTransformerSamples[i]);
+            }
+        }
+
+        verifyTransformers(fInst);
+    }
+
+}
diff --git a/jdk/test/java/lang/instrument/RetransformAgent.java b/jdk/test/java/lang/instrument/RetransformAgent.java
new file mode 100644
index 0000000..a88b756
--- /dev/null
+++ b/jdk/test/java/lang/instrument/RetransformAgent.java
@@ -0,0 +1,149 @@
+/*
+ * Copyright 2005 Sun Microsystems, Inc.  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 Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
+ * CA 95054 USA or visit www.sun.com if you need additional information or
+ * have any questions.
+ */
+
+/**
+ * @test
+ * @bug 6274264 6274241 5070281
+ * @summary test retransformClasses
+ * @author Robert Field, Sun Microsystems
+ *
+ * @run shell MakeJAR2.sh RetransformAgent RetransformApp 'Can-Retransform-Classes: true'
+ * @run main/othervm -javaagent:RetransformAgent.jar RetransformApp
+ */
+
+import java.lang.instrument.*;
+import java.security.ProtectionDomain;
+import java.io.*;
+
+import ilib.*;
+
+class RetransformAgent {
+
+    static ClassFileTransformer t1, t2, t3, t4;
+    static Instrumentation inst;
+    static boolean succeeded = true;
+    static int markCount = 0;
+    static int[] markGolden = {30, 40, 20, 30, 40, 20, 30, 40, 20, 30, 40, 20,
+                               11, 40, 20, 11, 40, 20, 11, 40, 20, 11, 40, 20};
+
+    static class Tr implements ClassFileTransformer {
+        final String trname;
+        final boolean onLoad;
+        final int loadIndex;
+        final boolean onRedef;
+        final int redefIndex;
+        final String cname;
+        final String nname;
+
+        Tr(String trname, boolean onLoad, int loadIndex, boolean onRedef, int redefIndex,
+           String cname, String nname) {
+            this.trname = trname;
+            this.onLoad = onLoad;
+            this.loadIndex = loadIndex;
+            this.onRedef = onRedef;
+            this.redefIndex = redefIndex;
+            this.cname = cname;
+            this.nname = nname;
+        }
+
+        public byte[] transform(ClassLoader loader,
+                                String className,
+                                Class<?> classBeingRedefined,
+                                ProtectionDomain    protectionDomain,
+                                byte[] classfileBuffer) {
+            boolean redef = classBeingRedefined != null;
+            // System.err.println("hook " + trname + ": " + className +
+            //                    (redef? " REDEF" : " LOAD"));
+            if ((redef? onRedef : onLoad) && className != null && className.equals(cname)) {
+                Options opt = new Options();
+                opt.shouldInstrumentIndexed = true;
+                opt.shouldInstrumentCall = true;
+                opt.targetMethod = nname;
+                opt.fixedIndex = redef? redefIndex : loadIndex;
+                opt.trackerClassName = "RetransformAgent";
+                try {
+                    byte[] newcf =  Inject.instrumentation(opt, loader, className, classfileBuffer);
+                    /*** debugging ...
+                         String fname = trname + (redef?"_redef" : "");
+                         write_buffer(fname + "_before.class", classfileBuffer);
+                         write_buffer(fname + "_instr.class", newcf);
+                    ***/
+                    System.err.println(trname + ": " + className + " index: " + opt.fixedIndex +
+                                       (redef? " REDEF" : " LOAD") +
+                                       " len before: " + classfileBuffer.length +
+                                       " after: " + newcf.length);
+                    return newcf;
+                } catch (Throwable ex) {
+                    System.err.println("Injection failure: " + ex);
+                    ex.printStackTrace();
+                }
+            }
+            return null;
+        }
+    }
+
+    static void write_buffer(String fname, byte[]buffer) {
+        try {
+            FileOutputStream outStream = new FileOutputStream(fname);
+            outStream.write(buffer, 0, buffer.length);
+            outStream.close();
+        } catch (Exception ex) {
+            System.err.println("EXCEPTION in write_buffer: " + ex);
+        }
+    }
+
+    public static void premain (String agentArgs, Instrumentation instArg) {
+        inst = instArg;
+        System.err.println("Premain");
+
+        t1 = new Tr("TR1", false, 10, true, 11, "RetransformApp", "foo");
+        inst.addTransformer(t1, true);
+        t2 = new Tr("TN2", true,  20, true, 21, "RetransformApp", "foo");
+        inst.addTransformer(t2, false);
+        t3 = new Tr("TR3", true,  30, true, 31, "RetransformApp", "foo");
+        inst.addTransformer(t3, true);
+        t4 = new Tr("TN4", true,  40, true, 41, "RetransformApp", "foo");
+        inst.addTransformer(t4, false);
+    }
+
+    public static void undo() {
+        inst.removeTransformer(t3);
+        try {
+            System.err.println("RETRANSFORM");
+            inst.retransformClasses(new RetransformApp().getClass());
+        } catch (Exception ex) {
+            System.err.println("EXCEPTION on undo: " + ex);
+        }
+    }
+
+    public static boolean succeeded() {
+        return succeeded && markCount == markGolden.length;
+    }
+
+    public static void callTracker(int mark) {
+        System.err.println("got mark " + mark);
+        if (markCount >= markGolden.length || mark != markGolden[markCount++]) {
+            succeeded = false;
+        }
+    }
+}
diff --git a/jdk/test/java/lang/instrument/RetransformApp.java b/jdk/test/java/lang/instrument/RetransformApp.java
new file mode 100644
index 0000000..aa8155d
--- /dev/null
+++ b/jdk/test/java/lang/instrument/RetransformApp.java
@@ -0,0 +1,59 @@
+/*
+ * Copyright 2005 Sun Microsystems, Inc.  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 Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
+ * CA 95054 USA or visit www.sun.com if you need additional information or
+ * have any questions.
+ */
+
+
+import java.io.PrintStream;
+import java.util.*;
+
+public class RetransformApp {
+
+    public static void main(String args[]) throws Exception {
+        (new RetransformApp()).run(args, System.out);
+    }
+
+    int foo(int x) {
+        return x * x;
+    }
+
+    public void run(String args[], PrintStream out) throws Exception {
+        out.println("start");
+        for (int i = 0; i < 4; i++) {
+            if (foo(3) != 9) {
+                throw new Exception("ERROR: unexpected application behavior");
+            }
+        }
+        out.println("undo");
+        RetransformAgent.undo();
+        for (int i = 0; i < 4; i++) {
+            if (foo(3) != 9) {
+                throw new Exception("ERROR: unexpected application behavior");
+            }
+        }
+        out.println("end");
+        if (RetransformAgent.succeeded()) {
+            out.println("Instrumentation succeeded.");
+        } else {
+            throw new Exception("ERROR: Instrumentation failed.");
+        }
+    }
+}
diff --git a/jdk/test/java/lang/instrument/RuntimeConstants.java b/jdk/test/java/lang/instrument/RuntimeConstants.java
new file mode 100644
index 0000000..16f78a3
--- /dev/null
+++ b/jdk/test/java/lang/instrument/RuntimeConstants.java
@@ -0,0 +1,730 @@
+/*
+ * Copyright 2003 Sun Microsystems, Inc.  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 Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
+ * CA 95054 USA or visit www.sun.com if you need additional information or
+ * have any questions.
+ */
+
+public interface RuntimeConstants {
+
+    /* Signature Characters */
+    char   SIGC_VOID                  = 'V';
+    String SIG_VOID                   = "V";
+    char   SIGC_BOOLEAN               = 'Z';
+    String SIG_BOOLEAN                = "Z";
+    char   SIGC_BYTE                  = 'B';
+    String SIG_BYTE                   = "B";
+    char   SIGC_CHAR                  = 'C';
+    String SIG_CHAR                   = "C";
+    char   SIGC_SHORT                 = 'S';
+    String SIG_SHORT                  = "S";
+    char   SIGC_INT                   = 'I';
+    String SIG_INT                    = "I";
+    char   SIGC_LONG                  = 'J';
+    String SIG_LONG                   = "J";
+    char   SIGC_FLOAT                 = 'F';
+    String SIG_FLOAT                  = "F";
+    char   SIGC_DOUBLE                = 'D';
+    String SIG_DOUBLE                 = "D";
+    char   SIGC_ARRAY                 = '[';
+    String SIG_ARRAY                  = "[";
+    char   SIGC_CLASS                 = 'L';
+    String SIG_CLASS                  = "L";
+    char   SIGC_METHOD                = '(';
+    String SIG_METHOD                 = "(";
+    char   SIGC_ENDCLASS              = ';';
+    String SIG_ENDCLASS               = ";";
+    char   SIGC_ENDMETHOD             = ')';
+    String SIG_ENDMETHOD              = ")";
+    char   SIGC_PACKAGE               = '/';
+    String SIG_PACKAGE                = "/";
+
+    /* Class File Constants */
+    int JAVA_MAGIC                   = 0xcafebabe;
+    int JAVA_MIN_SUPPORTED_VERSION   = 45;
+    int JAVA_MAX_SUPPORTED_VERSION   = 48;
+    int JAVA_MAX_SUPPORTED_MINOR_VERSION = 0;
+
+    /* Generate class file version for 1.1  by default */
+    int JAVA_DEFAULT_VERSION         = 45;
+    int JAVA_DEFAULT_MINOR_VERSION   = 3;
+
+    /* Constant table */
+    int CONSTANT_UTF8                = 1;
+    int CONSTANT_UNICODE             = 2;
+    int CONSTANT_INTEGER             = 3;
+    int CONSTANT_FLOAT               = 4;
+    int CONSTANT_LONG                = 5;
+    int CONSTANT_DOUBLE              = 6;
+    int CONSTANT_CLASS               = 7;
+    int CONSTANT_STRING              = 8;
+    int CONSTANT_FIELD               = 9;
+    int CONSTANT_METHOD              = 10;
+    int CONSTANT_INTERFACEMETHOD     = 11;
+    int CONSTANT_NAMEANDTYPE         = 12;
+
+    /* Access and modifier flags */
+    int ACC_PUBLIC                   = 0x00000001;
+    int ACC_PRIVATE                  = 0x00000002;
+    int ACC_PROTECTED                = 0x00000004;
+    int ACC_STATIC                   = 0x00000008;
+    int ACC_FINAL                    = 0x00000010;
+    int ACC_SYNCHRONIZED             = 0x00000020;
+    int ACC_VOLATILE                 = 0x00000040;
+    int ACC_TRANSIENT                = 0x00000080;
+    int ACC_NATIVE                   = 0x00000100;
+    int ACC_INTERFACE                = 0x00000200;
+    int ACC_ABSTRACT                 = 0x00000400;
+    int ACC_SUPER                    = 0x00000020;
+    int ACC_STRICT           = 0x00000800;
+
+    /* Type codes */
+    int T_CLASS                      = 0x00000002;
+    int T_BOOLEAN                    = 0x00000004;
+    int T_CHAR                       = 0x00000005;
+    int T_FLOAT                      = 0x00000006;
+    int T_DOUBLE                     = 0x00000007;
+    int T_BYTE                       = 0x00000008;
+    int T_SHORT                      = 0x00000009;
+    int T_INT                        = 0x0000000a;
+    int T_LONG                       = 0x0000000b;
+
+    /* Opcodes */
+    int opc_try                      = -3;
+    int opc_dead                     = -2;
+    int opc_label                    = -1;
+    int opc_nop                      = 0;
+    int opc_aconst_null              = 1;
+    int opc_iconst_m1                = 2;
+    int opc_iconst_0                 = 3;
+    int opc_iconst_1                 = 4;
+    int opc_iconst_2                 = 5;
+    int opc_iconst_3                 = 6;
+    int opc_iconst_4                 = 7;
+    int opc_iconst_5                 = 8;
+    int opc_lconst_0                 = 9;
+    int opc_lconst_1                 = 10;
+    int opc_fconst_0                 = 11;
+    int opc_fconst_1                 = 12;
+    int opc_fconst_2                 = 13;
+    int opc_dconst_0                 = 14;
+    int opc_dconst_1                 = 15;
+    int opc_bipush                   = 16;
+    int opc_sipush                   = 17;
+    int opc_ldc                      = 18;
+    int opc_ldc_w                    = 19;
+    int opc_ldc2_w                   = 20;
+    int opc_iload                    = 21;
+    int opc_lload                    = 22;
+    int opc_fload                    = 23;
+    int opc_dload                    = 24;
+    int opc_aload                    = 25;
+    int opc_iload_0                  = 26;
+    int opc_iload_1                  = 27;
+    int opc_iload_2                  = 28;
+    int opc_iload_3                  = 29;
+    int opc_lload_0                  = 30;
+    int opc_lload_1                  = 31;
+    int opc_lload_2                  = 32;
+    int opc_lload_3                  = 33;
+    int opc_fload_0                  = 34;
+    int opc_fload_1                  = 35;
+    int opc_fload_2                  = 36;
+    int opc_fload_3                  = 37;
+    int opc_dload_0                  = 38;
+    int opc_dload_1                  = 39;
+    int opc_dload_2                  = 40;
+    int opc_dload_3                  = 41;
+    int opc_aload_0                  = 42;
+    int opc_aload_1                  = 43;
+    int opc_aload_2                  = 44;
+    int opc_aload_3                  = 45;
+    int opc_iaload                   = 46;
+    int opc_laload                   = 47;
+    int opc_faload                   = 48;
+    int opc_daload                   = 49;
+    int opc_aaload                   = 50;
+    int opc_baload                   = 51;
+    int opc_caload                   = 52;
+    int opc_saload                   = 53;
+    int opc_istore                   = 54;
+    int opc_lstore                   = 55;
+    int opc_fstore                   = 56;
+    int opc_dstore                   = 57;
+    int opc_astore                   = 58;
+    int opc_istore_0                 = 59;
+    int opc_istore_1                 = 60;
+    int opc_istore_2                 = 61;
+    int opc_istore_3                 = 62;
+    int opc_lstore_0                 = 63;
+    int opc_lstore_1                 = 64;
+    int opc_lstore_2                 = 65;
+    int opc_lstore_3                 = 66;
+    int opc_fstore_0                 = 67;
+    int opc_fstore_1                 = 68;
+    int opc_fstore_2                 = 69;
+    int opc_fstore_3                 = 70;
+    int opc_dstore_0                 = 71;
+    int opc_dstore_1                 = 72;
+    int opc_dstore_2                 = 73;
+    int opc_dstore_3                 = 74;
+    int opc_astore_0                 = 75;
+    int opc_astore_1                 = 76;
+    int opc_astore_2                 = 77;
+    int opc_astore_3                 = 78;
+    int opc_iastore                  = 79;
+    int opc_lastore                  = 80;
+    int opc_fastore                  = 81;
+    int opc_dastore                  = 82;
+    int opc_aastore                  = 83;
+    int opc_bastore                  = 84;
+    int opc_castore                  = 85;
+    int opc_sastore                  = 86;
+    int opc_pop                      = 87;
+    int opc_pop2                     = 88;
+    int opc_dup                      = 89;
+    int opc_dup_x1                   = 90;
+    int opc_dup_x2                   = 91;
+    int opc_dup2                     = 92;
+    int opc_dup2_x1                  = 93;
+    int opc_dup2_x2                  = 94;
+    int opc_swap                     = 95;
+    int opc_iadd                     = 96;
+    int opc_ladd                     = 97;
+    int opc_fadd                     = 98;
+    int opc_dadd                     = 99;
+    int opc_isub                     = 100;
+    int opc_lsub                     = 101;
+    int opc_fsub                     = 102;
+    int opc_dsub                     = 103;
+    int opc_imul                     = 104;
+    int opc_lmul                     = 105;
+    int opc_fmul                     = 106;
+    int opc_dmul                     = 107;
+    int opc_idiv                     = 108;
+    int opc_ldiv                     = 109;
+    int opc_fdiv                     = 110;
+    int opc_ddiv                     = 111;
+    int opc_irem                     = 112;
+    int opc_lrem                     = 113;
+    int opc_frem                     = 114;
+    int opc_drem                     = 115;
+    int opc_ineg                     = 116;
+    int opc_lneg                     = 117;
+    int opc_fneg                     = 118;
+    int opc_dneg                     = 119;
+    int opc_ishl                     = 120;
+    int opc_lshl                     = 121;
+    int opc_ishr                     = 122;
+    int opc_lshr                     = 123;
+    int opc_iushr                    = 124;
+    int opc_lushr                    = 125;
+    int opc_iand                     = 126;
+    int opc_land                     = 127;
+    int opc_ior                      = 128;
+    int opc_lor                      = 129;
+    int opc_ixor                     = 130;
+    int opc_lxor                     = 131;
+    int opc_iinc                     = 132;
+    int opc_i2l                      = 133;
+    int opc_i2f                      = 134;
+    int opc_i2d                      = 135;
+    int opc_l2i                      = 136;
+    int opc_l2f                      = 137;
+    int opc_l2d                      = 138;
+    int opc_f2i                      = 139;
+    int opc_f2l                      = 140;
+    int opc_f2d                      = 141;
+    int opc_d2i                      = 142;
+    int opc_d2l                      = 143;
+    int opc_d2f                      = 144;
+    int opc_i2b                      = 145;
+    int opc_i2c                      = 146;
+    int opc_i2s                      = 147;
+    int opc_lcmp                     = 148;
+    int opc_fcmpl                    = 149;
+    int opc_fcmpg                    = 150;
+    int opc_dcmpl                    = 151;
+    int opc_dcmpg                    = 152;
+    int opc_ifeq                     = 153;
+    int opc_ifne                     = 154;
+    int opc_iflt                     = 155;
+    int opc_ifge                     = 156;
+    int opc_ifgt                     = 157;
+    int opc_ifle                     = 158;
+    int opc_if_icmpeq                = 159;
+    int opc_if_icmpne                = 160;
+    int opc_if_icmplt                = 161;
+    int opc_if_icmpge                = 162;
+    int opc_if_icmpgt                = 163;
+    int opc_if_icmple                = 164;
+    int opc_if_acmpeq                = 165;
+    int opc_if_acmpne                = 166;
+    int opc_goto                     = 167;
+    int opc_jsr                      = 168;
+    int opc_ret                      = 169;
+    int opc_tableswitch              = 170;
+    int opc_lookupswitch             = 171;
+    int opc_ireturn                  = 172;
+    int opc_lreturn                  = 173;
+    int opc_freturn                  = 174;
+    int opc_dreturn                  = 175;
+    int opc_areturn                  = 176;
+    int opc_return                   = 177;
+    int opc_getstatic                = 178;
+    int opc_putstatic                = 179;
+    int opc_getfield                 = 180;
+    int opc_putfield                 = 181;
+    int opc_invokevirtual            = 182;
+    int opc_invokespecial            = 183;
+    int opc_invokestatic             = 184;
+    int opc_invokeinterface          = 185;
+    int opc_xxxunusedxxx             = 186;
+    int opc_new                      = 187;
+    int opc_newarray                 = 188;
+    int opc_anewarray                = 189;
+    int opc_arraylength              = 190;
+    int opc_athrow                   = 191;
+    int opc_checkcast                = 192;
+    int opc_instanceof               = 193;
+    int opc_monitorenter             = 194;
+    int opc_monitorexit              = 195;
+    int opc_wide                     = 196;
+    int opc_multianewarray           = 197;
+    int opc_ifnull                   = 198;
+    int opc_ifnonnull                = 199;
+    int opc_goto_w                   = 200;
+    int opc_jsr_w                    = 201;
+    int opc_breakpoint               = 202;
+
+    /* Opcode Names */
+    String opcNames[] = {
+    "nop",
+    "aconst_null",
+    "iconst_m1",
+    "iconst_0",
+    "iconst_1",
+    "iconst_2",
+    "iconst_3",
+    "iconst_4",
+    "iconst_5",
+    "lconst_0",
+    "lconst_1",
+    "fconst_0",
+    "fconst_1",
+    "fconst_2",
+    "dconst_0",
+    "dconst_1",
+    "bipush",
+    "sipush",
+    "ldc",
+    "ldc_w",
+    "ldc2_w",
+    "iload",
+    "lload",
+    "fload",
+    "dload",
+    "aload",
+    "iload_0",
+    "iload_1",
+    "iload_2",
+    "iload_3",
+    "lload_0",
+    "lload_1",
+    "lload_2",
+    "lload_3",
+    "fload_0",
+    "fload_1",
+    "fload_2",
+    "fload_3",
+    "dload_0",
+    "dload_1",
+    "dload_2",
+    "dload_3",
+    "aload_0",
+    "aload_1",
+    "aload_2",
+    "aload_3",
+    "iaload",
+    "laload",
+    "faload",
+    "daload",
+    "aaload",
+    "baload",
+    "caload",
+    "saload",
+    "istore",
+    "lstore",
+    "fstore",
+    "dstore",
+    "astore",
+    "istore_0",
+    "istore_1",
+    "istore_2",
+    "istore_3",
+    "lstore_0",
+    "lstore_1",
+    "lstore_2",
+    "lstore_3",
+    "fstore_0",
+    "fstore_1",
+    "fstore_2",
+    "fstore_3",
+    "dstore_0",
+    "dstore_1",
+    "dstore_2",
+    "dstore_3",
+    "astore_0",
+    "astore_1",
+    "astore_2",
+    "astore_3",
+    "iastore",
+    "lastore",
+    "fastore",
+    "dastore",
+    "aastore",
+    "bastore",
+    "castore",
+    "sastore",
+    "pop",
+    "pop2",
+    "dup",
+    "dup_x1",
+    "dup_x2",
+    "dup2",
+    "dup2_x1",
+    "dup2_x2",
+    "swap",
+    "iadd",
+    "ladd",
+    "fadd",
+    "dadd",
+    "isub",
+    "lsub",
+    "fsub",
+    "dsub",
+    "imul",
+    "lmul",
+    "fmul",
+    "dmul",
+    "idiv",
+    "ldiv",
+    "fdiv",
+    "ddiv",
+    "irem",
+    "lrem",
+    "frem",
+    "drem",
+    "ineg",
+    "lneg",
+    "fneg",
+    "dneg",
+    "ishl",
+    "lshl",
+    "ishr",
+    "lshr",
+    "iushr",
+    "lushr",
+    "iand",
+    "land",
+    "ior",
+    "lor",
+    "ixor",
+    "lxor",
+    "iinc",
+    "i2l",
+    "i2f",
+    "i2d",
+    "l2i",
+    "l2f",
+    "l2d",
+    "f2i",
+    "f2l",
+    "f2d",
+    "d2i",
+    "d2l",
+    "d2f",
+    "i2b",
+    "i2c",
+    "i2s",
+    "lcmp",
+    "fcmpl",
+    "fcmpg",
+    "dcmpl",
+    "dcmpg",
+    "ifeq",
+    "ifne",
+    "iflt",
+    "ifge",
+    "ifgt",
+    "ifle",
+    "if_icmpeq",
+    "if_icmpne",
+    "if_icmplt",
+    "if_icmpge",
+    "if_icmpgt",
+    "if_icmple",
+    "if_acmpeq",
+    "if_acmpne",
+    "goto",
+    "jsr",
+    "ret",
+    "tableswitch",
+    "lookupswitch",
+    "ireturn",
+    "lreturn",
+    "freturn",
+    "dreturn",
+    "areturn",
+    "return",
+    "getstatic",
+    "putstatic",
+    "getfield",
+    "putfield",
+    "invokevirtual",
+    "invokespecial",
+    "invokestatic",
+    "invokeinterface",
+    "xxxunusedxxx",
+    "new",
+    "newarray",
+    "anewarray",
+    "arraylength",
+    "athrow",
+    "checkcast",
+    "instanceof",
+    "monitorenter",
+    "monitorexit",
+    "wide",
+    "multianewarray",
+    "ifnull",
+    "ifnonnull",
+    "goto_w",
+    "jsr_w",
+    "breakpoint"
+    };
+
+    /* Opcode Lengths */
+    int opcLengths[] = {
+    1,
+    1,
+    1,
+    1,
+    1,
+    1,
+    1,
+    1,
+    1,
+    1,
+    1,
+    1,
+    1,
+    1,
+    1,
+    1,
+    2,
+    3,
+    2,
+    3,
+    3,
+    2,
+    2,
+    2,
+    2,
+    2,
+    1,
+    1,
+    1,
+    1,
+    1,
+    1,
+    1,
+    1,
+    1,
+    1,
+    1,
+    1,
+    1,
+    1,
+    1,
+    1,
+    1,
+    1,
+    1,
+    1,
+    1,
+    1,
+    1,
+    1,
+    1,
+    1,
+    1,
+    1,
+    2,
+    2,
+    2,
+    2,
+    2,
+    1,
+    1,
+    1,
+    1,
+    1,
+    1,
+    1,
+    1,
+    1,
+    1,
+    1,
+    1,
+    1,
+    1,
+    1,
+    1,
+    1,
+    1,
+    1,
+    1,
+    1,
+    1,
+    1,
+    1,
+    1,
+    1,
+    1,
+    1,
+    1,
+    1,
+    1,
+    1,
+    1,
+    1,
+    1,
+    1,
+    1,
+    1,
+    1,
+    1,
+    1,
+    1,
+    1,
+    1,
+    1,
+    1,
+    1,
+    1,
+    1,
+    1,
+    1,
+    1,
+    1,
+    1,
+    1,
+    1,
+    1,
+    1,
+    1,
+    1,
+    1,
+    1,
+    1,
+    1,
+    1,
+    1,
+    1,
+    1,
+    1,
+    1,
+    1,
+    1,
+    1,
+    3,
+    1,
+    1,
+    1,
+    1,
+    1,
+    1,
+    1,
+    1,
+    1,
+    1,
+    1,
+    1,
+    1,
+    1,
+    1,
+    1,
+    1,
+    1,
+    1,
+    1,
+    3,
+    3,
+    3,
+    3,
+    3,
+    3,
+    3,
+    3,
+    3,
+    3,
+    3,
+    3,
+    3,
+    3,
+    3,
+    3,
+    2,
+    99,
+    99,
+    1,
+    1,
+    1,
+    1,
+    1,
+    1,
+    3,
+    3,
+    3,
+    3,
+    3,
+    3,
+    3,
+    5,
+    0,
+    3,
+    2,
+    3,
+    1,
+    1,
+    3,
+    3,
+    1,
+    1,
+    0,
+    4,
+    3,
+    3,
+    5,
+    5,
+    1
+    };
+
+}
diff --git a/jdk/test/java/lang/instrument/SimpleIdentityTransformer.java b/jdk/test/java/lang/instrument/SimpleIdentityTransformer.java
new file mode 100644
index 0000000..af582db
--- /dev/null
+++ b/jdk/test/java/lang/instrument/SimpleIdentityTransformer.java
@@ -0,0 +1,62 @@
+/*
+ * Copyright 2003-2004 Sun Microsystems, Inc.  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 Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
+ * CA 95054 USA or visit www.sun.com if you need additional information or
+ * have any questions.
+ */
+
+import java.lang.instrument.Instrumentation;
+import java.lang.instrument.ClassFileTransformer;
+
+import java.security.*;
+
+/*
+ * Copyright 2003 Wily Technology, Inc.
+ */
+
+/**
+ * ClassFileTransformer implementation that returns a copy of its input
+ */
+public class
+SimpleIdentityTransformer implements ClassFileTransformer {
+
+    /**
+     * Constructor for SimpleIdentityTransform.
+     */
+    public SimpleIdentityTransformer() {
+        super();
+    }
+
+    /**
+     *
+     */
+    public byte[]
+    transform(
+        ClassLoader loader,
+        String className,
+        Class<?> classBeingRedefined,
+        ProtectionDomain    protectionDomain,
+        byte[] classfileBuffer) {
+        byte[] newBuffer = new byte[classfileBuffer.length];
+        System.arraycopy(classfileBuffer, 0, newBuffer, 0, classfileBuffer.length);
+
+        return newBuffer;
+    }
+
+}
diff --git a/jdk/test/java/lang/instrument/SingleTransformerTest.java b/jdk/test/java/lang/instrument/SingleTransformerTest.java
new file mode 100644
index 0000000..a8e4114
--- /dev/null
+++ b/jdk/test/java/lang/instrument/SingleTransformerTest.java
@@ -0,0 +1,73 @@
+/*
+ * Copyright 2003-2005 Sun Microsystems, Inc.  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 Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
+ * CA 95054 USA or visit www.sun.com if you need additional information or
+ * have any questions.
+ */
+
+/**
+ * @test
+ * @bug 4882798
+ * @summary simple test with one transformer (makes sure it gets called)
+ * @author Gabriel Adauto, Wily Technology
+ *
+ * @run build SingleTransformerTest
+ * @run shell MakeJAR.sh redefineAgent
+ * @run main/othervm -javaagent:redefineAgent.jar SingleTransformerTest SingleTransformerTest
+ */
+public class
+SingleTransformerTest
+    extends ATransformerManagementTestCase
+{
+
+    /**
+     * Constructor for SingleTransformerTest.
+     * @param name
+     */
+    public SingleTransformerTest(String name)
+    {
+        super(name);
+    }
+
+    public static void
+    main (String[] args)
+        throws Throwable {
+        ATestCaseScaffold   test = new SingleTransformerTest(args[0]);
+        test.runTest();
+    }
+
+    protected final void
+    doRunTest()
+        throws Throwable {
+        beVerbose(); // We are seeing problems on this test -- print what is happenning
+        testOneTransformer();
+    }
+
+
+    /**
+     * Add and check just one transformer to the manager
+     */
+    public void
+    testOneTransformer()
+    {
+        addTransformerToManager(fInst, getRandomTransformer());
+        verifyTransformers(fInst);
+    }
+
+}
diff --git a/jdk/test/java/lang/instrument/TransformMethodTest.java b/jdk/test/java/lang/instrument/TransformMethodTest.java
new file mode 100644
index 0000000..329c072
--- /dev/null
+++ b/jdk/test/java/lang/instrument/TransformMethodTest.java
@@ -0,0 +1,78 @@
+/*
+ * Copyright 2003-2004 Sun Microsystems, Inc.  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 Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
+ * CA 95054 USA or visit www.sun.com if you need additional information or
+ * have any questions.
+ */
+
+/**
+ * @test
+ * @bug 4882798
+ * @summary test transformer add/remove pairs in sequence
+ * @author Gabriel Adauto, Wily Technology
+ *
+ * @run build TransformMethodTest
+ * @run shell MakeJAR.sh redefineAgent
+ * @run main/othervm -javaagent:redefineAgent.jar TransformMethodTest TransformMethodTest
+ */
+import java.lang.instrument.*;
+
+public class
+TransformMethodTest
+    extends ATransformerManagementTestCase
+{
+
+    /**
+     * Constructor for TransformMethodTest.
+     * @param name
+     */
+    public TransformMethodTest(String name)
+    {
+        super(name);
+    }
+
+    public static void
+    main (String[] args)
+        throws Throwable {
+        ATestCaseScaffold   test = new TransformMethodTest(args[0]);
+        test.runTest();
+    }
+
+    protected final void
+    doRunTest()
+        throws Throwable {
+        testTransform();
+    }
+
+    /**
+     * Verify that the transformers can be added and removed correctly
+     */
+    public void
+    testTransform()
+    {
+        for (int i = 0; i < kTransformerSamples.length; i++)
+        {
+            ClassFileTransformer transformer = getRandomTransformer();
+            addTransformerToManager(fInst, transformer);
+            verifyTransformers(fInst);
+            removeTransformerFromManager(fInst, transformer, true);
+        }
+    }
+
+}
diff --git a/jdk/test/java/lang/instrument/TransformerManagementThreadAddTests.java b/jdk/test/java/lang/instrument/TransformerManagementThreadAddTests.java
new file mode 100644
index 0000000..cc5a4b6
--- /dev/null
+++ b/jdk/test/java/lang/instrument/TransformerManagementThreadAddTests.java
@@ -0,0 +1,512 @@
+/*
+ * Copyright 2003-2004 Sun Microsystems, Inc.  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 Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
+ * CA 95054 USA or visit www.sun.com if you need additional information or
+ * have any questions.
+ */
+
+/**
+ * @test
+ * @bug 4882798
+ * @summary multi-thread test to exercise sync and contention for adds to transformer registry
+ * @author Gabriel Adauto, Wily Technology
+ *
+ * @run build TransformerManagementThreadAddTests
+ * @run shell MakeJAR.sh redefineAgent
+ * @run main/othervm -javaagent:redefineAgent.jar TransformerManagementThreadAddTests TransformerManagementThreadAddTests
+ */
+import java.io.*;
+import java.lang.instrument.*;
+import java.security.ProtectionDomain;
+import java.util.*;
+
+public class TransformerManagementThreadAddTests extends ATestCaseScaffold
+{
+    public static void
+    main (String[] args)
+        throws Throwable {
+        ATestCaseScaffold   test = new TransformerManagementThreadAddTests(args[0]);
+        test.runTest();
+    }
+
+    protected void
+    doRunTest()
+        throws Throwable {
+        testMultiThreadAdds();
+    }
+
+
+    /**
+     * CONFIGURATION FOR TEST
+     * ----------------------
+     * Set these variables to different values to test the object that
+     * manages the transformers.
+     *
+     * MIN_TRANS: the minimum number of transformers to add by a thread
+     * MAX_TRANS: the maximum number of transformers to add by a thread
+     *      There will be a total of MAX_TRANS-MIN_TRANS+1 threads created.
+     *      Each thread will add between MIN_TRANS and MAX_TRANS transformers
+     *      to the manager.
+     *
+     * REMOVE_THREADS: the number of threads to run that spend their time
+     *                  removing transformers
+     */
+    protected static final int MIN_TRANS = 33;
+    protected static final int MAX_TRANS = 45;
+    protected static final int REMOVE_THREADS = 5;
+
+    protected static final boolean LOG_TRANSFORMATIONS = false;
+
+    /**
+     * Field variables
+     */
+    protected static final int TOTAL_THREADS = MAX_TRANS - MIN_TRANS + 1;
+
+    private byte[]          fDummyClassBytes;
+    private Vector              fCheckedTransformers;
+    private Instrumentation fInstrumentation;
+    private int             fFinished;
+    private ExecuteTransformersThread fExec;
+
+    // Need to use this for synchronization in subclass
+    protected Vector            fAddedTransformers;
+    private String          fDummyClassName;
+
+    /**
+     * Constructor for TransformerManagementThreadAddTests.
+     * @param name  Name for the test
+     */
+    public TransformerManagementThreadAddTests(String name)
+    {
+        super(name);
+
+        fCheckedTransformers = new Vector();
+        fAddedTransformers = new Vector();
+
+        fDummyClassName = "DummyClass";
+        String resourceName = "DummyClass.class";
+        File f = new File(System.getProperty("test.classes", "."), resourceName);
+        System.out.println("Reading test class from " + f);
+        try
+        {
+            InputStream redefineStream = new FileInputStream(f);
+            fDummyClassBytes = NamedBuffer.loadBufferFromStream(redefineStream);
+        }
+        catch (IOException e)
+        {
+            fail("Could not load the class: "+resourceName);
+        }
+    }
+
+    public void
+    testMultiThreadAdds()
+    {
+        TransformerThread[] threads = new TransformerThread[TOTAL_THREADS];
+        for (int i = MIN_TRANS; i <= MAX_TRANS; i++)
+        {
+            int index = i - MIN_TRANS;
+            threads[index] = new TransformerThread("Trans"+prettyNum(index,2), i);
+        }
+
+        ExecuteTransformersThread exec = new ExecuteTransformersThread();
+        exec.start();
+        for (int i = threads.length - 1; i >= 0; i--)
+        {
+            threads[i].start();
+        }
+
+        while (!exec.fDone)
+        {
+            Thread.currentThread().yield();
+        }
+        assertTrue(finalCheck());
+
+        if (LOG_TRANSFORMATIONS) {
+            printTransformers();
+        }
+    }
+
+    /**
+     * Returns the Instrumentation.
+     * @return Instrumentation  the data type with JPLIS calls
+     */
+    public Instrumentation getInstrumentation()
+    {
+        return fInstrumentation;
+    }
+
+    /**
+     * Returns the execution thread
+     * @return ExecuteTransformersThread
+     */
+    protected ExecuteTransformersThread getExecThread()
+    {
+        return fExec;
+    }
+
+    /**
+     * Sets the execution thread
+     * @param exec The execution thread to set
+     */
+    protected void setExecThread(ExecuteTransformersThread exec)
+    {
+        this.fExec = exec;
+    }
+
+    protected synchronized void
+    threadFinished(Thread t)
+    {
+        fFinished++;
+    }
+
+    protected boolean
+    threadsDone()
+    {
+        return fFinished == TOTAL_THREADS;
+    }
+
+    /**
+     * Method testCompleted.
+     * @return boolean
+     */
+    protected boolean
+    testCompleted()
+    {
+        return getExecThread().fDone;
+    }
+
+    /**
+     *
+     */
+    protected boolean
+    finalCheck()
+    {
+        if (LOG_TRANSFORMATIONS) {
+            // log the list
+            for (int x = 0; x < fCheckedTransformers.size(); x++ ) {
+                System.out.println(x + "\t\t" + fCheckedTransformers.get(x));
+            }
+            System.out.println();
+            System.out.println();
+
+            // check for multiples
+            for (int x = 0; x < fCheckedTransformers.size(); x++ ) {
+                Object current = fCheckedTransformers.get(x);
+                for ( int y = x + 1; y < fCheckedTransformers.size(); y++) {
+                    Object running = fCheckedTransformers.get(y);
+                    if ( current.equals(running) ) {
+                        System.out.println(x + "\t" + y + " \t" + "FOUND DUPLICATE: " + current);
+                    }
+                }
+            }
+        }
+
+        for (int j = 1; j < fCheckedTransformers.size(); j++) {
+            ThreadTransformer transformer = (ThreadTransformer)fCheckedTransformers.get(j);
+            for (int i = 0; i < j; i++) {
+                ThreadTransformer currTrans = (ThreadTransformer)fCheckedTransformers.get(i);
+                assertTrue(currTrans + " incorrectly appeared before " +
+                           transformer + " i=" + i + " j=" + j + " size=" +
+                           fCheckedTransformers.size(),
+                           !(
+                             currTrans.getThread().equals(transformer.getThread()) &&
+                             currTrans.getIndex() > transformer.getIndex()));
+            }
+        }
+        return true;
+    }
+
+    /**
+     *
+     */
+    protected void
+    setUp()
+        throws Exception
+    {
+        super.setUp();
+
+        fFinished = 0;
+        assertTrue(MIN_TRANS < MAX_TRANS);
+        fInstrumentation = InstrumentationHandoff.getInstrumentationOrThrow();
+    }
+
+    /**
+     *
+     */
+    protected void
+    tearDown()
+        throws Exception
+    {
+        super.tearDown();
+    }
+
+
+
+    /**
+     * Method executeTransform.
+     */
+    private void
+    executeTransform()
+    {
+        fCheckedTransformers.clear();
+
+        try
+        {
+            ClassDefinition cd = new ClassDefinition(DummyClass.class, fDummyClassBytes);
+            getInstrumentation().redefineClasses(new ClassDefinition[]{ cd });
+        }
+        catch (ClassNotFoundException e)
+        {
+            fail("Could not find the class: "+DummyClass.class.getName());
+        }
+        catch (UnmodifiableClassException e)
+        {
+            fail("Could not modify the class: "+DummyClass.class.getName());
+        }
+    }
+
+    /**
+     * Method addTransformerToManager.
+     * @param threadTransformer
+     */
+    private void
+    addTransformerToManager(ThreadTransformer threadTransformer)
+    {
+        getInstrumentation().addTransformer(threadTransformer);
+        fAddedTransformers.add(threadTransformer);
+    }
+
+    /**
+     * Method checkInTransformer.
+     * @param myClassFileTransformer
+     */
+    private void
+    checkInTransformer(ThreadTransformer transformer)
+    {
+        fCheckedTransformers.add(transformer);
+    }
+
+    /**
+     * Method createTransformer.
+     * @param transformerThread
+     * @param i
+     * @return ThreadTransformer
+     */
+    private ThreadTransformer
+    createTransformer(TransformerThread thread, int index)
+    {
+        ThreadTransformer tt = null;
+
+        tt = new ThreadTransformer(thread, index);
+
+        return tt;
+    }
+
+
+    protected class
+    ExecuteTransformersThread
+        extends Thread
+    {
+        private boolean fDone = false;
+
+        public void
+        run()
+        {
+            while(!threadsDone())
+            {
+                executeTransform();
+            }
+
+            // Do a final check for good measure
+            executeTransform();
+            fDone = true;
+        }
+    }
+
+
+    protected class
+    TransformerThread
+        extends Thread
+    {
+        private final ThreadTransformer[] fThreadTransformers;
+
+        TransformerThread(String name, int numTransformers)
+        {
+            super(name);
+
+            fThreadTransformers = makeTransformers(numTransformers);
+        }
+
+        /**
+         * Method makeTransformers.
+         * @param numTransformers
+         * @return ThreadTransformer[]
+         */
+        private ThreadTransformer[]
+        makeTransformers(int numTransformers)
+        {
+            ThreadTransformer[] trans = new ThreadTransformer[numTransformers];
+
+            for (int i = 0; i < trans.length; i++)
+            {
+                trans[i] = createTransformer(TransformerThread.this, i);
+            }
+
+            return trans;
+        }
+
+        public void
+        run()
+        {
+            for (int i = 0; i < fThreadTransformers.length; i++)
+            {
+                addTransformerToManager(fThreadTransformers[i]);
+            }
+            threadFinished(TransformerThread.this);
+        }
+    }
+
+    /**
+     * ClassFileTransformer implementation that knows its thread
+     */
+    protected class
+    ThreadTransformer extends SimpleIdentityTransformer
+    {
+        private final String    fName;
+        private final int       fIndex;
+        private final Thread    fThread;
+
+        /**
+         * Constructor for ThreadTransformer.
+         */
+        public ThreadTransformer(Thread thread, int index) {
+            super();
+            fThread = thread;
+            fIndex = index;
+            fName = "TT["+fThread.getName()+"]["+prettyNum(fIndex,3)+"]";
+        }
+
+        public String toString()
+        {
+            return fName;
+        }
+
+        /**
+         *
+         */
+        public byte[]
+        transform(
+            ClassLoader loader,
+            String className,
+            Class<?> classBeingRedefined,
+            ProtectionDomain domain,
+            byte[] classfileBuffer)
+        {
+            if ( className.equals(TransformerManagementThreadAddTests.this.fDummyClassName) ) {
+                checkInTransformer(ThreadTransformer.this);
+            }
+            return super.transform(    loader,
+                                        className,
+                                        classBeingRedefined,
+                                        domain,
+                                        classfileBuffer);
+        }
+
+        /**
+         * Returns the index.
+         * @return int
+         */
+        public int getIndex()
+        {
+            return fIndex;
+        }
+
+        /**
+         * Returns the thread.
+         * @return Thread
+         */
+        public Thread getThread()
+        {
+            return fThread;
+        }
+
+    }
+
+    /**
+     * DEBUG STUFF
+     */
+    private int NUM_SWITCHES;
+
+    /**
+     * Method printTransformers.
+     */
+    protected void printTransformers()
+    {
+        NUM_SWITCHES = 0;
+        Iterator trans = fCheckedTransformers.iterator();
+        ThreadTransformer old = null;
+        StringBuffer buf = new StringBuffer();
+
+        for (int i = 1; trans.hasNext(); i++)
+        {
+            ThreadTransformer t = (ThreadTransformer)trans.next();
+            buf.append(t.toString());
+            if (old != null)
+            {
+                if (!old.getThread().equals(t.getThread()))
+                {
+                    NUM_SWITCHES++;
+                    buf.append("*");
+                }
+                else
+                { buf.append(" "); }
+            }
+            else
+            { buf.append(" "); }
+
+            if (i % 5 == 0)
+            {
+                buf.append("\n");
+            }
+            else
+            { buf.append(" "); }
+
+            old = t;
+        }
+        System.out.println(buf);
+        System.out.println("\nNumber of transitions from one thread to another: "+NUM_SWITCHES);
+    }
+
+    protected String
+    prettyNum(int n, int numSize)
+    {
+        StringBuffer num = new StringBuffer(Integer.toString(n));
+        int size = num.length();
+        for (int i = 0; i < numSize - size; i++)
+        {
+            num.insert(0, "0");
+        }
+
+        return num.toString();
+    }
+    /**
+     * END DEBUG STUFF
+     */
+
+}
diff --git a/jdk/test/java/lang/instrument/TransformerManagementThreadRemoveTests.java b/jdk/test/java/lang/instrument/TransformerManagementThreadRemoveTests.java
new file mode 100644
index 0000000..2836bde
--- /dev/null
+++ b/jdk/test/java/lang/instrument/TransformerManagementThreadRemoveTests.java
@@ -0,0 +1,142 @@
+/*
+ * Copyright 2003-2004 Sun Microsystems, Inc.  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 Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
+ * CA 95054 USA or visit www.sun.com if you need additional information or
+ * have any questions.
+ */
+
+/**
+ * @test
+ * @bug 4882798
+ * @summary multi-thread test to exercise sync and contention for removes to transformer registry
+ * @author Gabriel Adauto, Wily Technology
+ *
+ * @ignore Disabled until race condition which hangs test can be fixed.
+ * @run build TransformerManagementThreadRemoveTests
+ * @run shell MakeJAR.sh basicAgent
+ * @run main/othervm -javaagent:basicAgent.jar TransformerManagementThreadRemoveTests TransformerManagementThreadRemoveTests
+ */
+import java.util.*;
+
+public class TransformerManagementThreadRemoveTests
+    extends TransformerManagementThreadAddTests
+{
+
+    /**
+     * Constructor for TransformerManagementThreadRemoveTests.
+     * @param name
+     */
+    public TransformerManagementThreadRemoveTests(String name)
+    {
+        super(name);
+    }
+
+    public static void
+    main (String[] args)
+        throws Throwable {
+        ATestCaseScaffold   test = new TransformerManagementThreadRemoveTests(args[0]);
+        test.runTest();
+    }
+
+    protected final void
+    doRunTest()
+        throws Throwable {
+        testMultiThreadAddsAndRemoves();
+    }
+
+    public void
+    testMultiThreadAddsAndRemoves()
+    {
+        int size = TOTAL_THREADS + REMOVE_THREADS;
+        ArrayList threadList = new ArrayList(size);
+        for (int i = MIN_TRANS; i <= MAX_TRANS; i++)
+        {
+            int index = i - MIN_TRANS;
+            threadList.add(new TransformerThread("Trans"+prettyNum(index,2), i));
+        }
+
+        int factor = (int)Math.floor(TOTAL_THREADS / REMOVE_THREADS);
+        for (int i = 0; i < REMOVE_THREADS; i++)
+        {
+            threadList.add(factor * i, new RemoveThread("Remove"+i));
+        }
+
+        Thread[] threads = (Thread[])threadList.toArray(new Thread[size]);
+        setExecThread(new ExecuteTransformersThread());
+        getExecThread().start();
+        for (int i = threads.length - 1; i >= 0; i--)
+        {
+            threads[i].start();
+        }
+
+        while (!testCompleted())
+        {
+            Thread.currentThread().yield();
+        }
+        assertTrue(finalCheck());
+
+        //printTransformers();
+    }
+
+    /**
+     * Method removeTransformer.
+     */
+    private void
+    removeTransformer(Thread t)
+    {
+        ThreadTransformer tt = null;
+
+        synchronized (fAddedTransformers)
+        {
+            int size = fAddedTransformers.size();
+            if (size > 0)
+            {
+                int choose = (int)Math.floor(Math.random() * size);
+                tt = (ThreadTransformer)fAddedTransformers.remove(choose);
+            }
+            //System.out.println("removed("+tt+") size("+size+") chose("+choose+") by("+t+")");
+        }
+
+        if (tt != null)
+        {
+            getInstrumentation().removeTransformer(tt);
+        }
+    }
+
+    private class
+    RemoveThread
+        extends Thread
+    {
+
+        RemoveThread(String name)
+        {
+            super(name);
+        }
+
+        public void
+        run()
+        {
+            while (!threadsDone())
+            {
+                removeTransformer(RemoveThread.this);
+            }
+        }
+    }
+
+}
diff --git a/jdk/test/java/lang/instrument/appendToClassLoaderSearch/A.1 b/jdk/test/java/lang/instrument/appendToClassLoaderSearch/A.1
new file mode 100644
index 0000000..8080947
--- /dev/null
+++ b/jdk/test/java/lang/instrument/appendToClassLoaderSearch/A.1
@@ -0,0 +1,9 @@
+/*
+ *%E
+ *
+ * Simple "no-op" class used by CircularityErrorTest.sh to create a circularity
+ * condition.
+ *
+ */
+public interface A {
+}
diff --git a/jdk/test/java/lang/instrument/appendToClassLoaderSearch/A.2 b/jdk/test/java/lang/instrument/appendToClassLoaderSearch/A.2
new file mode 100644
index 0000000..1cf48e3
--- /dev/null
+++ b/jdk/test/java/lang/instrument/appendToClassLoaderSearch/A.2
@@ -0,0 +1,9 @@
+/*
+ *%E
+ *
+ * Simple "no-op" class used by CircularityErrorTest.sh to create a circularity
+ * condition.
+ *
+ */
+public interface A extends B {
+}
diff --git a/jdk/test/java/lang/instrument/appendToClassLoaderSearch/Agent.java b/jdk/test/java/lang/instrument/appendToClassLoaderSearch/Agent.java
new file mode 100644
index 0000000..72f4be2
--- /dev/null
+++ b/jdk/test/java/lang/instrument/appendToClassLoaderSearch/Agent.java
@@ -0,0 +1,45 @@
+/*
+ * Copyright 2005 Sun Microsystems, Inc.  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 Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
+ * CA 95054 USA or visit www.sun.com if you need additional information or
+ * have any questions.
+ */
+
+/*
+ *
+ *
+ * Used by run_tests.sh
+ *
+ * Simple agent that makes Instrumentation instance available to other classes.
+ */
+import java.lang.instrument.Instrumentation;
+
+public class Agent {
+
+    static Instrumentation inst;
+
+    public static void premain(String args, Instrumentation ins) {
+        inst = ins;
+    }
+
+    public static Instrumentation getInstrumentation() {
+        return inst;
+    }
+
+}
diff --git a/jdk/test/java/lang/instrument/appendToClassLoaderSearch/AgentSupport.java b/jdk/test/java/lang/instrument/appendToClassLoaderSearch/AgentSupport.java
new file mode 100644
index 0000000..faba2d7
--- /dev/null
+++ b/jdk/test/java/lang/instrument/appendToClassLoaderSearch/AgentSupport.java
@@ -0,0 +1,32 @@
+/*
+ * Copyright 2005 Sun Microsystems, Inc.  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 Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
+ * CA 95054 USA or visit www.sun.com if you need additional information or
+ * have any questions.
+ */
+
+/*
+ *
+ *
+ * Used by run_tests.sh
+ *
+ * An agent "supporting" class that will be loaded by the system class loader.
+ */
+public class AgentSupport {
+}
diff --git a/jdk/test/java/lang/instrument/appendToClassLoaderSearch/Application.java b/jdk/test/java/lang/instrument/appendToClassLoaderSearch/Application.java
new file mode 100644
index 0000000..69ad37b
--- /dev/null
+++ b/jdk/test/java/lang/instrument/appendToClassLoaderSearch/Application.java
@@ -0,0 +1,36 @@
+/*
+ * Copyright 2005 Sun Microsystems, Inc.  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 Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
+ * CA 95054 USA or visit www.sun.com if you need additional information or
+ * have any questions.
+ */
+
+/*
+ *
+ *
+ * Used by DynamicTest - simple Application with one method that returns the
+ * number of messages printed.
+ */
+public class Application {
+
+    public int doSomething() {
+        System.out.println("Bring us up to warp speed!");
+        return 1;
+    }
+}
diff --git a/jdk/test/java/lang/instrument/appendToClassLoaderSearch/B.1 b/jdk/test/java/lang/instrument/appendToClassLoaderSearch/B.1
new file mode 100644
index 0000000..615c55e
--- /dev/null
+++ b/jdk/test/java/lang/instrument/appendToClassLoaderSearch/B.1
@@ -0,0 +1,9 @@
+/*
+ *%E
+ *
+ * Simple "no-op" class used by CircularityErrorTest.sh to create a circularity
+ * condition.
+ *
+ */
+public interface B extends A {
+}
diff --git a/jdk/test/java/lang/instrument/appendToClassLoaderSearch/B.2 b/jdk/test/java/lang/instrument/appendToClassLoaderSearch/B.2
new file mode 100644
index 0000000..65f79a2
--- /dev/null
+++ b/jdk/test/java/lang/instrument/appendToClassLoaderSearch/B.2
@@ -0,0 +1,9 @@
+/*
+ *%E
+ *
+ * Simple "no-op" class used by CircularityErrorTest.sh to create a circularity
+ * condition.
+ *
+ */
+public interface B {
+}
diff --git a/jdk/test/java/lang/instrument/appendToClassLoaderSearch/BasicTest.java b/jdk/test/java/lang/instrument/appendToClassLoaderSearch/BasicTest.java
new file mode 100644
index 0000000..7b4969e
--- /dev/null
+++ b/jdk/test/java/lang/instrument/appendToClassLoaderSearch/BasicTest.java
@@ -0,0 +1,90 @@
+/*
+ * Copyright 2005 Sun Microsystems, Inc.  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 Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
+ * CA 95054 USA or visit www.sun.com if you need additional information or
+ * have any questions.
+ */
+
+/*
+ *
+ *
+ * Basic unit test for Instrumentation appendToBootstrapClassLoaderSearch and
+ * appendToSystemClassLoaderSearch methods:
+ *
+ * 1. Adds a jar file to the bootstrap class loader search; Loads a class known
+ *    to be in the jar file and checks that it was loaded by the bootstrap class
+ *    loader.
+ *
+ * 2. Adds a jar file to the system class loader search; Loads a class known
+ *    to be in the jar file and checks that it was indeed loaded by the system
+ *    class loader.
+ */
+import java.lang.instrument.Instrumentation;
+import java.util.jar.JarFile;
+import java.io.IOException;
+
+public class BasicTest {
+
+    // count of failures
+    static int failures = 0;
+
+    // check that the given class is loaded by the given loader
+    static void checkLoadedByLoader(String name, ClassLoader loader) {
+        try {
+            Class cl = Class.forName(name);
+            ClassLoader actual = cl.getClassLoader();
+            String loaderName = (actual == null) ? "boot class loader" : actual.toString();
+            if (actual != loader) {
+                System.out.println("FAIL: " + name + " incorrectly loaded by: " + loaderName);
+                failures++;
+            } else {
+                System.out.println("PASS: " + name + " loaded by: " + loaderName);
+            }
+        } catch (Exception x) {
+            System.out.println("FAIL: Unable to load " + name + ":" + x);
+            failures++;
+        }
+    }
+
+    public static void main(String args[]) throws IOException {
+        JarFile bootclasses = new JarFile("BootSupport.jar");
+        JarFile agentclasses = new JarFile("AgentSupport.jar");
+
+        Instrumentation ins = Agent.getInstrumentation();
+
+        // Test 1: Add BootSupport.jar to boot class path and check that
+        // BootSupport is loaded by the bootstrap class loader
+        ins.appendToBootstrapClassLoaderSearch(bootclasses);
+        checkLoadedByLoader("BootSupport", null);
+
+        // Test 2: Add AgentSupport.jar to the system class path and check that
+        // AgentSupport is loaded by the system class loader.
+        try {
+            ins.appendToSystemClassLoaderSearch(agentclasses);
+            checkLoadedByLoader("AgentSupport", ClassLoader.getSystemClassLoader());
+        } catch (UnsupportedOperationException x) {
+            System.out.println("System class loader does not support adding to class path");
+        }
+
+        // throw exception if a test failed
+        if (failures > 0) {
+            throw new RuntimeException(failures + " test(s) failed.");
+        }
+    }
+}
diff --git a/jdk/test/java/lang/instrument/appendToClassLoaderSearch/BootSupport.java b/jdk/test/java/lang/instrument/appendToClassLoaderSearch/BootSupport.java
new file mode 100644
index 0000000..6c59d1b
--- /dev/null
+++ b/jdk/test/java/lang/instrument/appendToClassLoaderSearch/BootSupport.java
@@ -0,0 +1,32 @@
+/*
+ * Copyright 2005 Sun Microsystems, Inc.  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 Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
+ * CA 95054 USA or visit www.sun.com if you need additional information or
+ * have any questions.
+ */
+
+/*
+ *
+ *
+ * Used by run_tests.sh
+ *
+ * An agent "supporting" class that will be loaded by the bootstrap class loader.
+ */
+public class BootSupport {
+}
diff --git a/jdk/test/java/lang/instrument/appendToClassLoaderSearch/CircularityErrorTest.java b/jdk/test/java/lang/instrument/appendToClassLoaderSearch/CircularityErrorTest.java
new file mode 100644
index 0000000..13b527e
--- /dev/null
+++ b/jdk/test/java/lang/instrument/appendToClassLoaderSearch/CircularityErrorTest.java
@@ -0,0 +1,64 @@
+/*
+ * Copyright 2005 Sun Microsystems, Inc.  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 Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
+ * CA 95054 USA or visit www.sun.com if you need additional information or
+ * have any questions.
+ */
+
+/*
+ *
+ *
+ * Unit test for Instrumentation appendToBootstrapClassLoaderSearch:
+ *
+ * 1. Reference class A. Resolving this class should fail with
+ *    ClassCircularityError.
+ *
+ * 2. Add JAR file to boot class path which contains a "good"
+ *    version of A.
+ *
+ * 3. Re-run the code for 1 again - it should fail with
+ *    ClassCircularityError again.
+ */
+import java.lang.instrument.Instrumentation;
+import java.util.jar.JarFile;
+
+public class CircularityErrorTest {
+
+    static Instrumentation ins;
+
+    static void resolve() {
+        try {
+            Class c = A.class;
+            throw new RuntimeException("Test failed - class A loaded by: " +
+                c.getClassLoader());
+        } catch (ClassCircularityError e) {
+            System.err.println(e);
+        }
+    }
+
+    public static void main(String args[]) throws Exception {
+        resolve();
+        ins.appendToBootstrapClassLoaderSearch(new JarFile("A.jar"));
+        resolve();
+    }
+
+    public static void premain(String args, Instrumentation i) {
+        ins = i;
+    }
+}
diff --git a/jdk/test/java/lang/instrument/appendToClassLoaderSearch/CircularityErrorTest.sh b/jdk/test/java/lang/instrument/appendToClassLoaderSearch/CircularityErrorTest.sh
new file mode 100644
index 0000000..c68016a
--- /dev/null
+++ b/jdk/test/java/lang/instrument/appendToClassLoaderSearch/CircularityErrorTest.sh
@@ -0,0 +1,75 @@
+#
+# Copyright 2005 Sun Microsystems, Inc.  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 Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
+# CA 95054 USA or visit www.sun.com if you need additional information or
+# have any questions.
+#
+
+# @test
+# @bug 6173575
+# @summary Unit tests for appendToBootstrapClassLoaderSearch and
+#   appendToSystemClasLoaderSearch methods.
+#
+# @run shell CircularityErrorTest.sh
+
+if [ "${TESTSRC}" = "" ]
+then
+  echo "TESTSRC not set.  Test cannot execute.  Failed."
+  exit 1
+fi
+                                                                                                        
+. ${TESTSRC}/CommonSetup.sh
+
+# Setup to create circularity condition
+
+# B extends A
+# This yields us A.jar (containing A.class) and B.keep (class file)
+rm -f "${TESTCLASSES}"/A.java "${TESTCLASSES}"/B.java
+cp "${TESTSRC}"/A.1 "${TESTCLASSES}"/A.java
+cp "${TESTSRC}"/B.1 "${TESTCLASSES}"/B.java
+(cd "${TESTCLASSES}"; \
+    $JAVAC A.java B.java; \
+    $JAVAC -d . "${TESTSRC}"/CircularityErrorTest.java; \
+    $JAR cf A.jar A.class; \
+    rm -f A.class; mv B.class B.keep)
+
+# A extends B
+# This yields us A.class
+rm -f "${TESTCLASSES}"/A.java "${TESTCLASSES}"/B.java
+cp "${TESTSRC}"/A.2 "${TESTCLASSES}"/A.java
+cp "${TESTSRC}"/B.2 "${TESTCLASSES}"/B.java
+(cd "${TESTCLASSES}"; \
+     $JAVAC A.java B.java; rm -f B.class A.java B.java)
+
+# Move B.keep to B.class creates the A extends B and
+# B extends A condition.
+(cd "${TESTCLASSES}"; mv B.keep B.class)
+
+# Create the manifest
+MANIFEST="${TESTCLASSES}"/agent.mf
+rm -f "${MANIFEST}"
+echo "Premain-Class: CircularityErrorTest" > "${MANIFEST}"
+
+# Setup test case as an agent
+$JAR -cfm "${TESTCLASSES}"/CircularityErrorTest.jar "${MANIFEST}" \
+  -C "${TESTCLASSES}" CircularityErrorTest.class
+
+# Finally we run the test
+(cd "${TESTCLASSES}"; 
+  $JAVA -javaagent:CircularityErrorTest.jar CircularityErrorTest)
diff --git a/jdk/test/java/lang/instrument/appendToClassLoaderSearch/ClassUnloadTest.java b/jdk/test/java/lang/instrument/appendToClassLoaderSearch/ClassUnloadTest.java
new file mode 100644
index 0000000..2645241
--- /dev/null
+++ b/jdk/test/java/lang/instrument/appendToClassLoaderSearch/ClassUnloadTest.java
@@ -0,0 +1,119 @@
+/*
+ * Copyright 2005 Sun Microsystems, Inc.  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 Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
+ * CA 95054 USA or visit www.sun.com if you need additional information or
+ * have any questions.
+ */
+
+/*
+ *
+ *
+ * Unit test for Instrumentation appendToSystemClassLoaderSearch. This
+ * test does the following:
+ *
+ * 1. Creates a class loader to load class Foo. Execute Foo.doSomething
+ *    which references a missing class Bar. The doSomething method
+ *    should fail with NoClassDefFoundError.
+ *
+ * 2. Add Bar.jar to the system class path. Bar.jar contains Bar.
+ *
+ * 3. Create another class loader to load Foo. Execute Foo.doSomething.
+ *    doSomething will load Bar.
+ *
+ * 4. Re-execute the first Foo's doSomething - it should fail a second
+ *    time because the attempt to resolve Bar must fail with the same
+ *    error as the first attempt.
+ *
+ * 5. De-reference both class loaders and execute System.gc(). We can't
+ *    assert that the Foo classes will be unloaded but it serves to
+ *    exercise the unload code path in HotSpot.
+ */
+import java.lang.instrument.Instrumentation;
+import java.io.File;
+import java.net.URL;
+import java.net.URLClassLoader;
+import java.lang.reflect.Method;
+import java.lang.reflect.InvocationTargetException;
+import java.util.jar.JarFile;
+
+public class ClassUnloadTest {
+
+    static Instrumentation ins;
+
+    public static void main(String args[]) throws Exception {
+        String dir = args[0] + File.separator;
+        String jar = dir + args[1];
+
+        System.out.println(jar);
+
+        URL u = (new File(dir)).toURL();
+        URL urls[] = { u };
+
+        // This should fail as Bar is not available
+        Invoker i1 = new Invoker(urls, "Foo", "doSomething");
+        Boolean result = (Boolean)i1.invoke((Object)null);
+        if (result.booleanValue()) {
+            throw new RuntimeException("Test configuration error - doSomething should not succeed");
+        }
+
+        // put Bar on the system class path
+        ins.appendToSystemClassLoaderSearch( new JarFile(jar) );
+
+        // This should fail even though Bar is now available
+        result = (Boolean)i1.invoke((Object)null);
+        if (result.booleanValue()) {
+            throw new RuntimeException("Test configuration error - doSomething should not succeed");
+        }
+
+        // This should succeed because this is a different Foo
+        Invoker i2 = new Invoker(urls, "Foo", "doSomething");
+        result = (Boolean)i2.invoke((Object)null);
+        if (!result.booleanValue()) {
+            throw new RuntimeException("Test configuration error - doSomething did not succeed");
+        }
+
+        // Exercise some class unloading
+        i1 = i2 = null;
+        System.gc();
+    }
+
+    static class Invoker {
+
+        URLClassLoader cl;
+        Method m;
+
+        public Invoker(URL urls[], String cn, String mn, Class ... params)
+            throws ClassNotFoundException, NoSuchMethodException
+        {
+            cl = new URLClassLoader(urls);
+            Class c = Class.forName("Foo", true, cl);
+            m = c.getDeclaredMethod(mn, params);
+        }
+
+        public Object invoke(Object ... args)
+            throws IllegalAccessException, InvocationTargetException
+        {
+            return m.invoke(args);
+        }
+    }
+
+    public static void premain(String args, Instrumentation i) {
+        ins = i;
+    }
+}
diff --git a/jdk/test/java/lang/instrument/appendToClassLoaderSearch/ClassUnloadTest.sh b/jdk/test/java/lang/instrument/appendToClassLoaderSearch/ClassUnloadTest.sh
new file mode 100644
index 0000000..cea2231
--- /dev/null
+++ b/jdk/test/java/lang/instrument/appendToClassLoaderSearch/ClassUnloadTest.sh
@@ -0,0 +1,83 @@
+#
+# Copyright 2005 Sun Microsystems, Inc.  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 Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
+# CA 95054 USA or visit www.sun.com if you need additional information or
+# have any questions.
+#
+
+# @test
+# @bug 6173575
+# @summary Unit tests for appendToBootstrapClassLoaderSearch and
+#   appendToSystemClasLoaderSearch methods.
+#
+# @build ClassUnloadTest
+# @run shell ClassUnloadTest.sh
+
+if [ "${TESTSRC}" = "" ]
+then
+  echo "TESTSRC not set.  Test cannot execute.  Failed."
+  exit 1
+fi
+                                                                                                        
+. ${TESTSRC}/CommonSetup.sh
+
+# Create Foo and Bar
+# Foo has a reference to Bar but we deleted Bar so that 
+# a NoClassDefFoundError will be thrown when Foo tries to
+# resolve the reference to Bar
+
+OTHERDIR="${TESTCLASSES}"/other
+mkdir "${OTHERDIR}"
+
+FOO="${OTHERDIR}"/Foo.java
+BAR="${OTHERDIR}"/Bar.java
+rm -f "${FOO}" "${BAR}"
+
+cat << EOF > "${FOO}"
+  public class Foo {
+      public static boolean doSomething() {
+          try {
+	      Bar b = new Bar();
+	      return true;
+	  } catch (NoClassDefFoundError x) {
+	      return false;
+	  }
+      }
+  }
+EOF
+
+echo "public class Bar { }" > "${BAR}"
+
+(cd "${OTHERDIR}"; \
+  $JAVAC Foo.java Bar.java; $JAR cf "${OTHERDIR}"/Bar.jar Bar.class; \
+  rm -f Bar.class)
+
+# Create the manifest
+MANIFEST="${TESTCLASSES}"/agent.mf
+rm -f "${MANIFEST}"
+echo "Premain-Class: ClassUnloadTest" > "${MANIFEST}"
+
+# Setup test case as an agent
+$JAR -cfm "${TESTCLASSES}"/ClassUnloadTest.jar "${MANIFEST}" \
+  -C "${TESTCLASSES}" ClassUnloadTest.class
+
+# Finally we run the test
+(cd "${TESTCLASSES}"; \
+  $JAVA -Xverify:none -XX:+TraceClassUnloading -javaagent:ClassUnloadTest.jar \
+    ClassUnloadTest "${OTHERDIR}" Bar.jar)
diff --git a/jdk/test/java/lang/instrument/appendToClassLoaderSearch/CommonSetup.sh b/jdk/test/java/lang/instrument/appendToClassLoaderSearch/CommonSetup.sh
new file mode 100644
index 0000000..4c59472
--- /dev/null
+++ b/jdk/test/java/lang/instrument/appendToClassLoaderSearch/CommonSetup.sh
@@ -0,0 +1,79 @@
+#!/bin/sh
+
+#
+# Copyright 2005 Sun Microsystems, Inc.  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 Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
+# CA 95054 USA or visit www.sun.com if you need additional information or
+# have any questions.
+#
+
+
+#%E
+#
+# Common setup for unit tests. Setups up the following variables:
+#
+# PS - path sep.
+# FS - file sep.
+# JAVA - java cmd.
+# JAVAC - javac cmd.
+# JAR - jar cmd.
+
+OS=`uname -s`
+case "$OS" in
+  SunOS )
+    PS=":"
+    FS="/"
+    ;;
+  Linux )
+    PS=":"
+    FS="/"
+    ;;
+  Windows* | CYGWIN*)
+    PS=";"
+    OS="Windows"
+    FS="\\"
+    ;;
+  * )
+    echo "Unrecognized system!"
+    exit 1;
+    ;;
+esac
+
+if [ "${TESTJAVA}" = "" ]
+then
+  echo "TESTJAVA not set.  Test cannot execute.  Failed."
+  exit 1
+fi
+
+if [ "${TESTSRC}" = "" ]
+then
+  echo "TESTSRC not set.  Test cannot execute.  Failed."
+  exit 1
+fi
+ 
+if [ "${TESTCLASSES}" = "" ]
+then
+  echo "TESTCLASSES not set.  Test cannot execute.  Failed."
+  exit 1
+fi
+
+JAVA="${TESTJAVA}/bin/java"
+JAVAC="${TESTJAVA}/bin/javac"
+JAR="${TESTJAVA}/bin/jar"
+
diff --git a/jdk/test/java/lang/instrument/appendToClassLoaderSearch/DynamicTest.java b/jdk/test/java/lang/instrument/appendToClassLoaderSearch/DynamicTest.java
new file mode 100644
index 0000000..68683f2
--- /dev/null
+++ b/jdk/test/java/lang/instrument/appendToClassLoaderSearch/DynamicTest.java
@@ -0,0 +1,84 @@
+/*
+ * Copyright 2005 Sun Microsystems, Inc.  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 Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
+ * CA 95054 USA or visit www.sun.com if you need additional information or
+ * have any questions.
+ */
+
+/*
+ *
+ *
+ * Unit test for Instrumentation appendToBootstrapClassLoaderSearch method.
+ * The test works as follows:
+ *
+ * 1. Load class "Application" and execute the doSomething() method
+ *
+ * 2. Append Tracer.jar to the boot class path - Tracer.jar has a single
+ *    class org.tools.Tracer.
+ *
+ * 3. Redefine class "Application" - the redefined version has an instrumented
+ *    version of doSomething() that invokes a method in org.tools.Tracer.
+ *
+ * 4. Re-execute doSomething() - this should provoke the loading of org.tools.Tracer
+ *    from the jar file. If updated version of doSomething() executes then test
+ *    passes.
+ */
+import java.lang.instrument.*;
+import java.util.jar.JarFile;
+import java.io.*;
+
+public class DynamicTest {
+
+    public static void main(String args[]) throws Exception {
+
+        // Load Application
+        Application app = new Application();
+        if (app.doSomething() != 1) {
+            throw new RuntimeException("Test configuration error - doSomething should return 1");
+        }
+
+        // Add org.tools.Tracer package to the boot class path
+        JarFile jf = new JarFile("Tracer.jar");
+        Agent.getInstrumentation().appendToBootstrapClassLoaderSearch(jf);
+
+        // Redefine Application with the instrumented version
+        File f = new File("InstrumentedApplication.bytes");
+        int len = (int)f.length();
+        byte[] def = new byte[len];
+
+        FileInputStream fis = new FileInputStream(f);
+        int nread = 0;
+        do {
+            int n = fis.read(def, nread, len-nread);
+            if (n > 0) {
+                nread += n;
+            }
+        } while (nread < len);
+
+        ClassDefinition classDefs = new ClassDefinition(Application.class, def);
+        Agent.getInstrumentation().redefineClasses(new ClassDefinition[] { classDefs } );
+
+        // Re-execute doSomething() - should get 3 messages printed
+        int res = app.doSomething();
+        if (res != 3) {
+            throw new RuntimeException("FAIL: redefined Application returned: " + res);
+        }
+        System.out.println("PASS: Test passed.");
+    }
+}
diff --git a/jdk/test/java/lang/instrument/appendToClassLoaderSearch/InstrumentedApplication.java b/jdk/test/java/lang/instrument/appendToClassLoaderSearch/InstrumentedApplication.java
new file mode 100644
index 0000000..ffb6f88
--- /dev/null
+++ b/jdk/test/java/lang/instrument/appendToClassLoaderSearch/InstrumentedApplication.java
@@ -0,0 +1,38 @@
+/*
+ * Copyright 2005 Sun Microsystems, Inc.  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 Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
+ * CA 95054 USA or visit www.sun.com if you need additional information or
+ * have any questions.
+ */
+
+/*
+ *
+ *
+ * Used by DynamicTest - simple Application with one method that returns the
+ * number of messages printed. This is the "instrumented" form.
+ */
+public class Application {
+
+    public int doSomething() {
+        org.tools.Tracer.trace("MethodEnter");
+        System.out.println("Bring us up to warp speed!");
+        org.tools.Tracer.trace("MethodExit");
+        return 3;
+    }
+}
diff --git a/jdk/test/java/lang/instrument/appendToClassLoaderSearch/PrematureLoadTest.java b/jdk/test/java/lang/instrument/appendToClassLoaderSearch/PrematureLoadTest.java
new file mode 100644
index 0000000..d1eaaa8
--- /dev/null
+++ b/jdk/test/java/lang/instrument/appendToClassLoaderSearch/PrematureLoadTest.java
@@ -0,0 +1,91 @@
+/*
+ * Copyright 2005 Sun Microsystems, Inc.  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 Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
+ * CA 95054 USA or visit www.sun.com if you need additional information or
+ * have any questions.
+ */
+
+/*
+ *
+ *
+ * Basic unit test for Instrumentation appendToBootstrapClassLoaderSearch and
+ * appendToSystemClassLoaderSearch methods:
+ *
+ * 1. Attempt to load a class that does not exist.
+ *
+ * 2. Add a jar file to the class path with the missing class.
+ *
+ * 3. Attempt to load the class again - CNF should be thrown as the JVMS requires that
+ *    the error from the first resolution attempt should be thrown.
+ */
+import java.lang.instrument.Instrumentation;
+import java.util.jar.JarFile;
+import java.io.IOException;
+
+public class PrematureLoadTest {
+
+    static int failures = 0;
+
+    public static void main(String args[]) throws IOException {
+
+        try {
+            new BootSupport();
+            throw new RuntimeException("Test configuration error - BootSupport loaded unexpectedly!");
+        } catch (NoClassDefFoundError x) {
+        }
+
+        try {
+            new AgentSupport();
+            throw new RuntimeException("Test configuration error - AgentSupport loaded unexpectedly!");
+        } catch (NoClassDefFoundError x) {
+        }
+
+
+        JarFile bootclasses = new JarFile("BootSupport.jar");
+        JarFile agentclasses = new JarFile("AgentSupport.jar");
+
+        Instrumentation ins = Agent.getInstrumentation();
+
+        ins.appendToBootstrapClassLoaderSearch(bootclasses);
+        try {
+            new BootSupport();
+            System.out.println("FAIL: BootSupport resolved");
+            failures++;
+        } catch (NoClassDefFoundError x) {
+            System.out.println("PASS: BootSupport failed to resolve");
+        }
+
+        try {
+            ins.appendToSystemClassLoaderSearch(agentclasses);
+            try {
+                new AgentSupport();
+                System.out.println("FAIL: AgentSupport resolved");
+                failures++;
+            } catch (NoClassDefFoundError x) {
+                System.out.println("PASS: AgentSupport failed to resolve");
+            }
+        } catch (UnsupportedOperationException x) {
+            System.out.println("System class loader does not support adding to class path");
+        }
+
+        if (failures > 0) {
+            throw new RuntimeException(failures + " test(s) failed.");
+        }
+    }
+}
diff --git a/jdk/test/java/lang/instrument/appendToClassLoaderSearch/Tracer.java b/jdk/test/java/lang/instrument/appendToClassLoaderSearch/Tracer.java
new file mode 100644
index 0000000..189fe22
--- /dev/null
+++ b/jdk/test/java/lang/instrument/appendToClassLoaderSearch/Tracer.java
@@ -0,0 +1,47 @@
+/*
+ * Copyright 2005 Sun Microsystems, Inc.  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 Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
+ * CA 95054 USA or visit www.sun.com if you need additional information or
+ * have any questions.
+ */
+
+/*
+ *
+ *
+ * Used by the unit tests for the Instrument appendToBootstrapClassLoaderSearch
+ * tests. This class is a "supporting" class which the agent puts on the boot
+ * class path.
+ */
+package org.tools;
+
+public class Tracer {
+
+    static {
+        ClassLoader cl = Tracer.class.getClassLoader();
+        if (cl != null) {
+            throw new RuntimeException("Tracer loaded by: " + cl);
+        }
+        System.out.println("Tracer loaded by boot class loader.");
+    }
+
+    public static void trace(String msg) {
+        System.out.println(msg);
+    }
+
+}
diff --git a/jdk/test/java/lang/instrument/appendToClassLoaderSearch/manifest.mf b/jdk/test/java/lang/instrument/appendToClassLoaderSearch/manifest.mf
new file mode 100644
index 0000000..8b1b520
--- /dev/null
+++ b/jdk/test/java/lang/instrument/appendToClassLoaderSearch/manifest.mf
@@ -0,0 +1,4 @@
+Manifest-Version: 1.0
+Premain-Class: Agent
+Can-Redefine-Classes: true
+
diff --git a/jdk/test/java/lang/instrument/appendToClassLoaderSearch/run_tests.sh b/jdk/test/java/lang/instrument/appendToClassLoaderSearch/run_tests.sh
new file mode 100644
index 0000000..0302b7a
--- /dev/null
+++ b/jdk/test/java/lang/instrument/appendToClassLoaderSearch/run_tests.sh
@@ -0,0 +1,102 @@
+#!/bin/sh
+
+#
+# Copyright 2005-2006 Sun Microsystems, Inc.  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 Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
+# CA 95054 USA or visit www.sun.com if you need additional information or
+# have any questions.
+#
+
+                                                                                                              
+# @test
+# @bug 6173575 6388987
+# @summary Unit tests for appendToBootstrapClassLoaderSearch and 
+#   appendToSystemClasLoaderSearch methods.
+#
+# @build Agent AgentSupport BootSupport BasicTest PrematureLoadTest DynamicTest
+# @run shell run_tests.sh
+
+if [ "${TESTSRC}" = "" ]
+then
+  echo "TESTSRC not set.  Test cannot execute.  Failed."
+  exit 1
+fi
+                                                                                                        
+. ${TESTSRC}/CommonSetup.sh
+
+                                                                          
+# Simple tests
+
+echo "Creating jar files for simple tests..."
+
+cd ${TESTCLASSES}
+
+"$JAR" -cfm Agent.jar "${TESTSRC}"/manifest.mf Agent.class
+"$JAR" -cf  AgentSupport.jar AgentSupport.class
+"$JAR" -cf  BootSupport.jar BootSupport.class
+"$JAR" -cf  SimpleTests.jar BasicTest.class PrematureLoadTest.class 
+
+failures=0
+
+go() {
+    echo ''
+    sh -xc "$JAVA -javaagent:Agent.jar -classpath SimpleTests.jar  $1 $2 $3" 2>&1
+    if [ $? != 0 ]; then failures=`expr $failures + 1`; fi
+}
+
+go BasicTest
+go PrematureLoadTest
+
+# Functional tests
+
+echo ''
+echo "Setup for functional tests..."
+
+# Create org.tools.Tracer in temp directory so that it's not seen on the
+# system class path
+
+mkdir tmp
+"${JAVAC}" -d tmp "${TESTSRC}"/Tracer.java
+(cd tmp; "${JAR}" cf ../Tracer.jar org/tools/Tracer.class)
+
+# InstrumentedApplication is Application+instrmentation - don't copy as 
+# we don't want the original file permission
+
+cat "${TESTSRC}"/InstrumentedApplication.java > ./Application.java
+"${JAVAC}" -classpath Tracer.jar -d . Application.java
+mv Application.class InstrumentedApplication.bytes
+
+cp "${TESTSRC}"/Application.java .
+"${JAVAC}" -d . Application.java
+
+sh -xc "$JAVA -classpath . -javaagent:Agent.jar DynamicTest" 2>&1
+if [ $? != 0 ]; then failures=`expr $failures + 1`; fi
+
+# Repeat test with security manager
+sh -xc "$JAVA -classpath . -javaagent:Agent.jar -Djava.security.manager DynamicTest" 2>&1
+if [ $? != 0 ]; then failures=`expr $failures + 1`; fi
+
+#
+# Results
+#
+echo ''
+if [ $failures -gt 0 ];
+  then echo "$failures test(s) failed";
+  else echo "All test(s) passed"; fi
+exit $failures
diff --git a/jdk/test/java/lang/instrument/basicAgent.mf b/jdk/test/java/lang/instrument/basicAgent.mf
new file mode 100644
index 0000000..94b15c1
--- /dev/null
+++ b/jdk/test/java/lang/instrument/basicAgent.mf
@@ -0,0 +1,2 @@
+Manifest-Version: 1.0
+Premain-Class: InstrumentationHandoff
diff --git a/jdk/test/java/lang/instrument/bootclasspathAgent.mf b/jdk/test/java/lang/instrument/bootclasspathAgent.mf
new file mode 100644
index 0000000..e1b0f88
--- /dev/null
+++ b/jdk/test/java/lang/instrument/bootclasspathAgent.mf
@@ -0,0 +1,3 @@
+Manifest-Version: 1.0
+Premain-Class: InstrumentationHandoff
+Boot-Class-Path: hidden/
diff --git a/jdk/test/java/lang/instrument/bootreporter/StringIdCallback.java b/jdk/test/java/lang/instrument/bootreporter/StringIdCallback.java
new file mode 100644
index 0000000..0dcbeca
--- /dev/null
+++ b/jdk/test/java/lang/instrument/bootreporter/StringIdCallback.java
@@ -0,0 +1,29 @@
+/*
+ * Copyright 2005 Sun Microsystems, Inc.  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 Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
+ * CA 95054 USA or visit www.sun.com if you need additional information or
+ * have any questions.
+ */
+
+
+package bootreporter;
+
+public interface StringIdCallback {
+    public void tracker(String name, int id);
+}
diff --git a/jdk/test/java/lang/instrument/bootreporter/StringIdCallbackReporter.java b/jdk/test/java/lang/instrument/bootreporter/StringIdCallbackReporter.java
new file mode 100644
index 0000000..d5c4815
--- /dev/null
+++ b/jdk/test/java/lang/instrument/bootreporter/StringIdCallbackReporter.java
@@ -0,0 +1,40 @@
+/*
+ * Copyright 2005 Sun Microsystems, Inc.  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 Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
+ * CA 95054 USA or visit www.sun.com if you need additional information or
+ * have any questions.
+ */
+
+
+package bootreporter;
+
+public class StringIdCallbackReporter {
+
+    static StringIdCallback callback = null;
+
+    public static void tracker(String name, int id) {
+        if (callback != null) {
+            callback.tracker(name, id);
+        }
+    }
+
+    public static void registerCallback(StringIdCallback aCallback) {
+        callback = aCallback;
+    }
+}
diff --git a/jdk/test/java/lang/instrument/classpathAgent.mf b/jdk/test/java/lang/instrument/classpathAgent.mf
new file mode 100644
index 0000000..e0c8fb2
--- /dev/null
+++ b/jdk/test/java/lang/instrument/classpathAgent.mf
@@ -0,0 +1,3 @@
+Manifest-Version: 1.0
+Class-Path: hidden/
+Premain-Class: InstrumentationHandoff
diff --git a/jdk/test/java/lang/instrument/ilib/ClassDump.java b/jdk/test/java/lang/instrument/ilib/ClassDump.java
new file mode 100644
index 0000000..93a57b8
--- /dev/null
+++ b/jdk/test/java/lang/instrument/ilib/ClassDump.java
@@ -0,0 +1,273 @@
+/*
+ * Copyright 2005 Sun Microsystems, Inc.  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 Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
+ * CA 95054 USA or visit www.sun.com if you need additional information or
+ * have any questions.
+ */
+
+package ilib;
+
+import java.io.IOException;
+import java.io.File;
+import java.io.FileOutputStream;
+import java.io.DataOutputStream;
+import java.io.PrintStream;
+import java.io.PrintWriter;
+import java.io.CharArrayWriter;
+import java.util.List;
+import java.util.Iterator;
+import java.util.ArrayList;
+
+public class ClassDump implements RuntimeConstants {
+
+  public static void dump(Options opt,
+                                       ClassLoader loader,
+                                       String className,
+                                       byte[] classfileBuffer) {
+    ClassReaderWriter c = new ClassReaderWriter(classfileBuffer);
+    (new ClassDump(className, c)).doit();
+  }
+
+    static boolean verbose = true;
+
+    final String className;
+    final ClassReaderWriter c;
+    private final PrintStream output;
+
+    int constantPoolCount;
+    int methodsCount;
+
+    ClassDump(String className, ClassReaderWriter c) {
+        this.className = className;
+        this.c = c;
+        this.output = System.err;
+    }
+
+    void doit() {
+        int i;
+        c.copy(4 + 2 + 2); // magic min/maj version
+        constantPoolCount = c.copyU2();
+        // copy old constant pool
+        c.copyConstantPool(constantPoolCount);
+
+        traceln("ConstantPool size: " + constantPoolCount);
+
+        c.copy(2 + 2 + 2);  // access, this, super
+        int interfaceCount = c.copyU2();
+        traceln("interfaceCount: " + interfaceCount);
+        c.copy(interfaceCount * 2);
+        copyFields(); // fields
+        copyMethods(); // methods
+        int attrCount = c.copyU2();
+        traceln("class attrCount: " + attrCount);
+        // copy the class attributes
+        copyAttrs(attrCount);
+    }
+
+
+    void copyFields() {
+        int count = c.copyU2();
+        if (verbose) {
+            System.out.println("fields count: " + count);
+        }
+        for (int i = 0; i < count; ++i) {
+            c.copy(6); // access, name, descriptor
+            int attrCount = c.copyU2();
+            if (verbose) {
+                System.out.println("field attr count: " + attrCount);
+            }
+            copyAttrs(attrCount);
+        }
+    }
+
+    void copyMethods() {
+        methodsCount = c.copyU2();
+        if (verbose) {
+            System.out.println("methods count: " + methodsCount);
+        }
+        for (int i = 0; i < methodsCount; ++i) {
+            copyMethod();
+        }
+    }
+
+    void copyMethod() {
+        int accessFlags = c.copyU2();// access flags
+        int nameIndex = c.copyU2();  // name
+        checkIndex(nameIndex, "Method name");
+        String methodName = c.constantPoolString(nameIndex);
+        traceln("method: " + methodName);
+        int descriptorIndex = c.copyU2();                  // descriptor
+        checkIndex(descriptorIndex, "Method descriptor");
+        int attrCount = c.copyU2();  // attribute count
+        if (verbose) {
+            System.out.println("method attr count: " + attrCount);
+        }
+        for (int i = 0; i < attrCount; ++i) {
+            copyAttrForMethod(methodName, accessFlags);
+        }
+    }
+
+    void copyAttrs(int attrCount) {
+        for (int i = 0; i < attrCount; ++i) {
+            copyAttr();
+        }
+    }
+
+    void copyAttr() {
+        c.copy(2);             // name
+        int len = c.copyU4();  // attr len
+        if (verbose) {
+            System.out.println("attr len: " + len);
+        }
+        c.copy(len);           // attribute info
+    }
+
+    void copyAttrForMethod(String methodName, int accessFlags) {
+        int nameIndex = c.copyU2();   // name
+        // check for Code attr
+        checkIndex(nameIndex, "Method attr name");
+        if (nameIndex == c.codeAttributeIndex) {
+            try {
+                copyCodeAttr(methodName);
+            } catch (IOException exc) {
+                System.err.println("Code Exception - " + exc);
+                System.exit(1);
+            }
+        } else {
+            int len = c.copyU4();     // attr len
+            traceln("method attr len: " + len);
+            c.copy(len);              // attribute info
+        }
+    }
+
+    void copyAttrForCode() throws IOException {
+        int nameIndex = c.copyU2();   // name
+
+        checkIndex(nameIndex, "Code attr name");
+        int len = c.copyU4();     // attr len
+        traceln("code attr len: " + len);
+        c.copy(len);              // attribute info
+    }
+
+    void copyCodeAttr(String methodName) throws IOException {
+        traceln("Code attr found");
+        int attrLength = c.copyU4();        // attr len
+        checkLength(attrLength, "Code attr length");
+        int maxStack = c.readU2();          // max stack
+        c.copyU2();                         // max locals
+        int codeLength = c.copyU4();        // code length
+        checkLength(codeLength, "Code length");
+
+        copyExceptionTable();
+
+        int attrCount = c.copyU2();
+        checkLength(attrCount, "Code attr count");
+        for (int i = 0; i < attrCount; ++i) {
+            copyAttrForCode();
+        }
+    }
+
+    /**
+     * Copy the exception table for this method code
+     */
+    void copyExceptionTable() throws IOException {
+        int tableLength = c.copyU2();   // exception table len
+        checkLength(tableLength, "Exception Table length");
+        if (tableLength > 0) {
+            traceln();
+            traceln("Exception table:");
+            traceln(" from:old/new  to:old/new target:old/new type");
+            for (int tcnt = tableLength; tcnt > 0; --tcnt) {
+                int startPC = c.readU2();
+                int endPC = c.readU2();
+                int handlerPC = c.readU2();
+                int catchType = c.copyU2();
+                if (verbose) {
+                    traceFixedWidthInt(startPC, 6);
+                    traceFixedWidthInt(endPC, 6);
+                    traceFixedWidthInt(handlerPC, 6);
+                    trace("    ");
+                    if (catchType == 0)
+                        traceln("any");
+                    else {
+                        traceln("" + catchType);
+                    }
+                }
+            }
+        }
+    }
+
+    private void checkIndex(int index, String comment) {
+        if (index > constantPoolCount) {
+            output.println("ERROR BAD INDEX " + comment + " : " + index);
+        } else {
+            traceln(comment + " : " + index);
+        }
+    }
+
+    private void checkLength(int length, String comment) {
+        if (length > c.inputBytes().length) {
+            output.println("ERROR BAD LENGTH " + comment + " : " + length);
+        } else {
+            traceln(comment + " : " + length);
+        }
+    }
+
+    private void trace(String str) {
+        if (verbose) {
+            output.print(str);
+        }
+    }
+
+    private void traceln(String str) {
+        if (verbose) {
+            output.println(str);
+        }
+    }
+
+    private void traceln() {
+        if (verbose) {
+            output.println();
+        }
+    }
+
+    private void trace(int i) {
+        if (verbose) {
+            output.print(i);
+        }
+    }
+
+    /**
+     * Print an integer so that it takes 'length' characters in
+     * the output.  Temporary until formatting code is stable.
+     */
+    private void traceFixedWidthInt(int x, int length) {
+        if (verbose) {
+            CharArrayWriter baStream = new CharArrayWriter();
+            PrintWriter pStream = new PrintWriter(baStream);
+            pStream.print(x);
+            String str = baStream.toString();
+            for (int cnt = length - str.length(); cnt > 0; --cnt)
+                trace(" ");
+            trace(str);
+        }
+    }
+
+
+}
diff --git a/jdk/test/java/lang/instrument/ilib/ClassReaderWriter.java b/jdk/test/java/lang/instrument/ilib/ClassReaderWriter.java
new file mode 100644
index 0000000..70ebce7
--- /dev/null
+++ b/jdk/test/java/lang/instrument/ilib/ClassReaderWriter.java
@@ -0,0 +1,263 @@
+/*
+ * Copyright 2005 Sun Microsystems, Inc.  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 Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
+ * CA 95054 USA or visit www.sun.com if you need additional information or
+ * have any questions.
+ */
+
+package ilib;
+
+class ClassReaderWriter implements RuntimeConstants {
+
+    int codeAttributeIndex;
+    int lineNumberAttributeIndex;
+    int localVarAttributeIndex;
+
+    private final byte[] orig;
+    private final byte[] gen;
+    private final int sectionLength;
+
+    private static final int GROWTH_FACTOR = 2;
+    private static final int SECTIONS = 2;
+    private static final String codeAttributeName = "Code";
+    private static final String lineNumberAttributeName = "LineNumberTable";
+    private static final String localVarAttributeName = "LocalVariableTable";
+
+    private int[] genSectionPos = new int[SECTIONS];
+
+    private int inputPos = 0;
+    private int genPos = 0;
+    private int markPos = 0;
+    private int currentSection = 0;
+
+    private String[] constantPool;
+
+    ClassReaderWriter(byte[] orig) {
+        this.orig = orig;
+        sectionLength = orig.length * GROWTH_FACTOR;
+        gen = new byte[sectionLength * SECTIONS];
+        for (int section = 0; section < SECTIONS; ++section) {
+            genSectionPos[section] = section * sectionLength;
+        }
+    }
+
+    int setSection(int section) {
+        int prevSection = currentSection;
+        genSectionPos[prevSection] = genPos;
+        genPos = genSectionPos[section];
+        currentSection = section;
+        return prevSection;
+    }
+
+    byte[] result() {
+        int section;
+        int totalLength = 0;
+
+        setSection(0); // save current section
+
+        for (section = 0; section < SECTIONS; ++section) {
+            int sectionStart = section * sectionLength;
+            int sectionGenLength = genSectionPos[section] - sectionStart;
+            totalLength += sectionGenLength;
+        }
+
+        byte[] newcf = new byte[totalLength];
+        int written = 0;
+        for (section = 0; section < SECTIONS; ++section) {
+            int sectionStart = section * sectionLength;
+            int sectionGenLength = genSectionPos[section] - sectionStart;
+            System.arraycopy(gen, sectionStart, newcf, written, sectionGenLength);
+            written += sectionGenLength;
+        }
+
+        return newcf;
+    }
+
+    int readU1() {
+        return ((int)orig[inputPos++]) & 0xFF;
+    }
+
+    int readU2() {
+        int res = readU1();
+        return (res << 8) + readU1();
+    }
+
+    short readS2() {
+        int res = readU1();
+        return (short)((res << 8) + readU1());
+    }
+
+    int readU4() {
+        int res = readU2();
+        return (res << 16) + readU2();
+    }
+
+    void writeU1(int val) {
+        gen[genPos++] = (byte)val;
+    }
+
+    void writeU2(int val) {
+        writeU1(val >> 8);
+        writeU1(val & 0xFF);
+    }
+
+    void writeU4(int val) {
+        writeU2(val >> 16);
+        writeU2(val & 0xFFFF);
+    }
+
+    int copyU1() {
+        int value = readU1();
+        writeU1(value);
+        return value;
+    }
+
+    int copyU2() {
+        int value = readU2();
+        writeU2(value);
+        return value;
+    }
+
+    int copyU4() {
+        int value = readU4();
+        writeU4(value);
+        return value;
+    }
+
+    void copy(int count) {
+        for (int i = 0; i < count; ++i) {
+            gen[genPos++] = orig[inputPos++];
+        }
+    }
+
+    void skip(int count) {
+        inputPos += count;
+    }
+
+    byte[] readBytes(int count) {
+        byte[] bytes = new byte[count];
+        for (int i = 0; i < count; ++i) {
+            bytes[i] = orig[inputPos++];
+        }
+        return bytes;
+    }
+
+    void writeBytes(byte[] bytes) {
+        for (int i = 0; i < bytes.length; ++i) {
+            gen[genPos++] = bytes[i];
+        }
+    }
+
+    byte[] inputBytes() {
+        return orig;
+    }
+
+    int inputPosition() {
+        return inputPos;
+    }
+
+    void setInputPosition(int pos) {
+        inputPos = pos;
+    }
+
+    void markLocalPositionStart() {
+        markPos = inputPos;
+    }
+
+    int localPosition() {
+        return inputPos - markPos;
+    }
+
+    void rewind() {
+        setInputPosition(markPos);
+    }
+
+    int generatedPosition() {
+        return genPos;
+    }
+
+    void randomAccessWriteU2(int pos, int val) {
+        int savePos = genPos;
+        genPos = pos;
+        writeU2(val);
+        genPos = savePos;
+    }
+
+    void randomAccessWriteU4(int pos, int val) {
+        int savePos = genPos;
+        genPos = pos;
+        writeU4(val);
+        genPos = savePos;
+    }
+
+    String constantPoolString(int index) {
+        return constantPool[index];
+    }
+
+    void copyConstantPool(int constantPoolCount){
+        // copy const pool
+        constantPool = new String[constantPoolCount];
+        // index zero not in class file
+        for (int i = 1; i < constantPoolCount; ++i) {
+            int tag = readU1();
+            writeU1(tag);
+            switch (tag) {
+                case CONSTANT_CLASS:
+                case CONSTANT_STRING:
+                    copy(2);
+                    break;
+                case CONSTANT_FIELD:
+                case CONSTANT_METHOD:
+                case CONSTANT_INTERFACEMETHOD:
+                case CONSTANT_INTEGER:
+                case CONSTANT_FLOAT:
+                case CONSTANT_NAMEANDTYPE:
+                    copy(4);
+                    break;
+                case CONSTANT_LONG:
+                case CONSTANT_DOUBLE:
+                    copy(8);
+                    ++i;  // these take two CP entries - duh!
+                    break;
+                case CONSTANT_UTF8:
+                    int len = copyU2();
+                    byte[] utf8 = readBytes(len);
+                    String str = null; // null to shut the compiler up
+                    try {
+                        str = new String(utf8, "UTF-8");
+                    } catch (Exception exc) {
+                        throw new Error("CP exception: " + exc);
+                    }
+                    constantPool[i] = str;
+                    if (str.equals(codeAttributeName)) {
+                        codeAttributeIndex = i;
+                    } else if (str.equals(lineNumberAttributeName)) {
+                        lineNumberAttributeIndex = i;
+                    } else if (str.equals(localVarAttributeName)) {
+                        localVarAttributeIndex = i;
+                    }
+                    writeBytes(utf8);
+                    break;
+                default:
+                    throw new Error(i + " unexpected CP tag: " + tag);
+            }
+        }
+    }
+
+}
diff --git a/jdk/test/java/lang/instrument/ilib/Info.java b/jdk/test/java/lang/instrument/ilib/Info.java
new file mode 100644
index 0000000..a1eff20
--- /dev/null
+++ b/jdk/test/java/lang/instrument/ilib/Info.java
@@ -0,0 +1,38 @@
+/*
+ * Copyright 2005 Sun Microsystems, Inc.  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 Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
+ * CA 95054 USA or visit www.sun.com if you need additional information or
+ * have any questions.
+ */
+
+package ilib;
+
+public class Info {
+        final int counter;
+        final String className;
+        final String methodName;
+        final int location;
+
+        Info(int counter, String className, String methodName, int location) {
+            this.counter = counter;
+            this.className = className;
+            this.methodName = methodName;
+            this.location = location;
+        }
+}
diff --git a/jdk/test/java/lang/instrument/ilib/Inject.java b/jdk/test/java/lang/instrument/ilib/Inject.java
new file mode 100644
index 0000000..aab7c4c
--- /dev/null
+++ b/jdk/test/java/lang/instrument/ilib/Inject.java
@@ -0,0 +1,745 @@
+/*
+ * Copyright 2005 Sun Microsystems, Inc.  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 Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
+ * CA 95054 USA or visit www.sun.com if you need additional information or
+ * have any questions.
+ */
+
+package ilib;
+
+import java.io.IOException;
+import java.io.File;
+import java.io.FileOutputStream;
+import java.io.DataOutputStream;
+import java.util.List;
+import java.util.Iterator;
+import java.util.ArrayList;
+
+public class Inject implements RuntimeConstants {
+
+    public static byte[] instrumentation(Options opt,
+                                         ClassLoader loader,
+                                         String className,
+                                         byte[] classfileBuffer) {
+        ClassReaderWriter c = new ClassReaderWriter(classfileBuffer);
+        (new Inject(className, c, loader == null, opt)).doit();
+        return c.result();
+    }
+
+    static boolean verbose = false;
+
+    final String className;
+    final ClassReaderWriter c;
+    final boolean isSystem;
+    final Options options;
+
+    int constantPoolCount;
+    int methodsCount;
+    int methodsCountPos;
+    int profiler;
+    int wrappedTrackerIndex = 0;
+    int thisClassIndex = 0;
+
+    TrackerInjector callInjector;
+    TrackerInjector allocInjector;
+    TrackerInjector defaultInjector;
+
+    static interface TrackerInjector extends Injector {
+        void reinit(int tracker);
+        int stackSize(int currentSize);
+    }
+
+    static class SimpleInjector implements TrackerInjector {
+        byte[] injection;
+
+        public int stackSize(int currentSize) {
+            return currentSize;
+        }
+
+        public void reinit(int tracker) {
+            injection = new byte[3];
+            injection[0] = (byte)opc_invokestatic;
+            injection[1] = (byte)(tracker >> 8);
+            injection[2] = (byte)tracker;
+        }
+
+        public byte[] bytecodes(String className, String methodName, int location) {
+            return injection;
+        }
+    }
+
+    static class ObjectInjector implements TrackerInjector {
+        byte[] injection;
+
+        public int stackSize(int currentSize) {
+            return currentSize + 1;
+        }
+
+        public void reinit(int tracker) {
+            injection = new byte[4];
+            injection[0] = (byte)opc_dup;
+            injection[1] = (byte)opc_invokestatic;
+            injection[2] = (byte)(tracker >> 8);
+            injection[3] = (byte)tracker;
+        }
+
+        public byte[] bytecodes(String className, String methodName, int location) {
+            return injection;
+        }
+    }
+
+    class IndexedInjector implements TrackerInjector {
+        int counter = 0;
+        int tracker;
+        List<Info> infoList = new ArrayList<Info>();
+
+        public int stackSize(int currentSize) {
+            return currentSize + 1;
+        }
+
+        public void reinit(int tracker) {
+            this.tracker = tracker;
+        }
+
+        void dump(File outDir, String filename) throws IOException {
+            FileOutputStream fileOut = new FileOutputStream(new File(outDir, filename));
+            DataOutputStream dataOut = new DataOutputStream(fileOut);
+
+            String currentClassName = null;
+
+            dataOut.writeInt(infoList.size());
+            for (Iterator<Info> it = infoList.iterator(); it.hasNext(); ) {
+                Info info = it.next();
+                if (!info.className.equals(currentClassName)) {
+                    dataOut.writeInt(123456); // class name marker
+                    currentClassName = info.className;
+                    dataOut.writeUTF(currentClassName);
+                }
+                dataOut.writeInt(info.location);
+                dataOut.writeUTF(info.methodName);
+            }
+            dataOut.close();
+        }
+
+        public byte[] bytecodes(String className, String methodName, int location) {
+            byte[] injection = new byte[6];
+            int injectedIndex = options.fixedIndex != 0? options.fixedIndex : ++counter;
+            infoList.add(new Info(counter, className, methodName, location));
+            injection[0] = (byte)opc_sipush;
+            injection[1] = (byte)(injectedIndex >> 8);
+            injection[2] = (byte)injectedIndex;
+            injection[3] = (byte)opc_invokestatic;
+            injection[4] = (byte)(tracker >> 8);
+            injection[5] = (byte)tracker;
+            return injection;
+        }
+    }
+
+    Inject(String className, ClassReaderWriter c, boolean isSystem, Options options) {
+        this.className = className;
+        this.c = c;
+        this.isSystem = isSystem;
+        this.options = options;
+    }
+
+    void doit() {
+        int i;
+        c.copy(4 + 2 + 2); // magic min/maj version
+        int constantPoolCountPos = c.generatedPosition();
+        constantPoolCount = c.copyU2();
+        // copy old constant pool
+        c.copyConstantPool(constantPoolCount);
+
+        if (verbose) {
+            System.out.println("ConstantPool expanded from: " +
+                               constantPoolCount);
+        }
+
+        profiler = addClassToConstantPool(options.trackerClassName);
+        if (options.shouldInstrumentNew || options.shouldInstrumentObjectInit) {
+            if (options.shouldInstrumentIndexed) {
+                if (allocInjector == null) {
+                    // first time - create it
+                    allocInjector = new IndexedInjector();
+                }
+                int allocTracker = addMethodToConstantPool(profiler,
+                                                           options.allocTrackerMethodName,
+                                                           "(I)V");
+                allocInjector.reinit(allocTracker);
+            } else if (options.shouldInstrumentObject) {
+                if (allocInjector == null) {
+                    // first time - create it
+                    allocInjector = new ObjectInjector();
+                }
+                int allocTracker = addMethodToConstantPool(profiler,
+                                                           options.allocTrackerMethodName,
+                                                           "(Ljava/lang/Object;)V");
+                allocInjector.reinit(allocTracker);
+            } else {
+                if (allocInjector == null) {
+                    // first time - create it
+                    allocInjector = new SimpleInjector();
+                }
+                int allocTracker = addMethodToConstantPool(profiler,
+                                                           options.allocTrackerMethodName,
+                                                           "()V");
+                allocInjector.reinit(allocTracker);
+            }
+            defaultInjector = allocInjector;
+        }
+        if (options.shouldInstrumentCall) {
+            if (options.shouldInstrumentIndexed) {
+                if (callInjector == null) {
+                    // first time - create it
+                    callInjector = new IndexedInjector();
+                }
+                int callTracker = addMethodToConstantPool(profiler,
+                                                          options.callTrackerMethodName,
+                                                          "(I)V");
+                callInjector.reinit(callTracker);
+            } else {
+                if (callInjector == null) {
+                    // first time - create it
+                    callInjector = new SimpleInjector();
+                }
+                int callTracker = addMethodToConstantPool(profiler,
+                                                          options.callTrackerMethodName,
+                                                          "()V");
+                callInjector.reinit(callTracker);
+            }
+            defaultInjector = callInjector;
+        }
+
+        if (verbose) {
+            System.out.println("To: " + constantPoolCount);
+        }
+
+        c.setSection(1);
+
+        c.copy(2 + 2 + 2);  // access, this, super
+        int interfaceCount = c.copyU2();
+        if (verbose) {
+            System.out.println("interfaceCount: " + interfaceCount);
+        }
+        c.copy(interfaceCount * 2);
+        copyFields(); // fields
+        copyMethods(); // methods
+        int attrCountPos = c.generatedPosition();
+        int attrCount = c.copyU2();
+        if (verbose) {
+            System.out.println("class attrCount: " + attrCount);
+        }
+        // copy the class attributes
+        copyAttrs(attrCount);
+
+        c.randomAccessWriteU2(constantPoolCountPos, constantPoolCount);
+    }
+
+
+    void copyFields() {
+        int count = c.copyU2();
+        if (verbose) {
+            System.out.println("fields count: " + count);
+        }
+        for (int i = 0; i < count; ++i) {
+            c.copy(6); // access, name, descriptor
+            int attrCount = c.copyU2();
+            if (verbose) {
+                System.out.println("field attr count: " + attrCount);
+            }
+            copyAttrs(attrCount);
+        }
+    }
+
+    void copyMethods() {
+        methodsCountPos = c.generatedPosition();
+        methodsCount = c.copyU2();
+        int initialMethodsCount = methodsCount;
+        if (verbose) {
+            System.out.println("methods count: " + methodsCount);
+        }
+        for (int i = 0; i < initialMethodsCount; ++i) {
+            copyMethod();
+        }
+    }
+
+    void copyMethod() {
+        int accessFlags = c.copyU2();// access flags
+        if (options.shouldInstrumentNativeMethods && (accessFlags & ACC_NATIVE) != 0) {
+            wrapNativeMethod(accessFlags);
+            return;
+        }
+        int nameIndex = c.copyU2();  // name
+        String methodName = c.constantPoolString(nameIndex);
+        c.copyU2();                  // descriptor
+        int attrCount = c.copyU2();  // attribute count
+        if (verbose) {
+            System.out.println("methods attr count: " + attrCount);
+        }
+        for (int i = 0; i < attrCount; ++i) {
+            copyAttrForMethod(methodName, accessFlags);
+        }
+    }
+
+    void wrapNativeMethod(int accessFlags) {
+        // first, copy the native method with the name changed
+        // accessFlags have already been copied
+        int nameIndex = c.readU2();        // name
+        String methodName = c.constantPoolString(nameIndex);
+        String wrappedMethodName = options.wrappedPrefix + methodName;
+        int wrappedNameIndex = writeCPEntryUtf8(wrappedMethodName);
+        c.writeU2(wrappedNameIndex);       // change to the wrapped name
+
+        int descriptorIndex = c.copyU2();  // descriptor index
+
+        int attrCount = c.copyU2();        // attribute count
+        // need to replicate these attributes (esp Exceptions) in wrapper
+        // so mark this location so we can rewind
+        c.markLocalPositionStart();
+        for (int i = 0; i < attrCount; ++i) {
+            copyAttrForMethod(methodName, accessFlags);
+        }
+        if (true) {
+            System.err.println("   wrapped: " + methodName);
+        }
+
+        // now write the wrapper method
+        c.writeU2(accessFlags & ~ACC_NATIVE);
+        c.writeU2(nameIndex);           // original unwrapped name
+        c.writeU2(descriptorIndex);     // descriptor is the same
+
+        c.writeU2(attrCount + 1);       // wrapped plus a code attribute
+        // rewind to wrapped attributes
+        c.rewind();
+        for (int i = 0; i < attrCount; ++i) {
+            copyAttrForMethod(methodName, accessFlags);
+        }
+
+        // generate a Code attribute for the wrapper method
+        int wrappedIndex = addMethodToConstantPool(getThisClassIndex(),
+                                                   wrappedNameIndex,
+                                                   descriptorIndex);
+        String descriptor = c.constantPoolString(descriptorIndex);
+        createWrapperCodeAttr(nameIndex, accessFlags, descriptor, wrappedIndex);
+
+        // increment method count
+        c.randomAccessWriteU2(methodsCountPos, ++methodsCount);
+    }
+
+    void copyAttrs(int attrCount) {
+        for (int i = 0; i < attrCount; ++i) {
+            copyAttr();
+        }
+    }
+
+    void copyAttr() {
+        c.copy(2);             // name
+        int len = c.copyU4();  // attr len
+        if (verbose) {
+            System.out.println("attr len: " + len);
+        }
+        c.copy(len);           // attribute info
+    }
+
+    void copyAttrForMethod(String methodName, int accessFlags) {
+        int nameIndex = c.copyU2();   // name
+        // check for Code attr
+        if (nameIndex == c.codeAttributeIndex) {
+            try {
+                copyCodeAttr(methodName);
+            } catch (IOException exc) {
+                System.err.println("Code Exception - " + exc);
+                System.exit(1);
+            }
+        } else {
+            int len = c.copyU4();     // attr len
+            if (verbose) {
+                System.out.println("method attr len: " + len);
+            }
+            c.copy(len);              // attribute info
+        }
+    }
+
+    void copyAttrForCode(InjectBytecodes ib) throws IOException {
+        int nameIndex = c.copyU2();   // name
+
+        // check for Code attr
+        if (nameIndex == c.lineNumberAttributeIndex) {
+            ib.copyLineNumberAttr();
+        } else if (nameIndex == c.localVarAttributeIndex) {
+            ib.copyLocalVarAttr();
+        } else {
+            int len = c.copyU4();     // attr len
+            if (verbose) {
+                System.out.println("code attr len: " + len);
+            }
+            c.copy(len);              // attribute info
+        }
+    }
+
+    void copyCodeAttr(String methodName) throws IOException {
+        if (verbose) {
+            System.out.println("Code attr found");
+        }
+        int attrLengthPos = c.generatedPosition();
+        int attrLength = c.copyU4();        // attr len
+        int maxStack = c.readU2();          // max stack
+        c.writeU2(defaultInjector == null? maxStack :
+                  defaultInjector.stackSize(maxStack));  // big enough for injected code
+        c.copyU2();                         // max locals
+        int codeLengthPos = c.generatedPosition();
+        int codeLength = c.copyU4();        // code length
+        if (options.targetMethod != null && !options.targetMethod.equals(methodName)) {
+            c.copy(attrLength - 8); // copy remainder minus already copied
+            return;
+        }
+        if (isSystem) {
+            if (codeLength == 1 && methodName.equals("finalize")) {
+                if (verbose) {
+                    System.out.println("empty system finalizer not instrumented");
+                }
+                c.copy(attrLength - 8); // copy remainder minus already copied
+                return;
+            }
+            if (codeLength == 1 && methodName.equals("<init>")) {
+                if (verbose) {
+                    System.out.println("empty system constructor not instrumented");
+                }
+                if (!options.shouldInstrumentObjectInit) {
+                    c.copy(attrLength - 8); // copy remainder minus already copied
+                    return;
+                }
+            }
+            if (methodName.equals("<clinit>")) {
+                if (verbose) {
+                    System.out.println("system class initializer not instrumented");
+                }
+                c.copy(attrLength - 8); // copy remainder minus already copied
+                return;
+            }
+        }
+        if (options.shouldInstrumentObjectInit
+            && (!className.equals("java/lang/Object")
+                || !methodName.equals("<init>"))) {
+            c.copy(attrLength - 8); // copy remainder minus already copied
+            return;
+        }
+
+        InjectBytecodes ib = new InjectBytecodes(c, codeLength, className, methodName);
+
+        if (options.shouldInstrumentNew) {
+            ib.injectAfter(opc_new, allocInjector);
+            ib.injectAfter(opc_newarray, allocInjector);
+            ib.injectAfter(opc_anewarray, allocInjector);
+            ib.injectAfter(opc_multianewarray, allocInjector);
+        }
+        if (options.shouldInstrumentCall) {
+            ib.inject(0, callInjector.bytecodes(className, methodName, 0));
+        }
+        if (options.shouldInstrumentObjectInit) {
+            ib.inject(0, allocInjector.bytecodes(className, methodName, 0));
+        }
+
+        ib.adjustOffsets();
+
+        // fix up code length
+        int newCodeLength = c.generatedPosition() - (codeLengthPos + 4);
+        c.randomAccessWriteU4(codeLengthPos, newCodeLength);
+        if (verbose) {
+            System.out.println("code length old: " + codeLength +
+                               ", new: " + newCodeLength);
+        }
+
+        ib.copyExceptionTable();
+
+        int attrCount = c.copyU2();
+        for (int i = 0; i < attrCount; ++i) {
+            copyAttrForCode(ib);
+        }
+
+        // fix up attr length
+        int newAttrLength = c.generatedPosition() - (attrLengthPos + 4);
+        c.randomAccessWriteU4(attrLengthPos, newAttrLength);
+        if (verbose) {
+            System.out.println("attr length old: " + attrLength +
+                               ", new: " + newAttrLength);
+        }
+    }
+
+    int nextDescriptorIndex(String descriptor, int index) {
+        switch (descriptor.charAt(index)) {
+        case 'B': // byte
+        case 'C': // char
+        case 'I': // int
+        case 'S': // short
+        case 'Z': // boolean
+        case 'F': // float
+        case 'D': // double
+        case 'J': // long
+            return index + 1;
+        case 'L': // object
+            int i = index + 1;
+            while (descriptor.charAt(i) != ';') {
+                ++i;
+            }
+            return i + 1;
+        case '[': // array
+            return nextDescriptorIndex(descriptor, index + 1);
+        }
+        throw new InternalError("should not reach here");
+    }
+
+    int getWrappedTrackerIndex() {
+        if (wrappedTrackerIndex == 0) {
+            wrappedTrackerIndex = addMethodToConstantPool(profiler,
+                                                          options.wrappedTrackerMethodName,
+                                                          "(Ljava/lang/String;I)V");
+        }
+        return wrappedTrackerIndex;
+    }
+
+    int getThisClassIndex() {
+        if (thisClassIndex == 0) {
+            thisClassIndex = addClassToConstantPool(className);
+        }
+        return thisClassIndex;
+    }
+
+    int computeMaxLocals(String descriptor, int accessFlags) {
+        int index = 1;
+        int slot = 0;
+
+        if ((accessFlags & ACC_STATIC) == 0) {
+            ++slot;
+        }
+        char type;
+        while ((type = descriptor.charAt(index)) != ')') {
+            switch (type) {
+            case 'B': // byte
+            case 'C': // char
+            case 'I': // int
+            case 'S': // short
+            case 'Z': // boolean
+            case 'F': // float
+            case 'L': // object
+            case '[': // array
+                ++slot;
+                break;
+            case 'D': // double
+            case 'J': // long
+                slot += 2;
+                break;
+            }
+            index = nextDescriptorIndex(descriptor, index);
+        }
+
+        return slot;
+    }
+
+
+    void createWrapperCodeAttr(int methodNameIndex, int accessFlags,
+                               String descriptor, int wrappedIndex) {
+        int maxLocals = computeMaxLocals(descriptor, accessFlags);
+
+        c.writeU2(c.codeAttributeIndex);        //
+        int attrLengthPos = c.generatedPosition();
+        c.writeU4(0);                // attr len -- fix up below
+        c.writeU2(maxLocals + 4);    // max stack
+        c.writeU2(maxLocals);        // max locals
+        int codeLengthPos = c.generatedPosition();
+        c.writeU4(0);                // code length -- fix up below
+
+        int methodStringIndex = writeCPEntryString(methodNameIndex);
+
+        c.writeU1(opc_ldc_w);
+        c.writeU2(methodStringIndex);  // send the method name
+        c.writeU1(opc_sipush);
+        c.writeU2(options.fixedIndex);
+        c.writeU1(opc_invokestatic);
+        c.writeU2(getWrappedTrackerIndex());
+
+        // set-up args
+        int index = 1;
+        int slot = 0;
+        if ((accessFlags & ACC_STATIC) == 0) {
+            c.writeU1(opc_aload_0);  // this
+            ++slot;
+        }
+        char type;
+        while ((type = descriptor.charAt(index)) != ')') {
+            switch (type) {
+            case 'B': // byte
+            case 'C': // char
+            case 'I': // int
+            case 'S': // short
+            case 'Z': // boolean
+                c.writeU1(opc_iload);
+                c.writeU1(slot);
+                ++slot;
+                break;
+            case 'F': // float
+                c.writeU1(opc_fload);
+                c.writeU1(slot);
+                ++slot;
+                break;
+            case 'D': // double
+                c.writeU1(opc_dload);
+                c.writeU1(slot);
+                slot += 2;
+                break;
+            case 'J': // long
+                c.writeU1(opc_lload);
+                c.writeU1(slot);
+                slot += 2;
+                break;
+            case 'L': // object
+            case '[': // array
+                c.writeU1(opc_aload);
+                c.writeU1(slot);
+                ++slot;
+                break;
+            }
+            index = nextDescriptorIndex(descriptor, index);
+        }
+
+        // call the wrapped version
+        if ((accessFlags & ACC_STATIC) == 0) {
+            c.writeU1(opc_invokevirtual);
+        } else {
+            c.writeU1(opc_invokestatic);
+        }
+        c.writeU2(wrappedIndex);
+
+        // return correct type
+        switch (descriptor.charAt(index+1)) {
+        case 'B': // byte
+        case 'C': // char
+        case 'I': // int
+        case 'S': // short
+        case 'Z': // boolean
+            c.writeU1(opc_ireturn);
+            break;
+        case 'F': // float
+            c.writeU1(opc_freturn);
+            break;
+        case 'D': // double
+            c.writeU1(opc_dreturn);
+            break;
+        case 'J': // long
+            c.writeU1(opc_lreturn);
+            break;
+        case 'L': // object
+        case '[': // array
+            c.writeU1(opc_areturn);
+            break;
+        case 'V': // void
+            c.writeU1(opc_return);
+            break;
+        }
+
+        // end of code
+
+        // fix up code length
+        int newCodeLength = c.generatedPosition() - (codeLengthPos + 4);
+        c.randomAccessWriteU4(codeLengthPos, newCodeLength);
+
+        c.writeU2(0);                // exception table length
+        c.writeU2(0);                // attribute count
+
+        // fix up attr length
+        int newAttrLength = c.generatedPosition() - (attrLengthPos + 4);
+        c.randomAccessWriteU4(attrLengthPos, newAttrLength);
+    }
+
+
+    int addClassToConstantPool(String className) {
+        int prevSection = c.setSection(0);
+        int classNameIndex = writeCPEntryUtf8(className);
+        int classIndex = writeCPEntryClass(classNameIndex);
+        c.setSection(prevSection);
+        return classIndex;
+    }
+
+    int addMethodToConstantPool(int classIndex,
+                                String methodName,
+                                String descr) {
+        int prevSection = c.setSection(0);
+        int methodNameIndex = writeCPEntryUtf8(methodName);
+        int descrIndex = writeCPEntryUtf8(descr);
+        c.setSection(prevSection);
+        return addMethodToConstantPool(classIndex, methodNameIndex, descrIndex);
+    }
+
+    int addMethodToConstantPool(int classIndex,
+                                int methodNameIndex,
+                                int descrIndex) {
+        int prevSection = c.setSection(0);
+        int nameAndTypeIndex = writeCPEntryNameAndType(methodNameIndex,
+                                                       descrIndex);
+        int methodIndex = writeCPEntryMethodRef(classIndex, nameAndTypeIndex);
+        c.setSection(prevSection);
+        return methodIndex;
+    }
+
+    int writeCPEntryUtf8(String str) {
+        int prevSection = c.setSection(0);
+        int len = str.length();
+        c.writeU1(CONSTANT_UTF8); // Utf8 tag
+        c.writeU2(len);
+        for (int i = 0; i < len; ++i) {
+            c.writeU1(str.charAt(i));
+        }
+        c.setSection(prevSection);
+        return constantPoolCount++;
+    }
+
+    int writeCPEntryString(int utf8Index) {
+        int prevSection = c.setSection(0);
+        c.writeU1(CONSTANT_STRING);
+        c.writeU2(utf8Index);
+        c.setSection(prevSection);
+        return constantPoolCount++;
+    }
+
+    int writeCPEntryClass(int classNameIndex) {
+        int prevSection = c.setSection(0);
+        c.writeU1(CONSTANT_CLASS);
+        c.writeU2(classNameIndex);
+        c.setSection(prevSection);
+        return constantPoolCount++;
+    }
+
+    int writeCPEntryNameAndType(int nameIndex, int descrIndex) {
+        int prevSection = c.setSection(0);
+        c.writeU1(CONSTANT_NAMEANDTYPE);
+        c.writeU2(nameIndex);
+        c.writeU2(descrIndex);
+        c.setSection(prevSection);
+        return constantPoolCount++;
+    }
+
+    int writeCPEntryMethodRef(int classIndex, int nameAndTypeIndex) {
+        int prevSection = c.setSection(0);
+        c.writeU1(CONSTANT_METHOD);
+        c.writeU2(classIndex);
+        c.writeU2(nameAndTypeIndex);
+        c.setSection(prevSection);
+        return constantPoolCount++;
+    }
+}
diff --git a/jdk/test/java/lang/instrument/ilib/InjectBytecodes.java b/jdk/test/java/lang/instrument/ilib/InjectBytecodes.java
new file mode 100644
index 0000000..4dd3ee6
--- /dev/null
+++ b/jdk/test/java/lang/instrument/ilib/InjectBytecodes.java
@@ -0,0 +1,769 @@
+/*
+ * Copyright 2005 Sun Microsystems, Inc.  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 Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
+ * CA 95054 USA or visit www.sun.com if you need additional information or
+ * have any questions.
+ */
+
+/*
+ * An extension of BinaryCode that allows code to be printed.
+ * Includes printing of disassembled byte codes, exception info,
+ * local variable and line number info.
+ *
+ */
+
+package ilib;
+
+import java.io.ByteArrayInputStream;
+import java.io.CharArrayWriter;
+import java.io.DataInputStream;
+import java.io.IOException;
+import java.io.PrintWriter;
+import java.io.PrintStream;
+import java.util.Map;
+import java.util.HashMap;
+
+class InjectBytecodes implements RuntimeConstants {
+
+    private final ClassReaderWriter c;
+    private final PrintStream output;
+    private final int length;
+    private final int[] map;
+    private final byte[] widening;
+    private final Injector[] before = new Injector[256];
+    private final Injector[] after  = new Injector[256];
+    private final String className;
+    private final String methodName;
+    private final Map<Integer,byte[]> snippets = new HashMap<Integer,byte[]>();
+
+    private int pos;
+    private int newPos;
+
+    private class Span {
+        final int delta;
+        final int target;
+        final int newDelta;
+        final int newTarget;
+
+        Span(int delta) {
+            this.delta = delta;
+            this.target = pos + delta;
+            this.newTarget = map[target];
+            this.newDelta = newTarget - newPos;
+        }
+    }
+
+    /**
+     * Constructor
+     */
+    InjectBytecodes(ClassReaderWriter c, int length,
+                    String className, String methodName) {
+        this.c = c;
+        this.output = System.out;
+        this.length = length;
+        this.map = new int[length + 1];
+        this.widening = new byte[length + 1];
+        this.className = className;
+        this.methodName = methodName;
+        c.markLocalPositionStart();
+        for (int i = 0; i <= length; ++i) {
+            map[i] = i;
+        }
+    }
+
+    public void inject(int at, byte[] newCode) {
+        snippets.put(new Integer(at), newCode);
+        trace("external ");
+        inject(at, newCode.length);
+    }
+
+    private void inject(int at, int len) {
+        if (Inject.verbose) {
+            traceln("Injecting " + len + " at " + at);
+        }
+        for (int i = at; i <= length; ++i) {
+            map[i] += len;
+        }
+    }
+
+    private void widen(int at, int len) {
+        int delta = len - widening[at];
+        if (Inject.verbose) {
+            traceln();
+            traceln("Widening to " + len + " at " + at);
+        }
+        inject(c.localPosition(), delta);  // inject at end of instruction
+        widening[at] = (byte)len;          // mark at beginning of instruction
+    }
+
+    public void injectBefore(int code, Injector inj) {
+        before[code] = inj;
+    }
+
+    public void injectAfter(int code, Injector inj) {
+        after[code] = inj;
+    }
+
+    private void trace(String str) {
+        if (Inject.verbose) {
+            output.print(str);
+        }
+    }
+
+    private void traceln(String str) {
+        if (Inject.verbose) {
+            output.println(str);
+        }
+    }
+
+    private void traceln() {
+        if (Inject.verbose) {
+            output.println();
+        }
+    }
+
+    private void trace(int i) {
+        if (Inject.verbose) {
+            output.print(i);
+        }
+    }
+
+    /**
+     * Print an integer so that it takes 'length' characters in
+     * the output.  Temporary until formatting code is stable.
+     */
+    private void traceFixedWidthInt(int x, int length) {
+        if (Inject.verbose) {
+            CharArrayWriter baStream = new CharArrayWriter();
+            PrintWriter pStream = new PrintWriter(baStream);
+            pStream.print(x);
+            String str = baStream.toString();
+            for (int cnt = length - str.length(); cnt > 0; --cnt)
+                trace(" ");
+            trace(str);
+        }
+    }
+
+    void adjustOffsets() throws IOException {
+        if (Inject.verbose) {
+            traceln();
+            traceln("Method " + methodName);
+            traceln();
+        }
+        c.rewind();
+        while (c.localPosition() < length) {
+            insertAtInstruction();
+        }
+        trace("Searching for adjustments...");
+        c.rewind();
+        while (c.localPosition() < length) {
+            if (!adjustInstruction()) {
+                c.rewind();
+                traceln();
+                traceln("Restarting adjustments after change...");
+            }
+        }
+        // write the new bytecodes
+        traceln();
+        traceln();
+        trace("Writing new code...");
+        c.rewind();
+        while (c.localPosition() < length) {
+            writeInstruction();
+        }
+        if (!snippets.isEmpty()) {
+            throw new Error("not all snippets written");
+        }
+    }
+
+    /**
+     * Walk one instruction inserting instrumentation at specified instructions
+     */
+    private void insertAtInstruction() throws IOException {
+        pos = c.localPosition();
+        int opcode = c.readU1();
+        if (opcode == opc_wide) {
+            // no support for instrumenting wide instructions
+            int wopcode = c.readU1();
+            int lvIndex = c.readU2();
+            switch (wopcode) {
+            case opc_aload: case opc_astore:
+            case opc_fload: case opc_fstore:
+            case opc_iload: case opc_istore:
+            case opc_lload: case opc_lstore:
+            case opc_dload: case opc_dstore:
+            case opc_ret:
+                break;
+
+            case opc_iinc:
+                c.readS2();
+                break;
+            default:
+                throw new Error("Invalid wide opcode: " + wopcode);
+            }
+        } else {
+            Injector inj;
+
+            inj = before[opcode];
+            if (inj != null) {
+                inject(pos, inj.bytecodes(className, methodName, pos));
+            }
+
+            switch (opcode) {
+            case opc_tableswitch:{
+                int header = (pos+1+3) & (~3);        // 4byte boundry
+                c.skip(header - (pos+1));             // skip old padding
+
+                c.readU4();
+                int low = c.readU4();
+                int high = c.readU4();
+                c.skip((high+1-low) * 4);
+                break;
+            }
+
+            case opc_lookupswitch:{
+                int header = (pos+1+3) & (~3);        // 4byte boundry
+                c.skip(header - (pos+1));             // skip padding
+
+                c.readU4();
+                int npairs = c.readU4();
+                c.skip(npairs * 8);
+                break;
+            }
+
+            default: {
+                int instrLen = opcLengths[opcode];
+                c.skip(instrLen-1);
+            }
+            }
+            inj = after[opcode];
+            if (inj != null) {
+                pos = c.localPosition();
+                inject(pos, inj.bytecodes(className, methodName, pos));
+            }
+        }
+    }
+
+    /**
+     * Walk one instruction adjusting for insertions
+     */
+    private boolean adjustInstruction() throws IOException {
+        pos = c.localPosition();
+        newPos = map[pos];
+        int opcode = c.readU1();
+        if (Inject.verbose) {
+            traceln();
+            traceFixedWidthInt(pos, 4);
+            traceFixedWidthInt(newPos, 4);
+            trace(" ");
+        }
+        if (opcode == opc_wide) {
+            int wopcode = c.readU1();
+            int lvIndex = c.readU2();
+            if (Inject.verbose) {
+                trace(opcNames[wopcode] + "_w ");
+            }
+            switch (wopcode) {
+            case opc_aload: case opc_astore:
+            case opc_fload: case opc_fstore:
+            case opc_iload: case opc_istore:
+            case opc_lload: case opc_lstore:
+            case opc_dload: case opc_dstore:
+            case opc_ret:
+                trace(lvIndex);
+                break;
+
+            case opc_iinc:
+                int constVal = c.readS2();
+                if (Inject.verbose) {
+                    trace(lvIndex + " " + constVal);
+                }
+                break;
+            default:
+                throw new Error("Invalid wide opcode: " + wopcode);
+            }
+        } else {
+            if (Inject.verbose) {
+                trace(opcNames[opcode]);
+            }
+            switch (opcode) {
+
+            case opc_tableswitch:{
+                int widened = widening[pos];
+                int header = (pos+1+3) & (~3);        // 4byte boundry
+                int newHeader = (newPos+1+3) & (~3);  // 4byte boundry
+
+                c.skip(header - (pos+1));             // skip old padding
+
+                Span defaultSkip = new Span(c.readU4());
+                int low = c.readU4();
+                int high = c.readU4();
+                if (Inject.verbose) {
+                    trace(" " + low + " to " + high);
+                    trace(": default= [was] " + defaultSkip.target);
+                    trace(" [now] " + defaultSkip.newTarget);
+                    for (int i = low; i <= high; ++i) {
+                        Span jump = new Span(c.readU4());
+                        traceln("");
+                        trace('\t');
+                        traceFixedWidthInt(i, 5);
+                        trace(": " + jump.newTarget);
+                    }
+                } else {
+                    c.skip((high+1-low) * 4);
+                }
+                int newPadding = newHeader - newPos;
+                int oldPadding = header - pos;
+                int deltaPadding = newPadding - oldPadding;
+                if (widened != deltaPadding) {
+                    widen(pos, deltaPadding);
+                    return false;       // cause restart
+                }
+                break;
+            }
+
+            case opc_lookupswitch:{
+                int widened = widening[pos];
+                int header = (pos+1+3) & (~3);        // 4byte boundry
+                int newHeader = (newPos+1+3) & (~3);  // 4byte boundry
+
+                c.skip(header - (pos+1));             // skip old padding
+
+                Span defaultSkip = new Span(c.readU4());
+                int npairs = c.readU4();
+                if (Inject.verbose) {
+                    trace(" npairs: " + npairs);
+                    trace(": default= [was] " + defaultSkip.target);
+                    trace(" [now] " + defaultSkip.newTarget);
+                    for (int i = 0; i< npairs; ++i) {
+                        int match = c.readU4();
+                        Span jump = new Span(c.readU4());
+                        traceln("");
+                        trace('\t');
+                        traceFixedWidthInt(match, 5);
+                        trace(": " + jump.newTarget);
+                    }
+                } else {
+                    c.skip(npairs * 8);
+                }
+                int newPadding = newHeader - newPos;
+                int oldPadding = header - pos;
+                int deltaPadding = newPadding - oldPadding;
+                if (widened != deltaPadding) {
+                    widen(pos, deltaPadding);
+                    return false;       // cause restart
+                }
+                break;
+            }
+
+            case opc_jsr: case opc_goto:
+            case opc_ifeq: case opc_ifge: case opc_ifgt:
+            case opc_ifle: case opc_iflt: case opc_ifne:
+            case opc_if_icmpeq: case opc_if_icmpne: case opc_if_icmpge:
+            case opc_if_icmpgt: case opc_if_icmple: case opc_if_icmplt:
+            case opc_if_acmpeq: case opc_if_acmpne:
+            case opc_ifnull: case opc_ifnonnull: {
+                int widened = widening[pos];
+                Span jump = new Span(c.readS2());
+                if (widened == 0) {  // not yet widened
+                    int newDelta = jump.newDelta;
+                    if ((newDelta < -32768) || (newDelta > 32767)) {
+                        switch (opcode) {
+                        case opc_jsr: case opc_goto:
+                            widen(pos, 2); // will convert to wide
+                            break;
+                        default:
+                            widen(pos, 5); // will inject goto_w
+                            break;
+                        }
+                        return false;       // cause restart
+                    }
+                }
+                if (Inject.verbose) {
+                    trace(" [was] " + jump.target + " ==> " +
+                          " [now] " + jump.newTarget);
+                }
+                break;
+            }
+
+            case opc_jsr_w:
+            case opc_goto_w: {
+                Span jump = new Span(c.readU4());
+                if (Inject.verbose) {
+                    trace(" [was] " + jump.target +
+                          " [now] " + jump.newTarget);
+                }
+                break;
+            }
+
+            default: {
+                int instrLen = opcLengths[opcode];
+                c.skip(instrLen-1);
+                break;
+            }
+            }
+        }
+        return true;     // successful return
+    }
+
+
+    /**
+     * Walk one instruction writing the transformed instruction.
+     */
+    private void writeInstruction() throws IOException {
+        pos = c.localPosition();
+        newPos = map[pos];
+        byte[] newCode = snippets.remove(new Integer(pos));
+        if (newCode != null) {
+            traceln();
+            traceFixedWidthInt(pos, 4);
+            trace(" ... -- Inserting new code");
+            c.writeBytes(newCode);
+        }
+        int opcode = c.readU1();
+        if (Inject.verbose) {
+            traceln();
+            traceFixedWidthInt(pos, 4);
+            traceFixedWidthInt(newPos, 4);
+            trace(" ");
+        }
+        if (opcode == opc_wide) {
+            int wopcode = c.readU1();
+            int lvIndex = c.readU2();
+            if (Inject.verbose) {
+                trace(opcNames[wopcode] + "_w ");
+            }
+            c.writeU1(opcode);
+            c.writeU1(wopcode);
+            c.writeU2(lvIndex);
+            switch (wopcode) {
+            case opc_aload: case opc_astore:
+            case opc_fload: case opc_fstore:
+            case opc_iload: case opc_istore:
+            case opc_lload: case opc_lstore:
+            case opc_dload: case opc_dstore:
+            case opc_ret:
+                trace(lvIndex);
+                break;
+
+            case opc_iinc:
+                int constVal = c.readS2();
+                c.writeU2(constVal);  // ??? U vs S
+                if (Inject.verbose) {
+                    trace(lvIndex + " " + constVal);
+                }
+                break;
+            default:
+                throw new Error("Invalid wide opcode: " + wopcode);
+            }
+        } else {
+            if (Inject.verbose) {
+                trace(opcNames[opcode]);
+            }
+            switch (opcode) {
+
+            case opc_tableswitch:{
+                int header = (pos+1+3) & (~3);   // 4byte boundry
+                int newHeader = (newPos+1+3) & (~3); // 4byte boundry
+
+                c.skip(header - (pos+1));             // skip old padding
+
+                Span defaultSkip = new Span(c.readU4());
+                int low = c.readU4();
+                int high = c.readU4();
+
+                c.writeU1(opcode);                   // copy instruction
+                for (int i = newPos+1; i < newHeader; ++i) {
+                    c.writeU1(0);                    // write new padding
+                }
+                c.writeU4(defaultSkip.newDelta);
+                c.writeU4(low);
+                c.writeU4(high);
+
+                if (Inject.verbose) {
+                    trace(" " + low + " to " + high);
+                    trace(": default= [was] " + defaultSkip.target);
+                    trace(" [now] " + defaultSkip.newTarget);
+                }
+                for (int i = low; i <= high; ++i) {
+                    Span jump = new Span(c.readU4());
+                    c.writeU4(jump.newDelta);
+                    if (Inject.verbose) {
+                        traceln("");
+                        trace('\t');
+                        traceFixedWidthInt(i, 5);
+                        trace(": " + jump.newTarget);
+                    }
+                }
+                break;
+            }
+
+            case opc_lookupswitch:{
+                int header = (pos+1+3) & (~3);   // 4byte boundry
+                int newHeader = (newPos+1+3) & (~3); // 4byte boundry
+
+                c.skip(header - (pos+1));             // skip old padding
+
+                Span defaultSkip = new Span(c.readU4());
+                int npairs = c.readU4();
+                if (Inject.verbose) {
+                    trace(" npairs: " + npairs);
+                    trace(": default= [was] " + defaultSkip.target);
+                    trace(" [now] " + defaultSkip.newTarget);
+                }
+                c.writeU1(opcode);                   // copy instruction
+                for (int i = newPos+1; i < newHeader; ++i) {
+                    c.writeU1(0);                    // write new padding
+                }
+                c.writeU4(defaultSkip.newDelta);
+                c.writeU4(npairs);
+                for (int i = 0; i< npairs; ++i) {
+                    int match = c.readU4();
+                    Span jump = new Span(c.readU4());
+                    c.writeU4(match);
+                    c.writeU4(jump.newDelta);
+                    if (Inject.verbose) {
+                        traceln("");
+                        trace('\t');
+                        traceFixedWidthInt(match, 5);
+                        trace(": " + jump.newTarget);
+                    }
+                }
+                break;
+            }
+
+            case opc_jsr: case opc_goto:
+            case opc_ifeq: case opc_ifge: case opc_ifgt:
+            case opc_ifle: case opc_iflt: case opc_ifne:
+            case opc_if_icmpeq: case opc_if_icmpne: case opc_if_icmpge:
+            case opc_if_icmpgt: case opc_if_icmple: case opc_if_icmplt:
+            case opc_if_acmpeq: case opc_if_acmpne:
+            case opc_ifnull: case opc_ifnonnull: {
+                int widened = widening[pos];
+                Span jump = new Span(c.readS2());
+                int newOpcode = opcode;   // default to unchanged
+                if (widened == 0) {        // not widened
+                    c.writeU1(opcode);    // rewrite instruction
+                    c.writeU2(jump.newDelta);
+                } else if (widened == 2) { // wide form
+                    switch (opcode) {
+                    case opc_jsr:
+                        newOpcode = opc_jsr_w;
+                        break;
+                    case opc_goto:
+                        newOpcode = opc_jsr_w;
+                        break;
+                    default:
+                        throw new Error("unexpected opcode: " +
+                                   opcode);
+                    }
+                    c.writeU1(newOpcode);      // write wide instruction
+                    c.writeU4(jump.newDelta);  // write new and wide delta
+                } else if (widened == 5) {      // insert goto_w
+                    switch (opcode) {
+                    case opc_ifeq:
+                        newOpcode = opc_ifne;
+                        break;
+                    case opc_ifge:
+                        newOpcode = opc_iflt;
+                        break;
+                    case opc_ifgt:
+                        newOpcode = opc_ifle;
+                        break;
+                    case opc_ifle:
+                        newOpcode = opc_ifgt;
+                        break;
+                    case opc_iflt:
+                        newOpcode = opc_ifge;
+                        break;
+                    case opc_ifne:
+                        newOpcode = opc_ifeq;
+                        break;
+                    case opc_if_icmpeq:
+                        newOpcode = opc_if_icmpne;
+                        break;
+                    case opc_if_icmpne:
+                        newOpcode = opc_if_icmpeq;
+                        break;
+                    case opc_if_icmpge:
+                        newOpcode = opc_if_icmplt;
+                        break;
+                    case opc_if_icmpgt:
+                        newOpcode = opc_if_icmple;
+                        break;
+                    case opc_if_icmple:
+                        newOpcode = opc_if_icmpgt;
+                        break;
+                    case opc_if_icmplt:
+                        newOpcode = opc_if_icmpge;
+                        break;
+                    case opc_if_acmpeq:
+                        newOpcode = opc_if_acmpne;
+                        break;
+                    case opc_if_acmpne:
+                        newOpcode = opc_if_acmpeq;
+                        break;
+                    case opc_ifnull:
+                        newOpcode = opc_ifnonnull;
+                        break;
+                    case opc_ifnonnull:
+                        newOpcode = opc_ifnull;
+                        break;
+                    default:
+                        throw new Error("unexpected opcode: " +
+                                   opcode);
+                    }
+                    c.writeU1(newOpcode); // write inverse branch
+                    c.writeU2(3 + 5);     // beyond if and goto_w
+                    c.writeU1(opc_goto_w);// add a goto_w
+                    c.writeU4(jump.newDelta);  // write new and wide delta
+                } else {
+                    throw new Error("unexpected widening");
+                }
+
+                if (Inject.verbose) {
+                    trace(" [was] " + jump.target + " ==> " +
+                          opcNames[newOpcode] +
+                          " [now] " + jump.newTarget);
+                }
+                break;
+            }
+
+            case opc_jsr_w:
+            case opc_goto_w: {
+                Span jump = new Span(c.readU4());
+                c.writeU1(opcode);        // instruction itself
+                c.writeU4(jump.newDelta);
+                if (Inject.verbose) {
+                    trace(" [was] " + jump.target +
+                          " [now] " + jump.newTarget);
+                }
+                break;
+            }
+
+            default: {
+                int instrLen = opcLengths[opcode];
+                c.writeU1(opcode);        // instruction itself
+                c.copy(instrLen-1);
+            }
+            }
+        }
+    }
+
+    /**
+     * Copy the exception table for this method code
+     */
+    void copyExceptionTable() throws IOException {
+        int tableLength = c.copyU2();   // exception table len
+        if (tableLength > 0) {
+            traceln();
+            traceln("Exception table:");
+            traceln(" from:old/new  to:old/new target:old/new type");
+            for (int tcnt = tableLength; tcnt > 0; --tcnt) {
+                int startPC = c.readU2();
+                int newStartPC = map[startPC];
+                c.writeU2(newStartPC);
+                int endPC = c.readU2();
+                int newEndPC = map[endPC];
+                c.writeU2(newEndPC);
+                int handlerPC = c.readU2();
+                int newHandlerPC = map[handlerPC];
+                c.writeU2(newHandlerPC);
+                int catchType = c.copyU2();
+                if (Inject.verbose) {
+                    traceFixedWidthInt(startPC, 6);
+                    traceFixedWidthInt(newStartPC, 6);
+                    traceFixedWidthInt(endPC, 6);
+                    traceFixedWidthInt(newEndPC, 6);
+                    traceFixedWidthInt(handlerPC, 6);
+                    traceFixedWidthInt(newHandlerPC, 6);
+                    trace("    ");
+                    if (catchType == 0)
+                        traceln("any");
+                    else {
+                        traceln("" + catchType);
+                    }
+                }
+            }
+        }
+    }
+
+    /**
+     * Copy the line number table for this method code
+     */
+    void copyLineNumberAttr() throws IOException {
+        // name index already read
+        c.copy(4);                      // attr len
+        int tableLength = c.copyU2();   // line table len
+        if (tableLength > 0) {
+            if (Inject.verbose) {
+                traceln();
+                traceln("Line numbers for method " + methodName);
+            }
+            for (int tcnt = tableLength; tcnt > 0; --tcnt) {
+                int startPC = c.readU2();
+                int newStartPC = map[startPC];
+                c.writeU2(newStartPC);
+                int lineNumber = c.copyU2();
+                if (Inject.verbose) {
+                    traceln("   line " + lineNumber +
+                            ": [was] " + startPC +
+                            " [now] " + newStartPC);
+                }
+            }
+        }
+    }
+
+    /**
+     * Copy the local variable table for this method code
+     */
+    void copyLocalVarAttr() throws IOException {
+        // name index already read
+        c.copy(4);                      // attr len
+        int tableLength = c.copyU2();   // local var table len
+        if (tableLength > 0) {
+            if (Inject.verbose) {
+                traceln();
+                traceln("Local variables for method " + methodName);
+            }
+            for (int tcnt = tableLength; tcnt > 0; --tcnt) {
+                int startPC = c.readU2();
+                int newStartPC = map[startPC];
+                c.writeU2(newStartPC);
+                int length = c.readU2();
+                int endPC = startPC + length;
+                int newEndPC = map[endPC];
+                int newLength = newEndPC - newStartPC;
+                c.writeU2(newLength);
+                int nameIndex = c.copyU2();
+                int descriptorIndex = c.copyU2();
+                int index = c.copyU2();
+                if (Inject.verbose) {
+                    trace("   ");
+                    trace(descriptorIndex);
+                    trace(" ");
+                    trace(nameIndex);
+                    traceln("  pc= [was] " + startPC + " [now] " + newStartPC +
+                            ", length= [was] " + length + " [now] " + newLength +
+                            ", slot=" + index);
+                }
+            }
+        }
+    }
+}
diff --git a/jdk/test/java/lang/instrument/ilib/Injector.java b/jdk/test/java/lang/instrument/ilib/Injector.java
new file mode 100644
index 0000000..5d04b46
--- /dev/null
+++ b/jdk/test/java/lang/instrument/ilib/Injector.java
@@ -0,0 +1,28 @@
+/*
+ * Copyright 2005 Sun Microsystems, Inc.  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 Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
+ * CA 95054 USA or visit www.sun.com if you need additional information or
+ * have any questions.
+ */
+
+package ilib;
+
+interface Injector {
+    byte[] bytecodes(String className, String methodName, int location);
+}
diff --git a/jdk/test/java/lang/instrument/ilib/Options.java b/jdk/test/java/lang/instrument/ilib/Options.java
new file mode 100644
index 0000000..090833d
--- /dev/null
+++ b/jdk/test/java/lang/instrument/ilib/Options.java
@@ -0,0 +1,40 @@
+/*
+ * Copyright 2005 Sun Microsystems, Inc.  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 Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
+ * CA 95054 USA or visit www.sun.com if you need additional information or
+ * have any questions.
+ */
+
+package ilib;
+
+public class Options {
+    public boolean shouldInstrumentNew = false;
+    public boolean shouldInstrumentCall = false;
+    public boolean shouldInstrumentIndexed = false;
+    public boolean shouldInstrumentObject = false;
+    public boolean shouldInstrumentObjectInit = false;
+    public boolean shouldInstrumentNativeMethods = false;
+    public String  targetMethod = null;
+    public int     fixedIndex = 0;
+    public String  trackerClassName = "MyTracker";
+    public String  allocTrackerMethodName = "allocTracker";
+    public String  callTrackerMethodName = "callTracker";
+    public String  wrappedTrackerMethodName = "wrappedTracker";
+    public String  wrappedPrefix = "wrapped_up_";
+}
diff --git a/jdk/test/java/lang/instrument/ilib/RuntimeConstants.java b/jdk/test/java/lang/instrument/ilib/RuntimeConstants.java
new file mode 100644
index 0000000..b78ef19
--- /dev/null
+++ b/jdk/test/java/lang/instrument/ilib/RuntimeConstants.java
@@ -0,0 +1,732 @@
+/*
+ * Copyright 2005 Sun Microsystems, Inc.  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 Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
+ * CA 95054 USA or visit www.sun.com if you need additional information or
+ * have any questions.
+ */
+
+package ilib;
+
+public interface RuntimeConstants {
+
+    /* Signature Characters */
+    char   SIGC_VOID                  = 'V';
+    String SIG_VOID                   = "V";
+    char   SIGC_BOOLEAN               = 'Z';
+    String SIG_BOOLEAN                = "Z";
+    char   SIGC_BYTE                  = 'B';
+    String SIG_BYTE                   = "B";
+    char   SIGC_CHAR                  = 'C';
+    String SIG_CHAR                   = "C";
+    char   SIGC_SHORT                 = 'S';
+    String SIG_SHORT                  = "S";
+    char   SIGC_INT                   = 'I';
+    String SIG_INT                    = "I";
+    char   SIGC_LONG                  = 'J';
+    String SIG_LONG                   = "J";
+    char   SIGC_FLOAT                 = 'F';
+    String SIG_FLOAT                  = "F";
+    char   SIGC_DOUBLE                = 'D';
+    String SIG_DOUBLE                 = "D";
+    char   SIGC_ARRAY                 = '[';
+    String SIG_ARRAY                  = "[";
+    char   SIGC_CLASS                 = 'L';
+    String SIG_CLASS                  = "L";
+    char   SIGC_METHOD                = '(';
+    String SIG_METHOD                 = "(";
+    char   SIGC_ENDCLASS              = ';';
+    String SIG_ENDCLASS               = ";";
+    char   SIGC_ENDMETHOD             = ')';
+    String SIG_ENDMETHOD              = ")";
+    char   SIGC_PACKAGE               = '/';
+    String SIG_PACKAGE                = "/";
+
+    /* Class File Constants */
+    int JAVA_MAGIC                   = 0xcafebabe;
+    int JAVA_MIN_SUPPORTED_VERSION   = 45;
+    int JAVA_MAX_SUPPORTED_VERSION   = 48;
+    int JAVA_MAX_SUPPORTED_MINOR_VERSION = 0;
+
+    /* Generate class file version for 1.1  by default */
+    int JAVA_DEFAULT_VERSION         = 45;
+    int JAVA_DEFAULT_MINOR_VERSION   = 3;
+
+    /* Constant table */
+    int CONSTANT_UTF8                = 1;
+    int CONSTANT_UNICODE             = 2;
+    int CONSTANT_INTEGER             = 3;
+    int CONSTANT_FLOAT               = 4;
+    int CONSTANT_LONG                = 5;
+    int CONSTANT_DOUBLE              = 6;
+    int CONSTANT_CLASS               = 7;
+    int CONSTANT_STRING              = 8;
+    int CONSTANT_FIELD               = 9;
+    int CONSTANT_METHOD              = 10;
+    int CONSTANT_INTERFACEMETHOD     = 11;
+    int CONSTANT_NAMEANDTYPE         = 12;
+
+    /* Access and modifier flags */
+    int ACC_PUBLIC                   = 0x00000001;
+    int ACC_PRIVATE                  = 0x00000002;
+    int ACC_PROTECTED                = 0x00000004;
+    int ACC_STATIC                   = 0x00000008;
+    int ACC_FINAL                    = 0x00000010;
+    int ACC_SYNCHRONIZED             = 0x00000020;
+    int ACC_VOLATILE                 = 0x00000040;
+    int ACC_TRANSIENT                = 0x00000080;
+    int ACC_NATIVE                   = 0x00000100;
+    int ACC_INTERFACE                = 0x00000200;
+    int ACC_ABSTRACT                 = 0x00000400;
+    int ACC_SUPER                    = 0x00000020;
+    int ACC_STRICT                   = 0x00000800;
+
+    /* Type codes */
+    int T_CLASS                      = 0x00000002;
+    int T_BOOLEAN                    = 0x00000004;
+    int T_CHAR                       = 0x00000005;
+    int T_FLOAT                      = 0x00000006;
+    int T_DOUBLE                     = 0x00000007;
+    int T_BYTE                       = 0x00000008;
+    int T_SHORT                      = 0x00000009;
+    int T_INT                        = 0x0000000a;
+    int T_LONG                       = 0x0000000b;
+
+    /* Opcodes */
+    int opc_try                      = -3;
+    int opc_dead                     = -2;
+    int opc_label                    = -1;
+    int opc_nop                      = 0;
+    int opc_aconst_null              = 1;
+    int opc_iconst_m1                = 2;
+    int opc_iconst_0                 = 3;
+    int opc_iconst_1                 = 4;
+    int opc_iconst_2                 = 5;
+    int opc_iconst_3                 = 6;
+    int opc_iconst_4                 = 7;
+    int opc_iconst_5                 = 8;
+    int opc_lconst_0                 = 9;
+    int opc_lconst_1                 = 10;
+    int opc_fconst_0                 = 11;
+    int opc_fconst_1                 = 12;
+    int opc_fconst_2                 = 13;
+    int opc_dconst_0                 = 14;
+    int opc_dconst_1                 = 15;
+    int opc_bipush                   = 16;
+    int opc_sipush                   = 17;
+    int opc_ldc                      = 18;
+    int opc_ldc_w                    = 19;
+    int opc_ldc2_w                   = 20;
+    int opc_iload                    = 21;
+    int opc_lload                    = 22;
+    int opc_fload                    = 23;
+    int opc_dload                    = 24;
+    int opc_aload                    = 25;
+    int opc_iload_0                  = 26;
+    int opc_iload_1                  = 27;
+    int opc_iload_2                  = 28;
+    int opc_iload_3                  = 29;
+    int opc_lload_0                  = 30;
+    int opc_lload_1                  = 31;
+    int opc_lload_2                  = 32;
+    int opc_lload_3                  = 33;
+    int opc_fload_0                  = 34;
+    int opc_fload_1                  = 35;
+    int opc_fload_2                  = 36;
+    int opc_fload_3                  = 37;
+    int opc_dload_0                  = 38;
+    int opc_dload_1                  = 39;
+    int opc_dload_2                  = 40;
+    int opc_dload_3                  = 41;
+    int opc_aload_0                  = 42;
+    int opc_aload_1                  = 43;
+    int opc_aload_2                  = 44;
+    int opc_aload_3                  = 45;
+    int opc_iaload                   = 46;
+    int opc_laload                   = 47;
+    int opc_faload                   = 48;
+    int opc_daload                   = 49;
+    int opc_aaload                   = 50;
+    int opc_baload                   = 51;
+    int opc_caload                   = 52;
+    int opc_saload                   = 53;
+    int opc_istore                   = 54;
+    int opc_lstore                   = 55;
+    int opc_fstore                   = 56;
+    int opc_dstore                   = 57;
+    int opc_astore                   = 58;
+    int opc_istore_0                 = 59;
+    int opc_istore_1                 = 60;
+    int opc_istore_2                 = 61;
+    int opc_istore_3                 = 62;
+    int opc_lstore_0                 = 63;
+    int opc_lstore_1                 = 64;
+    int opc_lstore_2                 = 65;
+    int opc_lstore_3                 = 66;
+    int opc_fstore_0                 = 67;
+    int opc_fstore_1                 = 68;
+    int opc_fstore_2                 = 69;
+    int opc_fstore_3                 = 70;
+    int opc_dstore_0                 = 71;
+    int opc_dstore_1                 = 72;
+    int opc_dstore_2                 = 73;
+    int opc_dstore_3                 = 74;
+    int opc_astore_0                 = 75;
+    int opc_astore_1                 = 76;
+    int opc_astore_2                 = 77;
+    int opc_astore_3                 = 78;
+    int opc_iastore                  = 79;
+    int opc_lastore                  = 80;
+    int opc_fastore                  = 81;
+    int opc_dastore                  = 82;
+    int opc_aastore                  = 83;
+    int opc_bastore                  = 84;
+    int opc_castore                  = 85;
+    int opc_sastore                  = 86;
+    int opc_pop                      = 87;
+    int opc_pop2                     = 88;
+    int opc_dup                      = 89;
+    int opc_dup_x1                   = 90;
+    int opc_dup_x2                   = 91;
+    int opc_dup2                     = 92;
+    int opc_dup2_x1                  = 93;
+    int opc_dup2_x2                  = 94;
+    int opc_swap                     = 95;
+    int opc_iadd                     = 96;
+    int opc_ladd                     = 97;
+    int opc_fadd                     = 98;
+    int opc_dadd                     = 99;
+    int opc_isub                     = 100;
+    int opc_lsub                     = 101;
+    int opc_fsub                     = 102;
+    int opc_dsub                     = 103;
+    int opc_imul                     = 104;
+    int opc_lmul                     = 105;
+    int opc_fmul                     = 106;
+    int opc_dmul                     = 107;
+    int opc_idiv                     = 108;
+    int opc_ldiv                     = 109;
+    int opc_fdiv                     = 110;
+    int opc_ddiv                     = 111;
+    int opc_irem                     = 112;
+    int opc_lrem                     = 113;
+    int opc_frem                     = 114;
+    int opc_drem                     = 115;
+    int opc_ineg                     = 116;
+    int opc_lneg                     = 117;
+    int opc_fneg                     = 118;
+    int opc_dneg                     = 119;
+    int opc_ishl                     = 120;
+    int opc_lshl                     = 121;
+    int opc_ishr                     = 122;
+    int opc_lshr                     = 123;
+    int opc_iushr                    = 124;
+    int opc_lushr                    = 125;
+    int opc_iand                     = 126;
+    int opc_land                     = 127;
+    int opc_ior                      = 128;
+    int opc_lor                      = 129;
+    int opc_ixor                     = 130;
+    int opc_lxor                     = 131;
+    int opc_iinc                     = 132;
+    int opc_i2l                      = 133;
+    int opc_i2f                      = 134;
+    int opc_i2d                      = 135;
+    int opc_l2i                      = 136;
+    int opc_l2f                      = 137;
+    int opc_l2d                      = 138;
+    int opc_f2i                      = 139;
+    int opc_f2l                      = 140;
+    int opc_f2d                      = 141;
+    int opc_d2i                      = 142;
+    int opc_d2l                      = 143;
+    int opc_d2f                      = 144;
+    int opc_i2b                      = 145;
+    int opc_i2c                      = 146;
+    int opc_i2s                      = 147;
+    int opc_lcmp                     = 148;
+    int opc_fcmpl                    = 149;
+    int opc_fcmpg                    = 150;
+    int opc_dcmpl                    = 151;
+    int opc_dcmpg                    = 152;
+    int opc_ifeq                     = 153;
+    int opc_ifne                     = 154;
+    int opc_iflt                     = 155;
+    int opc_ifge                     = 156;
+    int opc_ifgt                     = 157;
+    int opc_ifle                     = 158;
+    int opc_if_icmpeq                = 159;
+    int opc_if_icmpne                = 160;
+    int opc_if_icmplt                = 161;
+    int opc_if_icmpge                = 162;
+    int opc_if_icmpgt                = 163;
+    int opc_if_icmple                = 164;
+    int opc_if_acmpeq                = 165;
+    int opc_if_acmpne                = 166;
+    int opc_goto                     = 167;
+    int opc_jsr                      = 168;
+    int opc_ret                      = 169;
+    int opc_tableswitch              = 170;
+    int opc_lookupswitch             = 171;
+    int opc_ireturn                  = 172;
+    int opc_lreturn                  = 173;
+    int opc_freturn                  = 174;
+    int opc_dreturn                  = 175;
+    int opc_areturn                  = 176;
+    int opc_return                   = 177;
+    int opc_getstatic                = 178;
+    int opc_putstatic                = 179;
+    int opc_getfield                 = 180;
+    int opc_putfield                 = 181;
+    int opc_invokevirtual            = 182;
+    int opc_invokespecial            = 183;
+    int opc_invokestatic             = 184;
+    int opc_invokeinterface          = 185;
+    int opc_xxxunusedxxx             = 186;
+    int opc_new                      = 187;
+    int opc_newarray                 = 188;
+    int opc_anewarray                = 189;
+    int opc_arraylength              = 190;
+    int opc_athrow                   = 191;
+    int opc_checkcast                = 192;
+    int opc_instanceof               = 193;
+    int opc_monitorenter             = 194;
+    int opc_monitorexit              = 195;
+    int opc_wide                     = 196;
+    int opc_multianewarray           = 197;
+    int opc_ifnull                   = 198;
+    int opc_ifnonnull                = 199;
+    int opc_goto_w                   = 200;
+    int opc_jsr_w                    = 201;
+    int opc_breakpoint               = 202;
+
+    /* Opcode Names */
+    String opcNames[] = {
+        "nop",
+        "aconst_null",
+        "iconst_m1",
+        "iconst_0",
+        "iconst_1",
+        "iconst_2",
+        "iconst_3",
+        "iconst_4",
+        "iconst_5",
+        "lconst_0",
+        "lconst_1",
+        "fconst_0",
+        "fconst_1",
+        "fconst_2",
+        "dconst_0",
+        "dconst_1",
+        "bipush",
+        "sipush",
+        "ldc",
+        "ldc_w",
+        "ldc2_w",
+        "iload",
+        "lload",
+        "fload",
+        "dload",
+        "aload",
+        "iload_0",
+        "iload_1",
+        "iload_2",
+        "iload_3",
+        "lload_0",
+        "lload_1",
+        "lload_2",
+        "lload_3",
+        "fload_0",
+        "fload_1",
+        "fload_2",
+        "fload_3",
+        "dload_0",
+        "dload_1",
+        "dload_2",
+        "dload_3",
+        "aload_0",
+        "aload_1",
+        "aload_2",
+        "aload_3",
+        "iaload",
+        "laload",
+        "faload",
+        "daload",
+        "aaload",
+        "baload",
+        "caload",
+        "saload",
+        "istore",
+        "lstore",
+        "fstore",
+        "dstore",
+        "astore",
+        "istore_0",
+        "istore_1",
+        "istore_2",
+        "istore_3",
+        "lstore_0",
+        "lstore_1",
+        "lstore_2",
+        "lstore_3",
+        "fstore_0",
+        "fstore_1",
+        "fstore_2",
+        "fstore_3",
+        "dstore_0",
+        "dstore_1",
+        "dstore_2",
+        "dstore_3",
+        "astore_0",
+        "astore_1",
+        "astore_2",
+        "astore_3",
+        "iastore",
+        "lastore",
+        "fastore",
+        "dastore",
+        "aastore",
+        "bastore",
+        "castore",
+        "sastore",
+        "pop",
+        "pop2",
+        "dup",
+        "dup_x1",
+        "dup_x2",
+        "dup2",
+        "dup2_x1",
+        "dup2_x2",
+        "swap",
+        "iadd",
+        "ladd",
+        "fadd",
+        "dadd",
+        "isub",
+        "lsub",
+        "fsub",
+        "dsub",
+        "imul",
+        "lmul",
+        "fmul",
+        "dmul",
+        "idiv",
+        "ldiv",
+        "fdiv",
+        "ddiv",
+        "irem",
+        "lrem",
+        "frem",
+        "drem",
+        "ineg",
+        "lneg",
+        "fneg",
+        "dneg",
+        "ishl",
+        "lshl",
+        "ishr",
+        "lshr",
+        "iushr",
+        "lushr",
+        "iand",
+        "land",
+        "ior",
+        "lor",
+        "ixor",
+        "lxor",
+        "iinc",
+        "i2l",
+        "i2f",
+        "i2d",
+        "l2i",
+        "l2f",
+        "l2d",
+        "f2i",
+        "f2l",
+        "f2d",
+        "d2i",
+        "d2l",
+        "d2f",
+        "i2b",
+        "i2c",
+        "i2s",
+        "lcmp",
+        "fcmpl",
+        "fcmpg",
+        "dcmpl",
+        "dcmpg",
+        "ifeq",
+        "ifne",
+        "iflt",
+        "ifge",
+        "ifgt",
+        "ifle",
+        "if_icmpeq",
+        "if_icmpne",
+        "if_icmplt",
+        "if_icmpge",
+        "if_icmpgt",
+        "if_icmple",
+        "if_acmpeq",
+        "if_acmpne",
+        "goto",
+        "jsr",
+        "ret",
+        "tableswitch",
+        "lookupswitch",
+        "ireturn",
+        "lreturn",
+        "freturn",
+        "dreturn",
+        "areturn",
+        "return",
+        "getstatic",
+        "putstatic",
+        "getfield",
+        "putfield",
+        "invokevirtual",
+        "invokespecial",
+        "invokestatic",
+        "invokeinterface",
+        "xxxunusedxxx",
+        "new",
+        "newarray",
+        "anewarray",
+        "arraylength",
+        "athrow",
+        "checkcast",
+        "instanceof",
+        "monitorenter",
+        "monitorexit",
+        "wide",
+        "multianewarray",
+        "ifnull",
+        "ifnonnull",
+        "goto_w",
+        "jsr_w",
+        "breakpoint"
+    };
+
+    /* Opcode Lengths */
+    int opcLengths[] = {
+        1,
+        1,
+        1,
+        1,
+        1,
+        1,
+        1,
+        1,
+        1,
+        1,
+        1,
+        1,
+        1,
+        1,
+        1,
+        1,
+        2,
+        3,
+        2,
+        3,
+        3,
+        2,
+        2,
+        2,
+        2,
+        2,
+        1,
+        1,
+        1,
+        1,
+        1,
+        1,
+        1,
+        1,
+        1,
+        1,
+        1,
+        1,
+        1,
+        1,
+        1,
+        1,
+        1,
+        1,
+        1,
+        1,
+        1,
+        1,
+        1,
+        1,
+        1,
+        1,
+        1,
+        1,
+        2,
+        2,
+        2,
+        2,
+        2,
+        1,
+        1,
+        1,
+        1,
+        1,
+        1,
+        1,
+        1,
+        1,
+        1,
+        1,
+        1,
+        1,
+        1,
+        1,
+        1,
+        1,
+        1,
+        1,
+        1,
+        1,
+        1,
+        1,
+        1,
+        1,
+        1,
+        1,
+        1,
+        1,
+        1,
+        1,
+        1,
+        1,
+        1,
+        1,
+        1,
+        1,
+        1,
+        1,
+        1,
+        1,
+        1,
+        1,
+        1,
+        1,
+        1,
+        1,
+        1,
+        1,
+        1,
+        1,
+        1,
+        1,
+        1,
+        1,
+        1,
+        1,
+        1,
+        1,
+        1,
+        1,
+        1,
+        1,
+        1,
+        1,
+        1,
+        1,
+        1,
+        1,
+        1,
+        1,
+        1,
+        1,
+        3,
+        1,
+        1,
+        1,
+        1,
+        1,
+        1,
+        1,
+        1,
+        1,
+        1,
+        1,
+        1,
+        1,
+        1,
+        1,
+        1,
+        1,
+        1,
+        1,
+        1,
+        3,
+        3,
+        3,
+        3,
+        3,
+        3,
+        3,
+        3,
+        3,
+        3,
+        3,
+        3,
+        3,
+        3,
+        3,
+        3,
+        2,
+        99,
+        99,
+        1,
+        1,
+        1,
+        1,
+        1,
+        1,
+        3,
+        3,
+        3,
+        3,
+        3,
+        3,
+        3,
+        5,
+        0,
+        3,
+        2,
+        3,
+        1,
+        1,
+        3,
+        3,
+        1,
+        1,
+        0,
+        4,
+        3,
+        3,
+        5,
+        5,
+        1
+    };
+
+}
diff --git a/jdk/test/java/lang/instrument/redefineAgent.mf b/jdk/test/java/lang/instrument/redefineAgent.mf
new file mode 100644
index 0000000..85cdd56
--- /dev/null
+++ b/jdk/test/java/lang/instrument/redefineAgent.mf
@@ -0,0 +1,3 @@
+Manifest-Version: 1.0
+Premain-Class: InstrumentationHandoff
+Can-Redefine-Classes: true
diff --git a/jdk/test/java/lang/management/ClassLoadingMXBean/LoadCounts.java b/jdk/test/java/lang/management/ClassLoadingMXBean/LoadCounts.java
new file mode 100644
index 0000000..378caec
--- /dev/null
+++ b/jdk/test/java/lang/management/ClassLoadingMXBean/LoadCounts.java
@@ -0,0 +1,126 @@
+/*
+ * Copyright 2003-2004 Sun Microsystems, Inc.  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 Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
+ * CA 95054 USA or visit www.sun.com if you need additional information or
+ * have any questions.
+ */
+
+/*
+ * @test
+ * @bug     4530538
+ * @summary Basic unit test of ClassLoadingMXBean.getLoadedClassCount()
+ *                             ClassLoadingMXBean.getTotalLoadedClassCount()
+ *                             ClassLoadingMXBean.getUnloadedClassCount()
+ * @author  Alexei Guibadoulline
+ */
+
+import java.lang.management.*;
+import java.util.*;
+
+public class LoadCounts {
+    private static ClassLoadingMXBean mbean
+        = ManagementFactory.getClassLoadingMXBean();
+
+    public static void main(String argv[]) throws Exception {
+        // Get current count
+        int classesNowPrev = mbean.getLoadedClassCount();
+        long classesTotalPrev = mbean.getTotalLoadedClassCount();
+
+        System.out.println("Loading 4 classes with the system class loader");
+
+        new SimpleOne();
+        new SimpleTwo();
+        new Chain();
+
+        int classesNow = mbean.getLoadedClassCount();
+        long classesTotal = mbean.getTotalLoadedClassCount();
+
+        if (classesNow > classesTotal)
+            throw new RuntimeException("getLoadedClassCount() > "
+                                     + "getTotalLoadedClassCount()");
+
+        if (classesNowPrev + 4 != classesNow)
+            throw new RuntimeException("Number of loaded classes is "
+                                     + (classesNowPrev + 4) + ", but "
+                                     + "MBean.getLoadedClassCount() returned "
+                                     + classesNow);
+        if (classesTotalPrev + 4 != classesTotal)
+            throw new RuntimeException("Total number of loaded classes is "
+                                     + (classesTotalPrev + 4) + ", but "
+                                     + "MBean.getTotalLoadedClassCount() "
+                                     + "returned " + classesTotal);
+
+        System.out.println("Creating new class loader instances");
+
+        LeftHand leftHand = new LeftHand();
+        RightHand rightHand = new RightHand();
+        LoaderForTwoInstances ins1 = new LoaderForTwoInstances();
+        LoaderForTwoInstances ins2 = new LoaderForTwoInstances();
+
+        // Load different type of classes with different
+        // initiating classloaders but the same defining class loader.
+        System.out.println("Loading 2 class instances; each by " +
+                           "2 initiating class loaders.");
+
+        classesNowPrev = mbean.getLoadedClassCount();
+        classesTotalPrev = mbean.getTotalLoadedClassCount();
+        try {
+            Class.forName("Body", true, leftHand);
+            Class.forName("Body", true, rightHand);
+            Class.forName("TheSameClass", true, ins1);
+            Class.forName("TheSameClass", true, ins2);
+        } catch (ClassNotFoundException e) {
+            System.out.println("Unexpected excetion " + e);
+            e.printStackTrace(System.out);
+            throw new RuntimeException();
+        }
+        classesNow = mbean.getLoadedClassCount();
+        classesTotal = mbean.getTotalLoadedClassCount();
+
+        // Expected 2 classes got loaded since they are loaded by
+        // same defining class loader
+        if (classesNowPrev + 2 != classesNow)
+            throw new RuntimeException("Expected Number of loaded classes is "
+                                     + (classesNowPrev + 4) + ", but "
+                                     + "MBean.getLoadedClassCount() returned "
+                                     + classesNow);
+        if (classesTotalPrev + 2 != classesTotal)
+            throw new RuntimeException("Total number of loaded classes is "
+                                     + (classesTotalPrev + 4) + ", but "
+                                     + "MBean.getTotalLoadedClassCount() "
+                                     + "returned " + classesTotal);
+
+        System.out.println("Test passed.");
+    }
+}
+
+class SimpleOne {}
+class SimpleTwo {}
+
+class Chain {
+    Slave slave = new Slave();
+}
+class Slave {}
+
+class LeftHand extends ClassLoader {}
+class RightHand extends ClassLoader {}
+class Body {}
+
+class LoaderForTwoInstances extends ClassLoader {}
+class TheSameClass {}
diff --git a/jdk/test/java/lang/management/CompilationMXBean/Basic.java b/jdk/test/java/lang/management/CompilationMXBean/Basic.java
new file mode 100644
index 0000000..d4d6d47
--- /dev/null
+++ b/jdk/test/java/lang/management/CompilationMXBean/Basic.java
@@ -0,0 +1,83 @@
+/*
+ * Copyright 2004 Sun Microsystems, Inc.  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 Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
+ * CA 95054 USA or visit www.sun.com if you need additional information or
+ * have any questions.
+ */
+
+/*
+ * @test
+ * @bug 5011189
+ * @summary Unit test for java.lang.management.CompilationMXBean
+ *
+ * @run main/othervm -Xcomp -Xbatch -Djava.awt.headless=true Basic
+ */
+import java.lang.management.*;
+
+public class Basic {
+
+    public static void main(String args[]) {
+        CompilationMXBean mb = ManagementFactory.getCompilationMXBean();
+        if (mb == null) {
+            System.out.println("The virtual machine doesn't have a compilation system");
+            return;
+        }
+
+        // Exercise getName() method
+        System.out.println(mb.getName());
+
+        // If compilation time monitoring isn't supported then we are done
+        if (!mb.isCompilationTimeMonitoringSupported()) {
+            System.out.println("Compilation time monitoring not supported.");
+            return;
+        }
+
+        // Exercise getTotalCompilationTime();
+        long time;
+
+        // If the compiler has already done some work then we are done
+        time = mb.getTotalCompilationTime();
+        if (time > 0) {
+            printCompilationTime(time);
+            return;
+        }
+
+        // Now the hard bit - we do random work on the assumption
+        // that the compiler will be used.
+
+        System.out.println("Doing random work...");
+
+        java.util.Locale.getAvailableLocales();
+        java.security.Security.getProviders();
+        java.awt.Toolkit.getDefaultToolkit();
+        javax.swing.UIManager.getInstalledLookAndFeels();
+        java.nio.channels.spi.SelectorProvider.provider();
+
+        time = mb.getTotalCompilationTime();
+        if (time > 0) {
+            printCompilationTime(time);
+        } else {
+            throw new RuntimeException("getTimeCompilionTime returns 0");
+        }
+    }
+
+    static void printCompilationTime(long time) {
+        System.out.println("Total compilation time: " + time + " ms");
+    }
+}
diff --git a/jdk/test/java/lang/management/CompositeData/MemoryNotifInfoCompositeData.java b/jdk/test/java/lang/management/CompositeData/MemoryNotifInfoCompositeData.java
new file mode 100644
index 0000000..d833e5e
--- /dev/null
+++ b/jdk/test/java/lang/management/CompositeData/MemoryNotifInfoCompositeData.java
@@ -0,0 +1,196 @@
+/*
+ * Copyright 2004 Sun Microsystems, Inc.  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 Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
+ * CA 95054 USA or visit www.sun.com if you need additional information or
+ * have any questions.
+ */
+
+/*
+ * @test
+ * @bug     4982289
+ * @summary Test MemoryNotificationInfo.from to return a valid
+ *          MemoryNotificationInfo object. Or throw exception if
+ *          the input CompositeData is invalid.
+ * @author  Mandy Chung
+ *
+ * @compile -source 1.5 OpenTypeConverter.java
+ * @build MemoryNotifInfoCompositeData
+ * @run main MemoryNotifInfoCompositeData
+ */
+
+import javax.management.openmbean.*;
+import java.lang.management.MemoryNotificationInfo;
+import java.lang.management.MemoryUsage;
+import sun.management.MemoryUsageCompositeData;
+
+public class MemoryNotifInfoCompositeData {
+    public static void main(String[] argv) throws Exception {
+        createGoodCompositeData();
+        badNameCompositeData();
+        badTypeCompositeData();
+        System.out.println("Test passed");
+    }
+
+    private static final int POOL_NAME = 1;
+    private static final int COUNT     = 2;
+    private static final int USAGE     = 3;
+    private static final String[] validItemNames = {
+        "dummy1",
+        "poolName",
+        "count",
+        "usage",
+        "dummy2",
+    };
+
+    // these values are synchronized with the item names
+    private static final Object[] values = {
+        "Dummy",
+        "Foo",
+        new Long(100),
+        MemoryUsageCompositeData.
+            toCompositeData(new MemoryUsage(0, 100, 1000, 5000)),
+        "Dummy",
+    };
+
+    public static void createGoodCompositeData() throws Exception {
+
+        // get the CompositeType for MemoryUsage
+        validItemTypes[USAGE] = OpenTypeConverter.toOpenType(MemoryUsage.class);
+        CompositeType ct =
+            new CompositeType("MyCompositeType",
+                              "CompositeType for MemoryNotificationInfo",
+                              validItemNames,
+                              validItemNames,
+                              validItemTypes);
+        CompositeData cd =
+            new CompositeDataSupport(ct,
+                                     validItemNames,
+                                     values);
+
+        MemoryNotificationInfo info = MemoryNotificationInfo.from(cd);
+        if (!info.getPoolName().equals(values[POOL_NAME])) {
+            throw new RuntimeException("pool name = " + info.getPoolName() +
+               " expected = " + values[POOL_NAME]);
+        }
+        if (info.getCount() != ((Long) values[COUNT]).longValue()) {
+            throw new RuntimeException("count = " + info.getCount() +
+               " expected = " + values[COUNT]);
+        }
+        if (info.getUsage().getInit() != 0) {
+            throw new RuntimeException("usage init = " +
+               info.getUsage().getInit() +
+               " expected = 0");
+        }
+        if (info.getUsage().getUsed() != 100) {
+            throw new RuntimeException("usage used = " +
+               info.getUsage().getUsed() +
+               " expected = 100");
+        }
+        if (info.getUsage().getCommitted () != 1000) {
+            throw new RuntimeException("usage committed = " +
+               info.getUsage().getCommitted() +
+               " expected = 1000");
+        }
+        if (info.getUsage().getMax() != 5000) {
+            throw new RuntimeException("usage max = " +
+               info.getUsage().getMax() +
+               " expected = 5000");
+        }
+        System.out.print("Pool name = " + info.getPoolName());
+        System.out.println(" Count = " + info.getCount());
+        System.out.println("Usage = " + info.getUsage());
+    }
+
+    public static void badNameCompositeData() throws Exception {
+        CompositeType ct =
+            new CompositeType("MyCompositeType",
+                              "CompositeType for MemoryNotificationInfo",
+                              badItemNames,
+                              badItemNames,
+                              validItemTypes);
+        CompositeData cd =
+            new CompositeDataSupport(ct,
+                                     badItemNames,
+                                     values);
+
+        try {
+            MemoryNotificationInfo info = MemoryNotificationInfo.from(cd);
+        } catch (IllegalArgumentException e) {
+            System.out.println("Expected exception: " +
+                e.getMessage());
+            return;
+        }
+        throw new RuntimeException(
+            "IllegalArgumentException not thrown");
+    }
+
+    public static void badTypeCompositeData() throws Exception {
+        CompositeType ct =
+            new CompositeType("MyCompositeType",
+                              "CompositeType for MemoryNotificationInfo",
+                              validItemNames,
+                              validItemNames,
+                              badItemTypes);
+
+        final Object[] values1 = {
+            "Dummy",
+            "Foo",
+            new Long(100),
+            "Bad memory usage object",
+            "Dummy",
+        };
+
+        CompositeData cd =
+            new CompositeDataSupport(ct,
+                                     validItemNames,
+                                     values1);
+
+        try {
+            MemoryNotificationInfo info = MemoryNotificationInfo.from(cd);
+        } catch (IllegalArgumentException e) {
+            System.out.println("Expected exception: " +
+                e.getMessage());
+            return;
+        }
+        throw new RuntimeException(
+            "IllegalArgumentException not thrown");
+    }
+
+    private static OpenType[] validItemTypes = {
+        SimpleType.STRING,
+        SimpleType.STRING,
+        SimpleType.LONG,
+        null, // OpenTypeConverter.toOpenType(MemoryUsage.class)
+        SimpleType.STRING,
+    };
+    private static final String[] badItemNames = {
+        "poolName",
+        "BadCountName",
+        "usage",
+        "dummy1",
+        "dummy2",
+    };
+    private static final OpenType[] badItemTypes = {
+        SimpleType.STRING,
+        SimpleType.STRING,
+        SimpleType.LONG,
+        SimpleType.STRING, // Bad type
+        SimpleType.STRING,
+    };
+}
diff --git a/jdk/test/java/lang/management/CompositeData/MemoryUsageCompositeData.java b/jdk/test/java/lang/management/CompositeData/MemoryUsageCompositeData.java
new file mode 100644
index 0000000..b93c55c
--- /dev/null
+++ b/jdk/test/java/lang/management/CompositeData/MemoryUsageCompositeData.java
@@ -0,0 +1,188 @@
+/*
+ * Copyright 2004 Sun Microsystems, Inc.  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 Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
+ * CA 95054 USA or visit www.sun.com if you need additional information or
+ * have any questions.
+ */
+
+/*
+ * @test
+ * @bug     4982289
+ * @summary Test MemoryUsage.from() method to return a valid MemoryUsage
+ *          or throw exception if the input CompositeData is invalid.
+ * @author  Mandy Chung
+ *
+ * @build MemoryUsageCompositeData
+ * @run main MemoryUsageCompositeData
+ */
+
+import javax.management.openmbean.*;
+import java.lang.management.MemoryUsage;
+
+public class MemoryUsageCompositeData {
+    public static void main(String[] argv) throws Exception {
+        createGoodCompositeData();
+        badTypeCompositeData();
+        badNameCompositeData();
+        System.out.println("Test passed");
+    }
+
+    public static void createGoodCompositeData() throws Exception {
+        final int K = 1024;
+        // these values are synchronized with the item names
+        final Object[] values = {
+            new Long(5 * K),  // committed
+            new Long(1 * K),  // init
+            new Long(10 * K), // max
+            new Long(2 * K),  // used
+            "Dummy",
+            "Dummy",
+        };
+
+        CompositeType muct =
+            new CompositeType("MyMemoryUsageCompositeType",
+                              "CompositeType for MemoryUsage",
+                              memoryUsageItemNames,
+                              memoryUsageItemNames,
+                              memoryUsageItemTypes);
+        CompositeData cd =
+            new CompositeDataSupport(muct,
+                                     memoryUsageItemNames,
+                                     values);
+        MemoryUsage u = MemoryUsage.from(cd);
+        if (u.getInit() != ((Long) values[INIT]).longValue()) {
+            throw new RuntimeException("init = " + u.getInit() +
+               " expected = " + values[INIT]);
+        }
+        if (u.getUsed() != ((Long) values[USED]).longValue()) {
+            throw new RuntimeException("used = " + u.getUsed() +
+               " expected = " + values[USED]);
+        }
+        if (u.getCommitted() != ((Long) values[COMMITTED]).longValue()) {
+            throw new RuntimeException("committed = " + u.getCommitted() +
+               " expected = " + values[COMMITTED]);
+        }
+        if (u.getMax() != ((Long) values[MAX]).longValue()) {
+            throw new RuntimeException("max = " + u.getMax() +
+               " expected = " + values[MAX]);
+        }
+        System.out.println(u);
+    }
+
+    public static void badTypeCompositeData() throws Exception {
+        final int K = 1024;
+        final Object[] values = {
+            new Integer(5 * K),
+            new Long(1 * K),
+            new Long(10 * K),
+            new Long(2 * K),
+            "Dummy",
+            "Dummy",
+        };
+
+        CompositeType muct =
+            new CompositeType("MyMemoryUsageCompositeType",
+                              "CompositeType for MemoryUsage",
+                              memoryUsageItemNames,
+                              memoryUsageItemNames,
+                              badMUItemTypes);
+        CompositeData cd =
+           new CompositeDataSupport(muct,
+                                    memoryUsageItemNames,
+                                    values);
+        try {
+            MemoryUsage u = MemoryUsage.from(cd);
+        } catch (IllegalArgumentException e) {
+            System.out.println("Expected exception: " +
+                e.getMessage());
+            return;
+        }
+        throw new RuntimeException(
+            "IllegalArgumentException not thrown");
+    }
+
+    public static void badNameCompositeData() throws Exception {
+        final int K = 1024;
+        final Object[] values = {
+            new Long(5 * K),
+            new Long(1 * K),
+            new Long(10 * K),
+            new Long(2 * K),
+            "Dummy",
+            "Dummy",
+        };
+
+        CompositeType muct =
+            new CompositeType("MyMemoryUsageCompositeType",
+                              "CompositeType for MemoryUsage",
+                               badMUItemNames,
+                               badMUItemNames,
+                               memoryUsageItemTypes);
+        CompositeData cd =
+            new CompositeDataSupport(muct,
+                                     badMUItemNames,
+                                     values);
+        try {
+            MemoryUsage u = MemoryUsage.from(cd);
+        } catch (IllegalArgumentException e) {
+            System.out.println("Expected exception: " +
+                e.getMessage());
+            return;
+        }
+        throw new RuntimeException(
+            "IllegalArgumentException not thrown");
+    }
+
+    private static final int COMMITTED = 0;
+    private static final int INIT      = 1;
+    private static final int MAX       = 2;
+    private static final int USED      = 3;
+    private static final String[] memoryUsageItemNames = {
+        "committed",
+        "init",
+        "max",
+        "used",
+        "dummy1",
+        "dummy2",
+    };
+    private static final OpenType[] memoryUsageItemTypes = {
+        SimpleType.LONG,
+        SimpleType.LONG,
+        SimpleType.LONG,
+        SimpleType.LONG,
+        SimpleType.STRING,
+        SimpleType.STRING,
+    };
+    private static final String[] badMUItemNames = {
+        "Committed",
+        "Init",
+        "max",
+        "used",
+        "dummy1",
+        "dummy2",
+    };
+    private static final OpenType[] badMUItemTypes = {
+        SimpleType.INTEGER,
+        SimpleType.LONG,
+        SimpleType.LONG,
+        SimpleType.LONG,
+        SimpleType.STRING,
+        SimpleType.STRING,
+    };
+}
diff --git a/jdk/test/java/lang/management/CompositeData/OpenTypeConverter.java b/jdk/test/java/lang/management/CompositeData/OpenTypeConverter.java
new file mode 100644
index 0000000..8475eb8
--- /dev/null
+++ b/jdk/test/java/lang/management/CompositeData/OpenTypeConverter.java
@@ -0,0 +1,214 @@
+/*
+ * Copyright 2004 Sun Microsystems, Inc.  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 Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
+ * CA 95054 USA or visit www.sun.com if you need additional information or
+ * have any questions.
+ */
+
+/*
+ * @bug     5024531
+ * @summary Utility class to convert a struct-like class to a CompositeData.
+ * @author Mandy Chung
+ */
+
+import java.lang.reflect.*;
+import java.util.*;
+import javax.management.*;
+import javax.management.openmbean.*;
+import static javax.management.openmbean.SimpleType.*;
+
+/**
+ * A converter utiltiy class to automatically convert a given
+ * class to a CompositeType.
+ */
+public class OpenTypeConverter {
+    private static final WeakHashMap<Class,OpenType> convertedTypes =
+        new WeakHashMap<Class,OpenType>();
+    private static final OpenType[] simpleTypes = {
+        BIGDECIMAL, BIGINTEGER, BOOLEAN, BYTE, CHARACTER, DATE,
+        DOUBLE, FLOAT, INTEGER, LONG, OBJECTNAME, SHORT, STRING,
+        VOID,
+    };
+
+    static {
+        for (int i = 0; i < simpleTypes.length; i++) {
+            final OpenType t = simpleTypes[i];
+            Class c;
+            try {
+                c = Class.forName(t.getClassName(), false,
+                                  String.class.getClassLoader());
+            } catch (ClassNotFoundException e) {
+                // the classes that these predefined types declare must exist!
+                assert(false);
+                c = null; // not reached
+            }
+            convertedTypes.put(c, t);
+
+            if (c.getName().startsWith("java.lang.")) {
+                try {
+                    final Field typeField = c.getField("TYPE");
+                    final Class primitiveType = (Class) typeField.get(null);
+                    convertedTypes.put(primitiveType, t);
+                } catch (NoSuchFieldException e) {
+                    // OK: must not be a primitive wrapper
+                } catch (IllegalAccessException e) {
+                    // Should not reach here
+                    throw new AssertionError(e);
+                }
+            }
+        }
+    }
+
+    private static class InProgress extends OpenType {
+        private static final String description =
+                  "Marker to detect recursive type use -- internal use only!";
+
+        InProgress() throws OpenDataException {
+            super("java.lang.String", "java.lang.String", description);
+        }
+
+        public String toString() {
+            return description;
+        }
+
+        public int hashCode() {
+            return 0;
+        }
+
+        public boolean equals(Object o) {
+            return false;
+        }
+
+        public boolean isValue(Object o) {
+            return false;
+        }
+    }
+    private static final OpenType inProgress;
+    static {
+        OpenType t;
+        try {
+            t = new InProgress();
+        } catch (OpenDataException e) {
+            // Should not reach here
+            throw new AssertionError(e);
+        }
+        inProgress = t;
+    }
+
+    // Convert a class to an OpenType
+    public static synchronized OpenType toOpenType(Class c)
+            throws OpenDataException {
+
+        OpenType t;
+
+        t = convertedTypes.get(c);
+        if (t != null) {
+            if (t instanceof InProgress)
+                throw new OpenDataException("Recursive data structure");
+            return t;
+        }
+
+        convertedTypes.put(c, inProgress);
+
+        if (Enum.class.isAssignableFrom(c))
+            t = STRING;
+        else if (c.isArray())
+            t = makeArrayType(c);
+        else
+            t = makeCompositeType(c);
+
+        convertedTypes.put(c, t);
+
+        return t;
+    }
+
+    private static OpenType makeArrayType(Class c) throws OpenDataException {
+        int dim;
+        for (dim = 0; c.isArray(); dim++)
+            c = c.getComponentType();
+        return new ArrayType(dim, toOpenType(c));
+    }
+
+    private static OpenType makeCompositeType(Class c)
+            throws OpenDataException {
+        // Make a CompositeData containing all the getters
+        final Method[] methods = c.getMethods();
+        final List<String> names = new ArrayList<String>();
+        final List<OpenType> types = new ArrayList<OpenType>();
+
+        /* Select public methods that look like "T getX()" or "boolean
+           isX() or hasX()", where T is not void and X is not the empty
+           string.  Exclude "Class getClass()" inherited from Object.  */
+        for (int i = 0; i < methods.length; i++) {
+            final Method method = methods[i];
+            final String name = method.getName();
+            final Class type = method.getReturnType();
+            final String rest;
+            if (name.startsWith("get"))
+                rest = name.substring(3);
+            else if (name.startsWith("is") && type == boolean.class)
+                rest = name.substring(2);
+            else if (name.startsWith("has") && type == boolean.class)
+                rest = name.substring(3);
+            else
+                continue;
+
+            if (rest.equals("") || method.getParameterTypes().length > 0
+                || type == void.class || rest.equals("Class"))
+                continue;
+
+            names.add(decapitalize(rest));
+            types.add(toOpenType(type));
+        }
+
+        final String[] nameArray = names.toArray(new String[0]);
+        return new CompositeType(c.getName(),
+                                 c.getName(),
+                                 nameArray, // field names
+                                 nameArray, // field descriptions
+                                 types.toArray(new OpenType[0]));
+    }
+
+    /**
+     * Utility method to take a string and convert it to normal Java variable
+     * name capitalization.  This normally means converting the first
+     * character from upper case to lower case, but in the (unusual) special
+     * case when there is more than one character and both the first and
+     * second characters are upper case, we leave it alone.
+     * <p>
+     * Thus "FooBah" becomes "fooBah" and "X" becomes "x", but "URL" stays
+     * as "URL".
+     *
+     * @param  name The string to be decapitalized.
+     * @return  The decapitalized version of the string.
+     */
+    private static String decapitalize(String name) {
+        if (name == null || name.length() == 0) {
+            return name;
+        }
+        if (name.length() > 1 && Character.isUpperCase(name.charAt(1)) &&
+                        Character.isUpperCase(name.charAt(0))){
+            return name;
+        }
+        char chars[] = name.toCharArray();
+        chars[0] = Character.toLowerCase(chars[0]);
+        return new String(chars);
+    }
+
+}
diff --git a/jdk/test/java/lang/management/CompositeData/ThreadInfoCompositeData.java b/jdk/test/java/lang/management/CompositeData/ThreadInfoCompositeData.java
new file mode 100644
index 0000000..6c3cb0d
--- /dev/null
+++ b/jdk/test/java/lang/management/CompositeData/ThreadInfoCompositeData.java
@@ -0,0 +1,402 @@
+/*
+ * Copyright 2004-2005 Sun Microsystems, Inc.  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 Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
+ * CA 95054 USA or visit www.sun.com if you need additional information or
+ * have any questions.
+ */
+
+/*
+ * @test
+ * @bug     4982289
+ * @summary Test ThreadInfo.from to return a valid
+ *          ThreadInfo object. Or throw exception if
+ *          the input CompositeData is invalid.
+ * @author  Mandy Chung
+ *
+ * @compile -source 1.5 OpenTypeConverter.java
+ * @build ThreadInfoCompositeData
+ * @run main ThreadInfoCompositeData
+ */
+
+import javax.management.openmbean.*;
+import java.lang.management.LockInfo;
+import java.lang.management.MonitorInfo;
+import java.lang.management.ThreadInfo;
+
+public class ThreadInfoCompositeData {
+    private static StackTraceElement[] ste = new StackTraceElement[1];
+    private static CompositeData[] steCD = new CompositeData[1];
+    private static String lockClassName = "myClass";
+    private static int lockIdentityHashCode = 123456;
+    private static String lockName = lockClassName + '@' +
+        Integer.toHexString(lockIdentityHashCode);
+    private static LockInfo lockInfo =
+        new LockInfo(lockClassName, lockIdentityHashCode);
+
+    public static void main(String[] argv) throws Exception {
+        // A valid CompositeData is passed to ThreadInfo
+        createGoodCompositeData();
+        // A valid CompositeData for JDK 5.0 ThreadInfo
+        // is passed to ThreadInfo
+        createV5ThreadInfo();
+        // An invalid CompositeData is passed to ThreadInfo.from()
+        badNameCompositeData();
+        badTypeCompositeData();
+        System.out.println("Test passed");
+    }
+
+    public static void createGoodCompositeData() throws Exception {
+        CompositeType ct =
+            new CompositeType("MyCompositeType",
+                              "CompositeType for ThreadInfo",
+                              validItemNames,
+                              validItemNames,
+                              validItemTypes);
+        CompositeData cd =
+            new CompositeDataSupport(ct,
+                                     validItemNames,
+                                     values);
+        ThreadInfo info = ThreadInfo.from(cd);
+        checkThreadInfo(info);
+   }
+
+    public static void createV5ThreadInfo() throws Exception {
+        String[] v5ItemNames = new String[NUM_V5_ATTS];
+        OpenType[] v5ItemTypes = new OpenType[NUM_V5_ATTS];
+        Object[] v5ItemValues = new Object[NUM_V5_ATTS];
+        for (int i = 0; i < NUM_V5_ATTS; i++) {
+            v5ItemNames[i] = validItemNames[i];
+            v5ItemTypes[i] = validItemTypes[i];
+            v5ItemValues[i] = values[i];
+        }
+        CompositeType ct =
+            new CompositeType("MyCompositeType",
+                              "CompositeType for JDK 5.0 ThreadInfo",
+                              v5ItemNames,
+                              v5ItemNames,
+                              v5ItemTypes);
+        CompositeData cd =
+            new CompositeDataSupport(ct,
+                                     v5ItemNames,
+                                     v5ItemValues);
+        ThreadInfo info = ThreadInfo.from(cd);
+        checkThreadInfo(info);
+   }
+
+   static void checkThreadInfo(ThreadInfo info) throws Exception {
+        if (info.getThreadId() != ((Long) values[THREAD_ID]).longValue()) {
+            throw new RuntimeException("Thread Id = " + info.getThreadId() +
+               " expected = " + values[THREAD_ID]);
+        }
+        if (!info.getThreadName().equals(values[THREAD_NAME])) {
+            throw new RuntimeException("Thread Name = " +
+               info.getThreadName() + " expected = " + values[THREAD_NAME]);
+        }
+        if (info.getThreadState() != Thread.State.RUNNABLE) {
+            throw new RuntimeException("Thread Name = " +
+               info.getThreadName() + " expected = " + Thread.State.RUNNABLE);
+        }
+        if (info.getBlockedTime() != ((Long) values[BLOCKED_TIME]).longValue()) {
+            throw new RuntimeException("blocked time = " +
+               info.getBlockedTime() +
+               " expected = " + values[BLOCKED_TIME]);
+        }
+        if (info.getBlockedCount() != ((Long) values[BLOCKED_COUNT]).longValue()) {
+            throw new RuntimeException("blocked count = " +
+               info.getBlockedCount() +
+               " expected = " + values[BLOCKED_COUNT]);
+        }
+        if (info.getWaitedTime() != ((Long) values[WAITED_TIME]).longValue()) {
+            throw new RuntimeException("waited time = " +
+               info.getWaitedTime() +
+               " expected = " + values[WAITED_TIME]);
+        }
+        if (info.getWaitedCount() != ((Long) values[WAITED_COUNT]).longValue()) {
+            throw new RuntimeException("waited count = " +
+               info.getWaitedCount() +
+               " expected = " + values[WAITED_COUNT]);
+        }
+        if (!info.getLockName().equals(values[LOCK_NAME])) {
+            throw new RuntimeException("Lock Name = " +
+               info.getLockName() + " expected = " + values[LOCK_NAME]);
+        }
+        if (info.getLockOwnerId() !=
+                ((Long) values[LOCK_OWNER_ID]).longValue()) {
+            throw new RuntimeException(
+               "LockOwner Id = " + info.getLockOwnerId() +
+               " expected = " + values[LOCK_OWNER_ID]);
+        }
+        if (!info.getLockOwnerName().equals(values[LOCK_OWNER_NAME])) {
+            throw new RuntimeException("LockOwner Name = " +
+               info.getLockOwnerName() + " expected = " +
+               values[LOCK_OWNER_NAME]);
+        }
+
+        checkStackTrace(info.getStackTrace());
+
+        checkLockInfo(info.getLockInfo());
+    }
+
+    private static void checkStackTrace(StackTraceElement[] s)
+        throws Exception {
+        if (ste.length != s.length) {
+            throw new RuntimeException("Stack Trace length = " +
+                s.length + " expected = " + ste.length);
+        }
+
+        StackTraceElement s1 = ste[0];
+        StackTraceElement s2 = s[0];
+
+        if (!s1.getClassName().equals(s2.getClassName())) {
+            throw new RuntimeException("Class name = " +
+                s2.getClassName() + " expected = " + s1.getClassName());
+        }
+        if (!s1.getMethodName().equals(s2.getMethodName())) {
+            throw new RuntimeException("Method name = " +
+                s2.getMethodName() + " expected = " + s1.getMethodName());
+        }
+        if (!s1.getFileName().equals(s2.getFileName())) {
+            throw new RuntimeException("File name = " +
+                s2.getFileName() + " expected = " + s1.getFileName());
+        }
+        if (s1.getLineNumber() != s2.getLineNumber()) {
+            throw new RuntimeException("Line number = " +
+                s2.getLineNumber() + " expected = " + s1.getLineNumber());
+        }
+    }
+
+    private static void checkLockInfo(LockInfo li)
+        throws Exception {
+        if (!li.getClassName().equals(lockInfo.getClassName())) {
+            throw new RuntimeException("Class Name = " +
+                li.getClassName() + " expected = " + lockInfo.getClassName());
+        }
+        if (li.getIdentityHashCode() != lockInfo.getIdentityHashCode()) {
+            throw new RuntimeException("Class Name = " +
+                li.getIdentityHashCode() + " expected = " +
+                lockInfo.getIdentityHashCode());
+        }
+    }
+
+    public static void badNameCompositeData() throws Exception {
+        CompositeType ct =
+            new CompositeType("MyCompositeType",
+                              "CompositeType for ThreadInfo",
+                              badItemNames,
+                              badItemNames,
+                              validItemTypes);
+        CompositeData cd =
+            new CompositeDataSupport(ct,
+                                     badItemNames,
+                                     values);
+
+        try {
+            ThreadInfo info = ThreadInfo.from(cd);
+        } catch (IllegalArgumentException e) {
+            System.out.println("Expected exception: " +
+                e.getMessage());
+            return;
+        }
+        throw new RuntimeException(
+            "IllegalArgumentException not thrown");
+    }
+
+    public static void badTypeCompositeData() throws Exception {
+        CompositeType ct =
+            new CompositeType("MyCompositeType",
+                              "CompositeType for ThreadInfo",
+                              validItemNames,
+                              validItemNames,
+                              badItemTypes);
+
+        // patch values[STACK_TRACE] to Long
+        values[STACK_TRACE] = new Long(1000);
+        values[LOCK_INFO] = new Long(1000);
+        CompositeData cd =
+            new CompositeDataSupport(ct,
+                                     validItemNames,
+                                     values);
+
+        try {
+            ThreadInfo info = ThreadInfo.from(cd);
+        } catch (IllegalArgumentException e) {
+            System.out.println("Expected exception: " +
+                e.getMessage());
+            return;
+        }
+        throw new RuntimeException(
+            "IllegalArgumentException not thrown");
+    }
+
+    private static final int THREAD_ID       = 0;
+    private static final int THREAD_NAME     = 1;
+    private static final int THREAD_STATE    = 2;
+    private static final int BLOCKED_TIME    = 3;
+    private static final int BLOCKED_COUNT   = 4;
+    private static final int WAITED_TIME     = 5;
+    private static final int WAITED_COUNT    = 6;
+    private static final int LOCK_NAME       = 7;
+    private static final int LOCK_OWNER_ID   = 8;
+    private static final int LOCK_OWNER_NAME = 9;
+    private static final int STACK_TRACE     = 10;
+    private static final int SUSPENDED       = 11;
+    private static final int IN_NATIVE       = 12;
+    private static final int NUM_V5_ATTS     = 13;
+    // JDK 6.0 ThreadInfo attribtues
+    private static final int LOCK_INFO       = 13;
+
+    private static final String[] validItemNames = {
+        "threadId",
+        "threadName",
+        "threadState",
+        "blockedTime",
+        "blockedCount",
+        "waitedTime",
+        "waitedCount",
+        "lockName",
+        "lockOwnerId",
+        "lockOwnerName",
+        "stackTrace",
+        "suspended",
+        "inNative",
+        "lockInfo",
+    };
+
+    private static OpenType[] validItemTypes = {
+        SimpleType.LONG,
+        SimpleType.STRING,
+        SimpleType.STRING,
+        SimpleType.LONG,
+        SimpleType.LONG,
+        SimpleType.LONG,
+        SimpleType.LONG,
+        SimpleType.STRING,
+        SimpleType.LONG,
+        SimpleType.STRING,
+        null,  // ArrayType for StackTraceElement[]
+        SimpleType.BOOLEAN,
+        SimpleType.BOOLEAN,
+        null,  // CompositeType for LockInfo
+    };
+
+    private static Object[] values = {
+        new Long(100),
+        "FooThread",
+        "RUNNABLE",
+        new Long(200),
+        new Long(10),
+        new Long(300),
+        new Long(20),
+        lockName,
+        new Long(99),
+        "BarThread",
+        steCD,
+        new Boolean(false),
+        new Boolean(false),
+        null, // To be initialized to lockInfoCD
+    };
+
+    private static final String[] steItemNames = {
+        "className",
+        "methodName",
+        "fileName",
+        "lineNumber",
+        "nativeMethod",
+    };
+
+    private static final String[] lockInfoItemNames = {
+        "className",
+        "identityHashCode",
+    };
+
+    static {
+        // create stack trace element
+        ste[0] = new StackTraceElement("FooClass", "getFoo", "Foo.java", 100);
+
+        // initialize the ste[0] and values and validItemTypes
+        try {
+            CompositeType steCType = (CompositeType)
+                OpenTypeConverter.toOpenType(StackTraceElement.class);
+            validItemTypes[STACK_TRACE] = new ArrayType(1, steCType);
+
+            final Object[] steValue = {
+                ste[0].getClassName(),
+                ste[0].getMethodName(),
+                ste[0].getFileName(),
+                new Integer(ste[0].getLineNumber()),
+                new Boolean(ste[0].isNativeMethod()),
+            };
+
+            steCD[0] =
+                new CompositeDataSupport(steCType,
+                                         steItemNames,
+                                         steValue);
+
+            CompositeType lockInfoCType = (CompositeType)
+                OpenTypeConverter.toOpenType(LockInfo.class);
+            validItemTypes[LOCK_INFO] = lockInfoCType;
+
+            final Object[] lockInfoValue = {
+                lockInfo.getClassName(),
+                lockInfo.getIdentityHashCode(),
+            };
+
+            values[LOCK_INFO] =
+                new CompositeDataSupport(lockInfoCType,
+                                         lockInfoItemNames,
+                                         lockInfoValue);
+        } catch (Exception e) {
+            throw new RuntimeException(e);
+        }
+    }
+
+    private static final String[] badItemNames = {
+        "threadId",
+        "threadName",
+        "threadState",
+        "blockedTime",
+        "blockedCount",
+        "waitedTime",
+        "waitedCount",
+        "lockName",
+        "lockOwnerId",
+        "lockOwnerName",
+        "BadStackTrace", // bad item name
+        "suspended",
+        "inNative",
+        "lockInfo",
+    };
+    private static final OpenType[] badItemTypes = {
+        SimpleType.LONG,
+        SimpleType.STRING,
+        SimpleType.STRING,
+        SimpleType.LONG,
+        SimpleType.LONG,
+        SimpleType.LONG,
+        SimpleType.LONG,
+        SimpleType.STRING,
+        SimpleType.LONG,
+        SimpleType.STRING,
+        SimpleType.LONG,  // bad type
+        SimpleType.BOOLEAN,
+        SimpleType.BOOLEAN,
+        SimpleType.LONG,  // bad type
+    };
+
+}
diff --git a/jdk/test/java/lang/management/GarbageCollectorMXBean/GcInfoCompositeType.java b/jdk/test/java/lang/management/GarbageCollectorMXBean/GcInfoCompositeType.java
new file mode 100644
index 0000000..2d94808
--- /dev/null
+++ b/jdk/test/java/lang/management/GarbageCollectorMXBean/GcInfoCompositeType.java
@@ -0,0 +1,116 @@
+/*
+ * Copyright 2006 Sun Microsystems, Inc.  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 Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
+ * CA 95054 USA or visit www.sun.com if you need additional information or
+ * have any questions.
+ */
+
+/*
+ * @test
+ * @bug     6396794
+ * @summary Check that LastGcInfo contents are reasonable
+ * @author  Eamonn McManus
+ * @run     main/othervm GcInfoCompositeType
+ */
+
+import java.util.*;
+import java.lang.management.*;
+import java.lang.reflect.*;
+import javax.management.*;
+import javax.management.openmbean.*;
+import com.sun.management.GcInfo;
+
+public class GcInfoCompositeType {
+    private static int tested = 0;
+
+    public static void main(String[] args) throws Exception {
+        MBeanServer mbs = ManagementFactory.getPlatformMBeanServer();
+        final ObjectName gcMXBeanPattern =
+                new ObjectName("java.lang:type=GarbageCollector,*");
+        Set<ObjectName> names =
+                mbs.queryNames(gcMXBeanPattern, null);
+        if (names.isEmpty())
+            throw new Exception("Test incorrect: no GC MXBeans");
+        System.gc();
+        for (ObjectName n : names)
+            tested += test(mbs, n);
+        if (tested == 0)
+            throw new Exception("No MXBeans were tested");
+        System.out.println("Test passed");
+    }
+
+    private static int test(MBeanServer mbs, ObjectName n) throws Exception {
+        System.out.println("Testing " + n);
+        MBeanInfo mbi = mbs.getMBeanInfo(n);
+        MBeanAttributeInfo lastGcAI = null;
+        for (MBeanAttributeInfo mbai : mbi.getAttributes()) {
+            if (mbai.getName().equals("LastGcInfo")) {
+                lastGcAI = mbai;
+                break;
+            }
+        }
+        if (lastGcAI == null)
+            throw new Exception("No LastGcInfo attribute");
+        CompositeType declaredType =
+                (CompositeType) lastGcAI.getDescriptor().getFieldValue("openType");
+        checkType(declaredType);
+        CompositeData cd =
+                (CompositeData) mbs.getAttribute(n, "LastGcInfo");
+        if (cd == null) {
+            System.out.println("Value of attribute null");
+            return 0;
+        } else
+            return checkType(cd.getCompositeType());
+    }
+
+    private static int checkType(CompositeType ct) throws Exception {
+        Method[] methods = GcInfo.class.getMethods();
+        Set<String> getters = new TreeSet<String>(String.CASE_INSENSITIVE_ORDER);
+        for (Method m : methods) {
+            if (m.getName().startsWith("get") && m.getParameterTypes().length == 0)
+                getters.add(m.getName().substring(3));
+        }
+        Set<String> items = new HashSet<String>(ct.keySet());
+        System.out.println("Items at start: " + items);
+
+        // Now check that all the getters have a corresponding item in the
+        // CompositeType, except the following:
+        // getClass() inherited from Object should not be an item;
+        // getCompositeType() inherited from CompositeData is not useful so
+        // our hack removes it too.
+        // Also track which items had corresponding getters, to make sure
+        // there is at least one item which does not (GcThreadCount or
+        // another gc-type-specific item).
+        final String[] surplus = {"Class", "CompositeType"};
+        for (String key : ct.keySet()) {
+            if (getters.remove(key))
+                items.remove(key);
+        }
+        if (!getters.equals(new HashSet<String>(Arrays.asList(surplus)))) {
+            throw new Exception("Wrong getters: " + getters);
+        }
+        if (items.isEmpty()) {
+            System.out.println("No type-specific items");
+            return 0;
+        } else {
+            System.out.println("Type-specific items: " + items);
+            return 1;
+        }
+    }
+}
diff --git a/jdk/test/java/lang/management/MXBean/MXBeanBehavior.java b/jdk/test/java/lang/management/MXBean/MXBeanBehavior.java
new file mode 100644
index 0000000..7469776
--- /dev/null
+++ b/jdk/test/java/lang/management/MXBean/MXBeanBehavior.java
@@ -0,0 +1,172 @@
+/*
+ * Copyright 2005 Sun Microsystems, Inc.  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 Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
+ * CA 95054 USA or visit www.sun.com if you need additional information or
+ * have any questions.
+ */
+
+/*
+ * @test
+ * @bug     6320211
+ * @summary Check that java.lang.management MXBeans have the same behavior
+ *          as user MXBeans
+ * @author  Eamonn McManus
+ * @run     main/othervm MXBeanBehavior
+ */
+
+import java.lang.management.*;
+import java.lang.reflect.*;
+import java.util.*;
+import javax.management.*;
+
+public class MXBeanBehavior {
+    public static void main(String[] args) throws Exception {
+        MBeanServer mbs = ManagementFactory.getPlatformMBeanServer();
+
+        /* Test that all the MBeans in the java.* and com.sun.management*
+           domains are MXBeans with the appropriate behavior.  */
+        Set<ObjectName> names = mbs.queryNames(new ObjectName("java.*:*"),
+                                               null);
+        names.addAll(mbs.queryNames(new ObjectName("com.sun.management*:*"),
+                                    null));
+        for (ObjectName name : names)
+            test(mbs, name);
+
+        /* Now do some rudimentary testing of inter-MXBean references.
+           It should be possible for a user MXBean to return e.g.  the
+           CompilationMXBean from the platform from an attribute of
+           type CompilationMXBean, and have the MXBean infrastructure
+           map this into that MXBean's standard ObjectName.  It should
+           also be possible for a proxy for this user MXBean to have
+           this attribute's value mapped back into a CompilationMXBean
+           instance, which however will be another proxy rather than
+           the original object.  Finally, it should be possible to set
+           the attribute in the user's MXBean through a proxy, giving
+           the real CompilationMXBean as an argument, and have this be
+           translated into that MXBean's standard ObjectName.  The
+           user's MXBean will receive a proxy in this case, though we
+           don't check that.  */
+        ObjectName refName = new ObjectName("d:type=CompilationRef");
+        mbs.registerMBean(new CompilationImpl(), refName);
+        CompilationRefMXBean refProxy =
+            JMX.newMXBeanProxy(mbs, refName, CompilationRefMXBean.class);
+        refProxy.getCompilationMXBean();
+        refProxy.setCompilationMXBean(ManagementFactory.getCompilationMXBean());
+        ObjectName on =
+            (ObjectName) mbs.getAttribute(refName, "CompilationMXBean");
+        checkEqual(on, new ObjectName(ManagementFactory.COMPILATION_MXBEAN_NAME),
+                   "Referenced object name");
+        mbs.setAttribute(refName, new Attribute("CompilationMXBean", on));
+
+        System.out.println("TEST PASSED");
+    }
+
+    /* Check the behavior of this MXBean to ensure that it conforms to
+       what is expected of all MXBeans as detailed in
+       javax.management.MXBean.  Its MBeanInfo should have a
+       Descriptor with the fields mxbean and interfaceClassName, and
+       furthermore we know that our implementation sets immutableInfo
+       here.  Each attribute should have Descriptor with the fields
+       openType and originalType that have appropriate values.  We
+       don't currently check operations though the same considerations
+       would apply there.  (If the MBeanInfo and MBeanAttributeInfo
+       tests pass we can reasonably suppose that this MXBean will
+       behave the same as all other MXBeans, so MBeanOperationInfo,
+       MBeanNotificationInfo, and MBeanConstructorInfo will be covered
+       by generic MXBean tests.
+     */
+    private static void test(MBeanServer mbs, ObjectName name) throws Exception {
+        System.out.println("Testing: " + name);
+
+        MBeanInfo mbi = mbs.getMBeanInfo(name);
+        Descriptor mbid = mbi.getDescriptor();
+        Object[] values = mbid.getFieldValues("immutableInfo",
+                                              "interfaceClassName",
+                                              "mxbean");
+        checkEqual(values[0], "true", name + " immutableInfo field");
+        checkEqual(values[2], "true", name + " mxbean field");
+        String interfaceClassName = (String) values[1];
+        if (!mbs.isInstanceOf(name, interfaceClassName)) {
+            throw new RuntimeException(name + " not instance of " +
+                                       interfaceClassName);
+        }
+        Class interfaceClass = Class.forName(interfaceClassName);
+        for (MBeanAttributeInfo mbai : mbi.getAttributes()) {
+            Descriptor mbaid = mbai.getDescriptor();
+            Object[] avalues = mbaid.getFieldValues("openType",
+                                                    "originalType");
+            if (avalues[0] == null || avalues[1] == null) {
+                throw new RuntimeException("Null attribute descriptor fields: " +
+                                           Arrays.toString(avalues));
+            }
+            if (mbai.isReadable()) {
+                String mname = (mbai.isIs() ? "is" : "get") + mbai.getName();
+                Method m = interfaceClass.getMethod(mname);
+                Type t = m.getGenericReturnType();
+                String ret =
+                    (t instanceof Class) ? ((Class) t).getName() : t.toString();
+                if (!ret.equals(avalues[1])) {
+                    final String msg =
+                        name + " attribute " + mbai.getName() + " has wrong " +
+                        "originalType: " + avalues[1] + " vs " + ret;
+                    throw new RuntimeException(msg);
+                }
+            }
+        }
+    }
+
+    private static void checkEqual(Object x, Object y, String what) {
+        final boolean eq;
+        if (x == y)
+            eq = true;
+        else if (x == null)
+            eq = false;
+        else
+            eq = x.equals(y);
+        if (!eq)
+            throw new RuntimeException(what + " should be " + y + ", is " + x);
+    }
+
+    public static interface CompilationRefMXBean {
+        public CompilationMXBean getCompilationMXBean();
+        public void setCompilationMXBean(CompilationMXBean mxb);
+    }
+
+    public static class CompilationImpl implements CompilationRefMXBean {
+        public CompilationMXBean getCompilationMXBean() {
+            return ManagementFactory.getCompilationMXBean();
+        }
+
+        public void setCompilationMXBean(CompilationMXBean mxb) {
+            if (mxb == ManagementFactory.getCompilationMXBean())
+                return;
+            MBeanServerInvocationHandler mbsih = (MBeanServerInvocationHandler)
+                Proxy.getInvocationHandler(mxb);
+            ObjectName expectedName;
+            try {
+                expectedName =
+                    new ObjectName(ManagementFactory.COMPILATION_MXBEAN_NAME);
+            } catch (MalformedObjectNameException e) {
+                throw new RuntimeException(e);
+            }
+            checkEqual(mbsih.getObjectName(), expectedName,
+                       "Proxy name in setCompilationMXBean");
+        }
+    }
+}
diff --git a/jdk/test/java/lang/management/ManagementFactory/MBeanServerMXBeanUnsupportedTest.java b/jdk/test/java/lang/management/ManagementFactory/MBeanServerMXBeanUnsupportedTest.java
new file mode 100644
index 0000000..a70e7a1
--- /dev/null
+++ b/jdk/test/java/lang/management/ManagementFactory/MBeanServerMXBeanUnsupportedTest.java
@@ -0,0 +1,165 @@
+/*
+ * Copyright 2006 Sun Microsystems, Inc.  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 Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
+ * CA 95054 USA or visit www.sun.com if you need additional information or
+ * have any questions.
+ */
+
+/*
+ * @test
+ * @bug 6403794
+ * @summary Test that all the platform MXBeans are wrapped in StandardMBean so
+ *          an MBeanServer which does not have support for MXBeans can be used.
+ * @author Luis-Miguel Alventosa
+ * @run clean MBeanServerMXBeanUnsupportedTest
+ * @run build MBeanServerMXBeanUnsupportedTest
+ * @run main MBeanServerMXBeanUnsupportedTest
+ */
+
+import java.lang.management.ManagementFactory;
+import java.lang.reflect.InvocationHandler;
+import java.lang.reflect.Method;
+import java.lang.reflect.Proxy;
+import javax.management.MBeanServer;
+import javax.management.MBeanServerBuilder;
+import javax.management.MBeanServerDelegate;
+import javax.management.ObjectName;
+import javax.management.StandardMBean;
+import javax.management.remote.MBeanServerForwarder;
+
+public class MBeanServerMXBeanUnsupportedTest {
+
+    /**
+     * An MBeanServerBuilder that returns an MBeanServer which throws a
+     * RuntimeException if MXBeans are not converted into StandardMBean.
+     */
+    public static class MBeanServerBuilderImpl extends MBeanServerBuilder {
+
+        private final MBeanServerBuilder inner;
+
+        public MBeanServerBuilderImpl() {
+            inner = new MBeanServerBuilder();
+        }
+
+        public MBeanServer newMBeanServer(
+                String defaultDomain,
+                MBeanServer outer,
+                MBeanServerDelegate delegate) {
+            final MBeanServerForwarder mbsf =
+                    MBeanServerForwarderInvocationHandler.newProxyInstance();
+
+            final MBeanServer innerMBeanServer =
+                    inner.newMBeanServer(defaultDomain,
+                    (outer == null ? mbsf : outer),
+                    delegate);
+
+            mbsf.setMBeanServer(innerMBeanServer);
+            return mbsf;
+        }
+    }
+
+    /**
+     * An MBeanServerForwarderInvocationHandler that throws a
+     * RuntimeException if we try to register a non StandardMBean.
+     */
+    public static class MBeanServerForwarderInvocationHandler
+            implements InvocationHandler {
+
+        public static MBeanServerForwarder newProxyInstance() {
+
+            final InvocationHandler handler =
+                    new MBeanServerForwarderInvocationHandler();
+
+            final Class[] interfaces =
+                    new Class[] {MBeanServerForwarder.class};
+
+            Object proxy = Proxy.newProxyInstance(
+                    MBeanServerForwarder.class.getClassLoader(),
+                    interfaces,
+                    handler);
+
+            return MBeanServerForwarder.class.cast(proxy);
+        }
+
+        public Object invoke(Object proxy, Method method, Object[] args)
+                throws Throwable {
+
+            final String methodName = method.getName();
+
+            if (methodName.equals("getMBeanServer")) {
+                return mbs;
+            }
+
+            if (methodName.equals("setMBeanServer")) {
+                if (args[0] == null)
+                    throw new IllegalArgumentException("Null MBeanServer");
+                if (mbs != null)
+                    throw new IllegalArgumentException("MBeanServer object " +
+                            "already initialized");
+                mbs = (MBeanServer) args[0];
+                return null;
+            }
+
+            if (methodName.equals("registerMBean")) {
+                Object mbean = args[0];
+                ObjectName name = (ObjectName) args[1];
+                String domain = name.getDomain();
+                System.out.println("registerMBean: class=" +
+                        mbean.getClass().getName() + "\tname=" + name);
+                Object result = method.invoke(mbs, args);
+                if (domain.equals("java.lang") ||
+                    domain.equals("java.util.logging") ||
+                    domain.equals("com.sun.management")) {
+                    String mxbean = (String)
+                        mbs.getMBeanInfo(name).getDescriptor().getFieldValue("mxbean");
+                    if (mxbean == null || !mxbean.equals("true")) {
+                        throw new RuntimeException(
+                                "Platform MBeans must be MXBeans!");
+                    }
+                    if (!(mbean instanceof StandardMBean)) {
+                        throw new RuntimeException(
+                                "MXBeans must be wrapped in StandardMBean!");
+                    }
+                }
+                return result;
+            }
+
+            return method.invoke(mbs, args);
+        }
+
+        private MBeanServer mbs;
+    }
+
+    /*
+     * Standalone entry point.
+     *
+     * Run the test and report to stdout.
+     */
+    public static void main(String args[]) throws Exception {
+        System.setProperty("javax.management.builder.initial",
+                MBeanServerBuilderImpl.class.getName());
+        try {
+            ManagementFactory.getPlatformMBeanServer();
+        } catch (RuntimeException e) {
+            System.out.println(">>> Unhappy Bye, Bye!");
+            throw e;
+        }
+        System.out.println(">>> Happy Bye, Bye!");
+    }
+}
diff --git a/jdk/test/java/lang/management/ManagementFactory/MXBeanException.java b/jdk/test/java/lang/management/ManagementFactory/MXBeanException.java
new file mode 100644
index 0000000..5d3dc17
--- /dev/null
+++ b/jdk/test/java/lang/management/ManagementFactory/MXBeanException.java
@@ -0,0 +1,101 @@
+/*
+ * Copyright 2004-2005 Sun Microsystems, Inc.  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 Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
+ * CA 95054 USA or visit www.sun.com if you need additional information or
+ * have any questions.
+ */
+
+/*
+ * @test
+ * @bug     5058319
+ * @summary Check if a RuntimeException is wrapped by RuntimeMBeanException
+ *          only once.
+ *
+ * @author  Mandy Chung
+ *
+ * @build MXBeanException
+ * @run main MXBeanException
+ */
+
+import java.lang.management.*;
+import javax.management.*;
+import java.util.*;
+import static java.lang.management.ManagementFactory.*;
+
+public class MXBeanException {
+    private static MemoryPoolMXBean pool;
+
+    public static void main(String[] argv) throws Exception {
+        List<MemoryPoolMXBean> pools =
+            ManagementFactory.getMemoryPoolMXBeans();
+        for (MemoryPoolMXBean p : pools) {
+            if (!p.isUsageThresholdSupported()) {
+                pool = p;
+                break;
+            }
+        }
+
+        // check if UnsupportedOperationException is thrown
+        try {
+            pool.setUsageThreshold(1000);
+            throw new RuntimeException("TEST FAILED: " +
+                "UnsupportedOperationException not thrown");
+        } catch (UnsupportedOperationException e) {
+            // expected
+        }
+
+        // check if UnsupportedOperationException is thrown
+        // when calling through MBeanServer
+        MBeanServer mbs = ManagementFactory.getPlatformMBeanServer();
+        ObjectName on = new ObjectName(MEMORY_POOL_MXBEAN_DOMAIN_TYPE +
+                                       ",name=" + pool.getName());
+        Attribute att = new Attribute("UsageThreshold", 1000);
+        try {
+            mbs.setAttribute(on, att);
+        } catch (RuntimeMBeanException e) {
+            checkMBeanException(e);
+        } catch (RuntimeOperationsException e) {
+            checkMBeanException(e);
+        }
+
+        // check if UnsupportedOperationException is thrown
+        // when calling through proxy
+
+        MemoryPoolMXBean proxy = newPlatformMXBeanProxy(mbs,
+                                     on.toString(),
+                                     MemoryPoolMXBean.class);
+        try {
+            proxy.setUsageThreshold(1000);
+            throw new RuntimeException("TEST FAILED: " +
+                "UnsupportedOperationException not thrown via proxy");
+        } catch (UnsupportedOperationException e) {
+            // expected
+        }
+
+        System.out.println("Test passed");
+    }
+
+    private static void checkMBeanException(JMRuntimeException e) {
+        Throwable cause = e.getCause();
+        if (!(cause instanceof UnsupportedOperationException)) {
+            throw new RuntimeException("TEST FAILED: " + cause +
+                "is not UnsupportedOperationException");
+        }
+    }
+}
diff --git a/jdk/test/java/lang/management/ManagementFactory/MXBeanProxyTest.java b/jdk/test/java/lang/management/ManagementFactory/MXBeanProxyTest.java
new file mode 100644
index 0000000..afd6618
--- /dev/null
+++ b/jdk/test/java/lang/management/ManagementFactory/MXBeanProxyTest.java
@@ -0,0 +1,124 @@
+/*
+ * Copyright 2004 Sun Microsystems, Inc.  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 Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
+ * CA 95054 USA or visit www.sun.com if you need additional information or
+ * have any questions.
+ */
+
+/*
+ * @test
+ * @bug     5024531
+ * @summary Basic Test for ManagementFactory.newPlatformMXBean().
+ * @author  Mandy Chung
+ *
+ * @compile -source 1.5 MXBeanProxyTest.java
+ * @run main MXBeanProxyTest
+ */
+import javax.management.*;
+import java.lang.management.ClassLoadingMXBean;
+import java.lang.management.RuntimeMXBean;
+import static java.lang.management.ManagementFactory.*;
+public class MXBeanProxyTest {
+    private static MBeanServer server = getPlatformMBeanServer();
+    public static void main(String[] argv) throws Exception {
+        boolean iae = false;
+        try {
+            // Get a MXBean proxy with invalid name
+            newPlatformMXBeanProxy(server,
+                                   "Invalid ObjectName",
+                                   RuntimeMXBean.class);
+        } catch (IllegalArgumentException e) {
+            // Expected exception
+            System.out.println("EXPECTED: " + e);
+            iae = true;
+        }
+        if (!iae) {
+            throw new RuntimeException("Invalid ObjectName " +
+                " was not detected");
+        }
+
+        try {
+            // Get a MXBean proxy with non existent MXBean
+            newPlatformMXBeanProxy(server,
+                                   "java.lang:type=Foo",
+                                   RuntimeMXBean.class);
+            iae = false;
+        } catch (IllegalArgumentException e) {
+            // Expected exception
+            System.out.println("EXPECTED: " + e);
+            iae = true;
+        }
+        if (!iae) {
+            throw new RuntimeException("Non existent MXBean " +
+                " was not detected");
+        }
+
+        try {
+            // Mismatch MXBean interface
+            newPlatformMXBeanProxy(server,
+                                   RUNTIME_MXBEAN_NAME,
+                                   ClassLoadingMXBean.class);
+            iae = false;
+        } catch (IllegalArgumentException e) {
+            // Expected exception
+            System.out.println("EXPECTED: " + e);
+            iae = true;
+        }
+        if (!iae) {
+            throw new RuntimeException("Mismatched MXBean interface " +
+                " was not detected");
+        }
+
+        final FooMBean foo = new Foo();
+        final ObjectName objName = new ObjectName("java.lang:type=Foo");
+        server.registerMBean(foo, objName);
+        try {
+            // non-platform MXBean
+            newPlatformMXBeanProxy(server,
+                                   "java.lang:type=Foo",
+                                   FooMBean.class);
+            iae = false;
+        } catch (IllegalArgumentException e) {
+            // Expected exception
+            System.out.println("EXPECTED: " + e);
+            iae = true;
+        }
+        if (!iae) {
+            throw new RuntimeException("Non-platform MXBean " +
+                " was not detected");
+        }
+
+
+        // Successfully get MXBean
+        RuntimeMXBean rm = newPlatformMXBeanProxy(server,
+                                                  RUNTIME_MXBEAN_NAME,
+                                                  RuntimeMXBean.class);
+        System.out.println("VM uptime = " + rm.getUptime());
+        System.out.println("Test passed.");
+    }
+
+    public interface FooMBean {
+        public boolean isFoo();
+    }
+    static class Foo implements FooMBean {
+        public boolean isFoo() {
+            return true;
+        }
+    }
+}
diff --git a/jdk/test/java/lang/management/ManagementFactory/PlatformMBeanServerTest.java b/jdk/test/java/lang/management/ManagementFactory/PlatformMBeanServerTest.java
new file mode 100644
index 0000000..7deb892
--- /dev/null
+++ b/jdk/test/java/lang/management/ManagementFactory/PlatformMBeanServerTest.java
@@ -0,0 +1,143 @@
+/*
+ * Copyright 2003-2004 Sun Microsystems, Inc.  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 Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
+ * CA 95054 USA or visit www.sun.com if you need additional information or
+ * have any questions.
+ */
+
+/*
+ * @test
+ * @bug     4947536
+ * @summary Basic unit test of ManagementFactory.getPlatformMBeanServer()
+ * @author  Mandy Chung
+ *
+ * @compile -source 1.5 PlatformMBeanServerTest.java
+ * @run main PlatformMBeanServerTest
+ */
+
+import java.lang.management.*;
+import static java.lang.management.ManagementFactory.*;
+import java.util.*;
+import java.util.logging.LogManager;
+
+import javax.management.MBeanServer;
+import javax.management.ObjectName;
+
+public class PlatformMBeanServerTest {
+    public static void main(String[] argv) throws Exception {
+        MBeanServer mbs = ManagementFactory.getPlatformMBeanServer();
+        printMBeans(mbs);
+
+        // validate if all standard JVM MBeans are registered
+        checkStandardMBeans(mbs);
+
+        // validate if all platform MBeans are registered
+        checkPlatformMBeans(mbs);
+
+        MBeanServer mbs1 = ManagementFactory.getPlatformMBeanServer();
+        if (mbs != mbs1) {
+            throw new RuntimeException("Second call to getPlatformMBeanServer()"
+                + " returns a different MBeanServer.");
+        }
+
+        System.out.println("Test passed.");
+    }
+
+    private static void checkMBean(MBeanServer mbs, String mbeanName)
+            throws Exception {
+        try {
+            ObjectName objName = new ObjectName(mbeanName);
+            // We could call mbs.isRegistered(objName) here.
+            // Calling getMBeanInfo will throw exception if not found.
+            mbs.getMBeanInfo(objName);
+        } catch (Exception e) {
+            throw e;
+        }
+    }
+    private static void checkStandardMBeans(MBeanServer mbs) throws Exception {
+        checkMBean(mbs, CLASS_LOADING_MXBEAN_NAME);
+        checkMBean(mbs, MEMORY_MXBEAN_NAME);
+        checkMBean(mbs, OPERATING_SYSTEM_MXBEAN_NAME);
+        checkMBean(mbs, RUNTIME_MXBEAN_NAME);
+        checkMBean(mbs, THREAD_MXBEAN_NAME);
+        if (ManagementFactory.getCompilationMXBean() != null) {
+            checkMBean(mbs, COMPILATION_MXBEAN_NAME);
+        }
+
+        List pools = ManagementFactory.getMemoryPoolMXBeans();
+        for (ListIterator iter = pools.listIterator(); iter.hasNext(); ) {
+            MemoryPoolMXBean p = (MemoryPoolMXBean) iter.next();
+            checkMBean(mbs, MEMORY_POOL_MXBEAN_DOMAIN_TYPE + ",name=" + p.getName());
+        }
+
+        // Check the number of memory pools in the mbs
+        Set set = mbs.queryNames(new ObjectName(MEMORY_POOL_MXBEAN_DOMAIN_TYPE + ",*"), null);
+        if (set.size() != pools.size()) {
+            throw new RuntimeException("Unexpected number of memory pools:" +
+                "MBeanServer has " + set.size() +
+                ". Expected = " + pools.size());
+        }
+
+        List mgrs = ManagementFactory.getMemoryManagerMXBeans();
+        int num_mgrs = 0;
+        for (ListIterator iter = mgrs.listIterator(); iter.hasNext(); ) {
+            MemoryManagerMXBean m = (MemoryManagerMXBean) iter.next();
+            if (m instanceof GarbageCollectorMXBean) {
+                checkMBean(mbs, GARBAGE_COLLECTOR_MXBEAN_DOMAIN_TYPE
+                                    + ",name=" + m.getName());
+            } else {
+                checkMBean(mbs, MEMORY_MANAGER_MXBEAN_DOMAIN_TYPE
+                                    + ",name=" + m.getName());
+                num_mgrs++;
+            }
+        }
+
+        List gcs = ManagementFactory.getGarbageCollectorMXBeans();
+        for (ListIterator iter = gcs.listIterator(); iter.hasNext(); ) {
+            GarbageCollectorMXBean gc = (GarbageCollectorMXBean) iter.next();
+            checkMBean(mbs, GARBAGE_COLLECTOR_MXBEAN_DOMAIN_TYPE
+                                + ",name=" + gc.getName());
+        }
+
+        // Check the number of memory managers and garbage collectors in the mbs
+        set = mbs.queryNames(new ObjectName(MEMORY_MANAGER_MXBEAN_DOMAIN_TYPE + ",*"), null);
+        if (set.size() != num_mgrs) {
+            throw new RuntimeException("Unexpected number of memory managers:" +
+                "MBeanServer has " + set.size() +
+                ". Expected = " + num_mgrs);
+        }
+
+        set = mbs.queryNames(new ObjectName(GARBAGE_COLLECTOR_MXBEAN_DOMAIN_TYPE + ",*"), null);
+        if (set.size() != gcs.size()) {
+            throw new RuntimeException("Unexpected number of garbage collectors:" +
+                "MBeanServer has " + set.size() +
+                ". Expected = " + gcs.size());
+        }
+    }
+    private static void checkPlatformMBeans(MBeanServer mbs) throws Exception {
+        checkMBean(mbs, LogManager.LOGGING_MXBEAN_NAME);
+    }
+
+    private static void printMBeans(MBeanServer mbs) throws Exception {
+        Set set = mbs.queryNames(null, null);
+        for (Iterator iter = set.iterator(); iter.hasNext(); ) {
+            System.out.println(iter.next());
+        }
+    }
+}
diff --git a/jdk/test/java/lang/management/ManagementFactory/ProxyExceptions.java b/jdk/test/java/lang/management/ManagementFactory/ProxyExceptions.java
new file mode 100644
index 0000000..5be2510
--- /dev/null
+++ b/jdk/test/java/lang/management/ManagementFactory/ProxyExceptions.java
@@ -0,0 +1,123 @@
+/*
+ * Copyright 2004 Sun Microsystems, Inc.  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 Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
+ * CA 95054 USA or visit www.sun.com if you need additional information or
+ * have any questions.
+ */
+
+/*
+ * @test
+ * @bug     5024531
+ * @summary Test type mapping of the platform MXBean proxy
+ *          returned from Management.newPlatformMXBeanProxy().
+ * @author  Mandy Chung
+ *
+ * @compile -source 1.5 ProxyExceptions.java
+ * @run main ProxyExceptions
+ */
+import java.lang.management.*;
+import javax.management.*;
+import static java.lang.management.ManagementFactory.*;
+import java.util.List;
+import java.util.Map;
+import java.util.Properties;
+import com.sun.management.GcInfo;
+
+public class ProxyExceptions {
+    private static MBeanServer server =
+        ManagementFactory.getPlatformMBeanServer();
+    private static MemoryPoolMXBean heapPool = null;
+    private static MemoryPoolMXBean nonHeapPool = null;
+    public static void main(String[] argv) throws Exception {
+        List<MemoryPoolMXBean> pools = getMemoryPoolMXBeans();
+        for (MemoryPoolMXBean p : pools) {
+            MemoryPoolMXBean proxy = newPlatformMXBeanProxy(server,
+                MEMORY_POOL_MXBEAN_DOMAIN_TYPE + ",name=" + p.getName(),
+                MemoryPoolMXBean.class);
+            boolean uoeCaught;
+            if (!p.isUsageThresholdSupported()) {
+                try {
+                    proxy.getUsageThreshold();
+                    uoeCaught = false;
+                } catch (UnsupportedOperationException e) {
+                    uoeCaught = true;
+                }
+                if (!uoeCaught) {
+                    throw new RuntimeException("TEST FAILED: " +
+                        "UnsupportedOperationException not thrown " +
+                        "when calling getUsageThreshold on " + p.getName());
+                }
+                try {
+                    proxy.setUsageThreshold(100);
+                    uoeCaught = false;
+                } catch (UnsupportedOperationException e) {
+                    uoeCaught = true;
+                }
+                if (!uoeCaught) {
+                    throw new RuntimeException("TEST FAILED: " +
+                        "UnsupportedOperationException not thrown " +
+                        "when calling setUsageThreshold on " + p.getName());
+                }
+            }
+            if (!p.isCollectionUsageThresholdSupported()) {
+                try {
+                    proxy.getCollectionUsageThreshold();
+                    uoeCaught = false;
+                } catch (UnsupportedOperationException e) {
+                    uoeCaught = true;
+                }
+                if (!uoeCaught) {
+                    throw new RuntimeException("TEST FAILED: " +
+                        "UnsupportedOperationException not thrown " +
+                        "when calling getCollectionUsageThreshold on " +
+                        p.getName());
+                }
+                try {
+                    proxy.setCollectionUsageThreshold(100);
+                    uoeCaught = false;
+                } catch (UnsupportedOperationException e) {
+                    uoeCaught = true;
+                }
+                if (!uoeCaught) {
+                    throw new RuntimeException("TEST FAILED: " +
+                        "UnsupportedOperationException not thrown " +
+                        "when calling getCollectionUsageThreshold on " +
+                        p.getName());
+                }
+            }
+        }
+
+        ThreadMXBean thread = newPlatformMXBeanProxy(server,
+                                                  THREAD_MXBEAN_NAME,
+                                                  ThreadMXBean.class);
+        boolean iaeCaught = false;
+        try {
+            thread.getThreadInfo(-1);
+        } catch (IllegalArgumentException e) {
+            iaeCaught = true;
+        }
+        if (!iaeCaught) {
+            throw new RuntimeException("TEST FAILED: " +
+                "IllegalArgumentException not thrown " +
+                "when calling getThreadInfo(-1)");
+        }
+
+        System.out.println("Test passed.");
+    }
+}
diff --git a/jdk/test/java/lang/management/ManagementFactory/ProxyTypeMapping.java b/jdk/test/java/lang/management/ManagementFactory/ProxyTypeMapping.java
new file mode 100644
index 0000000..eb48825
--- /dev/null
+++ b/jdk/test/java/lang/management/ManagementFactory/ProxyTypeMapping.java
@@ -0,0 +1,269 @@
+/*
+ * Copyright 2004 Sun Microsystems, Inc.  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 Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
+ * CA 95054 USA or visit www.sun.com if you need additional information or
+ * have any questions.
+ */
+
+/*
+ * @test
+ * @bug     5024531
+ * @summary Test type mapping of the platform MXBean proxy
+ *          returned from Management.newPlatformMXBeanProxy().
+ * @author  Mandy Chung
+ *
+ * @compile -source 1.5 ProxyTypeMapping.java
+ * @run main/othervm -verbose:gc ProxyTypeMapping
+ */
+import java.lang.management.*;
+import javax.management.*;
+import static java.lang.management.ManagementFactory.*;
+import java.util.List;
+import java.util.Map;
+import java.util.Properties;
+import com.sun.management.GcInfo;
+
+public class ProxyTypeMapping {
+    private static MBeanServer server =
+        ManagementFactory.getPlatformMBeanServer();
+    private static RuntimeMXBean runtime;
+    private static ThreadMXBean thread;
+    private static MemoryMXBean memory;
+    private static MemoryPoolMXBean heapPool = null;
+    private static MemoryPoolMXBean nonHeapPool = null;
+    public static void main(String[] argv) throws Exception {
+        runtime = newPlatformMXBeanProxy(server,
+                                         RUNTIME_MXBEAN_NAME,
+                                         RuntimeMXBean.class);
+        thread = newPlatformMXBeanProxy(server,
+                                        THREAD_MXBEAN_NAME,
+                                        ThreadMXBean.class);
+        memory = newPlatformMXBeanProxy(server,
+                                        MEMORY_MXBEAN_NAME,
+                                        MemoryMXBean.class);
+
+        // check notification emitter
+        MyListener listener = new MyListener();
+        NotificationEmitter emitter = (NotificationEmitter) memory;
+        emitter.addNotificationListener(listener, null, null);
+        emitter.removeNotificationListener(listener);
+
+        List<MemoryPoolMXBean> pools = getMemoryPoolMXBeans();
+        for (MemoryPoolMXBean p : pools) {
+            if (heapPool == null &&
+                p.getType() == MemoryType.HEAP &&
+                p.isUsageThresholdSupported() &&
+                p.isCollectionUsageThresholdSupported()) {
+                heapPool = p;
+            }
+            if (nonHeapPool == null &&
+                p.getType() == MemoryType.NON_HEAP &&
+                p.isUsageThresholdSupported()) {
+                nonHeapPool = p;
+            }
+        }
+
+        checkEnum();
+        checkList();
+        checkMap();
+        checkMemoryUsage();
+        checkThreadInfo();
+
+        checkOS();
+        checkSunGC();
+
+        System.out.println("Test passed.");
+    }
+
+    private static void checkEnum() throws Exception {
+        MemoryType type = heapPool.getType();
+        if (type != MemoryType.HEAP) {
+            throw new RuntimeException("TEST FAILED: " +
+                " incorrect memory type for " + heapPool.getName());
+        }
+
+        type = nonHeapPool.getType();
+        if (type != MemoryType.NON_HEAP) {
+            throw new RuntimeException("TEST FAILED: " +
+                " incorrect memory type for " + nonHeapPool.getName());
+        }
+    }
+
+    private static final String OPTION = "-verbose:gc";
+    private static void checkList() throws Exception {
+        List<String> args = runtime.getInputArguments();
+        if (args.size() < 1) {
+           throw new RuntimeException("TEST FAILED: " +
+                " empty input arguments");
+        }
+        // check if -verbose:gc exists
+        boolean found = false;
+        for (String option : args) {
+           if (option.equals(OPTION)) {
+               found = true;
+               break;
+           }
+        }
+        if (!found) {
+            throw new RuntimeException("TEST FAILED: " +
+                "VM option " + OPTION + " not found");
+        }
+    }
+
+    private static final String KEY1   = "test.property.key1";
+    private static final String VALUE1 = "test.property.value1";
+    private static final String KEY2   = "test.property.key2";
+    private static final String VALUE2 = "test.property.value2";
+    private static final String KEY3   = "test.property.key3";
+    private static void checkMap() throws Exception {
+        // Add new system properties
+        System.setProperty(KEY1, VALUE1);
+        System.setProperty(KEY2, VALUE2);
+
+        Map<String,String> props1 = runtime.getSystemProperties();
+        String value1 = props1.get(KEY1);
+        if (value1 == null || !value1.equals(VALUE1)) {
+            throw new RuntimeException("TEST FAILED: " +
+                 KEY1 + " property found" +
+                 " with value = " + value1 +
+                 " but expected to be " + VALUE1);
+        }
+
+        String value2 = props1.get(KEY2);
+        if (value2 == null || !value2.equals(VALUE2)) {
+            throw new RuntimeException("TEST FAILED: " +
+                 KEY2 + " property found" +
+                 " with value = " + value2 +
+                 " but expected to be " + VALUE2);
+        }
+
+        String value3 = props1.get(KEY3);
+        if (value3 != null) {
+            throw new RuntimeException("TEST FAILED: " +
+                 KEY3 + " property found" +
+                 " but should not exist" );
+        }
+    }
+
+    private static void checkMemoryUsage() throws Exception {
+        // sanity check to have non-zero usage
+        MemoryUsage u1 = memory.getHeapMemoryUsage();
+        MemoryUsage u2 = memory.getNonHeapMemoryUsage();
+        MemoryUsage u3 = heapPool.getUsage();
+        MemoryUsage u4 = nonHeapPool.getUsage();
+        if (u1.getCommitted() <= 0 ||
+            u2.getCommitted() <= 0 ||
+            u3.getCommitted() <= 0 ||
+            u4.getCommitted() <= 0) {
+            throw new RuntimeException("TEST FAILED: " +
+                " expected non-zero committed usage");
+        }
+        memory.gc();
+        MemoryUsage u5 = heapPool.getCollectionUsage();
+        if (u5.getCommitted() <= 0) {
+            throw new RuntimeException("TEST FAILED: " +
+                " expected non-zero committed collected usage");
+        }
+    }
+
+    private static void checkThreadInfo() throws Exception {
+        // assume all threads stay alive
+        long[] ids = thread.getAllThreadIds();
+        ThreadInfo[] infos = thread.getThreadInfo(ids);
+        for (ThreadInfo ti : infos) {
+            printThreadInfo(ti);
+        }
+        infos = thread.getThreadInfo(ids, 2);
+        for (ThreadInfo ti : infos) {
+            printThreadInfo(ti);
+        }
+        long id = Thread.currentThread().getId();
+        ThreadInfo info = thread.getThreadInfo(id);
+        printThreadInfo(info);
+        info = thread.getThreadInfo(id, 2);
+        printThreadInfo(info);
+    }
+
+    private static void printThreadInfo(ThreadInfo info) {
+        if (info == null) {
+            throw new RuntimeException("TEST FAILED: " +
+                " Null ThreadInfo");
+        }
+
+        System.out.print(info.getThreadName());
+        System.out.print(" id=" + info.getThreadId());
+        System.out.println(" " + info.getThreadState());
+
+        for (StackTraceElement s : info.getStackTrace()) {
+            System.out.println(s);
+        }
+    }
+
+    private static void checkOS() throws Exception {
+        com.sun.management.OperatingSystemMXBean os =
+            newPlatformMXBeanProxy(server,
+                                   OPERATING_SYSTEM_MXBEAN_NAME,
+                                   com.sun.management.OperatingSystemMXBean.class);
+        System.out.println("# CPUs = " + os.getAvailableProcessors());
+        System.out.println("Committed virtual memory = " +
+                           os.getCommittedVirtualMemorySize());
+    }
+
+    private static void checkSunGC() throws Exception {
+        // Test com.sun.management proxy
+        List<GarbageCollectorMXBean> gcs = getGarbageCollectorMXBeans();
+        for (GarbageCollectorMXBean gc : gcs) {
+            com.sun.management.GarbageCollectorMXBean sunGc =
+               newPlatformMXBeanProxy(server,
+                   GARBAGE_COLLECTOR_MXBEAN_DOMAIN_TYPE + ",name=" + gc.getName(),
+                   com.sun.management.GarbageCollectorMXBean.class);
+            GcInfo info = sunGc.getLastGcInfo();
+            if (info != null) {
+                System.out.println("GC statistic for : " + gc.getName());
+                printGcInfo(info);
+            }
+        }
+    }
+    private static void printGcInfo(GcInfo info) throws Exception {
+        System.out.print("GC #" + info.getId());
+        System.out.print(" start:" + info.getStartTime());
+        System.out.print(" end:" + info.getEndTime());
+        System.out.println(" (" + info.getDuration() + "ms)");
+        Map<String,MemoryUsage> usage = info.getMemoryUsageBeforeGc();
+
+        for (Map.Entry<String,MemoryUsage> entry : usage.entrySet()) {
+            String poolname = entry.getKey();
+            MemoryUsage busage = entry.getValue();
+            MemoryUsage ausage = info.getMemoryUsageAfterGc().get(poolname);
+            if (ausage == null) {
+                throw new RuntimeException("After Gc Memory does not exist" +
+                    " for " + poolname);
+            }
+            System.out.println("Usage for pool " + poolname);
+            System.out.println("   Before GC: " + busage);
+            System.out.println("   After GC: " + ausage);
+        }
+    }
+
+    static class MyListener implements NotificationListener {
+        public void handleNotification(Notification notif, Object handback) {
+            return;
+        }
+    }
+}
diff --git a/jdk/test/java/lang/management/ManagementFactory/StateTest.java b/jdk/test/java/lang/management/ManagementFactory/StateTest.java
new file mode 100644
index 0000000..f2dcf85
--- /dev/null
+++ b/jdk/test/java/lang/management/ManagementFactory/StateTest.java
@@ -0,0 +1,30 @@
+/*
+ * Copyright 2003 Sun Microsystems, Inc.  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 Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
+ * CA 95054 USA or visit www.sun.com if you need additional information or
+ * have any questions.
+ */
+
+public class StateTest implements StateTestMBean {
+    private int state;
+    public StateTest(int state) { this.state = state; }
+    public int getState() {
+        return state;
+    }
+}
diff --git a/jdk/test/java/lang/management/ManagementFactory/StateTestMBean.java b/jdk/test/java/lang/management/ManagementFactory/StateTestMBean.java
new file mode 100644
index 0000000..47cb157
--- /dev/null
+++ b/jdk/test/java/lang/management/ManagementFactory/StateTestMBean.java
@@ -0,0 +1,26 @@
+/*
+ * Copyright 2003 Sun Microsystems, Inc.  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 Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
+ * CA 95054 USA or visit www.sun.com if you need additional information or
+ * have any questions.
+ */
+
+public interface StateTestMBean {
+    public int getState();
+}
diff --git a/jdk/test/java/lang/management/ManagementFactory/ThreadMXBeanProxy.java b/jdk/test/java/lang/management/ManagementFactory/ThreadMXBeanProxy.java
new file mode 100644
index 0000000..f76794f
--- /dev/null
+++ b/jdk/test/java/lang/management/ManagementFactory/ThreadMXBeanProxy.java
@@ -0,0 +1,237 @@
+/*
+ * Copyright 2005 Sun Microsystems, Inc.  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 Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
+ * CA 95054 USA or visit www.sun.com if you need additional information or
+ * have any questions.
+ */
+
+/*
+ * @test
+ * @bug     5086470 6358247
+ * @summary Test type conversion when invoking ThreadMXBean.dumpAllThreads
+ *          through proxy.
+ *
+ * @author  Mandy Chung
+ *
+ * @run main ThreadMXBeanProxy
+ */
+
+import static java.lang.management.ManagementFactory.*;
+import java.lang.management.*;
+import java.util.*;
+import java.util.concurrent.locks.*;
+import java.util.concurrent.TimeUnit;
+import java.io.*;
+import javax.management.*;
+
+public class ThreadMXBeanProxy {
+    private static MBeanServer server =
+        ManagementFactory.getPlatformMBeanServer();
+    private static ThreadMXBean mbean;
+    static Mutex mutex = new Mutex();
+    static Object lock = new Object();
+    static MyThread thread = new MyThread();
+    public static void main(String[] argv) throws Exception {
+        mbean = newPlatformMXBeanProxy(server,
+                                       THREAD_MXBEAN_NAME,
+                                       ThreadMXBean.class);
+
+        if (!mbean.isSynchronizerUsageSupported()) {
+            System.out.println("Monitoring of synchronizer usage not supported");
+            return;
+        }
+
+        thread.setDaemon(true);
+        thread.start();
+
+        // wait until myThread acquires mutex
+        while (!mutex.isLocked()) {
+           try {
+               Thread.sleep(100);
+           } catch (InterruptedException e) {
+               throw new RuntimeException(e);
+           }
+        }
+
+        long[] ids = new long[] { thread.getId() };
+
+        // validate the local access
+        ThreadInfo[] infos = getThreadMXBean().getThreadInfo(ids, true, true);
+        if (ids.length != 1) {
+            throw new RuntimeException("Returned ThreadInfo[] of length=" +
+                ids.length + ". Expected to be 1.");
+        }
+        thread.checkThreadInfo(infos[0]);
+
+        // validate the remote access
+        infos = mbean.getThreadInfo(ids, true, true);
+        if (ids.length != 1) {
+            throw new RuntimeException("Returned ThreadInfo[] of length=" +
+                ids.length + ". Expected to be 1.");
+        }
+        thread.checkThreadInfo(infos[0]);
+
+        boolean found = false;
+        infos = mbean.dumpAllThreads(true, true);
+        for (ThreadInfo ti : infos) {
+            if (ti.getThreadId() == thread.getId()) {
+                thread.checkThreadInfo(ti);
+                found = true;
+            }
+        }
+
+        if (!found) {
+            throw new RuntimeException("No ThreadInfo found for MyThread");
+        }
+
+        System.out.println("Test passed");
+    }
+
+    static class MyThread extends Thread {
+        public MyThread() {
+            super("MyThread");
+        }
+        public void run() {
+            synchronized (lock) {
+                mutex.lock();
+                Object o = new Object();
+                synchronized(o) {
+                    try {
+                        o.wait();
+                    } catch (InterruptedException e) {
+                        throw new RuntimeException(e);
+                    }
+                }
+            }
+        }
+
+        int OWNED_MONITORS = 1;
+        int OWNED_SYNCS = 1;
+        void checkThreadInfo(ThreadInfo info) {
+            if (!getName().equals(info.getThreadName())) {
+                throw new RuntimeException("Name: " + info.getThreadName() +
+                    " not matched. Expected: " + getName());
+            }
+
+            MonitorInfo[] monitors = info.getLockedMonitors();
+            if (monitors.length != OWNED_MONITORS) {
+                throw new RuntimeException("Number of locked monitors = " +
+                    monitors.length +
+                    " not matched. Expected: " + OWNED_MONITORS);
+            }
+            MonitorInfo m = monitors[0];
+            StackTraceElement ste = m.getLockedStackFrame();
+            int depth = m.getLockedStackDepth();
+            StackTraceElement[] stacktrace = info.getStackTrace();
+            if (!ste.equals(stacktrace[depth])) {
+                System.out.println("LockedStackFrame:- " + ste);
+                System.out.println("StackTrace at " + depth + " :-" +
+                    stacktrace[depth]);
+                throw new RuntimeException("LockedStackFrame does not match " +
+                    "stack frame in ThreadInfo.getStackTrace");
+           }
+
+           String className = lock.getClass().getName();
+           int hcode = System.identityHashCode(lock);
+           if (!className.equals(m.getClassName()) ||
+                   hcode != m.getIdentityHashCode() ||
+                   !m.getLockedStackFrame().getMethodName().equals("run")) {
+                System.out.println(info);
+                throw new RuntimeException("MonitorInfo " + m +
+                   " doesn't match.");
+            }
+
+            LockInfo[] syncs = info.getLockedSynchronizers();
+            if (syncs.length != OWNED_SYNCS) {
+                throw new RuntimeException("Number of locked syncs = " +
+                    syncs.length +
+                    " not matched. Expected: " + OWNED_SYNCS);
+            }
+            AbstractOwnableSynchronizer s = mutex.getSync();
+            String lockName = s.getClass().getName();
+            hcode = System.identityHashCode(s);
+            if (!lockName.equals(syncs[0].getClassName())) {
+                throw new RuntimeException("LockInfo : " + syncs[0] +
+                    " class name not matched. Expected: " + lockName);
+            }
+            if (hcode != syncs[0].getIdentityHashCode()) {
+                throw new RuntimeException("LockInfo: " + syncs[0] +
+                    " IdentityHashCode not matched. Expected: " + hcode);
+            }
+
+        }
+    }
+    static class Mutex implements Lock, java.io.Serializable {
+
+        // Our internal helper class
+        class Sync extends AbstractQueuedSynchronizer {
+            // Report whether in locked state
+            protected boolean isHeldExclusively() {
+                return getState() == 1;
+            }
+
+            // Acquire the lock if state is zero
+            public boolean tryAcquire(int acquires) {
+                assert acquires == 1; // Otherwise unused
+                if (compareAndSetState(0, 1)) {
+                    setExclusiveOwnerThread(Thread.currentThread());
+                    return true;
+                }
+                return false;
+            }
+
+            // Release the lock by setting state to zero
+            protected boolean tryRelease(int releases) {
+                assert releases == 1; // Otherwise unused
+                if (getState() == 0) throw new IllegalMonitorStateException();
+                setExclusiveOwnerThread(null);
+                setState(0);
+                return true;
+            }
+
+            // Provide a Condition
+            Condition newCondition() { return new ConditionObject(); }
+
+            // Deserialize properly
+            private void readObject(ObjectInputStream s)
+                throws IOException, ClassNotFoundException {
+                s.defaultReadObject();
+                setState(0); // reset to unlocked state
+            }
+        }
+
+        // The sync object does all the hard work. We just forward to it.
+        private final Sync sync = new Sync();
+
+        public void lock()                { sync.acquire(1); }
+        public boolean tryLock()          { return sync.tryAcquire(1); }
+        public void unlock()              { sync.release(1); }
+        public Condition newCondition()   { return sync.newCondition(); }
+        public boolean isLocked()         { return sync.isHeldExclusively(); }
+        public boolean hasQueuedThreads() { return sync.hasQueuedThreads(); }
+        public void lockInterruptibly() throws InterruptedException {
+            sync.acquireInterruptibly(1);
+        }
+        public boolean tryLock(long timeout, TimeUnit unit) throws InterruptedException {
+            return sync.tryAcquireNanos(1, unit.toNanos(timeout));
+        }
+
+        public AbstractOwnableSynchronizer getSync() { return sync; }
+    }
+}
diff --git a/jdk/test/java/lang/management/ManagementFactory/ValidateOpenTypes.java b/jdk/test/java/lang/management/ManagementFactory/ValidateOpenTypes.java
new file mode 100644
index 0000000..68d5304
--- /dev/null
+++ b/jdk/test/java/lang/management/ManagementFactory/ValidateOpenTypes.java
@@ -0,0 +1,304 @@
+/*
+ * Copyright 2004 Sun Microsystems, Inc.  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 Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
+ * CA 95054 USA or visit www.sun.com if you need additional information or
+ * have any questions.
+ */
+
+/*
+ * @test
+ * @bug     5024531
+ * @summary Validata open types mapped for the MXBeans in the platform
+ *          MBeanServer.
+ * @author  Mandy Chung
+ *
+ * @compile -source 1.5 ValidateOpenTypes.java
+ * @run main/othervm -verbose:gc ValidateOpenTypes
+ */
+import java.lang.management.*;
+import javax.management.*;
+import javax.management.openmbean.CompositeData;
+import javax.management.openmbean.TabularData;
+import static java.lang.management.ManagementFactory.*;
+import java.util.List;
+import java.util.Map;
+import java.util.Properties;
+import com.sun.management.GcInfo;
+
+public class ValidateOpenTypes {
+    private static MBeanServer server =
+        ManagementFactory.getPlatformMBeanServer();
+    private static ObjectName memory;
+    private static ObjectName thread;
+    private static ObjectName runtime;
+    private static ObjectName os;
+    private static ObjectName heapPool = null;
+    private static ObjectName nonHeapPool = null;
+
+    public static void main(String[] argv) throws Exception {
+        memory = new ObjectName(MEMORY_MXBEAN_NAME);
+        runtime = new ObjectName(RUNTIME_MXBEAN_NAME);
+        thread = new ObjectName(THREAD_MXBEAN_NAME);
+        os = new ObjectName(OPERATING_SYSTEM_MXBEAN_NAME);
+
+        List<MemoryPoolMXBean> pools = getMemoryPoolMXBeans();
+        for (MemoryPoolMXBean p : pools) {
+            if (heapPool == null &&
+                p.getType() == MemoryType.HEAP &&
+                p.isUsageThresholdSupported() &&
+                p.isCollectionUsageThresholdSupported()) {
+                heapPool = new ObjectName(MEMORY_POOL_MXBEAN_DOMAIN_TYPE +
+                               ",name=" + p.getName());
+            }
+            if (nonHeapPool == null &&
+                p.getType() == MemoryType.NON_HEAP &&
+                p.isUsageThresholdSupported()) {
+                nonHeapPool = new ObjectName(MEMORY_POOL_MXBEAN_DOMAIN_TYPE +
+                               ",name=" + p.getName());
+            }
+        }
+
+        // Check notification emitters
+        MyListener listener = new MyListener();
+        server.addNotificationListener(memory, listener, null, null);
+        server.removeNotificationListener(memory, listener);
+
+        checkEnum();
+        checkList();
+        checkMap();
+        checkMemoryUsage();
+        checkThreadInfo();
+
+        checkOS();
+        checkSunGC();
+
+        System.out.println("Test passed.");
+    }
+
+    private static void checkEnum() throws Exception {
+        String type = (String) server.getAttribute(heapPool, "Type");
+        if (!type.equals("HEAP")) {
+            throw new RuntimeException("TEST FAILED: " +
+                " incorrect memory type for " + heapPool);
+        }
+
+        type = (String) server.getAttribute(nonHeapPool, "Type");
+        if (!type.equals("NON_HEAP")) {
+            throw new RuntimeException("TEST FAILED: " +
+                " incorrect memory type for " + nonHeapPool);
+        }
+    }
+
+    private static final String OPTION = "-verbose:gc";
+    private static void checkList() throws Exception {
+        String[] args = (String[]) server.getAttribute(runtime,
+                                                       "InputArguments");
+        if (args.length < 1) {
+           throw new RuntimeException("TEST FAILED: " +
+                " empty input arguments");
+        }
+        // check if -verbose:gc exists
+        boolean found = false;
+        for (String option : args) {
+           if (option.equals(OPTION)) {
+               found = true;
+               break;
+           }
+        }
+        if (!found) {
+            throw new RuntimeException("TEST FAILED: " +
+                "VM option " + OPTION + " not found");
+        }
+    }
+
+    private static final String KEY1   = "test.property.key1";
+    private static final String VALUE1 = "test.property.value1";
+    private static final String KEY2   = "test.property.key2";
+    private static final String VALUE2 = "test.property.value2";
+    private static final String KEY3   = "test.property.key3";
+    private static void checkMap() throws Exception {
+        // Add new system properties
+        System.setProperty(KEY1, VALUE1);
+        System.setProperty(KEY2, VALUE2);
+
+        TabularData props1 = (TabularData)
+            server.getAttribute(runtime, "SystemProperties");
+
+        String value1 = getProperty(props1, KEY1);
+        if (value1 == null || !value1.equals(VALUE1)) {
+            throw new RuntimeException("TEST FAILED: " +
+                 KEY1 + " property found" +
+                 " with value = " + value1 +
+                 " but expected to be " + VALUE1);
+        }
+
+        String value2 = getProperty(props1, KEY2);
+        if (value2 == null || !value2.equals(VALUE2)) {
+            throw new RuntimeException("TEST FAILED: " +
+                 KEY2 + " property found" +
+                 " with value = " + value2 +
+                 " but expected to be " + VALUE2);
+        }
+
+        String value3 = getProperty(props1, KEY3);
+        if (value3 != null) {
+            throw new RuntimeException("TEST FAILED: " +
+                 KEY3 + " property found" +
+                 " but should not exist" );
+        }
+    }
+    private static String getProperty(TabularData td, String propName) {
+        CompositeData cd = td.get(new Object[] { propName});
+        if (cd != null) {
+            String key = (String) cd.get("key");
+            if (!propName.equals(key)) {
+                 throw new RuntimeException("TEST FAILED: " +
+                     key + " property found" +
+                     " but expected to be " + propName);
+            }
+            return (String) cd.get("value");
+        }
+        return null;
+    }
+
+    private static void checkMemoryUsage() throws Exception {
+        // sanity check to have non-zero usage
+        Object u1 = server.getAttribute(memory, "HeapMemoryUsage");
+        Object u2 = server.getAttribute(memory, "NonHeapMemoryUsage");
+        Object u3 = server.getAttribute(heapPool, "Usage");
+        Object u4 = server.getAttribute(nonHeapPool, "Usage");
+        if (getCommitted(u1) <= 0 ||
+            getCommitted(u2) <= 0 ||
+            getCommitted(u3) <= 0 ||
+            getCommitted(u4) <= 0) {
+            throw new RuntimeException("TEST FAILED: " +
+                " expected non-zero committed usage");
+        }
+        server.invoke(memory, "gc", new Object[0], new String[0]);
+        Object u5 = server.getAttribute(heapPool, "CollectionUsage");
+        if (getCommitted(u5) <= 0) {
+            throw new RuntimeException("TEST FAILED: " +
+                " expected non-zero committed collected usage");
+        }
+    }
+
+    private static long getCommitted(Object data) {
+        MemoryUsage u = MemoryUsage.from((CompositeData) data);
+        return u.getCommitted();
+    }
+
+    private static void checkThreadInfo() throws Exception {
+        // assume all threads stay alive
+        long[] ids = (long[]) server.getAttribute(thread, "AllThreadIds");
+        Object result = server.invoke(thread,
+                                      "getThreadInfo",
+                                      new Object[] { ids },
+                                      new String[] { "[J" });
+        for (CompositeData cd : (CompositeData[]) result) {
+            printThreadInfo(cd);
+        }
+
+        result = server.invoke(thread,
+                               "getThreadInfo",
+                               new Object[] { ids, new Integer(2) },
+                               new String[] { "[J", "int" });
+        for (CompositeData cd : (CompositeData[]) result) {
+            printThreadInfo(cd);
+        }
+
+        long id = Thread.currentThread().getId();
+        result = server.invoke(thread,
+                               "getThreadInfo",
+                               new Object[] { new Long(id) },
+                               new String[] { "long" });
+        printThreadInfo((CompositeData) result);
+
+        result = server.invoke(thread,
+                               "getThreadInfo",
+                               new Object[] { new Long(id), new Integer(2) },
+                               new String[] { "long", "int" });
+        printThreadInfo((CompositeData) result);
+    }
+
+    private static void printThreadInfo(CompositeData cd) {
+        ThreadInfo info = ThreadInfo.from(cd);
+        if (info == null) {
+            throw new RuntimeException("TEST FAILED: " +
+                " Null ThreadInfo");
+        }
+
+        System.out.print(info.getThreadName());
+        System.out.print(" id=" + info.getThreadId());
+        System.out.println(" " + info.getThreadState());
+
+        for (StackTraceElement s : info.getStackTrace()) {
+            System.out.println(s);
+        }
+    }
+
+    private static void checkOS() throws Exception {
+        Integer cpus = (Integer) server.getAttribute(os, "AvailableProcessors");
+        System.out.println("# CPUs = " + cpus);
+        Long vmem = (Long) server.getAttribute(os, "CommittedVirtualMemorySize");
+        System.out.println("Committed virtual memory = " + vmem);
+    }
+
+    private static void checkSunGC() throws Exception {
+       // Test com.sun.management proxy
+        List<GarbageCollectorMXBean> gcs = getGarbageCollectorMXBeans();
+        for (GarbageCollectorMXBean gc : gcs) {
+            ObjectName sunGc =
+                new ObjectName(GARBAGE_COLLECTOR_MXBEAN_DOMAIN_TYPE +
+                               ",name=" + gc.getName());
+            CompositeData cd = (CompositeData) server.getAttribute(sunGc, "LastGcInfo");
+            if (cd != null) {
+                System.out.println("GC statistic for : " + gc.getName());
+                printGcInfo(cd);
+            }
+        }
+    }
+
+    private static void printGcInfo(CompositeData cd) throws Exception {
+        GcInfo info = GcInfo.from(cd);
+        System.out.print("GC #" + info.getId());
+        System.out.print(" start:" + info.getStartTime());
+        System.out.print(" end:" + info.getEndTime());
+        System.out.println(" (" + info.getDuration() + "ms)");
+        Map<String,MemoryUsage> usage = info.getMemoryUsageBeforeGc();
+
+        for (Map.Entry<String,MemoryUsage> entry : usage.entrySet()) {
+            String poolname = entry.getKey();
+            MemoryUsage busage = entry.getValue();
+            MemoryUsage ausage = info.getMemoryUsageAfterGc().get(poolname);
+            if (ausage == null) {
+                throw new RuntimeException("After Gc Memory does not exist" +
+                    " for " + poolname);
+            }
+            System.out.println("Usage for pool " + poolname);
+            System.out.println("   Before GC: " + busage);
+            System.out.println("   After GC: " + ausage);
+        }
+    }
+
+    static class MyListener implements NotificationListener {
+        public void handleNotification(Notification notif, Object handback) {
+            return;
+        }
+    }
+}
diff --git a/jdk/test/java/lang/management/MemoryMXBean/CollectionUsageThreshold.java b/jdk/test/java/lang/management/MemoryMXBean/CollectionUsageThreshold.java
new file mode 100644
index 0000000..4b76243
--- /dev/null
+++ b/jdk/test/java/lang/management/MemoryMXBean/CollectionUsageThreshold.java
@@ -0,0 +1,270 @@
+/*
+ * Copyright 2003-2004 Sun Microsystems, Inc.  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 Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
+ * CA 95054 USA or visit www.sun.com if you need additional information or
+ * have any questions.
+ */
+
+/*
+ * @test
+ * @bug     4959889
+ * @summary Basic unit test of memory management testing:
+ *          1) setCollectionUsageThreshold() and getCollectionUsageThreshold()
+ *          2) test notification emitted for two different memory pools.
+ *
+ * @author  Mandy Chung
+ *
+ * @build CollectionUsageThreshold MemoryUtil
+ * @run main/timeout=300 CollectionUsageThreshold
+ */
+
+import java.lang.management.*;
+import java.util.*;
+import javax.management.*;
+import javax.management.openmbean.CompositeData;
+
+public class CollectionUsageThreshold {
+    private static MemoryMXBean mm = ManagementFactory.getMemoryMXBean();
+    private static List pools = ManagementFactory.getMemoryPoolMXBeans();
+    private static List managers = ManagementFactory.getMemoryManagerMXBeans();
+    private static Map result = new HashMap();
+    private static boolean trace = false;
+    private static boolean testFailed = false;
+    private static final int EXPECTED_NUM_POOLS = 2;
+    private static final int NUM_GCS = 3;
+    private static final int THRESHOLD = 10;
+    private static Checker checker;
+    private static int numGCs = 0;
+
+    static class PoolRecord {
+        private MemoryPoolMXBean pool;
+        private int listenerInvoked = 0;
+        private long notifCount = 0;
+        PoolRecord(MemoryPoolMXBean p) {
+            this.pool = p;
+        }
+        int getListenerInvokedCount() {
+            return listenerInvoked;
+        }
+        long getNotifCount() {
+            return notifCount;
+        }
+        MemoryPoolMXBean getPool() {
+            return pool;
+        }
+        void addNotification(MemoryNotificationInfo minfo) {
+            listenerInvoked++;
+            notifCount = minfo.getCount();
+        }
+    }
+
+    static class SensorListener implements NotificationListener {
+        private int numNotifs = 0;
+        public void handleNotification(Notification notif, Object handback) {
+            String type = notif.getType();
+            if (type.equals(MemoryNotificationInfo.MEMORY_THRESHOLD_EXCEEDED) ||
+                type.equals(MemoryNotificationInfo.
+                    MEMORY_COLLECTION_THRESHOLD_EXCEEDED)) {
+                MemoryNotificationInfo minfo = MemoryNotificationInfo.
+                    from((CompositeData) notif.getUserData());
+
+                MemoryUtil.printMemoryNotificationInfo(minfo, type);
+                PoolRecord pr = (PoolRecord) result.get(minfo.getPoolName());
+                if (pr == null) {
+                    throw new RuntimeException("Pool " + minfo.getPoolName() +
+                        " is not selected");
+                }
+                if (type != MemoryNotificationInfo.
+                        MEMORY_COLLECTION_THRESHOLD_EXCEEDED) {
+                    throw new RuntimeException("Pool " + minfo.getPoolName() +
+                        " got unexpected notification type: " +
+                        type);
+                }
+                pr.addNotification(minfo);
+                synchronized (this) {
+                    numNotifs++;
+                    if (numNotifs > 0 && (numNotifs % EXPECTED_NUM_POOLS) == 0) {
+                        checker.goCheckResult();
+                    }
+                }
+            }
+        }
+    }
+
+    private static long newThreshold;
+    public static void main(String args[]) throws Exception {
+        if (args.length > 0 && args[0].equals("trace")) {
+            trace = true;
+        }
+
+        if (trace) {
+            MemoryUtil.printMemoryPools(pools);
+            MemoryUtil.printMemoryManagers(managers);
+        }
+
+        // Find the Old generation which supports low memory detection
+        for (ListIterator iter = pools.listIterator(); iter.hasNext(); ) {
+            MemoryPoolMXBean p = (MemoryPoolMXBean) iter.next();
+            MemoryUsage u = p.getUsage();
+            if (p.isUsageThresholdSupported() && p.isCollectionUsageThresholdSupported()) {
+                PoolRecord pr = new PoolRecord(p);
+                result.put(p.getName(), pr);
+                if (result.size() == EXPECTED_NUM_POOLS) {
+                    break;
+                }
+            }
+        }
+        if (result.size() != EXPECTED_NUM_POOLS) {
+            throw new RuntimeException("Unexpected number of selected pools");
+        }
+
+        checker = new Checker("Checker thread");
+        checker.setDaemon(true);
+        checker.start();
+
+        for (Iterator iter = result.values().iterator(); iter.hasNext();) {
+            PoolRecord pr = (PoolRecord) iter.next();
+            pr.getPool().setCollectionUsageThreshold(THRESHOLD);
+            System.out.println("Collection usage threshold of " +
+                pr.getPool().getName() + " set to " + THRESHOLD);
+        }
+
+        SensorListener listener = new SensorListener();
+        NotificationEmitter emitter = (NotificationEmitter) mm;
+        emitter.addNotificationListener(listener, null, null);
+
+        mm.setVerbose(true);
+        for (int i = 0; i < NUM_GCS; i++) {
+            invokeGC();
+            checker.waitForCheckResult();
+        }
+
+        if (testFailed)
+            throw new RuntimeException("TEST FAILED.");
+
+        System.out.println("Test passed.");
+
+    }
+
+    private static void invokeGC() {
+        System.out.println("Calling System.gc()");
+        numGCs++;
+        mm.gc();
+
+        if (trace) {
+            for (Iterator iter = result.values().iterator(); iter.hasNext();) {
+                PoolRecord pr = (PoolRecord) iter.next();
+                System.out.println("Usage after GC for: " + pr.getPool().getName());
+                MemoryUtil.printMemoryUsage(pr.getPool().getUsage());
+            }
+        }
+    }
+
+    static class Checker extends Thread {
+        private Object lock = new Object();
+        private Object go = new Object();
+        private boolean checkerReady = false;
+        private int waiters = 0;
+        private boolean readyToCheck = false;
+        Checker(String name) {
+            super(name);
+        };
+        public void run() {
+            while (true) {
+                synchronized (lock) {
+                    checkerReady = true;
+                    try {
+                        lock.wait();
+                    } catch (InterruptedException e) {
+                        // ignore
+                    }
+                    checkResult();
+                    checkerReady = false;
+                }
+            }
+        }
+        private void checkResult() {
+            for (Iterator iter = result.values().iterator(); iter.hasNext();) {
+                PoolRecord pr = (PoolRecord) iter.next();
+                if (pr.getListenerInvokedCount() != numGCs) {
+                    throw new RuntimeException("Listeners invoked count = " +
+                         pr.getListenerInvokedCount() + " expected to be " +
+                         numGCs);
+                }
+                if (pr.getNotifCount() != numGCs) {
+                    throw new RuntimeException("Notif Count = " +
+                         pr.getNotifCount() + " expected to be " +
+                         numGCs);
+                }
+
+                long count = pr.getPool().getCollectionUsageThresholdCount();
+                if (count != numGCs) {
+                    throw new RuntimeException("CollectionUsageThresholdCount = " +
+                         count + " expected to be " + numGCs);
+                }
+                if (!pr.getPool().isCollectionUsageThresholdExceeded()) {
+                    throw new RuntimeException("isCollectionUsageThresholdExceeded" +
+                         " expected to be true");
+                }
+            }
+            synchronized (go) {
+                // wait until the main thread is waiting for notification
+                while (waiters == 0) {
+                    try {
+                        go.wait(50);
+                    } catch (InterruptedException e) {
+                        // ignore
+                    }
+                }
+
+                System.out.println(Thread.currentThread().getName() +
+                    " notifying main thread to continue - result checking finished");
+                go.notify();
+            }
+        }
+        public void goCheckResult() {
+            System.out.println(Thread.currentThread().getName() +
+                " notifying to check result");
+            synchronized (lock) {
+                while (!checkerReady) {
+                    try {
+                        lock.wait(50);
+                    } catch (InterruptedException e) {
+                        // ignore
+                    }
+                }
+                lock.notify();
+            }
+        }
+
+        public void waitForCheckResult() {
+            System.out.println(Thread.currentThread().getName() +
+                " waiting for result checking finishes");
+            synchronized (go) {
+                waiters++;
+                try {
+                    go.wait();
+                } catch (InterruptedException e) {
+                    // ignore
+                }
+                waiters--;
+            }
+        }
+    }
+}
diff --git a/jdk/test/java/lang/management/MemoryMXBean/CollectionUsageThresholdConcMarkSweepGC.sh b/jdk/test/java/lang/management/MemoryMXBean/CollectionUsageThresholdConcMarkSweepGC.sh
new file mode 100644
index 0000000..9d0af26
--- /dev/null
+++ b/jdk/test/java/lang/management/MemoryMXBean/CollectionUsageThresholdConcMarkSweepGC.sh
@@ -0,0 +1,52 @@
+#
+# Copyright 2003-2004 Sun Microsystems, Inc.  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 Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
+# CA 95054 USA or visit www.sun.com if you need additional information or
+# have any questions.
+#
+
+#
+# @test
+# @bug     4959889
+# @summary Test CollectionUsageThreshold with concurrent marksweep collector
+# @author  Mandy Chung
+#
+# @run build CollectionUsageThreshold
+# @run shell/timeout=300 CollectionUsageThresholdConcMarkSweepGC.sh
+#
+
+#Set appropriate jdk
+
+if [ ! -z "${TESTJAVA}" ] ; then
+     jdk="$TESTJAVA"
+else
+     echo "--Error: TESTJAVA must be defined as the pathname of a jdk to test."
+     exit 1
+fi
+
+runOne()
+{
+   echo "runOne $@"
+   $TESTJAVA/bin/java ${TESTVMOPTS} -classpath $TESTCLASSES $@ || exit 2
+}
+
+# Test CollectionUsageThreshold with concurrent collector
+runOne -XX:+UseConcMarkSweepGC CollectionUsageThreshold
+
+exit 0
diff --git a/jdk/test/java/lang/management/MemoryMXBean/CollectionUsageThresholdParallelGC.sh b/jdk/test/java/lang/management/MemoryMXBean/CollectionUsageThresholdParallelGC.sh
new file mode 100644
index 0000000..025ebf3
--- /dev/null
+++ b/jdk/test/java/lang/management/MemoryMXBean/CollectionUsageThresholdParallelGC.sh
@@ -0,0 +1,52 @@
+#
+# Copyright 2003 Sun Microsystems, Inc.  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 Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
+# CA 95054 USA or visit www.sun.com if you need additional information or
+# have any questions.
+#
+
+#
+# @test
+# @bug     4959889
+# @summary Test CollectionUsageThreshold with parallel collector
+# @author  Mandy Chung
+#
+# @run build CollectionUsageThreshold
+# @run shell/timeout=300 CollectionUsageThresholdParallelGC.sh
+#
+
+#Set appropriate jdk
+
+if [ ! -z "${TESTJAVA}" ] ; then
+     jdk="$TESTJAVA"
+else
+     echo "--Error: TESTJAVA must be defined as the pathname of a jdk to test."
+     exit 1
+fi
+
+runOne()
+{
+   echo "runOne $@"
+   $TESTJAVA/bin/java ${TESTVMOPTS} -classpath $TESTCLASSES $@ || exit 2
+}
+
+# Test CollectionUsageThreshold with parallel collector
+runOne -XX:+UseParallelGC CollectionUsageThreshold
+
+exit 0
diff --git a/jdk/test/java/lang/management/MemoryMXBean/CollectionUsageThresholdSerialGC.sh b/jdk/test/java/lang/management/MemoryMXBean/CollectionUsageThresholdSerialGC.sh
new file mode 100644
index 0000000..57849b9
--- /dev/null
+++ b/jdk/test/java/lang/management/MemoryMXBean/CollectionUsageThresholdSerialGC.sh
@@ -0,0 +1,52 @@
+#
+# Copyright 2003 Sun Microsystems, Inc.  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 Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
+# CA 95054 USA or visit www.sun.com if you need additional information or
+# have any questions.
+#
+
+#
+# @test
+# @bug     4959889
+# @summary Test CollectionUsageThreshold with serial collector
+# @author  Mandy Chung
+#
+# @run build CollectionUsageThreshold
+# @run shell/timeout=300 CollectionUsageThresholdSerialGC.sh
+#
+
+#Set appropriate jdk
+
+if [ ! -z "${TESTJAVA}" ] ; then
+     jdk="$TESTJAVA"
+else
+     echo "--Error: TESTJAVA must be defined as the pathname of a jdk to test."
+     exit 1
+fi
+
+runOne()
+{
+   echo "runOne $@"
+   $TESTJAVA/bin/java ${TESTVMOPTS} -classpath $TESTCLASSES $@ || exit 2
+}
+
+# Test CollectionUsageThreshold with serial collector
+runOne -XX:+UseSerialGC CollectionUsageThreshold
+
+exit 0
diff --git a/jdk/test/java/lang/management/MemoryMXBean/GetMBeanInfo.java b/jdk/test/java/lang/management/MemoryMXBean/GetMBeanInfo.java
new file mode 100644
index 0000000..f325622
--- /dev/null
+++ b/jdk/test/java/lang/management/MemoryMXBean/GetMBeanInfo.java
@@ -0,0 +1,66 @@
+/*
+ * Copyright 2003-2004 Sun Microsystems, Inc.  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 Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
+ * CA 95054 USA or visit www.sun.com if you need additional information or
+ * have any questions.
+ */
+
+/*
+ * @test
+ * @bug     4930397
+ * @summary Make sure MemoryMXBean has two notification types.
+ * @author  Mandy Chung
+ *
+ * @run main GetMBeanInfo
+ */
+
+import java.lang.management.*;
+import javax.management.*;
+
+public class GetMBeanInfo {
+    private final static int EXPECTED_NOTIF_TYPES = 2;
+    private static int count = 0;
+
+    public static void main(String argv[]) throws Exception {
+        final ObjectName objName;
+        objName = new ObjectName(ManagementFactory.MEMORY_MXBEAN_NAME);
+
+        MBeanServer mbs = ManagementFactory.getPlatformMBeanServer();
+
+        MBeanInfo minfo = mbs.getMBeanInfo(objName);
+        MBeanNotificationInfo[] notifs = minfo.getNotifications();
+        for (int i = 0; i < notifs.length; i++) {
+            printNotifType(notifs[i]);
+        }
+
+        if (count != EXPECTED_NOTIF_TYPES) {
+            throw new RuntimeException("Unexpected number of notification types"
+                                       + " count = " + count +
+                                       " expected = " + EXPECTED_NOTIF_TYPES);
+        }
+    }
+
+    private static void printNotifType(MBeanNotificationInfo notif) {
+        String[] types = notif.getNotifTypes();
+        for (int i = 0; i < types.length; i++) {
+            System.out.println(types[i]);
+            count++;
+        }
+    }
+}
diff --git a/jdk/test/java/lang/management/MemoryMXBean/LowMemoryTest.java b/jdk/test/java/lang/management/MemoryMXBean/LowMemoryTest.java
new file mode 100644
index 0000000..daf56e4
--- /dev/null
+++ b/jdk/test/java/lang/management/MemoryMXBean/LowMemoryTest.java
@@ -0,0 +1,290 @@
+/*
+ * Copyright 2003-2004 Sun Microsystems, Inc.  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 Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
+ * CA 95054 USA or visit www.sun.com if you need additional information or
+ * have any questions.
+ */
+
+/*
+ * @test
+ * @bug     4530538
+ * @summary Basic unit test of memory management testing:
+ *          1) setUsageThreshold() and getUsageThreshold()
+ *          2) test low memory detection on the old generation.
+ *
+ * @author  Mandy Chung
+ *
+ * @build LowMemoryTest MemoryUtil
+ * @run main/timeout=600 LowMemoryTest
+ */
+
+import java.lang.management.*;
+import java.util.*;
+import javax.management.*;
+import javax.management.openmbean.CompositeData;
+
+public class LowMemoryTest {
+    private static MemoryMXBean mm = ManagementFactory.getMemoryMXBean();
+    private static List pools = ManagementFactory.getMemoryPoolMXBeans();
+    private static List managers = ManagementFactory.getMemoryManagerMXBeans();
+    private static MemoryPoolMXBean mpool = null;
+    private static boolean trace = false;
+    private static boolean testFailed = false;
+    private static final int NUM_TRIGGERS = 5;
+    private static final int NUM_CHUNKS = 2;
+    private static long chunkSize;
+
+    private static boolean listenerInvoked = false;
+    static class SensorListener implements NotificationListener {
+        public void handleNotification(Notification notif, Object handback) {
+            String type = notif.getType();
+            if (type.equals(MemoryNotificationInfo.MEMORY_THRESHOLD_EXCEEDED) ||
+                type.equals(MemoryNotificationInfo.
+                    MEMORY_COLLECTION_THRESHOLD_EXCEEDED)) {
+
+                MemoryNotificationInfo minfo = MemoryNotificationInfo.
+                    from((CompositeData) notif.getUserData());
+
+                MemoryUtil.printMemoryNotificationInfo(minfo, type);
+                listenerInvoked = true;
+            }
+        }
+    }
+
+    static class TestListener implements NotificationListener {
+        private int triggers = 0;
+        private long[] count = new long[NUM_TRIGGERS * 2];
+        private long[] usedMemory = new long[NUM_TRIGGERS * 2];
+        public void handleNotification(Notification notif, Object handback) {
+            MemoryNotificationInfo minfo = MemoryNotificationInfo.
+                from((CompositeData) notif.getUserData());
+            count[triggers] = minfo.getCount();
+            usedMemory[triggers] = minfo.getUsage().getUsed();
+            triggers++;
+        }
+        public void checkResult() throws Exception {
+            if (triggers != NUM_TRIGGERS) {
+                throw new RuntimeException("Unexpected number of triggers = " +
+                    triggers + " but expected to be " + NUM_TRIGGERS);
+            }
+
+            for (int i = 0; i < triggers; i++) {
+                if (count[i] != i+1) {
+                    throw new RuntimeException("Unexpected count of" +
+                        " notification #" + i +
+                        " count = " + count[i] +
+                        " but expected to be " + (i+1));
+                }
+                if (usedMemory[i] < newThreshold) {
+                    throw new RuntimeException("Used memory = " +
+                        usedMemory[i] + " is less than the threshold = " +
+                        newThreshold);
+                }
+            }
+        }
+    }
+
+    private static long newThreshold;
+    public static void main(String args[]) throws Exception {
+        if (args.length > 0 && args[0].equals("trace")) {
+            trace = true;
+        }
+
+        // Find the Old generation which supports low memory detection
+        ListIterator iter = pools.listIterator();
+        while (iter.hasNext()) {
+            MemoryPoolMXBean p = (MemoryPoolMXBean) iter.next();
+            if (p.getType() == MemoryType.HEAP &&
+                    p.isUsageThresholdSupported()) {
+                mpool = p;
+                if (trace) {
+                    System.out.println("Selected memory pool for low memory " +
+                        "detection.");
+                    MemoryUtil.printMemoryPool(mpool);
+                }
+                break;
+            }
+        }
+
+        TestListener listener = new TestListener();
+        SensorListener l2 = new SensorListener();
+        NotificationEmitter emitter = (NotificationEmitter) mm;
+        emitter.addNotificationListener(listener, null, null);
+        emitter.addNotificationListener(l2, null, null);
+
+        Thread allocator = new AllocatorThread();
+        Thread sweeper = new SweeperThread();
+
+        // Now set threshold
+        MemoryUsage mu = mpool.getUsage();
+        chunkSize = (mu.getMax() - mu.getUsed()) / 20;
+        newThreshold = mu.getUsed() + (chunkSize * NUM_CHUNKS);
+
+        System.out.println("Setting threshold for " + mpool.getName() +
+            " from " + mpool.getUsageThreshold() + " to " + newThreshold +
+            ".  Current used = " + mu.getUsed());
+        mpool.setUsageThreshold(newThreshold);
+
+        if (mpool.getUsageThreshold() != newThreshold) {
+            throw new RuntimeException("TEST FAILED: " +
+                "Threshold for Memory pool " + mpool.getName() +
+                "is " + mpool.getUsageThreshold() + " but expected to be" +
+                newThreshold);
+        }
+
+        allocator.start();
+        sweeper.start();
+
+        try {
+            allocator.join();
+            sweeper.join();
+        } catch (InterruptedException e) {
+            e.printStackTrace();
+            System.out.println("Unexpected exception.");
+            testFailed = true;
+        }
+
+        listener.checkResult();
+
+        if (testFailed)
+            throw new RuntimeException("TEST FAILED.");
+
+        System.out.println("Test passed.");
+
+    }
+
+    private static void goSleep(long ms) {
+        try {
+            Thread.sleep(ms);
+        } catch (InterruptedException e) {
+            e.printStackTrace();
+            System.out.println("Unexpected exception.");
+            testFailed = true;
+        }
+    }
+
+    private static Object go = new Object();
+    private static boolean waiting = false; // No thread is waiting.
+
+    // Synchronizes two thread. If no thread is waiting then wait
+    // for notification from a different thread  and if it is
+    // is waiting then send notification.
+    // In this test case this method is used to synchronize sweeper
+    // thread and alocater thread to reach a particular point.
+    private static void wait_or_notify() {
+        synchronized (go) {
+            if (waiting == false) {
+                waiting = true;
+                System.out.println(" Waiting ");
+                try {
+                    go.wait();
+                } catch (InterruptedException e) {
+                    e.printStackTrace();
+                    testFailed = true;
+                }
+                waiting = false;
+            } else {
+                System.out.println(" Notify ");
+                go.notify();
+            }
+        }
+    }
+
+    private static List objectPool = new ArrayList();
+    static class AllocatorThread extends Thread {
+        public void doTask() {
+            int iterations = 0;
+            int numElements = (int) (chunkSize / 4); // minimal object size
+            while (!listenerInvoked) {
+                iterations++;
+                if (trace) {
+                    System.out.println("   Iteration " + iterations +
+                        ": before allocation " +
+                        mpool.getUsage().getUsed());
+                }
+
+                Object[] o = new Object[numElements];
+                if (iterations <= NUM_CHUNKS) {
+                    // only hold a reference to the first NUM_CHUNKS
+                    // allocated objects
+                    objectPool.add(o);
+                }
+
+                if (trace) {
+                    System.out.println("               " +
+                        "  after allocation " +
+                        mpool.getUsage().getUsed());
+                }
+                goSleep(100);
+            }
+        }
+        public void run() {
+            for (int i = 1; i <= NUM_TRIGGERS; i++) {
+                System.out.println("AllocatorThread is doing task " + i);
+                doTask();
+                synchronized (sweep) {
+                    sweep.notify();
+                }
+                // System.out.print(" Allocater Thread ");
+                // If sweeper thread is waiting then send notify
+                // else wait for notification from sweeper thread.
+                wait_or_notify();
+                if (testFailed) return;
+            }
+        }
+    }
+
+    private static Object sweep = new Object();
+    static class SweeperThread extends Thread {
+        private void doTask() {
+            for (; mpool.getUsage().getUsed() >=
+                       mpool.getUsageThreshold();) {
+                // clear all allocated objects and invoke GC
+                objectPool.clear();
+                mm.gc();
+                goSleep(100);
+            }
+        }
+        public void run() {
+            for (int i = 1; i <= NUM_TRIGGERS; i++) {
+                synchronized (sweep) {
+                    while (!listenerInvoked) {
+                        try {
+                            sweep.wait();
+                        } catch (InterruptedException e) {
+                            e.printStackTrace();
+                            System.out.println("Unexpected exception.");
+                            testFailed = true;
+                        }
+                    }
+                }
+                System.out.println("SweepThread is doing task " + i);
+                doTask();
+
+                listenerInvoked = false;
+
+                // System.out.print(" Sweeper Thread ");
+                // If Allocater thread is waiting wait send notify
+                // else wait for notfication from allocater thread.
+                wait_or_notify();
+                if (testFailed) return;
+            }
+        }
+    }
+}
diff --git a/jdk/test/java/lang/management/MemoryMXBean/LowMemoryTest2.java b/jdk/test/java/lang/management/MemoryMXBean/LowMemoryTest2.java
new file mode 100644
index 0000000..788c30f
--- /dev/null
+++ b/jdk/test/java/lang/management/MemoryMXBean/LowMemoryTest2.java
@@ -0,0 +1,230 @@
+/*
+ * Copyright 2004 Sun Microsystems, Inc.  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 Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
+ * CA 95054 USA or visit www.sun.com if you need additional information or
+ * have any questions.
+ */
+
+/*
+ * Test low memory detection of non-heap memory pool.
+ *
+ * The test set a listener to be notified when any of the non-heap pools
+ * exceed 80%. It then starts a thread that continuously loads classes.
+ * In the HotSpot implementation this causes perm space to be consumed.
+ * Test completes when we the notification is received or an OutOfMemory
+ * is generated.
+ */
+
+import java.lang.management.*;
+import javax.management.*;
+import javax.management.openmbean.CompositeData;
+import java.util.*;
+
+public class LowMemoryTest2 {
+
+    private static volatile boolean listenerInvoked = false;
+
+    private static String INDENT = "    ";
+
+    static class SensorListener implements NotificationListener {
+        public void handleNotification(Notification notif, Object handback) {
+            String type = notif.getType();
+            if (type.equals(MemoryNotificationInfo.MEMORY_THRESHOLD_EXCEEDED) ||
+                type.equals(MemoryNotificationInfo.
+                    MEMORY_COLLECTION_THRESHOLD_EXCEEDED)) {
+                listenerInvoked = true;
+                MemoryNotificationInfo minfo = MemoryNotificationInfo.
+                    from((CompositeData) notif.getUserData());
+
+                System.out.print("Notification for " + minfo.getPoolName());
+                System.out.print(" [type = " + type);
+                System.out.println(" count = " + minfo.getCount() + "]");
+                System.out.println(INDENT + "usage = " + minfo.getUsage());
+            }
+        }
+    }
+
+    // Loads classes Test100001, Test100002, .... until OutOfMemoryErrror or
+    // low memory notification
+
+    static class BoundlessLoaderThread extends ClassLoader implements Runnable {
+
+        static int count = 100000;
+
+        Class loadNext() throws ClassNotFoundException {
+
+            // public class TestNNNNNN extends java.lang.Object{
+            // public TestNNNNNN();
+            //   Code:
+            //    0:    aload_0
+            //    1:    invokespecial   #1; //Method java/lang/Object."<init>":()V
+            //    4:    return
+            // }
+
+            int begin[] = {
+                0xca, 0xfe, 0xba, 0xbe, 0x00, 0x00, 0x00, 0x30,
+                0x00, 0x0a, 0x0a, 0x00, 0x03, 0x00, 0x07, 0x07,
+                0x00, 0x08, 0x07, 0x00, 0x09, 0x01, 0x00, 0x06,
+                0x3c, 0x69, 0x6e, 0x69, 0x74, 0x3e, 0x01, 0x00,
+                0x03, 0x28, 0x29, 0x56, 0x01, 0x00, 0x04, 0x43,
+                0x6f, 0x64, 0x65, 0x0c, 0x00, 0x04, 0x00, 0x05,
+                0x01, 0x00, 0x0a, 0x54, 0x65, 0x73, 0x74 };
+
+            int end [] = {
+                0x01, 0x00, 0x10,
+                0x6a, 0x61, 0x76, 0x61, 0x2f, 0x6c, 0x61, 0x6e,
+                0x67, 0x2f, 0x4f, 0x62, 0x6a, 0x65, 0x63, 0x74,
+                0x00, 0x21, 0x00, 0x02, 0x00, 0x03, 0x00, 0x00,
+                0x00, 0x00, 0x00, 0x01, 0x00, 0x01, 0x00, 0x04,
+                0x00, 0x05, 0x00, 0x01, 0x00, 0x06, 0x00, 0x00,
+                0x00, 0x11, 0x00, 0x01, 0x00, 0x01, 0x00, 0x00,
+                0x00, 0x05, 0x2a, 0xb7, 0x00, 0x01, 0xb1, 0x00,
+                0x00, 0x00, 0x00, 0x00, 0x00 };
+
+
+            // TestNNNNNN
+
+            String name = "Test" + Integer.toString(count++);
+
+            byte value[];
+            try {
+                value = name.substring(4).getBytes("UTF-8");
+            } catch (java.io.UnsupportedEncodingException x) {
+                throw new Error();
+            }
+
+            // construct class file
+
+            int len = begin.length + value.length + end.length;
+            byte b[] = new byte[len];
+            int i, pos=0;
+            for (i=0; i<begin.length; i++) {
+                b[pos++] = (byte)begin[i];
+            }
+            for (i=0; i<value.length; i++) {
+                b[pos++] = value[i];
+            }
+            for (i=0; i<end.length; i++) {
+                b[pos++] = (byte)end[i];
+            }
+
+            return defineClass(name, b, 0, b.length);
+        }
+
+        /*
+         * Run method for thread that continuously loads classes.
+         *
+         * Note: Once the usage threshold has been exceeded the low memory
+         * detector thread will attempt to deliver its notification - this can
+         * potentially create a race condition with this thread contining to
+         * fill up perm space. To avoid the low memory detector getting an OutOfMemory
+         * we throttle this thread once the threshold has been exceeded.
+         */
+        public void run() {
+            List pools = ManagementFactory.getMemoryPoolMXBeans();
+            boolean thresholdExceeded = false;
+
+            for (;;) {
+                try {
+                    // the classes are small so we load 10 at a time
+                    for (int i=0; i<10; i++) {
+                        loadNext();
+                    }
+                } catch (ClassNotFoundException x) {
+                    return;
+                }
+                if (listenerInvoked) {
+                    return;
+                }
+
+                // if threshold has been exceeded we put in a delay to allow
+                // the low memory detector do its job.
+                if (thresholdExceeded) {
+                    try {
+                        Thread.currentThread().sleep(100);
+                    } catch (InterruptedException x) { }
+                } else {
+                    // check if the threshold has been exceeded
+                    ListIterator i = pools.listIterator();
+                    while (i.hasNext()) {
+                        MemoryPoolMXBean p = (MemoryPoolMXBean) i.next();
+                        if (p.getType() == MemoryType.NON_HEAP &&
+                            p.isUsageThresholdSupported())
+                        {
+                            thresholdExceeded = p.isUsageThresholdExceeded();
+                        }
+                    }
+                }
+            }
+        }
+    }
+
+    public static void main(String args[]) {
+        ListIterator iter = ManagementFactory.getMemoryPoolMXBeans().listIterator();
+
+        // Set threshold of 80% of all NON_HEAP memory pools
+        // In the Hotspot implementation this means we should get a notification
+        // if the CodeCache or perm generation fills up.
+
+        while (iter.hasNext()) {
+            MemoryPoolMXBean p = (MemoryPoolMXBean) iter.next();
+            if (p.getType() == MemoryType.NON_HEAP && p.isUsageThresholdSupported()) {
+
+                // set threshold
+                MemoryUsage mu = p.getUsage();
+                long threshold = (mu.getMax() * 80) / 100;
+
+                p.setUsageThreshold(threshold);
+
+                System.out.println("Selected memory pool for low memory " +
+                        "detection.");
+                MemoryUtil.printMemoryPool(p);
+
+            }
+        }
+
+
+        // Install the listener
+
+        MemoryMXBean mm = ManagementFactory.getMemoryMXBean();
+        SensorListener l2 = new SensorListener();
+
+        NotificationEmitter emitter = (NotificationEmitter) mm;
+        emitter.addNotificationListener(l2, null, null);
+
+        // Start the thread loading classes
+
+        Thread thr = new Thread(new BoundlessLoaderThread());
+        thr.start();
+
+        // Wait for the thread to terminate
+        try {
+            thr.join();
+        } catch (InterruptedException x) {
+            throw new RuntimeException(x);
+        }
+
+        if (listenerInvoked) {
+            System.out.println("Notification received - test passed.");
+        } else {
+            throw new RuntimeException("Test failed - notification not received!");
+        }
+    }
+
+}
diff --git a/jdk/test/java/lang/management/MemoryMXBean/LowMemoryTest2.sh b/jdk/test/java/lang/management/MemoryMXBean/LowMemoryTest2.sh
new file mode 100644
index 0000000..163eb18
--- /dev/null
+++ b/jdk/test/java/lang/management/MemoryMXBean/LowMemoryTest2.sh
@@ -0,0 +1,69 @@
+#
+# Copyright 2004-2005 Sun Microsystems, Inc.  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 Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
+# CA 95054 USA or visit www.sun.com if you need additional information or
+# have any questions.
+#
+
+#
+# @test
+# @bug     4982128
+# @summary Test low memory detection of non-heap memory pool
+#
+# @run build LowMemoryTest2 MemoryUtil
+# @run shell/timeout=600 LowMemoryTest2.sh
+#
+
+if [ ! -z "${TESTJAVA}" ] ; then
+     JAVA=${TESTJAVA}/bin/java
+     CLASSPATH=${TESTCLASSES}
+     export CLASSPATH
+else
+     echo "--Error: TESTJAVA must be defined as the pathname of a jdk to test."
+     exit 1
+fi
+
+# Test execution
+
+failures=0
+
+go() {
+    echo ''
+    sh -xc "$JAVA $TESTVMOPTS $*" 2>&1
+    if [ $? != 0 ]; then failures=`expr $failures + 1`; fi
+}
+
+# Run test with each GC configuration
+# 
+# Notes: To ensure that perm gen fills up we disable class unloading.
+# Also we set the max perm space to 8MB - otherwise the test takes too
+# long to run. 
+
+go -noclassgc -XX:PermSize=8m -XX:MaxPermSize=8m -XX:+UseSerialGC LowMemoryTest2
+go -noclassgc -XX:PermSize=8m -XX:MaxPermSize=8m -XX:+UseParallelGC LowMemoryTest2
+go -noclassgc -XX:PermSize=8m -XX:MaxPermSize=8m -XX:+UseParNewGC -XX:+UseConcMarkSweepGC \
+    LowMemoryTest2
+
+echo ''
+if [ $failures -gt 0 ];
+  then echo "$failures test(s) failed";
+  else echo "All test(s) passed"; fi
+exit $failures
+
+
diff --git a/jdk/test/java/lang/management/MemoryMXBean/LowMemoryTestConcMarkSweepGC.sh b/jdk/test/java/lang/management/MemoryMXBean/LowMemoryTestConcMarkSweepGC.sh
new file mode 100644
index 0000000..2c0009e
--- /dev/null
+++ b/jdk/test/java/lang/management/MemoryMXBean/LowMemoryTestConcMarkSweepGC.sh
@@ -0,0 +1,52 @@
+#
+# Copyright 2003 Sun Microsystems, Inc.  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 Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
+# CA 95054 USA or visit www.sun.com if you need additional information or
+# have any questions.
+#
+
+#
+# @test
+# @bug     4530538
+# @summary Test LowMemoryTest with concurrent mark sweep GC
+# @author  Mandy Chung
+#
+# @run build LowMemoryTest
+# @run shell/timeout=600 LowMemoryTestConcMarkSweepGC.sh
+#
+
+#Set appropriate jdk
+
+if [ ! -z "${TESTJAVA}" ] ; then
+     jdk="$TESTJAVA"
+else
+     echo "--Error: TESTJAVA must be defined as the pathname of a jdk to test."
+     exit 1
+fi
+
+runOne()
+{ 
+   echo "runOne $@"
+   $TESTJAVA/bin/java ${TESTVMOPTS} -classpath $TESTCLASSES $@ || exit 2
+}
+
+# Test LowMemoryTest with concurrent collector
+runOne -XX:+UseConcMarkSweepGC LowMemoryTest 
+
+exit 0
diff --git a/jdk/test/java/lang/management/MemoryMXBean/LowMemoryTestParallelGC.sh b/jdk/test/java/lang/management/MemoryMXBean/LowMemoryTestParallelGC.sh
new file mode 100644
index 0000000..dddbee7
--- /dev/null
+++ b/jdk/test/java/lang/management/MemoryMXBean/LowMemoryTestParallelGC.sh
@@ -0,0 +1,52 @@
+#
+# Copyright 2003 Sun Microsystems, Inc.  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 Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
+# CA 95054 USA or visit www.sun.com if you need additional information or
+# have any questions.
+#
+
+#
+# @test
+# @bug     4530538
+# @summary Test LowMemoryTest with parallel GC
+# @author  Mandy Chung
+#
+# @run build LowMemoryTest
+# @run shell/timeout=600 LowMemoryTestParallelGC.sh
+#
+
+#Set appropriate jdk
+
+if [ ! -z "${TESTJAVA}" ] ; then
+     jdk="$TESTJAVA"
+else
+     echo "--Error: TESTJAVA must be defined as the pathname of a jdk to test."
+     exit 1
+fi
+
+runOne()
+{ 
+   echo "runOne $@"
+   $TESTJAVA/bin/java ${TESTVMOPTS} -classpath $TESTCLASSES $@ || exit 2
+}
+
+# Test LowMemoryTest with parallel scavenger collector
+runOne -XX:+UseParallelGC LowMemoryTest 
+
+exit 0
diff --git a/jdk/test/java/lang/management/MemoryMXBean/LowMemoryTestSerialGC.sh b/jdk/test/java/lang/management/MemoryMXBean/LowMemoryTestSerialGC.sh
new file mode 100644
index 0000000..2a081bc
--- /dev/null
+++ b/jdk/test/java/lang/management/MemoryMXBean/LowMemoryTestSerialGC.sh
@@ -0,0 +1,52 @@
+#
+# Copyright 2003 Sun Microsystems, Inc.  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 Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
+# CA 95054 USA or visit www.sun.com if you need additional information or
+# have any questions.
+#
+
+#
+# @test
+# @bug     4530538
+# @summary Test LowMemoryTest with Serial GC
+# @author  Mandy Chung
+#
+# @run build LowMemoryTest
+# @run shell/timeout=600 LowMemoryTestSerialGC.sh
+#
+
+#Set appropriate jdk
+
+if [ ! -z "${TESTJAVA}" ] ; then
+     jdk="$TESTJAVA"
+else
+     echo "--Error: TESTJAVA must be defined as the pathname of a jdk to test."
+     exit 1
+fi
+
+runOne()
+{ 
+   echo "runOne $@"
+   $TESTJAVA/bin/java ${TESTVMOPTS} -classpath $TESTCLASSES $@ || exit 2
+}
+
+# Test LowMemoryTest with serial collector
+runOne -XX:+UseSerialGC LowMemoryTest 
+
+exit 0
diff --git a/jdk/test/java/lang/management/MemoryMXBean/MemoryManagement.java b/jdk/test/java/lang/management/MemoryMXBean/MemoryManagement.java
new file mode 100644
index 0000000..b81f83d
--- /dev/null
+++ b/jdk/test/java/lang/management/MemoryMXBean/MemoryManagement.java
@@ -0,0 +1,181 @@
+/*
+ * Copyright 2003-2004 Sun Microsystems, Inc.  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 Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
+ * CA 95054 USA or visit www.sun.com if you need additional information or
+ * have any questions.
+ */
+
+/*
+ * @test
+ * @bug     4530538
+ * @summary Basic unit test of memory management testing:
+ *          1) setUsatgeThreshold() and getUsageThreshold()
+ *          2) test low memory detection on the old generation.
+ *
+ * @author  Mandy Chung
+ *
+ * @build MemoryManagement MemoryUtil
+ * @run main/timeout=600 MemoryManagement
+ */
+
+import java.lang.management.*;
+import java.util.*;
+import javax.management.*;
+import javax.management.openmbean.CompositeData;
+
+public class MemoryManagement {
+    private static MemoryMXBean mm = ManagementFactory.getMemoryMXBean();
+    private static List pools = ManagementFactory.getMemoryPoolMXBeans();
+    private static List managers = ManagementFactory.getMemoryManagerMXBeans();
+    private static MemoryPoolMXBean mpool = null;
+    private static boolean trace = false;
+    private static boolean testFailed = false;
+    private static final int NUM_CHUNKS = 2;
+    private static long chunkSize;
+
+    private static int listenerInvoked = 0;
+    static class SensorListener implements NotificationListener {
+        public void handleNotification(Notification notif, Object handback) {
+            String type = notif.getType();
+            if (type.equals(MemoryNotificationInfo.MEMORY_THRESHOLD_EXCEEDED) ||
+                type.equals(MemoryNotificationInfo.
+                    MEMORY_COLLECTION_THRESHOLD_EXCEEDED)) {
+
+                MemoryNotificationInfo minfo = MemoryNotificationInfo.
+                    from((CompositeData) notif.getUserData());
+
+                MemoryUtil.printMemoryNotificationInfo(minfo, type);
+                listenerInvoked++;
+            }
+        }
+    }
+
+    private static long newThreshold;
+    public static void main(String args[]) throws Exception {
+        if (args.length > 0 && args[0].equals("trace")) {
+            trace = true;
+        }
+
+        if (trace) {
+            MemoryUtil.printMemoryPools(pools);
+            MemoryUtil.printMemoryManagers(managers);
+        }
+
+        // Find the Old generation which supports low memory detection
+        ListIterator iter = pools.listIterator();
+        while (iter.hasNext()) {
+            MemoryPoolMXBean p = (MemoryPoolMXBean) iter.next();
+            if (p.getType() == MemoryType.HEAP &&
+                p.isUsageThresholdSupported()) {
+                mpool = p;
+                if (trace) {
+                    System.out.println("Selected memory pool for low memory " +
+                        "detection.");
+                    MemoryUtil.printMemoryPool(mpool);
+                }
+                break;
+            }
+        }
+
+        SensorListener listener = new SensorListener();
+        NotificationEmitter emitter = (NotificationEmitter) mm;
+        emitter.addNotificationListener(listener, null, null);
+
+        Thread allocator = new AllocatorThread();
+
+        // Now set threshold
+        MemoryUsage mu = mpool.getUsage();
+        chunkSize = (mu.getMax() - mu.getUsed()) / 20;
+        newThreshold = mu.getUsed() + (chunkSize * NUM_CHUNKS);
+
+        System.out.println("Setting threshold for " + mpool.getName() +
+            " from " + mpool.getUsageThreshold() + " to " + newThreshold +
+            ".  Current used = " + mu.getUsed());
+        mpool.setUsageThreshold(newThreshold);
+
+        if (mpool.getUsageThreshold() != newThreshold) {
+            throw new RuntimeException("TEST FAILED: " +
+                "Threshold for Memory pool " + mpool.getName() +
+                "is " + mpool.getUsageThreshold() + " but expected to be" +
+                newThreshold);
+        }
+
+        // Start the AllocatorThread to continously allocate memory
+        System.out.println("Starting an AllocatorThread to allocate memory.");
+        allocator.start();
+
+        try {
+            allocator.join();
+        } catch (InterruptedException e) {
+            e.printStackTrace();
+            System.out.println("Unexpected exception.");
+            testFailed = true;
+        }
+
+        if (listenerInvoked == 0) {
+            throw new RuntimeException("No listener is invoked");
+        }
+
+        if (testFailed)
+            throw new RuntimeException("TEST FAILED.");
+
+        System.out.println("Test passed.");
+
+    }
+
+    static class AllocatorThread extends Thread {
+        private List objectPool = new ArrayList();
+        public void run() {
+            int iterations = 0;
+            int numElements = (int) (chunkSize / 4); // minimal object size
+            while (listenerInvoked == 0) {
+                iterations++;
+                if (trace) {
+                    System.out.println("    Iteration " + iterations +
+                        ": before allocation " +
+                        mpool.getUsage().getUsed());
+                }
+
+                Object[] o = new Object[numElements];
+                if (iterations <= NUM_CHUNKS) {
+                    // only hold a reference to the first NUM_CHUNKS
+                    // allocated objects
+                    objectPool.add(o);
+                }
+
+                if (trace) {
+                    System.out.println("                " +
+                        "  after allocation " +
+                        mpool.getUsage().getUsed());
+                }
+                try {
+                    Thread.sleep(100);
+                } catch (InterruptedException e) {
+                    e.printStackTrace();
+                    System.out.println("Unexpected exception.");
+                    testFailed = true;
+                }
+            }
+
+            System.out.println("AllocatedThread finished memory allocation " +
+                " num_iteration = " + iterations);
+        }
+    }
+
+}
diff --git a/jdk/test/java/lang/management/MemoryMXBean/MemoryManagementConcMarkSweepGC.sh b/jdk/test/java/lang/management/MemoryMXBean/MemoryManagementConcMarkSweepGC.sh
new file mode 100644
index 0000000..f9f92fa
--- /dev/null
+++ b/jdk/test/java/lang/management/MemoryMXBean/MemoryManagementConcMarkSweepGC.sh
@@ -0,0 +1,52 @@
+#
+# Copyright 2003 Sun Microsystems, Inc.  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 Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
+# CA 95054 USA or visit www.sun.com if you need additional information or
+# have any questions.
+#
+
+#
+# @test
+# @bug     4530538
+# @summary Run MemoryManagement test with concurrent mark sweep GC
+# @author  Mandy Chung
+#
+# @run build MemoryManagement
+# @run shell/timeout=600 MemoryManagementConcMarkSweepGC.sh
+#
+
+#Set appropriate jdk
+
+if [ ! -z "${TESTJAVA}" ] ; then
+     jdk="$TESTJAVA"
+else
+     echo "--Error: TESTJAVA must be defined as the pathname of a jdk to test."
+     exit 1
+fi
+
+runOne()
+{ 
+   echo "runOne $@"
+   $TESTJAVA/bin/java ${TESTVMOPTS} -classpath $TESTCLASSES $@ || exit 2
+}
+
+# Test MemoryManagement with concurrent collector
+runOne -XX:+UseConcMarkSweepGC MemoryManagement
+
+exit 0
diff --git a/jdk/test/java/lang/management/MemoryMXBean/MemoryManagementParallelGC.sh b/jdk/test/java/lang/management/MemoryMXBean/MemoryManagementParallelGC.sh
new file mode 100644
index 0000000..880a8a3
--- /dev/null
+++ b/jdk/test/java/lang/management/MemoryMXBean/MemoryManagementParallelGC.sh
@@ -0,0 +1,52 @@
+#
+# Copyright 2003 Sun Microsystems, Inc.  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 Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
+# CA 95054 USA or visit www.sun.com if you need additional information or
+# have any questions.
+#
+
+#
+# @test
+# @bug     4530538
+# @summary Run MemoryManagement test with parallel GC
+# @author  Mandy Chung
+#
+# @run build MemoryManagement
+# @run shell/timeout=600 MemoryManagementParallelGC.sh
+#
+
+#Set appropriate jdk
+
+if [ ! -z "${TESTJAVA}" ] ; then
+     jdk="$TESTJAVA"
+else
+     echo "--Error: TESTJAVA must be defined as the pathname of a jdk to test."
+     exit 1
+fi
+
+runOne()
+{ 
+   echo "runOne $@"
+   $TESTJAVA/bin/java ${TESTVMOPTS} -classpath $TESTCLASSES $@ || exit 2
+}
+
+# Test MemoryManagement with parallel collector
+runOne -XX:+UseParallelGC MemoryManagement
+
+exit 0
diff --git a/jdk/test/java/lang/management/MemoryMXBean/MemoryManagementSerialGC.sh b/jdk/test/java/lang/management/MemoryMXBean/MemoryManagementSerialGC.sh
new file mode 100644
index 0000000..e051895
--- /dev/null
+++ b/jdk/test/java/lang/management/MemoryMXBean/MemoryManagementSerialGC.sh
@@ -0,0 +1,52 @@
+#
+# Copyright 2003 Sun Microsystems, Inc.  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 Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
+# CA 95054 USA or visit www.sun.com if you need additional information or
+# have any questions.
+#
+
+#
+# @test
+# @bug     4530538
+# @summary Run MemoryManagement test with serial GC
+# @author  Mandy Chung
+#
+# @run build MemoryManagement
+# @run shell/timeout=600 MemoryManagementSerialGC.sh
+#
+
+#Set appropriate jdk
+
+if [ ! -z "${TESTJAVA}" ] ; then
+     jdk="$TESTJAVA"
+else
+     echo "--Error: TESTJAVA must be defined as the pathname of a jdk to test."
+     exit 1
+fi
+
+runOne()
+{ 
+   echo "runOne $@"
+   $TESTJAVA/bin/java ${TESTVMOPTS} -classpath $TESTCLASSES $@ || exit 2
+}
+
+# Test MemoryManagement with serial collector
+runOne -XX:+UseSerialGC MemoryManagement
+
+exit 0
diff --git a/jdk/test/java/lang/management/MemoryMXBean/MemoryTest.java b/jdk/test/java/lang/management/MemoryMXBean/MemoryTest.java
new file mode 100644
index 0000000..918d4bc
--- /dev/null
+++ b/jdk/test/java/lang/management/MemoryMXBean/MemoryTest.java
@@ -0,0 +1,161 @@
+/*
+ * Copyright 2003-2004 Sun Microsystems, Inc.  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 Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
+ * CA 95054 USA or visit www.sun.com if you need additional information or
+ * have any questions.
+ */
+
+/*
+ * @test
+ * @bug     4530538
+ * @summary Basic unit test of MemoryMXBean.getMemoryPools() and
+ *          MemoryMXBean.getMemoryManager().
+ * @author  Mandy Chung
+ *
+ * @run main MemoryTest 2
+ */
+
+/*
+ * NOTE: This expected result is hardcoded in this test and this test
+ *       will be affected if the heap memory layout is changed in
+ *       the future implementation.
+ */
+
+import java.lang.management.*;
+import java.util.*;
+
+public class MemoryTest {
+    private static boolean testFailed = false;
+    private static MemoryMXBean mm = ManagementFactory.getMemoryMXBean();
+    private static final int HEAP = 0;
+    private static final int NONHEAP = 1;
+    private static final int NUM_TYPES = 2;
+
+    // WARNING: if the number of pools changes in the future,
+    // this test needs to be modified to handle different version of VMs.
+
+    // Hotspot VM 1.5 expected to have
+    //   heap memory pools     = 3 (Eden, Survivor spaces, Old gen)
+    //   non-heap memory pools = 2 (Perm gen, Code cache)
+    //                           or 4 if Class Sharing is enabled.
+    // Number of memory managers = 3
+    // They are: Copy/Scavenger + MSC + CodeCache manager
+    // (or equivalent for other collectors)
+    // Number of GC memory managers = 2
+    private static int[] expectedMinNumPools = {3, 2};
+    private static int[] expectedMaxNumPools = {3, 4};
+    private static int expectedNumGCMgrs = 2;
+    private static int expectedNumMgrs = expectedNumGCMgrs + 1;
+    private static String[] types = { "heap", "non-heap" };
+
+    public static void main(String args[]) throws Exception {
+        Integer value = new Integer(args[0]);
+        expectedNumGCMgrs = value.intValue();
+        expectedNumMgrs = expectedNumGCMgrs + 1;
+
+        checkMemoryPools();
+        checkMemoryManagers();
+        if (testFailed)
+            throw new RuntimeException("TEST FAILED.");
+
+        System.out.println("Test passed.");
+
+    }
+
+    private static void checkMemoryPools() throws Exception {
+        List pools = ManagementFactory.getMemoryPoolMXBeans();
+
+        int[] numPools = new int[NUM_TYPES];
+        for (ListIterator iter = pools.listIterator(); iter.hasNext();) {
+            MemoryPoolMXBean pool = (MemoryPoolMXBean) iter.next();
+            if (pool.getType() == MemoryType.HEAP) {
+                numPools[HEAP]++;
+            }
+            if (pool.getType() == MemoryType.NON_HEAP) {
+                numPools[NONHEAP]++;
+            }
+        }
+
+        // Check the number of Memory pools
+        for (int i = 0; i < NUM_TYPES; i++) {
+            if (numPools[i] < expectedMinNumPools[i] ||
+                    numPools[i] > expectedMaxNumPools[i]) {
+                throw new RuntimeException("TEST FAILED: " +
+                    "Number of " + types[i] + " pools = " + numPools[i] +
+                    " but expected <= " + expectedMaxNumPools[i] +
+                    " and >= " + expectedMinNumPools[i]);
+            }
+        }
+    }
+
+    private static void checkMemoryManagers() throws Exception {
+        List mgrs = ManagementFactory.getMemoryManagerMXBeans();
+
+        int numGCMgr = 0;
+
+        // Check the number of Memory Managers
+        for (ListIterator iter = mgrs.listIterator(); iter.hasNext();) {
+            MemoryManagerMXBean mgr = (MemoryManagerMXBean) iter.next();
+            String[] poolNames = mgr.getMemoryPoolNames();
+            if (poolNames == null || poolNames.length == 0) {
+                throw new RuntimeException("TEST FAILED: " +
+                    "Expected to have one or more pools for " +
+                    mgr.getName() + "manager.");
+            }
+
+            if (mgr instanceof GarbageCollectorMXBean) {
+                numGCMgr++;
+            } else {
+                for (int i = 0; i < poolNames.length; i++) {
+                    checkPoolType(poolNames[i], MemoryType.NON_HEAP);
+                }
+            }
+        }
+
+        if (mgrs.size() != expectedNumMgrs) {
+            throw new RuntimeException("TEST FAILED: " +
+                "Number of memory managers = " + mgrs.size() +
+                " but expected = " + expectedNumMgrs);
+        }
+        if (numGCMgr != expectedNumGCMgrs) {
+            throw new RuntimeException("TEST FAILED: " +
+                "Number of GC managers = " + numGCMgr + " but expected = " +
+                expectedNumGCMgrs);
+        }
+    }
+    private static List pools = ManagementFactory.getMemoryPoolMXBeans();
+    private static void checkPoolType(String name, MemoryType type)
+        throws Exception {
+        for (ListIterator iter = pools.listIterator(); iter.hasNext(); ) {
+            MemoryPoolMXBean pool = (MemoryPoolMXBean) iter.next();
+            if (pool.getName().equals(name)) {
+                if (pool.getType() != type) {
+                    throw new RuntimeException("TEST FAILED: " +
+                        "Pool " + pool.getName() + " is of type " +
+                        pool.getType() + " but expected to be " + type);
+                } else {
+                    return;
+                }
+            }
+        }
+        throw new RuntimeException("TEST FAILED: " +
+            "Pool " + name + " is of type " + type +
+            " not found");
+    }
+}
diff --git a/jdk/test/java/lang/management/MemoryMXBean/MemoryTestAllGC.sh b/jdk/test/java/lang/management/MemoryMXBean/MemoryTestAllGC.sh
new file mode 100644
index 0000000..fd0ff2a
--- /dev/null
+++ b/jdk/test/java/lang/management/MemoryMXBean/MemoryTestAllGC.sh
@@ -0,0 +1,58 @@
+#
+# Copyright 2003-2004 Sun Microsystems, Inc.  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 Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
+# CA 95054 USA or visit www.sun.com if you need additional information or
+# have any questions.
+#
+
+#
+# @test
+# @bug     4530538
+# @summary 
+# @author  Mandy Chung
+#
+# @run compile MemoryTest.java
+# @run shell MemoryTestAllGC.sh
+#
+
+#Set appropriate jdk
+
+if [ ! -z "${TESTJAVA}" ] ; then
+     jdk="$TESTJAVA"
+else
+     echo "--Error: TESTJAVA must be defined as the pathname of a jdk to test."
+     exit 1
+fi
+
+runOne()
+{ 
+   echo "runOne $@"
+   $TESTJAVA/bin/java ${TESTVMOPTS} -classpath $TESTCLASSES $@ || exit 2
+}
+
+# Test MemoryTest with default collector
+runOne MemoryTest 2
+
+# Test MemoryTest with parallel scavenger collector
+runOne -XX:+UseParallelGC MemoryTest 2
+
+# Test MemoryTest with concurrent collector
+#runOne -XX:+UseConcMarkSweepGC MemoryTest 3
+
+exit 0
diff --git a/jdk/test/java/lang/management/MemoryMXBean/MemoryUtil.java b/jdk/test/java/lang/management/MemoryMXBean/MemoryUtil.java
new file mode 100644
index 0000000..06650f2
--- /dev/null
+++ b/jdk/test/java/lang/management/MemoryMXBean/MemoryUtil.java
@@ -0,0 +1,115 @@
+/*
+ * Copyright 2004 Sun Microsystems, Inc.  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 Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
+ * CA 95054 USA or visit www.sun.com if you need additional information or
+ * have any questions.
+ */
+
+/*
+ * @bug     4982289
+ * @summary Utility class.
+ * @author Mandy Chung
+ */
+
+import java.lang.management.*;
+import java.util.*;
+
+public class MemoryUtil {
+
+    private static String INDENT = "    ";
+    private static String formatSize(String name, long value) {
+        StringBuffer buf = new StringBuffer(name + " = " + value);
+        if (value > 0) {
+            buf.append(" (" + (value >> 10) + "K)");
+        }
+        return buf.toString();
+    }
+    public static void printMemoryUsage(MemoryUsage usage) {
+        System.out.println(INDENT + formatSize("Initial size  ", usage.getInit()));
+        System.out.println(INDENT + formatSize("Used size     ", usage.getUsed()));
+        System.out.println(INDENT + formatSize("Committd size ", usage.getCommitted()));
+        System.out.println(INDENT + formatSize("Max size      ", usage.getMax()));
+    }
+
+    public static void printMemoryPool(MemoryPoolMXBean pool) {
+        System.out.println(INDENT + "Memory Pool name: " + pool.getName());
+        System.out.println(INDENT + "Type: " + pool.getType());
+        System.out.println(INDENT + "Memory Usage: " +
+            pool.getUsage());
+        System.out.println(INDENT + "Threshold: " +
+            (pool.isUsageThresholdSupported() ? pool.getUsageThreshold() : -1));
+        System.out.print(INDENT + "Manager = [");
+        String[] mgrs = pool.getMemoryManagerNames();
+        for (int i = 0; i < mgrs.length; i++) {
+            System.out.print(mgrs[i]);
+            if (i < (mgrs.length - 1)) {
+                System.out.print(" | ");
+            }
+        }
+        System.out.println("]");
+    }
+
+    public static void printMemoryPools(List pools) {
+        ListIterator iter = pools.listIterator();
+        System.out.println(INDENT + "Number of memory pools = " + pools.size());
+        while (iter.hasNext()) {
+            MemoryPoolMXBean pool = (MemoryPoolMXBean) iter.next();
+            printMemoryPool(pool);
+        }
+    }
+
+    public static void printMemoryManager(MemoryManagerMXBean mgr) {
+        if (mgr instanceof GarbageCollectorMXBean) {
+            GarbageCollectorMXBean gc = (GarbageCollectorMXBean) mgr;
+            System.out.println(INDENT + "Garbage Collector name: " + gc.getName());
+            System.out.println(INDENT + "GC Count: " + gc.getCollectionCount());
+            System.out.println(INDENT + "GC Time : " + gc.getCollectionTime());
+        } else {
+            System.out.println(INDENT + "Memory Manager name: " + mgr.getName());
+        }
+
+        System.out.print("Pool = [");
+        String[] pools = mgr.getMemoryPoolNames();
+        for (int i = 0; i < pools.length; i++) {
+            System.out.print(INDENT + pools[i]);
+            if (i < (pools.length - 1)) {
+                System.out.print(" | ");
+            }
+        }
+        System.out.println("]");
+    }
+
+    public static void printMemoryManagers(List managers) {
+        ListIterator iter = managers.listIterator();
+        System.out.println(INDENT + "Number of memory managers = " +
+            managers.size());
+        while (iter.hasNext()) {
+            MemoryManagerMXBean mgr = (MemoryManagerMXBean) iter.next();
+            printMemoryManager(mgr);
+        }
+    }
+
+    public static void printMemoryNotificationInfo
+        (MemoryNotificationInfo minfo, String type) {
+        System.out.print("Notification for " + minfo.getPoolName());
+        System.out.print(" [type = " + type);
+        System.out.println(" count = " + minfo.getCount() + "]");
+        System.out.println(INDENT + "usage = " + minfo.getUsage());
+    }
+}
diff --git a/jdk/test/java/lang/management/MemoryMXBean/Pending.java b/jdk/test/java/lang/management/MemoryMXBean/Pending.java
new file mode 100644
index 0000000..0fff93d
--- /dev/null
+++ b/jdk/test/java/lang/management/MemoryMXBean/Pending.java
@@ -0,0 +1,239 @@
+/*
+ * Copyright 2003-2004 Sun Microsystems, Inc.  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 Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
+ * CA 95054 USA or visit www.sun.com if you need additional information or
+ * have any questions.
+ */
+
+/*
+ * @test
+ * @bug     4530538
+ * @summary Basic unit test of
+ *          RuntimeMXBean.getObjectPendingFinalizationCount()
+ *          1. GC and runFinalization() to get the current pending number
+ *          2. Create some number of objects with reference and without ref.
+ *          3. Clear all the references
+ *          4. GC and runFinalization() and the finalizable objects should
+ *             be garbage collected.
+ * @author  Alexei Guibadoulline and Mandy Chung
+ *
+ */
+
+import java.lang.management.*;
+
+public class Pending {
+    final static int NO_REF_COUNT = 600;
+    final static int REF_COUNT = 600;
+    final static int TOTAL_FINALIZABLE = (NO_REF_COUNT + REF_COUNT);
+    private static int finalized = 0;
+    private static MemoryMXBean mbean
+        = ManagementFactory.getMemoryMXBean();
+
+    private static final String INDENT = "      ";
+    private static void printFinalizerInstanceCount() {
+        if (!trace) return;
+
+        int count = sun.misc.VM.getFinalRefCount();
+        System.out.println(INDENT + "Finalizable object Count = " + count);
+
+        count = sun.misc.VM.getPeakFinalRefCount();
+        System.out.println(INDENT + "Peak Finalizable object Count = " + count);
+    }
+
+    private static boolean trace = false;
+    public static void main(String argv[]) throws Exception {
+        if (argv.length > 0 && argv[0].equals("trace")) {
+            trace = true;
+        }
+
+        // Turn on verbose:gc to track GC
+        mbean.setVerbose(true);
+
+        // Clean the memory and remove all objects that are pending
+        // finalization
+        System.gc();
+        Runtime.getRuntime().runFinalization();
+
+        // Let the finalizer to finish
+        try {
+            Thread.sleep(200);
+        } catch (Exception e) {
+            throw e;
+        }
+
+        // Create a number of new objects but no references to them
+        int startCount = mbean.getObjectPendingFinalizationCount();
+
+        System.out.println("Number of objects pending for finalization:");
+        System.out.println("   Before creating object: " + startCount +
+            " finalized = " + finalized);
+        printFinalizerInstanceCount();
+
+        for (int i = 0; i < NO_REF_COUNT; i++) {
+            new MyObject();
+        }
+
+        Snapshot snapshot = getSnapshot();
+        System.out.println("   Afer creating objects with no ref: " + snapshot);
+        printFinalizerInstanceCount();
+
+        Object[] objs = new Object[REF_COUNT];
+        for (int i = 0; i < REF_COUNT; i++) {
+            objs[i] = new MyObject();
+        }
+        snapshot = getSnapshot();
+        System.out.println("   Afer creating objects with ref: " + snapshot);
+        printFinalizerInstanceCount();
+
+        // Now check the expected count - GC and runFinalization will be
+        // invoked.
+        checkFinalizerCount(NO_REF_COUNT, 0);
+
+        // Clean the memory and remove all objects that are pending
+        // finalization again
+        objs = null;
+        snapshot = getSnapshot();
+        System.out.println("Clear all references finalized = " + snapshot);
+        printFinalizerInstanceCount();
+
+        checkFinalizerCount(TOTAL_FINALIZABLE, NO_REF_COUNT);
+
+        snapshot = getSnapshot();
+        printFinalizerInstanceCount();
+
+        // Check the mbean now
+        if (snapshot.curFinalized != TOTAL_FINALIZABLE) {
+            throw new RuntimeException("Wrong number of finalized objects "
+                                     + snapshot + ". Expected "
+                                     + TOTAL_FINALIZABLE);
+        }
+
+        if (startCount != 0 || snapshot.curPending != 0) {
+            throw new RuntimeException("Wrong number of objects pending "
+                                     + "finalization start = " + startCount
+                                     + " end = " + snapshot);
+        }
+
+        System.out.println("Test passed.");
+    }
+
+    private static void checkFinalizerCount(int expectedTotal, int curFinalized)
+        throws Exception {
+        int prevCount = -1;
+        Snapshot snapshot = getSnapshot();
+        if (snapshot.curFinalized != curFinalized) {
+            throw new RuntimeException(
+                    "Unexpected finalized objects: " + snapshot +
+                    " but expected = " + curFinalized);
+        }
+        int MAX_GC_LOOP = 6;
+        for (int i = 1;
+             snapshot.curFinalized != expectedTotal && i <= MAX_GC_LOOP;
+             i++) {
+            System.gc();
+
+            // Pause to give a chance to Finalizer thread to run
+            pause();
+
+            printFinalizerInstanceCount();
+            // Race condition may occur; attempt to check this
+            // a few times before throwing exception.
+            for (int j = 0; j < 5; j++) {
+                // poll for another current pending count
+                snapshot = getSnapshot();
+                if (snapshot.curFinalized == expectedTotal ||
+                    snapshot.curPending != 0) {
+                    break;
+                }
+            }
+            System.out.println("   After GC " + i + ": " + snapshot);
+
+            Runtime.getRuntime().runFinalization();
+
+            // Pause to give a chance to Finalizer thread to run
+            pause();
+
+            snapshot = getSnapshot();
+            if (snapshot.curFinalized == expectedTotal &&
+                snapshot.curPending != 0) {
+                throw new RuntimeException(
+                    "Unexpected current number of objects pending for " +
+                    "finalization: " + snapshot + " but expected = 0");
+            }
+
+            System.out.println("   After runFinalization " + i + ": " + snapshot);
+            printFinalizerInstanceCount();
+
+            try {
+                Thread.sleep(1000);
+            } catch (Exception e) {
+                throw e;
+            }
+        }
+        if (snapshot.curFinalized != expectedTotal) {
+            throw new RuntimeException(
+                "Unexpected current number of objects pending for " +
+                "finalization: " + snapshot + " but expected > 0");
+        }
+    }
+
+    private static Object lock = new Object();
+    private static class MyObject {
+        Object[] dummy = new Object[10];
+        public void finalize () {
+            synchronized (lock) {
+                finalized++;
+            }
+        }
+    }
+
+    static class Snapshot {
+        public int curFinalized;
+        public int curPending;
+        Snapshot(int f, int p) {
+            curFinalized = f;
+            curPending = p;
+        }
+        public String toString() {
+            return "Current finalized = " + curFinalized +
+                   " Current pending = " + curPending;
+        }
+    }
+
+    private static Snapshot getSnapshot() {
+        synchronized (lock) {
+            int curCount = mbean.getObjectPendingFinalizationCount();
+            return new Snapshot(finalized, curCount);
+        }
+    }
+
+    private static Object pauseObj = new Object();
+    private static void pause() {
+        // Enter lock a without blocking
+        synchronized (pauseObj) {
+            try {
+                // may need to tune this timeout for different platforms
+                pauseObj.wait(20);
+            } catch (Exception e) {
+                System.err.println("Unexpected exception.");
+                e.printStackTrace(System.err);
+            }
+        }
+    }
+}
diff --git a/jdk/test/java/lang/management/MemoryMXBean/PendingAllGC.sh b/jdk/test/java/lang/management/MemoryMXBean/PendingAllGC.sh
new file mode 100644
index 0000000..9865af3
--- /dev/null
+++ b/jdk/test/java/lang/management/MemoryMXBean/PendingAllGC.sh
@@ -0,0 +1,58 @@
+#
+# Copyright 2003 Sun Microsystems, Inc.  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 Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
+# CA 95054 USA or visit www.sun.com if you need additional information or
+# have any questions.
+#
+
+#
+# @test
+# @bug     4530538
+# @summary 
+# @author  Mandy Chung
+#
+# @run compile Pending.java
+# @run shell PendingAllGC.sh
+#
+
+#Set appropriate jdk
+
+if [ ! -z "${TESTJAVA}" ] ; then
+     jdk="$TESTJAVA"
+else
+     echo "--Error: TESTJAVA must be defined as the pathname of a jdk to test."
+     exit 1
+fi
+
+runOne()
+{ 
+   echo "runOne $@"
+   $TESTJAVA/bin/java ${TESTVMOPTS} -classpath $TESTCLASSES $@ || exit 2
+}
+
+# Test Pending with default collector
+runOne Pending
+
+# Test Pending with parallel scavenger collector
+runOne -XX:+UseParallelGC Pending 
+
+# Test Pending with concurrent collector
+runOne -XX:+UseConcMarkSweepGC Pending
+
+exit 0
diff --git a/jdk/test/java/lang/management/MemoryMXBean/ResetPeakMemoryUsage.java b/jdk/test/java/lang/management/MemoryMXBean/ResetPeakMemoryUsage.java
new file mode 100644
index 0000000..66218e4
--- /dev/null
+++ b/jdk/test/java/lang/management/MemoryMXBean/ResetPeakMemoryUsage.java
@@ -0,0 +1,156 @@
+/*
+ * Copyright 2003-2004 Sun Microsystems, Inc.  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 Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
+ * CA 95054 USA or visit www.sun.com if you need additional information or
+ * have any questions.
+ */
+
+/*
+ * @test
+ * @bug     4892507
+ * @summary Basic Test for MemoryPool.resetPeakUsage()
+ * @author  Mandy Chung
+ *
+ * @build ResetPeakMemoryUsage MemoryUtil
+ * @run main ResetPeakMemoryUsage
+ */
+
+import java.lang.management.*;
+import java.util.*;
+
+public class ResetPeakMemoryUsage {
+    private static MemoryMXBean mbean = ManagementFactory.getMemoryMXBean();
+    private static List pools = ManagementFactory.getMemoryPoolMXBeans();
+    private static MemoryPoolMXBean mpool = null;
+
+    public static void main(String[] argv) {
+        ListIterator iter = pools.listIterator();
+        while (iter.hasNext()) {
+            MemoryPoolMXBean p = (MemoryPoolMXBean) iter.next();
+            if (p.getType() == MemoryType.HEAP &&
+                    p.isUsageThresholdSupported()) {
+                mpool = p;
+                System.out.println("Selected memory pool: ");
+                MemoryUtil.printMemoryPool(mpool);
+                break;
+            }
+        }
+        if (mpool == null) {
+            throw new RuntimeException("No heap pool found with threshold != -1");
+        }
+
+        MemoryUsage usage0 = mpool.getUsage();
+        MemoryUsage peak0 = mpool.getPeakUsage();
+        final long largeArraySize = (usage0.getMax() - usage0.getUsed()) / 10;
+
+        System.out.println("Before big object is allocated: ");
+        printMemoryUsage();
+
+        // Allocate a big array - need to allocate from the old gen
+        Object[][][] obj = new Object[1][1][(int) largeArraySize];
+
+        System.out.println("After the object is allocated: ");
+        printMemoryUsage();
+
+        MemoryUsage usage1 = mpool.getUsage();
+        MemoryUsage peak1 = mpool.getPeakUsage();
+
+        if (usage1.getUsed() <= usage0.getUsed()) {
+            throw new RuntimeException(
+                formatSize("Before allocation: used", usage0.getUsed()) +
+                " expected to be > " +
+                formatSize("After allocation: used", usage1.getUsed()));
+        }
+
+        if (peak1.getUsed() <= peak0.getUsed()) {
+            throw new RuntimeException(
+                formatSize("Before allocation: peak", peak0.getUsed()) +
+                " expected to be > " +
+                formatSize("After allocation: peak", peak1.getUsed()));
+        }
+
+
+        // The object is now garbage and do a GC
+        // memory usage should drop
+        obj = null;
+        mbean.gc();
+
+        System.out.println("After GC: ");
+        printMemoryUsage();
+
+        MemoryUsage usage2 = mpool.getUsage();
+        MemoryUsage peak2 = mpool.getPeakUsage();
+
+        if (usage2.getUsed() >= usage1.getUsed()) {
+            throw new RuntimeException(
+                formatSize("Before GC: used", usage1.getUsed()) + " " +
+                " expected to be > " +
+                formatSize("After GC: used", usage2.getUsed()));
+        }
+
+        if (peak2.getUsed() != peak1.getUsed()) {
+            throw new RuntimeException(
+                formatSize("Before GC: peak", peak1.getUsed()) + " " +
+                " expected to be equal to " +
+                formatSize("After GC: peak", peak2.getUsed()));
+        }
+
+        mpool.resetPeakUsage();
+
+        System.out.println("After resetPeakUsage: ");
+        printMemoryUsage();
+
+        MemoryUsage usage3 = mpool.getUsage();
+        MemoryUsage peak3 = mpool.getPeakUsage();
+
+        if (peak3.getUsed() != usage3.getUsed()) {
+            throw new RuntimeException(
+                formatSize("After resetting peak: peak", peak3.getUsed()) + " " +
+                " expected to be equal to " +
+                formatSize("current used", usage3.getUsed()));
+        }
+
+        if (peak3.getUsed() >= peak2.getUsed()) {
+            throw new RuntimeException(
+                formatSize("After resetting peak: peak", peak3.getUsed()) + " " +
+                " expected to be < " +
+                formatSize("previous peak", peak2.getUsed()));
+        }
+
+        System.out.println("Test passed.");
+    }
+
+    private static String INDENT = "    ";
+    private static void printMemoryUsage() {
+        MemoryUsage current = mpool.getUsage();
+        MemoryUsage peak = mpool.getPeakUsage();
+        System.out.println("Current Usage: ");
+        MemoryUtil.printMemoryUsage(current);
+        System.out.println("Peak Usage: ");
+        MemoryUtil.printMemoryUsage(peak);
+
+    }
+    private static String formatSize(String name, long value) {
+        StringBuffer buf = new StringBuffer(name + " = " + value);
+        if (value > 0) {
+            buf.append(" (" + (value >> 10) + "K)");
+        }
+        return buf.toString();
+    }
+}
diff --git a/jdk/test/java/lang/management/MemoryPoolMXBean/ThresholdTest.java b/jdk/test/java/lang/management/MemoryPoolMXBean/ThresholdTest.java
new file mode 100644
index 0000000..67f0238
--- /dev/null
+++ b/jdk/test/java/lang/management/MemoryPoolMXBean/ThresholdTest.java
@@ -0,0 +1,160 @@
+/*
+ * Copyright (c) 2007 Sun Microsystems, Inc.  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 Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
+ * CA 95054 USA or visit www.sun.com if you need additional information or
+ * have any questions.
+ */
+
+/*
+ * @test
+ * @bug     6546089
+ * @summary Basic unit test of MemoryPoolMXBean.isUsageThresholdExceeded() and
+ *          MemoryPoolMXBean.isCollectionThresholdExceeded().
+ * @author  Mandy Chung
+ *
+ * @run main ThresholdTest
+ */
+
+import java.lang.management.*;
+import java.util.*;
+
+public class ThresholdTest {
+    public static void main(String args[]) throws Exception {
+        List<MemoryPoolMXBean> pools = ManagementFactory.getMemoryPoolMXBeans();
+        for (MemoryPoolMXBean p : pools) {
+            // verify if isUsageThresholdExceeded() returns correct value
+            checkUsageThreshold(p);
+            // verify if isCollectionUsageThresholdExceeded() returns correct value
+            checkCollectionUsageThreshold(p);
+        }
+
+        System.out.println("Test passed.");
+    }
+
+    private static void checkUsageThreshold(MemoryPoolMXBean p) throws Exception {
+
+        if (!p.isUsageThresholdSupported()) {
+            return;
+        }
+
+        long threshold = p.getUsageThreshold();
+        if (threshold != 0) {
+            // Expect the default threshold is zero (disabled)
+            throw new RuntimeException("TEST FAILED: " +
+                "Pool " + p.getName() +
+                " has non-zero threshold (" + threshold);
+        }
+
+        // isUsageThresholdExceeded() should return false if threshold == 0
+        if (p.isUsageThresholdExceeded()) {
+            throw new RuntimeException("TEST FAILED: " +
+                "Pool " + p.getName() +
+                " isUsageThresholdExceeded() returned true" +
+                " but threshold = 0");
+        }
+
+        p.setUsageThreshold(1);
+        MemoryUsage u = p.getUsage();
+        if (u.getUsed() >= 1) {
+            if (!p.isUsageThresholdExceeded()) {
+                throw new RuntimeException("TEST FAILED: " +
+                    "Pool " + p.getName() +
+                    " isUsageThresholdExceeded() returned false but " +
+                    " threshold(" + p.getUsageThreshold() +
+                    ") <= used(" + u.getUsed() + ")");
+            }
+        } else {
+            if (p.isUsageThresholdExceeded()) {
+                throw new RuntimeException("TEST FAILED: " +
+                    "Pool " + p.getName() +
+                    " isUsageThresholdExceeded() returned true but" +
+                    " threshold(" + p.getUsageThreshold() +
+                    ") > used(" + u.getUsed() + ")");
+            }
+        }
+
+        // disable low memory detection and isUsageThresholdExceeded()
+        // should return false
+        p.setUsageThreshold(0);
+        if (p.isUsageThresholdExceeded()) {
+            throw new RuntimeException("TEST FAILED: " +
+                "Pool " + p.getName() +
+                " isUsageThresholdExceeded() returned true but threshold = 0");
+        }
+    }
+
+    private static void checkCollectionUsageThreshold(MemoryPoolMXBean p) throws Exception {
+
+        if (!p.isCollectionUsageThresholdSupported()) {
+            return;
+        }
+
+        long threshold = p.getCollectionUsageThreshold();
+        if (threshold != 0) {
+            // Expect the default threshold is zero (disabled)
+            throw new RuntimeException("TEST FAILED: " +
+                "Pool " + p.getName() +
+                " has non-zero threshold (" + threshold);
+        }
+
+        // isCollectionUsageThresholdExceeded() should return false if threshold == 0
+        if (p.isCollectionUsageThresholdExceeded()) {
+            throw new RuntimeException("TEST FAILED: " +
+                "Pool " + p.getName() +
+                " isCollectionUsageThresholdExceeded() returned true" +
+                " but threshold = 0");
+        }
+
+        p.setCollectionUsageThreshold(1);
+        MemoryUsage u = p.getCollectionUsage();
+        if (u == null) {
+            if (p.isCollectionUsageThresholdExceeded()) {
+                throw new RuntimeException("TEST FAILED: " +
+                    "Pool " + p.getName() +
+                    " isCollectionUsageThresholdExceeded() returned true but" +
+                    " getCollectionUsage() return null");
+            }
+        } else if (u.getUsed() >= 1) {
+            if (!p.isCollectionUsageThresholdExceeded()) {
+                throw new RuntimeException("TEST FAILED: " +
+                    "Pool " + p.getName() +
+                    " isCollectionUsageThresholdExceeded() returned false but " +
+                    " threshold(" + p.getCollectionUsageThreshold() +
+                    ") < used(" + u.getUsed() + ")");
+            }
+        } else {
+            if (p.isCollectionUsageThresholdExceeded()) {
+                throw new RuntimeException("TEST FAILED: " +
+                    "Pool " + p.getName() +
+                    " isCollectionUsageThresholdExceeded() returned true but" +
+                    " threshold(" + p.getCollectionUsageThreshold() +
+                    ") > used(" + u.getUsed() + ")");
+            }
+        }
+
+        // disable low memory detection and isCollectionUsageThresholdExceeded()
+        // should return false
+        p.setCollectionUsageThreshold(0);
+        if (p.isCollectionUsageThresholdExceeded()) {
+            throw new RuntimeException("TEST FAILED: " +
+                "Pool " + p.getName() +
+                " isCollectionUsageThresholdExceeded() returned true but threshold = 0");
+        }
+    }
+}
diff --git a/jdk/test/java/lang/management/OperatingSystemMXBean/GetSystemLoadAverage.java b/jdk/test/java/lang/management/OperatingSystemMXBean/GetSystemLoadAverage.java
new file mode 100644
index 0000000..d9a017b
--- /dev/null
+++ b/jdk/test/java/lang/management/OperatingSystemMXBean/GetSystemLoadAverage.java
@@ -0,0 +1,130 @@
+/*
+ * Copyright 2005 Sun Microsystems, Inc.  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 Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
+ * CA 95054 USA or visit www.sun.com if you need additional information or
+ * have any questions.
+ */
+
+/*
+ *
+ *
+ * @bug     6336608 6511738
+ * @summary Basic unit test of OperatingSystemMXBean.getSystemLoadAverage()
+ * @author  Mandy Chung
+ */
+
+/*
+ * This test tests the load average on linux and solaris. On Windows,
+ * getSystemLoadAverage() returns -1.
+ *
+ * Usage: GetSystemLoadAverage ["-1.0"]
+ * Arguments:
+ *   o If no argument is specified, the test will verify the system load
+ *     average with the /usr/bin/uptime command.
+ *   o Otherwise, the input argument must be "-1.0" indicating the
+ *     expected system load average.  This would only be the case when
+ *     running on Windows.
+ */
+
+import java.lang.management.*;
+import java.io.*;
+
+public class GetSystemLoadAverage {
+
+    private static OperatingSystemMXBean mbean =
+        ManagementFactory.getOperatingSystemMXBean();
+
+    // The system load average may be changing due to other jobs running.
+    // Allow some delta.
+    private static double DELTA = 0.05;
+
+    public static void main(String args[]) throws Exception {
+        if (args.length > 1)  {
+            throw new IllegalArgumentException("Unexpected number of args " + args.length);
+        }
+
+        if (args.length == 0) {
+            // On Linux or Solaris
+            checkLoadAvg();
+        } else {
+            // On Windows, the system load average is expected to be -1.0
+            if (!args[0].equals("-1.0")) {
+                throw new IllegalArgumentException("Invalid argument: " + args[0]);
+            } else {
+                double loadavg = mbean.getSystemLoadAverage();
+                if (loadavg != -1.0) {
+                    throw new RuntimeException("Expected load average : -1.0" +
+                        " but getSystemLoadAverage returned: " +
+                        loadavg);
+                }
+            }
+        }
+
+        System.out.println("Test passed.");
+    }
+
+    private static String LOAD_AVERAGE_TEXT = "load average:";
+    private static void checkLoadAvg() throws Exception {
+        // Obtain load average from OS command
+        ProcessBuilder pb = new ProcessBuilder("/usr/bin/uptime");
+        Process p = pb.start();
+        String output = commandOutput(p);
+
+        // obtain load average from OperatingSystemMXBean
+        double loadavg = mbean.getSystemLoadAverage();
+
+        // verify if two values are close
+        output = output.substring(output.lastIndexOf(LOAD_AVERAGE_TEXT) +
+                                  LOAD_AVERAGE_TEXT.length());
+        System.out.println("Load average returned from uptime = " + output);
+        System.out.println("getSystemLoadAverage() returned " + loadavg);
+
+        String[] lavg = output.split(",");
+        double expected = Double.parseDouble(lavg[0]);
+        double lowRange = expected * (1 - DELTA);
+        double highRange = expected * (1 + DELTA);
+
+        if (loadavg < lowRange || loadavg >  highRange) {
+            throw new RuntimeException("Expected load average : " +
+                    expected +
+                    " but getSystemLoadAverage returned: " +
+                    loadavg);
+        }
+    }
+
+    private static String commandOutput(Reader r) throws Exception {
+        StringBuilder sb = new StringBuilder();
+        int c;
+        while ((c = r.read()) > 0) {
+            if (c != '\r') {
+                sb.append((char) c);
+            }
+        }
+        return sb.toString();
+    }
+
+    private static String commandOutput(Process p) throws Exception {
+        Reader r = new InputStreamReader(p.getInputStream(),"UTF-8");
+        String output = commandOutput(r);
+        p.waitFor();
+        p.exitValue();
+        return output;
+    }
+
+}
diff --git a/jdk/test/java/lang/management/OperatingSystemMXBean/TestSystemLoadAvg.sh b/jdk/test/java/lang/management/OperatingSystemMXBean/TestSystemLoadAvg.sh
new file mode 100644
index 0000000..862923c
--- /dev/null
+++ b/jdk/test/java/lang/management/OperatingSystemMXBean/TestSystemLoadAvg.sh
@@ -0,0 +1,86 @@
+#
+# Copyright 2005-2006 Sun Microsystems, Inc.  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 Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
+# CA 95054 USA or visit www.sun.com if you need additional information or
+# have any questions.
+#
+
+# 
+# @test
+# @summary  Tests OperatingSystemMXBean.getSystemLoadAverage() api.
+# @author   Mandy Chung 
+# @bug      6336608 6367473 6511738
+#
+# @run build GetSystemLoadAverage
+# @run shell/timeout=300 TestSystemLoadAvg.sh
+#
+
+#
+# This test tests the system load average on linux and solaris.
+# On windows tests if it returns -1.0 The verification is done
+# by the GetSystemLoadAverage class.  By default it takes no
+# input argument which verifies the system load average with
+# /usr/bin/uptime command. Or specify "-1.0" as the input argument
+# indicatiing that the platform doesn't support the system load average.
+
+#Set appropriate jdk
+#
+
+if [ ! -z "${TESTJAVA}" ] ; then
+     jdk="$TESTJAVA"
+else
+     echo "--Error: TESTJAVA must be defined as the pathname of a jdk to test."
+     exit 1
+fi
+
+runOne()
+{
+   echo "$TESTJAVA/bin/java -classpath $TESTCLASSES $@"
+   $TESTJAVA/bin/java -classpath $TESTCLASSES $@
+}
+
+# Retry 5 times to be more resilent to system load fluctation.
+MAX=5
+i=1
+while true; do
+  echo "Run $i: TestSystemLoadAvg"
+  case `uname -s` in
+       SunOS )
+         runOne GetSystemLoadAverage 
+         ;;
+       Linux )
+         runOne GetSystemLoadAverage
+         ;;
+      * )
+         # On Windows -1.0 should be returned
+         runOne GetSystemLoadAverage "-1.0"
+         ;;
+  esac
+  if [ $? -eq 0 ]; then
+      # exit if the test passes
+      echo "Run $i: TestSystemLoadAvg test passed"
+      exit 0
+  elif [ $i -eq $MAX ] ; then
+      echo "TEST FAILED: TestSystemLoadAvg test failed $i runs"
+      exit 1
+  fi
+  i=`expr $i + 1`
+  # sleep for 5 seconds 
+  sleep 5
+done
diff --git a/jdk/test/java/lang/management/RuntimeMXBean/GetSystemProperties.java b/jdk/test/java/lang/management/RuntimeMXBean/GetSystemProperties.java
new file mode 100644
index 0000000..6a324bf
--- /dev/null
+++ b/jdk/test/java/lang/management/RuntimeMXBean/GetSystemProperties.java
@@ -0,0 +1,102 @@
+/*
+ * Copyright 2004 Sun Microsystems, Inc.  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 Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
+ * CA 95054 USA or visit www.sun.com if you need additional information or
+ * have any questions.
+ */
+
+/*
+ * @test
+ * @bug     4990512
+ * @summary Basic Test for RuntimeMXBean.getSystemProperties().
+ * @author  Mandy Chung
+ *
+ * @compile -source 1.5 GetSystemProperties.java
+ * @run main GetSystemProperties
+ */
+
+import java.lang.management.ManagementFactory;
+import java.lang.management.RuntimeMXBean;
+import java.util.*;
+
+public class GetSystemProperties {
+    private static final String KEY1   = "test.property.key1";
+    private static final String VALUE1 = "test.property.value1";
+    private static final String KEY2   = "test.property.key2";
+    private static final String VALUE2 = "test.property.value2";
+
+    // system properties to be omitted
+    private static final String KEY3   = "test.property.key3";
+    private static final Long VALUE3   = new Long(0);;
+
+    private static final Object KEY4   = new Object();
+    private static final String VALUE4 = "test.property.value4";
+
+    public static void main(String[] argv) throws Exception {
+        RuntimeMXBean mbean = ManagementFactory.getRuntimeMXBean();
+
+        // Print all system properties
+        Map<String,String> props = mbean.getSystemProperties();
+        printProperties(props);
+
+        // Add new system properties
+        System.setProperty(KEY1, VALUE1);
+        System.setProperty(KEY2, VALUE2);
+
+        Map<String,String> props1 = mbean.getSystemProperties();
+        String value1 = props1.get(KEY1);
+        if (value1 == null || !value1.equals(VALUE1)) {
+            throw new RuntimeException(KEY1 + " property found" +
+                 " with value = " + value1 +
+                 " but expected to be " + VALUE1);
+        }
+
+        String value2 = props1.get(KEY2);
+        if (value2 == null || !value2.equals(VALUE2)) {
+            throw new RuntimeException(KEY2 + " property found" +
+                 " with value = " + value2 +
+                 " but expected to be " + VALUE2);
+        }
+
+        String value3 = props1.get(KEY3);
+        if (value3 != null) {
+            throw new RuntimeException(KEY3 + " property found" +
+                 " but should not exist" );
+        }
+
+        // Add new system properties but are not Strings
+        Properties sp = System.getProperties();
+        sp.put(KEY3, VALUE3);
+        sp.put(KEY4, VALUE4);
+
+        Map<String,String> props2 = mbean.getSystemProperties();
+        // expect the system properties returned should be
+        // same as the one before adding KEY3 and KEY4
+        props1.equals(props2);
+
+        System.out.println("Test passed.");
+    }
+
+    private static void printProperties(Map<String,String> props) {
+        Set<Map.Entry<String,String>> set = props.entrySet();
+        for (Map.Entry<String,String> p : set) {
+            System.out.println(p.getKey() + ": " + p.getValue());
+        }
+    }
+}
diff --git a/jdk/test/java/lang/management/RuntimeMXBean/InputArgument.java b/jdk/test/java/lang/management/RuntimeMXBean/InputArgument.java
new file mode 100644
index 0000000..d3d8122
--- /dev/null
+++ b/jdk/test/java/lang/management/RuntimeMXBean/InputArgument.java
@@ -0,0 +1,69 @@
+/*
+ * Copyright 2003-2004 Sun Microsystems, Inc.  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 Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
+ * CA 95054 USA or visit www.sun.com if you need additional information or
+ * have any questions.
+ */
+
+/*
+ * @bug     4530538
+ * @summary Basic unit test of RuntimeMXBean.getInputArguments().
+ *
+ * @author  Mandy Chung
+ *
+ */
+
+import java.lang.management.*;
+import java.util.List;
+import java.util.ListIterator;
+
+public class InputArgument {
+    private static RuntimeMXBean rm = ManagementFactory.getRuntimeMXBean();
+    private static String vmOption = null;
+
+    public static void main(String args[]) throws Exception {
+        // set the expected input argument
+        if (args.length > 0) {
+            vmOption = args[0];
+        }
+
+        List<String> options = rm.getInputArguments();
+        if (vmOption == null) {
+            return;
+        }
+
+        boolean testFailed = true;
+        System.out.println("Number of arguments = " + options.size());
+        int i = 0;
+        for (String arg : options) {
+            System.out.println("Input arg " + i + " = " + arg);
+            i++;
+            if (arg.equals(vmOption)) {
+                testFailed = false;
+                break;
+            }
+        }
+        if (testFailed) {
+            throw new RuntimeException("TEST FAILED: " +
+                "VM option " + vmOption + " not found");
+        }
+
+        System.out.println("Test passed.");
+    }
+}
diff --git a/jdk/test/java/lang/management/RuntimeMXBean/PropertiesTest.java b/jdk/test/java/lang/management/RuntimeMXBean/PropertiesTest.java
new file mode 100644
index 0000000..2900b3c
--- /dev/null
+++ b/jdk/test/java/lang/management/RuntimeMXBean/PropertiesTest.java
@@ -0,0 +1,75 @@
+/*
+ * Copyright 2005 Sun Microsystems, Inc.  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 Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
+ * CA 95054 USA or visit www.sun.com if you need additional information or
+ * have any questions.
+ */
+
+/*
+ * @test
+ * @bug     6260131
+ * @summary Test for RuntimeMXBean.getSystemProperties() if the system
+ *          properties contain another list of properties as the defaults.
+ * @author  Mandy Chung
+ *
+ * @run build PropertiesTest
+ * @run main  PropertiesTest
+ */
+
+import java.util.*;
+import java.io.*;
+import java.lang.management.ManagementFactory;
+import java.lang.management.RuntimeMXBean;
+
+public class PropertiesTest {
+    private static int NUM_MYPROPS = 3;
+    public static void main(String[] argv) throws Exception {
+        Properties sysProps = System.getProperties();
+
+        // Create a new system properties using the old one
+        // as the defaults
+        Properties myProps = new Properties( System.getProperties() );
+
+        // add several new properties
+        myProps.put("good.property.1", "good.value.1");
+        myProps.put("good.property.2", "good.value.2");
+        myProps.put("good.property.3", "good.value.3");
+        myProps.put("good.property.4", new Integer(4));
+        myProps.put(new Integer(5), "good.value.5");
+        myProps.put(new Object(), new Object());
+
+        System.setProperties(myProps);
+
+        Map<String,String> props =
+            ManagementFactory.getRuntimeMXBean().getSystemProperties();
+        int i=0;
+        for (Map.Entry<String,String> e : props.entrySet()) {
+            String key = e.getKey();
+            String value = e.getValue();
+            System.out.println(i++ + ": " + key + " : " + value);
+        }
+
+        if (props.size() != NUM_MYPROPS + sysProps.size()) {
+            throw new RuntimeException("Test Failed: " +
+                "Expected number of properties = " +
+                NUM_MYPROPS + sysProps.size() +
+                " but found = " + props.size());
+        }
+    }
+}
diff --git a/jdk/test/java/lang/management/RuntimeMXBean/TestInputArgument.sh b/jdk/test/java/lang/management/RuntimeMXBean/TestInputArgument.sh
new file mode 100644
index 0000000..f1fb705
--- /dev/null
+++ b/jdk/test/java/lang/management/RuntimeMXBean/TestInputArgument.sh
@@ -0,0 +1,55 @@
+#
+# Copyright 2003-2006 Sun Microsystems, Inc.  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 Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
+# CA 95054 USA or visit www.sun.com if you need additional information or
+# have any questions.
+#
+
+#
+# @test
+# @bug     4530538
+# @summary 
+# @author  Mandy Chung
+#
+# @run compile -source 1.5 InputArgument.java
+# @run shell TestInputArgument.sh
+#
+
+#Set appropriate jdk
+
+if [ ! -z "${TESTJAVA}" ] ; then
+     jdk="$TESTJAVA"
+else
+     echo "--Error: TESTJAVA must be defined as the pathname of a jdk to test."
+     exit 1
+fi
+
+runOne()
+{ 
+   echo "runOne $@"
+   $TESTJAVA/bin/java $TESTVMOPTS -classpath $TESTCLASSES "$@" || exit 2
+}
+
+runOne InputArgument 
+
+runOne -XX:+UseParallelGC -XX:+PrintGCDetails InputArgument -XX:+PrintGCDetails
+runOne -XX:+UseParallelGC -XX:+PrintGCDetails InputArgument -XX:+UseParallelGC
+runOne "-Dprops=one two three" InputArgument "-Dprops=one two three"
+
+exit 0
diff --git a/jdk/test/java/lang/management/RuntimeMXBean/UpTime.java b/jdk/test/java/lang/management/RuntimeMXBean/UpTime.java
new file mode 100644
index 0000000..fee1b84
--- /dev/null
+++ b/jdk/test/java/lang/management/RuntimeMXBean/UpTime.java
@@ -0,0 +1,116 @@
+/*
+ * Copyright 2003-2004 Sun Microsystems, Inc.  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 Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
+ * CA 95054 USA or visit www.sun.com if you need additional information or
+ * have any questions.
+ */
+
+/*
+ * @test
+ * @bug     4530538
+ * @summary Basic unit test of RuntimeMXBean.getUptime()
+ * @author  Alexei Guibadoulline
+ */
+
+import java.lang.management.*;
+
+public class UpTime {
+    final static long DELAY = 5; // Seconds
+    final static long TIMEOUT = 30; // Minutes
+    private static RuntimeMXBean metrics
+        = ManagementFactory.getRuntimeMXBean();
+
+    public static void main(String argv[]) throws Exception {
+        long systemStartOuter = System.currentTimeMillis();
+        long metricsStart = metrics.getUptime();
+        long systemStartInner = System.currentTimeMillis();
+
+        // If uptime is more than 30 minutes then it looks like a bug in
+        // the method
+        if (metricsStart > TIMEOUT * 60 * 1000)
+            throw new RuntimeException("Uptime of the JVM is more than 30 "
+                                     + "minutes ("
+                                     + (metricsStart / 60 / 1000)
+                                     + " minutes).");
+
+        // Wait for DELAY seconds
+        Object o = new Object();
+        while (System.currentTimeMillis() < systemStartInner + DELAY * 1000) {
+            synchronized (o) {
+                try {
+                    o.wait(DELAY * 1000);
+                } catch (Exception e) {
+                    e.printStackTrace();
+                    throw e;
+                }
+            }
+        }
+
+        long systemEndInner = System.currentTimeMillis();
+        long metricsEnd = metrics.getUptime();
+        long systemEndOuter = System.currentTimeMillis();
+
+        long systemDifferenceInner = systemEndInner - systemStartInner;
+        long systemDifferenceOuter = systemEndOuter - systemStartOuter;
+        long metricsDifference = metricsEnd - metricsStart;
+
+        // Check the flow of time in RuntimeMXBean.getUptime(). See the
+        // picture below
+        if (metricsDifference < systemDifferenceInner)
+            throw new RuntimeException("Flow of the time in "
+                                     + "RuntimeMXBean.getUptime() ("
+                                     + metricsDifference + ") is slower than "
+                                     + " in system (" + systemDifferenceInner
+                                     + ")");
+        if (metricsDifference > systemDifferenceOuter)
+            throw new RuntimeException("Flow of the time in "
+                                     + "RuntimeMXBean.getUptime() ("
+                                     + metricsDifference + ") is faster than "
+                                     + "in system (" + systemDifferenceOuter
+                                     + ")");
+
+        System.out.println("Test passed.");
+    }
+}
+
+/*
+
+   A picture to describe the second testcase that checks the flow of time in
+   RuntimeMXBean.getUptime()
+
+
+   start
+             o1  u1  i1    Sleep for DELAY minutes    i2  u2  o2
+     |-------|---|---|--------------------------------|---|---|---------------> time
+
+
+   The following inequality (checked by the test) must always be true:
+
+       o2-o1 >= u2-u1 >= i2-i1
+
+   In the test:
+
+   i1 - systemStartInner
+   i2 - systemEndInner
+   o1 - systemStartOuter
+   o2 - systemEndOuter
+   u1 - metricsStart
+   u2 - metricsEnd
+
+*/
diff --git a/jdk/test/java/lang/management/ThreadMXBean/AllThreadIds.java b/jdk/test/java/lang/management/ThreadMXBean/AllThreadIds.java
new file mode 100644
index 0000000..50b3415
--- /dev/null
+++ b/jdk/test/java/lang/management/ThreadMXBean/AllThreadIds.java
@@ -0,0 +1,269 @@
+/*
+ * Copyright 2003-2004 Sun Microsystems, Inc.  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 Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
+ * CA 95054 USA or visit www.sun.com if you need additional information or
+ * have any questions.
+ */
+
+/*
+ * @test
+ * @bug     4530538
+ * @summary Basic unit test of ThreadMXBean.getAllThreadIds()
+ * @author  Alexei Guibadoulline and Mandy Chung
+ *
+ * @run build Barrier
+ * @run main AllThreadIds
+ */
+
+import java.lang.management.*;
+import java.util.*;
+
+public class AllThreadIds {
+    final static int DAEMON_THREADS = 20;
+    final static int USER_THREADS = 5;
+    final static int ALL_THREADS = DAEMON_THREADS + USER_THREADS;
+    private static volatile boolean live[] = new boolean[ALL_THREADS];
+    private static Thread allThreads[] = new Thread[ALL_THREADS];
+    private static ThreadMXBean mbean
+        = ManagementFactory.getThreadMXBean();
+    private static boolean testFailed = false;
+    private static boolean trace = false;
+
+    private static long prevTotalThreadCount = 0;
+    private static int prevLiveThreadCount = 0;
+    private static int prevPeakThreadCount = 0;
+    private static long curTotalThreadCount = 0;
+    private static int curLiveThreadCount = 0;
+    private static int curPeakThreadCount = 0;
+
+    // barrier for threads communication
+    private static Barrier barrier = new Barrier(ALL_THREADS);
+
+    private static void printThreadList() {
+        if (!trace) return;
+
+        long[] list = mbean.getAllThreadIds();
+        for (int i = 1; i <= list.length; i++) {
+            System.out.println(i + ": Thread id = " + list[i-1]);
+        }
+        for (int i = 0; i < ALL_THREADS; i++) {
+            Thread t = allThreads[i];
+            System.out.println(t.getName() + " Id = " + t.getId() +
+                " die = " + live[i] +
+                " alive = " + t.isAlive());
+        }
+    }
+
+    private static void checkThreadCount(int numNewThreads,
+                                         int numTerminatedThreads)
+        throws Exception {
+        prevTotalThreadCount = curTotalThreadCount;
+        prevLiveThreadCount = curLiveThreadCount;
+        prevPeakThreadCount = curPeakThreadCount;
+        curTotalThreadCount = mbean.getTotalStartedThreadCount();
+        curLiveThreadCount = mbean.getThreadCount();
+        curPeakThreadCount = mbean.getPeakThreadCount();
+
+        if ((curLiveThreadCount - prevLiveThreadCount) !=
+            (numNewThreads - numTerminatedThreads)) {
+            throw new RuntimeException("Unexpected number of live threads: " +
+                " Prev Total = " + prevTotalThreadCount +
+                " Current Total = " + curTotalThreadCount +
+                " Threads added = " + numNewThreads +
+                " Threads terminated = " + numTerminatedThreads);
+        }
+        if (curPeakThreadCount - prevPeakThreadCount != numNewThreads) {
+            throw new RuntimeException("Unexpected number of peak threads: " +
+                " Prev Total = " + prevTotalThreadCount +
+                " Current Total = " + curTotalThreadCount +
+                " Threads added = " + numNewThreads);
+        }
+        if (curTotalThreadCount - prevTotalThreadCount != numNewThreads) {
+            throw new RuntimeException("Unexpected number of total threads: " +
+                " Prev Total = " + prevTotalThreadCount +
+                " Current Total = " + curTotalThreadCount +
+                " Threads added = " + numNewThreads);
+        }
+        long[] list = mbean.getAllThreadIds();
+        if (list.length != curLiveThreadCount) {
+            throw new RuntimeException("Array length returned by " +
+                "getAllThreadIds() = " + list.length +
+                " not matched count = " + curLiveThreadCount);
+        }
+    }
+
+    public static void main(String args[]) throws Exception {
+        if (args.length > 0 && args[0].equals("trace")) {
+            trace = true;
+        }
+
+        curTotalThreadCount = mbean.getTotalStartedThreadCount();
+        curLiveThreadCount = mbean.getThreadCount();
+        curPeakThreadCount = mbean.getPeakThreadCount();
+        checkThreadCount(0, 0);
+
+
+        // Start all threads and wait to be sure they all are alive
+        barrier.set(ALL_THREADS);
+        for (int i = 0; i < ALL_THREADS; i++) {
+            live[i] = true;
+            allThreads[i] = new MyThread(i);
+            allThreads[i].setDaemon( (i < DAEMON_THREADS) ? true : false);
+            allThreads[i].start();
+        }
+        // wait until all threads are started.
+        barrier.await();
+
+
+        checkThreadCount(ALL_THREADS, 0);
+        printThreadList();
+
+        // Check mbean now. All threads must appear in getAllThreadIds() list
+        long[] list = mbean.getAllThreadIds();
+
+        for (int i = 0; i < ALL_THREADS; i++) {
+            long expectedId = allThreads[i].getId();
+            boolean found = false;
+
+            if (trace) {
+                System.out.print("Looking for thread with id " + expectedId);
+            }
+            for (int j = 0; j < list.length; j++) {
+                if (expectedId == list[j]) {
+                    found = true;
+                    break;
+                }
+            }
+
+            if (!found) {
+                testFailed = true;
+            }
+            if (trace) {
+                if (!found) {
+                    System.out.print(". TEST FAILED.");
+                }
+                System.out.println();
+            }
+        }
+        if (trace) {
+            System.out.println();
+        }
+
+        // Stop daemon threads, wait to be sure they all are dead, and check
+        // that they disappeared from getAllThreadIds() list
+        barrier.set(DAEMON_THREADS);
+        for (int i = 0; i < DAEMON_THREADS; i++) {
+            live[i] = false;
+        }
+        // wait until daemon threads are terminated.
+        barrier.await();
+
+        // give chance to threads to terminate
+        pause();
+        checkThreadCount(0, DAEMON_THREADS);
+
+        // Check mbean now
+        list = mbean.getAllThreadIds();
+
+        for (int i = 0; i < ALL_THREADS; i++) {
+            long expectedId = allThreads[i].getId();
+            boolean found = false;
+            boolean live = (i >= DAEMON_THREADS);
+
+            if (trace) {
+                System.out.print("Looking for thread with id " + expectedId +
+                    (live ? " expected alive." : " expected terminated."));
+            }
+            for (int j = 0; j < list.length; j++) {
+                if (expectedId == list[j]) {
+                    found = true;
+                    break;
+                }
+            }
+
+            if (live != found) {
+                testFailed = true;
+            }
+            if (trace) {
+                if (live != found) {
+                    System.out.println(" TEST FAILED.");
+                } else {
+                    System.out.println();
+                }
+            }
+        }
+
+        // Stop all threads and wait to be sure they all are dead
+        barrier.set(ALL_THREADS - DAEMON_THREADS);
+        for (int i = DAEMON_THREADS; i < ALL_THREADS; i++) {
+            live[i] = false;
+        }
+        // wait until daemon threads are terminated .
+        barrier.await();
+
+        // give chance to threads to terminate
+        pause();
+        checkThreadCount(0, ALL_THREADS - DAEMON_THREADS);
+
+        if (testFailed)
+            throw new RuntimeException("TEST FAILED.");
+
+        System.out.println("Test passed.");
+    }
+
+    // The MyThread thread lives as long as correspondent live[i] value is true
+    private static class MyThread extends Thread {
+        int id;
+
+        MyThread(int id) {
+            this.id = id;
+        }
+
+        public void run() {
+            // signal started
+            barrier.signal();
+            while (live[id]) {
+                try {
+                    sleep(100);
+                } catch (InterruptedException e) {
+                    System.out.println("Unexpected exception is thrown.");
+                    e.printStackTrace(System.out);
+                    testFailed = true;
+                }
+            }
+            // signal about to exit
+            barrier.signal();
+        }
+    }
+
+    private static Object pauseObj = new Object();
+    private static void pause() {
+        // Enter lock a without blocking
+        synchronized (pauseObj) {
+            try {
+                // may need to tune this timeout for different platforms
+                pauseObj.wait(50);
+            } catch (Exception e) {
+                System.err.println("Unexpected exception.");
+                e.printStackTrace(System.err);
+            }
+        }
+    }
+
+}
diff --git a/jdk/test/java/lang/management/ThreadMXBean/Barrier.java b/jdk/test/java/lang/management/ThreadMXBean/Barrier.java
new file mode 100644
index 0000000..67739cf
--- /dev/null
+++ b/jdk/test/java/lang/management/ThreadMXBean/Barrier.java
@@ -0,0 +1,76 @@
+/*
+ * Copyright 2003 Sun Microsystems, Inc.  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 Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
+ * CA 95054 USA or visit www.sun.com if you need additional information or
+ * have any questions.
+ */
+
+/*
+ * @bug     4530538
+ * @summary A Barrier utility class.
+ * @author  Mandy Chung
+ */
+
+public class Barrier {
+    private Object go = new Object();
+    private int count;
+    private int waiters = 0;
+
+    public Barrier(int count) {
+        if (count <= 0) {
+            throw new IllegalArgumentException();
+        }
+        this.count = count;
+    }
+
+    public void set(int count) {
+        if (waiters != 0) {
+            throw new IllegalArgumentException();
+        }
+        this.count = count;
+        this.waiters = 0;
+    }
+
+    public void await() {
+        synchronized (go) {
+            waiters++;
+            while (count > 0) {
+                try {
+                    go.wait();
+                } catch (InterruptedException e) {
+                    e.printStackTrace();
+                    throw new InternalError();
+                }
+            }
+            waiters--;
+        }
+    }
+    public void signal() {
+        synchronized (go) {
+            count--;
+            go.notifyAll();
+        }
+    }
+
+    public int getWaiterCount() {
+        synchronized (go) {
+            return waiters;
+        }
+    }
+}
diff --git a/jdk/test/java/lang/management/ThreadMXBean/DisableTest.java b/jdk/test/java/lang/management/ThreadMXBean/DisableTest.java
new file mode 100644
index 0000000..e58ab7a
--- /dev/null
+++ b/jdk/test/java/lang/management/ThreadMXBean/DisableTest.java
@@ -0,0 +1,102 @@
+/*
+ * Copyright 2003-2004 Sun Microsystems, Inc.  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 Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
+ * CA 95054 USA or visit www.sun.com if you need additional information or
+ * have any questions.
+ */
+
+/*
+ * @test
+ * @bug     4956978
+ * @summary The capability is disabled regardless of number of times
+ *          it was enabled.
+ * @author  Mandy Chung
+ */
+
+import java.lang.management.ThreadMXBean;
+import java.lang.management.ManagementFactory;
+
+public class DisableTest {
+    private static ThreadMXBean tm = ManagementFactory.getThreadMXBean();
+
+    public static void main(String args[]) throws Exception {
+        testThreadContentionMonitoring();
+        testThreadCpuMonitoring();
+
+        System.out.println("Test passed.");
+    }
+
+    private static void testThreadContentionMonitoring()
+        throws Exception {
+        if (!tm.isThreadContentionMonitoringSupported()) {
+            System.out.println("JVM does not supports thread contention monitoring");
+            return;
+        }
+
+        // Default is false.
+        tm.setThreadContentionMonitoringEnabled(false);
+        tm.setThreadContentionMonitoringEnabled(false);
+
+        // check if disabled
+        if (tm.isThreadContentionMonitoringEnabled()) {
+            throw new RuntimeException("TEST FAILED: " +
+                "Expected thread contention monitoring to be disabled");
+        }
+
+        tm.setThreadContentionMonitoringEnabled(true);
+        // check if enabled
+        if (!tm.isThreadContentionMonitoringEnabled()) {
+            throw new RuntimeException("TEST FAILED: " +
+                "Expected thread contention monitoring to be enabled");
+        }
+    }
+
+    private static void testThreadCpuMonitoring()
+        throws Exception {
+        if (!tm.isThreadCpuTimeSupported()) {
+            System.out.println("JVM does not support thread CPU time monitoring");
+            return;
+        }
+
+        if (tm.isThreadCpuTimeEnabled()) {
+            tm.setThreadCpuTimeEnabled(false);
+        }
+
+        // check if disabled
+        if (tm.isThreadCpuTimeEnabled()) {
+            throw new RuntimeException("TEST FAILED: " +
+                "Expected thread CPU time monitoring to be disabled");
+        }
+
+        tm.setThreadCpuTimeEnabled(false);
+        tm.setThreadCpuTimeEnabled(false);
+
+        if (tm.isThreadCpuTimeEnabled()) {
+            throw new RuntimeException("TEST FAILED: " +
+                "Expected thread CPU time monitoring to be disabled");
+        }
+
+        tm.setThreadCpuTimeEnabled(true);
+        if (!tm.isThreadCpuTimeEnabled()) {
+            throw new RuntimeException("TEST FAILED: " +
+                "Expected thread CPU time monitoring to be disabled");
+        }
+    }
+
+}
diff --git a/jdk/test/java/lang/management/ThreadMXBean/EnableTest.java b/jdk/test/java/lang/management/ThreadMXBean/EnableTest.java
new file mode 100644
index 0000000..aa07504
--- /dev/null
+++ b/jdk/test/java/lang/management/ThreadMXBean/EnableTest.java
@@ -0,0 +1,127 @@
+/*
+ * Copyright 2003-2004 Sun Microsystems, Inc.  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 Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
+ * CA 95054 USA or visit www.sun.com if you need additional information or
+ * have any questions.
+ */
+
+/*
+ * @test
+ * @bug     4530538
+ * @summary Basic unit test of
+ *          ThreadMXBean.setThreadContentionMonitoringEnabled()
+ *          and ThreadMXBean.setThreadCpuTimeEnabled().
+ * @author  Mandy Chung
+ *
+ * @run main EnableTest
+ */
+
+import java.lang.management.*;
+
+public class EnableTest {
+    private static ThreadMXBean tm = ManagementFactory.getThreadMXBean();
+
+    private static void checkThreadContentionMonitoring(boolean expectedValue)
+        throws Exception {
+        boolean value = tm.isThreadContentionMonitoringEnabled();
+        if (value != expectedValue) {
+             throw new RuntimeException("TEST FAILED: " +
+                 "isThreadContentionMonitoringEnabled() returns " + value +
+                 " but expected to be " + expectedValue);
+        }
+
+    }
+
+    private static void testThreadContentionMonitoring()
+        throws Exception {
+        if (!tm.isThreadContentionMonitoringSupported()) return;
+
+        // Test setThreadContentionMonitoringEnabled()
+        checkThreadContentionMonitoring(false);
+
+        // Check enabled once
+        tm.setThreadContentionMonitoringEnabled(true);
+        checkThreadContentionMonitoring(true);
+
+        // Enable it two more times
+        tm.setThreadContentionMonitoringEnabled(true);
+        checkThreadContentionMonitoring(true);
+
+        tm.setThreadContentionMonitoringEnabled(true);
+
+        // Disable once will globally disable the thread contention monitoring
+        tm.setThreadContentionMonitoringEnabled(false);
+        checkThreadContentionMonitoring(false);
+
+        tm.setThreadContentionMonitoringEnabled(false);
+        checkThreadContentionMonitoring(false);
+
+        tm.setThreadContentionMonitoringEnabled(true);
+        checkThreadContentionMonitoring(true);
+    }
+
+    private static void checkThreadCpuTime(boolean expectedValue)
+        throws Exception {
+        boolean value = tm.isThreadCpuTimeEnabled();
+        if (value != expectedValue) {
+             throw new RuntimeException("TEST FAILED: " +
+                 "isThreadCpuTimeEnabled() returns " + value +
+                 " but expected to be " + expectedValue);
+        }
+    }
+
+    private static void testThreadCpuTime()
+        throws Exception {
+        if (!tm.isThreadCpuTimeSupported()) return;
+
+        // Test setThreadCpuTimeEnabled()
+        if (!tm.isThreadCpuTimeEnabled()) {
+            tm.setThreadCpuTimeEnabled(true);
+            checkThreadCpuTime(true);
+        }
+
+        tm.setThreadCpuTimeEnabled(false);
+        checkThreadCpuTime(false);
+
+        tm.setThreadCpuTimeEnabled(true);
+        checkThreadCpuTime(true);
+
+        tm.setThreadCpuTimeEnabled(true);
+        checkThreadCpuTime(true);
+
+        tm.setThreadCpuTimeEnabled(true);
+
+        // disable globally
+        tm.setThreadCpuTimeEnabled(false);
+        checkThreadCpuTime(false);
+
+        tm.setThreadCpuTimeEnabled(false);
+        checkThreadCpuTime(false);
+
+        tm.setThreadCpuTimeEnabled(true);
+        checkThreadCpuTime(true);
+    }
+
+    public static void main(String args[]) throws Exception {
+        testThreadContentionMonitoring();
+        testThreadCpuTime();
+
+        System.out.println("Test passed.");
+    }
+}
diff --git a/jdk/test/java/lang/management/ThreadMXBean/FindDeadlocks.java b/jdk/test/java/lang/management/ThreadMXBean/FindDeadlocks.java
new file mode 100644
index 0000000..51f6626
--- /dev/null
+++ b/jdk/test/java/lang/management/ThreadMXBean/FindDeadlocks.java
@@ -0,0 +1,126 @@
+/*
+ * Copyright 2005 Sun Microsystems, Inc.  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 Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
+ * CA 95054 USA or visit www.sun.com if you need additional information or
+ * have any questions.
+ */
+
+
+/*
+ * @test
+ * @bug     5086470
+ * @summary Basic Test for the following methods:
+ *          - ThreadMXBean.findDeadlockedThreads()
+ *          - ThreadMXBean.findMonitorDeadlockedThreads()
+ * @author  Mandy Chung
+ *
+ * @build MonitorDeadlock
+ * @build SynchronizerDeadlock
+ * @build ThreadDump
+ * @run main FindDeadlocks
+ */
+
+import java.lang.management.*;
+import java.util.*;
+
+public class FindDeadlocks {
+    static ThreadMXBean mbean = ManagementFactory.getThreadMXBean();
+    public static void main(String[] argv) {
+        ThreadMXBean mbean = ManagementFactory.getThreadMXBean();
+        // create deadlocked threads
+        MonitorDeadlock md = new MonitorDeadlock();
+
+        // no deadlock
+        if (findDeadlocks() != null) {
+            throw new RuntimeException("TEST FAILED: Should return null.");
+        }
+
+        // Let the threads to proceed
+        md.goDeadlock();
+        // wait until the deadlock is ready
+        md.waitUntilDeadlock();
+
+        long[] mthreads = findDeadlocks();
+        if (mthreads == null) {
+            ThreadDump.dumpStacks();
+            throw new RuntimeException("TEST FAILED: Deadlock not detected.");
+        }
+        md.checkResult(mthreads);
+
+        // create deadlocked threads on synchronizers
+        SynchronizerDeadlock sd = new SynchronizerDeadlock();
+
+        // Let the threads to proceed
+        sd.goDeadlock();
+        // wait until the deadlock is ready
+        sd.waitUntilDeadlock();
+
+        // Find Deadlock
+        long[] threads = findDeadlocks();
+        if (threads == null) {
+            ThreadDump.dumpStacks();
+            throw new RuntimeException("TEST FAILED: Deadlock not detected.");
+        }
+
+        // form a list of newly deadlocked threads
+        long[] newList = new long[threads.length - mthreads.length];
+        int count = 0;
+        for (int i = 0; i < threads.length; i++) {
+            long id = threads[i];
+            boolean isNew = true;
+            for (int j = 0; j < mthreads.length; j++) {
+                if (mthreads[j] == id) {
+                    isNew = false;
+                    break;
+                }
+            }
+            if (isNew) {
+                newList[count++] = id;
+            }
+        }
+
+        if (mbean.isSynchronizerUsageSupported()) {
+            sd.checkResult(newList);
+        } else {
+            // monitoring of synchronizer usage not supported
+            if (count != 0) {
+                throw new RuntimeException("TEST FAILED: NewList should be empty.");
+            }
+        }
+
+        // Print Deadlock stack trace
+        System.out.println("Found threads that are in deadlock:-");
+        ThreadInfo[] infos = mbean.getThreadInfo(threads, Integer.MAX_VALUE);
+        for (int i = 0; i < infos.length; i++) {
+            ThreadDump.printThreadInfo(infos[i]);
+        }
+
+        System.out.println("Test passed");
+    }
+    static long[] findDeadlocks() {
+        long[] threads;
+        if (mbean.isSynchronizerUsageSupported()) {
+            threads = mbean.findDeadlockedThreads();
+        } else {
+            threads = mbean.findMonitorDeadlockedThreads();
+        }
+        return threads;
+    }
+
+}
diff --git a/jdk/test/java/lang/management/ThreadMXBean/FindMonitorDeadlock.java b/jdk/test/java/lang/management/ThreadMXBean/FindMonitorDeadlock.java
new file mode 100644
index 0000000..017e39f
--- /dev/null
+++ b/jdk/test/java/lang/management/ThreadMXBean/FindMonitorDeadlock.java
@@ -0,0 +1,74 @@
+/*
+ * Copyright 2003-2005 Sun Microsystems, Inc.  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 Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
+ * CA 95054 USA or visit www.sun.com if you need additional information or
+ * have any questions.
+ */
+
+/*
+ * @test
+ * @bug     4892507
+ * @summary Basic Test for the following reset methods:
+ *          - ThreadMXBean.findMonitorDeadlockedThreads()
+ * @author  Mandy Chung
+ *
+ * @build MonitorDeadlock
+ * @build ThreadDump
+ * @run main FindMonitorDeadlock
+ */
+
+import java.lang.management.*;
+import java.util.*;
+
+public class FindMonitorDeadlock {
+    public static void main(String[] argv) {
+        // create deadlocked threads
+        MonitorDeadlock md = new MonitorDeadlock();
+
+        // No deadlock
+        ThreadMXBean mbean = ManagementFactory.getThreadMXBean();
+        long[] threads = mbean.findMonitorDeadlockedThreads();
+        if (threads != null) {
+            throw new RuntimeException("TEST FAILED: Should return null.");
+        }
+
+        // Let the threads to proceed
+        md.goDeadlock();
+
+        // wait until the deadlock is ready
+        md.waitUntilDeadlock();
+
+        // Find Deadlock
+        threads = mbean.findMonitorDeadlockedThreads();
+        if (threads == null) {
+            ThreadDump.dumpStacks();
+            throw new RuntimeException("TEST FAILED: Deadlock not detected.");
+        }
+
+        // Print Deadlock stack trace
+        System.out.println("Found threads that are in deadlock:-");
+        ThreadInfo[] infos = mbean.getThreadInfo(threads, Integer.MAX_VALUE);
+        for (int i = 0; i < infos.length; i++) {
+            ThreadDump.printThreadInfo(infos[i]);
+        }
+
+        md.checkResult(threads);
+        System.out.println("Test passed");
+    }
+}
diff --git a/jdk/test/java/lang/management/ThreadMXBean/InvalidThreadID.java b/jdk/test/java/lang/management/ThreadMXBean/InvalidThreadID.java
new file mode 100644
index 0000000..b706fc6
--- /dev/null
+++ b/jdk/test/java/lang/management/ThreadMXBean/InvalidThreadID.java
@@ -0,0 +1,70 @@
+/*
+ * Copyright 2003-2004 Sun Microsystems, Inc.  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 Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
+ * CA 95054 USA or visit www.sun.com if you need additional information or
+ * have any questions.
+ */
+
+/*
+ * @test
+ * @bug     4929401
+ * @summary ThreadMXBean.getThreadCpuTime() throws IllegalArgumentException
+ *          if id <= 0 and returns -1 if the thread doesn't exist.
+ * @author  Mandy Chung
+ *
+ * @run main InvalidThreadID
+ */
+
+import java.lang.management.ThreadMXBean;
+import java.lang.management.ManagementFactory;
+
+public class InvalidThreadID {
+
+    public static void main(String argv[]) {
+
+        ThreadMXBean mbean = ManagementFactory.getThreadMXBean();
+        int cnt = 0;
+        long [] idArr = {0, -1, -2, (Long.MIN_VALUE + 1), Long.MIN_VALUE};
+
+        if (mbean.isThreadCpuTimeSupported()) {
+            for (int i = 0; i < idArr.length; i++) {
+                try {
+                    mbean.getThreadCpuTime(idArr[i]);
+                    System.out.println("Test failed. IllegalArgumentException" +
+                        " expected for ID = " + idArr[i]);
+                } catch (IllegalArgumentException iae) {
+                    cnt++;
+                }
+            }
+            if (cnt != idArr.length) {
+                throw new RuntimeException("Unexpected number of " +
+                    "IllegalArgumentException = " + cnt +
+                    " expected = " + idArr.length);
+            }
+
+            // CPU time for a non-existence thread
+            long time = mbean.getThreadCpuTime(999999);
+            if (time < 0 && time != -1) {
+                throw new RuntimeException("Cpu time for thread 999999" +
+                    " is invalid = " + time + " expected to be -1.");
+            }
+        }
+        System.out.println("Test passed.");
+    }
+}
diff --git a/jdk/test/java/lang/management/ThreadMXBean/LockedMonitors.java b/jdk/test/java/lang/management/ThreadMXBean/LockedMonitors.java
new file mode 100644
index 0000000..63b215a
--- /dev/null
+++ b/jdk/test/java/lang/management/ThreadMXBean/LockedMonitors.java
@@ -0,0 +1,87 @@
+/*
+ * Copyright 2005 Sun Microsystems, Inc.  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 Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
+ * CA 95054 USA or visit www.sun.com if you need additional information or
+ * have any questions.
+ */
+
+/*
+ * @test
+ * @bug     5086470 6358247
+ * @summary Basic Test for ThreadInfo.getLockedMonitors()
+ *          - a stack frame acquires no monitor
+ *          - a stack frame acquires one or more monitors
+ *          - a stack frame blocks on Object.wait
+ *            and the monitor waiting is not locked.
+ *          LockingThread is the class that creates threads
+ *          and do the checking.
+ *
+ * @author  Mandy Chung
+ *
+ * @build Barrier
+ * @build LockingThread
+ * @build ThreadDump
+ * @run main LockedMonitors
+ */
+
+import java.lang.management.*;
+import java.util.*;
+
+public class LockedMonitors {
+    public static void main(String[] argv) throws Exception {
+        ThreadMXBean mbean = ManagementFactory.getThreadMXBean();
+        if (!mbean.isObjectMonitorUsageSupported()) {
+            System.out.println("Monitoring of object monitor usage is not supported");
+            return;
+        }
+
+        // Start the thread and print the thread dump
+        LockingThread.startLockingThreads();
+        ThreadDump.threadDump();
+
+        ThreadInfo[] tinfos;
+        long[] ids = LockingThread.getThreadIds();
+
+        // Dump all threads with locked monitors
+        tinfos = mbean.dumpAllThreads(true, false);
+        LockingThread.checkLockedMonitors(tinfos);
+
+        // Dump all threads with locked monitors and locked synchronizers
+        tinfos = mbean.dumpAllThreads(true, true);
+        LockingThread.checkLockedMonitors(tinfos);
+
+        // Test getThreadInfo with locked monitors
+        tinfos = mbean.getThreadInfo(ids, true, false);
+        if (tinfos.length != ids.length) {
+            throw new RuntimeException("Number of ThreadInfo objects = " +
+                tinfos.length + " not matched. Expected: " + ids.length);
+        }
+        LockingThread.checkLockedMonitors(tinfos);
+
+        // Test getThreadInfo with locked monitors and locked synchronizers
+        tinfos = mbean.getThreadInfo(ids, true, true);
+        if (tinfos.length != ids.length) {
+            throw new RuntimeException("Number of ThreadInfo objects = " +
+                tinfos.length + " not matched. Expected: " + ids.length);
+        }
+        LockingThread.checkLockedMonitors(tinfos);
+
+        System.out.println("Test passed");
+    }
+}
diff --git a/jdk/test/java/lang/management/ThreadMXBean/LockedSynchronizers.java b/jdk/test/java/lang/management/ThreadMXBean/LockedSynchronizers.java
new file mode 100644
index 0000000..7d997fb
--- /dev/null
+++ b/jdk/test/java/lang/management/ThreadMXBean/LockedSynchronizers.java
@@ -0,0 +1,70 @@
+/*
+ * Copyright 2005 Sun Microsystems, Inc.  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 Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
+ * CA 95054 USA or visit www.sun.com if you need additional information or
+ * have any questions.
+ */
+
+/*
+ * @test
+ * @bug     5086470 6358247
+ * @summary Basic Test for ThreadInfo.getLockedSynchronizers()
+ *          SynchronizerLockingThread is the class that creates threads
+ *          and do the checking.
+ *
+ * @author  Mandy Chung
+ *
+ * @build Barrier
+ * @build SynchronizerLockingThread
+ * @build ThreadDump
+ * @run main LockedSynchronizers
+ */
+
+import java.lang.management.*;
+import java.util.*;
+
+public class LockedSynchronizers {
+    public static void main(String[] argv) throws Exception {
+        ThreadMXBean mbean = ManagementFactory.getThreadMXBean();
+        if (!mbean.isSynchronizerUsageSupported()) {
+            System.out.println("Monitoring of synchronizer usage not supported");
+            return;
+        }
+
+        // Start thread and print thread dump
+        SynchronizerLockingThread.startLockingThreads();
+        ThreadDump.threadDump();
+
+        // Test dumpAllThreads with locked monitors and synchronizers
+        ThreadInfo[] tinfos = mbean.dumpAllThreads(true, true);
+        SynchronizerLockingThread.checkLocks(tinfos);
+
+        // Test getThreadInfo with locked monitors and synchronizers
+        long[] ids = SynchronizerLockingThread.getThreadIds();
+        tinfos = mbean.getThreadInfo(ids, true, true);
+        if (tinfos.length != ids.length) {
+            throw new RuntimeException("Number of ThreadInfo objects = " +
+                tinfos.length + " not matched. Expected: " + ids.length);
+        }
+
+        SynchronizerLockingThread.checkLocks(tinfos);
+
+        System.out.println("Test passed");
+    }
+}
diff --git a/jdk/test/java/lang/management/ThreadMXBean/LockingThread.java b/jdk/test/java/lang/management/ThreadMXBean/LockingThread.java
new file mode 100644
index 0000000..11fa9d9
--- /dev/null
+++ b/jdk/test/java/lang/management/ThreadMXBean/LockingThread.java
@@ -0,0 +1,308 @@
+/*
+ * Copyright 2005 Sun Microsystems, Inc.  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 Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
+ * CA 95054 USA or visit www.sun.com if you need additional information or
+ * have any questions.
+ */
+
+/*
+ * @bug     5086470  6358247
+ * @summary LockingThread is used by LockedMonitors test.
+ *          It will create threads that have:
+ *          - a stack frame acquires no monitor
+ *          - a stack frame acquires one or more monitors
+ *          - a stack frame blocks on Object.wait
+ *            and the monitor waiting is not locked.
+ * @author  Mandy Chung
+ *
+ * @build Barrier
+ * @build ThreadDump
+ */
+
+import java.lang.management.*;
+import java.util.*;
+
+public class LockingThread extends Thread {
+    static Lock lock1 = new Lock("lock1");
+    static Lock lock2 = new Lock("lock2");
+    static Lock lock3 = new Lock("lock3");
+    static Lock lock4 = new Lock("lock4");
+    static Lock lock5 = new Lock("lock5");
+    static Lock lock6 = new Lock("lock6");
+    static Lock lock7 = new Lock("lock7");
+    static Lock lock8 = new Lock("lock8");
+
+    static LockingThread t1 = new Thread1();
+    static LockingThread t2 = new Thread2();
+    static Barrier barr = new Barrier(2);
+    static int count = 2;
+    static void startLockingThreads() {
+        t1.setDaemon(true);
+        t2.setDaemon(true);
+        t1.start();
+        t2.start();
+
+        // wait until t1 waits
+        while (count != 0) {
+           try {
+               Thread.sleep(100);
+           } catch (InterruptedException e) {
+               throw new RuntimeException(e);
+           }
+        }
+    }
+    static long[] getThreadIds() {
+        return new long[] {t1.getId(), t2.getId()};
+    }
+
+    static void checkLockedMonitors(ThreadInfo[] tinfos)
+        throws Exception {
+
+        int matches = 0;
+        for (ThreadInfo ti : tinfos) {
+            if (ti.getThreadId() == t1.getId()) {
+                t1.checkLockedMonitors(ti);
+                matches++;
+            }
+            if (ti.getThreadId() == t2.getId()) {
+                t2.checkLockedMonitors(ti);
+                matches++;
+            }
+        }
+        if (matches != 2) {
+            throw new RuntimeException("MonitorInfo missing");
+        }
+    }
+
+    static class Lock {
+        String name;
+        Lock(String name) {
+            this.name = name;
+        }
+        public String toString() {
+            return name;
+        }
+    }
+
+    final String threadName;
+    Lock         waitingLock;
+    int          numOwnedMonitors;
+    Map<String, Lock[]> ownedMonitors;
+    public LockingThread(String name) {
+        this.threadName = name;
+    }
+
+    protected void setExpectedResult(Lock waitingLock,
+                                     int numOwnedMonitors,
+                                     Map<String, Lock[]> ownedMonitors) {
+        this.waitingLock = waitingLock;
+        this.numOwnedMonitors = numOwnedMonitors;
+        this.ownedMonitors = ownedMonitors;
+    }
+
+    void checkLockedMonitors(ThreadInfo info)
+        throws Exception {
+        checkThreadInfo(info);
+
+        MonitorInfo[] monitors = info.getLockedMonitors();
+        if (monitors.length != numOwnedMonitors) {
+            ThreadDump.threadDump();
+            throw new RuntimeException("Number of locked monitors = " +
+                monitors.length +
+                " not matched. Expected: " + numOwnedMonitors);
+        }
+        // check if each monitor returned in the list is the expected
+        // one
+        for (MonitorInfo m : monitors) {
+            StackTraceElement ste = m.getLockedStackFrame();
+            int depth = m.getLockedStackDepth();
+            checkStackFrame(info, ste, depth);
+            checkMonitor(m, ste.getMethodName());
+        }
+        // check if each expected monitor is included in the returned
+        // list
+        for (Map.Entry<String, Lock[]> e : ownedMonitors.entrySet()) {
+            for (Lock l : e.getValue()) {
+                checkMonitor(e.getKey(), l, monitors);
+            }
+        }
+
+        if (info.getLockedSynchronizers().length != 0) {
+            ThreadDump.threadDump();
+            throw new RuntimeException("Number of locked synchronizers = " +
+                info.getLockedSynchronizers().length +
+                " not matched. Expected: 0.");
+        }
+    }
+
+    void checkThreadInfo(ThreadInfo info) throws Exception {
+        if (!getName().equals(info.getThreadName())) {
+            throw new RuntimeException("Name: " + info.getThreadName() +
+                " not matched. Expected: " + getName());
+        }
+        LockInfo l = info.getLockInfo();
+        if ((waitingLock == null && l != null) ||
+            (waitingLock != null && l == null)) {
+            throw new RuntimeException("LockInfo: " + l +
+                " not matched. Expected: " + waitingLock);
+        }
+
+        String waitingLockName = waitingLock.getClass().getName();
+        int hcode = System.identityHashCode(waitingLock);
+        if (!waitingLockName.equals(l.getClassName())) {
+            throw new RuntimeException("LockInfo : " + l +
+                " class name not matched. Expected: " + waitingLockName);
+        }
+        if (hcode != l.getIdentityHashCode()) {
+            throw new RuntimeException("LockInfo: " + l +
+                " IdentityHashCode not matched. Expected: " + hcode);
+        }
+
+        String lockName = info.getLockName();
+        String[] s = lockName.split("@");
+        if (!waitingLockName.equals(s[0])) {
+            throw new RuntimeException("LockName: " + lockName +
+                " class name not matched. Expected: " + waitingLockName);
+        }
+        int i = Integer.parseInt(s[1], 16);
+        if (hcode != i) {
+            throw new RuntimeException("LockName: " + lockName +
+                " IdentityHashCode not matched. Expected: " + hcode);
+        }
+    }
+
+    void checkStackFrame(ThreadInfo info, StackTraceElement ste, int depth) {
+        StackTraceElement[] stacktrace = info.getStackTrace();
+        if (!ste.equals(stacktrace[depth])) {
+            System.out.println("LockedStackFrame:- " + ste);
+            System.out.println("StackTrace at " + depth + " :-" +
+                stacktrace[depth]);
+            throw new RuntimeException("LockedStackFrame does not match " +
+                "stack frame in ThreadInfo.getStackTrace");
+        }
+    }
+    void checkMonitor(MonitorInfo m, String methodName) {
+        for (Map.Entry<String, Lock[]> e : ownedMonitors.entrySet()) {
+            if (methodName.equals(e.getKey())) {
+                for (Lock l : e.getValue()) {
+                    String className = l.getClass().getName();
+                    int hcode = System.identityHashCode(l);
+                    if (className.equals(m.getClassName()) &&
+                        hcode == m.getIdentityHashCode()) {
+                        // monitor matched the expected
+                        return;
+                    }
+                }
+            }
+        }
+        throw new RuntimeException("Monitor not expected" + m);
+    }
+    void checkMonitor(String methodName, Lock l, MonitorInfo[] monitors) {
+        String className = l.getClass().getName();
+        int hcode = System.identityHashCode(l);
+        for (MonitorInfo m : monitors) {
+            if (className.equals(m.getClassName()) &&
+                hcode == m.getIdentityHashCode() &&
+                methodName.equals(m.getLockedStackFrame().getMethodName())) {
+                return;
+            }
+        }
+        throw new RuntimeException("Monitor not found in the returned list" +
+            " Method: " + methodName + " Lock: " + l);
+
+    }
+
+    static class Thread1 extends LockingThread {
+        public Thread1() {
+            super("t1");
+            initExpectedResult();
+        }
+        public void run() {
+            A();
+        }
+        void A() {
+            synchronized(lock1) {
+                synchronized(lock2) {
+                    synchronized(lock3) {
+                        B();
+                    }
+                }
+            }
+        }
+        void B() {
+            synchronized(lock4) {
+                synchronized(lock5) {
+                    C();
+                }
+            }
+        }
+        void C() {
+            synchronized(lock6) {
+                D();
+            }
+        }
+        void D() {
+            synchronized(lock7) {
+                try {
+                    // signal to about to wait
+                    count--;
+                    lock7.wait();
+                } catch (InterruptedException e) {
+                    throw new RuntimeException(e);
+                }
+            }
+        }
+
+        Map<String, Lock[]> LOCKED_MONITORS;
+        Lock WAITING_LOCK = lock7;
+        int OWNED_MONITORS = 6;
+        void initExpectedResult() {
+            LOCKED_MONITORS = new HashMap<String, Lock[]>();
+            LOCKED_MONITORS.put("D", new Lock[0]); // no monitored locked
+            LOCKED_MONITORS.put("C", new Lock[] {lock6});
+            LOCKED_MONITORS.put("B", new Lock[] {lock5, lock4});
+            LOCKED_MONITORS.put("A", new Lock[] {lock3, lock2, lock1});
+            this.setExpectedResult(WAITING_LOCK, OWNED_MONITORS, LOCKED_MONITORS);
+        }
+
+    }
+
+    static class Thread2 extends LockingThread {
+        Map<String, Lock[]> LOCKED_MONITORS = new HashMap<String, Lock[]>();
+        Lock WAITING_LOCK = lock8;
+        int OWNED_MONITORS = 0;
+        public Thread2() {
+            super("t2");
+            this.setExpectedResult(WAITING_LOCK, OWNED_MONITORS, LOCKED_MONITORS);
+        }
+        public void run() {
+            synchronized(lock8) {
+                try {
+                    synchronized(lock7) {
+                        count--;
+                    }
+                    lock8.wait();
+                } catch (InterruptedException e) {
+                    throw new RuntimeException(e);
+                }
+            }
+        }
+    }
+
+}
diff --git a/jdk/test/java/lang/management/ThreadMXBean/Locks.java b/jdk/test/java/lang/management/ThreadMXBean/Locks.java
new file mode 100644
index 0000000..9819375
--- /dev/null
+++ b/jdk/test/java/lang/management/ThreadMXBean/Locks.java
@@ -0,0 +1,356 @@
+/*
+ * Copyright 2003-2006 Sun Microsystems, Inc.  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 Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
+ * CA 95054 USA or visit www.sun.com if you need additional information or
+ * have any questions.
+ */
+
+/*
+ * @test
+ * @bug     4530538
+ * @summary Basic unit test of ThreadInfo.getLockName()
+ *          and ThreadInfo.getLockOwnerName()
+ * @author  Mandy Chung
+ *
+ * @build ThreadExecutionSynchronizer
+ * @run main Locks
+ */
+
+import java.lang.management.*;
+
+public class Locks {
+    private static Object objA = new Object();
+    private static Object objB = new Object();
+    private static Object objC = new Object();
+    private static ThreadMXBean tm = ManagementFactory.getThreadMXBean();
+
+    private static boolean testFailed = false;
+
+    private static String getLockName(Object lock) {
+        if (lock == null) return null;
+
+        return lock.getClass().getName() + '@' +
+            Integer.toHexString(System.identityHashCode(lock));
+    }
+
+    private static void checkBlockedObject(Thread t, Object lock, Thread owner,
+                                           Thread.State expectedState) {
+        ThreadInfo info = tm.getThreadInfo(t.getId());
+        String result = info.getLockName();
+        String expectedLock = (lock != null ? getLockName(lock) : null);
+        String expectedOwner = (owner != null ? owner.getName() : null);
+
+        if (lock != null) {
+            if (expectedState ==Thread.State.BLOCKED) {
+                int retryCount=0;
+                while(info.getThreadState() != Thread.State.BLOCKED) {
+                    if (retryCount++ > 500) {
+                        throw new RuntimeException("Thread " + t.getName() +
+                                  " is expected to block on " + expectedLock +
+                                  " but got " + result +
+                                  " Thread.State = " + info.getThreadState());
+                    }
+                    goSleep(100);
+                }
+            }
+            if (expectedState == Thread.State.WAITING &&
+                info.getThreadState() != Thread.State.WAITING) {
+                throw new RuntimeException("Thread " + t.getName() +
+                    " is expected to wait on " + expectedLock +
+                    " but got " + result +
+                    " Thread.State = " + info.getThreadState());
+            }
+        }
+
+        if ((result != null && !result.equals(expectedLock)) ||
+            (result == null && expectedLock != null)) {
+            throw new RuntimeException("Thread " + t.getName() + " is blocked on " +
+                expectedLock + " but got " + result);
+        }
+        result = info.getLockOwnerName();
+        if ((result != null && !result.equals(expectedOwner)) ||
+            (result == null && expectedOwner != null)) {
+            throw new RuntimeException("Owner of " + lock + " should be " +
+                expectedOwner + " but got " + result);
+        }
+    }
+
+    private static void goSleep(long ms) {
+        try {
+            Thread.sleep(ms);
+        } catch (InterruptedException e) {
+            e.printStackTrace();
+            testFailed = true;
+        }
+    }
+
+    static ThreadExecutionSynchronizer thrsync = new ThreadExecutionSynchronizer();
+    static ThreadExecutionSynchronizer thrsync1 = new ThreadExecutionSynchronizer();
+
+    static class LockAThread extends Thread {
+        public LockAThread() {
+            super("LockAThread");
+        }
+        public void run() {
+            synchronized(objA) {
+               // stop here  for LockBThread to hold objB
+               thrsync.waitForSignal();
+
+               System.out.println("LockAThread about to block on objB");
+               synchronized(objB) {};
+            }
+            System.out.println("LockAThread about to exit");
+            // The state could be anything. The expected state value
+            // passed with this method is not verified.
+            checkBlockedObject(this, null, null, Thread.State.TERMINATED);
+        }
+    }
+
+    static class LockBThread extends Thread {
+        public LockBThread() {
+            super("LockBThread");
+        }
+        public void run() {
+            synchronized(objB) {
+               // signal waiting LockAThread.
+               thrsync.signal();
+
+               System.out.println("LockBThread about to block on objC");
+               // Signal main thread about to block on objC
+               thrsync1.signal();
+               synchronized(objC) {};
+            }
+            System.out.println("LockBThread about to exit");
+            // The state could be anything. The expected state value
+            // passed with this method is not verified.
+            checkBlockedObject(this, null, null, Thread.State.TERMINATED);
+        }
+
+        public void aboutToLockC() {
+            // Stop here till LockBThread about to blocked
+            // for lock objC.
+            thrsync1.waitForSignal();
+            goSleep(500);
+        }
+    }
+
+    private static WaitingThread waiter;
+    private static Object ready = new Object();
+    private static CheckerThread checker;
+    static class WaitingThread extends Thread {
+        public WaitingThread() {
+            super("WaitingThread");
+        }
+        public void run() {
+            synchronized(objC) {
+               System.out.println("WaitingThread about to wait on objC");
+               try {
+                   // Signal checker thread, about to wait on objC.
+                   thrsync.signal();
+                   objC.wait();
+               } catch (InterruptedException e) {
+                   e.printStackTrace();
+                   testFailed = true;
+               }
+
+               // block until CheckerThread finishes checking
+               System.out.println("WaitingThread about to block on ready");
+               // signal checker thread that it is about acquire
+               // object ready.
+               thrsync.signal();
+               synchronized(ready) {};
+            }
+            synchronized(objC) {
+                try {
+                    // signal checker thread, about to wait on objC
+                    thrsync.signal();
+                    objC.wait();
+                } catch (InterruptedException e) {
+                    e.printStackTrace();
+                    testFailed = true;
+                }
+            }
+            System.out.println("WaitingThread about to exit waiting on objC 2");
+        }
+    }
+    static class CheckerThread extends Thread {
+        public CheckerThread() {
+            super("CheckerThread");
+        }
+        public void run() {
+            synchronized (ready) {
+                // wait until WaitingThread about to wait for objC
+                thrsync.waitForSignal();
+                // give chance to enter wait.
+                goSleep(100);
+                checkBlockedObject(waiter, objC, null, Thread.State.WAITING);
+
+                synchronized (objC) {
+                    objC.notify();
+                }
+
+                // wait for waiter thread to about to enter
+                // synchronized object ready.
+                thrsync.waitForSignal();
+                // give chance for waiter thread to get blocked on
+                // object ready.
+                goSleep(50);
+                checkBlockedObject(waiter, ready, this, Thread.State.BLOCKED);
+            }
+
+            // wait for signal from waiting thread that it is about
+            // wait for objC.
+            thrsync.waitForSignal();
+            synchronized(objC) {
+                checkBlockedObject(waiter, objC, Thread.currentThread(), Thread.State.WAITING);
+                objC.notify();
+            }
+
+        }
+    }
+
+    public static void main(String args[]) throws Exception {
+        Thread mainThread = Thread.currentThread();
+
+        // Test uncontested case
+        LockAThread t1;
+        LockBThread t2;
+
+        synchronized(objC) {
+            // The state could be anything. The expected state value
+            // passed with this method is not verified.
+            checkBlockedObject(mainThread, null, null, Thread.State.RUNNABLE);
+
+            // Test deadlock case
+            // t1 holds lockA and attempts to lock B
+            // t2 holds lockB and attempts to lock C
+            t1 = new LockAThread();
+            t1.start();
+
+            t2 = new LockBThread();
+            t2.start();
+
+            t2.aboutToLockC();
+
+            checkBlockedObject(t1, objB, t2, Thread.State.BLOCKED);
+            checkBlockedObject(t2, objC, mainThread, Thread.State.BLOCKED);
+
+            long[] expectedThreads = new long[3];
+            expectedThreads[0] = t1.getId(); // blocked on lockB
+            expectedThreads[1] = t2.getId(); // owner of lockB blocking on lockC
+            expectedThreads[2] = mainThread.getId(); // owner of lockC
+            findThreadsBlockedOn(objB, expectedThreads);
+        }
+        goSleep(100);
+
+        // Test Object.wait() case
+        waiter = new WaitingThread();
+        waiter.start();
+
+        checker = new CheckerThread();
+        checker.start();
+
+        try {
+            waiter.join();
+            checker.join();
+        } catch (InterruptedException e) {
+            e.printStackTrace();
+            testFailed = true;
+        }
+
+        if (testFailed) {
+            throw new RuntimeException("TEST FAILED.");
+        }
+        System.out.println("Test passed.");
+    }
+
+    private static ThreadInfo findOwnerInfo(ThreadInfo[] infos, String lock)
+        throws Exception {
+        ThreadInfo ownerInfo = null;
+        for (int i = 0; i < infos.length; i++) {
+            String blockedLock = infos[i].getLockName();
+            if (lock.equals(blockedLock)) {
+                long threadId = infos[i].getLockOwnerId();
+                if (threadId == -1) {
+                    throw new RuntimeException("TEST FAILED: " +
+                        lock + " expected to have owner");
+                }
+                for (int j = 0; j < infos.length; j++) {
+                    if (infos[j].getThreadId() == threadId) {
+                        ownerInfo = infos[j];
+                        break;
+                    }
+                }
+            }
+        }
+        return ownerInfo;
+    }
+    private static void findThreadsBlockedOn(Object o, long[] expectedThreads)
+        throws Exception {
+        String lock = getLockName(o);
+        // Check with ThreadInfo with no stack trace (i.e. no safepoint)
+        ThreadInfo[] infos = tm.getThreadInfo(tm.getAllThreadIds());
+        doCheck(infos, lock, expectedThreads);
+
+        // Check with ThreadInfo with stack trace
+        infos = tm.getThreadInfo(tm.getAllThreadIds(), 1);
+        doCheck(infos, lock, expectedThreads);
+    }
+
+    private static void doCheck(ThreadInfo[] infos, String lock, long[] expectedThreads)
+        throws Exception {
+        ThreadInfo ownerInfo = null;
+        // Find the thread who is blocking on lock
+        for (int i = 0; i < infos.length;  i++) {
+            String blockedLock = infos[i].getLockName();
+            if (lock.equals(blockedLock)) {
+                System.out.print(infos[i].getThreadName() +
+                    " blocked on " + blockedLock);
+                ownerInfo = infos[i];
+            }
+        }
+
+        long[] threads = new long[10];
+        int count = 0;
+        threads[count++] = ownerInfo.getThreadId();
+        while (ownerInfo != null && ownerInfo.getThreadState() == Thread.State.BLOCKED) {
+            ownerInfo = findOwnerInfo(infos, lock);
+            threads[count++] = ownerInfo.getThreadId();
+            System.out.println(" Owner = " + ownerInfo.getThreadName() +
+                " id = " + ownerInfo.getThreadId());
+            lock = ownerInfo.getLockName();
+            System.out.print(ownerInfo.getThreadName() + " Id = " +
+                    ownerInfo.getThreadId() +
+                    " blocked on " + lock);
+        }
+        System.out.println();
+
+        if (count != expectedThreads.length) {
+            throw new RuntimeException("TEST FAILED: " +
+                "Expected chain of threads not matched; current count =" + count);
+        }
+        for (int i = 0; i < count; i++) {
+            if (threads[i] != expectedThreads[i]) {
+                System.out.println("TEST FAILED: " +
+                    "Unexpected thread in the chain " + threads[i] +
+                    " expected to be " + expectedThreads[i]);
+            }
+        }
+    }
+}
diff --git a/jdk/test/java/lang/management/ThreadMXBean/MonitorDeadlock.java b/jdk/test/java/lang/management/ThreadMXBean/MonitorDeadlock.java
new file mode 100644
index 0000000..ad5b822
--- /dev/null
+++ b/jdk/test/java/lang/management/ThreadMXBean/MonitorDeadlock.java
@@ -0,0 +1,155 @@
+/*
+ * Copyright 2005 Sun Microsystems, Inc.  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 Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
+ * CA 95054 USA or visit www.sun.com if you need additional information or
+ * have any questions.
+ */
+
+/*
+ * @summary MonitorDeadlock creates threads that are deadlocked on
+ *          object monitors.
+ * @author  Mandy Chung
+ * @build Barrier
+ */
+
+import java.lang.management.*;
+import java.util.*;
+
+public class MonitorDeadlock {
+
+    private final int EXPECTED_THREADS = 3;
+    private Barrier go = new Barrier(1);
+    private Barrier barr = new Barrier(EXPECTED_THREADS);
+
+    private Object a = new Object();
+    private Object b = new Object();
+    private Object c = new Object();
+    private Thread[] dThreads = new Thread[EXPECTED_THREADS];
+
+    public MonitorDeadlock() {
+        dThreads[0] = new DeadlockingThread("MThread-1", a, b);
+        dThreads[1] = new DeadlockingThread("MThread-2", b, c);
+        dThreads[2] = new DeadlockingThread("MThread-3", c, a);
+
+        // make them daemon threads so that the test will exit
+        for (int i = 0; i < EXPECTED_THREADS; i++) {
+            dThreads[i].setDaemon(true);
+            dThreads[i].start();
+        }
+    }
+
+    void goDeadlock() {
+        // Wait until all threads have started
+        barr.await();
+
+        // reset for later signals
+        barr.set(EXPECTED_THREADS);
+
+        while (go.getWaiterCount() != EXPECTED_THREADS) {
+            synchronized(this) {
+                try {
+                    wait(100);
+                } catch (InterruptedException e) {
+                    // ignore
+                }
+            }
+        }
+
+        // sleep a little so that all threads are blocked before notified.
+        try {
+            Thread.sleep(100);
+        } catch (InterruptedException e) {
+            // ignore
+        }
+        go.signal();
+
+    }
+
+    void waitUntilDeadlock() {
+        barr.await();
+        // sleep a little while to wait until threads are blocked.
+        try {
+            Thread.sleep(100);
+        } catch (InterruptedException e) {
+            // ignore
+        }
+    }
+
+    private class DeadlockingThread extends Thread {
+        private final Object lock1;
+        private final Object lock2;
+
+        DeadlockingThread(String name, Object lock1, Object lock2) {
+            super(name);
+            this.lock1 = lock1;
+            this.lock2 = lock2;
+        }
+        public void run() {
+            f();
+        }
+        private void f() {
+            synchronized (lock1) {
+                barr.signal();
+                go.await();
+                g();
+            }
+        }
+        private void g() {
+            barr.signal();
+            synchronized (lock2) {
+                throw new RuntimeException("should not reach here.");
+            }
+        }
+    }
+
+    void checkResult(long[] threads) {
+        if (threads.length != EXPECTED_THREADS) {
+            throw new RuntimeException("Expected to have " +
+                EXPECTED_THREADS + " to be in the deadlock list");
+        }
+        boolean[] found = new boolean[EXPECTED_THREADS];
+        for (int i = 0; i < threads.length; i++) {
+            for (int j = 0; j < dThreads.length; j++) {
+                if (dThreads[j].getId() == threads[i]) {
+                    found[j] = true;
+                }
+            }
+        }
+        boolean ok = true;
+        for (int j = 0; j < found.length; j++) {
+            ok = ok && found[j];
+        }
+
+        if (!ok) {
+            System.out.print("Returned result is [");
+            for (int j = 0; j < threads.length; j++) {
+                System.out.print(threads[j] + " ");
+            }
+            System.out.println("]");
+
+            System.out.print("Expected result is [");
+            for (int j = 0; j < threads.length; j++) {
+                System.out.print(dThreads[j] + " ");
+            }
+            System.out.println("]");
+            throw new RuntimeException("Unexpected result returned " +
+                " by findMonitorDeadlockedThreads method.");
+        }
+    }
+}
diff --git a/jdk/test/java/lang/management/ThreadMXBean/MyOwnSynchronizer.java b/jdk/test/java/lang/management/ThreadMXBean/MyOwnSynchronizer.java
new file mode 100644
index 0000000..bd10c43
--- /dev/null
+++ b/jdk/test/java/lang/management/ThreadMXBean/MyOwnSynchronizer.java
@@ -0,0 +1,195 @@
+/*
+ * Copyright 2005 Sun Microsystems, Inc.  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 Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
+ * CA 95054 USA or visit www.sun.com if you need additional information or
+ * have any questions.
+ */
+
+/*
+ * @test
+ * @bug     5086470 6358247
+ * @summary Basic Test for ThreadMXBean.dumpAllThreads(false, true)
+ *          and getThreadInfo of customized JSR-166 synchronizers.
+ * @author  Mandy Chung
+ *
+ * @build Barrier
+ * @build ThreadDump
+ * @run main MyOwnSynchronizer
+ */
+
+import java.lang.management.*;
+import java.util.*;
+import java.util.concurrent.locks.*;
+import java.util.concurrent.TimeUnit;
+import java.io.*;
+
+public class MyOwnSynchronizer {
+    static ThreadMXBean mbean = ManagementFactory.getThreadMXBean();
+    static Mutex mutex = new Mutex();
+    static MyThread thread = new MyThread();
+    public static void main(String[] argv) throws Exception {
+        if (!mbean.isSynchronizerUsageSupported()) {
+            System.out.println("Monitoring of synchronizer usage not supported");
+            return;
+        }
+
+        thread.setDaemon(true);
+        thread.start();
+
+        // wait until myThread acquires mutex
+        while (!mutex.isLocked()) {
+           try {
+               Thread.sleep(100);
+           } catch (InterruptedException e) {
+               throw new RuntimeException(e);
+           }
+        }
+
+        ThreadDump.threadDump();
+        // Test dumpAllThreads with locked synchronizers
+        ThreadInfo[] tinfos = mbean.dumpAllThreads(false, true);
+        for (ThreadInfo ti : tinfos) {
+           MonitorInfo[] monitors = ti.getLockedMonitors();
+           if (monitors.length != 0) {
+               throw new RuntimeException("Name: " + ti.getThreadName() +
+                   " has non-empty locked monitors = " + monitors.length);
+           }
+           LockInfo[] syncs = ti.getLockedSynchronizers();
+           if (ti.getThreadId() == thread.getId()) {
+               thread.checkLockedSyncs(ti, syncs);
+           }
+        }
+
+        // Test getThreadInfo with locked synchronizers
+        tinfos = mbean.getThreadInfo(new long[] {thread.getId()}, false, true);
+        if (tinfos.length != 1) {
+            throw new RuntimeException("getThreadInfo() returns " +
+                tinfos.length + " ThreadInfo objects. Expected 0.");
+        }
+        ThreadInfo ti = tinfos[0];
+        if (ti.getLockedMonitors().length != 0) {
+            throw new RuntimeException("Name: " + ti.getThreadName() +
+               " has non-empty locked monitors = " +
+               ti.getLockedMonitors().length);
+        }
+        thread.checkLockedSyncs(ti, ti.getLockedSynchronizers());
+
+        System.out.println("Test passed");
+    }
+
+    static class Mutex implements Lock, java.io.Serializable {
+
+        // Our internal helper class
+        class Sync extends AbstractQueuedSynchronizer {
+            // Report whether in locked state
+            protected boolean isHeldExclusively() {
+                return getState() == 1;
+            }
+
+            // Acquire the lock if state is zero
+            public boolean tryAcquire(int acquires) {
+                assert acquires == 1; // Otherwise unused
+                if (compareAndSetState(0, 1)) {
+                  setExclusiveOwnerThread(Thread.currentThread());
+                  return true;
+                }
+                return false;
+            }
+
+            // Release the lock by setting state to zero
+            protected boolean tryRelease(int releases) {
+                assert releases == 1; // Otherwise unused
+                if (getState() == 0) throw new IllegalMonitorStateException();
+                setExclusiveOwnerThread(null);
+                setState(0);
+                return true;
+            }
+
+            // Provide a Condition
+            Condition newCondition() { return new ConditionObject(); }
+
+            // Deserialize properly
+            private void readObject(ObjectInputStream s)
+                throws IOException, ClassNotFoundException {
+                s.defaultReadObject();
+                setState(0); // reset to unlocked state
+            }
+        }
+
+        // The sync object does all the hard work. We just forward to it.
+        private final Sync sync = new Sync();
+
+        public void lock()                { sync.acquire(1); }
+        public boolean tryLock()          { return sync.tryAcquire(1); }
+        public void unlock()              { sync.release(1); }
+        public Condition newCondition()   { return sync.newCondition(); }
+        public boolean isLocked()         { return sync.isHeldExclusively(); }
+        public boolean hasQueuedThreads() { return sync.hasQueuedThreads(); }
+        public void lockInterruptibly() throws InterruptedException {
+            sync.acquireInterruptibly(1);
+        }
+        public boolean tryLock(long timeout, TimeUnit unit) throws InterruptedException {
+            return sync.tryAcquireNanos(1, unit.toNanos(timeout));
+        }
+
+        public AbstractOwnableSynchronizer getSync() { return sync; }
+    }
+
+    static class MyThread extends Thread {
+        public MyThread() {
+            super("MyThread");
+        }
+        public void run() {
+            mutex.lock();
+            Object o = new Object();
+            synchronized(o) {
+                try {
+                    o.wait();
+                } catch (InterruptedException e) {
+                    throw new RuntimeException(e);
+                }
+            }
+        }
+        int OWNED_SYNCS = 1;
+        void checkLockedSyncs(ThreadInfo info, LockInfo[] syncs) {
+            if (!getName().equals(info.getThreadName())) {
+                throw new RuntimeException("Name: " + info.getThreadName() +
+                    " not matched. Expected: " + getName());
+            }
+
+            if (syncs.length != OWNED_SYNCS) {
+                throw new RuntimeException("Number of locked syncs = " +
+                    syncs.length +
+                    " not matched. Expected: " + OWNED_SYNCS);
+            }
+            AbstractOwnableSynchronizer s = mutex.getSync();
+            String lockName = s.getClass().getName();
+            int hcode = System.identityHashCode(s);
+            if (!lockName.equals(syncs[0].getClassName())) {
+                throw new RuntimeException("LockInfo : " + syncs[0] +
+                    " class name not matched. Expected: " + lockName);
+            }
+            if (hcode != syncs[0].getIdentityHashCode()) {
+                throw new RuntimeException("LockInfo: " + syncs[0] +
+                    " IdentityHashCode not matched. Expected: " + hcode);
+            }
+
+        }
+    }
+}
diff --git a/jdk/test/java/lang/management/ThreadMXBean/ResetPeakThreadCount.java b/jdk/test/java/lang/management/ThreadMXBean/ResetPeakThreadCount.java
new file mode 100644
index 0000000..9bbd13b
--- /dev/null
+++ b/jdk/test/java/lang/management/ThreadMXBean/ResetPeakThreadCount.java
@@ -0,0 +1,259 @@
+/*
+ * Copyright 2003-2006 Sun Microsystems, Inc.  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 Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
+ * CA 95054 USA or visit www.sun.com if you need additional information or
+ * have any questions.
+ */
+
+/*
+ * @test
+ * @bug     4892507
+ * @summary Basic Test for the following reset methods:
+ *          - ThreadMXBean.resetPeakThreadCount()
+ * @author  Mandy Chung
+ *
+ * @build ResetPeakThreadCount
+ * @build ThreadDump
+ * @run main/othervm ResetPeakThreadCount
+ */
+
+import java.lang.management.*;
+
+public class ResetPeakThreadCount {
+    // initial number of new threads started
+    private static final int DAEMON_THREADS_1 = 8;
+    private static final int EXPECTED_PEAK_DELTA_1 = 8;
+
+    // Terminate half of the threads started
+    private static final int TERMINATE_1 = 4;
+
+    // start new threads but expected the peak unchanged
+    private static final int DAEMON_THREADS_2 = 2;
+    private static final int EXPECTED_PEAK_DELTA_2 = 0;
+
+    // peak thread count reset before starting new threads
+    private static final int DAEMON_THREADS_3 = 4;
+    private static final int EXPECTED_PEAK_DELTA_3 = 4;
+
+    private static final int TERMINATE_2 = 8;
+
+    private static final int ALL_THREADS = DAEMON_THREADS_1 +
+        DAEMON_THREADS_2 + DAEMON_THREADS_3;
+    // barrier for threads communication
+    private static Barrier barrier = new Barrier(DAEMON_THREADS_1);
+
+    private static Thread allThreads[] = new Thread[ALL_THREADS];
+    private static volatile boolean live[] = new boolean[ALL_THREADS];
+    private static final ThreadMXBean mbean = ManagementFactory.getThreadMXBean();
+    private static boolean testFailed = false;
+
+    public static void main(String[] argv) throws Exception {
+        // This test does not expect any threads to be created
+        // by the test harness after main() is invoked.
+        // The checkThreadCount() method is to produce more
+        // diagnostic information in case any unexpected test failure occur.
+        long previous = mbean.getThreadCount();
+        long current;
+
+        // start DAEMON_THREADS_1 number of threads
+        current = startThreads(0, DAEMON_THREADS_1, EXPECTED_PEAK_DELTA_1);
+
+        checkThreadCount(previous, current, DAEMON_THREADS_1);
+        previous = current;
+
+        // terminate TERMINATE_1 number of threads and reset peak
+        current = terminateThreads(0, TERMINATE_1);
+
+        checkThreadCount(previous, current, TERMINATE_1 * -1);
+
+        previous = current;
+
+        // start DAEMON_THREADS_2 number of threads
+        // expected peak is unchanged
+        current = startThreads(DAEMON_THREADS_1, DAEMON_THREADS_2,
+                               EXPECTED_PEAK_DELTA_2);
+
+        checkThreadCount(previous, current, DAEMON_THREADS_2);
+        previous = current;
+
+        // Reset the peak
+        resetPeak(current);
+
+        // start DAEMON_THREADS_3 number of threads
+        current = startThreads(DAEMON_THREADS_1 + DAEMON_THREADS_2,
+                               DAEMON_THREADS_3, EXPECTED_PEAK_DELTA_3);
+
+        checkThreadCount(previous, current, DAEMON_THREADS_3);
+        previous = current;
+
+        // terminate TERMINATE_2 number of threads and reset peak
+        current = terminateThreads(TERMINATE_1, TERMINATE_2);
+
+        checkThreadCount(previous, current, TERMINATE_2 * -1);
+        resetPeak(current);
+
+        if (testFailed)
+            throw new RuntimeException("TEST FAILED.");
+
+        System.out.println("Test passed");
+    }
+
+    private static long startThreads(int from, int count, int delta) {
+        // get current peak thread count
+        long peak1 = mbean.getPeakThreadCount();
+        long current = mbean.getThreadCount();
+
+        // Start threads and wait to be sure they all are alive
+        System.out.println("Starting " + count + " threads....");
+        barrier.set(count);
+        for (int i = from; i < (from + count); i++) {
+            live[i] = true;
+            allThreads[i] = new MyThread(i);
+            allThreads[i].setDaemon(true);
+            allThreads[i].start();
+        }
+        // wait until all threads have started.
+        barrier.await();
+
+        // get peak thread count after daemon threads have started
+        long peak2 = mbean.getPeakThreadCount();
+
+        System.out.println("   Current = " + mbean.getThreadCount() +
+            " Peak before = " + peak1 + " after: " + peak2);
+
+        if (peak2 != (peak1 + delta)) {
+            throw new RuntimeException("Current Peak = " + peak2 +
+                " Expected to be == previous peak = " + peak1 + " + " +
+                delta);
+        }
+        // wait until the current thread count gets incremented
+        while (mbean.getThreadCount() < (current + count)) {
+            try {
+                Thread.sleep(100);
+            } catch (InterruptedException e) {
+                e.printStackTrace();
+                System.out.println("Unexpected exception.");
+                testFailed = true;
+            }
+        }
+        current = mbean.getThreadCount();
+        System.out.println("   Live thread count before returns " + current);
+        return current;
+    }
+
+    private static long terminateThreads(int from, int count) {
+        // get current peak thread count
+        long peak1 = mbean.getPeakThreadCount();
+        long current = mbean.getThreadCount();
+
+        // Stop daemon threads and wait to be sure they all are dead
+        System.out.println("Terminating " + count + " threads....");
+        barrier.set(count);
+        for (int i = from; i < (from+count); i++) {
+            live[i] = false;
+        }
+        // wait until daemon threads terminated.
+        barrier.await();
+
+        // get peak thread count after daemon threads have terminated
+        long peak2 = mbean.getPeakThreadCount();
+        // assuming no system thread is added
+        if (peak2 != peak1) {
+            throw new RuntimeException("Current Peak = " + peak2 +
+                " Expected to be = previous peak = " + peak1);
+        }
+
+        // wait until the current thread count gets decremented
+        while (mbean.getThreadCount() > (current - count)) {
+            try {
+                Thread.sleep(100);
+            } catch (InterruptedException e) {
+                e.printStackTrace();
+                System.out.println("Unexpected exception.");
+                testFailed = true;
+            }
+        }
+
+        current = mbean.getThreadCount();
+        System.out.println("   Live thread count before returns " + current);
+        return current;
+    }
+
+    private static void resetPeak(long expectedCount) {
+        long peak3 = mbean.getPeakThreadCount();
+        long current = mbean.getThreadCount();
+
+        // Nightly testing showed some intermittent failure.
+        // Check here to get diagnostic information if some strange
+        // behavior occurs.
+        checkThreadCount(expectedCount, current, 0);
+
+        // Reset peak thread count
+        mbean.resetPeakThreadCount();
+
+        long afterResetPeak = mbean.getPeakThreadCount();
+        long afterResetCurrent = mbean.getThreadCount();
+        System.out.println("Reset peak before = " + peak3 +
+            " current = " + current +
+            " after reset peak = " + afterResetPeak +
+            " current = " + afterResetCurrent);
+
+        if (afterResetPeak != current) {
+            throw new RuntimeException("Current Peak after reset = " +
+                afterResetPeak +
+                " Expected to be = current count = " + current);
+        }
+    }
+
+    private static void checkThreadCount(long previous, long current, int expectedDelta) {
+        if (current != previous + expectedDelta) {
+            System.out.println("***** Unexpected thread count:" +
+                               " previous = " + previous +
+                               " current = " + current +
+                               " delta = " + expectedDelta + "*****");
+            ThreadDump.threadDump();
+        }
+    }
+
+    // The MyThread thread lives as long as correspondent live[i] value is true
+    private static class MyThread extends Thread {
+        int id;
+
+        MyThread(int id) {
+            this.id = id;
+        }
+
+        public void run() {
+            // signal started
+            barrier.signal();
+            while (live[id]) {
+                try {
+                    sleep(100);
+                } catch (InterruptedException e) {
+                    System.out.println("Unexpected exception is thrown.");
+                    e.printStackTrace(System.out);
+                    testFailed = true;
+                }
+            }
+            // signal about to exit
+            barrier.signal();
+        }
+    }
+
+}
diff --git a/jdk/test/java/lang/management/ThreadMXBean/Semaphore.java b/jdk/test/java/lang/management/ThreadMXBean/Semaphore.java
new file mode 100644
index 0000000..809191c
--- /dev/null
+++ b/jdk/test/java/lang/management/ThreadMXBean/Semaphore.java
@@ -0,0 +1,74 @@
+/*
+ * Copyright 2003 Sun Microsystems, Inc.  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 Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
+ * CA 95054 USA or visit www.sun.com if you need additional information or
+ * have any questions.
+ */
+
+/*
+ * @bug     4530538
+ * @summary A semaphore utility class.
+ * @author  Mandy Chung
+ */
+
+public class Semaphore {
+    private Object go = new Object();
+    private int semaCount;
+    private int waiters = 0;
+
+    public Semaphore() {
+        semaCount = 0;
+    }
+
+    public Semaphore(int initialCount) {
+        semaCount = initialCount;
+    }
+
+    public void semaP() {
+        synchronized (go) {
+            waiters++;
+            while (semaCount == 0) {
+                try {
+                    go.wait();
+                } catch (InterruptedException e) {
+                    e.printStackTrace();
+                    throw new InternalError();
+                }
+            }
+            semaCount--;
+            waiters--;
+        }
+    }
+    public void semaV() {
+        synchronized (go) {
+            semaCount++;
+            go.notify();
+        }
+    }
+
+    public int getWaiterCount() {
+        synchronized (go) {
+            return waiters;
+        }
+    }
+
+    public Object getLock() {
+        return go;
+    }
+}
diff --git a/jdk/test/java/lang/management/ThreadMXBean/SharedSynchronizer.java b/jdk/test/java/lang/management/ThreadMXBean/SharedSynchronizer.java
new file mode 100644
index 0000000..c603d27
--- /dev/null
+++ b/jdk/test/java/lang/management/ThreadMXBean/SharedSynchronizer.java
@@ -0,0 +1,81 @@
+/*
+ * Copyright 2005 Sun Microsystems, Inc.  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 Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
+ * CA 95054 USA or visit www.sun.com if you need additional information or
+ * have any questions.
+ */
+
+/*
+ * @test
+ * @bug     6337571
+ * @summary Test if findDeadlockedThreads works for an ownable synchronizer
+ *          in shared mode which has no owner when a thread is parked.
+ * @author  Mandy Chung
+ *
+ * @run main SharedSynchronizer
+ */
+
+
+import java.util.concurrent.*;
+import java.lang.management.ManagementFactory;
+import java.lang.management.ThreadMXBean;
+
+public class SharedSynchronizer {
+    public static void main(String[] args) throws Exception {
+        MyThread t = new MyThread();
+        t.setDaemon(true);
+        t.start();
+
+        ThreadMXBean tmbean = ManagementFactory.getThreadMXBean();
+        if (!tmbean.isSynchronizerUsageSupported()) {
+            System.out.println("Monitoring of synchronizer usage not supported")
+;
+            return;
+        }
+
+        long[] result = tmbean.findDeadlockedThreads();
+        if (result != null) {
+             throw new RuntimeException("TEST FAILED: result should be null");
+        }
+    }
+
+    static class MyThread extends Thread {
+        public void run() {
+            FutureTask f = new FutureTask(
+                new Callable() {
+                    public Object call() {
+                        throw new RuntimeException("should never reach here");
+                    }
+                }
+            );
+
+            // A FutureTask uses the AbstractOwnableSynchronizer in a shared
+            // mode (not exclusive mode). When the thread calls f.get(),
+            // it will put to park on the ownable synchronizer that
+            // is not owned by any thread.
+            try {
+                f.get();
+            } catch (Exception e) {
+                RuntimeException re = new RuntimeException(e.getMessage());
+                re.initCause(e);
+                throw re;
+            }
+        }
+    }
+}
diff --git a/jdk/test/java/lang/management/ThreadMXBean/SynchronizationStatistics.java b/jdk/test/java/lang/management/ThreadMXBean/SynchronizationStatistics.java
new file mode 100644
index 0000000..d8a9b7d
--- /dev/null
+++ b/jdk/test/java/lang/management/ThreadMXBean/SynchronizationStatistics.java
@@ -0,0 +1,531 @@
+/*
+ * Copyright 2003-2005 Sun Microsystems, Inc.  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 Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
+ * CA 95054 USA or visit www.sun.com if you need additional information or
+ * have any questions.
+ */
+
+/*
+ * @test
+ * @bug     4530538
+ * @summary Basic unit test of the synchronization statistics support:
+ *
+ * @author  Mandy Chung
+ *
+ * @ignore  6309226
+ * @build Semaphore
+ * @run main SynchronizationStatistics
+ */
+
+import java.lang.management.*;
+
+public class SynchronizationStatistics {
+    private static ThreadMXBean mbean = ManagementFactory.getThreadMXBean();
+
+    private static boolean blockedTimeCheck =
+        mbean.isThreadContentionMonitoringSupported();
+    private static boolean trace = false;
+
+    private static Object lockA = new Object();
+    private static Object lockB = new Object();
+    private static Object lockC = new Object();
+    private static Object lockD = new Object();
+    private static Object waiter = new Object();
+    private static volatile boolean testFailed = false;
+
+    private static Object go = new Object();
+
+    private static void goSleep(long ms) {
+        try {
+            Thread.sleep(ms);
+        } catch (InterruptedException e) {
+            e.printStackTrace();
+            System.out.println("Unexpected exception.");
+            testFailed = true;
+        }
+    }
+
+    public static void main(String args[]) throws Exception {
+        if (args.length > 0 && args[0].equals("trace")) {
+            trace = true;
+        }
+
+        if (blockedTimeCheck) {
+            mbean.setThreadContentionMonitoringEnabled(true);
+        }
+
+        if (!mbean.isThreadContentionMonitoringEnabled()) {
+            throw new RuntimeException("TEST FAILED: " +
+                "Thread Contention Monitoring is not enabled");
+        }
+
+        Examiner examiner = new Examiner("Examiner");
+        BlockedThread blocked = new BlockedThread("BlockedThread");
+        examiner.setThread(blocked);
+
+        // Start the threads and check them in  Blocked and Waiting states
+        examiner.start();
+
+        // wait until the examiner acquires all the locks and waiting
+        // for the BlockedThread to start
+        examiner.waitUntilWaiting();
+
+        System.out.println("Checking the thread state for the examiner thread " +
+                           "is waiting to begin.");
+
+        // The Examiner should be waiting to be notified by the BlockedThread
+        checkThreadState(examiner, Thread.State.WAITING);
+
+        System.out.println("Now starting the blocked thread");
+        blocked.start();
+
+        try {
+            examiner.join();
+            blocked.join();
+        } catch (InterruptedException e) {
+            e.printStackTrace();
+            System.out.println("Unexpected exception.");
+            testFailed = true;
+        }
+
+        if (testFailed)
+            throw new RuntimeException("TEST FAILED.");
+
+        System.out.println("Test passed.");
+    }
+
+    private static String INDENT = "    ";
+    private static void printStack(Thread t, StackTraceElement[] stack) {
+        System.out.println(INDENT +  t +
+                           " stack: (length = " + stack.length + ")");
+        if (t != null) {
+            for (int j = 0; j < stack.length; j++) {
+                System.out.println(INDENT + stack[j]);
+            }
+            System.out.println();
+        }
+    }
+
+    private static void checkThreadState(Thread thread, Thread.State s)
+        throws Exception {
+
+        ThreadInfo ti = mbean.getThreadInfo(thread.getId());
+        if (ti.getThreadState() != s) {
+            ThreadInfo info = mbean.getThreadInfo(thread.getId(),
+                                                  Integer.MAX_VALUE);
+            System.out.println(INDENT + "TEST FAILED:");
+            printStack(thread, info.getStackTrace());
+            System.out.println(INDENT + "Thread state: " + info.getThreadState());
+
+            throw new RuntimeException("TEST FAILED: " +
+                "Thread state for " + thread + " returns " + ti.getThreadState() +
+                ".  Expected to be " + s);
+        }
+    }
+
+    private static void checkThreadState(Thread thread,
+                                         Thread.State s1, Thread.State s2)
+        throws Exception {
+
+        ThreadInfo ti = mbean.getThreadInfo(thread.getId());
+        if (ti.getThreadState() != s1 && ti.getThreadState() != s2) {
+            throw new RuntimeException("TEST FAILED: " +
+                "Thread state for " + thread + " returns " + ti.getThreadState() +
+                ".  Expected to be " + s1 + " or " + s2);
+        }
+    }
+
+    static class StatThread extends Thread {
+        private long blockingBaseTime = 0;
+        private long totalWaitTime = 0;
+        private long totalBlockedEnterTime = 0;
+
+        StatThread(String name) {
+            super(name);
+        }
+
+        void addWaitTime(long ns) {
+            totalWaitTime = totalWaitTime + ns;
+        }
+        void addBlockedEnterTime(long ns) {
+            totalBlockedEnterTime = totalBlockedEnterTime + ns;
+        }
+        void setBlockingBaseTime(long time) {
+            blockingBaseTime = time;
+        }
+
+        long totalBlockedTimeMs() {
+            return totalBlockedEnterTime / 1000000;
+        }
+
+        long totalBlockedTimeMs(long now) {
+            long t = totalBlockedEnterTime + (now - blockingBaseTime);
+            return t / 1000000;
+        }
+
+        long totalWaitTimeMs() {
+            return totalWaitTime / 1000000;
+        }
+
+        long totalWaitTimeMs(long now) {
+            long t = totalWaitTime + (now - blockingBaseTime);
+            return t / 1000000;
+        }
+    }
+
+    static class BlockedThread extends StatThread {
+        private Semaphore handshake = new Semaphore();
+        BlockedThread(String name) {
+            super(name);
+        }
+        void waitUntilBlocked() {
+            handshake.semaP();
+
+            // give a chance for the examiner thread to really wait
+            goSleep(20);
+        }
+
+        void waitUntilWaiting() {
+            waitUntilBlocked();
+        }
+
+        boolean hasWaitersForBlocked() {
+            return (handshake.getWaiterCount() > 0);
+        }
+
+        private void notifyWaiter() {
+            // wait until the examiner waits on the semaphore
+            while (handshake.getWaiterCount() == 0) {
+                goSleep(20);
+            }
+            handshake.semaV();
+        }
+
+        private void waitObj(long ms) {
+            synchronized (waiter) {
+                try {
+                    // notify examinerabout to wait on a monitor
+                    notifyWaiter();
+
+                    long base = System.nanoTime();
+                    setBlockingBaseTime(base);
+                    waiter.wait(ms);
+                    long now = System.nanoTime();
+                    addWaitTime(now - base);
+                } catch (Exception e) {
+                    e.printStackTrace();
+                    System.out.println("Unexpected exception.");
+                    testFailed = true;
+                }
+            }
+        }
+
+        private void test() {
+            // notify examiner about to block on lockA
+            notifyWaiter();
+
+            long base = System.nanoTime();
+            setBlockingBaseTime(base);
+            synchronized (lockA) {
+                long now = System.nanoTime();
+                addBlockedEnterTime(now - base);
+
+                A(); // Expected blocked count = 1
+            }
+            E();
+        }
+        private void A() {
+            // notify examiner about to block on lockB
+            notifyWaiter();
+
+            long base = System.nanoTime();
+            setBlockingBaseTime(base);
+            synchronized (lockB) {
+                long now = System.nanoTime();
+                addBlockedEnterTime(now - base);
+
+                B(); // Expected blocked count = 2
+            }
+        }
+        private void B() {
+            // notify examiner about to block on lockC
+            notifyWaiter();
+
+            long base = System.nanoTime();
+            setBlockingBaseTime(base);
+            synchronized (lockC) {
+                long now = System.nanoTime();
+                addBlockedEnterTime(now - base);
+
+                C();  // Expected blocked count = 3
+            }
+        }
+        private void C() {
+            // notify examiner about to block on lockD
+            notifyWaiter();
+
+            long base = System.nanoTime();
+            setBlockingBaseTime(base);
+            synchronized (lockD) {
+                long now = System.nanoTime();
+                addBlockedEnterTime(now - base);
+
+                D();  // Expected blocked count = 4
+            }
+        }
+        private void D() {
+            goSleep(50);
+        }
+        private void E() {
+            final int WAIT = 1000;
+            waitObj(WAIT);
+            waitObj(WAIT);
+            waitObj(WAIT);
+        }
+
+        public void run() {
+            test();
+        } // run()
+    } // BlockedThread
+
+    static int blockedCount = 0;
+    static int waitedCount = 0;
+    static class Examiner extends StatThread {
+        private BlockedThread blockedThread;
+        private Semaphore semaphore = new Semaphore();
+
+        Examiner(String name) {
+            super(name);
+        }
+
+        public void setThread(BlockedThread thread) {
+            blockedThread = thread;
+        }
+
+        private void blockedTimeRangeCheck(StatThread t,
+                                           long blockedTime,
+                                           long nowNano)
+            throws Exception {
+            long expected = t.totalBlockedTimeMs(nowNano);
+
+            // accept 5% range
+            timeRangeCheck(blockedTime, expected, 5);
+        }
+        private void waitedTimeRangeCheck(StatThread t,
+                                          long waitedTime,
+                                          long nowNano)
+            throws Exception {
+            long expected = t.totalWaitTimeMs(nowNano);
+
+            // accept 5% range
+            timeRangeCheck(waitedTime, expected, 5);
+        }
+
+        private void timeRangeCheck(long time, long expected, int percent)
+            throws Exception {
+
+            double diff = expected - time;
+
+            if (trace) {
+                 System.out.println("  Time = " + time +
+                    " expected = " + expected +
+                    ".  Diff = " + diff);
+
+            }
+            // throw an exception if blockedTime and expectedTime
+            // differs > percent%
+            if (diff < 0) {
+                diff = diff * -1;
+            }
+
+            long range = (expected * percent) / 100;
+            // minimum range = 2 ms
+            if (range < 2) {
+                range = 2;
+            }
+            if (diff > range) {
+                throw new RuntimeException("TEST FAILED: " +
+                    "Time returned = " + time +
+                    " expected = " + expected + ".  Diff = " + diff);
+            }
+        }
+        private void checkInfo(StatThread t, Thread.State s, Object lock,
+                               String lockName, int bcount, int wcount)
+            throws Exception {
+
+            String action = "ERROR";
+            if (s == Thread.State.WAITING || s == Thread.State.TIMED_WAITING) {
+                action = "wait on ";
+            } else if (s == Thread.State.BLOCKED) {
+                action = "block on ";
+            }
+            System.out.println(t + " expected to " + action + lockName +
+                " with blocked count = " + bcount +
+                " and waited count = " + wcount);
+
+            long now = System.nanoTime();
+            ThreadInfo info = mbean.getThreadInfo(t.getId());
+            if (info.getThreadState() != s) {
+                printStack(t, info.getStackTrace());
+                throw new RuntimeException("TEST FAILED: " +
+                    "Thread state returned is " + info.getThreadState() +
+                    ". Expected to be " + s);
+            }
+
+            if (info.getLockName() == null ||
+                !info.getLockName().equals(lock.toString())) {
+                throw new RuntimeException("TEST FAILED: " +
+                    "getLockName() returned " + info.getLockName() +
+                    ". Expected to be " + lockName + " - "  + lock.toString());
+            }
+
+            if (info.getBlockedCount() != bcount) {
+                throw new RuntimeException("TEST FAILED: " +
+                    "Blocked Count returned is " + info.getBlockedCount() +
+                    ". Expected to be " + bcount);
+            }
+            if (info.getWaitedCount() != wcount) {
+                throw new RuntimeException("TEST FAILED: " +
+                    "Waited Count returned is " + info.getWaitedCount() +
+                    ". Expected to be " + wcount);
+            }
+
+            String lockObj = info.getLockName();
+            if (lockObj == null || !lockObj.equals(lock.toString())) {
+                throw new RuntimeException("TEST FAILED: " +
+                    "Object blocked on is " + lockObj  +
+                    ". Expected to be " + lock.toString());
+            }
+
+            if (!blockedTimeCheck) {
+                return;
+            }
+            long blockedTime = info.getBlockedTime();
+            if (blockedTime < 0) {
+                throw new RuntimeException("TEST FAILED: " +
+                    "Blocked time returned is negative = " + blockedTime);
+            }
+
+            if (s == Thread.State.BLOCKED) {
+                blockedTimeRangeCheck(t, blockedTime, now);
+            } else {
+                timeRangeCheck(blockedTime, t.totalBlockedTimeMs(), 5);
+            }
+
+            long waitedTime = info.getWaitedTime();
+            if (waitedTime < 0) {
+                throw new RuntimeException("TEST FAILED: " +
+                    "Waited time returned is negative = " + waitedTime);
+            }
+            if (s == Thread.State.WAITING || s == Thread.State.TIMED_WAITING) {
+                waitedTimeRangeCheck(t, waitedTime, now);
+            } else {
+                timeRangeCheck(waitedTime, t.totalWaitTimeMs(), 5);
+            }
+
+        }
+
+        private void examine() {
+            try {
+                synchronized (lockD) {
+                    synchronized (lockC) {
+                        synchronized (lockB) {
+                            synchronized (lockA) {
+                                // notify main thread to continue
+                                semaphore.semaV();
+
+                                // wait until BlockedThread has started
+                                blockedThread.waitUntilBlocked();
+
+                                blockedCount++;
+                                checkInfo(blockedThread, Thread.State.BLOCKED,
+                                          lockA, "lockA",
+                                          blockedCount, waitedCount);
+                            }
+
+                           // wait until BlockedThread to block on lockB
+                            blockedThread.waitUntilBlocked();
+
+                            blockedCount++;
+                            checkInfo(blockedThread, Thread.State.BLOCKED,
+                                      lockB, "lockB",
+                                      blockedCount, waitedCount);
+                        }
+
+                        // wait until BlockedThread to block on lockC
+                        blockedThread.waitUntilBlocked();
+
+                        blockedCount++;
+                        checkInfo(blockedThread, Thread.State.BLOCKED,
+                                  lockC, "lockC",
+                                  blockedCount, waitedCount);
+                    }
+                    // wait until BlockedThread to block on lockD
+                    blockedThread.waitUntilBlocked();
+                    blockedCount++;
+
+                    checkInfo(blockedThread, Thread.State.BLOCKED,
+                              lockD, "lockD",
+                              blockedCount, waitedCount);
+                }
+
+                // wait until BlockedThread about to call E()
+                // BlockedThread will wait on waiter for 3 times
+                blockedThread.waitUntilWaiting();
+
+                waitedCount++;
+                checkInfo(blockedThread, Thread.State.TIMED_WAITING,
+                          waiter, "waiter", blockedCount, waitedCount);
+
+                blockedThread.waitUntilWaiting();
+
+                waitedCount++;
+                checkInfo(blockedThread, Thread.State.TIMED_WAITING,
+                          waiter, "waiter", blockedCount, waitedCount);
+
+                blockedThread.waitUntilWaiting();
+
+                waitedCount++;
+                checkInfo(blockedThread, Thread.State.TIMED_WAITING,
+                          waiter, "waiter", blockedCount, waitedCount);
+
+            } catch (Exception e) {
+                e.printStackTrace();
+                System.out.println("Unexpected exception.");
+                testFailed = true;
+            }
+        }
+
+        public void run() {
+            examine();
+        } // run()
+
+        public void waitUntilWaiting() {
+            semaphore.semaP();
+
+            // wait until the examiner is waiting for
+            while (!blockedThread.hasWaitersForBlocked()) {
+                goSleep(50);
+            }
+            // give a chance for the examiner thread to really wait
+            goSleep(20);
+
+        }
+    } // Examiner
+}
diff --git a/jdk/test/java/lang/management/ThreadMXBean/SynchronizerDeadlock.java b/jdk/test/java/lang/management/ThreadMXBean/SynchronizerDeadlock.java
new file mode 100644
index 0000000..2a1441c
--- /dev/null
+++ b/jdk/test/java/lang/management/ThreadMXBean/SynchronizerDeadlock.java
@@ -0,0 +1,158 @@
+/*
+ * Copyright 2005 Sun Microsystems, Inc.  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 Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
+ * CA 95054 USA or visit www.sun.com if you need additional information or
+ * have any questions.
+ */
+
+/*
+ * @summary SynchronizerDeadlock creates threads that are deadlocked
+ *          waiting for JSR-166 synchronizers.
+ * @author  Mandy Chung
+ * @build Barrier
+ */
+
+import java.lang.management.*;
+import java.util.*;
+import java.util.concurrent.locks.*;
+
+public class SynchronizerDeadlock {
+
+    private Lock a = new ReentrantLock();
+    private Lock b = new ReentrantLock();
+    private Lock c = new ReentrantLock();
+    private final int EXPECTED_THREADS = 3;
+    private Thread[] dThreads = new Thread[EXPECTED_THREADS];
+    private Barrier go = new Barrier(1);
+    private Barrier barr = new Barrier(EXPECTED_THREADS);
+
+    public SynchronizerDeadlock() {
+        dThreads[0] = new DeadlockingThread("Deadlock-Thread-1", a, b);
+        dThreads[1] = new DeadlockingThread("Deadlock-Thread-2", b, c);
+        dThreads[2] = new DeadlockingThread("Deadlock-Thread-3", c, a);
+
+        // make them daemon threads so that the test will exit
+        for (int i = 0; i < EXPECTED_THREADS; i++) {
+            dThreads[i].setDaemon(true);
+            dThreads[i].start();
+        }
+    }
+
+    void goDeadlock() {
+        // Wait until all threads have started
+        barr.await();
+
+        // reset for later signals
+        barr.set(EXPECTED_THREADS);
+
+        while (go.getWaiterCount() != EXPECTED_THREADS) {
+            synchronized(this) {
+                try {
+                    wait(100);
+                } catch (InterruptedException e) {
+                    // ignore
+                }
+            }
+        }
+
+        // sleep a little so that all threads are blocked before notified.
+        try {
+            Thread.sleep(100);
+        } catch (InterruptedException e) {
+            // ignore
+        }
+        go.signal();
+
+    }
+
+    void waitUntilDeadlock() {
+        barr.await();
+        // sleep a little while to wait until threads are blocked.
+        try {
+            Thread.sleep(100);
+        } catch (InterruptedException e) {
+            // ignore
+        }
+    }
+
+    private class DeadlockingThread extends Thread {
+        private final Lock lock1;
+        private final Lock lock2;
+
+        DeadlockingThread(String name, Lock lock1, Lock lock2) {
+            super(name);
+            this.lock1 = lock1;
+            this.lock2 = lock2;
+        }
+        public void run() {
+            f();
+        }
+        private void f() {
+            lock1.lock();
+            try {
+                barr.signal();
+                go.await();
+                g();
+            } finally {
+                lock1.unlock();
+            }
+        }
+        private void g() {
+            barr.signal();
+            lock2.lock();
+            throw new RuntimeException("should not reach here.");
+        }
+    }
+
+    void checkResult(long[] threads) {
+        if (threads.length != EXPECTED_THREADS) {
+            ThreadDump.threadDump();
+            throw new RuntimeException("Expected to have " +
+                EXPECTED_THREADS + " to be in the deadlock list");
+        }
+        boolean[] found = new boolean[EXPECTED_THREADS];
+        for (int i = 0; i < threads.length; i++) {
+            for (int j = 0; j < dThreads.length; j++) {
+                if (dThreads[j].getId() == threads[i]) {
+                    found[j] = true;
+                }
+            }
+        }
+        boolean ok = true;
+        for (int j = 0; j < found.length; j++) {
+            ok = ok && found[j];
+        }
+
+        if (!ok) {
+            System.out.print("Returned result is [");
+            for (int j = 0; j < threads.length; j++) {
+                System.out.print(threads[j] + " ");
+            }
+            System.out.println("]");
+
+            System.out.print("Expected result is [");
+            for (int j = 0; j < threads.length; j++) {
+                System.out.print(dThreads[j] + " ");
+            }
+            System.out.println("]");
+            throw new RuntimeException("Unexpected result returned " +
+                " by findMonitorDeadlockedThreads method.");
+        }
+    }
+}
diff --git a/jdk/test/java/lang/management/ThreadMXBean/SynchronizerLockingThread.java b/jdk/test/java/lang/management/ThreadMXBean/SynchronizerLockingThread.java
new file mode 100644
index 0000000..83e07a8
--- /dev/null
+++ b/jdk/test/java/lang/management/ThreadMXBean/SynchronizerLockingThread.java
@@ -0,0 +1,355 @@
+/*
+ * Copyright 2005 Sun Microsystems, Inc.  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 Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
+ * CA 95054 USA or visit www.sun.com if you need additional information or
+ * have any questions.
+ */
+
+/*
+ * @bug     5086470 6358247
+ * @summary SynchronizersLockingThread is used by LockedSynchronizers.
+ *          It will create threads that acquire ReentrantLock and also object
+ *          monitors.
+ * @author  Mandy Chung
+ *
+ * @build ThreadDump
+ */
+
+import java.lang.management.*;
+import java.util.*;
+import java.util.concurrent.locks.ReentrantLock;
+import java.util.concurrent.locks.Condition;
+
+public class SynchronizerLockingThread extends Thread {
+    static ReentrantLock lock1 = new ReentrantLock();
+    static ReentrantLock lock2 = new ReentrantLock();
+    static ReentrantLock lock3 = new ReentrantLock();
+    static ReentrantLock lock4 = new ReentrantLock();
+    static Lock lock5 = new Lock("lock5");
+    static Lock lock6 = new Lock("lock6");
+    static Lock lock7 = new Lock("lock7");
+    static ReentrantLock lock8 = new ReentrantLock();
+
+    static SynchronizerLockingThread t1 = new Thread1();
+    static SynchronizerLockingThread t2 = new Thread2();
+    static int count = 2;
+    static void startLockingThreads() {
+        t1.setDaemon(true);
+        t2.setDaemon(true);
+        t1.start();
+        t2.start();
+
+        // wait until t1 and t2 waits
+        while (count != 0) {
+           try {
+               Thread.sleep(100);
+           } catch (InterruptedException e) {
+               throw new RuntimeException(e);
+           }
+        }
+    }
+
+    static long[] getThreadIds() {
+        return new long[] {t1.getId(), t2.getId()};
+    }
+
+    static void checkLocks(ThreadInfo[] tinfos) throws Exception {
+        int matches = 0;
+        for (ThreadInfo info : tinfos) {
+            if (info.getThreadId() == t1.getId()) {
+                t1.checkLocks(info);
+                matches++;
+            }
+            if (info.getThreadId() == t2.getId()) {
+                t2.checkLocks(info);
+                matches++;
+            }
+        }
+        if (matches != 2) {
+            throw new RuntimeException("MonitorInfo missing");
+        }
+    }
+
+    static class Lock {
+        String name;
+        Lock(String name) {
+            this.name = name;
+        }
+        public String toString() {
+            return name;
+        }
+    }
+
+    final String threadName;
+    Lock   waitingLock;
+    int    numOwnedMonitors;
+    Map<String, Lock[]> ownedMonitors;
+    Condition       waitingSync;
+    int             numOwnedSyncs;
+    Map<String, ReentrantLock[]> ownedSyncs;
+    public SynchronizerLockingThread(String name) {
+        this.threadName = name;
+    }
+
+    protected void setExpectedResult(Lock waitingLock,
+                                     int numOwnedMonitors,
+                                     Map<String, Lock[]> ownedMonitors,
+                                     Condition waitingSync,
+                                     int numOwnedSyncs,
+                                     Map<String, ReentrantLock[]> ownedSyncs) {
+        this.waitingLock = waitingLock;
+        this.numOwnedMonitors = numOwnedMonitors;
+        this.ownedMonitors = ownedMonitors;
+        this.waitingSync = waitingSync;
+        this.numOwnedSyncs = numOwnedSyncs;
+        this.ownedSyncs = ownedSyncs;
+    }
+
+    void checkLocks(ThreadInfo info) throws Exception {
+        checkThreadInfo(info);
+        MonitorInfo[] monitors = info.getLockedMonitors();
+        if (monitors.length != numOwnedMonitors) {
+            ThreadDump.threadDump();
+            throw new RuntimeException("Number of locked monitors = " +
+                monitors.length +
+                " not matched. Expected: " + numOwnedMonitors);
+        }
+        // check if each monitor returned in the list is the expected
+        // one
+        for (MonitorInfo m : monitors) {
+            StackTraceElement ste = m.getLockedStackFrame();
+            int depth = m.getLockedStackDepth();
+            checkStackFrame(info, ste, depth);
+            checkMonitor(m, ste.getMethodName());
+        }
+        // check if each expected monitor is included in the returned
+        // list
+        for (Map.Entry<String, Lock[]> e : ownedMonitors.entrySet()) {
+            for (Lock l : e.getValue()) {
+                checkMonitor(e.getKey(), l, monitors);
+            }
+        }
+
+        // We can only check if the length matches since we have no
+        // way to get the AbstractOwnableSynchronizer in ReentrantLock
+        LockInfo[] syncs = info.getLockedSynchronizers();
+        if (syncs.length != numOwnedSyncs) {
+            ThreadDump.threadDump();
+            throw new RuntimeException("Number of locked syncs = " +
+                syncs.length +
+                " not matched. Expected: " + numOwnedSyncs);
+        }
+    }
+
+    void checkThreadInfo(ThreadInfo info) throws Exception {
+        if (!getName().equals(info.getThreadName())) {
+            throw new RuntimeException("Name: " + info.getThreadName() +
+                " not matched. Expected: " + getName());
+        }
+        LockInfo l = info.getLockInfo();
+        if ((waitingLock != null || waitingSync != null) && l == null) {
+            throw new RuntimeException("LockInfo: " + l +
+                " not matched. Expected: non-null");
+        }
+        if (waitingLock == null && waitingSync == null && l != null) {
+            throw new RuntimeException("LockInfo: " + l +
+                " not matched. Expected: null");
+        }
+
+        String waitingLockName;
+        int hcode;
+        if (waitingLock != null) {
+            waitingLockName = waitingLock.getClass().getName();
+            hcode = System.identityHashCode(waitingLock);
+        } else {
+            waitingLockName = waitingSync.getClass().getName();
+            hcode = System.identityHashCode(waitingSync);
+        }
+        if (!waitingLockName.equals(l.getClassName())) {
+            throw new RuntimeException("LockInfo : " + l +
+                " class name not matched. Expected: " + waitingLockName);
+        }
+        if (hcode != l.getIdentityHashCode()) {
+            throw new RuntimeException("LockInfo: " + l +
+                " IdentityHashCode not matched. Expected: " + hcode);
+        }
+
+        String lockName = info.getLockName();
+        String[] s = lockName.split("@");
+        if (!waitingLockName.equals(s[0])) {
+            throw new RuntimeException("LockName: " + lockName +
+                " class name not matched. Expected: " + waitingLockName);
+        }
+        int i = Integer.parseInt(s[1], 16);
+        if (hcode != i) {
+            throw new RuntimeException("LockName: " + lockName +
+                " IdentityHashCode not matched. Expected: " + hcode);
+        }
+    }
+
+    void checkStackFrame(ThreadInfo info, StackTraceElement ste, int depth) {
+        StackTraceElement[] stacktrace = info.getStackTrace();
+        if (!ste.equals(stacktrace[depth])) {
+            System.out.println("LockedStackFrame:- " + ste);
+            System.out.println("StackTrace at " + depth + " :-" +
+                stacktrace[depth]);
+            throw new RuntimeException("LockedStackFrame does not match " +
+                "stack frame in ThreadInfo.getStackTrace");
+        }
+    }
+    void checkMonitor(MonitorInfo m, String methodName) {
+        for (Map.Entry<String, Lock[]> e : ownedMonitors.entrySet()) {
+            if (methodName.equals(e.getKey())) {
+                for (Lock l : e.getValue()) {
+                    String className = l.getClass().getName();
+                    int hcode = System.identityHashCode(l);
+                    if (className.equals(m.getClassName()) &&
+                        hcode == m.getIdentityHashCode()) {
+                        // monitor matched the expected
+                        return;
+                    }
+                }
+            }
+        }
+        throw new RuntimeException("Monitor not expected" + m);
+    }
+    void checkMonitor(String methodName, Lock l, MonitorInfo[] monitors) {
+        String className = l.getClass().getName();
+        int hcode = System.identityHashCode(l);
+        for (MonitorInfo m : monitors) {
+            if (className.equals(m.getClassName()) &&
+                hcode == m.getIdentityHashCode() &&
+                methodName.equals(m.getLockedStackFrame().getMethodName())) {
+                return;
+            }
+        }
+        throw new RuntimeException("Monitor not found in the returned list" +
+            " Method: " + methodName + " Lock: " + l);
+
+    }
+
+    static class Thread1 extends SynchronizerLockingThread {
+        public Thread1() {
+            super("t1");
+            initExpectedResult();
+        }
+        public void run() {
+            A();
+        }
+        void A() {
+            lock1.lock();
+            try {
+                lock2.lock();
+                try {
+                    lock3.lock();
+                    try {
+                        B();
+                    } finally {
+                        lock3.unlock();
+                    }
+                } finally {
+                    lock2.unlock();
+                }
+            } finally {
+                lock1.unlock();
+            }
+        }
+        void B() {
+            lock4.lock();
+            try {
+                synchronized(lock5) {
+                    C();
+                }
+            } finally {
+                lock4.unlock();
+            }
+        }
+        void C() {
+            synchronized(lock6) {
+                D();
+            }
+        }
+        void D() {
+            synchronized(lock7) {
+                try {
+                    // signal to about to wait
+                    count--;
+                    lock7.wait();
+                } catch (InterruptedException e) {
+                    throw new RuntimeException(e);
+                }
+            }
+        }
+
+        Map<String, Lock[]> LOCKED_MONITORS;
+        Map<String, ReentrantLock[]> LOCKED_SYNCS;
+        Lock WAITING_LOCK = lock7;
+        int OWNED_MONITORS = 2;
+        int OWNED_SYNCS = 4;
+        void initExpectedResult() {
+            LOCKED_MONITORS = new HashMap<String, Lock[]>();
+            LOCKED_MONITORS.put("D", new Lock[0]); // no monitored locked
+            LOCKED_MONITORS.put("C", new Lock[] {lock6});
+            LOCKED_MONITORS.put("B", new Lock[] {lock5});
+            LOCKED_MONITORS.put("A", new Lock[0]);
+
+            LOCKED_SYNCS = new HashMap<String, ReentrantLock[]>();
+            LOCKED_SYNCS.put("D", new ReentrantLock[0]); // no sync locked
+            LOCKED_SYNCS.put("C", new ReentrantLock[0]); // no sync locked
+            LOCKED_SYNCS.put("B", new ReentrantLock[] {lock4});
+            LOCKED_SYNCS.put("A", new ReentrantLock[] {lock3, lock2, lock1});
+            this.setExpectedResult(WAITING_LOCK,
+                                   OWNED_MONITORS, LOCKED_MONITORS,
+                                   null,
+                                   OWNED_SYNCS, LOCKED_SYNCS);
+        }
+
+    }
+
+    static class Thread2 extends SynchronizerLockingThread {
+        Map<String, Lock[]> LOCKED_MONITORS = new HashMap<String, Lock[]>();
+        Map<String, ReentrantLock[]> LOCKED_SYNCS = new HashMap<String, ReentrantLock[]>();
+        Condition c = lock8.newCondition();
+        Condition WAITING_LOCK = c;
+        int OWNED_MONITORS = 0;
+        int OWNED_SYNCS = 0;
+        public Thread2() {
+            super("t2");
+            this.setExpectedResult(null,
+                                   OWNED_MONITORS, LOCKED_MONITORS,
+                                   WAITING_LOCK,
+                                   OWNED_SYNCS, LOCKED_SYNCS);
+        }
+        public void run() {
+            lock8.lock();
+            try {
+                synchronized(lock7) {
+                    count--;
+                }
+                c.await();
+            } catch (InterruptedException e) {
+                throw new RuntimeException(e);
+            } finally {
+                lock8.unlock();
+            }
+            throw new RuntimeException("should not reach here");
+        }
+    }
+
+}
diff --git a/jdk/test/java/lang/management/ThreadMXBean/ThreadBlockedCount.java b/jdk/test/java/lang/management/ThreadMXBean/ThreadBlockedCount.java
new file mode 100644
index 0000000..7617a28
--- /dev/null
+++ b/jdk/test/java/lang/management/ThreadMXBean/ThreadBlockedCount.java
@@ -0,0 +1,236 @@
+/*
+ * Copyright 2003-2004 Sun Microsystems, Inc.  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 Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
+ * CA 95054 USA or visit www.sun.com if you need additional information or
+ * have any questions.
+ */
+
+/*
+ * @test
+ * @bug     4530538
+ * @summary Basic unit test of ThreadInfo.getBlockedCount()
+ * @author  Alexei Guibadoulline and Mandy Chung
+ *
+ * @build ThreadExecutionSynchronizer
+ * @run main ThreadBlockedCount
+ */
+
+import java.lang.management.*;
+import java.util.concurrent.locks.LockSupport;
+
+public class ThreadBlockedCount {
+    final static long EXPECTED_BLOCKED_COUNT = 3;
+    final static int  DEPTH = 10;
+    private static ThreadMXBean mbean
+        = ManagementFactory.getThreadMXBean();
+
+    private static Object a = new Object();
+    private static Object b = new Object();
+    private static Object c = new Object();
+    private static boolean aNotified = false;
+    private static boolean bNotified = false;
+    private static boolean cNotified = false;
+    private static Object blockedObj1 = new Object();
+    private static Object blockedObj2 = new Object();
+    private static Object blockedObj3 = new Object();
+    private static volatile boolean testFailed = false;
+    private static BlockingThread blocking;
+    private static BlockedThread blocked;
+    private static ThreadExecutionSynchronizer thrsync;
+
+
+
+    public static void main(String args[]) throws Exception {
+        // Create the BlockingThread before BlockedThread
+        // to make sure BlockingThread enter the lock before BlockedThread
+        thrsync = new ThreadExecutionSynchronizer();
+
+        blocking = new BlockingThread();
+        blocking.start();
+
+        blocked = new BlockedThread();
+        blocked.start();
+
+        try {
+            blocking.join();
+            blocked.join();
+        } catch (InterruptedException e) {
+            System.err.println("Unexpected exception.");
+            e.printStackTrace(System.err);
+            throw e;
+        }
+
+        if (testFailed) {
+            throw new RuntimeException("TEST FAILED.");
+        }
+        System.out.println("Test passed.");
+    }
+
+
+    static class BlockedThread extends Thread {
+        // NOTE: We can't use a.wait() here because wait() call is counted
+        // as blockedCount.  Instead, we use a boolean flag and sleep.
+        //
+        public void run() {
+            // wait Blocking thread
+            thrsync.signal();
+
+            // Enter lock a without blocking
+            synchronized (a) {
+                // wait until BlockingThread holds blockedObj1
+                while (!aNotified) {
+                    try {
+                        Thread.sleep(50);
+                    } catch (InterruptedException e) {
+                        System.err.println("Unexpected exception.");
+                        e.printStackTrace(System.err);
+                        testFailed = true;
+                    }
+                }
+
+                // signal BlockingThread.
+                thrsync.signal();
+
+                // Block to enter blockedObj1
+                // blockedObj1 should be owned by BlockingThread
+                synchronized (blockedObj1) {
+                    System.out.println("BlockedThread entered lock blockedObj1.");
+                }
+            }
+
+            // signal BlockingThread.
+            thrsync.signal();
+
+            // Enter lock a without blocking
+            synchronized (b) {
+                // wait until BlockingThread holds blockedObj2
+                while (!bNotified) {
+                    try {
+                        Thread.sleep(50);
+                    } catch (InterruptedException e) {
+                        System.err.println("Unexpected exception.");
+                        e.printStackTrace(System.err);
+                        testFailed = true;
+                    }
+                }
+
+                // signal BlockingThread.
+                thrsync.signal();
+
+                // Block to enter blockedObj2
+                // blockedObj2 should be owned by BlockingThread
+                synchronized (blockedObj2) {
+                    System.out.println("BlockedThread entered lock blockedObj2.");
+                }
+            }
+
+            // signal BlockingThread.
+            thrsync.signal();
+
+            // Enter lock a without blocking
+            synchronized (c) {
+                // wait until BlockingThread holds blockedObj3
+                while (!cNotified) {
+                    try {
+                        Thread.sleep(50);
+                    } catch (InterruptedException e) {
+                        System.err.println("Unexpected exception.");
+                        e.printStackTrace(System.err);
+                        testFailed = true;
+                    }
+                }
+
+                // signal BlockingThread.
+                thrsync.signal();
+
+                // Block to enter blockedObj3
+                // blockedObj3 should be owned by BlockingThread
+                synchronized (blockedObj3) {
+                    System.out.println("BlockedThread entered lock blockedObj3.");
+                }
+            }
+
+            // Check the mbean now
+            ThreadInfo ti = mbean.getThreadInfo(Thread.currentThread().
+                                                getId());
+            long count = ti.getBlockedCount();
+
+            if (count != EXPECTED_BLOCKED_COUNT) {
+                System.err.println("TEST FAILED: Blocked thread has " + count +
+                                   " blocked counts. Expected " +
+                                   EXPECTED_BLOCKED_COUNT);
+                testFailed = true;
+            }
+        } // run()
+    } // BlockingThread
+
+    static class BlockingThread extends Thread {
+        private void waitForSignalToRelease() {
+
+            // wait for BlockedThread.
+            thrsync.waitForSignal();
+
+            boolean threadBlocked = false;
+            while (!threadBlocked) {
+                // give a chance for BlockedThread to really block
+                try {
+                    Thread.sleep(50);
+                } catch (InterruptedException e) {
+                    System.err.println("Unexpected exception.");
+                    e.printStackTrace(System.err);
+                    testFailed = true;
+                }
+                ThreadInfo info = mbean.getThreadInfo(blocked.getId());
+                threadBlocked = (info.getThreadState() == Thread.State.BLOCKED);
+            }
+        }
+
+        public void run() {
+            // wait for BlockedThread.
+            thrsync.waitForSignal();
+
+            synchronized (blockedObj1) {
+                System.out.println("BlockingThread attempts to notify a");
+                aNotified = true;
+                waitForSignalToRelease();
+            }
+
+            // wait for BlockedThread.
+            thrsync.waitForSignal();
+
+            // block until BlockedThread is ready
+            synchronized (blockedObj2) {
+                System.out.println("BlockingThread attempts to notify b");
+                bNotified = true;
+                waitForSignalToRelease();
+            }
+
+            // wait for BlockedThread.
+            thrsync.waitForSignal();
+
+            // block until BlockedThread is ready
+            synchronized (blockedObj3) {
+                System.out.println("BlockingThread attempts to notify c");
+                cNotified = true;
+                waitForSignalToRelease();
+            }
+
+        } // run()
+    } // BlockedThread
+}
diff --git a/jdk/test/java/lang/management/ThreadMXBean/ThreadCounts.java b/jdk/test/java/lang/management/ThreadMXBean/ThreadCounts.java
new file mode 100644
index 0000000..95f581a
--- /dev/null
+++ b/jdk/test/java/lang/management/ThreadMXBean/ThreadCounts.java
@@ -0,0 +1,261 @@
+/*
+ * Copyright 2003-2004 Sun Microsystems, Inc.  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 Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
+ * CA 95054 USA or visit www.sun.com if you need additional information or
+ * have any questions.
+ */
+
+/*
+ * @test
+ * @bug     4530538
+ * @summary Basic unit test of mbean.getThreadCount()
+ *                             mbean.getTotalStartedThreadCount()
+ *                             mbean.getPeakThreadCount()
+ *                             mbean.getDaemonThreadCount()
+ * @author  Alexei Guibadoulline
+ *
+ * @run main ThreadCounts
+ */
+
+import java.lang.management.*;
+
+public class ThreadCounts {
+    final static int DAEMON_THREADS = 21;
+    final static int USER_THREADS_1 = 11;
+    final static int USER_THREADS_2 = 9;
+    final static int USER_THREADS = USER_THREADS_1 + USER_THREADS_2;
+    final static int ALL_THREADS = DAEMON_THREADS + USER_THREADS;
+    private static volatile boolean live[] = new boolean[ALL_THREADS];
+    private ThreadMXBean mbean = ManagementFactory.getThreadMXBean();
+    private static boolean testFailed = false;
+
+    // barrier for threads communication
+    private static Barrier barrier = new Barrier(DAEMON_THREADS);
+
+    public static void main(String argv[]) {
+        ThreadCounts test = new ThreadCounts();
+        Thread allThreads[] = new Thread[ALL_THREADS];
+
+        // Start DAEMON_THREADS threads and wait to be sure they all are alive
+        barrier.set(DAEMON_THREADS);
+        for (int i = 0; i < DAEMON_THREADS; i++) {
+            live[i] = true;
+            allThreads[i] = new MyThread(i);
+            allThreads[i].setDaemon(true);
+            allThreads[i].start();
+        }
+        // wait until all threads have started.
+        barrier.await();
+
+
+        System.out.println("Number of daemon threads added = " +
+                           DAEMON_THREADS);
+        // Check mbean now
+        if ( (!test.checkCount  (DAEMON_THREADS)) ||
+             (!test.checkCreated(DAEMON_THREADS)) ||
+             (!test.checkPeak   (DAEMON_THREADS)) ||
+             (!test.checkDaemon (DAEMON_THREADS))
+           )
+            testFailed = true;
+
+        // Start USER_THREADS_1 threads and wait to be sure they all are alive
+        barrier.set(USER_THREADS_1);
+        for (int i = DAEMON_THREADS; i < DAEMON_THREADS + USER_THREADS_1; i++) {
+            live[i] = true;
+            allThreads[i] = new MyThread(i);
+            allThreads[i].setDaemon(false);
+            allThreads[i].start();
+        }
+        // wait until user1 threads have started.
+        barrier.await();
+
+        System.out.println("Number of threads added = " +
+                           USER_THREADS_1);
+        // Check mbean now
+        if ( (!test.checkCount  (DAEMON_THREADS + USER_THREADS_1)) ||
+             (!test.checkCreated(DAEMON_THREADS + USER_THREADS_1)) ||
+             (!test.checkPeak   (DAEMON_THREADS + USER_THREADS_1)) ||
+             (!test.checkDaemon (DAEMON_THREADS))
+           )
+            testFailed = true;
+
+        // Stop daemon threads and wait to be sure they all are dead
+        barrier.set(DAEMON_THREADS);
+        for (int i = 0; i < DAEMON_THREADS; i++) {
+            live[i] = false;
+        }
+        // wait until daemon threads terminated.
+        barrier.await();
+
+        System.out.println("Daemon threads terminated.");
+        // Check mbean now
+        if ( (!test.checkCount  (USER_THREADS_1))                  ||
+             (!test.checkCreated(DAEMON_THREADS + USER_THREADS_1)) ||
+             (!test.checkPeak   (DAEMON_THREADS + USER_THREADS_1)) ||
+             (!test.checkDaemon (0))
+           )
+            testFailed = true;
+
+        // Start USER_THREADS_2 threads and wait to be sure they all are alive
+        barrier.set(USER_THREADS_2);
+        for (int i = DAEMON_THREADS + USER_THREADS_1; i < ALL_THREADS; i++) {
+            live[i] = true;
+            allThreads[i] = new MyThread(i);
+            allThreads[i].setDaemon(false);
+            allThreads[i].start();
+        }
+        // wait until user2 threads have started.
+        barrier.await();
+
+        System.out.println("Number of threads added = " +
+                           USER_THREADS_2);
+        // Check mbean now
+        if ( (!test.checkCount  (USER_THREADS_1 + USER_THREADS_2)) ||
+             (!test.checkCreated(ALL_THREADS))                     ||
+             (!test.checkPeak   (DAEMON_THREADS + USER_THREADS_1)) ||
+             (!test.checkDaemon (0))
+           )
+            testFailed = true;
+
+        // Stop user1 threads and wait to be sure they all are dead
+        barrier.set(USER_THREADS_1);
+        for (int i = DAEMON_THREADS; i < DAEMON_THREADS + USER_THREADS_1; i++) {
+            live[i] = false;
+        }
+        // wait until user1 threads terminated.
+        barrier.await();
+
+        System.out.println("Number of threads terminated = " +
+                           USER_THREADS_1);
+        // Check mbean now
+        if ( (!test.checkCount  (USER_THREADS_2))                  ||
+             (!test.checkCreated(ALL_THREADS))                     ||
+             (!test.checkPeak   (DAEMON_THREADS + USER_THREADS_1)) ||
+             (!test.checkDaemon (0))
+           )
+            testFailed = true;
+
+        // Stop user2 threads and wait to be sure they all are dead
+        barrier.set(USER_THREADS_2);
+        for (int i = DAEMON_THREADS + USER_THREADS_1; i < ALL_THREADS; i++) {
+            live[i] = false;
+        }
+        // wait until user2 threads terminated.
+        barrier.await();
+
+        System.out.println("Number of threads terminated = " +
+                           USER_THREADS_2);
+        // Check mbean now
+        if ( (!test.checkCount  (0))                               ||
+             (!test.checkCreated(ALL_THREADS))                     ||
+             (!test.checkPeak   (DAEMON_THREADS + USER_THREADS_1)) ||
+             (!test.checkDaemon (0))
+           )
+            testFailed = true;
+
+        if (testFailed)
+            throw new RuntimeException("TEST FAILED.");
+
+        System.out.println("Test passed.");
+    }
+
+    // Nobody knows how many threads are in the JVM in the exact moment. The
+    // only thing to check for sure is minimal number of threads alive (or
+    // created) in the application
+    private boolean checkCount(long min) {
+        long result = mbean.getThreadCount();
+
+        if (result < min) {
+            System.err.println("TEST FAILED: " +
+                               "Minimal number of live threads is " +
+                                min +
+                                ". ThreadMXBean.getThreadCount() returned " +
+                                result);
+            return false;
+        }
+        return true;
+    }
+
+    private boolean checkCreated(long min) {
+        long result = mbean.getTotalStartedThreadCount();
+
+        if (result < min) {
+            System.err.println("TEST FAILED: " +
+                               "Minimal number of created threads is " +
+                                min +
+                                ". ThreadMXBean.getTotalStartedThreadCount() "+
+                                "returned " + result);
+            return false;
+        }
+        return true;
+    }
+
+    private boolean checkPeak(long min) {
+        long result = mbean.getPeakThreadCount();
+
+        if (result < min) {
+            System.err.println("TEST FAILED: " +
+                               "Minimal peak thread count is " +
+                                min +
+                                ". ThreadMXBean.getPeakThreadCount() "+
+                                "returned " + result);
+            return false;
+        }
+        return true;
+    }
+
+    private boolean checkDaemon(long min) {
+        long result = mbean.getDaemonThreadCount();
+
+        if (result < min) {
+            System.err.println("TEST FAILED: " +
+                               "Minimal number of daemon thread count is " +
+                                min +
+                               "ThreadMXBean.getDaemonThreadCount() returned "
+                                + result);
+            return false;
+        }
+        return true;
+    }
+
+    // The MyThread thread lives as long as correspondent live[i] value is true
+    private static class MyThread extends Thread {
+        int id;
+
+        MyThread(int id) {
+            this.id = id;
+        }
+
+        public void run() {
+            // signal started
+            barrier.signal();
+            while (live[id]) {
+                try {
+                    sleep(100);
+                } catch (InterruptedException e) {
+                    System.out.println("Unexpected exception is thrown.");
+                    e.printStackTrace(System.out);
+                    testFailed = true;
+                }
+            }
+            // signal about to exit
+            barrier.signal();
+        }
+    }
+}
diff --git a/jdk/test/java/lang/management/ThreadMXBean/ThreadCpuTime.java b/jdk/test/java/lang/management/ThreadMXBean/ThreadCpuTime.java
new file mode 100644
index 0000000..332b257
--- /dev/null
+++ b/jdk/test/java/lang/management/ThreadMXBean/ThreadCpuTime.java
@@ -0,0 +1,243 @@
+/*
+ * Copyright 2003-2004 Sun Microsystems, Inc.  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 Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
+ * CA 95054 USA or visit www.sun.com if you need additional information or
+ * have any questions.
+ */
+
+/*
+ * @test
+ * @bug     4530538
+ * @summary Basic test of ThreadMXBean.getThreadCpuTime and
+ *          getCurrentThreadCpuTime.
+ * @author  Mandy Chung
+ */
+
+import java.lang.management.*;
+
+public class ThreadCpuTime {
+    private static ThreadMXBean mbean = ManagementFactory.getThreadMXBean();
+    private static boolean testFailed = false;
+    private static boolean done = false;
+    private static Object obj = new Object();
+    private static final int NUM_THREADS = 10;
+    private static Thread[] threads = new Thread[NUM_THREADS];
+    private static long[] times = new long[NUM_THREADS];
+
+    // careful about this value
+    private static final int DELTA = 100;
+
+    public static void main(String[] argv)
+        throws Exception {
+        if (!mbean.isCurrentThreadCpuTimeSupported()) {
+            return;
+        }
+
+       // disable CPU time
+        if (mbean.isThreadCpuTimeEnabled()) {
+            mbean.setThreadCpuTimeEnabled(false);
+        }
+
+        Thread curThread = Thread.currentThread();
+        long t = mbean.getCurrentThreadCpuTime();
+        if (t != -1) {
+            throw new RuntimeException("Invalid CurrenThreadCpuTime returned = " +
+                t + " expected = -1");
+        }
+
+        if (mbean.isThreadCpuTimeSupported()) {
+            long t1 = mbean.getThreadCpuTime(curThread.getId());
+            if (t1 != -1) {
+                throw new RuntimeException("Invalid ThreadCpuTime returned = " +
+                    t1 + " expected = -1");
+            }
+        }
+
+        // Enable CPU Time measurement
+        if (!mbean.isThreadCpuTimeEnabled()) {
+            mbean.setThreadCpuTimeEnabled(true);
+        }
+
+        if (!mbean.isThreadCpuTimeEnabled()) {
+            throw new RuntimeException("ThreadCpuTime is expected to be enabled");
+        }
+
+        long time = mbean.getCurrentThreadCpuTime();
+        if (time < 0) {
+            throw new RuntimeException("Invalid CPU time returned = " + time);
+        }
+
+        if (!mbean.isThreadCpuTimeSupported()) {
+            return;
+        }
+
+
+        // Expected to be time1 >= time
+        long time1 = mbean.getThreadCpuTime(curThread.getId());
+        if (time1 < time) {
+            throw new RuntimeException("CPU time " + time1 +
+                " expected >= " + time);
+        }
+        System.out.println(curThread.getName() +
+            " Current Thread Cpu Time = " + time +
+            " CPU time = " + time1);
+
+        for (int i = 0; i < NUM_THREADS; i++) {
+            threads[i] = new MyThread("MyThread-" + i);
+            threads[i].start();
+        }
+
+        waitUntilThreadBlocked();
+
+        for (int i = 0; i < NUM_THREADS; i++) {
+            times[i] = mbean.getThreadCpuTime(threads[i].getId());
+        }
+
+        goSleep(200);
+
+        for (int i = 0; i < NUM_THREADS; i++) {
+            long newTime = mbean.getThreadCpuTime(threads[i].getId());
+            if (times[i] > newTime) {
+                throw new RuntimeException("TEST FAILED: " +
+                    threads[i].getName() +
+                    " previous CPU time = " + times[i] +
+                    " > current CPU time = " + newTime);
+            }
+            if ((times[i] + DELTA) < newTime) {
+                throw new RuntimeException("TEST FAILED: " +
+                    threads[i].getName() +
+                    " CPU time = " + newTime +
+                    " previous CPU time " + times[i] +
+                    " out of expected range");
+            }
+
+            System.out.println(threads[i].getName() +
+                " Previous Cpu Time = " + times[i] +
+                " Current CPU time = " + newTime);
+        }
+
+        synchronized (obj) {
+            done = true;
+            obj.notifyAll();
+        }
+
+        for (int i = 0; i < NUM_THREADS; i++) {
+            try {
+                threads[i].join();
+            } catch (InterruptedException e) {
+                System.out.println("Unexpected exception is thrown.");
+                e.printStackTrace(System.out);
+                testFailed = true;
+                break;
+            }
+        }
+        if (testFailed) {
+            throw new RuntimeException("TEST FAILED");
+        }
+
+        System.out.println("Test passed");
+    }
+
+
+    private static void goSleep(long ms) throws Exception {
+        try {
+            Thread.sleep(ms);
+        } catch (InterruptedException e) {
+            System.out.println("Unexpected exception is thrown.");
+            throw e;
+        }
+    }
+
+    private static void waitUntilThreadBlocked()
+        throws Exception {
+        int count = 0;
+        while (count != NUM_THREADS) {
+            goSleep(100);
+            count = 0;
+            for (int i = 0; i < NUM_THREADS; i++) {
+                ThreadInfo info = mbean.getThreadInfo(threads[i].getId());
+                if (info.getThreadState() == Thread.State.WAITING) {
+                    count++;
+                }
+            }
+        }
+    }
+
+    static class MyThread extends Thread {
+        public MyThread(String name) {
+            super(name);
+        }
+
+        public void run() {
+            double sum = 0;
+            for (int i = 0; i < 5000; i++) {
+               double r = Math.random();
+               double x = Math.pow(3, r);
+               sum += x - r;
+            }
+            synchronized (obj) {
+                while (!done) {
+                    try {
+                        obj.wait();
+                    } catch (InterruptedException e) {
+                        System.out.println("Unexpected exception is thrown.");
+                        e.printStackTrace(System.out);
+                        testFailed = true;
+                        break;
+                    }
+                }
+            }
+
+            sum = 0;
+            for (int i = 0; i < 5000; i++) {
+               double r = Math.random();
+               double x = Math.pow(3, r);
+               sum += x - r;
+            }
+
+            long utime1 = mbean.getCurrentThreadUserTime();
+            long utime2 = mbean.getThreadUserTime(getId());
+            long time1 = mbean.getCurrentThreadCpuTime();
+            long time2 = mbean.getThreadCpuTime(getId());
+
+            System.out.println(getName() + ": " +
+                "CurrentThreadUserTime = " + utime1 +
+                " ThreadUserTime = " + utime2);
+            System.out.println(getName() + ": " +
+                "CurrentThreadCpuTime  = " + time1 +
+                " ThreadCpuTime  = " + time2);
+
+            if (time1 > time2) {
+                throw new RuntimeException("TEST FAILED: " + getName() +
+                    " CurrentThreadCpuTime = " + time1 +
+                    " > ThreadCpuTime = " + time2);
+            }
+/*************
+ * FIXME: Seems that on Solaris-sparc,
+ * It occasionally returns a different current thread user time > thread user time
+            if (utime1 > utime2) {
+                throw new RuntimeException("TEST FAILED: " + getName() +
+                    " CurrentThreadUserTime = " + utime1 +
+                    " > ThreadUserTime = " + utime2);
+            }
+*/
+        }
+    }
+
+}
diff --git a/jdk/test/java/lang/management/ThreadMXBean/ThreadDump.java b/jdk/test/java/lang/management/ThreadMXBean/ThreadDump.java
new file mode 100644
index 0000000..e262a37
--- /dev/null
+++ b/jdk/test/java/lang/management/ThreadMXBean/ThreadDump.java
@@ -0,0 +1,111 @@
+/*
+ * Copyright 2005 Sun Microsystems, Inc.  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 Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
+ * CA 95054 USA or visit www.sun.com if you need additional information or
+ * have any questions.
+ */
+
+/*
+ * Thread Dump utility class for printing
+ * @author  Mandy Chung
+ */
+
+import java.lang.management.*;
+import java.util.*;
+
+public class ThreadDump {
+    private static final String INDENT = "   ";
+
+    public static void printThreadInfo(ThreadInfo ti) {
+        StringBuilder sb = new StringBuilder("\"" + ti.getThreadName() + "\"" +
+                                             " Id=" + ti.getThreadId() +
+                                             " in " + ti.getThreadState());
+        if (ti.getLockName() != null) {
+            sb.append(" on lock=" + ti.getLockName());
+        }
+        if (ti.isSuspended()) {
+            sb.append(" (suspended)");
+        }
+        if (ti.isInNative()) {
+            sb.append(" (running in native)");
+        }
+        System.out.println(sb.toString());
+        if (ti.getLockOwnerName() != null) {
+             System.out.println(INDENT + " owned by " + ti.getLockOwnerName() +
+                                " Id=" + ti.getLockOwnerId());
+        }
+        StackTraceElement[] stacktrace = ti.getStackTrace();
+        MonitorInfo[] monitors = ti.getLockedMonitors();
+        for (int i = 0; i < stacktrace.length; i++) {
+            StackTraceElement ste = stacktrace[i];
+            System.out.println(INDENT + "at " + ste.toString());
+
+            for (MonitorInfo mi : monitors) {
+                if (mi.getLockedStackDepth() == i) {
+                    System.out.println(INDENT + "  - locked " + mi);
+                }
+            }
+        }
+        System.out.println();
+    }
+
+    public static void printStack(StackTraceElement[] stack) {
+        System.out.println(INDENT + "Stack: (length = " + stack.length + ")");
+        for (int j = 0; j < stack.length; j++) {
+            System.out.println(INDENT + INDENT + stack[j]);
+        }
+        System.out.println();
+    }
+
+    public static void dumpStacks() {
+        // Get stack traces of all Threads
+        Map m = Thread.getAllStackTraces();
+        Set s = m.entrySet();
+        Iterator iter = s.iterator();
+
+        Map.Entry entry;
+        while (iter.hasNext()) {
+            entry = (Map.Entry) iter.next();
+            Thread t = (Thread) entry.getKey();
+            StackTraceElement[] stack = (StackTraceElement[]) entry.getValue();
+            System.out.println(t);
+            printStack(stack);
+        }
+    }
+
+    public static void printLockInfo(LockInfo[] locks) {
+       System.out.println(INDENT + "Locked synchronizers: count = " + locks.length);
+       for (LockInfo li : locks) {
+           System.out.println(INDENT + "  - " + li);
+       }
+    }
+
+    static ThreadMXBean tmbean = ManagementFactory.getThreadMXBean();
+    public static void threadDump() {
+       System.out.println("Full Java thread dump");
+       ThreadInfo[] tinfos = tmbean.dumpAllThreads(true, true);
+       for (ThreadInfo ti : tinfos) {
+           printThreadInfo(ti);
+           LockInfo[] syncs = ti.getLockedSynchronizers();
+           printLockInfo(syncs);
+           System.out.println();
+       }
+    }
+
+}
diff --git a/jdk/test/java/lang/management/ThreadMXBean/ThreadExecutionSynchronizer.java b/jdk/test/java/lang/management/ThreadMXBean/ThreadExecutionSynchronizer.java
new file mode 100644
index 0000000..1f6dd4e
--- /dev/null
+++ b/jdk/test/java/lang/management/ThreadMXBean/ThreadExecutionSynchronizer.java
@@ -0,0 +1,85 @@
+/*
+ * Copyright 2004 Sun Microsystems, Inc.  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 Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
+ * CA 95054 USA or visit www.sun.com if you need additional information or
+ * have any questions.
+ */
+
+/*
+ *
+ * @summary Thiseclass is used to synchronize execution off two threads.
+ * @author  Swamy Venkataramanappa
+ */
+
+import java.util.concurrent.Semaphore;
+
+public class ThreadExecutionSynchronizer {
+
+    private boolean  waiting;
+    private Semaphore semaphore;
+
+    public ThreadExecutionSynchronizer() {
+        semaphore = new Semaphore(1);
+        waiting = false;
+    }
+
+    // Synchronizes two threads execution points.
+    // Basically any thread could get scheduled to run and
+    // it is not possible to know which thread reaches expected
+    // execution point. So whichever thread reaches a execution
+    // point first wait for the second thread. When the second thread
+    // reaches the expected execution point will wake up
+    // the thread which is waiting here.
+    void stopOrGo() {
+        semaphore.acquireUninterruptibly(); // Thread can get blocked.
+        if (!waiting) {
+            waiting = true;
+            // Wait for second thread to enter this method.
+            while(!semaphore.hasQueuedThreads()) {
+                try {
+                    Thread.sleep(20);
+                } catch (InterruptedException xx) {}
+            }
+            semaphore.release();
+        } else {
+            waiting = false;
+            semaphore.release();
+        }
+    }
+
+    // Wrapper function just for code readability.
+    void waitForSignal() {
+        stopOrGo();
+        goSleep(50);
+    }
+
+    void signal() {
+        stopOrGo();
+        goSleep(50);
+    }
+
+    private static void goSleep(long ms) {
+        try {
+            Thread.sleep(ms);
+        } catch (InterruptedException e) {
+            e.printStackTrace();
+            System.out.println("Unexpected exception.");
+        }
+    }
+}
diff --git a/jdk/test/java/lang/management/ThreadMXBean/ThreadInfoArray.java b/jdk/test/java/lang/management/ThreadMXBean/ThreadInfoArray.java
new file mode 100644
index 0000000..57629f5
--- /dev/null
+++ b/jdk/test/java/lang/management/ThreadMXBean/ThreadInfoArray.java
@@ -0,0 +1,77 @@
+/*
+ * Copyright 2004 Sun Microsystems, Inc.  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 Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
+ * CA 95054 USA or visit www.sun.com if you need additional information or
+ * have any questions.
+ */
+
+/*
+ * @test
+ * @bug     5058327
+ * @summary Test if getThreadInfo(long[]) returns a ThreadInfo[]
+ *          with null elements with no exception.
+ *
+ * @author  Mandy Chung
+ *
+ * @build ThreadInfoArray
+ * @run main ThreadInfoArray
+ */
+
+import java.lang.management.*;
+import javax.management.*;
+import java.util.*;
+import static java.lang.management.ManagementFactory.*;
+
+public class ThreadInfoArray {
+    public static void main(String[] argv) throws Exception {
+        ThreadMXBean mbean = ManagementFactory.getThreadMXBean();
+
+        // ID for a new thread
+        long [] ids = {new Thread().getId()};
+        ThreadInfo[] tinfos = mbean.getThreadInfo(ids);
+
+        if (tinfos[0] != null) {
+            throw new RuntimeException("TEST FAILED: " +
+                "Expected to have a null element");
+        }
+
+        // call getThreadInfo through MBeanServer
+        MBeanServer mbs = ManagementFactory.getPlatformMBeanServer();
+        ObjectName on = new ObjectName(THREAD_MXBEAN_NAME);
+        Object[] params = {ids};
+        String[] sigs = {"[J"};
+        Object[] result = (Object[]) mbs.invoke(on, "getThreadInfo", params, sigs);
+
+        if (result[0] != null) {
+            throw new RuntimeException("TEST FAILED: " +
+                "Expected to have a null element via MBeanServer");
+        }
+
+        // call getThreadInfo through proxy
+        ThreadMXBean proxy = newPlatformMXBeanProxy(mbs,
+                                 on.toString(),
+                                 ThreadMXBean.class);
+        tinfos = proxy.getThreadInfo(ids);
+        if (tinfos[0] != null) {
+            throw new RuntimeException("TEST FAILED: " +
+                "Expected to have a null element");
+        }
+        System.out.println("Test passed");
+    }
+}
diff --git a/jdk/test/java/lang/management/ThreadMXBean/ThreadLists.java b/jdk/test/java/lang/management/ThreadMXBean/ThreadLists.java
new file mode 100644
index 0000000..4b27b92
--- /dev/null
+++ b/jdk/test/java/lang/management/ThreadMXBean/ThreadLists.java
@@ -0,0 +1,69 @@
+/*
+ * Copyright 2004 Sun Microsystems, Inc.  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 Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
+ * CA 95054 USA or visit www.sun.com if you need additional information or
+ * have any questions.
+ */
+
+/*
+ * @test
+ * @bug 5047639
+ * @summary Check that the "java-level" APIs provide a consistent view of
+ *          the thread list
+ */
+import java.lang.management.ManagementFactory;
+import java.lang.management.ThreadMXBean;
+import java.util.Map;
+
+public class ThreadLists {
+    public static void main(String args[]) {
+
+        // get top-level thread group
+        ThreadGroup top = Thread.currentThread().getThreadGroup();
+        ThreadGroup parent;
+        do {
+            parent = top.getParent();
+            if (parent != null) top = parent;
+        } while (parent != null);
+
+        // get the thread count
+        int activeCount = top.activeCount();
+
+        Map<Thread, StackTraceElement[]> stackTraces = Thread.getAllStackTraces();
+
+        ThreadMXBean threadBean = ManagementFactory.getThreadMXBean();
+        int threadCount = threadBean.getThreadCount();
+        long[] threadIds = threadBean.getAllThreadIds();
+
+        System.out.println("ThreadGroup: " + activeCount + " active thread(s)");
+        System.out.println("Thread: " + stackTraces.size() + " stack trace(s) returned");
+        System.out.println("ThreadMXBean: " + threadCount + " live threads(s)");
+        System.out.println("ThreadMXBean: " + threadIds.length + " thread Id(s)");
+
+        // check results are consistent
+        boolean failed = false;
+        if (activeCount != stackTraces.size()) failed = true;
+        if (activeCount != threadCount) failed = true;
+        if (activeCount != threadIds.length) failed = true;
+
+        if (failed) {
+            throw new RuntimeException("inconsistent results");
+        }
+    }
+}
diff --git a/jdk/test/java/lang/management/ThreadMXBean/ThreadStackTrace.java b/jdk/test/java/lang/management/ThreadMXBean/ThreadStackTrace.java
new file mode 100644
index 0000000..dbe002e
--- /dev/null
+++ b/jdk/test/java/lang/management/ThreadMXBean/ThreadStackTrace.java
@@ -0,0 +1,368 @@
+/*
+ * Copyright 2003-2004 Sun Microsystems, Inc.  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 Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
+ * CA 95054 USA or visit www.sun.com if you need additional information or
+ * have any questions.
+ */
+
+/*
+ * @test
+ * @bug     4530538
+ * @summary Basic unit test of ThreadInfo.getStackTrace() and
+ *          ThreadInfo.getThreadState()
+ * @author  Mandy Chung
+ *
+ * @run build Semaphore
+ * @run main ThreadStackTrace
+ */
+
+import java.lang.management.*;
+
+public class ThreadStackTrace {
+    private static ThreadMXBean mbean
+        = ManagementFactory.getThreadMXBean();
+    private static boolean notified = false;
+    private static Object lockA = new Object();
+    private static Object lockB = new Object();
+    private static volatile boolean testFailed = false;
+    private static String[] blockedStack = {"run", "test", "A", "B", "C", "D"};
+    private static int bsDepth = 6;
+    private static int methodB = 4;
+    private static String[] examinerStack = {"run", "examine1", "examine2"};
+    private static int esDepth = 3;
+    private static int methodExamine1= 2;
+
+    private static void goSleep(long ms) {
+        try {
+            Thread.sleep(ms);
+        } catch (InterruptedException e) {
+            e.printStackTrace();
+            System.out.println("Unexpected exception.");
+            testFailed = true;
+        }
+    }
+
+    private static void checkNullThreadInfo(Thread t) throws Exception {
+        ThreadInfo ti = mbean.getThreadInfo(t.getId());
+        if (ti != null) {
+            ThreadInfo info =
+                mbean.getThreadInfo(t.getId(), Integer.MAX_VALUE);
+            System.out.println(INDENT + "TEST FAILED:");
+            if (info != null) {
+                printStack(t, info.getStackTrace());
+                System.out.println(INDENT + "Thread state: " + info.getThreadState());
+            }
+            throw new RuntimeException("TEST FAILED: " +
+                "getThreadInfo() is expected to return null for " + t);
+        }
+    }
+
+    private static boolean trace = false;
+    public static void main(String args[]) throws Exception {
+        if (args.length > 0 && args[0].equals("trace")) {
+            trace = true;
+        }
+
+        Examiner examiner = new Examiner("Examiner");
+        BlockedThread blocked = new BlockedThread("BlockedThread");
+        examiner.setThread(blocked);
+
+        checkNullThreadInfo(examiner);
+        checkNullThreadInfo(blocked);
+
+        // Start the threads and check them in  Blocked and Waiting states
+        examiner.start();
+
+        // block until examiner begins doing its real work
+        examiner.waitForStarted();
+
+        System.out.println("Checking stack trace for the examiner thread " +
+                           "is waiting to begin.");
+
+        // The Examiner should be waiting to be notified by the BlockedThread
+        checkThreadState(examiner, Thread.State.WAITING);
+
+        // Check that the stack is returned correctly for a new thread
+        checkStack(examiner, examinerStack, esDepth);
+
+        System.out.println("Now starting the blocked thread");
+        blocked.start();
+
+        try {
+            examiner.join();
+            blocked.join();
+        } catch (InterruptedException e) {
+            e.printStackTrace();
+            System.out.println("Unexpected exception.");
+            testFailed = true;
+        }
+
+        // Check that the stack is returned correctly for a terminated thread
+        checkNullThreadInfo(examiner);
+        checkNullThreadInfo(blocked);
+
+        if (testFailed)
+            throw new RuntimeException("TEST FAILED.");
+
+        System.out.println("Test passed.");
+    }
+
+    private static String INDENT = "    ";
+    private static void printStack(Thread t, StackTraceElement[] stack) {
+        System.out.println(INDENT +  t +
+                           " stack: (length = " + stack.length + ")");
+        if (t != null) {
+            for (int j = 0; j < stack.length; j++) {
+                System.out.println(INDENT + stack[j]);
+            }
+            System.out.println();
+        }
+    }
+
+    private static void checkThreadState(Thread thread, Thread.State s)
+        throws Exception {
+
+        ThreadInfo ti = mbean.getThreadInfo(thread.getId());
+        if (ti.getThreadState() != s) {
+            ThreadInfo info =
+                mbean.getThreadInfo(thread.getId(), Integer.MAX_VALUE);
+            System.out.println(INDENT + "TEST FAILED:");
+            printStack(thread, info.getStackTrace());
+            System.out.println(INDENT + "Thread state: " + info.getThreadState());
+
+            throw new RuntimeException("TEST FAILED: " +
+                "Thread state for " + thread + " returns " + ti.getThreadState() +
+                ".  Expected to be " + s);
+        }
+    }
+
+    private static void checkThreadState(Thread thread,
+                                         Thread.State s1, Thread.State s2)
+        throws Exception {
+
+        ThreadInfo ti = mbean.getThreadInfo(thread.getId());
+        if (ti.getThreadState() != s1 && ti.getThreadState() != s2) {
+            throw new RuntimeException("TEST FAILED: " +
+                "Thread state for " + thread + " returns " + ti.getThreadState() +
+                ".  Expected to be " + s1 + " or " + s2);
+        }
+    }
+
+    private static void checkStack(Thread t, String[] expectedStack,
+                                   int depth) throws Exception {
+        ThreadInfo ti = mbean.getThreadInfo(t.getId(), Integer.MAX_VALUE);
+        StackTraceElement[] stack = ti.getStackTrace();
+
+        if (trace) {
+            printStack(t, stack);
+        }
+        int frame = stack.length - 1;
+        for (int i = 0; i < depth; i++) {
+            if (! stack[frame].getMethodName().equals(expectedStack[i])) {
+                throw new RuntimeException("TEST FAILED: " +
+                    "Expected " + expectedStack[i] + " in frame " + frame +
+                    " but got " + stack[frame].getMethodName());
+            }
+            frame--;
+        }
+    }
+
+    static class BlockedThread extends Thread {
+        private Semaphore handshake = new Semaphore();
+
+        BlockedThread(String name) {
+            super(name);
+        }
+        boolean hasWaitersForBlocked() {
+            return (handshake.getWaiterCount() > 0);
+        }
+
+        void waitUntilBlocked() {
+            handshake.semaP();
+
+            // give a chance for the examiner thread to really wait
+            goSleep(20);
+        }
+
+        void waitUntilLockAReleased() {
+            handshake.semaP();
+
+            // give a chance for the examiner thread to really wait
+            goSleep(50);
+        }
+
+        private void notifyWaiter() {
+            // wait until the examiner waits on the semaphore
+            while (handshake.getWaiterCount() == 0) {
+                goSleep(20);
+            }
+            handshake.semaV();
+        }
+
+        private void test() {
+            A();
+        }
+        private void A() {
+            B();
+        }
+        private void B() {
+            C();
+
+            // notify the examiner about to block on lockB
+            notifyWaiter();
+
+            synchronized (lockB) {
+            };
+        }
+        private void C() {
+            D();
+        }
+        private void D() {
+            // Notify that examiner about to enter lockA
+            notifyWaiter();
+
+            synchronized (lockA) {
+                notified = false;
+                while (!notified) {
+                    try {
+                        // notify the examiner about to release lockA
+                        notifyWaiter();
+                        // Wait and let examiner thread check the mbean
+                        lockA.wait();
+                    } catch (InterruptedException e) {
+                        e.printStackTrace();
+                        System.out.println("Unexpected exception.");
+                        testFailed = true;
+                    }
+                }
+                System.out.println("BlockedThread notified");
+            }
+        }
+
+        public void run() {
+            test();
+        } // run()
+    } // BlockedThread
+
+    static class Examiner extends Thread {
+        private static BlockedThread blockedThread;
+        private Semaphore handshake = new Semaphore();
+
+        Examiner(String name) {
+            super(name);
+        }
+
+        public void setThread(BlockedThread thread) {
+            blockedThread = thread;
+        }
+
+        public synchronized void waitForStarted() {
+            // wait until the examiner is about to block
+            handshake.semaP();
+
+            // wait until the examiner is waiting for blockedThread's notification
+            while (!blockedThread.hasWaitersForBlocked()) {
+                goSleep(50);
+            }
+            // give a chance for the examiner thread to really wait
+            goSleep(20);
+        }
+
+        private Thread itself;
+        private void examine1() {
+            synchronized (lockB) {
+                examine2();
+                try {
+                    System.out.println("Checking examiner's its own stack trace");
+                    checkThreadState(itself, Thread.State.RUNNABLE);
+                    checkStack(itself, examinerStack, methodExamine1);
+
+                    // wait until blockedThread is blocked on lockB
+                    blockedThread.waitUntilBlocked();
+
+                    System.out.println("Checking stack trace for " +
+                        "BlockedThread - should be blocked on lockB.");
+                    checkThreadState(blockedThread, Thread.State.BLOCKED);
+                    checkStack(blockedThread, blockedStack, methodB);
+                } catch (Exception e) {
+                    e.printStackTrace();
+                    System.out.println("Unexpected exception.");
+                    testFailed = true;
+                }
+            }
+        }
+
+        private void examine2() {
+            synchronized (lockA) {
+                // wait until main thread gets signalled of the semaphore
+                while (handshake.getWaiterCount() == 0) {
+                    goSleep(20);
+                }
+
+                handshake.semaV();  // notify the main thread
+                try {
+                    // Wait until BlockedThread is about to block on lockA
+                    blockedThread.waitUntilBlocked();
+
+                    System.out.println("Checking examiner's its own stack trace");
+                    checkThreadState(itself, Thread.State.RUNNABLE);
+                    checkStack(itself, examinerStack, esDepth);
+
+                    System.out.println("Checking stack trace for " +
+                        "BlockedThread - should be blocked on lockA.");
+                    checkThreadState(blockedThread, Thread.State.BLOCKED);
+                    checkStack(blockedThread, blockedStack, bsDepth);
+
+                } catch (Exception e) {
+                    e.printStackTrace();
+                    System.out.println("Unexpected exception.");
+                    testFailed = true;
+                }
+            }
+
+            // release lockA and let BlockedThread to get the lock
+            // and wait on lockA
+            blockedThread.waitUntilLockAReleased();
+
+            synchronized (lockA) {
+                try {
+                    System.out.println("Checking stack trace for " +
+                        "BlockedThread - should be waiting on lockA.");
+                    checkThreadState(blockedThread, Thread.State.WAITING);
+                    checkStack(blockedThread, blockedStack, bsDepth);
+
+                    // Let the blocked thread go
+                    notified = true;
+                    lockA.notify();
+                } catch (Exception e) {
+                    e.printStackTrace();
+                    System.out.println("Unexpected exception.");
+                    testFailed = true;
+                }
+            }
+            // give some time for BlockedThread to proceed
+            goSleep(50);
+        } // examine2()
+
+        public void run() {
+            itself = Thread.currentThread();
+            examine1();
+        } // run()
+    } // Examiner
+}
diff --git a/jdk/test/java/lang/management/ThreadMXBean/ThreadStateTest.java b/jdk/test/java/lang/management/ThreadMXBean/ThreadStateTest.java
new file mode 100644
index 0000000..13f841c
--- /dev/null
+++ b/jdk/test/java/lang/management/ThreadMXBean/ThreadStateTest.java
@@ -0,0 +1,462 @@
+/*
+ * Copyright 2003-2006 Sun Microsystems, Inc.  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 Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
+ * CA 95054 USA or visit www.sun.com if you need additional information or
+ * have any questions.
+ */
+
+/*
+ * @test
+ * @bug     4967283
+ * @summary Basic unit test of thread states returned by
+ *          ThreadMXBean.getThreadInfo.getThreadState().
+ *          It also tests lock information returned by ThreadInfo.
+ *
+ * @author  Mandy Chung
+ *
+ * @build ThreadExecutionSynchronizer
+ * @run main ThreadStateTest
+ */
+
+import java.lang.management.ManagementFactory;
+import java.lang.management.ThreadMXBean;
+import java.lang.management.ThreadInfo;
+
+import java.util.concurrent.locks.LockSupport;
+
+public class ThreadStateTest {
+    private static final ThreadMXBean tm = ManagementFactory.getThreadMXBean();
+    private static boolean testFailed = false;
+
+    static class Lock {
+        private String name;
+        Lock(String name) {
+            this.name = name;
+        }
+        public String toString() {
+            return name;
+        }
+    }
+    private static Lock globalLock = new Lock("my lock");
+
+    public static void main(String[] argv) {
+        // Force thread state initialization now before the test
+        // verification begins.
+        Thread.currentThread().getState();
+
+        MyThread myThread = new MyThread("MyThread");
+
+        // before myThread starts
+        // checkThreadState(myThread, Thread.State.NEW);
+
+        myThread.start();
+        myThread.waitUntilStarted();
+        checkThreadState(myThread, Thread.State.RUNNABLE);
+        checkLockInfo(myThread, Thread.State.RUNNABLE, null, null);
+
+        myThread.suspend();
+        goSleep(10);
+        checkSuspendedThreadState(myThread, Thread.State.RUNNABLE);
+        myThread.resume();
+
+        synchronized (globalLock) {
+            myThread.goBlocked();
+            checkThreadState(myThread, Thread.State.BLOCKED);
+            checkLockInfo(myThread, Thread.State.BLOCKED,
+                          globalLock, Thread.currentThread());
+        }
+
+        myThread.goWaiting();
+        checkThreadState(myThread, Thread.State.WAITING);
+        checkLockInfo(myThread, Thread.State.WAITING,
+                      globalLock, null);
+
+        myThread.goTimedWaiting();
+        checkThreadState(myThread, Thread.State.TIMED_WAITING);
+        checkLockInfo(myThread, Thread.State.TIMED_WAITING,
+                      globalLock, null);
+
+
+
+      /*
+       *********** parkUntil seems not working
+       * ignore this park case for now.
+
+         Bug ID : 5062095
+       ***********************************************
+        myThread.goParked();
+        checkThreadState(myThread, Thread.State.WAITING);
+        checkLockInfo(myThread, Thread.State.WAITING, null, null);
+
+        myThread.goTimedParked();
+        checkThreadState(myThread, Thread.State.TIMED_WAITING);
+        checkLockInfo(myThread, Thread.State.TIMED_WAITING, null, null);
+
+       */
+
+        myThread.goSleeping();
+        checkThreadState(myThread, Thread.State.TIMED_WAITING);
+        checkLockInfo(myThread, Thread.State.TIMED_WAITING, null, null);
+
+
+        myThread.terminate();
+        // checkThreadState(myThread, ThreadState.TERMINATED);
+
+        try {
+            myThread.join();
+        } catch (InterruptedException e) {
+            e.printStackTrace();
+            System.out.println("Unexpected exception.");
+            testFailed = true;
+        }
+        if (testFailed)
+            throw new RuntimeException("TEST FAILED.");
+        System.out.println("Test passed.");
+    }
+
+    private static void checkSuspendedThreadState(Thread t, Thread.State state) {
+        ThreadInfo info = tm.getThreadInfo(t.getId());
+        if (info == null) {
+            throw new RuntimeException(t.getName() +
+               " expected to have ThreadInfo " +
+               " but got null.");
+        }
+
+        if (info.getThreadState() != state) {
+            throw new RuntimeException(t.getName() + " expected to be in " +
+                state + " state but got " + info.getThreadState());
+        }
+
+        if (!info.isSuspended()) {
+            throw new RuntimeException(t.getName() + " expected to be suspended " +
+                " but isSuspended() returns " + info.isSuspended());
+        }
+        checkThreadState(t, state);
+    }
+
+    private static void checkThreadState(Thread t, Thread.State expected) {
+        ThreadInfo ti = tm.getThreadInfo(t.getId());
+        Thread.State state = ti.getThreadState();
+        if (state == null) {
+            throw new RuntimeException(t.getName() + " expected to have " +
+                expected + " but got null.");
+        }
+
+        if (state != expected) {
+            if (expected ==  Thread.State.BLOCKED) {
+                int retryCount=0;
+                while (ti.getThreadState() != expected) {
+                    if (retryCount >= 500) {
+                        throw new RuntimeException(t.getName() +
+                            " expected to have " + expected + " but got " + state);
+                     }
+                     goSleep(100);
+                }
+            } else {
+                throw new RuntimeException(t.getName() + " expected to have " +
+                    expected + " but got " + state);
+            }
+        }
+    }
+
+    private static String getLockName(Object lock) {
+        if (lock == null) return null;
+
+        return lock.getClass().getName() + '@' +
+            Integer.toHexString(System.identityHashCode(lock));
+    }
+
+    private static void checkLockInfo(Thread t, Thread.State state, Object lock, Thread owner) {
+        ThreadInfo info = tm.getThreadInfo(t.getId());
+        if (info == null) {
+            throw new RuntimeException(t.getName() +
+               " expected to have ThreadInfo " +
+               " but got null.");
+        }
+
+        if (info.getThreadState() != state) {
+            throw new RuntimeException(t.getName() + " expected to be in " +
+                state + " state but got " + info.getThreadState());
+        }
+
+        if (lock == null && info.getLockName() != null) {
+            throw new RuntimeException(t.getName() +
+                " expected not to be blocked on any lock" +
+                " but got " + info.getLockName());
+        }
+        String expectedLockName = getLockName(lock);
+        if (lock != null && info.getLockName() == null) {
+            throw new RuntimeException(t.getName() +
+                " expected to be blocked on lock [" + expectedLockName +
+                "] but got null.");
+        }
+
+        if (lock != null && !expectedLockName.equals(info.getLockName())) {
+            throw new RuntimeException(t.getName() +
+                " expected to be blocked on lock [" + expectedLockName +
+                "] but got [" + info.getLockName() + "].");
+        }
+
+        if (owner == null && info.getLockOwnerName() != null) {
+            throw new RuntimeException("Lock owner is expected " +
+                " to be null but got " + info.getLockOwnerName());
+        }
+
+        if (owner != null && info.getLockOwnerName() == null) {
+            throw new RuntimeException("Lock owner is expected to be " +
+                owner.getName() +
+                " but got null.");
+        }
+        if (owner != null && !info.getLockOwnerName().equals(owner.getName())) {
+            throw new RuntimeException("Lock owner is expected to be " +
+                owner.getName() +
+                " but got " + owner.getName());
+        }
+        if (owner == null && info.getLockOwnerId() != -1) {
+            throw new RuntimeException("Lock owner is expected " +
+                " to be -1 but got " + info.getLockOwnerId());
+        }
+
+        if (owner != null && info.getLockOwnerId() <= 0) {
+            throw new RuntimeException("Lock owner is expected to be " +
+                owner.getName() + "(id = " + owner.getId() +
+                ") but got " + info.getLockOwnerId());
+        }
+        if (owner != null && info.getLockOwnerId() != owner.getId()) {
+            throw new RuntimeException("Lock owner is expected to be " +
+                owner.getName() + "(id = " + owner.getId() +
+                ") but got " + info.getLockOwnerId());
+        }
+        if (info.isSuspended()) {
+            throw new RuntimeException(t.getName() +
+                " isSuspended() returns " + info.isSuspended());
+        }
+    }
+
+    private static void goSleep(long ms) {
+        try {
+            Thread.sleep(ms);
+        } catch (InterruptedException e) {
+            e.printStackTrace();
+            System.out.println("Unexpected exception.");
+            testFailed = true;
+        }
+    }
+
+    static class MyThread extends Thread {
+        private ThreadExecutionSynchronizer thrsync = new ThreadExecutionSynchronizer();
+
+        MyThread(String name) {
+            super(name);
+        }
+
+        private final int RUNNABLE = 0;
+        private final int BLOCKED = 1;
+        private final int WAITING = 2;
+        private final int TIMED_WAITING = 3;
+        private final int PARKED = 4;
+        private final int TIMED_PARKED = 5;
+        private final int SLEEPING = 6;
+        private final int TERMINATE = 7;
+        private int state = RUNNABLE;
+
+        private boolean done = false;
+        public void run() {
+            // Signal main thread to continue.
+            thrsync.signal();
+            while (!done) {
+                switch (state) {
+                    case RUNNABLE: {
+                        double sum = 0;
+                        for (int i = 0; i < 1000; i++) {
+                           double r = Math.random();
+                           double x = Math.pow(3, r);
+                           sum += x - r;
+                        }
+                        break;
+                    }
+                    case BLOCKED: {
+                        // signal main thread.
+                        thrsync.signal();
+                        System.out.println("  myThread is going to block.");
+                        synchronized (globalLock) {
+                            // finish blocking
+                            state = RUNNABLE;
+                        }
+                        break;
+                    }
+                    case WAITING: {
+                        synchronized (globalLock) {
+                            // signal main thread.
+                            thrsync.signal();
+                            System.out.println("  myThread is going to wait.");
+                            try {
+                                globalLock.wait();
+                            } catch (InterruptedException e) {
+                                // ignore
+                            }
+                        }
+                        break;
+                    }
+                    case TIMED_WAITING: {
+                        synchronized (globalLock) {
+                            // signal main thread.
+                            thrsync.signal();
+                            System.out.println("  myThread is going to timed wait.");
+                            try {
+                                globalLock.wait(10000);
+                            } catch (InterruptedException e) {
+                                // ignore
+                            }
+                        }
+                        break;
+                    }
+                    case PARKED: {
+                        // signal main thread.
+                        thrsync.signal();
+                        System.out.println("  myThread is going to park.");
+                        LockSupport.park();
+                        // give a chance for the main thread to block
+                        System.out.println("  myThread is going to park.");
+                        goSleep(10);
+                        break;
+                    }
+                    case TIMED_PARKED: {
+                        // signal main thread.
+                        thrsync.signal();
+                        System.out.println("  myThread is going to timed park.");
+                        long deadline = System.currentTimeMillis() + 10000*1000;
+                        LockSupport.parkUntil(deadline);
+
+                        // give a chance for the main thread to block
+                        goSleep(10);
+                        break;
+                    }
+                    case SLEEPING: {
+                        // signal main thread.
+                        thrsync.signal();
+                        System.out.println("  myThread is going to sleep.");
+                        try {
+                            Thread.sleep(1000000);
+                        } catch (InterruptedException e) {
+                            // finish sleeping
+                            interrupted();
+                        }
+                        break;
+                    }
+                    case TERMINATE: {
+                        done = true;
+                        // signal main thread.
+                        thrsync.signal();
+                        break;
+                    }
+                    default:
+                        break;
+                }
+            }
+        }
+        public void waitUntilStarted() {
+            // wait for MyThread.
+            thrsync.waitForSignal();
+            goSleep(10);
+        }
+
+        public void goBlocked() {
+            System.out.println("Waiting myThread to go blocked.");
+            setState(BLOCKED);
+            // wait for MyThread to get blocked
+            thrsync.waitForSignal();
+            goSleep(20);
+        }
+
+        public void goWaiting() {
+            System.out.println("Waiting myThread to go waiting.");
+            setState(WAITING);
+            // wait for  MyThread to wait on object.
+            thrsync.waitForSignal();
+            goSleep(20);
+        }
+        public void goTimedWaiting() {
+            System.out.println("Waiting myThread to go timed waiting.");
+            setState(TIMED_WAITING);
+            // wait for MyThread timed wait call.
+            thrsync.waitForSignal();
+            goSleep(20);
+        }
+        public void goParked() {
+            System.out.println("Waiting myThread to go parked.");
+            setState(PARKED);
+            // wait for  MyThread state change to PARKED.
+            thrsync.waitForSignal();
+            goSleep(20);
+        }
+        public void goTimedParked() {
+            System.out.println("Waiting myThread to go timed parked.");
+            setState(TIMED_PARKED);
+            // wait for  MyThread.
+            thrsync.waitForSignal();
+            goSleep(20);
+        }
+
+        public void goSleeping() {
+            System.out.println("Waiting myThread to go sleeping.");
+            setState(SLEEPING);
+            // wait for  MyThread.
+            thrsync.waitForSignal();
+            goSleep(20);
+        }
+        public void terminate() {
+            System.out.println("Waiting myThread to terminate.");
+            setState(TERMINATE);
+            // wait for  MyThread.
+            thrsync.waitForSignal();
+            goSleep(20);
+        }
+
+        private void setState(int newState) {
+            switch (state) {
+                case BLOCKED:
+                    while (state == BLOCKED) {
+                        goSleep(20);
+                    }
+                    state = newState;
+                    break;
+                case WAITING:
+                case TIMED_WAITING:
+                    state = newState;
+                    synchronized (globalLock) {
+                        globalLock.notify();
+                    }
+                    break;
+                case PARKED:
+                case TIMED_PARKED:
+                    state = newState;
+                    LockSupport.unpark(this);
+                    break;
+                case SLEEPING:
+                    state = newState;
+                    this.interrupt();
+                    break;
+                default:
+                    state = newState;
+                    break;
+            }
+        }
+    }
+}
diff --git a/jdk/test/java/lang/management/ThreadMXBean/ThreadUserTime.java b/jdk/test/java/lang/management/ThreadMXBean/ThreadUserTime.java
new file mode 100644
index 0000000..c067190
--- /dev/null
+++ b/jdk/test/java/lang/management/ThreadMXBean/ThreadUserTime.java
@@ -0,0 +1,237 @@
+/*
+ * Copyright 2004 Sun Microsystems, Inc.  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 Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
+ * CA 95054 USA or visit www.sun.com if you need additional information or
+ * have any questions.
+ */
+
+/*
+ * @test
+ * @bug     4997799
+ * @summary Basic test of ThreadMXBean.getThreadUserTime and
+ *          getCurrentThreadUserTime.
+ * @author  Mandy Chung
+ */
+
+import java.lang.management.*;
+
+public class ThreadUserTime {
+    private static ThreadMXBean mbean = ManagementFactory.getThreadMXBean();
+    private static boolean testFailed = false;
+    private static boolean done = false;
+    private static Object obj = new Object();
+    private static final int NUM_THREADS = 10;
+    private static Thread[] threads = new Thread[NUM_THREADS];
+    private static long[] times = new long[NUM_THREADS];
+
+    // careful about this value
+    private static final int DELTA = 100;
+
+    public static void main(String[] argv)
+        throws Exception {
+        if (!mbean.isCurrentThreadCpuTimeSupported()) {
+            return;
+        }
+
+        // disable user time
+        if (mbean.isThreadCpuTimeEnabled()) {
+            mbean.setThreadCpuTimeEnabled(false);
+        }
+
+        Thread curThread = Thread.currentThread();
+        long t = mbean.getCurrentThreadUserTime();
+        if (t != -1) {
+            throw new RuntimeException("Invalid CurrenThreadUserTime returned = " +
+                t + " expected = -1");
+        }
+
+        if (mbean.isThreadCpuTimeSupported()) {
+            long t1 = mbean.getThreadUserTime(curThread.getId());
+            if (t1 != -1) {
+                throw new RuntimeException("Invalid ThreadUserTime returned = " +
+                    t1 + " expected = -1");
+            }
+        }
+
+        // Enable CPU Time measurement
+        if (!mbean.isThreadCpuTimeEnabled()) {
+            mbean.setThreadCpuTimeEnabled(true);
+        }
+
+        if (!mbean.isThreadCpuTimeEnabled()) {
+            throw new RuntimeException("ThreadUserTime is expected to be enabled");
+        }
+
+        long time = mbean.getCurrentThreadUserTime();
+        if (time < 0) {
+            throw new RuntimeException("Invalid user time returned = " + time);
+        }
+
+        if (!mbean.isThreadCpuTimeSupported()) {
+            return;
+        }
+
+
+        // Expected to be time1 >= time
+        long time1 = mbean.getThreadUserTime(curThread.getId());
+        if (time1 < time) {
+            throw new RuntimeException("User time " + time1 +
+                " expected >= " + time);
+        }
+        System.out.println(curThread.getName() +
+            " Current Thread User Time = " + time +
+            " user time = " + time1);
+
+        for (int i = 0; i < NUM_THREADS; i++) {
+            threads[i] = new MyThread("MyThread-" + i);
+            threads[i].start();
+        }
+
+        waitUntilThreadBlocked();
+
+        for (int i = 0; i < NUM_THREADS; i++) {
+            times[i] = mbean.getThreadUserTime(threads[i].getId());
+        }
+
+        goSleep(200);
+
+        for (int i = 0; i < NUM_THREADS; i++) {
+            long newTime = mbean.getThreadUserTime(threads[i].getId());
+            if (times[i] > newTime) {
+                throw new RuntimeException("TEST FAILED: " +
+                    threads[i].getName() +
+                    " previous user user time = " + times[i] +
+                    " > current user user time = " + newTime);
+            }
+            if ((times[i] + DELTA) < newTime) {
+                throw new RuntimeException("TEST FAILED: " +
+                    threads[i].getName() +
+                    " user time = " + newTime +
+                    " previous user time " + times[i] +
+                    " out of expected range");
+            }
+
+            System.out.println(threads[i].getName() +
+                " Previous User Time = " + times[i] +
+                " Current User time = " + newTime);
+        }
+
+        synchronized (obj) {
+            done = true;
+            obj.notifyAll();
+        }
+
+        for (int i = 0; i < NUM_THREADS; i++) {
+            try {
+                threads[i].join();
+            } catch (InterruptedException e) {
+                System.out.println("Unexpected exception is thrown.");
+                e.printStackTrace(System.out);
+                testFailed = true;
+                break;
+            }
+        }
+        if (testFailed) {
+            throw new RuntimeException("TEST FAILED");
+        }
+
+        System.out.println("Test passed");
+    }
+
+
+    private static void goSleep(long ms) throws Exception {
+        try {
+            Thread.sleep(ms);
+        } catch (InterruptedException e) {
+            System.out.println("Unexpected exception is thrown.");
+            throw e;
+        }
+    }
+
+    private static void waitUntilThreadBlocked()
+        throws Exception {
+        int count = 0;
+        while (count != NUM_THREADS) {
+            goSleep(100);
+            count = 0;
+            for (int i = 0; i < NUM_THREADS; i++) {
+                ThreadInfo info = mbean.getThreadInfo(threads[i].getId());
+                if (info.getThreadState() == Thread.State.WAITING) {
+                    count++;
+                }
+            }
+        }
+    }
+
+    static class MyThread extends Thread {
+        public MyThread(String name) {
+            super(name);
+        }
+
+        public void run() {
+            double sum = 0;
+            for (int i = 0; i < 5000; i++) {
+               double r = Math.random();
+               double x = Math.pow(3, r);
+               sum += x - r;
+            }
+            synchronized (obj) {
+                while (!done) {
+                    try {
+                        obj.wait();
+                    } catch (InterruptedException e) {
+                        System.out.println("Unexpected exception is thrown.");
+                        e.printStackTrace(System.out);
+                        testFailed = true;
+                        break;
+                    }
+                }
+            }
+            sum = 0;
+            for (int i = 0; i < 5000; i++) {
+               double r = Math.random();
+               double x = Math.pow(3, r);
+               sum += x - r;
+            }
+
+            long time1 = mbean.getCurrentThreadCpuTime();
+            long utime1 = mbean.getCurrentThreadUserTime();
+            long time2 = mbean.getThreadCpuTime(getId());
+            long utime2 = mbean.getThreadUserTime(getId());
+
+            System.out.println(getName() + ":");
+            System.out.println("CurrentThreadUserTime = " + utime1 +
+                " ThreadUserTime = " + utime2);
+            System.out.println("CurrentThreadCpuTime  = " + time1 +
+                " ThreadCpuTime  = " + time2);
+
+            if (time1 > time2) {
+                throw new RuntimeException("TEST FAILED: " + getName() +
+                    " CurrentThreadCpuTime = " + time1 +
+                    " > ThreadCpuTime = " + time2);
+            }
+            if (utime1 > utime2) {
+                throw new RuntimeException("TEST FAILED: " + getName() +
+                    " CurrentThreadUserTime = " + utime1 +
+                    " > ThreadUserTime = " + utime2);
+            }
+        }
+    }
+
+}
diff --git a/jdk/test/java/lang/ref/Basic.java b/jdk/test/java/lang/ref/Basic.java
new file mode 100644
index 0000000..a640786
--- /dev/null
+++ b/jdk/test/java/lang/ref/Basic.java
@@ -0,0 +1,148 @@
+/*
+ * Copyright 1997-1998 Sun Microsystems, Inc.  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 Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
+ * CA 95054 USA or visit www.sun.com if you need additional information or
+ * have any questions.
+ */
+
+/* @test
+ * @summary Basic functional test of reference objects
+ * @author Mark Reinhold
+ */
+
+
+import java.lang.ref.*;
+import java.util.Vector;
+
+
+public class Basic {
+
+    static ReferenceQueue q = new ReferenceQueue();
+    static ReferenceQueue q2 = new ReferenceQueue();
+    static Reference rw, rw2, rp, rp2;
+    static Vector keep = new Vector();
+    static boolean finalized = false;
+
+    public static class ClearFinalizerThread {
+        protected void finalize() {
+            System.err.println("Cleared finalizer thread");
+        }
+    };
+
+    protected void finalize() {
+        Basic.finalized = true;
+        System.err.println("Finalized " + this);
+    }
+
+    public static class Sub { };
+
+    Object sub = new Sub();
+
+    static void fork(Runnable proc) throws InterruptedException {
+        Thread t = new Thread(proc);
+        t.start();
+        t.join();
+    }
+
+    static void showReferences() throws InterruptedException {
+        fork(new Runnable() {
+            public void run() {
+                System.err.println("References: W " + rw.get()
+                                   + ", W2 " + rw2.get()
+                                   + ", P " + rp.get()
+                                   + ", P2 " + rp2.get());
+            }
+        });
+    }
+
+    static void createNoise() throws InterruptedException {
+        fork(new Runnable() {
+            public void run() {
+                keep.addElement(new PhantomReference(new Object(), q2));
+            }
+        });
+    }
+
+
+    public static void main(String[] args) throws Exception {
+
+        fork(new Runnable() {
+            public void run() {
+                Basic s = new Basic();
+                rw = new WeakReference(s, q);
+                rw2 = new WeakReference(s);
+                rp = new PhantomReference(s, q);
+                rp2 = new PhantomReference(s.sub, q);
+                s = null;
+            }
+        });
+
+        showReferences();
+
+        int ndq = 0;
+        boolean prevFinalized = false;
+    outer:
+        for (int i = 1;; i++) {
+            Reference r;
+
+            createNoise();
+            System.err.println("GC " + i);
+            Thread.sleep(10);
+            System.gc();
+
+            showReferences();
+            while ((r = q2.poll()) != null) {
+                System.err.println("Noise " + r);
+            }
+
+            /* Cause a dummy object to be finalized, since the finalizer thread
+               might retain a reference to the Basic instance after it's been
+               finalized (this happens with java_g) */
+            if (Basic.finalized && !prevFinalized) {
+                fork(new Runnable() {
+                    public void run() {
+                        new ClearFinalizerThread();
+                    }});
+                prevFinalized = true;
+            }
+
+            while ((r = q.poll()) != null) {
+                ndq++;
+                if (r != null) {
+                    System.err.println("Dequeued " + r);
+                    if (ndq == 3) break outer;
+                }
+            }
+
+            if (i >= 10) break;
+
+        }
+
+        if (ndq != 3) {
+            throw new Exception("Expected to dequeue 3 reference objects,"
+                                + " but only got " + ndq);
+        }
+
+        if (! Basic.finalized) {
+            throw new Exception("Test object not finalized");
+        }
+
+    }
+
+}
diff --git a/jdk/test/java/lang/ref/EnqueueNullRef.java b/jdk/test/java/lang/ref/EnqueueNullRef.java
new file mode 100644
index 0000000..e510a27
--- /dev/null
+++ b/jdk/test/java/lang/ref/EnqueueNullRef.java
@@ -0,0 +1,46 @@
+/*
+ * Copyright 2003 Sun Microsystems, Inc.  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 Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
+ * CA 95054 USA or visit www.sun.com if you need additional information or
+ * have any questions.
+ */
+
+/* @test
+ * @bug 4247236
+ * @summary Ensure that reference objects with null referents can be enqueued
+ */
+
+import java.lang.ref.*;
+
+
+public class EnqueueNullRef {
+
+    static void test(ReferenceQueue q, Reference r) {
+        if (!r.enqueue())
+            throw new RuntimeException("Enqueue operation failed");
+    }
+
+    public static void main(String[] args) {
+        ReferenceQueue q = new ReferenceQueue();
+        test(q, new WeakReference(null, q));
+        test(q, new SoftReference(null, q));
+        test(q, new PhantomReference(null, q));
+    }
+
+}
diff --git a/jdk/test/java/lang/ref/NullQueue.java b/jdk/test/java/lang/ref/NullQueue.java
new file mode 100644
index 0000000..1e11e87
--- /dev/null
+++ b/jdk/test/java/lang/ref/NullQueue.java
@@ -0,0 +1,89 @@
+/*
+ * Copyright 1999 Sun Microsystems, Inc.  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 Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
+ * CA 95054 USA or visit www.sun.com if you need additional information or
+ * have any questions.
+ */
+
+/* @test
+ * @bug 4178693
+ * @summary Ensure that null queue arguments don't crash the Reference handler
+ * @author Mark Reinhold
+ */
+
+import java.lang.ref.Reference;
+import java.lang.ref.WeakReference;
+
+
+public class NullQueue {
+
+    private static Reference r = null;
+
+    private static Thread findThread(String name) {
+        /* Find reference-handler thread */
+        ThreadGroup tg = Thread.currentThread().getThreadGroup();
+        for (ThreadGroup tgn = tg;
+             tgn != null;
+             tg = tgn, tgn = tg.getParent());
+        int nt = tg.activeCount();
+        Thread[] ts = new Thread[nt];
+        tg.enumerate(ts);
+        Thread refHandler = null;
+        for (int i = 0; i < ts.length; i++) {
+            if (ts[i].getName().equals(name)) return ts[i];
+        }
+        return null;
+    }
+
+    private static void fork(Runnable proc) throws InterruptedException {
+        Thread t = new Thread(proc);
+        t.start();
+        t.join();
+    }
+
+    public static void main(String[] args) throws Exception {
+
+        Thread refHandler = findThread("Reference Handler");
+        if (refHandler == null)
+            throw new Exception("Couldn't find Reference-handler thread");
+        if (!refHandler.isAlive())
+            throw new Exception("Reference-handler thread is not alive");
+
+        /* Invoke a Reference constructor, passing null for the queue */
+        fork(new Runnable() {
+            public void run() {
+                r = new WeakReference(new Object(), null);
+            }});
+
+        /* Force the reference to be cleared and enqueued by the GC */
+        for (int i = 0;; i++) {
+            Thread.sleep(10);
+            System.gc();
+            if (r.get() == null) break;
+            if (i >= 10)
+                throw new Exception("Couldn't cause weak ref to be cleared");
+        }
+
+        /* Check that the handler is still alive */
+        if (!refHandler.isAlive())
+            throw new Exception("Reference-handler thread died");
+
+    }
+
+}
diff --git a/jdk/test/java/lang/ref/SoftReference/Bash.java b/jdk/test/java/lang/ref/SoftReference/Bash.java
new file mode 100644
index 0000000..7cc598b
--- /dev/null
+++ b/jdk/test/java/lang/ref/SoftReference/Bash.java
@@ -0,0 +1,73 @@
+/*
+ * Copyright 1997-1998 Sun Microsystems, Inc.  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 Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
+ * CA 95054 USA or visit www.sun.com if you need additional information or
+ * have any questions.
+ */
+
+/* @test
+ * @bug 4076283
+ * @summary java.lang.ref.SoftReference should reliably prevent
+ *          OutOfMemoryErrors
+ * @author Peter Jones
+ * @author Mark Reinhold
+ */
+
+/* If this test fails, an OutOfMemoryError will be thrown */
+
+import java.lang.ref.SoftReference;
+
+
+public class Bash {
+
+    static class TestReference extends SoftReference {
+
+        public static TestReference head;
+        public TestReference next;
+
+        public TestReference(Object referent) {
+            super(referent);
+            next = head;
+            head = this;
+        }
+    }
+
+
+    final static int NUM_BLOCKS = 2048;
+    final static int BLOCK_SIZE = 32768;
+
+
+    public static void main(String[] args) throws Exception {
+
+        for (int i = 0; i < NUM_BLOCKS; ++ i) {
+            TestReference ref = new TestReference(new byte[BLOCK_SIZE]);
+        }
+
+        int emptyCount = 0;
+        int fullCount = 0;
+        for (TestReference r = TestReference.head; r != null; r = r.next) {
+            if (r.get() == null) emptyCount++;
+            else fullCount++;
+        }
+
+        System.err.println(fullCount + " full, " + emptyCount + " empty ");
+
+    }
+
+}
diff --git a/jdk/test/java/lang/ref/SoftReference/Pin.java b/jdk/test/java/lang/ref/SoftReference/Pin.java
new file mode 100644
index 0000000..769cfc2
--- /dev/null
+++ b/jdk/test/java/lang/ref/SoftReference/Pin.java
@@ -0,0 +1,98 @@
+/*
+ * Copyright 1997-2005 Sun Microsystems, Inc.  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 Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
+ * CA 95054 USA or visit www.sun.com if you need additional information or
+ * have any questions.
+ */
+
+/* @test
+ * @bug 4076287
+ * @summary Invoking get on a SoftReference shouldn't pin the referent
+ * @run main/othervm -ms16m -mx16m Pin
+ * @author Peter Jones
+ * @author Mark Reinhold
+ */
+
+
+import java.lang.ref.SoftReference;
+
+public class Pin {
+
+    final static int NUM_BLOCKS = 128;
+    final static int BLOCK_SIZE = 32768;
+
+    public static void main(String[] args) throws Exception {
+
+        SoftReference[] blocks = new SoftReference[NUM_BLOCKS];
+
+        byte[] block;
+
+        System.err.println("Filling array with " + NUM_BLOCKS +
+                           " SoftReferences to blocks of " +
+                           BLOCK_SIZE + " bytes.");
+
+        for (int i = 0; i < NUM_BLOCKS; ++ i) {
+            block = new byte[BLOCK_SIZE];
+            SoftReference ref = new SoftReference(block);
+            blocks[i] = ref;
+        }
+        block = null;
+
+        System.err.println("Allowing SoftReferences to be enqueued.");
+        System.gc();
+        Thread.sleep(1000);
+
+        /* -- Commenting out the following section will hide the bug -- */
+        System.err.println("Invoking get() on SoftReferences.");
+        for (int i = 0; i < NUM_BLOCKS; ++ i) {
+            block = (byte[]) blocks[i].get();
+        }
+        block = null;
+        /* -- end -- */
+
+        System.err.println("Forcing desperate garbage collection...");
+        java.util.Vector chain = new java.util.Vector();
+        try {
+            while (true) {
+                System.gc();
+                int[] hungry = new int[65536];
+                chain.addElement(hungry);
+                Thread.sleep(100);              // yield, for what it's worth
+            }
+        } catch (OutOfMemoryError e) {
+            System.err.println("Got OutOfMemoryError, as expected.");
+        }
+
+        int emptyCount = 0, fullCount = 0;
+        System.err.print("Examining contents of array:");
+        for (int i = 0; i < NUM_BLOCKS; ++ i) {
+            block = (byte[]) blocks[i].get();
+            if (block == null) {
+                emptyCount++;
+            } else {
+                fullCount++;
+            }
+        }
+        System.err.println(" " + emptyCount + " empty, " +
+                           fullCount + " full.");
+        if (emptyCount == 0)
+            throw new Exception("No SoftReference instances were cleared");
+    }
+
+}
diff --git a/jdk/test/java/lang/reflect/Array/ExceedMaxDim.java b/jdk/test/java/lang/reflect/Array/ExceedMaxDim.java
new file mode 100644
index 0000000..e2e41d8
--- /dev/null
+++ b/jdk/test/java/lang/reflect/Array/ExceedMaxDim.java
@@ -0,0 +1,84 @@
+/*
+ * Copyright 1998 Sun Microsystems, Inc.  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 Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
+ * CA 95054 USA or visit www.sun.com if you need additional information or
+ * have any questions.
+ */
+
+/* @test
+ * @bug 4100814
+ * @summary Make sure you can't create an array of dimension > 256.
+ */
+
+import java.lang.reflect.Array;
+
+public class ExceedMaxDim {
+
+    public static void main(String[] args) throws Exception {
+        newInstanceOne();
+        newInstanceMulti();
+        zeroDimension();
+    }
+
+    private static void newInstanceOne() throws Exception {
+        Object o = getArrayOf256Dimensions();
+        try {
+            o = Array.newInstance(o.getClass(), 1);
+        } catch (IllegalArgumentException iae) {
+            System.out.println("success: newInstanceOne test");
+            return;
+        }
+        throw new Exception("NewArray allowed dimensions > MAXDIM");
+    }
+
+    private static void newInstanceMulti() throws Exception {
+        Object o = getArrayOf256Dimensions();
+        try {
+            o = Array.newInstance(o.getClass(), new int[] { 1, 1 });
+            o = Array.newInstance(o.getClass(), new int[] { 1 });
+        } catch (IllegalArgumentException iae) {
+            System.out.println("success: newInstanceMulti test");
+            return;
+        }
+        throw new Exception("MultiNewArray allowed dimensions > MAXDIM");
+    }
+
+    private static void zeroDimension() throws Exception {
+        try {
+            Array.newInstance(Integer.TYPE, new int[0]);
+        } catch (IllegalArgumentException iae) {
+            System.out.println("success: zeroDimension test");
+            return;
+        }
+        throw new Exception("MultiNewArray allowed dimension == 0");
+    }
+
+    private static Object getArrayOf256Dimensions() {
+        /* 1 dimension */
+        Object o = Array.newInstance(Integer.TYPE, 0);
+
+        /* 254 more dimension. */
+        for (int i = 1; i <= 254; i++) {
+            o = Array.newInstance(o.getClass(), 1);
+        }
+
+        /* 255 in all. */
+        return o;
+    }
+}
diff --git a/jdk/test/java/lang/reflect/Assignment/ArrayAssignment.java b/jdk/test/java/lang/reflect/Assignment/ArrayAssignment.java
new file mode 100644
index 0000000..62393ad
--- /dev/null
+++ b/jdk/test/java/lang/reflect/Assignment/ArrayAssignment.java
@@ -0,0 +1,39 @@
+/*
+ * Copyright 1998 Sun Microsystems, Inc.  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 Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
+ * CA 95054 USA or visit www.sun.com if you need additional information or
+ * have any questions.
+ */
+
+/* @test 1.1 98/07/23
+   @bug 4090364
+   @summary Verify the rule for array assignment
+   */
+
+public class ArrayAssignment {
+
+    public static void main(String argv[]) throws Exception {
+        int[][] from = new int[5][5];
+        Object[] to = from;
+        to = new Object[1];
+        if (!to.getClass().isAssignableFrom(from.getClass()))
+            throw new Exception("bad array assignment check in reflection");
+   }
+
+}
diff --git a/jdk/test/java/lang/reflect/Constructor/GenericStringTest.java b/jdk/test/java/lang/reflect/Constructor/GenericStringTest.java
new file mode 100644
index 0000000..4970988
--- /dev/null
+++ b/jdk/test/java/lang/reflect/Constructor/GenericStringTest.java
@@ -0,0 +1,112 @@
+/*
+ * Copyright 2004-2006 Sun Microsystems, Inc.  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 Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
+ * CA 95054 USA or visit www.sun.com if you need additional information or
+ * have any questions.
+ */
+
+/*
+ * @test
+ * @bug 5033583 6316717 6470106
+ * @summary Check toGenericString() and toString() methods
+ * @author Joseph D. Darcy
+ * @compile -source 1.5 GenericStringTest.java
+ * @run main GenericStringTest
+ */
+
+import java.lang.reflect.*;
+import java.lang.annotation.*;
+import java.util.*;
+
+public class GenericStringTest {
+    public static void main(String argv[]) throws Exception{
+        int failures = 0;
+        List<Class<?>> classList = new LinkedList<Class<?>>();
+        classList.add(TestClass1.class);
+        classList.add(TestClass2.class);
+
+
+        for(Class<?> clazz: classList)
+            for(Constructor<?> ctor: clazz.getDeclaredConstructors()) {
+                ExpectedGenericString egs = ctor.getAnnotation(ExpectedGenericString.class);
+                String actual = ctor.toGenericString();
+                System.out.println(actual);
+                if (! egs.value().equals(actual)) {
+                    failures++;
+                    System.err.printf("ERROR: Expected generic string ''%s''; got ''%s''.\n",
+                                      egs.value(), actual);
+                }
+
+                if (ctor.isAnnotationPresent(ExpectedString.class)) {
+                    ExpectedString es = ctor.getAnnotation(ExpectedString.class);
+                    String result = ctor.toString();
+                    if (! es.value().equals(result)) {
+                        failures++;
+                        System.err.printf("ERROR: Expected ''%s''; got ''%s''.\n",
+                                          es.value(), result);
+                    }
+                }
+            }
+
+        if (failures > 0) {
+            System.err.println("Test failed.");
+            throw new RuntimeException();
+        }
+    }
+}
+
+class TestClass1 {
+    @ExpectedGenericString(
+   "TestClass1(int,double)")
+    TestClass1(int x, double y) {}
+
+    @ExpectedGenericString(
+   "private TestClass1(int,int)")
+    private TestClass1(int x, int param2) {}
+
+    @ExpectedGenericString(
+   "private TestClass1(java.lang.Object) throws java.lang.RuntimeException")
+    private TestClass1(Object o) throws RuntimeException {}
+
+    @ExpectedGenericString(
+   "protected <S,T> TestClass1(S,T) throws java.lang.Exception")
+    protected <S, T> TestClass1(S s, T t) throws Exception{}
+
+    @ExpectedGenericString(
+   "TestClass1(java.lang.Object...)")
+    @ExpectedString(
+   "TestClass1(java.lang.Object[])")
+    TestClass1(Object... o){}
+}
+
+class TestClass2<E> {
+    @ExpectedGenericString(
+   "public <T> TestClass2(E,T)")
+    public <T> TestClass2(E e, T t) {}
+}
+
+@Retention(RetentionPolicy.RUNTIME)
+@interface ExpectedGenericString {
+    String value();
+}
+
+@Retention(RetentionPolicy.RUNTIME)
+@interface ExpectedString {
+    String value();
+}
diff --git a/jdk/test/java/lang/reflect/Constructor/TestParameterAnnotations.java b/jdk/test/java/lang/reflect/Constructor/TestParameterAnnotations.java
new file mode 100644
index 0000000..f070cad
--- /dev/null
+++ b/jdk/test/java/lang/reflect/Constructor/TestParameterAnnotations.java
@@ -0,0 +1,99 @@
+/*
+ * Copyright 2005 Sun Microsystems, Inc.  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 Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
+ * CA 95054 USA or visit www.sun.com if you need additional information or
+ * have any questions.
+ */
+
+/*
+ * @test
+ * @bug 6332964
+ * @summary Verify getParameterAnnotations doesn't throw spurious errors
+ * @author Joseph D. Darcy
+ */
+
+import java.lang.reflect.*;
+import java.lang.annotation.*;
+import static java.lang.annotation.RetentionPolicy.*;
+import java.util.Arrays;
+
+public class TestParameterAnnotations {
+    class Inner {
+        public Inner(@Marker Object o) {}
+    }
+
+    static class StaticNested {
+        public StaticNested(@Marker Object o) {}
+    }
+
+    static int visitCtorParameterAnnotations(Class clazz) {
+        int errors = 0;
+        for(Constructor<?> ctor : clazz.getDeclaredConstructors()) {
+            try {
+                System.out.printf("%nNormal:  %s%nGeneric: %s%n",
+                                  ctor.toString(),
+                                  ctor.toGenericString());
+                Annotation[][] annotationArray = ctor.getParameterAnnotations();
+                System.out.println("\tParameter Annotations: " +
+                                   Arrays.deepToString(annotationArray));
+            } catch (AnnotationFormatError afe) {
+                System.err.println("\tWhoops, got an AnnotationFormatError on " +
+                                   ctor.toGenericString());
+                errors++;
+            }
+        }
+        return errors;
+    }
+
+    public static void main(String... argv) {
+        int errors = 0;
+        class LocalClass {
+            LocalClass(@Marker int i){}
+        }
+
+        Object anonymous = new Object() {public String toString(){return "Anonymous";}};
+
+        errors +=
+            visitCtorParameterAnnotations(Inner.class);
+        errors +=
+            visitCtorParameterAnnotations(StaticNested.class);
+        errors +=
+            visitCtorParameterAnnotations(CustomColors.class);
+        errors +=
+            visitCtorParameterAnnotations(TestParameterAnnotations.class);
+        errors +=
+            visitCtorParameterAnnotations(LocalClass.class);
+        errors +=
+            visitCtorParameterAnnotations(anonymous.getClass());
+
+        if (errors > 0)
+            throw new RuntimeException(errors +
+                                       " failures calling Constructor.getParameterAnnotations");
+    }
+}
+
+enum CustomColors {
+    FUCHSIA(5),
+    MULBERRY(6.0d);
+    CustomColors(@Marker int arg) {}
+    CustomColors(double arg) {}
+}
+
+@Retention(RUNTIME)
+    @interface Marker {}
diff --git a/jdk/test/java/lang/reflect/Field/4490864/StaticFieldTest.java b/jdk/test/java/lang/reflect/Field/4490864/StaticFieldTest.java
new file mode 100644
index 0000000..5e764d5
--- /dev/null
+++ b/jdk/test/java/lang/reflect/Field/4490864/StaticFieldTest.java
@@ -0,0 +1,80 @@
+/*
+ * Copyright 2001 Sun Microsystems, Inc.  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 Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
+ * CA 95054 USA or visit www.sun.com if you need additional information or
+ * have any questions.
+ */
+
+/*
+  @test
+  @bug 4490864
+  @summary Verify reflective static field accesses (sanity check)
+  @author Kenneth Russell
+*/
+
+import java.lang.reflect.*;
+
+public class StaticFieldTest {
+    private static byte   byteField;
+    private static short  shortField;
+    private static char   charField;
+    private static int    intField;
+    private static long   longField;
+    private static float  floatField;
+    private static double doubleField;
+    private static String stringField;
+
+    private static Field getAccessibleField(String name) throws NoSuchFieldException {
+        Field f = StaticFieldTest.class.getDeclaredField(name);
+        f.setAccessible(true);
+        return f;
+    }
+
+    public static void main(String[] args) throws Exception {
+        Field byteField   = getAccessibleField("byteField");
+        Field shortField  = getAccessibleField("shortField");
+        Field charField   = getAccessibleField("charField");
+        Field intField    = getAccessibleField("intField");
+        Field longField   = getAccessibleField("longField");
+        Field floatField  = getAccessibleField("floatField");
+        Field doubleField = getAccessibleField("doubleField");
+        Field stringField = getAccessibleField("stringField");
+
+        byteField.setByte    (null, (byte) 77);
+        shortField.setShort  (null, (short) 77);
+        charField.setChar    (null, (char) 77);
+        intField.setInt      (null, (int) 77);
+        longField.setLong    (null, (long) 77);
+        floatField.setFloat  (null, (float) 77);
+        doubleField.setDouble(null, (double) 77);
+        String myString = "Hello, world";
+        stringField.set      (null, myString);
+
+        if (byteField.getByte(null)     != 77) throw new RuntimeException("Test failed");
+        if (shortField.getShort(null)   != 77) throw new RuntimeException("Test failed");
+        if (charField.getChar(null)     != 77) throw new RuntimeException("Test failed");
+        if (intField.getInt(null)       != 77) throw new RuntimeException("Test failed");
+        if (longField.getLong(null)     != 77) throw new RuntimeException("Test failed");
+        if (floatField.getFloat(null)   != 77) throw new RuntimeException("Test failed");
+        if (doubleField.getDouble(null) != 77) throw new RuntimeException("Test failed");
+        if (stringField.get(null)       != myString) throw new RuntimeException("Test failed");
+
+        // Test passed.
+    }
+}
diff --git a/jdk/test/java/lang/reflect/Field/4498653/StaticInitializerTest.java b/jdk/test/java/lang/reflect/Field/4498653/StaticInitializerTest.java
new file mode 100644
index 0000000..796e46c
--- /dev/null
+++ b/jdk/test/java/lang/reflect/Field/4498653/StaticInitializerTest.java
@@ -0,0 +1,45 @@
+/*
+ * Copyright 2001 Sun Microsystems, Inc.  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 Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
+ * CA 95054 USA or visit www.sun.com if you need additional information or
+ * have any questions.
+ */
+
+/*
+  @test
+  @bug 4498653
+  @summary Verify reflective static field accesses cause static initialization
+  @author Michael Warres
+*/
+
+import java.lang.reflect.*;
+
+class Bar {
+    static { System.out.println("Bar.<clinit> called"); }
+    static Object obj = new Object();
+}
+
+public class StaticInitializerTest {
+    public static void main(String[] args) throws Exception {
+        Class cl = Class.forName("Bar", false, StaticInitializerTest.class.getClassLoader());
+        if (cl.getDeclaredField("obj").get(null) == null) {
+            throw new Error();
+        }
+    }
+}
diff --git a/jdk/test/java/lang/reflect/Field/GenericStringTest.java b/jdk/test/java/lang/reflect/Field/GenericStringTest.java
new file mode 100644
index 0000000..f25a6ca
--- /dev/null
+++ b/jdk/test/java/lang/reflect/Field/GenericStringTest.java
@@ -0,0 +1,80 @@
+/*
+ * Copyright 2004 Sun Microsystems, Inc.  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 Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
+ * CA 95054 USA or visit www.sun.com if you need additional information or
+ * have any questions.
+ */
+
+/*
+ * @test
+ * @bug 5033583
+ * @summary Check toGenericString() method
+ * @author Joseph D. Darcy
+ * @compile -source 1.5 GenericStringTest.java
+ * @run main GenericStringTest
+ */
+
+import java.lang.reflect.*;
+import java.lang.annotation.*;
+import java.util.*;
+
+public class GenericStringTest {
+    public static void main(String argv[]) throws Exception {
+        int failures = 0;
+        List<Class> classList = new LinkedList<Class>();
+        classList.add(TestClass1.class);
+        classList.add(TestClass2.class);
+
+
+        for(Class clazz: classList)
+            for(Field field: clazz.getDeclaredFields()) {
+                ExpectedString es = field.getAnnotation(ExpectedString.class);
+                String genericString = field.toGenericString();
+                System.out.println(genericString);
+                if (! es.value().equals(genericString)) {
+                    failures ++;
+                    System.err.printf("ERROR: Expected ''%s''; got ''%s''.\n",
+                                      es.value(), genericString);
+                }
+            }
+
+        if (failures > 0) {
+            System.err.println("Test failed.");
+            throw new RuntimeException();
+        }
+    }
+}
+
+class TestClass1 {
+    @ExpectedString("int TestClass1.field1")
+        int field1;
+
+    @ExpectedString("private static java.lang.String TestClass1.field2")
+        static private String field2;
+}
+
+class TestClass2<E> {
+    @ExpectedString("public E TestClass2.field1")
+        public E field1;
+}
+
+@Retention(RetentionPolicy.RUNTIME)
+@interface ExpectedString {
+    String value();
+}
diff --git a/jdk/test/java/lang/reflect/Field/Set.java b/jdk/test/java/lang/reflect/Field/Set.java
new file mode 100644
index 0000000..11993cf
--- /dev/null
+++ b/jdk/test/java/lang/reflect/Field/Set.java
@@ -0,0 +1,264 @@
+/*
+ * Copyright 1999-2004 Sun Microsystems, Inc.  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 Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
+ * CA 95054 USA or visit www.sun.com if you need additional information or
+ * have any questions.
+ */
+
+/**
+ * @test
+ * @bug 4250960 5044412
+ * @summary Should not be able to set final fields through reflection unless setAccessible(true) passes and is not static
+ * @author David Bowen (modified by Doug Lea)
+*/
+
+import java.lang.reflect.*;
+
+public class Set {
+    public static void main(String[] argv) throws Throwable {
+        boolean failed = false;
+        Test t = new Test();
+        if (!t.testPrimitive()) {
+            failed = true; System.out.println("FAILED: testPrimitive()");
+        }
+        if (!t.testAccessiblePrimitive()) {
+            failed = true; System.out.println("FAILED: testAccessiblePrimitive()");
+        }
+        if (!t.testVolatilePrimitive()) {
+            failed = true; System.out.println("FAILED: testVolatilePrimitive()");
+        }
+
+
+        if (!t.testStaticPrimitive()) {
+            failed = true; System.out.println("FAILED: testStaticPrimitive()");
+        }
+        if (!t.testAccessibleStaticPrimitive()) {
+            failed = true; System.out.println("FAILED: testAccessibleStaticPrimitive()");
+        }
+
+        if (!t.testObject()) {
+            failed = true; System.out.println("FAILED: testObject()");
+        }
+        if (!t.testAccessibleObject()) {
+            failed = true; System.out.println("FAILED: testAccessibleObject()");
+        }
+
+        if (!t.testVolatileObject()) {
+            failed = true; System.out.println("FAILED: testVolatileObject()");
+        }
+
+        if (!t.testStaticObject()) {
+            failed = true; System.out.println("FAILED: testStaticObject()");
+        }
+        if (!t.testAccessibleStaticObject()) {
+            failed = true; System.out.println("FAILED: testAccessibleStaticObject()");
+        }
+
+        if (failed) {
+            throw( new Throwable("Test for Field.set FAILED"));
+        }
+    }
+
+}
+
+class Test {
+
+    private final int i;
+    private final Object o;
+
+    public final int ni;
+    public final Object no;
+
+    public volatile int vi;
+    public volatile Object vo;
+
+    private static final int si = 408-343-1407;;
+    private static final Object so = new Object();
+
+    Test() {
+        i = 911;
+        ni = i;
+        vi = i;
+        o = new Object();
+        no = o;
+        vo = o;
+    }
+
+    boolean testPrimitive()
+        throws NoSuchFieldException
+    {
+        try {
+            Field f = this.getClass().getDeclaredField("ni");
+            f.setInt(this, 7);
+            if (ni != 7) {
+                System.out.println("setInt() did not work");
+            }
+            return false;  // FAILED
+        } catch (IllegalAccessException iae) {
+            return true;   // PASSED
+        }
+    }
+
+    boolean testStaticPrimitive()
+        throws NoSuchFieldException
+    {
+        try {
+            Field f = this.getClass().getDeclaredField("si");
+            f.setInt(this, 13);
+            if (si != 13) {
+                System.out.println("setInt() did not work for static");
+            }
+            return false;  // FAILED
+        } catch (IllegalAccessException iae) {
+            return true;   // PASSED
+        }
+    }
+
+    boolean testObject()
+        throws NoSuchFieldException
+    {
+        Object saved = no;
+        try {
+            Field f = this.getClass().getDeclaredField("no");
+            f.set(this, new Object());
+            if (no == saved) {
+                System.out.println("set() did not work");
+            }
+            return false;  // FAILED
+        } catch (IllegalAccessException iae) {
+            return true;   // PASSED
+        }
+    }
+
+    boolean testStaticObject()
+        throws NoSuchFieldException
+    {
+        Object saved = so;
+        try {
+            Field f = this.getClass().getDeclaredField("so");
+            f.set(this, new Object());
+            if (so == saved) {
+                System.out.println("set() did not work for static");
+            }
+            return false;  // FAILED
+        } catch (IllegalAccessException iae) {
+            return true;   // PASSED
+        }
+    }
+
+    boolean testAccessiblePrimitive()
+        throws NoSuchFieldException
+    {
+        try {
+            Field f = this.getClass().getDeclaredField("i");
+            f.setAccessible(true);
+            f.setInt(this, 7);
+            if (i != 7) {
+                System.out.println("setInt() did not work");
+            }
+            return true;   // PASSED
+        } catch (IllegalAccessException iae) {
+            return false;  // FAILED
+        }
+    }
+
+    boolean testAccessibleStaticPrimitive()
+        throws NoSuchFieldException
+    {
+        try {
+            Field f = this.getClass().getDeclaredField("si");
+            f.setAccessible(true);
+            f.setInt(this, 13);
+            if (si != 13) {
+                System.out.println("setInt() did not work for static");
+            }
+            return false;  // FAILED
+        } catch (IllegalAccessException iae) {
+            return true;   // PASSED
+        }
+    }
+
+    boolean testAccessibleObject()
+        throws NoSuchFieldException
+    {
+        Object saved = o;
+        try {
+            Field f = this.getClass().getDeclaredField("o");
+            f.setAccessible(true);
+            f.set(this, new Object());
+            if (o == saved) {
+                System.out.println("set() did not work");
+            }
+            return true;   // PASSED
+        } catch (IllegalAccessException iae) {
+            return false;  // FAILED
+        }
+    }
+
+    boolean testAccessibleStaticObject()
+        throws NoSuchFieldException
+    {
+        Object saved = so;
+        try {
+            Field f = this.getClass().getDeclaredField("so");
+            f.setAccessible(true);
+            f.set(this, new Object());
+            if (so == saved) {
+                System.out.println("set() did not work for static");
+            }
+            return false;  // FAILED
+        } catch (IllegalAccessException iae) {
+            return true;   // PASSED
+        }
+    }
+
+    boolean testVolatilePrimitive()
+        throws NoSuchFieldException
+    {
+        try {
+            Field f = this.getClass().getDeclaredField("vi");
+            f.setAccessible(true);
+            f.setInt(this, 7);
+            if (vi != 7) {
+                System.out.println("setInt() did not work");
+            }
+            return true;   // PASSED
+        } catch (IllegalAccessException iae) {
+            return false;  // FAILED
+        }
+    }
+
+
+    boolean testVolatileObject()
+        throws NoSuchFieldException
+    {
+        Object saved = vo;
+        try {
+            Field f = this.getClass().getDeclaredField("vo");
+            f.setAccessible(true);
+            f.set(this, new Object());
+            if (vo == saved) {
+                System.out.println("set() did not work");
+            }
+            return true;   // PASSED
+        } catch (IllegalAccessException iae) {
+            return false;  // FAILED
+        }
+    }
+}
diff --git a/jdk/test/java/lang/reflect/Generics/HashCodeTest.java b/jdk/test/java/lang/reflect/Generics/HashCodeTest.java
new file mode 100644
index 0000000..af91998
--- /dev/null
+++ b/jdk/test/java/lang/reflect/Generics/HashCodeTest.java
@@ -0,0 +1,78 @@
+/*
+ * Copyright 2004 Sun Microsystems, Inc.  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 Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
+ * CA 95054 USA or visit www.sun.com if you need additional information or
+ * have any questions.
+ */
+
+/*
+ * @test
+ * @bug 5097856
+ * @summary Computing hashCode of objects modeling generics shouldn't blow stack
+ * @author Joseph D. Darcy
+ */
+
+import java.util.*;
+import java.lang.reflect.*;
+
+public class HashCodeTest {
+
+    // Mutually recursive interface types
+    interface Edge<N extends Node<? extends Edge<N>>> {
+        void setEndNode(N n);
+    }
+    interface Node<E extends Edge<? extends Node<E>>> {
+        E getOutEdge();
+    }
+
+    public static void main(String argv[]) {
+        List<Class<?>> classes = new ArrayList<Class<?>>();
+        Set<TypeVariable> typeVariables = new HashSet<TypeVariable>();
+
+        classes.add(java.lang.Class.class);// Simple case
+        classes.add(java.util.Map.class);
+        classes.add(java.lang.Enum.class); // Contains f-bound
+        classes.add(Edge.class);
+        classes.add(Node.class);
+
+        for(Class<?> clazz: classes) {
+            System.out.println(clazz);
+
+            for (TypeVariable<?> tv : clazz.getTypeParameters()) {
+                int hc = tv.hashCode();
+                typeVariables.add(tv);
+                System.out.printf("\t%s 0x%x (%d)%n", tv.getName(), hc, hc);
+            }
+        }
+
+        // Loop over classes again, making sure all type variables are
+        // already present
+        int count = 0;
+        for(Class<?> clazz: classes) {
+            for (TypeVariable<?> tv : clazz.getTypeParameters()) {
+                if (!typeVariables.remove(tv))
+                    throw new RuntimeException("Type variable " + tv + " not found.");
+            }
+        }
+
+        if (typeVariables.size() != 0 )
+            throw new RuntimeException("Unexpected number of type variables.");
+
+    }
+}
diff --git a/jdk/test/java/lang/reflect/Generics/Probe.java b/jdk/test/java/lang/reflect/Generics/Probe.java
new file mode 100644
index 0000000..79628a3
--- /dev/null
+++ b/jdk/test/java/lang/reflect/Generics/Probe.java
@@ -0,0 +1,143 @@
+/*
+ * Copyright 2004-2006 Sun Microsystems, Inc.  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 Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
+ * CA 95054 USA or visit www.sun.com if you need additional information or
+ * have any questions.
+ */
+
+/*
+ * @test
+ * @bug 5003916
+ * @summary Testing parsing of signatures attributes of nested classes
+ * @author Joseph D. Darcy
+ * @compile -source 1.5 Probe.java
+ * @run main Probe
+ */
+
+import java.lang.reflect.*;
+import java.lang.annotation.*;
+
+@Classes({
+        "java.util.concurrent.FutureTask",
+        "java.util.concurrent.ConcurrentHashMap$EntryIterator",
+        "java.util.concurrent.ConcurrentHashMap$KeyIterator",
+        "java.util.concurrent.ConcurrentHashMap$ValueIterator",
+        "java.util.AbstractList$ListItr",
+        "java.util.EnumMap$EntryIterator",
+        "java.util.EnumMap$KeyIterator",
+        "java.util.EnumMap$ValueIterator",
+        "java.util.IdentityHashMap$EntryIterator",
+        "java.util.IdentityHashMap$KeyIterator",
+        "java.util.IdentityHashMap$ValueIterator",
+        "java.util.WeakHashMap$EntryIterator",
+        "java.util.WeakHashMap$KeyIterator",
+        "java.util.WeakHashMap$ValueIterator",
+        "java.util.TreeMap$EntryIterator",
+        "java.util.TreeMap$KeyIterator",
+        "java.util.TreeMap$ValueIterator",
+        "java.util.HashMap$EntryIterator",
+        "java.util.HashMap$KeyIterator",
+        "java.util.HashMap$ValueIterator",
+        "java.util.LinkedHashMap$EntryIterator",
+        "java.util.LinkedHashMap$KeyIterator",
+        "java.util.LinkedHashMap$ValueIterator",
+        "javax.crypto.SunJCE_c",
+        "javax.crypto.SunJCE_e",
+        "javax.crypto.SunJCE_f",
+        "javax.crypto.SunJCE_j",
+        "javax.crypto.SunJCE_k",
+        "javax.crypto.SunJCE_l"
+        })
+public class Probe {
+    public static void main (String[] args) throws Throwable {
+        String [] names = (Probe.class).getAnnotation(Classes.class).value();
+
+        int errs = 0;
+        for(String name: names) {
+            System.out.println("\nCLASS " + name);
+            Class c = Class.forName(name, false, null);
+            errs += probe(c);
+            System.out.println(errs == 0 ? "  ok" : "  ERRORS:" + errs);
+        }
+
+        if (errs > 0 )
+            throw new RuntimeException("Errors during probing.");
+    }
+
+    static int probe (Class c) {
+        int errs = 0;
+
+        try {
+            c.getTypeParameters();
+            c.getGenericSuperclass();
+            c.getGenericInterfaces();
+        } catch (Throwable t) {
+            errs++;
+            System.err.println(t);
+        }
+
+        Field[] fields = c.getDeclaredFields();
+        if (fields != null)
+            for(Field field: fields) {
+                try {
+                    field.getGenericType();
+                } catch (Throwable t) {
+                    errs++;
+                    System.err.println("FIELD " + field);
+                    System.err.println(t);
+                }
+            }
+
+        Method[] methods = c.getDeclaredMethods();
+        if (methods != null)
+            for(Method method: methods) {
+                try {
+                    method.getTypeParameters();
+                    method.getGenericReturnType();
+                    method.getGenericParameterTypes();
+                    method.getGenericExceptionTypes();
+                } catch (Throwable t) {
+                    errs++;
+                    System.err.println("METHOD " + method);
+                    System.err.println(t);
+                }
+            }
+
+        Constructor[] ctors = c.getDeclaredConstructors();
+        if (ctors != null)
+            for(Constructor ctor: ctors) {
+                try {
+                    ctor.getTypeParameters();
+                    ctor.getGenericParameterTypes();
+                    ctor.getGenericExceptionTypes();
+                } catch (Throwable t) {
+                    errs++;
+                    System.err.println("CONSTRUCTOR " + ctor);
+                    System.err.println(t);
+                }
+            }
+
+        return errs;
+    }
+}
+
+@Retention(RetentionPolicy.RUNTIME)
+@interface Classes {
+    String [] value(); // list of classes to probe
+}
diff --git a/jdk/test/java/lang/reflect/Generics/StringsAndBounds.java b/jdk/test/java/lang/reflect/Generics/StringsAndBounds.java
new file mode 100644
index 0000000..d49a5ea
--- /dev/null
+++ b/jdk/test/java/lang/reflect/Generics/StringsAndBounds.java
@@ -0,0 +1,96 @@
+/*
+ * Copyright 2004 Sun Microsystems, Inc.  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 Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
+ * CA 95054 USA or visit www.sun.com if you need additional information or
+ * have any questions.
+ */
+
+/*
+ * @test
+ * @bug 5015676 4987888 4997464
+ * @summary Testing upper bounds and availability of toString methods
+ * @author Joseph D. Darcy
+ * @compile -source 1.5 StringsAndBounds.java
+ * @run main StringsAndBounds
+ */
+
+import java.lang.reflect.*;
+import java.util.List;
+import java.util.Collection;
+
+class A<T> {
+    class B<U> {}
+}
+
+class Test<T> {
+    static class Inner1<U> {
+        void bar(U[] array1) { return;}
+    }
+
+    class Inner2<V> {
+        List<?> foo2(List<? extends V> t) {
+            return null;
+        }
+    }
+
+    static <S extends Object & Comparable<? super S> > S max(Collection<? extends S> coll) {
+        return null;
+    }
+
+    List<? extends T> foo(List<? super T> t) {
+        return null;
+    }
+}
+
+public class StringsAndBounds {
+    public void f(A<String>.B<Integer> x) {
+    }
+
+    public <T>  void g(T a) {return ;}
+
+    static void scanner(Class clazz) {
+        System.out.println("\n\nScanning " + clazz.getName());
+
+        for(Class c: clazz.getDeclaredClasses()) {
+            scanner(c);
+        }
+
+        for(Method m: clazz.getDeclaredMethods()) {
+            System.out.println("\nMethod:\t" + m.toString()); // Need toGenericString?
+            System.out.println("\tReturn Type: " + m.getGenericReturnType().toString() );
+            for(Type p: m.getGenericParameterTypes()) {
+                if (p instanceof WildcardType) { // Check upper bounds
+                    Type[] upperBounds = ((WildcardType)p).getUpperBounds();
+                    if (upperBounds.length < 1 ||
+                        upperBounds[0] == null)
+                        throw new RuntimeException("Malformed upper bounds: " + p);
+
+                }
+
+                System.out.println("\tParameter: " + p.toString());
+            }
+        }
+    }
+
+    public static void main(String[] argv) throws Exception {
+        scanner(StringsAndBounds.class);
+        scanner(A.B.class);
+        scanner(Test.class);
+    }
+}
diff --git a/jdk/test/java/lang/reflect/Generics/TestC1.java b/jdk/test/java/lang/reflect/Generics/TestC1.java
new file mode 100644
index 0000000..756a4c6
--- /dev/null
+++ b/jdk/test/java/lang/reflect/Generics/TestC1.java
@@ -0,0 +1,340 @@
+/*
+ * Copyright 2003 Sun Microsystems, Inc.  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 Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
+ * CA 95054 USA or visit www.sun.com if you need additional information or
+ * have any questions.
+ */
+
+/*
+* @test
+* @bug 4891872
+* @summary Some tests for the generic core reflection api.
+* @author Gilad Bracha
+* @compile -source 1.5 TestC1.java
+* @run main/othervm -ea TestC1
+*/
+
+
+import java.lang.reflect.*;
+
+
+abstract class C1<T> {
+
+    public T ft;
+    public C1<T> fc1t;
+    public C1 fc1;
+
+    public C1(T t) {}
+
+    public abstract  C1<T> mc1t(T t, C1<T> c1t, C1 c1);
+
+    public abstract C1 mc1();
+
+    public abstract T mt(T t);
+
+}
+
+public class TestC1 {
+
+    static Class<C1> cls = C1.class;
+    static {
+        TestC1.class.getClassLoader().setDefaultAssertionStatus(true);
+    }
+
+
+
+    public static void main(String[] args) throws Throwable {
+        testSuperclass();
+        testSuperInterfaces();
+        testTypeParameters();
+        testMethods();
+        testConstructor();
+        testFields();
+    }
+
+    static void testSuperclass() {
+        System.out.println("testing superclass");
+        Type sc = cls.getGenericSuperclass();
+        assert
+            (sc == Object.class) :
+            "The generic superclass of C1 should be Object";
+    }
+
+    static void testSuperInterfaces() {
+        System.out.println("testing superinterfaces");
+        Type[] sis = cls.getGenericInterfaces();
+        assert
+            (sis.length == 0) :
+            "C1 should have no generic superinterfaces";
+    }
+
+    static void testTypeParameters() {
+        System.out.println("testing type parameters");
+        TypeVariable[] tvs = cls.getTypeParameters();
+        assert
+            tvs.length == 1 :
+            "C1 should have one type parameter";
+        TypeVariable tv = tvs[0];
+        Type[] bs = tv.getBounds();
+        assert
+            bs.length == 1 :
+            "T should have one bound";
+        assert
+            bs[0] == Object.class :
+            "The default bound of a type variable should be Object";
+    }
+
+    static void testMethods() throws NoSuchMethodException {
+        System.out.println("testing methods");
+        Class[] params1 = new Class[3];
+        params1[0] = Object.class;
+        params1[1] = cls;
+        params1[2] = cls;
+
+        Class[] params3 = new Class[1];
+        params3[0] = Object.class;
+
+        Method mc1t = cls.getMethod("mc1t", params1);
+        Method mc1 = cls.getMethod("mc1", new Class[0]);
+        Method mt = cls.getMethod("mt", params3);
+
+        Type rt_mc1t = mc1t.getGenericReturnType();
+        Type rt_mc1 = mc1.getGenericReturnType();
+        Type rt_mt = mt.getGenericReturnType();
+
+        Type[] pt_mc1t = mc1t.getGenericParameterTypes();
+
+        assert
+            pt_mc1t.length == 3 :
+            "C1.mc1t has three parameters";
+        Type p1_mc1t = pt_mc1t[0];
+        assert p1_mc1t != null;
+        assert
+            p1_mc1t instanceof TypeVariable :
+            "Generic type of the 1st parameter of mc1t(T) is a type variable";
+        TypeVariable tv = (TypeVariable) p1_mc1t;
+
+        assert
+            tv.getName().equals("T") :
+            "Name of 1st type parameter of mc1t is T, not " + tv.getName();
+        Type[] bs = tv.getBounds();
+        assert
+            bs.length == 1 :
+            "T should have one bound (mc1t)";
+        assert
+            bs[0] == Object.class :
+            "The bound of T should be Object (mc1t)";
+
+        Type p2_mc1t = pt_mc1t[1];
+
+        assert
+            p2_mc1t instanceof ParameterizedType :
+            "The type of parameter 2 of mc1t is a parameterized type";
+        ParameterizedType pt = (ParameterizedType) p2_mc1t;
+        assert
+            pt.getRawType() == cls :
+            "Type of parameter 2 of mc1t is instantiation of C1";
+        assert
+            pt.getOwnerType() == null :
+            "Type of parameter 2 of mc1t is has null owner";
+
+        Type[] tas = pt.getActualTypeArguments();
+        assert
+            tas.length == 1 :
+            "The type of parameter 2 of mc1t has one type argument";
+        Type ta = tas[0];
+
+        assert
+            ta instanceof TypeVariable :
+            "The actual type arg of C1<T> is a type variable (mc1t)";
+        tv = (TypeVariable) ta;
+        assert
+            tv.getName().equals("T") :
+            "mc1t: Name of the type arg of C1<T> is T, not " + tv.getName();
+        bs = tv.getBounds();
+        assert
+            bs.length == 1 :
+            "mc1t: The type argument of C1<T>  should have one bound";
+        assert
+            bs[0] == Object.class :
+            "mc1t: The bound of the type arg of C1<T> should be Object";
+
+        Type p3_mc1t = pt_mc1t[2];
+
+        assert
+            p3_mc1t == cls :
+            "Type of parameter 3 of mc1t is C1";
+
+        Type[] pt_mc1 = mc1.getGenericParameterTypes();
+        assert
+            pt_mc1.length == 0 :
+            "C1.mc1 has zero parameters";
+
+        Type[] pt_mt = mt.getGenericParameterTypes();
+        assert
+            pt_mt.length == 1 :
+            "C1.mt has one parameter";
+        Type p_mt = pt_mt[0];
+        assert
+            p_mt instanceof TypeVariable :
+            "The generic type of the parameter of mt(T) is a type variable";
+        tv = (TypeVariable) p_mt;
+        assert
+            tv.getName().equals("T") :
+            "The name of the type parameter of mt is T, not " + tv.getName();
+        bs = tv.getBounds();
+        assert
+            bs.length == 1 :
+            "T should have one bound";
+        assert
+            bs[0] == Object.class :
+            "The bound of T should be Object";
+
+        Type[] et_mc1t = mc1t.getGenericExceptionTypes();
+        assert
+            et_mc1t.length == 0 :
+            "Method C1.mc1t should have no generic exception types";
+
+        Type[] et_mc1 = mc1.getGenericExceptionTypes();
+        assert
+            et_mc1.length == 0 :
+            "Method C1.mc1 should have no generic exception types";
+
+        Type[] et_mt = mt.getGenericExceptionTypes();
+
+        assert
+            et_mt.length == 0 :
+            "Method C1.mt should have no generic exception types";
+
+
+        TypeVariable[] tv_mc1t = mc1t.getTypeParameters();
+        assert
+            tv_mc1t.length == 0 :
+            "Method C1.mc1t should have no type parameters";
+
+        TypeVariable[] tv_mc1 = mc1.getTypeParameters();
+        assert
+            tv_mc1.length == 0 :
+            "Method C1.mc1 should have no type parameters";
+
+        TypeVariable[] tv_mt = mt.getTypeParameters();
+        assert
+            tv_mt.length == 0 :
+            "Method C1.mt should have no type parameters";
+    }
+
+
+    static void testFields() throws NoSuchFieldException{
+        System.out.println("testing fields");
+        Field ft = cls. getField("ft");
+        Field fc1t = cls. getField("fc1t");
+        Field fc1 = cls. getField("fc1");
+
+        Type gt_ft = ft.getGenericType();
+        assert
+            gt_ft instanceof TypeVariable :
+            "The generic type of C1.ft is a type variable";
+        TypeVariable tv = (TypeVariable) gt_ft;
+        assert
+            tv.getName().equals("T") :
+            "The name of the type of ft is T, not " + tv.getName();
+        Type[] bs = tv.getBounds();
+        assert
+            bs.length == 1 :
+            "The type of ft should have one bound";
+        assert
+            bs[0] == Object.class :
+            "The bound of the type of ft should be Object";
+
+        Type gt_fc1t = fc1t.getGenericType();
+        assert
+            gt_fc1t instanceof ParameterizedType :
+            "The generic type of C1.fc1t is a parameterized type";
+        ParameterizedType pt = (ParameterizedType) gt_fc1t;
+        assert
+            pt.getRawType() == cls :
+            "Type of C1.fc1t is instantiation of C1";
+        assert
+            pt.getOwnerType() == null :
+            "Type of C1.fc1t is has null owner";
+        Type[] tas = pt.getActualTypeArguments();
+        assert
+            tas.length == 1 :
+            "The type of fc1t has one type argument";
+        Type ta = tas[0];
+
+        assert
+            ta instanceof TypeVariable :
+            "The actual type arg of C1<T> is a type variable";
+        tv = (TypeVariable) ta;
+        assert
+            tv.getName().equals("T") :
+            "The name of the type arg of C1<T> is T, not " + tv.getName();
+        bs = tv.getBounds();
+        assert
+            bs.length == 1 :
+            "The type argument of C1<T>  should have one bound";
+        assert
+            bs[0] == Object.class :
+            "The bound of the type arg of C1<T> should be Object";
+
+        Type gt_fc1 = fc1.getGenericType();
+        assert
+            gt_fc1 == cls :
+            " Type of C1.fc1 should be C1";
+    }
+
+    static void testConstructor() throws NoSuchMethodException {
+        System.out.println("testing constructors");
+        Class[] params = new Class[1];
+        params[0] = Object.class;
+        Constructor<C1> con = cls.getDeclaredConstructor(params);
+
+        Type[] pt_con = con.getGenericParameterTypes();
+        assert
+            pt_con.length == 1 :
+            "Constructor C1(T) should have one generic parameter type";
+        Type pt = pt_con[0];
+        assert
+            pt instanceof TypeVariable :
+            "The generic type of the parameter of C1(T) is a type variable";
+        TypeVariable tv = (TypeVariable) pt;
+        assert
+            tv.getName().equals("T") :
+            "The name of the type parameter of C is T, not " + tv.getName();
+        Type[] bs = tv.getBounds();
+        assert
+            bs.length == 1 :
+            "T should have one bound";
+        assert
+            bs[0] == Object.class :
+            "The bound of T should be Object";
+
+        Type[] et_con = con.getGenericExceptionTypes();
+        assert
+            et_con.length == 0 :
+            "Constructor C1(T) should have no generic exception types";
+
+        TypeVariable[] tv_con = con.getTypeParameters();
+        assert
+            tv_con.length == 0 :
+            "Constructor C1(T) should have no type parameters";
+
+    }
+}
diff --git a/jdk/test/java/lang/reflect/Generics/TestC2.java b/jdk/test/java/lang/reflect/Generics/TestC2.java
new file mode 100644
index 0000000..d42671b
--- /dev/null
+++ b/jdk/test/java/lang/reflect/Generics/TestC2.java
@@ -0,0 +1,653 @@
+/*
+ * Copyright 2003 Sun Microsystems, Inc.  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 Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
+ * CA 95054 USA or visit www.sun.com if you need additional information or
+ * have any questions.
+ */
+
+/*
+* @test
+* @bug 4891872
+* @summary Some tests for the generic core reflection api.
+* @author Gilad Bracha
+* @compile -source 1.5 TestC2.java
+* @run main/othervm -ea TestC2
+*/
+
+
+import java.lang.reflect.*;
+
+
+abstract class C0<T> {
+
+    public T ft;
+    public C0<T> fc1t;
+    public C0 fc1;
+
+    public C0(){}
+    public C0(T t) {}
+
+    public abstract  C0<T> mc1t(T t, C0<T> c1t, C0 c1);
+
+    public abstract C0 mc1();
+
+    public abstract T mt(T t);
+
+}
+
+interface I1<X1, X2> extends I3 {
+
+    X1 foo(X2 x2);
+}
+
+interface I2<E1, E2 extends Throwable, E3> {
+
+
+    E1 bar(E3 e3) throws E2;
+
+}
+
+interface I3 {
+
+
+}
+
+
+abstract class C2<T1 extends C2<T1, T2, T3>, T2 extends C0<T2>,
+                                                        T3 extends Throwable>
+    extends C0<T1>
+    implements I1<T1, T2>, I2<T1, T3, T2>, I3
+{
+
+    public T1 ft;
+    public C0<String> fc1t;
+    public C0 fc1;
+    public int fi;
+
+    public C2(T2 t2) {}
+    public <T> C2(T t) {}
+    public <T1, T2, T3, T4> C2(T1 t1, T2 t2, T4 t4) {}
+    public C2() throws T3 {}
+
+    public abstract <T>  C0<T> mc1t(T3 t3, C0<T> c1t, C0 c1);
+
+    public abstract <E, R> C0 mc1(E e);
+
+    public abstract T1 mt(T2 t);
+
+}
+
+public class TestC2 {
+
+    static Class<C2> cls = C2.class;
+
+
+    public static void main(String[] args) throws Throwable {
+        testSuperclass();
+        testSuperInterfaces();
+        testTypeParameters();
+        testMethods();
+        testConstructors();
+        testFields();
+    }
+
+    static void testSuperclass() {
+
+        System.out.println("testing superclass");
+        Type sc = cls.getGenericSuperclass();
+        assert
+            sc instanceof ParameterizedType :
+            "Superclass of C2 should be a parameterized type";
+        ParameterizedType psc = (ParameterizedType) sc;
+        assert
+            ((psc.getRawType() == C0.class) ) :
+            "The raw generic superclass of C2 should be C0";
+
+        Type[] tas = psc.getActualTypeArguments();
+        assert
+            tas.length == 1 :
+            "Superclass of C2 should have one type argument";
+
+        Type t = tas[0];
+
+        assert
+            t instanceof TypeVariable :
+            "Type argument to superclass of C2 should be a type variable";
+
+        TypeVariable tv = (TypeVariable) t;
+        assert
+            tv.getName().equals("T1") :
+            "Name of type argument to superclass of C2 should be T1";
+        Type[] bs = tv.getBounds();
+        assert
+            bs.length == 1 :
+            "T1 has one bound (superclass)";
+        t = bs[0];
+        assert
+            t instanceof ParameterizedType :
+            "Bound of C0 should be a parameterized type";
+        ParameterizedType pt = (ParameterizedType) t;
+
+        assert
+            ((pt.getRawType() == C2.class) ) :
+            "The raw bound of T1 should be C2";
+
+        tas = pt.getActualTypeArguments();
+        assert
+            tas.length == 3 :
+            "Bound of T1 should have three type arguments";
+        assert
+            tas[0] instanceof TypeVariable :
+            "First argument to bound of T1 is a type variable";
+        assert
+            tas[1] instanceof TypeVariable :
+            "Second argument to bound of T1 is a type variable";
+        assert
+            tas[2] instanceof TypeVariable :
+            "Third argument to bound of T1 is a type variable";
+
+        TypeVariable tv1 = (TypeVariable) tas[0];
+        TypeVariable tv2 = (TypeVariable) tas[1];
+        TypeVariable tv3 = (TypeVariable) tas[2];
+
+        assert
+            tv1.getName().equals("T1"):
+            "First type arg to bound of T1 is T1";
+        assert
+            tv2.getName().equals("T2"):
+            "Seconmd type arg to bound of T1 is T2";
+        assert
+            tv3.getName().equals("T3"):
+            "Third type arg to bound of T1 is T3";
+
+
+    }
+
+    static void testSuperInterfaces() {
+        System.out.println("testing superinterfaces");
+        Type[] sis = cls.getGenericInterfaces();
+        assert
+            ((sis.length == 3)):
+            "C2 should have three generic superinterfaces";
+
+        Type t = sis[0];
+        assert
+            t instanceof ParameterizedType :
+            "First superinterface of C2 should be a parameterized type";
+        ParameterizedType pt = (ParameterizedType) t;
+        assert
+            pt.getRawType() == I1.class :
+            "First super interface of C2 is instantiation of I1";
+        Type[] tas = pt.getActualTypeArguments();
+        assert
+            tas.length == 2 :
+            "First super interface of C2 has 2 type arguments";
+
+        t = sis[1];
+        assert
+            t instanceof ParameterizedType :
+            "Second superinterface of C2 should be a parameterized type";
+        pt = (ParameterizedType) t;
+        assert
+            pt.getRawType() == I2.class :
+            "Second super interface of C2 is instantiation of I2";
+        tas = pt.getActualTypeArguments();
+        assert
+            tas.length == 3 :
+            "Second super interface of C2 has 3 type arguments";
+
+        t = sis[2];
+        assert
+            t == I3.class :
+            "Third superinterface of C2 is I3";
+
+        // Test interfaces themselves
+
+        TypeVariable[] tvs = I1.class.getTypeParameters();
+        assert
+            tvs.length == 2 :
+            "I3 has two formal type parameters";
+        assert
+            tvs[0].getName().equals("X1") :
+            "Name of first formal type arg of I1 is X1";
+        assert
+            tvs[1].getName().equals("X2") :
+            "Name of second formal type arg of I1 is X2";
+
+        assert
+            I1.class.getGenericSuperclass() == I1.class.getSuperclass() :
+            "The generic and non-generic superclasses of an interface must be the same";
+        sis = I1.class.getGenericInterfaces();
+        assert
+            sis.length == 1 :
+            "I1 has one generic superinterface";
+        assert
+            sis[0] == I3.class :
+            "Superinterface of I1 is I3";
+
+        tvs = I2.class.getTypeParameters();
+        assert
+            tvs.length == 3 :
+            "I3 has three formal type parameters";
+        assert
+            tvs[0].getName().equals("E1") :
+            "Name of first formal type arg of I2 is E1";
+        assert
+            tvs[1].getName().equals("E2") :
+            "Name of second formal type arg of I2 is E2";
+        assert
+            tvs[2].getName().equals("E3") :
+            "Name of third formal type arg of I2 is E3";
+
+        assert
+            I2.class.getGenericSuperclass() == I2.class.getSuperclass() :
+            "The generic and non-generic superclasses of an interface must be the same";
+
+        tvs = I3.class.getTypeParameters();
+        assert
+            tvs.length == 0 :
+            "I3 has no formal type parameters";
+
+        assert
+            I3.class.getGenericSuperclass() == I3.class.getSuperclass() :
+            "The generic and non-generic superclasses of an interface must be the same";
+
+
+    }
+
+    static void testTypeParameters() {
+        System.out.println("testing type parameters");
+        TypeVariable[] tvs = cls.getTypeParameters();
+        assert
+            tvs.length == 3 :
+            "C2 should have three type parameters";
+        TypeVariable tv = tvs[0];
+        Type[] bs = tv.getBounds();
+        assert
+            bs.length == 1 :
+            "T1 should have one bound";
+        assert
+            bs[0] instanceof ParameterizedType :
+            "The bound of T1 should be a parameterized type";
+
+        tv = tvs[1];
+        bs = tv.getBounds();
+        assert
+            bs.length == 1 :
+            "T2 should have one bound";
+        assert
+            bs[0] instanceof ParameterizedType :
+            "The bound of T2 should be a parameterized type";
+
+        tv = tvs[2];
+        bs = tv.getBounds();
+        assert
+            bs.length == 1 :
+            "T3 should have one bound";
+        assert
+            bs[0] == Throwable.class :
+            "The bound of T3 should be Throwable";
+    }
+
+    static void testMethods() throws NoSuchMethodException {
+        System.out.println("testing methods");
+
+
+
+        Class[] params1 = new Class[3];
+        params1[0] = Throwable.class;
+        params1[1] = C0.class;
+        params1[2] = C0.class;
+
+        Class[] params2 = new Class[1];
+        params2[0] = Object.class;
+
+        Class[] params3 = new Class[1];
+        params3[0] = C0.class;
+
+        Method mc1t = cls.getMethod("mc1t", params1);
+        Method mc1 = cls.getMethod("mc1", params2);
+        Method mt = cls.getMethod("mt", params3);
+
+        Type rt_mc1t = mc1t.getGenericReturnType();
+        assert
+            rt_mc1t  instanceof ParameterizedType :
+            "The return type of mc1t should be a parameterized type";
+        ParameterizedType pt = (ParameterizedType) rt_mc1t;
+
+        assert
+            pt.getRawType() == C0.class :
+            "The raw return type of mc1t should be C0";
+
+        Type[] tas = pt.getActualTypeArguments();
+        assert
+            tas.length == 1 :
+            "Return type of mc1t should have one type argument";
+        assert
+            tas[0] instanceof TypeVariable :
+            "Type argument of return type of mc1t is a type variable";
+
+        Type rt_mc1 = mc1.getGenericReturnType();
+        assert
+            rt_mc1 == C0.class :
+            "Return type of mc1 is C0";
+
+        Type rt_mt = mt.getGenericReturnType();
+        assert
+            rt_mt instanceof TypeVariable :
+            "Return type of mt is a type variable";
+
+        Type[] pt_mc1t = mc1t.getGenericParameterTypes();
+
+        assert
+            pt_mc1t.length == 3 :
+            "C0.mc1t has three parameters";
+        Type p1_mc1t = pt_mc1t[0];
+        assert p1_mc1t != null;
+        assert
+            p1_mc1t instanceof TypeVariable :
+            "Generic type of the 1st parameter of mc1t(T) is a type variable";
+        TypeVariable tv = (TypeVariable) p1_mc1t;
+
+        assert
+            tv.getName().equals("T3") :
+            "Name of 1st type parameter of mc1t is T3, not " + tv.getName();
+        Type[] bs = tv.getBounds();
+        assert
+            bs.length == 1 :
+            "T3 should have one bound (mc1t)";
+        assert
+            bs[0] == Throwable.class :
+            "The bound of T3 should be Throwable(mc1t)";
+
+        Type p2_mc1t = pt_mc1t[1];
+        assert
+            p2_mc1t instanceof ParameterizedType :
+            "The type of parameter 2 of mc1t is a parameterized type";
+        pt = (ParameterizedType) p2_mc1t;
+        assert
+            pt.getRawType() == C0.class :
+            "Type of parameter 2 of mc1t is instantiation of C0";
+        assert
+            pt.getOwnerType() == null :
+            "Type of parameter 2 of mc1t is has null owner";
+
+        tas = pt.getActualTypeArguments();
+        assert
+            tas.length == 1 :
+            "The type of parameter 2 of mc1t has one type argument";
+        Type ta = tas[0];
+
+        assert
+            ta instanceof TypeVariable :
+            "The actual type arg of C0<T> is a type variable (mc1t)";
+        tv = (TypeVariable) ta;
+        assert
+            tv.getName().equals("T") :
+            "mc1t: Name of the type arg of C0<T> is T, not " + tv.getName();
+        bs = tv.getBounds();
+        assert
+            bs.length == 1 :
+            "mc1t: The type argument of C0<T>  should have one bound";
+        assert
+            bs[0] == Object.class :
+            "mc1t: The bound of the type arg of C0<T> should be Object";
+
+        Type p3_mc1t = pt_mc1t[2];
+        assert
+            p3_mc1t == C0.class :
+            "Type of parameter 3 of mc1t is C0";
+
+        Type[] pt_mc1 = mc1.getGenericParameterTypes();
+        assert
+            pt_mc1.length == 1 :
+            "C2.mc1 has one parameter";
+
+        Type[] pt_mt = mt.getGenericParameterTypes();
+        assert
+            pt_mt.length == 1 :
+            "C2.mt has one parameter";
+        Type p_mt = pt_mt[0];
+        assert
+            p_mt instanceof TypeVariable :
+            "The generic type of the parameter of mt(T) is a type variable";
+        tv = (TypeVariable) p_mt;
+        assert
+            tv.getName().equals("T2") :
+            "The name of the type parameter of mt is T2, not " + tv.getName();
+        bs = tv.getBounds();
+        assert
+            bs.length == 1 :
+            "T2 should have one bound";
+        assert
+            bs[0] instanceof ParameterizedType:
+            "The bound of T2 should be parameterized type";
+
+        Type[] et_mc1t = mc1t.getGenericExceptionTypes();
+        assert
+            et_mc1t.length == 0 :
+            "Method C0.mc1t should have no generic exception types";
+
+        Type[] et_mc1 = mc1.getGenericExceptionTypes();
+        assert
+            et_mc1.length == 0 :
+            "Method C0.mc1 should have no generic exception types";
+
+        Type[] et_mt = mt.getGenericExceptionTypes();
+        assert
+            et_mt.length == 0 :
+            "Method C0.mt should have no generic exception types";
+
+
+        TypeVariable[] tv_mc1t = mc1t.getTypeParameters();
+        assert
+            tv_mc1t.length == 1 :
+            "Method C2.mc1t should have one type parameter";
+
+        TypeVariable[] tv_mc1 = mc1.getTypeParameters();
+        assert
+            tv_mc1.length == 2 :
+            "Method C2.mc1 should have two type parameters";
+
+        TypeVariable[] tv_mt = mt.getTypeParameters();
+        assert
+            tv_mt.length == 0 :
+            "Method C2.mt should have no type parameters";
+    }
+
+
+    static void testFields() throws NoSuchFieldException{
+        System.out.println("testing fields");
+        Field ft = cls. getField("ft");
+        Field fc1t = cls. getField("fc1t");
+        Field fc1 = cls. getField("fc1");
+        Field fi = cls. getField("fi");
+
+        Type gt_ft = ft.getGenericType();
+        assert
+            gt_ft instanceof TypeVariable :
+            "The generic type of C0.ft is a type variable";
+        TypeVariable tv = (TypeVariable) gt_ft;
+        assert
+            tv.getName().equals("T1") :
+            "The name of the type of ft is T1, not " + tv.getName();
+        Type[] bs = tv.getBounds();
+        assert
+            bs.length == 1 :
+            "The type of ft should have one bound";
+
+
+        Type gt_fc1t = fc1t.getGenericType();
+        assert
+            gt_fc1t instanceof ParameterizedType :
+            "The generic type of C0.fc1t is a parameterized type";
+        ParameterizedType pt = (ParameterizedType) gt_fc1t;
+        assert
+            pt.getRawType() == C0.class :
+            "Type of C2.fc1t is an instantiation of C0";
+        assert
+            pt.getOwnerType() == null :
+            "Type of C2.fc1t is has null owner";
+        Type[] tas = pt.getActualTypeArguments();
+        assert
+            tas.length == 1 :
+            "The type of fc1t has one type argument";
+        Type ta = tas[0];
+
+        assert
+            ta == String.class :
+            "The actual type arg of C0<String> is String";
+
+
+        Type gt_fc1 = fc1.getGenericType();
+        assert
+            gt_fc1 == C0.class :
+            " Type of C2.fc1 should be C0";
+
+        Type gt_fi = fi.getGenericType();
+        assert
+            gt_fi == int.class:
+            " Type of C2.fi should be int";
+
+    }
+
+    static void testConstructors() throws NoSuchMethodException {
+        System.out.println("testing constructors");
+        Class[] params1 = new Class[1];
+        params1[0] = C0.class;
+        Constructor<C2> con = cls.getDeclaredConstructor(params1);
+
+        Type[] pt_con = con.getGenericParameterTypes();
+        assert
+            pt_con.length == 1 :
+            "Constructor C0(T) should have one generic parameter type";
+        Type pt = pt_con[0];
+        assert
+            pt instanceof TypeVariable :
+            "The generic type of the parameter of C0(T2) is a type variable";
+        TypeVariable tv = (TypeVariable) pt;
+        assert
+            tv.getName().equals("T2") :
+            "The name of the type parameter of C2 is T2, not " + tv.getName();
+        Type[] bs = tv.getBounds();
+        assert
+            bs.length == 1 :
+            "T should have one bound";
+
+
+        Type[] et_con = con.getGenericExceptionTypes();
+        assert
+            et_con.length == 0 :
+            "Constructor C2(T2) should have no generic exception types";
+
+        TypeVariable[] tv_con = con.getTypeParameters();
+        assert
+            tv_con.length == 0 :
+            "Constructor C2(T2) should have no type parameters";
+
+
+        Class[] params2 = new Class[1];
+        params2[0] = Object.class;
+        con = cls.getDeclaredConstructor(params2);
+
+        pt_con = con.getGenericParameterTypes();
+        assert
+            pt_con.length == 1 :
+            "Constructor C0(T) should have one generic parameter type";
+        pt = pt_con[0];
+        assert
+            pt instanceof TypeVariable :
+            "The generic type of the parameter of C2(T) is a type variable";
+        tv = (TypeVariable) pt;
+        assert
+            tv.getName().equals("T") :
+            "The name of the type parameter of C2 is T, not " + tv.getName();
+        bs = tv.getBounds();
+        assert
+            bs.length == 1 :
+            "T should have one bound";
+
+
+        et_con = con.getGenericExceptionTypes();
+        assert
+            et_con.length == 0 :
+            "Constructor C2(T) should have no generic exception types";
+
+        tv_con = con.getTypeParameters();
+        assert
+            tv_con.length == 1 :
+            "Constructor C2(T) should have one type parameter";
+
+        Class[] params3 = new Class[3];
+        params3[0] = Object.class;
+        params3[1] = Object.class;
+        params3[2] = Object.class;
+
+        con = cls.getDeclaredConstructor(params3);
+
+        pt_con = con.getGenericParameterTypes();
+        assert
+            pt_con.length == 3 :
+            "Constructor C2(T1,T2,T4) should have three generic parameter types";
+        pt = pt_con[0];
+        assert
+            pt instanceof TypeVariable :
+            "The generic type of the first parameter of C2(T1,T2,T4) is a type variable";
+        tv = (TypeVariable) pt;
+        assert
+            tv.getName().equals("T1") :
+            "The name of the type parameter of C2(T1,T2,T4) is T1, not " + tv.getName();
+        bs = tv.getBounds();
+        assert
+            bs.length == 1 :
+            "T should have one bound";
+
+
+        et_con = con.getGenericExceptionTypes();
+        assert
+            et_con.length == 0 :
+            "Constructor C2(T1,T2,T4) should have no generic exception types";
+
+        tv_con = con.getTypeParameters();
+        assert
+            tv_con.length == 4 :
+            "Constructor C2(T1,T2,T4) should have four type parameters";
+
+        Class[] params4 = new Class[0];
+        con = cls.getDeclaredConstructor(params4);
+
+        pt_con = con.getGenericParameterTypes();
+        assert
+            pt_con.length == 0 :
+            "Constructor C2() should have no generic parameter types";
+
+
+        et_con = con.getGenericExceptionTypes();
+        assert
+            et_con.length == 1 :
+            "Constructor C2() should have one generic exception type";
+
+        tv_con = con.getTypeParameters();
+        assert
+            tv_con.length == 0 :
+            "Constructor C2() should have no type parameters";
+
+
+    }
+}
diff --git a/jdk/test/java/lang/reflect/Generics/TestN1.java b/jdk/test/java/lang/reflect/Generics/TestN1.java
new file mode 100644
index 0000000..d2dc8b2
--- /dev/null
+++ b/jdk/test/java/lang/reflect/Generics/TestN1.java
@@ -0,0 +1,207 @@
+/*
+ * Copyright 2003 Sun Microsystems, Inc.  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 Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
+ * CA 95054 USA or visit www.sun.com if you need additional information or
+ * have any questions.
+ */
+
+/*
+* @test
+* @bug 4891872
+* @summary Some tests for the generic core reflection api.
+* @author Gilad Bracha
+* @compile -source 1.5 TestN1.java
+* @run main/othervm -ea TestN1
+*/
+
+
+import java.lang.reflect.*;
+
+
+class N1<T1, T2> {
+
+    public Inner1 i1;
+    public Inner2 i2;
+    public Inner2<? super Character> i2sc;
+
+    public class Inner1 {
+
+    }
+
+    public class Inner2<T1> {
+        public boolean x;
+        public byte b;
+        public short s;
+        public char c;
+        public int i;
+        public long l;
+        public float f;
+        public double d;
+
+        public boolean[] xa;
+        public byte[] ba;
+        public short[] sa;
+        public char[] ca;
+        public int[] ia;
+        public long[] la;
+        public float[] fa;
+        public double[] da;
+    }
+
+    public class Inner3<X1, X2, X3> {
+        X1 x1;
+
+        Inner3(X1 x1, X2 x2, X3 x3, T1 t1, T2 t2) {}
+
+        <T, R, S> Inner3(T t, R r, S s, X1 x1) {}
+
+        int shazam(boolean b, short s, int[] ia, Object[] oa, Inner1 i1,
+                   Inner1 i1a, InnerInner<String,
+                   Inner3<Object, String, Object[]>> ii)
+        { return 3;}
+
+        public class InnerInner<T2, X2> {
+
+            boolean b;
+            Inner2<X2> i2x;
+
+            void foo(X3 x3){}
+            <X3> X3[] bar(X1 x1, X3[] x3, T1 t1) { return x3;}
+            N1<X1, X2> baz(N1<X1, X2> n1) { return n1;}
+            N1<?, ?> bam(N1<T1, X2> n1) { return n1;}
+            N1<? extends T1, ?> boom(N1<T1, X2> n1) { return n1;}
+
+        }
+
+    }
+
+
+
+
+}
+
+
+public class TestN1 {
+
+    static Class<N1> cls = N1.class;
+
+
+    public static void main(String[] args) throws Throwable {
+        testTypeParameters();
+        testInner1();
+        testInner2();
+        testInner3();
+    }
+
+
+    static void testTypeParameters() {
+
+        System.out.println("testing type parameters");
+        TypeVariable[] tvs = cls.getTypeParameters();
+        assert
+            tvs.length == 2 :
+            "N1 should have two type parameters";
+    }
+
+
+    static void testInner1() {
+        System.out.println("testing non-generic inner class");
+        Class in1 = N1.Inner1.class;
+
+        TypeVariable[] tvs = in1.getTypeParameters();
+        assert
+            tvs.length == 0 :
+            "N1.Inner2 should have no type parameters";
+
+    }
+
+    static void testInner2() throws NoSuchFieldException {
+        System.out.println("testing generic inner class 1");
+        Class in1 = N1.Inner2.class;
+
+        TypeVariable[] tvs = in1.getTypeParameters();
+        assert
+            tvs.length == 1 :
+            "N1.Inner2 should have one type parameter";
+
+
+        assert
+            in1.getField("x").getGenericType() == boolean.class :
+            "Type of Inner2.x should be boolean";
+
+        assert
+            in1.getField("b").getGenericType() == byte.class :
+            "Type of Inner2.b should be byte";
+        assert
+            in1.getField("s").getGenericType() == short.class :
+            "Type of Inner2.s should be short";
+        assert
+            in1.getField("c").getGenericType() == char.class :
+            "Type of Inner2.x should be char";
+        assert
+            in1.getField("i").getGenericType() == int.class :
+            "Type of Inner2.i should be int";
+        assert
+            in1.getField("l").getGenericType() == long.class :
+            "Type of Inner2.l should be long";
+        assert
+            in1.getField("f").getGenericType() == float.class :
+            "Type of Inner2.f should be float";
+        assert
+            in1.getField("d").getGenericType() == double.class :
+            "Type of Inner2.d should be double";
+
+        assert
+            in1.getField("xa").getGenericType() == boolean[].class :
+            "Type of Inner2.xa should be boolean[]";
+
+        assert
+            in1.getField("ba").getGenericType() == byte[].class :
+            "Type of Inner2.ba should be byte[]";
+        assert
+            in1.getField("sa").getGenericType() == short[].class :
+            "Type of Inner2.sa should be short[]";
+        assert
+            in1.getField("ca").getGenericType() == char[].class :
+            "Type of Inner2.xa should be char[]";
+        assert
+            in1.getField("ia").getGenericType() == int[].class :
+            "Type of Inner2.ia should be int[]";
+        assert
+            in1.getField("la").getGenericType() == long[].class :
+            "Type of Inner2.la should be long[]";
+        assert
+            in1.getField("fa").getGenericType() == float[].class :
+            "Type of Inner2.fa should be float[]";
+        assert
+            in1.getField("da").getGenericType() == double[].class :
+            "Type of Inner2.da should be double[]";
+    }
+
+
+    static void testInner3() {
+        System.out.println("testing generic inner class 3");
+        Class in1 = N1.Inner3.class;
+
+        TypeVariable[] tvs = in1.getTypeParameters();
+        assert
+            tvs.length == 3 :
+            "N1.Inner2 should have three type parameters";
+    }
+}
diff --git a/jdk/test/java/lang/reflect/Generics/TestParameterizedType.java b/jdk/test/java/lang/reflect/Generics/TestParameterizedType.java
new file mode 100644
index 0000000..5ace7fa
--- /dev/null
+++ b/jdk/test/java/lang/reflect/Generics/TestParameterizedType.java
@@ -0,0 +1,148 @@
+/*
+ * Copyright 2004 Sun Microsystems, Inc.  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 Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
+ * CA 95054 USA or visit www.sun.com if you need additional information or
+ * have any questions.
+ */
+
+/*
+ * @test
+ * @bug 5061485
+ * @summary Test sematics of ParameterizedType.equals
+ * @author Joseph D. Darcy
+ */
+
+import java.util.*;
+import java.lang.reflect.*;
+
+public class TestParameterizedType {
+    public <T> T genericMethod0() {
+        return null;
+    }
+
+    public <T> Set<T> genericMethod1() {
+        return null;
+    }
+
+    public <T> Set<T> genericMethod2() {
+        return null;
+    }
+
+    public <S> List<S> genericMethod3() {
+        return null;
+    }
+
+    public <X, Y> Map<X, Y> genericMethod4() {
+        return null;
+    }
+
+    public <T> T[] genericMethod5() {
+        return null;
+    }
+
+    public <T> T[] genericMethod6() {
+        return null;
+    }
+
+    public Set<? extends Cloneable> genericMethod7() {
+        return null;
+    }
+
+    public Set<? super Number> genericMethod8() {
+        return null;
+    }
+
+    public Set<?> genericMethod9() {
+        return null;
+    }
+
+
+    static List<Type> createTypes() throws Exception {
+        List<Type> typeList = new ArrayList<Type>(3);
+        String[] methodNames = {"genericMethod0",
+                                "genericMethod1",
+                                "genericMethod2",
+                                "genericMethod3",
+                                "genericMethod4",
+                                "genericMethod5",
+                                "genericMethod6",
+                                "genericMethod7",
+                                "genericMethod8",
+                                "genericMethod9",
+        };
+
+        for(String s : methodNames) {
+            Type t = TestParameterizedType.class.getDeclaredMethod(s).getGenericReturnType();
+            // if (! (t instanceof ParameterizedType))
+            //  throw new RuntimeException("Unexpected kind of return type");
+            typeList.add(t);
+        }
+
+        return typeList;
+    }
+
+    static boolean testReflexes(List<Type> typeList) {
+        for(Type t : typeList) {
+            if (! t.equals(t) ) {
+                System.err.printf("Bad reflexes for%s %s%n", t, t.getClass());
+                return true;
+            }
+        }
+        return false;
+    }
+
+    public static void main(String[] argv) throws Exception {
+        boolean failed = false;
+
+        List<Type> take1 = createTypes();
+        List<Type> take2 = createTypes();
+
+        // Test reflexivity
+        failed = failed | testReflexes(take1);
+        failed = failed | testReflexes(take2);
+
+        for(int i = 0; i < take1.size(); i++) {
+            Type type1 = take1.get(i);
+
+            for(int j = 0; j < take2.size(); j++) {
+                Type type2 = take2.get(j);
+
+                if (i == j) {
+                    // corresponding types should be .equals
+                    if (!type1.equals(type2) ) {
+                        failed = true;
+                        System.err.printf("Unexpected inequality: [%d, %d] %n\t%s%n\t%s%n",
+                                          i, j, type1, type2);
+                    }
+                } else {
+                    // non-corresponding types should *not* be .equals
+                    if (type1.equals(type2) ) {
+                        failed = true;
+                        System.err.printf("Unexpected equality: [%d, %d] %n\t%s%n\t%s%n",
+                                          i, j, type1, type2);
+                    }
+                }
+
+            }
+        }
+
+        if (failed)
+            throw new RuntimeException("Bad equality on ParameterizedTypes");
+    }
+}
diff --git a/jdk/test/java/lang/reflect/Generics/exceptionCauseTest.java b/jdk/test/java/lang/reflect/Generics/exceptionCauseTest.java
new file mode 100644
index 0000000..1427563
--- /dev/null
+++ b/jdk/test/java/lang/reflect/Generics/exceptionCauseTest.java
@@ -0,0 +1,48 @@
+/*
+ * Copyright 2004 Sun Microsystems, Inc.  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 Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
+ * CA 95054 USA or visit www.sun.com if you need additional information or
+ * have any questions.
+ */
+
+/*
+ * @test
+ * @bug 4981727
+ * @summary
+ * @author Joseph D. Darcy
+ * @compile -source 1.5 exceptionCauseTest.java
+ * @run main exceptionCauseTest
+ */
+
+import java.io.PrintStream;
+
+public class exceptionCauseTest {
+    public static void main(String args[]) {
+        Throwable cause = new Throwable("because");
+        Throwable par   = new Throwable(cause);
+        TypeNotPresentException cnp = new TypeNotPresentException("test", par);
+
+        try {
+            throw cnp;
+        } catch (TypeNotPresentException e) {
+            if (par != e.getCause() )
+                throw new RuntimeException("Unexpected value of cause.");
+        }
+    }
+}
diff --git a/jdk/test/java/lang/reflect/Generics/getAnnotationTest.java b/jdk/test/java/lang/reflect/Generics/getAnnotationTest.java
new file mode 100644
index 0000000..d7f5d6d
--- /dev/null
+++ b/jdk/test/java/lang/reflect/Generics/getAnnotationTest.java
@@ -0,0 +1,67 @@
+/*
+ * Copyright 2004 Sun Microsystems, Inc.  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 Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
+ * CA 95054 USA or visit www.sun.com if you need additional information or
+ * have any questions.
+ */
+
+/*
+ * @test
+ * @bug 4979440
+ * @summary Test for signature parsing corner case
+ * @author Joseph D. Darcy
+ * @compile -source 1.5 getAnnotationTest.java
+ * @run main getAnnotationTest
+ */
+
+import java.lang.reflect.*;
+import java.lang.annotation.*;
+
+/*
+ * Make sure:
+ * 1. getAnnotation can be called directly
+ * 2. getAnnotation can be called reflectively
+ * 3. generic information methods on the Method object for
+ * getAnnotation can be called
+ */
+
+public class getAnnotationTest {
+    public static void main (String[] args) throws Throwable {
+        // Base level
+        Class c = Class.forName("java.lang.annotation.Retention");
+        Annotation result  = c.getAnnotation(Retention.class);
+        // System.out.println("Base result:" + result);
+
+        // Meta level, invoke Class.getAnnotation reflectively...
+        Class meta_c = c.getClass();
+        Method meta_getAnnotation = meta_c.getMethod("getAnnotation",
+                                                     (Retention.class).getClass());
+
+        Object meta_result = meta_getAnnotation.invoke(c, Retention.class);
+        // System.out.println("Meta result:" + meta_result);
+
+        if (!meta_result.equals(result)) {
+            throw new RuntimeException("Base and meta results are not equal.");
+        }
+
+        meta_getAnnotation.getGenericExceptionTypes();
+        meta_getAnnotation.getGenericParameterTypes();
+        meta_getAnnotation.getGenericReturnType();
+    }
+}
diff --git a/jdk/test/java/lang/reflect/Method/Equals.java b/jdk/test/java/lang/reflect/Method/Equals.java
new file mode 100644
index 0000000..2bcb4ec
--- /dev/null
+++ b/jdk/test/java/lang/reflect/Method/Equals.java
@@ -0,0 +1,72 @@
+/*
+ * Copyright 2003 Sun Microsystems, Inc.  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 Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
+ * CA 95054 USA or visit www.sun.com if you need additional information or
+ * have any questions.
+ */
+
+/*
+ * @test
+ * @bug 4913433
+ * @summary Generic framework to test Method.equals.
+ *
+ * @clean A
+ * @compile -source 1.5 Equals.java
+ * @run main Equals
+ */
+
+import java.lang.reflect.*;
+
+class A {
+    public Object m() { return this; }
+}
+
+public class Equals extends A {
+    public Equals m() { return this; }
+
+    public static void main(String [] args) {
+        Equals e = new Equals();
+        e.returnType();
+    }
+
+    private void returnType() {
+        Class c = this.getClass();
+        Method [] ma = c.getMethods();
+        Method m0 = null, m1 = null;
+
+        for (int i = 0; i < ma.length; i++) {
+            if (ma[i].getName().equals("m")) {
+                if (m0 == null) {
+                    m0 = ma[i];
+                    continue;
+                } else {
+                    m1 = ma[i];
+                    break;
+                }
+            }
+        }
+
+        if (m0 == null || m1 == null)
+            throw new RuntimeException("Can't find bridge methods");
+
+        if (m0.equals(m1))
+            throw new RuntimeException("Return types not compared");
+        System.out.println("\"" + m0 + "\" and \"" + m1 + "\" are different");
+    }
+}
diff --git a/jdk/test/java/lang/reflect/Method/GenericStringTest.java b/jdk/test/java/lang/reflect/Method/GenericStringTest.java
new file mode 100644
index 0000000..361e3db
--- /dev/null
+++ b/jdk/test/java/lang/reflect/Method/GenericStringTest.java
@@ -0,0 +1,142 @@
+/*
+ * Copyright 2004-2006 Sun Microsystems, Inc.  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 Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
+ * CA 95054 USA or visit www.sun.com if you need additional information or
+ * have any questions.
+ */
+
+/*
+ * @test
+ * @bug 5033583 6316717 6470106
+ * @summary Check toGenericString() and toString() methods
+ * @author Joseph D. Darcy
+ * @compile -source 1.5 GenericStringTest.java
+ * @run main GenericStringTest
+ */
+
+import java.lang.reflect.*;
+import java.lang.annotation.*;
+import java.util.*;
+
+public class GenericStringTest {
+    public static void main(String argv[]) throws Exception {
+        int failures = 0;
+        List<Class<?>> classList = new LinkedList<Class<?>>();
+        classList.add(TestClass1.class);
+        classList.add(TestClass2.class);
+        classList.add(Roebling.class);
+
+
+        for(Class<?> clazz: classList)
+            for(Method method: clazz.getDeclaredMethods()) {
+                ExpectedGenericString egs = method.getAnnotation(ExpectedGenericString.class);
+                if (egs != null) {
+                    String actual = method.toGenericString();
+                    System.out.println(actual);
+                    if (! egs.value().equals(actual)) {
+                        failures++;
+                        System.err.printf("ERROR: Expected ''%s''; got ''%s''.\n",
+                                          egs.value(), actual);
+                    }
+                }
+
+                if (method.isAnnotationPresent(ExpectedString.class)) {
+                    ExpectedString es = method.getAnnotation(ExpectedString.class);
+                    String actual = method.toString();
+                    if (! es.value().equals(actual)) {
+                        failures++;
+                        System.err.printf("ERROR: Expected ''%s''; got ''%s''.\n",
+                                          es.value(), actual);
+                    }
+                }
+
+            }
+
+        // Bridge Test; no "volatile" methods
+        for(Method method: Roebling.class.getDeclaredMethods()) {
+            String s1 = method.toGenericString();
+            String s2 = method.toString();
+            System.out.println("Generic: " + s1);
+            System.out.println("Regular: " + s2);
+            if (s1.indexOf("volatile") != -1 ||
+                s2.indexOf("volatile") != -1) {
+                failures++;
+                System.err.println("ERROR: Bad string; unexpected  ``volatile''");
+            }
+        }
+
+        if (failures > 0) {
+            System.err.println("Test failed.");
+            throw new RuntimeException();
+        }
+    }
+}
+
+class TestClass1 {
+    @ExpectedGenericString(
+   "void TestClass1.method1(int,double)")
+    void method1(int x, double y) {}
+
+    @ExpectedGenericString(
+   "private static java.lang.String TestClass1.method2(int,int)")
+    private static String method2(int x, int param2) {return null;}
+
+    @ExpectedGenericString(
+   "static void TestClass1.method3() throws java.lang.RuntimeException")
+    static void method3() throws RuntimeException {return;}
+
+    @ExpectedGenericString(
+   "protected <S,T> S TestClass1.method4(S,T) throws java.lang.Exception")
+    protected <S, T> S method4(S s, T t) throws Exception {return null;}
+}
+
+class TestClass2<E, F extends Exception> {
+    @ExpectedGenericString(
+   "public <T> T TestClass2.method1(E,T)")
+    public <T> T method1(E e, T t) {return null;}
+
+    @ExpectedGenericString(
+   "public void TestClass2.method2() throws F")
+    public void method2() throws F {return;}
+}
+
+class Roebling implements Comparable<Roebling> {
+    @ExpectedGenericString(
+   "public int Roebling.compareTo(Roebling)")
+    public int compareTo(Roebling r) {
+        throw new IllegalArgumentException();
+    }
+
+    // Not a transient method, (transient var-arg overlap)
+    @ExpectedGenericString(
+   "void Roebling.varArg(java.lang.Object...)")
+    @ExpectedString(
+   "void Roebling.varArg(java.lang.Object[])")
+    void varArg(Object ... arg) {}
+}
+
+@Retention(RetentionPolicy.RUNTIME)
+@interface ExpectedGenericString {
+    String value();
+}
+
+@Retention(RetentionPolicy.RUNTIME)
+@interface ExpectedString {
+    String value();
+}
diff --git a/jdk/test/java/lang/reflect/Method/InheritedInterfaceMethods.java b/jdk/test/java/lang/reflect/Method/InheritedInterfaceMethods.java
new file mode 100644
index 0000000..086c606
--- /dev/null
+++ b/jdk/test/java/lang/reflect/Method/InheritedInterfaceMethods.java
@@ -0,0 +1,54 @@
+/*
+ * Copyright 2002 Sun Microsystems, Inc.  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 Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
+ * CA 95054 USA or visit www.sun.com if you need additional information or
+ * have any questions.
+ */
+
+/* @test
+   @bug 4424393
+   @summary Failure to properly traverse superinterfaces
+   @author Kenneth Russell
+*/
+
+import java.lang.reflect.Method;
+
+public class InheritedInterfaceMethods {
+  public static void main(String[] args) {
+    Method[] methods = InheritedInterfaceMethodsC.class.getMethods();
+    for (int i = 0; i < methods.length; i++) {
+      if (methods[i].getName().equals("a")) {
+        return;
+      }
+    }
+    throw new RuntimeException("TEST FAILED");
+  }
+}
+
+interface InheritedInterfaceMethodsA {
+  public void a();
+}
+
+interface InheritedInterfaceMethodsB extends InheritedInterfaceMethodsA {
+  public void b();
+}
+
+interface InheritedInterfaceMethodsC extends InheritedInterfaceMethodsB {
+  public void c();
+}
diff --git a/jdk/test/java/lang/reflect/Method/InheritedMethods.java b/jdk/test/java/lang/reflect/Method/InheritedMethods.java
new file mode 100644
index 0000000..943767f
--- /dev/null
+++ b/jdk/test/java/lang/reflect/Method/InheritedMethods.java
@@ -0,0 +1,46 @@
+/*
+ * Copyright 2002-2007 Sun Microsystems, Inc.  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 Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
+ * CA 95054 USA or visit www.sun.com if you need additional information or
+ * have any questions.
+ */
+
+/* @test
+   @bug 4471738
+   @summary Failure to properly traverse class hierarchy in Class.getMethod()
+*/
+
+import java.lang.reflect.Method;
+import java.util.Collection;
+import java.util.List;
+import javax.swing.JPanel;
+import javax.swing.JLabel;
+
+public class InheritedMethods extends JPanel {
+    public static void main(String[] args) throws Exception { new InheritedMethods(); }
+    InheritedMethods() throws Exception {
+        Class c = Foo.class;
+        Method m = c.getMethod("removeAll", new Class[] { Collection.class });
+        if (m.getDeclaringClass() != java.util.List.class) {
+          throw new RuntimeException("TEST FAILED");
+        }
+        add(new JLabel("Test"));
+    }
+    interface Foo extends List { }
+}
diff --git a/jdk/test/java/lang/reflect/Method/invoke/ErrorInInvoke.java b/jdk/test/java/lang/reflect/Method/invoke/ErrorInInvoke.java
new file mode 100644
index 0000000..6bad450
--- /dev/null
+++ b/jdk/test/java/lang/reflect/Method/invoke/ErrorInInvoke.java
@@ -0,0 +1,60 @@
+/*
+ * Copyright 2002 Sun Microsystems, Inc.  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 Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
+ * CA 95054 USA or visit www.sun.com if you need additional information or
+ * have any questions.
+ */
+
+/* @test
+   @bug 4428861
+   @summary Method.invoke() should wrap all Throwables in InvocationTargetException
+   @author Kenneth Russell
+*/
+
+import java.lang.reflect.Method;
+import java.lang.reflect.InvocationTargetException;
+
+public class ErrorInInvoke {
+  public static void run() {
+    throw new AbstractMethodError("Not really, just testing");
+  }
+
+  public static void main(String[] args) {
+    Method m = null;
+
+    try {
+      m = ErrorInInvoke.class.getMethod("run", new Class[] {});
+    } catch (Throwable t) {
+      throw new RuntimeException("Test failed (getMethod() failed");
+    }
+
+    try {
+      m.invoke(null, null);
+    } catch (AbstractMethodError e) {
+      throw new RuntimeException("Test failed (AbstractMethodError passed through)");
+    } catch (InvocationTargetException e) {
+      Throwable t = e.getTargetException();
+      if (!(t instanceof AbstractMethodError)) {
+        throw new RuntimeException("Test failed (InvocationTargetException didn't wrap AbstractMethodError)");
+      }
+    } catch (Throwable t) {
+      throw new RuntimeException("Test failed (Unexpected exception)");
+    }
+  }
+}
diff --git a/jdk/test/java/lang/reflect/Method/invoke/IllegalAccessInInvoke.java b/jdk/test/java/lang/reflect/Method/invoke/IllegalAccessInInvoke.java
new file mode 100644
index 0000000..67b3879
--- /dev/null
+++ b/jdk/test/java/lang/reflect/Method/invoke/IllegalAccessInInvoke.java
@@ -0,0 +1,69 @@
+/*
+ * Copyright 1998 Sun Microsystems, Inc.  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 Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
+ * CA 95054 USA or visit www.sun.com if you need additional information or
+ * have any questions.
+ */
+
+/* @test
+   @bug 4109289
+   @summary Turning off access checks now enables illegal reflection.
+   @author Anand Palaniswamy
+*/
+
+import java.lang.reflect.Method;
+
+/**
+ * Try to call a private method with Method.invoke(). If that doesn't
+ * throw a IllegalAccessException, then access checks are disabled,
+ * which is a bad idea.
+ */
+public class IllegalAccessInInvoke {
+    public static void main(String[] argv) {
+        Class[] argTypes = new Class[0];
+        Object[] args = new Object[0];
+        Method pm = null;
+
+        try {
+            pm = Foo.class.getDeclaredMethod("privateMethod", argTypes);
+        } catch (NoSuchMethodException nsme) {
+            throw new
+                RuntimeException("Bizzare: privateMethod *must* be there");
+        }
+
+        boolean ethrown = false;
+        try {
+            pm.invoke(new Foo(), args);
+        } catch (IllegalAccessException iae) {
+            ethrown = true;
+        } catch (Exception e) {
+            throw new RuntimeException("Unexpected " + e.toString());
+        }
+
+        if (!ethrown) {
+            throw new
+                RuntimeException("Reflection access checks are disabled");
+        }
+    }
+}
+
+class Foo {
+    private void privateMethod() {
+    }
+}
diff --git a/jdk/test/java/lang/reflect/Modifier/toStringTest.java b/jdk/test/java/lang/reflect/Modifier/toStringTest.java
new file mode 100644
index 0000000..ad82f1d
--- /dev/null
+++ b/jdk/test/java/lang/reflect/Modifier/toStringTest.java
@@ -0,0 +1,58 @@
+/*
+ * Copyright 2001 Sun Microsystems, Inc.  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 Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
+ * CA 95054 USA or visit www.sun.com if you need additional information or
+ * have any questions.
+ */
+
+/**
+ * @test
+ * @bug 4394937
+ * @summary tests the toString method of reflect.Modifier
+ */
+
+import java.lang.reflect.*;
+
+public class toStringTest {
+
+    static void testString(int test, String expected) {
+        if(!Modifier.toString(test).equals(expected))
+            throw new RuntimeException(test +
+                                          " yields incorrect toString result");
+    }
+
+    public static void main(String [] argv) {
+        int allMods = Modifier.PUBLIC | Modifier.PROTECTED | Modifier.PRIVATE |
+            Modifier.ABSTRACT | Modifier.STATIC | Modifier.FINAL |
+            Modifier.TRANSIENT | Modifier.VOLATILE | Modifier.SYNCHRONIZED |
+            Modifier.NATIVE | Modifier.STRICT | Modifier.INTERFACE;
+
+        String allModsString = "public protected private abstract static " +
+            "final transient volatile synchronized native strictfp interface";
+
+        /* zero should have an empty string */
+        testString(0, "");
+
+        /* test to make sure all modifiers print out in the proper order */
+        testString(allMods, allModsString);
+
+        /* verify no extraneous modifiers are printed */
+        testString(~0, allModsString);
+    }
+}
diff --git a/jdk/test/java/lang/reflect/Proxy/Basic1.java b/jdk/test/java/lang/reflect/Proxy/Basic1.java
new file mode 100644
index 0000000..8499c88
--- /dev/null
+++ b/jdk/test/java/lang/reflect/Proxy/Basic1.java
@@ -0,0 +1,167 @@
+/*
+ * Copyright 1999 Sun Microsystems, Inc.  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 Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
+ * CA 95054 USA or visit www.sun.com if you need additional information or
+ * have any questions.
+ */
+
+/* @test
+ * @bug 4227192
+ * @summary This is a basic functional test of the dynamic proxy API (part 1).
+ * @author Peter Jones
+ *
+ * @build Basic1
+ * @run main Basic1
+ */
+
+import java.lang.reflect.*;
+import java.security.*;
+import java.util.*;
+
+public class Basic1 {
+
+    public static void main(String[] args) {
+
+        System.err.println(
+            "\nBasic functional test of dynamic proxy API, part 1\n");
+
+        try {
+            Class[] interfaces =
+                new Class[] { Runnable.class, Observer.class };
+
+            ClassLoader loader = ClassLoader.getSystemClassLoader();
+
+            /*
+             * Generate a proxy class.
+             */
+            Class proxyClass = Proxy.getProxyClass(loader, interfaces);
+            System.err.println("+ generated proxy class: " + proxyClass);
+
+            /*
+             * Verify that it is public, final, and not abstract.
+             */
+            int flags = proxyClass.getModifiers();
+            System.err.println(
+                "+ proxy class's modifiers: " + Modifier.toString(flags));
+            if (!Modifier.isPublic(flags)) {
+                throw new RuntimeException("proxy class in not public");
+            }
+            if (!Modifier.isFinal(flags)) {
+                throw new RuntimeException("proxy class in not final");
+            }
+            if (Modifier.isAbstract(flags)) {
+                throw new RuntimeException("proxy class in abstract");
+            }
+
+            /*
+             * Verify that it is assignable to the proxy interfaces.
+             */
+            for (int i = 0; i < interfaces.length; i++) {
+                if (!interfaces[i].isAssignableFrom(proxyClass)) {
+                    throw new RuntimeException(
+                        "proxy class not assignable to proxy interface " +
+                        interfaces[i].getName());
+                }
+            }
+
+            /*
+             * Verify that it has the given permutation of interfaces.
+             */
+            List l1 = Arrays.asList(interfaces);
+            List l2 = Arrays.asList(proxyClass.getInterfaces());
+            System.err.println("+ proxy class's interfaces: " + l2);
+            if (!l1.equals(l2)) {
+                throw new RuntimeException(
+                    "proxy class interfaces are " + l2 +
+                    " (expected " + l1 + ")");
+            }
+
+            /*
+             * Verify that system agress that it is a proxy class.
+             */
+            if (Proxy.isProxyClass(Object.class)) {
+                throw new RuntimeException(
+                    "Proxy.isProxyClass returned true for java.lang.Object");
+            }
+            if (!Proxy.isProxyClass(proxyClass)) {
+                throw new RuntimeException(
+                    "Proxy.isProxyClass returned false for proxy class");
+            }
+
+            /*
+             * Verify that its protection domain is the bootstrap domain.
+             */
+            ProtectionDomain pd = proxyClass.getProtectionDomain();
+            System.err.println("+ proxy class's protextion domain: " + pd);
+            if (!pd.implies(new AllPermission())) {
+                throw new RuntimeException(
+                    "proxy class does not have AllPermission");
+            }
+
+            /*
+             * Verify that it has a constructor that takes an
+             * InvocationHandler instance.
+             */
+            Constructor cons = proxyClass.getConstructor(
+                new Class[] { InvocationHandler.class });
+
+            /*
+             * Construct a proxy instance.
+             */
+            Handler handler = new Handler();
+            Object proxy = cons.newInstance(new Object[] { handler });
+            handler.currentProxy = proxy;
+
+            /*
+             * Invoke a method on a proxy instance.
+             */
+            Method m = Runnable.class.getMethod("run", null);
+            ((Runnable) proxy).run();
+            if (!handler.lastMethod.equals(m)) {
+                throw new RuntimeException(
+                    "proxy method invocation failure (lastMethod = " +
+                        handler.lastMethod + ")");
+            }
+
+            System.err.println("\nTEST PASSED");
+
+        } catch (Exception e) {
+            System.err.println("\nTEST FAILED:");
+            e.printStackTrace();
+            throw new RuntimeException("TEST FAILED: " + e.toString());
+        }
+    }
+
+    public static class Handler implements InvocationHandler {
+
+        Object currentProxy;
+        Method lastMethod;
+
+        public Object invoke(Object proxy, Method method, Object[] args)
+            throws Throwable
+        {
+            if (proxy != currentProxy) {
+                throw new RuntimeException(
+                    "wrong proxy instance passed to invoke method");
+            }
+            lastMethod = method;
+            return null;
+        }
+    }
+}
diff --git a/jdk/test/java/lang/reflect/Proxy/Boxing.java b/jdk/test/java/lang/reflect/Proxy/Boxing.java
new file mode 100644
index 0000000..b1fcb46
--- /dev/null
+++ b/jdk/test/java/lang/reflect/Proxy/Boxing.java
@@ -0,0 +1,156 @@
+/*
+ * Copyright 2003 Sun Microsystems, Inc.  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 Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
+ * CA 95054 USA or visit www.sun.com if you need additional information or
+ * have any questions.
+ */
+
+/* @test
+ * @bug 4889342
+ * @summary This test verifies that when a primitive boolean value is
+ * passed by a dynamic proxy class to an invocation handler, it is
+ * boxed as one of the canonical Boolean instances (Boolean.TRUE or
+ * Boolean.FALSE).  This test also exercises a dynamic proxy class's
+ * boxing of all primitive types.
+ * @author Peter Jones
+ *
+ * @run main Boxing
+ */
+
+import java.lang.reflect.InvocationHandler;
+import java.lang.reflect.Method;
+import java.lang.reflect.Proxy;
+import java.util.Random;
+
+public class Boxing {
+
+    private interface Test {
+        void m(byte b,
+               char c,
+               double d,
+               float f,
+               int i,
+               long j,
+               short s,
+               boolean z);
+    }
+
+    private static final int REPS = 100000;
+
+    private byte b;
+    private char c;
+    private double d;
+    private float f;
+    private int i;
+    private long j;
+    private short s;
+    private boolean z;
+
+    public static void main(String[] args) {
+        (new Boxing()).run();
+        System.err.println("TEST PASSED");
+    }
+
+    private void run() {
+        Random random = new Random(42); // ensure consistent test domain
+
+        Test proxy = (Test) Proxy.newProxyInstance(
+            ClassLoader.getSystemClassLoader(),
+            new Class[] { Test.class },
+            new TestHandler());
+
+        for (int rep = 0; rep < REPS; rep++) {
+            b = (byte) random.nextInt();
+            c = (char) random.nextInt();
+            d = random.nextDouble();
+            f = random.nextFloat();
+            i = random.nextInt();
+            j = random.nextLong();
+            s = (short) random.nextInt();
+            z = random.nextBoolean();
+            proxy.m(b,c,d,f,i,j,s,z);
+        }
+    }
+
+    private class TestHandler implements InvocationHandler {
+        public Object invoke(Object proxy, Method method, Object[] args)
+            throws Throwable
+        {
+            if (!method.getName().equals("m")) {
+                throw new AssertionError();
+            }
+
+            byte b2 = ((Byte) args[0]).byteValue();
+            if (b2 != b) {
+                throw new RuntimeException("TEST FAILED: " +
+                    "wrong byte, expected " + b + " but got " + b2);
+            }
+
+            char c2 = ((Character) args[1]).charValue();
+            if (c2 != c) {
+                throw new RuntimeException("TEST FAILED: " +
+                    "wrong char, expected " + c + " but got " + c2);
+            }
+
+            double d2 = ((Double) args[2]).doubleValue();
+            if (d2 != d) {
+                throw new RuntimeException("TEST FAILED: " +
+                    "wrong double, expected " + d + " but got " + d2);
+            }
+
+            float f2 = ((Float) args[3]).floatValue();
+            if (f2 != f) {
+                throw new RuntimeException("TEST FAILED: " +
+                    "wrong float, expected " + f + " but got " + f2);
+            }
+
+            int i2 = ((Integer) args[4]).intValue();
+            if (i2 != i) {
+                throw new RuntimeException("TEST FAILED: " +
+                    "wrong int, expected " + i + " but got " + i2);
+            }
+
+            long j2 = ((Long) args[5]).longValue();
+            if (j2 != j) {
+                throw new RuntimeException("TEST FAILED: " +
+                    "wrong long, expected " + j + " but got " + j2);
+            }
+
+            short s2 = ((Short) args[6]).shortValue();
+            if (s2 != s) {
+                throw new RuntimeException("TEST FAILED: " +
+                    "wrong short, expected " + s + " but got " + s2);
+            }
+
+            Boolean Z = Boolean.valueOf(z);
+            Boolean Z2 = (Boolean) args[7];
+            if (Z2 != Z) {
+                throw new RuntimeException("TEST FAILED: " +
+                    "wrong Boolean instance, expected " +
+                    identityToString(Z) + " but got " + identityToString(Z2));
+            }
+
+            return null;
+        }
+    }
+
+    private static String identityToString(Object obj) {
+        return obj.toString() + "@" + System.identityHashCode(obj);
+    }
+}
diff --git a/jdk/test/java/lang/reflect/Proxy/CharType.java b/jdk/test/java/lang/reflect/Proxy/CharType.java
new file mode 100644
index 0000000..58ee894
--- /dev/null
+++ b/jdk/test/java/lang/reflect/Proxy/CharType.java
@@ -0,0 +1,50 @@
+/*
+ * Copyright 2000 Sun Microsystems, Inc.  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 Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
+ * CA 95054 USA or visit www.sun.com if you need additional information or
+ * have any questions.
+ */
+
+/*
+ * @test
+ * @bug 4346224
+ * @summary Test against a typo in sun.misc.ProxyGenerator:
+ *          "java/lang/Character" should be used instead of
+ *          "java/lang/Char".
+ */
+
+import java.lang.reflect.*;
+
+public class CharType {
+
+    public static void main (String args[]) throws Exception {
+        Proxy.newProxyInstance(CharMethod.class.getClassLoader(), new Class[] {
+            CharMethod.class }, new H());
+    }
+
+    static interface CharMethod {
+        void setChar(char c);
+    }
+
+    static class H implements InvocationHandler {
+        public Object invoke(Object o, Method m, Object[] arr) {
+            return null;
+        }
+    }
+}
diff --git a/jdk/test/java/lang/reflect/Proxy/ClassRestrictions.java b/jdk/test/java/lang/reflect/Proxy/ClassRestrictions.java
new file mode 100644
index 0000000..1f468b1
--- /dev/null
+++ b/jdk/test/java/lang/reflect/Proxy/ClassRestrictions.java
@@ -0,0 +1,187 @@
+/*
+ * Copyright 1999-2003 Sun Microsystems, Inc.  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 Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
+ * CA 95054 USA or visit www.sun.com if you need additional information or
+ * have any questions.
+ */
+
+/* @test
+ * @bug 4227192
+ * @summary This is a test of the restrictions on the parameters that may
+ * be passed to the Proxy.getProxyClass method.
+ * @author Peter Jones
+ *
+ * @build ClassRestrictions
+ * @run main ClassRestrictions
+ */
+
+import java.lang.reflect.Proxy;
+import java.net.URLClassLoader;
+
+public class ClassRestrictions {
+
+    public interface Bar {
+        int foo();
+    }
+
+    public interface Baz {
+        long foo();
+    }
+
+    interface Bashful {
+        void foo();
+    }
+
+    public static void main(String[] args) {
+
+        System.err.println(
+            "\nTest of restrictions on parameters to Proxy.getProxyClass\n");
+
+        try {
+            ClassLoader loader = ClassLoader.getSystemClassLoader();
+            Class[] interfaces;
+            Class proxyClass;
+
+            /*
+             * All of the Class objects in the interfaces array must represent
+             * interfaces, not classes or primitive types.
+             */
+            try {
+                interfaces = new Class[] { Object.class };
+                proxyClass = Proxy.getProxyClass(loader, interfaces);
+                throw new RuntimeException(
+                    "proxy class created with java.lang.Object as interface");
+            } catch (IllegalArgumentException e) {
+                e.printStackTrace();
+                System.err.println();
+                // assume exception is for intended failure
+            }
+            try {
+                interfaces = new Class[] { Integer.TYPE };
+                proxyClass = Proxy.getProxyClass(loader, interfaces);
+                throw new RuntimeException(
+                    "proxy class created with int.class as interface");
+            } catch (IllegalArgumentException e) {
+                e.printStackTrace();
+                System.err.println();
+                // assume exception is for intended failure
+            }
+
+            /*
+             * No two elements in the interfaces array may refer to identical
+             * Class objects.
+             */
+            try {
+                interfaces = new Class[] { Bar.class, Bar.class };
+                proxyClass = Proxy.getProxyClass(loader, interfaces);
+                throw new RuntimeException(
+                    "proxy class created with repeated interfaces");
+            } catch (IllegalArgumentException e) {
+                e.printStackTrace();
+                System.err.println();
+                // assume exception is for intended failure
+            }
+
+            /*
+             * All of the interfaces types must be visible by name though the
+             * specified class loader.
+             */
+            ClassLoader altLoader = new URLClassLoader(
+                ((URLClassLoader) loader).getURLs(), null);
+            Class altBarClass;
+            altBarClass = Class.forName(Bar.class.getName(), false, altLoader);
+            try {
+                interfaces = new Class[] { altBarClass };
+                proxyClass = Proxy.getProxyClass(loader, interfaces);
+                throw new RuntimeException(
+                    "proxy class created with interface " +
+                    "not visible to class loader");
+            } catch (IllegalArgumentException e) {
+                e.printStackTrace();
+                System.err.println();
+                // assume exception is for intended failure
+            }
+
+            /*
+             * All non-public interfaces must be in the same package.
+             */
+            Class nonPublic1 = Bashful.class;
+            Class nonPublic2 = null;
+            String[] nonPublicInterfaces = new String[] {
+                "java.awt.Conditional",
+                "java.util.zip.ZipConstants",
+                "javax.swing.GraphicsWrapper",
+                "javax.swing.JPopupMenu$Popup",
+                "javax.swing.JTable$Resizable2",
+                "javax.swing.JTable$Resizable3",
+                "javax.swing.ToolTipManager$Popup",
+                "sun.audio.Format",
+                "sun.audio.HaePlayable",
+                "sun.tools.agent.StepConstants",
+            };
+            for (int i = 0; i < nonPublicInterfaces.length; i++) {
+                try {
+                    nonPublic2 = Class.forName(nonPublicInterfaces[i]);
+                    break;
+                } catch (ClassNotFoundException e) {
+                }
+            }
+            if (nonPublic2 == null) {
+                throw new RuntimeException(
+                    "no second non-public interface found for test");
+            }
+            try {
+                interfaces = new Class[] { nonPublic1, nonPublic2 };
+                proxyClass = Proxy.getProxyClass(loader, interfaces);
+                throw new RuntimeException(
+                    "proxy class created with two non-public interfaces " +
+                    "in different packages");
+            } catch (IllegalArgumentException e) {
+                e.printStackTrace();
+                System.err.println();
+                // assume exception is for intended failure
+            }
+
+            /*
+             * No two interfaces may each have a method with the same name and
+             * parameter signature but different return type.
+             */
+            try {
+                interfaces = new Class[] { Bar.class, Baz.class };
+                proxyClass = Proxy.getProxyClass(loader, interfaces);
+                throw new RuntimeException(
+                    "proxy class created with conflicting methods");
+            } catch (IllegalArgumentException e) {
+                e.printStackTrace();
+                System.err.println();
+                // assume exception is for intended failure
+            }
+
+            /*
+             * All components of this test have passed.
+             */
+            System.err.println("\nTEST PASSED");
+
+        } catch (Exception e) {
+            System.err.println("\nTEST FAILED:");
+            e.printStackTrace();
+            throw new RuntimeException("TEST FAILED: " + e.toString());
+        }
+    }
+}
diff --git a/jdk/test/java/lang/reflect/Proxy/NullClassLoader.java b/jdk/test/java/lang/reflect/Proxy/NullClassLoader.java
new file mode 100644
index 0000000..192772b
--- /dev/null
+++ b/jdk/test/java/lang/reflect/Proxy/NullClassLoader.java
@@ -0,0 +1,65 @@
+/*
+ * Copyright 1999 Sun Microsystems, Inc.  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 Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
+ * CA 95054 USA or visit www.sun.com if you need additional information or
+ * have any questions.
+ */
+
+/* @test
+ * @bug 4227192
+ * @summary This test verifies that a proxy class can be created with
+ * (and defined in) the null class loader.
+ * @author Peter Jones
+ *
+ * @build NullClassLoader
+ * @run main NullClassLoader
+ */
+
+import java.lang.reflect.*;
+import java.util.Observer;
+
+public class NullClassLoader {
+
+    public static void main(String[] args) {
+
+        System.err.println(
+            "\nTest creating proxy class with the null class loader.\n");
+
+        try {
+            Class p = Proxy.getProxyClass(null,
+                new Class[] { Runnable.class, Observer.class });
+            System.err.println("proxy class: " + p);
+
+            ClassLoader loader = p.getClassLoader();
+            System.err.println("proxy class's class loader: " + loader);
+
+            if (loader != null) {
+                throw new RuntimeException(
+                    "proxy class not defined in the null class loader");
+            }
+
+            System.err.println("\nTEST PASSED");
+
+        } catch (Throwable e) {
+            System.err.println("\nTEST FAILED:");
+            e.printStackTrace();
+            throw new RuntimeException("TEST FAILED: " + e.toString());
+        }
+    }
+}
diff --git a/jdk/test/java/lang/reflect/Proxy/nonJavaNames/Test.java b/jdk/test/java/lang/reflect/Proxy/nonJavaNames/Test.java
new file mode 100644
index 0000000..d49ce3e
--- /dev/null
+++ b/jdk/test/java/lang/reflect/Proxy/nonJavaNames/Test.java
@@ -0,0 +1,81 @@
+/*
+ * Copyright 2004 Sun Microsystems, Inc.  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 Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
+ * CA 95054 USA or visit www.sun.com if you need additional information or
+ * have any questions.
+ */
+
+/* @test
+ * @bug 4978925
+ * @summary This test verifies that java.lang.reflect.Proxy will work
+ * with a proxy interface that contains names that are not valid Java
+ * identifiers but that are legal at runtime as of version 49.0 of the
+ * class file format.
+ * @author Peter Jones
+ *
+ * @build Test
+ * @run main Test
+ */
+
+import java.lang.reflect.Proxy;
+
+public class Test {
+
+    private static final String CLASS_NAME = "Test+Interface";
+
+    /**
+     * class file for empty interface named "Test+Interface"
+     */
+    private static final byte[] CLASS_FILE = {
+        (byte) 0xca, (byte) 0xfe, (byte) 0xba, (byte) 0xbe,
+                                0x00, 0x00, 0x00, 0x31,
+        0x00, 0x07, 0x07, 0x00, 0x05, 0x07, 0x00, 0x06,
+        0x01, 0x00, 0x0a, 0x53, 0x6f, 0x75, 0x72, 0x63,
+        0x65, 0x46, 0x69, 0x6c, 0x65, 0x01, 0x00, 0x13,
+        0x54, 0x65, 0x73, 0x74, 0x2b, 0x49, 0x6e, 0x74,
+        0x65, 0x72, 0x66, 0x61, 0x63, 0x65, 0x2e, 0x6a,
+        0x61, 0x76, 0x61, 0x01, 0x00, 0x0e, 0x54, 0x65,
+        0x73, 0x74, 0x2b, 0x49, 0x6e, 0x74, 0x65, 0x72,
+        0x66, 0x61, 0x63, 0x65, 0x01, 0x00, 0x10, 0x6a,
+        0x61, 0x76, 0x61, 0x2f, 0x6c, 0x61, 0x6e, 0x67,
+        0x2f, 0x4f, 0x62, 0x6a, 0x65, 0x63, 0x74, 0x06,
+        0x01, 0x00, 0x01, 0x00, 0x02, 0x00, 0x00, 0x00,
+        0x00, 0x00, 0x00, 0x00, 0x01, 0x00, 0x03, 0x00,
+        0x00, 0x00, 0x02, 0x00, 0x04
+    };
+
+    public static void main(String[] args) throws Exception {
+        ClassLoader l = new Loader();
+        Class i = Class.forName(CLASS_NAME, false, l);
+        System.out.println(i);
+        Class p = Proxy.getProxyClass(i.getClassLoader(), new Class[] { i });
+        System.out.println(p);
+    }
+
+    private static class Loader extends ClassLoader {
+        Loader() { }
+        protected Class findClass(String name) throws ClassNotFoundException {
+            if (name.equals(CLASS_NAME)) {
+                return defineClass(name, CLASS_FILE, 0, CLASS_FILE.length);
+            } else {
+                return super.findClass(name);
+            }
+        }
+    }
+}
diff --git a/jdk/test/java/lang/reflect/Proxy/returnTypes/GetArray.java b/jdk/test/java/lang/reflect/Proxy/returnTypes/GetArray.java
new file mode 100644
index 0000000..3dbe2ef
--- /dev/null
+++ b/jdk/test/java/lang/reflect/Proxy/returnTypes/GetArray.java
@@ -0,0 +1,26 @@
+/*
+ * Copyright 2003 Sun Microsystems, Inc.  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 Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
+ * CA 95054 USA or visit www.sun.com if you need additional information or
+ * have any questions.
+ */
+
+public interface GetArray {
+    Object[] get(double[][][] x);
+}
diff --git a/jdk/test/java/lang/reflect/Proxy/returnTypes/GetCloneable.java b/jdk/test/java/lang/reflect/Proxy/returnTypes/GetCloneable.java
new file mode 100644
index 0000000..479ed6a
--- /dev/null
+++ b/jdk/test/java/lang/reflect/Proxy/returnTypes/GetCloneable.java
@@ -0,0 +1,26 @@
+/*
+ * Copyright 2003 Sun Microsystems, Inc.  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 Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
+ * CA 95054 USA or visit www.sun.com if you need additional information or
+ * have any questions.
+ */
+
+public interface GetCloneable {
+    Cloneable get(double[][][] x);
+}
diff --git a/jdk/test/java/lang/reflect/Proxy/returnTypes/GetObject.java b/jdk/test/java/lang/reflect/Proxy/returnTypes/GetObject.java
new file mode 100644
index 0000000..d60bd97
--- /dev/null
+++ b/jdk/test/java/lang/reflect/Proxy/returnTypes/GetObject.java
@@ -0,0 +1,26 @@
+/*
+ * Copyright 2003 Sun Microsystems, Inc.  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 Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
+ * CA 95054 USA or visit www.sun.com if you need additional information or
+ * have any questions.
+ */
+
+public interface GetObject {
+    Object get(double[][][] x);
+}
diff --git a/jdk/test/java/lang/reflect/Proxy/returnTypes/GetSerializable.java b/jdk/test/java/lang/reflect/Proxy/returnTypes/GetSerializable.java
new file mode 100644
index 0000000..bdbb018
--- /dev/null
+++ b/jdk/test/java/lang/reflect/Proxy/returnTypes/GetSerializable.java
@@ -0,0 +1,28 @@
+/*
+ * Copyright 2003 Sun Microsystems, Inc.  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 Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
+ * CA 95054 USA or visit www.sun.com if you need additional information or
+ * have any questions.
+ */
+
+import java.io.Serializable;
+
+public interface GetSerializable {
+    Serializable get(double[][][] x);
+}
diff --git a/jdk/test/java/lang/reflect/Proxy/returnTypes/Test.java b/jdk/test/java/lang/reflect/Proxy/returnTypes/Test.java
new file mode 100644
index 0000000..f681a8e
--- /dev/null
+++ b/jdk/test/java/lang/reflect/Proxy/returnTypes/Test.java
@@ -0,0 +1,91 @@
+/*
+ * Copyright 2003 Sun Microsystems, Inc.  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 Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
+ * CA 95054 USA or visit www.sun.com if you need additional information or
+ * have any questions.
+ */
+
+/* @test
+ * @bug 4838310
+ * @summary This test verifies that the restrictions on proxy interface
+ * methods with the same signature but different return types are
+ * correctly enforced.
+ * @author Peter Jones
+ *
+ * @build GetObject GetSerializable GetCloneable GetArray
+ * @run main Test
+ */
+
+import java.lang.reflect.Proxy;
+import java.security.PrivilegedAction;
+import java.util.Arrays;
+import java.util.Collection;
+import java.util.List;
+
+public class Test {
+
+    // additional test cases may be added to both of these lists:
+
+    private static final Class[][] GOOD = {
+        { Collection.class },
+        { Iterable.class, Collection.class },
+        { Iterable.class, Collection.class, List.class },
+        { GetSerializable.class, GetCloneable.class, GetArray.class },
+        { GetObject.class, GetSerializable.class, GetCloneable.class,
+          GetArray.class }
+    };
+
+    private static final Class[][] BAD = {
+        { Runnable.class, PrivilegedAction.class },
+        { GetSerializable.class, GetCloneable.class },
+        { GetObject.class, GetSerializable.class, GetCloneable.class }
+    };
+
+    public static void main(String[] args) throws Exception {
+        System.err.println("\nRegression test for bug 4838310\n");
+
+        ClassLoader loader = ClassLoader.getSystemClassLoader();
+
+        System.err.println("Testing GOOD combinations:");
+
+        for (int i = 0; i < GOOD.length; i++) {
+            Class[] interfaces = GOOD[i];
+            System.err.println(Arrays.asList(interfaces));
+            Proxy.getProxyClass(loader, interfaces);
+            System.err.println("--- OK.");
+        }
+
+        System.err.println("Testing BAD combinations:");
+
+        for (int i = 0; i < BAD.length; i++) {
+            Class[] interfaces = BAD[i];
+            System.err.println(Arrays.asList(interfaces));
+            try {
+                Proxy.getProxyClass(loader, interfaces);
+                throw new RuntimeException(
+                    "TEST FAILED: bad combination succeeded");
+            } catch (IllegalArgumentException e) {
+                e.printStackTrace();
+                System.err.println("--- OK.");
+            }
+        }
+
+        System.err.println("TEST PASSED");
+    }
+}
diff --git a/jdk/test/java/lang/reflect/ReflectPermission/Exceptions.java b/jdk/test/java/lang/reflect/ReflectPermission/Exceptions.java
new file mode 100644
index 0000000..bb4b042
--- /dev/null
+++ b/jdk/test/java/lang/reflect/ReflectPermission/Exceptions.java
@@ -0,0 +1,92 @@
+/*
+ * Copyright 2004 Sun Microsystems, Inc.  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 Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
+ * CA 95054 USA or visit www.sun.com if you need additional information or
+ * have any questions.
+ */
+
+/**
+ * @test
+ * @bug 5002910
+ */
+
+import java.lang.reflect.ReflectPermission;
+
+public class Exceptions {
+    private static int fail = 0;
+    private static int pass = 0;
+
+    private static Throwable first;
+
+    static void pass() {
+        pass++;
+    }
+
+    static void fail(String fs, Throwable ex) {
+        String s = "'" + fs + "': " + ex.getClass().getName() + " thrown";
+        if (first == null)
+            first = ex;
+        System.err.println("FAILED: " + s);
+        fail++;
+    }
+
+    public static void main(String [] args) {
+        RuntimeException re = new RuntimeException("no exception thrown");
+        try {
+            new ReflectPermission(null);
+            fail("null", re);
+        } catch (NullPointerException x) {
+            pass();
+        } catch (Exception x) {
+            fail("null", x);
+        }
+        try {
+            new ReflectPermission("");
+            fail("\"\"", re);
+        } catch (IllegalArgumentException x) {
+            pass();
+        } catch (Exception x) {
+            fail("\"\"", x);
+        }
+
+        try {
+            new ReflectPermission(null, null);
+            fail("null, null", re);
+        } catch (NullPointerException x) {
+            pass();
+        } catch (Exception x) {
+            fail("null, null", x);
+        }
+        try {
+            new ReflectPermission("", null);
+            fail("\"\", null", re);
+        } catch (IllegalArgumentException x) {
+            pass();
+        } catch (Exception x) {
+            fail("\"\", null", x);
+        }
+
+        if (fail != 0)
+            throw new RuntimeException((fail + pass) + " tests: "
+                                       + fail + " failure(s), first", first);
+        else
+            System.out.println("all " + (fail + pass) + " tests passed");
+
+    }
+}