jsval toval( const BSONElement& e ) { switch( e.type() ) { case EOO: case jstNULL: case Undefined: return JSVAL_NULL; case NumberDouble: case NumberInt: return toval( e.number() ); case Symbol: // TODO: should we make a special class for this case String: return toval( e.valuestr() ); case Bool: return e.boolean() ? JSVAL_TRUE : JSVAL_FALSE; case Object: { BSONObj embed = e.embeddedObject().getOwned(); return toval( &embed ); } case Array: { BSONObj embed = e.embeddedObject().getOwned(); if ( embed.isEmpty() ) { return OBJECT_TO_JSVAL( JS_NewArrayObject( _context , 0 , 0 ) ); } int n = embed.nFields(); JSObject * array = JS_NewArrayObject( _context , n , 0 ); assert( array ); jsval myarray = OBJECT_TO_JSVAL( array ); for ( int i=0; i<n; i++ ) { jsval v = toval( embed[i] ); assert( JS_SetElement( _context , array , i , &v ) ); } return myarray; } case jstOID: { OID oid = e.__oid(); JSObject * o = JS_NewObject( _context , &object_id_class , 0 , 0 ); setProperty( o , "str" , toval( oid.str().c_str() ) ); return OBJECT_TO_JSVAL( o ); } case RegEx: { const char * flags = e.regexFlags(); uintN flagNumber = 0; while ( *flags ) { switch ( *flags ) { case 'g': flagNumber |= JSREG_GLOB; break; case 'i': flagNumber |= JSREG_FOLD; break; case 'm': flagNumber |= JSREG_MULTILINE; break; //case 'y': flagNumber |= JSREG_STICKY; break; default: log() << "warning: unknown regex flag:" << *flags << endl; } flags++; } JSObject * r = JS_NewRegExpObject( _context , (char*)e.regex() , strlen( e.regex() ) , flagNumber ); assert( r ); return OBJECT_TO_JSVAL( r ); } case Code: { JSFunction * func = compileFunction( e.valuestr() ); return OBJECT_TO_JSVAL( JS_GetFunctionObject( func ) ); } case CodeWScope: { JSFunction * func = compileFunction( e.codeWScopeCode() ); BSONObj extraScope = e.codeWScopeObject(); if ( ! extraScope.isEmpty() ) { log() << "warning: CodeWScope doesn't transfer to db.eval" << endl; } return OBJECT_TO_JSVAL( JS_GetFunctionObject( func ) ); } case Date: return OBJECT_TO_JSVAL( js_NewDateObjectMsec( _context , (jsdouble) e.date().millis ) ); case MinKey: return OBJECT_TO_JSVAL( JS_NewObject( _context , &minkey_class , 0 , 0 ) ); case MaxKey: return OBJECT_TO_JSVAL( JS_NewObject( _context , &maxkey_class , 0 , 0 ) ); case Timestamp: { JSObject * o = JS_NewObject( _context , ×tamp_class , 0 , 0 ); setProperty( o , "t" , toval( (double)(e.timestampTime()) ) ); setProperty( o , "i" , toval( (double)(e.timestampInc()) ) ); return OBJECT_TO_JSVAL( o ); } case NumberLong: { boost::uint64_t val = (boost::uint64_t)e.numberLong(); JSObject * o = JS_NewObject( _context , &numberlong_class , 0 , 0 ); setProperty( o , "floatApprox" , toval( (double)(boost::int64_t)( val ) ) ); if ( (boost::int64_t)val != (boost::int64_t)(double)(boost::int64_t)( val ) ) { // using 2 doubles here instead of a single double because certain double // bit patterns represent undefined values and sm might trash them setProperty( o , "top" , toval( (double)(boost::uint32_t)( val >> 32 ) ) ); setProperty( o , "bottom" , toval( (double)(boost::uint32_t)( val & 0x00000000ffffffff ) ) ); } return OBJECT_TO_JSVAL( o ); } case DBRef: { JSObject * o = JS_NewObject( _context , &dbpointer_class , 0 , 0 ); setProperty( o , "ns" , toval( e.dbrefNS() ) ); JSObject * oid = JS_NewObject( _context , &object_id_class , 0 , 0 ); setProperty( oid , "str" , toval( e.dbrefOID().str().c_str() ) ); setProperty( o , "id" , OBJECT_TO_JSVAL( oid ) ); return OBJECT_TO_JSVAL( o ); } case BinData: { JSObject * o = JS_NewObject( _context , &bindata_class , 0 , 0 ); int len; const char * data = e.binData( len ); assert( JS_SetPrivate( _context , o , new BinDataHolder( data ) ) ); setProperty( o , "len" , toval( len ) ); setProperty( o , "type" , toval( (int)e.binDataType() ) ); return OBJECT_TO_JSVAL( o ); } }
JSBool make_js_land_proxy(JohnsonRuntime* runtime, VALUE value, jsval* retval) { jsval base_value = (jsval)JS_HashTableLookup(runtime->rbids, (void *)value); JSContext * context = johnson_get_current_context(runtime); PREPARE_JROOTS(context, 2); jsval johnson = JSVAL_NULL; JCHECK(evaluate_js_property_expression(runtime, "Johnson", &johnson)); JROOT(johnson); if (base_value) { JCHECK(JS_CallFunctionName(context, johnson, "applyConversions", 1, &base_value, retval)); JRETURN; } else { JSObject *jsobj; JSClass *klass = &JSLandProxyClass; if (T_CLASS == TYPE(value)) klass = &JSLandClassProxyClass; // FIXME: hack; should happen in Rubyland if (T_STRUCT == TYPE(value)) rb_funcall(Johnson_SpiderMonkey_JSLandProxy(), rb_intern("treat_all_properties_as_methods"), 1, value); bool callable_p = Qtrue == rb_funcall(value, rb_intern("respond_to?"), 1, rb_str_new2("call")); if (callable_p) klass = &JSLandCallableProxyClass; JCHECK((jsobj = JS_NewObject(context, klass, NULL, NULL))); JROOT(jsobj); JCHECK(JS_SetPrivate(context, jsobj, (void*)value)); JCHECK(JS_DefineFunction(context, jsobj, "__noSuchMethod__", method_missing, 2, 0)); JCHECK(JS_DefineFunction(context, jsobj, "toArray", to_array, 0, 0)); JCHECK(JS_DefineFunction(context, jsobj, "toString", to_string, 0, 0)); base_value = OBJECT_TO_JSVAL(jsobj); // root the ruby value for GC VALUE ruby_runtime = (VALUE)JS_GetRuntimePrivate(runtime->js); rb_funcall(ruby_runtime, rb_intern("add_gcthing"), 1, value); jsval wrapped_value = JSVAL_NULL; JCHECK(JS_CallFunctionName(context, johnson, "applyWrappers", 1, &base_value, &wrapped_value)); // put the proxy OID in the id map JCHECK(JS_HashTableAdd(runtime->rbids, (void *)value, (void *)(wrapped_value))); JCHECK(JS_CallFunctionName(context, johnson, "applyConversions", 1, &wrapped_value, retval)); JRETURN; } }
static JSBool js_appendItem0(JSContext *cx, js_model_t *model, prop_t *parent, const char *url, const char *type, JSObject *metaobj, jsval *data, jsval *rval, int enabled, const char *metabind) { install_nodesub(model); prop_t *item = prop_create_root(NULL); rstr_t *rurl = url ? rstr_alloc(url) : NULL; if(url != NULL) prop_set(item, "url", PROP_SET_RSTRING, rurl); if(data != NULL) js_prop_set_from_jsval(cx, prop_create(item, "data"), *data); *rval = JSVAL_VOID; if(metabind != NULL) metadb_bind_url_to_prop(NULL, metabind, item); if(type != NULL) { prop_set_string(prop_create(item, "type"), type); if(metaobj) js_prop_from_object(cx, metaobj, prop_create(item, "metadata")); } else if(url != NULL) { if(backend_resolve_item(url, item)) { prop_destroy(item); rstr_release(rurl); return JS_TRUE; } } prop_set_int(prop_create(item, "enabled"), enabled); prop_t *p = prop_ref_inc(item); if(prop_set_parent(item, parent)) { prop_destroy(item); prop_ref_dec(p); } else { JSObject *robj = JS_NewObjectWithGivenProto(cx, &item_class, JSVAL_TO_OBJECT(model->jm_item_proto), NULL); *rval = OBJECT_TO_JSVAL(robj); js_item_t *ji = calloc(1, sizeof(js_item_t)); atomic_add(&model->jm_refcount, 1); ji->ji_url = rstr_dup(rurl); ji->ji_model = model; ji->ji_root = p; TAILQ_INSERT_TAIL(&model->jm_items, ji, ji_link); JS_SetPrivate(cx, robj, ji); ji->ji_enable_set_property = 1; ji->ji_eventsub = prop_subscribe(PROP_SUB_TRACK_DESTROY, PROP_TAG_CALLBACK, js_item_eventsub, ji, PROP_TAG_ROOT, ji->ji_root, PROP_TAG_COURIER, model->jm_pc, NULL); model->jm_subs++; ji->ji_this = OBJECT_TO_JSVAL(robj); JS_AddNamedRoot(cx, &ji->ji_this, "item_this"); prop_tag_set(ji->ji_root, model, ji); } rstr_release(rurl); return JS_TRUE; }
void rs::jsapi::Global::SetFunctionState(JSObject* obj, GlobalFunctionState* state) { JS_SetPrivate(obj, state); }
/* attribute JSContext safeJSContext; */ NS_IMETHODIMP XPCJSContextStack::GetSafeJSContext(JSContext * *aSafeJSContext) { if(!mSafeJSContext) { #ifndef XPCONNECT_STANDALONE // Start by getting the principal holder and principal for this // context. If we can't manage that, don't bother with the rest. nsCOMPtr<nsIPrincipal> principal = do_CreateInstance("@mozilla.org/nullprincipal;1"); nsCOMPtr<nsIScriptObjectPrincipal> sop; if(principal) { sop = new PrincipalHolder(principal); } if(!sop) { *aSafeJSContext = nsnull; return NS_ERROR_FAILURE; } #endif /* !XPCONNECT_STANDALONE */ JSRuntime *rt; XPCJSRuntime* xpcrt; nsXPConnect* xpc = nsXPConnect::GetXPConnect(); nsCOMPtr<nsIXPConnect> xpcholder(static_cast<nsIXPConnect*>(xpc)); if(xpc && (xpcrt = xpc->GetRuntime()) && (rt = xpcrt->GetJSRuntime())) { mSafeJSContext = JS_NewContext(rt, 8192); if(mSafeJSContext) { // scoped JS Request AutoJSRequestWithNoCallContext req(mSafeJSContext); JSObject *glob; glob = JS_NewObject(mSafeJSContext, &global_class, NULL, NULL); #ifndef XPCONNECT_STANDALONE if(glob) { // Note: make sure to set the private before calling // InitClasses nsIScriptObjectPrincipal* priv = nsnull; sop.swap(priv); if(!JS_SetPrivate(mSafeJSContext, glob, priv)) { // Drop the whole thing NS_RELEASE(priv); glob = nsnull; } } // After this point either glob is null and the // nsIScriptObjectPrincipal ownership is either handled by the // nsCOMPtr or dealt with, or we'll release in the finalize // hook. #endif if(!glob || NS_FAILED(xpc->InitClasses(mSafeJSContext, glob))) { // Explicitly end the request since we are about to kill // the JSContext that 'req' will try to use when it // goes out of scope. req.EndRequest(); JS_DestroyContext(mSafeJSContext); mSafeJSContext = nsnull; } // Save it off so we can destroy it later, even if // mSafeJSContext has been set to another context // via SetSafeJSContext. If we don't get here, // then mSafeJSContext must have been set via // SetSafeJSContext, and we're not responsible for // destroying the passed-in context. mOwnSafeJSContext = mSafeJSContext; } } } *aSafeJSContext = mSafeJSContext; return mSafeJSContext ? NS_OK : NS_ERROR_UNEXPECTED; }
void CoreTexture_finalize(JSFreeOp *fop, JSObject *obj) { CoreTexture* tex = (CoreTexture*)JS_GetPrivate(obj); JS_SetPrivate(obj, NULL); delete tex; }
JSBool constructorVideo(JSContext *cx, uintN argc, jsval *vp) { if(argc>0){ char *fName = NULL; char defer_load = 0; if(JSVAL_IS_STRING(JS_ARGV(cx,vp)[0])){ JSString *str = NULL; str = JSVAL_TO_STRING(JS_ARGV(cx,vp)[0]); if(str) fName = JS_EncodeString(cx,str); } if(argc > 1 && JSVAL_IS_BOOLEAN(JS_ARGV(cx,vp)[1])){ defer_load = JSVAL_TO_BOOLEAN(JS_ARGV(cx,vp)[1]); } if(fName){ video *vid = NULL; //Turn this into a fullpath! char *fullpath = contextChroot(cx,fName); if(!fullpath) { fprint(stderr,"Unable to chroot filepath\n"); return JS_FALSE; } JS_free(cx,fName); struct video_backend* vb = get_video_backend(fullpath); if(!vb) { fprint(stderr,"No video backend to handle file %s\n.",fullpath); return JS_FALSE; } vid = vb->openVideo(fullpath,cx); free(fullpath); if(vid){ //set function pointer table vid->vb = vb; //if(!(vid->tx)) fprint(stderr,"ERROR in openVideo creating texture\n"); JSObject *ob = NULL; ob = JS_NewObject(cx, &videoClass,NULL,NULL); if(ob){ JS_SetPrivate(cx,ob,vid); imageAddProps(cx,ob); imageAddFuncs(cx,ob); if(defer_load) { print("Am deferring!\n"); vid->vb->destroyVideoPlayback(vid); //if(vid->tx) // SDL_DestroyTexture(vid->tx); //vid->tx = SDL_CreateTexture(renderer,SDL_PIXELFORMAT_RGB24 ,SDL_TEXTUREACCESS_STREAMING, 1, 1); //temporary } JS_SET_RVAL(cx,vp,OBJECT_TO_JSVAL(ob)); return JS_TRUE; } } else { fprint(stderr,"ERROR in openVideo\n"); } } fprint(stderr,"Unable to create video\n"); } return JS_TRUE; }
JSObject * LM_ReflectNamedAnchor(MWContext *context, lo_NameList *name_rec, PA_Tag * tag, int32 layer_id, uint index) { JSObject *obj, *array_obj, *document; MochaDecoder *decoder; JSContext *cx; JSObjectArray *array; JSAnchor *named_anchor; lo_TopState *top_state; PRHashTable *map; JSString *str; obj = name_rec->mocha_object; if (obj) return obj; decoder = LM_GetMochaDecoder(context); if (!decoder) return NULL; cx = decoder->js_context; top_state = lo_GetMochaTopState(context); if (top_state->resize_reload) { map = lm_GetIdToObjectMap(decoder); if (map) obj = (JSObject *)PR_HashTableLookup(map, LM_GET_MAPPING_KEY(LM_NAMEDANCHORS, layer_id, index)); if (obj) { name_rec->mocha_object = obj; LM_PutMochaDecoder(decoder); return obj; } } /* Get the document object that will hold this anchor */ document = lm_GetDocumentFromLayerId(decoder, layer_id); if (!document) { LM_PutMochaDecoder(decoder); return NULL; } array_obj = lm_GetNameArray(decoder, document); if (!array_obj) { LM_PutMochaDecoder(decoder); return NULL; } array = JS_GetPrivate(cx, array_obj); if (!array) { LM_PutMochaDecoder(decoder); return NULL; } named_anchor = JS_malloc(cx, sizeof *named_anchor); if (!named_anchor) { LM_PutMochaDecoder(decoder); return NULL; } XP_BZERO(named_anchor, sizeof *named_anchor); obj = JS_NewObject(cx, &lm_anchor_class, decoder->anchor_prototype, document); if (!obj || !JS_SetPrivate(cx, obj, named_anchor)) { JS_free(cx, named_anchor); LM_PutMochaDecoder(decoder); return NULL; } /* Put obj into the document.anchors array. */ JS_DefineProperty(cx, array_obj, (char *) name_rec->name, OBJECT_TO_JSVAL(obj), NULL, NULL, JSPROP_ENUMERATE|JSPROP_READONLY); JS_AliasElement(cx, array_obj, (char *) name_rec->name, index); /* Put it in the index to object hash table */ map = lm_GetIdToObjectMap(decoder); if (map) { PR_HashTableAdd(map, LM_GET_MAPPING_KEY(LM_NAMEDANCHORS, layer_id, index), obj); } if ((jsint) index >= array->length) array->length = index + 1; named_anchor->decoder = HOLD_BACK_COUNT(decoder); named_anchor->layer_id = layer_id; named_anchor->index = index; if (name_rec->element && name_rec->element->type == LO_TEXT) { str = lm_LocalEncodingToStr(context, (char *) name_rec->element->lo_text.text); if (!str || !JS_LockGCThing(cx, str)) { LM_PutMochaDecoder(decoder); return NULL; } named_anchor->text = str; } str = JS_NewStringCopyZ(cx, (char *) name_rec->name); if (!str || !JS_LockGCThing(cx, str)) { LM_PutMochaDecoder(decoder); return NULL; } named_anchor->name = str; name_rec->mocha_object = obj; /* see if there are any attributes for event handlers */ if(tag) { PA_Block onlocate, id; /* don't hold the layout lock across compiles */ LO_UnlockLayout(); onlocate = lo_FetchParamValue(context, tag, PARAM_ONLOCATE); id = lo_FetchParamValue(context, tag, PARAM_ID); if (onlocate) { (void) lm_CompileEventHandler(decoder, id, tag->data, tag->newline_count, obj, PARAM_ONLOCATE, onlocate); PA_FREE(onlocate); } if (id) PA_FREE(id); LO_LockLayout(); } LM_PutMochaDecoder(decoder); return obj; }
void rs::jsapi::Object::SetState(JSObject* obj, ObjectState* state) { JS_SetPrivate(obj, state); }
static JSObject* ns_new(JSContext *context, const char *ns_name) { JSObject *ns; JSObject *global; Ns *priv; JSBool found; /* put constructor in the global namespace */ global = gjs_get_import_global(context); if (!JS_HasProperty(context, global, gjs_ns_class.name, &found)) return NULL; if (!found) { JSObject *prototype; prototype = JS_InitClass(context, global, /* parent prototype JSObject* for * prototype; NULL for * Object.prototype */ NULL, &gjs_ns_class, /* constructor for instances (NULL for * none - just name the prototype like * Math - rarely correct) */ gjs_ns_constructor, /* number of constructor args */ 0, /* props of prototype */ &gjs_ns_proto_props[0], /* funcs of prototype */ &gjs_ns_proto_funcs[0], /* props of constructor, MyConstructor.myprop */ NULL, /* funcs of constructor, MyConstructor.myfunc() */ NULL); if (prototype == NULL) g_error("Can't init class %s", gjs_ns_class.name); gjs_debug(GJS_DEBUG_GNAMESPACE, "Initialized class %s prototype %p", gjs_ns_class.name, prototype); } ns = JS_NewObject(context, &gjs_ns_class, NULL, global); if (ns == NULL) g_error("No memory to create ns object"); priv = g_slice_new0(Ns); GJS_INC_COUNTER(ns); g_assert(priv_from_js(context, ns) == NULL); JS_SetPrivate(ns, priv); gjs_debug_lifecycle(GJS_DEBUG_GNAMESPACE, "ns constructor, obj %p priv %p", ns, priv); priv = priv_from_js(context, ns); priv->gi_namespace = g_strdup(ns_name); return ns; }
/* * Called from the JSOP_GENERATOR case in the interpreter, with fp referring * to the frame by which the generator function was activated. Create a new * JSGenerator object, which contains its own JSStackFrame that we populate * from *fp. We know that upon return, the JSOP_GENERATOR opcode will return * from the activation in fp, so we can steal away fp->callobj and fp->argsobj * if they are non-null. */ JSObject * js_NewGenerator(JSContext *cx, JSStackFrame *fp) { JSObject *obj; uintN argc, nargs, nvars, nslots; JSGenerator *gen; jsval *slots; /* After the following return, failing control flow must goto bad. */ obj = js_NewObject(cx, &js_GeneratorClass, NULL, NULL, 0); if (!obj) return NULL; /* Load and compute stack slot counts. */ argc = fp->argc; nargs = JS_MAX(argc, fp->fun->nargs); nvars = fp->fun->u.i.nvars; nslots = 2 + nargs + fp->script->nslots; /* Allocate obj's private data struct. */ gen = (JSGenerator *) JS_malloc(cx, sizeof(JSGenerator) + (nslots - 1) * sizeof(jsval)); if (!gen) goto bad; gen->obj = obj; /* Steal away objects reflecting fp and point them at gen->frame. */ gen->frame.callobj = fp->callobj; if (fp->callobj) { JS_SetPrivate(cx, fp->callobj, &gen->frame); fp->callobj = NULL; } gen->frame.argsobj = fp->argsobj; if (fp->argsobj) { JS_SetPrivate(cx, fp->argsobj, &gen->frame); fp->argsobj = NULL; } /* These two references can be shared with fp until it goes away. */ gen->frame.varobj = fp->varobj; gen->frame.thisp = fp->thisp; /* Copy call-invariant script and function references. */ gen->frame.script = fp->script; gen->frame.callee = fp->callee; gen->frame.fun = fp->fun; /* Use slots to carve space out of gen->slots. */ slots = gen->slots; gen->arena.next = NULL; gen->arena.base = (jsuword) slots; gen->arena.limit = gen->arena.avail = (jsuword) (slots + nslots); /* Copy rval, argv and vars. */ gen->frame.rval = fp->rval; memcpy(slots, fp->argv - 2, (2 + nargs) * sizeof(jsval)); gen->frame.argc = nargs; gen->frame.argv = slots + 2; slots += 2 + nargs; memcpy(slots, fp->slots, fp->script->nfixed * sizeof(jsval)); /* Initialize or copy virtual machine state. */ gen->frame.down = NULL; gen->frame.annotation = NULL; gen->frame.scopeChain = fp->scopeChain; gen->frame.slots = slots; JS_ASSERT(StackBase(fp) == fp->regs->sp); gen->savedRegs.sp = slots + fp->script->nfixed; gen->savedRegs.pc = fp->regs->pc; gen->frame.regs = &gen->savedRegs; /* Copy remaining state (XXX sharp* and xml* should be local vars). */ gen->frame.sharpDepth = 0; gen->frame.sharpArray = NULL; gen->frame.flags = (fp->flags & ~JSFRAME_ROOTED_ARGV) | JSFRAME_GENERATOR; gen->frame.dormantNext = NULL; gen->frame.xmlNamespace = NULL; gen->frame.blockChain = NULL; /* Note that gen is newborn. */ gen->state = JSGEN_NEWBORN; if (!JS_SetPrivate(cx, obj, gen)) { JS_free(cx, gen); goto bad; } return obj; bad: cx->weakRoots.newborn[GCX_OBJECT] = NULL; return NULL; }
static void js_sub_query(subtitle_provider_t *SP, sub_scanner_t *ss, int score, int autosel) { js_subprovider_t *sp = (js_subprovider_t *)SP; JSContext *cx = js_newctx(NULL); JS_BeginRequest(cx); if(ss != NULL) { JSObject *obj = JS_NewObject(cx, &subreq_class, NULL, NULL); JS_AddNamedRoot(cx, &obj, "subscanner"); if(sp->sp_jsp != NULL) usage_inc_plugin_counter(sp->sp_jsp->jsp_id, "subsearch", 1); js_sub_job_t *jsj = malloc(sizeof(js_sub_job_t)); jsj->jsj_ss = ss; jsj->jsj_score = score; jsj->jsj_autosel = autosel; sub_scanner_retain(ss); JS_SetPrivate(cx, obj, jsj); JS_DefineFunctions(cx, obj, sub_functions); js_set_prop_rstr(cx, obj, "title", ss->ss_title); js_set_prop_rstr(cx, obj, "imdb", ss->ss_imdbid); if(ss->ss_season > 0) js_set_prop_int(cx, obj, "season", ss->ss_season); if(ss->ss_year > 0) js_set_prop_int(cx, obj, "year", ss->ss_year); if(ss->ss_episode > 0) js_set_prop_int(cx, obj, "episode", ss->ss_episode); if(ss->ss_fsize > 0) js_set_prop_dbl(cx, obj, "filesize", ss->ss_fsize); if(ss->ss_hash_valid) { char str[64]; snprintf(str, sizeof(str), "%016" PRIx64, ss->ss_opensub_hash); js_set_prop_str(cx, obj, "opensubhash", str); bin2hex(str, sizeof(str), ss->ss_subdbhash, 16); js_set_prop_str(cx, obj, "subdbhash", str); } if(ss->ss_duration > 0) js_set_prop_int(cx, obj, "duration", ss->ss_duration); jsval result; jsval arg = OBJECT_TO_JSVAL(obj); JS_CallFunctionValue(cx, NULL, sp->sp_func, 1, &arg, &result); JS_RemoveRoot(cx, &obj); } js_subprovider_release(cx, sp); JS_DestroyContext(cx); }
void * spidermonkey_get_interpreter(struct ecmascript_interpreter *interpreter) { JSContext *ctx; JSObject *window_obj, *document_obj, *forms_obj, *history_obj, *location_obj, *statusbar_obj, *menubar_obj, *navigator_obj; assert(interpreter); if (!js_module_init_ok) return NULL; ctx = JS_NewContext(spidermonkey_runtime, 8192 /* Stack allocation chunk size */); if (!ctx) return NULL; interpreter->backend_data = ctx; JS_SetContextPrivate(ctx, interpreter); JS_SetOptions(ctx, JSOPTION_VAROBJFIX | JSOPTION_JIT | JSOPTION_METHODJIT); JS_SetVersion(ctx, JSVERSION_LATEST); JS_SetErrorReporter(ctx, error_reporter); #if defined(CONFIG_ECMASCRIPT_SMJS_HEARTBEAT) JS_SetOperationCallback(ctx, heartbeat_callback); #endif window_obj = JS_NewCompartmentAndGlobalObject(ctx, (JSClass *) &window_class, NULL); if (!window_obj) goto release_and_fail; if (!JS_InitStandardClasses(ctx, window_obj)) goto release_and_fail; if (!JS_DefineProperties(ctx, window_obj, (JSPropertySpec *) window_props)) goto release_and_fail; if (!spidermonkey_DefineFunctions(ctx, window_obj, window_funcs)) goto release_and_fail; if (!JS_SetPrivate(ctx, window_obj, interpreter->vs)) /* to @window_class */ goto release_and_fail; document_obj = spidermonkey_InitClass(ctx, window_obj, NULL, (JSClass *) &document_class, NULL, 0, (JSPropertySpec *) document_props, document_funcs, NULL, NULL); if (!document_obj) goto release_and_fail; forms_obj = spidermonkey_InitClass(ctx, document_obj, NULL, (JSClass *) &forms_class, NULL, 0, (JSPropertySpec *) forms_props, forms_funcs, NULL, NULL); if (!forms_obj) goto release_and_fail; history_obj = spidermonkey_InitClass(ctx, window_obj, NULL, (JSClass *) &history_class, NULL, 0, (JSPropertySpec *) NULL, history_funcs, NULL, NULL); if (!history_obj) goto release_and_fail; location_obj = spidermonkey_InitClass(ctx, window_obj, NULL, (JSClass *) &location_class, NULL, 0, (JSPropertySpec *) location_props, location_funcs, NULL, NULL); if (!location_obj) goto release_and_fail; menubar_obj = JS_InitClass(ctx, window_obj, NULL, (JSClass *) &menubar_class, NULL, 0, (JSPropertySpec *) unibar_props, NULL, NULL, NULL); if (!menubar_obj) goto release_and_fail; if (!JS_SetPrivate(ctx, menubar_obj, "t")) /* to @menubar_class */ goto release_and_fail; statusbar_obj = JS_InitClass(ctx, window_obj, NULL, (JSClass *) &statusbar_class, NULL, 0, (JSPropertySpec *) unibar_props, NULL, NULL, NULL); if (!statusbar_obj) goto release_and_fail; if (!JS_SetPrivate(ctx, statusbar_obj, "s")) /* to @statusbar_class */ goto release_and_fail; navigator_obj = JS_InitClass(ctx, window_obj, NULL, (JSClass *) &navigator_class, NULL, 0, (JSPropertySpec *) navigator_props, NULL, NULL, NULL); if (!navigator_obj) goto release_and_fail; return ctx; release_and_fail: spidermonkey_put_interpreter(interpreter); return NULL; }
/* Wrap a JS value to export into perl * Returns a new SV, REFCNT_dec is caller's responsability */ JSBool PJS_ReflectJS2Perl( pTHX_ JSContext *cx, jsval value, SV** sv, int full ) { if(JSVAL_IS_PRIMITIVE(value)) { *sv = PrimJSVALToSV(aTHX_ cx, value); if(*sv) return JS_TRUE; } else if(JSVAL_IS_OBJECT(value)) { PJS_Context *pcx = PJS_GET_CONTEXT(cx); JSObject *object = JSVAL_TO_OBJECT(value); JSClass *clasp = PJS_GET_CLASS(cx, object); const char *classname = clasp->name; JSObject *passport; SV *wrapper; SV *box; char hkey[32]; jsval temp = JSVAL_VOID; snprintf(hkey, 32, "%p", (void *)object); PJS_DEBUG2("Wrapping a %s(%s)\n", classname, hkey); if(PJS_getFlag(pcx, "ConvertRegExp") && strEQ(classname, "RegExp")) { jsval src; char *str; if(JS_CallFunctionName(cx, object, "toSource", 0, NULL, &src) && (str = JS_GetStringBytes(JS_ValueToString(cx, src))) ) { dSP; SV *tmp = newSVpvf("qr%s", str); eval_sv(tmp, G_SCALAR); sv_free(tmp); // Don't leak SPAGAIN; tmp = POPs; PUTBACK; if(!SvTRUE(ERRSV)) { *sv = SvREFCNT_inc_simple_NN(tmp); return JS_TRUE; } } return JS_FALSE; } if(IS_PERL_CLASS(clasp)) { /* IS_PERL_CLASS means actual perl object is there */ SV *priv = (SV *)JS_GetPrivate(cx, object); if(priv && SvOK(priv) && SvROK(priv)) { *sv = SvREFCNT_inc_simple_NN(priv); return JS_TRUE; } croak("A private %s?!\n", classname); return JS_FALSE; } /* Common JSObject case */ /* Check registered perl visitors */ JS_LookupProperty(cx, pcx->pvisitors, hkey, &temp); if(temp != JSVAL_VOID) { /* Already registered, so exits a reference in perl space * _must_ hold a PASSPORT */ assert(JSVAL_TO_OBJECT(temp) == object); box = PJS_GetPassport(aTHX_ cx, object); SvREFCNT_inc_void_NN(box); /* In perl should be one more */ PJS_DEBUG1("Cached!: %s\n", hkey); } else { /* Check if with a PASSPORT */ JS_LookupPropertyWithFlags(cx, object, PJS_PASSPORT_PROP, 0, &temp); if(JSVAL_IS_OBJECT(temp) && (passport = JSVAL_TO_OBJECT(temp)) && PJS_GET_CLASS(cx, passport) == &passport_class && JS_GetReservedSlot(cx, passport, 0, &temp) && object == (JSObject *)JSVAL_TO_PRIVATE(temp) ) { /* Yes, reentering perl */ box = (SV *)JS_GetPrivate(cx, passport); /* Here we don't increment refcount, the ownership in passport is * transferred to perl land. */ PJS_DEBUG1("Reenter: %s\n", hkey); } else { /* No, first time, must wrap the object */ SV *boxref; const char *package; SV *robj = newSV(0); SV *rjsv = newSV(0); if (JS_ObjectIsFunction(cx, object)) package = PJS_FUNCTION_PACKAGE; else if(JS_IsArrayObject(cx, object)) package = PJS_ARRAY_PACKAGE; else if(strEQ(classname, PJS_PACKAGE_CLASS_NAME)) package = PJS_STASH_PACKAGE; #if JS_HAS_XML_SUPPORT else if(strEQ(classname, "XML")) package = PJS_XMLOBJ_PACKAGE; #endif else if(strEQ(classname, "Error")) package = PJS_ERROR_PACKAGE; else { SV **sv = hv_fetch(get_hv(NAMESPACE"ClassMap", 1), classname, strlen(classname), 0); if(sv) package = SvPV_nolen(*sv); else package = PJS_OBJECT_PACKAGE; } sv_setref_pv(robj, PJS_RAW_OBJECT, (void*)object); sv_setref_iv(rjsv, PJS_RAW_JSVAL, (IV)value); boxref = PJS_CallPerlMethod(aTHX_ cx, "__new", sv_2mortal(newSVpv(package, 0)), // package sv_2mortal(robj), // content sv_2mortal(rjsv), // jsval NULL ); if(!boxref) return JS_FALSE; if(!SvOK(boxref) || !sv_derived_from(boxref, PJS_BOXED_PACKAGE)) croak("PJS_Assert: Contructor must return a "NAMESPACE"Boxed"); /* Create a new PASSPORT */ passport = JS_NewObject(cx, &passport_class, NULL, object); if(!passport || !JS_DefineProperty(cx, object, PJS_PASSPORT_PROP, OBJECT_TO_JSVAL(passport), NULL, NULL, JSPROP_READONLY | JSPROP_PERMANENT)) return JS_FALSE; box = SvRV(boxref); /* boxref is mortal, so we need to increment its rc, at end of * scope, PASSPORT owns created box */ JS_SetPrivate(cx, passport, (void *)SvREFCNT_inc_simple_NN(box)); JS_SetReservedSlot(cx, passport, 0, PRIVATE_TO_JSVAL(object)); PJS_DEBUG2("New boxed: %s brc: %d\n", hkey, SvREFCNT(box)); } /* Root object adding it to pvisitors list, will be unrooted by * jsc_free_root at Boxed DESTROY time */ JS_DefineProperty(cx, pcx->pvisitors, hkey, value, NULL, NULL, 0); } /* Here the RC of box in PASSPORT reflects wrapper's ownership */ if(full && PJS_getFlag(pcx, "AutoTie") && (strEQ(classname, "Object") || strEQ(classname, "Array")) ) { /* Return tied */ AV *avbox = (AV *)SvRV(box); SV **last; SV *tied; SV *tier; if(strEQ(classname, "Array")) { last = av_fetch(avbox, 6, 1); if(last && SvOK(*last) && SvROK(*last)) { // Cached *sv = newSVsv(*last); sv_free(box); /* Hard copy 'sv' owns the reference */ return JS_TRUE; } tied = (SV *)newAV(); } else { // Object last = av_fetch(avbox, 5, 1); if(last && SvOK(*last) && SvROK(*last)) { // Cached *sv = newSVsv(*last); sv_free(box); /* Hard copy 'sv' owns the reference */ return JS_TRUE; } tied = (SV *)newHV(); } /* hv_magic below own a reference to box, we use an explicit path, * to make clear that to perl land only one reference is given */ tier = newRV_inc(box); hv_magic((HV *)tied, (GV *)tier, PERL_MAGIC_tied); sv_free(tier); wrapper = newRV_noinc(tied); /* Don't leak the hidden tied variable */ /* Save in cache a weaken copy, the cache itself dosn't hold a reference */ sv_setsv(*last, wrapper); sv_rvweaken(*last); PJS_DEBUG1("Return tied for %s\n", SvPV_nolen(tier)); } else { wrapper = newRV_noinc(box); /* Transfer ownership to wrapper */ #if PERL_VERSION < 9 sv_bless(wrapper, SvSTASH(box)); #endif } *sv = wrapper; return JS_TRUE; } return JS_FALSE; }
int js_plugin_load(const char *id, const char *url, char *errbuf, size_t errlen) { char *sbuf; struct fa_stat fs; JSContext *cx; js_plugin_t *jsp; JSObject *pobj, *gobj; JSScript *s; char path[PATH_MAX]; jsval val; fa_handle_t *ref; ref = fa_reference(url); if((sbuf = fa_quickload(url, &fs, NULL, errbuf, errlen)) == NULL) { fa_unreference(ref); return -1; } cx = js_newctx(err_reporter); JS_BeginRequest(cx); /* Remove any plugin with same URL */ LIST_FOREACH(jsp, &js_plugins, jsp_link) if(!strcmp(jsp->jsp_id, id)) break; if(jsp != NULL) js_plugin_unload0(cx, jsp); jsp = calloc(1, sizeof(js_plugin_t)); jsp->jsp_url = strdup(url); jsp->jsp_id = strdup(id); jsp->jsp_ref = ref; LIST_INSERT_HEAD(&js_plugins, jsp, jsp_link); gobj = JS_NewObject(cx, &global_class, NULL, NULL); JS_InitStandardClasses(cx, gobj); JS_DefineProperty(cx, gobj, "showtime", OBJECT_TO_JSVAL(showtimeobj), NULL, NULL, JSPROP_READONLY | JSPROP_PERMANENT); /* Plugin object */ pobj = JS_NewObject(cx, &plugin_class, NULL, gobj); JS_AddNamedRoot(cx, &pobj, "plugin"); JS_SetPrivate(cx, pobj, jsp); JS_DefineFunctions(cx, pobj, plugin_functions); val = STRING_TO_JSVAL(JS_NewStringCopyZ(cx, url)); JS_SetProperty(cx, pobj, "url", &val); if(!fa_parent(path, sizeof(path), url)) { val = STRING_TO_JSVAL(JS_NewStringCopyZ(cx, path)); JS_SetProperty(cx, pobj, "path", &val); } JS_DefineProperty(cx, pobj, "URIRouting", BOOLEAN_TO_JSVAL(1), NULL, jsp_setEnableURIRoute, JSPROP_PERMANENT); jsp->jsp_enable_uri_routing = 1; JS_DefineProperty(cx, pobj, "search", BOOLEAN_TO_JSVAL(1), NULL, jsp_setEnableSearch, JSPROP_PERMANENT); jsp->jsp_enable_search = 1; jsp->jsp_protect_object = 1; s = JS_CompileScript(cx, pobj, sbuf, fs.fs_size, url, 1); free(sbuf); if(s != NULL) { JSObject *sobj = JS_NewScriptObject(cx, s); jsval result; JS_AddNamedRoot(cx, &sobj, "script"); JS_ExecuteScript(cx, pobj, s, &result); JS_RemoveRoot(cx, &sobj); } JS_RemoveRoot(cx, &pobj); JS_EndRequest(cx); JS_GC(cx); JS_DestroyContext(cx); return 0; }
JSObject* gjs_keep_alive_new(JSContext *context) { KeepAlive *priv; JSObject *keep_alive = NULL; JSObject *global; JSBool found; /* This function creates an unattached KeepAlive object; following our * general strategy, we have a single KeepAlive class with a constructor * stored on our single "load global" pseudo-global object, and we create * instances with the load global as parent. */ g_assert(context != NULL); JS_BeginRequest(context); global = gjs_get_import_global(context); g_assert(global != NULL); if (!JS_HasProperty(context, global, gjs_keep_alive_class.name, &found)) goto out; if (!found) { JSObject *prototype; gjs_debug(GJS_DEBUG_KEEP_ALIVE, "Initializing keep-alive class in context %p global %p", context, global); prototype = JS_InitClass(context, global, /* parent prototype JSObject* for * prototype; NULL for * Object.prototype */ NULL, &gjs_keep_alive_class, /* constructor for instances (NULL for * none - just name the prototype like * Math - rarely correct) */ gjs_keep_alive_constructor, /* number of constructor args */ 0, /* props of prototype */ &gjs_keep_alive_proto_props[0], /* funcs of prototype */ &gjs_keep_alive_proto_funcs[0], /* props of constructor, MyConstructor.myprop */ NULL, /* funcs of constructor, MyConstructor.myfunc() */ NULL); if (prototype == NULL) g_error("Can't init class %s", gjs_keep_alive_class.name); gjs_debug(GJS_DEBUG_KEEP_ALIVE, "Initialized class %s prototype %p", gjs_keep_alive_class.name, prototype); } gjs_debug(GJS_DEBUG_KEEP_ALIVE, "Creating new keep-alive object for context %p global %p", context, global); keep_alive = JS_NewObject(context, &gjs_keep_alive_class, NULL, global); if (keep_alive == NULL) { gjs_log_exception(context); g_error("Failed to create keep_alive object"); } priv = g_slice_new0(KeepAlive); priv->children = g_hash_table_new_full(child_hash, child_equal, NULL, child_free); g_assert(priv_from_js(context, keep_alive) == NULL); JS_SetPrivate(keep_alive, priv); gjs_debug_lifecycle(GJS_DEBUG_KEEP_ALIVE, "keep_alive constructor, obj %p priv %p", keep_alive, priv); out: JS_EndRequest(context); return keep_alive; }
void MongoStatusInfo::postInstall(JSContext* cx, JS::HandleObject global, JS::HandleObject proto) { auto scope = getScope(cx); JS_SetPrivate(proto, scope->trackedNew<Status>(Status::OK())); }
static JSBool teletone_construct(JSContext * cx, JSObject * obj, uintN argc, jsval * argv, jsval * rval) { JSObject *session_obj; struct teletone_obj *tto = NULL; struct js_session *jss = NULL; switch_memory_pool_t *pool; char *timer_name = NULL; switch_codec_implementation_t read_impl = { 0 }; if (argc > 0) { if (JS_ValueToObject(cx, argv[0], &session_obj)) { if (!(jss = JS_GetPrivate(cx, session_obj))) { switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_ERROR, "Cannot Find Session [1]\n"); return JS_FALSE; } } else { switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_ERROR, "Cannot Find Session [2]\n"); return JS_FALSE; } } else { switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_ERROR, "Missing Session Arg\n"); return JS_FALSE; } if (argc > 1) { timer_name = JS_GetStringBytes(JS_ValueToString(cx, argv[1])); } switch_core_new_memory_pool(&pool); if (!(tto = switch_core_alloc(pool, sizeof(*tto)))) { switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_CRIT, "Memory Error\n"); return JS_FALSE; } switch_core_session_get_read_impl(jss->session, &read_impl); if (switch_core_codec_init(&tto->codec, "L16", NULL, read_impl.actual_samples_per_second, read_impl.microseconds_per_packet / 1000, read_impl.number_of_channels, SWITCH_CODEC_FLAG_ENCODE | SWITCH_CODEC_FLAG_DECODE, NULL, pool) == SWITCH_STATUS_SUCCESS) { switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_DEBUG, "Raw Codec Activated\n"); } else { switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_DEBUG, "Raw Codec Activation Failed\n"); return JS_FALSE; } if (timer_name) { unsigned int ms = read_impl.microseconds_per_packet / 1000; if (switch_core_timer_init(&tto->timer_base, timer_name, ms, (read_impl.samples_per_second / 50) * read_impl.number_of_channels, pool) == SWITCH_STATUS_SUCCESS) { tto->timer = &tto->timer_base; switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_DEBUG, "Timer INIT Success %u\n", ms); } else { switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_DEBUG, "Timer INIT Failed\n"); } } switch_buffer_create_dynamic(&tto->audio_buffer, JS_BLOCK_SIZE, JS_BUFFER_SIZE, 0); tto->pool = pool; tto->obj = obj; tto->cx = cx; tto->session = jss->session; teletone_init_session(&tto->ts, 0, teletone_handler, tto); JS_SetPrivate(cx, obj, tto); return JS_TRUE; }
static void JSB_IOSiAP_finalize(JSFreeOp *fop, JSObject *obj) { IOSiAP_Bridge *bridge = (IOSiAP_Bridge *)JS_GetPrivate(obj); JS_SetPrivate(obj, NULL); delete bridge; }
NPT_Result GPAC_GenericController::OnActionResponse(NPT_Result res, PLT_ActionReference& action, void* userdata) { #ifdef GPAC_HAS_SPIDERMONKEY u32 i, count; GPAC_DeviceItem *item = NULL; GPAC_ServiceItem *serv = NULL; GPAC_ActionArgListener *argl, *act_l; PLT_Service* service = action->GetActionDesc().GetService(); NPT_String uuid; GPAC_ActionUDTA *act_udta = (GPAC_ActionUDTA *)userdata; /*this is NOT an actionResponse to an action triggered on a generic device*/ if (act_udta && act_udta->m_Reserved) act_udta = NULL; GF_LOG(GF_LOG_INFO, GF_LOG_NETWORK, ("[UPnP] Receive %s Response - error code %d\n", (char *) action->GetActionDesc().GetName(), res)); gf_mx_p(m_ControlPointLock); /*get our device*/ uuid = service->GetDevice()->GetUUID(); count = gf_list_count(m_Devices); for (i=0; i<count; i++) { item = (GPAC_DeviceItem *) gf_list_get(m_Devices, i); if (item->m_UUID == uuid ) { break; } item = NULL; } gf_mx_v(m_ControlPointLock); if (!item) { GF_LOG(GF_LOG_ERROR, GF_LOG_NETWORK, ("[UPnP] Receive %s Response on unknown device (uuid %s)\n", (char *) action->GetActionDesc().GetName(), (char *) uuid)); goto exit; } /*get our service*/ count = gf_list_count(item->m_Services); for (i=0; i<count; i++) { serv = (GPAC_ServiceItem *)gf_list_get(item->m_Services, i); if (serv->m_service == service) break; } if (!serv) { GF_LOG(GF_LOG_ERROR, GF_LOG_NETWORK, ("[UPnP] Receive %s Response on unknown service %s\n", (char *) action->GetActionDesc().GetName(), (char *) service->GetServiceType())); goto exit; } /*locate our listeners*/ act_l = NULL; i=0; while ((argl = (GPAC_ActionArgListener *)gf_list_enum(serv->m_ArgListeners, &i))) { NPT_String value; GF_LOG(GF_LOG_INFO, GF_LOG_NETWORK, ("[UPnP] checking argument %s\n", (char *) argl->action->GetName() )); if (argl->action->GetName() != action->GetActionDesc().GetName() ) continue; /*global action listener*/ if (argl->arg==NULL) { act_l = argl; continue; } /*if error don't trigger listeners*/ if (res != NPT_SUCCESS) { GF_LOG(GF_LOG_WARNING, GF_LOG_NETWORK, ("[UPnP] Receive %s Response: error on remote device %d\n", (char *) action->GetActionDesc().GetName(), res)); continue; } /*action arg listener*/ if (action->GetArgumentValue(argl->arg->GetName(), value) == NPT_SUCCESS) { jsval argv[1], rval; GF_LOG(GF_LOG_INFO, GF_LOG_NETWORK, ("[UPnP] Calling handler for response %s argument %s\n", (char *) action->GetActionDesc().GetName(), (char *) argl->arg->GetName() )); m_pUPnP->LockJavascript(1); argv[0] = STRING_TO_JSVAL( JS_NewStringCopyZ(serv->js_ctx, value) ); JS_CallFunctionValue(serv->js_ctx, serv->obj, argl->on_event, 1, argv, &rval); m_pUPnP->LockJavascript(0); } else { GF_LOG(GF_LOG_ERROR, GF_LOG_NETWORK, ("[UPnP] %s Response: couldn't get argument %s value\n", (char *) action->GetActionDesc().GetName(), (char *) argl->arg->GetName() )); } } if (act_l) { jsval rval; m_pUPnP->LockJavascript(1); if (act_l->is_script) { JSObject *act_obj; jsval argv[2]; GF_LOG(GF_LOG_INFO, GF_LOG_NETWORK, ("[UPnP] Calling handler for response %s\n", (char *) action->GetActionDesc().GetName())); act_obj = JS_NewObject(serv->js_ctx, &item->m_pUPnP->upnpDeviceClass, 0, item->obj); JS_SetPrivate(serv->js_ctx, act_obj, (void *)action.AsPointer() ); JS_DefineFunction(serv->js_ctx, act_obj, "GetArgumentValue", upnp_action_get_argument_value, 1, 0); JS_DefineFunction(serv->js_ctx, act_obj, "GetErrorCode", upnp_action_get_error_code, 1, 0); JS_DefineFunction(serv->js_ctx, act_obj, "GetError", upnp_action_get_error, 1, 0); gf_js_add_root(serv->js_ctx, &act_obj, GF_JSGC_OBJECT); argv[0] = OBJECT_TO_JSVAL(act_obj); if (act_udta) { argv[1] = act_udta->udta; JS_CallFunctionValue(serv->js_ctx, serv->obj, act_l->on_event, 2, argv, &rval); } else { JS_CallFunctionValue(serv->js_ctx, serv->obj, act_l->on_event, 1, argv, &rval); } gf_js_remove_root(serv->js_ctx, &act_obj, GF_JSGC_OBJECT); } /*if error don't trigger listeners*/ else if (res == NPT_SUCCESS) { GF_LOG(GF_LOG_INFO, GF_LOG_NETWORK, ("[UPnP] Calling handler for response %s\n", (char *) action->GetActionDesc().GetName())); JS_CallFunctionValue(serv->js_ctx, serv->obj, act_l->on_event, 0, 0, &rval); } else { GF_LOG(GF_LOG_ERROR, GF_LOG_NETWORK, ("[UPnP] response %s has error %d\n", (char *) action->GetActionDesc().GetName(), res )); } m_pUPnP->LockJavascript(0); } GF_LOG(GF_LOG_INFO, GF_LOG_NETWORK, ("[UPnP] Done processing response %s\n", (char *) action->GetActionDesc().GetName())); exit: if (act_udta) { gf_js_remove_root(serv->js_ctx, &act_udta->udta, GF_JSGC_VAL); delete act_udta; } return NPT_SUCCESS; #else return NPT_SUCCESS; #endif }
JSURL * lm_NewURL(JSContext *cx, MochaDecoder *decoder, LO_AnchorData *anchor_data, JSObject *document) { JSObject *obj; JSURL *url; JSString *str; if (!decoder->url_prototype) { obj = JS_InitClass(cx, decoder->window_object, decoder->event_receiver_prototype, &lm_url_class, Url, 0, url_props, NULL, NULL, NULL); if (!obj) return NULL; decoder->url_prototype = obj; } url = JS_malloc(cx, sizeof *url); if (!url) return NULL; XP_BZERO(url, sizeof *url); obj = JS_NewObject(cx, &lm_url_class, decoder->url_prototype, lm_GetOuterObject(decoder)); if (!obj || !JS_SetPrivate(cx, obj, url)) { JS_free(cx, url); return NULL; } if (!JS_DefineFunctions(cx, obj, url_methods)) return NULL; url->url_decoder = HOLD_BACK_COUNT(decoder); url->url_type = FORM_TYPE_NONE; url->index = URL_NOT_INDEXED; url->url_object = obj; str = JS_NewStringCopyZ(cx, (char *) anchor_data->anchor); if (!str) return NULL; url->href = str; if (!JS_AddNamedRoot(cx, &url->href, "url.href")) return NULL; if (anchor_data->target) { str = JS_NewStringCopyZ(cx, (char *) anchor_data->target); if (!str) return NULL; url->target = str; } if (!JS_AddNamedRoot(cx, &url->target, "url.target")) return NULL; if (anchor_data->element && anchor_data->element->type == LO_TEXT) { str = lm_LocalEncodingToStr(decoder->window_context, (char *) anchor_data->element->lo_text.text); if (!str) return NULL; url->text = str; } if (!JS_AddNamedRoot(cx, &url->text, "url.text")) return NULL; return url; }
JSBool internal_cursor_constructor( JSContext *cx, JSObject *obj, uintN argc, jsval *argv, jsval *rval ){ uassert( "no args to internal_cursor_constructor" , argc == 0 ); assert( JS_SetPrivate( cx , obj , 0 ) ); // just for safety return JS_TRUE; }
JSBool gjs_define_error_class(JSContext *context, JSObject *in_object, GIEnumInfo *info, JSObject **constructor_p, JSObject **prototype_p) { const char *constructor_name; GIBoxedInfo *glib_error_info; JSObject *prototype, *parent_proto; JSObject *constructor; jsval value; Error *priv; /* See the comment in gjs_define_boxed_class() for an * explanation of how this all works; Error is pretty much the * same as Boxed (except that we inherit from GLib.Error). */ constructor_name = g_base_info_get_name( (GIBaseInfo*) info); if (gjs_object_get_property(context, in_object, constructor_name, &value)) { JSObject *constructor; if (!JSVAL_IS_OBJECT(value)) { gjs_throw(context, "Existing property '%s' does not look like a constructor", constructor_name); return JS_FALSE; } constructor = JSVAL_TO_OBJECT(value); gjs_object_get_property(context, constructor, "prototype", &value); if (!JSVAL_IS_OBJECT(value)) { gjs_throw(context, "error %s prototype property does not appear to exist or has wrong type", constructor_name); return JS_FALSE; } else { if (prototype_p) *prototype_p = JSVAL_TO_OBJECT(value); if (constructor_p) *constructor_p = constructor; return JS_TRUE; } } g_irepository_require(NULL, "GLib", "2.0", 0, NULL); glib_error_info = (GIBoxedInfo*) g_irepository_find_by_name(NULL, "GLib", "Error"); parent_proto = gjs_lookup_boxed_prototype(context, glib_error_info); g_base_info_unref((GIBaseInfo*)glib_error_info); if (!gjs_init_class_dynamic(context, in_object, parent_proto, g_base_info_get_namespace( (GIBaseInfo*) info), constructor_name, &gjs_error_class, gjs_error_constructor, 1, /* props of prototype */ &gjs_error_proto_props[0], /* funcs of prototype */ &gjs_error_proto_funcs[0], /* props of constructor, MyConstructor.myprop */ NULL, /* funcs of constructor, MyConstructor.myfunc() */ &gjs_error_constructor_funcs[0], &prototype, &constructor)) { gjs_log_exception(context, NULL); gjs_fatal("Can't init class %s", constructor_name); } GJS_INC_COUNTER(gerror); priv = g_slice_new0(Error); priv->info = info; g_base_info_ref( (GIBaseInfo*) priv->info); priv->domain = g_quark_from_string (g_enum_info_get_error_domain(priv->info)); JS_SetPrivate(context, prototype, priv); gjs_debug(GJS_DEBUG_GBOXED, "Defined class %s prototype is %p class %p in object %p", constructor_name, prototype, JS_GET_CLASS(context, prototype), in_object); gjs_define_enum_values(context, constructor, priv->info); if (constructor_p) *constructor_p = constructor; if (prototype_p) *prototype_p = prototype; return JS_TRUE; }
JSBool JsGlobal::event_GetProperty (JSContext *cx, JSObject *obj, jsid id, jsval *vp) { fsm::StateMachine * pstateMachine = NULL; static log4cplus::Logger log = log4cplus::Logger::getInstance("TUserManager.GetProperty"); pstateMachine = (fsm::StateMachine *)JS_GetContextPrivate(cx); if (!pstateMachine){ LOG4CPLUS_WARN(log,"GetContextPrivate is null."); } if (!JSID_IS_INT(id)) return JS_TRUE; int proid = JSID_TO_INT(id); jsval *val = (jsval *) JS_GetPrivate(cx, obj); if (val) { if(JSVAL_IS_NULL(*vp) || JSVAL_IS_VOID(*vp)) *vp = val[proid]; return JS_TRUE; } val = new jsval[4]; if (!val) { JS_ReportOutOfMemory(cx); JS_SET_RVAL(cx, vp, JSVAL_VOID); return JS_TRUE; } if (!JS_AddValueRoot(cx, val)) { delete[] val; JS_SET_RVAL(cx, vp, JSVAL_VOID); return JS_TRUE; } if (!JS_SetPrivate(cx, obj, (void*)val)) { JS_RemoveValueRoot(cx, val); delete[] val; JS_SET_RVAL(cx, vp, JSVAL_VOID); return JS_TRUE; } std::string prefix = "getting [_event] property:"; fsm::env::Js::IdToString idString(cx, id); if(pstateMachine ){ val[name] = STRING_TO_JSVAL(JS_NewStringCopyZ (cx,pstateMachine->m_currentEvt.getEventName().c_str())); //val[bodydata] = STRING_TO_JSVAL(JS_NewStringCopyZ (cx,pstateMachine->m_currentEvt.getData().c_str())); //val[messagetype] = STRING_TO_JSVAL(JS_NewStringCopyZ (cx,pstateMachine->m_currentEvt.getMsgType().c_str())); //val[ip] = STRING_TO_JSVAL(JS_NewStringCopyZ (cx,pstateMachine->m_currentEvt.getIP().c_str())); //val[port] = INT_TO_JSVAL(pstateMachine->m_currentEvt.getPort()); val[serviceid] = STRING_TO_JSVAL(JS_NewStringCopyZ (cx,pstateMachine->getName().c_str())); val[sessionid] = STRING_TO_JSVAL(JS_NewStringCopyZ (cx,pstateMachine->getSessionId().c_str())); val[callid] = STRING_TO_JSVAL(JS_NewStringCopyZ (cx,pstateMachine->getSessionId().c_str())); switch (proid) { case name: prefix.append("_name"); break; case serviceid: prefix.append("_serviceid"); break; case sessionid: prefix.append("_sessionid"); break; case callid: prefix.append("_callid"); break; //case from:{ // vp.setInt32(pstateMachine->getFrom().c_str()); // break; //case Enable: // vp.setBoolean(extPtr->m_bEnable); // break; default: prefix.append(idString.getBytes()); break; } }else{ prefix.append(idString.getBytes()); } fsm::env::Js::ToString valueString(cx, val[proid]); //fsm::env::Js::ToString objString(cx,OBJECT_TO_JSVAL(obj)); *vp = val[proid]; LOG4CPLUS_DEBUG(log,prefix<< ",value:" << valueString.getBytes()); return JS_TRUE; }
void SetNamespace(JSContext *cx, JSObject *obj, EConfigNamespace cfgNs) { JS_SetPrivate(cx, obj, (void *)((uintptr_t)cfgNs << 1)); // JS requires bottom bit = 0 }
void NumberDecimalInfo::make(JSContext* cx, JS::MutableHandleValue thisv, Decimal128 decimal) { auto scope = getScope(cx); scope->getProto<NumberDecimalInfo>().newObject(thisv); JS_SetPrivate(thisv.toObjectOrNull(), scope->trackedNew<Decimal128>(decimal)); }
void JS_SetPrivate(v8::Handle<v8::Object> pObj, void* p) { JS_SetPrivate(NULL, pObj, p); }
JSBool XPCWrappedNativeProto::Init( XPCCallContext& ccx, JSBool isGlobal, const XPCNativeScriptableCreateInfo* scriptableCreateInfo) { if(scriptableCreateInfo && scriptableCreateInfo->GetCallback()) { mScriptableInfo = XPCNativeScriptableInfo::Construct(ccx, isGlobal, scriptableCreateInfo); if(!mScriptableInfo) return JS_FALSE; } JSClass* jsclazz; if(mScriptableInfo) { const XPCNativeScriptableFlags& flags(mScriptableInfo->GetFlags()); if(flags.AllowPropModsToPrototype()) { jsclazz = flags.WantCall() ? &XPC_WN_ModsAllowed_WithCall_Proto_JSClass : &XPC_WN_ModsAllowed_NoCall_Proto_JSClass; } else { jsclazz = flags.WantCall() ? &XPC_WN_NoMods_WithCall_Proto_JSClass : &XPC_WN_NoMods_NoCall_Proto_JSClass; } } else { jsclazz = &XPC_WN_NoMods_NoCall_Proto_JSClass; } JSObject *parent = mScope->GetGlobalJSObject(); mJSProtoObject = xpc_NewSystemInheritingJSObject(ccx, jsclazz, mScope->GetPrototypeJSObject(), parent); JSBool ok = mJSProtoObject && JS_SetPrivate(ccx, mJSProtoObject, this); if(ok && scriptableCreateInfo) { nsIXPCScriptable *callback = scriptableCreateInfo->GetCallback(); if(callback) { nsresult rv = callback->PostCreatePrototype(ccx, mJSProtoObject); if(NS_FAILED(rv)) { JS_SetPrivate(ccx, mJSProtoObject, nsnull); mJSProtoObject = nsnull; XPCThrower::Throw(rv, ccx); return JS_FALSE; } } } DEBUG_ReportShadowedMembers(mSet, nsnull, this); return ok; }
static JSBool rpmts_getprop(JSContext *cx, JSObject *obj, jsval id, jsval *vp) { void * ptr = JS_GetInstancePrivate(cx, obj, &rpmtsClass, NULL); rpmts ts = ptr; jsint tiny = JSVAL_TO_INT(id); _PROP_DEBUG_ENTRY(_debug < 0); /* XXX the class has ptr == NULL, instances have ptr != NULL. */ if (ptr == NULL) return JS_TRUE; switch (tiny) { case _DEBUG: *vp = INT_TO_JSVAL(_debug); break; case _LENGTH: *vp = INT_TO_JSVAL(rpmtsNElements(ts)); break; case _VSFLAGS: *vp = INT_TO_JSVAL((jsint)rpmtsVSFlags(ts)); break; case _TYPE: *vp = INT_TO_JSVAL((jsint)rpmtsType(ts)); break; case _ARBGOAL: *vp = INT_TO_JSVAL((jsint)rpmtsARBGoal(ts)); break; case _ROOTDIR: *vp = STRING_TO_JSVAL(JS_NewStringCopyZ(cx, rpmtsRootDir(ts))); break; case _CURRDIR: *vp = STRING_TO_JSVAL(JS_NewStringCopyZ(cx, rpmtsCurrDir(ts))); break; case _SELINUX: *vp = INT_TO_JSVAL((jsint)rpmtsSELinuxEnabled(ts)); break; case _CHROOTDONE: *vp = INT_TO_JSVAL((jsint)rpmtsChrootDone(ts)); break; case _TID: *vp = INT_TO_JSVAL((jsint)rpmtsGetTid(ts)); break; case _NELEMENTS: *vp = INT_TO_JSVAL((jsint)rpmtsNElements(ts)); break; case _PROBFILTER: *vp = INT_TO_JSVAL((jsint)rpmtsFilterFlags(ts)); break; case _FLAGS: *vp = INT_TO_JSVAL((jsint)rpmtsFlags(ts)); break; case _DFLAGS: *vp = INT_TO_JSVAL((jsint)rpmtsDFlags(ts)); break; case _GOAL: *vp = INT_TO_JSVAL((jsint)rpmtsGoal(ts)); break; case _DBMODE: *vp = INT_TO_JSVAL((jsint)rpmtsDBMode(ts)); break; case _COLOR: *vp = INT_TO_JSVAL((jsint)rpmtsColor(ts)); break; case _PREFCOLOR: *vp = INT_TO_JSVAL((jsint)rpmtsPrefColor(ts)); break; default: if (JSVAL_IS_INT(id)) { int oc = JSVAL_TO_INT(id); JSObject *teo = NULL; rpmte te = NULL; /* XXX rpmteLink/rpmteUnlink are no-ops */ if ((te = rpmtsElement(ts, oc)) != NULL && (teo = JS_NewObject(cx, &rpmteClass, NULL, NULL)) != NULL && JS_SetPrivate(cx, teo, rpmteLink(te))) { *vp = OBJECT_TO_JSVAL(teo); } break; } #ifdef DYING if (JSVAL_IS_STRING(id)) { JSString * str = JS_ValueToString(cx, id); const char * name = JS_GetStringBytes(str); if (!strcmp(name, "NVRA")) { JSObject * NVRA = rpmtsLoadNVRA(cx, obj); *vp = OBJECT_TO_JSVAL(NVRA); } break; } #endif break; } return JS_TRUE; }
static JSObject* importer_new(JSContext *context, gboolean is_root) { JSObject *importer; Importer *priv; JSObject *global; JSBool found; global = gjs_get_import_global(context); if (!JS_HasProperty(context, global, gjs_importer_class.name, &found)) g_error("HasProperty call failed creating importer class"); if (!found) { JSObject *prototype; prototype = JS_InitClass(context, global, /* parent prototype JSObject* for * prototype; NULL for * Object.prototype */ NULL, &gjs_importer_class, /* constructor for instances (NULL for * none - just name the prototype like * Math - rarely correct) */ gjs_importer_constructor, /* number of constructor args */ 0, /* props of prototype */ &gjs_importer_proto_props[0], /* funcs of prototype */ &gjs_importer_proto_funcs[0], /* props of constructor, MyConstructor.myprop */ NULL, /* funcs of constructor, MyConstructor.myfunc() */ NULL); if (prototype == NULL) g_error("Can't init class %s", gjs_importer_class.name); gjs_debug(GJS_DEBUG_IMPORTER, "Initialized class %s prototype %p", gjs_importer_class.name, prototype); } importer = JS_NewObject(context, &gjs_importer_class, NULL, global); if (importer == NULL) g_error("No memory to create importer importer"); priv = g_slice_new0(Importer); priv->is_root = is_root; GJS_INC_COUNTER(importer); g_assert(priv_from_js(context, importer) == NULL); JS_SetPrivate(importer, priv); gjs_debug_lifecycle(GJS_DEBUG_IMPORTER, "importer constructor, obj %p priv %p", importer, priv); return importer; }