⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 jsj_jsobject.c

📁 caffeine-monkey java实现的js模拟引擎
💻 C
📖 第 1 页 / 共 3 页
字号:
/* -*- Mode: C; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 4 -*- * * ***** 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 Mozilla Communicator client code, released * March 31, 1998. * * 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): * * Alternatively, the contents of this file may be used under the terms of * either of 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 ***** */ /* This file is part of the Java-vendor-neutral implementation of LiveConnect * * It contains the implementation of the native methods for the  * netscape.javascript.JSObject Java class, which are used for calling into * JavaScript from Java.  It also contains the code that handles propagation * of exceptions both into and out of Java. * */#include <stdlib.h>#include <string.h>#include "jsj_private.h"#include "jsjava.h"#include "jscntxt.h"        /* For js_ReportErrorAgain().                               TODO - get rid of private header */#include "netscape_javascript_JSObject.h"   /* javah-generated headers *//* A captured JavaScript error, created when JS_ReportError() is called while   running JavaScript code that is itself called from Java. */struct CapturedJSError {    char *              message;    JSErrorReport       report;         /* Line # of error, etc. */    jthrowable          java_exception; /* Java exception, error, or null */    CapturedJSError *   next;           /* Next oldest captured JS error */};/*********************** Reflection of JSObjects ****************************/#ifdef PRESERVE_JSOBJECT_IDENTITY/* * This is a hash table that maps from JS objects to Java objects. * It is used to ensure that the same Java object results when a JS * object is reflected more than once, so that Java object equality * tests work in the expected manner. * * The entry keys are JSObject pointers and the entry values are Java objects * (of type jobject).  When the corresponding Java instance is finalized, * the entry is removed from the table, and a JavaScript GC root for the JS * object is removed. *  * This code is disabled because cycles in GC roots between the two systems * cause every reflected JS object to become uncollectable.  This can only * be solved by using weak links, a feature not available in JDK1.1. */static JSHashTable *js_obj_reflections = NULL;#ifdef JSJ_THREADSAFE/* * Used to protect the js_obj_reflections hashtable from simultaneous * read/write or * write/write access. */static PRMonitor *js_obj_reflections_monitor = NULL;#endif  /* JSJ_THREADSAFE */#endif  /* PRESERVE_JSOBJECT_IDENTITY */JSBooljsj_init_js_obj_reflections_table(){#ifdef PRESERVE_JSOBJECT_IDENTITY    if(js_obj_reflections != NULL)    {      return JS_TRUE;    }    js_obj_reflections = JS_NewHashTable(128, NULL, JS_CompareValues,                                         JS_CompareValues, NULL, NULL);    if (!js_obj_reflections)        return JS_FALSE;#ifdef JSJ_THREADSAFE    js_obj_reflections_monitor = PR_NewMonitor();    if (!js_obj_reflections_monitor) {        JS_HashTableDestroy(js_obj_reflections);        return JS_FALSE;    }#endif  /* JSJ_THREADSAFE */#endif  /* PRESERVE_JSOBJECT_IDENTITY */    return JS_TRUE;}/* * Return a Java object that "wraps" a given JS object by storing the address * of the JS object in a private field of the Java object.  A hash table is * used to ensure that the mapping of JS objects to Java objects is done on * one-to-one basis. * * If an error occurs, returns NULL and reports an error. */#ifdef PRESERVE_JSOBJECT_IDENTITYjobjectjsj_WrapJSObject(JSContext *cx, JNIEnv *jEnv, JSObject *js_obj){    jobject java_wrapper_obj;    JSHashEntry *he, **hep;    java_wrapper_obj = NULL;#ifdef JSJ_THREADSAFE    PR_EnterMonitor(js_obj_reflections_monitor);#endif    /* First, look in the hash table for an existing reflection of the same       JavaScript object.  If one is found, return it. */    hep = JS_HashTableRawLookup(js_obj_reflections, (JSHashNumber)js_obj, js_obj);    /* If the same JSObject is reflected into Java more than once then we should       return the same Java object, both for efficiency and so that the '=='       operator works as expected in Java when comparing two JSObjects.       However, it is not possible to hold a reference to a Java object without       inhibiting GC of that object, at least not in a portable way, i.e.       a weak reference. So, for now, JSObject identity is broken. */    he = *hep;    if (he) {        java_wrapper_obj = (jobject)he->value;        JS_ASSERT(java_wrapper_obj);        if (java_wrapper_obj)            goto done;    }    /* No existing reflection found, so create a new Java object that wraps       the JavaScript object by storing its address in a private integer field. */#ifndef OJI    java_wrapper_obj =        (*jEnv)->NewObject(jEnv, njJSObject, njJSObject_JSObject, (jint)js_obj);#else    if (JSJ_callbacks && JSJ_callbacks->get_java_wrapper != NULL) {        java_wrapper_obj = JSJ_callbacks->get_java_wrapper(jEnv, (jint)handle);    }#endif /*! OJI */    if (!java_wrapper_obj) {        jsj_UnexpectedJavaError(cx, jEnv, "Couldn't create new instance of "                                          "netscape.javascript.JSObject");        goto done;    }    /* Add the new reflection to the hash table. */    he = JS_HashTableRawAdd(js_obj_reflections, hep, (JSHashNumber)js_obj,                            js_obj, java_wrapper_obj);    if (he) {        /* Tell the JavaScript GC about this object since the only reference           to it may be in Java-land. */        JS_AddNamedRoot(cx, (void*)&he->key, "&he->key");    } else {        JS_ReportOutOfMemory(cx);        /* No need to delete java_wrapper_obj because Java GC will reclaim it */        java_wrapper_obj = NULL;    }        /*     * Release local reference to wrapper object, since some JVMs seem reticent     * about collecting it otherwise.     */    /* FIXME -- beard: this seems to make calls into Java with JSObject's fail. */    /* We should really be creating a global ref if we are putting it in a hash table. */    /* (*jEnv)->DeleteLocalRef(jEnv, java_wrapper_obj); */done:#ifdef JSJ_THREADSAFE        PR_ExitMonitor(js_obj_reflections_monitor);#endif            return java_wrapper_obj;}/* * Remove the mapping of a JS object from the hash table that maps JS objects * to Java objects.  This is called from the finalizer of an instance of * netscape.javascript.JSObject. */JSBooljsj_remove_js_obj_reflection_from_hashtable(JSContext *cx, JSObject *js_obj){    JSHashEntry *he, **hep;    JSBool success = JS_FALSE;#ifdef JSJ_THREADSAFE    PR_EnterMonitor(js_obj_reflections_monitor);#endif    /* Get the hash-table entry for this wrapper object */    hep = JS_HashTableRawLookup(js_obj_reflections, (JSHashNumber)js_obj, js_obj);    he = *hep;    JS_ASSERT(he);    if (he) {        /* Tell the JS GC that Java no longer keeps a reference to this           JS object. */        success = JS_RemoveRoot(cx, (void *)&he->key);        JS_HashTableRawRemove(js_obj_reflections, hep, he);    }#ifdef JSJ_THREADSAFE    PR_ExitMonitor(js_obj_reflections_monitor);#endif    return success;}#else /* !PRESERVE_JSOBJECT_IDENTITY *//* * The caller must call DeleteLocalRef() on the returned object when no more * references remain. */jobjectjsj_WrapJSObject(JSContext *cx, JNIEnv *jEnv, JSObject *js_obj){    jobject java_wrapper_obj;    JSObjectHandle *handle;    /* Create a tiny stub object to act as the GC root that points to the       JSObject from its netscape.javascript.JSObject counterpart. */    handle = (JSObjectHandle*)JS_malloc(cx, sizeof(JSObjectHandle));    if (!handle)        return NULL;    handle->js_obj = js_obj;    handle->rt = JS_GetRuntime(cx);    /* Create a new Java object that wraps the JavaScript object by storing its       address in a private integer field. */#ifndef OJI    java_wrapper_obj =        (*jEnv)->NewObject(jEnv, njJSObject, njJSObject_JSObject, (lcjsobject)handle);#else    if (JSJ_callbacks && JSJ_callbacks->get_java_wrapper != NULL) {        java_wrapper_obj = JSJ_callbacks->get_java_wrapper(jEnv, (lcjsobject)handle);    } else  {        java_wrapper_obj = NULL;    }#endif /*! OJI */    if (!java_wrapper_obj) {        jsj_UnexpectedJavaError(cx, jEnv, "Couldn't create new instance of "                                          "netscape.javascript.JSObject");        goto done;    }     JS_AddNamedRoot(cx, &handle->js_obj, "&handle->js_obj");done:            return java_wrapper_obj;}JSObject *jsj_UnwrapJSObjectWrapper(JNIEnv *jEnv, jobject java_wrapper_obj){    JSObjectHandle *handle;#ifndef OJI#if JS_BYTES_PER_LONG == 8    handle = (JSObjectHandle*)((*jEnv)->GetLongField(jEnv, java_wrapper_obj, njJSObject_long_internal));#else    handle = (JSObjectHandle*)((*jEnv)->GetIntField(jEnv, java_wrapper_obj, njJSObject_internal));#endif#else    /* Unwrapping this wrapper requires knowledge of the structure of the object. This is privileged       information that only the object implementor can know. In this case the object implementor       is the java plugin (such as the Sun plugin class sun.plugin.javascript.navig5.JSObject. 	   Since the plugin owns this structure, we defer to it to unwrap the object. If the plugin 	   does not implement this callback, then it should be set to null. In that case we try something 	   that works with Sun's plugin assuming that it has not yet been implemented yet. This 'else' 	   case should be removed as soon as the unwrap function is supported by the Sun JPI. */    if (JSJ_callbacks && JSJ_callbacks->unwrap_java_wrapper != NULL) {        handle = (JSObjectHandle*)JSJ_callbacks->unwrap_java_wrapper(jEnv, java_wrapper_obj);    }    else {        jclass   cid = (*jEnv)->GetObjectClass(jEnv, java_wrapper_obj);#if JS_BYTES_PER_LONG == 8        jfieldID fid = (*jEnv)->GetFieldID(jEnv, cid, "nativeJSObject", "J");        handle = (JSObjectHandle*)((*jEnv)->GetLongField(jEnv, java_wrapper_obj, fid));#else        jfieldID fid = (*jEnv)->GetFieldID(jEnv, cid, "nativeJSObject", "I");        handle = (JSObjectHandle*)((*jEnv)->GetIntField(jEnv, java_wrapper_obj, fid));#endif    }#endif    	/* JNI returns a NULL handle for a Java 'null' */    if (!handle)        return NULL;    return handle->js_obj;	}#endif  /* !PRESERVE_JSOBJECT_IDENTITY *//*************** Handling of Java exceptions in JavaScript ******************//* * Free up a JavaScript error that has been stored by the * capture_js_error_reports_for_java() function. */static CapturedJSError *destroy_saved_js_error(JNIEnv *jEnv, CapturedJSError *error){    CapturedJSError *next_error;    if (!error)        return NULL;    next_error = error->next;    if (error->java_exception)        (*jEnv)->DeleteGlobalRef(jEnv, error->java_exception);    if (error->message)        free((char*)error->message);    if (error->report.filename)        free((char*)error->report.filename);    if (error->report.linebuf)        free((char*)error->report.linebuf);    free(error);    return next_error;}/* * Capture a JS error that has been reported using JS_ReportError() by JS code * that has itself been called from Java.  A copy of the JS error data is made * and hung off the JSJ environment.  When JS completes and returns to its Java * caller, this data is used to synthesize an instance of * netscape.javascript.JSException.  If the resulting JSException is not caught * within Java, it may be propagated up the stack beyond the Java caller back * into JavaScript, in which case the error will be re-reported as a JavaScript * error. */JS_STATIC_DLL_CALLBACK(void)capture_js_error_reports_for_java(JSContext *cx, const char *message,                                  JSErrorReport *report){    CapturedJSError *new_error;    JSJavaThreadState *jsj_env;    jthrowable java_exception, tmp_exception;    JNIEnv *jEnv;    /* Warnings are not propagated as Java exceptions - they are simply       ignored.  Ditto for exceptions that are duplicated in the form       of error reports. */    if (report && (report->flags & (JSREPORT_WARNING | JSREPORT_EXCEPTION)))        return;    /* Create an empty struct to hold the saved JS error state */    new_error = malloc(sizeof(CapturedJSError));    if (!new_error)        goto out_of_memory;    memset(new_error, 0, sizeof(CapturedJSError));    /* Copy all the error info out of the original report into a private copy */    if (message) {        new_error->message = strdup(message);        if (!new_error->message)            goto out_of_memory;    }    if (report) {        new_error->report.lineno = report->lineno;        if (report->filename) {            new_error->report.filename = strdup(report->filename);            if (!new_error->report.filename)                goto out_of_memory;        }        if (report->linebuf) {            new_error->report.linebuf = strdup(report->linebuf);            if (!new_error->report.linebuf)                goto out_of_memory;            new_error->report.tokenptr =                new_error->report.linebuf + (report->tokenptr - report->linebuf);        }    }    /* Get the head of the list of pending JS errors */    jsj_env = jsj_EnterJava(cx, &jEnv);    if (!jsj_env)        goto abort;    /* If there's a Java exception associated with this error, save it too. */    java_exception = (*jEnv)->ExceptionOccurred(jEnv);    if (java_exception) {        (*jEnv)->ExceptionClear(jEnv);        tmp_exception = java_exception;     /* Make a copy */        java_exception = (*jEnv)->NewGlobalRef(jEnv, java_exception);        new_error->java_exception = java_exception;        (*jEnv)->DeleteLocalRef(jEnv, tmp_exception);    }    /* Push this error onto the list of pending JS errors */    new_error->next = jsj_env->pending_js_errors;    jsj_env->pending_js_errors = new_error;    jsj_ExitJava(jsj_env);    return;abort:out_of_memory:    /* No recovery action possible */    JS_ASSERT(0);    destroy_saved_js_error(jEnv, new_error);    return;}voidjsj_ClearPendingJSErrors(JSJavaThreadState *jsj_env){    while (jsj_env->pending_js_errors)        jsj_env->pending_js_errors = destroy_saved_js_error(jsj_env->jEnv, jsj_env->pending_js_errors);}/* * This is called upon returning from JS back into Java.  Any JS errors * reported during that time will be converted into Java exceptions.  It's

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -