Beispiel #1
0
static JSBool
obj_valueOf(JSContext *cx, JSObject *obj, uintN argc, jsval *argv, jsval *rval)
{
    *rval = OBJECT_TO_JSVAL(obj);
    return JS_TRUE;
}
Beispiel #2
0
JavaClass_getPropertyById(JSContext *cx, JSObject *obj, jsid id, jsval *vp)
{
    jsval idval;
    jclass java_class;
    const char *member_name;
    JavaClassDescriptor *class_descriptor;
    JavaMemberDescriptor *member_descriptor;
    JNIEnv *jEnv;
    JSJavaThreadState *jsj_env;
    JSBool result;

    /* printf("In JavaClass_getProperty\n"); */
    
    /* Get the Java per-thread environment pointer for this JSContext */
    jsj_env = jsj_EnterJava(cx, &jEnv);
    if (!jEnv)
        return JS_FALSE;

    if (!lookup_static_member_by_id(cx, jEnv, obj, &class_descriptor, id, &member_descriptor)) {
	jsj_ExitJava(jsj_env);
        return JS_FALSE;
    }
    if (!member_descriptor) {
        *vp = JSVAL_VOID;
	jsj_ExitJava(jsj_env);
        return JS_TRUE;
    }

    java_class = class_descriptor->java_class;

    if (member_descriptor->field) {
        if (!member_descriptor->methods) {
            result = jsj_GetJavaFieldValue(cx, jEnv, member_descriptor->field, java_class, vp);
	    jsj_ExitJava(jsj_env);
	    return result;
        } else {
            JS_ASSERT(0);
        }
    } else {
        JSFunction *function;
        
        /* TODO - eliminate JSFUN_BOUND_METHOD */
        if (member_descriptor->methods->is_alias) {
            /* If this is an explicit resolution of an overloaded method,
               use the fully-qualified method name as the name of the
               resulting JS function, i.e. "myMethod(int,long)" */
            JS_IdToValue(cx, id, &idval);
            member_name = JS_GetStringBytes(JSVAL_TO_STRING(idval));
        } else {
            /* Either not explicit resolution of overloaded method or
               explicit resolution was unnecessary because method was
               not overloaded. */
            member_name = member_descriptor->name;
        }
        function = JS_NewFunction(cx, jsj_JavaStaticMethodWrapper, 0,
                                  JSFUN_BOUND_METHOD, obj, member_name);
        if (!function) {
	    jsj_ExitJava(jsj_env);
            return JS_FALSE;
	}

        *vp = OBJECT_TO_JSVAL(JS_GetFunctionObject(function));
    }

    jsj_ExitJava(jsj_env);
    return JS_TRUE;
}
static bool js_cocos2dx_CCTableView_create(JSContext *cx, uint32_t argc, jsval *vp)
{
    JS::CallArgs args = JS::CallArgsFromVp(argc, vp);
    bool ok = true;
    if (argc == 3 || argc == 2)
    {

        JSB_TableViewDataSource* pNativeSource = new (std::nothrow) JSB_TableViewDataSource();
        JS::RootedObject jsdata(cx, args.get(0).toObjectOrNull());
        pNativeSource->setTableViewDataSource(jsdata);

        cocos2d::Size arg1;
        ok &= jsval_to_ccsize(cx, args.get(1), &arg1);
        cocos2d::extension::TableView* ret = NULL;
        ret = new (std::nothrow) TableView();
        ret->autorelease();

        ret->setDataSource(pNativeSource);

        jsval jsret;
        do {
            if (ret)
            {
                JS::RootedObject jsobj(cx, js_get_or_create_jsobject<cocos2d::extension::TableView>(cx, ret));
                jsret = OBJECT_TO_JSVAL(jsobj);

                JS_SetProperty(cx, jsobj, "_dataSource", args.get(0));
            }
            else
            {
                jsret = JSVAL_NULL;
            }
        } while (0);

        if (argc == 2)
        {
            ret->initWithViewSize(arg1);
        }
        else
        {
            cocos2d::Node* arg2;
            do
            {
                js_proxy_t *proxy;
                JS::RootedObject tmpObj(cx, args.get(2).toObjectOrNull());
                proxy = jsb_get_js_proxy(tmpObj);
                arg2 = (cocos2d::Node*)(proxy ? proxy->ptr : NULL);
                JSB_PRECONDITION2( arg2, cx, false, "Invalid Native Object");
            } while (0);
            JSB_PRECONDITION2(ok, cx, false, "Error processing arguments");
            ret->initWithViewSize(arg1, arg2);
        }
        ret->reloadData();

        __Dictionary* userDict = new (std::nothrow) __Dictionary();
        userDict->setObject(pNativeSource, KEY_TABLEVIEW_DATA_SOURCE);
        ret->setUserObject(userDict);
        userDict->release();

        pNativeSource->release();

        args.rval().set(jsret);
        return true;
    }

    JS_ReportError(cx, "wrong number of arguments");
    return false;
}
Beispiel #4
0
inline jsval object_to_jsval(JSObject *o) {
  return OBJECT_TO_JSVAL(o);
}
Beispiel #5
0
static JSBool
JO(JSContext *cx, jsval *vp, StringifyContext *scx)
{
    JSObject *obj = JSVAL_TO_OBJECT(*vp);

    if (!scx->cb.append('{'))
        return JS_FALSE;

    jsval vec[3] = {JSVAL_NULL, JSVAL_NULL, JSVAL_NULL};
    JSAutoTempValueRooter tvr(cx, 3, vec);
    jsval& key = vec[0];
    jsval& outputValue = vec[1];

    JSObject *iterObj = NULL;
    jsval *keySource = vp;
    bool usingWhitelist = false;

    // if the replacer is an array, we use the keys from it
    if (scx->replacer && JS_IsArrayObject(cx, scx->replacer)) {
        usingWhitelist = true;
        vec[2] = OBJECT_TO_JSVAL(scx->replacer);
        keySource = &vec[2];
    }

    if (!js_ValueToIterator(cx, JSITER_ENUMERATE, keySource))
        return JS_FALSE;
    iterObj = JSVAL_TO_OBJECT(*keySource);

    JSBool memberWritten = JS_FALSE;

    bool ok = false;
    while (true) {
        outputValue = JSVAL_VOID;
        if (!js_CallIteratorNext(cx, iterObj, &key))
            goto error_break;
        if (key == JSVAL_HOLE)
            break;

        jsuint index = 0;
        if (usingWhitelist) {
            // skip non-index properties
            if (!js_IdIsIndex(key, &index))
                continue;

            jsval newKey;
            if (!scx->replacer->getProperty(cx, key, &newKey))
                goto error_break;
            key = newKey;
        }

        JSString *ks;
        if (JSVAL_IS_STRING(key)) {
            ks = JSVAL_TO_STRING(key);
        } else {
            ks = js_ValueToString(cx, key);
            if (!ks)
                goto error_break;
        }
        JSAutoTempValueRooter keyStringRoot(cx, ks);

        // Don't include prototype properties, since this operation is
        // supposed to be implemented as if by ES3.1 Object.keys()
        jsid id;
        jsval v = JS_FALSE;
        if (!js_ValueToStringId(cx, STRING_TO_JSVAL(ks), &id) ||
            !js_HasOwnProperty(cx, obj->map->ops->lookupProperty, obj, id, &v)) {
            goto error_break;
        }

        if (v != JSVAL_TRUE)
            continue;

        if (!JS_GetPropertyById(cx, obj, id, &outputValue))
            goto error_break;

        if (JSVAL_IS_OBJECT(outputValue) && !js_TryJSON(cx, &outputValue))
            goto error_break;

        // call this here, so we don't write out keys if the replacer function
        // wants to elide the value.
        if (!CallReplacerFunction(cx, id, obj, scx, &outputValue))
            goto error_break;

        JSType type = JS_TypeOfValue(cx, outputValue);

        // elide undefined values and functions and XML
        if (outputValue == JSVAL_VOID || type == JSTYPE_FUNCTION || type == JSTYPE_XML)
            continue;

        // output a comma unless this is the first member to write
        if (memberWritten && !scx->cb.append(','))
            goto error_break;
        memberWritten = JS_TRUE;

        if (!WriteIndent(cx, scx, scx->depth))
            goto error_break;

        // Be careful below, this string is weakly rooted
        JSString *s = js_ValueToString(cx, key);
        if (!s)
            goto error_break;

        const jschar *chars;
        size_t length;
        s->getCharsAndLength(chars, length);
        if (!write_string(cx, scx->cb, chars, length) ||
            !scx->cb.append(':') ||
            !Str(cx, id, obj, scx, &outputValue, false)) {
            goto error_break;
        }
    }
    ok = true;

  error_break:
    if (iterObj) {
        // Always close the iterator, but make sure not to stomp on OK
        JS_ASSERT(OBJECT_TO_JSVAL(iterObj) == *keySource);
        ok &= js_CloseIterator(cx, *keySource);
    }

    if (!ok)
        return JS_FALSE;

    if (memberWritten && !WriteIndent(cx, scx, scx->depth - 1))
        return JS_FALSE;

    return scx->cb.append('}');
}
JSBool js_cocos2dx_CCBReader_createSceneWithNodeGraphFromFile(JSContext *cx, uint32_t argc, jsval *vp)
{
	jsval *argv = JS_ARGV(cx, vp);
    JSBool ok = JS_TRUE;
	JSObject *obj;
	cocos2d::extension::CCBReader* cobj;
	obj = JS_THIS_OBJECT(cx, vp);
	js_proxy_t *proxy = jsb_get_js_proxy(obj);
	cobj = (cocos2d::extension::CCBReader *)(proxy ? proxy->ptr : NULL);
	TEST_NATIVE_OBJECT(cx, cobj)
    
	if (argc == 2) {
		const char* arg0;
		std::string arg0_tmp; ok &= jsval_to_std_string(cx, argv[0], &arg0_tmp); arg0 = arg0_tmp.c_str();
		cocos2d::CCObject* arg1;
		do {
			js_proxy_t *proxy;
			JSObject *tmpObj = JSVAL_TO_OBJECT(argv[1]);
			proxy = jsb_get_js_proxy(tmpObj);
			arg1 = (cocos2d::CCObject*)(proxy ? proxy->ptr : NULL);
			TEST_NATIVE_OBJECT(cx, arg1)
		} while (0);
        
        JSB_PRECONDITION2(ok, cx, JS_FALSE, "Error processing arguments");
        
		cocos2d::CCScene* ret = cobj->createSceneWithNodeGraphFromFile(arg0, arg1);
		jsval jsret; do {
			if (ret) {
				js_proxy_t *proxy = js_get_or_create_proxy<cocos2d::CCScene>(cx, ret);
				jsret = OBJECT_TO_JSVAL(proxy->obj);
			} else {
				jsret = JSVAL_NULL;
			}
		} while (0);
		JS_SET_RVAL(cx, vp, jsret);
		return JS_TRUE;
	}
	if (argc == 1) {
		const char* arg0;
		std::string arg0_tmp; ok &= jsval_to_std_string(cx, argv[0], &arg0_tmp); arg0 = arg0_tmp.c_str();
        JSB_PRECONDITION2(ok, cx, JS_FALSE, "Error processing arguments");
        
		cocos2d::CCScene* ret = cobj->createSceneWithNodeGraphFromFile(arg0);
		jsval jsret; do {
			if (ret) {
				js_proxy_t *proxy = js_get_or_create_proxy<cocos2d::CCScene>(cx, ret);
				jsret = OBJECT_TO_JSVAL(proxy->obj);
			} else {
				jsret = JSVAL_NULL;
			}
		} while (0);
		JS_SET_RVAL(cx, vp, jsret);
		return JS_TRUE;
	}
	if (argc == 3) {
		const char* arg0;
		std::string arg0_tmp; ok &= jsval_to_std_string(cx, argv[0], &arg0_tmp); arg0 = arg0_tmp.c_str();
		cocos2d::CCObject* arg1;
		do {
			js_proxy_t *proxy;
			JSObject *tmpObj = JSVAL_TO_OBJECT(argv[1]);
			proxy = jsb_get_js_proxy(tmpObj);
			arg1 = (cocos2d::CCObject*)(proxy ? proxy->ptr : NULL);
			TEST_NATIVE_OBJECT(cx, arg1)
		} while (0);
		cocos2d::CCSize arg2;
        ok &= jsval_to_ccsize(cx, argv[2], &arg2);
        
        JSB_PRECONDITION2(ok, cx, JS_FALSE, "Error processing arguments");
        
		cocos2d::CCScene* ret = cobj->createSceneWithNodeGraphFromFile(arg0, arg1, arg2);
		jsval jsret; do {
			if (ret) {
				js_proxy_t *proxy = js_get_or_create_proxy<cocos2d::CCScene>(cx, ret);
				jsret = OBJECT_TO_JSVAL(proxy->obj);
			} else {
				jsret = JSVAL_NULL;
			}
		} while (0);
		JS_SET_RVAL(cx, vp, jsret);
		return JS_TRUE;
	}
    
    return JS_FALSE;
}
bool js_cocos2dx_spine_SkeletonAnimation_constructor(JSContext *cx, uint32_t argc, jsval *vp)
{
	jsval *argv = JS_ARGV(cx, vp);
	bool ok = true;

	JSObject *obj = NULL;
	spine::SkeletonAnimation* cobj = NULL;
	do {
		if (argc == 2) {
			const char* arg0;
			std::string arg0_tmp; ok &= jsval_to_std_string(cx, argv[0], &arg0_tmp); arg0 = arg0_tmp.c_str();
			if (!ok) { ok = true; break; }
			spAtlas* arg1;
			#pragma warning NO CONVERSION TO NATIVE FOR spAtlas*
			ok = false;
			if (!ok) { ok = true; break; }
			cobj = new (std::nothrow) spine::SkeletonAnimation(arg0, arg1);
			cocos2d::Ref *_ccobj = dynamic_cast<cocos2d::Ref *>(cobj);
			if (_ccobj) {
				_ccobj->autorelease();
			}
			TypeTest<spine::SkeletonAnimation> t;
			js_type_class_t *typeClass = nullptr;
			std::string typeName = t.s_name();
			auto typeMapIter = _js_global_type_map.find(typeName);
			CCASSERT(typeMapIter != _js_global_type_map.end(), "Can't find the class type!");
			typeClass = typeMapIter->second;
			CCASSERT(typeClass, "The value is null.");
			obj = JS_NewObject(cx, typeClass->jsclass, typeClass->proto, typeClass->parentProto);
			js_proxy_t* p = jsb_new_proxy(cobj, obj);
			JS_AddNamedObjectRoot(cx, &p->obj, "spine::SkeletonAnimation");
		}
	} while(0);

	do {
		if (argc == 3) {
			const char* arg0;
			std::string arg0_tmp; ok &= jsval_to_std_string(cx, argv[0], &arg0_tmp); arg0 = arg0_tmp.c_str();
			if (!ok) { ok = true; break; }
			spAtlas* arg1;
			#pragma warning NO CONVERSION TO NATIVE FOR spAtlas*
			ok = false;
			if (!ok) { ok = true; break; }
			double arg2;
			ok &= JS::ToNumber( cx, JS::RootedValue(cx, argv[2]), &arg2);
			if (!ok) { ok = true; break; }
			cobj = new (std::nothrow) spine::SkeletonAnimation(arg0, arg1, arg2);
			cocos2d::Ref *_ccobj = dynamic_cast<cocos2d::Ref *>(cobj);
			if (_ccobj) {
				_ccobj->autorelease();
			}
			TypeTest<spine::SkeletonAnimation> t;
			js_type_class_t *typeClass = nullptr;
			std::string typeName = t.s_name();
			auto typeMapIter = _js_global_type_map.find(typeName);
			CCASSERT(typeMapIter != _js_global_type_map.end(), "Can't find the class type!");
			typeClass = typeMapIter->second;
			CCASSERT(typeClass, "The value is null.");
			obj = JS_NewObject(cx, typeClass->jsclass, typeClass->proto, typeClass->parentProto);
			js_proxy_t* p = jsb_new_proxy(cobj, obj);
			JS_AddNamedObjectRoot(cx, &p->obj, "spine::SkeletonAnimation");
		}
	} while(0);

	do {
		if (argc == 1) {
			spSkeletonData* arg0;
			#pragma warning NO CONVERSION TO NATIVE FOR spSkeletonData*
			ok = false;
			if (!ok) { ok = true; break; }
			cobj = new (std::nothrow) spine::SkeletonAnimation(arg0);
			cocos2d::Ref *_ccobj = dynamic_cast<cocos2d::Ref *>(cobj);
			if (_ccobj) {
				_ccobj->autorelease();
			}
			TypeTest<spine::SkeletonAnimation> t;
			js_type_class_t *typeClass = nullptr;
			std::string typeName = t.s_name();
			auto typeMapIter = _js_global_type_map.find(typeName);
			CCASSERT(typeMapIter != _js_global_type_map.end(), "Can't find the class type!");
			typeClass = typeMapIter->second;
			CCASSERT(typeClass, "The value is null.");
			obj = JS_NewObject(cx, typeClass->jsclass, typeClass->proto, typeClass->parentProto);
			js_proxy_t* p = jsb_new_proxy(cobj, obj);
			JS_AddNamedObjectRoot(cx, &p->obj, "spine::SkeletonAnimation");
		}
	} while(0);

	do {
		if (argc == 2) {
			const char* arg0;
			std::string arg0_tmp; ok &= jsval_to_std_string(cx, argv[0], &arg0_tmp); arg0 = arg0_tmp.c_str();
			if (!ok) { ok = true; break; }
			const char* arg1;
			std::string arg1_tmp; ok &= jsval_to_std_string(cx, argv[1], &arg1_tmp); arg1 = arg1_tmp.c_str();
			if (!ok) { ok = true; break; }
			cobj = new (std::nothrow) spine::SkeletonAnimation(arg0, arg1);
			cocos2d::Ref *_ccobj = dynamic_cast<cocos2d::Ref *>(cobj);
			if (_ccobj) {
				_ccobj->autorelease();
			}
			TypeTest<spine::SkeletonAnimation> t;
			js_type_class_t *typeClass = nullptr;
			std::string typeName = t.s_name();
			auto typeMapIter = _js_global_type_map.find(typeName);
			CCASSERT(typeMapIter != _js_global_type_map.end(), "Can't find the class type!");
			typeClass = typeMapIter->second;
			CCASSERT(typeClass, "The value is null.");
			obj = JS_NewObject(cx, typeClass->jsclass, typeClass->proto, typeClass->parentProto);
			js_proxy_t* p = jsb_new_proxy(cobj, obj);
			JS_AddNamedObjectRoot(cx, &p->obj, "spine::SkeletonAnimation");
		}
	} while(0);

	do {
		if (argc == 3) {
			const char* arg0;
			std::string arg0_tmp; ok &= jsval_to_std_string(cx, argv[0], &arg0_tmp); arg0 = arg0_tmp.c_str();
			if (!ok) { ok = true; break; }
			const char* arg1;
			std::string arg1_tmp; ok &= jsval_to_std_string(cx, argv[1], &arg1_tmp); arg1 = arg1_tmp.c_str();
			if (!ok) { ok = true; break; }
			double arg2;
			ok &= JS::ToNumber( cx, JS::RootedValue(cx, argv[2]), &arg2);
			if (!ok) { ok = true; break; }
			cobj = new (std::nothrow) spine::SkeletonAnimation(arg0, arg1, arg2);
			cocos2d::Ref *_ccobj = dynamic_cast<cocos2d::Ref *>(cobj);
			if (_ccobj) {
				_ccobj->autorelease();
			}
			TypeTest<spine::SkeletonAnimation> t;
			js_type_class_t *typeClass = nullptr;
			std::string typeName = t.s_name();
			auto typeMapIter = _js_global_type_map.find(typeName);
			CCASSERT(typeMapIter != _js_global_type_map.end(), "Can't find the class type!");
			typeClass = typeMapIter->second;
			CCASSERT(typeClass, "The value is null.");
			obj = JS_NewObject(cx, typeClass->jsclass, typeClass->proto, typeClass->parentProto);
			js_proxy_t* p = jsb_new_proxy(cobj, obj);
			JS_AddNamedObjectRoot(cx, &p->obj, "spine::SkeletonAnimation");
		}
	} while(0);

	if (cobj) {
		if (JS_HasProperty(cx, obj, "_ctor", &ok))
        		ScriptingCore::getInstance()->executeFunctionWithOwner(OBJECT_TO_JSVAL(obj), "_ctor", argc, argv);

		JS_SET_RVAL(cx, vp, OBJECT_TO_JSVAL(obj));
		return true;
	}
	JS_ReportError(cx, "js_cocos2dx_spine_SkeletonAnimation_constructor : wrong number of arguments");
	return false;
}
Beispiel #8
0
static JSBool js_get(JSContext *cx, JSObject *obj, jsval id, jsval *vp)
{
    jsint			tiny;
    js_branch_t*	branch;

    if((branch=(js_branch_t*)JS_GetPrivate(cx,obj))==NULL)
        return(JS_FALSE);

    tiny = JSVAL_TO_INT(id);

    switch(tiny) {
    case PROP_VERSION:
        *vp=STRING_TO_JSVAL(JS_NewStringCopyZ(cx,(char *)JS_GetImplementationVersion()));
        break;
    case PROP_TERMINATED:
        if(branch->terminated==NULL)
            *vp=JSVAL_FALSE;
        else
            *vp=BOOLEAN_TO_JSVAL(*branch->terminated);
        break;
    case PROP_AUTO_TERMINATE:
        *vp=BOOLEAN_TO_JSVAL(branch->auto_terminate);
        break;
    case PROP_BRANCH_COUNTER:
        JS_NewNumberValue(cx,branch->counter,vp);
        break;
    case PROP_BRANCH_LIMIT:
        JS_NewNumberValue(cx,branch->limit,vp);
        break;
    case PROP_YIELD_INTERVAL:
        JS_NewNumberValue(cx,branch->yield_interval,vp);
        break;
    case PROP_GC_INTERVAL:
        JS_NewNumberValue(cx,branch->gc_interval,vp);
        break;
    case PROP_GC_ATTEMPTS:
        JS_NewNumberValue(cx,branch->gc_attempts,vp);
        break;
#ifdef jscntxt_h___
    case PROP_GC_COUNTER:
        JS_NewNumberValue(cx,cx->runtime->gcNumber,vp);
        break;
    case PROP_GC_LASTBYTES:
        JS_NewNumberValue(cx,cx->runtime->gcLastBytes,vp);
        break;
    case PROP_BYTES:
        JS_NewNumberValue(cx,cx->runtime->gcBytes,vp);
        break;
    case PROP_MAXBYTES:
        JS_NewNumberValue(cx,cx->runtime->gcMaxBytes,vp);
        break;
    case PROP_GLOBAL:
        *vp = OBJECT_TO_JSVAL(cx->globalObject);
        break;
#else
    case PROP_GLOBAL:
        *vp = OBJECT_TO_JSVAL(JS_GetParent(cx,obj));
        break;
#endif
    }

    return(JS_TRUE);
}
Beispiel #9
0
static JSObject *
load_module_init(JSContext  *context,
                 JSObject   *in_object,
                 const char *full_path)
{
    char *script;
    gsize script_len;
    jsval script_retval;
    JSObject *module_obj;
    GError *error;

    /* First we check if js module has already been loaded  */
    if (gjs_object_has_property(context, in_object, MODULE_INIT_PROPERTY)) {
        jsval module_obj_val;

        if (gjs_object_get_property(context,
                                    in_object,
                                    MODULE_INIT_PROPERTY,
                                    &module_obj_val)) {
            return JSVAL_TO_OBJECT(module_obj_val);
        }
    }

    module_obj = JS_NewObject(context, NULL, NULL, NULL);
    if (module_obj == NULL) {
        return JS_FALSE;
    }

    /* https://bugzilla.mozilla.org/show_bug.cgi?id=599651 means we
     * can't just pass in the global as the parent */
    JS_SetParent(context, module_obj,
                 gjs_get_import_global (context));

    /* Define module in importer for future use and to avoid module_obj
     * object to be garbage collected during the evaluation of the script */
    JS_DefineProperty(context, in_object,
                      MODULE_INIT_PROPERTY, OBJECT_TO_JSVAL(module_obj),
                      NULL, NULL,
                      GJS_MODULE_PROP_FLAGS & ~JSPROP_PERMANENT);

    script_len = 0;
    error = NULL;

    if (!g_file_get_contents(full_path, &script, &script_len, &error)) {
        if (!g_error_matches(error, G_FILE_ERROR, G_FILE_ERROR_ISDIR) &&
            !g_error_matches(error, G_FILE_ERROR, G_FILE_ERROR_NOTDIR) &&
            !g_error_matches(error, G_FILE_ERROR, G_FILE_ERROR_NOENT))
            gjs_throw_g_error(context, error);
        else
            g_error_free(error);

        return NULL;
    }

    g_assert(script != NULL);

    gjs_debug(GJS_DEBUG_IMPORTER, "Importing %s", full_path);

    if (!JS_EvaluateScript(context,
                           module_obj,
                           script,
                           script_len,
                           full_path,
                           1, /* line number */
                           &script_retval)) {
        g_free(script);

        /* If JSOPTION_DONT_REPORT_UNCAUGHT is set then the exception
         * would be left set after the evaluate and not go to the error
         * reporter function.
         */
        if (JS_IsExceptionPending(context)) {
            gjs_debug(GJS_DEBUG_IMPORTER,
                      "Module " MODULE_INIT_FILENAME " left an exception set");
            gjs_log_and_keep_exception(context, NULL);
        } else {
            gjs_throw(context,
                      "JS_EvaluateScript() returned FALSE but did not set exception");
        }

        return NULL;
    }

    g_free(script);

    return module_obj;
}
void SG_vc_hooks__execute(
        SG_context* pCtx, 
        const char* psz_js,
        SG_vhash* pvh_params,
        SG_vhash** ppvh_result
        )
{
	jsval rval;
    JSContext* cx = NULL;
    JSObject* glob = NULL;
    SG_vhash* pvh_result = NULL;
    JSObject* jso_params = NULL;

	SG_NULLARGCHECK_RETURN(psz_js);

    SG_jscore__new_runtime(pCtx, NULL, global_functions, SG_FALSE, NULL);
    SG_ERR_CHECK_CURRENT_DISREGARD(SG_ERR_ALREADY_INITIALIZED);
    SG_ERR_CHECK(  SG_jscore__new_context(pCtx, &cx, &glob, NULL)  );
	
	//This should tell the javascript engine how to report javascript errors to our jsglue.
	JS_SetErrorReporter(cx,SG_jsglue__error_reporter);

	if(!JS_EvaluateScript(cx, glob, psz_js, (uintN) strlen(psz_js), "hook_script", 1, &rval))
	{
		SG_ERR_CHECK_CURRENT;
		SG_ERR_THROW2(SG_ERR_UNSPECIFIED, (pCtx, "An error occurred evaluating hook"));
	}

    // note that we don't care about the rval from eval of the script

	{
		jsval params;
		jsval rval;
		
        if (pvh_params)
        {
            jso_params = JS_NewObject(cx, NULL, NULL, NULL);
            if(!jso_params)
                SG_ERR_THROW2(SG_ERR_MALLOCFAILED, (pCtx, "Failed to create new JS object for params to vc hook."));
            params = OBJECT_TO_JSVAL(jso_params);
            SG_ERR_CHECK(  sg_jsglue__copy_vhash_into_jsobject(pCtx, cx, pvh_params, jso_params)  );
        }
        else
        {
            params = JSVAL_NULL;
        }

		if(!JS_CallFunctionName(cx, glob, "hook", 1, &params, &rval))
		{
			SG_ERR_CHECK_CURRENT;
			SG_ERR_THROW2(SG_ERR_UNSPECIFIED, (pCtx, "An error occurred calling JS hook"));
		}

        if (JSVAL_IS_OBJECT(rval))
        {
            SG_ERR_CHECK(  sg_jsglue__jsobject_to_vhash(pCtx, cx, JSVAL_TO_OBJECT(rval), &pvh_result)  );
        }
	}

    if (ppvh_result)
    {
        *ppvh_result = pvh_result;
        pvh_result = NULL;
    }

fail:
    if (cx)
    {
		SG_ERR_IGNORE(  SG_jsglue__set_sg_context(NULL, cx)  );

		JS_EndRequest(cx);
		JS_DestroyContext(cx);

    }

    SG_VHASH_NULLFREE(pCtx, pvh_result);
}
Beispiel #11
0
void
SmsRequest::NotifyThreadList(const InfallibleTArray<ThreadListItem>& aItems)
{
  MOZ_ASSERT(!mParent);
  MOZ_ASSERT(GetOwner());

  nsresult rv;
  nsIScriptContext* sc = GetContextForEventHandlers(&rv);
  NS_ENSURE_SUCCESS_VOID(rv);
  NS_ENSURE_TRUE_VOID(sc);

  JSContext* cx = sc->GetNativeContext();
  MOZ_ASSERT(cx);

  nsCOMPtr<nsIScriptGlobalObject> sgo = do_QueryInterface(GetOwner());

  JSObject* ownerObj = sgo->GetGlobalJSObject();
  NS_ENSURE_TRUE_VOID(ownerObj);

  nsCxPusher pusher;
  NS_ENSURE_TRUE_VOID(pusher.Push(cx, false));

  JSAutoRequest ar(cx);
  JSAutoCompartment ac(cx, ownerObj);

  JSObject* array = JS_NewArrayObject(cx, aItems.Length(), nullptr);
  NS_ENSURE_TRUE_VOID(array);

  bool ok;

  for (uint32_t i = 0; i < aItems.Length(); i++) {
    const ThreadListItem& source = aItems[i];

    nsString temp = source.senderOrReceiver();

    jsval senderOrReceiver;
    ok = xpc::StringToJsval(cx, temp, &senderOrReceiver);
    NS_ENSURE_TRUE_VOID(ok);

    JSObject* timestampObj = JS_NewDateObjectMsec(cx, source.timestamp());
    NS_ENSURE_TRUE_VOID(timestampObj);

    jsval timestamp = OBJECT_TO_JSVAL(timestampObj);

    temp = source.body();

    jsval body;
    ok = xpc::StringToJsval(cx, temp, &body);
    NS_ENSURE_TRUE_VOID(ok);

    jsval unreadCount = JS_NumberValue(double(source.unreadCount()));

    JSObject* elementObj = JS_NewObject(cx, nullptr, nullptr, nullptr);
    NS_ENSURE_TRUE_VOID(elementObj);

    ok = JS_SetProperty(cx, elementObj, "senderOrReceiver", &senderOrReceiver);
    NS_ENSURE_TRUE_VOID(ok);

    ok = JS_SetProperty(cx, elementObj, "timestamp", &timestamp);
    NS_ENSURE_TRUE_VOID(ok);

    ok = JS_SetProperty(cx, elementObj, "body", &body);
    NS_ENSURE_TRUE_VOID(ok);

    ok = JS_SetProperty(cx, elementObj, "unreadCount", &unreadCount);
    NS_ENSURE_TRUE_VOID(ok);

    jsval element = OBJECT_TO_JSVAL(elementObj);

    ok = JS_SetElement(cx, array, i, &element);
    NS_ENSURE_TRUE_VOID(ok);
  }

  NotifyThreadList(OBJECT_TO_JSVAL(array), cx);
}
Beispiel #12
0
/*
 * This is a wrapper around JS_ReportError(), useful when an error condition
 * is the result of a JVM failure or exception condition.  It appends the
 * message associated with the pending Java exception to the passed in
 * printf-style format string and arguments.
 */
static void
vreport_java_error(JSContext *cx, JNIEnv *jEnv, const char *format, va_list ap)
{
    jobject java_obj;
    jclass java_class;
    JavaClassDescriptor *class_descriptor;
    jthrowable java_exception;
    JSType wrapped_exception_type;
    jsval js_exception;
       
    java_obj = NULL;
    class_descriptor = NULL;

    /* Get the exception out of the java environment. */
    java_exception = (*jEnv)->ExceptionOccurred(jEnv);
    if (!java_exception) {
        JSString *err_jsstr;
        char *err = JS_vsmprintf(format, ap);
        if (!err)
            return;
        err_jsstr = JS_NewString(cx, err, strlen(err));
        if (!err_jsstr)
            return;
        JS_SetPendingException(cx, STRING_TO_JSVAL(err_jsstr));
        return;
    }

    
    (*jEnv)->ExceptionClear(jEnv);
    
    /* Check for JSException */
    if (njJSException && 
        (*jEnv)->IsInstanceOf(jEnv, java_exception, njJSException)) {
        
        wrapped_exception_type = 
            (*jEnv)->GetIntField(jEnv, java_exception,
            njJSException_wrappedExceptionType);
        
        /* (int) to suppress warning */
        if ((int)wrapped_exception_type != JSTYPE_EMPTY) {
            java_obj = 
                (*jEnv)->GetObjectField(jEnv, java_exception, 
                njJSException_wrappedException);
            
            if ((java_obj == NULL) && 
                (wrapped_exception_type == JSTYPE_OBJECT)) {
                js_exception = JSVAL_NULL;
            } else { 
                java_class = (*jEnv)->GetObjectClass(jEnv, java_obj); 
                class_descriptor = jsj_GetJavaClassDescriptor(cx, jEnv, java_class);
                /* OK to delete ref, since above call adds global ref */
                (*jEnv)->DeleteLocalRef(jEnv, java_class);  
                
                /* Convert native JS values back to native types. */
                switch(wrapped_exception_type) {
                case JSTYPE_NUMBER:
                    if (!jsj_ConvertJavaObjectToJSNumber(cx, jEnv,
                        class_descriptor,
                        java_obj, 
                        &js_exception))
                        goto error;
                    break;
                case JSTYPE_BOOLEAN:
                    if (!jsj_ConvertJavaObjectToJSBoolean(cx, jEnv,
                        class_descriptor,
                        java_obj, 
                        &js_exception))
                        goto error;
                    break;
                case JSTYPE_STRING:
                    if (!jsj_ConvertJavaObjectToJSString(cx, jEnv,
                        class_descriptor,
                        java_obj, 
                        &js_exception))
                        goto error;
                    break;
                case JSTYPE_VOID:
                    js_exception = JSVAL_VOID;
                    break;
                case JSTYPE_OBJECT:
                case JSTYPE_FUNCTION:
                default:
                    if ((*jEnv)->IsInstanceOf(jEnv, java_obj, njJSObject)) {
                        js_exception = OBJECT_TO_JSVAL(jsj_UnwrapJSObjectWrapper(jEnv, java_obj));
                        if (!js_exception)
                            goto error;                        
                    } else {
                        if (!jsj_ConvertJavaObjectToJSValue(cx, jEnv, java_obj, 
                            &js_exception)) 
                            goto error;
                    }
                }
            }
        }
        /* Check for internal exception */
    } else {
        if (!JSJ_ConvertJavaObjectToJSValue(cx, java_exception,
            &js_exception)) {
            goto error;
        }
    }
    
    /* Set pending JS exception and clear the java exception. */
    JS_SetPendingException(cx, js_exception);                        
    goto done;

error:
    
    JS_ASSERT(0);
    jsj_LogError("Out of memory while attempting to throw JSException\n");
    
done:
    if (class_descriptor)
        jsj_ReleaseJavaClassDescriptor(cx, jEnv, class_descriptor);
    if (java_obj)
        (*jEnv)->DeleteLocalRef(jEnv, java_obj);
    if (java_exception)
        (*jEnv)->DeleteLocalRef(jEnv, java_exception);
}
Beispiel #13
0
jsval as_jsval(JSContext *cx, cairo::JSSurface::OWNERPTR theOwner, cairo::JSSurface::NATIVE * theNative) {
    JSObject * myReturnObject = cairo::JSSurface::Construct(cx, theOwner, theNative);
    return OBJECT_TO_JSVAL(myReturnObject);
}
Beispiel #14
0
static JSBool
obj_watch(JSContext *cx, JSObject *obj, uintN argc, jsval *argv, jsval *rval)
{
    JSFunction *fun;
    jsval userid, symid, propid, value;
    JSAtom *atom;
    JSRuntime *rt;
    JSBool ok;
    JSProperty *prop;
    JSPropertyOp getter, setter;
    JSClass *clasp;

    fun = JS_ValueToFunction(cx, argv[1]);
    if (!fun)
	return JS_FALSE;
    argv[1] = OBJECT_TO_JSVAL(fun->object);

    /*
     * Lock the world while we look in obj.  Be sure to return via goto out
     * on error, so we unlock.
     */
    rt = cx->runtime;
    JS_LOCK_RUNTIME(rt);

    /* Compute the unique int/atom symbol id needed by js_LookupProperty. */
    userid = argv[0];
    if (JSVAL_IS_INT(userid)) {
	symid = userid;
	atom = NULL;
    } else {
	atom = js_ValueToStringAtom(cx, userid);
	if (!atom) {
	    ok = JS_FALSE;
	    goto out;
	}
	symid = (jsval)atom;
    }

    ok = js_LookupProperty(cx, obj, symid, &obj, &prop);
    if (atom)
	js_DropAtom(cx, atom);
    if (!ok)
	goto out;

    /* Set propid from the property, in case it has a tinyid. */
    if (prop) {
	propid = prop->id;
	getter = prop->getter;
	setter = prop->setter;
	value = prop->object->slots[prop->slot];
    } else {
	propid = userid;
	clasp = obj->map->clasp;
	getter = clasp->getProperty;
	setter = clasp->setProperty;
	value = JSVAL_VOID;
    }

    /*
     * Security policy is implemented in getters and setters, so we have to
     * call get and set here to let the JS API client check for a watchpoint
     * that crosses a trust boundary.
     * XXX assumes get and set are idempotent, should use a clasp->watch hook
     */
    ok = getter(cx, obj, propid, &value) && setter(cx, obj, propid, &value);
    if (!ok)
	goto out;

    /* Finally, call into jsdbgapi.c to set the watchpoint on userid. */
    ok = JS_SetWatchPoint(cx, obj, userid, obj_watch_handler, fun->object);

out:
    JS_UNLOCK_RUNTIME(rt);
    return ok;
}
JSBool XPCIDispatchExtension::DefineProperty(XPCCallContext & ccx,
        JSObject *obj, jsval idval,
        XPCWrappedNative* wrapperToReflectInterfaceNames,
        uintN propFlags, JSBool* resolved)
{
    if(!JSVAL_IS_STRING(idval))
        return JS_FALSE;
    // Look up the native interface for IDispatch and then find a tearoff
    XPCNativeInterface* iface = XPCNativeInterface::GetNewOrUsed(ccx,
                                "IDispatch");
    // The native interface isn't defined so just exit with an error
    if(iface == nsnull)
        return JS_FALSE;
    XPCWrappedNativeTearOff* to =
        wrapperToReflectInterfaceNames->LocateTearOff(ccx, iface);
    // This object has no IDispatch interface so bail.
    if(to == nsnull)
        return JS_FALSE;
    // Look up the member in the interface
    const XPCDispInterface::Member * member = to->GetIDispatchInfo()->FindMember(idval);
    if(!member)
    {
        // IDispatch is case insensitive, so if we don't find a case sensitive
        // match, we'll try a more expensive case-insensisitive search
        // TODO: We need to create cleaner solution that doesn't create
        // multiple properties of different case on the JS Object
        member = to->GetIDispatchInfo()->FindMemberCI(ccx, idval);
        if(!member)
            return JS_FALSE;
    }
    // Get the function object
    jsval funval;
    if(!member->GetValue(ccx, iface, &funval))
        return JS_FALSE;
    // Protect the jsval
    AUTO_MARK_JSVAL(ccx, funval);
    // clone a function we can use for this object
    JSObject* funobj = xpc_CloneJSFunction(ccx, JSVAL_TO_OBJECT(funval), obj);
    if(!funobj)
        return JS_FALSE;
    jsid id;
    // If this is a function or a parameterized property
    if(member->IsFunction() || member->IsParameterizedProperty())
    {
        // define the function on the object
        AutoResolveName arn(ccx, idval);
        if(resolved)
            *resolved = JS_TRUE;
        return JS_ValueToId(ccx, idval, &id) &&
               OBJ_DEFINE_PROPERTY(ccx, obj, id, OBJECT_TO_JSVAL(funobj),
                                   nsnull, nsnull, propFlags, nsnull);
    }
    // Define the property on the object
    NS_ASSERTION(member->IsProperty(), "way broken!");
    propFlags |= JSPROP_GETTER | JSPROP_SHARED;
    if(member->IsSetter())
    {
        propFlags |= JSPROP_SETTER;
        propFlags &= ~JSPROP_READONLY;
    }
    AutoResolveName arn(ccx, idval);
    if(resolved)
        *resolved = JS_TRUE;
    return JS_ValueToId(ccx, idval, &id) &&
           OBJ_DEFINE_PROPERTY(ccx, obj, id, JSVAL_VOID,
                               (JSPropertyOp) funobj,
                               (JSPropertyOp) funobj,
                               propFlags, nsnull);

}
Beispiel #16
0
jsval CStdDeserializer::ReadScriptVal(JSObject* appendParent)
{
	JSContext* cx = m_ScriptInterface.GetContext();

	uint8_t type;
	NumberU8_Unbounded("type", type);
	switch (type)
	{
	case SCRIPT_TYPE_VOID:
		return JSVAL_VOID;

	case SCRIPT_TYPE_NULL:
		return JSVAL_NULL;

	case SCRIPT_TYPE_ARRAY:
	case SCRIPT_TYPE_OBJECT:
	{
		JSObject* obj;
		if (appendParent)
			obj = appendParent;
		else if (type == SCRIPT_TYPE_ARRAY)
			obj = JS_NewArrayObject(cx, 0, NULL);
		else
			obj = JS_NewObject(cx, NULL, NULL, NULL);

		if (!obj)
			throw PSERROR_Deserialize_ScriptError();
		CScriptValRooted objRoot(cx, OBJECT_TO_JSVAL(obj));

		AddScriptBackref(obj);

		uint32_t numProps;
		NumberU32_Unbounded("num props", numProps);

		for (uint32_t i = 0; i < numProps; ++i)
		{
			utf16string propname;
			ReadStringUTF16(propname);

			jsval propval = ReadScriptVal(NULL);
			CScriptValRooted propvalRoot(cx, propval);

			if (!JS_SetUCProperty(cx, obj, (const jschar*)propname.data(), propname.length(), &propval))
				throw PSERROR_Deserialize_ScriptError();
		}

		return OBJECT_TO_JSVAL(obj);
	}
	case SCRIPT_TYPE_STRING:
	{
		JSString* str;
		ScriptString("string", str);
		return STRING_TO_JSVAL(str);
	}
	case SCRIPT_TYPE_INT:
	{
		int32_t value;
		NumberI32("value", value, JSVAL_INT_MIN, JSVAL_INT_MAX);
		return INT_TO_JSVAL(value);
	}
	case SCRIPT_TYPE_DOUBLE:
	{
		double value;
		NumberDouble_Unbounded("value", value);
		jsval rval;
		if (!JS_NewNumberValue(cx, value, &rval))
			throw PSERROR_Deserialize_ScriptError("JS_NewNumberValue failed");
		return rval;
	}
	case SCRIPT_TYPE_BOOLEAN:
	{
		uint8_t value;
		NumberU8("value", value, 0, 1);
		return BOOLEAN_TO_JSVAL(value ? JS_TRUE : JS_FALSE);
	}
	case SCRIPT_TYPE_BACKREF:
	{
		u32 tag;
		NumberU32_Unbounded("tag", tag);
		JSObject* obj = GetScriptBackref(tag);
		if (!obj)
			throw PSERROR_Deserialize_ScriptError("Invalid backref tag");
		return OBJECT_TO_JSVAL(obj);
	}
	default:
		throw PSERROR_Deserialize_OutOfBounds();
	}
}
static JSBool
CommonConstructor(JSContext *cx, int name, JSObject *obj, uintN argc,
                  jsval *argv, jsval *rval, PRBool enforceSecurity)
{
    XPCCallContext ccx(JS_CALLER, cx, JS_GetGlobalObject(cx));
    // Check if IDispatch is enabled, fail if not
    if(!nsXPConnect::IsIDispatchEnabled())
    {
        XPCThrower::Throw(NS_ERROR_XPC_IDISPATCH_NOT_ENABLED, ccx);
        return JS_FALSE;
    }
    XPCJSRuntime *rt = ccx.GetRuntime();
    if(!rt)
    {
        XPCThrower::Throw(NS_ERROR_UNEXPECTED, ccx);
        return JS_FALSE;
    }
    nsIXPCSecurityManager* sm = ccx.GetXPCContext()
                                ->GetAppropriateSecurityManager(nsIXPCSecurityManager::HOOK_CALL_METHOD);
    XPCWrappedNative * wrapper = ccx.GetWrapper();
    if(sm && NS_FAILED(sm->CanAccess(nsIXPCSecurityManager::ACCESS_CALL_METHOD,
                                     &ccx, ccx, ccx.GetFlattenedJSObject(),
                                     wrapper->GetIdentityObject(),
                                     wrapper->GetClassInfo(),
                                     rt->GetStringJSVal(name),
                                     wrapper->GetSecurityInfoAddr())))
    {
        // Security manager will have set an exception
        return JS_FALSE;
    }
    // Make sure we were called with one string parameter
    if(argc != 1 || (argc == 1 && !JSVAL_IS_STRING(argv[0])))
    {
        XPCThrower::Throw(NS_ERROR_XPC_COM_INVALID_CLASS_ID, ccx);
        return JS_FALSE;
    }

    JSString* str = JSVAL_TO_STRING(argv[0]);
    PRUint32 len = JS_GetStringLength(str);

    // Cap constructor argument length to keep from crashing in string
    // code.
    if(len > XPC_IDISPATCH_CTOR_MAX_ARG_LEN)
    {
        XPCThrower::Throw(NS_ERROR_XPC_COM_INVALID_CLASS_ID, ccx);
        return JS_FALSE;
    }

    jschar * className = JS_GetStringChars(str);
    CComBSTR bstrClassName(len, reinterpret_cast<const WCHAR *>(className));
    if(!bstrClassName)
    {
        XPCThrower::Throw(NS_ERROR_XPC_COM_INVALID_CLASS_ID, ccx);
        return JS_FALSE;
    }
    // Instantiate the desired COM object
    CComPtr<IDispatch> pDispatch;
    HRESULT rv = XPCDispObject::COMCreateInstance(ccx, bstrClassName,
                 enforceSecurity, &pDispatch);
    if(FAILED(rv))
    {
        XPCThrower::ThrowCOMError(ccx, rv, NS_ERROR_XPC_COM_CREATE_FAILED);
        return JS_FALSE;
    }
    // Get a wrapper for our object
    nsCOMPtr<nsIXPConnectJSObjectHolder> holder;
    nsresult nsrv = ccx.GetXPConnect()->WrapNative(
                        ccx, ccx.GetOperandJSObject(), reinterpret_cast<nsISupports*>(pDispatch.p),
                        NSID_IDISPATCH, getter_AddRefs(holder));
    if(NS_FAILED(nsrv))
    {
        XPCThrower::Throw(nsrv, ccx);
        return JS_FALSE;
    }
    // get and return the JS object wrapper
    JSObject * jsobj;
    nsrv = holder->GetJSObject(&jsobj);
    if(NS_FAILED(nsrv))
    {
        XPCThrower::Throw(nsrv, ccx);
        return JS_FALSE;
    }
    *rval = OBJECT_TO_JSVAL(jsobj);
    return JS_TRUE;
}
Beispiel #18
0
/*
 * See:
 * https://bugzilla.mozilla.org/show_bug.cgi?id=166436
 * https://bugzilla.mozilla.org/show_bug.cgi?id=215173
 *
 * Very surprisingly, jsapi.h lacks any way to "throw new Error()"
 *
 * So here is an awful hack inspired by
 * http://egachine.berlios.de/embedding-sm-best-practice/embedding-sm-best-practice.html#error-handling
 */
static void
gjs_throw_valist(JSContext       *context,
                    const char      *format,
                    va_list          args)
{
    char *s;
    JSBool result;
    jsval v_constructor, v_message;
    JSObject *err_obj;

    s = g_strdup_vprintf(format, args);

    JS_BeginRequest(context);

    if (JS_IsExceptionPending(context)) {
        /* Often it's unclear whether a given jsapi.h function
         * will throw an exception, so we will throw ourselves
         * "just in case"; in those cases, we don't want to
         * overwrite an exception that already exists.
         * (Do log in case our second exception adds more info,
         * but don't log as topic ERROR because if the exception is
         * caught we don't want an ERROR in the logs.)
         */
        gjs_debug(GJS_DEBUG_CONTEXT,
                  "Ignoring second exception: '%s'",
                  s);
        g_free(s);
        JS_EndRequest(context);
        return;
    }

    result = JS_FALSE;

    (void)JS_EnterLocalRootScope(context);

    if (!gjs_string_from_utf8(context, s, -1, &v_message)) {
        JS_ReportError(context, "Failed to copy exception string");
        goto out;
    }

    if (!gjs_object_get_property(context, JS_GetGlobalObject(context),
                                 "Error", &v_constructor)) {
        JS_ReportError(context, "??? Missing Error constructor in global object?");
        goto out;
    }

    /* throw new Error(message) */
    err_obj = JS_New(context, JSVAL_TO_OBJECT(v_constructor), 1, &v_message);
    JS_SetPendingException(context, OBJECT_TO_JSVAL(err_obj));

    result = JS_TRUE;

 out:

    JS_LeaveLocalRootScope(context);

    if (!result) {
        /* try just reporting it to error handler? should not
         * happen though pretty much
         */
        JS_ReportError(context,
                       "Failed to throw exception '%s'",
                       s);
    }
    g_free(s);

    JS_EndRequest(context);
}
bool js_cocos2dx_spine_SkeletonAnimation_createWithFile(JSContext *cx, uint32_t argc, jsval *vp)
{
	jsval *argv = JS_ARGV(cx, vp);
	bool ok = true;
	
	do {
		if (argc == 2) {
			const char* arg0;
			std::string arg0_tmp; ok &= jsval_to_std_string(cx, argv[0], &arg0_tmp); arg0 = arg0_tmp.c_str();
			if (!ok) { ok = true; break; }
			const char* arg1;
			std::string arg1_tmp; ok &= jsval_to_std_string(cx, argv[1], &arg1_tmp); arg1 = arg1_tmp.c_str();
			if (!ok) { ok = true; break; }
			spine::SkeletonAnimation* ret = spine::SkeletonAnimation::createWithFile(arg0, arg1);
			jsval jsret = JSVAL_NULL;
			do {
				if (ret) {
					js_proxy_t *jsProxy = js_get_or_create_proxy<spine::SkeletonAnimation>(cx, (spine::SkeletonAnimation*)ret);
					jsret = OBJECT_TO_JSVAL(jsProxy->obj);
				} else {
					jsret = JSVAL_NULL;
				}
			} while (0);
			JS_SET_RVAL(cx, vp, jsret);
			return true;
		}
	} while (0);
	do {
		if (argc == 3) {
			const char* arg0;
			std::string arg0_tmp; ok &= jsval_to_std_string(cx, argv[0], &arg0_tmp); arg0 = arg0_tmp.c_str();
			if (!ok) { ok = true; break; }
			const char* arg1;
			std::string arg1_tmp; ok &= jsval_to_std_string(cx, argv[1], &arg1_tmp); arg1 = arg1_tmp.c_str();
			if (!ok) { ok = true; break; }
			double arg2;
			ok &= JS::ToNumber( cx, JS::RootedValue(cx, argv[2]), &arg2);
			if (!ok) { ok = true; break; }
			spine::SkeletonAnimation* ret = spine::SkeletonAnimation::createWithFile(arg0, arg1, arg2);
			jsval jsret = JSVAL_NULL;
			do {
				if (ret) {
					js_proxy_t *jsProxy = js_get_or_create_proxy<spine::SkeletonAnimation>(cx, (spine::SkeletonAnimation*)ret);
					jsret = OBJECT_TO_JSVAL(jsProxy->obj);
				} else {
					jsret = JSVAL_NULL;
				}
			} while (0);
			JS_SET_RVAL(cx, vp, jsret);
			return true;
		}
	} while (0);
	
	do {
		if (argc == 2) {
			const char* arg0;
			std::string arg0_tmp; ok &= jsval_to_std_string(cx, argv[0], &arg0_tmp); arg0 = arg0_tmp.c_str();
			if (!ok) { ok = true; break; }
			spAtlas* arg1;
			#pragma warning NO CONVERSION TO NATIVE FOR spAtlas*
			ok = false;
			if (!ok) { ok = true; break; }
			spine::SkeletonAnimation* ret = spine::SkeletonAnimation::createWithFile(arg0, arg1);
			jsval jsret = JSVAL_NULL;
			do {
				if (ret) {
					js_proxy_t *jsProxy = js_get_or_create_proxy<spine::SkeletonAnimation>(cx, (spine::SkeletonAnimation*)ret);
					jsret = OBJECT_TO_JSVAL(jsProxy->obj);
				} else {
					jsret = JSVAL_NULL;
				}
			} while (0);
			JS_SET_RVAL(cx, vp, jsret);
			return true;
		}
	} while (0);
	do {
		if (argc == 3) {
			const char* arg0;
			std::string arg0_tmp; ok &= jsval_to_std_string(cx, argv[0], &arg0_tmp); arg0 = arg0_tmp.c_str();
			if (!ok) { ok = true; break; }
			spAtlas* arg1;
			#pragma warning NO CONVERSION TO NATIVE FOR spAtlas*
			ok = false;
			if (!ok) { ok = true; break; }
			double arg2;
			ok &= JS::ToNumber( cx, JS::RootedValue(cx, argv[2]), &arg2);
			if (!ok) { ok = true; break; }
			spine::SkeletonAnimation* ret = spine::SkeletonAnimation::createWithFile(arg0, arg1, arg2);
			jsval jsret = JSVAL_NULL;
			do {
				if (ret) {
					js_proxy_t *jsProxy = js_get_or_create_proxy<spine::SkeletonAnimation>(cx, (spine::SkeletonAnimation*)ret);
					jsret = OBJECT_TO_JSVAL(jsProxy->obj);
				} else {
					jsret = JSVAL_NULL;
				}
			} while (0);
			JS_SET_RVAL(cx, vp, jsret);
			return true;
		}
	} while (0);
	JS_ReportError(cx, "js_cocos2dx_spine_SkeletonAnimation_createWithFile : wrong number of arguments");
	return false;
}
Beispiel #20
0
NS_IMETHODIMP
TelemetryImpl::GetChromeHangs(JSContext *cx, jsval *ret)
{
  MutexAutoLock hangReportMutex(mHangReportsMutex);
  JSObject *reportArray = JS_NewArrayObject(cx, 0, nsnull);
  if (!reportArray) {
    return NS_ERROR_FAILURE;
  }
  *ret = OBJECT_TO_JSVAL(reportArray);

  // Each hang report is an object in the 'chromeHangs' array
  for (size_t i = 0; i < mHangReports.Length(); ++i) {
    JSObject *reportObj = JS_NewObject(cx, NULL, NULL, NULL);
    if (!reportObj) {
      return NS_ERROR_FAILURE;
    }
    jsval reportObjVal = OBJECT_TO_JSVAL(reportObj);
    if (!JS_SetElement(cx, reportArray, i, &reportObjVal)) {
      return NS_ERROR_FAILURE;
    }

    // Record the hang duration (expressed in seconds)
    JSBool ok = JS_DefineProperty(cx, reportObj, "duration",
                                  INT_TO_JSVAL(mHangReports[i].duration),
                                  NULL, NULL, JSPROP_ENUMERATE);
    if (!ok) {
      return NS_ERROR_FAILURE;
    }

    // Represent call stack PCs as strings
    // (JS can't represent all 64-bit integer values)
    JSObject *pcArray = JS_NewArrayObject(cx, 0, nsnull);
    if (!pcArray) {
      return NS_ERROR_FAILURE;
    }
    ok = JS_DefineProperty(cx, reportObj, "stack", OBJECT_TO_JSVAL(pcArray),
                           NULL, NULL, JSPROP_ENUMERATE);
    if (!ok) {
      return NS_ERROR_FAILURE;
    }

    const PRUint32 pcCount = mHangReports[i].callStack.Length();
    for (size_t pcIndex = 0; pcIndex < pcCount; ++pcIndex) {
      nsCAutoString pcString;
      pcString.AppendPrintf("0x%p", mHangReports[i].callStack[pcIndex]);
      JSString *str = JS_NewStringCopyZ(cx, pcString.get());
      if (!str) {
        return NS_ERROR_FAILURE;
      }
      jsval v = STRING_TO_JSVAL(str);
      if (!JS_SetElement(cx, pcArray, pcIndex, &v)) {
        return NS_ERROR_FAILURE;
      }
    }

    // Record memory map info
    JSObject *moduleArray = JS_NewArrayObject(cx, 0, nsnull);
    if (!moduleArray) {
      return NS_ERROR_FAILURE;
    }
    ok = JS_DefineProperty(cx, reportObj, "memoryMap",
                           OBJECT_TO_JSVAL(moduleArray),
                           NULL, NULL, JSPROP_ENUMERATE);
    if (!ok) {
      return NS_ERROR_FAILURE;
    }

    const PRUint32 moduleCount = mHangReports[i].moduleMap.GetSize();
    for (size_t moduleIndex = 0; moduleIndex < moduleCount; ++moduleIndex) {
      // Current module
      const SharedLibrary &module =
        mHangReports[i].moduleMap.GetEntry(moduleIndex);

      JSObject *moduleInfoArray = JS_NewArrayObject(cx, 0, nsnull);
      if (!moduleInfoArray) {
        return NS_ERROR_FAILURE;
      }
      jsval val = OBJECT_TO_JSVAL(moduleInfoArray);
      if (!JS_SetElement(cx, moduleArray, moduleIndex, &val)) {
        return NS_ERROR_FAILURE;
      }

      // Start address
      nsCAutoString addressString;
      addressString.AppendPrintf("0x%p", module.GetStart());
      JSString *str = JS_NewStringCopyZ(cx, addressString.get());
      if (!str) {
        return NS_ERROR_FAILURE;
      }
      val = STRING_TO_JSVAL(str);
      if (!JS_SetElement(cx, moduleInfoArray, 0, &val)) {
        return NS_ERROR_FAILURE;
      }

      // Module name
      str = JS_NewStringCopyZ(cx, module.GetName());
      if (!str) {
        return NS_ERROR_FAILURE;
      }
      val = STRING_TO_JSVAL(str);
      if (!JS_SetElement(cx, moduleInfoArray, 1, &val)) {
        return NS_ERROR_FAILURE;
      }

      // Module size in memory
      val = INT_TO_JSVAL(int32_t(module.GetEnd() - module.GetStart()));
      if (!JS_SetElement(cx, moduleInfoArray, 2, &val)) {
        return NS_ERROR_FAILURE;
      }

      // "PDB Age" identifier
      val = INT_TO_JSVAL(0);
#if defined(MOZ_PROFILING) && defined(XP_WIN)
      val = INT_TO_JSVAL(module.GetPdbAge());
#endif
      if (!JS_SetElement(cx, moduleInfoArray, 3, &val)) {
        return NS_ERROR_FAILURE;
      }

      // "PDB Signature" GUID
      char guidString[NSID_LENGTH] = { 0 };
#if defined(MOZ_PROFILING) && defined(XP_WIN)
      module.GetPdbSignature().ToProvidedString(guidString);
#endif
      str = JS_NewStringCopyZ(cx, guidString);
      if (!str) {
        return NS_ERROR_FAILURE;
      }
      val = STRING_TO_JSVAL(str);
      if (!JS_SetElement(cx, moduleInfoArray, 4, &val)) {
        return NS_ERROR_FAILURE;
      }
    }
  }

  return NS_OK;
}
Beispiel #21
0
JSBool js_cocos2dx_extension_WebSocket_constructor(JSContext *cx, uint32_t argc, jsval *vp)
{
    jsval *argv = JS_ARGV(cx, vp);
    
	if (argc == 1 || argc == 2)
    {

		std::string url;
		
		do {
			JSBool ok = jsval_to_std_string(cx, argv[0], &url);
			JSB_PRECONDITION2( ok, cx, JS_FALSE, "Error processing arguments");
		} while (0);
        
		JSObject *obj = JS_NewObject(cx, js_cocos2dx_websocket_class, js_cocos2dx_websocket_prototype, NULL);
		
        
		cocos2d::extension::WebSocket* cobj = new cocos2d::extension::WebSocket();
        JSB_WebSocketDelegate* delegate = new JSB_WebSocketDelegate();
        delegate->setJSDelegate(obj);
        
        if (argc == 2)
        {
            std::vector<std::string> protocols;
            
            if (JSVAL_IS_STRING(argv[1]))
            {
                std::string protocol;
                do {
                    JSBool ok = jsval_to_std_string(cx, argv[1], &protocol);
                    JSB_PRECONDITION2( ok, cx, JS_FALSE, "Error processing arguments");
                } while (0);
                protocols.push_back(protocol);
            }
            else if (argv[1].isObject())
            {
                JSBool ok = JS_TRUE;
                JSObject* arg2 = JSVAL_TO_OBJECT(argv[1]);
                JSB_PRECONDITION(JS_IsArrayObject( cx, arg2 ),  "Object must be an array");
                
                uint32_t len = 0;
                JS_GetArrayLength(cx, arg2, &len);
                
                for( uint32_t i=0; i< len;i++ )
                {
                    jsval valarg;
                    JS_GetElement(cx, arg2, i, &valarg);
                    std::string protocol;
                    do {
                        ok = jsval_to_std_string(cx, valarg, &protocol);
                        JSB_PRECONDITION2( ok, cx, JS_FALSE, "Error processing arguments");
                    } while (0);
                    
                    protocols.push_back(protocol);
                }
            }
            cobj->init(*delegate, url, &protocols);
        }
        else
        {
            cobj->init(*delegate, url);
        }
        
        
        JS_DefineProperty(cx, obj, "URL", argv[0]
                          , NULL, NULL, JSPROP_ENUMERATE | JSPROP_PERMANENT | JSPROP_READONLY);
        
		//protocol not support yet (always return "")
		JS_DefineProperty(cx, obj, "protocol", c_string_to_jsval(cx, "")
                          , NULL, NULL, JSPROP_ENUMERATE | JSPROP_PERMANENT | JSPROP_READONLY);
        
        // link the native object with the javascript object
		js_proxy_t *p = jsb_new_proxy(cobj, obj);
        JS_AddNamedObjectRoot(cx, &p->obj, "WebSocket");
        
        JS_SET_RVAL(cx, vp, OBJECT_TO_JSVAL(obj));
		return JS_TRUE;
	}
    
	JS_ReportError(cx, "wrong number of arguments: %d, was expecting %d", argc, 0);
	return JS_FALSE;
}
Beispiel #22
0
static JSBool
Exception(JSContext *cx, JSObject *obj, uintN argc, jsval *argv, jsval *rval)
{
    JSBool ok;
    jsval pval;
    uint32 lineno;
    JSString *message, *filename;
    JSStackFrame *fp;

    if (cx->creatingException)
        return JS_FALSE;
    cx->creatingException = JS_TRUE;

    if (!(cx->fp->flags & JSFRAME_CONSTRUCTING)) {
        /*
         * ECMA ed. 3, 15.11.1 requires Error, etc., to construct even when
         * called as functions, without operator new.  But as we do not give
         * each constructor a distinct JSClass, whose .name member is used by
         * js_NewObject to find the class prototype, we must get the class
         * prototype ourselves.
         */
        ok = OBJ_GET_PROPERTY(cx, JSVAL_TO_OBJECT(argv[-2]),
                              ATOM_TO_JSID(cx->runtime->atomState
                                           .classPrototypeAtom),
                              &pval);
        if (!ok)
            goto out;
        obj = js_NewObject(cx, &ExceptionClass, JSVAL_TO_OBJECT(pval), NULL);
        if (!obj) {
            ok = JS_FALSE;
            goto out;
        }
        *rval = OBJECT_TO_JSVAL(obj);
    }

    /*
     * If it's a new object of class Exception, then null out the private
     * data so that the finalizer doesn't attempt to free it.
     */
    if (OBJ_GET_CLASS(cx, obj) == &ExceptionClass)
        OBJ_SET_SLOT(cx, obj, JSSLOT_PRIVATE, JSVAL_VOID);

    /* Set the 'message' property. */
    if (argc != 0) {
        message = js_ValueToString(cx, argv[0]);
        if (!message) {
            ok = JS_FALSE;
            goto out;
        }
        argv[0] = STRING_TO_JSVAL(message);
    } else {
        message = cx->runtime->emptyString;
    }

    /* Set the 'fileName' property. */
    if (argc > 1) {
        filename = js_ValueToString(cx, argv[1]);
        if (!filename) {
            ok = JS_FALSE;
            goto out;
        }
        argv[1] = STRING_TO_JSVAL(filename);
        fp = NULL;
    } else {
        fp = JS_GetScriptedCaller(cx, NULL);
        if (fp) {
            filename = FilenameToString(cx, fp->script->filename);
            if (!filename) {
                ok = JS_FALSE;
                goto out;
            }
        } else {
            filename = cx->runtime->emptyString;
        }
    }

    /* Set the 'lineNumber' property. */
    if (argc > 2) {
        ok = js_ValueToECMAUint32(cx, argv[2], &lineno);
        if (!ok)
            goto out;
    } else {
        if (!fp)
            fp = JS_GetScriptedCaller(cx, NULL);
        lineno = (fp && fp->pc) ? js_PCToLineNumber(cx, fp->script, fp->pc) : 0;
    }

    ok = InitExceptionObject(cx, obj, message, filename, lineno);

out:
    cx->creatingException = JS_FALSE;
    return ok;
}
Beispiel #23
0
JSBool
Library::Declare(JSContext* cx, uintN argc, jsval* vp)
{
  JSObject* obj = JS_THIS_OBJECT(cx, vp);
  if (!obj || !IsLibrary(cx, obj)) {
    JS_ReportError(cx, "not a library");
    return JS_FALSE;
  }

  PRLibrary* library = GetLibrary(cx, obj);
  if (!library) {
    JS_ReportError(cx, "library not open");
    return JS_FALSE;
  }

  // We allow two API variants:
  // 1) library.declare(name, abi, returnType, argType1, ...)
  //    declares a function with the given properties, and resolves the symbol
  //    address in the library.
  // 2) library.declare(name, type)
  //    declares a symbol of 'type', and resolves it. The object that comes
  //    back will be of type 'type', and will point into the symbol data.
  //    This data will be both readable and writable via the usual CData
  //    accessors. If 'type' is a PointerType to a FunctionType, the result will
  //    be a function pointer, as with 1). 
  if (argc < 2) {
    JS_ReportError(cx, "declare requires at least two arguments");
    return JS_FALSE;
  }

  jsval* argv = JS_ARGV(cx, vp);
  if (!JSVAL_IS_STRING(argv[0])) {
    JS_ReportError(cx, "first argument must be a string");
    return JS_FALSE;
  }

  JSObject* fnObj = NULL;
  JSObject* typeObj;
  js::AutoObjectRooter root(cx);
  bool isFunction = argc > 2;
  if (isFunction) {
    // Case 1).
    // Create a FunctionType representing the function.
    fnObj = FunctionType::CreateInternal(cx,
              argv[1], argv[2], &argv[3], argc - 3);
    if (!fnObj)
      return JS_FALSE;
    root.setObject(fnObj);

    // Make a function pointer type.
    typeObj = PointerType::CreateInternal(cx, fnObj);
    if (!typeObj)
      return JS_FALSE;
    root.setObject(typeObj);

  } else {
    // Case 2).
    if (JSVAL_IS_PRIMITIVE(argv[1]) ||
        !CType::IsCType(cx, JSVAL_TO_OBJECT(argv[1])) ||
        !CType::IsSizeDefined(cx, JSVAL_TO_OBJECT(argv[1]))) {
      JS_ReportError(cx, "second argument must be a type of defined size");
      return JS_FALSE;
    }

    typeObj = JSVAL_TO_OBJECT(argv[1]);
    if (CType::GetTypeCode(cx, typeObj) == TYPE_pointer) {
      fnObj = PointerType::GetBaseType(cx, typeObj);
      isFunction = fnObj && CType::GetTypeCode(cx, fnObj) == TYPE_function;
    }
  }

  void* data;
  PRFuncPtr fnptr;
  JSString* nameStr = JSVAL_TO_STRING(argv[0]);
  AutoCString symbol;
  if (isFunction) {
    // Build the symbol, with mangling if necessary.
    FunctionType::BuildSymbolName(cx, nameStr, fnObj, symbol);
    AppendString(symbol, "\0");

    // Look up the function symbol.
    fnptr = PR_FindFunctionSymbol(library, symbol.begin());
    if (!fnptr) {
      JS_ReportError(cx, "couldn't find function symbol in library");
      return JS_FALSE;
    }
    data = &fnptr;

  } else {
    // 'typeObj' is another data type. Look up the data symbol.
    AppendString(symbol, nameStr);
    AppendString(symbol, "\0");

    data = PR_FindSymbol(library, symbol.begin());
    if (!data) {
      JS_ReportError(cx, "couldn't find symbol in library");
      return JS_FALSE;
    }
  }

  JSObject* result = CData::Create(cx, typeObj, obj, data, isFunction);
  if (!result)
    return JS_FALSE;

  JS_SET_RVAL(cx, vp, OBJECT_TO_JSVAL(result));

  // Seal the CData object, to prevent modification of the function pointer.
  // This permanently associates this object with the library, and avoids
  // having to do things like reset SLOT_REFERENT when someone tries to
  // change the pointer value.
  // XXX This will need to change when bug 541212 is fixed -- CData::ValueSetter
  // could be called on a sealed object.
  if (isFunction && !JS_FreezeObject(cx, result))
    return JS_FALSE;

  return JS_TRUE;
}
Beispiel #24
0
JSBool
js_ErrorToException(JSContext *cx, const char *message, JSErrorReport *reportp)
{
    JSErrNum errorNumber;
    JSExnType exn;
    JSBool ok;
    JSObject *errProto, *errObject;
    JSString *messageStr, *filenameStr;
    uintN lineno;
    JSExnPrivate *privateData;
    const JSErrorFormatString *errorString;

    /*
     * Tell our caller to report immediately if cx has no active frames, or if
     * this report is just a warning.
     */
    JS_ASSERT(reportp);
    if (!cx->fp || JSREPORT_IS_WARNING(reportp->flags))
        return JS_FALSE;

    /* Find the exception index associated with this error. */
    errorNumber = (JSErrNum) reportp->errorNumber;
    errorString = js_GetLocalizedErrorMessage(cx, NULL, NULL, errorNumber);
    exn = errorString ? errorString->exnType : JSEXN_NONE;
    JS_ASSERT(exn < JSEXN_LIMIT);

#if defined( DEBUG_mccabe ) && defined ( PRINTNAMES )
    /* Print the error name and the associated exception name to stderr */
    fprintf(stderr, "%s\t%s\n",
            errortoexnname[errorNumber].name,
            errortoexnname[errorNumber].exception);
#endif

    /*
     * Return false (no exception raised) if no exception is associated
     * with the given error number.
     */
    if (exn == JSEXN_NONE)
        return JS_FALSE;

    /*
     * Prevent runaway recursion, just as the Exception native constructor
     * must do, via cx->creatingException.  If an out-of-memory error occurs,
     * no exception object will be created, but we don't assume that OOM is
     * the only kind of error that subroutines of this function called below
     * might raise.
     */
    if (cx->creatingException)
        return JS_FALSE;
    cx->creatingException = JS_TRUE;

    /* Protect the newly-created strings below from nesting GCs. */
    ok = js_EnterLocalRootScope(cx);
    if (!ok)
        goto out;

    /*
     * Try to get an appropriate prototype by looking up the corresponding
     * exception constructor name in the scope chain of the current context's
     * top stack frame, or in the global object if no frame is active.
     */
    ok = js_GetClassPrototype(cx, exceptions[exn].name, &errProto);
    if (!ok)
        goto out;

    errObject = js_NewObject(cx, &ExceptionClass, errProto, NULL);
    if (!errObject) {
        ok = JS_FALSE;
        goto out;
    }

    /*
     * Set the generated Exception object early, so it won't be GC'd by a last
     * ditch attempt to collect garbage, or a GC that otherwise nests or races
     * under any of the following calls.  If one of the following calls fails,
     * it will overwrite this exception object with one of its own (except in
     * case of OOM errors, of course).
     */
    JS_SetPendingException(cx, OBJECT_TO_JSVAL(errObject));

    messageStr = JS_NewStringCopyZ(cx, message);
    if (!messageStr) {
        ok = JS_FALSE;
        goto out;
    }

    if (reportp) {
        filenameStr = JS_NewStringCopyZ(cx, reportp->filename);
        if (!filenameStr) {
            ok = JS_FALSE;
            goto out;
        }
        lineno = reportp->lineno;
    } else {
        filenameStr = cx->runtime->emptyString;
        lineno = 0;
    }
    ok = InitExceptionObject(cx, errObject, messageStr, filenameStr, lineno);
    if (!ok)
        goto out;

    /*
     * Construct a new copy of the error report struct, and store it in the
     * exception object's private data.  We can't use the error report struct
     * that was passed in, because it's stack-allocated, and also because it
     * may point to transient data in the JSTokenStream.
     */
    privateData = exn_newPrivate(cx, reportp);
    if (!privateData) {
        ok = JS_FALSE;
        goto out;
    }
    OBJ_SET_SLOT(cx, errObject, JSSLOT_PRIVATE, PRIVATE_TO_JSVAL(privateData));

    /* Flag the error report passed in to indicate an exception was raised. */
    reportp->flags |= JSREPORT_EXCEPTION;

out:
    js_LeaveLocalRootScope(cx);
    cx->creatingException = JS_FALSE;
    return ok;
}
Beispiel #25
0
// static
nsresult
Key::DecodeJSValInternal(const unsigned char*& aPos, const unsigned char* aEnd,
                         JSContext* aCx, uint8_t aTypeOffset, jsval* aVal,
                         uint16_t aRecursionDepth)
{
  NS_ENSURE_TRUE(aRecursionDepth < MaxRecursionDepth, NS_ERROR_DOM_INDEXEDDB_DATA_ERR);

  if (*aPos - aTypeOffset >= eArray) {
    JS::Rooted<JSObject*> array(aCx, JS_NewArrayObject(aCx, 0, nullptr));
    if (!array) {
      NS_WARNING("Failed to make array!");
      return NS_ERROR_DOM_INDEXEDDB_UNKNOWN_ERR;
    }

    aTypeOffset += eMaxType;

    if (aTypeOffset == eMaxType * MaxArrayCollapse) {
      ++aPos;
      aTypeOffset = 0;
    }

    uint32_t index = 0;
    while (aPos < aEnd && *aPos - aTypeOffset != eTerminator) {
      JS::Rooted<JS::Value> val(aCx);
      nsresult rv = DecodeJSValInternal(aPos, aEnd, aCx, aTypeOffset,
                                        val.address(), aRecursionDepth + 1);
      NS_ENSURE_SUCCESS(rv, rv);

      aTypeOffset = 0;

      if (!JS_SetElement(aCx, array, index++, val.address())) {
        NS_WARNING("Failed to set array element!");
        return NS_ERROR_DOM_INDEXEDDB_UNKNOWN_ERR;
      }
    }

    NS_ASSERTION(aPos >= aEnd || (*aPos % eMaxType) == eTerminator,
                 "Should have found end-of-array marker");
    ++aPos;

    *aVal = OBJECT_TO_JSVAL(array);
  }
  else if (*aPos - aTypeOffset == eString) {
    nsString key;
    DecodeString(aPos, aEnd, key);
    if (!xpc::StringToJsval(aCx, key, aVal)) {
      return NS_ERROR_DOM_INDEXEDDB_UNKNOWN_ERR;
    }
  }
  else if (*aPos - aTypeOffset == eDate) {
    double msec = static_cast<double>(DecodeNumber(aPos, aEnd));
    JSObject* date = JS_NewDateObjectMsec(aCx, msec);
    if (!date) {
      NS_WARNING("Failed to make date!");
      return NS_ERROR_DOM_INDEXEDDB_UNKNOWN_ERR;
    }

    *aVal = OBJECT_TO_JSVAL(date);
  }
  else if (*aPos - aTypeOffset == eFloat) {
    *aVal = DOUBLE_TO_JSVAL(DecodeNumber(aPos, aEnd));
  }
  else {
    NS_NOTREACHED("Unknown key type!");
  }

  return NS_OK;
}
// any getUniform(WebGLProgram? program, WebGLUniformLocation? location);
bool JSB_glGetUniformfv(JSContext *cx, uint32_t argc, jsval *vp)
{
    JSB_PRECONDITION2( argc == 2, cx, false, "JSB_glGetUniformfv: Invalid number of arguments" );
    JS::CallArgs args = JS::CallArgsFromVp(argc, vp);
    bool ok = true;
    uint32_t arg0, arg1;

    ok &= jsval_to_uint( cx, args.get(0), &arg0 );
    ok &= jsval_to_uint( cx, args.get(1), &arg1 );

    JSB_PRECONDITION2(ok, cx, false, "JSB_glGetUniformfv: Error processing arguments");

    GLint activeUniforms;
    glGetProgramiv(arg0, GL_ACTIVE_UNIFORMS, &activeUniforms);
    
    GLsizei length;
    glGetProgramiv(arg0, GL_ACTIVE_UNIFORM_MAX_LENGTH, &length);
    GLchar* namebuffer = new GLchar[length+1];
    GLint size = -1;
    GLenum type = -1;

    bool isLocationFound = false;
    for(int i = 0; i  <  activeUniforms; ++i)
    {
        glGetActiveUniform(arg0, i, length, NULL, &size, &type, namebuffer);
        if(arg1 == glGetUniformLocation(arg0, namebuffer))
        {
            isLocationFound = true;
            break;
        }
    }
    if(!isLocationFound)
    {
        size = -1;
        type = -1;
    }
    CC_SAFE_DELETE_ARRAY(namebuffer);

    int usize = 0;
    int utype = 0;
    switch(type) {

        // float
        case GL_FLOAT:
            usize = 1;
            utype = GL_FLOAT;
            break;
        case GL_FLOAT_MAT2:
            usize = 2 * 2;
            utype = GL_FLOAT;
            break;
        case GL_FLOAT_MAT3:
            usize = 3 * 3;
            utype = GL_FLOAT;
            break;
        case GL_FLOAT_MAT4:
            usize = 4 * 4;
            utype = GL_FLOAT;
            break;
        case GL_FLOAT_VEC2:
            usize = 2;
            utype = GL_FLOAT;
            break;
        case GL_FLOAT_VEC3:
            usize = 3;
            utype = GL_FLOAT;
            break;
        case GL_FLOAT_VEC4:
            usize = 4;
            utype = GL_FLOAT;           
            break;

        // int
        case GL_INT:
            usize = 1;
            utype = GL_INT;
            break;
        case GL_INT_VEC2:
            usize = 1;
            utype = GL_INT;
            break;
        case GL_INT_VEC3:
            usize = 1;
            utype = GL_INT;
            break;
        case GL_INT_VEC4:
            usize = 1;
            utype = GL_INT;
            break;

        default:
            JSB_PRECONDITION2(false, cx, false, "JSB_glGetUniformfv: Uniform Type not supported");
    }

    JSObject *typedArray = NULL;
    if( utype == GL_FLOAT) {
        // FIXME: glew on windows will cause array overflow after invoking glGetUniformfv.
        // It seems that glGetUniformfv re-assign the memeroy with a wrong size which is 4x than we pass in.
        // For temporary solution, we allocate 4x array. 
        GLfloat* param = new GLfloat[usize*4];
        glGetUniformfv(arg0, arg1, param);

        typedArray = JS_NewFloat32Array(cx, usize);
        float *buffer = (float*)JS_GetArrayBufferViewData(typedArray);
        memcpy( buffer, param, sizeof(float) * usize);
        CC_SAFE_DELETE_ARRAY(param);
    } else if( utype == GL_INT ) {
        // FIXME: glew on windows will cause array overflow after invoking glGetUniformfv.
        // It seems that glGetUniformfv re-assign the memeroy with a wrong size which is 4x than we pass in.
        // For temporary solution, we allocate 4x array. 
        GLint* param = new GLint[usize*4];
        glGetUniformiv(arg0, arg1, param);

        typedArray = JS_NewInt32Array(cx, usize);
        GLint *buffer = (GLint*)JS_GetArrayBufferViewData(typedArray);
        memcpy( buffer, param, sizeof(GLint) * usize);
        CC_SAFE_DELETE_ARRAY(param);
    }

    args.rval().set(OBJECT_TO_JSVAL(typedArray));
    return true;
}
Beispiel #27
0
jsval as_jsval(JSContext *cx, JSVButtonBox::OWNERPTR theOwner, JSVButtonBox::NATIVE * theNative) {
    JSObject * myReturnObject = JSVButtonBox::Construct(cx, theOwner, theNative);
    return OBJECT_TO_JSVAL(myReturnObject);
}
Beispiel #28
0
static void getJSTouchObject(JSContext *cx, Touch *x, jsval &jsret) {
    js_proxy_t *proxy = js_get_or_create_proxy<cocos2d::Touch>(cx, x);
    jsret = OBJECT_TO_JSVAL(proxy->obj);
}
bool js_cocos2dx_extension_EventListenerAssetsManagerEx_create(JSContext *cx, uint32_t argc, jsval *vp)
{
    JS::CallArgs args = JS::CallArgsFromVp(argc, vp);
    bool ok = true;
    if (argc == 2) {
        cocos2d::extension::AssetsManagerEx* arg0 = nullptr;
        std::function<void (cocos2d::extension::EventAssetsManagerEx *)> arg1;
        do {
            if (args.get(0).isNull()) { arg0 = nullptr; break; }
            if (!args.get(0).isObject()) { ok = false; break; }
            js_proxy_t *jsProxy;
            JS::RootedObject tmpObj(cx, args.get(0).toObjectOrNull());
            jsProxy = jsb_get_js_proxy(tmpObj);
            arg0 = (cocos2d::extension::AssetsManagerEx*)(jsProxy ? jsProxy->ptr : NULL);
            JSB_PRECONDITION2( arg0, cx, false, "Invalid Native Object");
        } while (0);
        do {
            if(JS_TypeOfValue(cx, args.get(1)) == JSTYPE_FUNCTION)
            {
                JS::RootedObject jstarget(cx, args.thisv().toObjectOrNull());
                std::shared_ptr<JSFunctionWrapper> func(new JSFunctionWrapper(cx, jstarget, args.get(1)));
                auto lambda = [=](cocos2d::extension::EventAssetsManagerEx* larg0) -> void {
                    JSB_AUTOCOMPARTMENT_WITH_GLOBAL_OBJCET
                    jsval largv[1];
                    do {
                        if (larg0) {
                            js_type_class_t* typeClass = js_get_type_from_native<cocos2d::extension::EventAssetsManagerEx>(larg0);
                            largv[0] = OBJECT_TO_JSVAL(jsb_get_or_create_weak_jsobject(cx, larg0, typeClass, "cocos2d::extension::EventAssetsManagerEx"));
                        } else {
                            largv[0] = JSVAL_NULL;
                        }
                    } while (0);
                    JS::RootedValue rval(cx);
                    bool succeed = func->invoke(1, &largv[0], &rval);
                    if (!succeed && JS_IsExceptionPending(cx)) {
                        JS_ReportPendingException(cx);
                    }
                    removeJSObject(cx, larg0);
                };
                arg1 = lambda;
            }
            else
            {
                arg1 = nullptr;
            }
        } while(0)
            ;
        JSB_PRECONDITION2(ok, cx, false, "js_cocos2dx_extension_EventListenerAssetsManagerEx_create : Error processing arguments");
        cocos2d::extension::EventListenerAssetsManagerEx* ret = cocos2d::extension::EventListenerAssetsManagerEx::create(arg0, arg1);
        jsval jsret = JSVAL_NULL;
        if (ret) {
            JS::RootedObject jsobj(cx, js_get_or_create_jsobject<cocos2d::extension::EventListenerAssetsManagerEx>(cx, ret));
            jsret = OBJECT_TO_JSVAL(jsobj);
        } else {
            jsret = JSVAL_NULL;
        }
        args.rval().set(jsret);
        return true;
    }
    JS_ReportError(cx, "js_cocos2dx_extension_EventListenerAssetsManagerEx_create : wrong number of arguments");
    return false;
}
Beispiel #30
0
// any getUniform(WebGLProgram? program, WebGLUniformLocation? location);
JSBool JSB_glGetUniformfv(JSContext *cx, uint32_t argc, jsval *vp)
{
    JSB_PRECONDITION2( argc == 2, cx, JS_FALSE, "JSB_glGetUniformfv: Invalid number of arguments" );
    jsval *argvp = JS_ARGV(cx,vp);
    JSBool ok = JS_TRUE;
    uint32_t arg0, arg1;

    ok &= jsval_to_uint( cx, *argvp++, &arg0 );
    ok &= jsval_to_uint( cx, *argvp++, &arg1 );

    JSB_PRECONDITION2(ok, cx, JS_FALSE, "JSB_glGetUniformfv: Error processing arguments");

    GLsizei length;
    glGetProgramiv(arg0, GL_ACTIVE_ATTRIBUTE_MAX_LENGTH, &length);
    GLchar* namebuffer = new GLchar[length];
    GLint size = -1;
    GLenum type = -1;

    glGetActiveUniform(arg0, arg1, length, NULL, &size, &type, namebuffer);
    CC_SAFE_DELETE_ARRAY(namebuffer);

    int usize = 0;
    int utype = 0;
    switch(type) {

    // float
    case GL_FLOAT:
        usize = 1;
        utype = GL_FLOAT;
        break;
    case GL_FLOAT_MAT2:
        usize = 2 * 2;
        utype = GL_FLOAT;
        break;
    case GL_FLOAT_MAT3:
        usize = 3 * 3;
        utype = GL_FLOAT;
        break;
    case GL_FLOAT_MAT4:
        usize = 4 * 4;
        utype = GL_FLOAT;
        break;
    case GL_FLOAT_VEC2:
        usize = 2;
        utype = GL_FLOAT;
        break;
    case GL_FLOAT_VEC3:
        usize = 3;
        utype = GL_FLOAT;
        break;
    case GL_FLOAT_VEC4:
        usize = 4;
        utype = GL_FLOAT;
        break;

    // int
    case GL_INT:
        usize = 1;
        utype = GL_INT;
        break;
    case GL_INT_VEC2:
        usize = 1;
        utype = GL_INT;
        break;
    case GL_INT_VEC3:
        usize = 1;
        utype = GL_INT;
        break;
    case GL_INT_VEC4:
        usize = 1;
        utype = GL_INT;
        break;

    default:
        JSB_PRECONDITION2(false, cx, JS_FALSE, "JSB_glGetUniformfv: Uniform Type not supported");
    }

    JSObject *typedArray = NULL;
    if( utype == GL_FLOAT) {
        GLfloat* param = new GLfloat[usize];
        glGetUniformfv(arg0, arg1, param);

        typedArray = JS_NewFloat32Array(cx, usize);
        float *buffer = (float*)JS_GetArrayBufferViewData(typedArray);
        memcpy( buffer, param, sizeof(float) * usize);
        CC_SAFE_DELETE_ARRAY(param);
    } else if( utype == GL_INT ) {
        GLint* param = new GLint[usize];
        glGetUniformiv(arg0, arg1, param);

        typedArray = JS_NewInt32Array(cx, usize);
        GLint *buffer = (GLint*)JS_GetArrayBufferViewData(typedArray);
        memcpy( buffer, param, sizeof(GLint) * usize);
        CC_SAFE_DELETE_ARRAY(param);
    }

    JS_SET_RVAL(cx, vp, OBJECT_TO_JSVAL(typedArray));
    return JS_TRUE;
}