lookup.cc 65.6 KB
Newer Older
1 2 3 4
// Copyright 2014 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/lookup.h"
6

7
#include "src/common/globals.h"
8
#include "src/deoptimizer/deoptimizer.h"
9
#include "src/execution/isolate-inl.h"
10
#include "src/execution/protectors-inl.h"
11
#include "src/init/bootstrapper.h"
12
#include "src/logging/counters.h"
13
#include "src/objects/arguments-inl.h"
14 15
#include "src/objects/elements.h"
#include "src/objects/field-type.h"
16
#include "src/objects/hash-table-inl.h"
17
#include "src/objects/heap-number-inl.h"
18
#include "src/objects/js-shared-array-inl.h"
19
#include "src/objects/js-struct-inl.h"
20
#include "src/objects/map-updater.h"
21
#include "src/objects/ordered-hash-table.h"
22
#include "src/objects/property-details.h"
23
#include "src/objects/struct-inl.h"
24

25 26 27 28
#if V8_ENABLE_WEBASSEMBLY
#include "src/wasm/wasm-objects-inl.h"
#endif  // V8_ENABLE_WEBASSEMBLY

29 30 31
namespace v8 {
namespace internal {

32
PropertyKey::PropertyKey(Isolate* isolate, Handle<Object> key, bool* success) {
33
  if (key->ToIntegerIndex(&index_)) {
34
    *success = true;
35
    return;
36
  }
37
  *success = Object::ToName(isolate, key).ToHandle(&name_);
38 39
  if (!*success) {
    DCHECK(isolate->has_pending_exception());
40
    index_ = LookupIterator::kInvalidIndex;
41
    return;
42
  }
43 44 45
  if (!name_->AsIntegerIndex(&index_)) {
    // {AsIntegerIndex} may modify {index_} before deciding to fail.
    index_ = LookupIterator::kInvalidIndex;
46 47 48
  }
}

49 50 51 52 53 54 55 56 57 58 59 60
LookupIterator::LookupIterator(Isolate* isolate, Handle<Object> receiver,
                               Handle<Name> name, Handle<Map> transition_map,
                               PropertyDetails details, bool has_property)
    : configuration_(DEFAULT),
      state_(TRANSITION),
      has_property_(has_property),
      interceptor_state_(InterceptorState::kUninitialized),
      property_details_(details),
      isolate_(isolate),
      name_(name),
      transition_(transition_map),
      receiver_(receiver),
61
      lookup_start_object_(receiver),
62
      index_(kInvalidIndex) {
63
  holder_ = GetRoot(isolate, lookup_start_object_);
64 65
}

66 67
template <bool is_element>
void LookupIterator::Start() {
68 69
  // GetRoot might allocate if lookup_start_object_ is a string.
  holder_ = GetRoot(isolate_, lookup_start_object_, index_);
70

71
  {
72
    DisallowGarbageCollection no_gc;
73

74 75
    has_property_ = false;
    state_ = NOT_FOUND;
76

77 78
    JSReceiver holder = *holder_;
    Map map = holder.map(isolate_);
79

80 81 82 83 84
    state_ = LookupInHolder<is_element>(map, holder);
    if (IsFound()) return;

    NextInternal<is_element>(map, holder);
  }
85 86 87 88
}

template void LookupIterator::Start<true>();
template void LookupIterator::Start<false>();
89

90
void LookupIterator::Next() {
91 92
  DCHECK_NE(JSPROXY, state_);
  DCHECK_NE(TRANSITION, state_);
93
  DisallowGarbageCollection no_gc;
94
  has_property_ = false;
95

96
  JSReceiver holder = *holder_;
97
  Map map = holder.map(isolate_);
98

99
  if (map.IsSpecialReceiverMap()) {
100 101 102 103 104 105 106 107
    state_ = IsElement() ? LookupInSpecialHolder<true>(map, holder)
                         : LookupInSpecialHolder<false>(map, holder);
    if (IsFound()) return;
  }

  IsElement() ? NextInternal<true>(map, holder)
              : NextInternal<false>(map, holder);
}
108

109
template <bool is_element>
110
void LookupIterator::NextInternal(Map map, JSReceiver holder) {
111
  do {
112 113
    JSReceiver maybe_holder = NextHolder(map);
    if (maybe_holder.is_null()) {
114
      if (interceptor_state_ == InterceptorState::kSkipNonMasking) {
115
        RestartLookupForNonMaskingInterceptors<is_element>();
116 117
        return;
      }
118 119 120
      state_ = NOT_FOUND;
      if (holder != *holder_) holder_ = handle(holder, isolate_);
      return;
121
    }
122
    holder = maybe_holder;
123
    map = holder.map(isolate_);
124
    state_ = LookupInHolder<is_element>(map, holder);
125
  } while (!IsFound());
126

127
  holder_ = handle(holder, isolate_);
128 129
}

130
template <bool is_element>
131 132
void LookupIterator::RestartInternal(InterceptorState interceptor_state) {
  interceptor_state_ = interceptor_state;
133
  property_details_ = PropertyDetails::Empty();
134
  number_ = InternalIndex::NotFound();
135
  Start<is_element>();
136 137
}

138 139
template void LookupIterator::RestartInternal<true>(InterceptorState);
template void LookupIterator::RestartInternal<false>(InterceptorState);
140

141
// static
142
Handle<JSReceiver> LookupIterator::GetRootForNonJSReceiver(
143
    Isolate* isolate, Handle<Object> lookup_start_object, size_t index) {
144 145
  // Strings are the only objects with properties (only elements) directly on
  // the wrapper. Hence we can skip generating the wrapper for all other cases.
146 147 148
  if (lookup_start_object->IsString(isolate) &&
      index <
          static_cast<size_t>(String::cast(*lookup_start_object).length())) {
149 150 151 152
    // TODO(verwaest): Speed this up. Perhaps use a cached wrapper on the native
    // context, ensuring that we don't leak it into JS?
    Handle<JSFunction> constructor = isolate->string_function();
    Handle<JSObject> result = isolate->factory()->NewJSObject(constructor);
153
    Handle<JSPrimitiveWrapper>::cast(result)->set_value(*lookup_start_object);
154 155
    return result;
  }
156
  Handle<HeapObject> root(
157 158
      lookup_start_object->GetPrototypeChainRootMap(isolate).prototype(isolate),
      isolate);
159
  if (root->IsNull(isolate)) {
160 161
    isolate->PushStackTraceAndDie(
        reinterpret_cast<void*>(lookup_start_object->ptr()));
162
  }
163
  return Handle<JSReceiver>::cast(root);
164 165 166
}

Handle<Map> LookupIterator::GetReceiverMap() const {
167 168
  if (receiver_->IsNumber(isolate_)) return factory()->heap_number_map();
  return handle(Handle<HeapObject>::cast(receiver_)->map(isolate_), isolate_);
169 170
}

171
bool LookupIterator::HasAccess() const {
172
  // TRANSITION is true when being called from DefineNamedOwnIC.
173
  DCHECK(state_ == ACCESS_CHECK || state_ == TRANSITION);
174
  return isolate_->MayAccess(handle(isolate_->context(), isolate_),
175
                             GetHolder<JSObject>());
176 177
}

178
template <bool is_element>
179 180
void LookupIterator::ReloadPropertyInformation() {
  state_ = BEFORE_PROPERTY;
181
  interceptor_state_ = InterceptorState::kUninitialized;
182 183
  state_ = LookupInHolder<is_element>(holder_->map(isolate_), *holder_);
  DCHECK(IsFound() || !holder_->HasFastProperties(isolate_));
184 185
}

186 187 188 189 190 191 192
// static
void LookupIterator::InternalUpdateProtector(Isolate* isolate,
                                             Handle<Object> receiver_generic,
                                             Handle<Name> name) {
  if (isolate->bootstrapper()->IsActive()) return;
  if (!receiver_generic->IsHeapObject()) return;
  Handle<HeapObject> receiver = Handle<HeapObject>::cast(receiver_generic);
193

194 195
  ReadOnlyRoots roots(isolate);
  if (*name == roots.constructor_string()) {
196
    // Setting the constructor property could change an instance's @@species
197 198 199
    if (receiver->IsJSArray(isolate)) {
      if (!Protectors::IsArraySpeciesLookupChainIntact(isolate)) return;
      isolate->CountUsage(
200
          v8::Isolate::UseCounterFeature::kArrayInstanceConstructorModified);
201
      Protectors::InvalidateArraySpeciesLookupChain(isolate);
202
      return;
203 204 205
    } else if (receiver->IsJSPromise(isolate)) {
      if (!Protectors::IsPromiseSpeciesLookupChainIntact(isolate)) return;
      Protectors::InvalidatePromiseSpeciesLookupChain(isolate);
206
      return;
207
    } else if (receiver->IsJSRegExp(isolate)) {
208 209
      if (!Protectors::IsRegExpSpeciesLookupChainIntact(isolate)) return;
      Protectors::InvalidateRegExpSpeciesLookupChain(isolate);
210
      return;
211 212 213
    } else if (receiver->IsJSTypedArray(isolate)) {
      if (!Protectors::IsTypedArraySpeciesLookupChainIntact(isolate)) return;
      Protectors::InvalidateTypedArraySpeciesLookupChain(isolate);
214 215
      return;
    }
216
    if (receiver->map(isolate).is_prototype_map()) {
217
      DisallowGarbageCollection no_gc;
218 219
      // Setting the constructor of any prototype with the @@species protector
      // (of any realm) also needs to invalidate the protector.
220 221 222 223
      if (isolate->IsInAnyContext(*receiver,
                                  Context::INITIAL_ARRAY_PROTOTYPE_INDEX)) {
        if (!Protectors::IsArraySpeciesLookupChainIntact(isolate)) return;
        isolate->CountUsage(
224
            v8::Isolate::UseCounterFeature::kArrayPrototypeConstructorModified);
225
        Protectors::InvalidateArraySpeciesLookupChain(isolate);
226
      } else if (receiver->IsJSPromisePrototype()) {
227 228
        if (!Protectors::IsPromiseSpeciesLookupChainIntact(isolate)) return;
        Protectors::InvalidatePromiseSpeciesLookupChain(isolate);
229
      } else if (receiver->IsJSRegExpPrototype()) {
230 231
        if (!Protectors::IsRegExpSpeciesLookupChainIntact(isolate)) return;
        Protectors::InvalidateRegExpSpeciesLookupChain(isolate);
232
      } else if (receiver->IsJSTypedArrayPrototype()) {
233 234
        if (!Protectors::IsTypedArraySpeciesLookupChainIntact(isolate)) return;
        Protectors::InvalidateTypedArraySpeciesLookupChain(isolate);
235 236
      }
    }
237
  } else if (*name == roots.next_string()) {
238
    if (receiver->IsJSArrayIterator() ||
239
        receiver->IsJSArrayIteratorPrototype()) {
240 241
      // Setting the next property of %ArrayIteratorPrototype% also needs to
      // invalidate the array iterator protector.
242 243
      if (!Protectors::IsArrayIteratorLookupChainIntact(isolate)) return;
      Protectors::InvalidateArrayIteratorLookupChain(isolate);
244
    } else if (receiver->IsJSMapIterator() ||
245
               receiver->IsJSMapIteratorPrototype()) {
246 247
      if (!Protectors::IsMapIteratorLookupChainIntact(isolate)) return;
      Protectors::InvalidateMapIteratorLookupChain(isolate);
248
    } else if (receiver->IsJSSetIterator() ||
249
               receiver->IsJSSetIteratorPrototype()) {
250 251
      if (!Protectors::IsSetIteratorLookupChainIntact(isolate)) return;
      Protectors::InvalidateSetIteratorLookupChain(isolate);
252
    } else if (receiver->IsJSStringIterator() ||
253
               receiver->IsJSStringIteratorPrototype()) {
254 255
      // Setting the next property of %StringIteratorPrototype% invalidates the
      // string iterator protector.
256 257
      if (!Protectors::IsStringIteratorLookupChainIntact(isolate)) return;
      Protectors::InvalidateStringIteratorLookupChain(isolate);
258
    }
259
  } else if (*name == roots.species_symbol()) {
260 261
    // Setting the Symbol.species property of any Array, Promise or TypedArray
    // constructor invalidates the @@species protector
262
    if (receiver->IsJSArrayConstructor()) {
263 264
      if (!Protectors::IsArraySpeciesLookupChainIntact(isolate)) return;
      isolate->CountUsage(
265
          v8::Isolate::UseCounterFeature::kArraySpeciesModified);
266
      Protectors::InvalidateArraySpeciesLookupChain(isolate);
267
    } else if (receiver->IsJSPromiseConstructor()) {
268 269
      if (!Protectors::IsPromiseSpeciesLookupChainIntact(isolate)) return;
      Protectors::InvalidatePromiseSpeciesLookupChain(isolate);
270
    } else if (receiver->IsJSRegExpConstructor()) {
271 272
      if (!Protectors::IsRegExpSpeciesLookupChainIntact(isolate)) return;
      Protectors::InvalidateRegExpSpeciesLookupChain(isolate);
273
    } else if (receiver->IsTypedArrayConstructor()) {
274 275
      if (!Protectors::IsTypedArraySpeciesLookupChainIntact(isolate)) return;
      Protectors::InvalidateTypedArraySpeciesLookupChain(isolate);
276
    }
277 278 279 280 281 282 283 284
  } else if (*name == roots.is_concat_spreadable_symbol()) {
    if (!Protectors::IsIsConcatSpreadableLookupChainIntact(isolate)) return;
    Protectors::InvalidateIsConcatSpreadableLookupChain(isolate);
  } else if (*name == roots.iterator_symbol()) {
    if (receiver->IsJSArray(isolate)) {
      if (!Protectors::IsArrayIteratorLookupChainIntact(isolate)) return;
      Protectors::InvalidateArrayIteratorLookupChain(isolate);
    } else if (receiver->IsJSSet(isolate) || receiver->IsJSSetIterator() ||
285 286
               receiver->IsJSSetIteratorPrototype() ||
               receiver->IsJSSetPrototype()) {
287 288
      if (Protectors::IsSetIteratorLookupChainIntact(isolate)) {
        Protectors::InvalidateSetIteratorLookupChain(isolate);
289 290
      }
    } else if (receiver->IsJSMapIterator() ||
291
               receiver->IsJSMapIteratorPrototype()) {
292 293
      if (Protectors::IsMapIteratorLookupChainIntact(isolate)) {
        Protectors::InvalidateMapIteratorLookupChain(isolate);
294
      }
295
    } else if (receiver->IsJSIteratorPrototype()) {
296 297
      if (Protectors::IsMapIteratorLookupChainIntact(isolate)) {
        Protectors::InvalidateMapIteratorLookupChain(isolate);
298
      }
299 300
      if (Protectors::IsSetIteratorLookupChainIntact(isolate)) {
        Protectors::InvalidateSetIteratorLookupChain(isolate);
301
      }
302
    } else if (isolate->IsInAnyContext(
303
                   *receiver, Context::INITIAL_STRING_PROTOTYPE_INDEX)) {
304 305 306 307
      // Setting the Symbol.iterator property of String.prototype invalidates
      // the string iterator protector. Symbol.iterator can also be set on a
      // String wrapper, but not on a primitive string. We only support
      // protector for primitive strings.
308 309
      if (!Protectors::IsStringIteratorLookupChainIntact(isolate)) return;
      Protectors::InvalidateStringIteratorLookupChain(isolate);
310
    }
311 312
  } else if (*name == roots.resolve_string()) {
    if (!Protectors::IsPromiseResolveLookupChainIntact(isolate)) return;
313 314
    // Setting the "resolve" property on any %Promise% intrinsic object
    // invalidates the Promise.resolve protector.
315
    if (receiver->IsJSPromiseConstructor()) {
316
      Protectors::InvalidatePromiseResolveLookupChain(isolate);
317
    }
318 319
  } else if (*name == roots.then_string()) {
    if (!Protectors::IsPromiseThenLookupChainIntact(isolate)) return;
320 321
    // Setting the "then" property on any JSPromise instance or on the
    // initial %PromisePrototype% invalidates the Promise#then protector.
322 323 324 325 326
    // Also setting the "then" property on the initial %ObjectPrototype%
    // invalidates the Promise#then protector, since we use this protector
    // to guard the fast-path in AsyncGeneratorResolve, where we can skip
    // the ResolvePromise step and go directly to FulfillPromise if we
    // know that the Object.prototype doesn't contain a "then" method.
327 328
    if (receiver->IsJSPromise(isolate) || receiver->IsJSObjectPrototype() ||
        receiver->IsJSPromisePrototype()) {
329
      Protectors::InvalidatePromiseThenLookupChain(isolate);
330
    }
331 332
  }
}
333

334
void LookupIterator::PrepareForDataProperty(Handle<Object> value) {
335
  DCHECK(state_ == DATA || state_ == ACCESSOR);
336
  DCHECK(HolderIsReceiverOrHiddenPrototype());
337 338 339
#if V8_ENABLE_WEBASSEMBLY
  DCHECK(!receiver_->IsWasmObject(isolate_));
#endif  // V8_ENABLE_WEBASSEMBLY
340

341
  Handle<JSReceiver> holder = GetHolder<JSReceiver>();
342 343
  // We are not interested in tracking constness of a JSProxy's direct
  // properties.
344 345
  DCHECK_IMPLIES(holder->IsJSProxy(isolate_), name()->IsPrivate(isolate_));
  if (holder->IsJSProxy(isolate_)) return;
346

347
  if (IsElement(*holder)) {
348
    Handle<JSObject> holder_obj = Handle<JSObject>::cast(holder);
349 350
    ElementsKind kind = holder_obj->GetElementsKind(isolate_);
    ElementsKind to = value->OptimalElementsKind(isolate_);
351
    if (IsHoleyElementsKind(kind)) to = GetHoleyElementsKind(to);
352
    to = GetMoreGeneralElementsKind(kind, to);
353 354

    if (kind != to) {
355
      JSObject::TransitionElementsKind(holder_obj, to);
356
    }
357 358

    // Copy the backing store if it is copy-on-write.
359 360
    if (IsSmiOrObjectElementsKind(to) || IsSealedElementsKind(to) ||
        IsNonextensibleElementsKind(to)) {
361
      JSObject::EnsureWritableFastElements(holder_obj);
362
    }
363 364
    return;
  }
365

366
  if (holder->IsJSGlobalObject(isolate_)) {
367
    Handle<GlobalDictionary> dictionary(
368
        JSGlobalObject::cast(*holder).global_dictionary(isolate_, kAcquireLoad),
369 370
        isolate());
    Handle<PropertyCell> cell(dictionary->CellAt(isolate_, dictionary_entry()),
371
                              isolate());
372
    property_details_ = cell->property_details();
373 374
    PropertyCell::PrepareForAndSetValue(
        isolate(), dictionary, dictionary_entry(), value, property_details_);
375 376
    return;
  }
377

378
  PropertyConstness new_constness = PropertyConstness::kConst;
379
  if (constness() == PropertyConstness::kConst) {
380
    DCHECK_EQ(PropertyKind::kData, property_details_.kind());
381 382
    // Check that current value matches new value otherwise we should make
    // the property mutable.
383 384 385 386 387 388 389 390 391 392 393 394 395
    if (holder->HasFastProperties(isolate_)) {
      if (!IsConstFieldValueEqualTo(*value)) {
        new_constness = PropertyConstness::kMutable;
      }
    } else if (V8_DICT_PROPERTY_CONST_TRACKING_BOOL) {
      if (!IsConstDictValueEqualTo(*value)) {
        property_details_ =
            property_details_.CopyWithConstness(PropertyConstness::kMutable);

        // We won't reach the map updating code after Map::Update below, because
        // that's only for the case that the existing map is a fast mode map.
        // Therefore, we need to perform the necessary updates to the property
        // details and the prototype validity cell directly.
396
        if (V8_ENABLE_SWISS_NAME_DICTIONARY_BOOL) {
397 398 399 400 401 402
          SwissNameDictionary dict = holder->property_dictionary_swiss();
          dict.DetailsAtPut(dictionary_entry(), property_details_);
        } else {
          NameDictionary dict = holder->property_dictionary();
          dict.DetailsAtPut(dictionary_entry(), property_details_);
        }
403 404 405 406 407 408 409 410

        Map old_map = holder->map(isolate_);
        if (old_map.is_prototype_map()) {
          JSObject::InvalidatePrototypeChains(old_map);
        }
      }
      return;
    }
411 412
  }

413 414 415 416
  if (!holder->HasFastProperties(isolate_)) return;

  Handle<JSObject> holder_obj = Handle<JSObject>::cast(holder);
  Handle<Map> old_map(holder->map(isolate_), isolate_);
417 418

  Handle<Map> new_map = Map::Update(isolate_, old_map);
419
  if (!new_map->is_dictionary_map()) {  // fast -> fast
420 421 422 423 424 425
    new_map = Map::PrepareForDataProperty(
        isolate(), new_map, descriptor_number(), new_constness, value);

    if (old_map.is_identical_to(new_map)) {
      // Update the property details if the representation was None.
      if (constness() != new_constness || representation().IsNone()) {
426 427
        property_details_ = new_map->instance_descriptors(isolate_).GetDetails(
            descriptor_number());
428 429
      }
      return;
430
    }
431
  }
432 433 434
  // We should only get here if the new_map is different from the old map,
  // otherwise we would have falled through to the is_identical_to check above.
  DCHECK_NE(*old_map, *new_map);
435

436
  JSObject::MigrateToMap(isolate_, holder_obj, new_map);
437
  ReloadPropertyInformation<false>();
438 439 440 441 442 443 444 445 446 447

  // If we transitioned from fast to slow and the property changed from kConst
  // to kMutable, then this change in the constness is indicated by neither the
  // old or the new map. We need to update the constness ourselves.
  DCHECK(!old_map->is_dictionary_map());
  if (V8_DICT_PROPERTY_CONST_TRACKING_BOOL && new_map->is_dictionary_map() &&
      new_constness == PropertyConstness::kMutable) {  // fast -> slow
    property_details_ =
        property_details_.CopyWithConstness(PropertyConstness::kMutable);

448
    if (V8_ENABLE_SWISS_NAME_DICTIONARY_BOOL) {
449 450 451 452 453 454
      SwissNameDictionary dict = holder_obj->property_dictionary_swiss();
      dict.DetailsAtPut(dictionary_entry(), property_details_);
    } else {
      NameDictionary dict = holder_obj->property_dictionary();
      dict.DetailsAtPut(dictionary_entry(), property_details_);
    }
455 456 457 458

    DCHECK_IMPLIES(new_map->is_prototype_map(),
                   !new_map->IsPrototypeValidityCellValid());
  }
459 460
}

461 462
void LookupIterator::ReconfigureDataProperty(Handle<Object> value,
                                             PropertyAttributes attributes) {
463
  DCHECK(state_ == DATA || state_ == ACCESSOR);
464
  DCHECK(HolderIsReceiverOrHiddenPrototype());
465 466

  Handle<JSReceiver> holder = GetHolder<JSReceiver>();
467 468 469
#if V8_ENABLE_WEBASSEMBLY
  if (V8_UNLIKELY(holder->IsWasmObject())) UNREACHABLE();
#endif  // V8_ENABLE_WEBASSEMBLY
470

471
  // Property details can never change for private properties.
472 473
  if (holder->IsJSProxy(isolate_)) {
    DCHECK(name()->IsPrivate(isolate_));
474 475 476 477
    return;
  }

  Handle<JSObject> holder_obj = Handle<JSObject>::cast(holder);
478
  if (IsElement(*holder)) {
479
    DCHECK(!holder_obj->HasTypedArrayOrRabGsabTypedArrayElements(isolate_));
480 481 482
    DCHECK(attributes != NONE || !holder_obj->HasFastElements(isolate_));
    Handle<FixedArrayBase> elements(holder_obj->elements(isolate_), isolate());
    holder_obj->GetElementsAccessor(isolate_)->Reconfigure(
483
        holder_obj, elements, number_, value, attributes);
484
    ReloadPropertyInformation<true>();
485 486
  } else if (holder_obj->HasFastProperties(isolate_)) {
    Handle<Map> old_map(holder_obj->map(isolate_), isolate_);
487 488
    // Force mutable to avoid changing constant value by reconfiguring
    // kData -> kAccessor -> kData.
489
    Handle<Map> new_map = MapUpdater::ReconfigureExistingProperty(
490 491
        isolate_, old_map, descriptor_number(), i::PropertyKind::kData,
        attributes, PropertyConstness::kMutable);
492 493 494 495 496 497 498
    if (!new_map->is_dictionary_map()) {
      // Make sure that the data property has a compatible representation.
      // TODO(leszeks): Do this as part of ReconfigureExistingProperty.
      new_map =
          Map::PrepareForDataProperty(isolate(), new_map, descriptor_number(),
                                      PropertyConstness::kMutable, value);
    }
499
    JSObject::MigrateToMap(isolate_, holder_obj, new_map);
500
    ReloadPropertyInformation<false>();
501 502
  }

503
  if (!IsElement(*holder) && !holder_obj->HasFastProperties(isolate_)) {
504
    if (holder_obj->map(isolate_).is_prototype_map() &&
505 506 507 508
        (((property_details_.attributes() & READ_ONLY) == 0 &&
          (attributes & READ_ONLY) != 0) ||
         (property_details_.attributes() & DONT_ENUM) !=
             (attributes & DONT_ENUM))) {
509 510 511
      // Invalidate prototype validity cell when a property is reconfigured
      // from writable to read-only as this may invalidate transitioning store
      // IC handlers.
512 513
      // Invalidate prototype validity cell when a property changes
      // enumerability to clear the prototype chain enum cache.
514
      JSObject::InvalidatePrototypeChains(holder->map(isolate_));
515
    }
516
    if (holder_obj->IsJSGlobalObject(isolate_)) {
517 518
      PropertyDetails details(PropertyKind::kData, attributes,
                              PropertyCellType::kMutable);
519
      Handle<GlobalDictionary> dictionary(
520 521
          JSGlobalObject::cast(*holder_obj)
              .global_dictionary(isolate_, kAcquireLoad),
522
          isolate());
523

524
      Handle<PropertyCell> cell = PropertyCell::PrepareForAndSetValue(
525
          isolate(), dictionary, dictionary_entry(), value, details);
526
      property_details_ = cell->property_details();
527
      DCHECK_EQ(cell->value(), *value);
528
    } else {
529 530
      PropertyDetails details(PropertyKind::kData, attributes,
                              PropertyConstness::kMutable);
531
      if (V8_ENABLE_SWISS_NAME_DICTIONARY_BOOL) {
532 533 534 535
        Handle<SwissNameDictionary> dictionary(
            holder_obj->property_dictionary_swiss(isolate_), isolate());
        dictionary->ValueAtPut(dictionary_entry(), *value);
        dictionary->DetailsAtPut(dictionary_entry(), details);
536 537 538 539 540 541 542 543 544 545 546 547 548 549
        DCHECK_EQ(details.AsSmi(),
                  dictionary->DetailsAt(dictionary_entry()).AsSmi());
        property_details_ = details;
      } else {
        Handle<NameDictionary> dictionary(
            holder_obj->property_dictionary(isolate_), isolate());
        PropertyDetails original_details =
            dictionary->DetailsAt(dictionary_entry());
        int enumeration_index = original_details.dictionary_index();
        DCHECK_GT(enumeration_index, 0);
        details = details.set_index(enumeration_index);
        dictionary->SetEntry(dictionary_entry(), *name(), *value, details);
        property_details_ = details;
      }
550
    }
551
    state_ = DATA;
552 553
  }

554
  WriteDataValue(value, true);
555 556 557

#if VERIFY_HEAP
  if (FLAG_verify_heap) {
558
    holder->HeapObjectVerify(isolate());
559 560
  }
#endif
561 562
}

563 564 565
// Can only be called when the receiver is a JSObject, or when the name is a
// private field, otherwise JSProxy has to be handled via a trap.
// Adding properties to primitive values is not observable.
566
void LookupIterator::PrepareTransitionToDataProperty(
567
    Handle<JSReceiver> receiver, Handle<Object> value,
568
    PropertyAttributes attributes, StoreOrigin store_origin) {
569
  DCHECK_IMPLIES(receiver->IsJSProxy(isolate_), name()->IsPrivate(isolate_));
570 571
  DCHECK_IMPLIES(!receiver.is_identical_to(GetStoreTarget<JSReceiver>()),
                 name()->IsPrivateName());
572
  if (state_ == TRANSITION) return;
573

574
  if (!IsElement() && name()->IsPrivate(isolate_)) {
575 576 577
    attributes = static_cast<PropertyAttributes>(attributes | DONT_ENUM);
  }

578
  DCHECK(state_ != LookupIterator::ACCESSOR ||
579
         (GetAccessors()->IsAccessorInfo(isolate_) &&
580
          AccessorInfo::cast(*GetAccessors()).is_special_data_property()));
581
  DCHECK_NE(INTEGER_INDEXED_EXOTIC, state_);
582
  DCHECK(state_ == NOT_FOUND || !HolderIsReceiverOrHiddenPrototype());
583

584
  Handle<Map> map(receiver->map(isolate_), isolate_);
585 586 587 588 589

  // Dictionary maps can always have additional data properties.
  if (map->is_dictionary_map()) {
    state_ = TRANSITION;
    if (map->IsJSGlobalObjectMap()) {
590
      DCHECK(!value->IsTheHole(isolate_));
591
      // Don't set enumeration index (it will be set during value store).
592 593
      property_details_ =
          PropertyDetails(PropertyKind::kData, attributes,
594
                          PropertyCell::InitialType(isolate_, *value));
595 596
      transition_ = isolate_->factory()->NewPropertyCell(
          name(), property_details_, value);
597
      has_property_ = true;
598
    } else {
599
      // Don't set enumeration index (it will be set during value store).
600 601 602
      property_details_ =
          PropertyDetails(PropertyKind::kData, attributes,
                          PropertyDetails::kConstIfDictConstnessTracking);
603 604
      transition_ = map;
    }
605
    return;
606 607
  }

608 609
  Handle<Map> transition =
      Map::TransitionToDataProperty(isolate_, map, name_, value, attributes,
610
                                    PropertyConstness::kConst, store_origin);
611
  state_ = TRANSITION;
612 613
  transition_ = transition;

614
  if (transition->is_dictionary_map()) {
615
    DCHECK(!transition->IsJSGlobalObjectMap());
616
    // Don't set enumeration index (it will be set during value store).
617 618 619
    property_details_ =
        PropertyDetails(PropertyKind::kData, attributes,
                        PropertyDetails::kConstIfDictConstnessTracking);
620
  } else {
621
    property_details_ = transition->GetLastDescriptorDetails(isolate_);
622 623
    has_property_ = true;
  }
624 625
}

626 627
void LookupIterator::ApplyTransitionToDataProperty(
    Handle<JSReceiver> receiver) {
628 629
  DCHECK_EQ(TRANSITION, state_);

630 631
  DCHECK_IMPLIES(!receiver.is_identical_to(GetStoreTarget<JSReceiver>()),
                 name()->IsPrivateName());
632
  holder_ = receiver;
633 634
  if (receiver->IsJSGlobalObject(isolate_)) {
    JSObject::InvalidatePrototypeChains(receiver->map(isolate_));
635 636 637 638

    // Install a property cell.
    Handle<JSGlobalObject> global = Handle<JSGlobalObject>::cast(receiver);
    DCHECK(!global->HasFastProperties());
639 640
    Handle<GlobalDictionary> dictionary(
        global->global_dictionary(isolate_, kAcquireLoad), isolate_);
641 642 643 644

    dictionary =
        GlobalDictionary::Add(isolate_, dictionary, name(), transition_cell(),
                              property_details_, &number_);
645
    global->set_global_dictionary(*dictionary, kReleaseStore);
646 647 648 649

    // Reload details containing proper enumeration index value.
    property_details_ = transition_cell()->property_details();
    has_property_ = true;
650 651 652
    state_ = DATA;
    return;
  }
653
  Handle<Map> transition = transition_map();
654 655
  bool simple_transition =
      transition->GetBackPointer(isolate_) == receiver->map(isolate_);
656

657 658 659 660 661 662 663 664 665
  if (configuration_ == DEFAULT && !transition->is_dictionary_map() &&
      !transition->IsPrototypeValidityCellValid()) {
    // Only LookupIterator instances with DEFAULT (full prototype chain)
    // configuration can produce valid transition handler maps.
    Handle<Object> validity_cell =
        Map::GetOrCreatePrototypeChainValidityCell(transition, isolate());
    transition->set_prototype_validity_cell(*validity_cell);
  }

666
  if (!receiver->IsJSProxy(isolate_)) {
667 668
    JSObject::MigrateToMap(isolate_, Handle<JSObject>::cast(receiver),
                           transition);
669
  }
670 671

  if (simple_transition) {
672
    number_ = transition->LastAdded();
673
    property_details_ = transition->GetLastDescriptorDetails(isolate_);
674
    state_ = DATA;
675 676 677 678
  } else if (receiver->map(isolate_).is_dictionary_map()) {
    if (receiver->map(isolate_).is_prototype_map() &&
        receiver->IsJSObject(isolate_)) {
      JSObject::InvalidatePrototypeChains(receiver->map(isolate_));
679
    }
680
    if (V8_ENABLE_SWISS_NAME_DICTIONARY_BOOL) {
681 682
      Handle<SwissNameDictionary> dictionary(
          receiver->property_dictionary_swiss(isolate_), isolate_);
683 684

      dictionary =
685 686 687
          SwissNameDictionary::Add(isolate(), dictionary, name(),
                                   isolate_->factory()->uninitialized_value(),
                                   property_details_, &number_);
688 689 690 691 692 693 694 695 696 697 698 699 700
      receiver->SetProperties(*dictionary);
    } else {
      Handle<NameDictionary> dictionary(receiver->property_dictionary(isolate_),
                                        isolate_);

      dictionary =
          NameDictionary::Add(isolate(), dictionary, name(),
                              isolate_->factory()->uninitialized_value(),
                              property_details_, &number_);
      receiver->SetProperties(*dictionary);
      // Reload details containing proper enumeration index value.
      property_details_ = dictionary->DetailsAt(number_);
    }
701 702 703
    has_property_ = true;
    state_ = DATA;

704
  } else {
705
    ReloadPropertyInformation<false>();
706
  }
707 708
}

709
void LookupIterator::Delete() {
710
  Handle<JSReceiver> holder = Handle<JSReceiver>::cast(holder_);
711
  if (IsElement(*holder)) {
712
    Handle<JSObject> object = Handle<JSObject>::cast(holder);
713
    ElementsAccessor* accessor = object->GetElementsAccessor(isolate_);
714
    accessor->Delete(object, number_);
715
  } else {
716 717
    DCHECK(!name()->IsPrivateName(isolate_));
    bool is_prototype_map = holder->map(isolate_).is_prototype_map();
718 719 720 721
    RCS_SCOPE(isolate_,
              is_prototype_map
                  ? RuntimeCallCounterId::kPrototypeObject_DeleteProperty
                  : RuntimeCallCounterId::kObject_DeleteProperty);
722 723 724

    PropertyNormalizationMode mode =
        is_prototype_map ? KEEP_INOBJECT_PROPERTIES : CLEAR_INOBJECT_PROPERTIES;
725

726
    if (holder->HasFastProperties(isolate_)) {
727 728
      JSObject::NormalizeProperties(isolate_, Handle<JSObject>::cast(holder),
                                    mode, 0, "DeletingProperty");
729
      ReloadPropertyInformation<false>();
730
    }
731
    JSReceiver::DeleteNormalizedProperty(holder, dictionary_entry());
732
    if (holder->IsJSObject(isolate_)) {
733 734
      JSObject::ReoptimizeIfPrototype(Handle<JSObject>::cast(holder));
    }
735
  }
736
  state_ = NOT_FOUND;
737 738
}

739
void LookupIterator::TransitionToAccessorProperty(
740
    Handle<Object> getter, Handle<Object> setter,
741
    PropertyAttributes attributes) {
742
  DCHECK(!getter->IsNull(isolate_) || !setter->IsNull(isolate_));
743 744 745
  // Can only be called when the receiver is a JSObject. JSProxy has to be
  // handled via a trap. Adding properties to primitive values is not
  // observable.
746
  Handle<JSObject> receiver = GetStoreTarget<JSObject>();
747
  if (!IsElement() && name()->IsPrivate(isolate_)) {
748 749
    attributes = static_cast<PropertyAttributes>(attributes | DONT_ENUM);
  }
750

751
  if (!IsElement(*receiver) && !receiver->map(isolate_).is_dictionary_map()) {
752
    Handle<Map> old_map(receiver->map(isolate_), isolate_);
753 754 755 756 757 758 759

    if (!holder_.is_identical_to(receiver)) {
      holder_ = receiver;
      state_ = NOT_FOUND;
    } else if (state_ == INTERCEPTOR) {
      LookupInRegularHolder<false>(*old_map, *holder_);
    }
760 761 762
    // The case of IsFound() && number_.is_not_found() can occur for
    // interceptors.
    DCHECK_IMPLIES(!IsFound(), number_.is_not_found());
763

764
    Handle<Map> new_map = Map::TransitionToAccessorProperty(
765
        isolate_, old_map, name_, number_, getter, setter, attributes);
766 767
    bool simple_transition =
        new_map->GetBackPointer(isolate_) == receiver->map(isolate_);
768
    JSObject::MigrateToMap(isolate_, receiver, new_map);
769

770
    if (simple_transition) {
771
      number_ = new_map->LastAdded();
772
      property_details_ = new_map->GetLastDescriptorDetails(isolate_);
773 774 775
      state_ = ACCESSOR;
      return;
    }
776

777
    ReloadPropertyInformation<false>();
778
    if (!new_map->is_dictionary_map()) return;
779
  }
780 781

  Handle<AccessorPair> pair;
782
  if (state() == ACCESSOR && GetAccessors()->IsAccessorPair(isolate_)) {
783 784
    pair = Handle<AccessorPair>::cast(GetAccessors());
    // If the component and attributes are identical, nothing has to be done.
785
    if (pair->Equals(*getter, *setter)) {
786
      if (property_details().attributes() == attributes) {
787
        if (!IsElement(*receiver)) JSObject::ReoptimizeIfPrototype(receiver);
788 789
        return;
      }
790
    } else {
791
      pair = AccessorPair::Copy(isolate(), pair);
792
      pair->SetComponents(*getter, *setter);
793 794
    }
  } else {
795
    pair = factory()->NewAccessorPair();
796
    pair->SetComponents(*getter, *setter);
797 798
  }

799
  TransitionToAccessorPair(pair, attributes);
800 801 802

#if VERIFY_HEAP
  if (FLAG_verify_heap) {
803
    receiver->JSObjectVerify(isolate());
804 805
  }
#endif
806 807 808 809
}

void LookupIterator::TransitionToAccessorPair(Handle<Object> pair,
                                              PropertyAttributes attributes) {
810
  Handle<JSObject> receiver = GetStoreTarget<JSObject>();
811 812
  holder_ = receiver;

813 814
  PropertyDetails details(PropertyKind::kAccessor, attributes,
                          PropertyCellType::kMutable);
815

816
  if (IsElement(*receiver)) {
817
    // TODO(verwaest): Move code into the element accessor.
818
    isolate_->CountUsage(v8::Isolate::kIndexAccessor);
819
    Handle<NumberDictionary> dictionary = JSObject::NormalizeElements(receiver);
820

821 822
    dictionary = NumberDictionary::Set(isolate_, dictionary, array_index(),
                                       pair, receiver, details);
823
    receiver->RequireSlowElements(*dictionary);
824

825
    if (receiver->HasSlowArgumentsElements(isolate_)) {
826 827 828
      SloppyArgumentsElements parameter_map =
          SloppyArgumentsElements::cast(receiver->elements(isolate_));
      uint32_t length = parameter_map.length();
829
      if (number_.is_found() && number_.as_uint32() < length) {
830 831
        parameter_map.set_mapped_entries(
            number_.as_int(), ReadOnlyRoots(isolate_).the_hole_value());
832
      }
833
      parameter_map.set_arguments(*dictionary);
834 835 836
    } else {
      receiver->set_elements(*dictionary);
    }
837 838

    ReloadPropertyInformation<true>();
839
  } else {
840
    PropertyNormalizationMode mode = CLEAR_INOBJECT_PROPERTIES;
841 842
    if (receiver->map(isolate_).is_prototype_map()) {
      JSObject::InvalidatePrototypeChains(receiver->map(isolate_));
843 844 845
      mode = KEEP_INOBJECT_PROPERTIES;
    }

846
    // Normalize object to make this operation simple.
847
    JSObject::NormalizeProperties(isolate_, receiver, mode, 0,
848 849
                                  "TransitionToAccessorPair");

850 851
    JSObject::SetNormalizedProperty(receiver, name_, pair, details);
    JSObject::ReoptimizeIfPrototype(receiver);
852

853 854
    ReloadPropertyInformation<false>();
  }
855 856
}

857 858 859 860 861 862
bool LookupIterator::HolderIsReceiver() const {
  DCHECK(has_property_ || state_ == INTERCEPTOR || state_ == JSPROXY);
  // Optimization that only works if configuration_ is not mutable.
  if (!check_prototype_chain()) return true;
  return *receiver_ == *holder_;
}
863

864
bool LookupIterator::HolderIsReceiverOrHiddenPrototype() const {
865
  DCHECK(has_property_ || state_ == INTERCEPTOR || state_ == JSPROXY);
866
  // Optimization that only works if configuration_ is not mutable.
867
  if (!check_prototype_chain()) return true;
868
  if (*receiver_ == *holder_) return true;
869 870 871
  if (!receiver_->IsJSGlobalProxy(isolate_)) return false;
  return Handle<JSGlobalProxy>::cast(receiver_)->map(isolate_).prototype(
             isolate_) == *holder_;
872 873
}

874 875
Handle<Object> LookupIterator::FetchValue(
    AllocationPolicy allocation_policy) const {
876
  Object result;
877
  if (IsElement(*holder_)) {
878 879 880 881 882 883 884 885 886 887 888
#if V8_ENABLE_WEBASSEMBLY
    if (V8_UNLIKELY(holder_->IsWasmObject(isolate_))) {
      if (holder_->IsWasmStruct()) {
        // WasmStructs don't have elements.
        return isolate_->factory()->undefined_value();
      }
      Handle<WasmArray> holder = GetHolder<WasmArray>();
      return WasmArray::GetElement(isolate_, holder, number_.as_uint32());
    }
#endif  // V8_ENABLE_WEBASSEMBLY
    DCHECK(holder_->IsJSObject(isolate_));
889
    Handle<JSObject> holder = GetHolder<JSObject>();
890
    ElementsAccessor* accessor = holder->GetElementsAccessor(isolate_);
891
    return accessor->Get(isolate_, holder, number_);
892
  } else if (holder_->IsJSGlobalObject(isolate_)) {
893
    Handle<JSGlobalObject> holder = GetHolder<JSGlobalObject>();
894 895
    result = holder->global_dictionary(isolate_, kAcquireLoad)
                 .ValueAt(isolate_, dictionary_entry());
896
  } else if (!holder_->HasFastProperties(isolate_)) {
897
    if (V8_ENABLE_SWISS_NAME_DICTIONARY_BOOL) {
898
      result = holder_->property_dictionary_swiss(isolate_).ValueAt(
899 900 901 902 903
          dictionary_entry());
    } else {
      result = holder_->property_dictionary(isolate_).ValueAt(
          isolate_, dictionary_entry());
    }
904
  } else if (property_details_.location() == PropertyLocation::kField) {
905
    DCHECK_EQ(PropertyKind::kData, property_details_.kind());
906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926
#if V8_ENABLE_WEBASSEMBLY
    if (V8_UNLIKELY(holder_->IsWasmObject(isolate_))) {
      if (allocation_policy == AllocationPolicy::kAllocationDisallowed) {
        // TODO(ishell): consider taking field type into account and relaxing
        // this a bit.
        return isolate_->factory()->undefined_value();
      }
      if (holder_->IsWasmArray(isolate_)) {
        // WasmArrays don't have other named properties besides "length".
        DCHECK_EQ(*name_, ReadOnlyRoots(isolate_).length_string());
        Handle<WasmArray> holder = GetHolder<WasmArray>();
        uint32_t length = holder->length();
        return isolate_->factory()->NewNumberFromUint(length);
      }
      Handle<WasmStruct> holder = GetHolder<WasmStruct>();
      return WasmStruct::GetField(isolate_, holder,
                                  property_details_.field_index());
    }
#endif  // V8_ENABLE_WEBASSEMBLY

    DCHECK(holder_->IsJSObject(isolate_));
927
    Handle<JSObject> holder = GetHolder<JSObject>();
928
    FieldIndex field_index =
929
        FieldIndex::ForDescriptor(holder->map(isolate_), descriptor_number());
930 931 932 933
    if (allocation_policy == AllocationPolicy::kAllocationDisallowed &&
        field_index.is_inobject() && field_index.is_double()) {
      return isolate_->factory()->undefined_value();
    }
934 935
    return JSObject::FastPropertyAt(
        isolate_, holder, property_details_.representation(), field_index);
936
  } else {
937 938 939
    result =
        holder_->map(isolate_).instance_descriptors(isolate_).GetStrongValue(
            isolate_, descriptor_number());
940 941 942 943
  }
  return handle(result, isolate_);
}

944
bool LookupIterator::IsConstFieldValueEqualTo(Object value) const {
945
  DCHECK(!IsElement(*holder_));
946
  DCHECK(holder_->HasFastProperties(isolate_));
947
  DCHECK_EQ(PropertyLocation::kField, property_details_.location());
948
  DCHECK_EQ(PropertyConstness::kConst, property_details_.constness());
949 950 951 952 953 954
  if (value.IsUninitialized(isolate())) {
    // Storing uninitialized value means that we are preparing for a computed
    // property value in an object literal. The initializing store will follow
    // and it will properly update constness based on the actual value.
    return true;
  }
955
  Handle<JSObject> holder = GetHolder<JSObject>();
956
  FieldIndex field_index =
957
      FieldIndex::ForDescriptor(holder->map(isolate_), descriptor_number());
958
  if (property_details_.representation().IsDouble()) {
959
    if (!value.IsNumber(isolate_)) return false;
960
    uint64_t bits;
961 962
    Object current_value = holder->RawFastPropertyAt(isolate_, field_index);
    DCHECK(current_value.IsHeapNumber(isolate_));
963
    bits = HeapNumber::cast(current_value).value_as_bits(kRelaxedLoad);
964
    // Use bit representation of double to check for hole double, since
965
    // manipulating the signaling NaN used for the hole in C++, e.g. with
966 967
    // base::bit_cast or value(), will change its value on ia32 (the x87
    // stack is used to return values and stores to the stack silently clear the
968 969 970 971 972
    // signalling bit).
    if (bits == kHoleNanInt64) {
      // Uninitialized double field.
      return true;
    }
973 974
    return Object::SameNumberValue(base::bit_cast<double>(bits),
                                   value.Number());
975
  } else {
976
    Object current_value = holder->RawFastPropertyAt(isolate_, field_index);
977
    if (current_value.IsUninitialized(isolate()) || current_value == value) {
978 979
      return true;
    }
980
    return current_value.IsNumber(isolate_) && value.IsNumber(isolate_) &&
981
           Object::SameNumberValue(current_value.Number(), value.Number());
982 983 984
  }
}

985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000
bool LookupIterator::IsConstDictValueEqualTo(Object value) const {
  DCHECK(!IsElement(*holder_));
  DCHECK(!holder_->HasFastProperties(isolate_));
  DCHECK(!holder_->IsJSGlobalObject());
  DCHECK(!holder_->IsJSProxy());
  DCHECK_EQ(PropertyConstness::kConst, property_details_.constness());

  DisallowHeapAllocation no_gc;

  if (value.IsUninitialized(isolate())) {
    // Storing uninitialized value means that we are preparing for a computed
    // property value in an object literal. The initializing store will follow
    // and it will properly update constness based on the actual value.
    return true;
  }
  Handle<JSReceiver> holder = GetHolder<JSReceiver>();
1001
  Object current_value;
1002
  if (V8_ENABLE_SWISS_NAME_DICTIONARY_BOOL) {
1003 1004 1005 1006 1007 1008
    SwissNameDictionary dict = holder->property_dictionary_swiss();
    current_value = dict.ValueAt(dictionary_entry());
  } else {
    NameDictionary dict = holder->property_dictionary();
    current_value = dict.ValueAt(dictionary_entry());
  }
1009 1010 1011 1012 1013 1014 1015 1016

  if (current_value.IsUninitialized(isolate()) || current_value == value) {
    return true;
  }
  return current_value.IsNumber(isolate_) && value.IsNumber(isolate_) &&
         Object::SameNumberValue(current_value.Number(), value.Number());
}

1017 1018 1019
int LookupIterator::GetFieldDescriptorIndex() const {
  DCHECK(has_property_);
  DCHECK(holder_->HasFastProperties());
1020
  DCHECK_EQ(PropertyLocation::kField, property_details_.location());
1021
  DCHECK_EQ(PropertyKind::kData, property_details_.kind());
1022 1023
  // TODO(jkummerow): Propagate InternalIndex further.
  return descriptor_number().as_int();
1024
}
1025

1026 1027
int LookupIterator::GetAccessorIndex() const {
  DCHECK(has_property_);
1028
  DCHECK(holder_->HasFastProperties(isolate_));
1029
  DCHECK_EQ(PropertyLocation::kDescriptor, property_details_.location());
1030
  DCHECK_EQ(PropertyKind::kAccessor, property_details_.kind());
1031
  return descriptor_number().as_int();
1032 1033
}

1034
FieldIndex LookupIterator::GetFieldIndex() const {
1035
  DCHECK(has_property_);
1036
  DCHECK(holder_->HasFastProperties(isolate_));
1037
  DCHECK_EQ(PropertyLocation::kField, property_details_.location());
1038
  DCHECK(!IsElement(*holder_));
1039
  return FieldIndex::ForDescriptor(holder_->map(isolate_), descriptor_number());
1040 1041 1042
}

Handle<PropertyCell> LookupIterator::GetPropertyCell() const {
1043
  DCHECK(!IsElement(*holder_));
1044
  Handle<JSGlobalObject> holder = GetHolder<JSGlobalObject>();
1045 1046 1047
  return handle(holder->global_dictionary(isolate_, kAcquireLoad)
                    .CellAt(isolate_, dictionary_entry()),
                isolate_);
1048 1049
}

1050
Handle<Object> LookupIterator::GetAccessors() const {
1051
  DCHECK_EQ(ACCESSOR, state_);
1052 1053 1054
  return FetchValue();
}

1055 1056
Handle<Object> LookupIterator::GetDataValue(
    AllocationPolicy allocation_policy) const {
1057
  DCHECK_EQ(DATA, state_);
1058
  Handle<Object> value = FetchValue(allocation_policy);
1059 1060 1061
  return value;
}

1062 1063
Handle<Object> LookupIterator::GetDataValue(SeqCstAccessTag tag) const {
  DCHECK_EQ(DATA, state_);
1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078
  // Currently only shared structs and arrays support sequentially consistent
  // access.
  if (holder_->IsJSSharedStruct(isolate_)) {
    DCHECK_EQ(PropertyLocation::kField, property_details_.location());
    DCHECK_EQ(PropertyKind::kData, property_details_.kind());
    Handle<JSSharedStruct> holder = GetHolder<JSSharedStruct>();
    FieldIndex field_index =
        FieldIndex::ForDescriptor(holder->map(isolate_), descriptor_number());
    return JSObject::FastPropertyAt(
        isolate_, holder, property_details_.representation(), field_index, tag);
  }
  DCHECK(holder_->IsJSSharedArray(isolate_));
  Handle<JSSharedArray> holder = GetHolder<JSSharedArray>();
  ElementsAccessor* accessor = holder->GetElementsAccessor(isolate_);
  return accessor->GetAtomic(isolate_, holder, number_, kSeqCstAccess);
1079 1080
}

1081 1082
void LookupIterator::WriteDataValue(Handle<Object> value,
                                    bool initializing_store) {
1083
  DCHECK_EQ(DATA, state_);
1084 1085 1086 1087 1088
#if V8_ENABLE_WEBASSEMBLY
  // WriteDataValueToWasmObject() must be used instead for writing to
  // WasmObjects.
  DCHECK(!holder_->IsWasmObject(isolate_));
#endif  // V8_ENABLE_WEBASSEMBLY
1089
  DCHECK_IMPLIES(holder_->IsJSSharedStruct(), value->IsShared());
1090

1091
  Handle<JSReceiver> holder = GetHolder<JSReceiver>();
1092
  if (IsElement(*holder)) {
1093
    Handle<JSObject> object = Handle<JSObject>::cast(holder);
1094
    ElementsAccessor* accessor = object->GetElementsAccessor(isolate_);
1095
    accessor->Set(object, number_, *value);
1096
  } else if (holder->HasFastProperties(isolate_)) {
1097
    DCHECK(holder->IsJSObject(isolate_));
1098
    if (property_details_.location() == PropertyLocation::kField) {
1099 1100 1101 1102 1103
      // Check that in case of VariableMode::kConst field the existing value is
      // equal to |value|.
      DCHECK_IMPLIES(!initializing_store && property_details_.constness() ==
                                                PropertyConstness::kConst,
                     IsConstFieldValueEqualTo(*value));
1104 1105
      JSObject::cast(*holder).WriteToField(descriptor_number(),
                                           property_details_, *value);
1106
    } else {
1107
      DCHECK_EQ(PropertyLocation::kDescriptor, property_details_.location());
1108
      DCHECK_EQ(PropertyConstness::kConst, property_details_.constness());
1109
    }
1110
  } else if (holder->IsJSGlobalObject(isolate_)) {
1111 1112 1113
    // PropertyCell::PrepareForAndSetValue already wrote the value into the
    // cell.
#ifdef DEBUG
1114
    GlobalDictionary dictionary =
1115
        JSGlobalObject::cast(*holder).global_dictionary(isolate_, kAcquireLoad);
1116
    PropertyCell cell = dictionary.CellAt(isolate_, dictionary_entry());
Georg Neis's avatar
Georg Neis committed
1117
    DCHECK(cell.value() == *value ||
1118 1119
           (cell.value().IsString() && value->IsString() &&
            String::cast(cell.value()).Equals(String::cast(*value))));
1120
#endif  // DEBUG
1121
  } else {
1122
    DCHECK_IMPLIES(holder->IsJSProxy(isolate_), name()->IsPrivate(isolate_));
1123 1124 1125 1126 1127 1128
    // Check similar to fast mode case above.
    DCHECK_IMPLIES(
        V8_DICT_PROPERTY_CONST_TRACKING_BOOL && !initializing_store &&
            property_details_.constness() == PropertyConstness::kConst,
        holder->IsJSProxy(isolate_) || IsConstDictValueEqualTo(*value));

1129
    if (V8_ENABLE_SWISS_NAME_DICTIONARY_BOOL) {
1130 1131
      SwissNameDictionary dictionary =
          holder->property_dictionary_swiss(isolate_);
1132 1133 1134 1135 1136
      dictionary.ValueAtPut(dictionary_entry(), *value);
    } else {
      NameDictionary dictionary = holder->property_dictionary(isolate_);
      dictionary.ValueAtPut(dictionary_entry(), *value);
    }
1137 1138 1139
  }
}

1140 1141
void LookupIterator::WriteDataValue(Handle<Object> value, SeqCstAccessTag tag) {
  DCHECK_EQ(DATA, state_);
1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157
  // Currently only shared structs and arrays support sequentially consistent
  // access.
  if (holder_->IsJSSharedStruct(isolate_)) {
    DCHECK_EQ(PropertyLocation::kField, property_details_.location());
    DCHECK_EQ(PropertyKind::kData, property_details_.kind());
    Handle<JSSharedStruct> holder = GetHolder<JSSharedStruct>();
    DisallowGarbageCollection no_gc;
    FieldIndex field_index =
        FieldIndex::ForDescriptor(holder->map(isolate_), descriptor_number());
    holder->FastPropertyAtPut(field_index, *value, tag);
    return;
  }
  DCHECK(holder_->IsJSSharedArray(isolate_));
  Handle<JSSharedArray> holder = GetHolder<JSSharedArray>();
  ElementsAccessor* accessor = holder->GetElementsAccessor(isolate_);
  accessor->SetAtomic(holder, number_, *value, kSeqCstAccess);
1158 1159
}

1160 1161 1162
Handle<Object> LookupIterator::SwapDataValue(Handle<Object> value,
                                             SeqCstAccessTag tag) {
  DCHECK_EQ(DATA, state_);
1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179
  // Currently only shared structs and arrays support sequentially consistent
  // access.
  if (holder_->IsJSSharedStruct(isolate_)) {
    DCHECK_EQ(PropertyLocation::kField, property_details_.location());
    DCHECK_EQ(PropertyKind::kData, property_details_.kind());
    // Currently only shared structs support sequentially consistent access.
    Handle<JSSharedStruct> holder = GetHolder<JSSharedStruct>();
    DisallowGarbageCollection no_gc;
    FieldIndex field_index =
        FieldIndex::ForDescriptor(holder->map(isolate_), descriptor_number());
    return handle(holder->RawFastPropertyAtSwap(field_index, *value, tag),
                  isolate_);
  }
  DCHECK(holder_->IsJSSharedArray(isolate_));
  Handle<JSSharedArray> holder = GetHolder<JSSharedArray>();
  ElementsAccessor* accessor = holder->GetElementsAccessor(isolate_);
  return accessor->SwapAtomic(isolate_, holder, number_, *value, kSeqCstAccess);
1180 1181
}

1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209
#if V8_ENABLE_WEBASSEMBLY

wasm::ValueType LookupIterator::wasm_value_type() const {
  DCHECK(has_property_);
  DCHECK(holder_->IsWasmObject(isolate_));
  if (holder_->IsWasmStruct(isolate_)) {
    wasm::StructType* wasm_struct_type = WasmStruct::cast(*holder_).type();
    return wasm_struct_type->field(property_details_.field_index());

  } else {
    DCHECK(holder_->IsWasmArray(isolate_));
    wasm::ArrayType* wasm_array_type = WasmArray::cast(*holder_).type();
    return wasm_array_type->element_type();
  }
}

void LookupIterator::WriteDataValueToWasmObject(Handle<Object> value) {
  DCHECK_EQ(DATA, state_);
  DCHECK(holder_->IsWasmObject(isolate_));
  Handle<JSReceiver> holder = GetHolder<JSReceiver>();

  if (IsElement(*holder)) {
    // TODO(ishell): consider supporting indexed access to WasmStruct fields.
    // TODO(v8:11804): implement stores to WasmArrays.
    UNIMPLEMENTED();
  } else {
    // WasmArrays don't have writable properties.
    DCHECK(holder->IsWasmStruct());
1210 1211
    Handle<WasmStruct> wasm_holder = GetHolder<WasmStruct>();
    WasmStruct::SetField(isolate_, wasm_holder, property_details_.field_index(),
1212 1213 1214 1215 1216 1217
                         value);
  }
}

#endif  // V8_ENABLE_WEBASSEMBLY

1218
template <bool is_element>
1219
bool LookupIterator::SkipInterceptor(JSObject holder) {
1220
  InterceptorInfo info = GetInterceptor<is_element>(holder);
1221 1222
  if (!is_element && name_->IsSymbol(isolate_) &&
      !info.can_intercept_symbols()) {
1223 1224
    return true;
  }
1225
  if (info.non_masking()) {
1226 1227 1228
    switch (interceptor_state_) {
      case InterceptorState::kUninitialized:
        interceptor_state_ = InterceptorState::kSkipNonMasking;
1229
        V8_FALLTHROUGH;
1230 1231 1232 1233 1234 1235 1236 1237
      case InterceptorState::kSkipNonMasking:
        return true;
      case InterceptorState::kProcessNonMasking:
        return false;
    }
  }
  return interceptor_state_ == InterceptorState::kProcessNonMasking;
}
1238

1239
JSReceiver LookupIterator::NextHolder(Map map) {
1240
  DisallowGarbageCollection no_gc;
1241
  if (map.prototype(isolate_) == ReadOnlyRoots(isolate_).null_value()) {
1242 1243
    return JSReceiver();
  }
1244
  if (!check_prototype_chain() && !map.IsJSGlobalProxyMap()) {
1245 1246
    return JSReceiver();
  }
1247
  return JSReceiver::cast(map.prototype(isolate_));
1248 1249
}

1250
LookupIterator::State LookupIterator::NotFound(JSReceiver const holder) const {
1251 1252 1253
  if (!holder.IsJSTypedArray(isolate_)) return NOT_FOUND;
  if (IsElement()) return INTEGER_INDEXED_EXOTIC;
  if (!name_->IsString(isolate_)) return NOT_FOUND;
1254 1255
  return IsSpecialIndex(String::cast(*name_)) ? INTEGER_INDEXED_EXOTIC
                                              : NOT_FOUND;
1256
}
1257

1258 1259 1260
namespace {

template <bool is_element>
1261 1262
bool HasInterceptor(Map map, size_t index) {
  if (is_element) {
1263
    if (index > JSObject::kMaxElementIndex) {
1264 1265
      // There is currently no way to install interceptors on an object with
      // typed array elements.
1266
      DCHECK(!map.has_typed_array_or_rab_gsab_typed_array_elements());
1267 1268 1269 1270 1271 1272
      return map.has_named_interceptor();
    }
    return map.has_indexed_interceptor();
  } else {
    return map.has_named_interceptor();
  }
1273 1274 1275 1276 1277 1278
}

}  // namespace

template <bool is_element>
LookupIterator::State LookupIterator::LookupInSpecialHolder(
1279
    Map const map, JSReceiver const holder) {
1280
  static_assert(INTERCEPTOR == BEFORE_PROPERTY);
1281 1282
  switch (state_) {
    case NOT_FOUND:
1283
      if (map.IsJSProxyMap()) {
1284
        if (is_element || !name_->IsPrivate(isolate_)) return JSPROXY;
1285
      }
1286 1287 1288 1289 1290
#if V8_ENABLE_WEBASSEMBLY
      if (map.IsWasmObjectMap()) {
        return LookupInRegularHolder<is_element>(map, holder);
      }
#endif  // V8_ENABLE_WEBASSEMBLY
1291
      if (map.is_access_check_needed()) {
1292 1293 1294
        if (is_element || !name_->IsPrivate(isolate_) ||
            name_->IsPrivateName(isolate_))
          return ACCESS_CHECK;
1295
      }
1296
      V8_FALLTHROUGH;
1297
    case ACCESS_CHECK:
1298
      if (check_interceptor() && HasInterceptor<is_element>(map, index_) &&
1299
          !SkipInterceptor<is_element>(JSObject::cast(holder))) {
1300
        if (is_element || !name_->IsPrivate(isolate_)) return INTERCEPTOR;
1301
      }
1302
      V8_FALLTHROUGH;
1303
    case INTERCEPTOR:
1304
      if (map.IsJSGlobalObjectMap() && !is_js_array_element(is_element)) {
1305 1306
        GlobalDictionary dict = JSGlobalObject::cast(holder).global_dictionary(
            isolate_, kAcquireLoad);
1307 1308
        number_ = dict.FindEntry(isolate(), name_);
        if (number_.is_not_found()) return NOT_FOUND;
1309
        PropertyCell cell = dict.CellAt(isolate_, number_);
1310 1311 1312
        if (cell.value(isolate_).IsTheHole(isolate_)) {
          return NOT_FOUND;
        }
1313
        property_details_ = cell.property_details();
1314 1315
        has_property_ = true;
        switch (property_details_.kind()) {
1316
          case v8::internal::PropertyKind::kData:
1317
            return DATA;
1318
          case v8::internal::PropertyKind::kAccessor:
1319 1320
            return ACCESSOR;
        }
1321
      }
1322
      return LookupInRegularHolder<is_element>(map, holder);
1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333
    case ACCESSOR:
    case DATA:
      return NOT_FOUND;
    case INTEGER_INDEXED_EXOTIC:
    case JSPROXY:
    case TRANSITION:
      UNREACHABLE();
  }
  UNREACHABLE();
}

1334 1335
template <bool is_element>
LookupIterator::State LookupIterator::LookupInRegularHolder(
1336
    Map const map, JSReceiver const holder) {
1337
  DisallowGarbageCollection no_gc;
1338 1339
  if (interceptor_state_ == InterceptorState::kProcessNonMasking) {
    return NOT_FOUND;
verwaest's avatar
verwaest committed
1340
  }
1341

1342
  if (is_element && IsElement(holder)) {
1343
#if V8_ENABLE_WEBASSEMBLY
1344
    if (V8_UNLIKELY(holder.IsWasmObject(isolate_))) {
1345
      // TODO(ishell): consider supporting indexed access to WasmStruct fields.
1346
      if (holder.IsWasmArray(isolate_)) {
1347 1348 1349
        WasmArray wasm_array = WasmArray::cast(holder);
        number_ = index_ < wasm_array.length() ? InternalIndex(index_)
                                               : InternalIndex::NotFound();
1350
        wasm::ArrayType* wasm_array_type = wasm_array.type();
1351 1352 1353 1354
        property_details_ =
            PropertyDetails(PropertyKind::kData,
                            wasm_array_type->mutability() ? SEALED : FROZEN,
                            PropertyCellType::kNoCell);
1355 1356

      } else {
1357
        DCHECK(holder.IsWasmStruct(isolate_));
1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377
        DCHECK(number_.is_not_found());
      }
    } else  // NOLINT(readability/braces)
#endif      // V8_ENABLE_WEBASSEMBLY
    {
      JSObject js_object = JSObject::cast(holder);
      ElementsAccessor* accessor = js_object.GetElementsAccessor(isolate_);
      FixedArrayBase backing_store = js_object.elements(isolate_);
      number_ = accessor->GetEntryForIndex(isolate_, js_object, backing_store,
                                           index_);
      if (number_.is_not_found()) {
        return holder.IsJSTypedArray(isolate_) ? INTEGER_INDEXED_EXOTIC
                                               : NOT_FOUND;
      }
      property_details_ = accessor->GetDetails(js_object, number_);
      if (map.has_frozen_elements()) {
        property_details_ = property_details_.CopyAddAttributes(FROZEN);
      } else if (map.has_sealed_elements()) {
        property_details_ = property_details_.CopyAddAttributes(SEALED);
      }
1378
    }
1379
  } else if (!map.is_dictionary_map()) {
1380
    DescriptorArray descriptors = map.instance_descriptors(isolate_);
1381 1382 1383
    number_ = descriptors.SearchWithCache(isolate_, *name_, map);
    if (number_.is_not_found()) return NotFound(holder);
    property_details_ = descriptors.GetDetails(number_);
1384
  } else {
1385
    DCHECK_IMPLIES(holder.IsJSProxy(isolate_), name()->IsPrivate(isolate_));
1386
    if (V8_ENABLE_SWISS_NAME_DICTIONARY_BOOL) {
1387
      SwissNameDictionary dict = holder.property_dictionary_swiss(isolate_);
1388 1389 1390 1391 1392 1393 1394 1395 1396
      number_ = dict.FindEntry(isolate(), *name_);
      if (number_.is_not_found()) return NotFound(holder);
      property_details_ = dict.DetailsAt(number_);
    } else {
      NameDictionary dict = holder.property_dictionary(isolate_);
      number_ = dict.FindEntry(isolate(), name_);
      if (number_.is_not_found()) return NotFound(holder);
      property_details_ = dict.DetailsAt(number_);
    }
1397 1398 1399
  }
  has_property_ = true;
  switch (property_details_.kind()) {
1400
    case v8::internal::PropertyKind::kData:
1401
      return DATA;
1402
    case v8::internal::PropertyKind::kAccessor:
1403 1404 1405
      return ACCESSOR;
  }

1406 1407 1408
  UNREACHABLE();
}

1409 1410 1411
Handle<InterceptorInfo> LookupIterator::GetInterceptorForFailedAccessCheck()
    const {
  DCHECK_EQ(ACCESS_CHECK, state_);
1412 1413 1414 1415 1416
  // Skip the interceptors for private
  if (IsPrivateName()) {
    return Handle<InterceptorInfo>();
  }

1417
  DisallowGarbageCollection no_gc;
1418
  AccessCheckInfo access_check_info =
1419
      AccessCheckInfo::Get(isolate_, Handle<JSObject>::cast(holder_));
1420
  if (!access_check_info.is_null()) {
1421 1422
    // There is currently no way to create objects with typed array elements
    // and access checks.
1423
    DCHECK(!holder_->map().has_typed_array_or_rab_gsab_typed_array_elements());
1424 1425 1426
    Object interceptor = is_js_array_element(IsElement())
                             ? access_check_info.indexed_interceptor()
                             : access_check_info.named_interceptor();
1427
    if (interceptor != Object()) {
1428 1429 1430 1431 1432 1433
      return handle(InterceptorInfo::cast(interceptor), isolate_);
    }
  }
  return Handle<InterceptorInfo>();
}

1434 1435 1436 1437 1438
bool LookupIterator::TryLookupCachedProperty(Handle<AccessorPair> accessor) {
  DCHECK_EQ(state(), LookupIterator::ACCESSOR);
  return LookupCachedProperty(accessor);
}

1439
bool LookupIterator::TryLookupCachedProperty() {
1440 1441 1442 1443 1444
  if (state() != LookupIterator::ACCESSOR) return false;

  Handle<Object> accessor_pair = GetAccessors();
  return accessor_pair->IsAccessorPair(isolate_) &&
         LookupCachedProperty(Handle<AccessorPair>::cast(accessor_pair));
1445 1446
}

1447
bool LookupIterator::LookupCachedProperty(Handle<AccessorPair> accessor_pair) {
1448 1449 1450 1451 1452 1453
  if (!HolderIsReceiverOrHiddenPrototype()) return false;
  if (!lookup_start_object_.is_identical_to(receiver_) &&
      !lookup_start_object_.is_identical_to(holder_)) {
    return false;
  }

1454
  DCHECK_EQ(state(), LookupIterator::ACCESSOR);
1455
  DCHECK(GetAccessors()->IsAccessorPair(isolate_));
1456

1457
  Object getter = accessor_pair->getter(isolate_);
1458
  base::Optional<Name> maybe_name =
1459
      FunctionTemplateInfo::TryGetCachedPropertyName(isolate(), getter);
1460
  if (!maybe_name.has_value()) return false;
1461

1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472
  if (getter.IsJSFunction()) {
    // If the getter was a JSFunction there's no guarantee that the holder
    // actually has a property with the cached name. In that case look it up to
    // make sure.
    LookupIterator it(isolate_, holder_, handle(maybe_name.value(), isolate_));
    if (it.state() != DATA) return false;
    name_ = it.name();
  } else {
    name_ = handle(maybe_name.value(), isolate_);
  }

1473 1474 1475 1476 1477 1478
  // We have found a cached property! Modify the iterator accordingly.
  Restart();
  CHECK_EQ(state(), LookupIterator::DATA);
  return true;
}

1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522
// static
base::Optional<Object> ConcurrentLookupIterator::TryGetOwnCowElement(
    Isolate* isolate, FixedArray array_elements, ElementsKind elements_kind,
    int array_length, size_t index) {
  DisallowGarbageCollection no_gc;

  CHECK_EQ(array_elements.map(), ReadOnlyRoots(isolate).fixed_cow_array_map());
  DCHECK(IsFastElementsKind(elements_kind) &&
         IsSmiOrObjectElementsKind(elements_kind));
  USE(elements_kind);
  DCHECK_GE(array_length, 0);

  //  ________________________________________
  // ( Check against both JSArray::length and )
  // ( FixedArray::length.                    )
  //  ----------------------------------------
  //         o   ^__^
  //          o  (oo)\_______
  //             (__)\       )\/\
  //                 ||----w |
  //                 ||     ||
  // The former is the source of truth, but due to concurrent reads it may not
  // match the given `array_elements`.
  if (index >= static_cast<size_t>(array_length)) return {};
  if (index >= static_cast<size_t>(array_elements.length())) return {};

  Object result = array_elements.get(isolate, static_cast<int>(index));

  //  ______________________________________
  // ( Filter out holes irrespective of the )
  // ( elements kind.                       )
  //  --------------------------------------
  //         o   ^__^
  //          o  (..)\_______
  //             (__)\       )\/\
  //                 ||----w |
  //                 ||     ||
  // The elements kind may not be consistent with the given elements backing
  // store.
  if (result == ReadOnlyRoots(isolate).the_hole_value()) return {};

  return result;
}

1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545
// static
ConcurrentLookupIterator::Result
ConcurrentLookupIterator::TryGetOwnConstantElement(
    Object* result_out, Isolate* isolate, LocalIsolate* local_isolate,
    JSObject holder, FixedArrayBase elements, ElementsKind elements_kind,
    size_t index) {
  DisallowGarbageCollection no_gc;

  DCHECK_LE(index, JSObject::kMaxElementIndex);

  // Own 'constant' elements (PropertyAttributes READ_ONLY|DONT_DELETE) occur in
  // three main cases:
  //
  // 1. Frozen elements: guaranteed constant.
  // 2. Dictionary elements: may be constant.
  // 3. String wrapper elements: guaranteed constant.

  // Interesting field reads below:
  //
  // - elements.length (immutable on FixedArrays).
  // - elements[i] (immutable if constant; be careful around dictionaries).
  // - holder.AsJSPrimitiveWrapper.value.AsString.length (immutable).
  // - holder.AsJSPrimitiveWrapper.value.AsString[i] (immutable).
1546
  // - single_character_string_table()->get().
1547 1548

  if (IsFrozenElementsKind(elements_kind)) {
1549
    if (!elements.IsFixedArray()) return kGaveUp;
1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561
    FixedArray elements_fixed_array = FixedArray::cast(elements);
    if (index >= static_cast<uint32_t>(elements_fixed_array.length())) {
      return kGaveUp;
    }
    Object result = elements_fixed_array.get(isolate, static_cast<int>(index));
    if (IsHoleyElementsKindForRead(elements_kind) &&
        result == ReadOnlyRoots(isolate).the_hole_value()) {
      return kNotPresent;
    }
    *result_out = result;
    return kPresent;
  } else if (IsDictionaryElementsKind(elements_kind)) {
1562
    if (!elements.IsNumberDictionary()) return kGaveUp;
1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574
    // TODO(jgruber, v8:7790): Add support. Dictionary elements require racy
    // NumberDictionary lookups. This should be okay in general (slot iteration
    // depends only on the dict's capacity), but 1. we'd need to update
    // NumberDictionary methods to do atomic reads, and 2. the dictionary
    // elements case isn't very important for callers of this function.
    return kGaveUp;
  } else if (IsStringWrapperElementsKind(elements_kind)) {
    // In this case we don't care about the actual `elements`. All in-bounds
    // reads are redirected to the wrapped String.

    JSPrimitiveWrapper js_value = JSPrimitiveWrapper::cast(holder);
    String wrapped_string = String::cast(js_value.value());
1575 1576 1577
    return ConcurrentLookupIterator::TryGetOwnChar(
        static_cast<String*>(result_out), isolate, local_isolate,
        wrapped_string, index);
1578 1579 1580 1581 1582 1583 1584 1585 1586 1587
  } else {
    DCHECK(!IsFrozenElementsKind(elements_kind));
    DCHECK(!IsDictionaryElementsKind(elements_kind));
    DCHECK(!IsStringWrapperElementsKind(elements_kind));
    return kGaveUp;
  }

  UNREACHABLE();
}

1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608
// static
ConcurrentLookupIterator::Result ConcurrentLookupIterator::TryGetOwnChar(
    String* result_out, Isolate* isolate, LocalIsolate* local_isolate,
    String string, size_t index) {
  DisallowGarbageCollection no_gc;
  // The access guard below protects string accesses related to internalized
  // strings.
  // TODO(jgruber): Support other string kinds.
  Map string_map = string.map(isolate, kAcquireLoad);
  InstanceType type = string_map.instance_type();
  if (!(InstanceTypeChecker::IsInternalizedString(type)) ||
      InstanceTypeChecker::IsThinString(type)) {
    return kGaveUp;
  }

  const uint32_t length = static_cast<uint32_t>(string.length());
  if (index >= length) return kGaveUp;

  uint16_t charcode;
  {
    SharedStringAccessGuardIfNeeded access_guard(local_isolate);
1609 1610
    charcode = string.Get(static_cast<int>(index), PtrComprCageBase(isolate),
                          access_guard);
1611 1612 1613 1614
  }

  if (charcode > unibrow::Latin1::kMaxChar) return kGaveUp;

1615
  Object value = isolate->factory()->single_character_string_table()->get(
1616
      charcode, kRelaxedLoad);
1617 1618

  DCHECK_NE(value, ReadOnlyRoots(isolate).undefined_value());
1619 1620 1621 1622 1623

  *result_out = String::cast(value);
  return kPresent;
}

1624 1625 1626 1627 1628 1629 1630
// static
base::Optional<PropertyCell> ConcurrentLookupIterator::TryGetPropertyCell(
    Isolate* isolate, LocalIsolate* local_isolate,
    Handle<JSGlobalObject> holder, Handle<Name> name) {
  DisallowGarbageCollection no_gc;

  Map holder_map = holder->map();
1631 1632
  if (holder_map.is_access_check_needed()) return {};
  if (holder_map.has_named_interceptor()) return {};
1633 1634 1635 1636 1637 1638 1639

  GlobalDictionary dict = holder->global_dictionary(kAcquireLoad);
  base::Optional<PropertyCell> cell =
      dict.TryFindPropertyCellForConcurrentLookupIterator(isolate, name,
                                                          kRelaxedLoad);
  if (!cell.has_value()) return {};

1640
  if (cell->property_details(kAcquireLoad).kind() == PropertyKind::kAccessor) {
1641 1642 1643 1644 1645 1646
    Object maybe_accessor_pair = cell->value(kAcquireLoad);
    if (!maybe_accessor_pair.IsAccessorPair()) return {};

    base::Optional<Name> maybe_cached_property_name =
        FunctionTemplateInfo::TryGetCachedPropertyName(
            isolate, AccessorPair::cast(maybe_accessor_pair)
1647
                         .getter(isolate, kAcquireLoad));
1648 1649 1650 1651 1652 1653
    if (!maybe_cached_property_name.has_value()) return {};

    cell = dict.TryFindPropertyCellForConcurrentLookupIterator(
        isolate, handle(*maybe_cached_property_name, local_isolate),
        kRelaxedLoad);
    if (!cell.has_value()) return {};
1654 1655
    if (cell->property_details(kAcquireLoad).kind() != PropertyKind::kData)
      return {};
1656 1657 1658
  }

  DCHECK(cell.has_value());
1659
  DCHECK_EQ(cell->property_details(kAcquireLoad).kind(), PropertyKind::kData);
1660 1661 1662
  return cell;
}

1663 1664
}  // namespace internal
}  // namespace v8