Debian Codegraph @

js/src/proxy/Proxy.cpp

raw
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 "js/Proxy.h"
8
9 #include "mozilla/Attributes.h"
10 #include "mozilla/Maybe.h"
11
12 #include <string.h>
13
14 #include "js/friend/ErrorMessages.h" // JSMSG_*
15 #include "js/friend/StackLimits.h" // js::AutoCheckRecursionLimit, js::GetNativeStackLimit
16 #include "js/friend/WindowProxy.h" // js::IsWindow, js::IsWindowProxy, js::ToWindowProxyIfWindow
17 #include "js/PropertySpec.h"
18 #include "js/Value.h" // JS::ObjectValue
19 #include "js/Wrapper.h"
20 #include "proxy/DeadObjectProxy.h"
21 #include "proxy/ScriptedProxyHandler.h"
22 #include "vm/Compartment.h"
23 #include "vm/Interpreter.h" // js::CallGetter
24 #include "vm/JSContext.h"
25 #include "vm/JSFunction.h"
26 #include "vm/JSObject.h"
27 #include "vm/WrapperObject.h"
28
29 #include "gc/Marking-inl.h"
30 #include "vm/JSObject-inl.h"
31 #include "vm/NativeObject-inl.h"
32
33 using namespace js;
34
35 // Used by private fields to manipulate the ProxyExpando:
36 // All the following methods are called iff the handler for the proxy
37 // returns true for useProxyExpandoObjectForPrivateFields.
38 static bool ProxySetOnExpando(JSContext* cx, HandleObject proxy, HandleId id,
39 HandleValue v, HandleValue receiver,
40 ObjectOpResult& result) {
41 MOZ_ASSERT(id.isPrivateName());
42
43 // For BaseProxyHandler, private names are stored in the expando object.
44 RootedObject expando(cx, proxy->as<ProxyObject>().expando().toObjectOrNull());
45
46 // SetPrivateElementOperation checks for hasOwn first, which ensures the
47 // expando exsists.
48 //
49 // If we don't have an expando, then we're probably misusing debugger apis and
50 // should just throw.
51 if (!expando) {
52 JS_ReportErrorNumberASCII(cx, GetErrorMessage, nullptr,
53 JSMSG_SET_MISSING_PRIVATE);
54 return false;
55 }
56
57 Rooted<mozilla::Maybe<PropertyDescriptor>> ownDesc(cx);
58 if (!GetOwnPropertyDescriptor(cx, expando, id, &ownDesc)) {
59 return false;
60 }
61 if (ownDesc.isNothing()) {
62 JS_ReportErrorNumberASCII(cx, GetErrorMessage, nullptr,
63 JSMSG_SET_MISSING_PRIVATE);
64 return false;
65 }
66
67 RootedValue expandoValue(cx, proxy->as<ProxyObject>().expando());
68 return SetPropertyIgnoringNamedGetter(cx, expando, id, v, expandoValue,
69 ownDesc, result);
70 }
71
72 static bool ProxyGetOwnPropertyDescriptorFromExpando(
73 JSContext* cx, HandleObject proxy, HandleId id,
74 MutableHandle<mozilla::Maybe<PropertyDescriptor>> desc) {
75 RootedObject expando(cx, proxy->as<ProxyObject>().expando().toObjectOrNull());
76
77 if (!expando) {
78 return true;
79 }
80
81 return GetOwnPropertyDescriptor(cx, expando, id, desc);
82 }
83
84 static bool ProxyGetOnExpando(JSContext* cx, HandleObject proxy,
85 HandleValue receiver, HandleId id,
86 MutableHandleValue vp) {
87 // For BaseProxyHandler, private names are stored in the expando object.
88 RootedObject expando(cx, proxy->as<ProxyObject>().expando().toObjectOrNull());
89
90 // We must have the expando, or GetPrivateElemOperation didn't call
91 // hasPrivate first.
92 if (!expando) {
93 JS_ReportErrorNumberASCII(cx, GetErrorMessage, nullptr,
94 JSMSG_GET_MISSING_PRIVATE);
95 return false;
96 }
97
98 // Because we controlled the creation of the expando, we know it's not a
99 // proxy, and so can safely call internal methods on it without worrying about
100 // exposing information about private names.
101 Rooted<mozilla::Maybe<PropertyDescriptor>> desc(cx);
102 if (!GetOwnPropertyDescriptor(cx, expando, id, &desc)) {
103 return false;
104 }
105 // We must have the object, same reasoning as the expando.
106 if (desc.isNothing()) {
107 JS_ReportErrorNumberASCII(cx, GetErrorMessage, nullptr,
108 JSMSG_SET_MISSING_PRIVATE);
109 return false;
110 }
111
112 // If the private name has a getter, delegate to that.
113 if (desc->hasGetter()) {
114 RootedValue getter(cx, JS::ObjectValue(*desc->getter()));
115 return js::CallGetter(cx, receiver, getter, vp);
116 }
117
118 MOZ_ASSERT(desc->hasValue());
119 MOZ_ASSERT(desc->isDataDescriptor());
120
121 vp.set(desc->value());
122 return true;
123 }
124
125 static bool ProxyHasOnExpando(JSContext* cx, HandleObject proxy, HandleId id,
126 bool* bp) {
127 // For BaseProxyHandler, private names are stored in the expando object.
128 RootedObject expando(cx, proxy->as<ProxyObject>().expando().toObjectOrNull());
129
130 // If there is no expando object, then there is no private field.
131 if (!expando) {
132 *bp = false;
133 return true;
134 }
135
136 return HasOwnProperty(cx, expando, id, bp);
137 }
138
139 static bool ProxyDefineOnExpando(JSContext* cx, HandleObject proxy, HandleId id,
140 Handle<PropertyDescriptor> desc,
141 ObjectOpResult& result) {
142 MOZ_ASSERT(id.isPrivateName());
143
144 // For BaseProxyHandler, private names are stored in the expando object.
145 RootedObject expando(cx, proxy->as<ProxyObject>().expando().toObjectOrNull());
146
147 if (!expando) {
148 expando = NewPlainObjectWithProto(cx, nullptr);
149 if (!expando) {
150 return false;
151 }
152
153 proxy->as<ProxyObject>().setExpando(expando);
154 }
155
156 return DefineProperty(cx, expando, id, desc, result);
157 }
158
159 void js::AutoEnterPolicy::reportErrorIfExceptionIsNotPending(JSContext* cx,
160 HandleId id) {
161 if (JS_IsExceptionPending(cx)) {
162 return;
163 }
164
165 if (id.isVoid()) {
166 ReportAccessDenied(cx);
167 } else {
168 Throw(cx, id, JSMSG_PROPERTY_ACCESS_DENIED);
169 }
170 }
171
172 #ifdef DEBUG
173 void js::AutoEnterPolicy::recordEnter(JSContext* cx, HandleObject proxy,
174 HandleId id, Action act) {
175 if (allowed()) {
176 context = cx;
177 enteredProxy.emplace(proxy);
178 enteredId.emplace(id);
179 enteredAction = act;
180 prev = cx->enteredPolicy;
181 cx->enteredPolicy = this;
182 }
183 }
184
185 void js::AutoEnterPolicy::recordLeave() {
186 if (enteredProxy) {
187 MOZ_ASSERT(context->enteredPolicy == this);
188 context->enteredPolicy = prev;
189 }
190 }
191
192 JS_PUBLIC_API void js::assertEnteredPolicy(JSContext* cx, JSObject* proxy,
193 jsid id,
194 BaseProxyHandler::Action act) {
195 MOZ_ASSERT(proxy->is<ProxyObject>());
196 MOZ_ASSERT(cx->enteredPolicy);
197 MOZ_ASSERT(cx->enteredPolicy->enteredProxy->get() == proxy);
198 MOZ_ASSERT(cx->enteredPolicy->enteredId->get() == id);
199 MOZ_ASSERT(cx->enteredPolicy->enteredAction & act);
200 }
201 #endif
202
203 bool Proxy::getOwnPropertyDescriptor(
204 JSContext* cx, HandleObject proxy, HandleId id,
205 MutableHandle<mozilla::Maybe<PropertyDescriptor>> desc) {
206 AutoCheckRecursionLimit recursion(cx);
207 if (!recursion.check(cx)) {
208 return false;
209 }
210 const BaseProxyHandler* handler = proxy->as<ProxyObject>().handler();
211 desc.reset(); // default result if we refuse to perform this action
212 AutoEnterPolicy policy(cx, handler, proxy, id,
213 BaseProxyHandler::GET_PROPERTY_DESCRIPTOR, true);
214 if (!policy.allowed()) {
215 return policy.returnValue();
216 }
217
218 if (handler->useProxyExpandoObjectForPrivateFields() && id.isPrivateName()) {
219 return ProxyGetOwnPropertyDescriptorFromExpando(cx, proxy, id, desc);
220 }
221 return handler->getOwnPropertyDescriptor(cx, proxy, id, desc);
222 }
223
224 bool Proxy::defineProperty(JSContext* cx, HandleObject proxy, HandleId id,
225 Handle<PropertyDescriptor> desc,
226 ObjectOpResult& result) {
227 AutoCheckRecursionLimit recursion(cx);
228 if (!recursion.check(cx)) {
229 return false;
230 }
231 const BaseProxyHandler* handler = proxy->as<ProxyObject>().handler();
232
233 // We shouldn't be definining a private field if we are supposed to throw;
234 // this ought to have been caught by CheckPrivateField.
235 MOZ_ASSERT_IF(id.isPrivateName(), !handler->throwOnPrivateField());
236
237 AutoEnterPolicy policy(cx, handler, proxy, id, BaseProxyHandler::SET, true);
238 if (!policy.allowed()) {
239 if (!policy.returnValue()) {
240 return false;
241 }
242 return result.succeed();
243 }
244
245 // Private field accesses have different semantics depending on the kind
246 // of proxy involved, and so take a different path compared to regular
247 // [[Get]] operations. For example, scripted handlers don't fire traps
248 // when accessing private fields (because of the WeakMap semantics)
249 if (id.isPrivateName() && handler->useProxyExpandoObjectForPrivateFields()) {
250 return ProxyDefineOnExpando(cx, proxy, id, desc, result);
251 }
252
253 return proxy->as<ProxyObject>().handler()->defineProperty(cx, proxy, id, desc,
254 result);
255 }
256
257 bool Proxy::ownPropertyKeys(JSContext* cx, HandleObject proxy,
258 MutableHandleIdVector props) {
259 AutoCheckRecursionLimit recursion(cx);
260 if (!recursion.check(cx)) {
261 return false;
262 }
263 const BaseProxyHandler* handler = proxy->as<ProxyObject>().handler();
264 AutoEnterPolicy policy(cx, handler, proxy, JS::VoidHandlePropertyKey,
265 BaseProxyHandler::ENUMERATE, true);
266 if (!policy.allowed()) {
267 return policy.returnValue();
268 }
269 return proxy->as<ProxyObject>().handler()->ownPropertyKeys(cx, proxy, props);
270 }
271
272 bool Proxy::delete_(JSContext* cx, HandleObject proxy, HandleId id,
273 ObjectOpResult& result) {
274 AutoCheckRecursionLimit recursion(cx);
275 if (!recursion.check(cx)) {
276 return false;
277 }
278 const BaseProxyHandler* handler = proxy->as<ProxyObject>().handler();
279 AutoEnterPolicy policy(cx, handler, proxy, id, BaseProxyHandler::SET, true);
280 if (!policy.allowed()) {
281 bool ok = policy.returnValue();
282 if (ok) {
283 result.succeed();
284 }
285 return ok;
286 }
287
288 // Private names shouldn't take this path, as deleting a private name
289 // should be a syntax error.
290 MOZ_ASSERT(!id.isPrivateName());
291
292 return proxy->as<ProxyObject>().handler()->delete_(cx, proxy, id, result);
293 }
294
295 JS_PUBLIC_API bool js::AppendUnique(JSContext* cx, MutableHandleIdVector base,
296 HandleIdVector others) {
297 RootedIdVector uniqueOthers(cx);
298 if (!uniqueOthers.reserve(others.length())) {
299 return false;
300 }
301 for (size_t i = 0; i < others.length(); ++i) {
302 bool unique = true;
303 for (size_t j = 0; j < base.length(); ++j) {
304 if (others[i].get() == base[j]) {
305 unique = false;
306 break;
307 }
308 }
309 if (unique) {
310 if (!uniqueOthers.append(others[i])) {
311 return false;
312 }
313 }
314 }
315 return base.appendAll(std::move(uniqueOthers));
316 }
317
318 /* static */
319 bool Proxy::getPrototype(JSContext* cx, HandleObject proxy,
320 MutableHandleObject proto) {
321 MOZ_ASSERT(proxy->hasDynamicPrototype());
322 AutoCheckRecursionLimit recursion(cx);
323 if (!recursion.check(cx)) {
324 return false;
325 }
326 return proxy->as<ProxyObject>().handler()->getPrototype(cx, proxy, proto);
327 }
328
329 /* static */
330 bool Proxy::setPrototype(JSContext* cx, HandleObject proxy, HandleObject proto,
331 ObjectOpResult& result) {
332 MOZ_ASSERT(proxy->hasDynamicPrototype());
333 AutoCheckRecursionLimit recursion(cx);
334 if (!recursion.check(cx)) {
335 return false;
336 }
337 return proxy->as<ProxyObject>().handler()->setPrototype(cx, proxy, proto,
338 result);
339 }
340
341 /* static */
342 bool Proxy::getPrototypeIfOrdinary(JSContext* cx, HandleObject proxy,
343 bool* isOrdinary,
344 MutableHandleObject proto) {
345 AutoCheckRecursionLimit recursion(cx);
346 if (!recursion.check(cx)) {
347 return false;
348 }
349 return proxy->as<ProxyObject>().handler()->getPrototypeIfOrdinary(
350 cx, proxy, isOrdinary, proto);
351 }
352
353 /* static */
354 bool Proxy::setImmutablePrototype(JSContext* cx, HandleObject proxy,
355 bool* succeeded) {
356 AutoCheckRecursionLimit recursion(cx);
357 if (!recursion.check(cx)) {
358 return false;
359 }
360 const BaseProxyHandler* handler = proxy->as<ProxyObject>().handler();
361 return handler->setImmutablePrototype(cx, proxy, succeeded);
362 }
363
364 /* static */
365 bool Proxy::preventExtensions(JSContext* cx, HandleObject proxy,
366 ObjectOpResult& result) {
367 AutoCheckRecursionLimit recursion(cx);
368 if (!recursion.check(cx)) {
369 return false;
370 }
371 const BaseProxyHandler* handler = proxy->as<ProxyObject>().handler();
372 return handler->preventExtensions(cx, proxy, result);
373 }
374
375 /* static */
376 bool Proxy::isExtensible(JSContext* cx, HandleObject proxy, bool* extensible) {
377 AutoCheckRecursionLimit recursion(cx);
378 if (!recursion.check(cx)) {
379 return false;
380 }
381 return proxy->as<ProxyObject>().handler()->isExtensible(cx, proxy,
382 extensible);
383 }
384
385 bool Proxy::has(JSContext* cx, HandleObject proxy, HandleId id, bool* bp) {
386 AutoCheckRecursionLimit recursion(cx);
387 if (!recursion.check(cx)) {
388 return false;
389 }
390 const BaseProxyHandler* handler = proxy->as<ProxyObject>().handler();
391 *bp = false; // default result if we refuse to perform this action
392 AutoEnterPolicy policy(cx, handler, proxy, id, BaseProxyHandler::GET, true);
393 if (!policy.allowed()) {
394 return policy.returnValue();
395 }
396
397 // Private names shouldn't take this path, but only hasOwn;
398 MOZ_ASSERT(!id.isPrivateName());
399
400 if (handler->hasPrototype()) {
401 if (!handler->hasOwn(cx, proxy, id, bp)) {
402 return false;
403 }
404 if (*bp) {
405 return true;
406 }
407
408 RootedObject proto(cx);
409 if (!GetPrototype(cx, proxy, &proto)) {
410 return false;
411 }
412 if (!proto) {
413 return true;
414 }
415
416 return HasProperty(cx, proto, id, bp);
417 }
418
419 return handler->has(cx, proxy, id, bp);
420 }
421
422 bool js::ProxyHas(JSContext* cx, HandleObject proxy, HandleValue idVal,
423 bool* result) {
424 RootedId id(cx);
425 if (!ToPropertyKey(cx, idVal, &id)) {
426 return false;
427 }
428 if (MOZ_UNLIKELY(!proxy->is<ProxyObject>())) {
429 return HasProperty(cx, proxy, id, result);
430 }
431 return Proxy::has(cx, proxy, id, result);
432 }
433
434 bool Proxy::hasOwn(JSContext* cx, HandleObject proxy, HandleId id, bool* bp) {
435 AutoCheckRecursionLimit recursion(cx);
436 if (!recursion.check(cx)) {
437 return false;
438 }
439 const BaseProxyHandler* handler = proxy->as<ProxyObject>().handler();
440 *bp = false; // default result if we refuse to perform this action
441
442 // If the handler is supposed to throw, we'll never have a private field so
443 // simply return, as we shouldn't throw an invalid security error when
444 // checking for the presence of a private field (WeakMap model).
445 if (id.isPrivateName() && handler->throwOnPrivateField()) {
446 return true;
447 }
448
449 AutoEnterPolicy policy(cx, handler, proxy, id, BaseProxyHandler::GET, true);
450 if (!policy.allowed()) {
451 return policy.returnValue();
452 }
453
454 // Private field accesses have different semantics depending on the kind
455 // of proxy involved, and so take a different path compared to regular
456 // [[Get]] operations. For example, scripted handlers don't fire traps
457 // when accessing private fields (because of the WeakMap semantics)
458 if (id.isPrivateName() && handler->useProxyExpandoObjectForPrivateFields()) {
459 return ProxyHasOnExpando(cx, proxy, id, bp);
460 }
461
462 return handler->hasOwn(cx, proxy, id, bp);
463 }
464
465 bool js::ProxyHasOwn(JSContext* cx, HandleObject proxy, HandleValue idVal,
466 bool* result) {
467 RootedId id(cx);
468 if (!ToPropertyKey(cx, idVal, &id)) {
469 return false;
470 }
471 if (MOZ_UNLIKELY(!proxy->is<ProxyObject>())) {
472 return HasOwnProperty(cx, proxy, id, result);
473 }
474 return Proxy::hasOwn(cx, proxy, id, result);
475 }
476
477 static MOZ_ALWAYS_INLINE Value ValueToWindowProxyIfWindow(const Value& v,
478 JSObject* proxy) {
479 if (v.isObject() && v != ObjectValue(*proxy)) {
480 return ObjectValue(*ToWindowProxyIfWindow(&v.toObject()));
481 }
482 return v;
483 }
484
485 MOZ_ALWAYS_INLINE bool Proxy::getInternal(JSContext* cx, HandleObject proxy,
486 HandleValue receiver, HandleId id,
487 MutableHandleValue vp) {
488 MOZ_ASSERT_IF(receiver.isObject(), !IsWindow(&receiver.toObject()));
489
490 AutoCheckRecursionLimit recursion(cx);
491 if (!recursion.check(cx)) {
492 return false;
493 }
494 const BaseProxyHandler* handler = proxy->as<ProxyObject>().handler();
495
496 // Shouldn't have gotten here, as this should have been caught earlier.
497 MOZ_ASSERT_IF(id.isPrivateName(), !handler->throwOnPrivateField());
498
499 vp.setUndefined(); // default result if we refuse to perform this action
500 AutoEnterPolicy policy(cx, handler, proxy, id, BaseProxyHandler::GET, true);
501 if (!policy.allowed()) {
502 return policy.returnValue();
503 }
504
505 // Private field accesses have different semantics depending on the kind
506 // of proxy involved, and so take a different path compared to regular
507 // [[Get]] operations. For example, scripted handlers don't fire traps
508 // when accessing private fields (because of the WeakMap semantics)
509 if (id.isPrivateName() && handler->useProxyExpandoObjectForPrivateFields()) {
510 return ProxyGetOnExpando(cx, proxy, receiver, id, vp);
511 }
512
513 if (handler->hasPrototype()) {
514 bool own;
515 if (!handler->hasOwn(cx, proxy, id, &own)) {
516 return false;
517 }
518 if (!own) {
519 RootedObject proto(cx);
520 if (!GetPrototype(cx, proxy, &proto)) {
521 return false;
522 }
523 if (!proto) {
524 return true;
525 }
526 return GetProperty(cx, proto, receiver, id, vp);
527 }
528 }
529
530 return handler->get(cx, proxy, receiver, id, vp);
531 }
532
533 bool Proxy::get(JSContext* cx, HandleObject proxy, HandleValue receiver_,
534 HandleId id, MutableHandleValue vp) {
535 // Use the WindowProxy as receiver if receiver_ is a Window. Proxy handlers
536 // shouldn't have to know about the Window/WindowProxy distinction.
537 RootedValue receiver(cx, ValueToWindowProxyIfWindow(receiver_, proxy));
538 return getInternal(cx, proxy, receiver, id, vp);
539 }
540
541 bool js::ProxyGetProperty(JSContext* cx, HandleObject proxy, HandleId id,
542 MutableHandleValue vp) {
543 RootedValue receiver(cx, ObjectValue(*proxy));
544 return Proxy::getInternal(cx, proxy, receiver, id, vp);
545 }
546
547 bool js::ProxyGetPropertyByValue(JSContext* cx, HandleObject proxy,
548 HandleValue idVal, MutableHandleValue vp) {
549 RootedId id(cx);
550 if (!ToPropertyKey(cx, idVal, &id)) {
551 return false;
552 }
553
554 RootedValue receiver(cx, ObjectValue(*proxy));
555 if (MOZ_UNLIKELY(!proxy->is<ProxyObject>())) {
556 return GetProperty(cx, proxy, receiver, id, vp);
557 }
558 return Proxy::getInternal(cx, proxy, receiver, id, vp);
559 }
560
561 MOZ_ALWAYS_INLINE bool Proxy::setInternal(JSContext* cx, HandleObject proxy,
562 HandleId id, HandleValue v,
563 HandleValue receiver,
564 ObjectOpResult& result) {
565 MOZ_ASSERT_IF(receiver.isObject(), !IsWindow(&receiver.toObject()));
566
567 AutoCheckRecursionLimit recursion(cx);
568 if (!recursion.check(cx)) {
569 return false;
570 }
571
572 const BaseProxyHandler* handler = proxy->as<ProxyObject>().handler();
573
574 // Should have been handled already.
575 MOZ_ASSERT_IF(id.isPrivateName(), !handler->throwOnPrivateField());
576
577 AutoEnterPolicy policy(cx, handler, proxy, id, BaseProxyHandler::SET, true);
578 if (!policy.allowed()) {
579 if (!policy.returnValue()) {
580 return false;
581 }
582 return result.succeed();
583 }
584
585 // Private field accesses have different semantics depending on the kind
586 // of proxy involved, and so take a different path compared to regular
587 // [[Set]] operations.
588 //
589 // This doesn't interact with hasPrototype, as PrivateFields are always
590 // own propertiers, and so we never deal with prototype traversals.
591 if (id.isPrivateName() && handler->useProxyExpandoObjectForPrivateFields()) {
592 return ProxySetOnExpando(cx, proxy, id, v, receiver, result);
593 }
594
595 // Special case. See the comment on BaseProxyHandler::mHasPrototype.
596 if (handler->hasPrototype()) {
597 return handler->BaseProxyHandler::set(cx, proxy, id, v, receiver, result);
598 }
599
600 return handler->set(cx, proxy, id, v, receiver, result);
601 }
602
603 bool Proxy::set(JSContext* cx, HandleObject proxy, HandleId id, HandleValue v,
604 HandleValue receiver_, ObjectOpResult& result) {
605 // Use the WindowProxy as receiver if receiver_ is a Window. Proxy handlers
606 // shouldn't have to know about the Window/WindowProxy distinction.
607 RootedValue receiver(cx, ValueToWindowProxyIfWindow(receiver_, proxy));
608 return setInternal(cx, proxy, id, v, receiver, result);
609 }
610
611 bool js::ProxySetProperty(JSContext* cx, HandleObject proxy, HandleId id,
612 HandleValue val, bool strict) {
613 ObjectOpResult result;
614 RootedValue receiver(cx, ObjectValue(*proxy));
615 if (!Proxy::setInternal(cx, proxy, id, val, receiver, result)) {
616 return false;
617 }
618 return result.checkStrictModeError(cx, proxy, id, strict);
619 }
620
621 bool js::ProxySetPropertyByValue(JSContext* cx, HandleObject proxy,
622 HandleValue idVal, HandleValue val,
623 bool strict) {
624 RootedId id(cx);
625 if (!ToPropertyKey(cx, idVal, &id)) {
626 return false;
627 }
628
629 ObjectOpResult result;
630 RootedValue receiver(cx, ObjectValue(*proxy));
631 if (MOZ_UNLIKELY(!proxy->is<ProxyObject>())) {
632 if (!SetProperty(cx, proxy, id, val, receiver, result)) {
633 return false;
634 }
635 } else if (!Proxy::setInternal(cx, proxy, id, val, receiver, result)) {
636 return false;
637 }
638 return result.checkStrictModeError(cx, proxy, id, strict);
639 }
640
641 bool Proxy::getOwnEnumerablePropertyKeys(JSContext* cx, HandleObject proxy,
642 MutableHandleIdVector props) {
643 AutoCheckRecursionLimit recursion(cx);
644 if (!recursion.check(cx)) {
645 return false;
646 }
647 const BaseProxyHandler* handler = proxy->as<ProxyObject>().handler();
648 AutoEnterPolicy policy(cx, handler, proxy, JS::VoidHandlePropertyKey,
649 BaseProxyHandler::ENUMERATE, true);
650 if (!policy.allowed()) {
651 return policy.returnValue();
652 }
653 return handler->getOwnEnumerablePropertyKeys(cx, proxy, props);
654 }
655
656 bool Proxy::enumerate(JSContext* cx, HandleObject proxy,
657 MutableHandleIdVector props) {
658 AutoCheckRecursionLimit recursion(cx);
659 if (!recursion.check(cx)) {
660 return false;
661 }
662
663 const BaseProxyHandler* handler = proxy->as<ProxyObject>().handler();
664 if (handler->hasPrototype()) {
665 if (!Proxy::getOwnEnumerablePropertyKeys(cx, proxy, props)) {
666 return false;
667 }
668
669 RootedObject proto(cx);
670 if (!GetPrototype(cx, proxy, &proto)) {
671 return false;
672 }
673 if (!proto) {
674 return true;
675 }
676
677 cx->check(proxy, proto);
678
679 RootedIdVector protoProps(cx);
680 if (!GetPropertyKeys(cx, proto, 0, &protoProps)) {
681 return false;
682 }
683 return AppendUnique(cx, props, protoProps);
684 }
685
686 AutoEnterPolicy policy(cx, handler, proxy, JS::VoidHandlePropertyKey,
687 BaseProxyHandler::ENUMERATE, true);
688
689 // If the policy denies access but wants us to return true, we need
690 // to return an empty |props| list.
691 if (!policy.allowed()) {
692 MOZ_ASSERT(props.empty());
693 return policy.returnValue();
694 }
695
696 return handler->enumerate(cx, proxy, props);
697 }
698
699 bool Proxy::call(JSContext* cx, HandleObject proxy, const CallArgs& args) {
700 AutoCheckRecursionLimit recursion(cx);
701 if (!recursion.check(cx)) {
702 return false;
703 }
704 const BaseProxyHandler* handler = proxy->as<ProxyObject>().handler();
705
706 // Because vp[0] is JS_CALLEE on the way in and JS_RVAL on the way out, we
707 // can only set our default value once we're sure that we're not calling the
708 // trap.
709 AutoEnterPolicy policy(cx, handler, proxy, JS::VoidHandlePropertyKey,
710 BaseProxyHandler::CALL, true);
711 if (!policy.allowed()) {
712 args.rval().setUndefined();
713 return policy.returnValue();
714 }
715
716 return handler->call(cx, proxy, args);
717 }
718
719 bool Proxy::construct(JSContext* cx, HandleObject proxy, const CallArgs& args) {
720 AutoCheckRecursionLimit recursion(cx);
721 if (!recursion.check(cx)) {
722 return false;
723 }
724 const BaseProxyHandler* handler = proxy->as<ProxyObject>().handler();
725
726 // Because vp[0] is JS_CALLEE on the way in and JS_RVAL on the way out, we
727 // can only set our default value once we're sure that we're not calling the
728 // trap.
729 AutoEnterPolicy policy(cx, handler, proxy, JS::VoidHandlePropertyKey,
730 BaseProxyHandler::CALL, true);
731 if (!policy.allowed()) {
732 args.rval().setUndefined();
733 return policy.returnValue();
734 }
735
736 return handler->construct(cx, proxy, args);
737 }
738
739 bool Proxy::nativeCall(JSContext* cx, IsAcceptableThis test, NativeImpl impl,
740 const CallArgs& args) {
741 AutoCheckRecursionLimit recursion(cx);
742 if (!recursion.check(cx)) {
743 return false;
744 }
745 RootedObject proxy(cx, &args.thisv().toObject());
746 // Note - we don't enter a policy here because our security architecture
747 // guards against nativeCall by overriding the trap itself in the right
748 // circumstances.
749 return proxy->as<ProxyObject>().handler()->nativeCall(cx, test, impl, args);
750 }
751
752 bool Proxy::getBuiltinClass(JSContext* cx, HandleObject proxy, ESClass* cls) {
753 AutoCheckRecursionLimit recursion(cx);
754 if (!recursion.check(cx)) {
755 return false;
756 }
757 return proxy->as<ProxyObject>().handler()->getBuiltinClass(cx, proxy, cls);
758 }
759
760 bool Proxy::isArray(JSContext* cx, HandleObject proxy,
761 JS::IsArrayAnswer* answer) {
762 AutoCheckRecursionLimit recursion(cx);
763 if (!recursion.check(cx)) {
764 return false;
765 }
766 return proxy->as<ProxyObject>().handler()->isArray(cx, proxy, answer);
767 }
768
769 const char* Proxy::className(JSContext* cx, HandleObject proxy) {
770 // Check for unbounded recursion, but don't signal an error; className
771 // needs to be infallible.
772 AutoCheckRecursionLimit recursion(cx);
773 if (!recursion.checkDontReport(cx)) {
774 return "too much recursion";
775 }
776
777 const BaseProxyHandler* handler = proxy->as<ProxyObject>().handler();
778 AutoEnterPolicy policy(cx, handler, proxy, JS::VoidHandlePropertyKey,
779 BaseProxyHandler::GET, /* mayThrow = */ false);
780 // Do the safe thing if the policy rejects.
781 if (!policy.allowed()) {
782 return handler->BaseProxyHandler::className(cx, proxy);
783 }
784 return handler->className(cx, proxy);
785 }
786
787 JSString* Proxy::fun_toString(JSContext* cx, HandleObject proxy,
788 bool isToSource) {
789 AutoCheckRecursionLimit recursion(cx);
790 if (!recursion.check(cx)) {
791 return nullptr;
792 }
793 const BaseProxyHandler* handler = proxy->as<ProxyObject>().handler();
794 AutoEnterPolicy policy(cx, handler, proxy, JS::VoidHandlePropertyKey,
795 BaseProxyHandler::GET, /* mayThrow = */ false);
796 // Do the safe thing if the policy rejects.
797 if (!policy.allowed()) {
798 return handler->BaseProxyHandler::fun_toString(cx, proxy, isToSource);
799 }
800 return handler->fun_toString(cx, proxy, isToSource);
801 }
802
803 RegExpShared* Proxy::regexp_toShared(JSContext* cx, HandleObject proxy) {
804 AutoCheckRecursionLimit recursion(cx);
805 if (!recursion.check(cx)) {
806 return nullptr;
807 }
808 return proxy->as<ProxyObject>().handler()->regexp_toShared(cx, proxy);
809 }
810
811 bool Proxy::boxedValue_unbox(JSContext* cx, HandleObject proxy,
812 MutableHandleValue vp) {
813 AutoCheckRecursionLimit recursion(cx);
814 if (!recursion.check(cx)) {
815 return false;
816 }
817 return proxy->as<ProxyObject>().handler()->boxedValue_unbox(cx, proxy, vp);
818 }
819
820 JSObject* const TaggedProto::LazyProto = reinterpret_cast<JSObject*>(0x1);
821
822 /* static */
823 bool Proxy::getElements(JSContext* cx, HandleObject proxy, uint32_t begin,
824 uint32_t end, ElementAdder* adder) {
825 AutoCheckRecursionLimit recursion(cx);
826 if (!recursion.check(cx)) {
827 return false;
828 }
829 const BaseProxyHandler* handler = proxy->as<ProxyObject>().handler();
830 AutoEnterPolicy policy(cx, handler, proxy, JS::VoidHandlePropertyKey,
831 BaseProxyHandler::GET,
832 /* mayThrow = */ true);
833 if (!policy.allowed()) {
834 if (policy.returnValue()) {
835 MOZ_ASSERT(!cx->isExceptionPending());
836 return js::GetElementsWithAdder(cx, proxy, proxy, begin, end, adder);
837 }
838 return false;
839 }
840 return handler->getElements(cx, proxy, begin, end, adder);
841 }
842
843 /* static */
844 void Proxy::trace(JSTracer* trc, JSObject* proxy) {
845 const BaseProxyHandler* handler = proxy->as<ProxyObject>().handler();
846 handler->trace(trc, proxy);
847 }
848
849 static bool proxy_LookupProperty(JSContext* cx, HandleObject obj, HandleId id,
850 MutableHandleObject objp,
851 PropertyResult* propp) {
852 bool found;
853 if (!Proxy::has(cx, obj, id, &found)) {
854 return false;
855 }
856
857 if (found) {
858 propp->setProxyProperty();
859 objp.set(obj);
860 } else {
861 propp->setNotFound();
862 objp.set(nullptr);
863 }
864 return true;
865 }
866
867 static bool proxy_DeleteProperty(JSContext* cx, HandleObject obj, HandleId id,
868 ObjectOpResult& result) {
869 if (!Proxy::delete_(cx, obj, id, result)) {
870 return false;
871 }
872 return SuppressDeletedProperty(cx, obj, id); // XXX is this necessary?
873 }
874
875 /* static */
876 void ProxyObject::traceEdgeToTarget(JSTracer* trc, ProxyObject* obj) {
877 TraceCrossCompartmentEdge(trc, obj, obj->slotOfPrivate(), "proxy target");
878 }
879
880 #ifdef DEBUG
881 static inline void CheckProxyIsInCCWMap(ProxyObject* proxy) {
882 if (proxy->zone()->isGCCompacting()) {
883 // Skip this check during compacting GC since objects' object groups may be
884 // forwarded. It's not impossible to make this work, but requires adding a
885 // parallel lookupWrapper() path for this one case.
886 return;
887 }
888
889 JSObject* referent = MaybeForwarded(proxy->target());
890 if (referent->compartment() != proxy->compartment()) {
891 // Assert that this proxy is tracked in the wrapper map. We maintain the
892 // invariant that the wrapped object is the key in the wrapper map.
893 ObjectWrapperMap::Ptr p = proxy->compartment()->lookupWrapper(referent);
894 MOZ_ASSERT(p);
895 MOZ_ASSERT(*p->value().unsafeGet() == proxy);
896 }
897 }
898 #endif
899
900 /* static */
901 void ProxyObject::trace(JSTracer* trc, JSObject* obj) {
902 ProxyObject* proxy = &obj->as<ProxyObject>();
903
904 TraceNullableEdge(trc, proxy->slotOfExpando(), "expando");
905
906 #ifdef DEBUG
907 JSContext* cx = TlsContext.get();
908 if (cx && cx->isStrictProxyCheckingEnabled() && proxy->is<WrapperObject>()) {
909 CheckProxyIsInCCWMap(proxy);
910 }
911 #endif
912
913 // Note: If you add new slots here, make sure to change
914 // nuke() to cope.
915
916 traceEdgeToTarget(trc, proxy);
917
918 size_t nreserved = proxy->numReservedSlots();
919 for (size_t i = 0; i < nreserved; i++) {
920 /*
921 * The GC can use the second reserved slot to link the cross compartment
922 * wrappers into a linked list, in which case we don't want to trace it.
923 */
924 if (proxy->is<CrossCompartmentWrapperObject>() &&
925 i == CrossCompartmentWrapperObject::GrayLinkReservedSlot) {
926 continue;
927 }
928 TraceEdge(trc, proxy->reservedSlotPtr(i), "proxy_reserved");
929 }
930
931 Proxy::trace(trc, obj);
932 }
933
934 static void proxy_Finalize(JS::GCContext* gcx, JSObject* obj) {
935 // Suppress a bogus warning about finalize().
936 JS::AutoSuppressGCAnalysis nogc;
937
938 MOZ_ASSERT(obj->is<ProxyObject>());
939 ProxyObject* proxy = &obj->as<ProxyObject>();
940 proxy->handler()->finalize(gcx, obj);
941
942 if (!proxy->usingInlineValueArray() && proxy->isTenured()) {
943 auto* valArray = js::detail::GetProxyDataLayout(obj)->values();
944 size_t size =
945 js::detail::ProxyValueArray::sizeOf(proxy->numReservedSlots());
946 gcx->free_(obj, valArray, size, MemoryUse::ProxyExternalValueArray);
947 }
948 }
949
950 size_t js::proxy_ObjectMoved(JSObject* obj, JSObject* old) {
951 ProxyObject& proxy = obj->as<ProxyObject>();
952
953 if (IsInsideNursery(old)) {
954 proxy.nurseryProxyTenured(&old->as<ProxyObject>());
955 }
956
957 return proxy.handler()->objectMoved(obj, old);
958 }
959
960 void ProxyObject::nurseryProxyTenured(ProxyObject* old) {
961 if (old->usingInlineValueArray()) {
962 setInlineValueArray();
963 return;
964 }
965
966 Nursery& nursery = runtimeFromMainThread()->gc.nursery();
967 nursery.removeMallocedBufferDuringMinorGC(data.values());
968
969 size_t size = detail::ProxyValueArray::sizeOf(numReservedSlots());
970 AddCellMemory(this, size, MemoryUse::ProxyExternalValueArray);
971 }
972
973 const JSClassOps js::ProxyClassOps = {
974 nullptr, // addProperty
975 nullptr, // delProperty
976 nullptr, // enumerate
977 nullptr, // newEnumerate
978 nullptr, // resolve
979 nullptr, // mayResolve
980 proxy_Finalize, // finalize
981 nullptr, // call
982 nullptr, // construct
983 ProxyObject::trace, // trace
984 };
985
986 const ClassExtension js::ProxyClassExtension = {
987 proxy_ObjectMoved, // objectMovedOp
988 };
989
990 const ObjectOps js::ProxyObjectOps = {
991 proxy_LookupProperty, // lookupProperty
992 Proxy::defineProperty, // defineProperty
993 Proxy::has, // hasProperty
994 Proxy::get, // getProperty
995 Proxy::set, // setProperty
996 Proxy::getOwnPropertyDescriptor, // getOwnPropertyDescriptor
997 proxy_DeleteProperty, // deleteProperty
998 Proxy::getElements, // getElements
999 Proxy::fun_toString, // funToString
1000 };
1001
1002 static const JSFunctionSpec proxy_static_methods[] = {
1003 JS_FN("revocable", proxy_revocable, 2, 0),
1004 JS_FS_END,
1005 };
1006
1007 static const ClassSpec ProxyClassSpec = {
1008 GenericCreateConstructor<js::proxy, 2, gc::AllocKind::FUNCTION>,
1009 nullptr,
1010 proxy_static_methods,
1011 nullptr,
1012 };
1013
1014 const JSClass js::ProxyClass = PROXY_CLASS_DEF_WITH_CLASS_SPEC(
1015 "Proxy",
1016 JSCLASS_HAS_CACHED_PROTO(JSProto_Proxy) | JSCLASS_HAS_RESERVED_SLOTS(2),
1017 &ProxyClassSpec);
1018
1019 JS_PUBLIC_API JSObject* js::NewProxyObject(JSContext* cx,
1020 const BaseProxyHandler* handler,
1021 HandleValue priv, JSObject* proto_,
1022 const ProxyOptions& options) {
1023 AssertHeapIsIdle();
1024 CHECK_THREAD(cx);
1025
1026 // This can be called from the compartment wrap hooks while in a realm with a
1027 // gray global. Trigger the read barrier on the global to ensure this is
1028 // unmarked.
1029 cx->realm()->maybeGlobal();
1030
1031 if (proto_ != TaggedProto::LazyProto) {
1032 cx->check(proto_); // |priv| might be cross-compartment.
1033 }
1034
1035 if (options.lazyProto()) {
1036 MOZ_ASSERT(!proto_);
1037 proto_ = TaggedProto::LazyProto;
1038 }
1039
1040 return ProxyObject::New(cx, handler, priv, TaggedProto(proto_),
1041 options.clasp());
1042 }
1043
1044 void ProxyObject::renew(const BaseProxyHandler* handler, const Value& priv) {
1045 MOZ_ASSERT_IF(IsCrossCompartmentWrapper(this), IsDeadProxyObject(this));
1046 MOZ_ASSERT(getClass() == &ProxyClass);
1047 MOZ_ASSERT(!IsWindowProxy(this));
1048 MOZ_ASSERT(hasDynamicPrototype());
1049
1050 setHandler(handler);
1051
1052 setCrossCompartmentPrivate(priv);
1053 // The post barrier may add a store buffer entry but since this may be called
1054 // on a dying object we don't know if they will survive GC. Therefore we need
1055 // to set a flag to ensure we clear out the nursery before doing any sweeping.
1056 if (isTenured() && zone()->wasGCStarted() && priv.isGCThing() &&
1057 !priv.toGCThing()->isTenured()) {
1058 runtimeFromMainThread()->gc.storeBuffer().setMayHavePointersToDeadCells();
1059 }
1060
1061 for (size_t i = 0; i < numReservedSlots(); i++) {
1062 setReservedSlot(i, UndefinedValue());
1063 }
1064 }
1065
1066 // This implementation of HostEnsureCanAddPrivateElement is designed to work in
1067 // collaboration with Gecko to support the HTML implementation, which applies
1068 // only to Proxy type objects, and as a result we can simply provide proxy
1069 // handlers to correctly match the required semantics.
1070 bool DefaultHostEnsureCanAddPrivateElementCallback(JSContext* cx,
1071 HandleValue val) {
1072 if (!val.isObject()) {
1073 return true;
1074 }
1075
1076 Rooted<JSObject*> valObj(cx, &val.toObject());
1077 if (!IsProxy(valObj)) {
1078 return true;
1079 }
1080
1081 if (GetProxyHandler(valObj)->throwOnPrivateField()) {
1082 JS_ReportErrorNumberASCII(cx, GetErrorMessage, nullptr,
1083 JSMSG_ILLEGAL_PRIVATE_EXOTIC);
1084 return false;
1085 }
1086 return true;
1087 }