1 /* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
2 /* vim: set ts=8 sts=2 et sw=2 tw=80: */
3 /* This Source Code Form is subject to the terms of the Mozilla Public
4 * License, v. 2.0. If a copy of the MPL was not distributed with this
5 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
6
7 #include "XrayWrapper.h"
8 #include "AccessCheck.h"
9 #include "WrapperFactory.h"
10
11 #include "nsDependentString.h"
12 #include "nsIConsoleService.h"
13 #include "nsIScriptError.h"
14 #include "nsIXPConnect.h"
15 #include "mozilla/dom/Element.h"
16 #include "mozilla/dom/ScriptSettings.h"
17
18 #include "XPCWrapper.h"
19 #include "xpcprivate.h"
20
21 #include "jsapi.h"
22 #include "js/experimental/TypedData.h" // JS_GetTypedArrayLength
23 #include "js/friend/WindowProxy.h" // js::IsWindowProxy
24 #include "js/friend/XrayJitInfo.h" // JS::XrayJitInfo
25 #include "js/Object.h" // JS::GetClass, JS::GetCompartment, JS::GetReservedSlot, JS::SetReservedSlot
26 #include "js/PropertySpec.h"
27 #include "nsJSUtils.h"
28 #include "nsPrintfCString.h"
29
30 #include "mozilla/FloatingPoint.h"
31 #include "mozilla/dom/BindingUtils.h"
32 #include "mozilla/dom/BrowsingContext.h"
33 #include "mozilla/dom/WindowBinding.h"
34 #include "mozilla/dom/WindowProxyHolder.h"
35 #include "mozilla/dom/XrayExpandoClass.h"
36 #include "nsGlobalWindow.h"
37
38 using namespace mozilla::dom;
39 using namespace JS;
40 using namespace mozilla;
41
42 using js::BaseProxyHandler;
43 using js::CheckedUnwrapStatic;
44 using js::IsCrossCompartmentWrapper;
45 using js::UncheckedUnwrap;
46 using js::Wrapper;
47
48 namespace xpc {
49
50 #define Between(x, a, b) (a <= x && x <= b)
51
52 static_assert(JSProto_URIError - JSProto_Error == 8,
53 "New prototype added in error object range");
54 #define AssertErrorObjectKeyInBounds(key) \
55 static_assert(Between(key, JSProto_Error, JSProto_URIError), \
56 "We depend on js/ProtoKey.h ordering here");
57 MOZ_FOR_EACH(AssertErrorObjectKeyInBounds, (),
58 (JSProto_Error, JSProto_InternalError, JSProto_AggregateError,
59 JSProto_EvalError, JSProto_RangeError, JSProto_ReferenceError,
60 JSProto_SyntaxError, JSProto_TypeError, JSProto_URIError));
61
62 static_assert(JSProto_Uint8ClampedArray - JSProto_Int8Array == 8,
63 "New prototype added in typed array range");
64 #define AssertTypedArrayKeyInBounds(key) \
65 static_assert(Between(key, JSProto_Int8Array, JSProto_Uint8ClampedArray), \
66 "We depend on js/ProtoKey.h ordering here");
67 MOZ_FOR_EACH(AssertTypedArrayKeyInBounds, (),
68 (JSProto_Int8Array, JSProto_Uint8Array, JSProto_Int16Array,
69 JSProto_Uint16Array, JSProto_Int32Array, JSProto_Uint32Array,
70 JSProto_Float32Array, JSProto_Float64Array,
71 JSProto_Uint8ClampedArray));
72
73 #undef Between
74
IsErrorObjectKey(JSProtoKey key)75 inline bool IsErrorObjectKey(JSProtoKey key) {
76 return key >= JSProto_Error && key <= JSProto_URIError;
77 }
78
IsTypedArrayKey(JSProtoKey key)79 inline bool IsTypedArrayKey(JSProtoKey key) {
80 return key >= JSProto_Int8Array && key <= JSProto_Uint8ClampedArray;
81 }
82
83 // Whitelist for the standard ES classes we can Xray to.
IsJSXraySupported(JSProtoKey key)84 static bool IsJSXraySupported(JSProtoKey key) {
85 if (IsTypedArrayKey(key)) {
86 return true;
87 }
88 if (IsErrorObjectKey(key)) {
89 return true;
90 }
91 switch (key) {
92 case JSProto_Date:
93 case JSProto_DataView:
94 case JSProto_Object:
95 case JSProto_Array:
96 case JSProto_Function:
97 case JSProto_TypedArray:
98 case JSProto_SavedFrame:
99 case JSProto_RegExp:
100 case JSProto_Promise:
101 case JSProto_ArrayBuffer:
102 case JSProto_SharedArrayBuffer:
103 case JSProto_Map:
104 case JSProto_Set:
105 case JSProto_WeakMap:
106 case JSProto_WeakSet:
107 return true;
108 default:
109 return false;
110 }
111 }
112
GetXrayType(JSObject * obj)113 XrayType GetXrayType(JSObject* obj) {
114 obj = js::UncheckedUnwrap(obj, /* stopAtWindowProxy = */ false);
115 if (mozilla::dom::UseDOMXray(obj)) {
116 return XrayForDOMObject;
117 }
118
119 MOZ_ASSERT(!js::IsWindowProxy(obj));
120
121 JSProtoKey standardProto = IdentifyStandardInstanceOrPrototype(obj);
122 if (IsJSXraySupported(standardProto)) {
123 return XrayForJSObject;
124 }
125
126 // Modulo a few exceptions, everything else counts as an XrayWrapper to an
127 // opaque object, which means that more-privileged code sees nothing from
128 // the underlying object. This is very important for security. In some cases
129 // though, we need to make an exception for compatibility.
130 if (IsSandbox(obj)) {
131 return NotXray;
132 }
133
134 return XrayForOpaqueObject;
135 }
136
XrayAwareCalleeGlobal(JSObject * fun)137 JSObject* XrayAwareCalleeGlobal(JSObject* fun) {
138 MOZ_ASSERT(js::IsFunctionObject(fun));
139
140 if (!js::FunctionHasNativeReserved(fun)) {
141 // Just a normal function, no Xrays involved.
142 return JS::GetNonCCWObjectGlobal(fun);
143 }
144
145 // The functions we expect here have the Xray wrapper they're associated with
146 // in their XRAY_DOM_FUNCTION_PARENT_WRAPPER_SLOT and, in a debug build,
147 // themselves in their XRAY_DOM_FUNCTION_NATIVE_SLOT_FOR_SELF. Assert that
148 // last bit.
149 MOZ_ASSERT(&js::GetFunctionNativeReserved(
150 fun, XRAY_DOM_FUNCTION_NATIVE_SLOT_FOR_SELF)
151 .toObject() == fun);
152
153 Value v =
154 js::GetFunctionNativeReserved(fun, XRAY_DOM_FUNCTION_PARENT_WRAPPER_SLOT);
155 MOZ_ASSERT(IsXrayWrapper(&v.toObject()));
156
157 JSObject* xrayTarget = js::UncheckedUnwrap(&v.toObject());
158 return JS::GetNonCCWObjectGlobal(xrayTarget);
159 }
160
getExpandoChain(HandleObject obj)161 JSObject* XrayTraits::getExpandoChain(HandleObject obj) {
162 return ObjectScope(obj)->GetExpandoChain(obj);
163 }
164
detachExpandoChain(HandleObject obj)165 JSObject* XrayTraits::detachExpandoChain(HandleObject obj) {
166 return ObjectScope(obj)->DetachExpandoChain(obj);
167 }
168
setExpandoChain(JSContext * cx,HandleObject obj,HandleObject chain)169 bool XrayTraits::setExpandoChain(JSContext* cx, HandleObject obj,
170 HandleObject chain) {
171 return ObjectScope(obj)->SetExpandoChain(cx, obj, chain);
172 }
173
174 const JSClass XrayTraits::HolderClass = {
175 "XrayHolder", JSCLASS_HAS_RESERVED_SLOTS(HOLDER_SHARED_SLOT_COUNT)};
176
177 const JSClass JSXrayTraits::HolderClass = {
178 "JSXrayHolder", JSCLASS_HAS_RESERVED_SLOTS(SLOT_COUNT)};
179
resolveOwnProperty(JSContext * cx,HandleObject wrapper,HandleObject target,HandleObject holder,HandleId id,MutableHandle<Maybe<PropertyDescriptor>> desc)180 bool OpaqueXrayTraits::resolveOwnProperty(
181 JSContext* cx, HandleObject wrapper, HandleObject target,
182 HandleObject holder, HandleId id,
183 MutableHandle<Maybe<PropertyDescriptor>> desc) {
184 bool ok =
185 XrayTraits::resolveOwnProperty(cx, wrapper, target, holder, id, desc);
186 if (!ok || desc.isSome()) {
187 return ok;
188 }
189
190 return ReportWrapperDenial(cx, id, WrapperDenialForXray,
191 "object is not safely Xrayable");
192 }
193
ReportWrapperDenial(JSContext * cx,HandleId id,WrapperDenialType type,const char * reason)194 bool ReportWrapperDenial(JSContext* cx, HandleId id, WrapperDenialType type,
195 const char* reason) {
196 RealmPrivate* priv = RealmPrivate::Get(CurrentGlobalOrNull(cx));
197 bool alreadyWarnedOnce = priv->wrapperDenialWarnings[type];
198 priv->wrapperDenialWarnings[type] = true;
199
200 // The browser console warning is only emitted for the first violation,
201 // whereas the (debug-only) NS_WARNING is emitted for each violation.
202 #ifndef DEBUG
203 if (alreadyWarnedOnce) {
204 return true;
205 }
206 #endif
207
208 nsAutoJSString propertyName;
209 RootedValue idval(cx);
210 if (!JS_IdToValue(cx, id, &idval)) {
211 return false;
212 }
213 JSString* str = JS_ValueToSource(cx, idval);
214 if (!str) {
215 return false;
216 }
217 if (!propertyName.init(cx, str)) {
218 return false;
219 }
220 AutoFilename filename;
221 unsigned line = 0, column = 0;
222 DescribeScriptedCaller(cx, &filename, &line, &column);
223
224 // Warn to the terminal for the logs.
225 NS_WARNING(
226 nsPrintfCString("Silently denied access to property %s: %s (@%s:%u:%u)",
227 NS_LossyConvertUTF16toASCII(propertyName).get(), reason,
228 filename.get(), line, column)
229 .get());
230
231 // If this isn't the first warning on this topic for this global, we've
232 // already bailed out in opt builds. Now that the NS_WARNING is done, bail
233 // out in debug builds as well.
234 if (alreadyWarnedOnce) {
235 return true;
236 }
237
238 //
239 // Log a message to the console service.
240 //
241
242 // Grab the pieces.
243 nsCOMPtr<nsIConsoleService> consoleService =
244 do_GetService(NS_CONSOLESERVICE_CONTRACTID);
245 NS_ENSURE_TRUE(consoleService, true);
246 nsCOMPtr<nsIScriptError> errorObject =
247 do_CreateInstance(NS_SCRIPTERROR_CONTRACTID);
248 NS_ENSURE_TRUE(errorObject, true);
249
250 // Compute the current window id if any.
251 uint64_t windowId = 0;
252 if (nsGlobalWindowInner* win = CurrentWindowOrNull(cx)) {
253 windowId = win->WindowID();
254 }
255
256 Maybe<nsPrintfCString> errorMessage;
257 if (type == WrapperDenialForXray) {
258 errorMessage.emplace(
259 "XrayWrapper denied access to property %s (reason: %s). "
260 "See https://developer.mozilla.org/en-US/docs/Xray_vision "
261 "for more information. Note that only the first denied "
262 "property access from a given global object will be reported.",
263 NS_LossyConvertUTF16toASCII(propertyName).get(), reason);
264 } else {
265 MOZ_ASSERT(type == WrapperDenialForCOW);
266 errorMessage.emplace(
267 "Security wrapper denied access to property %s on privileged "
268 "Javascript object. Support for exposing privileged objects "
269 "to untrusted content via __exposedProps__ has been "
270 "removed - use WebIDL bindings or Components.utils.cloneInto "
271 "instead. Note that only the first denied property access from a "
272 "given global object will be reported.",
273 NS_LossyConvertUTF16toASCII(propertyName).get());
274 }
275 nsString filenameStr(NS_ConvertASCIItoUTF16(filename.get()));
276 nsresult rv = errorObject->InitWithWindowID(
277 NS_ConvertASCIItoUTF16(errorMessage.ref()), filenameStr, u""_ns, line,
278 column, nsIScriptError::warningFlag, "XPConnect", windowId);
279 NS_ENSURE_SUCCESS(rv, true);
280 rv = consoleService->LogMessage(errorObject);
281 NS_ENSURE_SUCCESS(rv, true);
282
283 return true;
284 }
285
getOwnPropertyFromWrapperIfSafe(JSContext * cx,HandleObject wrapper,HandleId id,MutableHandle<Maybe<PropertyDescriptor>> outDesc)286 bool JSXrayTraits::getOwnPropertyFromWrapperIfSafe(
287 JSContext* cx, HandleObject wrapper, HandleId id,
288 MutableHandle<Maybe<PropertyDescriptor>> outDesc) {
289 MOZ_ASSERT(js::IsObjectInContextCompartment(wrapper, cx));
290 RootedObject target(cx, getTargetObject(wrapper));
291 RootedObject wrapperGlobal(cx, JS::CurrentGlobalOrNull(cx));
292 {
293 JSAutoRealm ar(cx, target);
294 JS_MarkCrossZoneId(cx, id);
295 if (!getOwnPropertyFromTargetIfSafe(cx, target, wrapper, wrapperGlobal, id,
296 outDesc)) {
297 return false;
298 }
299 }
300 return JS_WrapPropertyDescriptor(cx, outDesc);
301 }
302
getOwnPropertyFromTargetIfSafe(JSContext * cx,HandleObject target,HandleObject wrapper,HandleObject wrapperGlobal,HandleId id,MutableHandle<Maybe<PropertyDescriptor>> outDesc)303 bool JSXrayTraits::getOwnPropertyFromTargetIfSafe(
304 JSContext* cx, HandleObject target, HandleObject wrapper,
305 HandleObject wrapperGlobal, HandleId id,
306 MutableHandle<Maybe<PropertyDescriptor>> outDesc) {
307 // Note - This function operates in the target compartment, because it
308 // avoids a bunch of back-and-forth wrapping in enumerateNames.
309 MOZ_ASSERT(getTargetObject(wrapper) == target);
310 MOZ_ASSERT(js::IsObjectInContextCompartment(target, cx));
311 MOZ_ASSERT(WrapperFactory::IsXrayWrapper(wrapper));
312 MOZ_ASSERT(JS_IsGlobalObject(wrapperGlobal));
313 js::AssertSameCompartment(wrapper, wrapperGlobal);
314 MOZ_ASSERT(outDesc.isNothing());
315
316 Rooted<Maybe<PropertyDescriptor>> desc(cx);
317 if (!JS_GetOwnPropertyDescriptorById(cx, target, id, &desc)) {
318 return false;
319 }
320
321 // If the property doesn't exist at all, we're done.
322 if (desc.isNothing()) {
323 return true;
324 }
325
326 // Disallow accessor properties.
327 if (desc->isAccessorDescriptor()) {
328 JSAutoRealm ar(cx, wrapperGlobal);
329 JS_MarkCrossZoneId(cx, id);
330 return ReportWrapperDenial(cx, id, WrapperDenialForXray,
331 "property has accessor");
332 }
333
334 // Apply extra scrutiny to objects.
335 if (desc->value().isObject()) {
336 RootedObject propObj(cx, js::UncheckedUnwrap(&desc->value().toObject()));
337 JSAutoRealm ar(cx, propObj);
338
339 // Disallow non-subsumed objects.
340 if (!AccessCheck::subsumes(target, propObj)) {
341 JSAutoRealm ar(cx, wrapperGlobal);
342 JS_MarkCrossZoneId(cx, id);
343 return ReportWrapperDenial(cx, id, WrapperDenialForXray,
344 "value not same-origin with target");
345 }
346
347 // Disallow non-Xrayable objects.
348 XrayType xrayType = GetXrayType(propObj);
349 if (xrayType == NotXray || xrayType == XrayForOpaqueObject) {
350 JSAutoRealm ar(cx, wrapperGlobal);
351 JS_MarkCrossZoneId(cx, id);
352 return ReportWrapperDenial(cx, id, WrapperDenialForXray,
353 "value not Xrayable");
354 }
355
356 // Disallow callables.
357 if (JS::IsCallable(propObj)) {
358 JSAutoRealm ar(cx, wrapperGlobal);
359 JS_MarkCrossZoneId(cx, id);
360 return ReportWrapperDenial(cx, id, WrapperDenialForXray,
361 "value is callable");
362 }
363 }
364
365 // Disallow any property that shadows something on its (Xrayed)
366 // prototype chain.
367 JSAutoRealm ar2(cx, wrapperGlobal);
368 JS_MarkCrossZoneId(cx, id);
369 RootedObject proto(cx);
370 bool foundOnProto = false;
371 if (!JS_GetPrototype(cx, wrapper, &proto) ||
372 (proto && !JS_HasPropertyById(cx, proto, id, &foundOnProto))) {
373 return false;
374 }
375 if (foundOnProto) {
376 return ReportWrapperDenial(
377 cx, id, WrapperDenialForXray,
378 "value shadows a property on the standard prototype");
379 }
380
381 // We made it! Assign over the descriptor, and don't forget to wrap.
382 outDesc.set(desc);
383 return true;
384 }
385
386 // Returns true on success (in the JSAPI sense), false on failure. If true is
387 // returned, desc.object() will indicate whether we actually resolved
388 // the property.
389 //
390 // id is the property id we're looking for.
391 // holder is the object to define the property on.
392 // fs is the relevant JSFunctionSpec*.
393 // ps is the relevant JSPropertySpec*.
394 // desc is the descriptor we're resolving into.
TryResolvePropertyFromSpecs(JSContext * cx,HandleId id,HandleObject holder,const JSFunctionSpec * fs,const JSPropertySpec * ps,MutableHandle<Maybe<PropertyDescriptor>> desc)395 static bool TryResolvePropertyFromSpecs(
396 JSContext* cx, HandleId id, HandleObject holder, const JSFunctionSpec* fs,
397 const JSPropertySpec* ps, MutableHandle<Maybe<PropertyDescriptor>> desc) {
398 // Scan through the functions.
399 const JSFunctionSpec* fsMatch = nullptr;
400 for (; fs && fs->name; ++fs) {
401 if (PropertySpecNameEqualsId(fs->name, id)) {
402 fsMatch = fs;
403 break;
404 }
405 }
406 if (fsMatch) {
407 // Generate an Xrayed version of the method.
408 RootedFunction fun(cx, JS::NewFunctionFromSpec(cx, fsMatch, id));
409 if (!fun) {
410 return false;
411 }
412
413 // The generic Xray machinery only defines non-own properties of the target
414 // on the holder. This is broken, and will be fixed at some point, but for
415 // now we need to cache the value explicitly. See the corresponding call to
416 // JS_GetOwnPropertyDescriptorById at the top of
417 // JSXrayTraits::resolveOwnProperty.
418 RootedObject funObj(cx, JS_GetFunctionObject(fun));
419 return JS_DefinePropertyById(cx, holder, id, funObj, 0) &&
420 JS_GetOwnPropertyDescriptorById(cx, holder, id, desc);
421 }
422
423 // Scan through the properties.
424 const JSPropertySpec* psMatch = nullptr;
425 for (; ps && ps->name; ++ps) {
426 if (PropertySpecNameEqualsId(ps->name, id)) {
427 psMatch = ps;
428 break;
429 }
430 }
431 if (psMatch) {
432 // The generic Xray machinery only defines non-own properties on the holder.
433 // This is broken, and will be fixed at some point, but for now we need to
434 // cache the value explicitly. See the corresponding call to
435 // JS_GetPropertyById at the top of JSXrayTraits::resolveOwnProperty.
436 //
437 // Note also that the public-facing API here doesn't give us a way to
438 // pass along JITInfo. It's probably ok though, since Xrays are already
439 // pretty slow.
440
441 unsigned attrs = psMatch->attributes();
442 if (psMatch->isAccessor()) {
443 if (psMatch->isSelfHosted()) {
444 JSFunction* getterFun = JS::GetSelfHostedFunction(
445 cx, psMatch->u.accessors.getter.selfHosted.funname, id, 0);
446 if (!getterFun) {
447 return false;
448 }
449 RootedObject getterObj(cx, JS_GetFunctionObject(getterFun));
450 RootedObject setterObj(cx);
451 if (psMatch->u.accessors.setter.selfHosted.funname) {
452 JSFunction* setterFun = JS::GetSelfHostedFunction(
453 cx, psMatch->u.accessors.setter.selfHosted.funname, id, 0);
454 if (!setterFun) {
455 return false;
456 }
457 setterObj = JS_GetFunctionObject(setterFun);
458 }
459 if (!JS_DefinePropertyById(cx, holder, id, getterObj, setterObj,
460 attrs)) {
461 return false;
462 }
463 } else {
464 if (!JS_DefinePropertyById(
465 cx, holder, id, psMatch->u.accessors.getter.native.op,
466 psMatch->u.accessors.setter.native.op, attrs)) {
467 return false;
468 }
469 }
470 } else {
471 RootedValue v(cx);
472 if (!psMatch->getValue(cx, &v)) {
473 return false;
474 }
475 if (!JS_DefinePropertyById(cx, holder, id, v, attrs)) {
476 return false;
477 }
478 }
479
480 return JS_GetOwnPropertyDescriptorById(cx, holder, id, desc);
481 }
482
483 return true;
484 }
485
ShouldResolvePrototypeProperty(JSProtoKey key)486 static bool ShouldResolvePrototypeProperty(JSProtoKey key) {
487 // Proxy constructors have no "prototype" property.
488 return key != JSProto_Proxy;
489 }
490
ShouldResolveStaticProperties(JSProtoKey key)491 static bool ShouldResolveStaticProperties(JSProtoKey key) {
492 if (!IsJSXraySupported(key)) {
493 // If we can't Xray this ES class, then we can't resolve statics on it.
494 return false;
495 }
496
497 // Don't try to resolve static properties on RegExp, because they
498 // have issues. In particular, some of them grab state off the
499 // global of the RegExp constructor that describes the last regexp
500 // evaluation in that global, which is not a useful thing to do
501 // over Xrays.
502 return key != JSProto_RegExp;
503 }
504
resolveOwnProperty(JSContext * cx,HandleObject wrapper,HandleObject target,HandleObject holder,HandleId id,MutableHandle<Maybe<PropertyDescriptor>> desc)505 bool JSXrayTraits::resolveOwnProperty(
506 JSContext* cx, HandleObject wrapper, HandleObject target,
507 HandleObject holder, HandleId id,
508 MutableHandle<Maybe<PropertyDescriptor>> desc) {
509 // Call the common code.
510 bool ok =
511 XrayTraits::resolveOwnProperty(cx, wrapper, target, holder, id, desc);
512 if (!ok || desc.isSome()) {
513 return ok;
514 }
515
516 // The non-HasPrototypes semantics implemented by traditional Xrays are kind
517 // of broken with respect to |own|-ness and the holder. The common code
518 // muddles through by only checking the holder for non-|own| lookups, but
519 // that doesn't work for us. So we do an explicit holder check here, and hope
520 // that this mess gets fixed up soon.
521 if (!JS_GetOwnPropertyDescriptorById(cx, holder, id, desc)) {
522 return false;
523 }
524 if (desc.isSome()) {
525 return true;
526 }
527
528 JSProtoKey key = getProtoKey(holder);
529 if (!isPrototype(holder)) {
530 // For Object and Array instances, we expose some properties from the
531 // underlying object, but only after filtering them carefully.
532 //
533 // Note that, as far as JS observables go, Arrays are just Objects with
534 // a different prototype and a magic (own, non-configurable) |.length| that
535 // serves as a non-tight upper bound on |own| indexed properties. So while
536 // it's tempting to try to impose some sort of structure on what Arrays
537 // "should" look like over Xrays, the underlying object is squishy enough
538 // that it makes sense to just treat them like Objects for Xray purposes.
539 if (key == JSProto_Object || key == JSProto_Array) {
540 return getOwnPropertyFromWrapperIfSafe(cx, wrapper, id, desc);
541 }
542 if (IsTypedArrayKey(key)) {
543 if (IsArrayIndex(GetArrayIndexFromId(id))) {
544 // WebExtensions can't use cloneInto(), so we just let them do
545 // the slow thing to maximize compatibility.
546 if (CompartmentPrivate::Get(CurrentGlobalOrNull(cx))
547 ->isWebExtensionContentScript) {
548 Rooted<Maybe<PropertyDescriptor>> innerDesc(cx);
549 {
550 JSAutoRealm ar(cx, target);
551 JS_MarkCrossZoneId(cx, id);
552 if (!JS_GetOwnPropertyDescriptorById(cx, target, id, &innerDesc)) {
553 return false;
554 }
555 }
556 if (innerDesc.isSome() && innerDesc->isDataDescriptor() &&
557 innerDesc->value().isNumber()) {
558 desc.set(innerDesc);
559 }
560 return true;
561 }
562 JS_ReportErrorASCII(
563 cx,
564 "Accessing TypedArray data over Xrays is slow, and forbidden "
565 "in order to encourage performant code. To copy TypedArrays "
566 "across origin boundaries, consider using "
567 "Components.utils.cloneInto().");
568 return false;
569 }
570 } else if (key == JSProto_Function) {
571 if (id == GetJSIDByIndex(cx, XPCJSContext::IDX_LENGTH)) {
572 uint16_t length;
573 RootedFunction fun(cx, JS_GetObjectFunction(target));
574 {
575 JSAutoRealm ar(cx, target);
576 if (!JS_GetFunctionLength(cx, fun, &length)) {
577 return false;
578 }
579 }
580 desc.set(Some(PropertyDescriptor::Data(NumberValue(length), {})));
581 return true;
582 }
583 if (id == GetJSIDByIndex(cx, XPCJSContext::IDX_NAME)) {
584 RootedString fname(cx, JS_GetFunctionId(JS_GetObjectFunction(target)));
585 if (fname) {
586 JS_MarkCrossZoneIdValue(cx, StringValue(fname));
587 }
588 desc.set(Some(PropertyDescriptor::Data(
589 fname ? StringValue(fname) : JS_GetEmptyStringValue(cx), {})));
590 } else {
591 // Look for various static properties/methods and the
592 // 'prototype' property.
593 JSProtoKey standardConstructor = constructorFor(holder);
594 if (standardConstructor != JSProto_Null) {
595 // Handle the 'prototype' property to make
596 // xrayedGlobal.StandardClass.prototype work.
597 if (id == GetJSIDByIndex(cx, XPCJSContext::IDX_PROTOTYPE) &&
598 ShouldResolvePrototypeProperty(standardConstructor)) {
599 RootedObject standardProto(cx);
600 {
601 JSAutoRealm ar(cx, target);
602 if (!JS_GetClassPrototype(cx, standardConstructor,
603 &standardProto)) {
604 return false;
605 }
606 MOZ_ASSERT(standardProto);
607 }
608
609 if (!JS_WrapObject(cx, &standardProto)) {
610 return false;
611 }
612 desc.set(Some(
613 PropertyDescriptor::Data(ObjectValue(*standardProto), {})));
614 return true;
615 }
616
617 if (ShouldResolveStaticProperties(standardConstructor)) {
618 const JSClass* clasp = js::ProtoKeyToClass(standardConstructor);
619 MOZ_ASSERT(clasp->specDefined());
620
621 if (!TryResolvePropertyFromSpecs(
622 cx, id, holder, clasp->specConstructorFunctions(),
623 clasp->specConstructorProperties(), desc)) {
624 return false;
625 }
626
627 if (desc.isSome()) {
628 return true;
629 }
630 }
631 }
632 }
633 } else if (IsErrorObjectKey(key)) {
634 // The useful state of error objects (except for .stack) is
635 // (unfortunately) represented as own data properties per-spec. This
636 // means that we can't have a a clean representation of the data
637 // (free from tampering) without doubling the slots of Error
638 // objects, which isn't great. So we forward these properties to the
639 // underlying object and then just censor any values with the wrong
640 // type. This limits the ability of content to do anything all that
641 // confusing.
642 bool isErrorIntProperty =
643 id == GetJSIDByIndex(cx, XPCJSContext::IDX_LINENUMBER) ||
644 id == GetJSIDByIndex(cx, XPCJSContext::IDX_COLUMNNUMBER);
645 bool isErrorStringProperty =
646 id == GetJSIDByIndex(cx, XPCJSContext::IDX_FILENAME) ||
647 id == GetJSIDByIndex(cx, XPCJSContext::IDX_MESSAGE);
648 if (isErrorIntProperty || isErrorStringProperty) {
649 RootedObject waiver(cx, wrapper);
650 if (!WrapperFactory::WaiveXrayAndWrap(cx, &waiver)) {
651 return false;
652 }
653 if (!JS_GetOwnPropertyDescriptorById(cx, waiver, id, desc)) {
654 return false;
655 }
656 if (desc.isSome()) {
657 // Make sure the property has the expected type.
658 if (!desc->isDataDescriptor() ||
659 (isErrorIntProperty && !desc->value().isInt32()) ||
660 (isErrorStringProperty && !desc->value().isString())) {
661 desc.reset();
662 }
663 }
664 return true;
665 }
666
667 #if defined(NIGHTLY_BUILD)
668 // The optional .cause property can have any value.
669 if (id == GetJSIDByIndex(cx, XPCJSContext::IDX_CAUSE)) {
670 return getOwnPropertyFromWrapperIfSafe(cx, wrapper, id, desc);
671 }
672 #endif
673
674 if (key == JSProto_AggregateError &&
675 id == GetJSIDByIndex(cx, XPCJSContext::IDX_ERRORS)) {
676 return getOwnPropertyFromWrapperIfSafe(cx, wrapper, id, desc);
677 }
678 } else if (key == JSProto_RegExp) {
679 if (id == GetJSIDByIndex(cx, XPCJSContext::IDX_LASTINDEX)) {
680 return getOwnPropertyFromWrapperIfSafe(cx, wrapper, id, desc);
681 }
682 }
683
684 // The rest of this function applies only to prototypes.
685 return true;
686 }
687
688 // Handle the 'constructor' property.
689 if (id == GetJSIDByIndex(cx, XPCJSContext::IDX_CONSTRUCTOR)) {
690 RootedObject constructor(cx);
691 {
692 JSAutoRealm ar(cx, target);
693 if (!JS_GetClassObject(cx, key, &constructor)) {
694 return false;
695 }
696 }
697 if (!JS_WrapObject(cx, &constructor)) {
698 return false;
699 }
700 desc.set(Some(PropertyDescriptor::Data(
701 ObjectValue(*constructor),
702 {PropertyAttribute::Configurable, PropertyAttribute::Writable})));
703 return true;
704 }
705
706 if (ShouldIgnorePropertyDefinition(cx, key, id)) {
707 MOZ_ASSERT(desc.isNothing());
708 return true;
709 }
710
711 // Grab the JSClass. We require all Xrayable classes to have a ClassSpec.
712 const JSClass* clasp = JS::GetClass(target);
713 MOZ_ASSERT(clasp->specDefined());
714
715 // Indexed array properties are handled above, so we can just work with the
716 // class spec here.
717 return TryResolvePropertyFromSpecs(cx, id, holder,
718 clasp->specPrototypeFunctions(),
719 clasp->specPrototypeProperties(), desc);
720 }
721
delete_(JSContext * cx,HandleObject wrapper,HandleId id,ObjectOpResult & result)722 bool JSXrayTraits::delete_(JSContext* cx, HandleObject wrapper, HandleId id,
723 ObjectOpResult& result) {
724 MOZ_ASSERT(js::IsObjectInContextCompartment(wrapper, cx));
725
726 RootedObject holder(cx, ensureHolder(cx, wrapper));
727 if (!holder) {
728 return false;
729 }
730
731 // If we're using Object Xrays, we allow callers to attempt to delete any
732 // property from the underlying object that they are able to resolve. Note
733 // that this deleting may fail if the property is non-configurable.
734 JSProtoKey key = getProtoKey(holder);
735 bool isObjectOrArrayInstance =
736 (key == JSProto_Object || key == JSProto_Array) && !isPrototype(holder);
737 if (isObjectOrArrayInstance) {
738 RootedObject wrapperGlobal(cx, JS::CurrentGlobalOrNull(cx));
739 RootedObject target(cx, getTargetObject(wrapper));
740 JSAutoRealm ar(cx, target);
741 JS_MarkCrossZoneId(cx, id);
742 Rooted<Maybe<PropertyDescriptor>> desc(cx);
743 if (!getOwnPropertyFromTargetIfSafe(cx, target, wrapper, wrapperGlobal, id,
744 &desc)) {
745 return false;
746 }
747 if (desc.isSome()) {
748 return JS_DeletePropertyById(cx, target, id, result);
749 }
750 }
751 return result.succeed();
752 }
753
defineProperty(JSContext * cx,HandleObject wrapper,HandleId id,Handle<PropertyDescriptor> desc,Handle<Maybe<PropertyDescriptor>> existingDesc,Handle<JSObject * > existingHolder,ObjectOpResult & result,bool * defined)754 bool JSXrayTraits::defineProperty(
755 JSContext* cx, HandleObject wrapper, HandleId id,
756 Handle<PropertyDescriptor> desc,
757 Handle<Maybe<PropertyDescriptor>> existingDesc,
758 Handle<JSObject*> existingHolder, ObjectOpResult& result, bool* defined) {
759 *defined = false;
760 RootedObject holder(cx, ensureHolder(cx, wrapper));
761 if (!holder) {
762 return false;
763 }
764
765 // Object and Array instances are special. For those cases, we forward
766 // property definitions to the underlying object if the following
767 // conditions are met:
768 // * The property being defined is a value-prop.
769 // * The property being defined is either a primitive or subsumed by the
770 // target.
771 // * As seen from the Xray, any existing property that we would overwrite
772 // is an |own| value-prop.
773 //
774 // To avoid confusion, we disallow expandos on Object and Array instances, and
775 // therefore raise an exception here if the above conditions aren't met.
776 JSProtoKey key = getProtoKey(holder);
777 bool isInstance = !isPrototype(holder);
778 bool isObjectOrArray = (key == JSProto_Object || key == JSProto_Array);
779 if (isObjectOrArray && isInstance) {
780 RootedObject target(cx, getTargetObject(wrapper));
781 if (desc.isAccessorDescriptor()) {
782 JS_ReportErrorASCII(cx,
783 "Not allowed to define accessor property on [Object] "
784 "or [Array] XrayWrapper");
785 return false;
786 }
787 if (desc.value().isObject() &&
788 !AccessCheck::subsumes(target,
789 js::UncheckedUnwrap(&desc.value().toObject()))) {
790 JS_ReportErrorASCII(cx,
791 "Not allowed to define cross-origin object as "
792 "property on [Object] or [Array] XrayWrapper");
793 return false;
794 }
795 if (existingDesc.isSome()) {
796 if (existingDesc->isAccessorDescriptor()) {
797 JS_ReportErrorASCII(cx,
798 "Not allowed to overwrite accessor property on "
799 "[Object] or [Array] XrayWrapper");
800 return false;
801 }
802 if (existingHolder != wrapper) {
803 JS_ReportErrorASCII(cx,
804 "Not allowed to shadow non-own Xray-resolved "
805 "property on [Object] or [Array] XrayWrapper");
806 return false;
807 }
808 }
809
810 Rooted<PropertyDescriptor> wrappedDesc(cx, desc);
811 JSAutoRealm ar(cx, target);
812 JS_MarkCrossZoneId(cx, id);
813 if (!JS_WrapPropertyDescriptor(cx, &wrappedDesc) ||
814 !JS_DefinePropertyById(cx, target, id, wrappedDesc, result)) {
815 return false;
816 }
817 *defined = true;
818 return true;
819 }
820
821 // For WebExtensions content scripts, we forward the definition of indexed
822 // properties. By validating that the key and value are both numbers, we can
823 // avoid doing any wrapping.
824 if (isInstance && IsTypedArrayKey(key) &&
825 CompartmentPrivate::Get(JS::CurrentGlobalOrNull(cx))
826 ->isWebExtensionContentScript &&
827 desc.isDataDescriptor() &&
828 (desc.value().isNumber() || desc.value().isUndefined()) &&
829 IsArrayIndex(GetArrayIndexFromId(id))) {
830 RootedObject target(cx, getTargetObject(wrapper));
831 JSAutoRealm ar(cx, target);
832 JS_MarkCrossZoneId(cx, id);
833 if (!JS_DefinePropertyById(cx, target, id, desc, result)) {
834 return false;
835 }
836 *defined = true;
837 return true;
838 }
839
840 return true;
841 }
842
MaybeAppend(jsid id,unsigned flags,MutableHandleIdVector props)843 static bool MaybeAppend(jsid id, unsigned flags, MutableHandleIdVector props) {
844 MOZ_ASSERT(!(flags & JSITER_SYMBOLSONLY));
845 if (!(flags & JSITER_SYMBOLS) && id.isSymbol()) {
846 return true;
847 }
848 return props.append(id);
849 }
850
851 // Append the names from the given function and property specs to props.
AppendNamesFromFunctionAndPropertySpecs(JSContext * cx,JSProtoKey key,const JSFunctionSpec * fs,const JSPropertySpec * ps,unsigned flags,MutableHandleIdVector props)852 static bool AppendNamesFromFunctionAndPropertySpecs(
853 JSContext* cx, JSProtoKey key, const JSFunctionSpec* fs,
854 const JSPropertySpec* ps, unsigned flags, MutableHandleIdVector props) {
855 // Convert the method and property names to jsids and pass them to the caller.
856 for (; fs && fs->name; ++fs) {
857 jsid id;
858 if (!PropertySpecNameToPermanentId(cx, fs->name, &id)) {
859 return false;
860 }
861 if (!js::ShouldIgnorePropertyDefinition(cx, key, id)) {
862 if (!MaybeAppend(id, flags, props)) {
863 return false;
864 }
865 }
866 }
867 for (; ps && ps->name; ++ps) {
868 jsid id;
869 if (!PropertySpecNameToPermanentId(cx, ps->name, &id)) {
870 return false;
871 }
872 if (!js::ShouldIgnorePropertyDefinition(cx, key, id)) {
873 if (!MaybeAppend(id, flags, props)) {
874 return false;
875 }
876 }
877 }
878
879 return true;
880 }
881
enumerateNames(JSContext * cx,HandleObject wrapper,unsigned flags,MutableHandleIdVector props)882 bool JSXrayTraits::enumerateNames(JSContext* cx, HandleObject wrapper,
883 unsigned flags, MutableHandleIdVector props) {
884 MOZ_ASSERT(js::IsObjectInContextCompartment(wrapper, cx));
885
886 RootedObject target(cx, getTargetObject(wrapper));
887 RootedObject holder(cx, ensureHolder(cx, wrapper));
888 if (!holder) {
889 return false;
890 }
891
892 JSProtoKey key = getProtoKey(holder);
893 if (!isPrototype(holder)) {
894 // For Object and Array instances, we expose some properties from the
895 // underlying object, but only after filtering them carefully.
896 if (key == JSProto_Object || key == JSProto_Array) {
897 MOZ_ASSERT(props.empty());
898 RootedObject wrapperGlobal(cx, JS::CurrentGlobalOrNull(cx));
899 {
900 JSAutoRealm ar(cx, target);
901 RootedIdVector targetProps(cx);
902 if (!js::GetPropertyKeys(cx, target, flags | JSITER_OWNONLY,
903 &targetProps)) {
904 return false;
905 }
906 // Loop over the properties, and only pass along the ones that
907 // we determine to be safe.
908 if (!props.reserve(targetProps.length())) {
909 return false;
910 }
911 for (size_t i = 0; i < targetProps.length(); ++i) {
912 Rooted<Maybe<PropertyDescriptor>> desc(cx);
913 RootedId id(cx, targetProps[i]);
914 if (!getOwnPropertyFromTargetIfSafe(cx, target, wrapper,
915 wrapperGlobal, id, &desc)) {
916 return false;
917 }
918 if (desc.isSome()) {
919 props.infallibleAppend(id);
920 }
921 }
922 }
923 for (size_t i = 0; i < props.length(); ++i) {
924 JS_MarkCrossZoneId(cx, props[i]);
925 }
926 return true;
927 }
928 if (IsTypedArrayKey(key)) {
929 size_t length = JS_GetTypedArrayLength(target);
930 // TypedArrays enumerate every indexed property in range, but
931 // |length| is a getter that lives on the proto, like it should be.
932
933 // Fail early if the typed array is enormous, because this will be very
934 // slow and will likely report OOM. This also means we don't need to
935 // handle indices greater than JSID_INT_MAX in the loop below.
936 static_assert(JSID_INT_MAX >= INT32_MAX);
937 if (length > INT32_MAX) {
938 JS_ReportOutOfMemory(cx);
939 return false;
940 }
941
942 if (!props.reserve(length)) {
943 return false;
944 }
945 for (int32_t i = 0; i < int32_t(length); ++i) {
946 props.infallibleAppend(INT_TO_JSID(i));
947 }
948 } else if (key == JSProto_Function) {
949 if (!props.append(GetJSIDByIndex(cx, XPCJSContext::IDX_LENGTH))) {
950 return false;
951 }
952 if (!props.append(GetJSIDByIndex(cx, XPCJSContext::IDX_NAME))) {
953 return false;
954 }
955 // Handle the .prototype property and static properties on standard
956 // constructors.
957 JSProtoKey standardConstructor = constructorFor(holder);
958 if (standardConstructor != JSProto_Null) {
959 if (ShouldResolvePrototypeProperty(standardConstructor)) {
960 if (!props.append(GetJSIDByIndex(cx, XPCJSContext::IDX_PROTOTYPE))) {
961 return false;
962 }
963 }
964
965 if (ShouldResolveStaticProperties(standardConstructor)) {
966 const JSClass* clasp = js::ProtoKeyToClass(standardConstructor);
967 MOZ_ASSERT(clasp->specDefined());
968
969 if (!AppendNamesFromFunctionAndPropertySpecs(
970 cx, key, clasp->specConstructorFunctions(),
971 clasp->specConstructorProperties(), flags, props)) {
972 return false;
973 }
974 }
975 }
976 } else if (IsErrorObjectKey(key)) {
977 if (!props.append(GetJSIDByIndex(cx, XPCJSContext::IDX_FILENAME)) ||
978 !props.append(GetJSIDByIndex(cx, XPCJSContext::IDX_LINENUMBER)) ||
979 !props.append(GetJSIDByIndex(cx, XPCJSContext::IDX_COLUMNNUMBER)) ||
980 !props.append(GetJSIDByIndex(cx, XPCJSContext::IDX_STACK)) ||
981 !props.append(GetJSIDByIndex(cx, XPCJSContext::IDX_MESSAGE))) {
982 return false;
983 }
984 } else if (key == JSProto_RegExp) {
985 if (!props.append(GetJSIDByIndex(cx, XPCJSContext::IDX_LASTINDEX))) {
986 return false;
987 }
988 }
989
990 // The rest of this function applies only to prototypes.
991 return true;
992 }
993
994 // Add the 'constructor' property.
995 if (!props.append(GetJSIDByIndex(cx, XPCJSContext::IDX_CONSTRUCTOR))) {
996 return false;
997 }
998
999 // Grab the JSClass. We require all Xrayable classes to have a ClassSpec.
1000 const JSClass* clasp = JS::GetClass(target);
1001 MOZ_ASSERT(clasp->specDefined());
1002
1003 return AppendNamesFromFunctionAndPropertySpecs(
1004 cx, key, clasp->specPrototypeFunctions(),
1005 clasp->specPrototypeProperties(), flags, props);
1006 }
1007
construct(JSContext * cx,HandleObject wrapper,const JS::CallArgs & args,const js::Wrapper & baseInstance)1008 bool JSXrayTraits::construct(JSContext* cx, HandleObject wrapper,
1009 const JS::CallArgs& args,
1010 const js::Wrapper& baseInstance) {
1011 JSXrayTraits& self = JSXrayTraits::singleton;
1012 JS::RootedObject holder(cx, self.ensureHolder(cx, wrapper));
1013 if (!holder) {
1014 return false;
1015 }
1016
1017 if (xpc::JSXrayTraits::getProtoKey(holder) == JSProto_Function) {
1018 JSProtoKey standardConstructor = constructorFor(holder);
1019 if (standardConstructor == JSProto_Null) {
1020 return baseInstance.construct(cx, wrapper, args);
1021 }
1022
1023 const JSClass* clasp = js::ProtoKeyToClass(standardConstructor);
1024 MOZ_ASSERT(clasp);
1025 if (!(clasp->flags & JSCLASS_HAS_XRAYED_CONSTRUCTOR)) {
1026 return baseInstance.construct(cx, wrapper, args);
1027 }
1028
1029 // If the JSCLASS_HAS_XRAYED_CONSTRUCTOR flag is set on the Class,
1030 // we don't use the constructor at hand. Instead, we retrieve the
1031 // equivalent standard constructor in the xray compartment and run
1032 // it in that compartment. The newTarget isn't unwrapped, and the
1033 // constructor has to be able to detect and handle this situation.
1034 // See the comments in js/public/Class.h and PromiseConstructor for
1035 // details and an example.
1036 RootedObject ctor(cx);
1037 if (!JS_GetClassObject(cx, standardConstructor, &ctor)) {
1038 return false;
1039 }
1040
1041 RootedValue ctorVal(cx, ObjectValue(*ctor));
1042 HandleValueArray vals(args);
1043 RootedObject result(cx);
1044 if (!JS::Construct(cx, ctorVal, wrapper, vals, &result)) {
1045 return false;
1046 }
1047 AssertSameCompartment(cx, result);
1048 args.rval().setObject(*result);
1049 return true;
1050 }
1051
1052 JS::RootedValue v(cx, JS::ObjectValue(*wrapper));
1053 js::ReportIsNotFunction(cx, v);
1054 return false;
1055 }
1056
createHolder(JSContext * cx,JSObject * wrapper)1057 JSObject* JSXrayTraits::createHolder(JSContext* cx, JSObject* wrapper) {
1058 RootedObject target(cx, getTargetObject(wrapper));
1059 RootedObject holder(cx,
1060 JS_NewObjectWithGivenProto(cx, &HolderClass, nullptr));
1061 if (!holder) {
1062 return nullptr;
1063 }
1064
1065 // Compute information about the target.
1066 bool isPrototype = false;
1067 JSProtoKey key = IdentifyStandardInstance(target);
1068 if (key == JSProto_Null) {
1069 isPrototype = true;
1070 key = IdentifyStandardPrototype(target);
1071 }
1072 MOZ_ASSERT(key != JSProto_Null);
1073
1074 // Special case: pretend Arguments objects are arrays for Xrays.
1075 //
1076 // Arguments objects are strange beasts - they inherit Object.prototype,
1077 // and implement iteration by defining an |own| property for
1078 // Symbol.iterator. Since this value is callable, Array/Object Xrays will
1079 // filter it out, causing the Xray view to be non-iterable, which in turn
1080 // breaks consumers.
1081 //
1082 // We can't trust the iterator value from the content compartment,
1083 // but the generic one on Array.prototype works well enough. So we force
1084 // the Xray view of Arguments objects to inherit Array.prototype, which
1085 // in turn allows iteration via the inherited
1086 // Array.prototype[Symbol.iterator]. This doesn't emulate any of the weird
1087 // semantics of Arguments iterators, but is probably good enough.
1088 //
1089 // Note that there are various Xray traps that do other special behavior for
1090 // JSProto_Array, but they also provide that special behavior for
1091 // JSProto_Object, and since Arguments would otherwise get JSProto_Object,
1092 // this does not cause any behavior change at those sites.
1093 if (key == JSProto_Object && js::IsArgumentsObject(target)) {
1094 key = JSProto_Array;
1095 }
1096
1097 // Store it on the holder.
1098 RootedValue v(cx);
1099 v.setNumber(static_cast<uint32_t>(key));
1100 JS::SetReservedSlot(holder, SLOT_PROTOKEY, v);
1101 v.setBoolean(isPrototype);
1102 JS::SetReservedSlot(holder, SLOT_ISPROTOTYPE, v);
1103
1104 // If this is a function, also compute whether it serves as a constructor
1105 // for a standard class.
1106 if (key == JSProto_Function) {
1107 v.setNumber(static_cast<uint32_t>(IdentifyStandardConstructor(target)));
1108 JS::SetReservedSlot(holder, SLOT_CONSTRUCTOR_FOR, v);
1109 }
1110
1111 return holder;
1112 }
1113
1114 DOMXrayTraits DOMXrayTraits::singleton;
1115 JSXrayTraits JSXrayTraits::singleton;
1116 OpaqueXrayTraits OpaqueXrayTraits::singleton;
1117
GetXrayTraits(JSObject * obj)1118 XrayTraits* GetXrayTraits(JSObject* obj) {
1119 switch (GetXrayType(obj)) {
1120 case XrayForDOMObject:
1121 return &DOMXrayTraits::singleton;
1122 case XrayForJSObject:
1123 return &JSXrayTraits::singleton;
1124 case XrayForOpaqueObject:
1125 return &OpaqueXrayTraits::singleton;
1126 default:
1127 return nullptr;
1128 }
1129 }
1130
1131 /*
1132 * Xray expando handling.
1133 *
1134 * We hang expandos for Xray wrappers off a reserved slot on the target object
1135 * so that same-origin compartments can share expandos for a given object. We
1136 * have a linked list of expando objects, one per origin. The properties on
1137 * these objects are generally wrappers pointing back to the compartment that
1138 * applied them.
1139 *
1140 * The expando objects should _never_ be exposed to script. The fact that they
1141 * live in the target compartment is a detail of the implementation, and does
1142 * not imply that code in the target compartment should be allowed to inspect
1143 * them. They are private to the origin that placed them.
1144 */
1145
1146 // Certain compartments do not share expandos with other compartments. Xrays in
1147 // these compartments cache expandos on the wrapper's holder, as there is only
1148 // one such wrapper which can create or access the expando. This allows for
1149 // faster access to the expando, including through JIT inline caches.
CompartmentHasExclusiveExpandos(JSObject * obj)1150 static inline bool CompartmentHasExclusiveExpandos(JSObject* obj) {
1151 JS::Compartment* comp = JS::GetCompartment(obj);
1152 CompartmentPrivate* priv = CompartmentPrivate::Get(comp);
1153 return priv && priv->hasExclusiveExpandos;
1154 }
1155
1156 static inline JSObject* GetCachedXrayExpando(JSObject* wrapper);
1157
1158 static inline void SetCachedXrayExpando(JSObject* holder,
1159 JSObject* expandoWrapper);
1160
WrapperPrincipal(JSObject * obj)1161 static nsIPrincipal* WrapperPrincipal(JSObject* obj) {
1162 // Use the principal stored in CompartmentOriginInfo. That works because
1163 // consumers are only interested in the origin-ignoring-document.domain.
1164 // See expandoObjectMatchesConsumer.
1165 MOZ_ASSERT(IsXrayWrapper(obj));
1166 JS::Compartment* comp = JS::GetCompartment(obj);
1167 CompartmentPrivate* priv = CompartmentPrivate::Get(comp);
1168 return priv->originInfo.GetPrincipalIgnoringDocumentDomain();
1169 }
1170
GetExpandoObjectPrincipal(JSObject * expandoObject)1171 static nsIPrincipal* GetExpandoObjectPrincipal(JSObject* expandoObject) {
1172 Value v = JS::GetReservedSlot(expandoObject, JSSLOT_EXPANDO_ORIGIN);
1173 return static_cast<nsIPrincipal*>(v.toPrivate());
1174 }
1175
ExpandoObjectFinalize(JSFreeOp * fop,JSObject * obj)1176 static void ExpandoObjectFinalize(JSFreeOp* fop, JSObject* obj) {
1177 // Release the principal.
1178 nsIPrincipal* principal = GetExpandoObjectPrincipal(obj);
1179 NS_RELEASE(principal);
1180 }
1181
1182 const JSClassOps XrayExpandoObjectClassOps = {
1183 nullptr, // addProperty
1184 nullptr, // delProperty
1185 nullptr, // enumerate
1186 nullptr, // newEnumerate
1187 nullptr, // resolve
1188 nullptr, // mayResolve
1189 ExpandoObjectFinalize, // finalize
1190 nullptr, // call
1191 nullptr, // hasInstance
1192 nullptr, // construct
1193 nullptr, // trace
1194 };
1195
expandoObjectMatchesConsumer(JSContext * cx,HandleObject expandoObject,nsIPrincipal * consumerOrigin)1196 bool XrayTraits::expandoObjectMatchesConsumer(JSContext* cx,
1197 HandleObject expandoObject,
1198 nsIPrincipal* consumerOrigin) {
1199 MOZ_ASSERT(js::IsObjectInContextCompartment(expandoObject, cx));
1200
1201 // First, compare the principals.
1202 nsIPrincipal* o = GetExpandoObjectPrincipal(expandoObject);
1203 // Note that it's very important here to ignore document.domain. We
1204 // pull the principal for the expando object off of the first consumer
1205 // for a given origin, and freely share the expandos amongst multiple
1206 // same-origin consumers afterwards. However, this means that we have
1207 // no way to know whether _all_ consumers have opted in to collaboration
1208 // by explicitly setting document.domain. So we just mandate that expando
1209 // sharing is unaffected by it.
1210 if (!consumerOrigin->Equals(o)) {
1211 return false;
1212 }
1213
1214 // Certain globals exclusively own the associated expandos, in which case
1215 // the caller should have used the cached expando on the wrapper instead.
1216 JSObject* owner = JS::GetReservedSlot(expandoObject,
1217 JSSLOT_EXPANDO_EXCLUSIVE_WRAPPER_HOLDER)
1218 .toObjectOrNull();
1219 return owner == nullptr;
1220 }
1221
getExpandoObjectInternal(JSContext * cx,JSObject * expandoChain,HandleObject exclusiveWrapper,nsIPrincipal * origin,MutableHandleObject expandoObject)1222 bool XrayTraits::getExpandoObjectInternal(JSContext* cx, JSObject* expandoChain,
1223 HandleObject exclusiveWrapper,
1224 nsIPrincipal* origin,
1225 MutableHandleObject expandoObject) {
1226 MOZ_ASSERT(!JS_IsExceptionPending(cx));
1227 expandoObject.set(nullptr);
1228
1229 // Use the cached expando if this wrapper has exclusive access to it.
1230 if (exclusiveWrapper) {
1231 JSObject* expandoWrapper = GetCachedXrayExpando(exclusiveWrapper);
1232 expandoObject.set(expandoWrapper ? UncheckedUnwrap(expandoWrapper)
1233 : nullptr);
1234 #ifdef DEBUG
1235 // Make sure the expando we found is on the target's chain. While we
1236 // don't use this chain to look up expandos for the wrapper,
1237 // the expando still needs to be on the chain to keep the wrapper and
1238 // expando alive.
1239 if (expandoObject) {
1240 JSObject* head = expandoChain;
1241 while (head && head != expandoObject) {
1242 head = JS::GetReservedSlot(head, JSSLOT_EXPANDO_NEXT).toObjectOrNull();
1243 }
1244 MOZ_ASSERT(head == expandoObject);
1245 }
1246 #endif
1247 return true;
1248 }
1249
1250 // The expando object lives in the compartment of the target, so all our
1251 // work needs to happen there.
1252 RootedObject head(cx, expandoChain);
1253 JSAutoRealm ar(cx, head);
1254
1255 // Iterate through the chain, looking for a same-origin object.
1256 while (head) {
1257 if (expandoObjectMatchesConsumer(cx, head, origin)) {
1258 expandoObject.set(head);
1259 return true;
1260 }
1261 head = JS::GetReservedSlot(head, JSSLOT_EXPANDO_NEXT).toObjectOrNull();
1262 }
1263
1264 // Not found.
1265 return true;
1266 }
1267
getExpandoObject(JSContext * cx,HandleObject target,HandleObject consumer,MutableHandleObject expandoObject)1268 bool XrayTraits::getExpandoObject(JSContext* cx, HandleObject target,
1269 HandleObject consumer,
1270 MutableHandleObject expandoObject) {
1271 // Return early if no expando object has ever been attached, which is
1272 // usually the case.
1273 JSObject* chain = getExpandoChain(target);
1274 if (!chain) {
1275 return true;
1276 }
1277
1278 bool isExclusive = CompartmentHasExclusiveExpandos(consumer);
1279 return getExpandoObjectInternal(cx, chain, isExclusive ? consumer : nullptr,
1280 WrapperPrincipal(consumer), expandoObject);
1281 }
1282
1283 // Wrappers which have exclusive access to the expando on their target object
1284 // need to be kept alive as long as the target object exists. This is done by
1285 // keeping the expando in the expando chain on the target (even though it will
1286 // not be used while looking up the expando for the wrapper), and keeping a
1287 // strong reference from that expando to the wrapper itself, via the
1288 // JSSLOT_EXPANDO_EXCLUSIVE_WRAPPER_HOLDER reserved slot. This slot does not
1289 // point to the wrapper itself, because it is a cross compartment edge and we
1290 // can't create a wrapper for a wrapper. Instead, the slot points to an
1291 // instance of the holder class below in the wrapper's compartment, and the
1292 // wrapper is held via this holder object's reserved slot.
1293 static const JSClass gWrapperHolderClass = {"XrayExpandoWrapperHolder",
1294 JSCLASS_HAS_RESERVED_SLOTS(1)};
1295 static const size_t JSSLOT_WRAPPER_HOLDER_CONTENTS = 0;
1296
attachExpandoObject(JSContext * cx,HandleObject target,HandleObject exclusiveWrapper,HandleObject exclusiveWrapperGlobal,nsIPrincipal * origin)1297 JSObject* XrayTraits::attachExpandoObject(JSContext* cx, HandleObject target,
1298 HandleObject exclusiveWrapper,
1299 HandleObject exclusiveWrapperGlobal,
1300 nsIPrincipal* origin) {
1301 // Make sure the compartments are sane.
1302 MOZ_ASSERT(js::IsObjectInContextCompartment(target, cx));
1303 if (exclusiveWrapper) {
1304 MOZ_ASSERT(!js::IsObjectInContextCompartment(exclusiveWrapper, cx));
1305 MOZ_ASSERT(JS_IsGlobalObject(exclusiveWrapperGlobal));
1306 js::AssertSameCompartment(exclusiveWrapper, exclusiveWrapperGlobal);
1307 }
1308
1309 // No duplicates allowed.
1310 #ifdef DEBUG
1311 {
1312 JSObject* chain = getExpandoChain(target);
1313 if (chain) {
1314 RootedObject existingExpandoObject(cx);
1315 if (getExpandoObjectInternal(cx, chain, exclusiveWrapper, origin,
1316 &existingExpandoObject)) {
1317 MOZ_ASSERT(!existingExpandoObject);
1318 } else {
1319 JS_ClearPendingException(cx);
1320 }
1321 }
1322 }
1323 #endif
1324
1325 // Create the expando object.
1326 const JSClass* expandoClass = getExpandoClass(cx, target);
1327 MOZ_ASSERT(!strcmp(expandoClass->name, "XrayExpandoObject"));
1328 RootedObject expandoObject(
1329 cx, JS_NewObjectWithGivenProto(cx, expandoClass, nullptr));
1330 if (!expandoObject) {
1331 return nullptr;
1332 }
1333
1334 // AddRef and store the principal.
1335 NS_ADDREF(origin);
1336 JS_SetReservedSlot(expandoObject, JSSLOT_EXPANDO_ORIGIN,
1337 JS::PrivateValue(origin));
1338
1339 // Note the exclusive wrapper, if there is one.
1340 RootedObject wrapperHolder(cx);
1341 if (exclusiveWrapper) {
1342 JSAutoRealm ar(cx, exclusiveWrapperGlobal);
1343 wrapperHolder =
1344 JS_NewObjectWithGivenProto(cx, &gWrapperHolderClass, nullptr);
1345 if (!wrapperHolder) {
1346 return nullptr;
1347 }
1348 JS_SetReservedSlot(wrapperHolder, JSSLOT_WRAPPER_HOLDER_CONTENTS,
1349 ObjectValue(*exclusiveWrapper));
1350 }
1351 if (!JS_WrapObject(cx, &wrapperHolder)) {
1352 return nullptr;
1353 }
1354 JS_SetReservedSlot(expandoObject, JSSLOT_EXPANDO_EXCLUSIVE_WRAPPER_HOLDER,
1355 ObjectOrNullValue(wrapperHolder));
1356
1357 // Store it on the exclusive wrapper, if there is one.
1358 if (exclusiveWrapper) {
1359 RootedObject cachedExpandoObject(cx, expandoObject);
1360 JSAutoRealm ar(cx, exclusiveWrapperGlobal);
1361 if (!JS_WrapObject(cx, &cachedExpandoObject)) {
1362 return nullptr;
1363 }
1364 JSObject* holder = ensureHolder(cx, exclusiveWrapper);
1365 if (!holder) {
1366 return nullptr;
1367 }
1368 SetCachedXrayExpando(holder, cachedExpandoObject);
1369 }
1370
1371 // If this is our first expando object, take the opportunity to preserve
1372 // the wrapper. This keeps our expandos alive even if the Xray wrapper gets
1373 // collected.
1374 RootedObject chain(cx, getExpandoChain(target));
1375 if (!chain) {
1376 preserveWrapper(target);
1377 }
1378
1379 // Insert it at the front of the chain.
1380 JS_SetReservedSlot(expandoObject, JSSLOT_EXPANDO_NEXT,
1381 ObjectOrNullValue(chain));
1382 setExpandoChain(cx, target, expandoObject);
1383
1384 return expandoObject;
1385 }
1386
ensureExpandoObject(JSContext * cx,HandleObject wrapper,HandleObject target)1387 JSObject* XrayTraits::ensureExpandoObject(JSContext* cx, HandleObject wrapper,
1388 HandleObject target) {
1389 MOZ_ASSERT(js::IsObjectInContextCompartment(wrapper, cx));
1390 RootedObject wrapperGlobal(cx, JS::CurrentGlobalOrNull(cx));
1391
1392 // Expando objects live in the target compartment.
1393 JSAutoRealm ar(cx, target);
1394 RootedObject expandoObject(cx);
1395 if (!getExpandoObject(cx, target, wrapper, &expandoObject)) {
1396 return nullptr;
1397 }
1398 if (!expandoObject) {
1399 bool isExclusive = CompartmentHasExclusiveExpandos(wrapper);
1400 expandoObject =
1401 attachExpandoObject(cx, target, isExclusive ? wrapper : nullptr,
1402 wrapperGlobal, WrapperPrincipal(wrapper));
1403 }
1404 return expandoObject;
1405 }
1406
cloneExpandoChain(JSContext * cx,HandleObject dst,HandleObject srcChain)1407 bool XrayTraits::cloneExpandoChain(JSContext* cx, HandleObject dst,
1408 HandleObject srcChain) {
1409 MOZ_ASSERT(js::IsObjectInContextCompartment(dst, cx));
1410 MOZ_ASSERT(getExpandoChain(dst) == nullptr);
1411
1412 RootedObject oldHead(cx, srcChain);
1413 while (oldHead) {
1414 // If movingIntoXrayCompartment is true, then our new reflector is in a
1415 // compartment that used to have an Xray-with-expandos to the old reflector
1416 // and we should copy the expandos to the new reflector directly.
1417 bool movingIntoXrayCompartment;
1418
1419 // exclusiveWrapper is only used if movingIntoXrayCompartment ends up true.
1420 RootedObject exclusiveWrapper(cx);
1421 RootedObject exclusiveWrapperGlobal(cx);
1422 RootedObject wrapperHolder(
1423 cx,
1424 JS::GetReservedSlot(oldHead, JSSLOT_EXPANDO_EXCLUSIVE_WRAPPER_HOLDER)
1425 .toObjectOrNull());
1426 if (wrapperHolder) {
1427 RootedObject unwrappedHolder(cx, UncheckedUnwrap(wrapperHolder));
1428 // unwrappedHolder is the compartment of the relevant Xray, so check
1429 // whether that matches the compartment of cx (which matches the
1430 // compartment of dst).
1431 movingIntoXrayCompartment =
1432 js::IsObjectInContextCompartment(unwrappedHolder, cx);
1433
1434 if (!movingIntoXrayCompartment) {
1435 // The global containing this wrapper holder has an xray for |src|
1436 // with expandos. Create an xray in the global for |dst| which
1437 // will be associated with a clone of |src|'s expando object.
1438 JSAutoRealm ar(cx, unwrappedHolder);
1439 exclusiveWrapper = dst;
1440 if (!JS_WrapObject(cx, &exclusiveWrapper)) {
1441 return false;
1442 }
1443 exclusiveWrapperGlobal = JS::CurrentGlobalOrNull(cx);
1444 }
1445 } else {
1446 JSAutoRealm ar(cx, oldHead);
1447 movingIntoXrayCompartment =
1448 expandoObjectMatchesConsumer(cx, oldHead, GetObjectPrincipal(dst));
1449 }
1450
1451 if (movingIntoXrayCompartment) {
1452 // Just copy properties directly onto dst.
1453 if (!JS_CopyOwnPropertiesAndPrivateFields(cx, dst, oldHead)) {
1454 return false;
1455 }
1456 } else {
1457 // Create a new expando object in the compartment of dst to replace
1458 // oldHead.
1459 RootedObject newHead(
1460 cx,
1461 attachExpandoObject(cx, dst, exclusiveWrapper, exclusiveWrapperGlobal,
1462 GetExpandoObjectPrincipal(oldHead)));
1463 if (!JS_CopyOwnPropertiesAndPrivateFields(cx, newHead, oldHead)) {
1464 return false;
1465 }
1466 }
1467 oldHead =
1468 JS::GetReservedSlot(oldHead, JSSLOT_EXPANDO_NEXT).toObjectOrNull();
1469 }
1470 return true;
1471 }
1472
ClearXrayExpandoSlots(JSObject * target,size_t slotIndex)1473 void ClearXrayExpandoSlots(JSObject* target, size_t slotIndex) {
1474 if (!NS_IsMainThread()) {
1475 // No Xrays
1476 return;
1477 }
1478
1479 MOZ_ASSERT(slotIndex != JSSLOT_EXPANDO_NEXT);
1480 MOZ_ASSERT(slotIndex != JSSLOT_EXPANDO_EXCLUSIVE_WRAPPER_HOLDER);
1481 MOZ_ASSERT(GetXrayTraits(target) == &DOMXrayTraits::singleton);
1482 RootingContext* rootingCx = RootingCx();
1483 RootedObject rootedTarget(rootingCx, target);
1484 RootedObject head(rootingCx,
1485 DOMXrayTraits::singleton.getExpandoChain(rootedTarget));
1486 while (head) {
1487 MOZ_ASSERT(JSCLASS_RESERVED_SLOTS(JS::GetClass(head)) > slotIndex);
1488 JS::SetReservedSlot(head, slotIndex, UndefinedValue());
1489 head = JS::GetReservedSlot(head, JSSLOT_EXPANDO_NEXT).toObjectOrNull();
1490 }
1491 }
1492
EnsureXrayExpandoObject(JSContext * cx,JS::HandleObject wrapper)1493 JSObject* EnsureXrayExpandoObject(JSContext* cx, JS::HandleObject wrapper) {
1494 MOZ_ASSERT(NS_IsMainThread());
1495 MOZ_ASSERT(GetXrayTraits(wrapper) == &DOMXrayTraits::singleton);
1496 MOZ_ASSERT(IsXrayWrapper(wrapper));
1497
1498 RootedObject target(cx, DOMXrayTraits::getTargetObject(wrapper));
1499 return DOMXrayTraits::singleton.ensureExpandoObject(cx, wrapper, target);
1500 }
1501
getExpandoClass(JSContext * cx,HandleObject target) const1502 const JSClass* XrayTraits::getExpandoClass(JSContext* cx,
1503 HandleObject target) const {
1504 return &DefaultXrayExpandoObjectClass;
1505 }
1506
1507 static const size_t JSSLOT_XRAY_HOLDER = 0;
1508
1509 /* static */
getHolder(JSObject * wrapper)1510 JSObject* XrayTraits::getHolder(JSObject* wrapper) {
1511 MOZ_ASSERT(WrapperFactory::IsXrayWrapper(wrapper));
1512 JS::Value v = js::GetProxyReservedSlot(wrapper, JSSLOT_XRAY_HOLDER);
1513 return v.isObject() ? &v.toObject() : nullptr;
1514 }
1515
ensureHolder(JSContext * cx,HandleObject wrapper)1516 JSObject* XrayTraits::ensureHolder(JSContext* cx, HandleObject wrapper) {
1517 RootedObject holder(cx, getHolder(wrapper));
1518 if (holder) {
1519 return holder;
1520 }
1521 holder = createHolder(cx, wrapper); // virtual trap.
1522 if (holder) {
1523 js::SetProxyReservedSlot(wrapper, JSSLOT_XRAY_HOLDER, ObjectValue(*holder));
1524 }
1525 return holder;
1526 }
1527
GetCachedXrayExpando(JSObject * wrapper)1528 static inline JSObject* GetCachedXrayExpando(JSObject* wrapper) {
1529 JSObject* holder = XrayTraits::getHolder(wrapper);
1530 if (!holder) {
1531 return nullptr;
1532 }
1533 Value v = JS::GetReservedSlot(holder, XrayTraits::HOLDER_SLOT_EXPANDO);
1534 return v.isObject() ? &v.toObject() : nullptr;
1535 }
1536
SetCachedXrayExpando(JSObject * holder,JSObject * expandoWrapper)1537 static inline void SetCachedXrayExpando(JSObject* holder,
1538 JSObject* expandoWrapper) {
1539 MOZ_ASSERT(JS::GetCompartment(holder) == JS::GetCompartment(expandoWrapper));
1540 JS_SetReservedSlot(holder, XrayTraits::HOLDER_SLOT_EXPANDO,
1541 ObjectValue(*expandoWrapper));
1542 }
1543
AsWindow(JSContext * cx,JSObject * wrapper)1544 static nsGlobalWindowInner* AsWindow(JSContext* cx, JSObject* wrapper) {
1545 // We want to use our target object here, since we don't want to be
1546 // doing a security check while unwrapping.
1547 JSObject* target = XrayTraits::getTargetObject(wrapper);
1548 return WindowOrNull(target);
1549 }
1550
IsWindow(JSContext * cx,JSObject * wrapper)1551 static bool IsWindow(JSContext* cx, JSObject* wrapper) {
1552 return !!AsWindow(cx, wrapper);
1553 }
1554
wrappedJSObject_getter(JSContext * cx,unsigned argc,Value * vp)1555 static bool wrappedJSObject_getter(JSContext* cx, unsigned argc, Value* vp) {
1556 CallArgs args = CallArgsFromVp(argc, vp);
1557 if (!args.thisv().isObject()) {
1558 JS_ReportErrorASCII(cx, "This value not an object");
1559 return false;
1560 }
1561 RootedObject wrapper(cx, &args.thisv().toObject());
1562 if (!IsWrapper(wrapper) || !WrapperFactory::IsXrayWrapper(wrapper) ||
1563 !WrapperFactory::AllowWaiver(wrapper)) {
1564 JS_ReportErrorASCII(cx, "Unexpected object");
1565 return false;
1566 }
1567
1568 args.rval().setObject(*wrapper);
1569
1570 return WrapperFactory::WaiveXrayAndWrap(cx, args.rval());
1571 }
1572
resolveOwnProperty(JSContext * cx,HandleObject wrapper,HandleObject target,HandleObject holder,HandleId id,MutableHandle<Maybe<PropertyDescriptor>> desc)1573 bool XrayTraits::resolveOwnProperty(
1574 JSContext* cx, HandleObject wrapper, HandleObject target,
1575 HandleObject holder, HandleId id,
1576 MutableHandle<Maybe<PropertyDescriptor>> desc) {
1577 desc.reset();
1578
1579 RootedObject expando(cx);
1580 if (!getExpandoObject(cx, target, wrapper, &expando)) {
1581 return false;
1582 }
1583
1584 // Check for expando properties first. Note that the expando object lives
1585 // in the target compartment.
1586 if (expando) {
1587 JSAutoRealm ar(cx, expando);
1588 JS_MarkCrossZoneId(cx, id);
1589 if (!JS_GetOwnPropertyDescriptorById(cx, expando, id, desc)) {
1590 return false;
1591 }
1592 }
1593
1594 // Next, check for ES builtins.
1595 if (!desc.isSome() && JS_IsGlobalObject(target)) {
1596 JSProtoKey key = JS_IdToProtoKey(cx, id);
1597 JSAutoRealm ar(cx, target);
1598 if (key != JSProto_Null) {
1599 MOZ_ASSERT(key < JSProto_LIMIT);
1600 RootedObject constructor(cx);
1601 if (!JS_GetClassObject(cx, key, &constructor)) {
1602 return false;
1603 }
1604 MOZ_ASSERT(constructor);
1605
1606 desc.set(Some(PropertyDescriptor::Data(
1607 ObjectValue(*constructor),
1608 {PropertyAttribute::Configurable, PropertyAttribute::Writable})));
1609 } else if (id == GetJSIDByIndex(cx, XPCJSContext::IDX_EVAL)) {
1610 RootedObject eval(cx);
1611 if (!js::GetRealmOriginalEval(cx, &eval)) {
1612 return false;
1613 }
1614 desc.set(Some(PropertyDescriptor::Data(
1615 ObjectValue(*eval),
1616 {PropertyAttribute::Configurable, PropertyAttribute::Writable})));
1617 } else if (id == GetJSIDByIndex(cx, XPCJSContext::IDX_INFINITY)) {
1618 desc.set(Some(PropertyDescriptor::Data(
1619 DoubleValue(PositiveInfinity<double>()), {})));
1620 } else if (id == GetJSIDByIndex(cx, XPCJSContext::IDX_NAN)) {
1621 desc.set(Some(PropertyDescriptor::Data(NaNValue(), {})));
1622 }
1623 }
1624
1625 if (desc.isSome()) {
1626 return JS_WrapPropertyDescriptor(cx, desc);
1627 }
1628
1629 // Handle .wrappedJSObject for subsuming callers. This should move once we
1630 // sort out own-ness for the holder.
1631 if (id == GetJSIDByIndex(cx, XPCJSContext::IDX_WRAPPED_JSOBJECT) &&
1632 WrapperFactory::AllowWaiver(wrapper)) {
1633 bool found = false;
1634 if (!JS_AlreadyHasOwnPropertyById(cx, holder, id, &found)) {
1635 return false;
1636 }
1637 if (!found && !JS_DefinePropertyById(cx, holder, id, wrappedJSObject_getter,
1638 nullptr, JSPROP_ENUMERATE)) {
1639 return false;
1640 }
1641 return JS_GetOwnPropertyDescriptorById(cx, holder, id, desc);
1642 }
1643
1644 return true;
1645 }
1646
resolveOwnProperty(JSContext * cx,HandleObject wrapper,HandleObject target,HandleObject holder,HandleId id,MutableHandle<Maybe<PropertyDescriptor>> desc)1647 bool DOMXrayTraits::resolveOwnProperty(
1648 JSContext* cx, HandleObject wrapper, HandleObject target,
1649 HandleObject holder, HandleId id,
1650 MutableHandle<Maybe<PropertyDescriptor>> desc) {
1651 // Call the common code.
1652 bool ok =
1653 XrayTraits::resolveOwnProperty(cx, wrapper, target, holder, id, desc);
1654 if (!ok || desc.isSome()) {
1655 return ok;
1656 }
1657
1658 // Check for indexed access on a window.
1659 uint32_t index = GetArrayIndexFromId(id);
1660 if (IsArrayIndex(index)) {
1661 nsGlobalWindowInner* win = AsWindow(cx, wrapper);
1662 // Note: As() unwraps outer windows to get to the inner window.
1663 if (win) {
1664 Nullable<WindowProxyHolder> subframe = win->IndexedGetter(index);
1665 if (!subframe.IsNull()) {
1666 Rooted<Value> value(cx);
1667 if (MOZ_UNLIKELY(!WrapObject(cx, subframe.Value(), &value))) {
1668 // It's gone?
1669 return xpc::Throw(cx, NS_ERROR_FAILURE);
1670 }
1671 desc.set(Some(PropertyDescriptor::Data(
1672 value,
1673 {PropertyAttribute::Configurable, PropertyAttribute::Enumerable})));
1674 return JS_WrapPropertyDescriptor(cx, desc);
1675 }
1676 }
1677 }
1678
1679 if (!JS_GetOwnPropertyDescriptorById(cx, holder, id, desc)) {
1680 return false;
1681 }
1682 if (desc.isSome()) {
1683 return true;
1684 }
1685
1686 bool cacheOnHolder;
1687 if (!XrayResolveOwnProperty(cx, wrapper, target, id, desc, cacheOnHolder)) {
1688 return false;
1689 }
1690
1691 if (desc.isNothing() || !cacheOnHolder) {
1692 return true;
1693 }
1694
1695 Rooted<PropertyDescriptor> defineDesc(cx, *desc);
1696 return JS_DefinePropertyById(cx, holder, id, defineDesc) &&
1697 JS_GetOwnPropertyDescriptorById(cx, holder, id, desc);
1698 }
1699
delete_(JSContext * cx,JS::HandleObject wrapper,JS::HandleId id,JS::ObjectOpResult & result)1700 bool DOMXrayTraits::delete_(JSContext* cx, JS::HandleObject wrapper,
1701 JS::HandleId id, JS::ObjectOpResult& result) {
1702 RootedObject target(cx, getTargetObject(wrapper));
1703 return XrayDeleteNamedProperty(cx, wrapper, target, id, result);
1704 }
1705
defineProperty(JSContext * cx,HandleObject wrapper,HandleId id,Handle<PropertyDescriptor> desc,Handle<Maybe<PropertyDescriptor>> existingDesc,Handle<JSObject * > existingHolder,JS::ObjectOpResult & result,bool * done)1706 bool DOMXrayTraits::defineProperty(
1707 JSContext* cx, HandleObject wrapper, HandleId id,
1708 Handle<PropertyDescriptor> desc,
1709 Handle<Maybe<PropertyDescriptor>> existingDesc,
1710 Handle<JSObject*> existingHolder, JS::ObjectOpResult& result, bool* done) {
1711 // Check for an indexed property on a Window. If that's happening, do
1712 // nothing but set done to true so it won't get added as an expando.
1713 if (IsWindow(cx, wrapper)) {
1714 if (IsArrayIndex(GetArrayIndexFromId(id))) {
1715 *done = true;
1716 return result.succeed();
1717 }
1718 }
1719
1720 JS::Rooted<JSObject*> obj(cx, getTargetObject(wrapper));
1721 return XrayDefineProperty(cx, wrapper, obj, id, desc, result, done);
1722 }
1723
enumerateNames(JSContext * cx,HandleObject wrapper,unsigned flags,MutableHandleIdVector props)1724 bool DOMXrayTraits::enumerateNames(JSContext* cx, HandleObject wrapper,
1725 unsigned flags,
1726 MutableHandleIdVector props) {
1727 // Put the indexed properties for a window first.
1728 nsGlobalWindowInner* win = AsWindow(cx, wrapper);
1729 if (win) {
1730 uint32_t length = win->Length();
1731 if (!props.reserve(props.length() + length)) {
1732 return false;
1733 }
1734 JS::RootedId indexId(cx);
1735 for (uint32_t i = 0; i < length; ++i) {
1736 if (!JS_IndexToId(cx, i, &indexId)) {
1737 return false;
1738 }
1739 props.infallibleAppend(indexId);
1740 }
1741 }
1742
1743 JS::Rooted<JSObject*> obj(cx, getTargetObject(wrapper));
1744 if (JS_IsGlobalObject(obj)) {
1745 // We could do this in a shared enumerateNames with JSXrayTraits, but we
1746 // don't really have globals we expose via those.
1747 JSAutoRealm ar(cx, obj);
1748 if (!JS_NewEnumerateStandardClassesIncludingResolved(
1749 cx, obj, props, !(flags & JSITER_HIDDEN))) {
1750 return false;
1751 }
1752 }
1753 return XrayOwnPropertyKeys(cx, wrapper, obj, flags, props);
1754 }
1755
call(JSContext * cx,HandleObject wrapper,const JS::CallArgs & args,const js::Wrapper & baseInstance)1756 bool DOMXrayTraits::call(JSContext* cx, HandleObject wrapper,
1757 const JS::CallArgs& args,
1758 const js::Wrapper& baseInstance) {
1759 RootedObject obj(cx, getTargetObject(wrapper));
1760 const JSClass* clasp = JS::GetClass(obj);
1761 // What we have is either a WebIDL interface object, a WebIDL prototype
1762 // object, or a WebIDL instance object. WebIDL prototype objects never have
1763 // a clasp->call. WebIDL interface objects we want to invoke on the xray
1764 // compartment. WebIDL instance objects either don't have a clasp->call or
1765 // are using "legacycaller". At this time for all the legacycaller users it
1766 // makes more sense to invoke on the xray compartment, so we just go ahead
1767 // and do that for everything.
1768 if (JSNative call = clasp->getCall()) {
1769 // call it on the Xray compartment
1770 return call(cx, args.length(), args.base());
1771 }
1772
1773 RootedValue v(cx, ObjectValue(*wrapper));
1774 js::ReportIsNotFunction(cx, v);
1775 return false;
1776 }
1777
construct(JSContext * cx,HandleObject wrapper,const JS::CallArgs & args,const js::Wrapper & baseInstance)1778 bool DOMXrayTraits::construct(JSContext* cx, HandleObject wrapper,
1779 const JS::CallArgs& args,
1780 const js::Wrapper& baseInstance) {
1781 RootedObject obj(cx, getTargetObject(wrapper));
1782 MOZ_ASSERT(mozilla::dom::HasConstructor(obj));
1783 const JSClass* clasp = JS::GetClass(obj);
1784 // See comments in DOMXrayTraits::call() explaining what's going on here.
1785 if (clasp->flags & JSCLASS_IS_DOMIFACEANDPROTOJSCLASS) {
1786 if (JSNative construct = clasp->getConstruct()) {
1787 if (!construct(cx, args.length(), args.base())) {
1788 return false;
1789 }
1790 } else {
1791 RootedValue v(cx, ObjectValue(*wrapper));
1792 js::ReportIsNotFunction(cx, v);
1793 return false;
1794 }
1795 } else {
1796 if (!baseInstance.construct(cx, wrapper, args)) {
1797 return false;
1798 }
1799 }
1800 if (!args.rval().isObject() || !JS_WrapValue(cx, args.rval())) {
1801 return false;
1802 }
1803 return true;
1804 }
1805
getPrototype(JSContext * cx,JS::HandleObject wrapper,JS::HandleObject target,JS::MutableHandleObject protop)1806 bool DOMXrayTraits::getPrototype(JSContext* cx, JS::HandleObject wrapper,
1807 JS::HandleObject target,
1808 JS::MutableHandleObject protop) {
1809 return mozilla::dom::XrayGetNativeProto(cx, target, protop);
1810 }
1811
preserveWrapper(JSObject * target)1812 void DOMXrayTraits::preserveWrapper(JSObject* target) {
1813 nsISupports* identity = mozilla::dom::UnwrapDOMObjectToISupports(target);
1814 if (!identity) {
1815 return;
1816 }
1817 nsWrapperCache* cache = nullptr;
1818 CallQueryInterface(identity, &cache);
1819 if (cache) {
1820 cache->PreserveWrapper(identity);
1821 }
1822 }
1823
createHolder(JSContext * cx,JSObject * wrapper)1824 JSObject* DOMXrayTraits::createHolder(JSContext* cx, JSObject* wrapper) {
1825 return JS_NewObjectWithGivenProto(cx, &HolderClass, nullptr);
1826 }
1827
getExpandoClass(JSContext * cx,HandleObject target) const1828 const JSClass* DOMXrayTraits::getExpandoClass(JSContext* cx,
1829 HandleObject target) const {
1830 return XrayGetExpandoClass(cx, target);
1831 }
1832
1833 template <typename Base, typename Traits>
preventExtensions(JSContext * cx,HandleObject wrapper,ObjectOpResult & result) const1834 bool XrayWrapper<Base, Traits>::preventExtensions(
1835 JSContext* cx, HandleObject wrapper, ObjectOpResult& result) const {
1836 // Xray wrappers are supposed to provide a clean view of the target
1837 // reflector, hiding any modifications by script in the target scope. So
1838 // even if that script freezes the reflector, we don't want to make that
1839 // visible to the caller. DOM reflectors are always extensible by default,
1840 // so we can just return failure here.
1841 return result.failCantPreventExtensions();
1842 }
1843
1844 template <typename Base, typename Traits>
isExtensible(JSContext * cx,JS::Handle<JSObject * > wrapper,bool * extensible) const1845 bool XrayWrapper<Base, Traits>::isExtensible(JSContext* cx,
1846 JS::Handle<JSObject*> wrapper,
1847 bool* extensible) const {
1848 // See above.
1849 *extensible = true;
1850 return true;
1851 }
1852
1853 template <typename Base, typename Traits>
getOwnPropertyDescriptor(JSContext * cx,HandleObject wrapper,HandleId id,MutableHandle<Maybe<PropertyDescriptor>> desc) const1854 bool XrayWrapper<Base, Traits>::getOwnPropertyDescriptor(
1855 JSContext* cx, HandleObject wrapper, HandleId id,
1856 MutableHandle<Maybe<PropertyDescriptor>> desc) const {
1857 assertEnteredPolicy(cx, wrapper, id,
1858 BaseProxyHandler::GET | BaseProxyHandler::SET |
1859 BaseProxyHandler::GET_PROPERTY_DESCRIPTOR);
1860 RootedObject target(cx, Traits::getTargetObject(wrapper));
1861 RootedObject holder(cx, Traits::singleton.ensureHolder(cx, wrapper));
1862 if (!holder) {
1863 return false;
1864 }
1865
1866 return Traits::singleton.resolveOwnProperty(cx, wrapper, target, holder, id,
1867 desc);
1868 }
1869
1870 // Consider what happens when chrome does |xray.expando = xray.wrappedJSObject|.
1871 //
1872 // Since the expando comes from the target compartment, wrapping it back into
1873 // the target compartment to define it on the expando object ends up stripping
1874 // off the Xray waiver that gives |xray| and |xray.wrappedJSObject| different
1875 // identities. This is generally the right thing to do when wrapping across
1876 // compartments, but is incorrect in the special case of the Xray expando
1877 // object. Manually re-apply Xrays if necessary.
1878 //
1879 // NB: In order to satisfy the invariants of WaiveXray, we need to pass
1880 // in an object sans security wrapper, which means we need to strip off any
1881 // potential same-compartment security wrapper that may have been applied
1882 // to the content object. This is ok, because the the expando object is only
1883 // ever accessed by code across the compartment boundary.
RecreateLostWaivers(JSContext * cx,const PropertyDescriptor * orig,MutableHandle<PropertyDescriptor> wrapped)1884 static bool RecreateLostWaivers(JSContext* cx, const PropertyDescriptor* orig,
1885 MutableHandle<PropertyDescriptor> wrapped) {
1886 // Compute whether the original objects were waived, and implicitly, whether
1887 // they were objects at all.
1888 bool valueWasWaived =
1889 orig->hasValue() && orig->value().isObject() &&
1890 WrapperFactory::HasWaiveXrayFlag(&orig->value().toObject());
1891 bool getterWasWaived = orig->hasGetter() && orig->getter() &&
1892 WrapperFactory::HasWaiveXrayFlag(orig->getter());
1893 bool setterWasWaived = orig->hasSetter() && orig->setter() &&
1894 WrapperFactory::HasWaiveXrayFlag(orig->setter());
1895
1896 // Recreate waivers. Note that for value, we need an extra UncheckedUnwrap
1897 // to handle same-compartment security wrappers (see above). This should
1898 // never happen for getters/setters.
1899
1900 RootedObject rewaived(cx);
1901 if (valueWasWaived &&
1902 !IsCrossCompartmentWrapper(&wrapped.value().toObject())) {
1903 rewaived = &wrapped.value().toObject();
1904 rewaived = WrapperFactory::WaiveXray(cx, UncheckedUnwrap(rewaived));
1905 NS_ENSURE_TRUE(rewaived, false);
1906 wrapped.value().set(ObjectValue(*rewaived));
1907 }
1908 if (getterWasWaived && !IsCrossCompartmentWrapper(wrapped.getter())) {
1909 // We can't end up with WindowProxy or Location as getters.
1910 MOZ_ASSERT(CheckedUnwrapStatic(wrapped.getter()));
1911 rewaived = WrapperFactory::WaiveXray(cx, wrapped.getter());
1912 NS_ENSURE_TRUE(rewaived, false);
1913 wrapped.setGetter(rewaived);
1914 }
1915 if (setterWasWaived && !IsCrossCompartmentWrapper(wrapped.setter())) {
1916 // We can't end up with WindowProxy or Location as setters.
1917 MOZ_ASSERT(CheckedUnwrapStatic(wrapped.setter()));
1918 rewaived = WrapperFactory::WaiveXray(cx, wrapped.setter());
1919 NS_ENSURE_TRUE(rewaived, false);
1920 wrapped.setSetter(rewaived);
1921 }
1922
1923 return true;
1924 }
1925
1926 template <typename Base, typename Traits>
defineProperty(JSContext * cx,HandleObject wrapper,HandleId id,Handle<PropertyDescriptor> desc,ObjectOpResult & result) const1927 bool XrayWrapper<Base, Traits>::defineProperty(JSContext* cx,
1928 HandleObject wrapper,
1929 HandleId id,
1930 Handle<PropertyDescriptor> desc,
1931 ObjectOpResult& result) const {
1932 assertEnteredPolicy(cx, wrapper, id, BaseProxyHandler::SET);
1933
1934 Rooted<Maybe<PropertyDescriptor>> existingDesc(cx);
1935 Rooted<JSObject*> existingHolder(cx);
1936 if (!JS_GetPropertyDescriptorById(cx, wrapper, id, &existingDesc,
1937 &existingHolder)) {
1938 return false;
1939 }
1940
1941 // Note that the check here is intended to differentiate between own and
1942 // non-own properties, since the above lookup is not limited to own
1943 // properties. At present, this may not always do the right thing because
1944 // we often lie (sloppily) about where we found properties and set
1945 // existingHolder to |wrapper|. Once we fully fix our Xray prototype
1946 // semantics, this should work as intended.
1947 if (existingDesc.isSome() && existingHolder == wrapper &&
1948 !existingDesc->configurable()) {
1949 // We have a non-configurable property. See if the caller is trying to
1950 // re-configure it in any way other than making it non-writable.
1951 if (existingDesc->isAccessorDescriptor() || desc.isAccessorDescriptor() ||
1952 (desc.hasEnumerable() &&
1953 existingDesc->enumerable() != desc.enumerable()) ||
1954 (desc.hasWritable() && !existingDesc->writable() && desc.writable())) {
1955 // We should technically report non-configurability in strict mode, but
1956 // doing that via JSAPI used to be a lot of trouble. See bug 1135997.
1957 return result.succeed();
1958 }
1959 if (!existingDesc->writable()) {
1960 // Same as the above for non-writability.
1961 return result.succeed();
1962 }
1963 }
1964
1965 bool done = false;
1966 if (!Traits::singleton.defineProperty(cx, wrapper, id, desc, existingDesc,
1967 existingHolder, result, &done)) {
1968 return false;
1969 }
1970 if (done) {
1971 return true;
1972 }
1973
1974 // Grab the relevant expando object.
1975 RootedObject target(cx, Traits::getTargetObject(wrapper));
1976 RootedObject expandoObject(
1977 cx, Traits::singleton.ensureExpandoObject(cx, wrapper, target));
1978 if (!expandoObject) {
1979 return false;
1980 }
1981
1982 // We're placing an expando. The expando objects live in the target
1983 // compartment, so we need to enter it.
1984 JSAutoRealm ar(cx, target);
1985 JS_MarkCrossZoneId(cx, id);
1986
1987 // Wrap the property descriptor for the target compartment.
1988 Rooted<PropertyDescriptor> wrappedDesc(cx, desc);
1989 if (!JS_WrapPropertyDescriptor(cx, &wrappedDesc)) {
1990 return false;
1991 }
1992
1993 // Fix up Xray waivers.
1994 if (!RecreateLostWaivers(cx, desc.address(), &wrappedDesc)) {
1995 return false;
1996 }
1997
1998 return JS_DefinePropertyById(cx, expandoObject, id, wrappedDesc, result);
1999 }
2000
2001 template <typename Base, typename Traits>
ownPropertyKeys(JSContext * cx,HandleObject wrapper,MutableHandleIdVector props) const2002 bool XrayWrapper<Base, Traits>::ownPropertyKeys(
2003 JSContext* cx, HandleObject wrapper, MutableHandleIdVector props) const {
2004 assertEnteredPolicy(cx, wrapper, JSID_VOID, BaseProxyHandler::ENUMERATE);
2005 return getPropertyKeys(
2006 cx, wrapper, JSITER_OWNONLY | JSITER_HIDDEN | JSITER_SYMBOLS, props);
2007 }
2008
2009 template <typename Base, typename Traits>
delete_(JSContext * cx,HandleObject wrapper,HandleId id,ObjectOpResult & result) const2010 bool XrayWrapper<Base, Traits>::delete_(JSContext* cx, HandleObject wrapper,
2011 HandleId id,
2012 ObjectOpResult& result) const {
2013 assertEnteredPolicy(cx, wrapper, id, BaseProxyHandler::SET);
2014
2015 // Check the expando object.
2016 RootedObject target(cx, Traits::getTargetObject(wrapper));
2017 RootedObject expando(cx);
2018 if (!Traits::singleton.getExpandoObject(cx, target, wrapper, &expando)) {
2019 return false;
2020 }
2021
2022 if (expando) {
2023 JSAutoRealm ar(cx, expando);
2024 JS_MarkCrossZoneId(cx, id);
2025 bool hasProp;
2026 if (!JS_HasPropertyById(cx, expando, id, &hasProp)) {
2027 return false;
2028 }
2029 if (hasProp) {
2030 return JS_DeletePropertyById(cx, expando, id, result);
2031 }
2032 }
2033
2034 return Traits::singleton.delete_(cx, wrapper, id, result);
2035 }
2036
2037 template <typename Base, typename Traits>
get(JSContext * cx,HandleObject wrapper,HandleValue receiver,HandleId id,MutableHandleValue vp) const2038 bool XrayWrapper<Base, Traits>::get(JSContext* cx, HandleObject wrapper,
2039 HandleValue receiver, HandleId id,
2040 MutableHandleValue vp) const {
2041 // This is called by Proxy::get, but since we return true for hasPrototype()
2042 // it's only called for properties that hasOwn() claims we have as own
2043 // properties. Since we only need to worry about own properties, we can use
2044 // getOwnPropertyDescriptor here.
2045 Rooted<Maybe<PropertyDescriptor>> desc(cx);
2046 if (!getOwnPropertyDescriptor(cx, wrapper, id, &desc)) {
2047 return false;
2048 }
2049
2050 MOZ_ASSERT(desc.isSome(),
2051 "hasOwn() claimed we have this property, so why would we not get "
2052 "a descriptor here?");
2053 desc->assertComplete();
2054
2055 // Everything after here follows [[Get]] for ordinary objects.
2056 if (desc->isDataDescriptor()) {
2057 vp.set(desc->value());
2058 return true;
2059 }
2060
2061 MOZ_ASSERT(desc->isAccessorDescriptor());
2062 RootedObject getter(cx, desc->getter());
2063
2064 if (!getter) {
2065 vp.setUndefined();
2066 return true;
2067 }
2068
2069 return Call(cx, receiver, getter, HandleValueArray::empty(), vp);
2070 }
2071
2072 template <typename Base, typename Traits>
set(JSContext * cx,HandleObject wrapper,HandleId id,HandleValue v,HandleValue receiver,ObjectOpResult & result) const2073 bool XrayWrapper<Base, Traits>::set(JSContext* cx, HandleObject wrapper,
2074 HandleId id, HandleValue v,
2075 HandleValue receiver,
2076 ObjectOpResult& result) const {
2077 MOZ_CRASH("Shouldn't be called: we return true for hasPrototype()");
2078 return false;
2079 }
2080
2081 template <typename Base, typename Traits>
has(JSContext * cx,HandleObject wrapper,HandleId id,bool * bp) const2082 bool XrayWrapper<Base, Traits>::has(JSContext* cx, HandleObject wrapper,
2083 HandleId id, bool* bp) const {
2084 MOZ_CRASH("Shouldn't be called: we return true for hasPrototype()");
2085 return false;
2086 }
2087
2088 template <typename Base, typename Traits>
hasOwn(JSContext * cx,HandleObject wrapper,HandleId id,bool * bp) const2089 bool XrayWrapper<Base, Traits>::hasOwn(JSContext* cx, HandleObject wrapper,
2090 HandleId id, bool* bp) const {
2091 // Skip our Base if it isn't already ProxyHandler.
2092 return js::BaseProxyHandler::hasOwn(cx, wrapper, id, bp);
2093 }
2094
2095 template <typename Base, typename Traits>
getOwnEnumerablePropertyKeys(JSContext * cx,HandleObject wrapper,MutableHandleIdVector props) const2096 bool XrayWrapper<Base, Traits>::getOwnEnumerablePropertyKeys(
2097 JSContext* cx, HandleObject wrapper, MutableHandleIdVector props) const {
2098 // Skip our Base if it isn't already ProxyHandler.
2099 return js::BaseProxyHandler::getOwnEnumerablePropertyKeys(cx, wrapper, props);
2100 }
2101
2102 template <typename Base, typename Traits>
enumerate(JSContext * cx,HandleObject wrapper,JS::MutableHandleIdVector props) const2103 bool XrayWrapper<Base, Traits>::enumerate(
2104 JSContext* cx, HandleObject wrapper,
2105 JS::MutableHandleIdVector props) const {
2106 MOZ_CRASH("Shouldn't be called: we return true for hasPrototype()");
2107 }
2108
2109 template <typename Base, typename Traits>
call(JSContext * cx,HandleObject wrapper,const JS::CallArgs & args) const2110 bool XrayWrapper<Base, Traits>::call(JSContext* cx, HandleObject wrapper,
2111 const JS::CallArgs& args) const {
2112 assertEnteredPolicy(cx, wrapper, JSID_VOID, BaseProxyHandler::CALL);
2113 // Hard cast the singleton since SecurityWrapper doesn't have one.
2114 return Traits::call(cx, wrapper, args, Base::singleton);
2115 }
2116
2117 template <typename Base, typename Traits>
construct(JSContext * cx,HandleObject wrapper,const JS::CallArgs & args) const2118 bool XrayWrapper<Base, Traits>::construct(JSContext* cx, HandleObject wrapper,
2119 const JS::CallArgs& args) const {
2120 assertEnteredPolicy(cx, wrapper, JSID_VOID, BaseProxyHandler::CALL);
2121 // Hard cast the singleton since SecurityWrapper doesn't have one.
2122 return Traits::construct(cx, wrapper, args, Base::singleton);
2123 }
2124
2125 template <typename Base, typename Traits>
getBuiltinClass(JSContext * cx,JS::HandleObject wrapper,js::ESClass * cls) const2126 bool XrayWrapper<Base, Traits>::getBuiltinClass(JSContext* cx,
2127 JS::HandleObject wrapper,
2128 js::ESClass* cls) const {
2129 return Traits::getBuiltinClass(cx, wrapper, Base::singleton, cls);
2130 }
2131
2132 template <typename Base, typename Traits>
hasInstance(JSContext * cx,JS::HandleObject wrapper,JS::MutableHandleValue v,bool * bp) const2133 bool XrayWrapper<Base, Traits>::hasInstance(JSContext* cx,
2134 JS::HandleObject wrapper,
2135 JS::MutableHandleValue v,
2136 bool* bp) const {
2137 assertEnteredPolicy(cx, wrapper, JSID_VOID, BaseProxyHandler::GET);
2138
2139 // CrossCompartmentWrapper::hasInstance unwraps |wrapper|'s Xrays and enters
2140 // its compartment. Any present XrayWrappers should be preserved, so the
2141 // standard "instanceof" implementation is called without unwrapping first.
2142 return JS::InstanceofOperator(cx, wrapper, v, bp);
2143 }
2144
2145 template <typename Base, typename Traits>
className(JSContext * cx,HandleObject wrapper) const2146 const char* XrayWrapper<Base, Traits>::className(JSContext* cx,
2147 HandleObject wrapper) const {
2148 return Traits::className(cx, wrapper, Base::singleton);
2149 }
2150
2151 template <typename Base, typename Traits>
getPrototype(JSContext * cx,JS::HandleObject wrapper,JS::MutableHandleObject protop) const2152 bool XrayWrapper<Base, Traits>::getPrototype(
2153 JSContext* cx, JS::HandleObject wrapper,
2154 JS::MutableHandleObject protop) const {
2155 // We really only want this override for non-SecurityWrapper-inheriting
2156 // |Base|. But doing that statically with templates requires partial method
2157 // specializations (and therefore a helper class), which is all more trouble
2158 // than it's worth. Do a dynamic check.
2159 if (Base::hasSecurityPolicy()) {
2160 return Base::getPrototype(cx, wrapper, protop);
2161 }
2162
2163 RootedObject target(cx, Traits::getTargetObject(wrapper));
2164 RootedObject expando(cx);
2165 if (!Traits::singleton.getExpandoObject(cx, target, wrapper, &expando)) {
2166 return false;
2167 }
2168
2169 // We want to keep the Xray's prototype distinct from that of content, but
2170 // only if there's been a set. If there's not an expando, or the expando
2171 // slot is |undefined|, hand back the default proto, appropriately wrapped.
2172
2173 if (expando) {
2174 RootedValue v(cx);
2175 { // Scope for JSAutoRealm
2176 JSAutoRealm ar(cx, expando);
2177 v = JS::GetReservedSlot(expando, JSSLOT_EXPANDO_PROTOTYPE);
2178 }
2179 if (!v.isUndefined()) {
2180 protop.set(v.toObjectOrNull());
2181 return JS_WrapObject(cx, protop);
2182 }
2183 }
2184
2185 // Check our holder, and cache there if we don't have it cached already.
2186 RootedObject holder(cx, Traits::singleton.ensureHolder(cx, wrapper));
2187 if (!holder) {
2188 return false;
2189 }
2190
2191 Value cached = JS::GetReservedSlot(holder, Traits::HOLDER_SLOT_CACHED_PROTO);
2192 if (cached.isUndefined()) {
2193 if (!Traits::singleton.getPrototype(cx, wrapper, target, protop)) {
2194 return false;
2195 }
2196
2197 JS::SetReservedSlot(holder, Traits::HOLDER_SLOT_CACHED_PROTO,
2198 ObjectOrNullValue(protop));
2199 } else {
2200 protop.set(cached.toObjectOrNull());
2201 }
2202 return true;
2203 }
2204
2205 template <typename Base, typename Traits>
setPrototype(JSContext * cx,JS::HandleObject wrapper,JS::HandleObject proto,JS::ObjectOpResult & result) const2206 bool XrayWrapper<Base, Traits>::setPrototype(JSContext* cx,
2207 JS::HandleObject wrapper,
2208 JS::HandleObject proto,
2209 JS::ObjectOpResult& result) const {
2210 // Do this only for non-SecurityWrapper-inheriting |Base|. See the comment
2211 // in getPrototype().
2212 if (Base::hasSecurityPolicy()) {
2213 return Base::setPrototype(cx, wrapper, proto, result);
2214 }
2215
2216 RootedObject target(cx, Traits::getTargetObject(wrapper));
2217 RootedObject expando(
2218 cx, Traits::singleton.ensureExpandoObject(cx, wrapper, target));
2219 if (!expando) {
2220 return false;
2221 }
2222
2223 // The expando lives in the target's realm, so do our installation there.
2224 JSAutoRealm ar(cx, target);
2225
2226 RootedValue v(cx, ObjectOrNullValue(proto));
2227 if (!JS_WrapValue(cx, &v)) {
2228 return false;
2229 }
2230 JS_SetReservedSlot(expando, JSSLOT_EXPANDO_PROTOTYPE, v);
2231 return result.succeed();
2232 }
2233
2234 template <typename Base, typename Traits>
getPrototypeIfOrdinary(JSContext * cx,JS::HandleObject wrapper,bool * isOrdinary,JS::MutableHandleObject protop) const2235 bool XrayWrapper<Base, Traits>::getPrototypeIfOrdinary(
2236 JSContext* cx, JS::HandleObject wrapper, bool* isOrdinary,
2237 JS::MutableHandleObject protop) const {
2238 // We want to keep the Xray's prototype distinct from that of content, but
2239 // only if there's been a set. This different-prototype-over-time behavior
2240 // means that the [[GetPrototypeOf]] trap *can't* be ECMAScript's ordinary
2241 // [[GetPrototypeOf]]. This also covers cross-origin Window behavior that
2242 // per
2243 // <https://html.spec.whatwg.org/multipage/browsers.html#windowproxy-getprototypeof>
2244 // must be non-ordinary.
2245 *isOrdinary = false;
2246 return true;
2247 }
2248
2249 template <typename Base, typename Traits>
setImmutablePrototype(JSContext * cx,JS::HandleObject wrapper,bool * succeeded) const2250 bool XrayWrapper<Base, Traits>::setImmutablePrototype(JSContext* cx,
2251 JS::HandleObject wrapper,
2252 bool* succeeded) const {
2253 // For now, lacking an obvious place to store a bit, prohibit making an
2254 // Xray's [[Prototype]] immutable. We can revisit this (or maybe give all
2255 // Xrays immutable [[Prototype]], because who does this, really?) later if
2256 // necessary.
2257 *succeeded = false;
2258 return true;
2259 }
2260
2261 template <typename Base, typename Traits>
getPropertyKeys(JSContext * cx,HandleObject wrapper,unsigned flags,MutableHandleIdVector props) const2262 bool XrayWrapper<Base, Traits>::getPropertyKeys(
2263 JSContext* cx, HandleObject wrapper, unsigned flags,
2264 MutableHandleIdVector props) const {
2265 assertEnteredPolicy(cx, wrapper, JSID_VOID, BaseProxyHandler::ENUMERATE);
2266
2267 // Enumerate expando properties first. Note that the expando object lives
2268 // in the target compartment.
2269 RootedObject target(cx, Traits::getTargetObject(wrapper));
2270 RootedObject expando(cx);
2271 if (!Traits::singleton.getExpandoObject(cx, target, wrapper, &expando)) {
2272 return false;
2273 }
2274
2275 if (expando) {
2276 JSAutoRealm ar(cx, expando);
2277 if (!js::GetPropertyKeys(cx, expando, flags, props)) {
2278 return false;
2279 }
2280 }
2281 for (size_t i = 0; i < props.length(); ++i) {
2282 JS_MarkCrossZoneId(cx, props[i]);
2283 }
2284
2285 return Traits::singleton.enumerateNames(cx, wrapper, flags, props);
2286 }
2287
2288 /*
2289 * The Permissive / Security variants should be used depending on whether the
2290 * compartment of the wrapper is guranteed to subsume the compartment of the
2291 * wrapped object (i.e. - whether it is safe from a security perspective to
2292 * unwrap the wrapper).
2293 */
2294
2295 template <typename Base, typename Traits>
2296 const xpc::XrayWrapper<Base, Traits> xpc::XrayWrapper<Base, Traits>::singleton(
2297 0);
2298
2299 template class PermissiveXrayDOM;
2300 template class PermissiveXrayJS;
2301 template class PermissiveXrayOpaque;
2302
2303 /*
2304 * This callback is used by the JS engine to test if a proxy handler is for a
2305 * cross compartment xray with no security requirements.
2306 */
IsCrossCompartmentXrayCallback(const js::BaseProxyHandler * handler)2307 static bool IsCrossCompartmentXrayCallback(
2308 const js::BaseProxyHandler* handler) {
2309 return handler == &PermissiveXrayDOM::singleton;
2310 }
2311
2312 JS::XrayJitInfo gXrayJitInfo = {
2313 IsCrossCompartmentXrayCallback, CompartmentHasExclusiveExpandos,
2314 JSSLOT_XRAY_HOLDER, XrayTraits::HOLDER_SLOT_EXPANDO,
2315 JSSLOT_EXPANDO_PROTOTYPE};
2316
2317 } // namespace xpc
2318