forked from mozilla/gecko-dev
-
Notifications
You must be signed in to change notification settings - Fork 2
/
BindingUtils.cpp
2156 lines (1896 loc) · 69 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: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*-*/
/* vim: set ts=2 sw=2 et tw=79: */
/* 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 "JavaScriptParent.h"
#include "mozilla/DebugOnly.h"
#include "mozilla/FloatingPoint.h"
#include "mozilla/Assertions.h"
#include "AccessCheck.h"
#include "jsfriendapi.h"
#include "js/OldDebugAPI.h"
#include "nsIDOMGlobalPropertyInitializer.h"
#include "nsIXPConnect.h"
#include "WrapperFactory.h"
#include "xpcprivate.h"
#include "XPCQuickStubs.h"
#include "XrayWrapper.h"
#include "nsPrintfCString.h"
#include "prprf.h"
#include "mozilla/dom/DOMError.h"
#include "mozilla/dom/DOMErrorBinding.h"
#include "mozilla/dom/HTMLObjectElement.h"
#include "mozilla/dom/HTMLObjectElementBinding.h"
#include "mozilla/dom/HTMLSharedObjectElement.h"
#include "mozilla/dom/HTMLEmbedElementBinding.h"
#include "mozilla/dom/HTMLAppletElementBinding.h"
#include "WorkerPrivate.h"
namespace mozilla {
namespace dom {
JSErrorFormatString ErrorFormatString[] = {
#define MSG_DEF(_name, _argc, _str) \
{ _str, _argc, JSEXN_TYPEERR },
#include "mozilla/dom/Errors.msg"
#undef MSG_DEF
};
const JSErrorFormatString*
GetErrorMessage(void* aUserRef, const char* aLocale,
const unsigned aErrorNumber)
{
MOZ_ASSERT(aErrorNumber < ArrayLength(ErrorFormatString));
return &ErrorFormatString[aErrorNumber];
}
bool
ThrowErrorMessage(JSContext* aCx, const ErrNum aErrorNumber, ...)
{
va_list ap;
va_start(ap, aErrorNumber);
JS_ReportErrorNumberVA(aCx, GetErrorMessage, nullptr,
static_cast<const unsigned>(aErrorNumber), ap);
va_end(ap);
return false;
}
bool
ThrowInvalidThis(JSContext* aCx, const JS::CallArgs& aArgs,
const ErrNum aErrorNumber,
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);
JS_ReportErrorNumberUC(aCx, GetErrorMessage, nullptr,
static_cast<const unsigned>(aErrorNumber),
JS_GetStringCharsZ(aCx, funcName),
ifaceName.get());
return false;
}
} // namespace dom
struct ErrorResult::Message {
nsTArray<nsString> mArgs;
dom::ErrNum mErrorNumber;
};
void
ErrorResult::ThrowTypeError(const dom::ErrNum errorNumber, ...)
{
va_list ap;
va_start(ap, errorNumber);
if (IsJSException()) {
// We have rooted our mJSException, and we don't have the info
// needed to unroot here, so just bail.
va_end(ap);
MOZ_ASSERT(false,
"Ignoring ThrowTypeError call because we have a JS exception");
return;
}
if (IsTypeError()) {
delete mMessage;
}
mResult = NS_ERROR_TYPE_ERR;
Message* message = new Message();
message->mErrorNumber = errorNumber;
uint16_t argCount =
dom::GetErrorMessage(nullptr, nullptr, errorNumber)->argCount;
MOZ_ASSERT(argCount <= 10);
argCount = std::min<uint16_t>(argCount, 10);
while (argCount--) {
message->mArgs.AppendElement(*va_arg(ap, nsString*));
}
mMessage = message;
va_end(ap);
}
void
ErrorResult::ReportTypeError(JSContext* aCx)
{
MOZ_ASSERT(mMessage, "ReportTypeError() can be called only once");
Message* message = mMessage;
const uint32_t argCount = message->mArgs.Length();
const jschar* args[11];
for (uint32_t i = 0; i < argCount; ++i) {
args[i] = message->mArgs.ElementAt(i).get();
}
args[argCount] = nullptr;
JS_ReportErrorNumberUCArray(aCx, dom::GetErrorMessage, nullptr,
static_cast<const unsigned>(message->mErrorNumber),
argCount > 0 ? args : nullptr);
ClearMessage();
}
void
ErrorResult::ClearMessage()
{
if (IsTypeError()) {
delete mMessage;
mMessage = nullptr;
}
}
void
ErrorResult::ThrowJSException(JSContext* cx, JS::Handle<JS::Value> exn)
{
MOZ_ASSERT(mMightHaveUnreportedJSException,
"Why didn't you tell us you planned to throw a JS exception?");
if (IsTypeError()) {
delete mMessage;
}
// Make sure 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.
mJSException = JS::UndefinedValue();
if (!JS_AddNamedValueRoot(cx, &mJSException, "ErrorResult::mJSException")) {
// Don't use NS_ERROR_DOM_JS_EXCEPTION, because that indicates we have
// in fact rooted mJSException.
mResult = NS_ERROR_OUT_OF_MEMORY;
} else {
mJSException = exn;
mResult = NS_ERROR_DOM_JS_EXCEPTION;
}
}
void
ErrorResult::ReportJSException(JSContext* cx)
{
MOZ_ASSERT(!mMightHaveUnreportedJSException,
"Why didn't you tell us you planned to handle JS exceptions?");
JS::Rooted<JS::Value> exception(cx, mJSException);
if (JS_WrapValue(cx, &exception)) {
JS_SetPendingException(cx, exception);
}
mJSException = exception;
// If JS_WrapValue failed, not much we can do about it... No matter
// what, go ahead and unroot mJSException.
JS_RemoveValueRoot(cx, &mJSException);
}
void
ErrorResult::ReportJSExceptionFromJSImplementation(JSContext* aCx)
{
MOZ_ASSERT(!mMightHaveUnreportedJSException,
"Why didn't you tell us you planned to handle JS exceptions?");
dom::DOMError* domError;
nsresult rv = UNWRAP_OBJECT(DOMError, aCx, &mJSException.toObject(),
domError);
if (NS_FAILED(rv)) {
// Unwrapping really shouldn't fail here, if mExceptionHandling is set to
// eRethrowContentExceptions then the CallSetup destructor only stores an
// exception if it unwraps to DOMError. If we reach this then either
// mExceptionHandling wasn't set to eRethrowContentExceptions and we
// shouldn't be calling ReportJSExceptionFromJSImplementation or something
// went really wrong.
NS_RUNTIMEABORT("We stored a non-DOMError exception!");
}
nsString message;
domError->GetMessage(message);
JSErrorReport errorReport;
memset(&errorReport, 0, sizeof(JSErrorReport));
errorReport.errorNumber = JSMSG_USER_DEFINED_ERROR;
errorReport.ucmessage = message.get();
errorReport.exnType = JSEXN_ERR;
JS::Rooted<JSScript*> script(aCx);
if (JS_DescribeScriptedCaller(aCx, &script, &errorReport.lineno)) {
errorReport.filename = JS_GetScriptFilename(aCx, script);
}
JS_ThrowReportedError(aCx, nullptr, &errorReport);
JS_RemoveValueRoot(aCx, &mJSException);
// We no longer have a useful exception but we do want to signal that an error
// occured.
mResult = NS_ERROR_FAILURE;
}
void
ErrorResult::StealJSException(JSContext* cx,
JS::MutableHandle<JS::Value> value)
{
MOZ_ASSERT(!mMightHaveUnreportedJSException,
"Must call WouldReportJSException unconditionally in all codepaths that might call StealJSException");
MOZ_ASSERT(IsJSException(), "No exception to steal");
value.set(mJSException);
JS_RemoveValueRoot(cx, &mJSException);
mResult = NS_OK;
}
void
ErrorResult::ReportNotEnoughArgsError(JSContext* cx,
const char* ifaceName,
const char* memberName)
{
MOZ_ASSERT(ErrorCode() == NS_ERROR_XPC_NOT_ENOUGH_ARGS);
nsPrintfCString errorMessage("%s.%s", ifaceName, memberName);
ThrowErrorMessage(cx, dom::MSG_MISSING_ARGUMENTS, errorMessage.get());
}
namespace dom {
bool
DefineConstants(JSContext* cx, JS::Handle<JSObject*> obj,
const ConstantSpec* cs)
{
for (; cs->name; ++cs) {
bool ok =
JS_DefineProperty(cx, obj, cs->name, cs->value, NULL, NULL,
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
DefineUnforgeableAttributes(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. Because Function.prototype.toString throws if
// passed a non-Function object we also need to provide our own toString method
// for interface objects.
enum {
TOSTRING_CLASS_RESERVED_SLOT = 0,
TOSTRING_NAME_RESERVED_SLOT = 1
};
static bool
InterfaceObjectToString(JSContext* cx, unsigned argc, JS::Value *vp)
{
JS::CallArgs args = JS::CallArgsFromVp(argc, vp);
JS::Rooted<JSObject*> callee(cx, &args.callee());
if (!args.thisv().isObject()) {
JS_ReportErrorNumber(cx, js_GetErrorMessage, NULL, JSMSG_CANT_CONVERT_TO,
"null", "object");
return false;
}
JS::Value v = js::GetFunctionNativeReserved(callee,
TOSTRING_CLASS_RESERVED_SLOT);
const JSClass* clasp = static_cast<const JSClass*>(v.toPrivate());
v = js::GetFunctionNativeReserved(callee, TOSTRING_NAME_RESERVED_SLOT);
JSString* jsname = static_cast<JSString*>(JSVAL_TO_STRING(v));
size_t length;
const jschar* name = JS_GetInternedStringCharsAndLength(jsname, &length);
if (js::GetObjectJSClass(&args.thisv().toObject()) != clasp) {
JS_ReportErrorNumber(cx, js_GetErrorMessage, NULL, JSMSG_INCOMPATIBLE_PROTO,
NS_ConvertUTF16toUTF8(name).get(), "toString",
"object");
return false;
}
nsString str;
str.AppendLiteral("function ");
str.Append(name, length);
str.AppendLiteral("() {");
str.Append('\n');
str.AppendLiteral(" [native code]");
str.Append('\n');
str.AppendLiteral("}");
return xpc::NonVoidStringToJsval(cx, str, args.rval());
}
bool
Constructor(JSContext* cx, unsigned argc, JS::Value* vp)
{
JSObject* callee = JSVAL_TO_OBJECT(JS_CALLEE(cx, vp));
const JS::Value& v =
js::GetFunctionNativeReserved(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, global,
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, const char* name,
JS::Handle<JSObject*> constructor)
{
bool alreadyDefined;
if (!JS_AlreadyHasOwnProperty(cx, global, name, &alreadyDefined)) {
return false;
}
// This is Enumerable: False per spec.
return alreadyDefined ||
JS_DefineProperty(cx, global, name, OBJECT_TO_JSVAL(constructor),
nullptr, nullptr, 0);
}
static JSObject*
CreateInterfaceObject(JSContext* cx, JS::Handle<JSObject*> global,
JS::Handle<JSObject*> constructorProto,
const JSClass* constructorClass,
const JSNativeHolder* constructorNative,
unsigned ctorNargs, const NamedConstructor* namedConstructors,
JS::Handle<JSObject*> proto,
const NativeProperties* properties,
const NativeProperties* chromeOnlyProperties,
const char* name, bool defineOnGlobal)
{
JS::Rooted<JSObject*> constructor(cx);
if (constructorClass) {
MOZ_ASSERT(constructorProto);
constructor = JS_NewObject(cx, constructorClass, constructorProto, global);
} else {
MOZ_ASSERT(constructorNative);
MOZ_ASSERT(constructorProto == JS_GetFunctionPrototype(cx, global));
constructor = CreateConstructor(cx, global, name, constructorNative,
ctorNargs);
}
if (!constructor) {
return NULL;
}
if (constructorClass) {
// Have to shadow Function.prototype.toString, since that throws
// on things that are not js::FunctionClass.
JS::Rooted<JSFunction*> toString(cx,
js::DefineFunctionWithReserved(cx, constructor,
"toString",
InterfaceObjectToString,
0, 0));
if (!toString) {
return NULL;
}
JSString *str = ::JS_InternString(cx, name);
if (!str) {
return NULL;
}
JSObject* toStringObj = JS_GetFunctionObject(toString);
js::SetFunctionNativeReserved(toStringObj, TOSTRING_CLASS_RESERVED_SLOT,
PRIVATE_TO_JSVAL(const_cast<JSClass *>(constructorClass)));
js::SetFunctionNativeReserved(toStringObj, TOSTRING_NAME_RESERVED_SLOT,
STRING_TO_JSVAL(str));
if (!JS_DefineProperty(cx, constructor, "length", JS::Int32Value(ctorNargs),
nullptr, nullptr, JSPROP_READONLY | JSPROP_PERMANENT)) {
return NULL;
}
}
if (properties) {
if (properties->staticMethods &&
!DefinePrefable(cx, constructor, properties->staticMethods)) {
return nullptr;
}
if (properties->staticAttributes &&
!DefinePrefable(cx, constructor, properties->staticAttributes)) {
return nullptr;
}
if (properties->constants &&
!DefinePrefable(cx, constructor, properties->constants)) {
return nullptr;
}
}
if (chromeOnlyProperties) {
if (chromeOnlyProperties->staticMethods &&
!DefinePrefable(cx, constructor, chromeOnlyProperties->staticMethods)) {
return nullptr;
}
if (chromeOnlyProperties->staticAttributes &&
!DefinePrefable(cx, constructor,
chromeOnlyProperties->staticAttributes)) {
return nullptr;
}
if (chromeOnlyProperties->constants &&
!DefinePrefable(cx, constructor, chromeOnlyProperties->constants)) {
return nullptr;
}
}
if (proto && !JS_LinkConstructorAndPrototype(cx, constructor, proto)) {
return NULL;
}
if (defineOnGlobal && !DefineConstructor(cx, global, name, 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",
JS::ObjectValue(*proto), JS_PropertyStub,
JS_StrictPropertyStub,
JSPROP_PERMANENT | JSPROP_READONLY) ||
(defineOnGlobal &&
!DefineConstructor(cx, global, namedConstructors->mName,
namedConstructor))) {
return nullptr;
}
js::SetReservedSlot(constructor, namedConstructorSlot++,
JS::ObjectValue(*namedConstructor));
++namedConstructors;
}
}
return constructor;
}
bool
DefineWebIDLBindingPropertiesOnXPCProto(JSContext* cx,
JS::Handle<JSObject*> proto,
const NativeProperties* properties)
{
if (properties->methods &&
!DefinePrefable(cx, proto, properties->methods)) {
return false;
}
if (properties->attributes &&
!DefinePrefable(cx, proto, properties->attributes)) {
return false;
}
return true;
}
static JSObject*
CreateInterfacePrototypeObject(JSContext* cx, JS::Handle<JSObject*> global,
JS::Handle<JSObject*> parentProto,
const JSClass* protoClass,
const NativeProperties* properties,
const NativeProperties* chromeOnlyProperties)
{
JS::Rooted<JSObject*> ourProto(cx,
JS_NewObjectWithUniqueType(cx, protoClass, parentProto, global));
if (!ourProto) {
return NULL;
}
if (properties) {
if (properties->methods &&
!DefinePrefable(cx, ourProto, properties->methods)) {
return nullptr;
}
if (properties->attributes &&
!DefinePrefable(cx, ourProto, properties->attributes)) {
return nullptr;
}
if (properties->constants &&
!DefinePrefable(cx, ourProto, properties->constants)) {
return nullptr;
}
}
if (chromeOnlyProperties) {
if (chromeOnlyProperties->methods &&
!DefinePrefable(cx, ourProto, chromeOnlyProperties->methods)) {
return nullptr;
}
if (chromeOnlyProperties->attributes &&
!DefinePrefable(cx, ourProto, chromeOnlyProperties->attributes)) {
return nullptr;
}
if (chromeOnlyProperties->constants &&
!DefinePrefable(cx, ourProto, chromeOnlyProperties->constants)) {
return nullptr;
}
}
return ourProto;
}
void
CreateInterfaceObjects(JSContext* cx, JS::Handle<JSObject*> global,
JS::Handle<JSObject*> protoProto,
const JSClass* protoClass, JS::Heap<JSObject*>* protoCache,
JS::Handle<JSObject*> constructorProto,
const JSClass* constructorClass, const JSNativeHolder* constructor,
unsigned ctorNargs, const NamedConstructor* namedConstructors,
JS::Heap<JSObject*>* constructorCache, const DOMClass* domClass,
const NativeProperties* properties,
const NativeProperties* chromeOnlyProperties,
const char* name, bool defineOnGlobal)
{
MOZ_ASSERT(protoClass || constructorClass || constructor,
"Need at least one class or a constructor!");
MOZ_ASSERT(!((properties &&
(properties->methods || properties->attributes)) ||
(chromeOnlyProperties &&
(chromeOnlyProperties->methods ||
chromeOnlyProperties->attributes))) || protoClass,
"Methods or properties but no protoClass!");
MOZ_ASSERT(!((properties &&
(properties->staticMethods || properties->staticAttributes)) ||
(chromeOnlyProperties &&
(chromeOnlyProperties->staticMethods ||
chromeOnlyProperties->staticAttributes))) ||
constructorClass || constructor,
"Static methods but no constructorClass or constructor!");
MOZ_ASSERT(bool(name) == bool(constructorClass || constructor),
"Must have name precisely when we have an interface object");
MOZ_ASSERT(!constructorClass || !constructor);
MOZ_ASSERT(!protoClass == !protoCache,
"If, and only if, there is an interface prototype object we need "
"to cache it");
MOZ_ASSERT(!(constructorClass || constructor) == !constructorCache,
"If, and only if, there is an interface object we need to cache "
"it");
JS::Rooted<JSObject*> proto(cx);
if (protoClass) {
proto =
CreateInterfacePrototypeObject(cx, global, protoProto, protoClass,
properties, chromeOnlyProperties);
if (!proto) {
return;
}
js::SetReservedSlot(proto, DOM_PROTO_INSTANCE_CLASS_SLOT,
JS::PrivateValue(const_cast<DOMClass*>(domClass)));
*protoCache = proto;
}
else {
MOZ_ASSERT(!proto);
}
JSObject* interface;
if (constructorClass || constructor) {
interface = CreateInterfaceObject(cx, global, constructorProto,
constructorClass, constructor,
ctorNargs, namedConstructors, proto,
properties, chromeOnlyProperties, name,
defineOnGlobal);
if (!interface) {
if (protoCache) {
// If we fail we need to make sure to clear the value of protoCache we
// set above.
*protoCache = nullptr;
}
return;
}
*constructorCache = interface;
}
}
bool
NativeInterface2JSObjectAndThrowIfFailed(JSContext* aCx,
JS::Handle<JSObject*> aScope,
JS::MutableHandle<JS::Value> aRetval,
xpcObjectHelper& aHelper,
const nsIID* aIID,
bool aAllowNativeWrapper)
{
nsresult rv;
// Inline some logic from XPCConvert::NativeInterfaceToJSObject that we need
// on all threads.
nsWrapperCache *cache = aHelper.GetWrapperCache();
if (cache && cache->IsDOMBinding()) {
JS::Rooted<JSObject*> obj(aCx, cache->GetWrapper());
if (!obj) {
obj = cache->WrapObject(aCx, aScope);
}
if (obj && aAllowNativeWrapper && !JS_WrapObject(aCx, &obj)) {
return false;
}
if (obj) {
aRetval.setObject(*obj);
return true;
}
}
MOZ_ASSERT(NS_IsMainThread());
if (!XPCConvert::NativeInterface2JSObject(aRetval, NULL, aHelper, aIID,
NULL, aAllowNativeWrapper, &rv)) {
// I can't tell if NativeInterface2JSObject throws JS exceptions
// or not. This is a sloppy stab at the right semantics; the
// method really ought to be fixed to behave consistently.
if (!JS_IsExceptionPending(aCx)) {
Throw(aCx, NS_FAILED(rv) ? rv : NS_ERROR_UNEXPECTED);
}
return false;
}
return true;
}
bool
TryPreserveWrapper(JSObject* obj)
{
MOZ_ASSERT(IsDOMObject(obj));
if (nsISupports* native = UnwrapDOMObjectToISupports(obj)) {
nsWrapperCache* cache = nullptr;
CallQueryInterface(native, &cache);
if (cache) {
cache->PreserveWrapper(native);
}
return true;
}
// If this DOMClass is not cycle collected, then it isn't wrappercached,
// so it does not need to be preserved. If it is cycle collected, then
// we can't tell if it is wrappercached or not, so we just return false.
const DOMClass* domClass = GetDOMClass(obj);
return domClass && !domClass->mParticipant;
}
// Can only be called with the immediate prototype of the instance object. Can
// only be called on the prototype of an object known to be a DOM instance.
bool
InstanceClassHasProtoAtDepth(JS::Handle<JSObject*> protoObject, uint32_t protoID,
uint32_t depth)
{
const DOMClass* domClass = static_cast<const DOMClass*>(
js::GetReservedSlot(protoObject, DOM_PROTO_INSTANCE_CLASS_SLOT).toPrivate());
return (uint32_t)domClass->mInterfaceChain[depth] == protoID;
}
// Only set allowNativeWrapper to false if you really know you need it, if in
// doubt use true. Setting it to false disables security wrappers.
bool
XPCOMObjectToJsval(JSContext* cx, JS::Handle<JSObject*> scope,
xpcObjectHelper& helper, const nsIID* iid,
bool allowNativeWrapper, JS::MutableHandle<JS::Value> rval)
{
if (!NativeInterface2JSObjectAndThrowIfFailed(cx, scope, rval, helper, iid,
allowNativeWrapper)) {
return false;
}
#ifdef DEBUG
JSObject* jsobj = rval.toObjectOrNull();
if (jsobj && !js::GetObjectParent(jsobj))
NS_ASSERTION(js::GetObjectClass(jsobj)->flags & JSCLASS_IS_GLOBAL,
"Why did we recreate this wrapper?");
#endif
return true;
}
bool
VariantToJsval(JSContext* aCx, JS::Handle<JSObject*> aScope,
nsIVariant* aVariant, JS::MutableHandle<JS::Value> aRetval)
{
nsresult rv;
if (!XPCVariant::VariantDataToJS(aVariant, &rv, aRetval)) {
// Does it throw? Who knows
if (!JS_IsExceptionPending(aCx)) {
Throw(aCx, NS_FAILED(rv) ? rv : NS_ERROR_UNEXPECTED);
}
return false;
}
return true;
}
bool
QueryInterface(JSContext* cx, unsigned argc, JS::Value* vp)
{
JS::CallArgs args = JS::CallArgsFromVp(argc, vp);
JS::Rooted<JS::Value> thisv(cx, JS_THIS(cx, vp));
if (thisv.isNull())
return false;
// Get the object. It might be a security wrapper, in which case we do a checked
// unwrap.
JS::Rooted<JSObject*> origObj(cx, &thisv.toObject());
JSObject* obj = js::CheckedUnwrap(origObj);
if (!obj) {
JS_ReportError(cx, "Permission denied to access object");
return false;
}
nsISupports* native = UnwrapDOMObjectToISupports(obj);
if (!native) {
return Throw(cx, NS_ERROR_FAILURE);
}
if (argc < 1) {
return Throw(cx, NS_ERROR_XPC_NOT_ENOUGH_ARGS);
}
if (!args[0].isObject()) {
return Throw(cx, NS_ERROR_XPC_BAD_CONVERT_JS);
}
nsIJSID* iid;
SelfRef iidRef;
if (NS_FAILED(xpc_qsUnwrapArg<nsIJSID>(cx, args[0], &iid, &iidRef.ptr,
args[0]))) {
return Throw(cx, NS_ERROR_XPC_BAD_CONVERT_JS);
}
MOZ_ASSERT(iid);
if (iid->GetID()->Equals(NS_GET_IID(nsIClassInfo))) {
nsresult rv;
nsCOMPtr<nsIClassInfo> ci = do_QueryInterface(native, &rv);
if (NS_FAILED(rv)) {
return Throw(cx, rv);
}
return WrapObject(cx, origObj, ci, &NS_GET_IID(nsIClassInfo), args.rval());
}
nsCOMPtr<nsISupports> unused;
nsresult rv = native->QueryInterface(*iid->GetID(), getter_AddRefs(unused));
if (NS_FAILED(rv)) {
return Throw(cx, rv);
}
*vp = thisv;
return true;
}
bool
ThrowingConstructor(JSContext* cx, unsigned argc, JS::Value* vp)
{
return ThrowErrorMessage(cx, MSG_ILLEGAL_CONSTRUCTOR);
}
inline const NativePropertyHooks*
GetNativePropertyHooks(JSContext *cx, JS::Handle<JSObject*> obj,
DOMObjectType& type)
{
const DOMClass* domClass = GetDOMClass(obj);
if (domClass) {
type = eInstance;
return domClass->mNativeHooks;
}
if (JS_ObjectIsFunction(cx, obj)) {
MOZ_ASSERT(JS_IsNativeFunction(obj, Constructor));
type = eInterface;
const JS::Value& v =
js::GetFunctionNativeReserved(obj,
CONSTRUCTOR_NATIVE_HOLDER_RESERVED_SLOT);
const JSNativeHolder* nativeHolder =
static_cast<const JSNativeHolder*>(v.toPrivate());
return nativeHolder->mPropertyHooks;
}
MOZ_ASSERT(IsDOMIfaceAndProtoClass(js::GetObjectClass(obj)));
const DOMIfaceAndProtoJSClass* ifaceAndProtoJSClass =
DOMIfaceAndProtoJSClass::FromJSClass(js::GetObjectClass(obj));
type = ifaceAndProtoJSClass->mType;
return ifaceAndProtoJSClass->mNativeHooks;
}
// Try to resolve a property as an unforgeable property from the given
// NativeProperties, if it's there. nativeProperties is allowed to be null (in
// which case we of course won't resolve anything).
static bool
XrayResolveUnforgeableProperty(JSContext* cx, JS::Handle<JSObject*> wrapper,
JS::Handle<JSObject*> obj, JS::Handle<jsid> id,
JS::MutableHandle<JSPropertyDescriptor> desc,
const NativeProperties* nativeProperties);
static bool
XrayResolveNativeProperty(JSContext* cx, JS::Handle<JSObject*> wrapper,
const NativePropertyHooks* nativePropertyHooks,
DOMObjectType type, JS::Handle<JSObject*> obj,
JS::Handle<jsid> id,
JS::MutableHandle<JSPropertyDescriptor> desc);
bool
XrayResolveOwnProperty(JSContext* cx, JS::Handle<JSObject*> wrapper,
JS::Handle<JSObject*> obj, JS::Handle<jsid> id,
JS::MutableHandle<JSPropertyDescriptor> desc, unsigned flags)
{
DOMObjectType type;
const NativePropertyHooks *nativePropertyHooks =
GetNativePropertyHooks(cx, obj, type);
if (type != eInstance) {
// For prototype objects and interface objects, just return their
// normal set of properties.
return XrayResolveNativeProperty(cx, wrapper, nativePropertyHooks, type,
obj, id, desc);
}
// Check for unforgeable properties before doing mResolveOwnProperty weirdness
const NativePropertiesHolder& nativeProperties =
nativePropertyHooks->mNativeProperties;
if (!XrayResolveUnforgeableProperty(cx, wrapper, obj, id, desc,
nativeProperties.regular)) {
return false;
}
if (desc.object()) {
return true;
}
if (!XrayResolveUnforgeableProperty(cx, wrapper, obj, id, desc,
nativeProperties.chromeOnly)) {
return false;
}
if (desc.object()) {
return true;
}
return !nativePropertyHooks->mResolveOwnProperty ||
nativePropertyHooks->mResolveOwnProperty(cx, wrapper, obj, id, desc, flags);
}
static bool
XrayResolveAttribute(JSContext* cx, JS::Handle<JSObject*> wrapper,
JS::Handle<JSObject*> obj, JS::Handle<jsid> id,
const Prefable<const JSPropertySpec>* attributes, jsid* attributeIds,
const JSPropertySpec* attributeSpecs, JS::MutableHandle<JSPropertyDescriptor> desc)
{
for (; attributes->specs; ++attributes) {
if (attributes->isEnabled(cx, obj)) {
// Set i to be the index into our full list of ids/specs that we're
// looking at now.
size_t i = attributes->specs - attributeSpecs;
for ( ; attributeIds[i] != JSID_VOID; ++i) {
if (id == attributeIds[i]) {
const JSPropertySpec& attrSpec = attributeSpecs[i];
// Because of centralization, we need to make sure we fault in the
// JitInfos as well. At present, until the JSAPI changes, the easiest
// way to do this is wrap them up as functions ourselves.
desc.setAttributes(attrSpec.flags & ~JSPROP_NATIVE_ACCESSORS);
// They all have getters, so we can just make it.
JS::Rooted<JSObject*> global(cx, JS_GetGlobalForObject(cx, wrapper));
JS::Rooted<JSFunction*> fun(cx,
JS_NewFunctionById(cx, (JSNative)attrSpec.getter.op,
0, 0, global, id));
if (!fun)
return false;
SET_JITINFO(fun, attrSpec.getter.info);
JSObject *funobj = JS_GetFunctionObject(fun);
desc.setGetterObject(funobj);
desc.attributesRef() |= JSPROP_GETTER;
if (attrSpec.setter.op) {
// We have a setter! Make it.
fun = JS_NewFunctionById(cx, (JSNative)attrSpec.setter.op, 1, 0,
global, id);
if (!fun)
return false;
SET_JITINFO(fun, attrSpec.setter.info);
funobj = JS_GetFunctionObject(fun);
desc.setSetterObject(funobj);
desc.attributesRef() |= JSPROP_SETTER;
} else {
desc.setSetter(nullptr);
}
desc.object().set(wrapper);
return true;
}
}
}
}
return true;
}
/* static */ bool
XrayResolveUnforgeableProperty(JSContext* cx, JS::Handle<JSObject*> wrapper,
JS::Handle<JSObject*> obj, JS::Handle<jsid> id,
JS::MutableHandle<JSPropertyDescriptor> desc,
const NativeProperties* nativeProperties)
{
return !nativeProperties || !nativeProperties->unforgeableAttributes ||
XrayResolveAttribute(cx, wrapper, obj, id,
nativeProperties->unforgeableAttributes,
nativeProperties->unforgeableAttributeIds,
nativeProperties->unforgeableAttributeSpecs,
desc);
}
static bool