forked from mozilla/gecko-dev
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathBindingUtils.cpp
4383 lines (3809 loc) · 151 KB
/
BindingUtils.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
/* vim: set ts=8 sts=2 et sw=2 tw=80: */
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this file,
* You can obtain one at http://mozilla.org/MPL/2.0/. */
#include "BindingUtils.h"
#include <algorithm>
#include <stdarg.h>
#include "mozilla/Assertions.h"
#include "mozilla/DebugOnly.h"
#include "mozilla/Encoding.h"
#include "mozilla/FloatingPoint.h"
#include "mozilla/Preferences.h"
#include "mozilla/ScopeExit.h"
#include "mozilla/StaticPrefs_dom.h"
#include "mozilla/UniquePtr.h"
#include "mozilla/Unused.h"
#include "mozilla/UseCounter.h"
#include "AccessCheck.h"
#include "js/CallAndConstruct.h" // JS::Call, JS::IsCallable
#include "js/experimental/JitInfo.h" // JSJit{Getter,Setter,Method}CallArgs, JSJit{Getter,Setter}Op, JSJitInfo
#include "js/friend/StackLimits.h" // js::AutoCheckRecursionLimit
#include "js/Id.h"
#include "js/JSON.h"
#include "js/MapAndSet.h"
#include "js/Object.h" // JS::GetClass, JS::GetCompartment, JS::GetReservedSlot, JS::SetReservedSlot
#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
#include "js/StableStringChars.h"
#include "js/String.h" // JS::GetStringLength, JS::MaxStringLength, JS::StringHasLatin1Chars
#include "js/Symbol.h"
#include "jsfriendapi.h"
#include "nsContentCreatorFunctions.h"
#include "nsContentUtils.h"
#include "nsGlobalWindow.h"
#include "nsHTMLTags.h"
#include "nsIDOMGlobalPropertyInitializer.h"
#include "nsINode.h"
#include "nsIOService.h"
#include "nsIPrincipal.h"
#include "nsIXPConnect.h"
#include "nsUTF8Utils.h"
#include "WorkerPrivate.h"
#include "WorkerRunnable.h"
#include "WrapperFactory.h"
#include "xpcprivate.h"
#include "XrayWrapper.h"
#include "nsPrintfCString.h"
#include "mozilla/Sprintf.h"
#include "nsReadableUtils.h"
#include "nsWrapperCacheInlines.h"
#include "mozilla/dom/ScriptSettings.h"
#include "mozilla/dom/CustomElementRegistry.h"
#include "mozilla/dom/DeprecationReportBody.h"
#include "mozilla/dom/DOMException.h"
#include "mozilla/dom/ElementBinding.h"
#include "mozilla/dom/Exceptions.h"
#include "mozilla/dom/HTMLObjectElement.h"
#include "mozilla/dom/HTMLObjectElementBinding.h"
#include "mozilla/dom/HTMLEmbedElement.h"
#include "mozilla/dom/HTMLElementBinding.h"
#include "mozilla/dom/HTMLEmbedElementBinding.h"
#include "mozilla/dom/MaybeCrossOriginObject.h"
#include "mozilla/dom/ObservableArrayProxyHandler.h"
#include "mozilla/dom/ReportingUtils.h"
#include "mozilla/dom/XULElementBinding.h"
#include "mozilla/dom/XULFrameElementBinding.h"
#include "mozilla/dom/XULMenuElementBinding.h"
#include "mozilla/dom/XULPopupElementBinding.h"
#include "mozilla/dom/XULResizerElementBinding.h"
#include "mozilla/dom/XULTextElementBinding.h"
#include "mozilla/dom/XULTreeElementBinding.h"
#include "mozilla/dom/Promise.h"
#include "mozilla/dom/WebIDLGlobalNameHash.h"
#include "mozilla/dom/WorkerPrivate.h"
#include "mozilla/dom/WorkerScope.h"
#include "mozilla/dom/XrayExpandoClass.h"
#include "mozilla/dom/WindowProxyHolder.h"
#include "ipc/ErrorIPCUtils.h"
#include "ipc/IPCMessageUtilsSpecializations.h"
#include "mozilla/dom/DocGroup.h"
#include "nsXULElement.h"
namespace mozilla {
namespace dom {
// Forward declare GetConstructorObject methods.
#define HTML_TAG(_tag, _classname, _interfacename) \
namespace HTML##_interfacename##Element_Binding { \
JSObject* GetConstructorObject(JSContext*); \
}
#define HTML_OTHER(_tag)
#include "nsHTMLTagList.h"
#undef HTML_TAG
#undef HTML_OTHER
using constructorGetterCallback = JSObject* (*)(JSContext*);
// Mapping of html tag and GetConstructorObject methods.
#define HTML_TAG(_tag, _classname, _interfacename) \
HTML##_interfacename##Element_Binding::GetConstructorObject,
#define HTML_OTHER(_tag) nullptr,
// We use eHTMLTag_foo (where foo is the tag) which is defined in nsHTMLTags.h
// to index into this array.
static const constructorGetterCallback sConstructorGetterCallback[] = {
HTMLUnknownElement_Binding::GetConstructorObject,
#include "nsHTMLTagList.h"
#undef HTML_TAG
#undef HTML_OTHER
};
static const JSErrorFormatString ErrorFormatString[] = {
#define MSG_DEF(_name, _argc, _has_context, _exn, _str) \
{#_name, _str, _argc, _exn},
#include "mozilla/dom/Errors.msg"
#undef MSG_DEF
};
#define MSG_DEF(_name, _argc, _has_context, _exn, _str) \
static_assert( \
(_argc) < JS::MaxNumErrorArguments, #_name \
" must only have as many error arguments as the JS engine can support");
#include "mozilla/dom/Errors.msg"
#undef MSG_DEF
static const JSErrorFormatString* GetErrorMessage(void* aUserRef,
const unsigned aErrorNumber) {
MOZ_ASSERT(aErrorNumber < ArrayLength(ErrorFormatString));
return &ErrorFormatString[aErrorNumber];
}
uint16_t GetErrorArgCount(const ErrNum aErrorNumber) {
return GetErrorMessage(nullptr, aErrorNumber)->argCount;
}
// aErrorNumber needs to be unsigned, not an ErrNum, because the latter makes
// va_start have undefined behavior, and we do not want undefined behavior.
void binding_detail::ThrowErrorMessage(JSContext* aCx,
const unsigned aErrorNumber, ...) {
va_list ap;
va_start(ap, aErrorNumber);
if (!ErrorFormatHasContext[aErrorNumber]) {
JS_ReportErrorNumberUTF8VA(aCx, GetErrorMessage, nullptr, aErrorNumber, ap);
va_end(ap);
return;
}
// Our first arg is the context arg. We want to replace nullptr with empty
// string, leave empty string alone, and for anything else append ": " to the
// end. See also the behavior of
// TErrorResult::SetPendingExceptionWithMessage, which this is mirroring for
// exceptions that are thrown directly, not via an ErrorResult.
const char* args[JS::MaxNumErrorArguments + 1];
size_t argCount = GetErrorArgCount(static_cast<ErrNum>(aErrorNumber));
MOZ_ASSERT(argCount > 0, "We have a context arg!");
nsAutoCString firstArg;
for (size_t i = 0; i < argCount; ++i) {
args[i] = va_arg(ap, const char*);
if (i == 0) {
if (args[0] && *args[0]) {
firstArg.Append(args[0]);
firstArg.AppendLiteral(": ");
}
args[0] = firstArg.get();
}
}
JS_ReportErrorNumberUTF8Array(aCx, GetErrorMessage, nullptr, aErrorNumber,
args);
va_end(ap);
}
static bool ThrowInvalidThis(JSContext* aCx, const JS::CallArgs& aArgs,
bool aSecurityError, const char* aInterfaceName) {
NS_ConvertASCIItoUTF16 ifaceName(aInterfaceName);
// This should only be called for DOM methods/getters/setters, which
// are JSNative-backed functions, so we can assume that
// JS_ValueToFunction and JS_GetFunctionDisplayId will both return
// non-null and that JS_GetStringCharsZ returns non-null.
JS::Rooted<JSFunction*> func(aCx, JS_ValueToFunction(aCx, aArgs.calleev()));
MOZ_ASSERT(func);
JS::Rooted<JSString*> funcName(aCx, JS_GetFunctionDisplayId(func));
MOZ_ASSERT(funcName);
nsAutoJSString funcNameStr;
if (!funcNameStr.init(aCx, funcName)) {
return false;
}
if (aSecurityError) {
return Throw(aCx, NS_ERROR_DOM_SECURITY_ERR,
nsPrintfCString("Permission to call '%s' denied.",
NS_ConvertUTF16toUTF8(funcNameStr).get()));
}
const ErrNum errorNumber = MSG_METHOD_THIS_DOES_NOT_IMPLEMENT_INTERFACE;
MOZ_RELEASE_ASSERT(GetErrorArgCount(errorNumber) == 2);
JS_ReportErrorNumberUC(aCx, GetErrorMessage, nullptr,
static_cast<unsigned>(errorNumber),
static_cast<const char16_t*>(funcNameStr.get()),
static_cast<const char16_t*>(ifaceName.get()));
return false;
}
bool ThrowInvalidThis(JSContext* aCx, const JS::CallArgs& aArgs,
bool aSecurityError, prototypes::ID aProtoId) {
return ThrowInvalidThis(aCx, aArgs, aSecurityError,
NamesOfInterfacesWithProtos(aProtoId));
}
bool ThrowNoSetterArg(JSContext* aCx, const JS::CallArgs& aArgs,
prototypes::ID aProtoId) {
nsPrintfCString errorMessage("%s attribute setter",
NamesOfInterfacesWithProtos(aProtoId));
return aArgs.requireAtLeast(aCx, errorMessage.get(), 1);
}
} // namespace dom
namespace binding_danger {
template <typename CleanupPolicy>
struct TErrorResult<CleanupPolicy>::Message {
Message() : mErrorNumber(dom::Err_Limit) {
MOZ_COUNT_CTOR(TErrorResult::Message);
}
~Message() { MOZ_COUNT_DTOR(TErrorResult::Message); }
// UTF-8 strings (probably ASCII in most cases) in mArgs.
nsTArray<nsCString> mArgs;
dom::ErrNum mErrorNumber;
bool HasCorrectNumberOfArguments() {
return GetErrorArgCount(mErrorNumber) == mArgs.Length();
}
bool operator==(const TErrorResult<CleanupPolicy>::Message& aRight) const {
return mErrorNumber == aRight.mErrorNumber && mArgs == aRight.mArgs;
}
};
template <typename CleanupPolicy>
nsTArray<nsCString>& TErrorResult<CleanupPolicy>::CreateErrorMessageHelper(
const dom::ErrNum errorNumber, nsresult errorType) {
AssertInOwningThread();
mResult = errorType;
Message* message = InitMessage(new Message());
message->mErrorNumber = errorNumber;
return message->mArgs;
}
template <typename CleanupPolicy>
void TErrorResult<CleanupPolicy>::SerializeMessage(
IPC::MessageWriter* aWriter) const {
using namespace IPC;
AssertInOwningThread();
MOZ_ASSERT(mUnionState == HasMessage);
MOZ_ASSERT(mExtra.mMessage);
WriteParam(aWriter, mExtra.mMessage->mArgs);
WriteParam(aWriter, mExtra.mMessage->mErrorNumber);
}
template <typename CleanupPolicy>
bool TErrorResult<CleanupPolicy>::DeserializeMessage(
IPC::MessageReader* aReader) {
using namespace IPC;
AssertInOwningThread();
auto readMessage = MakeUnique<Message>();
if (!ReadParam(aReader, &readMessage->mArgs) ||
!ReadParam(aReader, &readMessage->mErrorNumber)) {
return false;
}
if (!readMessage->HasCorrectNumberOfArguments()) {
return false;
}
MOZ_ASSERT(mUnionState == HasNothing);
InitMessage(readMessage.release());
#ifdef DEBUG
mUnionState = HasMessage;
#endif // DEBUG
return true;
}
template <typename CleanupPolicy>
void TErrorResult<CleanupPolicy>::SetPendingExceptionWithMessage(
JSContext* aCx, const char* context) {
AssertInOwningThread();
MOZ_ASSERT(mUnionState == HasMessage);
MOZ_ASSERT(mExtra.mMessage,
"SetPendingExceptionWithMessage() can be called only once");
Message* message = mExtra.mMessage;
MOZ_RELEASE_ASSERT(message->HasCorrectNumberOfArguments());
if (dom::ErrorFormatHasContext[message->mErrorNumber]) {
MOZ_ASSERT(!message->mArgs.IsEmpty(), "How could we have no args here?");
MOZ_ASSERT(message->mArgs[0].IsEmpty(), "Context should not be set yet!");
if (context) {
// Prepend our context and ": "; see API documentation.
message->mArgs[0].AssignASCII(context);
message->mArgs[0].AppendLiteral(": ");
}
}
const uint32_t argCount = message->mArgs.Length();
const char* args[JS::MaxNumErrorArguments + 1];
for (uint32_t i = 0; i < argCount; ++i) {
args[i] = message->mArgs.ElementAt(i).get();
}
args[argCount] = nullptr;
JS_ReportErrorNumberUTF8Array(aCx, dom::GetErrorMessage, nullptr,
static_cast<unsigned>(message->mErrorNumber),
argCount > 0 ? args : nullptr);
ClearMessage();
mResult = NS_OK;
}
template <typename CleanupPolicy>
void TErrorResult<CleanupPolicy>::ClearMessage() {
AssertInOwningThread();
MOZ_ASSERT(IsErrorWithMessage());
MOZ_ASSERT(mUnionState == HasMessage);
delete mExtra.mMessage;
mExtra.mMessage = nullptr;
#ifdef DEBUG
mUnionState = HasNothing;
#endif // DEBUG
}
template <typename CleanupPolicy>
void TErrorResult<CleanupPolicy>::ThrowJSException(JSContext* cx,
JS::Handle<JS::Value> exn) {
AssertInOwningThread();
MOZ_ASSERT(mMightHaveUnreportedJSException,
"Why didn't you tell us you planned to throw a JS exception?");
ClearUnionData();
// Make sure mExtra.mJSException is initialized _before_ we try to root it.
// But don't set it to exn yet, because we don't want to do that until after
// we root.
JS::Value& exc = InitJSException();
if (!js::AddRawValueRoot(cx, &exc, "TErrorResult::mExtra::mJSException")) {
// Don't use NS_ERROR_INTERNAL_ERRORRESULT_JS_EXCEPTION, because that
// indicates we have in fact rooted mExtra.mJSException.
mResult = NS_ERROR_OUT_OF_MEMORY;
} else {
exc = exn;
mResult = NS_ERROR_INTERNAL_ERRORRESULT_JS_EXCEPTION;
#ifdef DEBUG
mUnionState = HasJSException;
#endif // DEBUG
}
}
template <typename CleanupPolicy>
void TErrorResult<CleanupPolicy>::SetPendingJSException(JSContext* cx) {
AssertInOwningThread();
MOZ_ASSERT(!mMightHaveUnreportedJSException,
"Why didn't you tell us you planned to handle JS exceptions?");
MOZ_ASSERT(mUnionState == HasJSException);
JS::Rooted<JS::Value> exception(cx, mExtra.mJSException);
if (JS_WrapValue(cx, &exception)) {
JS_SetPendingException(cx, exception);
}
mExtra.mJSException = exception;
// If JS_WrapValue failed, not much we can do about it... No matter
// what, go ahead and unroot mExtra.mJSException.
js::RemoveRawValueRoot(cx, &mExtra.mJSException);
mResult = NS_OK;
#ifdef DEBUG
mUnionState = HasNothing;
#endif // DEBUG
}
template <typename CleanupPolicy>
struct TErrorResult<CleanupPolicy>::DOMExceptionInfo {
DOMExceptionInfo(nsresult rv, const nsACString& message)
: mMessage(message), mRv(rv) {}
nsCString mMessage;
nsresult mRv;
bool operator==(
const TErrorResult<CleanupPolicy>::DOMExceptionInfo& aRight) const {
return mRv == aRight.mRv && mMessage == aRight.mMessage;
}
};
template <typename CleanupPolicy>
void TErrorResult<CleanupPolicy>::SerializeDOMExceptionInfo(
IPC::MessageWriter* aWriter) const {
using namespace IPC;
AssertInOwningThread();
MOZ_ASSERT(mUnionState == HasDOMExceptionInfo);
MOZ_ASSERT(mExtra.mDOMExceptionInfo);
WriteParam(aWriter, mExtra.mDOMExceptionInfo->mMessage);
WriteParam(aWriter, mExtra.mDOMExceptionInfo->mRv);
}
template <typename CleanupPolicy>
bool TErrorResult<CleanupPolicy>::DeserializeDOMExceptionInfo(
IPC::MessageReader* aReader) {
using namespace IPC;
AssertInOwningThread();
nsCString message;
nsresult rv;
if (!ReadParam(aReader, &message) || !ReadParam(aReader, &rv)) {
return false;
}
MOZ_ASSERT(mUnionState == HasNothing);
MOZ_ASSERT(IsDOMException());
InitDOMExceptionInfo(new DOMExceptionInfo(rv, message));
#ifdef DEBUG
mUnionState = HasDOMExceptionInfo;
#endif // DEBUG
return true;
}
template <typename CleanupPolicy>
void TErrorResult<CleanupPolicy>::ThrowDOMException(nsresult rv,
const nsACString& message) {
AssertInOwningThread();
ClearUnionData();
mResult = NS_ERROR_INTERNAL_ERRORRESULT_DOMEXCEPTION;
InitDOMExceptionInfo(new DOMExceptionInfo(rv, message));
#ifdef DEBUG
mUnionState = HasDOMExceptionInfo;
#endif
}
template <typename CleanupPolicy>
void TErrorResult<CleanupPolicy>::SetPendingDOMException(JSContext* cx,
const char* context) {
AssertInOwningThread();
MOZ_ASSERT(mUnionState == HasDOMExceptionInfo);
MOZ_ASSERT(mExtra.mDOMExceptionInfo,
"SetPendingDOMException() can be called only once");
if (context && !mExtra.mDOMExceptionInfo->mMessage.IsEmpty()) {
// Prepend our context and ": "; see API documentation.
nsAutoCString prefix(context);
prefix.AppendLiteral(": ");
mExtra.mDOMExceptionInfo->mMessage.Insert(prefix, 0);
}
dom::Throw(cx, mExtra.mDOMExceptionInfo->mRv,
mExtra.mDOMExceptionInfo->mMessage);
ClearDOMExceptionInfo();
mResult = NS_OK;
}
template <typename CleanupPolicy>
void TErrorResult<CleanupPolicy>::ClearDOMExceptionInfo() {
AssertInOwningThread();
MOZ_ASSERT(IsDOMException());
MOZ_ASSERT(mUnionState == HasDOMExceptionInfo);
delete mExtra.mDOMExceptionInfo;
mExtra.mDOMExceptionInfo = nullptr;
#ifdef DEBUG
mUnionState = HasNothing;
#endif // DEBUG
}
template <typename CleanupPolicy>
void TErrorResult<CleanupPolicy>::ClearUnionData() {
AssertInOwningThread();
if (IsJSException()) {
JSContext* cx = dom::danger::GetJSContext();
MOZ_ASSERT(cx);
mExtra.mJSException.setUndefined();
js::RemoveRawValueRoot(cx, &mExtra.mJSException);
#ifdef DEBUG
mUnionState = HasNothing;
#endif // DEBUG
} else if (IsErrorWithMessage()) {
ClearMessage();
} else if (IsDOMException()) {
ClearDOMExceptionInfo();
}
}
template <typename CleanupPolicy>
void TErrorResult<CleanupPolicy>::SetPendingGenericErrorException(
JSContext* cx) {
AssertInOwningThread();
MOZ_ASSERT(!IsErrorWithMessage());
MOZ_ASSERT(!IsJSException());
MOZ_ASSERT(!IsDOMException());
dom::Throw(cx, ErrorCode());
mResult = NS_OK;
}
template <typename CleanupPolicy>
TErrorResult<CleanupPolicy>& TErrorResult<CleanupPolicy>::operator=(
TErrorResult<CleanupPolicy>&& aRHS) {
AssertInOwningThread();
aRHS.AssertInOwningThread();
// Clear out any union members we may have right now, before we
// start writing to it.
ClearUnionData();
#ifdef DEBUG
mMightHaveUnreportedJSException = aRHS.mMightHaveUnreportedJSException;
aRHS.mMightHaveUnreportedJSException = false;
#endif
if (aRHS.IsErrorWithMessage()) {
InitMessage(aRHS.mExtra.mMessage);
aRHS.mExtra.mMessage = nullptr;
} else if (aRHS.IsJSException()) {
JSContext* cx = dom::danger::GetJSContext();
MOZ_ASSERT(cx);
JS::Value& exn = InitJSException();
if (!js::AddRawValueRoot(cx, &exn, "TErrorResult::mExtra::mJSException")) {
MOZ_CRASH("Could not root mExtra.mJSException, we're about to OOM");
}
mExtra.mJSException = aRHS.mExtra.mJSException;
aRHS.mExtra.mJSException.setUndefined();
js::RemoveRawValueRoot(cx, &aRHS.mExtra.mJSException);
} else if (aRHS.IsDOMException()) {
InitDOMExceptionInfo(aRHS.mExtra.mDOMExceptionInfo);
aRHS.mExtra.mDOMExceptionInfo = nullptr;
} else {
// Null out the union on both sides for hygiene purposes. This is purely
// precautionary, so InitMessage/placement-new is unnecessary.
mExtra.mMessage = aRHS.mExtra.mMessage = nullptr;
}
#ifdef DEBUG
mUnionState = aRHS.mUnionState;
aRHS.mUnionState = HasNothing;
#endif // DEBUG
// Note: It's important to do this last, since this affects the condition
// checks above!
mResult = aRHS.mResult;
aRHS.mResult = NS_OK;
return *this;
}
template <typename CleanupPolicy>
bool TErrorResult<CleanupPolicy>::operator==(const ErrorResult& aRight) const {
auto right = reinterpret_cast<const TErrorResult<CleanupPolicy>*>(&aRight);
if (mResult != right->mResult) {
return false;
}
if (IsJSException()) {
// js exceptions are always non-equal
return false;
}
if (IsErrorWithMessage()) {
return *mExtra.mMessage == *right->mExtra.mMessage;
}
if (IsDOMException()) {
return *mExtra.mDOMExceptionInfo == *right->mExtra.mDOMExceptionInfo;
}
return true;
}
template <typename CleanupPolicy>
void TErrorResult<CleanupPolicy>::CloneTo(TErrorResult& aRv) const {
AssertInOwningThread();
aRv.AssertInOwningThread();
aRv.ClearUnionData();
aRv.mResult = mResult;
#ifdef DEBUG
aRv.mMightHaveUnreportedJSException = mMightHaveUnreportedJSException;
#endif
if (IsErrorWithMessage()) {
#ifdef DEBUG
aRv.mUnionState = HasMessage;
#endif
Message* message = aRv.InitMessage(new Message());
message->mArgs = mExtra.mMessage->mArgs.Clone();
message->mErrorNumber = mExtra.mMessage->mErrorNumber;
} else if (IsDOMException()) {
#ifdef DEBUG
aRv.mUnionState = HasDOMExceptionInfo;
#endif
auto* exnInfo = new DOMExceptionInfo(mExtra.mDOMExceptionInfo->mRv,
mExtra.mDOMExceptionInfo->mMessage);
aRv.InitDOMExceptionInfo(exnInfo);
} else if (IsJSException()) {
#ifdef DEBUG
aRv.mUnionState = HasJSException;
#endif
JSContext* cx = dom::danger::GetJSContext();
JS::Rooted<JS::Value> exception(cx, mExtra.mJSException);
aRv.ThrowJSException(cx, exception);
}
}
template <typename CleanupPolicy>
void TErrorResult<CleanupPolicy>::SuppressException() {
AssertInOwningThread();
WouldReportJSException();
ClearUnionData();
// We don't use AssignErrorCode, because we want to override existing error
// states, which AssignErrorCode is not allowed to do.
mResult = NS_OK;
}
template <typename CleanupPolicy>
void TErrorResult<CleanupPolicy>::SetPendingException(JSContext* cx,
const char* context) {
AssertInOwningThread();
if (IsUncatchableException()) {
// Nuke any existing exception on cx, to make sure we're uncatchable.
JS_ClearPendingException(cx);
// Don't do any reporting. Just return, to create an
// uncatchable exception.
mResult = NS_OK;
return;
}
if (IsJSContextException()) {
// Whatever we need to throw is on the JSContext already.
MOZ_ASSERT(JS_IsExceptionPending(cx));
mResult = NS_OK;
return;
}
if (IsErrorWithMessage()) {
SetPendingExceptionWithMessage(cx, context);
return;
}
if (IsJSException()) {
SetPendingJSException(cx);
return;
}
if (IsDOMException()) {
SetPendingDOMException(cx, context);
return;
}
SetPendingGenericErrorException(cx);
}
template <typename CleanupPolicy>
void TErrorResult<CleanupPolicy>::StealExceptionFromJSContext(JSContext* cx) {
AssertInOwningThread();
MOZ_ASSERT(mMightHaveUnreportedJSException,
"Why didn't you tell us you planned to throw a JS exception?");
JS::Rooted<JS::Value> exn(cx);
if (!JS_GetPendingException(cx, &exn)) {
ThrowUncatchableException();
return;
}
ThrowJSException(cx, exn);
JS_ClearPendingException(cx);
}
template <typename CleanupPolicy>
void TErrorResult<CleanupPolicy>::NoteJSContextException(JSContext* aCx) {
AssertInOwningThread();
if (JS_IsExceptionPending(aCx)) {
mResult = NS_ERROR_INTERNAL_ERRORRESULT_EXCEPTION_ON_JSCONTEXT;
} else {
mResult = NS_ERROR_UNCATCHABLE_EXCEPTION;
}
}
/* static */
template <typename CleanupPolicy>
void TErrorResult<CleanupPolicy>::EnsureUTF8Validity(nsCString& aValue,
size_t aValidUpTo) {
nsCString valid;
if (NS_SUCCEEDED(UTF_8_ENCODING->DecodeWithoutBOMHandling(aValue, valid,
aValidUpTo))) {
aValue = valid;
} else {
aValue.SetLength(aValidUpTo);
}
}
template class TErrorResult<JustAssertCleanupPolicy>;
template class TErrorResult<AssertAndSuppressCleanupPolicy>;
template class TErrorResult<JustSuppressCleanupPolicy>;
template class TErrorResult<ThreadSafeJustSuppressCleanupPolicy>;
} // namespace binding_danger
namespace dom {
bool DefineConstants(JSContext* cx, JS::Handle<JSObject*> obj,
const ConstantSpec* cs) {
JS::Rooted<JS::Value> value(cx);
for (; cs->name; ++cs) {
value = cs->value;
bool ok = JS_DefineProperty(
cx, obj, cs->name, value,
JSPROP_ENUMERATE | JSPROP_READONLY | JSPROP_PERMANENT);
if (!ok) {
return false;
}
}
return true;
}
static inline bool Define(JSContext* cx, JS::Handle<JSObject*> obj,
const JSFunctionSpec* spec) {
return JS_DefineFunctions(cx, obj, spec);
}
static inline bool Define(JSContext* cx, JS::Handle<JSObject*> obj,
const JSPropertySpec* spec) {
return JS_DefineProperties(cx, obj, spec);
}
static inline bool Define(JSContext* cx, JS::Handle<JSObject*> obj,
const ConstantSpec* spec) {
return DefineConstants(cx, obj, spec);
}
template <typename T>
bool DefinePrefable(JSContext* cx, JS::Handle<JSObject*> obj,
const Prefable<T>* props) {
MOZ_ASSERT(props);
MOZ_ASSERT(props->specs);
do {
// Define if enabled
if (props->isEnabled(cx, obj)) {
if (!Define(cx, obj, props->specs)) {
return false;
}
}
} while ((++props)->specs);
return true;
}
bool DefineLegacyUnforgeableMethods(
JSContext* cx, JS::Handle<JSObject*> obj,
const Prefable<const JSFunctionSpec>* props) {
return DefinePrefable(cx, obj, props);
}
bool DefineLegacyUnforgeableAttributes(
JSContext* cx, JS::Handle<JSObject*> obj,
const Prefable<const JSPropertySpec>* props) {
return DefinePrefable(cx, obj, props);
}
// We should use JSFunction objects for interface objects, but we need a custom
// hasInstance hook because we have new interface objects on prototype chains of
// old (XPConnect-based) bindings. We also need Xrays and arbitrary numbers of
// reserved slots (e.g. for named constructors). So we define a custom
// funToString ObjectOps member for interface objects.
JSString* InterfaceObjectToString(JSContext* aCx, JS::Handle<JSObject*> aObject,
bool /* isToSource */) {
const JSClass* clasp = JS::GetClass(aObject);
MOZ_ASSERT(IsDOMIfaceAndProtoClass(clasp));
const DOMIfaceAndProtoJSClass* ifaceAndProtoJSClass =
DOMIfaceAndProtoJSClass::FromJSClass(clasp);
return JS_NewStringCopyZ(aCx, ifaceAndProtoJSClass->mFunToString);
}
bool Constructor(JSContext* cx, unsigned argc, JS::Value* vp) {
JS::CallArgs args = JS::CallArgsFromVp(argc, vp);
const JS::Value& v = js::GetFunctionNativeReserved(
&args.callee(), CONSTRUCTOR_NATIVE_HOLDER_RESERVED_SLOT);
const JSNativeHolder* nativeHolder =
static_cast<const JSNativeHolder*>(v.toPrivate());
return (nativeHolder->mNative)(cx, argc, vp);
}
static JSObject* CreateConstructor(JSContext* cx, JS::Handle<JSObject*> global,
const char* name,
const JSNativeHolder* nativeHolder,
unsigned ctorNargs) {
JSFunction* fun = js::NewFunctionWithReserved(cx, Constructor, ctorNargs,
JSFUN_CONSTRUCTOR, name);
if (!fun) {
return nullptr;
}
JSObject* constructor = JS_GetFunctionObject(fun);
js::SetFunctionNativeReserved(
constructor, CONSTRUCTOR_NATIVE_HOLDER_RESERVED_SLOT,
JS::PrivateValue(const_cast<JSNativeHolder*>(nativeHolder)));
return constructor;
}
static bool DefineConstructor(JSContext* cx, JS::Handle<JSObject*> global,
JS::Handle<jsid> name,
JS::Handle<JSObject*> constructor) {
bool alreadyDefined;
if (!JS_AlreadyHasOwnPropertyById(cx, global, name, &alreadyDefined)) {
return false;
}
// This is Enumerable: False per spec.
return alreadyDefined ||
JS_DefinePropertyById(cx, global, name, constructor, JSPROP_RESOLVING);
}
static bool DefineConstructor(JSContext* cx, JS::Handle<JSObject*> global,
const char* name,
JS::Handle<JSObject*> constructor) {
JSString* nameStr = JS_AtomizeString(cx, name);
if (!nameStr) {
return false;
}
JS::Rooted<JS::PropertyKey> nameKey(cx, JS::PropertyKey::NonIntAtom(nameStr));
return DefineConstructor(cx, global, nameKey, constructor);
}
// name must be an atom (or JS::PropertyKey::NonIntAtom will assert).
static JSObject* CreateInterfaceObject(
JSContext* cx, JS::Handle<JSObject*> global,
JS::Handle<JSObject*> constructorProto, const JSClass* constructorClass,
unsigned ctorNargs, const LegacyFactoryFunction* namedConstructors,
JS::Handle<JSObject*> proto, const NativeProperties* properties,
const NativeProperties* chromeOnlyProperties, JS::Handle<JSString*> name,
bool isChrome, bool defineOnGlobal, const char* const* legacyWindowAliases,
bool isNamespace) {
JS::Rooted<JSObject*> constructor(cx);
MOZ_ASSERT(constructorProto);
MOZ_ASSERT(constructorClass);
constructor =
JS_NewObjectWithGivenProto(cx, constructorClass, constructorProto);
if (!constructor) {
return nullptr;
}
if (!isNamespace) {
if (!JS_DefineProperty(cx, constructor, "length", ctorNargs,
JSPROP_READONLY)) {
return nullptr;
}
if (!JS_DefineProperty(cx, constructor, "name", name, JSPROP_READONLY)) {
return nullptr;
}
}
if (DOMIfaceAndProtoJSClass::FromJSClass(constructorClass)
->wantsInterfaceHasInstance) {
if (StaticPrefs::dom_webidl_crosscontext_hasinstance_enabled()) {
JS::Rooted<jsid> hasInstanceId(
cx, JS::GetWellKnownSymbolKey(cx, JS::SymbolCode::hasInstance));
if (!JS_DefineFunctionById(
cx, constructor, hasInstanceId, InterfaceHasInstance, 1,
// Flags match those of Function[Symbol.hasInstance]
JSPROP_READONLY | JSPROP_PERMANENT)) {
return nullptr;
}
}
if (isChrome && !JS_DefineFunction(cx, constructor, "isInstance",
InterfaceIsInstance, 1,
// Don't bother making it enumerable
0)) {
return nullptr;
}
}
if (properties) {
if (properties->HasStaticMethods() &&
!DefinePrefable(cx, constructor, properties->StaticMethods())) {
return nullptr;
}
if (properties->HasStaticAttributes() &&
!DefinePrefable(cx, constructor, properties->StaticAttributes())) {
return nullptr;
}
if (properties->HasConstants() &&
!DefinePrefable(cx, constructor, properties->Constants())) {
return nullptr;
}
}
if (chromeOnlyProperties && isChrome) {
if (chromeOnlyProperties->HasStaticMethods() &&
!DefinePrefable(cx, constructor,
chromeOnlyProperties->StaticMethods())) {
return nullptr;
}
if (chromeOnlyProperties->HasStaticAttributes() &&
!DefinePrefable(cx, constructor,
chromeOnlyProperties->StaticAttributes())) {
return nullptr;
}
if (chromeOnlyProperties->HasConstants() &&
!DefinePrefable(cx, constructor, chromeOnlyProperties->Constants())) {
return nullptr;
}
}
if (proto && !JS_LinkConstructorAndPrototype(cx, constructor, proto)) {
return nullptr;
}
JS::Rooted<jsid> nameStr(cx, JS::PropertyKey::NonIntAtom(name));
if (defineOnGlobal && !DefineConstructor(cx, global, nameStr, constructor)) {
return nullptr;
}
if (legacyWindowAliases && NS_IsMainThread()) {
for (; *legacyWindowAliases; ++legacyWindowAliases) {
if (!DefineConstructor(cx, global, *legacyWindowAliases, constructor)) {
return nullptr;
}
}
}
if (namedConstructors) {
int namedConstructorSlot = DOM_INTERFACE_SLOTS_BASE;
while (namedConstructors->mName) {
JS::Rooted<JSObject*> namedConstructor(
cx, CreateConstructor(cx, global, namedConstructors->mName,
&namedConstructors->mHolder,
namedConstructors->mNargs));
if (!namedConstructor ||
!JS_DefineProperty(cx, namedConstructor, "prototype", proto,
JSPROP_PERMANENT | JSPROP_READONLY) ||
(defineOnGlobal &&
!DefineConstructor(cx, global, namedConstructors->mName,
namedConstructor))) {
return nullptr;
}
JS::SetReservedSlot(constructor, namedConstructorSlot++,
JS::ObjectValue(*namedConstructor));
++namedConstructors;
}
}
return constructor;
}
static JSObject* CreateInterfacePrototypeObject(
JSContext* cx, JS::Handle<JSObject*> global,
JS::Handle<JSObject*> parentProto, const JSClass* protoClass,
const NativeProperties* properties,
const NativeProperties* chromeOnlyProperties,
const char* const* unscopableNames, JS::Handle<JSString*> name,
bool isGlobal) {
JS::Rooted<JSObject*> ourProto(
cx, JS_NewObjectWithGivenProto(cx, protoClass, parentProto));
if (!ourProto ||
// We don't try to define properties on the global's prototype; those
// properties go on the global itself.
(!isGlobal &&
!DefineProperties(cx, ourProto, properties, chromeOnlyProperties))) {
return nullptr;
}
if (unscopableNames) {
JS::Rooted<JSObject*> unscopableObj(
cx, JS_NewObjectWithGivenProto(cx, nullptr, nullptr));
if (!unscopableObj) {
return nullptr;
}
for (; *unscopableNames; ++unscopableNames) {
if (!JS_DefineProperty(cx, unscopableObj, *unscopableNames,
JS::TrueHandleValue, JSPROP_ENUMERATE)) {
return nullptr;
}
}
JS::Rooted<jsid> unscopableId(
cx, JS::GetWellKnownSymbolKey(cx, JS::SymbolCode::unscopables));
// Readonly and non-enumerable to match Array.prototype.
if (!JS_DefinePropertyById(cx, ourProto, unscopableId, unscopableObj,
JSPROP_READONLY)) {
return nullptr;
}
}
JS::Rooted<jsid> toStringTagId(
cx, JS::GetWellKnownSymbolKey(cx, JS::SymbolCode::toStringTag));
if (!JS_DefinePropertyById(cx, ourProto, toStringTagId, name,
JSPROP_READONLY)) {
return nullptr;
}
return ourProto;
}
bool DefineProperties(JSContext* cx, JS::Handle<JSObject*> obj,
const NativeProperties* properties,