Bug 1732409 let fake:true getUserMedia() parameter override loopback prefs r=jib
[gecko.git] / dom / bindings / BindingUtils.cpp
blob3df0cf9b3802ad7e9cee555508d1f814d2d450b0
1 /* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
2 /* vim: set ts=8 sts=2 et sw=2 tw=80: */
3 /* This Source Code Form is subject to the terms of the Mozilla Public
4 * License, v. 2.0. If a copy of the MPL was not distributed with this file,
5 * You can obtain one at http://mozilla.org/MPL/2.0/. */
7 #include "BindingUtils.h"
9 #include <algorithm>
10 #include <stdarg.h>
12 #include "mozilla/Assertions.h"
13 #include "mozilla/DebugOnly.h"
14 #include "mozilla/Encoding.h"
15 #include "mozilla/FloatingPoint.h"
16 #include "mozilla/Preferences.h"
17 #include "mozilla/ScopeExit.h"
18 #include "mozilla/StaticPrefs_dom.h"
19 #include "mozilla/UniquePtr.h"
20 #include "mozilla/Unused.h"
21 #include "mozilla/UseCounter.h"
23 #include "AccessCheck.h"
24 #include "js/CallAndConstruct.h" // JS::Call, JS::IsCallable
25 #include "js/experimental/JitInfo.h" // JSJit{Getter,Setter,Method}CallArgs, JSJit{Getter,Setter}Op, JSJitInfo
26 #include "js/friend/StackLimits.h" // js::AutoCheckRecursionLimit
27 #include "js/Id.h"
28 #include "js/JSON.h"
29 #include "js/MapAndSet.h"
30 #include "js/Object.h" // JS::GetClass, JS::GetCompartment, JS::GetReservedSlot, JS::SetReservedSlot
31 #include "js/PropertyAndElement.h" // JS_AlreadyHasOwnPropertyById, JS_DefineFunction, JS_DefineFunctionById, JS_DefineFunctions, JS_DefineProperties, JS_DefineProperty, JS_DefinePropertyById, JS_ForwardGetPropertyTo, JS_GetProperty, JS_HasProperty, JS_HasPropertyById
32 #include "js/StableStringChars.h"
33 #include "js/String.h" // JS::GetStringLength, JS::MaxStringLength, JS::StringHasLatin1Chars
34 #include "js/Symbol.h"
35 #include "jsfriendapi.h"
36 #include "nsContentCreatorFunctions.h"
37 #include "nsContentUtils.h"
38 #include "nsGlobalWindow.h"
39 #include "nsHTMLTags.h"
40 #include "nsIDOMGlobalPropertyInitializer.h"
41 #include "nsINode.h"
42 #include "nsIOService.h"
43 #include "nsIPrincipal.h"
44 #include "nsIXPConnect.h"
45 #include "nsUTF8Utils.h"
46 #include "WorkerPrivate.h"
47 #include "WorkerRunnable.h"
48 #include "WrapperFactory.h"
49 #include "xpcprivate.h"
50 #include "XrayWrapper.h"
51 #include "nsPrintfCString.h"
52 #include "mozilla/Sprintf.h"
53 #include "nsReadableUtils.h"
54 #include "nsWrapperCacheInlines.h"
56 #include "mozilla/dom/ScriptSettings.h"
57 #include "mozilla/dom/CustomElementRegistry.h"
58 #include "mozilla/dom/DeprecationReportBody.h"
59 #include "mozilla/dom/DOMException.h"
60 #include "mozilla/dom/ElementBinding.h"
61 #include "mozilla/dom/Exceptions.h"
62 #include "mozilla/dom/HTMLObjectElement.h"
63 #include "mozilla/dom/HTMLObjectElementBinding.h"
64 #include "mozilla/dom/HTMLEmbedElement.h"
65 #include "mozilla/dom/HTMLElementBinding.h"
66 #include "mozilla/dom/HTMLEmbedElementBinding.h"
67 #include "mozilla/dom/MaybeCrossOriginObject.h"
68 #include "mozilla/dom/ReportingUtils.h"
69 #include "mozilla/dom/XULElementBinding.h"
70 #include "mozilla/dom/XULFrameElementBinding.h"
71 #include "mozilla/dom/XULMenuElementBinding.h"
72 #include "mozilla/dom/XULPopupElementBinding.h"
73 #include "mozilla/dom/XULTextElementBinding.h"
74 #include "mozilla/dom/XULTreeElementBinding.h"
75 #include "mozilla/dom/Promise.h"
76 #include "mozilla/dom/WebIDLGlobalNameHash.h"
77 #include "mozilla/dom/WorkerPrivate.h"
78 #include "mozilla/dom/WorkerScope.h"
79 #include "mozilla/dom/XrayExpandoClass.h"
80 #include "mozilla/dom/WindowProxyHolder.h"
81 #include "ipc/ErrorIPCUtils.h"
82 #include "mozilla/UseCounter.h"
83 #include "mozilla/dom/DocGroup.h"
84 #include "nsXULElement.h"
86 namespace mozilla {
87 namespace dom {
89 // Forward declare GetConstructorObject methods.
90 #define HTML_TAG(_tag, _classname, _interfacename) \
91 namespace HTML##_interfacename##Element_Binding { \
92 JSObject* GetConstructorObject(JSContext*); \
94 #define HTML_OTHER(_tag)
95 #include "nsHTMLTagList.h"
96 #undef HTML_TAG
97 #undef HTML_OTHER
99 using constructorGetterCallback = JSObject* (*)(JSContext*);
101 // Mapping of html tag and GetConstructorObject methods.
102 #define HTML_TAG(_tag, _classname, _interfacename) \
103 HTML##_interfacename##Element_Binding::GetConstructorObject,
104 #define HTML_OTHER(_tag) nullptr,
105 // We use eHTMLTag_foo (where foo is the tag) which is defined in nsHTMLTags.h
106 // to index into this array.
107 static const constructorGetterCallback sConstructorGetterCallback[] = {
108 HTMLUnknownElement_Binding::GetConstructorObject,
109 #include "nsHTMLTagList.h"
110 #undef HTML_TAG
111 #undef HTML_OTHER
114 static const JSErrorFormatString ErrorFormatString[] = {
115 #define MSG_DEF(_name, _argc, _has_context, _exn, _str) \
116 {#_name, _str, _argc, _exn},
117 #include "mozilla/dom/Errors.msg"
118 #undef MSG_DEF
121 #define MSG_DEF(_name, _argc, _has_context, _exn, _str) \
122 static_assert( \
123 (_argc) < JS::MaxNumErrorArguments, #_name \
124 " must only have as many error arguments as the JS engine can support");
125 #include "mozilla/dom/Errors.msg"
126 #undef MSG_DEF
128 static const JSErrorFormatString* GetErrorMessage(void* aUserRef,
129 const unsigned aErrorNumber) {
130 MOZ_ASSERT(aErrorNumber < ArrayLength(ErrorFormatString));
131 return &ErrorFormatString[aErrorNumber];
134 uint16_t GetErrorArgCount(const ErrNum aErrorNumber) {
135 return GetErrorMessage(nullptr, aErrorNumber)->argCount;
138 // aErrorNumber needs to be unsigned, not an ErrNum, because the latter makes
139 // va_start have undefined behavior, and we do not want undefined behavior.
140 void binding_detail::ThrowErrorMessage(JSContext* aCx,
141 const unsigned aErrorNumber, ...) {
142 va_list ap;
143 va_start(ap, aErrorNumber);
145 if (!ErrorFormatHasContext[aErrorNumber]) {
146 JS_ReportErrorNumberUTF8VA(aCx, GetErrorMessage, nullptr, aErrorNumber, ap);
147 va_end(ap);
148 return;
151 // Our first arg is the context arg. We want to replace nullptr with empty
152 // string, leave empty string alone, and for anything else append ": " to the
153 // end. See also the behavior of
154 // TErrorResult::SetPendingExceptionWithMessage, which this is mirroring for
155 // exceptions that are thrown directly, not via an ErrorResult.
156 const char* args[JS::MaxNumErrorArguments + 1];
157 size_t argCount = GetErrorArgCount(static_cast<ErrNum>(aErrorNumber));
158 MOZ_ASSERT(argCount > 0, "We have a context arg!");
159 nsAutoCString firstArg;
161 for (size_t i = 0; i < argCount; ++i) {
162 args[i] = va_arg(ap, const char*);
163 if (i == 0) {
164 if (args[0] && *args[0]) {
165 firstArg.Append(args[0]);
166 firstArg.AppendLiteral(": ");
168 args[0] = firstArg.get();
172 JS_ReportErrorNumberUTF8Array(aCx, GetErrorMessage, nullptr, aErrorNumber,
173 args);
174 va_end(ap);
177 static bool ThrowInvalidThis(JSContext* aCx, const JS::CallArgs& aArgs,
178 bool aSecurityError, const char* aInterfaceName) {
179 NS_ConvertASCIItoUTF16 ifaceName(aInterfaceName);
180 // This should only be called for DOM methods/getters/setters, which
181 // are JSNative-backed functions, so we can assume that
182 // JS_ValueToFunction and JS_GetFunctionDisplayId will both return
183 // non-null and that JS_GetStringCharsZ returns non-null.
184 JS::Rooted<JSFunction*> func(aCx, JS_ValueToFunction(aCx, aArgs.calleev()));
185 MOZ_ASSERT(func);
186 JS::Rooted<JSString*> funcName(aCx, JS_GetFunctionDisplayId(func));
187 MOZ_ASSERT(funcName);
188 nsAutoJSString funcNameStr;
189 if (!funcNameStr.init(aCx, funcName)) {
190 return false;
192 if (aSecurityError) {
193 return Throw(aCx, NS_ERROR_DOM_SECURITY_ERR,
194 nsPrintfCString("Permission to call '%s' denied.",
195 NS_ConvertUTF16toUTF8(funcNameStr).get()));
198 const ErrNum errorNumber = MSG_METHOD_THIS_DOES_NOT_IMPLEMENT_INTERFACE;
199 MOZ_RELEASE_ASSERT(GetErrorArgCount(errorNumber) == 2);
200 JS_ReportErrorNumberUC(aCx, GetErrorMessage, nullptr,
201 static_cast<unsigned>(errorNumber), funcNameStr.get(),
202 ifaceName.get());
203 return false;
206 bool ThrowInvalidThis(JSContext* aCx, const JS::CallArgs& aArgs,
207 bool aSecurityError, prototypes::ID aProtoId) {
208 return ThrowInvalidThis(aCx, aArgs, aSecurityError,
209 NamesOfInterfacesWithProtos(aProtoId));
212 bool ThrowNoSetterArg(JSContext* aCx, const JS::CallArgs& aArgs,
213 prototypes::ID aProtoId) {
214 nsPrintfCString errorMessage("%s attribute setter",
215 NamesOfInterfacesWithProtos(aProtoId));
216 return aArgs.requireAtLeast(aCx, errorMessage.get(), 1);
219 } // namespace dom
221 namespace binding_danger {
223 template <typename CleanupPolicy>
224 struct TErrorResult<CleanupPolicy>::Message {
225 Message() : mErrorNumber(dom::Err_Limit) {
226 MOZ_COUNT_CTOR(TErrorResult::Message);
228 ~Message() { MOZ_COUNT_DTOR(TErrorResult::Message); }
230 // UTF-8 strings (probably ASCII in most cases) in mArgs.
231 nsTArray<nsCString> mArgs;
232 dom::ErrNum mErrorNumber;
234 bool HasCorrectNumberOfArguments() {
235 return GetErrorArgCount(mErrorNumber) == mArgs.Length();
238 bool operator==(const TErrorResult<CleanupPolicy>::Message& aRight) const {
239 return mErrorNumber == aRight.mErrorNumber && mArgs == aRight.mArgs;
243 template <typename CleanupPolicy>
244 nsTArray<nsCString>& TErrorResult<CleanupPolicy>::CreateErrorMessageHelper(
245 const dom::ErrNum errorNumber, nsresult errorType) {
246 AssertInOwningThread();
247 mResult = errorType;
249 Message* message = InitMessage(new Message());
250 message->mErrorNumber = errorNumber;
251 return message->mArgs;
254 template <typename CleanupPolicy>
255 void TErrorResult<CleanupPolicy>::SerializeMessage(IPC::Message* aMsg) const {
256 using namespace IPC;
257 AssertInOwningThread();
258 MOZ_ASSERT(mUnionState == HasMessage);
259 MOZ_ASSERT(mExtra.mMessage);
260 WriteParam(aMsg, mExtra.mMessage->mArgs);
261 WriteParam(aMsg, mExtra.mMessage->mErrorNumber);
264 template <typename CleanupPolicy>
265 bool TErrorResult<CleanupPolicy>::DeserializeMessage(const IPC::Message* aMsg,
266 PickleIterator* aIter) {
267 using namespace IPC;
268 AssertInOwningThread();
269 auto readMessage = MakeUnique<Message>();
270 if (!ReadParam(aMsg, aIter, &readMessage->mArgs) ||
271 !ReadParam(aMsg, aIter, &readMessage->mErrorNumber)) {
272 return false;
274 if (!readMessage->HasCorrectNumberOfArguments()) {
275 return false;
278 MOZ_ASSERT(mUnionState == HasNothing);
279 InitMessage(readMessage.release());
280 #ifdef DEBUG
281 mUnionState = HasMessage;
282 #endif // DEBUG
283 return true;
286 template <typename CleanupPolicy>
287 void TErrorResult<CleanupPolicy>::SetPendingExceptionWithMessage(
288 JSContext* aCx, const char* context) {
289 AssertInOwningThread();
290 MOZ_ASSERT(mUnionState == HasMessage);
291 MOZ_ASSERT(mExtra.mMessage,
292 "SetPendingExceptionWithMessage() can be called only once");
294 Message* message = mExtra.mMessage;
295 MOZ_RELEASE_ASSERT(message->HasCorrectNumberOfArguments());
296 if (dom::ErrorFormatHasContext[message->mErrorNumber]) {
297 MOZ_ASSERT(!message->mArgs.IsEmpty(), "How could we have no args here?");
298 MOZ_ASSERT(message->mArgs[0].IsEmpty(), "Context should not be set yet!");
299 if (context) {
300 // Prepend our context and ": "; see API documentation.
301 message->mArgs[0].AssignASCII(context);
302 message->mArgs[0].AppendLiteral(": ");
305 const uint32_t argCount = message->mArgs.Length();
306 const char* args[JS::MaxNumErrorArguments + 1];
307 for (uint32_t i = 0; i < argCount; ++i) {
308 args[i] = message->mArgs.ElementAt(i).get();
310 args[argCount] = nullptr;
312 JS_ReportErrorNumberUTF8Array(aCx, dom::GetErrorMessage, nullptr,
313 static_cast<unsigned>(message->mErrorNumber),
314 argCount > 0 ? args : nullptr);
316 ClearMessage();
317 mResult = NS_OK;
320 template <typename CleanupPolicy>
321 void TErrorResult<CleanupPolicy>::ClearMessage() {
322 AssertInOwningThread();
323 MOZ_ASSERT(IsErrorWithMessage());
324 MOZ_ASSERT(mUnionState == HasMessage);
325 delete mExtra.mMessage;
326 mExtra.mMessage = nullptr;
327 #ifdef DEBUG
328 mUnionState = HasNothing;
329 #endif // DEBUG
332 template <typename CleanupPolicy>
333 void TErrorResult<CleanupPolicy>::ThrowJSException(JSContext* cx,
334 JS::Handle<JS::Value> exn) {
335 AssertInOwningThread();
336 MOZ_ASSERT(mMightHaveUnreportedJSException,
337 "Why didn't you tell us you planned to throw a JS exception?");
339 ClearUnionData();
341 // Make sure mExtra.mJSException is initialized _before_ we try to root it.
342 // But don't set it to exn yet, because we don't want to do that until after
343 // we root.
344 JS::Value& exc = InitJSException();
345 if (!js::AddRawValueRoot(cx, &exc, "TErrorResult::mExtra::mJSException")) {
346 // Don't use NS_ERROR_INTERNAL_ERRORRESULT_JS_EXCEPTION, because that
347 // indicates we have in fact rooted mExtra.mJSException.
348 mResult = NS_ERROR_OUT_OF_MEMORY;
349 } else {
350 exc = exn;
351 mResult = NS_ERROR_INTERNAL_ERRORRESULT_JS_EXCEPTION;
352 #ifdef DEBUG
353 mUnionState = HasJSException;
354 #endif // DEBUG
358 template <typename CleanupPolicy>
359 void TErrorResult<CleanupPolicy>::SetPendingJSException(JSContext* cx) {
360 AssertInOwningThread();
361 MOZ_ASSERT(!mMightHaveUnreportedJSException,
362 "Why didn't you tell us you planned to handle JS exceptions?");
363 MOZ_ASSERT(mUnionState == HasJSException);
365 JS::Rooted<JS::Value> exception(cx, mExtra.mJSException);
366 if (JS_WrapValue(cx, &exception)) {
367 JS_SetPendingException(cx, exception);
369 mExtra.mJSException = exception;
370 // If JS_WrapValue failed, not much we can do about it... No matter
371 // what, go ahead and unroot mExtra.mJSException.
372 js::RemoveRawValueRoot(cx, &mExtra.mJSException);
374 mResult = NS_OK;
375 #ifdef DEBUG
376 mUnionState = HasNothing;
377 #endif // DEBUG
380 template <typename CleanupPolicy>
381 struct TErrorResult<CleanupPolicy>::DOMExceptionInfo {
382 DOMExceptionInfo(nsresult rv, const nsACString& message)
383 : mMessage(message), mRv(rv) {}
385 nsCString mMessage;
386 nsresult mRv;
388 bool operator==(
389 const TErrorResult<CleanupPolicy>::DOMExceptionInfo& aRight) const {
390 return mRv == aRight.mRv && mMessage == aRight.mMessage;
394 template <typename CleanupPolicy>
395 void TErrorResult<CleanupPolicy>::SerializeDOMExceptionInfo(
396 IPC::Message* aMsg) const {
397 using namespace IPC;
398 AssertInOwningThread();
399 MOZ_ASSERT(mUnionState == HasDOMExceptionInfo);
400 MOZ_ASSERT(mExtra.mDOMExceptionInfo);
401 WriteParam(aMsg, mExtra.mDOMExceptionInfo->mMessage);
402 WriteParam(aMsg, mExtra.mDOMExceptionInfo->mRv);
405 template <typename CleanupPolicy>
406 bool TErrorResult<CleanupPolicy>::DeserializeDOMExceptionInfo(
407 const IPC::Message* aMsg, PickleIterator* aIter) {
408 using namespace IPC;
409 AssertInOwningThread();
410 nsCString message;
411 nsresult rv;
412 if (!ReadParam(aMsg, aIter, &message) || !ReadParam(aMsg, aIter, &rv)) {
413 return false;
416 MOZ_ASSERT(mUnionState == HasNothing);
417 MOZ_ASSERT(IsDOMException());
418 InitDOMExceptionInfo(new DOMExceptionInfo(rv, message));
419 #ifdef DEBUG
420 mUnionState = HasDOMExceptionInfo;
421 #endif // DEBUG
422 return true;
425 template <typename CleanupPolicy>
426 void TErrorResult<CleanupPolicy>::ThrowDOMException(nsresult rv,
427 const nsACString& message) {
428 AssertInOwningThread();
429 ClearUnionData();
431 mResult = NS_ERROR_INTERNAL_ERRORRESULT_DOMEXCEPTION;
432 InitDOMExceptionInfo(new DOMExceptionInfo(rv, message));
433 #ifdef DEBUG
434 mUnionState = HasDOMExceptionInfo;
435 #endif
438 template <typename CleanupPolicy>
439 void TErrorResult<CleanupPolicy>::SetPendingDOMException(JSContext* cx,
440 const char* context) {
441 AssertInOwningThread();
442 MOZ_ASSERT(mUnionState == HasDOMExceptionInfo);
443 MOZ_ASSERT(mExtra.mDOMExceptionInfo,
444 "SetPendingDOMException() can be called only once");
446 if (context && !mExtra.mDOMExceptionInfo->mMessage.IsEmpty()) {
447 // Prepend our context and ": "; see API documentation.
448 nsAutoCString prefix(context);
449 prefix.AppendLiteral(": ");
450 mExtra.mDOMExceptionInfo->mMessage.Insert(prefix, 0);
453 dom::Throw(cx, mExtra.mDOMExceptionInfo->mRv,
454 mExtra.mDOMExceptionInfo->mMessage);
456 ClearDOMExceptionInfo();
457 mResult = NS_OK;
460 template <typename CleanupPolicy>
461 void TErrorResult<CleanupPolicy>::ClearDOMExceptionInfo() {
462 AssertInOwningThread();
463 MOZ_ASSERT(IsDOMException());
464 MOZ_ASSERT(mUnionState == HasDOMExceptionInfo);
465 delete mExtra.mDOMExceptionInfo;
466 mExtra.mDOMExceptionInfo = nullptr;
467 #ifdef DEBUG
468 mUnionState = HasNothing;
469 #endif // DEBUG
472 template <typename CleanupPolicy>
473 void TErrorResult<CleanupPolicy>::ClearUnionData() {
474 AssertInOwningThread();
475 if (IsJSException()) {
476 JSContext* cx = dom::danger::GetJSContext();
477 MOZ_ASSERT(cx);
478 mExtra.mJSException.setUndefined();
479 js::RemoveRawValueRoot(cx, &mExtra.mJSException);
480 #ifdef DEBUG
481 mUnionState = HasNothing;
482 #endif // DEBUG
483 } else if (IsErrorWithMessage()) {
484 ClearMessage();
485 } else if (IsDOMException()) {
486 ClearDOMExceptionInfo();
490 template <typename CleanupPolicy>
491 void TErrorResult<CleanupPolicy>::SetPendingGenericErrorException(
492 JSContext* cx) {
493 AssertInOwningThread();
494 MOZ_ASSERT(!IsErrorWithMessage());
495 MOZ_ASSERT(!IsJSException());
496 MOZ_ASSERT(!IsDOMException());
497 dom::Throw(cx, ErrorCode());
498 mResult = NS_OK;
501 template <typename CleanupPolicy>
502 TErrorResult<CleanupPolicy>& TErrorResult<CleanupPolicy>::operator=(
503 TErrorResult<CleanupPolicy>&& aRHS) {
504 AssertInOwningThread();
505 aRHS.AssertInOwningThread();
506 // Clear out any union members we may have right now, before we
507 // start writing to it.
508 ClearUnionData();
510 #ifdef DEBUG
511 mMightHaveUnreportedJSException = aRHS.mMightHaveUnreportedJSException;
512 aRHS.mMightHaveUnreportedJSException = false;
513 #endif
514 if (aRHS.IsErrorWithMessage()) {
515 InitMessage(aRHS.mExtra.mMessage);
516 aRHS.mExtra.mMessage = nullptr;
517 } else if (aRHS.IsJSException()) {
518 JSContext* cx = dom::danger::GetJSContext();
519 MOZ_ASSERT(cx);
520 JS::Value& exn = InitJSException();
521 if (!js::AddRawValueRoot(cx, &exn, "TErrorResult::mExtra::mJSException")) {
522 MOZ_CRASH("Could not root mExtra.mJSException, we're about to OOM");
524 mExtra.mJSException = aRHS.mExtra.mJSException;
525 aRHS.mExtra.mJSException.setUndefined();
526 js::RemoveRawValueRoot(cx, &aRHS.mExtra.mJSException);
527 } else if (aRHS.IsDOMException()) {
528 InitDOMExceptionInfo(aRHS.mExtra.mDOMExceptionInfo);
529 aRHS.mExtra.mDOMExceptionInfo = nullptr;
530 } else {
531 // Null out the union on both sides for hygiene purposes. This is purely
532 // precautionary, so InitMessage/placement-new is unnecessary.
533 mExtra.mMessage = aRHS.mExtra.mMessage = nullptr;
536 #ifdef DEBUG
537 mUnionState = aRHS.mUnionState;
538 aRHS.mUnionState = HasNothing;
539 #endif // DEBUG
541 // Note: It's important to do this last, since this affects the condition
542 // checks above!
543 mResult = aRHS.mResult;
544 aRHS.mResult = NS_OK;
545 return *this;
548 template <typename CleanupPolicy>
549 bool TErrorResult<CleanupPolicy>::operator==(const ErrorResult& aRight) const {
550 auto right = reinterpret_cast<const TErrorResult<CleanupPolicy>*>(&aRight);
552 if (mResult != right->mResult) {
553 return false;
556 if (IsJSException()) {
557 // js exceptions are always non-equal
558 return false;
561 if (IsErrorWithMessage()) {
562 return *mExtra.mMessage == *right->mExtra.mMessage;
565 if (IsDOMException()) {
566 return *mExtra.mDOMExceptionInfo == *right->mExtra.mDOMExceptionInfo;
569 return true;
572 template <typename CleanupPolicy>
573 void TErrorResult<CleanupPolicy>::CloneTo(TErrorResult& aRv) const {
574 AssertInOwningThread();
575 aRv.AssertInOwningThread();
576 aRv.ClearUnionData();
577 aRv.mResult = mResult;
578 #ifdef DEBUG
579 aRv.mMightHaveUnreportedJSException = mMightHaveUnreportedJSException;
580 #endif
582 if (IsErrorWithMessage()) {
583 #ifdef DEBUG
584 aRv.mUnionState = HasMessage;
585 #endif
586 Message* message = aRv.InitMessage(new Message());
587 message->mArgs = mExtra.mMessage->mArgs.Clone();
588 message->mErrorNumber = mExtra.mMessage->mErrorNumber;
589 } else if (IsDOMException()) {
590 #ifdef DEBUG
591 aRv.mUnionState = HasDOMExceptionInfo;
592 #endif
593 auto* exnInfo = new DOMExceptionInfo(mExtra.mDOMExceptionInfo->mRv,
594 mExtra.mDOMExceptionInfo->mMessage);
595 aRv.InitDOMExceptionInfo(exnInfo);
596 } else if (IsJSException()) {
597 #ifdef DEBUG
598 aRv.mUnionState = HasJSException;
599 #endif
600 JSContext* cx = dom::danger::GetJSContext();
601 JS::Rooted<JS::Value> exception(cx, mExtra.mJSException);
602 aRv.ThrowJSException(cx, exception);
606 template <typename CleanupPolicy>
607 void TErrorResult<CleanupPolicy>::SuppressException() {
608 AssertInOwningThread();
609 WouldReportJSException();
610 ClearUnionData();
611 // We don't use AssignErrorCode, because we want to override existing error
612 // states, which AssignErrorCode is not allowed to do.
613 mResult = NS_OK;
616 template <typename CleanupPolicy>
617 void TErrorResult<CleanupPolicy>::SetPendingException(JSContext* cx,
618 const char* context) {
619 AssertInOwningThread();
620 if (IsUncatchableException()) {
621 // Nuke any existing exception on cx, to make sure we're uncatchable.
622 JS_ClearPendingException(cx);
623 // Don't do any reporting. Just return, to create an
624 // uncatchable exception.
625 mResult = NS_OK;
626 return;
628 if (IsJSContextException()) {
629 // Whatever we need to throw is on the JSContext already.
630 MOZ_ASSERT(JS_IsExceptionPending(cx));
631 mResult = NS_OK;
632 return;
634 if (IsErrorWithMessage()) {
635 SetPendingExceptionWithMessage(cx, context);
636 return;
638 if (IsJSException()) {
639 SetPendingJSException(cx);
640 return;
642 if (IsDOMException()) {
643 SetPendingDOMException(cx, context);
644 return;
646 SetPendingGenericErrorException(cx);
649 template <typename CleanupPolicy>
650 void TErrorResult<CleanupPolicy>::StealExceptionFromJSContext(JSContext* cx) {
651 AssertInOwningThread();
652 MOZ_ASSERT(mMightHaveUnreportedJSException,
653 "Why didn't you tell us you planned to throw a JS exception?");
655 JS::Rooted<JS::Value> exn(cx);
656 if (!JS_GetPendingException(cx, &exn)) {
657 ThrowUncatchableException();
658 return;
661 ThrowJSException(cx, exn);
662 JS_ClearPendingException(cx);
665 template <typename CleanupPolicy>
666 void TErrorResult<CleanupPolicy>::NoteJSContextException(JSContext* aCx) {
667 AssertInOwningThread();
668 if (JS_IsExceptionPending(aCx)) {
669 mResult = NS_ERROR_INTERNAL_ERRORRESULT_EXCEPTION_ON_JSCONTEXT;
670 } else {
671 mResult = NS_ERROR_UNCATCHABLE_EXCEPTION;
675 /* static */
676 template <typename CleanupPolicy>
677 void TErrorResult<CleanupPolicy>::EnsureUTF8Validity(nsCString& aValue,
678 size_t aValidUpTo) {
679 nsCString valid;
680 if (NS_SUCCEEDED(UTF_8_ENCODING->DecodeWithoutBOMHandling(aValue, valid,
681 aValidUpTo))) {
682 aValue = valid;
683 } else {
684 aValue.SetLength(aValidUpTo);
688 template class TErrorResult<JustAssertCleanupPolicy>;
689 template class TErrorResult<AssertAndSuppressCleanupPolicy>;
690 template class TErrorResult<JustSuppressCleanupPolicy>;
691 template class TErrorResult<ThreadSafeJustSuppressCleanupPolicy>;
693 } // namespace binding_danger
695 namespace dom {
697 bool DefineConstants(JSContext* cx, JS::Handle<JSObject*> obj,
698 const ConstantSpec* cs) {
699 JS::Rooted<JS::Value> value(cx);
700 for (; cs->name; ++cs) {
701 value = cs->value;
702 bool ok = JS_DefineProperty(
703 cx, obj, cs->name, value,
704 JSPROP_ENUMERATE | JSPROP_READONLY | JSPROP_PERMANENT);
705 if (!ok) {
706 return false;
709 return true;
712 static inline bool Define(JSContext* cx, JS::Handle<JSObject*> obj,
713 const JSFunctionSpec* spec) {
714 return JS_DefineFunctions(cx, obj, spec);
716 static inline bool Define(JSContext* cx, JS::Handle<JSObject*> obj,
717 const JSPropertySpec* spec) {
718 return JS_DefineProperties(cx, obj, spec);
720 static inline bool Define(JSContext* cx, JS::Handle<JSObject*> obj,
721 const ConstantSpec* spec) {
722 return DefineConstants(cx, obj, spec);
725 template <typename T>
726 bool DefinePrefable(JSContext* cx, JS::Handle<JSObject*> obj,
727 const Prefable<T>* props) {
728 MOZ_ASSERT(props);
729 MOZ_ASSERT(props->specs);
730 do {
731 // Define if enabled
732 if (props->isEnabled(cx, obj)) {
733 if (!Define(cx, obj, props->specs)) {
734 return false;
737 } while ((++props)->specs);
738 return true;
741 bool DefineLegacyUnforgeableMethods(
742 JSContext* cx, JS::Handle<JSObject*> obj,
743 const Prefable<const JSFunctionSpec>* props) {
744 return DefinePrefable(cx, obj, props);
747 bool DefineLegacyUnforgeableAttributes(
748 JSContext* cx, JS::Handle<JSObject*> obj,
749 const Prefable<const JSPropertySpec>* props) {
750 return DefinePrefable(cx, obj, props);
753 // We should use JSFunction objects for interface objects, but we need a custom
754 // hasInstance hook because we have new interface objects on prototype chains of
755 // old (XPConnect-based) bindings. We also need Xrays and arbitrary numbers of
756 // reserved slots (e.g. for named constructors). So we define a custom
757 // funToString ObjectOps member for interface objects.
758 JSString* InterfaceObjectToString(JSContext* aCx, JS::Handle<JSObject*> aObject,
759 bool /* isToSource */) {
760 const JSClass* clasp = JS::GetClass(aObject);
761 MOZ_ASSERT(IsDOMIfaceAndProtoClass(clasp));
763 const DOMIfaceAndProtoJSClass* ifaceAndProtoJSClass =
764 DOMIfaceAndProtoJSClass::FromJSClass(clasp);
765 return JS_NewStringCopyZ(aCx, ifaceAndProtoJSClass->mFunToString);
768 bool Constructor(JSContext* cx, unsigned argc, JS::Value* vp) {
769 JS::CallArgs args = JS::CallArgsFromVp(argc, vp);
770 const JS::Value& v = js::GetFunctionNativeReserved(
771 &args.callee(), CONSTRUCTOR_NATIVE_HOLDER_RESERVED_SLOT);
772 const JSNativeHolder* nativeHolder =
773 static_cast<const JSNativeHolder*>(v.toPrivate());
774 return (nativeHolder->mNative)(cx, argc, vp);
777 static JSObject* CreateConstructor(JSContext* cx, JS::Handle<JSObject*> global,
778 const char* name,
779 const JSNativeHolder* nativeHolder,
780 unsigned ctorNargs) {
781 JSFunction* fun = js::NewFunctionWithReserved(cx, Constructor, ctorNargs,
782 JSFUN_CONSTRUCTOR, name);
783 if (!fun) {
784 return nullptr;
787 JSObject* constructor = JS_GetFunctionObject(fun);
788 js::SetFunctionNativeReserved(
789 constructor, CONSTRUCTOR_NATIVE_HOLDER_RESERVED_SLOT,
790 JS::PrivateValue(const_cast<JSNativeHolder*>(nativeHolder)));
791 return constructor;
794 static bool DefineConstructor(JSContext* cx, JS::Handle<JSObject*> global,
795 JS::Handle<jsid> name,
796 JS::Handle<JSObject*> constructor) {
797 bool alreadyDefined;
798 if (!JS_AlreadyHasOwnPropertyById(cx, global, name, &alreadyDefined)) {
799 return false;
802 // This is Enumerable: False per spec.
803 return alreadyDefined ||
804 JS_DefinePropertyById(cx, global, name, constructor, JSPROP_RESOLVING);
807 static bool DefineConstructor(JSContext* cx, JS::Handle<JSObject*> global,
808 const char* name,
809 JS::Handle<JSObject*> constructor) {
810 JSString* nameStr = JS_AtomizeString(cx, name);
811 if (!nameStr) {
812 return false;
814 JS::Rooted<JS::PropertyKey> nameKey(cx,
815 JS::PropertyKey::fromNonIntAtom(nameStr));
816 return DefineConstructor(cx, global, nameKey, constructor);
819 // name must be an atom (or JS::PropertyKey::fromNonIntAtom will assert).
820 static JSObject* CreateInterfaceObject(
821 JSContext* cx, JS::Handle<JSObject*> global,
822 JS::Handle<JSObject*> constructorProto, const JSClass* constructorClass,
823 unsigned ctorNargs, const LegacyFactoryFunction* namedConstructors,
824 JS::Handle<JSObject*> proto, const NativeProperties* properties,
825 const NativeProperties* chromeOnlyProperties, JS::Handle<JSString*> name,
826 bool isChrome, bool defineOnGlobal, const char* const* legacyWindowAliases,
827 bool isNamespace) {
828 JS::Rooted<JSObject*> constructor(cx);
829 MOZ_ASSERT(constructorProto);
830 MOZ_ASSERT(constructorClass);
831 constructor =
832 JS_NewObjectWithGivenProto(cx, constructorClass, constructorProto);
833 if (!constructor) {
834 return nullptr;
837 if (!isNamespace) {
838 if (!JS_DefineProperty(cx, constructor, "length", ctorNargs,
839 JSPROP_READONLY)) {
840 return nullptr;
843 if (!JS_DefineProperty(cx, constructor, "name", name, JSPROP_READONLY)) {
844 return nullptr;
848 if (DOMIfaceAndProtoJSClass::FromJSClass(constructorClass)
849 ->wantsInterfaceHasInstance) {
850 if (isChrome ||
851 StaticPrefs::dom_webidl_crosscontext_hasinstance_enabled()) {
852 JS::Rooted<jsid> hasInstanceId(cx, SYMBOL_TO_JSID(JS::GetWellKnownSymbol(
853 cx, JS::SymbolCode::hasInstance)));
854 if (!JS_DefineFunctionById(
855 cx, constructor, hasInstanceId, InterfaceHasInstance, 1,
856 // Flags match those of Function[Symbol.hasInstance]
857 JSPROP_READONLY | JSPROP_PERMANENT)) {
858 return nullptr;
862 if (isChrome && !JS_DefineFunction(cx, constructor, "isInstance",
863 InterfaceIsInstance, 1,
864 // Don't bother making it enumerable
865 0)) {
866 return nullptr;
870 if (properties) {
871 if (properties->HasStaticMethods() &&
872 !DefinePrefable(cx, constructor, properties->StaticMethods())) {
873 return nullptr;
876 if (properties->HasStaticAttributes() &&
877 !DefinePrefable(cx, constructor, properties->StaticAttributes())) {
878 return nullptr;
881 if (properties->HasConstants() &&
882 !DefinePrefable(cx, constructor, properties->Constants())) {
883 return nullptr;
887 if (chromeOnlyProperties && isChrome) {
888 if (chromeOnlyProperties->HasStaticMethods() &&
889 !DefinePrefable(cx, constructor,
890 chromeOnlyProperties->StaticMethods())) {
891 return nullptr;
894 if (chromeOnlyProperties->HasStaticAttributes() &&
895 !DefinePrefable(cx, constructor,
896 chromeOnlyProperties->StaticAttributes())) {
897 return nullptr;
900 if (chromeOnlyProperties->HasConstants() &&
901 !DefinePrefable(cx, constructor, chromeOnlyProperties->Constants())) {
902 return nullptr;
906 if (proto && !JS_LinkConstructorAndPrototype(cx, constructor, proto)) {
907 return nullptr;
910 JS::Rooted<jsid> nameStr(cx, JS::PropertyKey::fromNonIntAtom(name));
911 if (defineOnGlobal && !DefineConstructor(cx, global, nameStr, constructor)) {
912 return nullptr;
915 if (legacyWindowAliases && NS_IsMainThread()) {
916 for (; *legacyWindowAliases; ++legacyWindowAliases) {
917 if (!DefineConstructor(cx, global, *legacyWindowAliases, constructor)) {
918 return nullptr;
923 if (namedConstructors) {
924 int namedConstructorSlot = DOM_INTERFACE_SLOTS_BASE;
925 while (namedConstructors->mName) {
926 JS::Rooted<JSObject*> namedConstructor(
927 cx, CreateConstructor(cx, global, namedConstructors->mName,
928 &namedConstructors->mHolder,
929 namedConstructors->mNargs));
930 if (!namedConstructor ||
931 !JS_DefineProperty(cx, namedConstructor, "prototype", proto,
932 JSPROP_PERMANENT | JSPROP_READONLY) ||
933 (defineOnGlobal &&
934 !DefineConstructor(cx, global, namedConstructors->mName,
935 namedConstructor))) {
936 return nullptr;
938 JS::SetReservedSlot(constructor, namedConstructorSlot++,
939 JS::ObjectValue(*namedConstructor));
940 ++namedConstructors;
944 return constructor;
947 static JSObject* CreateInterfacePrototypeObject(
948 JSContext* cx, JS::Handle<JSObject*> global,
949 JS::Handle<JSObject*> parentProto, const JSClass* protoClass,
950 const NativeProperties* properties,
951 const NativeProperties* chromeOnlyProperties,
952 const char* const* unscopableNames, JS::Handle<JSString*> name,
953 bool isGlobal) {
954 JS::Rooted<JSObject*> ourProto(
955 cx, JS_NewObjectWithGivenProto(cx, protoClass, parentProto));
956 if (!ourProto ||
957 // We don't try to define properties on the global's prototype; those
958 // properties go on the global itself.
959 (!isGlobal &&
960 !DefineProperties(cx, ourProto, properties, chromeOnlyProperties))) {
961 return nullptr;
964 if (unscopableNames) {
965 JS::Rooted<JSObject*> unscopableObj(
966 cx, JS_NewObjectWithGivenProto(cx, nullptr, nullptr));
967 if (!unscopableObj) {
968 return nullptr;
971 for (; *unscopableNames; ++unscopableNames) {
972 if (!JS_DefineProperty(cx, unscopableObj, *unscopableNames,
973 JS::TrueHandleValue, JSPROP_ENUMERATE)) {
974 return nullptr;
978 JS::Rooted<jsid> unscopableId(cx, SYMBOL_TO_JSID(JS::GetWellKnownSymbol(
979 cx, JS::SymbolCode::unscopables)));
980 // Readonly and non-enumerable to match Array.prototype.
981 if (!JS_DefinePropertyById(cx, ourProto, unscopableId, unscopableObj,
982 JSPROP_READONLY)) {
983 return nullptr;
987 JS::Rooted<jsid> toStringTagId(cx, SYMBOL_TO_JSID(JS::GetWellKnownSymbol(
988 cx, JS::SymbolCode::toStringTag)));
989 if (!JS_DefinePropertyById(cx, ourProto, toStringTagId, name,
990 JSPROP_READONLY)) {
991 return nullptr;
994 return ourProto;
997 bool DefineProperties(JSContext* cx, JS::Handle<JSObject*> obj,
998 const NativeProperties* properties,
999 const NativeProperties* chromeOnlyProperties) {
1000 if (properties) {
1001 if (properties->HasMethods() &&
1002 !DefinePrefable(cx, obj, properties->Methods())) {
1003 return false;
1006 if (properties->HasAttributes() &&
1007 !DefinePrefable(cx, obj, properties->Attributes())) {
1008 return false;
1011 if (properties->HasConstants() &&
1012 !DefinePrefable(cx, obj, properties->Constants())) {
1013 return false;
1017 if (chromeOnlyProperties) {
1018 if (chromeOnlyProperties->HasMethods() &&
1019 !DefinePrefable(cx, obj, chromeOnlyProperties->Methods())) {
1020 return false;
1023 if (chromeOnlyProperties->HasAttributes() &&
1024 !DefinePrefable(cx, obj, chromeOnlyProperties->Attributes())) {
1025 return false;
1028 if (chromeOnlyProperties->HasConstants() &&
1029 !DefinePrefable(cx, obj, chromeOnlyProperties->Constants())) {
1030 return false;
1034 return true;
1037 void CreateInterfaceObjects(
1038 JSContext* cx, JS::Handle<JSObject*> global,
1039 JS::Handle<JSObject*> protoProto, const JSClass* protoClass,
1040 JS::Heap<JSObject*>* protoCache, JS::Handle<JSObject*> constructorProto,
1041 const JSClass* constructorClass, unsigned ctorNargs,
1042 const LegacyFactoryFunction* namedConstructors,
1043 JS::Heap<JSObject*>* constructorCache, const NativeProperties* properties,
1044 const NativeProperties* chromeOnlyProperties, const char* name,
1045 bool defineOnGlobal, const char* const* unscopableNames, bool isGlobal,
1046 const char* const* legacyWindowAliases, bool isNamespace) {
1047 MOZ_ASSERT(protoClass || constructorClass, "Need at least one class!");
1048 MOZ_ASSERT(
1049 !((properties &&
1050 (properties->HasMethods() || properties->HasAttributes())) ||
1051 (chromeOnlyProperties && (chromeOnlyProperties->HasMethods() ||
1052 chromeOnlyProperties->HasAttributes()))) ||
1053 protoClass,
1054 "Methods or properties but no protoClass!");
1055 MOZ_ASSERT(!((properties && (properties->HasStaticMethods() ||
1056 properties->HasStaticAttributes())) ||
1057 (chromeOnlyProperties &&
1058 (chromeOnlyProperties->HasStaticMethods() ||
1059 chromeOnlyProperties->HasStaticAttributes()))) ||
1060 constructorClass,
1061 "Static methods but no constructorClass!");
1062 MOZ_ASSERT(!protoClass == !protoCache,
1063 "If, and only if, there is an interface prototype object we need "
1064 "to cache it");
1065 MOZ_ASSERT(bool(constructorClass) == bool(constructorCache),
1066 "If, and only if, there is an interface object we need to cache "
1067 "it");
1068 MOZ_ASSERT(constructorProto || !constructorClass,
1069 "Must have a constructor proto if we plan to create a constructor "
1070 "object");
1072 bool isChrome = nsContentUtils::ThreadsafeIsSystemCaller(cx);
1074 JS::Rooted<JSString*> nameStr(cx, JS_AtomizeString(cx, name));
1075 if (!nameStr) {
1076 return;
1079 JS::Rooted<JSObject*> proto(cx);
1080 if (protoClass) {
1081 proto = CreateInterfacePrototypeObject(
1082 cx, global, protoProto, protoClass, properties,
1083 isChrome ? chromeOnlyProperties : nullptr, unscopableNames, nameStr,
1084 isGlobal);
1085 if (!proto) {
1086 return;
1089 *protoCache = proto;
1090 } else {
1091 MOZ_ASSERT(!proto);
1094 JSObject* interface;
1095 if (constructorClass) {
1096 interface = CreateInterfaceObject(
1097 cx, global, constructorProto, constructorClass, ctorNargs,
1098 namedConstructors, proto, properties, chromeOnlyProperties, nameStr,
1099 isChrome, defineOnGlobal, legacyWindowAliases, isNamespace);
1100 if (!interface) {
1101 if (protoCache) {
1102 // If we fail we need to make sure to clear the value of protoCache we
1103 // set above.
1104 *protoCache = nullptr;
1106 return;
1108 *constructorCache = interface;
1112 // Only set aAllowNativeWrapper to false if you really know you need it; if in
1113 // doubt use true. Setting it to false disables security wrappers.
1114 static bool NativeInterface2JSObjectAndThrowIfFailed(
1115 JSContext* aCx, JS::Handle<JSObject*> aScope,
1116 JS::MutableHandle<JS::Value> aRetval, xpcObjectHelper& aHelper,
1117 const nsIID* aIID, bool aAllowNativeWrapper) {
1118 js::AssertSameCompartment(aCx, aScope);
1119 nsresult rv;
1120 // Inline some logic from XPCConvert::NativeInterfaceToJSObject that we need
1121 // on all threads.
1122 nsWrapperCache* cache = aHelper.GetWrapperCache();
1124 if (cache) {
1125 JS::Rooted<JSObject*> obj(aCx, cache->GetWrapper());
1126 if (!obj) {
1127 obj = cache->WrapObject(aCx, nullptr);
1128 if (!obj) {
1129 return Throw(aCx, NS_ERROR_UNEXPECTED);
1133 if (aAllowNativeWrapper && !JS_WrapObject(aCx, &obj)) {
1134 return false;
1137 aRetval.setObject(*obj);
1138 return true;
1141 MOZ_ASSERT(NS_IsMainThread());
1143 if (!XPCConvert::NativeInterface2JSObject(aCx, aRetval, aHelper, aIID,
1144 aAllowNativeWrapper, &rv)) {
1145 // I can't tell if NativeInterface2JSObject throws JS exceptions
1146 // or not. This is a sloppy stab at the right semantics; the
1147 // method really ought to be fixed to behave consistently.
1148 if (!JS_IsExceptionPending(aCx)) {
1149 Throw(aCx, NS_FAILED(rv) ? rv : NS_ERROR_UNEXPECTED);
1151 return false;
1153 return true;
1156 bool TryPreserveWrapper(JS::Handle<JSObject*> obj) {
1157 MOZ_ASSERT(IsDOMObject(obj));
1159 // nsISupports objects are special cased because DOM proxies are nsISupports
1160 // and have addProperty hooks that do more than wrapper preservation (so we
1161 // don't want to call them).
1162 if (nsISupports* native = UnwrapDOMObjectToISupports(obj)) {
1163 nsWrapperCache* cache = nullptr;
1164 CallQueryInterface(native, &cache);
1165 if (cache) {
1166 cache->PreserveWrapper(native);
1168 return true;
1171 // The addProperty hook for WebIDL classes does wrapper preservation, and
1172 // nothing else, so call it, if present.
1174 const JSClass* clasp = JS::GetClass(obj);
1175 const DOMJSClass* domClass = GetDOMClass(clasp);
1177 // We expect all proxies to be nsISupports.
1178 MOZ_RELEASE_ASSERT(clasp->isNativeObject(),
1179 "Should not call addProperty for proxies.");
1181 JSAddPropertyOp addProperty = clasp->getAddProperty();
1182 if (!addProperty) {
1183 return true;
1186 // The class should have an addProperty hook iff it is a CC participant.
1187 MOZ_RELEASE_ASSERT(domClass->mParticipant);
1189 JS::Rooted<jsid> dummyId(RootingCx());
1190 JS::Rooted<JS::Value> dummyValue(RootingCx());
1191 return addProperty(nullptr, obj, dummyId, dummyValue);
1194 bool HasReleasedWrapper(JS::Handle<JSObject*> obj) {
1195 MOZ_ASSERT(obj);
1196 MOZ_ASSERT(IsDOMObject(obj));
1198 nsWrapperCache* cache = nullptr;
1199 if (nsISupports* native = UnwrapDOMObjectToISupports(obj)) {
1200 CallQueryInterface(native, &cache);
1201 } else {
1202 const JSClass* clasp = JS::GetClass(obj);
1203 const DOMJSClass* domClass = GetDOMClass(clasp);
1205 // We expect all proxies to be nsISupports.
1206 MOZ_RELEASE_ASSERT(clasp->isNativeObject(),
1207 "Should not call getWrapperCache for proxies.");
1209 WrapperCacheGetter getter = domClass->mWrapperCacheGetter;
1211 if (getter) {
1212 // If the class has a wrapper cache getter it must be a CC participant.
1213 MOZ_RELEASE_ASSERT(domClass->mParticipant);
1215 cache = getter(obj);
1219 return cache && !cache->PreservingWrapper();
1222 // Can only be called with a DOM JSClass.
1223 bool InstanceClassHasProtoAtDepth(const JSClass* clasp, uint32_t protoID,
1224 uint32_t depth) {
1225 const DOMJSClass* domClass = DOMJSClass::FromJSClass(clasp);
1226 return static_cast<uint32_t>(domClass->mInterfaceChain[depth]) == protoID;
1229 // Only set allowNativeWrapper to false if you really know you need it; if in
1230 // doubt use true. Setting it to false disables security wrappers.
1231 bool XPCOMObjectToJsval(JSContext* cx, JS::Handle<JSObject*> scope,
1232 xpcObjectHelper& helper, const nsIID* iid,
1233 bool allowNativeWrapper,
1234 JS::MutableHandle<JS::Value> rval) {
1235 return NativeInterface2JSObjectAndThrowIfFailed(cx, scope, rval, helper, iid,
1236 allowNativeWrapper);
1239 bool VariantToJsval(JSContext* aCx, nsIVariant* aVariant,
1240 JS::MutableHandle<JS::Value> aRetval) {
1241 nsresult rv;
1242 if (!XPCVariant::VariantDataToJS(aCx, aVariant, &rv, aRetval)) {
1243 // Does it throw? Who knows
1244 if (!JS_IsExceptionPending(aCx)) {
1245 Throw(aCx, NS_FAILED(rv) ? rv : NS_ERROR_UNEXPECTED);
1247 return false;
1250 return true;
1253 bool WrapObject(JSContext* cx, const WindowProxyHolder& p,
1254 JS::MutableHandle<JS::Value> rval) {
1255 return ToJSValue(cx, p, rval);
1258 static int CompareIdsAtIndices(const void* aElement1, const void* aElement2,
1259 void* aClosure) {
1260 const uint16_t index1 = *static_cast<const uint16_t*>(aElement1);
1261 const uint16_t index2 = *static_cast<const uint16_t*>(aElement2);
1262 const PropertyInfo* infos = static_cast<PropertyInfo*>(aClosure);
1264 MOZ_ASSERT(JSID_BITS(infos[index1].Id()) != JSID_BITS(infos[index2].Id()));
1266 return JSID_BITS(infos[index1].Id()) < JSID_BITS(infos[index2].Id()) ? -1 : 1;
1269 // {JSPropertySpec,JSFunctionSpec} use {JSPropertySpec,JSFunctionSpec}::Name
1270 // and ConstantSpec uses `const char*` for name field.
1271 static inline JSPropertySpec::Name ToPropertySpecName(
1272 JSPropertySpec::Name name) {
1273 return name;
1276 static inline JSPropertySpec::Name ToPropertySpecName(const char* name) {
1277 return JSPropertySpec::Name(name);
1280 template <typename SpecT>
1281 static bool InitPropertyInfos(JSContext* cx, const Prefable<SpecT>* pref,
1282 PropertyInfo* infos, PropertyType type) {
1283 MOZ_ASSERT(pref);
1284 MOZ_ASSERT(pref->specs);
1286 // Index of the Prefable that contains the id for the current PropertyInfo.
1287 uint32_t prefIndex = 0;
1289 do {
1290 // We ignore whether the set of ids is enabled and just intern all the IDs,
1291 // because this is only done once per application runtime.
1292 const SpecT* spec = pref->specs;
1293 // Index of the property/function/constant spec for our current PropertyInfo
1294 // in the "specs" array of the relevant Prefable.
1295 uint32_t specIndex = 0;
1296 do {
1297 jsid id;
1298 if (!JS::PropertySpecNameToPermanentId(cx, ToPropertySpecName(spec->name),
1299 &id)) {
1300 return false;
1302 infos->SetId(id);
1303 infos->type = type;
1304 infos->prefIndex = prefIndex;
1305 infos->specIndex = specIndex++;
1306 ++infos;
1307 } while ((++spec)->name);
1308 ++prefIndex;
1309 } while ((++pref)->specs);
1311 return true;
1314 #define INIT_PROPERTY_INFOS_IF_DEFINED(TypeName) \
1316 if (nativeProperties->Has##TypeName##s() && \
1317 !InitPropertyInfos(cx, nativeProperties->TypeName##s(), \
1318 nativeProperties->TypeName##PropertyInfos(), \
1319 e##TypeName)) { \
1320 return false; \
1324 static bool InitPropertyInfos(JSContext* cx,
1325 const NativeProperties* nativeProperties) {
1326 INIT_PROPERTY_INFOS_IF_DEFINED(StaticMethod);
1327 INIT_PROPERTY_INFOS_IF_DEFINED(StaticAttribute);
1328 INIT_PROPERTY_INFOS_IF_DEFINED(Method);
1329 INIT_PROPERTY_INFOS_IF_DEFINED(Attribute);
1330 INIT_PROPERTY_INFOS_IF_DEFINED(UnforgeableMethod);
1331 INIT_PROPERTY_INFOS_IF_DEFINED(UnforgeableAttribute);
1332 INIT_PROPERTY_INFOS_IF_DEFINED(Constant);
1334 // Initialize and sort the index array.
1335 uint16_t* indices = nativeProperties->sortedPropertyIndices;
1336 for (unsigned int i = 0; i < nativeProperties->propertyInfoCount; ++i) {
1337 indices[i] = i;
1339 // CompareIdsAtIndices() doesn't actually modify the PropertyInfo array, so
1340 // the const_cast here is OK in spite of the signature of NS_QuickSort().
1341 NS_QuickSort(indices, nativeProperties->propertyInfoCount, sizeof(uint16_t),
1342 CompareIdsAtIndices,
1343 const_cast<PropertyInfo*>(nativeProperties->PropertyInfos()));
1345 return true;
1348 #undef INIT_PROPERTY_INFOS_IF_DEFINED
1350 static inline bool InitPropertyInfos(
1351 JSContext* aCx, const NativePropertiesHolder& nativeProperties) {
1352 MOZ_ASSERT(NS_IsMainThread());
1354 if (!*nativeProperties.inited) {
1355 if (nativeProperties.regular &&
1356 !InitPropertyInfos(aCx, nativeProperties.regular)) {
1357 return false;
1359 if (nativeProperties.chromeOnly &&
1360 !InitPropertyInfos(aCx, nativeProperties.chromeOnly)) {
1361 return false;
1363 *nativeProperties.inited = true;
1366 return true;
1369 void GetInterfaceImpl(JSContext* aCx, nsIInterfaceRequestor* aRequestor,
1370 nsWrapperCache* aCache, JS::Handle<JS::Value> aIID,
1371 JS::MutableHandle<JS::Value> aRetval,
1372 ErrorResult& aError) {
1373 Maybe<nsIID> iid = xpc::JSValue2ID(aCx, aIID);
1374 if (!iid) {
1375 aError.Throw(NS_ERROR_XPC_BAD_CONVERT_JS);
1376 return;
1379 RefPtr<nsISupports> result;
1380 aError = aRequestor->GetInterface(*iid, getter_AddRefs(result));
1381 if (aError.Failed()) {
1382 return;
1385 if (!WrapObject(aCx, result, iid.ptr(), aRetval)) {
1386 aError.Throw(NS_ERROR_FAILURE);
1390 bool ThrowingConstructor(JSContext* cx, unsigned argc, JS::Value* vp) {
1391 // Cast nullptr to void* to work around
1392 // https://gcc.gnu.org/bugzilla/show_bug.cgi?id=100666
1393 return ThrowErrorMessage<MSG_ILLEGAL_CONSTRUCTOR>(cx, (void*)nullptr);
1396 bool ThrowConstructorWithoutNew(JSContext* cx, const char* name) {
1397 return ThrowErrorMessage<MSG_CONSTRUCTOR_WITHOUT_NEW>(cx, name);
1400 inline const NativePropertyHooks* GetNativePropertyHooksFromConstructorFunction(
1401 JS::Handle<JSObject*> obj) {
1402 MOZ_ASSERT(JS_IsNativeFunction(obj, Constructor));
1403 const JS::Value& v = js::GetFunctionNativeReserved(
1404 obj, CONSTRUCTOR_NATIVE_HOLDER_RESERVED_SLOT);
1405 const JSNativeHolder* nativeHolder =
1406 static_cast<const JSNativeHolder*>(v.toPrivate());
1407 return nativeHolder->mPropertyHooks;
1410 inline const NativePropertyHooks* GetNativePropertyHooks(
1411 JSContext* cx, JS::Handle<JSObject*> obj, DOMObjectType& type) {
1412 const JSClass* clasp = JS::GetClass(obj);
1414 const DOMJSClass* domClass = GetDOMClass(clasp);
1415 if (domClass) {
1416 bool isGlobal = (clasp->flags & JSCLASS_DOM_GLOBAL) != 0;
1417 type = isGlobal ? eGlobalInstance : eInstance;
1418 return domClass->mNativeHooks;
1421 if (JS_ObjectIsFunction(obj)) {
1422 type = eInterface;
1423 return GetNativePropertyHooksFromConstructorFunction(obj);
1426 MOZ_ASSERT(IsDOMIfaceAndProtoClass(JS::GetClass(obj)));
1427 const DOMIfaceAndProtoJSClass* ifaceAndProtoJSClass =
1428 DOMIfaceAndProtoJSClass::FromJSClass(JS::GetClass(obj));
1429 type = ifaceAndProtoJSClass->mType;
1430 return ifaceAndProtoJSClass->mNativeHooks;
1433 static JSObject* XrayCreateFunction(JSContext* cx,
1434 JS::Handle<JSObject*> wrapper,
1435 JSNativeWrapper native, unsigned nargs,
1436 JS::Handle<jsid> id) {
1437 JSFunction* fun;
1438 if (JSID_IS_STRING(id)) {
1439 fun = js::NewFunctionByIdWithReserved(cx, native.op, nargs, 0, id);
1440 } else {
1441 // Can't pass this id (probably a symbol) to NewFunctionByIdWithReserved;
1442 // just use an empty name for lack of anything better.
1443 fun = js::NewFunctionWithReserved(cx, native.op, nargs, 0, nullptr);
1446 if (!fun) {
1447 return nullptr;
1450 SET_JITINFO(fun, native.info);
1451 JSObject* obj = JS_GetFunctionObject(fun);
1452 js::SetFunctionNativeReserved(obj, XRAY_DOM_FUNCTION_PARENT_WRAPPER_SLOT,
1453 JS::ObjectValue(*wrapper));
1454 #ifdef DEBUG
1455 js::SetFunctionNativeReserved(obj, XRAY_DOM_FUNCTION_NATIVE_SLOT_FOR_SELF,
1456 JS::ObjectValue(*obj));
1457 #endif
1458 return obj;
1461 struct IdToIndexComparator {
1462 // The id we're searching for.
1463 const jsid& mId;
1464 // The list of ids we're searching in.
1465 const PropertyInfo* mInfos;
1467 explicit IdToIndexComparator(const jsid& aId, const PropertyInfo* aInfos)
1468 : mId(aId), mInfos(aInfos) {}
1469 int operator()(const uint16_t aIndex) const {
1470 if (JSID_BITS(mId) == JSID_BITS(mInfos[aIndex].Id())) {
1471 return 0;
1473 return JSID_BITS(mId) < JSID_BITS(mInfos[aIndex].Id()) ? -1 : 1;
1477 static const PropertyInfo* XrayFindOwnPropertyInfo(
1478 JSContext* cx, JS::Handle<jsid> id,
1479 const NativeProperties* nativeProperties) {
1480 if (MOZ_UNLIKELY(nativeProperties->iteratorAliasMethodIndex >= 0) &&
1481 id.isWellKnownSymbol(JS::SymbolCode::iterator)) {
1482 return nativeProperties->MethodPropertyInfos() +
1483 nativeProperties->iteratorAliasMethodIndex;
1486 size_t idx;
1487 const uint16_t* sortedPropertyIndices =
1488 nativeProperties->sortedPropertyIndices;
1489 const PropertyInfo* propertyInfos = nativeProperties->PropertyInfos();
1491 if (BinarySearchIf(sortedPropertyIndices, 0,
1492 nativeProperties->propertyInfoCount,
1493 IdToIndexComparator(id, propertyInfos), &idx)) {
1494 return propertyInfos + sortedPropertyIndices[idx];
1497 return nullptr;
1500 static bool XrayResolveAttribute(
1501 JSContext* cx, JS::Handle<JSObject*> wrapper, JS::Handle<JSObject*> obj,
1502 JS::Handle<jsid> id, const Prefable<const JSPropertySpec>& pref,
1503 const JSPropertySpec& attrSpec,
1504 JS::MutableHandle<Maybe<JS::PropertyDescriptor>> desc,
1505 bool& cacheOnHolder) {
1506 if (!pref.isEnabled(cx, obj)) {
1507 return true;
1510 MOZ_ASSERT(attrSpec.isAccessor());
1512 MOZ_ASSERT(
1513 !attrSpec.isSelfHosted(),
1514 "Bad JSPropertySpec declaration: unsupported self-hosted accessor");
1516 cacheOnHolder = true;
1518 // Because of centralization, we need to make sure we fault in the JitInfos as
1519 // well. At present, until the JSAPI changes, the easiest way to do this is
1520 // wrap them up as functions ourselves.
1522 // They all have getters, so we can just make it.
1523 JS::Rooted<JSObject*> getter(
1524 cx, XrayCreateFunction(cx, wrapper, attrSpec.u.accessors.getter.native, 0,
1525 id));
1526 if (!getter) {
1527 return false;
1530 JS::Rooted<JSObject*> setter(cx);
1531 if (attrSpec.u.accessors.setter.native.op) {
1532 // We have a setter! Make it.
1533 setter = XrayCreateFunction(cx, wrapper, attrSpec.u.accessors.setter.native,
1534 1, id);
1535 if (!setter) {
1536 return false;
1540 desc.set(Some(
1541 JS::PropertyDescriptor::Accessor(getter, setter, attrSpec.attributes())));
1542 return true;
1545 static bool XrayResolveMethod(
1546 JSContext* cx, JS::Handle<JSObject*> wrapper, JS::Handle<JSObject*> obj,
1547 JS::Handle<jsid> id, const Prefable<const JSFunctionSpec>& pref,
1548 const JSFunctionSpec& methodSpec,
1549 JS::MutableHandle<Maybe<JS::PropertyDescriptor>> desc,
1550 bool& cacheOnHolder) {
1551 if (!pref.isEnabled(cx, obj)) {
1552 return true;
1555 cacheOnHolder = true;
1557 JSObject* funobj;
1558 if (methodSpec.selfHostedName) {
1559 JSFunction* fun = JS::GetSelfHostedFunction(cx, methodSpec.selfHostedName,
1560 id, methodSpec.nargs);
1561 if (!fun) {
1562 return false;
1564 MOZ_ASSERT(!methodSpec.call.op,
1565 "Bad FunctionSpec declaration: non-null native");
1566 MOZ_ASSERT(!methodSpec.call.info,
1567 "Bad FunctionSpec declaration: non-null jitinfo");
1568 funobj = JS_GetFunctionObject(fun);
1569 } else {
1570 funobj =
1571 XrayCreateFunction(cx, wrapper, methodSpec.call, methodSpec.nargs, id);
1572 if (!funobj) {
1573 return false;
1577 desc.set(Some(JS::PropertyDescriptor::Data(JS::ObjectValue(*funobj),
1578 methodSpec.flags)));
1579 return true;
1582 static bool XrayResolveConstant(
1583 JSContext* cx, JS::Handle<JSObject*> wrapper, JS::Handle<JSObject*> obj,
1584 JS::Handle<jsid>, const Prefable<const ConstantSpec>& pref,
1585 const ConstantSpec& constantSpec,
1586 JS::MutableHandle<Maybe<JS::PropertyDescriptor>> desc,
1587 bool& cacheOnHolder) {
1588 if (!pref.isEnabled(cx, obj)) {
1589 return true;
1592 cacheOnHolder = true;
1594 desc.set(Some(JS::PropertyDescriptor::Data(
1595 constantSpec.value, {JS::PropertyAttribute::Enumerable})));
1596 return true;
1599 #define RESOLVE_CASE(PropType, SpecType, Resolver) \
1600 case e##PropType: { \
1601 MOZ_ASSERT(nativeProperties->Has##PropType##s()); \
1602 const Prefable<const SpecType>& pref = \
1603 nativeProperties->PropType##s()[propertyInfo.prefIndex]; \
1604 return Resolver(cx, wrapper, obj, id, pref, \
1605 pref.specs[propertyInfo.specIndex], desc, cacheOnHolder); \
1608 static bool XrayResolveProperty(
1609 JSContext* cx, JS::Handle<JSObject*> wrapper, JS::Handle<JSObject*> obj,
1610 JS::Handle<jsid> id, JS::MutableHandle<Maybe<JS::PropertyDescriptor>> desc,
1611 bool& cacheOnHolder, DOMObjectType type,
1612 const NativeProperties* nativeProperties,
1613 const PropertyInfo& propertyInfo) {
1614 MOZ_ASSERT(type != eGlobalInterfacePrototype);
1616 // Make sure we resolve for matched object type.
1617 switch (propertyInfo.type) {
1618 case eStaticMethod:
1619 case eStaticAttribute:
1620 if (type != eInterface) {
1621 return true;
1623 break;
1624 case eMethod:
1625 case eAttribute:
1626 if (type != eGlobalInstance && type != eInterfacePrototype) {
1627 return true;
1629 break;
1630 case eUnforgeableMethod:
1631 case eUnforgeableAttribute:
1632 if (!IsInstance(type)) {
1633 return true;
1635 break;
1636 case eConstant:
1637 if (IsInstance(type)) {
1638 return true;
1640 break;
1643 switch (propertyInfo.type) {
1644 RESOLVE_CASE(StaticMethod, JSFunctionSpec, XrayResolveMethod)
1645 RESOLVE_CASE(StaticAttribute, JSPropertySpec, XrayResolveAttribute)
1646 RESOLVE_CASE(Method, JSFunctionSpec, XrayResolveMethod)
1647 RESOLVE_CASE(Attribute, JSPropertySpec, XrayResolveAttribute)
1648 RESOLVE_CASE(UnforgeableMethod, JSFunctionSpec, XrayResolveMethod)
1649 RESOLVE_CASE(UnforgeableAttribute, JSPropertySpec, XrayResolveAttribute)
1650 RESOLVE_CASE(Constant, ConstantSpec, XrayResolveConstant)
1653 return true;
1656 #undef RESOLVE_CASE
1658 static bool ResolvePrototypeOrConstructor(
1659 JSContext* cx, JS::Handle<JSObject*> wrapper, JS::Handle<JSObject*> obj,
1660 size_t protoAndIfaceCacheIndex, unsigned attrs,
1661 JS::MutableHandle<Maybe<JS::PropertyDescriptor>> desc,
1662 bool& cacheOnHolder) {
1663 JS::Rooted<JSObject*> global(cx, JS::GetNonCCWObjectGlobal(obj));
1665 JSAutoRealm ar(cx, global);
1666 ProtoAndIfaceCache& protoAndIfaceCache = *GetProtoAndIfaceCache(global);
1667 // This function is called when resolving the "constructor" and "prototype"
1668 // properties of Xrays for DOM prototypes and constructors respectively.
1669 // This means the relevant Xray exists, which means its _target_ exists.
1670 // And that means we managed to successfullly create the prototype or
1671 // constructor, respectively, and hence must have managed to create the
1672 // thing it's pointing to as well. So our entry slot must exist.
1673 JSObject* protoOrIface =
1674 protoAndIfaceCache.EntrySlotMustExist(protoAndIfaceCacheIndex);
1675 MOZ_RELEASE_ASSERT(protoOrIface, "How can this object not exist?");
1677 cacheOnHolder = true;
1679 desc.set(Some(
1680 JS::PropertyDescriptor::Data(JS::ObjectValue(*protoOrIface), attrs)));
1682 return JS_WrapPropertyDescriptor(cx, desc);
1685 /* static */ bool XrayResolveOwnProperty(
1686 JSContext* cx, JS::Handle<JSObject*> wrapper, JS::Handle<JSObject*> obj,
1687 JS::Handle<jsid> id, JS::MutableHandle<Maybe<JS::PropertyDescriptor>> desc,
1688 bool& cacheOnHolder) {
1689 MOZ_ASSERT(desc.isNothing());
1690 cacheOnHolder = false;
1692 DOMObjectType type;
1693 const NativePropertyHooks* nativePropertyHooks =
1694 GetNativePropertyHooks(cx, obj, type);
1695 ResolveOwnProperty resolveOwnProperty =
1696 nativePropertyHooks->mResolveOwnProperty;
1698 if (type == eNamedPropertiesObject) {
1699 MOZ_ASSERT(!resolveOwnProperty,
1700 "Shouldn't have any Xray-visible properties");
1701 return true;
1704 const NativePropertiesHolder& nativePropertiesHolder =
1705 nativePropertyHooks->mNativeProperties;
1707 if (!InitPropertyInfos(cx, nativePropertiesHolder)) {
1708 return false;
1711 const NativeProperties* nativeProperties = nullptr;
1712 const PropertyInfo* found = nullptr;
1714 if ((nativeProperties = nativePropertiesHolder.regular)) {
1715 found = XrayFindOwnPropertyInfo(cx, id, nativeProperties);
1717 if (!found && (nativeProperties = nativePropertiesHolder.chromeOnly) &&
1718 xpc::AccessCheck::isChrome(JS::GetCompartment(wrapper))) {
1719 found = XrayFindOwnPropertyInfo(cx, id, nativeProperties);
1722 if (IsInstance(type)) {
1723 // Check for unforgeable properties first to prevent names provided by
1724 // resolveOwnProperty callback from shadowing them.
1725 if (found && (found->type == eUnforgeableMethod ||
1726 found->type == eUnforgeableAttribute)) {
1727 if (!XrayResolveProperty(cx, wrapper, obj, id, desc, cacheOnHolder, type,
1728 nativeProperties, *found)) {
1729 return false;
1732 if (desc.isSome()) {
1733 return true;
1737 if (resolveOwnProperty) {
1738 if (!resolveOwnProperty(cx, wrapper, obj, id, desc)) {
1739 return false;
1742 if (desc.isSome()) {
1743 // None of these should be cached on the holder, since they're dynamic.
1744 return true;
1748 // For non-global instance Xrays there are no other properties, so return
1749 // here for them.
1750 if (type != eGlobalInstance) {
1751 return true;
1753 } else if (type == eInterface) {
1754 if (id.get() == GetJSIDByIndex(cx, XPCJSContext::IDX_PROTOTYPE)) {
1755 return nativePropertyHooks->mPrototypeID == prototypes::id::_ID_Count ||
1756 ResolvePrototypeOrConstructor(
1757 cx, wrapper, obj, nativePropertyHooks->mPrototypeID,
1758 JSPROP_PERMANENT | JSPROP_READONLY, desc, cacheOnHolder);
1761 if (id.get() == GetJSIDByIndex(cx, XPCJSContext::IDX_ISINSTANCE)) {
1762 const JSClass* objClass = JS::GetClass(obj);
1763 if (IsDOMIfaceAndProtoClass(objClass) &&
1764 DOMIfaceAndProtoJSClass::FromJSClass(objClass)
1765 ->wantsInterfaceHasInstance) {
1766 cacheOnHolder = true;
1767 JSNativeWrapper interfaceIsInstanceWrapper = {InterfaceIsInstance,
1768 nullptr};
1769 JSObject* funObj =
1770 XrayCreateFunction(cx, wrapper, interfaceIsInstanceWrapper, 1, id);
1771 if (!funObj) {
1772 return false;
1775 desc.set(Some(JS::PropertyDescriptor::Data(
1776 JS::ObjectValue(*funObj), {JS::PropertyAttribute::Configurable,
1777 JS::PropertyAttribute::Writable})));
1778 return true;
1782 if (id.isWellKnownSymbol(JS::SymbolCode::hasInstance)) {
1783 const JSClass* objClass = JS::GetClass(obj);
1784 if (IsDOMIfaceAndProtoClass(objClass) &&
1785 DOMIfaceAndProtoJSClass::FromJSClass(objClass)
1786 ->wantsInterfaceHasInstance) {
1787 cacheOnHolder = true;
1788 JSNativeWrapper interfaceHasInstanceWrapper = {InterfaceHasInstance,
1789 nullptr};
1790 JSObject* funObj =
1791 XrayCreateFunction(cx, wrapper, interfaceHasInstanceWrapper, 1, id);
1792 if (!funObj) {
1793 return false;
1796 desc.set(
1797 Some(JS::PropertyDescriptor::Data(JS::ObjectValue(*funObj), {})));
1798 return true;
1801 } else {
1802 MOZ_ASSERT(IsInterfacePrototype(type));
1804 if (id.get() == GetJSIDByIndex(cx, XPCJSContext::IDX_CONSTRUCTOR)) {
1805 return nativePropertyHooks->mConstructorID ==
1806 constructors::id::_ID_Count ||
1807 ResolvePrototypeOrConstructor(cx, wrapper, obj,
1808 nativePropertyHooks->mConstructorID,
1809 0, desc, cacheOnHolder);
1812 if (id.isWellKnownSymbol(JS::SymbolCode::toStringTag)) {
1813 const JSClass* objClass = JS::GetClass(obj);
1814 prototypes::ID prototypeID =
1815 DOMIfaceAndProtoJSClass::FromJSClass(objClass)->mPrototypeID;
1816 JS::Rooted<JSString*> nameStr(
1817 cx, JS_AtomizeString(cx, NamesOfInterfacesWithProtos(prototypeID)));
1818 if (!nameStr) {
1819 return false;
1822 desc.set(Some(JS::PropertyDescriptor::Data(
1823 JS::StringValue(nameStr), {JS::PropertyAttribute::Configurable})));
1824 return true;
1827 // The properties for globals live on the instance, so return here as there
1828 // are no properties on their interface prototype object.
1829 if (type == eGlobalInterfacePrototype) {
1830 return true;
1834 if (found && !XrayResolveProperty(cx, wrapper, obj, id, desc, cacheOnHolder,
1835 type, nativeProperties, *found)) {
1836 return false;
1839 return true;
1842 bool XrayDefineProperty(JSContext* cx, JS::Handle<JSObject*> wrapper,
1843 JS::Handle<JSObject*> obj, JS::Handle<jsid> id,
1844 JS::Handle<JS::PropertyDescriptor> desc,
1845 JS::ObjectOpResult& result, bool* done) {
1846 if (!js::IsProxy(obj)) return true;
1848 const DOMProxyHandler* handler = GetDOMProxyHandler(obj);
1849 return handler->defineProperty(cx, wrapper, id, desc, result, done);
1852 template <typename SpecType>
1853 bool XrayAppendPropertyKeys(JSContext* cx, JS::Handle<JSObject*> obj,
1854 const Prefable<const SpecType>* pref,
1855 const PropertyInfo* infos, unsigned flags,
1856 JS::MutableHandleVector<jsid> props) {
1857 do {
1858 bool prefIsEnabled = pref->isEnabled(cx, obj);
1859 if (prefIsEnabled) {
1860 const SpecType* spec = pref->specs;
1861 do {
1862 const jsid id = infos++->Id();
1863 if (((flags & JSITER_HIDDEN) ||
1864 (spec->attributes() & JSPROP_ENUMERATE)) &&
1865 ((flags & JSITER_SYMBOLS) || !id.isSymbol()) && !props.append(id)) {
1866 return false;
1868 } while ((++spec)->name);
1870 // Break if we have reached the end of pref.
1871 if (!(++pref)->specs) {
1872 break;
1874 // Advance infos if the previous pref is disabled. The -1 is required
1875 // because there is an end-of-list terminator between pref->specs and
1876 // (pref - 1)->specs.
1877 if (!prefIsEnabled) {
1878 infos += pref->specs - (pref - 1)->specs - 1;
1880 } while (1);
1882 return true;
1885 template <>
1886 bool XrayAppendPropertyKeys<ConstantSpec>(
1887 JSContext* cx, JS::Handle<JSObject*> obj,
1888 const Prefable<const ConstantSpec>* pref, const PropertyInfo* infos,
1889 unsigned flags, JS::MutableHandleVector<jsid> props) {
1890 do {
1891 bool prefIsEnabled = pref->isEnabled(cx, obj);
1892 if (prefIsEnabled) {
1893 const ConstantSpec* spec = pref->specs;
1894 do {
1895 if (!props.append(infos++->Id())) {
1896 return false;
1898 } while ((++spec)->name);
1900 // Break if we have reached the end of pref.
1901 if (!(++pref)->specs) {
1902 break;
1904 // Advance infos if the previous pref is disabled. The -1 is required
1905 // because there is an end-of-list terminator between pref->specs and
1906 // (pref - 1)->specs.
1907 if (!prefIsEnabled) {
1908 infos += pref->specs - (pref - 1)->specs - 1;
1910 } while (1);
1912 return true;
1915 #define ADD_KEYS_IF_DEFINED(FieldName) \
1917 if (nativeProperties->Has##FieldName##s() && \
1918 !XrayAppendPropertyKeys(cx, obj, nativeProperties->FieldName##s(), \
1919 nativeProperties->FieldName##PropertyInfos(), \
1920 flags, props)) { \
1921 return false; \
1925 bool XrayOwnPropertyKeys(JSContext* cx, JS::Handle<JSObject*> wrapper,
1926 JS::Handle<JSObject*> obj, unsigned flags,
1927 JS::MutableHandleVector<jsid> props,
1928 DOMObjectType type,
1929 const NativeProperties* nativeProperties) {
1930 MOZ_ASSERT(type != eNamedPropertiesObject);
1932 if (IsInstance(type)) {
1933 ADD_KEYS_IF_DEFINED(UnforgeableMethod);
1934 ADD_KEYS_IF_DEFINED(UnforgeableAttribute);
1935 if (type == eGlobalInstance) {
1936 ADD_KEYS_IF_DEFINED(Method);
1937 ADD_KEYS_IF_DEFINED(Attribute);
1939 } else {
1940 MOZ_ASSERT(type != eGlobalInterfacePrototype);
1941 if (type == eInterface) {
1942 ADD_KEYS_IF_DEFINED(StaticMethod);
1943 ADD_KEYS_IF_DEFINED(StaticAttribute);
1944 } else {
1945 MOZ_ASSERT(type == eInterfacePrototype);
1946 ADD_KEYS_IF_DEFINED(Method);
1947 ADD_KEYS_IF_DEFINED(Attribute);
1949 ADD_KEYS_IF_DEFINED(Constant);
1952 return true;
1955 #undef ADD_KEYS_IF_DEFINED
1957 bool XrayOwnNativePropertyKeys(JSContext* cx, JS::Handle<JSObject*> wrapper,
1958 const NativePropertyHooks* nativePropertyHooks,
1959 DOMObjectType type, JS::Handle<JSObject*> obj,
1960 unsigned flags,
1961 JS::MutableHandleVector<jsid> props) {
1962 MOZ_ASSERT(type != eNamedPropertiesObject);
1964 if (type == eInterface &&
1965 nativePropertyHooks->mPrototypeID != prototypes::id::_ID_Count &&
1966 !AddStringToIDVector(cx, props, "prototype")) {
1967 return false;
1970 if (IsInterfacePrototype(type) &&
1971 nativePropertyHooks->mConstructorID != constructors::id::_ID_Count &&
1972 (flags & JSITER_HIDDEN) &&
1973 !AddStringToIDVector(cx, props, "constructor")) {
1974 return false;
1977 const NativePropertiesHolder& nativeProperties =
1978 nativePropertyHooks->mNativeProperties;
1980 if (!InitPropertyInfos(cx, nativeProperties)) {
1981 return false;
1984 if (nativeProperties.regular &&
1985 !XrayOwnPropertyKeys(cx, wrapper, obj, flags, props, type,
1986 nativeProperties.regular)) {
1987 return false;
1990 if (nativeProperties.chromeOnly &&
1991 xpc::AccessCheck::isChrome(JS::GetCompartment(wrapper)) &&
1992 !XrayOwnPropertyKeys(cx, wrapper, obj, flags, props, type,
1993 nativeProperties.chromeOnly)) {
1994 return false;
1997 return true;
2000 bool XrayOwnPropertyKeys(JSContext* cx, JS::Handle<JSObject*> wrapper,
2001 JS::Handle<JSObject*> obj, unsigned flags,
2002 JS::MutableHandleVector<jsid> props) {
2003 DOMObjectType type;
2004 const NativePropertyHooks* nativePropertyHooks =
2005 GetNativePropertyHooks(cx, obj, type);
2006 EnumerateOwnProperties enumerateOwnProperties =
2007 nativePropertyHooks->mEnumerateOwnProperties;
2009 if (type == eNamedPropertiesObject) {
2010 MOZ_ASSERT(!enumerateOwnProperties,
2011 "Shouldn't have any Xray-visible properties");
2012 return true;
2015 if (IsInstance(type)) {
2016 // FIXME https://bugzilla.mozilla.org/show_bug.cgi?id=1071189
2017 // Should do something about XBL properties too.
2018 if (enumerateOwnProperties &&
2019 !enumerateOwnProperties(cx, wrapper, obj, props)) {
2020 return false;
2024 return type == eGlobalInterfacePrototype ||
2025 XrayOwnNativePropertyKeys(cx, wrapper, nativePropertyHooks, type, obj,
2026 flags, props);
2029 const JSClass* XrayGetExpandoClass(JSContext* cx, JS::Handle<JSObject*> obj) {
2030 DOMObjectType type;
2031 const NativePropertyHooks* nativePropertyHooks =
2032 GetNativePropertyHooks(cx, obj, type);
2033 if (!IsInstance(type)) {
2034 // Non-instances don't need any special expando classes.
2035 return &DefaultXrayExpandoObjectClass;
2038 return nativePropertyHooks->mXrayExpandoClass;
2041 bool XrayDeleteNamedProperty(JSContext* cx, JS::Handle<JSObject*> wrapper,
2042 JS::Handle<JSObject*> obj, JS::Handle<jsid> id,
2043 JS::ObjectOpResult& opresult) {
2044 DOMObjectType type;
2045 const NativePropertyHooks* nativePropertyHooks =
2046 GetNativePropertyHooks(cx, obj, type);
2047 if (!IsInstance(type) || !nativePropertyHooks->mDeleteNamedProperty) {
2048 return opresult.succeed();
2050 return nativePropertyHooks->mDeleteNamedProperty(cx, wrapper, obj, id,
2051 opresult);
2054 namespace binding_detail {
2056 bool ResolveOwnProperty(JSContext* cx, JS::Handle<JSObject*> wrapper,
2057 JS::Handle<JSObject*> obj, JS::Handle<jsid> id,
2058 JS::MutableHandle<Maybe<JS::PropertyDescriptor>> desc) {
2059 return js::GetProxyHandler(obj)->getOwnPropertyDescriptor(cx, wrapper, id,
2060 desc);
2063 bool EnumerateOwnProperties(JSContext* cx, JS::Handle<JSObject*> wrapper,
2064 JS::Handle<JSObject*> obj,
2065 JS::MutableHandleVector<jsid> props) {
2066 return js::GetProxyHandler(obj)->ownPropertyKeys(cx, wrapper, props);
2069 } // namespace binding_detail
2071 JSObject* GetCachedSlotStorageObjectSlow(JSContext* cx,
2072 JS::Handle<JSObject*> obj,
2073 bool* isXray) {
2074 if (!xpc::WrapperFactory::IsXrayWrapper(obj)) {
2075 JSObject* retval =
2076 js::UncheckedUnwrap(obj, /* stopAtWindowProxy = */ false);
2077 MOZ_ASSERT(IsDOMObject(retval));
2078 *isXray = false;
2079 return retval;
2082 *isXray = true;
2083 return xpc::EnsureXrayExpandoObject(cx, obj);
2086 DEFINE_XRAY_EXPANDO_CLASS(, DefaultXrayExpandoObjectClass, 0);
2088 bool sEmptyNativePropertiesInited = true;
2089 NativePropertyHooks sEmptyNativePropertyHooks = {
2090 nullptr,
2091 nullptr,
2092 nullptr,
2093 {nullptr, nullptr, &sEmptyNativePropertiesInited},
2094 prototypes::id::_ID_Count,
2095 constructors::id::_ID_Count,
2096 nullptr};
2098 const JSClassOps sBoringInterfaceObjectClassClassOps = {
2099 nullptr, /* addProperty */
2100 nullptr, /* delProperty */
2101 nullptr, /* enumerate */
2102 nullptr, /* newEnumerate */
2103 nullptr, /* resolve */
2104 nullptr, /* mayResolve */
2105 nullptr, /* finalize */
2106 ThrowingConstructor, /* call */
2107 nullptr, /* hasInstance */
2108 ThrowingConstructor, /* construct */
2109 nullptr, /* trace */
2112 const js::ObjectOps sInterfaceObjectClassObjectOps = {
2113 nullptr, /* lookupProperty */
2114 nullptr, /* defineProperty */
2115 nullptr, /* hasProperty */
2116 nullptr, /* getProperty */
2117 nullptr, /* setProperty */
2118 nullptr, /* getOwnPropertyDescriptor */
2119 nullptr, /* deleteProperty */
2120 nullptr, /* getElements */
2121 InterfaceObjectToString, /* funToString */
2124 bool GetPropertyOnPrototype(JSContext* cx, JS::Handle<JSObject*> proxy,
2125 JS::Handle<JS::Value> receiver, JS::Handle<jsid> id,
2126 bool* found, JS::MutableHandle<JS::Value> vp) {
2127 JS::Rooted<JSObject*> proto(cx);
2128 if (!js::GetObjectProto(cx, proxy, &proto)) {
2129 return false;
2131 if (!proto) {
2132 *found = false;
2133 return true;
2136 if (!JS_HasPropertyById(cx, proto, id, found)) {
2137 return false;
2140 if (!*found) {
2141 return true;
2144 return JS_ForwardGetPropertyTo(cx, proto, id, receiver, vp);
2147 bool HasPropertyOnPrototype(JSContext* cx, JS::Handle<JSObject*> proxy,
2148 JS::Handle<jsid> id, bool* has) {
2149 JS::Rooted<JSObject*> proto(cx);
2150 if (!js::GetObjectProto(cx, proxy, &proto)) {
2151 return false;
2153 if (!proto) {
2154 *has = false;
2155 return true;
2158 return JS_HasPropertyById(cx, proto, id, has);
2161 bool AppendNamedPropertyIds(JSContext* cx, JS::Handle<JSObject*> proxy,
2162 nsTArray<nsString>& names,
2163 bool shadowPrototypeProperties,
2164 JS::MutableHandleVector<jsid> props) {
2165 for (uint32_t i = 0; i < names.Length(); ++i) {
2166 JS::Rooted<JS::Value> v(cx);
2167 if (!xpc::NonVoidStringToJsval(cx, names[i], &v)) {
2168 return false;
2171 JS::Rooted<jsid> id(cx);
2172 if (!JS_ValueToId(cx, v, &id)) {
2173 return false;
2176 bool shouldAppend = shadowPrototypeProperties;
2177 if (!shouldAppend) {
2178 bool has;
2179 if (!HasPropertyOnPrototype(cx, proxy, id, &has)) {
2180 return false;
2182 shouldAppend = !has;
2185 if (shouldAppend) {
2186 if (!props.append(id)) {
2187 return false;
2192 return true;
2195 bool DictionaryBase::ParseJSON(JSContext* aCx, const nsAString& aJSON,
2196 JS::MutableHandle<JS::Value> aVal) {
2197 if (aJSON.IsEmpty()) {
2198 return true;
2200 return JS_ParseJSON(aCx, aJSON.BeginReading(), aJSON.Length(), aVal);
2203 bool DictionaryBase::StringifyToJSON(JSContext* aCx, JS::Handle<JSObject*> aObj,
2204 nsAString& aJSON) const {
2205 return JS::ToJSONMaybeSafely(aCx, aObj, AppendJSONToString, &aJSON);
2208 /* static */
2209 bool DictionaryBase::AppendJSONToString(const char16_t* aJSONData,
2210 uint32_t aDataLength, void* aString) {
2211 nsAString* string = static_cast<nsAString*>(aString);
2212 string->Append(aJSONData, aDataLength);
2213 return true;
2216 void UpdateReflectorGlobal(JSContext* aCx, JS::Handle<JSObject*> aObjArg,
2217 ErrorResult& aError) {
2218 js::AssertSameCompartment(aCx, aObjArg);
2220 aError.MightThrowJSException();
2222 // Check if we're anywhere near the stack limit before we reach the
2223 // transplanting code, since it has no good way to handle errors. This uses
2224 // the untrusted script limit, which is not strictly necessary since no
2225 // actual script should run.
2226 js::AutoCheckRecursionLimit recursion(aCx);
2227 if (!recursion.checkConservative(aCx)) {
2228 aError.StealExceptionFromJSContext(aCx);
2229 return;
2232 JS::Rooted<JSObject*> aObj(aCx, aObjArg);
2233 MOZ_ASSERT(IsDOMObject(aObj));
2235 const DOMJSClass* domClass = GetDOMClass(aObj);
2237 JS::Rooted<JSObject*> oldGlobal(aCx, JS::GetNonCCWObjectGlobal(aObj));
2238 MOZ_ASSERT(JS_IsGlobalObject(oldGlobal));
2240 JS::Rooted<JSObject*> newGlobal(aCx,
2241 domClass->mGetAssociatedGlobal(aCx, aObj));
2242 MOZ_ASSERT(JS_IsGlobalObject(newGlobal));
2244 JSAutoRealm oldAr(aCx, oldGlobal);
2246 if (oldGlobal == newGlobal) {
2247 return;
2250 nsISupports* native = UnwrapDOMObjectToISupports(aObj);
2251 if (!native) {
2252 return;
2255 bool isProxy = js::IsProxy(aObj);
2256 JS::Rooted<JSObject*> expandoObject(aCx);
2257 if (isProxy) {
2258 expandoObject = DOMProxyHandler::GetAndClearExpandoObject(aObj);
2261 JSAutoRealm newAr(aCx, newGlobal);
2263 // First we clone the reflector. We get a copy of its properties and clone its
2264 // expando chain.
2266 JS::Handle<JSObject*> proto = (domClass->mGetProto)(aCx);
2267 if (!proto) {
2268 aError.StealExceptionFromJSContext(aCx);
2269 return;
2272 JS::Rooted<JSObject*> newobj(aCx, JS_CloneObject(aCx, aObj, proto));
2273 if (!newobj) {
2274 aError.StealExceptionFromJSContext(aCx);
2275 return;
2278 // Assert it's possible to create wrappers when |aObj| and |newobj| are in
2279 // different compartments.
2280 MOZ_ASSERT_IF(JS::GetCompartment(aObj) != JS::GetCompartment(newobj),
2281 js::AllowNewWrapper(JS::GetCompartment(aObj), newobj));
2283 JS::Rooted<JSObject*> propertyHolder(aCx);
2284 JS::Rooted<JSObject*> copyFrom(aCx, isProxy ? expandoObject : aObj);
2285 if (copyFrom) {
2286 propertyHolder = JS_NewObjectWithGivenProto(aCx, nullptr, nullptr);
2287 if (!propertyHolder) {
2288 aError.StealExceptionFromJSContext(aCx);
2289 return;
2292 if (!JS_CopyOwnPropertiesAndPrivateFields(aCx, propertyHolder, copyFrom)) {
2293 aError.StealExceptionFromJSContext(aCx);
2294 return;
2296 } else {
2297 propertyHolder = nullptr;
2300 // We've set up |newobj|, so we make it own the native by setting its reserved
2301 // slot and nulling out the reserved slot of |obj|.
2303 // NB: It's important to do this _after_ copying the properties to
2304 // propertyHolder. Otherwise, an object with |foo.x === foo| will
2305 // crash when JS_CopyOwnPropertiesAndPrivateFields tries to call wrap() on
2306 // foo.x.
2307 JS::SetReservedSlot(newobj, DOM_OBJECT_SLOT,
2308 JS::GetReservedSlot(aObj, DOM_OBJECT_SLOT));
2309 JS::SetReservedSlot(aObj, DOM_OBJECT_SLOT, JS::PrivateValue(nullptr));
2311 aObj = xpc::TransplantObjectRetainingXrayExpandos(aCx, aObj, newobj);
2312 if (!aObj) {
2313 MOZ_CRASH();
2316 nsWrapperCache* cache = nullptr;
2317 CallQueryInterface(native, &cache);
2318 cache->UpdateWrapperForNewGlobal(native, aObj);
2320 if (propertyHolder) {
2321 JS::Rooted<JSObject*> copyTo(aCx);
2322 if (isProxy) {
2323 copyTo = DOMProxyHandler::EnsureExpandoObject(aCx, aObj);
2324 } else {
2325 copyTo = aObj;
2328 if (!copyTo ||
2329 !JS_CopyOwnPropertiesAndPrivateFields(aCx, copyTo, propertyHolder)) {
2330 MOZ_CRASH();
2335 GlobalObject::GlobalObject(JSContext* aCx, JSObject* aObject)
2336 : mGlobalJSObject(aCx), mCx(aCx), mGlobalObject(nullptr) {
2337 MOZ_ASSERT(mCx);
2338 JS::Rooted<JSObject*> obj(aCx, aObject);
2339 if (js::IsWrapper(obj)) {
2340 // aCx correctly represents the current global here.
2341 obj = js::CheckedUnwrapDynamic(obj, aCx, /* stopAtWindowProxy = */ false);
2342 if (!obj) {
2343 // We should never end up here on a worker thread, since there shouldn't
2344 // be any security wrappers to worry about.
2345 if (!MOZ_LIKELY(NS_IsMainThread())) {
2346 MOZ_CRASH();
2349 Throw(aCx, NS_ERROR_XPC_SECURITY_MANAGER_VETO);
2350 return;
2354 mGlobalJSObject = JS::GetNonCCWObjectGlobal(obj);
2357 nsISupports* GlobalObject::GetAsSupports() const {
2358 if (mGlobalObject) {
2359 return mGlobalObject;
2362 MOZ_ASSERT(!js::IsWrapper(mGlobalJSObject));
2364 // Most of our globals are DOM objects. Try that first. Note that this
2365 // assumes that either the first nsISupports in the object is the canonical
2366 // one or that we don't care about the canonical nsISupports here.
2367 mGlobalObject = UnwrapDOMObjectToISupports(mGlobalJSObject);
2368 if (mGlobalObject) {
2369 return mGlobalObject;
2372 MOZ_ASSERT(NS_IsMainThread(), "All our worker globals are DOM objects");
2374 // Remove everything below here once all our global objects are using new
2375 // bindings. If that ever happens; it would need to include Sandbox and
2376 // BackstagePass.
2378 // See whether mGlobalJSObject is an XPCWrappedNative. This will redo the
2379 // IsWrapper bit above and the UnwrapDOMObjectToISupports in the case when
2380 // we're not actually an XPCWrappedNative, but this should be a rare-ish case
2381 // anyway.
2383 // It's OK to use ReflectorToISupportsStatic, because we know we don't have a
2384 // cross-compartment wrapper.
2385 nsCOMPtr<nsISupports> supp = xpc::ReflectorToISupportsStatic(mGlobalJSObject);
2386 if (supp) {
2387 // See documentation for mGlobalJSObject for why this assignment is OK.
2388 mGlobalObject = supp;
2389 return mGlobalObject;
2392 // And now a final hack. Sandbox is not a reflector, but it does have an
2393 // nsIGlobalObject hanging out in its private slot. Handle that case here,
2394 // (though again, this will do the useless UnwrapDOMObjectToISupports if we
2395 // got here for something that is somehow not a DOM object, not an
2396 // XPCWrappedNative _and_ not a Sandbox).
2397 if (XPCConvert::GetISupportsFromJSObject(mGlobalJSObject, &mGlobalObject)) {
2398 return mGlobalObject;
2401 MOZ_ASSERT(!mGlobalObject);
2403 Throw(mCx, NS_ERROR_XPC_BAD_CONVERT_JS);
2404 return nullptr;
2407 nsIPrincipal* GlobalObject::GetSubjectPrincipal() const {
2408 if (!NS_IsMainThread()) {
2409 return nullptr;
2412 JS::Realm* realm = js::GetContextRealm(mCx);
2413 MOZ_ASSERT(realm);
2414 JSPrincipals* principals = JS::GetRealmPrincipals(realm);
2415 return nsJSPrincipals::get(principals);
2418 CallerType GlobalObject::CallerType() const {
2419 return nsContentUtils::ThreadsafeIsSystemCaller(mCx)
2420 ? dom::CallerType::System
2421 : dom::CallerType::NonSystem;
2424 static bool CallOrdinaryHasInstance(JSContext* cx, JS::CallArgs& args) {
2425 JS::Rooted<JSObject*> thisObj(cx, &args.thisv().toObject());
2426 bool isInstance;
2427 if (!JS::OrdinaryHasInstance(cx, thisObj, args.get(0), &isInstance)) {
2428 return false;
2430 args.rval().setBoolean(isInstance);
2431 return true;
2434 bool InterfaceHasInstance(JSContext* cx, unsigned argc, JS::Value* vp) {
2435 JS::CallArgs args = JS::CallArgsFromVp(argc, vp);
2436 // If the thing we were passed is not an object, return false like
2437 // OrdinaryHasInstance does.
2438 if (!args.get(0).isObject()) {
2439 args.rval().setBoolean(false);
2440 return true;
2443 // If "this" is not an object, likewise return false (again, like
2444 // OrdinaryHasInstance).
2445 if (!args.thisv().isObject()) {
2446 args.rval().setBoolean(false);
2447 return true;
2450 // If "this" doesn't have a DOMIfaceAndProtoJSClass, it's not a DOM
2451 // constructor, so just fall back to OrdinaryHasInstance. But note that we
2452 // should CheckedUnwrapStatic here, because otherwise we won't get the right
2453 // answers. The static version is OK, because we're looking for DOM
2454 // constructors, which are not cross-origin objects.
2455 JS::Rooted<JSObject*> thisObj(
2456 cx, js::CheckedUnwrapStatic(&args.thisv().toObject()));
2457 if (!thisObj) {
2458 // Just fall back on the normal thing, in case it still happens to work.
2459 return CallOrdinaryHasInstance(cx, args);
2462 const JSClass* thisClass = JS::GetClass(thisObj);
2464 if (!IsDOMIfaceAndProtoClass(thisClass)) {
2465 return CallOrdinaryHasInstance(cx, args);
2468 const DOMIfaceAndProtoJSClass* clasp =
2469 DOMIfaceAndProtoJSClass::FromJSClass(thisClass);
2471 // If "this" isn't a DOM constructor or is a constructor for an interface
2472 // without a prototype, just fall back to OrdinaryHasInstance.
2473 if (clasp->mType != eInterface ||
2474 clasp->mPrototypeID == prototypes::id::_ID_Count) {
2475 return CallOrdinaryHasInstance(cx, args);
2478 JS::Rooted<JSObject*> instance(cx, &args[0].toObject());
2479 const DOMJSClass* domClass = GetDOMClass(
2480 js::UncheckedUnwrap(instance, /* stopAtWindowProxy = */ false));
2482 if (domClass &&
2483 domClass->mInterfaceChain[clasp->mDepth] == clasp->mPrototypeID) {
2484 args.rval().setBoolean(true);
2485 return true;
2488 if (IsRemoteObjectProxy(instance, clasp->mPrototypeID)) {
2489 args.rval().setBoolean(true);
2490 return true;
2493 return CallOrdinaryHasInstance(cx, args);
2496 bool InterfaceHasInstance(JSContext* cx, int prototypeID, int depth,
2497 JS::Handle<JSObject*> instance, bool* bp) {
2498 const DOMJSClass* domClass = GetDOMClass(js::UncheckedUnwrap(instance));
2500 MOZ_ASSERT(!domClass || prototypeID != prototypes::id::_ID_Count,
2501 "Why do we have a hasInstance hook if we don't have a prototype "
2502 "ID?");
2504 *bp = (domClass && domClass->mInterfaceChain[depth] == prototypeID);
2505 return true;
2508 bool InterfaceIsInstance(JSContext* cx, unsigned argc, JS::Value* vp) {
2509 JS::CallArgs args = JS::CallArgsFromVp(argc, vp);
2511 // If the thing we were passed is not an object, return false.
2512 if (!args.get(0).isObject()) {
2513 args.rval().setBoolean(false);
2514 return true;
2517 // If "this" isn't a DOM constructor or is a constructor for an interface
2518 // without a prototype, return false.
2519 if (!args.thisv().isObject()) {
2520 args.rval().setBoolean(false);
2521 return true;
2524 // CheckedUnwrapStatic is fine, since we're just interested in finding out
2525 // whether this is a DOM constructor.
2526 JS::Rooted<JSObject*> thisObj(
2527 cx, js::CheckedUnwrapStatic(&args.thisv().toObject()));
2528 if (!thisObj) {
2529 args.rval().setBoolean(false);
2530 return true;
2533 const JSClass* thisClass = JS::GetClass(thisObj);
2534 if (!IsDOMIfaceAndProtoClass(thisClass)) {
2535 args.rval().setBoolean(false);
2536 return true;
2539 const DOMIfaceAndProtoJSClass* clasp =
2540 DOMIfaceAndProtoJSClass::FromJSClass(thisClass);
2542 if (clasp->mType != eInterface ||
2543 clasp->mPrototypeID == prototypes::id::_ID_Count) {
2544 args.rval().setBoolean(false);
2545 return true;
2548 JS::Rooted<JSObject*> instance(cx, &args[0].toObject());
2549 const DOMJSClass* domClass = GetDOMClass(
2550 js::UncheckedUnwrap(instance, /* stopAtWindowProxy = */ false));
2552 bool isInstance = domClass && domClass->mInterfaceChain[clasp->mDepth] ==
2553 clasp->mPrototypeID;
2555 args.rval().setBoolean(isInstance);
2556 return true;
2559 bool ReportLenientThisUnwrappingFailure(JSContext* cx, JSObject* obj) {
2560 JS::Rooted<JSObject*> rootedObj(cx, obj);
2561 GlobalObject global(cx, rootedObj);
2562 if (global.Failed()) {
2563 return false;
2565 nsCOMPtr<nsPIDOMWindowInner> window =
2566 do_QueryInterface(global.GetAsSupports());
2567 if (window && window->GetDoc()) {
2568 window->GetDoc()->WarnOnceAbout(DeprecatedOperations::eLenientThis);
2570 return true;
2573 bool GetContentGlobalForJSImplementedObject(BindingCallContext& cx,
2574 JS::Handle<JSObject*> obj,
2575 nsIGlobalObject** globalObj) {
2576 // Be very careful to not get tricked here.
2577 MOZ_ASSERT(NS_IsMainThread());
2578 if (!xpc::AccessCheck::isChrome(JS::GetCompartment(obj))) {
2579 MOZ_CRASH("Should have a chrome object here");
2582 // Look up the content-side object.
2583 JS::Rooted<JS::Value> domImplVal(cx);
2584 if (!JS_GetProperty(cx, obj, "__DOM_IMPL__", &domImplVal)) {
2585 return false;
2588 if (!domImplVal.isObject()) {
2589 cx.ThrowErrorMessage<MSG_NOT_OBJECT>("Value");
2590 return false;
2593 // Go ahead and get the global from it. GlobalObject will handle
2594 // doing unwrapping as needed.
2595 GlobalObject global(cx, &domImplVal.toObject());
2596 if (global.Failed()) {
2597 return false;
2600 DebugOnly<nsresult> rv =
2601 CallQueryInterface(global.GetAsSupports(), globalObj);
2602 MOZ_ASSERT(NS_SUCCEEDED(rv));
2603 MOZ_ASSERT(*globalObj);
2604 return true;
2607 void ConstructJSImplementation(const char* aContractId,
2608 nsIGlobalObject* aGlobal,
2609 JS::MutableHandle<JSObject*> aObject,
2610 ErrorResult& aRv) {
2611 MOZ_ASSERT(NS_IsMainThread());
2613 // Make sure to divorce ourselves from the calling JS while creating and
2614 // initializing the object, so exceptions from that will get reported
2615 // properly, since those are never exceptions that a spec wants to be thrown.
2617 AutoNoJSAPI nojsapi;
2619 nsCOMPtr<nsPIDOMWindowInner> window = do_QueryInterface(aGlobal);
2620 if (!window) {
2621 aRv.ThrowInvalidStateError("Global is not a Window");
2622 return;
2624 if (!window->IsCurrentInnerWindow()) {
2625 aRv.ThrowInvalidStateError("Window no longer active");
2626 return;
2629 // Get the XPCOM component containing the JS implementation.
2630 nsresult rv;
2631 nsCOMPtr<nsISupports> implISupports = do_CreateInstance(aContractId, &rv);
2632 if (!implISupports) {
2633 nsPrintfCString msg("Failed to get JS implementation for contract \"%s\"",
2634 aContractId);
2635 NS_WARNING(msg.get());
2636 aRv.Throw(rv);
2637 return;
2639 // Initialize the object, if it implements nsIDOMGlobalPropertyInitializer
2640 // and our global is a window.
2641 nsCOMPtr<nsIDOMGlobalPropertyInitializer> gpi =
2642 do_QueryInterface(implISupports);
2643 if (gpi) {
2644 JS::Rooted<JS::Value> initReturn(RootingCx());
2645 rv = gpi->Init(window, &initReturn);
2646 if (NS_FAILED(rv)) {
2647 aRv.Throw(rv);
2648 return;
2650 // With JS-implemented WebIDL, the return value of init() is not used to
2651 // determine if init() failed, so init() should only return undefined. Any
2652 // kind of permission or pref checking must happen by adding an attribute
2653 // to the WebIDL interface.
2654 if (!initReturn.isUndefined()) {
2655 MOZ_ASSERT(false,
2656 "The init() method for JS-implemented WebIDL should not "
2657 "return anything");
2658 MOZ_CRASH();
2661 // Extract the JS implementation from the XPCOM object.
2662 nsCOMPtr<nsIXPConnectWrappedJS> implWrapped =
2663 do_QueryInterface(implISupports, &rv);
2664 MOZ_ASSERT(implWrapped, "Failed to get wrapped JS from XPCOM component.");
2665 if (!implWrapped) {
2666 aRv.Throw(rv);
2667 return;
2669 aObject.set(implWrapped->GetJSObject());
2670 if (!aObject) {
2671 aRv.Throw(NS_ERROR_FAILURE);
2676 bool NonVoidByteStringToJsval(JSContext* cx, const nsACString& str,
2677 JS::MutableHandle<JS::Value> rval) {
2678 // ByteStrings are not UTF-8 encoded.
2679 JSString* jsStr = JS_NewStringCopyN(cx, str.Data(), str.Length());
2680 if (!jsStr) {
2681 return false;
2683 rval.setString(jsStr);
2684 return true;
2687 bool NormalizeUSVString(nsAString& aString) {
2688 return EnsureUTF16Validity(aString);
2691 bool NormalizeUSVString(binding_detail::FakeString<char16_t>& aString) {
2692 uint32_t upTo = Utf16ValidUpTo(aString);
2693 uint32_t len = aString.Length();
2694 if (upTo == len) {
2695 return true;
2697 // This is the part that's different from EnsureUTF16Validity with an
2698 // nsAString& argument, because we don't want to ensure mutability in our
2699 // BeginWriting() in the common case and nsAString's EnsureMutable is not
2700 // public. This is a little annoying; I wish we could just share the more or
2701 // less identical code!
2702 if (!aString.EnsureMutable()) {
2703 return false;
2706 char16_t* ptr = aString.BeginWriting();
2707 auto span = Span(ptr, len);
2708 span[upTo] = 0xFFFD;
2709 EnsureUtf16ValiditySpan(span.From(upTo + 1));
2710 return true;
2713 bool ConvertJSValueToByteString(BindingCallContext& cx, JS::Handle<JS::Value> v,
2714 bool nullable, const char* sourceDescription,
2715 nsACString& result) {
2716 JS::Rooted<JSString*> s(cx);
2717 if (v.isString()) {
2718 s = v.toString();
2719 } else {
2720 if (nullable && v.isNullOrUndefined()) {
2721 result.SetIsVoid(true);
2722 return true;
2725 s = JS::ToString(cx, v);
2726 if (!s) {
2727 return false;
2731 // Conversion from Javascript string to ByteString is only valid if all
2732 // characters < 256. This is always the case for Latin1 strings.
2733 size_t length;
2734 if (!JS::StringHasLatin1Chars(s)) {
2735 // ThrowErrorMessage can GC, so we first scan the string for bad chars
2736 // and report the error outside the AutoCheckCannotGC scope.
2737 bool foundBadChar = false;
2738 size_t badCharIndex;
2739 char16_t badChar;
2741 JS::AutoCheckCannotGC nogc;
2742 const char16_t* chars =
2743 JS_GetTwoByteStringCharsAndLength(cx, nogc, s, &length);
2744 if (!chars) {
2745 return false;
2748 for (size_t i = 0; i < length; i++) {
2749 if (chars[i] > 255) {
2750 badCharIndex = i;
2751 badChar = chars[i];
2752 foundBadChar = true;
2753 break;
2758 if (foundBadChar) {
2759 MOZ_ASSERT(badCharIndex < length);
2760 MOZ_ASSERT(badChar > 255);
2761 // The largest unsigned 64 bit number (18,446,744,073,709,551,615) has
2762 // 20 digits, plus one more for the null terminator.
2763 char index[21];
2764 static_assert(sizeof(size_t) <= 8, "index array too small");
2765 SprintfLiteral(index, "%zu", badCharIndex);
2766 // A char16_t is 16 bits long. The biggest unsigned 16 bit
2767 // number (65,535) has 5 digits, plus one more for the null
2768 // terminator.
2769 char badCharArray[6];
2770 static_assert(sizeof(char16_t) <= 2, "badCharArray too small");
2771 SprintfLiteral(badCharArray, "%d", badChar);
2772 cx.ThrowErrorMessage<MSG_INVALID_BYTESTRING>(sourceDescription, index,
2773 badCharArray);
2774 return false;
2776 } else {
2777 length = JS::GetStringLength(s);
2780 static_assert(JS::MaxStringLength < UINT32_MAX,
2781 "length+1 shouldn't overflow");
2783 if (!result.SetLength(length, fallible)) {
2784 return false;
2787 if (!JS_EncodeStringToBuffer(cx, s, result.BeginWriting(), length)) {
2788 return false;
2791 return true;
2794 void FinalizeGlobal(JSFreeOp* aFreeOp, JSObject* aObj) {
2795 MOZ_ASSERT(JS::GetClass(aObj)->flags & JSCLASS_DOM_GLOBAL);
2796 mozilla::dom::DestroyProtoAndIfaceCache(aObj);
2799 bool ResolveGlobal(JSContext* aCx, JS::Handle<JSObject*> aObj,
2800 JS::Handle<jsid> aId, bool* aResolvedp) {
2801 MOZ_ASSERT(JS_IsGlobalObject(aObj),
2802 "Should have a global here, since we plan to resolve standard "
2803 "classes!");
2805 return JS_ResolveStandardClass(aCx, aObj, aId, aResolvedp);
2808 bool MayResolveGlobal(const JSAtomState& aNames, jsid aId,
2809 JSObject* aMaybeObj) {
2810 return JS_MayResolveStandardClass(aNames, aId, aMaybeObj);
2813 bool EnumerateGlobal(JSContext* aCx, JS::HandleObject aObj,
2814 JS::MutableHandleVector<jsid> aProperties,
2815 bool aEnumerableOnly) {
2816 MOZ_ASSERT(JS_IsGlobalObject(aObj),
2817 "Should have a global here, since we plan to enumerate standard "
2818 "classes!");
2820 return JS_NewEnumerateStandardClasses(aCx, aObj, aProperties,
2821 aEnumerableOnly);
2824 bool IsNonExposedGlobal(JSContext* aCx, JSObject* aGlobal,
2825 uint32_t aNonExposedGlobals) {
2826 MOZ_ASSERT(aNonExposedGlobals, "Why did we get called?");
2827 MOZ_ASSERT(
2828 (aNonExposedGlobals & ~(GlobalNames::Window | GlobalNames::BackstagePass |
2829 GlobalNames::DedicatedWorkerGlobalScope |
2830 GlobalNames::SharedWorkerGlobalScope |
2831 GlobalNames::ServiceWorkerGlobalScope |
2832 GlobalNames::WorkerDebuggerGlobalScope |
2833 GlobalNames::WorkletGlobalScope |
2834 GlobalNames::AudioWorkletGlobalScope |
2835 GlobalNames::PaintWorkletGlobalScope)) == 0,
2836 "Unknown non-exposed global type");
2838 const char* name = JS::GetClass(aGlobal)->name;
2840 if ((aNonExposedGlobals & GlobalNames::Window) && !strcmp(name, "Window")) {
2841 return true;
2844 if ((aNonExposedGlobals & GlobalNames::BackstagePass) &&
2845 !strcmp(name, "BackstagePass")) {
2846 return true;
2849 if ((aNonExposedGlobals & GlobalNames::DedicatedWorkerGlobalScope) &&
2850 !strcmp(name, "DedicatedWorkerGlobalScope")) {
2851 return true;
2854 if ((aNonExposedGlobals & GlobalNames::SharedWorkerGlobalScope) &&
2855 !strcmp(name, "SharedWorkerGlobalScope")) {
2856 return true;
2859 if ((aNonExposedGlobals & GlobalNames::ServiceWorkerGlobalScope) &&
2860 !strcmp(name, "ServiceWorkerGlobalScope")) {
2861 return true;
2864 if ((aNonExposedGlobals & GlobalNames::WorkerDebuggerGlobalScope) &&
2865 !strcmp(name, "WorkerDebuggerGlobalScopex")) {
2866 return true;
2869 if ((aNonExposedGlobals & GlobalNames::WorkletGlobalScope) &&
2870 !strcmp(name, "WorkletGlobalScope")) {
2871 return true;
2874 if ((aNonExposedGlobals & GlobalNames::AudioWorkletGlobalScope) &&
2875 !strcmp(name, "AudioWorkletGlobalScope")) {
2876 return true;
2879 if ((aNonExposedGlobals & GlobalNames::PaintWorkletGlobalScope) &&
2880 !strcmp(name, "PaintWorkletGlobalScope")) {
2881 return true;
2884 return false;
2887 namespace binding_detail {
2890 * A ThisPolicy struct needs to provide the following methods:
2892 * HasValidThisValue: Takes a CallArgs and returns a boolean indicating whether
2893 * the thisv() is valid in the sense of being the right type
2894 * of Value. It does not check whether it's the right sort
2895 * of object if the Value is a JSObject*.
2897 * ExtractThisObject: Takes a CallArgs for which HasValidThisValue was true and
2898 * returns the JSObject* to use for getting |this|.
2900 * MaybeUnwrapThisObject: If our |this| is a JSObject* that this policy wants to
2901 * allow unchecked access to for this
2902 * getter/setter/method, unwrap it. Otherwise just
2903 * return the given object.
2905 * UnwrapThisObject: Takes a MutableHandle for a JSObject which contains the
2906 * this object (which the caller probably got from
2907 * MaybeUnwrapThisObject). It will try to get the right native
2908 * out of aObj. In some cases there are 2 possible types for
2909 * the native (which is why aSelf is a reference to a void*).
2910 * The ThisPolicy user should use the this JSObject* to
2911 * determine what C++ class aSelf contains. aObj is used to
2912 * keep the reflector object alive while self is being used,
2913 * so its value before and after the UnwrapThisObject call
2914 * could be different (if aObj was wrapped). The return value
2915 * is an nsresult, which will signal if an error occurred.
2917 * This is passed a JSContext for dynamic unwrapping purposes,
2918 * but should not throw exceptions on that JSContext.
2920 * HandleInvalidThis: If the |this| is not valid (wrong type of value, wrong
2921 * object, etc), decide what to do about it. Returns a
2922 * boolean to return from the JSNative (false for failure,
2923 * true for succcess).
2925 struct NormalThisPolicy {
2926 // This needs to be inlined because it's called on no-exceptions fast-paths.
2927 static MOZ_ALWAYS_INLINE bool HasValidThisValue(const JS::CallArgs& aArgs) {
2928 // Per WebIDL spec, all getters/setters/methods allow null/undefined "this"
2929 // and coerce it to the global. Then the "is this the right interface?"
2930 // check fails if the interface involved is not one that the global
2931 // implements.
2933 // As an optimization, we skip doing the null/undefined stuff if we know our
2934 // interface is not implemented by the global.
2935 return aArgs.thisv().isObject();
2938 static MOZ_ALWAYS_INLINE JSObject* ExtractThisObject(
2939 const JS::CallArgs& aArgs) {
2940 return &aArgs.thisv().toObject();
2943 static MOZ_ALWAYS_INLINE JSObject* MaybeUnwrapThisObject(JSObject* aObj) {
2944 return aObj;
2947 static MOZ_ALWAYS_INLINE nsresult UnwrapThisObject(
2948 JS::MutableHandle<JSObject*> aObj, JSContext* aCx, void*& aSelf,
2949 prototypes::ID aProtoID, uint32_t aProtoDepth) {
2950 binding_detail::MutableObjectHandleWrapper wrapper(aObj);
2951 return binding_detail::UnwrapObjectInternal<void, true>(
2952 wrapper, aSelf, aProtoID, aProtoDepth, aCx);
2955 static bool HandleInvalidThis(JSContext* aCx, const JS::CallArgs& aArgs,
2956 bool aSecurityError, prototypes::ID aProtoId) {
2957 return ThrowInvalidThis(aCx, aArgs, aSecurityError, aProtoId);
2961 struct MaybeGlobalThisPolicy : public NormalThisPolicy {
2962 static MOZ_ALWAYS_INLINE bool HasValidThisValue(const JS::CallArgs& aArgs) {
2963 // Here we have to allow null/undefined.
2964 return aArgs.thisv().isObject() || aArgs.thisv().isNullOrUndefined();
2967 static MOZ_ALWAYS_INLINE JSObject* ExtractThisObject(
2968 const JS::CallArgs& aArgs) {
2969 return aArgs.thisv().isObject()
2970 ? &aArgs.thisv().toObject()
2971 : JS::GetNonCCWObjectGlobal(&aArgs.callee());
2974 // We want the MaybeUnwrapThisObject of NormalThisPolicy.
2976 // We want the HandleInvalidThis of NormalThisPolicy.
2979 // Shared LenientThis behavior for our two different LenientThis policies.
2980 struct LenientThisPolicyMixin {
2981 static bool HandleInvalidThis(JSContext* aCx, const JS::CallArgs& aArgs,
2982 bool aSecurityError, prototypes::ID aProtoId) {
2983 if (aSecurityError) {
2984 return NormalThisPolicy::HandleInvalidThis(aCx, aArgs, aSecurityError,
2985 aProtoId);
2988 MOZ_ASSERT(!JS_IsExceptionPending(aCx));
2989 if (!ReportLenientThisUnwrappingFailure(aCx, &aArgs.callee())) {
2990 return false;
2992 aArgs.rval().set(JS::UndefinedValue());
2993 return true;
2997 // There are some LenientThis things on globals, so we inherit from
2998 // MaybeGlobalThisPolicy.
2999 struct LenientThisPolicy : public MaybeGlobalThisPolicy,
3000 public LenientThisPolicyMixin {
3001 // We want the HasValidThisValue of MaybeGlobalThisPolicy.
3003 // We want the ExtractThisObject of MaybeGlobalThisPolicy.
3005 // We want the MaybeUnwrapThisObject of MaybeGlobalThisPolicy.
3007 // We want HandleInvalidThis from LenientThisPolicyMixin
3008 using LenientThisPolicyMixin::HandleInvalidThis;
3011 // There are some cross-origin things on globals, so we inherit from
3012 // MaybeGlobalThisPolicy.
3013 struct CrossOriginThisPolicy : public MaybeGlobalThisPolicy {
3014 // We want the HasValidThisValue of MaybeGlobalThisPolicy.
3016 // We want the ExtractThisObject of MaybeGlobalThisPolicy.
3018 static MOZ_ALWAYS_INLINE JSObject* MaybeUnwrapThisObject(JSObject* aObj) {
3019 if (xpc::WrapperFactory::IsCrossOriginWrapper(aObj)) {
3020 return js::UncheckedUnwrap(aObj);
3023 // Else just return aObj; our UnwrapThisObject call will try to
3024 // CheckedUnwrap it, and either succeed or get a security error as needed.
3025 return aObj;
3028 // After calling UnwrapThisObject aSelf can contain one of 2 types, depending
3029 // on whether aObj is a proxy with a RemoteObjectProxy handler or a (maybe
3030 // wrapped) normal WebIDL reflector. The generated binding code relies on this
3031 // and uses IsRemoteObjectProxy to determine what type aSelf points to.
3032 static MOZ_ALWAYS_INLINE nsresult UnwrapThisObject(
3033 JS::MutableHandle<JSObject*> aObj, JSContext* aCx, void*& aSelf,
3034 prototypes::ID aProtoID, uint32_t aProtoDepth) {
3035 binding_detail::MutableObjectHandleWrapper wrapper(aObj);
3036 // We need to pass false here, because if aObj doesn't have a DOMJSClass
3037 // it might be a remote proxy object, and we don't want to throw in that
3038 // case (even though unwrapping would fail).
3039 nsresult rv = binding_detail::UnwrapObjectInternal<void, false>(
3040 wrapper, aSelf, aProtoID, aProtoDepth, nullptr);
3041 if (NS_SUCCEEDED(rv)) {
3042 return rv;
3045 if (js::IsWrapper(wrapper)) {
3046 // We want CheckedUnwrapDynamic here: aCx represents the Realm we are in
3047 // right now, so we want to check whether that Realm should be able to
3048 // access the object. And this object can definitely be a WindowProxy, so
3049 // we need he dynamic check.
3050 JSObject* unwrappedObj = js::CheckedUnwrapDynamic(
3051 wrapper, aCx, /* stopAtWindowProxy = */ false);
3052 if (!unwrappedObj) {
3053 return NS_ERROR_XPC_SECURITY_MANAGER_VETO;
3056 // At this point we want to keep "unwrappedObj" alive, because we don't
3057 // hold a strong reference in "aSelf".
3058 wrapper = unwrappedObj;
3060 return binding_detail::UnwrapObjectInternal<void, false>(
3061 wrapper, aSelf, aProtoID, aProtoDepth, nullptr);
3064 if (!IsRemoteObjectProxy(wrapper, aProtoID)) {
3065 return NS_ERROR_XPC_BAD_CONVERT_JS;
3067 aSelf = RemoteObjectProxyBase::GetNative(wrapper);
3068 return NS_OK;
3071 // We want the HandleInvalidThis of MaybeGlobalThisPolicy.
3074 // Some objects that can be cross-origin objects are globals, so we inherit
3075 // from MaybeGlobalThisPolicy.
3076 struct MaybeCrossOriginObjectThisPolicy : public MaybeGlobalThisPolicy {
3077 // We want the HasValidThisValue of MaybeGlobalThisPolicy.
3079 // We want the ExtractThisObject of MaybeGlobalThisPolicy.
3081 // We want the MaybeUnwrapThisObject of MaybeGlobalThisPolicy
3083 static MOZ_ALWAYS_INLINE nsresult UnwrapThisObject(
3084 JS::MutableHandle<JSObject*> aObj, JSContext* aCx, void*& aSelf,
3085 prototypes::ID aProtoID, uint32_t aProtoDepth) {
3086 // There are two cases at this point: either aObj is a cross-compartment
3087 // wrapper (CCW) or it's not. If it is, we don't need to do anything
3088 // special compared to MaybeGlobalThisPolicy: the CCW will do the relevant
3089 // security checks. Which is good, because if we tried to do the
3090 // cross-origin object check _before_ unwrapping it would always come back
3091 // as "same-origin" and if we tried to do it after unwrapping it would be
3092 // completely wrong: the checks rely on the two sides of the comparison
3093 // being symmetric (can access each other or cannot access each other), but
3094 // if we have a CCW we could have an Xray, which is asymmetric. And then
3095 // we'd think we should deny access, whereas we should actually allow
3096 // access.
3098 // If we do _not_ have a CCW here, then we need to check whether it's a
3099 // cross-origin-accessible object, and if it is check whether it's
3100 // same-origin-domain with our current callee.
3101 if (!js::IsCrossCompartmentWrapper(aObj) &&
3102 xpc::IsCrossOriginAccessibleObject(aObj) &&
3103 !MaybeCrossOriginObjectMixins::IsPlatformObjectSameOrigin(aCx, aObj)) {
3104 return NS_ERROR_XPC_SECURITY_MANAGER_VETO;
3107 return MaybeGlobalThisPolicy::UnwrapThisObject(aObj, aCx, aSelf, aProtoID,
3108 aProtoDepth);
3111 // We want the HandleInvalidThis of MaybeGlobalThisPolicy.
3114 // And in some cases we are dealing with a maybe-cross-origin object _and_ need
3115 // [LenientThis] behavior.
3116 struct MaybeCrossOriginObjectLenientThisPolicy
3117 : public MaybeCrossOriginObjectThisPolicy,
3118 public LenientThisPolicyMixin {
3119 // We want to get all of our behavior from
3120 // MaybeCrossOriginObjectLenientThisPolicy, except for HandleInvalidThis,
3121 // which should come from LenientThisPolicyMixin.
3122 using LenientThisPolicyMixin::HandleInvalidThis;
3126 * An ExceptionPolicy struct provides a single HandleException method which is
3127 * used to handle an exception, if any. The method is given the current
3128 * success/failure boolean so it can decide whether there is in fact an
3129 * exception involved.
3131 struct ThrowExceptions {
3132 // This needs to be inlined because it's called even on no-exceptions
3133 // fast-paths.
3134 static MOZ_ALWAYS_INLINE bool HandleException(JSContext* aCx,
3135 JS::CallArgs& aArgs,
3136 const JSJitInfo* aInfo,
3137 bool aOK) {
3138 return aOK;
3142 struct ConvertExceptionsToPromises {
3143 // This needs to be inlined because it's called even on no-exceptions
3144 // fast-paths.
3145 static MOZ_ALWAYS_INLINE bool HandleException(JSContext* aCx,
3146 JS::CallArgs& aArgs,
3147 const JSJitInfo* aInfo,
3148 bool aOK) {
3149 // Promise-returning getters/methods always return objects.
3150 MOZ_ASSERT(aInfo->returnType() == JSVAL_TYPE_OBJECT);
3152 if (aOK) {
3153 return true;
3156 return ConvertExceptionToPromise(aCx, aArgs.rval());
3160 template <typename ThisPolicy, typename ExceptionPolicy>
3161 bool GenericGetter(JSContext* cx, unsigned argc, JS::Value* vp) {
3162 JS::CallArgs args = JS::CallArgsFromVp(argc, vp);
3163 const JSJitInfo* info = FUNCTION_VALUE_TO_JITINFO(args.calleev());
3164 prototypes::ID protoID = static_cast<prototypes::ID>(info->protoID);
3165 if (!ThisPolicy::HasValidThisValue(args)) {
3166 bool ok = ThisPolicy::HandleInvalidThis(cx, args, false, protoID);
3167 return ExceptionPolicy::HandleException(cx, args, info, ok);
3169 JS::Rooted<JSObject*> obj(cx, ThisPolicy::ExtractThisObject(args));
3171 // NOTE: we want to leave obj in its initial compartment, so don't want to
3172 // pass it to UnwrapObjectInternal. Also, the thing we pass to
3173 // UnwrapObjectInternal may be affected by our ThisPolicy.
3174 JS::Rooted<JSObject*> rootSelf(cx, ThisPolicy::MaybeUnwrapThisObject(obj));
3175 void* self;
3177 nsresult rv =
3178 ThisPolicy::UnwrapThisObject(&rootSelf, cx, self, protoID, info->depth);
3179 if (NS_FAILED(rv)) {
3180 bool ok = ThisPolicy::HandleInvalidThis(
3181 cx, args, rv == NS_ERROR_XPC_SECURITY_MANAGER_VETO, protoID);
3182 return ExceptionPolicy::HandleException(cx, args, info, ok);
3186 MOZ_ASSERT(info->type() == JSJitInfo::Getter);
3187 JSJitGetterOp getter = info->getter;
3188 bool ok = getter(cx, obj, self, JSJitGetterCallArgs(args));
3189 #ifdef DEBUG
3190 if (ok) {
3191 AssertReturnTypeMatchesJitinfo(info, args.rval());
3193 #endif
3194 return ExceptionPolicy::HandleException(cx, args, info, ok);
3197 // Force instantiation of the specializations of GenericGetter we need here.
3198 template bool GenericGetter<NormalThisPolicy, ThrowExceptions>(JSContext* cx,
3199 unsigned argc,
3200 JS::Value* vp);
3201 template bool GenericGetter<NormalThisPolicy, ConvertExceptionsToPromises>(
3202 JSContext* cx, unsigned argc, JS::Value* vp);
3203 template bool GenericGetter<MaybeGlobalThisPolicy, ThrowExceptions>(
3204 JSContext* cx, unsigned argc, JS::Value* vp);
3205 template bool GenericGetter<MaybeGlobalThisPolicy, ConvertExceptionsToPromises>(
3206 JSContext* cx, unsigned argc, JS::Value* vp);
3207 template bool GenericGetter<LenientThisPolicy, ThrowExceptions>(JSContext* cx,
3208 unsigned argc,
3209 JS::Value* vp);
3210 // There aren't any [LenientThis] Promise-returning getters, so don't
3211 // bother instantiating that specialization.
3212 template bool GenericGetter<CrossOriginThisPolicy, ThrowExceptions>(
3213 JSContext* cx, unsigned argc, JS::Value* vp);
3214 // There aren't any cross-origin Promise-returning getters, so don't
3215 // bother instantiating that specialization.
3216 template bool GenericGetter<MaybeCrossOriginObjectThisPolicy, ThrowExceptions>(
3217 JSContext* cx, unsigned argc, JS::Value* vp);
3218 // There aren't any maybe-cross-origin-object Promise-returning getters, so
3219 // don't bother instantiating that specialization.
3220 template bool GenericGetter<MaybeCrossOriginObjectLenientThisPolicy,
3221 ThrowExceptions>(JSContext* cx, unsigned argc,
3222 JS::Value* vp);
3223 // There aren't any maybe-cross-origin-object Promise-returning lenient-this
3224 // getters, so don't bother instantiating that specialization.
3226 template <typename ThisPolicy>
3227 bool GenericSetter(JSContext* cx, unsigned argc, JS::Value* vp) {
3228 JS::CallArgs args = JS::CallArgsFromVp(argc, vp);
3229 const JSJitInfo* info = FUNCTION_VALUE_TO_JITINFO(args.calleev());
3230 prototypes::ID protoID = static_cast<prototypes::ID>(info->protoID);
3231 if (!ThisPolicy::HasValidThisValue(args)) {
3232 return ThisPolicy::HandleInvalidThis(cx, args, false, protoID);
3234 JS::Rooted<JSObject*> obj(cx, ThisPolicy::ExtractThisObject(args));
3236 // NOTE: we want to leave obj in its initial compartment, so don't want to
3237 // pass it to UnwrapObject. Also the thing we pass to UnwrapObjectInternal
3238 // may be affected by our ThisPolicy.
3239 JS::Rooted<JSObject*> rootSelf(cx, ThisPolicy::MaybeUnwrapThisObject(obj));
3240 void* self;
3242 nsresult rv =
3243 ThisPolicy::UnwrapThisObject(&rootSelf, cx, self, protoID, info->depth);
3244 if (NS_FAILED(rv)) {
3245 return ThisPolicy::HandleInvalidThis(
3246 cx, args, rv == NS_ERROR_XPC_SECURITY_MANAGER_VETO, protoID);
3249 if (args.length() == 0) {
3250 return ThrowNoSetterArg(cx, args, protoID);
3252 MOZ_ASSERT(info->type() == JSJitInfo::Setter);
3253 JSJitSetterOp setter = info->setter;
3254 if (!setter(cx, obj, self, JSJitSetterCallArgs(args))) {
3255 return false;
3257 args.rval().setUndefined();
3258 #ifdef DEBUG
3259 AssertReturnTypeMatchesJitinfo(info, args.rval());
3260 #endif
3261 return true;
3264 // Force instantiation of the specializations of GenericSetter we need here.
3265 template bool GenericSetter<NormalThisPolicy>(JSContext* cx, unsigned argc,
3266 JS::Value* vp);
3267 template bool GenericSetter<MaybeGlobalThisPolicy>(JSContext* cx, unsigned argc,
3268 JS::Value* vp);
3269 template bool GenericSetter<LenientThisPolicy>(JSContext* cx, unsigned argc,
3270 JS::Value* vp);
3271 template bool GenericSetter<CrossOriginThisPolicy>(JSContext* cx, unsigned argc,
3272 JS::Value* vp);
3273 template bool GenericSetter<MaybeCrossOriginObjectThisPolicy>(JSContext* cx,
3274 unsigned argc,
3275 JS::Value* vp);
3276 template bool GenericSetter<MaybeCrossOriginObjectLenientThisPolicy>(
3277 JSContext* cx, unsigned argc, JS::Value* vp);
3279 template <typename ThisPolicy, typename ExceptionPolicy>
3280 bool GenericMethod(JSContext* cx, unsigned argc, JS::Value* vp) {
3281 JS::CallArgs args = JS::CallArgsFromVp(argc, vp);
3282 const JSJitInfo* info = FUNCTION_VALUE_TO_JITINFO(args.calleev());
3283 prototypes::ID protoID = static_cast<prototypes::ID>(info->protoID);
3284 if (!ThisPolicy::HasValidThisValue(args)) {
3285 bool ok = ThisPolicy::HandleInvalidThis(cx, args, false, protoID);
3286 return ExceptionPolicy::HandleException(cx, args, info, ok);
3288 JS::Rooted<JSObject*> obj(cx, ThisPolicy::ExtractThisObject(args));
3290 // NOTE: we want to leave obj in its initial compartment, so don't want to
3291 // pass it to UnwrapObjectInternal. Also, the thing we pass to
3292 // UnwrapObjectInternal may be affected by our ThisPolicy.
3293 JS::Rooted<JSObject*> rootSelf(cx, ThisPolicy::MaybeUnwrapThisObject(obj));
3294 void* self;
3296 nsresult rv =
3297 ThisPolicy::UnwrapThisObject(&rootSelf, cx, self, protoID, info->depth);
3298 if (NS_FAILED(rv)) {
3299 bool ok = ThisPolicy::HandleInvalidThis(
3300 cx, args, rv == NS_ERROR_XPC_SECURITY_MANAGER_VETO, protoID);
3301 return ExceptionPolicy::HandleException(cx, args, info, ok);
3304 MOZ_ASSERT(info->type() == JSJitInfo::Method);
3305 JSJitMethodOp method = info->method;
3306 bool ok = method(cx, obj, self, JSJitMethodCallArgs(args));
3307 #ifdef DEBUG
3308 if (ok) {
3309 AssertReturnTypeMatchesJitinfo(info, args.rval());
3311 #endif
3312 return ExceptionPolicy::HandleException(cx, args, info, ok);
3315 // Force instantiation of the specializations of GenericMethod we need here.
3316 template bool GenericMethod<NormalThisPolicy, ThrowExceptions>(JSContext* cx,
3317 unsigned argc,
3318 JS::Value* vp);
3319 template bool GenericMethod<NormalThisPolicy, ConvertExceptionsToPromises>(
3320 JSContext* cx, unsigned argc, JS::Value* vp);
3321 template bool GenericMethod<MaybeGlobalThisPolicy, ThrowExceptions>(
3322 JSContext* cx, unsigned argc, JS::Value* vp);
3323 template bool GenericMethod<MaybeGlobalThisPolicy, ConvertExceptionsToPromises>(
3324 JSContext* cx, unsigned argc, JS::Value* vp);
3325 template bool GenericMethod<CrossOriginThisPolicy, ThrowExceptions>(
3326 JSContext* cx, unsigned argc, JS::Value* vp);
3327 // There aren't any cross-origin Promise-returning methods, so don't
3328 // bother instantiating that specialization.
3329 template bool GenericMethod<MaybeCrossOriginObjectThisPolicy, ThrowExceptions>(
3330 JSContext* cx, unsigned argc, JS::Value* vp);
3331 template bool GenericMethod<MaybeCrossOriginObjectThisPolicy,
3332 ConvertExceptionsToPromises>(JSContext* cx,
3333 unsigned argc,
3334 JS::Value* vp);
3336 } // namespace binding_detail
3338 bool StaticMethodPromiseWrapper(JSContext* cx, unsigned argc, JS::Value* vp) {
3339 JS::CallArgs args = JS::CallArgsFromVp(argc, vp);
3341 const JSJitInfo* info = FUNCTION_VALUE_TO_JITINFO(args.calleev());
3342 MOZ_ASSERT(info);
3343 MOZ_ASSERT(info->type() == JSJitInfo::StaticMethod);
3345 bool ok = info->staticMethod(cx, argc, vp);
3346 if (ok) {
3347 return true;
3350 return ConvertExceptionToPromise(cx, args.rval());
3353 bool ConvertExceptionToPromise(JSContext* cx,
3354 JS::MutableHandle<JS::Value> rval) {
3355 JS::Rooted<JS::Value> exn(cx);
3356 if (!JS_GetPendingException(cx, &exn)) {
3357 // This is very important: if there is no pending exception here but we're
3358 // ending up in this code, that means the callee threw an uncatchable
3359 // exception. Just propagate that out as-is.
3360 return false;
3363 JS_ClearPendingException(cx);
3365 JSObject* promise = JS::CallOriginalPromiseReject(cx, exn);
3366 if (!promise) {
3367 // We just give up. Put the exception back.
3368 JS_SetPendingException(cx, exn);
3369 return false;
3372 rval.setObject(*promise);
3373 return true;
3376 /* static */
3377 void CreateGlobalOptionsWithXPConnect::TraceGlobal(JSTracer* aTrc,
3378 JSObject* aObj) {
3379 xpc::TraceXPCGlobal(aTrc, aObj);
3382 /* static */
3383 bool CreateGlobalOptionsWithXPConnect::PostCreateGlobal(
3384 JSContext* aCx, JS::Handle<JSObject*> aGlobal) {
3385 JSPrincipals* principals =
3386 JS::GetRealmPrincipals(js::GetNonCCWObjectRealm(aGlobal));
3387 nsIPrincipal* principal = nsJSPrincipals::get(principals);
3389 SiteIdentifier site;
3390 nsresult rv = BasePrincipal::Cast(principal)->GetSiteIdentifier(site);
3391 NS_ENSURE_SUCCESS(rv, false);
3393 xpc::RealmPrivate::Init(aGlobal, site);
3394 return true;
3397 uint64_t GetWindowID(void* aGlobal) { return 0; }
3399 uint64_t GetWindowID(nsGlobalWindowInner* aGlobal) {
3400 return aGlobal->WindowID();
3403 uint64_t GetWindowID(DedicatedWorkerGlobalScope* aGlobal) {
3404 return aGlobal->WindowID();
3407 #ifdef DEBUG
3408 void AssertReturnTypeMatchesJitinfo(const JSJitInfo* aJitInfo,
3409 JS::Handle<JS::Value> aValue) {
3410 switch (aJitInfo->returnType()) {
3411 case JSVAL_TYPE_UNKNOWN:
3412 // Any value is good.
3413 break;
3414 case JSVAL_TYPE_DOUBLE:
3415 // The value could actually be an int32 value as well.
3416 MOZ_ASSERT(aValue.isNumber());
3417 break;
3418 case JSVAL_TYPE_INT32:
3419 MOZ_ASSERT(aValue.isInt32());
3420 break;
3421 case JSVAL_TYPE_UNDEFINED:
3422 MOZ_ASSERT(aValue.isUndefined());
3423 break;
3424 case JSVAL_TYPE_BOOLEAN:
3425 MOZ_ASSERT(aValue.isBoolean());
3426 break;
3427 case JSVAL_TYPE_STRING:
3428 MOZ_ASSERT(aValue.isString());
3429 break;
3430 case JSVAL_TYPE_NULL:
3431 MOZ_ASSERT(aValue.isNull());
3432 break;
3433 case JSVAL_TYPE_OBJECT:
3434 MOZ_ASSERT(aValue.isObject());
3435 break;
3436 default:
3437 // Someone messed up their jitinfo type.
3438 MOZ_ASSERT(false, "Unexpected JSValueType stored in jitinfo");
3439 break;
3442 #endif
3444 bool CallerSubsumes(JSObject* aObject) {
3445 // Remote object proxies are not CCWs, so unwrapping them does not get you
3446 // their "real" principal, but we want to treat them like cross-origin objects
3447 // when considering them as WebIDL arguments, for consistency.
3448 if (IsRemoteObjectProxy(aObject)) {
3449 return false;
3451 nsIPrincipal* objPrin =
3452 nsContentUtils::ObjectPrincipal(js::UncheckedUnwrap(aObject));
3453 return nsContentUtils::SubjectPrincipal()->Subsumes(objPrin);
3456 nsresult UnwrapArgImpl(JSContext* cx, JS::Handle<JSObject*> src,
3457 const nsIID& iid, void** ppArg) {
3458 if (!NS_IsMainThread()) {
3459 return NS_ERROR_NOT_AVAILABLE;
3462 // The JSContext represents the "who is unwrapping" realm, so we want to use
3463 // it for ReflectorToISupportsDynamic here.
3464 nsCOMPtr<nsISupports> iface = xpc::ReflectorToISupportsDynamic(src, cx);
3465 if (iface) {
3466 if (NS_FAILED(iface->QueryInterface(iid, ppArg))) {
3467 return NS_ERROR_XPC_BAD_CONVERT_JS;
3470 return NS_OK;
3473 // Only allow XPCWrappedJS stuff in system code. Ideally we would remove this
3474 // even there, but that involves converting some things to WebIDL callback
3475 // interfaces and making some other things builtinclass...
3476 if (!nsContentUtils::IsSystemCaller(cx)) {
3477 return NS_ERROR_XPC_BAD_CONVERT_JS;
3480 RefPtr<nsXPCWrappedJS> wrappedJS;
3481 nsresult rv =
3482 nsXPCWrappedJS::GetNewOrUsed(cx, src, iid, getter_AddRefs(wrappedJS));
3483 if (NS_FAILED(rv) || !wrappedJS) {
3484 return rv;
3487 // We need to go through the QueryInterface logic to make this return
3488 // the right thing for the various 'special' interfaces; e.g.
3489 // nsIPropertyBag. We must use AggregatedQueryInterface in cases where
3490 // there is an outer to avoid nasty recursion.
3491 return wrappedJS->QueryInterface(iid, ppArg);
3494 nsresult UnwrapWindowProxyArg(JSContext* cx, JS::Handle<JSObject*> src,
3495 WindowProxyHolder& ppArg) {
3496 if (IsRemoteObjectProxy(src, prototypes::id::Window)) {
3497 ppArg =
3498 static_cast<BrowsingContext*>(RemoteObjectProxyBase::GetNative(src));
3499 return NS_OK;
3502 nsCOMPtr<nsPIDOMWindowInner> inner;
3503 nsresult rv = UnwrapArg<nsPIDOMWindowInner>(cx, src, getter_AddRefs(inner));
3504 NS_ENSURE_SUCCESS(rv, rv);
3506 nsCOMPtr<nsPIDOMWindowOuter> outer = inner->GetOuterWindow();
3507 RefPtr<BrowsingContext> bc = outer ? outer->GetBrowsingContext() : nullptr;
3508 ppArg = std::move(bc);
3509 return NS_OK;
3512 template <decltype(JS::NewMapObject) Method>
3513 bool GetMaplikeSetlikeBackingObject(JSContext* aCx, JS::Handle<JSObject*> aObj,
3514 size_t aSlotIndex,
3515 JS::MutableHandle<JSObject*> aBackingObj,
3516 bool* aBackingObjCreated) {
3517 JS::Rooted<JSObject*> reflector(aCx);
3518 reflector = IsDOMObject(aObj)
3519 ? aObj
3520 : js::UncheckedUnwrap(aObj,
3521 /* stopAtWindowProxy = */ false);
3523 // Retrieve the backing object from the reserved slot on the maplike/setlike
3524 // object. If it doesn't exist yet, create it.
3525 JS::Rooted<JS::Value> slotValue(aCx);
3526 slotValue = JS::GetReservedSlot(reflector, aSlotIndex);
3527 if (slotValue.isUndefined()) {
3528 // Since backing object access can happen in non-originating realms,
3529 // make sure to create the backing object in reflector realm.
3531 JSAutoRealm ar(aCx, reflector);
3532 JS::Rooted<JSObject*> newBackingObj(aCx);
3533 newBackingObj.set(Method(aCx));
3534 if (NS_WARN_IF(!newBackingObj)) {
3535 return false;
3537 JS::SetReservedSlot(reflector, aSlotIndex,
3538 JS::ObjectValue(*newBackingObj));
3540 slotValue = JS::GetReservedSlot(reflector, aSlotIndex);
3541 *aBackingObjCreated = true;
3542 } else {
3543 *aBackingObjCreated = false;
3545 if (!MaybeWrapNonDOMObjectValue(aCx, &slotValue)) {
3546 return false;
3548 aBackingObj.set(&slotValue.toObject());
3549 return true;
3552 bool GetMaplikeBackingObject(JSContext* aCx, JS::Handle<JSObject*> aObj,
3553 size_t aSlotIndex,
3554 JS::MutableHandle<JSObject*> aBackingObj,
3555 bool* aBackingObjCreated) {
3556 return GetMaplikeSetlikeBackingObject<JS::NewMapObject>(
3557 aCx, aObj, aSlotIndex, aBackingObj, aBackingObjCreated);
3560 bool GetSetlikeBackingObject(JSContext* aCx, JS::Handle<JSObject*> aObj,
3561 size_t aSlotIndex,
3562 JS::MutableHandle<JSObject*> aBackingObj,
3563 bool* aBackingObjCreated) {
3564 return GetMaplikeSetlikeBackingObject<JS::NewSetObject>(
3565 aCx, aObj, aSlotIndex, aBackingObj, aBackingObjCreated);
3568 bool ForEachHandler(JSContext* aCx, unsigned aArgc, JS::Value* aVp) {
3569 JS::CallArgs args = CallArgsFromVp(aArgc, aVp);
3570 // Unpack callback and object from slots
3571 JS::Rooted<JS::Value> callbackFn(
3572 aCx,
3573 js::GetFunctionNativeReserved(&args.callee(), FOREACH_CALLBACK_SLOT));
3574 JS::Rooted<JS::Value> maplikeOrSetlikeObj(
3575 aCx, js::GetFunctionNativeReserved(&args.callee(),
3576 FOREACH_MAPLIKEORSETLIKEOBJ_SLOT));
3577 MOZ_ASSERT(aArgc == 3);
3578 JS::RootedVector<JS::Value> newArgs(aCx);
3579 // Arguments are passed in as value, key, object. Keep value and key, replace
3580 // object with the maplike/setlike object.
3581 if (!newArgs.append(args.get(0))) {
3582 return false;
3584 if (!newArgs.append(args.get(1))) {
3585 return false;
3587 if (!newArgs.append(maplikeOrSetlikeObj)) {
3588 return false;
3590 JS::Rooted<JS::Value> rval(aCx, JS::UndefinedValue());
3591 // Now actually call the user specified callback
3592 return JS::Call(aCx, args.thisv(), callbackFn, newArgs, &rval);
3595 static inline prototypes::ID GetProtoIdForNewtarget(
3596 JS::Handle<JSObject*> aNewTarget) {
3597 const JSClass* newTargetClass = JS::GetClass(aNewTarget);
3598 if (IsDOMIfaceAndProtoClass(newTargetClass)) {
3599 const DOMIfaceAndProtoJSClass* newTargetIfaceClass =
3600 DOMIfaceAndProtoJSClass::FromJSClass(newTargetClass);
3601 if (newTargetIfaceClass->mType == eInterface) {
3602 return newTargetIfaceClass->mPrototypeID;
3604 } else if (JS_IsNativeFunction(aNewTarget, Constructor)) {
3605 return GetNativePropertyHooksFromConstructorFunction(aNewTarget)
3606 ->mPrototypeID;
3609 return prototypes::id::_ID_Count;
3612 bool GetDesiredProto(JSContext* aCx, const JS::CallArgs& aCallArgs,
3613 prototypes::id::ID aProtoId,
3614 CreateInterfaceObjectsMethod aCreator,
3615 JS::MutableHandle<JSObject*> aDesiredProto) {
3616 // This basically implements
3617 // https://heycam.github.io/webidl/#internally-create-a-new-object-implementing-the-interface
3618 // step 3.
3619 MOZ_ASSERT(aCallArgs.isConstructing(), "How did we end up here?");
3621 // The desired prototype depends on the actual constructor that was invoked,
3622 // which is passed to us as the newTarget in the callargs. We want to do
3623 // something akin to the ES6 specification's GetProtototypeFromConstructor (so
3624 // get .prototype on the newTarget, with a fallback to some sort of default).
3626 // First, a fast path for the case when the the constructor is in fact one of
3627 // our DOM constructors. This is safe because on those the "constructor"
3628 // property is non-configurable and non-writable, so we don't have to do the
3629 // slow JS_GetProperty call.
3630 JS::Rooted<JSObject*> newTarget(aCx, &aCallArgs.newTarget().toObject());
3631 MOZ_ASSERT(JS::IsCallable(newTarget));
3632 JS::Rooted<JSObject*> originalNewTarget(aCx, newTarget);
3633 // See whether we have a known DOM constructor here, such that we can take a
3634 // fast path.
3635 prototypes::ID protoID = GetProtoIdForNewtarget(newTarget);
3636 if (protoID == prototypes::id::_ID_Count) {
3637 // We might still have a cross-compartment wrapper for a known DOM
3638 // constructor. CheckedUnwrapStatic is fine here, because we're looking for
3639 // DOM constructors and those can't be cross-origin objects.
3640 newTarget = js::CheckedUnwrapStatic(newTarget);
3641 if (newTarget && newTarget != originalNewTarget) {
3642 protoID = GetProtoIdForNewtarget(newTarget);
3646 if (protoID != prototypes::id::_ID_Count) {
3647 ProtoAndIfaceCache& protoAndIfaceCache =
3648 *GetProtoAndIfaceCache(JS::GetNonCCWObjectGlobal(newTarget));
3649 aDesiredProto.set(protoAndIfaceCache.EntrySlotMustExist(protoID));
3650 if (newTarget != originalNewTarget) {
3651 return JS_WrapObject(aCx, aDesiredProto);
3653 return true;
3656 // Slow path. This basically duplicates the ES6 spec's
3657 // GetPrototypeFromConstructor except that instead of taking a string naming
3658 // the fallback prototype we determine the fallback based on the proto id we
3659 // were handed.
3661 // Note that it's very important to do this property get on originalNewTarget,
3662 // not our unwrapped newTarget, since we want to get Xray behavior here as
3663 // needed.
3664 // XXXbz for speed purposes, using a preinterned id here sure would be nice.
3665 // We can't use GetJSIDByIndex, because that only works on the main thread,
3666 // not workers.
3667 JS::Rooted<JS::Value> protoVal(aCx);
3668 if (!JS_GetProperty(aCx, originalNewTarget, "prototype", &protoVal)) {
3669 return false;
3672 if (protoVal.isObject()) {
3673 aDesiredProto.set(&protoVal.toObject());
3674 return true;
3677 // Fall back to getting the proto for our given proto id in the realm that
3678 // GetFunctionRealm(newTarget) returns.
3679 JS::Rooted<JS::Realm*> realm(aCx, JS::GetFunctionRealm(aCx, newTarget));
3680 if (!realm) {
3681 return false;
3685 // JS::GetRealmGlobalOrNull should not be returning null here, because we
3686 // have live objects in the Realm.
3687 JSAutoRealm ar(aCx, JS::GetRealmGlobalOrNull(realm));
3688 aDesiredProto.set(
3689 GetPerInterfaceObjectHandle(aCx, aProtoId, aCreator, true));
3690 if (!aDesiredProto) {
3691 return false;
3695 return MaybeWrapObject(aCx, aDesiredProto);
3698 namespace {
3700 class MOZ_RAII AutoConstructionDepth final {
3701 public:
3702 MOZ_IMPLICIT AutoConstructionDepth(CustomElementDefinition* aDefinition)
3703 : mDefinition(aDefinition) {
3704 MOZ_ASSERT(mDefinition->mConstructionStack.IsEmpty());
3706 mDefinition->mConstructionDepth++;
3707 // If the mConstructionDepth isn't matched with the length of mPrefixStack,
3708 // this means the constructor is called directly from JS, i.e.
3709 // 'new CustomElementConstructor()', we have to push a dummy prefix into
3710 // stack.
3711 if (mDefinition->mConstructionDepth > mDefinition->mPrefixStack.Length()) {
3712 mDidPush = true;
3713 mDefinition->mPrefixStack.AppendElement(nullptr);
3716 MOZ_ASSERT(mDefinition->mConstructionDepth ==
3717 mDefinition->mPrefixStack.Length());
3720 ~AutoConstructionDepth() {
3721 MOZ_ASSERT(mDefinition->mConstructionDepth > 0);
3722 MOZ_ASSERT(mDefinition->mConstructionDepth ==
3723 mDefinition->mPrefixStack.Length());
3725 if (mDidPush) {
3726 MOZ_ASSERT(mDefinition->mPrefixStack.LastElement() == nullptr);
3727 mDefinition->mPrefixStack.RemoveLastElement();
3729 mDefinition->mConstructionDepth--;
3732 private:
3733 CustomElementDefinition* mDefinition;
3734 bool mDidPush = false;
3737 } // anonymous namespace
3739 // https://html.spec.whatwg.org/multipage/dom.html#htmlconstructor
3740 namespace binding_detail {
3741 bool HTMLConstructor(JSContext* aCx, unsigned aArgc, JS::Value* aVp,
3742 constructors::id::ID aConstructorId,
3743 prototypes::id::ID aProtoId,
3744 CreateInterfaceObjectsMethod aCreator) {
3745 JS::CallArgs args = JS::CallArgsFromVp(aArgc, aVp);
3747 // Per spec, this is technically part of step 3, but doing the check
3748 // directly lets us provide a better error message. And then in
3749 // step 2 we can work with newTarget in a simpler way because we
3750 // know it's an object.
3751 if (!args.isConstructing()) {
3752 return ThrowConstructorWithoutNew(aCx,
3753 NamesOfInterfacesWithProtos(aProtoId));
3756 JS::Rooted<JSObject*> callee(aCx, &args.callee());
3757 // 'callee' is not a function here; it's either an Xray for our interface
3758 // object or the interface object itself. So caling XrayAwareCalleeGlobal on
3759 // it is not safe. But since in the Xray case it's a wrapper for our
3760 // interface object, we can just construct our GlobalObject from it and end
3761 // up with the right thing.
3762 GlobalObject global(aCx, callee);
3763 if (global.Failed()) {
3764 return false;
3767 // Now we start the [HTMLConstructor] algorithm steps from
3768 // https://html.spec.whatwg.org/multipage/dom.html#htmlconstructor
3770 ErrorResult rv;
3771 auto scopeExit =
3772 MakeScopeExit([&]() { Unused << rv.MaybeSetPendingException(aCx); });
3774 // Step 1.
3775 nsCOMPtr<nsPIDOMWindowInner> window =
3776 do_QueryInterface(global.GetAsSupports());
3777 if (!window) {
3778 // This means we ended up with an HTML Element interface object defined in
3779 // a non-Window scope. That's ... pretty unexpected.
3780 rv.Throw(NS_ERROR_UNEXPECTED);
3781 return false;
3783 RefPtr<mozilla::dom::CustomElementRegistry> registry(
3784 window->CustomElements());
3786 // Technically, per spec, a window always has a document. In Gecko, a
3787 // sufficiently torn-down window might not, so check for that case. We're
3788 // going to need a document to create an element.
3789 Document* doc = window->GetExtantDoc();
3790 if (!doc) {
3791 rv.Throw(NS_ERROR_UNEXPECTED);
3792 return false;
3795 // Step 2.
3797 // The newTarget might be a cross-compartment wrapper. Get the underlying
3798 // object so we can do the spec's object-identity checks. If we ever stop
3799 // unwrapping here, carefully audit uses of newTarget below!
3801 // Note that the ES spec enforces that newTarget is always a constructor (in
3802 // the sense of having a [[Construct]]), so it's not a cross-origin object and
3803 // we can use CheckedUnwrapStatic.
3804 JS::Rooted<JSObject*> newTarget(
3805 aCx, js::CheckedUnwrapStatic(&args.newTarget().toObject()));
3806 if (!newTarget) {
3807 rv.ThrowTypeError<MSG_ILLEGAL_CONSTRUCTOR>();
3808 return false;
3811 // Enter the compartment of our underlying newTarget object, so we end
3812 // up comparing to the constructor object for our interface from that global.
3813 // XXXbz This is not what the spec says to do, and it's not super-clear to me
3814 // at this point why we're doing it. Why not just compare |newTarget| and
3815 // |callee| if the intent is just to prevent registration of HTML interface
3816 // objects as constructors? Of course it's not clear that the spec check
3817 // makes sense to start with: https://github.com/whatwg/html/issues/3575
3819 JSAutoRealm ar(aCx, newTarget);
3820 JS::Handle<JSObject*> constructor =
3821 GetPerInterfaceObjectHandle(aCx, aConstructorId, aCreator, true);
3822 if (!constructor) {
3823 return false;
3825 if (newTarget == constructor) {
3826 rv.ThrowTypeError<MSG_ILLEGAL_CONSTRUCTOR>();
3827 return false;
3831 // Step 3.
3832 CustomElementDefinition* definition =
3833 registry->LookupCustomElementDefinition(aCx, newTarget);
3834 if (!definition) {
3835 rv.ThrowTypeError<MSG_ILLEGAL_CONSTRUCTOR>();
3836 return false;
3839 // Steps 4, 5, 6 do some sanity checks on our callee. We add to those a
3840 // determination of what sort of element we're planning to construct.
3841 // Technically, this should happen (implicitly) in step 8, but this
3842 // determination is side-effect-free, so it's OK.
3843 int32_t ns = definition->mNamespaceID;
3845 constructorGetterCallback cb = nullptr;
3846 if (ns == kNameSpaceID_XUL) {
3847 if (definition->mLocalName == nsGkAtoms::description ||
3848 definition->mLocalName == nsGkAtoms::label) {
3849 cb = XULTextElement_Binding::GetConstructorObject;
3850 } else if (definition->mLocalName == nsGkAtoms::menupopup ||
3851 definition->mLocalName == nsGkAtoms::popup ||
3852 definition->mLocalName == nsGkAtoms::panel ||
3853 definition->mLocalName == nsGkAtoms::tooltip) {
3854 cb = XULPopupElement_Binding::GetConstructorObject;
3855 } else if (definition->mLocalName == nsGkAtoms::iframe ||
3856 definition->mLocalName == nsGkAtoms::browser ||
3857 definition->mLocalName == nsGkAtoms::editor) {
3858 cb = XULFrameElement_Binding::GetConstructorObject;
3859 } else if (definition->mLocalName == nsGkAtoms::menu ||
3860 definition->mLocalName == nsGkAtoms::menulist) {
3861 cb = XULMenuElement_Binding::GetConstructorObject;
3862 } else if (definition->mLocalName == nsGkAtoms::tree) {
3863 cb = XULTreeElement_Binding::GetConstructorObject;
3864 } else {
3865 cb = XULElement_Binding::GetConstructorObject;
3869 int32_t tag = eHTMLTag_userdefined;
3870 if (!definition->IsCustomBuiltIn()) {
3871 // Step 4.
3872 // If the definition is for an autonomous custom element, the active
3873 // function should be HTMLElement or extend from XULElement.
3874 if (!cb) {
3875 cb = HTMLElement_Binding::GetConstructorObject;
3878 // We want to get the constructor from our global's realm, not the
3879 // caller realm.
3880 JSAutoRealm ar(aCx, global.Get());
3881 JS::Rooted<JSObject*> constructor(aCx, cb(aCx));
3883 // CheckedUnwrapStatic is OK here, since our callee is callable, hence not a
3884 // cross-origin object.
3885 if (constructor != js::CheckedUnwrapStatic(callee)) {
3886 rv.ThrowTypeError<MSG_ILLEGAL_CONSTRUCTOR>();
3887 return false;
3889 } else {
3890 if (ns == kNameSpaceID_XHTML) {
3891 // Step 5.
3892 // If the definition is for a customized built-in element, the localName
3893 // should be one of the ones defined in the specification for this
3894 // interface.
3895 tag = nsHTMLTags::CaseSensitiveAtomTagToId(definition->mLocalName);
3896 if (tag == eHTMLTag_userdefined) {
3897 rv.ThrowTypeError<MSG_ILLEGAL_CONSTRUCTOR>();
3898 return false;
3901 MOZ_ASSERT(tag <= NS_HTML_TAG_MAX, "tag is out of bounds");
3903 // If the definition is for a customized built-in element, the active
3904 // function should be the localname's element interface.
3905 cb = sConstructorGetterCallback[tag];
3908 if (!cb) {
3909 rv.ThrowTypeError<MSG_ILLEGAL_CONSTRUCTOR>();
3910 return false;
3913 // We want to get the constructor from our global's realm, not the
3914 // caller realm.
3915 JSAutoRealm ar(aCx, global.Get());
3916 JS::Rooted<JSObject*> constructor(aCx, cb(aCx));
3917 if (!constructor) {
3918 return false;
3921 // CheckedUnwrapStatic is OK here, since our callee is callable, hence not a
3922 // cross-origin object.
3923 if (constructor != js::CheckedUnwrapStatic(callee)) {
3924 rv.ThrowTypeError<MSG_ILLEGAL_CONSTRUCTOR>();
3925 return false;
3929 // Steps 7 and 8.
3930 JS::Rooted<JSObject*> desiredProto(aCx);
3931 if (!GetDesiredProto(aCx, args, aProtoId, aCreator, &desiredProto)) {
3932 return false;
3935 MOZ_ASSERT(desiredProto, "How could we not have a prototype by now?");
3937 // We need to do some work to actually return an Element, so we do step 8 on
3938 // one branch and steps 9-12 on another branch, then common up the "return
3939 // element" work.
3940 RefPtr<Element> element;
3941 nsTArray<RefPtr<Element>>& constructionStack = definition->mConstructionStack;
3942 if (constructionStack.IsEmpty()) {
3943 // Step 8.
3944 // Now we go to construct an element. We want to do this in global's
3945 // realm, not caller realm (the normal constructor behavior),
3946 // just in case those elements create JS things.
3947 JSAutoRealm ar(aCx, global.Get());
3948 AutoConstructionDepth acd(definition);
3950 RefPtr<NodeInfo> nodeInfo = doc->NodeInfoManager()->GetNodeInfo(
3951 definition->mLocalName, definition->mPrefixStack.LastElement(), ns,
3952 nsINode::ELEMENT_NODE);
3953 MOZ_ASSERT(nodeInfo);
3955 if (ns == kNameSpaceID_XUL) {
3956 element = nsXULElement::Construct(nodeInfo.forget());
3958 } else {
3959 if (tag == eHTMLTag_userdefined) {
3960 // Autonomous custom element.
3961 element = NS_NewHTMLElement(nodeInfo.forget());
3962 } else {
3963 // Customized built-in element.
3964 element = CreateHTMLElement(tag, nodeInfo.forget(), NOT_FROM_PARSER);
3968 element->SetCustomElementData(MakeUnique<CustomElementData>(
3969 definition->mType, CustomElementData::State::eCustom));
3971 element->SetCustomElementDefinition(definition);
3972 } else {
3973 // Step 9.
3974 element = constructionStack.LastElement();
3976 // Step 10.
3977 if (element == ALREADY_CONSTRUCTED_MARKER) {
3978 rv.ThrowTypeError(
3979 "Cannot instantiate a custom element inside its own constructor "
3980 "during upgrades");
3981 return false;
3984 // Step 11.
3985 // Do prototype swizzling for upgrading a custom element here, for cases
3986 // when we have a reflector already. If we don't have one yet, we will
3987 // create it with the right proto (by calling GetOrCreateDOMReflector with
3988 // that proto), and will preserve it by means of the proto != canonicalProto
3989 // check).
3990 JS::Rooted<JSObject*> reflector(aCx, element->GetWrapper());
3991 if (reflector) {
3992 // reflector might be in different realm.
3993 JSAutoRealm ar(aCx, reflector);
3994 JS::Rooted<JSObject*> givenProto(aCx, desiredProto);
3995 if (!JS_WrapObject(aCx, &givenProto) ||
3996 !JS_SetPrototype(aCx, reflector, givenProto)) {
3997 return false;
3999 PreserveWrapper(element.get());
4002 // Step 12.
4003 constructionStack.LastElement() = ALREADY_CONSTRUCTED_MARKER;
4006 // Tail end of step 8 and step 13: returning the element. We want to do this
4007 // part in the global's realm, though in practice it won't matter much
4008 // because Element always knows which realm it should be created in.
4009 JSAutoRealm ar(aCx, global.Get());
4010 if (!js::IsObjectInContextCompartment(desiredProto, aCx) &&
4011 !JS_WrapObject(aCx, &desiredProto)) {
4012 return false;
4015 return GetOrCreateDOMReflector(aCx, element, args.rval(), desiredProto);
4017 } // namespace binding_detail
4019 #ifdef DEBUG
4020 namespace binding_detail {
4021 void AssertReflectorHasGivenProto(JSContext* aCx, JSObject* aReflector,
4022 JS::Handle<JSObject*> aGivenProto) {
4023 if (!aGivenProto) {
4024 // Nothing to assert here
4025 return;
4028 JS::Rooted<JSObject*> reflector(aCx, aReflector);
4029 JSAutoRealm ar(aCx, reflector);
4030 JS::Rooted<JSObject*> reflectorProto(aCx);
4031 bool ok = JS_GetPrototype(aCx, reflector, &reflectorProto);
4032 MOZ_ASSERT(ok);
4033 // aGivenProto may not be in the right realm here, so we
4034 // have to wrap it to compare.
4035 JS::Rooted<JSObject*> givenProto(aCx, aGivenProto);
4036 ok = JS_WrapObject(aCx, &givenProto);
4037 MOZ_ASSERT(ok);
4038 MOZ_ASSERT(givenProto == reflectorProto,
4039 "How are we supposed to change the proto now?");
4041 } // namespace binding_detail
4042 #endif // DEBUG
4044 void SetUseCounter(JSObject* aObject, UseCounter aUseCounter) {
4045 nsGlobalWindowInner* win =
4046 xpc::WindowGlobalOrNull(js::UncheckedUnwrap(aObject));
4047 if (win && win->GetDocument()) {
4048 win->GetDocument()->SetUseCounter(aUseCounter);
4052 void SetUseCounter(UseCounterWorker aUseCounter) {
4053 // If this is called from Worklet thread, workerPrivate will be null.
4054 WorkerPrivate* workerPrivate = GetCurrentThreadWorkerPrivate();
4055 if (workerPrivate) {
4056 workerPrivate->SetUseCounter(aUseCounter);
4060 namespace {
4062 #define DEPRECATED_OPERATION(_op) #_op,
4063 static const char* kDeprecatedOperations[] = {
4064 #include "nsDeprecatedOperationList.h"
4065 nullptr};
4066 #undef DEPRECATED_OPERATION
4068 class GetLocalizedStringRunnable final : public WorkerMainThreadRunnable {
4069 public:
4070 GetLocalizedStringRunnable(WorkerPrivate* aWorkerPrivate,
4071 const nsAutoCString& aKey,
4072 nsAutoString& aLocalizedString)
4073 : WorkerMainThreadRunnable(aWorkerPrivate,
4074 "GetLocalizedStringRunnable"_ns),
4075 mKey(aKey),
4076 mLocalizedString(aLocalizedString) {
4077 MOZ_ASSERT(aWorkerPrivate);
4078 aWorkerPrivate->AssertIsOnWorkerThread();
4081 bool MainThreadRun() override {
4082 AssertIsOnMainThread();
4084 nsresult rv = nsContentUtils::GetLocalizedString(
4085 nsContentUtils::eDOM_PROPERTIES, mKey.get(), mLocalizedString);
4086 Unused << NS_WARN_IF(NS_FAILED(rv));
4087 return true;
4090 private:
4091 const nsAutoCString& mKey;
4092 nsAutoString& mLocalizedString;
4095 void ReportDeprecation(nsIGlobalObject* aGlobal, nsIURI* aURI,
4096 DeprecatedOperations aOperation,
4097 const nsAString& aFileName,
4098 const Nullable<uint32_t>& aLineNumber,
4099 const Nullable<uint32_t>& aColumnNumber) {
4100 MOZ_ASSERT(aURI);
4102 // Anonymize the URL.
4103 // Strip the URL of any possible username/password and make it ready to be
4104 // presented in the UI.
4105 nsCOMPtr<nsIURI> exposableURI = net::nsIOService::CreateExposableURI(aURI);
4106 nsAutoCString spec;
4107 nsresult rv = exposableURI->GetSpec(spec);
4108 if (NS_WARN_IF(NS_FAILED(rv))) {
4109 return;
4112 nsAutoString type;
4113 type.AssignASCII(kDeprecatedOperations[static_cast<size_t>(aOperation)]);
4115 nsAutoCString key;
4116 key.AssignASCII(kDeprecatedOperations[static_cast<size_t>(aOperation)]);
4117 key.AppendASCII("Warning");
4119 nsAutoString msg;
4120 if (NS_IsMainThread()) {
4121 rv = nsContentUtils::GetLocalizedString(nsContentUtils::eDOM_PROPERTIES,
4122 key.get(), msg);
4123 if (NS_WARN_IF(NS_FAILED(rv))) {
4124 return;
4126 } else {
4127 // nsIStringBundle is thread-safe but its creation is not, and in particular
4128 // nsContentUtils doesn't create and store nsIStringBundle objects in a
4129 // thread-safe way. Better to call GetLocalizedString() on the main thread.
4130 WorkerPrivate* workerPrivate = GetCurrentThreadWorkerPrivate();
4131 if (!workerPrivate) {
4132 return;
4135 RefPtr<GetLocalizedStringRunnable> runnable =
4136 new GetLocalizedStringRunnable(workerPrivate, key, msg);
4138 IgnoredErrorResult ignoredRv;
4139 runnable->Dispatch(Canceling, ignoredRv);
4140 if (NS_WARN_IF(ignoredRv.Failed())) {
4141 return;
4144 if (msg.IsEmpty()) {
4145 return;
4149 RefPtr<DeprecationReportBody> body =
4150 new DeprecationReportBody(aGlobal, type, nullptr /* date */, msg,
4151 aFileName, aLineNumber, aColumnNumber);
4153 ReportingUtils::Report(aGlobal, nsGkAtoms::deprecation, u"default"_ns,
4154 NS_ConvertUTF8toUTF16(spec), body);
4157 // This runnable is used to write a deprecation message from a worker to the
4158 // console running on the main-thread.
4159 class DeprecationWarningRunnable final
4160 : public WorkerProxyToMainThreadRunnable {
4161 const DeprecatedOperations mOperation;
4163 public:
4164 explicit DeprecationWarningRunnable(DeprecatedOperations aOperation)
4165 : mOperation(aOperation) {}
4167 private:
4168 void RunOnMainThread(WorkerPrivate* aWorkerPrivate) override {
4169 MOZ_ASSERT(NS_IsMainThread());
4170 MOZ_ASSERT(aWorkerPrivate);
4172 // Walk up to our containing page
4173 WorkerPrivate* wp = aWorkerPrivate;
4174 while (wp->GetParent()) {
4175 wp = wp->GetParent();
4178 nsPIDOMWindowInner* window = wp->GetWindow();
4179 if (window && window->GetExtantDoc()) {
4180 window->GetExtantDoc()->WarnOnceAbout(mOperation);
4184 void RunBackOnWorkerThreadForCleanup(WorkerPrivate* aWorkerPrivate) override {
4188 void MaybeShowDeprecationWarning(const GlobalObject& aGlobal,
4189 DeprecatedOperations aOperation) {
4190 if (NS_IsMainThread()) {
4191 nsCOMPtr<nsPIDOMWindowInner> window =
4192 do_QueryInterface(aGlobal.GetAsSupports());
4193 if (window && window->GetExtantDoc()) {
4194 window->GetExtantDoc()->WarnOnceAbout(aOperation);
4196 return;
4199 WorkerPrivate* workerPrivate = GetWorkerPrivateFromContext(aGlobal.Context());
4200 if (!workerPrivate) {
4201 return;
4204 RefPtr<DeprecationWarningRunnable> runnable =
4205 new DeprecationWarningRunnable(aOperation);
4206 runnable->Dispatch(workerPrivate);
4209 void MaybeReportDeprecation(const GlobalObject& aGlobal,
4210 DeprecatedOperations aOperation) {
4211 nsCOMPtr<nsIURI> uri;
4213 if (NS_IsMainThread()) {
4214 nsCOMPtr<nsPIDOMWindowInner> window =
4215 do_QueryInterface(aGlobal.GetAsSupports());
4216 if (!window || !window->GetExtantDoc()) {
4217 return;
4220 uri = window->GetExtantDoc()->GetDocumentURI();
4221 } else {
4222 WorkerPrivate* workerPrivate =
4223 GetWorkerPrivateFromContext(aGlobal.Context());
4224 if (!workerPrivate) {
4225 return;
4228 uri = workerPrivate->GetResolvedScriptURI();
4231 if (NS_WARN_IF(!uri)) {
4232 return;
4235 nsAutoString fileName;
4236 Nullable<uint32_t> lineNumber;
4237 Nullable<uint32_t> columnNumber;
4238 uint32_t line = 0;
4239 uint32_t column = 0;
4240 if (nsJSUtils::GetCallingLocation(aGlobal.Context(), fileName, &line,
4241 &column)) {
4242 lineNumber.SetValue(line);
4243 columnNumber.SetValue(column);
4246 nsCOMPtr<nsIGlobalObject> global = do_QueryInterface(aGlobal.GetAsSupports());
4247 MOZ_ASSERT(global);
4249 ReportDeprecation(global, uri, aOperation, fileName, lineNumber,
4250 columnNumber);
4253 } // anonymous namespace
4255 void DeprecationWarning(JSContext* aCx, JSObject* aObject,
4256 DeprecatedOperations aOperation) {
4257 GlobalObject global(aCx, aObject);
4258 if (global.Failed()) {
4259 NS_ERROR("Could not create global for DeprecationWarning");
4260 return;
4263 DeprecationWarning(global, aOperation);
4266 void DeprecationWarning(const GlobalObject& aGlobal,
4267 DeprecatedOperations aOperation) {
4268 MaybeShowDeprecationWarning(aGlobal, aOperation);
4269 MaybeReportDeprecation(aGlobal, aOperation);
4272 namespace binding_detail {
4273 JSObject* UnprivilegedJunkScopeOrWorkerGlobal(const fallible_t&) {
4274 if (NS_IsMainThread()) {
4275 return xpc::UnprivilegedJunkScope(fallible);
4278 return GetCurrentThreadWorkerGlobal();
4280 } // namespace binding_detail
4282 JS::Handle<JSObject*> GetPerInterfaceObjectHandle(
4283 JSContext* aCx, size_t aSlotId, CreateInterfaceObjectsMethod aCreator,
4284 bool aDefineOnGlobal) {
4285 /* Make sure our global is sane. Hopefully we can remove this sometime */
4286 JSObject* global = JS::CurrentGlobalOrNull(aCx);
4287 if (!(JS::GetClass(global)->flags & JSCLASS_DOM_GLOBAL)) {
4288 return nullptr;
4291 /* Check to see whether the interface objects are already installed */
4292 ProtoAndIfaceCache& protoAndIfaceCache = *GetProtoAndIfaceCache(global);
4293 if (!protoAndIfaceCache.HasEntryInSlot(aSlotId)) {
4294 JS::Rooted<JSObject*> rootedGlobal(aCx, global);
4295 aCreator(aCx, rootedGlobal, protoAndIfaceCache, aDefineOnGlobal);
4299 * The object might _still_ be null, but that's OK.
4301 * Calling fromMarkedLocation() is safe because protoAndIfaceCache is
4302 * traced by TraceProtoAndIfaceCache() and its contents are never
4303 * changed after they have been set.
4305 * Calling address() avoids the read barrier that does gray unmarking, but
4306 * it's not possible for the object to be gray here.
4309 const JS::Heap<JSObject*>& entrySlot =
4310 protoAndIfaceCache.EntrySlotMustExist(aSlotId);
4311 JS::AssertObjectIsNotGray(entrySlot);
4312 return JS::Handle<JSObject*>::fromMarkedLocation(entrySlot.address());
4315 namespace binding_detail {
4316 bool IsGetterEnabled(JSContext* aCx, JS::Handle<JSObject*> aObj,
4317 JSJitGetterOp aGetter,
4318 const Prefable<const JSPropertySpec>* aAttributes) {
4319 MOZ_ASSERT(aAttributes);
4320 MOZ_ASSERT(aAttributes->specs);
4321 do {
4322 if (aAttributes->isEnabled(aCx, aObj)) {
4323 const JSPropertySpec* specs = aAttributes->specs;
4324 do {
4325 if (!specs->isAccessor() || specs->isSelfHosted()) {
4326 // It won't have a JSJitGetterOp.
4327 continue;
4329 const JSJitInfo* info = specs->u.accessors.getter.native.info;
4330 if (!info) {
4331 continue;
4333 MOZ_ASSERT(info->type() == JSJitInfo::OpType::Getter);
4334 if (info->getter == aGetter) {
4335 return true;
4337 } while ((++specs)->name);
4339 } while ((++aAttributes)->specs);
4341 // Didn't find it.
4342 return false;
4345 already_AddRefed<Promise> CreateRejectedPromiseFromThrownException(
4346 JSContext* aCx, ErrorResult& aError) {
4347 JS::Rooted<JS::Value> exn(aCx);
4348 if (!JS_GetPendingException(aCx, &exn)) {
4349 // If there is no pending exception here but we're ending up in this code,
4350 // that means the callee threw an uncatchable exception. Just propagate that
4351 // out as-is.
4352 aError.ThrowUncatchableException();
4353 return nullptr;
4356 JS_ClearPendingException(aCx);
4358 JS::Rooted<JSObject*> globalObj(aCx, GetEntryGlobal()->GetGlobalJSObject());
4359 JSAutoRealm ar(aCx, globalObj);
4360 if (!JS_WrapValue(aCx, &exn)) {
4361 aError.StealExceptionFromJSContext(aCx);
4362 return nullptr;
4365 GlobalObject promiseGlobal(aCx, globalObj);
4366 if (promiseGlobal.Failed()) {
4367 aError.StealExceptionFromJSContext(aCx);
4368 return nullptr;
4371 nsCOMPtr<nsIGlobalObject> global =
4372 do_QueryInterface(promiseGlobal.GetAsSupports());
4373 if (!global) {
4374 aError.Throw(NS_ERROR_UNEXPECTED);
4375 return nullptr;
4378 return Promise::Reject(global, aCx, exn, aError);
4381 } // namespace binding_detail
4383 } // namespace dom
4384 } // namespace mozilla