Line data Source code
1 : // Copyright 2013 the V8 project authors. All rights reserved.
2 : // Use of this source code is governed by a BSD-style license that can be
3 : // found in the LICENSE file.
4 :
5 : #include "src/keys.h"
6 :
7 : #include "src/api-arguments-inl.h"
8 : #include "src/elements-inl.h"
9 : #include "src/field-index-inl.h"
10 : #include "src/handles-inl.h"
11 : #include "src/heap/factory.h"
12 : #include "src/identity-map.h"
13 : #include "src/isolate-inl.h"
14 : #include "src/objects-inl.h"
15 : #include "src/objects/api-callbacks.h"
16 : #include "src/objects/hash-table-inl.h"
17 : #include "src/objects/module-inl.h"
18 : #include "src/objects/ordered-hash-table-inl.h"
19 : #include "src/property-descriptor.h"
20 : #include "src/prototype.h"
21 :
22 : namespace v8 {
23 : namespace internal {
24 :
25 : namespace {
26 :
27 : static bool ContainsOnlyValidKeys(Handle<FixedArray> array) {
28 : int len = array->length();
29 : for (int i = 0; i < len; i++) {
30 : Object e = array->get(i);
31 : if (!(e->IsName() || e->IsNumber())) return false;
32 : }
33 : return true;
34 : }
35 :
36 : } // namespace
37 :
38 : // static
39 1330800 : MaybeHandle<FixedArray> KeyAccumulator::GetKeys(
40 : Handle<JSReceiver> object, KeyCollectionMode mode, PropertyFilter filter,
41 : GetKeysConversion keys_conversion, bool is_for_in, bool skip_indices) {
42 : Isolate* isolate = object->GetIsolate();
43 : FastKeyAccumulator accumulator(isolate, object, mode, filter, is_for_in,
44 : skip_indices);
45 1330800 : return accumulator.GetKeys(keys_conversion);
46 : }
47 :
48 1430904 : Handle<FixedArray> KeyAccumulator::GetKeys(GetKeysConversion convert) {
49 1182090 : if (keys_.is_null()) {
50 931612 : return isolate_->factory()->empty_fixed_array();
51 : }
52 493662 : if (mode_ == KeyCollectionMode::kOwnOnly &&
53 243184 : keys_->map() == ReadOnlyRoots(isolate_).fixed_array_map()) {
54 1664 : return Handle<FixedArray>::cast(keys_);
55 : }
56 : USE(ContainsOnlyValidKeys);
57 : Handle<FixedArray> result =
58 248814 : OrderedHashSet::ConvertToKeysArray(isolate(), keys(), convert);
59 : DCHECK(ContainsOnlyValidKeys(result));
60 248814 : return result;
61 : }
62 :
63 0 : Handle<OrderedHashSet> KeyAccumulator::keys() {
64 10284386 : return Handle<OrderedHashSet>::cast(keys_);
65 : }
66 :
67 3943448 : void KeyAccumulator::AddKey(Object key, AddKeyConversion convert) {
68 7886896 : AddKey(handle(key, isolate_), convert);
69 3943448 : }
70 :
71 20080522 : void KeyAccumulator::AddKey(Handle<Object> key, AddKeyConversion convert) {
72 20089900 : if (key->IsSymbol()) {
73 55042 : if (filter_ & SKIP_SYMBOLS) return;
74 91214 : if (Handle<Symbol>::cast(key)->is_private()) return;
75 9999286 : } else if (filter_ & SKIP_STRINGS) {
76 : return;
77 : }
78 10044887 : if (IsShadowed(key)) return;
79 10035572 : if (keys_.is_null()) {
80 248847 : keys_ = OrderedHashSet::Allocate(isolate_, 16);
81 : }
82 : uint32_t index;
83 20075791 : if (convert == CONVERT_TO_ARRAY_INDEX && key->IsString() &&
84 10037886 : Handle<String>::cast(key)->AsArrayIndex(&index)) {
85 374 : key = isolate_->factory()->NewNumberFromUint(index);
86 : }
87 10035572 : Handle<OrderedHashSet> new_set = OrderedHashSet::Add(isolate(), keys(), key);
88 10035572 : if (*new_set != *keys_) {
89 : // The keys_ Set is converted directly to a FixedArray in GetKeys which can
90 : // be left-trimmer. Hence the previous Set should not keep a pointer to the
91 : // new one.
92 195526 : keys_->set(OrderedHashSet::NextTableIndex(), Smi::kZero);
93 195526 : keys_ = new_set;
94 : }
95 : }
96 :
97 994160 : void KeyAccumulator::AddKeys(Handle<FixedArray> array,
98 : AddKeyConversion convert) {
99 : int add_length = array->length();
100 3576588 : for (int i = 0; i < add_length; i++) {
101 2582428 : Handle<Object> current(array->get(i), isolate_);
102 2582428 : AddKey(current, convert);
103 : }
104 994160 : }
105 :
106 309 : void KeyAccumulator::AddKeys(Handle<JSObject> array_like,
107 : AddKeyConversion convert) {
108 : DCHECK(array_like->IsJSArray() || array_like->HasSloppyArgumentsElements());
109 309 : ElementsAccessor* accessor = array_like->GetElementsAccessor();
110 309 : accessor->AddElementsToKeyAccumulator(array_like, this, convert);
111 309 : }
112 :
113 2945 : MaybeHandle<FixedArray> FilterProxyKeys(KeyAccumulator* accumulator,
114 : Handle<JSProxy> owner,
115 : Handle<FixedArray> keys,
116 : PropertyFilter filter) {
117 1783 : if (filter == ALL_PROPERTIES) {
118 : // Nothing to do.
119 621 : return keys;
120 : }
121 : Isolate* isolate = accumulator->isolate();
122 : int store_position = 0;
123 9106 : for (int i = 0; i < keys->length(); ++i) {
124 : Handle<Name> key(Name::cast(keys->get(i)), isolate);
125 3463 : if (key->FilterKey(filter)) continue; // Skip this key.
126 3199 : if (filter & ONLY_ENUMERABLE) {
127 : PropertyDescriptor desc;
128 : Maybe<bool> found =
129 1714 : JSProxy::GetOwnPropertyDescriptor(isolate, owner, key, &desc);
130 1714 : MAYBE_RETURN(found, MaybeHandle<FixedArray>());
131 1885 : if (!found.FromJust()) continue;
132 1525 : if (!desc.enumerable()) {
133 126 : accumulator->AddShadowingKey(key);
134 126 : continue;
135 : }
136 : }
137 : // Keep this key.
138 2884 : if (store_position != i) {
139 180 : keys->set(store_position, *key);
140 : }
141 2884 : store_position++;
142 : }
143 1090 : return FixedArray::ShrinkOrEmpty(isolate, keys, store_position);
144 : }
145 :
146 : // Returns "nothing" in case of exception, "true" on success.
147 923869 : Maybe<bool> KeyAccumulator::AddKeysFromJSProxy(Handle<JSProxy> proxy,
148 : Handle<FixedArray> keys) {
149 : // Postpone the enumerable check for for-in to the ForInFilter step.
150 923869 : if (!is_for_in_) {
151 3566 : ASSIGN_RETURN_ON_EXCEPTION_VALUE(
152 : isolate_, keys, FilterProxyKeys(this, proxy, keys, filter_),
153 : Nothing<bool>());
154 1711 : if (mode_ == KeyCollectionMode::kOwnOnly) {
155 : // If we collect only the keys from a JSProxy do not sort or deduplicate.
156 1664 : keys_ = keys;
157 : return Just(true);
158 : }
159 : }
160 922133 : AddKeys(keys, is_for_in_ ? CONVERT_TO_ARRAY_INDEX : DO_NOT_CONVERT);
161 : return Just(true);
162 : }
163 :
164 1193762 : Maybe<bool> KeyAccumulator::CollectKeys(Handle<JSReceiver> receiver,
165 : Handle<JSReceiver> object) {
166 : // Proxies have no hidden prototype and we should not trigger the
167 : // [[GetPrototypeOf]] trap on the last iteration when using
168 : // AdvanceFollowingProxies.
169 3565540 : if (mode_ == KeyCollectionMode::kOwnOnly && object->IsJSProxy()) {
170 19036 : MAYBE_RETURN(CollectOwnJSProxyKeys(receiver, Handle<JSProxy>::cast(object)),
171 : Nothing<bool>());
172 : return Just(true);
173 : }
174 :
175 1174726 : PrototypeIterator::WhereToEnd end = mode_ == KeyCollectionMode::kOwnOnly
176 : ? PrototypeIterator::END_AT_NON_HIDDEN
177 1174726 : : PrototypeIterator::END_AT_NULL;
178 4493120 : for (PrototypeIterator iter(isolate_, object, kStartAtReceiver, end);
179 3318394 : !iter.IsAtEnd();) {
180 : // Start the shadow checks only after the first prototype has added
181 : // shadowing keys.
182 2145275 : if (HasShadowingKeys()) skip_shadow_check_ = false;
183 : Handle<JSReceiver> current =
184 : PrototypeIterator::GetCurrent<JSReceiver>(iter);
185 : Maybe<bool> result = Just(false); // Dummy initialization.
186 4290550 : if (current->IsJSProxy()) {
187 922196 : result = CollectOwnJSProxyKeys(receiver, Handle<JSProxy>::cast(current));
188 : } else {
189 : DCHECK(current->IsJSObject());
190 1223079 : result = CollectOwnKeys(receiver, Handle<JSObject>::cast(current));
191 : }
192 2145275 : MAYBE_RETURN(result, Nothing<bool>());
193 2145119 : if (!result.FromJust()) break; // |false| means "stop iterating".
194 : // Iterate through proxies but ignore access checks for the ALL_CAN_READ
195 : // case on API objects for OWN_ONLY keys handled in CollectOwnKeys.
196 2145082 : if (!iter.AdvanceFollowingProxiesIgnoringAccessChecks()) {
197 : return Nothing<bool>();
198 : }
199 2148112 : if (!last_non_empty_prototype_.is_null() &&
200 : *last_non_empty_prototype_ == *current) {
201 : break;
202 : }
203 : }
204 : return Just(true);
205 : }
206 :
207 0 : bool KeyAccumulator::HasShadowingKeys() { return !shadowing_keys_.is_null(); }
208 :
209 10044887 : bool KeyAccumulator::IsShadowed(Handle<Object> key) {
210 10044887 : if (!HasShadowingKeys() || skip_shadow_check_) return false;
211 19854 : return shadowing_keys_->Has(isolate_, key);
212 : }
213 :
214 110981 : void KeyAccumulator::AddShadowingKey(Object key) {
215 221962 : if (mode_ == KeyCollectionMode::kOwnOnly) return;
216 214686 : AddShadowingKey(handle(key, isolate_));
217 : }
218 214812 : void KeyAccumulator::AddShadowingKey(Handle<Object> key) {
219 214938 : if (mode_ == KeyCollectionMode::kOwnOnly) return;
220 107343 : if (shadowing_keys_.is_null()) {
221 6614 : shadowing_keys_ = ObjectHashSet::New(isolate_, 16);
222 : }
223 107343 : shadowing_keys_ = ObjectHashSet::Add(isolate(), shadowing_keys_, key);
224 : }
225 :
226 : namespace {
227 :
228 4645 : void TrySettingEmptyEnumCache(JSReceiver object) {
229 4645 : Map map = object->map();
230 : DCHECK_EQ(kInvalidEnumCacheSentinel, map->EnumLength());
231 5657 : if (!map->OnlyHasSimpleProperties()) return;
232 3975 : if (map->IsJSProxyMap()) return;
233 3975 : if (map->NumberOfEnumerableProperties() > 0) return;
234 : DCHECK(object->IsJSObject());
235 3633 : map->SetEnumLength(0);
236 : }
237 :
238 101183 : bool CheckAndInitalizeEmptyEnumCache(JSReceiver object) {
239 101183 : if (object->map()->EnumLength() == kInvalidEnumCacheSentinel) {
240 4645 : TrySettingEmptyEnumCache(object);
241 : }
242 101183 : if (object->map()->EnumLength() != 0) return false;
243 : DCHECK(object->IsJSObject());
244 99703 : return !JSObject::cast(object)->HasEnumerableElements();
245 : }
246 : } // namespace
247 :
248 1384842 : void FastKeyAccumulator::Prepare() {
249 : DisallowHeapAllocation no_gc;
250 : // Directly go for the fast path for OWN_ONLY keys.
251 2769684 : if (mode_ == KeyCollectionMode::kOwnOnly) return;
252 : // Fully walk the prototype chain and find the last prototype with keys.
253 54042 : is_receiver_simple_enum_ = false;
254 54042 : has_empty_prototype_ = true;
255 : JSReceiver last_prototype;
256 209267 : for (PrototypeIterator iter(isolate_, *receiver_); !iter.IsAtEnd();
257 101183 : iter.Advance()) {
258 101183 : JSReceiver current = iter.GetCurrent<JSReceiver>();
259 101183 : bool has_no_properties = CheckAndInitalizeEmptyEnumCache(current);
260 200841 : if (has_no_properties) continue;
261 1525 : last_prototype = current;
262 1525 : has_empty_prototype_ = false;
263 : }
264 54042 : if (has_empty_prototype_) {
265 : is_receiver_simple_enum_ =
266 96479 : receiver_->map()->EnumLength() != kInvalidEnumCacheSentinel &&
267 96479 : !JSObject::cast(*receiver_)->HasEnumerableElements();
268 1440 : } else if (!last_prototype.is_null()) {
269 2880 : last_non_empty_prototype_ = handle(last_prototype, isolate_);
270 : }
271 : }
272 :
273 : namespace {
274 :
275 174449 : Handle<FixedArray> ReduceFixedArrayTo(Isolate* isolate,
276 : Handle<FixedArray> array, int length) {
277 : DCHECK_LE(length, array->length());
278 174449 : if (array->length() == length) return array;
279 273 : return isolate->factory()->CopyFixedArrayUpTo(array, length);
280 : }
281 :
282 : // Initializes and directly returns the enume cache. Users of this function
283 : // have to make sure to never directly leak the enum cache.
284 222295 : Handle<FixedArray> GetFastEnumPropertyKeys(Isolate* isolate,
285 : Handle<JSObject> object) {
286 : Handle<Map> map(object->map(), isolate);
287 444590 : Handle<FixedArray> keys(map->instance_descriptors()->enum_cache()->keys(),
288 444590 : isolate);
289 :
290 : // Check if the {map} has a valid enum length, which implies that it
291 : // must have a valid enum cache as well.
292 : int enum_length = map->EnumLength();
293 222295 : if (enum_length != kInvalidEnumCacheSentinel) {
294 : DCHECK(map->OnlyHasSimpleProperties());
295 : DCHECK_LE(enum_length, keys->length());
296 : DCHECK_EQ(enum_length, map->NumberOfEnumerableProperties());
297 148272 : isolate->counters()->enum_cache_hits()->Increment();
298 148272 : return ReduceFixedArrayTo(isolate, keys, enum_length);
299 : }
300 :
301 : // Determine the actual number of enumerable properties of the {map}.
302 74023 : enum_length = map->NumberOfEnumerableProperties();
303 :
304 : // Check if there's already a shared enum cache on the {map}s
305 : // DescriptorArray with sufficient number of entries.
306 74023 : if (enum_length <= keys->length()) {
307 31940 : if (map->OnlyHasSimpleProperties()) map->SetEnumLength(enum_length);
308 26177 : isolate->counters()->enum_cache_hits()->Increment();
309 26177 : return ReduceFixedArrayTo(isolate, keys, enum_length);
310 : }
311 :
312 : Handle<DescriptorArray> descriptors =
313 95692 : Handle<DescriptorArray>(map->instance_descriptors(), isolate);
314 47846 : isolate->counters()->enum_cache_misses()->Increment();
315 : int nod = map->NumberOfOwnDescriptors();
316 :
317 : // Create the keys array.
318 : int index = 0;
319 : bool fields_only = true;
320 47846 : keys = isolate->factory()->NewFixedArray(enum_length);
321 360653 : for (int i = 0; i < nod; i++) {
322 : DisallowHeapAllocation no_gc;
323 312807 : PropertyDetails details = descriptors->GetDetails(i);
324 323607 : if (details.IsDontEnum()) continue;
325 302136 : Object key = descriptors->GetKey(i);
326 302136 : if (key->IsSymbol()) continue;
327 302007 : keys->set(index, key);
328 302007 : if (details.location() != kField) fields_only = false;
329 302007 : index++;
330 : }
331 : DCHECK_EQ(index, keys->length());
332 :
333 : // Optionally also create the indices array.
334 : Handle<FixedArray> indices = isolate->factory()->empty_fixed_array();
335 47846 : if (fields_only) {
336 47708 : indices = isolate->factory()->NewFixedArray(enum_length);
337 : index = 0;
338 359924 : for (int i = 0; i < nod; i++) {
339 : DisallowHeapAllocation no_gc;
340 312216 : PropertyDetails details = descriptors->GetDetails(i);
341 322858 : if (details.IsDontEnum()) continue;
342 301703 : Object key = descriptors->GetKey(i);
343 301703 : if (key->IsSymbol()) continue;
344 : DCHECK_EQ(kData, details.kind());
345 : DCHECK_EQ(kField, details.location());
346 301574 : FieldIndex field_index = FieldIndex::ForDescriptor(*map, i);
347 301574 : indices->set(index, Smi::FromInt(field_index.GetLoadByFieldIndex()));
348 301574 : index++;
349 : }
350 : DCHECK_EQ(index, indices->length());
351 : }
352 :
353 : DescriptorArray::InitializeOrChangeEnumCache(descriptors, isolate, keys,
354 47846 : indices);
355 95594 : if (map->OnlyHasSimpleProperties()) map->SetEnumLength(enum_length);
356 :
357 47846 : return keys;
358 : }
359 :
360 : template <bool fast_properties>
361 141622 : MaybeHandle<FixedArray> GetOwnKeysWithElements(Isolate* isolate,
362 : Handle<JSObject> object,
363 : GetKeysConversion convert,
364 : bool skip_indices) {
365 : Handle<FixedArray> keys;
366 141622 : ElementsAccessor* accessor = object->GetElementsAccessor();
367 : if (fast_properties) {
368 135282 : keys = GetFastEnumPropertyKeys(isolate, object);
369 : } else {
370 : // TODO(cbruni): preallocate big enough array to also hold elements.
371 6340 : keys = KeyAccumulator::GetOwnEnumPropertyKeys(isolate, object);
372 : }
373 :
374 : MaybeHandle<FixedArray> result;
375 141622 : if (skip_indices) {
376 : result = keys;
377 : } else {
378 141538 : result =
379 : accessor->PrependElementIndices(object, keys, convert, ONLY_ENUMERABLE);
380 : }
381 :
382 141622 : if (FLAG_trace_for_in_enumerate) {
383 0 : PrintF("| strings=%d symbols=0 elements=%u || prototypes>=1 ||\n",
384 0 : keys->length(), result.ToHandleChecked()->length() - keys->length());
385 : }
386 141622 : return result;
387 : }
388 :
389 : } // namespace
390 :
391 1381993 : MaybeHandle<FixedArray> FastKeyAccumulator::GetKeys(
392 : GetKeysConversion keys_conversion) {
393 1381993 : if (filter_ == ENUMERABLE_STRINGS) {
394 : Handle<FixedArray> keys;
395 470836 : if (GetKeysFast(keys_conversion).ToHandle(&keys)) {
396 194844 : return keys;
397 : }
398 40574 : if (isolate_->has_pending_exception()) return MaybeHandle<FixedArray>();
399 : }
400 :
401 1187149 : return GetKeysSlow(keys_conversion);
402 : }
403 :
404 235418 : MaybeHandle<FixedArray> FastKeyAccumulator::GetKeysFast(
405 : GetKeysConversion keys_conversion) {
406 235418 : bool own_only = has_empty_prototype_ || mode_ == KeyCollectionMode::kOwnOnly;
407 235418 : Map map = receiver_->map();
408 469396 : if (!own_only || map->IsCustomElementsReceiverMap()) {
409 40574 : return MaybeHandle<FixedArray>();
410 : }
411 :
412 : // From this point on we are certain to only collect own keys.
413 : DCHECK(receiver_->IsJSObject());
414 194844 : Handle<JSObject> object = Handle<JSObject>::cast(receiver_);
415 :
416 : // Do not try to use the enum-cache for dict-mode objects.
417 194844 : if (map->is_dictionary_map()) {
418 : return GetOwnKeysWithElements<false>(isolate_, object, keys_conversion,
419 6340 : skip_indices_);
420 : }
421 : int enum_length = receiver_->map()->EnumLength();
422 188504 : if (enum_length == kInvalidEnumCacheSentinel) {
423 : Handle<FixedArray> keys;
424 : // Try initializing the enum cache and return own properties.
425 110628 : if (GetOwnKeysWithUninitializedEnumCache().ToHandle(&keys)) {
426 53222 : if (FLAG_trace_for_in_enumerate) {
427 : PrintF("| strings=%d symbols=0 elements=0 || prototypes>=1 ||\n",
428 0 : keys->length());
429 : }
430 : is_receiver_simple_enum_ =
431 53222 : object->map()->EnumLength() != kInvalidEnumCacheSentinel;
432 53222 : return keys;
433 : }
434 : }
435 : // The properties-only case failed because there were probably elements on the
436 : // receiver.
437 : return GetOwnKeysWithElements<true>(isolate_, object, keys_conversion,
438 135282 : skip_indices_);
439 : }
440 :
441 : MaybeHandle<FixedArray>
442 55314 : FastKeyAccumulator::GetOwnKeysWithUninitializedEnumCache() {
443 55314 : Handle<JSObject> object = Handle<JSObject>::cast(receiver_);
444 : // Uninitalized enum cache
445 55314 : Map map = object->map();
446 110628 : if (object->elements()->length() != 0) {
447 : // Assume that there are elements.
448 2092 : return MaybeHandle<FixedArray>();
449 : }
450 : int number_of_own_descriptors = map->NumberOfOwnDescriptors();
451 53222 : if (number_of_own_descriptors == 0) {
452 4228 : map->SetEnumLength(0);
453 8456 : return isolate_->factory()->empty_fixed_array();
454 : }
455 : // We have no elements but possibly enumerable property keys, hence we can
456 : // directly initialize the enum cache.
457 48994 : Handle<FixedArray> keys = GetFastEnumPropertyKeys(isolate_, object);
458 48994 : if (is_for_in_) return keys;
459 : // Do not leak the enum cache as it might end up as an elements backing store.
460 44356 : return isolate_->factory()->CopyFixedArray(keys);
461 : }
462 :
463 1187149 : MaybeHandle<FixedArray> FastKeyAccumulator::GetKeysSlow(
464 : GetKeysConversion keys_conversion) {
465 1187149 : KeyAccumulator accumulator(isolate_, mode_, filter_);
466 1187149 : accumulator.set_is_for_in(is_for_in_);
467 1187149 : accumulator.set_skip_indices(skip_indices_);
468 : accumulator.set_last_non_empty_prototype(last_non_empty_prototype_);
469 :
470 1187149 : MAYBE_RETURN(accumulator.CollectKeys(receiver_, receiver_),
471 : MaybeHandle<FixedArray>());
472 1169612 : return accumulator.GetKeys(keys_conversion);
473 : }
474 :
475 : namespace {
476 :
477 : enum IndexedOrNamed { kIndexed, kNamed };
478 :
479 60 : void FilterForEnumerableProperties(Handle<JSReceiver> receiver,
480 : Handle<JSObject> object,
481 : Handle<InterceptorInfo> interceptor,
482 156 : KeyAccumulator* accumulator,
483 : Handle<JSObject> result,
484 : IndexedOrNamed type) {
485 : DCHECK(result->IsJSArray() || result->HasSloppyArgumentsElements());
486 60 : ElementsAccessor* accessor = result->GetElementsAccessor();
487 :
488 180 : uint32_t length = accessor->GetCapacity(*result, result->elements());
489 282 : for (uint32_t i = 0; i < length; i++) {
490 510 : if (!accessor->HasEntry(*result, i)) continue;
491 :
492 : // args are invalid after args.Call(), create a new one in every iteration.
493 : PropertyCallbackArguments args(accumulator->isolate(), interceptor->data(),
494 312 : *receiver, *object, Just(kDontThrow));
495 :
496 156 : Handle<Object> element = accessor->Get(result, i);
497 : Handle<Object> attributes;
498 156 : if (type == kIndexed) {
499 : uint32_t number;
500 84 : CHECK(element->ToUint32(&number));
501 84 : attributes = args.CallIndexedQuery(interceptor, number);
502 : } else {
503 144 : CHECK(element->IsName());
504 : attributes =
505 72 : args.CallNamedQuery(interceptor, Handle<Name>::cast(element));
506 : }
507 :
508 156 : if (!attributes.is_null()) {
509 : int32_t value;
510 144 : CHECK(attributes->ToInt32(&value));
511 144 : if ((value & DONT_ENUM) == 0) {
512 48 : accumulator->AddKey(element, DO_NOT_CONVERT);
513 : }
514 : }
515 : }
516 60 : }
517 :
518 : // Returns |true| on success, |nothing| on exception.
519 475 : Maybe<bool> CollectInterceptorKeysInternal(Handle<JSReceiver> receiver,
520 : Handle<JSObject> object,
521 : Handle<InterceptorInfo> interceptor,
522 844 : KeyAccumulator* accumulator,
523 : IndexedOrNamed type) {
524 : Isolate* isolate = accumulator->isolate();
525 : PropertyCallbackArguments enum_args(isolate, interceptor->data(), *receiver,
526 950 : *object, Just(kDontThrow));
527 :
528 : Handle<JSObject> result;
529 950 : if (!interceptor->enumerator()->IsUndefined(isolate)) {
530 475 : if (type == kIndexed) {
531 235 : result = enum_args.CallIndexedEnumerator(interceptor);
532 : } else {
533 : DCHECK_EQ(type, kNamed);
534 240 : result = enum_args.CallNamedEnumerator(interceptor);
535 : }
536 : }
537 475 : RETURN_VALUE_IF_SCHEDULED_EXCEPTION(isolate, Nothing<bool>());
538 445 : if (result.is_null()) return Just(true);
539 :
540 857 : if ((accumulator->filter() & ONLY_ENUMERABLE) &&
541 488 : !interceptor->query()->IsUndefined(isolate)) {
542 : FilterForEnumerableProperties(receiver, object, interceptor, accumulator,
543 60 : result, type);
544 : } else {
545 : accumulator->AddKeys(
546 309 : result, type == kIndexed ? CONVERT_TO_ARRAY_INDEX : DO_NOT_CONVERT);
547 : }
548 : return Just(true);
549 : }
550 :
551 2450811 : Maybe<bool> CollectInterceptorKeys(Handle<JSReceiver> receiver,
552 : Handle<JSObject> object,
553 2451246 : KeyAccumulator* accumulator,
554 : IndexedOrNamed type) {
555 : Isolate* isolate = accumulator->isolate();
556 2450811 : if (type == kIndexed) {
557 1227788 : if (!object->HasIndexedInterceptor()) return Just(true);
558 : } else {
559 1223023 : if (!object->HasNamedInterceptor()) return Just(true);
560 : }
561 : Handle<InterceptorInfo> interceptor(type == kIndexed
562 865 : ? object->GetIndexedInterceptor()
563 655 : : object->GetNamedInterceptor(),
564 1090 : isolate);
565 1305 : if ((accumulator->filter() & ONLY_ALL_CAN_READ) &&
566 435 : !interceptor->all_can_read()) {
567 : return Just(true);
568 : }
569 : return CollectInterceptorKeysInternal(receiver, object, interceptor,
570 435 : accumulator, type);
571 : }
572 :
573 : } // namespace
574 :
575 1228356 : Maybe<bool> KeyAccumulator::CollectOwnElementIndices(
576 : Handle<JSReceiver> receiver, Handle<JSObject> object) {
577 1228356 : if (filter_ & SKIP_STRINGS || skip_indices_) return Just(true);
578 :
579 1227788 : ElementsAccessor* accessor = object->GetElementsAccessor();
580 1227788 : accessor->CollectElementIndices(object, this);
581 :
582 1227788 : return CollectInterceptorKeys(receiver, object, this, kIndexed);
583 : }
584 :
585 : namespace {
586 :
587 : template <bool skip_symbols>
588 1146548 : int CollectOwnPropertyNamesInternal(Handle<JSObject> object,
589 2182562 : KeyAccumulator* keys,
590 : Handle<DescriptorArray> descs,
591 : int start_index, int limit) {
592 : int first_skipped = -1;
593 : PropertyFilter filter = keys->filter();
594 : KeyCollectionMode mode = keys->mode();
595 1207512 : for (int i = start_index; i < limit; i++) {
596 : bool is_shadowing_key = false;
597 1207512 : PropertyDetails details = descs->GetDetails(i);
598 :
599 1207512 : if ((details.attributes() & filter) != 0) {
600 12 : if (mode == KeyCollectionMode::kIncludePrototypes) {
601 : is_shadowing_key = true;
602 : } else {
603 183474 : continue;
604 : }
605 : }
606 :
607 1207500 : if (filter & ONLY_ALL_CAN_READ) {
608 18 : if (details.kind() != kAccessor) continue;
609 12 : Object accessors = descs->GetStrongValue(i);
610 6 : if (!accessors->IsAccessorInfo()) continue;
611 6 : if (!AccessorInfo::cast(accessors)->all_can_read()) continue;
612 : }
613 :
614 1207494 : Name key = descs->GetKey(i);
615 1207494 : if (skip_symbols == key->IsSymbol()) {
616 171480 : if (first_skipped == -1) first_skipped = i;
617 : continue;
618 : }
619 1036014 : if (key->FilterKey(keys->filter())) continue;
620 :
621 1024038 : if (is_shadowing_key) {
622 0 : keys->AddShadowingKey(key);
623 : } else {
624 1024038 : keys->AddKey(key, DO_NOT_CONVERT);
625 : }
626 : }
627 1146548 : return first_skipped;
628 : }
629 :
630 : template <class T>
631 43141 : Handle<FixedArray> GetOwnEnumPropertyDictionaryKeys(Isolate* isolate,
632 : KeyCollectionMode mode,
633 : KeyAccumulator* accumulator,
634 : Handle<JSObject> object,
635 : T raw_dictionary) {
636 : Handle<T> dictionary(raw_dictionary, isolate);
637 43141 : if (dictionary->NumberOfElements() == 0) {
638 : return isolate->factory()->empty_fixed_array();
639 : }
640 42867 : int length = dictionary->NumberOfEnumerableProperties();
641 42867 : Handle<FixedArray> storage = isolate->factory()->NewFixedArray(length);
642 42867 : T::CopyEnumKeysTo(isolate, dictionary, storage, mode, accumulator);
643 42867 : return storage;
644 : }
645 : } // namespace
646 :
647 1223077 : Maybe<bool> KeyAccumulator::CollectOwnPropertyNames(Handle<JSReceiver> receiver,
648 243 : Handle<JSObject> object) {
649 1223077 : if (filter_ == ENUMERABLE_STRINGS) {
650 : Handle<FixedArray> enum_keys;
651 72081 : if (object->HasFastProperties()) {
652 35488 : enum_keys = KeyAccumulator::GetOwnEnumPropertyKeys(isolate_, object);
653 : // If the number of properties equals the length of enumerable properties
654 : // we do not have to filter out non-enumerable ones
655 35488 : Map map = object->map();
656 : int nof_descriptors = map->NumberOfOwnDescriptors();
657 35488 : if (enum_keys->length() != nof_descriptors) {
658 : Handle<DescriptorArray> descs =
659 8958 : Handle<DescriptorArray>(map->instance_descriptors(), isolate_);
660 119518 : for (int i = 0; i < nof_descriptors; i++) {
661 110560 : PropertyDetails details = descs->GetDetails(i);
662 114119 : if (!details.IsDontEnum()) continue;
663 107001 : Object key = descs->GetKey(i);
664 107001 : this->AddShadowingKey(key);
665 : }
666 : }
667 73186 : } else if (object->IsJSGlobalObject()) {
668 : enum_keys = GetOwnEnumPropertyDictionaryKeys(
669 : isolate_, mode_, this, object,
670 36269 : JSGlobalObject::cast(*object)->global_dictionary());
671 : } else {
672 : enum_keys = GetOwnEnumPropertyDictionaryKeys(
673 324 : isolate_, mode_, this, object, object->property_dictionary());
674 : }
675 144162 : if (object->IsJSModuleNamespace()) {
676 : // Simulate [[GetOwnProperty]] for establishing enumerability, which
677 : // throws for uninitialized exports.
678 315 : for (int i = 0, n = enum_keys->length(); i < n; ++i) {
679 243 : Handle<String> key(String::cast(enum_keys->get(i)), isolate_);
680 243 : if (Handle<JSModuleNamespace>::cast(object)
681 729 : ->GetExport(isolate(), key)
682 486 : .is_null()) {
683 54 : return Nothing<bool>();
684 : }
685 : }
686 : }
687 72027 : AddKeys(enum_keys, DO_NOT_CONVERT);
688 : } else {
689 1150996 : if (object->HasFastProperties()) {
690 : int limit = object->map()->NumberOfOwnDescriptors();
691 : Handle<DescriptorArray> descs(object->map()->instance_descriptors(),
692 3382851 : isolate_);
693 : // First collect the strings,
694 : int first_symbol =
695 1127617 : CollectOwnPropertyNamesInternal<true>(object, this, descs, 0, limit);
696 : // then the symbols.
697 1127617 : if (first_symbol != -1) {
698 : CollectOwnPropertyNamesInternal<false>(object, this, descs,
699 18931 : first_symbol, limit);
700 : }
701 46758 : } else if (object->IsJSGlobalObject()) {
702 : GlobalDictionary::CollectKeysTo(
703 : handle(JSGlobalObject::cast(*object)->global_dictionary(), isolate_),
704 68010 : this);
705 : } else {
706 : NameDictionary::CollectKeysTo(
707 2127 : handle(object->property_dictionary(), isolate_), this);
708 : }
709 : }
710 : // Add the property keys from the interceptor.
711 1223023 : return CollectInterceptorKeys(receiver, object, this, kNamed);
712 : }
713 :
714 20 : Maybe<bool> KeyAccumulator::CollectAccessCheckInterceptorKeys(
715 : Handle<AccessCheckInfo> access_check_info, Handle<JSReceiver> receiver,
716 : Handle<JSObject> object) {
717 20 : if (!skip_indices_) {
718 40 : MAYBE_RETURN((CollectInterceptorKeysInternal(
719 : receiver, object,
720 : handle(InterceptorInfo::cast(
721 : access_check_info->indexed_interceptor()),
722 : isolate_),
723 : this, kIndexed)),
724 : Nothing<bool>());
725 : }
726 40 : MAYBE_RETURN(
727 : (CollectInterceptorKeysInternal(
728 : receiver, object,
729 : handle(InterceptorInfo::cast(access_check_info->named_interceptor()),
730 : isolate_),
731 : this, kNamed)),
732 : Nothing<bool>());
733 : return Just(true);
734 : }
735 :
736 : // Returns |true| on success, |false| if prototype walking should be stopped,
737 : // |nothing| if an exception was thrown.
738 1223079 : Maybe<bool> KeyAccumulator::CollectOwnKeys(Handle<JSReceiver> receiver,
739 : Handle<JSObject> object) {
740 : // Check access rights if required.
741 2446252 : if (object->IsAccessCheckNeeded() &&
742 188 : !isolate_->MayAccess(handle(isolate_->context(), isolate_), object)) {
743 : // The cross-origin spec says that [[Enumerate]] shall return an empty
744 : // iterator when it doesn't have access...
745 69 : if (mode_ == KeyCollectionMode::kIncludePrototypes) {
746 : return Just(false);
747 : }
748 : // ...whereas [[OwnPropertyKeys]] shall return whitelisted properties.
749 : DCHECK_EQ(KeyCollectionMode::kOwnOnly, mode_);
750 : Handle<AccessCheckInfo> access_check_info;
751 : {
752 : DisallowHeapAllocation no_gc;
753 52 : AccessCheckInfo maybe_info = AccessCheckInfo::Get(isolate_, object);
754 52 : if (!maybe_info.is_null()) {
755 42 : access_check_info = handle(maybe_info, isolate_);
756 : }
757 : }
758 : // We always have both kinds of interceptors or none.
759 94 : if (!access_check_info.is_null() &&
760 : access_check_info->named_interceptor() != Object()) {
761 20 : MAYBE_RETURN(CollectAccessCheckInterceptorKeys(access_check_info,
762 : receiver, object),
763 : Nothing<bool>());
764 : return Just(false);
765 : }
766 32 : filter_ = static_cast<PropertyFilter>(filter_ | ONLY_ALL_CAN_READ);
767 : }
768 1223042 : MAYBE_RETURN(CollectOwnElementIndices(receiver, object), Nothing<bool>());
769 1223030 : MAYBE_RETURN(CollectOwnPropertyNames(receiver, object), Nothing<bool>());
770 : return Just(true);
771 : }
772 :
773 : // static
774 44567 : Handle<FixedArray> KeyAccumulator::GetOwnEnumPropertyKeys(
775 : Isolate* isolate, Handle<JSObject> object) {
776 44567 : if (object->HasFastProperties()) {
777 38019 : return GetFastEnumPropertyKeys(isolate, object);
778 13096 : } else if (object->IsJSGlobalObject()) {
779 : return GetOwnEnumPropertyDictionaryKeys(
780 : isolate, KeyCollectionMode::kOwnOnly, nullptr, object,
781 18 : JSGlobalObject::cast(*object)->global_dictionary());
782 : } else {
783 : return GetOwnEnumPropertyDictionaryKeys(
784 : isolate, KeyCollectionMode::kOwnOnly, nullptr, object,
785 6530 : object->property_dictionary());
786 : }
787 : }
788 :
789 : namespace {
790 :
791 : class NameComparator {
792 : public:
793 : explicit NameComparator(Isolate* isolate) : isolate_(isolate) {}
794 :
795 : bool operator()(uint32_t hash1, uint32_t hash2, const Handle<Name>& key1,
796 : const Handle<Name>& key2) const {
797 786 : return Name::Equals(isolate_, key1, key2);
798 : }
799 :
800 : private:
801 : Isolate* isolate_;
802 : };
803 :
804 : } // namespace
805 :
806 : // ES6 #sec-proxy-object-internal-methods-and-internal-slots-ownpropertykeys
807 : // Returns |true| on success, |nothing| in case of exception.
808 941232 : Maybe<bool> KeyAccumulator::CollectOwnJSProxyKeys(Handle<JSReceiver> receiver,
809 : Handle<JSProxy> proxy) {
810 1883517 : STACK_CHECK(isolate_, Nothing<bool>());
811 : // 1. Let handler be the value of the [[ProxyHandler]] internal slot of O.
812 941214 : Handle<Object> handler(proxy->handler(), isolate_);
813 : // 2. If handler is null, throw a TypeError exception.
814 : // 3. Assert: Type(handler) is Object.
815 1882428 : if (proxy->IsRevoked()) {
816 : isolate_->Throw(*isolate_->factory()->NewTypeError(
817 54 : MessageTemplate::kProxyRevoked, isolate_->factory()->ownKeys_string()));
818 : return Nothing<bool>();
819 : }
820 : // 4. Let target be the value of the [[ProxyTarget]] internal slot of O.
821 941196 : Handle<JSReceiver> target(JSReceiver::cast(proxy->target()), isolate_);
822 : // 5. Let trap be ? GetMethod(handler, "ownKeys").
823 : Handle<Object> trap;
824 2823588 : ASSIGN_RETURN_ON_EXCEPTION_VALUE(
825 : isolate_, trap, Object::GetMethod(Handle<JSReceiver>::cast(handler),
826 : isolate_->factory()->ownKeys_string()),
827 : Nothing<bool>());
828 : // 6. If trap is undefined, then
829 2823480 : if (trap->IsUndefined(isolate_)) {
830 : // 6a. Return target.[[OwnPropertyKeys]]().
831 934021 : return CollectOwnJSProxyTargetKeys(proxy, target);
832 : }
833 : // 7. Let trapResultArray be Call(trap, handler, «target»).
834 : Handle<Object> trap_result_array;
835 : Handle<Object> args[] = {target};
836 14278 : ASSIGN_RETURN_ON_EXCEPTION_VALUE(
837 : isolate_, trap_result_array,
838 : Execution::Call(isolate_, trap, handler, arraysize(args), args),
839 : Nothing<bool>());
840 : // 8. Let trapResult be ? CreateListFromArrayLike(trapResultArray,
841 : // «String, Symbol»).
842 : Handle<FixedArray> trap_result;
843 2340 : ASSIGN_RETURN_ON_EXCEPTION_VALUE(
844 : isolate_, trap_result,
845 : Object::CreateListFromArrayLike(isolate_, trap_result_array,
846 : ElementTypes::kStringAndSymbol),
847 : Nothing<bool>());
848 : // 9. If trapResult contains any duplicate entries, throw a TypeError
849 : // exception. Combine with step 18
850 : // 18. Let uncheckedResultKeys be a new List which is a copy of trapResult.
851 2106 : Zone set_zone(isolate_->allocator(), ZONE_NAME);
852 : ZoneAllocationPolicy alloc(&set_zone);
853 : const int kPresent = 1;
854 : const int kGone = 0;
855 : base::TemplateHashMapImpl<Handle<Name>, int, NameComparator,
856 : ZoneAllocationPolicy>
857 : unchecked_result_keys(ZoneHashMap::kDefaultHashMapCapacity,
858 1053 : NameComparator(isolate_), alloc);
859 : int unchecked_result_keys_size = 0;
860 7578 : for (int i = 0; i < trap_result->length(); ++i) {
861 2817 : Handle<Name> key(Name::cast(trap_result->get(i)), isolate_);
862 5634 : auto entry = unchecked_result_keys.LookupOrInsert(key, key->Hash(), alloc);
863 2817 : if (entry->value != kPresent) {
864 2736 : entry->value = kPresent;
865 2736 : unchecked_result_keys_size++;
866 : } else {
867 : // found dupes, throw exception
868 : isolate_->Throw(*isolate_->factory()->NewTypeError(
869 162 : MessageTemplate::kProxyOwnKeysDuplicateEntries));
870 81 : return Nothing<bool>();
871 : }
872 : }
873 : // 10. Let extensibleTarget be ? IsExtensible(target).
874 972 : Maybe<bool> maybe_extensible = JSReceiver::IsExtensible(target);
875 972 : MAYBE_RETURN(maybe_extensible, Nothing<bool>());
876 : bool extensible_target = maybe_extensible.FromJust();
877 : // 11. Let targetKeys be ? target.[[OwnPropertyKeys]]().
878 : Handle<FixedArray> target_keys;
879 1944 : ASSIGN_RETURN_ON_EXCEPTION_VALUE(isolate_, target_keys,
880 : JSReceiver::OwnPropertyKeys(target),
881 : Nothing<bool>());
882 : // 12, 13. (Assert)
883 : // 14. Let targetConfigurableKeys be an empty List.
884 : // To save memory, we're re-using target_keys and will modify it in-place.
885 : Handle<FixedArray> target_configurable_keys = target_keys;
886 : // 15. Let targetNonconfigurableKeys be an empty List.
887 : Handle<FixedArray> target_nonconfigurable_keys =
888 972 : isolate_->factory()->NewFixedArray(target_keys->length());
889 : int nonconfigurable_keys_length = 0;
890 : // 16. Repeat, for each element key of targetKeys:
891 3312 : for (int i = 0; i < target_keys->length(); ++i) {
892 : // 16a. Let desc be ? target.[[GetOwnProperty]](key).
893 : PropertyDescriptor desc;
894 : Maybe<bool> found = JSReceiver::GetOwnPropertyDescriptor(
895 1368 : isolate_, target, handle(target_keys->get(i), isolate_), &desc);
896 684 : MAYBE_RETURN(found, Nothing<bool>());
897 : // 16b. If desc is not undefined and desc.[[Configurable]] is false, then
898 1368 : if (found.FromJust() && !desc.configurable()) {
899 : // 16b i. Append key as an element of targetNonconfigurableKeys.
900 : target_nonconfigurable_keys->set(nonconfigurable_keys_length,
901 243 : target_keys->get(i));
902 243 : nonconfigurable_keys_length++;
903 : // The key was moved, null it out in the original list.
904 243 : target_keys->set(i, Smi::kZero);
905 : } else {
906 : // 16c. Else,
907 : // 16c i. Append key as an element of targetConfigurableKeys.
908 : // (No-op, just keep it in |target_keys|.)
909 : }
910 : }
911 : // 17. If extensibleTarget is true and targetNonconfigurableKeys is empty,
912 : // then:
913 972 : if (extensible_target && nonconfigurable_keys_length == 0) {
914 : // 17a. Return trapResult.
915 828 : return AddKeysFromJSProxy(proxy, trap_result);
916 : }
917 : // 18. (Done in step 9)
918 : // 19. Repeat, for each key that is an element of targetNonconfigurableKeys:
919 234 : for (int i = 0; i < nonconfigurable_keys_length; ++i) {
920 : Object raw_key = target_nonconfigurable_keys->get(i);
921 243 : Handle<Name> key(Name::cast(raw_key), isolate_);
922 : // 19a. If key is not an element of uncheckedResultKeys, throw a
923 : // TypeError exception.
924 486 : auto found = unchecked_result_keys.Lookup(key, key->Hash());
925 243 : if (found == nullptr || found->value == kGone) {
926 : isolate_->Throw(*isolate_->factory()->NewTypeError(
927 18 : MessageTemplate::kProxyOwnKeysMissing, key));
928 9 : return Nothing<bool>();
929 : }
930 : // 19b. Remove key from uncheckedResultKeys.
931 234 : found->value = kGone;
932 234 : unchecked_result_keys_size--;
933 : }
934 : // 20. If extensibleTarget is true, return trapResult.
935 135 : if (extensible_target) {
936 54 : return AddKeysFromJSProxy(proxy, trap_result);
937 : }
938 : // 21. Repeat, for each key that is an element of targetConfigurableKeys:
939 621 : for (int i = 0; i < target_configurable_keys->length(); ++i) {
940 270 : Object raw_key = target_configurable_keys->get(i);
941 441 : if (raw_key->IsSmi()) continue; // Zapped entry, was nonconfigurable.
942 99 : Handle<Name> key(Name::cast(raw_key), isolate_);
943 : // 21a. If key is not an element of uncheckedResultKeys, throw a
944 : // TypeError exception.
945 198 : auto found = unchecked_result_keys.Lookup(key, key->Hash());
946 99 : if (found == nullptr || found->value == kGone) {
947 : isolate_->Throw(*isolate_->factory()->NewTypeError(
948 0 : MessageTemplate::kProxyOwnKeysMissing, key));
949 0 : return Nothing<bool>();
950 : }
951 : // 21b. Remove key from uncheckedResultKeys.
952 99 : found->value = kGone;
953 99 : unchecked_result_keys_size--;
954 : }
955 : // 22. If uncheckedResultKeys is not empty, throw a TypeError exception.
956 81 : if (unchecked_result_keys_size != 0) {
957 : DCHECK_GT(unchecked_result_keys_size, 0);
958 : isolate_->Throw(*isolate_->factory()->NewTypeError(
959 18 : MessageTemplate::kProxyOwnKeysNonExtensible));
960 : return Nothing<bool>();
961 : }
962 : // 23. Return trapResult.
963 72 : return AddKeysFromJSProxy(proxy, trap_result);
964 : }
965 :
966 934021 : Maybe<bool> KeyAccumulator::CollectOwnJSProxyTargetKeys(
967 : Handle<JSProxy> proxy, Handle<JSReceiver> target) {
968 : // TODO(cbruni): avoid creating another KeyAccumulator
969 : Handle<FixedArray> keys;
970 1868042 : ASSIGN_RETURN_ON_EXCEPTION_VALUE(
971 : isolate_, keys,
972 : KeyAccumulator::GetKeys(
973 : target, KeyCollectionMode::kOwnOnly, ALL_PROPERTIES,
974 : GetKeysConversion::kConvertToString, is_for_in_, skip_indices_),
975 : Nothing<bool>());
976 922915 : Maybe<bool> result = AddKeysFromJSProxy(proxy, keys);
977 922915 : return result;
978 : }
979 :
980 : } // namespace internal
981 178779 : } // namespace v8
|