/* THIS FILE IS AUTOGENERATED FROM UniFFI.webidl BY Codegen.py - DO NOT EDIT */ #include #include "AtomList.h" #include "MainThreadUtils.h" #include "UniFFIBinding.h" #include "WrapperFactory.h" #include "js/CallAndConstruct.h" #include "js/Exception.h" #include "js/MapAndSet.h" #include "js/Object.h" #include "js/PropertyAndElement.h" #include "js/PropertyDescriptor.h" #include "js/experimental/JitInfo.h" #include "jsapi.h" #include "jsfriendapi.h" #include "mozilla/Atomics.h" #include "mozilla/FloatingPoint.h" #include "mozilla/OwningNonNull.h" #include "mozilla/ProfilerLabels.h" #include "mozilla/dom/BindingCallContext.h" #include "mozilla/dom/BindingUtils.h" #include "mozilla/dom/DOMJSClass.h" #include "mozilla/dom/NonRefcountedDOMObject.h" #include "mozilla/dom/PrimitiveConversions.h" #include "mozilla/dom/Promise.h" #include "mozilla/dom/RootedDictionary.h" #include "mozilla/dom/ScriptSettings.h" #include "mozilla/dom/ToJSValue.h" #include "mozilla/dom/TypedArray.h" #include "mozilla/dom/UniFFIPointer.h" #include "mozilla/dom/UniFFIScaffolding.h" #include "mozilla/dom/XrayExpandoClass.h" #include "nsContentUtils.h" namespace mozilla { namespace dom { namespace binding_detail {}; // Just to make sure it's known as a namespace using namespace mozilla::dom::binding_detail; namespace binding_detail { constexpr nsLiteralCString EnumStrings::Values[3]; } // namespace binding_detail bool ToJSValue(JSContext* aCx, UniFFIScaffoldingCallCode aArgument, JS::MutableHandle aValue) { MOZ_ASSERT(uint32_t(aArgument) < std::size(binding_detail::EnumStrings::Values)); JSString* resultStr = JS_NewStringCopyN(aCx, binding_detail::EnumStrings::Values[uint32_t(aArgument)].BeginReading(), binding_detail::EnumStrings::Values[uint32_t(aArgument)].Length()); if (!resultStr) { return false; } aValue.setString(resultStr); return true; } void ImplCycleCollectionTraverse(nsCycleCollectionTraversalCallback& aCallback, OwningDoubleOrArrayBufferOrUniFFIPointer& aUnion, const char* aName, uint32_t aFlags) { if (aUnion.IsUniFFIPointer()) { ImplCycleCollectionTraverse(aCallback, aUnion.GetAsUniFFIPointer(), "mUniFFIPointer", aFlags); } } void ImplCycleCollectionUnlink(OwningDoubleOrArrayBufferOrUniFFIPointer& aUnion) { aUnion.Uninit(); } bool DoubleOrArrayBufferOrUniFFIPointer::TrySetToDouble(BindingCallContext& cx, JS::Handle value, bool& tryNext, bool passedToJSImpl) { tryNext = false; { // scope for memberSlot double& memberSlot = RawSetAsDouble(); if (!ValueToPrimitive(cx, value, "Double branch of (double or ArrayBuffer or UniFFIPointer)", &memberSlot)) { return false; } else if (!std::isfinite(memberSlot)) { cx.ThrowErrorMessage("Double branch of (double or ArrayBuffer or UniFFIPointer)"); return false; } } return true; } bool DoubleOrArrayBufferOrUniFFIPointer::TrySetToDouble(JSContext* cx_, JS::Handle value, bool& tryNext, bool passedToJSImpl) { BindingCallContext cx(cx_, nullptr); return TrySetToDouble(cx, value, tryNext, passedToJSImpl); } bool DoubleOrArrayBufferOrUniFFIPointer::TrySetToArrayBuffer(BindingCallContext& cx, JS::Handle value, bool& tryNext, bool passedToJSImpl) { tryNext = false; { // scope for memberSlot RootedSpiderMonkeyInterface& memberSlot = RawSetAsArrayBuffer(cx); if (!memberSlot.Init(&value.toObject())) { DestroyArrayBuffer(); tryNext = true; return true; } if (JS::IsSharedArrayBufferObject(memberSlot.Obj())) { cx.ThrowErrorMessage("ArrayBuffer branch of (double or ArrayBuffer or UniFFIPointer)"); return false; } if (JS::IsLargeArrayBufferMaybeShared(memberSlot.Obj())) { cx.ThrowErrorMessage("ArrayBuffer branch of (double or ArrayBuffer or UniFFIPointer)"); return false; } if (JS::IsResizableArrayBufferMaybeShared(memberSlot.Obj())) { cx.ThrowErrorMessage("ArrayBuffer branch of (double or ArrayBuffer or UniFFIPointer)"); return false; } if (JS::IsImmutableArrayBufferMaybeShared(memberSlot.Obj())) { cx.ThrowErrorMessage("ArrayBuffer branch of (double or ArrayBuffer or UniFFIPointer)"); return false; } } return true; } bool DoubleOrArrayBufferOrUniFFIPointer::TrySetToArrayBuffer(JSContext* cx_, JS::Handle value, bool& tryNext, bool passedToJSImpl) { BindingCallContext cx(cx_, nullptr); return TrySetToArrayBuffer(cx, value, tryNext, passedToJSImpl); } bool DoubleOrArrayBufferOrUniFFIPointer::TrySetToUniFFIPointer(BindingCallContext& cx, JS::Handle value, bool& tryNext, bool passedToJSImpl) { tryNext = false; { // scope for memberSlot NonNull& memberSlot = RawSetAsUniFFIPointer(); { // Our JSContext should be in the right global to do unwrapping in. nsresult rv = UnwrapObject(value, memberSlot, cx); if (NS_FAILED(rv)) { DestroyUniFFIPointer(); tryNext = true; return true; } } } return true; } bool DoubleOrArrayBufferOrUniFFIPointer::TrySetToUniFFIPointer(JSContext* cx_, JS::Handle value, bool& tryNext, bool passedToJSImpl) { BindingCallContext cx(cx_, nullptr); return TrySetToUniFFIPointer(cx, value, tryNext, passedToJSImpl); } bool DoubleOrArrayBufferOrUniFFIPointer::Init(BindingCallContext& cx, JS::Handle value, const char* sourceDescription, bool passedToJSImpl) { MOZ_ASSERT(mType == eUninitialized); bool done = false, failed = false, tryNext; if (value.isObject()) { done = (failed = !TrySetToArrayBuffer(cx, value, tryNext, passedToJSImpl)) || !tryNext || (failed = !TrySetToUniFFIPointer(cx, value, tryNext, passedToJSImpl)) || !tryNext; } if (!done) { do { done = (failed = !TrySetToDouble(cx, value, tryNext)) || !tryNext; break; } while (false); } if (failed) { return false; } if (!done) { cx.ThrowErrorMessage(sourceDescription, "ArrayBuffer, UniFFIPointer"); return false; } return true; } bool DoubleOrArrayBufferOrUniFFIPointer::Init(JSContext* cx_, JS::Handle value, const char* sourceDescription, bool passedToJSImpl) { BindingCallContext cx(cx_, nullptr); return Init(cx, value, sourceDescription, passedToJSImpl); } bool DoubleOrArrayBufferOrUniFFIPointer::ToJSVal(JSContext* cx, JS::Handle scopeObj, JS::MutableHandle rval) const { switch (mType) { case eUninitialized: { return false; } case eDouble: { rval.set(JS::NumberValue(double(mValue.mDouble.Value()))); return true; } case eArrayBuffer: { rval.setObject(*mValue.mArrayBuffer.Value().Obj()); if (!MaybeWrapNonDOMObjectValue(cx, rval)) { return false; } return true; } case eUniFFIPointer: { if (!GetOrCreateDOMReflector(cx, mValue.mUniFFIPointer.Value(), rval)) { MOZ_ASSERT(JS_IsExceptionPending(cx)); return false; } return true; } default: { return false; } } } OwningDoubleOrArrayBufferOrUniFFIPointer::OwningDoubleOrArrayBufferOrUniFFIPointer(OwningDoubleOrArrayBufferOrUniFFIPointer&& aOther) : mType(eUninitialized) { switch (aOther.mType) { case eUninitialized: { MOZ_ASSERT(mType == eUninitialized, "We need to destroy ourselves?"); break; } case eDouble: { mType = eDouble; mValue.mDouble.SetValue(std::move(aOther.mValue.mDouble.Value())); break; } case eArrayBuffer: { mType = eArrayBuffer; mValue.mArrayBuffer.SetValue(std::move(aOther.mValue.mArrayBuffer.Value())); break; } case eUniFFIPointer: { mType = eUniFFIPointer; mValue.mUniFFIPointer.SetValue(std::move(aOther.mValue.mUniFFIPointer.Value())); break; } } } bool OwningDoubleOrArrayBufferOrUniFFIPointer::TrySetToDouble(BindingCallContext& cx, JS::Handle value, bool& tryNext, bool passedToJSImpl) { tryNext = false; { // scope for memberSlot double& memberSlot = RawSetAsDouble(); if (!ValueToPrimitive(cx, value, "Double branch of (double or ArrayBuffer or UniFFIPointer)", &memberSlot)) { return false; } else if (!std::isfinite(memberSlot)) { cx.ThrowErrorMessage("Double branch of (double or ArrayBuffer or UniFFIPointer)"); return false; } } return true; } bool OwningDoubleOrArrayBufferOrUniFFIPointer::TrySetToDouble(JSContext* cx_, JS::Handle value, bool& tryNext, bool passedToJSImpl) { BindingCallContext cx(cx_, nullptr); return TrySetToDouble(cx, value, tryNext, passedToJSImpl); } [[nodiscard]] double& OwningDoubleOrArrayBufferOrUniFFIPointer::RawSetAsDouble() { if (mType == eDouble) { return mValue.mDouble.Value(); } MOZ_ASSERT(mType == eUninitialized); mType = eDouble; return mValue.mDouble.SetValue(); } [[nodiscard]] double& OwningDoubleOrArrayBufferOrUniFFIPointer::SetAsDouble() { if (mType == eDouble) { return mValue.mDouble.Value(); } Uninit(); mType = eDouble; return mValue.mDouble.SetValue(); } void OwningDoubleOrArrayBufferOrUniFFIPointer::DestroyDouble() { MOZ_RELEASE_ASSERT(IsDouble(), "Wrong type!"); mValue.mDouble.Destroy(); mType = eUninitialized; } bool OwningDoubleOrArrayBufferOrUniFFIPointer::TrySetToArrayBuffer(BindingCallContext& cx, JS::Handle value, bool& tryNext, bool passedToJSImpl) { tryNext = false; { // scope for memberSlot ArrayBuffer& memberSlot = RawSetAsArrayBuffer(); if (!memberSlot.Init(&value.toObject())) { DestroyArrayBuffer(); tryNext = true; return true; } if (JS::IsSharedArrayBufferObject(memberSlot.Obj())) { cx.ThrowErrorMessage("ArrayBuffer branch of (double or ArrayBuffer or UniFFIPointer)"); return false; } if (JS::IsLargeArrayBufferMaybeShared(memberSlot.Obj())) { cx.ThrowErrorMessage("ArrayBuffer branch of (double or ArrayBuffer or UniFFIPointer)"); return false; } if (JS::IsResizableArrayBufferMaybeShared(memberSlot.Obj())) { cx.ThrowErrorMessage("ArrayBuffer branch of (double or ArrayBuffer or UniFFIPointer)"); return false; } if (JS::IsImmutableArrayBufferMaybeShared(memberSlot.Obj())) { cx.ThrowErrorMessage("ArrayBuffer branch of (double or ArrayBuffer or UniFFIPointer)"); return false; } } return true; } bool OwningDoubleOrArrayBufferOrUniFFIPointer::TrySetToArrayBuffer(JSContext* cx_, JS::Handle value, bool& tryNext, bool passedToJSImpl) { BindingCallContext cx(cx_, nullptr); return TrySetToArrayBuffer(cx, value, tryNext, passedToJSImpl); } [[nodiscard]] ArrayBuffer& OwningDoubleOrArrayBufferOrUniFFIPointer::RawSetAsArrayBuffer() { if (mType == eArrayBuffer) { return mValue.mArrayBuffer.Value(); } MOZ_ASSERT(mType == eUninitialized); mType = eArrayBuffer; return mValue.mArrayBuffer.SetValue(); } [[nodiscard]] ArrayBuffer& OwningDoubleOrArrayBufferOrUniFFIPointer::SetAsArrayBuffer() { if (mType == eArrayBuffer) { return mValue.mArrayBuffer.Value(); } Uninit(); mType = eArrayBuffer; return mValue.mArrayBuffer.SetValue(); } void OwningDoubleOrArrayBufferOrUniFFIPointer::DestroyArrayBuffer() { MOZ_RELEASE_ASSERT(IsArrayBuffer(), "Wrong type!"); mValue.mArrayBuffer.Destroy(); mType = eUninitialized; } bool OwningDoubleOrArrayBufferOrUniFFIPointer::TrySetToUniFFIPointer(BindingCallContext& cx, JS::Handle value, bool& tryNext, bool passedToJSImpl) { tryNext = false; { // scope for memberSlot OwningNonNull& memberSlot = RawSetAsUniFFIPointer(); static_assert(IsRefcounted::value, "We can only store refcounted classes."); { // Our JSContext should be in the right global to do unwrapping in. nsresult rv = UnwrapObject(value, memberSlot, cx); if (NS_FAILED(rv)) { DestroyUniFFIPointer(); tryNext = true; return true; } } } return true; } bool OwningDoubleOrArrayBufferOrUniFFIPointer::TrySetToUniFFIPointer(JSContext* cx_, JS::Handle value, bool& tryNext, bool passedToJSImpl) { BindingCallContext cx(cx_, nullptr); return TrySetToUniFFIPointer(cx, value, tryNext, passedToJSImpl); } [[nodiscard]] OwningNonNull& OwningDoubleOrArrayBufferOrUniFFIPointer::RawSetAsUniFFIPointer() { if (mType == eUniFFIPointer) { return mValue.mUniFFIPointer.Value(); } MOZ_ASSERT(mType == eUninitialized); mType = eUniFFIPointer; return mValue.mUniFFIPointer.SetValue(); } [[nodiscard]] OwningNonNull& OwningDoubleOrArrayBufferOrUniFFIPointer::SetAsUniFFIPointer() { if (mType == eUniFFIPointer) { return mValue.mUniFFIPointer.Value(); } Uninit(); mType = eUniFFIPointer; return mValue.mUniFFIPointer.SetValue(); } void OwningDoubleOrArrayBufferOrUniFFIPointer::DestroyUniFFIPointer() { MOZ_RELEASE_ASSERT(IsUniFFIPointer(), "Wrong type!"); mValue.mUniFFIPointer.Destroy(); mType = eUninitialized; } bool OwningDoubleOrArrayBufferOrUniFFIPointer::Init(BindingCallContext& cx, JS::Handle value, const char* sourceDescription, bool passedToJSImpl) { MOZ_ASSERT(mType == eUninitialized); bool done = false, failed = false, tryNext; if (value.isObject()) { done = (failed = !TrySetToArrayBuffer(cx, value, tryNext, passedToJSImpl)) || !tryNext || (failed = !TrySetToUniFFIPointer(cx, value, tryNext, passedToJSImpl)) || !tryNext; } if (!done) { do { done = (failed = !TrySetToDouble(cx, value, tryNext)) || !tryNext; break; } while (false); } if (failed) { return false; } if (!done) { cx.ThrowErrorMessage(sourceDescription, "ArrayBuffer, UniFFIPointer"); return false; } return true; } bool OwningDoubleOrArrayBufferOrUniFFIPointer::Init(JSContext* cx_, JS::Handle value, const char* sourceDescription, bool passedToJSImpl) { BindingCallContext cx(cx_, nullptr); return Init(cx, value, sourceDescription, passedToJSImpl); } void OwningDoubleOrArrayBufferOrUniFFIPointer::Uninit() { switch (mType) { case eUninitialized: { break; } case eDouble: { DestroyDouble(); break; } case eArrayBuffer: { DestroyArrayBuffer(); break; } case eUniFFIPointer: { DestroyUniFFIPointer(); break; } } } bool OwningDoubleOrArrayBufferOrUniFFIPointer::ToJSVal(JSContext* cx, JS::Handle scopeObj, JS::MutableHandle rval) const { switch (mType) { case eUninitialized: { return false; } case eDouble: { rval.set(JS::NumberValue(double(mValue.mDouble.Value()))); return true; } case eArrayBuffer: { rval.setObject(*mValue.mArrayBuffer.Value().Obj()); if (!MaybeWrapNonDOMObjectValue(cx, rval)) { return false; } return true; } case eUniFFIPointer: { if (!GetOrCreateDOMReflector(cx, mValue.mUniFFIPointer.Value(), rval)) { MOZ_ASSERT(JS_IsExceptionPending(cx)); return false; } return true; } default: { return false; } } } void OwningDoubleOrArrayBufferOrUniFFIPointer::TraceUnion(JSTracer* trc) { switch (mType) { case eArrayBuffer: { mValue.mArrayBuffer.Value().TraceSelf(trc); break; } default: { } } } OwningDoubleOrArrayBufferOrUniFFIPointer& OwningDoubleOrArrayBufferOrUniFFIPointer::operator=(OwningDoubleOrArrayBufferOrUniFFIPointer&& aOther) { this->~OwningDoubleOrArrayBufferOrUniFFIPointer(); new (this) OwningDoubleOrArrayBufferOrUniFFIPointer (std::move(aOther)); return *this; } UniFFIScaffoldingCallResult::UniFFIScaffoldingCallResult() { // Safe to pass a null context if we pass a null value Init(nullptr, JS::NullHandleValue); } bool UniFFIScaffoldingCallResult::InitIds(JSContext* cx, UniFFIScaffoldingCallResultAtoms* atomsCache) { MOZ_ASSERT(reinterpret_cast(atomsCache)->isVoid()); // Initialize these in reverse order so that any failure leaves the first one // uninitialized. if (!atomsCache->data_id.init(cx, "data") || !atomsCache->code_id.init(cx, "code")) { return false; } return true; } bool UniFFIScaffoldingCallResult::Init(BindingCallContext& cx, JS::Handle val, const char* sourceDescription, bool passedToJSImpl) { // Passing a null JSContext is OK only if we're initing from null, // Since in that case we will not have to do any property gets // Also evaluate isNullOrUndefined in order to avoid false-positive // checkers by static analysis tools MOZ_ASSERT_IF(!cx, val.isNull() && val.isNullOrUndefined()); UniFFIScaffoldingCallResultAtoms* atomsCache = nullptr; if (cx) { atomsCache = GetAtomCache(cx); if (reinterpret_cast(atomsCache)->isVoid() && !InitIds(cx, atomsCache)) { return false; } } if (!IsConvertibleToDictionary(val)) { return cx.ThrowErrorMessage(sourceDescription, "dictionary"); } bool isNull = val.isNullOrUndefined(); // We only need these if !isNull, in which case we have |cx|. Maybe > object; Maybe > temp; if (!isNull) { MOZ_ASSERT(cx); object.emplace(cx, &val.toObject()); temp.emplace(cx); } if (!isNull) { if (!JS_GetPropertyById(cx, *object, atomsCache->code_id, temp.ptr())) { return false; } } if (!isNull && !temp->isUndefined()) { { int index; if (!binding_detail::FindEnumStringIndex(cx, temp.ref(), binding_detail::EnumStrings::Values, "UniFFIScaffoldingCallCode", "'code' member of UniFFIScaffoldingCallResult", &index)) { return false; } MOZ_ASSERT(index >= 0); mCode = static_cast(index); } mIsAnyMemberPresent = true; } else if (cx) { // Don't error out if we have no cx. In that // situation the caller is default-constructing us and we'll // just assume they know what they're doing. return cx.ThrowErrorMessage("'code' member of UniFFIScaffoldingCallResult"); } if (!isNull) { if (!JS_GetPropertyById(cx, *object, atomsCache->data_id, temp.ptr())) { return false; } } if (!isNull && !temp->isUndefined()) { mData.Construct(); if (!(mData.Value()).Init(cx, temp.ref(), "'data' member of UniFFIScaffoldingCallResult", passedToJSImpl)) { return false; } mIsAnyMemberPresent = true; } return true; } bool UniFFIScaffoldingCallResult::Init(JSContext* cx_, JS::Handle val, const char* sourceDescription, bool passedToJSImpl) { // We don't want to use sourceDescription for our context here; // that's not really what it's formatted for. BindingCallContext cx(cx_, nullptr); return Init(cx, val, sourceDescription, passedToJSImpl); } bool UniFFIScaffoldingCallResult::ToObjectInternal(JSContext* cx, JS::MutableHandle rval) const { UniFFIScaffoldingCallResultAtoms* atomsCache = GetAtomCache(cx); if (reinterpret_cast(atomsCache)->isVoid() && !InitIds(cx, atomsCache)) { return false; } JS::Rooted obj(cx, JS_NewPlainObject(cx)); if (!obj) { return false; } rval.setObject(*obj); do { // block for our 'break' successCode and scope for 'temp' and 'currentValue' JS::Rooted temp(cx); UniFFIScaffoldingCallCode const & currentValue = mCode; if (!ToJSValue(cx, currentValue, &temp)) { return false; } if (!JS_DefinePropertyById(cx, obj, atomsCache->code_id, temp, JSPROP_ENUMERATE)) { return false; } break; } while(false); if (mData.WasPassed()) { do { // block for our 'break' successCode and scope for 'temp' and 'currentValue' JS::Rooted temp(cx); OwningDoubleOrArrayBufferOrUniFFIPointer const & currentValue = mData.InternalValue(); if (!currentValue.ToJSVal(cx, obj, &temp)) { return false; } if (!JS_DefinePropertyById(cx, obj, atomsCache->data_id, temp, JSPROP_ENUMERATE)) { return false; } break; } while(false); } return true; } void UniFFIScaffoldingCallResult::TraceDictionary(JSTracer* trc) { if (mData.WasPassed()) { mData.Value().TraceUnion(trc); } } namespace UniFFIPointer_Binding { static void _finalize(JS::GCContext* gcx, JSObject* obj) { mozilla::dom::UniFFIPointer* self = UnwrapPossiblyNotInitializedDOMObject(obj); if (self) { JS::SetNativeObjectReservedSlot(obj, DOM_OBJECT_SLOT, JS::UndefinedValue()); ClearWrapper(self, self, obj); if (size_t mallocBytes = BindingJSObjectMallocBytes(self)) { JS::RemoveAssociatedMemory(obj, mallocBytes, JS::MemoryUse::DOMBinding); } AddForDeferredFinalization(self); } } bool sNativePropertiesInited = false; const NativePropertyHooks sNativePropertyHooks = { nullptr, { nullptr, nullptr, &sNativePropertiesInited }, prototypes::id::UniFFIPointer, constructors::id::UniFFIPointer, &DefaultXrayExpandoObjectClass }; static const DOMInterfaceInfo sInterfaceObjectInfo = { { ThrowingConstructor, &sNativePropertyHooks }, JS::GetRealmFunctionPrototypeHandle, PrototypeTraits::Depth, prototypes::id::UniFFIPointer, true, 0, "UniFFIPointer", }; static const DOMIfaceAndProtoJSClass sPrototypeClass = { { "UniFFIPointerPrototype", JSCLASS_IS_DOMIFACEANDPROTOJSCLASS | JSCLASS_HAS_RESERVED_SLOTS(DOM_INTERFACE_PROTO_SLOTS_BASE), JS_NULL_CLASS_OPS, JS_NULL_CLASS_SPEC, JS_NULL_CLASS_EXT, JS_NULL_OBJECT_OPS }, eInterfacePrototype, prototypes::id::UniFFIPointer, PrototypeTraits::Depth, &sNativePropertyHooks, JS::GetRealmObjectPrototype }; bool ConstructorEnabled(JSContext* aCx, JS::Handle aObj) { return nsContentUtils::ThreadsafeIsSystemCaller(aCx); } static JS::Handle GetProtoObjectHandle(JSContext* aCx); static const JSClassOps sClassOps = { nullptr, /* addProperty */ nullptr, /* delProperty */ nullptr, /* enumerate */ nullptr, /* newEnumerate */ nullptr, /* resolve */ nullptr, /* mayResolve */ _finalize, /* finalize */ nullptr, /* call */ nullptr, /* construct */ nullptr, /* trace */ }; static const DOMJSClass sClass = { { "UniFFIPointer", JSCLASS_IS_DOMJSCLASS | JSCLASS_FOREGROUND_FINALIZE | JSCLASS_HAS_RESERVED_SLOTS(1) | JSCLASS_PRESERVES_WRAPPER, &sClassOps, JS_NULL_CLASS_SPEC, &NativeTypeHelpers::sClassExtension, JS_NULL_OBJECT_OPS }, { prototypes::id::UniFFIPointer, prototypes::id::_ID_Count, prototypes::id::_ID_Count, prototypes::id::_ID_Count, prototypes::id::_ID_Count, prototypes::id::_ID_Count, prototypes::id::_ID_Count, prototypes::id::_ID_Count }, std::is_base_of_v, &sNativePropertyHooks, GetProtoObjectHandle, GetCCParticipant::Get(), nullptr, NativeTypeHelpers::GetWrapperCache }; static_assert(1 == DOM_INSTANCE_RESERVED_SLOTS, "Must have the right minimal number of reserved slots."); static_assert(1 >= 1, "Must have enough reserved slots."); bool Wrap(JSContext* aCx, mozilla::dom::UniFFIPointer* aObject, nsWrapperCache* aCache, JS::Handle aGivenProto, JS::MutableHandle aReflector) { static_assert(!std::is_base_of_v, "Shouldn't have wrappercached things that are not refcounted."); static_assert(std::is_same_v); MOZ_ASSERT(ToSupportsIsCorrect(aObject)); MOZ_ASSERT_IF(aGivenProto, js::IsObjectInContextCompartment(aGivenProto, aCx)); MOZ_ASSERT(!aCache->GetWrapper(), "You should probably not be using Wrap() directly; use " "GetOrCreateDOMReflector instead"); MOZ_ASSERT(ToSupportsIsOnPrimaryInheritanceChain(aObject, aCache), "nsISupports must be on our primary inheritance chain"); // If the wrapper cache contains a dead reflector then finalize that // now, ensuring that the finalizer for the old reflector always // runs before the new reflector is created and attached. This // avoids the awkward situation where there are multiple reflector // objects that contain pointers to the same native. if (JSObject* oldReflector = aCache->GetWrapperMaybeDead()) { _finalize(nullptr /* unused */, oldReflector); MOZ_ASSERT(!aCache->GetWrapperMaybeDead()); } JS::Rooted global(aCx, FindAssociatedGlobal(aCx, aObject->GetParentObject())); if (!global) { return false; } MOZ_ASSERT(JS_IsGlobalObject(global)); JS::AssertObjectIsNotGray(global); // That might have ended up wrapping us already, due to the wonders // of XBL. Check for that, and bail out as needed. aReflector.set(aCache->GetWrapper()); if (aReflector) { #ifdef DEBUG AssertReflectorHasGivenProto(aCx, aReflector, aGivenProto); #endif // DEBUG return true; } JSAutoRealm ar(aCx, global); JS::Handle canonicalProto = GetProtoObjectHandle(aCx); if (!canonicalProto) { return false; } JS::Rooted proto(aCx); if (aGivenProto) { proto = aGivenProto; // Unfortunately, while aGivenProto was in the compartment of aCx // coming in, we changed compartments to that of "parent" so may need // to wrap the proto here. if (js::GetContextCompartment(aCx) != JS::GetCompartment(proto)) { if (!JS_WrapObject(aCx, &proto)) { return false; } } } else { proto = canonicalProto; } BindingJSObjectCreator creator(aCx); creator.CreateObject(aCx, sClass.ToJSClass(), proto, aObject, aReflector); if (!aReflector) { return false; } aCache->SetWrapper(aReflector); creator.InitializationSucceeded(); MOZ_ASSERT(aCache->GetWrapperPreserveColor() && aCache->GetWrapperPreserveColor() == aReflector); // If proto != canonicalProto, we have to preserve our wrapper; // otherwise we won't be able to properly recreate it later, since // we won't know what proto to use. Note that we don't check // aGivenProto here, since it's entirely possible (and even // somewhat common) to have a non-null aGivenProto which is the // same as canonicalProto. if (proto != canonicalProto) { PreserveWrapper(aObject); } return true; } void CreateInterfaceObjects(JSContext* aCx, JS::Handle aGlobal, ProtoAndIfaceCache& aProtoAndIfaceCache, DefineInterfaceProperty aDefineOnGlobal) { JS::Heap* protoCache = &aProtoAndIfaceCache.EntrySlotOrCreate(prototypes::id::UniFFIPointer); JS::Heap* interfaceCache = &aProtoAndIfaceCache.EntrySlotOrCreate(constructors::id::UniFFIPointer); JS::Handle parentProto(JS::GetRealmObjectPrototypeHandle(aCx)); if (!parentProto) { return; } JS::Handle constructorProto(JS::GetRealmFunctionPrototypeHandle(aCx)); if (!constructorProto) { return; } dom::CreateInterfaceObjects(aCx, aGlobal, parentProto, &sPrototypeClass, protoCache, constructorProto, &sInterfaceObjectInfo, 0, false, Span{}, interfaceCache, nullptr, nullptr, "UniFFIPointer", ShouldExpose(aCx, aGlobal, aDefineOnGlobal), nullptr, false, nullptr); } static JS::Handle GetProtoObjectHandle(JSContext* aCx) { /* Get the interface prototype object for this class. This will create the object as needed. */ return GetPerInterfaceObjectHandle(aCx, prototypes::id::UniFFIPointer, &CreateInterfaceObjects, DefineInterfaceProperty::CheckExposure); } JS::Handle GetConstructorObjectHandle(JSContext* aCx) { /* Get the interface object for this class. This will create the object as needed. */ return GetPerInterfaceObjectHandle(aCx, constructors::id::UniFFIPointer, &CreateInterfaceObjects, DefineInterfaceProperty::CheckExposure); } } // namespace UniFFIPointer_Binding namespace UniFFIScaffolding_Binding { MOZ_CAN_RUN_SCRIPT static bool callSync(JSContext* cx_, unsigned argc, JS::Value* vp) { BindingCallContext cx(cx_, "UniFFIScaffolding.callSync"); AUTO_PROFILER_LABEL_DYNAMIC_FAST( "UniFFIScaffolding", "callSync", DOM, cx, uint32_t(js::ProfilingStackFrame::Flags::STRING_TEMPLATE_METHOD) | uint32_t(js::ProfilingStackFrame::Flags::RELEVANT_FOR_JS)); JS::CallArgs args = JS::CallArgsFromVp(argc, vp); JS::Rooted obj(cx, &args.callee()); if (!args.requireAtLeast(cx, "UniFFIScaffolding.callSync", 1)) { return false; } GlobalObject global(cx, xpc::XrayAwareCalleeGlobal(obj)); if (global.Failed()) { return false; } uint64_t arg0; if (!ValueToPrimitive(cx, args[0], "Argument 1", &arg0)) { return false; } AutoSequence arg1; SequenceRooter arg1_holder(cx, &arg1); if (args.length() > 1) { if (!arg1.SetCapacity(args.length() - 1, mozilla::fallible)) { JS_ReportOutOfMemory(cx); return false; } for (uint32_t variadicArg = 1; variadicArg < args.length(); ++variadicArg) { // OK to do infallible append here, since we ensured capacity already. OwningDoubleOrArrayBufferOrUniFFIPointer& slot = *arg1.AppendElement(); if (!slot.Init(cx, args[variadicArg], "Argument 2", false)) { return false; } } } FastErrorResult rv; RootedDictionary result(cx); // NOTE: This assert does NOT call the function. static_assert(std::is_void_v, "Should be returning void here"); mozilla::dom::UniFFIScaffolding::CallSync(global, arg0, Constify(arg1), result, rv); if (rv.MaybeSetPendingException(cx, "UniFFIScaffolding.callSync")) [[unlikely]] { return false; } MOZ_ASSERT(!JS_IsExceptionPending(cx)); if (!result.ToObjectInternal(cx, args.rval())) { return false; } return true; } MOZ_CAN_RUN_SCRIPT static bool callAsync(JSContext* cx_, unsigned argc, JS::Value* vp) { BindingCallContext cx(cx_, "UniFFIScaffolding.callAsync"); AUTO_PROFILER_LABEL_DYNAMIC_FAST( "UniFFIScaffolding", "callAsync", DOM, cx, uint32_t(js::ProfilingStackFrame::Flags::STRING_TEMPLATE_METHOD) | uint32_t(js::ProfilingStackFrame::Flags::RELEVANT_FOR_JS)); JS::CallArgs args = JS::CallArgsFromVp(argc, vp); JS::Rooted obj(cx, &args.callee()); if (!args.requireAtLeast(cx, "UniFFIScaffolding.callAsync", 1)) { return false; } GlobalObject global(cx, xpc::XrayAwareCalleeGlobal(obj)); if (global.Failed()) { return false; } uint64_t arg0; if (!ValueToPrimitive(cx, args[0], "Argument 1", &arg0)) { return false; } AutoSequence arg1; SequenceRooter arg1_holder(cx, &arg1); if (args.length() > 1) { if (!arg1.SetCapacity(args.length() - 1, mozilla::fallible)) { JS_ReportOutOfMemory(cx); return false; } for (uint32_t variadicArg = 1; variadicArg < args.length(); ++variadicArg) { // OK to do infallible append here, since we ensured capacity already. OwningDoubleOrArrayBufferOrUniFFIPointer& slot = *arg1.AppendElement(); if (!slot.Init(cx, args[variadicArg], "Argument 2", false)) { return false; } } } FastErrorResult rv; auto result(StrongOrRawPtr(mozilla::dom::UniFFIScaffolding::CallAsync(global, arg0, Constify(arg1), rv))); if (rv.MaybeSetPendingException(cx, "UniFFIScaffolding.callAsync")) [[unlikely]] { return false; } MOZ_ASSERT(!JS_IsExceptionPending(cx)); if (!ToJSValue(cx, result, args.rval())) { return false; } return true; } static const JSJitInfo callAsync_methodinfo = { { (JSJitGetterOp)callAsync }, { prototypes::id::_ID_Count }, { 0 }, JSJitInfo::StaticMethod, JSJitInfo::AliasEverything, JSVAL_TYPE_OBJECT, false, false, false, false, 0 }; MOZ_CAN_RUN_SCRIPT static bool callAsyncWrapper(JSContext* cx_, unsigned argc, JS::Value* vp) { BindingCallContext cx(cx_, "UniFFIScaffolding.callAsyncWrapper"); AUTO_PROFILER_LABEL_DYNAMIC_FAST( "UniFFIScaffolding", "callAsyncWrapper", DOM, cx, uint32_t(js::ProfilingStackFrame::Flags::STRING_TEMPLATE_METHOD) | uint32_t(js::ProfilingStackFrame::Flags::RELEVANT_FOR_JS)); JS::CallArgs args = JS::CallArgsFromVp(argc, vp); JS::Rooted obj(cx, &args.callee()); if (!args.requireAtLeast(cx, "UniFFIScaffolding.callAsyncWrapper", 1)) { return false; } GlobalObject global(cx, xpc::XrayAwareCalleeGlobal(obj)); if (global.Failed()) { return false; } uint64_t arg0; if (!ValueToPrimitive(cx, args[0], "Argument 1", &arg0)) { return false; } AutoSequence arg1; SequenceRooter arg1_holder(cx, &arg1); if (args.length() > 1) { if (!arg1.SetCapacity(args.length() - 1, mozilla::fallible)) { JS_ReportOutOfMemory(cx); return false; } for (uint32_t variadicArg = 1; variadicArg < args.length(); ++variadicArg) { // OK to do infallible append here, since we ensured capacity already. OwningDoubleOrArrayBufferOrUniFFIPointer& slot = *arg1.AppendElement(); if (!slot.Init(cx, args[variadicArg], "Argument 2", false)) { return false; } } } FastErrorResult rv; auto result(StrongOrRawPtr(mozilla::dom::UniFFIScaffolding::CallAsyncWrapper(global, arg0, Constify(arg1), rv))); if (rv.MaybeSetPendingException(cx, "UniFFIScaffolding.callAsyncWrapper")) [[unlikely]] { return false; } MOZ_ASSERT(!JS_IsExceptionPending(cx)); if (!ToJSValue(cx, result, args.rval())) { return false; } return true; } static const JSJitInfo callAsyncWrapper_methodinfo = { { (JSJitGetterOp)callAsyncWrapper }, { prototypes::id::_ID_Count }, { 0 }, JSJitInfo::StaticMethod, JSJitInfo::AliasEverything, JSVAL_TYPE_OBJECT, false, false, false, false, 0 }; MOZ_CAN_RUN_SCRIPT static bool readPointer(JSContext* cx_, unsigned argc, JS::Value* vp) { BindingCallContext cx(cx_, "UniFFIScaffolding.readPointer"); AUTO_PROFILER_LABEL_DYNAMIC_FAST( "UniFFIScaffolding", "readPointer", DOM, cx, uint32_t(js::ProfilingStackFrame::Flags::STRING_TEMPLATE_METHOD) | uint32_t(js::ProfilingStackFrame::Flags::RELEVANT_FOR_JS)); JS::CallArgs args = JS::CallArgsFromVp(argc, vp); JS::Rooted obj(cx, &args.callee()); if (!args.requireAtLeast(cx, "UniFFIScaffolding.readPointer", 3)) { return false; } GlobalObject global(cx, xpc::XrayAwareCalleeGlobal(obj)); if (global.Failed()) { return false; } uint64_t arg0; if (!ValueToPrimitive(cx, args[0], "Argument 1", &arg0)) { return false; } RootedSpiderMonkeyInterface arg1(cx); if (args[1].isObject()) { if (!arg1.Init(&args[1].toObject())) { cx.ThrowErrorMessage("Argument 2", "ArrayBuffer"); return false; } if (JS::IsSharedArrayBufferObject(arg1.Obj())) { cx.ThrowErrorMessage("Argument 2"); return false; } if (JS::IsLargeArrayBufferMaybeShared(arg1.Obj())) { cx.ThrowErrorMessage("Argument 2"); return false; } if (JS::IsResizableArrayBufferMaybeShared(arg1.Obj())) { cx.ThrowErrorMessage("Argument 2"); return false; } if (JS::IsImmutableArrayBufferMaybeShared(arg1.Obj())) { cx.ThrowErrorMessage("Argument 2"); return false; } } else { cx.ThrowErrorMessage("Argument 2"); return false; } int32_t arg2; if (!ValueToPrimitive(cx, args[2], "Argument 3", &arg2)) { return false; } FastErrorResult rv; auto result(StrongOrRawPtr(mozilla::dom::UniFFIScaffolding::ReadPointer(global, arg0, Constify(arg1), arg2, rv))); if (rv.MaybeSetPendingException(cx, "UniFFIScaffolding.readPointer")) [[unlikely]] { return false; } MOZ_ASSERT(!JS_IsExceptionPending(cx)); if (!GetOrCreateDOMReflector(cx, result, args.rval())) { MOZ_ASSERT(JS_IsExceptionPending(cx)); return false; } return true; } MOZ_CAN_RUN_SCRIPT static bool writePointer(JSContext* cx_, unsigned argc, JS::Value* vp) { BindingCallContext cx(cx_, "UniFFIScaffolding.writePointer"); AUTO_PROFILER_LABEL_DYNAMIC_FAST( "UniFFIScaffolding", "writePointer", DOM, cx, uint32_t(js::ProfilingStackFrame::Flags::STRING_TEMPLATE_METHOD) | uint32_t(js::ProfilingStackFrame::Flags::RELEVANT_FOR_JS)); JS::CallArgs args = JS::CallArgsFromVp(argc, vp); JS::Rooted obj(cx, &args.callee()); if (!args.requireAtLeast(cx, "UniFFIScaffolding.writePointer", 4)) { return false; } GlobalObject global(cx, xpc::XrayAwareCalleeGlobal(obj)); if (global.Failed()) { return false; } uint64_t arg0; if (!ValueToPrimitive(cx, args[0], "Argument 1", &arg0)) { return false; } NonNull arg1; if (args[1].isObject()) { { // Our JSContext should be in the right global to do unwrapping in. nsresult rv = UnwrapObject(args[1], arg1, cx); if (NS_FAILED(rv)) { cx.ThrowErrorMessage("Argument 2", "UniFFIPointer"); return false; } } } else { cx.ThrowErrorMessage("Argument 2"); return false; } RootedSpiderMonkeyInterface arg2(cx); if (args[2].isObject()) { if (!arg2.Init(&args[2].toObject())) { cx.ThrowErrorMessage("Argument 3", "ArrayBuffer"); return false; } if (JS::IsSharedArrayBufferObject(arg2.Obj())) { cx.ThrowErrorMessage("Argument 3"); return false; } if (JS::IsLargeArrayBufferMaybeShared(arg2.Obj())) { cx.ThrowErrorMessage("Argument 3"); return false; } if (JS::IsResizableArrayBufferMaybeShared(arg2.Obj())) { cx.ThrowErrorMessage("Argument 3"); return false; } if (JS::IsImmutableArrayBufferMaybeShared(arg2.Obj())) { cx.ThrowErrorMessage("Argument 3"); return false; } } else { cx.ThrowErrorMessage("Argument 3"); return false; } int32_t arg3; if (!ValueToPrimitive(cx, args[3], "Argument 4", &arg3)) { return false; } FastErrorResult rv; // NOTE: This assert does NOT call the function. static_assert(std::is_void_v, "Should be returning void here"); mozilla::dom::UniFFIScaffolding::WritePointer(global, arg0, MOZ_KnownLive(NonNullHelper(arg1)), Constify(arg2), arg3, rv); if (rv.MaybeSetPendingException(cx, "UniFFIScaffolding.writePointer")) [[unlikely]] { return false; } MOZ_ASSERT(!JS_IsExceptionPending(cx)); args.rval().setUndefined(); return true; } MOZ_CAN_RUN_SCRIPT static bool registerCallbackHandler(JSContext* cx_, unsigned argc, JS::Value* vp) { BindingCallContext cx(cx_, "UniFFIScaffolding.registerCallbackHandler"); AUTO_PROFILER_LABEL_DYNAMIC_FAST( "UniFFIScaffolding", "registerCallbackHandler", DOM, cx, uint32_t(js::ProfilingStackFrame::Flags::STRING_TEMPLATE_METHOD) | uint32_t(js::ProfilingStackFrame::Flags::RELEVANT_FOR_JS)); JS::CallArgs args = JS::CallArgsFromVp(argc, vp); JS::Rooted obj(cx, &args.callee()); if (!args.requireAtLeast(cx, "UniFFIScaffolding.registerCallbackHandler", 2)) { return false; } GlobalObject global(cx, xpc::XrayAwareCalleeGlobal(obj)); if (global.Failed()) { return false; } uint32_t arg0; if (!ValueToPrimitive(cx, args[0], "Argument 1", &arg0)) { return false; } RootedCallback> arg1(cx); if (args[1].isObject()) { { // scope for tempRoot and tempGlobalRoot if needed arg1 = new binding_detail::FastUniFFICallbackHandler(&args[1].toObject(), JS::CurrentGlobalOrNull(cx)); } } else { cx.ThrowErrorMessage("Argument 2"); return false; } FastErrorResult rv; // NOTE: This assert does NOT call the function. static_assert(std::is_void_v, "Should be returning void here"); mozilla::dom::UniFFIScaffolding::RegisterCallbackHandler(global, arg0, MOZ_KnownLive(NonNullHelper(arg1)), rv); if (rv.MaybeSetPendingException(cx, "UniFFIScaffolding.registerCallbackHandler")) [[unlikely]] { return false; } MOZ_ASSERT(!JS_IsExceptionPending(cx)); args.rval().setUndefined(); return true; } MOZ_CAN_RUN_SCRIPT static bool deregisterCallbackHandler(JSContext* cx, unsigned argc, JS::Value* vp) { AUTO_PROFILER_LABEL_DYNAMIC_FAST( "UniFFIScaffolding", "deregisterCallbackHandler", DOM, cx, uint32_t(js::ProfilingStackFrame::Flags::STRING_TEMPLATE_METHOD) | uint32_t(js::ProfilingStackFrame::Flags::RELEVANT_FOR_JS)); JS::CallArgs args = JS::CallArgsFromVp(argc, vp); JS::Rooted obj(cx, &args.callee()); if (!args.requireAtLeast(cx, "UniFFIScaffolding.deregisterCallbackHandler", 1)) { return false; } GlobalObject global(cx, xpc::XrayAwareCalleeGlobal(obj)); if (global.Failed()) { return false; } uint32_t arg0; if (!ValueToPrimitive(cx, args[0], "Argument 1", &arg0)) { return false; } FastErrorResult rv; // NOTE: This assert does NOT call the function. static_assert(std::is_void_v, "Should be returning void here"); mozilla::dom::UniFFIScaffolding::DeregisterCallbackHandler(global, arg0, rv); if (rv.MaybeSetPendingException(cx, "UniFFIScaffolding.deregisterCallbackHandler")) [[unlikely]] { return false; } MOZ_ASSERT(!JS_IsExceptionPending(cx)); args.rval().setUndefined(); return true; } MOZ_CAN_RUN_SCRIPT static bool callbackHandleCreate(JSContext* cx, unsigned argc, JS::Value* vp) { AUTO_PROFILER_LABEL_DYNAMIC_FAST( "UniFFIScaffolding", "callbackHandleCreate", DOM, cx, uint32_t(js::ProfilingStackFrame::Flags::STRING_TEMPLATE_METHOD) | uint32_t(js::ProfilingStackFrame::Flags::RELEVANT_FOR_JS)); JS::CallArgs args = JS::CallArgsFromVp(argc, vp); JS::Rooted obj(cx, &args.callee()); GlobalObject global(cx, xpc::XrayAwareCalleeGlobal(obj)); if (global.Failed()) { return false; } uint64_t result(mozilla::dom::UniFFIScaffolding::CallbackHandleCreate(global)); MOZ_ASSERT(!JS_IsExceptionPending(cx)); args.rval().set(JS::NumberValue(double(result))); return true; } MOZ_CAN_RUN_SCRIPT static bool callbackHandleRelease(JSContext* cx, unsigned argc, JS::Value* vp) { AUTO_PROFILER_LABEL_DYNAMIC_FAST( "UniFFIScaffolding", "callbackHandleRelease", DOM, cx, uint32_t(js::ProfilingStackFrame::Flags::STRING_TEMPLATE_METHOD) | uint32_t(js::ProfilingStackFrame::Flags::RELEVANT_FOR_JS)); JS::CallArgs args = JS::CallArgsFromVp(argc, vp); JS::Rooted obj(cx, &args.callee()); if (!args.requireAtLeast(cx, "UniFFIScaffolding.callbackHandleRelease", 1)) { return false; } GlobalObject global(cx, xpc::XrayAwareCalleeGlobal(obj)); if (global.Failed()) { return false; } uint64_t arg0; if (!ValueToPrimitive(cx, args[0], "Argument 1", &arg0)) { return false; } uint32_t result(mozilla::dom::UniFFIScaffolding::CallbackHandleRelease(global, arg0)); MOZ_ASSERT(!JS_IsExceptionPending(cx)); args.rval().setNumber(result); return true; } MOZ_CAN_RUN_SCRIPT static bool callbackHandleFree(JSContext* cx, unsigned argc, JS::Value* vp) { AUTO_PROFILER_LABEL_DYNAMIC_FAST( "UniFFIScaffolding", "callbackHandleFree", DOM, cx, uint32_t(js::ProfilingStackFrame::Flags::STRING_TEMPLATE_METHOD) | uint32_t(js::ProfilingStackFrame::Flags::RELEVANT_FOR_JS)); JS::CallArgs args = JS::CallArgsFromVp(argc, vp); JS::Rooted obj(cx, &args.callee()); if (!args.requireAtLeast(cx, "UniFFIScaffolding.callbackHandleFree", 1)) { return false; } GlobalObject global(cx, xpc::XrayAwareCalleeGlobal(obj)); if (global.Failed()) { return false; } uint64_t arg0; if (!ValueToPrimitive(cx, args[0], "Argument 1", &arg0)) { return false; } // NOTE: This assert does NOT call the function. static_assert(std::is_void_v, "Should be returning void here"); mozilla::dom::UniFFIScaffolding::CallbackHandleFree(global, arg0); MOZ_ASSERT(!JS_IsExceptionPending(cx)); args.rval().setUndefined(); return true; } MOZ_GLOBINIT static const JSFunctionSpec sStaticMethods_specs[] = { JS_FNSPEC("callSync", callSync, nullptr, 1, JSPROP_ENUMERATE, nullptr), JS_FNSPEC("callAsync", StaticMethodPromiseWrapper, &callAsync_methodinfo, 1, JSPROP_ENUMERATE, nullptr), JS_FNSPEC("callAsyncWrapper", StaticMethodPromiseWrapper, &callAsyncWrapper_methodinfo, 1, JSPROP_ENUMERATE, nullptr), JS_FNSPEC("readPointer", readPointer, nullptr, 3, JSPROP_ENUMERATE, nullptr), JS_FNSPEC("writePointer", writePointer, nullptr, 4, JSPROP_ENUMERATE, nullptr), JS_FNSPEC("registerCallbackHandler", registerCallbackHandler, nullptr, 2, JSPROP_ENUMERATE, nullptr), JS_FNSPEC("deregisterCallbackHandler", deregisterCallbackHandler, nullptr, 1, JSPROP_ENUMERATE, nullptr), JS_FNSPEC("callbackHandleCreate", callbackHandleCreate, nullptr, 0, JSPROP_ENUMERATE, nullptr), JS_FNSPEC("callbackHandleRelease", callbackHandleRelease, nullptr, 1, JSPROP_ENUMERATE, nullptr), JS_FNSPEC("callbackHandleFree", callbackHandleFree, nullptr, 1, JSPROP_ENUMERATE, nullptr), JS_FS_END }; static const Prefable sStaticMethods[] = { { nullptr, &sStaticMethods_specs[0] }, { nullptr, nullptr } }; static_assert(1 <= 1ull << NUM_BITS_PROPERTY_INFO_PREF_INDEX, "We have a prefable index that is >= (1 << NUM_BITS_PROPERTY_INFO_PREF_INDEX)"); static_assert(10 <= 1ull << NUM_BITS_PROPERTY_INFO_SPEC_INDEX, "We have a spec index that is >= (1 << NUM_BITS_PROPERTY_INFO_SPEC_INDEX)"); static uint16_t sNativeProperties_sortedPropertyIndices[10]; static PropertyInfo sNativeProperties_propertyInfos[10]; static const NativePropertiesN<1> sNativeProperties = { true, 0 /* sStaticMethods */, false, 0, false, 0, false, 0, false, 0, false, 0, false, 0, -1, 10, sNativeProperties_sortedPropertyIndices, { { sStaticMethods, &sNativeProperties_propertyInfos[0] } } }; static_assert(10 < 1ull << (CHAR_BIT * sizeof(sNativeProperties.propertyInfoCount)), "We have a property info count that is oversized"); bool sNativePropertiesInited = false; const NativePropertyHooks sNativePropertyHooks = { nullptr, { sNativeProperties.Upcast(), nullptr, &sNativePropertiesInited }, prototypes::id::_ID_Count, constructors::id::UniFFIScaffolding, &DefaultXrayExpandoObjectClass }; static const DOMIfaceAndProtoJSClass sNamespaceObjectClass = { { "UniFFIScaffolding", JSCLASS_IS_DOMIFACEANDPROTOJSCLASS, JS_NULL_CLASS_OPS, JS_NULL_CLASS_SPEC, JS_NULL_CLASS_EXT, JS_NULL_OBJECT_OPS }, eNamespace, prototypes::id::_ID_Count, 0, &sNativePropertyHooks, // This isn't strictly following the spec (see // https://console.spec.whatwg.org/#ref-for-dfn-namespace-object), // but should be ok for Xrays. JS::GetRealmObjectPrototype }; bool ConstructorEnabled(JSContext* aCx, JS::Handle aObj) { return nsContentUtils::ThreadsafeIsSystemCaller(aCx); } void CreateInterfaceObjects(JSContext* aCx, JS::Handle aGlobal, ProtoAndIfaceCache& aProtoAndIfaceCache, DefineInterfaceProperty aDefineOnGlobal) { JS::Rooted constructorProto(aCx, JS::GetRealmObjectPrototype(aCx)); if (!constructorProto) { return; } JS::Heap* interfaceCache = &aProtoAndIfaceCache.EntrySlotOrCreate(constructors::id::UniFFIScaffolding); dom::CreateNamespaceObject(aCx, aGlobal, constructorProto, sNamespaceObjectClass, interfaceCache, sNativeProperties.Upcast(), nullptr, "UniFFIScaffolding", ShouldExpose(aCx, aGlobal, aDefineOnGlobal)); } JS::Handle GetConstructorObjectHandle(JSContext* aCx) { /* Get the interface object for this class. This will create the object as needed. */ return GetPerInterfaceObjectHandle(aCx, constructors::id::UniFFIScaffolding, &CreateInterfaceObjects, DefineInterfaceProperty::CheckExposure); } } // namespace UniFFIScaffolding_Binding already_AddRefed UniFFICallbackHandler::CallAsync(uint64_t objectHandle, uint32_t methodIndex, const nsTArray& args, ErrorResult& aRv, const char* aExecutionReason, ExceptionHandling aExceptionHandling, JS::Realm* aRealm) { CallSetup s(this, aRv, "UniFFICallbackHandler.callAsync", aExceptionHandling, aRealm); if (aRv.Failed()) { return nullptr; } MOZ_ASSERT(s.GetContext()); BindingCallContext& cx = s.GetCallContext(); JS::Rooted rval(cx); JS::RootedVector argv(cx); if (!argv.resize((3 - 1) + args.Length())) { // That threw an exception on the JSContext, and our CallSetup will do // the right thing with that. return nullptr; } unsigned argc = (3 - 1) + args.Length(); do { for (uint32_t idx = 0; idx < args.Length(); ++idx) { JS::Rooted callbackObj(cx, CallbackKnownNotGray()); if (!args[idx].ToJSVal(cx, callbackObj, argv[2 + idx])) { aRv.Throw(NS_ERROR_UNEXPECTED); return nullptr; } continue; } break; } while (false); do { argv[1].setNumber(methodIndex); break; } while (false); do { argv[0].set(JS::NumberValue(double(objectHandle))); break; } while (false); JS::Rooted callable(cx); UniFFICallbackHandlerAtoms* atomsCache = GetAtomCache(cx); if ((reinterpret_cast(atomsCache)->isVoid() && !InitIds(cx, atomsCache)) || !GetCallableProperty(cx, atomsCache->callAsync_id, &callable)) { aRv.Throw(NS_ERROR_UNEXPECTED); return nullptr; } JS::Rooted thisValue(cx, JS::ObjectValue(*mCallback)); if (!JS::Call(cx, thisValue, callable, JS::HandleValueArray::subarray(argv, 0, argc), &rval)) { aRv.NoteJSContextException(cx); return nullptr; } RefPtr rvalDecl; { // Scope for our GlobalObject, FastErrorResult, JSAutoRealm, // etc. JS::Rooted globalObj(cx); // We basically want our entry global here. Play it safe // and use GetEntryGlobal() to get it, with whatever // principal-clamping it ends up doing. globalObj = GetEntryGlobal()->GetGlobalJSObject(); JSAutoRealm ar(cx, globalObj); GlobalObject promiseGlobal(cx, globalObj); if (promiseGlobal.Failed()) { aRv.Throw(NS_ERROR_UNEXPECTED); return nullptr; } JS::Rooted valueToResolve(cx, rval); if (!JS_WrapValue(cx, &valueToResolve)) { aRv.Throw(NS_ERROR_UNEXPECTED); return nullptr; } binding_detail::FastErrorResult promiseRv; nsCOMPtr global = do_QueryInterface(promiseGlobal.GetAsSupports()); if (!global) { promiseRv.Throw(NS_ERROR_UNEXPECTED); MOZ_ALWAYS_TRUE(promiseRv.MaybeSetPendingException(cx)); aRv.Throw(NS_ERROR_UNEXPECTED); return nullptr; } rvalDecl = Promise::Resolve(global, cx, valueToResolve, promiseRv); if (promiseRv.MaybeSetPendingException(cx)) { aRv.Throw(NS_ERROR_UNEXPECTED); return nullptr; } } return rvalDecl.forget(); } void UniFFICallbackHandler::CallSync(uint64_t objectHandle, uint32_t methodIndex, const nsTArray& args, UniFFIScaffoldingCallResult& aRetVal, ErrorResult& aRv, const char* aExecutionReason, ExceptionHandling aExceptionHandling, JS::Realm* aRealm) { CallSetup s(this, aRv, "UniFFICallbackHandler.callSync", aExceptionHandling, aRealm); if (aRv.Failed()) { return; } MOZ_ASSERT(s.GetContext()); BindingCallContext& cx = s.GetCallContext(); JS::Rooted rval(cx); JS::RootedVector argv(cx); if (!argv.resize((3 - 1) + args.Length())) { // That threw an exception on the JSContext, and our CallSetup will do // the right thing with that. return; } unsigned argc = (3 - 1) + args.Length(); do { for (uint32_t idx = 0; idx < args.Length(); ++idx) { JS::Rooted callbackObj(cx, CallbackKnownNotGray()); if (!args[idx].ToJSVal(cx, callbackObj, argv[2 + idx])) { aRv.Throw(NS_ERROR_UNEXPECTED); return; } continue; } break; } while (false); do { argv[1].setNumber(methodIndex); break; } while (false); do { argv[0].set(JS::NumberValue(double(objectHandle))); break; } while (false); JS::Rooted callable(cx); UniFFICallbackHandlerAtoms* atomsCache = GetAtomCache(cx); if ((reinterpret_cast(atomsCache)->isVoid() && !InitIds(cx, atomsCache)) || !GetCallableProperty(cx, atomsCache->callSync_id, &callable)) { aRv.Throw(NS_ERROR_UNEXPECTED); return; } JS::Rooted thisValue(cx, JS::ObjectValue(*mCallback)); if (!JS::Call(cx, thisValue, callable, JS::HandleValueArray::subarray(argv, 0, argc), &rval)) { aRv.NoteJSContextException(cx); return; } UniFFIScaffoldingCallResult& rvalDecl(aRetVal); if (!rvalDecl.Init(cx, rval, "Return value of UniFFICallbackHandler.callSync", false)) { aRv.Throw(NS_ERROR_UNEXPECTED); return; } } void UniFFICallbackHandler::Destroy(uint64_t objectHandle, ErrorResult& aRv, const char* aExecutionReason, ExceptionHandling aExceptionHandling, JS::Realm* aRealm) { CallSetup s(this, aRv, "UniFFICallbackHandler.destroy", aExceptionHandling, aRealm); if (aRv.Failed()) { return; } MOZ_ASSERT(s.GetContext()); BindingCallContext& cx = s.GetCallContext(); JS::Rooted rval(cx); JS::RootedVector argv(cx); if (!argv.resize(1)) { // That threw an exception on the JSContext, and our CallSetup will do // the right thing with that. return; } unsigned argc = 1; do { argv[0].set(JS::NumberValue(double(objectHandle))); break; } while (false); JS::Rooted callable(cx); UniFFICallbackHandlerAtoms* atomsCache = GetAtomCache(cx); if ((reinterpret_cast(atomsCache)->isVoid() && !InitIds(cx, atomsCache)) || !GetCallableProperty(cx, atomsCache->destroy_id, &callable)) { aRv.Throw(NS_ERROR_UNEXPECTED); return; } JS::Rooted thisValue(cx, JS::ObjectValue(*mCallback)); if (!JS::Call(cx, thisValue, callable, JS::HandleValueArray::subarray(argv, 0, argc), &rval)) { aRv.NoteJSContextException(cx); return; } } bool UniFFICallbackHandler::InitIds(JSContext* cx, UniFFICallbackHandlerAtoms* atomsCache) { MOZ_ASSERT(reinterpret_cast(atomsCache)->isVoid()); // Initialize these in reverse order so that any failure leaves the first one // uninitialized. if (!atomsCache->destroy_id.init(cx, "destroy") || !atomsCache->callSync_id.init(cx, "callSync") || !atomsCache->callAsync_id.init(cx, "callAsync")) { return false; } return true; } } // namespace dom } // namespace mozilla