Bug 1852740: add tests for the `fetchpriority` attribute in Link headers. r=necko...
[gecko.git] / js / xpconnect / src / XPCWrappedNative.cpp
blob21f5c3e003eabd5e21b0379d5638eaaa15885b95
1 /* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
2 /* vim: set ts=8 sts=2 et sw=2 tw=80: */
3 /* This Source Code Form is subject to the terms of the Mozilla Public
4 * License, v. 2.0. If a copy of the MPL was not distributed with this
5 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
7 /* Wrapper object for reflecting native xpcom objects into JavaScript. */
9 #include "xpcprivate.h"
10 #include "XPCMaps.h"
11 #include "nsWrapperCacheInlines.h"
12 #include "XPCLog.h"
13 #include "js/Array.h" // JS::GetArrayLength, JS::IsArrayObject
14 #include "js/experimental/TypedData.h" // JS_GetTypedArrayLength, JS_IsTypedArrayObject
15 #include "js/MemoryFunctions.h"
16 #include "js/Object.h" // JS::GetPrivate, JS::SetPrivate, JS::SetReservedSlot
17 #include "js/Printf.h"
18 #include "js/PropertyAndElement.h" // JS_GetProperty, JS_GetPropertyById, JS_SetProperty, JS_SetPropertyById
19 #include "jsfriendapi.h"
20 #include "AccessCheck.h"
21 #include "WrapperFactory.h"
22 #include "XrayWrapper.h"
24 #include "nsContentUtils.h"
25 #include "nsCycleCollectionNoteRootCallback.h"
27 #include <new>
28 #include <stdint.h>
29 #include "mozilla/DeferredFinalize.h"
30 #include "mozilla/Likely.h"
31 #include "mozilla/Unused.h"
32 #include "mozilla/Sprintf.h"
33 #include "mozilla/dom/BindingUtils.h"
34 #include "mozilla/ProfilerLabels.h"
35 #include <algorithm>
37 using namespace xpc;
38 using namespace mozilla;
39 using namespace mozilla::dom;
40 using namespace JS;
42 /***************************************************************************/
44 NS_IMPL_CYCLE_COLLECTION_CLASS(XPCWrappedNative)
46 // No need to unlink the JS objects: if the XPCWrappedNative is cycle
47 // collected then its mFlatJSObject will be cycle collected too and
48 // finalization of the mFlatJSObject will unlink the JS objects (see
49 // XPC_WN_NoHelper_Finalize and FlatJSObjectFinalized).
50 NS_IMPL_CYCLE_COLLECTION_UNLINK_BEGIN(XPCWrappedNative)
51 tmp->ExpireWrapper();
52 NS_IMPL_CYCLE_COLLECTION_UNLINK_END
54 NS_IMPL_CYCLE_COLLECTION_TRAVERSE_BEGIN_INTERNAL(XPCWrappedNative)
55 if (!tmp->IsValid()) {
56 return NS_OK;
59 if (MOZ_UNLIKELY(cb.WantDebugInfo())) {
60 char name[72];
61 nsCOMPtr<nsIXPCScriptable> scr = tmp->GetScriptable();
62 if (scr) {
63 SprintfLiteral(name, "XPCWrappedNative (%s)", scr->GetJSClass()->name);
64 } else {
65 SprintfLiteral(name, "XPCWrappedNative");
68 cb.DescribeRefCountedNode(tmp->mRefCnt.get(), name);
69 } else {
70 NS_IMPL_CYCLE_COLLECTION_DESCRIBE(XPCWrappedNative, tmp->mRefCnt.get())
73 if (tmp->HasExternalReference()) {
74 // If our refcount is > 1, our reference to the flat JS object is
75 // considered "strong", and we're going to traverse it.
77 // If our refcount is <= 1, our reference to the flat JS object is
78 // considered "weak", and we're *not* going to traverse it.
80 // This reasoning is in line with the slightly confusing lifecycle rules
81 // for XPCWrappedNatives, described in a larger comment below and also
82 // on our wiki at http://wiki.mozilla.org/XPConnect_object_wrapping
84 JSObject* obj = tmp->GetFlatJSObjectPreserveColor();
85 NS_CYCLE_COLLECTION_NOTE_EDGE_NAME(cb, "mFlatJSObject");
86 cb.NoteJSChild(JS::GCCellPtr(obj));
89 // XPCWrappedNative keeps its native object alive.
90 NS_CYCLE_COLLECTION_NOTE_EDGE_NAME(cb, "mIdentity");
91 cb.NoteXPCOMChild(tmp->GetIdentityObject());
93 tmp->NoteTearoffs(cb);
95 NS_IMPL_CYCLE_COLLECTION_TRAVERSE_END
97 void XPCWrappedNative::Suspect(nsCycleCollectionNoteRootCallback& cb) {
98 if (!IsValid() || IsWrapperExpired()) {
99 return;
102 MOZ_ASSERT(NS_IsMainThread(),
103 "Suspecting wrapped natives from non-main thread");
105 // Only record objects that might be part of a cycle as roots, unless
106 // the callback wants all traces (a debug feature). Do this even if
107 // the XPCWN doesn't own the JS reflector object in case the reflector
108 // keeps alive other C++ things. This is safe because if the reflector
109 // had died the reference from the XPCWN to it would have been cleared.
110 JSObject* obj = GetFlatJSObjectPreserveColor();
111 if (JS::ObjectIsMarkedGray(obj) || cb.WantAllTraces()) {
112 cb.NoteJSRoot(obj);
116 void XPCWrappedNative::NoteTearoffs(nsCycleCollectionTraversalCallback& cb) {
117 // Tearoffs hold their native object alive. If their JS object hasn't been
118 // finalized yet we'll note the edge between the JS object and the native
119 // (see nsXPConnect::Traverse), but if their JS object has been finalized
120 // then the tearoff is only reachable through the XPCWrappedNative, so we
121 // record an edge here.
122 for (XPCWrappedNativeTearOff* to = &mFirstTearOff; to;
123 to = to->GetNextTearOff()) {
124 JSObject* jso = to->GetJSObjectPreserveColor();
125 if (!jso) {
126 NS_CYCLE_COLLECTION_NOTE_EDGE_NAME(cb, "tearoff's mNative");
127 cb.NoteXPCOMChild(to->GetNative());
132 #ifdef XPC_CHECK_CLASSINFO_CLAIMS
133 static void DEBUG_CheckClassInfoClaims(XPCWrappedNative* wrapper);
134 #else
135 # define DEBUG_CheckClassInfoClaims(wrapper) ((void)0)
136 #endif
138 /***************************************************************************/
139 static nsresult FinishCreate(JSContext* cx, XPCWrappedNativeScope* Scope,
140 XPCNativeInterface* Interface,
141 nsWrapperCache* cache, XPCWrappedNative* inWrapper,
142 XPCWrappedNative** resultWrapper);
144 // static
146 // This method handles the special case of wrapping a new global object.
148 // The normal code path for wrapping natives goes through
149 // XPCConvert::NativeInterface2JSObject, XPCWrappedNative::GetNewOrUsed,
150 // and finally into XPCWrappedNative::Init. Unfortunately, this path assumes
151 // very early on that we have an XPCWrappedNativeScope and corresponding global
152 // JS object, which are the very things we need to create here. So we special-
153 // case the logic and do some things in a different order.
154 nsresult XPCWrappedNative::WrapNewGlobal(JSContext* cx,
155 xpcObjectHelper& nativeHelper,
156 nsIPrincipal* principal,
157 bool initStandardClasses,
158 JS::RealmOptions& aOptions,
159 XPCWrappedNative** wrappedGlobal) {
160 nsCOMPtr<nsISupports> identity = do_QueryInterface(nativeHelper.Object());
162 // The object should specify that it's meant to be global.
163 MOZ_ASSERT(nativeHelper.GetScriptableFlags() &
164 XPC_SCRIPTABLE_IS_GLOBAL_OBJECT);
166 // We shouldn't be reusing globals.
167 MOZ_ASSERT(!nativeHelper.GetWrapperCache() ||
168 !nativeHelper.GetWrapperCache()->GetWrapperPreserveColor());
170 // Get the nsIXPCScriptable. This will tell us the JSClass of the object
171 // we're going to create.
172 nsCOMPtr<nsIXPCScriptable> scrProto;
173 nsCOMPtr<nsIXPCScriptable> scrWrapper;
174 GatherScriptable(identity, nativeHelper.GetClassInfo(),
175 getter_AddRefs(scrProto), getter_AddRefs(scrWrapper));
176 MOZ_ASSERT(scrWrapper);
178 // Finally, we get to the JSClass.
179 const JSClass* clasp = scrWrapper->GetJSClass();
180 MOZ_ASSERT(clasp->flags & JSCLASS_IS_GLOBAL);
182 // Create the global.
183 aOptions.creationOptions().setTrace(XPCWrappedNative::Trace);
184 xpc::SetPrefableRealmOptions(aOptions);
186 RootedObject global(cx,
187 xpc::CreateGlobalObject(cx, clasp, principal, aOptions));
188 if (!global) {
189 return NS_ERROR_FAILURE;
191 XPCWrappedNativeScope* scope = ObjectScope(global);
193 // Immediately enter the global's realm, so that everything else we
194 // create ends up there.
195 JSAutoRealm ar(cx, global);
197 // If requested, initialize the standard classes on the global.
198 if (initStandardClasses && !JS::InitRealmStandardClasses(cx)) {
199 return NS_ERROR_FAILURE;
202 // Make a proto.
203 XPCWrappedNativeProto* proto = XPCWrappedNativeProto::GetNewOrUsed(
204 cx, scope, nativeHelper.GetClassInfo(), scrProto);
205 if (!proto) {
206 return NS_ERROR_FAILURE;
209 // Set up the prototype on the global.
210 MOZ_ASSERT(proto->GetJSProtoObject());
211 RootedObject protoObj(cx, proto->GetJSProtoObject());
212 bool success = JS_SetPrototype(cx, global, protoObj);
213 if (!success) {
214 return NS_ERROR_FAILURE;
217 // Construct the wrapper, which takes over the strong reference to the
218 // native object.
219 RefPtr<XPCWrappedNative> wrapper =
220 new XPCWrappedNative(std::move(identity), proto);
223 // We don't call ::Init() on this wrapper, because our setup requirements
224 // are different for globals. We do our setup inline here, instead.
227 wrapper->mScriptable = scrWrapper;
229 // Set the JS object to the global we already created.
230 wrapper->SetFlatJSObject(global);
232 // Set the reserved slot to the XPCWrappedNative.
233 static_assert(JSCLASS_GLOBAL_APPLICATION_SLOTS > 0,
234 "Need at least one slot for JSCLASS_SLOT0_IS_NSISUPPORTS");
235 JS::SetObjectISupports(global, wrapper);
237 // There are dire comments elsewhere in the code about how a GC can
238 // happen somewhere after wrapper initialization but before the wrapper is
239 // added to the hashtable in FinishCreate(). It's not clear if that can
240 // happen here, but let's just be safe for now.
241 AutoMarkingWrappedNativePtr wrapperMarker(cx, wrapper);
243 // Call the common Init finish routine. This mainly just does an AddRef
244 // on behalf of XPConnect (the corresponding Release is in the finalizer
245 // hook), but it does some other miscellaneous things too, so we don't
246 // inline it.
247 success = wrapper->FinishInit(cx);
248 MOZ_ASSERT(success);
250 // Go through some extra work to find the tearoff. This is kind of silly
251 // on a conceptual level: the point of tearoffs is to cache the results
252 // of QI-ing mIdentity to different interfaces, and we don't need that
253 // since we're dealing with nsISupports. But lots of code expects tearoffs
254 // to exist for everything, so we just follow along.
255 RefPtr<XPCNativeInterface> iface =
256 XPCNativeInterface::GetNewOrUsed(cx, &NS_GET_IID(nsISupports));
257 MOZ_ASSERT(iface);
258 nsresult status;
259 success = wrapper->FindTearOff(cx, iface, false, &status);
260 if (!success) {
261 return status;
264 // Call the common creation finish routine. This does all of the bookkeeping
265 // like inserting the wrapper into the wrapper map and setting up the wrapper
266 // cache.
267 nsresult rv = FinishCreate(cx, scope, iface, nativeHelper.GetWrapperCache(),
268 wrapper, wrappedGlobal);
269 NS_ENSURE_SUCCESS(rv, rv);
271 return NS_OK;
274 // static
275 nsresult XPCWrappedNative::GetNewOrUsed(JSContext* cx, xpcObjectHelper& helper,
276 XPCWrappedNativeScope* Scope,
277 XPCNativeInterface* Interface,
278 XPCWrappedNative** resultWrapper) {
279 MOZ_ASSERT(Interface);
280 nsWrapperCache* cache = helper.GetWrapperCache();
282 MOZ_ASSERT(!cache || !cache->GetWrapperPreserveColor(),
283 "We assume the caller already checked if it could get the "
284 "wrapper from the cache.");
286 nsresult rv;
288 MOZ_ASSERT(!Scope->GetRuntime()->GCIsRunning(),
289 "XPCWrappedNative::GetNewOrUsed called during GC");
291 nsCOMPtr<nsISupports> identity = do_QueryInterface(helper.Object());
293 if (!identity) {
294 NS_ERROR("This XPCOM object fails in QueryInterface to nsISupports!");
295 return NS_ERROR_FAILURE;
298 RefPtr<XPCWrappedNative> wrapper;
300 Native2WrappedNativeMap* map = Scope->GetWrappedNativeMap();
301 // Some things are nsWrapperCache subclasses but never use the cache, so go
302 // ahead and check our map even if we have a cache and it has no existing
303 // wrapper: we might have an XPCWrappedNative anyway.
304 wrapper = map->Find(identity);
306 if (wrapper) {
307 if (!wrapper->FindTearOff(cx, Interface, false, &rv)) {
308 MOZ_ASSERT(NS_FAILED(rv), "returning NS_OK on failure");
309 return rv;
311 wrapper.forget(resultWrapper);
312 return NS_OK;
315 // There is a chance that the object wants to have the self-same JSObject
316 // reflection regardless of the scope into which we are reflecting it.
317 // Many DOM objects require this. The scriptable helper specifies this
318 // in preCreate by indicating a 'parent' of a particular scope.
320 // To handle this we need to get the scriptable helper early and ask it.
321 // It is possible that we will then end up forwarding this entire call
322 // to this same function but with a different scope.
324 // If we are making a wrapper for an nsIClassInfo singleton then
325 // We *don't* want to have it use the prototype meant for instances
326 // of that class.
327 uint32_t classInfoFlags;
328 bool isClassInfoSingleton =
329 helper.GetClassInfo() == helper.Object() &&
330 NS_SUCCEEDED(helper.GetClassInfo()->GetFlags(&classInfoFlags)) &&
331 (classInfoFlags & nsIClassInfo::SINGLETON_CLASSINFO);
333 nsIClassInfo* info = helper.GetClassInfo();
335 nsCOMPtr<nsIXPCScriptable> scrProto;
336 nsCOMPtr<nsIXPCScriptable> scrWrapper;
338 // Gather scriptable create info if we are wrapping something
339 // other than an nsIClassInfo object. We need to not do this for
340 // nsIClassInfo objects because often nsIClassInfo implementations
341 // are also nsIXPCScriptable helper implementations, but the helper
342 // code is obviously intended for the implementation of the class
343 // described by the nsIClassInfo, not for the class info object
344 // itself.
345 if (!isClassInfoSingleton) {
346 GatherScriptable(identity, info, getter_AddRefs(scrProto),
347 getter_AddRefs(scrWrapper));
350 RootedObject parent(cx, Scope->GetGlobalForWrappedNatives());
352 mozilla::Maybe<JSAutoRealm> ar;
354 if (scrWrapper && scrWrapper->WantPreCreate()) {
355 RootedObject plannedParent(cx, parent);
356 nsresult rv = scrWrapper->PreCreate(identity, cx, parent, parent.address());
357 if (NS_FAILED(rv)) {
358 return rv;
360 rv = NS_OK;
362 MOZ_ASSERT(!xpc::WrapperFactory::IsXrayWrapper(parent),
363 "Xray wrapper being used to parent XPCWrappedNative?");
365 MOZ_ASSERT(JS_IsGlobalObject(parent),
366 "Non-global being used to parent XPCWrappedNative?");
368 ar.emplace(static_cast<JSContext*>(cx), parent);
370 if (parent != plannedParent) {
371 XPCWrappedNativeScope* betterScope = ObjectScope(parent);
372 MOZ_ASSERT(betterScope != Scope,
373 "How can we have the same scope for two different globals?");
374 return GetNewOrUsed(cx, helper, betterScope, Interface, resultWrapper);
377 // Take the performance hit of checking the hashtable again in case
378 // the preCreate call caused the wrapper to get created through some
379 // interesting path (the DOM code tends to make this happen sometimes).
381 if (cache) {
382 RootedObject cached(cx, cache->GetWrapper());
383 if (cached) {
384 wrapper = XPCWrappedNative::Get(cached);
386 } else {
387 wrapper = map->Find(identity);
390 if (wrapper) {
391 if (!wrapper->FindTearOff(cx, Interface, false, &rv)) {
392 MOZ_ASSERT(NS_FAILED(rv), "returning NS_OK on failure");
393 return rv;
395 wrapper.forget(resultWrapper);
396 return NS_OK;
398 } else {
399 ar.emplace(static_cast<JSContext*>(cx), parent);
402 AutoMarkingWrappedNativeProtoPtr proto(cx);
404 // If there is ClassInfo (and we are not building a wrapper for the
405 // nsIClassInfo interface) then we use a wrapper that needs a prototype.
407 // Note that the security check happens inside FindTearOff - after the
408 // wrapper is actually created, but before JS code can see it.
410 if (info && !isClassInfoSingleton) {
411 proto = XPCWrappedNativeProto::GetNewOrUsed(cx, Scope, info, scrProto);
412 if (!proto) {
413 return NS_ERROR_FAILURE;
416 wrapper = new XPCWrappedNative(std::move(identity), proto);
417 } else {
418 RefPtr<XPCNativeInterface> iface = Interface;
419 if (!iface) {
420 iface = XPCNativeInterface::GetISupports(cx);
423 XPCNativeSetKey key(cx, iface);
424 RefPtr<XPCNativeSet> set = XPCNativeSet::GetNewOrUsed(cx, &key);
426 if (!set) {
427 return NS_ERROR_FAILURE;
430 wrapper = new XPCWrappedNative(std::move(identity), Scope, set.forget());
433 MOZ_ASSERT(!xpc::WrapperFactory::IsXrayWrapper(parent),
434 "Xray wrapper being used to parent XPCWrappedNative?");
436 // We use an AutoMarkingPtr here because it is possible for JS gc to happen
437 // after we have Init'd the wrapper but *before* we add it to the hashtable.
438 // This would cause the mSet to get collected and we'd later crash. I've
439 // *seen* this happen.
440 AutoMarkingWrappedNativePtr wrapperMarker(cx, wrapper);
442 if (!wrapper->Init(cx, scrWrapper)) {
443 return NS_ERROR_FAILURE;
446 if (!wrapper->FindTearOff(cx, Interface, false, &rv)) {
447 MOZ_ASSERT(NS_FAILED(rv), "returning NS_OK on failure");
448 return rv;
451 return FinishCreate(cx, Scope, Interface, cache, wrapper, resultWrapper);
454 static nsresult FinishCreate(JSContext* cx, XPCWrappedNativeScope* Scope,
455 XPCNativeInterface* Interface,
456 nsWrapperCache* cache, XPCWrappedNative* inWrapper,
457 XPCWrappedNative** resultWrapper) {
458 MOZ_ASSERT(inWrapper);
460 Native2WrappedNativeMap* map = Scope->GetWrappedNativeMap();
462 RefPtr<XPCWrappedNative> wrapper;
463 // Deal with the case where the wrapper got created as a side effect
464 // of one of our calls out of this code. Add() returns the (possibly
465 // pre-existing) wrapper that ultimately ends up in the map, which is
466 // what we want.
467 wrapper = map->Add(inWrapper);
468 if (!wrapper) {
469 return NS_ERROR_FAILURE;
472 if (wrapper == inWrapper) {
473 JSObject* flat = wrapper->GetFlatJSObject();
474 MOZ_ASSERT(!cache || !cache->GetWrapperPreserveColor() ||
475 flat == cache->GetWrapperPreserveColor(),
476 "This object has a cached wrapper that's different from "
477 "the JSObject held by its native wrapper?");
479 if (cache && !cache->GetWrapperPreserveColor()) {
480 cache->SetWrapper(flat);
484 DEBUG_CheckClassInfoClaims(wrapper);
485 wrapper.forget(resultWrapper);
486 return NS_OK;
489 // This ctor is used if this object will have a proto.
490 XPCWrappedNative::XPCWrappedNative(nsCOMPtr<nsISupports>&& aIdentity,
491 XPCWrappedNativeProto* aProto)
492 : mMaybeProto(aProto), mSet(aProto->GetSet()) {
493 MOZ_ASSERT(NS_IsMainThread());
495 mIdentity = aIdentity;
496 mFlatJSObject.setFlags(FLAT_JS_OBJECT_VALID);
498 MOZ_ASSERT(mMaybeProto, "bad ctor param");
499 MOZ_ASSERT(mSet, "bad ctor param");
502 // This ctor is used if this object will NOT have a proto.
503 XPCWrappedNative::XPCWrappedNative(nsCOMPtr<nsISupports>&& aIdentity,
504 XPCWrappedNativeScope* aScope,
505 RefPtr<XPCNativeSet>&& aSet)
506 : mMaybeScope(TagScope(aScope)), mSet(std::move(aSet)) {
507 MOZ_ASSERT(NS_IsMainThread());
509 mIdentity = aIdentity;
510 mFlatJSObject.setFlags(FLAT_JS_OBJECT_VALID);
512 MOZ_ASSERT(aScope, "bad ctor param");
513 MOZ_ASSERT(mSet, "bad ctor param");
516 XPCWrappedNative::~XPCWrappedNative() { Destroy(); }
518 void XPCWrappedNative::Destroy() {
519 mScriptable = nullptr;
521 #ifdef DEBUG
522 // Check that this object has already been swept from the map.
523 XPCWrappedNativeScope* scope = GetScope();
524 if (scope) {
525 Native2WrappedNativeMap* map = scope->GetWrappedNativeMap();
526 MOZ_ASSERT(map->Find(GetIdentityObject()) != this);
528 #endif
530 if (mIdentity) {
531 XPCJSRuntime* rt = GetRuntime();
532 if (rt && rt->GetDoingFinalization()) {
533 DeferredFinalize(mIdentity.forget().take());
534 } else {
535 mIdentity = nullptr;
539 mMaybeScope = nullptr;
542 // A hack for bug 517665, increase the probability for GC.
543 // TODO: Try removing this and just using the actual size of the object.
544 static const size_t GCMemoryFactor = 2;
546 inline void XPCWrappedNative::SetFlatJSObject(JSObject* object) {
547 MOZ_ASSERT(!mFlatJSObject);
548 MOZ_ASSERT(object);
550 JS::AddAssociatedMemory(object, sizeof(*this) * GCMemoryFactor,
551 JS::MemoryUse::XPCWrappedNative);
553 mFlatJSObject = object;
554 mFlatJSObject.setFlags(FLAT_JS_OBJECT_VALID);
557 inline void XPCWrappedNative::UnsetFlatJSObject() {
558 MOZ_ASSERT(mFlatJSObject);
560 JS::RemoveAssociatedMemory(mFlatJSObject.unbarrieredGetPtr(),
561 sizeof(*this) * GCMemoryFactor,
562 JS::MemoryUse::XPCWrappedNative);
564 mFlatJSObject = nullptr;
565 mFlatJSObject.unsetFlags(FLAT_JS_OBJECT_VALID);
568 // This is factored out so that it can be called publicly.
569 // static
570 nsIXPCScriptable* XPCWrappedNative::GatherProtoScriptable(
571 nsIClassInfo* classInfo) {
572 MOZ_ASSERT(classInfo, "bad param");
574 nsCOMPtr<nsIXPCScriptable> helper;
575 nsresult rv = classInfo->GetScriptableHelper(getter_AddRefs(helper));
576 if (NS_SUCCEEDED(rv) && helper) {
577 return helper;
580 return nullptr;
583 // static
584 void XPCWrappedNative::GatherScriptable(nsISupports* aObj,
585 nsIClassInfo* aClassInfo,
586 nsIXPCScriptable** aScrProto,
587 nsIXPCScriptable** aScrWrapper) {
588 MOZ_ASSERT(!*aScrProto, "bad param");
589 MOZ_ASSERT(!*aScrWrapper, "bad param");
591 nsCOMPtr<nsIXPCScriptable> scrProto;
592 nsCOMPtr<nsIXPCScriptable> scrWrapper;
594 // Get the class scriptable helper (if present)
595 if (aClassInfo) {
596 scrProto = GatherProtoScriptable(aClassInfo);
599 // Do the same for the wrapper specific scriptable
600 scrWrapper = do_QueryInterface(aObj);
601 if (scrWrapper) {
602 // A whole series of assertions to catch bad uses of scriptable flags on
603 // the scrWrapper...
605 // Can't set WANT_PRECREATE on an instance scriptable without also
606 // setting it on the class scriptable.
607 MOZ_ASSERT_IF(scrWrapper->WantPreCreate(),
608 scrProto && scrProto->WantPreCreate());
610 // Can't set DONT_ENUM_QUERY_INTERFACE on an instance scriptable
611 // without also setting it on the class scriptable (if present).
612 MOZ_ASSERT_IF(scrWrapper->DontEnumQueryInterface() && scrProto,
613 scrProto->DontEnumQueryInterface());
615 // Can't set ALLOW_PROP_MODS_DURING_RESOLVE on an instance scriptable
616 // without also setting it on the class scriptable (if present).
617 MOZ_ASSERT_IF(scrWrapper->AllowPropModsDuringResolve() && scrProto,
618 scrProto->AllowPropModsDuringResolve());
619 } else {
620 scrWrapper = scrProto;
623 scrProto.forget(aScrProto);
624 scrWrapper.forget(aScrWrapper);
627 bool XPCWrappedNative::Init(JSContext* cx, nsIXPCScriptable* aScriptable) {
628 // Setup our scriptable...
629 MOZ_ASSERT(!mScriptable);
630 mScriptable = aScriptable;
632 // create our flatJSObject
634 const JSClass* jsclazz =
635 mScriptable ? mScriptable->GetJSClass() : &XPC_WN_NoHelper_JSClass;
637 // We should have the global jsclass flag if and only if we're a global.
638 MOZ_ASSERT_IF(mScriptable, !!mScriptable->IsGlobalObject() ==
639 !!(jsclazz->flags & JSCLASS_IS_GLOBAL));
641 MOZ_ASSERT(jsclazz && jsclazz->name && jsclazz->flags &&
642 jsclazz->getResolve() && jsclazz->hasFinalize(),
643 "bad class");
645 RootedObject protoJSObject(cx, HasProto() ? GetProto()->GetJSProtoObject()
646 : JS::GetRealmObjectPrototype(cx));
647 if (!protoJSObject) {
648 return false;
651 JSObject* object = JS_NewObjectWithGivenProto(cx, jsclazz, protoJSObject);
652 if (!object) {
653 return false;
656 SetFlatJSObject(object);
658 JS::SetObjectISupports(mFlatJSObject, this);
660 return FinishInit(cx);
663 bool XPCWrappedNative::FinishInit(JSContext* cx) {
664 // This reference will be released when mFlatJSObject is finalized.
665 // Since this reference will push the refcount to 2 it will also root
666 // mFlatJSObject;
667 MOZ_ASSERT(1 == mRefCnt, "unexpected refcount value");
668 NS_ADDREF(this);
670 return true;
673 NS_INTERFACE_MAP_BEGIN_CYCLE_COLLECTION(XPCWrappedNative)
674 NS_INTERFACE_MAP_ENTRY(nsIXPConnectWrappedNative)
675 NS_INTERFACE_MAP_ENTRY(nsIXPConnectJSObjectHolder)
676 NS_INTERFACE_MAP_ENTRY_AMBIGUOUS(nsISupports, nsIXPConnectWrappedNative)
677 NS_INTERFACE_MAP_END
679 NS_IMPL_CYCLE_COLLECTING_ADDREF(XPCWrappedNative)
681 // Release calls Destroy() immediately when the refcount drops to 0 to
682 // clear the weak references nsXPConnect has to XPCWNs and to ensure there
683 // are no pointers to dying protos.
684 NS_IMPL_CYCLE_COLLECTING_RELEASE_WITH_LAST_RELEASE(XPCWrappedNative, Destroy())
687 * Wrapped Native lifetime management is messy!
689 * - At creation we push the refcount to 2 (only one of which is owned by
690 * the native caller that caused the wrapper creation).
691 * - During the JS GC Mark phase we mark any wrapper with a refcount > 1.
692 * - The *only* thing that can make the wrapper get destroyed is the
693 * finalization of mFlatJSObject. And *that* should only happen if the only
694 * reference is the single extra (internal) reference we hold.
696 * - The wrapper has a pointer to the nsISupports 'view' of the wrapped native
697 * object i.e... mIdentity. This is held until the wrapper's refcount goes
698 * to zero and the wrapper is released, or until an expired wrapper (i.e.,
699 * one unlinked by the cycle collector) has had its JS object finalized.
701 * - The wrapper also has 'tearoffs'. It has one tearoff for each interface
702 * that is actually used on the native object. 'Used' means we have either
703 * needed to QueryInterface to verify the availability of that interface
704 * of that we've had to QueryInterface in order to actually make a call
705 * into the wrapped object via the pointer for the given interface.
707 * - Each tearoff's 'mNative' member (if non-null) indicates one reference
708 * held by our wrapper on the wrapped native for the given interface
709 * associated with the tearoff. If we release that reference then we set
710 * the tearoff's 'mNative' to null.
712 * - We use the occasion of the JavaScript GCCallback for the JSGC_MARK_END
713 * event to scan the tearoffs of all wrappers for non-null mNative members
714 * that represent unused references. We can tell that a given tearoff's
715 * mNative is unused by noting that no live XPCCallContexts hold a pointer
716 * to the tearoff.
718 * - As a time/space tradeoff we may decide to not do this scanning on
719 * *every* JavaScript GC. We *do* want to do this *sometimes* because
720 * we want to allow for wrapped native's to do their own tearoff patterns.
721 * So, we want to avoid holding references to interfaces that we don't need.
722 * At the same time, we don't want to be bracketing every call into a
723 * wrapped native object with a QueryInterface/Release pair. And we *never*
724 * make a call into the object except via the correct interface for which
725 * we've QI'd.
727 * - Each tearoff *can* have a mJSObject whose lazily resolved properties
728 * represent the methods/attributes/constants of that specific interface.
729 * This is optionally reflected into JavaScript as "foo.nsIFoo" when "foo"
730 * is the name of mFlatJSObject and "nsIFoo" is the name of the given
731 * interface associated with the tearoff. When we create the tearoff's
732 * mJSObject we set it's parent to be mFlatJSObject. This way we know that
733 * when mFlatJSObject get's collected there are no outstanding reachable
734 * tearoff mJSObjects. Note that we must clear the private of any lingering
735 * mJSObjects at this point because we have no guarentee of the *order* of
736 * finalization within a given gc cycle.
739 void XPCWrappedNative::FlatJSObjectFinalized() {
740 if (!IsValid()) {
741 return;
744 // Iterate the tearoffs and null out each of their JSObject's privates.
745 // This will keep them from trying to access their pointers to the
746 // dying tearoff object. We can safely assume that those remaining
747 // JSObjects are about to be finalized too.
749 for (XPCWrappedNativeTearOff* to = &mFirstTearOff; to;
750 to = to->GetNextTearOff()) {
751 JSObject* jso = to->GetJSObjectPreserveColor();
752 if (jso) {
753 JS::SetReservedSlot(jso, XPCWrappedNativeTearOff::TearOffSlot,
754 JS::UndefinedValue());
755 to->JSObjectFinalized();
758 // We also need to release any native pointers held...
759 RefPtr<nsISupports> native = to->TakeNative();
760 if (native && GetRuntime()) {
761 DeferredFinalize(native.forget().take());
764 to->SetInterface(nullptr);
767 nsWrapperCache* cache = nullptr;
768 CallQueryInterface(mIdentity, &cache);
769 if (cache) {
770 cache->ClearWrapper(mFlatJSObject.unbarrieredGetPtr());
773 UnsetFlatJSObject();
775 MOZ_ASSERT(mIdentity, "bad pointer!");
777 if (IsWrapperExpired()) {
778 Destroy();
781 // Note that it's not safe to touch mNativeWrapper here since it's
782 // likely that it has already been finalized.
784 Release();
787 void XPCWrappedNative::FlatJSObjectMoved(JSObject* obj, const JSObject* old) {
788 JS::AutoAssertGCCallback inCallback;
789 MOZ_ASSERT(mFlatJSObject == old);
791 nsWrapperCache* cache = nullptr;
792 CallQueryInterface(mIdentity, &cache);
793 if (cache) {
794 cache->UpdateWrapper(obj, old);
797 mFlatJSObject = obj;
800 void XPCWrappedNative::SystemIsBeingShutDown() {
801 if (!IsValid()) {
802 return;
805 // The long standing strategy is to leak some objects still held at shutdown.
806 // The general problem is that propagating release out of xpconnect at
807 // shutdown time causes a world of problems.
809 // We leak mIdentity (see above).
811 // Short circuit future finalization.
812 JS::SetObjectISupports(mFlatJSObject, nullptr);
813 UnsetFlatJSObject();
815 XPCWrappedNativeProto* proto = GetProto();
817 if (HasProto()) {
818 proto->SystemIsBeingShutDown();
821 // We don't clear mScriptable here. The destructor will do it.
823 // Cleanup the tearoffs.
824 for (XPCWrappedNativeTearOff* to = &mFirstTearOff; to;
825 to = to->GetNextTearOff()) {
826 if (JSObject* jso = to->GetJSObjectPreserveColor()) {
827 JS::SetReservedSlot(jso, XPCWrappedNativeTearOff::TearOffSlot,
828 JS::UndefinedValue());
829 to->SetJSObject(nullptr);
831 // We leak the tearoff mNative
832 // (for the same reason we leak mIdentity - see above).
833 Unused << to->TakeNative().take();
834 to->SetInterface(nullptr);
838 /***************************************************************************/
840 bool XPCWrappedNative::ExtendSet(JSContext* aCx,
841 XPCNativeInterface* aInterface) {
842 if (!mSet->HasInterface(aInterface)) {
843 XPCNativeSetKey key(mSet, aInterface);
844 RefPtr<XPCNativeSet> newSet = XPCNativeSet::GetNewOrUsed(aCx, &key);
845 if (!newSet) {
846 return false;
849 mSet = std::move(newSet);
851 return true;
854 XPCWrappedNativeTearOff* XPCWrappedNative::FindTearOff(
855 JSContext* cx, XPCNativeInterface* aInterface,
856 bool needJSObject /* = false */, nsresult* pError /* = nullptr */) {
857 nsresult rv = NS_OK;
858 XPCWrappedNativeTearOff* to;
859 XPCWrappedNativeTearOff* firstAvailable = nullptr;
861 XPCWrappedNativeTearOff* lastTearOff;
862 for (lastTearOff = to = &mFirstTearOff; to;
863 lastTearOff = to, to = to->GetNextTearOff()) {
864 if (to->GetInterface() == aInterface) {
865 if (needJSObject && !to->GetJSObjectPreserveColor()) {
866 AutoMarkingWrappedNativeTearOffPtr tearoff(cx, to);
867 bool ok = InitTearOffJSObject(cx, to);
868 // During shutdown, we don't sweep tearoffs. So make sure
869 // to unmark manually in case the auto-marker marked us.
870 // We shouldn't ever be getting here _during_ our
871 // Mark/Sweep cycle, so this should be safe.
872 to->Unmark();
873 if (!ok) {
874 to = nullptr;
875 rv = NS_ERROR_OUT_OF_MEMORY;
878 if (pError) {
879 *pError = rv;
881 return to;
883 if (!firstAvailable && to->IsAvailable()) {
884 firstAvailable = to;
888 to = firstAvailable;
890 if (!to) {
891 to = lastTearOff->AddTearOff();
895 // Scope keeps |tearoff| from leaking across the rest of the function.
896 AutoMarkingWrappedNativeTearOffPtr tearoff(cx, to);
897 rv = InitTearOff(cx, to, aInterface, needJSObject);
898 // During shutdown, we don't sweep tearoffs. So make sure to unmark
899 // manually in case the auto-marker marked us. We shouldn't ever be
900 // getting here _during_ our Mark/Sweep cycle, so this should be safe.
901 to->Unmark();
902 if (NS_FAILED(rv)) {
903 to = nullptr;
907 if (pError) {
908 *pError = rv;
910 return to;
913 XPCWrappedNativeTearOff* XPCWrappedNative::FindTearOff(JSContext* cx,
914 const nsIID& iid) {
915 RefPtr<XPCNativeInterface> iface = XPCNativeInterface::GetNewOrUsed(cx, &iid);
916 return iface ? FindTearOff(cx, iface) : nullptr;
919 nsresult XPCWrappedNative::InitTearOff(JSContext* cx,
920 XPCWrappedNativeTearOff* aTearOff,
921 XPCNativeInterface* aInterface,
922 bool needJSObject) {
923 // Determine if the object really does this interface...
925 const nsIID* iid = aInterface->GetIID();
926 nsISupports* identity = GetIdentityObject();
928 // This is an nsRefPtr instead of an nsCOMPtr because it may not be the
929 // canonical nsISupports for this object.
930 RefPtr<nsISupports> qiResult;
932 // We are about to call out to other code.
933 // So protect our intended tearoff.
935 aTearOff->SetReserved();
937 if (NS_FAILED(identity->QueryInterface(*iid, getter_AddRefs(qiResult))) ||
938 !qiResult) {
939 aTearOff->SetInterface(nullptr);
940 return NS_ERROR_NO_INTERFACE;
943 // Guard against trying to build a tearoff for a shared nsIClassInfo.
944 if (iid->Equals(NS_GET_IID(nsIClassInfo))) {
945 nsCOMPtr<nsISupports> alternate_identity(do_QueryInterface(qiResult));
946 if (alternate_identity.get() != identity) {
947 aTearOff->SetInterface(nullptr);
948 return NS_ERROR_NO_INTERFACE;
952 // Guard against trying to build a tearoff for an interface that is
953 // aggregated and is implemented as a nsIXPConnectWrappedJS using this
954 // self-same JSObject. The XBL system does this. If we mutate the set
955 // of this wrapper then we will shadow the method that XBL has added to
956 // the JSObject that it has inserted in the JS proto chain between our
957 // JSObject and our XPCWrappedNativeProto's JSObject. If we let this
958 // set mutation happen then the interface's methods will be added to
959 // our JSObject, but calls on those methods will get routed up to
960 // native code and into the wrappedJS - which will do a method lookup
961 // on *our* JSObject and find the same method and make another call
962 // into an infinite loop.
963 // see: http://bugzilla.mozilla.org/show_bug.cgi?id=96725
965 nsCOMPtr<nsIXPConnectWrappedJS> wrappedJS(do_QueryInterface(qiResult));
966 if (wrappedJS) {
967 RootedObject jso(cx, wrappedJS->GetJSObject());
968 if (jso == mFlatJSObject) {
969 // The implementing JSObject is the same as ours! Just say OK
970 // without actually extending the set.
972 // XXX It is a little cheesy to have FindTearOff return an
973 // 'empty' tearoff. But this is the centralized place to do the
974 // QI activities on the underlying object. *And* most caller to
975 // FindTearOff only look for a non-null result and ignore the
976 // actual tearoff returned. The only callers that do use the
977 // returned tearoff make sure to check for either a non-null
978 // JSObject or a matching Interface before proceeding.
979 // I think we can get away with this bit of ugliness.
981 aTearOff->SetInterface(nullptr);
982 return NS_OK;
986 if (NS_FAILED(nsXPConnect::SecurityManager()->CanCreateWrapper(
987 cx, *iid, identity, GetClassInfo()))) {
988 // the security manager vetoed. It should have set an exception.
989 aTearOff->SetInterface(nullptr);
990 return NS_ERROR_XPC_SECURITY_MANAGER_VETO;
993 // If this is not already in our set we need to extend our set.
994 // Note: we do not cache the result of the previous call to HasInterface()
995 // because we unlocked and called out in the interim and the result of the
996 // previous call might not be correct anymore.
998 if (!mSet->HasInterface(aInterface) && !ExtendSet(cx, aInterface)) {
999 aTearOff->SetInterface(nullptr);
1000 return NS_ERROR_NO_INTERFACE;
1003 aTearOff->SetInterface(aInterface);
1004 aTearOff->SetNative(qiResult);
1006 if (needJSObject && !InitTearOffJSObject(cx, aTearOff)) {
1007 return NS_ERROR_OUT_OF_MEMORY;
1010 return NS_OK;
1013 bool XPCWrappedNative::InitTearOffJSObject(JSContext* cx,
1014 XPCWrappedNativeTearOff* to) {
1015 JSObject* obj = JS_NewObject(cx, &XPC_WN_Tearoff_JSClass);
1016 if (!obj) {
1017 return false;
1020 JS::SetReservedSlot(obj, XPCWrappedNativeTearOff::TearOffSlot,
1021 JS::PrivateValue(to));
1022 to->SetJSObject(obj);
1024 JS::SetReservedSlot(obj, XPCWrappedNativeTearOff::FlatObjectSlot,
1025 JS::ObjectValue(*mFlatJSObject));
1026 return true;
1029 /***************************************************************************/
1031 static bool Throw(nsresult errNum, XPCCallContext& ccx) {
1032 XPCThrower::Throw(errNum, ccx);
1033 return false;
1036 /***************************************************************************/
1038 class MOZ_STACK_CLASS CallMethodHelper final {
1039 XPCCallContext& mCallContext;
1040 nsresult mInvokeResult;
1041 const nsXPTInterfaceInfo* const mIFaceInfo;
1042 const nsXPTMethodInfo* mMethodInfo;
1043 nsISupports* const mCallee;
1044 const uint16_t mVTableIndex;
1045 HandleId mIdxValueId;
1047 AutoTArray<nsXPTCVariant, 8> mDispatchParams;
1048 uint8_t mJSContextIndex; // TODO make const
1049 uint8_t mOptArgcIndex; // TODO make const
1051 Value* const mArgv;
1052 const uint32_t mArgc;
1054 MOZ_ALWAYS_INLINE bool GetArraySizeFromParam(const nsXPTType& type,
1055 HandleValue maybeArray,
1056 uint32_t* result);
1058 MOZ_ALWAYS_INLINE bool GetInterfaceTypeFromParam(const nsXPTType& type,
1059 nsID* result) const;
1061 MOZ_ALWAYS_INLINE bool GetOutParamSource(uint8_t paramIndex,
1062 MutableHandleValue srcp) const;
1064 MOZ_ALWAYS_INLINE bool GatherAndConvertResults();
1066 MOZ_ALWAYS_INLINE bool QueryInterfaceFastPath();
1068 nsXPTCVariant* GetDispatchParam(uint8_t paramIndex) {
1069 if (paramIndex >= mJSContextIndex) {
1070 paramIndex += 1;
1072 if (paramIndex >= mOptArgcIndex) {
1073 paramIndex += 1;
1075 return &mDispatchParams[paramIndex];
1077 const nsXPTCVariant* GetDispatchParam(uint8_t paramIndex) const {
1078 return const_cast<CallMethodHelper*>(this)->GetDispatchParam(paramIndex);
1081 MOZ_ALWAYS_INLINE bool InitializeDispatchParams();
1083 MOZ_ALWAYS_INLINE bool ConvertIndependentParams(bool* foundDependentParam);
1084 MOZ_ALWAYS_INLINE bool ConvertIndependentParam(uint8_t i);
1085 MOZ_ALWAYS_INLINE bool ConvertDependentParams();
1086 MOZ_ALWAYS_INLINE bool ConvertDependentParam(uint8_t i);
1088 MOZ_ALWAYS_INLINE nsresult Invoke();
1090 public:
1091 explicit CallMethodHelper(XPCCallContext& ccx)
1092 : mCallContext(ccx),
1093 mInvokeResult(NS_ERROR_UNEXPECTED),
1094 mIFaceInfo(ccx.GetInterface()->GetInterfaceInfo()),
1095 mMethodInfo(nullptr),
1096 mCallee(ccx.GetTearOff()->GetNative()),
1097 mVTableIndex(ccx.GetMethodIndex()),
1098 mIdxValueId(ccx.GetContext()->GetStringID(XPCJSContext::IDX_VALUE)),
1099 mJSContextIndex(UINT8_MAX),
1100 mOptArgcIndex(UINT8_MAX),
1101 mArgv(ccx.GetArgv()),
1102 mArgc(ccx.GetArgc())
1105 // Success checked later.
1106 mIFaceInfo->GetMethodInfo(mVTableIndex, &mMethodInfo);
1109 ~CallMethodHelper();
1111 MOZ_ALWAYS_INLINE bool Call();
1113 // Trace implementation so we can put our CallMethodHelper in a Rooted<T>.
1114 void trace(JSTracer* aTrc);
1117 // static
1118 bool XPCWrappedNative::CallMethod(XPCCallContext& ccx,
1119 CallMode mode /*= CALL_METHOD */) {
1120 nsresult rv = ccx.CanCallNow();
1121 if (NS_FAILED(rv)) {
1122 return Throw(rv, ccx);
1125 JS::Rooted<CallMethodHelper> helper(ccx, /* init = */ ccx);
1126 return helper.get().Call();
1129 bool CallMethodHelper::Call() {
1130 mCallContext.SetRetVal(JS::UndefinedValue());
1132 mCallContext.GetContext()->SetPendingException(nullptr);
1134 using Flags = js::ProfilingStackFrame::Flags;
1135 if (mVTableIndex == 0) {
1136 AUTO_PROFILER_LABEL_DYNAMIC_FAST(mIFaceInfo->Name(), "QueryInterface", DOM,
1137 mCallContext.GetJSContext(),
1138 uint32_t(Flags::STRING_TEMPLATE_METHOD) |
1139 uint32_t(Flags::RELEVANT_FOR_JS));
1141 return QueryInterfaceFastPath();
1144 if (!mMethodInfo) {
1145 Throw(NS_ERROR_XPC_CANT_GET_METHOD_INFO, mCallContext);
1146 return false;
1149 // Add profiler labels matching the WebIDL profiler labels,
1150 // which also use the DOM category.
1151 Flags templateFlag = Flags::STRING_TEMPLATE_METHOD;
1152 if (mMethodInfo->IsGetter()) {
1153 templateFlag = Flags::STRING_TEMPLATE_GETTER;
1155 if (mMethodInfo->IsSetter()) {
1156 templateFlag = Flags::STRING_TEMPLATE_SETTER;
1158 AUTO_PROFILER_LABEL_DYNAMIC_FAST(
1159 mIFaceInfo->Name(), mMethodInfo->NameOrDescription(), DOM,
1160 mCallContext.GetJSContext(),
1161 uint32_t(templateFlag) | uint32_t(Flags::RELEVANT_FOR_JS));
1163 if (!InitializeDispatchParams()) {
1164 return false;
1167 // Iterate through the params doing conversions of independent params only.
1168 // When we later convert the dependent params (if any) we will know that
1169 // the params upon which they depend will have already been converted -
1170 // regardless of ordering.
1171 bool foundDependentParam = false;
1172 if (!ConvertIndependentParams(&foundDependentParam)) {
1173 return false;
1176 if (foundDependentParam && !ConvertDependentParams()) {
1177 return false;
1180 mInvokeResult = Invoke();
1182 if (JS_IsExceptionPending(mCallContext)) {
1183 return false;
1186 if (NS_FAILED(mInvokeResult)) {
1187 ThrowBadResult(mInvokeResult, mCallContext);
1188 return false;
1191 return GatherAndConvertResults();
1194 CallMethodHelper::~CallMethodHelper() {
1195 for (nsXPTCVariant& param : mDispatchParams) {
1196 uint32_t arraylen = 0;
1197 if (!GetArraySizeFromParam(param.type, UndefinedHandleValue, &arraylen)) {
1198 continue;
1201 xpc::DestructValue(param.type, &param.val, arraylen);
1205 bool CallMethodHelper::GetArraySizeFromParam(const nsXPTType& type,
1206 HandleValue maybeArray,
1207 uint32_t* result) {
1208 if (type.Tag() != nsXPTType::T_LEGACY_ARRAY &&
1209 type.Tag() != nsXPTType::T_PSTRING_SIZE_IS &&
1210 type.Tag() != nsXPTType::T_PWSTRING_SIZE_IS) {
1211 *result = 0;
1212 return true;
1215 uint8_t argnum = type.ArgNum();
1216 uint32_t* lengthp = &GetDispatchParam(argnum)->val.u32;
1218 // TODO fixup the various exceptions that are thrown
1220 // If the array length wasn't passed, it might have been listed as optional.
1221 // When converting arguments from JS to C++, we pass the array as
1222 // |maybeArray|, and give ourselves the chance to infer the length. Once we
1223 // have it, we stick it in the right slot so that we can find it again when
1224 // cleaning up the params. from the array.
1225 if (argnum >= mArgc && maybeArray.isObject()) {
1226 MOZ_ASSERT(mMethodInfo->Param(argnum).IsOptional());
1227 RootedObject arrayOrNull(mCallContext, &maybeArray.toObject());
1229 bool isArray;
1230 bool ok = false;
1231 if (JS::IsArrayObject(mCallContext, maybeArray, &isArray) && isArray) {
1232 ok = JS::GetArrayLength(mCallContext, arrayOrNull, lengthp);
1233 } else if (JS_IsTypedArrayObject(&maybeArray.toObject())) {
1234 size_t len = JS_GetTypedArrayLength(&maybeArray.toObject());
1235 if (len <= UINT32_MAX) {
1236 *lengthp = len;
1237 ok = true;
1241 if (!ok) {
1242 return Throw(NS_ERROR_XPC_CANT_CONVERT_OBJECT_TO_ARRAY, mCallContext);
1246 *result = *lengthp;
1247 return true;
1250 bool CallMethodHelper::GetInterfaceTypeFromParam(const nsXPTType& type,
1251 nsID* result) const {
1252 result->Clear();
1254 const nsXPTType& inner = type.InnermostType();
1255 if (inner.Tag() == nsXPTType::T_INTERFACE) {
1256 if (!inner.GetInterface()) {
1257 return Throw(NS_ERROR_XPC_CANT_GET_PARAM_IFACE_INFO, mCallContext);
1260 *result = inner.GetInterface()->IID();
1261 } else if (inner.Tag() == nsXPTType::T_INTERFACE_IS) {
1262 const nsXPTCVariant* param = GetDispatchParam(inner.ArgNum());
1263 if (param->type.Tag() != nsXPTType::T_NSID &&
1264 param->type.Tag() != nsXPTType::T_NSIDPTR) {
1265 return Throw(NS_ERROR_UNEXPECTED, mCallContext);
1268 const void* ptr = &param->val;
1269 if (param->type.Tag() == nsXPTType::T_NSIDPTR) {
1270 ptr = *static_cast<nsID* const*>(ptr);
1273 if (!ptr) {
1274 return ThrowBadParam(NS_ERROR_XPC_CANT_GET_PARAM_IFACE_INFO,
1275 inner.ArgNum(), mCallContext);
1278 *result = *static_cast<const nsID*>(ptr);
1280 return true;
1283 bool CallMethodHelper::GetOutParamSource(uint8_t paramIndex,
1284 MutableHandleValue srcp) const {
1285 const nsXPTParamInfo& paramInfo = mMethodInfo->GetParam(paramIndex);
1286 bool isRetval = &paramInfo == mMethodInfo->GetRetval();
1288 if (paramInfo.IsOut() && !isRetval) {
1289 MOZ_ASSERT(paramIndex < mArgc || paramInfo.IsOptional(),
1290 "Expected either enough arguments or an optional argument");
1291 Value arg = paramIndex < mArgc ? mArgv[paramIndex] : JS::NullValue();
1292 if (paramIndex < mArgc) {
1293 RootedObject obj(mCallContext);
1294 if (!arg.isPrimitive()) {
1295 obj = &arg.toObject();
1297 if (!obj || !JS_GetPropertyById(mCallContext, obj, mIdxValueId, srcp)) {
1298 // Explicitly passed in unusable value for out param. Note
1299 // that if i >= mArgc we already know that |arg| is JS::NullValue(),
1300 // and that's ok.
1301 ThrowBadParam(NS_ERROR_XPC_NEED_OUT_OBJECT, paramIndex, mCallContext);
1302 return false;
1307 return true;
1310 bool CallMethodHelper::GatherAndConvertResults() {
1311 // now we iterate through the native params to gather and convert results
1312 uint8_t paramCount = mMethodInfo->GetParamCount();
1313 for (uint8_t i = 0; i < paramCount; i++) {
1314 const nsXPTParamInfo& paramInfo = mMethodInfo->GetParam(i);
1315 if (!paramInfo.IsOut()) {
1316 continue;
1319 const nsXPTType& type = paramInfo.GetType();
1320 nsXPTCVariant* dp = GetDispatchParam(i);
1321 RootedValue v(mCallContext, NullValue());
1323 uint32_t array_count = 0;
1324 nsID param_iid;
1325 if (!GetInterfaceTypeFromParam(type, &param_iid) ||
1326 !GetArraySizeFromParam(type, UndefinedHandleValue, &array_count))
1327 return false;
1329 nsresult err;
1330 if (!XPCConvert::NativeData2JS(mCallContext, &v, &dp->val, type, &param_iid,
1331 array_count, &err)) {
1332 ThrowBadParam(err, i, mCallContext);
1333 return false;
1336 if (&paramInfo == mMethodInfo->GetRetval()) {
1337 mCallContext.SetRetVal(v);
1338 } else if (i < mArgc) {
1339 // we actually assured this before doing the invoke
1340 MOZ_ASSERT(mArgv[i].isObject(), "out var is not object");
1341 RootedObject obj(mCallContext, &mArgv[i].toObject());
1342 if (!JS_SetPropertyById(mCallContext, obj, mIdxValueId, v)) {
1343 ThrowBadParam(NS_ERROR_XPC_CANT_SET_OUT_VAL, i, mCallContext);
1344 return false;
1346 } else {
1347 MOZ_ASSERT(paramInfo.IsOptional(),
1348 "Expected either enough arguments or an optional argument");
1352 return true;
1355 bool CallMethodHelper::QueryInterfaceFastPath() {
1356 MOZ_ASSERT(mVTableIndex == 0,
1357 "Using the QI fast-path for a method other than QueryInterface");
1359 if (mArgc < 1) {
1360 Throw(NS_ERROR_XPC_NOT_ENOUGH_ARGS, mCallContext);
1361 return false;
1364 if (!mArgv[0].isObject()) {
1365 ThrowBadParam(NS_ERROR_XPC_BAD_CONVERT_JS, 0, mCallContext);
1366 return false;
1369 JS::RootedValue iidarg(mCallContext, mArgv[0]);
1370 Maybe<nsID> iid = xpc::JSValue2ID(mCallContext, iidarg);
1371 if (!iid) {
1372 ThrowBadParam(NS_ERROR_XPC_BAD_CONVERT_JS, 0, mCallContext);
1373 return false;
1376 nsISupports* qiresult = nullptr;
1377 mInvokeResult = mCallee->QueryInterface(iid.ref(), (void**)&qiresult);
1379 if (NS_FAILED(mInvokeResult)) {
1380 ThrowBadResult(mInvokeResult, mCallContext);
1381 return false;
1384 RootedValue v(mCallContext, NullValue());
1385 nsresult err;
1386 bool success = XPCConvert::NativeData2JS(mCallContext, &v, &qiresult,
1387 {nsXPTType::T_INTERFACE_IS},
1388 iid.ptr(), 0, &err);
1389 NS_IF_RELEASE(qiresult);
1391 if (!success) {
1392 ThrowBadParam(err, 0, mCallContext);
1393 return false;
1396 mCallContext.SetRetVal(v);
1397 return true;
1400 bool CallMethodHelper::InitializeDispatchParams() {
1401 const uint8_t wantsOptArgc = mMethodInfo->WantsOptArgc() ? 1 : 0;
1402 const uint8_t wantsJSContext = mMethodInfo->WantsContext() ? 1 : 0;
1403 const uint8_t paramCount = mMethodInfo->GetParamCount();
1404 uint8_t requiredArgs = paramCount;
1406 // XXX ASSUMES that retval is last arg. The xpidl compiler ensures this.
1407 if (mMethodInfo->HasRetval()) {
1408 requiredArgs--;
1411 if (mArgc < requiredArgs || wantsOptArgc) {
1412 if (wantsOptArgc) {
1413 // The implicit JSContext*, if we have one, comes first.
1414 mOptArgcIndex = requiredArgs + wantsJSContext;
1417 // skip over any optional arguments
1418 while (requiredArgs &&
1419 mMethodInfo->GetParam(requiredArgs - 1).IsOptional()) {
1420 requiredArgs--;
1423 if (mArgc < requiredArgs) {
1424 Throw(NS_ERROR_XPC_NOT_ENOUGH_ARGS, mCallContext);
1425 return false;
1429 mJSContextIndex = mMethodInfo->IndexOfJSContext();
1431 // Allocate enough space in mDispatchParams up-front.
1432 // XXX(Bug 1631371) Check if this should use a fallible operation as it
1433 // pretended earlier.
1434 mDispatchParams.AppendElements(paramCount + wantsJSContext + wantsOptArgc);
1436 // Initialize each parameter to a valid state (for safe cleanup later).
1437 for (uint8_t i = 0, paramIdx = 0; i < mDispatchParams.Length(); i++) {
1438 nsXPTCVariant& dp = mDispatchParams[i];
1440 if (i == mJSContextIndex) {
1441 // Fill in the JSContext argument
1442 dp.type = nsXPTType::T_VOID;
1443 dp.val.p = mCallContext;
1444 } else if (i == mOptArgcIndex) {
1445 // Fill in the optional_argc argument
1446 dp.type = nsXPTType::T_U8;
1447 dp.val.u8 = std::min<uint32_t>(mArgc, paramCount) - requiredArgs;
1448 } else {
1449 // Initialize normal arguments.
1450 const nsXPTParamInfo& param = mMethodInfo->Param(paramIdx);
1451 dp.type = param.Type();
1452 xpc::InitializeValue(dp.type, &dp.val);
1454 // Specify the correct storage/calling semantics. This will also set
1455 // the `ptr` field to be self-referential.
1456 if (param.IsIndirect()) {
1457 dp.SetIndirect();
1460 // Advance to the next normal parameter.
1461 paramIdx++;
1465 return true;
1468 bool CallMethodHelper::ConvertIndependentParams(bool* foundDependentParam) {
1469 const uint8_t paramCount = mMethodInfo->GetParamCount();
1470 for (uint8_t i = 0; i < paramCount; i++) {
1471 const nsXPTParamInfo& paramInfo = mMethodInfo->GetParam(i);
1473 if (paramInfo.GetType().IsDependent()) {
1474 *foundDependentParam = true;
1475 } else if (!ConvertIndependentParam(i)) {
1476 return false;
1480 return true;
1483 bool CallMethodHelper::ConvertIndependentParam(uint8_t i) {
1484 const nsXPTParamInfo& paramInfo = mMethodInfo->GetParam(i);
1485 const nsXPTType& type = paramInfo.Type();
1486 nsXPTCVariant* dp = GetDispatchParam(i);
1488 // Even if there's nothing to convert, we still need to examine the
1489 // JSObject container for out-params. If it's null or otherwise invalid,
1490 // we want to know before the call, rather than after.
1492 // This is a no-op for 'in' params.
1493 RootedValue src(mCallContext);
1494 if (!GetOutParamSource(i, &src)) {
1495 return false;
1498 // All that's left to do is value conversion. Bail early if we don't need
1499 // to do that.
1500 if (!paramInfo.IsIn()) {
1501 return true;
1504 // Some types usually don't support default values, but we want to handle
1505 // the default value if IsOptional is true.
1506 if (i >= mArgc) {
1507 MOZ_ASSERT(paramInfo.IsOptional(), "missing non-optional argument!");
1508 if (type.Tag() == nsXPTType::T_NSID) {
1509 // Use a default value of the null ID for optional NSID objects.
1510 dp->ext.nsid.Clear();
1511 return true;
1514 if (type.Tag() == nsXPTType::T_ARRAY) {
1515 // Use a default value of empty array for optional Array objects.
1516 dp->ext.array.Clear();
1517 return true;
1521 // We're definitely some variety of 'in' now, so there's something to
1522 // convert. The source value for conversion depends on whether we're
1523 // dealing with an 'in' or an 'inout' parameter. 'inout' was handled above,
1524 // so all that's left is 'in'.
1525 if (!paramInfo.IsOut()) {
1526 // Handle the 'in' case.
1527 MOZ_ASSERT(i < mArgc || paramInfo.IsOptional(),
1528 "Expected either enough arguments or an optional argument");
1529 if (i < mArgc) {
1530 src = mArgv[i];
1531 } else if (type.Tag() == nsXPTType::T_JSVAL) {
1532 src.setUndefined();
1533 } else {
1534 src.setNull();
1538 nsID param_iid = {0};
1539 const nsXPTType& inner = type.InnermostType();
1540 if (inner.Tag() == nsXPTType::T_INTERFACE) {
1541 if (!inner.GetInterface()) {
1542 return ThrowBadParam(NS_ERROR_XPC_CANT_GET_PARAM_IFACE_INFO, i,
1543 mCallContext);
1545 param_iid = inner.GetInterface()->IID();
1548 nsresult err;
1549 if (!XPCConvert::JSData2Native(mCallContext, &dp->val, src, type, &param_iid,
1550 0, &err)) {
1551 ThrowBadParam(err, i, mCallContext);
1552 return false;
1555 return true;
1558 bool CallMethodHelper::ConvertDependentParams() {
1559 const uint8_t paramCount = mMethodInfo->GetParamCount();
1560 for (uint8_t i = 0; i < paramCount; i++) {
1561 const nsXPTParamInfo& paramInfo = mMethodInfo->GetParam(i);
1563 if (!paramInfo.GetType().IsDependent()) {
1564 continue;
1566 if (!ConvertDependentParam(i)) {
1567 return false;
1571 return true;
1574 bool CallMethodHelper::ConvertDependentParam(uint8_t i) {
1575 const nsXPTParamInfo& paramInfo = mMethodInfo->GetParam(i);
1576 const nsXPTType& type = paramInfo.Type();
1577 nsXPTCVariant* dp = GetDispatchParam(i);
1579 // Even if there's nothing to convert, we still need to examine the
1580 // JSObject container for out-params. If it's null or otherwise invalid,
1581 // we want to know before the call, rather than after.
1583 // This is a no-op for 'in' params.
1584 RootedValue src(mCallContext);
1585 if (!GetOutParamSource(i, &src)) {
1586 return false;
1589 // All that's left to do is value conversion. Bail early if we don't need
1590 // to do that.
1591 if (!paramInfo.IsIn()) {
1592 return true;
1595 // We're definitely some variety of 'in' now, so there's something to
1596 // convert. The source value for conversion depends on whether we're
1597 // dealing with an 'in' or an 'inout' parameter. 'inout' was handled above,
1598 // so all that's left is 'in'.
1599 if (!paramInfo.IsOut()) {
1600 // Handle the 'in' case.
1601 MOZ_ASSERT(i < mArgc || paramInfo.IsOptional(),
1602 "Expected either enough arguments or an optional argument");
1603 src = i < mArgc ? mArgv[i] : JS::NullValue();
1606 nsID param_iid;
1607 uint32_t array_count;
1608 if (!GetInterfaceTypeFromParam(type, &param_iid) ||
1609 !GetArraySizeFromParam(type, src, &array_count))
1610 return false;
1612 nsresult err;
1614 if (!XPCConvert::JSData2Native(mCallContext, &dp->val, src, type, &param_iid,
1615 array_count, &err)) {
1616 ThrowBadParam(err, i, mCallContext);
1617 return false;
1620 return true;
1623 nsresult CallMethodHelper::Invoke() {
1624 uint32_t argc = mDispatchParams.Length();
1625 nsXPTCVariant* argv = mDispatchParams.Elements();
1627 return NS_InvokeByIndex(mCallee, mVTableIndex, argc, argv);
1630 static void TraceParam(JSTracer* aTrc, void* aVal, const nsXPTType& aType,
1631 uint32_t aArrayLen = 0) {
1632 if (aType.Tag() == nsXPTType::T_JSVAL) {
1633 JS::TraceRoot(aTrc, (JS::Value*)aVal, "XPCWrappedNative::CallMethod param");
1634 } else if (aType.Tag() == nsXPTType::T_ARRAY) {
1635 auto* array = (xpt::detail::UntypedTArray*)aVal;
1636 const nsXPTType& elty = aType.ArrayElementType();
1638 for (uint32_t i = 0; i < array->Length(); ++i) {
1639 TraceParam(aTrc, elty.ElementPtr(array->Elements(), i), elty);
1641 } else if (aType.Tag() == nsXPTType::T_LEGACY_ARRAY && *(void**)aVal) {
1642 const nsXPTType& elty = aType.ArrayElementType();
1644 for (uint32_t i = 0; i < aArrayLen; ++i) {
1645 TraceParam(aTrc, elty.ElementPtr(*(void**)aVal, i), elty);
1650 void CallMethodHelper::trace(JSTracer* aTrc) {
1651 // We need to note each of our initialized parameters which contain jsvals.
1652 for (nsXPTCVariant& param : mDispatchParams) {
1653 // We only need to trace parameters which have an innermost JSVAL.
1654 if (param.type.InnermostType().Tag() != nsXPTType::T_JSVAL) {
1655 continue;
1658 uint32_t arrayLen = 0;
1659 if (!GetArraySizeFromParam(param.type, UndefinedHandleValue, &arrayLen)) {
1660 continue;
1663 TraceParam(aTrc, &param.val, param.type, arrayLen);
1667 /***************************************************************************/
1668 // interface methods
1670 JSObject* XPCWrappedNative::GetJSObject() { return GetFlatJSObject(); }
1672 XPCWrappedNative* nsIXPConnectWrappedNative::AsXPCWrappedNative() {
1673 return static_cast<XPCWrappedNative*>(this);
1676 nsresult nsIXPConnectWrappedNative::DebugDump(int16_t depth) {
1677 return AsXPCWrappedNative()->DebugDump(depth);
1680 nsresult XPCWrappedNative::DebugDump(int16_t depth) {
1681 #ifdef DEBUG
1682 depth--;
1683 XPC_LOG_ALWAYS(
1684 ("XPCWrappedNative @ %p with mRefCnt = %" PRIuPTR, this, mRefCnt.get()));
1685 XPC_LOG_INDENT();
1687 if (HasProto()) {
1688 XPCWrappedNativeProto* proto = GetProto();
1689 if (depth && proto) {
1690 proto->DebugDump(depth);
1691 } else {
1692 XPC_LOG_ALWAYS(("mMaybeProto @ %p", proto));
1694 } else
1695 XPC_LOG_ALWAYS(("Scope @ %p", GetScope()));
1697 if (depth && mSet) {
1698 mSet->DebugDump(depth);
1699 } else {
1700 XPC_LOG_ALWAYS(("mSet @ %p", mSet.get()));
1703 XPC_LOG_ALWAYS(("mFlatJSObject of %p", mFlatJSObject.unbarrieredGetPtr()));
1704 XPC_LOG_ALWAYS(("mIdentity of %p", mIdentity.get()));
1705 XPC_LOG_ALWAYS(("mScriptable @ %p", mScriptable.get()));
1707 if (depth && mScriptable) {
1708 XPC_LOG_INDENT();
1709 XPC_LOG_ALWAYS(("mFlags of %x", mScriptable->GetScriptableFlags()));
1710 XPC_LOG_ALWAYS(("mJSClass @ %p", mScriptable->GetJSClass()));
1711 XPC_LOG_OUTDENT();
1713 XPC_LOG_OUTDENT();
1714 #endif
1715 return NS_OK;
1718 /***************************************************************************/
1720 char* XPCWrappedNative::ToString(
1721 XPCWrappedNativeTearOff* to /* = nullptr */) const {
1722 #ifdef DEBUG
1723 # define FMT_ADDR " @ 0x%p"
1724 # define FMT_STR(str) str
1725 # define PARAM_ADDR(w) , w
1726 #else
1727 # define FMT_ADDR ""
1728 # define FMT_STR(str)
1729 # define PARAM_ADDR(w)
1730 #endif
1732 UniqueChars sz;
1733 UniqueChars name;
1735 nsCOMPtr<nsIXPCScriptable> scr = GetScriptable();
1736 if (scr) {
1737 name = JS_smprintf("%s", scr->GetJSClass()->name);
1739 if (to) {
1740 const char* fmt = name ? " (%s)" : "%s";
1741 name = JS_sprintf_append(std::move(name), fmt,
1742 to->GetInterface()->GetNameString());
1743 } else if (!name) {
1744 XPCNativeSet* set = GetSet();
1745 XPCNativeInterface** array = set->GetInterfaceArray();
1746 uint16_t count = set->GetInterfaceCount();
1747 MOZ_RELEASE_ASSERT(count >= 1, "Expected at least one interface");
1748 MOZ_ASSERT(*array[0]->GetIID() == NS_GET_IID(nsISupports),
1749 "The first interface must be nsISupports");
1751 // The first interface is always nsISupports, so don't print it, unless
1752 // there are no others.
1753 if (count == 1) {
1754 name = JS_sprintf_append(std::move(name), "nsISupports");
1755 } else if (count == 2) {
1756 name =
1757 JS_sprintf_append(std::move(name), "%s", array[1]->GetNameString());
1758 } else {
1759 for (uint16_t i = 1; i < count; i++) {
1760 const char* fmt = (i == 1) ? "(%s"
1761 : (i == count - 1) ? ", %s)"
1762 : ", %s";
1763 name =
1764 JS_sprintf_append(std::move(name), fmt, array[i]->GetNameString());
1769 if (!name) {
1770 return nullptr;
1772 const char* fmt = "[xpconnect wrapped %s" FMT_ADDR FMT_STR(" (native")
1773 FMT_ADDR FMT_STR(")") "]";
1774 if (scr) {
1775 fmt = "[object %s" FMT_ADDR FMT_STR(" (native") FMT_ADDR FMT_STR(")") "]";
1777 sz =
1778 JS_smprintf(fmt, name.get() PARAM_ADDR(this) PARAM_ADDR(mIdentity.get()));
1780 return sz.release();
1782 #undef FMT_ADDR
1783 #undef PARAM_ADDR
1786 /***************************************************************************/
1788 #ifdef XPC_CHECK_CLASSINFO_CLAIMS
1789 static void DEBUG_CheckClassInfoClaims(XPCWrappedNative* wrapper) {
1790 if (!wrapper || !wrapper->GetClassInfo()) {
1791 return;
1794 nsISupports* obj = wrapper->GetIdentityObject();
1795 XPCNativeSet* set = wrapper->GetSet();
1796 uint16_t count = set->GetInterfaceCount();
1797 for (uint16_t i = 0; i < count; i++) {
1798 nsIClassInfo* clsInfo = wrapper->GetClassInfo();
1799 XPCNativeInterface* iface = set->GetInterfaceAt(i);
1800 const nsXPTInterfaceInfo* info = iface->GetInterfaceInfo();
1801 nsISupports* ptr;
1803 nsresult rv = obj->QueryInterface(info->IID(), (void**)&ptr);
1804 if (NS_SUCCEEDED(rv)) {
1805 NS_RELEASE(ptr);
1806 continue;
1808 if (rv == NS_ERROR_OUT_OF_MEMORY) {
1809 continue;
1812 // Houston, We have a problem...
1814 char* className = nullptr;
1815 char* contractID = nullptr;
1816 const char* interfaceName = info->Name();
1818 clsInfo->GetContractID(&contractID);
1819 if (wrapper->GetScriptable()) {
1820 wrapper->GetScriptable()->GetClassName(&className);
1823 printf(
1824 "\n!!! Object's nsIClassInfo lies about its interfaces!!!\n"
1825 " classname: %s \n"
1826 " contractid: %s \n"
1827 " unimplemented interface name: %s\n\n",
1828 className ? className : "<unknown>",
1829 contractID ? contractID : "<unknown>", interfaceName);
1831 if (className) {
1832 free(className);
1834 if (contractID) {
1835 free(contractID);
1839 #endif