dom/bindings/BindingUtils.h

changeset 0
6474c204b198
     1.1 --- /dev/null	Thu Jan 01 00:00:00 1970 +0000
     1.2 +++ b/dom/bindings/BindingUtils.h	Wed Dec 31 06:09:35 2014 +0100
     1.3 @@ -0,0 +1,2751 @@
     1.4 +/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*-*/
     1.5 +/* vim: set ts=2 sw=2 et tw=79: */
     1.6 +/* This Source Code Form is subject to the terms of the Mozilla Public
     1.7 + * License, v. 2.0. If a copy of the MPL was not distributed with this file,
     1.8 + * You can obtain one at http://mozilla.org/MPL/2.0/. */
     1.9 +
    1.10 +#ifndef mozilla_dom_BindingUtils_h__
    1.11 +#define mozilla_dom_BindingUtils_h__
    1.12 +
    1.13 +#include "jsfriendapi.h"
    1.14 +#include "jswrapper.h"
    1.15 +#include "mozilla/ArrayUtils.h"
    1.16 +#include "mozilla/Alignment.h"
    1.17 +#include "mozilla/Array.h"
    1.18 +#include "mozilla/dom/BindingDeclarations.h"
    1.19 +#include "mozilla/dom/CallbackObject.h"
    1.20 +#include "mozilla/dom/DOMJSClass.h"
    1.21 +#include "mozilla/dom/DOMJSProxyHandler.h"
    1.22 +#include "mozilla/dom/Exceptions.h"
    1.23 +#include "mozilla/dom/NonRefcountedDOMObject.h"
    1.24 +#include "mozilla/dom/Nullable.h"
    1.25 +#include "mozilla/dom/RootedDictionary.h"
    1.26 +#include "mozilla/dom/workers/Workers.h"
    1.27 +#include "mozilla/ErrorResult.h"
    1.28 +#include "mozilla/Likely.h"
    1.29 +#include "mozilla/MemoryReporting.h"
    1.30 +#include "nsCycleCollector.h"
    1.31 +#include "nsIXPConnect.h"
    1.32 +#include "MainThreadUtils.h"
    1.33 +#include "nsISupportsImpl.h"
    1.34 +#include "qsObjectHelper.h"
    1.35 +#include "xpcpublic.h"
    1.36 +#include "nsIVariant.h"
    1.37 +#include "pldhash.h" // For PLDHashOperator
    1.38 +
    1.39 +#include "nsWrapperCacheInlines.h"
    1.40 +
    1.41 +class nsIJSID;
    1.42 +class nsPIDOMWindow;
    1.43 +
    1.44 +extern nsresult
    1.45 +xpc_qsUnwrapArgImpl(JSContext* cx, JS::Handle<JS::Value> v, const nsIID& iid, void** ppArg,
    1.46 +                    nsISupports** ppArgRef, JS::MutableHandle<JS::Value> vp);
    1.47 +
    1.48 +namespace mozilla {
    1.49 +namespace dom {
    1.50 +template<typename DataType> class MozMap;
    1.51 +
    1.52 +struct SelfRef
    1.53 +{
    1.54 +  SelfRef() : ptr(nullptr) {}
    1.55 +  explicit SelfRef(nsISupports *p) : ptr(p) {}
    1.56 +  ~SelfRef() { NS_IF_RELEASE(ptr); }
    1.57 +
    1.58 +  nsISupports* ptr;
    1.59 +};
    1.60 +
    1.61 +/** Convert a jsval to an XPCOM pointer. */
    1.62 +template <class Interface, class StrongRefType>
    1.63 +inline nsresult
    1.64 +UnwrapArg(JSContext* cx, JS::Handle<JS::Value> v, Interface** ppArg,
    1.65 +          StrongRefType** ppArgRef, JS::MutableHandle<JS::Value> vp)
    1.66 +{
    1.67 +  nsISupports* argRef = *ppArgRef;
    1.68 +  nsresult rv = xpc_qsUnwrapArgImpl(cx, v, NS_GET_TEMPLATE_IID(Interface),
    1.69 +                                    reinterpret_cast<void**>(ppArg), &argRef,
    1.70 +                                    vp);
    1.71 +  *ppArgRef = static_cast<StrongRefType*>(argRef);
    1.72 +  return rv;
    1.73 +}
    1.74 +
    1.75 +inline const ErrNum
    1.76 +GetInvalidThisErrorForMethod(bool aSecurityError)
    1.77 +{
    1.78 +  return aSecurityError ? MSG_METHOD_THIS_UNWRAPPING_DENIED :
    1.79 +                          MSG_METHOD_THIS_DOES_NOT_IMPLEMENT_INTERFACE;
    1.80 +}
    1.81 +
    1.82 +inline const ErrNum
    1.83 +GetInvalidThisErrorForGetter(bool aSecurityError)
    1.84 +{
    1.85 +  return aSecurityError ? MSG_GETTER_THIS_UNWRAPPING_DENIED :
    1.86 +                          MSG_GETTER_THIS_DOES_NOT_IMPLEMENT_INTERFACE;
    1.87 +}
    1.88 +
    1.89 +inline const ErrNum
    1.90 +GetInvalidThisErrorForSetter(bool aSecurityError)
    1.91 +{
    1.92 +  return aSecurityError ? MSG_SETTER_THIS_UNWRAPPING_DENIED :
    1.93 +                          MSG_SETTER_THIS_DOES_NOT_IMPLEMENT_INTERFACE;
    1.94 +}
    1.95 +
    1.96 +bool
    1.97 +ThrowInvalidThis(JSContext* aCx, const JS::CallArgs& aArgs,
    1.98 +                 const ErrNum aErrorNumber,
    1.99 +                 const char* aInterfaceName);
   1.100 +
   1.101 +bool
   1.102 +ThrowInvalidThis(JSContext* aCx, const JS::CallArgs& aArgs,
   1.103 +                 const ErrNum aErrorNumber,
   1.104 +                 prototypes::ID aProtoId);
   1.105 +
   1.106 +inline bool
   1.107 +ThrowMethodFailedWithDetails(JSContext* cx, ErrorResult& rv,
   1.108 +                             const char* ifaceName,
   1.109 +                             const char* memberName,
   1.110 +                             bool reportJSContentExceptions = false)
   1.111 +{
   1.112 +  if (rv.IsTypeError()) {
   1.113 +    rv.ReportTypeError(cx);
   1.114 +    return false;
   1.115 +  }
   1.116 +  if (rv.IsJSException()) {
   1.117 +    if (reportJSContentExceptions) {
   1.118 +      rv.ReportJSExceptionFromJSImplementation(cx);
   1.119 +    } else {
   1.120 +      rv.ReportJSException(cx);
   1.121 +    }
   1.122 +    return false;
   1.123 +  }
   1.124 +  if (rv.IsNotEnoughArgsError()) {
   1.125 +    rv.ReportNotEnoughArgsError(cx, ifaceName, memberName);
   1.126 +    return false;
   1.127 +  }
   1.128 +  return Throw(cx, rv.ErrorCode());
   1.129 +}
   1.130 +
   1.131 +// Returns true if the JSClass is used for DOM objects.
   1.132 +inline bool
   1.133 +IsDOMClass(const JSClass* clasp)
   1.134 +{
   1.135 +  return clasp->flags & JSCLASS_IS_DOMJSCLASS;
   1.136 +}
   1.137 +
   1.138 +inline bool
   1.139 +IsDOMClass(const js::Class* clasp)
   1.140 +{
   1.141 +  return IsDOMClass(Jsvalify(clasp));
   1.142 +}
   1.143 +
   1.144 +// Return true if the JSClass is used for non-proxy DOM objects.
   1.145 +inline bool
   1.146 +IsNonProxyDOMClass(const js::Class* clasp)
   1.147 +{
   1.148 +  return IsDOMClass(clasp) && !clasp->isProxy();
   1.149 +}
   1.150 +
   1.151 +inline bool
   1.152 +IsNonProxyDOMClass(const JSClass* clasp)
   1.153 +{
   1.154 +  return IsNonProxyDOMClass(js::Valueify(clasp));
   1.155 +}
   1.156 +
   1.157 +// Returns true if the JSClass is used for DOM interface and interface 
   1.158 +// prototype objects.
   1.159 +inline bool
   1.160 +IsDOMIfaceAndProtoClass(const JSClass* clasp)
   1.161 +{
   1.162 +  return clasp->flags & JSCLASS_IS_DOMIFACEANDPROTOJSCLASS;
   1.163 +}
   1.164 +
   1.165 +inline bool
   1.166 +IsDOMIfaceAndProtoClass(const js::Class* clasp)
   1.167 +{
   1.168 +  return IsDOMIfaceAndProtoClass(Jsvalify(clasp));
   1.169 +}
   1.170 +
   1.171 +static_assert(DOM_OBJECT_SLOT == js::PROXY_PRIVATE_SLOT,
   1.172 +              "js::PROXY_PRIVATE_SLOT doesn't match DOM_OBJECT_SLOT.  "
   1.173 +              "Expect bad things");
   1.174 +template <class T>
   1.175 +inline T*
   1.176 +UnwrapDOMObject(JSObject* obj)
   1.177 +{
   1.178 +  MOZ_ASSERT(IsDOMClass(js::GetObjectClass(obj)),
   1.179 +             "Don't pass non-DOM objects to this function");
   1.180 +
   1.181 +  JS::Value val = js::GetReservedSlot(obj, DOM_OBJECT_SLOT);
   1.182 +  return static_cast<T*>(val.toPrivate());
   1.183 +}
   1.184 +
   1.185 +inline const DOMClass*
   1.186 +GetDOMClass(JSObject* obj)
   1.187 +{
   1.188 +  const js::Class* clasp = js::GetObjectClass(obj);
   1.189 +  if (IsDOMClass(clasp)) {
   1.190 +    return &DOMJSClass::FromJSClass(clasp)->mClass;
   1.191 +  }
   1.192 +  return nullptr;
   1.193 +}
   1.194 +
   1.195 +inline nsISupports*
   1.196 +UnwrapDOMObjectToISupports(JSObject* aObject)
   1.197 +{
   1.198 +  const DOMClass* clasp = GetDOMClass(aObject);
   1.199 +  if (!clasp || !clasp->mDOMObjectIsISupports) {
   1.200 +    return nullptr;
   1.201 +  }
   1.202 + 
   1.203 +  return UnwrapDOMObject<nsISupports>(aObject);
   1.204 +}
   1.205 +
   1.206 +inline bool
   1.207 +IsDOMObject(JSObject* obj)
   1.208 +{
   1.209 +  return IsDOMClass(js::GetObjectClass(obj));
   1.210 +}
   1.211 +
   1.212 +#define UNWRAP_OBJECT(Interface, obj, value)                                 \
   1.213 +  mozilla::dom::UnwrapObject<mozilla::dom::prototypes::id::Interface,        \
   1.214 +    mozilla::dom::Interface##Binding::NativeType>(obj, value)
   1.215 +
   1.216 +// Some callers don't want to set an exception when unwrapping fails
   1.217 +// (for example, overload resolution uses unwrapping to tell what sort
   1.218 +// of thing it's looking at).
   1.219 +// U must be something that a T* can be assigned to (e.g. T* or an nsRefPtr<T>).
   1.220 +template <class T, typename U>
   1.221 +MOZ_ALWAYS_INLINE nsresult
   1.222 +UnwrapObject(JSObject* obj, U& value, prototypes::ID protoID,
   1.223 +             uint32_t protoDepth)
   1.224 +{
   1.225 +  /* First check to see whether we have a DOM object */
   1.226 +  const DOMClass* domClass = GetDOMClass(obj);
   1.227 +  if (!domClass) {
   1.228 +    /* Maybe we have a security wrapper or outer window? */
   1.229 +    if (!js::IsWrapper(obj)) {
   1.230 +      /* Not a DOM object, not a wrapper, just bail */
   1.231 +      return NS_ERROR_XPC_BAD_CONVERT_JS;
   1.232 +    }
   1.233 +
   1.234 +    obj = js::CheckedUnwrap(obj, /* stopAtOuter = */ false);
   1.235 +    if (!obj) {
   1.236 +      return NS_ERROR_XPC_SECURITY_MANAGER_VETO;
   1.237 +    }
   1.238 +    MOZ_ASSERT(!js::IsWrapper(obj));
   1.239 +    domClass = GetDOMClass(obj);
   1.240 +    if (!domClass) {
   1.241 +      /* We don't have a DOM object */
   1.242 +      return NS_ERROR_XPC_BAD_CONVERT_JS;
   1.243 +    }
   1.244 +  }
   1.245 +
   1.246 +  /* This object is a DOM object.  Double-check that it is safely
   1.247 +     castable to T by checking whether it claims to inherit from the
   1.248 +     class identified by protoID. */
   1.249 +  if (domClass->mInterfaceChain[protoDepth] == protoID) {
   1.250 +    value = UnwrapDOMObject<T>(obj);
   1.251 +    return NS_OK;
   1.252 +  }
   1.253 +
   1.254 +  /* It's the wrong sort of DOM object */
   1.255 +  return NS_ERROR_XPC_BAD_CONVERT_JS;
   1.256 +}
   1.257 +
   1.258 +template <prototypes::ID PrototypeID, class T, typename U>
   1.259 +MOZ_ALWAYS_INLINE nsresult
   1.260 +UnwrapObject(JSObject* obj, U& value)
   1.261 +{
   1.262 +  return UnwrapObject<T>(obj, value, PrototypeID,
   1.263 +                         PrototypeTraits<PrototypeID>::Depth);
   1.264 +}
   1.265 +
   1.266 +inline bool
   1.267 +IsNotDateOrRegExp(JSContext* cx, JS::Handle<JSObject*> obj)
   1.268 +{
   1.269 +  MOZ_ASSERT(obj);
   1.270 +  return !JS_ObjectIsDate(cx, obj) && !JS_ObjectIsRegExp(cx, obj);
   1.271 +}
   1.272 +
   1.273 +MOZ_ALWAYS_INLINE bool
   1.274 +IsObjectValueConvertibleToDictionary(JSContext* cx,
   1.275 +                                     JS::Handle<JS::Value> objVal)
   1.276 +{
   1.277 +  JS::Rooted<JSObject*> obj(cx, &objVal.toObject());
   1.278 +  return IsNotDateOrRegExp(cx, obj);
   1.279 +}
   1.280 +
   1.281 +MOZ_ALWAYS_INLINE bool
   1.282 +IsConvertibleToDictionary(JSContext* cx, JS::Handle<JS::Value> val)
   1.283 +{
   1.284 +  return val.isNullOrUndefined() ||
   1.285 +    (val.isObject() && IsObjectValueConvertibleToDictionary(cx, val));
   1.286 +}
   1.287 +
   1.288 +MOZ_ALWAYS_INLINE bool
   1.289 +IsConvertibleToCallbackInterface(JSContext* cx, JS::Handle<JSObject*> obj)
   1.290 +{
   1.291 +  return IsNotDateOrRegExp(cx, obj);
   1.292 +}
   1.293 +
   1.294 +// The items in the protoAndIfaceCache are indexed by the prototypes::id::ID and
   1.295 +// constructors::id::ID enums, in that order. The end of the prototype objects
   1.296 +// should be the start of the interface objects.
   1.297 +static_assert((size_t)constructors::id::_ID_Start ==
   1.298 +              (size_t)prototypes::id::_ID_Count,
   1.299 +              "Overlapping or discontiguous indexes.");
   1.300 +const size_t kProtoAndIfaceCacheCount = constructors::id::_ID_Count;
   1.301 +
   1.302 +class ProtoAndIfaceCache
   1.303 +{
   1.304 +  // The caching strategy we use depends on what sort of global we're dealing
   1.305 +  // with.  For a window-like global, we want everything to be as fast as
   1.306 +  // possible, so we use a flat array, indexed by prototype/constructor ID.
   1.307 +  // For everything else (e.g. globals for JSMs), space is more important than
   1.308 +  // speed, so we use a two-level lookup table.
   1.309 +
   1.310 +  class ArrayCache : public Array<JS::Heap<JSObject*>, kProtoAndIfaceCacheCount>
   1.311 +  {
   1.312 +  public:
   1.313 +    JSObject* EntrySlotIfExists(size_t i) {
   1.314 +      return (*this)[i];
   1.315 +    }
   1.316 +
   1.317 +    JS::Heap<JSObject*>& EntrySlotOrCreate(size_t i) {
   1.318 +      return (*this)[i];
   1.319 +    }
   1.320 +
   1.321 +    JS::Heap<JSObject*>& EntrySlotMustExist(size_t i) {
   1.322 +      MOZ_ASSERT((*this)[i]);
   1.323 +      return (*this)[i];
   1.324 +    }
   1.325 +
   1.326 +    void Trace(JSTracer* aTracer) {
   1.327 +      for (size_t i = 0; i < ArrayLength(*this); ++i) {
   1.328 +        if ((*this)[i]) {
   1.329 +          JS_CallHeapObjectTracer(aTracer, &(*this)[i], "protoAndIfaceCache[i]");
   1.330 +        }
   1.331 +      }
   1.332 +    }
   1.333 +
   1.334 +    size_t SizeOfIncludingThis(MallocSizeOf aMallocSizeOf) {
   1.335 +      return aMallocSizeOf(this);
   1.336 +    }
   1.337 +  };
   1.338 +
   1.339 +  class PageTableCache
   1.340 +  {
   1.341 +  public:
   1.342 +    PageTableCache() {
   1.343 +      memset(&mPages, 0, sizeof(mPages));
   1.344 +    }
   1.345 +
   1.346 +    ~PageTableCache() {
   1.347 +      for (size_t i = 0; i < ArrayLength(mPages); ++i) {
   1.348 +        delete mPages[i];
   1.349 +      }
   1.350 +    }
   1.351 +
   1.352 +    JSObject* EntrySlotIfExists(size_t i) {
   1.353 +      MOZ_ASSERT(i < kProtoAndIfaceCacheCount);
   1.354 +      size_t pageIndex = i / kPageSize;
   1.355 +      size_t leafIndex = i % kPageSize;
   1.356 +      Page* p = mPages[pageIndex];
   1.357 +      if (!p) {
   1.358 +        return nullptr;
   1.359 +      }
   1.360 +      return (*p)[leafIndex];
   1.361 +    }
   1.362 +
   1.363 +    JS::Heap<JSObject*>& EntrySlotOrCreate(size_t i) {
   1.364 +      MOZ_ASSERT(i < kProtoAndIfaceCacheCount);
   1.365 +      size_t pageIndex = i / kPageSize;
   1.366 +      size_t leafIndex = i % kPageSize;
   1.367 +      Page* p = mPages[pageIndex];
   1.368 +      if (!p) {
   1.369 +        p = new Page;
   1.370 +        mPages[pageIndex] = p;
   1.371 +      }
   1.372 +      return (*p)[leafIndex];
   1.373 +    }
   1.374 +
   1.375 +    JS::Heap<JSObject*>& EntrySlotMustExist(size_t i) {
   1.376 +      MOZ_ASSERT(i < kProtoAndIfaceCacheCount);
   1.377 +      size_t pageIndex = i / kPageSize;
   1.378 +      size_t leafIndex = i % kPageSize;
   1.379 +      Page* p = mPages[pageIndex];
   1.380 +      MOZ_ASSERT(p);
   1.381 +      return (*p)[leafIndex];
   1.382 +    }
   1.383 +
   1.384 +    void Trace(JSTracer* trc) {
   1.385 +      for (size_t i = 0; i < ArrayLength(mPages); ++i) {
   1.386 +        Page* p = mPages[i];
   1.387 +        if (p) {
   1.388 +          for (size_t j = 0; j < ArrayLength(*p); ++j) {
   1.389 +            if ((*p)[j]) {
   1.390 +              JS_CallHeapObjectTracer(trc, &(*p)[j], "protoAndIfaceCache[i]");
   1.391 +            }
   1.392 +          }
   1.393 +        }
   1.394 +      }
   1.395 +    }
   1.396 +
   1.397 +    size_t SizeOfIncludingThis(MallocSizeOf aMallocSizeOf) {
   1.398 +      size_t n = aMallocSizeOf(this);
   1.399 +      for (size_t i = 0; i < ArrayLength(mPages); ++i) {
   1.400 +        n += aMallocSizeOf(mPages[i]);
   1.401 +      }
   1.402 +      return n;
   1.403 +    }
   1.404 +
   1.405 +  private:
   1.406 +    static const size_t kPageSize = 16;
   1.407 +    typedef Array<JS::Heap<JSObject*>, kPageSize> Page;
   1.408 +    static const size_t kNPages = kProtoAndIfaceCacheCount / kPageSize +
   1.409 +      size_t(bool(kProtoAndIfaceCacheCount % kPageSize));
   1.410 +    Array<Page*, kNPages> mPages;
   1.411 +  };
   1.412 +
   1.413 +public:
   1.414 +  enum Kind {
   1.415 +    WindowLike,
   1.416 +    NonWindowLike
   1.417 +  };
   1.418 +
   1.419 +  ProtoAndIfaceCache(Kind aKind) : mKind(aKind) {
   1.420 +    MOZ_COUNT_CTOR(ProtoAndIfaceCache);
   1.421 +    if (aKind == WindowLike) {
   1.422 +      mArrayCache = new ArrayCache();
   1.423 +    } else {
   1.424 +      mPageTableCache = new PageTableCache();
   1.425 +    }
   1.426 +  }
   1.427 +
   1.428 +  ~ProtoAndIfaceCache() {
   1.429 +    if (mKind == WindowLike) {
   1.430 +      delete mArrayCache;
   1.431 +    } else {
   1.432 +      delete mPageTableCache;
   1.433 +    }
   1.434 +    MOZ_COUNT_DTOR(ProtoAndIfaceCache);
   1.435 +  }
   1.436 +
   1.437 +#define FORWARD_OPERATION(opName, args)              \
   1.438 +  do {                                               \
   1.439 +    if (mKind == WindowLike) {                       \
   1.440 +      return mArrayCache->opName args;               \
   1.441 +    } else {                                         \
   1.442 +      return mPageTableCache->opName args;           \
   1.443 +    }                                                \
   1.444 +  } while(0)
   1.445 +
   1.446 +  JSObject* EntrySlotIfExists(size_t i) {
   1.447 +    FORWARD_OPERATION(EntrySlotIfExists, (i));
   1.448 +  }
   1.449 +
   1.450 +  JS::Heap<JSObject*>& EntrySlotOrCreate(size_t i) {
   1.451 +    FORWARD_OPERATION(EntrySlotOrCreate, (i));
   1.452 +  }
   1.453 +
   1.454 +  JS::Heap<JSObject*>& EntrySlotMustExist(size_t i) {
   1.455 +    FORWARD_OPERATION(EntrySlotMustExist, (i));
   1.456 +  }
   1.457 +
   1.458 +  void Trace(JSTracer *aTracer) {
   1.459 +    FORWARD_OPERATION(Trace, (aTracer));
   1.460 +  }
   1.461 +
   1.462 +  size_t SizeOfIncludingThis(MallocSizeOf aMallocSizeOf) {
   1.463 +    size_t n = aMallocSizeOf(this);
   1.464 +    n += (mKind == WindowLike
   1.465 +          ? mArrayCache->SizeOfIncludingThis(aMallocSizeOf)
   1.466 +          : mPageTableCache->SizeOfIncludingThis(aMallocSizeOf));
   1.467 +    return n;
   1.468 +  }
   1.469 +#undef FORWARD_OPERATION
   1.470 +
   1.471 +private:
   1.472 +  union {
   1.473 +    ArrayCache *mArrayCache;
   1.474 +    PageTableCache *mPageTableCache;
   1.475 +  };
   1.476 +  Kind mKind;
   1.477 +};
   1.478 +
   1.479 +inline void
   1.480 +AllocateProtoAndIfaceCache(JSObject* obj, ProtoAndIfaceCache::Kind aKind)
   1.481 +{
   1.482 +  MOZ_ASSERT(js::GetObjectClass(obj)->flags & JSCLASS_DOM_GLOBAL);
   1.483 +  MOZ_ASSERT(js::GetReservedSlot(obj, DOM_PROTOTYPE_SLOT).isUndefined());
   1.484 +
   1.485 +  ProtoAndIfaceCache* protoAndIfaceCache = new ProtoAndIfaceCache(aKind);
   1.486 +
   1.487 +  js::SetReservedSlot(obj, DOM_PROTOTYPE_SLOT,
   1.488 +                      JS::PrivateValue(protoAndIfaceCache));
   1.489 +}
   1.490 +
   1.491 +inline void
   1.492 +TraceProtoAndIfaceCache(JSTracer* trc, JSObject* obj)
   1.493 +{
   1.494 +  MOZ_ASSERT(js::GetObjectClass(obj)->flags & JSCLASS_DOM_GLOBAL);
   1.495 +
   1.496 +  if (!HasProtoAndIfaceCache(obj))
   1.497 +    return;
   1.498 +  ProtoAndIfaceCache* protoAndIfaceCache = GetProtoAndIfaceCache(obj);
   1.499 +  protoAndIfaceCache->Trace(trc);
   1.500 +}
   1.501 +
   1.502 +inline void
   1.503 +DestroyProtoAndIfaceCache(JSObject* obj)
   1.504 +{
   1.505 +  MOZ_ASSERT(js::GetObjectClass(obj)->flags & JSCLASS_DOM_GLOBAL);
   1.506 +
   1.507 +  ProtoAndIfaceCache* protoAndIfaceCache = GetProtoAndIfaceCache(obj);
   1.508 +
   1.509 +  delete protoAndIfaceCache;
   1.510 +}
   1.511 +
   1.512 +/**
   1.513 + * Add constants to an object.
   1.514 + */
   1.515 +bool
   1.516 +DefineConstants(JSContext* cx, JS::Handle<JSObject*> obj,
   1.517 +                const ConstantSpec* cs);
   1.518 +
   1.519 +struct JSNativeHolder
   1.520 +{
   1.521 +  JSNative mNative;
   1.522 +  const NativePropertyHooks* mPropertyHooks;
   1.523 +};
   1.524 +
   1.525 +struct NamedConstructor
   1.526 +{
   1.527 +  const char* mName;
   1.528 +  const JSNativeHolder mHolder;
   1.529 +  unsigned mNargs;
   1.530 +};
   1.531 +
   1.532 +/*
   1.533 + * Create a DOM interface object (if constructorClass is non-null) and/or a
   1.534 + * DOM interface prototype object (if protoClass is non-null).
   1.535 + *
   1.536 + * global is used as the parent of the interface object and the interface
   1.537 + *        prototype object
   1.538 + * protoProto is the prototype to use for the interface prototype object.
   1.539 + * interfaceProto is the prototype to use for the interface object.
   1.540 + * protoClass is the JSClass to use for the interface prototype object.
   1.541 + *            This is null if we should not create an interface prototype
   1.542 + *            object.
   1.543 + * protoCache a pointer to a JSObject pointer where we should cache the
   1.544 + *            interface prototype object. This must be null if protoClass is and
   1.545 + *            vice versa.
   1.546 + * constructorClass is the JSClass to use for the interface object.
   1.547 + *                  This is null if we should not create an interface object or
   1.548 + *                  if it should be a function object.
   1.549 + * constructor holds the JSNative to back the interface object which should be a
   1.550 + *             Function, unless constructorClass is non-null in which case it is
   1.551 + *             ignored. If this is null and constructorClass is also null then
   1.552 + *             we should not create an interface object at all.
   1.553 + * ctorNargs is the length of the constructor function; 0 if no constructor
   1.554 + * constructorCache a pointer to a JSObject pointer where we should cache the
   1.555 + *                  interface object. This must be null if both constructorClass
   1.556 + *                  and constructor are null, and non-null otherwise.
   1.557 + * domClass is the DOMClass of instance objects for this class.  This can be
   1.558 + *          null if this is not a concrete proto.
   1.559 + * properties contains the methods, attributes and constants to be defined on
   1.560 + *            objects in any compartment.
   1.561 + * chromeProperties contains the methods, attributes and constants to be defined
   1.562 + *                  on objects in chrome compartments. This must be null if the
   1.563 + *                  interface doesn't have any ChromeOnly properties or if the
   1.564 + *                  object is being created in non-chrome compartment.
   1.565 + * defineOnGlobal controls whether properties should be defined on the given
   1.566 + *                global for the interface object (if any) and named
   1.567 + *                constructors (if any) for this interface.  This can be
   1.568 + *                false in situations where we want the properties to only
   1.569 + *                appear on privileged Xrays but not on the unprivileged
   1.570 + *                underlying global.
   1.571 + *
   1.572 + * At least one of protoClass, constructorClass or constructor should be
   1.573 + * non-null. If constructorClass or constructor are non-null, the resulting
   1.574 + * interface object will be defined on the given global with property name
   1.575 + * |name|, which must also be non-null.
   1.576 + */
   1.577 +void
   1.578 +CreateInterfaceObjects(JSContext* cx, JS::Handle<JSObject*> global,
   1.579 +                       JS::Handle<JSObject*> protoProto,
   1.580 +                       const JSClass* protoClass, JS::Heap<JSObject*>* protoCache,
   1.581 +                       JS::Handle<JSObject*> interfaceProto,
   1.582 +                       const JSClass* constructorClass, const JSNativeHolder* constructor,
   1.583 +                       unsigned ctorNargs, const NamedConstructor* namedConstructors,
   1.584 +                       JS::Heap<JSObject*>* constructorCache, const DOMClass* domClass,
   1.585 +                       const NativeProperties* regularProperties,
   1.586 +                       const NativeProperties* chromeOnlyProperties,
   1.587 +                       const char* name, bool defineOnGlobal);
   1.588 +
   1.589 +/*
   1.590 + * Define the unforgeable attributes on an object.
   1.591 + */
   1.592 +bool
   1.593 +DefineUnforgeableAttributes(JSContext* cx, JS::Handle<JSObject*> obj,
   1.594 +                            const Prefable<const JSPropertySpec>* props);
   1.595 +
   1.596 +bool
   1.597 +DefineWebIDLBindingPropertiesOnXPCObject(JSContext* cx,
   1.598 +                                         JS::Handle<JSObject*> obj,
   1.599 +                                         const NativeProperties* properties,
   1.600 +                                         bool defineUnforgeableAttributes);
   1.601 +
   1.602 +#ifdef _MSC_VER
   1.603 +#define HAS_MEMBER_CHECK(_name)                                           \
   1.604 +  template<typename V> static yes& Check(char (*)[(&V::_name == 0) + 1])
   1.605 +#else
   1.606 +#define HAS_MEMBER_CHECK(_name)                                           \
   1.607 +  template<typename V> static yes& Check(char (*)[sizeof(&V::_name) + 1])
   1.608 +#endif
   1.609 +
   1.610 +#define HAS_MEMBER(_name)                                                 \
   1.611 +template<typename T>                                                      \
   1.612 +class Has##_name##Member {                                                \
   1.613 +  typedef char yes[1];                                                    \
   1.614 +  typedef char no[2];                                                     \
   1.615 +  HAS_MEMBER_CHECK(_name);                                                \
   1.616 +  template<typename V> static no& Check(...);                             \
   1.617 +                                                                          \
   1.618 +public:                                                                   \
   1.619 +  static bool const Value = sizeof(Check<T>(nullptr)) == sizeof(yes);     \
   1.620 +};
   1.621 +
   1.622 +HAS_MEMBER(WrapObject)
   1.623 +
   1.624 +// HasWrapObject<T>::Value will be true if T has a WrapObject member but it's
   1.625 +// not nsWrapperCache::WrapObject.
   1.626 +template<typename T>
   1.627 +struct HasWrapObject
   1.628 +{
   1.629 +private:
   1.630 +  typedef char yes[1];
   1.631 +  typedef char no[2];
   1.632 +  typedef JSObject* (nsWrapperCache::*WrapObject)(JSContext*,
   1.633 +                                                  JS::Handle<JSObject*>);
   1.634 +  template<typename U, U> struct SFINAE;
   1.635 +  template <typename V> static no& Check(SFINAE<WrapObject, &V::WrapObject>*);
   1.636 +  template <typename V> static yes& Check(...);
   1.637 +
   1.638 +public:
   1.639 +  static bool const Value = HasWrapObjectMember<T>::Value &&
   1.640 +                            sizeof(Check<T>(nullptr)) == sizeof(yes);
   1.641 +};
   1.642 +
   1.643 +#ifdef DEBUG
   1.644 +template <class T, bool isISupports=IsBaseOf<nsISupports, T>::value>
   1.645 +struct
   1.646 +CheckWrapperCacheCast
   1.647 +{
   1.648 +  static bool Check()
   1.649 +  {
   1.650 +    return reinterpret_cast<uintptr_t>(
   1.651 +      static_cast<nsWrapperCache*>(
   1.652 +        reinterpret_cast<T*>(1))) == 1;
   1.653 +  }
   1.654 +};
   1.655 +template <class T>
   1.656 +struct
   1.657 +CheckWrapperCacheCast<T, true>
   1.658 +{
   1.659 +  static bool Check()
   1.660 +  {
   1.661 +    return true;
   1.662 +  }
   1.663 +};
   1.664 +#endif
   1.665 +
   1.666 +MOZ_ALWAYS_INLINE bool
   1.667 +CouldBeDOMBinding(void*)
   1.668 +{
   1.669 +  return true;
   1.670 +}
   1.671 +
   1.672 +MOZ_ALWAYS_INLINE bool
   1.673 +CouldBeDOMBinding(nsWrapperCache* aCache)
   1.674 +{
   1.675 +  return aCache->IsDOMBinding();
   1.676 +}
   1.677 +
   1.678 +inline bool
   1.679 +TryToOuterize(JSContext* cx, JS::MutableHandle<JS::Value> rval)
   1.680 +{
   1.681 +  if (js::IsInnerObject(&rval.toObject())) {
   1.682 +    JS::Rooted<JSObject*> obj(cx, &rval.toObject());
   1.683 +    obj = JS_ObjectToOuterObject(cx, obj);
   1.684 +    if (!obj) {
   1.685 +      return false;
   1.686 +    }
   1.687 +
   1.688 +    rval.set(JS::ObjectValue(*obj));
   1.689 +  }
   1.690 +
   1.691 +  return true;
   1.692 +}
   1.693 +
   1.694 +// Make sure to wrap the given string value into the right compartment, as
   1.695 +// needed.
   1.696 +MOZ_ALWAYS_INLINE
   1.697 +bool
   1.698 +MaybeWrapStringValue(JSContext* cx, JS::MutableHandle<JS::Value> rval)
   1.699 +{
   1.700 +  MOZ_ASSERT(rval.isString());
   1.701 +  JSString* str = rval.toString();
   1.702 +  if (JS::GetGCThingZone(str) != js::GetContextZone(cx)) {
   1.703 +    return JS_WrapValue(cx, rval);
   1.704 +  }
   1.705 +  return true;
   1.706 +}
   1.707 +
   1.708 +// Make sure to wrap the given object value into the right compartment as
   1.709 +// needed.  This will work correctly, but possibly slowly, on all objects.
   1.710 +MOZ_ALWAYS_INLINE
   1.711 +bool
   1.712 +MaybeWrapObjectValue(JSContext* cx, JS::MutableHandle<JS::Value> rval)
   1.713 +{
   1.714 +  MOZ_ASSERT(rval.isObject());
   1.715 +
   1.716 +  // Cross-compartment always requires wrapping.
   1.717 +  JSObject* obj = &rval.toObject();
   1.718 +  if (js::GetObjectCompartment(obj) != js::GetContextCompartment(cx)) {
   1.719 +    return JS_WrapValue(cx, rval);
   1.720 +  }
   1.721 +
   1.722 +  // We're same-compartment, but even then we might need to wrap
   1.723 +  // objects specially.  Check for that.
   1.724 +  if (IsDOMObject(obj)) {
   1.725 +    return TryToOuterize(cx, rval);
   1.726 +  }
   1.727 +
   1.728 +  // It's not a WebIDL object.  But it might be an XPConnect one, in which case
   1.729 +  // we may need to outerize here, so make sure to call JS_WrapValue.
   1.730 +  return JS_WrapValue(cx, rval);
   1.731 +}
   1.732 +
   1.733 +// Like MaybeWrapObjectValue, but also allows null
   1.734 +MOZ_ALWAYS_INLINE
   1.735 +bool
   1.736 +MaybeWrapObjectOrNullValue(JSContext* cx, JS::MutableHandle<JS::Value> rval)
   1.737 +{
   1.738 +  MOZ_ASSERT(rval.isObjectOrNull());
   1.739 +  if (rval.isNull()) {
   1.740 +    return true;
   1.741 +  }
   1.742 +  return MaybeWrapObjectValue(cx, rval);
   1.743 +}
   1.744 +
   1.745 +// Wrapping for objects that are known to not be DOM or XPConnect objects
   1.746 +MOZ_ALWAYS_INLINE
   1.747 +bool
   1.748 +MaybeWrapNonDOMObjectValue(JSContext* cx, JS::MutableHandle<JS::Value> rval)
   1.749 +{
   1.750 +  MOZ_ASSERT(rval.isObject());
   1.751 +  MOZ_ASSERT(!GetDOMClass(&rval.toObject()));
   1.752 +  MOZ_ASSERT(!(js::GetObjectClass(&rval.toObject())->flags &
   1.753 +               JSCLASS_PRIVATE_IS_NSISUPPORTS));
   1.754 +
   1.755 +  JSObject* obj = &rval.toObject();
   1.756 +  if (js::GetObjectCompartment(obj) == js::GetContextCompartment(cx)) {
   1.757 +    return true;
   1.758 +  }
   1.759 +  return JS_WrapValue(cx, rval);
   1.760 +}
   1.761 +
   1.762 +// Like MaybeWrapNonDOMObjectValue but allows null
   1.763 +MOZ_ALWAYS_INLINE
   1.764 +bool
   1.765 +MaybeWrapNonDOMObjectOrNullValue(JSContext* cx, JS::MutableHandle<JS::Value> rval)
   1.766 +{
   1.767 +  MOZ_ASSERT(rval.isObjectOrNull());
   1.768 +  if (rval.isNull()) {
   1.769 +    return true;
   1.770 +  }
   1.771 +  return MaybeWrapNonDOMObjectValue(cx, rval);
   1.772 +}
   1.773 +
   1.774 +// If rval is a gcthing and is not in the compartment of cx, wrap rval
   1.775 +// into the compartment of cx (typically by replacing it with an Xray or
   1.776 +// cross-compartment wrapper around the original object).
   1.777 +MOZ_ALWAYS_INLINE bool
   1.778 +MaybeWrapValue(JSContext* cx, JS::MutableHandle<JS::Value> rval)
   1.779 +{
   1.780 +  if (rval.isString()) {
   1.781 +    return MaybeWrapStringValue(cx, rval);
   1.782 +  }
   1.783 +
   1.784 +  if (!rval.isObject()) {
   1.785 +    return true;
   1.786 +  }
   1.787 +
   1.788 +  return MaybeWrapObjectValue(cx, rval);
   1.789 +}
   1.790 +
   1.791 +// Create a JSObject wrapping "value", if there isn't one already, and store it
   1.792 +// in rval.  "value" must be a concrete class that implements a
   1.793 +// GetWrapperPreserveColor() which can return its existing wrapper, if any, and
   1.794 +// a WrapObject() which will try to create a wrapper. Typically, this is done by
   1.795 +// having "value" inherit from nsWrapperCache.
   1.796 +template <class T>
   1.797 +MOZ_ALWAYS_INLINE bool
   1.798 +WrapNewBindingObject(JSContext* cx, T* value, JS::MutableHandle<JS::Value> rval)
   1.799 +{
   1.800 +  MOZ_ASSERT(value);
   1.801 +  JSObject* obj = value->GetWrapperPreserveColor();
   1.802 +  // We can get rid of this when we remove support for hasXPConnectImpls.
   1.803 +  bool couldBeDOMBinding = CouldBeDOMBinding(value);
   1.804 +  if (obj) {
   1.805 +    JS::ExposeObjectToActiveJS(obj);
   1.806 +  } else {
   1.807 +    // Inline this here while we have non-dom objects in wrapper caches.
   1.808 +    if (!couldBeDOMBinding) {
   1.809 +      return false;
   1.810 +    }
   1.811 +
   1.812 +    obj = value->WrapObject(cx);
   1.813 +    if (!obj) {
   1.814 +      // At this point, obj is null, so just return false.
   1.815 +      // Callers seem to be testing JS_IsExceptionPending(cx) to
   1.816 +      // figure out whether WrapObject() threw.
   1.817 +      return false;
   1.818 +    }
   1.819 +  }
   1.820 +
   1.821 +#ifdef DEBUG
   1.822 +  const DOMClass* clasp = GetDOMClass(obj);
   1.823 +  // clasp can be null if the cache contained a non-DOM object.
   1.824 +  if (clasp) {
   1.825 +    // Some sanity asserts about our object.  Specifically:
   1.826 +    // 1)  If our class claims we're nsISupports, we better be nsISupports
   1.827 +    //     XXXbz ideally, we could assert that reinterpret_cast to nsISupports
   1.828 +    //     does the right thing, but I don't see a way to do it.  :(
   1.829 +    // 2)  If our class doesn't claim we're nsISupports we better be
   1.830 +    //     reinterpret_castable to nsWrapperCache.
   1.831 +    MOZ_ASSERT(clasp, "What happened here?");
   1.832 +    MOZ_ASSERT_IF(clasp->mDOMObjectIsISupports, (IsBaseOf<nsISupports, T>::value));
   1.833 +    MOZ_ASSERT(CheckWrapperCacheCast<T>::Check());
   1.834 +  }
   1.835 +#endif
   1.836 +
   1.837 +  rval.set(JS::ObjectValue(*obj));
   1.838 +
   1.839 +  bool sameCompartment =
   1.840 +    js::GetObjectCompartment(obj) == js::GetContextCompartment(cx);
   1.841 +  if (sameCompartment && couldBeDOMBinding) {
   1.842 +    // We only need to outerize Window objects, so anything inheriting from
   1.843 +    // nsGlobalWindow (which inherits from EventTarget itself).
   1.844 +    return IsBaseOf<nsGlobalWindow, T>::value || IsSame<EventTarget, T>::value ?
   1.845 +           TryToOuterize(cx, rval) : true;
   1.846 +  }
   1.847 +
   1.848 +  return JS_WrapValue(cx, rval);
   1.849 +}
   1.850 +
   1.851 +// Create a JSObject wrapping "value", for cases when "value" is a
   1.852 +// non-wrapper-cached object using WebIDL bindings.  "value" must implement a
   1.853 +// WrapObject() method taking a JSContext and a scope.
   1.854 +template <class T>
   1.855 +inline bool
   1.856 +WrapNewBindingNonWrapperCachedObject(JSContext* cx,
   1.857 +                                     JS::Handle<JSObject*> scopeArg,
   1.858 +                                     T* value,
   1.859 +                                     JS::MutableHandle<JS::Value> rval)
   1.860 +{
   1.861 +  MOZ_ASSERT(value);
   1.862 +  // We try to wrap in the compartment of the underlying object of "scope"
   1.863 +  JS::Rooted<JSObject*> obj(cx);
   1.864 +  {
   1.865 +    // scope for the JSAutoCompartment so that we restore the compartment
   1.866 +    // before we call JS_WrapValue.
   1.867 +    Maybe<JSAutoCompartment> ac;
   1.868 +    // Maybe<Handle> doesn't so much work, and in any case, adding
   1.869 +    // more Maybe (one for a Rooted and one for a Handle) adds more
   1.870 +    // code (and branches!) than just adding a single rooted.
   1.871 +    JS::Rooted<JSObject*> scope(cx, scopeArg);
   1.872 +    if (js::IsWrapper(scope)) {
   1.873 +      scope = js::CheckedUnwrap(scope, /* stopAtOuter = */ false);
   1.874 +      if (!scope)
   1.875 +        return false;
   1.876 +      ac.construct(cx, scope);
   1.877 +    }
   1.878 +
   1.879 +    MOZ_ASSERT(js::IsObjectInContextCompartment(scope, cx));
   1.880 +    obj = value->WrapObject(cx);
   1.881 +  }
   1.882 +
   1.883 +  if (!obj) {
   1.884 +    return false;
   1.885 +  }
   1.886 +
   1.887 +  // We can end up here in all sorts of compartments, per above.  Make
   1.888 +  // sure to JS_WrapValue!
   1.889 +  rval.set(JS::ObjectValue(*obj));
   1.890 +  return JS_WrapValue(cx, rval);
   1.891 +}
   1.892 +
   1.893 +// Create a JSObject wrapping "value", for cases when "value" is a
   1.894 +// non-wrapper-cached owned object using WebIDL bindings.  "value" must implement a
   1.895 +// WrapObject() method taking a JSContext, a scope, and a boolean outparam that
   1.896 +// is true if the JSObject took ownership
   1.897 +template <class T>
   1.898 +inline bool
   1.899 +WrapNewBindingNonWrapperCachedOwnedObject(JSContext* cx,
   1.900 +                                          JS::Handle<JSObject*> scopeArg,
   1.901 +                                          nsAutoPtr<T>& value,
   1.902 +                                          JS::MutableHandle<JS::Value> rval)
   1.903 +{
   1.904 +  // We do a runtime check on value, because otherwise we might in
   1.905 +  // fact end up wrapping a null and invoking methods on it later.
   1.906 +  if (!value) {
   1.907 +    NS_RUNTIMEABORT("Don't try to wrap null objects");
   1.908 +  }
   1.909 +  // We try to wrap in the compartment of the underlying object of "scope"
   1.910 +  JS::Rooted<JSObject*> obj(cx);
   1.911 +  {
   1.912 +    // scope for the JSAutoCompartment so that we restore the compartment
   1.913 +    // before we call JS_WrapValue.
   1.914 +    Maybe<JSAutoCompartment> ac;
   1.915 +    // Maybe<Handle> doesn't so much work, and in any case, adding
   1.916 +    // more Maybe (one for a Rooted and one for a Handle) adds more
   1.917 +    // code (and branches!) than just adding a single rooted.
   1.918 +    JS::Rooted<JSObject*> scope(cx, scopeArg);
   1.919 +    if (js::IsWrapper(scope)) {
   1.920 +      scope = js::CheckedUnwrap(scope, /* stopAtOuter = */ false);
   1.921 +      if (!scope)
   1.922 +        return false;
   1.923 +      ac.construct(cx, scope);
   1.924 +    }
   1.925 +
   1.926 +    bool tookOwnership = false;
   1.927 +    MOZ_ASSERT(js::IsObjectInContextCompartment(scope, cx));
   1.928 +    obj = value->WrapObject(cx, &tookOwnership);
   1.929 +    MOZ_ASSERT_IF(obj, tookOwnership);
   1.930 +    if (tookOwnership) {
   1.931 +      value.forget();
   1.932 +    }
   1.933 +  }
   1.934 +
   1.935 +  if (!obj) {
   1.936 +    return false;
   1.937 +  }
   1.938 +
   1.939 +  // We can end up here in all sorts of compartments, per above.  Make
   1.940 +  // sure to JS_WrapValue!
   1.941 +  rval.set(JS::ObjectValue(*obj));
   1.942 +  return JS_WrapValue(cx, rval);
   1.943 +}
   1.944 +
   1.945 +// Helper for smart pointers (nsAutoPtr/nsRefPtr/nsCOMPtr).
   1.946 +template <template <typename> class SmartPtr, typename T>
   1.947 +inline bool
   1.948 +WrapNewBindingNonWrapperCachedObject(JSContext* cx, JS::Handle<JSObject*> scope,
   1.949 +                                     const SmartPtr<T>& value,
   1.950 +                                     JS::MutableHandle<JS::Value> rval)
   1.951 +{
   1.952 +  return WrapNewBindingNonWrapperCachedObject(cx, scope, value.get(), rval);
   1.953 +}
   1.954 +
   1.955 +// Only set allowNativeWrapper to false if you really know you need it, if in
   1.956 +// doubt use true. Setting it to false disables security wrappers.
   1.957 +bool
   1.958 +NativeInterface2JSObjectAndThrowIfFailed(JSContext* aCx,
   1.959 +                                         JS::Handle<JSObject*> aScope,
   1.960 +                                         JS::MutableHandle<JS::Value> aRetval,
   1.961 +                                         xpcObjectHelper& aHelper,
   1.962 +                                         const nsIID* aIID,
   1.963 +                                         bool aAllowNativeWrapper);
   1.964 +
   1.965 +/**
   1.966 + * A method to handle new-binding wrap failure, by possibly falling back to
   1.967 + * wrapping as a non-new-binding object.
   1.968 + */
   1.969 +template <class T>
   1.970 +MOZ_ALWAYS_INLINE bool
   1.971 +HandleNewBindingWrappingFailure(JSContext* cx, JS::Handle<JSObject*> scope,
   1.972 +                                T* value, JS::MutableHandle<JS::Value> rval)
   1.973 +{
   1.974 +  if (JS_IsExceptionPending(cx)) {
   1.975 +    return false;
   1.976 +  }
   1.977 +
   1.978 +  qsObjectHelper helper(value, GetWrapperCache(value));
   1.979 +  return NativeInterface2JSObjectAndThrowIfFailed(cx, scope, rval,
   1.980 +                                                  helper, nullptr, true);
   1.981 +}
   1.982 +
   1.983 +// Helper for calling HandleNewBindingWrappingFailure with smart pointers
   1.984 +// (nsAutoPtr/nsRefPtr/nsCOMPtr) or references.
   1.985 +HAS_MEMBER(get)
   1.986 +
   1.987 +template <class T, bool isSmartPtr=HasgetMember<T>::Value>
   1.988 +struct HandleNewBindingWrappingFailureHelper
   1.989 +{
   1.990 +  static inline bool Wrap(JSContext* cx, JS::Handle<JSObject*> scope,
   1.991 +                          const T& value, JS::MutableHandle<JS::Value> rval)
   1.992 +  {
   1.993 +    return HandleNewBindingWrappingFailure(cx, scope, value.get(), rval);
   1.994 +  }
   1.995 +};
   1.996 +
   1.997 +template <class T>
   1.998 +struct HandleNewBindingWrappingFailureHelper<T, false>
   1.999 +{
  1.1000 +  static inline bool Wrap(JSContext* cx, JS::Handle<JSObject*> scope, T& value,
  1.1001 +                          JS::MutableHandle<JS::Value> rval)
  1.1002 +  {
  1.1003 +    return HandleNewBindingWrappingFailure(cx, scope, &value, rval);
  1.1004 +  }
  1.1005 +};
  1.1006 +
  1.1007 +template<class T>
  1.1008 +inline bool
  1.1009 +HandleNewBindingWrappingFailure(JSContext* cx, JS::Handle<JSObject*> scope,
  1.1010 +                                T& value, JS::MutableHandle<JS::Value> rval)
  1.1011 +{
  1.1012 +  return HandleNewBindingWrappingFailureHelper<T>::Wrap(cx, scope, value, rval);
  1.1013 +}
  1.1014 +
  1.1015 +template<bool Fatal>
  1.1016 +inline bool
  1.1017 +EnumValueNotFound(JSContext* cx, const jschar* chars, size_t length,
  1.1018 +                  const char* type, const char* sourceDescription)
  1.1019 +{
  1.1020 +  return false;
  1.1021 +}
  1.1022 +
  1.1023 +template<>
  1.1024 +inline bool
  1.1025 +EnumValueNotFound<false>(JSContext* cx, const jschar* chars, size_t length,
  1.1026 +                         const char* type, const char* sourceDescription)
  1.1027 +{
  1.1028 +  // TODO: Log a warning to the console.
  1.1029 +  return true;
  1.1030 +}
  1.1031 +
  1.1032 +template<>
  1.1033 +inline bool
  1.1034 +EnumValueNotFound<true>(JSContext* cx, const jschar* chars, size_t length,
  1.1035 +                        const char* type, const char* sourceDescription)
  1.1036 +{
  1.1037 +  NS_LossyConvertUTF16toASCII deflated(static_cast<const char16_t*>(chars),
  1.1038 +                                       length);
  1.1039 +  return ThrowErrorMessage(cx, MSG_INVALID_ENUM_VALUE, sourceDescription,
  1.1040 +                           deflated.get(), type);
  1.1041 +}
  1.1042 +
  1.1043 +
  1.1044 +template<bool InvalidValueFatal>
  1.1045 +inline int
  1.1046 +FindEnumStringIndex(JSContext* cx, JS::Handle<JS::Value> v, const EnumEntry* values,
  1.1047 +                    const char* type, const char* sourceDescription, bool* ok)
  1.1048 +{
  1.1049 +  // JS_StringEqualsAscii is slow as molasses, so don't use it here.
  1.1050 +  JSString* str = JS::ToString(cx, v);
  1.1051 +  if (!str) {
  1.1052 +    *ok = false;
  1.1053 +    return 0;
  1.1054 +  }
  1.1055 +  JS::Anchor<JSString*> anchor(str);
  1.1056 +  size_t length;
  1.1057 +  const jschar* chars = JS_GetStringCharsAndLength(cx, str, &length);
  1.1058 +  if (!chars) {
  1.1059 +    *ok = false;
  1.1060 +    return 0;
  1.1061 +  }
  1.1062 +  int i = 0;
  1.1063 +  for (const EnumEntry* value = values; value->value; ++value, ++i) {
  1.1064 +    if (length != value->length) {
  1.1065 +      continue;
  1.1066 +    }
  1.1067 +
  1.1068 +    bool equal = true;
  1.1069 +    const char* val = value->value;
  1.1070 +    for (size_t j = 0; j != length; ++j) {
  1.1071 +      if (unsigned(val[j]) != unsigned(chars[j])) {
  1.1072 +        equal = false;
  1.1073 +        break;
  1.1074 +      }
  1.1075 +    }
  1.1076 +
  1.1077 +    if (equal) {
  1.1078 +      *ok = true;
  1.1079 +      return i;
  1.1080 +    }
  1.1081 +  }
  1.1082 +
  1.1083 +  *ok = EnumValueNotFound<InvalidValueFatal>(cx, chars, length, type,
  1.1084 +                                             sourceDescription);
  1.1085 +  return -1;
  1.1086 +}
  1.1087 +
  1.1088 +inline nsWrapperCache*
  1.1089 +GetWrapperCache(const ParentObject& aParentObject)
  1.1090 +{
  1.1091 +  return aParentObject.mWrapperCache;
  1.1092 +}
  1.1093 +
  1.1094 +template<class T>
  1.1095 +inline T*
  1.1096 +GetParentPointer(T* aObject)
  1.1097 +{
  1.1098 +  return aObject;
  1.1099 +}
  1.1100 +
  1.1101 +inline nsISupports*
  1.1102 +GetParentPointer(const ParentObject& aObject)
  1.1103 +{
  1.1104 +  return aObject.mObject;
  1.1105 +}
  1.1106 +
  1.1107 +template <typename T>
  1.1108 +inline bool
  1.1109 +GetUseXBLScope(T* aParentObject)
  1.1110 +{
  1.1111 +  return false;
  1.1112 +}
  1.1113 +
  1.1114 +inline bool
  1.1115 +GetUseXBLScope(const ParentObject& aParentObject)
  1.1116 +{
  1.1117 +  return aParentObject.mUseXBLScope;
  1.1118 +}
  1.1119 +
  1.1120 +template<class T>
  1.1121 +inline void
  1.1122 +ClearWrapper(T* p, nsWrapperCache* cache)
  1.1123 +{
  1.1124 +  cache->ClearWrapper();
  1.1125 +}
  1.1126 +
  1.1127 +template<class T>
  1.1128 +inline void
  1.1129 +ClearWrapper(T* p, void*)
  1.1130 +{
  1.1131 +  nsWrapperCache* cache;
  1.1132 +  CallQueryInterface(p, &cache);
  1.1133 +  ClearWrapper(p, cache);
  1.1134 +}
  1.1135 +
  1.1136 +// Attempt to preserve the wrapper, if any, for a Paris DOM bindings object.
  1.1137 +// Return true if we successfully preserved the wrapper, or there is no wrapper
  1.1138 +// to preserve. In the latter case we don't need to preserve the wrapper, because
  1.1139 +// the object can only be obtained by JS once, or they cannot be meaningfully
  1.1140 +// owned from the native side.
  1.1141 +//
  1.1142 +// This operation will return false only for non-nsISupports cycle-collected
  1.1143 +// objects, because we cannot determine if they are wrappercached or not.
  1.1144 +bool
  1.1145 +TryPreserveWrapper(JSObject* obj);
  1.1146 +
  1.1147 +// Can only be called with the immediate prototype of the instance object. Can
  1.1148 +// only be called on the prototype of an object known to be a DOM instance.
  1.1149 +bool
  1.1150 +InstanceClassHasProtoAtDepth(JSObject* protoObject, uint32_t protoID,
  1.1151 +                             uint32_t depth);
  1.1152 +
  1.1153 +// Only set allowNativeWrapper to false if you really know you need it, if in
  1.1154 +// doubt use true. Setting it to false disables security wrappers.
  1.1155 +bool
  1.1156 +XPCOMObjectToJsval(JSContext* cx, JS::Handle<JSObject*> scope,
  1.1157 +                   xpcObjectHelper& helper, const nsIID* iid,
  1.1158 +                   bool allowNativeWrapper, JS::MutableHandle<JS::Value> rval);
  1.1159 +
  1.1160 +// Special-cased wrapping for variants
  1.1161 +bool
  1.1162 +VariantToJsval(JSContext* aCx, nsIVariant* aVariant,
  1.1163 +               JS::MutableHandle<JS::Value> aRetval);
  1.1164 +
  1.1165 +// Wrap an object "p" which is not using WebIDL bindings yet.  This _will_
  1.1166 +// actually work on WebIDL binding objects that are wrappercached, but will be
  1.1167 +// much slower than WrapNewBindingObject.  "cache" must either be null or be the
  1.1168 +// nsWrapperCache for "p".
  1.1169 +template<class T>
  1.1170 +inline bool
  1.1171 +WrapObject(JSContext* cx, T* p, nsWrapperCache* cache, const nsIID* iid,
  1.1172 +           JS::MutableHandle<JS::Value> rval)
  1.1173 +{
  1.1174 +  if (xpc_FastGetCachedWrapper(cx, cache, rval))
  1.1175 +    return true;
  1.1176 +  qsObjectHelper helper(p, cache);
  1.1177 +  JS::Rooted<JSObject*> scope(cx, JS::CurrentGlobalOrNull(cx));
  1.1178 +  return XPCOMObjectToJsval(cx, scope, helper, iid, true, rval);
  1.1179 +}
  1.1180 +
  1.1181 +// A specialization of the above for nsIVariant, because that needs to
  1.1182 +// do something different.
  1.1183 +template<>
  1.1184 +inline bool
  1.1185 +WrapObject<nsIVariant>(JSContext* cx, nsIVariant* p,
  1.1186 +                       nsWrapperCache* cache, const nsIID* iid,
  1.1187 +                       JS::MutableHandle<JS::Value> rval)
  1.1188 +{
  1.1189 +  MOZ_ASSERT(iid);
  1.1190 +  MOZ_ASSERT(iid->Equals(NS_GET_IID(nsIVariant)));
  1.1191 +  return VariantToJsval(cx, p, rval);
  1.1192 +}
  1.1193 +
  1.1194 +// Wrap an object "p" which is not using WebIDL bindings yet.  Just like the
  1.1195 +// variant that takes an nsWrapperCache above, but will try to auto-derive the
  1.1196 +// nsWrapperCache* from "p".
  1.1197 +template<class T>
  1.1198 +inline bool
  1.1199 +WrapObject(JSContext* cx, T* p, const nsIID* iid,
  1.1200 +           JS::MutableHandle<JS::Value> rval)
  1.1201 +{
  1.1202 +  return WrapObject(cx, p, GetWrapperCache(p), iid, rval);
  1.1203 +}
  1.1204 +
  1.1205 +// Just like the WrapObject above, but without requiring you to pick which
  1.1206 +// interface you're wrapping as.  This should only be used for objects that have
  1.1207 +// classinfo, for which it doesn't matter what IID is used to wrap.
  1.1208 +template<class T>
  1.1209 +inline bool
  1.1210 +WrapObject(JSContext* cx, T* p, JS::MutableHandle<JS::Value> rval)
  1.1211 +{
  1.1212 +  return WrapObject(cx, p, nullptr, rval);
  1.1213 +}
  1.1214 +
  1.1215 +// Helper to make it possible to wrap directly out of an nsCOMPtr
  1.1216 +template<class T>
  1.1217 +inline bool
  1.1218 +WrapObject(JSContext* cx, const nsCOMPtr<T>& p,
  1.1219 +           const nsIID* iid, JS::MutableHandle<JS::Value> rval)
  1.1220 +{
  1.1221 +  return WrapObject(cx, p.get(), iid, rval);
  1.1222 +}
  1.1223 +
  1.1224 +// Helper to make it possible to wrap directly out of an nsCOMPtr
  1.1225 +template<class T>
  1.1226 +inline bool
  1.1227 +WrapObject(JSContext* cx, const nsCOMPtr<T>& p,
  1.1228 +           JS::MutableHandle<JS::Value> rval)
  1.1229 +{
  1.1230 +  return WrapObject(cx, p, nullptr, rval);
  1.1231 +}
  1.1232 +
  1.1233 +// Helper to make it possible to wrap directly out of an nsRefPtr
  1.1234 +template<class T>
  1.1235 +inline bool
  1.1236 +WrapObject(JSContext* cx, const nsRefPtr<T>& p,
  1.1237 +           const nsIID* iid, JS::MutableHandle<JS::Value> rval)
  1.1238 +{
  1.1239 +  return WrapObject(cx, p.get(), iid, rval);
  1.1240 +}
  1.1241 +
  1.1242 +// Helper to make it possible to wrap directly out of an nsRefPtr
  1.1243 +template<class T>
  1.1244 +inline bool
  1.1245 +WrapObject(JSContext* cx, const nsRefPtr<T>& p,
  1.1246 +           JS::MutableHandle<JS::Value> rval)
  1.1247 +{
  1.1248 +  return WrapObject(cx, p, nullptr, rval);
  1.1249 +}
  1.1250 +
  1.1251 +// Specialization to make it easy to use WrapObject in codegen.
  1.1252 +template<>
  1.1253 +inline bool
  1.1254 +WrapObject<JSObject>(JSContext* cx, JSObject* p,
  1.1255 +                     JS::MutableHandle<JS::Value> rval)
  1.1256 +{
  1.1257 +  rval.set(JS::ObjectOrNullValue(p));
  1.1258 +  return true;
  1.1259 +}
  1.1260 +
  1.1261 +inline bool
  1.1262 +WrapObject(JSContext* cx, JSObject& p, JS::MutableHandle<JS::Value> rval)
  1.1263 +{
  1.1264 +  rval.set(JS::ObjectValue(p));
  1.1265 +  return true;
  1.1266 +}
  1.1267 +
  1.1268 +// Given an object "p" that inherits from nsISupports, wrap it and return the
  1.1269 +// result.  Null is returned on wrapping failure.  This is somewhat similar to
  1.1270 +// WrapObject() above, but does NOT allow Xrays around the result, since we
  1.1271 +// don't want those for our parent object.
  1.1272 +template<typename T>
  1.1273 +static inline JSObject*
  1.1274 +WrapNativeISupportsParent(JSContext* cx, T* p, nsWrapperCache* cache)
  1.1275 +{
  1.1276 +  qsObjectHelper helper(ToSupports(p), cache);
  1.1277 +  JS::Rooted<JSObject*> scope(cx, JS::CurrentGlobalOrNull(cx));
  1.1278 +  JS::Rooted<JS::Value> v(cx);
  1.1279 +  return XPCOMObjectToJsval(cx, scope, helper, nullptr, false, &v) ?
  1.1280 +         v.toObjectOrNull() :
  1.1281 +         nullptr;
  1.1282 +}
  1.1283 +
  1.1284 +
  1.1285 +// Fallback for when our parent is not a WebIDL binding object.
  1.1286 +template<typename T, bool isISupports=IsBaseOf<nsISupports, T>::value>
  1.1287 +struct WrapNativeParentFallback
  1.1288 +{
  1.1289 +  static inline JSObject* Wrap(JSContext* cx, T* parent, nsWrapperCache* cache)
  1.1290 +  {
  1.1291 +    return nullptr;
  1.1292 +  }
  1.1293 +};
  1.1294 +
  1.1295 +// Fallback for when our parent is not a WebIDL binding object but _is_ an
  1.1296 +// nsISupports object.
  1.1297 +template<typename T >
  1.1298 +struct WrapNativeParentFallback<T, true >
  1.1299 +{
  1.1300 +  static inline JSObject* Wrap(JSContext* cx, T* parent, nsWrapperCache* cache)
  1.1301 +  {
  1.1302 +    return WrapNativeISupportsParent(cx, parent, cache);
  1.1303 +  }
  1.1304 +};
  1.1305 +
  1.1306 +// Wrapping of our native parent, for cases when it's a WebIDL object (though
  1.1307 +// possibly preffed off).
  1.1308 +template<typename T, bool hasWrapObject=HasWrapObject<T>::Value >
  1.1309 +struct WrapNativeParentHelper
  1.1310 +{
  1.1311 +  static inline JSObject* Wrap(JSContext* cx, T* parent, nsWrapperCache* cache)
  1.1312 +  {
  1.1313 +    MOZ_ASSERT(cache);
  1.1314 +
  1.1315 +    JSObject* obj;
  1.1316 +    if ((obj = cache->GetWrapper())) {
  1.1317 +      return obj;
  1.1318 +    }
  1.1319 +
  1.1320 +    // Inline this here while we have non-dom objects in wrapper caches.
  1.1321 +    if (!CouldBeDOMBinding(parent)) {
  1.1322 +      obj = WrapNativeParentFallback<T>::Wrap(cx, parent, cache);
  1.1323 +    } else {
  1.1324 +      obj = parent->WrapObject(cx);
  1.1325 +    }
  1.1326 +
  1.1327 +    return obj;
  1.1328 +  }
  1.1329 +};
  1.1330 +
  1.1331 +// Wrapping of our native parent, for cases when it's not a WebIDL object.  In
  1.1332 +// this case it must be nsISupports.
  1.1333 +template<typename T>
  1.1334 +struct WrapNativeParentHelper<T, false >
  1.1335 +{
  1.1336 +  static inline JSObject* Wrap(JSContext* cx, T* parent, nsWrapperCache* cache)
  1.1337 +  {
  1.1338 +    JSObject* obj;
  1.1339 +    if (cache && (obj = cache->GetWrapper())) {
  1.1340 +#ifdef DEBUG
  1.1341 +      NS_ASSERTION(WrapNativeISupportsParent(cx, parent, cache) == obj,
  1.1342 +                   "Unexpected object in nsWrapperCache");
  1.1343 +#endif
  1.1344 +      return obj;
  1.1345 +    }
  1.1346 +
  1.1347 +    return WrapNativeISupportsParent(cx, parent, cache);
  1.1348 +  }
  1.1349 +};
  1.1350 +
  1.1351 +// Wrapping of our native parent.
  1.1352 +template<typename T>
  1.1353 +static inline JSObject*
  1.1354 +WrapNativeParent(JSContext* cx, T* p, nsWrapperCache* cache,
  1.1355 +                 bool useXBLScope = false)
  1.1356 +{
  1.1357 +  if (!p) {
  1.1358 +    return JS::CurrentGlobalOrNull(cx);
  1.1359 +  }
  1.1360 +
  1.1361 +  JSObject* parent = WrapNativeParentHelper<T>::Wrap(cx, p, cache);
  1.1362 +  if (!useXBLScope) {
  1.1363 +    return parent;
  1.1364 +  }
  1.1365 +
  1.1366 +  // If useXBLScope is true, it means that the canonical reflector for this
  1.1367 +  // native object should live in the XBL scope.
  1.1368 +  if (xpc::IsInXBLScope(parent)) {
  1.1369 +    return parent;
  1.1370 +  }
  1.1371 +  JS::Rooted<JSObject*> rootedParent(cx, parent);
  1.1372 +  JS::Rooted<JSObject*> xblScope(cx, xpc::GetXBLScope(cx, rootedParent));
  1.1373 +  NS_ENSURE_TRUE(xblScope, nullptr);
  1.1374 +  JSAutoCompartment ac(cx, xblScope);
  1.1375 +  if (NS_WARN_IF(!JS_WrapObject(cx, &rootedParent))) {
  1.1376 +    return nullptr;
  1.1377 +  }
  1.1378 +
  1.1379 +  return rootedParent;
  1.1380 +}
  1.1381 +
  1.1382 +// Wrapping of our native parent, when we don't want to explicitly pass in
  1.1383 +// things like the nsWrapperCache for it.
  1.1384 +template<typename T>
  1.1385 +static inline JSObject*
  1.1386 +WrapNativeParent(JSContext* cx, const T& p)
  1.1387 +{
  1.1388 +  return WrapNativeParent(cx, GetParentPointer(p), GetWrapperCache(p), GetUseXBLScope(p));
  1.1389 +}
  1.1390 +
  1.1391 +// A way to differentiate between nodes, which use the parent object
  1.1392 +// returned by native->GetParentObject(), and all other objects, which
  1.1393 +// just use the parent's global.
  1.1394 +static inline JSObject*
  1.1395 +GetRealParentObject(void* aParent, JSObject* aParentObject)
  1.1396 +{
  1.1397 +  return aParentObject ?
  1.1398 +    js::GetGlobalForObjectCrossCompartment(aParentObject) : nullptr;
  1.1399 +}
  1.1400 +
  1.1401 +static inline JSObject*
  1.1402 +GetRealParentObject(Element* aParent, JSObject* aParentObject)
  1.1403 +{
  1.1404 +  return aParentObject;
  1.1405 +}
  1.1406 +
  1.1407 +HAS_MEMBER(GetParentObject)
  1.1408 +
  1.1409 +template<typename T, bool WrapperCached=HasGetParentObjectMember<T>::Value>
  1.1410 +struct GetParentObject
  1.1411 +{
  1.1412 +  static JSObject* Get(JSContext* cx, JS::Handle<JSObject*> obj)
  1.1413 +  {
  1.1414 +    MOZ_ASSERT(js::IsObjectInContextCompartment(obj, cx));
  1.1415 +    T* native = UnwrapDOMObject<T>(obj);
  1.1416 +    return
  1.1417 +      GetRealParentObject(native,
  1.1418 +                          WrapNativeParent(cx, native->GetParentObject()));
  1.1419 +  }
  1.1420 +};
  1.1421 +
  1.1422 +template<typename T>
  1.1423 +struct GetParentObject<T, false>
  1.1424 +{
  1.1425 +  static JSObject* Get(JSContext* cx, JS::Handle<JSObject*> obj)
  1.1426 +  {
  1.1427 +    MOZ_CRASH();
  1.1428 +    return nullptr;
  1.1429 +  }
  1.1430 +};
  1.1431 +
  1.1432 +MOZ_ALWAYS_INLINE
  1.1433 +JSObject* GetJSObjectFromCallback(CallbackObject* callback)
  1.1434 +{
  1.1435 +  return callback->Callback();
  1.1436 +}
  1.1437 +
  1.1438 +MOZ_ALWAYS_INLINE
  1.1439 +JSObject* GetJSObjectFromCallback(void* noncallback)
  1.1440 +{
  1.1441 +  return nullptr;
  1.1442 +}
  1.1443 +
  1.1444 +template<typename T>
  1.1445 +static inline JSObject*
  1.1446 +WrapCallThisObject(JSContext* cx, const T& p)
  1.1447 +{
  1.1448 +  // Callbacks are nsISupports, so WrapNativeParent will just happily wrap them
  1.1449 +  // up as an nsISupports XPCWrappedNative... which is not at all what we want.
  1.1450 +  // So we need to special-case them.
  1.1451 +  JS::Rooted<JSObject*> obj(cx, GetJSObjectFromCallback(p));
  1.1452 +  if (!obj) {
  1.1453 +    // WrapNativeParent is a bit of a Swiss army knife that will
  1.1454 +    // wrap anything for us.
  1.1455 +    obj = WrapNativeParent(cx, p);
  1.1456 +    if (!obj) {
  1.1457 +      return nullptr;
  1.1458 +    }
  1.1459 +  }
  1.1460 +
  1.1461 +  // But all that won't necessarily put things in the compartment of cx.
  1.1462 +  if (!JS_WrapObject(cx, &obj)) {
  1.1463 +    return nullptr;
  1.1464 +  }
  1.1465 +
  1.1466 +  return obj;
  1.1467 +}
  1.1468 +
  1.1469 +/*
  1.1470 + * This specialized function simply wraps a JS::Rooted<> since
  1.1471 + * WrapNativeParent() is not applicable for JS objects.
  1.1472 + */
  1.1473 +template<>
  1.1474 +inline JSObject*
  1.1475 +WrapCallThisObject<JS::Rooted<JSObject*>>(JSContext* cx,
  1.1476 +                                          const JS::Rooted<JSObject*>& p)
  1.1477 +{
  1.1478 +  JS::Rooted<JSObject*> obj(cx, p);
  1.1479 +
  1.1480 +  if (!JS_WrapObject(cx, &obj)) {
  1.1481 +    return nullptr;
  1.1482 +  }
  1.1483 +
  1.1484 +  return obj;
  1.1485 +}
  1.1486 +
  1.1487 +// Helper for calling WrapNewBindingObject with smart pointers
  1.1488 +// (nsAutoPtr/nsRefPtr/nsCOMPtr) or references.
  1.1489 +template <class T, bool isSmartPtr=HasgetMember<T>::Value>
  1.1490 +struct WrapNewBindingObjectHelper
  1.1491 +{
  1.1492 +  static inline bool Wrap(JSContext* cx, const T& value,
  1.1493 +                          JS::MutableHandle<JS::Value> rval)
  1.1494 +  {
  1.1495 +    return WrapNewBindingObject(cx, value.get(), rval);
  1.1496 +  }
  1.1497 +};
  1.1498 +
  1.1499 +template <class T>
  1.1500 +struct WrapNewBindingObjectHelper<T, false>
  1.1501 +{
  1.1502 +  static inline bool Wrap(JSContext* cx, T& value,
  1.1503 +                          JS::MutableHandle<JS::Value> rval)
  1.1504 +  {
  1.1505 +    return WrapNewBindingObject(cx, &value, rval);
  1.1506 +  }
  1.1507 +};
  1.1508 +
  1.1509 +template<class T>
  1.1510 +inline bool
  1.1511 +WrapNewBindingObject(JSContext* cx, T& value, JS::MutableHandle<JS::Value> rval)
  1.1512 +{
  1.1513 +  return WrapNewBindingObjectHelper<T>::Wrap(cx, value, rval);
  1.1514 +}
  1.1515 +
  1.1516 +// We need this version of WrapNewBindingObject for codegen, so it'll have the
  1.1517 +// same signature as WrapNewBindingNonWrapperCachedObject and
  1.1518 +// WrapNewBindingNonWrapperCachedOwnedObject, which still need the scope.
  1.1519 +template<class T>
  1.1520 +inline bool
  1.1521 +WrapNewBindingObject(JSContext* cx, JS::Handle<JSObject*> scope, T& value,
  1.1522 +                     JS::MutableHandle<JS::Value> rval)
  1.1523 +{
  1.1524 +  return WrapNewBindingObject(cx, value, rval);
  1.1525 +}
  1.1526 +
  1.1527 +template <class T>
  1.1528 +inline JSObject*
  1.1529 +GetCallbackFromCallbackObject(T* aObj)
  1.1530 +{
  1.1531 +  return aObj->Callback();
  1.1532 +}
  1.1533 +
  1.1534 +// Helper for getting the callback JSObject* of a smart ptr around a
  1.1535 +// CallbackObject or a reference to a CallbackObject or something like
  1.1536 +// that.
  1.1537 +template <class T, bool isSmartPtr=HasgetMember<T>::Value>
  1.1538 +struct GetCallbackFromCallbackObjectHelper
  1.1539 +{
  1.1540 +  static inline JSObject* Get(const T& aObj)
  1.1541 +  {
  1.1542 +    return GetCallbackFromCallbackObject(aObj.get());
  1.1543 +  }
  1.1544 +};
  1.1545 +
  1.1546 +template <class T>
  1.1547 +struct GetCallbackFromCallbackObjectHelper<T, false>
  1.1548 +{
  1.1549 +  static inline JSObject* Get(T& aObj)
  1.1550 +  {
  1.1551 +    return GetCallbackFromCallbackObject(&aObj);
  1.1552 +  }
  1.1553 +};
  1.1554 +
  1.1555 +template<class T>
  1.1556 +inline JSObject*
  1.1557 +GetCallbackFromCallbackObject(T& aObj)
  1.1558 +{
  1.1559 +  return GetCallbackFromCallbackObjectHelper<T>::Get(aObj);
  1.1560 +}
  1.1561 +
  1.1562 +static inline bool
  1.1563 +InternJSString(JSContext* cx, jsid& id, const char* chars)
  1.1564 +{
  1.1565 +  if (JSString *str = ::JS_InternString(cx, chars)) {
  1.1566 +    id = INTERNED_STRING_TO_JSID(cx, str);
  1.1567 +    return true;
  1.1568 +  }
  1.1569 +  return false;
  1.1570 +}
  1.1571 +
  1.1572 +// Spec needs a name property
  1.1573 +template <typename Spec>
  1.1574 +static bool
  1.1575 +InitIds(JSContext* cx, const Prefable<Spec>* prefableSpecs, jsid* ids)
  1.1576 +{
  1.1577 +  MOZ_ASSERT(prefableSpecs);
  1.1578 +  MOZ_ASSERT(prefableSpecs->specs);
  1.1579 +  do {
  1.1580 +    // We ignore whether the set of ids is enabled and just intern all the IDs,
  1.1581 +    // because this is only done once per application runtime.
  1.1582 +    Spec* spec = prefableSpecs->specs;
  1.1583 +    do {
  1.1584 +      if (!InternJSString(cx, *ids, spec->name)) {
  1.1585 +        return false;
  1.1586 +      }
  1.1587 +    } while (++ids, (++spec)->name);
  1.1588 +
  1.1589 +    // We ran out of ids for that pref.  Put a JSID_VOID in on the id
  1.1590 +    // corresponding to the list terminator for the pref.
  1.1591 +    *ids = JSID_VOID;
  1.1592 +    ++ids;
  1.1593 +  } while ((++prefableSpecs)->specs);
  1.1594 +
  1.1595 +  return true;
  1.1596 +}
  1.1597 +
  1.1598 +bool
  1.1599 +QueryInterface(JSContext* cx, unsigned argc, JS::Value* vp);
  1.1600 +
  1.1601 +template <class T>
  1.1602 +struct
  1.1603 +WantsQueryInterface
  1.1604 +{
  1.1605 +  static_assert(IsBaseOf<nsISupports, T>::value,
  1.1606 +                "QueryInterface can't work without an nsISupports.");
  1.1607 +  static bool Enabled(JSContext* aCx, JSObject* aGlobal)
  1.1608 +  {
  1.1609 +    return NS_IsMainThread() && IsChromeOrXBL(aCx, aGlobal);
  1.1610 +  }
  1.1611 +};
  1.1612 +
  1.1613 +void
  1.1614 +GetInterfaceImpl(JSContext* aCx, nsIInterfaceRequestor* aRequestor,
  1.1615 +                 nsWrapperCache* aCache, nsIJSID* aIID,
  1.1616 +                 JS::MutableHandle<JS::Value> aRetval, ErrorResult& aError);
  1.1617 +
  1.1618 +template<class T>
  1.1619 +void
  1.1620 +GetInterface(JSContext* aCx, T* aThis, nsIJSID* aIID,
  1.1621 +             JS::MutableHandle<JS::Value> aRetval, ErrorResult& aError)
  1.1622 +{
  1.1623 +  GetInterfaceImpl(aCx, aThis, aThis, aIID, aRetval, aError);
  1.1624 +}
  1.1625 +
  1.1626 +bool
  1.1627 +ThrowingConstructor(JSContext* cx, unsigned argc, JS::Value* vp);
  1.1628 +
  1.1629 +bool
  1.1630 +ThrowConstructorWithoutNew(JSContext* cx, const char* name);
  1.1631 +
  1.1632 +// vp is allowed to be null; in that case no get will be attempted,
  1.1633 +// and *found will simply indicate whether the property exists.
  1.1634 +bool
  1.1635 +GetPropertyOnPrototype(JSContext* cx, JS::Handle<JSObject*> proxy,
  1.1636 +                       JS::Handle<jsid> id, bool* found,
  1.1637 +                       JS::Value* vp);
  1.1638 +
  1.1639 +bool
  1.1640 +HasPropertyOnPrototype(JSContext* cx, JS::Handle<JSObject*> proxy,
  1.1641 +                       JS::Handle<jsid> id);
  1.1642 +
  1.1643 +
  1.1644 +// Append the property names in "names" to "props". If
  1.1645 +// shadowPrototypeProperties is false then skip properties that are also
  1.1646 +// present on the proto chain of proxy.  If shadowPrototypeProperties is true,
  1.1647 +// then the "proxy" argument is ignored.
  1.1648 +bool
  1.1649 +AppendNamedPropertyIds(JSContext* cx, JS::Handle<JSObject*> proxy,
  1.1650 +                       nsTArray<nsString>& names,
  1.1651 +                       bool shadowPrototypeProperties, JS::AutoIdVector& props);
  1.1652 +
  1.1653 +namespace binding_detail {
  1.1654 +
  1.1655 +// A struct that has the same layout as an nsDependentString but much
  1.1656 +// faster constructor and destructor behavior
  1.1657 +struct FakeDependentString {
  1.1658 +  FakeDependentString() :
  1.1659 +    mFlags(nsDependentString::F_TERMINATED)
  1.1660 +  {
  1.1661 +  }
  1.1662 +
  1.1663 +  void SetData(const nsDependentString::char_type* aData,
  1.1664 +               nsDependentString::size_type aLength) {
  1.1665 +    MOZ_ASSERT(mFlags == nsDependentString::F_TERMINATED);
  1.1666 +    mData = aData;
  1.1667 +    mLength = aLength;
  1.1668 +  }
  1.1669 +
  1.1670 +  void Truncate() {
  1.1671 +    mData = nsDependentString::char_traits::sEmptyBuffer;
  1.1672 +    mLength = 0;
  1.1673 +  }
  1.1674 +
  1.1675 +  void SetNull() {
  1.1676 +    Truncate();
  1.1677 +    mFlags |= nsDependentString::F_VOIDED;
  1.1678 +  }
  1.1679 +
  1.1680 +  const nsDependentString::char_type* Data() const
  1.1681 +  {
  1.1682 +    return mData;
  1.1683 +  }
  1.1684 +
  1.1685 +  nsDependentString::size_type Length() const
  1.1686 +  {
  1.1687 +    return mLength;
  1.1688 +  }
  1.1689 +
  1.1690 +  // If this ever changes, change the corresponding code in the
  1.1691 +  // Optional<nsAString> specialization as well.
  1.1692 +  const nsAString* ToAStringPtr() const {
  1.1693 +    return reinterpret_cast<const nsDependentString*>(this);
  1.1694 +  }
  1.1695 +
  1.1696 +  nsAString* ToAStringPtr() {
  1.1697 +    return reinterpret_cast<nsDependentString*>(this);
  1.1698 +  }
  1.1699 +
  1.1700 +  operator const nsAString& () const {
  1.1701 +    return *reinterpret_cast<const nsDependentString*>(this);
  1.1702 +  }
  1.1703 +
  1.1704 +private:
  1.1705 +  const nsDependentString::char_type* mData;
  1.1706 +  nsDependentString::size_type mLength;
  1.1707 +  uint32_t mFlags;
  1.1708 +
  1.1709 +  // A class to use for our static asserts to ensure our object layout
  1.1710 +  // matches that of nsDependentString.
  1.1711 +  class DependentStringAsserter;
  1.1712 +  friend class DependentStringAsserter;
  1.1713 +
  1.1714 +  class DepedentStringAsserter : public nsDependentString {
  1.1715 +  public:
  1.1716 +    static void StaticAsserts() {
  1.1717 +      static_assert(sizeof(FakeDependentString) == sizeof(nsDependentString),
  1.1718 +                    "Must have right object size");
  1.1719 +      static_assert(offsetof(FakeDependentString, mData) ==
  1.1720 +                      offsetof(DepedentStringAsserter, mData),
  1.1721 +                    "Offset of mData should match");
  1.1722 +      static_assert(offsetof(FakeDependentString, mLength) ==
  1.1723 +                      offsetof(DepedentStringAsserter, mLength),
  1.1724 +                    "Offset of mLength should match");
  1.1725 +      static_assert(offsetof(FakeDependentString, mFlags) ==
  1.1726 +                      offsetof(DepedentStringAsserter, mFlags),
  1.1727 +                    "Offset of mFlags should match");
  1.1728 +    }
  1.1729 +  };
  1.1730 +};
  1.1731 +
  1.1732 +} // namespace binding_detail
  1.1733 +
  1.1734 +enum StringificationBehavior {
  1.1735 +  eStringify,
  1.1736 +  eEmpty,
  1.1737 +  eNull
  1.1738 +};
  1.1739 +
  1.1740 +// pval must not be null and must point to a rooted JS::Value
  1.1741 +static inline bool
  1.1742 +ConvertJSValueToString(JSContext* cx, JS::Handle<JS::Value> v,
  1.1743 +                       JS::MutableHandle<JS::Value> pval,
  1.1744 +                       StringificationBehavior nullBehavior,
  1.1745 +                       StringificationBehavior undefinedBehavior,
  1.1746 +                       binding_detail::FakeDependentString& result)
  1.1747 +{
  1.1748 +  JSString *s;
  1.1749 +  if (v.isString()) {
  1.1750 +    s = v.toString();
  1.1751 +  } else {
  1.1752 +    StringificationBehavior behavior;
  1.1753 +    if (v.isNull()) {
  1.1754 +      behavior = nullBehavior;
  1.1755 +    } else if (v.isUndefined()) {
  1.1756 +      behavior = undefinedBehavior;
  1.1757 +    } else {
  1.1758 +      behavior = eStringify;
  1.1759 +    }
  1.1760 +
  1.1761 +    if (behavior != eStringify) {
  1.1762 +      if (behavior == eEmpty) {
  1.1763 +        result.Truncate();
  1.1764 +      } else {
  1.1765 +        result.SetNull();
  1.1766 +      }
  1.1767 +      return true;
  1.1768 +    }
  1.1769 +
  1.1770 +    s = JS::ToString(cx, v);
  1.1771 +    if (!s) {
  1.1772 +      return false;
  1.1773 +    }
  1.1774 +    pval.set(JS::StringValue(s));  // Root the new string.
  1.1775 +  }
  1.1776 +
  1.1777 +  size_t len;
  1.1778 +  const jschar *chars = JS_GetStringCharsZAndLength(cx, s, &len);
  1.1779 +  if (!chars) {
  1.1780 +    return false;
  1.1781 +  }
  1.1782 +
  1.1783 +  result.SetData(chars, len);
  1.1784 +  return true;
  1.1785 +}
  1.1786 +
  1.1787 +bool
  1.1788 +ConvertJSValueToByteString(JSContext* cx, JS::Handle<JS::Value> v,
  1.1789 +                           JS::MutableHandle<JS::Value> pval, bool nullable,
  1.1790 +                           nsACString& result);
  1.1791 +
  1.1792 +template<typename T>
  1.1793 +void DoTraceSequence(JSTracer* trc, FallibleTArray<T>& seq);
  1.1794 +template<typename T>
  1.1795 +void DoTraceSequence(JSTracer* trc, InfallibleTArray<T>& seq);
  1.1796 +
  1.1797 +// Class for simple sequence arguments, only used internally by codegen.
  1.1798 +namespace binding_detail {
  1.1799 +
  1.1800 +template<typename T>
  1.1801 +class AutoSequence : public AutoFallibleTArray<T, 16>
  1.1802 +{
  1.1803 +public:
  1.1804 +  AutoSequence() : AutoFallibleTArray<T, 16>()
  1.1805 +  {}
  1.1806 +
  1.1807 +  // Allow converting to const sequences as needed
  1.1808 +  operator const Sequence<T>&() const {
  1.1809 +    return *reinterpret_cast<const Sequence<T>*>(this);
  1.1810 +  }
  1.1811 +};
  1.1812 +
  1.1813 +} // namespace binding_detail
  1.1814 +
  1.1815 +// Class used to trace sequences, with specializations for various
  1.1816 +// sequence types.
  1.1817 +template<typename T,
  1.1818 +         bool isDictionary=IsBaseOf<DictionaryBase, T>::value,
  1.1819 +         bool isTypedArray=IsBaseOf<AllTypedArraysBase, T>::value,
  1.1820 +         bool isOwningUnion=IsBaseOf<AllOwningUnionBase, T>::value>
  1.1821 +class SequenceTracer
  1.1822 +{
  1.1823 +  explicit SequenceTracer() MOZ_DELETE; // Should never be instantiated
  1.1824 +};
  1.1825 +
  1.1826 +// sequence<object> or sequence<object?>
  1.1827 +template<>
  1.1828 +class SequenceTracer<JSObject*, false, false, false>
  1.1829 +{
  1.1830 +  explicit SequenceTracer() MOZ_DELETE; // Should never be instantiated
  1.1831 +
  1.1832 +public:
  1.1833 +  static void TraceSequence(JSTracer* trc, JSObject** objp, JSObject** end) {
  1.1834 +    for (; objp != end; ++objp) {
  1.1835 +      JS_CallObjectTracer(trc, objp, "sequence<object>");
  1.1836 +    }
  1.1837 +  }
  1.1838 +};
  1.1839 +
  1.1840 +// sequence<any>
  1.1841 +template<>
  1.1842 +class SequenceTracer<JS::Value, false, false, false>
  1.1843 +{
  1.1844 +  explicit SequenceTracer() MOZ_DELETE; // Should never be instantiated
  1.1845 +
  1.1846 +public:
  1.1847 +  static void TraceSequence(JSTracer* trc, JS::Value* valp, JS::Value* end) {
  1.1848 +    for (; valp != end; ++valp) {
  1.1849 +      JS_CallValueTracer(trc, valp, "sequence<any>");
  1.1850 +    }
  1.1851 +  }
  1.1852 +};
  1.1853 +
  1.1854 +// sequence<sequence<T>>
  1.1855 +template<typename T>
  1.1856 +class SequenceTracer<Sequence<T>, false, false, false>
  1.1857 +{
  1.1858 +  explicit SequenceTracer() MOZ_DELETE; // Should never be instantiated
  1.1859 +
  1.1860 +public:
  1.1861 +  static void TraceSequence(JSTracer* trc, Sequence<T>* seqp, Sequence<T>* end) {
  1.1862 +    for (; seqp != end; ++seqp) {
  1.1863 +      DoTraceSequence(trc, *seqp);
  1.1864 +    }
  1.1865 +  }
  1.1866 +};
  1.1867 +
  1.1868 +// sequence<sequence<T>> as return value
  1.1869 +template<typename T>
  1.1870 +class SequenceTracer<nsTArray<T>, false, false, false>
  1.1871 +{
  1.1872 +  explicit SequenceTracer() MOZ_DELETE; // Should never be instantiated
  1.1873 +
  1.1874 +public:
  1.1875 +  static void TraceSequence(JSTracer* trc, nsTArray<T>* seqp, nsTArray<T>* end) {
  1.1876 +    for (; seqp != end; ++seqp) {
  1.1877 +      DoTraceSequence(trc, *seqp);
  1.1878 +    }
  1.1879 +  }
  1.1880 +};
  1.1881 +
  1.1882 +// sequence<someDictionary>
  1.1883 +template<typename T>
  1.1884 +class SequenceTracer<T, true, false, false>
  1.1885 +{
  1.1886 +  explicit SequenceTracer() MOZ_DELETE; // Should never be instantiated
  1.1887 +
  1.1888 +public:
  1.1889 +  static void TraceSequence(JSTracer* trc, T* dictp, T* end) {
  1.1890 +    for (; dictp != end; ++dictp) {
  1.1891 +      dictp->TraceDictionary(trc);
  1.1892 +    }
  1.1893 +  }
  1.1894 +};
  1.1895 +
  1.1896 +// sequence<SomeTypedArray>
  1.1897 +template<typename T>
  1.1898 +class SequenceTracer<T, false, true, false>
  1.1899 +{
  1.1900 +  explicit SequenceTracer() MOZ_DELETE; // Should never be instantiated
  1.1901 +
  1.1902 +public:
  1.1903 +  static void TraceSequence(JSTracer* trc, T* arrayp, T* end) {
  1.1904 +    for (; arrayp != end; ++arrayp) {
  1.1905 +      arrayp->TraceSelf(trc);
  1.1906 +    }
  1.1907 +  }
  1.1908 +};
  1.1909 +
  1.1910 +// sequence<SomeOwningUnion>
  1.1911 +template<typename T>
  1.1912 +class SequenceTracer<T, false, false, true>
  1.1913 +{
  1.1914 +  explicit SequenceTracer() MOZ_DELETE; // Should never be instantiated
  1.1915 +
  1.1916 +public:
  1.1917 +  static void TraceSequence(JSTracer* trc, T* arrayp, T* end) {
  1.1918 +    for (; arrayp != end; ++arrayp) {
  1.1919 +      arrayp->TraceUnion(trc);
  1.1920 +    }
  1.1921 +  }
  1.1922 +};
  1.1923 +
  1.1924 +// sequence<T?> with T? being a Nullable<T>
  1.1925 +template<typename T>
  1.1926 +class SequenceTracer<Nullable<T>, false, false, false>
  1.1927 +{
  1.1928 +  explicit SequenceTracer() MOZ_DELETE; // Should never be instantiated
  1.1929 +
  1.1930 +public:
  1.1931 +  static void TraceSequence(JSTracer* trc, Nullable<T>* seqp,
  1.1932 +                            Nullable<T>* end) {
  1.1933 +    for (; seqp != end; ++seqp) {
  1.1934 +      if (!seqp->IsNull()) {
  1.1935 +        // Pretend like we actually have a length-one sequence here so
  1.1936 +        // we can do template instantiation correctly for T.
  1.1937 +        T& val = seqp->Value();
  1.1938 +        T* ptr = &val;
  1.1939 +        SequenceTracer<T>::TraceSequence(trc, ptr, ptr+1);
  1.1940 +      }
  1.1941 +    }
  1.1942 +  }
  1.1943 +};
  1.1944 +
  1.1945 +// XXXbz It's not clear whether it's better to add a pldhash dependency here
  1.1946 +// (for PLDHashOperator) or add a BindingUtils.h dependency (for
  1.1947 +// SequenceTracer) to MozMap.h...
  1.1948 +template<typename T>
  1.1949 +static PLDHashOperator
  1.1950 +TraceMozMapValue(T* aValue, void* aClosure)
  1.1951 +{
  1.1952 +  JSTracer* trc = static_cast<JSTracer*>(aClosure);
  1.1953 +  // Act like it's a one-element sequence to leverage all that infrastructure.
  1.1954 +  SequenceTracer<T>::TraceSequence(trc, aValue, aValue + 1);
  1.1955 +  return PL_DHASH_NEXT;
  1.1956 +}
  1.1957 +
  1.1958 +// sequence<MozMap>
  1.1959 +template<typename T>
  1.1960 +class SequenceTracer<MozMap<T>, false, false, false>
  1.1961 +{
  1.1962 +  explicit SequenceTracer() MOZ_DELETE; // Should never be instantiated
  1.1963 +
  1.1964 +public:
  1.1965 +  static void TraceSequence(JSTracer* trc, MozMap<T>* seqp, MozMap<T>* end) {
  1.1966 +    for (; seqp != end; ++seqp) {
  1.1967 +      seqp->EnumerateValues(TraceMozMapValue<T>, trc);
  1.1968 +    }
  1.1969 +  }
  1.1970 +};
  1.1971 +
  1.1972 +template<typename T>
  1.1973 +void DoTraceSequence(JSTracer* trc, FallibleTArray<T>& seq)
  1.1974 +{
  1.1975 +  SequenceTracer<T>::TraceSequence(trc, seq.Elements(),
  1.1976 +                                   seq.Elements() + seq.Length());
  1.1977 +}
  1.1978 +
  1.1979 +template<typename T>
  1.1980 +void DoTraceSequence(JSTracer* trc, InfallibleTArray<T>& seq)
  1.1981 +{
  1.1982 +  SequenceTracer<T>::TraceSequence(trc, seq.Elements(),
  1.1983 +                                   seq.Elements() + seq.Length());
  1.1984 +}
  1.1985 +
  1.1986 +// Rooter class for sequences; this is what we mostly use in the codegen
  1.1987 +template<typename T>
  1.1988 +class MOZ_STACK_CLASS SequenceRooter : private JS::CustomAutoRooter
  1.1989 +{
  1.1990 +public:
  1.1991 +  SequenceRooter(JSContext *aCx, FallibleTArray<T>* aSequence
  1.1992 +                 MOZ_GUARD_OBJECT_NOTIFIER_PARAM)
  1.1993 +    : JS::CustomAutoRooter(aCx MOZ_GUARD_OBJECT_NOTIFIER_PARAM_TO_PARENT),
  1.1994 +      mFallibleArray(aSequence),
  1.1995 +      mSequenceType(eFallibleArray)
  1.1996 +  {
  1.1997 +  }
  1.1998 +
  1.1999 +  SequenceRooter(JSContext *aCx, InfallibleTArray<T>* aSequence
  1.2000 +                 MOZ_GUARD_OBJECT_NOTIFIER_PARAM)
  1.2001 +    : JS::CustomAutoRooter(aCx MOZ_GUARD_OBJECT_NOTIFIER_PARAM_TO_PARENT),
  1.2002 +      mInfallibleArray(aSequence),
  1.2003 +      mSequenceType(eInfallibleArray)
  1.2004 +  {
  1.2005 +  }
  1.2006 +
  1.2007 +  SequenceRooter(JSContext *aCx, Nullable<nsTArray<T> >* aSequence
  1.2008 +                 MOZ_GUARD_OBJECT_NOTIFIER_PARAM)
  1.2009 +    : JS::CustomAutoRooter(aCx MOZ_GUARD_OBJECT_NOTIFIER_PARAM_TO_PARENT),
  1.2010 +      mNullableArray(aSequence),
  1.2011 +      mSequenceType(eNullableArray)
  1.2012 +  {
  1.2013 +  }
  1.2014 +
  1.2015 + private:
  1.2016 +  enum SequenceType {
  1.2017 +    eInfallibleArray,
  1.2018 +    eFallibleArray,
  1.2019 +    eNullableArray
  1.2020 +  };
  1.2021 +
  1.2022 +  virtual void trace(JSTracer *trc) MOZ_OVERRIDE
  1.2023 +  {
  1.2024 +    if (mSequenceType == eFallibleArray) {
  1.2025 +      DoTraceSequence(trc, *mFallibleArray);
  1.2026 +    } else if (mSequenceType == eInfallibleArray) {
  1.2027 +      DoTraceSequence(trc, *mInfallibleArray);
  1.2028 +    } else {
  1.2029 +      MOZ_ASSERT(mSequenceType == eNullableArray);
  1.2030 +      if (!mNullableArray->IsNull()) {
  1.2031 +        DoTraceSequence(trc, mNullableArray->Value());
  1.2032 +      }
  1.2033 +    }
  1.2034 +  }
  1.2035 +
  1.2036 +  union {
  1.2037 +    InfallibleTArray<T>* mInfallibleArray;
  1.2038 +    FallibleTArray<T>* mFallibleArray;
  1.2039 +    Nullable<nsTArray<T> >* mNullableArray;
  1.2040 +  };
  1.2041 +
  1.2042 +  SequenceType mSequenceType;
  1.2043 +};
  1.2044 +
  1.2045 +// Rooter class for MozMap; this is what we mostly use in the codegen.
  1.2046 +template<typename T>
  1.2047 +class MOZ_STACK_CLASS MozMapRooter : private JS::CustomAutoRooter
  1.2048 +{
  1.2049 +public:
  1.2050 +  MozMapRooter(JSContext *aCx, MozMap<T>* aMozMap
  1.2051 +               MOZ_GUARD_OBJECT_NOTIFIER_PARAM)
  1.2052 +    : JS::CustomAutoRooter(aCx MOZ_GUARD_OBJECT_NOTIFIER_PARAM_TO_PARENT),
  1.2053 +      mMozMap(aMozMap),
  1.2054 +      mMozMapType(eMozMap)
  1.2055 +  {
  1.2056 +  }
  1.2057 +
  1.2058 +  MozMapRooter(JSContext *aCx, Nullable<MozMap<T>>* aMozMap
  1.2059 +                 MOZ_GUARD_OBJECT_NOTIFIER_PARAM)
  1.2060 +    : JS::CustomAutoRooter(aCx MOZ_GUARD_OBJECT_NOTIFIER_PARAM_TO_PARENT),
  1.2061 +      mNullableMozMap(aMozMap),
  1.2062 +      mMozMapType(eNullableMozMap)
  1.2063 +  {
  1.2064 +  }
  1.2065 +
  1.2066 +private:
  1.2067 +  enum MozMapType {
  1.2068 +    eMozMap,
  1.2069 +    eNullableMozMap
  1.2070 +  };
  1.2071 +
  1.2072 +  virtual void trace(JSTracer *trc) MOZ_OVERRIDE
  1.2073 +  {
  1.2074 +    MozMap<T>* mozMap;
  1.2075 +    if (mMozMapType == eMozMap) {
  1.2076 +      mozMap = mMozMap;
  1.2077 +    } else {
  1.2078 +      MOZ_ASSERT(mMozMapType == eNullableMozMap);
  1.2079 +      if (mNullableMozMap->IsNull()) {
  1.2080 +        // Nothing to do
  1.2081 +        return;
  1.2082 +      }
  1.2083 +      mozMap = &mNullableMozMap->Value();
  1.2084 +    }
  1.2085 +
  1.2086 +    mozMap->EnumerateValues(TraceMozMapValue<T>, trc);
  1.2087 +  }
  1.2088 +
  1.2089 +  union {
  1.2090 +    MozMap<T>* mMozMap;
  1.2091 +    Nullable<MozMap<T>>* mNullableMozMap;
  1.2092 +  };
  1.2093 +
  1.2094 +  MozMapType mMozMapType;
  1.2095 +};
  1.2096 +
  1.2097 +template<typename T>
  1.2098 +class MOZ_STACK_CLASS RootedUnion : public T,
  1.2099 +                                    private JS::CustomAutoRooter
  1.2100 +{
  1.2101 +public:
  1.2102 +  RootedUnion(JSContext* cx MOZ_GUARD_OBJECT_NOTIFIER_PARAM) :
  1.2103 +    T(),
  1.2104 +    JS::CustomAutoRooter(cx MOZ_GUARD_OBJECT_NOTIFIER_PARAM_TO_PARENT)
  1.2105 +  {
  1.2106 +  }
  1.2107 +
  1.2108 +  virtual void trace(JSTracer *trc) MOZ_OVERRIDE
  1.2109 +  {
  1.2110 +    this->TraceUnion(trc);
  1.2111 +  }
  1.2112 +};
  1.2113 +
  1.2114 +template<typename T>
  1.2115 +class MOZ_STACK_CLASS NullableRootedUnion : public Nullable<T>,
  1.2116 +                                            private JS::CustomAutoRooter
  1.2117 +{
  1.2118 +public:
  1.2119 +  NullableRootedUnion(JSContext* cx MOZ_GUARD_OBJECT_NOTIFIER_PARAM) :
  1.2120 +    Nullable<T>(),
  1.2121 +    JS::CustomAutoRooter(cx MOZ_GUARD_OBJECT_NOTIFIER_PARAM_TO_PARENT)
  1.2122 +  {
  1.2123 +  }
  1.2124 +
  1.2125 +  virtual void trace(JSTracer *trc) MOZ_OVERRIDE
  1.2126 +  {
  1.2127 +    if (!this->IsNull()) {
  1.2128 +      this->Value().TraceUnion(trc);
  1.2129 +    }
  1.2130 +  }
  1.2131 +};
  1.2132 +
  1.2133 +inline bool
  1.2134 +IdEquals(jsid id, const char* string)
  1.2135 +{
  1.2136 +  return JSID_IS_STRING(id) &&
  1.2137 +         JS_FlatStringEqualsAscii(JSID_TO_FLAT_STRING(id), string);
  1.2138 +}
  1.2139 +
  1.2140 +inline bool
  1.2141 +AddStringToIDVector(JSContext* cx, JS::AutoIdVector& vector, const char* name)
  1.2142 +{
  1.2143 +  return vector.growBy(1) &&
  1.2144 +         InternJSString(cx, vector[vector.length() - 1], name);
  1.2145 +}
  1.2146 +
  1.2147 +// Implementation of the bits that XrayWrapper needs
  1.2148 +
  1.2149 +/**
  1.2150 + * This resolves indexed or named properties of obj.
  1.2151 + *
  1.2152 + * wrapper is the Xray JS object.
  1.2153 + * obj is the target object of the Xray, a binding's instance object or a
  1.2154 + *     interface or interface prototype object.
  1.2155 + */
  1.2156 +bool
  1.2157 +XrayResolveOwnProperty(JSContext* cx, JS::Handle<JSObject*> wrapper,
  1.2158 +                       JS::Handle<JSObject*> obj,
  1.2159 +                       JS::Handle<jsid> id,
  1.2160 +                       JS::MutableHandle<JSPropertyDescriptor> desc);
  1.2161 +
  1.2162 +/**
  1.2163 + * This resolves operations, attributes and constants of the interfaces for obj.
  1.2164 + *
  1.2165 + * wrapper is the Xray JS object.
  1.2166 + * obj is the target object of the Xray, a binding's instance object or a
  1.2167 + *     interface or interface prototype object.
  1.2168 + */
  1.2169 +bool
  1.2170 +XrayResolveNativeProperty(JSContext* cx, JS::Handle<JSObject*> wrapper,
  1.2171 +                          JS::Handle<JSObject*> obj,
  1.2172 +                          JS::Handle<jsid> id, JS::MutableHandle<JSPropertyDescriptor> desc);
  1.2173 +
  1.2174 +/**
  1.2175 + * Define a property on obj through an Xray wrapper.
  1.2176 + *
  1.2177 + * wrapper is the Xray JS object.
  1.2178 + * obj is the target object of the Xray, a binding's instance object or a
  1.2179 + *     interface or interface prototype object.
  1.2180 + * defined will be set to true if a property was set as a result of this call.
  1.2181 + */
  1.2182 +bool
  1.2183 +XrayDefineProperty(JSContext* cx, JS::Handle<JSObject*> wrapper,
  1.2184 +                   JS::Handle<JSObject*> obj, JS::Handle<jsid> id,
  1.2185 +                   JS::MutableHandle<JSPropertyDescriptor> desc, bool* defined);
  1.2186 +
  1.2187 +/**
  1.2188 + * This enumerates indexed or named properties of obj and operations, attributes
  1.2189 + * and constants of the interfaces for obj.
  1.2190 + *
  1.2191 + * wrapper is the Xray JS object.
  1.2192 + * obj is the target object of the Xray, a binding's instance object or a
  1.2193 + *     interface or interface prototype object.
  1.2194 + * flags are JSITER_* flags.
  1.2195 + */
  1.2196 +bool
  1.2197 +XrayEnumerateProperties(JSContext* cx, JS::Handle<JSObject*> wrapper,
  1.2198 +                        JS::Handle<JSObject*> obj,
  1.2199 +                        unsigned flags, JS::AutoIdVector& props);
  1.2200 +
  1.2201 +extern NativePropertyHooks sWorkerNativePropertyHooks;
  1.2202 +
  1.2203 +// We use one constructor JSNative to represent all DOM interface objects (so
  1.2204 +// we can easily detect when we need to wrap them in an Xray wrapper). We store
  1.2205 +// the real JSNative in the mNative member of a JSNativeHolder in the
  1.2206 +// CONSTRUCTOR_NATIVE_HOLDER_RESERVED_SLOT slot of the JSFunction object for a
  1.2207 +// specific interface object. We also store the NativeProperties in the
  1.2208 +// JSNativeHolder.
  1.2209 +// Note that some interface objects are not yet a JSFunction but a normal
  1.2210 +// JSObject with a DOMJSClass, those do not use these slots.
  1.2211 +
  1.2212 +enum {
  1.2213 +  CONSTRUCTOR_NATIVE_HOLDER_RESERVED_SLOT = 0
  1.2214 +};
  1.2215 +
  1.2216 +bool
  1.2217 +Constructor(JSContext* cx, unsigned argc, JS::Value* vp);
  1.2218 +
  1.2219 +inline bool
  1.2220 +UseDOMXray(JSObject* obj)
  1.2221 +{
  1.2222 +  const js::Class* clasp = js::GetObjectClass(obj);
  1.2223 +  return IsDOMClass(clasp) ||
  1.2224 +         JS_IsNativeFunction(obj, Constructor) ||
  1.2225 +         IsDOMIfaceAndProtoClass(clasp);
  1.2226 +}
  1.2227 +
  1.2228 +#ifdef DEBUG
  1.2229 +inline bool
  1.2230 +HasConstructor(JSObject* obj)
  1.2231 +{
  1.2232 +  return JS_IsNativeFunction(obj, Constructor) ||
  1.2233 +         js::GetObjectClass(obj)->construct;
  1.2234 +}
  1.2235 + #endif
  1.2236 + 
  1.2237 +// Transfer reference in ptr to smartPtr.
  1.2238 +template<class T>
  1.2239 +inline void
  1.2240 +Take(nsRefPtr<T>& smartPtr, T* ptr)
  1.2241 +{
  1.2242 +  smartPtr = dont_AddRef(ptr);
  1.2243 +}
  1.2244 +
  1.2245 +// Transfer ownership of ptr to smartPtr.
  1.2246 +template<class T>
  1.2247 +inline void
  1.2248 +Take(nsAutoPtr<T>& smartPtr, T* ptr)
  1.2249 +{
  1.2250 +  smartPtr = ptr;
  1.2251 +}
  1.2252 +
  1.2253 +inline void
  1.2254 +MustInheritFromNonRefcountedDOMObject(NonRefcountedDOMObject*)
  1.2255 +{
  1.2256 +}
  1.2257 +
  1.2258 +/**
  1.2259 + * This creates a JSString containing the value that the toString function for
  1.2260 + * obj should create according to the WebIDL specification, ignoring any
  1.2261 + * modifications by script. The value is prefixed with pre and postfixed with
  1.2262 + * post, unless this is called for an object that has a stringifier. It is
  1.2263 + * specifically for use by Xray code.
  1.2264 + *
  1.2265 + * wrapper is the Xray JS object.
  1.2266 + * obj is the target object of the Xray, a binding's instance object or a
  1.2267 + *     interface or interface prototype object.
  1.2268 + * pre is a string that should be prefixed to the value.
  1.2269 + * post is a string that should be prefixed to the value.
  1.2270 + * v contains the JSString for the value if the function returns true.
  1.2271 + */
  1.2272 +bool
  1.2273 +NativeToString(JSContext* cx, JS::Handle<JSObject*> wrapper,
  1.2274 +               JS::Handle<JSObject*> obj, const char* pre,
  1.2275 +               const char* post,
  1.2276 +               JS::MutableHandle<JS::Value> v);
  1.2277 +
  1.2278 +HAS_MEMBER(JSBindingFinalized)
  1.2279 +
  1.2280 +template<class T, bool hasCallback=HasJSBindingFinalizedMember<T>::Value>
  1.2281 +struct JSBindingFinalized
  1.2282 +{
  1.2283 +  static void Finalized(T* self)
  1.2284 +  {
  1.2285 +  }
  1.2286 +};
  1.2287 +
  1.2288 +template<class T>
  1.2289 +struct JSBindingFinalized<T, true>
  1.2290 +{
  1.2291 +  static void Finalized(T* self)
  1.2292 +  {
  1.2293 +    self->JSBindingFinalized();
  1.2294 +  }
  1.2295 +};
  1.2296 +
  1.2297 +// Helpers for creating a const version of a type.
  1.2298 +template<typename T>
  1.2299 +const T& Constify(T& arg)
  1.2300 +{
  1.2301 +  return arg;
  1.2302 +}
  1.2303 +
  1.2304 +// Helper for turning (Owning)NonNull<T> into T&
  1.2305 +template<typename T>
  1.2306 +T& NonNullHelper(T& aArg)
  1.2307 +{
  1.2308 +  return aArg;
  1.2309 +}
  1.2310 +
  1.2311 +template<typename T>
  1.2312 +T& NonNullHelper(NonNull<T>& aArg)
  1.2313 +{
  1.2314 +  return aArg;
  1.2315 +}
  1.2316 +
  1.2317 +template<typename T>
  1.2318 +const T& NonNullHelper(const NonNull<T>& aArg)
  1.2319 +{
  1.2320 +  return aArg;
  1.2321 +}
  1.2322 +
  1.2323 +template<typename T>
  1.2324 +T& NonNullHelper(OwningNonNull<T>& aArg)
  1.2325 +{
  1.2326 +  return aArg;
  1.2327 +}
  1.2328 +
  1.2329 +template<typename T>
  1.2330 +const T& NonNullHelper(const OwningNonNull<T>& aArg)
  1.2331 +{
  1.2332 +  return aArg;
  1.2333 +}
  1.2334 +
  1.2335 +inline
  1.2336 +void NonNullHelper(NonNull<binding_detail::FakeDependentString>& aArg)
  1.2337 +{
  1.2338 +  // This overload is here to make sure that we never end up applying
  1.2339 +  // NonNullHelper to a NonNull<binding_detail::FakeDependentString>. If we
  1.2340 +  // try to, it should fail to compile, since presumably the caller will try to
  1.2341 +  // use our nonexistent return value.
  1.2342 +}
  1.2343 +
  1.2344 +inline
  1.2345 +void NonNullHelper(const NonNull<binding_detail::FakeDependentString>& aArg)
  1.2346 +{
  1.2347 +  // This overload is here to make sure that we never end up applying
  1.2348 +  // NonNullHelper to a NonNull<binding_detail::FakeDependentString>. If we
  1.2349 +  // try to, it should fail to compile, since presumably the caller will try to
  1.2350 +  // use our nonexistent return value.
  1.2351 +}
  1.2352 +
  1.2353 +inline
  1.2354 +void NonNullHelper(binding_detail::FakeDependentString& aArg)
  1.2355 +{
  1.2356 +  // This overload is here to make sure that we never end up applying
  1.2357 +  // NonNullHelper to a FakeDependentString before we've constified it.  If we
  1.2358 +  // try to, it should fail to compile, since presumably the caller will try to
  1.2359 +  // use our nonexistent return value.
  1.2360 +}
  1.2361 +
  1.2362 +MOZ_ALWAYS_INLINE
  1.2363 +const nsAString& NonNullHelper(const binding_detail::FakeDependentString& aArg)
  1.2364 +{
  1.2365 +  return aArg;
  1.2366 +}
  1.2367 +
  1.2368 +// Reparent the wrapper of aObj to whatever its native now thinks its
  1.2369 +// parent should be.
  1.2370 +nsresult
  1.2371 +ReparentWrapper(JSContext* aCx, JS::Handle<JSObject*> aObj);
  1.2372 +
  1.2373 +/**
  1.2374 + * Used to implement the hasInstance hook of an interface object.
  1.2375 + *
  1.2376 + * instance should not be a security wrapper.
  1.2377 + */
  1.2378 +bool
  1.2379 +InterfaceHasInstance(JSContext* cx, JS::Handle<JSObject*> obj,
  1.2380 +                     JS::Handle<JSObject*> instance,
  1.2381 +                     bool* bp);
  1.2382 +bool
  1.2383 +InterfaceHasInstance(JSContext* cx, JS::Handle<JSObject*> obj, JS::MutableHandle<JS::Value> vp,
  1.2384 +                     bool* bp);
  1.2385 +bool
  1.2386 +InterfaceHasInstance(JSContext* cx, int prototypeID, int depth,
  1.2387 +                     JS::Handle<JSObject*> instance,
  1.2388 +                     bool* bp);
  1.2389 +
  1.2390 +// Helper for lenient getters/setters to report to console.  If this
  1.2391 +// returns false, we couldn't even get a global.
  1.2392 +bool
  1.2393 +ReportLenientThisUnwrappingFailure(JSContext* cx, JSObject* obj);
  1.2394 +
  1.2395 +inline JSObject*
  1.2396 +GetUnforgeableHolder(JSObject* aGlobal, prototypes::ID aId)
  1.2397 +{
  1.2398 +  ProtoAndIfaceCache& protoAndIfaceCache = *GetProtoAndIfaceCache(aGlobal);
  1.2399 +  JSObject* interfaceProto = protoAndIfaceCache.EntrySlotMustExist(aId);
  1.2400 +  return &js::GetReservedSlot(interfaceProto,
  1.2401 +                              DOM_INTERFACE_PROTO_SLOTS_BASE).toObject();
  1.2402 +}
  1.2403 +
  1.2404 +// Given a JSObject* that represents the chrome side of a JS-implemented WebIDL
  1.2405 +// interface, get the nsPIDOMWindow corresponding to the content side, if any.
  1.2406 +// A false return means an exception was thrown.
  1.2407 +bool
  1.2408 +GetWindowForJSImplementedObject(JSContext* cx, JS::Handle<JSObject*> obj,
  1.2409 +                                nsPIDOMWindow** window);
  1.2410 +
  1.2411 +void
  1.2412 +ConstructJSImplementation(JSContext* aCx, const char* aContractId,
  1.2413 +                          nsPIDOMWindow* aWindow,
  1.2414 +                          JS::MutableHandle<JSObject*> aObject,
  1.2415 +                          ErrorResult& aRv);
  1.2416 +
  1.2417 +already_AddRefed<nsPIDOMWindow>
  1.2418 +ConstructJSImplementation(JSContext* aCx, const char* aContractId,
  1.2419 +                          const GlobalObject& aGlobal,
  1.2420 +                          JS::MutableHandle<JSObject*> aObject,
  1.2421 +                          ErrorResult& aRv);
  1.2422 +
  1.2423 +/**
  1.2424 + * Convert an nsCString to jsval, returning true on success.
  1.2425 + * These functions are intended for ByteString implementations.
  1.2426 + * As such, the string is not UTF-8 encoded.  Any UTF8 strings passed to these
  1.2427 + * methods will be mangled.
  1.2428 + */
  1.2429 +bool NonVoidByteStringToJsval(JSContext *cx, const nsACString &str,
  1.2430 +                              JS::MutableHandle<JS::Value> rval);
  1.2431 +inline bool ByteStringToJsval(JSContext *cx, const nsACString &str,
  1.2432 +                              JS::MutableHandle<JS::Value> rval)
  1.2433 +{
  1.2434 +    if (str.IsVoid()) {
  1.2435 +        rval.setNull();
  1.2436 +        return true;
  1.2437 +    }
  1.2438 +    return NonVoidByteStringToJsval(cx, str, rval);
  1.2439 +}
  1.2440 +
  1.2441 +template<class T, bool isISupports=IsBaseOf<nsISupports, T>::value>
  1.2442 +struct PreserveWrapperHelper
  1.2443 +{
  1.2444 +  static void PreserveWrapper(T* aObject)
  1.2445 +  {
  1.2446 +    aObject->PreserveWrapper(aObject, NS_CYCLE_COLLECTION_PARTICIPANT(T));
  1.2447 +  }
  1.2448 +};
  1.2449 +
  1.2450 +template<class T>
  1.2451 +struct PreserveWrapperHelper<T, true>
  1.2452 +{
  1.2453 +  static void PreserveWrapper(T* aObject)
  1.2454 +  {
  1.2455 +    aObject->PreserveWrapper(reinterpret_cast<nsISupports*>(aObject));
  1.2456 +  }
  1.2457 +};
  1.2458 +
  1.2459 +template<class T>
  1.2460 +void PreserveWrapper(T* aObject)
  1.2461 +{
  1.2462 +  PreserveWrapperHelper<T>::PreserveWrapper(aObject);
  1.2463 +}
  1.2464 +
  1.2465 +template<class T, bool isISupports=IsBaseOf<nsISupports, T>::value>
  1.2466 +struct CastingAssertions
  1.2467 +{
  1.2468 +  static bool ToSupportsIsCorrect(T*)
  1.2469 +  {
  1.2470 +    return true;
  1.2471 +  }
  1.2472 +  static bool ToSupportsIsOnPrimaryInheritanceChain(T*, nsWrapperCache*)
  1.2473 +  {
  1.2474 +    return true;
  1.2475 +  }
  1.2476 +};
  1.2477 +
  1.2478 +template<class T>
  1.2479 +struct CastingAssertions<T, true>
  1.2480 +{
  1.2481 +  static bool ToSupportsIsCorrect(T* aObject)
  1.2482 +  {
  1.2483 +    return ToSupports(aObject) ==  reinterpret_cast<nsISupports*>(aObject);
  1.2484 +  }
  1.2485 +  static bool ToSupportsIsOnPrimaryInheritanceChain(T* aObject,
  1.2486 +                                                    nsWrapperCache* aCache)
  1.2487 +  {
  1.2488 +    return reinterpret_cast<void*>(aObject) != aCache;
  1.2489 +  }
  1.2490 +};
  1.2491 +
  1.2492 +template<class T>
  1.2493 +bool
  1.2494 +ToSupportsIsCorrect(T* aObject)
  1.2495 +{
  1.2496 +  return CastingAssertions<T>::ToSupportsIsCorrect(aObject);
  1.2497 +}
  1.2498 +
  1.2499 +template<class T>
  1.2500 +bool
  1.2501 +ToSupportsIsOnPrimaryInheritanceChain(T* aObject, nsWrapperCache* aCache)
  1.2502 +{
  1.2503 +  return CastingAssertions<T>::ToSupportsIsOnPrimaryInheritanceChain(aObject,
  1.2504 +                                                                     aCache);
  1.2505 +}
  1.2506 +
  1.2507 +template<class T, template <typename> class SmartPtr,
  1.2508 +         bool isISupports=IsBaseOf<nsISupports, T>::value>
  1.2509 +class DeferredFinalizer
  1.2510 +{
  1.2511 +  typedef nsTArray<SmartPtr<T> > SmartPtrArray;
  1.2512 +
  1.2513 +  static void*
  1.2514 +  AppendDeferredFinalizePointer(void* aData, void* aObject)
  1.2515 +  {
  1.2516 +    SmartPtrArray* pointers = static_cast<SmartPtrArray*>(aData);
  1.2517 +    if (!pointers) {
  1.2518 +      pointers = new SmartPtrArray();
  1.2519 +    }
  1.2520 +
  1.2521 +    T* self = static_cast<T*>(aObject);
  1.2522 +
  1.2523 +    SmartPtr<T>* defer = pointers->AppendElement();
  1.2524 +    Take(*defer, self);
  1.2525 +    return pointers;
  1.2526 +  }
  1.2527 +  static bool
  1.2528 +  DeferredFinalize(uint32_t aSlice, void* aData)
  1.2529 +  {
  1.2530 +    MOZ_ASSERT(aSlice > 0, "nonsensical/useless call with aSlice == 0");
  1.2531 +    SmartPtrArray* pointers = static_cast<SmartPtrArray*>(aData);
  1.2532 +    uint32_t oldLen = pointers->Length();
  1.2533 +    if (oldLen < aSlice) {
  1.2534 +      aSlice = oldLen;
  1.2535 +    }
  1.2536 +    uint32_t newLen = oldLen - aSlice;
  1.2537 +    pointers->RemoveElementsAt(newLen, aSlice);
  1.2538 +    if (newLen == 0) {
  1.2539 +      delete pointers;
  1.2540 +      return true;
  1.2541 +    }
  1.2542 +    return false;
  1.2543 +  }
  1.2544 +
  1.2545 +public:
  1.2546 +  static void
  1.2547 +  AddForDeferredFinalization(T* aObject)
  1.2548 +  {
  1.2549 +    cyclecollector::DeferredFinalize(AppendDeferredFinalizePointer,
  1.2550 +                                     DeferredFinalize, aObject);
  1.2551 +  }
  1.2552 +};
  1.2553 +
  1.2554 +template<class T, template <typename> class SmartPtr>
  1.2555 +class DeferredFinalizer<T, SmartPtr, true>
  1.2556 +{
  1.2557 +public:
  1.2558 +  static void
  1.2559 +  AddForDeferredFinalization(T* aObject)
  1.2560 +  {
  1.2561 +    cyclecollector::DeferredFinalize(reinterpret_cast<nsISupports*>(aObject));
  1.2562 +  }
  1.2563 +};
  1.2564 +
  1.2565 +template<class T, template <typename> class SmartPtr>
  1.2566 +static void
  1.2567 +AddForDeferredFinalization(T* aObject)
  1.2568 +{
  1.2569 +  DeferredFinalizer<T, SmartPtr>::AddForDeferredFinalization(aObject);
  1.2570 +}
  1.2571 +
  1.2572 +// This returns T's CC participant if it participates in CC or null if it
  1.2573 +// doesn't. This also returns null for classes that don't inherit from
  1.2574 +// nsISupports (QI should be used to get the participant for those).
  1.2575 +template<class T, bool isISupports=IsBaseOf<nsISupports, T>::value>
  1.2576 +class GetCCParticipant
  1.2577 +{
  1.2578 +  // Helper for GetCCParticipant for classes that participate in CC.
  1.2579 +  template<class U>
  1.2580 +  static MOZ_CONSTEXPR nsCycleCollectionParticipant*
  1.2581 +  GetHelper(int, typename U::NS_CYCLE_COLLECTION_INNERCLASS* dummy=nullptr)
  1.2582 +  {
  1.2583 +    return T::NS_CYCLE_COLLECTION_INNERCLASS::GetParticipant();
  1.2584 +  }
  1.2585 +  // Helper for GetCCParticipant for classes that don't participate in CC.
  1.2586 +  template<class U>
  1.2587 +  static MOZ_CONSTEXPR nsCycleCollectionParticipant*
  1.2588 +  GetHelper(double)
  1.2589 +  {
  1.2590 +    return nullptr;
  1.2591 +  }
  1.2592 +
  1.2593 +public:
  1.2594 +  static MOZ_CONSTEXPR nsCycleCollectionParticipant*
  1.2595 +  Get()
  1.2596 +  {
  1.2597 +    // Passing int() here will try to call the GetHelper that takes an int as
  1.2598 +    // its firt argument. If T doesn't participate in CC then substitution for
  1.2599 +    // the second argument (with a default value) will fail and because of
  1.2600 +    // SFINAE the next best match (the variant taking a double) will be called.
  1.2601 +    return GetHelper<T>(int());
  1.2602 +  }
  1.2603 +};
  1.2604 +
  1.2605 +template<class T>
  1.2606 +class GetCCParticipant<T, true>
  1.2607 +{
  1.2608 +public:
  1.2609 +  static MOZ_CONSTEXPR nsCycleCollectionParticipant*
  1.2610 +  Get()
  1.2611 +  {
  1.2612 +    return nullptr;
  1.2613 +  }
  1.2614 +};
  1.2615 +
  1.2616 +/*
  1.2617 + * Helper function for testing whether the given object comes from a
  1.2618 + * privileged app.
  1.2619 + */
  1.2620 +bool
  1.2621 +IsInPrivilegedApp(JSContext* aCx, JSObject* aObj);
  1.2622 +
  1.2623 +/*
  1.2624 + * Helper function for testing whether the given object comes from a
  1.2625 + * certified app.
  1.2626 + */
  1.2627 +bool
  1.2628 +IsInCertifiedApp(JSContext* aCx, JSObject* aObj);
  1.2629 +
  1.2630 +void
  1.2631 +TraceGlobal(JSTracer* aTrc, JSObject* aObj);
  1.2632 +
  1.2633 +void
  1.2634 +FinalizeGlobal(JSFreeOp* aFop, JSObject* aObj);
  1.2635 +
  1.2636 +bool
  1.2637 +ResolveGlobal(JSContext* aCx, JS::Handle<JSObject*> aObj,
  1.2638 +              JS::Handle<jsid> aId, JS::MutableHandle<JSObject*> aObjp);
  1.2639 +
  1.2640 +bool
  1.2641 +EnumerateGlobal(JSContext* aCx, JS::Handle<JSObject*> aObj);
  1.2642 +
  1.2643 +template <class T, JS::Handle<JSObject*> (*ProtoGetter)(JSContext*,
  1.2644 +                                                        JS::Handle<JSObject*>)>
  1.2645 +JSObject*
  1.2646 +CreateGlobal(JSContext* aCx, T* aObject, nsWrapperCache* aCache,
  1.2647 +             const JSClass* aClass, JS::CompartmentOptions& aOptions,
  1.2648 +             JSPrincipals* aPrincipal)
  1.2649 +{
  1.2650 +  MOZ_ASSERT(!NS_IsMainThread());
  1.2651 +
  1.2652 +  aOptions.setTrace(TraceGlobal);
  1.2653 +
  1.2654 +  JS::Rooted<JSObject*> global(aCx,
  1.2655 +    JS_NewGlobalObject(aCx, aClass, aPrincipal, JS::DontFireOnNewGlobalHook,
  1.2656 +                       aOptions));
  1.2657 +  if (!global) {
  1.2658 +    NS_WARNING("Failed to create global");
  1.2659 +    return nullptr;
  1.2660 +  }
  1.2661 +
  1.2662 +  JSAutoCompartment ac(aCx, global);
  1.2663 +
  1.2664 +  dom::AllocateProtoAndIfaceCache(global, ProtoAndIfaceCache::WindowLike);
  1.2665 +
  1.2666 +  js::SetReservedSlot(global, DOM_OBJECT_SLOT, PRIVATE_TO_JSVAL(aObject));
  1.2667 +  NS_ADDREF(aObject);
  1.2668 +
  1.2669 +  aCache->SetIsDOMBinding();
  1.2670 +  aCache->SetWrapper(global);
  1.2671 +
  1.2672 +  /* Intl API is broken and makes this fail intermittently, see bug 934889.
  1.2673 +  if (!JS_InitStandardClasses(aCx, global)) {
  1.2674 +    NS_WARNING("Failed to init standard classes");
  1.2675 +    return nullptr;
  1.2676 +  }
  1.2677 +  */
  1.2678 +
  1.2679 +  JS::Handle<JSObject*> proto = ProtoGetter(aCx, global);
  1.2680 +  NS_ENSURE_TRUE(proto, nullptr);
  1.2681 +
  1.2682 +  if (!JS_SetPrototype(aCx, global, proto)) {
  1.2683 +    NS_WARNING("Failed to set proto");
  1.2684 +    return nullptr;
  1.2685 +  }
  1.2686 +
  1.2687 +  MOZ_ALWAYS_TRUE(TryPreserveWrapper(global));
  1.2688 +
  1.2689 +  MOZ_ASSERT(UnwrapDOMObjectToISupports(global));
  1.2690 +
  1.2691 +  return global;
  1.2692 +}
  1.2693 +
  1.2694 +/*
  1.2695 + * Holds a jsid that is initialized to an interned string, with conversion to
  1.2696 + * Handle<jsid>.
  1.2697 + */
  1.2698 +class InternedStringId
  1.2699 +{
  1.2700 +  jsid id;
  1.2701 +
  1.2702 + public:
  1.2703 +  InternedStringId() : id(JSID_VOID) {}
  1.2704 +
  1.2705 +  bool init(JSContext *cx, const char *string) {
  1.2706 +    JSString* str = JS_InternString(cx, string);
  1.2707 +    if (!str)
  1.2708 +      return false;
  1.2709 +    id = INTERNED_STRING_TO_JSID(cx, str);
  1.2710 +    return true;
  1.2711 +  }
  1.2712 +
  1.2713 +  operator const jsid& () {
  1.2714 +    return id;
  1.2715 +  }
  1.2716 +
  1.2717 +  operator JS::Handle<jsid> () {
  1.2718 +    /* This is safe because we have interned the string. */
  1.2719 +    return JS::Handle<jsid>::fromMarkedLocation(&id);
  1.2720 +  }
  1.2721 +};
  1.2722 +
  1.2723 +bool
  1.2724 +GenericBindingGetter(JSContext* cx, unsigned argc, JS::Value* vp);
  1.2725 +
  1.2726 +bool
  1.2727 +GenericBindingSetter(JSContext* cx, unsigned argc, JS::Value* vp);
  1.2728 +
  1.2729 +bool
  1.2730 +GenericBindingMethod(JSContext* cx, unsigned argc, JS::Value* vp);
  1.2731 +
  1.2732 +bool
  1.2733 +GenericPromiseReturningBindingMethod(JSContext* cx, unsigned argc, JS::Value* vp);
  1.2734 +
  1.2735 +bool
  1.2736 +StaticMethodPromiseWrapper(JSContext* cx, unsigned argc, JS::Value* vp);
  1.2737 +
  1.2738 +// ConvertExceptionToPromise should only be called when we have an error
  1.2739 +// condition (e.g. returned false from a JSAPI method).  Note that there may be
  1.2740 +// no exception on cx, in which case this is an uncatchable failure that will
  1.2741 +// simply be propagated.  Otherwise this method will attempt to convert the
  1.2742 +// exception to a Promise rejected with the exception that it will store in
  1.2743 +// rval.
  1.2744 +//
  1.2745 +// promiseScope should be the scope in which the Promise should be created.
  1.2746 +bool
  1.2747 +ConvertExceptionToPromise(JSContext* cx,
  1.2748 +                          JSObject* promiseScope,
  1.2749 +                          JS::MutableHandle<JS::Value> rval);
  1.2750 +
  1.2751 +} // namespace dom
  1.2752 +} // namespace mozilla
  1.2753 +
  1.2754 +#endif /* mozilla_dom_BindingUtils_h__ */

mercurial