// Caller must root *aJSVal! bool nsEventListenerInfo::GetJSVal(JSContext* aCx, JSAutoEnterCompartment& aAc, jsval* aJSVal) { *aJSVal = JSVAL_NULL; nsCOMPtr<nsIXPConnectWrappedJS> wrappedJS = do_QueryInterface(mListener); if (wrappedJS) { JSObject* object = nsnull; if (NS_FAILED(wrappedJS->GetJSObject(&object)) || !aAc.enter(aCx, object)) { return false; } *aJSVal = OBJECT_TO_JSVAL(object); return true; } nsCOMPtr<nsIJSEventListener> jsl = do_QueryInterface(mListener); if (jsl) { JSObject *handler = static_cast<JSObject*>(jsl->GetHandler()); if (handler) { if (!aAc.enter(aCx, handler)) { return false; } *aJSVal = OBJECT_TO_JSVAL(handler); return true; } } return false; }
nsresult RadioManager::Init() { NS_ASSERTION(NS_IsMainThread(), "We can only initialize on the main thread"); nsCOMPtr<nsIObserverService> obs = do_GetService(NS_OBSERVERSERVICE_CONTRACTID); if (!obs) { NS_WARNING("Failed to get observer service!"); return NS_ERROR_FAILURE; } nsresult rv = obs->AddObserver(this, PROFILE_BEFORE_CHANGE_TOPIC, false); NS_ENSURE_SUCCESS(rv, rv); // The telephony worker component is a hack that gives us a global object for // our own functions and makes creating the worker possible. nsCOMPtr<nsIRadioWorker> worker(do_CreateInstance(kTelephonyWorkerCID)); NS_ENSURE_TRUE(worker, NS_ERROR_FAILURE); jsval workerval; rv = worker->GetWorker(&workerval); NS_ENSURE_SUCCESS(rv, rv); NS_ASSERTION(!JSVAL_IS_PRIMITIVE(workerval), "bad worker value"); JSContext *cx; rv = nsContentUtils::ThreadJSContextStack()->GetSafeJSContext(&cx); NS_ENSURE_SUCCESS(rv, rv); nsCxPusher pusher; if (!cx || !pusher.Push(cx, false)) { return NS_ERROR_FAILURE; } JSObject *workerobj = JSVAL_TO_OBJECT(workerval); JSAutoRequest ar(cx); JSAutoEnterCompartment ac; if (!ac.enter(cx, workerobj)) { return NS_ERROR_OUT_OF_MEMORY; } WorkerCrossThreadDispatcher *wctd = GetWorkerCrossThreadDispatcher(cx, workerval); if (!wctd) { return NS_ERROR_FAILURE; } nsRefPtr<ConnectWorkerToRIL> connection = new ConnectWorkerToRIL(); if (!wctd->PostTask(connection)) { return NS_ERROR_UNEXPECTED; } // Now that we're set up, connect ourselves to the RIL thread. mozilla::RefPtr<RILReceiver> receiver = new RILReceiver(wctd); StartRil(receiver); mTelephone = do_QueryInterface(worker); NS_ENSURE_TRUE(mTelephone, NS_ERROR_FAILURE); return NS_OK; }
// Try to get the the document corresponding to the given JSStackFrame. static already_AddRefed<nsIDocument> GetFrameDocument(JSContext *cx, JSStackFrame *fp) { if (!cx || !fp) return nsnull; JSObject* scope = JS_GetGlobalForFrame(fp); if (!scope) return nsnull; JSAutoEnterCompartment ac; if (!ac.enter(cx, scope)) return nsnull; nsCOMPtr<nsIDOMWindow> window = do_QueryInterface(nsJSUtils::GetStaticScriptGlobal(cx, scope)); if (!window) return nsnull; // If it's a window, get its document. nsCOMPtr<nsIDOMDocument> domDoc; window->GetDocument(getter_AddRefs(domDoc)); nsCOMPtr<nsIDocument> doc = do_QueryInterface(domDoc); return doc.forget(); }
bool JSRuntime::initSelfHosting(JSContext *cx) { JS_ASSERT(!selfHostedGlobal_); RootedObject savedGlobal(cx, JS_GetGlobalObject(cx)); if (!(selfHostedGlobal_ = JS_NewGlobalObject(cx, &self_hosting_global_class, NULL))) return false; JS_SetGlobalObject(cx, selfHostedGlobal_); JSAutoEnterCompartment ac; if (!ac.enter(cx, cx->global())) return false; const char *src = selfhosted::raw_sources; uint32_t srcLen = selfhosted::GetRawScriptsSize(); CompileOptions options(cx); options.setFileAndLine("self-hosted", 1); options.setSelfHostingMode(true); RootedObject shg(cx, selfHostedGlobal_); Value rv; if (!Evaluate(cx, shg, options, src, srcLen, &rv)) return false; JS_SetGlobalObject(cx, savedGlobal); return true; }
bool SmsRequest::SetSuccessInternal(nsISupports* aObject) { NS_PRECONDITION(!mDone, "mDone shouldn't have been set to true already!"); NS_PRECONDITION(mError == eNoError, "mError shouldn't have been set!"); NS_PRECONDITION(mResult == JSVAL_VOID, "mResult shouldn't have been set!"); JSContext* cx = mScriptContext->GetNativeContext(); NS_ASSERTION(cx, "Failed to get a context!"); JSObject* global = mScriptContext->GetNativeGlobal(); NS_ASSERTION(global, "Failed to get global object!"); JSAutoRequest ar(cx); JSAutoEnterCompartment ac; if (!ac.enter(cx, global)) { SetError(eInternalError); return false; } RootResult(); if (NS_FAILED(nsContentUtils::WrapNative(cx, global, aObject, &mResult))) { UnrootResult(); mResult = JSVAL_VOID; SetError(eInternalError); return false; } mDone = true; return true; }
static JSBool holder_set(JSContext *cx, JSObject *wrapper, jsid id, JSBool strict, jsval *vp) { wrapper = FindWrapper(wrapper); JSObject *holder = GetHolder(wrapper); if (IsResolving(holder, id)) { return true; } XPCWrappedNative *wn = GetWrappedNativeFromHolder(holder); if (NATIVE_HAS_FLAG(wn, WantSetProperty)) { JSAutoEnterCompartment ac; if (!ac.enter(cx, holder)) return false; PRBool retval = true; nsresult rv = wn->GetScriptableCallback()->SetProperty(wn, cx, wrapper, id, vp, &retval); if (NS_FAILED(rv) || !retval) { if (retval) XPCThrower::Throw(rv, cx); return false; } } return true; }
bool XrayWrapper<Base>::delete_(JSContext *cx, JSObject *wrapper, jsid id, bool *bp) { JSObject *holder = GetHolder(wrapper); jsval v; JSBool b; // Redirect access straight to the wrapper if we should be transparent. if (XrayUtils::IsTransparent(cx, wrapper)) { JSObject *wnObject = GetWrappedNativeObjectFromHolder(holder); JSAutoEnterCompartment ac; if (!ac.enter(cx, wnObject)) return false; if (!JS_DeletePropertyById2(cx, wnObject, id, &v) || !JS_ValueToBoolean(cx, v, &b)) return false; *bp = !!b; return true; } JSObject *expando = GetExpandoObject(holder); b = true; if (expando && (!JS_DeletePropertyById2(cx, expando, id, &v) || !JS_ValueToBoolean(cx, v, &b))) { return false; } *bp = !!b; return true; }
JSBool TestShellCommandParent::RunCallback(const nsString& aResponse) { NS_ENSURE_TRUE(mCallback != JSVAL_NULL && mCx, JS_FALSE); JSAutoRequest ar(mCx); JSObject* global = JS_GetGlobalObject(mCx); NS_ENSURE_TRUE(global, JS_FALSE); JSAutoEnterCompartment ac; if (!ac.enter(mCx, global)) { NS_ERROR("Failed to enter compartment!"); return false; } JSString* str = JS_NewUCStringCopyN(mCx, aResponse.get(), aResponse.Length()); NS_ENSURE_TRUE(str, JS_FALSE); jsval argv[] = { STRING_TO_JSVAL(str) }; int argc = NS_ARRAY_LENGTH(argv); jsval rval; JSBool ok = JS_CallFunctionValue(mCx, global, mCallback, argc, argv, &rval); NS_ENSURE_TRUE(ok, JS_FALSE); return JS_TRUE; }
nsresult IDBRequest::NotifyHelperCompleted(HelperBase* aHelper) { NS_ASSERTION(NS_IsMainThread(), "Wrong thread!"); NS_ASSERTION(!mHaveResultOrErrorCode, "Already called!"); NS_ASSERTION(JSVAL_IS_VOID(mResultVal), "Should be undefined!"); // See if our window is still valid. If not then we're going to pretend that // we never completed. if (NS_FAILED(CheckInnerWindowCorrectness())) { return NS_OK; } mHaveResultOrErrorCode = true; nsresult rv = aHelper->GetResultCode(); // If the request failed then set the error code and return. if (NS_FAILED(rv)) { SetError(rv); return NS_OK; } // Otherwise we need to get the result from the helper. JSContext* cx = GetJSContext(); if (!cx) { NS_WARNING("Failed to get safe JSContext!"); rv = NS_ERROR_DOM_INDEXEDDB_UNKNOWN_ERR; SetError(rv); return rv; } JSObject* global = GetParentObject(); NS_ASSERTION(global, "This should never be null!"); JSAutoRequest ar(cx); JSAutoEnterCompartment ac; if (ac.enter(cx, global)) { AssertIsRooted(); rv = aHelper->GetSuccessResult(cx, &mResultVal); if (NS_FAILED(rv)) { NS_WARNING("GetSuccessResult failed!"); } } else { NS_WARNING("Failed to enter correct compartment!"); rv = NS_ERROR_DOM_INDEXEDDB_UNKNOWN_ERR; } if (NS_SUCCEEDED(rv)) { mError = nullptr; } else { SetError(rv); mResultVal = JSVAL_VOID; } return rv; }
static bool EnumerateNames(JSContext *cx, JSObject *wrapper, uintN flags, js::AutoIdVector &props) { JSObject *holder = GetHolder(wrapper); JSObject *wnObject = GetWrappedNativeObjectFromHolder(holder); // Redirect access straight to the wrapper if we should be transparent. if (XrayUtils::IsTransparent(cx, wrapper)) { JSAutoEnterCompartment ac; if (!ac.enter(cx, wnObject)) return false; return js::GetPropertyNames(cx, wnObject, flags, &props); } if (WrapperFactory::IsPartiallyTransparent(wrapper)) { JS_ReportError(cx, "Not allowed to enumerate cross origin objects"); return false; } // Enumerate expando properties first. JSObject *expando = GetExpandoObject(holder); if (expando && !js::GetPropertyNames(cx, expando, flags, &props)) return false; // Force all native properties to be materialized onto the wrapped native. js::AutoIdVector wnProps(cx); { JSAutoEnterCompartment ac; if (!ac.enter(cx, wnObject)) return false; if (!js::GetPropertyNames(cx, wnObject, flags, &wnProps)) return false; } // Go through the properties we got and enumerate all native ones. for (size_t n = 0; n < wnProps.length(); ++n) { jsid id = wnProps[n]; JSBool hasProp; if (!JS_HasPropertyById(cx, wrapper, id, &hasProp)) return false; if (hasProp) props.append(id); } return true; }
nsresult CentralizedAdminPrefManagerInit() { nsresult rv; JSRuntime *rt; // If autoconfig_cx already created, no need to create it again if (autoconfig_cx) return NS_OK; // We need the XPCONNECT service nsCOMPtr<nsIXPConnect> xpc = do_GetService(nsIXPConnect::GetCID(), &rv); if (NS_FAILED(rv)) { return rv; } // Get the JS RunTime nsCOMPtr<nsIJSRuntimeService> rtsvc = do_GetService("@mozilla.org/js/xpc/RuntimeService;1", &rv); if (NS_SUCCEEDED(rv)) rv = rtsvc->GetRuntime(&rt); if (NS_FAILED(rv)) { NS_ERROR("Couldn't get JS RunTime"); return rv; } // Create a new JS context for autoconfig JS script autoconfig_cx = JS_NewContext(rt, 1024); if (!autoconfig_cx) return NS_ERROR_OUT_OF_MEMORY; JSAutoRequest ar(autoconfig_cx); JS_SetErrorReporter(autoconfig_cx, autoConfigErrorReporter); // Create a new Security Manger and set it for the new JS context nsCOMPtr<nsIXPCSecurityManager> secman = static_cast<nsIXPCSecurityManager*>(new AutoConfigSecMan()); xpc->SetSecurityManagerForJSContext(autoconfig_cx, secman, 0); autoconfig_glob = JS_NewGlobalObject(autoconfig_cx, &global_class, NULL); if (autoconfig_glob) { JSAutoEnterCompartment ac; if(!ac.enter(autoconfig_cx, autoconfig_glob)) return NS_ERROR_FAILURE; if (JS_InitStandardClasses(autoconfig_cx, autoconfig_glob)) { // XPCONNECT enable this JS context rv = xpc->InitClasses(autoconfig_cx, autoconfig_glob); if (NS_SUCCEEDED(rv)) return NS_OK; } } // failue exit... clean up the JS context JS_DestroyContext(autoconfig_cx); autoconfig_cx = nsnull; return NS_ERROR_FAILURE; }
nsresult nsXBLProtoImplProperty::InstallMember(nsIScriptContext* aContext, nsIContent* aBoundElement, void* aScriptObject, void* aTargetClassObject, const nsCString& aClassStr) { NS_PRECONDITION(mIsCompiled, "Should not be installing an uncompiled property"); JSContext* cx = aContext->GetNativeContext(); nsIDocument *ownerDoc = aBoundElement->GetOwnerDoc(); nsIScriptGlobalObject *sgo; if (!ownerDoc || !(sgo = ownerDoc->GetScopeObject())) { return NS_ERROR_UNEXPECTED; } JSObject * scriptObject = (JSObject *) aScriptObject; NS_ASSERTION(scriptObject, "uh-oh, script Object should NOT be null or bad things will happen"); if (!scriptObject) return NS_ERROR_FAILURE; JSObject * targetClassObject = (JSObject *) aTargetClassObject; JSObject * globalObject = sgo->GetGlobalJSObject(); // now we want to reevaluate our property using aContext and the script object for this window... if ((mJSGetterObject || mJSSetterObject) && targetClassObject) { JSObject * getter = nsnull; JSAutoRequest ar(cx); JSAutoEnterCompartment ac; if (!ac.enter(cx, globalObject)) return NS_ERROR_UNEXPECTED; if (mJSGetterObject) if (!(getter = ::JS_CloneFunctionObject(cx, mJSGetterObject, globalObject))) return NS_ERROR_OUT_OF_MEMORY; JSObject * setter = nsnull; if (mJSSetterObject) if (!(setter = ::JS_CloneFunctionObject(cx, mJSSetterObject, globalObject))) return NS_ERROR_OUT_OF_MEMORY; nsDependentString name(mName); if (!::JS_DefineUCProperty(cx, targetClassObject, reinterpret_cast<const jschar*>(mName), name.Length(), JSVAL_VOID, JS_DATA_TO_FUNC_PTR(JSPropertyOp, getter), JS_DATA_TO_FUNC_PTR(JSStrictPropertyOp, setter), mJSAttributes)) return NS_ERROR_OUT_OF_MEMORY; } return NS_OK; }
static JSObject * wrap(JSContext *cx, JSObject *toWrap, JSObject *target) { JSAutoEnterCompartment ac; if (!ac.enter(cx, target)) return NULL; JSObject *wrapper = toWrap; if (!JS_WrapObject(cx, &wrapper)) return NULL; return wrapper; }
static JSObject * wrap(JSContext *cx, JS::HandleObject toWrap, JS::HandleObject target) { JSAutoEnterCompartment ac; if (!ac.enter(cx, target)) return NULL; JS::RootedObject wrapper(cx, toWrap); if (!JS_WrapObject(cx, wrapper.address())) return NULL; return wrapper; }
// DoubleWrap is called from PrepareForWrapping to maintain the state that // we're supposed to waive Xray wrappers for the given on. On entrance, it // expects |cx->compartment != obj->compartment()|. The returned object will // be in the same compartment as |obj|. JSObject * WrapperFactory::DoubleWrap(JSContext *cx, JSObject *obj, unsigned flags) { if (flags & WrapperFactory::WAIVE_XRAY_WRAPPER_FLAG) { JSAutoEnterCompartment ac; if (!ac.enter(cx, obj)) return nsnull; return WaiveXray(cx, obj); } return obj; }
bool XPCShellEnvironment::EvaluateString(const nsString& aString, nsString* aResult) { XPCShellEnvironment* env = Environment(mCx); XPCShellEnvironment::AutoContextPusher pusher(env); JSAutoRequest ar(mCx); JS_ClearPendingException(mCx); JSObject* global = GetGlobalObject(); JSAutoEnterCompartment ac; if (!ac.enter(mCx, global)) { NS_ERROR("Failed to enter compartment!"); return false; } JSScript* script = JS_CompileUCScriptForPrincipals(mCx, global, GetPrincipal(), aString.get(), aString.Length(), "typein", 0); if (!script) { return false; } if (!ShouldCompileOnly()) { if (aResult) { aResult->Truncate(); } jsval result; JSBool ok = JS_ExecuteScript(mCx, global, script, &result); if (ok && result != JSVAL_VOID) { JSErrorReporter old = JS_SetErrorReporter(mCx, NULL); JSString* str = JS_ValueToString(mCx, result); nsDependentJSString depStr; if (str) depStr.init(mCx, str); JS_SetErrorReporter(mCx, old); if (!depStr.IsEmpty() && aResult) { aResult->Assign(depStr); } } } JS_DestroyScript(mCx, script); return true; }
bool JetpackChild::RecvSendMessage(const nsString& messageName, const InfallibleTArray<Variant>& data) { JSAutoRequest request(mCx); JSObject *global = JS_GetGlobalObject(mCx); JSAutoEnterCompartment ac; if (!ac.enter(mCx, global)) return false; return JetpackActorCommon::RecvMessage(mCx, messageName, data, NULL); }
nsresult ArchiveRequest::ReaderReady(nsTArray<nsCOMPtr<nsIDOMFile> >& aFileList, nsresult aStatus) { if (NS_FAILED(aStatus)) { FireError(aStatus); return NS_OK; } jsval result; nsresult rv; nsIScriptContext* sc = GetContextForEventHandlers(&rv); NS_ENSURE_STATE(sc); JSContext* cx = sc->GetNativeContext(); NS_ASSERTION(cx, "Failed to get a context!"); JSObject* global = sc->GetNativeGlobal(); NS_ASSERTION(global, "Failed to get global object!"); JSAutoRequest ar(cx); JSAutoEnterCompartment ac; if (ac.enter(cx, global)) { switch (mOperation) { case GetFilenames: rv = GetFilenamesResult(cx, &result, aFileList); break; case GetFile: rv = GetFileResult(cx, &result, aFileList); break; } if (NS_FAILED(rv)) { NS_WARNING("Get*Result failed!"); } } else { NS_WARNING("Failed to enter correct compartment!"); rv = NS_ERROR_FAILURE; } if (NS_SUCCEEDED(rv)) { FireSuccess(result); } else { FireError(rv); } return NS_OK; }
nsresult nsXBLProtoImplMethod::InstallMember(nsIScriptContext* aContext, nsIContent* aBoundElement, void* aScriptObject, void* aTargetClassObject, const nsCString& aClassStr) { NS_PRECONDITION(IsCompiled(), "Should not be installing an uncompiled method"); JSContext* cx = aContext->GetNativeContext(); nsIDocument *ownerDoc = aBoundElement->OwnerDoc(); nsIScriptGlobalObject *sgo; if (!(sgo = ownerDoc->GetScopeObject())) { return NS_ERROR_UNEXPECTED; } JSObject * scriptObject = (JSObject *) aScriptObject; NS_ASSERTION(scriptObject, "uh-oh, script Object should NOT be null or bad things will happen"); if (!scriptObject) return NS_ERROR_FAILURE; JSObject * targetClassObject = (JSObject *) aTargetClassObject; JSObject * globalObject = sgo->GetGlobalJSObject(); // now we want to reevaluate our property using aContext and the script object for this window... if (mJSMethodObject && targetClassObject) { nsDependentString name(mName); JSAutoRequest ar(cx); JSAutoEnterCompartment ac; if (!ac.enter(cx, globalObject)) { return NS_ERROR_UNEXPECTED; } JSObject * method = ::JS_CloneFunctionObject(cx, mJSMethodObject, globalObject); if (!method) { return NS_ERROR_OUT_OF_MEMORY; } if (!::JS_DefineUCProperty(cx, targetClassObject, reinterpret_cast<const jschar*>(mName), name.Length(), OBJECT_TO_JSVAL(method), NULL, NULL, JSPROP_ENUMERATE)) { return NS_ERROR_OUT_OF_MEMORY; } } return NS_OK; }
JSObject * WrapperFactory::WaiveXray(JSContext *cx, JSObject *obj) { obj = UnwrapObject(obj); // We have to make sure that if we're wrapping an outer window, that // the .wrappedJSObject also wraps the outer window. obj = GetCurrentOuter(cx, obj); { // See if we already have a waiver wrapper for this object. CompartmentPrivate *priv = (CompartmentPrivate *)JS_GetCompartmentPrivate(js::GetObjectCompartment(obj)); JSObject *wobj = nsnull; if (priv && priv->waiverWrapperMap) { wobj = priv->waiverWrapperMap->Find(obj); xpc_UnmarkGrayObject(wobj); } // No wrapper yet, make one. if (!wobj) { JSObject *proto = js::GetObjectProto(obj); if (proto && !(proto = WaiveXray(cx, proto))) return nsnull; JSAutoEnterCompartment ac; if (!ac.enter(cx, obj) || !JS_WrapObject(cx, &proto)) return nsnull; wobj = Wrapper::New(cx, obj, proto, JS_GetGlobalForObject(cx, obj), &WaiveXrayWrapperWrapper); if (!wobj) return nsnull; // Add the new wrapper so we find it next time. if (priv) { if (!priv->waiverWrapperMap) { priv->waiverWrapperMap = JSObject2JSObjectMap::newMap(XPC_WRAPPER_MAP_SIZE); if (!priv->waiverWrapperMap) return nsnull; } if (!priv->waiverWrapperMap->Add(obj, wobj)) return nsnull; } } obj = wobj; } return obj; }
nsresult nsStructuredCloneContainer::InitFromVariant(nsIVariant *aData, JSContext *aCx) { NS_ENSURE_STATE(!mData); NS_ENSURE_ARG_POINTER(aData); NS_ENSURE_ARG_POINTER(aCx); // First, try to extract a jsval from the variant |aData|. This works only // if the variant implements GetAsJSVal. jsval jsData; nsresult rv = aData->GetAsJSVal(&jsData); NS_ENSURE_SUCCESS(rv, NS_ERROR_UNEXPECTED); // Make sure that we serialize in the right context. JSAutoRequest ar(aCx); JSAutoEnterCompartment ac; NS_ENSURE_STATE(ac.enter(aCx, JS_GetGlobalObject(aCx))); JS_WrapValue(aCx, &jsData); nsCxPusher cxPusher; cxPusher.Push(aCx); uint64_t* jsBytes = nullptr; bool success = JS_WriteStructuredClone(aCx, jsData, &jsBytes, &mSize, nullptr, nullptr); NS_ENSURE_STATE(success); NS_ENSURE_STATE(jsBytes); // Copy jsBytes into our own buffer. mData = (uint64_t*) malloc(mSize); if (!mData) { mSize = 0; mVersion = 0; // FIXME This should really be js::Foreground::Free, but that's not public. JS_free(aCx, jsBytes); return NS_ERROR_FAILURE; } else { mVersion = JS_STRUCTURED_CLONE_VERSION; } memcpy(mData, jsBytes, mSize); // FIXME Similarly, this should be js::Foreground::free. JS_free(aCx, jsBytes); return NS_OK; }
bool JetpackChild::RecvEvalScript(const nsString& code) { JSAutoRequest request(mCx); JSObject *global = JS_GetGlobalObject(mCx); JSAutoEnterCompartment ac; if (!ac.enter(mCx, global)) return false; jsval ignored; (void) JS_EvaluateUCScript(mCx, global, code.get(), code.Length(), "", 1, &ignored); return true; }
nsresult mozilla::dom::bluetooth::StringArrayToJSArray(JSContext* aCx, JSObject* aGlobal, const nsTArray<nsString>& aSourceArray, JSObject** aResultArray) { NS_ASSERTION(aCx, "Null context!"); NS_ASSERTION(aGlobal, "Null global!"); JSAutoRequest ar(aCx); JSAutoEnterCompartment ac; if (!ac.enter(aCx, aGlobal)) { NS_WARNING("Failed to enter compartment!"); return NS_ERROR_FAILURE; } JSObject* arrayObj; if (aSourceArray.IsEmpty()) { arrayObj = JS_NewArrayObject(aCx, 0, nullptr); } else { uint32_t valLength = aSourceArray.Length(); mozilla::ScopedDeleteArray<jsval> valArray(new jsval[valLength]); JS::AutoArrayRooter tvr(aCx, valLength, valArray); for (PRUint32 index = 0; index < valLength; index++) { JSString* s = JS_NewUCStringCopyN(aCx, aSourceArray[index].BeginReading(), aSourceArray[index].Length()); if(!s) { NS_WARNING("Memory allocation error!"); return NS_ERROR_OUT_OF_MEMORY; } valArray[index] = STRING_TO_JSVAL(s); } arrayObj = JS_NewArrayObject(aCx, valLength, valArray); } if (!arrayObj) { return NS_ERROR_OUT_OF_MEMORY; } // XXX This is not what Jonas wants. He wants it to be live. // Followup at bug 717414 if (!JS_FreezeObject(aCx, arrayObj)) { return NS_ERROR_FAILURE; } *aResultArray = arrayObj; return NS_OK; }
bool XrayWrapper<Base>::defineProperty(JSContext *cx, JSObject *wrapper, jsid id, js::PropertyDescriptor *desc) { JSObject *holder = GetHolder(wrapper); JSPropertyDescriptor *jsdesc = desc; // Redirect access straight to the wrapper if we should be transparent. if (XrayUtils::IsTransparent(cx, wrapper)) { JSObject *wnObject = GetWrappedNativeObjectFromHolder(holder); JSAutoEnterCompartment ac; if (!ac.enter(cx, wnObject)) return false; if (!JS_WrapPropertyDescriptor(cx, desc)) return false; return JS_DefinePropertyById(cx, wnObject, id, jsdesc->value, jsdesc->getter, jsdesc->setter, jsdesc->attrs); } PropertyDescriptor existing_desc; if (!getOwnPropertyDescriptor(cx, wrapper, id, true, &existing_desc)) return false; if (existing_desc.obj && (existing_desc.attrs & JSPROP_PERMANENT)) return true; // silently ignore attempt to overwrite native property if (IsResolving(holder, id)) { if (!(jsdesc->attrs & (JSPROP_GETTER | JSPROP_SETTER))) { if (!desc->getter) jsdesc->getter = holder_get; if (!desc->setter) jsdesc->setter = holder_set; } return JS_DefinePropertyById(cx, holder, id, jsdesc->value, jsdesc->getter, jsdesc->setter, jsdesc->attrs); } JSObject *expando = EnsureExpandoObject(cx, holder); if (!expando) return false; return JS_DefinePropertyById(cx, expando, id, jsdesc->value, jsdesc->getter, jsdesc->setter, jsdesc->attrs); }
JSBool JetpackChild::EvalInSandbox(JSContext* cx, uintN argc, jsval* vp) { if (argc != 2) { JS_ReportError(cx, "evalInSandbox takes two arguments"); return JS_FALSE; } jsval* argv = JS_ARGV(cx, vp); JSObject* obj; if (!JSVAL_IS_OBJECT(argv[0]) || !(obj = JSVAL_TO_OBJECT(argv[0]))) { JS_ReportError(cx, "The first argument to evalInSandbox must be a global object created using createSandbox."); JS_ASSERT(JS_FALSE); return JS_FALSE; } // Unwrap, and switch compartments obj = js::UnwrapObject(obj); JSAutoEnterCompartment ac; if (!ac.enter(cx, obj)) return JS_FALSE; if (&sGlobalClass != JS_GetClass(cx, obj) || obj == JS_GetGlobalObject(cx)) { JS_ReportError(cx, "The first argument to evalInSandbox must be a global object created using createSandbox."); JS_ASSERT(JS_FALSE); return JS_FALSE; } if (!JS_WrapValue(cx, &argv[1])) return JS_FALSE; JSString* str = JS_ValueToString(cx, argv[1]); if (!str) return JS_FALSE; size_t length; const jschar* chars = JS_GetStringCharsAndLength(cx, str, &length); if (!chars) return JS_FALSE; js::AutoValueRooter ignored(cx); return JS_EvaluateUCScript(cx, obj, chars, length, "", 1, ignored.jsval_addr()); }
bool JetpackChild::Init(base::ProcessHandle aParentProcessHandle, MessageLoop* aIOLoop, IPC::Channel* aChannel) { if (!Open(aChannel, aParentProcessHandle, aIOLoop)) return false; if (!(mRuntime = JS_NewRuntime(32L * 1024L * 1024L)) || !(mCx = JS_NewContext(mRuntime, 8192))) return false; JS_SetVersion(mCx, JSVERSION_LATEST); JS_SetOptions(mCx, JS_GetOptions(mCx) | JSOPTION_DONT_REPORT_UNCAUGHT | JSOPTION_ATLINE | JSOPTION_JIT); JS_SetErrorReporter(mCx, ReportError); { JSAutoRequest request(mCx); JS_SetContextPrivate(mCx, this); JSObject* implGlobal = JS_NewCompartmentAndGlobalObject(mCx, const_cast<JSClass*>(&sGlobalClass), NULL); if (!implGlobal) return false; JSAutoEnterCompartment ac; if (!ac.enter(mCx, implGlobal)) return false; jsval ctypes; if (!JS_InitStandardClasses(mCx, implGlobal) || #ifdef BUILD_CTYPES !JS_InitCTypesClass(mCx, implGlobal) || !JS_GetProperty(mCx, implGlobal, "ctypes", &ctypes) || !JS_SetCTypesCallbacks(mCx, JSVAL_TO_OBJECT(ctypes), &sCallbacks) || #endif !JS_DefineFunctions(mCx, implGlobal, const_cast<JSFunctionSpec*>(sImplMethods))) return false; } return true; }
bool XrayWrapper<Base>::getOwnPropertyDescriptor(JSContext *cx, JSObject *wrapper, jsid id, bool set, PropertyDescriptor *desc) { JSObject *holder = GetHolder(wrapper); if (IsResolving(holder, id)) { desc->obj = NULL; return true; } bool status; JSWrapper::Action action = set ? JSWrapper::SET : JSWrapper::GET; desc->obj = NULL; // default value if (!this->enter(cx, wrapper, id, action, &status)) return status; AutoLeaveHelper<Base> helper(*this, cx, wrapper); ResolvingId resolving(holder, id); // NB: Nothing we do here acts on the wrapped native itself, so we don't // enter our policy. // Redirect access straight to the wrapper if we should be transparent. if (XrayUtils::IsTransparent(cx, wrapper)) { JSObject *wnObject = GetWrappedNativeObjectFromHolder(holder); { JSAutoEnterCompartment ac; if (!ac.enter(cx, wnObject)) return false; if (!JS_GetPropertyDescriptorById(cx, wnObject, id, (set ? JSRESOLVE_ASSIGNING : 0) | JSRESOLVE_QUALIFIED, desc)) { return false; } } desc->obj = (desc->obj == wnObject) ? wrapper : nsnull; return JS_WrapPropertyDescriptor(cx, desc); } return this->resolveOwnProperty(cx, wrapper, id, set, desc); }
bool testIndirectEval(JSObject *scope, JSObject *g, const char *code, int expectedHits) { EXEC("hits = 0;"); { JSAutoEnterCompartment ae; CHECK(ae.enter(cx, scope)); JSString *codestr = JS_NewStringCopyZ(cx, code); CHECK(codestr); jsval argv[1] = { STRING_TO_JSVAL(codestr) }; jsval v; CHECK(JS_CallFunctionName(cx, g, "eval", 1, argv, &v)); } jsval hitsv; EVAL("hits", &hitsv); CHECK_SAME(hitsv, INT_TO_JSVAL(expectedHits)); return true; }
NS_IMETHODIMP nsJSON::EncodeFromJSVal(JS::Value *value, JSContext *cx, nsAString &result) { result.Truncate(); // Begin a new request JSAutoRequest ar(cx); JSAutoEnterCompartment ac; nsIScriptSecurityManager *ssm = nsnull; if (value->isObject()) { JSObject *obj = &value->toObject(); if (!ac.enter(cx, obj)) { return NS_ERROR_FAILURE; } nsCOMPtr<nsIPrincipal> principal; ssm = nsContentUtils::GetSecurityManager(); nsresult rv = ssm->GetObjectPrincipal(cx, obj, getter_AddRefs(principal)); NS_ENSURE_SUCCESS(rv, rv); JSStackFrame *fp = nsnull; rv = ssm->PushContextPrincipal(cx, JS_FrameIterator(cx, &fp), principal); NS_ENSURE_SUCCESS(rv, rv); } nsJSONWriter writer; JSBool ok = JS_Stringify(cx, value, NULL, JSVAL_NULL, WriteCallback, &writer); if (ssm) { ssm->PopContextPrincipal(cx); } if (!ok) { return NS_ERROR_XPC_BAD_CONVERT_JS; } NS_ENSURE_TRUE(writer.DidWrite(), NS_ERROR_UNEXPECTED); writer.FlushBuffer(); result.Assign(writer.mOutputString); return NS_OK; }
JSBool CallTrusted(JSContext *cx, unsigned argc, jsval *vp) { if (!JS_SaveFrameChain(cx)) return JS_FALSE; JSBool ok = JS_FALSE; { JSAutoEnterCompartment ac; ok = ac.enter(cx, trusted_glob.get()); if (!ok) goto out; ok = JS_CallFunctionValue(cx, NULL, OBJECT_TO_JSVAL(trusted_fun.get()), 0, NULL, vp); } out: JS_RestoreFrameChain(cx); return ok; }