keys.cc 53.7 KB
Newer Older
1 2 3 4
// Copyright 2013 the V8 project authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

5
#include "src/objects/keys.h"
6

7
#include "src/api/api-arguments-inl.h"
8
#include "src/common/globals.h"
9
#include "src/execution/isolate-inl.h"
10
#include "src/handles/handles-inl.h"
11
#include "src/heap/factory.h"
12
#include "src/objects/api-callbacks.h"
13 14
#include "src/objects/elements-inl.h"
#include "src/objects/field-index-inl.h"
15
#include "src/objects/hash-table-inl.h"
16
#include "src/objects/module-inl.h"
17
#include "src/objects/objects-inl.h"
18
#include "src/objects/ordered-hash-table-inl.h"
19 20
#include "src/objects/property-descriptor.h"
#include "src/objects/prototype.h"
21
#include "src/objects/slots-atomic-inl.h"
22
#include "src/utils/identity-map.h"
23
#include "src/zone/zone-hashmap.h"
24 25 26 27

namespace v8 {
namespace internal {

28 29 30 31 32 33 34 35 36 37 38
#define RETURN_NOTHING_IF_NOT_SUCCESSFUL(call) \
  do {                                         \
    if (!(call)) return Nothing<bool>();       \
  } while (false)

#define RETURN_FAILURE_IF_NOT_SUCCESSFUL(call)          \
  do {                                                  \
    ExceptionStatus status_enum_result = (call);        \
    if (!status_enum_result) return status_enum_result; \
  } while (false)

39 40 41 42 43
namespace {

static bool ContainsOnlyValidKeys(Handle<FixedArray> array) {
  int len = array->length();
  for (int i = 0; i < len; i++) {
44
    Object e = array->get(i);
45
    if (!(e.IsName() || e.IsNumber())) return false;
46 47 48 49
  }
  return true;
}

50 51 52 53 54 55 56 57 58 59 60 61 62
static int AddKey(Object key, Handle<FixedArray> combined_keys,
                  Handle<DescriptorArray> descs, int nof_descriptors,
                  int target) {
  for (InternalIndex i : InternalIndex::Range(nof_descriptors)) {
    if (descs->GetKey(i) == key) return 0;
  }
  combined_keys->set(target, key);
  return 1;
}

static Handle<FixedArray> CombineKeys(Isolate* isolate,
                                      Handle<FixedArray> own_keys,
                                      Handle<FixedArray> prototype_chain_keys,
63 64
                                      Handle<JSReceiver> receiver,
                                      bool may_have_elements) {
65 66 67 68 69
  int prototype_chain_keys_length = prototype_chain_keys->length();
  if (prototype_chain_keys_length == 0) return own_keys;

  Map map = receiver->map();
  int nof_descriptors = map.NumberOfOwnDescriptors();
70
  if (nof_descriptors == 0 && !may_have_elements) return prototype_chain_keys;
71

72 73
  Handle<DescriptorArray> descs(map.instance_descriptors(kRelaxedLoad),
                                isolate);
74 75 76 77 78 79 80 81 82 83 84 85 86 87
  int own_keys_length = own_keys.is_null() ? 0 : own_keys->length();
  Handle<FixedArray> combined_keys = isolate->factory()->NewFixedArray(
      own_keys_length + prototype_chain_keys_length);
  if (own_keys_length != 0) {
    own_keys->CopyTo(0, *combined_keys, 0, own_keys_length);
  }
  int target_keys_length = own_keys_length;
  for (int i = 0; i < prototype_chain_keys_length; i++) {
    target_keys_length += AddKey(prototype_chain_keys->get(i), combined_keys,
                                 descs, nof_descriptors, target_keys_length);
  }
  return FixedArray::ShrinkOrEmpty(isolate, combined_keys, target_keys_length);
}

88
}  // namespace
89 90

// static
91
MaybeHandle<FixedArray> KeyAccumulator::GetKeys(
92
    Handle<JSReceiver> object, KeyCollectionMode mode, PropertyFilter filter,
93
    GetKeysConversion keys_conversion, bool is_for_in, bool skip_indices) {
94
  Isolate* isolate = object->GetIsolate();
95 96
  FastKeyAccumulator accumulator(isolate, object, mode, filter, is_for_in,
                                 skip_indices);
97
  return accumulator.GetKeys(keys_conversion);
98 99
}

100
Handle<FixedArray> KeyAccumulator::GetKeys(GetKeysConversion convert) {
101
  if (keys_.is_null()) {
102 103
    return isolate_->factory()->empty_fixed_array();
  }
104
  if (mode_ == KeyCollectionMode::kOwnOnly &&
105
      keys_->map() == ReadOnlyRoots(isolate_).fixed_array_map()) {
106
    return Handle<FixedArray>::cast(keys_);
107
  }
108 109
  USE(ContainsOnlyValidKeys);
  Handle<FixedArray> result =
110
      OrderedHashSet::ConvertToKeysArray(isolate(), keys(), convert);
111
  DCHECK(ContainsOnlyValidKeys(result));
112 113 114 115 116 117 118 119

  if (try_prototype_info_cache_ && !first_prototype_map_.is_null()) {
    PrototypeInfo::cast(first_prototype_map_->prototype_info())
        .set_prototype_chain_enum_cache(*result);
    Map::GetOrCreatePrototypeChainValidityCell(
        Handle<Map>(receiver_->map(), isolate_), isolate_);
    DCHECK(first_prototype_map_->IsPrototypeValidityCellValid());
  }
120
  return result;
121 122
}

123 124 125 126
Handle<OrderedHashSet> KeyAccumulator::keys() {
  return Handle<OrderedHashSet>::cast(keys_);
}

127 128
ExceptionStatus KeyAccumulator::AddKey(Object key, AddKeyConversion convert) {
  return AddKey(handle(key, isolate_), convert);
129 130
}

131 132
ExceptionStatus KeyAccumulator::AddKey(Handle<Object> key,
                                       AddKeyConversion convert) {
133
  if (filter_ == PRIVATE_NAMES_ONLY) {
134 135
    if (!key->IsSymbol()) return ExceptionStatus::kSuccess;
    if (!Symbol::cast(*key).is_private_name()) return ExceptionStatus::kSuccess;
136
  } else if (key->IsSymbol()) {
137 138
    if (filter_ & SKIP_SYMBOLS) return ExceptionStatus::kSuccess;
    if (Symbol::cast(*key).is_private()) return ExceptionStatus::kSuccess;
139
  } else if (filter_ & SKIP_STRINGS) {
140
    return ExceptionStatus::kSuccess;
141
  }
142

143
  if (IsShadowed(key)) return ExceptionStatus::kSuccess;
144
  if (keys_.is_null()) {
145
    keys_ = OrderedHashSet::Allocate(isolate_, 16).ToHandleChecked();
146
  }
147 148 149 150
  uint32_t index;
  if (convert == CONVERT_TO_ARRAY_INDEX && key->IsString() &&
      Handle<String>::cast(key)->AsArrayIndex(&index)) {
    key = isolate_->factory()->NewNumberFromUint(index);
151
  }
152 153 154 155 156 157 158 159
  MaybeHandle<OrderedHashSet> new_set_candidate =
      OrderedHashSet::Add(isolate(), keys(), key);
  Handle<OrderedHashSet> new_set;
  if (!new_set_candidate.ToHandle(&new_set)) {
    THROW_NEW_ERROR_RETURN_VALUE(
        isolate_, NewRangeError(MessageTemplate::kTooManyProperties),
        ExceptionStatus::kException);
  }
160 161 162 163
  if (*new_set != *keys_) {
    // The keys_ Set is converted directly to a FixedArray in GetKeys which can
    // be left-trimmer. Hence the previous Set should not keep a pointer to the
    // new one.
164
    keys_->set(OrderedHashSet::NextTableIndex(), Smi::zero());
165
    keys_ = new_set;
166
  }
167
  return ExceptionStatus::kSuccess;
168 169
}

170 171
ExceptionStatus KeyAccumulator::AddKeys(Handle<FixedArray> array,
                                        AddKeyConversion convert) {
172 173 174
  int add_length = array->length();
  for (int i = 0; i < add_length; i++) {
    Handle<Object> current(array->get(i), isolate_);
175
    RETURN_FAILURE_IF_NOT_SUCCESSFUL(AddKey(current, convert));
176
  }
177
  return ExceptionStatus::kSuccess;
178 179
}

180 181
ExceptionStatus KeyAccumulator::AddKeys(Handle<JSObject> array_like,
                                        AddKeyConversion convert) {
182 183
  DCHECK(array_like->IsJSArray() || array_like->HasSloppyArgumentsElements());
  ElementsAccessor* accessor = array_like->GetElementsAccessor();
184
  return accessor->AddElementsToKeyAccumulator(array_like, this, convert);
185 186
}

187 188
MaybeHandle<FixedArray> FilterProxyKeys(KeyAccumulator* accumulator,
                                        Handle<JSProxy> owner,
189
                                        Handle<FixedArray> keys,
190 191
                                        PropertyFilter filter) {
  if (filter == ALL_PROPERTIES) {
192 193 194
    // Nothing to do.
    return keys;
  }
195
  Isolate* isolate = accumulator->isolate();
196 197 198
  int store_position = 0;
  for (int i = 0; i < keys->length(); ++i) {
    Handle<Name> key(Name::cast(keys->get(i)), isolate);
199
    if (key->FilterKey(filter)) continue;  // Skip this key.
200
    if (filter & ONLY_ENUMERABLE) {
201
      PropertyDescriptor desc;
202
      Maybe<bool> found =
203
          JSProxy::GetOwnPropertyDescriptor(isolate, owner, key, &desc);
204
      MAYBE_RETURN(found, MaybeHandle<FixedArray>());
205 206
      if (!found.FromJust()) continue;
      if (!desc.enumerable()) {
207
        accumulator->AddShadowingKey(key);
208 209
        continue;
      }
210 211 212 213 214 215 216
    }
    // Keep this key.
    if (store_position != i) {
      keys->set(store_position, *key);
    }
    store_position++;
  }
217
  return FixedArray::ShrinkOrEmpty(isolate, keys, store_position);
218 219
}

220
// Returns "nothing" in case of exception, "true" on success.
221 222
Maybe<bool> KeyAccumulator::AddKeysFromJSProxy(Handle<JSProxy> proxy,
                                               Handle<FixedArray> keys) {
223 224
  // Postpone the enumerable check for for-in to the ForInFilter step.
  if (!is_for_in_) {
225
    ASSIGN_RETURN_ON_EXCEPTION_VALUE(
226
        isolate_, keys, FilterProxyKeys(this, proxy, keys, filter_),
227
        Nothing<bool>());
228 229 230 231 232
    if (mode_ == KeyCollectionMode::kOwnOnly) {
      // If we collect only the keys from a JSProxy do not sort or deduplicate.
      keys_ = keys;
      return Just(true);
    }
233
  }
234 235
  RETURN_NOTHING_IF_NOT_SUCCESSFUL(
      AddKeys(keys, is_for_in_ ? CONVERT_TO_ARRAY_INDEX : DO_NOT_CONVERT));
236
  return Just(true);
237 238
}

239 240
Maybe<bool> KeyAccumulator::CollectKeys(Handle<JSReceiver> receiver,
                                        Handle<JSReceiver> object) {
241 242 243
  // Proxies have no hidden prototype and we should not trigger the
  // [[GetPrototypeOf]] trap on the last iteration when using
  // AdvanceFollowingProxies.
244
  if (mode_ == KeyCollectionMode::kOwnOnly && object->IsJSProxy()) {
245 246
    MAYBE_RETURN(CollectOwnJSProxyKeys(receiver, Handle<JSProxy>::cast(object)),
                 Nothing<bool>());
247 248 249
    return Just(true);
  }

250
  PrototypeIterator::WhereToEnd end = mode_ == KeyCollectionMode::kOwnOnly
251 252
                                          ? PrototypeIterator::END_AT_NON_HIDDEN
                                          : PrototypeIterator::END_AT_NULL;
253
  for (PrototypeIterator iter(isolate_, object, kStartAtReceiver, end);
254
       !iter.IsAtEnd();) {
255 256 257
    // Start the shadow checks only after the first prototype has added
    // shadowing keys.
    if (HasShadowingKeys()) skip_shadow_check_ = false;
258 259 260 261
    Handle<JSReceiver> current =
        PrototypeIterator::GetCurrent<JSReceiver>(iter);
    Maybe<bool> result = Just(false);  // Dummy initialization.
    if (current->IsJSProxy()) {
262
      result = CollectOwnJSProxyKeys(receiver, Handle<JSProxy>::cast(current));
263 264
    } else {
      DCHECK(current->IsJSObject());
265
      result = CollectOwnKeys(receiver, Handle<JSObject>::cast(current));
266 267 268 269
    }
    MAYBE_RETURN(result, Nothing<bool>());
    if (!result.FromJust()) break;  // |false| means "stop iterating".
    // Iterate through proxies but ignore access checks for the ALL_CAN_READ
270
    // case on API objects for OWN_ONLY keys handled in CollectOwnKeys.
271 272 273
    if (!iter.AdvanceFollowingProxiesIgnoringAccessChecks()) {
      return Nothing<bool>();
    }
274 275 276 277
    if (!last_non_empty_prototype_.is_null() &&
        *last_non_empty_prototype_ == *current) {
      break;
    }
278 279 280 281
  }
  return Just(true);
}

282 283
bool KeyAccumulator::HasShadowingKeys() { return !shadowing_keys_.is_null(); }

284
bool KeyAccumulator::IsShadowed(Handle<Object> key) {
285 286
  if (!HasShadowingKeys() || skip_shadow_check_) return false;
  return shadowing_keys_->Has(isolate_, key);
287 288
}

289
void KeyAccumulator::AddShadowingKey(Object key,
290
                                     AllowGarbageCollection* allow_gc) {
291
  if (mode_ == KeyCollectionMode::kOwnOnly) return;
292
  AddShadowingKey(handle(key, isolate_));
293
}
294
void KeyAccumulator::AddShadowingKey(Handle<Object> key) {
295
  if (mode_ == KeyCollectionMode::kOwnOnly) return;
296 297
  if (shadowing_keys_.is_null()) {
    shadowing_keys_ = ObjectHashSet::New(isolate_, 16);
298
  }
299
  shadowing_keys_ = ObjectHashSet::Add(isolate(), shadowing_keys_, key);
300 301
}

302 303
namespace {

304
void TrySettingEmptyEnumCache(JSReceiver object) {
305 306 307 308 309 310 311
  Map map = object.map();
  DCHECK_EQ(kInvalidEnumCacheSentinel, map.EnumLength());
  if (!map.OnlyHasSimpleProperties()) return;
  if (map.IsJSProxyMap()) return;
  if (map.NumberOfEnumerableProperties() > 0) return;
  DCHECK(object.IsJSObject());
  map.SetEnumLength(0);
312 313
}

314
bool CheckAndInitalizeEmptyEnumCache(JSReceiver object) {
315
  if (object.map().EnumLength() == kInvalidEnumCacheSentinel) {
316 317
    TrySettingEmptyEnumCache(object);
  }
318 319 320
  if (object.map().EnumLength() != 0) return false;
  DCHECK(object.IsJSObject());
  return !JSObject::cast(object).HasEnumerableElements();
321 322 323 324
}
}  // namespace

void FastKeyAccumulator::Prepare() {
325
  DisallowGarbageCollection no_gc;
326
  // Directly go for the fast path for OWN_ONLY keys.
327
  if (mode_ == KeyCollectionMode::kOwnOnly) return;
328 329 330
  // Fully walk the prototype chain and find the last prototype with keys.
  is_receiver_simple_enum_ = false;
  has_empty_prototype_ = true;
331 332
  only_own_has_simple_elements_ =
      !receiver_->map().IsCustomElementsReceiverMap();
333
  JSReceiver last_prototype;
334
  may_have_elements_ = MayHaveElements(*receiver_);
335 336
  for (PrototypeIterator iter(isolate_, *receiver_); !iter.IsAtEnd();
       iter.Advance()) {
337
    JSReceiver current = iter.GetCurrent<JSReceiver>();
338 339 340 341 342
    if (!may_have_elements_ || only_own_has_simple_elements_) {
      if (MayHaveElements(current)) {
        may_have_elements_ = true;
        only_own_has_simple_elements_ = false;
      }
343
    }
344
    bool has_no_properties = CheckAndInitalizeEmptyEnumCache(current);
345 346
    if (has_no_properties) continue;
    last_prototype = current;
347 348
    has_empty_prototype_ = false;
  }
349 350 351
  // Check if we should try to create/use prototype info cache.
  try_prototype_info_cache_ = TryPrototypeInfoCache(receiver_);
  if (has_prototype_info_cache_) return;
352 353
  if (has_empty_prototype_) {
    is_receiver_simple_enum_ =
354 355
        receiver_->map().EnumLength() != kInvalidEnumCacheSentinel &&
        !JSObject::cast(*receiver_).HasEnumerableElements();
356
  } else if (!last_prototype.is_null()) {
357 358
    last_non_empty_prototype_ = handle(last_prototype, isolate_);
  }
359 360 361
}

namespace {
362 363 364

Handle<FixedArray> ReduceFixedArrayTo(Isolate* isolate,
                                      Handle<FixedArray> array, int length) {
365 366 367 368 369
  DCHECK_LE(length, array->length());
  if (array->length() == length) return array;
  return isolate->factory()->CopyFixedArrayUpTo(array, length);
}

370 371
// Initializes and directly returns the enume cache. Users of this function
// have to make sure to never directly leak the enum cache.
372 373
Handle<FixedArray> GetFastEnumPropertyKeys(Isolate* isolate,
                                           Handle<JSObject> object) {
374
  Handle<Map> map(object->map(), isolate);
375 376
  Handle<FixedArray> keys(
      map->instance_descriptors(kRelaxedLoad).enum_cache().keys(), isolate);
377 378 379 380 381 382 383 384 385 386

  // Check if the {map} has a valid enum length, which implies that it
  // must have a valid enum cache as well.
  int enum_length = map->EnumLength();
  if (enum_length != kInvalidEnumCacheSentinel) {
    DCHECK(map->OnlyHasSimpleProperties());
    DCHECK_LE(enum_length, keys->length());
    DCHECK_EQ(enum_length, map->NumberOfEnumerableProperties());
    isolate->counters()->enum_cache_hits()->Increment();
    return ReduceFixedArrayTo(isolate, keys, enum_length);
387 388
  }

389 390
  // Determine the actual number of enumerable properties of the {map}.
  enum_length = map->NumberOfEnumerableProperties();
391

392 393 394 395
  // Check if there's already a shared enum cache on the {map}s
  // DescriptorArray with sufficient number of entries.
  if (enum_length <= keys->length()) {
    if (map->OnlyHasSimpleProperties()) map->SetEnumLength(enum_length);
396
    isolate->counters()->enum_cache_hits()->Increment();
397
    return ReduceFixedArrayTo(isolate, keys, enum_length);
398 399
  }

400
  Handle<DescriptorArray> descriptors =
401
      Handle<DescriptorArray>(map->instance_descriptors(kRelaxedLoad), isolate);
402 403
  isolate->counters()->enum_cache_misses()->Increment();

404
  // Create the keys array.
405
  int index = 0;
406 407
  bool fields_only = true;
  keys = isolate->factory()->NewFixedArray(enum_length);
408
  for (InternalIndex i : map->IterateOwnDescriptors()) {
409
    DisallowGarbageCollection no_gc;
410
    PropertyDetails details = descriptors->GetDetails(i);
411
    if (details.IsDontEnum()) continue;
412
    Object key = descriptors->GetKey(i);
413
    if (key.IsSymbol()) continue;
414 415
    keys->set(index, key);
    if (details.location() != kField) fields_only = false;
416 417
    index++;
  }
418 419 420 421 422 423 424
  DCHECK_EQ(index, keys->length());

  // Optionally also create the indices array.
  Handle<FixedArray> indices = isolate->factory()->empty_fixed_array();
  if (fields_only) {
    indices = isolate->factory()->NewFixedArray(enum_length);
    index = 0;
425
    for (InternalIndex i : map->IterateOwnDescriptors()) {
426
      DisallowGarbageCollection no_gc;
427 428
      PropertyDetails details = descriptors->GetDetails(i);
      if (details.IsDontEnum()) continue;
429
      Object key = descriptors->GetKey(i);
430
      if (key.IsSymbol()) continue;
431 432 433 434 435 436 437
      DCHECK_EQ(kData, details.kind());
      DCHECK_EQ(kField, details.location());
      FieldIndex field_index = FieldIndex::ForDescriptor(*map, i);
      indices->set(index, Smi::FromInt(field_index.GetLoadByFieldIndex()));
      index++;
    }
    DCHECK_EQ(index, indices->length());
438
  }
439

440 441
  DescriptorArray::InitializeOrChangeEnumCache(descriptors, isolate, keys,
                                               indices);
442 443 444
  if (map->OnlyHasSimpleProperties()) map->SetEnumLength(enum_length);

  return keys;
445
}
446 447

template <bool fast_properties>
448 449
MaybeHandle<FixedArray> GetOwnKeysWithElements(Isolate* isolate,
                                               Handle<JSObject> object,
450 451
                                               GetKeysConversion convert,
                                               bool skip_indices) {
452
  Handle<FixedArray> keys;
453
  ElementsAccessor* accessor = object->GetElementsAccessor();
454
  if (fast_properties) {
455
    keys = GetFastEnumPropertyKeys(isolate, object);
456 457
  } else {
    // TODO(cbruni): preallocate big enough array to also hold elements.
458
    keys = KeyAccumulator::GetOwnEnumPropertyKeys(isolate, object);
459
  }
460 461 462 463 464 465 466 467

  MaybeHandle<FixedArray> result;
  if (skip_indices) {
    result = keys;
  } else {
    result =
        accessor->PrependElementIndices(object, keys, convert, ONLY_ENUMERABLE);
  }
468 469 470

  if (FLAG_trace_for_in_enumerate) {
    PrintF("| strings=%d symbols=0 elements=%u || prototypes>=1 ||\n",
471
           keys->length(), result.ToHandleChecked()->length() - keys->length());
472 473
  }
  return result;
474 475 476 477
}

}  // namespace

478 479
MaybeHandle<FixedArray> FastKeyAccumulator::GetKeys(
    GetKeysConversion keys_conversion) {
480 481 482 483 484
  // TODO(v8:9401): We should extend the fast path of KeyAccumulator::GetKeys to
  // also use fast path even when filter = SKIP_SYMBOLS. We used to pass wrong
  // filter to use fast path in cases where we tried to verify all properties
  // are enumerable. However these checks weren't correct and passing the wrong
  // filter led to wrong behaviour.
485 486 487 488 489 490
  if (filter_ == ENUMERABLE_STRINGS) {
    Handle<FixedArray> keys;
    if (GetKeysFast(keys_conversion).ToHandle(&keys)) {
      return keys;
    }
    if (isolate_->has_pending_exception()) return MaybeHandle<FixedArray>();
491
  }
492

493 494 495
  if (try_prototype_info_cache_) {
    return GetKeysWithPrototypeInfoCache(keys_conversion);
  }
496
  return GetKeysSlow(keys_conversion);
497 498 499
}

MaybeHandle<FixedArray> FastKeyAccumulator::GetKeysFast(
500
    GetKeysConversion keys_conversion) {
501
  bool own_only = has_empty_prototype_ || mode_ == KeyCollectionMode::kOwnOnly;
502
  Map map = receiver_->map();
503
  if (!own_only || map.IsCustomElementsReceiverMap()) {
504 505 506
    return MaybeHandle<FixedArray>();
  }

507
  // From this point on we are certain to only collect own keys.
508 509 510
  DCHECK(receiver_->IsJSObject());
  Handle<JSObject> object = Handle<JSObject>::cast(receiver_);

511
  // Do not try to use the enum-cache for dict-mode objects.
512
  if (map.is_dictionary_map()) {
513 514
    return GetOwnKeysWithElements<false>(isolate_, object, keys_conversion,
                                         skip_indices_);
515
  }
516
  int enum_length = receiver_->map().EnumLength();
517
  if (enum_length == kInvalidEnumCacheSentinel) {
518
    Handle<FixedArray> keys;
519
    // Try initializing the enum cache and return own properties.
520
    if (GetOwnKeysWithUninitializedEnumCache().ToHandle(&keys)) {
521 522 523 524
      if (FLAG_trace_for_in_enumerate) {
        PrintF("| strings=%d symbols=0 elements=0 || prototypes>=1 ||\n",
               keys->length());
      }
525
      is_receiver_simple_enum_ =
526
          object->map().EnumLength() != kInvalidEnumCacheSentinel;
527 528 529 530 531
      return keys;
    }
  }
  // The properties-only case failed because there were probably elements on the
  // receiver.
532 533
  return GetOwnKeysWithElements<true>(isolate_, object, keys_conversion,
                                      skip_indices_);
534 535
}

536 537 538 539
MaybeHandle<FixedArray>
FastKeyAccumulator::GetOwnKeysWithUninitializedEnumCache() {
  Handle<JSObject> object = Handle<JSObject>::cast(receiver_);
  // Uninitalized enum cache
540
  Map map = object->map();
541 542 543
  if (object->elements() != ReadOnlyRoots(isolate_).empty_fixed_array() &&
      object->elements() !=
          ReadOnlyRoots(isolate_).empty_slow_element_dictionary()) {
544 545 546
    // Assume that there are elements.
    return MaybeHandle<FixedArray>();
  }
547
  int number_of_own_descriptors = map.NumberOfOwnDescriptors();
548
  if (number_of_own_descriptors == 0) {
549
    map.SetEnumLength(0);
550 551 552 553 554 555 556 557 558 559
    return isolate_->factory()->empty_fixed_array();
  }
  // We have no elements but possibly enumerable property keys, hence we can
  // directly initialize the enum cache.
  Handle<FixedArray> keys = GetFastEnumPropertyKeys(isolate_, object);
  if (is_for_in_) return keys;
  // Do not leak the enum cache as it might end up as an elements backing store.
  return isolate_->factory()->CopyFixedArray(keys);
}

560
MaybeHandle<FixedArray> FastKeyAccumulator::GetKeysSlow(
561 562 563
    GetKeysConversion keys_conversion) {
  KeyAccumulator accumulator(isolate_, mode_, filter_);
  accumulator.set_is_for_in(is_for_in_);
564
  accumulator.set_skip_indices(skip_indices_);
565
  accumulator.set_last_non_empty_prototype(last_non_empty_prototype_);
566
  accumulator.set_may_have_elements(may_have_elements_);
567 568
  accumulator.set_first_prototype_map(first_prototype_map_);
  accumulator.set_try_prototype_info_cache(try_prototype_info_cache_);
569 570 571 572

  MAYBE_RETURN(accumulator.CollectKeys(receiver_, receiver_),
               MaybeHandle<FixedArray>());
  return accumulator.GetKeys(keys_conversion);
573
}
574

575 576
MaybeHandle<FixedArray> FastKeyAccumulator::GetKeysWithPrototypeInfoCache(
    GetKeysConversion keys_conversion) {
577 578
  Handle<FixedArray> own_keys;
  if (may_have_elements_) {
579
    MaybeHandle<FixedArray> maybe_own_keys;
580
    if (receiver_->map().is_dictionary_map()) {
581 582 583
      maybe_own_keys = GetOwnKeysWithElements<false>(
          isolate_, Handle<JSObject>::cast(receiver_), keys_conversion,
          skip_indices_);
584
    } else {
585 586 587
      maybe_own_keys = GetOwnKeysWithElements<true>(
          isolate_, Handle<JSObject>::cast(receiver_), keys_conversion,
          skip_indices_);
588
    }
589
    ASSIGN_RETURN_ON_EXCEPTION(isolate_, own_keys, maybe_own_keys, FixedArray);
590 591 592 593
  } else {
    own_keys = KeyAccumulator::GetOwnEnumPropertyKeys(
        isolate_, Handle<JSObject>::cast(receiver_));
  }
594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613
  Handle<FixedArray> prototype_chain_keys;
  if (has_prototype_info_cache_) {
    prototype_chain_keys =
        handle(FixedArray::cast(
                   PrototypeInfo::cast(first_prototype_map_->prototype_info())
                       .prototype_chain_enum_cache()),
               isolate_);
  } else {
    KeyAccumulator accumulator(isolate_, mode_, filter_);
    accumulator.set_is_for_in(is_for_in_);
    accumulator.set_skip_indices(skip_indices_);
    accumulator.set_last_non_empty_prototype(last_non_empty_prototype_);
    accumulator.set_may_have_elements(may_have_elements_);
    accumulator.set_receiver(receiver_);
    accumulator.set_first_prototype_map(first_prototype_map_);
    accumulator.set_try_prototype_info_cache(try_prototype_info_cache_);
    MAYBE_RETURN(accumulator.CollectKeys(first_prototype_, first_prototype_),
                 MaybeHandle<FixedArray>());
    prototype_chain_keys = accumulator.GetKeys(keys_conversion);
  }
614 615 616 617 618 619 620 621
  Handle<FixedArray> result = CombineKeys(
      isolate_, own_keys, prototype_chain_keys, receiver_, may_have_elements_);
  if (is_for_in_ && own_keys.is_identical_to(result)) {
    // Don't leak the enumeration cache without the receiver since it might get
    // trimmed otherwise.
    return isolate_->factory()->CopyFixedArrayUpTo(result, result->length());
  }
  return result;
622 623
}

624 625 626 627 628 629 630 631
bool FastKeyAccumulator::MayHaveElements(JSReceiver receiver) {
  if (!receiver.IsJSObject()) return true;
  JSObject object = JSObject::cast(receiver);
  if (object.HasEnumerableElements()) return true;
  if (object.HasIndexedInterceptor()) return true;
  return false;
}

632
bool FastKeyAccumulator::TryPrototypeInfoCache(Handle<JSReceiver> receiver) {
633
  if (may_have_elements_ && !only_own_has_simple_elements_) return false;
634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656
  Handle<JSObject> object = Handle<JSObject>::cast(receiver);
  if (!object->HasFastProperties()) return false;
  if (object->HasNamedInterceptor()) return false;
  if (object->IsAccessCheckNeeded() &&
      !isolate_->MayAccess(handle(isolate_->context(), isolate_), object)) {
    return false;
  }
  HeapObject prototype = receiver->map().prototype();
  if (prototype.is_null()) return false;
  if (!prototype.map().is_prototype_map() ||
      !prototype.map().prototype_info().IsPrototypeInfo()) {
    return false;
  }
  first_prototype_ = handle(JSReceiver::cast(prototype), isolate_);
  Handle<Map> map(prototype.map(), isolate_);
  first_prototype_map_ = map;
  has_prototype_info_cache_ = map->IsPrototypeValidityCellValid() &&
                              PrototypeInfo::cast(map->prototype_info())
                                  .prototype_chain_enum_cache()
                                  .IsFixedArray();
  return true;
}

657 658
V8_WARN_UNUSED_RESULT ExceptionStatus
KeyAccumulator::FilterForEnumerableProperties(
659
    Handle<JSReceiver> receiver, Handle<JSObject> object,
660 661
    Handle<InterceptorInfo> interceptor, Handle<JSObject> result,
    IndexedOrNamed type) {
662 663 664
  DCHECK(result->IsJSArray() || result->HasSloppyArgumentsElements());
  ElementsAccessor* accessor = result->GetElementsAccessor();

665 666
  size_t length = accessor->GetCapacity(*result, result->elements());
  for (InternalIndex entry : InternalIndex::Range(length)) {
667
    if (!accessor->HasEntry(*result, entry)) continue;
668 669

    // args are invalid after args.Call(), create a new one in every iteration.
670 671
    PropertyCallbackArguments args(isolate_, interceptor->data(), *receiver,
                                   *object, Just(kDontThrow));
672

673
    Handle<Object> element = accessor->Get(result, entry);
674 675 676 677
    Handle<Object> attributes;
    if (type == kIndexed) {
      uint32_t number;
      CHECK(element->ToUint32(&number));
678
      attributes = args.CallIndexedQuery(interceptor, number);
679 680
    } else {
      CHECK(element->IsName());
681 682
      attributes =
          args.CallNamedQuery(interceptor, Handle<Name>::cast(element));
683 684 685 686 687 688
    }

    if (!attributes.is_null()) {
      int32_t value;
      CHECK(attributes->ToInt32(&value));
      if ((value & DONT_ENUM) == 0) {
689
        RETURN_FAILURE_IF_NOT_SUCCESSFUL(AddKey(element, DO_NOT_CONVERT));
690 691 692
      }
    }
  }
693
  return ExceptionStatus::kSuccess;
694 695
}

696
// Returns |true| on success, |nothing| on exception.
697 698 699 700
Maybe<bool> KeyAccumulator::CollectInterceptorKeysInternal(
    Handle<JSReceiver> receiver, Handle<JSObject> object,
    Handle<InterceptorInfo> interceptor, IndexedOrNamed type) {
  PropertyCallbackArguments enum_args(isolate_, interceptor->data(), *receiver,
701
                                      *object, Just(kDontThrow));
702

703
  Handle<JSObject> result;
704
  if (!interceptor->enumerator().IsUndefined(isolate_)) {
705
    if (type == kIndexed) {
706
      result = enum_args.CallIndexedEnumerator(interceptor);
707
    } else {
708
      DCHECK_EQ(type, kNamed);
709
      result = enum_args.CallNamedEnumerator(interceptor);
710
    }
711
  }
712
  RETURN_VALUE_IF_SCHEDULED_EXCEPTION(isolate_, Nothing<bool>());
713
  if (result.is_null()) return Just(true);
714

715 716
  if ((filter_ & ONLY_ENUMERABLE) &&
      !interceptor->query().IsUndefined(isolate_)) {
717
    RETURN_NOTHING_IF_NOT_SUCCESSFUL(FilterForEnumerableProperties(
718
        receiver, object, interceptor, result, type));
719
  } else {
720
    RETURN_NOTHING_IF_NOT_SUCCESSFUL(AddKeys(
721
        result, type == kIndexed ? CONVERT_TO_ARRAY_INDEX : DO_NOT_CONVERT));
722
  }
723 724 725
  return Just(true);
}

726 727 728
Maybe<bool> KeyAccumulator::CollectInterceptorKeys(Handle<JSReceiver> receiver,
                                                   Handle<JSObject> object,
                                                   IndexedOrNamed type) {
729 730 731 732 733 734 735 736
  if (type == kIndexed) {
    if (!object->HasIndexedInterceptor()) return Just(true);
  } else {
    if (!object->HasNamedInterceptor()) return Just(true);
  }
  Handle<InterceptorInfo> interceptor(type == kIndexed
                                          ? object->GetIndexedInterceptor()
                                          : object->GetNamedInterceptor(),
737 738
                                      isolate_);
  if ((filter() & ONLY_ALL_CAN_READ) && !interceptor->all_can_read()) {
739 740
    return Just(true);
  }
741
  return CollectInterceptorKeysInternal(receiver, object, interceptor, type);
742 743
}

744 745 746 747
Maybe<bool> KeyAccumulator::CollectOwnElementIndices(
    Handle<JSReceiver> receiver, Handle<JSObject> object) {
  if (filter_ & SKIP_STRINGS || skip_indices_) return Just(true);

748
  ElementsAccessor* accessor = object->GetElementsAccessor();
749 750
  RETURN_NOTHING_IF_NOT_SUCCESSFUL(
      accessor->CollectElementIndices(object, this));
751
  return CollectInterceptorKeys(receiver, object, kIndexed);
752 753
}

754 755 756
namespace {

template <bool skip_symbols>
757 758 759
base::Optional<int> CollectOwnPropertyNamesInternal(
    Handle<JSObject> object, KeyAccumulator* keys,
    Handle<DescriptorArray> descs, int start_index, int limit) {
760
  AllowGarbageCollection allow_gc;
761
  int first_skipped = -1;
762 763
  PropertyFilter filter = keys->filter();
  KeyCollectionMode mode = keys->mode();
764
  for (InternalIndex i : InternalIndex::Range(start_index, limit)) {
765
    bool is_shadowing_key = false;
766
    PropertyDetails details = descs->GetDetails(i);
767 768 769 770 771 772 773 774 775 776

    if ((details.attributes() & filter) != 0) {
      if (mode == KeyCollectionMode::kIncludePrototypes) {
        is_shadowing_key = true;
      } else {
        continue;
      }
    }

    if (filter & ONLY_ALL_CAN_READ) {
777
      if (details.kind() != kAccessor) continue;
778
      Object accessors = descs->GetStrongValue(i);
779 780
      if (!accessors.IsAccessorInfo()) continue;
      if (!AccessorInfo::cast(accessors).all_can_read()) continue;
781
    }
782

783
    Name key = descs->GetKey(i);
784
    if (skip_symbols == key.IsSymbol()) {
785
      if (first_skipped == -1) first_skipped = i.as_int();
786 787
      continue;
    }
788
    if (key.FilterKey(keys->filter())) continue;
789 790

    if (is_shadowing_key) {
791 792 793
      // This might allocate, but {key} is not used afterwards.
      keys->AddShadowingKey(key, &allow_gc);
      continue;
794
    } else {
795 796 797
      if (keys->AddKey(key, DO_NOT_CONVERT) != ExceptionStatus::kSuccess) {
        return base::Optional<int>();
      }
798
    }
799 800 801 802
  }
  return first_skipped;
}

803 804 805 806 807
// Logic shared between different specializations of CopyEnumKeysTo.
template <typename Dictionary>
void CommonCopyEnumKeysTo(Isolate* isolate, Handle<Dictionary> dictionary,
                          Handle<FixedArray> storage, KeyCollectionMode mode,
                          KeyAccumulator* accumulator) {
808 809 810 811
  DCHECK_IMPLIES(mode != KeyCollectionMode::kOwnOnly, accumulator != nullptr);
  int length = storage->length();
  int properties = 0;
  ReadOnlyRoots roots(isolate);
812

813
  AllowGarbageCollection allow_gc;
814 815 816 817 818 819 820 821 822 823
  for (InternalIndex i : dictionary->IterateEntries()) {
    Object key;
    if (!dictionary->ToKey(roots, i, &key)) continue;
    bool is_shadowing_key = false;
    if (key.IsSymbol()) continue;
    PropertyDetails details = dictionary->DetailsAt(i);
    if (details.IsDontEnum()) {
      if (mode == KeyCollectionMode::kIncludePrototypes) {
        is_shadowing_key = true;
      } else {
824
        continue;
825 826 827 828 829 830 831 832
      }
    }
    if (is_shadowing_key) {
      // This might allocate, but {key} is not used afterwards.
      accumulator->AddShadowingKey(key, &allow_gc);
      continue;
    } else {
      if (Dictionary::kIsOrderedDictionaryType) {
833
        storage->set(properties, dictionary->NameAt(i));
834
      } else {
835 836 837 838
        // If the dictionary does not store elements in enumeration order,
        // we need to sort it afterwards in CopyEnumKeysTo. To enable this we
        // need to store indices at this point, rather than the values at the
        // given indices.
839 840 841
        storage->set(properties, Smi::FromInt(i.as_int()));
      }
    }
842 843
    properties++;
    if (mode == KeyCollectionMode::kOwnOnly && properties == length) break;
844 845 846
  }

  CHECK_EQ(length, properties);
847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862
}

// Copies enumerable keys to preallocated fixed array.
// Does not throw for uninitialized exports in module namespace objects, so
// this has to be checked separately.
template <typename Dictionary>
void CopyEnumKeysTo(Isolate* isolate, Handle<Dictionary> dictionary,
                    Handle<FixedArray> storage, KeyCollectionMode mode,
                    KeyAccumulator* accumulator) {
  STATIC_ASSERT(!Dictionary::kIsOrderedDictionaryType);

  CommonCopyEnumKeysTo<Dictionary>(isolate, dictionary, storage, mode,
                                   accumulator);

  int length = storage->length();

863
  DisallowGarbageCollection no_gc;
864 865 866 867 868 869 870 871 872 873
  Dictionary raw_dictionary = *dictionary;
  FixedArray raw_storage = *storage;
  EnumIndexComparator<Dictionary> cmp(raw_dictionary);
  // Use AtomicSlot wrapper to ensure that std::sort uses atomic load and
  // store operations that are safe for concurrent marking.
  AtomicSlot start(storage->GetFirstElementAddress());
  std::sort(start, start + length, cmp);
  for (int i = 0; i < length; i++) {
    InternalIndex index(Smi::ToInt(raw_storage.get(i)));
    raw_storage.set(i, raw_dictionary.NameAt(index));
874 875 876
  }
}

877 878 879 880 881 882 883 884 885 886 887 888 889
template <>
void CopyEnumKeysTo(Isolate* isolate, Handle<OrderedNameDictionary> dictionary,
                    Handle<FixedArray> storage, KeyCollectionMode mode,
                    KeyAccumulator* accumulator) {
  CommonCopyEnumKeysTo<OrderedNameDictionary>(isolate, dictionary, storage,
                                              mode, accumulator);

  // No need to sort, as CommonCopyEnumKeysTo on OrderedNameDictionary
  // adds entries to |storage| in the dict's insertion order
  // Further, the template argument true above means that |storage|
  // now contains the actual values from |dictionary|, rather than indices.
}

890 891 892 893 894
template <class T>
Handle<FixedArray> GetOwnEnumPropertyDictionaryKeys(Isolate* isolate,
                                                    KeyCollectionMode mode,
                                                    KeyAccumulator* accumulator,
                                                    Handle<JSObject> object,
895
                                                    T raw_dictionary) {
896
  Handle<T> dictionary(raw_dictionary, isolate);
897
  if (dictionary->NumberOfElements() == 0) {
898 899
    return isolate->factory()->empty_fixed_array();
  }
900
  int length = dictionary->NumberOfEnumerableProperties();
901
  Handle<FixedArray> storage = isolate->factory()->NewFixedArray(length);
902
  CopyEnumKeysTo(isolate, dictionary, storage, mode, accumulator);
903 904
  return storage;
}
905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920

// Collect the keys from |dictionary| into |keys|, in ascending chronological
// order of property creation.
template <typename Dictionary>
ExceptionStatus CollectKeysFromDictionary(Handle<Dictionary> dictionary,
                                          KeyAccumulator* keys) {
  Isolate* isolate = keys->isolate();
  ReadOnlyRoots roots(isolate);
  // TODO(jkummerow): Consider using a std::unique_ptr<InternalIndex[]> instead.
  Handle<FixedArray> array =
      isolate->factory()->NewFixedArray(dictionary->NumberOfElements());
  int array_size = 0;
  PropertyFilter filter = keys->filter();
  // Handle enumerable strings in CopyEnumKeysTo.
  DCHECK_NE(keys->filter(), ENUMERABLE_STRINGS);
  {
921
    DisallowGarbageCollection no_gc;
922 923 924 925 926 927 928
    for (InternalIndex i : dictionary->IterateEntries()) {
      Object key;
      Dictionary raw_dictionary = *dictionary;
      if (!raw_dictionary.ToKey(roots, i, &key)) continue;
      if (key.FilterKey(filter)) continue;
      PropertyDetails details = raw_dictionary.DetailsAt(i);
      if ((details.attributes() & filter) != 0) {
929
        AllowGarbageCollection gc;
930 931 932 933 934 935 936 937 938 939
        // This might allocate, but {key} is not used afterwards.
        keys->AddShadowingKey(key, &gc);
        continue;
      }
      if (filter & ONLY_ALL_CAN_READ) {
        if (details.kind() != kAccessor) continue;
        Object accessors = raw_dictionary.ValueAt(i);
        if (!accessors.IsAccessorInfo()) continue;
        if (!AccessorInfo::cast(accessors).all_can_read()) continue;
      }
940 941
      // TODO(emrich): consider storing keys instead of indices into the array
      // in case of ordered dictionary type.
942 943
      array->set(array_size++, Smi::FromInt(i.as_int()));
    }
944 945 946 947 948 949 950 951 952 953
    if (!Dictionary::kIsOrderedDictionaryType) {
      // Sorting only needed if it's an unordered dictionary,
      // otherwise we traversed elements in insertion order

      EnumIndexComparator<Dictionary> cmp(*dictionary);
      // Use AtomicSlot wrapper to ensure that std::sort uses atomic load and
      // store operations that are safe for concurrent marking.
      AtomicSlot start(array->GetFirstElementAddress());
      std::sort(start, start + array_size, cmp);
    }
954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978
  }

  bool has_seen_symbol = false;
  for (int i = 0; i < array_size; i++) {
    InternalIndex index(Smi::ToInt(array->get(i)));
    Object key = dictionary->NameAt(index);
    if (key.IsSymbol()) {
      has_seen_symbol = true;
      continue;
    }
    ExceptionStatus status = keys->AddKey(key, DO_NOT_CONVERT);
    if (!status) return status;
  }
  if (has_seen_symbol) {
    for (int i = 0; i < array_size; i++) {
      InternalIndex index(Smi::ToInt(array->get(i)));
      Object key = dictionary->NameAt(index);
      if (!key.IsSymbol()) continue;
      ExceptionStatus status = keys->AddKey(key, DO_NOT_CONVERT);
      if (!status) return status;
    }
  }
  return ExceptionStatus::kSuccess;
}

979 980 981 982 983
}  // namespace

Maybe<bool> KeyAccumulator::CollectOwnPropertyNames(Handle<JSReceiver> receiver,
                                                    Handle<JSObject> object) {
  if (filter_ == ENUMERABLE_STRINGS) {
984 985 986 987 988
    Handle<FixedArray> enum_keys;
    if (object->HasFastProperties()) {
      enum_keys = KeyAccumulator::GetOwnEnumPropertyKeys(isolate_, object);
      // If the number of properties equals the length of enumerable properties
      // we do not have to filter out non-enumerable ones
989
      Map map = object->map();
990
      int nof_descriptors = map.NumberOfOwnDescriptors();
991
      if (enum_keys->length() != nof_descriptors) {
992
        if (map.prototype(isolate_) != ReadOnlyRoots(isolate_).null_value()) {
993
          AllowGarbageCollection allow_gc;
994 995
          Handle<DescriptorArray> descs = Handle<DescriptorArray>(
              map.instance_descriptors(kRelaxedLoad), isolate_);
996
          for (InternalIndex i : InternalIndex::Range(nof_descriptors)) {
997 998
            PropertyDetails details = descs->GetDetails(i);
            if (!details.IsDontEnum()) continue;
999
            this->AddShadowingKey(descs->GetKey(i), &allow_gc);
1000
          }
1001 1002 1003 1004
        }
      }
    } else if (object->IsJSGlobalObject()) {
      enum_keys = GetOwnEnumPropertyDictionaryKeys(
1005
          isolate_, mode_, this, object,
1006
          JSGlobalObject::cast(*object).global_dictionary(kAcquireLoad));
1007 1008 1009
    } else if (V8_DICT_MODE_PROTOTYPES_BOOL) {
      enum_keys = GetOwnEnumPropertyDictionaryKeys(
          isolate_, mode_, this, object, object->property_dictionary_ordered());
1010 1011 1012 1013
    } else {
      enum_keys = GetOwnEnumPropertyDictionaryKeys(
          isolate_, mode_, this, object, object->property_dictionary());
    }
1014 1015 1016 1017 1018
    if (object->IsJSModuleNamespace()) {
      // Simulate [[GetOwnProperty]] for establishing enumerability, which
      // throws for uninitialized exports.
      for (int i = 0, n = enum_keys->length(); i < n; ++i) {
        Handle<String> key(String::cast(enum_keys->get(i)), isolate_);
1019 1020 1021
        if (Handle<JSModuleNamespace>::cast(object)
                ->GetExport(isolate(), key)
                .is_null()) {
1022 1023 1024 1025
          return Nothing<bool>();
        }
      }
    }
1026
    RETURN_NOTHING_IF_NOT_SUCCESSFUL(AddKeys(enum_keys, DO_NOT_CONVERT));
1027
  } else {
1028
    if (object->HasFastProperties()) {
1029
      int limit = object->map().NumberOfOwnDescriptors();
1030 1031
      Handle<DescriptorArray> descs(
          object->map().instance_descriptors(kRelaxedLoad), isolate_);
1032
      // First collect the strings,
1033
      base::Optional<int> first_symbol =
1034 1035
          CollectOwnPropertyNamesInternal<true>(object, this, descs, 0, limit);
      // then the symbols.
1036 1037 1038 1039
      RETURN_NOTHING_IF_NOT_SUCCESSFUL(first_symbol);
      if (first_symbol.value() != -1) {
        RETURN_NOTHING_IF_NOT_SUCCESSFUL(CollectOwnPropertyNamesInternal<false>(
            object, this, descs, first_symbol.value(), limit));
1040 1041
      }
    } else if (object->IsJSGlobalObject()) {
1042
      RETURN_NOTHING_IF_NOT_SUCCESSFUL(CollectKeysFromDictionary(
1043 1044
          handle(JSGlobalObject::cast(*object).global_dictionary(kAcquireLoad),
                 isolate_),
1045
          this));
1046 1047 1048
    } else if (V8_DICT_MODE_PROTOTYPES_BOOL) {
      RETURN_NOTHING_IF_NOT_SUCCESSFUL(CollectKeysFromDictionary(
          handle(object->property_dictionary_ordered(), isolate_), this));
1049
    } else {
1050
      RETURN_NOTHING_IF_NOT_SUCCESSFUL(CollectKeysFromDictionary(
1051
          handle(object->property_dictionary(), isolate_), this));
1052
    }
1053
  }
1054
  // Add the property keys from the interceptor.
1055
  return CollectInterceptorKeys(receiver, object, kNamed);
1056 1057
}

1058 1059
ExceptionStatus KeyAccumulator::CollectPrivateNames(Handle<JSReceiver> receiver,
                                                    Handle<JSObject> object) {
1060
  DCHECK_EQ(mode_, KeyCollectionMode::kOwnOnly);
1061
  if (object->HasFastProperties()) {
1062
    int limit = object->map().NumberOfOwnDescriptors();
1063 1064
    Handle<DescriptorArray> descs(
        object->map().instance_descriptors(kRelaxedLoad), isolate_);
1065 1066
    CollectOwnPropertyNamesInternal<false>(object, this, descs, 0, limit);
  } else if (object->IsJSGlobalObject()) {
1067
    RETURN_FAILURE_IF_NOT_SUCCESSFUL(CollectKeysFromDictionary(
1068 1069
        handle(JSGlobalObject::cast(*object).global_dictionary(kAcquireLoad),
               isolate_),
1070
        this));
1071 1072 1073
  } else if (V8_DICT_MODE_PROTOTYPES_BOOL) {
    RETURN_FAILURE_IF_NOT_SUCCESSFUL(CollectKeysFromDictionary(
        handle(object->property_dictionary_ordered(), isolate_), this));
1074
  } else {
1075
    RETURN_FAILURE_IF_NOT_SUCCESSFUL(CollectKeysFromDictionary(
1076
        handle(object->property_dictionary(), isolate_), this));
1077
  }
1078
  return ExceptionStatus::kSuccess;
1079 1080
}

1081 1082 1083
Maybe<bool> KeyAccumulator::CollectAccessCheckInterceptorKeys(
    Handle<AccessCheckInfo> access_check_info, Handle<JSReceiver> receiver,
    Handle<JSObject> object) {
1084 1085 1086 1087 1088 1089
  if (!skip_indices_) {
    MAYBE_RETURN((CollectInterceptorKeysInternal(
                     receiver, object,
                     handle(InterceptorInfo::cast(
                                access_check_info->indexed_interceptor()),
                            isolate_),
1090
                     kIndexed)),
1091 1092
                 Nothing<bool>());
  }
1093
  MAYBE_RETURN(
1094
      (CollectInterceptorKeysInternal(
1095 1096 1097
          receiver, object,
          handle(InterceptorInfo::cast(access_check_info->named_interceptor()),
                 isolate_),
1098
          kNamed)),
1099 1100 1101 1102
      Nothing<bool>());
  return Just(true);
}

1103 1104
// Returns |true| on success, |false| if prototype walking should be stopped,
// |nothing| if an exception was thrown.
1105 1106
Maybe<bool> KeyAccumulator::CollectOwnKeys(Handle<JSReceiver> receiver,
                                           Handle<JSObject> object) {
1107 1108
  // Check access rights if required.
  if (object->IsAccessCheckNeeded() &&
1109
      !isolate_->MayAccess(handle(isolate_->context(), isolate_), object)) {
1110 1111
    // The cross-origin spec says that [[Enumerate]] shall return an empty
    // iterator when it doesn't have access...
1112
    if (mode_ == KeyCollectionMode::kIncludePrototypes) {
1113 1114
      return Just(false);
    }
Dan Elphick's avatar
Dan Elphick committed
1115
    // ...whereas [[OwnPropertyKeys]] shall return allowlisted properties.
1116
    DCHECK_EQ(KeyCollectionMode::kOwnOnly, mode_);
1117 1118
    Handle<AccessCheckInfo> access_check_info;
    {
1119
      DisallowGarbageCollection no_gc;
1120 1121 1122 1123
      AccessCheckInfo maybe_info = AccessCheckInfo::Get(isolate_, object);
      if (!maybe_info.is_null()) {
        access_check_info = handle(maybe_info, isolate_);
      }
1124 1125 1126
    }
    // We always have both kinds of interceptors or none.
    if (!access_check_info.is_null() &&
1127
        access_check_info->named_interceptor() != Object()) {
1128 1129 1130 1131 1132
      MAYBE_RETURN(CollectAccessCheckInterceptorKeys(access_check_info,
                                                     receiver, object),
                   Nothing<bool>());
      return Just(false);
    }
1133 1134
    filter_ = static_cast<PropertyFilter>(filter_ | ONLY_ALL_CAN_READ);
  }
1135
  if (filter_ & PRIVATE_NAMES_ONLY) {
1136
    RETURN_NOTHING_IF_NOT_SUCCESSFUL(CollectPrivateNames(receiver, object));
1137 1138 1139
    return Just(true);
  }

1140 1141 1142
  if (may_have_elements_) {
    MAYBE_RETURN(CollectOwnElementIndices(receiver, object), Nothing<bool>());
  }
1143
  MAYBE_RETURN(CollectOwnPropertyNames(receiver, object), Nothing<bool>());
1144 1145 1146 1147
  return Just(true);
}

// static
1148
Handle<FixedArray> KeyAccumulator::GetOwnEnumPropertyKeys(
1149 1150 1151 1152
    Isolate* isolate, Handle<JSObject> object) {
  if (object->HasFastProperties()) {
    return GetFastEnumPropertyKeys(isolate, object);
  } else if (object->IsJSGlobalObject()) {
1153 1154
    return GetOwnEnumPropertyDictionaryKeys(
        isolate, KeyCollectionMode::kOwnOnly, nullptr, object,
1155
        JSGlobalObject::cast(*object).global_dictionary(kAcquireLoad));
1156 1157 1158 1159
  } else if (V8_DICT_MODE_PROTOTYPES_BOOL) {
    return GetOwnEnumPropertyDictionaryKeys(
        isolate, KeyCollectionMode::kOwnOnly, nullptr, object,
        object->property_dictionary_ordered());
1160
  } else {
1161 1162 1163
    return GetOwnEnumPropertyDictionaryKeys(
        isolate, KeyCollectionMode::kOwnOnly, nullptr, object,
        object->property_dictionary());
1164 1165 1166
  }
}

1167 1168
namespace {

1169 1170 1171 1172
class NameComparator {
 public:
  explicit NameComparator(Isolate* isolate) : isolate_(isolate) {}

1173 1174
  bool operator()(uint32_t hash1, uint32_t hash2, const Handle<Name>& key1,
                  const Handle<Name>& key2) const {
1175
    return Name::Equals(isolate_, key1, key2);
1176
  }
1177 1178 1179

 private:
  Isolate* isolate_;
1180 1181 1182 1183
};

}  // namespace

1184
// ES6 #sec-proxy-object-internal-methods-and-internal-slots-ownpropertykeys
1185
// Returns |true| on success, |nothing| in case of exception.
1186 1187
Maybe<bool> KeyAccumulator::CollectOwnJSProxyKeys(Handle<JSReceiver> receiver,
                                                  Handle<JSProxy> proxy) {
1188
  STACK_CHECK(isolate_, Nothing<bool>());
1189
  if (filter_ == PRIVATE_NAMES_ONLY) {
1190 1191 1192 1193 1194 1195 1196
    if (V8_DICT_MODE_PROTOTYPES_BOOL) {
      RETURN_NOTHING_IF_NOT_SUCCESSFUL(CollectKeysFromDictionary(
          handle(proxy->property_dictionary_ordered(), isolate_), this));
    } else {
      RETURN_NOTHING_IF_NOT_SUCCESSFUL(CollectKeysFromDictionary(
          handle(proxy->property_dictionary(), isolate_), this));
    }
1197 1198 1199
    return Just(true);
  }

1200 1201 1202 1203 1204 1205 1206 1207 1208 1209
  // 1. Let handler be the value of the [[ProxyHandler]] internal slot of O.
  Handle<Object> handler(proxy->handler(), isolate_);
  // 2. If handler is null, throw a TypeError exception.
  // 3. Assert: Type(handler) is Object.
  if (proxy->IsRevoked()) {
    isolate_->Throw(*isolate_->factory()->NewTypeError(
        MessageTemplate::kProxyRevoked, isolate_->factory()->ownKeys_string()));
    return Nothing<bool>();
  }
  // 4. Let target be the value of the [[ProxyTarget]] internal slot of O.
1210
  Handle<JSReceiver> target(JSReceiver::cast(proxy->target()), isolate_);
1211 1212 1213
  // 5. Let trap be ? GetMethod(handler, "ownKeys").
  Handle<Object> trap;
  ASSIGN_RETURN_ON_EXCEPTION_VALUE(
1214 1215 1216
      isolate_, trap,
      Object::GetMethod(Handle<JSReceiver>::cast(handler),
                        isolate_->factory()->ownKeys_string()),
1217 1218
      Nothing<bool>());
  // 6. If trap is undefined, then
1219
  if (trap->IsUndefined(isolate_)) {
1220
    // 6a. Return target.[[OwnPropertyKeys]]().
1221
    return CollectOwnJSProxyTargetKeys(proxy, target);
1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237
  }
  // 7. Let trapResultArray be Call(trap, handler, «target»).
  Handle<Object> trap_result_array;
  Handle<Object> args[] = {target};
  ASSIGN_RETURN_ON_EXCEPTION_VALUE(
      isolate_, trap_result_array,
      Execution::Call(isolate_, trap, handler, arraysize(args), args),
      Nothing<bool>());
  // 8. Let trapResult be ? CreateListFromArrayLike(trapResultArray,
  //    «String, Symbol»).
  Handle<FixedArray> trap_result;
  ASSIGN_RETURN_ON_EXCEPTION_VALUE(
      isolate_, trap_result,
      Object::CreateListFromArrayLike(isolate_, trap_result_array,
                                      ElementTypes::kStringAndSymbol),
      Nothing<bool>());
1238 1239 1240 1241
  // 9. If trapResult contains any duplicate entries, throw a TypeError
  // exception. Combine with step 18
  // 18. Let uncheckedResultKeys be a new List which is a copy of trapResult.
  Zone set_zone(isolate_->allocator(), ZONE_NAME);
1242

1243 1244
  const int kPresent = 1;
  const int kGone = 0;
1245 1246 1247 1248 1249 1250
  using ZoneHashMapImpl =
      base::TemplateHashMapImpl<Handle<Name>, int, NameComparator,
                                ZoneAllocationPolicy>;
  ZoneHashMapImpl unchecked_result_keys(
      ZoneHashMapImpl::kDefaultHashMapCapacity, NameComparator(isolate_),
      ZoneAllocationPolicy(&set_zone));
1251 1252 1253
  int unchecked_result_keys_size = 0;
  for (int i = 0; i < trap_result->length(); ++i) {
    Handle<Name> key(Name::cast(trap_result->get(i)), isolate_);
1254
    auto entry = unchecked_result_keys.LookupOrInsert(key, key->EnsureHash());
1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265
    if (entry->value != kPresent) {
      entry->value = kPresent;
      unchecked_result_keys_size++;
    } else {
      // found dupes, throw exception
      isolate_->Throw(*isolate_->factory()->NewTypeError(
          MessageTemplate::kProxyOwnKeysDuplicateEntries));
      return Nothing<bool>();
    }
  }
  // 10. Let extensibleTarget be ? IsExtensible(target).
1266 1267 1268
  Maybe<bool> maybe_extensible = JSReceiver::IsExtensible(target);
  MAYBE_RETURN(maybe_extensible, Nothing<bool>());
  bool extensible_target = maybe_extensible.FromJust();
1269
  // 11. Let targetKeys be ? target.[[OwnPropertyKeys]]().
1270 1271 1272 1273
  Handle<FixedArray> target_keys;
  ASSIGN_RETURN_ON_EXCEPTION_VALUE(isolate_, target_keys,
                                   JSReceiver::OwnPropertyKeys(target),
                                   Nothing<bool>());
1274 1275
  // 12, 13. (Assert)
  // 14. Let targetConfigurableKeys be an empty List.
1276 1277
  // To save memory, we're re-using target_keys and will modify it in-place.
  Handle<FixedArray> target_configurable_keys = target_keys;
1278
  // 15. Let targetNonconfigurableKeys be an empty List.
1279 1280 1281
  Handle<FixedArray> target_nonconfigurable_keys =
      isolate_->factory()->NewFixedArray(target_keys->length());
  int nonconfigurable_keys_length = 0;
1282
  // 16. Repeat, for each element key of targetKeys:
1283
  for (int i = 0; i < target_keys->length(); ++i) {
1284
    // 16a. Let desc be ? target.[[GetOwnProperty]](key).
1285 1286 1287 1288
    PropertyDescriptor desc;
    Maybe<bool> found = JSReceiver::GetOwnPropertyDescriptor(
        isolate_, target, handle(target_keys->get(i), isolate_), &desc);
    MAYBE_RETURN(found, Nothing<bool>());
1289
    // 16b. If desc is not undefined and desc.[[Configurable]] is false, then
1290
    if (found.FromJust() && !desc.configurable()) {
1291
      // 16b i. Append key as an element of targetNonconfigurableKeys.
1292 1293 1294 1295
      target_nonconfigurable_keys->set(nonconfigurable_keys_length,
                                       target_keys->get(i));
      nonconfigurable_keys_length++;
      // The key was moved, null it out in the original list.
1296
      target_keys->set(i, Smi::zero());
1297
    } else {
1298 1299
      // 16c. Else,
      // 16c i. Append key as an element of targetConfigurableKeys.
1300 1301 1302
      // (No-op, just keep it in |target_keys|.)
    }
  }
1303
  // 17. If extensibleTarget is true and targetNonconfigurableKeys is empty,
1304 1305
  //     then:
  if (extensible_target && nonconfigurable_keys_length == 0) {
1306
    // 17a. Return trapResult.
1307
    return AddKeysFromJSProxy(proxy, trap_result);
1308
  }
1309 1310
  // 18. (Done in step 9)
  // 19. Repeat, for each key that is an element of targetNonconfigurableKeys:
1311
  for (int i = 0; i < nonconfigurable_keys_length; ++i) {
1312
    Object raw_key = target_nonconfigurable_keys->get(i);
1313
    Handle<Name> key(Name::cast(raw_key), isolate_);
1314
    // 19a. If key is not an element of uncheckedResultKeys, throw a
1315
    //      TypeError exception.
1316
    auto found = unchecked_result_keys.Lookup(key, key->hash());
1317
    if (found == nullptr || found->value == kGone) {
1318
      isolate_->Throw(*isolate_->factory()->NewTypeError(
1319
          MessageTemplate::kProxyOwnKeysMissing, key));
1320 1321
      return Nothing<bool>();
    }
1322
    // 19b. Remove key from uncheckedResultKeys.
1323
    found->value = kGone;
1324 1325
    unchecked_result_keys_size--;
  }
1326
  // 20. If extensibleTarget is true, return trapResult.
1327
  if (extensible_target) {
1328
    return AddKeysFromJSProxy(proxy, trap_result);
1329
  }
1330
  // 21. Repeat, for each key that is an element of targetConfigurableKeys:
1331
  for (int i = 0; i < target_configurable_keys->length(); ++i) {
1332
    Object raw_key = target_configurable_keys->get(i);
1333
    if (raw_key.IsSmi()) continue;  // Zapped entry, was nonconfigurable.
1334
    Handle<Name> key(Name::cast(raw_key), isolate_);
1335
    // 21a. If key is not an element of uncheckedResultKeys, throw a
1336
    //      TypeError exception.
1337
    auto found = unchecked_result_keys.Lookup(key, key->hash());
1338
    if (found == nullptr || found->value == kGone) {
1339
      isolate_->Throw(*isolate_->factory()->NewTypeError(
1340
          MessageTemplate::kProxyOwnKeysMissing, key));
1341 1342
      return Nothing<bool>();
    }
1343
    // 21b. Remove key from uncheckedResultKeys.
1344
    found->value = kGone;
1345 1346
    unchecked_result_keys_size--;
  }
1347
  // 22. If uncheckedResultKeys is not empty, throw a TypeError exception.
1348 1349 1350 1351 1352 1353
  if (unchecked_result_keys_size != 0) {
    DCHECK_GT(unchecked_result_keys_size, 0);
    isolate_->Throw(*isolate_->factory()->NewTypeError(
        MessageTemplate::kProxyOwnKeysNonExtensible));
    return Nothing<bool>();
  }
1354
  // 23. Return trapResult.
1355 1356 1357 1358 1359 1360 1361 1362
  return AddKeysFromJSProxy(proxy, trap_result);
}

Maybe<bool> KeyAccumulator::CollectOwnJSProxyTargetKeys(
    Handle<JSProxy> proxy, Handle<JSReceiver> target) {
  // TODO(cbruni): avoid creating another KeyAccumulator
  Handle<FixedArray> keys;
  ASSIGN_RETURN_ON_EXCEPTION_VALUE(
1363
      isolate_, keys,
1364 1365 1366
      KeyAccumulator::GetKeys(
          target, KeyCollectionMode::kOwnOnly, ALL_PROPERTIES,
          GetKeysConversion::kConvertToString, is_for_in_, skip_indices_),
1367
      Nothing<bool>());
1368 1369
  Maybe<bool> result = AddKeysFromJSProxy(proxy, keys);
  return result;
1370 1371
}

1372 1373
#undef RETURN_NOTHING_IF_NOT_SUCCESSFUL
#undef RETURN_FAILURE_IF_NOT_SUCCESSFUL
1374 1375
}  // namespace internal
}  // namespace v8