diff -U 10 -r -N old/js/src/liveconnect/classes/netscape/javascript/JSObject.java new/js/src/liveconnect/classes/netscape/javascript/JSObject.java
--- old/js/src/liveconnect/classes/netscape/javascript/JSObject.java	2003-11-14 17:11:08.000000000 -0600
+++ new/js/src/liveconnect/classes/netscape/javascript/JSObject.java	2006-08-21 15:01:59.000000000 -0500
@@ -40,20 +40,21 @@
 /* more doc todo:
  *  threads
  *  gc
  *  
  *
  */
 
 package netscape.javascript;
 
 import java.applet.Applet;
+import java.lang.ref.WeakReference;
 
 /**
  * JSObject allows Java to manipulate objects that are
  * defined in JavaScript.
  * Values passed from Java to JavaScript are converted as
  * follows:<ul>
  * <li>JSObject is converted to the original JavaScript object
  * <li>Any other Java object is converted to a JavaScript wrapper,
  *   which can be used to access methods and fields of the java object.
  *   Converting this wrapper to a string will call the toString method
@@ -72,24 +73,26 @@
  * <li>other objects are wrapped with a JSObject
  * <li>strings, numbers and booleans are converted to String, Double,
  *   and Boolean objects respectively
  * </ul>
  * This means that all JavaScript values show up as some kind
  * of java.lang.Object in Java.  In order to make much use of them,
  * you will have to cast them to the appropriate subclass of Object,
  * e.g. <code>(String) window.getMember("name");</code> or
  * <code>(JSObject) window.getMember("document");</code>.
  */
-public final class JSObject {
+public class JSObject {
     /* the internal object data */
     private int                               internal;
     private long                              long_internal;
+    private WeakReference                     applet = null;
+    private int                               pluginInstance = 0;
 
     /**
      * initialize
      */
     private static native void initClass();
     static {
     	// On MRJ, this property won't exist, because the library is preloaded.
     	String liveConnectLibrary = System.getProperty("netscape.jsj.dll", null);
     	if (liveConnectLibrary != null) {
 			System.loadLibrary(liveConnectLibrary);
@@ -97,24 +100,44 @@
 		}
     }
 
     /**
      * it is illegal to construct a JSObject manually
      */
     private JSObject(int jsobj_addr) {
         internal = jsobj_addr;
     }
 
+    private JSObject(int jsobj_addr, Applet applet) {
+        internal = jsobj_addr;
+        this.applet = new WeakReference(applet);
+    }
+
+    private JSObject(int jsobj_addr, int pluginInstance) {
+        internal = jsobj_addr;
+        this.pluginInstance = pluginInstance;
+    }
+
     private JSObject(long jsobj_addr) {
         long_internal = jsobj_addr;
     }
 
+    private Applet getApplet() {
+        if (applet == null)
+            return null;
+        return (Applet) applet.get();
+    }
+
+    private int getPluginInstance() {
+        return pluginInstance;
+    }
+
     /**
      * Retrieves a named member of a JavaScript object. 
      * Equivalent to "this.<i>name</i>" in JavaScript.
      */
     public native Object	getMember(String name);
 
     /**
      * Retrieves an indexed member of a JavaScript object.
      * Equivalent to "this[<i>index</i>]" in JavaScript.
      */
diff -U 10 -r -N old/plugin/oji/MRJCarbon/MRJSDK/JavaFrameworks/JavaVM/jni.h new/plugin/oji/MRJCarbon/MRJSDK/JavaFrameworks/JavaVM/jni.h
--- old/plugin/oji/MRJCarbon/MRJSDK/JavaFrameworks/JavaVM/jni.h	2003-06-11 01:11:18.000000000 -0500
+++ new/plugin/oji/MRJCarbon/MRJSDK/JavaFrameworks/JavaVM/jni.h	2005-10-04 14:10:37.000000000 -0500
@@ -1,18 +1,15 @@
 /*
- * @(#)jni.h	1.48 00/02/02
+ * @(#)jni.h	1.55 03/01/23
  *
- * Copyright 1996-2000 Sun Microsystems, Inc. All Rights Reserved.
- * 
- * This software is the proprietary information of Sun Microsystems, Inc.  
- * Use is subject to license terms.
- * 
+ * Copyright 2003 Sun Microsystems, Inc. All rights reserved.
+ * SUN PROPRIETARY/CONFIDENTIAL. Use is subject to license terms.
  */
 
 /*
  * We used part of Netscape's Java Runtime Interface (JRI) as the starting
  * point of our design and implementation.
  */
 
 /******************************************************************************
  * Java Runtime Interface
  * Copyright (c) 1996 Netscape Communications Corporation. All rights reserved.
@@ -187,23 +184,23 @@
 typedef const struct JNIInvokeInterface_ *JavaVM;
 #endif
 
 struct JNINativeInterface_ {
     void *reserved0;
     void *reserved1;
     void *reserved2;
 
     void *reserved3;
     
-#if !TARGET_RT_MAC_CFM
+#if !TARGET_RT_MAC_CFM && defined(__ppc__)
     void* cfm_vectors[225];
-#endif /* !TARGET_RT_MAC_CFM */
+#endif /* !TARGET_RT_MAC_CFM && defined(__ppc__) */
 
     jint (JNICALL *GetVersion)(JNIEnv *env);
 
     jclass (JNICALL *DefineClass)
       (JNIEnv *env, const char *name, jobject loader, const jbyte *buf,
        jsize len);
     jclass (JNICALL *FindClass)
       (JNIEnv *env, const char *name);
 
     jmethodID (JNICALL *FromReflectedMethod)
@@ -253,189 +250,189 @@
     jint (JNICALL *EnsureLocalCapacity)
       (JNIEnv *env, jint capacity);
 
     jobject (JNICALL *AllocObject)
       (JNIEnv *env, jclass clazz);
     jobject (JNICALL *NewObject)
       (JNIEnv *env, jclass clazz, jmethodID methodID, ...);
     jobject (JNICALL *NewObjectV)
       (JNIEnv *env, jclass clazz, jmethodID methodID, va_list args);
     jobject (JNICALL *NewObjectA)
-      (JNIEnv *env, jclass clazz, jmethodID methodID, jvalue *args);
+      (JNIEnv *env, jclass clazz, jmethodID methodID, const jvalue *args);
 
     jclass (JNICALL *GetObjectClass)
       (JNIEnv *env, jobject obj);
     jboolean (JNICALL *IsInstanceOf)
       (JNIEnv *env, jobject obj, jclass clazz);
 
     jmethodID (JNICALL *GetMethodID)
       (JNIEnv *env, jclass clazz, const char *name, const char *sig);
 
     jobject (JNICALL *CallObjectMethod)
       (JNIEnv *env, jobject obj, jmethodID methodID, ...);
     jobject (JNICALL *CallObjectMethodV)
       (JNIEnv *env, jobject obj, jmethodID methodID, va_list args);
     jobject (JNICALL *CallObjectMethodA)
-      (JNIEnv *env, jobject obj, jmethodID methodID, jvalue * args);
+      (JNIEnv *env, jobject obj, jmethodID methodID, const jvalue * args);
 
     jboolean (JNICALL *CallBooleanMethod)
       (JNIEnv *env, jobject obj, jmethodID methodID, ...);
     jboolean (JNICALL *CallBooleanMethodV)
       (JNIEnv *env, jobject obj, jmethodID methodID, va_list args);
     jboolean (JNICALL *CallBooleanMethodA)
-      (JNIEnv *env, jobject obj, jmethodID methodID, jvalue * args);
+      (JNIEnv *env, jobject obj, jmethodID methodID, const jvalue * args);
 
     jbyte (JNICALL *CallByteMethod)
       (JNIEnv *env, jobject obj, jmethodID methodID, ...);
     jbyte (JNICALL *CallByteMethodV)
       (JNIEnv *env, jobject obj, jmethodID methodID, va_list args);
     jbyte (JNICALL *CallByteMethodA)
-      (JNIEnv *env, jobject obj, jmethodID methodID, jvalue *args);
+      (JNIEnv *env, jobject obj, jmethodID methodID, const jvalue *args);
 
     jchar (JNICALL *CallCharMethod)
       (JNIEnv *env, jobject obj, jmethodID methodID, ...);
     jchar (JNICALL *CallCharMethodV)
       (JNIEnv *env, jobject obj, jmethodID methodID, va_list args);
     jchar (JNICALL *CallCharMethodA)
-      (JNIEnv *env, jobject obj, jmethodID methodID, jvalue *args);
+      (JNIEnv *env, jobject obj, jmethodID methodID, const jvalue *args);
 
     jshort (JNICALL *CallShortMethod)
       (JNIEnv *env, jobject obj, jmethodID methodID, ...);
     jshort (JNICALL *CallShortMethodV)
       (JNIEnv *env, jobject obj, jmethodID methodID, va_list args);
     jshort (JNICALL *CallShortMethodA)
-      (JNIEnv *env, jobject obj, jmethodID methodID, jvalue *args);
+      (JNIEnv *env, jobject obj, jmethodID methodID, const jvalue *args);
 
     jint (JNICALL *CallIntMethod)
       (JNIEnv *env, jobject obj, jmethodID methodID, ...);
     jint (JNICALL *CallIntMethodV)
       (JNIEnv *env, jobject obj, jmethodID methodID, va_list args);
     jint (JNICALL *CallIntMethodA)
-      (JNIEnv *env, jobject obj, jmethodID methodID, jvalue *args);
+      (JNIEnv *env, jobject obj, jmethodID methodID, const jvalue *args);
 
     jlong (JNICALL *CallLongMethod)
       (JNIEnv *env, jobject obj, jmethodID methodID, ...);
     jlong (JNICALL *CallLongMethodV)
       (JNIEnv *env, jobject obj, jmethodID methodID, va_list args);
     jlong (JNICALL *CallLongMethodA)
-      (JNIEnv *env, jobject obj, jmethodID methodID, jvalue *args);
+      (JNIEnv *env, jobject obj, jmethodID methodID, const jvalue *args);
 
     jfloat (JNICALL *CallFloatMethod)
       (JNIEnv *env, jobject obj, jmethodID methodID, ...);
     jfloat (JNICALL *CallFloatMethodV)
       (JNIEnv *env, jobject obj, jmethodID methodID, va_list args);
     jfloat (JNICALL *CallFloatMethodA)
-      (JNIEnv *env, jobject obj, jmethodID methodID, jvalue *args);
+      (JNIEnv *env, jobject obj, jmethodID methodID, const jvalue *args);
 
     jdouble (JNICALL *CallDoubleMethod)
       (JNIEnv *env, jobject obj, jmethodID methodID, ...);
     jdouble (JNICALL *CallDoubleMethodV)
       (JNIEnv *env, jobject obj, jmethodID methodID, va_list args);
     jdouble (JNICALL *CallDoubleMethodA)
-      (JNIEnv *env, jobject obj, jmethodID methodID, jvalue *args);
+      (JNIEnv *env, jobject obj, jmethodID methodID, const jvalue *args);
 
     void (JNICALL *CallVoidMethod)
       (JNIEnv *env, jobject obj, jmethodID methodID, ...);
     void (JNICALL *CallVoidMethodV)
       (JNIEnv *env, jobject obj, jmethodID methodID, va_list args);
     void (JNICALL *CallVoidMethodA)
-      (JNIEnv *env, jobject obj, jmethodID methodID, jvalue * args);
+      (JNIEnv *env, jobject obj, jmethodID methodID, const jvalue * args);
 
     jobject (JNICALL *CallNonvirtualObjectMethod)
       (JNIEnv *env, jobject obj, jclass clazz, jmethodID methodID, ...);
     jobject (JNICALL *CallNonvirtualObjectMethodV)
       (JNIEnv *env, jobject obj, jclass clazz, jmethodID methodID,
        va_list args);
     jobject (JNICALL *CallNonvirtualObjectMethodA)
       (JNIEnv *env, jobject obj, jclass clazz, jmethodID methodID,
-       jvalue * args);
+       const jvalue * args);
 
     jboolean (JNICALL *CallNonvirtualBooleanMethod)
       (JNIEnv *env, jobject obj, jclass clazz, jmethodID methodID, ...);
     jboolean (JNICALL *CallNonvirtualBooleanMethodV)
       (JNIEnv *env, jobject obj, jclass clazz, jmethodID methodID,
        va_list args);
     jboolean (JNICALL *CallNonvirtualBooleanMethodA)
       (JNIEnv *env, jobject obj, jclass clazz, jmethodID methodID,
-       jvalue * args);
+       const jvalue * args);
 
     jbyte (JNICALL *CallNonvirtualByteMethod)
       (JNIEnv *env, jobject obj, jclass clazz, jmethodID methodID, ...);
     jbyte (JNICALL *CallNonvirtualByteMethodV)
       (JNIEnv *env, jobject obj, jclass clazz, jmethodID methodID,
        va_list args);
     jbyte (JNICALL *CallNonvirtualByteMethodA)
       (JNIEnv *env, jobject obj, jclass clazz, jmethodID methodID,
-       jvalue *args);
+       const jvalue *args);
 
     jchar (JNICALL *CallNonvirtualCharMethod)
       (JNIEnv *env, jobject obj, jclass clazz, jmethodID methodID, ...);
     jchar (JNICALL *CallNonvirtualCharMethodV)
       (JNIEnv *env, jobject obj, jclass clazz, jmethodID methodID,
        va_list args);
     jchar (JNICALL *CallNonvirtualCharMethodA)
       (JNIEnv *env, jobject obj, jclass clazz, jmethodID methodID,
-       jvalue *args);
+       const jvalue *args);
 
     jshort (JNICALL *CallNonvirtualShortMethod)
       (JNIEnv *env, jobject obj, jclass clazz, jmethodID methodID, ...);
     jshort (JNICALL *CallNonvirtualShortMethodV)
       (JNIEnv *env, jobject obj, jclass clazz, jmethodID methodID,
        va_list args);
     jshort (JNICALL *CallNonvirtualShortMethodA)
       (JNIEnv *env, jobject obj, jclass clazz, jmethodID methodID,
-       jvalue *args);
+       const jvalue *args);
 
     jint (JNICALL *CallNonvirtualIntMethod)
       (JNIEnv *env, jobject obj, jclass clazz, jmethodID methodID, ...);
     jint (JNICALL *CallNonvirtualIntMethodV)
       (JNIEnv *env, jobject obj, jclass clazz, jmethodID methodID,
        va_list args);
     jint (JNICALL *CallNonvirtualIntMethodA)
       (JNIEnv *env, jobject obj, jclass clazz, jmethodID methodID,
-       jvalue *args);
+       const jvalue *args);
 
     jlong (JNICALL *CallNonvirtualLongMethod)
       (JNIEnv *env, jobject obj, jclass clazz, jmethodID methodID, ...);
     jlong (JNICALL *CallNonvirtualLongMethodV)
       (JNIEnv *env, jobject obj, jclass clazz, jmethodID methodID,
        va_list args);
     jlong (JNICALL *CallNonvirtualLongMethodA)
       (JNIEnv *env, jobject obj, jclass clazz, jmethodID methodID,
-       jvalue *args);
+       const jvalue *args);
 
     jfloat (JNICALL *CallNonvirtualFloatMethod)
       (JNIEnv *env, jobject obj, jclass clazz, jmethodID methodID, ...);
     jfloat (JNICALL *CallNonvirtualFloatMethodV)
       (JNIEnv *env, jobject obj, jclass clazz, jmethodID methodID,
        va_list args);
     jfloat (JNICALL *CallNonvirtualFloatMethodA)
       (JNIEnv *env, jobject obj, jclass clazz, jmethodID methodID,
-       jvalue *args);
+       const jvalue *args);
 
     jdouble (JNICALL *CallNonvirtualDoubleMethod)
       (JNIEnv *env, jobject obj, jclass clazz, jmethodID methodID, ...);
     jdouble (JNICALL *CallNonvirtualDoubleMethodV)
       (JNIEnv *env, jobject obj, jclass clazz, jmethodID methodID,
        va_list args);
     jdouble (JNICALL *CallNonvirtualDoubleMethodA)
       (JNIEnv *env, jobject obj, jclass clazz, jmethodID methodID,
-       jvalue *args);
+       const jvalue *args);
 
     void (JNICALL *CallNonvirtualVoidMethod)
       (JNIEnv *env, jobject obj, jclass clazz, jmethodID methodID, ...);
     void (JNICALL *CallNonvirtualVoidMethodV)
       (JNIEnv *env, jobject obj, jclass clazz, jmethodID methodID,
        va_list args);
     void (JNICALL *CallNonvirtualVoidMethodA)
       (JNIEnv *env, jobject obj, jclass clazz, jmethodID methodID,
-       jvalue * args);
+       const jvalue * args);
 
     jfieldID (JNICALL *GetFieldID)
       (JNIEnv *env, jclass clazz, const char *name, const char *sig);
 
     jobject (JNICALL *GetObjectField)
       (JNIEnv *env, jobject obj, jfieldID fieldID);
     jboolean (JNICALL *GetBooleanField)
       (JNIEnv *env, jobject obj, jfieldID fieldID);
     jbyte (JNICALL *GetByteField)
       (JNIEnv *env, jobject obj, jfieldID fieldID);
@@ -472,84 +469,84 @@
       (JNIEnv *env, jobject obj, jfieldID fieldID, jdouble val);
 
     jmethodID (JNICALL *GetStaticMethodID)
       (JNIEnv *env, jclass clazz, const char *name, const char *sig);
 
     jobject (JNICALL *CallStaticObjectMethod)
       (JNIEnv *env, jclass clazz, jmethodID methodID, ...);
     jobject (JNICALL *CallStaticObjectMethodV)
       (JNIEnv *env, jclass clazz, jmethodID methodID, va_list args);
     jobject (JNICALL *CallStaticObjectMethodA)
-      (JNIEnv *env, jclass clazz, jmethodID methodID, jvalue *args);
+      (JNIEnv *env, jclass clazz, jmethodID methodID, const jvalue *args);
 
     jboolean (JNICALL *CallStaticBooleanMethod)
       (JNIEnv *env, jclass clazz, jmethodID methodID, ...);
     jboolean (JNICALL *CallStaticBooleanMethodV)
       (JNIEnv *env, jclass clazz, jmethodID methodID, va_list args);
     jboolean (JNICALL *CallStaticBooleanMethodA)
-      (JNIEnv *env, jclass clazz, jmethodID methodID, jvalue *args);
+      (JNIEnv *env, jclass clazz, jmethodID methodID, const jvalue *args);
 
     jbyte (JNICALL *CallStaticByteMethod)
       (JNIEnv *env, jclass clazz, jmethodID methodID, ...);
     jbyte (JNICALL *CallStaticByteMethodV)
       (JNIEnv *env, jclass clazz, jmethodID methodID, va_list args);
     jbyte (JNICALL *CallStaticByteMethodA)
-      (JNIEnv *env, jclass clazz, jmethodID methodID, jvalue *args);
+      (JNIEnv *env, jclass clazz, jmethodID methodID, const jvalue *args);
 
     jchar (JNICALL *CallStaticCharMethod)
       (JNIEnv *env, jclass clazz, jmethodID methodID, ...);
     jchar (JNICALL *CallStaticCharMethodV)
       (JNIEnv *env, jclass clazz, jmethodID methodID, va_list args);
     jchar (JNICALL *CallStaticCharMethodA)
-      (JNIEnv *env, jclass clazz, jmethodID methodID, jvalue *args);
+      (JNIEnv *env, jclass clazz, jmethodID methodID, const jvalue *args);
 
     jshort (JNICALL *CallStaticShortMethod)
       (JNIEnv *env, jclass clazz, jmethodID methodID, ...);
     jshort (JNICALL *CallStaticShortMethodV)
       (JNIEnv *env, jclass clazz, jmethodID methodID, va_list args);
     jshort (JNICALL *CallStaticShortMethodA)
-      (JNIEnv *env, jclass clazz, jmethodID methodID, jvalue *args);
+      (JNIEnv *env, jclass clazz, jmethodID methodID, const jvalue *args);
 
     jint (JNICALL *CallStaticIntMethod)
       (JNIEnv *env, jclass clazz, jmethodID methodID, ...);
     jint (JNICALL *CallStaticIntMethodV)
       (JNIEnv *env, jclass clazz, jmethodID methodID, va_list args);
     jint (JNICALL *CallStaticIntMethodA)
-      (JNIEnv *env, jclass clazz, jmethodID methodID, jvalue *args);
+      (JNIEnv *env, jclass clazz, jmethodID methodID, const jvalue *args);
 
     jlong (JNICALL *CallStaticLongMethod)
       (JNIEnv *env, jclass clazz, jmethodID methodID, ...);
     jlong (JNICALL *CallStaticLongMethodV)
       (JNIEnv *env, jclass clazz, jmethodID methodID, va_list args);
     jlong (JNICALL *CallStaticLongMethodA)
-      (JNIEnv *env, jclass clazz, jmethodID methodID, jvalue *args);
+      (JNIEnv *env, jclass clazz, jmethodID methodID, const jvalue *args);
 
     jfloat (JNICALL *CallStaticFloatMethod)
       (JNIEnv *env, jclass clazz, jmethodID methodID, ...);
     jfloat (JNICALL *CallStaticFloatMethodV)
       (JNIEnv *env, jclass clazz, jmethodID methodID, va_list args);
     jfloat (JNICALL *CallStaticFloatMethodA)
-      (JNIEnv *env, jclass clazz, jmethodID methodID, jvalue *args);
+      (JNIEnv *env, jclass clazz, jmethodID methodID, const jvalue *args);
 
     jdouble (JNICALL *CallStaticDoubleMethod)
       (JNIEnv *env, jclass clazz, jmethodID methodID, ...);
     jdouble (JNICALL *CallStaticDoubleMethodV)
       (JNIEnv *env, jclass clazz, jmethodID methodID, va_list args);
     jdouble (JNICALL *CallStaticDoubleMethodA)
-      (JNIEnv *env, jclass clazz, jmethodID methodID, jvalue *args);
+      (JNIEnv *env, jclass clazz, jmethodID methodID, const jvalue *args);
 
     void (JNICALL *CallStaticVoidMethod)
       (JNIEnv *env, jclass cls, jmethodID methodID, ...);
     void (JNICALL *CallStaticVoidMethodV)
       (JNIEnv *env, jclass cls, jmethodID methodID, va_list args);
     void (JNICALL *CallStaticVoidMethodA)
-      (JNIEnv *env, jclass cls, jmethodID methodID, jvalue * args);
+      (JNIEnv *env, jclass cls, jmethodID methodID, const jvalue * args);
 
     jfieldID (JNICALL *GetStaticFieldID)
       (JNIEnv *env, jclass clazz, const char *name, const char *sig);
     jobject (JNICALL *GetStaticObjectField)
       (JNIEnv *env, jclass clazz, jfieldID fieldID);
     jboolean (JNICALL *GetStaticBooleanField)
       (JNIEnv *env, jclass clazz, jfieldID fieldID);
     jbyte (JNICALL *GetStaticByteField)
       (JNIEnv *env, jclass clazz, jfieldID fieldID);
     jchar (JNICALL *GetStaticCharField)
@@ -675,35 +672,35 @@
     void (JNICALL *GetIntArrayRegion)
       (JNIEnv *env, jintArray array, jsize start, jsize len, jint *buf);
     void (JNICALL *GetLongArrayRegion)
       (JNIEnv *env, jlongArray array, jsize start, jsize len, jlong *buf);
     void (JNICALL *GetFloatArrayRegion)
       (JNIEnv *env, jfloatArray array, jsize start, jsize len, jfloat *buf);
     void (JNICALL *GetDoubleArrayRegion)
       (JNIEnv *env, jdoubleArray array, jsize start, jsize len, jdouble *buf);
 
     void (JNICALL *SetBooleanArrayRegion)
-      (JNIEnv *env, jbooleanArray array, jsize start, jsize l, jboolean *buf);
+      (JNIEnv *env, jbooleanArray array, jsize start, jsize l, const jboolean *buf);
     void (JNICALL *SetByteArrayRegion)
-      (JNIEnv *env, jbyteArray array, jsize start, jsize len, jbyte *buf);
+      (JNIEnv *env, jbyteArray array, jsize start, jsize len, const jbyte *buf);
     void (JNICALL *SetCharArrayRegion)
-      (JNIEnv *env, jcharArray array, jsize start, jsize len, jchar *buf);
+      (JNIEnv *env, jcharArray array, jsize start, jsize len, const jchar *buf);
     void (JNICALL *SetShortArrayRegion)
-      (JNIEnv *env, jshortArray array, jsize start, jsize len, jshort *buf);
+      (JNIEnv *env, jshortArray array, jsize start, jsize len, const jshort *buf);
     void (JNICALL *SetIntArrayRegion)
-      (JNIEnv *env, jintArray array, jsize start, jsize len, jint *buf);
+      (JNIEnv *env, jintArray array, jsize start, jsize len, const jint *buf);
     void (JNICALL *SetLongArrayRegion)
-      (JNIEnv *env, jlongArray array, jsize start, jsize len, jlong *buf);
+      (JNIEnv *env, jlongArray array, jsize start, jsize len, const jlong *buf);
     void (JNICALL *SetFloatArrayRegion)
-      (JNIEnv *env, jfloatArray array, jsize start, jsize len, jfloat *buf);
+      (JNIEnv *env, jfloatArray array, jsize start, jsize len, const jfloat *buf);
     void (JNICALL *SetDoubleArrayRegion)
-      (JNIEnv *env, jdoubleArray array, jsize start, jsize len, jdouble *buf);
+      (JNIEnv *env, jdoubleArray array, jsize start, jsize len, const jdouble *buf);
 
     jint (JNICALL *RegisterNatives)
       (JNIEnv *env, jclass clazz, const JNINativeMethod *methods,
        jint nMethods);
     jint (JNICALL *UnregisterNatives)
       (JNIEnv *env, jclass clazz);
 
     jint (JNICALL *MonitorEnter)
       (JNIEnv *env, jobject obj);
     jint (JNICALL *MonitorExit)
@@ -727,24 +724,32 @@
     void (JNICALL *ReleaseStringCritical)
       (JNIEnv *env, jstring string, const jchar *cstring);
 
     jweak (JNICALL *NewWeakGlobalRef)
        (JNIEnv *env, jobject obj);
     void (JNICALL *DeleteWeakGlobalRef)
        (JNIEnv *env, jweak ref);
 
     jboolean (JNICALL *ExceptionCheck)
        (JNIEnv *env);
+
+    jobject (JNICALL *NewDirectByteBuffer)
+       (JNIEnv* env, void* address, jlong capacity);
+    void* (JNICALL *GetDirectBufferAddress)
+       (JNIEnv* env, jobject buf);
+    jlong (JNICALL *GetDirectBufferCapacity)
+       (JNIEnv* env, jobject buf);
     
-#if TARGET_RT_MAC_CFM
-    void* real_functions[225];
-#endif /* TARGET_RT_MAC_CFM */
+#if TARGET_RT_MAC_CFM && defined(__ppc__)
+    void* real_functions[228];
+#endif /* TARGET_RT_MAC_CFM && defined(__ppc__) */
+
 };
 
 /*
  * We use inlined functions for C++ so that programmers can write:
  *
  *    env->FindClass("java/lang/String")
  *
  * in C++ rather than:
  *
  *    (*env)->FindClass(env, "java/lang/String")
@@ -844,21 +849,21 @@
 	va_start(args, methodID);
         result = functions->NewObjectV(this,clazz,methodID,args);
 	va_end(args);
 	return result;
     }
     jobject NewObjectV(jclass clazz, jmethodID methodID,
 		       va_list args) {
         return functions->NewObjectV(this,clazz,methodID,args);
     }
     jobject NewObjectA(jclass clazz, jmethodID methodID,
-		       jvalue *args) {
+		       const jvalue *args) {
         return functions->NewObjectA(this,clazz,methodID,args);
     }
 
     jclass GetObjectClass(jobject obj) {
         return functions->GetObjectClass(this,obj);
     }
     jboolean IsInstanceOf(jobject obj, jclass clazz) {
         return functions->IsInstanceOf(this,obj,clazz);
     }
 
@@ -873,319 +878,319 @@
 	va_start(args,methodID);
 	result = functions->CallObjectMethodV(this,obj,methodID,args);
 	va_end(args);
 	return result;
     }
     jobject CallObjectMethodV(jobject obj, jmethodID methodID,
 			va_list args) {
         return functions->CallObjectMethodV(this,obj,methodID,args);
     }
     jobject CallObjectMethodA(jobject obj, jmethodID methodID,
-			jvalue * args) {
+			const jvalue * args) {
         return functions->CallObjectMethodA(this,obj,methodID,args);
     }
 
     jboolean CallBooleanMethod(jobject obj,
 			       jmethodID methodID, ...) {
         va_list args;
 	jboolean result;
 	va_start(args,methodID);
 	result = functions->CallBooleanMethodV(this,obj,methodID,args);
 	va_end(args);
 	return result;
     }
     jboolean CallBooleanMethodV(jobject obj, jmethodID methodID,
 				va_list args) {
         return functions->CallBooleanMethodV(this,obj,methodID,args);
     }
     jboolean CallBooleanMethodA(jobject obj, jmethodID methodID,
-				jvalue * args) {
+				const jvalue * args) {
         return functions->CallBooleanMethodA(this,obj,methodID, args);
     }
 
     jbyte CallByteMethod(jobject obj, jmethodID methodID, ...) {
         va_list args;
 	jbyte result;
 	va_start(args,methodID);
 	result = functions->CallByteMethodV(this,obj,methodID,args);
 	va_end(args);
 	return result;
     }
     jbyte CallByteMethodV(jobject obj, jmethodID methodID,
 			  va_list args) {
         return functions->CallByteMethodV(this,obj,methodID,args);
     }
     jbyte CallByteMethodA(jobject obj, jmethodID methodID,
-			  jvalue * args) {
+			  const jvalue * args) {
         return functions->CallByteMethodA(this,obj,methodID,args);
     }
 
     jchar CallCharMethod(jobject obj, jmethodID methodID, ...) {
         va_list args;
 	jchar result;
 	va_start(args,methodID);
 	result = functions->CallCharMethodV(this,obj,methodID,args);
 	va_end(args);
 	return result;
     }
     jchar CallCharMethodV(jobject obj, jmethodID methodID,
 			  va_list args) {
         return functions->CallCharMethodV(this,obj,methodID,args);
     }
     jchar CallCharMethodA(jobject obj, jmethodID methodID,
-			  jvalue * args) {
+			  const jvalue * args) {
         return functions->CallCharMethodA(this,obj,methodID,args);
     }
 
     jshort CallShortMethod(jobject obj, jmethodID methodID, ...) {
         va_list args;
 	jshort result;
 	va_start(args,methodID);
 	result = functions->CallShortMethodV(this,obj,methodID,args);
 	va_end(args);
 	return result;
     }
     jshort CallShortMethodV(jobject obj, jmethodID methodID,
 			    va_list args) {
         return functions->CallShortMethodV(this,obj,methodID,args);
     }
     jshort CallShortMethodA(jobject obj, jmethodID methodID,
-			    jvalue * args) {
+			    const jvalue * args) {
         return functions->CallShortMethodA(this,obj,methodID,args);
     }
 
     jint CallIntMethod(jobject obj, jmethodID methodID, ...) {
         va_list args;
 	jint result;
 	va_start(args,methodID);
 	result = functions->CallIntMethodV(this,obj,methodID,args);
 	va_end(args);
 	return result;
     }
     jint CallIntMethodV(jobject obj, jmethodID methodID,
 			va_list args) {
         return functions->CallIntMethodV(this,obj,methodID,args);
     }
     jint CallIntMethodA(jobject obj, jmethodID methodID,
-			jvalue * args) {
+			const jvalue * args) {
         return functions->CallIntMethodA(this,obj,methodID,args);
     }
 
     jlong CallLongMethod(jobject obj, jmethodID methodID, ...) {
         va_list args;
 	jlong result;
 	va_start(args,methodID);
 	result = functions->CallLongMethodV(this,obj,methodID,args);
 	va_end(args);
 	return result;
     }
     jlong CallLongMethodV(jobject obj, jmethodID methodID,
 			  va_list args) {
         return functions->CallLongMethodV(this,obj,methodID,args);
     }
     jlong CallLongMethodA(jobject obj, jmethodID methodID,
-			  jvalue * args) {
+			  const jvalue * args) {
         return functions->CallLongMethodA(this,obj,methodID,args);
     }
 
     jfloat CallFloatMethod(jobject obj, jmethodID methodID, ...) {
         va_list args;
 	jfloat result;
 	va_start(args,methodID);
 	result = functions->CallFloatMethodV(this,obj,methodID,args);
 	va_end(args);
 	return result;
     }
     jfloat CallFloatMethodV(jobject obj, jmethodID methodID,
 			    va_list args) {
         return functions->CallFloatMethodV(this,obj,methodID,args);
     }
     jfloat CallFloatMethodA(jobject obj, jmethodID methodID,
-			    jvalue * args) {
+			    const jvalue * args) {
         return functions->CallFloatMethodA(this,obj,methodID,args);
     }
 
     jdouble CallDoubleMethod(jobject obj, jmethodID methodID, ...) {
         va_list args;
 	jdouble result;
 	va_start(args,methodID);
 	result = functions->CallDoubleMethodV(this,obj,methodID,args);
 	va_end(args);
 	return result;
     }
     jdouble CallDoubleMethodV(jobject obj, jmethodID methodID,
 			va_list args) {
         return functions->CallDoubleMethodV(this,obj,methodID,args);
     }
     jdouble CallDoubleMethodA(jobject obj, jmethodID methodID,
-			jvalue * args) {
+			const jvalue * args) {
         return functions->CallDoubleMethodA(this,obj,methodID,args);
     }
 
     void CallVoidMethod(jobject obj, jmethodID methodID, ...) {
         va_list args;
 	va_start(args,methodID);
 	functions->CallVoidMethodV(this,obj,methodID,args);
 	va_end(args);
     }
     void CallVoidMethodV(jobject obj, jmethodID methodID,
 			 va_list args) {
         functions->CallVoidMethodV(this,obj,methodID,args);
     }
     void CallVoidMethodA(jobject obj, jmethodID methodID,
-			 jvalue * args) {
+			 const jvalue * args) {
         functions->CallVoidMethodA(this,obj,methodID,args);
     }
 
     jobject CallNonvirtualObjectMethod(jobject obj, jclass clazz,
 				       jmethodID methodID, ...) {
         va_list args;
 	jobject result;
 	va_start(args,methodID);
 	result = functions->CallNonvirtualObjectMethodV(this,obj,clazz,
 							methodID,args);
 	va_end(args);
 	return result;
     }
     jobject CallNonvirtualObjectMethodV(jobject obj, jclass clazz,
 					jmethodID methodID, va_list args) {
         return functions->CallNonvirtualObjectMethodV(this,obj,clazz,
 						      methodID,args);
     }
     jobject CallNonvirtualObjectMethodA(jobject obj, jclass clazz,
-					jmethodID methodID, jvalue * args) {
+					jmethodID methodID, const jvalue * args) {
         return functions->CallNonvirtualObjectMethodA(this,obj,clazz,
 						      methodID,args);
     }
 
     jboolean CallNonvirtualBooleanMethod(jobject obj, jclass clazz,
 					 jmethodID methodID, ...) {
         va_list args;
 	jboolean result;
 	va_start(args,methodID);
 	result = functions->CallNonvirtualBooleanMethodV(this,obj,clazz,
 							 methodID,args);
 	va_end(args);
 	return result;
     }
     jboolean CallNonvirtualBooleanMethodV(jobject obj, jclass clazz,
 					  jmethodID methodID, va_list args) {
         return functions->CallNonvirtualBooleanMethodV(this,obj,clazz,
 						       methodID,args);
     }
     jboolean CallNonvirtualBooleanMethodA(jobject obj, jclass clazz,
-					  jmethodID methodID, jvalue * args) {
+					  jmethodID methodID, const jvalue * args) {
         return functions->CallNonvirtualBooleanMethodA(this,obj,clazz,
 						       methodID, args);
     }
 
     jbyte CallNonvirtualByteMethod(jobject obj, jclass clazz,
 				   jmethodID methodID, ...) {
         va_list args;
 	jbyte result;
 	va_start(args,methodID);
 	result = functions->CallNonvirtualByteMethodV(this,obj,clazz,
 						      methodID,args);
 	va_end(args);
 	return result;
     }
     jbyte CallNonvirtualByteMethodV(jobject obj, jclass clazz,
 				    jmethodID methodID, va_list args) {
         return functions->CallNonvirtualByteMethodV(this,obj,clazz,
 						    methodID,args);
     }
     jbyte CallNonvirtualByteMethodA(jobject obj, jclass clazz,
-				    jmethodID methodID, jvalue * args) {
+				    jmethodID methodID, const jvalue * args) {
         return functions->CallNonvirtualByteMethodA(this,obj,clazz,
 						    methodID,args);
     }
 
     jchar CallNonvirtualCharMethod(jobject obj, jclass clazz,
 				   jmethodID methodID, ...) {
         va_list args;
 	jchar result;
 	va_start(args,methodID);
 	result = functions->CallNonvirtualCharMethodV(this,obj,clazz,
 						      methodID,args);
 	va_end(args);
 	return result;
     }
     jchar CallNonvirtualCharMethodV(jobject obj, jclass clazz,
 				    jmethodID methodID, va_list args) {
         return functions->CallNonvirtualCharMethodV(this,obj,clazz,
 						    methodID,args);
     }
     jchar CallNonvirtualCharMethodA(jobject obj, jclass clazz,
-				    jmethodID methodID, jvalue * args) {
+				    jmethodID methodID, const jvalue * args) {
         return functions->CallNonvirtualCharMethodA(this,obj,clazz,
 						    methodID,args);
     }
 
     jshort CallNonvirtualShortMethod(jobject obj, jclass clazz,
 				     jmethodID methodID, ...) {
         va_list args;
 	jshort result;
 	va_start(args,methodID);
 	result = functions->CallNonvirtualShortMethodV(this,obj,clazz,
 						       methodID,args);
 	va_end(args);
 	return result;
     }
     jshort CallNonvirtualShortMethodV(jobject obj, jclass clazz,
 				      jmethodID methodID, va_list args) {
         return functions->CallNonvirtualShortMethodV(this,obj,clazz,
 						     methodID,args);
     }
     jshort CallNonvirtualShortMethodA(jobject obj, jclass clazz,
-				      jmethodID methodID, jvalue * args) {
+				      jmethodID methodID, const jvalue * args) {
         return functions->CallNonvirtualShortMethodA(this,obj,clazz,
 						     methodID,args);
     }
 
     jint CallNonvirtualIntMethod(jobject obj, jclass clazz,
 				 jmethodID methodID, ...) {
         va_list args;
 	jint result;
 	va_start(args,methodID);
 	result = functions->CallNonvirtualIntMethodV(this,obj,clazz,
 						     methodID,args);
 	va_end(args);
 	return result;
     }
     jint CallNonvirtualIntMethodV(jobject obj, jclass clazz,
 				  jmethodID methodID, va_list args) {
         return functions->CallNonvirtualIntMethodV(this,obj,clazz,
 						   methodID,args);
     }
     jint CallNonvirtualIntMethodA(jobject obj, jclass clazz,
-				  jmethodID methodID, jvalue * args) {
+				  jmethodID methodID, const jvalue * args) {
         return functions->CallNonvirtualIntMethodA(this,obj,clazz,
 						   methodID,args);
     }
 
     jlong CallNonvirtualLongMethod(jobject obj, jclass clazz,
 				   jmethodID methodID, ...) {
         va_list args;
 	jlong result;
 	va_start(args,methodID);
 	result = functions->CallNonvirtualLongMethodV(this,obj,clazz,
 						      methodID,args);
 	va_end(args);
 	return result;
     }
     jlong CallNonvirtualLongMethodV(jobject obj, jclass clazz,
 				    jmethodID methodID, va_list args) {
         return functions->CallNonvirtualLongMethodV(this,obj,clazz,
 						    methodID,args);
     }
     jlong CallNonvirtualLongMethodA(jobject obj, jclass clazz,
-				    jmethodID methodID, jvalue * args) {
+				    jmethodID methodID, const jvalue * args) {
         return functions->CallNonvirtualLongMethodA(this,obj,clazz,
 						    methodID,args);
     }
 
     jfloat CallNonvirtualFloatMethod(jobject obj, jclass clazz,
 				     jmethodID methodID, ...) {
         va_list args;
 	jfloat result;
 	va_start(args,methodID);
 	result = functions->CallNonvirtualFloatMethodV(this,obj,clazz,
@@ -1194,21 +1199,21 @@
 	return result;
     }
     jfloat CallNonvirtualFloatMethodV(jobject obj, jclass clazz,
 				      jmethodID methodID,
 				      va_list args) {
         return functions->CallNonvirtualFloatMethodV(this,obj,clazz,
 						     methodID,args);
     }
     jfloat CallNonvirtualFloatMethodA(jobject obj, jclass clazz,
 				      jmethodID methodID,
-				      jvalue * args) {
+				      const jvalue * args) {
         return functions->CallNonvirtualFloatMethodA(this,obj,clazz,
 						     methodID,args);
     }
 
     jdouble CallNonvirtualDoubleMethod(jobject obj, jclass clazz,
 				       jmethodID methodID, ...) {
         va_list args;
 	jdouble result;
 	va_start(args,methodID);
 	result = functions->CallNonvirtualDoubleMethodV(this,obj,clazz,
@@ -1217,40 +1222,40 @@
 	return result;
     }
     jdouble CallNonvirtualDoubleMethodV(jobject obj, jclass clazz,
 					jmethodID methodID,
 					va_list args) {
         return functions->CallNonvirtualDoubleMethodV(this,obj,clazz,
 						      methodID,args);
     }
     jdouble CallNonvirtualDoubleMethodA(jobject obj, jclass clazz,
 					jmethodID methodID,
-					jvalue * args) {
+					const jvalue * args) {
         return functions->CallNonvirtualDoubleMethodA(this,obj,clazz,
 						      methodID,args);
     }
 
     void CallNonvirtualVoidMethod(jobject obj, jclass clazz,
 				  jmethodID methodID, ...) {
         va_list args;
 	va_start(args,methodID);
 	functions->CallNonvirtualVoidMethodV(this,obj,clazz,methodID,args);
 	va_end(args);
     }
     void CallNonvirtualVoidMethodV(jobject obj, jclass clazz,
 				   jmethodID methodID,
 				   va_list args) {
         functions->CallNonvirtualVoidMethodV(this,obj,clazz,methodID,args);
     }
     void CallNonvirtualVoidMethodA(jobject obj, jclass clazz,
 				   jmethodID methodID,
-				   jvalue * args) {
+				   const jvalue * args) {
         functions->CallNonvirtualVoidMethodA(this,obj,clazz,methodID,args);
     }
 
     jfieldID GetFieldID(jclass clazz, const char *name,
 			const char *sig) {
         return functions->GetFieldID(this,clazz,name,sig);
     }
 
     jobject GetObjectField(jobject obj, jfieldID fieldID) {
         return functions->GetObjectField(this,obj,fieldID);
@@ -1328,180 +1333,180 @@
 	va_start(args,methodID);
 	result = functions->CallStaticObjectMethodV(this,clazz,methodID,args);
 	va_end(args);
 	return result;
     }
     jobject CallStaticObjectMethodV(jclass clazz, jmethodID methodID,
 			      va_list args) {
         return functions->CallStaticObjectMethodV(this,clazz,methodID,args);
     }
     jobject CallStaticObjectMethodA(jclass clazz, jmethodID methodID,
-			      jvalue *args) {
+			      const jvalue *args) {
         return functions->CallStaticObjectMethodA(this,clazz,methodID,args);
     }
 
     jboolean CallStaticBooleanMethod(jclass clazz,
 				     jmethodID methodID, ...) {
         va_list args;
 	jboolean result;
 	va_start(args,methodID);
 	result = functions->CallStaticBooleanMethodV(this,clazz,methodID,args);
 	va_end(args);
 	return result;
     }
     jboolean CallStaticBooleanMethodV(jclass clazz,
 				      jmethodID methodID, va_list args) {
         return functions->CallStaticBooleanMethodV(this,clazz,methodID,args);
     }
     jboolean CallStaticBooleanMethodA(jclass clazz,
-				      jmethodID methodID, jvalue *args) {
+				      jmethodID methodID, const jvalue *args) {
         return functions->CallStaticBooleanMethodA(this,clazz,methodID,args);
     }
 
     jbyte CallStaticByteMethod(jclass clazz,
 			       jmethodID methodID, ...) {
         va_list args;
 	jbyte result;
 	va_start(args,methodID);
 	result = functions->CallStaticByteMethodV(this,clazz,methodID,args);
 	va_end(args);
 	return result;
     }
     jbyte CallStaticByteMethodV(jclass clazz,
 				jmethodID methodID, va_list args) {
         return functions->CallStaticByteMethodV(this,clazz,methodID,args);
     }
     jbyte CallStaticByteMethodA(jclass clazz,
-				jmethodID methodID, jvalue *args) {
+				jmethodID methodID, const jvalue *args) {
         return functions->CallStaticByteMethodA(this,clazz,methodID,args);
     }
 
     jchar CallStaticCharMethod(jclass clazz,
 			       jmethodID methodID, ...) {
         va_list args;
 	jchar result;
 	va_start(args,methodID);
 	result = functions->CallStaticCharMethodV(this,clazz,methodID,args);
 	va_end(args);
 	return result;
     }
     jchar CallStaticCharMethodV(jclass clazz,
 				jmethodID methodID, va_list args) {
         return functions->CallStaticCharMethodV(this,clazz,methodID,args);
     }
     jchar CallStaticCharMethodA(jclass clazz,
-				jmethodID methodID, jvalue *args) {
+				jmethodID methodID, const jvalue *args) {
         return functions->CallStaticCharMethodA(this,clazz,methodID,args);
     }
 
     jshort CallStaticShortMethod(jclass clazz,
 				 jmethodID methodID, ...) {
         va_list args;
 	jshort result;
 	va_start(args,methodID);
 	result = functions->CallStaticShortMethodV(this,clazz,methodID,args);
 	va_end(args);
 	return result;
     }
     jshort CallStaticShortMethodV(jclass clazz,
 				  jmethodID methodID, va_list args) {
         return functions->CallStaticShortMethodV(this,clazz,methodID,args);
     }
     jshort CallStaticShortMethodA(jclass clazz,
-				  jmethodID methodID, jvalue *args) {
+				  jmethodID methodID, const jvalue *args) {
         return functions->CallStaticShortMethodA(this,clazz,methodID,args);
     }
 
     jint CallStaticIntMethod(jclass clazz,
 			     jmethodID methodID, ...) {
         va_list args;
 	jint result;
 	va_start(args,methodID);
 	result = functions->CallStaticIntMethodV(this,clazz,methodID,args);
 	va_end(args);
 	return result;
     }
     jint CallStaticIntMethodV(jclass clazz,
 			      jmethodID methodID, va_list args) {
         return functions->CallStaticIntMethodV(this,clazz,methodID,args);
     }
     jint CallStaticIntMethodA(jclass clazz,
-			      jmethodID methodID, jvalue *args) {
+			      jmethodID methodID, const jvalue *args) {
         return functions->CallStaticIntMethodA(this,clazz,methodID,args);
     }
 
     jlong CallStaticLongMethod(jclass clazz,
 			       jmethodID methodID, ...) {
         va_list args;
 	jlong result;
 	va_start(args,methodID);
 	result = functions->CallStaticLongMethodV(this,clazz,methodID,args);
 	va_end(args);
 	return result;
     }
     jlong CallStaticLongMethodV(jclass clazz,
 				jmethodID methodID, va_list args) {
         return functions->CallStaticLongMethodV(this,clazz,methodID,args);
     }
     jlong CallStaticLongMethodA(jclass clazz,
-				jmethodID methodID, jvalue *args) {
+				jmethodID methodID, const jvalue *args) {
         return functions->CallStaticLongMethodA(this,clazz,methodID,args);
     }
 
     jfloat CallStaticFloatMethod(jclass clazz,
 				 jmethodID methodID, ...) {
         va_list args;
 	jfloat result;
 	va_start(args,methodID);
 	result = functions->CallStaticFloatMethodV(this,clazz,methodID,args);
 	va_end(args);
 	return result;
     }
     jfloat CallStaticFloatMethodV(jclass clazz,
 				  jmethodID methodID, va_list args) {
         return functions->CallStaticFloatMethodV(this,clazz,methodID,args);
     }
     jfloat CallStaticFloatMethodA(jclass clazz,
-				  jmethodID methodID, jvalue *args) {
+				  jmethodID methodID, const jvalue *args) {
         return functions->CallStaticFloatMethodA(this,clazz,methodID,args);
     }
 
     jdouble CallStaticDoubleMethod(jclass clazz,
 				   jmethodID methodID, ...) {
         va_list args;
 	jdouble result;
 	va_start(args,methodID);
 	result = functions->CallStaticDoubleMethodV(this,clazz,methodID,args);
 	va_end(args);
 	return result;
     }
     jdouble CallStaticDoubleMethodV(jclass clazz,
 				    jmethodID methodID, va_list args) {
         return functions->CallStaticDoubleMethodV(this,clazz,methodID,args);
     }
     jdouble CallStaticDoubleMethodA(jclass clazz,
-				    jmethodID methodID, jvalue *args) {
+				    jmethodID methodID, const jvalue *args) {
         return functions->CallStaticDoubleMethodA(this,clazz,methodID,args);
     }
 
     void CallStaticVoidMethod(jclass cls, jmethodID methodID, ...) {
         va_list args;
 	va_start(args,methodID);
 	functions->CallStaticVoidMethodV(this,cls,methodID,args);
 	va_end(args);
     }
     void CallStaticVoidMethodV(jclass cls, jmethodID methodID,
 			       va_list args) {
         functions->CallStaticVoidMethodV(this,cls,methodID,args);
     }
     void CallStaticVoidMethodA(jclass cls, jmethodID methodID,
-			       jvalue * args) {
+			       const jvalue * args) {
         functions->CallStaticVoidMethodA(this,cls,methodID,args);
     }
 
     jfieldID GetStaticFieldID(jclass clazz, const char *name,
 			      const char *sig) {
         return functions->GetStaticFieldID(this,clazz,name,sig);
     }
     jobject GetStaticObjectField(jclass clazz, jfieldID fieldID) {
         return functions->GetStaticObjectField(this,clazz,fieldID);
     }
@@ -1727,49 +1732,49 @@
     void GetFloatArrayRegion(jfloatArray array,
 			     jsize start, jsize len, jfloat *buf) {
         functions->GetFloatArrayRegion(this,array,start,len,buf);
     }
     void GetDoubleArrayRegion(jdoubleArray array,
 			      jsize start, jsize len, jdouble *buf) {
         functions->GetDoubleArrayRegion(this,array,start,len,buf);
     }
 
     void SetBooleanArrayRegion(jbooleanArray array, jsize start, jsize len,
-			       jboolean *buf) {
+			       const jboolean *buf) {
         functions->SetBooleanArrayRegion(this,array,start,len,buf);
     }
     void SetByteArrayRegion(jbyteArray array, jsize start, jsize len,
-			    jbyte *buf) {
+			    const jbyte *buf) {
         functions->SetByteArrayRegion(this,array,start,len,buf);
     }
     void SetCharArrayRegion(jcharArray array, jsize start, jsize len,
-			    jchar *buf) {
+			    const jchar *buf) {
         functions->SetCharArrayRegion(this,array,start,len,buf);
     }
     void SetShortArrayRegion(jshortArray array, jsize start, jsize len,
-			     jshort *buf) {
+			     const jshort *buf) {
         functions->SetShortArrayRegion(this,array,start,len,buf);
     }
     void SetIntArrayRegion(jintArray array, jsize start, jsize len,
-			   jint *buf) {
+			   const jint *buf) {
         functions->SetIntArrayRegion(this,array,start,len,buf);
     }
     void SetLongArrayRegion(jlongArray array, jsize start, jsize len,
-			    jlong *buf) {
+			    const jlong *buf) {
         functions->SetLongArrayRegion(this,array,start,len,buf);
     }
     void SetFloatArrayRegion(jfloatArray array, jsize start, jsize len,
-			     jfloat *buf) {
+			     const jfloat *buf) {
         functions->SetFloatArrayRegion(this,array,start,len,buf);
     }
     void SetDoubleArrayRegion(jdoubleArray array, jsize start, jsize len,
-			      jdouble *buf) {
+			      const jdouble *buf) {
         functions->SetDoubleArrayRegion(this,array,start,len,buf);
     }
 
     jint RegisterNatives(jclass clazz, const JNINativeMethod *methods,
 			 jint nMethods) {
         return functions->RegisterNatives(this,clazz,methods,nMethods);
     }
     jint UnregisterNatives(jclass clazz) {
         return functions->UnregisterNatives(this,clazz);
     }
@@ -1810,20 +1815,30 @@
         return functions->NewWeakGlobalRef(this,obj);
     }
     void DeleteWeakGlobalRef(jweak ref) {
         functions->DeleteWeakGlobalRef(this,ref);
     }
 
     jboolean ExceptionCheck() {
 	return functions->ExceptionCheck(this);
     }
 
+    jobject NewDirectByteBuffer(void* address, jlong capacity) {
+        return functions->NewDirectByteBuffer(this, address, capacity);
+    }
+    void* GetDirectBufferAddress(jobject buf) {
+        return functions->GetDirectBufferAddress(this, buf);
+    }
+    jlong GetDirectBufferCapacity(jobject buf) {
+        return functions->GetDirectBufferCapacity(this, buf);
+    }
+
 #endif /* __cplusplus */
 };
 
 typedef struct JavaVMOption {
     char *optionString;
     void *extraInfo;
 } JavaVMOption;
 
 typedef struct JavaVMInitArgs {
     jint version;
@@ -1864,62 +1879,68 @@
     jint verbose;
     jboolean debugging;
     jint debugPort;
 } JDK1_1InitArgs;
 
 typedef struct JDK1_1AttachArgs {
     void * __padding; /* C compilers don't allow empty structures. */
 } JDK1_1AttachArgs;
 
 #define JDK1_2
+#define JDK1_4
 
 /* End VM-specific. */
 
 struct JNIInvokeInterface_ {
     void *reserved0;
     void *reserved1;
     void *reserved2;
 
-#if !TARGET_RT_MAC_CFM
+#if !TARGET_RT_MAC_CFM && defined(__ppc__)
     void* cfm_vectors[4];
-#endif /* !TARGET_RT_MAC_CFM */
+#endif /* !TARGET_RT_MAC_CFM && defined(__ppc__) */
 
     jint (JNICALL *DestroyJavaVM)(JavaVM *vm);
 
     jint (JNICALL *AttachCurrentThread)(JavaVM *vm, void **penv, void *args);
 
     jint (JNICALL *DetachCurrentThread)(JavaVM *vm);
 
     jint (JNICALL *GetEnv)(JavaVM *vm, void **penv, jint version);
+
+    jint (JNICALL *AttachCurrentThreadAsDaemon)(JavaVM *vm, void **penv, void *args);
     
-#if TARGET_RT_MAC_CFM
-    void* real_functions[4];
-#endif /* TARGET_RT_MAC_CFM */
+#if TARGET_RT_MAC_CFM && defined(__ppc__)
+    void* real_functions[5];
+#endif /* TARGET_RT_MAC_CFM && defined(__ppc__) */
 };
 
 struct JavaVM_ {
     const struct JNIInvokeInterface_ *functions;
 #ifdef __cplusplus
 
     jint DestroyJavaVM() {
         return functions->DestroyJavaVM(this);
     }
     jint AttachCurrentThread(void **penv, void *args) {
         return functions->AttachCurrentThread(this, penv, args);
     }
     jint DetachCurrentThread() {
         return functions->DetachCurrentThread(this);
     }
 
     jint GetEnv(void **penv, jint version) {
         return functions->GetEnv(this, penv, version);
     }
+    jint AttachCurrentThreadAsDaemon(void **penv, void *args) {
+        return functions->AttachCurrentThreadAsDaemon(this, penv, args);
+    }
 #endif
 };
 
 #ifdef _JNI_IMPLEMENTATION_
 #define _JNI_IMPORT_OR_EXPORT_ JNIEXPORT
 #else
 #define _JNI_IMPORT_OR_EXPORT_ JNIIMPORT
 #endif
 _JNI_IMPORT_OR_EXPORT_ jint JNICALL
 JNI_GetDefaultJavaVMInitArgs(void *args);
@@ -1932,18 +1953,17 @@
 
 /* Defined by native libraries. */
 JNIEXPORT jint JNICALL
 JNI_OnLoad(JavaVM *vm, void *reserved);
 
 JNIEXPORT void JNICALL
 JNI_OnUnload(JavaVM *vm, void *reserved);
 
 #define JNI_VERSION_1_1 0x00010001
 #define JNI_VERSION_1_2 0x00010002
+#define JNI_VERSION_1_4 0x00010004
 
 #ifdef __cplusplus
 } /* extern "C" */
 #endif /* __cplusplus */
 
 #endif /* !_JAVASOFT_JNI_H_ */
-
-
diff -U 10 -r -N old/plugin/oji/MRJCarbon/plugin/Changes-JEP.txt new/plugin/oji/MRJCarbon/plugin/Changes-JEP.txt
--- old/plugin/oji/MRJCarbon/plugin/Changes-JEP.txt	1969-12-31 18:00:00.000000000 -0600
+++ new/plugin/oji/MRJCarbon/plugin/Changes-JEP.txt	2007-04-17 09:24:20.000000000 -0500
@@ -0,0 +1,330 @@
+Changes to the MRJ Plugin Carbon for the Java Embedding Plugin
+
+A) Changes related to the Java Embedding Plugin
+
+1. Added calls to Java Embedding Plugin routines (all of whose names
+   start with "JEP") to MRJSession.cpp and (especially) MRJContext.cp.
+   Added supporting code to MRJContext.cp and MRJContext.h.  Added the
+   API header file JavaEmbeddingPlugin.h.
+
+2. Added JavaEmbeddingPlugin.cpp, which allows support for the Java
+   Embedding Plugin API to be conditional:  Support is enabled only if
+   JavaEmbeddingPlugin.bundle can be found.  Otherwise the MRJ Plugin
+   Carbon falls back to using Apple's Java Embedding Framework.
+
+3. Added MIME types for Java 1.4.X and 1.5 to the MRJ Plugin Carbon's
+   STR# resources (in the Strings.rsrc file).
+
+4. Changed various resource strings to make the copyright and version
+   information consistent and to mention the Java Embedding Plugin.
+
+5. Removed the JSObject class's "final" modifier (in JSObject.java in
+   js/src/liveconnect/classes/netscape/javascript).  This allows
+   apple.applet.JSObject (present in Java 1.4.2 through Update 2) or
+   sun.plugin.javascript.webkit.JSObject (present in later versions)
+   to override it -- which in turn allows the Java Embedding Plugin to
+   load libAppletsInCocoa.jnilib (or JavaPluginCocoa in Update 1 and
+   later), which avoids various UnsatisfiedLinkError messages.
+
+6. Changed how the JVM is started and applets are created, to better
+   accomodate the asynchronicity of these procedures.  The changes
+   were much bigger for Java 1.4.X than for Java 1.3.1.  For more
+   information see CreateJVM(), OpenSessionJNI(), InitSecurityJNI()
+   and afterInitAWT() in MRJSession.cpp, appletCreatedCallback() and
+   loadApplet() in MRJContext.cp, and AppletView's loadAWTLibraries
+   and initWithParams methods in JEP's AppletView.m.
+
+7. Now detects whether or not the HTML that invoked an applet
+   specified its "width" and "height" using absolute numbers of pixels
+   or percentages of the space available.  In the latter case (on Java
+   1.4.X and higher) the Java Embedding Plugin will resize the applet
+   "natively".  See MRJContext::fixAttributes(), JEPController
+   fixAttributes and AppletFrame.resizeApplet() for more information.
+
+8. Tightened up the code that implements security settings, and
+   altered it to accomodate the different needs of the Java 1.4.X and
+   Java 1.3.1 JVMs.  See MRJSession.java for more information.
+
+9. Added a JEPDoLiveConnectProxy() call to the Java Embedding Plugin
+   API to make it possible to do JavaScript-to-Java LiveConnect on
+   Tiger.  The Mozilla-family browsers always do JavaScript on the
+   main thread.  But for Tiger compatibility, JavaScript-to-Java calls
+   that can trigger Java drawing need to run on a secondary thread.
+   This is handled by JEPDoLiveConnectProxy() in the JEP's
+   Controller.m and by LiveConnect.java.  The new API also ensures (on
+   all Java 1.4.X and 1.5.X versions) that an autorelease pool is in
+   place during JavaScript-to-Java LiveConnect.
+
+10. Added support for getting and setting cookies (via the
+   nsICookieStorage interface) in Mozilla.org browsers.
+
+   See MRJGetCookie() and MRJSetCookie() in MRJPlugin.cpp.
+
+11. Added support for getting a JSObject for a particular
+   MRJPluginInstance without using the Java-to-JavaScript
+   JSObject.getWindow() method.  This is needed to support automatic
+   proxy configuration.
+
+   For more information see MRJGetJSObject() and the
+   GetWindowAltMessage class in LiveConnectNativeMethods.cpp.
+
+B) Unrelated Bug Fixes or Changes
+
+1. Disabled all the "SupportsMixin" code.
+
+   As best I can tell this code is supposed to make it easier to use
+   XPCOM's "QueryInterface" functionality (see
+   http://www.geocrawler.com/archives/3/137/1999/2/0/1048574/, which
+   is the only reference I've been able to find outside the source
+   code itself).  But in at least one case, it causes a crash by (in
+   effect) making QueryInterface() return the wrong answer!  (The
+   browser queries for the nsIJVMPluginInstance interface on an
+   MRJPluginInstance object, with the intention of calling its
+   GetJavaObject() method.  Instead it gets the nsIPluginInstance
+   interface and ends up calling the Initialize() method ... which of
+   course leads to a crash.)
+
+   I didn't feel like spending huge amounts of time fixing the
+   SupportsMixin code (which is very cryptic) and then testing it
+   comprehensively.  So I just disabled all of it (which only took a
+   couple of hours).
+
+2. Fixed a crash bug in GetLiveConnectProxy() in CSecureEnv.cpp --
+   until I added a test to prevent it, the code could (and often did)
+   dereference a null pointer.
+
+3. Fixed a couple of Java class specifications in JNI code in
+   CSecureEnv.cpp -- they used '.' for the path separator, but it
+   should be '/'.
+
+4. Added a PkgInfo file:  This makes OS X recognize the MRJ Plugin
+   Carbon as a plugin.
+
+5. Got rid of a block of code in MRJContext.cp's
+   synchronizeVisibility() method which was causing applets to display
+   22 pixels higher than they should display -- whether using the Java
+   Embedding Plugin or the Java Embedding Framework.
+
+6. Changed the MRJSession::getCurrentEnv() method (in plugin/oji/
+   MRJCarbon/plugin/Source/MRJSession.cpp) to always return (and if
+   necessary create) a "JNI environment" usable in the current thread.
+
+7. Changed the getCurrentClassLoader() method of the
+   StubSecurityManager class (in JNIUtils.java) to get it to work
+   properly when we're running on the main thread with AllPermission.
+   The previous (unfixed) version caused JSObject.getWindow() to
+   always return null, which in turn disabled the Java-to-JavaScript
+   side of LiveConnect.
+
+8. Changed the ToGlobalRef(), Wrap_JSObject() and Unwrap_JSObject()
+   routines in LiveConnectNativeMethods.cpp and the GetVersion(),
+   FatalError(), DeleteGlobalRef() and GetJavaVM() routines in
+   CSecureEnv.cpp, to ensure that their 'env' parameters always point
+   to a "native" JNIEnv structure (instead of sometimes to a
+   ProxyJNIEnv class).  Before this change, LiveConnect methods other
+   than JSObject.getWindow() would sometimes crash mysteriously.
+
+9. Optimized Java-to-JavaScript calls -- speeding them up considerably
+   and avoiding certain kinds of hangs.  Previously, making a
+   Java-to-JavaScript call entailed posting a message to a different
+   thread, which would in turn post an encapsulated message to the
+   "JavaScript thread" (i.e. the main thread).  Now, if we're
+   currently running on the main thread I just execute the message
+   directly (this avoids the hang that would occur if we waited (on
+   the main thread) for the message to be executed (on the main
+   thread)).  And if we're currently running on a secondary thread, I
+   just post the message to the main thread -- using either
+   nsIJVMThreadManager::PostEvent() (on Java 1.3.1) or
+   JEPRunOnMainThread() on more recent Java versions.
+   JEPRunOnMainThread() is much more efficient than
+   nsIJVMThreadManager::PostEvent(), and less likely to cause hangs.
+   For more information see sendMessage() in
+   LiveConnectNativeMethods.cpp.
+
+10. Tightened up the code that detects when an applet has been or is
+   being loaded or destroyed.  For more information do a
+   case-insensitive search on "appletLoading", "isDestroying" and
+   "isValidInstance" in MRJContext.cp and MRJPlugin.cpp.
+
+11. Ensured that all Java-to-Javascript LiveConnect methods (members
+   of the JSObject class) wait, if need be, until the JavaScript
+   methods they invoke are finished, and that the current plugin
+   instance stays in existence while they're waiting.
+
+   Some of these methods can return values.  But when they're not
+   called on the main thread, their JavaScript counterparts are
+   invoked, asynchronously, on a different thread (the "JavaScript
+   thread", which is the main thread).  The original MRJ Plugin's
+   Java-to-Javascript calls make no provision to wait until the
+   JavaScript methods they've invoked have returned.  In most cases
+   these methods do return quickly enough, and there isn't any
+   trouble.  But sometimes they don't -- particularly when a
+   JavaScript method displays an alert box (in which case it doesn't
+   return until the user dismisses the box).  This leads to crashes
+   and other wierdness.
+
+   Version 0.8.3 of the MRJ Plugin JEP included a partial fix for this
+   problem which used a new call in the Embedding Plugin API --
+   JEPRunJRunnableOnMainThread().  But this "fix" didn't address the
+   real problem (which at that point I didn't understand), and I have
+   now removed it.  The MRJ Plugin JEP no longer has any "extraneous"
+   dependencies on JavaEmbeddingPlugin.bundle.
+
+   As of JEP 0.8.7, the Java-to-JavaScript methods that return values
+   can safely be made to time out after 2 seconds -- this is now the
+   default.
+
+   For more information see the JavaMessage class in
+   JavaMessageQueue.h and the code for all the Java-to-JavaScript
+   methods that return values in LiveConnectNativeMethods.cpp (an
+   example is Java_netscape_javascript_JSObject_getWindow()).
+
+12. Added a fix for the "Sun Java Plugin Arbitrary Package Access
+   Vulnerability" (which effects JavaScript-to-Java LiveConnect), as
+   reported at the following URLs:
+
+   http://securityfocus.com/archive/1/382072/2004-11-23/2004-11-29/0
+   http://securityfocus.com/archive/1/381940/2004-11-16/2004-11-22/0
+
+   The fix works for both Java 1.4.X (what you get when you use the
+   MRJ Plugin JEP with JavaEmbeddingPlugin.bundle) and Java 1.3.1
+   (what you get when you use the MRJ Plugin JEP by itself).  Earlier
+   versions (prior to 0.8.8) of the Java Embedding Plugin are
+   vulnerable, in both configurations.
+
+   As of version 0.8.8 the Java Embedding Plugin now passes the test
+   for this vulnerability at the following URLs, in both
+   configurations:
+
+   http://bcheck.scanit.be/bcheck/
+   http://bcheck.scanit.be/bcheck/choosetests.php
+
+   You might think that it's Apple's responsibility to fix this.  But
+   none of Apple's own products are vulnerable -- either because (like
+   the Java Applet.plugin and earlier versions of Safari) they don't
+   support LiveConnect at all, or because (like more recent versions
+   of Safari) their LiveConnect implementations have somehow avoided
+   the problem.  So I suspect that Apple may never release versions of
+   Java 1.4.X or Java 1.3.1 to address it.
+
+   Interestingly, the bcheck test crashes the current version of
+   Safari (the one that's included in Apple's 2004-12-02 security
+   update).  But I wrote a simpler test of my own (a "hello world"
+   applet plus the proof-of-concept JavaScript code given in Jouko
+   Pynnonen's advisory), which doesn't crash Safari and does (I think)
+   show that it's not vulnerable.
+
+   For more information see checkClassAccess() in JNIUtils.java and
+   Java_java_lang_Class_forName0_redirect() and InitSecurityJNI() in
+   MRJSession.cpp.
+
+13. Added code to fix a design flaw in the original MRJ Plugin -- it
+   sometimes fails to elevate a signed applet's privileges when the
+   applet's code is called via LiveConnect.  This helps when
+   connecting to http://hushmail.com/.  For more information see
+   fixProtectionDomains() in JNIUtils.java.
+
+14. Fixed a bug in MRJContext::setWindow() that occasionally causes it
+   to crash (with an access violation) when an applet is loaded --
+   sometimes loadApplet() takes so long that mPluginWindow is invalid
+   by the time it returns.
+
+15. Fixed a (minor) security hole in all of Apple's Java versions
+   (from 1.3.1 to 1.5.0), and in previous versions of the MRJPlugin
+   and MRJPlugin JEP, that allows an applet "Frame"'s methods (to
+   which access is normally forbidden) to be called from JavaScript.
+   For more information search on "getAppletFrame" in MRJSession.cpp.
+
+16. Added code to work around what I call the "spurious updates"
+   bug(s) in the Mozilla family of browsers.  All of these browsers
+   trigger large numbers of unnecessary screen updates (which trigger
+   calls to MRJContext::drawApplet()) and make many redundant calls to
+   SetWindow().  Camino even triggers one screen update for every
+   keystroke while the focus is in an applet.  Unless we do something
+   about it, this causes applets to flash annoyingly, sometimes
+   several times per second.
+
+   Some of the workarounds are in the MRJ Plugin JEP, in drawApplet(),
+   setWindow(), checkUpdateNeeded() and checkPaintNeeded() in
+   MRJContext.cp.  But, as of JEP 0.9.3, even more are in
+   JavaEmbeddingPlugin.bundle.  See item #1 in that version's
+   Changes.txt.
+
+17. Fixed a bug in the MRJPlugin that is triggered by more than one
+   applet on the same page doing Java-to-JavaScript LiveConnect -- the
+   MRJPlugin is sometimes mistaken about which applet a given call
+   comes from.  This caused some of the problems reported in bug
+   1086807 (at the following URL):
+
+   http://sourceforge.net/tracker/index.php?func=detail&aid=1086807&group_id=107955&atid=649116
+
+   For more information see GetAnInstance(JNIEnv *) and
+   GetAppletInstance(JNIEnv *, jobject) in
+   LiveConnectNativeMethods.cpp, and getApplet() in JSObject.java.
+
+18. Worked around a bug/design-flaw in Firefox 1.0RC1 (and later
+   versions on the "Aviary" branch) and Mozilla 1.7.5 (and later
+   versions on the "Mozilla 1.7" branch) which caused the MRJ Plugin
+   to crash when attempting JavaScript-to-Java LiveConnect.  For more
+   information see sendMessageToJava() in CSecureEnv.cpp.
+
+19. Fixed a major security hole in JavaScript-to-Java LiveConnect
+   triggered by recent changes to the nsIScriptSecurityManager
+   interface on the Mozilla "trunk".  The hole effects all nightlies,
+   alphas and betas of Mozilla-family browsers issued since
+   2004-04-25, but not any of the released versions.  So, for example,
+   Firefox 1.0.X, Mozilla 1.7.X and Camino 0.8.X aren't vulnerable.
+
+   In browsers effected by this hole, potentially all security checks
+   are disabled when doing JavaScript-to-Java LiveConnect.  So, for
+   example, my fix for the ""Sun Java Plugin Arbitrary Package Access
+   Vulnerability" (item #B12 above) doesn't work on any of the
+   vulnerable browsers on JEP versions earlier than 0.9.2 (the first
+   version to include this fix).
+
+   For more information see sendMessageToJava() in CSecureEnv.cpp and
+   https://bugzilla.mozilla.org/show_bug.cgi?id=293973.  Though some
+   of these changes took place quite a while ago, I was unaware until
+   very recently of those on the "trunk" -- because JavaScript-to-Java
+   LiveConnect appeared to continue to work, though its security was
+   broken.
+
+   Part of my fix for this problem is code that will cause
+   JavaScript-to-Java LiveConnect to fail if/when Mozilla.org makes
+   further changes to the nsIScriptSecurityManager interface that the
+   MRJ Plugin JEP is not yet aware of.
+
+20. Fixed a problem with Java-to-JavaScript LiveConnect that caused
+   hangs when several calls are made in succession to JSObject.call()
+   or JSObject.eval() that trigger the display of JavaScript alert()
+   messages.  For more information see the CallMessage and EvalMessage
+   classes in LiveConnectNativeMethods.cpp and other code nearby.
+
+21. Made changes to allow building the MRJ Plugin JEP inside more
+   recent Mozilla-family source distros than Mozilla 1.6.  For more
+   information see particularly the (conditional) definitions of
+   nsPluginThreadPtr and nsPluginThread in MRJPlugin.h (together with
+   the preceeding comment), and the conditional definition of
+   NS_COMPONENTMANAGER_CID in LiveConnectNativeMethods.cpp.
+
+   The MRJ Plugin JEP can now (as of JEP 0.9.3) be built inside a
+   built-from-source copy of any Mozilla-family browser from Mozilla
+   1.6 on, except for source trees pulled from the trunk between
+   2004-04-02 and 2004-05-13.  The comment above the definition of
+   nsPluginThreadPtr in MRJPlugin.h shows why this exclusion is
+   necessary.
+
+22. The Java Embedding Framework is now loaded dynamically.  And the
+   MRJ Plugin JEP refuses to instantiate itself if neither the Java
+   Embedding Framework nor the Java Embedding Plugin are present.
+   This is needed because the Java Embedding Framework will disappear
+   (along with Java 1.3.1) in the transition from PPC to Intel.
+
+   For more information see JavaEmbeddingFramework.cpp and
+   NSGetFactory() in MRJPlugin.cpp.
+
+23. Changed the resource files in the plugin/oji/MRJCarbon/plugin/
+   Resources/ directory from binary files (with names ending in
+   *.rsrc) to text files (with names ending in *.r).  This makes them
+   much easier to edit.
+
diff -U 10 -r -N old/plugin/oji/MRJCarbon/plugin/MRJPlugin.pbproj/project.pbxproj new/plugin/oji/MRJCarbon/plugin/MRJPlugin.pbproj/project.pbxproj
--- old/plugin/oji/MRJCarbon/plugin/MRJPlugin.pbproj/project.pbxproj	2003-06-11 00:11:30.000000000 -0500
+++ new/plugin/oji/MRJCarbon/plugin/MRJPlugin.pbproj/project.pbxproj	2007-10-06 20:48:02.000000000 -0500
@@ -29,39 +29,38 @@
 				19C28FB4FE9D528D11CA2CBB,
 			);
 			isa = PBXGroup;
 			name = MRJPlugin;
 			refType = 4;
 		};
 		089C1671FE841209C02AAC07 = {
 			children = (
 				08EA7FFBFE8413EDC02AAC07,
 				F535746F0299A36101FE39E3,
-				F53574700299A36101FE39E3,
-				F51A400C0299CD65012FC976,
 			);
 			isa = PBXGroup;
 			name = "External Frameworks and Libraries";
 			refType = 4;
 		};
 		089C1673FE841209C02AAC07 = {
 			buildPhases = (
 				089C1674FE841209C02AAC07,
 				089C1675FE841209C02AAC07,
 				089C1676FE841209C02AAC07,
 				089C1677FE841209C02AAC07,
 				089C1679FE841209C02AAC07,
 				F5BFB5E8029AD01B01000102,
+				DF80C69D06318E7400A80005,
 			);
 			buildSettings = {
 				FRAMEWORK_SEARCH_PATHS = "";
-				HEADER_SEARCH_PATHS = "../MRJSDK/JavaFrameworks/JavaVM ../MRJSDK/JavaFrameworks/JavaEmbedding ../../../../dist/sdk/xpcom/include ../../../../dist/include/caps ../../../../dist/include/java ../../../../dist/include/js ../../../../dist/include/nspr ../../../../dist/include/oji ../../../../dist/include/plugin ../../../../dist/include/xpcom ../../../../dist/include/xpconnect /Developer/Headers/FlatCarbon";
+				HEADER_SEARCH_PATHS = "../MRJSDK/JavaFrameworks/JavaVM ../MRJSDK/JavaFrameworks/JavaEmbedding ../../../../dist/sdk/xpcom/include ../../../../dist/include/caps ../../../../dist/include/java ../../../../dist/include/js ../../../../dist/include/liveconnect ../../../../dist/include/nspr ../../../../dist/include/oji ../../../../dist/include/plugin ../../../../dist/include/xpcom ../../../../dist/include/xpconnect ../../../../dist/include/widget /Developer/Headers/FlatCarbon";
 				LIBRARY_SEARCH_PATHS = /usr/lib;
 				OTHER_CFLAGS = "-DXP_MACOSX=1 -DNO_X11=1 -DUSE_SYSTEM_CONSOLE=1";
 				OTHER_LDFLAGS = "";
 				OTHER_REZFLAGS = "";
 				PRODUCT_NAME = MRJPlugin;
 				SECTORDER_FLAGS = "";
 				WARNING_CFLAGS = "-Wmost -Wno-four-char-constants -Wno-unknown-pragmas";
 				WRAPPER_EXTENSION = plugin;
 			};
 			dependencies = (
@@ -73,32 +72,38 @@
 			productName = MRJPlugin;
 			productReference = 4F9091AB011F3BD104CA0E50;
 			productSettingsXML = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>
 <!DOCTYPE plist SYSTEM \"file://localhost/System/Library/DTDs/PropertyList.dtd\">
 <plist version=\"0.9\">
 <dict>
 	<key>CFBundleDevelopmentRegion</key>
 	<string>English</string>
 	<key>CFBundleExecutable</key>
 	<string>MRJPlugin</string>
+	<key>CFBundleGetInfoString</key>
+	<string>MRJ Plugin 1.0-JEP-0.9.6.4, Copyright (c) 2002 The Mozilla Organization</string>
+	<key>CFBundleName</key>
+	<string>MRJ Plugin</string>
+	<key>CFBundleShortVersionString</key>
+	<string>1.0-JEP-0.9.6.4</string>
 	<key>CFBundleIconFile</key>
 	<string></string>
 	<key>CFBundleIdentifier</key>
 	<string>com.netscape.MRJPlugin</string>
 	<key>CFBundleInfoDictionaryVersion</key>
 	<string>6.0</string>
 	<key>CFBundlePackageType</key>
 	<string>NSPL</string>
 	<key>CFBundleSignature</key>
 	<string>MOSS</string>
 	<key>CFBundleVersion</key>
-	<string>1.0fc2</string>
+	<string>1.0-JEP-0.9.6.4</string>
 	<key>CSResourcesFileMapped</key>
 	<true/>
 </dict>
 </plist>
 ";
 			shouldUseHeadermap = 1;
 		};
 		089C1674FE841209C02AAC07 = {
 			buildActionMask = 2147483647;
 			files = (
@@ -110,41 +115,38 @@
 			buildActionMask = 2147483647;
 			files = (
 				089C1680FE841241C02AAC07,
 			);
 			isa = PBXResourcesBuildPhase;
 			name = "Bundle Resources";
 		};
 		089C1676FE841209C02AAC07 = {
 			buildActionMask = 2147483647;
 			files = (
-				F535747C0299B28B01FE39E3,
 				F53574820299B7B201FE39E3,
 				F53574830299BAF701FE39E3,
 				F53574840299C0DB01FE39E3,
 				F53574850299C1B701FE39E3,
 				F53574860299C80701FE39E3,
 				F51A400F0299CE02012FC976,
 				F5DC13A60299D19A01403EB6,
 				F5DC13A80299D2CA01403EB6,
 				F5DC13AA0299D38E01403EB6,
 			);
 			isa = PBXSourcesBuildPhase;
 			name = Sources;
 		};
 		089C1677FE841209C02AAC07 = {
 			buildActionMask = 2147483647;
 			files = (
 				08EA7FFCFE8413EDC02AAC07,
 				F53574710299A36101FE39E3,
-				F53574720299A36101FE39E3,
-				F51A400D0299CD65012FC976,
 			);
 			isa = PBXFrameworksBuildPhase;
 			name = "Frameworks & Libraries";
 		};
 		089C1679FE841209C02AAC07 = {
 			buildActionMask = 2147483647;
 			files = (
 				F59D146F02AC308301000104,
 				F59D147002AC308301000104,
 			);
@@ -195,21 +197,20 @@
 			settings = {
 			};
 		};
 		08FB77ADFE841716C02AAC07 = {
 			children = (
 				F53574730299B1E101FE39E3,
 				F53574750299B20701FE39E3,
 				F53574770299B25701FE39E3,
 				F53574780299B25701FE39E3,
 				F535747D0299B74301FE39E3,
-				F535747B0299B28B01FE39E3,
 				F51A400E0299CE02012FC976,
 				F5DC13A50299D19A01403EB6,
 				F5DC13A70299D2CA01403EB6,
 				F5DC13A90299D38E01403EB6,
 			);
 			isa = PBXGroup;
 			name = Source;
 			refType = 4;
 		};
 //080
@@ -268,68 +269,44 @@
 //4F0
 //4F1
 //4F2
 //4F3
 //4F4
 //F50
 //F51
 //F52
 //F53
 //F54
-		F51A400C0299CD65012FC976 = {
-			isa = PBXFileReference;
-			name = "libstdc++.a";
-			path = "/usr/lib/libstdc++.a";
-			refType = 0;
-		};
-		F51A400D0299CD65012FC976 = {
-			fileRef = F51A400C0299CD65012FC976;
-			isa = PBXBuildFile;
-			settings = {
-			};
-		};
 		F51A400E0299CE02012FC976 = {
 			isa = PBXFileReference;
 			name = LiveConnectNativeMethods.cpp;
 			path = Source/LiveConnectNativeMethods.cpp;
 			refType = 4;
 		};
 		F51A400F0299CE02012FC976 = {
 			fileRef = F51A400E0299CE02012FC976;
 			isa = PBXBuildFile;
 			settings = {
 			};
 		};
 		F535746F0299A36101FE39E3 = {
 			isa = PBXFrameworkReference;
 			name = JavaVM.framework;
 			path = /System/Library/Frameworks/JavaVM.framework;
 			refType = 0;
 		};
-		F53574700299A36101FE39E3 = {
-			isa = PBXFrameworkReference;
-			name = JavaEmbedding.framework;
-			path = /System/Library/Frameworks/JavaEmbedding.framework;
-			refType = 0;
-		};
 		F53574710299A36101FE39E3 = {
 			fileRef = F535746F0299A36101FE39E3;
 			isa = PBXBuildFile;
 			settings = {
 			};
 		};
-		F53574720299A36101FE39E3 = {
-			fileRef = F53574700299A36101FE39E3;
-			isa = PBXBuildFile;
-			settings = {
-			};
-		};
 		F53574730299B1E101FE39E3 = {
 			isa = PBXFileReference;
 			name = MRJPlugin.cpp;
 			path = Source/MRJPlugin.cpp;
 			refType = 4;
 		};
 		F53574750299B20701FE39E3 = {
 			isa = PBXFileReference;
 			name = MRJContext.cp;
 			path = Source/MRJContext.cp;
@@ -340,32 +317,20 @@
 			name = MRJMonitor.cpp;
 			path = Source/MRJMonitor.cpp;
 			refType = 4;
 		};
 		F53574780299B25701FE39E3 = {
 			isa = PBXFileReference;
 			name = MRJPage.cpp;
 			path = Source/MRJPage.cpp;
 			refType = 4;
 		};
-		F535747B0299B28B01FE39E3 = {
-			isa = PBXFileReference;
-			name = SupportsMixin.cpp;
-			path = Source/SupportsMixin.cpp;
-			refType = 4;
-		};
-		F535747C0299B28B01FE39E3 = {
-			fileRef = F535747B0299B28B01FE39E3;
-			isa = PBXBuildFile;
-			settings = {
-			};
-		};
 		F535747D0299B74301FE39E3 = {
 			isa = PBXFileReference;
 			name = MRJSession.cpp;
 			path = Source/MRJSession.cpp;
 			refType = 4;
 		};
 		F53574820299B7B201FE39E3 = {
 			fileRef = F53574780299B25701FE39E3;
 			isa = PBXBuildFile;
 			settings = {
@@ -399,28 +364,28 @@
 			children = (
 				F59D148402AC3AC401000104,
 				F59D148502AC3AC401000104,
 			);
 			isa = PBXGroup;
 			name = Classes;
 			refType = 4;
 		};
 		F59D146D02AC308301000104 = {
 			isa = PBXFileReference;
-			name = _Dialogs.rsrc;
-			path = Resources/_Dialogs.rsrc;
+			name = Dialogs.r;
+			path = Resources/Dialogs.r;
 			refType = 2;
 		};
 		F59D146E02AC308301000104 = {
 			isa = PBXFileReference;
-			name = _Strings.rsrc;
-			path = Resources/_Strings.rsrc;
+			name = Strings.r;
+			path = Resources/Strings.r;
 			refType = 2;
 		};
 		F59D146F02AC308301000104 = {
 			fileRef = F59D146D02AC308301000104;
 			isa = PBXBuildFile;
 			settings = {
 			};
 		};
 		F59D147002AC308301000104 = {
 			fileRef = F59D146E02AC308301000104;
@@ -470,20 +435,22 @@
 		F59D147502AC39EF01000104 = {
 			buildPhases = (
 				F59D147602AC39EF01000104,
 				F59D147702AC39EF01000104,
 				F59D147802AC39EF01000104,
 				F59D147902AC39EF01000104,
 			);
 			buildSettings = {
 				DYLIB_COMPATIBILITY_VERSION = 1;
 				DYLIB_CURRENT_VERSION = 1;
+				JAVA_COMPILER_FLAGS = "-source 1.4";
+				JAVA_COMPILER_TARGET_VM_VERSION = 1.4;
 				LIBRARY_STYLE = STATIC;
 				OTHER_CFLAGS = "";
 				OTHER_LDFLAGS = "";
 				OTHER_LIBTOOL_FLAGS = "";
 				OTHER_REZFLAGS = "";
 				PRODUCT_NAME = MRJPlugin;
 				REZ_EXECUTABLE = YES;
 				SECTORDER_FLAGS = "";
 				WARNING_CFLAGS = "-Wmost -Wno-four-char-constants -Wno-unknown-pragmas";
 			};
@@ -694,46 +661,68 @@
 			dstPath = "";
 			dstSubfolderSpec = 6;
 			files = (
 				F5BFB5F0029AD0D101000102,
 				F5BFB5EE029AD0B901000102,
 				F59D149202AC3C1401000104,
 			);
 			isa = PBXCopyFilesBuildPhase;
 			name = "Copy Files";
 		};
+		DF80C69D06318E7400A80005 = {
+			buildActionMask = 2147483647;
+			dstPath = Contents;
+			dstSubfolderSpec = 1;
+			files = (
+				DF80C69E06318E9900A80005,
+			);
+			isa = PBXCopyFilesBuildPhase;
+			runOnlyForDeploymentPostprocessing = 0;
+		};
 		F5BFB5E9029AD0B901000102 = {
 			isa = PBXFileReference;
 			path = MRJPlugin.policy;
 			refType = 4;
 		};
 		F5BFB5EA029AD0B901000102 = {
 			isa = PBXFileReference;
 			path = MRJPlugin.properties;
 			refType = 4;
 		};
+		DF80C69B06318E5700A80005 = {
+			isa = PBXFileReference;
+			path = PkgInfo;
+			refType = 4;
+		};
 		F5BFB5EE029AD0B901000102 = {
 			fileRef = F5BFB5EA029AD0B901000102;
 			isa = PBXBuildFile;
 			settings = {
 			};
 		};
 		F5BFB5F0029AD0D101000102 = {
 			fileRef = F5BFB5E9029AD0B901000102;
 			isa = PBXBuildFile;
 			settings = {
 			};
 		};
+		DF80C69E06318E9900A80005 = {
+			fileRef = DF80C69B06318E5700A80005;
+			isa = PBXBuildFile;
+			settings = {
+			};
+		};
 		F5BFB5F1029AD43001000102 = {
 			children = (
 				F5BFB5E9029AD0B901000102,
 				F5BFB5EA029AD0B901000102,
+				DF80C69B06318E5700A80005,
 			);
 			isa = PBXGroup;
 			name = Misc;
 			refType = 4;
 		};
 		F5DC13A50299D19A01403EB6 = {
 			isa = PBXFileReference;
 			name = CSecureEnv.cpp;
 			path = Source/CSecureEnv.cpp;
 			refType = 4;
@@ -751,22 +740,22 @@
 			refType = 4;
 		};
 		F5DC13A80299D2CA01403EB6 = {
 			fileRef = F5DC13A70299D2CA01403EB6;
 			isa = PBXBuildFile;
 			settings = {
 			};
 		};
 		F5DC13A90299D38E01403EB6 = {
 			isa = PBXFileReference;
-			name = RunnableMixin.cpp;
-			path = Source/RunnableMixin.cpp;
+			name = JavaEmbeddingFramework.cpp;
+			path = Source/JavaEmbeddingFramework.cpp;
 			refType = 4;
 		};
 		F5DC13AA0299D38E01403EB6 = {
 			fileRef = F5DC13A90299D38E01403EB6;
 			isa = PBXBuildFile;
 			settings = {
 			};
 		};
 	};
 	rootObject = 089C1669FE841209C02AAC07;
diff -U 10 -r -N old/plugin/oji/MRJCarbon/plugin/PkgInfo new/plugin/oji/MRJCarbon/plugin/PkgInfo
--- old/plugin/oji/MRJCarbon/plugin/PkgInfo	1969-12-31 18:00:00.000000000 -0600
+++ new/plugin/oji/MRJCarbon/plugin/PkgInfo	2004-04-17 10:59:35.000000000 -0500
@@ -0,0 +1 @@
+NSPLMOSS
\ No newline at end of file
diff -U 10 -r -N old/plugin/oji/MRJCarbon/plugin/Resources/Dialogs.r new/plugin/oji/MRJCarbon/plugin/Resources/Dialogs.r
--- old/plugin/oji/MRJCarbon/plugin/Resources/Dialogs.r	1969-12-31 18:00:00.000000000 -0600
+++ new/plugin/oji/MRJCarbon/plugin/Resources/Dialogs.r	2007-01-28 12:33:08.000000000 -0600
@@ -0,0 +1,152 @@
+/* ***** BEGIN LICENSE BLOCK *****
+ * Version: NPL 1.1/GPL 2.0/LGPL 2.1
+ *
+ * The contents of this file are subject to the Netscape Public License
+ * Version 1.1 (the "License"); you may not use this file except in
+ * compliance with the License. You may obtain a copy of the License at
+ * http://www.mozilla.org/NPL/
+ *
+ * Software distributed under the License is distributed on an "AS IS" basis,
+ * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
+ * for the specific language governing rights and limitations under the
+ * License.
+ *
+ * The Original Code is mozilla.org code.
+ *
+ * The Initial Developer of the Original Code is 
+ * Netscape Communications Corporation.
+ * Portions created by the Initial Developer are Copyright (C) 1998
+ * the Initial Developer. All Rights Reserved.
+ *
+ * Contributor(s):
+ *        Steven Michaud
+ *
+ * Alternatively, the contents of this file may be used under the terms of
+ * either the GNU General Public License Version 2 or later (the "GPL"), or 
+ * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
+ * in which case the provisions of the GPL or the LGPL are applicable instead
+ * of those above. If you wish to allow use of your version of this file only
+ * under the terms of either the GPL or the LGPL, and not to allow others to
+ * use your version of this file under the terms of the NPL, indicate your
+ * decision by deleting the provisions above and replace them with the notice
+ * and other provisions required by the GPL or the LGPL. If you do not delete
+ * the provisions above, a recipient may use your version of this file under
+ * the terms of any one of the NPL, the GPL or the LGPL.
+ *
+ * ***** END LICENSE BLOCK ***** */
+
+#include "Carbon.r"
+
+resource 'CNTL' (128, purgeable) {
+	{48, 88, 64, 288},
+	0,
+	visible,
+	0,
+	0,
+	272,
+	0,
+	""
+};
+
+resource 'CNTL' (129, purgeable) {
+	{76, 88, 92, 288},
+	0,
+	visible,
+	0,
+	0,
+	274,
+	0,
+	""
+};
+
+resource 'DITL' (128, purgeable) {
+	{	/* array DITLarray: 6 elements */
+		/* [1] */
+		{76, 224, 96, 292},
+		Button {
+			enabled,
+			"OK"
+		},
+		/* [2] */
+		{76, 144, 96, 208},
+		Button {
+			enabled,
+			"Cancel"
+		},
+		/* [3] */
+		{16, 92, 32, 292},
+		Control {
+			enabled,
+			128
+		},
+		/* [4] */
+		{44, 92, 60, 292},
+		Control {
+			enabled,
+			129
+		},
+		/* [5] */
+		{44, 12, 64, 88},
+		StaticText {
+			disabled,
+			"Password:"
+		},
+		/* [6] */
+		{16, 12, 36, 80},
+		StaticText {
+			disabled,
+			"Name:"
+		}
+	}
+};
+
+data 'DLGX' (128) {
+	$"0843 6861 7263 6F61 6C00 0000 0000 0000"            /* .Charcoal....... */
+	$"0000 0000 0000 0000 0000 0000 0000 0000"            /* ................ */
+	$"0000 0000 0000 0000 0000 0000 0000 0000"            /* ................ */
+	$"0000 0000 0000 0000 0000 0000 0000 0000"            /* ................ */
+	$"000C 0000 0000 0000 0004 0004 0000 0000"            /* ................ */
+	$"0006 0000 0000 0000 0000 0000 0000 0001"            /* ................ */
+	$"0000 0000 0000 0000 0000 0005 0000 0000"            /* ................ */
+	$"0000 0000 0000 0005 0000 0000 0000 0000"            /* ................ */
+	$"0000 0006 0000 0000 0000 0000 0000 0006"            /* ................ */
+	$"0000 0000 0000 0000 0000"                           /* .......... */
+};
+
+resource 'DLOG' (128, "Authentication", purgeable) {
+	{259, 337, 371, 645},
+	movableDBoxProc,
+	invisible,
+	noGoAway,
+	0x0,
+	128,
+	"MRJ Plugin:  Enter Name & Password",
+	alertPositionParentWindow
+};
+
+resource 'dctb' (128) {
+	{	/* array ColorSpec: 5 elements */
+		/* [1] */
+		wContentColor, 65535, 65535, 65535,
+		/* [2] */
+		wFrameColor, 0, 0, 0,
+		/* [3] */
+		wTextColor, 0, 0, 0,
+		/* [4] */
+		wHiliteColor, 0, 0, 0,
+		/* [5] */
+		wTitleBarColor, 65535, 65535, 65535
+	}
+};
+
+resource 'dlgx' (128) {
+	versionZero {
+		11
+	}
+};
+
+data 'ictb' (128) {
+	$"0000 0000 0000 0000 0000 0000 0000 0000"            /* ................ */
+	$"0000 0000 0000 0000 0000 0000"                      /* ............ */
+};
+
diff -U 10 -r -N old/plugin/oji/MRJCarbon/plugin/Resources/Makefile new/plugin/oji/MRJCarbon/plugin/Resources/Makefile
--- old/plugin/oji/MRJCarbon/plugin/Resources/Makefile	2003-06-11 00:11:34.000000000 -0500
+++ new/plugin/oji/MRJCarbon/plugin/Resources/Makefile	2007-01-27 15:35:27.000000000 -0600
@@ -1,15 +1,15 @@
 # decodes resource files from AppleSingle to Resource Manager format.
 
-ASDECODE = ../../../../../dist/bin/asdecode
-RESOURCE_FILES = _Dialogs.rsrc _Strings.rsrc
+REZ = Rez
+RESOURCE_FILES = Dialogs.rsrc Strings.rsrc
 
 all:  $(RESOURCE_FILES)
 
-_Dialogs.rsrc:  Dialogs.rsrc
-	$(ASDECODE) Dialogs.rsrc _Dialogs.rsrc
+Dialogs.rsrc:  Dialogs.r
+	$(REZ) Dialogs.r -o Dialogs.rsrc -useDF
 
-_Strings.rsrc:  Strings.rsrc
-	$(ASDECODE) Strings.rsrc _Strings.rsrc
+Strings.rsrc:  Strings.r
+	$(REZ) Strings.r -o Strings.rsrc -useDF
 
 clean:
 	rm -f $(RESOURCE_FILES)
diff -U 10 -r -N old/plugin/oji/MRJCarbon/plugin/Resources/Strings.r new/plugin/oji/MRJCarbon/plugin/Resources/Strings.r
--- old/plugin/oji/MRJCarbon/plugin/Resources/Strings.r	1969-12-31 18:00:00.000000000 -0600
+++ new/plugin/oji/MRJCarbon/plugin/Resources/Strings.r	2007-10-06 20:48:23.000000000 -0500
@@ -0,0 +1,152 @@
+/* ***** BEGIN LICENSE BLOCK *****
+ * Version: NPL 1.1/GPL 2.0/LGPL 2.1
+ *
+ * The contents of this file are subject to the Netscape Public License
+ * Version 1.1 (the "License"); you may not use this file except in
+ * compliance with the License. You may obtain a copy of the License at
+ * http://www.mozilla.org/NPL/
+ *
+ * Software distributed under the License is distributed on an "AS IS" basis,
+ * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
+ * for the specific language governing rights and limitations under the
+ * License.
+ *
+ * The Original Code is mozilla.org code.
+ *
+ * The Initial Developer of the Original Code is 
+ * Netscape Communications Corporation.
+ * Portions created by the Initial Developer are Copyright (C) 1998
+ * the Initial Developer. All Rights Reserved.
+ *
+ * Contributor(s):
+ *        Steven Michaud
+ *
+ * Alternatively, the contents of this file may be used under the terms of
+ * either the GNU General Public License Version 2 or later (the "GPL"), or 
+ * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
+ * in which case the provisions of the GPL or the LGPL are applicable instead
+ * of those above. If you wish to allow use of your version of this file only
+ * under the terms of either the GPL or the LGPL, and not to allow others to
+ * use your version of this file under the terms of the NPL, indicate your
+ * decision by deleting the provisions above and replace them with the notice
+ * and other provisions required by the GPL or the LGPL. If you do not delete
+ * the provisions above, a recipient may use your version of this file under
+ * the terms of any one of the NPL, the GPL or the LGPL.
+ *
+ * ***** END LICENSE BLOCK ***** */
+
+#include "Carbon.r"
+
+resource 'STR#' (127, purgeable) {
+	{	/* array StringArray: 15 elements */
+		/* [1] */
+		"Embedded JVM",
+		/* [2] */
+		"Embedded Java Applet",
+		/* [3] */
+		"Embedded Java Applet",
+		/* [4] */
+		"Embedded Java Applet",
+		/* [5] */
+		"Embedded Java Applet",
+		/* [6] */
+		"Embedded Java Applet",
+		/* [7] */
+		"Embedded Java Applet",
+		/* [8] */
+		"Embedded Java Applet",
+		/* [9] */
+		"Embedded Java Applet",
+		/* [10] */
+		"Embedded Java Applet",
+		/* [11] */
+		"Embedded Java Applet",
+		/* [12] */
+		"Embedded Java Applet",
+		/* [13] */
+		"Embedded Java Applet",
+		/* [14] */
+		"Embedded Java Applet",
+		/* [15] */
+		"Embedded Java Applet"
+	}
+};
+
+resource 'STR#' (126, purgeable) {
+	{	/* array StringArray: 2 elements */
+		/* [1] */
+		"Runs Java applets using the latest installed versions of Java. "
+		"For more information: "
+		"<A HREF=http://javaplugin.sourceforge.net/>Java Embedding Plugin</A>. "
+		"Run version test: "
+		"<A HREF=http://gemal.dk/browserspy/java.html>Java Information</A>.",
+		/* [2] */
+		"Java Embedding Plugin 0.9.6.4"
+	}
+};
+
+resource 'STR#' (128, purgeable) {
+	{	/* array StringArray: 30 elements */
+		/* [1] */
+		"application/x-java-vm",
+		/* [2] */
+		"xjv",
+		/* [3] */
+		"application/x-java-applet",
+		/* [4] */
+		"xja",
+		/* [5] */
+		"application/x-java-applet;version=1.1",
+		/* [6] */
+		"xja11",
+		/* [7] */
+		"application/x-java-applet;version=1.1.1",
+		/* [8] */
+		"xja111",
+		/* [9] */
+		"application/x-java-applet;version=1.1.2",
+		/* [10] */
+		"xja112",
+		/* [11] */
+		"application/x-java-applet;version=1.1.3",
+		/* [12] */
+		"xja113",
+		/* [13] */
+		"application/x-java-applet;version=1.2",
+		/* [14] */
+		"xja12",
+		/* [15] */
+		"application/x-java-applet;version=1.2.1",
+		/* [16] */
+		"xja121",
+		/* [17] */
+		"application/x-java-applet;version=1.2.2",
+		/* [18] */
+		"xja122",
+		/* [19] */
+		"application/x-java-applet;version=1.3",
+		/* [20] */
+		"xja13",
+		/* [21] */
+		"application/x-java-applet;version=1.3.1",
+		/* [22] */
+		"xja131",
+		/* [23] */
+		"application/x-java-applet;version=1.4",
+		/* [24] */
+		"xja14",
+		/* [25] */
+		"application/x-java-applet;version=1.4.1",
+		/* [26] */
+		"xja141",
+		/* [27] */
+		"application/x-java-applet;version=1.4.2",
+		/* [28] */
+		"xja142",
+		/* [29] */
+		"application/x-java-applet;version=1.5",
+		/* [30] */
+		"xja15"
+	}
+};
+
diff -U 10 -r -N old/plugin/oji/MRJCarbon/plugin/Source/CSecureEnv.cpp new/plugin/oji/MRJCarbon/plugin/Source/CSecureEnv.cpp
--- old/plugin/oji/MRJCarbon/plugin/Source/CSecureEnv.cpp	2003-07-24 02:23:50.000000000 -0500
+++ new/plugin/oji/MRJCarbon/plugin/Source/CSecureEnv.cpp	2008-04-11 15:45:56.000000000 -0500
@@ -32,63 +32,212 @@
  * the provisions above, a recipient may use your version of this file under
  * the terms of any one of the MPL, the GPL or the LGPL.
  *
  * ----- END LICENSE BLOCK ----- */
 
 #include "CSecureEnv.h"
 #include "nsISecurityContext.h"
 
 #include "MRJPlugin.h"
 #include "MRJSession.h"
-#include "nsIThreadManager.h"
 #include "nsIJVMManager.h"
-#include "nsIScriptSecurityManager.h"
 #include "nsIPrincipal.h"
 
 #include "MRJMonitor.h"
 #include "NativeMonitor.h"
 #include "JavaMessageQueue.h"
 
+#import "JavaEmbeddingPlugin.h"
+extern "C" Boolean JEPCheckBundle();
+extern Boolean debugProxyJNI;
+extern long getSystemVersion();
+
+extern MRJPluginInstance *GetAppletInstance(JNIEnv* env, jobject applet);
+extern MRJPluginInstance *GetSecContextInstance(nsISecurityContext *context);
+
+template<class RefType>
+class cfref {
+    RefType mRef;
+public:
+    cfref() : mRef(NULL) {}
+    cfref(RefType ref) : mRef(ref) {}
+    ~cfref() { if(mRef) ::CFRelease(mRef); }
+    
+    RefType operator=(RefType ref)
+    {
+        if (mRef && mRef != ref)
+            ::CFRelease(mRef);
+        return (mRef = ref);
+    }
+    
+    operator RefType() { return mRef; }
+    operator int() { return (mRef != NULL); }
+
+private:
+    // cfref(const cfref<RefType>& other) {}
+};
+
+nsID nsIScriptSecurityManagerNewIID = NS_ISCRIPTSECURITYMANAGERNEW_IID;
+nsID nsIScriptSecurityManagerNewAlt1IID = NS_ISCRIPTSECURITYMANAGERNEWALT1_IID;
+nsID nsIScriptSecurityManagerNewAlt2IID = NS_ISCRIPTSECURITYMANAGERNEWALT2_IID;
+nsID nsIScriptSecurityManagerNewAlt3IID = NS_ISCRIPTSECURITYMANAGERNEWALT3_IID;
+nsID nsIScriptSecurityManagerNewAlt4IID = NS_ISCRIPTSECURITYMANAGERNEWALT4_IID;
+nsID nsIScriptSecurityManagerNewerAlt1IID = NS_ISCRIPTSECURITYMANAGERNEWERALT1_IID;
+nsID nsIScriptSecurityManagerNewerAlt2IID = NS_ISCRIPTSECURITYMANAGERNEWERALT2_IID;
+nsID nsIScriptSecurityManagerNewerAlt3IID = NS_ISCRIPTSECURITYMANAGERNEWERALT3_IID;
+nsID nsIScriptSecurityManagerNewerAlt4IID = NS_ISCRIPTSECURITYMANAGERNEWERALT4_IID;
+nsID nsIScriptSecurityManagerNewerAlt5IID = NS_ISCRIPTSECURITYMANAGERNEWERALT5_IID;
+nsID nsIScriptSecurityManagerNewerAlt6IID = NS_ISCRIPTSECURITYMANAGERNEWERALT6_IID;
+nsID nsIScriptSecurityManagerNewerAlt7IID = NS_ISCRIPTSECURITYMANAGERNEWERALT7_IID;
+nsID nsIScriptSecurityManagerNewestAlt1IID = NS_ISCRIPTSECURITYMANAGERNEWESTALT1_IID;
+nsID nsIScriptSecurityManagerObsoleteIID = NS_ISCRIPTSECURITYMANAGEROBSOLETE_IID;
+
 #define PROXY_JNI_CALLS 1
 #define USE_LIVECONNECT_PROXY 1
 #define LOCAL_REFS_ARE_GLOBAL USE_LIVECONNECT_PROXY
 
 inline jobject ToGlobalRef(JNIEnv* env, jobject localRef)
 {
+    if (!localRef)
+        return NULL;
     jobject globalRef = env->NewGlobalRef(localRef);
-    // env->DeleteLocalRef(localRef);   // not necessary from native methods. done en-masse.
+    env->DeleteLocalRef(localRef);
     return globalRef;
 }
 
+extern MRJPlugin* theJVMPlugin;
+
+JavaMessage::JavaMessage()
+	:	mDone(false), mCallMethodCall(false), mNext(NULL),
+			mMessageMonitor(NULL), mPluginInstance(NULL),
+			mIsFinalizeMessage(false)
+{
+}
+
+/* The extra initial AddRef() gives us more control over when we'll be
+ * released.  (It stops us from being released after the next pair of calls
+ * to AddRef() and Release(), but requires us to call Release() on ourselves
+ * at the appropriate time.  As a result, we'll be released after the end of
+ * the _last_ pair of calls (including our own pair) to AddRef() and
+ * Release().)
+ */
+JavaMessage::JavaMessage(MRJPluginInstance *pluginInstance)
+	:	mDone(false), mCallMethodCall(false), mNext(NULL),
+			mMessageMonitor(NULL), mPluginInstance(pluginInstance),
+			mIsFinalizeMessage(false)
+{
+	AddRef();
+	NS_IF_ADDREF(mPluginInstance);
+	if (theJVMPlugin)
+		mMessageMonitor = new MRJMonitor(theJVMPlugin->getSession());
+}
+
+JavaMessage::~JavaMessage()
+{
+	if (mMessageMonitor)
+		delete mMessageMonitor;
+	NS_IF_RELEASE(mPluginInstance);
+}
+
+NS_IMPL_ISUPPORTS0(JavaMessage)
+
+/* waitTilDone(), setIsDone() and timedOut() must be used together -- either
+ * all of them (though timedOut() is optional) or none of them.
+ */
+
+/* Use on "client side".  Call no more than once (or exactly once if you're
+ * not also using waitAWhile()).  Returns "true" if our "message" has finished
+ * executing by the time this method is ready to return.  Otherwise returns
+ * "false".
+ */
+Boolean JavaMessage::waitTilDone(long long millis)
+{
+	if (!mDone && mMessageMonitor)
+		mMessageMonitor->wait(millis);
+	Boolean done = mDone;
+	if (mDone) {
+		Release();
+	} else {
+		mDone = true;
+	}
+	return done;
+}
+
+/* Use on "client side".  Returns "true" if our "message" has finished
+ * executing by the time this method is ready to return.  Otherwise
+ * returns "false".
+ */
+Boolean JavaMessage::waitAWhile(long long millis)
+{
+	if (!mDone && mMessageMonitor)
+		mMessageMonitor->wait(millis);
+	return mDone;
+}
+
+/* Use on "server side".  Call exactly once.  If we'll be Released by external
+ * code, set "release" to "false".
+ */
+void JavaMessage::setIsDone(Boolean release)
+{
+	if (mDone) {
+		if (release)
+			Release();
+	} else {
+		mDone = true;
+		if (mMessageMonitor)
+			mMessageMonitor->notify();
+	}
+}
+
+/* Use on "server side".  Use zero or more times, but don't call again after
+ * it's returned TRUE.  If we'll be Released by external code, set "release"
+ * to "false".
+ */
+Boolean JavaMessage::timedOut(Boolean release)
+{
+	if (!theJVMPlugin)
+		return true;
+	if (mDone) {
+		if (release)
+			Release();
+		return true;
+	}
+	return false;
+}
+
 JavaMessageQueue::JavaMessageQueue(Monitor* monitor)
 	:	mFirst(NULL), mLast(NULL), mMonitor(monitor)
 {
 }
 
 void JavaMessageQueue::putMessage(JavaMessage* msg)
 {
+	mMonitor->enter();
 	if (mFirst == NULL) {
 		mFirst = mLast = msg;
 	} else {
 		mLast->setNext(msg);
 		mLast = msg;
 	}
 	msg->setNext(NULL);
+	mMonitor->exit();
 }
 
 JavaMessage* JavaMessageQueue::getMessage()
 {
+	mMonitor->enter();
 	JavaMessage* msg = mFirst;
 	if (msg != NULL) {
 		mFirst = mFirst->getNext();
 		if (mFirst == NULL) mLast = NULL;
 	}
+	mMonitor->exit();
 	return msg;
 }
 
 void JavaMessageQueue::enter()
 {
 	mMonitor->enter();
 }
 
 void JavaMessageQueue::exit()
 {
@@ -103,22 +252,25 @@
 void JavaMessageQueue::wait(long long millis)
 {
 	mMonitor->wait(millis);
 }
 
 void JavaMessageQueue::notify()
 {
 	mMonitor->notify();
 }
 
+#if !USE_LIVECONNECT_PROXY
 /**
- * Native run method that communicates with LiveConnect from a Java thread.
+ * Runs (as a "server") on the Java thread that calls from LiveConnect to Java
+ * are processed in when USE_LIVECONNECT_PROXY is "false".  So this "server"
+ * is currently not used.
  */
 static void netscape_oji_JNIThread_run(JNIEnv* env, jobject self)
 {
 	CSecureEnv* secureEnv = NULL;
 	jmethodID yieldMethod = NULL;
 	jmethodID sleepMethod = NULL;
 	
 	jclass clazz = env->GetObjectClass(self);
 	if (clazz != NULL) {
 		// the field fSecureEnv contains a pointer to a CSecureEnv.
@@ -133,21 +285,23 @@
 	// notify the secure JNI that we are here, and wait for messages to arrive.
 	if (secureEnv != NULL) {
 		jboolean isRunning = true;
 		MRJSession* session = secureEnv->getSession();
 		MRJMonitor requestMonitor(session, self);
 		MRJMonitor replyMonitor(session);
 		// NativeMonitor replyMonitor(secureEnv->getThreadManager());
 		JavaMessageQueue requests(&requestMonitor), replies(&replyMonitor);
 		secureEnv->initialize(env, &isRunning, &requests, &replies);
 		
-		// when this thread is running, no other thread can enter the request queue monitor.
+		// when this thread is running, no other thread can enter the request
+		// queue monitor at an inappropriate time (i.e. except when we're
+		// inside a call to requests.wait()).
 		requests.enter();
 		
 		while (isRunning) {
 			// the protocol for now is dead simple:  get a message from the
 			// requests message queue, process it, and then put it back in
 			// the replies queue. This will get more elaborate to handle
 			// upcall requests. 
 			JavaMessage* msg = requests.getMessage();
 			if (msg != NULL) {
 				msg->execute(env);
@@ -158,215 +312,246 @@
 				// should we do sleep, timed wait, or what?
 				// env->CallStaticVoidMethod(clazz, yieldMethod);
 				// env->CallStaticVoidMethod(clazz, sleepMethod, jlong(kDefaultJMTime));
 				requests.wait();
 			}
 		}
 		
 		requests.exit();
 	}
 }
+#endif
 
-static jclass netscape_oji_JNIRunnable;
-static jmethodID netscape_oji_JNIRunnable_constructorID;
-static jfieldID netscape_oji_JNIRunnable_mJavaMessageID;
+static jclass netscape_oji_JNIRunnable = NULL;
+static jmethodID netscape_oji_JNIRunnable_constructorID = NULL;
+static jfieldID netscape_oji_JNIRunnable_mJavaMessageID = NULL;
 
 static void netscape_oji_JNIRunnable_run(JNIEnv* env, jobject self)
 {
     JavaMessage* msg = (JavaMessage*) env->GetIntField(self, netscape_oji_JNIRunnable_mJavaMessageID);
     if (msg) {
-        msg->execute(env);
+        msg->execute((JNIEnv *)env);
         // what about upcalls?
     }
 }
 
 static bool check_exceptions(JNIEnv* env)
 {
     jthrowable exc = env->ExceptionOccurred();
 	if (exc) {
 	    env->ExceptionDescribe();
 	    env->ExceptionClear();
 	    env->DeleteLocalRef(exc);
 	    return true;
 	}
 	return false;
 }
 
+#if !USE_LIVECONNECT_PROXY
 /**
  * Called from browser side, starts the Java thread that calls from LiveConnect to Java
- * are processed in.
+ * are processed in if USE_LIVECONNECT_PROXY is "false".
  */
 static void CreateJNIThread(CSecureEnv* secureEnv)
 {
-	nsIThreadManager* manager = secureEnv->getThreadManager();
+	nsIJVMThreadManager* manager = secureEnv->getThreadManager();
 	MRJSession* session = secureEnv->getSession();
 	JNIEnv* env = session->getCurrentEnv();
 	
     check_exceptions(env);
 
-	jclass JNIThreadClass = env->FindClass("netscape.oji.JNIThread");
+	jclass JNIThreadClass = env->FindClass("netscape/oji/JNIThread");
 	if (JNIThreadClass != NULL) {
-		JNINativeMethod method = { "run", "()V", &netscape_oji_JNIThread_run };
+		JNINativeMethod method = { "run", "()V", (void *) &netscape_oji_JNIThread_run };
 		env->RegisterNatives(JNIThreadClass, &method, 1);
 		jmethodID constructorID = env->GetMethodID(JNIThreadClass, "<init>", "(I)V");
 		if (constructorID != NULL) {
-			jobject javaThread = env->NewObject(JNIThreadClass, constructorID, secureEnv);
+			env->NewObject(JNIThreadClass, constructorID, secureEnv);
 			for (;;) {
 				// was there some kind of exception? bail if so.
 				if (check_exceptions(env))
 				    break;
 				// give time to Java, to allow the thread to come up.
 				session->idle();
 				// has the thread made contact?
 				if (secureEnv->isInitialized())
 					break;
 				// give time to NSPR, to avoid hanging too long.
 				manager->Sleep();
 			}
 		}
 		env->DeleteLocalRef(JNIThreadClass);
 	}
 }
+#endif
 
+/* Needs to return a global ref, since it might be used on a different thread
+ * than the main thread (in OS X 10.4.X and higher).
+ */
 static jobject CreateJNIRunnable(JNIEnv* env, JavaMessage* msg)
 {
     // XXX:  does this have to be thread safe?
     if (!netscape_oji_JNIRunnable) {
-    	jclass clazz = env->FindClass("netscape.oji.JNIRunnable");
+    	jclass clazz = env->FindClass("netscape/oji/JNIRunnable");
     	if (!clazz) return NULL;
-		JNINativeMethod method = { "run", "()V", &netscape_oji_JNIRunnable_run };
+		JNINativeMethod method = { "run", "()V", (void *) &netscape_oji_JNIRunnable_run };
 		env->RegisterNatives(clazz, &method, 1);
 		netscape_oji_JNIRunnable_constructorID = env->GetMethodID(clazz, "<init>", "(I)V");
         netscape_oji_JNIRunnable_mJavaMessageID = env->GetFieldID(clazz, "mJavaMessage", "I");
 		netscape_oji_JNIRunnable = (jclass) env->NewGlobalRef(clazz);
 		env->DeleteLocalRef(clazz);
     }
     check_exceptions(env);
-    return env->NewObject(netscape_oji_JNIRunnable, netscape_oji_JNIRunnable_constructorID, msg);
+    jobject retval = env->NewObject(netscape_oji_JNIRunnable,
+        netscape_oji_JNIRunnable_constructorID, msg);
+    retval = ToGlobalRef(env, retval);
+    return retval;
 }
 
-static jclass GetLiveConnectProxy(JNIEnv* env, nsIPrincipal* codebasePrincipal)
+static jclass GetLiveConnectProxy(JNIEnv* env, nsIPrincipal* codebasePrincipal, CSecureEnv *secureEnv)
 {
     jclass liveConnectProxy = NULL;
     jclass netscape_oji_ProxyClassLoaderFactory = env->FindClass("netscape/oji/ProxyClassLoaderFactory");
     if (netscape_oji_ProxyClassLoaderFactory) {
         jmethodID createClassLoaderID = env->GetStaticMethodID(netscape_oji_ProxyClassLoaderFactory,
                                                                "createClassLoader", 
-                                                               "(Ljava/lang/String;)Ljava/lang/ClassLoader;");
+                                                               "(Ljava/lang/String;I)Ljava/lang/ClassLoader;");
         if (createClassLoaderID) {
             jstring codebaseUTF = NULL;
-            char* codebase;
+            char* codebase = NULL;
+            cfref<CFStringRef> info;
             nsresult rv = codebasePrincipal->GetOrigin(&codebase);
-            if (NS_SUCCEEDED(rv)) {
+            if (NS_SUCCEEDED(rv) && codebase) {
+                if (debugProxyJNI) {
+                    info = CFStringCreateWithFormat(NULL, NULL,
+                        CFSTR("MRJPluginJEP: nsIPrincipal::GetOrigin() succeeded, origin %s"),
+                        codebase);
+                }
                 codebaseUTF = env->NewStringUTF(codebase);
                 delete[] codebase;
+            } else if (debugProxyJNI) {
+                if (NS_SUCCEEDED(rv)) {
+                    info = CFStringCreateWithFormat(NULL, NULL,
+                        CFSTR("MRJPluginJEP: nsIPrincipal::GetOrigin() failed"),
+                        codebase);
+                } else {
+                    info = CFStringCreateWithFormat(NULL, NULL,
+                        CFSTR("MRJPluginJEP: nsIPrincipal::GetOrigin() succeeded, origin null"));
+                }
             }
+            if (debugProxyJNI)
+                JEPLogJavaMessage(info);
             if (codebaseUTF) {
                 jobject classLoader = env->CallStaticObjectMethod(netscape_oji_ProxyClassLoaderFactory,
-                                                                  createClassLoaderID, codebaseUTF);
+                                                                  createClassLoaderID, codebaseUTF, (jint) secureEnv);
                 if (classLoader) {
                     jclass clazz = env->GetObjectClass(classLoader);
                     jmethodID loadClassID = env->GetMethodID(clazz, "loadClass",
                                                              "(Ljava/lang/String;)Ljava/lang/Class;");
                     if (loadClassID) {
                         jstring className = env->NewStringUTF("netscape.oji.LiveConnectProxy");
                         if (className) {
                             liveConnectProxy = (jclass) env->CallObjectMethod(classLoader, loadClassID, className);
                             env->DeleteLocalRef(className);
                         }
                     }
                     env->DeleteLocalRef(clazz);
+                    env->DeleteLocalRef(classLoader);
                 }
                 env->DeleteLocalRef(codebaseUTF);
             }
         }
         env->DeleteLocalRef(netscape_oji_ProxyClassLoaderFactory);
     }
     check_exceptions(env);
     return liveConnectProxy;
 }
 
 /**
  * Creates a new native thread in MRJ's main thread, to avoid deadlock problems.
  */
 class CreateNativeThreadMessage : public NativeMessage {
 	nsresult* mResult;
-	PRUint32* mThreadID;
+	nsPluginThreadPtr* mThreadID;
 	CSecureEnv* mSecureEnv;
 public:
-	CreateNativeThreadMessage(nsresult* outResult, PRUint32* outThreadID, CSecureEnv* secureEnv)
+	CreateNativeThreadMessage(nsresult* outResult, nsPluginThreadPtr* outThreadID, CSecureEnv* secureEnv)
 		:	mResult(outResult), mThreadID(outThreadID), mSecureEnv(secureEnv)
 	{
 	}
 
 	virtual void execute()
 	{
-		nsIThreadManager* manager = mSecureEnv->getThreadManager();
+		nsIJVMThreadManager* manager = mSecureEnv->getThreadManager();
 		*mResult = manager->CreateThread(mThreadID, mSecureEnv);
 	}
 };
 
 /**
  * Called from a Java thread that wants to communicate with the browser.
  */
 static void CreateNativeThread(CSecureEnv* secureEnv)
 {
 	nsresult result;
-	PRUint32 threadID;
+	nsPluginThreadPtr threadID;
 	MRJSession* session = secureEnv->getSession();
-	
+
 	// cause a native thread to be created on our behalf. Perhaps this should be a message we send to the
 	// session itself. otherwise we could have reentrancy problems.
 	CreateNativeThreadMessage message(&result, &threadID, secureEnv);
 	session->sendMessage(&message);
 
 	if (session->onMainThread()) {
 		// give time to other native threads, so the new thread can come up.
-		nsIThreadManager* manager = secureEnv->getThreadManager();
+		nsIJVMThreadManager* manager = secureEnv->getThreadManager();
 		while (!secureEnv->isInitialized()) {
 			manager->Sleep();
 		}
 	} else {
 		// sleep the current Java thread until we rendezvous with the Native thread.
 		JNIEnv* env = session->getCurrentEnv();
 		jclass threadClass = env->FindClass("java/lang/Thread");
 		if (threadClass != NULL) {
 			jmethodID sleepMethod = env->GetStaticMethodID(threadClass, "sleep", "(J)V");
 			if (sleepMethod != NULL) {
 				while (!secureEnv->isInitialized())
 					env->CallStaticVoidMethod(threadClass, sleepMethod, jlong(1024));
 			}
 			env->DeleteLocalRef(threadClass);
 		}
 	}
 }
 
 /**
- * Runs the server thread for LiveConnect upcalls from spontaneous Java threads.
+ * Runs on a native thread as a "server" that processes LiveConnect calls from
+ * Java.  Different kinds of Java-to-LiveConnect calls can be processed by
+ * different "servers".
  */
 NS_IMETHODIMP CSecureEnv::Run()
 {
 	jboolean isRunning = true;
 	NativeMonitor requestMonitor(mSession, mThreadManager);
 	MRJMonitor replyMonitor(mSession);
 	JavaMessageQueue requests(&requestMonitor), replies(&replyMonitor);
 	// initialize(env, self, &isRunning, &requests, &replies);
 	
 	// we have to create the Proxy JNI here, so it associated with this thread.
 	nsIJVMManager* manager = mPlugin->getManager();
 	manager->CreateProxyJNI(this, &mProxyEnv);
 	
 	mIsRunning = &isRunning;
 	mNativeQueue = &requests;
 	mJavaQueue = &replies;
 	
-	// when this thread is running, no other thread can enter the request queue monitor.
+	// when this thread is running, no other thread can enter the request
+	// queue monitor at an inappropriate time (i.e. except when we're
+	// inside a call to requests.wait()).
 	requests.enter();
 	
 	while (isRunning) {
 		// the protocol for now is dead simple:  get a message from the
 		// requests message queue, process it, and then put it back in
 		// the replies queue. This will get more elaborate to handle
 		// upcall requests. 
 		JavaMessage* msg = requests.getMessage();
 		if (msg != NULL) {
 			msg->execute(mProxyEnv);
@@ -378,117 +563,423 @@
 			// env->CallStaticVoidMethod(clazz, sleepMethod, jlong(kDefaultJMTime));
 			requests.wait();
 		}
 	}
 	
 	requests.exit();
 
 	return NS_OK;
 }
 
+static void proxyJNIProxySecurityBreak()
+{
+	return;
+}
+
+static void proxyJNINoSecurityBreak()
+{
+	return;
+}
+
+static void proxyJNINoSecurityNullPrincipalBreak()
+{
+	return;
+}
+
 /**
  * Used to send a message from Native to Java threads.
  */
 void CSecureEnv::sendMessageToJava(JavaMessage* msg)
 {
+    if (!theJVMPlugin)
+        return;
 #if USE_LIVECONNECT_PROXY
     JNIEnv* env = mSession->getCurrentEnv();
     // XXX this needs to be optimized up the wazoo.
     // somehow, get the associated class loader for the codebase of the currently running
     // script. doing this here would require us to use lots of unfrozen interfaces.
     nsresult rv = NS_OK;
-    if (!mScriptSecurityManager) {
+    cfref<CFStringRef> info;
+    nsIScriptSecurityManager *scriptSecurityManager = NULL;
+    nsIScriptSecurityManagerNew *scriptSecurityManagerNew = NULL;
+    nsIScriptSecurityManagerNewer *scriptSecurityManagerNewer = NULL;
+    nsIScriptSecurityManagerNewest *scriptSecurityManagerNewest = NULL;
+    nsIPrincipal* scriptPrincipal = NULL;
+    if (debugProxyJNI || (!mScriptSecurityManager &&
+        !mScriptSecurityManagerNew && !mScriptSecurityManagerNewer &&
+        !mScriptSecurityManagerNewest))
+    {
+		/* The following is needed to work around a bug in Firefox 1.0RC1 (and
+		 * everything on the Aviary branch(es)), which was subsequently added
+		 * to Mozilla 1.7.5 (and everything on the Mozilla 1.7 branch), plus
+		 * two (unrelated) changes that were made (on 2004-04-25 and 2005-02-02)
+		 * to the nsIScriptSecurityManager on the trunk.
+		 * **The Bug**
+		 * Firefox 1.0RC1 made a backwards-incompatible change in the
+		 * nsIScriptSecurityManager XPCOM "service" ... despite (or perhaps
+		 * because of) an attempt to preserve backwards compatibility.  As of
+		 * Firefox 1.0RC1, this service and nsIPrincipal now exist (on the
+		 * Aviary and Mozilla 1.7 branches, though not on the trunk) in two
+		 * versions -- nsIScriptSecurityManager and
+		 * nsIScriptSecurityManagerObsolete, and nsIPrincipal and
+		 * nsIPrincipalObsolete.  The "obsolete" versions have the IIDs that
+		 * were previously in use.  The "plain" versions have new IIDs.  The
+		 * old version of nsIPrincipal (which became "obsolete" in Firefox
+		 * 1.0RC1) had an "origin" attribute, and hence a GetOrigin() method
+		 * -- called in GetLiveConnectProxy(JNIEnv *, nsIPrincipal *) above.
+		 * So does Firefox 1.0RC1's new nsIPrincipal interface.  But its
+		 * nsIPrincipalObsolete interface _doesn't_ have either an origin
+		 * attribute or a GetOrigin() method.  When old programs (like the MRJ
+		 * Plugin) look for the nsIScriptSecurityManager service they use the
+		 * old IID, and hence in Firefox 1.0RC1 they now get
+		 * nsIScriptSecurityManagerObsolete, whose GetSubjectPrincipal()
+		 * method returns an nsIPrincipalObsolete object.  But this object
+		 * doesn't have a GetOrigin() method, and when we call it above we get
+		 * a crash.
+		 * **The Other Changes to the nsIScriptSecurityManager Interface**
+		 * They both (correctly) resulted in changes to the interface IID --
+		 * which we have to accomodate.  The first one changed the interface
+		 * sufficiently that we've needed to add a new header file
+		 * (nsIScriptSecurityManagerAlt.h).  The second didn't make any
+		 * difference to us (beyond the change to the IID), so we don't need
+		 * a second new header file.  I didn't know about any of this before
+		 * JEP 0.9.2 -- because JavaScript-to-Java LiveConnect seemed to
+		 * continue to work normally.  But it _wasn't_ working normally.
+		 * In fact, the MRJ Plugin allowed JavaScript-to-Java LiveConnect to
+		 * proceed even when no script security manager could be found, which
+		 * meant that there were no security checks at all!  Fortunately this
+		 * only happened with nightlies, alphas and betas (everything on the
+		 * trunk), and not with any of the releases (which are on the Aviary
+		 * branch for Firefox and the Mozilla 1.7 branch for Mozilla).  I am
+		 * going to try to keep track of future changes to this interface at
+		 * https://bugzilla.mozilla.org/show_bug.cgi?id=293973.
+		 */
+		/* To get around these problems we define the IIDs ourselves (ignoring
+		 * the Mozilla source distro's header files).  First we look for the
+		 * nsIScriptSecurityManager service by its new Aviary-and-Mozilla-1.7-
+		 * branch IID, then by the old ("obsolete") IID, then by the first of
+		 * the two new trunk IIDs, then by the second new trunk IID.
+		 */
         rv = MRJPlugin::GetService("@mozilla.org/scriptsecuritymanager;1",
-                                   NS_GET_IID(nsIScriptSecurityManager),
-                                   (void**)&mScriptSecurityManager);
+                                   nsIScriptSecurityManagerNewIID,
+                                   (void**)&scriptSecurityManager);
+        if (!NS_SUCCEEDED(rv)) {
+            rv = MRJPlugin::GetService("@mozilla.org/scriptsecuritymanager;1",
+                                       nsIScriptSecurityManagerObsoleteIID,
+                                       (void**)&scriptSecurityManager);
+        }
+        if (!NS_SUCCEEDED(rv)) {
+            rv = MRJPlugin::GetService("@mozilla.org/scriptsecuritymanager;1",
+                                       nsIScriptSecurityManagerNewAlt1IID,
+                                       (void**)&scriptSecurityManagerNew);
+        }
+        if (!NS_SUCCEEDED(rv)) {
+            rv = MRJPlugin::GetService("@mozilla.org/scriptsecuritymanager;1",
+                                       nsIScriptSecurityManagerNewAlt2IID,
+                                       (void**)&scriptSecurityManagerNew);
+        }
+        if (!NS_SUCCEEDED(rv)) {
+            rv = MRJPlugin::GetService("@mozilla.org/scriptsecuritymanager;1",
+                                       nsIScriptSecurityManagerNewAlt3IID,
+                                       (void**)&scriptSecurityManagerNew);
+        }
+        if (!NS_SUCCEEDED(rv)) {
+            rv = MRJPlugin::GetService("@mozilla.org/scriptsecuritymanager;1",
+                                       nsIScriptSecurityManagerNewAlt4IID,
+                                       (void**)&scriptSecurityManagerNew);
+        }
+        if (!NS_SUCCEEDED(rv)) {
+            rv = MRJPlugin::GetService("@mozilla.org/scriptsecuritymanager;1",
+                                       nsIScriptSecurityManagerNewestAlt1IID,
+                                       (void**)&scriptSecurityManagerNewest);
+        }
+        if (!NS_SUCCEEDED(rv)) {
+            rv = MRJPlugin::GetService("@mozilla.org/scriptsecuritymanager;1",
+                                       nsIScriptSecurityManagerNewerAlt7IID,
+                                       (void**)&scriptSecurityManagerNewer);
+        }
+        if (!NS_SUCCEEDED(rv)) {
+            rv = MRJPlugin::GetService("@mozilla.org/scriptsecuritymanager;1",
+                                       nsIScriptSecurityManagerNewerAlt6IID,
+                                       (void**)&scriptSecurityManagerNewer);
+        }
+        if (!NS_SUCCEEDED(rv)) {
+            rv = MRJPlugin::GetService("@mozilla.org/scriptsecuritymanager;1",
+                                       nsIScriptSecurityManagerNewerAlt5IID,
+                                       (void**)&scriptSecurityManagerNewer);
+        }
+        if (!NS_SUCCEEDED(rv)) {
+            rv = MRJPlugin::GetService("@mozilla.org/scriptsecuritymanager;1",
+                                       nsIScriptSecurityManagerNewerAlt4IID,
+                                       (void**)&scriptSecurityManagerNewer);
+        }
+        //if (!NS_SUCCEEDED(rv)) {
+        //    rv = MRJPlugin::GetService("@mozilla.org/scriptsecuritymanager;1",
+        //                               nsIScriptSecurityManagerNewerAlt3IID,
+        //                               (void**)&scriptSecurityManagerNewer);
+        //}
+        //if (!NS_SUCCEEDED(rv)) {
+        //    rv = MRJPlugin::GetService("@mozilla.org/scriptsecuritymanager;1",
+        //                               nsIScriptSecurityManagerNewerAlt2IID,
+        //                               (void**)&scriptSecurityManagerNewer);
+        //}
+        if (!NS_SUCCEEDED(rv)) {
+            rv = MRJPlugin::GetService("@mozilla.org/scriptsecuritymanager;1",
+                                       nsIScriptSecurityManagerNewerAlt1IID,
+                                       (void**)&scriptSecurityManagerNewer);
+        }
+        if (NS_SUCCEEDED(rv)) {
+            if (scriptSecurityManager && !mScriptSecurityManager)
+                mScriptSecurityManager = scriptSecurityManager;
+            if (scriptSecurityManagerNew && !mScriptSecurityManagerNew)
+                mScriptSecurityManagerNew = scriptSecurityManagerNew;
+            if (scriptSecurityManagerNewer && !mScriptSecurityManagerNewer)
+                mScriptSecurityManagerNewer = scriptSecurityManagerNewer;
+            if (scriptSecurityManagerNewest && !mScriptSecurityManagerNewest)
+                mScriptSecurityManagerNewest = scriptSecurityManagerNewest;
+        }
+        if (debugProxyJNI) {
+            if (NS_SUCCEEDED(rv)) {
+                info = CFStringCreateWithFormat(NULL, NULL,
+                    CFSTR("MRJPluginJEP: GetService() succeeded, security manager 0x%.8X"),
+                    ((unsigned) scriptSecurityManager ? (unsigned) scriptSecurityManager :
+                    ((unsigned) scriptSecurityManagerNew ? (unsigned) scriptSecurityManagerNew :
+                    ((unsigned) scriptSecurityManagerNewest ? (unsigned) scriptSecurityManagerNewest :
+                    (unsigned) scriptSecurityManagerNewer))));
+            } else {
+                info = CFStringCreateWithFormat(NULL, NULL,
+                    CFSTR("MRJPluginJEP: GetService() failed"));
+            }
+            JEPLogJavaMessage(info);
+        }
     }
     // XXX Simple principal caching mechanism. If the principal is the same as
     // last time, then keep using the same LiveConnect proxy class. This should
     // be adequate for the simple cases of a single document using LiveConnect.
     // There should also be some caching going on inside ProxyClassLoaderFactory,
     // which should return the same class loader for the same URL, until this
     // prinicipal changes. Idea:  could use a weak reference dictionary that
     // only holds the class loader while there are other strong references to it.
-    if (NS_SUCCEEDED(rv)) {
-        nsIPrincipal* scriptPrincipal;
-        rv = mScriptSecurityManager->GetSubjectPrincipal(&scriptPrincipal);
+    if (NS_SUCCEEDED(rv) && (mScriptSecurityManager ||
+        mScriptSecurityManagerNew || mScriptSecurityManagerNewer ||
+        mScriptSecurityManagerNewest))
+    {
+        if (mScriptSecurityManager) {
+            rv = mScriptSecurityManager->GetSubjectPrincipal(&scriptPrincipal);
+        } else if (mScriptSecurityManagerNew) {
+            rv = mScriptSecurityManagerNew->GetSubjectPrincipal(&scriptPrincipal);
+        } else if (mScriptSecurityManagerNewest) {
+            rv = mScriptSecurityManagerNewest->GetSubjectPrincipal(&scriptPrincipal);
+        } else {
+            rv = mScriptSecurityManagerNewer->GetSubjectPrincipal(&scriptPrincipal);
+        }
         if (NS_SUCCEEDED(rv)) {
+            if (debugProxyJNI) {
+                info = CFStringCreateWithFormat(NULL, NULL,
+                    CFSTR("MRJPluginJEP: GetSubjectPrincipal() succeeded, principal 0x%.8X"),
+                    (unsigned) scriptPrincipal);
+                JEPLogJavaMessage(info);
+            }
             if (scriptPrincipal != mScriptPrincipal) {
                 // invalidate our cached LiveConnectProxy class.
                 NS_IF_RELEASE(mScriptPrincipal);
                 mScriptPrincipal = scriptPrincipal;
                 if (mLiveConnectProxy) {
                     env->DeleteGlobalRef(mLiveConnectProxy);
                     mLiveConnectProxy = NULL;
                 }
             }
             if (!mLiveConnectProxy && scriptPrincipal) {
-                jclass liveConnectProxy = GetLiveConnectProxy(env, scriptPrincipal);
+                jclass liveConnectProxy = GetLiveConnectProxy(env, scriptPrincipal, this);
                 if (liveConnectProxy) {
                     mLiveConnectProxy = (jclass) env->NewGlobalRef(liveConnectProxy);
                     env->DeleteLocalRef(liveConnectProxy);
                 }
             }
+        } else if (debugProxyJNI) {
+            info = CFStringCreateWithFormat(NULL, NULL,
+                CFSTR("MRJPluginJEP: GetSubjectPrincipal() failed"));
+            JEPLogJavaMessage(info);
+        }
+    } else if (!NS_SUCCEEDED(rv)) {
+        if (debugProxyJNI) {
+            info = CFStringCreateWithFormat(NULL, NULL,
+                CFSTR("MRJPluginJEP: failing proxyJNI call, GetService() failed"));
+            JEPLogJavaMessage(info);
         }
+        /* Don't proceed if we can't find a security manager because
+         * GetService() has failed -- this helps protect us from disaster if
+         * mozilla.org continues to fiddle with the nsIScriptSecurityManager
+         * interface.  LiveConnect will break, but that's better than
+         * allowing it to proceed with no security.
+         */
+        printf("MRJ Plugin JEP: JavaScript-to-Java LiveConnect failed -- no security manager!\n");
+        return;
     }
     if (mLiveConnectProxy) {
+        proxyJNIProxySecurityBreak();
+        if (debugProxyJNI) {
+            info = CFStringCreateWithFormat(NULL, NULL,
+                CFSTR("MRJPluginJEP: doing proxyJNI with LiveConnectProxy security, security manager 0x%.8X"),
+                ((unsigned) scriptSecurityManager ? (unsigned) scriptSecurityManager :
+                ((unsigned) scriptSecurityManagerNew ? (unsigned) scriptSecurityManagerNew :
+                ((unsigned) scriptSecurityManagerNewest ? (unsigned) scriptSecurityManagerNewest :
+                (unsigned) scriptSecurityManagerNewer))));
+            JEPLogJavaMessage(info);
+        }
         jobject runnable = CreateJNIRunnable(env, msg);
         if (runnable) {
-            jmethodID runID = env->GetStaticMethodID(mLiveConnectProxy, "run", "(Ljava/lang/Runnable;)V");
-            if (runID) {
-                env->CallStaticVoidMethod(mLiveConnectProxy, runID, runnable);
+            if (JEPCheckBundle()) {
+                jobject applet = NULL;
+                MRJPluginInstance *pluginInstance = msg->getPluginInstance();
+                if (pluginInstance)
+                    pluginInstance->GetJavaObject(&applet);
+                Boolean isCallMethodCall = msg->isCallMethodCall();
+                JEPDoLiveConnectProxy(mLiveConnectProxy, runnable, applet,
+                    isCallMethodCall);
                 savePendingException(env);
+            } else {
+                jmethodID runID = env->GetStaticMethodID(mLiveConnectProxy, "run", "(Ljava/lang/Runnable;)V");
+                if (runID) {
+                    env->CallStaticVoidMethod(mLiveConnectProxy, runID, runnable);
+                    savePendingException(env);
+                }
             }
-            env->DeleteLocalRef(runnable);
+            env->DeleteGlobalRef(runnable);
         }
     } else {
+        if (!scriptPrincipal) {
+            proxyJNINoSecurityNullPrincipalBreak();
+        } else {
+            proxyJNINoSecurityBreak();
+        }
+        if (debugProxyJNI) {
+            info = CFStringCreateWithFormat(NULL, NULL,
+                CFSTR("MRJPluginJEP: doing proxyJNI with no additional security, security manager 0x%.8X"),
+                ((unsigned) scriptSecurityManager ? (unsigned) scriptSecurityManager :
+                ((unsigned) scriptSecurityManagerNew ? (unsigned) scriptSecurityManagerNew :
+                ((unsigned) scriptSecurityManagerNewest ? (unsigned) scriptSecurityManagerNewest :
+                (unsigned) scriptSecurityManagerNewer))));
+            JEPLogJavaMessage(info);
+        }
         msg->execute(env);
         savePendingException(env);
     }
 #else
 	messageLoop(mProxyEnv, msg, mJavaQueue, mNativeQueue, true);
 #endif
 }
 
 /**
  * Used to send a message from Java to Native threads.
  */
 void CSecureEnv::sendMessageFromJava(JNIEnv* javaEnv, JavaMessage* msg, Boolean busyWaiting)
 {
 	messageLoop(javaEnv, msg, mNativeQueue, mJavaQueue, busyWaiting);
 }
 
-////////////////////////////////////////////////////////////////////////////
-// Table-driven nsISupports data.
+/* See JNIUtils.java for an explanation of PushLCInfo() and PopLCInfo(),
+ * and why they're necessary.
+ */
 
-const InterfaceInfo CSecureEnv::sInterfaces[] = {
-	{ NS_ISECUREENV_IID, INTERFACE_OFFSET(CSecureEnv, nsISecureEnv) },
-	{ NS_IRUNNABLE_IID, INTERFACE_OFFSET(CSecureEnv, nsIRunnable) },
-};
-const UInt32 CSecureEnv::kInterfaceCount = sizeof(sInterfaces) / sizeof(InterfaceInfo);
+static jclass netscape_oji_JNIUtils = NULL;
+static jmethodID netscape_oji_JNIUtils_PushLCInfo = NULL;
+static jmethodID netscape_oji_JNIUtils_PopLCInfo = NULL;
+static jmethodID netscape_oji_JNIUtils_CurrentLCPluginInstance = NULL;
+
+static void PushLCInfo(JNIEnv* env, jint pluginInstance)
+{
+	if (!netscape_oji_JNIUtils) {
+		jclass clazz = env->FindClass("netscape/oji/JNIUtils");
+		if (!clazz) return;
+		netscape_oji_JNIUtils_PushLCInfo =
+			env->GetStaticMethodID(clazz, "PushLCInfo", "(I)V");
+		netscape_oji_JNIUtils_PopLCInfo =
+			env->GetStaticMethodID(clazz, "PopLCInfo", "()V");
+		netscape_oji_JNIUtils_CurrentLCPluginInstance =
+			env->GetStaticMethodID(clazz, "CurrentLCPluginInstance", "()I");
+		netscape_oji_JNIUtils = (jclass) env->NewGlobalRef(clazz);
+		env->DeleteLocalRef(clazz);
+	}
+    check_exceptions(env);
+	env->CallStaticVoidMethod(netscape_oji_JNIUtils,
+		netscape_oji_JNIUtils_PushLCInfo, pluginInstance);
+}
+
+static void PopLCInfo(JNIEnv* env)
+{
+	if (!netscape_oji_JNIUtils)
+		return;
+    check_exceptions(env);
+	env->CallStaticVoidMethod(netscape_oji_JNIUtils,
+		netscape_oji_JNIUtils_PopLCInfo);
+}
+
+static MRJPluginInstance *CurrentLCPluginInstance(JNIEnv* env)
+{
+	if (!netscape_oji_JNIUtils)
+		return NULL;
+	check_exceptions(env);
+	return (MRJPluginInstance *)
+		env->CallStaticIntMethod(netscape_oji_JNIUtils,
+		netscape_oji_JNIUtils_CurrentLCPluginInstance);
+}
+
+static char *toString(jobject javaThing, JNIEnv *env)
+{
+	jclass objectClass;
+	jmethodID toString;
+	jstring description;
+	const char *descriptionUTF8;
+	jint descriptionLength;
+	char *retval = NULL;
+	if (!javaThing || !env)
+		return NULL;
+	objectClass = env->FindClass("java/lang/Object");
+	toString = env->GetMethodID(objectClass, "toString",
+		"()Ljava/lang/String;");
+	env->DeleteLocalRef(objectClass);
+	description = (jstring) env->CallObjectMethod(javaThing, toString);
+	if (check_exceptions(env))
+		return NULL;
+	descriptionLength = env->GetStringUTFLength(description);
+	descriptionUTF8 = env->GetStringUTFChars(description, nil);
+	if (check_exceptions(env))
+		return NULL;
+	if ((retval = (char *) calloc(descriptionLength+1, sizeof(char))) == NULL)
+		return NULL;
+	memcpy(retval, descriptionUTF8, descriptionLength);
+	env->ReleaseStringUTFChars(description, descriptionUTF8);
+	env->DeleteLocalRef(description);
+	return retval;
+}
 
 CSecureEnv::CSecureEnv(MRJPlugin* plugin, JNIEnv* proxyEnv, JNIEnv* javaEnv)
-	:	SupportsMixin(this, sInterfaces, kInterfaceCount),
-		mPlugin(plugin), mProxyEnv(proxyEnv), mJavaEnv(javaEnv),
+	:	mPlugin(plugin), mProxyEnv(proxyEnv), mJavaEnv(javaEnv),
 		mSession(plugin->getSession()), mThreadManager(plugin->getThreadManager()),
 		mIsRunning(NULL), mJavaQueue(NULL), mNativeQueue(NULL),
 		mPendingException(NULL),
-		mScriptSecurityManager(NULL), mScriptPrincipal(NULL), mLiveConnectProxy(NULL)
+		mScriptSecurityManager(NULL), mScriptSecurityManagerNew(NULL),
+		mScriptSecurityManagerNewer(NULL), mScriptSecurityManagerNewest(NULL),
+		mScriptPrincipal(NULL), mLiveConnectProxy(NULL)
 {
-	// need to create the JNIThread for communicating with Java.
-	if (mJavaEnv != NULL)
-        CreateNativeThread(this);
-	else
-	    CreateJNIThread(this);
+	if (mJavaEnv != NULL) {
+		CreateNativeThread(this);
+	} else {
+#if USE_LIVECONNECT_PROXY
+		mJavaEnv = mSession->getCurrentEnv();
+#else
+		CreateJNIThread(this);
+#endif
+	}
 }
 
-
 CSecureEnv::~CSecureEnv()  
 {
 	// Tell the Java thread to die.
 	if (mIsRunning != NULL) {
 		*mIsRunning = false;
 		mJavaQueue->notify();
 	}
 
     JNIEnv* env = mSession->getCurrentEnv();
     if (mPendingException) {
@@ -496,20 +987,51 @@
         mPendingException = NULL;
     }
     
     if (mLiveConnectProxy) {
         env->DeleteGlobalRef(mLiveConnectProxy);
         mLiveConnectProxy = NULL;
     }
     
     NS_IF_RELEASE(mScriptPrincipal);
     NS_IF_RELEASE(mScriptSecurityManager);
+    NS_IF_RELEASE(mScriptSecurityManagerNew);
+    NS_IF_RELEASE(mScriptSecurityManagerNewer);
+    NS_IF_RELEASE(mScriptSecurityManagerNewest);
+}
+
+NS_IMPL_ADDREF(CSecureEnv)
+NS_IMPL_RELEASE(CSecureEnv)
+
+NS_METHOD CSecureEnv::QueryInterface(const nsIID& aIID, void** aInstancePtr)
+{
+	static nsID nsISecureEnvIID = NS_ISECUREENV_IID;
+    if (aInstancePtr == NULL) {
+        return NS_ERROR_NULL_POINTER;
+    }
+    *aInstancePtr = NULL;
+    if (aIID.Equals(nsISecureEnvIID)) {
+        *aInstancePtr = (void *) (nsISecureEnv *) this;
+        AddRef();
+        return NS_OK;
+    }
+    if (aIID.Equals(NS_GET_IID(nsIRunnable))) {
+        *aInstancePtr = (void *) (nsIRunnable *) this;
+        AddRef();
+        return NS_OK;
+    }
+    if (aIID.Equals(NS_GET_IID(nsISupports))) {
+        *aInstancePtr = (void *) this;
+        AddRef();
+        return NS_OK;
+    }
+    return NS_NOINTERFACE;
 }
 
 void CSecureEnv::initialize(JNIEnv* javaEnv, jboolean* isRunning, JavaMessageQueue* javaQueue, JavaMessageQueue* nativeQueue)
 {
 	mJavaEnv = javaEnv;
 	mIsRunning = isRunning;
 	mJavaQueue = javaQueue;
 	mNativeQueue = nativeQueue;
 }
 
@@ -573,31 +1095,40 @@
 #endif
 	}
 };
 
 NS_IMETHODIMP CSecureEnv::NewObject(/*[in]*/  jclass clazz, 
                                     /*[in]*/  jmethodID methodID, 
                                     /*[in]*/  jvalue *args, 
                                     /*[out]*/ jobject* result,
                                     /*[in]*/  nsISecurityContext* ctx)
 {
-    if (clazz == NULL || methodID == NULL)
+    if (clazz == NULL || methodID == NULL || result == NULL)
         return NS_ERROR_NULL_POINTER;
+    /* http://java.sun.com/j2se/1.4.2/docs/guide/jni/jni-12.html's 2001
+     * "clarification" says that NewGlobalRef() and NewLocalRef() return NULL
+     * if the object they're called on has been freed.
+     */
+    JNIEnv *javaEnv = mSession->getCurrentEnv();
+    if (!javaEnv || ((clazz = (jclass) javaEnv->NewGlobalRef(clazz)) == NULL))
+        return NS_ERROR_FAILURE;
 
+    *result = NULL;
 #if PROXY_JNI_CALLS
     // Call method on Java side
     NewObjectMessage msg(clazz, methodID, args, result);
     sendMessageToJava(&msg);
 #else
 	*result = mJavaEnv->NewObjectA(clazz, methodID, args);
 #endif
-	
+
+	javaEnv->DeleteGlobalRef(clazz);
 	return NS_OK;
 }
 
 
 ///=--------------------------------------------------------------------------=
 // CSecureEnv::CallMethod
 ///=--------------------------------------------------------------------------=
 // Invoke method on Java object in LiveConnect.
 //
 // @param type       -- Return type
@@ -606,33 +1137,119 @@
 // @param result     -- return result of invocation.
 // @param ctx        -- security context 
 //
 
 class CallMethodMessage : public JavaMessage {
 	jni_type return_type;
 	jobject obj;
 	jmethodID methodID;
 	jvalue* args;
 	jvalue* result;
+	jclass ourClass;
+	jobject ourMethod;
+	char *ourMethodStr;
+	static jclass classClass;
+	static jclass constructorClass;
+	static jclass fieldClass;
+	static jclass methodClass;
 
 public:
-	CallMethodMessage(jni_type return_type, jobject obj, jmethodID methodID, jvalue *args, jvalue* result)
+	CallMethodMessage(jni_type return_type, jobject obj, jmethodID methodID,
+		jvalue *args, jvalue* result, MRJPluginInstance *pluginInstance)
+		: JavaMessage(pluginInstance)
 	{
 		this->return_type = return_type;
 		this->obj = obj;
 		this->methodID = methodID;
 		this->args = args;
 		this->result = result;
+		ourClass = NULL;
+		ourMethod = NULL;
+		ourMethodStr = NULL;
+	}
+
+	/* As noted in the comment above setCallMethodCall() in JavaMessageQueue.h,
+	 * in Tiger and above we need to avoid making LiveConnect calls on the
+	 * main thread that might trigger Java drawing.  But avoiding the main
+	 * thread is _very_ costly (especially (for some reason) on Intel Macs),
+	 * so we want to do these calls on the main thread if at all possible.
+	 * The cost is particularly apparent when you make the first JavaScript-
+	 * to-Java call on an applet that has lots of methods and fields (as do
+	 * GUI applets) -- because the browser "reflects" all these methods on
+	 * this first call, which can trigger thousands of extra JavaScript-to-
+	 * Java calls (for more information see bmo bug 191035, comments 14 and
+	 * 15).  Before JEP 0.9.5+h we simply avoided the main thread for all
+	 * CallMethod calls.  But this strategy isn't good enough for Intel Macs
+	 * -- the first call penalty can still be as much as 30 seconds (as
+	 * opposed to 3-4 seconds on a much slower PPC Mac).  So now I've added an
+	 * initializeMessage() method to this class and CallStaticMethodMessage
+	 * (below), which specifically keeps those calls on the main thread which
+	 * tend to be part of the Mozilla.org browser first-call storm (and which
+	 * can't trigger Java drawing).
+	 */
+	void initializeMessage(JNIEnv *env)
+	{
+		if ((getSystemVersion() < 0x1040) || !JEPCheckBundle())
+			return;
+		jclass clazz;
+		if (!classClass) {
+			if ((clazz = env->FindClass("java/lang/Class")) != NULL) {
+				classClass = (jclass) env->NewGlobalRef(clazz);
+				env->DeleteLocalRef(clazz);
+			}
+		}
+		if (!constructorClass) {
+			if ((clazz = env->FindClass("java/lang/reflect/Constructor")) != NULL) {
+				constructorClass = (jclass) env->NewGlobalRef(clazz);
+				env->DeleteLocalRef(clazz);
+			}
+		}
+		if (!fieldClass) {
+			if ((clazz = env->FindClass("java/lang/reflect/Field")) != NULL) {
+				fieldClass = (jclass) env->NewGlobalRef(clazz);
+				env->DeleteLocalRef(clazz);
+			}
+		}
+		if (!methodClass) {
+			if ((clazz = env->FindClass("java/lang/reflect/Method")) != NULL) {
+				methodClass = (jclass) env->NewGlobalRef(clazz);
+				env->DeleteLocalRef(clazz);
+			}
+		}
+		ourClass = env->GetObjectClass(obj);
+		ourMethod = env->ToReflectedMethod(ourClass, methodID, false);
+		ourMethodStr = toString(ourMethod, env);
+
+		Boolean shouldSetCallMethod = true;
+		if (env->IsSameObject(ourClass, classClass)) {
+			if (!is_Class_newInstance(env))
+				shouldSetCallMethod = false;
+		} else if (env->IsSameObject(ourClass, constructorClass)) {
+			if (!is_Constructor_newInstance(env))
+				shouldSetCallMethod = false;
+		} else if (env->IsSameObject(ourClass, fieldClass)) {
+			shouldSetCallMethod = false;
+		} else if (env->IsSameObject(ourClass, methodClass)) {
+			if (!is_Method_invoke(env))
+				shouldSetCallMethod = false;
+		}
+
+		if (shouldSetCallMethod)
+			setCallMethodCall();
+		free(ourMethodStr);
+		env->DeleteLocalRef(ourMethod);
+		env->DeleteLocalRef(ourClass);
 	}
 	
 	virtual void execute(JNIEnv* env)
 	{
+		PushLCInfo(env, (unsigned) mPluginInstance);
 		switch (return_type) {
 		case jobject_type:
 			result->l = env->CallObjectMethodA(obj, methodID, args);
 #if LOCAL_REFS_ARE_GLOBAL
             result->l = ToGlobalRef(env, result->l);
 #endif
 			break;
 		case jboolean_type:
 			result->z = env->CallBooleanMethodA(obj, methodID, args);
 			break;
@@ -654,38 +1271,124 @@
 		case jfloat_type:
 			result->f = env->CallFloatMethodA(obj, methodID, args);
 			break;
 		case jdouble_type:
 			result->d = env->CallDoubleMethodA(obj, methodID, args);
 			break;
 		case jvoid_type:
 			env->CallVoidMethodA(obj, methodID, args);
 			break;
 		}
+		PopLCInfo(env);
+		Release();
 	}
-};
+
+protected:
+	Boolean is_Class_newInstance(JNIEnv *env)
+	{
+		Boolean retval = false;
+		static jmethodID newInstanceID = env->GetMethodID(classClass,
+			"newInstance", "()Ljava/lang/Object;");
+		jobject newInstance = env->ToReflectedMethod(classClass,
+			newInstanceID, false);
+		if (check_exceptions(env))
+			return false;
+		char *newInstanceStr = toString(newInstance, env);
+		if (!newInstanceStr)
+			return false;
+		if (strcmp(newInstanceStr, ourMethodStr) == 0) 
+			retval = true;
+		free(newInstanceStr);
+		env->DeleteLocalRef(newInstance);
+		return retval;
+	}
+
+	Boolean is_Constructor_newInstance(JNIEnv *env)
+	{
+		Boolean retval = false;
+		static jmethodID newInstanceID = env->GetMethodID(constructorClass,
+			"newInstance", "([Ljava/lang/Object;)Ljava/lang/Object;");
+		jobject newInstance = env->ToReflectedMethod(constructorClass,
+			newInstanceID, false);
+		if (check_exceptions(env))
+			return false;
+		char *newInstanceStr = toString(newInstance, env);
+		if (!newInstanceStr)
+			return false;
+		if (strcmp(newInstanceStr, ourMethodStr) == 0) 
+			retval = true;
+		free(newInstanceStr);
+		env->DeleteLocalRef(newInstance);
+		return retval;
+	}
+
+	Boolean is_Method_invoke(JNIEnv *env)
+	{
+		Boolean retval = false;
+		static jmethodID invokeID = env->GetMethodID(methodClass,
+			"invoke", "(Ljava/lang/Object;[Ljava/lang/Object;)Ljava/lang/Object;");
+		jobject invoke = env->ToReflectedMethod(methodClass,
+			invokeID, false);
+		if (check_exceptions(env))
+			return false;
+		char *invokeStr = toString(invoke, env);
+		if (!invokeStr)
+			return false;
+		if (strcmp(invokeStr, ourMethodStr) == 0) 
+			retval = true;
+		free(invokeStr);
+		env->DeleteLocalRef(invoke);
+		return retval;
+	}
+};
+
+jclass CallMethodMessage::classClass = NULL;
+jclass CallMethodMessage::constructorClass = NULL;
+jclass CallMethodMessage::fieldClass = NULL;
+jclass CallMethodMessage::methodClass = NULL;
 
 NS_IMETHODIMP CSecureEnv::CallMethod(/*[in]*/  jni_type return_type,
                                       /*[in]*/  jobject obj, 
                                       /*[in]*/  jmethodID methodID, 
                                       /*[in]*/  jvalue *args, 
                                       /*[out]*/ jvalue* result,
                                       /*[in]*/  nsISecurityContext* ctx)
 {
-    if (obj == NULL || methodID == NULL)
+    if (mJavaEnv == NULL || obj == NULL || methodID == NULL || result == NULL)
         return NS_ERROR_NULL_POINTER;
+    /* http://java.sun.com/j2se/1.4.2/docs/guide/jni/jni-12.html's 2001
+     * "clarification" says that NewGlobalRef() and NewLocalRef() return NULL
+     * if the object they're called on has been freed.  It also helps to ensure
+     * 'obj' is a global ref, since msg->execute() might be called on a
+     * different thread (on OS X 10.4.X and above).  As far as I can tell we
+     * don't need to do the same for the jobjects among 'args'.
+     */
+    JNIEnv *javaEnv = mSession->getCurrentEnv();
+    if (!javaEnv || ((obj = javaEnv->NewGlobalRef(obj)) == NULL))
+        return NS_ERROR_FAILURE;
 
+	result->l = NULL;
 #if PROXY_JNI_CALLS
+	MRJPluginInstance *pluginInstance =
+		GetAppletInstance(javaEnv, obj);
+	if (!pluginInstance)
+		pluginInstance = CurrentLCPluginInstance(javaEnv);
+	if (!pluginInstance)
+		pluginInstance = GetSecContextInstance(ctx);
 	// Call method on Java side
 	// return CallJavaMethod(obj, method, args, ctx, result);
-	CallMethodMessage msg(return_type, obj, methodID, args, result);
-	sendMessageToJava(&msg);
+	CallMethodMessage *msg = new CallMethodMessage(return_type, obj, methodID,
+		args, result, pluginInstance);
+	if (msg) {
+		msg->initializeMessage(javaEnv);
+		sendMessageToJava(msg);
+	}
 #else
     JNIEnv* env = mJavaEnv;
 	switch (return_type) {
 	case jobject_type:
 		result->l = env->CallObjectMethodA(obj, methodID, args);
 		break;
 	case jboolean_type:
 		result->z = env->CallBooleanMethodA(obj, methodID, args);
 		break;
 	case jbyte_type:
@@ -708,20 +1411,21 @@
 		break;
 	case jdouble_type:
 		result->d = env->CallDoubleMethodA(obj, methodID, args);
 		break;
 	case jvoid_type:
 		env->CallVoidMethodA(obj, methodID, args);
 		break;
 	}
 #endif
 	
+	javaEnv->DeleteGlobalRef(obj);
 	return NS_OK;
 }
 
 
 ///=--------------------------------------------------------------------------=
 // CSecureEnv::CallNonvirtualMethod
 ///=--------------------------------------------------------------------------=
 // Invoke non-virtual method on Java object in LiveConnect.
 //
 // @param obj        -- Java object.
@@ -733,32 +1437,37 @@
 
 class CallNonvirtualMethodMessage : public JavaMessage {
 	jni_type type;
 	jobject obj;
 	jclass clazz;
 	jmethodID methodID;
 	jvalue* args;
 	jvalue* result;
 
 public:
-	CallNonvirtualMethodMessage(jni_type type, jobject obj, jclass clazz, jmethodID methodID, jvalue *args, jvalue* result)
+	CallNonvirtualMethodMessage(jni_type type, jobject obj, jclass clazz,
+		jmethodID methodID, jvalue *args, jvalue* result,
+		MRJPluginInstance *pluginInstance)
+		: JavaMessage(pluginInstance)
 	{
 		this->type = type;
 		this->obj = obj;
 		this->clazz = clazz;
 		this->methodID = methodID;
 		this->args = args;
 		this->result = result;
+		setCallMethodCall();
 	}
-	
+
 	virtual void execute(JNIEnv* env)
 	{
+		PushLCInfo(env, (unsigned) mPluginInstance);
 		switch (type) {
 		case jobject_type:
 			result->l = env->CallNonvirtualObjectMethodA(obj, clazz, methodID, args);
 #if LOCAL_REFS_ARE_GLOBAL
             result->l = ToGlobalRef(env, result->l);
 #endif
 			break;
 		case jboolean_type:
 			result->z = env->CallNonvirtualBooleanMethodA(obj, clazz, methodID, args);
 			break;
@@ -780,43 +1489,70 @@
 		case jfloat_type:
 			result->f = env->CallNonvirtualFloatMethodA(obj, clazz, methodID, args);
 			break;
 		case jdouble_type:
 			result->d = env->CallNonvirtualDoubleMethodA(obj, clazz, methodID, args);
 			break;
 		case jvoid_type:
 			env->CallNonvirtualVoidMethodA(obj, clazz, methodID, args);
 			break;
 		}
+		PopLCInfo(env);
+		Release();
 	}
 };
 
 NS_IMETHODIMP CSecureEnv::CallNonvirtualMethod(/*[in]*/  jni_type type,
                                                 /*[in]*/  jobject obj, 
                                                 /*[in]*/  jclass clazz,
                                                 /*[in]*/  jmethodID methodID,
                                                 /*[in]*/  jvalue *args, 
                                                 /*[out]*/ jvalue* result,
                                                 /*[in]*/  nsISecurityContext* ctx)
 {
-    if (obj == NULL || clazz == NULL || methodID == NULL)
+    if (obj == NULL || clazz == NULL || methodID == NULL || result == NULL)
         return NS_ERROR_NULL_POINTER;
+    /* http://java.sun.com/j2se/1.4.2/docs/guide/jni/jni-12.html's 2001
+     * "clarification" says that NewGlobalRef() and NewLocalRef() return NULL
+     * if the object they're called on has been freed.  It also helps to ensure
+     * 'obj' and 'clazz' are global refs, since msg->execute() might be called
+     * on a different thread (on OS X 10.4.X and above).  As far as I can tell
+     * we don't need to do the same for the jobjects among 'args'.
+     */
+    JNIEnv *javaEnv = mSession->getCurrentEnv();
+    if (!javaEnv || ((obj = javaEnv->NewGlobalRef(obj)) == NULL))
+        return NS_ERROR_FAILURE;
+    if ((clazz = (jclass) javaEnv->NewGlobalRef(clazz)) == NULL) {
+        javaEnv->DeleteGlobalRef(obj);
+        return NS_ERROR_FAILURE;
+    }
 
+	result->l = NULL;
 #if PROXY_JNI_CALLS
+	MRJPluginInstance *pluginInstance =
+		GetAppletInstance(javaEnv, obj);
+	if (!pluginInstance)
+		pluginInstance = CurrentLCPluginInstance(javaEnv);
+	if (!pluginInstance)
+		pluginInstance = GetSecContextInstance(ctx);
 	// Call non-virtual method on Java side
 	// return CallJavaMethod(obj, method, args, ctx, result);
-	CallNonvirtualMethodMessage msg(type, obj, clazz, methodID, args, result);
-	sendMessageToJava(&msg);
+	CallNonvirtualMethodMessage *msg = new CallNonvirtualMethodMessage(
+		type, obj, clazz, methodID, args, result, pluginInstance);
+	if (msg)
+		sendMessageToJava(msg);
 #else
     #error "Implement me!"
 #endif
 
+	javaEnv->DeleteGlobalRef(obj);
+	javaEnv->DeleteGlobalRef(clazz);
 	return NS_OK;
 }
 
 
 ///=--------------------------------------------------------------------------=
 // CSecureEnv::GetField
 ///=--------------------------------------------------------------------------=
 // Get a field on Java object in LiveConnect.
 //
 // @param obj        -- Java object.
@@ -865,33 +1601,43 @@
 			break;
 		case jlong_type:
 			result->j = env->GetLongField(obj, fieldID);
 			break;
 		case jfloat_type:
 			result->f = env->GetFloatField(obj, fieldID);
 			break;
 		case jdouble_type:
 			result->d = env->GetDoubleField(obj, fieldID);
 			break;
+		case jvoid_type:
+			break;
 		}
 	}
 };
 
 NS_IMETHODIMP CSecureEnv::GetField(/*[in]*/  jni_type type,
                                    /*[in]*/  jobject obj, 
                                    /*[in]*/  jfieldID fieldID,
                                    /*[out]*/ jvalue* result,
                                    /*[in]*/  nsISecurityContext* ctx)
 {
-    if (mJavaEnv == NULL || obj == NULL || fieldID == NULL)
+    if (mJavaEnv == NULL || obj == NULL || fieldID == NULL || result == NULL)
         return NS_ERROR_NULL_POINTER;
+    /* http://java.sun.com/j2se/1.4.2/docs/guide/jni/jni-12.html's 2001
+     * "clarification" says that NewGlobalRef() and NewLocalRef() return NULL
+     * if the object they're called on has been freed.
+     */
+    JNIEnv *javaEnv = mSession->getCurrentEnv();
+    if (!javaEnv || ((obj = javaEnv->NewGlobalRef(obj)) == NULL))
+        return NS_ERROR_FAILURE;
 
+    result->l = NULL;
 #if PROXY_JNI_CALLS
     // Get field on Java side
     GetFieldMessage msg(type, obj, fieldID, result);
     sendMessageToJava(&msg);
 #else    
 	JNIEnv* env = mJavaEnv;
 	switch (type) {
 	case jobject_type:
 		result->l = env->GetObjectField(obj, fieldID);
 		break;
@@ -912,23 +1658,26 @@
 		break;
 	case jlong_type:
 		result->j = env->GetLongField(obj, fieldID);
 		break;
 	case jfloat_type:
 		result->f = env->GetFloatField(obj, fieldID);
 		break;
 	case jdouble_type:
 		result->d = env->GetDoubleField(obj, fieldID);
 		break;
+	case jvoid_type:
+		break;
 	}
 #endif
 
+	javaEnv->DeleteGlobalRef(obj);
 	return NS_OK;
 }
 
 
 ///=--------------------------------------------------------------------------=
 // CSecureEnv::SetField
 ///=--------------------------------------------------------------------------=
 //
 // Set a field on Java object in LiveConnect.
 //
@@ -975,32 +1724,41 @@
     		break;
     	case jlong_type:
     		env->SetLongField(obj, fieldID, val.j);
     		break;
     	case jfloat_type:
     		env->SetFloatField(obj, fieldID, val.f);
     		break;
     	case jdouble_type:
     		env->SetDoubleField(obj, fieldID, val.d);
     		break;
+		case jvoid_type:
+			break;
     	}
 	}
 };
 
 NS_IMETHODIMP CSecureEnv::SetField(/*[in]*/ jni_type type,
                                     /*[in]*/ jobject obj, 
                                     /*[in]*/ jfieldID fieldID,
                                     /*[in]*/ jvalue val,
                                     /*[in]*/ nsISecurityContext* ctx)
 {
     if (mJavaEnv == NULL || obj == NULL || fieldID == NULL)
         return NS_ERROR_NULL_POINTER;
+    /* http://java.sun.com/j2se/1.4.2/docs/guide/jni/jni-12.html's 2001
+     * "clarification" says that NewGlobalRef() and NewLocalRef() return NULL
+     * if the object they're called on has been freed.
+     */
+    JNIEnv *javaEnv = mSession->getCurrentEnv();
+    if (!javaEnv || ((obj = javaEnv->NewGlobalRef(obj)) == NULL))
+        return NS_ERROR_FAILURE;
 
 #if PROXY_JNI_CALLS
     // Set field on Java side
     SetFieldMessage msg(type, obj, fieldID, val);
     sendMessageToJava(&msg);
 #else
 	JNIEnv* env = mJavaEnv;
 	switch (type) {
 	case jobject_type:
 		env->SetObjectField(obj, fieldID, val.l);
@@ -1022,23 +1780,26 @@
 		break;
 	case jlong_type:
 		env->SetLongField(obj, fieldID, val.j);
 		break;
 	case jfloat_type:
 		env->SetFloatField(obj, fieldID, val.f);
 		break;
 	case jdouble_type:
 		env->SetDoubleField(obj, fieldID, val.d);
 		break;
+	case jvoid_type:
+		break;
 	}
 #endif
 
+	javaEnv->DeleteGlobalRef(obj);
 	return NS_OK;
 }
 
 
 ///=--------------------------------------------------------------------------=
 // CSecureEnv::CallStaticMethod
 ///=--------------------------------------------------------------------------=
 //
 // Invoke static method on Java object in LiveConnect.
 //
@@ -1048,32 +1809,67 @@
 // @param result     -- return result of invocation.
 // @param ctx        -- security context 
 //
 
 class CallStaticMethodMessage : public JavaMessage {
 	jni_type type;
 	jclass clazz;
 	jmethodID methodID;
 	jvalue* args;
 	jvalue* result;
+	jobject ourMethod;
+	char *ourMethodStr;
+	static jclass systemClass;
+
 public:
-	CallStaticMethodMessage(jni_type type, jclass clazz, jmethodID methodID, jvalue *args, jvalue* result)
+	CallStaticMethodMessage(jni_type type, jclass clazz, jmethodID methodID,
+		jvalue *args, jvalue* result, MRJPluginInstance *pluginInstance)
+		: JavaMessage(pluginInstance)
 	{
 		this->type = type;
 		this->clazz = clazz;
 		this->methodID = methodID;
 		this->args = args;
 		this->result = result;
+		ourMethod = NULL;
+		ourMethodStr = NULL;
 	}
 	
+	void initializeMessage(JNIEnv *env)
+	{
+		if ((getSystemVersion() < 0x1040) || !JEPCheckBundle())
+			return;
+		if (!systemClass) {
+			jclass temp;
+			if ((temp = env->FindClass("java/lang/System")) != NULL) {
+				systemClass = (jclass) env->NewGlobalRef(temp);
+				env->DeleteLocalRef(temp);
+			}
+		}
+		ourMethod = env->ToReflectedMethod(clazz, methodID, true);
+		ourMethodStr = toString(ourMethod, env);
+
+		Boolean shouldSetCallMethod = true;
+		if (env->IsSameObject(clazz, systemClass)) {
+			if (is_System_identityHashCode(env))
+				shouldSetCallMethod = false;
+		}
+
+		if (shouldSetCallMethod)
+			setCallMethodCall();
+		free(ourMethodStr);
+		env->DeleteLocalRef(ourMethod);
+	}
+
 	virtual void execute(JNIEnv* env)
 	{
+		PushLCInfo(env, (unsigned) mPluginInstance);
 		switch (type) {
 		case jobject_type:
 			result->l = env->CallStaticObjectMethodA(clazz, methodID, args);
 #if LOCAL_REFS_ARE_GLOBAL
             result->l = ToGlobalRef(env, result->l);
 #endif
 			break;
 		case jboolean_type:
 			result->z = env->CallStaticBooleanMethodA(clazz, methodID, args);
 			break;
@@ -1095,42 +1891,85 @@
 		case jfloat_type:
 			result->f = env->CallStaticFloatMethodA(clazz, methodID, args);
 			break;
 		case jdouble_type:
 			result->d = env->CallStaticDoubleMethodA(clazz, methodID, args);
 			break;
 		case jvoid_type:
 			env->CallStaticVoidMethodA(clazz, methodID, args);
 			break;
 		}
+		PopLCInfo(env);
+		Release();
+	}
+
+protected:
+	Boolean is_System_identityHashCode(JNIEnv *env)
+	{
+		Boolean retval = false;
+		static jmethodID identityHashCodeID = env->GetStaticMethodID(
+			systemClass, "identityHashCode", "(Ljava/lang/Object;)I");
+		jobject identityHashCode = env->ToReflectedMethod(systemClass,
+			identityHashCodeID, true);
+		if (check_exceptions(env))
+			return false;
+		char *identityHashCodeStr = toString(identityHashCode, env);
+		if (!identityHashCodeStr)
+			return false;
+		if (strcmp(identityHashCodeStr, ourMethodStr) == 0) 
+			retval = true;
+		free(identityHashCodeStr);
+		env->DeleteLocalRef(identityHashCode);
+		return retval;
 	}
 };
 
+jclass CallStaticMethodMessage::systemClass = NULL;
+
 NS_IMETHODIMP CSecureEnv::CallStaticMethod(/*[in]*/  jni_type type,
                                             /*[in]*/  jclass clazz,
                                             /*[in]*/  jmethodID methodID,
                                             /*[in]*/  jvalue *args, 
                                             /*[out]*/ jvalue* result,
                                             /*[in]*/  nsISecurityContext* ctx)
 {
-    if (clazz == NULL || methodID == NULL)
+    if (clazz == NULL || methodID == NULL || result == NULL)
         return NS_ERROR_NULL_POINTER;
+    /* http://java.sun.com/j2se/1.4.2/docs/guide/jni/jni-12.html's 2001
+     * "clarification" says that NewGlobalRef() and NewLocalRef() return NULL
+     * if the object they're called on has been freed.  It also helps to ensure
+     * 'clazz' is a global ref, since msg->execute() might be called on a
+     * different thread (on OS X 10.4.X and above).  As far as I can tell we
+     * don't need to do the same for the jobjects among 'args'.
+     */
+    JNIEnv *javaEnv = mSession->getCurrentEnv();
+    if (!javaEnv || ((clazz = (jclass) javaEnv->NewGlobalRef(clazz)) == NULL))
+        return NS_ERROR_FAILURE;
 
+	result->l = NULL;
 #if PROXY_JNI_CALLS
+	MRJPluginInstance *pluginInstance = CurrentLCPluginInstance(javaEnv);
+	if (!pluginInstance)
+		pluginInstance = GetSecContextInstance(ctx);
 	// Call method on Java side
 	// return CallJavaMethod(NULL, method, args, ctx, result);
-	CallStaticMethodMessage msg(type, clazz, methodID, args, result);
-	sendMessageToJava(&msg);
+	CallStaticMethodMessage *msg = new CallStaticMethodMessage(type, clazz,
+		methodID, args, result, pluginInstance);
+	if (msg) {
+		msg->initializeMessage(javaEnv);
+		sendMessageToJava(msg);
+	}
 #else
     #error "Implement me!"
 #endif
 
+	javaEnv->DeleteGlobalRef(clazz);
 	return NS_OK;
 }
 
 
 ///=--------------------------------------------------------------------------=
 // CSecureEnv::GetStaticField
 ///=--------------------------------------------------------------------------=
 // Get a static field on Java object in LiveConnect.
 //
 // @param obj        -- Java object.
@@ -1179,33 +2018,43 @@
 			break;
 		case jlong_type:
 			result->j = env->GetStaticLongField(clazz, fieldID);
 			break;
 		case jfloat_type:
 			result->f = env->GetStaticFloatField(clazz, fieldID);
 			break;
 		case jdouble_type:
 			result->d = env->GetStaticDoubleField(clazz, fieldID);
 			break;
+		case jvoid_type:
+			break;
 		}
 	}
 };
 
 NS_IMETHODIMP CSecureEnv::GetStaticField(/*[in]*/  jni_type type,
                                           /*[in]*/  jclass clazz, 
                                           /*[in]*/  jfieldID fieldID,
                                           /*[out]*/ jvalue* result,
                                           /*[in]*/  nsISecurityContext* ctx)
 {
-    if (mJavaEnv == NULL || clazz == NULL || fieldID == NULL)
+    if (mJavaEnv == NULL || clazz == NULL || fieldID == NULL || result == NULL)
         return NS_ERROR_NULL_POINTER;
+    /* http://java.sun.com/j2se/1.4.2/docs/guide/jni/jni-12.html's 2001
+     * "clarification" says that NewGlobalRef() and NewLocalRef() return NULL
+     * if the object they're called on has been freed.
+     */
+    JNIEnv *javaEnv = mSession->getCurrentEnv();
+    if (!javaEnv || ((clazz = (jclass) javaEnv->NewGlobalRef(clazz)) == NULL))
+        return NS_ERROR_FAILURE;
 
+    result->l = NULL;
 #if PROXY_JNI_CALLS
     // Get static field on Java side
 	GetStaticFieldMessage msg(type, clazz, fieldID, result);
 	sendMessageToJava(&msg);
 #else
     // This doesn't work in Mac OS X.
 	// should be able to perform in Java env.
 	JNIEnv* env = mJavaEnv;
 	switch (type) {
 	case jobject_type:
@@ -1228,23 +2077,26 @@
 		break;
 	case jlong_type:
 		result->j = env->GetStaticLongField(clazz, fieldID);
 		break;
 	case jfloat_type:
 		result->f = env->GetStaticFloatField(clazz, fieldID);
 		break;
 	case jdouble_type:
 		result->d = env->GetStaticDoubleField(clazz, fieldID);
 		break;
+	case jvoid_type:
+		break;
 	}
 #endif
 
+	javaEnv->DeleteGlobalRef(clazz);
 	return NS_OK;
 }
 
 
 ///=--------------------------------------------------------------------------=
 // CSecureEnv::SetStaticField
 ///=--------------------------------------------------------------------------=
 // Set a static field on Java object in LiveConnect.
 //
 // @param obj        -- Java object.
@@ -1290,32 +2142,41 @@
     		break;
     	case jlong_type:
     		env->SetStaticLongField(clazz, fieldID, val.j);
     		break;
     	case jfloat_type:
     		env->SetStaticFloatField(clazz, fieldID, val.f);
     		break;
     	case jdouble_type:
     		env->SetStaticDoubleField(clazz, fieldID, val.d);
     		break;
+		case jvoid_type:
+			break;
     	}
 	}
 };
 
 NS_IMETHODIMP CSecureEnv::SetStaticField(/*[in]*/  jni_type type,
                                           /*[in]*/ jclass clazz, 
                                           /*[in]*/ jfieldID fieldID,
                                           /*[in]*/ jvalue val,
                                           /*[in]*/ nsISecurityContext* ctx)
 {
     if (mJavaEnv == NULL || clazz == NULL || fieldID == NULL)
         return NS_ERROR_NULL_POINTER;
+    /* http://java.sun.com/j2se/1.4.2/docs/guide/jni/jni-12.html's 2001
+     * "clarification" says that NewGlobalRef() and NewLocalRef() return NULL
+     * if the object they're called on has been freed.
+     */
+    JNIEnv *javaEnv = mSession->getCurrentEnv();
+    if (!javaEnv || ((clazz = (jclass) javaEnv->NewGlobalRef(clazz)) == NULL))
+        return NS_ERROR_FAILURE;
 
 #if PROXY_JNI_CALLS
 	// Set static field on Java side
 	SetStaticFieldMessage msg(type, clazz, fieldID, val);
 	sendMessageToJava(&msg);
 #else
 	JNIEnv* env = mJavaEnv;
 	switch (type) {
 	case jobject_type:
 		env->SetStaticObjectField(clazz, fieldID, val.l);
@@ -1337,34 +2198,38 @@
 		break;
 	case jlong_type:
 		env->SetStaticLongField(clazz, fieldID, val.j);
 		break;
 	case jfloat_type:
 		env->SetStaticFloatField(clazz, fieldID, val.f);
 		break;
 	case jdouble_type:
 		env->SetStaticDoubleField(clazz, fieldID, val.d);
 		break;
+	case jvoid_type:
+		break;
 	}
 #endif
 
+	javaEnv->DeleteGlobalRef(clazz);
 	return NS_OK;
 }
 
 
 NS_IMETHODIMP CSecureEnv::GetVersion(/*[out]*/ jint* version) 
 {
-    if (mJavaEnv == NULL || version == NULL)
+    JNIEnv* env = mSession->getCurrentEnv();
+
+    if (env == NULL || version == NULL)
         return NS_ERROR_NULL_POINTER;
-    
- 	JNIEnv* env = mJavaEnv;
-	*version = env->GetVersion();
+
+    *version = env->GetVersion();
 
     return NS_OK;
 }
 
 /**
  * To give proper "local" refs, need to run this in the Java thread.
  */
 class DefineClassMessage : public JavaMessage {
 	const char* name;
 	jobject loader;
@@ -1377,32 +2242,36 @@
 		this->name = name;
 		this->loader = loader;
 		this->buf = buf;
 		this->len = len;
 		this->clazz = clazz;
 	}
 	
 	virtual void execute(JNIEnv* env)
 	{
     	*clazz = env->DefineClass(name, loader, buf, len);
+#if LOCAL_REFS_ARE_GLOBAL
+        *clazz = (jclass) ToGlobalRef(env, *clazz);
+#endif
 	}
 };
 
 NS_IMETHODIMP CSecureEnv::DefineClass(/*[in]*/  const char* name,
                                        /*[in]*/  jobject loader,
                                        /*[in]*/  const jbyte *buf,
                                        /*[in]*/  jsize len,
                                        /*[out]*/ jclass* clazz) 
 {
-    if (mJavaEnv == NULL || clazz == NULL)
+    if (mJavaEnv == NULL || name == NULL || buf == NULL || clazz == NULL)
         return NS_ERROR_NULL_POINTER;
 
+    *clazz = NULL;
 #if PROXY_JNI_CALLS
     DefineClassMessage msg(name, loader, buf, len, clazz);
     sendMessageToJava(&msg);
 #else
     *clazz = mJavaEnv->DefineClass(name, loader, buf, len);
 #endif
 
     return NS_OK;
 }
 
@@ -1424,23 +2293,24 @@
 		*result = env->FindClass(name);
 #if LOCAL_REFS_ARE_GLOBAL
         *result = (jclass) ToGlobalRef(env, *result);
 #endif
 	}
 };
 
 NS_IMETHODIMP CSecureEnv::FindClass(/*[in]*/  const char* name, 
                                      /*[out]*/ jclass* clazz) 
 {
-    if (clazz == NULL)
+    if (name == NULL || clazz == NULL)
         return NS_ERROR_NULL_POINTER;
 
+	*clazz = NULL;
 #if PROXY_JNI_CALLS
 	FindClassMessage msg(name, clazz);
 	sendMessageToJava(&msg);
 #else
 	*clazz = mJavaEnv->FindClass(name);
 #endif
 
     return NS_OK;
 }
 
@@ -1453,36 +2323,48 @@
 public:
 	GetSuperclassMessage(jclass sub, jclass* super)
 	{
 		this->sub = sub;
 		this->super = super;
 	}
 
 	virtual void execute(JNIEnv* env)
 	{
     	*super = env->GetSuperclass(sub);
+#if LOCAL_REFS_ARE_GLOBAL
+        *super = (jclass) ToGlobalRef(env, *super);
+#endif
 	}
 };
 
 NS_IMETHODIMP CSecureEnv::GetSuperclass(/*[in]*/  jclass sub,
                                          /*[out]*/ jclass* super) 
 {
-    if (mJavaEnv == NULL || super == NULL)
+    if (mJavaEnv == NULL || sub == NULL || super == NULL)
         return NS_ERROR_NULL_POINTER;
+    /* http://java.sun.com/j2se/1.4.2/docs/guide/jni/jni-12.html's 2001
+     * "clarification" says that NewGlobalRef() and NewLocalRef() return NULL
+     * if the object they're called on has been freed.
+     */
+    JNIEnv *javaEnv = mSession->getCurrentEnv();
+    if (!javaEnv || ((sub = (jclass) javaEnv->NewGlobalRef(sub)) == NULL))
+        return NS_ERROR_FAILURE;
 
+	*super = NULL;
 #if PROXY_JNI_CALLS
 	GetSuperclassMessage msg(sub, super);
 	sendMessageToJava(&msg);
 #else
 	*super = mJavaEnv->GetSuperclass(sub);
 #endif
 
+    javaEnv->DeleteGlobalRef(sub);
     return NS_OK;
 }
 
 
 class IsAssignableFromMessage : public JavaMessage {
     jclass sub;
     jclass super;
     jboolean* result;
 public:
 	IsAssignableFromMessage(jclass sub, jclass super, jboolean* result)
@@ -1495,31 +2377,45 @@
 	virtual void execute(JNIEnv* env)
 	{
         *result = env->IsAssignableFrom(sub, super);
 	}
 };
 
 NS_IMETHODIMP CSecureEnv::IsAssignableFrom(/*[in]*/  jclass sub,
                                             /*[in]*/  jclass super,
                                             /*[out]*/ jboolean* result) 
 {
-    if (mJavaEnv == NULL || result == NULL)
+    if (mJavaEnv == NULL || sub == NULL || super == NULL || result == NULL)
         return NS_ERROR_NULL_POINTER;
+    /* http://java.sun.com/j2se/1.4.2/docs/guide/jni/jni-12.html's 2001
+     * "clarification" says that NewGlobalRef() and NewLocalRef() return NULL
+     * if the object they're called on has been freed.
+     */
+    JNIEnv *javaEnv = mSession->getCurrentEnv();
+    if (!javaEnv || ((sub = (jclass) javaEnv->NewGlobalRef(sub)) == NULL))
+        return NS_ERROR_FAILURE;
+    if ((super = (jclass) javaEnv->NewGlobalRef(super)) == NULL) {
+        javaEnv->DeleteGlobalRef(sub);
+        return NS_ERROR_FAILURE;
+    }
 
+	*result = false;
 #if PROXY_JNI_CALLS    
 	IsAssignableFromMessage msg(sub, super, result);
 	sendMessageToJava(&msg);
 #else
 	// JNIEnv* env = mSession->getCurrentEnv();
 	*result = mJavaEnv->IsAssignableFrom(sub, super);
 #endif
 
+    javaEnv->DeleteGlobalRef(sub);
+    javaEnv->DeleteGlobalRef(super);
     return NS_OK;
 }
 
 
 class ThrowMessage : public JavaMessage {
     jthrowable obj;
     jint* result;
 public:
 	ThrowMessage(jthrowable obj, jint* result)
 	{
@@ -1529,30 +2425,38 @@
 
 	virtual void execute(JNIEnv* env)
 	{
         *result = env->Throw(obj);
 	}
 };
 
 NS_IMETHODIMP CSecureEnv::Throw(/*[in]*/  jthrowable obj,
                                  /*[out]*/ jint* result) 
 {
-	if (mJavaEnv == NULL || result == NULL)
+	if (mJavaEnv == NULL || obj == NULL || result == NULL)
         return NS_ERROR_NULL_POINTER;
+    /* http://java.sun.com/j2se/1.4.2/docs/guide/jni/jni-12.html's 2001
+     * "clarification" says that NewGlobalRef() and NewLocalRef() return NULL
+     * if the object they're called on has been freed.
+     */
+    JNIEnv *javaEnv = mSession->getCurrentEnv();
+    if (!javaEnv || ((obj = (jthrowable) javaEnv->NewGlobalRef(obj)) == NULL))
+        return NS_ERROR_FAILURE;
     
 #if PROXY_JNI_CALLS    
 	ThrowMessage msg(obj, result);
 	sendMessageToJava(&msg);
 #else
     *result = mJavaEnv->Throw(obj);
 #endif
 
+    javaEnv->DeleteGlobalRef(obj);
     return NS_OK;
 }
 
 class ThrowNewMessage : public JavaMessage {
     jclass clazz;
     const char* message;
     jint* result;
 public:
 	ThrowNewMessage(jclass clazz, const char* message, jint* result)
 	{
@@ -1566,48 +2470,53 @@
         *result = env->ThrowNew(clazz, message);
 	}
 };
 
 NS_IMETHODIMP CSecureEnv::ThrowNew(/*[in]*/  jclass clazz,
                                     /*[in]*/  const char *message,
                                     /*[out]*/ jint* result) 
 {
     if (mJavaEnv == NULL || result == NULL)
         return NS_ERROR_NULL_POINTER;
+    /* http://java.sun.com/j2se/1.4.2/docs/guide/jni/jni-12.html's 2001
+     * "clarification" says that NewGlobalRef() and NewLocalRef() return NULL
+     * if the object they're called on has been freed.
+     */
+    JNIEnv *javaEnv = mSession->getCurrentEnv();
+    if (!javaEnv || ((clazz = (jclass) javaEnv->NewGlobalRef(clazz)) == NULL))
+        return NS_ERROR_FAILURE;
     
 #if PROXY_JNI_CALLS    
 	ThrowNewMessage msg(clazz, message, result);
 	sendMessageToJava(&msg);
 #else
     *result = mJavaEnv->ThrowNew(clazz, msg);
 #endif
 
+    javaEnv->DeleteGlobalRef(clazz);
     return NS_OK;
 }
 
 
 class ExceptionOccurredMessage : public JavaMessage {
     CSecureEnv* secureEnv;
     jthrowable* result;
 public:
 	ExceptionOccurredMessage(CSecureEnv* secureEnv, jthrowable* result)
 	{
 	    this->secureEnv = secureEnv;
 		this->result = result;
 	}
 
 	virtual void execute(JNIEnv* env)
 	{
         *result = secureEnv->getPendingException(env);
-#if LOCAL_REFS_ARE_GLOBAL
-        *result = (jthrowable) ToGlobalRef(env, *result);
-#endif
 	}
 };
 
 NS_IMETHODIMP CSecureEnv::ExceptionOccurred(/*[out]*/ jthrowable* result)
 {
 	if (mJavaEnv == NULL || result == NULL)
 		return NS_ERROR_NULL_POINTER;
     
 #if PROXY_JNI_CALLS
 	ExceptionOccurredMessage msg(this, result);
@@ -1655,21 +2564,24 @@
 #else
     mJavaEnv->ExceptionClear();
 #endif
 
     return NS_OK;
 }
 
 
 NS_IMETHODIMP CSecureEnv::FatalError(/*[in]*/ const char* msg)
 {
-    mJavaEnv->FatalError(msg);
+    JNIEnv* env = mSession->getCurrentEnv();
+    if (env == NULL)
+        return NS_ERROR_FAILURE;
+    env->FatalError(msg);
     return NS_OK;
 }
 
 
 /**
  * To give proper "local" refs, need to run this in the true thread.
  */
 
 class NewGlobalRefMessage : public JavaMessage {
 	jobject localRef;
@@ -1683,40 +2595,46 @@
 
 	virtual void execute(JNIEnv* env)
 	{
 		*result = env->NewGlobalRef(localRef);
 	}
 };
 
 NS_IMETHODIMP CSecureEnv::NewGlobalRef(/*[in]*/  jobject localRef, 
                                         /*[out]*/ jobject* result)
 {
-    if (result == NULL)
+    if (localRef == NULL || result == NULL)
         return NS_ERROR_NULL_POINTER;
 
+    *result = NULL;
 #if PROXY_JNI_CALLS
     NewGlobalRefMessage msg(localRef, result);
  	sendMessageToJava(&msg);
 #else
 	*result = mJavaEnv->NewGlobalRef(localRef);
 #endif
 
     return NS_OK;
 }
 
 /**
  * This should be safe to call from any thread, since global refs
  * are thread independent.
  */
 NS_IMETHODIMP CSecureEnv::DeleteGlobalRef(/*[in]*/ jobject globalRef) 
 {
-    mJavaEnv->DeleteGlobalRef(globalRef);
+    if (globalRef == NULL)
+        return NS_ERROR_NULL_POINTER;
+    JNIEnv* env = mSession->getCurrentEnv();
+    if (env == NULL)
+        return NS_ERROR_FAILURE;
+    env->DeleteGlobalRef(globalRef);
     return NS_OK;
 }
 
 /**
  * To give proper "local" refs, need to run this in the true thread.
  */
 class DeleteLocalRefMessage : public JavaMessage {
 	jobject localRef;
 public:
 	DeleteLocalRefMessage(jobject localRef)
@@ -1729,20 +2647,22 @@
 #if LOCAL_REFS_ARE_GLOBAL
 		env->DeleteGlobalRef(localRef);
 #else
 		env->DeleteLocalRef(localRef);
 #endif
 	}
 };
 
 NS_IMETHODIMP CSecureEnv::DeleteLocalRef(/*[in]*/ jobject localRef)
 {
+    if (localRef == NULL)
+        return NS_ERROR_NULL_POINTER;
 #if PROXY_JNI_CALLS
     DeleteLocalRefMessage msg(localRef);
  	sendMessageToJava(&msg);
 #else
     mJavaEnv->DeleteLocalRef(localRef);
 #endif
     return NS_OK;
 }
 
 class IsSameObjectMessage : public JavaMessage {
@@ -1760,30 +2680,44 @@
 	virtual void execute(JNIEnv* env)
 	{
 		*result = env->IsSameObject(obj1, obj2);
 	}
 };
 
 NS_IMETHODIMP CSecureEnv::IsSameObject(/*[in]*/  jobject obj1,
                                         /*[in]*/  jobject obj2,
                                         /*[out]*/ jboolean* result) 
 {
-    if (mJavaEnv == NULL || result == NULL)
+    if (mJavaEnv == NULL || obj1 == NULL || obj2 == NULL || result == NULL)
         return NS_ERROR_NULL_POINTER;
-    
+    /* http://java.sun.com/j2se/1.4.2/docs/guide/jni/jni-12.html's 2001
+     * "clarification" says that NewGlobalRef() and NewLocalRef() return NULL
+     * if the object they're called on has been freed.
+     */
+    JNIEnv *javaEnv = mSession->getCurrentEnv();
+    if (!javaEnv || ((obj1 = javaEnv->NewGlobalRef(obj1)) == NULL))
+        return NS_ERROR_FAILURE;
+    if ((obj2 = javaEnv->NewGlobalRef(obj2)) == NULL) {
+        javaEnv->DeleteGlobalRef(obj1);
+        return NS_ERROR_FAILURE;
+    }
+
+    *result = false;
 #if PROXY_JNI_CALLS
     IsSameObjectMessage msg(obj1, obj2, result);
  	sendMessageToJava(&msg);
 #else
     *result = mJavaEnv->IsSameObject(obj1, obj2);
 #endif
 
+    javaEnv->DeleteGlobalRef(obj1);
+    javaEnv->DeleteGlobalRef(obj2);
     return NS_OK;
 }
 
 
 class AllocObjectMessage : public JavaMessage {
 	jclass clazz;
 	jobject* result;
 public:
 	AllocObjectMessage(jclass clazz, jobject* result)
 	{
@@ -1796,30 +2730,39 @@
 		*result = env->AllocObject(clazz);
 #if LOCAL_REFS_ARE_GLOBAL
         *result = ToGlobalRef(env, *result);
 #endif
 	}
 };
 
 NS_IMETHODIMP CSecureEnv::AllocObject(/*[in]*/  jclass clazz,
                                       /*[out]*/ jobject* result) 
 {
-    if (mJavaEnv == NULL || result == NULL)
+    if (mJavaEnv == NULL || clazz == NULL || result == NULL)
         return NS_ERROR_NULL_POINTER;
-    
+    /* http://java.sun.com/j2se/1.4.2/docs/guide/jni/jni-12.html's 2001
+     * "clarification" says that NewGlobalRef() and NewLocalRef() return NULL
+     * if the object they're called on has been freed.
+     */
+    JNIEnv *javaEnv = mSession->getCurrentEnv();
+    if (!javaEnv || ((clazz = (jclass) javaEnv->NewGlobalRef(clazz)) == NULL))
+        return NS_ERROR_FAILURE;
+
+    *result = NULL;
 #if PROXY_JNI_CALLS
     AllocObjectMessage msg(clazz, result);
  	sendMessageToJava(&msg);
 #else
     *result = mJavaEnv->AllocObject(clazz);
 #endif
 
+    javaEnv->DeleteGlobalRef(clazz);
     return NS_OK;
 }
 
 class GetObjectClassMessage : public JavaMessage {
     jobject obj;
 	jclass* result;
 public:
 	GetObjectClassMessage(jobject obj, jclass* result)
 	{
 		this->obj = obj;
@@ -1831,30 +2774,39 @@
 		*result = env->GetObjectClass(obj);
 #if LOCAL_REFS_ARE_GLOBAL
         *result = (jclass) ToGlobalRef(env, *result);
 #endif
 	}
 };
 
 NS_IMETHODIMP CSecureEnv::GetObjectClass(/*[in]*/  jobject obj,
                                           /*[out]*/ jclass* result) 
 {
-    if (mJavaEnv == NULL || result == NULL)
+    if (mJavaEnv == NULL || obj == NULL || result == NULL)
         return NS_ERROR_NULL_POINTER;
-    
+    /* http://java.sun.com/j2se/1.4.2/docs/guide/jni/jni-12.html's 2001
+     * "clarification" says that NewGlobalRef() and NewLocalRef() return NULL
+     * if the object they're called on has been freed.
+     */
+    JNIEnv *javaEnv = mSession->getCurrentEnv();
+    if (!javaEnv || ((obj = javaEnv->NewGlobalRef(obj)) == NULL))
+        return NS_ERROR_FAILURE;
+
+    *result = NULL;
 #if PROXY_JNI_CALLS
     GetObjectClassMessage msg(obj, result);
  	sendMessageToJava(&msg);
 #else
     *result = mJavaEnv->GetObjectClass(obj);
 #endif
 
+    javaEnv->DeleteGlobalRef(obj);
     return NS_OK;
 }
 
 
 class IsInstanceOfMessage : public JavaMessage {
     jobject obj;
     jclass clazz;
 	jboolean* result;
 public:
 	IsInstanceOfMessage(jobject obj, jclass clazz, jboolean* result)
@@ -1867,30 +2819,44 @@
 	virtual void execute(JNIEnv* env)
 	{
 		*result = env->IsInstanceOf(obj, clazz);
 	}
 };
 
 NS_IMETHODIMP CSecureEnv::IsInstanceOf(/*[in]*/  jobject obj,
                                         /*[in]*/  jclass clazz,
                                         /*[out]*/ jboolean* result) 
 {
-    if (mJavaEnv == NULL || result == NULL)
+    if (mJavaEnv == NULL || obj == NULL || clazz == NULL || result == NULL)
         return NS_ERROR_NULL_POINTER;
-    
+    /* http://java.sun.com/j2se/1.4.2/docs/guide/jni/jni-12.html's 2001
+     * "clarification" says that NewGlobalRef() and NewLocalRef() return NULL
+     * if the object they're called on has been freed.
+     */
+    JNIEnv *javaEnv = mSession->getCurrentEnv();
+    if (!javaEnv || ((obj = javaEnv->NewGlobalRef(obj)) == NULL))
+        return NS_ERROR_FAILURE;
+    if ((clazz = (jclass) javaEnv->NewGlobalRef(clazz)) == NULL) {
+        javaEnv->DeleteGlobalRef(obj);
+        return NS_ERROR_FAILURE;
+    }
+
+    *result = false;
 #if PROXY_JNI_CALLS
     IsInstanceOfMessage msg(obj, clazz, result);
  	sendMessageToJava(&msg);
 #else
     *result = mJavaEnv->IsInstanceOf(obj, clazz);
 #endif
 
+    javaEnv->DeleteGlobalRef(obj);
+    javaEnv->DeleteGlobalRef(clazz);
     return NS_OK;
 }
 
 class GetMethodIDMessage : public JavaMessage {
     jclass clazz;
     const char* name;
     const char* sig;
     jboolean isStatic;
 	jmethodID* result;
 public:
@@ -1933,87 +2899,123 @@
 		*result = (isStatic ? env->GetStaticFieldID(clazz, name, sig)
 		                    : env->GetFieldID(clazz, name, sig));
 	}
 };
 
 NS_IMETHODIMP CSecureEnv::GetMethodID(/*[in]*/  jclass clazz, 
                                        /*[in]*/  const char* name,
                                        /*[in]*/  const char* sig,
                                        /*[out]*/ jmethodID* result) 
 {
-    if (result == NULL)
+    if (clazz == NULL || name == NULL || sig == NULL || result == NULL)
         return NS_ERROR_NULL_POINTER;
+    /* http://java.sun.com/j2se/1.4.2/docs/guide/jni/jni-12.html's 2001
+     * "clarification" says that NewGlobalRef() and NewLocalRef() return NULL
+     * if the object they're called on has been freed.
+     */
+    JNIEnv *javaEnv = mSession->getCurrentEnv();
+    if (!javaEnv || ((clazz = (jclass) javaEnv->NewGlobalRef(clazz)) == NULL))
+        return NS_ERROR_FAILURE;
 
+    *result = NULL;
 #if PROXY_JNI_CALLS
     GetMethodIDMessage msg(clazz, name, sig, JNI_FALSE, result);
  	sendMessageToJava(&msg);
 #else
     *result = mJavaEnv->GetMethodID(clazz, name, sig);
 #endif
 
+    javaEnv->DeleteGlobalRef(clazz);
     return NS_OK;
 }
 
 
 NS_IMETHODIMP CSecureEnv::GetFieldID(/*[in]*/  jclass clazz, 
                                       /*[in]*/  const char* name,
                                       /*[in]*/  const char* sig,
                                       /*[out]*/ jfieldID* result) 
 {
-    if (result == NULL)
+    if (clazz == NULL || name == NULL || sig == NULL || result == NULL)
         return NS_ERROR_NULL_POINTER;
-    
+    /* http://java.sun.com/j2se/1.4.2/docs/guide/jni/jni-12.html's 2001
+     * "clarification" says that NewGlobalRef() and NewLocalRef() return NULL
+     * if the object they're called on has been freed.
+     */
+    JNIEnv *javaEnv = mSession->getCurrentEnv();
+    if (!javaEnv || ((clazz = (jclass) javaEnv->NewGlobalRef(clazz)) == NULL))
+        return NS_ERROR_FAILURE;
+
+    *result = NULL;
 #if PROXY_JNI_CALLS
     GetFieldIDMessage msg(clazz, name, sig, JNI_FALSE, result);
  	sendMessageToJava(&msg);
 #else
     *result = mJavaEnv->GetFieldID(clazz, name, sig);
 #endif
 
+    javaEnv->DeleteGlobalRef(clazz);
     return NS_OK;
 }
 
 
 NS_IMETHODIMP CSecureEnv::GetStaticMethodID(/*[in]*/  jclass clazz, 
                                              /*[in]*/  const char* name,
                                              /*[in]*/  const char* sig,
                                              /*[out]*/ jmethodID* result)
 {
-    if (result == NULL)
+    if (clazz == NULL || name == NULL || sig == NULL || result == NULL)
         return NS_ERROR_NULL_POINTER;
-    
+    /* http://java.sun.com/j2se/1.4.2/docs/guide/jni/jni-12.html's 2001
+     * "clarification" says that NewGlobalRef() and NewLocalRef() return NULL
+     * if the object they're called on has been freed.
+     */
+    JNIEnv *javaEnv = mSession->getCurrentEnv();
+    if (!javaEnv || ((clazz = (jclass) javaEnv->NewGlobalRef(clazz)) == NULL))
+        return NS_ERROR_FAILURE;
+
+    *result = NULL;
 #if PROXY_JNI_CALLS
     GetMethodIDMessage msg(clazz, name, sig, JNI_TRUE, result);
  	sendMessageToJava(&msg);
 #else
     *result = mJavaEnv->GetStaticMethodID(clazz, name, sig);
 #endif
 
+    javaEnv->DeleteGlobalRef(clazz);
     return NS_OK;
 }
 
 
 NS_IMETHODIMP CSecureEnv::GetStaticFieldID(/*[in]*/  jclass clazz, 
                                             /*[in]*/  const char* name,
                                             /*[in]*/  const char* sig,
                                             /*[out]*/ jfieldID* result) 
 {
-    if (result == NULL)
+    if (clazz == NULL || name == NULL || sig == NULL || result == NULL)
         return NS_ERROR_NULL_POINTER;
-    
+    /* http://java.sun.com/j2se/1.4.2/docs/guide/jni/jni-12.html's 2001
+     * "clarification" says that NewGlobalRef() and NewLocalRef() return NULL
+     * if the object they're called on has been freed.
+     */
+    JNIEnv *javaEnv = mSession->getCurrentEnv();
+    if (!javaEnv || ((clazz = (jclass) javaEnv->NewGlobalRef(clazz)) == NULL))
+        return NS_ERROR_FAILURE;
+
+    *result = NULL;
 #if PROXY_JNI_CALLS
     GetFieldIDMessage msg(clazz, name, sig, JNI_TRUE, result);
  	sendMessageToJava(&msg);
 #else
     *result = mJavaEnv->GetStaticFieldID(clazz, name, sig);
 #endif
 
+    javaEnv->DeleteGlobalRef(clazz);
     return NS_OK;
 }
 
 /**
  * To give proper "local" refs, need to run this in the true thread.
  */
 
 class NewStringMessage : public JavaMessage {
 	const jchar* unicode;
 	jsize len;
@@ -2035,20 +3037,21 @@
 	}
 };
 
 NS_IMETHODIMP CSecureEnv::NewString(/*[in]*/  const jchar* unicode,
                                      /*[in]*/  jsize len,
                                      /*[out]*/ jstring* result) 
 {
     if (result == NULL)
         return NS_ERROR_NULL_POINTER;
 
+    *result = NULL;
 #if PROXY_JNI_CALLS    
     NewStringMessage msg(unicode, len, result);
     sendMessageToJava(&msg);
 #else
 	*result = mJavaEnv->NewString(unicode, len);
 #endif
 
     return NS_OK;
 }
 
@@ -2064,30 +3067,39 @@
 
 	virtual void execute(JNIEnv* env)
 	{
     	*result = env->GetStringLength(str);
 	}
 };
 
 NS_IMETHODIMP CSecureEnv::GetStringLength(/*[in]*/  jstring str,
                                            /*[out]*/ jsize* result) 
 {
-    if (mJavaEnv == NULL || result == NULL)
+    if (mJavaEnv == NULL || str == NULL || result == NULL)
         return NS_ERROR_NULL_POINTER;
+    /* http://java.sun.com/j2se/1.4.2/docs/guide/jni/jni-12.html's 2001
+     * "clarification" says that NewGlobalRef() and NewLocalRef() return NULL
+     * if the object they're called on has been freed.
+     */
+    JNIEnv *javaEnv = mSession->getCurrentEnv();
+    if (!javaEnv || ((str = (jstring) javaEnv->NewGlobalRef(str)) == NULL))
+        return NS_ERROR_FAILURE;
 
+    *result = 0;
 #if PROXY_JNI_CALLS    
     GetStringLengthMessage msg(str, result);
     sendMessageToJava(&msg);
 #else
     *result = mJavaEnv->GetStringLength(str);
 #endif
 
+    javaEnv->DeleteGlobalRef(str);
     return NS_OK;
 }
 
 class GetStringCharsMessage : public JavaMessage {
 	jstring str;
 	jboolean* isCopy;
 	const jchar** result;
 public:
 	GetStringCharsMessage(jstring str, jboolean* isCopy, const jchar** result)
 	{
@@ -2099,30 +3111,39 @@
 	virtual void execute(JNIEnv* env)
 	{
     	*result = env->GetStringChars(str, isCopy);
 	}
 };
 
 NS_IMETHODIMP CSecureEnv::GetStringChars(/*[in]*/  jstring str,
                                           /*[in]*/  jboolean *isCopy,
                                           /*[out]*/ const jchar** result) 
 {
-    if (mJavaEnv == NULL || result == NULL)
+    if (mJavaEnv == NULL || str == NULL || result == NULL)
         return NS_ERROR_NULL_POINTER;
-    
+    /* http://java.sun.com/j2se/1.4.2/docs/guide/jni/jni-12.html's 2001
+     * "clarification" says that NewGlobalRef() and NewLocalRef() return NULL
+     * if the object they're called on has been freed.
+     */
+    JNIEnv *javaEnv = mSession->getCurrentEnv();
+    if (!javaEnv || ((str = (jstring) javaEnv->NewGlobalRef(str)) == NULL))
+        return NS_ERROR_FAILURE;
+
+    *result = NULL;
 #if PROXY_JNI_CALLS    
     GetStringCharsMessage msg(str, isCopy, result);
     sendMessageToJava(&msg);
 #else
     *result = mJavaEnv->GetStringChars(str, isCopy);
 #endif
 
+    javaEnv->DeleteGlobalRef(str);
     return NS_OK;
 }
 
 
 class ReleaseStringCharsMessage : public JavaMessage {
 	jstring str;
 	const jchar* chars;
 public:
 	ReleaseStringCharsMessage(jstring str, const jchar* chars)
 	{
@@ -2132,30 +3153,38 @@
 
 	virtual void execute(JNIEnv* env)
 	{
     	env->ReleaseStringChars(str, chars);
 	}
 };
 
 NS_IMETHODIMP CSecureEnv::ReleaseStringChars(/*[in]*/  jstring str,
                                               /*[in]*/  const jchar *chars) 
 {
-    if (mJavaEnv == NULL)
+    if (mJavaEnv == NULL || str == NULL || chars == NULL)
         return NS_ERROR_NULL_POINTER;
+    /* http://java.sun.com/j2se/1.4.2/docs/guide/jni/jni-12.html's 2001
+     * "clarification" says that NewGlobalRef() and NewLocalRef() return NULL
+     * if the object they're called on has been freed.
+     */
+    JNIEnv *javaEnv = mSession->getCurrentEnv();
+    if (!javaEnv || ((str = (jstring) javaEnv->NewGlobalRef(str)) == NULL))
+        return NS_ERROR_FAILURE;
     
 #if PROXY_JNI_CALLS    
     ReleaseStringCharsMessage msg(str, chars);
     sendMessageToJava(&msg);
 #else
     mJavaEnv->ReleaseStringChars(str, chars);
 #endif
 
+    javaEnv->DeleteGlobalRef(str);
     return NS_OK;
 }
 
 class NewStringUTFMessage : public JavaMessage {
 	const char *utf;
 	jstring* result;
 public:
 	NewStringUTFMessage(const char *utf, jstring* result)
 	{
 		this->utf = utf;
@@ -2169,21 +3198,22 @@
         *result = (jstring) ToGlobalRef(env, *result);
 #endif
 	}
 };
 
 NS_IMETHODIMP CSecureEnv::NewStringUTF(/*[in]*/  const char *utf,
                                         /*[out]*/ jstring* result) 
 {
     if (mJavaEnv == NULL || result == NULL)
         return NS_ERROR_NULL_POINTER;
-    
+
+	*result = NULL;
 #if PROXY_JNI_CALLS    
 	NewStringUTFMessage msg(utf, result);
     sendMessageToJava(&msg);
 #else
 	*result = mJavaEnv->NewStringUTF(utf);
 #endif
 
     return NS_OK;
 }
 
@@ -2200,30 +3230,39 @@
 
 	virtual void execute(JNIEnv* env)
 	{
     	*result = env->GetStringUTFLength(str);
 	}
 };
 
 NS_IMETHODIMP CSecureEnv::GetStringUTFLength(/*[in]*/  jstring str,
                                               /*[out]*/ jsize* result) 
 {
-    if (mJavaEnv == NULL || result == NULL)
+    if (mJavaEnv == NULL || str == NULL || result == NULL)
         return NS_ERROR_NULL_POINTER;
-    
+    /* http://java.sun.com/j2se/1.4.2/docs/guide/jni/jni-12.html's 2001
+     * "clarification" says that NewGlobalRef() and NewLocalRef() return NULL
+     * if the object they're called on has been freed.
+     */
+    JNIEnv *javaEnv = mSession->getCurrentEnv();
+    if (!javaEnv || ((str = (jstring) javaEnv->NewGlobalRef(str)) == NULL))
+        return NS_ERROR_FAILURE;
+
+	*result = 0;
 #if PROXY_JNI_CALLS    
 	GetStringUTFLengthMessage msg(str, result);
     sendMessageToJava(&msg);
 #else
     *result = mJavaEnv->GetStringUTFLength(str);
 #endif
 
+    javaEnv->DeleteGlobalRef(str);
     return NS_OK;
 }
 
     
 class GetStringUTFCharsMessage : public JavaMessage {
 	jstring str;
 	jboolean* isCopy;
 	const char** result;
 public:
 	GetStringUTFCharsMessage(jstring str, jboolean* isCopy, const char** result)
@@ -2236,30 +3275,39 @@
 	virtual void execute(JNIEnv* env)
 	{
     	*result = env->GetStringUTFChars(str, isCopy);
 	}
 };
 
 NS_IMETHODIMP CSecureEnv::GetStringUTFChars(/*[in]*/  jstring str,
                                              /*[in]*/  jboolean *isCopy,
                                              /*[out]*/ const char** result) 
 {
-    if (mJavaEnv == NULL || result == NULL)
+    if (mJavaEnv == NULL || str == NULL || result == NULL)
         return NS_ERROR_NULL_POINTER;
-    
+    /* http://java.sun.com/j2se/1.4.2/docs/guide/jni/jni-12.html's 2001
+     * "clarification" says that NewGlobalRef() and NewLocalRef() return NULL
+     * if the object they're called on has been freed.
+     */
+    JNIEnv *javaEnv = mSession->getCurrentEnv();
+    if (!javaEnv || ((str = (jstring) javaEnv->NewGlobalRef(str)) == NULL))
+        return NS_ERROR_FAILURE;
+
+	*result = NULL;
 #if PROXY_JNI_CALLS    
 	GetStringUTFCharsMessage msg(str, isCopy, result);
     sendMessageToJava(&msg);
 #else
     *result = mJavaEnv->GetStringUTFChars(str, isCopy);
 #endif
 
+    javaEnv->DeleteGlobalRef(str);
     return NS_OK;
 }
 
 
 class ReleaseStringUTFCharsMessage : public JavaMessage {
 	jstring str;
 	const char* chars;
 public:
 	ReleaseStringUTFCharsMessage(jstring str, const char* chars)
 	{
@@ -2269,30 +3317,38 @@
 
 	virtual void execute(JNIEnv* env)
 	{
     	env->ReleaseStringUTFChars(str, chars);
 	}
 };
 
 NS_IMETHODIMP CSecureEnv::ReleaseStringUTFChars(/*[in]*/  jstring str,
                                                  /*[in]*/  const char *chars) 
 {
-    if (mJavaEnv == NULL)
+    if (mJavaEnv == NULL || str == NULL || chars == NULL)
         return NS_ERROR_NULL_POINTER;
-    
+    /* http://java.sun.com/j2se/1.4.2/docs/guide/jni/jni-12.html's 2001
+     * "clarification" says that NewGlobalRef() and NewLocalRef() return NULL
+     * if the object they're called on has been freed.
+     */
+    JNIEnv *javaEnv = mSession->getCurrentEnv();
+    if (!javaEnv || ((str = (jstring) javaEnv->NewGlobalRef(str)) == NULL))
+        return NS_ERROR_FAILURE;
+
 #if PROXY_JNI_CALLS    
 	ReleaseStringUTFCharsMessage msg(str, chars);
     sendMessageToJava(&msg);
 #else
     mJavaEnv->ReleaseStringUTFChars(str, chars);
 #endif
 
+    javaEnv->DeleteGlobalRef(str);
     return NS_OK;
 }
 
 
 class GetArrayLengthMessage : public JavaMessage {
 	jarray array;
 	jsize* result;
 public:
 	GetArrayLengthMessage(jarray array, jsize* result)
 	{
@@ -2302,30 +3358,39 @@
 
 	virtual void execute(JNIEnv* env)
 	{
     	*result = env->GetArrayLength(array);
 	}
 };
 
 NS_IMETHODIMP CSecureEnv::GetArrayLength(/*[in]*/  jarray array,
                                          /*[out]*/ jsize* result) 
 {
-    if (mJavaEnv == NULL || result == NULL)
+    if (mJavaEnv == NULL || array == NULL || result == NULL)
         return NS_ERROR_NULL_POINTER;
-    
+    /* http://java.sun.com/j2se/1.4.2/docs/guide/jni/jni-12.html's 2001
+     * "clarification" says that NewGlobalRef() and NewLocalRef() return NULL
+     * if the object they're called on has been freed.
+     */
+    JNIEnv *javaEnv = mSession->getCurrentEnv();
+    if (!javaEnv || ((array = (jarray) javaEnv->NewGlobalRef(array)) == NULL))
+        return NS_ERROR_FAILURE;
+
+	*result = 0;
 #if PROXY_JNI_CALLS    
 	GetArrayLengthMessage msg(array, result);
     sendMessageToJava(&msg);
 #else
     *result = mJavaEnv->GetArrayLength(array);
 #endif
 
+    javaEnv->DeleteGlobalRef(array);
     return NS_OK;
 }
 
 class NewObjectArrayMessage : public JavaMessage {
     jsize len;
 	jclass clazz;
 	jobject init;
 	jobjectArray* result;
 public:
 	NewObjectArrayMessage(jsize len, jclass clazz, jobject init, jobjectArray* result)
@@ -2343,30 +3408,39 @@
         *result = (jobjectArray) ToGlobalRef(env, *result);
 #endif
 	}
 };
 
 NS_IMETHODIMP CSecureEnv::NewObjectArray(/*[in]*/  jsize len,
 										 /*[in]*/  jclass clazz,
 					                     /*[in]*/  jobject init,
 					                     /*[out]*/ jobjectArray* result)
 {
-    if (mJavaEnv == NULL || result == NULL)
+    if (mJavaEnv == NULL || clazz == NULL || result == NULL)
         return NS_ERROR_NULL_POINTER;
+    /* http://java.sun.com/j2se/1.4.2/docs/guide/jni/jni-12.html's 2001
+     * "clarification" says that NewGlobalRef() and NewLocalRef() return NULL
+     * if the object they're called on has been freed.
+     */
+    JNIEnv *javaEnv = mSession->getCurrentEnv();
+    if (!javaEnv || ((clazz = (jclass) javaEnv->NewGlobalRef(clazz)) == NULL))
+        return NS_ERROR_FAILURE;
 
+	*result = NULL;
 #if PROXY_JNI_CALLS    
 	NewObjectArrayMessage msg(len, clazz, init, result);
     sendMessageToJava(&msg);
 #else
     *result = mJavaEnv->NewObjectArray(len, clazz, init);
 #endif
 
+    javaEnv->DeleteGlobalRef(clazz);
     return NS_OK;
 }
 
 class GetObjectArrayElementMessage : public JavaMessage {
 	jobjectArray array;
 	jsize index;
 	jobject* result;
 public:
 	GetObjectArrayElementMessage(jobjectArray array, jsize index, jobject* result)
 	{
@@ -2381,30 +3455,39 @@
 #if LOCAL_REFS_ARE_GLOBAL
         *result = ToGlobalRef(env, *result);
 #endif
 	}
 };
 
 NS_IMETHODIMP CSecureEnv::GetObjectArrayElement(/*[in]*/  jobjectArray array,
                                                  /*[in]*/  jsize index,
                                                  /*[out]*/ jobject* result)
 {
-    if (mJavaEnv == NULL || result == NULL)
+    if (mJavaEnv == NULL || array == NULL || result == NULL)
         return NS_ERROR_NULL_POINTER;
+    /* http://java.sun.com/j2se/1.4.2/docs/guide/jni/jni-12.html's 2001
+     * "clarification" says that NewGlobalRef() and NewLocalRef() return NULL
+     * if the object they're called on has been freed.
+     */
+    JNIEnv *javaEnv = mSession->getCurrentEnv();
+    if (!javaEnv || ((array = (jobjectArray) javaEnv->NewGlobalRef(array)) == NULL))
+        return NS_ERROR_FAILURE;
 
+	*result = NULL;
 #if PROXY_JNI_CALLS    
 	GetObjectArrayElementMessage msg(array, index, result);
     sendMessageToJava(&msg);
 #else
     *result = mJavaEnv->GetObjectArrayElement(array, index);
 #endif
 
+    javaEnv->DeleteGlobalRef(array);
     return NS_OK;
 }
 
 
 class SetObjectArrayElementMessage : public JavaMessage {
 	jobjectArray array;
 	jsize index;
 	jobject val;
 public:
 	SetObjectArrayElementMessage(jobjectArray array, jsize index, jobject val)
@@ -2417,30 +3500,38 @@
 	virtual void execute(JNIEnv* env)
 	{
         env->SetObjectArrayElement(array, index, val);
 	}
 };
 
 NS_IMETHODIMP CSecureEnv::SetObjectArrayElement(/*[in]*/  jobjectArray array,
                                                  /*[in]*/  jsize index,
                                                  /*[in]*/  jobject val) 
 {
-    if (mJavaEnv == NULL)
+    if (mJavaEnv == NULL || array == NULL)
         return NS_ERROR_NULL_POINTER;
+    /* http://java.sun.com/j2se/1.4.2/docs/guide/jni/jni-12.html's 2001
+     * "clarification" says that NewGlobalRef() and NewLocalRef() return NULL
+     * if the object they're called on has been freed.
+     */
+    JNIEnv *javaEnv = mSession->getCurrentEnv();
+    if (!javaEnv || ((array = (jobjectArray) javaEnv->NewGlobalRef(array)) == NULL))
+        return NS_ERROR_FAILURE;
 
 #if PROXY_JNI_CALLS    
 	SetObjectArrayElementMessage msg(array, index, val);
     sendMessageToJava(&msg);
 #else
     mJavaEnv->SetObjectArrayElement(array, index, val);
 #endif
 
+    javaEnv->DeleteGlobalRef(array);
     return NS_OK;
 }
 
 class NewArrayMessage : public JavaMessage {
 	jni_type element_type;
 	jsize len;
 	jarray* result;
 public:
 	NewArrayMessage(jni_type element_type, jsize len, jarray* result)
 	{
@@ -2485,20 +3576,21 @@
 	}
 };
 
 NS_IMETHODIMP CSecureEnv::NewArray(/*[in]*/ jni_type element_type,
                         			/*[in]*/  jsize len,
                         			/*[out]*/ jarray* result) 
 {
     if (mJavaEnv == NULL || result == NULL)
         return NS_ERROR_NULL_POINTER;
 
+	*result = NULL;
 #if PROXY_JNI_CALLS    
 	NewArrayMessage msg(element_type, len, result);
     sendMessageToJava(&msg);
 #else
     JNIEnv* env = mJavaEnv;
     switch (element_type) {
     case jboolean_type:
         *result = env->NewBooleanArray(len);
         break;
     case jbyte_type:
@@ -2575,23 +3667,31 @@
     	    *(void**)result = NULL;
     	}
 	}
 };
 
 NS_IMETHODIMP CSecureEnv::GetArrayElements(/*[in]*/  jni_type element_type,
                                            /*[in]*/  jarray array,
                                            /*[in]*/  jboolean *isCopy,
                                            /*[out]*/ void* result)
 {
-    if (mJavaEnv == NULL || result == NULL)
+    if (mJavaEnv == NULL || array == NULL || result == NULL)
         return NS_ERROR_NULL_POINTER;
+    /* http://java.sun.com/j2se/1.4.2/docs/guide/jni/jni-12.html's 2001
+     * "clarification" says that NewGlobalRef() and NewLocalRef() return NULL
+     * if the object they're called on has been freed.
+     */
+    JNIEnv *javaEnv = mSession->getCurrentEnv();
+    if (!javaEnv || ((array = (jarray) javaEnv->NewGlobalRef(array)) == NULL))
+        return NS_ERROR_FAILURE;
 
+    *(void **)result = NULL;
 #if PROXY_JNI_CALLS
     GetArrayElementsMessage msg(element_type, array, isCopy, result);
     sendMessageToJava(&msg);
 #else
     JNIEnv* env = mJavaEnv;
     switch (element_type) {
 	case jboolean_type:
 	    *(jboolean**) result = env->GetBooleanArrayElements((jbooleanArray)array, isCopy);
 	    break;
 	case jbyte_type:
@@ -2613,20 +3713,21 @@
 	    * (jfloat**) result = env->GetFloatArrayElements((jfloatArray)array, isCopy);
 	    break;
 	case jdouble_type:
 	    * (jdouble**) result = env->GetDoubleArrayElements((jdoubleArray)array, isCopy);
 	    break;
 	default:
 	    *(void**)result = NULL;
 	}
 #endif
 
+    javaEnv->DeleteGlobalRef(array);
     return NS_OK;
 }
 
 
 class ReleaseArrayElementsMessage : public JavaMessage {
 	jni_type element_type;
 	jarray array;
 	void* elems;
 	jint mode;
 public:
@@ -2658,31 +3759,41 @@
     		break;
     	case jlong_type:
     		env->ReleaseLongArrayElements((jlongArray)array, (jlong*)elems, mode);
     		break;
     	case jfloat_type:
     		env->ReleaseFloatArrayElements((jfloatArray)array, (jfloat*)elems, mode);
     		break;
     	case jdouble_type:
     		env->ReleaseDoubleArrayElements((jdoubleArray)array, (jdouble*)elems, mode);
     		break;
+        case jobject_type:
+        case jvoid_type:
+            break;
     	}
 	}
 };
 
 NS_IMETHODIMP CSecureEnv::ReleaseArrayElements(/*[in]*/ jni_type element_type,
                                                 /*[in]*/ jarray array,
                                                 /*[in]*/ void *elems,
                                                 /*[in]*/ jint mode) 
 {
-	if (mJavaEnv == NULL)
+	if (mJavaEnv == NULL || array == NULL || elems == NULL)
 		return NS_ERROR_NULL_POINTER;
+    /* http://java.sun.com/j2se/1.4.2/docs/guide/jni/jni-12.html's 2001
+     * "clarification" says that NewGlobalRef() and NewLocalRef() return NULL
+     * if the object they're called on has been freed.
+     */
+    JNIEnv *javaEnv = mSession->getCurrentEnv();
+    if (!javaEnv || ((array = (jarray) javaEnv->NewGlobalRef(array)) == NULL))
+        return NS_ERROR_FAILURE;
 	
 #if PROXY_JNI_CALLS
     ReleaseArrayElementsMessage msg(element_type, array, elems, mode);
     sendMessageToJava(&msg);
 #else
 	JNIEnv* env = mJavaEnv;
 	switch (element_type) {
 	case jboolean_type:
 		env->ReleaseBooleanArrayElements((jbooleanArray)array, (jboolean*)elems, mode);
 		break;
@@ -2700,23 +3811,27 @@
 		break;
 	case jlong_type:
 		env->ReleaseLongArrayElements((jlongArray)array, (jlong*)elems, mode);
 		break;
 	case jfloat_type:
 		env->ReleaseFloatArrayElements((jfloatArray)array, (jfloat*)elems, mode);
 		break;
 	case jdouble_type:
 		env->ReleaseDoubleArrayElements((jdoubleArray)array, (jdouble*)elems, mode);
 		break;
+    case jobject_type:
+    case jvoid_type:
+        break;
 	}
 #endif
 
+    javaEnv->DeleteGlobalRef(array);
     return NS_OK;
 }
 
 class GetArrayRegionMessage : public JavaMessage {
 	jni_type element_type;
 	jarray array;
 	jsize start;
 	jsize len;
 	void* buf;
 public:
@@ -2749,33 +3864,71 @@
             break;
         case jlong_type:
             env->GetLongArrayRegion((jlongArray)array, start, len, (jlong*)buf);
             break;
         case jfloat_type:
             env->GetFloatArrayRegion((jfloatArray)array, start, len, (jfloat*)buf);
             break;
         case jdouble_type:
             env->GetDoubleArrayRegion((jdoubleArray)array, start, len, (jdouble*)buf);
             break;
+        case jobject_type:
+        case jvoid_type:
+            break;
         }
 	}
 };
 
 NS_IMETHODIMP CSecureEnv::GetArrayRegion(/*[in]*/  jni_type element_type,
                                          /*[in]*/  jarray array,
                                          /*[in]*/  jsize start,
                                          /*[in]*/  jsize len,
                                          /*[out]*/ void* buf)
 {
-    if (mJavaEnv == NULL || buf == NULL)
+    if (mJavaEnv == NULL || array == NULL || buf == NULL)
         return NS_ERROR_NULL_POINTER;
+    /* http://java.sun.com/j2se/1.4.2/docs/guide/jni/jni-12.html's 2001
+     * "clarification" says that NewGlobalRef() and NewLocalRef() return NULL
+     * if the object they're called on has been freed.
+     */
+    JNIEnv *javaEnv = mSession->getCurrentEnv();
+    if (!javaEnv || ((array = (jarray) javaEnv->NewGlobalRef(array)) == NULL))
+        return NS_ERROR_FAILURE;
 
+    switch (element_type) {
+    case jboolean_type:
+        *(jboolean *)buf = false;
+        break;
+    case jbyte_type:
+        *(jbyte *)buf = 0;
+        break;
+    case jchar_type:
+        *(jchar *)buf = 0;
+        break;
+    case jshort_type:
+        *(jshort *)buf = 0;
+        break;
+    case jint_type:
+        *(jint *)buf = 0;
+        break;
+    case jlong_type:
+        *(jlong *)buf = 0;
+        break;
+    case jfloat_type:
+        *(jfloat *)buf = 0;
+        break;
+    case jdouble_type:
+        *(jdouble *)buf = 0;
+        break;
+    default:
+        break;
+    }
 #if PROXY_JNI_CALLS
     GetArrayRegionMessage msg(element_type, array, start, len, buf);
     sendMessageToJava(&msg);
 #else
     JNIEnv* env = mJavaEnv;
     switch (element_type) {
     case jboolean_type:
         env->GetBooleanArrayRegion((jbooleanArray)array, start, len, (jboolean*)buf);
         break;
     case jbyte_type:
@@ -2797,20 +3950,21 @@
         env->GetFloatArrayRegion((jfloatArray)array, start, len, (jfloat*)buf);
         break;
     case jdouble_type:
         env->GetDoubleArrayRegion((jdoubleArray)array, start, len, (jdouble*)buf);
         break;
     default:
         return NS_ERROR_FAILURE;
     }
 #endif
 
+    javaEnv->DeleteGlobalRef(array);
     return NS_OK;
 }
 
 
 class SetArrayRegionMessage : public JavaMessage {
 	jni_type element_type;
 	jarray array;
 	jsize start;
 	jsize len;
 	void* buf;
@@ -2844,32 +3998,42 @@
             break;
         case jlong_type:
             env->SetLongArrayRegion((jlongArray)array, start, len, (jlong*)buf);
             break;
         case jfloat_type:
             env->SetFloatArrayRegion((jfloatArray)array, start, len, (jfloat*)buf);
             break;
         case jdouble_type:
             env->SetDoubleArrayRegion((jdoubleArray)array, start, len, (jdouble*)buf);
             break;
+        case jobject_type:
+        case jvoid_type:
+            break;
         }
 	}
 };
 
 NS_IMETHODIMP CSecureEnv::SetArrayRegion(/*[in]*/  jni_type element_type,
                                          /*[in]*/  jarray array,
                                          /*[in]*/  jsize start,
                                          /*[in]*/  jsize len,
                                          /*[in]*/  void* buf)
 {
-    if (mJavaEnv == NULL || buf == NULL)
+    if (mJavaEnv == NULL || array == NULL || buf == NULL)
         return NS_ERROR_NULL_POINTER;
+    /* http://java.sun.com/j2se/1.4.2/docs/guide/jni/jni-12.html's 2001
+     * "clarification" says that NewGlobalRef() and NewLocalRef() return NULL
+     * if the object they're called on has been freed.
+     */
+    JNIEnv *javaEnv = mSession->getCurrentEnv();
+    if (!javaEnv || ((array = (jarray) javaEnv->NewGlobalRef(array)) == NULL))
+        return NS_ERROR_FAILURE;
 
 #if PROXY_JNI_CALLS
     SetArrayRegionMessage msg(element_type, array, start, len, buf);
     sendMessageToJava(&msg);
 #else
     JNIEnv* env = mJavaEnv;
     switch (type) {
     case jboolean_type:
         env->SetBooleanArrayRegion((jbooleanArray)array, start, len, (jboolean*)buf);
         break;
@@ -2892,20 +4056,21 @@
         env->SetFloatArrayRegion((jfloatArray)array, start, len, (jfloat*)buf);
         break;
     case jdouble_type:
         env->SetDoubleArrayRegion((jdoubleArray)array, start, len, (jdouble*)buf);
         break;
     default:
         return NS_ERROR_FAILURE;
     }
 #endif
 
+    javaEnv->DeleteGlobalRef(array);
     return NS_OK;
 }
 
 
 class RegisterNativesMessage : public JavaMessage {
 	jclass clazz;
 	const JNINativeMethod *methods;
 	jint nMethods;
 	jint* result;
 public:
@@ -2921,30 +4086,39 @@
 	{
     	*result = env->RegisterNatives(clazz, methods, nMethods);
 	}
 };
 
 NS_IMETHODIMP CSecureEnv::RegisterNatives(/*[in]*/  jclass clazz,
                                            /*[in]*/  const JNINativeMethod *methods,
                                            /*[in]*/  jint nMethods,
                                            /*[out]*/ jint* result) 
 {
-    if (mJavaEnv == NULL || result == NULL)
+    if (mJavaEnv == NULL || clazz == NULL || methods == NULL || result == NULL)
         return NS_ERROR_NULL_POINTER;
+    /* http://java.sun.com/j2se/1.4.2/docs/guide/jni/jni-12.html's 2001
+     * "clarification" says that NewGlobalRef() and NewLocalRef() return NULL
+     * if the object they're called on has been freed.
+     */
+    JNIEnv *javaEnv = mSession->getCurrentEnv();
+    if (!javaEnv || ((clazz = (jclass) javaEnv->NewGlobalRef(clazz)) == NULL))
+        return NS_ERROR_FAILURE;
 
+    *result = -1;
 #if PROXY_JNI_CALLS
     RegisterNativesMessage msg(clazz, methods, nMethods, result);
     sendMessageToJava(&msg);
 #else
     *result = mJavaEnv->RegisterNatives(clazz, methods, nMethods);
 #endif
 
+    javaEnv->DeleteGlobalRef(clazz);
     return NS_OK;
 }
 
 
 class UnregisterNativesMessage : public JavaMessage {
 	jclass clazz;
 	jint* result;
 public:
 	UnregisterNativesMessage(jclass clazz, jint* result)
 	{
@@ -2954,30 +4128,39 @@
 	
 	virtual void execute(JNIEnv* env)
 	{
     	*result = env->UnregisterNatives(clazz);
 	}
 };
 
 NS_IMETHODIMP CSecureEnv::UnregisterNatives(/*[in]*/  jclass clazz,
                                              /*[out]*/ jint* result) 
 {
-    if (mJavaEnv == NULL || result == NULL)
+    if (mJavaEnv == NULL || clazz == NULL || result == NULL)
         return NS_ERROR_NULL_POINTER;
+    /* http://java.sun.com/j2se/1.4.2/docs/guide/jni/jni-12.html's 2001
+     * "clarification" says that NewGlobalRef() and NewLocalRef() return NULL
+     * if the object they're called on has been freed.
+     */
+    JNIEnv *javaEnv = mSession->getCurrentEnv();
+    if (!javaEnv || ((clazz = (jclass) javaEnv->NewGlobalRef(clazz)) == NULL))
+        return NS_ERROR_FAILURE;
 
+    *result = -1;
 #if PROXY_JNI_CALLS
     UnregisterNativesMessage msg(clazz, result);
     sendMessageToJava(&msg);
 #else
     *result = mJavaEnv->UnregisterNatives(clazz);
 #endif
 
+    javaEnv->DeleteGlobalRef(clazz);
     return NS_OK;
 }
 
 
 class MonitorEnterMessage : public JavaMessage {
 	jobject obj;
 	jint* result;
 public:
 	MonitorEnterMessage(jobject obj, jint* result)
 	{
@@ -2987,30 +4170,39 @@
 
 	virtual void execute(JNIEnv* env)
 	{
 		*result = env->MonitorEnter(obj);
 	}
 };
 
 NS_IMETHODIMP CSecureEnv::MonitorEnter(/*[in]*/  jobject obj,
                                         /*[out]*/ jint* result) 
 {
-    if (mJavaEnv == NULL || result == NULL)
+    if (mJavaEnv == NULL || obj == NULL || result == NULL)
         return NS_ERROR_NULL_POINTER;
+    /* http://java.sun.com/j2se/1.4.2/docs/guide/jni/jni-12.html's 2001
+     * "clarification" says that NewGlobalRef() and NewLocalRef() return NULL
+     * if the object they're called on has been freed.
+     */
+    JNIEnv *javaEnv = mSession->getCurrentEnv();
+    if (!javaEnv || ((obj = javaEnv->NewGlobalRef(obj)) == NULL))
+        return NS_ERROR_FAILURE;
 
+	*result = -1;
 #if PROXY_JNI_CALLS
 	MonitorEnterMessage msg(obj, result);
 	sendMessageToJava(&msg);
 #else
 	*result = mJavaEnv->MonitorEnter(obj);
 #endif
 
+    javaEnv->DeleteGlobalRef(obj);
     return NS_OK;
 }
 
 class MonitorExitMessage : public JavaMessage {
 	jobject obj;
 	jint* result;
 public:
 	MonitorExitMessage(jobject obj, jint* result)
 	{
 		this->obj = obj;
@@ -3019,107 +4211,134 @@
 
 	virtual void execute(JNIEnv* env)
 	{
 		*result = env->MonitorExit(obj);
 	}
 };
  
 NS_IMETHODIMP CSecureEnv::MonitorExit(/*[in]*/  jobject obj,
                                        /*[out]*/ jint* result)
 {
-    if (mJavaEnv == NULL || result == NULL)
+    if (mJavaEnv == NULL || obj == NULL || result == NULL)
         return NS_ERROR_NULL_POINTER;
+    /* http://java.sun.com/j2se/1.4.2/docs/guide/jni/jni-12.html's 2001
+     * "clarification" says that NewGlobalRef() and NewLocalRef() return NULL
+     * if the object they're called on has been freed.
+     */
+    JNIEnv *javaEnv = mSession->getCurrentEnv();
+    if (!javaEnv || ((obj = javaEnv->NewGlobalRef(obj)) == NULL))
+        return NS_ERROR_FAILURE;
 
+	*result = -1;
 #if PROXY_JNI_CALLS
 	MonitorExitMessage msg(obj, result);
 	sendMessageToJava(&msg);
 #else
 	*result = mJavaEnv->MonitorExit(obj);
 #endif
 
+    javaEnv->DeleteGlobalRef(obj);
     return NS_OK;
 }
 
 NS_IMETHODIMP CSecureEnv::GetJavaVM(/*[in]*/  JavaVM **vm,
                                      /*[out]*/ jint* result)
 {
-    if (mJavaEnv == NULL || result == NULL)
+    JNIEnv* env = mSession->getCurrentEnv();
+
+    if (env == NULL || result == NULL)
         return NS_ERROR_NULL_POINTER;
 
-    *result = mJavaEnv->GetJavaVM(vm);
+    *result = env->GetJavaVM(vm);
 
     return NS_OK;
 }
 
 /**
  * Runs a message loop. Puts the message in the sendQueue, then waits on the receiveQueue for the reply.
  */
 
 void CSecureEnv::messageLoop(JNIEnv* env, JavaMessage* msg, JavaMessageQueue* sendQueue, JavaMessageQueue* receiveQueue, Boolean busyWaiting)
 {
 	// put the message in the send queue, and wait for a reply.
+	JavaMessage* replyMsg = NULL;
+	/* I've made some additions (the calls to receiveQueue->enter() and
+	 * receiveQueue->exit()) to guarantee that the "reply" isn't sent
+	 * before receiveQueue->wait() is called, which (in turn) ensures that
+	 * receiveQueue->getMessage() is always called at the "right" time.  This
+	 * helps avoid hangs in applets that make heavy use of LiveConnect -- e.g.
+	 * http://www.spurgius.com/colorpicker/colorpicker.html.
+	 */
+	receiveQueue->enter();
 	sendQueue->putMessage(msg);
 	sendQueue->notify();
-	JavaMessage* replyMsg = receiveQueue->getMessage();
 	for (;;) {
 		// Fully synchronized approach.
 		if (replyMsg != NULL) {
 			if (replyMsg == msg)
 				break;
 			// must be a message that needs executing.
 			replyMsg->execute(env);
 			sendQueue->putMessage(replyMsg);
 			sendQueue->notify();
 			// notify can cause a yield, so look again.
 			replyMsg = receiveQueue->getMessage();
 			if (replyMsg != NULL)
 				continue;
 		}
 		// when busy waiting, must give time to browser between timed waits.
 		if (busyWaiting) {
-			receiveQueue->wait(1024);
+			receiveQueue->wait(100);
 			replyMsg = receiveQueue->getMessage();
 			if (replyMsg != NULL)
 				continue;
 			// mSession->lock();
 			mThreadManager->Sleep();
 			// mSession->unlock();
 		} else {
 			// wait for a message to arrive.
 			receiveQueue->wait();
 		}
 		replyMsg = receiveQueue->getMessage();
 	}
+	receiveQueue->exit();
 }
 
+long CSecureEnv::mSuspendExceptionsLevel = 0;
+
 void CSecureEnv::savePendingException(JNIEnv* env)
 {
     // first off, always restore the env to a known state.
     jthrowable pendingException = env->ExceptionOccurred();
     if (pendingException) {
-#if USE_LIVECONNECT_PROXY    
-        env->ExceptionDescribe();
+#if USE_LIVECONNECT_PROXY
+        if (mSuspendExceptionsLevel <= 0)
+            env->ExceptionDescribe();
 #endif
         env->ExceptionClear();
-        
-        if (mPendingException)
-            env->DeleteGlobalRef(mPendingException);
-
-        mPendingException = (jthrowable) env->NewGlobalRef(pendingException);
+        if (mSuspendExceptionsLevel <= 0) {
+            if (mPendingException)
+                env->DeleteGlobalRef(mPendingException);
+            mPendingException = (jthrowable) env->NewGlobalRef(pendingException);
+        }
         env->DeleteLocalRef(pendingException);
     }
 }
 
 jthrowable CSecureEnv::getPendingException(JNIEnv* env)
 {
     if (mPendingException)
+#if LOCAL_REFS_ARE_GLOBAL
+        return (jthrowable) env->NewGlobalRef(mPendingException);
+#else
         return (jthrowable) env->NewLocalRef(mPendingException);
+#endif
     return NULL;
 }
 
 void CSecureEnv::clearPendingException(JNIEnv* env)
 {
     if (mPendingException) {
         env->DeleteGlobalRef(mPendingException);
         mPendingException = NULL;
     }
 }
diff -U 10 -r -N old/plugin/oji/MRJCarbon/plugin/Source/CSecureEnv.h new/plugin/oji/MRJCarbon/plugin/Source/CSecureEnv.h
--- old/plugin/oji/MRJCarbon/plugin/Source/CSecureEnv.h	2003-06-11 00:11:38.000000000 -0500
+++ new/plugin/oji/MRJCarbon/plugin/Source/CSecureEnv.h	2008-04-11 15:26:36.000000000 -0500
@@ -36,39 +36,90 @@
 
 /*
     CSecureEnv.h
     
     Rewritten for use with MRJ plugin by Patrick C. Beard.
  */
 
 #ifndef CSecureJNI2_h___
 #define CSecureJNI_h___
 
+#include <MacTypes.h>
 #include "nsISecureEnv.h"
-#include "nsIThreadManager.h"
-#include "SupportsMixin.h"
+#include "nsjvmFixes.h"
+#include "nsIScriptSecurityManagerOld.h"
+#include "nsIScriptSecurityManagerNew.h"
+#include "nsIScriptSecurityManagerNewer.h"
+#include "nsIScriptSecurityManagerNewest.h"
+
+/* See https://bugzilla.mozilla.org/show_bug.cgi?id=293973 for the latest
+ * on this issue -- proliferating nsIScriptSecurityManager IIDs.
+ */
+#define NS_ISCRIPTSECURITYMANAGERNEW_IID \
+  {0x18158378, 0xb632, 0x436a, \
+    { 0x9c, 0xed, 0xc5, 0x2d, 0xed, 0x35, 0x0b, 0xde }}
+#define NS_ISCRIPTSECURITYMANAGERNEWALT1_IID \
+  {0x82bff35d, 0xebb7, 0x4cb9, \
+    { 0xbb, 0x47, 0x4f, 0x9e, 0xbd, 0xf1, 0x1f, 0x77 }}
+#define NS_ISCRIPTSECURITYMANAGERNEWALT2_IID \
+  {0x463eb1fa, 0x9dac, 0x4ca7, \
+    { 0x82, 0x6f, 0x1f, 0xc9, 0x21, 0x97, 0x1d, 0x3a }}
+#define NS_ISCRIPTSECURITYMANAGERNEWALT3_IID \
+  {0xf4d74511, 0x2b2d, 0x4a14, \
+    { 0xa3, 0xe4, 0xa3, 0x92, 0xac, 0x5a, 0xc3, 0xff }}
+#define NS_ISCRIPTSECURITYMANAGERNEWALT4_IID \
+  {0x6c86a0d8, 0x7a19, 0x42a4, \
+    { 0xbe, 0x18, 0xd2, 0x82, 0xa2, 0x63, 0x88, 0xfd }}
+#define NS_ISCRIPTSECURITYMANAGERNEWERALT1_IID \
+  {0x5a46e611, 0xcf4a, 0x4407, \
+    { 0xa5, 0xb4, 0x00, 0x2f, 0xcf, 0x05, 0x11, 0x20 }}
+#define NS_ISCRIPTSECURITYMANAGERNEWERALT2_IID \
+  {0x5ed0b9b8, 0xe7f4, 0x4b55, \
+    { 0x98, 0x05, 0x7a, 0xb8, 0x57, 0xb3, 0x35, 0xa1 }}
+#define NS_ISCRIPTSECURITYMANAGERNEWERALT3_IID \
+  {0xb9024f88, 0x9ad2, 0x491c, \
+    { 0x97, 0x77, 0xce, 0x51, 0x91, 0x03, 0x3d, 0x3d }}
+#define NS_ISCRIPTSECURITYMANAGERNEWERALT4_IID \
+  {0xc61d3ad1, 0x00aa, 0x407c, \
+    { 0xb7, 0xd7, 0xde, 0x48, 0xb3, 0xf1, 0x86, 0x62 }}
+#define NS_ISCRIPTSECURITYMANAGERNEWERALT5_IID \
+  {0x0b8a9b32, 0x713f, 0x4c39, \
+    { 0xbe, 0xa0, 0x6c, 0xac, 0xec, 0x46, 0xf3, 0x85 }}
+#define NS_ISCRIPTSECURITYMANAGERNEWERALT6_IID \
+  {0xce216cf7, 0x3bcb, 0x48ab, \
+    { 0x9f, 0xf8, 0xd0, 0x3a, 0x24, 0xf1, 0x9c, 0xa5 }}
+#define NS_ISCRIPTSECURITYMANAGERNEWERALT7_IID \
+  {0x3fffd8e8, 0x3fea, 0x442e, \
+    { 0xa0, 0xed, 0x2b, 0xa8, 0x1a, 0xe1, 0x97, 0xd5 }}
+#define NS_ISCRIPTSECURITYMANAGERNEWESTALT1_IID \
+  {0xe74487fd, 0x98ef, 0x48d1, \
+    { 0xb9, 0x73, 0x3f, 0x29, 0x38, 0xf0, 0x4e, 0x8e }}
+#ifndef NS_ISCRIPTSECURITYMANAGEROBSOLETE_IID
+#define NS_ISCRIPTSECURITYMANAGEROBSOLETE_IID \
+  {0x58df5780, 0x8006, 0x11d2, \
+    { 0xbd, 0x91, 0x00, 0x80, 0x5f, 0x8a, 0xe3, 0xf4 }}
+#endif
 
 class MRJPlugin;
 class MRJSession;
 
 class Monitor;
-class nsIThreadManager;
 class nsIJVMManager;
 class nsIScriptSecurityManager;
 class nsIPrincipal;
 
 class JavaMessage;
 class JavaMessageQueue;
 
-class CSecureEnv : public nsISecureEnv, public nsIRunnable, private SupportsMixin {
+class CSecureEnv : public nsISecureEnv, public nsIRunnable {
 public:
-    DECL_SUPPORTS_MIXIN
+    NS_DECL_ISUPPORTS
 
     static NS_METHOD Create(MRJPlugin* plugin, JNIEnv* proxyEnv, const nsIID& aIID, void* *aInstancePtr);
 
     ////////////////////////////////////////////////////////////////////////////
     // from nsISecureJNI2:
 
 
     /**
      * Create new Java object in LiveConnect.
      *
@@ -375,55 +426,58 @@
     
     jboolean isInitialized() { return mJavaQueue != NULL; }
 
     void setProxyEnv(JNIEnv* proxyEnv) { mProxyEnv = proxyEnv; }
     JNIEnv* getProxyEnv() { return mProxyEnv; }
     
     void setJavaEnv(JNIEnv* javaEnv) { mJavaEnv = javaEnv; }
     JNIEnv* getJavaEnv() { return mJavaEnv; }
     
     MRJSession* getSession() { return mSession; }
-    nsIThreadManager* getThreadManager() { return mThreadManager; }
+    nsIJVMThreadManager* getThreadManager() { return mThreadManager; }
     
     void getMessageQueues(JavaMessageQueue*& javaQueue, JavaMessageQueue*& nativeQueue)
     {
         javaQueue = mJavaQueue;
         nativeQueue = mNativeQueue;
     }
     
     void sendMessageToJava(JavaMessage* msg);
     void sendMessageFromJava(JNIEnv* javaEnv, JavaMessage* msg, Boolean busyWaiting = false);
     void messageLoop(JNIEnv* env, JavaMessage* msgToSend, JavaMessageQueue* sendQueue, JavaMessageQueue* receiveQueue, Boolean busyWaiting = false);
 
     void savePendingException(JNIEnv* env);
     jthrowable getPendingException(JNIEnv* env);
     void clearPendingException(JNIEnv* env);
-    
+    static void suspendExceptions() { ++mSuspendExceptionsLevel; }
+    static void resumeExceptions() { --mSuspendExceptionsLevel; }
+
+	void resetLiveConnectProxy(JNIEnv *env);
+
 protected:
     MRJPlugin*                  mPlugin;
     JNIEnv*                     mProxyEnv;
     JNIEnv*                     mJavaEnv;
     MRJSession*                 mSession;
-    nsIThreadManager*           mThreadManager;
+    nsIJVMThreadManager*        mThreadManager;
     
     jboolean*                   mIsRunning;
     JavaMessageQueue*           mJavaQueue;
     JavaMessageQueue*           mNativeQueue;
 
     jthrowable                  mPendingException;
+    static long                 mSuspendExceptionsLevel;
     
-    nsIScriptSecurityManager*   mScriptSecurityManager;
-    nsIPrincipal*               mScriptPrincipal;
-    jclass                      mLiveConnectProxy;
-    
-private:
-    // support for SupportsMixin.
-    static const InterfaceInfo sInterfaces[];
-    static const UInt32 kInterfaceCount;
+    nsIScriptSecurityManager*       mScriptSecurityManager;
+    nsIScriptSecurityManagerNew*    mScriptSecurityManagerNew;
+    nsIScriptSecurityManagerNewer*  mScriptSecurityManagerNewer;
+    nsIScriptSecurityManagerNewest* mScriptSecurityManagerNewest;
+    nsIPrincipal*                   mScriptPrincipal;
+    jclass                          mLiveConnectProxy;
 };
 
 /**
  * Returns the secure JNI associated with the current thread (if any).
  */
 CSecureEnv* GetSecureJNI(JNIEnv* env, jobject thread);
 
 #endif // CSecureJNI2_h___
diff -U 10 -r -N old/plugin/oji/MRJCarbon/plugin/Source/JavaEmbeddingFramework.cpp new/plugin/oji/MRJCarbon/plugin/Source/JavaEmbeddingFramework.cpp
--- old/plugin/oji/MRJCarbon/plugin/Source/JavaEmbeddingFramework.cpp	1969-12-31 18:00:00.000000000 -0600
+++ new/plugin/oji/MRJCarbon/plugin/Source/JavaEmbeddingFramework.cpp	2006-03-04 22:23:51.000000000 -0600
@@ -0,0 +1,198 @@
+/* ----- BEGIN LICENSE BLOCK -----
+ * Version: MPL 1.1/GPL 2.0/LGPL 2.1
+ *
+ * The contents of this file are subject to the Mozilla Public License Version
+ * 1.1 (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ * http://www.mozilla.org/MPL/
+ *
+ * Software distributed under the License is distributed on an "AS IS" basis,
+ * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
+ * for the specific language governing rights and limitations under the
+ * License.
+ *
+ * The Original Code is the MRJ Carbon OJI Plugin.
+ *
+ * The Initial Developer of the Original Code is
+ * Netscape Communications Corp.
+ * Portions created by the Initial Developer are Copyright (C) 2001
+ * the Initial Developer. All Rights Reserved.
+ *
+ * Contributor(s):  Patrick C. Beard <beard@netscape.com>
+ *
+ * Alternatively, the contents of this file may be used under the terms of
+ * either the GNU General Public License Version 2 or later (the "GPL"), or
+ * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
+ * in which case the provisions of the GPL or the LGPL are applicable instead
+ * of those above. If you wish to allow use of your version of this file only
+ * under the terms of either the GPL or the LGPL, and not to allow others to
+ * use your version of this file under the terms of the MPL, indicate your
+ * decision by deleting the provisions above and replace them with the notice
+ * and other provisions required by the GPL or the LGPL. If you do not delete
+ * the provisions above, a recipient may use your version of this file under
+ * the terms of any one of the MPL, the GPL or the LGPL.
+ *
+ * ----- END LICENSE BLOCK ----- */
+
+/*
+    JavaEmbeddingFramework.cpp
+
+    Dynamically loads the JavaEmbeddingFramework.  We need this because the
+	JavaEmbeddingFramework isn't present on Mac OS X for Intel.
+
+    by Steven Michaud (modeled on JavaVMFramework.cpp by Patrick C. Beard).
+ */
+
+#include <jni.h>
+#include <CarbonEvents.h>
+#include <JavaApplet.h>
+#include <JavaControl.h>
+
+#include <CFURL.h>
+#include <CFBundle.h>
+#include <CFString.h>
+
+static CFBundleRef getBundle(CFStringRef frameworkPath)
+{
+	CFBundleRef bundle = NULL;
+
+	//	Make a CFURLRef from the CFString representation of the bundle's path.
+	//	See the Core Foundation URL Services chapter for details.
+	CFURLRef bundleURL = CFURLCreateWithFileSystemPath(NULL, frameworkPath, kCFURLPOSIXPathStyle, true);
+	if (bundleURL != NULL) {
+		bundle = CFBundleCreate(NULL, bundleURL);
+		if (bundle != NULL)
+			CFBundleLoadExecutable(bundle);
+		CFRelease(bundleURL);
+	}
+
+	return bundle;
+}
+
+static void* getJavaEmbeddingFunction(CFStringRef functionName)
+{
+// The #ifdef __ppc__ is from Mark Mentovai's patch at
+// https://bugzilla.mozilla.org/show_bug.cgi?id=315163.
+#ifdef __ppc__
+	static CFBundleRef javaBundle = getBundle(CFSTR("/System/Library/Frameworks/JavaEmbedding.framework"));
+	if (javaBundle) return CFBundleGetFunctionPointerForName(javaBundle, functionName);
+#endif
+	return NULL;
+}
+
+typedef OSStatus (*CreateJavaApplet_proc_ptr) (JNIEnv *env, AppletDescriptor applet, Boolean trusted, AppletArena arena, jobject *outJavaFrame);
+static CreateJavaApplet_proc_ptr _CreateJavaApplet = (CreateJavaApplet_proc_ptr) getJavaEmbeddingFunction(CFSTR("CreateJavaApplet"));
+
+OSStatus CreateJavaApplet(JNIEnv *env, AppletDescriptor applet,
+	Boolean trusted, AppletArena arena, jobject *outJavaFrame)
+{
+	if (_CreateJavaApplet) return _CreateJavaApplet(env, applet, trusted, arena, outJavaFrame);
+	return -1;
+}
+
+Boolean CheckJavaEmbeddingFramework(void)
+{
+	static Boolean frameworkChecked = FALSE;
+	static Boolean frameworkStatus = FALSE;
+	if (frameworkChecked) return frameworkStatus;
+	if (_CreateJavaApplet)
+		frameworkStatus = TRUE;
+	frameworkChecked = TRUE;
+	return frameworkStatus;
+}
+
+typedef OSStatus (*CreateJavaControl_proc_ptr) (JNIEnv *env, WindowRef inNativeWindow, const Rect *inBounds, jobject inAppletFrame, Boolean inVisible, ControlRef *outControl);
+static CreateJavaControl_proc_ptr _CreateJavaControl = (CreateJavaControl_proc_ptr) getJavaEmbeddingFunction(CFSTR("CreateJavaControl"));
+
+OSStatus CreateJavaControl(JNIEnv *env, WindowRef inNativeWindow,
+	const Rect *inBounds, jobject inAppletFrame, Boolean inVisible,
+	ControlRef *outControl)
+{
+	if (_CreateJavaControl) return _CreateJavaControl(env, inNativeWindow, inBounds, inAppletFrame, inVisible, outControl);
+	return -1;
+}
+
+typedef OSStatus (*DrawJavaControl_proc_ptr) (JNIEnv *env, ControlRef theControl);
+static DrawJavaControl_proc_ptr _DrawJavaControl = (DrawJavaControl_proc_ptr) getJavaEmbeddingFunction(CFSTR("DrawJavaControl"));
+
+OSStatus DrawJavaControl(JNIEnv *env, ControlRef theControl)
+{
+	if (_DrawJavaControl) return _DrawJavaControl(env, theControl);
+	return -1;
+}
+
+typedef OSStatus (*MoveAndClipJavaControl_proc_ptr) (JNIEnv *env, ControlRef theControl, int posX, int posY, int clipX, int clipY, int clipWidth, int clipHeight);
+static MoveAndClipJavaControl_proc_ptr _MoveAndClipJavaControl = (MoveAndClipJavaControl_proc_ptr) getJavaEmbeddingFunction(CFSTR("MoveAndClipJavaControl"));
+
+OSStatus MoveAndClipJavaControl(JNIEnv *env, ControlRef theControl,
+	int posX, int posY, int clipX, int clipY, int clipWidth, int clipHeight)
+{
+	if (_MoveAndClipJavaControl) return _MoveAndClipJavaControl(env, theControl, posX, posY, clipX, clipY, clipWidth, clipHeight);
+	return -1;
+}
+
+typedef OSStatus (*RegisterShowDocumentCallback_proc_ptr) (JNIEnv *env, jobject inJavaFrame, JE_ShowDocumentCallback showDocumentFunction, void *userData);
+static RegisterShowDocumentCallback_proc_ptr _RegisterShowDocumentCallback = (RegisterShowDocumentCallback_proc_ptr) getJavaEmbeddingFunction(CFSTR("RegisterShowDocumentCallback"));
+
+OSStatus RegisterShowDocumentCallback(JNIEnv *env, jobject inJavaFrame,
+	JE_ShowDocumentCallback showDocumentFunction, void *userData)
+{
+	if (_RegisterShowDocumentCallback) return _RegisterShowDocumentCallback(env, inJavaFrame, showDocumentFunction, userData);
+	return -1;
+}
+
+typedef OSStatus (*RegisterStatusCallback_proc_ptr) (JNIEnv *env, jobject inJavaFrame, JE_SetStatusCallback showStatusFunction, void *userData);
+static RegisterStatusCallback_proc_ptr _RegisterStatusCallback = (RegisterStatusCallback_proc_ptr) getJavaEmbeddingFunction(CFSTR("RegisterStatusCallback"));
+
+OSStatus RegisterStatusCallback(JNIEnv *env, jobject inJavaFrame,
+	JE_SetStatusCallback showStatusFunction, void *userData)
+{
+	if (_RegisterStatusCallback) return _RegisterStatusCallback(env, inJavaFrame, showStatusFunction, userData);
+	return -1;
+}
+
+typedef OSStatus (*RestartJavaControlAsyncDrawing_proc_ptr) (JNIEnv *env, ControlRef theControl);
+static RestartJavaControlAsyncDrawing_proc_ptr _RestartJavaControlAsyncDrawing = (RestartJavaControlAsyncDrawing_proc_ptr) getJavaEmbeddingFunction(CFSTR("RestartJavaControlAsyncDrawing"));
+
+OSStatus RestartJavaControlAsyncDrawing(JNIEnv *env, ControlRef theControl)
+{
+	if (_RestartJavaControlAsyncDrawing) return _RestartJavaControlAsyncDrawing(env, theControl);
+	return -1;
+}
+
+typedef OSStatus (*SetJavaAppletState_proc_ptr) (JNIEnv *env, jobject inAppletFrame, AppletState inNewState);
+static SetJavaAppletState_proc_ptr _SetJavaAppletState = (SetJavaAppletState_proc_ptr) getJavaEmbeddingFunction(CFSTR("SetJavaAppletState"));
+
+OSStatus SetJavaAppletState(JNIEnv *env, jobject inAppletFrame, AppletState inNewState)
+{
+	if (_SetJavaAppletState) return _SetJavaAppletState(env, inAppletFrame, inNewState);
+	return -1;
+}
+
+typedef OSStatus (*ShowHideJavaControl_proc_ptr) (JNIEnv *env, ControlRef theControl, Boolean visible);
+static ShowHideJavaControl_proc_ptr _ShowHideJavaControl = (ShowHideJavaControl_proc_ptr) getJavaEmbeddingFunction(CFSTR("ShowHideJavaControl"));
+
+OSStatus ShowHideJavaControl(JNIEnv *env, ControlRef theControl, Boolean visible)
+{
+	if (_ShowHideJavaControl) return _ShowHideJavaControl(env, theControl, visible);
+	return -1;
+}
+
+typedef OSStatus (*SizeJavaControl_proc_ptr) (JNIEnv *env, ControlRef theControl, int width, int height);
+static SizeJavaControl_proc_ptr _SizeJavaControl = (SizeJavaControl_proc_ptr) getJavaEmbeddingFunction(CFSTR("SizeJavaControl"));
+
+OSStatus SizeJavaControl(JNIEnv *env, ControlRef theControl, int width, int height)
+{
+	if (_SizeJavaControl) return _SizeJavaControl(env, theControl, width, height);
+	return -1;
+}
+
+typedef OSStatus (*StopJavaControlAsyncDrawing_proc_ptr) (JNIEnv *env, ControlRef theControl);
+static StopJavaControlAsyncDrawing_proc_ptr _StopJavaControlAsyncDrawing = (StopJavaControlAsyncDrawing_proc_ptr) getJavaEmbeddingFunction(CFSTR("StopJavaControlAsyncDrawing"));
+
+OSStatus StopJavaControlAsyncDrawing(JNIEnv *env, ControlRef theControl)
+{
+	if (_StopJavaControlAsyncDrawing) return _StopJavaControlAsyncDrawing(env, theControl);
+	return -1;
+}
+
diff -U 10 -r -N old/plugin/oji/MRJCarbon/plugin/Source/JavaEmbeddingPlugin.cpp new/plugin/oji/MRJCarbon/plugin/Source/JavaEmbeddingPlugin.cpp
--- old/plugin/oji/MRJCarbon/plugin/Source/JavaEmbeddingPlugin.cpp	1969-12-31 18:00:00.000000000 -0600
+++ new/plugin/oji/MRJCarbon/plugin/Source/JavaEmbeddingPlugin.cpp	2006-11-10 14:17:24.000000000 -0600
@@ -0,0 +1,355 @@
+/*
+ * Copyright (c) 2004, Steven Michaud, All Rights Reserved
+ * 
+ * Permission is hereby granted, free of charge, to any person obtaining
+ * a copy of this software and associated documentation files (the
+ * "Software"), to deal in the Software without restriction, including
+ * without limitation the rights to use, copy, modify, merge, publish,
+ * distribute, sublicense, and/or sell copies of the Software, and to
+ * permit persons to whom the Software is furnished to do so, subject to
+ * the following conditions:
+ * 
+ * The above copyright notice and this permission notice shall be
+ * included in all copies or substantial portions of the Software.
+ * 
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+ * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+ * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
+ * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
+ * CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
+ * TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
+ * SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+ */
+
+#import "JavaEmbeddingPlugin.h"
+extern FSSpec thePluginSpec;
+extern CFBundleRef thePluginBundle;
+CFBundleRef getPluginBundle();
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+/* This routine must not be called more than once. */
+static CFBundleRef getJEPBundle(void)
+{
+	int i, j;
+	OSStatus retval;
+	FSRef pluginsFolderRef;
+	CFURLRef bundleURL, bundleBaseURL;
+	CFBundleRef bundle = NULL;
+
+	thePluginBundle = getPluginBundle();
+
+	FSRef thePluginRef;
+	char path[1024] = {0};
+	char *lastSlash;
+	for (i = 1, retval = -1; i <= 4; ++i) {
+		switch (i) {
+			/* First look in our (MRJPlugin.plugin's) current directory */
+			case 1:
+				retval = FSpMakeFSRef(&thePluginSpec, &thePluginRef);
+				if (retval != noErr)
+					break;
+				retval = FSRefMakePath(&thePluginRef, (UInt8 *) path,
+					sizeof(path));
+				if (retval != noErr)
+					break;
+				for (j = 1; j <= 4; ++j) {
+					lastSlash = strrchr(path, '/');
+					if (lastSlash) {
+						*lastSlash = 0;
+					} else {
+						break;
+					}
+				}
+				retval = FSPathMakeRef((const UInt8 *) path,
+					&pluginsFolderRef, NULL);
+				break;
+			/* Then (if need be) look in our parent directory */
+			case 2:
+				lastSlash = strrchr(path, '/');
+				if (lastSlash)
+					*lastSlash = 0;
+				retval = FSPathMakeRef((const UInt8 *) path,
+					&pluginsFolderRef, NULL);
+				break;
+			/* Then (if need be) look in the user's Plug-Ins directory */
+			case 3:
+				retval = FSFindFolder(kUserDomain, kInternetPlugInFolderType,
+					kDontCreateFolder, &pluginsFolderRef);
+				break;
+			/* Then (if need be) look in the system Plug-Ins directory */
+			case 4:
+				retval = FSFindFolder(kLocalDomain, kInternetPlugInFolderType,
+					kDontCreateFolder, &pluginsFolderRef);
+				break;
+			default:
+				break;
+		}
+		if (retval != noErr)
+			continue;
+		bundleBaseURL = CFURLCreateFromFSRef(kCFAllocatorSystemDefault,
+			&pluginsFolderRef);
+		bundleURL = CFURLCreateWithFileSystemPathRelativeToBase(
+			kCFAllocatorSystemDefault, CFSTR("JavaEmbeddingPlugin.bundle"),
+			kCFURLPOSIXPathStyle, true, bundleBaseURL);
+		if (bundleURL) {
+			bundle = CFBundleCreate(kCFAllocatorDefault, bundleURL);
+			if (bundle) {
+				if (!CFBundleLoadExecutable(bundle)) {
+					CFRelease(bundle);
+					bundle = NULL;
+				}
+			}
+			CFRelease(bundleURL);
+		}
+		if (bundleBaseURL)
+			CFRelease(bundleBaseURL);
+		if (bundle)
+			break;
+	}
+
+	return bundle;
+}
+
+void *getJEPFunction(CFStringRef functionName)
+{
+	static CFBundleRef bundle = getJEPBundle();
+	if (bundle) return CFBundleGetFunctionPointerForName(bundle, functionName);
+	return NULL;
+}
+
+typedef Boolean (*JEPCheckBundleWithVersion_proc_ptr) (CFStringRef version);
+static JEPCheckBundleWithVersion_proc_ptr _JEPCheckBundleWithVersion = (JEPCheckBundleWithVersion_proc_ptr) getJEPFunction(CFSTR("JEPCheckBundleWithVersion"));
+
+Boolean JEPCheckBundle(void)
+{
+	static Boolean JEPBundleChecked = FALSE;
+	static Boolean JEPBundleStatus = FALSE;
+	if (JEPBundleChecked) return JEPBundleStatus;
+	if (_JEPCheckBundleWithVersion)
+		JEPBundleStatus = _JEPCheckBundleWithVersion(CFSTR(JEP_VERSION));
+	JEPBundleChecked = TRUE;
+	return JEPBundleStatus;
+}
+
+typedef CFStringRef (*JEPGetInstalledPath_proc_ptr) (void);
+static JEPGetInstalledPath_proc_ptr _JEPGetInstalledPath = (JEPGetInstalledPath_proc_ptr) getJEPFunction(CFSTR("JEPGetInstalledPath"));
+
+CFStringRef JEPGetInstalledPath(void)
+{
+    if (_JEPGetInstalledPath) return _JEPGetInstalledPath();
+    return NULL;
+}
+
+typedef OSStatus (*JEPCreateJavaVM_proc_ptr) (JavaVMOption *jvmExtraOpts, int jvmExtraOptsNum, JavaVM **vm, void **env);
+static JEPCreateJavaVM_proc_ptr _JEPCreateJavaVM = (JEPCreateJavaVM_proc_ptr) getJEPFunction(CFSTR("JEPCreateJavaVM"));
+
+OSStatus JEPCreateJavaVM(JavaVMOption *jvmExtraOpts, int jvmExtraOptsNum, JavaVM **vm,  void **env)
+{
+    if (_JEPCreateJavaVM) return _JEPCreateJavaVM(jvmExtraOpts, jvmExtraOptsNum, vm, env);
+    return -1;
+}
+
+typedef OSStatus (*JEPCreateJavaVMAndInitAWT_proc_ptr) (JavaVMOption *jvmExtraOpts, int jvmExtraOptsNum, JavaVM **vm, void **env, void (*runAfterInitAWT) (void *), void *runAfterInitAWTInfo);
+static JEPCreateJavaVMAndInitAWT_proc_ptr _JEPCreateJavaVMAndInitAWT = (JEPCreateJavaVMAndInitAWT_proc_ptr) getJEPFunction(CFSTR("JEPCreateJavaVMAndInitAWT"));
+
+OSStatus JEPCreateJavaVMAndInitAWT(JavaVMOption *jvmExtraOpts, int jvmExtraOptsNum, JavaVM **vm,  void **env, void (*runAfterInitAWT) (void *), void *runAfterInitAWTInfo)
+{
+    if (_JEPCreateJavaVMAndInitAWT) return _JEPCreateJavaVMAndInitAWT(jvmExtraOpts, jvmExtraOptsNum, vm, env, runAfterInitAWT, runAfterInitAWTInfo);
+    return -1;
+}
+
+typedef OSStatus (*JEPCreateJavaApplet_proc_ptr) (CFURLRef docbase, CFDictionaryRef attributes, WindowRef parentWindow, JEPOptions *options, void **handle);
+static JEPCreateJavaApplet_proc_ptr _JEPCreateJavaApplet = (JEPCreateJavaApplet_proc_ptr) getJEPFunction(CFSTR("JEPCreateJavaApplet"));
+
+OSStatus JEPCreateJavaApplet(CFURLRef docbase, CFDictionaryRef attributes, WindowRef parentWindow, JEPOptions *options, void **handle)
+{
+    if (_JEPCreateJavaApplet) return _JEPCreateJavaApplet(docbase, attributes, parentWindow, options, handle);
+    return -1;
+}
+
+typedef OSStatus (*JEPGetJavaApplet_proc_ptr) (void *handle, jobject *applet);
+static JEPGetJavaApplet_proc_ptr _JEPGetJavaApplet = (JEPGetJavaApplet_proc_ptr) getJEPFunction(CFSTR("JEPGetJavaApplet"));
+
+OSStatus JEPGetJavaApplet(void *handle, jobject *applet)
+{
+    if (_JEPGetJavaApplet) return _JEPGetJavaApplet(handle, applet);
+    return -1;
+}
+
+typedef OSStatus (*JEPGetJavaVM_proc_ptr) (void *handle, JavaVM **vm);
+static JEPGetJavaVM_proc_ptr _JEPGetJavaVM = (JEPGetJavaVM_proc_ptr) getJEPFunction(CFSTR("JEPGetJavaVM"));
+
+OSStatus JEPGetJavaVM(void *handle, JavaVM **vm)
+{
+    if (_JEPGetJavaVM) return _JEPGetJavaVM(handle, vm);
+    return -1;
+}
+
+typedef OSStatus (*JEPSetJavaAppletState_proc_ptr) (void *handle, AppletStateJEP newState);
+static JEPSetJavaAppletState_proc_ptr _JEPSetJavaAppletState = (JEPSetJavaAppletState_proc_ptr) getJEPFunction(CFSTR("JEPSetJavaAppletState"));
+
+OSStatus JEPSetJavaAppletState(void *handle, AppletStateJEP newState)
+{
+    if (_JEPSetJavaAppletState) return _JEPSetJavaAppletState(handle, newState);
+    return -1;
+}
+
+typedef OSStatus (*JEPGetJavaAppletState_proc_ptr) (void *handle, AppletStateJEP *state);
+static JEPGetJavaAppletState_proc_ptr _JEPGetJavaAppletState = (JEPGetJavaAppletState_proc_ptr) getJEPFunction(CFSTR("JEPGetJavaAppletState"));
+
+OSStatus JEPGetJavaAppletState(void *handle, AppletStateJEP *state)
+{
+    if (_JEPGetJavaAppletState) return _JEPGetJavaAppletState(handle, state);
+    return -1;
+}
+
+typedef OSStatus (*JEPDrawJavaApplet_proc_ptr) (void *handle);
+static JEPDrawJavaApplet_proc_ptr _JEPDrawJavaApplet = (JEPDrawJavaApplet_proc_ptr) getJEPFunction(CFSTR("JEPDrawJavaApplet"));
+
+OSStatus JEPDrawJavaApplet(void *handle)
+{
+    if (_JEPDrawJavaApplet) return _JEPDrawJavaApplet(handle);
+    return -1;
+}
+
+typedef OSStatus (*JEPMaybeDrawJavaApplet_proc_ptr) (void *handle);
+static JEPMaybeDrawJavaApplet_proc_ptr _JEPMaybeDrawJavaApplet = (JEPMaybeDrawJavaApplet_proc_ptr) getJEPFunction(CFSTR("JEPMaybeDrawJavaApplet"));
+
+OSStatus JEPMaybeDrawJavaApplet(void *handle)
+{
+    if (_JEPMaybeDrawJavaApplet) return _JEPMaybeDrawJavaApplet(handle);
+    return -1;
+}
+
+typedef OSStatus (*JEPSuspendJavaAppletUpdates_proc_ptr) (void *handle);
+static JEPSuspendJavaAppletUpdates_proc_ptr _JEPSuspendJavaAppletUpdates = (JEPSuspendJavaAppletUpdates_proc_ptr) getJEPFunction(CFSTR("JEPSuspendJavaAppletUpdates"));
+
+OSStatus JEPSuspendJavaAppletUpdates(void *handle)
+{
+    if (_JEPSuspendJavaAppletUpdates) return _JEPSuspendJavaAppletUpdates(handle);
+    return -1;
+}
+
+typedef OSStatus (*JEPResumeJavaAppletUpdates_proc_ptr) (void *handle);
+static JEPResumeJavaAppletUpdates_proc_ptr _JEPResumeJavaAppletUpdates = (JEPResumeJavaAppletUpdates_proc_ptr) getJEPFunction(CFSTR("JEPResumeJavaAppletUpdates"));
+
+OSStatus JEPResumeJavaAppletUpdates(void *handle)
+{
+    if (_JEPResumeJavaAppletUpdates) return _JEPResumeJavaAppletUpdates(handle);
+    return -1;
+}
+
+typedef OSStatus (*JEPSizeJavaApplet_proc_ptr) (void *handle, int width, int height);
+static JEPSizeJavaApplet_proc_ptr _JEPSizeJavaApplet = (JEPSizeJavaApplet_proc_ptr) getJEPFunction(CFSTR("JEPSizeJavaApplet"));
+
+OSStatus JEPSizeJavaApplet(void *handle, int width, int height)
+{
+    if (_JEPSizeJavaApplet) return _JEPSizeJavaApplet(handle, width, height);
+    return -1;
+}
+
+typedef OSStatus (*JEPPositionJavaApplet_proc_ptr) (void *handle, int posX, int posY);
+static JEPPositionJavaApplet_proc_ptr _JEPPositionJavaApplet = (JEPPositionJavaApplet_proc_ptr) getJEPFunction(CFSTR("JEPPositionJavaApplet"));
+
+OSStatus JEPPositionJavaApplet(void *handle, int posX, int posY)
+{
+    if (_JEPPositionJavaApplet) return _JEPPositionJavaApplet(handle, posX, posY);
+    return -1;
+}
+
+typedef OSStatus (*JEPMoveAndClipJavaApplet_proc_ptr) (void *handle, int posX, int posY, int clipX, int clipY, int clipWidth, int clipHeight);
+static JEPMoveAndClipJavaApplet_proc_ptr _JEPMoveAndClipJavaApplet = (JEPMoveAndClipJavaApplet_proc_ptr) getJEPFunction(CFSTR("JEPMoveAndClipJavaApplet"));
+
+OSStatus JEPMoveAndClipJavaApplet(void *handle, int posX, int posY, int clipX, int clipY, int clipWidth, int clipHeight)
+{
+    if (_JEPMoveAndClipJavaApplet) return _JEPMoveAndClipJavaApplet(handle, posX, posY, clipX, clipY, clipWidth, clipHeight);
+    return -1;
+}
+
+typedef OSStatus (*JEPShowHideJavaApplet_proc_ptr) (void *handle, Boolean visible);
+static JEPShowHideJavaApplet_proc_ptr _JEPShowHideJavaApplet = (JEPShowHideJavaApplet_proc_ptr) getJEPFunction(CFSTR("JEPShowHideJavaApplet"));
+
+OSStatus JEPShowHideJavaApplet(void *handle, Boolean visible)
+{
+    if (_JEPShowHideJavaApplet) return _JEPShowHideJavaApplet(handle, visible);
+    return -1;
+}
+
+typedef OSStatus (*JEPRegisterStatusCallback_proc_ptr) (void *handle, JEPShowStatusCallback showStatusFunction, void *userData);
+static JEPRegisterStatusCallback_proc_ptr _JEPRegisterStatusCallback = (JEPRegisterStatusCallback_proc_ptr) getJEPFunction(CFSTR("JEPRegisterStatusCallback"));
+
+OSStatus JEPRegisterStatusCallback(void *handle, JEPShowStatusCallback showStatusFunction, void *userData)
+{
+    if (_JEPRegisterStatusCallback) return _JEPRegisterStatusCallback(handle, showStatusFunction, userData);
+    return -1;
+}
+
+typedef OSStatus (*JEPRegisterShowDocumentCallback_proc_ptr) (void *handle, JEPShowDocumentCallback showDocumentFunction, void *userData);
+static JEPRegisterShowDocumentCallback_proc_ptr _JEPRegisterShowDocumentCallback = (JEPRegisterShowDocumentCallback_proc_ptr) getJEPFunction(CFSTR("JEPRegisterShowDocumentCallback"));
+
+OSStatus JEPRegisterShowDocumentCallback(void *handle, JEPShowDocumentCallback showDocumentFunction, void *userData)
+{
+    if (_JEPRegisterShowDocumentCallback) return _JEPRegisterShowDocumentCallback(handle, showDocumentFunction, userData);
+    return -1;
+}
+
+typedef Boolean (*JEPGetJavaRuntimeParameterBoolean_proc_ptr) (CFStringRef key);
+static JEPGetJavaRuntimeParameterBoolean_proc_ptr _JEPGetJavaRuntimeParameterBoolean = (JEPGetJavaRuntimeParameterBoolean_proc_ptr) getJEPFunction(CFSTR("JEPGetJavaRuntimeParameterBoolean"));
+
+Boolean JEPGetJavaRuntimeParameterBoolean(CFStringRef key)
+{
+    if (_JEPGetJavaRuntimeParameterBoolean) return _JEPGetJavaRuntimeParameterBoolean(key);
+    return false;
+}
+
+typedef CFStringRef (*JEPGetJavaRuntimeParameterString_proc_ptr) (CFStringRef key);
+static JEPGetJavaRuntimeParameterString_proc_ptr _JEPGetJavaRuntimeParameterString = (JEPGetJavaRuntimeParameterString_proc_ptr) getJEPFunction(CFSTR("JEPGetJavaRuntimeParameterString"));
+
+CFStringRef JEPGetJavaRuntimeParameterString(CFStringRef key)
+{
+    if (_JEPGetJavaRuntimeParameterString) return _JEPGetJavaRuntimeParameterString(key);
+    return NULL;
+}
+
+typedef OSStatus (*JEPLogJavaMessage_proc_ptr) (CFStringRef message);
+static JEPLogJavaMessage_proc_ptr _JEPLogJavaMessage = (JEPLogJavaMessage_proc_ptr) getJEPFunction(CFSTR("JEPLogJavaMessage"));
+
+OSStatus JEPLogJavaMessage(CFStringRef message)
+{
+    if (_JEPLogJavaMessage) return _JEPLogJavaMessage(message);
+    return -1;
+}
+
+typedef void (*JEPDoLiveConnectProxy_proc_ptr) (jclass proxyClass, jobject runnable, jobject applet, jboolean isCallMethodCall);
+JEPDoLiveConnectProxy_proc_ptr _JEPDoLiveConnectProxy = (JEPDoLiveConnectProxy_proc_ptr) getJEPFunction(CFSTR("JEPDoLiveConnectProxy"));
+
+void JEPDoLiveConnectProxy(jclass proxyClass, jobject runnable, jobject applet, jboolean isCallMethodCall)
+{
+    if (_JEPDoLiveConnectProxy) return _JEPDoLiveConnectProxy(proxyClass, runnable, applet, isCallMethodCall);
+    return;
+}
+
+typedef void (*JEPRunOnMainThread_proc_ptr) (void (*runnable) (void *), void *info, Boolean wait);
+JEPRunOnMainThread_proc_ptr _JEPRunOnMainThread = (JEPRunOnMainThread_proc_ptr) getJEPFunction(CFSTR("JEPRunOnMainThread"));
+
+void JEPRunOnMainThread(void (*runnable) (void *), void *info, Boolean wait)
+{
+    if (_JEPRunOnMainThread) return _JEPRunOnMainThread(runnable, info, wait);
+    return;
+}
+
+typedef jthrowable (*JEPRunJRunnableOnMainThread_proc_ptr) (jobject jrunnable);
+JEPRunJRunnableOnMainThread_proc_ptr _JEPRunJRunnableOnMainThread = (JEPRunJRunnableOnMainThread_proc_ptr) getJEPFunction(CFSTR("JEPRunJRunnableOnMainThread"));
+
+jthrowable JEPRunJRunnableOnMainThread(jobject jrunnable)
+{
+    if (_JEPRunJRunnableOnMainThread) return _JEPRunJRunnableOnMainThread(jrunnable);
+    return NULL;
+}
+
+#ifdef __cplusplus
+}
+#endif
diff -U 10 -r -N old/plugin/oji/MRJCarbon/plugin/Source/JavaEmbeddingPlugin.h new/plugin/oji/MRJCarbon/plugin/Source/JavaEmbeddingPlugin.h
--- old/plugin/oji/MRJCarbon/plugin/Source/JavaEmbeddingPlugin.h	1969-12-31 18:00:00.000000000 -0600
+++ new/plugin/oji/MRJCarbon/plugin/Source/JavaEmbeddingPlugin.h	2007-10-06 20:46:43.000000000 -0500
@@ -0,0 +1,242 @@
+/*
+ * Copyright (c) 2004, Steven Michaud, All Rights Reserved
+ * 
+ * Permission is hereby granted, free of charge, to any person obtaining
+ * a copy of this software and associated documentation files (the
+ * "Software"), to deal in the Software without restriction, including
+ * without limitation the rights to use, copy, modify, merge, publish,
+ * distribute, sublicense, and/or sell copies of the Software, and to
+ * permit persons to whom the Software is furnished to do so, subject to
+ * the following conditions:
+ * 
+ * The above copyright notice and this permission notice shall be
+ * included in all copies or substantial portions of the Software.
+ * 
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+ * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+ * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
+ * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
+ * CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
+ * TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
+ * SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+ */
+
+/* The API declared in this file is modeled on Apple's old Java Embedding
+ * API declared and documented in JavaApplet.h and JavaControl.h in
+ * /System/Library/Frameworks/JavaEmbedding.framework/Headers.  Some of
+ * the differences from the original API are required by changes in the
+ * newer JVMs (1.4.1 and 1.4.2).  Others are intended to fill holes in
+ * the original API, or to make improvements upon it.
+ *
+ * The biggest difference from the original Java Embedding API is that
+ * applets must now be created in a separate thread.  The calling app gets
+ * notified by callbacks of progress (or failure) at several stages in
+ * creating the applet.  As of version 0.8.7, the JEP defaults to doing part
+ * of this synchronously (creation and at least part of initialization).
+ * This makes it possible for the applet to be visible in a JavaScript onLoad
+ * handler in a browser that (like all of the Mozilla family) assumes applet
+ * creation and initialization will be synchronous.  To go back to the
+ * original, fully asynchronous behavior, add "-Djep.asyncinit=true" to the
+ * Java Control Panel's "runtime parameters".)
+ */
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+#define JEP_VERSION "0.9.6.4"
+#define JEP_VERSION_OPTION "jep.version"
+
+/* As described above */
+#define JEP_ASYNCINIT_OPTION "jep.asyncinit"
+/* As of JEP 0.8.7, JSObject's methods (the Java-to-JavaScript LiveConnect
+ * calls) time out after a fairly long interval (currently 2000 milliseconds).
+ * This was how versions 0.8.3 through 0.8.5 behaved.  Version 0.8.6 waited
+ * indefinitely for these calls to return.  This sometimes allows poorly
+ * written applets to hang the browser, but timing out the calls can also
+ * cause trouble.  Adding "-Djep.jsobjectnotimeout=true" to the Java Control
+ * Panel's "runtime parameters" restores JEP 0.8.6's behavior.
+ */
+#define JEP_JSOBJECT_NOTIMEOUT_OPTION "jep.jsobjectnotimeout"
+/* Setting this to "true" makes the JEP log applet visibility and clipping
+ * information to System.out.
+ */
+#define JEP_DEBUG_VISIBILITY_OPTION "jep.debug.visibility"
+/* Setting this to "true" makes the JEP log the various stages of releasing
+ * applet resources to System.out.
+ */
+#define JEP_DEBUG_RELEASE_OPTION "jep.debug.release"
+/* Setting this to "true" makes the JEP (actually the MRJ Plugin JEP) log
+ * to System.out calls (such as setWindow() and drawApplet()) that result in
+ * whole-applet updates.
+ */
+#define JEP_DEBUG_UPDATES_OPTION "jep.debug.updates"
+/* Setting this to "true" makes the JEP (actually the MRJ Plugin JEP) log
+ * to System.out CAPS interface calls used when doing JavaScript-to-Java
+ * LiveConnect (and other "ProxyJNI" stuff).  _Very_ noisy and slow.
+ */
+#define JEP_DEBUG_PROXYJNI_OPTION "jep.debug.proxyjni"
+#define JEP_DEBUG_PRINTING_OPTION "jep.debug.printing"
+
+#import <Carbon/Carbon.h>
+#import <JavaVM/jni.h>
+
+#ifndef JNI_VERSION_1_4
+#define JNI_VERSION_1_4 0x00010004
+#endif
+
+enum AppletStateJEP {
+	kAppletCreateJEP	= 1,
+	kAppletInitJEP		= 2,
+	kAppletStartJEP		= 3,
+	kAppletStopJEP		= 4,
+	kAppletDestroyJEP	= 5,
+	kAppletErrorJEP		= 7
+};
+typedef enum AppletStateJEP AppletStateJEP;
+
+typedef CALLBACK_API_C( void , JEPShowDocumentCallback )(jobject applet, CFURLRef url, CFStringRef windowName, void *userData);
+typedef CALLBACK_API_C( void , JEPShowStatusCallback )(jobject applet, CFStringRef statusMessage, void *userData);
+typedef CALLBACK_API_C( void , JEPAppletCreatedCallback )(void *handle, JavaVM *vm, jobject applet, WindowRef window, AppletStateJEP status, void *userData);
+typedef CALLBACK_API_C( void , JEPAppletInitializedCallback )(void *handle, JavaVM *vm, jobject applet, WindowRef window, AppletStateJEP status, void *userData);
+typedef CALLBACK_API_C( void , JEPAppletStartedCallback )(void *handle, JavaVM *vm, jobject applet, WindowRef window, AppletStateJEP status, void *userData);
+
+typedef struct {
+	Rect appletClip;		// In parentWindow's coordinate system
+	int appletPosX;			// In parentWindow's coordinate system, upper-left origin
+	int appletPosY;			// In parentWindow's coordinate system, upper-left origin
+	unsigned appletWidth;	// May be overridden by applet's "WIDTH" tag
+	unsigned appletHeight;	// May be overridden by applet's "HEIGHT" tag
+
+	Boolean createdInvisible;
+	Boolean erasePreviousFrame;
+	Boolean resizeAppletDirectly;
+
+	JavaVMOption *jvmExtraOpts;
+	int jvmExtraOptsNum;
+
+	JEPShowDocumentCallback showDocumentCallback;
+	void *showDocumentUserData;
+	JEPShowStatusCallback showStatusCallback;
+	void *showStatusUserData;
+	/* appletCreatedCallback, if specified, will _always_ (we hope) be
+	 * called if JEPCreateJavaApplet() returned no error -- even if the
+	 * applet ultimately failed to load or if it was destroyed while
+	 * loading.  At this point the applet has been created (or it failed
+	 * to load, or was created and destroyed), but it hasn't necessarily
+	 * either been initialized or started (and it might never be).  The
+	 * callback might happen before JEPCreateJavaApplet() returns.  It
+	 * might be called on a secondary thread (not the main thread) -- as
+	 * of JEP 0.8.7 it always is.
+	 */
+	JEPAppletCreatedCallback appletCreatedCallback;
+	void *appletCreatedUserData;
+	/* appletInitializedCallback is called just after the applet has been
+	 * initialized.  The callback might happen before JEPCreateJavaApplet()
+	 * returns.  It might be called on a secondary thread (not the main
+	 * thread).
+	 */
+	JEPAppletInitializedCallback appletInitializedCallback;
+	void *appletInitializedUserData;
+	/* appletStartedCallback is called just after the applet has been started.
+	 * The callback might happen before JEPCreateJavaApplet() returns.  It
+	 * might be called on a secondary thread (not the main thread) -- though
+	 * as of JEP 0.8.7 it's always called on the main thread.
+	 */
+	JEPAppletStartedCallback appletStartedCallback;
+	void *appletStartedUserData;
+	void *instance; // For Mozilla.org browsers, a MRJPluginInstance*.
+} JEPOptions;
+
+/* JEPCheckBundleWithVersion() checks whether the Java Embedding Plugin
+ * matches the specified version string and has everything that it needs.
+ * Always call this first.  The version check prevents version mismatches
+ * between JavaEmbeddingPlugin.bundle and the MRJ Plugin JEP.  (As of JEP
+ * 0.8.7, this function replaces JEPCheckBundle(), which is no longer
+ * supported.)
+ */
+Boolean JEPCheckBundleWithVersion(CFStringRef version);
+/* JEPGetInstalledPath() returns the full path to the Java Embedding Plugin's
+ * location.
+ */
+CFStringRef JEPGetInstalledPath(void);
+/* Call JEPCreateJavaVM() instead of calling JNI_CreateJavaVM() directly --
+ * otherwise the JVM you create may not have all the options we need (such as
+ * an appropriate xbootclasspath).
+ */
+OSStatus JEPCreateJavaVM(JavaVMOption *jvmExtraOpts, int jvmExtraOptsNum,
+	JavaVM **vm, void **env);
+OSStatus JEPCreateJavaVMAndInitAWT(JavaVMOption *jvmExtraOpts,
+	int jvmExtraOptsNum, JavaVM **vm, void **env,
+	void (*runAfterInitAWT) (void *), void *runAfterInitAWTInfo);
+/* Given input from an HTML tag in either of the two standard forms
+ * (< ... "name"="value" ... > or <param name="name" value="value">),
+ * an entry in "attributes" should have "name" as its key and "value"
+ * as its value.  Only returns an error if appletCreatedCallback will
+ * _not_ be called.
+ */
+OSStatus JEPCreateJavaApplet(CFURLRef docbase, CFDictionaryRef attributes,
+	WindowRef parentWindow, JEPOptions *options, void **handle);
+OSStatus JEPGetJavaApplet(void *handle, jobject *applet);
+OSStatus JEPGetJavaVM(void *handle, JavaVM **vm);
+OSStatus JEPSetJavaAppletState(void *handle, AppletStateJEP newState);
+OSStatus JEPGetJavaAppletState(void *handle, AppletStateJEP *state);
+/* A call to JEPDrawJavaApplet() tells the JEP to redraw the (entire) applet.
+ * A call to JEPMaybeDrawJavaApplet() tells the JEP to redraw or not redraw
+ * the applet, at its own discretion -- a client makes this call if it thinks
+ * a given update might be excessive or unnecessary, but isn't completely
+ * sure.  For now I use JEPMaybeDrawJavaApplet() to deal with excessive
+ * updates from the Mozilla family of browsers, particularly recent versions
+ * of Camino (e.g. 0.9a1).
+ */
+OSStatus JEPDrawJavaApplet(void *handle);
+OSStatus JEPMaybeDrawJavaApplet(void *handle);
+/* Unlike their counterparts in the original Java Embedding API,
+ * JEPSuspendJavaAppletUpdates() and JEPResumeJavaAppletUpdates() suspend and
+ * resume _all_ updates -- not just asynchronous ones.  And calls to them
+ * may be nested.
+ */
+OSStatus JEPSuspendJavaAppletUpdates(void *handle);
+OSStatus JEPResumeJavaAppletUpdates(void *handle);
+OSStatus JEPSizeJavaApplet(void *handle, int width, int height);
+/* posX and posY are in JEPCreateJavaApplet's parentWindow's coordinate
+ * system.
+ */
+OSStatus JEPPositionJavaApplet(void *handle, int posX, int posY);
+/* posX and posY are in JEPCreateJavaApplet's parentWindow's coordinate
+ * system.
+ */
+OSStatus JEPMoveAndClipJavaApplet(void *handle, int posX, int posY,
+	int clipX, int clipY, int clipWidth, int clipHeight);
+OSStatus JEPShowHideJavaApplet(void *handle, Boolean visible);
+OSStatus JEPRegisterStatusCallback(void *handle,
+	JEPShowStatusCallback showStatusFunction, void *userData);
+OSStatus JEPRegisterShowDocumentCallback(void *handle,
+	JEPShowDocumentCallback showDocumentFunction, void * userData);
+/* Convenience functions to access Java Console "runtime parameters" from
+ * outside the JVM, possibly before it has been started.
+ */
+Boolean JEPGetJavaRuntimeParameterBoolean(CFStringRef key);
+CFStringRef JEPGetJavaRuntimeParameterString(CFStringRef key);
+/* Convenience function to log messages to System.out.
+ */
+OSStatus JEPLogJavaMessage(CFStringRef message);
+/* In Tiger (both Java 1.4.2_07 and 1.5.0), LiveConnect calls that trigger
+ * Java drawing can no longer be made on the main thread (hangs will result).
+ * But all the Mozilla-family's LiveConnect calls are made on the main
+ * thread, so we need a way to call some of them on another thread and wait
+ * for the results.  At the same time we can ensure that an autorelease pool
+ * is always present (a problem we used to use hookJNIRunnable in AppletView.m
+ * to fix).
+ */
+void JEPDoLiveConnectProxy(jclass proxyClass, jobject runnable, jobject applet,
+	jboolean isCallMethodCall);
+void JEPRunOnMainThread(void (*runnable) (void *), void *info, Boolean wait);
+/* JEPRunJRunnableOnMainThread is a hack, unused as of JEP 0.8.6, that might
+ * not stay in the Java Embedding Plugin API.
+ */
+jthrowable JEPRunJRunnableOnMainThread(jobject jrunnable);
+
+#ifdef __cplusplus
+}
+#endif
diff -U 10 -r -N old/plugin/oji/MRJCarbon/plugin/Source/JavaMessageQueue.h new/plugin/oji/MRJCarbon/plugin/Source/JavaMessageQueue.h
--- old/plugin/oji/MRJCarbon/plugin/Source/JavaMessageQueue.h	2003-06-11 00:11:42.000000000 -0500
+++ new/plugin/oji/MRJCarbon/plugin/Source/JavaMessageQueue.h	2006-11-06 10:37:41.000000000 -0600
@@ -37,34 +37,58 @@
 /*
 	JavaMessageQueue.h
  */
 
 #pragma once
 
 #ifndef JNI_H
 #include "jni.h"
 #endif
 
+#include "MRJPlugin.h"
+
 class Monitor;
 
-class JavaMessage {
+class JavaMessage : public nsISupports {
 public:
-	JavaMessage() : mNext(NULL) {}
-	virtual ~JavaMessage() {}
+	JavaMessage();
+	JavaMessage(MRJPluginInstance *pluginInstance);
+	virtual ~JavaMessage();
+
+	NS_DECL_ISUPPORTS
 
 	void setNext(JavaMessage* next) { mNext = next; }
 	JavaMessage* getNext() { return mNext; }
+	MRJPluginInstance *getPluginInstance() { return mPluginInstance; }
+	Boolean isFinalizeMessage() { return mIsFinalizeMessage; }
+	Boolean waitTilDone(long long millis = 0);
+	Boolean waitAWhile(long long millis = 2000);
+	void setIsDone(Boolean release = true);
+	Boolean timedOut(Boolean release = true);
+	/* In Tiger, we need to avoid making LiveConnect calls on the main thread
+	 * that might trigger Java drawing (using JEPDoLiveConnectProxy()).
+	 * Fortunately (since avoiding the main thread is very costly), only a
+	 * few calls (the CallMethod ones) need this treatment.
+	 */
+	void setCallMethodCall() { mCallMethodCall = true; }
+	Boolean isCallMethodCall() { return mCallMethodCall; }
 
 	virtual void execute(JNIEnv* env) = 0;
 
 private:
+	Boolean mDone;
+	Boolean mCallMethodCall;
 	JavaMessage* mNext;
+	Monitor *mMessageMonitor;
+protected:
+	MRJPluginInstance *mPluginInstance;
+	Boolean mIsFinalizeMessage;
 };
 
 class JavaMessageQueue {
 public:
 	JavaMessageQueue(Monitor* monitor);
 
 	void putMessage(JavaMessage* msg);
 	JavaMessage* getMessage();
 
 	void enter();
@@ -73,10 +97,32 @@
 	void wait();
 	void wait(long long millis);
 	void notify();
 
 private:
 	// Message queue.
 	JavaMessage* mFirst;
 	JavaMessage* mLast;
 	Monitor* mMonitor;
 };
+
+/*
+ * Wraps a JavaMessage in an nsIRunnable form, so that it runs on the correct
+ * native thread.
+ */
+class MessageRunnable : public JavaMessage, public nsIRunnable {
+public:
+    MessageRunnable(nsPluginThreadPtr threadID, JavaMessage* msg);
+    virtual ~MessageRunnable();
+
+    NS_DECL_ISUPPORTS_INHERITED
+
+    virtual void execute(JNIEnv* env);
+
+    NS_IMETHOD Run();
+    static void RunAlt(void *info);
+
+private:
+    nsPluginThreadPtr mThreadID;
+    JavaMessage* mMessage;
+};
+
diff -U 10 -r -N old/plugin/oji/MRJCarbon/plugin/Source/JNIUtils.java new/plugin/oji/MRJCarbon/plugin/Source/JNIUtils.java
--- old/plugin/oji/MRJCarbon/plugin/Source/JNIUtils.java	2003-06-11 00:11:42.000000000 -0500
+++ new/plugin/oji/MRJCarbon/plugin/Source/JNIUtils.java	2006-12-06 09:44:01.000000000 -0600
@@ -33,48 +33,302 @@
  * the terms of any one of the MPL, the GPL or the LGPL.
  *
  * ----- END LICENSE BLOCK ----- */
 
 /*
 	JNIUtils.java
  */
 
 package netscape.oji;
 
+import java.lang.reflect.*;
+import java.security.CodeSource;
+import java.security.ProtectionDomain;
+import java.security.cert.Certificate;
+
+import java.util.Stack;
+import java.util.EmptyStackException;
+
 public class JNIUtils {
 	/**
 	 * Returns a local reference for a passed-in global reference.
 	 */
 	public static Object NewLocalRef(Object object) {
 		return object;
 	}
 	
 	/**
 	 * Returns the currently running thread.
 	 */
 	public static Object GetCurrentThread() {
 		return Thread.currentThread();
 	}
-	
-	
+
+	public static void checkClassAccess(Class clazz) {
+		//System.out.println("JNIUtils.checkClassAccess(Class): class is " + clazz.getName());
+		checkClassAccess(clazz.getName());
+	}
+
+	// At least in Java versions prior to 1.4.2_06 (of which there isn't yet
+	// any Apple release), Class.forName() doesn't always work properly when
+	// doing JavaScript-to-Java LiveConnect.  I'm not sure why this is the
+	// case, but it seems that calls to SecurityManager.checkPackageAccess()
+	// and possibly also ClassLoader.loadClass() are sometimes being missed.
+	// I work around this problem by hooking calls to Class.forName0() (in
+	// MRJSession.cpp), calling this method, then calling checkPackageAccess()
+	// if we're doing JavaScript-to-Java LiveConnect (which we are if the top
+	// class of the current class context is netscape.oji.LiveConnectProxy).
+	// See the following URLs for more info and a proof of concept:
+	// http://securityfocus.com/archive/1/382072/2004-11-23/2004-11-29/0
+	// http://securityfocus.com/archive/1/381940/2004-11-16/2004-11-22/0
+	public static void checkClassAccess(String name) {
+		Class[] classContext = stubManager.getCurrentClassContext();
+		//String topClassName =
+		//	classContext[classContext.length-1].getName().replace('/', '.');
+		//System.out.println("JNIUtils.checkClassAccess(String): name is " + name +
+		//	" topClassName is " + topClassName);
+		if (!inLiveConnect(classContext))
+			return;
+		// The following is based on code found in URLClassLoader.loadClass()
+		// and AppletClassLoader.loadClass(), among other places.  I'm not
+		// sure it's all really necessary.  But I've noticed that class names
+		// can sometimes have wierd formats (e.g. "[A" and "[B"), so I'm
+		// keeping it just in case.
+		String pkg = name.replace('/', '.');
+		if (pkg.startsWith("[")) {
+			int b = pkg.lastIndexOf('[') + 2;
+			if (b > 1 && b < pkg.length()) {
+				pkg = pkg.substring(b);
+			}
+		}
+		int i = pkg.lastIndexOf('.');
+		if (i != -1) {
+			pkg = pkg.substring(0, i);
+			System.getSecurityManager().checkPackageAccess(pkg);
+		}
+	}
+
+	// This is called from our hook for AccessController.
+	// getStackAccessControlContext() in MRJSession.cpp.  I use it to fix a
+	// design flaw in the LiveConnect implementation of the original MRJ
+	// Plugin -- it sometimes failed to elevate a signed applet's privileges
+	// when the applet's code was called via LiveConnect.  My fix is to reset
+	// the LiveConnectProxy class's protection domain, when appropriate, just
+	// before a call to getStackAccessControlContext() (which takes place
+	// before every permission check).  I only do this during JavaScript-to-
+	// Java LiveConnect.  The effect is to either increase or decrease our
+	// privileges.  If the protection domain of the "top" class
+	// (netscape.oji.LiveConnectProxy) currently has ordinary privileges but
+	// the protection domain of one of the other classes in the execution
+	// stack has certificates, I take this to mean that a signed applet (with
+	// elevated privileges) has been loaded.  If no other class has a cert-
+	// less protection domain (which would cancel our elevated privileges), I
+	// replace the "top" class's protection domain with the "highest" one that
+	// has certificates (which gives the currently running code elevated
+	// privileges).  On the other hand, if the top class currently has
+	// elevated privileges but at least one class has a cert-less protection
+	// domain, I take this to mean that we're currently running code from an
+	// unsigned applet (with no special privileges).  In this case I replace
+	// the top class's protection domain with the "highest" cert-less
+	// protection domain.  I try to make these changes only as needed, for the
+	// sake of efficiency.  It's probably not necessary to downgrade the top
+	// class's protection domain -- the presence of a cert-less protection
+	// domain in the "stack" should stop privileged actions from taking place.
+	// I'm doing it on general principles (just in case) -- I'm worried about
+	// the possibility that an unsigned applet loaded from the same page as a
+	// signed applet might run with the signed applet's privileges (if both
+	// were called via LiveConnect and the unsigned applet was called after
+	// the signed one).
+	public static void fixProtectionDomains() {
+		Class[] classContext = stubManager.getCurrentClassContext();
+		if (!inLiveConnect(classContext))
+			return;
+		int topPDClassOffset = getTopPDClassOffset(classContext);
+		if (topPDClassOffset == -1)
+			return;
+
+		Class topPDClass = classContext[topPDClassOffset];
+		//String topPDClassName = topPDClass.getName().replace('/', '.');
+		//System.out.println("JNIUtils.fixProtectionDomains(): " +
+		//	" topPDClassName is " + topPDClassName);
+		ProtectionDomain topPD = getClassProtectionDomain(topPDClass);
+		boolean topPDHasCerts = false;
+		CodeSource cs = topPD.getCodeSource();
+		Certificate[] certs;
+		if (cs != null) {
+			certs = cs.getCertificates();
+			if (certs != null)
+				topPDHasCerts = true;
+		}
+		ProtectionDomain nextPDWithCerts = null;
+		ProtectionDomain nextPDWithoutCerts = null;
+		for (int i = 1; i <= topPDClassOffset; ++i) {
+			ProtectionDomain pd = getClassProtectionDomain(classContext[i-1]);
+			if (pd == null)
+				continue;
+			boolean hasCerts = false;
+			cs = pd.getCodeSource();
+			if (cs != null) {
+				certs = cs.getCertificates();
+				if (certs != null)
+					hasCerts = true;
+			}
+			if (hasCerts) {
+				nextPDWithCerts = pd;
+			} else {
+				nextPDWithoutCerts = pd;
+			}
+		}
+
+		//String topPDClassName = topPDClass.getName().replace('/', '.');
+		if (topPDHasCerts) {
+			if (nextPDWithoutCerts != null) {
+				//System.out.println("JNIUtils.fixProtectionDomains(): Setting topPDClass " +
+				//	topPDClassName + "'s pd to one without certs");
+				setClassProtectionDomain(topPDClass, nextPDWithoutCerts);
+				topPD = nextPDWithoutCerts;
+			}
+		} else if ((nextPDWithCerts != null) && (nextPDWithoutCerts == null)) {
+			//System.out.println("JNIUtils.fixProtectionDomains(): Setting topPDClass " +
+			//	topPDClassName + "'s pd to one with certs");
+			setClassProtectionDomain(topPDClass, nextPDWithCerts);
+			topPD = nextPDWithCerts;
+		}
+	}
+
+	// Check if we're doing LiveConnect either directly (in which case the
+	// top class is always netscape.oji.LiveConnectProxy) or via
+	// JEPRunOnLiveConnectThread() (in which case the top class is
+	// java.awt.EventDispatchThread and netscape.oji.LiveConnectProxy is
+	// a few classes below it).
+	protected static boolean inLiveConnect(Class[] classContext) {
+		int elements = classContext.length;
+		String topClassName = classContext[elements-1].getName().replace('/', '.');
+		if (topClassName.equals("netscape.oji.LiveConnectProxy"))
+			return true;
+		if (!topClassName.equals("java.awt.EventDispatchThread"))
+			return false;
+		for (int i = 1; i <= elements; ++i) {
+			String className = classContext[i-1].getName().replace('/', '.');
+			if (className.equals("netscape.oji.LiveConnectProxy"))
+				return true;
+		}
+		return false;
+	}
+
+	// Returns the (zero-based) offset of the topmost class that has a
+	// protection domain, or -1 if none of them do.
+	protected static int getTopPDClassOffset(Class[] classContext) {
+		for (int i = classContext.length - 1; i >= 0; --i) {
+			ProtectionDomain pd = getClassProtectionDomain(classContext[i]);
+			if (pd == null)
+				continue;
+			return i;
+		}
+		return -1;
+	}
+
+	private static native ProtectionDomain getClassProtectionDomain(Class clazz);
+	private static native void setClassProtectionDomain(Class clazz,
+		ProtectionDomain newProtectionDomain);
+
 	/**
 	 * Stub SecurityManager class, to expose access to class loaders.
 	 */
 	static class StubSecurityManager extends SecurityManager {
+		// We generally call this from a thread with AllPermission, so
+		// currentClassLoader() will generally no longer work here.
 		public ClassLoader getCurrentClassLoader() {
-			return currentClassLoader();
+			ClassLoader retval = null;
+			ClassLoader systemLoader = ClassLoader.getSystemClassLoader();
+			Class[] classContext = getClassContext();
+			for (int i = 1; i <= classContext.length; ++i) {
+				ClassLoader loader = null;
+				try {
+					loader = classContext[i-1].getClassLoader();
+				} catch (SecurityException ex) {
+					loader = currentClassLoader();
+				}
+				if ((loader != null) && !systemLoader.equals(loader)) {
+					retval = loader;
+					break;
+				}
+			}
+			return retval;
+		}
+		public Class[] getCurrentClassContext() {
+			return getClassContext();
 		}
 	}
 	
 	private static StubSecurityManager stubManager = new StubSecurityManager();
 	
 	/**
 	 * Returns the current class loader.
 	 */
 	public static Object GetCurrentClassLoader() {
 		return stubManager.getCurrentClassLoader();
 	}
 	
 	public static Object GetObjectClassLoader(Object object) {
 		return object.getClass().getClassLoader();
 	}
+
+	// PushLCInfo(), PopLCInfo() and friends are needed to get around a design
+	// flaw in how the OJI interface creates JSObject objects -- it uses an
+	// nsIPlugin method (GetJavaWrapper()) to create them (instead of an
+	// nsIPluginInstance method), and therefore provides no easy way to
+	// associate them with a particular plugin instance.  This is important
+	// for a couple of reasons:  1) When a JSObject method is called from a
+	// Java applet's instance method, we should run the method in the security
+	// context of the plugin instance correponding to the applet.  2) When a
+	// Java method is called on a non-applet Java object during JavaScript-to-
+	// Java LiveConnect, and this call was initiated (however indirectly) from
+	// a Java applet instance, the method should run in the AppContext of the
+	// Java applet instance.  But neither Java nor JavaScript gives us any way
+	// of knowing which applet we're running under.  (These problems don't
+	// arise when using an applet's static methods.)  We get around these
+	// problems by assuming that only one plugin instance will be doing
+	// JavaScript-to-Java LiveConnect at any one time, and that only one
+	// JavaScript-to-Java or Java-to-JavaScript call will be running at any
+	// one time (since they all get processed on the main thread).  So we can
+	// keep a stack of "current" plugin instances, and "push" and "pop" these
+	// as appropriate (before and after every JavaScript-to-Java or Java-to-
+	// JavaScript call, on the main thread).
+	private static Object lcInfoLock = new Object();
+	private static Stack lcInfo = new Stack();
+
+	public static void PushLCInfo(int pluginInstance)
+	{
+		synchronized (lcInfoLock) {
+			int newInfo[] = {0};
+			try {
+				newInfo = (int[]) lcInfo.peek();
+			} catch (EmptyStackException e) {
+			}
+			if (pluginInstance != 0)
+				newInfo[0] = pluginInstance;
+			lcInfo.push(newInfo);
+		}
+	}
+
+	public static void PopLCInfo() {
+		synchronized (lcInfoLock) {
+			try {
+				lcInfo.pop();
+			} catch (EmptyStackException e) {
+			}
+		}
+	}
+
+	public static int CurrentLCPluginInstance() {
+		synchronized (lcInfoLock) {
+			int currentInfo[] = {0};
+			try {
+				currentInfo = (int[]) lcInfo.peek();
+			} catch (EmptyStackException e) {
+			}
+			return currentInfo[0];
+		}
+	}
+
 }
diff -U 10 -r -N old/plugin/oji/MRJCarbon/plugin/Source/LiveConnectNativeMethods.cpp new/plugin/oji/MRJCarbon/plugin/Source/LiveConnectNativeMethods.cpp
--- old/plugin/oji/MRJCarbon/plugin/Source/LiveConnectNativeMethods.cpp	2003-06-11 00:11:44.000000000 -0500
+++ new/plugin/oji/MRJCarbon/plugin/Source/LiveConnectNativeMethods.cpp	2007-02-22 11:35:30.000000000 -0600
@@ -35,186 +35,421 @@
  * ----- END LICENSE BLOCK ----- */
 
 /*
     LiveConnectNativeMethods.cpp
  */
 
 #include <memory>
 
 #include "LiveConnectNativeMethods.h"
 
-#include "nsIComponentManagerObsolete.h"
+/* Two and a half years ago the MRJ Plugin changed from using
+ * nsIComponentManager to using nsIComponentManagerObsolete, to preserve
+ * binary compatibility with older Mozilla (pre 0.9.4?) versions after
+ * the original nsIComponentManager interface was "obsoleted"
+ * (https://bugzilla.mozilla.org/show_bug.cgi?id=129250#c10 and
+ * https://bugzilla.mozilla.org/show_bug.cgi?id=98553).  Now we need to
+ * undo this change, because Mozilla.org is about to dump support for the
+ * nsIComponentManagerObsolete interface
+ * (https://bugzilla.mozilla.org/show_bug.cgi?id=267040).  Binary
+ * compatibility with pre-1.0 versions should no longer be a concern.
+ */
+#include "nsIComponentManager.h"
 #include "nsIPluginManager.h"
 #include "nsIJVMManager.h"
 #include "nsILiveconnect.h"
+#include "nsISecureLiveconnect.h"
 #include "nsIPluginInstancePeer2.h"
 
+#ifndef NS_COMPONENTMANAGER_CID
+#define NS_COMPONENTMANAGER_CID                      \
+{ /* 91775d60-d5dc-11d2-92fb-00e09805570f */         \
+    0x91775d60,                                      \
+    0xd5dc,                                          \
+    0x11d2,                                          \
+    {0x92, 0xfb, 0x00, 0xe0, 0x98, 0x05, 0x57, 0x0f} \
+}
+#endif
+
 #include "MRJPlugin.h"
 #include "MRJContext.h"
 #include "MRJSession.h"
 #include "MRJSecurityContext.h"
 #include "CSecureEnv.h"
 #include "JavaMessageQueue.h"
 #include "MRJMonitor.h"
 #include "NativeMonitor.h"
-#include "RunnableMixin.h"
 #include "StringUtils.h"
 
 #include "netscape_javascript_JSObject.h"   /* javah-generated headers */
 
+#include "jsapi.h"
+#import <mach-o/dyld.h>
+#import "JavaEmbeddingPlugin.h"
+extern "C" Boolean JEPCheckBundle();
+static unsigned jsObjectTimeout = 2000;  /* In milliseconds */
+
 extern nsIPluginManager* thePluginManager;
+extern Boolean IsNested(void);
+extern void ProcessMainThreadEvents(void);
 
-static MRJPlugin* theJVMPlugin = NULL;
+extern MRJPlugin *theJVMPlugin;
 static nsILiveconnect* theLiveConnectManager = NULL;
-static nsIComponentManagerObsolete* theComponentManager = NULL;
+static nsIComponentManager* theComponentManager = NULL;
+nsPluginThreadPtr theJavaScriptThread = 0;
+Boolean liveConnectInited = false;
 
 static jclass netscape_javascript_JSObject = NULL;
-static jmethodID netscape_javascript_JSObject_JSObject;
-static jfieldID netscape_javascript_JSObject_internal;
+static jmethodID netscape_javascript_JSObject_JSObject_applet = NULL;
+static jmethodID netscape_javascript_JSObject_JSObject_instance = NULL;
+static jmethodID netscape_javascript_JSObject_getApplet = NULL;
+static jmethodID netscape_javascript_JSObject_getPluginInstance = NULL;
+static jfieldID netscape_javascript_JSObject_internal = NULL;
 
 static jclass netscape_oji_JNIUtils = NULL;
 static jmethodID netscape_oji_JNIUtils_NewLocalRef = NULL;
 static jmethodID netscape_oji_JNIUtils_GetCurrentThread = NULL;
 static jmethodID netscape_oji_JNIUtils_GetCurrentClassLoader = NULL;
 static jmethodID netscape_oji_JNIUtils_GetObjectClassLoader = NULL;
+static jmethodID netscape_oji_JNIUtils_PushLCInfo = NULL;
+static jmethodID netscape_oji_JNIUtils_PopLCInfo = NULL;
+static jmethodID netscape_oji_JNIUtils_CurrentLCPluginInstance = NULL;
 
 static NS_DEFINE_IID(kLiveConnectCID, NS_CLIVECONNECT_CID);
 static NS_DEFINE_IID(kComponentManagerCID, NS_COMPONENTMANAGER_CID);
 
-static nsresult getGlobalComponentManager(nsIComponentManagerObsolete* *result)
+static nsresult getGlobalComponentManager(nsIComponentManager* *result)
 {
-    return MRJPlugin::GetService(kComponentManagerCID, NS_GET_IID(nsIComponentManagerObsolete), (void**)result);
+    return MRJPlugin::GetService(kComponentManagerCID, NS_GET_IID(nsIComponentManager), (void**)result);
 }
 
-nsresult InitLiveConnectSupport(MRJPlugin* jvmPlugin)
-{
-    theJVMPlugin = jvmPlugin;
+static MRJMonitor *callEvalMonitor = NULL;
+
+static MRJSecurityContext *staticSecurityContext = NULL;
+
+// From js/src/liveconnect/jsj_private.h
+struct JSObjectHandle {
+    JSObject *js_obj;
+    void *rt;	// Originally JSRuntime *rt
+};
+typedef struct JSObjectHandle JSObjectHandle;
+
+//JSRuntime *JS_GetRuntime(JSContext *cx);
+//void *JS_malloc(JSContext *cx, size_t nbytes);
+//void JS_ClearPendingException(JSContext *cx);
+typedef void * (*JSGETRUNTIME) (JSContext *);
+typedef void * (*JSMALLOC) (JSContext *, size_t);
+typedef void (*JSCLEAREXCEPTION) (JSContext *);
+static JSGETRUNTIME JS_GetRuntimePtr = NULL;
+static JSMALLOC JS_mallocPtr = NULL;
+static JSCLEAREXCEPTION JS_ClearPendingExceptionPtr = NULL;
+
+static Boolean findJSUtils(void)
+{
+	unsigned long i, count;
+	NSSymbol symbol = nil;
+	const struct mach_header *image = nil;
+	count = _dyld_image_count();
+	if (JS_GetRuntimePtr && JS_mallocPtr && JS_ClearPendingExceptionPtr)
+		return true;
+	for (i = 1; i <= count; ++i) {
+		image = (const struct mach_header *) _dyld_get_image_header(i - 1);
+		if (!JS_GetRuntimePtr) {
+			symbol = NSLookupSymbolInImage(image, "_JS_GetRuntime",
+				NSLOOKUPSYMBOLINIMAGE_OPTION_RETURN_ON_ERROR);
+			if (symbol)
+				JS_GetRuntimePtr = (JSGETRUNTIME) NSAddressOfSymbol(symbol);
+		}
+		if (!JS_mallocPtr) {
+			symbol = NSLookupSymbolInImage(image, "_JS_malloc",
+				NSLOOKUPSYMBOLINIMAGE_OPTION_RETURN_ON_ERROR);
+			if (symbol)
+				JS_mallocPtr = (JSMALLOC) NSAddressOfSymbol(symbol);
+		}
+		if (!JS_ClearPendingExceptionPtr) {
+			symbol = NSLookupSymbolInImage(image, "_JS_ClearPendingException",
+				NSLOOKUPSYMBOLINIMAGE_OPTION_RETURN_ON_ERROR);
+			if (symbol) {
+				JS_ClearPendingExceptionPtr = (JSCLEAREXCEPTION)
+					NSAddressOfSymbol(symbol);
+			}
+		}
+		if (JS_GetRuntimePtr && JS_mallocPtr && JS_ClearPendingExceptionPtr)
+			return true;
+	}
+	return false;
+}
+
+nsresult InitLiveConnectSupport(MRJPlugin *jvmPlugin)
+{
+    if (!jvmPlugin)
+        return NS_ERROR_FAILURE;
+
+    findJSUtils();
+
+    /* See JavaEmbeddingPlugin.h for info */
+    if (JEPGetJavaRuntimeParameterBoolean(CFSTR(JEP_JSOBJECT_NOTIMEOUT_OPTION)))
+       jsObjectTimeout = 0;
 
     getGlobalComponentManager(&theComponentManager);
 
     nsresult result = MRJPlugin::GetService(kLiveConnectCID, NS_GET_IID(nsILiveconnect),
                                             (void**)&theLiveConnectManager);
     if (result != NS_OK)
         return result;
-    
+
+    /* This needs to be created as early as possible -- if it's created on
+     * demand, we may end up with more than one of it (which makes it useless
+     * as a "monitor").
+     */
+    callEvalMonitor = new MRJMonitor(jvmPlugin->getSession());
+
+    staticSecurityContext = new MRJSecurityContext(NULL);
+    NS_IF_ADDREF(staticSecurityContext);
+
     // Manually load the required native methods.
     static JNINativeMethod nativeMethods[] = {
         "getMember", "(Ljava/lang/String;)Ljava/lang/Object;", (void*)&Java_netscape_javascript_JSObject_getMember,
         "getSlot", "(I)Ljava/lang/Object;", (void*)&Java_netscape_javascript_JSObject_getSlot,
         "setMember", "(Ljava/lang/String;Ljava/lang/Object;)V", (void*)&Java_netscape_javascript_JSObject_setMember,
         "setSlot", "(ILjava/lang/Object;)V", (void*)&Java_netscape_javascript_JSObject_setSlot,
         "removeMember", "(Ljava/lang/String;)V", (void*)&Java_netscape_javascript_JSObject_removeMember,
         "call", "(Ljava/lang/String;[Ljava/lang/Object;)Ljava/lang/Object;", (void*)&Java_netscape_javascript_JSObject_call,
         "eval", "(Ljava/lang/String;)Ljava/lang/Object;", (void*)&Java_netscape_javascript_JSObject_eval,
         "toString", "()Ljava/lang/String;", (void*)&Java_netscape_javascript_JSObject_toString,
         "getWindow", "(Ljava/applet/Applet;)Lnetscape/javascript/JSObject;", (void*)&Java_netscape_javascript_JSObject_getWindow,
         "finalize", "()V", (void*)&Java_netscape_javascript_JSObject_finalize,
     };
     
     MRJSession* session = jvmPlugin->getSession();
     JNIEnv* env = session->getCurrentEnv();
     if (env != NULL) {
+        // load netscape.oji.JNIUtils class.
+        jclass classJNIUtils = env->FindClass("netscape/oji/JNIUtils");
+        if (classJNIUtils != NULL) {
+            netscape_oji_JNIUtils = (jclass) env->NewGlobalRef(classJNIUtils);
+            env->DeleteLocalRef(classJNIUtils);
+            netscape_oji_JNIUtils_NewLocalRef = env->GetStaticMethodID(netscape_oji_JNIUtils, "NewLocalRef", "(Ljava/lang/Object;)Ljava/lang/Object;");
+            netscape_oji_JNIUtils_GetCurrentThread = env->GetStaticMethodID(netscape_oji_JNIUtils, "GetCurrentThread", "()Ljava/lang/Object;");
+            netscape_oji_JNIUtils_GetCurrentClassLoader = env->GetStaticMethodID(netscape_oji_JNIUtils, "GetCurrentClassLoader", "()Ljava/lang/Object;");
+            netscape_oji_JNIUtils_GetObjectClassLoader = env->GetStaticMethodID(netscape_oji_JNIUtils, "GetObjectClassLoader", "(Ljava/lang/Object;)Ljava/lang/Object;");
+            netscape_oji_JNIUtils_PushLCInfo = env->GetStaticMethodID(netscape_oji_JNIUtils, "PushLCInfo", "(I)V");
+            netscape_oji_JNIUtils_PopLCInfo = env->GetStaticMethodID(netscape_oji_JNIUtils, "PopLCInfo", "()V");
+            netscape_oji_JNIUtils_CurrentLCPluginInstance = env->GetStaticMethodID(netscape_oji_JNIUtils, "CurrentLCPluginInstance", "()I");
+        }
+
         jclass classJSObject = env->FindClass("netscape/javascript/JSObject");
         if (classJSObject != NULL) {
             // register LiveConnect native methods.
             netscape_javascript_JSObject = (jclass) env->NewGlobalRef(classJSObject);
             env->DeleteLocalRef(classJSObject);
             
-            netscape_javascript_JSObject_JSObject = env->GetMethodID(netscape_javascript_JSObject, "<init>", "(I)V");
+            netscape_javascript_JSObject_JSObject_applet = env->GetMethodID(netscape_javascript_JSObject, "<init>", "(ILjava/applet/Applet;)V");
+            if (env->ExceptionCheck()) {
+                env->ExceptionClear();
+                result = NS_ERROR_FAILURE;
+            }
+
+            netscape_javascript_JSObject_JSObject_instance = env->GetMethodID(netscape_javascript_JSObject, "<init>", "(II)V");
+            if (env->ExceptionCheck()) {
+                env->ExceptionClear();
+                result = NS_ERROR_FAILURE;
+            }
+
+            netscape_javascript_JSObject_getApplet = env->GetMethodID(netscape_javascript_JSObject, "getApplet", "()Ljava/applet/Applet;");
+            if (env->ExceptionCheck()) {
+                env->ExceptionClear();
+                result = NS_ERROR_FAILURE;
+            }
+
+            netscape_javascript_JSObject_getPluginInstance = env->GetMethodID(netscape_javascript_JSObject, "getPluginInstance", "()I");
             if (env->ExceptionCheck()) {
                 env->ExceptionClear();
                 result = NS_ERROR_FAILURE;
             }
 
             netscape_javascript_JSObject_internal = env->GetFieldID(netscape_javascript_JSObject, "internal", "I");
             if (env->ExceptionCheck()) {
                 env->ExceptionClear();
                 result = NS_ERROR_FAILURE;
             }
 
             env->RegisterNatives(netscape_javascript_JSObject, nativeMethods, sizeof(nativeMethods) / sizeof(JNINativeMethod));
             if (env->ExceptionCheck()) {
                 env->ExceptionClear();
                 result = NS_ERROR_FAILURE;
             }
         }
-        
-        // load netscape.oji.JNIUtils class.
-        jclass classJNIUtils = env->FindClass("netscape/oji/JNIUtils");
-        if (classJNIUtils != NULL) {
-            netscape_oji_JNIUtils = (jclass) env->NewGlobalRef(classJNIUtils);
-            env->DeleteLocalRef(classJNIUtils);
-            netscape_oji_JNIUtils_NewLocalRef = env->GetStaticMethodID(netscape_oji_JNIUtils, "NewLocalRef", "(Ljava/lang/Object;)Ljava/lang/Object;");
-            netscape_oji_JNIUtils_GetCurrentThread = env->GetStaticMethodID(netscape_oji_JNIUtils, "GetCurrentThread", "()Ljava/lang/Object;");
-            netscape_oji_JNIUtils_GetCurrentClassLoader = env->GetStaticMethodID(netscape_oji_JNIUtils, "GetCurrentClassLoader", "()Ljava/lang/Object;");
-            netscape_oji_JNIUtils_GetObjectClassLoader = env->GetStaticMethodID(netscape_oji_JNIUtils, "GetObjectClassLoader", "(Ljava/lang/Object;)Ljava/lang/Object;");
-        }
     }
-    
+
     return result;
 }
 
+nsresult PostInitLiveConnectSupport(MRJPlugin *jvmPlugin)
+{
+    if (!jvmPlugin)
+        return NS_ERROR_FAILURE;
+    theJVMPlugin = jvmPlugin;
+    liveConnectInited = true;
+    return noErr;
+}
+
 nsresult ShutdownLiveConnectSupport()
 {
+    theJVMPlugin = NULL;
+    liveConnectInited = false;
+    
+    NS_IF_RELEASE(staticSecurityContext);
+
     NS_IF_RELEASE(theLiveConnectManager);
     NS_IF_RELEASE(theComponentManager);
     
-    if (theJVMPlugin != NULL) {
-        theJVMPlugin = NULL;
-    }
-    
     return NS_OK;
 }
 
+static jobject ToGlobalRef(JNIEnv* env, jobject localRef);
+
+jobject Wrap_JSObject(JNIEnv *env, jsobject js_obj, jobject applet)
+{
+    jobject retval = env->NewObject(netscape_javascript_JSObject,
+        netscape_javascript_JSObject_JSObject_applet, js_obj, applet);
+    if (retval)
+        retval = ToGlobalRef(env, retval);
+    return retval;
+}
+
+jobject Wrap_JSObject(JNIEnv *env, jsobject js_obj, MRJPluginInstance *instance)
+{
+    jobject retval = env->NewObject(netscape_javascript_JSObject,
+        netscape_javascript_JSObject_JSObject_instance, js_obj, (jint) instance);
+    if (retval)
+        retval = ToGlobalRef(env, retval);
+    return retval;
+}
+
+jobject GetAppletForWrapper(JNIEnv *env, jobject java_wrapper_obj)
+{
+    jobject retval = env->CallObjectMethod(java_wrapper_obj,
+        netscape_javascript_JSObject_getApplet);
+    if (retval)
+        retval = ToGlobalRef(env, retval);
+    return retval;
+}
+
+MRJPluginInstance *GetInstanceForWrapper(JNIEnv *env, jobject java_wrapper_obj)
+{
+    return (MRJPluginInstance *) env->CallObjectMethod(java_wrapper_obj,
+        netscape_javascript_JSObject_getPluginInstance);
+}
+
+/* Wrap_JSObject() and Unwrap_JSObject() may, like ToGlobalRef() below, be
+ * called either from a "Java thread" or a "native thread".  We need the
+ * same fix here that we use in ToGlobalRef().  See that routine for more
+ * info.
+ */
 jobject Wrap_JSObject(JNIEnv* env, jsobject js_obj)
 {
+    if (!theJVMPlugin)
+        return (jobject) NULL;
+    MRJSession* session = theJVMPlugin->getSession();
+    env = session->getCurrentEnv();
     jmethodID constructorID = env->GetMethodID(netscape_javascript_JSObject, "<init>", "(I)V");
-    return env->NewObject(netscape_javascript_JSObject, constructorID, js_obj);
+    jobject retval = NULL;
+    jobject obj = env->NewObject(netscape_javascript_JSObject, constructorID, js_obj);
+    if (obj) {
+        retval = env->NewGlobalRef(obj);
+        env->DeleteLocalRef(obj);
+    }
+    return retval;
 }
 
 jsobject Unwrap_JSObject(JNIEnv* env, jobject java_wrapper_obj)
 {
+    if (!theJVMPlugin)
+        return (jsobject) NULL;
+    MRJSession* session = theJVMPlugin->getSession();
+    env = session->getCurrentEnv();
     return env->GetIntField(java_wrapper_obj, netscape_javascript_JSObject_internal);
 }
 
 static jobject NewLocalRef(JNIEnv* env, jobject global_ref)
 {
     return env->CallStaticObjectMethod(netscape_oji_JNIUtils, netscape_oji_JNIUtils_NewLocalRef, global_ref);
 }
 
+/* This routine may be called either from a "Java thread" (with 'env' set to a
+ * pointer to an ordinary JNIEnv structure) or from a "native thread" (with
+ * 'env' set to a pointer to a ProxyJNIEnv class).  The calls from Java
+ * threads work fine.  And so should the calls from native threads -- the
+ * ProxyJNIEnv class is just a subclass of the JNIEnv structure, and similar
+ * calls work fine inside the browser.  But inside the MRJ Plugin, for some
+ * reason the compiler "forgets" (or never knows) that it's dealing with a
+ * ProxyJNIEnv pointer, which leads to crashes when this routine tries to
+ * call NewGlobalRef() (presumably what the compiler thinks is the function
+ * pointer really is something else).  The easiest fix for this is to use
+ * MRJSession.cpp's getCurrentEnv() to make sure that we're always dealing
+ * with an ordinary JNIEnv pointer.
+ */
 static jobject ToGlobalRef(JNIEnv* env, jobject localRef)
 {
+    if (!theJVMPlugin || !localRef)
+        return NULL;
+    MRJSession* session = theJVMPlugin->getSession();
+    env = session->getCurrentEnv();
     jobject globalRef = env->NewGlobalRef(localRef);
     env->DeleteLocalRef(localRef);
     return globalRef;
 }
 
 static jobject ToLocalRef(JNIEnv* env, jobject globalRef)
 {
+    if (!globalRef)
+        return NULL;
     jobject localRef = NewLocalRef(env, globalRef);
     env->DeleteGlobalRef(globalRef);
     return localRef;
 }
 
+#if 0
 static jobject GetCurrentThread(JNIEnv* env)
 {
     return env->CallStaticObjectMethod(netscape_oji_JNIUtils, netscape_oji_JNIUtils_GetCurrentThread);
 }
+#endif
+
+static JSContext *getJSContext(MRJPluginInstance *pluginInstance)
+{
+    JSContext *context = NULL;
+    if (MRJPluginInstance::isValidInstance(pluginInstance)) {
+        nsIPluginInstancePeer *peer;
+        if (pluginInstance->GetPeer(&peer) == NS_OK) {
+            nsIPluginInstancePeer2 *peer2 = NULL;
+            if (peer->QueryInterface(NS_GET_IID(nsIPluginInstancePeer2), (void**) &peer2) == NS_OK) {
+                if (peer2->GetJSContext(&context) != NS_OK)
+                    context = NULL;
+                NS_RELEASE(peer2);
+            }
+            NS_RELEASE(peer);
+        }
+    }
+    return context;
+}
 
 /**
  * Security Considerations.
  */
 
 MRJSecurityContext::MRJSecurityContext(const char* location)
     :   mLocation(nsnull), mConnection(nsnull)
 {
-    mLocation = ::strdup(location);
+    if (location)
+        mLocation = ::strdup(location);
     if (mLocation) {
         // find the 3rd slash of the URL, hopefully it's in canonical form.
         char* colon = ::strchr(mLocation, ':');
         if (colon) {
             if (colon[1] == '/' && colon[2] == '/') {
                 char* slash = ::strchr(colon + 3, '/');
                 if (slash) *slash = '\0';
             }
         }
     }
@@ -239,228 +474,306 @@
 
 NS_METHOD MRJSecurityContext::Implies(const char* target, const char* action, PRBool *bAllowedAccess)
 {
     *bAllowedAccess = (target != NULL && action == NULL);
     return NS_OK;
 }
 
 NS_METHOD 
 MRJSecurityContext::GetOrigin(char* buf, int len)
 {
-    char* origin = nsnull;
     if (mLocation) {
         ::strncpy(buf, mLocation, len);
         return NS_OK;
     }
     return NS_ERROR_FAILURE;
 }
 
 NS_METHOD 
 MRJSecurityContext::GetCertificateID(char* buf, int len)
 {
     // ACTION: Implement me.
     return NS_ERROR_NOT_IMPLEMENTED;
 }
 
 // NOTE:  this a weak reference to the MRJSecurityContext associated with this
 // plugin instance. The MRJSecurityContext is owned by the MRJContext.
 
 static MRJSecurityContext* getSecurityContext(MRJPluginInstance* pluginInstance)
 {
-    if (pluginInstance != NULL) {
+    if (MRJPluginInstance::isValidInstance(pluginInstance)) {
         MRJContext* context = pluginInstance->getContext();
+        if (context == NULL)
+            return NULL;
         MRJSecurityContext* securityContext = context->getSecurityContext();
         if (securityContext == NULL) {
             securityContext = new MRJSecurityContext(context->getDocumentBase());
             context->setSecurityContext(securityContext);
         }
         return securityContext;
     }
     return NULL;
 }
 
 inline nsILiveconnect* getLiveconnectInstance(MRJSecurityContext* securityContext)
 {
+    if (!theJVMPlugin)
+        return NULL;
     return (securityContext ? securityContext->getConnection() : theLiveConnectManager);
 }
 
 static jobject GetCurrentClassLoader(JNIEnv* env)
 {
     return env->CallStaticObjectMethod(netscape_oji_JNIUtils, netscape_oji_JNIUtils_GetCurrentClassLoader);
 }
 
 static jobject GetObjectClassLoader(JNIEnv* env, jobject object)
 {
     return env->CallStaticObjectMethod(netscape_oji_JNIUtils, netscape_oji_JNIUtils_GetObjectClassLoader, object);
 }
 
-/**
- * Maps the given JNIEnv to a given plugin instance by comparing the current class loader
- * with the class loader of the applet of each plugin instance. This could be made
- * faster, but it's probably good enough. Note:  the reference count of the plugin
- * instance isn't affected by this call.
+static void PushLCInfo(JNIEnv* env, jint pluginInstance)
+{
+	env->CallStaticVoidMethod(netscape_oji_JNIUtils, netscape_oji_JNIUtils_PushLCInfo, pluginInstance);
+}
+
+static void PopLCInfo(JNIEnv* env)
+{
+	env->CallStaticVoidMethod(netscape_oji_JNIUtils, netscape_oji_JNIUtils_PopLCInfo);
+}
+
+static MRJPluginInstance *CurrentLCPluginInstance(JNIEnv* env)
+{
+	return (MRJPluginInstance *)
+		env->CallStaticIntMethod(netscape_oji_JNIUtils, netscape_oji_JNIUtils_CurrentLCPluginInstance);
+}
+
+/* Returns a plugin instance in which an applet has been created (if at least
+ * one exists), without being too picky about which one gets returned.  If
+ * we're running in a non-privileged context (i.e. if GetCurrentClassLoader()
+ * doesn't return NULL), we return any plugin instance whose applet was loaded
+ * by the same class loader (applets that have the same docbase will share the
+ * same class loader).  GetAppletInstance() and GetUniqueInstance() are more
+ * picky (and therefore more secure), but need more information than just the
+ * current JNIEnv.  GetAnInstance() is useful when we really should be running
+ * in some applet's context (i.e. when we're in a JSObject.call() or eval(),
+ * or a JavaScript-to-Java CallMethod call, either of which may call Java).
  */
-static MRJPluginInstance* GetCurrentInstance(JNIEnv* env)
+static MRJPluginInstance *GetAnInstance(JNIEnv* env)
 {
     MRJPluginInstance* pluginInstance = NULL;
     jobject classLoader = GetCurrentClassLoader(env);
     if (classLoader != NULL) {
         pluginInstance = MRJPluginInstance::getInstances();
-        while (pluginInstance != NULL) {
-            jobject applet;
+        while (pluginInstance && !pluginInstance->isDestroying()) {
+            jobject applet = NULL;
             pluginInstance->GetJavaObject(&applet);
-            jobject appletClassLoader = GetObjectClassLoader(env, applet);
-            jboolean sameClassLoader = env->IsSameObject(appletClassLoader, classLoader);
-            env->DeleteLocalRef(appletClassLoader);
-            if (sameClassLoader)
-                break;
+            if (applet) {
+                jobject appletClassLoader = GetObjectClassLoader(env, applet);
+                jboolean sameClassLoader = env->IsSameObject(appletClassLoader, classLoader);
+                env->DeleteLocalRef(appletClassLoader);
+                if (sameClassLoader)
+                    break;
+            }
             pluginInstance = pluginInstance->getNextInstance();
         }
         env->DeleteLocalRef(classLoader);
     }
     return pluginInstance;
 }
 
 /**
  * Maps the given applet to a given plugin instance by walking the PluginInstance list looking
  * for an instance which contains the current applet. 
  * Note:  the reference count of the plugin instance isn't affected by this call.
  */
-static MRJPluginInstance* GetCurrentInstance(JNIEnv* env, jobject applet)
+MRJPluginInstance* GetAppletInstance(JNIEnv* env, jobject applet)
 {
+    if (!applet || !env->IsInstanceOf(applet, env->FindClass("java/applet/Applet")))
+       return (MRJPluginInstance *) NULL;
     MRJPluginInstance* pluginInstance = MRJPluginInstance::getInstances();
-    while (pluginInstance != NULL) {
+    while (pluginInstance && !pluginInstance->isDestroying()) {
         jobject object = NULL;
-        if (pluginInstance->GetJavaObject(&object) == NS_OK && env->IsSameObject(applet, object)) {
+        pluginInstance->GetJavaObject(&object);
+        if (object && env->IsSameObject(applet, object))
             return pluginInstance;
-        }
         pluginInstance = pluginInstance->getNextInstance();
     }
     return NULL;
 }
 
-/**
- * Wraps a JavaMessage in an nsIRunnable form, so that it runs on the correct native thread.
+/* Returns a plugin instance in which an applet has been created, whose code
+ * base is the same as that of our nsISecurityContext parameter.  More than
+ * one applet may share the same code base.  GetSecContextInstance() is useful
+ * when we really should be running in some applet's context (i.e. when we're
+ * in a JSObject.call() or eval(), or a JavaScript-to-Java CallMethod call,
+ * either of which may call Java).
  */
-class MessageRunnable : public JavaMessage, public RunnableMixin {
-public:
-    MessageRunnable(PRUint32 threadID, JavaMessage* msg);
-    
-    virtual void execute(JNIEnv* env);
-    
-    NS_IMETHOD Run();
+MRJPluginInstance *GetSecContextInstance(nsISecurityContext *context)
+{
+    if (!context)
+        return (MRJPluginInstance *) NULL;
+    char codebase[4096] = {0};
+    if (context->GetOrigin(codebase, sizeof(codebase)-1) != NS_OK)
+        return (MRJPluginInstance *) NULL;
+    MRJPluginInstance *pluginInstance = MRJPluginInstance::getInstances();
+    while (pluginInstance && !pluginInstance->isDestroying()) {
+        jobject object = NULL;
+        pluginInstance->GetJavaObject(&object);
+        if (!object) {
+            pluginInstance = pluginInstance->getNextInstance();
+            continue;
+        }
+        nsISecurityContext *aContext =
+            (nsISecurityContext *) getSecurityContext(pluginInstance);
+        char aCodebase[4096] = {0};
+        if (aContext->GetOrigin(aCodebase, sizeof(aCodebase)-1) == NS_OK) {
+            if (strncmp(codebase, aCodebase, sizeof(codebase)-1) == 0) {
+                return pluginInstance;
+            }
+        }
+        pluginInstance = pluginInstance->getNextInstance();
+    }
+    return NULL;
+}
 
-private:
-    PRUint32 mThreadID;
-    JavaMessage* mMessage;
-};
+/* Use this instead of GetAnInstance(JNIEnv *) above when calling from one
+ * of the non-static JSObject "native" methods.  This routine guarantees a
+ * one-to-one correspondence between a JSObject object and a plugin instance.
+ */
+static MRJPluginInstance* GetUniqueInstance(JNIEnv* env, jobject java_wrapper_obj)
+{
+    MRJPluginInstance *retval = GetInstanceForWrapper(env, java_wrapper_obj);
+    if (!retval) {
+        jobject applet = GetAppletForWrapper(env, java_wrapper_obj);
+        if (applet) {
+            retval = GetAppletInstance(env, applet);
+            env->DeleteGlobalRef(applet);
+        }
+    }
+    return retval;
+}
 
-MessageRunnable::MessageRunnable(PRUint32 threadID, JavaMessage* msg)
+/* The extra initial AddRef() gives us more control over when we'll be
+ * released.  (It stops us from being released after the next pair of calls
+ * to AddRef() and Release(), but requires us to call Release() on ourselves
+ * at the appropriate time.  As a result, we'll be released after the end of
+ * the _last_ pair of calls (including our own pair) to AddRef() and
+ * Release().)
+ */
+MessageRunnable::MessageRunnable(nsPluginThreadPtr threadID, JavaMessage* msg)
     : mThreadID(threadID), mMessage(msg)
 {
+	AddRef();
+	NS_ADDREF(mMessage);
+	mPluginInstance = mMessage->getPluginInstance();
+	NS_IF_ADDREF(mPluginInstance);
+}
+
+MessageRunnable::~MessageRunnable()
+{
+	NS_RELEASE(mMessage);
+	NS_IF_RELEASE(mPluginInstance);
+}
+
+NS_IMPL_ADDREF_INHERITED(MessageRunnable, JavaMessage)
+NS_IMPL_RELEASE_INHERITED(MessageRunnable, JavaMessage)
+
+NS_METHOD MessageRunnable::QueryInterface(const nsIID& aIID, void** aInstancePtr)
+{
+    if (aInstancePtr == NULL) {
+        return NS_ERROR_NULL_POINTER;
+    }
+    *aInstancePtr = NULL;
+    if (aIID.Equals(NS_GET_IID(nsIRunnable))) {
+        *aInstancePtr = (void *) (nsIRunnable *) this;
+        AddRef();
+        return NS_OK;
+    }
+    return JavaMessage::QueryInterface(aIID, aInstancePtr);
 }
 
 void MessageRunnable::execute(JNIEnv* env)
 {
+    if (mMessage->timedOut()) {
+        Release();
+        return;
+    }
     // because a spontaneous Java thread called us, we have to switch to the JavaScript thread
     // to handle this request.
-    nsIThreadManager* threadManager = NULL;
-    if (MRJPlugin::GetService(nsIJVMManager::GetCID(), NS_GET_IID(nsIThreadManager), (void**)&threadManager) == NS_OK) {
-        threadManager->PostEvent(mThreadID, this, PR_FALSE);
+    nsIJVMThreadManager* threadManager = NULL;
+    if (MRJPlugin::GetService(nsIJVMManager::GetCID(), nsIJVMThreadManagerIID, (void**)&threadManager) == NS_OK) {
+        /* As of JEP 0.8.7 we post our event asynchrously, instead of
+         * synchronously as we used to.  This helps to avoid hangs as
+         * we're waiting for JavaScript methods (which always run on
+         * the main thread) to return.
+         */
+        threadManager->PostEvent(mThreadID, this, PR_TRUE);
         NS_RELEASE(threadManager);
     }
 }
 
 NS_IMETHODIMP MessageRunnable::Run()
 {
+    if (mMessage->timedOut()) {
+        Release();
+        return NS_OK;
+    }
     nsIJVMManager* javaManager = NULL;
     if (MRJPlugin::GetService(nsIJVMManager::GetCID(), NS_GET_IID(nsIJVMManager), (void**)&javaManager) == NS_OK) {
         JNIEnv* proxyEnv = NULL;
-        if (javaManager->GetProxyJNI(&proxyEnv) == NS_OK && proxyEnv != NULL)
+        JNIEnv *javaEnv = theJVMPlugin->getSession()->getCurrentEnv();
+        if (javaEnv && (javaManager->GetProxyJNI(&proxyEnv) == NS_OK) && proxyEnv) {
+            PushLCInfo(javaEnv, (unsigned) mPluginInstance);
             mMessage->execute(proxyEnv);
+            PopLCInfo(javaEnv);
+        }
         NS_RELEASE(javaManager);
     }
+    Release();
     return NS_OK;
 }
 
-static PRUint32 getJavaScriptThread(JNIEnv* env)
+void MessageRunnable::RunAlt(void *info)
 {
-    PRUint32 threadID = 0;
-    MRJPluginInstance* pluginInstance = GetCurrentInstance(env);
-    if (pluginInstance != NULL) {
-        nsIPluginInstancePeer* peer;
-        if (pluginInstance->GetPeer(&peer) == NS_OK) {
-            nsIPluginInstancePeer2* peer2 = NULL;
-            if (peer->QueryInterface(NS_GET_IID(nsIPluginInstancePeer2), (void**)&peer2) == NS_OK) {
-                if (peer2->GetJSThread(&threadID) != NS_OK)
-                    threadID = 0;
-                NS_RELEASE(peer2);
-            }
-            NS_RELEASE(peer);
-        }
-    }
-    return threadID;
+    if (!info)
+        return;
+    MessageRunnable *self = (MessageRunnable *) info;
+    self->Run();
 }
 
-/**
- * Sends a message by rendezvousing with an existing JavaScript thread, or creates a new one
- * if none exists for this thread already.
- */
 static void sendMessage(JNIEnv* env, JavaMessage* msg)
 {
-    // the main thread gets its own secure env, so it won't contend with other threads. this
-    // is needed to handle finalization, which seems to get called from the main thread sometimes.
-    if (env == theJVMPlugin->getSession()->getMainEnv()) {
-        static CSecureEnv* mainEnv = NULL;
-        if (mainEnv == NULL) {
-            mainEnv = new CSecureEnv(theJVMPlugin, NULL, env);
-            mainEnv->AddRef();
-        }
-        mainEnv->setJavaEnv(env);
-        mainEnv->sendMessageFromJava(env, msg, true);
+    if (!theJVMPlugin)
         return;
-    }
-    
-    // If this is a call back into JavaScript from Java, there will be a secureEnv associated with this thread.
-    jobject thread = GetCurrentThread(env);
-    CSecureEnv* secureEnv = GetSecureJNI(env, thread);
-    env->DeleteLocalRef(thread);
-    if (secureEnv != NULL) {
-        secureEnv->sendMessageFromJava(env, msg);
-    } else {
-        // spontaneous call in from Java. this communicates with a shared server thread. this is *VERY* slow right now.
-        static MRJMonitor sharedMonitor(theJVMPlugin->getSession());
-        // only 1 Java thread can use this at a time.
-        sharedMonitor.enter();
-        {
-            static CSecureEnv* sharedEnv = NULL;
-            if (sharedEnv == NULL) {
-                sharedEnv = new CSecureEnv(theJVMPlugin, NULL, env);
-                sharedEnv->AddRef();
-            }
-            sharedEnv->setJavaEnv(env);
-
-            // In the current Seamonkey architecture, there's really only one thread that JavaScript
-            // can execute in. We take advantage of that fact here. When we have a more multithreaded
-            // system, this will have to be revisited.
-            static PRUint32 theJavaScriptThread = getJavaScriptThread(env);
-            
-            // if the JavaScript thread is known, wrap the message in a MessageRunnable to handle
-            // the message in the JavaScript thread.
-            if (theJavaScriptThread != 0) {
-                MessageRunnable* runnableMsg = new MessageRunnable(theJavaScriptThread, msg);
-                NS_ADDREF(runnableMsg);
-                sharedEnv->sendMessageFromJava(env, runnableMsg);
-                NS_IF_RELEASE(runnableMsg);
-            }
-        }
-        sharedMonitor.exit();
+
+    /* This routine is now _much_ simpler (and faster).  The original MRJ
+     * Plugin Carbon ran CSecureEnv::Run() on a number of threads to process
+     * messages sent from here.  But that's completely unnecessary (and when
+     * we came through here on the main thread it actually caused hangs).
+     */
+
+    if (env == theJVMPlugin->getSession()->getMainEnv()) {
+        MessageRunnable* runnableMsg =
+            new MessageRunnable(theJavaScriptThread, msg);
+        if (runnableMsg)
+            runnableMsg->Run();
+    } else if (JEPCheckBundle()) {
+        MessageRunnable *runnableMsg =
+            new MessageRunnable(theJavaScriptThread, msg);
+        if (runnableMsg)
+            JEPRunOnMainThread(runnableMsg->RunAlt, runnableMsg, false);
+    } else if (theJavaScriptThread) {
+        MessageRunnable *runnableMsg =
+            new MessageRunnable(theJavaScriptThread, msg);
+        if (runnableMsg)
+            runnableMsg->execute(NULL);
     }
 }
 
 static nsIPrincipal* newCodebasePrincipal(const char* codebaseURL)
 {
     nsIPrincipal* principal = NULL;
 #if 0
     nsICapsManager* capsManager = NULL;
     static NS_DEFINE_IID(kICapsManagerIID, NS_ICAPSMANAGER_IID);
     if (thePluginManager->QueryInterface(kICapsManagerIID, &capsManager) == NS_OK) {
@@ -474,534 +787,1060 @@
 
 /****************** Implementation of methods of JSObject *******************/
 
 /*
  * Class:     netscape_javascript_JSObject
  * Method:    getMember
  * Signature: (Ljava/lang/String;)Ljava/lang/Object;
  */
 
 class GetMemberMessage : public JavaMessage {
-    MRJPluginInstance* mPluginInstance;
     jsobject mObject;
     const jchar* mPropertyName;
     jsize mLength;
+    jstring mJPropertyName;
     jobject* mResultObject;
 public:
     GetMemberMessage(MRJPluginInstance* pluginInstance, jsobject js_obj,
-                     const jchar* propertyName, jsize nameLength, jobject* member)
-        :   mPluginInstance(pluginInstance), mObject(js_obj), mPropertyName(propertyName),
-            mLength(nameLength), mResultObject(member)
+                     const jchar* propertyName, jsize nameLength,
+                     jstring jPropertyName, jobject* member)
+        :   JavaMessage(pluginInstance), mObject(js_obj), mPropertyName(propertyName),
+            mLength(nameLength), mJPropertyName(jPropertyName), mResultObject(member)
     {
     }
 
     virtual void execute(JNIEnv* env)
     {
-        MRJSecurityContext* securityContext = getSecurityContext(mPluginInstance);
+        if (timedOut())
+            return;
+        MRJSecurityContext* securityContext = NULL;
+        // mPluginInstance will be NULL if we were called from static code in
+        // an applet.
+        if (mPluginInstance) {
+            securityContext = getSecurityContext(mPluginInstance);
+        } else {
+            securityContext = staticSecurityContext;
+        }
+        if (securityContext == NULL) {
+            setIsDone();
+            return;
+        }
         nsILiveconnect* connection = getLiveconnectInstance(securityContext);
+        if (connection == NULL) {
+            setIsDone();
+            return;
+        }
+        if (timedOut())
+            return;
         jobject member;
         nsresult result = connection->GetMember(env, mObject, mPropertyName, mLength, NULL, 0, securityContext, &member);
+        JNIEnv *javaEnv = theJVMPlugin->getSession()->getCurrentEnv();
+        if (javaEnv)
+            javaEnv->ReleaseStringChars(mJPropertyName, mPropertyName);
+        if (timedOut())
+            return;
         if (result == NS_OK) {
             // convert reference to a global reference, in case we're switching threads.
             *mResultObject = ToGlobalRef(env, member);
         }
+        setIsDone();
     }
 };
 
 JNIEXPORT jobject JNICALL
 Java_netscape_javascript_JSObject_getMember(JNIEnv* env,
                                             jobject java_wrapper_obj,
                                             jstring property_name_jstr)
 {
     if (property_name_jstr == NULL) {
         env->ThrowNew(env->FindClass("java/lang/NullPointerException"), "illegal null member name");
         return NULL;
     }
 
-    MRJPluginInstance* pluginInstance = GetCurrentInstance(env);
-    if (pluginInstance == NULL) {
-        env->ThrowNew(env->FindClass("java/lang/NullPointerException"), "illegal JNIEnv (can't find plugin)");
+    MRJPluginInstance* pluginInstance = GetUniqueInstance(env, java_wrapper_obj);
+    if (!pluginInstance)
+        pluginInstance = CurrentLCPluginInstance(env);
+    if (pluginInstance && !MRJPluginInstance::isValidInstance(pluginInstance))
         return NULL;
-    }
+    // pluginInstance will be NULL if we were called from static code in
+    // an applet.
+    NS_IF_ADDREF(pluginInstance);
 
     /* Get the Unicode string for the JS property name */
     jboolean is_copy;
     const jchar* property_name_ucs2 = env->GetStringChars(property_name_jstr, &is_copy);
     jsize property_name_len = env->GetStringLength(property_name_jstr);
 
     jsobject js_obj = Unwrap_JSObject(env, java_wrapper_obj);
     jobject member = NULL;
 
-    GetMemberMessage msg(pluginInstance, js_obj, property_name_ucs2, property_name_len, &member);
-    sendMessage(env, &msg);
+    GetMemberMessage *msg = new GetMemberMessage(pluginInstance, js_obj,
+        property_name_ucs2, property_name_len, property_name_jstr, &member);
+    if (msg) {
+        sendMessage(env, msg);
+        msg->waitTilDone(jsObjectTimeout);
+    }
 
     // convert the resulting reference back to a local reference.
     if (member != NULL)
         member = ToLocalRef(env, member);
     
-    env->ReleaseStringChars(property_name_jstr, property_name_ucs2);
-
+    NS_IF_RELEASE(pluginInstance);
     return member;
 }
 
 /*
  * Class:     netscape_javascript_JSObject
  * Method:    getSlot
  * Signature: (I)Ljava/lang/Object;
  */
 
 class GetSlotMessage : public JavaMessage {
-    MRJPluginInstance* mPluginInstance;
     jsobject mObject;
     jint mSlot;
     jobject* mResultObject;
 public:
     GetSlotMessage(MRJPluginInstance* pluginInstance, jsobject js_obj,
                    jint slot, jobject* member)
-        :   mPluginInstance(pluginInstance), mObject(js_obj), mSlot(slot), mResultObject(member)
+        :   JavaMessage(pluginInstance), mObject(js_obj), mSlot(slot), mResultObject(member)
     {
     }
 
     virtual void execute(JNIEnv* env)
     {
-        MRJSecurityContext* securityContext = getSecurityContext(mPluginInstance);
+        if (timedOut())
+            return;
+        MRJSecurityContext* securityContext = NULL;
+        // mPluginInstance will be NULL if we were called from static code in
+        // an applet.
+        if (mPluginInstance) {
+            securityContext = getSecurityContext(mPluginInstance);
+        } else {
+            securityContext = staticSecurityContext;
+        }
+        if (securityContext == NULL) {
+            setIsDone();
+            return;
+        }
         nsILiveconnect* connection = getLiveconnectInstance(securityContext);
+        if (connection == NULL) {
+            setIsDone();
+            return;
+        }
+        if (timedOut())
+            return;
         jobject member;
         nsresult result = connection->GetSlot(env, mObject, mSlot, NULL, 0, securityContext, &member);
+        if (timedOut())
+            return;
         if (result == NS_OK) {
             // convert reference to a global reference, in case we're switching threads.
             *mResultObject = ToGlobalRef(env, member);
         }
+        setIsDone();
     }
 };
 
 JNIEXPORT jobject JNICALL
 Java_netscape_javascript_JSObject_getSlot(JNIEnv* env,
                                           jobject java_wrapper_obj,
                                           jint slot)
 {
-    MRJPluginInstance* pluginInstance = GetCurrentInstance(env);
+    MRJPluginInstance* pluginInstance = GetUniqueInstance(env, java_wrapper_obj);
+    if (!pluginInstance)
+        pluginInstance = CurrentLCPluginInstance(env);
 
-    if (pluginInstance == NULL) {
-        env->ThrowNew(env->FindClass("java/lang/NullPointerException"), "illegal JNIEnv (can't find plugin)");
+    if (pluginInstance && !MRJPluginInstance::isValidInstance(pluginInstance))
         return NULL;
-    }
+    // pluginInstance will be NULL if we were called from static code in
+    // an applet.
+    NS_IF_ADDREF(pluginInstance);
 
     jsobject js_obj = Unwrap_JSObject(env, java_wrapper_obj);
     jobject member = NULL;
-    
-    GetSlotMessage msg(pluginInstance, js_obj, slot, &member);
-    sendMessage(env, &msg);
-    
+
+    GetSlotMessage *msg = new GetSlotMessage(pluginInstance, js_obj, slot, &member);
+    if (msg) {
+        sendMessage(env, msg);
+        msg->waitTilDone(jsObjectTimeout);
+    }
+
     // convert the resulting reference back to a local reference.
     if (member != NULL)
         member = ToLocalRef(env, member);
+
+    NS_IF_RELEASE(pluginInstance);
     return member;
 }
 
 /*
  * Class:     netscape_javascript_JSObject
  * Method:    setMember
  * Signature: (Ljava/lang/String;Ljava/lang/Object;)V
  */
 
 class SetMemberMessage : public JavaMessage {
-    MRJPluginInstance* mPluginInstance;
     jsobject mObject;
     const jchar* mPropertyName;
     jsize mLength;
+    jstring mJPropertyName;
     jobject mJavaObject;
 public:
-    SetMemberMessage(MRJPluginInstance* pluginInstance, jsobject js_obj, const jchar* propertyName,
-                     jsize nameLength, jobject java_obj)
-        :   mPluginInstance(pluginInstance), mObject(js_obj), mPropertyName(propertyName), mLength(nameLength), mJavaObject(java_obj)
+    SetMemberMessage(MRJPluginInstance* pluginInstance, jsobject js_obj,
+                     const jchar* propertyName, jsize nameLength,
+                     jstring jPropertyName, jobject java_obj)
+        :   JavaMessage(pluginInstance), mObject(js_obj), mPropertyName(propertyName),
+            mLength(nameLength), mJPropertyName(jPropertyName), mJavaObject(java_obj)
     {
     }
 
     virtual void execute(JNIEnv* env)
     {
-        MRJSecurityContext* securityContext = getSecurityContext(mPluginInstance);
+        if (!theJVMPlugin)
+            return;
+        MRJSecurityContext* securityContext = NULL;
+        // mPluginInstance will be NULL if we were called from static code in
+        // an applet.
+        if (mPluginInstance) {
+            securityContext = getSecurityContext(mPluginInstance);
+        } else {
+            securityContext = staticSecurityContext;
+        }
+        if (securityContext == NULL) {
+            Release();
+            return;
+        }
         nsILiveconnect* connection = getLiveconnectInstance(securityContext);
-        nsresult result = connection->SetMember(env, mObject, mPropertyName, mLength, mJavaObject, 0, NULL, securityContext);
+        if (connection == NULL) {
+            Release();
+            return;
+        }
+        connection->SetMember(env, mObject, mPropertyName, mLength, mJavaObject, 0, 0, securityContext);
+        JNIEnv *javaEnv = theJVMPlugin->getSession()->getCurrentEnv();
+        if (javaEnv) {
+            javaEnv->ReleaseStringChars(mJPropertyName, mPropertyName);
+            if (mJavaObject)
+                javaEnv->DeleteGlobalRef(mJavaObject);
+        }
+        Release();
     }
 };
 
 JNIEXPORT void JNICALL
 Java_netscape_javascript_JSObject_setMember(JNIEnv* env,
                                             jobject java_wrapper_obj,
                                             jstring property_name_jstr,
                                             jobject java_obj)
 {
     if (property_name_jstr == NULL) {
         env->ThrowNew(env->FindClass("java/lang/NullPointerException"), "illegal null member name");
         return;
     }
 
-    MRJPluginInstance* pluginInstance = GetCurrentInstance(env);
-    if (pluginInstance == NULL) {
-        env->ThrowNew(env->FindClass("java/lang/NullPointerException"), "illegal JNIEnv (can't find plugin)");
+    MRJPluginInstance* pluginInstance = GetUniqueInstance(env, java_wrapper_obj);
+    if (!pluginInstance)
+        pluginInstance = CurrentLCPluginInstance(env);
+    if (pluginInstance && !MRJPluginInstance::isValidInstance(pluginInstance))
         return;
-    }
+    // pluginInstance will be NULL if we were called from static code in
+    // an applet.
+    NS_IF_ADDREF(pluginInstance);
 
     /* Get the Unicode string for the JS property name */
     jboolean is_copy;
     const jchar* property_name_ucs2 = env->GetStringChars(property_name_jstr, &is_copy);
     jsize property_name_len = env->GetStringLength(property_name_jstr);
+
+    /* Add an extra global ref for java_obj (to make sure it _is_ global) */
+    if (java_obj)
+        java_obj = (jobjectArray) env->NewGlobalRef(java_obj);
     
     jsobject js_obj = Unwrap_JSObject(env, java_wrapper_obj);
-    java_obj = ToGlobalRef(env, java_obj);
 
-    SetMemberMessage msg(pluginInstance, js_obj, property_name_ucs2, property_name_len, java_obj);
-    sendMessage(env, &msg);
-    
-    env->DeleteGlobalRef(java_obj);
-    env->ReleaseStringChars(property_name_jstr, property_name_ucs2);
+    SetMemberMessage *msg = new SetMemberMessage(pluginInstance, js_obj,
+        property_name_ucs2, property_name_len, property_name_jstr, java_obj);
+    if (msg) {
+        sendMessage(env, msg);
+    }
+
+    NS_IF_RELEASE(pluginInstance);
 }
 
 /*
  * Class:     netscape_javascript_JSObject
  * Method:    setSlot
  * Signature: (ILjava/lang/Object;)V
  */
 
 class SetSlotMessage : public JavaMessage {
-    MRJPluginInstance* mPluginInstance;
     jsobject mObject;
     jint mSlot;
     jobject mJavaObject;
 public:
     SetSlotMessage(MRJPluginInstance* pluginInstance, jsobject js_obj, jint slot, jobject java_obj)
-        :   mPluginInstance(pluginInstance), mObject(js_obj), mSlot(slot), mJavaObject(java_obj)
+        :   JavaMessage(pluginInstance), mObject(js_obj), mSlot(slot), mJavaObject(java_obj)
     {
     }
 
     virtual void execute(JNIEnv* env)
     {
-        MRJSecurityContext* securityContext = getSecurityContext(mPluginInstance);
+        MRJSecurityContext* securityContext = NULL;
+        // mPluginInstance will be NULL if we were called from static code in
+        // an applet.
+        if (mPluginInstance) {
+            securityContext = getSecurityContext(mPluginInstance);
+        } else {
+            securityContext = staticSecurityContext;
+        }
+        if (securityContext == NULL) {
+            Release();
+            return;
+        }
         nsILiveconnect* connection = getLiveconnectInstance(securityContext);
-        nsresult result = connection->SetSlot(env, mObject, mSlot, mJavaObject, 0, NULL, securityContext);
+        if (connection == NULL) {
+            Release();
+            return;
+        }
+        connection->SetSlot(env, mObject, mSlot, mJavaObject, 0, 0, securityContext);
+        if (mJavaObject) {
+            JNIEnv *javaEnv = theJVMPlugin->getSession()->getCurrentEnv();
+            if (javaEnv)
+                javaEnv->DeleteGlobalRef(mJavaObject);
+        }
+		Release();
     }
 };
 
 JNIEXPORT void JNICALL
 Java_netscape_javascript_JSObject_setSlot(JNIEnv* env,
                                           jobject java_wrapper_obj,
                                           jint slot,
                                           jobject java_obj)
 {
-    MRJPluginInstance* pluginInstance = GetCurrentInstance(env);
+    MRJPluginInstance* pluginInstance = GetUniqueInstance(env, java_wrapper_obj);
+    if (!pluginInstance)
+        pluginInstance = CurrentLCPluginInstance(env);
 
-    if (pluginInstance == NULL) {
-        env->ThrowNew(env->FindClass("java/lang/NullPointerException"), "illegal JNIEnv (can't find plugin)");
+    if (pluginInstance && !MRJPluginInstance::isValidInstance(pluginInstance))
         return;
-    }
+    // pluginInstance will be NULL if we were called from static code in
+    // an applet.
+    NS_IF_ADDREF(pluginInstance);
+
+    /* Add an extra global ref for java_obj (to make sure it _is_ global) */
+    if (java_obj)
+        java_obj = (jobjectArray) env->NewGlobalRef(java_obj);
 
     jsobject js_obj = Unwrap_JSObject(env, java_wrapper_obj);
-    java_obj = ToGlobalRef(env, java_obj);
     
-    SetSlotMessage msg(pluginInstance, js_obj, slot, java_obj);
-    sendMessage(env, &msg);
-    env->DeleteGlobalRef(java_obj);
+    SetSlotMessage *msg = new SetSlotMessage(pluginInstance, js_obj, slot, java_obj);
+    if (msg) {
+        sendMessage(env, msg);
+    }
+
+    NS_IF_RELEASE(pluginInstance);
 }
 
 /*
  * Class:     netscape_javascript_JSObject
  * Method:    removeMember
  * Signature: (Ljava/lang/String;)V
  */
 
 class RemoveMemberMessage : public JavaMessage {
-    MRJPluginInstance* mPluginInstance;
     jsobject mObject;
     const jchar* mPropertyName;
     jsize mLength;
+    jstring mJPropertyName;
 public:
     RemoveMemberMessage(MRJPluginInstance* pluginInstance, jsobject obj,
-                        const jchar* propertyName, jsize length)
-        :   mPluginInstance(pluginInstance), mObject(obj),
-            mPropertyName(propertyName), mLength(length)
+                        const jchar* propertyName, jsize length,
+                        jstring jPropertyName)
+        :   JavaMessage(pluginInstance), mObject(obj),
+            mPropertyName(propertyName), mLength(length),
+            mJPropertyName(jPropertyName)
     {
     }
 
     virtual void execute(JNIEnv* env)
     {
-        MRJSecurityContext* securityContext = getSecurityContext(mPluginInstance);
+        if (!theJVMPlugin)
+            return;
+        MRJSecurityContext* securityContext = NULL;
+        // mPluginInstance will be NULL if we were called from static code in
+        // an applet.
+        if (mPluginInstance) {
+            securityContext = getSecurityContext(mPluginInstance);
+        } else {
+            securityContext = staticSecurityContext;
+        }
+        if (securityContext == NULL) {
+            Release();
+            return;
+        }
         nsILiveconnect* connection = getLiveconnectInstance(securityContext);
-        nsresult result = connection->RemoveMember(env, mObject, mPropertyName, mLength, NULL, 0, securityContext);
+        if (connection == NULL) {
+            Release();
+            return;
+        }
+        connection->RemoveMember(env, mObject, mPropertyName, mLength, NULL, 0, securityContext);
+        JNIEnv *javaEnv = theJVMPlugin->getSession()->getCurrentEnv();
+        if (javaEnv)
+            javaEnv->ReleaseStringChars(mJPropertyName, mPropertyName);
+        Release();
     }
 };
 
 JNIEXPORT void JNICALL
 Java_netscape_javascript_JSObject_removeMember(JNIEnv* env,
                                                jobject java_wrapper_obj,
                                                jstring property_name_jstr)
 {
     if (property_name_jstr == NULL) {
         env->ThrowNew(env->FindClass("java/lang/NullPointerException"), "illegal null member name");
         return;
     }
 
-    MRJPluginInstance* pluginInstance = GetCurrentInstance(env);
-    if (pluginInstance == NULL) {
-        env->ThrowNew(env->FindClass("java/lang/NullPointerException"), "illegal JNIEnv (can't find plugin)");
+    MRJPluginInstance* pluginInstance = GetUniqueInstance(env, java_wrapper_obj);
+    if (!pluginInstance)
+        pluginInstance = CurrentLCPluginInstance(env);
+    if (pluginInstance && !MRJPluginInstance::isValidInstance(pluginInstance))
         return;
-    }
+    // pluginInstance will be NULL if we were called from static code in
+    // an applet.
+    NS_IF_ADDREF(pluginInstance);
 
     /* Get the Unicode string for the JS property name */
     jboolean is_copy;
     const jchar* property_name_ucs2 = env->GetStringChars(property_name_jstr, &is_copy);
     jsize property_name_len = env->GetStringLength(property_name_jstr);
 
     jsobject js_obj = Unwrap_JSObject(env, java_wrapper_obj);
-    RemoveMemberMessage msg(pluginInstance, js_obj, property_name_ucs2, property_name_len);
-    
-    sendMessage(env, &msg);
-    
-    env->ReleaseStringChars(property_name_jstr, property_name_ucs2);
-}
+    RemoveMemberMessage *msg = new RemoveMemberMessage(pluginInstance, js_obj,
+        property_name_ucs2, property_name_len, property_name_jstr);
+    if (msg) {
+        sendMessage(env, msg);
+    }
+
+    NS_IF_RELEASE(pluginInstance);
+}
+
+/* The Mozilla-family browsers have trouble handling several calls to
+ * nsILiveconnect::Call() or nsILiveconnect::Eval() in quick succession --
+ * particularly if user interaction is involved (e.g. a JavaScript alert()
+ * box gets displayed), which holds open the call that spawned it (e.g. while
+ * the alert() box is waiting for the user to press OK), and seems to cause
+ * Call() or Eval() to be interrupted by subsequent Calls or Evals, which can
+ * lead to crashes on exiting.  The problem is worst on Tiger (probably thanks
+ * to its new Java "threading model") -- only Mozilla's Carbon-based browsers
+ * (Firefox and "SeaMonkey") seem to have this problem on earlier OSes.  A
+ * good solution is to use the following monitor to space out calls to Call()
+ * or Eval():  As long as we don't exceed the two-second timeout, only one
+ * call to Call() or Eval() may be active at any one time.  And if we do
+ * exceed the timeout, there's a two-second gap between the start of one call
+ * the start of the next -- which allows us (on Carbon browsers) to check for
+ * a popup window after the timeout has expired, and (if necessary) extend it
+ * indefinitely.
+ */
 
 /*
  * Class:     netscape_javascript_JSObject
  * Method:    call
  * Signature: (Ljava/lang/String;[Ljava/lang/Object;)Ljava/lang/Object;
  */
 class CallMessage : public JavaMessage {
-    MRJPluginInstance* mPluginInstance;
     jsobject mObject;
     const jchar* mFunctionName;
     jsize mLength;
+    jstring mJFunctionName;
     jobjectArray mJavaArgs;
     jobject* mJavaResult;
 public:
-    CallMessage(MRJPluginInstance* pluginInstance, jsobject obj, const jchar* functionName,
-                jsize length, jobjectArray javaArgs, jobject* javaResult)
-        :   mPluginInstance(pluginInstance), mObject(obj), mFunctionName(functionName),
-            mLength(length), mJavaArgs(javaArgs), mJavaResult(javaResult)
+    CallMessage(MRJPluginInstance* pluginInstance, jsobject obj,
+                const jchar* functionName, jsize length, jstring jFunctionName,
+                jobjectArray javaArgs, jobject* javaResult)
+        :   JavaMessage(pluginInstance), mObject(obj), mFunctionName(functionName),
+            mLength(length), mJFunctionName(jFunctionName), mJavaArgs(javaArgs),
+            mJavaResult(javaResult)
     {
     }
 
     virtual void execute(JNIEnv* env)
     {
-        /* If we have an applet, try to create a codebase principle. */
-        MRJSecurityContext* securityContext = getSecurityContext(mPluginInstance);
+        if (timedOut())
+            return;
+        MRJSecurityContext* securityContext = NULL;
+        // mPluginInstance will be NULL if we were called from static code in
+        // an applet.
+        if (mPluginInstance) {
+            securityContext = getSecurityContext(mPluginInstance);
+        } else {
+            securityContext = staticSecurityContext;
+        }
+        if (securityContext == NULL) {
+            setIsDone();
+            return;
+        }
         nsILiveconnect* connection = getLiveconnectInstance(securityContext);
+        if (connection == NULL) {
+            setIsDone();
+            return;
+        }
+        if (timedOut())
+            return;
         jobject jresult = NULL;
         nsresult result = connection->Call(env, mObject, mFunctionName, mLength, mJavaArgs, NULL, 0, securityContext, &jresult);
+        JNIEnv *javaEnv = theJVMPlugin->getSession()->getCurrentEnv();
+        if (javaEnv) {
+            javaEnv->ReleaseStringChars(mJFunctionName, mFunctionName);
+            if (mJavaArgs)
+                javaEnv->DeleteGlobalRef(mJavaArgs);
+        }
+        if (timedOut())
+            return;
         if (result == NS_OK)
             *mJavaResult = ToGlobalRef(env, jresult);
+        setIsDone();
     }
 };
 
 JNIEXPORT jobject JNICALL
 Java_netscape_javascript_JSObject_call(JNIEnv* env, jobject java_wrapper_obj,
                                        jstring function_name_jstr, jobjectArray java_args)
 {
     if (function_name_jstr == NULL) {
         env->ThrowNew(env->FindClass("java/lang/NullPointerException"), "illegal null function name");
         return NULL;
     }
 
-    /* Try to determine which plugin instance is responsible for this thread. This is done by checking class loaders. */
-    MRJPluginInstance* pluginInstance = GetCurrentInstance(env);
-    if (pluginInstance == NULL) {
-        env->ThrowNew(env->FindClass("java/lang/NullPointerException"), "illegal JNIEnv (can't find plugin)");
+    if (callEvalMonitor == NULL)
         return NULL;
-    }
+
+    /* Try to determine which plugin instance is responsible for this thread. */
+    MRJPluginInstance* pluginInstance = GetUniqueInstance(env, java_wrapper_obj);
+    if (!pluginInstance)
+        pluginInstance = CurrentLCPluginInstance(env);
+    if (!pluginInstance)
+        pluginInstance = GetAnInstance(env);
+    if (pluginInstance && !MRJPluginInstance::isValidInstance(pluginInstance))
+        return NULL;
+    // pluginInstance will be NULL if we were called from static code in
+    // an applet.
+    NS_IF_ADDREF(pluginInstance);
 
     /* Get the Unicode string for the JS function name */
     jboolean is_copy;
     const jchar* function_name_ucs2 = env->GetStringChars(function_name_jstr, &is_copy);
     jsize function_name_len = env->GetStringLength(function_name_jstr);
 
+    /* Add an extra global ref for java_args (to make sure it _is_ global)
+	 * Doing this clears up the following crash bug --
+	 * http://sourceforge.net/tracker/index.php?func=detail&aid=1638030&group_id=107955&atid=649116.
+	 * As far as I can tell we don't need to do the same for the objects
+	 * contained in java_args.
+	 */
+    if (java_args)
+        java_args = (jobjectArray) env->NewGlobalRef(java_args);
+
     jsobject js_obj = Unwrap_JSObject(env, java_wrapper_obj);
     jobject jresult = NULL;
 
-    CallMessage msg(pluginInstance, js_obj, function_name_ucs2, function_name_len, java_args, &jresult);
-    sendMessage(env, &msg);
-
-    env->ReleaseStringChars(function_name_jstr, function_name_ucs2);
+    CallMessage *msg = new CallMessage(pluginInstance, js_obj, function_name_ucs2,
+        function_name_len, function_name_jstr, java_args, &jresult);
+    if (msg) {
+        callEvalMonitor->enter();
+        sendMessage(env, msg);
+        Boolean done = msg->waitAWhile(jsObjectTimeout);
+        /* If our "message" hasn't finished executing by the end of the normal
+         * timeout, check for popup windows that have been spawned as children
+         * of the current browser window.  If any are found we extend the
+         * timeout indefinitely -- on the assumption that the reason our
+         * "message" hasn't finished is that it's waiting for user interaction
+         * in the popped-up window (which is presumably a JavaScript alert()
+         * box or some other kind of dialog).  (This solution doesn't work for
+         * Cocoa browsers like Camino -- their JavaScript dialogs seem to be
+         * "pure" Cocoa windows, which aren't included in the Carbon "window
+         * list".  But that's not a big deal, since orphaning a call to
+         * nsILiveconnect::Call() doesn't seem to cause crashes on exit in
+         * Cocoa browsers (if we use callEvalMonitor).)
+         */
+        if (!done) {
+            long long timeout = 100;
+            WindowRef browserWindow = NULL;
+            WindowRef activeWindow = GetUserFocusWindow();
+            nsPluginWindow *pluginWindow = NULL;
+            if (pluginInstance)
+                pluginWindow = pluginInstance->getWindow();
+            if (pluginWindow) {
+                browserWindow = GetWindowFromPort(pluginWindow->window->port);
+            } else {
+                browserWindow = ActiveNonFloatingWindow();
+            }
+            if (activeWindow && browserWindow &&
+                (activeWindow != browserWindow))
+            {
+                WindowRef prevWindow = GetPreviousWindow(browserWindow);
+                while (prevWindow) {
+                    if (prevWindow == activeWindow) {
+                        timeout = 0;
+                        break;
+                    }
+                    prevWindow = GetPreviousWindow(prevWindow);
+                }
+            }
+            msg->waitTilDone(timeout);
+        }
+        callEvalMonitor->exit();
+    }
 
     if (jresult != NULL)
         jresult = ToLocalRef(env, jresult);
 
+    NS_IF_RELEASE(pluginInstance);
     return jresult;
 }
 
 /*
  * Class:     netscape_javascript_JSObject
  * Method:    eval
  * Signature: (Ljava/lang/String;)Ljava/lang/Object;
  */
 class EvalMessage : public JavaMessage {
-    MRJPluginInstance* mPluginInstance;
     jsobject mObject;
     const jchar* mScript;
     jsize mLength;
+    jstring mJScript;
     jobject* mJavaResult;
 public:
-    EvalMessage(MRJPluginInstance* pluginInstance, jsobject obj, const jchar* script, jsize length, jobject* javaResult)
-        :   mPluginInstance(pluginInstance), mObject(obj), mScript(script), mLength(length), mJavaResult(javaResult)
+    EvalMessage(MRJPluginInstance* pluginInstance, jsobject obj, const jchar* script,
+                jsize length, jstring jScript, jobject* javaResult)
+        :   JavaMessage(pluginInstance), mObject(obj), mScript(script),
+            mLength(length), mJScript(jScript), mJavaResult(javaResult)
     {
     }
 
     virtual void execute(JNIEnv* env)
     {
+        if (timedOut())
+            return;
         jobject jresult = NULL;
-        MRJSecurityContext* securityContext = getSecurityContext(mPluginInstance);
+        MRJSecurityContext* securityContext = NULL;
+        // mPluginInstance will be NULL if we were called from static code in
+        // an applet.
+        if (mPluginInstance) {
+            securityContext = getSecurityContext(mPluginInstance);
+        } else {
+            securityContext = staticSecurityContext;
+        }
+        if (securityContext == NULL) {
+            setIsDone();
+            return;
+        }
         nsILiveconnect* connection = getLiveconnectInstance(securityContext);
+        if (connection == NULL) {
+            setIsDone();
+            return;
+        }
+        if (timedOut())
+            return;
         nsresult result = connection->Eval(env, mObject, mScript, mLength, NULL, 0, securityContext, &jresult);
-        if (result == NS_OK && jresult != NULL)
+        JNIEnv *javaEnv = theJVMPlugin->getSession()->getCurrentEnv();
+        if (javaEnv)
+            javaEnv->ReleaseStringChars(mJScript, mScript);
+        if (timedOut())
+            return;
+        if ((result == NS_OK) && (jresult != NULL))
             *mJavaResult = ToGlobalRef(env, jresult);
+        setIsDone();
     }
 };
 
 JNIEXPORT jobject JNICALL
 Java_netscape_javascript_JSObject_eval(JNIEnv* env,
                                        jobject java_wrapper_obj,
                                        jstring script_jstr)
 {
     /* Get the Unicode string for the JS function name */
     if (script_jstr == NULL) {
         env->ThrowNew(env->FindClass("java/lang/NullPointerException"), "illegal null script string");
         return NULL;
     }
+
+    if (callEvalMonitor == NULL)
+        return NULL;
+
     jboolean is_copy;
     const jchar* script_ucs2 = env->GetStringChars(script_jstr, &is_copy);
     jsize script_len = env->GetStringLength(script_jstr);
 
     /* unwrap the JS object from the Java object. */
     jsobject js_obj = Unwrap_JSObject(env, java_wrapper_obj);
     jobject jresult = NULL;
     
     /* determine the plugin instance so we can obtain its codebase. */
     // beard: should file a bug with Apple that JMJNIToAWTContext doesn't work.
-    MRJPluginInstance* pluginInstance = GetCurrentInstance(env);
-    if (pluginInstance == NULL) {
-        env->ThrowNew(env->FindClass("java/lang/NullPointerException"), "illegal JNIEnv (can't find plugin)");
+    MRJPluginInstance* pluginInstance = GetUniqueInstance(env, java_wrapper_obj);
+    if (!pluginInstance)
+        pluginInstance = CurrentLCPluginInstance(env);
+    if (!pluginInstance)
+        pluginInstance = GetAnInstance(env);
+    if (pluginInstance && !MRJPluginInstance::isValidInstance(pluginInstance))
         return NULL;
+    // pluginInstance will be NULL if we were called from static code in
+    // an applet.
+    NS_IF_ADDREF(pluginInstance);
+
+    EvalMessage *msg = new EvalMessage(pluginInstance, js_obj, script_ucs2,
+        script_len, script_jstr, &jresult);
+    if (msg) {
+        callEvalMonitor->enter();
+        sendMessage(env, msg);
+        Boolean done = msg->waitAWhile(jsObjectTimeout);
+        /* If our "message" hasn't finished executing by the end of the normal
+         * timeout, check for popup windows that have been spawned as children
+         * of the current browser window.  If any are found we extend the
+         * timeout indefinitely -- on the assumption that the reason our
+         * "message" hasn't finished is that it's waiting for user interaction
+         * in the popped-up window (which is presumably a JavaScript alert()
+         * box or some other kind of dialog).  (This solution doesn't work for
+         * Cocoa browsers like Camino -- their JavaScript dialogs seem to be
+         * "pure" Cocoa windows, which aren't included in the Carbon "window
+         * list".  But that's not a big deal, since orphaning a call to
+         * nsILiveconnect::Eval() doesn't seem to cause crashes on exit in
+         * Cocoa browsers (if we use callEvalMonitor).)
+         */
+        if (!done) {
+            long long timeout = 100;
+            WindowRef browserWindow = NULL;
+            WindowRef activeWindow = GetUserFocusWindow();
+            nsPluginWindow *pluginWindow = NULL;
+            if (pluginInstance)
+                pluginWindow = pluginInstance->getWindow();
+            if (pluginWindow) {
+                browserWindow = GetWindowFromPort(pluginWindow->window->port);
+            } else {
+                browserWindow = ActiveNonFloatingWindow();
+            }
+            if (activeWindow && browserWindow &&
+                (activeWindow != browserWindow))
+            {
+                WindowRef prevWindow = GetPreviousWindow(browserWindow);
+                while (prevWindow) {
+                    if (prevWindow == activeWindow) {
+                        timeout = 0;
+                        break;
+                    }
+                    prevWindow = GetPreviousWindow(prevWindow);
+                }
+            }
+            msg->waitTilDone(timeout);
+        }
+        callEvalMonitor->exit();
     }
 
-    EvalMessage msg(pluginInstance, js_obj, script_ucs2, script_len, &jresult);
-    sendMessage(env, &msg);
-    
     if (jresult != NULL)
         jresult = ToLocalRef(env, jresult);
 
-    env->ReleaseStringChars(script_jstr, script_ucs2);
-
+    NS_IF_RELEASE(pluginInstance);
     return jresult;
 }
 
 /*
  * Class:     netscape_javascript_JSObject
  * Method:    toString
  * Signature: ()Ljava/lang/String;
  */
 class ToStringMessage : public JavaMessage {
-    MRJPluginInstance* mPluginInstance;
     jsobject mObject;
     jstring* mStringResult;
 public:
     ToStringMessage(MRJPluginInstance* pluginInstance, jsobject js_obj, jstring* stringResult)
-        :   mPluginInstance(pluginInstance), mObject(js_obj), mStringResult(stringResult)
+        :   JavaMessage(pluginInstance), mObject(js_obj), mStringResult(stringResult)
     {
     }
 
     virtual void execute(JNIEnv* env)
     {
-        MRJSecurityContext* securityContext = getSecurityContext(mPluginInstance);
+        if (timedOut())
+            return;
+        MRJSecurityContext* securityContext = NULL;
+        // mPluginInstance will be NULL if we were called from static code in
+        // an applet.
+        if (mPluginInstance) {
+            securityContext = getSecurityContext(mPluginInstance);
+        } else {
+            securityContext = staticSecurityContext;
+        }
+        if (securityContext == NULL) {
+            setIsDone();
+            return;
+        }
         nsILiveconnect* connection = getLiveconnectInstance(securityContext);
+        if (connection == NULL) {
+            setIsDone();
+            return;
+        }
+        if (timedOut())
+            return;
         jstring jresult = NULL;
         nsresult status = connection->ToString(env, mObject, &jresult);
-        if (status == NS_OK && jresult != NULL)
+        if (timedOut())
+            return;
+        if ((status == NS_OK) && (jresult != NULL))
             *mStringResult = (jstring) ToGlobalRef(env, jresult);
+        setIsDone();
     }
 };
 
 JNIEXPORT jstring JNICALL
 Java_netscape_javascript_JSObject_toString(JNIEnv* env, jobject java_wrapper_obj)
 {
     /* unwrap the JS object from the Java object. */
     jstring jresult = NULL;
     jsobject js_obj = Unwrap_JSObject(env, java_wrapper_obj);
 
-    MRJPluginInstance* pluginInstance = GetCurrentInstance(env);
-    if (pluginInstance == NULL) {
-        env->ThrowNew(env->FindClass("java/lang/NullPointerException"), "illegal JNIEnv (can't find plugin)");
+    MRJPluginInstance* pluginInstance = GetUniqueInstance(env, java_wrapper_obj);
+    if (!pluginInstance)
+        pluginInstance = CurrentLCPluginInstance(env);
+    if (pluginInstance && !MRJPluginInstance::isValidInstance(pluginInstance))
         return NULL;
+    // pluginInstance will be NULL if we were called from static code in
+    // an applet.
+    NS_IF_ADDREF(pluginInstance);
+
+    ToStringMessage *msg = new ToStringMessage(pluginInstance, js_obj, &jresult);
+    if (msg) {
+        sendMessage(env, msg);
+        msg->waitTilDone(jsObjectTimeout);
     }
 
-    ToStringMessage msg(pluginInstance, js_obj, &jresult);
-    sendMessage(env, &msg);
-    
     if (jresult != NULL)
         jresult = (jstring) ToLocalRef(env, jresult);
     
+    NS_IF_RELEASE(pluginInstance);
     return jresult;
 }
 
 /*
  * Class:     netscape_javascript_JSObject
  * Method:    getWindow
  * Signature: (Ljava/applet/Applet;)Lnetscape/javascript/JSObject;
  */
 class GetWindowMessage : public JavaMessage {
-    MRJPluginInstance* mPluginInstance;
     jsobject* mWindowResult;
 public:
     GetWindowMessage(MRJPluginInstance* pluginInstance, jsobject* windowResult)
-        :   mPluginInstance(pluginInstance), mWindowResult(windowResult)
+        :   JavaMessage(pluginInstance), mWindowResult(windowResult)
     {
     }
     
     virtual void execute(JNIEnv* env)
     {
+        if (timedOut())
+            return;
+        jsobject jresult = 0;
         MRJSecurityContext* securityContext = getSecurityContext(mPluginInstance);
+        if (securityContext == NULL) {
+            setIsDone();
+            return;
+        }
         nsILiveconnect* connection = getLiveconnectInstance(securityContext);
-        nsresult status = connection->GetWindow(env, mPluginInstance, NULL, 0, securityContext, mWindowResult);
+        if (connection == NULL) {
+            setIsDone();
+            return;
+        }
+        if (timedOut())
+            return;
+        nsresult status = connection->GetWindow(env, mPluginInstance, NULL, 0, securityContext, &jresult);
+        if (timedOut())
+            return;
+        if ((status == NS_OK) && (jresult != 0))
+            *mWindowResult = jresult;
+        setIsDone();
     }
 };
 
 JNIEXPORT jobject JNICALL
 Java_netscape_javascript_JSObject_getWindow(JNIEnv* env,
                                             jclass js_object_class,
                                             jobject java_applet_obj)
 {
-    MRJPluginInstance* pluginInstance = GetCurrentInstance(env, java_applet_obj);
-    if (pluginInstance != NULL) {
-        jsobject jswindow = NULL;
-        GetWindowMessage msg(pluginInstance, &jswindow);
-        sendMessage(env, &msg);
-        
-        if (jswindow != NULL)
-            return Wrap_JSObject(env, jswindow);
+    MRJPluginInstance* pluginInstance = GetAppletInstance(env, java_applet_obj);
+    if (MRJPluginInstance::isValidInstance(pluginInstance)) {
+        NS_ADDREF(pluginInstance);
+        jsobject jswindow = 0;
+        GetWindowMessage *msg = new GetWindowMessage(pluginInstance, &jswindow);
+        if (msg) {
+            sendMessage(env, msg);
+            msg->waitTilDone(jsObjectTimeout);
+        }
+
+        jobject retval = NULL;
+        if (jswindow != 0)
+            retval = Wrap_JSObject(env, jswindow, java_applet_obj);
+        if (retval != NULL)
+            retval = ToLocalRef(env, retval);
+        NS_RELEASE(pluginInstance);
+        return retval;
     }
     return NULL;
 }
 
+/* Used only by MRJGetJSObject() below, which needs to be able to obtain a
+ * JSObject for an MRJPluginInstance that can be used in Java-to-JavaScript
+ * LiveConnect (so that, for example, the JVM's proxy support will work
+ * properly), without the MAYSCRIPT property having been set in one of that
+ * plugin instance's tags.  The Mozilla.org browsers don't seem to have
+ * anticipated the need for this, so I've had to hack out a solution myself.
+ * (The JVM calls the FindProxyForURL() JavaScript method (from
+ * AutoProxyHandler.getProxyInfo()) using Java-to-JavaScript LiveConnect,
+ * just after an MRJPluginInstance has been created (and before its applet has
+ * been loaded/created).)
+ */
+class GetWindowAltMessage : public JavaMessage {
+    jsobject* mWindowResult;
+public:
+    GetWindowAltMessage(MRJPluginInstance* pluginInstance, jsobject* windowResult)
+        :   JavaMessage(pluginInstance), mWindowResult(windowResult)
+    {
+    }
+    
+    virtual void execute(JNIEnv* env)
+    {
+        if (timedOut())
+            return;
+        jsobject jresult = 0;
+        MRJSecurityContext* securityContext = getSecurityContext(mPluginInstance);
+        if (securityContext == NULL) {
+            setIsDone();
+            return;
+        }
+        nsILiveconnect* connection = getLiveconnectInstance(securityContext);
+        if (connection == NULL) {
+            setIsDone();
+            return;
+        }
+        if (timedOut())
+            return;
+        JSContext *jsContext = getJSContext(mPluginInstance);
+        if (jsContext == NULL) {
+            setIsDone();
+            return;
+        }
+        if (timedOut())
+            return;
+        /* nsCLiveconnect::GetWindow() won't work if MAYSCRIPT isn't set, but
+         * we still need to call it, because it initializes mJavaClient.  And
+         * we need to squelch the exception that gets thrown when GetWindow()
+         * fails:  JS_ClearPendingException() works fine in Firefox 2.0 and
+         * on the trunk, but not in earlier Firefox versions (presumably
+         * because they don't yet support JavaScript exceptions) -- those
+         * earlier versions immediately throw a Java exception (in
+         * jsj_exit_js()).  But fortunately the JNI Throw call goes through
+         * our CSecureEnv class, so we're able to intervene to stop it from
+         * having any effect.
+         */
+        CSecureEnv::suspendExceptions();
+        nsresult status = connection->GetWindow(env, mPluginInstance, NULL, 0, securityContext, &jresult);
+        JS_ClearPendingExceptionPtr(jsContext);
+        CSecureEnv::resumeExceptions();
+        if (timedOut())
+            return;
+        if ((status != NS_OK) || !jresult) {
+            /* If GetWindow() fails because MAYSCRIPT isn't set, do here what
+             * GetWindow() would normally do if it _had_ been set (and the
+             * call to map_java_object_to_js_object() hadn't failed).
+             */
+            jresult = 0;
+            JSObject *window = NULL;
+            nsIPluginInstancePeer *peer;
+            if (mPluginInstance->GetPeer(&peer) == NS_OK) {
+                nsIPluginInstancePeer2 *peer2 = NULL;
+                if (peer->QueryInterface(NS_GET_IID(nsIPluginInstancePeer2),
+                    (void **) &peer2) == NS_OK)
+                {
+                    if (peer2->GetJSWindow(&window) != NS_OK)
+                        window = NULL;
+                    NS_RELEASE(peer2);
+                }
+                NS_RELEASE(peer);
+            }
+            if (window) {
+                JSObjectHandle *handle = (JSObjectHandle *)
+                    JS_mallocPtr(jsContext, sizeof(JSObjectHandle));
+                if (handle) {
+                    handle->js_obj = window;
+                    handle->rt = JS_GetRuntimePtr(jsContext);
+                    jresult = (jsobject) handle;
+                }
+            }
+        }
+        if (timedOut())
+            return;
+        *mWindowResult = jresult;
+        setIsDone();
+    }
+};
+
+#pragma export on
+
+extern "C"
+jobject MRJGetJSObject(JNIEnv *env, void *instance)
+{
+    MRJPluginInstance *pluginInstance = (MRJPluginInstance *) instance;
+    if (!liveConnectInited || !MRJPluginInstance::isValidInstance(pluginInstance))
+        return NULL;
+    NS_ADDREF(pluginInstance);
+    jsobject jswindow = 0;
+    GetWindowAltMessage *msg = new GetWindowAltMessage(pluginInstance, &jswindow);
+    if (msg) {
+        sendMessage(env, msg);
+        msg->waitTilDone(jsObjectTimeout);
+    }
+    jobject retval = NULL;
+    if (jswindow)
+        retval = Wrap_JSObject(env, jswindow, pluginInstance);
+    NS_RELEASE(pluginInstance);
+    return retval;
+}
+
+#pragma export off
+
 /*
  * Class:     netscape_javascript_JSObject
  * Method:    finalize
  * Signature: ()V
  */
 class FinalizeMessage : public JavaMessage {
     jsobject m_jsobj;
 public:
+	/* The extra initial AddRef() gives us more control over when we'll be
+	 * released.  (It stops us from being released after the next pair of
+	 * calls to AddRef() and Release(), but requires us to call Release() on
+	 * ourselves at the appropriate time.  As a result, we'll be released
+	 * after the end of the _last_ pair of calls (including our own pair) to
+	 * AddRef() and Release().)
+	 */
     FinalizeMessage(jsobject jsobj)
-        :   m_jsobj(jsobj)
+        :   JavaMessage(), m_jsobj(jsobj)
     {
+        AddRef();
+        mIsFinalizeMessage = true;
     }
 
     virtual void execute(JNIEnv* env)
     {
-        nsresult result = theLiveConnectManager->FinalizeJSObject(env, m_jsobj);
+        theLiveConnectManager->FinalizeJSObject(env, m_jsobj);
+        Release();
     }
 };
 
 JNIEXPORT void JNICALL
 Java_netscape_javascript_JSObject_finalize(JNIEnv* env, jobject java_wrapper_obj)
 {
     jsobject jsobj = Unwrap_JSObject(env, java_wrapper_obj);
 
-    FinalizeMessage msg(jsobj);
-    sendMessage(env, &msg);
+    FinalizeMessage *msg = new FinalizeMessage(jsobj);
+    if (msg) {
+        sendMessage(env, msg);
+    }
 }
diff -U 10 -r -N old/plugin/oji/MRJCarbon/plugin/Source/LiveConnectNativeMethods.h new/plugin/oji/MRJCarbon/plugin/Source/LiveConnectNativeMethods.h
--- old/plugin/oji/MRJCarbon/plugin/Source/LiveConnectNativeMethods.h	1969-12-31 18:00:00.000000000 -0600
+++ new/plugin/oji/MRJCarbon/plugin/Source/LiveConnectNativeMethods.h	2006-11-10 16:58:46.000000000 -0600
@@ -0,0 +1,57 @@
+/* ----- BEGIN LICENSE BLOCK -----
+ * Version: MPL 1.1/GPL 2.0/LGPL 2.1
+ *
+ * The contents of this file are subject to the Mozilla Public License Version
+ * 1.1 (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ * http://www.mozilla.org/MPL/
+ *
+ * Software distributed under the License is distributed on an "AS IS" basis,
+ * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
+ * for the specific language governing rights and limitations under the
+ * License.
+ *
+ * The Original Code is the MRJ Carbon OJI Plugin.
+ *
+ * The Initial Developer of the Original Code is
+ * Netscape Communications Corp.
+ * Portions created by the Initial Developer are Copyright (C) 2001
+ * the Initial Developer. All Rights Reserved.
+ *
+ * Contributor(s):  Patrick C. Beard <beard@netscape.com>
+ *
+ * Alternatively, the contents of this file may be used under the terms of
+ * either the GNU General Public License Version 2 or later (the "GPL"), or
+ * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
+ * in which case the provisions of the GPL or the LGPL are applicable instead
+ * of those above. If you wish to allow use of your version of this file only
+ * under the terms of either the GPL or the LGPL, and not to allow others to
+ * use your version of this file under the terms of the MPL, indicate your
+ * decision by deleting the provisions above and replace them with the notice
+ * and other provisions required by the GPL or the LGPL. If you do not delete
+ * the provisions above, a recipient may use your version of this file under
+ * the terms of any one of the MPL, the GPL or the LGPL.
+ *
+ * ----- END LICENSE BLOCK ----- */
+
+/*
+	LiveConnectNativeMethods.h
+ */
+
+#pragma once
+
+#include "nsError.h"
+
+#include "jni.h"
+
+class MRJPlugin;
+class MRJPluginInstance;
+
+nsresult InitLiveConnectSupport(MRJPlugin *jvmPlugin);
+nsresult PostInitLiveConnectSupport(MRJPlugin *jvmPlugin);
+nsresult ShutdownLiveConnectSupport(void);
+
+jobject Wrap_JSObject(JNIEnv* env, jint js_obj);
+jobject Wrap_JSObject(JNIEnv *env, jint js_obj, jobject applet);
+jobject Wrap_JSObject(JNIEnv *env, jint js_obj, MRJPluginInstance *instance);
+jint Unwrap_JSObject(JNIEnv* env, jobject java_wrapper_obj);
diff -U 10 -r -N old/plugin/oji/MRJCarbon/plugin/Source/MRJConsole.cpp new/plugin/oji/MRJCarbon/plugin/Source/MRJConsole.cpp
--- old/plugin/oji/MRJCarbon/plugin/Source/MRJConsole.cpp	2003-06-11 00:11:44.000000000 -0500
+++ new/plugin/oji/MRJCarbon/plugin/Source/MRJConsole.cpp	2004-04-17 20:29:45.000000000 -0500
@@ -51,29 +51,22 @@
 #include "MRJPlugin.h"
 #include "MRJSession.h"
 #include "TopLevelFrame.h"
 
 #include "nsIPluginManager2.h"
 
 extern nsIPluginManager2* thePluginManager2;
 
 MRJConsole* theConsole = NULL;
 
-const InterfaceInfo MRJConsole::sInterfaces[] = {
-	{ NS_IJVMCONSOLE_IID, INTERFACE_OFFSET(MRJConsole, nsIJVMConsole) },
-	{ NS_IEVENTHANDLER_IID, INTERFACE_OFFSET(MRJConsole, nsIEventHandler) },
-};
-const UInt32 MRJConsole::kInterfaceCount = sizeof(sInterfaces) / sizeof(InterfaceInfo);
-
 MRJConsole::MRJConsole(MRJPlugin* plugin)
-	:	SupportsMixin(this, sInterfaces, kInterfaceCount, (nsIPlugin*) plugin),
-		mPlugin(plugin), mSession(NULL), mIsInitialized(PR_FALSE),
+	:	mPlugin(plugin), mSession(NULL), mIsInitialized(PR_FALSE),
 		mConsoleClass(NULL), mInitMethod(NULL), mDisposeMethod(NULL),
 		mShowMethod(NULL), mHideMethod(NULL), mVisibleMethod(NULL), mPrintMethod(NULL), mFinishMethod(NULL),
 		mResults(NULL), mContext(NULL), mFrame(NULL)
 {
 	// Initialize();
 }
 
 MRJConsole::~MRJConsole()
 {
 	theConsole = NULL;
@@ -95,29 +88,46 @@
 
 #if !TARGET_CARBON		
 		if (mContext != NULL) {
 			JMDisposeAWTContext(mContext);
 			mContext = NULL;
 		}
 #endif
 	}
 }
 
+NS_IMPL_ADDREF(MRJConsole)
+NS_IMPL_RELEASE(MRJConsole)
+
 NS_METHOD MRJConsole::QueryInterface(const nsIID& aIID, void** aInstancePtr)
 {
-	nsresult result = queryInterface(aIID, aInstancePtr);
-	if (result == NS_NOINTERFACE)
-		result = mPlugin->queryInterface(aIID, aInstancePtr);
-	return result;
+    if (aInstancePtr == NULL) {
+        return NS_ERROR_NULL_POINTER;
+    }
+    *aInstancePtr = NULL;
+    if (aIID.Equals(NS_GET_IID(nsIJVMConsole))) {
+        *aInstancePtr = (void *) (nsIJVMConsole *) this;
+        AddRef();
+        return NS_OK;
+    }
+    if (aIID.Equals(NS_GET_IID(nsIEventHandler))) {
+        *aInstancePtr = (void *) (nsIEventHandler *) this;
+        AddRef();
+        return NS_OK;
+    }
+    if (aIID.Equals(NS_GET_IID(nsISupports))) {
+        *aInstancePtr = (void *) this;
+        AddRef();
+        return NS_OK;
+    }
+	return mPlugin->QueryInterface(aIID, aInstancePtr);
 }
-nsrefcnt MRJConsole::AddRef() { return addRef(); }
-nsrefcnt MRJConsole::Release() { return release(); }
 
 #pragma mark ***** MRJConsole *****
 
 NS_METHOD MRJConsole::Show()
 {
 	Initialize();
 
 	if (mShowMethod != NULL) {
 		CallConsoleMethod(mShowMethod);
 		return NS_OK;
diff -U 10 -r -N old/plugin/oji/MRJCarbon/plugin/Source/MRJConsole.h new/plugin/oji/MRJCarbon/plugin/Source/MRJConsole.h
--- old/plugin/oji/MRJCarbon/plugin/Source/MRJConsole.h	2003-06-11 00:11:44.000000000 -0500
+++ new/plugin/oji/MRJCarbon/plugin/Source/MRJConsole.h	2004-03-07 10:46:12.000000000 -0600
@@ -37,40 +37,34 @@
 /*
 	MRJConsole.h
 	
 	Implements the JVM console interface.
 	
 	by Patrick C. Beard.
  */
 
 #include "nsIJVMConsole.h"
 #include "nsIEventHandler.h"
-#include "SupportsMixin.h"
 
 #include "jni.h"
 
 class MRJPlugin;
 class MRJSession;
 class TopLevelFrame;
 
 class MRJConsole :	public nsIJVMConsole,
-					public nsIEventHandler,
-					public SupportsMixin {
+					public nsIEventHandler {
 public:
 	MRJConsole(MRJPlugin* plugin);
 	virtual ~MRJConsole();
 
-	// NS_DECL_ISUPPORTS
-	// DECL_SUPPORTS_MIXIN
-	NS_IMETHOD QueryInterface(REFNSIID aIID, void** aInstancePtr);
-	NS_IMETHOD_(nsrefcnt) AddRef(void);
-	NS_IMETHOD_(nsrefcnt) Release(void);
+    NS_DECL_ISUPPORTS
 
 	// nsIJVMConsole methods.
 
     NS_IMETHOD
     Show(void);
 
     NS_IMETHOD
     Hide(void);
 
     NS_IMETHOD
@@ -112,15 +106,11 @@
 	jmethodID mPrintMethod;
 	jmethodID mFinishMethod;
 
 	jbooleanArray mResults;
 
 #if !TARGET_CARBON
 	JMAWTContextRef mContext;
 #endif
     
 	TopLevelFrame* mFrame;
-
-	// support for SupportsMixin.
-	static const InterfaceInfo sInterfaces[];
-	static const UInt32 kInterfaceCount;
 };
diff -U 10 -r -N old/plugin/oji/MRJCarbon/plugin/Source/MRJContext.cp new/plugin/oji/MRJCarbon/plugin/Source/MRJContext.cp
--- old/plugin/oji/MRJCarbon/plugin/Source/MRJContext.cp	2003-06-11 00:11:46.000000000 -0500
+++ new/plugin/oji/MRJCarbon/plugin/Source/MRJContext.cp	2006-12-14 22:59:46.000000000 -0600
@@ -76,31 +76,38 @@
 #include "MRJMonitor.h"
 #include "AsyncMessage.h"
 #include "LocalPort.h"
 #include "StringUtils.h"
 #include "TimedMessage.h"
 #if !TARGET_CARBON
 #include "TopLevelFrame.h"
 #include "EmbeddedFrame.h"
 #endif
 
+#import "JavaEmbeddingPlugin.h"
+#include "JavaEmbeddingPlugin.cpp"
+extern "C" Boolean JEPCheckBundle();
+
 #include "nsIPluginManager2.h"
 #include "nsIPluginInstancePeer.h"
 #include "nsIJVMPluginTagInfo.h"
 #include "MRJSecurityContext.h"
 
 #include <string>
 
 using namespace std;
 
 extern nsIPluginManager* thePluginManager;
 extern nsIPluginManager2* thePluginManager2;
+extern MRJPlugin* theJVMPlugin;
+extern Boolean debugUpdates;
+extern Boolean debugPrinting;
 
 static void blinkRgn(RgnHandle rgn);
 
 void LocalPort::Enter()
 {
     ::GetPort(&fOldPort);
     if (fPort != fOldPort)
         ::SetPort(fPort);
     Rect portRect;
     GetPortBounds(fPort, &portRect);
@@ -123,31 +130,35 @@
     if (region != NULL) ::SetEmptyRgn(region);
     return region;
 }
 
 MRJContext::MRJContext(MRJSession* session, MRJPluginInstance* instance)
     :   mPluginInstance(instance), mSession(session), mPeer(NULL),
 #if !TARGET_CARBON
         mLocator(NULL), mContext(NULL), mViewer(NULL), mViewerFrame(NULL),
 #endif
         mIsActive(false), mIsFocused(false), mIsVisible(false),
-        mPluginClipping(NULL), mPluginWindow(NULL), mPluginPort(NULL),
-        mDocumentBase(NULL), mAppletHTML(NULL), mPage(NULL), mSecurityContext(NULL)
+        mUpdatesSequence(0), mPluginClipping(NULL), mPluginWindow(NULL),
+        mPluginPort(NULL), mDocumentBase(NULL), mAppletHTML(NULL),
+        mPage(NULL), mSecurityContext(NULL), mAppletLoading(false),
+        mDestroying(false)
 #if TARGET_CARBON
-        , mAppletFrame(NULL), mAppletObject(NULL), mAppletControl(NULL), mScrollCounter(0)
+        , mAppletFrame(NULL), mAppletObject(NULL), mAppletControl(NULL),
+        mScrollCounter(0), mJEPHandle(NULL)
 #endif
 {
     instance->GetPeer(&mPeer);
     
     // we cache attributes of the window, and periodically notice when they change.
     mCachedOrigin.x = mCachedOrigin.y = -1;
     ::SetRect((Rect*)&mCachedClipRect, 0, 0, 0, 0);
+    ::SetRect(&mCachedWindowRect, 0, 0, 0, 0);
     mPluginClipping =::NewEmptyRgn();
     mPluginPort = getEmptyPort();
 }
 
 MRJContext::~MRJContext()
 {
 #if !TARGET_CARBON
     if (mLocator != NULL) {
         JMDisposeAppletLocator(mLocator);
         mLocator = NULL;
@@ -201,24 +212,20 @@
     }
     
     if (mSecurityContext != NULL) {
         mSecurityContext->Release();
         mSecurityContext = NULL;
     }
 
 #if TARGET_CARBON
     if (mSession) {
         JNIEnv* env = mSession->getCurrentEnv();
-        if (mAppletObject != NULL) {
-            env->DeleteGlobalRef(mAppletObject);
-            mAppletObject = NULL;
-        }
         if (mAppletControl != NULL) {
             ::DisposeControl(mAppletControl);
             mAppletControl = NULL;
         }
         if (mAppletFrame != NULL) {
             OSStatus status;
             
             // disconnect callbacks.
             status = ::RegisterStatusCallback(env, mAppletFrame, NULL, NULL);
             status = ::RegisterShowDocumentCallback(env, mAppletFrame, NULL, NULL);
@@ -240,23 +247,39 @@
     return mContext;
 }
 
 JMAppletViewerRef MRJContext::getViewerRef()
 {
     return mViewer;
 }
 
 #endif
 
+/* If the applet wasn't created for some reason it stays "loading" forever --
+ * that stops the browser from repeatedly trying to reload it MRJContext::
+ * setWindow().
+ */
+Boolean MRJContext::appletLoading()
+{
+    return mAppletLoading;
+}
+
+void MRJContext::setAppletLoading(Boolean loading)
+{
+    mAppletLoading = loading;
+}
+
 Boolean MRJContext::appletLoaded()
 {
 #if TARGET_CARBON
+    if (JEPCheckBundle())
+        return (mJEPHandle && mAppletObject);
     return (mAppletFrame && mAppletControl);
 #else
     return (mViewer != NULL);
 #endif
 }
 
 static char* slashify(char* url)
 {
     int len = ::strlen(url);
     if (url[len - 1] != '/') {
@@ -478,20 +501,47 @@
                 cfref<CFStringRef> value = CFStringCreateWithCString(NULL, values[i], kCFStringEncodingUTF8);
                 if (name && value)
                     CFDictionaryAddValue(parameters, name, value);
             }
             return parameters;
         }
     }
     return NULL;
 }
 
+static CFMutableDictionaryRef combineAttrsAndParms(
+	CFMutableDictionaryRef attributes, CFMutableDictionaryRef parameters)
+{
+    CFIndex countAttrs = 0, countParms = 0, countTotal;
+	if (attributes)
+		countAttrs = CFDictionaryGetCount(attributes);
+	if (parameters)
+		countParms = CFDictionaryGetCount(parameters);
+	countTotal = countAttrs + countParms;
+	CFMutableDictionaryRef combined = NULL;
+	if (attributes) {
+		combined = CFDictionaryCreateMutableCopy(NULL, countTotal, attributes);
+		if (combined && parameters) {
+			char *names[countParms];
+			char *values[countParms];
+			CFDictionaryGetKeysAndValues(parameters, (const void **) &names,
+				(const void **) &values);
+			for (CFIndex i = 0; i < countParms; ++i) {
+				CFDictionaryAddValue(combined, names[i], values[i]);
+			}
+		}
+	} else if (parameters) {
+		combined = CFDictionaryCreateMutableCopy(NULL, countTotal, parameters);
+	}
+	return combined;
+}
+
 #endif
 
 void MRJContext::processAppletTag()
 {
     // use the applet's HTML element to create a locator. this is required
     // in general, to specify a separate CODEBASE.
 
     nsIPluginTagInfo* tagInfo = NULL;
     if (mPeer->QueryInterface(NS_GET_IID(nsIPluginTagInfo), (void**)&tagInfo) == NS_OK) {
         nsIPluginTagInfo2* tagInfo2 = NULL;
@@ -781,62 +831,84 @@
 {
 	// worst case length scenario would encode every character
     CFIndex len = (1 + ::CFStringGetLength(stringRef)) * 3;
     char* result = new char[len];
     if (result)
         CFStringGetCString(stringRef, result, len, kCFStringEncodingUTF8);
     return result;
 }
 
 class SetStatusMessage : public TimedMessage {
-    nsIPluginInstance* mPluginInstance;
+    MRJPluginInstance* mPluginInstance;
     CFStringRef mStatus;
 
 public:
-    SetStatusMessage(nsIPluginInstance* pluginInstance, CFStringRef statusString)
+    SetStatusMessage(MRJPluginInstance* pluginInstance, CFStringRef statusString)
         : mPluginInstance(pluginInstance), mStatus(statusString)
     {
         NS_ADDREF(mPluginInstance);
         ::CFRetain(mStatus);
     }
     
     ~SetStatusMessage()
     {
         ::CFRelease(mStatus);
         NS_RELEASE(mPluginInstance);
     }
     
     virtual void execute();
 };
 
 void SetStatusMessage::execute()
 {
+    if (!MRJPluginInstance::isValidInstance(mPluginInstance))
+        return;
     char* status = getCString(mStatus);
     if (status) {
         nsIPluginInstancePeer* peer;
         mPluginInstance->GetPeer(&peer);
         if (peer) {
             peer->ShowStatus(status);
             NS_RELEASE(peer);
         }
         delete[] status;
     }
 }
 
 static void setStatusCallback(jobject applet, CFStringRef statusMessage, void *inUserData)
 {
+    if (!theJVMPlugin)
+        return;
     // use a timer on the main event loop to handle this?
-    MRJContext* context = reinterpret_cast<MRJContext*>(inUserData);
-    SetStatusMessage* message = new SetStatusMessage(context->getInstance(), statusMessage);
+    /* inUserData used to be set to a pointer to our MRJContext, but this is
+     * more likely to have been deleted by this point than a pointer to our
+     * MRJPluginInstance -- from which we can more safely determine whether
+     * the applet is being destroyed.
+     */
+    MRJPluginInstance *pluginInstance = reinterpret_cast<MRJPluginInstance*>(inUserData);
+    if (!MRJPluginInstance::isValidInstance(pluginInstance))
+        return;
+    SetStatusMessage* message = new SetStatusMessage(pluginInstance, statusMessage);
     if (message) {
-        OSStatus status = message->send();
-        if (status != noErr) delete message;
+        /* Execute the "message" directly if we're already on the main thread.
+         * Otherwise get it posted to the main event loop -- where it will get
+         * executed on the main thread.
+         */
+        if (theJVMPlugin->getSession()->getCurrentEnv() ==
+            theJVMPlugin->getSession()->getMainEnv())
+        {
+            message->execute();
+            delete message;
+        } else {
+            OSStatus status = message->send();
+            if (status != noErr) delete message;
+        }
     }
 }
 
 class ShowDocumentMessage : public TimedMessage {
     MRJPluginInstance* mPluginInstance;
     CFURLRef mURL;
     CFStringRef mWindowName;
 
 public:
     ShowDocumentMessage(MRJPluginInstance* pluginInstance, CFURLRef url, CFStringRef windowName)
@@ -948,23 +1020,22 @@
         *fullPath = NULL;
         *fullPathLength = 0;
     }
     
     return ( result );
 }
 
 void ShowDocumentMessage::execute()
 {
     // guard against the plugin instance already having been destroyed.
-    if (mPluginInstance->getContext() == NULL) {
+    if (!MRJPluginInstance::isValidInstance(mPluginInstance))
         return;
-    }
     
     char* url = NULL;
     char* target = NULL;
 
     CFStringRef urlRef = ::CFURLGetString(mURL);
     if (urlRef) {
         if (::CFStringHasPrefix(urlRef, CFSTR("file:"))) {
             // work around for bug #108519, convert to HFS+ file system path.
             // question:  why can't CFURLGetFSRef be used to extract the FSRef
             // directly from the FSRef provided? I believe it's in the wrong
@@ -1011,71 +1082,139 @@
     
     if (url && target)
         thePluginManager->GetURL((nsIPluginInstance*)mPluginInstance, url, target);
 
     delete[] url;
     delete[] target;
 }
 
 static void showDocumentCallback(jobject applet, CFURLRef url, CFStringRef windowName, void *inUserData)
 {
+    if (!theJVMPlugin)
+        return;
     // workaround for bug #108054, sometimes url parameter is NULL.
     if (url) {
         // use a timer on the main event loop to handle this?
-        MRJContext* context = reinterpret_cast<MRJContext*>(inUserData);
-        ShowDocumentMessage* message = new ShowDocumentMessage((MRJPluginInstance*)context->getInstance(), url, windowName);
+        /* inUserData used to be set to a pointer to our MRJContext, but this is
+         * more likely to have been deleted by this point than a pointer to our
+         * MRJPluginInstance -- from which we can more safely determine whether
+         * the applet is being destroyed.
+         */
+        MRJPluginInstance *pluginInstance = reinterpret_cast<MRJPluginInstance*>(inUserData);
+        if (!MRJPluginInstance::isValidInstance(pluginInstance))
+            return;
+        ShowDocumentMessage* message = new ShowDocumentMessage(pluginInstance, url, windowName);
         if (message) {
-            OSStatus status = message->send();
-            if (status != noErr) delete message;
+            /* Execute the "message" directly if we're already on the main
+             * thread.  Otherwise get it posted to the main event loop --
+             * where it will get executed on the main thread.
+             */
+            if (theJVMPlugin->getSession()->getCurrentEnv() ==
+                theJVMPlugin->getSession()->getMainEnv())
+            {
+                message->execute();
+                delete message;
+            } else {
+                OSStatus status = message->send();
+                if (status != noErr) delete message;
+            }
         }
     }
 }
 
-static void fixAttributes(CFMutableDictionaryRef attributes, nsIPluginTagInfo* tagInfo, nsPluginWindow* window)
+static Boolean fixAttributes(CFMutableDictionaryRef attributes, nsIPluginTagInfo* tagInfo, nsPluginWindow* window)
 {
+    if (!window)
+        return false;
+    Boolean nonAbsoluteSize = false;
+    unsigned percent;
     // check for WIDTH & HEIGHT attributes that end with % or *, and replace those with the physical values.
     const char* width;
     if (tagInfo->GetAttribute("WIDTH", &width) == NS_OK) {
         if (strpbrk(width, "%*")) {
-            cfref<CFStringRef> actualWidth = CFStringCreateWithFormat(NULL, NULL, CFSTR("%d"), window->width);
+            sscanf(width, "%u", &percent);
+            cfref<CFStringRef> actualWidth = CFStringCreateWithFormat(NULL, NULL, CFSTR("%d"), (window->width * percent)/100);
             CFDictionaryReplaceValue(attributes, CFSTR("WIDTH"), actualWidth);
+            nonAbsoluteSize = true;
         }
     }
     
     const char* height;
     if (tagInfo->GetAttribute("HEIGHT", &height) == NS_OK) {
         if (strpbrk(height, "%*")) {
-            cfref<CFStringRef> actualHeight = CFStringCreateWithFormat(NULL, NULL, CFSTR("%d"), window->height);
+            sscanf(height, "%u", &percent);
+            cfref<CFStringRef> actualHeight = CFStringCreateWithFormat(NULL, NULL, CFSTR("%d"), (window->height * percent)/100);
             CFDictionaryReplaceValue(attributes, CFSTR("HEIGHT"), actualHeight);
+            nonAbsoluteSize = true;
         }
     }
+    return nonAbsoluteSize;
+}
+
+static void appletCreatedCallback(void *handle, JavaVM *vm, jobject applet,
+    WindowRef window, AppletStateJEP status, void *userData)
+{
+    /* We used to set our userData parameter to a pointer to MRJContext.  But
+     * our MRJContext object might have been deleted before this point is
+     * reached, so we need to get our MRJContext object's address from our
+     * MRJPluginInstance object -- which by means of an extra call to
+     * NS_ADDREF() in loadApplet() we guarantee to still be around when we
+     * reach this point.
+     */
+    MRJPluginInstance *pluginInstance =
+        reinterpret_cast<MRJPluginInstance*>(userData);
+    if (!MRJPluginInstance::isValidInstance(pluginInstance))
+        return;
+    MRJContext* context = pluginInstance->getContext();
+    if (!context)
+        return;
+    if (status == kAppletDestroyJEP) {
+        NS_RELEASE(pluginInstance);
+        return;
+    }
+    context->setApplet(applet);		// Might be NULL if loading applet failed
+    context->clearAttributeCaches();
+    if (status != kAppletErrorJEP)
+        context->setAppletLoading(false);
+    /* As of version 0.8.7 the JEP takes care of making the applet view
+     * visible (just after the applet has been created or failed to be
+     * created) and starting the applet (just after it's been initialized).
+     */
+    NS_RELEASE(pluginInstance);
 }
 
 #endif /* TARGET_CARBON */
 
 Boolean MRJContext::loadApplet()
 {
     OSStatus status = noErr;
-    
+
+    if (isDestroying())
+        return false;
+
 #if TARGET_CARBON
     // Use whizzy new JavaEmbedding APIs to construct an AppletDescriptor.
     
     // gather all attributes and parameters.
-    cfref<CFMutableDictionaryRef> attributes, parameters;
+    cfref<CFMutableDictionaryRef> attributes, parameters, attrsAndParms;
     nsIPluginTagInfo2* tagInfo2 = NULL;
     if (mPeer->QueryInterface(NS_GET_IID(nsIPluginTagInfo2), (void**)&tagInfo2) == NS_OK) {
         attributes = getAttributes(tagInfo2);
-        fixAttributes(attributes, tagInfo2, mPluginWindow); 
         parameters = getParameters(tagInfo2);
+        if (JEPCheckBundle()) {
+            attrsAndParms = combineAttrsAndParms(attributes, parameters);
+        } else {
+            fixAttributes(attributes, tagInfo2, mPluginWindow);
+        }
         NS_RELEASE(tagInfo2);
     }
-    
+
     cfref<CFURLRef> documentBase;
     if (!TARGET_RT_MAC_MACHO && ::strncmp(mDocumentBase, "file:", 5) == 0) {
         // file: URLs. Need to create the URL from HFS+ style using CFURLCreateWithFileSystemPath.
         // this is to workaround the same problem in bug #108519, Mozilla uses HFS+ paths that are
         // simply converted to '/' delimited URLs. The mach-o build won't have this problem, so
         // we'll need to detect that build somehow.
         char* path = mDocumentBase + 5;
         while (*path == '/') ++path;
         path = strdup(path);
         if (path) {
@@ -1091,40 +1230,82 @@
                 // unescape the path in case there are spaces in it
                 cfref<CFStringRef> unescPathRef = CFURLCreateStringByReplacingPercentEscapes(NULL, pathRef, CFSTR(""));
                 if (unescPathRef)
                     documentBase = CFURLCreateWithFileSystemPath(NULL, unescPathRef, kCFURLHFSPathStyle, false);
             }
         }
     } else {
         documentBase = CFURLCreateWithBytes(NULL, (const UInt8*)mDocumentBase,
                                             strlen(mDocumentBase), kCFStringEncodingUTF8, NULL);
     }
-    
-    if (attributes && parameters && documentBase) {
+
+    if (JEPCheckBundle() && attrsAndParms && documentBase) {
+		NS_ADDREF(mPluginInstance);
+        JEPOptions options = {{0},0};
+		if (mPluginWindow) {
+			options.appletClip.top = mPluginWindow->clipRect.top;
+			options.appletClip.left = mPluginWindow->clipRect.left;
+			options.appletClip.bottom = mPluginWindow->clipRect.bottom;
+			options.appletClip.right = mPluginWindow->clipRect.right;
+			options.appletPosX = -mPluginWindow->window->portx;
+			options.appletPosY = -mPluginWindow->window->porty;
+			options.appletWidth = mPluginWindow->width;
+			options.appletHeight = mPluginWindow->height;
+		}
+		//options.createdInvisible = true;
+        options.appletCreatedCallback = appletCreatedCallback;
+        options.appletCreatedUserData = mPluginInstance;
+        options.showStatusCallback = &setStatusCallback;
+        options.showStatusUserData = mPluginInstance;
+        options.showDocumentCallback = &showDocumentCallback;
+        options.showDocumentUserData = mPluginInstance;
+        options.instance = mPluginInstance;
+        status = JEPCreateJavaApplet(documentBase, attrsAndParms,
+            GetWindowFromPort(mPluginPort), &options, &mJEPHandle);
+        if (status != noErr)
+            NS_RELEASE(mPluginInstance);
+    } else if (attributes && parameters && documentBase) {
         AppletDescriptor desc = {
             documentBase,
             NULL,
             attributes,
             parameters,
         };
         JNIEnv* env = mSession->getCurrentEnv();
         status = ::CreateJavaApplet(env, desc, false, kUniqueArena, &mAppletFrame);
         if (status == noErr) {
             // install status/document callbacks.
-            status = ::RegisterStatusCallback(env, mAppletFrame, &setStatusCallback, this);
-            status = ::RegisterShowDocumentCallback(env, mAppletFrame, &showDocumentCallback, this);
+            status = ::RegisterStatusCallback(env, mAppletFrame, &setStatusCallback, mPluginInstance);
+            status = ::RegisterShowDocumentCallback(env, mAppletFrame, &showDocumentCallback, mPluginInstance);
 
             // wrap applet in a control.
             Rect bounds = { 0, 0, 100, 100 };
             status = ::CreateJavaControl(env, GetWindowFromPort(mPluginPort), &bounds, mAppletFrame, true, &mAppletControl);
             if (status == noErr) {
                 status = ::SetJavaAppletState(env, mAppletFrame, kAppletStart);
+                /* The following makes it more likely for an applet to be
+                 * visible in a JavaScript onLoad handler -- and thus for
+                 * JavaScript to be able to call the applet's methods from
+                 * the handler.  But even with this fix, you ususally have to
+                 * reload the page at least once.  The second and subsequent
+                 * times the applet will already be in the JVM's cache, so
+                 * it will load more quickly.  In any case the applet will
+                 * never be ready before loadApplet() returns -- I suppose
+                 * the JVM, while mostly working on secondary threads, must
+                 * do some processing on the main thread (from which
+                 * loadApplet() is called) before the applet can be created.
+                 */
+                nsIJVMThreadManager *manager = NULL;
+                if (theJVMPlugin)
+                    manager = theJVMPlugin->getThreadManager();
+                if (manager)
+                    manager->Sleep(300);
             }
         }
     }
 #else
     static JMAppletSecurity security = {
         kJMVersion,                     /* should be set to kJMVersion */
         eAppletHostAccess,              /* can this applet access network resources */
         eLocalAppletAccess,             /* can this applet access network resources */
         true,                           /* restrict access to system packages (com.apple.*, sun.*, netscape.*) also found in the property "mrj.security.system.access" */
         true,                           /* restrict classes from loading system packages (com.apple.*, sun.*, netscape.*) also found in the property "mrj.security.system.define" */
@@ -1188,21 +1369,25 @@
     if (NS_SUCCEEDED(peer->QueryInterface(NS_GET_IID(nsIPluginTagInfo), (void**)&tagInfo))) {
         tagInfo->GetAttribute(name, &value);
         NS_RELEASE(tagInfo);
     }
     return value;
 }
 
 jobject MRJContext::getApplet()
 {
 #if TARGET_CARBON
-    if (appletLoaded() && mAppletObject == NULL) {
+    if (JEPCheckBundle()) {
+        //printf("MRJContext::getApplet(): Returning mAppletObject == 0x%.8X (1.4.X)\n", mAppletObject);
+        return mAppletObject;
+    }
+    if (!isDestroying() && appletLoaded() && mAppletObject == NULL) {
         // mAppletFrame is an instance of javap com.apple.mrj.JavaEmbedding.JE_AppletViewer, as of Mac OS X 10.1.
         // In Mac OS X 10.1, it implemented the java.applet.AppletContext interface, but this is no longer true
         // in Mac OS X 10.2 (Jaguar). However both versions of JE_AppletViewer have a public field panel, which
         // is an instance of com.apple.mrj.JavaEmbedding.JE_AppletViewerPanel, which extends sun.applet.AppletPanel,
         // which contains the method public java.applet.Applet getApplet(). Apple needs to provide us with an API
         // that we can use, but for now this is the best that we can do.
         JNIEnv* env = mSession->getCurrentEnv();
         jclass frameClass = env->GetObjectClass(mAppletFrame);
         if (frameClass) {
             jfieldID panelID = env->GetFieldID(frameClass, "panel", "Lcom/apple/mrj/JavaEmbedding/JE_AppletViewerPanel;");
@@ -1228,21 +1413,21 @@
             } else {
                 env->ExceptionClear();
             }
             env->DeleteLocalRef(frameClass);
         } else {
             env->ExceptionClear();
         }
     }
     return mAppletObject;
 #else
-    if (appletLoaded() && &::JMGetAppletJNIObject != NULL) {
+    if (!isDestroying() && appletLoaded() && &::JMGetAppletJNIObject != NULL) {
         JNIEnv* env = ::JMGetCurrentEnv(mSessionRef);
         jobject appletObject = ::JMGetAppletJNIObject(mViewer, env);
         if (appletObject == NULL) {
             // Give MRJ some time to try to comply. 100 calls to JMIdle should be enough.
             // 10 seconds should be enough. Could ask the user...
             UInt32 deadline = ::TickCount() + 600;
             while (appletObject == NULL && ::TickCount() < deadline) {
                 mSession->idle(kDefaultJMTime);
                 appletObject = ::JMGetAppletJNIObject(mViewer, env);
             }
@@ -1255,44 +1440,96 @@
                     SInt16 itemHit = 0;
                     Str255 appletURL = { "\pUnknown APPLET URL" };
                     if (mDocumentBase != NULL) {
                         appletURL[0] = ::strlen(mDocumentBase);
                         ::BlockMoveData(mDocumentBase, appletURL + 1, mDocumentBase[0]);
                     }
                     ::StandardAlert(kAlertPlainAlert, "\pApplet failed to load from URL:", appletURL, NULL, &itemHit);
                 }
             }
         }
-        return appletObject;
     }
+    return appletObject;
 #endif
 }
 
+#if TARGET_CARBON
+
+void MRJContext::setApplet(jobject newApplet)
+{
+	JNIEnv* env = mSession->getCurrentEnv();
+	if (mAppletObject != NULL)
+		env->DeleteGlobalRef(mAppletObject);
+	if (!newApplet) {
+		mAppletObject = NULL;
+		return;
+	}
+	mAppletObject = env->NewGlobalRef(newApplet);
+}
+
+#endif
+
 nsIPluginInstance* MRJContext::getInstance()
 {
     return mPluginInstance;
 }
 
 nsIPluginInstancePeer* MRJContext::getPeer()
 {
     return mPeer;
 }
 
+//#define UPDATES_SEQUENCE_MAX 1
+#define UPDATES_SEQUENCE_MAX 2
+
 /**
  * At various times during development, it is useful to see what bits are supposed to be drawn by
  * the applet. Defining DEBUG_CLIPPING as 1 turns on this behavior.
  */
 #define DEBUG_CLIPPING 0
 
 void MRJContext::drawApplet()
 {
+    if (isDestroying())
+        return;
 #if TARGET_CARBON
+    /* If mUpdatesSequence is greater than a certain amount, we don't redraw
+     * the applet unless it seems to be necessary.  This helps to deal with
+     * the excessive number of updates triggered by all of the Mozilla-family
+     * browsers, but particularly by Camino -- among other things, if an
+     * applet accepts keyboard input, its display gets updated every time you
+     * press a key!  (As of JEP 0.9.3 we now handle the spurious keystroke
+     * updates in JEPMaybeDrawJavaApplet().  We also now pass all the
+     * potentially spurious updates to JavaEmbeddingPlugin.bundle for it to
+     * handle -- which results in more of them being acted on.  This was
+     * needed to stop applets occasionally disappearing, especially in Camino
+     * 0.9a1.)
+     */
+    if (mUpdatesSequence > UPDATES_SEQUENCE_MAX) {
+        if (debugUpdates)
+            JEPLogJavaMessage(CFSTR("MRJContext::drawApplet(): Processing potentially spurious update"));
+        if (JEPCheckBundle()) {
+            JEPMaybeDrawJavaApplet(mJEPHandle);
+        } else if (checkPaintNeeded()) {
+            synchronizeClipping();
+        }
+        return;
+    } else {
+        if (++mUpdatesSequence == 0)
+            mUpdatesSequence = UPDATES_SEQUENCE_MAX + 1;
+    }
+    if (debugUpdates)
+        JEPLogJavaMessage(CFSTR("MRJContext::drawApplet(): Drawing"));
+    if (JEPCheckBundle()) {
+        JEPDrawJavaApplet(mJEPHandle);
+        return;
+    }
     // ??? It's a control. Draw it with Draw1Control?
     JNIEnv* env = mSession->getCurrentEnv();
     OSStatus status = ::DrawJavaControl(env, mAppletControl);
 #else
     // We assume the proper coordinate system for the frame has
     // already been set up.
     if (appletLoaded()) {
 #if DEBUG_CLIPPING
         nsPluginPort* npPort = (nsPluginPort*) mCache.window;
         GrafPtr framePort = GrafPtr(npPort->port);
@@ -1308,20 +1545,22 @@
 
         // ::JMFrameUpdate(mViewerFrame, framePort->visRgn);
         // OSStatus status = ::JMFrameUpdate(mViewerFrame, framePort->clipRgn);
         OSStatus status = ::JMFrameUpdate(mViewerFrame, mPluginClipping);
     }
 #endif /* !TARGET_CARBON */
 }
 
 void MRJContext::printApplet(nsPluginWindow* printingWindow)
 {
+    if (debugPrinting)
+        JEPLogJavaMessage(CFSTR("MRJContext::printApplet(): Calling"));
 #if TARGET_CARBON
 #else
     jobject frameObject = NULL;
     jclass utilsClass = NULL;
     OSStatus status = noErr;
     JNIEnv* env = ::JMGetCurrentEnv(mSessionRef); 
     
     // put the printing port into window coordinates:  (0, 0) in upper left corner.
     GrafPtr printingPort = GrafPtr(printingWindow->window->port);
     LocalPort localPort(printingPort);
@@ -1393,21 +1632,28 @@
     // ???
 #else
     if (mViewerFrame != NULL) {
         ::JMFrameResume(mViewerFrame, inFront);
     }
 #endif
 }
 
 void MRJContext::click(const EventRecord* event, MRJFrame* appletFrame)
 {
+    if (isDestroying())
+        return;
 #if TARGET_CARBON
+    mUpdatesSequence = UPDATES_SEQUENCE_MAX + 1;
+    if (JEPCheckBundle()) {
+        mIsFocused = true;
+        return;
+    }
     // won't Carbon events just take care of everything?
     LocalPort port(mPluginPort);
     port.Enter();
 
     Point localWhere = event->where;
     ::GlobalToLocal(&localWhere);
     ::HandleControlClick(mAppletControl, localWhere,
                          event->modifiers, NULL);
 
     // the Java control seems to focus itself automatically when clicked in.
@@ -1455,74 +1701,121 @@
 #else
     if (mViewerFrame != NULL) {
         ::JMFrameKeyRelease(mViewerFrame, message & charCodeMask,
                     (message & keyCodeMask) >> 8, modifiers);
     }
 #endif
 }
 
 void MRJContext::scrollingBegins()
 {
+    if (isDestroying())
+        return;
+    if (debugUpdates)
+        JEPLogJavaMessage(CFSTR("MRJContext::scrollingBegins(): Calling"));
     if (mScrollCounter++ == 0) {
+        if (mJEPHandle)
+            JEPSuspendJavaAppletUpdates(mJEPHandle);
         if (mAppletControl) {
             JNIEnv* env = mSession->getCurrentEnv();
             StopJavaControlAsyncDrawing(env, mAppletControl);
         }
     }
 }
 
 void MRJContext::scrollingEnds()
 {
+    if (isDestroying())
+        return;
+    if (debugUpdates)
+        JEPLogJavaMessage(CFSTR("MRJContext::scrollingEnds(): Calling"));
     if (--mScrollCounter == 0) {
+        if (mJEPHandle) {
+            synchronizeClipping();
+            JEPResumeJavaAppletUpdates(mJEPHandle);
+        }
         if (mAppletControl) {
             synchronizeClipping();
             JNIEnv* env = mSession->getCurrentEnv();
             RestartJavaControlAsyncDrawing(env, mAppletControl);
         }
     }
 }
 
+static void updateEvtBreak()
+{
+	return;
+}
+
 Boolean MRJContext::handleEvent(EventRecord* event)
 {
+    if (isDestroying())
+        return false;
     Boolean eventHandled = false;
-    if (mAppletControl) {
+    if (mJEPHandle || mAppletControl) {
         eventHandled = true;
         switch (event->what) {
         case updateEvt:
+            if (debugUpdates) {
+				updateEvtBreak();
+                JEPLogJavaMessage(CFSTR("MRJContext::handleEvent(): updateEvt"));
+			}
             drawApplet();
             break;
             
         case keyDown:
+            if (debugUpdates)
+                JEPLogJavaMessage(CFSTR("MRJContext::handleEvent(): keyDown"));
+            mUpdatesSequence = UPDATES_SEQUENCE_MAX + 1;
             if (mIsFocused) {
-                ::HandleControlKey(mAppletControl,
-                                   (event->message & keyCodeMask) >> 8,
-                                   (event->message & charCodeMask),
-                                   event->modifiers);
+                if (mAppletControl) {
+                    ::HandleControlKey(mAppletControl,
+                                      (event->message & keyCodeMask) >> 8,
+                                      (event->message & charCodeMask),
+                                      event->modifiers);
+                }
                 eventHandled = true;
             }
             break;  
 
         case mouseDown:
+            if (debugUpdates)
+                JEPLogJavaMessage(CFSTR("MRJContext::handleEvent(): mouseDown"));
             click(event, NULL);
             eventHandled = mIsFocused;
             break;
 
         case nsPluginEventType_GetFocusEvent:
+            if (debugUpdates)
+                JEPLogJavaMessage(CFSTR("MRJContext::handleEvent(): nsPluginEventType_GetFocusEvent"));
             if (!mIsFocused) {
-                ::SetKeyboardFocus(::GetWindowFromPort(mPluginPort), mAppletControl, kControlFocusNextPart);
+                if (mAppletControl)
+                    ::SetKeyboardFocus(::GetWindowFromPort(mPluginPort), mAppletControl, kControlFocusNextPart);
                 mIsFocused = true;
             }
+            /* Setting mUpdatesSequence to zero here and for a "lose focus"
+             * event helps deal with an obnoxious new spurious update that
+             * happens on the trunk and 1.8/1.8.1 branches, but not on the
+             * 1.8.0 branch:  When the focus is in an applet text input
+             * field and you click on the Google search widget (in the
+             * upper right), the entire applet gets blanked.
+             */
+            mUpdatesSequence = 0;
             break;
         
         case nsPluginEventType_LoseFocusEvent:
-            ::SetKeyboardFocus(::GetWindowFromPort(mPluginPort), mAppletControl, kControlFocusNoPart);
-            mIsFocused = true;
+            if (debugUpdates)
+                JEPLogJavaMessage(CFSTR("MRJContext::handleEvent(): nsPluginEventType_LoseFocusEvent"));
+            if (mAppletControl)
+                ::SetKeyboardFocus(::GetWindowFromPort(mPluginPort), mAppletControl, kControlFocusNoPart);
+            mIsFocused = false;
+            mUpdatesSequence = 0;
             break;
 
         case nsPluginEventType_AdjustCursorEvent:
             ::IdleControls(::GetWindowFromPort(mPluginPort));
             break;
         
         case nsPluginEventType_MenuCommandEvent:
             // frame->menuSelected(event->message, event->modifiers);
             break;
         
@@ -1570,79 +1863,196 @@
     // install mouseDown/mouseUp handlers for this window, so we can disable
     // async updates during mouse tracking.
     return noErr;
 }
 
 OSStatus MRJContext::removeEventHandlers(WindowRef window)
 {
     return noErr;
 }
 
+static void setWindowBreak()
+{
+	return;
+}
+
 void MRJContext::setWindow(nsPluginWindow* pluginWindow)
 {
+    if (isDestroying())
+        return;
+    if (debugUpdates) {
+		setWindowBreak();
+        cfref<CFStringRef> info = CFStringCreateWithFormat(NULL, NULL,
+            CFSTR("MRJContext::setWindow(): pluginWindow 0x%.8X, pluginWindow->window->port 0x%.8X, mIsVisible %s"),
+            (unsigned) pluginWindow,
+            (unsigned) (pluginWindow && pluginWindow->window) ? pluginWindow->window->port : NULL,
+            mIsVisible ? "true" : "false");
+        JEPLogJavaMessage(info);
+    }
     if (pluginWindow != NULL) {
         mPluginWindow = pluginWindow;
 
         // establish the GrafPort the plugin will draw in.
         mPluginPort = pluginWindow->window->port;
 
-        if (! appletLoaded())
+        if (!appletLoaded() && !appletLoading()) {
+            setAppletLoading(true);
             loadApplet();
+            /* Sometimes loading the applet can take so long that
+             * mPluginWindow has become invalid.  The time we spend
+             * here may also block subsequent calls to setWindow with
+             * pluginWindow == NULL.
+             */
+            mPluginWindow = NULL;
+            mPluginPort = getEmptyPort();
+        }
     } else {
         // tell MRJ the window has gone away.
         mPluginWindow = NULL;
         
         // use a single, 0x0, empty port for all future drawing.
         mPluginPort = getEmptyPort();
     }
-    synchronizeClipping();
+    /* We used to always call synchronizeClipping() here, but it's far better
+     * to call it only if checkUpdateNeeded() thinks it's necessary.  This
+     * helps resolve Camino's "spurious updates" problem (if an applet accepts
+     * keyboard input, its display gets updated every time you press a key).
+     * The reason for the problem is that Camino calls setWindow() and creates
+     * an update event (which causes drawApplet() to be called from
+     * handleEvent()) every single time a key is pressed in the applet!
+     */
+    if (checkUpdateNeeded())
+        synchronizeClipping();
 }
 
 static Boolean equalRect(const nsPluginRect* r1, const nsPluginRect* r2)
 {
     SInt32* r1p = (SInt32*)r1;
     SInt32* r2p = (SInt32*)r2;
     return (r1p[0] == r2p[0] && r1p[1] == r2p[1]);
 }
 
 Boolean MRJContext::inspectWindow()
 {
-    // don't bother looking, if the applet doesn't exist yet.
-    if (!appletLoaded())
-        return false;
+	Boolean recomputeClipping = checkPaintNeeded();
+	if (recomputeClipping)
+		synchronizeClipping();
+	return recomputeClipping;
+}
 
-    Boolean recomputeClipping = false;
-    
+Boolean MRJContext::checkUpdateNeeded()
+{
+    if (isDestroying())
+        return false;
     if (mPluginWindow != NULL) {
-        // Check for origin or clipping changes.
-        nsPluginPort* npPort = mPluginWindow->window;
-        if (mCachedOrigin.x != npPort->portx || mCachedOrigin.y != npPort->porty || !equalRect(&mCachedClipRect, &mPluginWindow->clipRect)) {
-            // transfer over values to the window cache.
-            recomputeClipping = true;
+		if (!mIsVisible) {
+			mUpdatesSequence = 0;
+			return true;
+		} else {
+			return checkPaintNeeded();
+		}
+	} else if (mIsVisible) {
+		mUpdatesSequence = 0;
+		return true;
+	}
+	return false;
+}
+
+Boolean MRJContext::checkPaintNeeded()
+{
+	if (!mPluginWindow || !mIsVisible || isDestroying())
+		return false;
+
+	Boolean paintNeeded = false;
+
+	// See if our parent window has changed size
+	Rect windowRect;
+	WindowRef window = GetWindowFromPort(mPluginPort);
+	if (!window)
+		return false;
+	GetWindowBounds(window, kWindowContentRgn, &windowRect);
+	windowRect.bottom -= windowRect.top;
+	windowRect.right -= windowRect.left;
+	windowRect.top = windowRect.left = 0;
+	if ((windowRect.right != mCachedWindowRect.right) ||
+		(windowRect.bottom != mCachedWindowRect.bottom))
+	{
+		mUpdatesSequence = 0;
+		paintNeeded = true;
+	}
+	// Check for origin or clipping changes
+	if (!paintNeeded) {
+		nsPluginPort* npPort = mPluginWindow->window;
+		if (mCachedOrigin.x != npPort->portx || mCachedOrigin.y != npPort->porty ||
+			!equalRect(&mCachedClipRect, &mPluginWindow->clipRect))
+		{
+			mUpdatesSequence = 0;
+			paintNeeded = true;
+		}
+	}
+
+	if (!paintNeeded) {
+		if (++mUpdatesSequence == 0)
+			mUpdatesSequence = UPDATES_SEQUENCE_MAX + 1;
+	}
+	return paintNeeded;
+}
+
+void MRJContext::clearAttributeCaches()
+{
+    mCachedOrigin.x = mCachedOrigin.y = -1;
+    ::SetRect((Rect*)&mCachedClipRect, 0, 0, 0, 0);
+    ::SetRect(&mCachedWindowRect, 0, 0, 0, 0);
+}
+
+void MRJContext::startDestroying()
+{
+    mDestroying = true;
+#if TARGET_CARBON
+    if (mSession) {
+        JNIEnv* env = mSession->getCurrentEnv();
+        if (mAppletObject != NULL) {
+            env->DeleteGlobalRef(mAppletObject);
+            mAppletObject = NULL;
         }
     }
-    
-    if (recomputeClipping)
-        synchronizeClipping();
-    
-    return recomputeClipping;
+    if (mJEPHandle != NULL) {
+        JEPRegisterStatusCallback(mJEPHandle, NULL, NULL);
+        JEPRegisterShowDocumentCallback(mJEPHandle, NULL, NULL);
+        JEPSetJavaAppletState(mJEPHandle, kAppletDestroyJEP);
+        mJEPHandle = NULL;
+    }
+#endif
+}
+
+Boolean MRJContext::isDestroying()
+{
+    if (mDestroying)
+        return true;
+    if (!MRJPluginInstance::isValidInstance(mPluginInstance))
+        return true;
+    return false;
 }
 
 /**
  * This routine ensures that the browser and MRJ agree on what the current clipping
  * should be. If the browser has assigned us a window to draw in (see setWindow()
  * above), then we use that window's clipRect to set up clipping, which is cached
  * in mPluginClipping, as a region. Otherwise, mPluginClipping is set to an empty
  * region.
  */
 void MRJContext::synchronizeClipping()
 {
+    if (isDestroying())
+        return;
+    if (debugUpdates)
+        JEPLogJavaMessage(CFSTR("MRJContext::synchronizeClipping(): Calling"));
     // this is called on update events to make sure the clipping region is in sync with the browser's.
     if (mPluginWindow != NULL) {
         // plugin clipping is intersection of clipRgn and the clipRect.
         nsPluginRect clipRect = mPluginWindow->clipRect;
         nsPluginPort* pluginPort = mPluginWindow->window;
         clipRect.left += pluginPort->portx, clipRect.right += pluginPort->portx;
         clipRect.top += pluginPort->porty, clipRect.bottom += pluginPort->porty;
         ::SetRectRgn(mPluginClipping, clipRect.left, clipRect.top, clipRect.right, clipRect.bottom);
     } else {
         ::SetEmptyRgn(mPluginClipping);
@@ -1707,76 +2117,94 @@
 {
     ::InvertRgn(rgn);
     UInt32 ticks = ::TickCount();
     while (::TickCount() - ticks < 10) ;
     ::InvertRgn(rgn);
 }
 
 void MRJContext::synchronizeVisibility()
 {
     OSStatus status;
-    
-    if (mAppletControl) {
+
+    if (isDestroying())
+        return;
+
+    if (mJEPHandle || mAppletControl) {
         JNIEnv* env = mSession->getCurrentEnv();
         if (mPluginWindow != NULL) {
             nsPluginRect oldClipRect = mCachedClipRect;
             nsPluginPort* pluginPort = mPluginWindow->window;
             mCachedOrigin.x = pluginPort->portx;
             mCachedOrigin.y = pluginPort->porty;
             mCachedClipRect = mPluginWindow->clipRect;
+            GetWindowBounds(GetWindowFromPort(mPluginPort), kWindowContentRgn,
+                &mCachedWindowRect);
+            mCachedWindowRect.bottom -= mCachedWindowRect.top;
+            mCachedWindowRect.right -= mCachedWindowRect.left;
+            mCachedWindowRect.top = mCachedWindowRect.left = 0;
 
             int posX = -pluginPort->portx;
             int posY = -pluginPort->porty;
             int clipX = mCachedClipRect.left;
             int clipY = mCachedClipRect.top;
             int clipWidth = (mCachedClipRect.right - mCachedClipRect.left);
             int clipHeight = (mCachedClipRect.bottom - mCachedClipRect.top);
 
-#if TARGET_RT_MAC_MACHO
-            // XXX hack a little bit to make it work...
-            const SInt32 kTitleBarHeight = 22;
-            posY -= kTitleBarHeight;
-            clipY -= kTitleBarHeight;
-#endif
-
-            status = ::SizeJavaControl(env, mAppletControl, mPluginWindow->width, mPluginWindow->height);
-            status = ::MoveAndClipJavaControl(env, mAppletControl, posX, posY,
-                                              clipX, clipY, clipWidth, clipHeight);
+            if (mJEPHandle) {
+                JEPSuspendJavaAppletUpdates(mJEPHandle);
+                status = JEPSizeJavaApplet(mJEPHandle, mPluginWindow->width, mPluginWindow->height);
+                status = JEPMoveAndClipJavaApplet(mJEPHandle, posX, posY, clipX, clipY, clipWidth, clipHeight);
+                JEPResumeJavaAppletUpdates(mJEPHandle);
+            } else {
+                status = ::SizeJavaControl(env, mAppletControl, mPluginWindow->width, mPluginWindow->height);
+                status = ::MoveAndClipJavaControl(env, mAppletControl, posX, posY,
+                                                  clipX, clipY, clipWidth, clipHeight);
+            }
 
             if (!mIsVisible) {
-                status = ::ShowHideJavaControl(env, mAppletControl, true);
+                if (mJEPHandle) {
+                    status = JEPShowHideJavaApplet(mJEPHandle, true);
+                } else {
+                    status = ::ShowHideJavaControl(env, mAppletControl, true);
+                }
                 mIsVisible = (status == noErr);
             } else {
-                status = ::DrawJavaControl(env, mAppletControl);
+                if (!mJEPHandle) {
+                    status = ::DrawJavaControl(env, mAppletControl);
+                }
             }
 
 #if TARGET_RT_MAC_MACHO && 0
             if (GetCurrentKeyModifiers() & alphaLock) {
                 // raise(SIGINT);
                 printf("@@@ (posX = %d, posY = %d), (clipX = %d, clipY = %d, clipWidth = %d, clipHeight = %d) @@@\n",
                     posX, posY, clipX, clipY, clipWidth, clipHeight);
     
                 Rect clipBounds;
                 clipBounds.left = clipX, clipBounds.top = clipY;
                 clipBounds.right = clipX + clipWidth, clipBounds.bottom = clipY + clipHeight;
                 LocalPort port(mPluginPort);
                 port.Enter();
                     FrameRect(&clipBounds);
                     InvertRect(&clipBounds);
                     QDFlushPortBuffer(mPluginPort, NULL);
                 port.Exit();
             }
 #endif
         } else {
-           status = ::MoveAndClipJavaControl(env, mAppletControl, 0, 0, 0, 0, 0, 0);
-           status = ::ShowHideJavaControl(env, mAppletControl, false);
-           mIsVisible = false;
+            if (mJEPHandle)
+                status = JEPShowHideJavaApplet(mJEPHandle, false);
+            else {
+                status = ::MoveAndClipJavaControl(env, mAppletControl, 0, 0, 0, 0, 0, 0);
+                status = ::ShowHideJavaControl(env, mAppletControl, false);
+            }
+            mIsVisible = false;
         }
     }
 }
 
 void MRJContext::showFrames()
 {
 #if TARGET_CARBON
     // Won't Carbon events handle all of this?
 #else           
     UInt32 frameCount;
diff -U 10 -r -N old/plugin/oji/MRJCarbon/plugin/Source/MRJContext.h new/plugin/oji/MRJCarbon/plugin/Source/MRJContext.h
--- old/plugin/oji/MRJCarbon/plugin/Source/MRJContext.h	2003-06-11 00:11:46.000000000 -0500
+++ new/plugin/oji/MRJCarbon/plugin/Source/MRJContext.h	2006-10-28 22:47:33.000000000 -0500
@@ -76,28 +76,34 @@
 	~MRJContext();
 
 	void processAppletTag();
 	Boolean createContext();
 
 #if !TARGET_CARBON
 	JMAWTContextRef getContextRef();
     JMAppletViewerRef getViewerRef();
 #endif
     
+	Boolean appletLoading();
+	void setAppletLoading(Boolean loading);
 	Boolean appletLoaded();
 	Boolean loadApplet();
 	Boolean isActive();
 	
 	void suspendApplet();
 	void resumeApplet();
 	jobject getApplet();
 
+#if TARGET_CARBON
+	void setApplet(jobject newApplet);
+#endif
+
 	nsIPluginInstance* getInstance();
 	nsIPluginInstancePeer* getPeer();
 	
 	Boolean handleEvent(EventRecord* event);
 	
 	void idle(short modifiers);
 	void drawApplet();
 	void printApplet(nsPluginWindow* printingWindow);
 	
 	void activate(Boolean active);
@@ -105,20 +111,25 @@
 
 	void click(const EventRecord* event, MRJFrame* frame);
 	void keyPress(long message, short modifiers);
 	void keyRelease(long message, short modifiers);
 	
     void scrollingBegins();
     void scrollingEnds();
 
 	void setWindow(nsPluginWindow* pluginWindow);
 	Boolean inspectWindow();
+	Boolean checkUpdateNeeded();
+	Boolean checkPaintNeeded();
+	void clearAttributeCaches();
+	void startDestroying();
+	Boolean isDestroying();
 	
 	MRJFrame* findFrame(WindowRef window);
 	GrafPtr getPort();
 	
 	void showFrames();
 	void hideFrames();
 	void releaseFrames();
 	
 	void setDocumentBase(const char* documentBase);
 	const char* getDocumentBase();
@@ -167,26 +178,31 @@
 	nsIPluginInstancePeer* 	    mPeer;
 #if !TARGET_CARBON
     JMAppletLocatorRef		    mLocator;
 	JMAWTContextRef			    mContext;
 	JMAppletViewerRef		    mViewer;
 	JMFrameRef				    mViewerFrame;
 #endif
     Boolean					    mIsActive;
 	Boolean                     mIsFocused;
 	Boolean                     mIsVisible;
+	unsigned                    mUpdatesSequence;
 	nsPluginPoint               mCachedOrigin;
 	nsPluginRect                mCachedClipRect;
+	Rect						mCachedWindowRect;
 	RgnHandle				    mPluginClipping;
 	nsPluginWindow*			    mPluginWindow;
 	CGrafPtr				    mPluginPort;
 	char*					    mDocumentBase;
 	char*					    mAppletHTML;
 	MRJPage*				    mPage;
 	MRJSecurityContext*         mSecurityContext;
+	Boolean						mAppletLoading;
+	Boolean						mDestroying;
 #if TARGET_CARBON
     jobject                     mAppletFrame;
     jobject                     mAppletObject;
     ControlRef                  mAppletControl;
     UInt32                      mScrollCounter;
+    void*                       mJEPHandle;
 #endif
 };
diff -U 10 -r -N old/plugin/oji/MRJCarbon/plugin/Source/MRJMonitor.cpp new/plugin/oji/MRJCarbon/plugin/Source/MRJMonitor.cpp
--- old/plugin/oji/MRJCarbon/plugin/Source/MRJMonitor.cpp	2003-06-11 01:11:48.000000000 -0500
+++ new/plugin/oji/MRJCarbon/plugin/Source/MRJMonitor.cpp	2006-03-04 22:23:14.000000000 -0600
@@ -42,21 +42,25 @@
 	by Patrick C. Beard.
  */
 
 #include "MRJMonitor.h"
 #include "MRJSession.h"
 
 MRJMonitor::MRJMonitor(MRJSession* session, jobject monitor)
 	:	mSession(session), mMonitor(NULL), mWaitMethod(NULL), mNotifyMethod(NULL), mNotifyAllMethod(NULL)
 {
 	JNIEnv* env = mSession->getCurrentEnv();
-	jclass javaLangObject = env->FindClass("java/lang/Object");
+	// Testing env != NULL from patch by Mark Mentovai at
+	// https://bugzilla.mozilla.org/show_bug.cgi?id=315163.
+	jclass javaLangObject = NULL;
+	if (env)
+		javaLangObject = env->FindClass("java/lang/Object");
 	if (javaLangObject != NULL) {
 		// look up method IDs.
 		mWaitMethod = env->GetMethodID(javaLangObject, "wait", "()V");
 		mTimedWaitMethod = env->GetMethodID(javaLangObject, "wait", "(J)V");
 		mNotifyMethod = env->GetMethodID(javaLangObject, "notify", "()V");
 		mNotifyAllMethod = env->GetMethodID(javaLangObject, "notifyAll", "()V");
 		
 		Boolean allocateMonitor = (monitor == NULL);
 		if (allocateMonitor)
 			monitor = env->AllocObject(javaLangObject);
diff -U 10 -r -N old/plugin/oji/MRJCarbon/plugin/Source/MRJPlugin.cpp new/plugin/oji/MRJCarbon/plugin/Source/MRJPlugin.cpp
--- old/plugin/oji/MRJCarbon/plugin/Source/MRJPlugin.cpp	2003-06-11 00:11:50.000000000 -0500
+++ new/plugin/oji/MRJCarbon/plugin/Source/MRJPlugin.cpp	2007-02-22 11:41:47.000000000 -0600
@@ -41,48 +41,82 @@
     
     by Patrick C. Beard.
  */
 
 #include "MRJPlugin.h"
 #include "MRJSession.h"
 #include "MRJContext.h"
 #include "MRJConsole.h"
 #include "EmbeddedFramePluginInstance.h"
 
+#import <mach-o/dyld.h>
+#import "JavaEmbeddingPlugin.h"
+extern "C" Boolean JEPCheckBundle();
+extern Boolean CheckJavaEmbeddingFramework();
+extern Boolean debugPrinting;
+extern nsPluginThreadPtr theJavaScriptThread;
+extern OSStatus spec2path(const FSSpec& spec, char* path, UInt32 maxPathSize);
+
 #if !TARGET_CARBON
 #include "MRJFrame.h"
 #endif
 
 #include "nsIServiceManager.h"
 #include "nsIServiceManagerObsolete.h"
 #include "nsObsoleteModuleLoading.h"
 
 #include "nsIMemory.h"
 #include "nsIJVMManager.h"
 #include "nsIJVMPluginTagInfo.h"
 #include "nsIPluginManager2.h"
 #include "nsIPluginInstancePeer.h"
+#include "nsIPluginInstancePeer2.h"
 #include "nsIWindowlessPlugInstPeer.h"
 #include "LiveConnectNativeMethods.h"
 #include "CSecureEnv.h"
 
 #include <Resources.h>
 #include <LaunchServices.h>
 #include <string>
 #include <CFBundle.h>
 
 nsIPluginManager* thePluginManager = NULL;
 nsIPluginManager2* thePluginManager2 = NULL;
 nsIMemory* theMemoryAllocator = NULL;
 
 FSSpec thePluginSpec;
 short thePluginRefnum = -1;
+MRJPlugin *theJVMPlugin = NULL;
+
+// We assume (in LiveConnectNativeMethods.cpp) that there's exactly one
+// JavaScript thread, that that it's the main thread.  When/if this becomes
+// invalid, we'll need to change things.
+static nsPluginThreadPtr getJavaScriptThread(MRJPluginInstance *pluginInstance)
+{
+    nsPluginThreadPtr threadID = 0;
+    if (MRJPluginInstance::isValidInstance(pluginInstance)) {
+        nsIPluginInstancePeer *peer;
+        if (pluginInstance->GetPeer(&peer) == NS_OK) {
+            nsIPluginInstancePeer2 *peer2 = NULL;
+            if (peer->QueryInterface(NS_GET_IID(nsIPluginInstancePeer2), (void**) &peer2) == NS_OK) {
+                if (peer2->GetJSThread((PRUint32 *) &threadID) != NS_OK)
+                    threadID = 0;
+                NS_RELEASE(peer2);
+            }
+            NS_RELEASE(peer);
+        }
+    }
+    return threadID;
+}
+
+// Deal with breakage caused by the fix for bmo bug 326273.  See nsjvmFixes.h.
+nsID nsIJVMThreadManagerIID = NS_IJVMTHREADMANAGER_IID;
 
 // Common interface IDs.
 
 static NS_DEFINE_IID(kPluginCID, NS_PLUGIN_CID);
 static NS_DEFINE_IID(kPluginManagerCID, NS_PLUGINMANAGER_CID);
 static NS_DEFINE_IID(kJVMManagerCID, NS_JVMMANAGER_CID);
 
 static NS_DEFINE_IID(kIWindowlessPluginInstancePeerIID, NS_IWINDOWLESSPLUGININSTANCEPEER_IID);
 
 /**
@@ -103,58 +137,149 @@
 
 nsresult MRJPlugin::GetService(const char* aContractID, const nsIID& aIID, void* *aService)
 {
     if (theServiceManager)
         return theServiceManager->GetServiceByContractID(aContractID, aIID, aService);
     if (theServiceManagerObsolete)
         return theServiceManagerObsolete->GetService(aContractID, aIID, (nsISupports **)aService);
     return NS_ERROR_FAILURE;
 }
 
+struct QITableEntry;
+
+typedef nsresult (*TABLEDRIVENQI) (void *, const QITableEntry*, REFNSIID, void **);
+
+// As of the fix for bug 313309, the Mozilla.org trunk now has "table-driven
+// QI", which means that all plugins/extensions that use the NS_IMPL_ISUPPORTS
+// macros now need to (statically) link in or implement a NS_TableDrivenQI()
+// method.  In principle we could link to the "standalone xpcomglue library".
+// But this would be a royal pain (since we'd need a universal-binary version
+// of libxpcomglue.a).  So (to avoid having to link it in) I'm going to
+// implement NS_TableDrivenQI() right here.  I _think_ the OS's "two-level
+// namespace" magic will ensure that the right copy of this symbol is used
+// (i.e. that our implementation will never be called).  But in case our
+// NS_TableDrivenQI() does get called, I've made it locate the "right"
+// NS_TableDrivenQI method and call through to that.
+nsresult NS_TableDrivenQI(void* aThis, const QITableEntry* entries, REFNSIID aIID, void **aInstancePtr)
+{
+	nsresult retval = NS_ERROR_FAILURE;
+	static TABLEDRIVENQI NS_TableDrivenQI_Ptr = NULL;
+	if (!NS_TableDrivenQI_Ptr) {
+		unsigned long i, count;
+		NSSymbol symbol = nil;
+		const struct mach_header *image = nil;
+		char our_name[4096];
+		const char *image_name = nil;
+		spec2path(thePluginSpec, our_name, sizeof(our_name));
+		count = _dyld_image_count();
+		// We assume that the "right" NS_TableDrivenQI symbol will be the
+		// first one we find that isn't ours (i.e. that other plugins and
+		// extensions that implement or statically link in this symbol will
+		// have been loaded later than the module that contains the "right"
+		// one).
+		for (i = 1; i <= count; ++i) {
+			image = (const struct mach_header *) _dyld_get_image_header(i - 1);
+			image_name = _dyld_get_image_name(i - 1);
+			if (strcmp(our_name, image_name) == 0)
+				continue;
+			symbol = NSLookupSymbolInImage(image,
+				"__Z16NS_TableDrivenQIPvPK12QITableEntryRK4nsIDPS_",
+				NSLOOKUPSYMBOLINIMAGE_OPTION_RETURN_ON_ERROR);
+			if (symbol)
+				NS_TableDrivenQI_Ptr = (TABLEDRIVENQI) NSAddressOfSymbol(symbol);
+			if (NS_TableDrivenQI_Ptr)
+				break;
+		}
+	}
+	if (NS_TableDrivenQI_Ptr)
+		retval = NS_TableDrivenQI_Ptr(aThis, entries, aIID, aInstancePtr);
+    return retval;
+}
+
 #pragma export on
 
-static long getSystemVersion()
+long getSystemVersion()
 {
-    long version = 0;
-    Gestalt(gestaltSystemVersion, &version);
+    static long version = 0;
+    if (!version) {
+        Gestalt(gestaltSystemVersion, &version);
+        version &= 0xFFFF;
+    }
     return version;
 }
 
 extern "C"
 nsresult NSGetFactory(nsISupports* serviceManager, const nsCID &aClass, const char *aClassName, const char *aContractID, nsIFactory **aFactory)
 {
     nsresult result = NS_OK;
 
     // First off, fail if not running on AT LEAST Mac OS X, v10.1.
     if (getSystemVersion() < 0x00001010)
         return NS_ERROR_FAILURE;
 
+	// Also fail if neither the Java Embedding Plugin nor the JavaEmbedding
+	// framework are present -- as happens if someone tries to use
+	// MRJPlugin.plugin without JavaEmbeddingPlugin.bundle on Mac OS X for
+	// Intel.
+	if (!JEPCheckBundle() && !CheckJavaEmbeddingFramework())
+		return NS_ERROR_FAILURE;
+
     if (theServiceManager == NULL && theServiceManagerObsolete == NULL) {
         if (NS_FAILED(serviceManager->QueryInterface(NS_GET_IID(nsIServiceManager), (void**)&theServiceManager)))
             if (NS_FAILED(serviceManager->QueryInterface(NS_GET_IID(nsIServiceManagerObsolete), (void**)&theServiceManagerObsolete)))
                 return NS_ERROR_FAILURE;
 
         // Our global operator new wants to use nsIMalloc to do all of its allocation.
         // This should be available from the Service Manager.
         if (NS_FAILED(MRJPlugin::GetService("@mozilla.org/xpcom/memory-service;1", NS_GET_IID(nsIMemory), (void **)&theMemoryAllocator)))
             return NS_ERROR_FAILURE;
     }
 
     if (aClass.Equals(kPluginCID)) {
         MRJPlugin* pluginFactory = new MRJPlugin();
         pluginFactory->AddRef();
         *aFactory = pluginFactory;
         return NS_OK;
     }
     return NS_NOINTERFACE;
 }
 
+#include "nsICookieStorage.h"
+
+extern "C"
+unsigned MRJGetCookie(const char *inCookieURL, void *inOutCookieBuffer, unsigned *inOutCookieSize)
+{
+	nsICookieStorage *cookieMonster = NULL;
+	nsresult rv = MRJPlugin::GetService(kPluginManagerCID, NS_GET_IID(nsICookieStorage), (void **) &cookieMonster);
+	if (NS_SUCCEEDED(rv) && (cookieMonster != NULL)) {
+		rv = cookieMonster->GetCookie(inCookieURL, inOutCookieBuffer, *inOutCookieSize);
+		cookieMonster->Release();
+	}
+	if (NS_SUCCEEDED(rv))
+		rv = 0;
+	return rv;
+}
+
+extern "C"
+unsigned MRJSetCookie(const char *inCookieURL, const void *inCookieBuffer, unsigned inCookieSize)
+{
+	nsICookieStorage *cookieMonster = NULL;
+	nsresult rv = MRJPlugin::GetService(kPluginManagerCID, NS_GET_IID(nsICookieStorage), (void **) &cookieMonster);
+	if (NS_SUCCEEDED(rv) && (cookieMonster != NULL)) {
+		rv = cookieMonster->SetCookie(inCookieURL, inCookieBuffer, inCookieSize);
+		cookieMonster->Release();
+	}
+	if (NS_SUCCEEDED(rv))
+		rv = 0;
+	return rv;
+}
+
 #pragma export off
 
 #if TARGET_RT_MAC_CFM
 
 extern "C" {
 
 pascal OSErr __initialize(const CFragInitBlock *initBlock);
 pascal void __terminate(void);
 
 #if defined(MRJPLUGIN_GC)
@@ -205,102 +330,133 @@
 }
 
 #endif /* TARGET_RT_MAC_CFM */
 
 #if TARGET_RT_MAC_MACHO
 
 extern "C" {
 CF_EXPORT Boolean CFURLGetFSRef(CFURLRef url, FSRef *fsRef);
 }
 
-static CFBundleRef getPluginBundle()
+/* getPluginBundle()'s now being called from getJEPBundle() in
+ * JavaEmbeddingPlugin.cpp.
+ */
+CFBundleRef getPluginBundle()
 {
     printf("### MRJPlugin:  getPluginBundle() here. ###\n");
-    CFBundleRef bundle = CFBundleGetBundleWithIdentifier(CFSTR("com.netscape.MRJPlugin"));
+    CFBundleRef bundle = NULL;
+    CFArrayRef allBundles = CFBundleGetAllBundles();
+    int count = CFArrayGetCount(allBundles);
+    for (int i = 1; i <= count; ++i) {
+        CFBundleRef aBundle = (CFBundleRef) CFArrayGetValueAtIndex(allBundles, i-1);
+        CFStringRef anIdentifier = CFBundleGetIdentifier(aBundle);
+        if (!anIdentifier)
+            continue;
+        if (CFStringCompare(anIdentifier, CFSTR("com.netscape.MRJPlugin"), 0) == kCFCompareEqualTo) {
+            bundle = aBundle;
+            break;
+        }
+    }
     if (bundle) {
         printf("### MRJPlugin:  CFBundleGetBundleWithIdentifier() succeeded. ###\n");
         // initialize thePluginSpec for later use. open our resource fork as well?
         CFURLRef url = CFBundleCopyExecutableURL(bundle);
         if (url) {
             FSRef ref;
             if (CFURLGetFSRef(url, &ref)) {
                 printf("### MRJPlugin:  CFURLGetFSRef() succeeded. ###\n");
                 FSGetCatalogInfo(&ref, kFSCatInfoNone, NULL, NULL, &thePluginSpec, NULL);
 
                 // Open plugin's resource fork for read-only access. is this really necessary?
                 thePluginRefnum = ::CFBundleOpenBundleResourceMap(bundle);
             }
             CFRelease(url);
         }
     }
     return bundle;
 }
 
-CFBundleRef thePluginBundle = getPluginBundle();
+CFBundleRef thePluginBundle;
 
 #endif /* TARGET_RT_MAC_MACHO */
 
 //
 // The MEAT of the plugin.
 //
 
 #pragma mark *** MRJPlugin ***
 
-const InterfaceInfo MRJPlugin::sInterfaces[] = {
-    { NS_IPLUGIN_IID, INTERFACE_OFFSET(MRJPlugin, nsIPlugin) },
-    { NS_IJVMPLUGIN_IID, INTERFACE_OFFSET(MRJPlugin, nsIJVMPlugin) },
-#if USE_SYSTEM_CONSOLE
-    { NS_IJVMCONSOLE_IID, INTERFACE_OFFSET(MRJPlugin, nsIJVMConsole) },
-#endif
-    { NS_IRUNNABLE_IID, INTERFACE_OFFSET(MRJPlugin, nsIRunnable) },
-};
-const UInt32 MRJPlugin::kInterfaceCount = sizeof(sInterfaces) / sizeof(InterfaceInfo);
-
 MRJPlugin::MRJPlugin()
-    :   SupportsMixin(this, sInterfaces, kInterfaceCount),
-        mManager(NULL), mThreadManager(NULL), mSession(NULL), mConsole(NULL), mPluginThreadID(NULL), mIsEnabled(false)
+    :   mManager(NULL), mThreadManager(NULL), mSession(NULL), mConsole(NULL), mPluginThreadID(NULL), mIsEnabled(false)
 {
 }
 
 MRJPlugin::~MRJPlugin()
 {
     // Release the console.
     NS_IF_RELEASE(mConsole);
 
     // tear down the MRJ session, if it exists.
     if (mSession != NULL) {
         delete mSession;
         mSession = NULL;
     }
 
     // Release the managers.
     NS_IF_RELEASE(mManager);
     NS_IF_RELEASE(mThreadManager);
 }
 
-#if !USE_SYSTEM_CONSOLE
-/**
+NS_IMPL_ADDREF(MRJPlugin)
+NS_IMPL_RELEASE(MRJPlugin)
+
+NS_METHOD MRJPlugin::QueryInterface(const nsIID& aIID, void** aInstancePtr)
+{
+    if (aInstancePtr == NULL) {
+        return NS_ERROR_NULL_POINTER;
+    }
+    *aInstancePtr = NULL;
+    if (aIID.Equals(NS_GET_IID(nsIPlugin))) {
+        *aInstancePtr = (void *) (nsIPlugin *) this;
+        AddRef();
+        return NS_OK;
+    }
+    if (aIID.Equals(NS_GET_IID(nsIJVMPlugin))) {
+        *aInstancePtr = (void *) (nsIJVMPlugin *) this;
+        AddRef();
+        return NS_OK;
+    }
+    if (aIID.Equals(NS_GET_IID(nsIRunnable))) {
+        *aInstancePtr = (void *) (nsIRunnable *) this;
+        AddRef();
+        return NS_OK;
+    }
+/*
  * MRJPlugin aggregates MRJConsole, so that it can be QI'd to be an nsIJVMConsole.
- * To save code size, we use the SupportsMixin class instead of the macros in 
- * nsAgg.h. SupportsMixin::queryInterface, addRef, and release are all local
- * operations, regardless of aggregation. The capitalized versions take aggregation
- * into account.
  */
-NS_METHOD MRJPlugin::QueryInterface(const nsIID& aIID, void** instancePtr)
-{
-    nsresult result = queryInterface(aIID, instancePtr);
-    if (result == NS_NOINTERFACE) {
-        result = mConsole->queryInterface(aIID, instancePtr);
+#if USE_SYSTEM_CONSOLE
+    if (aIID.Equals(NS_GET_IID(nsIJVMConsole))) {
+        *aInstancePtr = (void *) (nsIJVMConsole *) this;
+        AddRef();
+        return NS_OK;
     }
-    return result;
-}
 #endif
+    if (aIID.Equals(NS_GET_IID(nsISupports))) {
+        *aInstancePtr = (void *) this;
+        AddRef();
+        return NS_OK;
+    }
+#if USE_SYSTEM_CONSOLE
+    return mConsole->QueryInterface(aIID, aInstancePtr);
+#endif
+    return NS_NOINTERFACE;
+}
 
 NS_METHOD MRJPlugin::CreateInstance(nsISupports *aOuter, const nsIID& aIID, void **aResult)
 {
     nsresult result = StartupJVM();
     if (result == NS_OK) {
         MRJPluginInstance* instance = new MRJPluginInstance(this);
         if (instance == nsnull)
             return NS_ERROR_OUT_OF_MEMORY;
         result = instance->QueryInterface(aIID, aResult);
         if (result != NS_OK)
@@ -346,21 +502,21 @@
         if (thePluginManager->QueryInterface(NS_GET_IID(nsIPluginManager2), (void**)&thePluginManager2) != NS_OK)
             thePluginManager2 = NULL;
     }
 
     // try to get a JVM manager. we have to be able to run without one.
     if (MRJPlugin::GetService(kJVMManagerCID, NS_GET_IID(nsIJVMManager), (void**)&mManager) != NS_OK)
         mManager = NULL;
     
     // try to get a Thread manager.
     if (mManager != NULL) {
-        if (mManager->QueryInterface(NS_GET_IID(nsIThreadManager), (void**)&mThreadManager) != NS_OK)
+        if (mManager->QueryInterface(nsIJVMThreadManagerIID, (void**)&mThreadManager) != NS_OK)
             mThreadManager = NULL;
 
         if (mThreadManager != NULL)
             mThreadManager->GetCurrentThread(&mPluginThreadID);
     }
 
 #if !USE_SYSTEM_CONSOLE
     // create a console, only if there's user interface for it.
     if (thePluginManager2 != NULL) {
         mConsole = new MRJConsole(this);
@@ -402,64 +558,63 @@
 {
     StartupJVM();
     return mSession;
 }
 
 nsIJVMManager* MRJPlugin::getManager()
 {
     return mManager;
 }
 
-nsIThreadManager* MRJPlugin::getThreadManager()
+nsIJVMThreadManager* MRJPlugin::getThreadManager()
 {
     return mThreadManager;
 }
 
-static char* getJavaConsolePath(char* path, UInt32 maxPathSize)
+char* getJavaConsolePath(char* path, UInt32 maxPathSize)
 {
     path[0] = '\0';
     FSRef ref;
     OSErr err = FSFindFolder(kUserDomain, kDomainLibraryFolderType, true, &ref);
     if (err == noErr) {
         err = FSRefMakePath(&ref, (UInt8*) path, maxPathSize);
         const char kJavaConsoleLog[] = { "/Logs/Java Console.log" };
         int len = strlen(path);
         if (err == noErr && (len + sizeof(kJavaConsoleLog)) <= maxPathSize) {
             strcat(path + len, kJavaConsoleLog);
         }
     }
     return path;
 }
 
 nsresult MRJPlugin::StartupJVM()
 {
     if (mSession == NULL) {
         // start a session with MRJ.
-        mSession = new MRJSession();
+        mSession = new MRJSession(this);
 
         // Add "MRJPlugin.jar" to the class path.
         FSSpec jarFileSpec = { thePluginSpec.vRefNum, thePluginSpec.parID, "\pMRJPlugin.jar" };
         mSession->addToClassPath(jarFileSpec);
-        
+
         // Compute location of ~/Library/Logs/JavaConsole.log
         char consolePath[512];
         mSession->open(getJavaConsolePath(consolePath, sizeof(consolePath)));
 
         if (mSession->getStatus() != noErr) {
             // how can we signal an error?
             delete mSession;
             mSession = NULL;
+            ShutdownLiveConnectSupport();
             return NS_ERROR_FAILURE;
         }
 
-        InitLiveConnectSupport(this);
-
 #if 0
         // start our idle thread.
         if (mThreadManager != NULL) {
             PRUint32 threadID;
             mThreadManager->CreateThread(&threadID, this);
         }
 #endif
 
         mIsEnabled = true;
     }
@@ -571,49 +726,53 @@
         mSession->idle();
         mThreadManager->Sleep();
     }
     return NS_OK;
 }
 
 MRJPluginInstance* MRJPlugin::getPluginInstance(jobject applet)
 {
     JNIEnv* env = mSession->getCurrentEnv();
     MRJPluginInstance* instance = MRJPluginInstance::getInstances();
-    while (instance != NULL) {
+    while (instance && !instance->isDestroying()) {
         jobject object = NULL;
-        if (instance->GetJavaObject(&object) == NS_OK && env->IsSameObject(applet, object)) {
+        instance->GetJavaObject(&object);
+        if (object && env->IsSameObject(applet, object)) {
             instance->AddRef();
             return instance;
         }
         instance = instance->getNextInstance();
     }
     return NULL;
 }
 
 MRJPluginInstance* MRJPlugin::getPluginInstance(JNIEnv* jenv)
 {
 #if !TARGET_CARBON
     // Apple will provide an API that maps a JNIEnv to an JMAWTContextRef. We can map this to the MRJContext/Applet/Instance.
     MRJPluginInstance* instance = MRJPluginInstance::getInstances();
     if (&::JMJNIToAWTContext != NULL) {
         JMAWTContextRef contextRef = ::JMJNIToAWTContext(mSession->getSessionRef(), jenv);
         if (contextRef != NULL) {
-            while (instance != NULL) {
-                if (instance->getContext()->getContextRef() == contextRef) {
+            while (instance && !instance->isDestroying()) {
+                MRJContext context = instance->getContext();
+                if (!context)
+                    continue;
+                if (context->getContextRef() == contextRef) {
                     instance->AddRef();
                     return instance;
                 }
                 instance = instance->getNextInstance();
             }
         }
     } else {
-        if (instance != NULL) {
+        if (MRJPluginInstance::isValidInstance(instance)) {
             instance->AddRef();
             return instance;
         }
     }
 #endif
     return NULL;
 }
 
 Boolean MRJPlugin::inPluginThread()
 {
@@ -626,45 +785,41 @@
         if (currentThreadID == mPluginThreadID) {
             result = true;
         }
     }
     
     return result;
 }
 
 #pragma mark *** MRJPluginInstance ***
 
-const InterfaceInfo MRJPluginInstance::sInterfaces[] = {
-    { NS_IPLUGININSTANCE_IID, INTERFACE_OFFSET(MRJPluginInstance, nsIPluginInstance) },
-    { NS_IJVMPLUGININSTANCE_IID, INTERFACE_OFFSET(MRJPluginInstance, nsIJVMPluginInstance) },
-    { NS_IEVENTHANDLER_IID, INTERFACE_OFFSET(MRJPluginInstance, nsIEventHandler) },
-};
-const UInt32 MRJPluginInstance::kInterfaceCount = sizeof(sInterfaces) / sizeof(InterfaceInfo);
-
 MRJPluginInstance::MRJPluginInstance(MRJPlugin* plugin)
-    :   SupportsMixin(this, sInterfaces, kInterfaceCount),
-        mPeer(NULL), mWindowlessPeer(NULL),
+    :   mPeer(NULL), mWindowlessPeer(NULL),
         mPlugin(plugin), mSession(plugin->getSession()),
-        mContext(NULL), mApplet(NULL), mPluginWindow(NULL),
+        mContext(NULL), mApplet(NULL), mPluginWindow(NULL), mDestroying(false),
         mNext(NULL)
 {
     // add this instance to the instance list.
     pushInstance();
 
     // Tell the plugin we are retaining a reference.
     mPlugin->AddRef();
 }
 
+/* In recent Mozilla.org browsers (at least) this never gets called.  So it
+ * appears all MRJPluginInstances are leaked, and we need to do all our
+ * tearing down in Destroy().  (Tested with Camino 1.0 and Firefox 1.5.0.2.)
+ */
 MRJPluginInstance::~MRJPluginInstance()
 {
     // Remove this instance from the global list.
-    popInstance();
+    //popInstance();
 
 #if 0
     if (mContext != NULL) {
         delete mContext;
         mContext = NULL;
     }
 
     if (mPlugin != NULL) {
         mPlugin->Release();
         mPlugin = NULL;
@@ -681,20 +836,52 @@
     }
 
     if (mApplet != NULL) {
         JNIEnv* env = mSession->getCurrentEnv();
         env->DeleteGlobalRef(mApplet);
         mApplet = NULL;
     }
 #endif
 }
 
+NS_IMPL_ADDREF(MRJPluginInstance)
+NS_IMPL_RELEASE(MRJPluginInstance)
+
+NS_METHOD MRJPluginInstance::QueryInterface(const nsIID& aIID, void** aInstancePtr)
+{
+    if (aInstancePtr == NULL) {
+        return NS_ERROR_NULL_POINTER;
+    }
+    *aInstancePtr = NULL;
+    if (aIID.Equals(NS_GET_IID(nsIPluginInstance))) {
+        *aInstancePtr = (void *) (nsIPluginInstance *) this;
+        AddRef();
+        return NS_OK;
+    }
+    if (aIID.Equals(NS_GET_IID(nsIJVMPluginInstance))) {
+        *aInstancePtr = (void *) (nsIJVMPluginInstance *) this;
+        AddRef();
+        return NS_OK;
+    }
+    if (aIID.Equals(NS_GET_IID(nsIEventHandler))) {
+        *aInstancePtr = (void *) (nsIEventHandler *) this;
+        AddRef();
+        return NS_OK;
+    }
+    if (aIID.Equals(NS_GET_IID(nsISupports))) {
+        *aInstancePtr = (void *) this;
+        AddRef();
+        return NS_OK;
+    }
+    return NS_NOINTERFACE;
+}
+
 static const char* kGetCodeBaseScriptURL = "javascript:var href = window.location.href; href.substring(0, href.lastIndexOf('/') + 1)";
 static const char* kGetDocumentBaseScriptURL = "javascript:window.location";
 
 static bool hasTagInfo(nsISupports* supports)
 {
     nsIJVMPluginTagInfo* tagInfo;
     if (supports->QueryInterface(NS_GET_IID(nsIJVMPluginTagInfo), (void**)&tagInfo) == NS_OK) {
         NS_RELEASE(tagInfo);
         return true;
     }
@@ -718,28 +905,31 @@
         mContext->processAppletTag();
         mContext->createContext();
     } else {
         // we'll be using JavaScript to create windows.
         // fire up a JavaScript URL to get the current document's location.
         nsIPluginInstance* pluginInstance = this;
         nsIPluginStreamListener* listener = this;
         result = thePluginManager->GetURL(pluginInstance, kGetDocumentBaseScriptURL, NULL, listener);
     }
 
+    if (!theJavaScriptThread)
+        theJavaScriptThread = getJavaScriptThread(this);
+
     return NS_OK;
 }
 
 NS_METHOD MRJPluginInstance::OnDataAvailable(nsIPluginStreamInfo* pluginInfo, nsIInputStream* input, PRUint32 length)
 {
     // hopefully all our data is available.
     char* documentBase = new char[length + 1];
-    if (documentBase != NULL) {
+    if (documentBase && !mDestroying) {
         if (input->Read(documentBase, length, &length) == NS_OK) {
             // We've delayed processing the applet tag, because we
             // don't know the location of the current document yet.
             documentBase[length] = '\0';
             
             // set up the default document location, which can be used to compute relative CODEBASE, etc.
             mContext->setDocumentBase(documentBase);
             delete[] documentBase;
             
             mContext->processAppletTag();
@@ -755,46 +945,54 @@
 
 NS_METHOD MRJPluginInstance::GetPeer(nsIPluginInstancePeer* *result)
 {
     NS_IF_ADDREF(mPeer);
     *result = mPeer;
     return NS_OK;
 }
 
 NS_METHOD MRJPluginInstance::Start()
 {
+    if (mDestroying)
+        return NS_OK;
+
     // Take this moment to show the applet's frames (if any).
     mContext->showFrames();
     
     mContext->resumeApplet();
     
     return NS_OK;
 }
 
 NS_METHOD MRJPluginInstance::Stop()
 {
+    if (mDestroying)
+        return NS_OK;
+
     // Take this moment to hide the applet's frames.
     mContext->hideFrames();
 
     mContext->suspendApplet();
 
     return NS_OK;
 }
 
 NS_METHOD MRJPluginInstance::Destroy()
 {
+    mDestroying = true;
+
+	popInstance();
+
     // Use this opportunity to break any cycles that might exist, and reduce
     // reference counts to their minimum values.
-    if (mContext != NULL) {
-        delete mContext;
-        mContext = NULL;
-    }
+    if (mContext != NULL)
+        mContext->startDestroying();
 
     if (mPlugin != NULL) {
         mPlugin->Release();
         mPlugin = NULL;
     }
 
     if (mWindowlessPeer != NULL) {
         mWindowlessPeer->Release();
         mWindowlessPeer = NULL;
     }
@@ -803,40 +1001,48 @@
         mPeer->Release();
         mPeer = NULL;
     }
 
     if (mApplet != NULL) {
         JNIEnv* env = mSession->getCurrentEnv();
         env->DeleteGlobalRef(mApplet);
         mApplet = NULL;
     }
 
+    if (mContext != NULL) {
+        delete mContext;
+        mContext = NULL;
+    }
+
     return NS_OK;
 }
 
 /** FIXME:  Need an intelligent way to track changes to the NPPluginWindow. */
 
 NS_METHOD MRJPluginInstance::SetWindow(nsPluginWindow* pluginWindow)
 {
+    if (mDestroying)
+        return NS_OK;
+
     mPluginWindow = pluginWindow;
 
     mContext->setWindow(pluginWindow);
 
     return NS_OK;
 }
 
 NS_METHOD MRJPluginInstance::HandleEvent(nsPluginEvent* pluginEvent, PRBool* eventHandled)
 {
     *eventHandled = PR_TRUE;
     Boolean isUpdate;
 
-    if (pluginEvent != NULL) {
+    if (pluginEvent && !mDestroying) {
         EventRecord* event = pluginEvent->event;
 
         // Check for coordinate/clipping changes.
         // Too bad nsPluginEventType_ClippingChangedEvent events aren't implemented.
         isUpdate = (event->what == updateEvt);
         inspectInstance(isUpdate);
     
         if (event->what == nullEvent) {
             // Give Java another quantum of time. We don't need this on Mac OS X.
             mSession->idle(0x00000400); // now SpendTime does this.
@@ -874,20 +1080,24 @@
             }
 #endif
         }
     }
     
     return NS_OK;
 }
 
 NS_METHOD MRJPluginInstance::Print(nsPluginPrint* platformPrint)
 {
+    if (debugPrinting)
+        JEPLogJavaMessage(CFSTR("MRJPluginInstance::Print(): Calling"));
+    if (mDestroying)
+        return NS_ERROR_FAILURE;
     if (platformPrint->mode == nsPluginMode_Embedded) {
         mContext->printApplet(&platformPrint->print.embedPrint.window);
         return NS_OK;
     }
     return NS_ERROR_NOT_IMPLEMENTED;
 }
 
 NS_METHOD MRJPluginInstance::GetValue(nsPluginInstanceVariable variable, void *value)
 {
     switch (variable) {
@@ -899,27 +1109,33 @@
         break;
     case nsPluginInstanceVariable_DoCacheBool:
         *(PRBool*)value = PR_FALSE;
         break;
     default:
         break;
     }
     return NS_OK;
 }
 
+// Doesn't "addref" the object it returns.
 NS_METHOD MRJPluginInstance::GetJavaObject(jobject *result)
 {
+    if (mDestroying) {
+        *result = NULL;
+        return NS_ERROR_FAILURE;
+    }
     if (mApplet == NULL) {
         jobject applet = mContext->getApplet();
         JNIEnv* env = mSession->getCurrentEnv();
         mApplet = env->NewGlobalRef(applet);
     }
+    //printf("MRJPluginInstance::GetJavaObject(): returning mApplet == 0x%.8X, thread 0x%.8X\n", mApplet, pthread_self());
     *result = mApplet;
     return NS_OK;
 }
 
 // Accessing the list of instances.
 
 static MRJPluginInstance* theInstances = NULL;
 
 void MRJPluginInstance::pushInstance()
 {
@@ -945,25 +1161,45 @@
 MRJPluginInstance* MRJPluginInstance::getInstances()
 {
     return theInstances;
 }
 
 MRJPluginInstance* MRJPluginInstance::getNextInstance()
 {
     return mNext;
 }
 
+Boolean MRJPluginInstance::isValidInstance(MRJPluginInstance *instance)
+{
+    if (!instance)
+        return false;
+    MRJPluginInstance *pluginInstance = MRJPluginInstance::getInstances();
+    while (pluginInstance && !pluginInstance->isDestroying()) {
+        if (instance == pluginInstance)
+            return true;
+        pluginInstance = pluginInstance->getNextInstance();
+    }
+    return false;
+}
+
 MRJContext* MRJPluginInstance::getContext()
 {
+    if (mDestroying)
+        return NULL;
     return mContext;
 }
 
 MRJSession* MRJPluginInstance::getSession()
 {
     return mSession;
 }
 
+Boolean MRJPluginInstance::isDestroying()
+{
+	return mDestroying;
+}
+
 void MRJPluginInstance::inspectInstance(Boolean isUpdateEvt)
 {
-    if (mContext != NULL && mContext->inspectWindow() && !isUpdateEvt && mWindowlessPeer != NULL)
+    if (!mDestroying && (mContext != NULL) && mContext->inspectWindow() && !isUpdateEvt && (mWindowlessPeer != NULL))
         mWindowlessPeer->ForceRedraw();
 }
diff -U 10 -r -N old/plugin/oji/MRJCarbon/plugin/Source/MRJPlugin.h new/plugin/oji/MRJCarbon/plugin/Source/MRJPlugin.h
--- old/plugin/oji/MRJCarbon/plugin/Source/MRJPlugin.h	2003-06-11 00:11:50.000000000 -0500
+++ new/plugin/oji/MRJCarbon/plugin/Source/MRJPlugin.h	2006-11-09 15:59:01.000000000 -0600
@@ -40,54 +40,60 @@
     MRJPlugin encapsulates the global state of the MRJ plugin as a single COM object.
     MRJPluginInstance represents an instance of the MRJ plugin.
     
     by Patrick C. Beard.
  */
 
 #pragma once
 
 #include "nsIPlugin.h"
 #include "nsIPluginInstance.h"
-#include "nsIJVMPlugin.h"
-#include "nsIJVMConsole.h"
-#include "nsIJVMPluginInstance.h"
-#include "nsIThreadManager.h"
+#include "nsjvmFixes.h"
 #include "nsIEventHandler.h"
 #include "nsIPluginStreamListener.h"
-#include "SupportsMixin.h"
+
+/* On 5-9-2004 (1.10) and 5-13-2004 (1.11), the definition of nsPluginThread
+ * was dumped from nsIThreadManager.h (on the trunk) and the threadID
+ * parameters of CreateThread(), PostEvent() and GetCurrentThread() were
+ * changed from PRUint32 (or PRUint32 *) to PRThread * (or PRThread **),
+ * but no change was made to the IID.  Around the same time (2004-04-02), the
+ * value of PR_VERSION (defined in nsprpub/pr/include/prinit.h) was changed
+ * (on the trunk) from "4.5 Beta" to "4.6 Beta" (3.26).  In the following we
+ * assume that both sets of changes took place at the same time ... which is
+ * reasonably close to being true.  Yes, this is a gross hack, but what else
+ * can I do?
+ */
+#if ((PR_VMAJOR <= 4) && (PR_VMINOR <= 5))
+typedef PRUint32 nsPluginThreadPtr;
+#else
+typedef PRThread nsPluginThread;
+typedef PRThread * nsPluginThreadPtr;
+#endif
 
 class MRJPlugin;
 class MRJPluginInstance;
 class MRJSession;
 class MRJContext;
 class MRJConsole;
 
 class nsIJVMManager;
 
 class MRJPlugin :   public nsIPlugin, public nsIJVMPlugin,
-                    public nsIJVMConsole, public nsIRunnable,
-                    public SupportsMixin {
+                    public nsIJVMConsole, public nsIRunnable {
 public:
     MRJPlugin();
     virtual ~MRJPlugin();
 
     static nsresult GetService(const nsCID &aCID, const nsIID& aIID, void* *aService);
     static nsresult GetService(const char* aContractID, const nsIID& aIID, void* *aService);
     
-    // NS_DECL_ISUPPORTS
-#if USE_SYSTEM_CONSOLE
-    DECL_SUPPORTS_MIXIN
-#else
-    NS_IMETHOD QueryInterface(const nsIID& aIID, void** aInstancePtr);
-    NS_IMETHOD_(nsrefcnt) AddRef(void) { return addRef(); }
-    NS_IMETHOD_(nsrefcnt) Release(void) { return release(); }
-#endif
+    NS_DECL_ISUPPORTS
 
     // The Release method on NPIPlugin corresponds to NPP_Shutdown.
 
     // The old NPP_New call has been factored into two plugin instance methods:
     //
     // NewInstance -- called once, after the plugin instance is created. This 
     // method is used to initialize the new plugin instance (although the actual
     // plugin instance object will be created by the plugin manager).
     //
     // NPIPluginInstance::Start -- called when the plugin instance is to be
@@ -233,49 +239,43 @@
     /**
      * The Run method gives time to the JVM periodically. This makes SpendTIme() obsolete.
      */
     NS_IMETHOD
     Run();
     
     // NON-INTERFACE methods, for internal use only.
 
     MRJSession* getSession();
     nsIJVMManager* getManager();
-    nsIThreadManager* getThreadManager();
+    nsIJVMThreadManager* getThreadManager();
 
     MRJPluginInstance* getPluginInstance(jobject applet);
     MRJPluginInstance* getPluginInstance(JNIEnv* jenv);
     
     Boolean inPluginThread();
     
 private:
     nsIJVMManager* mManager;
-    nsIThreadManager* mThreadManager;
+    nsIJVMThreadManager* mThreadManager;
     MRJSession* mSession;
     MRJConsole* mConsole;
     nsPluginThread *mPluginThreadID;
     Boolean mIsEnabled;
-    
-    // support for SupportsMixin.
-    static const InterfaceInfo sInterfaces[];
-    static const UInt32 kInterfaceCount;
 };
 
 class MRJPluginInstance :   public nsIPluginInstance, public nsIJVMPluginInstance,
-                            public nsIEventHandler, public nsIPluginStreamListener,
-                            private SupportsMixin {
+                            public nsIEventHandler, public nsIPluginStreamListener {
 public:
     MRJPluginInstance(MRJPlugin* plugin);
     virtual ~MRJPluginInstance();
 
-    // NS_DECL_ISUPPORTS
-    DECL_SUPPORTS_MIXIN
+    NS_DECL_ISUPPORTS
 
     // (Corresponds to NPP_HandleEvent.)
     NS_IMETHOD
     HandleEvent(nsPluginEvent* event, PRBool* handled);
 
     /**
      * Initializes a newly created plugin instance, passing to it the plugin
      * instance peer which it should use for all communication back to the browser.
      * 
      * @param peer - the corresponding plugin instance peer
@@ -449,35 +449,36 @@
     NS_IMETHOD
     GetStreamType(nsPluginStreamType *result)
     {
         *result = nsPluginStreamType_Normal;
         return NS_OK;
     }
 
     // Accessing the list of instances.
     static MRJPluginInstance* getInstances(void);
     MRJPluginInstance* getNextInstance(void);
+    static Boolean isValidInstance(MRJPluginInstance *instance);
     
     MRJContext* getContext(void);
     MRJSession* getSession(void);
+    Boolean isDestroying(void);
+    nsPluginWindow *getWindow() { return mPluginWindow; }
+    MRJPlugin *getPlugin() { return mPlugin; }
 
 private:
     void pushInstance(void);
     void popInstance(void);
     void inspectInstance(Boolean isUpdateEvt);
 
 private:
     nsIPluginInstancePeer* mPeer;
     nsIWindowlessPluginInstancePeer* mWindowlessPeer;
     MRJPlugin* mPlugin;
     MRJSession* mSession;
     MRJContext* mContext;
     jobject mApplet;
     nsPluginWindow* mPluginWindow;
-    
+    Boolean mDestroying;
+
     // maintain a list of instances.
     MRJPluginInstance* mNext;
-
-    // support for SupportsMixin.
-    static const InterfaceInfo sInterfaces[];
-    static const UInt32 kInterfaceCount;
 };
diff -U 10 -r -N old/plugin/oji/MRJCarbon/plugin/Source/MRJSession.cpp new/plugin/oji/MRJCarbon/plugin/Source/MRJSession.cpp
--- old/plugin/oji/MRJCarbon/plugin/Source/MRJSession.cpp	2003-06-11 00:11:52.000000000 -0500
+++ new/plugin/oji/MRJCarbon/plugin/Source/MRJSession.cpp	2007-02-03 14:05:17.000000000 -0600
@@ -35,26 +35,30 @@
  * ----- END LICENSE BLOCK ----- */
 
 /*
 	MRJSession.cpp
 
 	Encapsulates a session with the MacOS Runtime for Java.
 	
 	by Patrick C. Beard.
  */
 
+#include "CSecureEnv.h"
 #include "MRJSession.h"
 #include "MRJPlugin.h"
 #include "MRJContext.h"
 #include "MRJConsole.h"
 #include "MRJMonitor.h"
 #include "TimedMessage.h"
+#include "LiveConnectNativeMethods.h"
+#import "JavaEmbeddingPlugin.h"
+extern "C" Boolean JEPCheckBundle();
 
 #include <ControlDefinitions.h>
 #include <string.h>
 #include <Memory.h>
 #include <Files.h>
 #include <Dialogs.h>
 #include <Appearance.h>
 #include <Resources.h>
 #include <Gestalt.h>
 #include <Folders.h>
@@ -63,20 +67,23 @@
 #include <JavaControl.h>
 #include <CFString.h>
 
 #include <string>
 
 extern MRJConsole* theConsole;
 extern short thePluginRefnum;
 extern FSSpec thePluginSpec;
 
 static MRJSession* theSession;
+Boolean debugUpdates = false;
+Boolean debugProxyJNI = false;
+Boolean debugPrinting = false;
 
 #if REDIRECT_VFPRINTF
 
 /**
  * As of JDK 1.2, there is a standard way to redirect *LOW LEVEL* messages from the JVM by
  * providing a vfprintf hook. Since this plugin is built using CFM compilers, this means
  * the function pointer has to be wrapped in glue code which can be called from Mach-O.
  * To get low level messages to go to the same location as Java's System.out/err, we can
  * try various techniques. One way would be to have all output go through a common
  * native method, which ends up calling java_vfprintf. Another way, is to send output
@@ -200,81 +207,755 @@
             }
             result = ::CFStringGetLength(text);
             ::CFRelease(text);
         }
     }
     return result;
 }
 
 #endif /* REDIRECT_VFPRINTF */
 
-MRJSession::MRJSession()
-	:	mStatus(noErr), mMainEnv(NULL), mJavaVM(NULL), mSession(NULL),
-	    mFirst(NULL), mLast(NULL), mMessageMonitor(NULL), mLockCount(0)
+static OSStatus OpenSessionJNI(JNIEnv *env, jclass *session, const char* consolePath);
+static OSStatus InitSecurityJNI(JNIEnv *env, jclass session);
+
+#if TARGET_RT_MAC_MACHO
+
+#import <mach-o/dyld.h>
+
+static jclass netscape_oji_JNIUtils = NULL;
+static jmethodID netscape_oji_JNIUtils_checkClassAccessID = NULL;
+static jmethodID netscape_oji_JNIUtils_checkClassAccess2ID = NULL;
+static jmethodID netscape_oji_JNIUtils_fixProtectionDomainsID = NULL;
+
+typedef jclass (*CLASS_FORNAME0) (JNIEnv *, jclass, jstring, jboolean, jobject);
+// Java 1.4.X only (start)
+typedef jobjectArray (*CLASS_GETDECLAREDFIELDS0) (JNIEnv *, jobject, jboolean);
+typedef jobjectArray (*CLASS_GETDECLAREDMETHODS0) (JNIEnv *, jobject, jboolean);
+typedef jobjectArray (*CLASS_GETDECLAREDCONSTRUCTORS0) (JNIEnv *, jobject, jboolean);
+// Java 1.4.X only (end)
+// Java 1.3.1 only (start)
+typedef jobjectArray (*CLASS_GETFIELDS0) (JNIEnv *, jobject, jint);
+typedef jobjectArray (*CLASS_GETMETHODS0) (JNIEnv *, jobject, jint);
+typedef jobjectArray (*CLASS_GETCONSTRUCTORS0) (JNIEnv *, jobject, jint);
+typedef jobject (*CLASS_GETFIELD0) (JNIEnv *, jobject, jstring, jint);
+typedef jobject (*CLASS_GETMETHOD0) (JNIEnv *, jobject, jstring, jobjectArray, jint);
+typedef jobject (*CLASS_GETCONSTRUCTOR0) (JNIEnv *, jobject, jobjectArray, jint);
+// Java 1.3.1 only (end)
+typedef jobjectArray (*CLASS_GETDECLAREDCLASSES0) (JNIEnv *, jobject);
+typedef jobject (*ACCESSCONTROLLER_GETSTACK) (JNIEnv *, jclass);
+
+// We use the following routine to "hook" a Java native method --
+// Class.forName0().  This is part of a fix for a security hole in Java
+// versions prior to 1.4.2_06 (though the earliest one we're actually
+// concerned about is 1.3.1).  See the comment to JNIUtils.checkClassAccess().
+// That method will throw a SecurityException when appropriate.
+JNIEXPORT jclass JNICALL
+	Java_java_lang_Class_forName0_redirect(JNIEnv *env, jclass clazz,
+	jstring name, jboolean initialize, jobject loader)
+{
+	jclass retval = NULL;
+	NSSymbol symbol = NULL;
+	static CLASS_FORNAME0 forName0 = NULL;
+	if (!forName0) {
+		/* We assume the library containing the symbol we're looking for
+		 * has already been loaded -- if it hasn't the following call will
+		 * cause a failed-assertion-style crash.  We might be running in
+		 * either Java 1.4.X or Java 1.3.1, so we don't want to explicitly
+		 * load (or link to) a particular library.
+		 */
+		if (symbol = NSLookupAndBindSymbol("_Java_java_lang_Class_forName0"))
+			forName0 = (CLASS_FORNAME0) NSAddressOfSymbol(symbol);
+	}
+	if (forName0)
+		retval = forName0(env, clazz, name, initialize, loader);
+	static unsigned entered = 0;
+	if (++entered > 1) {
+		--entered;
+		return retval;
+	}
+	env->CallStaticVoidMethod(netscape_oji_JNIUtils,
+		netscape_oji_JNIUtils_checkClassAccessID, name);
+	if (env->ExceptionCheck())
+		retval = NULL;
+	--entered;
+	return retval;
+}
+
+/* The following ten routines (from Java_java_lang_Class_getDeclaredFields0_redirect()
+ * to Java_java_lang_Class_getDeclaredClasses0_redirect()) constitute a fix
+ * for a (relatively minor) security hole in Sun's and Apple's JVMs (all
+ * versions including the latest, 1.5.0_02).  Without this fix, it's possible
+ * to call an applet's "EmbeddedFrame"'s methods via JavaScript-to-Java
+ * LiveConnect even when access to this class has been denied using the
+ * "package access" setting in jre/lib/security/java.security.  Create the
+ * following method in your applet:
+ *
+ *  public Frame getAppletFrame() {
+ *      Component c = this;
+ *      while (!(c instanceof Frame))
+ *          c = (Component) c.getParent();
+ *      return (Frame) c;
+ *  }
+ *
+ * Then call it from JavaScript as follows:
+ *
+ *  document.[appletName].getAppletFrame().[appletFrameMethod]();
+ *
+ */
+JNIEXPORT jobjectArray JNICALL
+	Java_java_lang_Class_getDeclaredFields0_redirect(JNIEnv *env, jobject self,
+	jboolean publicOnly)
+{
+	jobjectArray retval = NULL;
+	NSSymbol symbol = NULL;
+	static CLASS_GETDECLAREDFIELDS0 getFields = NULL;
+	if (!getFields) {
+		if (symbol = NSLookupAndBindSymbol("_JVM_GetClassDeclaredFields"))
+			getFields = (CLASS_GETDECLAREDFIELDS0) NSAddressOfSymbol(symbol);
+	}
+	if (getFields)
+		retval = getFields(env, self, publicOnly);
+	static unsigned entered = 0;
+	if (++entered > 1) {
+		--entered;
+		return retval;
+	}
+	env->CallStaticVoidMethod(netscape_oji_JNIUtils,
+		netscape_oji_JNIUtils_checkClassAccess2ID, self);
+	if (env->ExceptionCheck())
+		retval = NULL;
+	--entered;
+	return retval;
+}
+
+JNIEXPORT jobjectArray JNICALL
+	Java_java_lang_Class_getDeclaredMethods0_redirect(JNIEnv *env, jobject self,
+	jboolean publicOnly)
+{
+	jobjectArray retval = NULL;
+	NSSymbol symbol = NULL;
+	static CLASS_GETDECLAREDMETHODS0 getMethods = NULL;
+	if (!getMethods) {
+		if (symbol = NSLookupAndBindSymbol("_JVM_GetClassDeclaredMethods"))
+			getMethods = (CLASS_GETDECLAREDMETHODS0) NSAddressOfSymbol(symbol);
+	}
+	if (getMethods)
+		retval = getMethods(env, self, publicOnly);
+	static unsigned entered = 0;
+	if (++entered > 1) {
+		--entered;
+		return retval;
+	}
+	env->CallStaticVoidMethod(netscape_oji_JNIUtils,
+		netscape_oji_JNIUtils_checkClassAccess2ID, self);
+	if (env->ExceptionCheck())
+		retval = NULL;
+	--entered;
+	return retval;
+}
+
+JNIEXPORT jobjectArray JNICALL
+	Java_java_lang_Class_getDeclaredConstructors0_redirect(JNIEnv *env, jobject self,
+	jboolean publicOnly)
+{
+	jobjectArray retval = NULL;
+	NSSymbol symbol = NULL;
+	static CLASS_GETDECLAREDCONSTRUCTORS0 getConstructors = NULL;
+	if (!getConstructors) {
+		if (symbol = NSLookupAndBindSymbol("_JVM_GetClassDeclaredConstructors"))
+			getConstructors = (CLASS_GETDECLAREDCONSTRUCTORS0) NSAddressOfSymbol(symbol);
+	}
+	if (getConstructors)
+		retval = getConstructors(env, self, publicOnly);
+	static unsigned entered = 0;
+	if (++entered > 1) {
+		--entered;
+		return retval;
+	}
+	env->CallStaticVoidMethod(netscape_oji_JNIUtils,
+		netscape_oji_JNIUtils_checkClassAccess2ID, self);
+	if (env->ExceptionCheck())
+		retval = NULL;
+	--entered;
+	return retval;
+}
+
+JNIEXPORT jobjectArray JNICALL
+	Java_java_lang_Class_getFields0_redirect(JNIEnv *env, jobject self, jint which)
+{
+	jobjectArray retval = NULL;
+	NSSymbol symbol = NULL;
+	static CLASS_GETFIELDS0 getFields = NULL;
+	if (!getFields) {
+		if (symbol = NSLookupAndBindSymbol("_JVM_GetClassFields"))
+			getFields = (CLASS_GETFIELDS0) NSAddressOfSymbol(symbol);
+	}
+	if (getFields)
+		retval = getFields(env, self, which);
+	static unsigned entered = 0;
+	if (++entered > 1) {
+		--entered;
+		return retval;
+	}
+	env->CallStaticVoidMethod(netscape_oji_JNIUtils,
+		netscape_oji_JNIUtils_checkClassAccess2ID, self);
+	if (env->ExceptionCheck())
+		retval = NULL;
+	--entered;
+	return retval;
+}
+
+JNIEXPORT jobjectArray JNICALL
+	Java_java_lang_Class_getMethods0_redirect(JNIEnv *env, jobject self, jint which)
+{
+	jobjectArray retval = NULL;
+	NSSymbol symbol = NULL;
+	static CLASS_GETMETHODS0 getMethods = NULL;
+	if (!getMethods) {
+		if (symbol = NSLookupAndBindSymbol("_JVM_GetClassMethods"))
+			getMethods = (CLASS_GETMETHODS0) NSAddressOfSymbol(symbol);
+	}
+	if (getMethods)
+		retval = getMethods(env, self, which);
+	static unsigned entered = 0;
+	if (++entered > 1) {
+		--entered;
+		return retval;
+	}
+	env->CallStaticVoidMethod(netscape_oji_JNIUtils,
+		netscape_oji_JNIUtils_checkClassAccess2ID, self);
+	if (env->ExceptionCheck())
+		retval = NULL;
+	--entered;
+	return retval;
+}
+
+JNIEXPORT jobjectArray JNICALL
+	Java_java_lang_Class_getConstructors0_redirect(JNIEnv *env, jobject self, jint which)
+{
+	jobjectArray retval = NULL;
+	NSSymbol symbol = NULL;
+	static CLASS_GETCONSTRUCTORS0 getConstructors = NULL;
+	if (!getConstructors) {
+		if (symbol = NSLookupAndBindSymbol("_JVM_GetClassConstructors"))
+			getConstructors = (CLASS_GETCONSTRUCTORS0) NSAddressOfSymbol(symbol);
+	}
+	if (getConstructors)
+		retval = getConstructors(env, self, which);
+	static unsigned entered = 0;
+	if (++entered > 1) {
+		--entered;
+		return retval;
+	}
+	env->CallStaticVoidMethod(netscape_oji_JNIUtils,
+		netscape_oji_JNIUtils_checkClassAccess2ID, self);
+	if (env->ExceptionCheck())
+		retval = NULL;
+	--entered;
+	return retval;
+}
+
+JNIEXPORT jobject JNICALL
+	Java_java_lang_Class_getField0_redirect(JNIEnv *env, jobject self,
+	jstring name, jint which)
+{
+	jobject retval = NULL;
+	NSSymbol symbol = NULL;
+	static CLASS_GETFIELD0 getField = NULL;
+	if (!getField) {
+		if (symbol = NSLookupAndBindSymbol("_JVM_GetClassField"))
+			getField = (CLASS_GETFIELD0) NSAddressOfSymbol(symbol);
+	}
+	if (getField)
+		retval = getField(env, self, name, which);
+	static unsigned entered = 0;
+	if (++entered > 1) {
+		--entered;
+		return retval;
+	}
+	env->CallStaticVoidMethod(netscape_oji_JNIUtils,
+		netscape_oji_JNIUtils_checkClassAccess2ID, self);
+	if (env->ExceptionCheck())
+		retval = NULL;
+	--entered;
+	return retval;
+}
+
+JNIEXPORT jobject JNICALL
+	Java_java_lang_Class_getMethod0_redirect(JNIEnv *env, jobject self,
+	jstring name, jobjectArray parameterTypes, jint which)
+{
+	jobject retval = NULL;
+	NSSymbol symbol = NULL;
+	static CLASS_GETMETHOD0 getMethod = NULL;
+	if (!getMethod) {
+		if (symbol = NSLookupAndBindSymbol("_JVM_GetClassMethod"))
+			getMethod = (CLASS_GETMETHOD0) NSAddressOfSymbol(symbol);
+	}
+	if (getMethod)
+		retval = getMethod(env, self, name, parameterTypes, which);
+	static unsigned entered = 0;
+	if (++entered > 1) {
+		--entered;
+		return retval;
+	}
+	env->CallStaticVoidMethod(netscape_oji_JNIUtils,
+		netscape_oji_JNIUtils_checkClassAccess2ID, self);
+	if (env->ExceptionCheck())
+		retval = NULL;
+	--entered;
+	return retval;
+}
+
+JNIEXPORT jobject JNICALL
+	Java_java_lang_Class_getConstructor0_redirect(JNIEnv *env, jobject self,
+	jobjectArray parameterTypes, jint which)
+{
+	jobject retval = NULL;
+	NSSymbol symbol = NULL;
+	static CLASS_GETCONSTRUCTOR0 getConstructor = NULL;
+	if (!getConstructor) {
+		if (symbol = NSLookupAndBindSymbol("_JVM_GetClassConstructor"))
+			getConstructor = (CLASS_GETCONSTRUCTOR0) NSAddressOfSymbol(symbol);
+	}
+	if (getConstructor)
+		retval = getConstructor(env, self, parameterTypes, which);
+	static unsigned entered = 0;
+	if (++entered > 1) {
+		--entered;
+		return retval;
+	}
+	env->CallStaticVoidMethod(netscape_oji_JNIUtils,
+		netscape_oji_JNIUtils_checkClassAccess2ID, self);
+	if (env->ExceptionCheck())
+		retval = NULL;
+	--entered;
+	return retval;
+}
+
+JNIEXPORT jobjectArray JNICALL
+	Java_java_lang_Class_getDeclaredClasses0_redirect(JNIEnv *env, jobject self)
+{
+	jobjectArray retval = NULL;
+	NSSymbol symbol = NULL;
+	static CLASS_GETDECLAREDCLASSES0 getClasses = NULL;
+	if (!getClasses) {
+		/* We assume the library containing the symbol we're looking for
+		 * has already been loaded -- if it hasn't the following call will
+		 * cause a failed-assertion-style crash.  We might be running in
+		 * either Java 1.4.X or Java 1.3.1, so we don't want to explicitly
+		 * load (or link to) a particular library.
+		 */
+		if (symbol = NSLookupAndBindSymbol("_JVM_GetDeclaredClasses"))
+			getClasses = (CLASS_GETDECLAREDCLASSES0) NSAddressOfSymbol(symbol);
+	}
+	if (getClasses)
+		retval = getClasses(env, self);
+	static unsigned entered = 0;
+	if (++entered > 1) {
+		--entered;
+		return retval;
+	}
+	env->CallStaticVoidMethod(netscape_oji_JNIUtils,
+		netscape_oji_JNIUtils_checkClassAccess2ID, self);
+	if (env->ExceptionCheck())
+		retval = NULL;
+	--entered;
+	return retval;
+}
+
+/* The following routine is another hook for a Java native method.  It's part
+ * of a fix for a design flaw in the LiveConnect implentation of the original
+ * MRJ Plugin -- it sometimes failed to elevate an applet's privileges when
+ * the applet's code was called via LiveConnect.  See JNIUtils.
+ * fixProtectionDomains() for more information.
+ */
+JNIEXPORT jobject JNICALL
+	Java_java_security_AccessController_getStackAccessControlContext_redirect(JNIEnv *env,
+	jclass self)
+{
+	jobject retval = NULL;
+	NSSymbol symbol = NULL;
+	static ACCESSCONTROLLER_GETSTACK getStack = NULL;
+	if (!getStack) {
+		/* We assume the library containing the symbol we're looking for
+		 * has already been loaded -- if it hasn't the following call will
+		 * cause a failed-assertion-style crash.  We might be running in
+		 * either Java 1.4.X or Java 1.3.1, so we don't want to explicitly
+		 * load (or link to) a particular library.
+		 */
+		if (symbol = NSLookupAndBindSymbol("_Java_java_security_AccessController_getStackAccessControlContext"))
+			getStack = (ACCESSCONTROLLER_GETSTACK) NSAddressOfSymbol(symbol);
+	}
+	if (!getStack)
+		return NULL;
+	static unsigned entered = 0;
+	if (++entered == 1) {
+		env->CallStaticVoidMethod(netscape_oji_JNIUtils,
+			netscape_oji_JNIUtils_fixProtectionDomainsID);
+		if (env->ExceptionCheck()) {
+			--entered;
+			return NULL;
+		}
+	}
+	retval = getStack(env, self);
+	--entered;
+	return retval;
+}
+
+#endif	//#if TARGET_RT_MAC_MACHO
+
+typedef JNIEXPORT void JNICALL (*JVM_SETPROTECTIONDOMAIN) (JNIEnv *, jclass, jobject);
+typedef JNIEXPORT jobject JNICALL (*JVM_GETPROTECTIONDOMAIN) (JNIEnv *, jclass);
+typedef JNIEXPORT jobject JNICALL (*JVM_GETCLASSLOADER) (JNIEnv *, jclass);
+
+/* The following two methods (called from JNIUtils.fixProtectionDomains())
+ * allow us to bypass standard Java permission checks when getting and setting
+ * a class's protection domain.
+ */
+JNIEXPORT void JNICALL
+	Java_netscape_oji_JNIUtils_setClassProtectionDomain(JNIEnv *env, jclass self,
+	jclass clazz, jobject newProtectionDomain)
+{
+#if TARGET_RT_MAC_MACHO
+	NSSymbol symbol = NULL;
+	static JVM_SETPROTECTIONDOMAIN JVM_SetProtectionDomain = NULL;
+	if (!JVM_SetProtectionDomain) {
+		/* We assume the library containing the symbol we're looking for
+		 * has already been loaded -- if it hasn't the following call will
+		 * cause a failed-assertion-style crash.  We might be running in
+		 * either Java 1.4.X or Java 1.3.1, so we don't want to explicitly
+		 * load (or link to) a particular library.
+		 */
+		if (symbol = NSLookupAndBindSymbol("_JVM_SetProtectionDomain"))
+			JVM_SetProtectionDomain = (JVM_SETPROTECTIONDOMAIN) NSAddressOfSymbol(symbol);
+	}
+	if (JVM_SetProtectionDomain && clazz && newProtectionDomain)
+		JVM_SetProtectionDomain(env, clazz, newProtectionDomain);
+#endif
+}
+
+JNIEXPORT jobject JNICALL
+	Java_netscape_oji_JNIUtils_getClassProtectionDomain(JNIEnv *env, jclass self,
+	jclass clazz)
+{
+#if TARGET_RT_MAC_MACHO
+	jobject retval = NULL;
+	NSSymbol symbol = NULL;
+	static JVM_GETPROTECTIONDOMAIN JVM_GetProtectionDomain = NULL;
+	if (!JVM_GetProtectionDomain) {
+		/* We assume the library containing the symbol we're looking for
+		 * has already been loaded -- if it hasn't the following call will
+		 * cause a failed-assertion-style crash.  We might be running in
+		 * either Java 1.4.X or Java 1.3.1, so we don't want to explicitly
+		 * load (or link to) a particular library.
+		 */
+		if (symbol = NSLookupAndBindSymbol("_JVM_GetProtectionDomain"))
+			JVM_GetProtectionDomain = (JVM_GETPROTECTIONDOMAIN) NSAddressOfSymbol(symbol);
+	}
+	if (JVM_GetProtectionDomain && clazz)
+		retval = JVM_GetProtectionDomain(env, clazz);
+	return retval;
+#endif
+}
+
+/* The following two methods are needed by ProxyClassLoader in
+ * ProxyClassLoaderFactory.java.
+ */
+JNIEXPORT void JNICALL
+	Java_netscape_oji_ProxyClassLoaderFactory_holdSecureEnv(JNIEnv *env,
+	jclass self, jint secureEnvAddr)
+{
+	if (secureEnvAddr == 0)
+		return;
+	CSecureEnv *secureEnv = (CSecureEnv *) secureEnvAddr;
+	NS_ADDREF(secureEnv);
+}
+
+JNIEXPORT void JNICALL
+	Java_netscape_oji_ProxyClassLoaderFactory_releaseSecureEnv(JNIEnv *env,
+	jclass self, jint secureEnvAddr)
+{
+	if (secureEnvAddr == 0)
+		return;
+	CSecureEnv *secureEnv = (CSecureEnv *) secureEnvAddr;
+	NS_RELEASE(secureEnv);
+}
+
+/* This must be called just after the JVM was started and before the AWT
+ * libraries are loaded -- so that the "poor man's console" is initialized
+ * early enough.  If the "poor man's console" is initialized later,
+ * Sun/Apple's Java Console won't work properly.
+ */
+static OSStatus OpenSessionJNI(JNIEnv *env, jclass *session, const char* consolePath)
+{
+	if (session)
+		*session = NULL;
+	if (!env)
+		return EINVAL;
+	jclass sessionLocal = env->FindClass("netscape/oji/MRJSession");
+	if (!sessionLocal)
+		return ENOENT;
+	if (session)
+		*session = (jclass) env->NewGlobalRef(sessionLocal);
+	jmethodID openMethod = env->GetStaticMethodID(sessionLocal, "open",
+		"(Ljava/lang/String;)V");
+	if (!openMethod)
+		return ENOENT;
+	jstring path = env->NewStringUTF(consolePath);
+	if (!path)
+		return ENOMEM;
+	env->CallStaticVoidMethod(sessionLocal, openMethod, path);
+	if (env->ExceptionCheck())
+		return ENOENT;
+	env->DeleteLocalRef(sessionLocal);
+	return noErr;
+}
+
+/* This must be called after JavaEmbeddingPlugin.bundle's security has been
+ * initialized (i.e. after the AWT libraries are loaded).
+ */
+static OSStatus InitSecurityJNI(JNIEnv *env, jclass session)
+{
+	if (!env || !session)
+		return EINVAL;
+	jmethodID initSecurityMethod = env->GetStaticMethodID(session, "initSecurity",
+		"()V");
+	if (!initSecurityMethod)
+		return ENOENT;
+	env->CallStaticVoidMethod(session, initSecurityMethod);
+	if (env->ExceptionCheck())
+		return ENOENT;
+	jclass jniUtilsClass = env->FindClass("netscape/oji/JNIUtils");
+	jclass loaderFactoryClass = env->FindClass("netscape/oji/ProxyClassLoaderFactory");
+	if (!jniUtilsClass || !loaderFactoryClass)
+		return ENOENT;
+#if TARGET_RT_MAC_MACHO
+	netscape_oji_JNIUtils = (jclass) env->NewGlobalRef(jniUtilsClass);
+#endif
+	JNINativeMethod JNIUtilsMethods[] = {
+		{"setClassProtectionDomain",
+			"(Ljava/lang/Class;Ljava/security/ProtectionDomain;)V",
+			(void *) &Java_netscape_oji_JNIUtils_setClassProtectionDomain},
+		{"getClassProtectionDomain",
+			"(Ljava/lang/Class;)Ljava/security/ProtectionDomain;",
+			(void *) &Java_netscape_oji_JNIUtils_getClassProtectionDomain}
+		};
+	env->RegisterNatives(jniUtilsClass, JNIUtilsMethods,
+		sizeof(JNIUtilsMethods)/sizeof(JNINativeMethod));
+	env->DeleteLocalRef(jniUtilsClass);
+	JNINativeMethod LoaderFactoryMethods[] = {
+		{"holdSecureEnv", "(I)V",
+			(void *) &Java_netscape_oji_ProxyClassLoaderFactory_holdSecureEnv},
+		{"releaseSecureEnv", "(I)V",
+			(void *) &Java_netscape_oji_ProxyClassLoaderFactory_releaseSecureEnv}
+		};
+	env->RegisterNatives(loaderFactoryClass, LoaderFactoryMethods,
+		sizeof(LoaderFactoryMethods)/sizeof(JNINativeMethod));
+	env->DeleteLocalRef(loaderFactoryClass);
+	if (env->ExceptionCheck())
+		return ENOENT;
+#if TARGET_RT_MAC_MACHO
+	jclass classClass = env->FindClass("java/lang/Class");
+	jclass accessControllerClass = env->FindClass("java/security/AccessController");
+	if (!classClass || !accessControllerClass)
+		return ENOENT;
+	netscape_oji_JNIUtils_checkClassAccessID =
+		env->GetStaticMethodID(netscape_oji_JNIUtils, "checkClassAccess",
+		"(Ljava/lang/String;)V");
+	netscape_oji_JNIUtils_checkClassAccess2ID =
+		env->GetStaticMethodID(netscape_oji_JNIUtils, "checkClassAccess",
+		"(Ljava/lang/Class;)V");
+	netscape_oji_JNIUtils_fixProtectionDomainsID =
+		env->GetStaticMethodID(netscape_oji_JNIUtils, "fixProtectionDomains",
+		"()V");
+	if (env->ExceptionCheck())
+		return ENOENT;
+	JNINativeMethod ClassMethods14[] = {
+		{"forName0",
+			"(Ljava/lang/String;ZLjava/lang/ClassLoader;)Ljava/lang/Class;",
+			(void *) &Java_java_lang_Class_forName0_redirect},
+		{"getDeclaredFields0",
+			"(Z)[Ljava/lang/reflect/Field;",
+			(void *) &Java_java_lang_Class_getDeclaredFields0_redirect},
+		{"getDeclaredMethods0",
+			"(Z)[Ljava/lang/reflect/Method;",
+			(void *) &Java_java_lang_Class_getDeclaredMethods0_redirect},
+		{"getDeclaredConstructors0",
+			"(Z)[Ljava/lang/reflect/Constructor;",
+			(void *) &Java_java_lang_Class_getDeclaredConstructors0_redirect},
+		{"getDeclaredClasses0",
+			"()[Ljava/lang/Class;",
+			(void *) &Java_java_lang_Class_getDeclaredClasses0_redirect}
+		};
+	JNINativeMethod ClassMethods131[] = {
+		{"forName0",
+			"(Ljava/lang/String;ZLjava/lang/ClassLoader;)Ljava/lang/Class;",
+			(void *) &Java_java_lang_Class_forName0_redirect},
+		{"getFields0",
+			"(I)[Ljava/lang/reflect/Field;",
+			(void *) &Java_java_lang_Class_getFields0_redirect},
+		{"getMethods0",
+			"(I)[Ljava/lang/reflect/Method;",
+			(void *) &Java_java_lang_Class_getMethods0_redirect},
+		{"getConstructors0",
+			"(I)[Ljava/lang/reflect/Constructor;",
+			(void *) &Java_java_lang_Class_getConstructors0_redirect},
+		{"getField0",
+			"(Ljava/lang/String;I)Ljava/lang/reflect/Field;",
+			(void *) &Java_java_lang_Class_getField0_redirect},
+		{"getMethod0",
+			"(Ljava/lang/String;[Ljava/lang/Class;I)Ljava/lang/reflect/Method;",
+			(void *) &Java_java_lang_Class_getMethod0_redirect},
+		{"getConstructor0",
+			"([Ljava/lang/Class;I)Ljava/lang/reflect/Constructor;",
+			(void *) &Java_java_lang_Class_getConstructor0_redirect},
+		{"getDeclaredClasses0",
+			"()[Ljava/lang/Class;",
+			(void *) &Java_java_lang_Class_getDeclaredClasses0_redirect}
+		};
+	env->RegisterNatives(classClass, ClassMethods14,
+		sizeof(ClassMethods14)/sizeof(JNINativeMethod));
+	if (env->ExceptionCheck()) {
+		env->ExceptionClear();
+		env->RegisterNatives(classClass, ClassMethods131,
+			sizeof(ClassMethods131)/sizeof(JNINativeMethod));
+		if (env->ExceptionCheck())
+			return ENOENT;
+	}
+	env->DeleteLocalRef(classClass);
+	JNINativeMethod AccessControllerMethods[] = {
+		{"getStackAccessControlContext",
+			"()Ljava/security/AccessControlContext;",
+			(void *) &Java_java_security_AccessController_getStackAccessControlContext_redirect}
+		};
+	env->RegisterNatives(accessControllerClass, AccessControllerMethods,
+		sizeof(AccessControllerMethods)/sizeof(JNINativeMethod));
+	env->DeleteLocalRef(accessControllerClass);
+	if (env->ExceptionCheck())
+		return ENOENT;
+#endif
+	return noErr;
+}
+
+MRJSession::MRJSession(MRJPlugin *plugin)
+    :   mStatus(noErr), mMainEnv(NULL), mJavaVM(NULL), mSession(NULL),
+        mPlugin(plugin), mFirst(NULL), mLast(NULL), mMessageMonitor(NULL),
+        mLockCount(0)
 {
 }
 
 MRJSession::~MRJSession()
 {
     close();
 }
 
+/* Called on a secondary thread in AppletView loadAWTLibraries, just after the
+ * AWT libraries have finished loading.  We do this to make sure applets (and
+ * the browser) don't start using Java until it has been fully initialized
+ * (including LiveConnect).  This is required in order for the JVM's proxy
+ * support to work properly:  The FindProxyForURL() JavaScript method is
+ * invoked (in AutoProxyHandler.getProxyInfo()) using Java-to-JavaScript
+ * LiveConnect), just after an MRJPluginInstance (including the very first
+ * one) has been created.  And (of course) this needs to happen (for the first
+ * time) before the first Java applet has even been loaded.
+ */
+void afterInitAWT(void *info)
+{
+    if (!info)
+        return;
+    MRJSession *session = (MRJSession *) info;
+    if (session->getStatus() != noErr)
+        return;
+    JNIEnv *env = session->getCurrentEnv();
+    OSStatus retval = InitSecurityJNI(env, session->getClass());
+    if (retval == noErr)
+        retval = PostInitLiveConnectSupport(session->getPlugin());
+    if (retval != noErr)
+        session->setStatus(retval);
+}
+
 OSStatus MRJSession::open(const char* consolePath)
 {
     // Use vanilla JNI invocation API to fire up a fresh JVM.
     string classPath = getClassPath();
     string pluginHome = getPluginHome();
     JavaVMOption theOptions[] = {
     	{ (char*) classPath.c_str() },
     	{ (char*) pluginHome.c_str() },
 #if REDIRECT_VFPRINTF
     	{ "vfprintf", NewMachOFunctionPointer(&java_vfprintf) }
 #endif
     };
 
     JavaVMInitArgs theInitArgs = {
     	JNI_VERSION_1_2,
     	sizeof(theOptions) / sizeof(JavaVMOption),
     	theOptions,
     	JNI_TRUE
     };
 
-    mStatus = ::JNI_CreateJavaVM(&mJavaVM, (void**) &mMainEnv, &theInitArgs);
-    
-    if (mStatus == noErr) {
-       	// create a monitor for the message queue to unblock Java threads.
-		mMessageMonitor = new MRJMonitor(this);
+	/* We need to be very careful how we launch the JVM when working with the
+	 * Java Embedding Plugin, because in Apple's 1.4.X and 1.5.X JVMs,
+	 * JNI_CreateJavaVM() does its work mostly asynchronously (i.e. it returns
+	 * well before the JVM has finished initializing).  JEPCreateJavaVMAndInitAWT()
+	 * doesn't return until the AWT libraries have loaded (which allows us to
+	 * avoid hangs in libawt.jnilib's JNI_OnLoad() when we start using code
+	 * from it).  But we need to initialize the MRJ Plugin's "poor man's
+	 * console" just after we've created the JVM, and before the AWT libraries
+	 * have started loading.  This is why, in what follows, we first call
+	 * JEPCreateJavaVM(), then call OpenSessionJNI() (which creates the "poor
+	 * man's console"), then call JEPCreateJavaVMAndInitAWT() (which, because
+	 * we've called it after JEPCreateJavaVM(), just loads the AWT libraries
+	 * (and returns after they've finished loading)).
+	 */
+    if (JEPCheckBundle()) {
+        mStatus = JEPCreateJavaVM(theOptions, sizeof(theOptions)/sizeof(JavaVMOption),
+            &mJavaVM, (void **) &mMainEnv);
+        if (mStatus == EALREADY)
+            mStatus = noErr;
+    } else {
+        mStatus = ::JNI_CreateJavaVM(&mJavaVM, (void**) &mMainEnv, &theInitArgs);
     }
 
+    if (mStatus != noErr)
+        return mStatus;
+
+    // create a monitor for the message queue to unblock Java threads.
+    mMessageMonitor = new MRJMonitor(this);
+
     JNIEnv* env = mMainEnv;
-    jclass session = env->FindClass("netscape/oji/MRJSession");
-    if (session) {
-        mSession = (jclass) env->NewGlobalRef(session);
-        jmethodID openMethod = env->GetStaticMethodID(session, "open", "(Ljava/lang/String;)V");
-        if (openMethod) {
-            jstring path = env->NewStringUTF(consolePath);
-            if (path) {
-                env->CallStaticVoidMethod(session, openMethod, path);
-                if (env->ExceptionCheck())
-                    env->ExceptionClear();
-                env->DeleteLocalRef(path);
-            }
-        } else {
-            env->ExceptionClear();
-        }
-        env->DeleteLocalRef(session);
+    if ((mStatus = OpenSessionJNI(env, &mSession, consolePath)) != noErr)
+        return mStatus;
+    if ((mStatus = InitLiveConnectSupport(getPlugin())) != noErr)
+        return mStatus;
+    if (JEPCheckBundle()) {
+        mStatus = JEPCreateJavaVMAndInitAWT(theOptions,
+            sizeof(theOptions)/sizeof(JavaVMOption), NULL, NULL, afterInitAWT, this);
+        if (mStatus == EALREADY)
+            mStatus = noErr;
+        if (mStatus != noErr)
+            return mStatus;
     } else {
-        env->ExceptionClear();
+        if ((mStatus = InitSecurityJNI(env, mSession)) != noErr)
+            return mStatus;
+        if ((mStatus = PostInitLiveConnectSupport(getPlugin())) != noErr)
+            return mStatus;
     }
 
-    if (mStatus == noErr)
-        theSession = this;
+    theSession = this;
+    debugUpdates =
+        JEPGetJavaRuntimeParameterBoolean(CFSTR(JEP_DEBUG_UPDATES_OPTION));
+	debugProxyJNI =
+        JEPGetJavaRuntimeParameterBoolean(CFSTR(JEP_DEBUG_PROXYJNI_OPTION));
+	debugPrinting =
+		JEPGetJavaRuntimeParameterBoolean(CFSTR(JEP_DEBUG_PRINTING_OPTION));
 
 #if REDIRECT_VFPRINTF
     // XXX test the vfprintf function.
     jclass notThere = env->FindClass("class/not/Found");
     if (env->ExceptionCheck()) {
         env->ExceptionDescribe();
         env->ExceptionClear();
     }
 #endif
 
@@ -293,37 +974,57 @@
     	}
     	
     	if (mSession) {
     	    jclass session = mSession;
     	    JNIEnv* env = mMainEnv;
             jmethodID closeMethod = env->GetStaticMethodID(session, "close", "()V");
             if (closeMethod)
                 env->CallStaticVoidMethod(session, closeMethod);
             else
                 env->ExceptionClear();
-    	    env->DeleteGlobalRef(mSession);
+    	    env->DeleteGlobalRef(session);
     	    mSession = NULL;
         }
 
 #if !TARGET_RT_MAC_MACHO // XXX right now, this hangs Chimera...
         mJavaVM->DestroyJavaVM();
 #endif
         mJavaVM = NULL;
     }
     return noErr;
 }
 
 JNIEnv* MRJSession::getCurrentEnv()
 {
+	jint retval;
 	JNIEnv* env;
-	if (mJavaVM->GetEnv((void**)&env, JNI_VERSION_1_2) == JNI_OK)
+	int jvmVersion = JNI_VERSION_1_2;
+	/* We don't actually use any 1.4.X-specific JNI calls or features, and
+	 * we should (presumably) preserve compatibility between the "native"
+	 * JNIEnv structure and the Mozilla family's ProxyJNIEnv class (see
+	 * modules/oji/src/ProxyJNI.cpp).
+	 */
+	//if (JEPCheckBundle()) {
+	//	jvmVersion = JNI_VERSION_1_4;
+	//}
+
+	if (!mJavaVM)
+		return NULL;
+
+	retval = mJavaVM->GetEnv((void**)&env, jvmVersion);
+	if (retval == JNI_EDETACHED) {
+		if (!mJavaVM->AttachCurrentThread((void **)&env, nil))
+			retval = JNI_OK;
+	}
+	if (retval == JNI_OK)
 		return env;
+
     return NULL;
 }
 
 JNIEnv* MRJSession::getMainEnv()
 {
 	return mMainEnv;
 }
 
 JavaVM* MRJSession::getJavaVM()
 {
@@ -485,21 +1186,21 @@
 void MRJSession::unlock()
 {
 	--mLockCount;
 }
 
 static OSStatus ref2path(const FSRef& ref, char* path, UInt32 maxPathSize)
 {
     return FSRefMakePath(&ref, (UInt8*)path, maxPathSize);
 }
 
-static OSStatus spec2path(const FSSpec& spec, char* path, UInt32 maxPathSize)
+OSStatus spec2path(const FSSpec& spec, char* path, UInt32 maxPathSize)
 {
     FSRef ref;
     OSStatus status = FSpMakeFSRef(&spec, &ref);
     if (status == noErr)
         status = ref2path(ref, path, maxPathSize);
     return status;
 }
 
 string MRJSession::getClassPath()
 {
diff -U 10 -r -N old/plugin/oji/MRJCarbon/plugin/Source/MRJSession.h new/plugin/oji/MRJCarbon/plugin/Source/MRJSession.h
--- old/plugin/oji/MRJCarbon/plugin/Source/MRJSession.h	2003-06-11 00:11:54.000000000 -0500
+++ new/plugin/oji/MRJCarbon/plugin/Source/MRJSession.h	2006-11-10 14:21:16.000000000 -0600
@@ -65,43 +65,46 @@
 	NativeMessage* getNext() { return mNext; }
 
 private:
 	NativeMessage* mNext;
 };
 
 // FIXME:  need an interface for setting security options, etc.
 
 class MRJContext;
 class Monitor;
+class MRJPlugin;
 
 class MRJSession {
 public:
-	MRJSession();
+	MRJSession(MRJPlugin *plugin);
 	virtual ~MRJSession();
 	
 	OSStatus open(const char* consolePath);
 	OSStatus close();
 	
 	JNIEnv* getCurrentEnv();
 	JNIEnv* getMainEnv();
 	JavaVM* getJavaVM();
 	
 	Boolean onMainThread();
 	
 	Boolean addToClassPath(const FSSpec& fileSpec);
 	Boolean addToClassPath(const char* dirPath);
 	Boolean addURLToClassPath(const char* fileURL);
 
 	char* getProperty(const char* propertyName);
 	
 	void setStatus(OSStatus status);
 	OSStatus getStatus();
+	MRJPlugin *getPlugin() { return mPlugin; }
+	jclass getClass() { return mSession; }
 	
 	void idle(UInt32 milliseconds = 0x00000400);
 
 	void sendMessage(NativeMessage* message, Boolean async = false);
 	
 	/**
 	 * Used to prevent reentering the VM.
 	 */
 	void lock();
 	void unlock();
@@ -115,18 +118,19 @@
 	
 private:
 	OSStatus mStatus;
 	
 	typedef vector<FSRef> MRJClassPath;
 	MRJClassPath mClassPath;
 	
 	JNIEnv* mMainEnv;
 	JavaVM* mJavaVM;
 	jclass mSession;
+	MRJPlugin *mPlugin;
 
 	// Message queue.
 	NativeMessage* mFirst;
 	NativeMessage* mLast;
 	Monitor* mMessageMonitor;
 	
 	UInt32 mLockCount;
 };
diff -U 10 -r -N old/plugin/oji/MRJCarbon/plugin/Source/MRJSession.java new/plugin/oji/MRJCarbon/plugin/Source/MRJSession.java
--- old/plugin/oji/MRJCarbon/plugin/Source/MRJSession.java	2003-06-11 00:11:54.000000000 -0500
+++ new/plugin/oji/MRJCarbon/plugin/Source/MRJSession.java	2004-12-10 12:34:22.000000000 -0600
@@ -30,83 +30,153 @@
  * decision by deleting the provisions above and replace them with the notice
  * and other provisions required by the GPL or the LGPL. If you do not delete
  * the provisions above, a recipient may use your version of this file under
  * the terms of any one of the MPL, the GPL or the LGPL.
  *
  * ----- END LICENSE BLOCK ----- */
 
 package netscape.oji;
 
 import java.io.*;
-import java.awt.*;
-import java.awt.event.*;
 import java.util.Date;
 import java.util.Properties;
-import java.net.URL;
+import java.security.Security;
 
 /**
  * Performs startup actions on behalf of the MRJ plugin.
  * 1. Sends System.out/err to a specified disk file.
  * 2. Installs an appropriate security manager for
  *    integrating with the Netscape 6 security system.
  */
 public class MRJSession {
     // Save primordial System streams.
-    private static PrintStream out;
-    private static PrintStream err;
-    private static PrintStream console;
+    private static PrintStream out = null;
+    private static PrintStream err = null;
+    private static PrintStream console = null;
+    private static Properties props = null;
+    private static String pluginHome = "";
 
-    private static Properties loadProperties(String pluginHome) {
+    private static Properties loadProperties() {
         Properties props = new Properties();
         try {
             InputStream propsStream = new FileInputStream(pluginHome + "/MRJPlugin.properties");
             props.load(propsStream);
             propsStream.close();
         } catch (IOException ex) {
+            System.out.println("MRJSession.loadProperties(): Exception " +
+                ex.getMessage());
+            ex.printStackTrace();
+            throw new InternalError();
         }
         return props;
     }
 
+	// This code was "borrowed" from AppletHolderFactory.java of the Java
+	// Embedding Plugin.  The previous code simply replaced other policy files
+	// with the one that comes with the MRJ Plugin Carbon.  This needs either
+	// to be called on the main thread (as it is here) or before a security
+	// manager is created.  Original comment:  Make sure that the classes in
+	// MRJPlugin.jar are granted all permissions.  See p. 117 of "Inside Java
+	// 2 Platform Security" for more information.
+	private static void giveOurselvesAllPermissions() {
+		try {
+			int n = 1;
+			while (Security.getProperty("policy.url." + n) != null)
+				++n;
+			String ourPolicyProperty = "policy.url." + n;
+			Security.setProperty(ourPolicyProperty,
+				"file:" + pluginHome + "/MRJPlugin.policy");
+		} catch (Exception ex) {
+			System.out.println("MRJSession.giveOurselvesAllPermissions(): Exception " +
+				ex.getMessage());
+			ex.printStackTrace();
+			throw new InternalError();
+		}
+	}
+
+	// We should restrict access to the "netscape.oji" package, to avoid
+	// possible security holes.  This code was "borrowed" from
+	// AppletHolderFactory.java of the Java Embedding Plugin.  For some
+	// reason this doesn't work in Java 1.3.1 -- the "package.access"
+	// property gets changed to the correct value, but SecurityManager.
+	// checkPackageAccess() ignores the change.
+	private static void restrictPackageAccess() {
+		try {
+			String packageAccess = Security.getProperty("package.access");
+			packageAccess += ",netscape.oji.";
+			Security.setProperty("package.access", packageAccess);
+		} catch (Exception ex) {
+			System.out.println("MRJSession.restrictPackageAccess(): Exception " +
+				ex.getMessage());
+			ex.printStackTrace();
+			throw new InternalError();
+		}
+	}
+
     public static void open(String consolePath) throws IOException {
-        String pluginHome = System.getProperty("netscape.oji.plugin.home");
-        Properties props = loadProperties(pluginHome);
+        pluginHome = System.getProperty("netscape.oji.plugin.home");
+        props = loadProperties();
         boolean append = Boolean.valueOf(props.getProperty("netscape.oji.plugin.console.append")).booleanValue();
     
         // Make sure the parent directories exist.
         File consoleFile = new File(consolePath);
         File parentFile = consoleFile.getParentFile();
         if (!parentFile.exists()) {
             parentFile.mkdirs();
         }
     
         // redirect console I/O to specified file.
         MRJSession.out = System.out;
         MRJSession.err = System.err;
         console = new PrintStream(new FileOutputStream(consolePath, append));
         System.setOut(console);
         System.setErr(console);
+    }
 
+    public static void initSecurity() {
         Date date = new Date();
         String version = props.getProperty("netscape.oji.plugin.version");
         System.out.println("MRJ Plugin for Mac OS X v" + version);
         System.out.println("[starting up Java Applet Security @ " + date + "]");
 
+        giveOurselvesAllPermissions();
+        restrictPackageAccess();
+
+        // What follows is only necessary when not using JavaEmbeddingPlugin.bundle.
+        if (System.getProperty("java.version").compareTo("1.4") >= 0)
+            return;
+
         // bring up MRJ Applet Security.
+        // In versions of the MRJ Plugin JEP before 0.8.8, we failed to create
+        // and set a security manager here when doing Java 1.3.1 -- because the
+        // "netscape.oji.plugin.security" property used to specify a path that
+        // didn't exist in Java 1.3.1.  But Java 1.3.1's applet launcher saved
+        // the day because it creates (another) security manager later on -- so
+        // that we _weren't_ running with no applet security in Java 1.3.1 in
+        // previous versions of the JEP.  Whew!  (The old code didn't have a
+        // problem running in Java 1.4.X.)  So the following code isn't,
+        // strictly speaking, actually necessary.  But I'm keeping it anyway,
+        // if only for redundancy.
         if (System.getSecurityManager() == null) {
             try {
-                // make sure that the classes in MRJPlugin.jar are granted all permissions.
-                // see p. 117 of "Inside Java 2 Platform Security" for more information.
-                System.setProperty("java.security.policy", "file:" + pluginHome + "/MRJPlugin.policy");
                 String name = props.getProperty("netscape.oji.plugin.security");
                 SecurityManager securityManager = (SecurityManager) Class.forName(name).newInstance();
                 System.setSecurityManager(securityManager);
             } catch (Exception ex) {
+                // Part of the reason I missed the earlier problems with this
+                // code is that no error messages were displayed when it
+                // failed to create and install a security manager.  Now we
+                // do.
+                System.err.println("MRJ Plugin: Exception while setting Java 1.3.1 security manager: " +
+                    ex.getMessage());
+                ex.printStackTrace();
+                throw new InternalError();
             }
         }
     }
 
     public static void close() throws IOException {
         System.setOut(MRJSession.out);
         System.setErr(MRJSession.err);
         console.close();
     }
 }
diff -U 10 -r -N old/plugin/oji/MRJCarbon/plugin/Source/NativeMonitor.cpp new/plugin/oji/MRJCarbon/plugin/Source/NativeMonitor.cpp
--- old/plugin/oji/MRJCarbon/plugin/Source/NativeMonitor.cpp	2003-06-11 00:11:54.000000000 -0500
+++ new/plugin/oji/MRJCarbon/plugin/Source/NativeMonitor.cpp	2006-05-22 21:31:26.000000000 -0500
@@ -37,23 +37,22 @@
 /*
 	NativeMonitor.cpp
 	
 	Provides a C++ interface to native monitors.
 	
 	by Patrick C. Beard.
  */
 
 #include "NativeMonitor.h"
 #include "MRJSession.h"
-#include "nsIThreadManager.h"
 
-NativeMonitor::NativeMonitor(MRJSession* session, nsIThreadManager* manager, void* address)
+NativeMonitor::NativeMonitor(MRJSession* session, nsIJVMThreadManager* manager, void* address)
 	:	mSession(session), mManager(manager), mAddress(address)
 {
 	if (address == NULL)
 		mAddress = this;
 }
 
 NativeMonitor::~NativeMonitor() {}
 
 void NativeMonitor::enter()
 {
diff -U 10 -r -N old/plugin/oji/MRJCarbon/plugin/Source/NativeMonitor.h new/plugin/oji/MRJCarbon/plugin/Source/NativeMonitor.h
--- old/plugin/oji/MRJCarbon/plugin/Source/NativeMonitor.h	2003-06-11 00:11:54.000000000 -0500
+++ new/plugin/oji/MRJCarbon/plugin/Source/NativeMonitor.h	2006-05-22 21:31:52.000000000 -0500
@@ -36,32 +36,32 @@
 
 /*
 	NativeMonitor.h
 	
 	Provides a C++ interface to native monitors.
 	
 	by Patrick C. Beard.
  */
 
 #include "Monitor.h"
+#include "nsjvmFixes.h"
 
 class MRJSession;
-class nsIThreadManager;
 
 class NativeMonitor : public Monitor {
 public:
-	NativeMonitor(MRJSession* session, nsIThreadManager* manager, void* address = 0);
+	NativeMonitor(MRJSession* session, nsIJVMThreadManager* manager, void* address = 0);
 	virtual ~NativeMonitor();
 
 	virtual void enter();
 	virtual void exit();
 	
 	virtual void wait();
 	virtual void wait(long long millis);
 	virtual void notify();
 	virtual void notifyAll();
 
 private:
 	MRJSession* mSession;
-	nsIThreadManager* mManager;
+	nsIJVMThreadManager* mManager;
 	void* mAddress;
 };
diff -U 10 -r -N old/plugin/oji/MRJCarbon/plugin/Source/nsIScriptSecurityManagerNewer.h new/plugin/oji/MRJCarbon/plugin/Source/nsIScriptSecurityManagerNewer.h
--- old/plugin/oji/MRJCarbon/plugin/Source/nsIScriptSecurityManagerNewer.h	1969-12-31 18:00:00.000000000 -0600
+++ new/plugin/oji/MRJCarbon/plugin/Source/nsIScriptSecurityManagerNewer.h	2006-11-11 21:27:13.000000000 -0600
@@ -0,0 +1,562 @@
+/*
+ * DO NOT EDIT.  THIS FILE IS GENERATED FROM /Volumes/Storage/Developer/Mozilla/cvs/mozilla/caps/idl/nsIScriptSecurityManager.idl
+ */
+
+#ifndef __gen_nsIScriptSecurityManagerNewer_h__
+#define __gen_nsIScriptSecurityManagerNewer_h__
+
+
+#ifndef __gen_nsISupports_h__
+#include "nsISupports.h"
+#endif
+
+#ifndef __gen_nsIPrincipal_h__
+#include "nsIPrincipal.h"
+#endif
+
+#ifndef __gen_nsIXPCSecurityManager_h__
+#include "nsIXPCSecurityManager.h"
+#endif
+
+/* For IDL files that don't want to include root IDL files. */
+#ifndef NS_NO_VTABLE
+#define NS_NO_VTABLE
+#endif
+class nsIURI; /* forward declaration */
+
+
+/* starting interface:    nsIScriptSecurityManager */
+#define NS_ISCRIPTSECURITYMANAGERNEWERALT1_IID_STR "5a46e611-cf4a-4407-a5b4-002fcf051120"
+
+#ifndef NS_ISCRIPTSECURITYMANAGERNEWERALT1_IID
+#define NS_ISCRIPTSECURITYMANAGERNEWERALT1_IID \
+  {0x5a46e611, 0xcf4a, 0x4407, \
+    { 0xa5, 0xb4, 0x00, 0x2f, 0xcf, 0x05, 0x11, 0x20 }}
+#endif
+
+class NS_NO_VTABLE nsIScriptSecurityManagerNewer : public nsIXPCSecurityManager {
+ public: 
+
+#ifdef NS_DECLARE_STATIC_IID_ACCESSOR
+  NS_DECLARE_STATIC_IID_ACCESSOR(NS_ISCRIPTSECURITYMANAGERNEWERALT1_IID)
+#else
+  NS_DEFINE_STATIC_IID_ACCESSOR(NS_ISCRIPTSECURITYMANAGERNEWERALT1_IID)
+#endif
+
+  /**
+     * Checks whether the running script is allowed to access aProperty.
+     */
+  /* [noscript] void checkPropertyAccess (in JSContextPtr aJSContext, in JSObjectPtr aJSObject, in string aClassName, in JSVal aProperty, in PRUint32 aAction); */
+  NS_IMETHOD CheckPropertyAccess(JSContext * aJSContext, JSObject * aJSObject, const char *aClassName, jsval aProperty, PRUint32 aAction) = 0;
+
+  /**
+     * Checks whether the running script is allowed to connect to aTargetURI
+     */
+  /* [noscript] void checkConnect (in JSContextPtr aJSContext, in nsIURI aTargetURI, in string aClassName, in string aProperty); */
+  NS_IMETHOD CheckConnect(JSContext * aJSContext, nsIURI *aTargetURI, const char *aClassName, const char *aProperty) = 0;
+
+  /**
+     * Check that the script currently running in context "cx" can load "uri".
+     *
+     * Will return error code NS_ERROR_DOM_BAD_URI if the load request 
+     * should be denied.
+     *
+     * @param cx the JSContext of the script causing the load
+     * @param uri the URI that is being loaded
+     */
+  /* [noscript] void checkLoadURIFromScript (in JSContextPtr cx, in nsIURI uri); */
+  NS_IMETHOD CheckLoadURIFromScript(JSContext * cx, nsIURI *uri) = 0;
+
+  /**
+     * Default CheckLoadURI permissions
+     */
+  enum { STANDARD = 0U };
+
+  enum { DISALLOW_FROM_MAIL = 1U };
+
+  enum { ALLOW_CHROME = 2U };
+
+  enum { DISALLOW_SCRIPT_OR_DATA = 4U };
+
+  enum { DISALLOW_SCRIPT = 8U };
+
+  /**
+     * Check that content with principal aPrincipal can load "uri".
+     *
+     * Will return error code NS_ERROR_DOM_BAD_URI if the load request 
+     * should be denied.
+     *
+     * @param aPrincipal the principal identifying the actor causing the load
+     * @param uri the URI that is being loaded
+     * @param flags the permission set, see above
+     */
+  /* void checkLoadURIWithPrincipal (in nsIPrincipal aPrincipal, in nsIURI uri, in unsigned long flags); */
+  NS_IMETHOD CheckLoadURIWithPrincipal(nsIPrincipal *aPrincipal, nsIURI *uri, PRUint32 flags) = 0;
+
+  /**
+     * Check that content from "from" can load "uri".
+     *
+     * Will return error code NS_ERROR_DOM_BAD_URI if the load request 
+     * should be denied.
+     *
+     * @param from the URI causing the load
+     * @param uri the URI that is being loaded
+     * @param flags the permission set, see above
+     *
+     * @deprecated Use checkLoadURIWithPrincipal instead of this function.
+     */
+  /* void checkLoadURI (in nsIURI from, in nsIURI uri, in unsigned long flags); */
+  NS_IMETHOD CheckLoadURI(nsIURI *from, nsIURI *uri, PRUint32 flags) = 0;
+
+  /**
+     * Similar to checkLoadURIWithPrincipal but there are two differences:
+     *
+     * 1) The URI is a string, not a URI object.
+     * 2) This function assumes that the URI may still be subject to fixup (and
+     * hence will check whether fixed-up versions of the URI are allowed to
+     * load as well); if any of the versions of this URI is not allowed, this
+     * function will return error code NS_ERROR_DOM_BAD_URI.
+     */
+  /* void checkLoadURIStrWithPrincipal (in nsIPrincipal aPrincipal, in AUTF8String uri, in unsigned long flags); */
+  NS_IMETHOD CheckLoadURIStrWithPrincipal(nsIPrincipal *aPrincipal, const nsACString & uri, PRUint32 flags) = 0;
+
+  /**
+     * Same as CheckLoadURI but takes string arguments for ease of use
+     * by scripts
+     *
+     * @deprecated Use checkLoadURIStrWithPrincipal instead of this function.
+     */
+  /* void checkLoadURIStr (in AUTF8String from, in AUTF8String uri, in unsigned long flags); */
+  NS_IMETHOD CheckLoadURIStr(const nsACString & from, const nsACString & uri, PRUint32 flags) = 0;
+
+  /**
+     * Check that the function 'funObj' is allowed to run on 'targetObj'
+     *
+     * Will return error code NS_ERROR_DOM_SECURITY_ERR if the function
+     * should not run
+     *
+     * @param cx The current active JavaScript context.
+     * @param funObj The function trying to run..
+     * @param targetObj The object the function will run on.
+     */
+  /* [noscript] void checkFunctionAccess (in JSContextPtr cx, in voidPtr funObj, in voidPtr targetObj); */
+  NS_IMETHOD CheckFunctionAccess(JSContext * cx, void * funObj, void * targetObj) = 0;
+
+  /**
+     * Return true if content from the given principal is allowed to
+     * execute scripts.
+     */
+  /* [noscript] boolean canExecuteScripts (in JSContextPtr cx, in nsIPrincipal principal); */
+  NS_IMETHOD CanExecuteScripts(JSContext * cx, nsIPrincipal *principal, PRBool *_retval) = 0;
+
+  /**
+     * Return the principal of the innermost frame of the currently 
+     * executing script. Will return null if there is no script 
+     * currently executing.
+     */
+  /* [noscript] nsIPrincipal getSubjectPrincipal (); */
+  NS_IMETHOD GetSubjectPrincipal(nsIPrincipal **_retval) = 0;
+
+  /**
+     * Return the all-powerful system principal.
+     */
+  /* [noscript] nsIPrincipal getSystemPrincipal (); */
+  NS_IMETHOD GetSystemPrincipal(nsIPrincipal **_retval) = 0;
+
+  /**
+     * Return a principal with the specified certificate fingerprint, subject
+     * name (the full name or concatenated set of names of the entity
+     * represented by the certificate), pretty name, certificate, and
+     * codebase URI.  The certificate fingerprint and subject name MUST be
+     * nonempty; otherwise an error will be thrown.  Similarly, aCert must
+     * not be null.
+     */
+  /* [noscript] nsIPrincipal getCertificatePrincipal (in AUTF8String aCertFingerprint, in AUTF8String aSubjectName, in AUTF8String aPrettyName, in nsISupports aCert, in nsIURI aURI); */
+  NS_IMETHOD GetCertificatePrincipal(const nsACString & aCertFingerprint, const nsACString & aSubjectName, const nsACString & aPrettyName, nsISupports *aCert, nsIURI *aURI, nsIPrincipal **_retval) = 0;
+
+  /**
+     * Return a principal that has the same origin as aURI.
+     */
+  /* [noscript] nsIPrincipal getCodebasePrincipal (in nsIURI aURI); */
+  NS_IMETHOD GetCodebasePrincipal(nsIURI *aURI, nsIPrincipal **_retval) = 0;
+
+  /**
+     * Request that 'capability' can be enabled by scripts or applets
+     * running with 'principal'. Will prompt user if
+     * necessary. Returns nsIPrincipal::ENABLE_GRANTED or
+     * nsIPrincipal::ENABLE_DENIED based on user's choice.
+     */
+  /* [noscript] short requestCapability (in nsIPrincipal principal, in string capability); */
+  NS_IMETHOD RequestCapability(nsIPrincipal *principal, const char *capability, PRInt16 *_retval) = 0;
+
+  /**
+     * Return true if the currently executing script has 'capability' enabled.
+     */
+  /* boolean isCapabilityEnabled (in string capability); */
+  NS_IMETHOD IsCapabilityEnabled(const char *capability, PRBool *_retval) = 0;
+
+  /**
+     * Enable 'capability' in the innermost frame of the currently executing
+     * script.
+     */
+  /* void enableCapability (in string capability); */
+  NS_IMETHOD EnableCapability(const char *capability) = 0;
+
+  /**
+     * Remove 'capability' from the innermost frame of the currently
+     * executing script. Any setting of 'capability' from enclosing
+     * frames thus comes into effect.
+     */
+  /* void revertCapability (in string capability); */
+  NS_IMETHOD RevertCapability(const char *capability) = 0;
+
+  /**
+     * Disable 'capability' in the innermost frame of the currently executing
+     * script.
+     */
+  /* void disableCapability (in string capability); */
+  NS_IMETHOD DisableCapability(const char *capability) = 0;
+
+  /**
+     * Allow 'certificateID' to enable 'capability.' Can only be performed
+     * by code signed by the system certificate.
+     */
+  /* void setCanEnableCapability (in AUTF8String certificateFingerprint, in string capability, in short canEnable); */
+  NS_IMETHOD SetCanEnableCapability(const nsACString & certificateFingerprint, const char *capability, PRInt16 canEnable) = 0;
+
+  /**
+     * Return the principal of the specified object in the specified context.
+     */
+  /* [noscript] nsIPrincipal getObjectPrincipal (in JSContextPtr cx, in JSObjectPtr obj); */
+  NS_IMETHOD GetObjectPrincipal(JSContext * cx, JSObject * obj, nsIPrincipal **_retval) = 0;
+
+  /**
+     * Returns true if the principal of the currently running script is the
+     * system principal, false otherwise.
+     */
+  /* [noscript] boolean subjectPrincipalIsSystem (); */
+  NS_IMETHOD SubjectPrincipalIsSystem(PRBool *_retval) = 0;
+
+  /**
+     * Returns OK if aJSContext and target have the same "origin"
+     * (scheme, host, and port).
+     */
+  /* [noscript] void checkSameOrigin (in JSContextPtr aJSContext, in nsIURI aTargetURI); */
+  NS_IMETHOD CheckSameOrigin(JSContext * aJSContext, nsIURI *aTargetURI) = 0;
+
+  /**
+     * Returns OK if aSourceURI and target have the same "origin"
+     * (scheme, host, and port).
+     */
+  /* void checkSameOriginURI (in nsIURI aSourceURI, in nsIURI aTargetURI); */
+  NS_IMETHOD CheckSameOriginURI(nsIURI *aSourceURI, nsIURI *aTargetURI) = 0;
+
+  /**
+     * Returns OK if aSourcePrincipal and aTargetPrincipal
+     * have the same "origin" (scheme, host, and port).
+     */
+  /* void checkSameOriginPrincipal (in nsIPrincipal aSourcePrincipal, in nsIPrincipal aTargetPrincipal); */
+  NS_IMETHOD CheckSameOriginPrincipal(nsIPrincipal *aSourcePrincipal, nsIPrincipal *aTargetPrincipal) = 0;
+
+  /**
+     * Returns the principal of the global object of the given context, or null
+     * if no global or no principal.
+     */
+  /* [noscript] nsIPrincipal getPrincipalFromContext (in JSContextPtr cx); */
+  NS_IMETHOD GetPrincipalFromContext(JSContext * cx, nsIPrincipal **_retval) = 0;
+
+  /**
+     * Utility method for comparing two URIs.  For security purposes, two URIs
+     * are equivalent if their schemes, hosts, and ports (if any) match.  This
+     * method returns true if aSubjectURI and aObjectURI have the same origin,
+     * false otherwise.
+     // FIXME: Bug 327243 -- this is no longer used outside caps.
+     // Should it even be exposed?
+     */
+  /* [noscript] boolean securityCompareURIs (in nsIURI aSubjectURI, in nsIURI aObjectURI); */
+  NS_IMETHOD SecurityCompareURIs(nsIURI *aSubjectURI, nsIURI *aObjectURI, PRBool *_retval) = 0;
+
+};
+
+/* Use this macro when declaring classes that implement this interface. */
+#define NS_DECL_NSISCRIPTSECURITYMANAGERNEWER \
+  NS_IMETHOD CheckPropertyAccess(JSContext * aJSContext, JSObject * aJSObject, const char *aClassName, jsval aProperty, PRUint32 aAction); \
+  NS_IMETHOD CheckConnect(JSContext * aJSContext, nsIURI *aTargetURI, const char *aClassName, const char *aProperty); \
+  NS_IMETHOD CheckLoadURIFromScript(JSContext * cx, nsIURI *uri); \
+  NS_IMETHOD CheckLoadURIWithPrincipal(nsIPrincipal *aPrincipal, nsIURI *uri, PRUint32 flags); \
+  NS_IMETHOD CheckLoadURI(nsIURI *from, nsIURI *uri, PRUint32 flags); \
+  NS_IMETHOD CheckLoadURIStrWithPrincipal(nsIPrincipal *aPrincipal, const nsACString & uri, PRUint32 flags); \
+  NS_IMETHOD CheckLoadURIStr(const nsACString & from, const nsACString & uri, PRUint32 flags); \
+  NS_IMETHOD CheckFunctionAccess(JSContext * cx, void * funObj, void * targetObj); \
+  NS_IMETHOD CanExecuteScripts(JSContext * cx, nsIPrincipal *principal, PRBool *_retval); \
+  NS_IMETHOD GetSubjectPrincipal(nsIPrincipal **_retval); \
+  NS_IMETHOD GetSystemPrincipal(nsIPrincipal **_retval); \
+  NS_IMETHOD GetCertificatePrincipal(const nsACString & aCertFingerprint, const nsACString & aSubjectName, const nsACString & aPrettyName, nsISupports *aCert, nsIURI *aURI, nsIPrincipal **_retval); \
+  NS_IMETHOD GetCodebasePrincipal(nsIURI *aURI, nsIPrincipal **_retval); \
+  NS_IMETHOD RequestCapability(nsIPrincipal *principal, const char *capability, PRInt16 *_retval); \
+  NS_IMETHOD IsCapabilityEnabled(const char *capability, PRBool *_retval); \
+  NS_IMETHOD EnableCapability(const char *capability); \
+  NS_IMETHOD RevertCapability(const char *capability); \
+  NS_IMETHOD DisableCapability(const char *capability); \
+  NS_IMETHOD SetCanEnableCapability(const nsACString & certificateFingerprint, const char *capability, PRInt16 canEnable); \
+  NS_IMETHOD GetObjectPrincipal(JSContext * cx, JSObject * obj, nsIPrincipal **_retval); \
+  NS_IMETHOD SubjectPrincipalIsSystem(PRBool *_retval); \
+  NS_IMETHOD CheckSameOrigin(JSContext * aJSContext, nsIURI *aTargetURI); \
+  NS_IMETHOD CheckSameOriginURI(nsIURI *aSourceURI, nsIURI *aTargetURI); \
+  NS_IMETHOD CheckSameOriginPrincipal(nsIPrincipal *aSourcePrincipal, nsIPrincipal *aTargetPrincipal); \
+  NS_IMETHOD GetPrincipalFromContext(JSContext * cx, nsIPrincipal **_retval); \
+  NS_IMETHOD SecurityCompareURIs(nsIURI *aSubjectURI, nsIURI *aObjectURI, PRBool *_retval); 
+
+/* Use this macro to declare functions that forward the behavior of this interface to another object. */
+#define NS_FORWARD_NSISCRIPTSECURITYMANAGERNEWER(_to) \
+  NS_IMETHOD CheckPropertyAccess(JSContext * aJSContext, JSObject * aJSObject, const char *aClassName, jsval aProperty, PRUint32 aAction) { return _to CheckPropertyAccess(aJSContext, aJSObject, aClassName, aProperty, aAction); } \
+  NS_IMETHOD CheckConnect(JSContext * aJSContext, nsIURI *aTargetURI, const char *aClassName, const char *aProperty) { return _to CheckConnect(aJSContext, aTargetURI, aClassName, aProperty); } \
+  NS_IMETHOD CheckLoadURIFromScript(JSContext * cx, nsIURI *uri) { return _to CheckLoadURIFromScript(cx, uri); } \
+  NS_IMETHOD CheckLoadURIWithPrincipal(nsIPrincipal *aPrincipal, nsIURI *uri, PRUint32 flags) { return _to CheckLoadURIWithPrincipal(aPrincipal, uri, flags); } \
+  NS_IMETHOD CheckLoadURI(nsIURI *from, nsIURI *uri, PRUint32 flags) { return _to CheckLoadURI(from, uri, flags); } \
+  NS_IMETHOD CheckLoadURIStrWithPrincipal(nsIPrincipal *aPrincipal, const nsACString & uri, PRUint32 flags) { return _to CheckLoadURIStrWithPrincipal(aPrincipal, uri, flags); } \
+  NS_IMETHOD CheckLoadURIStr(const nsACString & from, const nsACString & uri, PRUint32 flags) { return _to CheckLoadURIStr(from, uri, flags); } \
+  NS_IMETHOD CheckFunctionAccess(JSContext * cx, void * funObj, void * targetObj) { return _to CheckFunctionAccess(cx, funObj, targetObj); } \
+  NS_IMETHOD CanExecuteScripts(JSContext * cx, nsIPrincipal *principal, PRBool *_retval) { return _to CanExecuteScripts(cx, principal, _retval); } \
+  NS_IMETHOD GetSubjectPrincipal(nsIPrincipal **_retval) { return _to GetSubjectPrincipal(_retval); } \
+  NS_IMETHOD GetSystemPrincipal(nsIPrincipal **_retval) { return _to GetSystemPrincipal(_retval); } \
+  NS_IMETHOD GetCertificatePrincipal(const nsACString & aCertFingerprint, const nsACString & aSubjectName, const nsACString & aPrettyName, nsISupports *aCert, nsIURI *aURI, nsIPrincipal **_retval) { return _to GetCertificatePrincipal(aCertFingerprint, aSubjectName, aPrettyName, aCert, aURI, _retval); } \
+  NS_IMETHOD GetCodebasePrincipal(nsIURI *aURI, nsIPrincipal **_retval) { return _to GetCodebasePrincipal(aURI, _retval); } \
+  NS_IMETHOD RequestCapability(nsIPrincipal *principal, const char *capability, PRInt16 *_retval) { return _to RequestCapability(principal, capability, _retval); } \
+  NS_IMETHOD IsCapabilityEnabled(const char *capability, PRBool *_retval) { return _to IsCapabilityEnabled(capability, _retval); } \
+  NS_IMETHOD EnableCapability(const char *capability) { return _to EnableCapability(capability); } \
+  NS_IMETHOD RevertCapability(const char *capability) { return _to RevertCapability(capability); } \
+  NS_IMETHOD DisableCapability(const char *capability) { return _to DisableCapability(capability); } \
+  NS_IMETHOD SetCanEnableCapability(const nsACString & certificateFingerprint, const char *capability, PRInt16 canEnable) { return _to SetCanEnableCapability(certificateFingerprint, capability, canEnable); } \
+  NS_IMETHOD GetObjectPrincipal(JSContext * cx, JSObject * obj, nsIPrincipal **_retval) { return _to GetObjectPrincipal(cx, obj, _retval); } \
+  NS_IMETHOD SubjectPrincipalIsSystem(PRBool *_retval) { return _to SubjectPrincipalIsSystem(_retval); } \
+  NS_IMETHOD CheckSameOrigin(JSContext * aJSContext, nsIURI *aTargetURI) { return _to CheckSameOrigin(aJSContext, aTargetURI); } \
+  NS_IMETHOD CheckSameOriginURI(nsIURI *aSourceURI, nsIURI *aTargetURI) { return _to CheckSameOriginURI(aSourceURI, aTargetURI); } \
+  NS_IMETHOD CheckSameOriginPrincipal(nsIPrincipal *aSourcePrincipal, nsIPrincipal *aTargetPrincipal) { return _to CheckSameOriginPrincipal(aSourcePrincipal, aTargetPrincipal); } \
+  NS_IMETHOD GetPrincipalFromContext(JSContext * cx, nsIPrincipal **_retval) { return _to GetPrincipalFromContext(cx, _retval); } \
+  NS_IMETHOD SecurityCompareURIs(nsIURI *aSubjectURI, nsIURI *aObjectURI, PRBool *_retval) { return _to SecurityCompareURIs(aSubjectURI, aObjectURI, _retval); } 
+
+/* Use this macro to declare functions that forward the behavior of this interface to another object in a safe way. */
+#define NS_FORWARD_SAFE_NSISCRIPTSECURITYMANAGERNEWER(_to) \
+  NS_IMETHOD CheckPropertyAccess(JSContext * aJSContext, JSObject * aJSObject, const char *aClassName, jsval aProperty, PRUint32 aAction) { return !_to ? NS_ERROR_NULL_POINTER : _to->CheckPropertyAccess(aJSContext, aJSObject, aClassName, aProperty, aAction); } \
+  NS_IMETHOD CheckConnect(JSContext * aJSContext, nsIURI *aTargetURI, const char *aClassName, const char *aProperty) { return !_to ? NS_ERROR_NULL_POINTER : _to->CheckConnect(aJSContext, aTargetURI, aClassName, aProperty); } \
+  NS_IMETHOD CheckLoadURIFromScript(JSContext * cx, nsIURI *uri) { return !_to ? NS_ERROR_NULL_POINTER : _to->CheckLoadURIFromScript(cx, uri); } \
+  NS_IMETHOD CheckLoadURIWithPrincipal(nsIPrincipal *aPrincipal, nsIURI *uri, PRUint32 flags) { return !_to ? NS_ERROR_NULL_POINTER : _to->CheckLoadURIWithPrincipal(aPrincipal, uri, flags); } \
+  NS_IMETHOD CheckLoadURI(nsIURI *from, nsIURI *uri, PRUint32 flags) { return !_to ? NS_ERROR_NULL_POINTER : _to->CheckLoadURI(from, uri, flags); } \
+  NS_IMETHOD CheckLoadURIStrWithPrincipal(nsIPrincipal *aPrincipal, const nsACString & uri, PRUint32 flags) { return !_to ? NS_ERROR_NULL_POINTER : _to->CheckLoadURIStrWithPrincipal(aPrincipal, uri, flags); } \
+  NS_IMETHOD CheckLoadURIStr(const nsACString & from, const nsACString & uri, PRUint32 flags) { return !_to ? NS_ERROR_NULL_POINTER : _to->CheckLoadURIStr(from, uri, flags); } \
+  NS_IMETHOD CheckFunctionAccess(JSContext * cx, void * funObj, void * targetObj) { return !_to ? NS_ERROR_NULL_POINTER : _to->CheckFunctionAccess(cx, funObj, targetObj); } \
+  NS_IMETHOD CanExecuteScripts(JSContext * cx, nsIPrincipal *principal, PRBool *_retval) { return !_to ? NS_ERROR_NULL_POINTER : _to->CanExecuteScripts(cx, principal, _retval); } \
+  NS_IMETHOD GetSubjectPrincipal(nsIPrincipal **_retval) { return !_to ? NS_ERROR_NULL_POINTER : _to->GetSubjectPrincipal(_retval); } \
+  NS_IMETHOD GetSystemPrincipal(nsIPrincipal **_retval) { return !_to ? NS_ERROR_NULL_POINTER : _to->GetSystemPrincipal(_retval); } \
+  NS_IMETHOD GetCertificatePrincipal(const nsACString & aCertFingerprint, const nsACString & aSubjectName, const nsACString & aPrettyName, nsISupports *aCert, nsIURI *aURI, nsIPrincipal **_retval) { return !_to ? NS_ERROR_NULL_POINTER : _to->GetCertificatePrincipal(aCertFingerprint, aSubjectName, aPrettyName, aCert, aURI, _retval); } \
+  NS_IMETHOD GetCodebasePrincipal(nsIURI *aURI, nsIPrincipal **_retval) { return !_to ? NS_ERROR_NULL_POINTER : _to->GetCodebasePrincipal(aURI, _retval); } \
+  NS_IMETHOD RequestCapability(nsIPrincipal *principal, const char *capability, PRInt16 *_retval) { return !_to ? NS_ERROR_NULL_POINTER : _to->RequestCapability(principal, capability, _retval); } \
+  NS_IMETHOD IsCapabilityEnabled(const char *capability, PRBool *_retval) { return !_to ? NS_ERROR_NULL_POINTER : _to->IsCapabilityEnabled(capability, _retval); } \
+  NS_IMETHOD EnableCapability(const char *capability) { return !_to ? NS_ERROR_NULL_POINTER : _to->EnableCapability(capability); } \
+  NS_IMETHOD RevertCapability(const char *capability) { return !_to ? NS_ERROR_NULL_POINTER : _to->RevertCapability(capability); } \
+  NS_IMETHOD DisableCapability(const char *capability) { return !_to ? NS_ERROR_NULL_POINTER : _to->DisableCapability(capability); } \
+  NS_IMETHOD SetCanEnableCapability(const nsACString & certificateFingerprint, const char *capability, PRInt16 canEnable) { return !_to ? NS_ERROR_NULL_POINTER : _to->SetCanEnableCapability(certificateFingerprint, capability, canEnable); } \
+  NS_IMETHOD GetObjectPrincipal(JSContext * cx, JSObject * obj, nsIPrincipal **_retval) { return !_to ? NS_ERROR_NULL_POINTER : _to->GetObjectPrincipal(cx, obj, _retval); } \
+  NS_IMETHOD SubjectPrincipalIsSystem(PRBool *_retval) { return !_to ? NS_ERROR_NULL_POINTER : _to->SubjectPrincipalIsSystem(_retval); } \
+  NS_IMETHOD CheckSameOrigin(JSContext * aJSContext, nsIURI *aTargetURI) { return !_to ? NS_ERROR_NULL_POINTER : _to->CheckSameOrigin(aJSContext, aTargetURI); } \
+  NS_IMETHOD CheckSameOriginURI(nsIURI *aSourceURI, nsIURI *aTargetURI) { return !_to ? NS_ERROR_NULL_POINTER : _to->CheckSameOriginURI(aSourceURI, aTargetURI); } \
+  NS_IMETHOD CheckSameOriginPrincipal(nsIPrincipal *aSourcePrincipal, nsIPrincipal *aTargetPrincipal) { return !_to ? NS_ERROR_NULL_POINTER : _to->CheckSameOriginPrincipal(aSourcePrincipal, aTargetPrincipal); } \
+  NS_IMETHOD GetPrincipalFromContext(JSContext * cx, nsIPrincipal **_retval) { return !_to ? NS_ERROR_NULL_POINTER : _to->GetPrincipalFromContext(cx, _retval); } \
+  NS_IMETHOD SecurityCompareURIs(nsIURI *aSubjectURI, nsIURI *aObjectURI, PRBool *_retval) { return !_to ? NS_ERROR_NULL_POINTER : _to->SecurityCompareURIs(aSubjectURI, aObjectURI, _retval); } 
+
+#if 0
+/* Use the code below as a template for the implementation class for this interface. */
+
+/* Header file */
+class nsScriptSecurityManager : public nsIScriptSecurityManager
+{
+public:
+  NS_DECL_ISUPPORTS
+  NS_DECL_NSISCRIPTSECURITYMANAGER
+
+  nsScriptSecurityManager();
+
+private:
+  ~nsScriptSecurityManager();
+
+protected:
+  /* additional members */
+};
+
+/* Implementation file */
+NS_IMPL_ISUPPORTS1(nsScriptSecurityManager, nsIScriptSecurityManager)
+
+nsScriptSecurityManager::nsScriptSecurityManager()
+{
+  /* member initializers and constructor code */
+}
+
+nsScriptSecurityManager::~nsScriptSecurityManager()
+{
+  /* destructor code */
+}
+
+/* [noscript] void checkPropertyAccess (in JSContextPtr aJSContext, in JSObjectPtr aJSObject, in string aClassName, in JSVal aProperty, in PRUint32 aAction); */
+NS_IMETHODIMP nsScriptSecurityManager::CheckPropertyAccess(JSContext * aJSContext, JSObject * aJSObject, const char *aClassName, jsval aProperty, PRUint32 aAction)
+{
+    return NS_ERROR_NOT_IMPLEMENTED;
+}
+
+/* [noscript] void checkConnect (in JSContextPtr aJSContext, in nsIURI aTargetURI, in string aClassName, in string aProperty); */
+NS_IMETHODIMP nsScriptSecurityManager::CheckConnect(JSContext * aJSContext, nsIURI *aTargetURI, const char *aClassName, const char *aProperty)
+{
+    return NS_ERROR_NOT_IMPLEMENTED;
+}
+
+/* [noscript] void checkLoadURIFromScript (in JSContextPtr cx, in nsIURI uri); */
+NS_IMETHODIMP nsScriptSecurityManager::CheckLoadURIFromScript(JSContext * cx, nsIURI *uri)
+{
+    return NS_ERROR_NOT_IMPLEMENTED;
+}
+
+/* void checkLoadURIWithPrincipal (in nsIPrincipal aPrincipal, in nsIURI uri, in unsigned long flags); */
+NS_IMETHODIMP nsScriptSecurityManager::CheckLoadURIWithPrincipal(nsIPrincipal *aPrincipal, nsIURI *uri, PRUint32 flags)
+{
+    return NS_ERROR_NOT_IMPLEMENTED;
+}
+
+/* void checkLoadURI (in nsIURI from, in nsIURI uri, in unsigned long flags); */
+NS_IMETHODIMP nsScriptSecurityManager::CheckLoadURI(nsIURI *from, nsIURI *uri, PRUint32 flags)
+{
+    return NS_ERROR_NOT_IMPLEMENTED;
+}
+
+/* void checkLoadURIStrWithPrincipal (in nsIPrincipal aPrincipal, in AUTF8String uri, in unsigned long flags); */
+NS_IMETHODIMP nsScriptSecurityManager::CheckLoadURIStrWithPrincipal(nsIPrincipal *aPrincipal, const nsACString & uri, PRUint32 flags)
+{
+    return NS_ERROR_NOT_IMPLEMENTED;
+}
+
+/* void checkLoadURIStr (in AUTF8String from, in AUTF8String uri, in unsigned long flags); */
+NS_IMETHODIMP nsScriptSecurityManager::CheckLoadURIStr(const nsACString & from, const nsACString & uri, PRUint32 flags)
+{
+    return NS_ERROR_NOT_IMPLEMENTED;
+}
+
+/* [noscript] void checkFunctionAccess (in JSContextPtr cx, in voidPtr funObj, in voidPtr targetObj); */
+NS_IMETHODIMP nsScriptSecurityManager::CheckFunctionAccess(JSContext * cx, void * funObj, void * targetObj)
+{
+    return NS_ERROR_NOT_IMPLEMENTED;
+}
+
+/* [noscript] boolean canExecuteScripts (in JSContextPtr cx, in nsIPrincipal principal); */
+NS_IMETHODIMP nsScriptSecurityManager::CanExecuteScripts(JSContext * cx, nsIPrincipal *principal, PRBool *_retval)
+{
+    return NS_ERROR_NOT_IMPLEMENTED;
+}
+
+/* [noscript] nsIPrincipal getSubjectPrincipal (); */
+NS_IMETHODIMP nsScriptSecurityManager::GetSubjectPrincipal(nsIPrincipal **_retval)
+{
+    return NS_ERROR_NOT_IMPLEMENTED;
+}
+
+/* [noscript] nsIPrincipal getSystemPrincipal (); */
+NS_IMETHODIMP nsScriptSecurityManager::GetSystemPrincipal(nsIPrincipal **_retval)
+{
+    return NS_ERROR_NOT_IMPLEMENTED;
+}
+
+/* [noscript] nsIPrincipal getCertificatePrincipal (in AUTF8String aCertFingerprint, in AUTF8String aSubjectName, in AUTF8String aPrettyName, in nsISupports aCert, in nsIURI aURI); */
+NS_IMETHODIMP nsScriptSecurityManager::GetCertificatePrincipal(const nsACString & aCertFingerprint, const nsACString & aSubjectName, const nsACString & aPrettyName, nsISupports *aCert, nsIURI *aURI, nsIPrincipal **_retval)
+{
+    return NS_ERROR_NOT_IMPLEMENTED;
+}
+
+/* [noscript] nsIPrincipal getCodebasePrincipal (in nsIURI aURI); */
+NS_IMETHODIMP nsScriptSecurityManager::GetCodebasePrincipal(nsIURI *aURI, nsIPrincipal **_retval)
+{
+    return NS_ERROR_NOT_IMPLEMENTED;
+}
+
+/* [noscript] short requestCapability (in nsIPrincipal principal, in string capability); */
+NS_IMETHODIMP nsScriptSecurityManager::RequestCapability(nsIPrincipal *principal, const char *capability, PRInt16 *_retval)
+{
+    return NS_ERROR_NOT_IMPLEMENTED;
+}
+
+/* boolean isCapabilityEnabled (in string capability); */
+NS_IMETHODIMP nsScriptSecurityManager::IsCapabilityEnabled(const char *capability, PRBool *_retval)
+{
+    return NS_ERROR_NOT_IMPLEMENTED;
+}
+
+/* void enableCapability (in string capability); */
+NS_IMETHODIMP nsScriptSecurityManager::EnableCapability(const char *capability)
+{
+    return NS_ERROR_NOT_IMPLEMENTED;
+}
+
+/* void revertCapability (in string capability); */
+NS_IMETHODIMP nsScriptSecurityManager::RevertCapability(const char *capability)
+{
+    return NS_ERROR_NOT_IMPLEMENTED;
+}
+
+/* void disableCapability (in string capability); */
+NS_IMETHODIMP nsScriptSecurityManager::DisableCapability(const char *capability)
+{
+    return NS_ERROR_NOT_IMPLEMENTED;
+}
+
+/* void setCanEnableCapability (in AUTF8String certificateFingerprint, in string capability, in short canEnable); */
+NS_IMETHODIMP nsScriptSecurityManager::SetCanEnableCapability(const nsACString & certificateFingerprint, const char *capability, PRInt16 canEnable)
+{
+    return NS_ERROR_NOT_IMPLEMENTED;
+}
+
+/* [noscript] nsIPrincipal getObjectPrincipal (in JSContextPtr cx, in JSObjectPtr obj); */
+NS_IMETHODIMP nsScriptSecurityManager::GetObjectPrincipal(JSContext * cx, JSObject * obj, nsIPrincipal **_retval)
+{
+    return NS_ERROR_NOT_IMPLEMENTED;
+}
+
+/* [noscript] boolean subjectPrincipalIsSystem (); */
+NS_IMETHODIMP nsScriptSecurityManager::SubjectPrincipalIsSystem(PRBool *_retval)
+{
+    return NS_ERROR_NOT_IMPLEMENTED;
+}
+
+/* [noscript] void checkSameOrigin (in JSContextPtr aJSContext, in nsIURI aTargetURI); */
+NS_IMETHODIMP nsScriptSecurityManager::CheckSameOrigin(JSContext * aJSContext, nsIURI *aTargetURI)
+{
+    return NS_ERROR_NOT_IMPLEMENTED;
+}
+
+/* void checkSameOriginURI (in nsIURI aSourceURI, in nsIURI aTargetURI); */
+NS_IMETHODIMP nsScriptSecurityManager::CheckSameOriginURI(nsIURI *aSourceURI, nsIURI *aTargetURI)
+{
+    return NS_ERROR_NOT_IMPLEMENTED;
+}
+
+/* void checkSameOriginPrincipal (in nsIPrincipal aSourcePrincipal, in nsIPrincipal aTargetPrincipal); */
+NS_IMETHODIMP nsScriptSecurityManager::CheckSameOriginPrincipal(nsIPrincipal *aSourcePrincipal, nsIPrincipal *aTargetPrincipal)
+{
+    return NS_ERROR_NOT_IMPLEMENTED;
+}
+
+/* [noscript] nsIPrincipal getPrincipalFromContext (in JSContextPtr cx); */
+NS_IMETHODIMP nsScriptSecurityManager::GetPrincipalFromContext(JSContext * cx, nsIPrincipal **_retval)
+{
+    return NS_ERROR_NOT_IMPLEMENTED;
+}
+
+/* [noscript] boolean securityCompareURIs (in nsIURI aSubjectURI, in nsIURI aObjectURI); */
+NS_IMETHODIMP nsScriptSecurityManager::SecurityCompareURIs(nsIURI *aSubjectURI, nsIURI *aObjectURI, PRBool *_retval)
+{
+    return NS_ERROR_NOT_IMPLEMENTED;
+}
+
+/* End of implementation class template. */
+#endif
+
+#define NS_SCRIPTSECURITYMANAGERNEWER_CONTRACTID "@mozilla.org/scriptsecuritymanager;1"
+#define NS_SCRIPTSECURITYMANAGERNEWER_CLASSNAME "scriptsecuritymanager"
+
+#endif /* __gen_nsIScriptSecurityManagerNewer_h__ */
diff -U 10 -r -N old/plugin/oji/MRJCarbon/plugin/Source/nsIScriptSecurityManagerNewest.h new/plugin/oji/MRJCarbon/plugin/Source/nsIScriptSecurityManagerNewest.h
--- old/plugin/oji/MRJCarbon/plugin/Source/nsIScriptSecurityManagerNewest.h	1969-12-31 18:00:00.000000000 -0600
+++ new/plugin/oji/MRJCarbon/plugin/Source/nsIScriptSecurityManagerNewest.h	2008-04-11 16:07:11.000000000 -0500
@@ -0,0 +1,573 @@
+/*
+ * DO NOT EDIT.  THIS FILE IS GENERATED FROM /usr/local/src/Mozilla/cvs/mozilla/caps/idl/nsIScriptSecurityManager.idl
+ */
+
+#ifndef __gen_nsIScriptSecurityManagerNewest_h__
+#define __gen_nsIScriptSecurityManagerNewest_h__
+
+
+#ifndef __gen_nsISupports_h__
+#include "nsISupports.h"
+#endif
+
+#ifndef __gen_nsIPrincipal_h__
+#include "nsIPrincipal.h"
+#endif
+
+#ifndef __gen_nsIXPCSecurityManager_h__
+#include "nsIXPCSecurityManager.h"
+#endif
+
+/* For IDL files that don't want to include root IDL files. */
+#ifndef NS_NO_VTABLE
+#define NS_NO_VTABLE
+#endif
+class nsIURI; /* forward declaration */
+
+class nsIChannel; /* forward declaration */
+
+
+/* starting interface:    nsIScriptSecurityManager */
+#define NS_ISCRIPTSECURITYMANAGERNEWESTALT1_IID_STR "e74487fd-98ef-48d1-b973-3f2938f04e8e"
+
+#ifndef NS_ISCRIPTSECURITYMANAGERNEWESTALT1_IID
+#define NS_ISCRIPTSECURITYMANAGERNEWESTALT1_IID \
+  {0xe74487fd, 0x98ef, 0x48d1, \
+    { 0xb9, 0x73, 0x3f, 0x29, 0x38, 0xf0, 0x4e, 0x8e }}
+#endif
+
+#ifndef NS_SCRIPTABLE
+#define NS_SCRIPTABLE
+#endif
+
+class NS_NO_VTABLE NS_SCRIPTABLE nsIScriptSecurityManagerNewest : public nsIXPCSecurityManager {
+ public: 
+
+#ifdef NS_DECLARE_STATIC_IID_ACCESSOR
+  NS_DECLARE_STATIC_IID_ACCESSOR(NS_ISCRIPTSECURITYMANAGERNEWESTALT1_IID)
+#else
+  NS_DEFINE_STATIC_IID_ACCESSOR(NS_ISCRIPTSECURITYMANAGERNEWESTALT1_IID)
+#endif
+
+  /**
+     * Checks whether the running script is allowed to access aProperty.
+     */
+  /* [noscript] void checkPropertyAccess (in JSContextPtr aJSContext, in JSObjectPtr aJSObject, in string aClassName, in JSVal aProperty, in PRUint32 aAction); */
+  NS_IMETHOD CheckPropertyAccess(JSContext * aJSContext, JSObject * aJSObject, const char *aClassName, jsval aProperty, PRUint32 aAction) = 0;
+
+  /**
+     * Check that the script currently running in context "cx" can load "uri".
+     *
+     * Will return error code NS_ERROR_DOM_BAD_URI if the load request 
+     * should be denied.
+     *
+     * @param cx the JSContext of the script causing the load
+     * @param uri the URI that is being loaded
+     */
+  /* [noscript] void checkLoadURIFromScript (in JSContextPtr cx, in nsIURI uri); */
+  NS_IMETHOD CheckLoadURIFromScript(JSContext * cx, nsIURI *uri) = 0;
+
+  /**
+     * Default CheckLoadURI permissions
+     */
+  enum { STANDARD = 0U };
+
+  enum { LOAD_IS_AUTOMATIC_DOCUMENT_REPLACEMENT = 1U };
+
+  enum { ALLOW_CHROME = 2U };
+
+  enum { DISALLOW_INHERIT_PRINCIPAL = 4U };
+
+  enum { DISALLOW_SCRIPT_OR_DATA = 4U };
+
+  enum { DISALLOW_SCRIPT = 8U };
+
+  /**
+     * Check that content with principal aPrincipal can load "uri".
+     *
+     * Will return error code NS_ERROR_DOM_BAD_URI if the load request 
+     * should be denied.
+     *
+     * @param aPrincipal the principal identifying the actor causing the load
+     * @param uri the URI that is being loaded
+     * @param flags the permission set, see above
+     */
+  /* void checkLoadURIWithPrincipal (in nsIPrincipal aPrincipal, in nsIURI uri, in unsigned long flags); */
+  NS_SCRIPTABLE NS_IMETHOD CheckLoadURIWithPrincipal(nsIPrincipal *aPrincipal, nsIURI *uri, PRUint32 flags) = 0;
+
+  /**
+     * Check that content from "from" can load "uri".
+     *
+     * Will return error code NS_ERROR_DOM_BAD_URI if the load request 
+     * should be denied.
+     *
+     * @param from the URI causing the load
+     * @param uri the URI that is being loaded
+     * @param flags the permission set, see above
+     *
+     * @deprecated Use checkLoadURIWithPrincipal instead of this function.
+     */
+  /* void checkLoadURI (in nsIURI from, in nsIURI uri, in unsigned long flags); */
+  NS_SCRIPTABLE NS_IMETHOD CheckLoadURI(nsIURI *from, nsIURI *uri, PRUint32 flags) = 0;
+
+  /**
+     * Similar to checkLoadURIWithPrincipal but there are two differences:
+     *
+     * 1) The URI is a string, not a URI object.
+     * 2) This function assumes that the URI may still be subject to fixup (and
+     * hence will check whether fixed-up versions of the URI are allowed to
+     * load as well); if any of the versions of this URI is not allowed, this
+     * function will return error code NS_ERROR_DOM_BAD_URI.
+     */
+  /* void checkLoadURIStrWithPrincipal (in nsIPrincipal aPrincipal, in AUTF8String uri, in unsigned long flags); */
+  NS_SCRIPTABLE NS_IMETHOD CheckLoadURIStrWithPrincipal(nsIPrincipal *aPrincipal, const nsACString & uri, PRUint32 flags) = 0;
+
+  /**
+     * Same as CheckLoadURI but takes string arguments for ease of use
+     * by scripts
+     *
+     * @deprecated Use checkLoadURIStrWithPrincipal instead of this function.
+     */
+  /* void checkLoadURIStr (in AUTF8String from, in AUTF8String uri, in unsigned long flags); */
+  NS_SCRIPTABLE NS_IMETHOD CheckLoadURIStr(const nsACString & from, const nsACString & uri, PRUint32 flags) = 0;
+
+  /**
+     * Check that the function 'funObj' is allowed to run on 'targetObj'
+     *
+     * Will return error code NS_ERROR_DOM_SECURITY_ERR if the function
+     * should not run
+     *
+     * @param cx The current active JavaScript context.
+     * @param funObj The function trying to run..
+     * @param targetObj The object the function will run on.
+     */
+  /* [noscript] void checkFunctionAccess (in JSContextPtr cx, in voidPtr funObj, in voidPtr targetObj); */
+  NS_IMETHOD CheckFunctionAccess(JSContext * cx, void * funObj, void * targetObj) = 0;
+
+  /**
+     * Return true if content from the given principal is allowed to
+     * execute scripts.
+     */
+  /* [noscript] boolean canExecuteScripts (in JSContextPtr cx, in nsIPrincipal principal); */
+  NS_IMETHOD CanExecuteScripts(JSContext * cx, nsIPrincipal *principal, PRBool *_retval) = 0;
+
+  /**
+     * Return the principal of the innermost frame of the currently 
+     * executing script. Will return null if there is no script 
+     * currently executing.
+     */
+  /* [noscript] nsIPrincipal getSubjectPrincipal (); */
+  NS_IMETHOD GetSubjectPrincipal(nsIPrincipal **_retval) = 0;
+
+  /**
+     * Return the all-powerful system principal.
+     */
+  /* [noscript] nsIPrincipal getSystemPrincipal (); */
+  NS_IMETHOD GetSystemPrincipal(nsIPrincipal **_retval) = 0;
+
+  /**
+     * Return a principal with the specified certificate fingerprint, subject
+     * name (the full name or concatenated set of names of the entity
+     * represented by the certificate), pretty name, certificate, and
+     * codebase URI.  The certificate fingerprint and subject name MUST be
+     * nonempty; otherwise an error will be thrown.  Similarly, aCert must
+     * not be null.
+     */
+  /* [noscript] nsIPrincipal getCertificatePrincipal (in AUTF8String aCertFingerprint, in AUTF8String aSubjectName, in AUTF8String aPrettyName, in nsISupports aCert, in nsIURI aURI); */
+  NS_IMETHOD GetCertificatePrincipal(const nsACString & aCertFingerprint, const nsACString & aSubjectName, const nsACString & aPrettyName, nsISupports *aCert, nsIURI *aURI, nsIPrincipal **_retval) = 0;
+
+  /**
+     * Return a principal that has the same origin as aURI.
+     */
+  /* nsIPrincipal getCodebasePrincipal (in nsIURI aURI); */
+  NS_SCRIPTABLE NS_IMETHOD GetCodebasePrincipal(nsIURI *aURI, nsIPrincipal **_retval) = 0;
+
+  /**
+     * Request that 'capability' can be enabled by scripts or applets
+     * running with 'principal'. Will prompt user if
+     * necessary. Returns nsIPrincipal::ENABLE_GRANTED or
+     * nsIPrincipal::ENABLE_DENIED based on user's choice.
+     */
+  /* [noscript] short requestCapability (in nsIPrincipal principal, in string capability); */
+  NS_IMETHOD RequestCapability(nsIPrincipal *principal, const char *capability, PRInt16 *_retval) = 0;
+
+  /**
+     * Return true if the currently executing script has 'capability' enabled.
+     */
+  /* boolean isCapabilityEnabled (in string capability); */
+  NS_SCRIPTABLE NS_IMETHOD IsCapabilityEnabled(const char *capability, PRBool *_retval) = 0;
+
+  /**
+     * Enable 'capability' in the innermost frame of the currently executing
+     * script.
+     */
+  /* void enableCapability (in string capability); */
+  NS_SCRIPTABLE NS_IMETHOD EnableCapability(const char *capability) = 0;
+
+  /**
+     * Remove 'capability' from the innermost frame of the currently
+     * executing script. Any setting of 'capability' from enclosing
+     * frames thus comes into effect.
+     */
+  /* void revertCapability (in string capability); */
+  NS_SCRIPTABLE NS_IMETHOD RevertCapability(const char *capability) = 0;
+
+  /**
+     * Disable 'capability' in the innermost frame of the currently executing
+     * script.
+     */
+  /* void disableCapability (in string capability); */
+  NS_SCRIPTABLE NS_IMETHOD DisableCapability(const char *capability) = 0;
+
+  /**
+     * Allow 'certificateID' to enable 'capability.' Can only be performed
+     * by code signed by the system certificate.
+     */
+  /* void setCanEnableCapability (in AUTF8String certificateFingerprint, in string capability, in short canEnable); */
+  NS_SCRIPTABLE NS_IMETHOD SetCanEnableCapability(const nsACString & certificateFingerprint, const char *capability, PRInt16 canEnable) = 0;
+
+  /**
+     * Return the principal of the specified object in the specified context.
+     */
+  /* [noscript] nsIPrincipal getObjectPrincipal (in JSContextPtr cx, in JSObjectPtr obj); */
+  NS_IMETHOD GetObjectPrincipal(JSContext * cx, JSObject * obj, nsIPrincipal **_retval) = 0;
+
+  /**
+     * Returns true if the principal of the currently running script is the
+     * system principal, false otherwise.
+     */
+  /* [noscript] boolean subjectPrincipalIsSystem (); */
+  NS_IMETHOD SubjectPrincipalIsSystem(PRBool *_retval) = 0;
+
+  /**
+     * Returns OK if aJSContext and target have the same "origin"
+     * (scheme, host, and port).
+     */
+  /* [noscript] void checkSameOrigin (in JSContextPtr aJSContext, in nsIURI aTargetURI); */
+  NS_IMETHOD CheckSameOrigin(JSContext * aJSContext, nsIURI *aTargetURI) = 0;
+
+  /**
+     * Returns OK if aSourceURI and target have the same "origin"
+     * (scheme, host, and port).
+     * ReportError flag suppresses error reports for functions that
+     * don't need reporting.
+     */
+  /* void checkSameOriginURI (in nsIURI aSourceURI, in nsIURI aTargetURI, in boolean reportError); */
+  NS_SCRIPTABLE NS_IMETHOD CheckSameOriginURI(nsIURI *aSourceURI, nsIURI *aTargetURI, PRBool reportError) = 0;
+
+  /**
+     * Returns the principal of the global object of the given context, or null
+     * if no global or no principal.
+     */
+  /* [noscript] nsIPrincipal getPrincipalFromContext (in JSContextPtr cx); */
+  NS_IMETHOD GetPrincipalFromContext(JSContext * cx, nsIPrincipal **_retval) = 0;
+
+  /**
+     * Get the principal for the given channel.  This will typically be the
+     * channel owner if there is one, and the codebase principal for the
+     * channel's URI otherwise.  aChannel must not be null.
+     */
+  /* nsIPrincipal getChannelPrincipal (in nsIChannel aChannel); */
+  NS_SCRIPTABLE NS_IMETHOD GetChannelPrincipal(nsIChannel *aChannel, nsIPrincipal **_retval) = 0;
+
+  /**
+     * Check whether a given principal is a system principal.  This allows us
+     * to avoid handing back the system principal to script while allowing
+     * script to check whether a given principal is system.
+     */
+  /* boolean isSystemPrincipal (in nsIPrincipal aPrincipal); */
+  NS_SCRIPTABLE NS_IMETHOD IsSystemPrincipal(nsIPrincipal *aPrincipal, PRBool *_retval) = 0;
+
+  /**
+     * Same as getSubjectPrincipal(), only faster. cx must *never* be
+     * passed null, and it must be the context on the top of the
+     * context stack. Does *not* reference count the returned
+     * principal.
+     */
+  /* [noscript, notxpcom] nsIPrincipal getCxSubjectPrincipal (in JSContextPtr cx); */
+  NS_IMETHOD_(nsIPrincipal *) GetCxSubjectPrincipal(JSContext * cx) = 0;
+
+};
+
+/* Use this macro when declaring classes that implement this interface. */
+#define NS_DECL_NSISCRIPTSECURITYMANAGERNEWEST \
+  NS_IMETHOD CheckPropertyAccess(JSContext * aJSContext, JSObject * aJSObject, const char *aClassName, jsval aProperty, PRUint32 aAction); \
+  NS_IMETHOD CheckLoadURIFromScript(JSContext * cx, nsIURI *uri); \
+  NS_SCRIPTABLE NS_IMETHOD CheckLoadURIWithPrincipal(nsIPrincipal *aPrincipal, nsIURI *uri, PRUint32 flags); \
+  NS_SCRIPTABLE NS_IMETHOD CheckLoadURI(nsIURI *from, nsIURI *uri, PRUint32 flags); \
+  NS_SCRIPTABLE NS_IMETHOD CheckLoadURIStrWithPrincipal(nsIPrincipal *aPrincipal, const nsACString & uri, PRUint32 flags); \
+  NS_SCRIPTABLE NS_IMETHOD CheckLoadURIStr(const nsACString & from, const nsACString & uri, PRUint32 flags); \
+  NS_IMETHOD CheckFunctionAccess(JSContext * cx, void * funObj, void * targetObj); \
+  NS_IMETHOD CanExecuteScripts(JSContext * cx, nsIPrincipal *principal, PRBool *_retval); \
+  NS_IMETHOD GetSubjectPrincipal(nsIPrincipal **_retval); \
+  NS_IMETHOD GetSystemPrincipal(nsIPrincipal **_retval); \
+  NS_IMETHOD GetCertificatePrincipal(const nsACString & aCertFingerprint, const nsACString & aSubjectName, const nsACString & aPrettyName, nsISupports *aCert, nsIURI *aURI, nsIPrincipal **_retval); \
+  NS_SCRIPTABLE NS_IMETHOD GetCodebasePrincipal(nsIURI *aURI, nsIPrincipal **_retval); \
+  NS_IMETHOD RequestCapability(nsIPrincipal *principal, const char *capability, PRInt16 *_retval); \
+  NS_SCRIPTABLE NS_IMETHOD IsCapabilityEnabled(const char *capability, PRBool *_retval); \
+  NS_SCRIPTABLE NS_IMETHOD EnableCapability(const char *capability); \
+  NS_SCRIPTABLE NS_IMETHOD RevertCapability(const char *capability); \
+  NS_SCRIPTABLE NS_IMETHOD DisableCapability(const char *capability); \
+  NS_SCRIPTABLE NS_IMETHOD SetCanEnableCapability(const nsACString & certificateFingerprint, const char *capability, PRInt16 canEnable); \
+  NS_IMETHOD GetObjectPrincipal(JSContext * cx, JSObject * obj, nsIPrincipal **_retval); \
+  NS_IMETHOD SubjectPrincipalIsSystem(PRBool *_retval); \
+  NS_IMETHOD CheckSameOrigin(JSContext * aJSContext, nsIURI *aTargetURI); \
+  NS_SCRIPTABLE NS_IMETHOD CheckSameOriginURI(nsIURI *aSourceURI, nsIURI *aTargetURI, PRBool reportError); \
+  NS_IMETHOD GetPrincipalFromContext(JSContext * cx, nsIPrincipal **_retval); \
+  NS_SCRIPTABLE NS_IMETHOD GetChannelPrincipal(nsIChannel *aChannel, nsIPrincipal **_retval); \
+  NS_SCRIPTABLE NS_IMETHOD IsSystemPrincipal(nsIPrincipal *aPrincipal, PRBool *_retval); \
+  NS_IMETHOD_(nsIPrincipal *) GetCxSubjectPrincipal(JSContext * cx); 
+
+/* Use this macro to declare functions that forward the behavior of this interface to another object. */
+#define NS_FORWARD_NSISCRIPTSECURITYMANAGERNEWEST(_to) \
+  NS_IMETHOD CheckPropertyAccess(JSContext * aJSContext, JSObject * aJSObject, const char *aClassName, jsval aProperty, PRUint32 aAction) { return _to CheckPropertyAccess(aJSContext, aJSObject, aClassName, aProperty, aAction); } \
+  NS_IMETHOD CheckLoadURIFromScript(JSContext * cx, nsIURI *uri) { return _to CheckLoadURIFromScript(cx, uri); } \
+  NS_SCRIPTABLE NS_IMETHOD CheckLoadURIWithPrincipal(nsIPrincipal *aPrincipal, nsIURI *uri, PRUint32 flags) { return _to CheckLoadURIWithPrincipal(aPrincipal, uri, flags); } \
+  NS_SCRIPTABLE NS_IMETHOD CheckLoadURI(nsIURI *from, nsIURI *uri, PRUint32 flags) { return _to CheckLoadURI(from, uri, flags); } \
+  NS_SCRIPTABLE NS_IMETHOD CheckLoadURIStrWithPrincipal(nsIPrincipal *aPrincipal, const nsACString & uri, PRUint32 flags) { return _to CheckLoadURIStrWithPrincipal(aPrincipal, uri, flags); } \
+  NS_SCRIPTABLE NS_IMETHOD CheckLoadURIStr(const nsACString & from, const nsACString & uri, PRUint32 flags) { return _to CheckLoadURIStr(from, uri, flags); } \
+  NS_IMETHOD CheckFunctionAccess(JSContext * cx, void * funObj, void * targetObj) { return _to CheckFunctionAccess(cx, funObj, targetObj); } \
+  NS_IMETHOD CanExecuteScripts(JSContext * cx, nsIPrincipal *principal, PRBool *_retval) { return _to CanExecuteScripts(cx, principal, _retval); } \
+  NS_IMETHOD GetSubjectPrincipal(nsIPrincipal **_retval) { return _to GetSubjectPrincipal(_retval); } \
+  NS_IMETHOD GetSystemPrincipal(nsIPrincipal **_retval) { return _to GetSystemPrincipal(_retval); } \
+  NS_IMETHOD GetCertificatePrincipal(const nsACString & aCertFingerprint, const nsACString & aSubjectName, const nsACString & aPrettyName, nsISupports *aCert, nsIURI *aURI, nsIPrincipal **_retval) { return _to GetCertificatePrincipal(aCertFingerprint, aSubjectName, aPrettyName, aCert, aURI, _retval); } \
+  NS_SCRIPTABLE NS_IMETHOD GetCodebasePrincipal(nsIURI *aURI, nsIPrincipal **_retval) { return _to GetCodebasePrincipal(aURI, _retval); } \
+  NS_IMETHOD RequestCapability(nsIPrincipal *principal, const char *capability, PRInt16 *_retval) { return _to RequestCapability(principal, capability, _retval); } \
+  NS_SCRIPTABLE NS_IMETHOD IsCapabilityEnabled(const char *capability, PRBool *_retval) { return _to IsCapabilityEnabled(capability, _retval); } \
+  NS_SCRIPTABLE NS_IMETHOD EnableCapability(const char *capability) { return _to EnableCapability(capability); } \
+  NS_SCRIPTABLE NS_IMETHOD RevertCapability(const char *capability) { return _to RevertCapability(capability); } \
+  NS_SCRIPTABLE NS_IMETHOD DisableCapability(const char *capability) { return _to DisableCapability(capability); } \
+  NS_SCRIPTABLE NS_IMETHOD SetCanEnableCapability(const nsACString & certificateFingerprint, const char *capability, PRInt16 canEnable) { return _to SetCanEnableCapability(certificateFingerprint, capability, canEnable); } \
+  NS_IMETHOD GetObjectPrincipal(JSContext * cx, JSObject * obj, nsIPrincipal **_retval) { return _to GetObjectPrincipal(cx, obj, _retval); } \
+  NS_IMETHOD SubjectPrincipalIsSystem(PRBool *_retval) { return _to SubjectPrincipalIsSystem(_retval); } \
+  NS_IMETHOD CheckSameOrigin(JSContext * aJSContext, nsIURI *aTargetURI) { return _to CheckSameOrigin(aJSContext, aTargetURI); } \
+  NS_SCRIPTABLE NS_IMETHOD CheckSameOriginURI(nsIURI *aSourceURI, nsIURI *aTargetURI, PRBool reportError) { return _to CheckSameOriginURI(aSourceURI, aTargetURI, reportError); } \
+  NS_IMETHOD GetPrincipalFromContext(JSContext * cx, nsIPrincipal **_retval) { return _to GetPrincipalFromContext(cx, _retval); } \
+  NS_SCRIPTABLE NS_IMETHOD GetChannelPrincipal(nsIChannel *aChannel, nsIPrincipal **_retval) { return _to GetChannelPrincipal(aChannel, _retval); } \
+  NS_SCRIPTABLE NS_IMETHOD IsSystemPrincipal(nsIPrincipal *aPrincipal, PRBool *_retval) { return _to IsSystemPrincipal(aPrincipal, _retval); } \
+  NS_IMETHOD_(nsIPrincipal *) GetCxSubjectPrincipal(JSContext * cx) { return _to GetCxSubjectPrincipal(cx); } 
+
+/* Use this macro to declare functions that forward the behavior of this interface to another object in a safe way. */
+#define NS_FORWARD_SAFE_NSISCRIPTSECURITYMANAGERNEWEST(_to) \
+  NS_IMETHOD CheckPropertyAccess(JSContext * aJSContext, JSObject * aJSObject, const char *aClassName, jsval aProperty, PRUint32 aAction) { return !_to ? NS_ERROR_NULL_POINTER : _to->CheckPropertyAccess(aJSContext, aJSObject, aClassName, aProperty, aAction); } \
+  NS_IMETHOD CheckLoadURIFromScript(JSContext * cx, nsIURI *uri) { return !_to ? NS_ERROR_NULL_POINTER : _to->CheckLoadURIFromScript(cx, uri); } \
+  NS_SCRIPTABLE NS_IMETHOD CheckLoadURIWithPrincipal(nsIPrincipal *aPrincipal, nsIURI *uri, PRUint32 flags) { return !_to ? NS_ERROR_NULL_POINTER : _to->CheckLoadURIWithPrincipal(aPrincipal, uri, flags); } \
+  NS_SCRIPTABLE NS_IMETHOD CheckLoadURI(nsIURI *from, nsIURI *uri, PRUint32 flags) { return !_to ? NS_ERROR_NULL_POINTER : _to->CheckLoadURI(from, uri, flags); } \
+  NS_SCRIPTABLE NS_IMETHOD CheckLoadURIStrWithPrincipal(nsIPrincipal *aPrincipal, const nsACString & uri, PRUint32 flags) { return !_to ? NS_ERROR_NULL_POINTER : _to->CheckLoadURIStrWithPrincipal(aPrincipal, uri, flags); } \
+  NS_SCRIPTABLE NS_IMETHOD CheckLoadURIStr(const nsACString & from, const nsACString & uri, PRUint32 flags) { return !_to ? NS_ERROR_NULL_POINTER : _to->CheckLoadURIStr(from, uri, flags); } \
+  NS_IMETHOD CheckFunctionAccess(JSContext * cx, void * funObj, void * targetObj) { return !_to ? NS_ERROR_NULL_POINTER : _to->CheckFunctionAccess(cx, funObj, targetObj); } \
+  NS_IMETHOD CanExecuteScripts(JSContext * cx, nsIPrincipal *principal, PRBool *_retval) { return !_to ? NS_ERROR_NULL_POINTER : _to->CanExecuteScripts(cx, principal, _retval); } \
+  NS_IMETHOD GetSubjectPrincipal(nsIPrincipal **_retval) { return !_to ? NS_ERROR_NULL_POINTER : _to->GetSubjectPrincipal(_retval); } \
+  NS_IMETHOD GetSystemPrincipal(nsIPrincipal **_retval) { return !_to ? NS_ERROR_NULL_POINTER : _to->GetSystemPrincipal(_retval); } \
+  NS_IMETHOD GetCertificatePrincipal(const nsACString & aCertFingerprint, const nsACString & aSubjectName, const nsACString & aPrettyName, nsISupports *aCert, nsIURI *aURI, nsIPrincipal **_retval) { return !_to ? NS_ERROR_NULL_POINTER : _to->GetCertificatePrincipal(aCertFingerprint, aSubjectName, aPrettyName, aCert, aURI, _retval); } \
+  NS_SCRIPTABLE NS_IMETHOD GetCodebasePrincipal(nsIURI *aURI, nsIPrincipal **_retval) { return !_to ? NS_ERROR_NULL_POINTER : _to->GetCodebasePrincipal(aURI, _retval); } \
+  NS_IMETHOD RequestCapability(nsIPrincipal *principal, const char *capability, PRInt16 *_retval) { return !_to ? NS_ERROR_NULL_POINTER : _to->RequestCapability(principal, capability, _retval); } \
+  NS_SCRIPTABLE NS_IMETHOD IsCapabilityEnabled(const char *capability, PRBool *_retval) { return !_to ? NS_ERROR_NULL_POINTER : _to->IsCapabilityEnabled(capability, _retval); } \
+  NS_SCRIPTABLE NS_IMETHOD EnableCapability(const char *capability) { return !_to ? NS_ERROR_NULL_POINTER : _to->EnableCapability(capability); } \
+  NS_SCRIPTABLE NS_IMETHOD RevertCapability(const char *capability) { return !_to ? NS_ERROR_NULL_POINTER : _to->RevertCapability(capability); } \
+  NS_SCRIPTABLE NS_IMETHOD DisableCapability(const char *capability) { return !_to ? NS_ERROR_NULL_POINTER : _to->DisableCapability(capability); } \
+  NS_SCRIPTABLE NS_IMETHOD SetCanEnableCapability(const nsACString & certificateFingerprint, const char *capability, PRInt16 canEnable) { return !_to ? NS_ERROR_NULL_POINTER : _to->SetCanEnableCapability(certificateFingerprint, capability, canEnable); } \
+  NS_IMETHOD GetObjectPrincipal(JSContext * cx, JSObject * obj, nsIPrincipal **_retval) { return !_to ? NS_ERROR_NULL_POINTER : _to->GetObjectPrincipal(cx, obj, _retval); } \
+  NS_IMETHOD SubjectPrincipalIsSystem(PRBool *_retval) { return !_to ? NS_ERROR_NULL_POINTER : _to->SubjectPrincipalIsSystem(_retval); } \
+  NS_IMETHOD CheckSameOrigin(JSContext * aJSContext, nsIURI *aTargetURI) { return !_to ? NS_ERROR_NULL_POINTER : _to->CheckSameOrigin(aJSContext, aTargetURI); } \
+  NS_SCRIPTABLE NS_IMETHOD CheckSameOriginURI(nsIURI *aSourceURI, nsIURI *aTargetURI, PRBool reportError) { return !_to ? NS_ERROR_NULL_POINTER : _to->CheckSameOriginURI(aSourceURI, aTargetURI, reportError); } \
+  NS_IMETHOD GetPrincipalFromContext(JSContext * cx, nsIPrincipal **_retval) { return !_to ? NS_ERROR_NULL_POINTER : _to->GetPrincipalFromContext(cx, _retval); } \
+  NS_SCRIPTABLE NS_IMETHOD GetChannelPrincipal(nsIChannel *aChannel, nsIPrincipal **_retval) { return !_to ? NS_ERROR_NULL_POINTER : _to->GetChannelPrincipal(aChannel, _retval); } \
+  NS_SCRIPTABLE NS_IMETHOD IsSystemPrincipal(nsIPrincipal *aPrincipal, PRBool *_retval) { return !_to ? NS_ERROR_NULL_POINTER : _to->IsSystemPrincipal(aPrincipal, _retval); } \
+  NS_IMETHOD_(nsIPrincipal *) GetCxSubjectPrincipal(JSContext * cx) { return !_to ? NS_ERROR_NULL_POINTER : _to->GetCxSubjectPrincipal(cx); } 
+
+#if 0
+/* Use the code below as a template for the implementation class for this interface. */
+
+/* Header file */
+class nsScriptSecurityManager : public nsIScriptSecurityManager
+{
+public:
+  NS_DECL_ISUPPORTS
+  NS_DECL_NSISCRIPTSECURITYMANAGER
+
+  nsScriptSecurityManager();
+
+private:
+  ~nsScriptSecurityManager();
+
+protected:
+  /* additional members */
+};
+
+/* Implementation file */
+NS_IMPL_ISUPPORTS1(nsScriptSecurityManager, nsIScriptSecurityManager)
+
+nsScriptSecurityManager::nsScriptSecurityManager()
+{
+  /* member initializers and constructor code */
+}
+
+nsScriptSecurityManager::~nsScriptSecurityManager()
+{
+  /* destructor code */
+}
+
+/* [noscript] void checkPropertyAccess (in JSContextPtr aJSContext, in JSObjectPtr aJSObject, in string aClassName, in JSVal aProperty, in PRUint32 aAction); */
+NS_IMETHODIMP nsScriptSecurityManager::CheckPropertyAccess(JSContext * aJSContext, JSObject * aJSObject, const char *aClassName, jsval aProperty, PRUint32 aAction)
+{
+    return NS_ERROR_NOT_IMPLEMENTED;
+}
+
+/* [noscript] void checkLoadURIFromScript (in JSContextPtr cx, in nsIURI uri); */
+NS_IMETHODIMP nsScriptSecurityManager::CheckLoadURIFromScript(JSContext * cx, nsIURI *uri)
+{
+    return NS_ERROR_NOT_IMPLEMENTED;
+}
+
+/* void checkLoadURIWithPrincipal (in nsIPrincipal aPrincipal, in nsIURI uri, in unsigned long flags); */
+NS_IMETHODIMP nsScriptSecurityManager::CheckLoadURIWithPrincipal(nsIPrincipal *aPrincipal, nsIURI *uri, PRUint32 flags)
+{
+    return NS_ERROR_NOT_IMPLEMENTED;
+}
+
+/* void checkLoadURI (in nsIURI from, in nsIURI uri, in unsigned long flags); */
+NS_IMETHODIMP nsScriptSecurityManager::CheckLoadURI(nsIURI *from, nsIURI *uri, PRUint32 flags)
+{
+    return NS_ERROR_NOT_IMPLEMENTED;
+}
+
+/* void checkLoadURIStrWithPrincipal (in nsIPrincipal aPrincipal, in AUTF8String uri, in unsigned long flags); */
+NS_IMETHODIMP nsScriptSecurityManager::CheckLoadURIStrWithPrincipal(nsIPrincipal *aPrincipal, const nsACString & uri, PRUint32 flags)
+{
+    return NS_ERROR_NOT_IMPLEMENTED;
+}
+
+/* void checkLoadURIStr (in AUTF8String from, in AUTF8String uri, in unsigned long flags); */
+NS_IMETHODIMP nsScriptSecurityManager::CheckLoadURIStr(const nsACString & from, const nsACString & uri, PRUint32 flags)
+{
+    return NS_ERROR_NOT_IMPLEMENTED;
+}
+
+/* [noscript] void checkFunctionAccess (in JSContextPtr cx, in voidPtr funObj, in voidPtr targetObj); */
+NS_IMETHODIMP nsScriptSecurityManager::CheckFunctionAccess(JSContext * cx, void * funObj, void * targetObj)
+{
+    return NS_ERROR_NOT_IMPLEMENTED;
+}
+
+/* [noscript] boolean canExecuteScripts (in JSContextPtr cx, in nsIPrincipal principal); */
+NS_IMETHODIMP nsScriptSecurityManager::CanExecuteScripts(JSContext * cx, nsIPrincipal *principal, PRBool *_retval)
+{
+    return NS_ERROR_NOT_IMPLEMENTED;
+}
+
+/* [noscript] nsIPrincipal getSubjectPrincipal (); */
+NS_IMETHODIMP nsScriptSecurityManager::GetSubjectPrincipal(nsIPrincipal **_retval)
+{
+    return NS_ERROR_NOT_IMPLEMENTED;
+}
+
+/* [noscript] nsIPrincipal getSystemPrincipal (); */
+NS_IMETHODIMP nsScriptSecurityManager::GetSystemPrincipal(nsIPrincipal **_retval)
+{
+    return NS_ERROR_NOT_IMPLEMENTED;
+}
+
+/* [noscript] nsIPrincipal getCertificatePrincipal (in AUTF8String aCertFingerprint, in AUTF8String aSubjectName, in AUTF8String aPrettyName, in nsISupports aCert, in nsIURI aURI); */
+NS_IMETHODIMP nsScriptSecurityManager::GetCertificatePrincipal(const nsACString & aCertFingerprint, const nsACString & aSubjectName, const nsACString & aPrettyName, nsISupports *aCert, nsIURI *aURI, nsIPrincipal **_retval)
+{
+    return NS_ERROR_NOT_IMPLEMENTED;
+}
+
+/* nsIPrincipal getCodebasePrincipal (in nsIURI aURI); */
+NS_IMETHODIMP nsScriptSecurityManager::GetCodebasePrincipal(nsIURI *aURI, nsIPrincipal **_retval)
+{
+    return NS_ERROR_NOT_IMPLEMENTED;
+}
+
+/* [noscript] short requestCapability (in nsIPrincipal principal, in string capability); */
+NS_IMETHODIMP nsScriptSecurityManager::RequestCapability(nsIPrincipal *principal, const char *capability, PRInt16 *_retval)
+{
+    return NS_ERROR_NOT_IMPLEMENTED;
+}
+
+/* boolean isCapabilityEnabled (in string capability); */
+NS_IMETHODIMP nsScriptSecurityManager::IsCapabilityEnabled(const char *capability, PRBool *_retval)
+{
+    return NS_ERROR_NOT_IMPLEMENTED;
+}
+
+/* void enableCapability (in string capability); */
+NS_IMETHODIMP nsScriptSecurityManager::EnableCapability(const char *capability)
+{
+    return NS_ERROR_NOT_IMPLEMENTED;
+}
+
+/* void revertCapability (in string capability); */
+NS_IMETHODIMP nsScriptSecurityManager::RevertCapability(const char *capability)
+{
+    return NS_ERROR_NOT_IMPLEMENTED;
+}
+
+/* void disableCapability (in string capability); */
+NS_IMETHODIMP nsScriptSecurityManager::DisableCapability(const char *capability)
+{
+    return NS_ERROR_NOT_IMPLEMENTED;
+}
+
+/* void setCanEnableCapability (in AUTF8String certificateFingerprint, in string capability, in short canEnable); */
+NS_IMETHODIMP nsScriptSecurityManager::SetCanEnableCapability(const nsACString & certificateFingerprint, const char *capability, PRInt16 canEnable)
+{
+    return NS_ERROR_NOT_IMPLEMENTED;
+}
+
+/* [noscript] nsIPrincipal getObjectPrincipal (in JSContextPtr cx, in JSObjectPtr obj); */
+NS_IMETHODIMP nsScriptSecurityManager::GetObjectPrincipal(JSContext * cx, JSObject * obj, nsIPrincipal **_retval)
+{
+    return NS_ERROR_NOT_IMPLEMENTED;
+}
+
+/* [noscript] boolean subjectPrincipalIsSystem (); */
+NS_IMETHODIMP nsScriptSecurityManager::SubjectPrincipalIsSystem(PRBool *_retval)
+{
+    return NS_ERROR_NOT_IMPLEMENTED;
+}
+
+/* [noscript] void checkSameOrigin (in JSContextPtr aJSContext, in nsIURI aTargetURI); */
+NS_IMETHODIMP nsScriptSecurityManager::CheckSameOrigin(JSContext * aJSContext, nsIURI *aTargetURI)
+{
+    return NS_ERROR_NOT_IMPLEMENTED;
+}
+
+/* void checkSameOriginURI (in nsIURI aSourceURI, in nsIURI aTargetURI, in boolean reportError); */
+NS_IMETHODIMP nsScriptSecurityManager::CheckSameOriginURI(nsIURI *aSourceURI, nsIURI *aTargetURI, PRBool reportError)
+{
+    return NS_ERROR_NOT_IMPLEMENTED;
+}
+
+/* [noscript] nsIPrincipal getPrincipalFromContext (in JSContextPtr cx); */
+NS_IMETHODIMP nsScriptSecurityManager::GetPrincipalFromContext(JSContext * cx, nsIPrincipal **_retval)
+{
+    return NS_ERROR_NOT_IMPLEMENTED;
+}
+
+/* nsIPrincipal getChannelPrincipal (in nsIChannel aChannel); */
+NS_IMETHODIMP nsScriptSecurityManager::GetChannelPrincipal(nsIChannel *aChannel, nsIPrincipal **_retval)
+{
+    return NS_ERROR_NOT_IMPLEMENTED;
+}
+
+/* boolean isSystemPrincipal (in nsIPrincipal aPrincipal); */
+NS_IMETHODIMP nsScriptSecurityManager::IsSystemPrincipal(nsIPrincipal *aPrincipal, PRBool *_retval)
+{
+    return NS_ERROR_NOT_IMPLEMENTED;
+}
+
+/* [noscript, notxpcom] nsIPrincipal getCxSubjectPrincipal (in JSContextPtr cx); */
+NS_IMETHODIMP_(nsIPrincipal *) nsScriptSecurityManager::GetCxSubjectPrincipal(JSContext * cx)
+{
+    return NS_ERROR_NOT_IMPLEMENTED;
+}
+
+/* End of implementation class template. */
+#endif
+
+#define NS_SCRIPTSECURITYMANAGERNEWEST_CONTRACTID "@mozilla.org/scriptsecuritymanager;1"
+#define NS_SCRIPTSECURITYMANAGERNEWEST_CLASSNAME "scriptsecuritymanager"
+
+#endif /* __gen_nsIScriptSecurityManagerNewest_h__ */
diff -U 10 -r -N old/plugin/oji/MRJCarbon/plugin/Source/nsIScriptSecurityManagerNew.h new/plugin/oji/MRJCarbon/plugin/Source/nsIScriptSecurityManagerNew.h
--- old/plugin/oji/MRJCarbon/plugin/Source/nsIScriptSecurityManagerNew.h	1969-12-31 18:00:00.000000000 -0600
+++ new/plugin/oji/MRJCarbon/plugin/Source/nsIScriptSecurityManagerNew.h	2006-08-28 10:55:54.000000000 -0500
@@ -0,0 +1,539 @@
+/*
+ * DO NOT EDIT.  THIS FILE IS GENERATED FROM nsIScriptSecurityManager.idl
+ */
+/* But we _will_ edit it, since we need it to use the script security manager
+ * with browsers that support newer versions of its interface.  The difference
+ * bewteen the NEW interface and the NEWALT1 interface is that the latter adds
+ * CheckLoadURIWithPrincipal().  It's added _before_ the one function that we
+ * need to use (GetSubjectPrincipal()) ... which is why we need this file.
+ * The following method is different between NEWALT1 and NEWALT2.  But that
+ * makes no difference to us, since we don't use it:
+ *     CheckLoadURIStr()
+ */
+
+#ifndef __gen_nsIScriptSecurityManagerNew_h__
+#define __gen_nsIScriptSecurityManagerNew_h__
+
+
+#ifndef __gen_nsISupports_h__
+#include "nsISupports.h"
+#endif
+
+#ifndef __gen_nsIPrincipal_h__
+#include "nsIPrincipal.h"
+#endif
+
+#ifndef __gen_nsIXPCSecurityManager_h__
+#include "nsIXPCSecurityManager.h"
+#endif
+
+/* For IDL files that don't want to include root IDL files. */
+#ifndef NS_NO_VTABLE
+#define NS_NO_VTABLE
+#endif
+class nsIURI; /* forward declaration */
+
+
+/* starting interface:    nsIScriptSecurityManager */
+#define NS_ISCRIPTSECURITYMANAGERNEWALT2_IID_STR "463eb1fa-9dac-4ca7-826f-1fc921971d3a"
+
+#ifndef NS_ISCRIPTSECURITYMANAGERNEWALT2_IID
+#define NS_ISCRIPTSECURITYMANAGERNEWALT2_IID \
+  {0x463eb1fa, 0x9dac, 0x4ca7, \
+    { 0x82, 0x6f, 0x1f, 0xc9, 0x21, 0x97, 0x1d, 0x3a }}
+#endif
+
+class NS_NO_VTABLE nsIScriptSecurityManagerNew : public nsIXPCSecurityManager {
+ public: 
+
+#ifdef NS_DECLARE_STATIC_IID_ACCESSOR
+  NS_DECLARE_STATIC_IID_ACCESSOR(NS_ISCRIPTSECURITYMANAGERNEWALT2_IID)
+#else
+  NS_DEFINE_STATIC_IID_ACCESSOR(NS_ISCRIPTSECURITYMANAGERNEWALT2_IID)
+#endif
+
+  /**
+     * Checks whether the running script is allowed to access aProperty.
+     */
+  /* [noscript] void checkPropertyAccess (in JSContextPtr aJSContext, in JSObjectPtr aJSObject, in string aClassName, in JSVal aProperty, in PRUint32 aAction); */
+  NS_IMETHOD CheckPropertyAccess(JSContext * aJSContext, JSObject * aJSObject, const char *aClassName, jsval aProperty, PRUint32 aAction) = 0;
+
+  /**
+     * Checks whether the running script is allowed to connect to aTargetURI
+     */
+  /* [noscript] void checkConnect (in JSContextPtr aJSContext, in nsIURI aTargetURI, in string aClassName, in string aProperty); */
+  NS_IMETHOD CheckConnect(JSContext * aJSContext, nsIURI *aTargetURI, const char *aClassName, const char *aProperty) = 0;
+
+  /**
+     * Check that the script currently running in context "cx" can load "uri".
+     *
+     * Will return error code NS_ERROR_DOM_BAD_URI if the load request 
+     * should be denied.
+     *
+     * @param cx the JSContext of the script causing the load
+     * @param uri the URI that is being loaded
+     */
+  /* [noscript] void checkLoadURIFromScript (in JSContextPtr cx, in nsIURI uri); */
+  NS_IMETHOD CheckLoadURIFromScript(JSContext * cx, nsIURI *uri) = 0;
+
+  /**
+     * Default CheckLoadURI permissions
+     */
+  enum { STANDARD = 0U };
+
+  enum { DISALLOW_FROM_MAIL = 1U };
+
+  enum { ALLOW_CHROME = 2U };
+
+  enum { DISALLOW_SCRIPT_OR_DATA = 4U };
+
+  enum { DISALLOW_SCRIPT = 8U };
+
+  /**
+     * Check that content with principal aPrincipal can load "uri".
+     *
+     * Will return error code NS_ERROR_DOM_BAD_URI if the load request 
+     * should be denied.
+     *
+     * @param aPrincipal the URI causing the load
+     * @param uri the URI that is being loaded
+     * @param flags the permission set, see above
+     */
+  /* [noscript] void checkLoadURIWithPrincipal (in nsIPrincipal aPrincipal, in nsIURI uri, in unsigned long flags); */
+  NS_IMETHOD CheckLoadURIWithPrincipal(nsIPrincipal *aPrincipal, nsIURI *uri, PRUint32 flags) = 0;
+
+  /**
+     * Check that content from "from" can load "uri".
+     *
+     * Will return error code NS_ERROR_DOM_BAD_URI if the load request 
+     * should be denied.
+     *
+     * @param from the URI causing the load
+     * @param uri the URI that is being loaded
+     * @param flags the permission set, see above
+     */
+  /* void checkLoadURI (in nsIURI from, in nsIURI uri, in unsigned long flags); */
+  NS_IMETHOD CheckLoadURI(nsIURI *from, nsIURI *uri, PRUint32 flags) = 0;
+
+  /**
+     * Same as CheckLoadURI but takes string arguments for ease of use
+     * by scripts
+     */
+  /* void checkLoadURIStr (in AUTF8String from, in AUTF8String uri, in unsigned long flags); */
+  NS_IMETHOD CheckLoadURIStr(const nsACString & from, const nsACString & uri, PRUint32 flags) = 0;
+
+  /**
+     * Check that the function 'funObj' is allowed to run on 'targetObj'
+     *
+     * Will return error code NS_ERROR_DOM_SECURITY_ERR if the function
+     * should not run
+     *
+     * @param cx The current active JavaScript context.
+     * @param funObj The function trying to run..
+     * @param targetObj The object the function will run on.
+     */
+  /* [noscript] void checkFunctionAccess (in JSContextPtr cx, in voidPtr funObj, in voidPtr targetObj); */
+  NS_IMETHOD CheckFunctionAccess(JSContext * cx, void * funObj, void * targetObj) = 0;
+
+  /**
+     * Return true if content from the given principal is allowed to
+     * execute scripts.
+     */
+  /* [noscript] boolean canExecuteScripts (in JSContextPtr cx, in nsIPrincipal principal); */
+  NS_IMETHOD CanExecuteScripts(JSContext * cx, nsIPrincipal *principal, PRBool *_retval) = 0;
+
+  /**
+     * Return the principal of the innermost frame of the currently 
+     * executing script. Will return null if there is no script 
+     * currently executing.
+     */
+  /* [noscript] nsIPrincipal getSubjectPrincipal (); */
+  NS_IMETHOD GetSubjectPrincipal(nsIPrincipal **_retval) = 0;
+
+  /**
+     * Return the all-powerful system principal.
+     */
+  /* [noscript] nsIPrincipal getSystemPrincipal (); */
+  NS_IMETHOD GetSystemPrincipal(nsIPrincipal **_retval) = 0;
+
+  /**
+     * Return a principal with the specified certificate ID and codebase URI.
+     */
+  /* [noscript] nsIPrincipal getCertificatePrincipal (in string CertID, in nsIURI aURI); */
+  NS_IMETHOD GetCertificatePrincipal(const char *CertID, nsIURI *aURI, nsIPrincipal **_retval) = 0;
+
+  /**
+     * Return a principal that has the same origin as aURI.
+     */
+  /* [noscript] nsIPrincipal getCodebasePrincipal (in nsIURI aURI); */
+  NS_IMETHOD GetCodebasePrincipal(nsIURI *aURI, nsIPrincipal **_retval) = 0;
+
+  /**
+     * Request that 'capability' can be enabled by scripts or applets
+     * running with 'principal'. Will prompt user if
+     * necessary. Returns nsIPrincipal::ENABLE_GRANTED or
+     * nsIPrincipal::ENABLE_DENIED based on user's choice.
+     */
+  /* [noscript] short requestCapability (in nsIPrincipal principal, in string capability); */
+  NS_IMETHOD RequestCapability(nsIPrincipal *principal, const char *capability, PRInt16 *_retval) = 0;
+
+  /**
+     * Return true if the currently executing script has 'capability' enabled.
+     */
+  /* boolean isCapabilityEnabled (in string capability); */
+  NS_IMETHOD IsCapabilityEnabled(const char *capability, PRBool *_retval) = 0;
+
+  /**
+     * Enable 'capability' in the innermost frame of the currently executing
+     * script.
+     */
+  /* void enableCapability (in string capability); */
+  NS_IMETHOD EnableCapability(const char *capability) = 0;
+
+  /**
+     * Remove 'capability' from the innermost frame of the currently
+     * executing script. Any setting of 'capability' from enclosing
+     * frames thus comes into effect.
+     */
+  /* void revertCapability (in string capability); */
+  NS_IMETHOD RevertCapability(const char *capability) = 0;
+
+  /**
+     * Disable 'capability' in the innermost frame of the currently executing
+     * script.
+     */
+  /* void disableCapability (in string capability); */
+  NS_IMETHOD DisableCapability(const char *capability) = 0;
+
+  /**
+     * Allow 'certificateID' to enable 'capability.' Can only be performed
+     * by code signed by the system certificate.
+     */
+  /* void setCanEnableCapability (in string certificateID, in string capability, in short canEnable); */
+  NS_IMETHOD SetCanEnableCapability(const char *certificateID, const char *capability, PRInt16 canEnable) = 0;
+
+  /**
+     * Return the principal of the specified object in the specified context.
+     */
+  /* [noscript] nsIPrincipal getObjectPrincipal (in JSContextPtr cx, in JSObjectPtr obj); */
+  NS_IMETHOD GetObjectPrincipal(JSContext * cx, JSObject * obj, nsIPrincipal **_retval) = 0;
+
+  /**
+     * Returns true if the principal of the currently running script is the
+     * system principal, false otherwise.
+     */
+  /* [noscript] boolean subjectPrincipalIsSystem (); */
+  NS_IMETHOD SubjectPrincipalIsSystem(PRBool *_retval) = 0;
+
+  /**
+     * Returns OK if aJSContext and target have the same "origin"
+     * (scheme, host, and port).
+     */
+  /* [noscript] void checkSameOrigin (in JSContextPtr aJSContext, in nsIURI aTargetURI); */
+  NS_IMETHOD CheckSameOrigin(JSContext * aJSContext, nsIURI *aTargetURI) = 0;
+
+  /**
+     * Returns OK if aSourceURI and target have the same "origin"
+     * (scheme, host, and port).
+     */
+  /* void checkSameOriginURI (in nsIURI aSourceURI, in nsIURI aTargetURI); */
+  NS_IMETHOD CheckSameOriginURI(nsIURI *aSourceURI, nsIURI *aTargetURI) = 0;
+
+  /**
+     * Returns OK if aSourcePrincipal and aTargetPrincipal
+     * have the same "origin" (scheme, host, and port).
+     */
+  /* [noscript] void checkSameOriginPrincipal (in nsIPrincipal aSourcePrincipal, in nsIPrincipal aTargetPrincipal); */
+  NS_IMETHOD CheckSameOriginPrincipal(nsIPrincipal *aSourcePrincipal, nsIPrincipal *aTargetPrincipal) = 0;
+
+  /**
+     * Returns the principal of the global object of the given context, or null
+     * if no global or no principal.
+     */
+  /* [noscript] nsIPrincipal getPrincipalFromContext (in JSContextPtr cx); */
+  NS_IMETHOD GetPrincipalFromContext(JSContext * cx, nsIPrincipal **_retval) = 0;
+
+  /**
+     * Utility method for comparing two URIs.  For security purposes, two URIs
+     * are equivalent if their schemes, hosts, and ports (if any) match.  This
+     * method returns true if aSubjectURI and aObjectURI have the same origin,
+     * false otherwise.
+     */
+  /* [noscript] boolean securityCompareURIs (in nsIURI aSubjectURI, in nsIURI aObjectURI); */
+  NS_IMETHOD SecurityCompareURIs(nsIURI *aSubjectURI, nsIURI *aObjectURI, PRBool *_retval) = 0;
+
+};
+
+/* Use this macro when declaring classes that implement this interface. */
+#define NS_DECL_NSISCRIPTSECURITYMANAGERNEW \
+  NS_IMETHOD CheckPropertyAccess(JSContext * aJSContext, JSObject * aJSObject, const char *aClassName, jsval aProperty, PRUint32 aAction); \
+  NS_IMETHOD CheckConnect(JSContext * aJSContext, nsIURI *aTargetURI, const char *aClassName, const char *aProperty); \
+  NS_IMETHOD CheckLoadURIFromScript(JSContext * cx, nsIURI *uri); \
+  NS_IMETHOD CheckLoadURIWithPrincipal(nsIPrincipal *aPrincipal, nsIURI *uri, PRUint32 flags); \
+  NS_IMETHOD CheckLoadURI(nsIURI *from, nsIURI *uri, PRUint32 flags); \
+  NS_IMETHOD CheckLoadURIStr(const nsACString & from, const nsACString & uri, PRUint32 flags); \
+  NS_IMETHOD CheckFunctionAccess(JSContext * cx, void * funObj, void * targetObj); \
+  NS_IMETHOD CanExecuteScripts(JSContext * cx, nsIPrincipal *principal, PRBool *_retval); \
+  NS_IMETHOD GetSubjectPrincipal(nsIPrincipal **_retval); \
+  NS_IMETHOD GetSystemPrincipal(nsIPrincipal **_retval); \
+  NS_IMETHOD GetCertificatePrincipal(const char *CertID, nsIURI *aURI, nsIPrincipal **_retval); \
+  NS_IMETHOD GetCodebasePrincipal(nsIURI *aURI, nsIPrincipal **_retval); \
+  NS_IMETHOD RequestCapability(nsIPrincipal *principal, const char *capability, PRInt16 *_retval); \
+  NS_IMETHOD IsCapabilityEnabled(const char *capability, PRBool *_retval); \
+  NS_IMETHOD EnableCapability(const char *capability); \
+  NS_IMETHOD RevertCapability(const char *capability); \
+  NS_IMETHOD DisableCapability(const char *capability); \
+  NS_IMETHOD SetCanEnableCapability(const char *certificateID, const char *capability, PRInt16 canEnable); \
+  NS_IMETHOD GetObjectPrincipal(JSContext * cx, JSObject * obj, nsIPrincipal **_retval); \
+  NS_IMETHOD SubjectPrincipalIsSystem(PRBool *_retval); \
+  NS_IMETHOD CheckSameOrigin(JSContext * aJSContext, nsIURI *aTargetURI); \
+  NS_IMETHOD CheckSameOriginURI(nsIURI *aSourceURI, nsIURI *aTargetURI); \
+  NS_IMETHOD CheckSameOriginPrincipal(nsIPrincipal *aSourcePrincipal, nsIPrincipal *aTargetPrincipal); \
+  NS_IMETHOD GetPrincipalFromContext(JSContext * cx, nsIPrincipal **_retval); \
+  NS_IMETHOD SecurityCompareURIs(nsIURI *aSubjectURI, nsIURI *aObjectURI, PRBool *_retval); 
+
+/* Use this macro to declare functions that forward the behavior of this interface to another object. */
+#define NS_FORWARD_NSISCRIPTSECURITYMANAGERNEW(_to) \
+  NS_IMETHOD CheckPropertyAccess(JSContext * aJSContext, JSObject * aJSObject, const char *aClassName, jsval aProperty, PRUint32 aAction) { return _to CheckPropertyAccess(aJSContext, aJSObject, aClassName, aProperty, aAction); } \
+  NS_IMETHOD CheckConnect(JSContext * aJSContext, nsIURI *aTargetURI, const char *aClassName, const char *aProperty) { return _to CheckConnect(aJSContext, aTargetURI, aClassName, aProperty); } \
+  NS_IMETHOD CheckLoadURIFromScript(JSContext * cx, nsIURI *uri) { return _to CheckLoadURIFromScript(cx, uri); } \
+  NS_IMETHOD CheckLoadURIWithPrincipal(nsIPrincipal *aPrincipal, nsIURI *uri, PRUint32 flags) { return _to CheckLoadURIWithPrincipal(aPrincipal, uri, flags); } \
+  NS_IMETHOD CheckLoadURI(nsIURI *from, nsIURI *uri, PRUint32 flags) { return _to CheckLoadURI(from, uri, flags); } \
+  NS_IMETHOD CheckLoadURIStr(const nsACString & from, const nsACString & uri, PRUint32 flags) { return _to CheckLoadURIStr(from, uri, flags); } \
+  NS_IMETHOD CheckFunctionAccess(JSContext * cx, void * funObj, void * targetObj) { return _to CheckFunctionAccess(cx, funObj, targetObj); } \
+  NS_IMETHOD CanExecuteScripts(JSContext * cx, nsIPrincipal *principal, PRBool *_retval) { return _to CanExecuteScripts(cx, principal, _retval); } \
+  NS_IMETHOD GetSubjectPrincipal(nsIPrincipal **_retval) { return _to GetSubjectPrincipal(_retval); } \
+  NS_IMETHOD GetSystemPrincipal(nsIPrincipal **_retval) { return _to GetSystemPrincipal(_retval); } \
+  NS_IMETHOD GetCertificatePrincipal(const char *CertID, nsIURI *aURI, nsIPrincipal **_retval) { return _to GetCertificatePrincipal(CertID, aURI, _retval); } \
+  NS_IMETHOD GetCodebasePrincipal(nsIURI *aURI, nsIPrincipal **_retval) { return _to GetCodebasePrincipal(aURI, _retval); } \
+  NS_IMETHOD RequestCapability(nsIPrincipal *principal, const char *capability, PRInt16 *_retval) { return _to RequestCapability(principal, capability, _retval); } \
+  NS_IMETHOD IsCapabilityEnabled(const char *capability, PRBool *_retval) { return _to IsCapabilityEnabled(capability, _retval); } \
+  NS_IMETHOD EnableCapability(const char *capability) { return _to EnableCapability(capability); } \
+  NS_IMETHOD RevertCapability(const char *capability) { return _to RevertCapability(capability); } \
+  NS_IMETHOD DisableCapability(const char *capability) { return _to DisableCapability(capability); } \
+  NS_IMETHOD SetCanEnableCapability(const char *certificateID, const char *capability, PRInt16 canEnable) { return _to SetCanEnableCapability(certificateID, capability, canEnable); } \
+  NS_IMETHOD GetObjectPrincipal(JSContext * cx, JSObject * obj, nsIPrincipal **_retval) { return _to GetObjectPrincipal(cx, obj, _retval); } \
+  NS_IMETHOD SubjectPrincipalIsSystem(PRBool *_retval) { return _to SubjectPrincipalIsSystem(_retval); } \
+  NS_IMETHOD CheckSameOrigin(JSContext * aJSContext, nsIURI *aTargetURI) { return _to CheckSameOrigin(aJSContext, aTargetURI); } \
+  NS_IMETHOD CheckSameOriginURI(nsIURI *aSourceURI, nsIURI *aTargetURI) { return _to CheckSameOriginURI(aSourceURI, aTargetURI); } \
+  NS_IMETHOD CheckSameOriginPrincipal(nsIPrincipal *aSourcePrincipal, nsIPrincipal *aTargetPrincipal) { return _to CheckSameOriginPrincipal(aSourcePrincipal, aTargetPrincipal); } \
+  NS_IMETHOD GetPrincipalFromContext(JSContext * cx, nsIPrincipal **_retval) { return _to GetPrincipalFromContext(cx, _retval); } \
+  NS_IMETHOD SecurityCompareURIs(nsIURI *aSubjectURI, nsIURI *aObjectURI, PRBool *_retval) { return _to SecurityCompareURIs(aSubjectURI, aObjectURI, _retval); } 
+
+/* Use this macro to declare functions that forward the behavior of this interface to another object in a safe way. */
+#define NS_FORWARD_SAFE_NSISCRIPTSECURITYMANAGERNEW(_to) \
+  NS_IMETHOD CheckPropertyAccess(JSContext * aJSContext, JSObject * aJSObject, const char *aClassName, jsval aProperty, PRUint32 aAction) { return !_to ? NS_ERROR_NULL_POINTER : _to->CheckPropertyAccess(aJSContext, aJSObject, aClassName, aProperty, aAction); } \
+  NS_IMETHOD CheckConnect(JSContext * aJSContext, nsIURI *aTargetURI, const char *aClassName, const char *aProperty) { return !_to ? NS_ERROR_NULL_POINTER : _to->CheckConnect(aJSContext, aTargetURI, aClassName, aProperty); } \
+  NS_IMETHOD CheckLoadURIFromScript(JSContext * cx, nsIURI *uri) { return !_to ? NS_ERROR_NULL_POINTER : _to->CheckLoadURIFromScript(cx, uri); } \
+  NS_IMETHOD CheckLoadURIWithPrincipal(nsIPrincipal *aPrincipal, nsIURI *uri, PRUint32 flags) { return !_to ? NS_ERROR_NULL_POINTER : _to->CheckLoadURIWithPrincipal(aPrincipal, uri, flags); } \
+  NS_IMETHOD CheckLoadURI(nsIURI *from, nsIURI *uri, PRUint32 flags) { return !_to ? NS_ERROR_NULL_POINTER : _to->CheckLoadURI(from, uri, flags); } \
+  NS_IMETHOD CheckLoadURIStr(const nsACString & from, const nsACString & uri, PRUint32 flags) { return !_to ? NS_ERROR_NULL_POINTER : _to->CheckLoadURIStr(from, uri, flags); } \
+  NS_IMETHOD CheckFunctionAccess(JSContext * cx, void * funObj, void * targetObj) { return !_to ? NS_ERROR_NULL_POINTER : _to->CheckFunctionAccess(cx, funObj, targetObj); } \
+  NS_IMETHOD CanExecuteScripts(JSContext * cx, nsIPrincipal *principal, PRBool *_retval) { return !_to ? NS_ERROR_NULL_POINTER : _to->CanExecuteScripts(cx, principal, _retval); } \
+  NS_IMETHOD GetSubjectPrincipal(nsIPrincipal **_retval) { return !_to ? NS_ERROR_NULL_POINTER : _to->GetSubjectPrincipal(_retval); } \
+  NS_IMETHOD GetSystemPrincipal(nsIPrincipal **_retval) { return !_to ? NS_ERROR_NULL_POINTER : _to->GetSystemPrincipal(_retval); } \
+  NS_IMETHOD GetCertificatePrincipal(const char *CertID, nsIURI *aURI, nsIPrincipal **_retval) { return !_to ? NS_ERROR_NULL_POINTER : _to->GetCertificatePrincipal(CertID, aURI, _retval); } \
+  NS_IMETHOD GetCodebasePrincipal(nsIURI *aURI, nsIPrincipal **_retval) { return !_to ? NS_ERROR_NULL_POINTER : _to->GetCodebasePrincipal(aURI, _retval); } \
+  NS_IMETHOD RequestCapability(nsIPrincipal *principal, const char *capability, PRInt16 *_retval) { return !_to ? NS_ERROR_NULL_POINTER : _to->RequestCapability(principal, capability, _retval); } \
+  NS_IMETHOD IsCapabilityEnabled(const char *capability, PRBool *_retval) { return !_to ? NS_ERROR_NULL_POINTER : _to->IsCapabilityEnabled(capability, _retval); } \
+  NS_IMETHOD EnableCapability(const char *capability) { return !_to ? NS_ERROR_NULL_POINTER : _to->EnableCapability(capability); } \
+  NS_IMETHOD RevertCapability(const char *capability) { return !_to ? NS_ERROR_NULL_POINTER : _to->RevertCapability(capability); } \
+  NS_IMETHOD DisableCapability(const char *capability) { return !_to ? NS_ERROR_NULL_POINTER : _to->DisableCapability(capability); } \
+  NS_IMETHOD SetCanEnableCapability(const char *certificateID, const char *capability, PRInt16 canEnable) { return !_to ? NS_ERROR_NULL_POINTER : _to->SetCanEnableCapability(certificateID, capability, canEnable); } \
+  NS_IMETHOD GetObjectPrincipal(JSContext * cx, JSObject * obj, nsIPrincipal **_retval) { return !_to ? NS_ERROR_NULL_POINTER : _to->GetObjectPrincipal(cx, obj, _retval); } \
+  NS_IMETHOD SubjectPrincipalIsSystem(PRBool *_retval) { return !_to ? NS_ERROR_NULL_POINTER : _to->SubjectPrincipalIsSystem(_retval); } \
+  NS_IMETHOD CheckSameOrigin(JSContext * aJSContext, nsIURI *aTargetURI) { return !_to ? NS_ERROR_NULL_POINTER : _to->CheckSameOrigin(aJSContext, aTargetURI); } \
+  NS_IMETHOD CheckSameOriginURI(nsIURI *aSourceURI, nsIURI *aTargetURI) { return !_to ? NS_ERROR_NULL_POINTER : _to->CheckSameOriginURI(aSourceURI, aTargetURI); } \
+  NS_IMETHOD CheckSameOriginPrincipal(nsIPrincipal *aSourcePrincipal, nsIPrincipal *aTargetPrincipal) { return !_to ? NS_ERROR_NULL_POINTER : _to->CheckSameOriginPrincipal(aSourcePrincipal, aTargetPrincipal); } \
+  NS_IMETHOD GetPrincipalFromContext(JSContext * cx, nsIPrincipal **_retval) { return !_to ? NS_ERROR_NULL_POINTER : _to->GetPrincipalFromContext(cx, _retval); } \
+  NS_IMETHOD SecurityCompareURIs(nsIURI *aSubjectURI, nsIURI *aObjectURI, PRBool *_retval) { return !_to ? NS_ERROR_NULL_POINTER : _to->SecurityCompareURIs(aSubjectURI, aObjectURI, _retval); } 
+
+#if 0
+/* Use the code below as a template for the implementation class for this interface. */
+
+/* Header file */
+class nsScriptSecurityManager : public nsIScriptSecurityManager
+{
+public:
+  NS_DECL_ISUPPORTS
+  NS_DECL_NSISCRIPTSECURITYMANAGER
+
+  nsScriptSecurityManager();
+
+private:
+  ~nsScriptSecurityManager();
+
+protected:
+  /* additional members */
+};
+
+/* Implementation file */
+NS_IMPL_ISUPPORTS1(nsScriptSecurityManager, nsIScriptSecurityManager)
+
+nsScriptSecurityManager::nsScriptSecurityManager()
+{
+  /* member initializers and constructor code */
+}
+
+nsScriptSecurityManager::~nsScriptSecurityManager()
+{
+  /* destructor code */
+}
+
+/* [noscript] void checkPropertyAccess (in JSContextPtr aJSContext, in JSObjectPtr aJSObject, in string aClassName, in JSVal aProperty, in PRUint32 aAction); */
+NS_IMETHODIMP nsScriptSecurityManager::CheckPropertyAccess(JSContext * aJSContext, JSObject * aJSObject, const char *aClassName, jsval aProperty, PRUint32 aAction)
+{
+    return NS_ERROR_NOT_IMPLEMENTED;
+}
+
+/* [noscript] void checkConnect (in JSContextPtr aJSContext, in nsIURI aTargetURI, in string aClassName, in string aProperty); */
+NS_IMETHODIMP nsScriptSecurityManager::CheckConnect(JSContext * aJSContext, nsIURI *aTargetURI, const char *aClassName, const char *aProperty)
+{
+    return NS_ERROR_NOT_IMPLEMENTED;
+}
+
+/* [noscript] void checkLoadURIFromScript (in JSContextPtr cx, in nsIURI uri); */
+NS_IMETHODIMP nsScriptSecurityManager::CheckLoadURIFromScript(JSContext * cx, nsIURI *uri)
+{
+    return NS_ERROR_NOT_IMPLEMENTED;
+}
+
+/* [noscript] void checkLoadURIWithPrincipal (in nsIPrincipal aPrincipal, in nsIURI uri, in unsigned long flags); */
+NS_IMETHODIMP nsScriptSecurityManager::CheckLoadURIWithPrincipal(nsIPrincipal *aPrincipal, nsIURI *uri, PRUint32 flags)
+{
+    return NS_ERROR_NOT_IMPLEMENTED;
+}
+
+/* void checkLoadURI (in nsIURI from, in nsIURI uri, in unsigned long flags); */
+NS_IMETHODIMP nsScriptSecurityManager::CheckLoadURI(nsIURI *from, nsIURI *uri, PRUint32 flags)
+{
+    return NS_ERROR_NOT_IMPLEMENTED;
+}
+
+/* void checkLoadURIStr (in AUTF8String from, in AUTF8String uri, in unsigned long flags); */
+NS_IMETHODIMP nsScriptSecurityManager::CheckLoadURIStr(const nsACString & from, const nsACString & uri, PRUint32 flags)
+{
+    return NS_ERROR_NOT_IMPLEMENTED;
+}
+
+/* [noscript] void checkFunctionAccess (in JSContextPtr cx, in voidPtr funObj, in voidPtr targetObj); */
+NS_IMETHODIMP nsScriptSecurityManager::CheckFunctionAccess(JSContext * cx, void * funObj, void * targetObj)
+{
+    return NS_ERROR_NOT_IMPLEMENTED;
+}
+
+/* [noscript] boolean canExecuteScripts (in JSContextPtr cx, in nsIPrincipal principal); */
+NS_IMETHODIMP nsScriptSecurityManager::CanExecuteScripts(JSContext * cx, nsIPrincipal *principal, PRBool *_retval)
+{
+    return NS_ERROR_NOT_IMPLEMENTED;
+}
+
+/* [noscript] nsIPrincipal getSubjectPrincipal (); */
+NS_IMETHODIMP nsScriptSecurityManager::GetSubjectPrincipal(nsIPrincipal **_retval)
+{
+    return NS_ERROR_NOT_IMPLEMENTED;
+}
+
+/* [noscript] nsIPrincipal getSystemPrincipal (); */
+NS_IMETHODIMP nsScriptSecurityManager::GetSystemPrincipal(nsIPrincipal **_retval)
+{
+    return NS_ERROR_NOT_IMPLEMENTED;
+}
+
+/* [noscript] nsIPrincipal getCertificatePrincipal (in string CertID, in nsIURI aURI); */
+NS_IMETHODIMP nsScriptSecurityManager::GetCertificatePrincipal(const char *CertID, nsIURI *aURI, nsIPrincipal **_retval)
+{
+    return NS_ERROR_NOT_IMPLEMENTED;
+}
+
+/* [noscript] nsIPrincipal getCodebasePrincipal (in nsIURI aURI); */
+NS_IMETHODIMP nsScriptSecurityManager::GetCodebasePrincipal(nsIURI *aURI, nsIPrincipal **_retval)
+{
+    return NS_ERROR_NOT_IMPLEMENTED;
+}
+
+/* [noscript] short requestCapability (in nsIPrincipal principal, in string capability); */
+NS_IMETHODIMP nsScriptSecurityManager::RequestCapability(nsIPrincipal *principal, const char *capability, PRInt16 *_retval)
+{
+    return NS_ERROR_NOT_IMPLEMENTED;
+}
+
+/* boolean isCapabilityEnabled (in string capability); */
+NS_IMETHODIMP nsScriptSecurityManager::IsCapabilityEnabled(const char *capability, PRBool *_retval)
+{
+    return NS_ERROR_NOT_IMPLEMENTED;
+}
+
+/* void enableCapability (in string capability); */
+NS_IMETHODIMP nsScriptSecurityManager::EnableCapability(const char *capability)
+{
+    return NS_ERROR_NOT_IMPLEMENTED;
+}
+
+/* void revertCapability (in string capability); */
+NS_IMETHODIMP nsScriptSecurityManager::RevertCapability(const char *capability)
+{
+    return NS_ERROR_NOT_IMPLEMENTED;
+}
+
+/* void disableCapability (in string capability); */
+NS_IMETHODIMP nsScriptSecurityManager::DisableCapability(const char *capability)
+{
+    return NS_ERROR_NOT_IMPLEMENTED;
+}
+
+/* void setCanEnableCapability (in string certificateID, in string capability, in short canEnable); */
+NS_IMETHODIMP nsScriptSecurityManager::SetCanEnableCapability(const char *certificateID, const char *capability, PRInt16 canEnable)
+{
+    return NS_ERROR_NOT_IMPLEMENTED;
+}
+
+/* [noscript] nsIPrincipal getObjectPrincipal (in JSContextPtr cx, in JSObjectPtr obj); */
+NS_IMETHODIMP nsScriptSecurityManager::GetObjectPrincipal(JSContext * cx, JSObject * obj, nsIPrincipal **_retval)
+{
+    return NS_ERROR_NOT_IMPLEMENTED;
+}
+
+/* [noscript] boolean subjectPrincipalIsSystem (); */
+NS_IMETHODIMP nsScriptSecurityManager::SubjectPrincipalIsSystem(PRBool *_retval)
+{
+    return NS_ERROR_NOT_IMPLEMENTED;
+}
+
+/* [noscript] void checkSameOrigin (in JSContextPtr aJSContext, in nsIURI aTargetURI); */
+NS_IMETHODIMP nsScriptSecurityManager::CheckSameOrigin(JSContext * aJSContext, nsIURI *aTargetURI)
+{
+    return NS_ERROR_NOT_IMPLEMENTED;
+}
+
+/* void checkSameOriginURI (in nsIURI aSourceURI, in nsIURI aTargetURI); */
+NS_IMETHODIMP nsScriptSecurityManager::CheckSameOriginURI(nsIURI *aSourceURI, nsIURI *aTargetURI)
+{
+    return NS_ERROR_NOT_IMPLEMENTED;
+}
+
+/* [noscript] void checkSameOriginPrincipal (in nsIPrincipal aSourcePrincipal, in nsIPrincipal aTargetPrincipal); */
+NS_IMETHODIMP nsScriptSecurityManager::CheckSameOriginPrincipal(nsIPrincipal *aSourcePrincipal, nsIPrincipal *aTargetPrincipal)
+{
+    return NS_ERROR_NOT_IMPLEMENTED;
+}
+
+/* [noscript] nsIPrincipal getPrincipalFromContext (in JSContextPtr cx); */
+NS_IMETHODIMP nsScriptSecurityManager::GetPrincipalFromContext(JSContext * cx, nsIPrincipal **_retval)
+{
+    return NS_ERROR_NOT_IMPLEMENTED;
+}
+
+/* [noscript] boolean securityCompareURIs (in nsIURI aSubjectURI, in nsIURI aObjectURI); */
+NS_IMETHODIMP nsScriptSecurityManager::SecurityCompareURIs(nsIURI *aSubjectURI, nsIURI *aObjectURI, PRBool *_retval)
+{
+    return NS_ERROR_NOT_IMPLEMENTED;
+}
+
+/* End of implementation class template. */
+#endif
+
+#define NS_SCRIPTSECURITYMANAGERNEW_CONTRACTID "@mozilla.org/scriptsecuritymanager;1"
+#define NS_SCRIPTSECURITYMANAGERNEW_CLASSNAME "scriptsecuritymanager"
+
+#endif /* __gen_nsIScriptSecurityManagerNew_h__ */
diff -U 10 -r -N old/plugin/oji/MRJCarbon/plugin/Source/nsIScriptSecurityManagerOld.h new/plugin/oji/MRJCarbon/plugin/Source/nsIScriptSecurityManagerOld.h
--- old/plugin/oji/MRJCarbon/plugin/Source/nsIScriptSecurityManagerOld.h	1969-12-31 18:00:00.000000000 -0600
+++ new/plugin/oji/MRJCarbon/plugin/Source/nsIScriptSecurityManagerOld.h	2007-01-27 14:57:37.000000000 -0600
@@ -0,0 +1,500 @@
+/*
+ * DO NOT EDIT.  THIS FILE IS GENERATED FROM nsIScriptSecurityManager.idl
+ */
+
+#ifndef __gen_nsIScriptSecurityManager_h__
+#define __gen_nsIScriptSecurityManager_h__
+
+
+#ifndef __gen_nsISupports_h__
+#include "nsISupports.h"
+#endif
+
+#ifndef __gen_nsIPrincipal_h__
+#include "nsIPrincipal.h"
+#endif
+
+#ifndef __gen_nsIXPCSecurityManager_h__
+#include "nsIXPCSecurityManager.h"
+#endif
+
+/* For IDL files that don't want to include root IDL files. */
+#ifndef NS_NO_VTABLE
+#define NS_NO_VTABLE
+#endif
+class nsIURI; /* forward declaration */
+
+
+/* starting interface:    nsIScriptSecurityManager */
+#define NS_ISCRIPTSECURITYMANAGER_IID_STR "58df5780-8006-11d2-bd91-00805f8ae3f4"
+
+#define NS_ISCRIPTSECURITYMANAGER_IID \
+  {0x58df5780, 0x8006, 0x11d2, \
+    { 0xbd, 0x91, 0x00, 0x80, 0x5f, 0x8a, 0xe3, 0xf4 }}
+
+class NS_NO_VTABLE nsIScriptSecurityManager : public nsIXPCSecurityManager {
+ public: 
+
+#ifdef NS_DECLARE_STATIC_IID_ACCESSOR
+  NS_DECLARE_STATIC_IID_ACCESSOR(NS_ISCRIPTSECURITYMANAGER_IID)
+#else
+  NS_DEFINE_STATIC_IID_ACCESSOR(NS_ISCRIPTSECURITYMANAGER_IID)
+#endif
+
+  /**
+     * Checks whether the running script is allowed to access aProperty.
+     */
+  /* [noscript] void checkPropertyAccess (in JSContextPtr aJSContext, in JSObjectPtr aJSObject, in string aClassName, in JSVal aProperty, in PRUint32 aAction); */
+  NS_IMETHOD CheckPropertyAccess(JSContext * aJSContext, JSObject * aJSObject, const char *aClassName, jsval aProperty, PRUint32 aAction) = 0;
+
+  /**
+     * Checks whether the running script is allowed to connect to aTargetURI
+     */
+  /* [noscript] void checkConnect (in JSContextPtr aJSContext, in nsIURI aTargetURI, in string aClassName, in string aProperty); */
+  NS_IMETHOD CheckConnect(JSContext * aJSContext, nsIURI *aTargetURI, const char *aClassName, const char *aProperty) = 0;
+
+  /**
+     * Check that the script currently running in context "cx" can load "uri".
+     *
+     * Will return error code NS_ERROR_DOM_BAD_URI if the load request 
+     * should be denied.
+     *
+     * @param cx the JSContext of the script causing the load
+     * @param uri the URI that is being loaded
+     */
+  /* [noscript] void checkLoadURIFromScript (in JSContextPtr cx, in nsIURI uri); */
+  NS_IMETHOD CheckLoadURIFromScript(JSContext * cx, nsIURI *uri) = 0;
+
+  /**
+     * Default CheckLoadURI permissions
+     */
+  enum { STANDARD = 0U };
+
+  enum { DISALLOW_FROM_MAIL = 1U };
+
+  enum { ALLOW_CHROME = 2U };
+
+  enum { DISALLOW_SCRIPT_OR_DATA = 4U };
+
+  /**
+     * Check that content from "from" can load "uri".
+     *
+     * Will return error code NS_ERROR_DOM_BAD_URI if the load request 
+     * should be denied.
+     *
+     * @param from the URI causing the load
+     * @param uri the URI that is being loaded
+     * @param flags the permission set, see above
+     */
+  /* void checkLoadURI (in nsIURI from, in nsIURI uri, in unsigned long flags); */
+  NS_IMETHOD CheckLoadURI(nsIURI *from, nsIURI *uri, PRUint32 flags) = 0;
+
+  /**
+     * Same as CheckLoadURI but takes string arguments for ease of use
+     * by scripts
+     */
+  /* void checkLoadURIStr (in string from, in string uri, in unsigned long flags); */
+  NS_IMETHOD CheckLoadURIStr(const char *from, const char *uri, PRUint32 flags) = 0;
+
+  /**
+     * Check that the function 'funObj' is allowed to run on 'targetObj'
+     *
+     * Will return error code NS_ERROR_DOM_SECURITY_ERR if the function
+     * should not run
+     *
+     * @param cx The current active JavaScript context.
+     * @param funObj The function trying to run..
+     * @param targetObj The object the function will run on.
+     */
+  /* [noscript] void checkFunctionAccess (in JSContextPtr cx, in voidPtr funObj, in voidPtr targetObj); */
+  NS_IMETHOD CheckFunctionAccess(JSContext * cx, void * funObj, void * targetObj) = 0;
+
+  /**
+     * Return true if content from the given principal is allowed to
+     * execute scripts.
+     */
+  /* [noscript] boolean canExecuteScripts (in JSContextPtr cx, in nsIPrincipal principal); */
+  NS_IMETHOD CanExecuteScripts(JSContext * cx, nsIPrincipal *principal, PRBool *_retval) = 0;
+
+  /**
+     * Return the principal of the innermost frame of the currently 
+     * executing script. Will return null if there is no script 
+     * currently executing.
+     */
+  /* [noscript] nsIPrincipal getSubjectPrincipal (); */
+  NS_IMETHOD GetSubjectPrincipal(nsIPrincipal **_retval) = 0;
+
+  /**
+     * Return the all-powerful system principal.
+     */
+  /* [noscript] nsIPrincipal getSystemPrincipal (); */
+  NS_IMETHOD GetSystemPrincipal(nsIPrincipal **_retval) = 0;
+
+  /**
+     * Return a principal with the specified certificate ID and codebase URI.
+     */
+  /* [noscript] nsIPrincipal getCertificatePrincipal (in string CertID, in nsIURI aURI); */
+  NS_IMETHOD GetCertificatePrincipal(const char *CertID, nsIURI *aURI, nsIPrincipal **_retval) = 0;
+
+  /**
+     * Return a principal that has the same origin as aURI.
+     */
+  /* [noscript] nsIPrincipal getCodebasePrincipal (in nsIURI aURI); */
+  NS_IMETHOD GetCodebasePrincipal(nsIURI *aURI, nsIPrincipal **_retval) = 0;
+
+  /**
+     * Request that 'capability' can be enabled by scripts or applets
+     * running with 'principal'. Will prompt user if
+     * necessary. Returns nsIPrincipal::ENABLE_GRANTED or
+     * nsIPrincipal::ENABLE_DENIED based on user's choice.
+     */
+  /* [noscript] short requestCapability (in nsIPrincipal principal, in string capability); */
+  NS_IMETHOD RequestCapability(nsIPrincipal *principal, const char *capability, PRInt16 *_retval) = 0;
+
+  /**
+     * Return true if the currently executing script has 'capability' enabled.
+     */
+  /* boolean isCapabilityEnabled (in string capability); */
+  NS_IMETHOD IsCapabilityEnabled(const char *capability, PRBool *_retval) = 0;
+
+  /**
+     * Enable 'capability' in the innermost frame of the currently executing
+     * script.
+     */
+  /* void enableCapability (in string capability); */
+  NS_IMETHOD EnableCapability(const char *capability) = 0;
+
+  /**
+     * Remove 'capability' from the innermost frame of the currently
+     * executing script. Any setting of 'capability' from enclosing
+     * frames thus comes into effect.
+     */
+  /* void revertCapability (in string capability); */
+  NS_IMETHOD RevertCapability(const char *capability) = 0;
+
+  /**
+     * Disable 'capability' in the innermost frame of the currently executing
+     * script.
+     */
+  /* void disableCapability (in string capability); */
+  NS_IMETHOD DisableCapability(const char *capability) = 0;
+
+  /**
+     * Allow 'certificateID' to enable 'capability.' Can only be performed
+     * by code signed by the system certificate.
+     */
+  /* void setCanEnableCapability (in string certificateID, in string capability, in short canEnable); */
+  NS_IMETHOD SetCanEnableCapability(const char *certificateID, const char *capability, PRInt16 canEnable) = 0;
+
+  /**
+     * Return the principal of the specified object in the specified context.
+     */
+  /* [noscript] nsIPrincipal getObjectPrincipal (in JSContextPtr cx, in JSObjectPtr obj); */
+  NS_IMETHOD GetObjectPrincipal(JSContext * cx, JSObject * obj, nsIPrincipal **_retval) = 0;
+
+  /**
+     * Returns true if the principal of the currently running script is the
+     * system principal, false otherwise.
+     */
+  /* boolean subjectPrincipalIsSystem (); */
+  NS_IMETHOD SubjectPrincipalIsSystem(PRBool *_retval) = 0;
+
+  /**
+     * Returns OK if aJSContext and target have the same "origin"
+     * (scheme, host, and port).
+     */
+  /* [noscript] void checkSameOrigin (in JSContextPtr aJSContext, in nsIURI aTargetURI); */
+  NS_IMETHOD CheckSameOrigin(JSContext * aJSContext, nsIURI *aTargetURI) = 0;
+
+  /**
+     * Returns OK if aSourceURI and target have the same "origin"
+     * (scheme, host, and port).
+     */
+  /* [noscript] void checkSameOriginURI (in nsIURI aSourceURI, in nsIURI aTargetURI); */
+  NS_IMETHOD CheckSameOriginURI(nsIURI *aSourceURI, nsIURI *aTargetURI) = 0;
+
+  /**
+     * Returns OK if aSourcePrincipal and aTargetPrincipal
+     * have the same "origin" (scheme, host, and port).
+     */
+  /* [noscript] void checkSameOriginPrincipal (in nsIPrincipal aSourcePrincipal, in nsIPrincipal aTargetPrincipal); */
+  NS_IMETHOD CheckSameOriginPrincipal(nsIPrincipal *aSourcePrincipal, nsIPrincipal *aTargetPrincipal) = 0;
+
+  /**
+     * Returns the principal of the global object of the given context, or null
+     * if no global or no principal.
+     */
+  /* [noscript] nsIPrincipal getPrincipalFromContext (in JSContextPtr cx); */
+  NS_IMETHOD GetPrincipalFromContext(JSContext * cx, nsIPrincipal **_retval) = 0;
+
+  /**
+     * Utility method for comparing two URIs.  For security purposes, two URIs
+     * are equivalent if their schemes, hosts, and ports (if any) match.  This
+     * method returns true if aSubjectURI and aObjectURI have the same origin,
+     * false otherwise.
+     */
+  /* [noscript] boolean securityCompareURIs (in nsIURI aSubjectURI, in nsIURI aObjectURI); */
+  NS_IMETHOD SecurityCompareURIs(nsIURI *aSubjectURI, nsIURI *aObjectURI, PRBool *_retval) = 0;
+
+};
+
+/* Use this macro when declaring classes that implement this interface. */
+#define NS_DECL_NSISCRIPTSECURITYMANAGER \
+  NS_IMETHOD CheckPropertyAccess(JSContext * aJSContext, JSObject * aJSObject, const char *aClassName, jsval aProperty, PRUint32 aAction); \
+  NS_IMETHOD CheckConnect(JSContext * aJSContext, nsIURI *aTargetURI, const char *aClassName, const char *aProperty); \
+  NS_IMETHOD CheckLoadURIFromScript(JSContext * cx, nsIURI *uri); \
+  NS_IMETHOD CheckLoadURI(nsIURI *from, nsIURI *uri, PRUint32 flags); \
+  NS_IMETHOD CheckLoadURIStr(const char *from, const char *uri, PRUint32 flags); \
+  NS_IMETHOD CheckFunctionAccess(JSContext * cx, void * funObj, void * targetObj); \
+  NS_IMETHOD CanExecuteScripts(JSContext * cx, nsIPrincipal *principal, PRBool *_retval); \
+  NS_IMETHOD GetSubjectPrincipal(nsIPrincipal **_retval); \
+  NS_IMETHOD GetSystemPrincipal(nsIPrincipal **_retval); \
+  NS_IMETHOD GetCertificatePrincipal(const char *CertID, nsIURI *aURI, nsIPrincipal **_retval); \
+  NS_IMETHOD GetCodebasePrincipal(nsIURI *aURI, nsIPrincipal **_retval); \
+  NS_IMETHOD RequestCapability(nsIPrincipal *principal, const char *capability, PRInt16 *_retval); \
+  NS_IMETHOD IsCapabilityEnabled(const char *capability, PRBool *_retval); \
+  NS_IMETHOD EnableCapability(const char *capability); \
+  NS_IMETHOD RevertCapability(const char *capability); \
+  NS_IMETHOD DisableCapability(const char *capability); \
+  NS_IMETHOD SetCanEnableCapability(const char *certificateID, const char *capability, PRInt16 canEnable); \
+  NS_IMETHOD GetObjectPrincipal(JSContext * cx, JSObject * obj, nsIPrincipal **_retval); \
+  NS_IMETHOD SubjectPrincipalIsSystem(PRBool *_retval); \
+  NS_IMETHOD CheckSameOrigin(JSContext * aJSContext, nsIURI *aTargetURI); \
+  NS_IMETHOD CheckSameOriginURI(nsIURI *aSourceURI, nsIURI *aTargetURI); \
+  NS_IMETHOD CheckSameOriginPrincipal(nsIPrincipal *aSourcePrincipal, nsIPrincipal *aTargetPrincipal); \
+  NS_IMETHOD GetPrincipalFromContext(JSContext * cx, nsIPrincipal **_retval); \
+  NS_IMETHOD SecurityCompareURIs(nsIURI *aSubjectURI, nsIURI *aObjectURI, PRBool *_retval); 
+
+/* Use this macro to declare functions that forward the behavior of this interface to another object. */
+#define NS_FORWARD_NSISCRIPTSECURITYMANAGER(_to) \
+  NS_IMETHOD CheckPropertyAccess(JSContext * aJSContext, JSObject * aJSObject, const char *aClassName, jsval aProperty, PRUint32 aAction) { return _to CheckPropertyAccess(aJSContext, aJSObject, aClassName, aProperty, aAction); } \
+  NS_IMETHOD CheckConnect(JSContext * aJSContext, nsIURI *aTargetURI, const char *aClassName, const char *aProperty) { return _to CheckConnect(aJSContext, aTargetURI, aClassName, aProperty); } \
+  NS_IMETHOD CheckLoadURIFromScript(JSContext * cx, nsIURI *uri) { return _to CheckLoadURIFromScript(cx, uri); } \
+  NS_IMETHOD CheckLoadURI(nsIURI *from, nsIURI *uri, PRUint32 flags) { return _to CheckLoadURI(from, uri, flags); } \
+  NS_IMETHOD CheckLoadURIStr(const char *from, const char *uri, PRUint32 flags) { return _to CheckLoadURIStr(from, uri, flags); } \
+  NS_IMETHOD CheckFunctionAccess(JSContext * cx, void * funObj, void * targetObj) { return _to CheckFunctionAccess(cx, funObj, targetObj); } \
+  NS_IMETHOD CanExecuteScripts(JSContext * cx, nsIPrincipal *principal, PRBool *_retval) { return _to CanExecuteScripts(cx, principal, _retval); } \
+  NS_IMETHOD GetSubjectPrincipal(nsIPrincipal **_retval) { return _to GetSubjectPrincipal(_retval); } \
+  NS_IMETHOD GetSystemPrincipal(nsIPrincipal **_retval) { return _to GetSystemPrincipal(_retval); } \
+  NS_IMETHOD GetCertificatePrincipal(const char *CertID, nsIURI *aURI, nsIPrincipal **_retval) { return _to GetCertificatePrincipal(CertID, aURI, _retval); } \
+  NS_IMETHOD GetCodebasePrincipal(nsIURI *aURI, nsIPrincipal **_retval) { return _to GetCodebasePrincipal(aURI, _retval); } \
+  NS_IMETHOD RequestCapability(nsIPrincipal *principal, const char *capability, PRInt16 *_retval) { return _to RequestCapability(principal, capability, _retval); } \
+  NS_IMETHOD IsCapabilityEnabled(const char *capability, PRBool *_retval) { return _to IsCapabilityEnabled(capability, _retval); } \
+  NS_IMETHOD EnableCapability(const char *capability) { return _to EnableCapability(capability); } \
+  NS_IMETHOD RevertCapability(const char *capability) { return _to RevertCapability(capability); } \
+  NS_IMETHOD DisableCapability(const char *capability) { return _to DisableCapability(capability); } \
+  NS_IMETHOD SetCanEnableCapability(const char *certificateID, const char *capability, PRInt16 canEnable) { return _to SetCanEnableCapability(certificateID, capability, canEnable); } \
+  NS_IMETHOD GetObjectPrincipal(JSContext * cx, JSObject * obj, nsIPrincipal **_retval) { return _to GetObjectPrincipal(cx, obj, _retval); } \
+  NS_IMETHOD SubjectPrincipalIsSystem(PRBool *_retval) { return _to SubjectPrincipalIsSystem(_retval); } \
+  NS_IMETHOD CheckSameOrigin(JSContext * aJSContext, nsIURI *aTargetURI) { return _to CheckSameOrigin(aJSContext, aTargetURI); } \
+  NS_IMETHOD CheckSameOriginURI(nsIURI *aSourceURI, nsIURI *aTargetURI) { return _to CheckSameOriginURI(aSourceURI, aTargetURI); } \
+  NS_IMETHOD CheckSameOriginPrincipal(nsIPrincipal *aSourcePrincipal, nsIPrincipal *aTargetPrincipal) { return _to CheckSameOriginPrincipal(aSourcePrincipal, aTargetPrincipal); } \
+  NS_IMETHOD GetPrincipalFromContext(JSContext * cx, nsIPrincipal **_retval) { return _to GetPrincipalFromContext(cx, _retval); } \
+  NS_IMETHOD SecurityCompareURIs(nsIURI *aSubjectURI, nsIURI *aObjectURI, PRBool *_retval) { return _to SecurityCompareURIs(aSubjectURI, aObjectURI, _retval); } 
+
+/* Use this macro to declare functions that forward the behavior of this interface to another object in a safe way. */
+#define NS_FORWARD_SAFE_NSISCRIPTSECURITYMANAGER(_to) \
+  NS_IMETHOD CheckPropertyAccess(JSContext * aJSContext, JSObject * aJSObject, const char *aClassName, jsval aProperty, PRUint32 aAction) { return !_to ? NS_ERROR_NULL_POINTER : _to->CheckPropertyAccess(aJSContext, aJSObject, aClassName, aProperty, aAction); } \
+  NS_IMETHOD CheckConnect(JSContext * aJSContext, nsIURI *aTargetURI, const char *aClassName, const char *aProperty) { return !_to ? NS_ERROR_NULL_POINTER : _to->CheckConnect(aJSContext, aTargetURI, aClassName, aProperty); } \
+  NS_IMETHOD CheckLoadURIFromScript(JSContext * cx, nsIURI *uri) { return !_to ? NS_ERROR_NULL_POINTER : _to->CheckLoadURIFromScript(cx, uri); } \
+  NS_IMETHOD CheckLoadURI(nsIURI *from, nsIURI *uri, PRUint32 flags) { return !_to ? NS_ERROR_NULL_POINTER : _to->CheckLoadURI(from, uri, flags); } \
+  NS_IMETHOD CheckLoadURIStr(const char *from, const char *uri, PRUint32 flags) { return !_to ? NS_ERROR_NULL_POINTER : _to->CheckLoadURIStr(from, uri, flags); } \
+  NS_IMETHOD CheckFunctionAccess(JSContext * cx, void * funObj, void * targetObj) { return !_to ? NS_ERROR_NULL_POINTER : _to->CheckFunctionAccess(cx, funObj, targetObj); } \
+  NS_IMETHOD CanExecuteScripts(JSContext * cx, nsIPrincipal *principal, PRBool *_retval) { return !_to ? NS_ERROR_NULL_POINTER : _to->CanExecuteScripts(cx, principal, _retval); } \
+  NS_IMETHOD GetSubjectPrincipal(nsIPrincipal **_retval) { return !_to ? NS_ERROR_NULL_POINTER : _to->GetSubjectPrincipal(_retval); } \
+  NS_IMETHOD GetSystemPrincipal(nsIPrincipal **_retval) { return !_to ? NS_ERROR_NULL_POINTER : _to->GetSystemPrincipal(_retval); } \
+  NS_IMETHOD GetCertificatePrincipal(const char *CertID, nsIURI *aURI, nsIPrincipal **_retval) { return !_to ? NS_ERROR_NULL_POINTER : _to->GetCertificatePrincipal(CertID, aURI, _retval); } \
+  NS_IMETHOD GetCodebasePrincipal(nsIURI *aURI, nsIPrincipal **_retval) { return !_to ? NS_ERROR_NULL_POINTER : _to->GetCodebasePrincipal(aURI, _retval); } \
+  NS_IMETHOD RequestCapability(nsIPrincipal *principal, const char *capability, PRInt16 *_retval) { return !_to ? NS_ERROR_NULL_POINTER : _to->RequestCapability(principal, capability, _retval); } \
+  NS_IMETHOD IsCapabilityEnabled(const char *capability, PRBool *_retval) { return !_to ? NS_ERROR_NULL_POINTER : _to->IsCapabilityEnabled(capability, _retval); } \
+  NS_IMETHOD EnableCapability(const char *capability) { return !_to ? NS_ERROR_NULL_POINTER : _to->EnableCapability(capability); } \
+  NS_IMETHOD RevertCapability(const char *capability) { return !_to ? NS_ERROR_NULL_POINTER : _to->RevertCapability(capability); } \
+  NS_IMETHOD DisableCapability(const char *capability) { return !_to ? NS_ERROR_NULL_POINTER : _to->DisableCapability(capability); } \
+  NS_IMETHOD SetCanEnableCapability(const char *certificateID, const char *capability, PRInt16 canEnable) { return !_to ? NS_ERROR_NULL_POINTER : _to->SetCanEnableCapability(certificateID, capability, canEnable); } \
+  NS_IMETHOD GetObjectPrincipal(JSContext * cx, JSObject * obj, nsIPrincipal **_retval) { return !_to ? NS_ERROR_NULL_POINTER : _to->GetObjectPrincipal(cx, obj, _retval); } \
+  NS_IMETHOD SubjectPrincipalIsSystem(PRBool *_retval) { return !_to ? NS_ERROR_NULL_POINTER : _to->SubjectPrincipalIsSystem(_retval); } \
+  NS_IMETHOD CheckSameOrigin(JSContext * aJSContext, nsIURI *aTargetURI) { return !_to ? NS_ERROR_NULL_POINTER : _to->CheckSameOrigin(aJSContext, aTargetURI); } \
+  NS_IMETHOD CheckSameOriginURI(nsIURI *aSourceURI, nsIURI *aTargetURI) { return !_to ? NS_ERROR_NULL_POINTER : _to->CheckSameOriginURI(aSourceURI, aTargetURI); } \
+  NS_IMETHOD CheckSameOriginPrincipal(nsIPrincipal *aSourcePrincipal, nsIPrincipal *aTargetPrincipal) { return !_to ? NS_ERROR_NULL_POINTER : _to->CheckSameOriginPrincipal(aSourcePrincipal, aTargetPrincipal); } \
+  NS_IMETHOD GetPrincipalFromContext(JSContext * cx, nsIPrincipal **_retval) { return !_to ? NS_ERROR_NULL_POINTER : _to->GetPrincipalFromContext(cx, _retval); } \
+  NS_IMETHOD SecurityCompareURIs(nsIURI *aSubjectURI, nsIURI *aObjectURI, PRBool *_retval) { return !_to ? NS_ERROR_NULL_POINTER : _to->SecurityCompareURIs(aSubjectURI, aObjectURI, _retval); } 
+
+#if 0
+/* Use the code below as a template for the implementation class for this interface. */
+
+/* Header file */
+class nsScriptSecurityManager : public nsIScriptSecurityManager
+{
+public:
+  NS_DECL_ISUPPORTS
+  NS_DECL_NSISCRIPTSECURITYMANAGER
+
+  nsScriptSecurityManager();
+  virtual ~nsScriptSecurityManager();
+  /* additional members */
+};
+
+/* Implementation file */
+NS_IMPL_ISUPPORTS1(nsScriptSecurityManager, nsIScriptSecurityManager)
+
+nsScriptSecurityManager::nsScriptSecurityManager()
+{
+  /* member initializers and constructor code */
+}
+
+nsScriptSecurityManager::~nsScriptSecurityManager()
+{
+  /* destructor code */
+}
+
+/* [noscript] void checkPropertyAccess (in JSContextPtr aJSContext, in JSObjectPtr aJSObject, in string aClassName, in JSVal aProperty, in PRUint32 aAction); */
+NS_IMETHODIMP nsScriptSecurityManager::CheckPropertyAccess(JSContext * aJSContext, JSObject * aJSObject, const char *aClassName, jsval aProperty, PRUint32 aAction)
+{
+    return NS_ERROR_NOT_IMPLEMENTED;
+}
+
+/* [noscript] void checkConnect (in JSContextPtr aJSContext, in nsIURI aTargetURI, in string aClassName, in string aProperty); */
+NS_IMETHODIMP nsScriptSecurityManager::CheckConnect(JSContext * aJSContext, nsIURI *aTargetURI, const char *aClassName, const char *aProperty)
+{
+    return NS_ERROR_NOT_IMPLEMENTED;
+}
+
+/* [noscript] void checkLoadURIFromScript (in JSContextPtr cx, in nsIURI uri); */
+NS_IMETHODIMP nsScriptSecurityManager::CheckLoadURIFromScript(JSContext * cx, nsIURI *uri)
+{
+    return NS_ERROR_NOT_IMPLEMENTED;
+}
+
+/* void checkLoadURI (in nsIURI from, in nsIURI uri, in unsigned long flags); */
+NS_IMETHODIMP nsScriptSecurityManager::CheckLoadURI(nsIURI *from, nsIURI *uri, PRUint32 flags)
+{
+    return NS_ERROR_NOT_IMPLEMENTED;
+}
+
+/* void checkLoadURIStr (in string from, in string uri, in unsigned long flags); */
+NS_IMETHODIMP nsScriptSecurityManager::CheckLoadURIStr(const char *from, const char *uri, PRUint32 flags)
+{
+    return NS_ERROR_NOT_IMPLEMENTED;
+}
+
+/* [noscript] void checkFunctionAccess (in JSContextPtr cx, in voidPtr funObj, in voidPtr targetObj); */
+NS_IMETHODIMP nsScriptSecurityManager::CheckFunctionAccess(JSContext * cx, void * funObj, void * targetObj)
+{
+    return NS_ERROR_NOT_IMPLEMENTED;
+}
+
+/* [noscript] boolean canExecuteScripts (in JSContextPtr cx, in nsIPrincipal principal); */
+NS_IMETHODIMP nsScriptSecurityManager::CanExecuteScripts(JSContext * cx, nsIPrincipal *principal, PRBool *_retval)
+{
+    return NS_ERROR_NOT_IMPLEMENTED;
+}
+
+/* [noscript] nsIPrincipal getSubjectPrincipal (); */
+NS_IMETHODIMP nsScriptSecurityManager::GetSubjectPrincipal(nsIPrincipal **_retval)
+{
+    return NS_ERROR_NOT_IMPLEMENTED;
+}
+
+/* [noscript] nsIPrincipal getSystemPrincipal (); */
+NS_IMETHODIMP nsScriptSecurityManager::GetSystemPrincipal(nsIPrincipal **_retval)
+{
+    return NS_ERROR_NOT_IMPLEMENTED;
+}
+
+/* [noscript] nsIPrincipal getCertificatePrincipal (in string CertID, in nsIURI aURI); */
+NS_IMETHODIMP nsScriptSecurityManager::GetCertificatePrincipal(const char *CertID, nsIURI *aURI, nsIPrincipal **_retval)
+{
+    return NS_ERROR_NOT_IMPLEMENTED;
+}
+
+/* [noscript] nsIPrincipal getCodebasePrincipal (in nsIURI aURI); */
+NS_IMETHODIMP nsScriptSecurityManager::GetCodebasePrincipal(nsIURI *aURI, nsIPrincipal **_retval)
+{
+    return NS_ERROR_NOT_IMPLEMENTED;
+}
+
+/* [noscript] short requestCapability (in nsIPrincipal principal, in string capability); */
+NS_IMETHODIMP nsScriptSecurityManager::RequestCapability(nsIPrincipal *principal, const char *capability, PRInt16 *_retval)
+{
+    return NS_ERROR_NOT_IMPLEMENTED;
+}
+
+/* boolean isCapabilityEnabled (in string capability); */
+NS_IMETHODIMP nsScriptSecurityManager::IsCapabilityEnabled(const char *capability, PRBool *_retval)
+{
+    return NS_ERROR_NOT_IMPLEMENTED;
+}
+
+/* void enableCapability (in string capability); */
+NS_IMETHODIMP nsScriptSecurityManager::EnableCapability(const char *capability)
+{
+    return NS_ERROR_NOT_IMPLEMENTED;
+}
+
+/* void revertCapability (in string capability); */
+NS_IMETHODIMP nsScriptSecurityManager::RevertCapability(const char *capability)
+{
+    return NS_ERROR_NOT_IMPLEMENTED;
+}
+
+/* void disableCapability (in string capability); */
+NS_IMETHODIMP nsScriptSecurityManager::DisableCapability(const char *capability)
+{
+    return NS_ERROR_NOT_IMPLEMENTED;
+}
+
+/* void setCanEnableCapability (in string certificateID, in string capability, in short canEnable); */
+NS_IMETHODIMP nsScriptSecurityManager::SetCanEnableCapability(const char *certificateID, const char *capability, PRInt16 canEnable)
+{
+    return NS_ERROR_NOT_IMPLEMENTED;
+}
+
+/* [noscript] nsIPrincipal getObjectPrincipal (in JSContextPtr cx, in JSObjectPtr obj); */
+NS_IMETHODIMP nsScriptSecurityManager::GetObjectPrincipal(JSContext * cx, JSObject * obj, nsIPrincipal **_retval)
+{
+    return NS_ERROR_NOT_IMPLEMENTED;
+}
+
+/* boolean subjectPrincipalIsSystem (); */
+NS_IMETHODIMP nsScriptSecurityManager::SubjectPrincipalIsSystem(PRBool *_retval)
+{
+    return NS_ERROR_NOT_IMPLEMENTED;
+}
+
+/* [noscript] void checkSameOrigin (in JSContextPtr aJSContext, in nsIURI aTargetURI); */
+NS_IMETHODIMP nsScriptSecurityManager::CheckSameOrigin(JSContext * aJSContext, nsIURI *aTargetURI)
+{
+    return NS_ERROR_NOT_IMPLEMENTED;
+}
+
+/* [noscript] void checkSameOriginURI (in nsIURI aSourceURI, in nsIURI aTargetURI); */
+NS_IMETHODIMP nsScriptSecurityManager::CheckSameOriginURI(nsIURI *aSourceURI, nsIURI *aTargetURI)
+{
+    return NS_ERROR_NOT_IMPLEMENTED;
+}
+
+/* [noscript] void checkSameOriginPrincipal (in nsIPrincipal aSourcePrincipal, in nsIPrincipal aTargetPrincipal); */
+NS_IMETHODIMP nsScriptSecurityManager::CheckSameOriginPrincipal(nsIPrincipal *aSourcePrincipal, nsIPrincipal *aTargetPrincipal)
+{
+    return NS_ERROR_NOT_IMPLEMENTED;
+}
+
+/* [noscript] nsIPrincipal getPrincipalFromContext (in JSContextPtr cx); */
+NS_IMETHODIMP nsScriptSecurityManager::GetPrincipalFromContext(JSContext * cx, nsIPrincipal **_retval)
+{
+    return NS_ERROR_NOT_IMPLEMENTED;
+}
+
+/* [noscript] boolean securityCompareURIs (in nsIURI aSubjectURI, in nsIURI aObjectURI); */
+NS_IMETHODIMP nsScriptSecurityManager::SecurityCompareURIs(nsIURI *aSubjectURI, nsIURI *aObjectURI, PRBool *_retval)
+{
+    return NS_ERROR_NOT_IMPLEMENTED;
+}
+
+/* End of implementation class template. */
+#endif
+
+#define NS_SCRIPTSECURITYMANAGER_CONTRACTID "@mozilla.org/scriptsecuritymanager;1"
+#define NS_SCRIPTSECURITYMANAGER_CLASSNAME "scriptsecuritymanager"
+
+#endif /* __gen_nsIScriptSecurityManager_h__ */
diff -U 10 -r -N old/plugin/oji/MRJCarbon/plugin/Source/nsjvmFixes.h new/plugin/oji/MRJCarbon/plugin/Source/nsjvmFixes.h
--- old/plugin/oji/MRJCarbon/plugin/Source/nsjvmFixes.h	1969-12-31 18:00:00.000000000 -0600
+++ new/plugin/oji/MRJCarbon/plugin/Source/nsjvmFixes.h	2006-05-22 21:26:04.000000000 -0500
@@ -0,0 +1,58 @@
+/* ***** BEGIN LICENSE BLOCK *****
+ * Version: NPL 1.1/GPL 2.0/LGPL 2.1
+ *
+ * The contents of this file are subject to the Netscape Public License
+ * Version 1.1 (the "License"); you may not use this file except in
+ * compliance with the License. You may obtain a copy of the License at
+ * http://www.mozilla.org/NPL/
+ *
+ * Software distributed under the License is distributed on an "AS IS" basis,
+ * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
+ * for the specific language governing rights and limitations under the
+ * License.
+ *
+ * The Original Code is mozilla.org code.
+ *
+ * The Initial Developer of the Original Code is 
+ * Netscape Communications Corporation.
+ * Portions created by the Initial Developer are Copyright (C) 1998
+ * the Initial Developer. All Rights Reserved.
+ *
+ * Contributor(s):
+ *        Steven Michaud
+ *
+ * Alternatively, the contents of this file may be used under the terms of
+ * either the GNU General Public License Version 2 or later (the "GPL"), or 
+ * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
+ * in which case the provisions of the GPL or the LGPL are applicable instead
+ * of those above. If you wish to allow use of your version of this file only
+ * under the terms of either the GPL or the LGPL, and not to allow others to
+ * use your version of this file under the terms of the NPL, indicate your
+ * decision by deleting the provisions above and replace them with the notice
+ * and other provisions required by the GPL or the LGPL. If you do not delete
+ * the provisions above, a recipient may use your version of this file under
+ * the terms of any one of the NPL, the GPL or the LGPL.
+ *
+ * ***** END LICENSE BLOCK ***** */
+
+#ifndef nsjvmFixes_h___
+#define nsjvmFixes_h___
+
+#define nsIJRIPlugin_h___ // Don't include nsIJRIPlugin.h
+#include "nsjvm.h"
+
+/* Deal with breakage caused by the fix for bmo bug 326273.  See:
+ * https://bugzilla.mozilla.org/show_bug.cgi?id=338685
+ * https://bugzilla.mozilla.org/show_bug.cgi?id=326273
+ */
+#ifndef NS_IJVMTHREADMANAGER_IID
+#define NS_IJVMTHREADMANAGER_IID \
+  {0x97bb54c0, 0x6846, 0x11d2, \
+    { 0x80, 0x1f, 0x00, 0x80, 0x5f, 0x71, 0x10, 0x1c }}
+typedef nsIThreadManager nsIJVMThreadManager;
+#endif
+
+// From MRJPlugin.cpp.
+extern nsID nsIJVMThreadManagerIID;
+
+#endif /* nsjvmFixes_h___ */
diff -U 10 -r -N old/plugin/oji/MRJCarbon/plugin/Source/ProxyClassLoaderFactory.java new/plugin/oji/MRJCarbon/plugin/Source/ProxyClassLoaderFactory.java
--- old/plugin/oji/MRJCarbon/plugin/Source/ProxyClassLoaderFactory.java	2003-06-11 00:11:56.000000000 -0500
+++ new/plugin/oji/MRJCarbon/plugin/Source/ProxyClassLoaderFactory.java	2006-09-11 16:03:14.000000000 -0500
@@ -36,24 +36,26 @@
  *
  * ----- END LICENSE BLOCK ----- */
 
 package netscape.oji;
 
 import java.net.URLClassLoader;
 import java.net.URL;
 import java.net.MalformedURLException;
 
 import java.io.*;
+import java.util.*;
 import java.util.zip.*;
-import java.util.WeakHashMap;
+import java.lang.ref.WeakReference;
 
 import java.security.CodeSource;
+import java.security.cert.Certificate;
 
 public abstract class ProxyClassLoaderFactory {
     static void debug(String message) {
         System.out.println("<<< " + message + " >>>");
     }
 
     /**
      * Loads specified class file as an array of bytes from ${netscape.oji.plugin.home}/MRJPlugin.jar.
      */
     private static byte[] getMRJPluginClassFile(String path) {
@@ -67,53 +69,95 @@
     			DataInputStream input = new DataInputStream(jarFile.getInputStream(classEntry));
     			input.readFully(data);
     			input.close();
     			jarFile.close();
     			return data;
     		}
         } catch (IOException ioe) {
         }
 		return null;
     }
-    
+
     /**
      * Trivial subclass of URLClassLoader that predefines the class netscape.oji.LiveConnectProxy
      * as if it were loaded from the specified codebase URL passed to the constructor.
      * @see        netscape.oji.LiveConnectProxy
      */
     private static class ProxyClassLoader extends URLClassLoader {
+        private int secureEnv = 0;
+        private String documentURL = null;
         private static byte[] data = getMRJPluginClassFile("netscape/oji/LiveConnectProxy.class");
-        ProxyClassLoader(URL[] documentURLs) {
-            super(documentURLs);
+        ProxyClassLoader(String documentURL, int secureEnv)
+            throws MalformedURLException
+        {
+            super(new URL[] {new URL(documentURL)});
+            this.documentURL = documentURL;
+            this.secureEnv = secureEnv;
+            holdSecureEnv(secureEnv);
             if (data != null) {
                 Class proxyClass = defineClass("netscape.oji.LiveConnectProxy",
                                                data, 0, data.length,
-                                               new CodeSource(documentURLs[0], null));
+                                               new CodeSource(new URL(documentURL),
+                                               (Certificate[]) null));
                 debug("ProxyClassLoader: defined LiveConnectProxy class.");
-                debug("Here're the permisssions you've got:");
+                debug("Here're the permissions you've got:");
                 debug(proxyClass.getProtectionDomain().getPermissions().toString());
             } else {
                 debug("ProxyClassLoader: failed to define LiveConnectProxy class.");
             }
         }
+        protected void finalize() throws Throwable {
+            releaseSecureEnv(secureEnv);
+			mClassLoaders.remove(documentURL);
+            super.finalize();
+        }
     }
-    
-    // XXX  Should this be a weak table of some sort?
-    private static WeakHashMap mClassLoaders = new WeakHashMap();
-
-    public static ClassLoader createClassLoader(final String documentURL) throws MalformedURLException {
-        ClassLoader loader = (ClassLoader) mClassLoaders.get(documentURL);
-        if (loader == null) {
-            try {
-                URL[] documentURLs = new URL[] { new URL(documentURL) };
-                loader = new ProxyClassLoader(documentURLs);
-                mClassLoaders.put(documentURL, loader);
-    		} catch (MalformedURLException e) {
-            }
+
+	private static native void holdSecureEnv(int secureEnv);
+	private static native void releaseSecureEnv(int secureEnv);
+
+    private static HashMap mClassLoaders = new HashMap();
+
+    // Previous versions (before JEP 0.9.1) cached proxy classloaders in
+    // mClassLoaders and re-used ones with the same codebase.  But there
+    // isn't necessarily a one-to-one correspondence between documentURL
+    // (the JavaScript principal's "origin") and an applet's codebase.
+    // Moreover, we don't want to re-use a classloader whose protection
+    // domain we've changed in JNIUtils.fixProtectionDomains().  The cost
+    // of not caching the proxy classloaders is very minor.
+    // As of JEP 0.9.6 (0.9.5+e) we're caching proxy classloaders again
+    // (just the last one we created) but for a different reason -- see
+    // below.
+    public static ClassLoader createClassLoader(final String documentURL, int secureEnv)
+        throws MalformedURLException
+    {
+        ClassLoader loader = null;
+        try {
+            loader = new ProxyClassLoader(documentURL, secureEnv);
+            // We only cache the last one we created.
+            mClassLoaders.clear();
+            mClassLoaders.put(documentURL, new WeakReference(loader));
+        } catch (MalformedURLException e) {
         }
         return loader;
     }
-    
-    public static void destroyClassLoader(final String documentURL) {
-        mClassLoaders.remove(documentURL);
-    }
+
+    // Mozilla.org browsers actually call this method (in getScriptClassLoader()
+    // in modules/oji/src/ProxyClassLoader.cpp), so we need to have a version
+    // that uses the "old" API.  Moreover, these calls are always made after
+    // we've already created a ClassLoader for documentURL using the "new" API,
+    // and when we don't have permissions to create a new ClassLoader.  So we
+    // cache the last one created and return that instead (if it matches
+    // documentURL).
+    // But getScriptClassLoader() serves no useful purpose, so there's no point
+    // in making this method available, after all.
+    //public static ClassLoader createClassLoader(final String documentURL)
+    //    throws MalformedURLException
+    //{
+    //    ClassLoader loader = null;
+    //    WeakReference classLoaderRef = (WeakReference)
+    //        mClassLoaders.get(documentURL);
+    //    if (classLoaderRef != null)
+    //        loader = (ClassLoader) classLoaderRef.get();
+    //    return loader;
+    //}
 }
