Debian Codegraph @

js/src/builtin/Object.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 "builtin/Object.h"
8 #include "js/Object.h" // JS::GetBuiltinClass
9
10 #include "mozilla/Maybe.h"
11 #include "mozilla/Range.h"
12 #include "mozilla/RangedPtr.h"
13
14 #include <algorithm>
15 #include <string_view>
16
17 #include "jsapi.h"
18
19 #include "builtin/Eval.h"
20 #include "builtin/SelfHostingDefines.h"
21 #include "gc/GC.h"
22 #include "jit/InlinableNatives.h"
23 #include "js/friend/ErrorMessages.h" // js::GetErrorMessage, JSMSG_*
24 #include "js/friend/StackLimits.h" // js::AutoCheckRecursionLimit
25 #include "js/PropertySpec.h"
26 #include "js/UniquePtr.h"
27 #include "util/Identifier.h" // js::IsIdentifier
28 #include "util/StringBuilder.h"
29 #include "util/Text.h"
30 #include "vm/BooleanObject.h"
31 #include "vm/DateObject.h"
32 #include "vm/EqualityOperations.h" // js::SameValue
33 #include "vm/ErrorObject.h"
34 #include "vm/Iteration.h"
35 #include "vm/JSContext.h"
36 #include "vm/NumberObject.h"
37 #include "vm/PlainObject.h" // js::PlainObject
38 #include "vm/RegExpObject.h"
39 #include "vm/StringObject.h"
40 #include "vm/StringType.h"
41 #include "vm/ToSource.h" // js::ValueToSource
42 #include "vm/Watchtower.h"
43 #include "vm/GeckoProfiler-inl.h"
44 #include "vm/JSObject-inl.h"
45 #include "vm/NativeObject-inl.h"
46 #include "vm/Shape-inl.h"
47
48 #ifdef FUZZING
49 # include "builtin/TestingFunctions.h"
50 #endif
51
52 using namespace js;
53
54 using mozilla::Maybe;
55 using mozilla::Range;
56 using mozilla::RangedPtr;
57
58 static PlainObject* CreateThis(JSContext* cx, HandleObject newTarget) {
59 RootedObject proto(cx);
60 if (!GetPrototypeFromConstructor(cx, newTarget, JSProto_Object, &proto)) {
61 return nullptr;
62 }
63
64 gc::AllocKind allocKind = NewObjectGCKind();
65
66 if (proto) {
67 return NewPlainObjectWithProtoAndAllocKind(cx, proto, allocKind);
68 }
69 return NewPlainObjectWithAllocKind(cx, allocKind);
70 }
71
72 bool js::obj_construct(JSContext* cx, unsigned argc, Value* vp) {
73 CallArgs args = CallArgsFromVp(argc, vp);
74
75 JSObject* obj;
76 if (args.isConstructing() &&
77 (&args.newTarget().toObject() != &args.callee())) {
78 RootedObject newTarget(cx, &args.newTarget().toObject());
79 obj = CreateThis(cx, newTarget);
80 } else if (args.length() > 0 && !args[0].isNullOrUndefined()) {
81 obj = ToObject(cx, args[0]);
82 } else {
83 /* Make an object whether this was called with 'new' or not. */
84 gc::AllocKind allocKind = NewObjectGCKind();
85 obj = NewPlainObjectWithAllocKind(cx, allocKind);
86 }
87 if (!obj) {
88 return false;
89 }
90
91 args.rval().setObject(*obj);
92 return true;
93 }
94
95 /* ES5 15.2.4.7. */
96 bool js::obj_propertyIsEnumerable(JSContext* cx, unsigned argc, Value* vp) {
97 CallArgs args = CallArgsFromVp(argc, vp);
98
99 HandleValue idValue = args.get(0);
100
101 // As an optimization, provide a fast path when rooting is not necessary and
102 // we can safely retrieve the attributes from the object's shape.
103
104 /* Steps 1-2. */
105 jsid id;
106 if (args.thisv().isObject() && idValue.isPrimitive() &&
107 PrimitiveValueToId<NoGC>(cx, idValue, &id)) {
108 JSObject* obj = &args.thisv().toObject();
109
110 /* Step 3. */
111 PropertyResult prop;
112 if (obj->is<NativeObject>() &&
113 NativeLookupOwnProperty<NoGC>(cx, &obj->as<NativeObject>(), id,
114 &prop)) {
115 /* Step 4. */
116 if (prop.isNotFound()) {
117 args.rval().setBoolean(false);
118 return true;
119 }
120
121 /* Step 5. */
122 JS::PropertyAttributes attrs = GetPropertyAttributes(obj, prop);
123 args.rval().setBoolean(attrs.enumerable());
124 return true;
125 }
126 }
127
128 /* Step 1. */
129 RootedId idRoot(cx);
130 if (!ToPropertyKey(cx, idValue, &idRoot)) {
131 return false;
132 }
133
134 /* Step 2. */
135 RootedObject obj(cx, ToObject(cx, args.thisv()));
136 if (!obj) {
137 return false;
138 }
139
140 /* Step 3. */
141 Rooted<Maybe<PropertyDescriptor>> desc(cx);
142 if (!GetOwnPropertyDescriptor(cx, obj, idRoot, &desc)) {
143 return false;
144 }
145
146 /* Step 4. */
147 if (desc.isNothing()) {
148 args.rval().setBoolean(false);
149 return true;
150 }
151
152 /* Step 5. */
153 args.rval().setBoolean(desc->enumerable());
154 return true;
155 }
156
157 static bool obj_toSource(JSContext* cx, unsigned argc, Value* vp) {
158 AutoJSMethodProfilerEntry pseudoFrame(cx, "Object.prototype", "toSource");
159 CallArgs args = CallArgsFromVp(argc, vp);
160
161 AutoCheckRecursionLimit recursion(cx);
162 if (!recursion.check(cx)) {
163 return false;
164 }
165
166 RootedObject obj(cx, ToObject(cx, args.thisv()));
167 if (!obj) {
168 return false;
169 }
170
171 JSString* str = ObjectToSource(cx, obj);
172 if (!str) {
173 return false;
174 }
175
176 args.rval().setString(str);
177 return true;
178 }
179
180 template <typename CharT>
181 static bool Consume(RangedPtr<const CharT>& s, RangedPtr<const CharT> e,
182 std::string_view chars) {
183 MOZ_ASSERT(s <= e);
184 size_t len = chars.length();
185 if (e - s < len) {
186 return false;
187 }
188 if (!EqualChars(s.get(), chars.data(), len)) {
189 return false;
190 }
191 s += len;
192 return true;
193 }
194
195 template <typename CharT>
196 static bool ConsumeUntil(RangedPtr<const CharT>& s, RangedPtr<const CharT> e,
197 char16_t ch) {
198 MOZ_ASSERT(s <= e);
199 const CharT* result = js_strchr_limit(s.get(), ch, e.get());
200 if (!result) {
201 return false;
202 }
203 s += result - s.get();
204 MOZ_ASSERT(*s == ch);
205 return true;
206 }
207
208 template <typename CharT>
209 static void ConsumeSpaces(RangedPtr<const CharT>& s, RangedPtr<const CharT> e) {
210 while (s < e && *s == ' ') {
211 s++;
212 }
213 }
214
215 /*
216 * Given a function source string, return the offset and length of the part
217 * between '(function $name' and ')'.
218 */
219 template <typename CharT>
220 static bool ArgsAndBodySubstring(Range<const CharT> chars, size_t* outOffset,
221 size_t* outLen) {
222 const RangedPtr<const CharT> start = chars.begin();
223 RangedPtr<const CharT> s = start;
224 RangedPtr<const CharT> e = chars.end();
225
226 if (s == e) {
227 return false;
228 }
229
230 // Remove enclosing parentheses.
231 if (*s == '(' && *(e - 1) == ')') {
232 s++;
233 e--;
234 }
235
236 // Support the following cases, with spaces between tokens:
237 //
238 // -+---------+-+------------+-+-----+-+- [ - <any> - ] - ( -+-
239 // | | | | | | | |
240 // +- async -+ +- function -+ +- * -+ +- <any> - ( ---------+
241 // | |
242 // +- get ------+
243 // | |
244 // +- set ------+
245 //
246 // This accepts some invalid syntax, but we don't care, since it's only
247 // used by the non-standard toSource, and we're doing a best-effort attempt
248 // here.
249
250 (void)Consume(s, e, "async");
251 ConsumeSpaces(s, e);
252 (void)(Consume(s, e, "function") || Consume(s, e, "get") ||
253 Consume(s, e, "set"));
254 ConsumeSpaces(s, e);
255 (void)Consume(s, e, "*");
256 ConsumeSpaces(s, e);
257
258 // Jump over the function's name.
259 if (Consume(s, e, "[")) {
260 if (!ConsumeUntil(s, e, ']')) {
261 return false;
262 }
263 s++; // Skip ']'.
264 ConsumeSpaces(s, e);
265 if (s >= e || *s != '(') {
266 return false;
267 }
268 } else {
269 if (!ConsumeUntil(s, e, '(')) {
270 return false;
271 }
272 }
273
274 MOZ_ASSERT(*s == '(');
275
276 *outOffset = s - start;
277 *outLen = e - s;
278 MOZ_ASSERT(*outOffset + *outLen <= chars.length());
279 return true;
280 }
281
282 enum class PropertyKind { Getter, Setter, Method, Normal };
283
284 JSString* js::ObjectToSource(JSContext* cx, HandleObject obj) {
285 /* If outermost, we need parentheses to be an expression, not a block. */
286 bool outermost = cx->cycleDetectorVector().empty();
287
288 AutoCycleDetector detector(cx, obj);
289 if (!detector.init()) {
290 return nullptr;
291 }
292 if (detector.foundCycle()) {
293 return NewStringCopyZ<CanGC>(cx, "{}");
294 }
295
296 JSStringBuilder buf(cx);
297 if (outermost && !buf.append('(')) {
298 return nullptr;
299 }
300 if (!buf.append('{')) {
301 return nullptr;
302 }
303
304 RootedIdVector idv(cx);
305 if (!GetPropertyKeys(cx, obj, JSITER_OWNONLY | JSITER_SYMBOLS, &idv)) {
306 return nullptr;
307 }
308
309 bool comma = false;
310
311 auto AddProperty = [cx, &comma, &buf](HandleId id, HandleValue val,
312 PropertyKind kind) -> bool {
313 /* Convert id to a string. */
314 RootedString idstr(cx);
315 if (id.isSymbol()) {
316 RootedValue v(cx, SymbolValue(id.toSymbol()));
317 idstr = ValueToSource(cx, v);
318 if (!idstr) {
319 return false;
320 }
321 } else {
322 RootedValue idv(cx, IdToValue(id));
323 idstr = ToString<CanGC>(cx, idv);
324 if (!idstr) {
325 return false;
326 }
327
328 /*
329 * If id is a string that's not an identifier, or if it's a
330 * negative integer, then it must be quoted.
331 */
332 if (id.isAtom() ? !IsIdentifier(id.toAtom()) : id.toInt() < 0) {
333 UniqueChars quotedId = QuoteString(cx, idstr, '\'');
334 if (!quotedId) {
335 return false;
336 }
337 idstr = NewStringCopyZ<CanGC>(cx, quotedId.get());
338 if (!idstr) {
339 return false;
340 }
341 }
342 }
343
344 RootedString valsource(cx, ValueToSource(cx, val));
345 if (!valsource) {
346 return false;
347 }
348
349 Rooted<JSLinearString*> valstr(cx, valsource->ensureLinear(cx));
350 if (!valstr) {
351 return false;
352 }
353
354 if (comma && !buf.append(", ")) {
355 return false;
356 }
357 comma = true;
358
359 size_t voffset, vlength;
360
361 // Methods and accessors can return exact syntax of source, that fits
362 // into property without adding property name or "get"/"set" prefix.
363 // Use the exact syntax when the following conditions are met:
364 //
365 // * It's a function object
366 // (exclude proxies)
367 // * Function's kind and property's kind are same
368 // (this can be false for dynamically defined properties)
369 // * Function has explicit name
370 // (this can be false for computed property and dynamically defined
371 // properties)
372 // * Function's name and property's name are same
373 // (this can be false for dynamically defined properties)
374 if (kind == PropertyKind::Getter || kind == PropertyKind::Setter ||
375 kind == PropertyKind::Method) {
376 RootedFunction fun(cx);
377 if (val.toObject().is<JSFunction>()) {
378 fun = &val.toObject().as<JSFunction>();
379 // Method's case should be checked on caller.
380 if (((fun->isGetter() && kind == PropertyKind::Getter &&
381 !fun->isAccessorWithLazyName()) ||
382 (fun->isSetter() && kind == PropertyKind::Setter &&
383 !fun->isAccessorWithLazyName()) ||
384 kind == PropertyKind::Method) &&
385 fun->fullExplicitName()) {
386 bool result;
387 if (!EqualStrings(cx, fun->fullExplicitName(), idstr, &result)) {
388 return false;
389 }
390
391 if (result) {
392 if (!buf.append(valstr)) {
393 return false;
394 }
395 return true;
396 }
397 }
398 }
399
400 {
401 // When falling back try to generate a better string
402 // representation by skipping the prelude, and also removing
403 // the enclosing parentheses.
404 bool success;
405 JS::AutoCheckCannotGC nogc;
406 if (valstr->hasLatin1Chars()) {
407 success = ArgsAndBodySubstring(valstr->latin1Range(nogc), &voffset,
408 &vlength);
409 } else {
410 success = ArgsAndBodySubstring(valstr->twoByteRange(nogc), &voffset,
411 &vlength);
412 }
413 if (!success) {
414 kind = PropertyKind::Normal;
415 }
416 }
417
418 if (kind == PropertyKind::Getter) {
419 if (!buf.append("get ")) {
420 return false;
421 }
422 } else if (kind == PropertyKind::Setter) {
423 if (!buf.append("set ")) {
424 return false;
425 }
426 } else if (kind == PropertyKind::Method && fun) {
427 if (fun->isAsync()) {
428 if (!buf.append("async ")) {
429 return false;
430 }
431 }
432
433 if (fun->isGenerator()) {
434 if (!buf.append('*')) {
435 return false;
436 }
437 }
438 }
439 }
440
441 bool needsBracket = id.isSymbol();
442 if (needsBracket && !buf.append('[')) {
443 return false;
444 }
445 if (!buf.append(idstr)) {
446 return false;
447 }
448 if (needsBracket && !buf.append(']')) {
449 return false;
450 }
451
452 if (kind == PropertyKind::Getter || kind == PropertyKind::Setter ||
453 kind == PropertyKind::Method) {
454 if (!buf.appendSubstring(valstr, voffset, vlength)) {
455 return false;
456 }
457 } else {
458 if (!buf.append(':')) {
459 return false;
460 }
461 if (!buf.append(valstr)) {
462 return false;
463 }
464 }
465 return true;
466 };
467
468 RootedId id(cx);
469 Rooted<Maybe<PropertyDescriptor>> desc(cx);
470 RootedValue val(cx);
471 for (size_t i = 0; i < idv.length(); ++i) {
472 id = idv[i];
473 if (!GetOwnPropertyDescriptor(cx, obj, id, &desc)) {
474 return nullptr;
475 }
476
477 if (desc.isNothing()) {
478 continue;
479 }
480
481 if (desc->isAccessorDescriptor()) {
482 if (desc->hasGetter() && desc->getter()) {
483 val.setObject(*desc->getter());
484 if (!AddProperty(id, val, PropertyKind::Getter)) {
485 return nullptr;
486 }
487 }
488 if (desc->hasSetter() && desc->setter()) {
489 val.setObject(*desc->setter());
490 if (!AddProperty(id, val, PropertyKind::Setter)) {
491 return nullptr;
492 }
493 }
494 continue;
495 }
496
497 val.set(desc->value());
498
499 JSFunction* fun = nullptr;
500 if (IsFunctionObject(val, &fun) && fun->isMethod()) {
501 if (!AddProperty(id, val, PropertyKind::Method)) {
502 return nullptr;
503 }
504 continue;
505 }
506
507 if (!AddProperty(id, val, PropertyKind::Normal)) {
508 return nullptr;
509 }
510 }
511
512 if (!buf.append('}')) {
513 return nullptr;
514 }
515 if (outermost && !buf.append(')')) {
516 return nullptr;
517 }
518
519 return buf.finishString();
520 }
521
522 static JSString* GetBuiltinTagSlow(JSContext* cx, HandleObject obj) {
523 // Step 4.
524 bool isArray;
525 if (!IsArray(cx, obj, &isArray)) {
526 return nullptr;
527 }
528
529 // Step 5.
530 if (isArray) {
531 return cx->names().object_Array_;
532 }
533
534 // Steps 6-14.
535 ESClass cls;
536 if (!JS::GetBuiltinClass(cx, obj, &cls)) {
537 return nullptr;
538 }
539
540 switch (cls) {
541 case ESClass::String:
542 return cx->names().object_String_;
543 case ESClass::Arguments:
544 return cx->names().object_Arguments_;
545 case ESClass::Error:
546 return cx->names().object_Error_;
547 case ESClass::Boolean:
548 return cx->names().object_Boolean_;
549 case ESClass::Number:
550 return cx->names().object_Number_;
551 case ESClass::Date:
552 return cx->names().object_Date_;
553 case ESClass::RegExp:
554 return cx->names().object_RegExp_;
555 default:
556 if (obj->isCallable()) {
557 // Non-standard: Prevent <object> from showing up as Function.
558 JSObject* unwrapped = CheckedUnwrapDynamic(obj, cx);
559 if (!unwrapped || !unwrapped->getClass()->isDOMClass()) {
560 return cx->names().object_Function_;
561 }
562 }
563 return cx->names().object_Object_;
564 }
565 }
566
567 static MOZ_ALWAYS_INLINE JSString* GetBuiltinTagFast(JSObject* obj,
568 JSContext* cx) {
569 const JSClass* clasp = obj->getClass();
570 MOZ_ASSERT(!clasp->isProxyObject());
571
572 // Optimize the non-proxy case to bypass GetBuiltinClass.
573 if (clasp == &PlainObject::class_) {
574 // This case is by far the most common so we handle it first.
575 return cx->names().object_Object_;
576 }
577
578 if (clasp == &ArrayObject::class_) {
579 return cx->names().object_Array_;
580 }
581
582 if (clasp->isJSFunction()) {
583 return cx->names().object_Function_;
584 }
585
586 if (clasp == &StringObject::class_) {
587 return cx->names().object_String_;
588 }
589
590 if (clasp == &NumberObject::class_) {
591 return cx->names().object_Number_;
592 }
593
594 if (clasp == &BooleanObject::class_) {
595 return cx->names().object_Boolean_;
596 }
597
598 if (clasp == &DateObject::class_) {
599 return cx->names().object_Date_;
600 }
601
602 if (clasp == &RegExpObject::class_) {
603 return cx->names().object_RegExp_;
604 }
605
606 if (obj->is<ArgumentsObject>()) {
607 return cx->names().object_Arguments_;
608 }
609
610 if (obj->is<ErrorObject>()) {
611 return cx->names().object_Error_;
612 }
613
614 if (obj->isCallable() && !obj->getClass()->isDOMClass()) {
615 // Non-standard: Prevent <object> from showing up as Function.
616 return cx->names().object_Function_;
617 }
618
619 return cx->names().object_Object_;
620 }
621
622 // For primitive values we try to avoid allocating the object if we can
623 // determine that the prototype it would use does not define Symbol.toStringTag.
624 static JSAtom* MaybeObjectToStringPrimitive(JSContext* cx, const Value& v) {
625 JSProtoKey protoKey = js::PrimitiveToProtoKey(cx, v);
626
627 // If prototype doesn't exist yet, just fall through.
628 JSObject* proto = cx->global()->maybeGetPrototype(protoKey);
629 if (!proto) {
630 return nullptr;
631 }
632
633 // If determining this may have side-effects, we must instead create the
634 // object normally since it is the receiver while looking up
635 // Symbol.toStringTag.
636 if (MaybeHasInterestingSymbolProperty(
637 cx, proto, cx->wellKnownSymbols().toStringTag, nullptr)) {
638 return nullptr;
639 }
640
641 // Return the direct result.
642 switch (protoKey) {
643 case JSProto_String:
644 return cx->names().object_String_;
645 case JSProto_Number:
646 return cx->names().object_Number_;
647 case JSProto_Boolean:
648 return cx->names().object_Boolean_;
649 case JSProto_Symbol:
650 return cx->names().object_Symbol_;
651 case JSProto_BigInt:
652 return cx->names().object_BigInt_;
653 default:
654 break;
655 }
656
657 return nullptr;
658 }
659
660 // ES6 19.1.3.6
661 bool js::obj_toString(JSContext* cx, unsigned argc, Value* vp) {
662 AutoJSMethodProfilerEntry pseudoFrame(cx, "Object.prototype", "toString");
663 CallArgs args = CallArgsFromVp(argc, vp);
664 RootedObject obj(cx);
665
666 if (args.thisv().isPrimitive()) {
667 // Step 1.
668 if (args.thisv().isUndefined()) {
669 args.rval().setString(cx->names().object_Undefined_);
670 return true;
671 }
672
673 // Step 2.
674 if (args.thisv().isNull()) {
675 args.rval().setString(cx->names().object_Null_);
676 return true;
677 }
678
679 // Try fast-path for primitives. This is unusual but we encounter code like
680 // this in the wild.
681 JSAtom* result = MaybeObjectToStringPrimitive(cx, args.thisv());
682 if (result) {
683 args.rval().setString(result);
684 return true;
685 }
686
687 // Step 3.
688 obj = ToObject(cx, args.thisv());
689 if (!obj) {
690 return false;
691 }
692 } else {
693 obj = &args.thisv().toObject();
694 }
695
696 // When |obj| is a non-proxy object, compute |builtinTag| only when needed.
697 RootedString builtinTag(cx);
698 if (MOZ_UNLIKELY(obj->is<ProxyObject>())) {
699 builtinTag = GetBuiltinTagSlow(cx, obj);
700 if (!builtinTag) {
701 return false;
702 }
703 }
704
705 // Step 15.
706 RootedValue tag(cx);
707 if (!GetInterestingSymbolProperty(cx, obj, cx->wellKnownSymbols().toStringTag,
708 &tag)) {
709 return false;
710 }
711
712 // Step 16.
713 if (!tag.isString()) {
714 if (!builtinTag) {
715 builtinTag = GetBuiltinTagFast(obj, cx);
716 #ifdef DEBUG
717 // Assert this fast path is correct and matches BuiltinTagSlow.
718 JSString* builtinTagSlow = GetBuiltinTagSlow(cx, obj);
719 if (!builtinTagSlow) {
720 return false;
721 }
722 MOZ_ASSERT(builtinTagSlow == builtinTag);
723 #endif
724 }
725
726 args.rval().setString(builtinTag);
727 return true;
728 }
729
730 // Step 17.
731 StringBuilder sb(cx);
732 if (!sb.append("[object ") || !sb.append(tag.toString()) || !sb.append(']')) {
733 return false;
734 }
735
736 JSString* str = sb.finishAtom();
737 if (!str) {
738 return false;
739 }
740
741 args.rval().setString(str);
742 return true;
743 }
744
745 JSString* js::ObjectClassToString(JSContext* cx, JSObject* obj) {
746 AutoUnsafeCallWithABI unsafe;
747
748 if (MaybeHasInterestingSymbolProperty(cx, obj,
749 cx->wellKnownSymbols().toStringTag)) {
750 return nullptr;
751 }
752 return GetBuiltinTagFast(obj, cx);
753 }
754
755 static bool obj_setPrototypeOf(JSContext* cx, unsigned argc, Value* vp) {
756 CallArgs args = CallArgsFromVp(argc, vp);
757
758 if (!args.requireAtLeast(cx, "Object.setPrototypeOf", 2)) {
759 return false;
760 }
761
762 /* Step 1-2. */
763 if (args[0].isNullOrUndefined()) {
764 JS_ReportErrorNumberASCII(
765 cx, GetErrorMessage, nullptr, JSMSG_CANT_CONVERT_TO,
766 args[0].isNull() ? "null" : "undefined", "object");
767 return false;
768 }
769
770 /* Step 3. */
771 if (!args[1].isObjectOrNull()) {
772 JS_ReportErrorNumberASCII(cx, GetErrorMessage, nullptr,
773 JSMSG_NOT_EXPECTED_TYPE, "Object.setPrototypeOf",
774 "an object or null",
775 InformalValueTypeName(args[1]));
776 return false;
777 }
778
779 /* Step 4. */
780 if (!args[0].isObject()) {
781 args.rval().set(args[0]);
782 return true;
783 }
784
785 /* Step 5-7. */
786 RootedObject obj(cx, &args[0].toObject());
787 RootedObject newProto(cx, args[1].toObjectOrNull());
788 if (!SetPrototype(cx, obj, newProto)) {
789 return false;
790 }
791
792 /* Step 8. */
793 args.rval().set(args[0]);
794 return true;
795 }
796
797 static bool PropertyIsEnumerable(JSContext* cx, HandleObject obj, HandleId id,
798 bool* enumerable) {
799 PropertyResult prop;
800 if (obj->is<NativeObject>() &&
801 NativeLookupOwnProperty<NoGC>(cx, &obj->as<NativeObject>(), id, &prop)) {
802 if (prop.isNotFound()) {
803 *enumerable = false;
804 return true;
805 }
806
807 JS::PropertyAttributes attrs = GetPropertyAttributes(obj, prop);
808 *enumerable = attrs.enumerable();
809 return true;
810 }
811
812 Rooted<Maybe<PropertyDescriptor>> desc(cx);
813 if (!GetOwnPropertyDescriptor(cx, obj, id, &desc)) {
814 return false;
815 }
816
817 *enumerable = desc.isSome() && desc->enumerable();
818 return true;
819 }
820
821 // Returns true if properties not named "__proto__" can be added to |obj|
822 // with a fast path that doesn't check any properties on the prototype chain.
823 static bool CanAddNewPropertyExcludingProtoFast(PlainObject* obj) {
824 if (!obj->isExtensible() || obj->isUsedAsPrototype()) {
825 return false;
826 }
827
828 // Don't fastpath assign if we're watching for property value changes.
829 if (Watchtower::watchesPropertyValueChange(obj)) {
830 return false;
831 }
832
833 // Ensure the object has no non-writable properties or getters/setters.
834 // For now only support PlainObjects so that we don't have to worry about
835 // resolve hooks and other JSClass hooks.
836 while (true) {
837 if (obj->hasNonWritableOrAccessorPropExclProto()) {
838 return false;
839 }
840
841 JSObject* proto = obj->staticPrototype();
842 if (!proto) {
843 return true;
844 }
845 if (!proto->is<PlainObject>()) {
846 return false;
847 }
848 obj = &proto->as<PlainObject>();
849 }
850 }
851
852 #ifdef DEBUG
853 void PlainObjectAssignCache::assertValid() const {
854 MOZ_ASSERT(emptyToShape_);
855 MOZ_ASSERT(fromShape_);
856 MOZ_ASSERT(newToShape_);
857
858 MOZ_ASSERT(emptyToShape_->propMapLength() == 0);
859 MOZ_ASSERT(emptyToShape_->base() == newToShape_->base());
860 MOZ_ASSERT(emptyToShape_->numFixedSlots() == newToShape_->numFixedSlots());
861
862 MOZ_ASSERT(emptyToShape_->getObjectClass() == &PlainObject::class_);
863 MOZ_ASSERT(fromShape_->getObjectClass() == &PlainObject::class_);
864
865 MOZ_ASSERT(fromShape_->slotSpan() == newToShape_->slotSpan());
866 }
867 #endif
868
869 [[nodiscard]] static bool TryAssignPlain(JSContext* cx, HandleObject to,
870 HandleObject from, bool* optimized) {
871 // Object.assign is used with PlainObjects most of the time. This is a fast
872 // path to optimize that case. This lets us avoid checks that are only
873 // relevant for other JSClasses.
874
875 MOZ_ASSERT(*optimized == false);
876
877 if (!from->is<PlainObject>() || !to->is<PlainObject>()) {
878 return true;
879 }
880
881 // Don't use the fast path if |from| may have extra indexed properties.
882 Handle<PlainObject*> fromPlain = from.as<PlainObject>();
883 if (fromPlain->getDenseInitializedLength() > 0 || fromPlain->isIndexed()) {
884 return true;
885 }
886 MOZ_ASSERT(!fromPlain->getClass()->getNewEnumerate());
887 MOZ_ASSERT(!fromPlain->getClass()->getEnumerate());
888
889 // Empty |from| objects are common, so check for this first.
890 if (fromPlain->empty()) {
891 *optimized = true;
892 return true;
893 }
894
895 Handle<PlainObject*> toPlain = to.as<PlainObject>();
896 if (!CanAddNewPropertyExcludingProtoFast(toPlain)) {
897 return true;
898 }
899
900 const bool toWasEmpty = toPlain->empty();
901 if (toWasEmpty) {
902 const PlainObjectAssignCache& cache = cx->realm()->plainObjectAssignCache;
903 SharedShape* newShape = cache.lookup(toPlain->shape(), fromPlain->shape());
904 if (newShape) {
905 *optimized = true;
906 uint32_t oldSpan = 0;
907 uint32_t newSpan = newShape->slotSpan();
908 if (!toPlain->setShapeAndAddNewSlots(cx, newShape, oldSpan, newSpan)) {
909 return false;
910 }
911 MOZ_ASSERT(fromPlain->slotSpan() == newSpan);
912 for (size_t i = 0; i < newSpan; i++) {
913 toPlain->initSlot(i, fromPlain->getSlot(i));
914 }
915 return true;
916 }
917 }
918
919 // Get a list of all enumerable |from| properties.
920
921 Rooted<PropertyInfoWithKeyVector> props(cx, PropertyInfoWithKeyVector(cx));
922
923 #ifdef DEBUG
924 Rooted<Shape*> fromShape(cx, fromPlain->shape());
925 #endif
926
927 bool hasPropsWithNonDefaultAttrs = false;
928 bool hasOnlyEnumerableProps = true;
929 for (ShapePropertyIter<NoGC> iter(fromPlain->shape()); !iter.done(); iter++) {
930 // Symbol properties need to be assigned last. For now fall back to the
931 // slow path if we see a symbol property.
932 jsid id = iter->key();
933 if (MOZ_UNLIKELY(id.isSymbol())) {
934 return true;
935 }
936 // __proto__ is not supported by CanAddNewPropertyExcludingProtoFast.
937 if (MOZ_UNLIKELY(id.isAtom(cx->names().proto_))) {
938 return true;
939 }
940 if (MOZ_UNLIKELY(!iter->isDataProperty())) {
941 return true;
942 }
943 if (iter->flags() != PropertyFlags::defaultDataPropFlags) {
944 hasPropsWithNonDefaultAttrs = true;
945 if (!iter->enumerable()) {
946 hasOnlyEnumerableProps = false;
947 continue;
948 }
949 }
950 if (MOZ_UNLIKELY(!props.append(*iter))) {
951 return false;
952 }
953 }
954
955 MOZ_ASSERT_IF(hasOnlyEnumerableProps && !fromPlain->inDictionaryMode(),
956 fromPlain->slotSpan() == props.length());
957
958 *optimized = true;
959
960 Rooted<Shape*> origToShape(cx, toPlain->shape());
961
962 // If the |to| object has no properties and the |from| object only has plain
963 // enumerable/writable/configurable data properties, try to use its shape or
964 // property map.
965 if (toWasEmpty && !hasPropsWithNonDefaultAttrs) {
966 CanReuseShape canReuse =
967 toPlain->canReuseShapeForNewProperties(fromPlain->shape());
968 if (canReuse != CanReuseShape::NoReuse) {
969 SharedShape* newShape;
970 if (canReuse == CanReuseShape::CanReuseShape) {
971 newShape = fromPlain->sharedShape();
972 } else {
973 // Get a shape with fromPlain's PropMap and ObjectFlags (because we need
974 // the HasEnumerable flag checked in canReuseShapeForNewProperties) and
975 // the other fields (BaseShape, numFixedSlots) unchanged.
976 MOZ_ASSERT(canReuse == CanReuseShape::CanReusePropMap);
977 ObjectFlags objectFlags = fromPlain->sharedShape()->objectFlags();
978 Rooted<SharedPropMap*> map(cx, fromPlain->sharedShape()->propMap());
979 uint32_t mapLength = fromPlain->sharedShape()->propMapLength();
980 BaseShape* base = toPlain->sharedShape()->base();
981 uint32_t nfixed = toPlain->sharedShape()->numFixedSlots();
982 newShape = SharedShape::getPropMapShape(cx, base, nfixed, map,
983 mapLength, objectFlags);
984 if (!newShape) {
985 return false;
986 }
987 }
988 uint32_t oldSpan = 0;
989 uint32_t newSpan = props.length();
990 if (!toPlain->setShapeAndAddNewSlots(cx, newShape, oldSpan, newSpan)) {
991 return false;
992 }
993 MOZ_ASSERT(fromPlain->slotSpan() == newSpan);
994 MOZ_ASSERT(toPlain->slotSpan() == newSpan);
995 for (size_t i = 0; i < newSpan; i++) {
996 toPlain->initSlot(i, fromPlain->getSlot(i));
997 }
998 PlainObjectAssignCache& cache = cx->realm()->plainObjectAssignCache;
999 cache.fill(&origToShape->asShared(), fromPlain->sharedShape(), newShape);
1000 return true;
1001 }
1002 }
1003
1004 RootedValue propValue(cx);
1005 RootedId nextKey(cx);
1006
1007 for (size_t i = props.length(); i > 0; i--) {
1008 // Assert |from| still has the same properties.
1009 MOZ_ASSERT(fromPlain->shape() == fromShape);
1010
1011 PropertyInfoWithKey fromProp = props[i - 1];
1012 MOZ_ASSERT(fromProp.isDataProperty());
1013 MOZ_ASSERT(fromProp.enumerable());
1014
1015 nextKey = fromProp.key();
1016 propValue = fromPlain->getSlot(fromProp.slot());
1017
1018 if (!toWasEmpty) {
1019 if (Maybe<PropertyInfo> toProp = toPlain->lookup(cx, nextKey)) {
1020 MOZ_ASSERT(toProp->isDataProperty());
1021 MOZ_ASSERT(toProp->writable());
1022 toPlain->setSlot(toProp->slot(), propValue);
1023 continue;
1024 }
1025 }
1026
1027 MOZ_ASSERT(!toPlain->containsPure(nextKey));
1028
1029 if (!AddDataPropertyToPlainObject(cx, toPlain, nextKey, propValue)) {
1030 return false;
1031 }
1032 }
1033
1034 // Note: dictionary shapes are not supported by the cache because they have a
1035 // more complicated slot layout (the slot numbers may not match the property
1036 // definition order and the slots may contain holes).
1037 if (toWasEmpty && hasOnlyEnumerableProps && !fromPlain->inDictionaryMode() &&
1038 !toPlain->inDictionaryMode()) {
1039 PlainObjectAssignCache& cache = cx->realm()->plainObjectAssignCache;
1040 cache.fill(&origToShape->asShared(), fromPlain->sharedShape(),
1041 toPlain->sharedShape());
1042 }
1043
1044 return true;
1045 }
1046
1047 static bool TryAssignNative(JSContext* cx, HandleObject to, HandleObject from,
1048 bool* optimized) {
1049 MOZ_ASSERT(*optimized == false);
1050
1051 if (!from->is<NativeObject>() || !to->is<NativeObject>()) {
1052 return true;
1053 }
1054
1055 // Don't use the fast path if |from| may have extra indexed or lazy
1056 // properties.
1057 NativeObject* fromNative = &from->as<NativeObject>();
1058 if (fromNative->getDenseInitializedLength() > 0 || fromNative->isIndexed() ||
1059 fromNative->is<TypedArrayObject>() ||
1060 fromNative->getClass()->getNewEnumerate() ||
1061 fromNative->getClass()->getEnumerate()) {
1062 return true;
1063 }
1064
1065 // Get a list of |from| properties. As long as from->shape() == fromShape
1066 // we can use this to speed up both the enumerability check and the GetProp.
1067
1068 Rooted<PropertyInfoWithKeyVector> props(cx, PropertyInfoWithKeyVector(cx));
1069
1070 Rooted<NativeShape*> fromShape(cx, fromNative->shape());
1071 for (ShapePropertyIter<NoGC> iter(fromShape); !iter.done(); iter++) {
1072 // Symbol properties need to be assigned last. For now fall back to the
1073 // slow path if we see a symbol property.
1074 if (MOZ_UNLIKELY(iter->key().isSymbol())) {
1075 return true;
1076 }
1077 if (MOZ_UNLIKELY(!props.append(*iter))) {
1078 return false;
1079 }
1080 }
1081
1082 *optimized = true;
1083
1084 RootedValue propValue(cx);
1085 RootedId nextKey(cx);
1086 RootedValue toReceiver(cx, ObjectValue(*to));
1087
1088 for (size_t i = props.length(); i > 0; i--) {
1089 PropertyInfoWithKey prop = props[i - 1];
1090 nextKey = prop.key();
1091
1092 // If |from| still has the same shape, it must still be a NativeObject with
1093 // the properties in |props|.
1094 if (MOZ_LIKELY(from->shape() == fromShape && prop.isDataProperty())) {
1095 if (!prop.enumerable()) {
1096 continue;
1097 }
1098 propValue = from->as<NativeObject>().getSlot(prop.slot());
1099 } else {
1100 // |from| changed shape or the property is not a data property, so
1101 // we have to do the slower enumerability check and GetProp.
1102 bool enumerable;
1103 if (!PropertyIsEnumerable(cx, from, nextKey, &enumerable)) {
1104 return false;
1105 }
1106 if (!enumerable) {
1107 continue;
1108 }
1109 if (!GetProperty(cx, from, from, nextKey, &propValue)) {
1110 return false;
1111 }
1112 }
1113
1114 ObjectOpResult result;
1115 if (MOZ_UNLIKELY(
1116 !SetProperty(cx, to, nextKey, propValue, toReceiver, result))) {
1117 return false;
1118 }
1119 if (MOZ_UNLIKELY(!result.checkStrict(cx, to, nextKey))) {
1120 return false;
1121 }
1122 }
1123
1124 return true;
1125 }
1126
1127 static bool AssignSlow(JSContext* cx, HandleObject to, HandleObject from) {
1128 // Step 4.b.ii.
1129 RootedIdVector keys(cx);
1130 if (!GetPropertyKeys(
1131 cx, from, JSITER_OWNONLY | JSITER_HIDDEN | JSITER_SYMBOLS, &keys)) {
1132 return false;
1133 }
1134
1135 // Step 4.c.
1136 RootedId nextKey(cx);
1137 RootedValue propValue(cx);
1138 for (size_t i = 0, len = keys.length(); i < len; i++) {
1139 nextKey = keys[i];
1140
1141 // Step 4.c.i.
1142 bool enumerable;
1143 if (MOZ_UNLIKELY(!PropertyIsEnumerable(cx, from, nextKey, &enumerable))) {
1144 return false;
1145 }
1146 if (!enumerable) {
1147 continue;
1148 }
1149
1150 // Step 4.c.ii.1.
1151 if (MOZ_UNLIKELY(!GetProperty(cx, from, from, nextKey, &propValue))) {
1152 return false;
1153 }
1154
1155 // Step 4.c.ii.2.
1156 if (MOZ_UNLIKELY(!SetProperty(cx, to, nextKey, propValue))) {
1157 return false;
1158 }
1159 }
1160
1161 return true;
1162 }
1163
1164 JS_PUBLIC_API bool JS_AssignObject(JSContext* cx, JS::HandleObject target,
1165 JS::HandleObject src) {
1166 bool optimized = false;
1167
1168 if (!TryAssignPlain(cx, target, src, &optimized)) {
1169 return false;
1170 }
1171 if (optimized) {
1172 return true;
1173 }
1174
1175 if (!TryAssignNative(cx, target, src, &optimized)) {
1176 return false;
1177 }
1178 if (optimized) {
1179 return true;
1180 }
1181
1182 return AssignSlow(cx, target, src);
1183 }
1184
1185 // ES2018 draft rev 48ad2688d8f964da3ea8c11163ef20eb126fb8a4
1186 // 19.1.2.1 Object.assign(target, ...sources)
1187 static bool obj_assign(JSContext* cx, unsigned argc, Value* vp) {
1188 AutoJSMethodProfilerEntry pseudoFrame(cx, "Object", "assign");
1189 CallArgs args = CallArgsFromVp(argc, vp);
1190 RootedTuple<JSObject*, JSObject*> roots(cx);
1191
1192 // Step 1.
1193 RootedField<JSObject*, 0> to(roots, ToObject(cx, args.get(0)));
1194 if (!to) {
1195 return false;
1196 }
1197
1198 // Note: step 2 is implicit. If there are 0 arguments, ToObject throws. If
1199 // there's 1 argument, the loop below is a no-op.
1200
1201 // Step 4.
1202 for (size_t i = 1; i < args.length(); i++) {
1203 // Step 4.a.
1204 if (args[i].isNullOrUndefined()) {
1205 continue;
1206 }
1207
1208 // Step 4.b.i.
1209 RootedField<JSObject*, 1> from(roots, ToObject(cx, args[i]));
1210 if (!from) {
1211 return false;
1212 }
1213
1214 // Steps 4.b.ii, 4.c.
1215 if (!JS_AssignObject(cx, to, from)) {
1216 return false;
1217 }
1218 }
1219
1220 // Step 5.
1221 args.rval().setObject(*to);
1222 return true;
1223 }
1224
1225 /* ES5 15.2.4.6. */
1226 bool js::obj_isPrototypeOf(JSContext* cx, unsigned argc, Value* vp) {
1227 CallArgs args = CallArgsFromVp(argc, vp);
1228
1229 /* Step 1. */
1230 if (args.length() < 1 || !args[0].isObject()) {
1231 args.rval().setBoolean(false);
1232 return true;
1233 }
1234
1235 /* Step 2. */
1236 RootedObject obj(cx, ToObject(cx, args.thisv()));
1237 if (!obj) {
1238 return false;
1239 }
1240
1241 /* Step 3. */
1242 bool isPrototype;
1243 if (!IsPrototypeOf(cx, obj, &args[0].toObject(), &isPrototype)) {
1244 return false;
1245 }
1246 args.rval().setBoolean(isPrototype);
1247 return true;
1248 }
1249
1250 PlainObject* js::ObjectCreateImpl(JSContext* cx, HandleObject proto,
1251 NewObjectKind newKind) {
1252 // Give the new object a small number of fixed slots, like we do for empty
1253 // object literals ({}).
1254 gc::AllocKind allocKind = NewObjectGCKind();
1255 return NewPlainObjectWithProtoAndAllocKind(cx, proto, allocKind, newKind);
1256 }
1257
1258 PlainObject* js::ObjectCreateWithTemplate(JSContext* cx,
1259 Handle<PlainObject*> templateObj) {
1260 RootedObject proto(cx, templateObj->staticPrototype());
1261 return ObjectCreateImpl(cx, proto, GenericObject);
1262 }
1263
1264 // ES 2017 draft 19.1.2.3.1
1265 static bool ObjectDefineProperties(JSContext* cx, HandleObject obj,
1266 HandleValue properties,
1267 bool* failedOnWindowProxy) {
1268 // Step 1. implicit
1269 // Step 2.
1270 RootedObject props(cx, ToObject(cx, properties));
1271 if (!props) {
1272 return false;
1273 }
1274
1275 // Step 3.
1276 RootedIdVector keys(cx);
1277 if (!GetPropertyKeys(
1278 cx, props, JSITER_OWNONLY | JSITER_SYMBOLS | JSITER_HIDDEN, &keys)) {
1279 return false;
1280 }
1281
1282 RootedId nextKey(cx);
1283 Rooted<Maybe<PropertyDescriptor>> keyDesc(cx);
1284 Rooted<PropertyDescriptor> desc(cx);
1285 RootedValue descObj(cx);
1286
1287 // Step 4.
1288 Rooted<PropertyDescriptorVector> descriptors(cx,
1289 PropertyDescriptorVector(cx));
1290 RootedIdVector descriptorKeys(cx);
1291
1292 // Step 5.
1293 for (size_t i = 0, len = keys.length(); i < len; i++) {
1294 nextKey = keys[i];
1295
1296 // Step 5.a.
1297 if (!GetOwnPropertyDescriptor(cx, props, nextKey, &keyDesc)) {
1298 return false;
1299 }
1300
1301 // Step 5.b.
1302 if (keyDesc.isSome() && keyDesc->enumerable()) {
1303 if (!GetProperty(cx, props, props, nextKey, &descObj) ||
1304 !ToPropertyDescriptor(cx, descObj, true, &desc) ||
1305 !descriptors.append(desc) || !descriptorKeys.append(nextKey)) {
1306 return false;
1307 }
1308 }
1309 }
1310
1311 // Step 6.
1312 *failedOnWindowProxy = false;
1313 for (size_t i = 0, len = descriptors.length(); i < len; i++) {
1314 ObjectOpResult result;
1315 if (!DefineProperty(cx, obj, descriptorKeys[i], descriptors[i], result)) {
1316 return false;
1317 }
1318
1319 if (!result.ok()) {
1320 if (result.failureCode() == JSMSG_CANT_DEFINE_WINDOW_NC) {
1321 *failedOnWindowProxy = true;
1322 } else if (!result.checkStrict(cx, obj, descriptorKeys[i])) {
1323 return false;
1324 }
1325 }
1326 }
1327
1328 return true;
1329 }
1330
1331 // ES6 draft rev34 (2015/02/20) 19.1.2.2 Object.create(O [, Properties])
1332 bool js::obj_create(JSContext* cx, unsigned argc, Value* vp) {
1333 CallArgs args = CallArgsFromVp(argc, vp);
1334
1335 // Step 1.
1336 if (!args.requireAtLeast(cx, "Object.create", 1)) {
1337 return false;
1338 }
1339
1340 if (!args[0].isObjectOrNull()) {
1341 UniqueChars bytes =
1342 DecompileValueGenerator(cx, JSDVG_SEARCH_STACK, args[0], nullptr);
1343 if (!bytes) {
1344 return false;
1345 }
1346
1347 JS_ReportErrorNumberUTF8(cx, GetErrorMessage, nullptr,
1348 JSMSG_UNEXPECTED_TYPE, bytes.get(),
1349 "not an object or null");
1350 return false;
1351 }
1352
1353 // Step 2.
1354 RootedObject proto(cx, args[0].toObjectOrNull());
1355 Rooted<PlainObject*> obj(cx, ObjectCreateImpl(cx, proto));
1356 if (!obj) {
1357 return false;
1358 }
1359
1360 // Step 3.
1361 if (args.hasDefined(1)) {
1362 // we can't ever end up with failures to define on a WindowProxy
1363 // here, because "obj" is never a WindowProxy.
1364 bool failedOnWindowProxy = false;
1365 if (!ObjectDefineProperties(cx, obj, args[1], &failedOnWindowProxy)) {
1366 return false;
1367 }
1368 MOZ_ASSERT(!failedOnWindowProxy, "How did we get a WindowProxy here?");
1369 }
1370
1371 // Step 4.
1372 args.rval().setObject(*obj);
1373 return true;
1374 }
1375
1376 // ES2017 draft rev 6859bb9ccaea9c6ede81d71e5320e3833b92cb3e
1377 // 6.2.4.4 FromPropertyDescriptor ( Desc )
1378 static bool FromPropertyDescriptorToArray(
1379 JSContext* cx, Handle<Maybe<PropertyDescriptor>> desc,
1380 MutableHandleValue vp) {
1381 // Step 1.
1382 if (desc.isNothing()) {
1383 vp.setUndefined();
1384 return true;
1385 }
1386
1387 // Steps 2-11.
1388 // Retrieve all property descriptor fields and place them into the result
1389 // array. The actual return object is created in self-hosted code for
1390 // performance reasons.
1391
1392 int32_t attrsAndKind = 0;
1393 if (desc->enumerable()) {
1394 attrsAndKind |= ATTR_ENUMERABLE;
1395 }
1396 if (desc->configurable()) {
1397 attrsAndKind |= ATTR_CONFIGURABLE;
1398 }
1399 if (!desc->isAccessorDescriptor()) {
1400 if (desc->writable()) {
1401 attrsAndKind |= ATTR_WRITABLE;
1402 }
1403 attrsAndKind |= DATA_DESCRIPTOR_KIND;
1404 } else {
1405 attrsAndKind |= ACCESSOR_DESCRIPTOR_KIND;
1406 }
1407
1408 Rooted<ArrayObject*> result(cx);
1409 if (!desc->isAccessorDescriptor()) {
1410 result = NewDenseFullyAllocatedArray(cx, 2);
1411 if (!result) {
1412 return false;
1413 }
1414 result->setDenseInitializedLength(2);
1415
1416 result->initDenseElement(PROP_DESC_ATTRS_AND_KIND_INDEX,
1417 Int32Value(attrsAndKind));
1418 result->initDenseElement(PROP_DESC_VALUE_INDEX, desc->value());
1419 } else {
1420 result = NewDenseFullyAllocatedArray(cx, 3);
1421 if (!result) {
1422 return false;
1423 }
1424 result->setDenseInitializedLength(3);
1425
1426 result->initDenseElement(PROP_DESC_ATTRS_AND_KIND_INDEX,
1427 Int32Value(attrsAndKind));
1428
1429 if (JSObject* get = desc->getter()) {
1430 result->initDenseElement(PROP_DESC_GETTER_INDEX, ObjectValue(*get));
1431 } else {
1432 result->initDenseElement(PROP_DESC_GETTER_INDEX, UndefinedValue());
1433 }
1434
1435 if (JSObject* set = desc->setter()) {
1436 result->initDenseElement(PROP_DESC_SETTER_INDEX, ObjectValue(*set));
1437 } else {
1438 result->initDenseElement(PROP_DESC_SETTER_INDEX, UndefinedValue());
1439 }
1440 }
1441
1442 vp.setObject(*result);
1443 return true;
1444 }
1445
1446 // ES2017 draft rev 6859bb9ccaea9c6ede81d71e5320e3833b92cb3e
1447 // 19.1.2.6 Object.getOwnPropertyDescriptor ( O, P )
1448 bool js::GetOwnPropertyDescriptorToArray(JSContext* cx, unsigned argc,
1449 Value* vp) {
1450 CallArgs args = CallArgsFromVp(argc, vp);
1451 MOZ_ASSERT(args.length() == 2);
1452
1453 // Step 1.
1454 RootedObject obj(cx, ToObject(cx, args[0]));
1455 if (!obj) {
1456 return false;
1457 }
1458
1459 // Step 2.
1460 RootedId id(cx);
1461 if (!ToPropertyKey(cx, args[1], &id)) {
1462 return false;
1463 }
1464
1465 // Step 3.
1466 Rooted<Maybe<PropertyDescriptor>> desc(cx);
1467 if (!GetOwnPropertyDescriptor(cx, obj, id, &desc)) {
1468 return false;
1469 }
1470
1471 // Step 4.
1472 return FromPropertyDescriptorToArray(cx, desc, args.rval());
1473 }
1474
1475 static bool NewValuePair(JSContext* cx, HandleValue val1, HandleValue val2,
1476 MutableHandleValue rval,
1477 gc::Heap heap = gc::Heap::Default) {
1478 NewObjectKind kind =
1479 heap == gc::Heap::Tenured ? TenuredObject : GenericObject;
1480 ArrayObject* array = NewDenseFullyAllocatedArray(cx, 2, kind);
1481 if (!array) {
1482 return false;
1483 }
1484
1485 array->setDenseInitializedLength(2);
1486 array->initDenseElement(0, val1);
1487 array->initDenseElement(1, val2);
1488
1489 rval.setObject(*array);
1490 return true;
1491 }
1492
1493 enum class EnumerableOwnPropertiesKind { Keys, Values, KeysAndValues, Names };
1494
1495 static bool HasEnumerableStringNonDataProperties(NativeObject* obj) {
1496 // We also check for enumerability and symbol properties, so uninteresting
1497 // non-data properties like |array.length| don't let us fall into the slow
1498 // path.
1499 if (!obj->hasEnumerableProperty()) {
1500 return false;
1501 }
1502 for (ShapePropertyIter<NoGC> iter(obj->shape()); !iter.done(); iter++) {
1503 if (!iter->isDataProperty() && iter->enumerable() &&
1504 !iter->key().isSymbol()) {
1505 return true;
1506 }
1507 }
1508 return false;
1509 }
1510
1511 template <EnumerableOwnPropertiesKind kind>
1512 static bool TryEnumerableOwnPropertiesNative(JSContext* cx, HandleObject obj,
1513 MutableHandleValue rval,
1514 bool* optimized) {
1515 *optimized = false;
1516
1517 // Use the fast path if |obj| has neither extra indexed properties nor a
1518 // newEnumerate hook. String objects need to be special-cased, because
1519 // they're only marked as indexed after their enumerate hook ran. And
1520 // because their enumerate hook is slowish, it's more performant to
1521 // exclude them directly instead of executing the hook first.
1522 if (!obj->is<NativeObject>() || obj->as<NativeObject>().isIndexed() ||
1523 obj->getClass()->getNewEnumerate() || obj->is<StringObject>()) {
1524 return true;
1525 }
1526
1527 Handle<NativeObject*> nobj = obj.as<NativeObject>();
1528
1529 // Resolve lazy properties on |nobj|.
1530 if (JSEnumerateOp enumerate = nobj->getClass()->getEnumerate()) {
1531 if (!enumerate(cx, nobj)) {
1532 return false;
1533 }
1534
1535 // Ensure no extra indexed properties were added through enumerate().
1536 if (nobj->isIndexed()) {
1537 return true;
1538 }
1539 }
1540
1541 *optimized = true;
1542
1543 RootedValueVector properties(cx);
1544 RootedValue key(cx);
1545 RootedValue value(cx);
1546
1547 if (kind == EnumerableOwnPropertiesKind::Keys) {
1548 // If possible, attempt to use the shape's iterator cache.
1549 Rooted<PropertyIteratorObject*> piter(cx,
1550 LookupInShapeIteratorCache(cx, nobj));
1551 if (piter) {
1552 do {
1553 NativeIterator* ni = piter->getNativeIterator();
1554 MOZ_ASSERT(ni->isReusable());
1555
1556 // Guard against indexes.
1557 if (ni->mayHavePrototypeProperties()) {
1558 break;
1559 }
1560
1561 JSLinearString** properties =
1562 ni->propertiesBegin()->unbarrieredAddress();
1563 JSObject* array = NewDenseCopiedArray(cx, ni->numKeys(), properties);
1564 if (!array) {
1565 return false;
1566 }
1567
1568 rval.setObject(*array);
1569 return true;
1570
1571 } while (false);
1572 }
1573 }
1574
1575 // Switch to allocating in the tenured heap if necessary to avoid possible
1576 // quadratic behaviour marking stack rooted |properties| vector.
1577 AutoSelectGCHeap gcHeap(cx, 1);
1578
1579 // We have ensured |nobj| contains no extra indexed properties, so the
1580 // only indexed properties we need to handle here are dense and typed
1581 // array elements.
1582 //
1583 // Pre-reserve to avoid reallocating the properties vector frequently.
1584 if (nobj->getDenseInitializedLength() > 0 &&
1585 !properties.reserve(nobj->getDenseInitializedLength())) {
1586 return false;
1587 }
1588 for (uint32_t i = 0, len = nobj->getDenseInitializedLength(); i < len; i++) {
1589 value.set(nobj->getDenseElement(i));
1590 if (value.isMagic(JS_ELEMENTS_HOLE)) {
1591 continue;
1592 }
1593
1594 JSString* str;
1595 if (kind != EnumerableOwnPropertiesKind::Values) {
1596 static_assert(
1597 NativeObject::MAX_DENSE_ELEMENTS_COUNT <= PropertyKey::IntMax,
1598 "dense elements don't exceed PropertyKey::IntMax");
1599 str = Int32ToStringWithHeap<CanGC>(cx, i, gcHeap);
1600 if (!str) {
1601 return false;
1602 }
1603 }
1604
1605 if (kind == EnumerableOwnPropertiesKind::Keys ||
1606 kind == EnumerableOwnPropertiesKind::Names) {
1607 value.setString(str);
1608 } else if (kind == EnumerableOwnPropertiesKind::KeysAndValues) {
1609 key.setString(str);
1610 if (!NewValuePair(cx, key, value, &value, gcHeap)) {
1611 return false;
1612 }
1613 }
1614
1615 if (!properties.append(value)) {
1616 return false;
1617 }
1618 }
1619
1620 if (obj->is<TypedArrayObject>()) {
1621 Handle<TypedArrayObject*> tobj = obj.as<TypedArrayObject>();
1622 size_t len = tobj->length().valueOr(0);
1623
1624 // Fail early if the typed array contains too many elements for a
1625 // dense array, because we likely OOM anyway when trying to allocate
1626 // more than 2GB for the properties vector. This also means we don't
1627 // need to handle indices greater than MAX_INT32 in the loop below.
1628 if (len > NativeObject::MAX_DENSE_ELEMENTS_COUNT) {
1629 ReportOversizedAllocation(cx, JSMSG_ALLOC_OVERFLOW);
1630 return false;
1631 }
1632
1633 MOZ_ASSERT(properties.empty(), "typed arrays cannot have dense elements");
1634 if (!properties.resize(len)) {
1635 return false;
1636 }
1637
1638 for (uint32_t i = 0; i < len; i++) {
1639 JSString* str;
1640 if (kind != EnumerableOwnPropertiesKind::Values) {
1641 static_assert(
1642 NativeObject::MAX_DENSE_ELEMENTS_COUNT <= PropertyKey::IntMax,
1643 "dense elements don't exceed PropertyKey::IntMax");
1644 str = Int32ToStringWithHeap<CanGC>(cx, i, gcHeap);
1645 if (!str) {
1646 return false;
1647 }
1648 }
1649
1650 if (kind == EnumerableOwnPropertiesKind::Keys ||
1651 kind == EnumerableOwnPropertiesKind::Names) {
1652 value.setString(str);
1653 } else if (kind == EnumerableOwnPropertiesKind::Values) {
1654 if (!tobj->getElement<CanGC>(cx, i, &value)) {
1655 return false;
1656 }
1657 } else {
1658 key.setString(str);
1659 if (!tobj->getElement<CanGC>(cx, i, &value)) {
1660 return false;
1661 }
1662 if (!NewValuePair(cx, key, value, &value, gcHeap)) {
1663 return false;
1664 }
1665 }
1666
1667 properties[i].set(value);
1668 }
1669 }
1670
1671 // Up to this point no side-effects through accessor properties are
1672 // possible which could have replaced |obj| with a non-native object.
1673 MOZ_ASSERT(obj->is<NativeObject>());
1674 MOZ_ASSERT(obj.as<NativeObject>() == nobj);
1675
1676 size_t approximatePropertyCount =
1677 nobj->shape()->propMap()
1678 ? nobj->shape()->propMap()->approximateEntryCount()
1679 : 0;
1680 if (!properties.reserve(properties.length() + approximatePropertyCount)) {
1681 return false;
1682 }
1683
1684 if (kind == EnumerableOwnPropertiesKind::Keys ||
1685 kind == EnumerableOwnPropertiesKind::Names ||
1686 !HasEnumerableStringNonDataProperties(nobj)) {
1687 // If |kind == Values| or |kind == KeysAndValues|:
1688 // All enumerable properties with string property keys are data
1689 // properties. This allows us to collect the property values while
1690 // iterating over the shape hierarchy without worrying over accessors
1691 // modifying any state.
1692
1693 constexpr bool onlyEnumerable = kind != EnumerableOwnPropertiesKind::Names;
1694 if (!onlyEnumerable || nobj->hasEnumerableProperty()) {
1695 size_t elements = properties.length();
1696 constexpr AllowGC allowGC =
1697 kind != EnumerableOwnPropertiesKind::KeysAndValues ? AllowGC::NoGC
1698 : AllowGC::CanGC;
1699 mozilla::Maybe<ShapePropertyIter<allowGC>> m;
1700 if constexpr (allowGC == AllowGC::NoGC) {
1701 m.emplace(nobj->shape());
1702 } else {
1703 m.emplace(cx, nobj->shape());
1704 }
1705 for (auto& iter = m.ref(); !iter.done(); iter++) {
1706 jsid id = iter->key();
1707 if ((onlyEnumerable && !iter->enumerable()) || id.isSymbol()) {
1708 continue;
1709 }
1710 MOZ_ASSERT(!id.isInt(), "Unexpected indexed property");
1711 MOZ_ASSERT_IF(kind == EnumerableOwnPropertiesKind::Values ||
1712 kind == EnumerableOwnPropertiesKind::KeysAndValues,
1713 iter->isDataProperty());
1714
1715 if constexpr (kind == EnumerableOwnPropertiesKind::Keys ||
1716 kind == EnumerableOwnPropertiesKind::Names) {
1717 value.setString(id.toString());
1718 } else if constexpr (kind == EnumerableOwnPropertiesKind::Values) {
1719 value.set(nobj->getSlot(iter->slot()));
1720 } else {
1721 key.setString(id.toString());
1722 value.set(nobj->getSlot(iter->slot()));
1723 if (!NewValuePair(cx, key, value, &value, gcHeap)) {
1724 return false;
1725 }
1726 }
1727
1728 if (!properties.append(value)) {
1729 return false;
1730 }
1731 }
1732
1733 // The (non-indexed) properties were visited in reverse iteration order,
1734 // call std::reverse() to ensure they appear in iteration order.
1735 std::reverse(properties.begin() + elements, properties.end());
1736 }
1737 } else {
1738 MOZ_ASSERT(kind == EnumerableOwnPropertiesKind::Values ||
1739 kind == EnumerableOwnPropertiesKind::KeysAndValues);
1740
1741 // Get a list of all |obj| properties. As long as obj->shape()
1742 // is equal to |objShape|, we can use this to speed up both the
1743 // enumerability check and GetProperty.
1744 Rooted<PropertyInfoWithKeyVector> props(cx, PropertyInfoWithKeyVector(cx));
1745
1746 // Collect all non-symbol properties.
1747 Rooted<NativeShape*> objShape(cx, nobj->shape());
1748 for (ShapePropertyIter<NoGC> iter(objShape); !iter.done(); iter++) {
1749 if (iter->key().isSymbol()) {
1750 continue;
1751 }
1752 MOZ_ASSERT(!iter->key().isInt(), "Unexpected indexed property");
1753
1754 if (!props.append(*iter)) {
1755 return false;
1756 }
1757 }
1758
1759 RootedId id(cx);
1760 for (size_t i = props.length(); i > 0; i--) {
1761 PropertyInfoWithKey prop = props[i - 1];
1762 id = prop.key();
1763
1764 // If |obj| still has the same shape, it must still be a NativeObject with
1765 // the properties in |props|.
1766 if (obj->shape() == objShape && prop.isDataProperty()) {
1767 if (!prop.enumerable()) {
1768 continue;
1769 }
1770 value = obj->as<NativeObject>().getSlot(prop.slot());
1771 } else {
1772 // |obj| changed shape or the property is not a data property,
1773 // so we have to do the slower enumerability check and
1774 // GetProperty.
1775 bool enumerable;
1776 if (!PropertyIsEnumerable(cx, obj, id, &enumerable)) {
1777 return false;
1778 }
1779 if (!enumerable) {
1780 continue;
1781 }
1782 if (!GetProperty(cx, obj, obj, id, &value)) {
1783 return false;
1784 }
1785 }
1786
1787 if (kind == EnumerableOwnPropertiesKind::KeysAndValues) {
1788 key.setString(id.toString());
1789 if (!NewValuePair(cx, key, value, &value, gcHeap)) {
1790 return false;
1791 }
1792 }
1793
1794 if (!properties.append(value)) {
1795 return false;
1796 }
1797 }
1798 }
1799
1800 JSObject* array =
1801 NewDenseCopiedArray(cx, properties.length(), properties.begin());
1802 if (!array) {
1803 return false;
1804 }
1805
1806 rval.setObject(*array);
1807 return true;
1808 }
1809
1810 // Optimization dedicated for `Object.keys(..).length` JS pattern. This function
1811 // replicates TryEnumerableOwnPropertiesNative code, except that instead of
1812 // generating an array we only return the length of the array that would have
1813 // been generated.
1814 //
1815 // As opposed to TryEnumerableOwnPropertiesNative, this function only support
1816 // EnumerableOwnPropertiesKind::Keys variant.
1817 static bool CountEnumerableOwnPropertiesNative(JSContext* cx, HandleObject obj,
1818 int32_t& rval, bool* optimized) {
1819 *optimized = false;
1820
1821 // Use the fast path if |obj| has neither extra indexed properties nor a
1822 // newEnumerate hook. String objects need to be special-cased, because
1823 // they're only marked as indexed after their enumerate hook ran. And
1824 // because their enumerate hook is slowish, it's more performant to
1825 // exclude them directly instead of executing the hook first.
1826 if (!obj->is<NativeObject>() || obj->as<NativeObject>().isIndexed() ||
1827 obj->getClass()->getNewEnumerate() || obj->is<StringObject>()) {
1828 return true;
1829 }
1830
1831 Handle<NativeObject*> nobj = obj.as<NativeObject>();
1832
1833 // Resolve lazy properties on |nobj|.
1834 if (JSEnumerateOp enumerate = nobj->getClass()->getEnumerate()) {
1835 if (!enumerate(cx, nobj)) {
1836 return false;
1837 }
1838
1839 // Ensure no extra indexed properties were added through enumerate().
1840 if (nobj->isIndexed()) {
1841 return true;
1842 }
1843 }
1844
1845 *optimized = true;
1846
1847 int32_t num_properties = 0;
1848
1849 // If possible, attempt to use the shape's iterator cache.
1850 Rooted<PropertyIteratorObject*> piter(cx,
1851 LookupInShapeIteratorCache(cx, nobj));
1852 if (piter) {
1853 NativeIterator* ni = piter->getNativeIterator();
1854 MOZ_ASSERT(ni->isReusable());
1855
1856 // Guard against indexes.
1857 if (!ni->mayHavePrototypeProperties()) {
1858 rval = ni->numKeys();
1859 return true;
1860 }
1861 }
1862
1863 for (uint32_t i = 0, len = nobj->getDenseInitializedLength(); i < len; i++) {
1864 if (nobj->getDenseElement(i).isMagic(JS_ELEMENTS_HOLE)) {
1865 continue;
1866 }
1867
1868 num_properties += 1;
1869 }
1870
1871 if (obj->is<TypedArrayObject>()) {
1872 Handle<TypedArrayObject*> tobj = obj.as<TypedArrayObject>();
1873 size_t len = tobj->length().valueOr(0);
1874
1875 // Fail early if the typed array contains too many elements for a
1876 // dense array, because we likely OOM anyway when trying to allocate
1877 // more than 2GB for the properties vector. This also means we don't
1878 // need to handle indices greater than MAX_INT32 in the loop below.
1879 if (len > NativeObject::MAX_DENSE_ELEMENTS_COUNT) {
1880 ReportOversizedAllocation(cx, JSMSG_ALLOC_OVERFLOW);
1881 return false;
1882 }
1883
1884 MOZ_ASSERT(num_properties == 0, "typed arrays cannot have dense elements");
1885 num_properties = len;
1886 }
1887
1888 // All enumerable properties with string property keys are data
1889 // properties. This allows us to collect the property values while
1890 // iterating over the shape hierarchy without worrying over accessors
1891 // modifying any state.
1892
1893 if (nobj->hasEnumerableProperty()) {
1894 for (ShapePropertyIter<AllowGC::NoGC> iter(obj.as<NativeObject>()->shape());
1895 !iter.done(); iter++) {
1896 jsid id = iter->key();
1897 if (!iter->enumerable() || id.isSymbol()) {
1898 continue;
1899 }
1900 MOZ_ASSERT(!id.isInt(), "Unexpected indexed property");
1901 num_properties += 1;
1902 }
1903 }
1904
1905 rval = num_properties;
1906 return true;
1907 }
1908
1909 // ES2018 draft rev c164be80f7ea91de5526b33d54e5c9321ed03d3f
1910 // 7.3.21 EnumerableOwnProperties ( O, kind )
1911 template <EnumerableOwnPropertiesKind kind>
1912 static bool EnumerableOwnProperties(JSContext* cx, const JS::CallArgs& args) {
1913 static_assert(kind == EnumerableOwnPropertiesKind::Values ||
1914 kind == EnumerableOwnPropertiesKind::KeysAndValues,
1915 "Only implemented for Object.keys and Object.entries");
1916
1917 // Step 1. (Step 1 of Object.{keys,values,entries}, really.)
1918 RootedObject obj(cx, ToObject(cx, args.get(0)));
1919 if (!obj) {
1920 return false;
1921 }
1922
1923 bool optimized;
1924 if (!TryEnumerableOwnPropertiesNative<kind>(cx, obj, args.rval(),
1925 &optimized)) {
1926 return false;
1927 }
1928 if (optimized) {
1929 return true;
1930 }
1931
1932 // Typed arrays are always handled in the fast path.
1933 MOZ_ASSERT(!obj->is<TypedArrayObject>());
1934
1935 // Step 2.
1936 RootedIdVector ids(cx);
1937 if (!GetPropertyKeys(cx, obj, JSITER_OWNONLY | JSITER_HIDDEN, &ids)) {
1938 return false;
1939 }
1940
1941 // Step 3.
1942 RootedValueVector properties(cx);
1943 size_t len = ids.length();
1944 if (!properties.resize(len)) {
1945 return false;
1946 }
1947
1948 RootedId id(cx);
1949 RootedValue key(cx);
1950 RootedValue value(cx);
1951 Rooted<Shape*> shape(cx);
1952 Rooted<Maybe<PropertyDescriptor>> desc(cx);
1953 // Step 4.
1954 size_t out = 0;
1955 for (size_t i = 0; i < len; i++) {
1956 id = ids[i];
1957
1958 // Step 4.a. (Symbols were filtered out in step 2.)
1959 MOZ_ASSERT(!id.isSymbol());
1960
1961 if (kind != EnumerableOwnPropertiesKind::Values) {
1962 if (!IdToStringOrSymbol(cx, id, &key)) {
1963 return false;
1964 }
1965 }
1966
1967 // Step 4.a.i.
1968 if (obj->is<NativeObject>()) {
1969 Handle<NativeObject*> nobj = obj.as<NativeObject>();
1970 if (id.isInt() && nobj->containsDenseElement(id.toInt())) {
1971 value.set(nobj->getDenseElement(id.toInt()));
1972 } else {
1973 Maybe<PropertyInfo> prop = nobj->lookup(cx, id);
1974 if (prop.isNothing() || !prop->enumerable()) {
1975 continue;
1976 }
1977 if (prop->isDataProperty()) {
1978 value = nobj->getSlot(prop->slot());
1979 } else if (!GetProperty(cx, obj, obj, id, &value)) {
1980 return false;
1981 }
1982 }
1983 } else {
1984 if (!GetOwnPropertyDescriptor(cx, obj, id, &desc)) {
1985 return false;
1986 }
1987
1988 // Step 4.a.ii. (inverted.)
1989 if (desc.isNothing() || !desc->enumerable()) {
1990 continue;
1991 }
1992
1993 // Step 4.a.ii.1.
1994 // (Omitted because Object.keys doesn't use this implementation.)
1995
1996 // Step 4.a.ii.2.a.
1997 if (!GetProperty(cx, obj, obj, id, &value)) {
1998 return false;
1999 }
2000 }
2001
2002 // Steps 4.a.ii.2.b-c.
2003 if (kind == EnumerableOwnPropertiesKind::Values) {
2004 properties[out++].set(value);
2005 } else if (!NewValuePair(cx, key, value, properties[out++])) {
2006 return false;
2007 }
2008 }
2009
2010 // Step 5.
2011 // (Implemented in step 2.)
2012
2013 // Step 3 of Object.{keys,values,entries}
2014 JSObject* aobj = NewDenseCopiedArray(cx, out, properties.begin());
2015 if (!aobj) {
2016 return false;
2017 }
2018
2019 args.rval().setObject(*aobj);
2020 return true;
2021 }
2022
2023 // ES2018 draft rev c164be80f7ea91de5526b33d54e5c9321ed03d3f
2024 // 19.1.2.16 Object.keys ( O )
2025 bool js::obj_keys(JSContext* cx, unsigned argc, Value* vp) {
2026 AutoJSMethodProfilerEntry pseudoFrame(cx, "Object", "keys");
2027 CallArgs args = CallArgsFromVp(argc, vp);
2028
2029 // Step 1.
2030 RootedObject obj(cx, ToObject(cx, args.get(0)));
2031 if (!obj) {
2032 return false;
2033 }
2034
2035 bool optimized;
2036 static constexpr EnumerableOwnPropertiesKind kind =
2037 EnumerableOwnPropertiesKind::Keys;
2038 if (!TryEnumerableOwnPropertiesNative<kind>(cx, obj, args.rval(),
2039 &optimized)) {
2040 return false;
2041 }
2042 if (optimized) {
2043 return true;
2044 }
2045
2046 // Steps 2-3.
2047 return GetOwnPropertyKeys(cx, obj, JSITER_OWNONLY, args.rval());
2048 }
2049
2050 bool js::obj_keys_length(JSContext* cx, HandleObject obj, int32_t& length) {
2051 bool optimized;
2052 if (!CountEnumerableOwnPropertiesNative(cx, obj, length, &optimized)) {
2053 return false;
2054 }
2055 if (optimized) {
2056 return true;
2057 }
2058
2059 // Object.keys: Steps 2-3.
2060 // (GetOwnPropertyKeys / CountOwnPropertyKeys)
2061 RootedIdVector keys(cx);
2062 if (!GetPropertyKeys(cx, obj, JSITER_OWNONLY, &keys)) {
2063 return false;
2064 }
2065
2066 length = keys.length();
2067 return true;
2068 }
2069
2070 // ES2018 draft rev c164be80f7ea91de5526b33d54e5c9321ed03d3f
2071 // 19.1.2.21 Object.values ( O )
2072 static bool obj_values(JSContext* cx, unsigned argc, Value* vp) {
2073 AutoJSMethodProfilerEntry pseudoFrame(cx, "Object", "values");
2074 CallArgs args = CallArgsFromVp(argc, vp);
2075
2076 // Steps 1-3.
2077 return EnumerableOwnProperties<EnumerableOwnPropertiesKind::Values>(cx, args);
2078 }
2079
2080 // ES2018 draft rev c164be80f7ea91de5526b33d54e5c9321ed03d3f
2081 // 19.1.2.5 Object.entries ( O )
2082 static bool obj_entries(JSContext* cx, unsigned argc, Value* vp) {
2083 AutoJSMethodProfilerEntry pseudoFrame(cx, "Object", "entries");
2084 CallArgs args = CallArgsFromVp(argc, vp);
2085
2086 // Steps 1-3.
2087 return EnumerableOwnProperties<EnumerableOwnPropertiesKind::KeysAndValues>(
2088 cx, args);
2089 }
2090
2091 /* ES6 draft 15.2.3.16 */
2092 bool js::obj_is(JSContext* cx, unsigned argc, Value* vp) {
2093 CallArgs args = CallArgsFromVp(argc, vp);
2094
2095 bool same;
2096 if (!SameValue(cx, args.get(0), args.get(1), &same)) {
2097 return false;
2098 }
2099
2100 args.rval().setBoolean(same);
2101 return true;
2102 }
2103
2104 bool js::IdToStringOrSymbol(JSContext* cx, HandleId id,
2105 MutableHandleValue result) {
2106 if (id.isInt()) {
2107 JSString* str = Int32ToString<CanGC>(cx, id.toInt());
2108 if (!str) {
2109 return false;
2110 }
2111 result.setString(str);
2112 } else if (id.isAtom()) {
2113 result.setString(id.toAtom());
2114 } else {
2115 result.setSymbol(id.toSymbol());
2116 }
2117 return true;
2118 }
2119
2120 // ES2018 draft rev c164be80f7ea91de5526b33d54e5c9321ed03d3f
2121 // 19.1.2.10.1 Runtime Semantics: GetOwnPropertyKeys ( O, Type )
2122 bool js::GetOwnPropertyKeys(JSContext* cx, HandleObject obj, unsigned flags,
2123 MutableHandleValue rval) {
2124 // Step 1 (Performed in caller).
2125
2126 // Steps 2-4.
2127 RootedIdVector keys(cx);
2128 if (!GetPropertyKeys(cx, obj, flags, &keys)) {
2129 return false;
2130 }
2131
2132 // Step 5 (Inlined CreateArrayFromList).
2133 Rooted<ArrayObject*> array(cx,
2134 NewDenseFullyAllocatedArray(cx, keys.length()));
2135 if (!array) {
2136 return false;
2137 }
2138
2139 array->ensureDenseInitializedLength(0, keys.length());
2140
2141 RootedValue val(cx);
2142 for (size_t i = 0, len = keys.length(); i < len; i++) {
2143 MOZ_ASSERT_IF(keys[i].isSymbol(), flags & JSITER_SYMBOLS);
2144 MOZ_ASSERT_IF(!keys[i].isSymbol(), !(flags & JSITER_SYMBOLSONLY));
2145 if (!IdToStringOrSymbol(cx, keys[i], &val)) {
2146 return false;
2147 }
2148 array->initDenseElement(i, val);
2149 }
2150
2151 rval.setObject(*array);
2152 return true;
2153 }
2154
2155 // ES2018 draft rev c164be80f7ea91de5526b33d54e5c9321ed03d3f
2156 // 19.1.2.9 Object.getOwnPropertyNames ( O )
2157 static bool obj_getOwnPropertyNames(JSContext* cx, unsigned argc, Value* vp) {
2158 AutoJSMethodProfilerEntry pseudoFrame(cx, "Object", "getOwnPropertyNames");
2159 CallArgs args = CallArgsFromVp(argc, vp);
2160
2161 RootedObject obj(cx, ToObject(cx, args.get(0)));
2162 if (!obj) {
2163 return false;
2164 }
2165
2166 bool optimized;
2167 static constexpr EnumerableOwnPropertiesKind kind =
2168 EnumerableOwnPropertiesKind::Names;
2169 if (!TryEnumerableOwnPropertiesNative<kind>(cx, obj, args.rval(),
2170 &optimized)) {
2171 return false;
2172 }
2173 if (optimized) {
2174 return true;
2175 }
2176
2177 return GetOwnPropertyKeys(cx, obj, JSITER_OWNONLY | JSITER_HIDDEN,
2178 args.rval());
2179 }
2180
2181 // ES2018 draft rev c164be80f7ea91de5526b33d54e5c9321ed03d3f
2182 // 19.1.2.10 Object.getOwnPropertySymbols ( O )
2183 static bool obj_getOwnPropertySymbols(JSContext* cx, unsigned argc, Value* vp) {
2184 AutoJSMethodProfilerEntry pseudoFrame(cx, "Object", "getOwnPropertySymbols");
2185 CallArgs args = CallArgsFromVp(argc, vp);
2186
2187 RootedObject obj(cx, ToObject(cx, args.get(0)));
2188 if (!obj) {
2189 return false;
2190 }
2191
2192 return GetOwnPropertyKeys(
2193 cx, obj,
2194 JSITER_OWNONLY | JSITER_HIDDEN | JSITER_SYMBOLS | JSITER_SYMBOLSONLY,
2195 args.rval());
2196 }
2197
2198 /* ES5 15.2.3.7: Object.defineProperties(O, Properties) */
2199 static bool obj_defineProperties(JSContext* cx, unsigned argc, Value* vp) {
2200 AutoJSMethodProfilerEntry pseudoFrame(cx, "Object", "defineProperties");
2201 CallArgs args = CallArgsFromVp(argc, vp);
2202
2203 /* Step 1. */
2204 RootedObject obj(cx);
2205 if (!GetFirstArgumentAsObject(cx, args, "Object.defineProperties", &obj)) {
2206 return false;
2207 }
2208
2209 /* Step 2. */
2210 if (!args.requireAtLeast(cx, "Object.defineProperties", 2)) {
2211 return false;
2212 }
2213
2214 /* Steps 3-6. */
2215 bool failedOnWindowProxy = false;
2216 if (!ObjectDefineProperties(cx, obj, args[1], &failedOnWindowProxy)) {
2217 return false;
2218 }
2219
2220 /* Step 7, but modified to deal with WindowProxy mess */
2221 if (failedOnWindowProxy) {
2222 args.rval().setNull();
2223 } else {
2224 args.rval().setObject(*obj);
2225 }
2226 return true;
2227 }
2228
2229 // ES6 20141014 draft 19.1.2.15 Object.preventExtensions(O)
2230 static bool obj_preventExtensions(JSContext* cx, unsigned argc, Value* vp) {
2231 CallArgs args = CallArgsFromVp(argc, vp);
2232 args.rval().set(args.get(0));
2233
2234 // Step 1.
2235 if (!args.get(0).isObject()) {
2236 return true;
2237 }
2238
2239 // Steps 2-5.
2240 RootedObject obj(cx, &args.get(0).toObject());
2241 return PreventExtensions(cx, obj);
2242 }
2243
2244 // ES6 draft rev27 (2014/08/24) 19.1.2.5 Object.freeze(O)
2245 static bool obj_freeze(JSContext* cx, unsigned argc, Value* vp) {
2246 CallArgs args = CallArgsFromVp(argc, vp);
2247 args.rval().set(args.get(0));
2248
2249 // Step 1.
2250 if (!args.get(0).isObject()) {
2251 return true;
2252 }
2253
2254 // Steps 2-5.
2255 RootedObject obj(cx, &args.get(0).toObject());
2256 return SetIntegrityLevel(cx, obj, IntegrityLevel::Frozen);
2257 }
2258
2259 // ES6 draft rev27 (2014/08/24) 19.1.2.12 Object.isFrozen(O)
2260 static bool obj_isFrozen(JSContext* cx, unsigned argc, Value* vp) {
2261 CallArgs args = CallArgsFromVp(argc, vp);
2262
2263 // Step 1.
2264 bool frozen = true;
2265
2266 // Step 2.
2267 if (args.get(0).isObject()) {
2268 RootedObject obj(cx, &args.get(0).toObject());
2269 if (!TestIntegrityLevel(cx, obj, IntegrityLevel::Frozen, &frozen)) {
2270 return false;
2271 }
2272 }
2273 args.rval().setBoolean(frozen);
2274 return true;
2275 }
2276
2277 // ES6 draft rev27 (2014/08/24) 19.1.2.17 Object.seal(O)
2278 static bool obj_seal(JSContext* cx, unsigned argc, Value* vp) {
2279 CallArgs args = CallArgsFromVp(argc, vp);
2280 args.rval().set(args.get(0));
2281
2282 // Step 1.
2283 if (!args.get(0).isObject()) {
2284 return true;
2285 }
2286
2287 // Steps 2-5.
2288 RootedObject obj(cx, &args.get(0).toObject());
2289 return SetIntegrityLevel(cx, obj, IntegrityLevel::Sealed);
2290 }
2291
2292 // ES6 draft rev27 (2014/08/24) 19.1.2.13 Object.isSealed(O)
2293 static bool obj_isSealed(JSContext* cx, unsigned argc, Value* vp) {
2294 CallArgs args = CallArgsFromVp(argc, vp);
2295
2296 // Step 1.
2297 bool sealed = true;
2298
2299 // Step 2.
2300 if (args.get(0).isObject()) {
2301 RootedObject obj(cx, &args.get(0).toObject());
2302 if (!TestIntegrityLevel(cx, obj, IntegrityLevel::Sealed, &sealed)) {
2303 return false;
2304 }
2305 }
2306 args.rval().setBoolean(sealed);
2307 return true;
2308 }
2309
2310 bool js::obj_setProto(JSContext* cx, unsigned argc, Value* vp) {
2311 CallArgs args = CallArgsFromVp(argc, vp);
2312 MOZ_ASSERT(args.length() == 1);
2313
2314 HandleValue thisv = args.thisv();
2315 if (thisv.isNullOrUndefined()) {
2316 ReportIncompatible(cx, args);
2317 return false;
2318 }
2319 if (thisv.isPrimitive()) {
2320 // Mutating a boxed primitive's [[Prototype]] has no side effects.
2321 args.rval().setUndefined();
2322 return true;
2323 }
2324
2325 /* Do nothing if __proto__ isn't being set to an object or null. */
2326 if (!args[0].isObjectOrNull()) {
2327 args.rval().setUndefined();
2328 return true;
2329 }
2330
2331 Rooted<JSObject*> obj(cx, &args.thisv().toObject());
2332 Rooted<JSObject*> newProto(cx, args[0].toObjectOrNull());
2333 if (!SetPrototype(cx, obj, newProto)) {
2334 return false;
2335 }
2336
2337 args.rval().setUndefined();
2338 return true;
2339 }
2340
2341 static const JSFunctionSpec object_methods[] = {
2342 JS_FN("toSource", obj_toSource, 0, 0),
2343 JS_INLINABLE_FN("toString", obj_toString, 0, 0, ObjectToString),
2344 JS_SELF_HOSTED_FN("toLocaleString", "Object_toLocaleString", 0, 0),
2345 JS_SELF_HOSTED_FN("valueOf", "Object_valueOf", 0, 0),
2346 JS_SELF_HOSTED_FN("hasOwnProperty", "Object_hasOwnProperty", 1, 0),
2347 JS_INLINABLE_FN("isPrototypeOf", obj_isPrototypeOf, 1, 0,
2348 ObjectIsPrototypeOf),
2349 JS_FN("propertyIsEnumerable", obj_propertyIsEnumerable, 1, 0),
2350 JS_SELF_HOSTED_FN("__defineGetter__", "ObjectDefineGetter", 2, 0),
2351 JS_SELF_HOSTED_FN("__defineSetter__", "ObjectDefineSetter", 2, 0),
2352 JS_SELF_HOSTED_FN("__lookupGetter__", "ObjectLookupGetter", 1, 0),
2353 JS_SELF_HOSTED_FN("__lookupSetter__", "ObjectLookupSetter", 1, 0),
2354 JS_FS_END,
2355 };
2356
2357 static const JSPropertySpec object_properties[] = {
2358 JS_SELF_HOSTED_GETSET("__proto__", "$ObjectProtoGetter",
2359 "$ObjectProtoSetter", 0),
2360 JS_PS_END,
2361 };
2362
2363 static const JSFunctionSpec object_static_methods[] = {
2364 JS_FN("assign", obj_assign, 2, 0),
2365 JS_SELF_HOSTED_FN("getPrototypeOf", "ObjectGetPrototypeOf", 1, 0),
2366 JS_FN("setPrototypeOf", obj_setPrototypeOf, 2, 0),
2367 JS_SELF_HOSTED_FN("getOwnPropertyDescriptor",
2368 "ObjectGetOwnPropertyDescriptor", 2, 0),
2369 JS_SELF_HOSTED_FN("getOwnPropertyDescriptors",
2370 "ObjectGetOwnPropertyDescriptors", 1, 0),
2371 JS_INLINABLE_FN("keys", obj_keys, 1, 0, ObjectKeys),
2372 JS_FN("values", obj_values, 1, 0),
2373 JS_FN("entries", obj_entries, 1, 0),
2374 JS_INLINABLE_FN("is", obj_is, 2, 0, ObjectIs),
2375 JS_SELF_HOSTED_FN("defineProperty", "ObjectDefineProperty", 3, 0),
2376 JS_FN("defineProperties", obj_defineProperties, 2, 0),
2377 JS_INLINABLE_FN("create", obj_create, 2, 0, ObjectCreate),
2378 JS_FN("getOwnPropertyNames", obj_getOwnPropertyNames, 1, 0),
2379 JS_FN("getOwnPropertySymbols", obj_getOwnPropertySymbols, 1, 0),
2380 JS_SELF_HOSTED_FN("isExtensible", "ObjectIsExtensible", 1, 0),
2381 JS_FN("preventExtensions", obj_preventExtensions, 1, 0),
2382 JS_FN("freeze", obj_freeze, 1, 0),
2383 JS_FN("isFrozen", obj_isFrozen, 1, 0),
2384 JS_FN("seal", obj_seal, 1, 0),
2385 JS_FN("isSealed", obj_isSealed, 1, 0),
2386 JS_SELF_HOSTED_FN("fromEntries", "ObjectFromEntries", 1, 0),
2387 JS_SELF_HOSTED_FN("hasOwn", "ObjectHasOwn", 2, 0),
2388 JS_SELF_HOSTED_FN("groupBy", "ObjectGroupBy", 2, 0),
2389 JS_FS_END,
2390 };
2391
2392 static JSObject* CreateObjectConstructor(JSContext* cx, JSProtoKey key) {
2393 Rooted<GlobalObject*> self(cx, cx->global());
2394 if (!GlobalObject::ensureConstructor(cx, self, JSProto_Function)) {
2395 return nullptr;
2396 }
2397
2398 /* Create the Object function now that we have a [[Prototype]] for it. */
2399 JSFunction* fun = NewNativeConstructor(
2400 cx, obj_construct, 1, Handle<PropertyName*>(cx->names().Object),
2401 gc::AllocKind::FUNCTION, TenuredObject);
2402 if (!fun) {
2403 return nullptr;
2404 }
2405
2406 fun->setJitInfo(&jit::JitInfo_Object);
2407 return fun;
2408 }
2409
2410 static JSObject* CreateObjectPrototype(JSContext* cx, JSProtoKey key) {
2411 MOZ_ASSERT(!cx->zone()->isAtomsZone());
2412 MOZ_ASSERT(cx->global()->is<NativeObject>());
2413
2414 /*
2415 * Create |Object.prototype| first, mirroring CreateBlankProto but for the
2416 * prototype of the created object.
2417 */
2418 Rooted<PlainObject*> objectProto(
2419 cx, NewPlainObjectWithProto(cx, nullptr, TenuredObject));
2420 if (!objectProto) {
2421 return nullptr;
2422 }
2423
2424 bool succeeded;
2425 if (!SetImmutablePrototype(cx, objectProto, &succeeded)) {
2426 return nullptr;
2427 }
2428 MOZ_ASSERT(succeeded,
2429 "should have been able to make a fresh Object.prototype's "
2430 "[[Prototype]] immutable");
2431
2432 return objectProto;
2433 }
2434
2435 static bool FinishObjectClassInit(JSContext* cx, JS::HandleObject ctor,
2436 JS::HandleObject proto) {
2437 Rooted<GlobalObject*> global(cx, cx->global());
2438
2439 // ES5 15.1.2.1.
2440 RootedId evalId(cx, NameToId(cx->names().eval));
2441 JSFunction* evalobj =
2442 DefineFunction(cx, global, evalId, IndirectEval, 1, JSPROP_RESOLVING);
2443 if (!evalobj) {
2444 return false;
2445 }
2446 global->setOriginalEval(evalobj);
2447
2448 #ifdef FUZZING
2449 if (cx->options().fuzzing()) {
2450 if (!DefineTestingFunctions(cx, global, /* fuzzingSafe = */ true,
2451 /* disableOOMFunctions = */ false)) {
2452 return false;
2453 }
2454 }
2455 #endif
2456
2457 // The global object should have |Object.prototype| as its [[Prototype]].
2458 MOZ_ASSERT(global->staticPrototype() == nullptr);
2459 MOZ_ASSERT(!global->staticPrototypeIsImmutable());
2460 return SetPrototype(cx, global, proto);
2461 }
2462
2463 static const ClassSpec PlainObjectClassSpec = {
2464 CreateObjectConstructor, CreateObjectPrototype,
2465 object_static_methods, nullptr,
2466 object_methods, object_properties,
2467 FinishObjectClassInit,
2468 };
2469
2470 const JSClass PlainObject::class_ = {
2471 "Object",
2472 JSCLASS_HAS_CACHED_PROTO(JSProto_Object),
2473 JS_NULL_CLASS_OPS,
2474 &PlainObjectClassSpec,
2475 };
2476
2477 const JSClass* const js::ObjectClassPtr = &PlainObject::class_;